rel-1.3.36

git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/tags/rel-1.3.36@10585 626c5289-ae23-0410-ae9c-e8d60b6d4f22
diff --git a/trunk/.project b/trunk/.project
new file mode 100644
index 0000000..86af752
--- /dev/null
+++ b/trunk/.project
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>SWIG</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+	</buildSpec>
+	<natures>
+	</natures>
+</projectDescription>
diff --git a/trunk/ANNOUNCE b/trunk/ANNOUNCE
new file mode 100644
index 0000000..7c0e95e
--- /dev/null
+++ b/trunk/ANNOUNCE
@@ -0,0 +1,47 @@
+*** ANNOUNCE: SWIG 1.3.36 (24 June 2008) ***
+
+http://www.swig.org
+
+
+We're pleased to announce SWIG-1.3.36, the latest installment in the
+SWIG development effort.  SWIG-1.3.36 includes a number of bug fixes
+and large number of enhancements throughout.
+
+What is SWIG?
+-------------
+
+SWIG is a software development tool that reads C/C++ header files and
+generates the wrapper code needed to make C and C++ code accessible
+from other languages including Perl, Python, Tcl, Ruby, PHP, Java,
+Scheme (Guile, MzScheme, CHICKEN), Ocaml, Lua, Pike, C#, Modula-3, Octave, R,
+Common Lisp (CLISP, Allegro CL, CFFI, UFFI). SWIG can also export its parse
+tree in the form of XML and Lisp s-expressions.  Major applications of
+SWIG include generation of scripting language extension modules, rapid
+prototyping, testing, and user interface development for large C/C++
+systems.
+
+Availability:
+-------------
+The release is available for download on Sourceforge at
+
+     http://prdownloads.sourceforge.net/swig/swig-1.3.36.tar.gz
+
+A Windows version is also available at
+
+     http://prdownloads.sourceforge.net/swig/swigwin-1.3.36.zip
+
+Release numbers
+---------------
+With SWIG-1.3, we are adopting an odd/even version numbering scheme for
+SWIG.  Odd version numbers (1.3, 1.5, 1.7, etc...) are considered to
+be development releases.  Even numbers (1.4,1.6,1.8) are stable
+releases.  The current 1.3 effort is working to produce a stable 2.0
+release.  A stable 2.0 release will not be made until it can
+accompanied by fully updated documentation.  In the meantime, we will
+continue to make periodic 1.3.x releases.
+
+Please report problems with this release to the swig-dev mailing list,
+details at http://www.swig.org/mail.html.
+
+--- The SWIG Developers
+
diff --git a/trunk/CHANGES b/trunk/CHANGES
new file mode 100644
index 0000000..fc3018a
--- /dev/null
+++ b/trunk/CHANGES
@@ -0,0 +1,19658 @@
+SWIG (Simplified Wrapper and Interface Generator)
+
+See CHANGES.current for current version.
+
+Version 1.3.35 (7 April 2008)
+=============================
+
+04/07/2008: wsfulton
+            [Lua] Add missing pointer reference typemaps
+
+04/06/2008: wsfulton
+            Fix stack overflow when using typemap warning suppression, eg 
+              %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG)
+
+04/05/2008: wsfulton
+            [Python] Fix shared_ptr typemaps so that %pythonnondynamic can be used. Also corrects
+            display of the proxy class type. Reported by Robert Lupton.
+
+04/04/2008: olly
+	    [Python] Add %newobject reference to python memory management subsection of manual
+	    (patch from mdbeachy in SF#1894610).
+
+03/27/2008: wsfulton
+            [Python] Fix shared_ptr typemaps where the pointer type is a templated type with
+            with more than one parameter. Reported by Robert Lupton.
+
+03/27/2008: mgossage
+            [Lua] Added a typemap DISOWN for SWIGTYPE* and SWIGTYPE[], and support for %delobject feature.
+            Added Examples/lua/owner which demonstrates the use of the memory management.
+
+03/26/2008: wsfulton
+            [Java] Apply patch #1844301 from Monty Taylor to suppress enum constructor
+            unused warnings.
+
+03/26/2008: wsfulton
+            [Python] Apply patch #1924524 from Casey Raymondson which ensures the
+            "No constructor defined" message is displayed when attempting to call a
+            constructor on a class that doesn't have a constructor wrapper, eg if
+            the C++ class is abstract.
+
+03/26/2008: wsfulton
+            [Python] Apply patch #1925702 from Casey Raymondson which removes warning 512
+            for std::vector wrappers.
+
+03/26/2008: olly
+	    [Python] Apply GCC 4.3 warnings patch from Philipp Thomas
+	    (SF#1925122).
+
+03/21/2008: wsfulton
+            [Python] Thread safety patch for STL iterators from Abhinandan Jain.
+
+03/17/2008: mgossage
+            [Lua] Added %luacode feature to add source code into wrappers.
+            Updated documentation to document this.
+            Added Examples/lua/arrays to show its use (and typemaps)
+
+03/17/2008: olly
+	    Fix nonportable sed usage which failed on Mac OS X (and probably
+	    other platforms).  Fixes SF#1903612.
+
+03/17/2008: olly
+	    Fix memory leak in SWIG's parser (based on patch from Russell
+	    Bryant in SF#1914023).`
+
+03/12/2008: wsfulton
+            Fix bug #1878285 - unnecessary cast for C struct creation wrappers.
+
+03/12/2008: wsfulton
+            [Python] Remove debugging info when using shared_ptr support
+
+03/06/2008: mgossage
+            [Lua] Updated documentation for Lua exceptions.
+            Added Examples/lua/exception and Examples/lua/embed2.
+            Small updates to the typemaps.
+
+03/04/2008: wsfulton
+            [Java, C#] Add char *& typemaps.
+
+03/04/2008: wsfulton
+            Fix occasional seg fault when attempting to report overloaded methods as being ignored.
+
+02/29/2008: wsfulton
+            [Perl] Fix #1904537 Swig causes a Perl warning "x used only once" in Perl 5.10
+            reported by Ari Jolma
+
+02/29/2008: wsfulton
+            [Python] Add shared_ptr varin/varout typemaps for wrapping global variables.
+
+02/25/2008: wsfulton
+            Fix $wrapname to work in %exception (fixes some wrap:name assertions)
+
+Version 1.3.34 (27 February 2008)
+=================================
+
+02/13/2008: wsfulton
+            [R] Fix wrapping of global function pointer variables.
+
+02/13/2008: wsfulton
+            Add new special variables for use within %exception:
+              $wrapname - language specific wrapper name
+              $overname - if a method is overloaded this contains the extra mangling used on 
+                          the overloaded method
+              $decl     - the fully qualified C/C++ declaration of the method being wrapped 
+                          without the return type
+              $fulldecl - the fully qualified C/C++ declaration of the method being wrapped 
+                          including the return type
+
+02/12/2008: drjoe
+            [R] Now setting S4 flag in SWIG created objects.  This
+            fixes R-SWIG for 2.6 and warning for 2.6 failure has been removed.
+
+02/11/2008: mgossage
+            [Lua] Added a patch by Torsten Landschoff to fix the unary minus issue
+            Ran 'astyle --style=kr -2' across lua.cxx to neaten it up
+
+02/10/2008: wsfulton
+            Bump SWIG_RUNTIME_VERSION to 4. This is because of the recently introduced API 
+            change in the conversion functions, ie change in definition of swig_converter_func.
+            Anyone calling SWIG_TypeCast must pass in a valid value for the new additional
+            (third) parameter and then handle the newly created memory if the returned value
+            is set to SWIG_CAST_NEW_MEMORY else a memory leak will ensue.
+
+02/09/2008: wsfulton
+            [Python] Experimental shared_ptr typemaps added. Usage is the same as the recently
+            added Java and C# shared_ptr typemaps. Two macros are available, although these
+            may well change in a future version:
+
+            For base classes or classes not in an inheritance chain:
+              SWIG_SHARED_PTR(PROXYCLASS, TYPE)
+            For derived classes:
+              SWIG_SHARED_PTR_DERIVED(PROXYCLASS, BASECLASSTYPE, TYPE)
+
+            The PROXYCLASS is the name of the proxy class, but is only required for Java/C#.
+            Example usage:
+
+              %include "boost_shared_ptr.i"
+
+              SWIG_SHARED_PTR(Klass, Space::Klass)
+              SWIG_SHARED_PTR_DERIVED(KlassDerived, Space::Klass, Space::KlassDerived)
+
+              namespace Space {
+                struct Klass { ... };
+                struct KlassDerived : Klass { ... };
+              }
+
+            Further details to follow in future documentation, but the following features
+            should be noted:
+
+            - Not restricted to boost::shared_ptr, eg std::tr1::shared_ptr can also be used.
+            - Available typemap groups:
+              (a) Typemaps for shared_ptr passed by value, reference, pointer and pointer 
+                  reference.
+            - (b) Typemaps for passing by raw value, raw pointer, raw reference, raw pointer
+                  reference. 
+            - The code being wrapped does not even have to use shared_ptr, SWIG can use
+              shared_ptr as the underlying storage mechanism instead of a raw pointer due to 
+              the typemaps in group (b) above.
+            - No array support as shared_ptr does not support arrays.
+            - This works quite differently to the usual SWIG smart pointer support when
+              operator-> is parsed by SWIG:
+              - An additional smart pointer class is not generated reducing code bloat in
+                the wrappers.
+              - Using smart pointers and raw pointers can be mixed seamlessly.
+              - Missing constructors for the smart pointers is no longer a problem and so
+                separate factory type functions do not have to be written and wrapped.
+              - The implicit C++ shared_ptr< derived class > to shared_ptr< base class >
+                cast also works in the target language. This negates the necessity to write
+                an explicit helper cast function providing the upcast which would need
+                calling prior to passing a derived class to a method taking a shared_ptr to
+                a base class.
+
+02/09/2008: wsfulton
+            [Python] Add support for overriding the class registration function via a new
+            "smartptr" feature. This is a very low level of customisation most users
+            would never need to know. The feature will typically be used for intrusive 
+            smart pointers along with additional typemaps. Example usage of the feature:
+
+              %feature("smartptr", noblock=1) Foo { boost::shared_ptr< Foo > }
+              class Foo {};
+
+            The generated Foo_swigregister function will then register boost::shared < Foo >
+            (SWIGTYPE_p_boost__shared_ptrTFoo_t instead of SWIGTYPE_p_Foo) as the underlying
+            type for instantiations of Foo.
+
+02/09/2008: wsfulton
+            Features now supports the optional 'noblock' attribute for all usage of %feature. 
+            When specified, the { } braces are removed from the feature code. This is identical
+            in behaviour to usage of 'noblock' in typemaps and is used when the preprocessor
+            is required to operate on the code in the feature and the enclosing { } braces
+            are not required. Example:
+
+              #define FOO foo
+              %feature("smartptr", noblock="1") { FOO::bar }
+
+            The preprocessor then reduces this as if this had been used instead:
+
+              %feature("smartptr") "foo::bar"
+
+02/01/2008: olly
+	    [Python] Fix format string bug (SF#1882220).
+
+01/31/2008: wsfulton
+            Additions to the %types directive. Now the conversion / casting code can be
+            overridden to some custom code in the %types directive, like so:
+
+              %types(fromtype = totype) %{
+                ... code to convert fromtype to totype and return ...
+              %}
+
+            The special variable $from will be replaced by the name of the parameter of the
+            type being converted from. The code must return the totype cast to void *. Example:
+
+              class Time;
+              class Date;
+              Date &Time::dateFromTime();
+
+              %types(Time = Date) %{
+                Time *t = (Time *)$from;
+                Date &d = t->dateFromTime();
+                return (void *) &d;
+              %}
+
+            resulting in the conversion / casting code looking something like:
+
+              static void *_p_TimeTo_p_Date(void *x) {
+                Time *t = (Time *)x;
+                Date &d = t->dateFromTime();
+                return (void *) &d;
+              }
+
+            This is advanced usage, please use only if you understand the runtime type system.
+
+01/30/2008: mgossage
+	    Small update to documentation in Typemaps.html, to warn about use of local 
+	    variables in typemaps for multiple types.
+
+01/25/2008: wsfulton
+	    [Java] Fix bug reported by Kevin Mills in ARRAYSOFCLASSES typemaps where any
+            changes made to an array element passed from Java to C are not reflected back
+            into Java.
+
+01/24/2008: mgossage
+	    More updates to the configure script for detecting lua.
+	    Also looks in /usr/include/lua*
+	    Also changed typemaps.i not to check for NULL before freeing a pointer
+
+01/21/2008: wsfulton
+	    [Python] For STL containers, SWIG no longer attempts to convert from one
+            STL container to another, eg from std::vector<int> to std::vector<double>
+            or std::list<int> to std::vector<int> or even std::vector<Foo> to
+            std::vector<Bar> as it previously did. In fact SWIG no longer attempts to
+            convert any SWIG wrapped C++ proxy class that is also a Python sequence,
+            whereas previously it would. Any non-SWIG Python sequence will still be
+            accepted wherever an STL container is accepted. Overloaded methods using
+            containers should be faster.
+
+01/18/2008: wsfulton
+	    [C#] Add 'directorinattributes' and 'directoroutattributes' typemap attributes
+            for the imtype typemap. These should contain C# attributes which will
+            be generated into the C# director delegate methods.
+
+01/18/2008: olly
+	    Fix handling of byte value 255 in input files on platforms where
+	    char is signed (it was getting mapped to EOF).  Fixes SF#1518219.
+
+01/16/2008: wsfulton
+	    Fix template member variables wrapped by a smart pointer. Bug reported 
+            by Robert Lupton.
+
+01/14/2008: mgossage
+	    Substantial changes to configure script for detecting lua.
+	      Code can now link to liblua.a, liblua50.a or liblua51.a
+	      It's also a lot neater now.
+
+12/16/2007: wsfulton
+	    [Perl] Backed out #1798728 - numbers can be passed to functions taking char *
+
+12/16/2007: wsfulton
+	    Fix #1832613 - Templates and some typedefs involving pointers or function pointers
+
+12/12/2007: wsfulton
+	    [Java] Fix #1632625 - Compilation errors on Visual C++ 6 when using directors.
+
+12/12/2007: wsfulton
+	    [Perl] Fix #1798728 - numbers can be passed to functions taking char *.
+
+12/12/2007: wsfulton
+	    Fix #1819847 %template with just one default template parameter 
+
+              template<typename T = int> class Foo {...};
+              %template(FooDefault) Foo<>;
+
+12/12/2007: mgossage
+	    [Lua] Small correction on Lua.html
+
+12/09/2007: wsfulton
+	    Apply patch #1838248 from Monty Taylor for vpath builds of SWIG.
+
+12/08/2007: wsfulton
+	    [Lua] Fixes to remove gcc-4.2 warnings
+
+12/06/2007: wsfulton
+	    Fix #1734415 - template template parameters with default arguments such as:
+
+              template<typename t_item, template<typename> class t_alloc = pfc::alloc_fast >
+                class list_t : public list_impl_t<t_item,pfc::array_t<t_item,t_alloc> > { ... };
+
+12/04/2007: mgossage
+	    [lua] Fix a bug in the class hierachy code, where the methods were not propagated, 
+	    if the name ordering was in a certain order.
+	    Added new example programs (dual, embed) and runtime tests for test-suite.
+
+11/30/2007: wsfulton
+	    Fix using statements using a base class method where the methods were overloaded.
+            Depending on the order of the using statements and method declarations, these
+            were previously generating uncompileable wrappers, eg:
+
+              struct Derived : Base {
+                virtual void funk();
+                using Base::funk;
+              };
+
+Version 1.3.33 (November 23, 2007)
+=================================
+
+11/21/2007: mikel
+	    [allegrocl] omit private slot type info in the classes/types
+	    defined on the lisp side. Fix bug in mapping of C/++ types
+	    to lisp types. Fix typo in modules generated defpackage form.
+	    Have std::string *'s automatically marshalled between foreign
+	    and lisp strings.
+	
+11/20/2007: olly
+	    [Python] Fill in Python Dictionary functions list (patch from
+	    Jelmer Vernooij posted to swig-devel).
+
+11/20/2007: beazley
+            Fixed a bug in the C scanner related to backslash characters.
+
+11/19/2007: wsfulton
+	    [Perl] Fix broken compilation of C++ wrappers on some compilers.
+
+11/16/2007: olly
+	    [Python] Don't pass Py_ssize_t for a %d printf-like format as
+	    that's undefined behaviour when sizeof(Py_ssize_t) != sizeof(int).
+
+Version 1.3.32 (November 15, 2007)
+==================================
+
+11/14/2007: wsfulton
+            [R] Package name and dll name is now the same as the SWIG module
+            name. It used to be the module name with _wrap as a suffix. The package
+            and dll names can be modified using the -package and -dll commandline
+            options.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+11/11/2007: wsfulton
+            [R] Add support for Windows (Visual C++ 8 tested)
+
+11/10/2007: olly
+	    [php] Fix makefile generated by -make (SF#1633679).  Update
+	    documentation to mark "-make" as deprecated (none of the other
+	    SWIG backends seem to offer such a feature, it can't realistically
+	    generate a fully portable makefile, and the commands to build an
+	    extension are easy enough to write for the user's preferred build
+	    tool).  Also recommend against the use of "-phpfull" (it's only
+	    really useful when static linking, and a dynamically loadable
+	    module is virtually always the better approach).
+
+11/09/2007: olly
+	    Fix --help output to note that `export SWIG_FEATURES' is required.
+
+10/29/2007: wsfulton
+            [R] Fix seg fault on Windows
+            [R] Examples R scripts are now platform independent
+
+10/30/2007: mgossage
+	    [lua] fixed bug in template classes which cases template_default2
+	    and template_specialization_defarg to fail.
+	    Added several warning filters into the overload's test cases.
+	    Added runtime tests for several codes.
+	    You can now make check-lua-test-suite with no errors and only a few warnings.
+
+10/30/2007: olly
+	    [guile] Fix the configure test to put GUILELINK in LIBS not LDFLAGS
+	    (SF#1822430).
+
+10/30/2007: olly
+	    [guile] Fix the guile examples on 64-bit platforms.
+
+10/29/2007: wsfulton
+            [C#] Fix member pointers on 64 bit platforms.
+
+10/28/2007: olly
+	    [lua] Fix swig_lua_class instances to be static to allow multiple
+	    SWIG wrappers to be compiled into the same executable statically.
+	    Patch from Andreas Fredriksson (posted to the swig mailing list).
+
+10/28/2007: olly
+	    [lua] Fix Examples/lua to pass SRCS for C tests rather than CXXSRCS.
+	    The code as it was happened to work on x86, but broke on x86_64 (and
+	    probably any other platforms which require -fPIC).
+
+10/28/2007: wsfulton
+            [Java, C#] New approach for fixing uninitialised variable usage on error in director
+            methods using the new templated initialisation function SwigValueInit().
+
+10/28/2007: wsfulton
+            [Perl] Use more efficient SvPV_nolen(x) instead of SvPV(x,PL_na) if SvPV_nolen is
+            supported.
+
+10/26/2007: wuzzeb
+	    [Chicken] Fix global variables of class member function pointers.
+	    Other minor fixes, so all tests in the chicken test suite now pass
+
+10/25/2007: olly
+	    Fix UTL typecheck macro for a function taking char[] or const
+	    char[] (SF#1820132).
+
+10/22/2007: mkoeppe
+	    [Guile] Filter out -ansi -pedantic from CFLAGS while compiling test programs for Guile
+	    in configure.  This enables running the test suite for Guile if it is installed and
+	    usable.
+
+10/22/2007: mkoeppe
+	    [Guile -scm] Fix testcases apply_signed_char and apply_strings
+	    by adding explicit casts to the appropriate $ltype.
+
+10/22/2007: wsfulton
+            [Java, C#] Fix uninitialised variable usage on error in director methods.
+
+10/19/2007: wsfulton
+            [Java, C#] Bug #1794247 - fix generated code for derived classes when csbase or javabase
+            typemaps are used with the replace="1" attribute.
+
+10/19/2007: wsfulton
+            [Python] Docs updated to suggest using distutils. Patch #1796681 from Christopher Barker.
+
+10/19/2007: olly
+	    [perl5] Clear errno before calls to strtol(), strtoul(), strtoll()
+	    and strtoull() which we check errno after to avoid seeing a junk
+	    value of errno if there isn't an error in the call.
+
+10/16/2007: wsfulton
+            Deprecate %attribute_ref and replace with %attributeref. There is just an argument
+            order change in order to maintain consistency with %attribute, from:
+
+              %attribute_ref(Class, AttributeType, AccessorMethod, AttributeName)
+            to
+              %attributeref(Class, AttributeType, AttributeName, AccessorMethod)
+
+10/16/2007: olly
+	    [Tcl] Fix several ocurrences of "warning: deprecated conversion
+	    from string constant to 'char*'" from GCC 4.2 in generated C/C++
+	    code.
+
+10/16/2007: olly
+	    [PHP] Fix many occurrences of "warning: deprecated conversion from
+	    string constant to 'char*'" from GCC 4.2 in generated C/C++ code
+	    when compiling with a new enough version of PHP 5 (tested with
+	    PHP 5.2.3, but PHP 5.2.1 is probably the minimum requirement).
+
+10/15/2007: wsfulton
+            Patch #1797133 from David Piepgrass fixes %attribute when the getter has the same name
+            as the attribute name and no longer generate non-functional setter for read-only attributes.
+
+10/15/2007: olly
+	    [Tcl] Prevent SWIG_Tcl_ConvertPtr from calling the unknown proc.
+	    Add Examples/tcl/std_vector/ which this change fixes.  Patch
+	    is from "Cliff C" in SF#1809819.
+
+10/12/2007: wsfulton
+            [Java] Add DetachCurrentThread back in for directors. See entry dated 08/11/2006 and
+            search for DetachCurrentThread on the mailing lists for details. The crashes on Solaris
+            seem to be only present in jdk-1.4.2 and lower (jdk-1.5.0 and jdk-1.6.0 are okay), so
+            anyone using directors should use a recent jdk on Solaris, or define (see director.swg)
+            SWIG_JAVA_NO_DETACH_CURRENT_THREAD to the C++ compiler to get old behaviour.
+
+10/12/2007: wsfulton
+	    [Java] Ensure the premature garbage collection prevention parameter (pgcpp) is generated
+            when there are C comments in the jtype and jstype typemaps.
+
+10/12/2007: wuzzeb
+	    Added a testsuite entry for Bug #1735931
+
+10/09/2007: olly
+	    Automatically rerun autogen.sh if configure.in is modified.
+
+10/09/2007: olly
+	    Enhance check-%-test-suite rule and friends to give a more helpful
+	    error message if you try them for a language which doesn't exist
+	    (e.g. "make check-php-test-suite" rather than the correct
+	    "make check-php4-test-suite").
+
+10/09/2007: olly
+	    Add make rule to regenerate Makefile from Makefile.in if it has
+	    changed.
+
+10/09/2007: olly
+	    [php] Fix long-standing memory leak in wrapped constructors and
+	    wrapped functions/methods which return an object.
+
+10/08/2007: olly
+	    Fix Makefile.in to read check.list files correctly in a VPATH
+	    build.
+
+10/07/2007: wsfulton
+            [C#, Java] Experimental shared_ptr typemaps added
+
+09/27/2007: mgossage
+	    [lua] added more verbose error messages for incorrect typechecks.
+	    Added a routine which checks the exact number of parameters passed to a function
+	    (breaks operator_overloading for unary minus operator, currently disabled).
+	    Reorganised the luatypemaps.swg to tidy it up.
+	    Added a lot of %ignores on the operators not supported by lua.
+	    Added support for constant member function pointers & runtest for member_pointer.i
+	    Added first version of wchar.i
+
+09/25/2007: wsfulton
+            [C#, Java] throws typemaps for std::wstring using C# patch #1799064 from David Piepgrass
+
+09/24/2007: wsfulton
+            [Tcl] Apply #1771313 to fix bug #1650229 - fixes long long and unsigned long long
+            handling.
+
+09/20/2007: olly
+	    [Java] Eliminate some unnecessary uses of a temporary buffer
+	    allocated using new[].  SF#1796609.
+
+09/19/2007: wsfulton
+            [C#] The $csinput special variable can be used in the csvarin typemap where it is always
+            expanded to 'value'.
+
+09/19/2007: wsfulton
+            [C#] Fix bug reported by Glenn A Watson and #1795260 where the cstype typemap used the 'ref'
+            keyword in the typemap body, it produced uncompilable C# properties (variable wrappers).
+            The type for the property now correctly comes from the 'out' attribute in the cstype typemap.
+
+09/19/2007: wsfulton
+            [Java] Fix const std::wstring& typemaps
+
+09/19/2007: wsfulton
+	    [Java] Ensure the premature garbage collection prevention parameter (pgcpp) is generated
+            where a parameter is passed by pointer reference, eg in the std::vector wrappers. The pgcpp
+            is also generated now when user's custom typemaps use a proxy class in the jstype typemap
+            and a 'long' in the jtype typemap.
+
+09/18/2007: olly
+	    [php] Add typemaps for handling parameters of type std::string &
+	    which are modified by the wrapped function.
+
+09/17/2007: olly
+	    [python] Split potentially long string literals to avoid hitting
+	    MSVC's low fixed limit on string literal length - patch from
+	    SF#1723770, also reported as SF#1630855.
+
+09/17/2007: olly
+	    [ocaml] Fix renaming of overloaded methods in the method_table -
+	    my patch from SF#940399.
+
+09/17/2007: olly
+	    [python] Simpler code for SWIG_AsVal_bool() which fixes a "strict
+	    aliasing" warning from GCC - patch from SF#1724581 by Andrew
+	    Baumann.
+
+09/17/2007: olly
+	    [perl5] Use sv_setpvn() to set a scalar from a pointer and length
+	    - patch from SF#174460 by "matsubaray".
+
+09/17/2007: olly
+	    When wrapping C++ code, generate code which uses
+	    std::string::assign(PTR, LEN) rather than assigning
+	    std::string(PTR, LEN).  Using assign generates more efficient code
+	    (tested with GCC 4.1.2).
+
+09/07/2007: wsfulton
+	    Fix %ignore on constructors which are not explicitly declared [SF #1777712]
+
+09/05/2007: wuzzeb (John Lenz)
+	    - Change r_ltype in typesys.c to store a hashtable instead of a single value.
+	      several very subtle bugs were being caused by multiple ltypes being mapped
+	      to a single mangled type, mostly when using typedefed template parameters.
+	      Now, r_ltype stores a hashtable of possible ltypes, and when generating the
+	      type table, all the ltypes are added into the swig_type_info structure.
+
+08/31/2007: wsfulton
+            SF #1754967 from James Bigler.
+            - Fix bug in turning on warnings that were turned off by default. Eg 'swig -w+309' will now
+              turn on the normally suppressed warning 309.
+
+            - New -Wextra commandline option which enables the extra warning numbers:
+              202,309,403,512,321,322 (this is the list of warnings that have always been suppressed by
+              default). By specifying -Wextra, all warnings will be turned on, but unlike -Wall,
+              warnings can still be selectively turned on/off using %warnfilter,
+              #pragma SWIG nowarn or further -w commandline options, eg:
+                swig -Wextra -w309
+              will turn on all warnings except 309.
+
+08/28/2007: wsfulton
+            - New debugging options, -debug-module <n> and -debug-top <n> to display the parse tree at
+              various stages, where <n> is a comma separated list of stages 1-4.For example, to
+              display top of parse tree at stages 1 and 3:
+                swig -debug-top 1,3
+
+            - Deprecate the following options which have equivalents below:
+              -dump_parse_module    =>   -debug-module 1
+              -dump_module          =>   -debug-module 4
+              -dump_parse_top       =>   -debug-top 1
+              -dump_top             =>   -debug-top 4
+
+            - Renamed some commandline options for naming consistency across all options:
+              -debug_template  =>   -debug-template
+              -debug_typemap   =>   -debug-typemap
+              -dump_classes    =>   -debug-classes
+              -dump_tags       =>   -debug-tags
+              -dump_typedef    =>   -debug-typedef
+              -dump_memory     =>   -debug-memory
+
+08/25/2007: olly
+	    [PHP5] Fix handling of double or float parameters with an integer
+	    default value.
+
+08/25/2007: olly
+	    [PHP5] Generate __isset() methods for setters for PHP 5.1 and later.
+
+08/20/2007: wsfulton
+            [Java C#] Fix director bug #1776651 reported by Stephane Routelous which occurred when
+            the director class name is the same as the start of some other symbols used within
+            the director class.
+
+08/17/2007: wsfulton
+            Correct behaviour for templated methods used with %rename or %ignore and the empty
+            template declaration - %template(). A warning is issued if the method has not been
+            renamed.
+
+08/16/2007: mutandiz (Mikel Bancroft)
+	    [allegrocl] Name generated cl file based on input file rather than by
+	    module name. It was possible to end up with a mypackage.cl and a test_wrap.c
+	    when parsing a test.i input file. Confusing. Also, include external-format
+	    templates for :fat and :fat-le automatically to avoid these being compiled
+	    at runtime.
+
+08/15/2007: efuzzyone
+            [cffi] Apply patch #1766076 from Leigh Smith adding support for newly introduced
+            in cffi :long-long and :unsigned-long-long.
+
+08/10/2007: wsfulton
+            [Java] Add documentation patch #1743573 from Jeffrey Sorensen. It contains a neat
+            idea with respect to better memory management by the JVM of C++ allocated memory.
+
+08/10/2007: wsfulton
+            [Perl] Apply patch #1771410 from Wade Brainerd to fix typedef XS(SwigPerlWrapper) in
+            perlrun.swg for ActiveState Perl build 822 and Perl 5.8.9 and 5.10 branches.
+
+08/10/2007: wsfulton
+            [Lua] const enum reference typemaps fixed.
+
+08/09/2007: wsfulton
+            [C#] Added missing support for C++ class member pointers.
+
+08/09/2007: wsfulton
+            [C#, Java] Add support for $owner in the "out" typemaps like in the the scripting
+            language modules. Note that $owner has always been supported in the "javaout" / "csout"
+            typemaps.
+
+08/01/2007: wsfulton
+            Fix smart pointer handling for classes that have templated methods within the smart
+            pointer type. Problem reported by craigdo at ee.washington.edu.
+
+07/31/2007: efuzzyone
+            [cffi] fixed memory access after being freed bug. thanks to Martin Percossi.
+            package name clos changed to cl. thanks to Ralf Mattes
+
+07/24/2007: wsfulton
+            Parallel make support added for the examples and test-suite for developers who have
+            more than one CPU. Now parallel make can be used for checking in addition to building
+            the SWIG executable. Some typical checking examples:
+
+              make -j8 -k check
+              make -j4 check-java-test-suite
+              make -j2 check-java-examples
+
+07/19/2007: mgossage
+            Fixed bug that stopped configure working on mingw (applied dos2unix to configure.in)
+
+07/10/2007: mgossage
+            [lua] Extra compatibility with Lua 5.1 (updated SWIG_init, docs, examples, test suite)
+	    Removed name clash for static link of multiple modules
+
+07/05/2007: mgossage
+            [lua] Fix a bug in SWIG_ALLOC_ARRAY()
+            improved the error messages for incorrect arguments.
+            Changed the output of swig_type() to use the human readable form of the type,
+	    rather than the raw swig type.
+
+07/03/2007: wsfulton
+            [C#] Fix directors for some overloaded methods where the imtype resulted in identical
+            methods being generated in the C# director class, eg void foo(int *) and void foo(double *)
+            used to generated two of these:
+
+              private void SwigDirectorfoo(IntPtr p) { ... }
+
+06/25/2007: wsfulton
+            [Java, C#] Some parameter name changes in std_vector.i allowing better targeting
+            of typemaps for method parameters (for memory management of containers of pointers).
+
+06/07/2007: mutandiz (Mikel Bancroft)
+	    [allegrocl]
+	    fix foreign-type constructor to properly look for ffitype typemap
+	    bindings. fix inout_typemaps.i for strings.
+
+06/06/2007: olly
+	    [Ruby]
+	    Use whichever of "long" or "long long" is the same size as "void*"
+	    to hold pointers as integers, rather than whichever matches off_t.
+	    Fixes compilation on OS X and GCC warnings on platforms where
+	    sizeof(void*) < sizeof(off_t) (SF patch #1731979).
+
+06/06/2007: olly
+	    [PHP5]
+	    Fix handling of a particular case involving overloaded functions
+	    with default parameters.
+
+06/05/2007: mutandiz (Mikel Bancroft)
+	    [allegrocl]
+	    Fix case where we'd pass fully qualified identifiers
+	    (i.e. NS1::NS2::FOO) to swig-insert-id. All namespaces
+	    should be stripped.
+
+	    Fix bug in TypedefHandler introduced by last fix.
+
+06/05/2007: olly
+	    Fix reporting of filenames in errors after %include (patch from
+	    Leigh Smith in #1731040; also reported as #1699940).
+
+05/31/2007: olly
+	    [Python]
+	    Fix "missing initialiser" warning when compiling generated C/C++
+	    wrapper code with Python 2.5 with warnings enabled (patch from
+	    bug#1727668 from Luke Moore).
+
+05/29/2007: olly
+	    [Python]
+	    Split docstrings into separate string literals at each newline when
+	    generating C/C++ wrapper code (the C/C++ compiler will just combine
+	    them back into a single string literal).  This avoids MSVC
+	    complaining that the strings are too long (problem reported by
+	    Bo Peng on the mailing list).
+
+05/28/2007: olly
+	    [Python]
+	    Escape backslashes in docstrings.
+
+05/26/2007: olly
+	    [Python]
+	    Fix autodoc generation of enums to be more consistent with how the
+	    enums are wrapped - patch #1697226 from Josh Cherry.
+
+05/26/2007: olly
+	    [PHP5]
+	    Fix wrapping of methods and functions which return a pointer to a
+	    class (bug#1700788) and those which have overloaded forms returning
+	    both classes and non-classes (bug#1712717, thanks to Simon
+	    Berthiaume for the patch).
+
+05/25/2007: wsfulton
+            Fixed %rename inconsistency in conversion operators as reported by Zhong Ren. The matching
+            is now done on the operator name in the same way as it is done for parameters. For example:
+
+              %rename(opABC) Space::ABC::operator ABC() const;
+              %rename(methodABC) Space::ABC::method(ABC a) const;
+              namespace Space {
+                class ABC {
+                  public:
+                    void method(ABC a) const {}
+                    operator ABC() const { ABC a; return a; }
+                };
+              }
+
+            Note that qualifying the conversion operator previously may or may not have matched.
+            Now it definitely won't, so this will not match:
+
+              %rename(opABC) Space::ABC::operator Space::ABC() const;
+
+            in the same way that this does not match:
+
+              %rename(methodABC) Space::ABC::method(Space::ABC a) const;
+
+            The documentation has been improved with respect to %rename, namespaces and templates.
+            Conversion operators documentation too.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+05/16/2007: mutandiz
+	    [allegrocl]
+	    Fix bad generation of local var ltype's in functionWrapper().
+	    Try to work better with the backward order in which swig
+	    unrolls nested class definitions.
+	    cleaned up a little unnecessary code/debug printf's.
+	    Remove warning when replacing $ldestructor for ff:foreign-pointer
+
+05/12/2007: olly
+	    [Python]
+	    swig -python -threads now generates C/C++ code which uses Python's
+	    own threading abstraction (from pythread.h) rather than OS specific
+	    code.  The old code failed to compile on MS Windows.  (See SF patch
+	    tracker #1710341).
+
+05/04/2007: gga
+	    [Ruby]
+	    Changed STL renames to be global renames.  This fixes
+	    STL functions not being renamed when autorename is on.
+            This is a not a totally perfect work-around, but better.
+	    Someone really needs to fix the template renaming code.
+	    (See bug #1545634)
+
+05/04/2007  gga
+	    [All]
+            Changed %rename("%(undercase)s") a little so that single
+	    numbers at the end of a function are not undercased.  That is:
+		getSomething -> get_something
+		get2D	     -> get_2d
+		get234	     -> get_234
+	    BUT:
+		asFloat2     -> as_float2
+	    (Bug #1699714)
+
+05/03/2007: gga
+	    [Ruby]
+	    Made __swigtype__ => @__swigtype__ so it can be accessed
+	    from the scripting language (and follows Ruby's official
+            documentation, just in case).
+	    Made tracking => @__trackings__ for same reason.
+	    Currently storing ivars without the @ seems valid, but
+	    the PickAxe says this is not correct, so just in case...
+
+05/03/2007: gga
+	    [Ruby]
+	    Applied patch for -minherit bug and exception classes.
+	    This issue should be revisited more closely, as Multiple
+	    Inheritance in Ruby is still problematic.
+	    (patch/bug #1604878)
+
+05/03/2007: gga
+	    [Ruby]
+	    Overloaded functions in ruby will now report to the user
+            the possible prototypes when the user mistypes the number or
+            type of a parameter.
+
+05/03/2007: gga
+	    [Ruby]
+	    Forgot to document the bug fixing of an old bug regarding
+	    exceptions.
+	    (bug #1458247)
+
+05/03/2007: gga
+	    [Ruby]
+	    Fixed Ruby documentation to use the proper css styles for
+	    each section. Added autodoc section to Ruby's docs to
+	    document the features supported by Ruby in documenting its modules.
+	    Made rdoc documentation spit out the full name of the class +
+	    method name.  Albeit this will make the current rdoc not recognize
+            the method, this is still needed to disambiguate between different
+            classes with similar methods (rdoc was created to document the
+	    ruby source which only contains one class per c file, unlike swig)
+            I have patched rdoc to make it more friendly to swig.  This
+            patch needs to be merged in the ruby std library now.
+
+05/03/2007: gga
+	    [Ruby]
+	    Changed flag -feature to be -init_name to better reflect its
+	    purpose and avoid confusion with -features.
+
+05/03/2007: gga
+	    [Ruby]
+	    Improved autodoc generation.
+	    Added autodoc .swg files to Ruby library for easily adding
+	    documentation to common Ruby methods and STL methods.
+	    Fixed autodoc documenting of getters and setters and module.
+	    Made test suite always generate autodocs.
+
+05/03/2007: gga
+	    [Ruby]
+	    Removed some warnings from STL and test suite.
+
+05/02/2007: mgossage
+            [Lua] Fixed issues with C++ classes and hierachies across multiple
+	    source files. Fixed imports test case & added run test.
+	    Added Examples/imports.
+	    Added typename for raw lua_State*
+	    Added documentation on native functions.
+
+05/02/2007: gga
+	    [Ruby]
+	    Docstrings are now supported.
+	    %feature("autodoc") and %feature("docstring") are now
+	    properly supported in Ruby.  These features will generate
+	    a _wrap.cxx file with rdoc comments in them.
+
+05/02/2007: gga
+	    [Ruby]
+	    STL files have been upgraded to follow the new swig/python
+	    Lib/std conventions.
+	    This means std::vector, std::set, std::map, set::multimap,
+	    std::multiset, std::deque and std::string are now properly
+	    supported, including their iterators, support for containing
+	    ruby objects (swig::GC_VALUE) and several other ruby
+	    enhancements.
+	    std::complex, std::ios, std::iostream, std::iostreambuf and
+	    std::sstream are now also supported.
+	    std::wstring, std::wios, std::wiostream, std::wiostreambuf
+	    and std::wsstream are supported verbatim with no unicode
+	    conversion.
+
+	    std_vector.i now mimics the behavior of Ruby Arrays much more
+	    closely, supporting slicing, shifting, unshifting,
+            multiple indexing and proper return values on assignment.
+
+	    COMPATABILITY NOTE: this changes the older api a little bit in
+	    that improper indexing would previously (incorrectly) raise
+	    exceptions.  Now, nil is returned instead, following ruby's
+	    standard Array behavior.
+
+05/02/2007: gga
+	    [Ruby]
+	    Changed the value of SWIG_TYPECHECK_BOOL to be 10000 (ie. higher
+	    than that of all integers).
+	    This is because Ruby allows typecasting
+	    integers down to booleans which can make overloaded functions on
+	    bools and integers to fail.
+	    (bug# 1488142)
+
+05/02/2007: gga
+	    [Ruby]
+	    Fixed a subtle bug in multiple argouts that could get triggered if
+	    the user returned two or more arguments and the first one was an
+	    array.
+
+05/01/2007: gga
+	    [Ruby]
+	    Improved the documentation to document the new features
+            added, add directorin/out/argout typemaps, etc.
+
+05/01/2007: gga
+	    [Ruby]
+	    Added %initstack and %ignorestack directives for director
+	    functions.  These allow you to control whether a director
+	    function should re-init the Ruby stack.
+	    This is sometimes needed for an embedded Ruby where the
+	    director method is used as a C++ callback and not called
+            by the user from ruby code.
+	    Explanation:
+	    Ruby's GC needs to be aware of the running OS stack in order to
+	    mark any VALUE (Ruby objects) it finds there to avoid collection
+	    of them.  This allows the ruby API to be very simple and allows
+	    you to write code like "VALUE a = sth" anywhere without needing
+	    to do things like refcounting like python.
+	    By default, the start of the stack is set when ruby_init() is
+	    called.   If ruby is inited within main(), as it usually is the
+	    case with the main ruby executable, ruby will be able to calculate
+	    its stack properly.  However, when this is not possible, as when
+	    ruby is embedded as a plugin to an application where main is not
+	    available, ruby_init() will be called in the wrong place, and
+	    ruby will be incorrectly tracking the stack from the function
+	    that called ruby_init() forwards only, which can lead to
+	    all sorts of weird crashes or to ruby thinking it has run out of
+	    stack space incorrectly.
+	    To avoid this, director (callback) functions can now be tagged
+	    to try to reset the ruby stack, which will solve the issues.
+	    NOTE: ruby1.8.6 still contains a bug in it in that its function
+	    to reset the stack will not always do so.  This bug is triggered
+	    very rarely, when ruby is called from two very distinct places
+	    in memory, like a branch of main() and another dso.  This bug
+	    has now been reported to ruby-core and is pending further
+	    investigation.
+	    (bug #1700535 and patch #1702907)
+
+04/30/2007: wsfulton
+            Fix #1707582 - Restore building from read-only source directories.
+
+04/30/2007: gga
+	    [Ruby]
+	    Ruby will now report the parameter index properly on type
+	    errors as well as the class and value of the incorrect
+	    argument passed.
+	    (feature request #1699670)
+
+04/30/2007: gga
+	    [Ruby]
+	    Ruby no longer creates the free_Class function if the class
+	    contains its own user defined free function (%freefunc).
+	    (bug #1702882)
+
+04/30/2007: gga
+	    [Ruby]
+	    Made directors raise a ruby exception for incorrect argout
+	    returned values if RUBY_EMBEDDED is set, instead of throwing
+	    an actual SwigDirector exception.
+	    This will prevent crashes when ruby is embedded and unaware
+	    of the SwigDirector exception.
+
+04/30/2007: gga
+	    [Ruby]
+	    Removed the need for -DSWIGEXTERN.
+	    Changed swig_ruby_trackings to be a static variable, but also
+	    be kept within a hidden instance variable in the SWIG module.
+	    This allows properly dealing with trackings across multiple
+	    DSOs, which was previously broken.
+	    (bug #1700535 and improvement to patch #1702907)
+
+04/29/2007: gga
+	    [Ruby] Fixed GC memory issues with trackings that could lead
+	    to segfaults when dealing, mainly, with static variables.
+	    (bug #1700535 and patch #1702907)
+
+04/29/2007: gga
+	    [Ruby]
+	    Fixed String conversion using old ruby1.6 macros.  Now
+	    StringValuePtr() is used if available.  This removes warnings
+	    when converting strings with \0 in them.
+	    (bug #1700535 and patch #1702907)
+
+04/29/2007: gga
+	    [Ruby]
+	    Fixed the argout count in directors for Ruby.  Previously,
+	    ignored or "numinputs=0" typemaps would incorrectly not get
+	    counted towards the argout count.
+	    (bug/patch #1545585)
+
+04/29/2007: gga
+	    [Ruby]
+	    Upgraded Ruby converter to recognize "numinputs=0".  Previously,
+	    only the old "ignore" flag was checked (which would currently
+	    still work properly, but is deprecated).
+
+04/29/2007: gga
+	    [Ruby - but should be made generic]
+
+	    %feature("numoutputs","0") added.
+
+	    This feature allows you to ignore the output of a function so
+	    that it is not added to a list of output values
+	    ( ie. argouts ).
+	    This should also become a feature of %typemap(directorout)
+	    as "numoutputs"=0, just like "numinputs"=0 exists.
+
+	    %feature("directors"=1)
+
+	    %include <typemaps.i>
+
+	    %feature("numoutputs","0") { Class::member_function1 };
+	    %typemap(out) MStatus { // some code, like check mstatus
+	                            // and raise exception if wrong };
+
+	    %inline %{
+	      typedef int MStatus;
+	      class Class {
+
+	      // one argument returned, but director out code added
+	      // MStatus is discarded as a return (out) parameter.
+	      virtual MStatus member_function1( int& OUTPUT );
+
+	      // two arguments returned, director out code added
+	      // MStatus is not discarded
+	      virtual MStatus member_function2( int& OUTPUT );
+	      };
+            %}
+
+
+04/21/2007: olly
+	    Fix parsing of float constants with an exponent (e.g. 1e-02f)
+	    (bug #1699646).
+
+04/20/2007: olly
+	    [Python] Fix lack of generation of docstrings when -O is used.
+	    Also, fix generation of docstrings containing a double quote
+	    character.  Patch from Richard Boulton in bug#1700146.
+
+04/17/2007: wsfulton
+            [Java, C#] Support for adding in Java/C# code before and after the intermediary call,
+            specifically related to the marshalling of the proxy type to the intermediary type.
+            The javain/csin typemap now supports the 'pre' and 'post' attributes to achieve this.
+            The javain typemap also supports an optional 'pgcppname' attribute for premature garbage
+            collection prevention parameter naming and the csin typemap supports an optional 'cshin'
+            attribute for the parameter type used in a constructor helper generated when the type is used
+            in a constructor. Details in the Java.html and CSharp.html documentation.
+
+04/16/2007: olly
+	    Don't treat `restrict' as a reserved identifier in C++ mode
+	    (bug#1685534).
+
+04/16/2007: olly
+	    [PHP5] Fix how zend_throw_exception() is called (bug #1700785).
+
+04/10/2007: olly
+	    Define SWIGTEMPLATEDISAMBIGUATOR to template for aCC (reported on
+	    swig-user that this is needed).
+
+04/04/2007: olly
+	    [PHP5] If ZTS is enabled, release <module>_globals_id in MSHUTDOWN
+	    to avoid PHP interpreter crash on shutdown.  This solution was
+	    suggested here: http://bugs.php.net/bug.php?id=40985
+
+04/03/2007: olly
+	    [PHP4] Add missing ZTS annotations to generated C++ wrapper code
+	    to fix compilation failures when using ZTS enabled SWIG (Linux
+	    distributions tend to disable ZTS, but notably the Windows build
+	    uses it by default).
+
+04/01/2007: efuzzyone
+            [CFFI] Patch #1684261: fixes handling of unsigned int literals, thanks Leigh Smith.
+            Also, improved documentation.
+
+03/30/2007: olly
+	    Avoid generating '<:' token when using SwigValueWrapper<> on a type
+	    which starts with '::' (patch #1690948).
+
+03/25/2007: wuzzeb (John Lenz)
+	    [perl5] Add SWIG_fail to the SWIG_exception macro.  Fixes a few problems reported
+	    on the mailing list.
+
+03/23/2007: wsfulton
+            String copying patch from Josh Cherry reducing memory consumption by about 25%.
+
+03/21/2007: wsfulton
+            [Java] Apply patch #1631987 from Ulrik Peterson - bool INOUT typemaps
+            fail on big endian machines.
+
+03/16/2007: wsfulton
+            Fix seg fault given dodgy C++ code: namespace abc::def { }
+
+03/16/2007: wsfulton
+            [Java] Fixes so that ARRAYSOFCLASSES and ARRAYSOFENUMS in arrays_java.i can be applied
+            to pointer types.
+
+03/03/2007: olly
+	    [PHP5] When we know the literal numeric value for a constant, use
+	    that to initialise the const member in the PHP wrapper class.
+
+03/02/2007: olly
+	    [PHP5] Fix PHP wrapper code generated for certain cases of
+	    overloaded forms with default arguments.
+
+02/26/2007: efuzzyone
+            [CFFI] Patch #1656395: fixed hex and octal values bug, thanks to Arthur Smyles.
+
+02/22/2007: mgossage
+            [Lua] Fixed bug in typemaps which caused derived_byvalue and rname test cases to fail.
+	    Updated derived_byvalue.i to explain how to find and fix the problem
+
+01/25/2007: wsfulton
+            Fix #1538522 and #1338527, forward templated class declarations without a
+            name for the templated class parameters, such as:
+
+              template <typename, class> class X;
+
+01/23/2007: mgossage
+            [Lua] Patch #1640862: <malloc.h> replaced by <stdlib.h>
+	    Patch #1598063 Typo in typemaps.i
+
+01/22/2007: mgossage
+            [Lua] Added a lua specific carrays.i which adds the operator[] support.
+	    modified the main code to make it not emit all the class member functions & accessors
+	    Note: C structs are created using new_XXX() while C++ classes use XXX() (should be standardised)
+	    Updated test case: li_carrays
+	    Updated the documentation.
+
+01/12/2007: wsfulton
+            [Php] Add support for newfree typemaps (sometimes used by %newobject)
+
+01/12/2007: beazley
+            New command line option -macroerrors.   When supplied, this will force
+            the C scanner/parser to report proper location information for code contained
+            inside SWIG macros (defined with %define).  By default, SWIG merely reports
+            errors on the line at which a macro is used.  With this option, you
+            can expand the error back to its source---something which may simplify
+            debugging.
+
+01/12/2007: beazley
+            [Internals] Major overhaul of C/C++ scanning implementation.  For quite
+            some time, SWIG contained two completely independent C/C++ tokenizers--
+            the legacy scanner in CParse/cscanner.c and a general purpose scanner
+            in Swig/scanner.c. SWIG still has two scanning modules, but the C parser
+            scanner (CParse/cscanner.c) now relies upon the general purpose
+            scanner found in Swig/scanner.c.  As a result, it is much smaller and
+            less complicated.  This change also makes it possible to maintain all
+            of the low-level C tokenizing in one central location instead of two
+            places as before.
+
+            ***POTENTIAL FLAKINESS***
+            This change may cause problems with accurate line number reporting
+            as well as error reporting more generally. I have tried to resolve this
+            as much as possible, but there might be some corner cases.
+
+01/12/2007: mgossage
+            [Lua] Added typemap throws for std::string*, typemap for SWIGTYPE DYNAMIC,
+	    changed the existing throws typemap to throw a string instead of making a copy of
+	    the object (updating a few test cases to deal with the change).
+	    fixed test case: dynamic_casts, exception_partial_info, li_std_string, size_t
+
+01/03/2007: beazley
+            [Internals].  Use of swigkeys.c/.h variables is revoked.  Please use
+            simple strings for attribute names.
+
+12/30/2006: beazley
+            Internal API functions HashGetAttr() and HashCheckAttr() have been revoked.
+            Please use Getattr() to retrieve attributes.  The function Checkattr() can
+            be used to check attributes.  Note:  These functions have been revoked
+            because they only added a marginal performance improvement at the expense
+            code clarity.
+
+12/26/2006: mgossage
+            [Lua] Added more STL (more exceptions, map, size_t),
+	    fixed test case: conversion_ns_template.
+
+12/21/2006: mgossage
+            [Lua] Update to throw errors when setting immutables,
+	    and allowing user addition of module variables.
+
+12/20/2006: wsfulton
+            Fix typedef'd variable wrappers that use %naturalvar, eg, std::string.
+
+12/14/2006: wsfulton
+            [C#] Add std::wstring and wchar_t typemaps
+
+12/14/2006: olly
+	    [php] Fix bug #1613673 (bad PHP5 code generated for getters and
+	    setters).
+
+12/02/2006: wsfulton, John Lenz, Dave Beazley
+            Move from cvs to Subversion for source control
+
+11/30/2006: beazley
+            Cleaned up swigwarnings.swg file not to use nested macro
+            definitions.
+
+11/12/2006: wsfulton
+            [Java, C#] Fix for %extend to work for static member variables.
+
+Version 1.3.31 (November 20, 2006)
+==================================
+
+11/12/2006: Luigi Ballabio
+            [Python] Alternate fix for Python exceptions bug #1578346 (the previous one broke Python
+            properties in modern classes)
+
+11/12/2006: wsfulton
+            -fakeversion commandline option now generates the fake version into the generated wrappers
+            as well as displaying it when the -version commandline option is used.
+
+14/11/2006: mgossage
+	    [lua] update to typemap for object by value, to make it c89 compliant
+
+Version 1.3.30 (November 13, 2006)
+=================================
+
+11/12/2006: wsfulton
+            [java] Remove DetachCurrentThread patch from  08/11/2006 - it causes segfaults
+            on some systems.
+
+11/12/2006: wsfulton
+            [python] Fix #1578346 - Python exceptions with -modern
+
+11/10/2006: wsfulton
+            Fix #1593291 - Smart pointers and inheriting from templates 
+
+11/09/2006: wsfulton
+            Fix director operator pointer/reference casts - #1592173.
+
+11/07/2006: wsfulton
+            Add $self special variable for %extend methods. Please use this instead of just 'self'
+            as the C++ 'this' pointer.
+
+11/07/2006: mutandiz
+	    [allegrocl] 
+	    allegrocl.swg: swig-defvar updated to allow specifying of
+	    		   non-default foreign type (via :ftype keyword arg).
+	    allegrocl.cxx: Specify proper access type for enum values.
+
+11/03/2006: wsfulton
+            [Java/C#] Fix const std::string& return types for directors as reported by
+            Mark Donselzmann
+
+10/29/2006: wsfulton
+            [Java] Remove DeleteLocalRef from end of director methods for now as it is causing a
+            seg fault when run on Solaris 8.
+
+10/29/2006: wuzzeb (John Lenz)
+	    [Guile] Patch from Chris Shoemaker to clean up some warnings in the generated code.
+
+10/29/2006: wsfulton
+            [Java] Important fix to prevent early garbage collection of the Java proxy class
+            while it is being used in a native method. The finalizer could destroy the underlying
+            C++ object while it was being used. The problem occurs when the proxy class is no
+            longer strongly reachable after a native call.  The problem seems to occur in
+            memory stress situations on some JVMs. It does not seem to occur on the
+            Sun client JVM up to jdk 1.5. However the 1.6 client jdk has a more aggressive garbage
+            collector and so the problem does occur. It does occur on the Sun server
+            JVMs (certainly 1.4 onwards). The fix entails passing the proxy class into the native
+            method in addition to the C++ pointer in the long parameter, as Java classes are not
+            collected when they are passed into JNI methods. The extra parameter can be suppressed
+            by setting the nopgcpp attribute in the jtype typemap to "1" or using the new -nopgcpp
+            commandline option.
+
+            See Java.html#java_pgcpp for further details on this topic.
+
+10/24/2006: wsfulton
+            [C#] Fix smart pointer wrappers. The virtual/override/new keyword is not generated
+            for each method as the smart pointer class does not mirror the underlying pointer
+            class inheritance hierarchy. SF #1496535
+
+10/24/2006: mgossage
+            [lua] added support for native methods & member function pointers.
+            fixed test cases arrays_dimensionless & cpp_basic. Added new example (functor).
+            tidied up a little of the code (around classHandler).
+
+10/17/2006: wsfulton
+            [C#, Java] directorout typemap changes to fall in line with the other director
+            languages. $result is now used where $1 used to be used. Please change your typemaps
+            if you have a custom directorout typemap.
+
+10/18/2006: wsfulton
+            Some fixes for applying the char array typemaps to unsigned char arrays.
+
+10/17/2006: wsfulton
+            [C#, Java] Add in const size_t& and const std::size_t& typemaps.
+
+10/15/2006: efuzzyone 
+            [CFFI] Suppress generating defctype for enums, thanks to Arthur Smyles. Patch 1560983. 
+
+10/14/2006: wuzzeb (John Lenz)
+            [Chicken] Minor fix to make SWIG work with the (as yet unreleased) chicken 2.5
+
+            [Guile,Chicken] Fix SF Bug 1573892.  Added an ext_test to the test suite to test
+            this bug, but this test can not really be made generic because the external code must
+            plug into the target language interpreter directly.
+            See Examples/test-suite/chicken/ext_test.i and ext_test_external.cxx
+
+            Added a %.externaltest to common.mk, and any interested language modules can
+            copy and slightly modify either the chicken or the guile ext_test.i
+
+10/14/2006: mgossage
+            [Lua] added OUTPUT& for all number types, added a long long type
+            fixed several test cases.
+            update: changed typemaps to use SWIG_ConvertPtr rather than SWIG_MustGetPointer
+            started spliting lua.swg into smaller parts to make it neater
+
+10/13/2006: wsfulton
+            [C#, Java] Marginally better support for multiple inheritance only in that you can
+            control what the base class is. This is done using the new 'replace' attribute in the 
+            javabase/csbase typemap, eg in the following, 'Me' will be the base class,
+            no matter what Foo is really derived from in the C++ layer.
+
+              %typemap(javabase, replace="1") Foo "Me";
+              %typemap(csbase, replace="1") Foo "Me";
+
+            Previously it was not possible for the javabase/csbase typemaps to override the C++ base.
+
+10/12/2006: wsfulton
+            [Java] Remove potential race condition on the proxy class' delete() method 
+            (it is now a synchronized method, but is now customisable by changing the 
+            methodmodifiers attribute in the the javadestruct or javadestruct_derived typemap)
+
+            [C#] Remove potential race condition on the proxy class' Dispose() method, 
+            similar to Java's delete() above.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+10/12/2006: wsfulton
+            [Ruby, Python] Remove redundant director code in %extend methods (%extend
+            methods cannot be director methods)
+
+10/12/2006: wsfulton
+            [Ruby, Python] Fix #1505594 - director objects not returned as director objects
+            in %extend methods.
+
+10/11/2006: wsfulton
+            [Java] Fix #1238798 - Directors using unsigned long long or any other type
+            marshalled across the JNI boundary using a Java class (where the jni typemap 
+            contains jobject).
+
+10/06/2006: wsfulton
+            Fix #1162194 - #include/%include within a structure
+
+10/06/2006: wsfulton
+            Fix #1450661, string truncation in String_seek truncating Java/C# enums.
+
+10/06/2006: mgossage
+            [Lua] Fix #1569587. The name is now correct.
+
+10/04/2006: wsfulton
+            Director fixes for virtual conversion operators
+
+10/04/2006: olly
+	    [php] Fix #1569587 for PHP.  Don't use sizeof() except with string
+	    literals.  Change some "//" comments to "/* */" for portability.
+
+10/04/2006: mgossage
+            [Lua] Partial Fix #1569587. The type is now correct, but the name is still not correct.
+
+10/03/2006: wsfulton
+            [Ruby] Fix #1527885 - Overloaded director virtual methods sometimes produced
+            uncompileable code when used with the director:except feature.
+
+10/03/2006: wsfulton
+            Directors: Directors are output in the order in which they are declared in 
+            the C++ class rather than in some pseudo-random order.
+
+10/03/2006: mmatus
+            Fix #1486281 and #1471039.
+
+10/03/2006: olly
+	    [Perl] Fix for handling strings with zero bytes from Stephen Hutsal.
+
+09/30/2006: efuzzyone
+            [CFFI] Bitfield support and vararg support due to Arthur Smyles.
+            C expression to Lisp conversion, thanks to Arthur Smyles for the initial
+            idea, it now supports conversion for a whole range of C expressions. 
+
+09/28/2006: wsfulton
+            Fix #1508327 - Overloaded methods are hidden when using -fvirtual optimisation.
+            Overloaded methods are no longer candidates for elimination - this mimics
+            C++ behaviour where all overloaded methods must be defined and implemented
+            in a derived class in order for them to be available.
+
+09/25/2006: wsfulton
+            [Ruby, Python, Ocaml] Fix #1505591 Throwing exceptions in extended directors
+
+09/25/2006: wsfulton
+            Fix #1056100 - virtual operators. 
+
+09/24/2006: olly
+	    Don't accidentally create a "<:" token (which is the same as "[" in C++).
+	    Fixes bug # 1521788.
+
+09/23/2006: olly
+	    [Ruby] Support building with recent versions of the Ruby 1.9
+	    development branch.  Fixes bug #1560092.
+
+09/23/2006: olly
+	    Templates can now be instantiated using negative numbers and
+	    constant expressions, e.g.:
+
+	    template<int q> class x {};
+	    %template(x_minus1) x<-1>;
+	    %template(x_1plus2) x<1+2>;
+
+	    Also, constant expressions can now include comparisons (>, <, >=,
+	    <=, !=, ==), modulus (%), and ternary conditionals (a ? b : c).
+
+	    Fixes bugs #646275, #925555, #956282, #994301.
+
+09/22/2006: wsfulton
+            Fix %ignore on director methods - Bugs #1546254, #1543533
+
+09/20/2006: wsfulton
+            Fix %ignore on director constructors
+
+09/20/2006: wsfulton
+            Fix seg faults and asserts when director methods are ignored (#1543533)
+
+09/20/2006: wsfulton
+            Fix out of source builds - bug #1544718
+
+09/20/2006: olly
+	    Treat a nested class definition as a forward declaration rather
+	    than ignoring it completely, so that we generate correct code for
+	    passing opaque pointers to the nested class (fixes SF bug #909387).
+
+09/20/2006: olly
+            *** POTENTIAL INCOMPATIBILITY ***
+	    [php] Overload resolution now works.  However to allow this, SWIG
+	    generated wrappers no longer coerce PHP types (which reverts a change
+	    made in 1.3.26).  So for example, if a method takes a string, you
+	    can no longer pass a number without explicitly converting it to a
+	    string in PHP using: (string)x
+
+09/18/2006: mgossage
+            [ALL] fix on swiginit.swg, has been reported to crash on several test cases
+	    found and fixed problem in imports under python (mingw)
+
+09/16/2006: wsfulton
+            [Python] Patch from Michal Marek for Python 2.5 to fix 64 bit array indexes on
+            64 bit machines.
+
+09/13/2006: wsfulton
+            The explicitcall feature has been scrapped. This feature was introduced primarily
+            to solve recursive director method calls. Director upcall improvements made instead:
+
+            [Python, Ruby, Ocaml] The swig_up flag is no longer used. The required mutexes
+            wrapping this flag are also no longer needed. The recursive calls going from C++
+            to the target language and back again etc are now avoided by a subtlely different
+            approach. Instead of using the swig_up flag in each director method to indicate
+            whether the explicit C++ call to the appropriate base class method or a normal
+            polymorphic C++ call should be made, the new approach makes one of these calls
+            directly from the wrapper method.
+
+            [Java, C#] The recursive call problem when calling a C++ base class method from
+            Java/C# is now fixed. The implementation is slightly different to the other languages
+            as the detection as to whether the explicit call or a normal polymorphic call is made
+            in the Java/C# layer rather than in the C++ layer.
+
+09/11/2006: mgossage
+            [ALL] updated swiginit.swg to allow multiple interpreters to use multiple
+	    swig modules at once. This has been tested in Lua (mingw & linux),
+	    perl5 & python (linux) only.
+
+09/11/2006: mgossage
+            [lua] added support for passing function pointers as well as native lua object
+            into wrappered function.
+            Added example funcptr3 to demonstrate this feature
+
+09/05/2006: olly
+	    [php] Rename ErrorCode and ErrorMsg #define-s to SWIG_ErrorCode
+	    and SWIG_ErrorMsg to avoid clashes with code the user might be
+	    wrapping (patch from Darren Warner in SF bug #1466086).  Any
+	    user typemaps which use ErrorCode and/or ErrorMsg directly will
+	    need adjusting - you can easily fix them to work with both old
+	    and new SWIG by changing to use SWIG_ErrorMsg and adding:
+
+		#ifndef SWIG_ErrorMsg
+		#define SWIG_ErrorMsg() ErrorMsg()
+		#endif
+
+08/29/2006: olly
+	    [php] Move constant initialisation from RINIT to MINIT to fix a
+	    warning when using Apache and mod_php.  We only need to create
+	    PHP constants once when we're first initialised, not for every HTTP
+	    request.
+
+08/21/2006: mgossage
+            [Lua]
+	    Bugfix #1542466 added code to allow mapping Lua nil's <-> C/C++ NULL's
+	    updated various typemaps to work correctly with the changes
+	    added voidtest_runme.lua to show the features working
+
+08/19/2006: wuzzeb (John Lenz)
+	    [Guile] Add feature:constasvar to export constants as variables instead of functions
+            that return the constant value.
+
+08/11/2006: wsfulton
+            [Java] DetachCurrentThread calls have been added so that natively created threads
+            no longer prevent the JVM from exiting. Bug reported by Thomas Dudziak and
+            Paul Noll.
+
+08/10/2006: wsfulton
+            [C#] Fix director protected methods so they work
+
+07/25/2006: mutandiz
+	    [allegrocl]
+	    more additions to std::string, some tweaks and small bug fixes
+	    -nocwrap mode.
+
+07/21/2006: mgossage
+            [Lua]
+	    Bugfix #1526022 pdated std::string to support strings with '\0' inside them
+	    updated typemaps.i to add support for pointer to pointers
+
+07/19/2006: mutandiz
+	    [allegrocl]
+	    - Add std_string.i support.
+	    - Add newobject patch submitted by mkoeppe (thanks!)
+	    - Fix type name mismatch issue for nested type definitions.
+	      specifically typedefs in templated class defns.
+
+07/18/2006: mgossage
+	    Bugfix #1522858
+	    updated lua.cxx to support -external-runtime command
+
+07/14/2006: wuzzeb (John Lenz)
+	    Increment the SWIG_RUNTIME_VERSION to 3, because of the
+	    addition of the owndata member in swig_type_info.
+	    Reported by: Prabhu Ramachandran
+
+07/05/2006: wsfulton
+            Search path fixes:
+            - Fix search path for library files to behave as documented in Library.html.
+            - Fix mingw/msys builds which did not find the SWIG library when installed.
+            - Windows builds also output the mingw/msys install location when running
+              swig -swiglib.
+            - The non-existent and undocumented config directory in the search path has
+              been removed.
+
+07/05/2006: wsfulton
+            Fix $symname special variable expansion.
+
+07/04/2006: wuzzeb (John Lenz)
+	    [Chicken]
+	    Add %feature("constasvar"), which instead of exporting a constant as a
+	    scheme function, exports the constant as a scheme variable.  Update the
+	    documentation as well.
+
+07/04/2006: wsfulton
+            [See entry of 09/13/2006 - explicitcall feature and documentation to it removed]
+            New explicitcall feature which generates additional wrappers for virtual methods
+            that call the method explicitly, not relying on polymorphism to make the method
+            call. The feature is a feature flag and is enabled like any other feature flag.
+            It also recognises an attribute, "suffix" for mangling the feature name, see
+            SWIGPlus.html#SWIGPlus_explicitcall documentation for more details.
+
+            [Java, C#]
+            The explicitcall feature is also a workaround for solving the recursive calls
+            problem when a director method makes a call to a base class method. See
+            Java.html#java_directors_explicitcall for updated documentation.
+
+06/28/2006: joe (Joseph Wang)
+	    [r] Initial support for R
+
+06/20/2006: wuzzeb (John Lenz)
+	    [Chicken]
+            Minor fixes to get apply_strings.i testsuite to pass
+	    Remove integers_runme.scm from the testsuite, because SWIG and Chicken does
+            handle overflows.
+
+06/19/2005: olly
+	    [php] Add support for generating PHP5 class wrappers for C++
+	    classes (use "swig -php5").
+
+06/17/2006: olly
+	    [php] Added some missing keywords to the PHP4 keyword list, and
+	    fixed __LINE__ and __FILE__ which were in the wrong category.
+	    Also added all the keywords new in PHP5, and added comments
+	    noting the PHP4 keywords which aren't keywords in PHP5.
+
+06/17/2006: olly
+	    [php] Don't segfault if PHP Null is passed as this pointer (e.g.
+	    Class_method(Null)) - give a PHP Error instead.
+
+06/15/2006: mutandiz
+	    [allegrocl]
+	    Add initial support for std::list container class.
+	    Fix a few bugs in helper functions.
+
+05/13/2006: wsfulton
+            [Java] Replace JNIEXPORT with SWIGEXPORT, thereby enabling the possibility
+            of using gcc -fvisibility=hidden for potentially smaller faster loading wrappers.
+
+05/13/2006: wsfulton
+            Fix for Makefiles for autoconf-2.60 beta
+
+05/13/2006: wsfulton
+            Vladimir Menshakov patch for compiling wrappers with python-2.5 alpha.
+
+05/12/2006: wsfulton
+            Fix buffer overflow error when using large %feature(docstring) reported
+            by Joseph Winston.
+
+05/12/2006: wsfulton
+            [Perl] Operator overload fix from Daniel Moore.
+
+05/25/2006: mutandiz
+	    [allegrocl]
+	    Fix bug in generation of CLOS type declarations for unions
+	    and equivalent types.
+
+05/24/2006: mutandiz
+	    [allegrocl]
+	    Don't require a full class definition to generate a CLOS wrapper.
+
+05/20/2006: olly
+	    [php] GCC Visibility support now works with PHP.
+
+05/19/2006: olly
+	    [php] Removed support for -dlname (use -module instead).  Fixed
+	    naming of PHP extension module to be consistent with PHP
+	    conventions (no "php_" prefix on Unix; on PHP >= 4.3.0, handle Unix
+	    platforms which use something other than ".so" as the extension.)
+
+05/13/2006: wsfulton
+            [C#] Director support added
+
+05/07/2006: olly
+	    [php] Don't segfault if PHP Null is passed where a C++ reference
+	    is wanted.
+
+05/05/2006: olly
+	    [php] Fix wrappers generated for global 'char' variables to not
+	    include a terminating zero byte in the PHP string.
+
+05/03/2006: wsfulton
+            Modify typemaps so that char * can be applied to unsigned char * or signed char *
+            types and visa versa.
+
+05/03/2006: efuzzyone
+	    [cffi]Thanks to Luke J Crook for this idea.
+             - a struct/enum/union is replaced with :pointer only if
+               that slot is actually a pointer to that type. So,: 
+                    struct a_struct { int x; } and
+                    struct b_struct { a_struct struct_1; }; 
+               will be converted as:
+                   (cffi:defcstruct b_struct
+                           (struct_1 a_struct))
+             - Other minor fixes in lispifying names.
+
+05/02/2006: wsfulton
+            Fix possible redefinition of _CRT_SECURE_NO_DEPRECATE for VC++.
+
+04/14/2006: efuzzyone
+	    [cffi]
+            Thanks to Thomas Weidner for the patch.
+            - when feature export is set (export 'foo) is 
+              generated for every symbol
+            - when feature inline is set (declaim (inline foo)) is 
+              generated before every function definition
+            - when feature intern_function is set 
+              #.(value-of-intern-function "name" "nodeType" package)
+              is emitted instead of the plain symbol. A sample swig-lispify 
+              is provided.
+            - every symbol is prefixed by it's package.
+
+04/13/2006: efuzzyone
+	    [cffi]
+	    Fixed the generation of wrappers for global variables. 
+            Added the option [no]swig-lisp which turns on/off generation 
+            of code for swig helper lisp macro, functions, etc.
+
+Version 1.3.29 (March 21, 2006)
+===============================
+
+04/05/2006: mutandiz
+	    [allegrocl]
+	    Fix output typemap of char so it produces a character instead
+	    of an integer. Also adds input/output typemaps for 'char *'.
+
+	    add command-line argument -isolate to generate an interface
+	    file that won't interfere with other SWIG generated files that
+	    may be used in the same application.
+
+03/20/2005: mutandiz
+	    [allegrocl]
+	    More tweaks to INPUT/OUTPUT typemaps for bool.
+
+	    Fix constantWrapper for char and string literals.
+
+	    find-definition keybindings should work in ELI/SLIME.
+	    Output (in-package <module-name>) to lisp wrapper
+	    instead of (in-package #.*swig-module-name*).
+
+	    slight rework of multiple return values.
+
+	    doc updates.
+
+03/17/2005: mutandiz
+	    [allegrocl]
+	    mangle names of constants generated via constantWrapper.
+	    
+	    When using OUTPUT typemaps and the function has a non-void
+	    return value, it should be first in the values-list, followed
+	    by the OUTPUT mapped values.
+
+	    Fix bug with boolean parameters, which needed to be
+	    passed in as int values, rather than T or NIL.
+
+03/15/2006: mutandiz
+	    [allegrocl]
+	    Generate wrappers for constants when in C++ or -cwrap mode.
+	    Make -cwrap the default, since it is most correct. Users
+	    can use the -nocwrap option to avoid the creation of a .cxx
+	    file when interfacing to C code.
+
+	    When in -nocwrap mode, improve the handling of converting
+ 	    infix literals to prefix notation for lisp. This is very
+	    basic and not likely to be improved upon since this only
+	    applies to the -nocwrap case. Literals we can't figure out
+	    will result in a warning and be included in the generated
+	    code.
+
+	    validIdentifier now more closely approximates what may be
+	    a legal common lisp symbol.
+
+	    Fix typemap error in allegrocl.swg
+	    
+03/12/2006: mutandiz
+	    [allegrocl]
+	    fix up INPUT/OUTPUT typemaps for bool.
+	    Generate c++ style wrapper functions for struct/union members
+	    when -cwrap option specified.
+
+03/10/2006: mutandiz
+	    [allegrocl]
+	    Fix bug in C wrapper generation introduced by last allegrocl
+	    commit.
+
+03/10/2006: wsfulton
+            [Java]
+            Commit #1447337 - Delete LocalRefs at the end of director methods to fix potential leak
+
+03/10/2006: wsfulton
+            Fix #1444949 - configure does not honor --program-prefix.
+            Removed non-standard configure option --with-release-suffix. Fix the autoconf standard
+            options --program-prefix and --program-suffix which were being shown in the help,
+            but were being ignored. Use --program-suffix instead of --with-release-suffix now.
+
+03/10/2006: wsfulton
+            [Java]
+            Fix #1446319 with patch from andreasth - more than one wstring parameter in director methods
+
+03/07/2006: mkoeppe
+	    [Guile] 
+	    Fix for module names containing a "-" in non-"shadow" mode.
+	    Patch from Aaron VanDevender (#1441474).
+
+03/04/2006: mmatus
+	    - Add -O to the main program, which now enables -fastdispatch
+	    
+	    [Python]
+
+	    - Add the -fastinit option to enable faster __init__
+              methods. Setting 'this' as 'self.this.append(this)' in the python
+	      code confuses PyLucene. Now the initialization is done in the
+	      the C++ side, as reported by Andi and Robin.
+
+	    - Add the -fastquery option to enable faster SWIG_TypeQuery via a
+              python dict cache, as proposed by Andi Vajda
+
+	    - Avoid to call PyObject_GetAttr inside SWIG_Python_GetSwigThis,
+	      since this confuses PyLucene, as reported by Andi Vajda.
+	    
+03/02/2006: wsfulton
+            [Java]
+            Removed extra (void *) cast when casting pointers to and from jlong as this
+            was suppressing gcc's "dereferencing type-punned pointer will break strict-aliasing rules"
+            warning. This warning could be ignored in versions of gcc prior to 4.0, but now the
+            warning is useful as gcc -O2 and higher optimisation levels includes -fstrict-aliasing which
+            generates code that doesn't work with these casts. The assignment is simply never made.
+            Please use -fno-strict-aliasing to both suppress the warning and fix the bad assembly
+            code generated. Note that the warning is only generated by the C compiler, but not
+            the C++ compiler, yet the C++ compiler will also generate broken code. Alternatively use 
+            -Wno-strict-aliasing to suppress the warning for gcc-3.x. The typemaps affected
+            are the "in" and "out" typemaps in java.swg and arrays_java.swg. Users ought to fix
+            their own typemaps to do the same. Note that removal of the void * cast simply prevents
+            suppression of the warning for the C compiler and nothing else. Typical change:
+
+            From:
+              %typemap(in) SWIGTYPE * %{ $1 = *($&1_ltype)(void *)&$input; %}
+            To:
+              %typemap(in) SWIGTYPE * %{ $1 = *($&1_ltype)&$input; %}
+
+            From:
+              %typemap(out) SWIGTYPE * %{ *($&1_ltype)(void *)&$result = $1; %} 
+            To:
+              %typemap(out) SWIGTYPE * %{ *($&1_ltype)&$result = $1; %} 
+
+03/02/2006: mkoeppe
+	    [Guile -scm]
+	    Add typemaps for "long long"; whether the generated code compiles, however, depends
+	    on the version and configuration of Guile.
+
+03/02/2006: wsfulton
+            [C#]
+            Add support for inner exceptions. If any of the delegates are called which construct
+            a pending exception and there is already a pending exception, it will create the new
+            exception with the pending exception as an inner exception.
+
+03/02/2006: wsfulton
+            [Php]
+            Added support for Php5 exceptions if compiling against Php5 (patch from Olly Betts).
+
+03/01/2006: mmatus
+	    Use the GCC visibility attribute in SWIGEXPORT.
+
+	    Now you can compile (with gcc 3.4 or later) using
+	    CFLAGS="-fvisibility=hidden".
+	    
+	    Check the difference for the 'std_containers.i' python 
+	    test case:
+ 
+            Sizes:
+
+	      3305432 _std_containers.so
+	      2383992 _std_containers.so.hidden
+
+	    Exported symbols (nm -D <file>.so | wc -l):
+
+              6146 _std_containers.so 
+              174  _std_containers.so.hidden 
+
+	    Excecution times:
+
+	      real 0m0.050s user 0m0.039s sys 0m0.005s   _std_containers.so
+              real 0m0.039s user 0m0.026s sys 0m0.007s   _std_containers.so.hidden
+
+	    Read http://gcc.gnu.org/wiki/Visibility for more details.
+
+
+02/27/2006: mutandiz
+	    [allegrocl]
+	    Add support for INPUT, OUTPUT, and INOUT typemaps.
+	    For OUTPUT variables, the lisp wrapper returns multiple
+	    values.
+
+02/26/2006: mmatus
+
+	    [Ruby] add argcargv.i library file.
+	    
+	    Use it as follow:
+
+		%include argcargv.i
+	      									 
+   	        %apply (int ARGC, char **ARGV) { (size_t argc, const char **argv) } 
+	      									 
+   	        %inline {				
+   	          int mainApp(size_t argc, const char **argv) 	
+   	          {						
+   	            return argc;					
+   	          }
+                }							
+	      							
+   	    then in the ruby side:					
+	      								
+   	        args = ["asdf", "asdf2"]				
+   	        n = mainApp(args);
+	
+
+	    This is the similar to the python version Lib/python/argcargv.i
+
+02/24/2006: mgossage
+
+	    Small update Lua documents on troubleshooting problems
+	    
+02/22/2006: mmatus 
+
+	    Fix all the errors reported for 1.3.28.
+	    - fix bug #1158178
+	    - fix bug #1060789
+	    - fix bug #1263457
+	    - fix 'const  char*&' typemap in the UTL, reported by Geoff Hutchison
+	    - fixes for python 2.1 and the runtime library
+	    - fix copyctor + template bug #1432125
+	    - fix [ 1432152 ] %rename friend operators in namespace
+	    - fix gcc warning reported by R. Bernstein
+	    - avoid assert when finding a recursive scope inheritance,
+	      emit a warning in the worst case, reported by Nitro 
+	    - fix premature object deletion reported by Paul in tcl3d
+	    - fix warning reported by Nitro in VC7
+	    - more fixes for old Solaris compiler
+	    - fix for python 2.3 and gc_refs issue reported by Luigi
+	    - fix fastproxy for methods using kwargs
+	    - fix overload + protected member issue reported by Colin McDonald
+	    - fix seterrormsg as reported by Colin McDonald
+	    - fix directors, now the test-suite runs again using -directors
+	    - fix for friend operator and Visual studio and bug 1432152
+	    - fix bug #1435090
+	    - fix using + %extend as reported by William
+	    - fix bug #1094964
+	    - fix for Py_NotImplemented as reported by Olly and Amaury
+	    - fix nested namespace issue reported by Charlie
+
+	    and also:
+	    
+	    - allow director protected members by default
+	    - delete extra new lines in swigmacros[UTL]
+	    - cosmetic for generated python code
+	    - add the factory.i library for UTL
+	    - add swigregister proxy method and move __repr__ to a
+	      single global module  [python]
+
+02/22/2006: mmatus 
+
+	    When using directors, now swig will emit all the virtual
+	    protected methods by default. 
+
+	    In previous releases, you needed to use the 'dirprot'
+	    option to acheive the same.
+
+	    If you want, you can disable the new default behaviour,
+	    use the 'nodirprot' option: 
+
+	       swig -nodirprot ...
+
+	    and/or the %nodirector feature for specific methods, i.e.:
+
+	       %nodirector Foo::bar;
+
+	       struct Foo {
+	         virtual ~Foo();
+
+	       protected:
+	         virtual void bar();
+	       };
+	    
+
+	    As before, pure abstract protected members are allways
+	    emitted, independent of the 'dirprot/nodirprot' options.
+
+
+02/22/2006: mmatus
+	    Add the factory.i library for languages using the UTL (python,tcl,ruby,perl).
+	    
+            factory.i implements a more natural wrap for factory methods. 
+
+	    For example, if you have:							    
+	    								    
+  	    ----  geometry.h --------					    
+  	         struct Geometry {                          		    
+  	           enum GeomType{			     			    
+  	             POINT,				     		    
+  	             CIRCLE				     		    
+  	           };					     		    
+  	           					     		    
+  	           virtual ~Geometry() {}    		     		    
+  	           virtual int draw() = 0;				    
+  	    	 							    
+  	    	 //							    
+  	    	 // Factory method for all the Geometry objects		    
+  	    	 //							    
+  	           static Geometry *create(GeomType i);     		    
+  	         };					     		    
+  	         					     			    
+  	         struct Point : Geometry  {		     		    
+  	           int draw() { return 1; }		     		    
+  	           double width() { return 1.0; }    	     		    
+  	         };					     		    
+  	         					     			    
+  	         struct Circle : Geometry  {		     		    
+  	           int draw() { return 2; }		     		    
+  	           double radius() { return 1.5; }          		    
+  	         }; 					     		    
+  	         								    
+  	         //							    
+  	         // Factory method for all the Geometry objects		    
+  	         //							    
+  	         Geometry *Geometry::create(GeomType type) {		    
+  	           switch (type) {			     		    
+  	           case POINT: return new Point();	     		    
+  	           case CIRCLE: return new Circle(); 	     		    
+  	           default: return 0;			     		    
+  	           }					     		    
+  	         }					    		    
+  	    ----  geometry.h --------					    
+	    								    
+	    								    
+	    You can use the %factory with the Geometry::create method as follows:
+	    								    
+  	      %newobject Geometry::create;				    
+  	      %factory(Geometry *Geometry::create, Point, Circle);	    
+  	      %include "geometry.h"					    
+	    								    
+  	    and Geometry::create will return a 'Point' or 'Circle' instance   
+  	    instead of the plain 'Geometry' type. For example, in python:	    
+	    								    
+  	      circle = Geometry.create(Geometry.CIRCLE)			    
+  	      r = circle.radius()						    
+	    								    
+  	    where 'circle' now is a Circle proxy instance.	    		    
+
+
+02/17/2006: mkoeppe
+	    [MzScheme] Typemaps for all integral types now accept the full range of integral
+	    values, and they signal an error when a value outside the valid range is passed.
+	    [Guile] Typemaps for all integral types now signal an error when a value outside
+	    the valid range is passed.
+
+02/13/2006: mgossage
+            [Documents] updated the extending documents to give a skeleton swigging code
+            with a few typemaps.
+            [Lua] added an extra typemap for void* [in], so a function which requires a void*
+            can take any kind of pointer
+
+Version 1.3.28 (February 12, 2006)
+==================================
+
+02/11/2006: mmatus
+	    Fix many issues with line counting and error reports.
+
+02/11/2006: mmatus
+	    [Python] Better static data member support, if you have
+	    
+                struct Foo {
+                  static int bar;
+                };
+
+            then now is valid to access the static data member, ie:
+
+                f = Foo()
+                f.bar = 3
+
+	    just as in C++.
+
+
+02/11/2006: wsfulton
+            [Perl]
+            Fixed code generation to work again with old versions of Perl
+            (5.004 and later tested)
+
+02/04/2006: mmatus
+	    [Python] Add the %extend_smart_pointer() directive to extend
+	    SWIG smart pointer support in python. 
+
+	    For example, if you have a smart pointer as:
+	    
+	      template <class Type> class RCPtr {
+	      public:
+	        ...
+	        RCPtr(Type *p);
+		Type * operator->() const;
+		...
+	      };
+	      
+	    you use the %extend_smart_pointer directive as:
+	    
+	      %extend_smart_pointer(RCPtr<A>);
+	      %template(RCPtr_A)  RCPtr<A>;
+	    
+	    then, if you have something like:
+
+	      RCPtr<A> make_ptr();
+	      int foo(A *);
+
+	    you can do the following:
+
+	      a = make_ptr();
+	      b = foo(a);
+
+            ie, swig will accept a RCPtr<A> object where a 'A *' is
+            expected.
+
+	    Also, when using vectors
+	    
+	      %extend_smart_pointer(RCPtr<A>);
+	      %template(RCPtr_A) RCPtr<A>;
+	      %template(vector_A) std::vector<RCPtr<A> >;
+		
+	    you can type
+
+	      a = A();
+	      v = vector_A(2)
+	      v[0] = a
+
+            ie, an 'A *' object is accepted, via implicit conversion, 
+	    where a RCPtr<A> object is expected. Additionally
+
+	      x = v[0]
+
+	    returns (and sets 'x' as) a copy of v[0], making reference
+	    counting possible and consistent.
+
+	    %extend_smart_pointer is just a collections of new/old
+	    tricks, including %typemaps and the new %implicitconv
+	    directive.
+
+02/02/2006: mgossage
+            bugfix #1356577, changed double=>lua_number in a few places.
+            added the std::pair wrapping
+
+01/30/2006: wsfulton
+            std::string and std::wstring member variables and global variables now use
+            %naturalvar by default, meaning they will now be wrapped as expected in all languages.
+            Previously these were wrapped as a pointer rather than a target language string.
+            It is no longer necessary to add the following workaround to wrap these as strings:
+
+		%apply const std::string & { std::string *}
+
+            *** POTENTIAL INCOMPATIBILITY  ***
+
+01/28/2006: mkoeppe
+	    [Guile -scm] 
+	    Add typemaps for handling of member function pointers.
+
+01/24/2006: mmatus
+	    - Better support for the %naturalvar directive, now it
+	      works with the scripting languages as well as
+	      Java/C#.
+	      
+	      Now, it can also be applied to class types:
+
+	        %naturalvar std::string;
+	        %include <std_string.i>
+	      
+              that will tell swig to use the the 'natural' wrapping
+              mechanism to all std::string global and member
+              variables.
+
+	    - Add support for the %allowexcept feature along the
+              scripting languages, which allows the %exception feature
+              to be applied to the variable access methods. Also, add
+              the %exceptionvar directive to specify a distintic
+              exception mechanism only for variables.
+	      
+	    
+	    - Add more docs for the %delobject directive to mark a method as a
+	      destructor, 'disowning' the first argument. For example:
+
+	        %newobject create_foo;
+	        %delobject destroy_foo;
+
+	        Foo *create_foo() { return new Foo(); }
+	        void destroy_foo(Foo *foo) { delete foo; }
+
+	      or in a member method as:
+
+	        %delobject Foo::destroy;
+
+	        class Foo {
+	        public:
+	          void destroy() { delete this;}
+
+	        private:
+	          ~Foo();
+               };
+
+
+01/24/2006: mgossage
+            [Lua]
+	    - Removed the type swig_lua_command_info & replace with luaL_reg
+	      (which then broke the code), fixed this
+	    - added an additional cast in the typemaps for enum's
+	      due to the issue that VC.Net will not allow casting of
+	      a double to an enum directly. Therefore cast to int then to enum
+	      (thanks to Jason Rego for this observation)
+
+01/16/2006: mmatus (Change disabled... will be back in CVS soon)
+	    Add initial support for regexp via the external library
+	    RxSpencer. SWIG doesn't require this library to compile
+	    and/or run. But if you specify --with-rxspencer, and the
+	    library is found during installation, then swig will use
+	    it in three places:
+
+	    - In %renames rules, via the new rxsmatch rules, for example:
+	    	  
+	    	  %rename("%(lowercase)",rxsmatch$name="GSL_.*") "";
+	    	  %rename("%(lowercase)",rxsmatch$nodeType="enum GSL_.*") "";
+	    	 
+              rxsmatch is similar to the match rule, it just uses
+              the RxSpencer regexp library to decide if there is a
+              match with the provided regexp. As with the match
+              rule, you can also use the negate rule notrxsmatch.
+
+	    - In the %rename target name via the rxstarget option, for example:
+	    		 
+	    	  %rename("%(lowercase)",rxstarget=1) "GSL_.*";
+
+	    	where the target name "GSL.*" is now understood as a
+	    	regexp to be matched.  
+	    	 
+            - In the new encoder "rxspencer", which looks like:
+
+	    	  %(rxspencer:[regexp][replace])s
+
+	    	where "regexp" is the regular expression and "replace"
+	    	is a string used as a replacement, where the @0,@1,...,@9
+	    	pseudo arguments are used to represent the
+	    	corresponding matching items in the reg expression.
+
+	    	For example:
+	    		      
+	        %(rxspencer:[GSL.*][@0])s       <- Hello    -> 
+	        %(rxspencer:[GSL.*][@0])s       <- GSLHello -> GSLHello
+	        %(rxspencer:[GSL(.*)][@1])s     <- GSLHello -> Hello
+	        %(rxspencer:[GSL(.*)][gsl@1])s  <- GSLHello -> gslHello
+
+	    	Another example could be:
+
+                %rename("%(lowercase)s",sourcefmt="%(rxspencer:[GSL_(.*)][@1])s",%$isfunction) "";
+
+	    	which take out the prefix "GSL_" and returns all the
+	    	function names in lower cases, as following:
+
+	    	    void GSL_Hello();   ->   hello();
+	    	    void GSL_Hi();      ->   hi();
+	    	    const int GSL_MAX;  ->   GSL_MAX;  // no change, is not a function
+	
+	    We use the RxSpencer as an initial test bed to
+            implemention while we decide which library will be
+            finally added to swig.
+
+            You can obtain the RxSpencer library from 
+	    
+	      http://arglist.com/regex (Unix)
+
+	    or
+	     
+	      http://gnuwin32.sourceforge.net/packages.html (Windows)
+
+	    Once installed, use "man rxspencer" to get more info
+	    about the regexp format, or just google rxspencer.
+
+	    Since now you can enable the rxsmatch rules (see above),
+            the simple or '|' support for the match rules
+            (01/12/2006: mmatus) is disabled. Still, if you have
+            problems with the rxspencer library, you can re-enable
+            the simple 'match or' support using
+            -DSWIG_USE_SIMPLE_MATCHOR.
+	  
+
+01/16/2006: mmatus
+	    Change the %rename predicates to use the prefix '%$', as in:
+	    
+	      %rename("%(utitle)s",%$isfunction,%$ismember) ""; 
+	   	
+            to avoid clashings with other swig macros/directives.
+
+01/14/2006: cfisavage
+            [Ruby]
+	    Added support for Ruby bang! methods via a new %bang feature.
+	    Bang methods end in exclamation points and indicate that the
+	    object being processed will be modified in-place as 
+	    opposed to being copied.
+
+01/12/2006: cfisavage
+            [Ruby]
+	    Updated the Ruby module to automatically convert
+	    method names to lower_case_with_underscores using the
+	    new %rename functionality.
+
+01/12/2006: mmatus
+	    - Add aliases for 'case' encoders used with %rename/%namewarn
+
+	      %(uppercase)s   hello_world -> HELLO_WORLD
+	      %(lowercase)s   HelloWorld  -> helloworld
+	      %(camelcase)s   hello_world -> HelloWorld
+	      %(undercase)s   HelloWorld  -> hello_world
+
+
+01/12/2006: mmatus
+	    - Add the -dump_parse_module and -dump_parse_top options,
+	    which are similar to -dump_module and -dump_top, but they
+	    dump the node trees just after parsing, showing only the 
+	    attributes visible at the parsing stage, and not the added
+	    later in typemap.cxx, allocate.cxx, lang.cxx or elsewhere.
+	    
+	    Besides debugging porpuses, these options are very useful
+	    if you plan to use %rename in an "advance way", since it
+	    shows only and all the node's attributes you can use
+	    inside the match rules.
+
+
+01/12/2006: mmatus
+	    - Add predicates to %rename, so, you don't need to
+	      remember, for example, how to match a member function.
+
+	      Now it is easy, for example to use the 'utitle' encoder 
+	      in all the member methods, you type:
+
+	        %rename("%(utitle)s",%isfunction,%ismember) "";
+
+	      or to ignore all the enumitems in a given class:
+
+	        %rename("$ignore", %isenumitem, %classname="MyClass") "";  
+
+	      Available predicates are (see swig.swg):
+
+                %isenum         
+		%isenumitem     
+		%isaccess       
+		%isclass        
+		%isextend       
+		%isextend       
+		%isconstructor  
+		%isdestructor   
+		%isnamespace    
+		%istemplate     
+		%isconstant     
+					
+		%isunion        
+		%isfunction     
+		%isvariable     
+		%isimmutable    
+					
+		%isstatic       
+		%isfriend       
+		%istypedef      
+		%isvirtual      
+		%isexplicit     
+		%isextern       
+					
+		%ismember       
+		%isglobal 
+		%innamespace
+
+		%ispublic    
+		%isprotected 
+		%isprivate   
+				     
+		%classname   
+
+              These predicates correspond to specific 'match'
+              declarations, which sometimes are not as evident as the
+              predicates names.
+
+
+            - Add the or '|' operation in %rename match, for
+              example to capitalize all the constants (%constant or
+              const cdecl):
+
+                 %rename("%(upper)s",match="cdecl|constant",%isimmutable) "";
+                
+
+
+01/12/2006: mgossage
+	    -	Partial fixed of errors under C89, bug #1356574
+	    	(converted C++ style comments to C style)
+	    -	Added patches from neomantra@users.sf.net #1379988 and #1388343
+	    	missing a 'return' statement for error conditions
+	    	also updated the %init block bug #1356586
+		 
+01/10/2006: mmatus
+	    - Add the 'utitle' encoder, as an example of how to add
+	      your own encoder. I added the encoder method in misc.c 
+	      but developers can add others, the same way, inside any
+	      target language.
+	      
+	      Well, 'utitle' is the reverse of 'ctitle', ie:
+
+	         %rename("%(ctitle)s") camel_case;  -> CamelCase;
+	         %rename("%(utitle)s") CamelCase;   -> camel_case;
+		 
+
+01/10/2006: cfisavage
+            [Ruby]
+            Updated Ruby Exception handling.  Classes that are specified in throws clauses, 
+            or are marked as %exceptionclass, are now inherited from rb_eRuntimeError. 
+            This allows instances of these classes to be returned to Ruby as exceptions. 
+            Thus if a C++ method throws an instance of MyException, the calling Ruby 
+            method will get back a MyException object.  To see an example, 
+            look at ruby/examples/exception_class.
+
+01/10/2006: mmatus
+	    
+            - Add the %catches directive, which complements the %exception
+	    directive in a more automatic way. For example, if you have
+
+                int foo() throw(E1);
+
+            swig generates the proper try/catch code to dispatch E1.
+	    
+	    But if you have:
+
+
+	          int barfoo(int i) {
+                    if (i == 1) {
+	               throw E1();
+                    } else {
+	              throw E2();
+                    }
+                    return 0;
+                  }
+
+            ie, where there is no explicit exception specification in the decl, you 
+	    end up doing:
+		  
+               %exception barfoo {			
+	         try {				
+	           $action			
+	         } catch(E1) {	... }				  
+	         } catch(E2) {	... }				  
+	       }				
+	    
+	    which is very tedious. Well, the %catches directive defines
+	    the list of exceptions to catch, and from swig:
+ 	
+	       %catches(E1,E2) barfoo(int i);
+	       int barfoo(int i);
+
+            is equivalent to 
+
+	       int barfoo(int i) throw(E1,E2);
+
+	    Note, however, that the %catches list doesn't have to
+	    correspond to the C++ exception specification. For example, if you
+	    have:
+
+		struct E {};
+		struct E1 : E {};
+		struct E2 : E {};
+
+  	        int barfoo(int i) throw(E1,E2);
+
+            you can define
+	        
+		%catches(E) barfoo(int i);
+	
+	    and swig will generate an action code equivalent to
+
+	         try {				
+	           $action			
+	         } catch(E &_e) { 
+		   <raise _e>;
+		 }	
+
+            Of course, you still have to satisfy the C++ restrictions,
+	    and the catches list must be compatible (not the same)
+	    as the original list of types in the exception specification.
+
+	    Also, you can now specify that you want to catch the
+	    unknown exception '...', for example:
+
+	       %catches(E1,E2,...) barfoo(int);
+
+	    In any case, the %catches directive will emit the
+	    code to convert into the target language error/exception
+            using the 'throws' typemap.
+
+	    For the '...' case to work, you need to
+	    write the proper typemap in your target language. In the
+	    UTL, this looks like:
+
+	      %typemap(throws) (...) {
+	        SWIG_exception(SWIG_RuntimeError,"unknown exception");
+              }
+
+01/09/2006: mutandiz
+	    [Allegrocl]
+
+            Fixes a number of SEGVs primarily in the handling of
+            various anonymous types. Found in a pass through the
+            swig test-suite. Still more to do here, but this is a
+            good checkpoint.
+
+            Adds -cwrap and -nocwrap as an allegrocl specific
+            command-line argument. Controls generating of a C
+            wrapper file when wrapping C code. By default only a
+            lisp file is created for C code wrapping.
+
+            Doc updates for the command-line arguments and fixes as
+            pointed out on swig-devel
+
+01/05/2006: wsfulton
+            [Java] Fix unsigned long long and const unsigned long long & typemaps
+            - Bug #1398394  with patch from Dries Decock
+
+01/06/2006: mmatus
+	    Add 'named' warning codes, now in addition to:
+	    
+	      %warnfilter(813);
+	   
+	    you can use
+
+	      %warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE);
+
+	    just use the same code name found in  Source/Include/swigwarn.h 
+	    plus the 'SWIG' prefix.
+
+	    If a developer adds a new warning code, the Lib/swigwarn.swg file
+            will be generated when running the top level make.
+
+01/05/2006: cfisavage
+            [Ruby]
+	    Reimplemented object tracking for Ruby.  The new implementation works
+	    by expanding the swig_class structure for Ruby by adding a trackObjects
+	    field.  This field can be set/unset via %trackobjects as explained
+	    in the Ruby documentation.  The new implementation is more robust
+	    and takes less code to implement.
+		
+01/05/2006: wsfulton
+            Fix for %extend and static const integral types, eg:
+
+              class Foo {
+                public:
+                %extend {
+                    static const int bar = 42;
+                }
+              }; 
+
+12/30/2005: mmatus
+
+	  - Add info for old and new debug options:
+              
+            -dump_top       - Print information of the entire node tree, including system nodes    
+     	    -dump_module    - Print information of the module node tree, avoiding system nodes     
+     	    -dump_classes   - Print information about the classes found in the interface	       
+     	    -dump_typedef   - Print information about the types and typedefs found in the interface
+     	    -dump_tags      - Print information about the tags found in the interface	       
+     	    -debug_typemap  - Print information for debugging typemaps			       
+            -debug_template - Print information for debugging templates			        
+
+	  - Add the fakeversion. If you have a project that uses
+            configure/setup.py, or another automatic building system
+            and requires a specific swig version, let say 1.3.22 
+	    you can use:
+
+	       SWIG_FEATURES="-fakeversion 1.3.22"
+
+	     or
+ 
+               swig -fakeversion 1.3.22
+
+             and then swig -version will report 1.3.22 instead of the
+             current version.
+
+	     Typical use would be
+
+	       SWIG_FEATURES="-fakeversion 1.3.22" ./configure 	     
+
+12/30/2005: mmatus
+
+	  - Add option/format support to %rename and %namewarn.	
+	    Now %namewarn can force renaming, for example:
+
+	      %namewarn("314: import is a keyword",rename="_%s") "import";
+	    
+	    and rename can also support format forms:
+
+	       %rename("swig_%s") import;
+
+	    Now, since the format is processed via swig Printf, you
+	    can use encoders as follows:
+
+	       %rename("%(title)s")  import;     -> Import
+	       %rename("%(upper)s")  import;     -> IMPORT
+	       %rename("%(lower)s")  Import;     -> import
+	       %rename("%(ctitle)s") camel_case; -> CamelCase
+	       
+	    This will allow us to add more encoders, as the 
+	    expected one for regular expressions. 
+
+	  - Add the above 'ctitle' encoder, which does the camel case:
+
+	        camel_case -> CamelCase
+  
+	  - Also, while we get the regexp support, add the 'command' encoder,
+            you can use it as follows
+
+               %rename("%(command:sed -e 's/\([a-z]\)/\U\\1/' <<< )s") import; 
+
+	    then swig will popen the command
+	    
+		"sed -e 's/\([a-z]\)/\U\\1/' <<< import"
+		
+            see below for anonymous renames for better examples.		
+
+          - The rename directive now also allows:
+
+	    - simple match: only apply the rename if a type match
+	      happen, for example
+
+		 %rename(%(title)s,match="enumitem") hello;
+
+		 enum Hello {
+		   hi, hello  ->  hi, Hello  
+		 };
+		 int hello()  ->  hello; 
+
+	    - extended match: only apply the rename if the 'extended attribute' match
+	      occurred, for example: 
+
+	         // same as simple match 		
+		 %rename(%(title)s,match$nodeType="enumitem") hello; 
+
+		 enum Hello {
+		   hi, hello  ->  hi, Hello  
+		 };
+
+	       Note that the symbol '$' is used to define the attribute name in
+	       a 'recursive' way, for example:
+
+		 // match only hello in 'enum Hello'
+		 %rename(%(title)s,match$parentNode$type="enum Hello") hello; 
+
+		 enum Hello {
+ 		   hi, hello  ->  hi, Hello   // match
+		 };
+
+		 enum Hi {
+ 		   hi, hello  ->  hi, hello   // no match
+		 };
+
+               here, for Hello::hi, the "parentNode" is "Hello", and its "type"
+               is "enum Hello".
+	       
+	       
+            - Anonymous renames: you can use 'anonymous' rename directives, for example: 
+
+	         // rename all the enum items in Hello
+		 %rename(%(title)s,match$parentNode$type="enum Hello") ""; 
+
+		 enum Hello {
+ 		   hi, hello  ->  Hi, Hello   // match both
+		 };
+
+		 enum Hi {
+ 		   hi, hello  ->  hi, hello   // no match
+		 };
+		 
+	         // rename all the enum items 
+		 %rename(%(title)s,match$nodeType="enumitem") ""; 
+
+	         // rename all the items in given command (sloooow, but...)
+		 %rename(%(command:<my external cmd>)s) ""; 
+
+	
+	      Anonymous renames with commands can be very powerful, since you
+	      can 'outsource' all the renaming mechanism (or part of it) to an
+	      external program:
+	      
+	        // Uppercase all (and only) the names that start with 'i'
+	        %rename("%(command:awk '/^i/{print toupper($1)}' <<<)s") "";   
+	       
+	        int imported() -> IMPORTED;
+	        int hello()    -> hello
+
+	      Note that if the 'command' encoder returns an empty string, swig
+	      understands that no rename is necessary.
+
+	      Also note that %rename 'passes' the matched name. For example, in
+	      this case
+
+	        namespace ns1 {
+		  int foo();
+		}
+
+	        namespace ns2 {
+		  int bar();
+		}
+
+	      the external program only receives "foo" and "bar". If needed,
+	      however, you can request the 'fullname' 
+	       	
+	        %rename("%(command:awk 'awk '/ns1::/{l=split($1,a,"::"); print toupper(a[l])}'' <<<)s",fullname=1) "";   
+                
+		ns1::foo -> FOO
+		ns2::bar -> bar	
+	
+	    - Mixing encoders and matching: of course, you can do mix commands
+	      and match fields, for example:
+
+	        %rename("%(<my encoder for fncs>)",match="cdecl") "";
+	        %rename("%(<my encoder for enums>)",match="enumitem") "";
+	        %rename("%(<my encoder for enums inside a class>)",match="enumitem",
+		        match$parentNode$parentNode$nodeType="class") "";
+		
+	      Use "swig -dump_parse_module" to see the attribute names you can use to
+	      match a specific case.
+	
+            - 'sourcefmt' and 'targetfmt': sometimes you need to
+              process the 'source' name before comparing, for example
+
+	        %namewarn("314: empty is a keyword",sourcefmt="%(lower)s") "empty";
+
+	      then if you have
+
+	        int Empty();  // "Empty" is the source 
+		
+	      you will get the keyword warning since 'Empty' will be
+	      lower cased, via the sourcefmt="%(lower)s" option,
+	      before been compared to the 'target' "empty".
+
+	      There is an additional 'targetfmt' option to process the
+	      'target' before comparing.
+
+	    - complementing 'match': you can use 'notmatch', for example
+	      
+	        %namewarn("314: empty is a keyword",sourcefmt="%(lower)s",notmatch="namespace") "empty";
+
+	      here, the name warning will be applied to all the symbols except namespaces.
+	    
+      	
+12/30/2005: mmatus
+
+	  - Add initial support for gcj and Java -> <target language> mechanism.
+
+	    See	examples in:  
+	  
+		Examples/python/java
+		Examples/ruby/java
+		Examples/tcl/java
+
+            to see how to use gcj+swig to export java classes into
+            python/ruby/tcl.
+	    
+	    The idea is to put all the common code for gcj inside
+
+	          Lib/gcj
+
+            and localize specific types such as jstring, as can be found
+            in
+
+	         Lib/python/jstring.i
+	         Lib/ruby/jstring.i
+	         Lib/tcl/jstring.i
+
+            Using the UTL, this is very easy, and the perl version for
+            jstring.i will be next.
+		 	    
+
+12/29/2005: mmatus
+	  - Add the copyctor feature/directive/option to enable the automatic
+	    generation of copy constructors. Use as in:
+
+	      %copyctor A;
+
+	      struct A {
+
+              };
+
+	    then this will work
+
+	      a1 = A();
+	      a2 = A(a1);
+
+	    Also, since it is a feature, if you just type
+
+	      %copyctor;
+
+	    that will  enable the automatic generation for all the
+	    classes. It is also equivalent to
+
+	       swig -copyctor -c++ ...
+
+	    Notes: 
+
+	    1.- The feature only works in C++ mode.
+
+	    2.- The automatic creation of the copy constructor will
+	        usually produce overloading. Hence, if the target
+	        language doesn't support overloading, a special name
+	        will be used (A_copy).
+	    
+	    3.- For the overloading reasons above, it is probably not
+                a good idea to use the flag when, for example, you are
+		using keywords in Python.
+
+            4.- The copyctor automatic mechanism follows more or less
+	        the same rules as the default constructor mechanism,
+	        i.e., a copy constructor will not be added if the
+	        class is abstract or if there is a pertinent non-public 
+		copy ctor in the class or its hierarchy.
+
+		Hence, it might be necessary for you to complete the
+		class declaration with the proper non-public copy ctor
+		to avoid a wrong constructor addition.
+		
+          - Fix features/rename for templates ctor/dtor and other
+            things around while adding the copyctor mechanism.
+	    
+
+12/27/2005: mmatus
+	  - Add the 'match' option to typemaps. Assume you have:
+
+	      %typemap(in) SWIGTYPE * (int res) {..}
+	      %typemap(freearg) SWIGTYPE * { if (res$argnum) ...}
+
+	    then if you do
+ 
+	      %typemap(in) A * {...}
+
+	    swig will 'overload the 'in' typemap, but the 'freearg' 
+	    typemap will be also applied, even when this is wrong. The old
+	    solutions is to write:
+
+	      %typemap(in) A * {...}
+  	      %typemap(freeag) A * "";
+
+	    overload 'freearg' with an empty definition.
+
+	    The problem is, however, there is no way to know you need
+	    to do that until you start getting broken C++ code, or
+	    worse, broken runtime code.
+
+	    The same applies to the infamous 'typecheck' typemap,
+	    which always confuses people, since the first thing you do
+	    is to just write the 'in' typemap.
+
+	    The 'match' option solves the problem, and if instead you write:
+
+	      %typemap(in) SWIGTYPE * (int res) {..}
+	      %typemap(freearg,match="in") SWIGTYPE * { if (res$argnum) ...}
+	      %typemap(typecheck,match="in",precedence...) SWIGTYPE * {...}
+	    
+	    it will tell swig to apply the 'freearg/typecheck'
+	    typemaps only if they 'match' the type of the 'in'
+	    typemap. The same can be done with other typemaps as:
+
+	      %typemap(directorout) SWIGTYPE * {...}
+	      %typemap(directorfree,match="directorout") SWIGTYPE * {...}
+	    
+
+12/27/2005: mmatus
+	  - Add the 'naturalvar' option/mode/feature to treat member
+	    variables in a more natural way, ie, similar to the global
+	    variable behavior.
+
+	    You can use it in a global way via the command line
+
+	      swig -naturalvar ...
+
+	    or the module mode option
+ 
+	      %module(naturalvar=1)
+
+	    both forms make swig treat all the member variables in the
+	    same way it treats global variables. 
+
+	    Also, you can use it in a case by case approach for
+	    specific member variables using the directive form:
+
+	      %naturalvar Bar::s;
+	    
+	    Then, in the following case for example:
+
+	       std::string s;
+	       struct Bar {
+		 std::string s;
+               };
+
+            you can do:  
+
+	       b = Bar()
+	       b.s ="hello"
+	       cvar.s = "hello"
+	       
+	       if (b.s != cvar.s):
+	          raise RuntimeError
+
+		  
+            This is valid for all the languages, and the
+            implementation is based on forcing the use of the 
+            const SWIGTYPE& (C++)/SWIGTYPE (C) typemaps for the
+            get/set methods instead of the SWIGTYPE * typemaps.
+	    Hence, for 'naturalvar' to work, each target language
+	    must implement 'typemap(in/out) const Type&' properly.
+
+	    The 'naturalvar' option replaces or makes workarounds such  as:
+	    
+		%apply const std::string & { std::string *}
+
+            unnecessary.
+
+	    Note1: If your interface has other kinds of workarounds to
+	    deal with the old 'unnatural' way to deal with member
+	    variables (returning/expecting pointers), the
+	    'naturalvar' option could break them.
+	    
+	    Note2: the option has no effect on unnamed types, such
+	    as unnamed nested unions.
+	    
+	  
+12/27/2005: mmatus
+	  - Add more 'expressive' result states for the typemap
+            libraries.
+
+	    In the past, for scripting languages, you would do checking something like:
+
+	      if (ConvertPtr(obj,&vptr,ty,flags) != -1) {
+	        // success
+              } else {
+	        // error
+	      }
+
+	    Now the result state can carry more information,
+	    including:
+
+	      - Error state: like the old -1/0, but with error codes from swigerrors.swg.
+
+	         int res = ConvertPtr(obj,&vptr,ty,flags);
+		 if (SWIG_IsOK(res)) {
+		   // success code
+                 } else {
+		   SWIG_Error(res); // res carries the error code
+                 }
+
+	      - Cast rank: when returning a simple successful
+                conversion, you just return SWIG_OK, but if you need
+                to do a 'cast', you can add the casting rank, ie:
+		
+		  if (PyFloat_Check(obj)) {
+		    value = PyFloat_AsDouble(obj);
+		    return SWIG_OK;
+		  } else if (PyInt_Check(obj)) {
+		    value = (double) PyInt_AsLong(obj);
+		    return SWIG_AddCast(SWIG_OK);		    
+                  }
+		
+		later, the casting rank is used to properly dispatch
+		the overloaded function, for example. This of course
+		requires your language to support and use the new
+		dispatch cast/rank mechanism (Now mainly supported in
+		perl and python, and easily expandable to ruby and tcl).
+	      
+	  - [UTL] Add support for the new 'expressive' result states.
+
+12/27/2005: mmatus
+	  - Add support for the C++ implicit conversion mechanism, which
+            required some modifications in parser.y (to recognize
+            'explicit') and overload.cxx (to replace $implicitconv as
+            needed).
+	    
+	    Still, real support in each target language requires each
+	    target language to be modified. Python provides an example,
+            see below.
+
+
+	  - Add support for native C++ implicit conversions, ie, if you
+            have
+
+	        %implicitconv A;
+
+	        struct A {
+		   int ii;
+		   A() {ii = 1;}
+		   A(int) {ii = 2;}
+		   A(double) {ii = 3;}
+		   explicit A(char *s) {ii = 4;}
+		};
+		
+		int get(const A& a) {return a.ii;}
+
+            you can call:
+
+	        a = A()
+	        ai = A(1)
+	        ad = A(1.0)
+	        as = A("hello")
+		
+		# old forms
+	        get(a)  -> 1
+	        get(ai) -> 2
+	        get(ad) -> 3
+	        get(as) -> 4
+		
+		#implicit conversions
+	        get(1)       -> 2
+	        get(1.0)     -> 3
+	        get("hello") -> Error, explicit constructor
+
+            Also, as in C++, now implicit conversions are supported in
+            variable assigments, and if you have:
+
+	      A ga;
+	      struct Bar {
+	        A a;
+              };
+
+	    you can do:
+
+	      cvar.ga = A(1)
+	      cvar.ga = 1
+	      cvar.ga = 1.0
+	      cvar.ga = A("hello") 
+	      cvar.ga = "hello" -> error, explicit constructor
+
+	      b = Bar()
+	      b.a = A("hello")
+	      b.a = 1
+	      b.a = 1.0
+	      b.a = "hello" -> error, explicit constructor
+
+	    Note that the last case, assigning a member var directly, 
+	    also requires the 'naturalvar' option.
+
+	    This support now makes the old '%implicit' macro, which
+	    was found in 'implicit.i' and it was fragile in many ways,
+	    obsolete, and you should use the new '%implicitconv'
+	    directive instead.
+
+	    Note that we follow the C++ conventions, ie, in the
+	    following the implicit conversion is allowed:
+
+		int get(A a) {return a.ii;}
+		int get(const A& a) {return a.ii;}
+	    
+	    but not in these cases:
+
+		int get(A *a) {return a->ii;}
+		int get(A& a) {return a.ii;}
+		
+	    Also, it works for director methods that return a by value
+	    result, ie, the following will work:
+
+                virtual A get_a() = 0;
+
+		def get_a(self):
+		   return 1
+
+            but not in this case:
+
+                virtual const A& get_a() = 0;
+                virtual A& get_a() = 0;
+                virtual A* get_a() = 0;
+	    
+	  Notes:
+
+	  - the implicitconv mechanism is implemented by directly
+	    calling/dispatching the python constructor, triggering a
+	    call to the __init__method. Hence, if you expanded the
+	    __init__ method, like in:
+
+	        class A:
+		   def __init__(self,args):
+		      <swig code>
+		      <my code here>
+
+            then 'my code' will also be executed.
+	    
+	  - Since the %implicitconv directive is a SWIG feature, if you type:
+	    
+  	       %implicitconv;  
+
+	    that will enable implicit conversion for all the classes in
+	    your module.
+
+	    But if you are worried about performance, maybe that will be
+	    too much, especially if you have overloaded methods, since
+	    to resolve the dispatching problem, python will efectively
+	    try to call all the implicit constructors as needed.
+
+	  - For the same reason, it is highly recommended that you use
+            the new 'castmode' when mixing implicit conversion and
+            overloading.
+
+	 - [python] The %implicit directive is declared obsolete, and
+           you should use %implicitconv instead. If you include
+	   the implicit.i file, a warning will remind you of this.
+
+	   Note: Since %implicit is fragile, just replacing it by
+	   %implicitconv could lead to different behavior. Hence, we
+	   don't automatically switch from to the other, and the user
+	   must migrate to the new %implicitconv directive manually.
+
+
+12/26/2005: wsfulton
+            [C#]
+            Modify std::vector wrappers to use std::vector::value_type as this is
+            closer to the real STL declarations for some methods, eg for push_back().
+            Fixes some compilation errors for some compilers eg when the templated
+            type is a pointer.
+
+            [Java]
+            std::vector improvements - a few more methods are wrapped and specializations are
+            no longer required. The specialize_std_vector macro is no longer needed (a
+            warning is issued if an attempt is made to use it).
+
+12/26/2005: wsfulton
+            [Java, C#]
+            Add in pointer reference typemaps. This also enables one to easily wrap
+            std::vector<T> where T is a pointer.
+
+12/24/2005: efuzzyone
+            [CFFI] The cffi module for SWIG:
+              - Fully supports C, but provides limited supports for C++, in
+               particular C++ support for templates and overloading needs to
+               be worked upon. 
+
+12/23/2005: mmatus
+	    [python] Add the castmode that allows the python
+	    type casting to occur.
+
+	    For example, if you have 'int foo(int)', now
+	    
+	      class Ai():
+	         def __init__(self,x): 
+		    self.x = x
+	         def __int__(self): 
+		    return self.x
+
+	      foo(1)   // Ok
+	      foo(1.0) // Ok
+	      foo(1.3) // Error
+	      a = Ai(4)
+              foo(ai)  // Ok
+
+            The castmode, which can be enabled either with the
+            '-castmode' option or the %module("castmode") option, uses
+            the new cast/rank dispatch mechanism. Hence, now if you
+            have 'int foo(int); int foo(double);', the following works
+            as expected:
+
+	      foo(1)   -> foo(int)
+	      foo(1.0) -> foo(double)
+	      ai = Ai(4)
+	      foo(ai)  -> foo(int)
+
+	    Note1: the 'castmode' could disrupt some specialized
+	    typemaps. In particular, the "implicit.i" library seems to
+	    have problem with the castmode. But besides that one, the
+	    entire test-suite compiles fine with and without the
+	    castmode.
+
+ 	    Note2: the cast mode can't be combined with the fast
+	    dispatch mode, ie, the -fastdispatch option has no effect
+	    when the cast mode is selected. The penalties, however,
+	    are minimum since the cast dispatch code is already based
+	    on the same fast dispatch mechanism.
+
+	    See the file overload_dispatch_cast_runme.py file for
+	    new cases and examples.
+
+12/22/2005: mmatus
+	    Add the cast and rank mechanism to dispatch overloading
+	    functions. The UTF supports it now, but for each language
+	    it must be decided how to implement and/or when to use it.
+
+	    [perl] Now perl uses the new cast and rank dispatch
+	    mechanism, which solves all the past problems known 
+	    in perl, such as the old '+ 1' problem:
+
+	        int foo(int);
+	    
+		$n = 1
+                $n = $n + 1
+                $r = foo(n)
+
+            also works:
+
+                 foo(1);
+                 foo("1");
+                 foo(1.0);
+                 foo("1.0");
+
+             but fails
+
+                 foo("l");
+
+             and when overloading  foo(int) and foo(double);
+
+                 foo(1) -> foo(int)
+                 foo(1.0) -> foo(double)
+                 foo("1") -> foo(int)
+                 foo("1.0") -> foo(double)
+                 foo("l") -> error
+		 foo($n) -> foo(int)  for good perl versions
+		 foo($n) -> foo(double)  for old bad perl versions
+
+	     when overloading foo(int), foo(char*) and foo(double):
+
+                 foo(1) -> foo(int)
+                 foo(1.0) -> foo(double)
+                 foo("1") -> foo(char*)
+                 foo("1.0") -> foo(char*)
+                 foo("l") -> foo(char*)
+
+             Note: In perl the old dispatch mechanism was broken,
+             so, we don't provide an option to enable the old one
+	     since, again, it was really really broken.
+
+	     See 'overload_simple_runme.pl' for more cases and tests.
+
+	     PS: all the old known issues are declared resolved, any
+	     new "problem" that could be discovered is declared, 
+	     a priori, as "features" of the new dispatch mechanism
+	     (until we find another solution at least).
+	     
+	     
+            *** POTENTIAL INCOMPATIBILITY  ***
+
+	    As with the introduction of the UTF, some things could
+	    now start to work as expected, and people used to deal or
+	    workaround previous bugs related to the dispatch
+	    mechanism, could see now a difference in perl behavior.
+
+12/21/2005: mmatus
+	  - The '-nodefault' flag (pragma and feature) now generates
+	    a warning, and recommends to use the explicit
+	    -nodefaultctor and  -nodefaultdtor options.
+	    
+	    The reason to split the 'nodefault' behavior is that, in
+	    general, ignoring the default destructor generates memory
+	    leaks in the target language. Hence, is too risky just to
+	    disable both the default constructor and destructor
+	    at the same time.
+
+	    If you need to disable the default destructor, it is
+	    also recommended you use the directive form:
+
+	       %nodefaultdtor  MyVerySpecialClass;
+
+            for specific classes, and always avoid using the global
+            -nodefault and -nodefaultdtor options.
+	    
+12/21/2005: wsfulton
+            [Java, C#]
+            Fix incorrect code generation when the intermediary classname is changed
+            in the module directive from its default. For example:
+
+              %module(jniclassname="myimclassnewname") "mymodule" // Java
+              %module(imclassname="myimclassnewname") "mymodule" // C#
+
+            Add in new special variable $imclassname. See docs.
+
+12/17/2005: mmatus
+	  [Python]
+	  - Add the -aliasobj0/-noaliasobj0 options to use with
+	    -fastunpack and/or -O and old typemaps that use 'obj0'
+	    directly.
+
+	    So, if you compile your code using -O and get errors about
+	    the undeclared 'obj0' variable, run again using 
+
+		swig -O -aliasobj0 -python ....
+	    
+	    For new typemaps, never use 'obj0' directly, if needed,
+	    use the '$self' name that will be properly  expanded to
+	    'obj0' (nofastunpack) or 'swig_obj[0]' (fastunpack). 
+  
+	    If you have no idea what I am talking about, better, that
+	    means you have no typemap with this problem.
+
+
+12/14/2005: mmatus 	 
+	  [Python]
+	  - Add the -fastunpack/-nofastunpack options to enable/disable
+	    the use of the internal UnpackTuple method, instead of
+	    calling the one from the python C API.
+
+	    The option -O now also implies -fastunpack.
+	    
+
+12/11/2005: mmatus 
+	  [Python]
+	  - Add the -proxydel/-noproxydel options to enable/disable
+	    the generation of proxy/shadow __del__ methods, even
+	    when now they are redundant, since they are empty.
+	    However, old interfaces could rely on calling them.
+
+	    The default behavior is to generate the __del__ methods
+	    as in 1.3.27 or older swig versions.
+
+	    The option -O now also implies -noproxydel.
+
+12/10/2005: mmatus 
+	  [UTF]
+          - Fix unneccessary calls to SWIG_TypeQuery for 'char *'
+	    and 'wchar_t *', problem found by Clay Culver while
+	    profiling the PyOgre project.
+
+	  
+	  [Python] 
+	  - Add the -dirvtable/-nodirvtable to enable/disable
+	    a pseudo virtual table used for directors, avoiding
+	    the need to resolve the python method at each call.
+	    
+	  - Add the -safecstrings/-nosafecstrings options to
+	    enable/disable the use of safe conversions from PyString
+	    to char *. Python requires you to never change the internal
+	    buffer directly, and hence 'safectrings' warranties that
+	    but returning a copy of the internal python string buffer.
+
+	    The default, as in previous releases, is to return a
+	    pointer to the buffer (nosafecstrings), so, it is the user's
+	    responsibility to avoid its modification.
+	    
+	  - Add the -O option to enable all the optimization options
+	    at once, initially equivalent to
+
+	    -modern -fastdispatch -dirvtable -nosafecstrings -fvirtual
+
+12/08/2005: mmatus 
+
+	  - Add the -fastdispatch option (fastdispatch feature). This
+	    enables the "fast dispatch" mechanism for overloaded
+	    methods provided by Salvador Fandi~no Garc'ia (#930586).
+
+	    The resulting code is smaller and faster since less type
+	    checking is performed. However, the error messages you
+	    get when the overloading is not resolved could be
+	    different from what the traditional method returns.
+
+	    With the old method you always get an error such as 
+
+	       "No matching function for overloaded ..."
+
+            with the new method you can also get errors such as
+
+	       "Type error in argument 1 of type ..."
+
+	    See bug report #930586 for more details.
+            
+  	    So, this optimization must be explicitly enabled by users.
+
+	    The new mechanism can be used as:
+
+              swig -fastdispatch
+
+            or using the feature form
+
+	      %feature("fastdispatch") method;
+            or
+              %fastdispatch method;
+	    
+
+12/06/2005: mmatus 
+
+          - Several memory and speed improvements, specially for
+	    templates. Now swig is up to 20 faster than before for
+	    large template interfaces, such as the std_containers.i
+	    and template_matrix.i files in the python test-suite.
+
+	    Memory footprint is also reduced in consideration of small
+	    pcs/architectures.
+
+	  - add commandline options -cpperraswarn and -nocpperraswarn" to force
+            the swig preprocessor to treat the #error directive as a #warning.
+	    
+	    the pragmas
+
+               #pragma SWIG cpperraswarn=1
+               #pragma SWIG cpperraswarn=0
+	       
+	    are equivalent to the command line options, respectively.
+             
+
+12/06/2005: mmatus
+	    [Python] The generated code is now more portable, especially
+	    for Windows. Following 
+
+                 http://www.python.org/doc/faq/windows.html
+
+            Py_None is never accessed as a structure, plus other
+            tricks mentioned there.
+
+12/06/2005: mmatus
+	    [Python] Added initial support for threads based in the
+	    proposal by Joseph Winston.
+
+	    The user interface is as follows:
+
+	    1.- the module thread support is enable via the "threads" module
+                option, i.e.
+
+                  %module("threads"=1)
+
+            2.- Equivalent to that, is the new '-threads' swig option
+
+                  swig -threads -python ...
+
+            3.- You can partially disable thread support for a given
+                method using:
+
+                  %feature("nothread") method;
+                or
+		  %nothread method;
+
+                also, you can disable sections of the thread support, 
+                for example
+
+                  %feature("nothreadblock") method;
+                or
+		  %nothreadblock method;
+
+                  %feature("nothreadallow") method;
+                or
+		  %nothreadallow method;
+
+                the first disables the C++/python thread protection, and the
+                second disables the python/C++ thread protection. 
+
+            4.- The current thread support is based in the PyGIL
+                extension present in python version 2.3 or later, but
+                you can provide the thread code for older versions by
+                defining the macros in pythreads.swg.
+
+		If you get a working implementation for older versions,
+		please send us a patch.
+
+            For the curious about performance, here are some numbers
+            for the profiletest.i test, which is used to check the speed
+	    of the wrapped code:
+
+	        nothread           9.6s  (no thread code)
+		nothreadblock     12.2s  (only 'allow' code)
+		nothreadallow     13.6s  (only 'block' code)
+                full thread       15.5s  ('allow' + 'block' code)
+	    
+	    i.e., full thread code decreases the wrapping performance by
+	    around 60%. If that is important to your application, you
+	    can tune each method using the different 'nothread',
+	    'nothreadblock' or 'nothreadallow' features as
+	    needed. Note that for some methods deactivating the
+	    'thread block' or 'thread allow' code is not an option,
+	    so, be careful.
+	    
+
+11/26/2005: wsfulton
+            SWIG library files use system angle brackets everywhere for %include, eg
+              %include "std_common.i"
+            becomes
+              %include <std_common.i>
+
+11/26/2005: wsfulton
+            [Java, C#]
+            Typesafe enums and proper enums have an extra constructor so that enum item values that
+            are initialised by another enum item value can be wrapped without having to use %javaconstvalue/
+            %csconstvalue for when using %javaconst(1)/%csconst(1). Suggestion by
+            Bob Marinier/Douglas Pearson.
+            For example:
+
+              typedef enum
+              {
+                 xyz,
+                 last = xyz
+              } repeat;
+
+11/21/2005: mmatus
+	    [ruby + python]
+
+	    Fixes for directors + pointers. This is an ugly problem without an easy
+	    solution. Before we identified this case as problematic:
+
+	          virtual const MyClass& my_method();
+
+            but it turns out that all the cases where a pointer, array or
+            reference is returned, are problematic, even for 
+	    primitive types (as int, double, char*, etc).
+
+	    To try to fix the issue, a new typemap was added,
+	    'directorfree', which is used to 'free' the resources
+	    allocated during the 'directorout' phase. At the same
+	    time, a primitive garbage collector engine was added to
+	    deal with orphaned addresses, when needed.
+	    
+	    The situation is much better now, but still it is possible to have
+	    memory exhaustation if recursion is used.
+
+	    So, still you need to avoid returning pointers, arrays or
+	    references when using director methods.
+
+	    - Added stdint.i - typemaps for latest C99 integral types found in stdint.h.
+	    
+11/14/2005: wsfulton
+            More types added to windows.i, eg UINT8, WORD, BYTE etc. 
+            Including windows.i will also enable SWIG to parse the __declspec Microsoft
+            extension, eg __declspec(dllimport). Also other Windows calling conventions
+            such as __stdcall.
+
+11/10/2005: wsfulton
+            New library file for Windows - windows.i. This file will contain useful type
+            information for users who include windows.h. Initial support is for the
+            non ISO integral types: __int8, __int16, __int32, __int64 and unsigned versions.
+            The unsigned versions previously could not be parsed by SWIG.  SF #872013.
+
+11/09/2005: wsfulton
+            [Java, C#] Portability warning for files which will overwrite each other on case
+            insensitive file systems such as FAT32/NTFS. This will occur, for example, when two
+            class names are the same barring case. The warning is issued on all platforms and
+            can be suppressed with the usual warning suppression techniques. SF bug #1084507.
+
+11/09/2005: wsfulton
+            ./configure --with-python --with-ruby --with-perl5 etc enable these languages,
+            ie the --with-xxxx options, where no path is specified, work the same as if 
+            the option was not specified at all. Based on patches #1335042 #1329048 #1329047.
+
+11/09/2005: dancy
+
+	    [Allegrocl]
+	    Add C++ support to the Allegrocl module. Further
+	    enhances the C support as well. Some of the
+	    features:
+
+	    - MUCH better generation of foreign types based on
+	    the C/C++ types for use in defining the FFI on
+	    the lisp side. We don't pass everything as a (* :void)
+	    any longer.
+
+	    - Uses typemaps for better control of type conversions
+	    and code generation in the generated lisp and c++ wrapper
+	    code.
+
+	    - CLOS wrapping of pointers returned from foreign space
+	    makes it easier to differentiate pointers in user code.
+	    The wrapping objects can be passed directly to FF calls.
+
+	    - Defun wrapping of FF calls, allowing for more lispy
+	    interface. Conversion, GCing, of lisp objects to 
+	    foreign objects can be done in the wrapping defun via
+	    the use of typemaps.
+	    
+	    - overload dispatching implemented on the lisp side
+	    using generic functions.
+
+	    - Templates and synonymous types supported.
+
+11/07/2005: mmatus
+
+	    [Python] Adding proper support for multi-inheritance in
+	    the python side, ie, if you have two C++ wrapped class, Foo
+	    and Bar, now:
+
+	       class MyPythonClass(Foo,Bar):
+	          ....
+
+            will properly work, even with directors, and the
+            deallocation of Foo.this and Bar.this will follow
+            correctly. Before, a class could only have one 'this'
+            instance (unlike C++), only the last base class was
+            properly deleted, or detected with directors.
+
+	    Now 'self.this' can be a list, which will contain the C++
+	    instance pointers for all the base classes.
+	    
+	    Also, swig.this is responsible for deallocating the C++
+	    instance(s), and the __del__ method is not emitted unless
+	    the user preppend/append some code to it.
+
+	  - Swig can now detect memory leaks, ie, if you still
+	    don't use proxy/shadow classes, and type something like
+	    
+	         import _example
+	         f = _example.new_Foo()
+
+	    and forget to call _example.delete_Foo(f), then swig will
+	    tell you that there is a memory leak.
+
+	    Otherwise, if you always use the proxy classes, you probably
+	    you will never ever see this warning unless there is
+	    something wrong inside the swig wrapping code.
+	       
+	
+            *** POTENTIAL INCOMPATIBILITY ***
+	    
+	    If you overloaded the __del__ method, and call the base
+	    one	 without a try block, as in
+
+	           class MyClass(SwigClass):
+
+	              def __del__(self):
+		          <your code here>
+		          SwigClass.__del__(self)
+			  
+            python could complain that the method SwigClass.__del__ is
+            undefined. Try to use instead:
+	    
+	              def __del__(self):
+		          <your code here>
+		          try: SwigClass.__del__(self)
+			  except: pass
+
+	    or simply 		  
+
+	              def __del__(self):
+		          <your code here>
+
+11/02/2005: mmatus
+
+	    [Python] Adding more fun to STL/STD containers, now you
+	    can do
+
+	       %template(pyset) std::set<PyObject *>;		
+	       %template(pyvector) std::vector<PyObject *>;	
+	       %template() std::pair<PyObject *,PyObject *>;	
+	       %template(pyvector) std::map<PyObject *,PyObject *>;
+	       ....
+
+	    The same  applies to std::list, std::deque, std::multiset, etc.
+
+	    Then, at the python side you can do now:
+
+	       # C++ std::vector as native python sequence
+	       v = pyvector([1,"hello",(1,2)])
+	       print v[1]
+	       >> 'hello'
+	       print v[2]
+	       >> (1,2)
+	       					   
+	       # C++ std::set as native python sequence
+	       s = pyset()			   
+	       s.insert((1,2))		   
+	       s.insert(1)			   
+	       s.insert("hello")
+	       sum=()
+	       for i in s:
+	         sum +=(i,)
+	       print sum
+	       >>> (1, 'hello', (1, 2))
+	       				   
+	       # C++ std::map as native python sequence
+	       m = pymap()			   
+	       m["foo"] = "hello"		   
+	       m[1] = (1,2)
+	       pm = {}
+	       for k in m:	    	   
+	         pm[k] = m[k]
+	       print pm
+	       >>> {1: (1, 2), 'foo': 'hello'}
+
+	    ie, the STD/STL containers work as real native python
+	    container, with arbitrary item types and so.
+
+	    But since normal C++ containers do not properly ref/unref
+	    their items, you should use the safer versions:
+	    
+	      %template(pyset) std::set<swig::PyObject_ptr>;
+	      %template(pyvector) std::vector<swig::PyObject_ptr>;
+	      %template() std::pair<swig::PyObject_ptr, swig::PyObject_ptr>;
+	      %template(pyvector) std::map<swig::PyObject_ptr,swig::PyObject_ptr>;
+	      ....
+
+	    where swig::PyObject_ptr is a PyObject * envelope class provided
+	    to safely incref/decref the python object. 
+	    
+	    So, now you can use all the STL/STD containers as native
+	    Python containers. 
+
+	    Note 1: std::map, std::set and the other 'ordered'
+	    containers will properly use PyObject_Compare for sorting,
+	    when needed.
+
+	    Note 2: all the STL/STD containers have a limit size of
+	    SIZE_MAX, ie, you can have manage containers larger than
+	    INT_MAX, the python limit.
+	    
+	      
+11/02/2005: mmatus
+
+	    [Python]
+	    - add 'iterator()' method for all sequences and additionally
+	      'key_iterator()' for maps.
+
+	      'iterator()' will always return the native C++ iterator.
+	      Additionally, in maps, 'key_iterator()' will return a python
+	      iterator using only the map keys.
+	      
+	      In general the sequence method __iter__ will call
+	      'iterator()', returning the native C++ iterator, but in
+	      maps it will call 'key_iterator()', maintaining
+	      backward compatibility.
+
+	      Hence, for std::maps, you can play then with the native
+	      C++ iterator, which value is a (key, value) pair, by
+	      calling map.iterator(), as with map.begin(), map.end(), etc.
+
+	      The difference is that map.iterator() returns a safe
+	      'closed' iterator, while map.begin() and map.end() are
+	      'open' iterators.
+
+	      A 'closed' iterator knows the begin and the end of the
+	      sequence, and it never can seg. fault. An 'open'
+	      iterator, as in C++, can seg. fault at the C++ side.
+
+	         # a closed iterator is safe in the following example.
+		 # the next() method will throw a StopIteration
+	         # exception as needed
+	
+	         i = seq.iterator()
+		 try:
+                      while True:
+		        sum += i.next()
+		 except: pass
+		 
+		 # an open iterator always need to be checked,
+		 # or it will crash at the C++ side
+
+	         current = seq.begin()
+                 end = seq.end()
+		 while (current != end):
+		    sum += current.next()
+	      
+	      
+	    [Python]
+	    - Finally, when we call 
+
+	        f = Foo()
+
+	      the construction is 'one-way'. Before construction  was done
+	      something like
+
+	          Foo() (python) -> _new_Foo() (C++) 
+                  new_Foo() (C++) -> FooPtr() (python) 
+                  FooPtr() (python) -> Foo() (python)
+
+              and returning a pointer was done like
+
+                  NewPointerObj() (C++) -> FooPtr() (python)
+                  FooPtr(python) -> Foo() (python)
+                  		  
+
+	      ie, we when going back and forward between the C++ and
+	      python side.
+
+	      Now since there is no FooPtr the construction process is
+
+	          Foo() (python) -> _new_Foo() (C++)
+                  _new_Foo() (C++) -> NewPointerObj() (C++) (no shadow class)
+
+              and returning a pointer is done
+
+                  NewPointerObj() (C++) (with shadow class) -> NewInstaceObj() (C++)
+
+	      where NewInstanceObj creates a new instance without
+	      calling __init__ and it doesn't go 'back' to python, is
+	      'pure' C API.
+
+	     - With this change, and the other ones in the
+               PySwigObject type, which now carries the thisown and
+               swig_type_info pointer, the generated code should be as
+               fast as boost::Python and/or the other python wrappers
+               based in pure Python/C API calls.
+
+	       As a reference, the profiletest_runme.py example, which
+	       does a simple call function many times, such as this code:
+
+                    import profiletest       
+		                             
+		    a = profiletest.A()      
+		    b = profiletest.B()      
+		    for i in range(0,1000000)
+	              a = b.fn(a)            
+
+
+	       where fn is defined as 'A* B::fn(A *a) {return a;}',
+	       produces  the following times
+
+                               nomodern    modern
+	         swig-1.3.26    19.70s      5.98s
+                 swig-CVS        0.99s      0.98s
+	       
+
+	       Clearly, there is a large improvement for the python
+	       'nomodern' mode. Still, the 'modern' mode is around
+	       6 times faster than before. For the same test, but
+	       using the non-shadow version of the module, we get
+
+	                       _profiletest (non-shadow)
+	         swig-1.3.26     0.80s 
+                 swig-CVS        0.60s 
+
+	       Hence, now for practical purposes, the proxy overhead
+	       is insignificant.
+
+	       Note that the performance numbers we are showing is for
+	       a simple module (two types) and a simple function (one
+	       argument). For real situations, for modules with many
+	       more types and/or functions with many more parameters,
+	       you will see even better results.
+	       
+		  	      
+10/31/2005: mmatus
+	    [Python]
+
+	    - Finally, no more ClassPtr proxy classes. You will see
+	      only a clean Class proxy class in the .py file.
+
+	    - No more 'real' thisown attribute either, the PySwigObject now
+              carries the ownership info.
+
+	      You can also do something like
+
+	          print self.this.own() 
+		  >>> True
+		  
+		  self.this.disown()
+		  self.this.own(0)
+	          print self.this.own() 
+		  >>> False		  
+
+		  self.this.acquire()
+		  self.this.own(1)
+	          print self.this.own() 
+		  >>> True
+
+	      Still the old way,
+	      
+	          print self.thisown
+		  >>> True
+
+		  self.thisown = 0
+	          print self.thisown
+		  >>> False		  
+
+		  self.thisown = 1
+	          print self.thisown
+		  >>> True
+
+              is supported, and python dispatches the proper method
+              calls as needed. 		  
+	       
+
+	    - Support for iterators in STL/STD containers, for example, if you have
+
+                    %template<set_string> std::set<std::string>;
+	          
+               you can use the C++ iterators as:  
+
+                     s = set_string()
+		                     
+		     s.append("c")   
+		     s.append("a")   
+	             s.append("b")
+
+                     b = s.begin()      
+		     e = s.end()        
+		     sum = ""           
+		     while (b != e):    
+                         sum += b.next()        
+                     print sum
+
+                     >>> "abc" 
+
+		advance the iterator as in C++
+
+                     current = s.begin()      
+		     current += 1
+                     print current.value()
+		     >>> "b"
+		     
+		now using the reverse operators
+
+                     b = s.rbegin()      
+		     e = s.rend()        
+		     sum = ""           
+		     while (b != e):    
+                         sum += b.next()        
+                     print sum
+
+                     >>> "cba" 
+
+	        or the 'previous' method
+
+                     b = s.begin()      
+		     e = s.end()        
+		     sum = ""           
+		     while (b != e):    
+                         sum += e.previous()
+                     print sum
+
+                     >>> "cba" 
+
+                or just as in a python fashion
+
+                     for i in s:
+                         sum += i        
+                           
+                Note 1: Iterators in C++ are very powerful, but
+                dangerous too. And in python you can shoot yourself in the foot
+                just like in C++, so, be careful.
+		
+		Note 2: the iterators are 'light', ie, they do not
+		convert sequence elements until you request to do so, via
+		next(), value() or previous(). If you just increment/decrement one
+		no conversion is performed, for example:
+
+                      
+                     b = s.begin()      
+	             b += 1
+                     b.incr()
+                     b.incr(2)
+		     b.decr(2)
+                     b.decr()
+                     b -= 1
+
+		 only the iterator is modified, and not value wrapper
+		 is generated. Other typical C++ operations are also 
+		 available, such as:
+
+		     print s.end() - s.begin()
+		     >>> 3
+		     f = s.begin() + 1
+		     print f.value()
+		     >>> "b"
+		     l = s.end() - 1
+		     print l.value()
+		     >>> "c"
+		 
+		 etc.  Of course, the 'find', 'insert', 'erase', and
+		 so on methods also supports iterators now, ie:
+
+		      i = s.begin()
+		      i += 1
+		      s.erase(i)
+                      for i in s:
+                         sum += i
+		      print sum
+		      >>> "ac"
+		      
+            *** POTENTIAL INCOMPATIBILITY ***
+
+	    There is no more 'thisown' attribute. If you use it, python
+	    will translate the following code as follows:
+
+                if (self.thisown):   ==>   if (self.this.own()):
+		self.thisown = 1     ==>   self.this.own(1)
+                self.thisown = 0     ==>   self.this.own(0)
+
+	    Still, maybe in some unusual cases the translation will not be
+	    100% correct, so if you have a problem, please report it
+	    and/or use the new 'self.this.own()' accessor.
+	    
+	    
+            *** POTENTIAL INCOMPATIBILITY ***
+	    
+	    There is no more ClassPtr classes in the python code. Hence,
+	    if in the past you needed to resort to some kind of trickery
+	    with them, or overcome their presence, it is no longer
+	    required, but the extra code you added could now break
+	    things.
+
+	    If needed, you can use the option -classptr, i.e.,
+
+               swig -classptr -python ...
+
+	    to generate the old ClassPtr classes.
+
+
+10/30/2005: mkoeppe 
+	    [Guile] Make declared and defined linkage of SWIG_init consistent.  
+	    Reported by Steven G. Johnson (SF patch 1315498).
+
+10/26/2005: mmatus
+
+	  - Added the attribute.i file to the global library director.
+	    Now it can be used from other languages that do not use
+	    the unified typemap library as well.
+
+	    So, if you have something like:
+
+	       %include attribute.i
+
+               %attribute(A, int, a, get_a, set_a);
+	       				      	  
+	       struct A			      	  
+	       {    				  
+	         int get_a() const; 		  
+	         void set_a(int aa); 		  
+	       };				  
+
+               %attribute_ref(B, int, c);
+	       				
+	       struct B			
+	       {    			
+	         int& c(); 		
+	       }; 
+
+	    then in the target language the 'A.a' and 'B.c' attributes will
+	    be visible, ie, you can access them as plain variables:
+
+               f   = A()
+               f.a = 3
+               g   = B()
+               g.c = 3 
+           
+	       h   = f.a + g.c
+
+	    and the proper get/set methods will be dispatched. See
+	    attribute.i for more info.
+   
+          - More cleanups around and adding more test-cases. The
+            DISOWN typemap now is tested and working in all the
+            languages that use the unified typemap library, ie, tcl,
+            ruby, perl and python.
+	    
+
+10/25/2005: mmatus
+
+	    - Perl, complete the DISOWN typemap.
+	    
+	    - added the attribute.i file to the unified typemap
+              library (before was only usable from python).
+
+	    - unify the names for the setter and getter methods in
+	      perl,tcl,ruby and python, so, the attribute.i library
+	      can work across them.
+	      
+	    - see the li_attribute.i test-case or the library file
+
+ 	        Lib/typemaps/attribute.swg
+
+              for more info about how to use it.
+
+ 
+	      
+
+10/24/2005: mmatus
+
+	    - Perl now uses the unified typemap library.
+
+	    - Changes in ruby to use the $track option in typemaps.
+
+	    - Changes in the unified typemap library to follow the
+	      convention that all macros that are not used in the
+	      C/C++ side starts with %, such as
+
+	           %delete
+		   %new_array
+
+              etc.
+	      
+	    - Documenting fragments, see fragments.swg.
+
+	    - Cleaner way to use the unified typemap library, include
+	      just <typemaps/swigtypes.swg>.
+
+	      Check some of the supported languages: perl, tcl, ruby,
+	      python.
+
+	      Always start with the head file, such as
+
+	         python/python.swg
+	         tcl/tcl8.swg
+	         ruby/ruby.swg
+	         perl5/perl5.swg
+
+              and the principal file that invokes the unified library, such as
+
+	         python/pytypemaps.swg	    
+	         tcl/tcltypemaps.swg	    
+	         ruby/rubytypemaps.swg	    
+	         perl/perltypemaps.swg	    
+	    
+	      The file that provide the specialization for each
+	      language are the one that provides the basic types:
+
+	         python/pyprimtypes.swg	
+	         ruby/rubyprimtypes.swg	
+	         tcl/tclprimtypes.swg	
+	         perl5/perlprimtypes.swg
+
+	      and the string manipulation:  	 
+	    
+	         python/pystrings.swg	
+	         ruby/rubystrings.swg	
+	         tcl/tclstrings.swg	
+	         perl5/perlstrings.swg
+
+		 
+	      The rest of the files, such as carray.i, are mostly one 
+	      line files that include the proper typemap library
+	      version.
+
+            *** POTENTIAL INCOMPATIBILITY in Perl ***
+
+	    Some missing/wrong typemaps could start working properly,
+	    and change the old expected behavior in Perl.
+
+10/23/2005: wuzzeb
+            Chicken:
+              + pointers to member functions finally work properly
+              + add test of member function pointers to cpp_basic.i
+
+10/20/2005: dancy
+	    [allegrocl] Added C++ support. Large update, many changes. See
+	    newly added Allegro Common Lisp section in lisp.html
+
+10/20/2005: mmatus
+	    Ruby, Tcl, Python:
+
+	    - Uniform way to fail (label fail:), now finally
+	      SWIG_exception works across the three languages and all
+	      the typemaps.
+
+	    - Add proper cleanup code to ruby
+
+	    - More valgrind fixes
+
+	    - Simplify the inline use, it seems a small interface of
+	      20,000 lines (plus many many templates) can break 
+	      gcc -O3 easily.
+
+	    - Finalize the typemaps library. All the old  *.i files
+	      (carray.i, cpointer.i, exception.i) had been implemented
+	      in the new typemaps library.
+	    
+
+10/19/2005: wuzzeb
+	    Update the Runtime Typemap documentation in Typemaps.html
+
+10/18/2005: wuzzeb
+	    Chicken:
+	      - Correctly handle %ignored classes
+              - Correctly convert long, long long, unsigned long, etc
+                to chicken primitives. (Thanks to Felix Winkelmann)
+              - Using argout parameters when the return value was a
+                wrapped pointer caused a memory corruption.  The chicken
+                garbage collector moved a pointer out from under us.
+                This is now fixed by running all the proxy creation
+                functions as continuations after the wrapper function
+                returns.  As part of this, we no longer need the
+                chickenfastproxy flag on output typemaps.
+              - using -proxy and -nocollection together works now
+                Before, it was not exporting the destructor in the proxy
+                wrapper.
+
+10/18/2005: mmatus
+	    
+	    Added the Unified Typemap Library (UTL). It unifies the typemaps for
+
+ 	        python, ruby, tcl
+
+	    and in the process, fixes several problems in each of the three
+	    languages to work in a "canonical" way now established in
+	    the typemap library
+	    
+	       SWIG/Lib/typempas
+
+	    The current status of the unification is that everything
+	    compiles and runs inside the test-suite and examples
+	    directories. And for the first time we have three
+	    languages than pass the primitive_types.i case.
+
+	    Also, we have a uniform way to treat the errors, for example
+	    if you do something like
+
+	      >>> from primitive_types import *
+              >>> print val_uchar(10)
+              10
+	      >>> print val_uchar(1000)
+              Traceback (most recent call last):		      
+	        File "<stdin>", line 1, in ?			    
+	      OverflowError: in argument 1 of type 'unsigned char'
+
+	    you get the same exception in all the three languages.
+	    
+	    And well, many more good things will come from this
+	    unification, for example, proper support of the STL/STD classes
+	    for all the languages, and hopefully, we can keep
+	    adding other languages.
+
+	    The hardest part, writing a common typemap library
+	    that suites the three different languages, is done,
+	    and adding another language should now be easy. 
+
+	    Still the global unification is not complete, the STL/STD 
+	    part is next, and probably as well as adding one or two more
+	    languages.
+
+	    If you are curious, look at the python, ruby and/or tcl
+	    directories to see what is needed to support the new
+	    common typemaps library.  Still, the final way to
+	    integrate a new language could change as we move to
+	    integrate the STD/STL.
+
+            *** POTENTIAL INCOMPATIBILITY in Ruby/Tcl ***
+
+	    Some missing/wrong typemaps could start working properly,
+	    and change the old behavior, specially in ruby and tcl.
+
+Version 1.3.27 (October 15, 2005)
+=================================
+
+10/15/2005: wsfulton
+            [Java] Fix for typesafe enum wrapping so that it is possible to
+            overload a method with 2 different enum types.
+
+10/15/2005: wsfulton
+            Fix for %feature("immutable","0") attempting to generate setters
+            for constants.
+
+            Restored %immutable and %makedefault to clear the feature as it
+            behaved in SWIG-1.3.25 and earlier.
+
+10/14/2005: mmatus
+            Fix bug in anonymous typedef structures which was leading to
+            strange behaviour.
+
+10/13/2005: mmatus
+	    Several minor changes:
+	    
+	    - Improve the wchar_t type support
+	    - Add a warning for when you define the 'in' typemap but
+	      you don't define the 'typecheck' one. Very common mistake.
+	    - Add proper default rule for function pointers, now you
+	      can define a typemap such as:
+
+	      %typemap(in) SWIGTYPE ((*)(ANY)) {...}
+
+	      That will apply to all the pointer to functions. The
+	      rule in C++ also apply to the function 'reference', ie,
+	      in both cases
+
+	        typedef  int (*fptr)(int a);
+	        typedef  int (func)(int a);
+
+	      This was needed since it seems to be 'illegal' in C++ to
+	      do something like:
+
+	         void *ptr = static_cast<void *>(fptr);
+
+	      and probably, as for member functions, it is not
+	      warrantied that the pointer sizes will match.
+
+	    - Add the #error/#warning directives to swig's cpp.
+
+	    - Add the noblock option for typemaps, which is used as
+              follows: supposed you a typemap, like this
+
+	      
+	      %typemap(in,noblock=1) Hello {			   
+	         ....
+              }
+
+	      then the typemap will be inserted without the block
+	      imposed by the brackets, similar to
+
+	       %typemap(in) Hello "...";
+
+	      So, why you don't just use the quote style?, because:
+	      
+	         1.- The quote style doesn't get preprocessed, for example
+	      
+	              %typemap(in) Hello "$1= SWIG_macro($1);";
+	      
+	             here, SWIG_macro doesn't get expanded
+
+                 2.- Inside a quote typemap, you have to use 
+                     quotes carefully
+
+		      %typemap(in) Hello "$1 = \"hello\" ";
+
+		 3.- You can't make emacs and/or other editors
+		     to indent inside a string!. 
+
+
+	      So, why do you want to remove the block?, because an extra
+	      block when not needed (no local variables in it):
+
+	          1.- makes the code harder to read
+                  2.- makes the code larger
+                  3.- or in short, for the same reason we have the quote style.
+
+Version 1.3.26 (October 9, 2005)
+================================
+
+10/08/2005: wsfulton
+            [Php] Added 'throws' typemaps.
+
+10/08/2005: wsfulton
+            Fixes for languages that don't support multiple inheritance. The
+            first non-ignored class in the public base class list is used for inheritance.
+            by the proxy class. Previously, if the first class in the list was ignored, then
+            the proxy class wouldn't have any base classes.
+
+10/07/2005: mmatus
+	     Update more features to follow new convention, including:
+
+	       callback
+	       ref/unref
+	       except
+	    
+	     All of them use not only the feature as a flag, but also
+	     as code value. To deal with those features, we use now
+	     GetFlagAttr, which is similar to GetFlag, but instead or
+	     returning 1 or 0, it returns the attr value, if happens
+	     to be different of "0" of course.
+
+	     Now there are also more uniform directive names for the 
+	     ones based in features, for example, for the old
+	     %newobject directive now we have tree directives defined:
+	     
+
+	     #define %newobject        %feature("new")
+	     #define %nonewobject      %feature("new","0")
+	     #define %clearnewobject   %feature("new","")
+
+	     and so on for all the other feature directives.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+09/30/2005: wsfulton
+            Subtle change to some features. Previously it was not possible to disable many
+            features once they had been enabled. This was for most features that behave as
+            flags. These features now work as follows:
+
+              %feature("name")              // enables the feature
+              %feature("name", "1")         // enables the feature
+              %feature("name", "0")         // disables the feature
+              %feature("name", "")          // clears the feature
+
+            In fact any non-empty value other than "0" will enable the feature (like C boolean logic).
+            Previously "1", "0" or any other non-empty value would enable the feature and it would
+            only be possible to disable the feature by clearing it (assuming there was no global enable).
+
+            The following features are affected:
+
+              allowexcept
+              compactdefaultargs
+              classic                (Python)
+              cs:const               (C#)
+              director
+              exceptionclass         (Python)
+              ignore
+              immutable
+              java:const             (Java)
+              java:downcast          (Java)
+              kwargs
+              modern                 (Python)
+              new
+              noautodoc              (Python)
+              nodefault
+              nodirector
+              noref
+              notabstract
+              nounref
+              novaluewrapper
+              python:maybecall       (Python)
+              python:nondynamic      (Python)
+              modula3:multiretval    (Modula3)
+              predicate              (Ruby)
+              trackobjects           (Ruby)
+              valuewrapper
+
+            It is now possible, for example to ignore all methods/classes in a header file, except for a
+            few targetted methods, for example:
+
+              %feature("ignore");                                // ignore all methods/classes
+              %feature("ignore","0") some_function(int, double); // do not ignore this function
+              %feature("ignore","0") SomeClass;                  // do not ignore this Class
+              %feature("ignore","0") SomeClass::method;          // do not ignore this method
+              %include "bigheader.h"
+
+            Removed %pythondynamic - it never worked properly. Use %pythonnondynamic instead.
+            Removed %feature("nokwargs") - it wasn't fully implemented  - use %feature("kwargs","0") instead.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+09/25/2005: mkoeppe
+	    [Guile] Add "throws" typemaps.
+
+09/24/2005: cfisavage
+            [Ruby] Adds new %trackobjects functionality that maps C++ objects to
+            Ruby objects.  This functionality makes it much easier to implement
+            mark functions for the garbage collector.  For more information
+            refer to the update documentation and examples.
+            
+09/20/2005: wsfulton
+            [Perl] Patch 1116431 from Josh Cherry. Fixes non member functions inadvertently
+            being called instead of member functions.
+
+09/20/2005: wsfulton
+            [Lua] Patch from Mark Gossage to add support for Lua-5.1, std::string,
+            std::vector, std::exception and documentation.
+
+09/14/2005: mmatus
+	    [Python] Add -nocppcast. Now the default behavior is to
+	    always use the cppcast operators. Before that was the case
+	    only when you used the -cppcast option.
+
+            If this seems to break your code... your welcome!, it
+	    means it was broken before, and you never notice. 
+
+	    If you thing the error is due to one of the SWIG typemaps,
+	    send us an example.
+
+	    Use -nocppcast only with very old C++ compilers that
+	    do not support the cppcast operations. 
+
+	    So, here applies:
+
+		This change doesn't break compatibility, it was broken before.
+
+09/13/2005: wsfulton
+            [Java] Fix for director methods when a class is passed by value as a
+            parameter.
+
+09/11/2005: mmatus
+            Adding the module option to the %import directive. Now you
+            can use it as
+
+	        %import(module="BigModule") foo.i
+
+	    where subfile could (or not) define the module name via
+	    the %module directive. The module option take precedence
+	    and it has the same effects than having the directive 
+
+	        %module BigModule  
+
+	    inside the imported file foo.i.
+
+	    You can use the option in mainly two cases:
+
+	    1.- You used the -module option when you generated the
+                module to be imported, and hence the module name in
+                the imported %module directive is not really useful.
+
+	    2.- The module you want to import is very large, and it
+                has several .i/.h files. Then, if you just one to
+                import a class or so from the module, says 'foo', and
+                not the entire module via importing the main
+                BigModule.i file, then you just do:
+
+ 		    %import(module="BigModule") foo.h
+
+   	        or
+		
+ 		    %import(module="BigModule") foo.i
+
+		where foo.i contains the 'foo' declaration and maybe a
+		couple of extra %include directives, as needed.
+
+	    
+09/11/2005: mmatus
+	    Fix bug #1282637, about the -module option not having effect
+	    in places where it was needed.
+
+09/11/2005: wsfulton
+            When wrapping variables, ensure that none of the typemaps used for the
+            set wrappers are used when generating the get wrappers. I doubt this was a
+            problem for any languages except for the recently introduced null attribute
+            in the out typemap (C# only).
+
+09/08/2005: wsfulton
+            More descriptive error messages when files fail to open.
+
+09/06/2005: mmatus 
+
+	    Allow a %define a macro inside another %define macro, for example
+
+	      %define hello(name, Type)
+	      %define name ## a(Type)
+	      %typemap(in) Type "hello;";
+	      %enddef
+	      %enddef
+	      
+	    To learn how to use this new features in your own typemaps library, see
+	    python/cstring.i, python/cwstring.i and python/cwstrbase.i.	    
+
+            [Python] Normalize the cstring.i implementation to use fragments, and add
+            cwstring.i, which implements the same typemaps but for wchar_t strings.
+
+	    [Python] Bug fixed: 1247477, 1245591, 1249878 and others.
+
+08/18/2005: wsfulton
+            [Ruby] Implement support for SWIGTYPE* DISOWN typemap (like in Python) for
+            better control of memory management, eg when adding an object created in Ruby
+            to a C++ container. Patch #1261692 from Charlie Savage.
+
+08/18/2005: wsfulton
+            [Tcl] 64 bit platform fixes for the varargs handling in SWIG_GetArgs. This is an
+            improved fix for bug #1011604 as suggested by Jeremy Lin.
+
+08/18/2005: wsfulton
+            [Tcl] Bug #1240469 - %newobject support for Tcl. Patch from Bob Marinier.
+
+08/16/2005: wsfulton
+            [Perl] Bug #1254494 - Fix for global namespace pollution by perl header files
+            (bool define) prevented STL headers from being used on some systems, eg
+            Windows with Visual Studio.
+
+08/16/2005: wsfulton
+            [Java] Bug #1240937 - Redefinition of __int64 typedef for Intel compilers.
+
+08/15/2005: wsfulton
+            [Xml] Bug #1251832 -  C++ template may generate invalid XML file
+
+08/15/2005: wsfulton
+            [Lua] Support added for Lua. Patch #1242772 from Mark Gossage.
+            It supports most C/C++ features (functions, struct, classes, arrays, pointers,
+            exceptions), as well as lots of documentation and a few test cases & examples.
+
+08/14/2005: wsfulton
+            [Xml] Fix incorrect xml escaping in base class name when base class is a template.
+
+08/13/2005: efuzzyone
+	    [CLISP] Added support for handling enums. Does not adds the return type declaration
+	    to the function definition, if a function returns void.
+
+08/09/2005: mkoeppe
+	    New language module, Common Lisp with UFFI, from Utz-Uwe Haus.
+
+08/09/2005: mkoeppe
+	    Fix the Lisp s-expression output module; it no longer complains about "unknown targets".
+
+07/27/2005: wsfulton
+            Modifications to STL wrappers so that it is possible for a user's %exception directive
+            to be applied to the STL wrapper methods. Previously the following global %exception
+            directive would not be used on the wrapper methods:
+
+                %exception { 
+                  try {
+                    $action
+                  } catch (...) {
+                    // handle uncaught exceptions
+                  }
+                }
+
+            This has been implemented by replacing %exception directives for specific STL wrapper
+            methods with an exception specification declared on the wrapper methods. throws typemaps
+            are now supplied for handling the STL exception specification. These can also be easily
+            overridden, for example the std::out_of_range exception, which is used a lot in the STL
+            wrappers, can be customised easily:
+
+              %include "std_vector.i"
+              %typemap(throws) std::out_of_range {
+                // custom exception handler
+              }
+              %template(VectInt) std::vector<int>;
+
+07/22/2005: efuzzyone
+            [CLISP] The clisp module for SWIG:
+              - It can only handle C, clisp currently does not supports ffi bindings to C++.
+              - It has two options, (a) -extern-all this will generate wrappers for all functions
+        	and variablestions, (b) -generate-typedef this will generate wrappers "def-c-type"
+	        wrappers for typedefs
+	      - Can handle pointers to functions, complex types such as n-dimensional arrays of 
+	 	pointers of depth d
+	      - Generates wrappers for constants as well as variables
+	      - Correctly distinguishes between the declaration of variables in structures and functions
+	      - Creates a defpackage "declaration" with the module name as the package name, the created 
+	    	package exports both functions and variables
+	      - tries to guess when should a pointer variable be declared as c-ptr or c-pointer
+
+07/22/2005: wsfulton
+            [C#] Changes to support C# structs returned by value. The changes required are:
+              - Using an optional 'null' attribute in the out typemap. If this attribute is specified,
+                then it is used for the $null special variable substitution.
+              - The ctype used in the C/C++ wrappers is no longer initialised to 0 on declaration.
+            Both of these changes fix the situations where an attempt was made to assign 0 to the
+            returned struct. Marshalling structs as value types still requires user defined typemaps.
+            See documentation for an example.
+
+07/22/2005: wsfulton
+            [C#, Java] Fix SWIG_exception usage to work with compilers that don't support empty macro
+            arguments. Unfortunately this fix will stop usage of SWIG_exception being used within typemaps
+            that use "" or %{ %} delimiters, but continues to work with typemaps using {} delimiters.
+            Please use the SWIG_CSharpSetPendingExceptionArgument or SWIG_JavaThrowException methods instead
+            as SWIG_exception is really intended as a platform independent macro for the SWIG library writers.
+
+07/16/2005: mkoeppe
+	    [Allegro CL] Use specific foreign types rather than (* :void). 
+	    Use *swig-identifier-converter*.
+
+06/27/2005: wsfulton
+            Functions declared as 'extern' no longer have an additional function declaration added to the 
+            wrapper files. There are some cases where SWIG does not get this right, eg bug #1205859 (extern
+            functions with default arguments declared in a namespace). Also SWIG cannot get non-standard
+            calling conventions correct, eg Windows calling conventions are usually handled like this:
+
+              %{
+              #define DLLIMPORT __declspec(dllimport)
+              #define STDCALL __stdcall
+              %}
+              #define DLLIMPORT
+              #define STDCALL
+              %inline %{
+              DLLIMPORT extern STDCALL void function(int);
+              %}
+
+            SWIG incorrectly generates:
+
+            extern void function(int);
+
+            To which there is no solution as SWIG doesn't handle non-standard calling conventions. The extra
+            'extern' function that SWIG generates is superfluous unless a user has forgotten to add the function
+            declaration into the wrappers.
+
+            The -noextern commandline argument is now redundant and a new commandline argument -addextern can
+            be used to obtain the original behaviour. This shouldn't be necessary unless the header file
+            containing the function declaration was inadvertently not added to the wrappers. To fix this
+            add the function declaration into your wrappers, For example, replace:
+
+              extern void foo(int);
+
+            with:
+
+              %inline %{
+              extern void foo(int);
+              %}
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+06/22/2005: wsfulton
+            [C#, Java, Modula3, Ocaml]
+            The intermediary function names have been changed when wrapping variables to
+            match the other language modules so that %extend for a member variable works
+            uniformly across all language modules, eg:
+
+              %extend ExtendMe {
+                Var;
+              };
+
+              %{
+                void ExtendMe_Var_set(ExtendMe *, double) {...}
+                double ExtendMe_Var_get(ExtendMe *) {...}
+              %}
+
+            The methods implementing the get/set used to be:
+
+              %{
+                void set_ExtendMe_Var(ExtendMe *, double) {...}
+                double get_ExtendMe_Var(ExtendMe *) {...}
+              %}
+
+            This also changes the name of variable wrapper functions when using -noproxy.
+            The original names can be generated with the -oldvarnames commandline option.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+Version 1.3.25 (June 11, 2005)
+==============================
+
+06/11/2006: mkoeppe
+	    [Guile] Fix handling of anonymous-enum variables.
+
+06/10/2005: mkoeppe
+	    [Guile] Fix for function arguments that are passed by
+	    copy-of-value.  Fix for global "const char *" variables.
+	    Fix testcases arrays_dimensionless, arrays_global.
+
+06/08/2005: wsfulton
+            Fix for when a base class defines a symbol as a member variable and a derived class defines
+            the same symbol as a member method.
+
+06/08/2005: wsfulton
+            [C#] More fixes for virtual/new/override modifiers - when a method has protected access 
+            in base and public access in derived class.
+
+06/02/2005: wsfulton
+            Fix #1066363 - Follow convention of release tarball name matching directory name.
+
+06/02/2005: wsfulton
+            [C#, Java] Fix #1211353 - typesafe enums (and Java proper enums) wrappers when enum value
+            is negative.
+
+05/27/2005: wsfulton
+            Modernised and tidied up Windows macros --> SWIGEXPORT, SWIGSTDCALL. They can be overridden
+            by users via -D compiler directives if need be.
+
+05/26/2005: wsfulton
+            %csmethodmodifiers can be applied to variables as well as methods now.
+
+            In addition to the default 'public' modifier that SWIG generates, %csmethodmodifiers will also
+            replace the virtual/new/override modifiers that SWIG thinks is appropriate. This feature is
+            useful for some obscure cases where SWIG might get the modifiers incorrect, for example
+            with multiple inheritance and overriding a method in the base class.
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+05/25/2005: wsfulton
+            Added missing constructors to std::pair wrappers (std_pair.i) for all languages.
+
+05/25/2005: wsfulton
+            [C#] Added std::pair wrappers in std_pair.i
+
+05/25/2005: wsfulton
+            [C#] The C# 'new' and 'override' modifiers will be generated when a C++ class inherits methods
+            via a C++ 'using' declaration.
+
+05/25/2005: wsfulton
+            Fix for exception specifications previously being ignored in classes that inherited methods
+            from 'using' declarations, eg calls to Derived::bar below will convert C++ exceptions into
+            a target language exception/error, like it always has done for Base::Bar.
+
+            class Base {
+              virtual bar() throw (std::string);
+            };
+            class Derived : public Base {
+              using Base::bar;
+            };
+
+05/23/2005: wsfulton
+            Fixes for detecting virtual methods in %extend for the -fvirtual option and C# override and new
+            method modifiers.
+
+05/23/2005: wsfulton
+            [C#] The 'new' modifier is now generated on the proxy method when a method in a derived
+            class is not polymorphic and the same method exists in the derived class (ie it hides
+            the base class' non-virtual method).
+
+05/23/2005: wsfulton
+            [Java, C#] Fixes to detection of covariant return types - when the class hierarchy is more
+            than 2 classes deep.
+
+05/21/2005: wsfulton
+            [Java] std::wstring typemaps moved from std_string.i to std_wstring.i
+
+05/21/2005: wsfulton
+            Fix for crash in DohStrstr, bug #1190921
+
+05/21/2005: wsfulton
+            [TCL] Fix for methods with similar names when showing list of names on error - bug #1191828.
+            Patch from Jeroen Dobbelaere.
+
+05/21/2005: wsfulton
+            [TCL] long long overloading fix - bug #1191835, patch from Jeroen Dobbelaere.
+
+05/21/2005: wsfulton
+            Fix bug #1196755 to remove debug from swigtcl8.swg.
+
+05/19/2005: wsfulton
+            [C# and -fvirtual option] Fix for the override key not being generated in the derived class when a
+            virtual method's return type was a typedef in either the base or derived class. Also ensures the
+            method is eliminated when using the -fvirtual option. For example, Derived.method now has the C#
+            override keyword generated:
+
+              typedef int* IntegerPtr;
+
+              struct Base {
+                virtual IntegerPtr method();
+              };
+
+              struct Derived : Base {
+                int * method() const;
+              };
+
+            [C#] Fix for the override key being incorrectly generated for virtual methods when a base class
+            is ignored with %ignore.
+
+05/13/2005: wsfulton
+            [Java] Fixes to remove "dereferencing type-punned pointer will break strict-aliasing rules"
+            warnings in C wrappers when compiling C code with 'gcc -Wall -fstrict-aliasing'. Patch from
+            Michael Cahill. This modifies many of the casts slightly, for example
+              arg1 = *(DB_ENV **)&jarg1;
+            to
+              arg1 = *(DB_ENV **)(void *)&jarg1;
+
+05/12/2005: wsfulton
+            [C#] Support for C# attributes. C# attributes can be generated:
+            1) On a C/C++ type basis by specifying an inattributes and/or outattributes typemap attribute
+               in the imtype or cstype typemaps (for C# return type or C# parameter type attributes).
+            2) On a wrapped method or variable by specifying a csattributes feature (%feature).
+            3) On a wrapped proxy class or enum by specifying a csattributes typemap.
+
+            Examples are in the C# documentation (CSharp.html).
+
+04/29/2005: wsfulton
+            New configure option to turn off the default maximum compiler warning as
+            they couldn't be removed even when overriding CFLAGS and CXXFLAGS with configure
+            (./configure CFLAGS= CXXFLAGS=). To turn the maximum warnings off, run:  
+
+              ./configure --without-maximum-compile-warnings
+
+04/28/2005: wsfulton
+            Patch from Scott Michel which reworks the Java constructor and finalize/destructor typemaps,
+            for directors to reduce the number of overall Java typemaps. Added the director_take and 
+            director_release typemaps to emulate other modules' __disown__ functionality.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA DIRECTORS ***
+
+04/28/2005: wsfulton
+            [C#] Fixed problems due to the over eager garbage collector. Occasionally the
+            garbage collector would collect a C# proxy class instance while it was being used
+            in unmanaged code if the object was passed as a parameter to a wrapped function.
+            Needless to say this caused havoc as the C# proxy class calls the C++ destructor
+            when it is collected. Proxy classes and type wrapper classes now use a HandleRef,
+            which holds an IntPtr, instead of a plain IntPtr to marshal the C++ pointer to unmanaged
+            code. There doesn't appear to be any performance degradation as a result of this
+            modification.
+
+            The changes are in the proxy and type wrapper classes. The swigCPtr is now of type HandleRef
+            instead of IntPtr and consequently the getCPtr method return type has also changed. The net
+            effect is that any custom written typemaps might have to be modified to suite. Affected users
+            should note that the implementation uses the new 'out' attribute in the imtype typemap as the
+            input type is now a HandleRef and the output type is still an IntPtr.
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+04/28/2005: wsfulton
+            [C#] Support for asymmetric type marshalling added. Sometimes the output type needs to be
+            different to the input type. Support for this comes in the form of a new optional 'out'
+            attribute for the ctype, imtype and cstype typemaps. If this typemap attribute is not
+            specified, then the type used for both input and output is the type specified in the
+            typemap, as has always previously been the case. If this typemap attribute is specified,
+            then the type specified in the attribute is used for output types and the type specified
+            in the typemap itself is used for the input type. An output type is a return value from
+            a wrapped method or wrapped constant and an input type is a parameter in a wrapped method.
+
+            An example shows that char * could be marshalled in different ways, 
+
+              %typemap(imtype, out="IntPtr") char * "string"
+              char * function(char *);
+
+            The output type is thus IntPtr and the input type is string. The resulting intermediary C# code is:
+
+              public static extern IntPtr function(string jarg1);
+
+04/22/2005: mkoeppe (Matthias Koeppe)
+	    [Guile] Fix generation of "define-method" for methods of
+	    classes with a constructor.  Reported by Luigi Ballabio.
+
+04/15/2005: wuzzeb (John Lenz)
+	    [Chicken]
+	    For wrapped functions that return multiple values (using argout),
+	    SWIG CHICKEN now returns them as multiple values instead of as
+	    a list.  They can then be accessed using (call-with-values).
+
+04/14/2005: wuzzeb (John Lenz)
+            [Chicken]
+            + Added a whole bunch of new _runme scripts into the chicken test
+            suite.  Also fix some bugs these new scripts turned up.
+
+            + Added optimization when returning a wrapped proxy class.  Before,
+            a minor garbage collection was invoked every time a function returned.
+
+	    + All the chicken Examples should now run correctly
+
+04/14/2005: wsfulton
+            [C#] More fixes for typemap matching when wrapping variables, in particular
+            std::string, so that std::string variables can be easily marshalled with
+            a C# string property using:
+
+              %include "std_string.i"
+              %apply const std::string & { std::string *variable_name };
+              std::string variable_name;
+
+            (Recall that all class variables are wrapped using pointers)
+
+04/05/2005: wuzzeb (John Lenz)
+	    [Chicken]
+	    + Added Examples/chicken/egg, an example on how to build a chicken
+	      extension library in the form of an egg.  Also updated the
+	      documentation on the different linking options.
+
+	    + chicken test-suite now has support to check SWIG with the -proxy
+	      argument if there exists a _proxy_runme.ss file.
+
+	    + More fixes for overloaded functions and -proxy
+
+03/31/2005: wsfulton
+            Turned on extra template features for all languages which were
+            previously only available to Python.
+
+            This enables typemaps defined within a templated class to be used as
+            expected. Requires %template on the templated class, %template() will
+            also pick up the typemaps. Example:
+
+              template <typename T> struct Foo {
+                ...
+                %typemap(in) Foo "in typemap for Foo<T> "
+                or
+                %typemap(in) Foo<T> "in typemap for Foo<T> "
+              };
+              
+              %template(Foo_i) Foo<int>;
+              %template() Foo<double>;
+              
+            will generate the proper 'in' typemaps wherever Foo<int> and Foo<double>
+            are used.
+
+03/30/2005: mkoeppe (Matthias Koeppe)
+	    [MzScheme] Patch from Hans Oesterholt for supporting MzScheme 30x.
+
+03/29/2005: wuzzeb (John Lenz)
+	    [Chicken]
+	    + Reallow older versions of chicken (1.40 to 1.89) by passing -nocollection
+	      argument to SWIG
+	    + %import now works correctly with tinyclos.  (declare (uses ...)) will be
+	      exported correctly.
+	    + TinyCLOS proxy classes now work correctly with overloaded functions
+	      and constructors.
+
+03/29/2005: wsfulton
+            [Java] Patch from Scott Michel for directorout typemaps. Java directors
+            require the directorout typemaps like the other languages now. The new
+            typemaps provide fixes for methods where the return type is returned
+            by reference (this cannot automatically be made thread safe though).
+
+03/22/2005: wsfulton
+            Enum casting fixes. Visual C++ didn't like the C type casting SWIG produced
+            when wrapping C++ enum references, as reported by Admire Kandawasvika.
+
+03/21/2005: wsfulton
+            [Perl] SF #1124490. Fix Perl macro clashes when using Visual Studio's STL string,
+            so now projects can #include <string>.
+
+03/21/2005: wsfulton
+            Fixed %varargs which got broken with the recent default argument changes.
+            Also works for Java and C# for the first time now.
+
+03/17/2005: wuzzeb (John Lenz)
+            [Chicken] 
+	    + Fix a whole bunch of bugs in the chicken module.  The entire
+              test suite now compiles, with the exception of the tests that require
+	      std_vector.i, std_deque.i, and so on, which chicken does not have yet.
+
+	    + Add support for %exception and %typemap(exceptions).  Exceptions are
+	      thrown with a call to (abort) and can be handled by (handle-exceptions)
+
+03/15/2005: wsfulton
+            [Java] Patch from Scott Michel for directors. Modifications to the typemaps
+            giving users fine control over memory ownership and lifetime of director classes.
+            Director classes no longer live forever by default as they are now collectable
+            by the GC.
+
+03/15/2005: wuzzeb (John Lenz)
+	    [Chicken] Add support for adding finalizers garbage collected objects.
+	    Functions that return new objects should be marked with %newobject and
+	    input arguments which consume (or take ownership) of a pointer should
+	    be marked with the DISOWN typemap.
+
+	    Also add support for correctly checking the number of arguments passed
+	    to a function, and raising an error if the wrong number are passed.
+
+03/14/2005: wuzzeb (John Lenz)
+            Add --without-alllang option to configure.in, which is the same as
+            passing all the --without-python --without-perl5 etc... that Matthias added.
+
+03/09/2005: wsfulton
+            [Php] Memory leak fix for functions returning classes/structs by value.
+
+03/08/2005: wsfulton
+            [Perl] Fix for Perl incorrectly taking memory ownership for return types that
+            are typedefs to a struct/class pointer. Reported by Josh Cherry.
+
+03/07/2005: wsfulton
+            [C#] Various exception changes for the std::vector wrappers. These now more
+            accurately mirror the same exceptions that System.Collections.ArrayList throw.
+
+03/07/2005: wsfulton
+            [C#] Fix undefined behaviour after any of the std::vector methods
+            throw an exception.
+
+03/07/2005: wsfulton
+            [C#] When null is passed for a C++ reference or value parameter, the 
+            exception thrown has been corrected to an ArgumentNullException instead
+            of NullReferenceException as recommended in the .NET Framework documentation.
+
+            The default throws typemaps turn a C++ exception into an ApplicationException,
+            not a SystemException now.
+
+03/07/2005: wsfulton
+            [C#] Numerous changes in C# exception handling have been made over the past
+            few weeks. A summary follows:
+
+            The way in which C++ exceptions are mapped to C# exceptions is quite different.
+            The change is to fix C# exceptions so that the C++ exception stack is correctly
+            unwound as previously C++ exceptions were being thrown across the C PInvoke layer
+            into the managed world.
+
+            New typemap attributes (canthrow and excode) have been introduced to control the
+            mapping of C++ to C# exceptions. Essentially a callback into the unmanaged world
+            is made to set a pending exception. The exception to throw is stored in thread local
+            storage (so the approach is thread-safe). The typemaps are expected to return
+            from unmanaged code as soon as the pending exception is set. Any pending exceptions
+            are checked for and thrown once managed code starts executing. There should
+            be minimal impact on execution speed during normal behaviour. Full details will be
+            documented in CSharp.html.
+
+            The SWIG_CSharpThrowException() function has been removed and replaced with the
+            SWIG_CSharpSetPendingExceptionArgument() and SWIG_CSharpSetPendingException()
+            functions. The original name has been deliberately changed to break old code as
+            the old approach was somewhat flawed. Any user defined exceptions that follow the
+            same pattern as the old approach should also be fixed.
+
+            Numerous new .NET framework exceptions are now available for easy throwing from 
+            unmanaged code. The complete list is: 
+
+              ApplicationException, ArithmeticException, DivideByZeroException, 
+              IndexOutOfRangeException, InvalidOperationException, IOException, 
+              NullReferenceException, OutOfMemoryException, OverflowException, 
+              SystemException, ArgumentException, ArgumentNullException and
+              ArgumentOutOfRangeException.
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+05/05/2005: mmatus
+	    
+	    Fix several memory leaks around. Even when we survive  knowning
+	    swig is a memory leak factory, it was a little out of
+	    control. To run std_containers.i in the python test-suite,
+	    swig was using ~260MB, now it uses 'only' ~40MB, which is
+	    the same ammount that g++ uses, so, is not that bad.
+	    In the process, I found a couple of extra Deletes, which
+	    in some cases could trigger seg. faults and/or
+	    DOH/asserts.
+	    
+	    [python] Better support for directors + exception. More
+	    verbose errors and added an unexpected exception handler.
+
+	    [python] Fix memory leak for the
+
+	    	    std::vector<std::vector<int> > 
+
+	    case,reported by Bo Peng.
+
+	    [python] Fix SwigPyObject compare problem reporte by
+	    Cameron Patrick. 
+
+	    [python] Fix several warnings in the generated code 
+	    for gnu-gcc, Intel and VC7.1  compilers.
+
+
+02/25/2005: wuzzeb (John Lenz)
+	    Update documentation to use CSS and <div> instead of <blockquote>
+	    I used a script to convert the docs, and it set all the box classes
+	    to be "code".  There are actually 4 different classes,
+	    "shell", "code", "targetlang", and "diagram".  We need to go through
+	    and convert the divs depending on what they contain.
+
+02/23/2005: mmatus
+
+	    [Python] Added option -nortti to disable the use of native
+	    C++ RTTI with directors (dynamic_cast<> is not used).
+
+	    Add more code for directors to detect and report errors in
+	    the python side.
+
+	    Extend the use of SWIGINTERN whenever is possible.
+
+	    Remove template warnings reported by VC7.1.
+
+	    Remove warnings reported by gcc/g++. Finally you can
+	    compile using
+
+	       g++ -W -Wall -c mymodule_wrap.cxx
+
+	    and no spurious errors will be generated in the wrapper
+	    code.
+
+02/23/2005: wuzzeb (John Lenz)
+	    Added -external-runtime argument.  This argument is used to dump
+	    out all the code needed for external access to the runtime system,
+	    and it replaces including the files directly.  This change adds
+	    two new virtual functions to the Language class, which are used
+	    to find the language specific runtime code.  I also updated
+	    all languages that use the runtime to implement these two functions.
+
+02/22/2005: mmatus 
+	    Fix %template + private error SF#1099976.
+
+02/21/2005: mmatus 
+
+	    Fix swigrun.swg warnings reported when using "gcc -W -Wall"
+	    (static/inline not used in front of a function
+	    declaration), and add SWIGUNUSED attribute to avoid
+	    unused warnings elsewhere.
+
+	    Fix unused variable warnings.
+
+	    [Python] Use new SWIGUNUSED attribute to avoid warnings in
+	    SWIGINTERN methods.
+
+	    [Python] Fix PyOS_snprintf for python versions < 2.2 (SF #1104919).
+
+	    [Python] Fix map/multimap to allow empty maps (reported by
+  	    Philippe Hetroy).
+
+	    [Docs] Add some documentation to Python.html and
+	    SWIGPlus.html, including for example the fact that
+	    'friends' are now supported.
+
+02/21/2005: wsfulton
+            [PHP] Patch from Olly Betts, so that wrappers compile with Zend thread safety enabled.
+
+02/17/2005: wsfulton
+            Memory leak fix in some of the scripting language modules when using default
+            arguments in constructors. The scripting language was not taking ownership of the
+            C++ object memory when any of the constructors that use default arguments was called.
+
+02/16/2005: wsfulton
+            SF #1115055: Failed make install. Patch from Rob Stone.
+
+02/16/2005: wsfulton
+            [Java] SF #1123416 from Paul Moore. Correct memory allocation for STRINGARRAY
+            typemaps in various.i.
+
+02/15/2005: wsfulton
+            Disabled typemap search changes for now (see entry 19/12/2004). It breaks
+            old typemaps, lengthens the execution time by about 25% and introduces
+            inconsistencies.
+
+02/15/2005: wsfulton
+            swig -help follows other software by printing to stdout instead of stderr now.
+            swig -version also displays to stdout instead of stderr now.
+            Behaviour reported by Torsten Landschoff.
+
+02/15/2005: wsfulton
+            [Ruby] Fix for the less commonly used ordering of %include and #include, so
+            that the generated code compiles. Bug reported by reported by Max Bowsher.
+              %include foo.h
+              %{
+              #include foo.h
+              %} 
+
+02/15/2005: wsfulton
+            [C#, Java] SWIG_exception macro will now return from unmanaged code / native code
+            as soon as it is called. Fixes possible JVM crashes and other code unexpectedly
+            being executed. Note SWIG_exception is only occasionally used by SWIG library
+            writers, and is best avoided by SWIG users.
+
+02/15/2005: wsfulton
+            [C#, Java] Typemaps can now be targeted at global variable names
+            and static member variable names. Previously the typemaps for 
+            the setters were ignored, for example:
+
+              %typemap(in) int globalint "..."
+              int globalint;
+
+02/13/2005: mkoeppe (Matthias Koeppe)
+	    [Guile] Add %typecheck for SWIGTYPE, add %typecheck for ptrdiff_t, fix
+	    typemaps for size_t.
+
+	    [Pike] Merge patch from Torsten Landschoff for improved Pike configuration.
+
+02/12/2005: mkoeppe (Matthias Koeppe)
+	    New configure switches --without-tcl, --without-python etc. allow to
+            disable the search for installed languages.
+
+01/31/2005: wuzzeb (John Lenz)
+            - Add DohSortList to DOH
+	    
+	    - Improve the runtime type system:
+               + Speed. Type loading is now O(n log n) instead of O(N^2), which
+	         for large modules is a huge improvement.
+               + A whole bunch of functions in swigrun.swg no longer need the 
+                 swig_type_list_handle passed to them.  The only one left is 
+		 TypeQuery.  This also makes runtime.swg a lot smaller.
+	       + Split up swig_type_info structure into two structures
+	         (swig_type_info and swig_cast_info)
+	       + Store a pointer to a swig_type_info rather than just the type
+	         name string in the linked list of casts. First off, this makes
+	         the guile module a little faster, and second, the
+	         SWIG_TypeClientData() function is faster too. 
+	       + Add the idea of a module into the type system.  Before, all the
+	         types were stored in one huge linked list. Now, another level is
+	         added, and the type system stores a linked list of modules, each
+	         of which stores an array of types associated with it.
+	       + For more information of how the runtime type system now works,
+	         please see Doc/Manual/typemaps.html and Doc/Devel/runtime.txt
+		 
+	    - Update all language modules to use the new type system.  The changes
+	      to each language module are minor.  All languages are now able to
+	      use runtime.swg for external access to the type system.  Before
+	      only python and perl did.
+
+	    - [guile, mzscheme, ocaml, and php4]  These languages opened up the
+	      init function inside the .cxx code, and any code in the .swg files
+	      in the init section was inside this function.  This was a problem
+	      for swiginit.swg, which needs to be inserted before the SWIG_init
+	      function is opened.  Thus I changed these languages to be like
+	      python or perl, where the init function is declared in the .swg
+	      file.
+	      
+	    - [Ruby] Instead of moving the init function to the .swg file, I
+	      added a new section initbeforefunc, and then added
+	      %insert(initbeforefunc) "swiginit.swg"
+
+	    - [MzScheme] Fix enums and fix Examples/Makefile.in so that if
+	      multiple -I arguments are specified in the INCLUDES variable, each
+	      gets a ++ccf.
+
+	    - [Guile GH] Update Guile GH to use the new type system.  See
+	      Doc/Manual/Guile.html for how smobs are now used.
+
+01/11/2005: wsfulton
+            [C#] New typemap called 'csconstruct'. The code in this typemaps was previously hard
+            coded and could not be customised by a user. This typemap contains the code that is
+            generated into a proxy class's constructor.
+
+            [Java] New typemap called 'javaconstruct'. The code in this typemaps was previously hard
+            coded and could not be customised by a user. This typemap contains the code that is
+            generated into a proxy class's constructor. Another typemap named 'javaconstruct_director'
+            is used instead when the proxy class is a director class.
+
+            [C#, Java] If a C++ class did not have a default constructor, a protected default constructor
+            was automatically generated by SWIG. This seems is unnecessary and has been removed
+            and thereby giving the user almost complete control over the generated code along with the
+            new typemaps above.
+
+19/12/2004: mmatus
+            [Disabled, see entry 02/15/2004]
+            - Fix typemap search, now the "out" typemap search is done as follows
+
+                 int *Foo::foo(int bar)   ->  int *Foo::foo(int bar)
+                                          ->  int *Foo::foo
+                                          ->  int *foo(int bar)
+                                          ->  int *foo
+                                          ->  int *
+
+               then, now you can be more specific, and define
+
+              /* apply only for  'Foo::foo' method */
+              %typemap(out) int * Foo::foo(int *bar) ...; 
+
+              /* apply for all 'foo' functions/methods */
+              %typemap(out) int * foo(int *bar) ...; 
+
+              %inline {
+                struct Foo {
+                   int *foo(int *bar);
+                };
+              }
+	  
+
+15/12/2004: mmatus
+            - More fixes for templates and template default args.
+              See template_default.i for scary cases that now are 
+              supported, besides the already ugly STL/std cases.
+              
+            - Cosmetics and more use of 'const' where it was implicit.
+            - Other fixes for OSS, which is now working again with 1.3.25.
+	
+Version 1.3.24 (December 14, 2004)
+==================================
+
+12/12/2004: wuzzeb (John Lenz)
+            [Chicken] Fix a bunch of bugs relating to -proxy support
+	      + non-class variables now export properly using -proxy
+	      + static member functions now export properly using -proxy
+	      + member class variables now export properly using -proxy
+	      + added a -nounit argument, which does not export the (declare (unit ...))
+	      + correctly install swigclosprefix.scm
+	      + constants (enums, defines) now correcly export when using -proxy
+
+12/11/2004: wsfulton
+            configure fix for when more than one version of jni_md.h is found
+            in the Java include directory (was generating lots of sed error
+            messages).
+
+12/08/2004: wsfulton
+            [Java] Fixes to arrays_java.i so that one can apply the array
+            typemaps to functions taking pointers as input, eg
+
+                %include "arrays_java.i"
+                %apply int[] {int*};
+                void foo(int *a);
+
+12/05/2004: wsfulton
+            [Java] Director mods contributed by Scott Michel. New typemaps
+            directordisconnect and directordisconnect_derived for the 
+            swigDirectorDisconnect() method. Also fix to get the javapackage
+            typemap working again.
+
+12/05/2004: mmatus
+	    - Finishing the fixes for templates + default template
+	      args + specializations.
+
+            - [Python] Now we use the new templates + default template
+	      args in the std/STL library. That means the internal
+	      swig files are getting uglier since we now support the
+	      original declarations:
+
+	        template<class _Tp, class _Alloc = std::allocator< _Tp > >
+		class vector {
+		....
+		};
+	      	     
+                template<class _Key, class _Tp, class _Compare = std::less<_Key >,
+	        class _Alloc = std::allocator<std::pair<const _Key, _Tp > > >
+                class map {
+		....
+		};
+ 
+              and the user can use the %template directive as
+
+	        %template() std::vector<int>;
+	        %template() std::vector<int, std::allocator<int> >;
+	        %template() std::vector<int, MyAllocator<int> >;
+
+              Now we are closer to the cleaning/rewriting of the
+	      python std/STL support, such that we recover support for
+	      MSVC++ 6.0, and we can add support for other languages
+	      too.
+
+
+12/02/2004: wsfulton
+            [Java] Fix for directors when wrapping methods using a member enum
+            and typesafe/proper enums enabled.
+
+12/01/2004: mmatus
+	    - Fix typemaps to work with templates and default template
+	      args, ie
+
+	       template <class A, class B = int>
+               struct Foo {
+	       };
+
+	       %typemap(in) Foo<int> *{...}
+	       %typemap(out) Foo<int,int> *{...}
+
+	       Foo<int> * foo( Foo<int> *f1, Foo<int,int> *f2);
+
+	      now 'f1', 'f2' and the return value resolve the provided
+	      typemaps properly.
+
+	      This is highly needed for proper STL support, see new 
+	      std_basic_string.i, std_sstream.i, etc.
+
+	    - Added std_sstream.i, and fix std_basic_string.i to use
+	      the new typemaps + template def. arg mechanism. Also,
+	      added the needed std_alloc.i. Now, all the containers
+	      can be modified to support std::allocator, like in:
+	      
+	        template<class T, class A = std::allocator<T > >
+		class vector {
+		public:
+		....
+		};
+	      
+	      This change is only completed by now for basic_string.
+
+	    - Fix for smart pointers + members + extensions:
+
+	      %extend Foo {
+	        int extension(int i, int j) { return i; }
+		int extension() { return 1; }
+	      }
+
+	      %inline %{
+
+	      class Foo {
+	      public:
+		int y;
+		static const int z;
+	      };
+  
+	      class Bar {
+	        Foo *f;
+	      public:
+	        Bar(Foo *f) : f(f) { }
+		Foo *operator->() {
+		  return f;
+		}
+	      };
+
+	      now you can 
+	     
+	      f = Foo()
+	      f.y = 3
+	      a = f.z
+	      f->extension()
+ 
+	      b = Bar(f)
+	      b.y = 3
+	      a = b.z
+	      b->extension()
+
+	    - Other small errors fixes, mostly python.
+
+11/25/2004: wsfulton
+            [Java] Numerous director bug fixes so that the correct java types
+            and canonicalized types in the JNI code are emitted. Use of the
+            $javaclassname special variables in the director typemaps now
+            consistent with the non-director typemaps. The types used for 
+            typemap lookups are also corrected in a few places. If you 
+            previously had your own director typemaps, ensure they are using the
+            correct C++ type.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA DIRECTORS ***
+
+11/25/2004: wsfulton
+            const enum SWIGTYPE & typemaps added. These wrap const enum references
+            as if they were passed by value. Const enum references thus work the
+            same as const reference primitive types such as const double &, 
+            const int & etc. Typemaps added for Java, C#, Ruby, Tcl, Perl and Pike.
+
+11/25/2004: wsfulton
+            [Java, C#] New special variable: $*javaclassname, similar to $javaclassname
+            and $&javaclassname. The new one removes a pointer from the C type before
+            obtaining the Java class name. One or more of $javaclassname,
+            $&javaclassname or $*javaclassname may now appear in a typemap. Likewise for
+            C# using csclassname instead of javaclassname.
+
+11/25/2004: wsfulton
+            The last vestiges of enums being handled as integers removed from the
+            internals. The wrapper methods use the enum type rather than an int
+            now. The net result is added type safety for enums when handled as
+            pointers, references etc. Previously in situations such as a method
+            taking a pointer to an enum, a pointer to an int or a pointer to an
+            enum of some other type could inadvertantly be passed to the method.
+            This is now fixed as the descriptor for an enum is no longer based on
+            an int, but the enum type instead. Anonymous enums are still handled
+            as integers.
+
+            The consequence for scripting language users in correct usage of enums
+            should not be noticeable. There is no change for any of the languages
+            where enums are passed by value - most of the scripting languages will
+            still accept an integer for an enum value and the strongly typed
+            languages still use either typesafe enums, integers or proper enums
+            depending on what the user configures. For Java and C# users a change
+            in the typewrapper class name has occurred (for enum pointers,
+            references etc). For example:
+
+              enum Numbers { one=1, two };
+              enum Numbers* number();
+
+            In Java and C# this must now be coded as
+
+              SWIGTYPE_p_Numbers n = modulename.number();
+
+            rather than
+
+              SWIGTYPE_p_int n = modulename.number();
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+11/21/2004: wsfulton/mmatus
+            Added missing deprecated warning for %name and remove remaining %name
+            usage in the SWIG libraries.
+
+11/21/04: mmatus
+	    - [Python] Adding the PySwigObject to be used for carrying
+	      the instance C/C++ pointers. This is used instead of
+	      string and PyCObjects.
+
+	      The new PySwigObject is even safer than PyCObject, and
+	      more friendly than plain strings:
+
+	      now you can do
+
+	        print a.this
+		<Swig Object at _00691608_p_A>
+
+		print str(a.this)
+		_00691608_p_A
+
+		print long(a.this)
+		135686400
+
+		print "%s 0x%x" % (a.this, a.this)
+		_00691608_p_A 0x8166900
+
+	      the last one is very useful when debugging the C/C++
+	      side, since is the pointer value you will usually get
+	      from the debugger.
+
+	      Also, if you have some old code that uses the string
+	      representation "_00691608_p_A", you can use it now again
+	      using 'str(ptr)', or by calling 'str = PyObject_Str(obj)'
+	      in the C/C++ side.
+ 
+	      This change is mainly for nostalgic swig users that miss
+	      the string representation, but also allows to say again
+
+	        if a.this == b.this:
+		  return "a is b"
+
+	      and well, since the change were really simple, maybe in
+	      the future we will be able to do
+   
+		next = a.this + 1
+
+	      or add native python iteration over native C/C++ arrays,
+	      ie, no need to create/copy new tuples when returning and
+	      array or vector.
+
+	      Also, a PySwigPacked object was adding to carry a member
+	      method pointer, but this is probably a temporal solution
+	      until a more general object for methods is added.
+
+	      Be aware that to simplify maintaining and compatibility
+	      with other tools, the old string and PyCObjects
+	      representation could disappear very soon, and the
+	      SWIG_COBJECTS_TYPES or SWIG_NO_OBJECT_TYPES macros will
+	      have no effect at compilation time. Still, the three
+	      mechanisms are present in the code just for testing,
+	      debugging and comparison purposes.
+	      
+11/21/04: mmatus
+
+	    - [Python] Adding back support for using the swig runtime code
+	      inside the user code. We just allow the user to include
+	      the minimal code needed to implement the runtime
+	      mechanism statically, just as in done in the swig
+	      modules.
+	      
+	      To use the swig runtime code, for example with python,
+	      the user needs include the following:
+ 
+               #include <Python.h>         // or using your favorite language
+               #include <swigrun.swg>
+               #include <python/pyrun.swg> // or using your favorite language
+               #include <runtime.swg>
+
+	      the files swigrun.swg, pyrun.swg and runtime.swg can 
+	      be checked out by using swig -co, or they can simply 
+	      be found by adding the swig lib directory to the
+	      compiler include directory list, for example
+
+	       SWIGLIB=`swig -swiglib`
+	       c++ -I${SWIGLIB} ..
+
+	      of better, using the CPPFLAGS, but that depends on your
+	      environment.
+	       
+	      This change can be ported to the other languages too,
+	      you just need to isolate the needed runtime code in
+	      a single file like 'pyrun.swg', and provide the 
+	      SWIG_Runtime_GetTypeList() method. Look at the
+	      Lib/python/pyrun.swg file and the Examples/python/swigrun
+	      example.
+
+11/15/04: mmatus
+	    - Fix mixed_types.i + gcc-3.4, ie, arrays + references +
+	      typedefs
+
+	    - Fix multidim arrays + typedefs,ie
+
+	       typedef char character[1];
+	       typedef character word[64];
+
+	    - Process protected/private bases in the same way before
+	      we process protected/private members, ie, we check
+	      for constructors, operator new, virtual members, etc.
+   
+	    - Fix Ruby/Java to work (or ignore) multi-inheritance +
+              directors. Allow other languages to define if it is
+              supported or not.
+	    
+	    - Now you can run
+
+                SWIG_FEATURES="-directors -dirprot" 
+                make check-ruby-test-suite
+                make check-python-test-suite
+                make check-java-test-suite
+                make check-ocaml-test-suite
+
+	      and you will get only 'real' errors. ruby and python
+	      compile with no errors, java shows some problems.	
+
+Version 1.3.23 (November 11, 2004)
+=================================
+
+11/05/2004: wsfulton
+            Patch #982753 from Fabrice Salvaire: Adds dependencies generation for
+            constructing makefiles. New command line options -MF -MD -MMD to work
+            with the current options -M and -MM. These options are named the same
+            and work the same as in gcc.
+
+11/05/2004: wsfulton
+            %ignore/%rename changes for methods with default arguments to mirror
+            %feature behaviour. See previous entry.
+
+                      *** POTENTIAL INCOMPATIBILITY ***
+
+11/04/2004: wsfulton
+            %feature improvements for fine tuning when wrapping methods with
+            default arguments. Any %feature targeting a method with default arguments
+            will apply to all the extra overloaded methods that SWIG generates if the
+            default arguments are specified in the feature. If the default arguments are
+            not specified in the feature, then the feature will match that exact
+            wrapper method only and not the extra overloaded methods that SWIG generates.
+            For example:
+
+              %feature("except") void hello(int i=0, double d=0.0);
+              void hello(int i=0, double d=0.0);
+
+           will apply the feature to all three wrapper methods, that is:
+
+              void hello(int i, double d);
+              void hello(int i);
+              void hello();
+
+           If the default arguments are not specified in the feature:
+
+              %feature("except") void hello(int i, double d);
+              void hello(int i=0, double d=0.0);
+
+           then the feature will only apply to this wrapper method:
+
+              void hello(int i, double d);
+
+           and not these wrapper methods:
+
+              void hello(int i);
+              void hello();
+
+           This has been introduced to make %feature more powerful to ease the migration
+           to new default arguments wrapping approach.
+
+                      *** POTENTIAL INCOMPATIBILITY ***
+
+           If you previously had a %feature and didn't specify the default arguments,
+           you will have to add them in now or you can obtain the original behaviour
+           by using %feature("compactdefaultargs").
+
+11/04/2004: wsfulton
+            [C#] Typemaps for std::vector added into std_vector.i. The proxy classes
+            generated are modelled on the .NET ArrayList class. This isn't quite
+            ready for general consumption yet, but will work with vectors of primitive
+            types and some classes.
+
+10/3/2004: wuzzeb (John Lenz)
+            [GUILE] The -scm interface is now the default.  The old GH interface can
+	    still be enabled by passing -gh to SWIG.
+
+10/2/2004: mmatus
+
+	    - More fixes for namespace + class declarations.
+	      As an extra bonus, we get %template support for static/members class
+	      methods, ie, now you can say:
+
+	        namespace space {
+                 struct A			    
+	         {				    
+	           template <class Y>	    
+	           static void fooT(Y y) { }
+	         };	
+		}			    
+	      	      			    
+	        struct B			    
+	        {				    
+	          template <class Y>		    
+	          void barT(Y y) {} 
+	        };                           
+
+		%template(foo) space::A::fooT<double>;
+		%template(foo) space::A::fooT<int>;
+		%template(foo) space::A::fooT<char>;
+                                                                                
+		%template(bar) B::barT<double>;
+		%template(bar) B::barT<int>;
+		%template(bar) B::barT<char>;
+
+	      and call
+
+	        A.foo(1)
+		b = B()
+		b.bar(1)
+	      
+	      note the the methods are emitted inside the classes,
+	      and hence, the %template name refers to the 'member'
+	      method name, not a global namespace name.
+
+10/31/2004: mmatus
+	    - Solve namespace + class declarations, as in
+
+	       namespace foo {
+                 struct Bar;
+		 struct Foo {
+                 };
+               }
+
+               struct foo::Bar : Foo {
+               };
+
+	       see namespace_class.i for more examples.
+
+            - Fix %template directive to properly use namespaces,
+              including the case:
+
+		   namespace one
+		   {
+		       template <typename T>
+		       struct Ptr {};
+                   }
+
+		   namespace one
+		   {		  
+		       struct Obj1 {};
+		       typedef Ptr<Obj1> Obj1_ptr;
+  		       %template(Obj1_ptr) Ptr<Obj1>; 
+		   }				  
+		   				  
+		   namespace two  
+		   {
+		       struct Obj2 {};	
+		       typedef one::Ptr<Obj2> Obj2_ptr;
+		       %template(Obj2_ptr) one::Ptr<Obj2>;
+		   }
+
+	      this is done by using the namespace name 'one' to create
+              a namespace node to emit the template instantiation,
+              just as before, but the template parameters are resolved
+              and qualified in the current namespace ('one' or 'two').
+              This is same way that typedef works. 
+
+	      This resolve the smart_pointer_namespace2.i case, and at
+              the same time, several other ones where before swig was
+              generating the
+
+	        "Can't instantiate template 'xx' inside namespace 'yy'"
+	      
+	      error message. In fact, that error doesn't exist
+	      anymore. You can only get an error if you use a bad
+	      namespace name or so.
+
+10/30/2004: mmatus
+	    - [ruby] Directors fixes:
+	      - enums and std::strings are working now (several
+	        reports in bug track system)
+	      - added patch 1025861 for director + exceptions
+		
+              *** Attention ***: ruby with directors + protected
+              members work with version 1.7+. Older versions seems to
+              have a broken signature for'rb_protect'.
+		
+	      If you need to use an old version, look at
+
+	      http://excruby.sourceforge.net/docs/html/ruby__hacks_8hpp-source.html
+  	      for workarounds.
+	      
+            - [ruby] Fix memory allocation problem in typemap (bug 1037259)
+
+	    - [tcl] Fix (enums|constants) + namespace option 
+	            (reported by jason.m.surprise@intel.com).
+
+            - [perl] Add patch 962168 for multiple inheretance
+	    
+	    - Fix 'defined' as variable name.
+
+10/29/2004: wsfulton
+            Seg fault fix for global scope operator used for friend methods:
+
+              class B {
+                friend void ::globalscope();
+                ...
+              };
+
+10/28/2004:mmatus
+	    - Added module and swig option "templatereduce" to force swig
+	      to reduce any type needed with templates, ie, in these cases
+
+                %module("templatereduce") test
+
+                template <class T> struct A { };
+
+                typedef int Int;
+	        %template(A_Int) A<Int>  ==>  %template(A_Int) A<int>
+
+                typedef B* Bp;
+	        %template(A_Bp) A<Bp>  ==>  %template(A_Bp) A<B*>
+
+              swig reduces the types Int and Bp to their primitives
+              int and B*. This is closer to the usual compiler
+              resolution mechanism, and it is really needed sometimes
+              when you mix templates + typedefs + specializations.
+
+	      Don't use it if you don't have any problem already,
+	      since the type reduction can interfere with some
+	      user typemaps, specially if you defined something like
+
+		   typedef int Int;
+		   %typemap(in) Int ...;
+
+              in this case, when you use the "templatereduce" option,
+	      swig will ignore the user typemap, since the "typedef int Int"
+	      will take precedence, and the usual "int" typemap will be
+	      applied. 
+
+	      Note that the previous case is not common, and should be
+	      avoided, ie, is not recommended to use a typedef and a
+	      typemap at the same time, specially if you are going to
+	      use templates + specializations.
+
+	    - Directors:
+
+	        virtual destructor is always emitted now, this doesn't
+	        cause any harm, and could solve some nasty and
+	        mysterious errors, like the one mentioned by Scott.
+
+		also the destructor is not in-lined, so, that can solve
+		some other mysterious errors when mixing directors +
+		imports + embedded applications + some specific compilers.
+		
+10/27/2004: wsfulton
+            [C#] typemaps.i library file with INPUT, OUTPUT and INOUT typemaps added.
+
+10/27/2004: wsfulton
+            [Java] std::wstring typemap fixes in std_string.i from Russell Keith-Magee.
+
+10/25/2004: mmatus 
+
+	    - Using + namespace is working now (using_namespace.i).
+
+	    - Derived + nested classes is working now
+	      (deriver_nested.i), but of course, we are still waiting
+	      for the nested class support.
+	    
+	    - Directors:
+	      - unnamed parameters support,
+
+	      - protected constructor support (automatic and with
+                dirprot mode),
+
+	      - detection of really needed protected declarations
+                (members and constructors) now is done automatically.
+                Even if you don't use the 'dirprot' mode, swig will
+                wrap what is minimally needed (and protected) for the
+                code to compile.
+		
+		what is public, as usual, is always wrapped, and if
+		you use the 'dirport'
+		
+
+	    - Final fixes for the OSS to compile with SWIG 1.3.23 (my
+	      very very ugly C++ + templates + everything mounters wrap).
+
+10/25/2004: wsfulton
+            [C#] New commandline option -dllimport. This enables one to specify
+            the name of the DLL for the DllImport attribute. Normally this name
+            comes from the module name, so now it is possible to override this:
+
+              swig -csharp -dllimport xyz example.i
+
+            will generate for all the wrapped PInvoke methods:
+
+              [DllImport("xyz", EntryPoint="...")]
+              public static extern ...
+
+            The wrappers from many different SWIG invocations can thus be compiled
+            into one DLL.
+
+            A new special variable $dllimport can also be used in typemaps, pragmas,
+            features etc. This will get translated into the value specified by -dllimport
+            if specified, otherwise the module name.
+
+10/22/2004: wsfulton
+            [Java] Patch #1049496 from Scott Michel fixes directors methods with 
+            enums when wrapped with typesafe or proper Java enums.
+
+10/21/2004: wsfulton
+            Fixes for default arguments in director constructors (Python, Ruby, Ocaml).
+
+10/21/2004: mmatus
+	    - [Python] Add the '-cpluscast' option to enable the 'new'
+	      C++ casting operators, such as 'static_cast', inside the
+	      typemaps. By default swig use the old C cast style, even
+	      when parsing C++.
+	      
+	    - [Python] Add the '-new_vwm' option to enable the new
+              SwigValueWrapper mode. Now this is mainly for testing
+              that the typemaps are really safe for any future
+              solution, but you can use it if you have a very strange
+              error with default cosntructors missing + %apply +
+              %typemap, and if everything else fails (see
+              valuwrapper_opaque.i for alternative and current
+              solutions). If you are a user that don't know what is
+              SwigValueWrapper, don't even try it.
+
+	    - [Python] Add the '-noh' option to be used with directors
+	      and when you prefer to disable the generation of the
+	      director header file. If not used, swig will work as
+	      usual generating both the wrap.cxx and wrap.h files. If
+	      you use it, swig will only generate wrap.cxx.
+
+10/21/2004: wuzzeb (John Lenz)
+            - If you define SWIG_TYPE_TABLE when compiling a wrapper file,
+	      the runtime types will be stored in the given type table name.
+	      Using this, you can seperate different modules to share their
+	      own type systems.  -DSWIG_TYPE_TABLE=Mytable
+
+	    - [Python] If you define SWIG_STATIC_RUNTIME then the type information
+	      will be static to this wrapper.  Nothing will be shared with any
+	      other modules
+
+	    - [Python] If you define SWIG_LINK_RUNTIME, then instead of using
+	      the new way of sharing type information, the wrapper will expect
+	      to be linked against the Lib/linkruntime.c file.  Any modules compiled
+	      with SWIG_LINK_RUNTIME and linked against linkruntime.c will all
+	      share type information.
+
+10/20/2004: mmatus
+	    - [Python] Initial fix for python/import example. Please
+	      update the Makefile (autoconf, configure, etc, expert),
+	      since now probably is only working with g++, icc and a
+	      few other compilers that have the -shared option.
+
+	      We need to create additional shared libraries for the
+	      virtual destructors. Old and usually forgotten C++
+	      requirement.
+	      
+	      Same fix need to be used in perl, I think.
+
+            - [Python] Fix generation of header file for directors,
+              now directors.swg is also included, so, it can be really
+	      used from C++, and it solves some problem with compiler
+	      that require that, even with the simple swig inclusion.  
+
+            - [Python] Reordering the methods and moving some bodies
+              outside the class declaration. This is needed due to
+              some gcc-2.96 internal compiler errors. It seems the
+              PYTHON class is getting too large to been declared and
+              defined at the same time.
+
+	    - Add the -oh option to change the output header file name
+              if needed:
+
+                 swig -c++ -python test.i -o test.CC -oh test.HH
+	      
+              this is mainly needed when using directors, and if the
+              current default header file name is not good for you,
+              which is generated as follow:	      
+
+                 swig -c++ -python test.i             => test_wrap.h
+                 swig -c++ -python test.i -o test.CC  => test.h
+
+
+10/20/2004: wsfulton
+            1) Compact default arguments feature added. This feature allows one
+              to use the default argument code generation that was used in
+              SWIG-1.3.22 and earlier versions. It produces more compact wrappers
+              as only one wrapper method is generated for any method with default
+              arguments. So the advantage is it generates less code but has the
+              original limitations, like it it does not work with all default arguments
+              and default arguments cannot be taken advantage of in the strongly typed
+              languages (C# and Java). It is implemented via the usual %feature mechanism:
+
+                %feature("compactdefaultargs");
+
+            2) Keyword arguments (kwargs) are working again for default arguments
+               in the languages that support it, ie, Python and Ruby. The new default
+               argument wrapping approach using overloaded methods cannot support kwargs
+               so the compact default argument feature is automatically turned on when
+               kwargs are specified, by %feature("kwargs").
+
+            3) Compact default arguments are also automatically turned on when wrapping
+               C (not C++) code. This is to support the bizarre notion of default arguments
+               for C code.
+
+10/20/2004: wsfulton
+            Overloaded templated functions in namespaces also working now.
+            Templated functions with default arguments in namespaces too.
+
+10/19/2004: mmatus
+
+	    - Allow to disable the new SwigValueWrapper mechanism,
+	      if you add the following line in your language main.
+
+		 /* Turn on safe value wrapper use mode */
+                 Swig_value_wrapper_mode(1);
+
+	      
+	      Now is only active in python. All the other languages
+	      are using the old resolution, but they  can also use the
+	      "valuewrapper"/"novaluewrapper" features to fix some
+	      of the old broken cases. Note, however,  that not all 
+	      the broken cases can be solved in that way.
+
+	      The new mechanism seems to be working fine in perl, ruby
+	      and tcl, but failing in some typemaps in java.
+
+	      Hence, is upto the language maintainer to test it, and
+	      decide to enable it or not.
+
+	      Look at the valuewrapper_opaque.i for examples.
+
+	    - Fix more SwigValueWrapper cases when the new mechanism
+	      is active. Now it also check for local typemap
+	      variables, see valuewrapper_opaque.i for an example when
+	      this is needed. But again, this extra checking will only
+	      be activated when using the new value wrapper mode.
+
+	    - [Python] Fix variable wrapping of classes with private
+	      assign operators. It should be easy to fix in all the 
+	      other modules, instead of checking
+
+	         if (!Getattr(n,"immutable")) ...
+	
+	      you need to verify
+
+	         if (is_assignable(n)) ...
+
+	      Look at the private_assign.i for an example.
+
+10/18/2004: mmatus
+	    - %features "director"/"nodirector" now work as expected.
+            - General fixes in %feature to resolve function decl
+	      properly,
+	      
+	        %feature("hello") foo();
+	        char foo() ->  f()    // was working
+	        char *foo() -> f().p  // it wasn't
+ 
+
+            - Template + specialization + default template args now is
+	      working, (don't confuse with template + default arg
+	      values, that was solved before), now this ugly case is
+	      working:
+
+	        template <class T, class A = Alloc<T> >
+		struct Vector
+		{
+		   Vector(T a){}
+		};		   
+
+		template <>
+		struct Vector<double>
+		{
+		  Vector(){}
+		  int foo() { return 0; }
+                };
+
+	        %template(V_c) Vector<char, Alloc<char> >;
+	        %template(V_i) Vector<int>;    // picks Vector<int,Alloc<int> >
+	        %template(V_d) Vector<double>; // picks the specialization
+	      
+              this is needed for automatic STL support (later will
+              be).
+
+	    - Fix the template + typedef errors in test-suite, which
+              probably will fix another group of strange template +
+              namespaces + typedefs errors.
+
+	    - %warnfilter is working better now, parser.y tries to use
+	      them when needed.
+
+	    - **** New default type resolution method (stype.c) ***** 
+
+	      It preserves the original mixed types, then it goes
+	      'backward' first deleting the qualifier, then the inner
+	      types, for example:
+    		 							  
+    		 typedef A *Aptr;				  
+    		 const Aptr&;						
+    		 r.q(const).Aptr       -> r.q(const).p.SWIGTYPE		
+    		 r.q(const).p.SWIGTYPE -> r.p.SWIGTYPE			
+    		 r.p.SWIGTYPE          -> r.SWIGTYPE			
+    		 r.SWIGTYPE            -> SWIGTYPE			
+		 							
+    		 enum Hello {};						
+    		 const Hello& hi;					
+    		 r.q(const).Hello          -> r.q(const).enum SWIGTYPE	
+    		 r.q(const).enum SWIGTYPE  -> r.enum SWIGTYPE		
+    		 r.enum SWIGTYPE           -> r.SWIGTYPE		
+    		 r.SWIGTYPE                -> SWIGTYPE			
+		 							
+    		 int a[2][4];						
+    		 a(2).a(4).int           -> a(ANY).a(ANY).SWIGTYPE	
+    		 a(ANY).a(ANY).SWIGTYPE  -> a(ANY).a().SWIGTYPE		
+    		 a(ANY).a().SWIGTYPE     -> a(ANY).p.SWIGTYPE		
+    		 a(ANY).p.SWIGTYPE       -> a(ANY).SWIGTYPE		
+    		 a(ANY).SWIGTYPE         -> a().SWIGTYPE		
+    		 a().SWIGTYPE            -> p.SWIGTYPE			
+    		 p.SWIGTYPE              -> SWIGTYPE                    
+
+	      before it always stops after finding ref/pointer/enum/array/etc.
+	       
+	      Now, then, you can define (use and apply) 'higher' typemaps such as:
+
+                %typemap(in) SWIGTYPE* const&  
+	        %typemap(out) char FIXSIZE[ANY]
+                %typemap(in) SWIGTYPE* const&  
+	        %typemap(in) const enum SWIGTYPE&
+	        %typemap(in) SWIGTYPE[ANY][ANY]
+	        %typemap(in) const char (&)[ANY]
+	       
+	      It is possible with this change that previous typemaps
+	      that were defined (but ignored), now will start to work.
+
+	      Also, it is necessary check for the '%typemap(varin) SWIGTYPE[]',
+	      before it was usually not defined (but char[] was),
+	      and that can produce some inconsistencies.
+
+                      *** POTENTIAL INCOMPATIBILITY ***
+
+	      This change was needed for STL, since std::vector<enum Hello> 
+	      std::vector<A*>, etc, will always generate methods that
+	      mix const references with the vector type.
+
+	      Now that is working, all the std::container<T*>
+	      specialization will not be needed anymore, well, in
+	      theory. 
+
+	      In the practice, everythin is working as before until
+	      the proper mixed types are defined and the libraries
+	      simplified to use them.
+
+	    - Change the behavior of extern "java"/"fortran"/"etc", 
+	      now swig produces a warning, and use extern "C" instead.
+	      The warning can also be disable with the "-w 313" flag.
+	      (WARN_PARSE_UNDEFINED_EXTERN).
+
+	    - SwigValueWrapper is now more selective (lang.cxx).
+
+            [Perl/Tcl]
+	    - Fix some typemaps (perl/tcl) to work properly with
+	      SwigValueWrapper. This was not a problem with
+	      SwigValueWrapper, but with the typemaps that now are
+	      safe to use with %apply.
+
+	    [Python]
+
+            - Fix %callback/%pythoncallback work now as before after
+	      the def args changes. Also, %callback now is an alias
+	      for %pythoncallback, so, they do the same.
+
+	    [Python/Ruby]
+	    - %callback is more usable and uniform:
+
+                 %callback("%s_cb") foo();  // for both, python/ruby
+                 %callback("%s_cb");        // for both, python/ruby
+                 %callback(1) foo();        // only in python.
+
+10/17/2004: arty
+	    [OCAML]
+	    - Tweak to enum typing for soundness in the presence of multiple
+	      modules.
+	    - global functions are now unambiguous in multiple loaded modules.
+	    - Fixed test case code to build multimodule test cases correctly.
+	    - There is no way to share overload resolution across modules
+	      because of soundness issues.  If the user wants to call some
+	      function foo from an arbitrary module bar, they will have to
+	      use Bar._foo to call it correctly.  Later I will fix the 
+	      camlp4 module to do something clever in this case.  
+            - Promided performance overhaul of class mechanism.
+	    - Removed symbol hack for ocaml-3.07 and below which is not needed
+	      for ocaml-3.08 and above.
+
+10/16/2004: wuzzeb (John Lenz)
+            [CHICKEN]
+	    - Completly change how chicken.cxx handles CLOS and generic code.
+	      chicken no longer exports -clos.scm and -generic.scm.  The clos
+	      code is exported directly into the module.scm file if -proxy is passed.
+	    - The code now always exports a unit.  Running the test-suite is now
+	      majorly broken, and needs to be fixed.
+	    - CLOS now generates virtual slots for member variables similar to how
+	      GOOPS support works in the guile module.
+	    - chicken no longer prefixes symbols by the module name, and no longer
+	      forces all names to lower case.  It now has -useclassprefix and -closprefix
+	      similar to how guile handles GOOPS names.
+
+10/16/2004: wsfulton
+            Templated functions with default arguments working with new default argument
+            wrapping approach. The new approach no longer fails with the following default
+            argument pattern (previously failed with some primitive types, like 
+            unsigned primitive types):
+
+              template<typename T> int foo(const T& u = T());
+              %template(foo) foo<unsigned int>;
+
+            This relies on the templated function overloading support just added, so all
+            the combinations of overloading by template parameters and normal parameters
+            as well as overloading with default parameters works.
+
+10/16/2004: wsfulton
+            Added support for the large range of templated function overloading that C++
+            supports.
+
+            - Overloaded templated functions, eg
+
+              template<typename T> int overload(T t);
+              template<typename T> int overload(T t, const T &r);
+
+            - Fixes where the templated type is not used in the parameter list, eg
+
+              template<typename T> void xyz();
+              template<> void xyz<double>();
+
+            - Fixes for overloading of plain functions by a templated function:
+
+              void abc(double d);
+              template<typename T> void abc(T t);
+
+            - Overloading by templated parameters fixed:
+
+              template<typename T> void foo(T t) {}
+              template<typename T, typename U> void foo(T t, U u) {}
+
+              %template(foo) foo<double, double>;
+
+            - All combinations of the above also working including specializations, eg:
+
+              void abc(double d);
+              template<typename T> void abc(T t);
+              template<> void abc<double>(double t);
+              template<> void abc(int t);
+
+10/16/2004: wuzzeb (John Lenz)
+            - Remove the ability to share type information by using c linking.
+              All type sharing happens through a global variable in the target language.
+                + Remove SWIG_NOIMPORT, SWIG_RUNTIME, and related defines.
+                + Depreciate -runtime, -noruntime command line options
+                + Update test-suite common.mk to correctly build multicpptest
+                + Remove reference to precommon.swg
+                + Update the guile_gh interface to share data by a global var instead
+                  of c linkage.
+
+            - Remove Advanced.html, since everything in it is now obsolete
+
+10/09/2004: mmatus
+	    - Split the python std/STL C++ library files, now
+	      all the language independent definitions are under
+	      the directory
+	      
+		Lib/std
+
+	      and hence, can be used from other languages.
+
+	    - Add more documentation to the Python STL, and
+	      clean unnecessary code.
+
+	    - Add initial C99 complex support, and some fixes
+	      for long double.
+
+10/08/2004: mmatus
+	    - Fix the SwigValueWrapper for opaque types, now it is 
+	      applied for opaque templates and classes, for which we
+	      don't know if there is or not a default constructor, ie
+
+                 struct A { 
+                   A(int);
+                 };
+ 
+              Still, if you know that you class has a default
+              constructor, and for some very very particular reason
+              you want to avoid the SwigValueWrapper, and you don't
+              want or can't expose the class to swig, now you can
+              say
+
+                 %feature("novaluewrapper") A;    
+                 class A;
+               
+              or the other way around, if the class has a default
+              constructor, but you want to use the value wrapper, you
+              can say
+
+                 %feature("valuewrapper") A;
+                 struct A { 
+                   A();
+		   ....
+                 };   
+      
+	    - Fix for char > 128, ie
+
+                const char tilde_a = '\341';
+
+            - Add patch 1041858 for $lextype, which carries the 
+              literal type of a symbol. See lextype.i in the
+              test-suite for more details.
+
+                            
+ 
+
+10/07/2004: wsfulton
+	    {Ruby, Java] Fix director + 'empty' throws
+
+		    struct A {
+		      A() throw();
+		      virtual ~A() throw();
+		      int foo() throw();
+		    };
+
+
+10/06/2004: wuzzeb (John Lenz)
+            [TCL]
+            - Fix bug reported by William A. Hoffman propagating clientdata
+            between modules.  Added clientdata_prop.multicpptest to check for
+            this bug.  The fix involved the following changes:
+                + SwigType_clientdata_collect does not need to check
+                types in r_resolved because we only want to propagate clientdata
+                to typedefed classes, and r_mangled already takes care of typedefs.
+
+                + SWIG_TypeRegister now copies the clientdata field correctly
+
+                + Move SWIG_Guile_PropagateClientData function from guile module
+                into common.swg, because we need to call it from both guile and tcl.
+
+                + Add base_names to swig_class to delay the lookup of bases.  SWIG
+                now exports the base names and only when the base swig_class is
+                needed is SWIG_TypeQuery(name)->clientdata looked up.
+
+            - conversion_ns_template testsuite test was failing because
+            the name of the wrapped constructor function was not calculated
+            correctly for structs.  Fixed.
+
+10/06/2004: wsfulton
+            Fixes for default arguments used in directors - in virtual
+            methods and director constructors.
+
+10/06/2004: mmatus
+	    Fix the __cplusplus macro, and bug 1041170.
+	    Now it is working as supposed, ie, you can safely use
+
+	      #ifdef __cplusplus
+	      ...
+	    
+	    all over swig, including inside %defines and %{ %} bodies.
+
+	    
+                      *** POTENTIAL INCOMPATIBILITY ***
+
+	    The old trick of using
+
+	      #if __cplusplus
+
+	    doesn't work any more. So, if you have your own typemaps
+	    using that syntax, you will need to migrate them to use
+	    "#ifdef __cplusplus".
+
+10/05/2004: wuzzeb (John Lenz)
+            - Reorganize how runtime type information is stored and shared
+	    between modules.  For chicken and mzscheme, I removed
+	    the ability to use runtime libraries, while perl, tcl, python, and
+	    ruby default to using the new method but can go back to the old
+	    method by declaring SWIG_ALLOW_RUNTIME.
+
+	    - line 582 in mzscheme.cxx was generating a segfault on 
+	    imports.multicpptest, so I fixed it.
+
+10/05/2004: wsfulton
+            Fixes for %extend and overloaded static methods with default
+            arguments.
+
+10/05/2004: mmatus
+	    - [python] Fix director + method with 'empty' throw, ie
+
+		    struct A {
+		      virtual int foo() throw();
+		    };
+		    
+	      other languages should also easy to fix, look for
+	      Getattr(n,"throw") in python.cxx.
+
+	    - Fix director + destructor with 'empty' throw
+
+		    struct A {
+		      virtual ~A() throw();
+		    };
+
+	    - Now SWIG_FEATURES parse all and the same  options you
+              can pass to swig in the command line.
+	      
+	    - New command line flag: -features <list>, as in
+
+	        swig -features autodoc=3,director
+
+	      ie, any global feature can be initialized from the
+	      command line. This is mainly for testing, but users
+	      can also take advantage of it.
+
+10/04/2004: mmatus
+	    - Properly qualify type in syntax as 'long(2)' or 'Foo()',
+	      this solve old problem with default args, and probably
+	      other problems around. However, the default arg problem
+	      was also already solved by William (see bellow).
+
+	    - Fix feature_set and feature_get methods. Before
+	      they look from particular to general and keep the first
+	      feature found. This didn't work well with templates.
+	      Now the methods look from general to particular, and
+	      override any found feature.
+
+            - Previously a feature could not be applied to constructors
+              or destructors that weren't explicitly declared in the class.
+              This is now fixed, for example:
+
+                %feature("featurename") Foo() "..."
+                %feature("featurename") ~Foo() "..."
+                class Foo {
+                  // implicit Foo() and ~Foo()
+                };
+
+	    - Fix missing features for default const/dest, by really
+	      'creating' the methods and applying the features.
+
+	    - Fix return_const_value.i case by adding SwigValueWrapper<const T>
+	      specialization.
+
+	    - Fix %extend + overload, including overloading actual
+              class methods. 
+
+	    - Adding more cases in related files in the test-suite.  
+
+10/04/2004: wsfulton
+            Changes to the way default arguments are wrapped. Previously a single
+            method was generated for each method that had default arguments. If
+            a method had 5 arguments, say, of which 1 had a default argument
+            then the call to the wrapped method would pass 5 arguments. The default
+            value was copied into the wrapper method and used if the scripting
+            language passed just 4 arguments. However, this was flawed as the
+            default argument sometimes does not have global access, for example
+            SWIG would generate code that couldn't compile when wrapping:
+
+              class Tricky {
+              public:
+                void foo(int val = privatevalue);
+                void bar(int val = Tricky::getDefault());
+              private:
+                static int getDefault();
+                enum { privatevalue = 200 };
+              };
+
+            Also bugs in resolving symbols generated code that wouldn't compile, for example
+            (probably fixable though):
+
+              namespace Space {
+                class Klass {
+                };
+                Klass constructorcall(const Klass& k = Klass());
+              }
+
+            The approach also does not work for statically typed languages (C# and Java)
+            as these languages do not allow methods to have variable number of arguments.
+            Although C# has a mechanism to pass a variable number of arguments they
+            must be of the same type and are more like varargs.
+
+            The new approach solves the above problems and wraps methods with default
+            arguments as if the method was overloaded. So SWIG will now treat
+
+              void foo(int val=0);
+
+            as if it had parsed:
+
+              void foo(int);
+              void foo();
+
+            The code generated is then exactly the same as if SWIG had parsed the two
+            overloaded methods. The scripting languages count the arguments passed and call
+            the appropriate method, just like overloaded methods. C# and Java are now able
+            to properly wrap methods with default arguments by generating extra methods,
+            again as if the method was overloaded, so for:
+
+              void bar(string s="hello", double d=10.0, int i=0);
+
+            the following proxy methods are generated:
+
+              void bar(string s, double d, int i);
+              void bar(string s, double d);
+              void bar(string s);
+              void bar();
+
+            The new approach comes with a couple of minor knock on effects.
+
+            1) SWIG support for default arguments for C (not C++) code no longer works.
+            Previously you could have this interface:
+
+              %{
+              void foo(int val);
+              %}
+              void foo(int val=0);
+
+            and call the wrapped method from a scripting language and pass no arguments
+            whereupon the default of 0 was used. You can get the same behaviour for C
+            code by using the "default" typemap:
+
+              %typemap(default) int val "$1 = 0;";
+              %{
+              void foo(int val);
+              %}
+              void foo(int val);
+
+            or you could of course compile your code as C++ if you want C++ features :) :
+
+              %{
+              void foo(int val=0);
+              %}
+              void foo(int val=0);
+
+            A couple of SWIG's libraries used this C extension and these have been modified
+            to use the "default" typemap. The "default" typemap is thus unchanged (and still
+            is not and is not fully supported by C# and Java, and is likely to remain so).
+
+
+            2) All features (%feature, %rename, %ignore etc) no longer work as if the method
+            with default arguments is just one method. For example, previously
+
+              %ignore foo(int);
+
+            would have ignored the method completely. Now it will only ignore foo(int) but
+            not the extra foo() method. Instead use:
+
+              %ignore foo;
+
+            to ignore them all. or
+
+              %ignore foo(int);
+              %ignore foo();
+
+            This of course allows one to fine tune the wrapping, for example one could use:
+
+              %rename(fooint) foo(int);
+              %rename(foodefaults) foo();
+              void foo(int val=0);
+
+            and call them from any language like so:
+
+              fooint(200)
+              foodefaults()
+
+            or for example ignore the extra overloaded method, so the defaults cannot be used:
+
+              %ignore foo();
+              void foo(int val=0);
+
+                      *** POTENTIAL INCOMPATIBILITY ***
+
+10/2/2004: mmatus
+	   [Python]
+	   - More cleaning up and uniformation on the Python Lib
+
+	   - Added Robin's docstring patch, plus some fixes, plus
+	     some extensions, see autodoc.i example in the test-suite,
+	     and try using %feature("autodoc","extended").
+	    
+	     This patch is not a complete solution for the
+	     documentation problem, just enough to inform python about
+	     the parameter list.
+
+	     The expected swig documentation support is far far away yet.
+	     
+
+10/1/2004: mmatus
+	   - Fix the %callback feature (only used in ruby and python examples,
+	     by now, but it should be generic), now member callbacks
+	     are working again
+	     
+	   - Fix wrapping of functions pointers like
+
+		 std::ostream& std::endl(std::ostream&);
+
+	     ie, the ones that return references or enums.
+	 
+	   [Python] Add the %pythoncallback directive, which is 
+	   an improved version of %callback, ie,
+
+	     %pythoncallback(1) foo;
+	     %pythoncallback(1) A::bar;
+	     %pythoncallback(1) A::barm;
+
+	     int foo(int a) {
+	         return a;
+	     }
+  
+	     struct A 
+	     {
+	       static int bar(int a);
+	       int barm(int a);
+
+	     };
+
+             int foobar(int a, int (*pf)(int a));
+
+	   in python you can use
+
+             foo(2)
+	     foobar(2,foo)
+             A.bar(2)
+	     foobar(2,A.bar)
+          
+           ie, no additional pointer elements are created, and
+	   the original 'foo' and 'A.bar' can be used as parameters.
+
+	   In the case of member fucntion however, still you need
+	   to use the special variable Class::<fnc_name>_cb_ptr, ie:
+
+ 	     foobarm(3, a, A.barm_cb_ptr)
+	   
+	   we will try to fix this situation also, but later.  
+
+	   [Python] Add more elements from the STL library, now
+	   you can use
+
+	     import std
+	     std.cout << "hello " << 123 << std.endl
+
+	   [Python] Fix in/out return mechanism, now swig will behave
+	   as 1.3.21 but using a python list when needed. The problem
+	   is that the types std::pair,std::vector,etc, use tuples,
+	   and they interfer with the previous inout tuple type.
+
+	   By using lists we solve the conflicts, swig acts as before,
+	   but returns a list when more than one parameter are using
+	   the OUT typemap. See the new inout.i example in the
+	   test-suite.
+
+            *** POTENTIAL INCOMPATIBILITY FOR PYTHON MODULE ***
+		   
+           [Python] Much better error messages for bad arguments, now
+	   you always get the argument number where the error occurred.
+
+09/27/2004: wsfulton
+            Patch from Bill Clarke -
+            1) Warning emitted when -importall and -includeall is used together,
+               with -includeall taking precedence.
+            2) Ensure SWIGIMPORTED is always defined when a file is being
+               imported with %import. Note that this is not the same as SWIGIMPORT,
+               which gets defined in all generated wrapper files.
+
+09/26/2004: mmatus
+
+	    - add %feature("exceptionclass") to identify a class used
+	      as exception. Before swig identified and marked a class
+	      using the "cplus:exceptionclass" attribute. However, the
+	      class needed to appear on an throw() statement.  Now
+	      swig keeps trying to identify the exception classes, as
+	      before, but it also allows the user to mark a class by
+	      using the %feature explicitly. (mostly relevant for
+	      python and chicken)
+
+	    [Python]
+
+	    - fix -modern option + exceptions, which mix old class
+	      style with the new one. So, we always need to emit
+	      the "nonmodern" python code.
+
+	    - add the "python:nondynamic" feature and its handler
+
+	      now if you have
+	      
+	      %pythonnondynamic(1) A;
+	      
+	      struct A {
+	       int a;
+	       int b;
+	      };
+
+	      then, in the python side
+	      
+	      aa = A()
+	      
+	      aa.a = 1 # ok
+	      aa.b = 2 # ok
+	      aa.c = 3 # error, the class can not be extended dynamically.
+
+	    
+	    Since this is a feature, you can use
+
+	      %pythonnondynamic(1);
+
+            or 
+
+	      %pythondynamic(0); [ Note: %pythondynamic since deprecated ]
+   
+	    to force all the wrapped classes to be "nondynamic" ones.
+
+	    The default, as in regular python, is that all the wrapped
+	    classes are dynamics. So, careful with your spelling.
+
+09/14/2004: mmatus 
+	    - Support the -I- option.
+
+	    - Differentiate between %include <file> and %include "file".
+	      This fix several corner cases.
+
+	    
+	    [Python] Several patches:
+
+	    - Normalize the Lib file names: 
+		*.swg internal files, 
+		*.i   user files.
+
+	    - Fix Char[ANY] typemaps, so they also delete any extra '\0' chars,
+	      now they behave as before (1.3.21). Still, you can use
+	      the SWIG_PRESERVE_CARRAY_SIZE macro if you need to
+	      preserve the original size (see pystrbase.swg).
+
+	    - Add the Char FIXSIZE[ANY] typemaps, to preserve the
+              original C array sizes (see above). Though, you can't
+              use them yet since %apply and arrays are not working
+              together.
+
+            - Add pyfragments.swg, now the user can add fragments
+	      to override the default ones.
+
+09/10/2004: wsfulton
+            Patch from Bill Clarke which fixes spurious preprocessor bug which
+            shows on Solaris and gcc, eg:
+                Warning(202): Could not evaluate '!defined(SWIGJAVA) &&
+                !(defined(SWIGCSHARP)'
+            Also fixes a bug where '#if "a" == "b" == 1' wouldn't have worked 
+
+09/10/2004: wsfulton
+            Restored multiple build directories for the test-suite. Patch from
+            Bill Clarke.
+
+09/06/2004: wsfulton
+            Added the missing runtime.dsp Visual Studio project files for the
+            import examples to work.
+
+
+Version 1.3.22 (September 4, 2004)
+==================================
+
+09/03/2004: wsfulton
+            The swig.m4 macro for use with the Autoconf/Automake/Libtool has
+            been removed and is no longer installed. Please use the new and better
+            maintained version derived from swig.m4 in the Autoconf macro archive.
+            See http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html and
+            http://www.gnu.org/software/ac-archive/htmldoc/ac_python_devel.html.
+
+09/01/2004: wsfulton
+            [Perl] Applied patch #1019669 from Christoph Flamm. Adds support
+            for %feature("shadow") in the same way as it works in Python. This
+            enables one to override the generated shadow/proxy methods, including
+            constructors and destructors. For example:
+
+              /* Let's make the constructor of the class Square more verbose */
+
+              %feature("shadow") Square(double w)
+              %{
+                sub new {
+                  my $pkg = shift;
+                  my $self = examplec::new_Square(@_);
+                  print STDERR "Constructed an @{[ref($self)]}\n";
+                  bless $self, $pkg if defined($self);
+                }
+              %}
+
+              class Square {
+              public:
+                Square(double w);
+                ...
+              };
+
+08/31/2004: mmatus 
+	    [Python] Incompatibility reported by Bill Clarke (llib@computer.org):
+	    
+	    If you are using Sun Studio 8 (and possibly earlier
+	    versions) to compile the output produced by swig
+	    1.3.22rc1, and you are using C++ and STL templates then
+	    you need to use either "-runtime" or "-noruntime".  If you
+	    use neither of these options then you will probably get
+	    compiler errors when trying to compile the wrapper file;
+	    the error message will be like this: The name
+	    SWIG_Python_ConvertPtr[...] is unusable in static
+	    swigpy::traits_asptr[...]  If you get this error message,
+	    you need to regenerate your wrapper file using 'swig
+	    -runtime' or 'swig -noruntime'.
+
+	    You shouldn't get this problem with Sun Studio 9.
+
+            *** POTENTIAL INCOMPATIBILITY FOR PYTHON MODULE ***
+	    
+08/26/2004: wsfulton
+            [Perl] Applied #932333 from Ikegami Tsutomu. Fixes long long *OUTPUT
+            and unsigned long long *OUTPUT typemaps in typemaps.i.
+
+08/26/2004: wsfulton
+            Applied patch #857344 from Art Yerkes. Workaround for autoconf bug when
+            running 'make install'.
+
+08/26/2004: wsfulton
+            [Perl] Part of patch #982753 applied. This implements a %perlcode directive.
+            It allows one to add Perl code to the generated .pm file. Works the same 
+            as %pythoncode.
+
+08/26/2004: wsfulton
+            [Java] Fix for directors when wrapping virtual methods with exception
+            specifications that were not simple types. Previously code was generated that
+            didn't compile, for example when the exception specification was a pointer.
+
+08/25/2004: wsfulton
+            [C#] Typemap fix for methods that return char *. The CLR would incorrectly
+            delete the memory pointed to by char *. Also applied the same correction to
+            the char array typemaps.
+
+08/24/2004: wsfulton
+            Fixes for -fmicrosoft error/warning message display: 
+            - End of file (EOF) warning messages not displaying in correct format
+            - Some messages containing a file path were displaying a double backslash
+              instead of a single backslash
+
+08/23/2004: wsfulton
+            Applied patch #1011604 submitted by Charles Schwieters. Fix for 64 bit tcl
+            interpreters.
+
+08/23/2004: wsfulton
+            Fix for bug #875583 - enum forward declarations previously gave a syntax error.
+
+08/23/2004: mkoeppe
+	    [Allegro CL] Use typemaps "ffitype" and "lisptype" to determine the FFI type
+	    specifiers from the C type.  This makes it possible, for instance, to control
+	    whether a C "char" argument takes a Lisp character or a Lisp integer value.
+	    The default (taking Lisp characters) is done by these built-in typemaps:
+	      %typemap(ffitype) char ":char"; %typemap(lisptype) char "character";
+	    If char means an integer instead, use these typemaps:
+	      %typemap(ffitype) char ":char"; %typemap(lisptype) char "integer";
+
+08/22/2004: wsfulton
+            As discussed in bug #772453, the SWIG library directory is now installed
+            into a different default directory. The library used to be installed to
+            /usr/local/lib/swig1.3. It is now in the more usual architecture independent
+            directory and I have additionally used a version specific subdirectory as
+            the library will rarely work with older versions of SWIG. This release
+            will thus use /usr/local/share/swig/1.3.22 by default, which can be
+            tailored as before using './configure --swiglibdir'.
+
+08/17/2004: mkoeppe
+	    [MzScheme] Add support to create native MzScheme structures from C structures.
+	    To convert a C structure to an MzScheme structure, use the new runtime macro
+	    SWIG_NewStructFromPtr in a typemap.  Patch from Dmitriy Zavin. 
+
+08/12/2004: wsfulton
+            Patch #837715 from Ben Reser to correctly detect Python lib directory
+            on 64 bit systems.
+
+08/12/2004: wsfulton
+            [C# and Java] Prevent memory leaks in the case of early return
+            from wrapper methods using const std::string & parameters. Modified
+            Mark Traudt patch #951565.
+
+08/12/2004: wsfulton
+            Bug #943783 with patch fixes php char * out typemap NULL values.
+
+08/03/2004: Ahmon Dancy  <dancy@dancy>
+
+            [allegrocl] Additional case mode fixes.  Also, make sure
+	    foreign types are exported.
+
+07/24/2004: mkoeppe 
+	    [Guile] In -scm mode, SWIG modules now exchange their pointer type
+	    information via the Guile interpreter.  It is no longer necessary to build a
+	    runtime library or to use -noruntime and -runtime etc.
+	    
+	    The module (Swig swigrun) which was introduced in the change of 05/17/2004 is
+	    no longer automatically built.  If you need it, run SWIG on the interface file
+	    swigrun.i. 
+
+07/23/2004: wsfulton
+            [C#] Bug #917601 Mapping C++ bool fix from Mark Traudt
+
+07/23/2004: wsfulton
+            RPM fixes for latest CVS version including removal of runtime
+            library.
+
+07/23/2004: wsfulton
+            Patch #908955 from Robert H De Vries.
+            RPM file generation fix for Fedore Core 1 and Redhat AS2.1.
+
+07/12/2004: wsfulton
+            Patch #864689 from Robin Dunn:
+
+            This patch corrects two problems in the XML output of SWIG:
+             
+              1. There were often extra '/>\n' in the output.
+              
+              2. value attributes were output with '\n' in them but
+              since that is not technically legal most (all?) XML
+              parsers will strip them out. Replacing the '\n' with
+              the '&#10;' entity reference solves this as that is
+              legal and XML parsers will convert it to a '\n' when
+              reading the values back in.
+              
+              This patch also adds a new global command line option
+              that will allow the parse tree to be written out in XML
+              *after* some other language module has been run, in
+              order to be able to get extra info that the language
+              module puts in the tree. In this way the XML is a
+              post-processed version of the tree rather than a
+              pre-processed version. 
+ 
+              Command line option is -dump_xml or -xmlout <file>
+
+07/12/2004: wsfulton
+            [Java] Patch from Scott Michel to fix typesafe enums and proper enums
+            with directors.
+
+07/12/2004: wsfulton
+            HTML documentation (makechap.py) file generator missing end of line
+            patch #908951 from Robert de Vries.
+
+07/08/2004: wsfulton
+            The deprecated runtime library build has been removed. This also removes
+            the dependency on Libtool. Libtool is no longer required to build SWIG.
+            The associated -ldflags SWIG commandline option has also been removed.
+
+            The examples and test-suite testcases that used the runtime library have
+            been updated to use the replacement approach to using SWIG across 
+            multiple modules, that is they use the -noruntime and -runtime commandline
+            options, see Modules.html. Effectively they build their own runtime
+            libraries using -runtime. The examples are import and import_template.
+            The test cases are in the imports and template_typedef_import directories.
+
+            Anyone who wants the original runtime libraries can either run the test-suite
+            or build the examples and use the appropriate shared object/DLL that is
+            generated with the -runtime commandline option. For example libimports_runtime.so
+            (Python calls it lib_imports_runtime.so) is generated after running the 
+            'make imports.multicpptest' testcase in the Examples/test-suite/<lang>
+            directory. Or use libruntime.so / runtime.dll after building the import
+            examples in Examples/<lang>/import.
+
+07/07/2004: mkoeppe
+	    [Allegro CL] Convert character and string literals in constants to 
+	    CL syntax.  Fix FF:DEF-FOREIGN-CALL for mixed-case C functions.
+
+06/27/2004: wsfulton
+            [Java] New feature for Java exceptions with format %javaexception(exceptionclasses).
+            This feature is a slight enhancement to %exception and the only difference is the 
+            addition of the exception classes which are generated into a throws clause.
+            The 'exceptionclasses' is a comma separated list of classes which will be
+            added to the associated proxy method's throws clause. The 'exceptionclasses'
+            are specified like the exception classes in the 'throws' attribute in the
+            typemaps. This feature should be used for correctly handling checked exceptions
+            thrown from JNI code. For example:
+
+              %javaexception("java.lang.Exception") throwException %{
+                ... convert a std::logic_error into a java.lang.Exception using JNI code ...
+              %}
+
+              #include <stdexcept>
+              void throwException() {
+                throw std::logic_error("Logic error!");
+              }
+
+            will generate a method with a throws clause in the module class:
+
+              public static void throwException() throws java.lang.Exception { ... }
+
+06/27/2004: wsfulton
+            [C#] New %csconstvalue(value) feature directive for use with constants and
+            enums. This works the same way as %javaconstvalue. For C#, this directive
+            is the only way that one can fix wrapping of C/C++ enums with proper C#
+            enums if the enum item's initialiser cannot compile as C# code. This is
+            because Java enums can use a call into C code to initialise the enum item,
+            whereas in C#, the enum value must be a compile time constant. That is,
+            using %csconst(0) cannot be used in C# to initialise the C# enum item via
+            a PINVOKE call.
+
+06/27/2004: wsfulton
+            [Java] New %javaconstvalue(value) feature directive for use with constants and
+            enums. Sometimes the use of %javaconst(1) will produce code that won't compile
+            under Java. If a compile time constant is required, %javaconst(0) is not an
+            option. The %javaconstvalue directive achieves this goal and the value specified
+            is generated as Java code to initialise the constant.  For example:
+
+              %javaconst(1);
+              %javaconstvalue(1000) BIG;
+              %javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE;
+              %javaconstvalue(10) bar;
+              %{
+                const int bar = 10;
+              %}
+              %inline %{
+                #define BIG 1000LL
+                #define LARGE 2000ULL
+                enum Foo { BAR = ::bar };
+              %}
+
+            Generates:
+
+              public interface exampleConstants {
+                public final static long BIG = 1000;
+                public final static java.math.BigInteger LARGE = new java.math.BigInteger("2000");
+              }
+              public final class Foo {
+                public final static Foo BAR = new Foo("BAR", 10);
+                ...
+              }
+
+            Previously, none of BIG, LARGE or BAR would have produced compileable code
+            when using %javaconst(1).
+
+06/27/2004: wsfulton
+            %feature enhancements. Features can now take an unlimited number of attributes
+            in addition to the feature name and feature value. The attributes are optional 
+            and are much the same as the typemap attributes. For example, the following
+            specifies two optional attributes, attrib1 and attrib2:
+
+             %feature(featurename, attrib1="attribval1", attrib2="attribval2") name "val";
+             %feature(featurename, val, attrib1="attribval1", attrib2="attribval2") name;
+
+06/27/2004: wsfulton
+            %feature improvements for the syntax that takes the feature value within the
+            %feature() brackets. The value specified is no longer restricted to being just
+            a string. It can be a string or a number. For example, this is now acceptable
+            syntax:
+              %feature("featurename",20.0);
+            whereas previously it would have to have been:
+              %feature("featurename","20.0");
+            Useful for features that are implemented as a macro, for example:
+              #define %somefeature(value)      %feature("somefeature",value)
+            These will now work accepting either a string or a number:
+              %somefeature("Fred");
+              %somefeature(4);
+
+06/06/2004: wuzzeb (John Lenz)
+            [Chicken, Guile]
+             - Created the Examples/test-suite/schemerunme directory, which holds all the
+	       runme scripts for guile and chicken (and possibly mzscheme...).  The guile
+	       and chicken _runme files then (load "../schemerunme/foo.scm").
+             - In chicken module, fix a few bugs invlolving dynamic casts.
+
+06/03/2004: wsfulton
+            Patch to fix wrapping of templated methods. ISO compliant compilers, like
+            Comeau and GCC-3.4.0, don't like the template specifier that SWIG was generating
+            when calling the method. This fix may break some non standard compliant compilers,
+            for example, Sun workshop compilers prior to version 6.2.p2. Patch submitted
+            by Bill Clarke.
+
+06/03/2004: wsfulton
+            [Java, C#] Undocumented special variable $imclassname removed.
+            New special variable $module is replaced by the module name, as specified
+            by %module or -module commandline option. $imclassname can be created from $module.
+
+06/03/2004: wsfulton
+            [C#] Same as for Java below. The new typemaps are named differently, namely,
+            csbody and csbody_derived. The deprecated typemaps are csgetcptr and
+            csptrconstructormodifiers.
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+06/03/2004: wsfulton
+            [Java] Typemap changes for the Java proxy / typewrapper and enum classes. A new
+            typemap called javabody contains the essential support code for generation into the body
+            of these classes. There is also a new javabody_derived typemap which is used instead for
+            wrapped classes that have a wrapped base class. The code is basically, the getCPtr()
+            method and swigCPtr and swigCMemOwn member variables. These used to be hard coded
+            with no way to modify the code. The introduction of this typemap makes it possible for
+            the user to tailor nearly every aspect of the code generation.
+            The exception now is the code for director classes.
+
+            The javagetcptr and javaptrconstructormodifiers typemaps are deprecated and are
+            no longer used as the code that these generated can be put in the more flexible
+            javabody and javabody_derived typemaps.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+            The following macros contributed by Scott Michel may help you upgrade if you have used
+            the javagetcptr typemap:
+
+                /* Utility macro for manipulating the Java body code method attributes */
+                %define SWIGJAVA_ATTRIBS(TYPENAME, CTOR_ATTRIB, GETCPTR_ATTRIB)
+                %typemap(javabody) TYPENAME %{
+                  private long swigCPtr;
+                  protected boolean swigCMemOwn;
+
+                  CTOR_ATTRIB $javaclassname(long cPtr, boolean cMemoryOwn) {
+                    swigCMemOwn = cMemoryOwn;
+                    swigCPtr = cPtr;
+                  }
+
+                  GETCPTR_ATTRIB static long getCPtr($javaclassname obj) {
+                    return (obj == null) ? 0 : obj.swigCPtr;
+                  }
+                %}
+
+                %typemap(javabody_derived) TYPENAME %{
+                  private long swigCPtr;
+
+                  CTOR_ATTRIB $javaclassname(long cPtr, boolean cMemoryOwn) {
+                    super($moduleJNI.SWIG$javaclassnameUpcast(cPtr), cMemoryOwn);
+                    swigCPtr = cPtr;
+                  }
+
+                  GETCPTR_ATTRIB static long getCPtr($javaclassname obj) {
+                    return (obj == null) ? 0 : obj.swigCPtr;
+                  }
+                %}
+                %enddef
+
+                /* The default is protected getCPtr, protected constructor */
+                SWIGJAVA_ATTRIBS(SWIGTYPE, protected, protected)
+
+                /* Public getCPtr method, protected constructor */
+                %define PUBLIC_GETCPTR(TYPENAME)
+                SWIGJAVA_ATTRIBS(TYPENAME, protected, public)
+                %enddef
+
+                /* Public getCPtr method, public constructor */
+                %define PUBLIC_BODYMETHODS(TYPENAME)
+                SWIGJAVA_ATTRIBS(TYPENAME, public, public)
+                %enddef
+
+06/03/2004: wsfulton
+            [Java, C#] The contents of the class modifier typemaps and pragmas have changed.
+            They must now include the class type. Previously 'class' was hard coded.
+            This change enables flexibility into what type of class is generated,
+            for example the proxy class could be an interface instead of a class.
+
+            For Java this affects the javaclassmodifiers typemap and the jniclassclassmodifiers
+            and moduleclassmodifiers pragmas.
+
+            For C# this affects the csclassmodifiers typemap and the imclassclassmodifiers
+            and moduleclassmodifiers pragmas.
+
+            Unless you have overridden the default versions of these typemaps or pragmas, you
+            shouldn't be affected. However, if you have, upgrading is easy, for example
+
+                class Foo {};
+                %typemap(javaclassmodifiers) Foo "public final"
+
+            must now be:
+
+                class Foo {};
+                %typemap(javaclassmodifiers) Foo "public final class"
+
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+05/31/2004: wsfulton
+            Fix for C++ exception specifications that are references. Problem reported by
+            Oren Miller. Also improves the generated exception declarations in the
+            catch handler for pointers - a pointer is used instead of a reference to
+            a pointer. Added default throws typemaps for SWIGTYPE &, SWIGTYPE * and
+            SWIGTYPE[ANY] (Java and C#).
+
+05/31/2004: wsfulton
+            [Java, C#] Some minor typesafe enum improvements, including storing the name of
+            the enum item. The toSring() / ToString() methods are overridden to return this name.
+
+05/30/2004: wuzzeb (John Lenz)
+            [Chicken] 
+	     - Update how examples and the test suite are built.
+	     - Symbol names are no longer converted to lower case
+	     - Added union_runme.ss, which was copied and modified from the guile module
+
+05/26/2004: lballabio (Luigi Ballabio)
+            Committed on behalf of Marcelo (who still has problems with 
+	    the SourceForge CVS.)
+
+	    Added Python typemaps for FILE* with (Python-only) test.
+
+5/24/2004:  dancy
+
+	* Allegro CL module:  Now using some macros (defined in
+	Lib/allegrocl/allegrocl.swg), swig-defconstant and swig-defun, for
+	defining constants and foreign functions.  This makes the
+	generated file a bit neater.    
+
+	Now strips a layer of parenthesis from constants.
+
+	Uses (* :void) instead of :foreign-address now.
+
+05/20/2004: wsfulton
+            Unnamed enum global variables are now supported in addition
+            to the recently added support for unnamed enum member variables.
+            For example:
+
+                struct Foo {
+                  enum { enum1, enum2 } MemberInstance;
+                };
+                enum { enum3, enum4 } GlobalInstance;
+
+            The int typemaps are used for wrapping the get/set accessor methods.
+            If the sizeof an enum is not the same size as an int then setting the
+            variable will silently do nothing as the casts cannot be easily and portably
+            generated. If you need to solve this highly obscure situation, write
+            the assignment using the %exception feature.
+
+05/20/2004: wsfulton
+            [C#] C# enum wrapping mods. Similar to the Java module, enums can be wrapped using
+            one of 3 approaches:
+
+            1) Proper C# enums - use %include "enums.swg"
+            2) Typesafe enums - use %include "enumtypesafe.swg"
+            3) Simple constant integers (original approach) - use %include "enumsimple.swg"
+
+            See each of these files for further details. Each of these files use typemaps
+            and a new feature to control the generated code. The feature is:
+
+                %csenum(wrapapproach);
+
+            where wrapapproach should be one of: "proper", "typesafe", "typeunsafe" or "simple".
+            [No implementation deemed necessary for type unsafe enums].
+
+            The default approach is proper C# enums. Anonymous enums are always wrapped by
+            constant integers. 
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+05/20/2004: wsfulton
+            [Java] Java enum support added. There are now 4 ways in which enums can be wrapped:
+
+            1) Proper Java enums - use %include "enums.swg"
+            2) Typesafe enums - use %include "enumtypesafe.swg"
+            3) Type unsafe enums (constant integers) - use %include "enumtypeunsafe.swg"
+            4) Simple constant integers (original approach) - use %include "enumsimple.swg"
+
+            See each of these files for further details. Each of these files use typemaps
+            and a new feature to control the generated code. The feature is:
+
+                %javaenum(wrapapproach);
+
+            where wrapapproach should be one of: "proper", "typesafe", "typeunsafe" or "simple".
+            The default typemaps will handle enums that may or may not have specified initial
+            values, for example ten is specified:
+
+                enum Numbers { zero, ten(10) };
+
+            However, the amount of generated Java code can be cut down, by modifying these typemaps
+            if none of the enums have initial values (proper Java enums and typesafe enums approach).
+            
+            The default approach is typesafe enums. Anonymous enums are always wrapped by
+            constant integers. 
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+05/11/2004: wsfulton
+            [Java, C#] Fix bug using %rename on enum items and when using
+            %javaconst(1) / %csconst(1)
+            For example, the following used to generate code that wouldn't compile:
+
+                %rename(Obj) Object;
+                enum Grammar { Subject, Object };
+
+04/28/2004: wsfulton
+            [Java, C#] Minor fixes when using combinations of the 
+            javainterfaces, javabase, csinterfaces and csbase typemaps.
+
+05/18/2004: wsfulton
+            [Java] JVM link failure on some systems fixed when using std_vector.i.
+            Also adds default vector constructor for use from Java.
+
+05/17/2004: mkoeppe (Matthias Koeppe)
+
+	    [Guile] New runtime functions SWIG_PointerAddress,
+	    SWIG_PointerType, SWIG_IsPointerOfType, SWIG_IsPointer.
+
+	    [Guile] In -scm mode, wrap several SWIG runtime functions
+	    and export them into the module (Swig swigrun).  The
+	    runtime module is now built with "module" linkage.
+
+	    [Guile] GOOPS proxy objects now also print the pointer
+	    address of the C object.
+
+05/14/2004: lyle
+            Added Kou's patch for the Ruby %import directive so that modules
+            with "nested" names are handled properly. Consider an interface
+            file foo.i that has this %module declaration at its top:
+
+                %module "misc::text::foo"
+
+            Now consider another interface file spam.i that imports foo.i:
+
+                %import foo.i
+            
+            Before this patch, this would result in the following code being
+            generated for spam_wrap.c:
+
+                rb_require("misc::text::foo");
+
+            With this patch, however, you'll get the correct path name
+            for the call to rb_require(), e.g.
+
+                rb_require("misc/text/foo");
+
+            See SourceForge Bug #928299.
+
+05/12/2004: wsfulton
+            Patch for emitting directors when %feature("director") specified
+            for a class with no virtual methods, but does have a virtual destructor.
+            Submitted by Kevin Smith.
+
+05/06/2004: mkoeppe (Matthias Koeppe)
+	    New SWIG runtime function SWIG_TypePrettyName, which 
+	    returns an unmangled type name for a swig_type_info
+	    object. 
+
+	    [Guile]: Use it for printing pointer objects.
+
+05/03/2004:  dancy (Ahmon Dancy)
+
+	* Lib/allegrocl/allegrocl.swg:  Updated comments about identifer
+	conversion.  
+
+	* Sources/Modules/allegrocl.cxx:  Register /dev/null for "header"
+	target.   Also, disregard "const" qualifiers during type
+	conversion.  
+
+	
+05/02/2004: wuzzeb (John Lenz)
+	    [Chicken] Fix bug 782468.
+	    To fix this bug, the runtime code has been rewritten, and
+	    pointers are now represented as a C_SWIG_POINTER_TYPE.
+
+	    Chicken version > 1.40 is now required!
+
+	    * Typemap incompatibility:  typemaps no longer use chicken_words.
+	      If a typemap needs some space, it should just call C_alloc
+
+	    * argout typemaps no longer use the /* if ONE */ construct to
+	      build an output list.  A SWIG_APPEND_VALUE macro, exactly like
+	      guile and mzscheme is now used.
+
+04/25/2004: mkoeppe (Matthias Koeppe)
+	    [Guile] In the generated GOOPS code, don't create methods
+	    that would not specialize any arguments; simply re-export
+	    the primitive functions.  (This is a performance
+	    optimization which reduces load time and execution time.)
+
+	    [Guile] In -gh mode, fix the "too many initializers" error
+	    which was caused by an incompatible swig_type_info layout.
+
+	    [Guile] The typemap for FILE * in ports.i now also accepts
+	    a regular FILE * pointer object.  Also a bug with Scheme
+	    file ports that are open for input and output has been
+	    fixed. 
+
+04/25/2004: wsfulton
+            Change entry 03/21/2004 revoked. The change introduced another
+            inconsistency (reference typemaps beings used instead of
+            pointer typemaps for member variables as well as static
+            member variables and global variables for some languages,
+            but only for C++ and not C). This would break user's current
+            typemaps and introduce further inconsistencies. Alternative
+            solution required and being discussed.
+
+04/10/2004: mmatus (Marcelo Matus) 
+	    
+	    Added the -directors flag. This enables the director
+	    mode for the interface and all the classes that
+	    don't set the "feature:nodirector" explicitly.
+
+	    You can use this in your module if you want to use the
+	    director feature in all your classes, but it is most
+	    intended for testing purposes, like:
+
+	      make check-python-test-suite SWIG="../../../swig  -directors"
+	      make check-ruby-test-suite SWIG="../../../swig  -directors"
+	      make check-java-test-suite SWIG="../../../../swig  -directors"
+
+	    These commands will run the entire test-suite using
+	    directors, and not only the specific 'directors_*'
+	    cases. This should be done from time to time.
+
+04/10/2004: mmatus (Marcelo Matus) 
+	    
+	    [python] Added support for std::wstring and wchar_t,
+	    for compiler and python versions that support them.
+	    
+	    When needed, use 
+
+	     %inlcude std_string.i      // 'char' strings
+	     %inlcude std_wstring.i     // 'wchar_t; strings
+	    
+
+04/10/2004: mmatus (Marcelo Matus) 
+	    
+	    [python] Fix the default behaviour (seg. fault) when an
+	    inplace operator (+=,-=,...) was wrapped, as reported by
+	    Lucriz (lucriz@sitilandia.it), when the most common
+	    form was used:
+
+                   A&  A::operator+=(int i) { ...; return *this; }
+                  ^^^^                                    ^^^^^^
+	    
+
+	    ie, an object is returned and its contains the same 'this'
+	    value than the input object, which is deleted after the
+	    operation "a += b", leaving the result with no real
+	    object, but a seg. fault.
+
+	    To fix it, we needed to introduce a new feature and use an
+	    old one:
+
+               %feature("self:disown") A::operator+=;
+               %feature("new") A::operator+=;
+	    
+	    here, "self:disown" disable the ownership of the 'self'
+	    or input object, and the "new" feature transfers the
+	    ownership to the result object.
+	    
+	    The feature/solution could also be used in other languages
+	    that use gc and implement the inplace operators, or other
+	    operators, in a similar way.
+
+            *** POTENTIAL INCOMPATIBILITY FOR Python MODULE ***
+
+	    If you already are using the inplace operators in python,
+	    and you implemented some kind of workaround to the problem
+	    fixed here, it is possible you could end with 'free'
+	    objects that never get deleted. If that is the case, and
+	    you want to disable the current fix, use:
+
+               %feature("self:disown","") A::operator+=;
+               %feature("new","") A::operator+=;
+
+
+04/07/2004: cheetah (William Fulton)
+            [C#] C++ enums are no longer wrapped by integers, they are now wrapped by 
+            C# enums. For Example, given C++:
+
+                enum AnEnum { foo, bar };
+                typedef AnEnum AnEnumeration;
+                void something(AnEnum e, AnEnumeration f);
+
+            The following is generated:
+
+                public enum AnEnum {
+                  foo,
+                  bar
+                }
+                public static void something(AnEnum e, AnEnum f) {...}
+
+            Note that a global enum like AnEnum above is generated into its own
+            file called AnEnum.cs. Enums defined within a C++ class are defined
+            within the C# proxy class. Some of the typemaps for modifying C# proxy
+            classes also work for enums. For example global enums can use
+
+                %typemap(csimports) to add in extra using statements.
+
+            Global enums and class enums can use
+
+                %typemap(csclassmodifiers) to make the enum private, public etc.
+                %typemap(csbase) to change the underlying enum type (enum base)
+
+            If we add this for the above example:
+
+                %typemap(csclassmodifiers) AnEnum "protected"
+                %typemap(csbase) AnEnum "long"
+
+            the following is generated:
+            
+                protected enum AnEnum : long {
+                  foo,
+                  bar
+                }
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+04/07/2004: cheetah (William Fulton)
+            Seg fault fix for empty enums, like
+                enum Foo {};
+
+03/21/2004: mmatus
+            [Note: this change revoked on 04/25/2004]
+	    [Python] Makes the following 'var' cases more uniform:
+
+                std::string ga;
+ 
+                struct A {
+                  static std::string sa;
+                  std::string ma;
+                };
+
+
+            now the three variables (ga, sa, ma) can be assigned as:
+
+
+                  cvar.ga = "hello";
+                  A.sa = "hello";
+                  a.ma = "hello";
+
+            ie, now 'ma' will also use a std::string typemap 'in' if
+            defined, before it was only accepting a 'p_std_string'
+            pointer.  Note, however, that 'ma' will not use the
+            'varin/varout' typemaps (that probably could be more
+            natural), but it will pick up the 'in' typemap for const
+            std::string& (which is easier).
+
+	    The changes in cwrap.c and lang.cxx will probably fix the
+	    behaviour in other languages that do not overload the
+	    membervarHandler method "too much".
+ 
+            
+03/21/2004: mmatus
+	    [Python] Disabling the default instantiations like:
+
+	      %template() std::pair<int,int>;
+
+            for all the primitive types and STL containers/classes.
+	    They are expensive, specially for pair and map, and the
+	    previous behaviour also requires the user to perform
+	    manual instantiations. Still, if the speed difference is
+	    not important, it can be re-enabled by defining the macro
+	    SWIG_STD_DEFAULT_INSTANTIATION (see std_common.i).
+
+	    Also, normalizing the INPUT/OUTPUT/INOUT typemaps. Now
+	    they use the same conversors than the rest of the
+	    typemaps, and you can use them for std::pair, std::string
+	    and all the other STL types, like in:
+
+	      void p_inoutd(std::pair<double, double> *INOUT);
+
+	    Added the attribute.i and implicit.i files with macros to
+	    transform functions pairs like 'set_x'/'get_x' 
+	    (or 'T& x()'/'const T& x() const') into an attribute,
+	    and allowing the use of implicit constructors in typemaps
+	    (see the files for more details).
+
+03/21/2004: mkoeppe
+	    [Guile] Fix the documentation strings of functions with
+	    anonymous arguments.
+
+03/18/2004: mmatus
+	    [Python] More general std_string.i interface.
+	    Now you can wrap it using
+
+	      %template(string) std::basic_string<char>;
+
+            and use the std::string as a base class:
+
+	      struct A : std::string {
+              };
+
+	    But more important, swig will recognize 
+	    both std::basic_string<char> and std::string as
+	    the same type.
+
+03/16/2004: mmatus
+	    Previously added, but not mentioned before:
+
+	    - friend declaration support, swig now emits a global
+	      function in the same class scope.
+
+	    - ref/unref features: to mix ref counting C++ classes
+	      and native script ref counting mechanisms (like in python).
+	    
+	      Use it like:
+
+ 	        %feature("ref")   RCObj "$this->ref();"
+                %feature("unref") RCObj "$this->unref();"
+
+	      And the class RCObj, and all the derived ones, will
+	      perform the right ref/unref calls when a new pointer  
+	      is returned to the target language, or when the target
+	      language attempts to delete the object.
+	      
+	      See the refcount.i file in the test-suite for more
+	      details.
+
+	    
+03/16/2004: mmatus
+	    [Python] Using the new %fragment support, major rewrote 
+	    of the python swig library, including:
+
+	    - Almost automatic template/typemap instantiation for
+	      the STL components. For example, now you can write:
+
+		   %template(vector_i) std::vector<int>;
+
+              and a specialized vector_i class is emitted with all
+	      the needed typemaps. No need to use the old
+	      'specialize_vector' macros.
+
+	      Note you can also define
+
+	          %template(matrix_i)   std::vector<std::vector<int> >;
+	          %template(vector_pii) std::vector<std::pair<int,int> >;
+
+	    - The empty template instantiation 
+ 	 
+           	  %template() std::vector<int>;
+
+	      defines the vector typemaps, but no proxy class. For all the
+              fundamental types, the empty template instantiation are
+              defined, so, you can say
+
+	      %include std_vector
+
+	      int func(const std::vector<int>& a);
+	      
+	      where the proper typemap is applied to 'a', but no
+	      std::vector<int> proxy is generated.
+	      
+
+            - All the STL containers present a more uniform behavior and
+	      more complete interface declaration. The following are 
+	      now supported:
+
+		  std::vector<T>
+		  std::list<T>
+		  std::deque<T>
+		  std::set<T>
+		  std::multiset<T>
+		  std::map<T>
+		  std::multimap<T>
+              
+              not a container, but also supported:
+
+		  std::pair<T,U>
+
+              also, more typemaps are defined for all of them,
+	      including varin, varout, typecheck, etc.
+
+            - Initial attempt to implement the STL containers
+              considering allocators, ie:
+
+	          std::vector<T,A>			
+
+	      it is partially working, but it is just a workaround
+	      while swig improves its template type support.
+	      
+	      
+	     Please test with your particular setup. It seems to be
+	     working with g++ 3.2.2, g++ 2.96, Intel icc and SGI CC
+	     compilers, plus python 1.5.2, 2.0 and 2.3, but since
+	     we are using templates, there is a chance you can find
+	     some problems when using with an old C++ compiler.
+
+03/16/2004: mmatus
+
+            - Allowing the empty %template directive, such as
+
+                 %template() std::vector<int>;
+
+	      to process the class "typedef"s and "typemap"s. Before
+	      only the internal "typedef"s were processed.
+
+              This makes possible to emit the default in/out
+              typemaps without the need of wrapping an specialized
+              vector instance.
+
+	    - Adding the preprocessor extension #@ which mangles the
+              following macro argument, like in:
+
+                #define macro(X)  #@X
+                macro(int)         -> int
+                macro(std::string) -> std_s_s_string
+                
+	    - Fragments can now be "type specialized", as the typemaps. The
+	      syntax is as follows
+ 
+                %fragment("name","header") 
+                  { /* a type independent fragment (old syntax) */ }
+                %fragment("name" {Type}, "header") 
+                  { /* the fragment is type dependent */}
+ 
+              Now fragments can also be used inside templates: 
+
+                template <class T>
+                struct A {
+                   %fragment("incode"{A<T>},"header") {
+		      /* 'incode' specialized fragment */
+		   }
+ 
+		   %typemap(in,fragment="incode"{A<T>}) {
+		      /*
+		         here we use the 'type specialized' 
+                         fragment "incode"{A<T>}
+                      */
+		    }
+                };
+			     	
+
+03/11/2004: cheetah (William Fulton)
+            [Java] Director bug which meant that some virtual functions overridden in
+            Java were not being called on some operating systems. Bug reported and fixed
+            by Robert de Vries and Scott Michel.
+
+03/02/2004: mkoeppe (Matthias Koeppe)
+	    [Guile] In -scm mode, don't forget to check the type of string arguments.
+
+02/24/2004: cheetah (William Fulton)
+            [C#] New commandline option -namespace <name>. This allows one to specify
+            a C# namespace into which all C# classes are generated.
+
+02/23/2004: mkoeppe (Matthias Koeppe) 
+	    [MzScheme] Use FUNC_NAME rather than a bogus typemap variable for signalling
+	    errors.  Call scheme_wrong_type with a zero-based argument number.  
+	    Reported by Ondrej Pacovsky, SF #902621.
+
+	    [Guile] Define FUNC_NAME also in the dispatch wrapper for overloaded
+	    functions.  Patch by John Lenz, SF #896255.
+
+02/22/2004: mkoeppe (Matthias Koeppe)
+	    [Guile] In -scm mode, don't try to invoke a null destructor function.
+
+02/20/2004: cheetah (William Fulton)
+            Fixes so that the SWIG source will compile using the Digital Mars Compiler
+            (formerly Symantic compiler) on Windows. Submitted by Scott Michel.
+
+02/13/2004: mkoeppe (Matthias Koeppe)
+	    [MzScheme] New command-line argument -noinit.  Use it for building
+	    the runtime library, where we don't want to define the functions
+	    scheme_initialize etc.  Reported by Tim Brown, SF #891754.
+
+	    [MzScheme] Don't produce invalid C code when invoked with the
+	    -declaremodule option.  Reported by Tim Brown, SF #891108.
+	    
+	    [Guile] Build the runtime library with passive linkage, to rename
+	    the SWIG_init function uniquely.
+
+02/12/2004: cheetah (William Fulton)
+            [Java, C#] Patch submitted by Bill Hoffman which prevents SWIG from crashing
+            when a file for the typewrapper class cannot be opened.
+
+02/11/2004: cheetah (William Fulton)
+            [Java, C#] Overloading changes:
+              - Methods which are overloaded in const only no longer generate Java
+                code that won't compile - the first method parsed is used and a
+                warning is displayed. Note that this behaviour is slightly different
+                to the scripting languages which always uses the non-const method.
+              - Warning messages 509 and 512 replaced by new warning number 516, which 
+                is more relevant to these statically typed languages as the overloaded
+                methods aren't 'shadowed', they are ignored.
+
+01/23/2004: mkoeppe (Matthias Koeppe)
+	    [Guile] Replace the "known_classes" hash table by a node
+	    attribute.  Methods of classes in C++ namespaces now get
+	    the proper specializer in the GOOPS declaration.
+	    Reported by rm@mh-freiburg.de.
+
+01/23/2004: mkoeppe (Matthias Koeppe)
+	    [Guile] Uniquify the argument names in GOOPS shadow method
+	    declarations.  Reported by rm@mh-freiburg.de.
+
+01/21/2004: sunshine (Eric Sunshine)
+            Revived the NextStep port of SWIG.
+
+            Fixed fatal problem in DohStrstr() caused by difference in strstr()
+            implementation which made %apply become entirely dysfunctional.  On
+            NextStep, strstr("foo","") evaluates to NULL; whereas, on modern
+            platforms, it evaluates to "foo".  %apply relies extensively upon
+            strstr("foo","") evaluating to non-NULL, therefore it failed
+            catastrophically when faced with NextStep's strstr().
+
+            Added `bool' check to configure.in since NextStep's C++ compiler
+            does not supply this type.  swig.h now fakes up `bool' if needed.
+
+            Worked around NextStep C++ compiler bug in which C++ code is
+            disallowed inside extern "C" functions.  This problem affected all
+            language modules, since they publish hook functions of the form:
+                extern "C" Language *swig_foo(void) { return new FOO(); }
+            Fixed by creating a C++ wrapper:
+                static Language *new_swig_foo() { return new FOO(); }
+                extern "C" Language *swig_foo(void) { return new_swig_foo(); }
+
+            Ensured that Swig_copy_string() is used in place of strdup() since
+            NextStep does not supply strdup().
+
+            Fixed detection of Ruby library name and location in configure.in.
+            Problem 1: Assumed that library always resided in Ruby's "archdir",
+            which was correct for Ruby 1.6.x, but which is incorrect for Ruby
+            1.8.x, in which case the library normally resides in Ruby's
+            "libdir".  Problem 2: Assumed that the library could always be
+            linked via "-l"+RUBY_INSTALL_NAME (where RUBY_INSTALL_NAME
+            typically is "ruby"), however this failed for platforms, such as
+            NextStep, which do not support shared libraries.  In this case, the
+            static library name in 1.8.x is libruby-static.a, thus
+            -lruby-static is required.  The new logic works correctly for
+            static and shared libraries for 1.6.x and 1.8.x.
+
+            Fixed detection of Perl CFLAGS in configure.in for NextStep.
+            Detection code extracted CFLAGS from Perl's %Config hash but
+            neglected to add a newline to the value before passing it through
+            `sed'.  NextStep's ancient `sed' discards input which is not
+            terminated with a newline, thus Perl CFLAGS always evaluated to the
+            empty string.
+
+01/16/2004: cheetah (William Fulton)
+            Tidy up in the exception handling code that is generated when
+            C++ exception specifications are wrapped with the throws typemap.
+            This redundant code is no longer generated:
+
+                catch(...) {
+                    throw; 
+                }
+
+01/12/2004: wsfulton on behalf of mmatus (marcelo matus) 
+            if a method uses %exception and the method requires the use
+            of the throws typemap, the code in a throws typemap will be
+            generated inside the try body. For example:
+
+              %exception method {
+                try {
+                  // method action 
+                  $action
+                } catch (int i) {
+                  // method int catch handler
+                } catch (...) {
+                  // method generic catch handler
+                }
+              }
+              %typemap(throws) Except %{
+                // throws typemap Except catch handler
+              %}
+
+              %inline %{
+              class Except {};
+              void method(int i) throw (Except);
+
+            Will generate:
+
+              {
+                  try {
+                      // method action 
+                      try {
+                          method(arg1);
+                      }
+                      catch(Except &_e) {
+                          // throws typemap Except catch handler
+                          
+                      }
+                      
+                  } catch (int i) {
+                      // method int catch handler
+                  } catch (...) {
+                      // method generic catch handler
+                  }
+              }
+
+
+            As can be seen, the inner try catch block is for the throws typemaps.
+            Previously, this was reversed so that the inner try catch block
+            was the %exception code. In the example above, it would have been
+            impossible to catch Except as the catch all (...) would catch the
+            exception instead.
+
+Version 1.3.21 (January 11, 2004)
+==================================
+01/10/2004: cheetah (William Fulton)
+            The output format for both warnings and errors can be selected for
+            integration with your favourite IDE/editor. Editors and IDEs can usually
+            parse error messages and if in the appropriate format will easily take you 
+            directly to the source of the error. The standard format is used by 
+            default except on Windows where the Microsoft format is used by default.
+            These can be overridden using command line options, for example:
+
+                $ swig -python -Fstandard example.i
+                example.i:4: Syntax error in input.
+                $ swig -python -Fmicrosoft example.i
+                example.i(4): Syntax error in input.
+
+01/09/2004: beazley
+            Fixed [ 871909 ] simple namespace problem.
+            This was a problem using anonymous structures in a namespace.
+            For example:
+
+                namespace ns {
+                   typedef struct  {
+                      int n;
+                   } S;
+                };
+
+            Reported by Josh Cherry.
+
+01/09/2004: beazley
+            Fixed some broken Perl examples.
+
+12/28/2003: cheetah (William Fulton)
+            [Java and C#] Fixes for wrapping covariant (polymorphic) return types.
+            For example:
+
+                struct Base {
+                  virtual ~Base();
+                  virtual Base* copy() const = 0;
+                };
+                struct Derived : Base {
+                  virtual Derived* copy() const;
+                };
+
+            The Derived::copy proxy method returns Base not Derived. A warning is issued
+            about this. Previously the pointer used by the proxy class was incorrectly
+            treated as a Base* instead of a Derived*.
+
+12/18/2003: cheetah (William Fulton)
+            Fix so that Windows paths are displayed correctly when reporting errors.
+            An error previously would have been shown something like:
+
+              .?xample.i:14: Syntax error in input.
+
+            instead of:
+
+              .\example.i:14: Syntax error in input.
+
+
+Version 1.3.20 (December 17, 2003)
+==================================
+
+12/17/2003: beazley
+            Last minute modifications.   Perl5 module now generates shadow classes
+            by default like all of the other modules.  PHP4 wrappers no longer
+            include "config.h". 
+
+12/14/2003: beazley
+            Weakened warning message related to constructor names so that an
+            unusual nested-class wrapping technique would work again (apparently
+            it worked in some older SWIG releases).   For example:
+
+               class Scope {
+                   class ClassA;
+                   class ClassB;
+               };
+               class Scope::ClassA {
+               ...
+               };
+               class Scope::ClassB {
+               ...
+               }
+
+            Note:  There is still some odd interaction with the SWIG symbol
+            table/type system that will need to be looked at in a future release.
+            Reported by Gustavo Niemeyer.
+
+
+12/11/2003: cheetah (William Fulton)
+            [Java] Protected class methods are wrapped as protected Java methods 
+            when using the dirprot director feature. This can be changed using
+            %javamethodmodifiers to something else should the need arise, for
+            example, private or package access.
+
+12/11/2003: cheetah (William Fulton)
+            [Java, C#] 
+            %javamethodmodifiers (Java) and %csmethodmodifiers (C#) operate slightly 
+            differently. Previously this feature had to be present to set the method
+            modifiers. Now it is only used if it exists for the method being wrapped.
+            The default is "public" as previous however, when wrapping protected
+            director methods it is "protected". This change will not affect existing
+            use of the %javamethodmodifiers or %csmethodmodifiers.
+
+12/11/2003: mmatus (Marcelo Matus)
+
+	    This fix some recurring reports about keywords not been
+	    properly identified and warned, and it solves the problem
+	    of how to add a test file to the test-suite such that it
+	    doesn't use any keyword of all the supported languages
+	    (and doing it without compiling the test for all the
+	    supported languages, thing that is not always possible,
+	    and without requiring you to know all the supported
+	    language keywords, thing that is always impossible).
+
+	    So these are the changes globally speaking:
+
+	    - Uniform the definition of the keyword warnings through
+	      the supported languages: all the languages has now a
+	      separate file that defines the keywords or bad names:
+
+		  python/pythonkw.swg
+		  chicken/chickenkw.swg
+                  ....
+
+	    - Added keyword list for most of the languages that didn't
+	      have one (using the new separated file).
+		    	    
+	    - Added the "All keywords" warning support: -Wallkw option.
+
+              This option allows you to include all the known keywords
+	      for all the supported languages, and can be used as:
+
+                 swig -Wallkw ....
+	    
+	      This will help to the process of adding a test-suite
+	      file that can be compiled in all the swig supported
+	      languages, and it will be also helpful for users who
+	      want to create multi-language libraries.
+	    
+	    And these are the detailed changes (mostly file addition):
+
+	    - For the languages that already have some sort of keyword
+	      warning list, move it to an external languagekw.swg
+	      file, ie:
+	    
+	         move keywords from python.swg -> pythonkw.swg
+	         move keywords from chicken.swg -> chickenkw.swg
+	         move keywords from tcl8.swg -> tclkw.swg
+ 
+              and re-include languagekw.swg from language.swg.
+	    
+	    - For the language that didn't have a keyword list, and
+	      for the ones that I could find a list, add the
+	      languagekw.swg file, ie:
+
+                 csharp/csharpkw.swg
+                 java/javakw.swg
+                 php4/phpkw.swg
+		 pike/pikekw.swg	 
+		 ruby/rubykw.swg
+
+
+              also add a line in language.swg to include
+	      languagekw.swg, but now it is commented!!!, like in
+	      java.swg:
+
+                  /* java keywords */
+                  /* please test and activate */
+                  //%include "javakw.swg"
+
+	      ie, there will be no change in how swig runs normally
+	      until the language maintainer test and uncomment that
+	      line.
+	      
+	      So, please check each languagekw.swg file (I left the
+	      link to the keyword list source for checking), and after
+	      testing, uncomment the %include line.
+
+	    - Added the file allkw.swg, which includes all the
+              languagekw.swg files.
+
+	      For the languages that has no languagekw.swg file right
+	      now, and if they need one, add the file into the
+	      language directory, and add the corresponding include
+	      line into the allkw.swg file.
+	      
+	    - Added the -Wallkw that includes the allkw.swg file.
+	      Note that the old -lallkw.swg option couldn't be used
+	      since it include the file after it would be needed.
+
+
+	    Hopefully, the -Wallkw option will be added to the default
+	    rules in the related test-suite Makefiles, so, when
+	    creating a new test, or adding a new swig library file
+	    (like _std_deque.i), swig will warn you if you are using a
+	    bad name, considering all the language where it needs to
+	    run.
+	    
+	    Right now you can test it by using:
+
+               make check-python-test-suite SWIG="swig -Wallkw"
+
+	    or using your favorite target language, it doesn't matter.
+
+	    And yes, there are several examples that are using
+	    reserved keywords, specially from csharp.
+          
+	    *** Remember ****: the new keyword warning lists are not
+	    included by default in any of language that before didn't
+	    have one. To enable the keyword warnings as the default
+	    behavior, the inclusion of the languagekw.swg file has to
+	    be uncommented at each language.swg file.
+
+	    So, all the language maintainers, please check the
+	    keywords list. 
+
+	    Also, you can add buit-in names, and not only keywords, like
+	    'True/False' in python.  Remember that you can be more
+	    specific and refer only to member names, like *::configure
+	    or *::cget (see an example in the tcl8/tcl8kw.swg file),
+	    or only global names, like ::range (see an example in the
+	    python/pythonkw.swg file.
+
+	    Just to be consistent, use the following codes:
+
+	    - Use code 314 for keyword and/or fatal bad names.
+	    - Use code 321 for buit-in and/or not fatal bad names.
+           
+            so, they can't be disabled/enabled independently (see
+	    python/pyhtonkw.swg for examples).
+
+	    **** And don't add any new test file without checking it
+	    with the -Wallkw option!! (that includes me) *****.
+	  
+
+12/11/2003: cheetah (William Fulton)
+            SF bug #854634
+            Added support for accepting the Unix directory separator '/' on 
+            Windows and the Mac in addition to the native one ( '\' on 
+            Windows). This can be used in %import, %include and commandline 
+            options taking a path, for example -I. On Cygwin, both the Windows
+            and Unix directory separator can now be used (was '/' only).
+            
+12/10/2003: mmatus (Marcelo Matus)
+
+            [python] Implementing the runtime "reprotected" director
+	    members, if you have:
+    
+                %feature("director") B;
+
+                class Bar {
+                public:
+                  virtual ~Bar();
+                  virtual int hello() { return do_hello();)
+
+                protected:
+                  virtual int do_hi() {return 0;}
+                  virtual int do_hello() {return 0;}
+                };
+
+            then, at the python side
+
+                import my_module
+
+                class Foo(my_module.Bar):
+                  def do_hello(self):
+                    return 1
+                  pass
+                 
+	        b = Bar() # Pure C++ Director class
+                f = Foo() # C++ Director + python methods
+
+                b.hello() # Ok, and it calls C++ Bar::do_hello()
+                f.hello() # Ok, and it calls Python Foo::do_hello()
+
+                b.do_hi() # RuntimeError, do_hi() is protected!!
+                f.do_hi() # RuntimeError, do_hi() is protected!!
+ 
+                b.do_hello() # RuntimeError, do_hello() is protected!!
+                f.do_hello() # Ok, since it its redefined in python.
+
+            Here Bar.do_hello is always protected, but Foo.do_hello
+            is "public", because it is redefined in python. Before,
+	    all the 'do_hello' methods were public.
+
+	    This seems to be a good compromise between C++ and python
+	    philosophies, ie, all the director protected methods keep
+	    protected at the user side (C++ way) until they are
+	    redefined (python way, were all defined methods are always
+	    public). And this is not only a good compromise, it also
+	    seems to be the only way to do it :).
+
+	    Now ruby has native director protected members, and python
+	    pure runtime support. I guess these are the two possible
+	    extreme cases. And hopefully, they could be used as
+	    templates to modify the other languages that support
+	    directors, so they can "reprotect" the protected director
+	    members at the target language side.
+
+	    This finished the director protected support for the 
+	    python language. Ocalm will need to add the
+	    "reprotection" later.
+
+12/10/2003: mmatus (Marcelo Matus)
+
+	    The following case (reported by Lyle Johnson) was fixed:
+
+	      %rename(x) Foo::y();
+ 
+	      class Foo { 
+	      public:
+	        void y();
+
+	      protected:
+	        int x;
+	      };
+
+	   swig warned that the symbol 'x' was already defined, and
+           the renaming fails. 'x' was not emitted, since it is
+           protected, but it was kept in the symbol table with too
+           much information.
+
+	   Now swig works for all the cases (plain, director and
+	   dirprot) again. This was fixed by allowing the parser.y to
+	   decide much closer what to do with 'x'. Before all the
+	   discarding or generation was resolved at the lang.cxx
+	   stage. Also the changes in parser.y to implement the
+	   director protected mode are now much more encapsulated, and
+	   they get disabled if the mode is not enabled. Before the
+	   deactivation was done at the generation stage (lang.cxx).
+
+	   By the other hand, if the director mode is enabled, and
+	   %rename is done, reusing a protected member name, there is
+	   a pathological case:
+
+	     %rename(x) Foo::y();
+ 
+             class Foo : public A {
+	     public:
+	       void y();
+
+	     protected:
+	       int x;            /* works */
+	       static  int x;    /* works */
+	       static  void x(); /* works */
+	       typedef void x(); /* works */
+
+	       virtual void x(); /* always fails, as it should, since
+                                    Foo::x() will be emitted in the
+                                    director */
+
+	       void x(); /* always fails, but sometimes it shouldn't,
+                            since the Foo::x() will not be emitted if
+                            it is not virtual */
+
+	     };
+
+	   The last case is not always right because at the parser.py
+	   stage it is not possible to decide if the protected member
+	   Foo::x() could or not conflict with the renamed Foo::y(),
+	   since Foo::x() could be virtual by inheritance.
+
+	   I guess this just an intrinsic limitation, and no much can
+	   be done about it without resorting into larger changes to
+	   postpone, under certain conditions, the multiply symbol
+	   detection (lang.cxx stage).
+	   
+	   So, by now, it is just considered a well known "feature" in
+	   the director protected mode. The good news is that it seems
+	   to be a rare case, and it can be avoided by the user by
+	   hiding 'x' before renaming 'y':
+
+	     %rename(_x) Foo::x();
+	     %rename(x) Foo::y();
+	   
+
+12/08/2003: mmatus (Marcelo Matus)
+	    The virtual method detections now properly
+	    treats the following cases:
+
+             namespace foo { typedef int Int; }
+	     struct A {};
+	     typedef A B;
+
+             struct Foo {
+               virtual ~Foo() {}
+
+               virtual Foo* cloner() = 0;
+	       virtual int get_value() = 0;
+	       virtual A* get_class() = 0;
+	       virtual void just_do_it() = 0;
+	     };
+
+             struct Bar : Foo
+             {
+               Bar* cloner();
+               foo::Int get_value();
+               B* get_class();
+               void just_do_it();
+             };
+ 
+            All the Foo and Bar methods are virtual.  A new attribute
+	    "virtual:type" record the base polymorphic type. In the
+	    previous cases we have:
+
+	       type : Bar       virtual:type : Foo
+	       type : foo::Int  virtual:type : int
+	       type : B         virtual:type : A
+	       type : void      virtual:type : void
+
+            This attribute is useful in languages (java+directors)
+	    that could have problems redefining Bar* Bar::cloner().
+
+	    If you never had code like the above, you will see no
+	    effects. But if you have some code like that, you
+	    will see some effects since some methods that
+	    before were not properly treated as virtual,
+	    will start to act like that. This could enlarge
+	    your director classes.
+	    
+
+12/08/2003: mmatus (Marcelo Matus)
+	    The director protected member support (dirprot)
+	    is disabled by default.
+	    
+	    It can be enable by using '-dirprot' or by adding
+	    the option to the module declaration, like:
+
+            %module(directors="1",dirprot="1") my_module
+
+	    This module option was added to properly compile the
+	    director_protected.i and director_nested.i examples.
+	    
+	    The feature has been tested with python[2.2,2.3] 
+	    and ruby[1.6.7], both at compilation and runtime, and 
+	    java[j2sdk1.4.1_01], but only at compilation (my java
+	    installation doesn't run any of the director examples,
+	    olds nor news).
+
+	    Please test for ocaml and java.
+	    
+	    The errors reported by William and Scott were fixed,
+	    except for a warning about  SWIG_JavaThrowExecption()
+	    multiply defined. I can't reproduce this error with my
+	    examples. We will wait for Scott to send us a minimal
+	    case.
+
+
+12/07/2003: mmatus (Marcelo Matus)
+	    The director protected member support has been
+	    completly moved out from python.cxx, and now
+	    resides in the common lang.cxx, emit.cxx and
+	    allocate.cxx files. 
+
+	    This means it should work for all the other languages
+	    that currently support directors, ie, python, java, ocalm
+	    and ruby.
+
+	    The change has been tested with python (compilation+runtime)
+	    and java (just compilation).
+	    
+	    Please add runtime tests for the missing languages 
+	    and test it.
+
+	    The '-nodirprot' option was moved to the principal main,
+	    and can be used from all the languages.
+
+12/07/2003: cheetah (William Fulton)
+            [Java] Fixed and improved error checking of STRING_OUT typemaps in 
+            various.i.
+
+12/04/2003: mmatus (Marcelo Matus)
+
+	    - Now the virtual members with no explicit declarator
+	    are properly identified:
+	    
+                struct A  {
+                 virtual int f() = 0;
+                };
+
+                struct B : A {
+                  int f();
+                };
+
+	    Here, B::f() is virtual, and the director and the
+	    virtual elimination mechanism now recognize that.
+
+            - [C#] This fix also fixes the problem where 'override' was not being 
+            used on any overridden virtual method, so for struct B above, 
+            this C# code is generated:
+
+                public class B : A {
+                  ...
+                  public override int f() {
+                    ...
+                  }
+                  ...
+                }
+
+	    - Initial support for protected virtual methods. They are now
+	    properly emitted when using with director (python only by
+	    now).
+	    
+                %feature("director") A;    
+                struct A  {
+                protected:
+                 virtual int f1() = 0;
+                };
+
+                %feature("director") B;
+                struct B : A{
+                protected:
+                  int f1();
+                  virtual f2();
+                };
+
+	    This can be dissabled by using the '-nodirprot' option.
+
+	    - The feature 'nodirector' is working now at the top level,
+	    so, it must work for all the languages:
+
+                %feature("director") A;
+                %feature("nodirector") A::f2;
+
+                struct A {
+                 virtual int f1();
+                 virtual int f2();
+                };
+                
+	    in this case, only 'f1' is exported to the director class.
+	    
+	    - Added director support for const TYPE& arguments (python).
+
+12/02/2003: cheetah (William Fulton)
+            [Java] Fix for INOUT and OUTPUT typemaps in typemaps.i for when the JNI type 
+            is bigger than the C type. For example, unsigned long (32bits on most systems)
+            is mapped to jlong (64bits). Returned value was incorrect. Bug reported by 
+            Brian Hawley.
+
+12/02/2003: cheetah (William Fulton)
+            [C# and Java] Better fix for entry dated 05/11/2003. Fixes the following
+            typemaps:
+
+            Java: javabase, javainterfaces, javaimports, javaclassmodifiers,
+            javaptrconstructormodifiers, javafinalize, javagetcptr & javacode.
+            C#: csbase, csinterfaces, csimports, csclassmodifiers,
+            csptrconstructormodifiers, csfinalize, csgetcptr & cscode.
+
+            It also fixes bug in using arrays of C structs with arrays_java.i 
+            as reported Scott Michel.
+
+12/02/2003: beazley
+            [Perl] Fixed [ 852119 ] recursive inheritance in output .pm, perl5.
+            Reported by William Dowling.
+
+12/02/2003: beazley
+            [Tcl] Fixed [ 755382 ] calling func(const vector<T>& p) evaluates p[0] in interp.
+            The Tcl type checker was improperly handling the interpreter result when
+            type violations were supposed to be ignored.
+            Reported by Flaviu Popp-Nowak.
+
+11/30/2003: cheetah (William Fulton)
+            Fixed [ 545058 ] configure's --with-tclincl has no effect
+
+11/30/2003: cheetah (William Fulton)
+            [Java] Fixed [ 766409 ] missing symbol SWIG_JavaThrowException during module load
+            SWIGs internal functions are all static as there is no need for different SWIG
+            generated modules to share any code at runtime.
+
+11/30/2003: beazley
+            [Tcl] Added support for C++ pointers to members.
+
+11/28/2003: cheetah (William Fulton)
+            Fixed [ 848335 ] Directors: #include wrapper .h file - was incorrectly
+            adding a directory to the generated #include "foo_wrap.h" statement
+            in some situations.
+
+11/28/2003: cheetah (William Fulton)
+            [Java] Fixed [ 849064 ] JAVA : Access modifier for derived class wrong.
+            The delete() method is always public now. It used to be protected whenever a 
+            destructor was non public. An UnsupportedOperationException runtime 
+            exception is thrown instead of making delete() protected now.
+
+11/28/2003: beazley
+            [Perl5] Added support for C++ pointers to members.
+
+11/28/2003: beazley
+            Fixed [ 850151 ] PYVERSION with python2.3 in configure of SWIG 1.3.19 (Maybe).
+
+11/28/2003: beazley
+            Fixed  [ 850666 ] #include extra line added.  
+            This should fix some problems with getting correct line numbers on
+            error messages.
+
+11/26/2003: beazley
+            Fixed another one of Marcelo's evil template bugs (infinite
+            recursion). [ 849504 ] template and typedef -> inf. recursion.
+
+11/26/2003: beazley
+            Fixed parsing problem with declarations like this:
+
+	         int *x = &somearray[0];
+
+11/25/2003: beazley
+            Fixed [ 756552 ] missing default argument class scope with "|".
+            This is really only a band-aid fix for use of class-enums in
+            expressions.  For example:
+
+                  class A {
+                  public:
+                     enum Flag { flag1 = 0x1, flag2 = 0x2 };
+                     void foo(int x = flag1 | flag2);
+                  };
+
+            Note: there are still some (more subtle) cases that are broken,
+            but hard to fix due to an issue with template expansion. Will
+            address later.
+            Reported by Dmitry Mironov.
+
+11/25/2003: beazley
+            Incorporated [ 840878 ] support for %inline { ... } (PATCH).
+            This adds support for the following:
+
+                  %inline {
+                      ... some code ...
+                  }
+
+            The difference between this and %inline %{ ... %} is that the
+            enclosed text is processed by the SWIG preprocessor.   This
+            allows special macros and other processing to be used in 
+            conjunction with %inline.
+            Contributed by Salvador Fandino Garcia.
+
+11/25/2003: beazley
+            Fixed [ 836903 ] C++ inconsistency (with void arguments).
+            SWIG was having difficulty with f() vs f(void) in C++ programs.
+            For instance:
+
+                  class A {
+                  public:
+                      virtual void f(void) = 0;
+                  };
+
+                  class B {
+                  public:
+                      virtual void f();    // Not matched to f(void) correctly
+                  }; 
+
+            The parser now normalizes all declarations of the form f(void) 
+            in C++ classes to f().  This should fix a variety of subtle 
+            problems with inheritance, optimizations, overloading, etc.
+            Problem reported by Partho Bhowmick.
+ 
+11/25/2003: beazley
+            [Perl5] Incorporated [ 841074 ] better croaking (PATCH).  This fixes some problems
+            with strings and provides some new error functions. 
+            Contributed by Salvador Fandino Garcia.
+            
+11/25/2003: beazley
+            Fixed [ 791835 ] Default argument with cast: txt = (char *)"txt" syntax Error.
+            The parser should now accept things like this:
+
+                 void foo(char *s = (char *) "Hello");
+
+            Problem reported by Claudius Schnorr.
+
+11/24/2003: beazley
+            [Tcl] Fixed problem with cross module linking.  Previously modules referred
+            to base classes through a global variable.   Now, the module looks up base
+            classes through the type system itself---avoiding the need to link to a global
+            like before.  Caveat:  modules with base classes must be loaded before
+            modules with derived classes.
+ 
+11/24/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] In -scm mode, use () to represent null pointers,
+	    as it is done in -gh mode.
+
+11/23/2003: mkoeppe (Matthias Koeppe)
+	    Add a generated script "preinst-swig", which can be used
+	    to invoke SWIG before it has been installed.  It arranges
+	    that the runtime libraries from the source directory are
+	    used. 
+
+11/23/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] In -gh mode, don't forget to call SWIG_Guile_Init.
+	    Add a SWIG_contract_assert macro.
+
+11/23/2003: mkoeppe (Matthias Koeppe)
+	    [MzScheme] Update the configure check for the dynext object to work
+	    with MzScheme 205.
+
+11/20/2003: mmatus
+	    Fixed the include/import error reported by Kerim Borchaev,
+	    where two files with names like
+
+	    'dir1/hello.i'
+	    'dir2/hello.i'
+	    
+	    can not be include at the same time. Swig was including
+	    just the first one, assuming the second one was not a
+	    different one, since it was checking/keeping just the
+	    basename 'hello.i'.
+
+11/19/2003: beazley
+            Changes to the SWIG runtime library support. 
+              -  The -c command line option has been renamed to -noruntime
+              -  New command line option: -runtime.  When supplied, this
+                 inserts the symbol SWIG_GLOBAL into the wrapper code.  This,
+                 in turn, makes all of the runtime support functions globally
+                 visible.
+               - New library file: swigrun.i.   Used to create modules
+                 for runtime library (if needed).
+    
+11/18/2003: cheetah (William Fulton)
+            'make srcrpm' rpmbuild fix - patch from Joe Cooper
+
+11/18/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Change meaning of configure option --with-guile to
+	    the name of the Guile executable.  The new option --with-guile-prefix 
+	    can be used to specify the tree where Guile is
+	    installed.  (However, usually it suffices to use the
+	    single option --with-guile-config.)  
+	    When running the run tests test-suite, make sure to use the
+	    version of Guile that SWIG was configured for.
+
+11/17/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Improvements to object-ownership management in 
+	    "-scm" mode.  (They do not apply to the default "-gh" mode.)
+	    * Renamed the smob type that indicates that the object can
+	      be garbage collected from "collected swig" to "collectable
+	      swig", which is more precise.  
+	    * Export the destructor functions again.  It is now
+ 	      allowed to explicitly call destructors, even for
+	      garbage-collected pointer objects.  A pointer object
+	      that has been passed to a destructor is marked in a
+	      special way using a new smob type, "destroyed swig".
+	      (This helps avoid nasty memory bugs, where references to
+	      dead C objects are still held in Scheme. Moreover, the
+	      garbage collector will not try to free a destroyed
+	      object once more.)
+	    * Destructor-like functions can also mark their arguments 
+	      as destroyed by applying the typemap SWIGTYPE *DESTROYED.
+	      (It calls the function SWIG_Guile_MarkPointerDestroyed.)
+	    * Functions that "consume" their objects (or that "own"
+	      them after the call) can mark their arguments as
+	      not garbage collectable.  This can be done by applying
+	      the typemap SWIGTYPE *CONSUMED.  (It calls the function
+	      SWIG_Guile_MarkPointerNoncollectable.)
+	    * The macro TYPEMAP_POINTER_INPUT_OUTPUT from library
+	      pointer-in-out.i creates additional typemaps 
+	      PTRTYPE *INPUT_CONSUMED, PTRTYPE *INPUT_DESTROYED.
+	      They mark the passed pointer object likewise.
+	      The typemap PTRTYPE *OUTPUT creates a garbage-collectable
+	      pointer object, like %newobject does for a returned 
+	      pointer.  Use the new typemap PTRTYPE *OUTPUT_NONCOLLECTABLE
+	      to create a pointer object that will not be garbage collected.
+
+11/17/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Handle $input in "freearg" typemaps.
+	    Never qualify GOOPS slot names with the class name. 
+	    Handle optional arguments properly in the GOOPS methods.
+
+11/16/2003: cheetah (William Fulton)
+            Fixes for installation to work with the upcoming Automake-1.8.
+            mkinstalldirs was being used by a non-Automake makefile. 
+            mkinstalldirs is being phased out and so was not being
+            created by Automake. install-sh used instead.
+
+11/16/2003: cheetah (William Fulton)
+            [Java] Numerous director improvements, tweaks and bug fixes since 
+            the initial implementation have been contributed by Scott Michel.
+
+11/12/2003: beazley
+            [Python] When %feature("shadow") is used to add code to shadow
+            classes, the special variable $action expands to the name of the
+            underlying wrapper function that would have been called normally.
+
+11/12/2003: beazley
+            [Python] When generating proxy class code, SWIG emits a few
+            default methods for __repr__() and other Python special
+            methods.  Some of these methods are emitted after all of the
+            contents of a class. However, this makes it hard to override
+            the methods using %pythoncode and some other directives that
+            allow code to be inserted into a class.  These special methods
+            are now emitted into the code *before* all of the other methods.
+            Suggested by Eric Jones.
+ 
+11/11/2003: beazley
+            Preprocessor enhancement.   For include statements like this:
+
+                  %include "foo/bar.i"
+
+            the directory "foo" is now added to the search path while 
+            processing the contents of bar.i.  Thus, if bar.i includes other
+            files in the same directory, they will be found. Previously,
+            you would have to add additional directories using -I to make this
+            work correctly.  Note: the C preprocessor seems to behave in
+            an identical manner on many (most? all?) systems.
+            Suggested by Kerim Borchaev.
+
+11/11/2003: beazley
+            Configuration changes to make SWIG work on Mac OSX 10.3.x (Panther).
+            Tested with Python, Tcl, Perl, and Ruby---all of which seem to work.
+
+11/08/2003: cheetah (William Fulton)
+            [Java] Fixed the typemaps in various.i which were mostly broken.
+            char **STRING_IN and char **STRING_RET typemaps replaced with 
+            STRING_ARRAY. float *FLOAT_ARRAY_RETURN typemap removed.
+
+11/08/2003: beazley
+            [Tcl] Tcl module now emits a safe module initialization function by
+            default.  It can be removed by running 'swig -nosafe'.
+
+11/04/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Only use the SCM_ API when the function
+	    `scm_slot_exists_p' exists (needed for GOOPS support).  
+	    This function was renamed during the Guile 1.5 series
+	    from `scm_slots_exists_p'.
+	    Report the right runtime library when invoked with
+	    -scm -ldflags.
+
+11/03/2003: mkoeppe (Matthias Koeppe)
+	    [Chicken] Fix #782052.  The --with-chickencfg configure
+	    option (and others) were not accepted.
+
+11/02/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Merge new set of GOOPS changes by John Lenz.
+	    GOOPS objects are now manipulated directly by the C code.
+	    Some fixes to typemap-GOOPS interaction.
+
+11/02/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Remove the file argument to -scmstub and -goops.
+	    The Scheme files are now always called MODULE.scm or
+	    MODULE-primitive.scm, where MODULE is the module name and 
+	    "primitive" can be changed by the -primsuffix option.
+	    The Scheme files are now placed in the directory given by
+	    the -outdir option, or the current directory.
+	    (Patch by John Lenz, slightly modified.)
+
+	    *** INCOMPATIBILITY [Guile] ***
+
+11/02/2003: mkoeppe (Matthias Koeppe)
+	    Unify the pointer-conversion runtime API.  The standard
+	    functions are:
+	     * SWIG_NewPointerObj (POINTER, TYPE, FLAGS)
+	        -- Create an scripting object that represents a typed
+		   pointer. FLAGS are language specific.
+	     * SWIG_ConvertPtr (INPUT, RESULT, TYPE, FLAGS)
+	        -- Get a pointer from the scripting object INPUT and
+		   store it in the place RESULT.  When a type mismatch 
+		   occurs, return nonzero.
+	     * SWIG_MustGetPtr (INPUT, TYPE, ARGNUM, FLAGS)
+	        -- Get a pointer from the scripting object INPUT and
+		   return it.  When a type mismatch occurs, throw an
+		   exception.  If ARGNUM > 0, report it as the 
+		   argument number that has the type mismatch.
+            [Guile]:    No changes.
+	    [MzScheme]: No changes.
+	    [Perl]:     Add the function SWIG_NewPointerObj.
+		        The function SWIG_MakePtr is kept.
+			The function SWIG_MustGetPtr is currently not
+			supported.
+	    [Python]:   Add the function SWIG_MustGetPtr.
+	    [Ruby]:     Add the function SWIG_MustGetPtr.
+	    [Tcl]:      Remove the "interp" argument of
+		        SWIG_NewInstanceObj, SWIG_ConvertPtr,
+		        SWIG_ConvertPacked, and SWIG_ConvertPtrFromString.
+			The function SWIG_MustGetPtr is currently 
+			not supported.
+	    No changes to Pike because its pointer conversion code did
+	    not look complete.  No changes to PHP4, because I did not
+	    understand its runtime code.  No changes to Chicken
+	    because major changes are expected soon anyway.  No
+	    changes to Java, OCaml, C# because they do not seem to
+	    have a pointer-conversion runtime API.
+
+            *** INCOMPATIBILITY [Tcl] ***
+
+11/02/2003: mkoeppe (Matthias Koeppe)
+	    [Perl5, PHP4, Pike, Python, Ruby, Tcl]: Use the
+	    preprocessor to rename external functions of the SWIG
+	    runtime API to follow the naming convention
+	    SWIG_<language>_<function>.  This should allow linking
+	    more than one interpreter into a program.
+
+10/31/2003: cheetah (William Fulton)
+            [C#] Fix since introducing the exception and std::string delegates.
+            The fix overcomes linker errors when using more than one SWIG module.
+            Problem reported by Andreas Schörk.
+
+10/31/2003: beazley
+            Incorporated patch: [ 823302 ] Incr Tcl support.
+            Contributed by Alexey Dyachenko.
+            Note: needs documentation.
+
+10/31/2003: beazley
+            Incorporated patch: [ 829325 ] new Python Module options and features.
+            Robin Dunn writes:
+
+            This patch makes a number of changes to the SWIG python module.
+
+            1. Add -apply option, and change the default code
+            output to use the foo(*args, **kw) calling syntax
+            instead of using apply(). If the -apply option is
+            given then code is generated as before. This is very
+            similar to Patch #737281 but the new -modern option
+            makes the second half of that patch unnecessary so it
+            is not included here.
+	    
+            2. Add -new_repr option. This is the same as my Patch
+            #797002 which I will mark as closed since it is no
+            longer needed. When this new option is used then the
+            __repr__ methods that are generated for proxy classes
+            will be more informative and give details about the
+            python class and the C++ class.
+	    
+            3. Add %feature("addtofunc"). It allows you to insert
+            one or more lines of code inside the shadow method or
+            function that is already generated, instead of
+            replacing the whole thing like %feature("shadow") does.
+            For __init__ it goes at the end, for __del__ it goes
+            at the begining and for all others the code generated
+            is expanded out to be like
+	    
+            def Bar(*args, **kwargs):
+            val = _module.Foo_Bar(*args, **kwargs)
+            return val
+	    
+            and the "addtofunc" code is inserted just before the
+            return statement. If the feature is not used for a
+            particular method or function then the shorter code is
+            generated just like before.
+	    
+            4. A little bit of refactoring to make implementing
+            addtofunc a little easier.
+	    
+            5. Added a -modern command-line flag that will cause
+            SWIG to omit the cruft in the proxy modules that allows
+            it to work with versions of Python prior to 2.2. The
+            result is a simpler, cleaner and faster python proxy
+            module, but one that requires Python 2.2 or greater. 
+
+10/31/2003: beazley 
+            Incorporated patch: [ 829319 ] XML module tweaks.
+            This adds a new command line option -xmllite that 
+            greatly reduces the amount of emitted XML code by
+            eliminating some fields mostly used in SWIG's
+            internal processing.  Contributed by Robin Dunn.
+
+10/31/2003: beazley
+            Incorporated patch: [ 829317 ] Adds DohSplitLines function.
+            Contributed by Robin Dunn.
+
+10/29/2003: beazley
+            Fixed [ 827907 ] argout objects not being wrapped properly (PATH).
+            Patch contributed by Salvador Fandiño García.
+	     
+10/29/2003: beazley
+            Fixed [ 826996 ] perl type checking ignores perl subclasses.
+            This enhancement makes it so wrapped classes and structs can
+            be subclassed in Perl and used normally. 
+            Patch contributed by Salvador Fandiño García.
+
+10/16/2003: cheetah (William Fulton)
+            [C#] IntPtr marshalled with a void* instead of int in C function 
+            declarations. The casts thus look more conventional, for example:
+
+                // old
+                DllExport double SWIGSTDCALL CSharp_get_Shape_x(int jarg1) {
+                    ...
+                    Shape *arg1 = (Shape *) 0 ;
+                    arg1 = *(Shape **)&jarg1; 
+                    ...
+                }
+                // new
+                DllExport double SWIGSTDCALL CSharp_get_Shape_x(void * jarg1) {
+                    ...
+                    Shape *arg1 = (Shape *) 0 ;
+                    arg1 = (Shape *)jarg1; 
+                    ...
+                }
+
+
+10/14/2003: beazley
+            Fixed a subtle problem with overloaded methods and smart pointers.
+            If a class has overloaded methods like this:
+
+                 class Foo {
+                 public:
+                     int bar(int x);
+                     static int bar(int x, int y);
+                 };
+
+            and the class is used as a smart pointer:
+
+                class FooPtr {
+                public:
+                     Foo *operator->();
+                };
+
+            The SWIG would try to expose the static member Foo::bar
+            through FooPtr---resulting bogus wrapper code and a compiler
+            error.
+
+            Due to the way in which overloading is handled, it is
+            extremely difficult to eliminate the static method in
+            this case.  Therefore, it is still exposed.  However,
+            the generated code now compiles and works.
+
+10/05/2003: mkoeppe (Matthias Koeppe)
+	    [Guile, MzScheme, Chicken]: Remove symbol clashes between
+	    the runtime libraries by renaming all extern common.swg
+	    functions with the preprocessor.
+
+10/05/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Added basic GOOPS support, contributed by John Lenz.
+	    See the documentation for details.
+	    
+            *** NEW FEATURE ***
+
+10/04/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] New option, -only-setters, which disables
+	    traditional getter and setter procedures for structure slots.
+
+10/03/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Added run test for reference_global_vars by John Lenz.
+
+09/30/2003: beazley
+            Partial solution to [ 792180 ] C++ smart-pointer/namespace mixup revisited.
+            The problem is not easy to fix (at least it doesn't seem so), but is
+            related to the instantiation of qualified templates inside of other
+            namespaces.   SWIG now generates an error message in this case rather
+            than generating broken wrappers.
+
+09/30/2003: beazley
+            Fixed [ 800012 ] ENTER macro from CORE/scope.h clashes with libc search.h.
+            Reported by Britton Leo Kerin.
+
+09/30/2003: beazley
+            Fixed [ 811518 ] Casting ints to doubles (w/ solution?)
+            Addresses a problem with overloading in the Perl module.
+            Reported by Gerald Dalley.
+
+09/28/2003: mkoeppe
+	    [Guile with -scm option] Fix typo in generated code for
+	    procedures-with-setters.  Reported by John Lenz.
+
+09/26/2003: beazley
+            Fixed [ 812528 ] externs not correct when throw is in signature.
+            Reported by Joseph Winston.
+            
+09/23/2003: cheetah (William Fulton)
+            SWIG was generating a number of symbols that didn't comply with 
+            the ISO C/C++ standard, in particular ISO/IEC 14882:1998(E) 17.4.3.1.2
+            where double underscores are forbidden as well as symbols starting with
+            an underscore followed by an upper case letter. Most of these have
+            been rooted out. See new section added to internals.html development
+            manual 'Symbol Naming Guidelines for Generated C/C++ Code'.
+
+09/23/2003: cheetah (William Fulton)
+            Director typemap name changes:
+            inv     => directorin
+            outv    => directorout
+            argoutv => directorargout
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+09/19/2003: mrose (Mark Rose)
+            [Python] Director constructors now default to __disown = 0, 
+	    which is the intended behavior and fixes the director_finalizer 
+	    test case under python.
+
+09/12/2003: cheetah (William Fulton)
+            [C#] - Typemaps added for std::string and const std::string &.
+                 - New delegate for creating a C# string given a char *. It
+                   can be used by calling SWIG_csharp_string_callback as shown
+                   in the std::string 'out' typemap. Useful if the return type is
+                   mapped to a C# string and the calling function is responsible 
+                   for cleaning up memory as the C# garbage collector doesn't
+                   free the memory created in C/C++ and then returned as a C# string.
+                 - The exception delegates have moved into an inner class in the
+                   intermediate class, thereby freeing up the static constructor.
+
+09/11/2003: beazley
+            (Internals)
+            Major refactoring of iteration over lists and hashes.  The
+            DOH library now uses iterators.  They work like this:
+
+                List *l = (some list);
+
+                Iterator i;
+                for (i = First(l); i.item; i = Next(i)) {
+                    // i.item contains the actual list item.
+                    // i.item is NULL at end of list
+                    ...
+                }
+
+                Hash *h = (some hash);
+                Iterator j;
+                for (j = First(h); j.item; j = Next(j)) {
+                    // j.item contains hash table item
+                    // j.key  contains hash table key
+                    // Both j.item and j.key are NULL at end
+                    ...
+                }
+ 
+            The old iteration functions Firstitem(), Nextitem(), Firstkey(),
+            and Nextkey() are gone.  
+
+            The new iterators are simpler, result in better memory use,
+            and may be faster.  Also, there are no longer any problems
+            iterating over the same list/hash in multiple places at
+            the same time.  For example, this is fine:
+
+                 Iterator i,j;
+                 for (i = First(l); i.item; i = Next(i)) {
+                    for (j = First(l); j.item; j = Next(j)) {
+                         ...
+                    }
+                 }
+
+            (This never worked in previous versions).
+            *** POTENTIAL INCOMPATIBILITY ***.  This will probably break 
+            third party extensions to SWIG (or give them further encouragement
+            to join the SWIG CVS-tree :-).
+
+09/10/2003: mkoeppe (Matthias Koeppe)
+	    [Guile] Fix memory leaks in the "list-vector.i" typemaps.
+
+09/09/2003: mkoeppe (Matthias Koeppe)
+	    [Chicken] Use C_mk_bool rather than C_mkbool.  This fixes
+	    the wrapping of boolean values for Chicken 1.10 and newer.
+	    Reported by Dave <hundo@yahoo.com> / Felix Winkelmann
+	    <felix@proxima-mt.de>.
+
+09/05/2003: cheetah (William Fulton)
+            [Java] Directors implemented for Java. In summary this is a big new feature 
+            which supports upcalls from C++ to Java. Code is generated to support C++ 
+            callbacks to call into Java and true polymorphic behaviour for Java classes 
+            derived from C++ classes. See java.html for details. Contributed by 
+            Scott Michel.
+
+09/05/2003: Tiger
+            Created contract example directory at /SWIG/Examples/contract
+            Added simple contract examples (simple_c & simple_cxx)
+            Modified contract module's output format
+
+            *** NEW FEATURE ***
+
+09/01/2003: cheetah (William Fulton)
+            Test-suite build improvements:
+            - Multiple build directories working for the test suite, so it is now
+              possible to run configure in multiple subdirectories and run the test
+              suite in each of these sub directories.
+            - 'make distclean' fixed so it doesn't bomb out on the Examples directory
+              when using multiple subdiretory builds. Required the following directories
+              to be moved:
+                Examples/GIFPlot/Perl -> Examples/GIFPlot/Perl5
+                Examples/GIFPlot/Php  -> Examples/GIFPlot/Php4
+              These new directories used to be symbolic links to the old directory.
+              Also the Examples/test-suite/Perl symbolic link has been removed.
+            - Running the test-suite, other than from the root directory, say
+              in Examples/test-suite/python will now display all the code being
+              executed.
+            - The following 3 C# compilers are detected during configure and work with 
+              the test-suite: Mono, Portable.NET and Microsoft.
+
+09/01/2003: Tiger
+            Added inheritance support for design by contract feature.
+
+09/01/2003: beazley
+            Fixed [ 794914 ] Wrong types in template specialization.
+            SWIG was not handling arguments correctly in template 
+            partial specialization.  For example,
+
+                template<class T> class Foo<T *> {
+                public:
+                    T *blah();
+                };
+
+                %template(FooInt) Foo<int *>;
+
+            in this class, the return type of blah was set to
+            'int **', but it should really be 'int *'.  This has been
+            fixed, but it will affect all prior uses of partial
+            specialization.
+ 
+09/01/2003: beazley
+            Fixed [ 786394 ] Patch for generated perl code does not compile under RedHat9.
+            Reported by Scott Finneran.
+
+09/01/2003: beazley
+            Fixed [ 791579 ] (unsigned) long long handled incorrectly (Tcl).
+            This was an error in the Tcl typemaps.i file. 
+            Reported by Kjell Wooding.
+        
+09/01/2003: beazley
+            Fixed [ 797573 ] no way to rename classes coming from C structures.
+            This problem relates to renaming of anonymous structures with a
+            typedef.  For example: 
+
+                  %rename(Bar) Foo;
+                  typedef struct {
+                     ...
+                  } Foo;
+
+            Reported by Britton Leo Kerin.
+            
+09/01/2003: beazley
+            Fixed [ 797576 ] -help seems to imply that only tcl-specific options exist.
+            Added a comment to alert user to other options.
+            Reported by Britton Leo Kerin.
+
+09/01/2003: beazley
+            Fixed [ 798205 ] Segfault in SWIG_ConvertPtr.
+            Reported by Prabhu Ramachandran.
+
+08/30/2003: mrose (Mark Rose)
+            Modified the director typemaps in python/std_complex.i to use the 
+	    new-style macro and conversion functions, which eliminated some
+	    redundant code.  Fixed a few bugs in these typemaps as well, although
+	    more testing is needed.
+
+08/29/2003: mrose (Mark Rose)
+            Completed initial support for wrapping abstract classes with directors.
+	    Constructor wrappers will be generated for abstract classes that have
+	    directors, and instances of the director classes will be created regardless
+	    of whether the proxy class has been subclassed in the target language.
+	    No checks are made during construction to ensure that all pure virtual
+	    methods are implemented in the target language.  Instead, calls to
+	    unimplemented methods will throw SWIG_DIRECTOR_PURE_VIRTUAL_EXCEPTION
+	    exceptions in C++.
+
+	    Integrated Prabhu Ramachandran's typemap patches, which provide director
+	    typemap support for enums and std::size_t, and fix a couple bugs in the 
+	    director std::vector<> typemaps.
+
+08/29/2003: cheetah (William Fulton)
+            [C#] Implemented exception handling for throwing C# exceptions from C/C++ code.
+            A few delegate functions are available for calling which then throw the C#
+            exception. Use the SWIG_CSharpThrowException function from C/C++ typemaps.
+            See the generated wrapper code or csharphead.swg for all available exceptions.
+            Example:
+
+              SWIG_CSharpThrowException(SWIG_CSharpException, "exception description");
+
+            The 'throws' typemaps are also now implemented, so code is automatically 
+            generated to convert any C++ exception into a C# System.Exception when the C++ 
+            method declares an exception specification such as:
+
+               int foo() throw(Bar);
+
+            Also any parameters that are references to a C++ class or a class passed by value
+            and are passed as a C# null will now throw a C# NullReferenceException.
+
+08/29/2003: cheetah (William Fulton)
+            [C#] Fix to match the calling convention of all pinvoke methods so that they
+            match the calling convention used by default in the C# 'static extern' declarations 
+            (__stdcall is used on Windows).
+
+08/19/2003: cheetah (William Fulton)
+            [Java] Reworked std::string typemaps. Fixes a number of string in std namespace 
+            problems. For example %template vector<string>. The templated class' get method 
+            wasn't returning a Java String, but a SWIGTYPE_p_string. Reported
+            by Zach Baum.
+
+08/15/2003: beazley
+            Fixed [ 763522 ] 1.3.19 segfault in SwigType_add_pointer/DohInsertitem.
+            Related to problem with unnamed class handling in Perl module.
+
+08/15/2003: beazley
+            Fixed [ 763563 ] Missing indication of optional arguments.
+            Tcl module.  Reported by Krzysztof Kozminski.
+
+08/15/2003: beazley
+            Fixed [ 787432 ] long param handled as int.  Tcl module
+            now uses Tcl_GetLongFromObj to convert integer values.
+
+08/11/2003: beazley
+            Fixed [ 775989 ] numeric template parameters.   There were
+            some errors in template expansion related to the use of
+            arrays where the array dimension was a template parameter.
+            It should work now.  Reported by Bryan Green.
+
+08/10/2003: mrose (Mark Rose)
+            Added a director typemap (outv) for return by value and cleaned up up a few 
+	    of the commented director typemaps.
+
+08/10/2003: mrose (Mark Rose)
+            Fixed constructor generation for director classes to ignore private
+	    constructors.  Protected constructors are also ignored for now, pending
+	    a solution to the problem of wrapping classes that only define protected
+	    constructors.
+
+08/07/2003: cheetah (William Fulton)
+            New commandline option -outdir <dir> to specify where the language specific
+            files are to be generated. This is useful for target languages like Python,
+            Java etc which generate proxy files in the appropriate language.
+            This option does not apply to the C/C++ wrapper file.
+
+08/07/2003: cheetah (William Fulton)
+            On Windows the generated files (other than the _wrap.c or _wrap.cxx files)
+            were sometimes incorrectly being generated into the current directory unless
+            the input file used the Unix path separator. The Windows path separator 
+            should now be used. Bug reported by Robert Davies.
+
+08/07/2003: beazley
+            Added array variable set typemap to Perl module.
+
+08/07/2003: beazley
+            Fixed [ 775677 ] Array init causes codegen bug..
+
+08/07/2003: beazley
+            Fixed [ 779062 ] Class"\n"::foo not supported.  SWIG
+            should now correctly handle whitespace in between 
+            namespace qualifiers.  For example "A :: Foo :: Bar".
+            
+07/31/2003: cheetah (William Fulton)
+            Fixes for parameters which are classes that are passed by value and have 
+            a default value. A copy constructor for SwigValueWrapper is required 
+            (SF #780056). Also fixed memory leak in these circumstances. These mods
+            also fix SF #780054.
+
+07/28/2003: beazley
+            Improved run-time error message for pointers in Python module.
+            Contributed by Zooko.
+
+07/10/2003: ballabio (Luigi Ballabio)
+            [Almost all languages] Wrappers for std::pair added.
+	    Typemaps for Python, Ruby, Guile and MzScheme.
+
+07/01/2003: mkoeppe (Matthias Koeppe)
+	    [Chicken] Handle the case of more than one argout typemap
+	    per function.
+
+06/29/2003: cheetah (William Fulton)
+            [Java, C#] SF #670949 request. The destructor wrapper function name is now 
+            configurable.  A new attribute called methodname in the 
+            javadestruct/javadestruct_derived (Java) or csdestruct/csdestruct_derived (C#)
+            typemaps specifies the method name. For example in Java the destructor is 
+            wrapped by default with the delete method:
+
+                %typemap(javadestruct, methodname="delete") SWIGTYPE {...}
+
+06/27/2003: cheetah (William Fulton)
+            [Java, C#] The throws attribute for adding exception classes to the throws
+            clause also now works with the following typemaps: 
+            newfree
+            javain, javaout (Java)
+            csin, csout (C#)
+
+            For example, the 'AnException' will be added to the throws clause in the
+            proxy function:
+
+            %typemap(javaout, throws="AnException") int {
+                int returnValue=$jnicall;
+                if (returnValue==0) throw new AnException("Value must not be zero");
+                return returnValue;
+            }
+
+06/25/2003: mrose (Mark Rose)
+            [Python] Director typemap marshalling checks for null pointers when
+	    walking the parameter list instead of relying soley on the parameter
+	    count.  Cures a segfault that occured for multiple argument inv typemaps.
+	    Someone with more Swig experience should probably review this code.
+
+06/24/2003: mkoeppe (Matthias Koeppe)
+	    [Chicken] Don't emit calls to "C_check_for_interrupt",
+	    which may result in an endless loop.  Patch by felix@proxima-mt.de.
+
+06/20/2003: cheetah (William Fulton)
+            [C#] Finalizers now use destructor syntax as the override which was used in 
+            the Finalize method is not in the ECMA standards, spotted by the MS compiler.
+
+06/10/2003: cheetah (William Fulton)
+            [C#] A number of changes have been made to remove the Java naming 
+            that was used in the C# module.
+            
+            Typemap name changes:
+            jni                         -> ctype
+            jtype                       -> imtype
+            jstype                      -> cstype
+            javain                      -> csin
+            javaout                     -> csout
+            javainterfaces              -> csinterfaces
+            javabase                    -> csbase
+            javaclassmodifiers          -> csclassmodifiers
+            javacode                    -> cscode
+            javaimports                 -> csimports
+            javaptrconstructormodifiers -> csptrconstructormodifiers
+            javagetcptr                 -> csgetcptr
+            javafinalize                -> csfinalize
+
+            Feature name changes:
+            javaconst                   -> csconst
+            javamethodmodifiers         -> csmethodmodifiers
+
+            Pragma changes:
+            pragma(java)                -> pragma(csharp)
+            jniclassbase                -> imclassbase
+            jniclassclassmodifiers      -> imclassclassmodifiers
+            jniclasscode                -> imclasscode
+            jniclassimports             -> imclassimports
+            jniclassinterfaces          -> imclassinterfaces
+
+            Special variable name changes:
+            $javaclassname              -> $csclassname
+            $javainput                  -> $csinput
+            $jnicall                    -> $imcall
+
+            This will break SWIG interface files that use these typemaps, features
+            and pragmas. Please update your code or use macros for backwards
+            compatibility.
+
+            *** POTENTIAL INCOMPATIBILITY FOR C# MODULE ***
+
+06/10/2003: mkoeppe (Matthias Koeppe)
+	    [MzScheme] Applied MzScheme module updates contributed by
+	    John Lenz <jelenz@students.wisc.edu>.
+
+            - Updated mzscheme to use SWIG's common runtime type
+              system from common.swg. 
+
+	    - The Lib/mzscheme directory has been reorganized to
+              standardize names across the language modules:
+              mzscheme.i was moved to mzscheme.swg, mzscheme.swg and
+              mzschemedec.swg have been removed, mzrun.swg (which
+              contains the runtime code) has been added.
+
+            - The swig_proxy structure was renamed to swig_mz_proxy.
+              swig_mz_proxy now contains a pointer to a swig_type_info
+              structure.  
+
+	    - Added varin and varout typemaps for SWIGTYPE [] and
+              SWIGTYPE &.
+
+	    - Garbage collection by calling scheme_add_finalizer() has
+              been added.
+
+	    *** NEW FEATURE [MzScheme] ***
+
+06/10/2003: cheetah (William Fulton)
+            [Java] New typemaps: javadestruct and javadestruct_derived
+            for the C++ destructor wrapper. The javadestruct version gets used by
+            classes at the top of an inheritance chain and the javadestruct_derived 
+            version gets used by other classes.
+
+            [C#] cildispose and cildisposeoverride typemaps replaced by
+            csdestruct and csdestruct_derived typemaps. The delete()
+            method has been removed and its functionality put into these
+            typemaps designed for the Dispose() method.
+
+            - New typemaps csinterfaces and csinterfaces_derived replace
+            the javainterfaces typemap. Also fixes the peculiarity of all classes
+            in an inheritance chain individually deriving from the IDisposable 
+            interface.
+
+            - New typemap csfinalize for finalizers. C++ destructors are now called
+            by garbage collector during finalization. Problem reported by 
+            Andreas Schörk.
+
+06/10/2003: Tiger
+	    Modified contract code for error message output.
+            Contract code can now print out simple error message.
+            Modified contract code to prepare for inheritance
+            
+06/03/2003: mkoeppe
+	    [Guile] Applied Guile module updates contributed by 
+	    John Lenz <jelenz@students.wisc.edu>. 
+
+	    - SWIG currently uses Guile's gh_ API, which is marked as
+	      deprecated in Guile 1.6 and will be removed in Guile
+	      1.9.  This change introduces a command-line flag "-scm"
+	      which causes SWIG to generate wrappers that use Guile's
+	      SCM API instead; this requires Guile >= 1.6.
+	    
+	    - The Lib/guile directory has been reorganized to
+              standardize names across language modules: guiledec.swg
+              and guile.swg have been moved into guile_gh_run.swg,
+              guile.i has been moved to guile_gh.swg, guile_scm.swg
+              and guile_scm_run.swg which contain the SCM API stuff
+              have been added
+
+	    - ghinterface.i, which contains the defines from the gh_
+              functions to the scm_functions has been added
+
+	    - The API for dealing with pointer objects is now
+	      SWIG_ConvertPtr, SWIG_MustGetPtr, SWIG_NewPointerObj.
+
+            - Added varin and varout typemaps for SWIGTYPE [] and SWIGTYPE &
+
+            - Garbage collection has been added.
+
+            *** NEW FEATURE [Guile] ***
+	    	
+06/01/2003: cheetah (William Fulton)
+            Dimensionless arrays such as 
+
+                int foo[] = {1, 2};
+                extern int bar[];
+
+            produce a warning that the variable is read-only. Depending on the target
+            language, this used to cause compile errors or generate a setter that
+            generated a runtime error. A setter cannot be automatically generated
+            because the array size cannot be determined by SWIG. A varin, globalin 
+            or memberin typemap (depending on the target language) must be written 
+            by the user.
+
+05/29/2003: beazley
+            Refinement to default typemap matching and arrays.  When an
+            array is declared like this:
+
+                       int foo[4];
+
+            The default typemap now resolves to 
+
+                       SWIGTYPE [ANY]
+
+            If no match is found for that, it then resolves to
+
+                       SWIGTYPE []
+
+            If no array dimension is specified in the original declaration,
+            the SWIGTYPE [] is used right away. 
+
+            Note: This change has been made to resolve problems related to
+            arrays with and without dimensions.  For example, sometimes SWIG
+            was generating setter functions for array variables with no dimensions
+            (an error). Likewise, SWIG sometimes made arrays with dimensions
+            read-only (also an error).  This fixes the arrays_global test
+            problem.
+                        
+05/28/2003: beazley
+            Fixed subtle type handling bug with references and pointers.
+            If you had functions like this:
+
+                  typedef Foo Bar;
+
+                  Foo *func1();
+                  void func2(Bar &x);
+
+            Then func2() wouldn't accept objects returned by func1()
+            because of a type error.   It should work now.
+            Reported by Brian Yang.
+
+05/21/2003: cheetah (William Fulton)
+            Fixes to some of the Visual C++ example project files which would not 
+            work with spaces in the paths held in the environment variables used to 
+            point to the target language's library / include directory.
+            SF bug #740769
+
+05/21/2003:  songyanf (Tiger)
+            Added -contracts option.
+            First try of the idea of "Wrap by Contract": 
+            build up realiable cross-language module by wrapping with SWIG.
+            Implemented basic assertion
+            (preassertion & postassertion & invariant)
+            for simple C/C++ functions.
+            
+            Current format of contracts are:
+            %contract class_name :: func_name (paras...) {
+            require:
+                   boolean exprs;
+                   exprs;
+            ensure:
+                   boolean expr;
+                   exprs;
+            invariant:
+                   boolean expr;
+                   exprs;
+            }
+
+            *** NEW FEATURE ***
+	    	
+05/19/2003: cheetah (William Fulton)
+            Build tweaks. There were a few preprocessor definitions which were
+            specified in the Makefile for passing on the commandline when compiling.
+            These are now all defined in swigconfig.h. Autoconf doesn't normally 
+            allow installation directories to be defined in this config header file, 
+            but an autoconf archive macro enables this. This macro along with future 
+            autoconf macros are going to be put in the Tools/config directory.
+
+            'swig -version' now reports the target build platform.
+
+05/11/2003: cheetah (William Fulton)
+            [C# and Java] Fix to the following typemaps:
+
+            javabase, javainterfaces, javaimports, javaclassmodifiers,
+            javaptrconstructormodifiers, javafinalize, javagetcptr & javacode.
+
+            These are the typemaps for modifying/generating proxy classes.
+            Previously the typemaps would use the proxy class name and not the 
+            C++ type, which was inconsistent with all other typemaps. 
+
+            In most circumstances the proxy class name and the C++ class name/type 
+            is the same except for classes in namespace, templated classes etc. so
+            this shouldn't affect most cases.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA and C# MODULES ***
+
+05/09/2003: cheetah (William Fulton)
+            Visual C++ Project files have been added so that the runtime libraries
+            can be built on Windows (for Tcl, Perl, Python and Ruby).
+
+05/01/2003: beazley
+            Fixed problem with return by value, const, and private constructors.
+            For example:
+
+                class B {
+                private:
+                   B();
+                public:
+                   B(const B&);
+                };
+
+                class A {
+                   ...
+                   const B returnB() const;
+                   ...
+                };
+
+            Problem and patch suggestion reported by Bill Hoffman.
+
+04/29/2003: cheetah (William Fulton)
+            Build changes:
+            - Single autoconf invocation - autoconf in the Tools directory has gone.
+
+            - Libtool bootstrapped when running autogen.sh. This requires anyone
+              using the cvs version of SWIG to have libtool installed on their
+              machine. Suggest version 1.4.2 or higher, preferably the latest - 1.5.
+
+            - Automake is now used to build the runtime libraries in conjunction 
+              with libtool.
+
+            - Runtime libraries are now successfully built as DLLs on Cygwin.
+
+            - Skipping languages is no longer just determined in the top level 
+              makefile but in configure.in. This info is used for building
+              the runtime libraries and for running the examples and test-suite.
+
+            - These changes have fixed multiple build directory builds, that is
+              building from directories other than the top level directory. 
+              Installation from multiple build directories also working. An initial
+              configure in the top level directory is no longer needed as described
+              in 04/02/2003 entry. A 'make distclean' will be needed before building
+              in a directory other than the top level directory if the autotools 
+              have been run from this top level directory at some point, but 
+              autoconf will tell you this. Note that 'make check' only works from 
+              the top level directory at the moment.
+
+04/28/2003: beazley
+            Fixed [ 723471 ] Wrapper_print() fails with preprocessor directives.
+
+04/28/2003: beazley
+            Minor refinement of const static member variable handling 
+            described in CHANGES 08/11/2002.   Previously, SWIG merely
+            checked to see if there was an initializer in the declaration.
+            Now, SWIG additionally checks to make sure the static member
+            is const.
+
+04/25/2003: ljohnson (Lyle Johnson)
+            [Ruby] Added a kind of limited support for multiple inheritance,
+            activated using the -minherit command-line option. I've also updated
+            the "C++ Inheritance" section of the Ruby documentation to discuss
+            how this works, and its limitations. Also also modified the minherit.i
+            test case to run against this.
+
+04/25/2003: ljohnson (Lyle Johnson)
+            [Ruby] Added the -globalmodule command-line option for the Ruby
+            module, for wrapping stuff into the global module (Kernel) instead
+            of a nested module. Updated documentation accordingly.
+
+04/23/2003: mrose (Mark Rose)
+            Fixed symname error in director calls to Python methods
+	    that extend C++ operators.
+
+	    Stopped director destructor wrappers from calling __set_up,
+	    which was leaving the director flag in an inconsistent state.
+
+04/23/2003: beazley
+            Fixed problem with namespace resolution and nested namespaces.
+            Reported by Alfred Lorber (and Marcelo Matus).
+
+04/16/2003: cheetah (William Fulton)
+            Patch for Java examples and test-suite to run on Mac OS X.
+
+04/15/2003: ljohnson (Lyle Johnson)
+            [Ruby] Incorporated Nobu Nakada's patches for supporting the Ruby
+            1.8 allocation framework.
+
+04/15/2003: ljohnson (Lyle Johnson)
+            [Ruby] Replaced all uses of the deprecated STR2CSTR() macro with the
+            safer StringValuePtr() macro. For more information, see ruby-talk:67059
+            and follow-ups to that post.
+
+04/11/2003: beazley
+            Fixed problem with preprocessor macro expansion.  For example:
+ 
+                #define min(x,y) ((x) < (y)) ? (x) : (y) 
+                int f(int min);
+
+            Reported by Sebastien Recio.
+
+04/10/2003: cheetah (William Fulton)
+            [Java] Added a runtime check to typemaps in arrays_java.i library to check 
+            that the Java array passed in is the same size as the C array and throw an 
+            exception if not.
+
+            Also fix to use delete instead of free for arrays created using new.
+
+04/07/2003: cheetah (William Fulton)
+            Remove GCC3 warning when compiling the examples and test-suite:
+
+              cc1plus: warning: changing search order for system directory "/usr/include"
+              cc1plus: warning: as it has already been specified as a non-system directory 
+
+            See SF patch #715531 submitted by Gerald Williams
+
+04/03/2003: cheetah (William Fulton)
+            [C#] Improved wrapping of enums and constants. These were previously
+            wrapped as C# variables rather than constants. Either these are wrapped
+            as readonly (runtime) constants or compile time constants, depending on
+            the %javaconst directive (The directive is likely to change name soon).
+            For example wrapping:
+              %javaconst(0);
+              #define ABC 22
+              %javaconst(1) XYZ;
+              #define XYZ 33
+            is now:
+              public static readonly int ABC = examplePINVOKE.get_ABC();
+              public const int XYZ = 33;
+
+04/03/2003: cheetah (William Fulton)
+            [Java] Global constants and enums are put in their own interface called
+            xxxConstants, where xxx is the module name. This is an improvement as 
+            it is possible to derive (implement) a Java class from the xxxConstants
+            interface to improve the syntax; namely when wrapping:
+              enum {ONE=1, TWO, THREE};
+            accessing these from a Java class implementing xxxConstants is neater:
+              int number = ONE;
+            than the previous:
+              int number = xxx.ONE;
+
+            Patch submitted by Dave Dribin.
+
+04/02/2003: cheetah (William Fulton)
+            Build improvements for multiple builds. This allows one to build
+            the SWIG executable and runtime libraries for different platforms/compilers 
+            etc by running configure in different directories. This isn't 100% just 
+            yet and won't be until libtool is better configured... a 'configure' and 
+            'make distclean' needs to be run in the root directory before it all works.
+            For example:
+              $ ./configure
+              $ make distclean
+              $ mkdir config1; cd config1; ../configure CC=gcc CXX=g++; make; cd ..
+              $ mkdir config2; cd config2; ../configure CC=cc CXX=c++; make; cd ..
+            
+            To be improved. A 'make check' does not work yet either. 
+
+04/01/2003: beazley
+            Fixed template partial specialization argument expansion bug.
+            This showed up when trying to use std_vector.i with vectors
+            of pointers.
+
+03/31/2003: cheetah (William Fulton)
+            Fix for parallel make builds of SWIG, for example
+              make -j 4
+            Build failure reported by Bill Clarke.
+
+03/28/2003: beazley
+            Released 1.3.19.
+
+
+
+Version 1.3.19 (March 28, 2003)
+===============================
+03/28/2003: beazley
+            Variety of minor bug fixes to the 1.3.18 release including:
+
+                - Segmentation fault with %extend directive.
+                - Typemap variable substitution bug.
+                - Expression evaluation bug.
+                - Large memory leak with template expansion.
+
+Version 1.3.18 (March 23, 2003)
+===============================
+
+03/21/2003: beazley
+            Fixed two problems with the %extend directive, overloading, and
+            template expansion.  See the 'template_extend_overload' and
+            'template_extend_overload_2' tests in Examples/test-suite for
+            details.
+
+03/20/2003: cheetah (William Fulton)
+            [C#] Added some typemaps as suggested by Andreas Schoerk for handling
+            parameters that are passed as pointers or by reference. These have
+            been put in typemaps.i.
+
+03/20/2003: beazley
+            Fixed a C++ scoping bug related to code like this:
+
+                class Foo {
+                public:
+                     int Foo::bar();
+                };
+
+            Previously, SWIG just tossed out the Foo::bar() declaration. Now,
+            the declaration is wrapped provided that the prefix is exactly the
+            same as the current scope (including any enclosing namespaces).
+            Reported by Bruce Lowery.
+
+03/20/2003: beazley
+            Incorporated [ 696516 ] Enabling exception processing for data member access.
+            In some compilers, attribute access can generate exceptions.  However,
+            SWIG ordinarily assumes that no exceptions will be raised.  To disable this,
+            use the %feature("allowexcept").  For example:
+
+                  %feature("allowexcept") Foo::x;
+                  ...
+                  class Foo {
+                  public:
+                      int x;     /* Exception handling enabled */
+                      ...
+                  };
+
+            Patch contributed by Yakov Markovitch. 
+ 
+03/20/2003: beazley
+            Incorporated Patch. [ 701860 ] Improve Performance (python proxies).
+            Gives a performance boost to proxy class code and the management of the
+            .this and .thisown attributes.  Contributed by Mike Romberg.
+
+03/19/2003: cheetah (William Fulton)
+            [C# and Java] Added missing vararg support.
+
+03/18/2003: mrose (Mark Rose)
+            Removed code related to tagging individual methods for directors.
+	    The concept of having directors for some but not all virtual methods
+	    of a class is deeply flawed.  The %feature("nodirector") tag is also
+	    gone.  
+	    
+	    Directors are off by default.  To enable them for a class, issue
+	    %feature("director") classname; which will create director methods
+	    for every virtual method in the hierarchy of the class.
+
+03/17/2003: beazley
+            Fixed a subtle problem with passing arguments of type function.  For
+            example:
+
+               int foo(int x(int, int));
+
+            or
+
+               typedef int binop_t(int, int);
+               int foo(binop_t x);
+
+            In old versions, this would produce code that wouldn't compile.  Now,
+            SWIG merely adds an extra pointer, making these declarations the same
+            as:
+
+               int foo(int (*x)(int, int));
+
+               typedef int binop_t(int, int);
+               int foo(binop_t *x);
+
+            Reported by Garth Bushell.
+
+03/17/2003: mrose (Mark Rose)
+            Fixed the return statement for director base class calls that have no
+            return value.
+
+03/15/2003: beazley
+            Fixed a problem with const smart-pointer wrapping.  For example:
+
+                 class Foo {
+                 public:
+                    int x;
+                    void bar() const;
+                    void spam();
+                };
+
+                class Blah {
+                ...
+                   const Foo *operator->();
+                ...
+                };
+
+            In this case, only "x" and "bar" are visible from Blah (since application
+            of spam violates constness).  Moreover, access to "x" is read-only.
+           
+03/15/2003: mrose (Mark Rose)
+            Cleaned up two signed versus unsigned comparisons in python/std_vector.i.
+	    
+03/15/2003: cheetah (William Fulton)
+            [C#] Global variables are wrapped using properties instead of get and set methods.
+            Member variable wrapping bug fixes, for example wrapping pointers work now.
+            Typemaps are used for all variable wrapping to generate the property code.
+
+03/13/2003: mrose (Mark Rose)
+            Fixed a bug in the virtual method unrolling for directors. 
+	    The order of unrolling is now from base to derived, to ensure
+	    that the most derived implementation of a director method is
+	    found.
+
+	    Director methods for pure virtual methods now throw
+	    DIRECTOR_PURE_VIRTUAL_EXCEPTION if _up is set.
+
+03/12/2003: cheetah (William Fulton)
+            [C#] Polymorphism fix: virtual functions now use the appropriate
+            keyword in the C# proxy class, virtual or override.
+            Some 'using System;' statement fixes needed by the Mono compiler.
+
+03/11/2003: beazley
+            Fixed subtle bug in the application of SwigValueWrapper<> to
+            template classes with default constructors.  Reported by
+            Bruce Lowery.
+
+03/11/2003: beazley
+            The $descriptor(type) variable is now expanded in code supplied to
+            %extend.  This is useful for certain kinds of advanced wrapping 
+            (especially container classes).
+
+03/11/2003: luigi
+            Support for std::map.
+            (a) Integration with scripting language (a la std::vector) for
+                Python, Ruby, MzScheme, and Guile;
+            (b) Simple wrapper for other languages
+
+03/10/2003: beazley
+            Fixed problem with escape sequences in string and character constants.  SWIG
+            wasn't parsing certain octal codes correctly.
+
+03/07/2003: beazley
+            Fixed a variety of subtle preprocessor problems reported by
+            Sebastien Recio.
+
+            (a) Empty preprocessor values no longer generate "bad constant
+            value" errors.  For example:
+
+                  #define FOO
+                  #define FOO BAR
+
+            (b) Macro names can now span multiple lines (technically valid,
+            although questionable practice).  For example:
+
+                  #define A_LONG_MACRO_\
+                  NAME 42
+
+            (c) Whitespace is no longer required before certain macro values.
+            For example:
+
+                  #define FOO"Hello"
+                  #define BAR\
+                  "Hello"
+ 
+03/07/2003: ljohnson (Lyle Johnson)
+            [Ruby] Added missing long long and unsigned long long typemaps
+            in the Lib/ruby/typemaps.i library file.
+
+03/07/2003: mrose (Mark Rose)
+            Added Examples/python/callback to demostrate how directors can
+	    be used to implement callbacks in Python
+	    Added Examples/python/extend to demonstrate virtual method
+	    calls from C++ to Python (really the same as the callback
+	    example, just a different context).
+	    Added four tests for very basic director functionality.  These
+	    have runtime tests under python.
+	    The Python module now emits #define SWIG_DIRECTORS near the
+	    top of the output file if directors are enabled.  This is useful
+	    for disabling parts of tests in target languages that don't
+	    support directors.
+
+03/06/2003: mrose (Mark Rose)
+            Added a section to Doc/Manual/Python.html on cross language
+	    polymorphism (directors).
+
+03/06/2003: mrose (Mark Rose)
+            The short-lived "-fdirectors" command line option has been
+	    removed.  To enable directors, instead use the extended %module 
+	    directive as follows:
+
+	        %module(directors="1") modulename
+
+03/06/2003: cheetah (William Fulton)
+            The long long typemaps have been rewritten so that they can be more
+            easily used with non ISO compilers, like Visual C++. For example
+            if you are wrapping the Windows 64 bit type __int64 the long long
+            typemaps can be used with %apply:
+
+                %apply long long { __int64 };
+                __int64 value1(__int64 x);
+
+            __int64 will now appear in the generated code instead of long long.
+            
+03/06/2003: beazley
+            *** DEVELOPER CHANGE ***
+            Swig module mutation has been changed slightly.  When a language
+            class method wants to save node attributes, it now uses one of the
+            following functions:
+
+                  Swig_require()
+                  Swig_save()
+
+            The first argument to these functions is a namespace in which
+            saved attributes are placed.  For example,this code
+
+                  Node *n;
+                  Swig_save("cDeclaration",n,"type","parms","name",NIL);
+
+            saves the attributes as "cDeclaration:type", "cDeclaration:parms",
+            and so forth.   If necessary, a language module can refer to
+            old values by using this special namespace qualifier.
+
+            In addition to this, a special attribute "view" contains the name
+            of the last namespace used to save attributes.  In the above 
+            example, "view" would have the value "cDeclaration".   The value
+            of "cDeclaration:view" would have the previous view and so forth.
+
+            Swig_restore(n) restores a node to the state before the last
+            Swig_require() or Swig_save() call.
+
+            Note:  This change makes it easier for language modules to refer
+            to old values of attributes.  
+
+
+03/06/2003: mrose (Mark Rose)
+            Merged the cross-language polymorphism patch.  When enabled, C++ 
+	    "proxy" classes (called directors) are generated for each specified 
+	    C++ class.  Directors pass method calls from C++ to Python, similar 
+	    to the way the usual proxy (shadow) classes pass method calls from 
+	    Python to C++.  Together, these two types of proxies allow C++ 
+	    classes that are extended in Python to behave just like ordinary 
+	    C++ classes and be used in C++ like native objects.  
+	    
+	    This feature is still very experimental and is disabled by default.
+	    To enable director support, specify '-fdirectors' on the SWIG command
+	    line or in the SWIG_FEATURES environment variable.  In the interface
+	    file, add %feature("director") to generate directors for all classes
+	    that have virtual methods.  
+	    
+	    See http://stm.lbl.gov/~tm2/swig/ProxyDoc.html for more details.
+	    
+
+03/03/2003: beazley
+            Fixed a small glitch in typemap local variable replacement.  If you had
+            a typemap like this:
+
+                 %typemap(in) type ($1_type temp) {
+                      ...
+                      temp = ...;
+                      ...
+                 }
+
+            and no occurrence of "$1_type" appeared in the body, then the local
+            variable type wouldn't be substituted.
+
+03/03/2003: cheetah (William Fulton)
+            [C#] New version of the CSharp module which is typemap based.
+            It also uses ECMA C# and no longer uses Microsoft Visual C++.NET 
+            glue. This means that it will work on non-Windows platforms.
+            Contributed by Neil Cawse.
+
+02/27/2003: beazley
+            Fixed [ 653548 ] error parsing casting operator definition.
+            SWIG now ignores casting operators declared outside of a class.
+            For example:
+
+                inline A::operator char *() { ... }
+
+            Bug reported by Martin Casado.
+
+02/27/2003: beazley
+            Added support for anonymous bit-fields.  For example:
+
+                 struct Foo {
+                      int x : 4;
+                      int   : 4;
+                      int y : 8;
+                 };
+
+            Anonymous bit-fields are ignored by SWIG.   Problem
+            reported by Franz Höpfinger.
+
+02/26/2003: cheetah (William Fulton)
+            [Java] Better typemaps in the Examples/java/typemap example and also 
+            fixes subtle bug when using the StringBuffer typemaps more than once.
+
+02/26/2003: beazley
+            Fixed [ 642112 ] Constants char bug.
+
+02/26/2003: beazley
+            Fixed [ 675337 ] Partial template specialization not entirely working.
+            There was a subtle problem related to the naming and ordering of
+            template partial specialization arguments.  Matching worked okay,
+            the resulting templates weren't expanded correctly.
+
+02/25/2003: beazley
+            Fixed problem with parsing (and generating code) for 
+            references to arrays.  For example:
+
+                int foo(int (&x)[10]);
+  
+02/25/2003: beazley
+            Fixed [ 635347 ] Compilation warning from libpy.c.
+            Reported by Daniel L. Rall.
+ 
+02/25/2003: beazley
+            Fixed a subtle problem with virtual method implementation
+            checking and typedef.
+
+                 typedef int *intptr;
+
+                 struct A {
+                    virtual int *foo() = 0;
+                 };
+                 struct B : public A {
+                    virtual intptr foo() { };
+                 };
+
+            SWIG was treating these declarations as different even though
+            they are the same (via typedef).
+
+02/25/2003: ljohnson (Lyle Johnson)
+            [Ruby] Added range checking for the NUM2USHRT macro, per [ 675353 ].
+
+02/24/2003: beazley
+            Fixed a subtle problem with the code that determined if a class is abstract
+            and can be instantiated.    If you had classes like this:
+
+                  struct A {
+                     virtual int foo(int) = 0;
+                  };
+                  struct B : virtual A {
+                     virtual int foo(int);
+                  };
+
+                  struct C : virtual A { 
+                  };
+
+                  /* Note order of base classes */	
+                  struct D : B, C { };    /* Ok */
+                  struct E : C, B { };    /* Broken */
+
+            then SWIG determined that it could instantiate D(), but not E().
+            This inconsistency arose from the depth-first search of the 
+            inheritance hierarchy to locate the implementations of virtual
+            methods.   This problem should now be fixed---SWIG will attempt
+            to locate any valid implementation of a virtual method by
+            traversing over the entire hierarchy.
+
+02/22/2003: cheetah (William Fulton)
+            [Java] Fix for using enum typemaps. The Java final static variable type
+            can be set using the jstype typemap, enabling enums to be mapped to 
+            something other than int. Bug reported by Heiner Petith.
+
+02/21/2003: songyanf (Tiger)
+            Added CSharp (C#) module prototype
+            i.e. csharp.cxx & csharp.h at Source/Modules/.
+            They are for test usage only now and need improvement.
+            The interface also need to be modified.
+
+            *** NEW FEATURE ***
+        
+02/20/2003: songyanf (Tiger)
+            Fixed problem with typedef with -fvirtual.
+            Similar as beazley's modification today.
+
+02/20/2003: beazley
+            Added support for gcc-style variadic preprocessor macros.  
+            Patch [ 623258 ] GCC-style vararg macro support.
+            Contributed by Joe Mason.
+
+02/20/2003: beazley
+            Fixed [ 605162 ] Typemap local variables.
+            Reported by Lyle Johnson.
+
+02/20/2003: beazley
+            Fixed problem with abstract classes and typedef.  For example:
+
+               class Foo {
+               public:
+                  virtual void foo(int x) = 0;
+               };
+
+               typedef int Integer;
+               class Bar : public Foo {
+               public:
+                  virtual void foo(Integer x);
+               };
+
+            SWIG was getting confused about the latter method---making Bar
+            abstract.  Reported by Marcelo Matus.
+
+02/19/2003: cheetah (William Fulton)
+            [Java] %javaconst(flag) can also be used on enums as well as constants.
+            This feature enables true Java compiler constants so that they can be 
+            used in Java switch statements. Thanks to Heiner Petith for patches.
+
+02/19/2003: songyanf (Tiger)
+            Modified -fcompact feature to deal with PP lines
+
+02/18/2003: beazley
+            Fixed [ 689040 ] Missing return value in std_vector.i.
+            Reported by Robert H. de Vries.
+
+02/18/2003: beazley
+            Fixed a few evil scoping problems with templates, namespaces, and the
+            %extend directive.  Problem reported by Luigi Ballabio.
+
+
+02/18/2003: cheetah (William Fulton)
+            [Ruby] Improved support for Visual C++ and other native Windows compilers. 
+            It is no longer necessary to specify "/EXPORT:Init_<module>", where <module> is the
+            swig module name when linking using these native Windows compilers.
+
+02/15/2003: songyanf (Tiger)
+            Added -fvirtual option.
+            Reduce the lines and size of the wrapper file
+            by omitting redifined virtual function in children classes.
+
+            Modified -compact option to -fcompact option
+
+            Added -small option.
+            -small = -fvirtual -fcompact
+            And it can be extended by future feature options,
+            which are used to reduce wrapper file szie.
+
+            Added SWIG_FEATURES environment variable check.
+            To dynamically set the feature options such as -fcompact & -fvirtual
+            *** NEW FEATURE ***
+
+02/13/2003: lenz
+            Updated Doc/Manual/Perl5.html to talk about C++ compile problems
+            configure.in now checks for PERL5_CCFLAGS
+            Runtime/Makefile.in and Example/Makefile.in now use PERL5_CCFLAGS
+            Added Lib/perl5/noembed.h which contains all the known macro conflicts
+
+02/12/2003: beazley
+            Fixed [ 685410 ] C++ Explicit template instantiation causes SWIG to exit.
+            Fixes a syntax error with declarations similar to this:
+
+                 template class std::vector<int>;
+
+            SWIG now ignores the instantiation and generates a warning message.
+            We might do more later.  Reported by Thomas Williamson.
+
+02/11/2003: cheetah (William Fulton)
+            Rewrote bool typemaps to remove performance warning for compiling generated code
+            under Visual C++.
+
+02/11/2003: cheetah (William Fulton)
+            Fix for wrapping reference variables (const non-primitive and all non-const types) 
+            for example:
+              int& i;
+              Class& c;
+              const Class& c;
+
+02/11/2003: beazley
+            Fixed more very subtle preprocessor corner cases related to recursive
+            macro expansion.  For example:
+
+                   #define cat(x,y) x ## y
+
+                   cat(cat(1,2),3)    // Produces: cat(1,2)3
+                   
+                   #define xcat(x,y) cat(x,y)
+
+                   xcat(xcat(1,2),3)  // Produces 123
+
+            See K&R, 2nd Ed. p. 231.
+
+02/10/2003: cheetah (William Fulton)
+            Fixed [ 683882 ] - patch submitted by F. Postma for SWIG to compile on HP-UX.
+
+02/10/2003: beazley
+            Fixed subtle preprocessor argument expansion bug. Reported by Marcelo Matus.
+
+02/10/2003: songyanf
+            Added -compact option.
+            Reduce the lines and size of the wrapper file
+            by omitting comments and combining short lines.
+            *** NEW FEATURE ***
+ 
+02/07/2003: beazley
+            Fixed [ 651355 ] Syntax error with cstring.i
+            Reported by Omri Barel.
+
+02/07/2003: beazley
+            Fixed [ 663632 ] incompatibility with standard cpp.
+            This is a refinement that fixes this problem:
+
+                 // Some macro with an argument
+                 #define FOO(x)       x
+
+                 int FOO;        /* Not a macro---no arguments */
+ 
+02/05/2003: beazley
+            Fixed [ 675491 ] parse error with global namespace qualification.
+            Submitted by Jeremy Yallop.
+
+02/04/2003: beazley
+            Fixed bug in varargs processing introduced by the numinputs typemap parameter.
+
+01/08/2003: ttn
+	    [xml] Fix string-replacement ordering buglet.
+	    Thanks to Gary Herron.
+
+12/23/2002: cheetah (William Fulton)
+            Further build changes:
+            - The SWIG executable is now built using a single Makefile.
+            - This makefile is generated by Automake (Source/Makefile.am).
+            - Dependency tracking and tags support are in this makefile.
+            - Automake 1.7.2 and Autoconf 2.54 minimum versions are needed to build SWIG from CVS.
+            - Running ./autogen.sh now installs Autoconf/Automake support files into
+              Tools/config and these files are no longer stored in CVS.
+            - Bug fixes in 'make install' for systems using .exe executable extension and
+              ./configure --with-release-suffix=whatever
+
+12/16/2002: cheetah (William Fulton)
+            More build changes:
+            - Autoconf's AC_CANONICAL_HOST replaces proprietary approach for detecting build host.
+            - Autoconf support files moved to Tools/config.
+
+12/16/2002: cheetah (William Fulton)
+            Modifications to run on MacOS, submitted by Bernard Desgraupes.
+            Mainly ensuring generated files are output in the appropriate directory for
+            some modules.
+
+12/11/2002: cheetah (William Fulton)
+            Various build modifications and bug fixes:
+            - Simplification of version string. Use autoconf's PACKAGE_VERSION instead.
+            - Build time removed from SWIG version.
+            - Using standard autoconf config header generation.
+            - Updated old autoconf macros as reported by autoupdate.
+            - Removed $prefix in autoconf from search paths as autoconf won't expand them.
+            - Subtle bug fix where 'make prefix=/somewhere; make clean; make prefix=/somwhere/else'
+              produced an executable using the incorrect library directories.
+            - Added -ldflags commandline option for MzScheme, Ocaml, Pike and PHP.
+            - Fixed reporting of compiler used when using -version commandline option.
+            - SWIG web address added to -version commandline option.
+
+12/11/2002: beazley
+            Minor fix to Tcl dynamic cast typemaps. Reported by
+            Kristopher Blom.
+
+12/10/2002: beazley
+            Fixed subtle template argument replace bug.  Reported by
+            Chris Flatley.
+
+12/10/2002: beazley
+            Reverted CHANGES 09/03/2002, preprocessor argument evaluation.  Arguments
+            are not evaluated during collection, K&R, p. 230.
+
+12/06/2002: beazley
+            Fixed [ 649022 ] Compilation problems with KAI/KCC
+
+12/02/2002: beazley
+            SWIG 'rel-1-3' CVS branch merged back into the main branch.
+
+
+Version 1.3.17 (November 22, 2002)
+==================================
+11/19/2002: beazley
+            Fixed [ 613922 ] preprocessor errors with HAVE_LONG_LONG.
+            
+11/19/2002: beazley
+            Fixed [ 615480 ] mzscheme SWIG_MustGetPtr_.
+
+11/19/2002: beazley
+            Fixed [ 635119 ] SWIG_croak causes compiler warning.
+
+11/16/2002: cheetah (William Fulton)
+            [Java] Added typemaps for pointers to class members.
+
+11/15/2002: cheetah (William Fulton)
+            [Java] Bug fix: Overloaded C++ functions which cannot be overloaded in Java 
+            once again issue a warning.
+
+11/14/2002: cheetah (William Fulton)
+            [Java] Handling of NULL pointers is improved. A java null object will now
+            be translated to and from a NULL C/C++ pointer by default. Previously when 
+            wrapping:
+
+                class SomeClass {...};
+                void foo(SomeClass *s);
+
+            and it was called from Java with null:
+
+                modulename.foo(null)
+
+            a Java NullPointerException was thrown. Extra typemaps had to be written in
+            order to obtain a NULL pointer to pass to functions like this one. Now the 
+            default wrapping will detect 'null' and translate it into a NULL pointer.
+            Also if a function returns a NULL pointer, eg:
+            
+                SomeClass *bar() { return NULL; }
+            
+            Then this used to be wrapped with a SomeClass proxy class holding a NULL
+            pointer. Now null is returned instead. These changes are subtle but useful.
+            The original behaviour can be obtained by using the original typemaps:
+
+                %typemap(javaout) SWIGTYPE {
+                    return new $&javaclassname($jnicall, true);
+                  }
+                %typemap(javaout) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+                    return new $javaclassname($jnicall, $owner);
+                  }
+                %typemap(javagetcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] %{
+                  protected static long getCPtr($javaclassname obj) {
+                    return obj.swigCPtr;
+                  }
+                %}
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+
+11/12/2002: beazley
+            Fixed problem with abstract methods and signatures.  For example:
+
+            class abstract_foo { 
+            public: 
+                virtual int   meth(int meth_param) = 0; 
+            }; 
+ 
+ 
+            class abstract_bar : public abstract_foo { 
+            public: 
+                int meth(int meth_param_1, int meth_param_2) { return 0; }
+            };
+
+            In this case, abstract_bar is still abstract.
+
+            Fixes [ 628438 ] Derived abstract class not abstract.
+            Reported and patched by Scott Michel.
+
+11/11/2002: beazley
+            Fixed a matching problem with typemaps and array dimensions.  For example, if you
+            had this:
+
+               typedef char blah[20];
+
+            and a typemap:
+
+               %typemap() char [ANY] {
+                   ... $1_dim0 ...
+               }
+
+            then $1_dim* variables weren't be expanded properly.  It should work now.
+            Problem reported by Pankaj Kumar Goel.
+               
+11/07/2002: mkoeppe
+	    Added an experimental new module that dumps SWIG's parse
+	    tree as (Common) Lisp s-expressions.  The module is
+	    invoked with SWIG's -sexp command-line switch.  The output
+	    can be read into Common Lisp.  There is (prototype)
+	    example Lisp code that generates Foreign Function Interface
+	    definitions for use with Kevin Rosenberg's UFFI.
+
+	    *** EXPERIMENTAL NEW FEATURE ***
+
+11/07/2002: mkoeppe
+	    Removed duplicate declaration of "cpp_template_decl" in
+	    parser.y; bison 1.75 complained.
+
+11/06/2002: cheetah (William Fulton)
+            [Java] Default primitive array handling has changed like arrays of classes. 
+            C primitive arrays are no longer wrapped by a Java array but with a pointer 
+            (type wrapper class). Again the changes have been made for efficiency reasons. 
+            The original typemaps have been moved into arrays_java.i, so the original 
+            behaviour can be obtained merely including this file:
+
+                %include "arrays_java.i"
+
+            The array support functions are no longer generated by default. They are only
+            generated when including this file, thus this often unused code is only
+            generated when specifically requiring this type of array support.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+11/05/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added support for nested module declarations (as was
+            previously added for the Perl module). So a %module directive
+            of the form:
+
+                %module "Outer::Inner::Foo"
+
+            will nest everything as (in Ruby code):
+
+                module Outer
+                  module Inner
+                    module Foo
+                      # stuff goes here
+                    end
+                  end
+                end
+ 
+11/05/2002: mkoeppe 
+	    [MzScheme] Add an argument (-declaremodule) that generates
+	    code to correctly declare a primitive module extension.
+	    Patch submitted by Bruce Butterfield.
+
+11/02/2002: cheetah (William Fulton)
+            [Java] Added patch submitted by Michael Cahill to remove unused parameter
+            warnings for the jenv and cls parameters. This patch also also allows one
+            to use "void" in the jni typemap for any type without code being generated
+            attempting to return a value.
+
+10/29/2002: cheetah (William Fulton)
+            [Java] Array handling is different. Arrays of classes are no longer wrapped
+            with proxy arrays, eg wrapping
+
+                class X {...};
+                X foo[10];
+            
+            used to be wrapped with these Java getters and setters:
+
+                public static void setFoo(X[] value) {...}
+                public static X[] getFoo() {...}
+
+            This approach is very inefficient as the entire array is copied numerous
+            times on each invocation of the getter or setter. These arrays are now
+            wrapped with a pointer so it is only possible to access the first array element 
+            using a proxy class:
+
+                public static void setFoo(X value) {...}
+                public static X getFoo() {...}
+
+            Arrays of enums have also been similarly changed. This behaviour is now like the 
+            other SWIG language's implementation and the array library should be used to 
+            access the other elements. The original behaviour can be achieved using the 
+            macros and typemaps in arrays_java.i, for example:
+
+                %include "arrays_java.i"
+                JAVA_ARRAYSOFCLASSES(X)
+                class X {...};
+                X foo[10];
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+10/29/2002: cheetah (William Fulton)
+            [Java] Two new typemaps javain and javaout for generating the proxy class 
+            and type wrapper class method calls to the JNI class. The new typemaps are 
+            really used for transforming the jstype (used in proxy class and type wrapper
+            classes) to the jtype (used in the JNI class) and visa versa. A javain typemap
+            is required whenever an in typemap is written and similarly javaout for an out
+            typemap. An example is probably best to show them working:
+
+                %typemap(javain) Class "Class.getCPtr($javainput)"
+                %typemap(javain) unsigned short "$javainput"
+                %typemap(javaout) Class * {
+                    return new Class($jnicall, $owner);
+                  }
+
+                %inline %{
+                    class Class {};
+                    Class * bar(Class cls, unsigned short ush) { return new Class(); };
+                %}
+
+            The generated proxy code is then:
+
+                public static Class bar(Class cls, int ush) {
+                  return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), false);
+                }
+
+
+            Some new special variables have been introduced in order to use these typemaps.
+            Here $javainput has been replaced by 'cls' and 'ush'. $jnicall has been replaced by 
+            the native method call, 'exampleJNI.bar(...)' and $owner has been replaced by 'false'.
+            $javainput is analogous to the $input special variable. It is replaced by the parameter name.
+            $jnicall is analogous to $action in %exception. It is replaced by the call to the native
+            method in the JNI class.
+            $owner is replaced by either true if %newobject has been used otherwise false.
+
+            The java.swg file contains default javain and javout typemaps which will produce the same code
+            as previously. This change is only of concern to those who have written their own typemaps as
+            you will then most likely have to write your own javain and javaout typemaps.
+
+            The javaout typemap also makes it possible to use a Java downcast to be used on abstract 
+            proxy base classes. See the Java documentation on dynamic_cast.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+10/24/2002: ttn
+	    [Methodology] Upgaded to libtool 1.4.3, presumably w/ better
+	    support for newish platforms (like MacOS X).
+
+10/21/2002: ttn
+	    Fixed Runtime/Makefile.in bug -- thanks to Richard Calmbach.
+
+10/18/2002: ttn
+	    Fixed typo in doh.h -- thanks to Max Horn.
+
+Version 1.3.16 (October 14, 2002)
+=================================
+
+10/13/2002: beazley
+            Fixed bug with %extend directive and %feature reported
+            by William Fulton.
+
+10/13/2002: beazley
+            Added OpenVMS build directory (vms).  Contributed by 
+            Jean-François Pieronne.
+
+10/09/2002: cheetah (William Fulton)
+            [Java] Added throws clause to the native functions in the JNI class.
+            The throws clause is the same as the one generated for proxy functions
+            and module class functions.
+
+09/27/2002: beazley
+            Fixed some problems with the %import directive and classes that
+            were defined but not wrapped.  Problem reported by Leslie Brooks,
+            Gerry Woods, and others.
+
+09/23/2002: cheetah (William Fulton)
+            [Java] Some error checking added:
+            1) OutOfMemoryException check in the char * typemaps. 
+            2) As SWIG treats pointers, references and passing by value all the
+            same, it is possible to pass a NULL pointer to a function that expects
+            an object passed by value or by reference. A NullPointerException is 
+            now thrown under this scenario.
+
+09/20/2002: ttn
+	    [Methodology] Reworked "make clean" and "make install"
+			  to be more table driven.
+	    [Docs] Explain how to extend "make install" w/ extra-install.list.
+
+09/15/2002: beazley
+            Deprecation of the "ignore" typemap.   The "ignore" typemap has
+            been deprecated in favor of a generalization of the "in" typemap.
+            To ignore an argument, use something like this instead:
+
+                %typemap(in,numinputs=0) int *output (int temp) {
+                     $1 = &temp;
+                }
+
+            This change fixes a number of subtle bugs related to the interaction
+            of the "in" and "ignore" typemaps (which were supposed to be
+            mutually exclusive).
+
+            The use of the numinputs argument is reserved for future expansion.
+            Currently, values >1 will generate an error.  However, future
+            releases of SWIG may utilize that to support multi-input typemaps.
+
+            %typemap(ignore) still works, but generates a warning message and is
+            translated to %typemap(in,numinputs=0).
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            *** NEW FEATURE ***
+
+09/15/2002: beazley
+            Fixed segmentation fault for unnamed structures.  For example:
+
+               typedef struct {
+               } *blah;
+
+
+            Reported by Roger Gibson.
+            Note: we might be able to generate wrappers in special cases.
+
+09/13/2002: beazley
+            Minor modification to generated wrapper functions.  Pointer arguments are now
+            always set to an initial value of 0.   Simplifies typemap writing and cleanup
+            code (since you can rely on zero-value initialization).   This also greatly
+            reduces the need to ever write an "arginit" typemap.
+
+09/12/2002: beazley
+            Minor enhancement to smart-pointer support.  If operator->()
+            is part of an ignored base class like this,
+
+                 %ignore Bar;
+
+                 class Foo {
+                 public:
+                     int blah();
+                 };
+
+                 class Bar {         /* Ignored */
+                 public:
+                     ...
+                     Foo *operator->();
+                     ...
+                 };
+
+                 class Spam : public Bar { };
+
+            then methods from Foo are still available.  For example,
+
+                 >>> s = Spam()
+                 >>> s.blah()
+                 0
+                 >>>
+
+             The only catch is that the operator->() itself is not available
+             (since it wasn't wrapped).   Therefore, there won't be any
+             __deref__() operation unless it is explicitly added to Spam
+             (either using %extend or just placing operator->() in the
+             definition of Spam).
+
+09/11/2002: ttn
+	    [Methodology] Reworked "make check" to be more table driven.
+	    [Docs] Docuemented methodology in Manual/Extending.html.
+
+09/11/2002: ttn
+	    [Docs] Prefixed Manual/*.html with "<!DOCTYPE html ...>" to
+	    pander dotingly to (over-)sensitive editors.
+
+09/10/2002: ttn
+	    [Guile] Converted Examples/guile/simple "make check"
+	    behavior to actually check execution results.  Reduced
+	    iteration counts so that the test doesn't take too long.
+
+09/10/2002: beazley
+            SWIG-1.3.15 released.
+
+
+Version 1.3.15 (September 9, 2002)
+==================================
+09/09/2002: beazley
+            Fixed nasty runtime type checking bug with subtypes and inheritance
+            and templates. 
+
+09/09/2002: cheetah (William Fulton)
+            [Java] Java exception classes for a method's throws clause can be generated by 
+            specifying them in a comma separated list in the throws attribute in any one
+            of the following typemaps: in, out, check, freearg, argout and throws. A classic
+            example would be to convert C++ exceptions into a standard Java exception:
+
+                %typemap(throws, throws="java.io.IOException") file_exception {
+                    jclass excep = jenv->FindClass("java/io/IOException");
+                    if (excep)
+                        jenv->ThrowNew(excep, $1.what());
+                    return $null; // or use SWIG_fail
+                }
+
+                class file_exception {...};
+                void open(const char *filename) throw(file_exception);
+
+            The Java method will then be declared with a throws clause:
+
+                public static void open(String filename) throws java.io.IOException {...}
+
+09/08/2002: mkoeppe
+	  * [Guile] Improved the documentation system.  The arglist no
+	    longer gets cluttered with type specification, making it
+	    more readable.  (Also the ILISP function C-u M-x
+	    `arglist-lisp' RET works better this way.)  The types of
+	    arguments are explained in an extra sentence after the
+	    arglist. 
+	    
+	    There are now two documentation-related typemap arguments:
+
+	        %typemap(in, doc="$NAME is a vector of integers", 
+			 arglist="$name")  int *VECTOR { ... }
+			 
+            The "arglist" texts of all arguments of a function make up
+	    its arglist in the documentation.  The "doc" texts of all
+	    arguments are collected to make a sentence that describes
+	    the types of the arguments.  Reasonable defaults are
+	    provided. 
+
+	    As usual, $name is substituted by the name of the
+	    argument. The new typemap variable $NAME is like $name,
+	    but marked-up as a variable.  This means that it is
+	    upper-cased; in TeXinfo mode ("-procdocformat texinfo") it
+	    comes out as @var{name}. 
+	    
+	    The directives %values_as_list, %values_as_vector,
+	    %multiple_values now also have an effect on the
+	    documentation. (This is achieved via the new pragmas
+	    return_nothing_doc, return_one_doc, return_multi_doc.)
+
+	    Documentation has also improved for variables that are
+	    wrapped as procedures-with-setters (command-line switch
+	    "-emit-setters").
+
+          * [Guile] Emit constants as _immutable_ variables.  (This
+            was broken recently.)
+
+09/07/2002: mkoeppe
+	    [Guile] Updated the typemaps in list-vector.i.
+
+09/07/2002: mkoeppe
+	    Short-circuit the typechecks for overloaded functions.
+	    (The changes in code generation are visible in the new
+	    testcase "overload_complicated".)
+
+09/06/2002: cheetah (William Fulton)
+            [Java] Solution for [ 596413 ]
+            New typemap so that the Java proxy classes and type wrapper classes
+            wrapper constructor modifier can be tailored by users. The default value is 
+            protected. Normally SWIG generates a constructor like this which can only 
+            be accessed within one package:
+
+              protected Bar(long cPtr, boolean cMemoryOwn) {
+              ...
+              }
+            
+            If you are using SWIG across multiple packages or want to use this constructor
+            anyway, it can now be accessed outside the package. To modify use for example:
+
+              %typemap(javaptrconstructormodifiers) SWIGTYPE "public"
+
+            to change to public for all proxy classes and similarly for all type wrapper classes:
+            
+              %typemap(javaptrconstructormodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "public"
+
+09/06/2002: cheetah (William Fulton)
+            [Java] Added throws typemaps for the Java module. C++ exceptions get converted into
+            java.lang.RuntimeException Java exceptions. 
+            
+            Warning: This may change from java.lang.Runtime exception in the future.
+
+09/05/2002: cheetah (William Fulton)
+            [Java] Fix for variables declared as references.
+
+09/05/2002: beazley
+            Fixed [ 605162 ] Typemap local variables. Reported by Lyle Johnson.
+
+09/05/2002: ljohnson (Lyle Johnson)
+            [Ruby] More updates to the Ruby module documentation, including
+	    a new typemap example that demonstrates how to collect key-value
+	    pairs from an argument list into a Hash.
+
+09/05/2002: beazley
+            Fixed bug with template expansion and constructors.
+
+                template<class T> class Foo {
+                public:
+                    Foo<T>() { }
+                };
+
+            The extra <T> in the constructor was carried through in the
+            name--causing runtime problems in generated modules.
+            Reported by Jordi Arnabat Benedicto.
+ 
+09/05/2002: mkoeppe
+	    [Guile] Support overloading.
+
+09/04/2002: ljohnson (Lyle Johnson)
+            [Ruby] Updated typemaps for long long and unsigned long long types
+	    to use Ruby 1.7 support for these types when available.
+
+09/04/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added output typemaps for const reference to primitive
+	    types.
+
+09/04/2002: mkoeppe
+	    [Guile] Fix pass-by-value typemaps.  Reported by Arno
+	    Peters via Debian bugtracking (#156902), patch by Torsten
+	    Landschoff <torsten@debian.org>.
+
+09/03/2002: samjam (Sam Liddicott)
+	    Better reference support.
+	    Functions that want a void** can take a NULL by reference and
+	    the void* will be made for you and then passed-by-reference
+
+	    Also all integer-class native types can be passed by reference
+	    where an int* or int& etc is needed
+
+09/03/2002: beazley
+            Changed the evaluation order of preprocessor macro arguments.
+            Arguments are now expanded by the preprocessor *before* they
+            are passed to macro expansion.  This fixes a subtle expansion
+            bug reported by Anthony Heading.
+
+09/03/2002: beazley
+            Fixed the file include order (again, apparently). See 2/27/99.
+
+09/02/2002: beazley
+            [Perl] Better exception handling support.  Since Perl error handling
+            relies on setjmp/longjmp, wrapper functions have been modified slightly
+            to provide an extra block scope:
+
+                XS(foo) {
+                   char _swigmsg[SWIG_MAX_ERRMSG] = "";
+                   const char *_swigerr = _swigmsg;
+                   {
+                      /* Normal wrapper function here */
+                      ...
+                      SWIG_croak("An error occurred\n");
+                      ...
+                      XSRETURN(argvi);      /* Successful return */
+                      fail:
+                        /* cleanup code */
+                   }
+                   croak(_swig_err);
+                }
+
+            The macro SWIG_croak(x) sets the value of _swigerr to x and
+            executes a "goto fail".  The whole wrapper function is enclosed
+            block scope to provide proper cleanup of C++ objects.  Since
+            croak executes a longjmp(), there is no way to properly reclaim
+            resources if this executes in the same scope as the wrapper
+            function.
+
+            The _swigmsg[] variable is normally unused, but can be used
+            to store small error messages using sprintf or snprintf. It
+            has a capacity of at least 256 bytes (SWIG_MAX_ERRMSG).
+            
+09/02/2002: beazley
+            [Tcl] Added better support for exceptions.  Instead of returning TCL_ERROR,
+            use the macro SWIG_fail to return with an error.  This ensures that
+            arguments are properly cleaned up.  Exception specifiers are now
+            handled by default.
+
+09/02/2002: ljohnson (Lyle Johnson)
+            [Ruby] The type-checking system for the Ruby module has had a flaw
+	    in that some types which should be considered equivalent
+	    weren't. This bug was best demonstrated by the inherit_missing.i
+	    test suite case, which defines a base class "Foo" that is
+	    subclassed by "Bar". The "Foo" class isn't actually wrapped (i.e.
+	    it's not directly accessible from Ruby) but we'd still like to be
+	    able to pass "Bar" instances to functions expecting Foos and have
+	    that work; it wasn't. The revised implementation (similar to that
+	    used for some other language modules) adds a new instance variable
+	    (__swigtype__) to each object that indicates its SWIG type;
+	    that is, each "Bar" instance will now have a string instance
+	    variable called "__swigtype__" whose value is "_p_Bar".
+
+            Unless developers were taking advantage of this low-level
+	    implementation detail, they shouldn't notice any compatibility
+	    problems; nevertheless, I'm marking it as a "potential
+	    incompatibility".
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+09/01/2002: ljohnson (Lyle Johnson)
+            [Ruby] Fixed SF Bug #603199.
+
+08/08/2002: cheetah (William Fulton)
+            [Java] Added OUTPUT, INPUT and INOUT typemaps in typemaps.i for C++ 
+            references.
+
+08/27/2002: mkoeppe
+	    [Guile] Fixed error in "lib_std_vector" testcase and
+	    compiler warning in "lib_cdata" testcase.
+
+08/27/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added the "%mixin" directive, which allows the user to
+	    specify a comma-separated list of module names to mix-in to a
+	    class. So, for example, if you'd like to specify that Ruby's
+	    Enumerable module should be mixed-in to your class Foo, you'd
+	    write:
+	    
+	        %mixin Foo "Enumerable";
+		
+            or to specify that the modules Fee, Fie and Fo should be mixed
+	    in to Foo:
+	    
+	        %mixin Foo "Fee,Fie,Fo";
+		
+	    *** NEW FEATURE ***
+
+08/27/2002: ljohnson (Lyle Johnson)
+            [Ruby] Modified the %alias directive so that multiple aliases
+	    can be specified for an instance method by using a comma-separated
+	    list of aliases.
+
+08/27/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added "throw" typemaps for the Ruby module.
+
+08/26/2002: beazley
+            Two new command line options for printing dependencies.
+            'swig -M' lists all file dependencies.  'swig -MM' lists
+            dependencies, but excludes files in the SWIG library. 
+            Example:
+
+               % swig -M -python example.i
+               example_wrap.cxx: \
+                /u0/beazley/Projects/lib/swig1.3/swig.swg \
+                /u0/beazley/Projects/lib/swig1.3/python/python.swg \
+                example.i \
+                example.h 
+
+               % swig -MM -python example.i
+               example_wrap.cxx: \
+                example.i \
+                example.h 
+
+            *** NEW FEATURE ***
+
+08/26/2002: beazley
+            Fixed [ 597599 ] union in class: incorrect scope.
+            Reported by Art Yerkes.
+
+08/26/2002: beazley
+            Fixed [ 600132 ] Default argument with namespace. 
+            Reported by Shibukawa Yoshiki.
+ 
+08/24/2002: beazley
+            Automatic C++ exception handling enabled for all language modules.    This is
+            pretty simple.  If you have a class like this:
+
+                class Foo {
+                };
+                class Bar {
+                public:
+                    void blah() throw(Foo);
+                }
+
+            then the generated wrapper code looks like this:
+
+                  wrap_Bar_blah() {
+                       ...
+                       try {
+                           arg1->blah();
+                       } 
+                       catch (Foo &_e) {
+                           /* "throw" typemap code inserted. $1 = _e */
+                       }
+                       catch (...) {
+                          throw;
+                       }
+                  }
+            The "throw" typemap can be used to raise an error in the target 
+            language.  It can do anything.  Here is a very simple example:
+
+                 %typemap("throw") Foo {
+                     PyErr_SetString(PyExc_RuntimeError, "Foo exception");
+                     return NULL;
+                 }
+
+            To make this work in each language module, simply define a few default
+            "throw" typemaps for SWIGTYPE, SWIGTYPE *, int, const char *, and a
+            few common exception types.   That's all there is to it.
+
+            Automatic exception handling can be disabled using -noexcept or
+            setting the NoExcept global variable to 1.
+            *** NEW FEATURE ***
+
+08/23/2002: beazley
+            [ Python ]
+            Automatic translation of C++ exception specifications into error handling code.
+            For example:
+ 
+                class Foo {
+                };
+                class Bar {
+                public:
+                    void blah() throw(Foo);
+                }
+
+            In this case, Foo is wrapped as a classic-style class (compatible
+            with exception handling).  Furthermore, you can write Python code
+            like this:
+
+                b = Bar()
+                try:
+                    b.blah();
+                except Foo,e:     # Note use of exception class here!
+                    # Handle Foo error
+                    ...
+
+            The object "e" in the exception handler is just a wrapped Foo
+            object.  Access it like a normal object.
+
+            If an exception is not wrapped as a class, a RuntimeError
+            exception is raised.  The argument to this exception is
+            the exception object.  For example:
+ 
+                class Bar {
+                public:
+                    void blah() throw(int);
+                }
+
+                b = Bar()
+                try:
+                   b.blah();
+                except RuntimeError,e:
+                   print e.args[0]       # Integer exception value
+
+            Comments:
+
+                -  If a class is used as an exception, it *must* be wrapped
+                   as a Python classic-style class (new classes don't work).
+
+                -  Automatic exception handling is compatible with %exception.
+
+                -  Use -noexcept to turn off this feature.
+
+                -  The newly introduced "throw" typemap is used to raise
+                   Python errors (naturally).
+
+            *** EXPERIMENTAL NEW FEATURE ***
+
+08/23/2002: beazley
+            Information from throw() specifiers is now stored in the parse
+            tree.  For example:
+
+                class Foo {
+                public:
+                     int blah() throw(spam,bar);
+                }
+
+            The stored information is fully corrected for namespaces and works
+            with templates.  Uses will follow.
+            
+08/22/2002: beazley
+            Exception handling code is no longer applied to member access
+            function.  For example, in this code
+
+                %exception {
+                   try {
+                      $action
+                   } catch(whatever) {
+                      ...
+                   }
+                }
+
+                class Foo {
+                public:
+                    int x;
+                    ...
+                }
+
+            The exception handling code is not applied to accessor functions
+            for Foo::x.   This should reduce the amount of extra code
+            generated.
+
+            Caveat:  Exception handling code *is* used when attributes are
+            accessed through a smart-pointer or a synthesized attributed
+            added with %extend is used.
+
+08/22/2002: beazley
+            Made more patches to hopefully eliminate problems when compiling SWIG 
+            as a 64-bit executable.
+
+08/22/2002: beazley
+            Fixed a bug with const reference members, variables, and static members.
+            For example:
+
+                  class Foo {
+                  public:
+                       static const int &ref;
+                  };
+
+            SWIG was trying to generate "set" functions which wouldn't compile. 
+
+08/21/2002: beazley
+            Made the warning message for "Class X might abstract" off by default.
+            Enable with -Wall.
+
+08/21/2002: beazley
+            Refined handling of const and non-const overloaded methods.  If
+            a class defines a method like this:
+
+                class Foo {
+                public:
+                    int bar(int);
+                    int bar(int) const;
+                }
+
+            Then the non-const method is *always* selected in overloading and
+            the const method silently discarded.  If running with -Wall, a warning
+            message will be generated.
+
+08/19/2002: beazley
+            Better support for using declarations and inheritance.   Consider this:
+
+                class Foo {
+                public:
+                      int blah(int x);
+                };
+
+                class Bar {
+                public:
+                      double blah(double x);
+                };
+
+                class FooBar : public Foo, public Bar {
+                public:
+                      char *blah(char *x);
+                      using Foo::blah;
+                      using Bar::blah;
+                };
+
+            Now SWIG wraps FooBar::blah as an overloaded method that uses all
+            accessible versions of blah().  See section 15.2.2 in Stroustrup, 3rd Ed.
+
+            SWIG also supports access change through using declarations.  For example:
+
+                class Foo {
+                protected:
+                     int x;
+                     int blah(int x);
+                };
+
+                class Bar : public Foo {
+                public:
+                     using Foo::x;
+                     using Foo::blah;
+                };
+
+
+            Caveat:   SWIG does not actually check to see if declarations imported
+            via 'using' are in the inheritance hierarchy.  If this occurs, the
+            wrapper code won't compile anyways---not sure it's worth worrying about.
+          
+08/18/2002: beazley
+            Modified overloading dispatch to not include nodes with an "error" attribute.
+            A language module can set this if a node couldn't be wrapped and you don't want
+            it included in the dispatch function.
+
+08/18/2002: beazley
+            Enhancement to overloaded function dispatch.   The dispatcher is now aware of
+            inheritance relationships.   For example:
+
+                   class Foo { };
+                   class Bar : public Foo { };
+                    
+                   void spam(Foo *f);
+                   void spam(Bar *b);
+
+            In this case, the dispatcher re-orders the functions so that spam(Bar *b) is
+            checked first---it is more specific than spam(Foo *f).
+
+08/17/2002: beazley
+            Added -Werror command line option.   If supplied, warning messages are treated
+            as errors and SWIG will return a non-zero exit code.
+
+08/17/2002: beazley
+            Fixed [ 596135 ] Typedef of reference can't compile.  For example:
+
+                 typedef int &IntRef;
+                 void foo(IntRef i);
+
+            SWIG-1.3.14 generated code that wouldn't compile.
+
+Version 1.3.14 (August 12, 2002)
+================================
+
+08/11/2002: mmatus
+	    Static const members initialized during declaration, and
+	    only them, ie:
+
+	    struct A
+	    {		 
+		static const int a = 1 ;  // this one
+		static const int b;       // not this one
+            };     
+
+	    are emitted like constants (equivalent to enums or
+	    explicit %constant).
+	    
+	    This is because they cannot be added directly to 'cvar'
+	    since they lack the needed reference (well, you can force
+	    them to have a real reference, but in an ugly way which
+	    goes completely again the original purpose of initialize
+	    them during declaration, you also have to deal with extra
+	    linking matters, and it take a while to figure out what is
+	    the problem and how to solve it).
+	    
+	    Please test it with your preferred target language, and
+	    not only the code generation, but really run the example
+	    in the test-suite (static-const-member-2.i) because the
+	    problem and the solution cannot be "fully" appreciated
+	    until you try to load the module and run it.
+
+	    In some target languages (python specially), this can
+	    produces a difference in the way that the static constant
+	    members 'a' and 'b' are internally wrapped. Hopefully,
+	    they still can be accessed in the same way.
+
+
+08/11/2002: mmatus
+	    [python] Now static const members can be accessed in a more
+	    natural way, ie, if you have
+
+	    struct A
+             {		 
+		typedef unsigned int viewflags;
+		static const viewflags forward_field = 0;
+		static const viewflags backward_field;
+            };     
+	    
+	    now you can do:
+
+		print A.backward_field
+
+	    and also
+
+	        a = A()
+		print a.forward_field
+		
+	    Note that if the static const members don't have an
+	    initializer (like backward_field), still you can access
+	    them in the same way in the python side, but the
+	    implementation is a quite different: backward_field will
+	    still appear in the cvar entity, and also, you are 
+	    responsible to initialize it in some code unit, and link it
+	    properly. forward_field, by the other hand, will not
+	    appear in the cvar entity but only as a A member, similar
+	    to what happen with enum or %constant members.
+
+08/11/2002: mmatus
+	    [python] Common code in the __setattr__/__getattr__ now
+	    goes to two "free" methods at the beginning of the proxy
+	    file, from where each class use it. This change reduces
+	    the size of the proxy file, specially if you wrap a lot of
+	    small classes in one module (up to 33% in some cases),
+	    making it faster to load too.
+
+08/09/2002: beazley
+            [Perl5] If a function that returns char * returns NULL,
+            undef is returned to the Perl interpreter.
+ 
+08/09/2002: beazley
+            Fix to conversion operators and namespaces.  For example:
+
+                namespace ns {
+                    struct Foo { };
+                    struct Bar {
+                        operator Foo*();
+                    };
+                }
+
+            In the wrapper code, SWIG was using ->operator Foo*()
+            when it should have been using ->operator ns::Foo*().
+
+            Note: if using %rename with a conversion operator, you
+            might have to do this:
+
+               %rename(toFooPtr) ns::operator ns::Foo*();
+                                      //      ^^^^ note extra qualifier
+               namespace ns {
+                    ...
+
+            
+08/09/2002: beazley
+            [Python] Minor enhancement to 'const' variable declarations. 
+            Normally const declarations are wrapped as read-only variables
+            accessible only through the cvar attribute (see SWIG.html for
+            a discussion of why).  However, in many programs, "const" 
+            declarations may just be constants---making the cvar. access
+            awkward.  To fix this, "const" declarations are now available
+            both through cvar. and as a simple name.  For example:
+
+                 const int FOO = 42;
+
+            In Python:
+
+                 >>> print example.cvar.FOO
+                 42
+                 >>> print example.FOO
+                 42
+
+            Note: There are cases where the value of a "const" variable
+            might change.  For example:
+
+                 char *const BAR = "Hello World";
+
+            In this case, the pointer itself can not change, but the 
+            data being pointed to could be modified.  In these situations,
+            cvar.BAR should be accessed to obtained the current value.
+
+08/08/2002: beazley
+            [Python] Fixed generation of the proxy code (.py files) to more
+            closely follow the order of declarations as they appear in
+            the .i file.   In the past, all of the class wrappers appeared
+            first, followed by function stubs, inserted Python code, and
+            other details.
+
+08/08/2002: cheetah (William Fulton)
+            [Java] Proxy method _delete() changed to delete(). There shouldn't ever
+            be a wrapped function called delete() as it is a C++ keyword and there
+            is no such thing as a member function in C.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+            Backwards compatibility can be achieved by adding the function back in
+            for all proxy classes:
+            %typemap(javacode) SWIGTYPE %{
+              public void _delete() {
+                delete();
+              }
+            %}
+
+            Java backwards compatibility summary
+            ------------------------------------
+
+            There are a number of changes that have been made in improving the Java module 
+            for ver 1.3.14.  If at all possible change your code to take advantages of the 
+            improvements. If you were using proxy classes you may not notice any backwards 
+            compatibility issues. Here is an example which will help with most backwards 
+            compatibility problems where it is not possible to modify the code that uses
+            the generated output:
+
+            Replace:
+                %module modulename
+
+            With:
+                %module (jniclassname="modulename") modulename;
+                %typemap(javacode) SWIGTYPE %{
+                    public long getCPtr$javaclassname() {
+                        return swigCPtr;
+                    }
+                    public void _delete() {
+                      delete();
+                    }
+                %}
+                %pragma(java) jniclassclassmodifiers="public";
+
+            The proxy constructors that took parameters (long cPtr, boolean cMemoryOwn)
+            were public and are now protected. If you were making use of these then you'll 
+            have to modify your code and the best solution would be to use the new type 
+            wrapper classes.
+
+            The other main areas are the pragmas and global variable wrapping. Replace 
+            the pragmas with one of the new directives or typemaps mentioned below and use
+            %rename on the variables.
+
+            If you were not using proxy classes, you will have to define a jstype typemap
+            as well as a jtype typemap.
+
+08/08/2002: cheetah (William Fulton)
+            [Java] Fix for wrapping two dimension array variables.
+
+08/07/2002: beazley
+            [Python,Tcl]
+            Object management now has a much better sense of ownership.
+            Ownership bits is changed whenever an object is stored in a
+            global variable or structure member.  For example:
+
+                struct Foo {
+                    int val;
+                    Foo *next;
+                };
+
+            Now in Python
+
+               >>> f = Foo()
+               >>> f.thisown
+               1
+               >>> g = Foo()
+               >>> g.next = f          # Assign a pointer
+               >>> f.thisown           # Notice ownership change
+               0
+               >>>
+
+            This scheme is mostly a conservative heuristic designed to 
+            provide segmentation faults.  It could cause a memory leak
+            if ownership is changed unnecessarily.  In this case, you can
+            either write a typemap (that doesn't change ownership), or
+            manually set the thisown attribute back to 1.
+
+08/07/2002: beazley
+            [Tcl] Major usability improvements to the object interface.
+            Suppose you had code like this:
+
+                 struct Foo { 
+                     int x;
+                     int spam();
+                 };
+
+                 void  blah(Foo *f);
+
+            In past versions of SWIG, you could create objects and use
+            them like this:
+
+                % Foo f
+                % f configure -x 3
+                % f spam
+                37
+    
+            The only problem is that if you tried to call blah(), it didn't
+            work:
+
+                % blah f
+                Type Error. Expected _p_Foo
+                %
+
+            Instead, you had to do this:
+
+                % blah [f cget -this]
+  
+            SWIG now automatically extracts the -this pointer, avoiding this
+            problem.  This means that saying "blah f" is perfectly legal and
+            everything will still work normally.
+
+            Caveat: Since pointer strings start with a leading underscore (_),
+            don't use this in object names.  For example:
+
+                % Foo _f 
+                % blah _f        # Potential crash
+
+            Objects now have a -thisown attribute that shows the ownership.
+            This builds upon the CHANGES 11/24/2001 entry.
+
+08/07/2002: samjam, Sam Liddicott
+            Properly implemented pointer system using php resources.
+            Still need to work out whether or not to let script-users call
+            destructors directly
+
+08/06/2002: beazley
+            Upgraded mzscheme module to support version 201 and added
+            overloading support.
+
+08/05/2002: beazley
+            Added parsing support for extra grouping (in very limited cases).
+            For example:
+
+                    typedef int (FuncPtr)(int, double);
+
+            *** EXPERIMENTAL ***
+            
+08/03/2002: ljohnson (Lyle Johnson)
+            [Ruby] Updates to typemaps.i as those done previously for Perl,
+            Python and Tcl modules. Now supports reference types with INPUT,
+            OUTPUT and INOUT typemaps.
+
+08/02/2002: beazley
+            New library file cstring.i added.  Provides macros for
+            manipulating char * data.
+ 
+08/02/2002: beazley
+            Deprecated the %new directive.  Use %newobject instead.  For
+            example:
+
+               %newobject foo;
+               ...
+               char *foo();
+
+            %newobject follows the same rules as %rename, %ignore, %feature,
+            etc.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+
+08/01/2002: cheetah (William Fulton)
+            [Java] New attribute 'jniclassname' for the module directive allows a way of
+            changing the JNI class name from the default which uses the modulename with JNI
+            appended after it.
+
+                %module (jniclassname="name") modulename
+
+            If 'name' is the same as 'modulename' then the module class name gets changed
+            from 'modulename' to modulenameModule.
+
+08/01/2002: beazley
+            Fixed problem with file include order.  Language specific
+            directories should take precedence over generic directories.
+            For example:  "swig_lib/python/foo.i" should be loaded before
+            "swig_lib/foo.i".    I thought this was the case already, but
+            apparently it has been broken for quite some time.
+
+08/01/2002: beazley
+            Added std_deque.i library file.  Work in progress.
+
+08/01/2002: beazley
+            [Python,Tcl,Perl]
+            Improvements to typemaps.i.  INPUT/INOUT typemaps perform better
+            error checking.  Typemaps are now supplied for references like 
+            int &OUTPUT, double &INOUT, etc.
+          
+08/01/2002: beazley
+            [Python] Deprecated the T_* and L_* typemaps in typemaps.i.
+            Multiple return values are always placed in a tuple. Deprecated
+            the BOTH typemaps.  This is now INOUT (e.g., int *INOUT).
+
+            *** POTENTIAL INCOMPATIBILITY FOR PYTHON MODULE ***
+
+08/01/2002: beazley
+            Deprecated the array.i, carray.i, and timer.i library files.
+
+08/01/2002: beazley
+            Deprecated the pointer.i library file.  Use cpointer.i instead.
+            *** POTENTIAL INCOMPATIBILITY ***
+            
+08/01/2002: cheetah (William Fulton)
+            [Java] For consistency the global variable getters and setters use the JavaBean 
+            property design pattern like member variables always have. This means if you are 
+            wrapping a variable called foo, the getter is called getFoo() and the setter is 
+            called setFoo(). Before the recent changes to the Java module the getters and 
+            setters were called get_foo() and set_foo(). If you really want the original 
+            function names use the %rename directive like this: %rename(_foo) Foo;
+
+07/31/2002: beazley
+            Fixed casting problem with multiple inheritance.  If you had this,
+
+                  class foo {};
+                  class bar : public foo {};
+                  class baz : public foo {};
+                  class spam : public bar, public baz {};
+
+            then the wrappers wouldn't compile due to an ambiguous cast.
+            Reported by Art Yerkes.
+
+07/30/2002: cheetah (William Fulton)
+            [Java] Due to new static typechecking all pointers held in a Java long are part of 
+            the internal workings and this pointer value in the Java long has become abstracted
+            data. The type wrapper constructor and getCPtr() methods are as such protected.
+            If you need to mess around with pointers from Java or for example create a proxy 
+            class or type wrapper class around a null pointer, add a function/constructor 
+            to do so with the %javacode typemap. You can also make getCPtr() public again with
+            the %javagetcptr typemap.
+
+07/30/2002: cheetah (William Fulton)
+            [Java] Fixes for %typemap(ignore). In particular when ignoring the last parameter
+            in a function. Also for all parameters in constructors. These mods have also fixed
+            multi-argument typemaps for proxy classes - SF 581791.
+
+07/30/2002: cheetah (William Fulton)
+            [Java] %newobject (replacement for %new) now implemented for Java. 
+
+07/29/2002: beazley
+            Fixed problem with typemap copies, %apply, and %clear inside
+            C++ namespaces.
+
+07/28/2002: cheetah (William Fulton)
+            [Java] The JNI class now has package access as the class modifier
+            has been changed from "public" to nothing. This has been done
+            as this class is now more for the internal workings of SWIG since the module
+            class has static type checking for all types.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+            Backwards compatibility can be achieved by using the %jniclassclassmodifier 
+            pragma to change it back to "public".
+
+07/28/2002: cheetah (William Fulton)
+            [Java] Proxy/Shadow classes are generated by default. The -proxy and 
+            -shadow command line options are deprecated. If you want to use the 
+            low-level functional interface then use the new -noproxy commandline option.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+07/28/2002: cheetah (William Fulton)
+            [Java] Remaining pragmas shakeup. These were the remaining pragmas and their
+            new names where changed:
+
+            modulebase
+            modulecode
+            moduleclassmodifiers
+            moduleimport => moduleimports
+            moduleinterface => moduleinterfaces
+
+            The moduleimports works slightly differently to how the moduleimport pragma worked. 
+            Now it actually takes code which gets placed before the class definition so the 
+            whole import statement has to be given, for example:
+
+            %pragma(java) moduleimports=%{
+            import java.io.*;
+            import java.math.*;
+            %}
+
+            The moduleinterfaces is slightly different to the old moduleinterface in that if 
+            more than one interface is required they must be comma separated in one use of 
+            the pragma, for example:
+
+            %pragma(java) moduleinterfaces="Serializable, MyInterface"
+
+            These last two pragmas are consistent with the javainterfaces and javaimports 
+            typemap.
+
+            A similar set of pragmas has been introduced, namely:
+
+            jniclassbase
+            jniclasscode
+            jniclassclassmodifiers
+            jniclassimport
+            jniclassinterface
+
+            These work in the same way as their module counterparts. Note that previously
+            the moduleXXX pragmas worked on the old module class which is now called the
+            JNI class (the class with the native functions). The jniclassXXX pragmas now 
+            work on the new module class (the class that has all the global functions and
+            global variable getters and setters when using proxy classes, plus all other
+            remaining functions when using the low-level procedural interface).
+
+            In summary the contents of the pragmas make up a class like this:
+
+            <jniclassimports>
+            <jniclassmodifiers> class modulename extends <jniclassbase> implements <jniclassinterfaces> {
+                <jniclasscode>
+                ... SWIG generated functions ...
+            }
+}
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+07/28/2002: cheetah (William Fulton)
+            [Java] Deprecated modulemethodmodifiers pragma and replaced with 
+            a better %feature based directive called %javamethodmodifiers.
+            A useful example would be for synchronisation in multi-threaded apps:
+
+            %javamethodmodifiers foo(int a) "public synchronized";
+
+            Changes this function from the default ("public") to "public synchronized".
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+07/26/2002: beazley
+            Several directives now allow optional configuration parameters.
+            These include:
+
+                %module(name="value", name="value", ...) modulename
+                %import(name="value", ...) "filename.i"
+                %extend(name="value", ...) classname {
+                   ...
+                }
+
+            These currently have no effect and are reserved for
+            future expansion.
+               
+07/26/2002: beazley
+            Enhancements to smart-pointer handling.  SWIG only provides
+            extra support for a smart-pointer if operator->() returns
+            a proper pointer.  For example:
+
+                 Foo *operator->();
+
+            If operator->() returns an object by value or reference,
+            then SWIG examines the returned object to see if it also
+            implements operator->().  If so, SWIG chases operator->()
+            until it can find one that returns a pointer.  This allows
+            cases like this to work:
+
+                 class Foo {
+                 public:
+                     void blah();
+                 };
+
+                 class Bar {
+                   ...
+                   Foo *operator->();
+                   ...
+                 };
+
+                 class Spam {
+                   ...
+                   Bar operator->();
+                   ...
+                 };
+
+            For example:
+
+                 >>> s = Spam()
+                 >>> s.blah()      # Invokes Foo::blah()
+
+            The s.blah() call actually invokes:
+
+                  ((s.operator->()).operator->())->blah();
+ 
+07/26/2002: beazley
+            Fixed a bug with typedef and references.  For example:
+
+                 typedef Foo & FooRef;
+                 FooRef blah();
+
+            Previous versions of SWIG generated code that wouldn't
+            compile.
+
+07/25/2002: beazley
+            Wrapping of static methods has been improved in proxy classes.  In older
+            versions of SWIG, if you had this:
+
+                  class Foo {
+                  public:
+                     static void bar();
+                  };
+
+            The static method was only available as a function Foo_bar().  For example:
+
+                  >>> Foo_bar()
+
+            Now, the static method can also be invoked through an instance like this:
+
+                  >>> f = Foo()
+                  >>> f.bar()        # Invokes static method
+
+            This works with all versions of Python.  Additionally, for Python-2.2,
+            the static method can be invoked as:
+
+                  >>> Foo.bar()
+
+            The old-style function is still support for backwards compatibility. If
+            you care about making your code across different versions of Python,
+            either use Foo_bar() or access the method through an instance.
+ 
+07/25/2002: beazley
+            Changes to the Python module.  Proxy classes now utilize new Python-2.2
+            features including properties and static methods.  However, these features
+            are supported in a way that provides backwards compatibility with older
+            Python versions.  In other words, proxy classes work with all versions
+            of Python and only use new features when running on Python-2.2.
+
+
+07/25/2002: beazley
+            Modified %extend so that overloaded methods can be added.  For example:
+
+                %extend Foo {
+                     void bar(int x) { };
+                     void bar(char *s) { };
+                     ...
+                }
+
+            This works with both C++ *and* C.
+
+07/24/2002: cheetah (William Fulton)
+            [Java] More new typemaps so that the Java proxy classes and type wrapper classes
+            can be further tailored by users. These are the default code for generating the 
+            finalize() methods (proxy classes only) and the getCPtr() methods for proxy 
+            classes and type wrapper classes:
+
+            %typemap(javafinalize) SWIGTYPE %{
+              protected void finalize() {
+                _delete();
+              }
+            %}
+            
+            %typemap(javagetcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] %{
+              public static long getCPtr($javaclassname obj) {
+                return obj.swigCPtr;
+              }
+            %}
+
+            The javagetcptr typemap will enable users to handle Java null by overriding
+            this typemap - a requested feature.
+
+            The -nofinalize commandline option has been deprecated. The javafinalize
+            typemap is more powerful as it will allow the removal of the finalize methods 
+            for all or any one or more particular proxy class.
+
+07/23/2002: cheetah (William Fulton)
+            [Java] The getCPtrXXX() function has been changed to a static function and
+            is now of the form:
+
+            protected static long getCPtr(XXX obj) {...}
+
+            This is a requested change which will allow Java null pointers to be used as null
+            can be passed in for obj. However, to achieve this the appropriate code must be
+            written using the new javagetcptr typemap directive.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+            Backwards compatibility can be achieved by adding this function back in using the
+            new javacode typemap:
+
+            %typemap(javacode) SWIGTYPE %{
+
+              // SWIG-1.3.12 and SWIG-1.3.13
+              public long getCPtr$javaclassname() {
+                return swigCPtr;
+              }
+              // SWIG-1.3.11 and earlier
+              public long getCPtr() {
+                return swigCPtr;
+              }
+
+            %}
+
+
+07/23/2002: cheetah (William Fulton)
+            [Java] New directive to control constant code generation - %javaconst.
+            The default handling for handling constants is to get the value through
+            a JNI call, eg
+
+            #define YELLOW 5
+            #define BIG 1234LL
+
+            results in:
+
+            public final static int YELLOW = modulename.get_YELLOW();
+            public final static long BIG = modulename.get_BIG();
+
+            Earlier versions of the Java module initialised the value using the C value:
+
+            public final static int YELLOW = 5;
+            public final static long BIG = 1234LL;
+
+            This works in most cases, but the value for BIG won't compile as 1234LL is not
+            valid Java code and this is one of the reasons why the default is now to get the 
+            values through a JNI call. The side effect is that these 'constants' cannot be used 
+            in switch statements. The %javaconst directive allows one to specify the
+            way the constant value is initialised and works like other %feature
+            directives, eg
+
+            %javaconst(0);     // all constants from this point on are initialised using the C value
+            %javaconst(1) BIG; // just BIG initialised using JNI call (must be parsed before BIG is defined)
+
+07/23/2002: beazley
+            *** IMPORTANT CHANGES TO THE PYTHON MODULE ***
+
+            (1) The Python module now enables shadow/proxy classes by default.
+            This means that two files are always created by SWIG.  For
+            instance, if you have this:
+
+                 // file: foo.i
+                 %module foo
+                 ...
+
+            Then swig generates two files "foo_wrap.c" and "foo.py".
+
+            (2) The name of the low-level C extension module has been changed
+            to start with a leading underscore.   This means that you have
+            to compile the module as follows:
+
+                $ cc -c -I/usr/local/include/python2.2 foo_wrap.c
+                $ cc -shared foo_wrap.o $(OBJS) -o _foo.so
+                                                   ^^^^
+                                                   note extra underscore
+
+            This naming scheme is consistent with other Python modules that
+            utilize extension code.  For instance, the socket module consists
+            of "_socket.so" and "socket.py".  In previous versions of SWIG,
+            the shared object file was named "foocmodule.so".
+
+            (3) A new directive can be used to insert Python code into
+            the corresponding .py file.  For example:
+
+                %pythoncode %{
+                def foo():
+                    print "Hello World"
+                %}
+
+             This directive allows you to create modules as a mix of C and Python.
+             Python code is seamlessly added to the module.
+
+            (4) The -shadow command line option is deprecated.  This is turned on
+            by default.
+
+            (5) To disable the generation of the extra python file, use the "-noproxy"
+            command line option.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            This change will likely break the build environment of projects that
+            utilize shadow classes.   To fix this, you probably only need to
+            change the name of the target .so file.  For example, if you have
+            Makefile information like this:
+
+                   TARGET = examplecmodule.so
+
+            Just change it to:
+
+                   TARGET = _example.so
+
+            *** DOCUMENTATION UPDATE ***
+            The file Doc/Manual/Python.html has been updated to describe these changes.
+
+
+07/23/2002: beazley
+            Added -noextern option.   If supplied, SWIG will not generate
+            extra extern declarations.  This is sometimes an issue on 
+            non-unix platforms.
+
+07/23/2002: beazley
+            Added a warning for ignored friend functions.
+
+07/23/2002: beazley
+            Fixed [ 574498 ] -proxy and %include "pointer.i" clash.
+            Reported by David Creasy.
+
+07/23/2002: beazley
+            Fixed [ 576103 ] global destruction warning with shadow.
+            Perl extensions should no longer report the warning
+
+               "Use of uninitialized value during global destruction."
+ 
+            when running with "perl -w".  Reported by
+            Brett Williams.
+
+07/23/2002: beazley
+            In C++ mode, SWIG now always defines namespace std.  By default,
+            it's empty.  However, this will silence errors from programs
+            that include statements such as "using namespace std;".
+            This fixes Bug [ 584017 ] using namespace std generates error.
+            Reported by Joseph Winston.
+
+07/22/2002: beazley
+            Added a new warning message for %apply.  If you use %apply but no typemaps
+            are defined, you will get a warning message.  This should help with
+            problems like this:
+
+                   %apply char *OUTPUT { ... };
+
+            In old versions of SWIG, this silently did nothing.  Now you get an error like this:
+  
+                   file:line. Warning. Can't apply (char *OUTPUT). No typemaps are defined.
+
+07/22/2002: cheetah (William Fulton)
+            [Java] Started Java pragma deprecation. Replacements use %typemap based 
+            directives and enable proxy classes and the new type wrapper classes to be 
+            tailored in various ways. These are the new typemaps:
+            
+            %typemap(javabase)           - base (extends) for Java class
+            %typemap(javaclassmodifiers) - class modifiers for the Java class: default is "public"
+            %typemap(javacode)           - java code is copied verbatim to the Java class
+            %typemap(javaimports)        - import statements for Java class
+            %typemap(javainterfaces)     - interfaces (extends) for Java class
+            
+            And these are the %pragma directives being deprecated:
+            allshadowbase
+            allshadowclassmodifiers
+            allshadowcode
+            allshadowimport
+            allshadowinterface
+            shadowbase
+            shadowclassmodifiers
+            shadowcode
+            shadowimport
+            shadowinterface
+            
+            Note that it is possible to target a particular proxy class:
+            %typemap(javaimports) Foo "import java.util.*";
+            or a particular type wrapper class:
+            %typemap(javaimports) double* "import java.math.*";
+            Note that $javaclassname in these typemaps are substituted with either the proxy 
+            classname when using proxy classes or the SWIGTYPE class name.
+
+07/18/2002: cheetah (William Fulton)
+            [Java] Java module overhaul to implement static type checking of all 
+            types. 
+            
+            1) Changes when using Java Proxy classes
+            ----------------------------------------
+
+            Previously when wrapping global functions: 
+
+            class SomeClass{};
+            void foo(SomeClass* s);
+            SomeClass* bar();
+
+            The native method prototypes used a long for pointers and looked like this:
+
+            public class modulename  {
+                ...
+                public final static native void foo(long jarg1);
+                public final static native long bar();
+            }
+
+            and unlike member functions of a C++ class there was no wrapper around the native calls 
+            to make the use of them more user friendly. They would be used from Java like this:
+
+            SomeClass s = new SomeClass(modulename.bar(), false);
+            modulename.foo(s.getCPtrSomeClass());
+
+            Note that the following will have the same effect, but then it would not have 
+            been possible to call any proxy member functions in SomeClass:
+
+            long s = modulename.bar();
+            modulename.foo(s);
+
+            Now wrapper functions are generated:
+
+            public class modulename  {
+                public static void foo(SomeClass s) {
+                    // calls the native function
+                }
+
+                public static SomeClass bar() {
+                    // calls the native function
+                }
+            }
+
+            Which means these functions can now be used more naturally with proxy classes:
+
+            SomeClass s = modulename.bar();
+            modulename.foo(s);
+
+            2) Changes when not using Java Proxy classes
+            --------------------------------------------
+
+            The so called low-level interface was rather low-level indeed. The 
+            new static type checking implementation makes it less so but it remains a
+            functional interface to the C/C++ world. Proxy classes are the obvious way to use
+            SWIG generated code, but for those who want a functional interface all non-primitive
+            types now have a simple Java class wrapper around the C/C++ type. Pointers and
+            references to primitive types are also wrapped by type wrapper classes. The type
+            wrapper classnames are based on the SWIG descriptors used by the other language 
+            modules. For example:
+
+            C/C++ type      Java type wrapper class name
+            ----------      ----------------------------
+            int*            SWIGTYPE_p_int
+            double**        SWIGTYPE_p_p_double
+            SomeClass*      SWIGTYPE_p_SomeClass
+            SomeClass&      SWIGTYPE_p_SomeClass
+            SomeClass       SWIGTYPE_p_SomeClass
+
+            Note that everything wrapped by SWIG is accessed via a pointer even when wrapping 
+            functions that pass by value or reference. So the previous example would now be 
+            used like this:
+
+            SWIGTYPE_p_SomeClass s = example.bar();
+            example.foo(s);
+
+            Note that typedefs that SWIG knows about are resolved, so that if one has 
+
+            class Foo{};
+            typedef Foo Bar;
+
+            then any use of Bar will require one to use SWIGTYPE_p_Foo;
+
+            Some considerations:
+            Make sure you make a firm decision to use either proxy classes or the functional 
+            interface early on as the classnames are different.
+
+            3) Pointers and non-parsed types
+            --------------------------------
+            Sometimes SWIG cannot generate a proxy class. This occurs when the definition of 
+            a type is not parsed by SWIG, but is then used as a variable or a parameter. 
+            For example,
+
+            void foo(Snazzy sds);
+
+            If SWIG has not parsed Snazzy it handles it simply as a pointer to a Snazzy.
+            The Java module gives it a type wrapper class around the pointer and calls it 
+            SWIGTYPE_p_Snazzy. In other words it handles it in the same manner as types are 
+            handled in the low-level functional interface. This approach is used for all 
+            non-proxy classes, eg all pointer to pointers and pointers to primitive types.
+
+            4) Backwards compatibility
+            -----------------------
+            Backwards compatibility is not an issue if you have been using proxy classes and 
+            no global variables/functions. Otherwise some changes will have to be made. 
+            The native methods still exist but they are now in a JNI class, which is called 
+            modulenameJNI. As this class is really part of the internal workings,
+            it should not be required so the class has become protected. Some pragmas/directives
+            will hopefully be added to help with backwards compatibility.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+07/18/2002: beazley
+            Modified wrapping of uninstantiated templates returned by
+            value.  Just to be safe, they are now wrapped by SwigValueWrapper<>
+            just in case they don't define a default constructor.  This
+            would be used if you had code like this
+
+                 Foo<int> blah();
+                 void     moreblah(Foo<int> x);
+
+            but you didn't instantiate Foo<int> using %template.  
+            We should probably add a warning for this.
+
+07/17/2002: beazley
+            Added an error check to detect shadowed template paramaters.
+            For example:
+
+                  template<class T> class Foo {
+                  public:
+                        int T;
+                  };
+
+            This results in an error, not a warning.  This warning is
+            also needed to fix some rather insidious problems like
+            this:
+
+                 struct T {
+                      int  blah;
+                 };
+
+                 template<class T> class Foo {
+                 public:
+                      typedef T Traits;    // Which T is this????
+                 };
+
+            In this case, the template parameter T shadows the outer
+            structure (which is what you want).
+
+07/16/2002: beazley
+            Improved support for templates with integer arguments.  SWIG is
+            much more aware of situations such as this:
+
+                const int Size = 100;
+
+                %template(Foo100) Foo<100>;
+                void bar(Foo<Size> *x);   // Knows that Foo<Size> is the same as Foo<100>;
+
+07/15/2002: beazley
+            Fixed bug with %feature/%ignore/%rename and namespaces.
+            For example:
+
+                %ignore Foo::Bar
+                namespace Foo {
+                     class Bar {
+                     ...
+                     };
+                }
+
+            Reported by Marcelo Matus.
+
+07/09/2002: beazley
+            Added parsing support for constructors that try to catch
+            exceptions in initializers.   For example:
+
+              class Foo {
+                 Bar b;
+              public:
+                 Foo(int x) try 
+                     : b(x) { ... }
+                 catch(int) {
+                     ...
+                 }
+              }
+
+            This has no effect on the generated wrappers.  However, the try and catch
+            parts of the declaration are ignored.  See Stroustrup, 3rd Ed, section 
+            14.4.6.1 for details.
+                   
+07/06/2002: beazley
+            Fixed bug in template symbol table management.  This fixes
+            two bugs.  First, mixing abstract methods, templates, and 
+            inheritance no longer generates a failed assertion.
+ 
+                template <class T>
+                class A {
+                public:
+                   virtual void foo() = 0;
+                };
+ 
+               template <class T>
+               class B : public A<T>
+               {
+               };
+               %template(A_int) A<int>;
+               %template(B_int) B<int>;
+
+            This fix also fixes a subtle problem with default values and
+            templates.  For example:
+
+               template <class C>
+               struct B {
+                   typedef unsigned int size_type;
+                   static const size_type nindex = static_cast<size_type>(-1);
+                   void foo(size_type index = nindex);
+               };
+
+            Bugs reported by Marcelo Matus.
+
+
+07/05/2002: ljohnson (Lyle Johnson)
+            [Ruby] Changed the definition of the SWIG_ConvertPtr() function
+	    for the SWIG/Ruby runtime support so that it looks like the
+	    Python version. If the last argument (flags) is non-zero,
+	    SWIG_ConvertPtr() will raise an exception for type mismatches
+	    as before. If flags is zero, this function will return -1 for
+	    type mismatches without raising an exception. 
+
+            *** POTENTIAL INCOMPATIBILITY FOR RUBY MODULE ***
+
+07/04/2002: beazley
+            Overloaded functions/methods/constructors now work in many language
+            modules.  The support is completely transparent--just call the
+            function normally and SWIG will dispatch to the correct implementation.
+            There are a variety of issues associated with this.  Please refer
+            to the overloading section of Doc/Manual/SWIGPlus.html for details.
+            *** NEW FEATURE ***
+            
+07/04/2002: beazley
+            Fixed a bug with namespaces, enums, and templates.  For example:
+
+               namespace hello {
+                  enum Hello { Hi, Hola };
+ 
+                  template <Hello H>
+                      struct traits
+                      {
+                          typedef double value_type;
+                      };
+ 
+                 traits<Hi>::value_type say_hi()
+                 {
+                    return traits<Hi>::value_type(1);
+                 }
+               }
+            SWIG wasn't generating wrappers that properly qualified 
+            traits<Hi>.  Reported by Marcelo Matus.         
+
+06/30/2002: beazley
+            Supplied array variable typemaps for Tcl module.   If you have a
+            variable like this:
+
+                int foo[10];
+
+            then a set function like this is generated:
+
+                void foo_set(int *x) {
+                   memmove(foo,x,10*sizeof(int));
+                }
+
+06/30/2002: beazley
+            New %fragment directive.   When writing typemaps, it can be easy to
+            get carried away and write a lot of code.  However, doing so causes
+            tremendous code bloat.   A common way to solve this is to write 
+            helper functions.  For example:
+
+                %{
+                void some_helper_function() {
+                     ...
+                }
+                %}
+
+                %typemap(in) type {
+                   some_helper_function(...);
+                }
+
+            The only problem with this is that the wrapper file gets polluted
+            with helper functions even if they aren't used.    To fix this,
+            a new fragment directive is available.  For example:
+
+               %fragment("type_helper","header") %{
+                  void some_helper_function() {
+                      ...
+                  }
+               %}
+
+               %typemap(in, fragment="type_header") type {
+                   some_helper_function(...);
+               }
+
+            In this case, the code fragment is only emitted if the typemap is
+            actually used.   A similar capability is provided for declaration
+            annotation and the %feature directive.  For example:
+
+               %feature("fragment","type_header")  SomeDeclaration;
+
+            The first argument to %fragment is the fragment name.  The second argument
+            is the file section where the fragment should be emitted.  
+
+            The primary use of this directive is for writers of language modules
+            and advanced users wanting to streamline typemap code.
+
+            *** EXPERIMENTAL NEW FEATURE ***
+
+06/30/2002: beazley
+            Supplied memberin typemaps for all arrays in an attempt to eliminate
+            confusion about their use.
+
+06/29/2002: beazley
+            Experimental support for smart-pointers.  When a class defines
+            operator->() like this
+
+               class Foo {
+                  ...
+                  Bar *operator->();
+                  ...
+               };
+
+            SWIG locates class Bar and tries to wrap its member variables and
+            methods as part of Foo.  For example, if Bar was defined like this:
+
+               class Bar {
+               public:
+                    int x;
+                    int spam();
+               };
+
+            You could do this (in the target language):
+
+              f = Foo()
+              f.x = 4            # Accesses Bar::x
+              f.spam()           # Accesses Bar::spam
+
+            The primary use of this feature is to emulate the behavior of C++
+            smart-pointers---which allow attributes to accessed transparently
+            through operator->.
+
+            This feature is supported automatically in SWIG---no special directives
+            are needed.   To disable this behavior.  Use %ignore to ignore 
+            operator->.
+            *** NEW FEATURE ***
+
+06/26/2002: beazley
+            Deprecated the %except directive.   %exception should be used instead.
+
+06/25/2002: beazley
+            Major cleanup of the modules directory.  Eliminated most
+            header files, consolidated module code into single files.
+
+06/24/2002: beazley
+            Reworked the instantiation of language modules.  All language
+            modules must now define a factory function similar to this:
+
+                extern "C" Language *
+                swig_python(void) {
+                   return new PYTHON();
+                }
+
+            This function is then placed in a table and associated with
+            a command line option in swigmain.cxx.  
+
+            This approach has a number of benefits.  It decouples the 
+            SWIG main program from having to know about the class
+            definitions for each module.  Also, by using a factory
+            function, it will be easier to implement dynamic loading
+            of modules (simply load the file and invoke the factory
+            function).
+
+06/24/2002: beazley
+            Fixed syntax error for reference conversions.  For example:
+
+                     operator Foo &();
+
+06/24/2002: beazley
+            Fixed syntax error for operator new[] and operator delete[].
+
+06/24/2002: beazley
+            Fixed code generation problem for constants and default arguments
+            involving templates.
+
+06/19/2002: ljohnson (Lyle Johnson)
+            [Ruby] Fixed a bug for the '-feature' command line argument;
+            that setting was effectively being ignored and so the feature
+            name was always set equal to the module name.
+
+06/17/2002: beazley
+            Fixed problems with static members and enums in templates.
+
+Version 1.3.13 (June 17, 2002)
+==============================
+06/16/2002: beazley
+            Fixed a bug with __FILE__ expansion in the preprocessor.   On Windows,
+            the backslash (\) is now converted to (\\) in the string literal
+            used for __FILE__.  Reported by Steve Glaser.
+
+06/14/2002: beazley
+            Fixed warning message about 'name private in this context'.  The
+            warning is only generated for public methods.  Reported by
+            Scott Michel.
+ 
+06/14/2002: beazley
+            Fixed some problems related to template instantiation 
+            and namespaces.   When SWIG expands a template, it does
+            so with fully resolved types.  For example, if you have this:
+
+                template<class T> class foo { };
+                typedef double Double;
+                %template(foo_d) foo<Double>;
+
+            then, it is handled as foo<double> in the typesystem.
+            This fixes a number of subtle problems with inheritance
+            and templates.
+
+06/14/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added missing bool typemaps for INPUT, OUTPUT and
+	    INOUT in Lib/ruby/typemaps.i.
+
+05/29/2002: cheetah (William Fulton)
+            [Java] Fix for a couple of broken pragmas.
+
+05/29/2002: cheetah (William Fulton)
+            Fix for unnecessary cast when wrapping global variable where 
+            the type is not parsed by SWIG - Java variables example 
+            failure as reported by Larry Virden.
+
+06/10/2002: beazley
+            Modified %template to allow for empty instantiations.
+
+                  %template() foo<int,int>;
+
+            This registers foo<int,int> with the type system, but
+            doesn't wrap it (same as %ignore).   This may only be a
+            temporary measure.   SWIG might be able to automatically
+            instantiate templates in certain cases.
+
+06/10/2002: beazley
+            Fixed function prototype problems with Tcl 8.4
+
+06/09/2002: beazley
+            Fixed problem with templates and location of base classes.  
+            This one is a little mind-bending, but here is an example
+            that illustrates:
+ 
+             template <class ArgType, class ResType>
+             struct traits
+             {
+                  typedef ArgType arg_type;
+                  typedef ResType res_type;
+             };
+ 
+             template <class ArgType, class ResType>
+             struct Function
+             {
+             };
+ 
+             template <class AF, class AG>
+             struct Class : Function<typename traits<AF, AG>::arg_type,
+                                     typename traits<AF, AG>::res_type>
+             {
+             };
+
+             %template(traits_dd) traits <double, double>;
+             %template(Function_dd) Function <double, double>;
+             %template(Class_dd) Class <double, double>;
+
+
+            In this example, the base class of 'Class' is determined from
+            the Function template, but the types are obtained through typedefs.
+            Because of this, SWIG could not locate the wrapped base class
+            (Function<double,double>).   Should be fixed in 1.3.13 even
+            though I can think of a million other things that might
+            also be broken.
+
+06/07/2002: beazley
+            Fixed a problem with conversion operators.  If you had an
+            operator like this,
+
+                  operator double() const;
+
+            SWIG was ommitting the "const" qualifier.  This affected
+            %rename and other directives.  Reported by Zhong Ren.
+
+06/07/2002: beazley
+            Lessened the strictness of abstract class checking.  If
+            you have code like this:
+
+                class Foo {
+                public:
+                   virtual int method() = 0;
+                };
+
+                class Bar : public Foo {
+                public:
+                    Bar();
+                   ~Bar();
+                };
+
+             SWIG will go ahead and generate constructor/destructors
+             for Bar.  However, it will also generate a warning message 
+             that "Bar" might be abstract (since method() isn't defined).
+             In SWIG-1.3.12, SWIG refused to generate a constructor at all.
+
+06/07/2002: beazley
+            Change to %template directive.  If you specify something like this:
+
+                %template(vi) std::vector<int>;
+
+            It is *exactly* the same as this:
+ 
+                namespace std {
+                    %template(vi) vector<int>;
+                }
+
+            SWIG-1.3.12 tried to instantiate the template outside of the namespace
+            using some trick.  However, this was extremely problematic and full
+            holes.   This version is safer.
+
+06/07/2002: beazley
+            Fixed bug with scope qualification and templates.  For example:
+
+                 A<B::C>::DD
+
+            Before, this was separated as scopes A<B, C>, and DD.  Fixed now.
+
+06/06/2002: beazley
+            Allow the following syntax: 
+               
+               class A { };
+               struct B : A { ... };
+
+            A base class without a specifier is assumed to be public for a struct.
+ 
+06/06/2002: beazley
+            Fixed syntax error with template constructor initializers.
+            Reported by Marcelo Matus.
+
+06/06/2002: beazley
+            Fixed bug with default template arguments. 
+            Reported by Marcelo Matus.
+
+06/05/2002: beazley
+            Fixed subtle problems with %rename directive and template
+            expansion.
+
+            Code like this should now work:
+
+               %rename(blah) foo<double>::method;
+               ...
+               template<class T> class foo {
+               public:
+                   void method();
+               };
+
+               %template(whatever) foo<double>;
+
+06/05/2002: beazley
+            Resolved some tricky issues of multi-pass compilation and 
+            and inheritance.  The following situation now generates
+            an error:
+
+                  class Foo : public Bar {
+                  ...
+                  };
+
+                  class Bar {
+                  ...
+                  };
+
+            The following code generates a warning about incomplete classes.
+
+                  class Bar;
+                  class Foo : public Bar { };
+
+            The following code generates a warning about an undefined class.
+
+                  class Foo : public Bar { };  // Bar undefined
+
+            This fixes a failed assertion bug reported by Jason Stewart.
+
+06/05/2002: ljohnson
+            [Ruby] Added a warning message for the Ruby module about the lack
+            of support for multiple inheritance. Only the first base class
+            listed is used and the others are ignored. (Reported by Craig
+            Files).
+            
+06/03/2002: beazley
+            Fixed a bug with struct declarations and typedef. For example:
+
+                 typedef struct Foo Foo;
+                 struct Foo {
+                    ...
+                 };
+
+            A few other subtle struct related typing problems were
+            also resolved.
+
+Version 1.3.12 (June 2, 2002)
+=============================
+            
+05/30/2002: beazley
+            Fixed problem related to forward template class declarations and
+            namespaces.  Bug reported by Marcelo Matus.
+
+05/30/2002: beazley
+            Added 'make uninstall' target.  Contributed by Joel Reed.
+
+05/29/2002: beazley
+            Fixed rather insidious bug with %rename, %feature and template specialization.
+            For example:
+
+                %exception vector::__getitem__ {
+                     ... some exception ...
+                }
+
+                template<class T> class vector {
+                    ...
+                    T __getitem__(int index);       // Fine
+                    ...
+                };
+
+                template<> class vector<int> {
+                    ...
+                    T __getitem__(int index);       // Oops.
+                    ...
+                };
+
+            Now, the %exception directive (and other features) should correctly apply to
+            both vector and specializations.
+
+05/29/2002: beazley
+            Subtle changes to %template() directive.   Template arguments are now
+            reduced to primitive types in template matching.  For example:
+
+               template<class T> class vector<T *> {
+                ... partial specialization ...
+               }
+
+               typedef int *IntPtr;     // Gross typedef
+
+               // Gets the above partial specialization
+               %template(vectorIntPtr) vector<IntPtr>;
+
+            This change is extremely subtle, but it fixes a number of potential
+            holes in Luigi's STL library modules.    For example:
+
+                typedef int Integer;
+                %template(vectori) vector<int>;
+
+05/29/2002: beazley
+            Fixed rather insidious typemap bug related to const.  const
+            was being discarded through typedefs.
+
+05/29/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added input typemaps for const references to primitive
+            types (in Lib/ruby/ruby.swg).
+
+05/29/2002: cheetah (William Fulton)
+            [Java] The java arrray support functions are enclosed by 
+            a SWIG_NOARRAYS #define. Useful if not using arrays and 
+            it is desirable to minimise the amount of compiled code.
+
+05/29/2002: cheetah (William Fulton)
+            [Java] Enums were not renamed when using %name or %rename
+            fix.
+
+05/28/2002: ljohnson
+            [Ruby] Modified the name of the wrapper functions for the
+	    "new" singleton method and "initialize" instance method for
+	    consistency with the other language modules. The wrapper name
+	    for the function that implements "new" is alloc_classname and
+	    the wrapper name for the function that implements "initialize"
+	    is new_classname.
+
+
+05/27/2002: beazley
+            Changes to runtime.  Pointer conversion/creation functions
+            now almost always have an extra "flags" argument.  For
+            example:
+
+              SWIG_ConvertPtr(obj, void **, swig_type_info *ty, int flags);
+                                                                ^^^^^^^^^^
+            This extra parameter is reserved for future expansion and will
+            be used for more control over pointers in future versions.
+
+05/27/2002: beazley
+            Fix for C++ classes with private assignment operators.  It
+            is now possible to safely return objects like this by value.
+            Caveat:  the class must provide a copy constructor.
+	    
+05/26/2002: beazley
+            -proxy option added to many language modules.  This is the
+            same as -shadow.  We are merely changing terminology.
+            
+05/26/2002: beazley
+            [perl] Fixed some inconsistencies in the -package option.
+            -package merely sets the package name to be used on the
+            wrappers.  It does not change the name of the shared library
+            file or the name of the generated .pm file.  This was
+            broken at some point, but works again now.
+
+05/25/2002: beazley
+            [perl] Fixed [ 475452 ] memory leak in return-by-value.
+            Problem related to static member variables returning newly
+            allocated objects. Reported by Roy Lecates.
+ 
+05/25/2002: beazley
+            [perl] Fixed [ 513134 ] %BLESSEDMEMBERS isn't always right.
+            Reported by Fleur Diana Dragan.
+
+05/25/2002: beazley
+            Fixed [ 540735 ] -importall and the -I option.
+
+05/25/2002: beazley
+            [guile] Fixed [ 532723 ] Default arg for char* can SegV.  
+            Error in guile module.  Reported by Brett Williams.
+
+05/25/2002: beazley
+            Subtle change to typemap application code.  The "freearg"
+            typemap must exactly match up with the "in" or "ignore"
+            typemap.  For example:
+
+                 %typemap(in) (char *data, int len) { ... };
+                 %typemap(freearg) char *data { ... }; 
+
+                 void foo(char *data, int len);
+
+             In this case, the "in" typemap is applied, but the
+             freearg typemap is not.  This is because the freearg
+             typemap doesn't match up with the input argument sequence.
+
+05/25/2002: beazley
+            Fixed [ 548272 ] Default argument code missing braces.
+            Reported by Brett Williams.
+
+05/25/2002: beazley
+            Fixed [ 547730 ] SwigValueWrapper needed for constructors.
+            Reported by William Fulton.
+
+05/25/2002: beazley
+            Undefined identifiers now evaluate to 0 when evaluating
+            preprocessor expressions.  For example:
+
+                  #if !FOO
+                  ...
+                  #endif
+      
+            where FOO is undefined or set to some non-numeric value.
+
+            Fixes [ 540868 ] #if defined whatever - not parsed.
+            Reported by Adam Hupp.
+
+ 
+05/24/2002: beazley
+            SWIG now ignores the C++ 'export' keyword.
+
+05/23/2002: beazley
+            Some refinement of type-name mangling to account for pointers, arrays,
+            references, and other embedded type constructs.
+
+05/23/2002: beazley
+            Initial attempt at supporting template partial specialization.  At
+            the very least, it is parsed and the classes are stored.  Matching
+            of instantiations to specialized version is more limited and based on
+            the SWIG default typemap rules:
+
+                     SWIGTYPE *
+                     SWIGTYPE []
+                     SWIGTYPE &
+
+            Now, why in the world would you want to use this feature?  Other
+            than allowing for slightly modified class APIs, this capability is
+            primarily used to provide advanced wrapping support for STL-like
+            objects.  It can also be mixed with typemaps.  Here is an example:
+
+
+                /* Generic version */
+                template<class T> class vector {
+                    %typemap(in) vector<T> * {
+                        // A container of objects 
+                    }
+                };
+                /* Partial specialization (pointers) */
+                template<class T> class vector<T *> {
+                    %typemap(in) vector<T> * {
+                        // A container of pointers to objects.
+                    }
+                };
+                /* Specialization (integers). */
+                template<> class vector<int> {
+                    %typemap(in) vector<int> * {
+                        // A container of integers.
+                    }
+                };
+
+             *** EXPERIMENTAL FEATURE ***
+            
+05/23/2002: beazley
+            Enhancement to typemaps.   Normally, typemap variables are
+            renamed to avoid conflicts.  For example:
+
+               %typemap(in) int * (int temp) {
+                    $1 = &temp;
+               }
+
+            This results in code that creates and uses variables "temp1","temp2", 
+            "temp3" and so forth depending on how many times the typemap is used.
+            Sometimes you want a single variable instead.  To do that, using
+            the following naming scheme:
+
+                %typemap(in) int *(int _global_temp) {
+                }
+ 
+            Is this case, a single variable _global_temp is emitted in the
+            wrapper functions.  It is shared across all typemaps.  Repeated
+            typemaps do not replicate the variable---they use the first one
+            emitted.
+            *** NEW FEATURE ***
+           
+05/23/2002: beazley
+            Minor enhancement to typemaps.  If you have this code,
+
+               %typemap(in) Foo (int somevar = 3) {
+                     ...
+               }
+
+            the default value for somevar is now emitted into the wrapper code.
+
+05/22/2002: beazley
+            Fixed %extend to be better behaved in namespaces.  If you have code
+            like this:
+
+                namespace foo {
+                     struct bar {
+                        %extend {
+                             void blah();
+                        };
+                     };
+                }
+  
+            SWIG matches the blah() method to a C function named 
+            void foo_bar_blah(foo::bar *self).
+
+            This is consistent with the non-namespace version.
+            Bug reported by Marcelo Matus.
+
+05/22/2002: beazley
+            New library files: cpointer.i, carrays.i, cmalloc.i.  These
+            provide access to C pointers and memory allocation functions.
+            See Doc/Manual/Library.html for details.
+
+05/22/2002: cheetah (William Fulton)
+            [Java] C type char no longer maps to Java type byte, but to Java type char.
+            It is now treated as a character rather than a signed number. This fits in
+            with the other language modules and is a more natural mapping as char* is 
+            mapped as a string of characters. Note that the C signed char type is still
+            mapped to a Java byte.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+05/22/2002: cheetah (William Fulton)
+            [Java] Improved constants wrapping. Constants (#define and %constant) values 
+            are now obtained through a JNI call. Previously the value was compiled as 
+            Java code, but this didn't work for all cases, eg #define 123ULL.
+
+05/22/2002: beazley
+            Fixed bogus error message with %extend directive and C++
+            access specifiers.  Reported by Marcelo Matus.
+
+05/22/2002: beazley
+            Namespaces and enums now work correctly.  For example:
+
+                namespace Foo {
+                    enum Bar { A, B };
+                }
+
+            Bug reported by Marcelo Matus.
+
+05/21/2002: beazley
+            The %types directive can now be used to specify inheritance relationships
+            in the runtime type system.  For example,
+
+                %types(Foo = Bar);
+
+            specifies that Foo isa Bar.    Using this is potentially quite dangerous.
+            However, this is useful in certain cases (and in the SWIG library).
+            
+05/20/2002: beazley
+            %nodefault and %makedefault directives now require a trailing semicolon.
+            For example:
+
+                %nodefault;
+                ...
+                %makedefault;
+
+            In addition both directives can take a class name.  For example:
+
+                %nodefault Foo;
+
+                class Foo {   /* No default constructor/destructor */
+                };
+
+                class Bar {  /* Default constructor/destructor generated */
+                };
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            If you don't use the trailing semicolon, things will mysteriously break.
+
+05/20/2002: beazley
+            More improvements to type system handling.  SWIG now correctly handles
+            template names and parameters in a namespace. For example:
+
+                namespace foo {
+                    template<class T> class bar { };
+                    typedef int Integer;
+
+                    void blah(bar<Integer> *x);
+                };
+
+            In the generated code, all of the typenames are properly qualified.
+
+05/17/2002: cheetah (William Fulton)
+            [Java] deprecated broken -jnic and -jnicpp commandline options. The C or C++ 
+            JNI calling convention is now determined from the -c++ commandline option.
+
+05/16/2002: cheetah (William Fulton)
+            [Java] The JCALL macros which exist so that the same typemaps can be used
+            for generating both the C and C++ JNI calling conventions no longer appear
+            in the generated code. This is because the output is now passed through the 
+            SWIG preprocessor which does the macro expansion for either C or C++ (depending
+            on whether -c++ is passed on the SWIG commandline).
+
+            The generation of the functions used in the array typemaps have been adjusted 
+            to take account of this. The side effect is that any typemaps which contained 
+            JCALL macros within %{ %} brackets will have to be moved within {} brackets 
+            so that the SWIG preprocessor can expand the macros.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+05/13/2002: beazley
+            Class templates may now be used as template parameters.  For example:
+
+              template<class T, template<class> class C> class Foo {
+                  ...
+              };
+              template<class T> class Bar {
+                  ...
+              };
+
+              %template(Fooi) Foo<int, Bar>;
+     
+            SWIG doesn't really do anything special with this---it's just
+            another way of specifying a template parameter.  
+         
+05/13/2002: beazley
+            Minor refinement of template support.  Template parameter names are no longer
+            required for types.  For example:
+
+                template<bool> class Foo {
+                };
+
+            Obviously, names are required for template<class T>;
+
+05/12/2002: beazley
+            New macro expansion in typemaps.  The sequence:
+
+                $descriptor(type)
+
+            Will expand into the SWIG type descriptor structor for
+            the given type.  Type may be any abstract datatype.
+            For example:
+
+                $descriptor(int *)
+                $descriptor(int (*)(int,double))
+                $descriptor(vector<int> *)
+
+            Caveat: It is *NOT* currently legal to use other typemap
+            substitution variables in the macro.  For example 
+            $descriptor($1_type).
+
+            The primary purpose of this modification is to better
+            support typemaps for container objects or to allow typemaps
+            that might be performing type conversions.
+            *** NEW FEATURE ***
+
+05/11/2002: beazley
+            The wrapping of references to primitive types has been
+            changed as follows:
+
+            Arguments of type 'const primitive &' are now passed
+            by value as opposed to pointers.  Return values of
+            type 'const primitive &' are returned as values instead of
+            pointers.
+
+            'primitive' is any one of int, short, long, long long,
+            char, float, double, bool (as well as unsigned variants).
+            
+            This change is being made to better support C++ wrapping--especially
+            code that makes use of templates and the STL.
+            
+05/11/2002: beazley
+            The %template directive can now be used to access templates
+            in a namespace.  For example:
+
+                namespace std {
+                    template<class T> class complex {
+                       T re, im;
+                    public:
+                       complex(T _r = T(), T _i = T()) : re(_r), im(_i) { }
+                       T real() { return re; }
+                       T imag() { return im; }
+                    };
+                }
+
+                %template(complex) std::complex<double>;
+
+            Note: There are some very subtle namespace/symbol table 
+            management issues involved in the implementation of this.
+            It may not work in certain cases.
+
+05/10/2002: beazley
+            Member template constructor support added.  For example:
+
+               template<typename _T1, typename _T2> 
+               struct pair {
+                 _T1 first;
+                 _T2 second;
+                 pair() : first(_T1()), second(_T2()) { }
+                 template<class _U1, class _U2> pair(const pair<_U1,_U2> &x);
+               };
+
+            To instantiate the template, use %template and %extend.
+            For example, this expands the constructor into a default
+            copy constructor:
+
+               %extend pair {
+                  %template(pair) pair<_T1,_T2>;
+               }
+            
+            Highly experimental.  Other uses may be broken.
+
+05/10/2002: beazley
+            The %extend (%addmethods) directive no longer works unless
+            it appears in the public section of a class.   An error
+            message is now generated (as opposed to a segmentation fault).
+
+05/09/2002: beazley
+            New %warnfilter() directive.  This directive attaches a warning
+            filter to specific declarations and has the same semantics as
+            %rename, %ignore, %feature, and so forth.  For example:
+
+               %warnfilter(501) foo;   // Suppress overloaded warning
+               int foo(int);
+               int foo(double); 
+
+            or
+
+               %warnfilter(501) Object::foo(double);
+               class Object {
+               public:
+                  int foo(int);
+                  int foo(double);
+               };
+
+            This feature only suppresses warnings in later stages of code
+            generation.  It does not suppress warnings related to preprocessing
+            or parsing.
+            *** NEW FEATURE ***
+
+05/09/2002: beazley
+            SWIG now supports C99 variadic preprocessor macros.  For example:
+
+               #define debugf(fmt,...) fprintf(stderr,fmt,__VA_ARGS__)
+
+            The argument "..." is used to indicate variable arguments which
+            are all placed into the special argument name __VA_ARGS__ in
+            the macro expansion.  
+
+            SWIG also implements the GNU (##) extension for swallowing the
+            preceding comma when __VA_ARGS__ is empty. For example:
+
+               #define debugf(fmt,...) fprintf(stderr,fmt, ##__VA_ARGS__)
+
+            Here is how this is expanded:
+
+               debugf("%d", 3)  --> fprintf(stderr,"%d",3)
+               debugf("Hello")  --> fprintf(stderr,"Hello" )
+
+            (notice the deleted comma).
+            *** NEW FEATURE ***
+
+05/08/2002: samjam (Sam Liddicott)
+            Many changes to php module.  Shadow classes are now implemented
+            entirely in native C and no need for php-code shadow wrappers
+            Populated template config.m4 and Makefile.in as needed by
+            phpize are generated.
+
+05/08/2002: ljohnson (Lyle Johnson)
+            [Ruby] A copy constructor is now turned into a "clone"
+            instance method (see Dave's change for copy constructors
+            dated 4/7/2002). This seems like the appropriate thing
+            to do for Ruby code.
+
+05/08/2002: ljohnson (Lyle Johnson)
+            [Ruby] Fixed [ 553864 ] Inline destructor code not written.
+
+05/08/2002: beazley
+            %ignore behaves better with constructors, destructors, and the
+            type system in general.   For constructors and destructors,
+            %ignore now suppresses the creation of a default constructor
+            or destructor.  For example:
+
+                 %ignore ~Foo;
+                 class Foo {
+                 public:
+                     Foo();
+                    ~Foo();
+                     ...
+                 };
+
+            In SWIG-1.3.11, ~Foo() simply "disappeared" and the code generator
+            created a wrapper for a default destructor (as if it was never
+            declared in the interface).  In SWIG-1.3.12, %ignore suppresses
+            the creation of a destructor if one is actually defined. 
+
+            Similarly, even though a declaration is ignored, information
+            may still be needed to properly handle types. For example, here
+            is a very subtle error that is fixed by this change:
+
+                %ignore std::string;         // Prevent class wrapping
+                namespace std {
+                   class string {
+                        ...
+                   };
+                   %typemap(in) string * {
+                        ...
+                   }
+                }
+                
+                void foo(std::string *s);   // Broken.
+
+            Before this fix, %ignore would cause the class definition to disappear.
+            This, in turn, would cause the typemap to be misapplied. 
+ 
+05/08/2002: beazley
+            Minor changes to %rename, %ignore, %feature, and related directives
+            for better support of destructors.  Destructors can now be precisely
+            tagged.  For example:
+
+                  %ignore Foo::~Foo;
+                  %feature("action") ~Bar {
+                      ...
+                  }
+             
+            *Developer warning* 
+            Operations such as renaming and feature attachment for classes used to
+            be applied to destructors as well.  For instance, if you did this:
+ 
+                 %rename(Bar) Foo;
+
+            The operation applied to the class itself, the constructor, and
+            the destructor.   This is no longer the case.  Now such operations
+            will only apply to the class and the constructor.  Note: if you
+            were relying on this for class renaming, be aware that renamed
+            classes should really only be handled at the level of the class itself
+            and not the level of individual declarations in the class (although
+            they can be renamed individually if needed).  As far as I know,
+            the Language class is already taking care of this case correctly.
+
+05/07/2002: beazley
+            New set of tests.  The Examples/test-suite/errors directory contains
+            tests that try to exercise all of SWIG's error and warning messages.
+
+05/07/2002: beazley
+            Start of a warning framework.  Warning messages are now assigned numeric values
+            that are shown in warning messages.   These can be suppressed using the
+            -w option.  For example:
+
+                 swig -w302 example.i
+                 swig -w302,305 example.i
+
+            Alternatively, the #pragma preprocessor directive can be used to disable this:
+
+                 #pragma SWIG nowarn=302
+                 #pragma SWIG nowarn=302,305
+
+            Note: Since SWIG is a multi-pass compiler, this pragma should
+            only be used to change global settings of the warning filter.  It should
+            not be used to selectively enable/disable warnings in an interface file.
+            The handling of #pragma occurs in the C++ preprocoessor and affects all 
+            subsequent stages of compilation.
+
+            The -Wall option turns on all warnings and overrides any filters that
+            might have been set.
+
+            Warnings can be issued from an interface using %warn.  For example:
+
+                 %warn "110:%section is deprecated"
+
+            The first part of a warning message is an optional warning number.
+            A complete set of warning numbers is found in Source/Include/swigwarn.h.
+            *** NEW FEATURE ***
+
+05/07/2002: beazley
+            Internal parsing change.   Directives to include files now use brackets [ ... ]
+            instead of { ... }.   
+
+                  %includefile "foo.i" [
+                     ...
+                  ]
+
+            The use of { ... } was a bad choice because they were included implicitly by
+            the preprocessor and made it impossible to properly detect legitimate missing '}' 
+            errors.
+
+04/16/2002-
+05/02/2002: beazley
+            SWIG European Tour: Paris-Amsterdam-Bath.
+
+04/23/2002: beazley
+            The %addmethods directive has been renamed to %extend.
+            For example:
+
+                class Foo {
+                ...
+                };
+
+                %extend Foo {
+                   int blah() { ... };
+                   int bar() { ... };
+                   ...
+                };
+
+            Motivation: the %addmethods directive can be used for many
+            other tasks including adding synthesized attributes, constructors,
+            and typemaps. Because of this, "addmethods" is somewhat misleading.
+            %extend more precisely describes this operation---extension of a
+            class or structure.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            %addmethods still works via a macro definition.   However,
+            a warning message may be generated.   Errors involving %addmethods
+            will actually refer to the %extend directive.  
+            
+04/23/2002: beazley
+            Further refinement of the type system.  Typedef now
+            propagates through functions, pointers to functions,
+            and pointers to member functions.
+            For example:
+
+               typedef int Integer;
+               void foo(int (*x)(int), Integer (*y)(Integer));
+
+            In this case, arguments 'x' and 'y' have exactly
+            the same type (and would obviously accept objects
+            of either type).
+
+            Similarly, consider this:
+
+               class Foo {
+               };
+
+               typedef Foo Bar;
+               void bar(int (Foo::*x)(int), int (Bar::*y)(int));
+
+            In this case, arguments x and y are the same 
+            type (via typedef).
+            
+04/22/2002: beazley
+            SWIG now generates a warning message if any part of
+            an expression involves values from a private part of a class.
+            For example:
+
+                class Foo {
+                private:
+                    static int X;
+                public:
+                     void blah(int a, int b = X);   // Warning
+                };
+
+            In this case, the default argument is ignored.  There
+            are workarounds, but they are rather clumsy.  For instance,
+            you might do this:
+
+                    %feature("action") blah(int,int) {
+                       if ($nargs == 1) {
+                          result = blah(arg1);
+                       } else {
+                          result = blah(arg1,arg2);
+                       }
+                    }
+                    void blah(int a, int b = 0);
+
+
+04/21/2002: beazley
+            Use of the %inline directive inside a namespace is
+            forbidden and now generates an error message.   This is
+            not allowed since the inlined code that is emitted is
+            not placed inside a namespace.  This confuses other
+            stages of parsing.
+                    
+04/21/2002: beazley
+            Some bug fixes to casting operations and expression
+            parsing.   Due to some parsing issues, it is not 
+            currently possible to use casts for all possible
+            datatypes.   However, the common cases work.
+
+04/20/2002: beazley (Amsterdam)
+            Member templates now work.  Simply use the %template
+            directive inside a class or %addmethods to create
+            instantiations (see Doc/Manual/SWIGPlus.html).  Supporting
+            this was easy---earlier changes to templates made it
+            possible using only a two-line modification to the parser
+            and a few minor modifications elsewhere.  Hmmm, come to 
+            think of it, the smoke was rather thick in that Internet "cafe".
+            *** NEW FEATURE ***
+            
+04/19/2002: beazley (TGV)
+            Improved handling of non-type template parameters.  For example:
+
+                 vector<int,100>;
+
+            Simple numbers and strings can be used with the %template
+            directive as well.  For example:
+
+                 %template(vecint100) vector<int,100>;
+
+            Note: Arithmetic expressions are not currently allowed.
+            
+            Default template arguments now work and do not have to
+            be given to %template.
+                        
+04/18/2002: beazley (Paris)
+            Change in internal template handling.  Template
+            parameters are now fully integrated into the type
+            system and are aware of typedefs, etc.  This builds
+            upon the change below.   
+
+            *** DEVELOPER WARNING ***
+            Word of caution to language module writers.  The "name"
+            parameter of certain parse tree nodes (classes, functions, etc.)
+            may be parameterized with types.   This parameterization is
+            done using SWIG type-strings and not the underlying C version.
+            For example,
+
+               int max<int *>(int *,int *)  
+
+            has a name of "max<(p.int)>".  If you use the name directly,
+            you may get syntax errors in the generated code.  To fix this,
+            use SwigType_namestr(name) to convert a parameterized name 
+            to a C name with valid syntax.  The internal version is
+            used to reduce template types to a common representation 
+            and to handle issues of typedef.
+            
+04/16/2002: beazley (somewhere over the Atlantic)
+            Enhancement of typedef resolution.  The type system is now
+            aware of template arguments and typedef.  For example:
+
+                  typedef int Integer;
+                 
+                  foo(vector<int> *x, vector<Integer> *y);
+
+            In this case, vector<int> and vector<Integer> are
+            the same type.   There is some interaction between this
+            mechanism and the implementation of typemaps.  For example,
+            a typemap defined for vector<int> * would apply to either type.
+            However, a typemap for vector<Integer> * would only apply to
+            that type.
+
+            Typedefs and typemaps and matched by left-most expansion.
+            For example:
+
+              vector<Integer,Integer> --> 
+              vector<int, Integer> -->
+              vector<int, int>
+
+
+04/24/2002: cheetah (William Fulton)
+            [Java] Changes to Java shadow classes.
+            Overcomes a bug where the module assumed that a pointer to a derived
+            class could be used in place of a pointer to a base class. Thanks 
+            to Stephen McCaul for analysing the bug and submitting patches.
+
+            A consequence is that the getCPtr() method in each shadow class has
+            disappeared and has been replaced with a getCPtrXXX(), where XXX is the 
+            shadow class name. If you have code that previously used getCPtr(), 
+            and the associated class is wrapping a C struct or a C++ class that
+            is not involved in an inheritance chain, just use the new method. If
+            however, the class is involved in an inheritance chain, you'll have
+            to choose which pointer you really want. Backwards compatibility 
+            has been broken as not using the correct pointer can lead to weird bugs
+            through ill-defined behaviour. If you are sure you want the old methods, 
+            you could add them back into all shadow classes by adding this at the 
+            beginning of your interface file:
+
+            %pragma(java) allshadowcode=%{
+              public long getCPtr(){
+                return swigCPtr;
+              }
+            %}
+
+            Please see entry dated 07/23/2002 to see how to do this after the deprecation
+            of the allshadowcode pragma.
+
+            *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+04/13/2002: beazley
+            Fixed problem with default arguments and references.   Declarations such 
+            as this should now work:
+
+                void foo(const string &x = "Hello");
+
+04/12/2002: beazley
+            Added typemap $* substitutions for typemaps involving arrays.
+            Requested by William Fulton.
+
+04/11/2002: beazley
+            Template specialization is now supported.  For example:
+
+               template<> class vector<int> {
+               ...
+               };
+
+            When the %template directive is used, it will use a specialization
+            if one is defined.   There are still some limitations. Partial
+            specialization is not supported.  A template of type <void *> does
+            not match all pointers.
+            *** NEW FEATURE ***
+
+04/11/2002: beazley
+            Major change to template wrapping internals. Template declarations are
+            no longer processed as macros but now result in real parse-tree
+            nodes.  The %template directive expands these nodes into a
+            specific instantiation.   This change enables a number of
+            new and interesting capabilities:
+
+            Directives such as %rename, %feature, and %addmethods can
+            now be applied to uninstantiated templates.  For example:
+
+              %rename(barsize) vector::bar(char *buf, int len);
+              ...
+              template<typename T> class vector {
+              public:
+                 ...
+                 void bar(char *buf);
+                 void bar(char *buf, int len);   // Renamed
+                 ...
+              };
+
+              %template(intvector) vector<int>;   // Renaming carries through
+
+            
+            By parsing templates into an internal data structure, it will
+            be possible to support specialization (and maybe partial
+            specialization).
+            
+            This is highly experimental and a work in progress.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            In SWIG-1.3.11, template declarations were simply processed
+            as weird macros.  No other information was retained.   This 
+            made it impossible to support more advanced features and 
+            complicated many other parts of the implementation.
+
+04/09/2002: beazley
+            Change to template class wrapping.   There were a variety of
+            "issues" with the old approach related to parsing, the type
+            system, and namespaces.   These changes are meant to rectify
+            some of these problems:
+
+            A specific instantiation of a template can now be specified
+            by including the class inline like this:
+ 
+                  class vector<int> {
+                  public:
+                       vector();
+                      ~vector();
+                       ... whatever ...
+	                  };
+
+            This is template specialization, but partial specialization is
+            not yet implemented.
+            
+            The %template directive has been modified to expand roughly as
+            follows:
+
+                 %template(vecint) vector<int>;
+
+            becomes
+
+                 %rename(vecint> vector<int>;
+                 class vector<int> {
+                 public:
+                     vector();
+                     ...
+                 };
+
+            Note that this simply builds upon the code above (templates
+            included inline).
+
+            This modified approach to wrapping fixes some subtle type
+            issues.  For instance, you can now define typemaps and typedefs
+            like this:
+
+                 %typemap(in) vector<int> * {
+                 ...
+                 }
+                 typedef vector<int> intvector;
+                 ...
+                 void blah(intvector *v);   // Gets the above typemap
+
+            This did not work in SWIG-1.3.11 due to a peculiarity of
+            the template implementation.
+
+            %template(name) no longer installs the template as a class
+            with name "name".   This might break %addmethods as described
+            in the manual.  For example:
+
+                 %template(vecint) vector<int>;
+                 %addmethods vecint {    // Fails. vecint not a class
+                   ...
+                 };
+           
+            To fix this, just use the template name instead:
+
+                 %addmethods vector<int> {
+                     ...
+                 }
+
+            Note: This technique might be a way to implement some bizarre
+            template specialization techniques.   For example:
+
+                 %addmethods vector<int> {
+                     // Only applied if vector<int> instantiated later
+                     %typemap(in) vector<int> * {
+                        ...
+                     }
+                     ...
+                 };
+
+            *** POTENTIAL INCOMPATIBILITY ***
+             
+04/08/2002: beazley
+            Fixed [ 540868 ] #if defined whatever - not parsed.  SWIG should
+            now correctly handle preprocessor directives like this:
+
+                #if defined __cplusplus
+                ...
+                #endif
+             
+            Note: was implemented previously, but there was a minor bug.
+            Reported by Adam Hupp.
+                   
+04/07/2002: beazley
+            %readonly and %readwrite are deprecated due to a change in the 
+            implementation.  Instead of being pragmas, mutability is now
+            controlled as a "feature" using the following two directives:
+
+                 %immutable;
+                 int x;           // read-only variable
+                 int y;           // read-only variable
+                 %mutable;
+                 int z;           // Modifiable
+
+            %immutable and %mutable are much more powerful than their older
+            counterparts.  They can now pinpoint a specific declaration like
+            this:
+
+               %immutable  x;         /* Any x */
+               %immutable  Foo::x;    /* x in class Foo */
+
+            In fact, the matching algorithm is the same as for %rename, 
+            %ignore, and other directives.   This means that the declaration
+      
+               %immutable  Foo::x;
+
+            would not only apply to class Foo but to all derived classes
+            as well.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            %immutable and %mutable must be terminated by a semi-colon.  This
+            differs slightly from the older %readonly and %readwrite directives.
+            Since %immutable and %mutable can be applied to declarations the
+            semicolon is needed to distinguish between a global feature and 
+            one targeted to a single declaration.  Note: this incompatibility is the
+            primary reason for changing the name of the directive.
+
+04/07/2002: beazley
+            New handling of copy constructors.  If a class defines 
+            constructors like this:
+
+                class Foo {
+                public:
+                      Foo();
+                      Foo(const Foo &);       // Copy constructor
+                      ...
+                };
+
+            SWIG now generates a function copy_Foo() for the copy
+            constructor.
+
+            In previous verions, this generated a name-clash and an
+            error message.   To preserve backwards compatibility, SWIG
+            does not change the behavior if %rename is used to resolve
+            the name conflict.   However, if no name resolution is made,
+            this new approach is used.
+
+            Copy constructors may be handled as a special case in the
+            target language.  However, this is up to the language module
+            itself.
+                  
+04/07/2002: beazley
+            The %template directive is now namespace aware.   This allows
+            code like this:
+
+                namespace foo {
+                    template<typename T> max(T a, T b) { return a > b ? a : b; }
+                }
+
+                using namespace foo;
+                %template(maxint) max<int>;            // Ok
+
+                namespace bar {
+                   using foo::max;
+                   %template(maxdouble) max<double>;   // Ok
+                }
+
+            Caveat: the template name supplied to %template must be defined in the
+            same scope in which the %template directive appears.   This code is
+            illegal:
+
+                %template(maxint) foo::max<int>;
+
+04/07/2002: beazley
+            Minor enhancement to preprocessor.   The preprocessor can now perform
+            string comparison.   For example:
+
+               #define A "hello"
+               ...
+               #if A == "hello"
+               ...
+               #endif
+
+            The primary use of this is in SWIG macros.  For example:
+
+              %define FOO(x) 
+              #if #x == "int"
+              /* Special handling for int */
+              ...
+              #endif
+              %enddef
+
+            Normal users can probably safely ignore this feature.  However, it may
+            be used in parts of the SWIG library.
+
+04/07/2002: beazley
+            Further refinement of default constructor/destructor wrapper generation.
+            SWIG is now much more aware of pure virtual methods. For instance:
+
+              class A {             /* Abstract */
+              public:
+                 virtual void method1() = 0;
+                 virtual void method2() = 0;
+              };
+              class B : public A {  /* Abstract */
+              public:
+                 virtual void method1() { };
+              };
+
+              class C : public B {  /* Ok */
+              public:
+                 virtual void method2() { };
+              };
+
+            In this case, SWIG will only generate default constructors for C.
+            Even though B looks fine, it's missing a required method and is abstract.
+
+04/04/2002: beazley
+            Subtle change to structure data member access.  If you
+            have a structure like this:
+
+                struct Foo {
+                    Bar   b;
+                };
+
+            The accessor functions for b are generated as follows:
+
+            (1) If b is *not* defined as a structure or class:
+
+                Bar Foo_b_get(Foo *self) {
+                    return self->b;
+                }
+                void Foo_b_set(Foo *self, Bar value) {
+                    self->b = value;
+                }
+
+            (2) If b *is* defined as a structure or class:
+
+                Bar *Foo_b_get(Foo *self) {
+                    return &self->b;
+                }
+                void Foo_b_set(Foo *self, Bar *value) {
+                    self->b = *value;
+                }
+            See the "Structure data members" section of Doc/Manual/SWIG.html
+            for further details.
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            This may break interfaces that relied on a lot of a undeclared
+            structure and class names.    To get the old behavior, simply
+            use a forward declaration such as "struct Bar;"
+            
+04/04/2002: beazley
+            C++ namespace support added.  SWIG supports all aspects of
+            namespaces including namespace, using, and namespace alias
+            declarations.    The default behavior of SWIG is to flatten
+            namespaces in the target language.  However, namespaces are
+            fully supported at the C++ level and in the type system.
+            See Doc/Manual/SWIGPlus.html for details on the implementation.
+     
+04/02/2002: cheetah (William Fulton)
+            [Java] Sun has modified javac in jdk1.4 to no longer compile
+            an import of an unnamed namespace. To fix this SWIG no longer 
+            generates the import for packageless classes.
+            http://developer.java.sun.com/developer/bugParade/bugs/4361575.html
+            As reported SF #538415.
+
+03/27/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added support for pointer-to-member, similar to that
+            for the Python module. Remarkably similar. Also added a new
+            example for this (Examples/ruby/mpointer), which is remarkably
+            similar to the Python example of the same name.
+
+03/26/2002: ljohnson (Lyle Johnson)
+            [Ruby] Made a few minor edits to the "Advanced Topics"
+            chapter of the SWIG manual and added a new major section
+            about how to create multi-module Ruby packages with SWIG.
+
+03/26/2002: ljohnson (Lyle Johnson)
+            [Ruby] Removed all of the old Ruby pragmas. If any of this
+            functionality is truly missed we can resurrect it, preferably
+            with some kind of feature-based directive.
+            
+03/25/2002: ljohnson (Lyle Johnson)
+            [Ruby] Fixed SWIG exception library support for Ruby, which
+            has apparently been broken for some time. Luckily, no one seems
+            to have noticed.
+
+03/23/2002: beazley
+            C++-namespace support in SWIG directives.
+
+            %addmethods: 
+
+            The %addmethods directive now accepts a fully qualified classname
+            and can be used inside C++ namespace declarations.  For example:
+
+                 // Attaches to the class Foo::Bar below
+                 %addmethods Foo::Bar {
+                     int somemethod() { ... }
+                 };
+
+                 namespace Foo {
+                    class Bar {
+                    public:
+                        ...
+                    };
+                 
+                    // Attaches to the class Bar above
+                    %addmethods Bar {
+                      int othermethod() { ... };
+                    }
+                 }
+
+            %feature, %rename, %ignore, %exception, and related directives:
+
+            Namespaces are fully integrated into the the renaming and declaration
+            matcher.  For example:
+
+                 %rename(display) Foo::print;          // Rename in namespace Foo
+                 %ignore Foo::Bar::blah;               // Ignore a declaration
+
+            %rename directives can be placed inside namespace blocks as well. For
+            example:
+
+                namespace Foo {
+                   %rename(display) print;         // Applies to print below
+
+                   void print();
+                };
+
+            Most other SWIG directives should work properly inside namespaces.
+            No other changes are needed.
+      
+03/22/2002: beazley
+            Some changes to internal symbol table handling.   SWIG no longer
+            manages structures and unions in a separate namespace than normal
+            declarations like ANSI C.  This means you can't have a structure
+            with the same name as a function.  For example:
+
+                 struct Foo {
+                 ...
+                 }
+ 
+                 int Foo() { ... }
+
+            This approach is more like C++.   It's not clear that SWIG ever
+            really supported the ANSI C anyways---using the same name would
+            almost certainly generate a name-clash in the target language.
+
+03/22/2002: ljohnson (Lyle Johnson)
+            [Ruby] Fixed [ 517302 ] for handling of renamed overloaded
+            constructors. Now, renamed overloaded constructors are converted
+            into class singleton methods (basically acting as "factory"
+            methods).
+
+03/21/2002: beazley
+            Fixed [ 532957 ] %ignore parse error and casting operator.
+            Reported by William Fulton.
+
+03/18/2002: beazley (** ADVANCED USERS ONLY **)
+            Added support for dynamic casting in return values.  A somewhat
+            common problem in certain C++ programs is functions that hide
+            the identity of underlying objects when they are returned 
+            from methods and functions.  For example, a program might include
+            some generic method like this:
+
+                      Node *getNode();
+
+            However, Node * may just be base class to a whole hierarchy
+            of different objects.   Instead of returning this generic Node *,
+            it might be nice to automatically downcast the object into the
+            appropriate type using some kind dynamic cast.
+
+            Assuming you understand the peril involved, a downcast can now
+            be performed using the following function in the run-time type
+            checker:
+
+              swig_type_info *SWIG_TypeDynamicCast(swig_type_info *, void **ptr);
+
+            This function checks to see if the type can be converted to another
+            type.  If so, a different type descriptor (for the converted type)
+            is returned.   This type descriptor would then be used to create
+            a pointer in the target language.
+
+            To use this, you would write a typemap similar to this:
+
+              %typemap(out) Node * {
+                swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor, (void **) &$1);
+                $result = SWIG_NewPointerObj($1, ty);
+              }
+
+            Alternatively,
+
+              %typemap(out) Node * = SWIGTYPE *DYNAMIC;
+
+            To make the typemap have any effect, you have to write a supporting 
+            function that knows how to perform downcasting. For example:
+
+              %{
+              static swig_type_info *
+              Node_dynamic_cast(void **ptr) {
+                 Node **nptr = (Node **) ptr;
+                 Element *e = dynamic_cast<Element *>(*nptr);
+                 if (e) {
+                    *ptr = (void *) e;
+                    return SWIGTYPE_p_Element;
+                 }
+                 Data *d = dynamic_cast<Data *>(*nptr);
+                 if (d) {
+                    *ptr = (void *) d;
+                    return SWIGTYPE_p_Data;
+                 }
+                 return 0;
+              }
+              %}
+
+            There is no restriction on how types are determined. dynamic_cast<>
+            uses C++ RTTI.  However, if you had some other mechanism for determining
+            the type, you could use that here.  Note: it is important to save
+            the new pointer value back into the argument as shown.  When downcasting,
+            the value of the pointer could change. 
+
+            Finally, to make the casting function available, you have to register
+            it with the run-time type checker. Put this macro in your interface file.
+
+               DYNAMIC_CAST(SWIGTYPE_p_Node, Node_dynamic_cast);
+
+            Note: this feature does not introduce a performance penalty on 
+            normal SWIG operation.  The feature is only enabled by writing
+            a new typemap that explicitly calls SWIG_TypeDynamicCast() to
+            make a conversion. 
+  
+            Examples/test-suite/dynamic_cast.i contains a simple example.
+            This feature is not supported in the Java module due to differences
+            in the type-checking implementation.
+
+            *** EXPERIMENTAL FEATURE ***
+
+03/17/2002: beazley
+            Small change to type-name handling of unnamed structures and
+            typedef.  If a structure of this form appears:
+
+                   typedef struct {
+                        ...
+                   } Foo;
+
+            Then 'Foo' is used as the proper typename for the structure.
+            Furthermore, Foo can now be used as a name in C++ inheritance.
+            SWIG was already kind of doing this, but this modification refines
+            the implementation to more closely follow the C++ ARM, section
+            7.1.3, p. 106.  This fixes a couple of obscure corner cases.
+
+03/16/2002: beazley
+            Modified C++ inheritance with a few enhancements.  First, type information
+            needed for casting and type-equivalence is generated even when base-classes
+            aren't defined in the interface.  For example:
+
+                class Foo : public Bar  {    /* Bar unspecified */
+                public:
+                  ...
+                };
+
+               void blah(Bar *b);
+
+            In this case, the blah() function still accepts Foo * even though nothing
+            is really known about Bar.   Previous SWIG versions would just generate
+            a type error.
+
+            Inheritance has also been modified to work through typedef.  For example:
+
+               class Bar {
+               };
+
+               typedef Bar OtherBar;
+               class Foo: public OtherBar {
+               }
+
+            In this case, the base class of OtherBar is correctly resolved back to
+            Bar.   The use of the name OtherBar is lost in this resolution (the wrappers
+            will simply use Bar instead of the typedef name OtherBar).
+           
+03/13/2002: beazley
+            %typemap, %apply, and related directives can now appear inside
+            class definitions.   
+
+03/13/2002: beazley
+            Fixed a variety of problems related to compiling SWIG on 64-bit
+            platforms.
+
+03/12/2002: beazley
+            Fixed problem with "ignore" and "in" typemaps.  Local variables
+            associated with "in" were being added to the wrapper function even
+            though they were never used.   Mostly harmless, but it would lead
+            to a variety of compilation warnings.
+  
+03/12/2002: beazley
+            Some changes to the internal type system and handling of nested C++
+            types.   In previous versions of SWIG, if you had the following:
+
+                 class Foo {
+                 public:
+                      typedef int Blah;
+                 };
+                 class Bar : public Foo {
+                 public:
+                       void somemethod(Blah x);
+                 };
+
+            The argument type in somemethod() would implicitly be set to Bar::Blah.
+            Although this is technically allowed, it breaks typemaps.  For example:
+
+                 %typemap(in) Foo::Blah { ... }
+
+            doesn't match like you expect.   This has been changed in SWIG-1.3.12.
+            Now, types are expanded using the class in which they were defined.
+            So, the argument type in somemethod() will be Foo::Blah---since the
+            type Blah was defined in Foo.
+ 
+03/10/2002: beazley
+            Fixed some subtle type scoping problems with typedef and C++ classes.
+            For example:
+ 
+                typedef int Blah;
+                class Bar {
+                public:
+                    typedef double Blah;
+                    void foo(Blah x, ::Blah y);
+                ...
+                }
+
+03/10/2002: beazley
+            Highly experimental change to handle variable length arguments.
+            First, there is no portable or reliable way to wrap
+            a varargs function in full generality.  However, you *can* change
+            the function signature using %varargs.
+
+               %varargs(char *) fprintf;
+               ...
+               void fprintf(FILE *f, char *fmt, ...);
+
+            In this case, the variable length parameter "..." is
+            simply replaced by the parameters given in %varargs. This
+            results in a function like this:
+
+               void fprintf(FILE *f, char *fmt, char *s);
+
+            More than one argument can be used and default values
+            can be defined.  For example, this code specifies a
+            maximum of four arguments.
+
+               %varargs(char *x1 = 0, char *x2 = 0, char *x3 = 0, char *x4 = 0) fprintf;
+ 
+            *** EXPERIMENTAL NEW FEATURE ***
+ 
+03/10/2002: beazley
+            Change to handling of variable length arguments.  varargs
+            is now handled as a proper parameter and is passed to the
+            code generator.  However, it still can't be handled correctly
+            (and will generate a typemap warning).   This change has been
+            made to better incorporate variable length arguments with other
+            directives such as %ignore, %rename, %feature, and so forth.
+
+03/10/2002: beazley
+            Fixed [ 522555 ] Syntax error parsing "define" construct. SWIG
+            is a little more restrictive in determining #define statements
+            that will be wrapped as constants.  Also added a better parser
+            error rule for handling bad constants.
+
+03/08/2002: cheetah (William Fulton)
+            [Java] Bug fix: Classes renamed with %rename that are derived from 
+            another class generate more appropriate shadow class code.
+
+03/08/2002: cheetah (William Fulton)
+            [Java] Fixed SF [ #523632 ] and [ #513335 ] both reported by Israel 
+            Tanner. Support for types that are used which are in a typedef. The
+            appropriate shadow class name is generated. Also generated correct
+            shadow classname when a templated class is used within another 
+            templated class. See the cpp_typedef.i testcase.
+
+03/08/2002: cheetah (William Fulton)
+            [Java] Bug fix: No type was generated in shadow classes for types 
+            that weren't wrapped by SWIG.  The type is treated as a raw 
+            pointer, ie no shadow class.
+
+02/22/2002: beazley
+            Refined the matching algorithm used by %rename, %ignore, and
+            %feature.   If a type signature is supplied, it must exactly
+            match that used in the declaration---including any use of
+            const.  For example:
+
+                %rename(foo1)   foo(int);
+                %rename(bar1)   bar(int) const;
+
+                class Blah {
+                   public:
+                      void foo(int);       // Matched --> foo1
+                      void foo(int) const; // Not matched 
+                      void bar(int);       // Not matched
+                      void bar(int) const; // Matched --> bar1
+                }
+
+            In previous versions, a non-const specification would match
+            both the non-const and const declarations.  However, the whole
+            point of %rename and related directives is that they be able
+            to precisely pinpoint exact declarations in an interface.  This
+            fixes the problem.
+
+02/21/2002: beazley
+            Reworked the handling of default constructor and destructors.
+            SWIG now makes a preliminary pass over the parse tree to discover
+            which classes support default allocation.   This fixes a number
+            of very subtle issues in code generation and call/return by value.
+
+02/18/2002: cheetah (William Fulton)
+            Improved support on Cygwin: Perl, Python, Tcl, Ruby and Java should
+            work out of the box, barring the runtime library. Removed dllwrap 
+            and replaced with newly working gcc -shared instead for Cygwin. 
+            All this will require the new improved binutils 20010802 and later,
+            but the latest Cygwin is usually the best recommendation.
+
+02/15/2002: beazley
+            Fixed some problems related to wrapping of global variables
+            and Perl shadow classes. Reported by Chia-liang Kao.
+
+02/15/2002: ljohnson (Lyle Johnson)
+            [Ruby] Made a fix to the code generation for C++ class
+            constructors so that we get both a "new" singleton method
+            and an "initialize" instance method for each class. This
+            change enables developers to derive new Ruby classes from
+            SWIG-wrapped C++ classes and then override their initialize
+            methods to provide subclass-specific instance initialization.
+
+02/15/2002: ljohnson (Lyle Johnson)
+            [Ruby] Massive documentation update for the Ruby module,
+            contributed by Craig Files.
+
+02/14/2002: ljohnson (Lyle Johnson)
+            [Ruby] Bug fix: An error in the SWIG runtime support for Ruby
+            was causing several of the examples to fail. Reported by
+            William Fulton.
+
+02/14/2002: ljohnson (Lyle Johnson)
+            [Ruby] Bug fix: Enumerations defined within a class (such
+            as those seen in the Examples/ruby/enum example) were not
+            being exported with the correct names. Reported by William
+            Fulton.
+
+02/13/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added a warning message when we run across overloaded
+            class constructors for C++ code, that this is currently not
+            supported (even if the overloads have been %renamed). For an
+            example of where this doesn't work, see Examples/ruby/operator.
+
+02/13/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added an "ignored" warning message when the parser runs
+            across an operator!=() declaration for C++ code.
+
+02/11/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added the "import", "import_template", "operator" and
+            "template" examples.
+
+02/11/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added multi-module support.
+
+02/09/2002: ljohnson (Lyle Johnson)
+            [Ruby] Added the missing "#define SWIG_NOINCLUDE" at the top of
+            the wrapper code when the '-c' option is used.
+
+02/09/2002: ljohnson (Lyle Johnson)
+            Corrected a minor off-by-one error for the size of the
+            swig_types[] array that's generated in the wrapper code.
+
+02/08/2002: beazley
+            Fixed SF [ #515058 ] Wrong code for C++ templates.
+            Reported by Israel Taller.
+
+Version 1.3.11 (January 31, 2002)
+=================================
+
+01/30/2002: beazley
+            Fix to pass/return by value for C++ objects that define
+            no default constructor.  Changes to the typemap system
+            made it impossible to wrap C++ objects with no default
+            constructor.   This has been fixed, but the solution 
+            involves some clever template magic contributed by 
+            William Fulton.  Please see the comments in the file
+            Lib/swig.swg for further details.  This solution is
+            experimental and may be refined in a future release.
+
+01/30/2002: beazley
+            Global variables and member data of type "const char *"
+            can be set, but the old value is silently discarded without
+            any garbage collection.   This may generate a memory leak.
+            This change is needed to more safely handle variables
+            like this:
+
+                   const char *foo = "Hello World\n";
+
+            In this case, it's not safe to free the old value.  However,
+            SWIG can dynamically allocate a new value and make foo point
+            to it.   To fix this memory leak, you can probably do this:
+
+               %clear const char *foo;
+               %apply char * {const char *foo};
+
+            *** POTENTIAL INCOMPATIBILITY ***
+            
+01/30/2002: beazley
+            Two minor typemap enhancements have been added.  First,
+            typemaps can issue a warning message by including a special
+            warning attribute. For example:
+
+             %typemap(in,warning="I'm going to do something dangerous") ...
+
+            The warning message will show up whenever the typemap is
+            applied.
+
+            Second, a typemap can force a no-match by defining
+
+             %typemap(in) sometype "pass";
+
+            If this is used, the typemap system will *not* record a
+            typemap match for "sometype".   This can be used to block
+            selected typemaps.  For example, if you wanted to disable
+            a typemap feature for some type, you could do this.
+
+               // Do not allow global variables of type 'const char *' to be set.
+               %typemap(varin) const char * "pass";
+
+            It might also be possible to use this to do subtle and
+            strange things with typemaps.  For example, if you wanted to
+            make 'blah *' an output value and 'const blah *' an input
+            parameter, you might do this:
+
+                %typemap(ignore) blah *(blah temp) {
+                    $1 = &temp;
+                }
+                %typemap(argout) blah * {
+                    ... return a value ...
+                }
+                /* Block unqualified typemaps defined above */
+                %typemap(ignore) const blah * "pass";
+                %typemap(argout) const blah * "pass";
+                %typemap(in)     const blah * {
+                    ... get input value ...
+                }
+
+             (This potential applications of typemaps suggested by Greg Stein).
+            *** NEW FEATURE ***
+
+01/29/2002: cheetah (william fulton)
+           [Java] Bug fix: No enumerations were wrapped when the -shadow 
+           commandline option was not specified. Reported by Israel Taller.
+
+01/28/2002: cheetah (william fulton)
+           [Java] Global arrays are successfully wrapped. In fact they started
+           mostly working in SWIG-1.3.10.
+
+01/28/2002:richardp
+	   Added first attempt at C++ and -shadow support for PHP4 module,
+	   please test and mail me if any problems/ideas on improving it.
+
+	   There is a known problem with uninitialized member variables,
+	   please see Examples/php4/sync/README for details.
+
+	   Also more PHP documentation added to Doc/Manual/Php.html
+
+01/27/2002:beazley
+           The ANSI C size_t type is now recognized as an integer by default.
+
+01/26/2002:beazley
+           long long and unsigned long long support added to many language modules.
+           This is not a portable feature and will require compiler support
+           for the long long type.  In target languages that do not support
+           long long (e.g., Tcl and Perl), numbers are converted to a string
+           of digits.  This prevents their use in arithmetic calculations, but
+           still allows values to be set from a string.  
+
+           long long support requires the use of the strtoll() and strtoull()
+           functions as well as the 'lld' and 'llu' format specifiers
+           of sprintf().
+
+01/26/2002:beazley
+           Fixed [ #501827 ] Delete method is not called.   The Tcl
+           module wasn't correctly calling destructors when they
+           were defined using %addmethods.  This has been fixed.
+           Reported by Reinhard Fobbe.
+
+01/26/2002: beazley
+           Better support for long long and unsigned long long.  Typemaps
+           have been included in a number of modules for handling these types.
+           In addition, the parser has been modified to accept long long
+           literals such as 1234LL and 1234ULL.
+
+01/27/2002: cheetah (william fulton)
+           [Java] A C char[] is mapped to a Java String which is the default 
+           SWIG handling of char[] and char*. It used to be mapped to byte[]. 
+           Note that a C signed char[] array is mapped to byte[].
+
+           *** POTENTIAL INCOMPATIBILITY ***
+
+01/25/2002: beazley
+           Fixed a problem with return-by-value, C++, and
+           objects that define no default constructor.
+           Reported by Joel Reed.
+
+01/25/2002: cheetah (william fulton)
+           [Java] Overhaul of the Java module. The C code generation is now 
+           done from typemaps.
+
+01/24/2002: cheetah (william fulton)
+           [Java] Support for arrays of enum pointers
+
+01/20/2002: cheetah (william fulton)
+           [Java] Error checking for null Java objects being passed to native 
+           functions.  Exception thrown now whereas before the JVM crashed.
+
+01/18/2002: cheetah (william fulton)
+           [Java] Corrected behaviour for functions that take arrays. For 
+           example, when this c function: 
+
+           void arrayfn(int array[]);
+           
+           is wrapped the corresponding native function
+
+           public final static native void arrayfn(int[] array);
+
+           is produced. Previously if the C function made any changes to the 
+           array elements, these were not reflected back into the Java array. 
+           This has now been corrected so that the changes are propogated back
+           to Java and the calling function will see these changes. This is 
+           how pure Java functions work, ie arrays are passed by reference.
+
+01/15/2002:mkoeppe
+           [Guile] New file cplusplus.i with C++ typemaps contributed
+           by Marcio Luis Teixeira <marciot@holly.colostate.edu>.
+
+01/11/2002: cheetah (william fulton)
+           [Java] Changed mapping of C long to Java type. Was mapped to Java
+           long, now mapped to Java int. If you want the previous mapping to 
+           Java long use this approach in your interface file:
+           
+             %clear long;
+             %typemap(jni) long             "jlong"
+             %typemap(jtype) long           "long"
+             %typemap(jstype) long          "long"
+
+             %clear long[ANY];
+             %typemap(jni) long[ANY]        "jlongArray"
+             %typemap(jtype) long[ANY]      "long[]"
+             %typemap(jstype) long[ANY]     "long[]"
+             %typemap(in) long[ANY]         {write me for array support}
+             %typemap(out) long[ANY]        {write me for array support}
+             %typemap(argout) long[ANY]     {write me for array support}
+             %typemap(freearg) long[ANY]    {write me for array support}
+
+           *** POTENTIAL INCOMPATIBILITY ***
+
+           This new mapping is more appropriate when interfacing to 32 bit 
+           applications which are used in the current 32-bit JVMs. For future 
+           64-bit JVMs you may have to change these mappings - eg on Unix LP64 
+           systems, but not on Microsoft 64bit Windows which will be using a 
+           P64 IL32 model. This may be automated in a future version of SWIG.
+
+01/10/2002:beazley
+           Fixed [ 501677 ] %init block in wrong place. Reported
+           by Luigi Ballabio.
+
+01/09/2002: cheetah (william fulton)
+           [Java] Default support for the long long type. signed long long is 
+           mapped to a Java long. unsigned long long is mapped to BigInteger.
+
+01/09/2002:beazley
+           Experimental change to parser to better support mixing of
+           int, long, short, unsigned, float, and double.   The parser
+           should now support types like this:
+    
+                short unsigned int
+                int   unsigned short
+                unsigned short int
+                unsigned int short
+
+            This change also enables a type of 'long double' (previously
+            unsupported) to be used.
+            *** NEW FEATURE ***
+
+01/05/2002: cheetah (william fulton)
+           [Java] Casting fix for when function return type is a pointer as 
+           reported by Gary Pennington 2002-01-05. The upper 32bits of the 
+           64 bit jlong will have contained junk for 32bit pointers.
+
+01/05/2002: cheetah (william fulton)
+           [Java] Better pointer handling in Java is possible as the 
+           INPUT, OUTPUT and INOUT typemaps have been added into typemaps.i.
+
+01/05/2002: cheetah (william fulton)
+           [Java] $null can be used in input typemaps to return early from JNI 
+           functions that have either void or a non-void return type. Example:
+
+             %typemap(check) int * %{ 
+               if (error) {
+                 SWIG_exception(SWIG_IndexError, "Array element error");
+                 return $null;
+               }
+             %}
+
+           If the typemap gets put into a function with void as return, $null 
+           will expand to nothing:
+
+             void jni_fn(...) {
+                 if (error) {
+                   SWIG_exception(SWIG_IndexError, "Array element error");
+                   return ;
+                 }
+               ...
+             }
+
+           otherwise $null expands to zero, where javareturntype is either a 
+           pointer or a primitive type:
+
+             javareturntype jni_fn(...) {
+                 if (error) {
+                   SWIG_exception(SWIG_IndexError, "Array element error");
+                   return 0;
+                 }
+               ...
+             }
+
+01/02/2002: cheetah (william fulton)
+           [Java] The Java module incorrectly used argout typemaps for 
+           strings. This is now corrected and the code now resides
+           in the freearg typemap. The argout array typemaps have been split into 
+           argout and freearg typemaps. This correction may require some user 
+           written typemaps to be modified. 
+           *** POTENTIAL INCOMPATIBILITY ***
+
+12/28/2001: cheetah (william fulton)
+           [Java] Multi typemaps now working for Java see multimap example.
+           [Java] Fix for recently introduced bug - freearg typemap code was appearing
+           before the function call.
+
+12/28/2001: cheetah (william fulton)
+           [Java] JCALL macro for JNI calls that work in both C and C++ typemaps
+           have been replaced with JCALL0, JCALL1, JCALL2, JCALL3 and JCALL4 
+           macros.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+12/22/2001:beazley
+           Resolved some inconsistent behavior with %rename and class renaming.
+           If you specify the following:
+ 
+               %rename(Foo)  Bar;
+
+               class Bar {
+               public:
+                    Bar();
+                    ~Bar();
+               }
+
+           Then the %rename directive applies to the class itself, the constructor,
+           and the destructor (all will be renamed to Foo).
+
+           If a class defines more than one constructor, the overloaded variants
+           can still be renamed by specifying parameters to %rename.  For example:
+
+               %rename(Bar_copy) Bar(Bar &);
+               class Bar {
+               public:
+                     Bar();
+                     Bar(Bar &);
+                    ~Bar();
+               };
+
+           There are still some odd corner cases.  If you specify
+
+               %rename(Foo) ::Bar;
+
+           then only the name of the class is changed and the constructor/destructor
+           names are left unmodified.  If you specify 
+
+               %rename(Foo) *::Bar;
+
+           then the names of the constructor/destructor functions are modified but
+           the name of the class is not.
+
+12/21/2001: cheetah (william fulton)
+           [Java] jni, jtype and jstype typemaps no longer hardcoded but real 
+           typemaps. New variable substitution, $javaclassname, can be used in
+           the jstype typemaps. It is replaced with the Java shadow class name
+           where applicable.
+           [Java] Fix for recently introduced bug to do with inheritance when 
+           using %import.
+           [Java] A few more bug fixes, todo with %rename and using the kind
+           with the type, eg 
+           void fn(union uni myuni, struct str mystr, class cl mycl);
+
+12/20/2001:beazley
+           Fixed [ #494524 ] Preprocessor bug - apostrophe and #subst.
+
+12/20/2001:beazley
+           Added SWIG_VERSION preprocessor symbol.   This is a hexadecimal
+           integer such as 0x010311 (corresponding to SWIG-1.3.11).  This can
+           be used in the interface as follows:
+
+               #if SWIG_VERSION >= 0x010311
+               /* Use some fancy new feature */
+               #endif
+
+           Note: The version symbol is not defined in the generated SWIG
+           wrapper file.
+
+           *** NEW FEATURE ***
+
+12/20/2001:mkoeppe
+	   [MzScheme]: Renamed mzswig_make_boolean to
+	   swig_make_boolean, as the latter is used in the typemaps.
+	   Reported by Luigi Ballabio.
+
+12/17/2001:mkoeppe
+	   [Guile]: Rewrote list-vector.i using multi-dispatch
+	   typemaps.  Updated pointer-in-out.i.  Make the
+	   deprecated typemap-substitution of "$source" in "argout"
+	   work as before.
+
+12/16/2001:mkoeppe
+	   [Guile]: Fixed macros %values_as_list, %values_as_vector,
+	   %multiple_values to use the proper %pragma syntax.  New
+	   Guile example/test "multivalue"; new Guile run-test for
+	   test-suite item "list-vector" (currently broken).
+
+12/14/2001:mkoeppe
+	   [Guile]: Fixed typemap-substition bug for "varin".  Relaxed
+	   valid-identifier check to allow all R5RS identifiers.
+
+
+Version 1.3.10 (December 10, 2001)
+==================================
+
+12/08/2001:beazley
+           Modified %typemap so that %{ ... %} can also be used as a
+           code block (mostly for completeness).  For example:
+ 
+              %typemap(in) blah %{
+                 ...
+              %}
+
+           This form does not introduce a new block scope.  Also, the
+           code enclosed in %{ ... %} is not processed by the preprocessor.
+
+12/08/2001:beazley
+           Fixed [ #459614 ] SWIG with multiple TCL interpreters.
+
+12/08/2001:beazley
+           Fixed [ #417141 ] rubydec.swg is wrong
+           Reported by Paul Brannan.
+
+12/08/2001:beazley
+           Fixed [ #410557 ] Problem with %addmethods on NT.
+           Reported by Magnus Ljung.
+
+12/08/2001:beazley
+           Fixed [ #445233 ] Enhancement: handle access change.
+           SWIG now parses (but ignores) C++ access changes for the
+           the following:
+
+             class A {
+             protected:
+                void something() { }
+             public:
+                A() {}
+             };
+
+             class B : private A {
+             public:
+                B() : A() { }
+             protected:
+                A::something;    <---- Parsed, but ignored
+             };
+ 
+           Suggested by Krzysztof Kozminski.
+
+12/08/2001: cheetah (william fulton)
+           Fix for Ruby to work using Visual C++.
+
+12/06/2001:beazley
+           Fixed [ #465687 ] unsigned short parameters fail.
+           Reported by Gerald Williams.
+
+12/06/2001:beazley
+           Fixed SF [ #489594 ] PyString_FromString can't take NULL arg.
+           Reported by John Merritt.   SWIG now converts string values
+           to Python using code like this:
+
+           resultobj = result ? PyString_FromString(result) : Py_BuildValue("");
+
+12/06/2001:beazley
+           Fixed SF [ #463561 ] Type conversions not generated.
+           Reported by Gerald Williams.
+	
+12/04/2001:beazley
+           Fixed SF [ #470217 ] Tcl default argument handling.
+           Reported by Shaun Lowry.
+
+12/04/2001:beazley
+           Fixed SF [ #472088 ] defined(MACRO) expanded everywhere.
+           Embedded preprocessor directives such as
+
+              %#if defined(FOO)
+
+           are not expanded by the SWIG preprocessor.
+           Reported by Gerald Williams.
+
+12/04/2001:beazley
+           Fixed SF [ #476467 ] Problems with #define & commas.
+
+12/04/2001:beazley
+           Fixed SF [ #477547 ] wrong declaration of pointer functions.
+           Bad prototypes in Lib/tcl/ptrlang.i.
+
+12/04/2001:beazley
+           Fixed SF [ #483182 ] Constants can take args by mistake. 
+           When swig -perl5 -const is used, constants are declared
+           with a void prototype.  For example:
+
+                sub ICONST () { $examplec::ICONST }
+
+           Patch submitted by Rich Wales.
+
+12/03/2001:beazley
+           New %exception directive.   This is intended to replace %except.
+           It works in exactly the same manner except it does not accept a 
+           language specifier. For example:
+
+               %exception {
+                   try {
+                      $action
+                   } 
+                   catch(SomeError) {
+                       error
+                   }
+               }
+
+           %exception is also name aware---allowing it to be applied to
+           specific declarations in an interface.  For example:
+
+              %exception foo {
+                  ...
+                  exception for any function/method foo
+                  ...
+              }
+
+              %exception Foo::bar {
+                  ...
+                  exception for method bar in class Foo
+                  ...
+              }
+ 
+              %exception Foo::bar(double) {
+                  ...
+                  exception for method bar(double) in class Foo
+                  ...
+              }
+
+           The semantics of this name matching is exactly the same as for %rename.
+           *** NEW FEATURE ***
+           
+12/03/2001:beazley
+           Substantial cleanup of the Python shadow class code.  Shadow classes
+           used to be created in this rather complicated manner involving about
+           a half-dozen strings created in bits and pieces.   Shadow classes
+           are now generated in a more straightforward manner--in the same
+           order that appears in the interface file.
+
+           *** POTENTIAL INCOMPATIBILITY ***
+           The order in which declarations appear in the shadow file may differ.
+           
+12/03/2001:beazley
+           The %insert directive (%{ ... %}, %runtime, %header, %wrapper, etc.)
+           can now be used inside of a class definition.   This has potential
+           uses when generating shadow class code.  For example:
+
+                 class Foo {
+                     ...
+                 %insert("shadow") %{
+                 # Some python code
+                 def blah(self):
+                      print "I'm blah!"
+                 %}
+                     ...
+                 };
+
+           The support for class code insertion depends on the language module.
+           However, the intent of this feature is to simplify the task of extending
+           shadow class code.   In the Python module, this inserts code with the
+           proper level of indendation (regardless of what was used in the SWIG
+           interface).
+           *** NEW FEATURE ***
+
+11/29/2001: cheetah (william fulton)
+           Modifications for Java and Python modules to work on cygwin.
+           Unfortunately a lot of the python module has started to produces code 
+           which cannot be auto-imported using cygwin libtools so most of it is 
+           still broken.
+
+11/28/2001:beazley
+           The %rename and %feature directive can now be used inside
+           of a class definition. For example:
+
+             class Foo {
+                 %rename(foo_i) foo(int);
+                 %rename(foo_d) foo(double);
+             public:
+                 ...
+                 void foo(int);
+                 void foo(double);
+                 ...
+             };
+
+           When used in this manner, the %rename directive only applies
+           to members of the class in which it appears as well as all
+           derived classes.  In fact, this is really just the same
+           as saying:
+
+             %rename(foo_i) Foo::foo(int);
+             %rename(foo_d) Foo::foo(double);
+             class Foo {
+                ...
+             };
+
+           *** NEW FEATURE ***
+
+11/26/2001:beazley
+           Added the experimental %feature directive.  %feature can be
+           used to attach arbitrary string attributes to parse tree nodes.
+           For example:
+
+               %feature("except") blah {
+                   try {
+                      $function
+                   } catch (Error) {
+                       whatever;      
+                   }
+               }
+
+           or
+
+              %feature("set") *::x_set "x";
+
+           or
+
+              %feature("blah") Foo::bar(int,double) const "spam";
+
+           The syntax is borrowed from the %rename directive.  In fact, the
+           exact same semantics apply (inheritance, matching, etc.).
+
+           %feature is a very powerful low-level primitive that can be used to
+           customize individual language modules and to provide hints to 
+           any stage of code generation.   Features are attached to
+           parse tree nodes as attributes with names like "feature:*" where * 
+           is replaced by the feature name (e.g., "feature:except", "feature:set", 
+           etc.).   Language modules can then look for the features using 
+           a simple attribute lookup.
+
+           %feature is intended to be a replacement for a number of
+           older SWIG directives including %except and specialized
+           pragmas. It is more powerful (due to its parameterized
+           name matching) and it provides very precise control over
+           how customization features are attached to individual
+           declarations.   There are future expansion plans that will
+           build upon this capability as well.
+
+           It's not certain that %feature will ever be used directly
+           by SWIG users.  Instead, it may be a low-level primitive
+           that is used in high-level macro definitions.  For instance,
+           to support properties, you might define a macro like this:
+
+           %define %property(name, setf, getf)
+           %feature("set") setf #name;
+           %feature("get") getf #name;
+           %enddef
+
+           Which allows a user to specify things like this:
+
+           %property(p, get_p, set_p);
+
+           class Blah {
+           public:
+              int  get_p();
+              void set_p(int);
+           };
+
+           *** EXPERIMENTAL NEW FEATURE ***
+  
+11/24/2001:beazley
+           The Tcl module has been expanded with some new features for
+           managing object ownership.  For example:
+         
+                set c [Circle -args 20]
+                $c area             # Invoke a method
+                $c -disown          # Releases ownership of the object
+                $c -acquire         # Acquires ownership of the object
+
+           If Tcl owns the object, its destructor is invoked when the 
+           corresponding object command is deleted in Tcl.  
+
+           To simplify the destruction of objects, the following syntax
+           can be used:
+
+                $c -delete         # Delete an object
+
+           This is an alternative for the more obscure variant of 
+
+                rename $c {}
+
+           These features also add functionality at the C API level.
+           The following functions manage ownership from C and
+           can be used in typemaps.
+
+                SWIG_Acquire(void *ptr);
+                SWIG_Disown(void *ptr);
+
+           A new function for constructing instances is also available:
+
+                Tcl_Obj *
+                SWIG_NewInstanceObj(Tcl_Interp *interp, void *ptr,
+                                    swig_type_info *type, int own);
+
+           When used in a typemap, this creates a pointer object and
+           an interpreter command that can be used to issue methods and
+           access attributes as shown above.
+           *** NEW FEATURE ***
+           
+11/23/2001:beazley
+           All Python-related %pragma operations have been eliminated.
+           Most of these were written for older SWIG versions in order to
+           compensate for limitations in earlier releases.  In an effort
+           to reduce the amount of code-clutter and potential for errors,
+           it is easier to simply eliminate the pragmas and to start over
+           (if needed).  To be honest, I'm not even sure the pragmas
+           worked in 1.3.9 and recent releases.
+
+           Note: If you need to insert code into the shadow class file
+           created by SWIG, simply use the %shadow directive like this:
+
+              %shadow %{
+              def some_python_code():         
+                  print "blah!"
+              %}
+
+           *** POTENTIAL INCOMPATIBILITY ***
+
+11/22/2001:beazley
+           Sweeping changes to the way in which the Python module handles
+           shadow classes.   In early implementations, shadow classes were
+           merely Python wrappers around typed pointer objects. However, 
+           some users actually wanted to receive the shadow class object in C.
+           To accomodate this, the dereferencing of the "this" pointer in
+           a shadow class was moved to C as described in CHANGES [8/8/99].
+           However, the process of returning pointers to Python was still
+           somewhat problematic.  Specifically, shadow classes never worked
+           in situations such as these:
+
+             -   Use of any kind of output typemap ('out' or 'argout')
+             -   Global variables (broken as far as I can tell).
+
+           In the past, some users have dealt with this by manually trying
+           to create shadow class objects themselves from C/C++.  However,
+           this was difficult because the C wrappers don't really know how
+           to get access to the corresponding Python class.
+
+           The Python module has now been modified to automatically attach
+           shadow class objects to pointers when they are returned to 
+           Python.   This process occurs in the function SWIG_NewPointerObj()
+           so the process is completely transparent to users.    As a result,
+           shadow classes are now more seamlessly integrated with typemaps
+           and other features of SWIG.
+
+           This change may introduce a number of incompatibilities.  The
+           SWIG_NewPointerObj() now takes an extra parameter "own" to 
+           indicate object ownership.   This can be used to return a pointer
+           to Python that Python should destroy.   In addition, older code
+           that tries to manually construct shadow class objects or which
+           expects bare pointers may break---such pointers may already be
+           encapsulated by a shadow class.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+11/20/2001:beazley
+           Modified the %insert directive to accept single braces { ... }.
+           For example:
+
+                %insert("header") {
+                   ... some code ...
+                }
+
+           This works exactly like %{ ... %} except that the code in the
+           braces is processed using the preprocessor.   This can be useful
+           in certain contexts such as low-level code generation in 
+           language modules.
+           *** NEW FEATURE ***
+           
+11/20/2001:beazley
+           Command line options are now translated into preprocessor
+           symbols.  For example:
+	
+              ./swig -python -shadow -module blah interface.i
+
+           Creates the symbols:
+
+              SWIGOPT_PYTHON 1
+              SWIGOPT_SHADOW 1
+              SWIGOPT_MODULE blah
+              
+           Modules can look for these symbols to alter their code generation
+           if needed.
+           *** NEW FEATURE ***
+             
+11/20/2001:beazley
+           Massive overhaul of the Perl5 module.  A lot of code generation is
+           now driven by tables and typemaps.   The generated wrapper code 
+           also makes use of tables to install constants, variables, and
+           functions instead of inlining a bunch of procedure calls.  The
+           separate variable initialization function is gone.   Most
+           code generation is controlled via the perl5.swg file in the
+           library.
+           *** POTENTIAL INCOMPATIBILITY ***
+           
+11/13/2001:beazley
+           Added parsing support for the C++ typename keyword.  Primarily this
+           is added to better support templates.  For example:
+
+             template<typename T> void  blah(C& v) {
+                 typename C::iterator i = v.begin();
+             }
+
+           Note: typename is supported in the parser in the same way as 'struct'
+           or 'class'.  You probably shouldn't use it anywhere except in templates.
+           *** NEW FEATURE ***
+
+11/11/2001:beazley
+           Massive overhaul of the language module API.   Most functions now
+           use a common, very simple,  API.   There are also a number of
+           interesting semantic side-effects of how code is actually generated.
+           Details will be forthcoming in Doc/Manual/Extending.html.
+
+           *** POTENTIAL INCOMPATIBILITY *** Language modules written for
+           previous versions of SWIG will no longer work,
+
+11/10/2001:beazley
+           Fixed a very subtle bug due to unnamed class wrapping. For example, if
+           you did this
+
+              typedef struct {
+                  int x,y;
+              } gdPoint, *gdPointPtr;
+
+              void foo(gdPointPtr x);
+
+           Then the foo function would get a type-error.   The problem has
+           to do with internal typedef handling and the fact that the typedef
+           declarations after the struct appear later in the parse tree.
+           It should work now.  Problem reported by Vin Jovanovic.
+
+11/09/2001:beazley
+           Subtle change to "out" typemaps (and related variations).  The name
+           that is attached to the typemap is now the raw C identifier that
+           appears on a declaration.  This changes the behavior of
+           member functions.  For example:
+
+               %typemap(out) int foo {
+                  ...
+               }
+
+               class Blah {
+                   public:
+                      int foo();    // typemap gets applied
+               }
+            
+           Previous versions never really specified how this was supposed to
+           work.  In SWIG1.1, you could probably write a typemap for the
+           wrapper name like this:
+
+                %typemap(out) int Blah_foo { ... }
+
+           However, this old behavior is now withdrawn and not supported. 
+           Just use the member name without any sort of special prefix.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+11/06/2001:beazley
+           Changes to Tcl module initialization:
+
+           (1) SWIG now automatically includes the code needed to work with
+                Tcl stubs.  Simply compile with -DUSE_TCL_STUBS.
+
+           (2) SWIG now automatically calls Tcl_PkgProvide to register
+               a package name.  The package name is the same as the name
+               specified with the %module directive.  The version number is
+               set to "0.0" by default.  To change the version number, use
+               swig -pkgversion 1.2 interface.i.
+
+           *** POTENTIAL INCOMPATIBILITY ***
+           Modules that provided stubs and Tcl_PkgProvide on their own might
+           break.  Simply remove that code.
+
+11/05/2001:beazley
+           Changed code generation of constants in the Tcl module.  Constants
+           are now stored in a large table that get installed at module startup.
+           There are also no longer any static variables so it should generate
+           somewhat less code.
+
+11/04/2001:beazley
+           The "const" typemap has been renamed to "constant" in many language
+           modules.  "const" is a C keyword which made the handling of the typemap
+           directive somewhat awkward in the parser.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+11/04/2001:beazley
+           %typemap directive can now accept nearly arbitrary keyword parameters.
+           For example:
+
+              %typemap(in,parse="i",doc="integer") int "...";
+
+           The purpose of the keyword parameters is to supply code generation
+           hints to the target language module.   The intepretation of the
+           parameters is language specific.
+           *** NEW FEATURE ***
+
+11/04/2001:beazley
+           Slight semantic change to internal call/return by value handling.
+           In previous versions of SWIG, call-by-value was translated
+           into pointers.  For example:
+
+               double dot_product(Vector a, Vector b);
+
+           turned into this:
+
+               double wrap_dot_product(Vector *a, Vector *b) {
+                  return dot_product(*a,*b);
+               }
+
+           This translation was normally performed by the SWIG core, outside
+           of the control of language modules.  However, a side effect
+           of this was a lot of bizarre typemap behavior.   For example,
+           if you did something like this:
+
+                %typemap(in) int32 {
+                    ...
+                }
+
+           You would find that int32 was transformed into a pointer everywhere!
+           (needless to say, such behavior is unexpected and quite awkward to
+           deal with).  To make matters worse, if a typedef was also used,
+           the pointer behavior suddenly disappeared.
+
+           To fix this, the pointer transformation is now pushed to the
+           language modules.   This produces wrappers that look roughly
+           like this:
+
+               double wrap_dot_product(Vector *a, Vector *b) {
+                  Vector arg1 = *a;
+                  Vector arg2 = *b;
+                  return dot_product(arg1,arg2);
+               }
+
+           This change also makes it easy to define typemaps for
+           arbitrary undefined types.  For example, you can do this (and it
+           will work regardless what int32 is):
+
+               %typemap(in) int32 {
+                  $1 = (int32) PyInt_AsLong($input);
+               }
+
+           *** POTENTIAL IMCOMPATIBILITY ***
+           This change may break call/return by value code generation in
+           some language modules.
+
+11/03/2001:beazley
+           Changed the name of the default typemaps to the following:
+
+               %typemap() SWIGTYPE  { 
+                   ... an object ...
+               }
+               %typemap() SWIGTYPE * {
+                   ... a pointer ...
+               }
+               %typemap() SWIGTYPE & {
+                   ... a reference ...
+               }
+               %typemap() SWIGTYPE [] {
+                   ... an array ...
+               }
+               %typemap() enum SWIGTYPE {
+                  ... an enum value ...
+               }
+               %typemap() SWIGTYPE (CLASS::*) {
+                   ... pointer to member ...
+               }
+
+
+           These types are used as the default for all types that don't match
+           anything else.  See CHANGES log entry for 8/27/2000 for the
+           old behavior.  The role of these types is also described in 
+           Doc/Manual/Typemaps.html
+
+           *** POTENTIAL INCOMPATIBILITY ***
+          
+10/25/2001:beazley
+           Modified Guile and Mzscheme modules to support
+           multi-argument typemaps.
+
+10/25/2001: cheetah (william fulton)
+           [Java] Fix to handle pointers to arrays.
+
+10/24/2001:beazley
+           Defining a typemap rule for enum SWIGENUM can now be used
+           to define default behavior for enum variables.
+
+10/22/2001:beazley
+           Ruby module modified to support multi-argument typemaps.
+
+10/22/2001:beazley
+           The Ruby module can now handle functions with an arbitrary
+           number of arguments.  Previous versions were limited to 
+           to functions with only 9 or 16 arguments depending on
+           the use of default arguments.   Note: from some inspection
+           of the Ruby interpreter source, the new approach might be
+           a little faster as well.
+
+10/18/2001:beazley
+           Fixed a bug with forward class declarations and
+           templates.
+
+                 class Foo <S,T>;
+
+           Bug reported by Irina Kotlova.
+
+10/16/2001:beazley
+           Support for multivalued typemaps added.  The typemaps
+           are specified using the syntax below.   Within each
+           typemap, variable substitution is handled as follows:
+
+              %typemap(in) (int argc, char *argv[]) {
+                  $arg;  // The input object in the target language
+                  $1;    // C local variable for first argument
+                  $2;    // C local variable for second argument
+
+                  // These variables refer to either argument
+                  $1_type, $1_ltype, $1_basetype, etc...  (argc)
+                  $2_type, $2_ltype, $2_basetype, etc...  (argv[])
+
+                  // Array dimension of argv
+                  $2_dim0
+              }
+
+           Basically any variable that was available in normal typemaps
+           is available for either argument by prefacing the variable
+           name by '$n_' where n is the argument position.
+
+           Notes:  
+           (1) Multi-valued typemaps can only be applied to a single
+               object in the target scripting language.   For example,
+               you can split a string into a (char *, int) pair or
+               split a list into a (int, char []) pair.  It is not
+               possible to map multiple objects to multiple arguments.
+
+           (2) To maintain compatibility with older SWIG versions, the
+               variables such as $target and $type are preserved and
+               are mapped onto the first argument only.
+
+           (3) This should not affect compatibility with older code.
+               Multi-valued typemaps are an extension to typemap handling.
+               Single valued typemaps can be specified in the usual
+               way.
+
+           The old $source and $target variables are officially
+           deprecated.  Input variables are referenced through
+           $arg$ and output values are reference through $result$.
+
+           *** NEW FEATURE ***
+
+10/16/2001:beazley
+           Added parsing support for multivalued typemaps.  The syntax
+           is a little funky, but here goes:
+
+              // Define a multivalued typemap
+              %typemap(in) (int argc, char *argv[]) {
+                    ... typemap code ...
+              }
+
+              // Multivalued typemap with locals
+              %typemap(in) (int argc, char *argv[])(int temp) {
+                    ... typemap code ...
+              }
+              
+              // Copy a multivalued typemap
+              %typemap(in) (int argcount, char **argv) = (int argc, char *argv[]);
+
+              // Apply a multivalued typemap
+              %apply (int argc, char *argv[]) { (int argcount, char **argv) };
+
+           Note: this extra parsing support is added for future extension.
+           No language modules currently support multi-valued typemaps.
+
+10/11/2001:beazley
+           Modified the typemap matching code to discard qualifiers when
+           checking for a match.   For example, if you have a declaration
+           like this:
+
+                 void blah(const char *x);
+
+           The typemap checker checks for a match in the following order:
+
+                 const char *x
+                 const char *
+                 char *x
+                 char *
+
+           If typedef's are involved, qualifier stripping occurs before
+           typedef resolution.  So if you had this,
+
+                typedef char *string;
+                void blah(const string x);
+
+           typemap checking would be as follows:
+
+                const string x
+                const string
+                string x
+                string
+                const char *x
+                const char *
+                char *x
+                char *
+
+           The primary reason for this change is to simplify the implementation
+           of language modules.  Without qualifier stripping, one has to write
+           seperate typemaps for all variations of const and volatile (which
+           is a pain).
+
+           *** POTENTIAL INCOMPATIBILITY ***  Typemaps might be applied in
+           places where they weren't before.
+
+
+10/9/2001: beazley
+           SWIG now generates wrappers that properly disambiguate
+           overloaded methods that only vary in constness.  For
+           example:
+
+               class Foo {
+                  ...
+                  void blah();
+                  void blah() const;
+                  ...
+               };
+
+           To handle this, the %rename directive can be used normally.
+           
+               %rename(blah_const) blah() const;
+
+           In the resulting wrapper code, method calls like this
+           are now generated:
+
+               (obj)->blah()               // Non-const version
+               ((Foo const *)obj)->blah()  // const version
+
+           This should force the right method to be invoked.
+           Admittedly, this is probably obscure, but we might
+           as well get it right.
+
+10/8/2001: beazley
+           The preprocessor now ignores '\r' in the input.
+           This should fix the following bug:
+           [ #468416 ] SWIG thinks macro defs are declarations?
+
+10/8/2001: beazley
+           Added support for ||, &&, and ! in constants.  This
+           fixes SF [ #468988 ] Logical ops break preprocessor.
+           However, at this time, constants using these operators
+           are not supported (the parser will issue a warning).
+
+10/4/2001: beazley
+           Added -show_templates command line option.  This makes
+           SWIG display the code it actually parses to generate
+           template wrappers.  Mostly useful for debugging.
+           *** NEW FEATURE ***
+
+10/4/2001: beazley
+           Change to semantics of %template directive.  When
+           using %template, the template arguments are handled
+           as types by default.  For example:
+
+                %template(vecint) vector<int>;
+                %template(vecdouble) vector<double>;
+
+           To specify a template argument that is *not* a type, you
+           need to use default-value syntax. For example:
+
+                %template(vecint) vector<int,int=50>;
+                %template(vecdouble) vector<int,size=100>;
+
+           In this case, the type name doesn't really matter--only
+           the default value (e.g., 50, 100) is used during
+           expansion.  This differs from normal C++, but I couldn't
+           figure out a better way to do it in the parser.  Might
+           implement an alternative later.
+           *** POTENTIAL INCOMPATIBILITY ***
+       
+10/4/2001: beazley
+           Major changes to template handling in order to provide
+           better integration with the C++ type-system. The main
+           problem is as follows:
+
+           Suppose you have a template like this:
+
+              template<class T> void blah(const T x) { stuff };
+                   
+           Now suppose, that you instantiate the template on a
+           type like this in SWIG:
+
+              %template(blahint) blah<int *>;
+
+           In C++, this is *supposed* to generate code like this:
+
+              void blah(int *const x) { stuff };
+
+           However, in SWIG-1.3.9, the template substitution gets it wrong
+           and produces
+
+              void blah(const int *x) { stuff };
+
+           (notice the bad placement of the 'const' qualifier).
+
+           To fix this, the SWIG parser now generates implicit typedefs
+           for template type arguments that produces code roughly
+           equivalent to doing this:
+
+              typedef int *__swigtmpl1;
+              %template(blahint) blah<__swigtmpl1>;
+
+           which generates code like this:
+
+              void blah(const __swigtmpl1 x) { stuff };
+
+           Since this is correct in both C++ and SWIG, it provides the right
+           semantics and allows everything to compile properly.  However,
+           to clean up the generated code a little bit, the parser keeps
+           track of the template types and performs back-substitution to
+           the original type when building the parse tree.  Thus, even
+           though the implicit typedef is used in the input and may appear
+           in the generated wrapper file (for proper compilation), the parse
+           tree will hide a lot of these details.   For example:
+
+              void blah(const __swigtmpl1 x) { stuff };
+
+           will look like it was declared as follows (which is what
+           you want):
+
+              void blah(int *const x) { stuff }
+
+           The only place you are likely to notice the typedef hack
+           is in bodies of template functions.  For example, if you
+           did this,
+
+              template<class T> class blah {
+                   ...
+                   %addmethods {
+                       void spam() {
+                          T  tempvalue;
+                          ...
+                       }
+                   }
+              }
+
+           you will find that 'T tempvalue' got expanded into some
+           strange typedef type.  This *still* compiles correctly 
+           so it's not a big deal (other than looking kind of ugly
+           in the wrapper file).
+
+10/4/2001: beazley
+           Fixed some inheritance problems in Tcl Object interface.
+
+10/1/2001: beazley
+           Tcl module has changed to use byte-backed pointer strings.  This
+           implementation should be safe on 64-bit platforms.  However,
+           the order in which digits appear in pointer values no longer
+           directly corresponds to the actual numerical value of a
+           pointer (on little-endian machines, pairs of digits appear
+           in reverse order).
+
+10/1/2001: beazley
+           Perl5 module is now driven by a configuration file 'perl5.swg'
+           in the SWIG library.
+
+10/1/2001: beazley
+           The perl5 module no longer tries to apply the "out" typemap
+           in code generated for magic variables.  I'm surprised that
+           this ever worked at all (since all of the code that was there
+           was wrong anyways).   Use the "varout" typemap to handle
+           global variables.
+
+10/1/2001: beazley
+           Fixed a bug related to character array members of structures.
+           For example:
+
+                struct Foo {
+                   char name[32];
+                };
+
+           SWIG is normally supposed to return a string, but this was
+           broken in 1.3.9.   The reason it was broken was actually
+           due to a subtle new feature of typemaps.  When a data member
+           is set to an array like this, the return type of the related
+           accessor function is actually set to an array.  This means
+           that you can now write typemaps like this:
+
+              %typemap(python,out) char [ANY] {
+                 $target = PyString_FromStringAndSize($source,$dim0);
+              }
+
+           This functionality can be used to replace the defunct
+           memberout typemap in a more elegant manner.
+
+9/29/2001: beazley
+           Some further refinement of qualified C++ member functions.
+           For example:
+
+               class Foo {
+                  ...
+                  void foo() const;
+                  ...
+               };
+
+           (i) The SWIG parser was extended slightly to allow 'volatile'
+           and combinations of 'const' and 'volatile' to be used.  This
+           is probably rare, but technically legal.  Only added for
+           completeness.
+
+           (ii) For the purposes of overloading, qualified and non-qualified
+           functions are different.  Thus, when a class has methods like this:
+
+                 void foo();
+                 void foo() const;
+
+           Two distinct methods are declared.  To deal with this, %rename
+           and similar directives have been extended to recognize const.
+           Thus, one can disambiguate the two functions like this:
+
+                %rename(fooconst) Foo::foo() const;
+
+           or simply ignore the const variant like this:
+
+                %ignore Foo::foo() const;
+
+           Note: SWIG currently has no way to actually invoke the const
+           member since the 'const' is discarded when generating wrappers
+           for objects.  
+
+9/27/2001: beazley
+           New directive. %namewarn can be used to issue warning
+           messages for certain declaration names.   The name
+           matching is the same as for the %rename directive.
+           The intent of this directive is to issue warnings for
+           possible namespace conflicts.  For example:
+
+              %namewarn("print is a python keyword") print;
+
+           The name matching algorithm is performed after a name
+           has been resolved using %rename.  Therefore, a
+           declaration like this will not generate a warning:
+
+              %rename("Print") print;
+              ...
+              void print();    /* No warning generated */
+
+           Since the warning mechanism follows %rename semantics, it is
+           also to issue warnings for specific classes or just for
+           certain member function names.
+
+           (Dave - I've been thinking about adding something like this
+           for quite some time.  Just never got around to it)
+           *** NEW FEATURE ***
+
+
+9/27/2001: beazley
+           Enhanced the %ignore directive so that warning messages
+           can be issued to users.   This is done using %ignorewarn
+           like this:
+
+             %ignorewarn("operator new ignored") operator new;
+
+           The names and semantics of %ignorewarn is exactly the 
+           same as %ignore. The primary purpose of this directive
+           is for module writers who want to ignore certain types
+           of declarations, but who also want to alert users about it.
+           A user might also use this for debugging (since messages
+           will appear whenever an ignored declaration appears).
+           *** NEW FEATURE ***
+
+9/26/2001: beazley
+           Super-experimental support for overloaded operators. 
+           This implementation consists of a few different parts.
+
+           (i) Operator names such as 'operator+' are now allowed
+           as valid declarator names.  Thus the 'operator' syntax
+           can appear *anyplace* a normal declarator name was used
+           before.  On the surface, this means that operators can
+           be parsed just like normal functions and methods. 
+           However, it also means that operator names can be used
+           in many other SWIG directives like %rename.  For example:
+
+            %rename(__add__) Complex::operator+(const Complex &);
+
+           (ii) Operators are wrapped *exactly* like normal functions
+           and methods.  Internally, the operator name is used 
+           directly meaning that the wrapper code might contain
+           statements like this:
+
+                arg0->operator*((Complex const &)*arg1);
+
+           This all seems to parse and compile correctly (at least
+           on my machine).
+
+           (iii) SWIG will no longer wrap a declaration if its symbol
+           table name contains illegal identifier characters.  If
+           illegal characters are detected, you will see an error
+           like this:
+ 
+                Warning. Can't wrap operator* unless renamed to a valid identifier.
+
+           The only way to fix this is to use %rename or %name to bind
+           the operator to a nice name like "add" or something. Note:
+           the legal identifier characters are determined by the target
+           language.
+
+           There are certain issues with friend functions and operators.
+           Sometimes, friends are used to define mixed operators such
+           as adding a Complex and a double together.  Currently, SWIG
+           ignores all friend declarations in a class.  A global operator
+           declaration can probably be made to work, but you'll have to
+           rename it and it probably won't work very cleanly in the
+           target language since it's not a class member.
+
+           SWIG doesn't know how to handle operator specifications 
+           sometimes used for automatic type conversion. For example:
+
+           class String {
+              ...
+              operator const char*();
+              ...
+           };
+
+           (this doesn't parse correctly and generates a syntax error).
+
+           Also: operators no longer show up as separate parse-tree
+           nodes (instead they are normal 'cdecl' nodes).  I may
+           separate them as a special case later.
+
+           See Examples/python/operator for an example.
+
+           *** SUPER-EXPERIMENTAL NEW FEATURE ***
+
+Version 1.3.9 (September 25, 2001)
+==================================
+9/25/2001: beazley
+           Fixed parsing problem with type declarations like 
+           'char ** const'.  SWIG parsed this correctly, but the
+           internal type was represented incorrectly (the pointers
+           and qualifiers were in the wrong order).
+
+9/25/2001: beazley
+           Withdrew experimental feature (noted below) that was
+           causing serious parsing problems.
+
+Version 1.3.8 (September 23, 2001)
+==================================
+9/23/2001: beazley
+           Included improved distutils setup.py file in the Tools 
+           directory (look for the setup.py.tmpl file).  Contributed by
+           Tony Seward.
+
+9/23/2001: beazley
+           Included two new RPM spec files in the Tools directory. Contributed
+           by Tony Seward and Uwe Steinmann.
+  
+9/21/2001: beazley
+           Fixed SF Bug [ #463635 ] Perl5.swg does not compile in Visual C++
+
+9/21/2001: beazley
+           Two new directives control the creation of default
+           constructors and destructors:
+
+                %nodefault
+                %makedefault
+
+           These replace %pragma nodefault and %pragma makedefault.
+           (old code will still work, but documentation will only
+           describe the new directives).
+
+9/21/2001: beazley
+           Fixed SF Bug [ #462354 ] %import broken in 1.3.7.
+
+9/20/2001: beazley
+
+           Parser modified to ignore out-of-class constructor
+           and destructor declarations.  For example:
+
+               inline Foo::Foo() :
+                    Bar("foo")
+               { 
+               } 
+
+               inline Foo::~Foo() {
+               }
+
+           Suggested by Jason Stewart.
+           *** EXPERIMENTAL FEATURE ***
+
+9/20/2001: beazley
+           Modified the parser to ignore forward template class
+           declarations.  For example:
+
+              template <class V, long S> class MapIter;
+
+           Suggested by an email example from Irina Kotlova.
+
+9/20/2001: beazley
+           Fixed problem with undeclared tcl_result variable in 
+           the "out" typemap for Tcl.  Reported by Shaun Lowry.
+
+9/20/2001: beazley
+           Incorporated changes to make SWIG work with ActivePerl.  
+           Contributed by Joel Reed.
+
+9/20/2001: beazley
+           Slight change to the parsing of C++ constructor initializers.
+           For example:
+
+           class Foo : public Bar {
+           public:
+                  Foo() : Bar(...) {...}
+           };
+
+           SWIG now discards the contents of the (...) regardless of 
+           what might enclosed (even if syntactically wrong).  SWIG
+           doesn't need this information and there is no reason to
+           needless add syntax rules to handle all of the possibilities
+           here.
+
+9/20/2001: beazley
+           Change to typemaps for structure members.  If you have a
+           structure like this:
+
+              struct Vector {
+                int *bar;
+              };
+
+           The member name 'bar' is now used in any accessor functions.
+           This allows the "in" typemap to be used when setting the value.
+           For example, this typemap
+
+               %typemap(python,in) int *bar {
+                   ...
+               }
+
+           now matches Vector::bar.  It should be noted that this will also
+           match any function with an argument of "int *bar" (so you should
+           be careful).
+           *** NEW FEATURE. POTENTIAL INCOMPATIBILITY ***
+
+9/20/2001: beazley
+           Fixed SF bug #462642 setting string values in structures
+
+9/20/2001: beazley
+           Fixed SF bug #462398 problem with nested templates.
+
+9/20/2001: beazley
+           Fixed SF bug #461626 problem with formatting and C++ comments.
+            
+9/20/2001: beazley
+           Fixed SF bug #462845 Wrong ownership of returned objects.
+           
+9/19/2001: beazley
+           Fixed SF bug #459367.  Default constructors for classes
+           with pure virtual methods.
+
+9/19/2001: beazley
+           Fixed problem with default arguments and class scope.  For
+           example:
+
+               class Foo {
+               public:
+                  enum bar { FOO, BAR };
+                  void blah(bar b = FOO);
+                  ...
+               }
+
+           SWIG now correctly generates a default value of "Foo::FOO" for
+           the blah() method above.  This used to work in 1.1, but was
+           broken in 1.3.7.   Bug reported by Mike Romberg.
+
+Version 1.3.7  (September 3, 2001)
+==================================
+
+9/02/2001: beazley
+           Added special %ignore directive to ignore declarations.  This
+           feature works exactly like %rename.  For example:
+
+             %ignore  foo;        // Ignore all declarations foo
+             %ignore  ::foo;      // Only ignore foo in global scope
+             %ignore  Spam::foo;  // Only ignore in class Spam
+             %ignore  *::foo;     // Ignore in all classes
+
+           %ignore can also be parameterized.  For example:
+
+             %ignore foo(int);
+             %ignore ::foo(int);
+             %ignore Spam::foo(int);
+             %ignore *::foo(int);
+
+           *** NEW FEATURE ***
+            
+
+9/02/2001: cheetah (william fulton)
+           [Java] shadowcode pragma modified so that the code that is output 
+           in the shadow file is placed relative to where it is placed in the 
+           c/c++ code. This allows support for JavaDoc function comments. 
+
+9/01/2001: beazley
+           Fixed SF Patch [ #447791 ] Fix for python -interface option.
+           Submitted by Tarn Weisner Burton.
+
+9/01/2001: beazley
+           SWIG no longer generates default constructors/destructors
+           for a class if it only defines a private/protected constructor
+           or destructor or if any one of its base classes only has
+           private constructors/destructors.  This was reported in
+           SF Patch [ #444281 ] nonpublic/default/inhereted ctor/dtor
+           by Marcelo Matus.
+
+9/01/2001: beazley
+           Added patch to Perl5 module that allows constants to be
+           wrapped as constants that don't require the leading $.
+           This feature is enabled using the -const option.
+           Patch contributed by Rich Wales.
+           *** NEW FEATURE ***
+
+8/31/2001: beazley
+           Added parsing support for the 'volatile' type qualifier.
+           volatile doesn't mean anything to SWIG, but it is
+           needed to properly generate prototypes for declarations
+           that use it.  It's also been added to make the SWIG type
+           system more complete.
+           *** NEW FEATURE ***
+
+8/30/2001: beazley
+           Added support for parameterized %rename directive.  *** This
+           new feature can be used to greatly simplify the task of
+           resolving overloaded methods and functions. ***
+           
+           In prior versions of SWIG, the %rename directive was
+           used to consistently apply an identifier renaming. For 
+           example, if you said this:
+
+                %rename foo bar;
+
+           Every occurrence of 'foo' would be renamed to 'bar'. 
+           Although this works fine for resolving a conflict with a
+           target language reserved word, it is useless for
+           for dealing with overloaded methods.    This is because
+           all methods are simply renamed to the same thing 
+           (generating the same conflict as before).
+
+           Therefore, the only way to deal with overloaded methods
+           was to go through and individually rename them all using
+           %name.  For example:
+
+             class Foo {
+             public:
+                 virtual void bar(void);
+                 %name(bar_i) virtual void bar(int);
+                 ...
+             };
+
+           To make matters worse, you had to do this for all
+           derived classes too.
+
+             class Spam : public Foo {
+             public:
+                 virtual void bar(void);
+                 %name(bar_i) virtual void bar(int);
+                 ...
+             };
+
+           Needless to say, this makes it extremely hard to resolve
+           overloading without a lot of work and makes it almost
+           impossible to use SWIG on raw C++ .h files.
+
+           To fix this, %rename now accepts parameter declarators.
+           The syntax has also been changed slightly.  For example,
+           the following declaration renames all occurrences of 'bar(int)'
+           to 'bar_i', leaving any other occurrence of 'bar' alone.
+
+             %rename(bar_i) bar(int);
+
+           Using this feature, you can now selectively rename 
+           certain declarations in advance.  For example:
+
+             %rename(bar_i) bar(int);
+             %rename(bar_d) bar(double);
+
+             // Include raw C++ header    
+             %include "header.h"
+
+           When %rename is used in this manner, all occurrence of bar(int)
+           are renamed wherever they might occur.  More control is obtained
+           through explicit qualification. For example,
+
+              %rename(bar_i) ::bar(int);
+
+           only applies the renaming if bar(int) is defined in the global scope.
+           The declaration,
+     
+              %rename(bar_i) Foo::bar(int);
+
+           applies the renaming if bar(int) is defined in a class Foo.
+           This latter form also supports inheritance.  Therefore, if you
+           had a class like this:
+
+               class Spam : public Foo {
+               public:
+                   void bar(int);
+               }
+
+           The Spam::bar(int) method would also be renamed (since Spam 
+           is a subclass of Foo).   This latter feature makes it easy
+           for SWIG to apply a consistent renaming across an entire
+           class hierarchy simply by specifying renaming rules for
+           the base class.
+
+           A class wildcard of * can be used if you want to renaming
+           all matching members of all classes.  For example:
+
+              %rename(bar_i) *::bar(int);
+
+           will rename all members bar(int) that are defined in classes.
+           It will not renamed definitions of bar(int) in the global
+           scope.
+
+           The old use of %rename is still supported, but is somewhat
+           enhanced.  
+
+              %rename(foo) bar;      // Renames all occurrences of 'bar'.
+              %rename(foo) ::bar;    // Rename all 'bar' in global scope only.
+              %rename(foo) *::bar;   // Rename all 'bar' in classes only.
+              %rename(foo) Foo::bar; // Rename all 'bar' defined in class Foo.
+
+           *** NEW FEATURE ***
+
+8/30/2001: beazley
+           Added support for data-member to member-function 
+           transformation.  For example, suppose you had a
+           structure like this:
+
+                struct Vector {
+                    double x,y;
+                };
+
+           Now suppose that you wanted to access x and y 
+           through a member function interface instead 
+           of the usual SWIG behavior. For example:
+
+              f.set_x(3.4)      # instead of f.x = 3.4
+              x = f.get_x()     # instead of x = f.x
+
+           To do this, simply use the new %attributefunc
+           directive.  For example:
+
+              %attributefunc(get_%s,set_%s)
+              struct Vector {
+                 double x,y;
+              };
+              %noattributefunc
+
+           The arguments to %attributefunc are C-style printf
+           format strings that determine the naming convention
+           to use.  %s is replaced with the actual name of the
+           data member. SWIG provides a number of printf
+           extensions that might help.  For example, if you
+           wanted to title case all of the attributes, you
+           could do this:
+
+              %attributefunc(get%(title)s,set%(title)s);
+
+           This will turn an attribute 'bar' to 'getBar()' and 'setBar()'.
+
+           (someone requested this long ago, but I finally figured
+           how to implement it in a straightforward manner).
+           *** EXPERIMENTAL NEW FEATURE ***
+           
+8/30/2001: beazley
+           SWIG now automatically generates default constructors
+           and destructors if none are defined.  This used to be
+           enabled with a command line switch -make_default, but
+           most people want these functions anyways.  To turn
+           off this behavior use the -no_default option or include
+           the following pragma in the interface file:
+ 
+                 %pragma no_default;
+  
+           This may break certain interfaces that defined their
+           own constructors/destructors using the same naming
+           convention as SWIG.  If so, you will get duplicate
+           symbols when compiling the SWIG wrapper file.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+8/29/2001: beazley
+           Changes to Perl5 shadow class code generation.  Iterators
+           are no longer supported (FIRSTKEY, NEXTKEY).  Also, attribute
+           access has been changed to rely on inheritance in order
+           to provide better behavior across modules.  
+
+8/28/2001: beazley
+           Various obscure improvements to the type system and classes.
+           Strange declarations like this are now wrapped correctly
+           (i.e., the generated wrapper code doesn't cause the C++
+            compiler to die with a type error).
+
+            class Foo {
+            public:
+                 typedef double Real;
+                 Real foo(Real (*op)(Real,Real), Real x, Real y);
+            };
+
+           Inheritance of types is also handled correctly.
+           
+8/28/2001: beazley
+           Changes to class wrappers.   When SWIG sees two classes like this,
+ 
+           class X {
+           public:
+             void foo();
+             ...
+           }
+ 
+           class Y : public X {
+           public:
+             void bar();
+             ...
+           }
+ 
+           it now only generates two wrapper functions:
+ 
+             X_foo(X *x) { x->foo(); }
+             Y_bar(Y *y) { y->bar(); }
+ 
+           Unlike SWIG1.15, the foo() method does *not* propagate to a wrapper
+           function Y_foo(). Instead, the base class method X_foo() must be
+           used.
+
+           This change should not affect modules that use shadow classes, but
+           it might break modules that directly use the low-level C wrappers.
+           This change is being made for a number of reasons:
+
+               -  It greatly simplifies the implementation of SWIG--especially
+                  with anticipated future changes such as overloaded methods.
+
+               -  It results in substantially less wrapper code--especially
+                  for big C++ class hierarchies (inherited declarations
+                  are no longer copied into every single derived class).
+
+               -  It allows for better code generation across multiple
+                  SWIG generated modules (code isn't replicated in
+                  every single module).
+
+           *** POTENTIAL INCOMPATIBILITY ***                                    
+
+8/22/2001: cheetah (william fulton)
+           Provided some Windows documentation in the Win directory and some
+           Visual C++ project files for running examples on Windows.
+
+8/28/2001: mkoeppe
+	   [Guile] Handle renamed overloaded functions properly;
+	   thanks to Marc Zonzon <Marc.Zonzon@univ-rennes1.fr> for the
+	   patch.  See the new test case name_cxx.
+
+8/27/2001: mkoeppe
+	   [Tcl] Removed lots of warnings issued by the Sun Forte
+	   compilers, which were caused by mixing function pointers
+	   of different linkages (C++/C). 
+
+8/23/2001: mkoeppe
+	   Improved the MzScheme module by porting Guile's pointer
+	   type checking system and making type dispatch
+	   typemap-driven. 
+
+8/22/2001: beazley
+           Entirely new symbol table processing.   SWIG should be able to
+           report much better error messages for multiple declarations. 
+           Also, the new symbol table allows for overloaded functions
+           (although overloading isn't quite supported in the language
+           modules yet).
+
+8/22/2001: cheetah (william fulton)
+           * [Java] %new support added.
+           * [Java] Package JNI name refixed!
+
+8/19/2001: beazley
+           Python module modified to support pointers to C++ members.  This
+           is an experimental feature.
+           *** NEW FEATURE ***
+     
+8/19/2001: beazley
+           Added limited parsing and full type-system support for pointers to
+           members. None of SWIG's language modules really know how to deal with
+           this so this is really only provided for completeness and future
+           expansion.  Note: SWIG does not support pointers to members which 
+           are themselves pointers to members, references to pointers to members,
+           or other complicated declarations like this.
+           *** NEW FEATURE ***
+
+8/19/2001: beazley
+           SWIG is much better at parsing certain C++ declarations. Operators and
+           friends generally don't cause anymore syntax errors.  However, neither
+           are really supported.
+
+8/18/2001: beazley
+           Added *highly* experimental support for wrapping of C++
+           template declarations.  Since C++ templates are essentially
+           glorified macros and SWIG has a fully operational C 
+           preprocessor with macro support, the parser now converts
+           template declarations to macros.  For example, a function
+           template like this
+
+               template<class T> T max(T a, T b);
+
+           is internally converted into a macro like this:
+
+               %define %_template_max(__name,T)
+               %name(__name) T max(T a, T b);
+               %enddef
+
+           To instantiate a version of the template, a special %template declaration
+           is used like this:
+
+               %template(maxint) max<int>;          
+               %template(maxdouble) max<double>;
+
+           The parameter to the %template directive must be proper C identifier that's
+           used to uniquely name the resulting instantiation.   When used, the
+           the expanded macro looks like this:
+
+              %name(maxint) int max(int a, int b);
+              %name(maxdouble) double max(double a, double b);
+
+           A similar technique is used for template classes.   For instance:
+
+              template<class T> class vector {
+                 T *data;
+                 int sz;
+              public:
+                 vector(int nitems);
+                 T *get(int n);
+                 ...
+              };
+
+           Gets converted into a macro like this:
+
+              %define %_template_vector(__name, T)
+              %{
+              typedef vector<T> __name;
+              %}
+              class __name {
+                 T *data;
+                 int sz;
+              public:
+                 __name(int nitems);
+                 T *get(int n);
+                 ...
+              };
+              typedef __name vector<T>;
+              %enddef
+
+           An a specific instantiation is created in exactly the same way:
+
+             %template(intvec) vector<int>;
+
+           The resulting code parsed by SWIG is then:
+
+              %{
+              typedef vector<int> intvec;
+              %}
+              class intvec {
+                  int *data;
+                  int sz;
+              public:
+                  intvec(int nitems);
+                  int *get(int n);
+                  ...
+              };
+              typedef intvec vector<int>;
+
+           Note: the last typedef is non-standard C and is used by SWIG to provide
+           an association between the name "intvec" and the template type 
+           "vector<int>".
+
+           CAUTION:  This is an experimental feature and the first time SWIG has
+           supported C++ templates.   Error reporting is essential non-existent.
+           It will probably break in certain cases.
+           *** EXPERIMENTAL NEW FEATURE ****
+
+8/15/2001: beazley
+           Change to wrapping of multi-dimensional arrays.  Arrays
+           are now properly mapped to a pointer to an array of
+           one less dimension.  For example:
+
+                int [10];              -->  int *
+                int [10][20];          -->  int (*)[20];
+                int [10][20][30];      -->  int (*)[20][30];
+
+           This change may break certain SWIG extensions because
+           older versions simply mapped all arrays into a single
+           pointer such as "int *".   Although possibly unusual, 
+           the new version is correct in terms of the C type system.
+           *** POTENTIAL INCOMPATIBILITY ***
+    
+8/06/2001: cheetah (william fulton)
+           * [Java] Array setters generated for struct/class array members.
+
+8/13/2001: beazley
+           Many improvements to Tcl/Perl/Python modules to better
+           work with multiple interface files and the %import directive.
+
+8/13/2001: beazley
+           Fixed up the behavior of %import in the Python module.
+           SWIG no longer pollutes the module namespace by using
+           'from module import *' to refer to the other module. 
+           Instead, it does a proper 'import module'.   Also, SWIG
+           may work a lot better when importing modules that include
+           references to other imported modules.
+
+8/13/2001: mkoeppe
+	   Added new typemap substitutions, generalizing those of the
+	   Guile-specific 5/27/2001 changes: 
+	   * $descriptor is the same as SWIGTYPE$mangle, but also
+	     ensures that the type descriptor of this name gets
+	     defined.
+	   * $*type, $*ltype, $*mangle, $*descriptor are the same as
+	     the variants without star, but they REMOVE one level of
+	     pointers from the type. (This is only valid for pointer 
+	     types.)
+	   * $&type, $&ltype, $&mangle, $&descriptor are the same as
+	     the variants without ampersand, but they ADD one level of
+	     pointers to the type.
+	   The Guile-specific substitution $basedescriptor was removed
+	   because it was useless.
+
+8/12/2001: beazley
+           The %extern directive is now deprecated and withdrawn.  The
+           purpose of this directive was to import selected definitions
+           from other interface files and headers.  However, the same
+           functionality is better handled through %import.   This
+           leaves SWIG with two file inclusion directives:
+
+              %include filename     - Inserts into current interface
+              %import filename      - Import types and classes from 
+                                      another module
+
+           *** POTENTIAL INCOMPATIBILITY ***
+
+8/09/2001: beazley
+           Added new support for wrapping C/C++ callback functions. 
+           A common problem with some C libraries is that many
+           functions take a function pointer as an argument. For example:
+
+              int do_op(..., int (*op)(int,int), ...);
+
+           Unfortunately, the only way to call such a function is to
+           pass it a function pointer of some compatible type.  In
+           previous versions of SWIG, you had to solve this problem
+           with some really gross hacks.  For example, if you wanted to
+           use the following function as a callback,
+
+               int foo(int, int);
+
+           you had to install a pointer to it as a constant.  For example:
+
+               %constant int (*FOO)(int,int) = foo;
+
+           or 
+
+               const int (*FOO)(int,int) = foo;
+
+           or if you had a really old SWIG version:
+
+               typedef int (*OP_FUNC)(int,int);
+               int do_op(..., OP_FUNC, ...);
+               const OP_FUNC FOO = foo;
+
+           
+           Now, you can do one of two things:
+
+               %constant int foo(int,int);
+
+           This creates a constant 'foo' of type int (*)(int,int).
+           Alternatively, you can do this:
+
+               %callback("%s");
+               int foo(int,int);
+               int bar(int,int);
+               %nocallback;
+
+           In this case, the functions are installed as constants where
+           the name is defined by the format string given to %callback().
+           If the names generated by the format string differ from the
+           actual function name, both a function wrapper and a callback 
+           constant are created.  For example:
+
+               %callback("%(upper)s");
+               int foo(int,int);
+               int bar(int,int);
+               %nocallback;
+           
+           Creates two wrapper functions 'foo', 'bar' and additionally
+           creates two callback constants 'FOO', 'BAR'.
+
+           Note: SWIG still does not provide automatic support for 
+           writing callback functions in the target language.
+           *** NEW FEATURE ***
+
+8/06/2001: cheetah (william fulton)
+           * struct nesting fixes as per SF bug #447488.
+
+8/03/2001: beazley
+           The %name directive now applies to constants created with
+           #define and %constant.  However, most language modules
+           were never written to support this and will have to be
+           modified to make it work.  Tcl, Python, and Perl modules
+           are working now.
+           *** NEW FEATURE ***
+
+8/03/2001: beazley
+           Massive changes and simplification of C declaration parsing.
+           Although SWIG is still not a full C parser, its ability
+           to handle complex datatypes including pointers to functions
+           and pointers to arrays has been vastly improved.  
+
+8/03/2001: cheetah (william fulton)
+           * Distribution fixes: autoconf no longer needed to install SWIG.
+
+8/02/2001: beazley
+           Removed two undocumented parsing features.  SWIG no longer
+           supports out-of-class static function or variable
+           declarations.  For example:
+
+                static int Foo::bar;
+
+           This feature may return if there is sufficient demand. 
+           However, since SWIG is most often used with header files,
+           it is more likely for these definitions to be included
+           in the class definition.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+8/02/2001: cheetah (william fulton)
+	   * Cleanup of the GIFPlot examples. Upgraded Java GIFPlot example.
+
+8/01/2001: cheetah (william fulton)
+	   * [Java] Efficiency changes: _cPtr used where possible rather than
+	     getCPtr(). Bug fixes for inheritance - derived class sometimes
+	     didn't delete the c memory when _delete() was called.
+	   * [Java] Abstract c++ classes are wrapped with a java abstract shadow
+	     class. Also a pure virtual function is mapped with an abstract method.
+	   * The default output file has always been <module>_wrap.c. It is now
+	     <module>_wrap.cxx if the -c++ commandline option is passed to swig.
+	     This has been done as otherwise c++ code would appear in a c file.
+           *** POTENTIAL INCOMPATIBILITY *** 
+
+7/31/2001: beazley
+           Modified the %constant directive to be more C-like in syntax.
+           The syntax is now:
+
+                %constant NAME = VALUE;
+                %constant TYPE NAME = VALUE;
+ 
+           For example:
+
+                %constant Foo *Bar = &Spam;
+
+           A more subtle case is as follows:
+
+               %constant int (*FOO)(int,int) = blah;
+
+           *** POTENTIAL INCOMPATIBILITY ***  Modules that were using
+           the %constant directive directly will need to be modified.
+      
+7/30/2001: beazley
+           Removed obscure and undocumented form of the %inline directive:
+
+               %inline int blah(int a, int b) {
+                  ...
+               }
+
+           *** POTENTIAL INCOMPATIBILITY *** 
+           (note: this feature was never documented and is withdrawn)
+
+7/30/2001: beazley
+           Removed support for functions with no explicitly declared
+           return type.  For example:
+
+                  foo(int);
+
+           In C, such functions were implicitly assumed to return an 'int'.
+           In C++, this is illegal.  Either way, it's considered bad
+           style.  Removing support for this in SWIG will simplify
+           certain issues in parsing.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+7/30/2001: mkoeppe
+	   * Partial merge from the CVS trunk.  The Source/DOH directory
+	     and most of the Source/Swig directory is up-to-date now.
+	   * [Guile] %scheme is now a macro for %insert("scheme").  
+	     New syntax:  %scheme "FILENAME"; 
+	     New syntax:  %scheme %{ SCHEME-CODE %}
+	     New macros %multiple_values, %values_as_list,
+	     %values_as_vector. 
+
+7/29/2001: beazley
+           %readonly and %readwrite have been turned into SWIG pragmas.
+           %pragma(swig) readonly and %pragma(swig) readwrite.  Macros
+           are used to provide backwards compatibility.
+
+7/29/2001: beazley
+           Minor changes to %pragma directive.  %pragma must always
+           be directed to a specific language.  For example:
+
+              %pragma(swig) make_default;
+              %pragma(perl5) include = "blah.i";
+
+           Also extended the pragma directive to allow code blocks
+ 
+              %pragma(foo) code = %{
+                  ... some code ...
+              %}
+
+           *** POTENTIAL INCOMPATIBILITY ***
+
+7/29/2001: beazley
+           Change to the way 'const' variables are wrapped.  In 
+           previous versions of SWIG, a 'const' variable was
+           wrapped as a constant.   Now, 'const' variables are
+           wrapped as read-only variables.  There are several
+           reasons for making this change, mostly pertaining to
+           subtle details of how 'const' actually works. 
+
+           This will probably break old interfaces that used 'const'
+           to create constants.   As a replacement, consider using this:
+
+           const int a = 4;   ===>   %constant int a = 4;
+           *** POTENTIAL INCOMPATIBILITY ***
+
+7/29/2001: beazley
+           Reorganization and simplification of type parsing.
+           Types with 'const' should work correctly now.
+
+7/29/2001: beazley
+           Most swig directives related to the documentation system
+           are now deprecated.
+
+7/29/2001: beazley
+           Removed support for Objective-C in order to simplify
+           parser reconstruction.  Will return if there is sufficient
+           demand.
+           *** POTENTIAL INCOMPATIBILITY ***
+
+7/29/2001: beazley
+           Code inclusion has been modified in the parser.  A common
+           directive %insert is now used for everything.  This
+           inserts a file into the output:
+
+               %insert(header) "foo.swg"
+
+           This inserts some inline code into the output
+
+               %insert(header) %{
+                   ... some code ... 
+               %}
+
+           There are five predefined targets for the insert directive:
+
+               "header"    - Header section of wrapper file
+               "runtime"   - Runtime section of wrapper file
+               "wrapper"   - Wrapper section
+               "init"      - Initialization function
+               "null"      - Nothing. Discard.
+
+           The following directives are still supported, but are
+           now defined in terms of macros:
+
+               %{ ... %}           -> %insert(header)  %{ ... %}
+               %init %{ ... %}     -> %insert(init)    %{ ... %}
+               %wrapper %{ ... %}  -> %insert(wrapper) %{ ... %}
+               %runtime %{ ... %}  -> %insert(runtime) %{ ... %}
+
+           Language modules can define new named targets by using the
+           C API function Swig_register_filebyname() (see main.cxx).
+           For example, if you wanted to expose a shadow class file,
+           you could do this:
+
+              Swig_register_filebyname("shadow", f_shadow);
+
+           Then in the interface file:
+
+              %insert(shadow) %{ ... %}
+
+           Note: this change should not affect any old interfaces, but
+           does open up new possibilities for enhancements.
+
+7/29/2001: beazley
+           SWIG now always includes a standard library file 'swig.swg'.
+           This file defines a large number of macro definitions
+           that define the behavior of various SWIG directives.
+           Previously, all SWIG directives were handled as special
+           cases in the parser.  This made the parser a large 
+           bloated mess.  Now, the parser is stripped down to a few
+           simple directives and macros are used to handle everything else.
+
+7/26/2001: cheetah (william fulton)
+	   * Fixes for Sourceforge bug #444748 - new testcase cpp_static:
+	     [TCL] Class with just static member variable/function fix
+	     [Java] Fixed static variables support
+	     [Ruby] Static variables workaround removed
+
+7/27/2001: mkoeppe
+	   * stype.c (SwigType_default): Strip qualifiers first. The
+	     default type of "int * const" is now "SWIGPOINTER *".
+	   * main.cxx: Define "__cplusplus" in SWIG's preprocessor if
+	     in C++ mode.
+	   * [Guile]: Added some support for arrays and C++
+	     references, fixing the "constant_pointers" test case.
+	   * Moved most tests from the old Guile-specific test-suite
+	     to the new test-suite.  Also moved perl5/pointer-cxx
+	     example there.
+
+7/26/2001: cheetah (william fulton)
+	   * Test-suite added.
+	   * Initial testcases: constant_pointers cpp_enum defines
+	     sizeof_pointers unions virtual_destructor
+	   * Make clean improvements.
+
+7/24/2001: cheetah (william fulton)
+	   * [Java] Underscores in the package name and/or module name
+	   no longer give linking problems.
+
+7/17/2001: cheetah (william fulton)
+	   * More parser bug fixes for constant pointers
+
+7/19/2001: mkoeppe
+	   * [Guile] Aesthetic improvement in variable wrappers.
+
+7/18/2001: beazley
+           * Fixed core-dump problem in pointer library when 
+             freeing character arrays.
+             SF Bug [ #415837 ] pointer lib core dump
+
+7/18/2001: beazley
+           * Fixed problem with default destructors and shadow
+             classes.  SF bug #221128.
+
+7/18/2001: beazley
+           * To provide better line-number tracking in interfaces
+             with lots of macros, special locator comments are
+             now generated by the SWIG preprocessor.  For example:
+
+                 /*@foo.i,42,BLAH@*/expanded macro/*@@*/
+
+             The first /*@...@*/ sequence sets the context
+             to point to the macro code.  The /*@@*/ comment
+             terminates the context.  The SWIG parser should
+             ignore all of the locator comments as should
+             the C compiler (should such comments end up
+             in generated wrapper code).
+
+7/18/2001: mkoeppe
+	   * The parser now handles severely constified types in
+	   typemaps.  This introduced a new shift/reduce conflict, but
+	   only with a heuristic function-pointer catch-all rule.  
+	   * [Guile]: Added typemaps for severely constified types. 
+	   * Fixed the "template-whitespace" problem by canonicalizing
+	     whitespace, especially around angle brackets and commas. 
+
+7/17/2001: mkoeppe
+	   * [Guile]: A Scheme file is emitted if the -scmstub FILE.SCM
+	   command-line option is used.  The %scheme directive
+	   (implemented as a macro for a pragma) allows to insert
+	   arbitrary code here.  In "simple" and "passive" linkage,
+	   the file gets filled with define-module and export
+	   declarations.
+
+7/17/2001: cheetah (william fulton)
+	   * Parser bug fix to support constant pointers, eg int* const ptr.
+	   Fixed everywhere - variables, parameters, return types etc. Note that
+	   when wrapping a constant pointer variable only the getter is generated.
+
+7/17/2001: mkoeppe
+	   * Fixed SF bug #441470 (#define X "//" would not be parsed,
+	     see test-suite entry "preproc-1"), reported by T. W. Burton
+	     <twburton@users.sf.net>.
+	   * Changed the type of character constants to "char", rather
+	     than "char *".  Changed the individual language modules
+	     to keep the old behaviour, except for the Guile module,
+	     where it is desired to make them Scheme characters.  This
+	     fixes SF bug #231409, test-suite entry "char-constant".
+	   * Applied patch for DOH/Doh/memory.c by Les Schaffer
+	     <schaffer@optonline.net> (avoid required side effects in
+	     assert). 
+
+7/17/2001: cheetah (william fulton)
+	   * Bug fix in parser for virtual destructor with void as parameter
+	   * Bug fix in parser #defines embedded within classes/structs/unions
+	   Consequently %constant can now also be placed within a struct/class/union.
+	   * Bug fix in parser to allow sizeof(*I_am_a_pointer) within a #define
+
+7/16/2001: mkoeppe
+	   * Added changes for the Macintosh contributed by Luigi
+	   Ballabio <ballabio@mac.com>. 
+	   * Some "const" fixes in the code.
+	   * [Guile]: Made the constant-wrapper functions much shorter.
+
+7/13/2001: mkoeppe
+	   * [Guile]: Some "const" fixes for Guile version 1.3.4.
+	   * Handle anonymous arguments with default values and static
+	     array members of classes.  Both bugs reported by Annalisa Terracina
+	     <annalisa.terracina@datamat.it>; see the files
+	     Examples/guile/test-suite/static-array-member.i and
+	     anonymous-arg.i.
+
+Version 1.3.6  (July 9, 2001)
+=============================
+
+7/09/2001: cheetah (william fulton)
+	   * GIFPlot examples: FOREGROUND and BACKGROUND definition missing 
+	   after TRANSPARENT #define fix in GIFPlot
+
+7/03/2001: beazley
+           Fixed up the version numbers so that the release is known
+           as 1.3.6.  All future releases should have a similar
+           version format.
+
+7/02/2001: mkoeppe
+	   * [Python]: Prevent the problem of self.thisown not being
+	   defined if the C++ class constructor raised an exception.
+	   Thanks to Luigi Ballabio <ballabio@mac.com>.
+
+6/29/2001: mkoeppe
+	   * More portability fixes; fixed "gcc -Wall" warnings.
+
+6/29/2001: cheetah (william fulton)
+	   * GIFPlot examples: TRANSPARENT #define multiple times on Solaris 
+	   (clashes with stream.h).
+	   * Multiple definition bug fix for shadow classes. The perl and python 
+	   modules had workarounds which have been replaced with fixes in 
+	   the core. Many of the Language::cpp_xxxx functions now set a 
+	   flag which the derived classes can access through 
+	   is_multiple_definition() to see whether or not code should be 
+	   generated.  The code below would have produced varying degrees 
+	   of incorrect shadow class code for the various modules:
+	   class TestClass
+	   {
+	   public:
+	     TestClass() {};
+	     TestClass(int a) {};
+	     ~TestClass() {};
+	     unsigned long xyz(short k) {};
+	     unsigned long xyz(int n) {};
+	     static void static_func() {};
+	     static void static_func(int a) {};
+	   };
+	   void delete_TestClass(int a);
+
+6/27/2001: mkoeppe
+	   * [Perl] Another const-related portability fix.
+
+6/26/2001: cheetah (william fulton)
+	   * [Java] Added in cpp_pragma() support with a host of new pragmas - see 
+	   jswig.html. These are designed for better mixing of Java and c++. It 
+	   enables the user to specify pure Java classes as bases and/or interfaces 
+	   for the wrapped c/c++.
+	   * [Java] Old pragmas renamed. Warning given for the moment if used.
+          *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+6/25/2001: mkoeppe
+	   * Incorporated more build changes contributed by Wyss Clemens
+	   <WYS@helbling.ch> for swig/ruby on cygwin.
+
+6/20/2001: cheetah (william fulton)
+	   * Makefile mods so that 'make check' uses the swig options in the makefiles
+	   * [Java] Removed Generating wrappers message
+	   * [Java] NULL pointer bug fix
+	   * [Java] Bug fix for Kaffe JVM
+
+6/20/2001: mkoeppe
+	   * SWIG_TypeQuery from common.swg now returns a
+	   swig_type_info* rather than a void*.  This fixes a problem
+	   when using pointer.i and C++, as illustrated by the new
+	   test-suite example perl5/pointer-cxx.
+	   * Portability fixes (const char *). 
+	   * Incorporated build changes contributed by Wyss Clemens
+	   <WYS@helbling.ch>, which make swig runnable on cygwin.
+
+6/19/2001: cheetah (william fulton)
+	   * [Java] Bug fix for SF bug #211144. This fix is a workaround 
+	     until fixed in the core.
+
+6/19/2001: mkoeppe
+	   * [Guile]: Portability fixes for use with the Sun Forte
+	   compilers. 
+	   * [Tcl]: Portability fix (const char *).
+	   * [Tcl]: Configure now first tries to find a tclConfig.sh
+	   file in order to find the Tcl include directory, library
+	   location and library name.
+	   * [Python]: Added a few possible library locations.
+
+6/18/2001: mkoeppe
+	   * [Guile]: Don't call scm_c_export if nothing is to be
+	     exported.  Don't warn on %module if module has been set
+	     already (this frequently occurs when %import is used).
+
+6/16/2001: mkoeppe
+	   * [Guile]: New "passive" linkage, which is appropriate for
+	     multi-module extensions without Guile module magic.
+
+6/15/2001: mkoeppe
+	   * [Guile]: Fixed printing of smobs (space and angle were
+	     missing). 
+	   * Properly generate type information for base classes
+	     imported with the %import directive.  Thanks to Marcelo
+	     Matus <mmatus@acms.arizona.edu> for the report and the
+	     patch; this closes SF bug #231619; see also
+	     Examples/guile/test-suite/import*. 
+	   * [Guile]: Fix casting between class and base class; the
+	     runtime type system had it the wrong way around; see
+	     Examples/guile/test-suite/casts.i
+	   * Make typemaps for SWIGPOINTER * with arg name take
+	     precedence over those without arg name, to match normal
+	     typemap precedence rules.
+	   * Fixed the random-line-numbers problem reported as SF bug
+	     #217310; thanks to Michael Scharf <scharf@users.sf.net>.
+	   * [Guile]: Handle the %name and %rename directives.
+	   * New syntax: %name and %rename now optionally take double
+	     quotes around the scripting name.  This is to allow scripting
+	     names that aren't valid C identifiers.
+
+6/14/2001: beazley
+           Made a minor change to the way files are loaded in
+           order to get file/line number reporting correct in
+           the preprocessor.
+
+6/14/2001: mkoeppe
+	   * The parser now understands the (non-standard) "long long"
+	     types. It is up to the individual language modules to
+	     provide typemaps if needed. Reported by Sam Steingold, SF
+	     bug #429176.
+	   * The parser now understands arguments like "const int *
+	     const i". This fixes SF bug #215649.
+	   * Fixed the Guile test-suite.
+
+6/13/2001: mkoeppe
+	   Partial merge from the CVS trunk at tag
+	   "mkoeppe-merge-1". This covers the following changes:
+
+| 01/16/01: ttn
+|	   Wrote table of contents for Doc/engineering.html.  Added section
+|	   on CVS tagging conventions.  Added copyright to other docs.
+| 9/25/00 : beazley
+| 	   Modified the preprocessor so that macro names can start with a '%'.
+| 	   This may allow new SWIG "directives" to be defined as macros instead
+| 	   of having to be hard-coded into the parser.  
+|
+| *** Also a yet-to-be-documented quoting mechanism with backquotes
+| *** has been implemented?
+
+6/13/2001: mkoeppe
+	 * When configure does not find a language, don't use default
+	   paths like /usr/local/include; this only causes build
+	   problems.
+	 * New directory: Examples/Guile/test-suite, where a few
+	   bugs in 1.3a5 are demonstrated. 
+	 * Handle C++ methods that have both a "const" and a "throw"
+	   directive (see Examples/Guile/test-suite/cplusplus-throw.i); 
+	   thanks to Scott B. Drummonds for the report and the fix. 
+	 * Handle C++ pointer-reference arguments (like "int *& arg") 
+	   (see Examples/Guile/test-suite/pointer-reference.i,
+	   reported as SF bug #432224).
+	 * [Ruby] Fixed typo in rubydec.swg; thanks to Lyle Johnson!
+	 * Don't stop testing when one test fails.
+	 * [Guile, MzScheme] Don't print "Generating wrappers...".
+
+6/12/2001: mkoeppe
+	   [Guile] VECTORLENINPUT and LISTLENINPUT now have separate
+	   list length variables. TYPEMAP_POINTER_INPUT_OUTPUT
+	   attaches argument documentation involving SCM_TYPE to the
+	   standard pointer typemaps. INOUT is now an alias for BOTH.
+
+6/12/2001: cheetah (william fulton)
+	   Some Java documentation added.
+	   [Java] Fixed bugs in import pragma and shadow pragma. 
+
+6/12/2001: mkoeppe
+	   Fix declarations of SWIG_define_class
+	   (Lib/ruby/rubydec.swg) and SWIG_TypeQuery
+	   (Lib/common.swg). Thanks to Lyle Johnson
+	   <ljohnson@resgen.com> for the patches.
+
+6/11/2001: mkoeppe
+	   [Guile] Use long instead of scm_bits_t; this makes the
+	   generated wrapper code compatible with Guile 1.3.4
+	   again. Thanks to Masaki Fukushima for pointing this out.
+
+6/11/2001: cheetah (william fulton)
+	   The generic INSTALL file from autoconf added. Few changes to README file.
+
+6/11/2001: mkoeppe
+	   Fixed typo in Makefile.in; thanks to Greg Troxel
+	   <gdt@ir.bbn.com>. 
+
+6/08/2001: cheetah (william fulton)
+	   make check works again. Examples/GIFPlot configure generated by
+	   top level autoconf now.
+
+6/08/2001: mkoeppe
+	   Another build change: The new script autogen.sh runs
+	   autoconf in the appropriate directories.  The top-level
+	   configure also configures in Examples/GIFPlot.
+
+6/07/2001: mkoeppe
+	   Made the Makefile work with non-GNU make again.
+
+6/07/2001: cheetah (william fulton)
+	   [Java] Class/struct members that are arrays of pointers to classes/structs -
+	   Shadow class's get/set accessors now use Java classes instead of longs (pointers).
+	   [Java] Shadow classes will now clean up memory if function return type 
+	   is a class/struct.
+	   [Java] New example called reference based on the same example from other modules.
+
+6/06/2001: mkoeppe
+	   New configure option --with-release-suffix allows for
+	   attaching a suffix to the swig binary and the swig runtime
+	   libraries.  Minor changes to the build system.  "swig
+	   -swiglib" works again.  If invoked with the new option
+	   "-ldflags", SWIG prints a line of linker flags needed to
+	   link with the runtime library of the selected language
+	   module. 
+
+6/06/2001: mkoeppe
+	   [Guile] gswig_list_p is an int, not a SCM.  This typo
+	   caused warnings when compiling with a Guile configured with
+	   strict C type checking. In INPUT and BOTH typemaps
+	   generated by the SIMPLE_MAP macro, use the SCM_TO_C
+	   function to convert from Guile to C (rather than C_TO_SCM).
+	   Use scm_intprint to print pointers (rather than
+	   sprintf). Allow using "-linkage" instead of "-Linkage". 
+
+6/05/2001: cheetah (william fulton)
+	   [Java] Mods for using inherited c++ classes from Java
+	   [Java] New example called class based on the same example from other modules
+
+6/05/2001: cheetah (william fulton)
+	   [Java] destructor (_delete()) was not aware of %name renaming
+	   [Java] extends baseclass did not know about %name renaming
+	   [Java] extends baseclass did extend even when the baseclass was not known to swig
+	   [Java] sometimes enum-declarations occured before the Java class declaration
+	   [Java] unrelated enum initialisations no longer appear in Java class
+	   [Java] if module ends in '_' correct JNI names are now produced
+
+6/04/2001: cheetah (william fulton)
+	   [Java] Shadow class mods - Modified constructor replaces
+	   newInstance(). _delete() now thread safe. getCPtr() replaces
+	   _self. _selfClass() removed as now redundant. 
+          *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+	   [Java] Not all output java files had SWIG banner. New banner.
+
+	   [Java] Shadow class finalizers are output by default: Command
+	   line option -finalize deprecated and replaced with -nofinalize.
+          *** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
+
+6/ 1/2001: mkoeppe
+	   [Guile] Cast SCM_CAR() to scm_bits_t before shifting it.
+	   This is required for compiling with a Guile configured with
+	   strict C type checking.  
+
+6/ 1/2001: mkoeppe
+	   Added configure option "--with-swiglibdir".
+
+5/31/2001: mkoeppe
+	   [Guile] Support multiple parallel lists or vectors in
+	   the typemaps provided by list-vector.i.  New typemaps file,
+	   pointer-in-out.i. 
+
+5/25/2001: cheetah (william fulton)
+	   [Java] HTML update for examples.
+
+5/28/2001: mkoeppe
+	   Minor changes to the build system.  Added subdirectory for
+	   Debian package control files.
+
+5/28/2001: mkoeppe
+	   [Guile] Build a runtime library, libswigguile.
+
+5/28/2001: mkoeppe
+	   [Guile] New typemap substitution $*descriptor.  Use the {}
+	   syntax, rather than the "" syntax for the standard
+	   typemaps, in order to work around strange macro-expansion
+	   behavior of the SWIG preprocessor.  This introduces some
+	   extra braces.
+
+5/27/2001: mkoeppe
+	   [Guile] Handle pointer types with typemaps, rather than
+	   hard-coded. New typemap substitutions $descriptor,
+	   $basedescriptor; see documentation. Some clean-up in the
+	   variable/constants wrapper generator code.  New convenience
+	   macro SWIG_Guile_MustGetPtr, which allows getting pointers
+	   from smobs in a functional style.  New typemap file
+	   "list-vector.i", providing macros that define typemaps for
+	   converting between C arrays and Scheme lists and vectors.
+
+5/25/2001: cheetah (william fulton)
+	   [Java] STL string moved into its own typemap as it is c++ code and 
+	   it break any c code using the typemaps.i file.
+	   - Fixes for wrappers around global variables - applies to primitive 
+	   types and user types (class/struct) and pointers to these.
+	   - Structure member variables and class public member variables getters 
+	   and setters pass a pointer to the member as was in 1.3a3 and 1.1 
+	   (1.3a5 was passing by value)
+	   - Parameters that were arrays and return types were incorrectly 
+	   being passed to create_function() as pointers.
+	   - Fix for arrays of enums. 
+	   [Java] Updated java examples and added two more.
+	   [Java] Java module updated from SWIG1.3a3 including code cleanup etc.
+	   [Java] enum support added.
+	   [Java] Array support implemented
+	   [Java] Shadow classes improved - Java objects used rather than 
+	   longs holding the c pointer to the wrapped structure/c++class
+
+5/22/2001: mkoeppe
+	   [Guile] Fixed extern "C" declarations in C++ mode. Thanks
+	   to Greg Troxel <gdt@ir.bbn.com>.
+
+5/21/2001: mkoeppe
+	   [Guile] New linkage "module" for creating Guile modules for
+	   Guile versions >= 1.5.0. 
+
+4/18/2001: mkoeppe
+	   [MzScheme] Added typemaps for passing through Scheme_Object
+	   pointers. 
+
+4/9/2001 : mkoeppe 
+	   [MzScheme] Added typemaps for `bool'.  Inclusion of headers
+	   and support routines is now data-driven via mzscheme.i.
+	   Headers come from the new file mzschemdec.swg.  Don't abort
+	   immediately when a type-handling error is reported.  When
+	   searching for typemaps for enums, fall back to using int,
+	   like the Guile backend does.  Support char constants.  Emit
+	   correct wrapper code for variables.
+
+3/12/2001: mkoeppe
+	   [Guile] Fixed typemaps for char **OUTPUT, char **BOTH.
+
+3/2/2001 : mkoeppe 
+	   [Guile] Every wrapper function now gets a boolean variable
+	   gswig_list_p which indicates whether multiple values are
+	   present. The macros GUILE_APPEND_RESULT, GUILE_MAYBE_VALUES
+	   and GUILE_MAYBE_VECTOR use this variable, rather than
+	   checking whether the current return value is a list. This
+	   allows for typemaps returning a list as a single value (a
+	   list was erroneously converted into a vector or a
+	   multiple-value object in this case).
+
+3/1/2001 : mkoeppe
+	   [Guile] Added support for returning multiple values as
+	   vectors, or passing them to a muliple-value
+	   continuation. By default, multiple values still get
+	   returned as a list.
+
+3/1/2001 : mkoeppe
+	   [Guile] Added a "beforereturn" pragma. The value of this
+	   pragma is inserted just before every return statement.
+
+3/1/2001 : mkoeppe
+	   [Guile] Added support for Guile 1.4.1 procedure
+	   documentation formats, see internals.html.
+
+2/26/2001: mkoeppe
+	   [Guile] Made the wrapper code compile with C++ if the
+	   "-c++" command-line switch is given.  Thanks to
+	   <monkeyiq@dingoblue.net.au>. 
+
+2/26/2001: mkoeppe
+	   [Guile] Now two type tables, swig_types and
+	   swig_types_initial, are used, as all other SWIG language
+	   modules do.  This removes the need for the tricky
+	   construction used before that the broken Redhat 7.0 gcc
+	   doesn't parse. Reported by <monkeyiq@dingoblue.net.au>. 
+
+2/26/2001: mkoeppe
+	   [Guile] Fixed typemaps for char *OUTPUT, char *BOTH; a bad
+	   free() would be emitted.  Added typemap for SCM.
+
+
+Version 1.3 Alpha 5 
+===================
+
+9/19/00 : beazley
+          [Python] Python module generates more efficient code for
+          creating the return value of a wrapper function. Modification
+          suggested by Jon Travis.
+
+9/19/00 : beazley
+          Library files specified with the -l option are now included at the
+          end of the interface file (reverting to the old behavior).
+
+9/19/00 : beazley
+          Fixed some problems with enum handling.  enums are now manipulated as
+          'int', but cast into the enum type when values are passed to the 
+          corresponding C function.
+
+9/19/00 : mkoeppe
+	  [Guile] Removed "-with-smobs" command-line option, as this is the
+	  default now.  Added "-emit-setters" command-line option,
+	  which turns on generating procedures-with-setters; see
+	  internals.html.
+
+9/18/00 : mkoeppe
+	  Incorporated patch #101430, fixing bugs in the Guile module: 
+	  1. Some arguments were erroneously taken as *optional* arguments when
+	     ignored arguments were present. 
+	  2. Guile 1.3.4 was not supported since functions introduced in Guile
+	      1.4 were used.	  
+	  3. Added handling of `const char *'.
+
+9/17/00 : beazley
+          Fixed problem with failed assertion and large files.
+
+9/17/00 : beazley
+          Fixed problem with the '%' character appearing in added methods
+          and function bodies.  Preprocessor bug.
+
+Version 1.3 Alpha 4 (September 4, 2000)
+======================================
+
+9/3/00  : ttn
+          Added instructions for maintainers in Examples/README on how
+          to make examples also be useful in the testing framework.
+          Also, "make check" now uses ./Lib by via env var `SWIG_LIB'.
+          This is overridable like so:
+             make chk-swiglib=/my/experimental/swig/Lib check
+
+9/3/00  : beazley
+          Added $typemap variable to typemaps.  This gets replaced with
+          a string indicating the typemap that is applied.  Feature
+          request from rsalz.
+
+9/3/00  : beazley
+          Experimental optimization to code generation for virtual
+          member functions.  If you have two classes like this:
+
+                 class A() {
+                   virtual void foo();
+                 }
+
+                 class B() : public A {
+                   virtual void foo();
+                 }
+
+          Swig now will generate a single wrapper function for this
+
+                A_foo(A *a) {
+                    a->foo();
+                }
+
+          and use it as the implementation of both A_foo() and B_foo().
+          This optimization only takes place if both methods are declared
+          as virtual and both take identical parameters.
+          *** EXPERIMENTAL FEATURE ***
+
+9/3/00  : beazley
+          Restored the "memberin" typemap for setting structure members.
+          Unlike the old version, the new version is expanded inline in the
+          wrapper function allowing access to scripting language
+          internals (a sometimes requested feature). The "memberout" typemap
+          is gone. Use the "out" typemaps instead.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+9/3/00  : beazley
+          Attribute set methods no longer return the value of a member.
+          For example:
+
+               struct Foo {
+                    int x;
+                    ...
+               }
+
+          now gets set as follows:
+
+              void Foo_x_set(Foo *f, int x) {
+                    f->x = x;
+              }
+
+          In SWIG1.1 it used to be this:
+
+              int Foo_x_set(Foo *f, int x) {
+                   return (f->x = x);
+              }
+
+          This has been changed due to the complexity created by trying
+          to do this with more exotic datatypes such as arrays.  It also
+          complicates inlining and handling of the "memberin" typemap.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+9/2/00  : beazley
+          Removed the ptrcast() and ptrmap() functions from the
+          pointer.i library file.  Old implementation is incompatible
+          with new type system.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+9/2/00  : beazley
+          New runtime function SWIG_TypeQuery(const char *name) added.
+          This function can be used to extract the type info structure
+          that is used for type-checking.  It works with either the
+          nice C name or mangled version of a datatype.  For example:
+
+              swig_type_info *ty = Swig_TypeQuery("int *");
+              swig_type_info *ty = Swig_TypeQuery("_p_int");
+
+          This is an advanced feature that has been added to support some
+          exotic extension modules that need to directly manipulate
+          scripting language objects.
+          *** NEW FEATURE ***
+
+9/2/00  : beazley
+          New directive %types() added.  This is used to
+          explicitly list datatypes that should be included in
+          the runtime type-checking code. Normally it is never
+          necessary to use this but sometimes advanced extensions
+          (such as the pointer.i library) may need to manually
+          add types to the type-checker.
+          *** NEW FEATURE ***
+
+8/31/00 : beazley
+          Improved handling of string array variables. For example,
+          a global variable of the form "char name[64]" is automatically
+          managed as a 64 character string.  Previously this didn't
+          work at all or required the use of a special typemap.
+          *** NEW FEATURE (Tcl, Perl, Python) ***
+
+8/31/00 : ttn
+	  Added Makefile target `check-c++-examples', which uses new
+	  files under Examples/C++ contributed by Tal Shalif.  Now "make
+	  check" also does "make check-c++-examples".  Also, expanded
+	  actions in `check-gifplot-example' and `check-aliveness'.
+
+8/30/00 : mkoeppe
+	  Major clean-up in the Guile module. Added typemap-driven
+	  documentation system. Changed to handle more than 10
+	  args. Updated and extended examples.
+	  *** NEW FEATURE ***
+
+8/29/00 : beazley
+          Added new %insert directive that inserts the contents of a file
+          into a portion of the output wrapper file.  This is only intended
+          for use by writers of language modules.  Works as follows:
+
+               %insert(headers)  "file.swg";
+               %insert(runtime)  "file.swg";
+               %insert(wrappers) "file.swg";
+               %insert(init)     "file.swg";
+
+          *** NEW FEATURE ***
+
+8/29/00 : beazley
+          Added new %runtime directive which includes code into the runtime
+          portion of the wrapper code. For example:
+
+              %runtime %{
+                    ... some internal runtime code ...
+              %}
+
+          There is no practical reason for ordinary users to use this
+          feature (almost everything can be done using %{ ... %}
+          instead).   However, writers of language modules may want to
+          use this in language configuration files.
+          *** NEW FEATURE ***
+
+8/28/00 : beazley
+          Typemaps can now be specified using string literals like
+          this:
+
+              %typemap(in) int "$target = SvIV($source);";
+
+          When code is specified like this, it is *NOT* enclosed
+          inside a local scope (as with older typemap declarations).
+          Note: character escape sequences are interpreted in the
+          code string so if you want to include a quote or some
+          other special character, make sure you use a (\).
+          *** NEW FEATURE ***
+
+8/27/00 : beazley
+          Typemaps have been modified to follow typedef declarations.
+          For example, if you have this:
+
+              typedef int Number;
+
+              %typemap(in) int {
+                      ... get an integer ...
+              }
+
+              void foo(Number a);
+
+          The typemap for 'int' will be applied to the argument 'Number a'.
+          Of course, if you specify a typemap for 'Number' it will take
+          precedence (nor will it ever be applied to an 'int').
+          *** POTENTIAL INCOMPATIBILITY ***
+
+8/27/00 : beazley
+          Default typemap specification has changed.   In older
+          versions of swig, you could do this:
+
+               %typemap(in) int SWIG_DEFAULT_TYPE {
+                   ...
+               }
+
+          To specify the default handling of a datatype.   Now that
+          SWIG follows typedef declarations, this is unnecessary.
+          Simply specifying a typemap for 'int' will work for all
+          variations of integers that are typedef'd to 'int'.
+
+          Caveat, specifying the default behavior for pointers,
+          references, arrays, and user defined types is a little
+          different.  This must be done as follows:
+
+               %typemap() SWIGPOINTER * {
+                      ... a pointer ...
+               }
+               %typemap() SWIGREFERENCE & {
+                      ... a reference ...
+               }
+               %typemap() SWIGARRAY [] {
+                      ... an array ...
+               }
+               %typemap() SWIGTYPE {
+                      ... a user-defined type (by value) ...
+               }
+          *** POTENTIAL INCOMPATIBILITY ***
+
+8/15/00 : dustin
+          The file swig-1.3a1-1.spec has been added to the Tools directory.
+          It can be used to build a redhat package for SWIG, although it
+          will need to be updated for the next public release.
+
+8/15/00 : beazley
+          Typemaps have been completely rewritten.  Eventually they may be
+          replaced with something better, but for now they stay.  However,
+          there are a number of a significant changes that may trip some
+          people up:
+
+          1.  Typemap scoping is currently broken.  Because of this, the
+              following code won't work.
+
+              %typemap(in) blah * {
+                   ...
+              }
+              class Foo {
+                   ...
+                   int bar(blah *x);
+              }
+              %typemap(in) blah *;   /* Clear typemap */
+
+              (this breaks because the code for the class Foo is actually
+              generated after the entire interface file has been processed).
+              This is only a temporary bug.
+
+          2.  In SWIG1.1, the %apply directive worked by performing a
+              very complex type-aliasing procedure.  From this point on,
+              %apply is simply a generalized typemap copy operation.
+              For example,
+
+                  %apply double *OUTPUT { double *x, double *y };
+
+              Copies *ALL* currently defined typemaps for 'double *OUTPUT' and
+              copies them to 'double *x' and 'double *y'.
+
+              Most people probably won't even notice this change in
+              %apply.  However, where it will break things is in code like
+              this:
+
+                  %apply double *OUTPUT { double *x };
+                  %typemap(in) double *OUTPUT {
+                       ... whatever ...
+                  }
+
+                  void foo(double *x);
+
+              In SWIG1.1, you will find that 'foo' uses the 'double *OUTPUT' rule
+              even though it was defined after the %apply directive (this is
+              the weird aliasing scheme at work).  In SWIG1.3 and later,
+              the 'double *OUTPUT' rule is ignored because it is defined
+              after the %apply directive.
+
+          3.  The %clear directive has been modified to erase all currently
+              defined typemaps for a particular type.  This differs from
+              SWIG1.1 where %clear only removed rules that were added using
+              the %apply directive.
+
+          4.  Typemap matching is now performed using *exact* types.
+              This means that things like this
+
+                   %typemap(in) char * { }
+                   %typemap(in) const char * { }
+
+              are different typemaps.    A similar rule applies for pointers,
+              arrays, and references.  For example:
+
+                   %typemap(in) double * { }
+
+              used to apply to 'double &', 'double []',  Now, it only applies
+              to 'double *'.  If you want a 'double &', you'll need to handle
+              that separately.
+
+          5.  Array matching has been simplfied.  In SWIG1.1, array matching
+              was performed by trying various combinations of dimensions.
+              For example, 'double a[10][20]' was matched as follows:
+
+                   double [10][20]
+                   double [ANY][20]
+                   double [10][ANY]
+                   double [ANY][ANY]
+
+              In SWIG1.3, only the following matches are attempted:
+
+                   double [10][20]
+                   double [ANY][ANY]
+
+          On the positive side, typemap matching is now *significantly* faster
+          than before.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+8/15/00 : beazley
+          Secret developer feature.  Since datatypes are now represented as 
+          strings internally, you can bypass limitations of the parser and
+          create a wild datatype by simply enclosing the raw string encoding
+          in backticks (``) and sticking it in the interface file anywhere a
+          type is expected.  For example, `a(20).a(10).p.f(int,int)`.  This 
+          feature is only intended for testing (i.e., you want to see what
+          happens to your language module if it gets a reference to a pointer
+          to an array of pointers to functions or something). 
+          *** SICK HACK ***
+
+8/14/00 : beazley
+          Completely new type-system added to the implementation.
+          More details later.
+
+8/11/00 : beazley
+          Cleaned up some of the I/O handling.  SWIG no longer generates
+          any temporary files such as _wrap.wrap, _wrap.ii, _wrap.init.
+          Instead, these "files" are kept around in memory as strings
+          (although this is transparent to language modules).
+
+8/4/00  : ttn
+	  Added Makefile target "check" and variants.
+	  This can be used like "make check" or, to explicitly skip a
+	  language LANG: "make skip-LANG=true check".  LANG is skipped
+	  automatically if ./configure determines that LANG support is
+	  insufficient.
+
+	  Currently, the check is limited to doing the equivalent of
+	  "make all" in some of the Examples directories.  This should
+	  be expanded both horizontally (different types of tests) and
+	  vertically (after "make all" in an Examples subdir succeeds,
+	  do some additional tests with the resulting interpreter, etc).
+
+8/4/00  : ttn
+	  Added Makefile target "distclean", which deletes all the
+	  files ./configure creates, including config.status and friends.
+
+8/3/00  : harcoh
+	  java changes??? [todo: document changes]
+
+7/23/00 : beazley
+          Typemaps have been modified to key off of the real datatypes
+          used in the interface file.  This means that typemaps for
+          "const char *" and "char *" will be difference as will typemaps
+          for "Vector" and "Vector *."
+          *** POTENTIAL INCOMPATIBILITY ***
+          This is likely to break interfaces that rely on the odd type
+          handling behavior of typemaps in SWIG1.1--especially with
+          respect to interfaces involving pass-by-value.
+
+7/23/00 : beazley
+          New %constant directive.  This directive can be used to
+          create true constants in the target scripting language.
+          It's most simple form is something like this:
+
+             %constant FOO 42;
+
+          In this case, the type is inferred from the syntax of the
+          value (in reality, all #define macros are translated into
+          directives of this form).
+
+          An expanded version is as follows:
+
+            %constant(Foo *) FOO = &FooObj;
+
+          In this case, an explicit type can be specified.  This
+          latter form may be useful for creating constants that
+          used to be specified as
+
+             const Foo *FOO = &FooObj;
+
+          (which are now treated as variables).
+          *** EXPERIMENTAL FEATURE *** The syntax may change in
+          the final release.
+
+7/23/00 : beazley
+          Modified the parser so that variable declarations of the form
+          "const type *a" are handled as variables, not constants.
+          Note: SWIG1.1 handled this case erroneously because
+          const char *a is a pointer variable that can be reassigned.
+          *** POTENTIAL INCOMPATIBILITY ***
+          Note: just because this is the "right" way to do things,
+          doesn't mean it's the most appropriate interpretation.
+          I suspect that many C programmers might use 'const char *'
+          with the intent of creating a constant, without realizing
+          that they've created a reassignable global variable.
+
+7/23/00 : beazley
+          The C/C++ wrapping layer has been completely redesigned and
+          reimplemented.  This change should iron out a few rough
+          spots with the handling of datatypes.  In addition, the
+          wrapper code is somewhat cleaner.
+          *** POTENTIAL INCOMPATIBILITY ***
+          This change may break interfaces that involve
+          subtle corner-cases with typemaps and the %addmethods
+          directive since some of these features had somewhat
+          type handling behavior in SWIG1.1.
+
+7/23/00 : beazley
+          The "memberin" and "memberout" typemaps are gone for the
+          moment, but they might return as soon as I figure out
+          how to integrate them with some of the streamlined C wrapper
+          functions.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+7/22/00 : beazley
+          A variety of old type handling functions such as print_type(),
+          print_full(), print_mangle(), etc... are gone and have been
+          replaced with a smaller set of functions.  See the file
+          Doc/internals.html for details.  This will break all third
+          party language modules.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+7/20/00 : beazley
+          Deprecated the %val and %out directives.  These directives
+          shouldn't really be necessary since typemaps can be used
+          to achieve similar results.   This also cleans up the
+          handling of types and parameters quite a bit.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+7/20/00 : ttn
+	  Fixed unspecified-module bug in Guile support and removed
+	  more non-"with-smobs" functionality using patches submitted
+	  by Matthias Koeppe.
+
+	  Re-enable recognition of "-with-smobs" (with no effect since
+	  we use smobs by default now) for the time being.  After the
+	  1.3a4 release, this option will signal an error.
+
+7/17/00 : ttn
+	  Fixed NULL-input bug in parameter list handling.
+	  Reported by Matthias Koeppe.
+
+7/12/00 : beazley
+          Fixed memory leak in Python type-checking code. Reported by
+          Keith Davidson.  Bug #109379.
+
+7/10/00 : beazley
+          Changed internal data structures related to function parameters.
+
+7/10/00 : beazley
+          Fixed some bugs related to the handling of the %name() directive
+          and classes in the Tcl module. Problem reported by James Bailey.
+
+7/10/00 : beazley
+          Fixed parsing and enum handling problems with character constants.
+          Reported by Greg Kochanski.
+
+7/10/00 : beazley
+          Removed WrapperFunction class from the core and updated the language
+          module.  This will break third party modules.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+7/9/00  : beazley
+          Implementation of SWIG no longer makes use of C++ operator overloading.
+          This will almost certainly break *all* third party language modules
+          that are not part of the main SWIG CVS tree. Sorry.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+7/8/00  : beazley
+          Removed the experimental and undocumented "build" typemap that
+          was intended to work with multiple arguments. Simply too weird
+          to keep around.  Besides, a better replacement is in the works.
+
+7/6/00  : ttn
+          Removed non-"with-smobs" functionality (Guile support), i.e.,
+          "-with-smobs" is now the default and no longer needs to be
+	  specified on the command-line.
+
+7/5/00  : ttn
+          Incorporated Ruby support contributed by Masaki Fukushima.
+
+6/28/00 : ttn
+          Applied more-than-10-args bugfix patch contributed
+	  by Matthias Koeppe.
+
+6/27/00 : beazley
+          Rewrote some of the string handling and eliminated the C++
+          implementation (which is now just a wrapper).
+
+6/27/00 : ttn
+          Added Doc/index.html and Doc/internals.html.  The target
+          audience for the latter is new SWIG developers.
+
+
+Version 1.3 Alpha 3 (June 18, 2000)
+===================================
+
+6/18/00 : beazley
+          Removed the naming.cxx, hash.cxx, and symbol.cxx files from
+          the SWIG1.1 directory.   Continued to migrate things away
+          from the C++ base (although there's still a lot of work to do).
+
+6/17/00 : beazley
+          Added a few more examples to the Examples directory.  Still
+          need to do a lot of work on this.
+
+6/16/00 : beazley
+          Added -includeall to follow all #include statements in the
+          preprocessor.
+
+6/15/00 : beazley
+          Tried to fix as many C++ warnings as possible when compiling
+          with the Sun Workshop C++ compiler.  Unfortunately, this means
+          that there are a lot of statements that contain string literals
+          of the form (char*)"Blah".
+
+6/15/00:  beazley
+          A variety of cleanup and performance optimization in the
+          low-level DOH library.   This seems to result in a speedup
+          of 50-100% for preprocessing and other related tasks.
+
+5/10/00 : ttn
+	  Applied variable-wrapping bugfix patch contributed
+	  by Matthias Koeppe.
+
+4/17/00 : ttn
+	  Updated MzScheme support contributed by Oleg Tolmatcev.
+	  We now use a `Scheme_Type'-based structure to wrap pointers.
+
+4/11/00 : ttn
+	  Incorporated further Guile-support patch by Matthias Koeppe.
+	  Typemaps previously deleted have been re-added.  There is now
+	  exception handling (see Doc/engineering.html).  `SWIG_init' is now
+	  declared extern only for simple linkage.  Some bugs were fixed.
+
+4/06/00 : ttn
+	  Incorporated MzScheme support contributed by Oleg Tolmatcev.
+	  This includes new directories Lib/mzscheme and Examples/mzscheme.
+
+4/03/00 : ttn
+	  Added Examples/guile and children.  This is an adaptation of
+	  the same-named directory from the SWIG-1.1p5 distribution.
+	  Added Guile-specific section to Doc/engineering.html.
+
+4/02/00 : ttn
+	  Incorporated new guilemain.i by Martin Froehlich.
+	  Incorporated Guile-support rewrite patch by Matthias Koeppe.
+	  The command line option "-with-smobs" enables implementation of
+	  pointer type handling using smobs, the canonical mechanism for
+	  defining new types in Guile.  Previous implementation (using
+	  strings) is at the moment still supported but deprecated.  At
+	  some point, "-with-smobs" will be the default and no longer
+	  required.
+
+3/13/00 : beazley
+          Added purify patches submitted by Ram Bhamidipaty.
+
+3/02/00 : ttn
+          Added support for different Guile "linkage" schemes.
+	  Currently, "-Linkage hobbit" works.
+
+
+Version 1.3 Alpha 2 (March 1, 2000)
+===================================
+
+2/29/00 : beazley
+          Made SWIG ignore the 'mutable' keyword.
+
+2/29/00 : beazley
+          Incorporated some patches to the Perl5 module related to
+          the -hide option and the destruction of objects.
+          Patch submitted by Karl Forner.
+
+2/27/00 : ttn
+	  Incorporated Guile support contributed by Matthias Koeppe.
+	  This includes a cpp macro in Lib/guile/guile.swg and the
+	  entire file Lib/guile/typemaps.i.
+
+2/25/00 : ttn
+	  Modified configure.in and Makefile.in files to support
+	  non-local build (useful in multi-arch environments).
+
+2/24/00 : ttn
+	  Incorporated Guile support contributed by Clark McGrew.
+	  This works with Guile 1.3, but since it depends heavily
+	  on the gh_ interface, it should work for all later versions.
+	  It has not been tested with versions before 1.3.
+	  WARNING: Code is unstable due to experimentation by ttn.
+
+2/16/00 : beazley
+          A variety of performance improvements to the Python shadow
+          class code generation.  Many of these result in substantial
+          runtime performance gains.  However, these have come at
+          a cost of requiring the use of Python 1.5.2.  For older
+          versions, use 'swig -noopt -python' to turn off these
+          optimization features.
+
+Version 1.3 Alpha 1 (February 11, 2000)
+=======================================
+
+2/11/00 : Added 'void' to prototype of Python module initializer.
+          Reported by Mark Howson (1/20/00).
+
+2/11/00 : beazley
+          Modified the Python shadow class code to discard ownership of an
+          object whenever it is assigned to a member of another object.
+          This problem has been around for awhile, but was most recently
+          reported by Burkhard Kloss (12/30/99).
+
+2/11/00 : beazley
+          Added braces around macros in the exception.i library.  Reported
+          by Buck Hodges (12/19/99)
+
+2/11/00 : beazley
+          Fixed bug in the constraints.i library. Reported by Buck
+          Hodges (12/14/99)
+
+2/11/00 : beazley
+          The %native directive now generates Tcl8 object-style command calls.
+          A full solution for Tcl7 and Tcl8 is still needed. Patch suggested
+          by Mike Weiblen (11/29/99)
+
+2/11/00 : beazley
+          Modified the typemap code to include the $ndim variable for arrays.
+          Patch provided by Michel Sanner (11/12/99).
+
+2/11/00 : beazley
+          Modified the Python module to raise a Runtime error if an attempt
+          is made to set a read-only member of a shadow class.  Reported by
+          Michel Sanner (11/5/99).
+
+2/10/00 : The documentation system has been removed. However, it is likely
+          to return at some point in the future.
+
+2/1/00  : Added a number of performance enhancements to the Python shadow
+          classing and type-checking code.  Contributed by Vadim Chugunov.
+
+          1. Remove _kwargs argument from the shadow wrappers when -keyword
+             option is not specified. This saves us a construction of keyword
+             dictionary on each method call.
+
+             def method1(self, *_args, **_kwargs):
+                 val = apply(test2c.PyClass1_method1, (self,) + _args, _kwargs)
+                 return val
+
+             becomes
+
+             def method1(self, *_args):
+                 val = apply(test2c.PyClass1_method1, (self,) + _args)
+                 return val
+
+          2. Incorporate self into the _args tuple.  This saves at least one tuple
+             allocation per method call.
+
+             def method1(self, *_args):
+                 val = apply(test2c.PyClass1_method1, (self,) + _args)
+                 return val
+
+             becomes
+
+             def method1(*_args):
+                 val = apply(test2c.PyClass1_method1, _args)
+                 return val
+
+          3. Remove *Ptr classes.
+             Assume that we are SWIGging a c++ class CppClass.
+             Currently SWIG will generate both CppClassPtr class
+             that hosts all methods and also CppClass that is derived
+             from the former and contains just the constructor.
+             When CppClass method is called, the interpreter will try
+             to find it in the CppClass's dictionary first, and only then
+             check the base class.
+
+             CppClassPtr functionality may be emulated with:
+
+             import new
+             _new_instance = new.instance
+             def CppClassPtr(this):
+                  return _new_instance(CppClass, {"this":this,"thisown":0})
+
+             This saves us one dictionary lookup per call.
+
+             <DB>The new module was first added in Python-1.5.2 so it
+             won't work with older versions.  I've implemented an
+             alternative that achieves the same thing</DB>
+
+          4. Use CObjects instead of strings for pointers.
+
+          Dave: This enhancements result in speedups of up to 50% in some
+          of the preliminary tests I ran.
+
+2/1/00  : Upgraded the Python module to use a new type-checking scheme that
+          is more memory efficient, provides better performance, and
+          is less error prone. Unfortunately, it will break all code that
+          depends on the SWIG_GetPtr() function call in typemaps.
+          These functions should be changed as follows:
+
+                if (SWIG_GetPtr(string,&ptr,"_Foo_p")) {
+                    return NULL;
+                }
+
+          becomes
+
+                if (SWIG_ConvertPtr(pyobj, &ptr, SWIG_TYPE_Foo_p) == -1) {
+                    return NULL;
+                }
+
+          Note: In the new implementation SWIG_TYPE_Foo_p is no longer
+          a type-signature string, but rather an index into a type
+          encoding table that contains type information.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+1/30/00 : loic
+	  Conditionaly compile experimental code with --enable-experiment
+	  configure flag.
+	  Fix .cvsignore to ignore configrue & yacc generated files
+
+1/28/00 : loic
+	  Apply automake everywhere
+	  Keep configure scripts so that people are not *forced* to autoconf
+          Keep sources generated by yacc so that compilation without yacc
+	  is possible.
+	  Source/LParse/cscanner.c: change lyacc.h into parser.h to please
+	  default yacc generation rules.
+	  Use AC_CONFIG_SUBDIRS in configure.in instead of hand made script.
+	  Update all relevant .cvsignore to include .deps
+	  Fixed missing ; line 136 Source/Swig/swig.h
+
+1/13/00 : beazley
+          Fixed a number of minor end-of-file parsing problems in the
+          preprocessor.
+
+1/13/00 : beazley
+          Added -freeze option that forces SWIG to freeze upon exit.
+          This is only used as a debugging tool so that I can more
+          easily examine SWIG's memory footprint.
+
+1/13/00 : beazley
+          Added patch to guile module for supporting optional arguments
+          Patch contributed by Dieter Baron.
+
+1/13/00 : loic
+	  Added .cvsignore, Examples/.cvsignore, Source/DOH/Doh/.cvsignore
+	  Source/SWIG1.1/main.cxx: Fixed -I handling bug
+	  Source/Modules1.1/java.cxx: fixed char* -> const char* warnings that are
+	  errors when compiling with gcc-2.95.2
+	  Source/SWIG1.1/main.cxx: cast const char* to char* for String_replace
+	  token and rep should really be const.
+
+1/12/00 : beazley
+          Added Harco's Java modules.
+
+1/12/00 : beazley
+          Revoked the %ifdef, %ifndef, %endif, %if, %elif, and %else
+          directives.  These are no longer needed as SWIG now has a real
+          preprocessor.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+1/12/00 : beazley
+          Moved the documentation modules from the SWIG directory
+          to the Modules directory (where they really should have been
+          to begin with).
+
+1/12/00 : beazley
+          Removed the -stat option for printing statistics. The
+          statistics reporting was inadequate and mostly broken
+          anyway.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+1/12/00 : beazley
+          Removed the -t option for reading a typemap file.  More
+          trouble than it's worth.  Just include typemaps at the top
+          of the interface file.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+1/12/00 : beazley
+          Removed the %checkout directive.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+1/12/00 : beazley
+          Removed the -ci option for file checkin.   Too problematic
+          to implement.  Probably better to just put your SWIG library
+          under CVS instead.
+          *** POTENTIAL INCOMPATIBILITY ***.
+
+1/11/00 : beazley
+          Deleted the LATEX module.  Sorry... Didn't know anyone
+          who was using it.  Besides, I'm looking to simplify
+          the documentation system.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+1/11/00 : beazley
+          Modified the ASCII documentation module to use a .txt
+          suffix for its output file instead of .doc.
+
+1/11/00 : beazley
+          Added the long-lost SWIG preprocessor back to the system.
+          It should be enabled by default.  Raw preprocessed output
+          can be viewed using swig -E file.i.
+          *** NEW FEATURE ***
+
+1/11/00 : beazley and djmitche
+          Completely reorganized the SWIG directory structure.  The
+          basic organization is now:
+
+                Source/         SWIG source code
+                Lib/            SWIG library files (swig_lib)
+                Doc/            Documentation
+                Examples/       Examples
+
+          More directories will be added as needed.
+
+12/08/99: Loic Dachary (loic@senga.org)
+	  Enhanced package handling for perl5 and c++.
+
+	  With new option -hide Foo::Bar, every perl5 object (Frob) is
+	  qualified by Foo::Bar::Frob. The package name is solely used
+	  to encapsulate C/C++ wrappers output in <module>_wrap.c and the
+	  corresponding perl package in <module>.pm. Note that a package
+	  name may contain :: (Frob::Nitz) and will be relative to the
+	  package name provided by -hide (Foo::Bar::Frob::Nitz).
+
+	  In *_wrap.c, SWIG_init macro is used. Was previously defined
+	  but not used and simplifies code.
+
+	  Added typemap(perl5,perl5in) and typemap(perl5,perl5out) that
+	  do the equivalent of typemap(perl5,in) and typemap(perl5,out)
+	  but contain perl code and applies to wrappers generated by
+	  -shadow.
+
+	  Lacking proper regression tests I used
+	  Examples/perl5/{c++,constraint,defarg,except,
+	  graph/graph[1234],multinherit,nested,shadow,simple,tree,
+	  typemaps/{argv,argv2,arraymember,database,file,ignore,integer,
+	  output,passref,reference,return}}/. I ran swig with and without
+	  the patches, diff the generatedsources, run the .pl files
+	  and checked that the results are identical. In all those examples
+	  I had no error.
+
+11/21/99: Modified the Tcl module to provide full variable linking capabilities
+          to all datatypes.   In previous versions, a pair of accessor functions
+          were created for datatypes incompatible with the Tcl_LinkVar() function.
+          Now, we simply use variable traces to support everything. This may
+          break scripts that rely upon the older behavior.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+11/21/99: Added slight tweak to wrapper generator to collect local variables
+          of similar type.  Produces somewhat more compact wrapper code.
+
+11/20/99: Modified the Tcl module to use SWIG_GetArgs() to parse
+          arguments.    This is a technique borrowed from Python in which
+          arguments are converted using a format string convention similiar
+          to fprintf().   This results in a *substantial* reduction in the
+          size of the resulting wrapper code with only a modest runtime overhead
+          in going through the extra conversion function.
+
+11/13/99: Completely rewrote the class/structure generation code for the
+          Tcl module.  Now, a small set of runtime functions are used
+          to implement the functionality for all classes (instead of a
+          massive amount of runtime code being generated for each class).
+          Class specific information is simply encoded in a series of
+          static tables.   This results in a *HUGE* reduction in wrapper
+          code size--especially for C++.
+
+11/13/99: Removed the -tcl (Tcl 7.x) module.  Tcl 8.0 is now several
+          years old and the defacto standard--no real reason to keep
+          supporting the old version at this point.
+
+11/13/99: Cleaned up -c option for Python module.  The pyexp.swg file
+          is now gone.
+
+11/13/99: Fixed external declarations to work better with static linking
+          on Windows.  Static linking should now be possible by defining
+          the -DSTATIC_LINK option on the command line.  Patch contributed
+          by Alberto Fonseca.
+
+11/5/99 : Fixed an obscure code generation bug related to the generation
+          of default constructors.   Bug reported by Brad Clements.
+
+11/5/99 : Fixed a few memory problems found by purify.
+
+11/5/99 : Officially deprecated the -htcl, -htk, and -plugin options
+          from the Tcl and Tcl8 modules.
+
+10/26/99: Removed unused variable from python/typemaps.i.  Patch
+          contributed by Keith Davidson.
+
+8/16/99 : Added _WIN32 symbol to libraries to better support Windows.
+
+8/16/99 : Deprecated the Perl4 module.   It is no longer included in the
+          distribution and no longer supported.  In the entire 3 years SWIG
+          has been around I never received a single comment about it so I'm
+          assuming no one will miss it...
+
+8/16/99 : Modified the type-checking code to register type mappings using a
+          table instead of repeated calls to SWIG_RegisterMapping().  This
+          reduces the size of the module initialization function somewhat.
+
+8/15/99 : Cleaned up the pointer type-checking code in the Tcl module.
+
+8/15/99 : Many changes to the libraries to support runtime libraries.
+
+8/13/99 : Eliminated C++ compiler warning messages about extern "C" linkage.
+
+8/13/99 : Some cleanup of Python .swg files to better support runtime libraries
+          on Windows.
+
+8/13/99 : Modified the %pragma directive to attach pragmas declared inside
+          a class definition to the class itself. For example:
+
+               class foo {
+                    ...
+                    %pragma(python) addtomethod = "insert:print `hello world'"
+                    ...
+               }
+
+          Most people don't need to worry about how this works.  For people
+          writing backend modules, class-based pragmas work like this:
+
+              lang->cpp_open_class()             // Open a class
+              lang->cpp_pragma()                 // Supply pragmas
+              ...                                // Emit members
+
+              lang->cpp_close_class()            // Close the class
+
+          All of the pragmas are passed first since they might be used to
+          affect the code generation of other members.   Please see
+          the Python module for an example.   Patches contributed
+          by Robin Dunn.
+
+8/13/99 : Patch to Python shadow classes to eliminate ignored
+          exception errors in destructors.  Patch contributed
+          by Robin Dunn.
+
+8/11/99 : Minor patch to swig_lib/python/swigptr.swg  (added SWIGSTATIC
+          declaration).  Patch contributed by Lyle Johnson.
+
+8/11/99 : Added FIRSTKEY/NEXTKEY methods to Perl5 shadow classes
+          Patch contributed by Dennis Marsa.
+
+8/11/99 : Modified Python module so that NULL pointers are returned
+          and passed as 'None.'  Patch contributed by Tal Shalif.
+
+8/10/99 : Fixed missing 'int' specifiers in various places.
+
+8/10/99 : Added Windows makefile for Runtime libraries.  Contributed
+          by Bob Techentin.
+
+8/10/99 : Fixed minor problem in Python runtime makefile introduced
+          by keyword arguments.
+
+8/8/99  : Changed $target of perl5(out) typemap from ST(0) to
+          ST(argvi).  Patch contributed by Geoffrey Hort.
+
+8/8/99  : Fixed bug in typemap checking related to the ANY keyword
+          in arrays and ignored arguments.  Error reported by
+          Geoffrey Hort.
+
+8/8/99  : %enabledoc and %disabledoc directives can now be used
+          inside class/structure definitions.   However, no check
+          is made to see if they are balanced (i.e., a %disabledoc
+          directive inside a class does not have to have a matching
+          %enabledoc in the same class).
+
+8/8/99  : Keyword argument handling is now supported in the Python
+          module.   For example:
+
+               int foo(char *bar, int spam, double x);
+
+          Can be called from Python as
+
+               foo(x = 3.4, bar="hello", spam=42)
+
+          To enable this feature, run SWIG with the '-keyword' command
+          line option.    Mixing keyword and default arguments
+          should work as well.   Unnamed arguments are assigned names
+          such as "arg1", "arg2", etc...
+
+          *** POTENTIAL INCOMPATIBILITY ***
+          Functions with duplicate argument names such as
+          bar(int *OUTPUT, int *OUTPUT) will likely cause problematic
+          wrapper code to be generated.   To fix this,  use different
+          names or use %apply to map typemaps to alternate names.
+
+8/8/99  : Handling of the 'this' pointer has been changed in Python shadow
+          classes.  Previously, dereferencing of '.this' occured in the
+          Python shadow class itself.   Now, this step occurs in the C
+          wrappers using the following function:
+
+                SWIG_GetPtrObj(PyObject *, void **ptr, char *type)
+
+          This function can accept either a string containing a pointer
+          or a shadow class instance with a '.this' attribute of
+          appropriate type.  This change allows the following:
+
+          1.  The real shadow class instance for an object is
+              passed to the C wrappers where it can be examined/modified
+              by typemaps.
+
+          2.  Handling of default/keyword arguments is now greatly
+              simplified.
+
+          3.  The Python wrapper code is much more simple.
+
+          Plus, it eliminated more than 300 lines of C++ code in the
+          Python module.
+
+          *** CAVEAT : This requires the abstract object interface.
+          It should work with Python 1.4, but probably nothing older
+          than that.
+
+
+8/8/99  : Fixed handling of "const" and pointers in classes.  In particular,
+          declarations such as
+
+           class foo {
+             ...
+             const char *msg;
+             const int  *iptr;
+          }
+
+          are handled as assignable variables as opposed to constant
+          values (this is the correct behavior in C/C++).   Note:
+          declarations such as "char *const msg" are still unsupported.
+          Constants declared at the global level using const are also
+          broken (because I have a number of interfaces that rely upon
+          this behavior).
+
+          *** POTENTIAL INCOMPATIBILITY ***  This may break interfaces that
+          mistakenly treat 'const char *' types as constant values.
+
+8/8/99  : Modified the parser to support bit-fields.    For example:
+
+          typedef struct {
+              unsigned int is_keyword : 1;
+              unsigned int is_extern  : 1;
+              unsigned int is_static  : 1;
+          } flags;
+
+          Bit-fields can only be applied to integer types and their
+          are other restrictions.  SWIG performs no such type-checking
+          (although the C compiler will catch problems when it tries to
+          compile the wrapper code).
+
+8/8/99  : Removed trailing space of $basetype substitution in typemaps.
+          This is to allow things like this:
+
+          %typemap(python, argout) spam** OUTPUT{
+              ...
+              char* a = "$basetype_p";
+              ...
+          }
+
+          (Patch suggested by Nathan Dunfield).
+
+6/22/99 : Made a very slight tweak to the Perl5 shadow class
+          code that allows typemaps to alter the return type
+          of objects (to support polymorphic types).  Patch
+          contributed by Drake Diedrich.
+
+4/8/99  : Fixed null pointer handling bug in Perl module.
+          Patch contributed by Junio Hamano.
+
+3/17/99 : Fixed bug in perl5ptr.swg for ActiveState Perl.
+          Patch contributed by Greg Anderson.
+
+2/27/99 : Eliminated segmentation fault when Swig runs on
+          empty files.
+
+2/27/99 : Added patch to Guile module to eliminate unused
+          variables.   Contributed by Mike Simons.
+
+2/27/99 : Fixed problem with %addmethods returning references.
+
+2/27/99 : Fixed Runtime/Makefile. Patch contributed by
+          Mike Romberg.
+
+2/27/99 : Incorporated patches to the type-checker.
+
+2/27/99 : Fixed problem with -exportall switch and shadow classes
+          in Perl5 module.  Patch contributed by Dennis Marsa.
+
+2/27/99 : Modified Perl5 module to recognize 'undef' as a NULL char *.
+          Patch contributed by Junio Hamano.
+
+2/27/99 : Fixed the Perl5 module to support the newer versions of
+          ActiveState Perl for Win32.
+
+2/27/99 : Fixed the include order of files specified with the
+          -I option.
+
+2/5/98- : Dave finishes his dissertation, goes job hunting, moves to
+2/5/99    Chicago and generally thrashes about.
+
+Version 1.1 Patch 5 (February 5, 1998)
+======================================
+2/4/98  : Fixed a bug in the configure script when different package
+          locations are specified (--with-tclincl, etc...).
+
+2/2/98  : Fixed name-clash bug related to the switch to C macros for accessor
+          functions.  The new scheme did not work correctly for objects
+          with members such as 'obj', 'val', etc...   Fixed the bug by
+          appending the word 'swig' to macro argument names.  Patch
+          contributed by Rudy Albachten.
+
+2/2/98  : Slight fix to the Perl5 module to eliminate warning messages
+          about 'varname used only once : possible typo'.  Fix
+          contributed by Rudy Albachten.
+
+1/9/98  : Fixed a bug in the Perl 5 module related to the creation of
+          constants and shadow classes.
+
+1/9/98  : Fixed linking bug with Python 1.5 embed.i library file.
+
+Version 1.1 Patch 4 (January 4, 1998)
+=====================================
+
+1/4/98  : Changed structured of the Examples directory to be more friendly
+          to Borland C++.
+
+1/4/98  : Added the function Makefile.win.bc for compiling the examples
+          under Borland 5.2.
+
+1/4/98  : Slight change to the perl5 module and C++ compilation.  The
+          <math.h> library is now included before any Perl headers
+          because Perl the extern "C" linkage of math.h screws alot
+          of things up (especially on Windows).
+
+1/2/98  : Change to the Python module that reduces the number of constants
+          created by C++ classes, inheritance, and shadow classes.   This
+          modification may introduce a few slight incompatibilities if
+          you attempt to use the non-shadow class interface with shadow
+          classes enabled.    Patch contributed by Mike Romberg.
+
+1/2/98  : Support for Tcl 8.0 namespaces has been added.   This *replaces*
+          the original SWIG mechanism that assumed [incr Tcl] namespaces.
+          To use namespaces, simply run SWIG with the following options
+
+             swig -tcl -namespace  foo.i
+
+                    This places everything in a namespace that matches
+                    the module name
+
+             swig -tcl -namespace -prefix bar foo.i
+
+                    This places everything in the namespace 'bar'
+
+          The use of namespaces is new in Tcl 8.0.  However, the wrapper code
+          generated by SWIG will still work with all versions of Tcl newer
+          than and including Tcl 7.3/Tk3.6 even if the -namespace option is
+          used.
+
+          *** POTENTIAL INCOMPATIBILITY ***
+          This change may break existing applications that relied on the
+          -prefix and -namespace options.
+
+1/2/98  : Added the following constants to the Tcl wrapper code
+
+                 SWIG_name      - Name of the SWIG module
+                 SWIG_prefix    - Prefix/namespace appended to command names
+                 SWIG_namespace - Name of the namespace
+
+          SWIG library writers can use these to their advantages.
+
+1/2/98  : Fixed a bug in the Tcl8 module related to the creation of
+          pointer constants (the function SWIG_MakePtr was missing from
+          the wrapper code).
+
+1/2/98  : Added the consthash.i library file to the Tcl and Tcl8 modules.
+
+1/1/98  : Changed and cleaned up the Python typemaps.i file.   The following
+          significant changes were made :
+
+                1.  The OUTPUT typemap now returns Python tuples instead of
+                    lists.   Lists can be returned as before by using the
+                    L_OUTPUT type.    If compatibility with older versions
+                    is needed, run SWIG with the -DOUTPUT_LIST option.
+
+                2.  The BOTH typemap has been renamed to INOUT.  For backwards
+                    compatibility, the "BOTH" method still exists however.
+
+                3.  Output typemaps now generate less code than before.
+
+          Changes to typemaps.i may break existing Python scripts that assume
+          output in the form of a list.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+12/31/97: Fixed long overdue problems with the testing scripts and certain
+          makefiles that required the use of the bash shell.   Everything should
+          work properly with the standard Bourne shell (sh) now.
+
+12/31/97: Modified typemaps to allow $basetype as a valid local variable.
+          This allows for all sorts of bizarre hackish typemaps that
+          do cool things.   Patch contributed by Dominique Dumont.
+
+12/31/97: Switched accessor functions generated for member data to
+          C preprocessor macros (except in cases involving typemaps
+          or char *).
+
+12/31/97: Fixed a bug related to C++ member data involving references.
+
+12/31/97: Changed accessor functions for C++ member functions to
+          preprocessor macros.   This cleans up the wrapper code
+          and results in fewer function definitions.
+
+12/31/97: Changed the default C constructor to use calloc() instead
+          of malloc()
+
+12/30/97: Changed the creation of constants in the Perl5 module.
+          For all practical purposes, they should work in exactly the
+          same way as before except that they now require much less
+          wrapper code.   Modules containing large numbers of
+          constants may see greater than a 50% reduction in wrapper
+          code size.
+
+12/30/97: Modified the Python module to be more intelligent about the
+          creation of constants.  SWIG no longer generates redundant
+          global variables and the size of the module initialization
+          function should be reduced.   (Many thanks to Jim Fulton).
+
+12/29/97: Fixed a bug in C++ code generation related to member functions,
+          default arguments, and references.
+
+12/29/97: Fixed configure script and a few makefiles to support Python 1.5
+
+12/29/97: Added 'embed15.i' library file.  This file should be used to
+          staticly link versions of Python 1.5.    To make it the default,
+          simply copy 'swig_lib/python/embed15.i' to 'swig_lib/python/embed.i'
+
+Version 1.1 Patch 3 (November 24, 1997)
+========================================
+
+11/23/97: Fixed a bug in the Perl5 module with shadow classes and
+          static class functions that return class instances.
+          Note : The fix for this bug requires a slight restructuring of
+          of the .pm files created by SWIG.
+
+11/23/97: Fixed a bug in the Tcl/Tcl8 modules related to variable linking
+          of character arrays.  If you declared a global variable 'char foo[10]',
+          the generated wrapper code would either cause a segmentation fault
+          immediately upon loading or weird memory corruption elsewhere.
+          This should now be fixed although character arrays can only be
+          read-only.
+
+11/23/97: Fixed a bug with the %import directive that caused it to
+          fail if files were imported from directories other than
+          the current working directory.
+
+11/23/97: Fixed incorrect diagnostic message in the ASCII documentation
+          module.
+
+11/23/97: Changed the behavior of the -o option when used with shadow
+          classes. If -o was used to specify both the pathname and filename
+          of SWIG's output such as
+
+                 swig -o /home/swig/wrapper.c -shadow -perl5 foo.i
+
+          The wrapper code would be placed the file specified with -o,
+          but the .pm file and documentation would be placed in the
+          directory where SWIG was run.   Now, these files are placed
+          in the same directory as the file specified with the -o option.
+          This change is also needed for proper operation on the
+          Macintosh.
+
+11/23/97: Added a 'this()' method to Perl5 shadow classes.   This can
+          be used to return the normal pointer value from a shadow
+          class that is represented as a tied hash.   To use just
+          invoke as a method like this :
+
+              $l = new List;       # Create an object
+              $ptr = $l->this();   # Get the normal pointer value
+
+          *** NEW FEATURE ***
+
+11/23/97: Fixed the Tcl 8 pointer.i library file (which was completely
+          broken in 1.1p2).
+
+11/23/97: Modified the Perl5 type-checker to fix a few problems
+          with global variables of pointer types and to allow
+          tied hashes to be used interchangably with normal
+          pointer values.
+
+11/23/97: Modified the typemap mechanism to allow output
+          typemaps of type 'void'.   These were ignored previously,
+          but now if you specify,
+
+                %typemap(lang,out) void {
+                      ... return a void ...
+                }
+
+          You can change or assign a return value to the function.
+
+11/23/97: Fixed processing of 'bool' datatypes in the Python module.
+
+11/23/97: Fixed minor parsing error with C++ initializers. For example,
+
+                 class B : public A {
+                 public:
+                       B() : A() { ... };
+                       ...
+                 }
+
+11/23/97: Fixed the Tcl8 module so that C functions that call back into
+          Tcl don't corrupt the return result object (SWIG was gathering
+          the result object too early which leads to problems if subsequent
+          Tcl calls are made).
+
+11/23/97: Fixed a code generation bug in the Python module when two or
+          more output parameters were used as the first arguments of a
+          function.  For example :
+
+                 %include typemaps.i
+                 void foo(double *OUTPUT, double *OUTPUT, double a);
+
+          Previously, doing this resulted in the creation of an
+          extraneous comma in the output, resulting in a C syntax error.
+
+11/22/97: Fixed a bug when template handling that was stripping whitespace
+          around nested templates.   For example :
+
+                 Foo<Bar<double> >
+
+          was getting munged into Foo<Bar>> which is a syntax error in
+          in the C++ compiler.
+
+11/22/97: Fixed bugs in the Borland C++ makefiles.
+
+11/22/97: Fixed memory corruption bug when processing integer
+          arguments in Tcl8 module.
+
+11/21/97: Fixed a bug in the Runtime/Makefile related to Tcl 8.
+
+11/21/97: Fixed a bug with the %new directive and Perl5 shadow classes.
+          No longer generates a perl syntax error.
+
+11/9/97 : Changed a strncpy() to strcpy() in the pointer type-checker.
+          This results in a substantial performance improvement in
+          type-checking.
+
+10/29/97: Fixed a bug in the code generation of default arguments and
+          user-defined types.  For example :
+
+                 void foo(Vector a, Vector b = d);
+
+          should now work properly.
+
+Version 1.1 Patch 2 (September 4, 1997)
+=======================================
+9/4/97  : Fixed problem with handling of virtual functions that
+          was introduced by some changes in the C++ module.
+
+Version 1.1 Patch 1 (August 27, 1997)
+=====================================
+
+8/26/97 : Fixed compilation and run-time bugs with Tcl 8.0 final.
+
+8/21/97 : Fixed code generation bug with arrays appearing as arguments
+          to C++ member functions.  For example :
+
+                class Foo {
+                public:
+                      void Bar(int a[20][20]);
+                };
+
+          There is still a bug using arrays with added methods
+          however.
+
+8/20/97 : Fixed a bug with generating the code for added methods
+          involving pass-by-value.
+
+8/19/97 : Modified the typemapper to substitute the '$arg' value
+          when declaring local variables.    For example :
+
+              %typemap(in) double * (double temp_$arg) {
+                    ... do something ...
+              }
+
+          When applied to a real function such as the following :
+
+              void foo(double *a, double *b, double *result);
+
+          three local variables will be created as follows :
+
+              double temp_a;
+              double temp_b;
+              double temp_result;
+
+          This can be used when writing multiple typemaps that need
+          to access the same local variables.
+
+
+7/27/97 : Fixed a variety of problems with the %apply directive and arrays.
+          The following types of declarations should now work :
+
+               %apply double [ANY] { Real [ANY] };
+               %apply double [4] { double [10] };
+
+          A generic version of apply like this :
+
+               %apply double { Real };
+
+          should now work--even if arrays involving doubles and Reals are
+          used later.
+
+7/27/97 : Changed warning message about "Array X has been converted to Y" to
+          only appear if running SWIG in verbose mode.
+
+7/27/97 : Added the variables $parmname and $basemangle to the typemap
+          generator.    $parmname is the name of the parameter used
+          when the typemap was matched.  It may be "" if no parameter
+          was used.   $basemangle is a mangled version of the base
+          datatype.    Sometimes used for array handling.
+
+7/27/97 : Changed the behavior of output arguments with Python shadow classes.
+          Originally, if a function returned an object 'Foo', the shadow class
+          mechanism would create code like this :
+
+                def return_foo():
+                      val = FooPtr(shadowc.return_foo())
+                      val.this = 1
+                      return val
+
+          The problem with this is that typemaps allow a user to redefine
+          the output behavior of a function--as a result, we can no longer
+          make any assumptions about the return type being a pointer or
+          even being a single value for that matter (it could be a list,
+          tuple, etc...).   If SWIG detects the use of output typemaps
+          (either "out" or "argout") it returns the result unmodified like
+          this :
+
+                def return_foo():
+                      val = shadowc.return_foo()
+                      return val
+
+          In this case, it is up to the user to figure out what to do
+          with the return value (including the possibility of converting it
+          into a Python class).
+
+7/26/97 : Fixed a parsing problem with types like 'unsigned long int',
+          'unsigned short int', etc...
+
+7/24/97 : Minor bug fix to Tcl 8 module to parse enums properly.  Also
+          fixed a memory corruption problem in the type-checker.
+          (patch contributed by Henry Rowley.
+
+7/24/97 : Added Python-tuple typemaps contributed by Robin Dunn.
+
+7/24/97 : Incorporated some changes to the Python module in support of
+          Mark Hammond's COM support.  I'm not entirely sure they
+          work yet however.  Needs documentation and testing.
+
+7/24/97 : Fixed code generation bugs when structures had array members
+          and typemaps were used.  For example :
+
+              %typemap(memberin) double [20][20] {
+                      ... get a double [20][20] ...
+              }
+              struct Foo {
+                     double a[20][20];
+              }
+
+          Originally, this would generate a compiler-type error when
+          the wrapper code was compiled.   Now, a helper function like
+          this is generated :
+
+                double *Foo_a_set(Foo *a, double val[20][20]) {
+                         ... memberin typemap here ...
+                         return (double *) val;
+                }
+
+          When writing typemaps, one can assume that the source variable
+          is an array of the *same* type as the structure member. This
+          may break some codes that managed to work around the array bug.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+7/13/97 : Fixed bug in Perl5 module when using C global variables that
+          are pointers.  When used in function calls and other operations,
+          the value of the pointer would be invalid---causing core
+          dumps and other problems.  SWIG implements global variables
+          using Perl magic variables.  As it turns out, the error
+          was caused by the fact that the pointer-extraction code
+          was somehow bypassing the procedure used to resolve magical
+          variables (hence, leaving the value undefined).  To fix
+          the problem, SWIG now explicitly resolves magic before
+          extracting pointer values.
+
+7/12/97 : Eliminated the last remnants of free() and malloc() from
+          the SWIG compiler.
+
+7/12/97 : Fixed parsing problems with typemaps involving arrays and
+          temporary variables of arrays.    Also made it possible for
+          SWIG to handle typemaps like this :
+
+                 %typemap(in) double [ANY] (double temp[$dim0]) {
+		      ... store data in temp[$dim0] ...
+                 }
+
+          Not only does this typemap match any double [] array, it
+          creates a local variable with precisely the right dimensions.
+          (ie. $dim0 gets filled in with the real number of dimensions).
+          Of course, off the record, this will be a way to add more
+          functionality to the typemaps.i libraries.
+
+7/9/97  : Fixed some problems with Perl5, static linking, and shadow
+          classes.  When statically linking multiple modules together, write
+          a top-level interface file like this when shadow classes are not
+          used :
+
+                 %module swig, foo, bar, glob;
+                 %include perlmain.i
+
+          When shadow classes are used, the module names have an extra 'c'
+          appended so it should read as :
+
+                 %module swig, fooc, barc, globc;
+                 %include perlmain.i
+
+          When linking multiple modules, consider using the SWIG runtime
+          library.
+
+7/8/97  : Incorporated fixed versions of the Borland C++ Makefiles.
+
+7/8/97  : First cut at trying to eliminate excessive compiler warnings.
+          As it turns out, alot of warnings go away if you just make
+          declarations like this
+
+                  clientData = clientData;
+
+          in the resulting wrapper code.  Most compilers should just
+          ignore this code (at least would can hope).
+
+7/8/97  : Fixed bizarre code generation bug with typemaps and C++ classes.
+          In some cases, typemaps containing printf formatting strings such as
+
+                  %typemap(memberout) int * {
+                         printf("%d",42);
+                  }
+
+          Would generate completely bogus code with garbage replacing
+          the '%d'.   Caused by one faulty use of printf (wasn't able to find
+          any other occurences).
+
+7/7/97  : Fixed bug in Python shadow class generation with non-member
+          functions that are returning more than one value.
+
+7/7/97  : Incorporated modifications to make SWIG work with Guile 1.2.
+          Still need to test it out, but it is rumored to work.
+
+7/2/97  : Fixed some bugs related to output arguments and Python shadow
+          classes.    If an output argument is detected, SWIG assumes
+          that the result is a list and handles it appropriately.
+          If the normal return type of an function is an object,
+          it will be converted into a shadow class as before, but
+          with the assumption that it is the first element of a
+          list.  *** NOTE : This behavior has been subsequently changed ***
+
+6/29/97 : Changed EXPORT to SWIGEXPORT in all of the language modules.
+          Should provide better compatibility with Windows.
+
+6/29/97 : Modified Python shadow classes so that output arguments
+          work correctly (when typemaps are used).
+
+Version 1.1 (June 24, 1997)
+===========================
+
+6/24/97 : Fixed Objective-C constructor bug when working with Perl5
+          shadow classes.
+
+6/23/97 : Fixed some parsing problems with Objective-C.  Declarations
+          such as the following should work now :
+
+               - foo : (int) a with: (int) b;
+
+6/22/97 : Added SWIG Runtime library.   This library contains
+          the SWIG pointer type-checker and support functions
+          that are normally included in every module.  By using
+          the library, it is easier to work with multiple SWIG
+          generated modules.
+
+6/22/97 : Fixed minor bug in Perl5 module related to static linking
+          of multiple modules.
+
+6/22/97 : Fixed some bugs with the %import directive. When used with
+          Perl5 shadow classes, this generates a 'require' statement
+          to load in external modules.
+
+6/22/97 : Added -swiglib option.  This prints out the location of the
+          SWIG library and exits.  This option is only really useful to
+          configuration tools that are looking for SWIG and its library
+          location (e.g. autoconf, configure, etc...).
+
+6/21/97 : Fixed export bug with Perl5.004 on Windows-NT.
+
+6/20/97 : Minor change to code generation of class/structure members in
+          order to work better with typemaps. Should have no noticable
+          impact on existing SWIG modules.
+
+6/19/97 : Added -t option. This allows SWIG to load a typemap file before
+          processing any declarations.  For example :
+
+                 swig -t typemaps.i -python example.i
+
+          At most, only one typemap file can be specified in this manner.
+          *** NEW FEATURE ***
+
+6/18/97 : Need a Makefile fast? Type
+
+                 swig [-tcl, -perl5, -python] -co Makefile
+
+          and you will get a Makefile specific to that target language.
+          You just need to modify it for your application and you're
+          ready to run.
+
+6/18/97 : Completed the -ci option.  This option checks a file into the
+          SWIG library.   It should be used in conjunction with a
+          language option. For example :
+
+                  swig -tcl -ci foobar.i
+
+          Checks the file foobar.i into the Tcl part of the library.
+          In order to check a file into the general library (accessible
+          to all languages modules), do the following
+
+                  swig -ci -o ../foobar.i foobar.i
+
+          (Admittedly this looks a little strange but is unavoidable).
+          The check-in option is primarily designed for SWIG maintenance
+          and library development. The command will fail if the user does
+          not have write permission to the SWIG library.  Third party library
+          extensions can easily install themselves by simply providing
+          a shell script that uses 'swig -ci' to install the appropriate
+          library files.  It is not necessary to know where the SWIG library
+          is located if you use this mechanism.
+          *** NEW FEATURE ***
+
+6/16/97 : Fixed a bug in shadow class generation when %name() was applied
+          to a class definition.   Unfortunately, fixing the bug required
+          a change in the Language C API by adding an extra argument to
+          the Language::cpp_class_decl() function.  This may break
+          SWIG C++ extensions.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+6/15/97 : Added a warning message if no module name is specified with the
+          %module directive or -module option.
+
+6/15/97 : Fixed line number bug when reporting errors for undefined
+          base classes.
+
+6/15/97 : Added new %rename directive.  This allows the forward declaration
+          of a renaming.  For example :
+
+                 %rename OldName NewName;
+
+                 .... later ...
+                 int OldName(int);
+
+          Unlike %name, %rename will rename any occurence of the old name.
+          This applies to functions, variables, class members and so forth.
+          There is no way to disable %rename once set, but you can change the
+          name by redeclaring it to something else.
+          *** NEW FEATURE ***
+
+6/15/97 : Improved the implementation of the %name directive so that it
+          could be used with conditional compilation :
+
+                    #ifdef SWIG
+                    %name(NewName)
+                    #endif
+                    int OldName(int);
+
+6/15/97 : Added support for functions with no return datatype.  In this case,
+          SWIG assumes a return type of 'int'.
+
+6/11/97 : Improved error reporting in the parser.  It should be a little
+          less sensitive to errors that occur inside class definitions
+          now.  Also reports errors for function pointers.
+
+6/11/97 : Made '$' a legal symbol in identifiers.  This is to support
+          some Objective-C libraries.  Some compilers (such as gcc) may also
+          allow identifiers to contain a $ in C/C++ code as well (this is
+          an obscure feature of C). When '$' appears in identifier, SWIG
+          remaps it to the string '_S_' when creating the scripting language
+          function. Thus a function 'foo$bar' would be called 'foo_S_bar'.
+
+6/11/97 : Fixed bug in Python shadow classes with __repr__ method.  If
+          supplied by the user, it was ignored, but now it should work.
+
+6/9/97  : Fixed the Tcl 8.0 module to work with Tcl 8.0b1.   SWIG is no
+          longer compatible with *any* alpha release of Tcl 8.0.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+6/7/97  : Put a maximal error count in (currently set to 20). SWIG will bail out
+          if it generates more errors than this (useful for preventing SWIG
+          from printing 4000 syntax errors when it gets confused).
+
+6/7/97  : Fixed segmentation fault when parsing variable length arguments.
+
+6/7/97  : Minor change to Perl5 module.  C++ static functions are now
+          put in the same package as their class when using shadow classes.
+
+6/7/97  : Centralized the naming of functions, members, wrappers etc... By
+          centralizing the naming scheme, it should be possible to make
+          some multi-file optimizations.  Also, it should be possible to
+          change SWIG's naming scheme (perhaps a new feature to be added
+          later).
+
+6/2/97  : Added 'arginit' typemap.   This can be used to assign initial values
+          to function arguments.  Doing so makes it somewhat easier to detect
+          improper argument passing when working with other typemaps.
+
+6/2/97  : Fixed code generation bug when read-only variables were inherited
+          into other classes.  Under inheritance, the variables would
+          become writable, but this has now been corrected.
+
+5/30/97 : An empty %name() directive is no longer allowed or supported.
+          This directive was originally used to strip the prefix
+          off of a class or structure.  Unfortunately, this never really
+          seemed to work right and it complicated the C++ code generator
+          significantly.   As far as I can tell no one uses it, so it
+          is now history.  *** POTENTIAL INCOMPATIBILITY ***
+
+5/28/97 : Fixed a parsing bug with #define and C++ comments.  Declarations
+          such as the following now work properly :
+
+                   #define CONST   4     // A Comment
+
+5/28/97 : Made some performance improvements to the SWIG String class.
+          (only affects the SWIG compiler itself).
+
+5/28/97 : Modified the parser to skip template definitions and issue a
+          warning message.
+
+5/28/97 : Preliminary support for parameterized types added (ie. templates).
+          Types such as the following should pass through the SWIG compiler
+
+                    void foo(vector<complex> *a, vector<double> *b);
+
+          When used, the entire name 'vector<complex>' becomes the name
+          of the datatype.      Due to space limitations in datatype
+          representations, the name should not exceed 96 characters.
+
+          Note : This is only part of what is needed for template support.
+          Template class definitions are not yet supported by SWIG.
+
+          The template notation above may also be used when specifying
+          Objective-C protocol lists.
+          *** NEW FEATURE ***
+
+5/24/97 : First cut at Objective-C support added.   As it turns out, almost
+          everything can be handled with only a few minor modifications to
+          the C++ module.
+          *** NEW FEATURE ***
+
+5/23/97 : Fixed repeated definition bug in multiple inheritance handling
+          when multiple base classes share a common base class (ie.
+          the evil diamond).
+
+5/21/97 : Fixed rather embarrassing typo that worked its way into the
+          Tests/Build directory.
+
+5/19/97 : Fixed code generation bug when using native methods and
+          shadow classes with Python and Perl5 modules.
+
+5/19/97 : Modified the %apply directive slightly so that it would work
+          with pointers a little better. For example :
+
+                  %apply unsigned long { DWORD };
+
+          Applies *all* typemaps associated with "unsigned long" to
+          "DWORD".   This now includes pointers to the two datatypes.
+          For example, a typemap applied to "unsigned long **" would
+          also be applied to any occurrence of "DWORD **" as well.
+
+5/19/97 : Fixed an ownership assignment bug in the Perl5 module when
+          class members were returning new objects belonging to
+          different classes.
+
+5/17/97 : Added a few more typemap variables.
+
+                  $name          - Name of function/variable/member
+                  $basetype      - Base datatype (type without pointers)
+                  $argnum        - Argument number
+
+5/16/97 : Fixed embarrassing underscore error in local variable
+          allocator.
+
+5/16/97 : Fixed namespace clash bug in parameterized typemaps
+          when creating arrays as new local variables.
+
+5/15/97 : Fixed some bugs with inheritance of added methods across
+          multiple files.   SWIG now uses names of base classes
+          when generating such functions.
+
+5/14/97 : Finished support for default typemaps.  Primarily used
+          internally, they can be used to match the basic
+          built-in datatypes used inside of SWIG.   You can
+          specify them in interface files as well like this :
+
+               %typemap(tcl,in) int SWIG_DEFAULT_TYPE {
+                        $target = atoi($target);
+               }
+
+          Unlike normal typemaps, this default map will get applied
+          to *all* integer datatypes encountered, including those
+          renamed with typedef, etc...
+
+5/13/97 : Fixed substring bug in type checker.
+
+5/12/97 : Fixed bug in parameterized typemaps when declaring local
+          variables of structures.
+
+Version 1.1 Beta6 (May 9, 1997)
+===============================
+
+5/9/97  : Fixed bizarre NULL pointer handling bug in Perl5 module.
+
+5/8/97  : Fixed mysterious segmentation fault when running SWIG on an
+          empty file.
+
+5/7/97  : The code generator will now replace the special symbol "$cleanup"
+          with the cleanup code specified with the "freearg" typemap.
+          This change needed to properly manage memory and exceptions.
+
+5/5/97  : Added the 'typemaps.i' library file.  This contains a
+          variety of common typemaps for input values, pointers,
+          and so on.
+
+5/5/97  : Changed behavior of "argout" typemap in Python module.
+          Old versions automatically turned the result into a
+          Python list.  The new version does nothing, leaving the
+          implementation up to the user.  This provides more flexibility
+          but may break older codes that rely on typemaps.
+          *** POTENTIAL INCOMPATIBILITY ***
+
+5/5/97  : Fixed bug in Python module related to the interaction of
+          "argout" and "ignore" typemaps.
+
+5/5/97  : Fixed bug in Python module that would generate incorrect code
+          if all function arguments are "ignored".
+
+5/4/97  : Added %apply and %clear directives.   These form a higher level
+          interface to the typemap mechanism.  In a nutshell, they
+          can be used to change the processing of various datatypes without
+          ever having to write a typemap.  See the SWIG documentation
+          for more details.  ** NEW FEATURE **
+
+5/4/97  : Added a local variable extension to the typemap handler.
+          For example :
+
+                 %typemap(tcl,in) double *(double temp) {
+		        temp = atof($source);
+                        $target = &temp;
+                 }
+
+          In this case, 'temp' is a local variable that exists
+          in the entire wrapper function (not just the typemap
+          code).  This mechanism provides better support for
+          certain types of argument handling and also makes it
+          possible to write thread-safe typemaps.  Any number
+          local variables can be declared by supplying a comma
+          separated list.   Local variables are guaranteed to be
+          unique, even if the same typemap is applied many times
+          in a given function.
+          ** Not currently supported in Perl4 or Guile modules.
+
+5/2/97  : Fixed processing of %ifdef, %endif, %if, etc...  (These are
+          SWIG equivalents of the C preprocessor directives that
+          can pass through the C preprocessor without modification).
+
+5/2/97  : Fixed major (but subtle) bug in the run-time type checker
+          related to searching and type-checking for C++ inheritance.
+          To make a long story short, if you had two classes named
+          "Foo" and "FooObject" the type checker would sometimes
+          get confused and be unable to locate "Foo" in an internal
+          table.
+
+5/2/97  : Fixed some bugs in the -co option.
+
+4/24/97 : Pointer library added to the SWIG library.
+
+4/19/97 : Added the %new directive.   This is a "hint" that can be used
+          to tell SWIG that a function is returning a new object. For
+          example :
+
+                  %new Foo *create_foo();
+
+          This tells SWIG that create_foo() is creating a new object
+          and returning a pointer to it.   Many language modules may
+          choose to ignore the hint, but when working with shadow classes,
+          the %new is used to handle proper ownership of objects.
+
+          %new can also be used with dynamically allocated strings.
+          For example :
+
+                  %new char *create_string();
+
+          When used, all of the language modules will automatically cleanup
+          the returned string--eliminating memory leaks.
+          ** NEW FEATURE **
+
+4/19/97 : Added a new typemap "newfree".   This is used in conjunction with
+          the %new directive and can be used to change the method by which
+          a new object returned by a function is deleted.
+
+4/19/97 : The symbol "__cplusplus" is now defined in the SWIG interpreter
+          when running with the -c++ option.
+
+4/17/97 : Added support for static member functions when used inside the
+          %addmethods directive.
+
+4/15/97 : Added a special typemap symbol PREVIOUS that can be used to
+          restore a previous typemap. For example :
+
+	         %typemap(tcl,in) int * = PREVIOUS;
+
+          This is primarily used in library files.
+
+4/13/97 : Added %pragma directive for Perl5 module.   Two new pragmas are
+          available :
+
+                 %pragma(perl5) code = "string"
+                 %pragma(perl5) include = "file.pl"
+
+          Both insert code into the .pm file created by SWIG.  This can
+          be used to automatically customize the .pm file created by SWIG.
+
+4/13/97 : Scanner modified to only recognize C++ keywords when the -c++
+          option has been specified.  This provides support for C programs
+          that make use of these keywords for identifiers.
+          SWIG may need to be explicitly run with the -c++ option when
+          compiling C++ code (this was allowed, but not recommended in
+          previous versions). **POTENTIAL INCOMPATIBILITY**
+
+4/11/97 : Fixed a rather nasty bug in the Perl5 module related to using
+          variable linking with complex datatypes and pointers.   On Unix,
+          code would work (somehow), but would cause an access violation
+          under Windows-NT.  The fix should correct the problem,
+          but there may still be a problem using global variables of
+          complex datatypes in conjunction with shadow classes.  Fortunately,
+          this sort of thing seems to be relatively rare (considering
+          that the bug has been around for more than a year - yikes!).
+
+4/11/97 : Fixed bizarre constant evaluation bug in Perl5 code generation
+          when running under Windows-NT.
+
+4/8/97  : Bug when using default arguments and C++ references fixed.
+
+4/8/97  : Fixed code generation bugs in Python and Perl5 modules related to
+          using class renaming (applying the %name directive to a class
+          definition) and shadow classes.
+
+4/7/97  : Fixed minor bugs in swigptr.swg, tcl8ptr.swg, and perl5ptr.swg to
+          prevent infinite loops when weird datatypes are passed.
+
+3/29/97 : 'Makefile.win' added.   This is used to build most of the examples
+          in the Examples directory under Windows NT/95.
+
+3/27/97 : Fixes to SWIG's error return codes.   SWIG now returns non-zero
+          exit codes for certain kinds of errors (which makes it more
+          friendly to makefiles).     An overhaul of the error handling
+          is on the to-do list and will probably show up in a later release.
+
+3/25/97 : Bug fix.  "freearg" and "argout" typemaps have been fixed in
+          the Perl5 module.  In previous versions, function input parameters
+          and function output parameters shared the same memory space--causing
+          all sorts of nasty problems when trying to pass perl values by
+          reference.   SWIG now internally makes a "copy" (which is really
+          just a pointer) of affected parameters and uses that.   This
+          is done transparently so there is no noticable impact on any
+          SWIG generated modules.   This change is probably only noticable
+          to expert users.
+
+3/25/97 : Added type-check to verbose and stat mode.  SWIG will now generate a list
+          of all datatypes that were used but undefined (useful for tracking
+          down weird bugs).   This is enabled with the -v option (which
+          is now officially known as "overly verbose" mode) or the -stat option.
+
+3/25/97 : Slight change to the parser to make include guards work correctly.
+          For example :
+
+                #ifndef INTERFACE_I
+                #define INTERFACE_I
+                %module foobar.i
+                ... declarations ...
+                #endif
+
+3/24/97 : %checkout directive added.   This allows an interface file to
+          extract files from the SWIG library and place them in the
+          current directory.   This can be used to extract scripts and
+          other helper code that might be associated with library files.
+          For example :
+
+                %checkout array.tcl
+
+          Will look for a file "array.tcl" in the library and copy it
+          to the current directory.    If the file already exists in the
+          directory, this directive does nothing (it will not overwrite an
+          existing file).  This only an experimental feature for now.
+
+3/24/97 : SWIG will now look in the SWIG Library for a file if it can't
+          find it in the current directory.  As a result, it is easy to
+          make modules from SWIG library files.  For example, if you
+          want to make a Python module from the SWIG timers library, just
+          type this in any directory :
+
+                swig -python timers.i
+
+          You will get the files timers_wrap.c and timers_wrap.doc in
+          the current directory that you can now compile.   The file
+          remains in the SWIG library (although you can check it out
+          using the -co option).  *** New Feature ***
+
+3/24/97 : -co option added to SWIG to allow easy access to the SWIG library.
+          When used, this instructs SWIG to check out a library file and
+          place it in the current directory.  For example :
+
+                unix > swig -co array.i
+                array.i checked out from the SWIG library
+                unix >
+
+          Once in your directory you can customize the file to suit your
+          particular purposes.  The checkout option makes it easy to
+          grab library files without knowing anything about the SWIG
+          installation, but it also makes it possible to start
+          including scripts, C code, and other miscellaneous files
+          in the library.  For example, you could put a cool script
+          in the library and check it out whenever you wanted to use it.
+          *** New Feature ***
+
+3/24/97 : #pragma export directives added to Tcl output for compiling
+          shared libraries on the Mac.
+
+3/24/97 : Minor changes to wish.i and tclsh.i library files to provide
+          support for the Macintosh.
+
+3/19/97 : SWIG's policy towards NULL pointers has been relaxed.  The
+          policy of requiring a special compiler directive -DALLOW_NULL
+          to use NULL pointers is no longer supported.  While this may
+          seem "unsafe", it turns out that you can use a "check"
+          typemap to achieve some safety.   For example :
+
+                %typemap(perl5,check) Node * {
+                       if (!$target)
+                            croak("NULL Pointers not allowed.");
+                }
+
+          This prevents any NULL value of a "Node *" pointer to be
+          passed to a function.   (I think this is much cleaner
+          than the old -DALLOW_NULL hack anyways).
+
+3/19/97 : Fixed pointer handling errors in Perl5 module.  Modules no
+          longer core dump when a Perl reference is inadvertently
+          passed in as a C pointer.
+
+3/18/97 : Added a "check" typemap.   This can be used to check the
+          validity of function input values.  For example :
+
+                %typemap(perl5,check) int posint {
+                       if ($target < 0)
+                           croak("Argument is not a positive integer");
+                }
+
+3/18/97 : Added an $arg variable to Tcl typemaps.   This makes it easier
+          to return argument values by "reference".
+
+3/18/97 : Fixed a code generation bug when using C++ references and
+          the %addmethods directive.
+
+3/18/97 : Fixed a few glitches in the typemap module with respect to
+          chaining. For example :
+
+                %typemap(tcl,in) int {
+                       $in                // Inserts prexisting typemap
+                       printf("Received a %d\n", $target);
+                }
+
+          This has been allowed for quite some time, but didn't work
+          if no existing typemap was defined.  Now, it still doesn't
+          work if no existing typemap is defined, but it issues a
+          warning message.   There is some support using default typemaps,
+          but none of the language modules take advantage of it.  This
+          should be considered experimental at this time.
+
+Version 1.1b5 Patch 1 (March 16, 1997)
+======================================
+
+3/16/97 : Fixed references bug with C++ code generation.
+
+3/16/97 : Fixed initialization bug in the documentation system that
+          was causing weird problems.
+
+3/16/97 : Fixed fatal bug with -c option in the Python module.
+
+3/13/97 : Fixed bug in the documentation system involving the %text directive
+          and sorting. In the old system, %text entries would float to the
+          top of a section because they were "nameless".   Now they are
+          attached to the previous declaration and will stay in the proper
+          location relative to the previous entry.
+
+Version 1.1b5 (March 12, 1997)
+==============================
+
+3/11/97 : Fixed compilation problems introduced by Tcl/Tk 8.0a2.
+          *** INCOMPATIBILITY *** SWIG no longer works with Tcl/Tk 8.0a1.
+
+3/10/97 : Fixed bug with ignored arguments and C++ member functions in
+          the Python module.
+
+3/9/97  : Parsing bugs with nested class definitions and privately
+          declared nested class definitions fixed.
+
+3/9/97  : Fixed a few minor code generation bugs with C++ classes and
+          constructors.   In some cases, the resulting wrapper code
+          would not compile properly.   SWIG now attempts to use
+          the default copy constructor instead.
+
+3/8/97  : Added a -l option to SWIG that allows additional SWIG library files
+          to be grabbed without having them specified in the interface file.
+          This makes it easier to keep the interface file clean and move certain
+          options into a Makefile.   For example :
+
+              swig -tcl example.i              #  Build a normal Tcl extension
+              swig -tcl -lwish.i example.i     #  Build it as a wish extension
+                                               #  by including the 'wish.i' file.
+
+              swig -python example.i           # Build a dynamically loaded extension
+              swig -python -lembed.i example.i # Build a static extension
+
+          These kinds of options could previously be accomplished with
+          conditional compilation such as :
+
+                   %module example
+                   ...
+                   #ifdef STATIC
+                   %include embed.i
+                   #endif
+
+3/8/97  : Incorporated changes to Guile module to use the new gh interface
+          in FSF Guile 1.0.    The older gscm interface used in Cygnus
+          Guile releases is no longer supported by SWIG.
+
+3/8/97  : Cleaned up the Tcl Netscape plugin example.   It should work with
+          version 1.1 of the plugin now.
+
+3/8/97  : Added better array support to the typemap module.  The keyword
+          ANY can now be used to match any array dimension.  For example :
+
+                    %typemap(tcl,in) double [ANY] {
+                           ... get an array ...
+                    }
+
+          This will match any single-dimensional double array.   The array
+          dimension is passed in the variables $dim0, $dim1, ... $dim9.  For
+          example :
+
+		    %typemap(tcl,in) double [ANY][ANY][ANY] {
+			printf("Received a double[%d][%d][%d]\n",$dim0,$dim1,$dim2);
+	            }
+
+          Any typemap involving a specific array dimension will override any
+          specified with the ANY tag.  Thus, a %typemap(tcl,in) double [5][4][ANY] {}
+          would override a double [ANY][ANY][ANY].  However, overuse of the ANY
+          tag in arrays of high-dimensions may not work as you expect due to
+          the pattern matching rule used. For example, which of the following
+          typemaps has precedence?
+
+                      %typemap(in) double [ANY][5] {}     // Avoid this!
+                      %typemap(in) double [5][ANY] {}
+
+3/7/97  : Fixed a number of bugs related to multi-dimensional array handling.
+          Typedefs involving multi-dimensional arrays now works correctly.
+          For example :
+
+                    typedef double MATRIX[4][4];
+
+                    ...
+                    extern double foo(MATRIX a);
+
+          Typecasting of pointers into multi-dimensional arrays is now
+          implemented properly when making C/C++ function calls.
+
+3/6/97  : Fixed potentially dangerous bug in the Tcl Object-oriented
+          interface.  Well, actually, didn't fix it but issued a
+          Tcl error instead.   The bug would manifest itself as follows:
+
+                 % set l [List]           # Create an object
+                 ...
+                 % set m [List -this $l]  # Make $m into an object assuming $l
+                                          # contains a pointer.
+                                          # Since $m == $l, $l gets destroyed
+                                          # (since its the same command name)
+                 % $m insert Foo
+                 Segmentation fault       # Note : the list no longer exists!
+
+          Now, an error will be generated instead of redefining the command.
+          As in :
+
+                 % set l [List]
+                 ...
+                 % set m [List -this $l]
+                 Object name already exists!
+
+          Use catch{} to ignore the error.
+
+3/3/97  : Better support for enums added.   Datatypes of 'enum MyEnum'
+          and typedefs such as 'typedef enum MyEnum Foo;' now work.
+
+3/3/97  : Parser modified to ignore constructor initializers such as :
+
+               class Foo : public Bar {
+               int a,b;
+               public:
+                     Foo(int i) : a(0), b(i), Bar(i,0) { };
+               };
+
+3/3/97  : Modified parser to ignore C++ exception specifications such as :
+
+               int foo(double) throw(X,Y);
+
+3/3/97  : Added %import directive.  This works exactly like %extern
+          except it tells the language module that the declarations are
+          coming from a separate module.   This is usually only
+          needed when working with shadow classes.
+
+3/2/97  : Changed pointer type-checker to be significantly more
+          efficient when working with derived datatypes.  This
+          has been accomplished by storing type-mappings in sorted
+          order, using binary search schemes, and caching recently
+          used datatypes.   For SWIG generated C++ modules that
+          make a large number of C function calls with derived types,
+          this could result in speedups of between 100 and 50000 percent.
+          However, due to the required sorting operation, module
+          loading time may increased slightly when there are lots of
+          datatypes.
+
+3/2/97  : Fixed some C++ compilation problems with Python
+          embed.i library files.
+
+2/27/97 : Slight change to C++ code generation to use copy constructors
+          when returning complex data type by value.
+
+2/26/97 : Fixed bug in Python module with -c option.
+
+2/26/97 : Slight tweak of parser to allow trailing comma in enumerations
+          such as
+
+                enum Value (ALE, STOUT, LAGER, };
+
+2/25/97 : Fixed code generation bug in Tcl module when using the
+          %name() directive on a classname.
+
+2/25/97 : Finished code-size optimization of C++ code generation with
+          inheritance of attributes.    Inherited attributes now
+          only generate one set of wrapper functions that are re-used
+          in any derived classes.   This could provide big code
+          size improvements in some scripting language interfaces.
+
+2/25/97 : Perl5 module modified to support both the Unix and Windows
+          versions.  The windows version has been tested with the
+          Activeware port of Perl 5.003 running under Windows 95.
+          The C source generated by SWIG should compile without
+          modification under both versions of Perl, but is now
+          even more hideous than before.
+
+2/25/97 : Modified parser to allow scope resolution operation to
+          appear in expressions and default arguments as in :
+
+                void foo(int a =  Bar::defvalue);
+
+2/25/97 : Fixed bug when resolving symbols inside C++ classes.
+          For example :
+
+               class Foo {
+               public:
+                   enum Value {ALE, STOUT, LAGER};
+                   ...
+                   void defarg(Value v = STOUT);
+
+              };
+
+2/24/97 : Fixed bug with member functions returning void *.
+
+2/23/97 : Modified Python module to be better behaved under Windows
+
+            -  Module initialization function is now properly exported.
+               It should not be neccessary to explicitly export this function
+               yourself.
+
+            -  Bizarre compilation problems when compiling the SWIG wrapper
+               code as ANSI C under Visual C++ 4.x fixed.
+
+            -  Tested with both the stock Python-1.4 distribution and Pythonwin
+               running under Win95.
+
+2/19/97 : Fixed typedef handling bug in Perl5 shadow classes.
+
+2/19/97 : Added exception support.  To use it, do the following :
+
+              %except(lang) {
+                  ... try part of the exception ...
+                  $function
+                  ... catch part of exception ...
+              }
+
+          $function is a SWIG variable that will be replaced by the
+          actual C/C++ function call in a wrapper function.  Thus,
+          a real exception specification might look like this :
+
+             %except(perl5) {
+                  try {
+                  $function
+                  } catch (char *& sz) {
+                    ... process an exception ...
+                  } catch(...) {
+                    croak("Unknown exception. Bailing out...");
+                  }
+             }
+
+2/19/97 : Added support for managing generic code fragments (needed
+          for exceptions).
+
+2/19/97 : Fixed some really obscure typemap scoping bugs in the C++
+          handler.
+
+2/18/97 : Cleaned up perlmain.i file by removing some problematic,
+          but seemingly unnecessary declarations.
+
+2/18/97 : Optimized handling of member functions under inheritance.
+          SWIG can now use wrapper functions generated for a
+          base class instead of regenerating wrappers for
+          the same functions in a derived class.    This could
+          make a drastic reduction in wrapper code size for C++
+          applications with deep inheritance hierarchies and
+          lots of functions.
+
+2/18/97 : Additional methods specified with %addmethods can now
+          be inherited along with normal C++ member functions.
+
+2/18/97 : Minor internal fixes to make SWIG's string handling a little
+          safer.
+
+2/16/97 : Moved some code generation of Tcl shadow classes to
+          library files.
+
+2/16/97 : Fixed documentation error of '-configure' method in
+          Tcl modules.
+
+2/16/97 : Modified Perl5 module slightly to allow typemaps
+          to use Perl references.
+
+2/12/97 : Fixed argument checking bug that was introduced by
+          default arguments (function calls with too many
+          arguments would still be executed).  Functions now
+          must have the same number of arguments as C version
+          (with possibility of default/optional arguments
+          still supported).
+
+2/12/97 : Fixed default argument bug in Perl5 module when
+          generating wrapper functions involving default
+          arguments of complex datatypes.
+
+2/12/97 : Fixed typemap scoping problems.  For example :
+
+              %typemap(tcl,in) double {
+                    .. get a double ..
+              }
+
+              class Foo {
+              public:
+                   double bar(double);
+              }
+
+              %typemap(tcl,in) double {
+                    .. new get double ..
+              }
+
+          Would apply the second typemap to all functions in Foo
+          due to delayed generation of C++ wrapper code (clearly this
+          is not the desired effect).   Problem has been fixed by
+          assigning unique numerical identifiers to every datatype in
+          an interface file and recording the "range of effect" of each
+          typemap.
+
+2/11/97 : Added support for "ignore" and "default" typemaps.  Only use
+          if you absolutely know what you're doing.
+
+2/9/97  : Added automatic creation of constructors and destructors for
+          C structs and C++ classes that do not specify any sort of
+          constructor or destructor.   This feature can be enabled by
+          running SWIG with the '-make_default' option or by inserting
+          the following pragma into an interface file :
+
+                 %pragma make_default
+
+          The following pragma disables automatic constructor generation
+
+                 %pragma no_default
+
+2/9/97  : Added -make_default option for producing default constructors
+          and destructors for classes without them.
+
+2/9/97  : Changed the syntax of the SWIG %pragma directive to
+          %pragma option=value or %pragma(lang) option=value.
+          This change makes the syntax a little more consistent
+          between general pragmas and language-specific pragmas.
+          The old syntax still works, but will probably be phased
+          out (a warning message is currently printed).
+
+2/9/97  : Improved Tcl support of global variables that are of
+          structures, classes, and unions.
+
+2/9/97  : Fixed C++ compilation problem in Python 'embed.i' library file.
+
+2/9/97  : Fixed missing return value in perlmain.i library file.
+
+2/9/97  : Fixed Python shadow classes to return an AttributeError when
+          undefined attributes are accessed (older versions returned
+          a NameError).
+
+2/9/97  : Fixed bug when %addmethods is used after a class definition whose
+          last section is protected or private.
+
+2/8/97  : Made slight changes in include file processing to support
+          the Macintosh.
+
+2/8/97  : Extended swigmain.cxx to provide a rudimentary Macintosh interface.
+          It's a really bad interface, but works until something better
+          is written.
+
+1/29/97 : Fixed type-casting bug introduced by 1.1b4 when setting/getting the
+          value of global variables involving complex data types.
+
+1/29/97 : Removed erroneous white space before an #endif in the code generated
+          by the Python module (was causing errors on DEC Alpha compilers).
+
+1/26/97 : Fixed errors when using default/optional arguments in Python shadow
+	  shadow classes.
+
+1/23/97 : Fixed bug with nested %extern declarations.
+
+1/21/97 : Fixed problem with typedef involving const datatypes.
+
+1/21/97 : Somewhat obscure, but serious bug with having multiple levels
+          of typedefs fixed.  For example :
+
+		typedef char *String;
+                typedef String  Name;
+
+Version 1.1 Beta4 (January 16, 1997)
+====================================
+
+Note : SWIG 1.1b3 crashed and burned shortly after take off due
+to a few major run-time problems that surfaced after release.
+This release should fix most, if not all, of those problems.
+
+1/16/97 : Fixed major memory management bug on Linux
+
+1/14/97 : Fixed bug in functions returning constant C++ references.
+
+1/14/97 : Modified C++ module to handle datatypes better.
+
+1/14/97 : Modified parser to allow a *single* scope resolution
+          operator in datatypes.  Ie : Foo::bar.   SWIG doesn't
+          yet handle nested classes, so this should be
+          sufficient for now.
+
+1/14/97 : Modified parser to allow typedef inside a C++ class.
+
+1/14/97 : Fixed some problems related to datatypes defined inside
+          a C++ class.  SWIG was not generating correct code,
+          but a new scoping mechanism and method for handling
+          datatypes inside a C++ class have been added.
+
+1/14/97 : Changed enumerations to use the value name instead
+          of any values that might have appeared in the interface
+          file.  This makes the code a little more friendly to
+          C++ compilers.
+
+1/14/97 : Removed typedef bug that made all enumerations
+          equivalent to each other in the type checker (since
+          it generated alot of unnecessary code).
+
+Version 1.1 Beta3 (January 9, 1997)
+====================================
+
+Note : A *huge* number of changes related to ongoing modifications.
+
+1.  Support for C++ multiple inheritance added.
+
+2.  Typemaps added.
+
+3.  Some support for nested structure definitions added.
+
+4.  Default argument handling added.
+
+5.  -c option added for building bare wrapper code modules.
+
+6.  Rewrote Pointer type-checking to support multiple inheritance
+    correctly.
+
+7.  Tcl 8.0 module added.
+
+8.  Perl4 and Guile modules resurrected from the dead (well, they
+    at least work again).
+
+9.  New Object Oriented Tcl interface added.
+
+10. Bug fixes to Perl5 shadow classes.
+
+11. Cleaned up many of the internal modules of the parser.
+
+12. Tons of examples and testing modules added.
+
+13. Fixed bugs related to use of "const" return values.
+
+14. Fixed bug with C++ member functions returning void *.
+
+15. Changed SWIG configuration script.
+
+Version 1.1 Beta2 (December 3, 1996)
+====================================
+
+1. Completely rewrote the SWIG documentation system.  The changes
+   involved are too numerous to mention.  Basically, take everything
+   you knew about the old system, throw them out, and read the
+   file Doc/doc.ps.
+
+2. Limited support for #if defined() added.
+
+3. Type casts are now allowed in constant expressions.  ie
+
+         #define  A   (int) 3
+
+4. Added support for typedef lists.  For example :
+
+	typedef struct {
+	        double x,y,z;
+        } Vector, *VectorPtr;
+
+5. New SWIG directives (related to documentation system)
+
+	%style
+	%localstyle
+	%subsection
+	%subsubsection
+
+6. Reorganized the C++ handling and made it a little easier to
+   work with internally.
+
+7.  Fixed problem with inheriting data members in Python
+    shadow classes.
+
+8.  Fixed symbol table problems with shadow classes in both
+    Python and Perl.
+
+9.  Fixed annoying segmentation fault bug in wrapper code
+    generated for Perl5.
+
+10. Fixed bug with %addmethods directive.  Now it can be placed
+    anywhere in a class.
+
+11. More test cases added to the SWIG self-test.   Documentation
+    tests are now performed along with other things.
+
+12. Reorganized the SWIG library a little bit and set it up to
+    self-document itself using SWIG.
+
+13. Lots and lots of minor bug fixes (mostly obscure, but bugs
+    nonetheless).
+
+
+Version 1.1 Beta1 (October 30, 1996)
+====================================
+
+1. Added new %extern directive for handling multiple files
+
+2. Perl5 shadow classes added
+
+3. Rewrote conditional compilation to work better
+
+4. Added 'bool' datatype
+
+5. %{,%} block is now optional.
+
+6. Fixed some bugs in the Python shadow class module
+
+7. Rewrote all of the SWIG tests to be more informative
+   (and less scary).
+
+8. Rewrote parameter list handling to be more memory
+   efficient and flexible.
+
+9. Changed parser to ignore 'static' declarations.
+
+10. Initializers are now ignored.  For example :
+
+	struct FooBar a = {3,4,5};
+
+11. Somewhat better parsing of arrays (although it's
+    usually just a better error message now).
+
+12. Lot's of minor bug fixes.
+
+
+Version 1.0 Final (August 31, 1996)
+===================================
+1. Fixed minor bug in C++ module
+
+2. Fixed minor bug in pointer type-checker when using
+   -DALLOW_NULL.
+
+3. Fixed configure script to work with Python 1.4beta3
+
+4. Changed configure script to allow compilation without
+   yacc or bison.
+
+Version 1.0 Final (August 28, 1996)
+===================================
+
+1.  Changed parser to support more C/C++ datatypes (well,
+    more variants).   Types like "unsigned", "short int",
+    "long int", etc... now work.
+
+2.  "unions" added to parser.
+
+3.  Use of "typedef" as in :
+
+	typedef struct {
+	     double x,y,z;
+	} Vector;
+
+    Now works correctly.   The name of the typedef is used as
+    the structure name.
+
+4.  Conditional compilation with #ifdef, #else, #endif, etc...
+    added.
+
+5.  New %disabledoc, %enabledoc directives allow documentation
+    to selectively be disabled for certain parts of a wrapper
+    file.
+
+6.  New Python module supports better variable linking, constants,
+    and shadow classes.
+
+7.  Perl5 module improved with better compatibility with XS
+    and xsubpp.   SWIG pointers and now created so that they
+    are compatible with xsubpp pointers.
+
+8.  Support for [incr Tcl] namespaces added to Tcl module.
+
+9.  %pragma directive added.
+
+10. %addmethods directive added.
+
+11. %native directive added to allow pre-existing wrapper functions
+    to be used.
+
+12. Wrote configure script for SWIG installation.
+
+13. Function pointers now allowed with typedef statements.
+
+14. %typedef modified to insert a corresponding C typedef into
+    the output file.
+
+15. Fixed some problems related to C++ references.
+
+16. New String and WrapperFunction classes add to make generating
+    wrapper code easier.
+
+17. Fixed command line option processing to eliminate core dumps
+    and to allow help messages.
+
+18. Lot's of minor bug fixes to almost all code modules
+
+
+Version 1.0 Beta 3 (Patch 1) July 17, 1996
+==========================================
+
+1.0 Final is not quite ready yet, but this release fixes a
+number of immediate problems :
+
+1.  Compiler errors when using -strict 1 type checking have been fixed.
+
+2.  Pointer type checker now recognizes pointers of the form
+    _0_Type correctly.
+
+3.  A few minor fixes were made in the Makefile
+
+Version 1.0 Beta 3 (June 14, 1996)
+===================================
+
+
+There are lots of changes in this release :
+
+1.  SWIG is now invoked using the "swig" command instead of "wrap".
+    Hey, swig sounds cooler.
+
+2.  The SWIG_LIB environment variable can be set to change the
+    location where SWIG looks for library files.
+
+3.  C++ support has been added.   You should use the -c++ option
+    to enable it.
+
+4.  The %init directive has been replaced by the %module directive.
+    %module constructs a valid name for the initialization function
+    for whatever target language you're using (actually this makes
+    SWIG files a little cleaner).  The old %init directive still works.
+
+5.  The syntax of the %name directive has been changed.   Use of the
+    old one should generate a warning message, but may still work.
+
+6.  To support Tcl/Tk on non-unix platforms, SWIG imports a file called
+    swigtcl.cfg from the $(SWIG_LIB)/tcl directory.   I don't have access
+    to an NT machine, but this file is supposedly allows SWIG to
+    produce wrapper code that compiles on both UNIX and non UNIX machines.
+    If this doesn't work, you'll have to edit the file swigtcl.cfg. Please
+    let me know if this doesn't work so I can update the file as
+    necessary.
+
+7.  The SWIG run-time typechecker has been improved.    You can also
+    now redefine how it works by supplying a file called "swigptr.cfg"
+    in the same directory as your SWIG interface files.   By default,
+    SWIG reads this file from $(SWIG_LIB)/config.
+
+8.  The documentation system has been changed to support the following :
+
+	-  Documentation order is printed in interface file order by
+           default.   This can be overridden by putting an %alpha
+           directive in the beginning of the interface file.
+
+        -  You can supply additional documentation text using
+
+           %text %{ put your text here %}
+
+        -  A few minor bugs were fixed.
+
+9.  A few improvements have been made to the handling of command line
+    options (but it's still not finished).
+
+10.  Lots of minor bug fixes in most of the language modules have been
+     made.
+
+11. Filenames have been changed to 8.3 for compatibility with a SWIG
+    port to non-unix platforms (work in progress).
+
+12. C++ file suffix is now .cxx (for same reason).
+
+13. The documentation has been upgraded significantly and is now
+    around 100 pages.    I added new examples and a section on
+    C++.  The documentation now includes a Table of Contents.
+
+14. The SWIG Examples directory is still woefully sparse, but is
+    getting better.
+
+Special notice about C++
+------------------------
+This is the first version of SWIG to support C++ parsing.  Currently
+the C++ is far from complete, but seems to work for simple cases.
+No work has been done to add special C++ processing to any of
+the target languages.   See the user manual for details about how
+C++ is handled.   If you find problems with the C++ implementation,
+please let me know.  Expect major improvements in this area.
+
+Note : I have only successfully used SWIG and C++ with Tcl and
+Python.
+
+Notice about Version 1.0Final
+-----------------------------
+
+Version 1.0B3 is the last Beta release before version 1.0 Final is
+released.  I have frozen the list of features supported in version 1.0
+and will only fix bugs as they show up.  Work on SWIG version 2.0 is
+already in progress, but is going to result in rather significant
+changes to SWIG's internal structure (hopefully for the better).  No
+anticipated date for version 2.0 is set, but if you've got an idea,
+let me know.
+
+Version 1.0 Beta 2 (April 26, 1996)
+===================================
+This release is identical to Beta1 except a few minor bugs are
+fixed and the SWIG library has been updated to work with Tcl 7.5/Tk 4.1.
+A tcl7.5 examples directory is now included.
+
+- Fixed a bug in the Makefile that didn't install the libraries
+  correctly.
+
+- SWIG Library files are now updated to work with Tcl 7.5 and Tk 4.1.
+
+- Minor bug fixes in other modules.
+
+
+Version 1.0 Beta 1  (April 10, 1996).
+=====================================
+This is the first "semi-official" release of SWIG.    It has a
+number of substantial improvements over the Alpha release.   These
+notes are in no particular order--hope I remembered everything....
+
+1.  Tcl/Tk
+
+SWIG is known to work with Tcl7.3, Tk3.6 and later versions.
+I've also tested SWIG with expect-5.19.
+
+Normally SWIG expects to use the header files "tcl.h" and "tk.h".
+Newer versions of Tcl/Tk use version numbers.   You can specify these
+in SWIG as follows :
+
+        % wrap -htcl tcl7.4.h -htk tk4.0.h example.i
+
+Of course, I prefer to simply set up symbolic links between "tcl.h" and
+the most recent stable version on the machine.
+
+2.  Perl4
+
+This implementation has been based on Perl-4.035.  SWIG's interface to
+Perl4 is based on the documentation provided in the "Programming Perl"
+book by Larry Wall, and files located in the "usub" directory of the
+Perl4 distribution.
+
+In order to compile with Perl4, you'll need to link with the uperl.o
+file found in the Perl4 source directory.  You may want to move this
+file to a more convenient location.
+
+3.  Perl5
+
+This is a somewhat experimental implementation, but is alot less
+buggy than the alpha release.     SWIG operates independently of
+the XS language and xsubpp supplied with Perl5.  Currently SWIG
+produces the necessary C code and .pm file needed to dynamically
+load a module into Perl5.
+
+To support Perl5's notion of modules and packages (as with xsubpp),
+you can use the following command line options :
+
+        % wrap -perl5 -module MyModule -package MyPackage example.i
+
+Note : In order for dynamic loading to be effective, you need to be
+careful about naming.    For a module named "MyModule", you'll need to
+create a shared object file called "MyModule.so" using something like
+
+        % ld -shared my_obj.o -o MyModule.so
+
+The use of the %init directive must match the module name since Perl5
+calls a function "boot_ModuleName" in order to initialize things.
+See the Examples directory for some examples of how to get things
+to work.
+
+4.  Python1.3
+
+This is the first release supporting Python.    The Python port is
+experimental and may be rewritten.   Variable linkage is done through
+functions which is sort of a kludge.  I also think it would be nice
+to import SWIG pointers into Python as a new object (instead of strings).
+Of course, this needs a little more work.
+
+5.  Guile3
+
+If you really want to live on the edge, pick up a copy of Guile-iii and
+play around with this.      This is highly experimental---especially since
+I'm not sure what the official state of Guile is these days.  This
+implementation may change at any time should I suddenly figure out better
+ways to do things.
+
+6.  Extending SWIG
+
+SWIG is written in C++ although I tend to think of the code as mostly
+being ANSI C with a little inheritance thrown in.   Each target language
+is implemented as a C++ class that can be plugged into the system.
+If you want to add your own modifications, see Appendix C of the user
+manual.   Then take a look at the "user" directory which contains some
+code for building your own extenions.
+
+7. The SWIG library
+
+The SWIG library is still incomplete.  Some of the files mentioned in
+the user manual are unavailable.    These files will be made available
+when they are ready.   Subscribe to the SWIG mailing list for announcements
+and updates.
+
+8. SWIG Documentation
+
+I have sometimes experienced problems viewing the SWIG documentation in
+some postscript viewers.   However, the documentation seems to print
+normally.    I'm working on making much of the documentation online,
+but this takes time.
+
+Version 0.1 Alpha (February 9, 1996)
+====================================
+
+1.  Run-time type-checking of SWIG pointers.   Pointers are now represented
+    as strings with both numeric and encoded type information.    This makes
+    it a little harder to shoot yourself in the foot (and it eliminates
+    some segmentation faults and other oddities).
+
+2.  Python 1.3 now supported.
+
+3.  #define and enum can be used to install constants.
+
+4.  Completely rewrote the %include directive and made it alot more powerful.
+
+5.  Restructured the SWIG library to make it work better.
+
+6.  Various bug fixes to Tcl, Perl4, Perl5, and Guile implementations.
+
+7.  Better implementation of %typedef directive.
+
+8.  Made some changes to SWIG's class structure to make it easier to expand.
+    SWIG is now built into a library file that you can use to make your
+    own extenions.
+
+9.  Made extensive changes to the documentation.
+
+10. Minor changes to the SWIG parser to make it use less memory.
+    Also took out some extraneous rules that were undocumented and
+    didn't work in the first place.
+
+11. The SWIG library files "tclsh", "wish", "expect", etc... in the first
+    release have been restructured and renamed to "tclsh.i", "wish.i",
+    and so on.
diff --git a/trunk/CHANGES.current b/trunk/CHANGES.current
new file mode 100644
index 0000000..1bb8004
--- /dev/null
+++ b/trunk/CHANGES.current
@@ -0,0 +1,156 @@
+Version 1.3.36 (24 June 2008)
+=============================
+
+06/24/2008: wsfulton
+            Remove deprecated -c commandline option (runtime library generation).
+
+06/24/2008: olly
+	    [PHP] Fix assertion failure when handling %typemap(in,numinputs=0)
+	    (testcase ignore_parameter).
+
+06/24/2008: olly
+	    [PHP] Fix segfault when wrapping a non-class function marked with
+	    %newobject (testcase char_strings).
+
+06/22/2008: wsfulton
+            [Java] Add a way to use AttachCurrentThreadAsDaemon instead of AttachCurrentThread
+            in director code. Define the SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro, see
+            Lib/java/director.swg.
+
+06/21/2008: wsfulton
+            [Ruby] Fix crashing in the STL wrappers (reject! and delete_if methods)
+
+06/19/2008: wsfulton
+            [Java, C#] C# and Java keywords will be renamed instead of just issuing a warning
+            and then generating uncompileable code. Warning 314 gives the new name when a 
+            keyword is found.
+
+06/19/2008: wsfulton
+            [R] Keyword handling added. R Keywords will be renamed as necessary.
+            Warning 314 gives the new name when a keyword is found.
+
+06/17/2008: mgossage
+            [Lua] Added missing support for bool& and bool*. Added runtest for li_typemaps testcase.
+            (Bug #1938142)
+
+06/07/2008: bhy
+            Added test case keyword_rename, then made the keyword renaming works properly
+            by fixing Swig_name_make() for a incomplete condition checking.
+
+06/02/2008: wsfulton
+            [Java, C#] Fix enum wrappers when using -noproxy.
+
+05/30/2008: bhy
+            Added std::wstring into Lib/typemaps/primtypes.swg, since it is also a primitive 
+            type in SWIG - fixed SF #1976978.
+
+05/29/2008: wsfulton
+            [Java, C#] Fix variable wrappers when using -noproxy.
+
+05/29/2008: bhy
+            [Python] Fixed a typo of %#ifdef in Lib/python/pycontainer.swg, which is related 
+            to -extranative SWIG option - SF #1971977.
+
+05/20/2008: wsfulton
+            New partialcheck makefile targets for partial testing of the test-suite. These
+            just invoke SWIG, ie no compilation and no runtime testing. It can be faster
+            when developing by just doing a directory diff of the files SWIG generates
+            against those from a previous run. Example usage from the top level directory:
+
+              make partialcheck-test-suite
+              make partialcheck-java-test-suite
+
+            This change also encompasses more flexibility in running the test-suite, eg
+            it is possible to prefix the command line which runs any target language test
+            with a tool. See the RUNTOOL, COMPILETOOL and SWIGTOOL targets in the common.mk
+            file and makefiles in the test-suite directory. For example it is possible to 
+            run the runtime tests through valgrind using:
+
+              make check RUNTOOL="valgrind --leak-check=full"
+
+            or invoke SWIG under valgrind using:
+
+              make check SWIGTOOL="valgrind --tool=memcheck"
+
+05/19/2008: drjoe
+            [R] Fixed define that was breaking pre-2.7.  Checked in
+            patch from Soren Sonnenburg that creates strings in  
+	    version independent way
+
+05/15/2008: wsfulton
+            [Java] Fix variable name clash in directors - SF #1963316 reported by Tristan.
+
+05/14/2008: wsfulton
+            Add an optimisation for functions that return objects by value, reducing
+            the number of copies of the object that are made. Implemented using an
+            optional attribute in the "out" typemap called "optimal". Details in 
+            Typemaps.html.
+
+05/11/2008: olly
+	    [PHP] Check for %feature("notabstract") when generating PHP5 class
+	    wrapper.
+
+05/11/2008: wsfulton
+            Fix SF #1943608 - $self substitution in %contract, patch submitted by
+            Toon Verstraelen.
+
+05/09/2008: olly
+	    [PHP] Fix char * typemaps to work when applied to signed char * and
+	    unsigned char * (uncovered by testcase apply_strings).
+
+05/09/2008: wsfulton
+            Fix wrapping of char * member variables when using allprotected mode.
+            Bug reported by Warren Wang.
+
+05/09/2008: olly
+	    [PHP] Fix bad PHP code generated when wrapping an enum in a
+	    namespace (uncovered by testcase arrays_scope).
+
+05/09/2008: olly
+	    [PHP] SWIG now runs the PHP testsuite using PHP5, not PHP4.  PHP4
+	    is essentially obsolete now, so we care much more about solid PHP5
+	    support.
+
+05/07/2008: wsfulton
+            STL fixes when using %import rather than %include and the Solaris Workshop
+            compiler and the Roguewave STL.
+
+05/07/2008: wsfulton
+            Fix wrapping of overloaded protected methods when using allprotected mode.
+            Bug reported by Warren Wang.
+
+05/03/2008: wsfulton
+            Commit patch #1956607 to add -MT support from Richard Boulton.
+            This patch mirrors the gcc -MT option which allows one to change the default
+            Makefile target being generated when generating makefiles with the -M family
+            of options. For example:
+
+              $ swig -java -MM -MT overiddenname -c++  example.i
+              overiddenname: \
+               example.i \
+               example.h 
+
+04/30/2008: mgossage
+	    [Lua] Removed generation of _wrap_delete_XXXXX (wrappered destructor)
+	    which was unused and causing warning with g++ -Wall.
+	    Removed other unused warning in typemaps.i and other places.
+	    Added Examples/lua/embed3, and run tests a few test cases.
+
+04/24/2008: olly
+	    [Python] Fix generated code for IBM's C++ compiler on AIX (patch
+	    from Goeran Uddeborg in SF#1928048).
+
+04/24/2008: olly
+	    Rename BSIZE in Examples/test-suite/arrays_scope.i to BBSIZE to
+	    avoid a clash with BSIZE defined by headers on AIX with Perl
+	    (reported in SF#1928048).
+
+04/20/2008: wsfulton
+            Add the ability to wrap all protected members when using directors.
+            Previously only the virtual methods were available to the target language.
+            Now all protected members, (static and non-static variables, non-virtual methods
+            and static methods) are wrapped when using the allprotected mode. The allprotected
+            mode is turned on in the module declaration:
+
+              %module(directors="1", allprotected="1") modulename
+
diff --git a/trunk/Doc/Devel/cmdopt.html b/trunk/Doc/Devel/cmdopt.html
new file mode 100644
index 0000000..c5f207c
--- /dev/null
+++ b/trunk/Doc/Devel/cmdopt.html
@@ -0,0 +1,79 @@
+<html>
+<head>
+<title>SWIG Command Line Handling</title>
+</head>
+
+<body>
+<center>
+<h1>SWIG Command Line Handling</h1>
+
+<p>
+David M. Beazley <br>
+dave-swig@dabeaz.com<br>
+December, 2006<br>
+
+</b>
+</center>
+
+<h2>Introduction</h2>
+
+This document describes the functions related to the handling of
+command line options passed to SWIG. These functions are defined in
+the header file <tt>Source/Swig/swigopt.h</tt>.  This API is
+considered to be stable.
+
+<h2>Initialization</h2>
+
+Upon SWIG startup, the following function is called:
+
+<p>
+<b><tt>void Swig_init_args(int argc, char **argv_)</tt></b>
+
+<blockquote>
+Registers command line options with the SWIG core.  This creates an internal array that is used by other
+functions to mark whether or not a particular command line option was used.  This is ultimately used to issue error messages about unused or unknown command line options.   This function is currently invoked in the SWIG main() function that is found in <tt>Source/Modules/swigmain.cxx</tt>.
+</blockquote>
+
+<h2>Argument Marking</h2>
+
+As command line options are are processed by language modules, the following functions are used
+to mark the arguments as used:
+
+<p>
+<b><tt>void Swig_mark_arg(int n)</tt></b>
+<blockquote>
+Mark argument number <tt>n</tt> as used. 
+</blockquote>
+
+<p>
+<b><tt>int Swig_check_marked(int n)</tt></b>
+<blockquote>
+Check to see if argument <tt>n</tt> has been marked.  Returns 0 or 1.
+</blockquote>
+
+<h2>Argument Checking</h2>
+
+The following function is used to check all of the command line options after parsing.  It looks at the marked list
+and issues an error message if any unconsumed arguments are found.
+
+<p>
+<b><tt>void Swig_check_options()</tt></b>
+<blockquote>
+Checks all command line options to see if they have all been processed.  If not, an error message is generated and
+execution terminates with a call to <tt>exit()</tt>.   This function is currently invoked in <tt>Source/Modules/main.cxx</tt> just before SWIG starts any processing of input files.
+</blockquote>
+
+<h2>Utility Function</h2>
+<p>
+<b><tt>void Swig_arg_error())</tt></b>
+
+<blockquote>
+A generic function that issues an error message about being unable to parse command line options.  SWIG is terminated by a call to <tt>exit()</tt>.
+
+</body>
+</html>
+
+
+
+
+
diff --git a/trunk/Doc/Devel/engineering.html b/trunk/Doc/Devel/engineering.html
new file mode 100644
index 0000000..5ccfb78
--- /dev/null
+++ b/trunk/Doc/Devel/engineering.html
@@ -0,0 +1,411 @@
+<html>
+<head>
+<title>SWIG Engineering Manual</title>
+</head>
+<body bgcolor="#ffffff">
+<center>
+<h1>SWIG Engineering Manual</h1>
+
+<b>David Beazley <br>
+</b>
+</center>
+
+<p>
+(Note : This is a work in progress.) 
+
+<h2>Table of Contents</h2>
+<ul>
+<li><a name="i1" href="#1">1. Introduction</a>
+<li><a name="i2" href="#2">2. Programming Languages and Libraries</a>
+<li><a name="i3" href="#3">3. The Source Directory and Module Names</a>
+<li><a name="i4" href="#4">4. Include Files</a>
+<li><a name="i5" href="#5">5. File Structure</a>
+<li><a name="i6" href="#6">6. Bottom-Up Design</a>
+<li><a name="i7" href="#7">7. Functions</a>
+<li><a name="i8" href="#8">8. Naming Conventions</a>
+<li><a name="i9" href="#9">9. Visibility</a>
+<li><a name="i10" href="#10">10. Miscellaneous Coding Guidelines</a>
+<li><a name="i11" href="#11">11. SVN Tagging Conventions</a>
+</ul>
+
+<a name="1" href="#i1">
+<h2>1. Introduction</h2>
+</a>
+
+The purpose of this document is to describe various coding conventions
+and organizational aspects for SWIG developers. The idea for this
+document is largely borrowed from John Ousterhout's Tcl/Tk Engineering
+Manual.  It is not my intent to overly managerial about matters--rather I'm
+hoping to make life a little less chaotic for everyone.
+
+<p>
+First a little background: SWIG was started in 1995 as a one-person
+project and continued in this mode of operation until about 1998.
+Most of this development was driven by ideas submitted by early SWIG
+users as opposed to being motivated by a grand design.  As a result,
+the code ended up being a pretty horrible C++ coding disaster.  A
+mostly working disaster perhaps, but a disaster nonetheless.
+
+<p>
+With that said, the primary goal of future SWIG development is to
+reengineer the original system, fix most of its inherent design flaws,
+and to produce what I hope will become a highly extensible and modular
+interface compiler framework.  To this do this, there are a few
+critical areas of work.  First, I want to restructure SWIG as a
+collection of loosely coupled modules written in either ANSI C or an
+scripting language.  Second, I want the system to be minimalistic in
+its use of data structures and interconnections.  The primary reason
+for this is that the fewer data structures there are, the less users
+will have to remember.  This will also make the system more accessible
+to non-experts.  Finally, I want to reevaluate the whole idea of a
+SWIG module is and expand the definition to include just about
+anything from parsers, preprocessors, optimizers, interface editors,
+and code generators.
+
+<p>
+The rest of this document outlines a few general rules of how code
+should be developed within the SWIG project.  These rules are
+primarily drawn from my own experience developing software and
+observing the practices of other successful projects.
+
+<a name="2" href="#i2">
+<h2>2. Programming Languages and Libraries </h2>
+</a>
+
+All SWIG modules must be written in either ANSI C or one of the
+scripting languages for which SWIG can generate an interface (e.g.,
+Perl, Python, or Tcl).  C++ is currently being used to write
+SWIG modules, but it is only being utilized to avoid working with 
+a lot of pointers to functions.  <b>Advanced C++ features like namespaces, templates,
+and overloading should not be used.</b>.
+
+<p>
+Module writers should make every attempt to use only those functions
+described in the POSIX.1 standard.  This includes most of the
+functions contained the Kernighan and Ritchie C programming book.  Use
+of operating system dependent functionality such as socket libraries
+should always be included inside a conditional compilation block so
+that it can be omitted on problematic platforms.  If you are unsure
+about a library call, check the man page or contact Dave.
+
+<a name="3" href="#i3">
+<h2>3. The Source Directory and Module Names</h2>
+</a>
+
+All SWIG modules are contained within the "Source" directory.  Within
+this directory, each module is placed into its own subdirectory.  The
+name of this subdirectory should exactly match the name of the module.
+For example, if you are creating a module called "Tcl", all of your
+files should be placed in a directory "Tcl".
+
+<p>
+When choosing a module name, please pick a name that is not
+currently in use.  As a general convention, the first letter of a
+module name is capitalized such as "Perl".  Alternatives such as
+"perl" or "PERL" should be avoided.  In certain instances, the first
+two letters may be capitalized as in "CParse."  The exact usage of
+this is somewhat inconsistent and isn't terribly important--just make
+sure the first letter is capitalized.  Also, module names should not
+start with numbers, include underscores or any other special
+non-alphanumeric characters.
+
+<a name="5" href="#i5">
+<h2>5. File Structure </h2>
+</a>
+
+Each file in a module should be given a filename that is all lowercase letters
+such as "parser.c", not "Parser.c" or "PARSER.c".   Please note that filenames
+are case-insensitive on Windows so this convention will prevent you from inadvertently
+creating two files that differ in case-only.
+
+<p>
+Each file should include a short abstract, author information, copyright information, and
+a SVN revision tag like this:
+
+<blockquote>
+<pre>
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cwrap.c
+ *
+ * This file defines a variety of wrapping rules for C/C++ handling including
+ * the naming of local variables, calling conventions, and so forth.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_cwrap_c[] = "$Id$";
+
+#include "swig.h"
+
+/* Declarations */
+typedef struct {
+   int x, y;
+} Foo;
+
+...
+
+/* Private Declarations (used only in this file) */
+static int  avariable;
+
+...
+
+/* Functions */
+... 
+
+</pre>
+</blockquote>
+
+The SVN revision tag should be placed into a static string as shown
+above mangled with the name of the file.
+This adds the revision information to the SWIG executable and
+makes it possible to extract version information from a raw binary
+(sometimes useful in debugging).  
+
+<p>
+As a general rule, files start to get unmanageable once they exceed
+about 2000 lines.  Files larger than this should be broken up into
+multiple files.  Similarly, you should avoid the temptation to create
+many small files as this increases compilation time and makes the
+directory structure too complicated.
+
+<a name="6" href="#i6">
+<h2>6. Bottom-Up Design </h2>
+</a>
+
+Within each source file, the preferred organization is to use what is
+known as "bottom-up" design.  Under this scheme, lower-level functions
+appear first and the highest level function appears last.  The easy
+way to remember is that the "main" function of your module should
+always appear last in the source file.  For example:
+
+<blockquote>
+<pre>
+/* Simple bottom-up program */
+#include &lt;stdio.h&gt;
+
+int foo(int x, int y) {
+    /* Implement foo */
+    ...
+}
+
+int bar() {
+    ...
+    foo(i,j);
+    ...
+}
+
+...
+int main(int argc, char **argv) {
+    ...
+    bar();   
+    ...
+}
+</pre>
+</blockquote>
+
+This choice of design is somewhat arbitrary however it has a number of
+benefits particular to C. In particular, a bottom-up design generally
+eliminates the need to include forward references--resulting in
+cleaner code and fewer compilation errors.
+
+<a name="7" href="#i7">
+<h2>7. Functions</h2>
+</a>
+
+All functions should have a function header that gives the function name
+and a short description like this:
+
+<blockquote>
+<pre>
+/* -------------------------------------------------------------------------
+ * Swig_add_directory()
+ *
+ * Adds a directory to the SWIG search path.
+ * ------------------------------------------------------------------------- */
+
+void 
+Swig_add_directory(DOH *dirname) {
+...
+
+}
+</pre>
+</blockquote>
+
+In the function declaration, the return type and any specifiers
+(extern or static) should appear on a separate line followed by the
+function name and arguments as shown above.  The left curly brace
+should appear on the same line as the function name.
+
+<p>
+Function declarations should <b>NOT</b> use the pre-ANSI function
+declaration syntax.   The ANSI standard has been around long enough for 
+this to be a non-issue.
+
+<a name="8" href="#i8">
+<h2>8. Naming Conventions</h2>
+</a>
+
+The following conventions are used to name various objects throughout SWIG.
+
+<h4>Functions</h4>
+
+Functions should consist of the module name and the function name separated by an underscore like this:
+
+<blockquote>
+<pre>
+Preprocessor_define()
+Swig_add_directory()
+</pre>
+</blockquote>
+
+In general, the module name should match the name of the module
+subdirectory and the function name should be in all lowercase with
+words separated by underscores.
+
+<h4>Structures and Types</h4>
+
+If your module defines new structures, the structure name should include the name of the
+module and the name of the structure appended together like this:
+
+<blockquote>
+<pre>
+typedef struct SwigScanner {
+   ...
+} SwigScanner;
+
+typedef struct LParseType {
+   ...
+} LParseType;
+</pre>
+</blockquote>
+
+In this case, both the name of the module and the type should be capitalized.  Also, whenever
+possible, you should use the "typedef struct Name { ... } Name" form when defining new
+data structures. 
+
+<h4>Global Variables</h4>
+
+Global variables should be avoided if at all possible.  However, if you must use a global
+variable, please prepend the module name and use the same naming scheme as for functions.
+
+<h4>Constants</h4>
+
+Constants should be created using #define and should be in all caps like this:
+
+<blockquote>
+<pre>
+#define   SWIG_TOKEN_LPAREN  1
+</pre>
+</blockquote>
+
+Separate words in a constant should be separated by underscores as with functions.
+
+<h4>Structure members</h4>
+
+Structure members should be in all lower-case and follow the same word-separation convention
+as for function names.  However, the module name does not have to be included.
+For example:
+
+<blockquote>
+<pre>
+typedef struct SwigScanner {
+  DOH           *text;           /* Current token value */
+  DOH           *scanobjs;       /* Objects being scanned */
+  DOH           *str;            /* Current object being scanned */
+  char          *idstart;        /* Optional identifier start characters */
+  int            next_token;     /* Next token to be returned */
+  int            start_line;     /* Starting line of certain declarations */
+  int            yylen;          /* Length of text pushed into text */
+  DOH           *file;           /* Current file name */
+} SwigScanner;
+</pre>
+</blockquote>
+
+<h4>Static Functions and Variables </h4>
+
+Static declarations are free to use any naming convention that is appropriate. However, most
+existing parts of SWIG use lower-case names and follow the same convention as described for functions.
+
+<a name="9" href="#i9">
+<h2>9. Visibility</h2>
+</a>
+
+Modules should keep the following rules in mind when exposing their internals:
+
+<ul>
+<li>Only publicly accessible functions should be included in the module header file.
+<li>All non-static declarations must be prepended with some form of the module name
+to avoid potential linker namespace conflicts with other modules.
+<li>Modules should not expose global variables or use global variables in their
+public interface.
+<li>Similarly, modules should discourage the direct manipulation of data contained
+within data structures in favor of using function calls instead.  For example,
+instead of providing a user with a structure like this:
+
+<blockquote>
+<pre>
+typedef struct Foo {
+   int line;
+} Foo;
+</pre>
+</blockquote>
+
+It is better to hide the implementation of Foo and provide an
+function-call interface like this:
+
+<blockquote>
+<pre>
+typedef struct Foo Foo;
+extern int  Foo_getline(Foo *f);
+extern void Foo_setline(Foo *f, int line);
+</pre>
+</blockquote>
+
+Although this results in worse performance, there are many practical
+reasons for doing this.  The most important reason is that it allows
+you to change the internal representation of Foo without breaking all
+of the other modules or having to recompile the entire universe after
+making your changes.
+
+</ul>
+
+<a name="10" href="#i10">
+<h2>10. Miscellaneous Coding Guidelines</h2>
+</a>
+These are largely covered in the main documentation in the Extending.html file.
+
+<a name="11" href="#i11">
+<h2>11. SVN Tagging Conventions</h2>
+</a>
+
+Use <tt>svn tag</tt> to declare some set of file revisions as related in some
+symbolic way.  This eases reference, retrieval and manipulation of these files
+later.  At the moment (2001/01/16 14:02:53), the conventions are very simple;
+let's hope they stay that way!
+
+<p>
+There are two types of tags, internal (aka personal) and external.
+Internal tags are used by SWIG developers primarily, whereas external
+tags are used when communicating with people w/ anonymous svn access.
+<ul>
+<li> Internal tags should start with the developer name and a hyphen.
+<li> External tags should start with "v-".
+</ul>
+
+That's all there is to it.  Some example tags:
+
+<ul>
+<li> ttn-pre-xml-patch
+<li> ttn-post-xml-patch
+<li> ttn-going-on-vacation-so-dutifully-tagging-now
+<li> v-1-3-a37-fixes-bug-2432
+<li> v-1-3-a37-fixes-bug-2433
+<li> v-1-3-a37-fixes-bug-2432-again
+<li> v-1-3-a37-release
+</ul>
+
+<hr>
+Copyright (C) 1999-2004 SWIG Development Team.
+</body>
+</html>
diff --git a/trunk/Doc/Devel/file.html b/trunk/Doc/Devel/file.html
new file mode 100644
index 0000000..77ad7ed
--- /dev/null
+++ b/trunk/Doc/Devel/file.html
@@ -0,0 +1,181 @@
+<html>
+<head>
+<title>SWIG File Handling</title>
+</head>
+
+<body>
+<center>
+<h1>SWIG File Handling</h1>
+
+<p>
+David M. Beazley <br>
+dave-swig@dabeaz.com<br>
+December, 2006<br>
+
+</b>
+</center>
+
+<h2>Introduction</h2>
+
+This document describes the functions related to file and filename handling in the SWIG core.   These functions are
+defined in the header file <tt>Source/Swig/swigfile.h</tt>.   This API is considered to be stable.
+
+<h2>File Search Path</h2>
+
+These functions manipulate the search path for locating files.
+
+<p>
+<b><tt>List *Swig_add_directory(const String_or_char *dirname)</tt></b>
+
+<blockquote>
+Adds a new directory to the system search path.  The directory is appended to
+the end of the search path.  Returns a list containing the current
+system search path. 
+</blockquote>
+
+<p>
+<b><tt>void Swig_push_directory(const String_or_char *dirname)</tt></b>
+<blockquote>
+Pushes a temporary directory onto the search path.  This directory is searched before 
+directories added with <tt>Swig_add_directory()</tt> except when including a system
+file explicitly (either using #include &lt;file&gt; or calling <tt>Swig_include_sys()</tt>).
+This function is normally used by the preprocessor to add temporary directories when
+processing #include statements.
+</blockquote>
+
+<p>
+<b><tt>void Swig_pop_directory()</tt></b>
+<blockquote>
+Pops off the last pushed directory with <tt>Swig_push_directory()</tt>
+</blockquote>
+
+<p>
+<b><tt>int Swig_get_push_dir()</tt></b>
+
+<blockquote>
+Returns a flag that indicates whether directory pushing is enabled or not.
+</blockquote>
+
+<p>
+<b><tt>void Swig_set_push_dir(int dopush)</tt></b>
+<blockquote>
+Enables or disables directory pushing.  By default, it is turned on.  However, the <tt>-I-</tt> command line
+option to SWIG disables it.
+</blockquote>
+
+<p>
+<b><tt>List *Swig_search_path()</tt></b>
+<blockquote>
+Returns the current search path.
+</blockquote>
+
+
+<h2>File access functions</h2>
+
+<p>
+<b><tt>FILE *Swig_open(const String_or_char *name)</tt></b>
+
+<blockquote>
+Opens a file, using the applicable search paths, and returns an open <tt>FILE *</tt> object if found.  Returns NULL if the file is not found.
+</blockquote>
+
+<p>
+<b><tt>String *Swig_read_file(FILE *f)</tt></b>
+
+<blockquote>
+Reads all of the data from an open file into a string which is returned.
+</blockquote>
+
+<p>
+<b><tt>String *Swig_include(const String_or_char *name)</tt></b>
+
+<blockquote>
+Searches for an include file <tt>name</tt> and returns its contents as
+a string if found.  Returns NULL if not found.  All of the applicable
+search paths are searched when trying to locate the file.
+</blockquote>
+
+<p>
+<b><tt>String *Swig_include_sys(const String_or_char *name)</tt></b>
+
+<blockquote>
+Searches for an include file <tt>name</tt> and returns its contents as
+a string if found.  Returns NULL if not found.  All of the applicable
+search paths are searched when trying to locate the file, but
+preference is given to system paths first. This mimics the behavior
+of <tt>#include &lt;file&gt;</tt> in the preprocessor.
+</blockquote>
+
+<p>
+<b><tt>int Swig_insert_file(const String_or_char *name, File *outfile)</tt></b>
+
+<blockquote>
+Searches for a file <tt>name</tt> and dumps its contents to <tt>outfile</tt> if found.
+Returns 0 on success, -1 if the file couldn't be found.
+</blockquote>
+
+<h2>Query functions</h2>
+
+<p>
+<b><tt>String *Swig_last_file()</tt></b>
+
+<blockquote>
+Returns the full pathname of the file last opened or included.
+</blockquote>
+
+<h2>Named files</h2>
+
+<p>
+<b><tt>void *Swig_register_filebyname(const String_or_char *filename, File *outfile)</tt></b>
+
+<blockquote>
+Registers a file object <tt>outfile</tt> with a specific name <tt>filename</tt>.   This function is
+used to implement the SWIG %insert directive and to manage different sections of the output
+file such as "runtime","header","wrapper","init", etc.   Different language modules may add their own
+sections for generating Python code, Perl code, etc.
+</blockquote>
+
+<p>
+<b><tt>File *Swig_filebyname(const String_or_char *filename)</tt></b>
+<blockquote>
+This looks up a file object previously registered using <tt>Swig_register_filebyname()</tt>.  This 
+is used to implement the %insert directive.
+</blockquote>
+
+<h2>Filename utilities</h2>
+
+<p>
+<b><tt>char *Swig_file_suffix(const String_or_char *filename)</tt></b>
+<blockquote>
+Returns the suffix of a filename.  For instance, if the filename is "foo.txt", it returns ".txt".
+</blockquote>
+
+<p>
+<b><tt>char *Swig_file_basename(const String_or_char *filename)</tt></b>
+<blockquote>
+Returns the filename without the suffix attached to it.  For instance, if the filename is "foo.txt", it returns
+"foo".  The result is stored in a static variable. If you need to save it, make your own copy.
+</blockquote>
+
+<p>
+<b><tt>char *Swig_file_filename(const String_or_char *filename)</tt></b>
+<blockquote>
+Returns the filename without any leading directories.  For instance, if the filename is "/bar/spam/foo.txt", it
+returns "foo.txt".   This function is aware of local naming conventions on the machine (e.g., forward versus back slashes on Unix and Windows).   The result is stored in a static variable.  If you need to save the value, make a copy.
+</blockquote>
+
+<p>
+<b><tt>char *Swig_file_dirname(const String_or_char *filename)</tt></b>
+<blockquote>
+Returns the directory name (if any).  For instance, if the filename is "/bar/spam/foo.txt", it
+returns "/bar/spam/".   This function is aware of local naming conventions on the machine (e.g., forward versus back slashes on Unix and Windows).  The result is stored in a static variable.  If you need to save the value, make a copy.
+</blockquote>
+
+<p>
+<b><tt>SWIG_FILE_DELIMITER</tt></b>
+<blockquote>
+This macro contains the file delimiter string for the local machine.  On Unix it is "/", on Windows it is "\\".
+</blockquote>
+
+</body>
+</html>
diff --git a/trunk/Doc/Devel/index.html b/trunk/Doc/Devel/index.html
new file mode 100644
index 0000000..55c612e
--- /dev/null
+++ b/trunk/Doc/Devel/index.html
@@ -0,0 +1,30 @@
+<html>
+<head>
+<title>SWIG Documentation</title>
+</head>
+
+<body>
+This directory contains SWIG documentation:
+
+<ul>
+<li><a href="engineering.html">Engineering Manual</a>
+<li><a href="internals.html">Internals Manual</a>
+<li><a href="migrate.txt">SWIG1.3 Migration Guide</a>
+</ul>
+
+The following documentation describe the internal APIs used by SWIG.  These may be useful to module developers.
+
+<ul>
+<li><a href="file.html">File handling functions</a>
+<li><a href="cmdopt.html">Command line arguments</a>
+<li><a href="tree.html">Parse tree navigation and manipulation</a>
+<li><a href="parm.html">Parameter and Parameter list handling functions</a>
+<li><a href="scanner.html">Generic C/C++ Scanner interface</a>
+<li><a href="wrapobj.html">Wrapper objects</a>.
+</ul>
+
+<hr>
+Copyright (C) 1999-2007 SWIG Development Team.
+
+</body>
+</html>
diff --git a/trunk/Doc/Devel/internals.html b/trunk/Doc/Devel/internals.html
new file mode 100644
index 0000000..ea36f84
--- /dev/null
+++ b/trunk/Doc/Devel/internals.html
@@ -0,0 +1,1102 @@
+<html>
+<head>
+<title>SWIG Internals</title>
+</head>
+
+<body>
+<center>
+<h1>SWIG Internals Manual</h1>
+
+<b>Thien-Thi Nguyen <br>
+
+<p>
+David M. Beazley <br>
+
+</b>
+</center>
+
+<p>
+
+<p>
+(Note : This is a work in progress.) 
+
+<h2>Table of Contents</h2>
+<ul>
+<li><a name="i1" href="#1">1. Introduction</a>
+<ul>
+<li><a name="i1.1" href="#1.1">1.1 Directory Guide</a>
+<li><a name="i1.2" href="#1.2">1.2 Overall Program Flow</a>
+</ul>
+<li><a name="i2" href="#2">2. DOH</a>
+<ul>
+<li><a name="i2.1" href="#2.1">2.1 Motivation and Background</a>
+<li><a name="i2.2" href="#2.2">2.2 Basic Types</a>
+<li><a name="i2.3" href="#2.3">2.3 Creating, Copying and Destroying Objects</a>
+<li><a name="i2.4" href="#2.4">2.4 A Word About Mutability and Copying</a>
+<li><a name="i2.5" href="#2.5">2.5 Strings</a>
+<li><a name="i2.6" href="#2.6">2.6 Lists</a>
+<li><a name="i2.7" href="#2.7">2.7 Hash Tables</a>
+<li><a name="i2.8" href="#2.8">2.8 Files</a>
+<li><a name="i2.9" href="#2.9">2.9 Void Objects</a>
+<li><a name="i2.10" href="#2.10">2.10 Utility Functions</a>
+</ul>
+<li><a name="i3" href="#3">3. Types and Typemaps</a>
+<li><a name="i4" href="#4">4. Parsing</a>
+<li><a name="i5" href="#5">5. Difference Between SWIG 1.1 and SWIG 1.3</a>
+<li><a name="i6" href="#6">6. Plans for SWIG 2.0</a>
+<li><a name="i7" href="#7">7. C/C++ Wrapper Support Functions</a>
+<li><a name="i8" href="#8">8. Symbol Naming Guidelines for Generated C/C++ Code</a>
+<li><a name="i9" href="#9">9. Debugging SWIG</a>
+</ul>
+
+<a name="1" href="#i1">
+<h2>1. Introduction</h2>
+</a>
+
+This document details SWIG internals: architecture and sometimes
+implementation.  The first few sections concentrate on data structures,
+interfaces, conventions and code shared by all language targets.
+Subsequent sections focus on a particular language.
+
+<p>
+The audience is assumed to be SWIG developers (who should also read the
+<a href="engineering.html">SWIG Engineering Manual</a> before starting
+to code).
+
+<a name="1.1" href="#i1.1">
+<h3>1.1 Directory Guide</h3>
+</a>
+
+<table border=1>
+<tr><td><a href="index.html">Doc</a></td>
+<td>HTML documentation.  If you find a documentation bug, please
+<a href="mailto:bug-swig-doc@glug.org">let us know</a>.</td>
+</tr>
+
+<tr><td>Examples</td>
+<td>This subdir tree contains examples of using SWIG w/ different
+scripting languages, including makefiles.  Typically, there are the
+"simple" and "matrix" examples, w/ some languages offering additional
+examples.  The GIFPlot example has its own set of per-language
+subdirectories.  See the README more index.html file in each directory
+for more info.  [FIXME: Ref SWIG user manual.]</td>
+</tr>
+
+<tr><td>Lib</td>
+<td>These are the <tt>.i</tt> (interface) files that form the SWIG
+installed library.  Language-specific files are in subdirectories (for
+example, guile/typemaps.i).  Each language also has a <tt>.swg</tt> file
+implementing runtime type support for that language.  The SWIG library
+is not versioned.</td>
+</tr>
+
+<tr><td>Misc</td>
+<td>Currently this subdir only contains file <tt>fileheader</tt>.  See
+the <a href="engineering.html">Engineering Manual</a> for more
+info.</td>
+</tr>
+
+<tr><td>Source</td>
+<td>SWIG source code is in this subdir tree.  Directories marked w/ "(*)"
+are used in building the <tt>swig</tt> executable. 
+
+  <table border=1>
+
+  <tr><td>DOH (*)</td>
+  <td>C library providing memory allocation, file access and generic
+  containers.  Result: libdoh.a</td>
+  </tr>
+
+  <tr><td>Experiment</td>
+  <td>[TODO]</td>
+  </tr>
+
+  <tr><td>Include (*)</td>
+  <td>Configuration .h files</td>
+  </tr>
+
+  <tr><td>LParse</td>
+  <td>Parser (lex / yacc) files and support [why not (*)?!]</td>
+  </tr>
+
+  <tr><td>Modules</td>
+  <td>[TODO]</td>
+  </tr>
+
+  <tr><td>Modules1.1 (*)</td>
+  <td>Language-specific callbacks that does actual code generation (each
+  language has a .cxx and a .h file).  Result: libmodules11.a</td>
+  </tr>
+
+  <tr><td>Preprocessor (*)</td>
+  <td>SWIG-specialized C/C++ preprocessor.  Result: libcpp.a</td>
+  </tr>
+
+  <tr><td>SWIG1.1 (*)</td>
+  <td>Parts of SWIG that are not language-specific, including option
+  processing and the type-mapping system.  Result: libswig11.a.
+  Note: This directory is currently being phased out. </td>
+  </tr>
+
+  <tr><td>SWIG1.3</td>
+  <td>[TODO] [funny, nothing here is presently used for swig-1.3].
+  This directory might turn into a compatibility interface between
+  SWIG1.3 and the SWIG1.1 modules.</td>
+  </tr>
+
+  <tr><td>Swig (*)</td>
+  <td>This directory contains the new ANSI C core of the system
+  and contains generic functions related to types, file handling,
+  scanning, and so forth.</td>
+  </tr>
+
+  </table></td>
+</tr>
+
+<tr><td>Tools</td>
+<td>Libtool support and the mkdist.py script.</td>
+</tr>
+
+<tr><td>Win</td>
+<td>This improperly-named (spit spit) subdir only has README.txt.</td>
+</tr>
+
+</table>
+
+
+<a name="1.2" href="#1.2">
+<h3>1.2 Overall Program Flow</h3>
+</a>
+
+Here is the general control flow and where under subdir <tt>Source</tt>
+to look for code:
+
+<ul>
+
+<li> <tt>Modules1.1/swigmain.cxx:main()</tt> is the program entry
+point.  It parses the language-specifying command-line option (for
+example, <tt>-java</tt>), creating a new language-specific wrapping
+object (each language is a C++ class derived from base class
+<tt>Language</tt>).  This object and the command-line is passed to
+<tt>SWIG_main()</tt>, whose return value is the program exit value.
+
+<li> <tt>SWIG1.1/main.cxx:SWIG_main()</tt> is the "real" main.  It
+initializes the preprocessor and typemap machinery, defines some
+preprocessor symbols, locates the SWIG library, processes common
+command-line options, and then calls the language-specific command-line
+parser.  From here there are three paths: "help", "checkout" and
+everything else.
+  <ul>
+  <li> In "help" mode, clean up open files and exit.
+  <li> In "checkout" mode, copy specified files from the SWIG library
+       to the current directory.  Errors cause error messages but no
+       non-local exits. 
+  <li> Otherwise, do wrapping: determine output file name(s), define
+       some preprocessor symbols and run the preprocessor, initialize
+       the interface-definition parser, set up the typemap for handling
+       new return strings, and finally do the language-specific parse
+       (by calling the language object's <tt>parse()</tt> method), which
+       creates output files by side-effect.
+  </ul>
+Afterwards, remove temporary files, and clean up.  If the command-line
+included <tt>-freeze</tt>, go into an infinite loop; otherwise return the
+error count.
+
+<li> The language-specific <tt>parse()</tt> (and all other
+language-specific code) lives in <tt>Modules1.1/foo.{h,cxx}</tt> for
+language Foo.  Typically, <tt>FOO::parse()</tt> calls
+<tt>FOO::headers()</tt> and then the global function <tt>yyparse()</tt>,
+which uses the callbacks registered by <tt>SWIG_main()</tt> above. 
+
+</ul>
+
+<a name="2" href="#i2">
+<h2>2. DOH</h2>
+</a>
+
+DOH is a collection of low-level objects such as strings, lists, and
+hash tables upon which the rest of SWIG is built.  The name 'DOH'
+unofficially stands for "Dave's Object Hack", but it's also a good
+expletive to use when things don't work (as in "SWIG core
+dumped---DOH!").
+
+<a name="2.1" href="#2.1">
+<h3>2.1  Motivation and Background</h3>
+</a>
+
+The development of DOH is influenced heavily by the problems
+encountered during earlier attempts to create a C++ based version of
+SWIG2.0.  In each of these attempts (over a 3 year period), the
+resulting system always ended up growing into a colossal nightmare of
+large inheritance hierarchies and dozens of specialized classes for
+different types of objects (functions, variables, constants, etc.).
+The end result was that the system was tremendously complicated,
+difficult to understand, difficult to maintain, and fairly inflexible
+in the grand scheme of things.
+
+<p>
+DOH takes a different approach to tackling the complexity problem.
+First, rather than going overboard with dozens of types and class
+definitions, DOH only defines a handful of simple yet very useful
+objects that are easy to remember.  Second, DOH uses dynamic
+typing---one of the features that make scripting languages so useful
+and which make it possible to accomplish things with much less code.
+Finally, DOH utilizes a few coding tricks that allow it to perform
+a limited form of function overloading for certain C datatypes (more
+on that a little later). 
+
+<p>
+The key point to using DOH is that instead of thinking about code in
+terms of highly specialized C data structures, just about everything
+ends up being represented in terms of a just a few datatypes. For
+example, structures are replaced by DOH hash tables whereas arrays are
+replaced by DOH lists.  At first, this is probably a little strange to
+most C/C++ programmers, but in the long run in makes the system
+extremely flexible and highly extensible.  Also, in terms of coding,
+many of the newly DOH-based subsystems are less than half the size (in
+lines of code) of the earlier C++ implementation.
+
+<a name="2.2" href="#i2.2">
+<h3>2.2 Basic Types</h3>
+</a>
+
+The following built-in types are currently provided by DOH:
+
+<ul>
+<li><b>String</b>.  A string of characters with automatic memory
+management and high-level operations such as string replacement.  In addition,
+strings support file I/O operations that make it possible to use them just
+about anyplace a file can be used.
+
+<p>
+<li><b>List</b>. A list of arbitrary DOH objects (of possibly mixed types). 
+
+<p>
+<li><b>Hash</b>. A hash table that maps a set of string keys to a set of arbitrary
+DOH objects.  The DOH version of an associative array for all of you Perl fans.
+
+<p>
+<li><b>File</b>. A DOH wrapper around the C FILE * structure.  This is provided
+since other objects sometimes want to behave like files (strings for instance).
+
+<p>
+<li><b>Void</b>. A DOH wrapper around an arbitrary C pointer.  This can be used
+if you want to place arbitrary C data structures in DOH lists and hash tables.
+</ul>
+
+Due to dynamic typing, all of the objects in DOH are represented by pointers
+of type <tt>DOH *</tt>.  Furthermore, all objects are completely
+opaque--that means that the only way to access the internals of an
+object is through a well-defined public API.   For convenience, the following
+symbolic names are sometimes used to improve readability:
+
+<ul>
+<Li><tt>DOHString *</tt>.  A String object.
+<li><tt>DOHList *</tt>. A list object.
+<li><tt>DOHHash *</tt>. A hash object.
+<li><tt>DOHFile *</tt>. A file object.
+<li><tt>DOHVoid *</tt>. A void object.
+<li><tt>DOHString_or_char *</tt>. A DOH String object or a raw C "char *".
+</ul>
+
+It should be stressed that all of these names are merely symbolic aliases to the
+type <tt>DOH *</tt> and that no compile-time type checking is performed (of course,
+a runtime error may occur if you screw up).
+
+<a name="2.3" href="#i2.3">
+<h3>2.3 Creating, Copying, and Destroying Objects </h3>
+</a>
+
+The following functions can be used to create new DOH objects
+
+<ul>
+<Li><tt>NewString(DOHString_or_char *value)</tt><br>
+Create a new string object with contents initially
+set to value.  value can be either a C string or a DOH string object.
+
+<p>
+<li><tt>NewStringf(char *fmt, ...)</tt><br>
+Create a new string object with contents initially set to
+a formatted string.  Think of this as being sprintf() combined with an object constructor.
+
+<p>
+<li><tt>NewList()</tt><br>
+Create a new list object that is initially empty.
+
+<p>
+<Li><tt>NewHash()</tt><br>
+Create a new hash object that is initially empty.
+
+<p>
+<li><tt>NewFile(DOHString_or_char *filename, char *mode)</tt><br>
+Open a file and return a file object.  This is a
+wrapper around the C <tt>fopen()</tt> library call.
+
+<p>
+<li><tt>NewFileFromFile(FILE *f)</tt><br>
+Create a new file object given an already opened <tt>FILE *</tt> object.
+
+<p>
+<li><tt>NewVoid(void *obj, void (*del)(void *))</tt><br>
+Create a new DOH object that is a wrapper around an
+arbitrary C pointer.  <tt>del</tt> is an optional destructor function that will be called when the object
+is destroyed.
+
+</ul>
+
+Any object can be copied using the <tt>Copy()</tt> function. For example:
+
+<blockquote>
+<pre>
+DOH *a, *b, *c, *d;
+a = NewString("Hello World");
+b = NewList();
+c = Copy(a);         /* Copy the string a */
+d = Copy(b);         /* Copy the list b */
+</pre>
+</blockquote>
+
+Copies of lists and hash tables are shallow.  That is, their contents are only copied by reference.
+
+<p>
+Objects can be deleted using the <tt>Delete()</tt> function. For example:
+
+<blockquote>
+<pre>
+DOH *a = NewString("Hello World");
+...
+Delete(a);              /* Destroy a */
+</pre>
+</blockquote>
+
+All objects are referenced counted and given a reference count of 1 when initially created.  The
+<tt>Delete()</tt> function only destroys an object when the reference count reaches zero.  When
+an object is placed in a list or hash table, it's reference count is automatically increased. For example:
+
+<blockquote>
+<pre>
+DOH *a, *b;
+a = NewString("Hello World");
+b = NewList();
+Append(b,a);         /* Increases refcnt of a to 2 */
+Delete(a);           /* Decreases refcnt of a to 1 */
+Delete(b);           /* Destroys b, and destroys a */
+</pre>
+</blockquote>
+
+Should it ever be necessary to manually increase the reference count of an object, the DohIncref() function
+can be used:
+
+<blockquote>
+<pre>
+DOH *a = NewString("Hello");
+DohIncref(a);
+</pre>
+</blockquote>
+
+<a name="2.4" href="#i2.4">
+<h3>2.4 A Word About Mutability and Copying</h3>
+</a>
+
+All DOH objects are mutable regardless of their current reference
+count.  For example, if you create a string and then create a 1000
+references to it (in lists and hash tables), changes to the string
+will be reflected in all of the references.  Therefore, if you need to
+make any kind of local change, you should first make a copy using the
+Copy() function.  Caveat:  when copying lists and hash tables, elements
+are copied by reference.
+
+<a name="2.5" href="#i2.5">
+<h3>2.5 Strings</h3>
+</a>
+
+The DOH String type is perhaps the most flexible object.  First, it supports a variety of string-oriented
+operations.  Second, it supports many of the same operations as lists.  Finally, strings provide file I/O
+operations that allow them to be used interchangeably with DOH file objects.
+
+[ TODO ]
+
+<a name="2.6" href="#i2.6">
+<h3>2.6 Lists</h3>
+</a>
+
+<p>
+Example usage of lists:
+</p>
+
+<blockquote>
+<pre>
+/* Create and populate */
+List *list = NewList();
+Append(list, NewString("listval1"));
+Append(list, NewString("listval2"));
+Append(list, NewString("listval3"));
+Append(list, NewString("listval4"));
+Append(list, NewString("listval5"));
+
+/* Size */
+Printf(stdout, "list len: %d\n", Len(list));
+
+/* Delete */
+Delitem(list, 3);
+
+/* Replace */
+Setitem(list, 0, NewString("newlistval1"));
+
+/* Get */
+String *item = Getitem(list,1);
+if (item)
+  Printf(stdout, "get: %s\n", item);
+else
+  Printf(stdout, "get: [non-existent]\n");
+
+/* Iterate through the container */
+int len = Len(list);
+for (int i=0; i&lt;len; i++) {
+  String *item = Getitem(list,i);
+  Printf(stdout, "list item: %s\n", item);
+}
+</blockquote>
+</pre>
+
+<p>
+Resulting output:
+</p>
+
+<blockquote>
+<pre>
+hash len: 5
+get: hashval2
+hash item: hashval5 [h5]
+hash item: hashval1 [h1]
+hash item: hashval2 [h2]
+hash item: hashval3 [h3]
+</pre>
+</blockquote>
+
+<a name="2.7" href="#i2.7">
+<h3>2.7 Hash tables </h3>
+</a>
+
+<p>
+Example usage of hash tables:
+</p>
+
+<blockquote>
+<pre>
+/* Create and populate */
+Hash *hash = NewHash();
+Setattr(hash, "h1", NewString("hashval1"));
+Setattr(hash, "h2", NewString("hashval2"));
+Setattr(hash, "h3", NewString("hashval3"));
+Setattr(hash, "h4", NewString("hashval4"));
+Setattr(hash, "h5", NewString("hashval5"));
+
+/* Size */
+Printf(stdout, "hash len: %d\n", Len(hash));
+
+/* Delete */
+Delattr(hash, "h4");
+
+/* Get */
+String *item = Getattr(hash, "h2");
+if (item)
+  Printf(stdout, "get: %s\n", item);
+else
+  Printf(stdout, "get: [non-existent]\n");
+
+/* Iterate through the container */
+Iterator it;
+for (it = First(hash); it.key; it= Next(it))
+  Printf(stdout, "hash item: %s [%s]\n", (it.item), (it.key));
+</pre>
+</blockquote>
+
+<p>
+Resulting output:
+</p>
+
+<blockquote>
+<pre>
+list len: 5
+get: listval2
+list item: newlistval1
+list item: listval2
+list item: listval3
+list item: listval5
+</pre>
+</blockquote>
+
+<a name="2.8" href="#i2.8">
+<h3>2.8 Files </h3>
+</a>
+
+[ TODO ]
+
+<a name="2.9" href="#i2.9">
+<h3>2.9 Void objects </h3>
+</a>
+
+[ TODO ]
+
+<a name="2.10" href="#i2.10">
+<h3>2.10 Utility functions </h3>
+</a>
+
+[ TODO ]
+
+<a name="3" href="#i3">
+<h2>3. Types and Typemaps</h2>
+</a>
+
+<p>
+The representation and manipulation of types is currently in the
+process of being reorganized and (hopefully) simplified.  The
+following list describes the current set of functions that are used to
+manipulate datatypes.  These functions are different than in
+SWIG1.1 and may change names in the final SWIG1.3 release.
+
+<ul>
+<li><tt>SwigType_str(SwigType *t, char *name)</tt>.<br>
+ This function produces the exact string 
+representation of the datatype <tt>t</tt>.  <tt>name</tt> is an optional parameter that 
+specifies a declaration name.   This is used when dealing with more complicated datatypes
+such as arrays and pointers to functions where the output might look something like
+"<tt>int (*name)(int, double)</tt>".
+
+<p>
+<li><tt>SwigType_lstr(SwigType *t, char *name)</tt>.<br>
+This function produces a string
+representation of a datatype that can be safely be assigned a value (i.e., can be used as the
+"lvalue" of an expression).   To do this, qualifiers such as "const", arrays, and references
+are stripped away or converted into pointers.  For example:
+
+<blockquote>
+<pre>
+Original Datatype              lstr()
+------------------             --------
+const char *a                  char *a
+double a[20]                   double *a
+double a[20][30]               double *a
+double &amp;a                      double *a
+</pre>
+</blockquote>
+
+The intent of the lstr() function is to produce local variables inside wrapper functions--all
+of which must be reassignable types since they are the targets of conversions from a scripting
+representation. 
+
+<p>
+<li><tt>SwigType_rcaststr(SwigType *t, char *name)</tt>.
+<br>  This function produces a string
+that casts a type produced by the <tt>lstr()</tt> function to the type produced by the
+<tt>str()</tt> function.  You might view it as the inverse of lstr().   This function only produces
+output when it needs to (when str() and lstr() produce different results).  Furthermore, an optional
+name can be supplied when the cast is to be applied to a specific name.   Examples:
+
+<blockquote>
+<pre>
+Original Datatype             rcaststr()
+------------------            ---------
+char *a                       
+const char *a                 (const char *) name
+double a[20]                  (double *) name
+double a[20][30]              (double (*)[30]) name
+double &amp;a                     (double &amp;) *name
+</pre>
+</blockquote>
+
+
+<p>
+<li><tt>SwigType_lcaststr(SwigType *t, char *name)</tt>.
+<br>  This function produces a string
+that casts a type produced by the <tt>str()</tt> function to the type produced by the
+<tt>lstr()</tt> function.  This function only produces
+output when it needs to (when str() and lstr() produce different results).  Furthermore, an optional
+name can be supplied when the cast is to be applied to a specific name.  
+
+<blockquote>
+<pre>
+Original Datatype             lcaststr()
+------------------            ---------
+char *a                       
+const char *a                 (char *) name
+double a[20]                  (double *) name
+double a[20][30]              (double *) name
+double &amp;a                     (double *) &amp;name
+</pre>
+</blockquote>
+
+<p>
+<li><tt>SwigType_manglestr(SwigType *t)</tt>. <br>
+Produces a type-string that is used to identify this datatype in the target scripting language.
+Usually this string looks something like "<tt>_p_p_double</tt>" although the target language
+may redefine the output for its own purposes.  Normally this function strips all qualifiers,
+references, and arrays---producing a mangled version of the type produced by the <tt>lstr()</tt> function.
+</ul>
+
+The following example illustrates the intended use of the above functions when creating wrapper
+functions using shorthand pseudocode.   Suppose you had a function like this:
+
+<blockquote>
+<pre>
+int foo(int a, double b[20][30], const char *c, double &amp;d);
+</pre>
+</blockquote>
+
+Here's how a wrapper function would be generated using the type generation functions above:
+
+<blockquote>
+<pre>
+wrapper_foo() {
+   lstr("int","result")
+   lstr("int","arg0")
+   lstr("double [20][30]", "arg1")
+   lstr("const char *", "arg2")
+   lstr("double &amp;", "arg3")
+   ...
+   get arguments
+   ...
+   result = (lcaststr("int"))  foo(rcaststr("int","arg0"),
+                               rcaststr("double [20][30]","arg1"),
+                               rcaststr("const char *", "arg2"),
+                               rcaststr("double &amp;", "arg3"))
+   ...
+}
+</pre>
+</blockquote>
+
+Here's how it would look with the corresponding output filled in:
+<blockquote>
+<pre>
+wrapper_foo() {
+   int      result;
+   int      arg0;
+   double  *arg1;
+   char    *arg2;
+   double  *arg3;
+   ...
+   get arguments
+   ...
+   result = (int) foo(arg0,
+                      (double (*)[30]) arg1,
+                      (const char *) arg2,
+                      (double &amp;) *arg3);
+   ...
+}
+</pre>
+</blockquote>
+
+
+<b>Notes:</b>
+
+<ul>
+<li>For convenience, the string generation functions return a
+"<tt>char *</tt>" that points to statically allocated memory living
+inside the type library.  Therefore, it is never necessary (and it's
+an error) to free the pointer returned by the functions.  Also, if you
+need to save the result, you should make a copy of it.  However, with
+that said, it is probably worth nothing that these functions do cache
+the last 8 results.  Therefore, it's fairly safe to make a handful of
+repeated calls without making any copies.
+</ul>
+
+[TODO]
+
+<a name="4" href="#i4">
+<h2>4. Parsing</h2>
+</a>
+
+[TODO]
+
+<a name="5" href="#i5">
+<h2>5. Difference Between SWIG 1.1 and SWIG 1.3</h2>
+</a>
+
+[TODO]
+
+<a name="6" href="#i6">
+<h2>6. Plans for SWIG 2.0</h2>
+</a>
+
+[TODO]
+
+<a name="7" href="#i7">
+<h2>7. The C/C++ Wrapping Layer</h2>
+</a>
+
+Added: Dave Beazley (July 22, 2000)
+
+<p>
+When SWIG generates wrappers, it tries to provide a mostly seamless integration
+with the original code.  However, there are a number of problematic features
+of C/C++ programs that complicate this interface. 
+
+<ul>
+<li><b>Passing and returning structures by value.</b>  When used, SWIG converts
+all pass-by-value functions into wrappers that pass by reference.  For example:
+
+<blockquote>
+<pre>
+double dot_product(Vector a, Vector b);
+</pre>
+</blockquote>
+
+gets turned into a wrapper like this:
+
+<blockquote>
+<pre>
+double wrap_dot_product(Vector *a, Vector *b) {
+     return dot_product(*a,*b);
+}
+</pre>
+</blockquote>
+
+Functions that return by value require a memory allocation to store the result. For example:
+
+<blockquote>
+<pre>
+Vector cross_product(Vector *a, Vector *b);
+</pre>
+</blockquote>
+
+become
+
+<blockquote>
+<pre>
+Vector *wrap_cross_product(Vector *a, Vector *b) {
+   Vector *result = (Vector *) malloc(sizeof(Vector));
+   *result = cross_product(a,b);
+   return result;
+}
+</pre>
+</blockquote>
+
+Note: If C++ is being wrapped, the default copy constructor is used
+instead of malloc() to create a copy of the return result.
+
+<p>
+<li><b>C++ references</b>.   C++ references are handled exactly the same as
+pass/return by value except that a memory allocation is not made for functions
+that return a reference.
+
+<p>
+<li><b>Qualifiers such as "const" and "volatile".</b> SWIG strips all
+qualifiers from the interface presented to the target language.
+Besides, what in the heck is "const" in Perl anyways?
+
+<p>
+<li><b>Instance Methods</b>.   Method invocations are handled as a function call in which
+a pointer to the object (the "this" pointer) appears as the first argument.  For example, in
+the following class:
+
+<blockquote>
+<pre>
+class Foo {
+public:
+    double bar(double);
+};
+</pre>
+</blockquote>
+
+The "bar" method is wrapped by a function like this:
+
+<blockquote>
+<pre>
+double Foo_bar(Foo *self, double arg0) {
+   return self-&gt;bar(arg0);
+}
+</pre>
+</blockquote>
+
+<p>
+<li><b>Structure/class data members</b>.  Data members are handled by creating a pair
+of wrapper functions that set and get the value respectively.   For example:
+
+<blockquote>
+<pre>
+struct Foo {
+    int x;
+};
+</pre>
+</blockquote>
+
+gets wrapped as follows:
+
+<blockquote>
+<pre>
+int Foo_x_get(Foo *self) {
+    return self-&gt;x;
+}
+int Foo_x_set(Foo *self, int value) {
+    return (self-&gt;x = value);
+}
+</pre>
+</blockquote>
+
+<p>
+<li><b>Constructors</b>.  Constructors for C/C++ data structures are wrapped by
+a function like this:
+
+<blockquote>
+<pre>
+Foo *new_Foo() {
+    return new Foo;
+}
+</pre>
+</blockquote>
+Note: For C, new objects are created using the calloc() function.
+
+<p>
+<li><b>Destructors</b>.  Destructors for C/C++ data structures are wrapper like this:
+
+<blockquote>
+<pre>
+void delete_Foo(Foo *self) {
+    delete self;
+}
+</pre>
+</blockquote>
+Note: For C, objects are destroyed using free().
+
+</ul>
+
+The creation of wrappers and various type transformations are handled by a collection of functions
+found in the file <tt>Source/Swig/cwrap.c</tt>.
+
+<ul>
+<li>
+<tt>char *Swig_clocal(DataType *t, char *name, char *value)</tt><br>
+This function creates a string containing the declaration of a local variable with
+type <tt>t</tt>, name <tt>name</tt>, and default value <tt>value</tt>.  This local
+variable is stripped of all qualifiers and will be a pointer if the type is a reference
+or user defined type.
+
+<p>
+<li>
+<tt>DataType *Swig_clocal_type(DataType *t)</tt><br>
+Returns a type object corresponding to the type string produced by the Swig_clocal() function.
+
+<p>
+<li><tt>char *Swig_clocal_deref(DataType *t, char *name)</tt><br>
+This function is the inverse of the <tt>clocal()</tt> function.  Given a type and a name,
+it produces a string containing the code needed to cast/convert the type produced by
+<tt>Swig_clocal()</tt> back into it's original type.
+
+<p>
+<li><tt>char *Swig_clocal_assign(DataType *t, char *name)</tt><br>
+Given a type and name, this produces a string containing the code (and an optional cast)
+needed to make an assignment from the real datatype to the local datatype produced
+by <tt>Swig_clocal()</tt>.  Kind of the opposite of deref().
+
+<p>
+<li><tt>int Swig_cargs(Wrapper *w, ParmList *l)</tt><br>
+Given a wrapper function object and a list of parameters, this function declares a set
+of local variables for holding all of the parameter values (using Swig_clocal()).  Returns 
+the number of parameters.  In addition, this function sets the local name of each parameter
+which can be retrieved using the <tt>Parm_Getlname()</tt> function.
+
+<p>
+<li><tt>void Swig_cresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
+Generates the code needed to set the result of a wrapper function and performs all of
+the needed memory allocations for ANSI C (if necessary).  <tt>t</tt> is the type of the
+result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
+a string that contains the C code which produces the result.
+
+<p>
+<li><tt>void Swig_cppresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
+Generates the code needed to set the result of a wrapper function and performs all of
+the needed memory allocations for C++ (if necessary).  <tt>t</tt> is the type of the
+result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
+a string that contains the C code which produces the result.
+
+<p>
+<li><tt>Wrapper *Swig_cfunction_wrapper(char *fname, DataType *rtype, ParmList *parms, char *code)</tt><br>
+Create a wrapper around a normal function declaration.  <tt>fname</tt> is the name of the wrapper,
+<tt>rtype</tt> is the return type, <tt>parms</tt> are the function parameters, and <tt>code</tt> is a
+string containing the code in the function body.
+
+<p>
+<li><tt>Wrapper *Swig_cmethod_wrapper(char *classname, char *methodname, DataType *rtype, DataType *parms, char *code)</tt><br>
+
+<p>
+<li><tt>char *Swig_cfunction_call(char *name, ParmList *parms)</tt>
+This function produces a string containing the code needed to call a C function.
+The string that is produced contains all of the transformations needed to convert
+pass-by-value into pass-by-reference as well as handle C++ references.  Produces
+a string like "name(arg0, arg1, ..., argn)".
+
+</ul>
+
+Here is a short example showing how these functions could be used.  Suppose you had a 
+C function like this:
+
+<blockquote>
+<pre>
+double dot_product(Vector a, Vector b);
+</pre>
+</blockquote>
+
+Here's how you might write a really simple wrapper function
+
+<blockquote>
+<pre>
+ParmList *l = ... parameter list of the function ...
+DataType *t = ... return type of the function ...
+char     *name = ... name of the function ...
+Wrapper *w = NewWrapper();
+Printf(w-&gt;def,"void wrap_%s() {\n", name);
+
+/* Declare all of the local variables */
+Swig_cargs(w, l);
+
+/* Convert all of the arguments */
+...
+
+/* Make the function call and declare the result variable */
+Swig_cresult(w,t,"result",Swig_cfunction(name,l));
+
+/* Convert the result into whatever */
+...
+
+Printf(w-&gt;code,"}\n");
+Wrapper_print(w,out);
+</pre>
+</blockquote>
+
+The output of this would appear as follows:
+
+<blockquote>
+<pre>
+void wrap_dot_product() {
+    Vector *arg0;
+    Vector *arg1;
+    double  result;
+
+    ...
+    result = dot_product(*arg0, *arg1);
+    ...
+}
+</pre>
+</blockquote>
+
+Notice that the <tt>Swig_cargs()</tt>, <tt>Swig_cresult()</tt>, and <tt>Swig_cfunction()</tt> functions
+have taken care of the type conversions for the <tt>Vector</tt> type automatically.
+
+<p>
+<b>Notes:</b>
+<ul>
+<Li>The intent of these functions is to provide <em>consistent</em> handling of function parameters
+and return values so that language module writers don't have to worry about it too much.
+
+<p>
+<li>These functions may be superseded by features in the new typemap system which provide hooks
+for specifying local variable declarations and argument conversions.
+
+</ul>
+
+ 
+
+
+
+
+
+<a name="8" href="#i8">
+<h2>8. Symbol Naming Guidelines for Generated C/C++ Code</h2>
+</a>
+The C++ standard (ISO/IEC 14882:1998(E)) states:
+<blockquote>
+<pre>
+<i>
+17.4.3.1.2 Global names [lib.global.names]
+
+1 Certain sets of names and function signatures are always reserved to the implementation:
+
+    * Each name that contains a double underscore (__) or begins with an underscore followed 
+      by an upper case letter (2.11) is reserved to the implementation for any use.
+    * Each name that begins with an underscore is reserved to the implementation for use as 
+      a name in the global namespace.165)
+
+    165) Such names are also reserved in namespace ::std (17.4.3.1). [back to text] 
+</i>
+</pre>
+</blockquote>
+
+When generating code it is important not to generate symbols that might clash with the code being wrapped. It is tempting to flout the standard or just use a symbol which starts with a single underscore followed by a lowercase letter in order to avoid name clashes. However even these legal symbols can also clash with symbols being wrapped. The following guidelines should be used when generating code in order to meet the standard and make it highly unlikely that symbol clashes will occur:
+<p>
+
+For C++ code that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):
+<ul>
+    <li> Put symbols in the <tt>Swig</tt> namespace, for example class <tt>Swig::Director</tt>. Qualify using the <tt>Swig</tt> namespace whenever the symbol is referenced, even within the <tt>Swig</tt> namespace, for example <tt>new Swig::Director()</tt> not <tt>new Director()</tt>.</li>
+    <li> Use <tt>swig_</tt> as a prefix for all member variables and member functions that are involved in an inheritance chain with wrapped classes, for example <tt>Swig::Director::swig_get_up()</tt> and <tt>bool Swig::Director::swig_up</tt>.</li>
+    <li> Alternatively class names can be prefixed with <tt>Swig</tt> in the global namespace for example <tt>template&lt;class T&gt; class SwigValueWrapper</tt>.</li>
+</ul>
+<p>
+
+For code compiled as C or C++ that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):
+<ul>
+    <li> Use <tt>SWIG_</tt> as a prefix for structures for example <tt>SWIG_JavaExceptions_t</tt>.</li>
+    <li> Use <tt>SWIG_</tt> as a prefix for global functions for example <tt>SWIG_TypeRegister</tt>. </li>
+    <li> Use <tt>SWIG_</tt> as a prefix for macros for example <tt>#define SWIG_PY_INT 1</tt></li>
+</ul>
+
+For code compiled as C or C++ that attempts to mangle a wrapped symbol:
+<ul>
+    <li> Use <tt>SWIGxxx</tt> or <tt>Swigxxx</tt> as a prefix where xxx is chosen which would make <tt>SWIGxxx</tt>/<tt>Swigxxx</tt> a unique symbol in the global namespace, for example <tt>class SwigDirectorFoo</tt> when wrapping <tt>class Foo</tt>. Don't use a trailing underscore for the prefix as this may generate a double underscore when wrapping a symbol which starts with a single underscore.</li>
+</ul>
+
+In the past SWIG has generated many symbols which flout the standard especially double underscores. In fact they may not all be rooted out yet, so please fix them when you see them.
+
+
+<a name="9" href="#i9">
+<h2>9. Debugging SWIG</h2>
+</a>
+Warning. Debugging SWIG is for the very patient.
+<p>
+
+The DOH types are all typedefined to void. 
+Consequently, it is impossible for debuggers to extract any information about DOH objects.
+Most debuggers will be able to display useful variable information when an object is cast to the appropriate type.
+Below are some tips for displaying some of the DOH objects.
+Be sure to compile with compiler optimisations turned off before attempting the casts shown in a debugger window else they are unlikely to work.
+Even displaying the underlying string in a String* doesn't work straight off in all debuggers due to the multiple definition of String as a struct and a void.
+<p>
+
+Below are a list of common SWIG types.
+With each is the cast that can be used in the debugger to extract the underlying type information and the underlying char * string.
+
+<ul>
+
+<p>
+<li>String *s;</li>
+<br>
+(String *)((DohBase *)s)-&gt;data
+<br>
+The underlying char * string can be displayed with
+<br>
+((String *)((DohBase *)s)-&gt;data)-&gt;str
+
+<p>
+<li>SwigType *t;</li>
+<br>
+(String *)((DohBase *)t)-&gt;data
+<br>
+The underlying char * string can be displayed with
+<br>
+((String *)((DohBase *)t)-&gt;data)-&gt;str
+
+<p>
+<li>String_or_char *sc;</li>
+Either <br>
+((String *)((DohBase *)sc)-&gt;data)-&gt;str
+<br> or <br>
+(char *)sc
+<br> will work depending on whether the underlying type is really a String * or char *.
+
+</ul>
+
+<hr>
+Copyright (C) 1999-2004 SWIG Development Team.
+
+</body>
+</html>
diff --git a/trunk/Doc/Devel/migrate.txt b/trunk/Doc/Devel/migrate.txt
new file mode 100644
index 0000000..b40fa36
--- /dev/null
+++ b/trunk/Doc/Devel/migrate.txt
@@ -0,0 +1,140 @@
+SWIG1.3 Migration Guide 
+(The not entirely complete guide to updating language modules to work with SWIG1.3).
+
+Dave Beazley
+August 15, 2000
+
+1. Introduction
+---------------
+
+Virtually all of SWIG's internal data structures have now been
+rewritten.  Take everything you thought you knew about SWIG1.1 and
+throw it out.
+
+2. DataTypes
+------------
+The old 'DataType' data structure is gone.  Therefore, direct
+manipulation of 'is_pointer', 'implicit_ptr', and 'arraystr'
+attributes no longer applies.  Sorry.
+
+Datatypes are now represented by the type 'SwigType' which has no
+public attributes.  Actually, if you look at it closely, 'SwigType' is
+really just an alias for 'void' and if you look at it even closer than
+that you will realize that it's nothing more than a string!
+
+The string encoding of types is described in more detail in the file
+Source/Swig/stype.c and is not so important here. What is important is
+the functions used to produce various types of output:
+
+SwigType_str(type,name = 0);
+     This produces an exact C representation of the datatype with all
+     qualifiers, arrays, references, and so forth.  name is an optional
+     name that is given if you wanted to associate the type with a
+     parameter name or something.
+
+SwigType_lstr(type,name = 0);
+     This function takes a type and produces a C string containing
+     a type suitable for assignment (appearing as an lvalue in an
+     expression).  To do this, certain things such as 'const',
+     arrays, and references are stripped away or converted into
+     pointers.  
+     
+SwigType_ltype(type);
+     Returns a SwigType object corresponding to the type created
+     by SwigType_lstr().
+
+SwigType_lcaststr(type,name);
+     Produces a string casting a value 'name' from the real datatype
+     to the assignable type created by SwigType_lstr().
+
+SwigType_rcaststr(type,name)
+     Produces a string that casts a value 'name' from the type
+     created by SwigType_lstr() to the real datatype.
+    
+SwigType_manglestr(type)
+     Produces the 'mangled' version of a datatype.
+
+
+Getting the 'type' code.  Most language modules still operate by
+looking at special integer type codes.  This interface is a little
+ragged and will probably go away at some point.  However, for now the
+following function can be used to get the type code:
+
+   int SwigType_type(type)
+
+The codes are the same as the before, except that there are a few 
+special codes:
+
+     T_STRING          - The 'char *' type and variations.
+     T_POINTER         - Any pointer type (not char * though)
+     T_REFERENCE       - Any C++ reference
+     T_ARRAY           - Any array
+     T_FUNCTION        - A function (this is usually an error).
+
+Because of the special codes, it is no longer necessary to have code like this:
+
+     if ((t->is_pointer == 1) and (t->type == T_CHAR)) {
+           ... get a string ...
+     }
+
+Instead, just use the type code above like this:
+
+     switch(SwigType_type(type)) {
+     case T_STRING:
+          ... get a string ...
+          break;
+     case T_POINTER:
+          ... get a pointer ...
+          break;
+     }
+
+There are about 2-dozen type manipulation functions that could also be useful.
+See Source/Swig/swig.h and Source/Swig/stype.c.
+
+3. Parameter Lists
+------------------
+
+The ParmList data structure is gone.  In reality, parameter lists are nothing more than
+a linked list of parameters.   The proper way to iterate over this list and get
+parameter values is as follows:
+
+  ParmList *l;
+  Parm *p;
+
+  for (p = l; p; p = Getnext(p)) {
+      SwigType *pt = Gettype(p);        /* Get parameter type */
+      String   *pn = Getname(p);        /* Get parameter name */
+      String   *value = Getvalue(p);    /* Get parameter value */
+      ...
+      do whatever
+      ...
+  }
+
+4. Typemaps
+-----------
+
+Typemaps more or less work.  However, the interface has changed slightly.  Instead of
+
+     typemap_lookup("in","python",type,pname,"$source","$target",wrapper);
+
+the function is
+
+     Swig_typemap_lookup("in",type,pname,"$source","$target",wrapper);
+
+There are a variety of other changes to typemaps (see CHANGES).
+
+5. Use of new types
+-------------------
+When possible, language modules should try to use the built in String,
+List, and Hash objects instead of C arrays or 'char *'.   This will probably require a
+detailed pass through the code with an eye towards cleanup.
+
+6. Miscellaneous
+----------------
+Language modules no longer need to concern themselves with formatting the
+wrapper code they produce (provided you are using the special Wrapper object).
+The function Wrapper_print() passes everything through a pretty-printer that
+automatically performs indentation and tries to clean things up.   This especially
+works well when there are lots of typemaps.
+
+
diff --git a/trunk/Doc/Devel/parm.html b/trunk/Doc/Devel/parm.html
new file mode 100644
index 0000000..1cab070
--- /dev/null
+++ b/trunk/Doc/Devel/parm.html
@@ -0,0 +1,102 @@
+<html>
+<head>
+<title>SWIG Parameter Handling</title>
+</head>
+
+<body>
+<center>
+<h1>SWIG Parameter Handling</h1>
+
+<p>
+David M. Beazley <br>
+dave-swig@dabeaz.com<br>
+January 9, 2007<br>
+
+</b>
+</center>
+
+<h2>Introduction</h2>
+
+This document describes the functions related to management of function parameters and parameter lists in the SWIG core. These functions are declared in <tt>Source/Swig/swigparm.h</tt>.   This API is considered to be stable.
+
+<h2>Parameters</h2>
+
+The following utility functions are used to create and copy individual parameters.  In their most basic form, a parameter merely contains a type, a name, and an optional default value.
+
+<p>
+<b><tt>Parm *NewParm(SwigType *type, const String_or_char *name)</tt></b>
+
+<blockquote>
+Creates a new parameter object with type <tt>type</tt> and name <tt>name</tt>.  The type is stored in the attribute "type" and the name is stored in the attribute "name".
+</blockquote>
+
+<p>
+<b><tt>Parm *CopyParm(Parm *p)</tt></b>
+<blockquote>
+Copies a parameter object.  All string attributes are copied in the
+process of making the copy.  However, no complex attributes (lists,
+hashes, etc.) are copied.
+</blockquote>
+
+<h2>Parameter Lists</h2>
+
+<p>
+<b><tt>ParmList *CopyParmList(ParmList *p)</tt></b>
+<blockquote>
+Creates a copy of a parameter list.  A parameter list is merely a linked list of parameters created by NewParm().
+</blockquote>
+
+<p>
+<b><tt>ParmList *CopyParmListMax(ParmList *p, int count)</tt></b>
+<blockquote>
+Copies at most <tt>count</tt> parameters from the parameter list <tt>p</tt>.
+</blockquote>
+
+<p>
+<b><tt>int ParmList_len(ParmList *p)</tt></b>
+
+<blockquote>
+Returns the total number of parameters in a parameter list.
+</blockquote>
+
+<p>
+<b><tt>int ParmList_numrequired(ParmList *p)</tt></b>
+<blockquote>
+Returns the number of required parameters in a parameter list.   This pertains to invoking a function/method in C/C++.
+</blockquote>
+
+<p>
+<b><tt>int ParmList_has_defaultargs(ParmList *p)</tt></b>
+<blockquote>
+Returns 1 if the parameter list has any default arguments.  Otherwise returns 0.
+</blockquote>
+
+
+<h2>Code Generation Functions</h2>
+
+<p>
+<b><tt>String *ParmList_str(ParmList *p)</tt></b>
+<blockquote>
+Creates a C prototype string of the parameters, but without any default values.
+</blockquote>
+
+<p>
+<b><tt>String *ParmList_str_defaultargs(ParmList *p)</tt></b>
+<blockquote>
+Creates a C prototype string of the parameters and includes the default values (if any).
+</blockquote>
+
+<p>
+<b><tt>String *ParmList_protostr(ParmList *p)</tt></b>
+<blockquote>
+Creates a C prototype string of the parameters. 
+</blockquote>
+
+
+</body>
+</html>
+
+
+
+
+
diff --git a/trunk/Doc/Devel/runtime.txt b/trunk/Doc/Devel/runtime.txt
new file mode 100644
index 0000000..f88edf7
--- /dev/null
+++ b/trunk/Doc/Devel/runtime.txt
@@ -0,0 +1,169 @@
+This file describes the necessary functions and interfaces a language module
+needs to implement to take advantage of the run time type system.  I assume you
+have read the run-time section of the Typemaps chapter in the SWIG
+documentation.
+
+Last updated: February 23, 2005
+
+The file we are concerned with here should be named langrun.swg.  A good example
+of a simple file is the Lib/mzscheme/mzrun.swg file.  First, a few requirements
+and notes:
+
+1) Every function in this file should be declared static.  
+
+2) It should be inserted into the runtime section of the _wrap file from your
+config file.  The Lib/swigrun.swg file should be included before this file.
+That is, you need to have
+%runtime "swigrun.swg" 
+%runtime "langrun.swg"
+
+3) You must also include the swiginit.swg file in the init section of the
+wrapper.  That is, you should have
+%insert(init) "swiginit.swg"
+
+4) From module.cxx, you need to call the SwigType_emit_type_table function, as
+well as register types with SwigType_remember or SwigType_remember_clientdata
+
+5) By convention, all functions in this file are of the form
+SWIG_Language_Whatever, and #defines are used to rename SWIG API functions to
+these function names
+
+6) You need to call void SWIG_InitializeModule(void *clientdata) from your init
+function.
+
+7) You need to implement the runtimeCode() and defaultExternalRuntimeFilename()
+functions inside module.cxx.  runtimeCode should return all the language
+specific runtime code as a string, and defaultExternalRuntimeFilename should
+return a string for the default name of the external runtime header.  This is
+usually "swigpyrun.h", where "py" is replaced by the language name.  These
+two functions are used by the -external-runtime argument.
+
+-------------------------------------------------------------------------------
+Required Functions
+-------------------------------------------------------------------------------
+swig_module_info *SWIG_GetModule(void *clientdata);
+void SWIG_SetModule(void *clientdata, swig_module_info *mod);
+
+The SetModule function should store the mod argument into some globally
+accessible variable in the target language.  The action of these two functions
+is to provide a way for multiple modules to share information.  The SetModule
+function should create a new global var named something like
+"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME
+SWIG_RUNTIME_VERSION is currently defined as "2", and SWIG_TYPE_TABLE_NAME is
+defined by the -DSWIG_TYPE_TABLE=mytable option when compiling the wrapper.
+
+Alternatively, if the language supports modules, a module named
+"swig_runtime_data" SWIG_RUNTIME_VERSION can be created, and a global variable
+named "type_table" SWIG_TYPE_TABLE_NAME can be created inside it.  The most
+common approach is to store the mod pointer in some global variable in the
+target language, but if the language provides an alternative place to store data
+(like the chicken module), then that is good too.
+
+The way the code is set up, SetModule should only be called when GetModule
+returns NULL, and if SetModule is called a second time, the behavior is
+undefined. Just make sure it doesn't crash in the random chance occurrence that
+SetModule is called twice.
+
+There are two options here.  
+
+1) The preferred approach is for GetModule and SetModule to not require a
+clientdata pointer.  If you can at all avoid it, please do so.  Here, you would
+write swig_module_info *SWIG_Language_GetModule(); 
+void SWIG_Language_SetModule(swig_module_info *mod);
+and then add
+#define SWIG_GetModule(clientdata) SWIG_Language_GetModule()
+#define SWIG_SetModule(cd, ptr) SWIG_Language_SetModule(ptr)
+You would then call
+SWIG_InitializeModule(0)
+
+2) If GetModule and SetModule need to take a custom pointer (most notably an
+environment pointer, see tcl or mzscheme), then you should write
+swig_module_info *SWIG_Language_GetModule(void *clientdata)
+void SWIG_Language_SetModule(void *clientdata, swig_module_info *mod);
+and also define
+#define SWIG_GetModule(cd) SWIG_Language_GetModule(cd)
+#define SWIG_SetModule(cd, ptr) SWIG_Language_SetModule(cd, ptr)
+#define SWIG_MODULE_CLIENTDATA_TYPE Whatever
+SWIG_MODULE_CLIENTDATA_TYPE should be defined to whatever the type of
+clientdata is.
+
+You would then call SWIG_InitializeModule(clientdata), and clientdata would get
+passed to GetModule and SetModule.  clientdata will not be stored and will only
+be referenced during the InitializeModule call.  After InitializeModule returns,
+clientdata does not need to be valid any more.
+
+This method is not preferred, because it makes external access to the type
+system more complicated.  See the Modules chapter of the documentation, and read
+the "External access to the run-time" section.  Then take a look at
+Lib/runtime.swg.  Anybody that calls SWIG_TypeQuery needs to pass along the
+clientdata pointer, and that is the reason for defining
+SWIG_MODULE_CLIENTDATA_TYPE.
+
+-------------------------------------------------------------------------------
+Standard Functions
+-------------------------------------------------------------------------------
+These functions are not required and their API is not formalized, but almost all
+language modules implement them for consistency across languages.  Throughout
+this discussion, I will use LangType to represent the underlying language type
+(C_word in chicken, Scheme_Object * in mzscheme, PyObject * in python, etc)
+
+
+
+LangObj SWIG_NewPointerObj(void *ptr, swig_type_info *type, int flags);
+Create and return a new pointer object that has both ptr and type.  For almost
+all language modules, flags is used for ownership.  If flags==1, then the
+created pointer should be registered to be garbage collected.
+
+
+
+int SWIG_ConvertPtr(LangType obj, void **result, swig_type_info *type, int flags);
+Convert a language wrapped pointer into a void *.  The pointer is returned in
+result, and the function should return 0 on success, non-zero on error.
+A sample ConvertPtr is given here:
+
+  swig_cast_info *cast;
+
+  if (<obj is a wrapped pointer type>) {
+    cast = SWIG_TypeCheck(<obj type name>, type);
+    cast = SWIG_TypeCheckStruct(<obj type structure>, type);
+    if (cast) {
+      *result = SWIG_TypeCast(cast, <obj pointer>);
+      return 0;
+    }
+  }
+  return 1;
+
+Either TypeCheck or TypeCheckStruct can be called, depending on how the pointer
+is wrapped in langtype.  If obj stores the void pointer and the type name, then
+the TypeCheck function should be used, while if obj stores the void pointer and
+a pointer to the swig_type_info structure, then the TypeCheckStruct function
+should be called.  The TypeCheckStruct is slightly faster, since it does a
+pointer comparison instead of a strcmp.  
+
+The flag argument to ConvertPtr is used in some languages for disowning a
+pointer.  If the wrapped C function is taking ownership of the pointer (that
+means, the wrapped C function is responsible for deleting the object), then that
+pointer should be removed from the garbage collector.  We do that in the
+ConvertPtr function.  The pointer is still valid in the target language, but
+when the target language type is garbage collected, it will not call the
+associated destructor.  Languages have a special typemap called DISOWN that can be
+applied which passes this argument.  All the languages have the flags argument
+for consistency, and the flags argument can be ignored or used for some other
+purpose.
+
+
+void *SWIG_MustGetPtr(LangType obj, swig_type_info *type, int flags,
+                      int argnum, const char *func_name) {
+ void *result;
+  if (SWIG_ConvertPtr(s, &result, type, flags)) {
+    generate runtime type error ("Error in func_name, expected a" +
+                                 type->str ? type->str : "void *" + 
+				 "at argument number" + argnum);
+  }
+  return result;
+}
+This function is optional, and the number and type of parameters can be
+different, but is useful for typemap purposes:
+%typemap(in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, 0, $argnum, FUNC_NAME);
+}
diff --git a/trunk/Doc/Devel/scanner.html b/trunk/Doc/Devel/scanner.html
new file mode 100644
index 0000000..2722164
--- /dev/null
+++ b/trunk/Doc/Devel/scanner.html
@@ -0,0 +1,288 @@
+<html>
+<head>
+<title>SWIG C Scanner</title>
+</head>
+
+<body>
+<center>
+<h1>SWIG C/C++ Scanning</h1>
+
+<p>
+David M. Beazley <br>
+dave-swig@dabeaz.com<br>
+January 11, 2007<br>
+
+</b>
+</center>
+
+<h2>Introduction</h2>
+
+This document describes functions that can be used to tokenize C/C++
+input text.  These functions are relatively low-level and are meant to
+be used in the implementation of scanners that can be plugged into yacc or used for
+other purposes.  For instance, the preprocessor uses these functions to evaluate and test 
+constant expressions.  
+
+<p>
+All of these functions are declared in <tt>Source/Swig/swigscan.h</tt>.   This API is considered to be stable.
+
+<h2>Creation and Deletion of Scanners</h2>
+
+The following functions are used to create and destroy a scanner object.  More than one scanner object can be created and used
+as necessary.
+
+<p>
+<b><tt>Scanner *NewScanner()</tt></b>
+
+<blockquote>
+Creates a new scanner object.  The scanner contains initially contains no text.  To feed text to the scanner use <tt>Scanner_push()</tt>.
+</blockquote>
+
+<p>
+<b><tt>Scanner *DelScanner()</tt></b>
+
+<blockquote>
+Deletes a scanner object. 
+</blockquote>
+
+<h2>Scanner Functions</h2>
+
+<p>
+<b><tt>void Scanner_clear(Scanner *s)</tt></b>
+<blockquote>
+Clears all text from the scanner.  This can be used to reset a scanner to its initial state, ready to receive new input text.
+</blockquote>
+
+<p>
+<b><tt>void Scanner_push(Scanner *s, String *text)</tt></b>
+<blockquote>
+Pushes an input string into the scanner. Subsequent tokens will be
+returned from the new string.  If the scanner is already processing a
+string, the pushed string takes precedence--in effect, interrupting
+the scanning of the previous string.  This behavior is used to
+implement certain SWIG features such as the <tt>%inline</tt>
+directive. Once the pushed string has been completely scanned, the
+scanner will return to scanning the previous string (if any).  The
+scanning of text relies upon the DOH file interface to strings
+(<tt>Getc()</tt>, <tt>Ungetc()</tt>, etc.).  Prior to calling this
+function, the input string should be set so that its file pointer is
+in the location where you want scanning to begin. You may have to
+use <tt>Seek()</tt> to set the file pointer back to the beginning of a
+string prior to using this function.
+</blockquote>
+
+<p>
+<b><tt>void Scanner_pushtoken(Scanner *s, int tokvalue, String_or_char *val)</tt></b>
+<blockquote>
+Pushes a token into the scanner.  This exact token will be returned by the next call to <tt>Scanner_token()</tt>.  
+<tt>tokvalue</tt> is the integer token value to return and <tt>val</tt> is the token text to return.   This
+function is only used to handle very special parsing cases. For instance, if you need the scanner to
+return a ficticious token into order to enter a special parsing case.
+</blockquote>
+
+<p>
+<b><tt>int Scanner_token(Scanner *s)</tt></b>
+
+<blockquote>
+Returns the next token.  An integer token code is returned (see table below) on success.  If no more input text is
+available 0 is returned.  If a scanning error occurred, -1 is returned.  In this case, error information can be
+obtained using <tt>Scanner_errinfo()</tt>.
+</blockquote>
+
+<p>
+<b><tt>String *Scanner_text(Scanner *s)</tt></b>
+<blockquote>
+Returns the scanned text corresponding to the last token returned by <tt>Scanner_token()</tt>.   The returned string
+is only valid until the next call to <tt>Scanner_token()</tt>. If you need to save it, make a copy.
+</blockquote>
+
+<p>
+<b><tt>void Scanner_skip_line(Scanner *s)</tt></b>
+<blockquote>
+Skips to the end of the current line.   The text skipped can be obtained using <tt>Scanner_text()</tt> afterwards.
+</blockquote>
+
+<p>
+<b><tt>void Scanner_skip_balanced(Scanner *s, int startchar, int endchar)</tt></b>
+<blockquote>
+Skips to the end of a block of text denoted by starting and ending characters.  For example, <tt>{</tt> and <tt>}</tt>.  The
+function is smart about how it skips text.  String literals and comments are ignored.   The function also is aware of nesting.  The
+skipped text can be obtained using <tt>Scanner_text()</tt> afterwards. Returns 0 on success, -1 if no matching <tt>endchar</tt> could be found.
+</blockquote>
+
+
+<p>
+<b><tt>void Scanner_set_location(Scanner *s, int startchar, int endchar)</tt></b>
+<blockquote>
+Changes the current filename and line number of the scanner.
+</blockquote>
+
+<p>
+<b><tt>String *Scanner_file(Scanner *s)</tt></b>
+<blockquote>
+Gets the current filename associated with text in the scanner.
+</blockquote>
+
+<p>
+<b><tt>int Scanner_line(Scanner *s)</tt></b>
+<blockquote>
+Gets the current line number associated with text in the scanner.
+</blockquote>
+
+<p>
+<b><tt>int Scanner_start_line(Scanner *s)</tt></b>
+<blockquote>
+Gets the starting line number of the last token returned by the scanner.
+</blockquote>
+
+<p>
+<b><tt>void Scanner_idstart(Scanner *s, char *idchar)</tt></b>
+<blockquote>
+Sets additional characters (other than the C default) that may be used to start C identifiers.  <tt>idchar</tt> is a string
+containing the characters (e.g., "%@").  The purpose of this function is to up special keywords such as "%module" or "@directive" as
+simple identifiers.
+</blockquote>
+
+<p>
+<b><tt>String *Scanner_errmsg(Scanner *s)</tt></b>
+<blockquote>
+Returns the error message associated with the last scanner error (if any).   This will only return a meaningful result
+if <tt>Scanner_token()</tt> returned -1.
+</blockquote>
+
+<p>
+<b><tt>int Scanner_errline(Scanner *s)</tt></b>
+<blockquote>
+Returns the line number associated with the last scanner error (if any).   This will only return a meaningful result
+if <tt>Scanner_token()</tt> returned -1.  The line number usually corresponds to the starting line number of a particular
+token (e.g., for unterminated strings, comments, etc.).
+</blockquote>
+
+<p>
+<b><tt>int Scanner_isoperator(int tokval)</tt></b>
+<blockquote>
+A convenience function that returns 0 or 1 depending on whether <tt>tokval</tt> is a valid C/C++ operator (i.e., a candidate for
+operator overloading).  
+</blockquote>
+
+<p>
+<b><tt>void Scanner_freeze_line(int val)</tt></b>
+<blockquote>
+Freezes the current line number depending upon whether or not <tt>val</tt> is 1 or 0.  When the line number is frozen, newline characters will not result in 
+updates to the line number.  This is sometimes useful in tracking line numbers through complicated macro expansions.
+</blockquote>
+
+
+<h2>Token Codes</h2>
+
+The following table shows token codes returned by the scanner.  These are integer codes returned by
+the <tt>Scanner_token()</tt> function.
+
+<blockquote>
+<pre>
+Token code                   C Token
+-------------------------    -------------
+SWIG_TOKEN_LPAREN            (
+SWIG_TOKEN_RPAREN            )
+SWIG_TOKEN_SEMI              ; 
+SWIG_TOKEN_COMMA             , 
+SWIG_TOKEN_STAR              * 
+SWIG_TOKEN_TIMES             *
+SWIG_TOKEN_LBRACE            { 
+SWIG_TOKEN_RBRACE            } 
+SWIG_TOKEN_EQUAL             = 
+SWIG_TOKEN_EQUALTO           == 
+SWIG_TOKEN_NOTEQUAL          != 
+SWIG_TOKEN_PLUS              + 
+SWIG_TOKEN_MINUS             - 
+SWIG_TOKEN_AND               &amp; 
+SWIG_TOKEN_LAND              &amp;&amp; 
+SWIG_TOKEN_OR                | 
+SWIG_TOKEN_LOR               || 
+SWIG_TOKEN_XOR               ^ 
+SWIG_TOKEN_LESSTHAN          &lt; 
+SWIG_TOKEN_GREATERTHAN       &gt; 
+SWIG_TOKEN_LTEQUAL           &lt;= 
+SWIG_TOKEN_GTEQUAL           &gt;= 
+SWIG_TOKEN_NOT               ~ 
+SWIG_TOKEN_LNOT              ! 
+SWIG_TOKEN_LBRACKET          [ 
+SWIG_TOKEN_RBRACKET          ] 
+SWIG_TOKEN_SLASH             / 
+SWIG_TOKEN_DIVIDE            /
+SWIG_TOKEN_BACKSLASH         \ 
+SWIG_TOKEN_POUND             # 
+SWIG_TOKEN_PERCENT           % 
+SWIG_TOKEN_MODULO            %
+SWIG_TOKEN_COLON             : 
+SWIG_TOKEN_DCOLON            :: 
+SWIG_TOKEN_DCOLONSTAR        ::*
+SWIG_TOKEN_LSHIFT            &lt;&lt; 
+SWIG_TOKEN_RSHIFT            &gt;&gt; 
+SWIG_TOKEN_QUESTION          ? 
+SWIG_TOKEN_PLUSPLUS          ++ 
+SWIG_TOKEN_MINUSMINUS        -- 
+SWIG_TOKEN_PLUSEQUAL         += 
+SWIG_TOKEN_MINUSEQUAL        -= 
+SWIG_TOKEN_TIMESEQUAL        *= 
+SWIG_TOKEN_DIVEQUAL          /= 
+SWIG_TOKEN_ANDEQUAL          &amp;= 
+SWIG_TOKEN_OREQUAL           |= 
+SWIG_TOKEN_XOREQUAL          ^= 
+SWIG_TOKEN_LSEQUAL           &lt;&lt;= 
+SWIG_TOKEN_RSEQUAL           &gt;&gt;= 
+SWIG_TOKEN_MODEQUAL          %= 
+SWIG_TOKEN_ARROW             -&gt; 
+SWIG_TOKEN_ARROWSTAR         -&gt;* 
+SWIG_TOKEN_PERIOD            . 
+SWIG_TOKEN_AT                @ 
+SWIG_TOKEN_DOLLAR            $ 
+SWIG_TOKEN_ENDLINE           Literal newline
+SWIG_TOKEN_ID                identifer 
+SWIG_TOKEN_FLOAT             Floating point with F suffix (e.g., 3.1415F)
+SWIG_TOKEN_DOUBLE            Floating point (e.g., 3.1415 )
+SWIG_TOKEN_INT               Integer (e.g., 314)
+SWIG_TOKEN_UINT              Unsigned integer (e.g., 314U)
+SWIG_TOKEN_LONG              Long integer (e.g., 314L) 
+SWIG_TOKEN_ULONG             Unsigned long integer (e.g., 314UL)
+SWIG_TOKEN_LONGLONG          Long long integer (e.g., 314LL )
+SWIG_TOKEN_ULONGLONG         Unsigned long long integer (e.g., 314ULL) 
+SWIG_TOKEN_CHAR              Character literal in single quotes ('c')
+SWIG_TOKEN_STRING            String literal in double quotes ("str")
+SWIG_TOKEN_RSTRING           Reverse quote string (`str`)
+SWIG_TOKEN_CODEBLOCK         SWIG code literal block %{ ... %}
+SWIG_TOKEN_COMMENT           C or C++ comment  (// or /* ... */)
+SWIG_TOKEN_ILLEGAL           Illegal character
+</pre>
+</blockquote>
+
+<b>Notes</b>
+
+<ul>
+<li>When more than one token code exist for the same token text, those codes are identical (e.g., <tt>SWIG_TOKEN_STAR</tt> and <tt>SWIG_TOKEN_TIMES</tt>).
+
+<p>
+<li>
+String literals are returned in their exact representation in which escape codes (if any) have been interpreted.
+
+<p>
+<li>
+All C identifiers and keywords are simply returned as <tt>SWIG_TOKEN_ID</tt>.  To check for specific keywords, you will need to
+add extra checking on the returned text.
+
+<p>
+<li>C and C++ comments include the comment starting and ending text (e.g., "//", "/*").
+
+<p>
+<li>The maximum token integer value is found in the constant <tt>SWIG_MAXTOKENS</tt>.   This can be used if you wanted to create 
+an array or table for the purposes of remapping tokens to a different set of codes. For instance, if you are
+using these functions to write a yacc-compatible lexer.
+</ul>
+
+</body>
+</html>
+
+
+
+
+
diff --git a/trunk/Doc/Devel/tree.html b/trunk/Doc/Devel/tree.html
new file mode 100644
index 0000000..64d9d19
--- /dev/null
+++ b/trunk/Doc/Devel/tree.html
@@ -0,0 +1,265 @@
+<html>
+<head>
+<title>SWIG Parse Tree Handling</title>
+</head>
+
+<body>
+<center>
+<h1>SWIG Parse Tree Handling</h1>
+
+<p>
+David M. Beazley <br>
+dave-swig@dabeaz.com<br>
+December, 2006<br>
+
+</b>
+</center>
+
+<h2>Introduction</h2>
+
+This document describes the functions related to the handling of
+parse trees in SWIG.  The structure of SWIG parse trees has been influenced heavily by ideas
+from XML-DOM trees.  In fact, the functions in the API and attribute names are nearly identical.  
+The header file <tt>Source/swig/swigtree.h</tt> contains the functions and macros described in
+this document. This API is
+considered to be stable.
+
+<h2>Parse tree navigation</h2>
+
+The following macros are used to navigate the parse tree.
+
+<p>
+<b><tt>nodeType(n)</tt></b>
+
+<blockquote>
+Returns the type of a node as a String object.  The type is stored in the "nodeType" attribute of <tt>n</tt>.
+</blockquote>
+
+<p>
+<b><tt>parentNode(n)</tt></b>
+
+<blockquote>
+Returns the parent of a node. This is found in the "parentNode" attribute of <tt>n</tt>.
+</blockquote>
+
+<p>
+<b><tt>previousSibling(n)</tt></b>
+
+<blockquote>
+Returns the previous sibling of a node (if any). This is found in the "previousSibling" attribute of <tt>n</tt>.
+</blockquote>
+
+<p>
+<b><tt>nextSibling(n)</tt></b>
+
+<blockquote>
+Returns the next sibling of a node (if any). This is found in the "nextSibling" attribute of <tt>n</tt>.
+</blockquote>
+
+<p>
+<b><tt>firstChild(n)</tt></b>
+
+<blockquote>
+Returns the first child of a node (if any). This is found in the "firstChild" attribute of <tt>n</tt>.
+</blockquote>
+
+<p>
+<b><tt>lastChild(n)</tt></b>
+
+<blockquote>
+Returns the last child of a node (if any). This is found in the "lastChild" attribute of <tt>n</tt>.
+</blockquote>
+
+
+<h2>Parse Tree Construction</h2>
+
+The following macros are used to construct parse trees.
+
+<p>
+<b><tt>set_nodeType(n, val)</tt></b>
+
+<blockquote>
+Sets the nodeType attribute of n.  val is a string containing the type.
+</blockquote>
+
+<p>
+<b><tt>set_parentNode(n, parent)</tt></b>
+
+<blockquote>
+Sets the parent of node n.
+</blockquote>
+
+<p>
+<b><tt>set_previousSibling(n, prev)</tt></b>
+
+<blockquote>
+Sets the previous sibling of node n.
+</blockquote>
+
+<p>
+<b><tt>set_nextSibling(n, next)</tt></b>
+
+<blockquote>
+Sets the next sibling of node n.
+</blockquote>
+
+<p>
+<b><tt>set_firstChild(n, chd)</tt></b>
+
+<blockquote>
+Sets the first child of node n.
+</blockquote>
+
+<p>
+<b><tt>set_lastChild(n, chd)</tt></b>
+
+<blockquote>
+Sets the last child of node n.
+</blockquote>
+
+<h2>Tree Management Functions</h2>
+
+The following functions are used to help with the management and construction of parse trees.
+
+<p>
+<b><tt>void appendChild(Node *node, Node *child)</tt></b>
+<blockquote>
+Adds a new child to <tt>node</tt>.  This function takes care of adjusting the "firstChild" and "lastChild" attributes of <tt>node</tt> to appropriate values.   After calling this function, the "lastChild" attribute will point to <tt>child</tt>.
+</blockquote>
+
+<p>
+<b><tt>void prependChild(Node *node, Node *child)</tt></b>
+<blockquote>
+Prepends a new child to <tt>node</tt>.  The new child is added so that it becomes the first child of <tt>node</tt>.
+</blockquote>
+
+<p>
+<b><tt>void removeNode(Node *node)</tt></b>
+<blockquote>
+Removes a node from the parse tree.  The removal process detaches a node from its parent by removing it from the parent's child list.  Upon return, <tt>node</tt> will have no parent and no siblings.   This function does NOT delete <tt>node</tt> or modify children of <tt>node</tt>.  If desired, <tt>node</tt> could be reattached to a different part of the parse tree.
+</blockquote>
+
+<p>
+<b><tt>Node *copyNode(Node *node)</tt></b>
+<blockquote>
+Copies a node, but only copies those attributes that are simple strings.  Thus, the new node will not contain any references to other nodes, lists, hashes, or other complex data structures.   This function may be useful if you want to copy the data contents of a node in the process of creating a new parse tree node.
+</blockquote>
+
+
+<h2>Attribute Checking</h2>
+
+The following utility is provided since this is an extremely common operation.
+
+<p>
+<b><tt>int checkAttribute(Node *n, const String_or_char *name, const String_or_char *value)</tt></b>
+<blockquote>
+This function checks to see whether node <tt>n</tt> has a given
+attribute name and that the attribute has a given value.  Returns 0 or
+1.
+</blockquote>
+
+
+<h2>Node Transformation</h2>
+
+In the course of processing, SWIG often applies a transform to a node.
+This transformation process made modify many of the attributes--even
+changing the type of a node.  The following functions are used to help
+manage this transformation process.  In addition to provide sanity
+checks, they save the old contents of the node so that they can be
+restored later.
+
+<p>
+<b><tt>void Swig_save(const char *namespace, Node *n, ...)</tt></b>
+
+<blockquote>
+This function takes a node and a list of attribute names and saves their contents in a specified namespace.   For example,
+the call
+
+<pre>
+Swig_save("temp",n,"type","parms","name",NIL)
+</pre>
+
+takes the attributes "type","parms", and "name" and saves their
+contents under the attribute names "temp:type","temp:parms","temp:name".  In addition, this function sets
+an attribute "view" to hold the name of the current namespace.  In this example, the "view" attribute would be set
+to "temp".  The attribute names specified are all optional.  If one or more of the attributes don't exist,
+this function merely records that those attributes did not exist in the original node.
+</blockquote>
+
+<p>
+<b><tt>void Swig_require(const char *namespace, Node *n, ...)</tt></b>
+
+<blockquote>
+This function is similar to <tt>Swig_save()</tt> except that adds additional attribute checking. There are different interpretations
+of the attribute names.  A name of "attr" merely requests that the function check for the presence of an attribute.  If the attribute is missing, SWIG will exit with a failed assertion.   An attribute name of "?attr" specifies that the attribute "attr" is optional and
+that it's old value must be saved (if any).   An attribute name of "*attr" specifies that the attribute is required and that
+its value must be saved.   The saving of attributes is performed in the same manner as with <tt>Swig_save()</tt>. Here is an example:
+
+<pre>
+Swig_require("temp",n,"type","*name","?parms",NIL);
+</pre>
+
+</blockquote>
+
+<p>
+<b><tt>void Swig_restore(Node *n)</tt></b>
+
+<blockquote>
+This function restores a node to the state it was in prior to the last <tt>Swig_save()</tt> or <tt>Swig_require()</tt> call.  This is used to undo node transformations.
+</blockquote>
+
+<h2>Debugging Functions</h2>
+
+The following functions are used to help debug SWIG parse trees.
+
+<p>
+<b><tt>void Swig_print_tags(Node *node, String_or_char *prefix)</tt></b>
+
+<blockquote>
+Prints the tag-structure of the parse tree to standard output.  <tt>node</tt> is the top-level parse tree node.  <tt>prefix</tt> is
+a string prefix thats added to the start of each line.  Normally, you would specify the empty string or NIL for <tt>prefix</tt>.  
+This function is called by the <tt>-dump_tags</tt> option to SWIG.
+
+<pre>
+% swig -dump_tags -python example.i
+ . top (:1)
+ . top . include (/Users/beazley/Projects/share/swig/1.3.31/swig.swg:0)
+ . top . include . include (/Users/beazley/Projects/share/swig/1.3.31/swigwarnings.swg:0)
+ . top . include . include . include (/Users/beazley/Projects/share/swig/1.3.31/swigwarn.swg:0)
+...
+...
+ . top . include (example.i:0)
+ . top . include . module (example.i:2)
+ . top . include . insert (example.i:7)
+ . top . include . cdecl (example.i:5)
+ . top . include . cdecl (example.i:6)
+</pre>
+
+Since many language modules include hundreds of typemaps and other information, the output of this can be significantly more complicated than you might expect.
+</blockquote>
+
+<p>
+<b><tt>void Swig_print_node(Node *node)</tt></b>
+
+<blockquote>
+Prints the contents of a parse tree node, including all children, to standard output.  The output includes all attributes
+and other details.  The command line option <tt>-dump_tree</tt> produces output generated by this function.
+</blockquote>
+
+<p>
+<b><tt>void Swig_print_tree(Node *node)</tt></b>
+
+<blockquote>
+Prints the same output as <tt>Swig_print_node()</tt> except that it also processes all of the siblings of <tt>node</tt>.  This can
+be used to dump the entire parse tree to standard output.  Use the command line option <tt>-dump_tree</tt> to get
+the output of this function for a SWIG input file.
+</blockquote> 
+
+
+</body>
+</html>
+
+
+
+
+
diff --git a/trunk/Doc/Devel/wrapobj.html b/trunk/Doc/Devel/wrapobj.html
new file mode 100644
index 0000000..10e3acc
--- /dev/null
+++ b/trunk/Doc/Devel/wrapobj.html
@@ -0,0 +1,223 @@
+<html>
+<head>
+<title>Wrapper Objects</title>
+</head>
+
+<body>
+<center>
+<h1>Wrapper Objects</h1>
+
+<p>
+David M. Beazley <br>
+dave-swig@dabeaz.com<br>
+January 15, 2007<br>
+
+</b>
+</center>
+
+<h2>Introduction</h2>
+
+This document describes the functions related to management of
+wrapper objects.  A wrapper object is a low-level
+data structure used to contain the C/C++ code that is emitted during the
+wrapping process.  It contains not only the emitted code, but information
+about local variables.   These objects are a critical component of almost all
+SWIG target language modules. 
+
+<p>
+The functions described here are declared
+in <tt>Source/Swig/swigwrap.h</tt>.  This API is considered to be
+stable.
+
+<h2>Creating and Destroying Wrappers</h2>
+
+The following functions create and destroy wrapper objects.
+
+<p>
+<b><tt>Wrapper *NewWrapper()</tt></b>
+
+<blockquote>
+Creates a new wrapper object.
+</blockquote>
+
+<p>
+<b><tt>void DelWrapper(Wrapper *w)</tt></b>
+<blockquote>
+Destroys a wrapper object.
+</blockquote>
+
+<h2>Wrapper Objects</h2>
+
+The <tt>Wrapper</tt> object returned by <tt>NewWrapper()</tt> has
+three public attributes.
+
+<blockquote><pre>
+typedef struct Wrapper {
+    String *def;
+    String *locals;
+    String *code;
+} Wrapper;
+</pre></blockquote>
+
+The <tt>def</tt> attribute is a string that holds the function
+definition line.  This line declares the function name, return type,
+and parameters.   Language modules create this declaration by simply printing 
+the appropriate text into this attribute.
+
+<p>
+The <tt>locals</tt> attribute is a string that holds the code
+related to any local variables declaration.   Normally, language modules
+do not emit code to this string directly.  They use <tt>Wrapper_add_local()</tt> or <tt>Wrapper_new_local()</tt> to do this.
+
+<p>
+The <tt>code</tt> attribute is a string that holds code related to the body of the function.  Almost all code emitted by SWIG language modules is printed into this attribute.
+
+<h2>Creating Local Variables</h2>
+
+Perhaps the most useful aspect of <tt>Wrapper</tt> objects is the
+management of local variables.  When creating a wrapper, it is often
+necessary to emit local variables related to the API of the target
+language.  In addition to this, typemaps and other aspects of SWIG
+rely upon their own local variables.  The following functions are used
+to create local variables, but also provide support for renaming
+variables in order to avoid name clashes.
+
+<p>
+<b><tt>int Wrapper_add_local(Wrapper *w, const String_or_char *name, const String_or_char *decl)</tt></b>
+<blockquote>
+Adds a new local variable to the wrapper object. <tt>name</tt> is the
+name of the local variable.  <tt>decl</tt> is a string containing the
+actual variable declaration code.  For example, if you wanted to
+declare a variable "<tt>int x = 42;</tt>", you would set <tt>name</tt>
+to <tt>"x"</tt> and
+<tt>decl</tt> to <tt>"int x = 42;"</tt>.  On success, the text in
+<tt>decl</tt> is added to the <tt>locals</tt> attribute of <tt>w</tt>
+and 0 is returned.  -1 is returned if a variable with the given name
+has already been declared.
+</blockquote>
+
+<p>
+<b><tt>int Wrapper_add_localv(Wrapper *w, const String_or_char *name, ...)</tt></b>
+<blockquote>
+The same as <tt>Wrapper_add_local()</tt> except that instead of
+passing a single string for the declaration, a NULL-terminated list of
+strings can be passed.  These strings are joined together when
+producing the output.  This convention turns out to be fairly useful
+since language modules often create their output into pieces.
+</blockquote>
+
+<p>
+<b><tt>char * Wrapper_new_local(Wrapper *w, const String_or_char *name, const String_or_char *decl)</tt></b>
+<blockquote>
+The same as <tt>Wrapper_add_local()</tt> except that if a local variable
+with the given name already exists, this function picks a new name and adds
+the declaration using the new name.  The actual name used for the variable
+is returned.   This function is used when generating code originating from
+typemaps.  For instance, if a typemap declares a local variable, that variable
+might have to be renamed if the same typemap is used more than once in the same function.
+</blockquote>
+
+<p>
+<b><tt>char * Wrapper_new_localv(Wrapper *w, const String_or_char *name,...)</tt></b>
+<blockquote>
+The same as <tt>Wrapper_new_localv()</tt>, but accepts a NULL-terminated list
+of strings as code output. 
+</blockquote>
+
+<p>
+<b><tt>int Wrapper_check_local(Wrapper *w, const String_or_char *name)</tt></b>
+<blockquote>
+Checks to see if a local variable with name <tt>name</tt> has been declared.  Returns 1 if the local is defined, 0 otherwise.
+</blockquote>
+
+<h2>Output</h2>
+
+<p>
+<b><tt>void Wrapper_print(Wrapper *w, File *f)</tt></b>
+<blockquote>
+This function is used to format a wrapper function for output.  The
+formatted wrapper function is emitted to <tt>f</tt> which may be any
+file-like object including a <tt>FILE *</tt> object or a <tt>String
+*</tt> object.   When emitting the wrapper, the code printed to the
+wrapper object is automatically formatted.  By default, the formatting
+is done according to a "pretty printing" style in which lines are split onto
+multiple lines and indented according to reasonable C formatting rules.   This produces code that is moderately readable should you want to look at the wrapper
+code output.   An alternative output mode is "compact printing" in which
+lines are collected and compacted.   This may result in multiple C statements
+appearing on the same line.   This mode is sometimes used when the size of
+a wrapper file is too large for certain compilers. For example, some compilers
+might impose a limit of 65536 lines per source file.
+</blockquote>
+
+<p>
+<b><tt>void Wrapper_compact_print_mode_set(int flag)</tt></b>
+<blockquote>
+Sets the output mode of the <tt>Wrapper_print()</tt>
+function. If <tt>flag</tt> is set to 1, then wrapper code is formatted
+to be compact.
+</blockquote>
+
+<p>
+<b><tt>void Wrapper_pretty_print(String *str, File *f)</tt></b>
+<blockquote>
+Utility function that reformats a string containing C/C++ code and outputs
+it to the file-like object <tt>f</tt>.   The formatting process indents the code
+and structures it according to reasonable C formatting rules.
+</blockquote>
+
+<p>
+<b><tt>void Wrapper_compact_print(String *str, File *f)</tt></b>
+<blockquote>
+Utility function that reformats a string containing C/C++ code and outputs
+it to the file-like object <tt>f</tt>.   The formatting process tries to
+make the code as compact as possible, without going completely overboard.  For
+example, multiple C statements may be combined onto a single line and braces may be aligned to not use up extra lines.
+</blockquote>
+
+
+<h2>An Example</h2>
+
+Here is a simple example of how these functions are used.  Suppose
+you wanted to emit the following C function:
+
+<blockquote>
+<pre>
+void foo(int n) {
+   int i;
+   for (i = 0; i &lt; n; i++) {
+       printf("%d\n", i);
+   }
+}
+</pre>
+</blockquote>
+
+Here is code that generates the above function:
+
+<blockquote>
+<pre>
+Wrapper *w = NewWrapper();
+Printf(w-&gt;def,"void foo(int n) {");
+Wrapper_add_local(w,"n","");         /* parameter n */
+Wrapper_add_local(w,"i", "int i;");  /* local i */
+Printv(w-&gt;code,"for (i = 0; i &lt; n; i++) {",
+               "printf(\"%d\n",i);",
+               "}\n", NIL);
+Printf(w-&gt;code,"}\n");
+
+/* Emit wrapper code */
+Wrapper_print(w,outf);
+DelWrapper(w);
+</pre>
+</blockquote>
+
+Within different language modules, this process is obviously much more
+involved.  However, this example shows the basic idea of how C/C++
+code is prepared for output.
+
+</body>
+</html>
+
+
+
+
+
diff --git a/trunk/Doc/Manual/Allegrocl.html b/trunk/Doc/Manual/Allegrocl.html
new file mode 100755
index 0000000..8981f52
--- /dev/null
+++ b/trunk/Doc/Manual/Allegrocl.html
@@ -0,0 +1,2150 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<!-- Hand-written HTML -->
+<html>
+<head>
+<title>SWIG and Allegro Common Lisp</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+
+<H1><a name="Allegrocl_nn1"></a>16 SWIG and Allegro Common Lisp</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Allegrocl_nn2">Basics</a>
+<ul>
+<li><a href="#Allegrocl_nn3">Running Swig</a>
+<li><a href="#Allegrocl_nn4">Command Line Options</a>
+<li><a href="#Allegrocl_nn5">Inserting user code into generated files</a>
+</ul>
+<li><a href="#Allegrocl_nn6">Wrapping Overview</a>
+<ul>
+<li><a href="#Allegrocl_nn7">Function Wrapping</a>
+<li><a href="#Allegrocl_nn8">Foreign Wrappers</a>
+<li><a href="#Allegrocl_nn9">FFI Wrappers</a>
+<li><a href="#Allegrocl_nn10">Non-overloaded Defuns</a>
+<li><a href="#Allegrocl_nn11">Overloaded Defuns</a>
+<li><a href="#Allegrocl_nn12">What about constant and variable access?</a>
+<li><a href="#Allegrocl_nn13">Object Wrapping</a>
+</ul>
+<li><a href="#Allegrocl_nn14">Wrapping Details</a>
+<ul>
+<li><a href="#Allegrocl_nn15">Namespaces</a>
+<li><a href="#Allegrocl_nn16">Constants</a>
+<li><a href="#Allegrocl_nn17">Variables</a>
+<li><a href="#Allegrocl_nn18">Enumerations</a>
+<li><a href="#Allegrocl_nn19">Arrays</a>
+<li><a href="#Allegrocl_nn20">Classes and Structs and Unions (oh my!)</a>
+<ul>
+<li><a href="#Allegrocl_nn21">CLOS wrapping of</a>
+<li><a href="#Allegrocl_nn22">CLOS Inheritance</a>
+<li><a href="#Allegrocl_nn23">Member fields and functions</a>
+<li><a href="#Allegrocl_nn24">Why not directly access C++ classes using foreign types?</a>
+</ul>
+<li><a href="#Allegrocl_nn25">Templates</a>
+<ul>
+<li><a href="#Allegrocl_nn26">Generating wrapper code for templates</a>
+<li><a href="#Allegrocl_nn27">Implicit Template instantiation</a>
+</ul>
+<li><a href="#Allegrocl_nn28">Typedef, Templates, and Synonym Types</a>
+<ul>
+<li><a href="#Allegrocl_nn29">Choosing a primary type</a>
+</ul>
+<li><a href="#Allegrocl_nn30">Function overloading/Parameter defaulting</a>
+<li><a href="#Allegrocl_nn31">Operator wrapping and Operator overloading</a>
+<li><a href="#Allegrocl_nn32">Varargs</a>
+<li><a href="#Allegrocl_nn33">C++ Exceptions</a>
+<li><a href="#Allegrocl_nn34">Pass by value, pass by reference</a>
+</ul>
+<li><a href="#Allegrocl_nn35">Typemaps</a>
+<ul>
+<li><a href="#Allegrocl_nn36">Code Generation in the C++ Wrapper</a>
+<ul>
+<li><a href="#Allegrocl_nn37">IN Typemap</a>
+<li><a href="#Allegrocl_nn38">OUT Typemap</a>
+<li><a href="#Allegrocl_nn39">CTYPE Typemap</a>
+</ul>
+<li><a href="#Allegrocl_nn40">Code generation in Lisp wrappers</a>
+<ul>
+<li><a href="#Allegrocl_nn41">LIN Typemap</a>
+<li><a href="#Allegrocl_nn42">LOUT Typemap</a>
+<li><a href="#Allegrocl_nn43">FFITYPE Typemap</a>
+<li><a href="#Allegrocl_nn44">LISPTYPE Typemap</a>
+<li><a href="#Allegrocl_nn45">LISPCLASS Typemap</a>
+</ul>
+<li><a href="#Allegrocl_nn46">Modifying SWIG behavior using typemaps</a>
+</ul>
+<li><a href="#Allegrocl_nn47">Identifier Converter functions</a>
+<ul>
+<li><a href="#Allegrocl_nn48">Creating symbols in the lisp environment</a>
+<li><a href="#Allegrocl_nn49">Existing identifier-converter functions</a>
+<ul>
+<li><a href="#Allegrocl_nn50">identifier-convert-null</a>
+<li><a href="#Allegrocl_nn51">identifier-convert-lispify</a>
+<li><a href="#Allegrocl_nn52">Default identifier to symbol conversions</a>
+</ul>
+<li><a href="#Allegrocl_nn53">Defining your own identifier-converter</a>
+<li><a href="#Allegrocl_nn54">Instructing SWIG to use a particular identifier-converter</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes SWIG's support of Allegro Common Lisp. Allegro
+CL is a full-featured implementation of the Common Lisp language
+standard that includes many vendor-specific enhancements and add-on
+modules for increased usability.
+</p>
+
+<p>
+One such module included in Allegro CL is the Foreign Functions
+Interface (FFI). This module, tailored primarily toward interfacing
+with C/C++ and, historically, Fortran, provides a means by which
+compiled foreign code can be loaded into a running lisp
+environment and executed. The interface supports the calling of
+foreign functions and methods, allows for executing lisp routines
+from foreign code (callbacks), and the passing of data between foreign
+and lisp code.
+</p>
+
+<p>
+The goal of this module is to make it possible to quickly generate the
+necessary foreign function definitions so one can make use of C/C++
+foreign libraries directly from lisp without the tedium of having to
+code them by hand. When necessary, it will also generate further C/C++
+code that will need to be linked with the intended library for proper
+interfacing from lisp. It has been designed with an eye toward
+flexibility. Some foreign function calls may release the heap, while
+other should not. Some foreign functions should automatically convert
+lisp strings into native strings, while others should not. These
+adjustments and many more are possible with the current module.
+</p>
+
+<p>
+It is significant to note that, while this is a vendor-specific
+module, we would like to acknowledge the current and ongoing
+work by developers in the open source lisp community that are
+working on similar interfaces to implementation-independent
+foreign function interfaces (UFFI or CFFI, for example). Such
+work can only benefit the lisp community, and we would not
+be unhappy to see some enterprising folk use this work to add
+to it.
+</p>
+
+<H2><a name="Allegrocl_nn2"></a>16.1 Basics</H2>
+
+
+<H3><a name="Allegrocl_nn3"></a>16.1.1 Running Swig</H3>
+
+
+<p>
+If you're reading this, you must have some library you need to
+generate an interface for. In order for SWIG to do this work, however,
+it needs a bit of information about how it should go about creating
+your interface, and what you are interfacing to.
+</p>
+
+<p>
+SWIG expects a description of what in the foreign interface you wish
+to connect to. It must consisting of C/C++ declarations and special
+SWIG directives. SWIG can be furnished with a header file, but an
+interface can also be generated without library headers by supplying a
+simple text file--called the interface file, which is typically named
+with a <tt>.i</tt> extension--containing any foreign declarations of
+identifiers you wish to use. The most common approach is to use a an
+interface file with directives to parse the needed headers. A straight
+parse of library headers will result in usable code, but SWIG
+directives provides much freedom in how a user might tailor the
+generated code to their needs or style of coding.
+</p>
+
+<p>
+Note that SWIG does not require any function definitions; the
+declarations of those functions is all that is necessary. Be careful
+when tuning the interface as it is quite possible to generate code
+that will not load or compile.
+</p>
+
+<p>
+An example interface file is shown below. It makes use of two SWIG
+directives, one of which requests that the declarations in a header
+file be used to generate part of the interface, and also includes an
+additional declaration to be added.</p>
+
+<div class="code">example.i
+<pre>
+%module example
+
+%include "header.h"
+
+int fact(int n);
+</pre>
+</div>
+
+<p>The contents of header.h are very simple:</p>
+<div class="code">header.h
+<pre>
+int fact(char *statement);   // pass it a fact, and it will rate it.
+</pre>
+</div>
+
+<p>The contents of example.cl will look like this:</p>
+
+<div class="targetlang">example.cl
+<pre>
+(defpackage :example
+  (:use :common-lisp :swig :ff :excl))
+
+  ... helper routines for defining the interface ...
+
+(swig-in-package ())
+
+(swig-defun ("fact")
+  ((PARM0_statement cl:string (* :char) ))
+  (:returning (:int )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_statement))
+  (swig-ff-call SWIG_arg0)))
+
+(swig-defun ("fact")
+  ((PARM0_n cl:integer :int ))
+  (:returning (:int )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_n))
+  (swig-ff-call SWIG_arg0)))
+
+(swig-dispatcher ("fact" :type :function :arities (1)))
+</pre>
+</div>
+
+<p>
+The generated file contains calls to internal swig helper
+functions. In this case there are two calls to swig-defun.
+These calls will expand into code that will make the appropriate
+definitions using the Allegro FFI. Note also, that this code is
+<b>erroneous</b>. Function overloading is not supported in C, and this
+code will not compile even though SWIG did not complain.
+</p>
+
+<p>
+In order to generate a C interface to Allegro CL using this code run
+swig using the <tt>-allegrocl</tt> option, as below:
+</p>
+
+<div class="shell">
+<pre>
+% swig -allegrocl example.i
+</pre>
+</div>
+
+<p>
+When building an interface to C++ code, include the <tt>-c++</tt> option:
+</p>
+
+<div class="shell">
+<pre>
+% swig -allegrocl -c++ example.i
+</pre>
+</div>
+
+<p>
+As a result of running one of the above commands, a file named <tt>example.cl</tt> 
+will be generated containing the lisp side of the interface. As well, a file 
+<tt>example_wrap.cxx</tt> is also generated, containing C/C++ wrapper code to
+facilitate access to C++ methods, enumeration values, and constant values.
+Wrapper functions are necessary in C++ due to the lack of a standard for mangling 
+the names of symbols across all C++ compilers. These wrapper functions are
+exported from the shared library as appropriate, using the C name mangling
+convention. The lisp code that is generated will interface to your foreign
+library through these wrappers.
+</p>
+
+<p>
+It is possible to disable the creation of the .cxx file when generating a C
+interface by using the -nocwrap command-line argument. For interfaces that
+don't contain complex enum or constant expressions, contain nested struct/union
+declarations, or doesn't need to use many of the SWIG customization featuers, 
+this will result in a more streamlined, direct interface to the
+intended module.
+</p>
+
+<p>
+The generated wrapper file is below. It contains very simple
+wrappers by default, that simply pass the arguments to the
+actual function.
+</p>
+
+<div class="code">example_wrap.i
+<pre>
+   ... lots of SWIG internals ...
+
+EXPORT int ACL___fact__SWIG_0 (char *larg1) {
+    int lresult = (int)0 ;
+    char *arg1 = (char *) 0 ;
+    int result;
+    
+    arg1 = larg1;
+    try {
+        result = (int)fact(arg1);
+        
+        lresult = result;
+        return lresult;
+    } catch (...) {
+        return (int)0;
+    }
+}
+
+
+EXPORT int ACL___fact__SWIG_1 (int larg1) {
+    int lresult = (int)0 ;
+    int arg1 ;
+    int result;
+    
+    arg1 = larg1;
+    try {
+        result = (int)fact(arg1);
+        
+        lresult = result;
+        return lresult;
+    } catch (...) {
+        return (int)0;
+    }
+}
+</pre>
+</div>
+
+<p>
+And again, the generated lisp code. Note that it differs from
+what is generated when parsing C code:
+</p>
+
+<div class="targetlang">
+<pre>
+   ...
+
+(swig-in-package ())
+
+(swig-defmethod ("fact" "ACL___fact__SWIG_0" :type :function :arity 1)
+  ((PARM0_statement cl:string (* :char) ))
+  (:returning (:int )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_statement))
+  (swig-ff-call SWIG_arg0)))
+
+(swig-defmethod ("fact" "ACL___fact__SWIG_1" :type :function :arity 1)
+  ((PARM0_n cl:integer :int ))
+  (:returning (:int )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_n))
+  (swig-ff-call SWIG_arg0)))
+
+(swig-dispatcher ("fact" :type :function :arities (1)))
+</pre>
+</div>
+
+<p>In this case, the interface generates two swig-defmethod forms and
+a swig-dispatcher form. This provides a single functional interface for
+all overloaded routines. A more detailed description of this features 
+is to be found in the section titled <b>Function overloading/Parameter defaulting</b>.
+
+<p>
+In order to load a C++ interface, you will need to build a shared library
+from example_wrap.cxx. Be sure to link in the actual library you created
+the interface for, as well as any other dependent shared libraries. For
+example, if you intend to be able to call back into lisp, you will also
+need to link in the Allegro shared library. The library you create from
+the C++ wrapper will be what you then load into Allegro CL.
+</p>
+
+<H3><a name="Allegrocl_nn4"></a>16.1.2 Command Line Options</H3>
+
+
+<p>
+There are three Allegro CL specific command-line option:
+</p>
+
+<div class="shell">
+<pre>
+swig -allegrocl [ options ] filename
+
+   -identifier-converter [name] - Binds the variable swig:*swig-identifier-convert* 
+                                  in the generated .cl file to <tt>name</tt>.
+				  This function is used to generate symbols
+				  for the lisp side of the interface. 
+
+   -cwrap - [default] Generate a .cxx file containing C wrapper function when
+            wrapping C code. The interface generated is similar to what is
+	    done for C++ code.
+   -nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable
+              for modules with simple interfaces. Can not handle all legal enum
+	      and constant constructs, or take advantage of SWIG customization features.
+
+   -isolate - With this command-line argument, all lisp helper functions are defined
+              in a unique package named <tt>swig.&lt;module-name&gt;</tt> rather than
+	      <tt>swig</tt>. This prevents conflicts when the module is
+	      intended to be used with other swig generated interfaces that may, 
+	      for instance, make use of different identifier converters.
+</pre>
+</div>
+
+<p>
+See <a href="#Allegrocl_nn47">Section 17.5 Identifier converter
+functions</a> for more details.
+</p>
+
+<H3><a name="Allegrocl_nn5"></a>16.1.3 Inserting user code into generated files</H3>
+
+
+<p>
+It is often necessary to include user-defined code into the
+automatically generated interface files. For example, when building
+a C++ interface, example_wrap.cxx will likely not compile unless
+you add a <tt>#include "header.h"</tt> directive. This can be done
+using the SWIG <tt>%insert(section) %{ ...code... %}</tt> directive:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+%insert("runtime") %{
+#include "header.h"
+%}
+
+%include "header.h"
+
+int fact(int n);
+</pre>
+</div>
+
+<p>
+Additional sections have been added for inserting into the
+generated lisp interface file
+</p>
+<ul>
+  <li><tt>lisphead</tt> - inserts before type declarations</li>
+  <li><tt>lisp</tt> - inserts after type declarations according to
+    where it appears in the .i file</li>
+</ul>
+<p>
+Note that the block <tt>%{ ... %}</tt> is effectively a shortcut for
+<tt>%insert("runtime") %{ ... %}</tt>.
+</p>
+
+
+<H2><a name="Allegrocl_nn6"></a>16.2 Wrapping Overview</H2>
+
+
+<p>
+New users to SWIG are encouraged to read
+<a href="SWIG.html#SWIG">SWIG Basics</a>, and
+<a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>, for those
+interested in generating an interface to C++.
+</p>
+
+<H3><a name="Allegrocl_nn7"></a>16.2.1 Function Wrapping</H3>
+
+
+  <p>
+  Writing lisp code that directly invokes functions at the foreign
+  function interface level can be cumbersome. Data must often be
+  translated between lisp and foreign types, data extracted from
+  objects, foreign objects allocated and freed upon completion of
+  the foreign call. Dealing with pointers can be unwieldy when it
+  comes to keeping them distinct from other valid integer values.
+  </p>
+
+  <p>
+  We make an attempt to ease some of these burdens by making the
+  interface to foreign code much more lisp-like, rather than C
+  like. How this is done is described in later chapters. The
+  layers themselves, appear as follows:
+  </p>
+
+  <div class="diagram">
+  <pre>
+        ______________
+       |              |  (foreign side)
+       | Foreign Code |  What we're generating an interface to.
+       |______________|
+               |
+	       |
+        _______v______
+       |              |  (foreign side)
+       | Wrapper code |  extern "C" wrappers calling C++ 
+       |______________|  functions and methods.
+               |
+    .  . . - - + - - . .  .
+        _______v______
+       |              |  (lisp side)
+       |  FFI Layer   |  Low level lisp interface. ff:def-foreign-call,
+       |______________|  ff:def-foreign-variable
+               |
+	       +----------------------------
+        _______v______              _______v______
+       |              |            |              | (lisp side)    
+       |    Defuns    |            |  Defmethods  | wrapper for overloaded
+       |______________|            |______________| functions or those with
+        (lisp side)                        |        defaulted arguments
+	Wrapper for non-overloaded         |
+	functions and methods       _______v______
+	                           |              | (lisp side)
+				   |    Defuns    | dispatch function
+				   |______________| to overloads based
+				                    on arity
+  </pre>
+  </div>
+
+<H3><a name="Allegrocl_nn8"></a>16.2.2 Foreign Wrappers</H3>
+
+
+  <p>
+    These wrappers are as generated by SWIG default. The types of
+    function parameters can be transformed in place using the CTYPE
+    typemap. This is use for converting pass-by-value parameters to
+    pass-by-reference where necessary. All wrapper parameters are then
+    bound to local variables for possible transformation of values
+    (see LIN typemap). Return values can be transformed via the OUT
+    typemap. 
+  </p>
+
+<H3><a name="Allegrocl_nn9"></a>16.2.3 FFI Wrappers</H3>
+
+
+  <p>
+    These are the generated ff:def-foreign-call forms. No typemaps are
+    applicable to this layer, but the <tt>%ffargs</tt> directive is
+    available for use in .i files, to specify which keyword arguments
+    should be specified for a given function.
+  </p>
+  
+  <div class="code">ffargs.i:
+  <pre>
+%module ffargs
+
+%ffargs(strings_convert="nil",call_direct="t") foo;
+%ffargs(strings_convert="nil",release_heap=":never",optimize_for_space="t") bar;
+
+int foo(float f1, float f2);
+int foo(float f1, char c2);
+
+void bar(void *lisp_fn);
+
+char *xxx();
+  </pre>
+  </div>
+
+  <p>Generates:
+  </p>
+  <div class="targetlang">ffargs.cl:
+  <pre>
+(swig-in-package ())
+
+(swig-defmethod ("foo" "ACL___foo__SWIG_0" :type :function :arity 2)
+  ((PARM0_f1 cl:single-float :float )
+   (PARM1_f2 cl:single-float :float ))
+  (:returning (:int )
+   :call-direct t
+   :strings-convert nil)
+  (let ((SWIG_arg0 PARM0_f1))
+  (let ((SWIG_arg1 PARM1_f2))
+  (swig-ff-call SWIG_arg0 SWIG_arg1))))
+
+(swig-defmethod ("foo" "ACL___foo__SWIG_1" :type :function :arity 2)
+  ((PARM0_f1 cl:single-float :float )
+   (PARM1_c2 cl:character :char character))
+  (:returning (:int )
+   :call-direct t
+   :strings-convert nil)
+  (let ((SWIG_arg0 PARM0_f1))
+  (let ((SWIG_arg1 PARM1_c2))
+  (swig-ff-call SWIG_arg0 SWIG_arg1))))
+
+(swig-dispatcher ("foo" :type :function :arities (2)))
+(swig-defun ("bar" "ACL___bar__SWIG_0" :type :function)
+  ((PARM0_lisp_fn  (* :void) ))
+  (:returning (:void )
+   :release-heap :never
+   :optimize-for-space t
+   :strings-convert nil)
+  (let ((SWIG_arg0 PARM0_lisp_fn))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("xxx" "ACL___xxx__SWIG_0" :type :function)
+  (:void)
+  (:returning ((* :char) )
+   :strings-convert t)
+  (swig-ff-call))
+  </pre>
+  </div>
+
+  <div class="code">
+    <pre>%ffargs(strings_convert="t");</pre>
+  </div>
+
+  <p>
+    Is the only default value specified in <tt>allegrocl.swg</tt> to force
+    the muffling of warnings about automatic string conversion when defining
+    ff:def-foreign-call's.
+  </p>
+
+<H3><a name="Allegrocl_nn10"></a>16.2.4 Non-overloaded Defuns</H3>
+
+
+  <p>
+    These are simple defuns. There is no typechecking of arguments.
+    Parameters are bound to local variables for possible
+    transformation of values, such as pulling values out of instance
+    slots or allocating temporary stack allocated structures, via the
+    <tt>lin</tt> typemap. These arguments are then passed to the
+    foreign-call (where typechecking may occur). The return value from
+    this function can be manipulated via the <tt>lout</tt> typemap.
+  </p>
+
+<H3><a name="Allegrocl_nn11"></a>16.2.5 Overloaded Defuns</H3>
+
+
+  <p>
+    In the case of overloaded functions, mulitple layers are
+    generated. First, all the overloads for a given name are separated
+    out into groups based on arity, and are wrapped in
+    defmethods. Each method calls a distinct wrapper function, but are
+    themselves distinguished by the types of their arguments
+    (see <tt>lispclass</tt> typemap). These are further wrapped in a
+    dispatching function (defun) which will invoke the appropriate
+    generic-function based on arity. This provides a single functional
+    interface to all overloads. The return value from this function
+    can be manipulated via the <tt>lout</tt> typemap.
+  </p>
+
+<H3><a name="Allegrocl_nn12"></a>16.2.6 What about constant and variable access?</H3>
+
+
+  <p>
+    Along with the described functional layering, when creating a .cxx wrapper, 
+    this module will generate getter and--if not immutable--setter,
+    functions for variables and constants. If the -nocwrap option is used,
+    <tt>defconstant</tt> and <tt>ff:def-foreign-variable</tt> forms will be
+    generated for accessing constants and global variables. These, along with
+    the <tt>defuns</tt> listed above are the intended API for calling
+    into the foreign module.
+  </p>
+
+<H3><a name="Allegrocl_nn13"></a>16.2.7 Object Wrapping</H3>
+
+
+  <p>
+  All non-primitive types (Classes, structs, unions, and typedefs
+  involving same) have a corresponding foreign-type defined on the
+  lisp side via ff:def-foreign-type.
+  </p>
+
+  <p>
+  All non-primitive types are further represented by a CLOS class,
+  created via defclass. An attempt is made to create the same class
+  hierarchy, with all classes inheriting directly or indirectly from
+  ff:foreign-pointer. Further, wherever it is apparent, all pointers
+  returned from foreign code are wrapped in a CLOS instance of the
+  appropriate class. For ff:def-foreign-calls that have been defined
+  to expect a :foreign-address type as argument, these CLOS instances
+  can legally be passed and the pointer to the C++ object
+  automatically extracted. This is a natural feature of Allegro's
+  foreign function interface.
+  </p>
+
+<H2><a name="Allegrocl_nn14"></a>16.3 Wrapping Details</H2>
+
+
+  <p>
+    In this section is described how particular C/C++ constructs are
+    translated into lisp.
+  </p>
+
+<H3><a name="Allegrocl_nn15"></a>16.3.1 Namespaces</H3>
+
+
+  <p>
+    C++ namespaces are translated into Lisp packages by SWIG. The
+    Global namespace is mapped to a package named by the <tt>%module</tt>
+    directive or the <tt>-module</tt> command-line argument. Further
+    namespaces are generated by the <tt>swig-defpackage</tt> utility
+    function and given names based on Allegro CLs nested namespace
+    convention. For example:
+  </p>
+
+    <div class="code">foo.i:
+    <pre>
+%module foo
+
+%{
+#include "foo.h"
+%}
+
+%include "foo.h"
+
+namespace car {
+   ...
+   namespace tires {
+      int do_something(int n);
+   }
+}
+    </pre>
+    </div>
+  <p>Generates the following code.
+  </p>
+    <div class="targetlang">foo.cl
+    <pre>
+(defpackage :foo
+  (:use :common-lisp :swig :ff :excl))
+
+...
+
+(swig-defpackage ("car"))
+(swig-defpackage ("car" "tires"))
+
+...
+
+(swig-in-package ("car" "tires"))
+(swig-defun ("do_something" "ACL_car_tires__do_something__SWIG_0" :type :function)
+  ((PARM0_n  :int ))
+  (:returning (:int )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_n))
+  (swig-ff-call SWIG_arg0)))
+    </pre>
+    </div>
+
+    <p>
+      The above interface file would cause packages foo, foo.car, and
+      foo.car.tires to be created. One would find the function wrapper
+      for do_something defined in the foo.car.tires package(*).
+    </p>
+
+    <p>(<b>*</b>) Except for the package named by the module, all
+      namespace names are passed to the identifier-converter-function
+      as strings with a <tt>:type</tt> of <tt>:namespace</tt>. It is the
+      job of this function to generate the desired symbol, accounting for
+      case preferences, additional naming cues, etc.
+    </p>
+
+    <p>
+      Note that packages created by <tt>swig-defpackage</tt> do not
+      use the COMMON-LISP or EXCL package. This reduces possible
+      conflicts when defining foreign types via the SWIG interface
+      in <b>all but the toplevel modules package</b>. This may
+      lead to confusion if, for example, the current package is
+      <tt>foo.car.tires</tt> and you attempt to use a common-lisp
+      function such as <tt>(car '(1 2 3)</tt>.
+    </p>
+
+<H3><a name="Allegrocl_nn16"></a>16.3.2 Constants</H3>
+
+
+    
+    <p>
+      Constants, as declared by the preprocessor #define macro or SWIG
+      <tt>%constant</tt> directive, are included in SWIGs parse tree
+      when it can be determined that they are, or could be reduced to,
+      a literal value. Such values are translated into defconstant
+      forms in the generated lisp wrapper when the -nocwrap command-line
+      options is used. Else, wrapper functions are generated as in the
+      case of variable access (see section below).
+    </p>
+    <p>
+      Here are examples of simple preprocessor constants when using -nocwrap.
+    </p>
+      <div class="code">
+      <pre>
+#define A 1                    =&gt; (swig-defconstant "A" 1)  
+#define B 'c'                  =&gt; (swig-defconstant "B" #\c)
+#define C B                    =&gt; (swig-defconstant "C" #\c)
+#define D 1.0e2                =&gt; (swig-defconstant "D" 1.0d2)
+#define E 2222                 =&gt; (swig-defconstant "E" 2222)
+#define F (unsigned int)2222   =&gt; no code generated
+#define G 1.02e2f              =&gt; (swig-defconstant "G" 1.02f2)
+#define H foo                  =&gt; no code generated
+      </pre>
+      </div>
+
+      <p>
+      Note that where SWIG is unable to determine if a constant is
+      a literal, no node is added to the SWIG parse tree, and so
+      no values can be generated.
+      </p>
+
+    <p>
+      For preprocessor constants containing expressions which can be
+      reduced to literal values, nodes are created, but with no simplification
+      of the constant value. A very very simple infix to prefix converter
+      has been implemented that tries to do the right thing for simple cases, but
+      does not for more complex expressions. If the literal parser determines
+      that something is wrong, a warning will be generated and the literal 
+      expression will be included in the generated code, but commented out.
+    </p>
+      
+      <div class="code">
+      <pre>
+#define I A + E                =&gt; (swig-defconstant "I" (+ 1 2222))
+#define J 1|2                  =&gt; (swig-defconstant "J" (logior 1 2))
+#define Y 1 + 2 * 3 + 4        =&gt; (swig-defconstant "Y" (* (+ 1 2) (+ 3 4)))
+#define Y1 (1 + 2) * (3 + 4)   =&gt; (swig-defconstant "Y1" (* (+ 1 2) (+ 3 4)))
+#define Y2 1 * 2 + 3 * 4       =&gt; (swig-defconstant "Y2" (* 1 (+ 2 3) 4))  ;; WRONG
+#define Y3 (1 * 2) + (3 * 4)   =&gt; (swig-defconstant "Y3" (* 1 (+ 2 3) 4))  ;; WRONG
+#define Z 1 + 2 - 3 + 4 * 5    =&gt; (swig-defconstant "Z" (* (+ 1 (- 2 3) 4) 5)) ;; WRONG
+      </pre>
+      </div>
+      <p>
+	Users are cautioned to get to know their constants before use, or
+	not use the <tt>-nocwrap</tt> command-line option.
+      </p>
+
+<H3><a name="Allegrocl_nn17"></a>16.3.3 Variables</H3>
+
+
+    <p>
+      For C wrapping, a def-foreign-variable call is generated for access
+      to global variables.
+    </p>
+    <p>
+      When wrapping C++ code, both global and member variables, getter
+      wrappers are generated for accessing their value, and if not immutable,
+      setter wrappers as well. In the example below, note the lack of a 
+      setter wrapper for global_var, defined as const.
+    </p>
+
+    <div class="code">vars.h
+    <pre>
+namespace nnn {
+  int const global_var = 2;
+  float glob_float = 2.0;
+}
+    </pre>
+    </div>
+
+    <p>
+    Generated code:
+    </p>
+    <div class="targetlang">vars.cl
+    <pre>
+(swig-in-package ("nnn"))
+(swig-defun ("global_var" "ACL_nnn__global_var_get__SWIG_0" :type :getter)
+  (:void)
+  (:returning (:int )
+   :strings-convert t)
+  (swig-ff-call))
+
+
+(swig-defun ("glob_float" "ACL_nnn__glob_float_set__SWIG_0" :type :setter)
+  ((PARM0_glob_float  :float ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_glob_float))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("glob_float" "ACL_nnn__glob_float_get__SWIG_0" :type :getter)
+  (:void)
+  (:returning (:float )
+   :strings-convert t)
+  (swig-ff-call))
+    </pre>
+    </div>
+
+    <p>
+      Note also, that where applicable, setter wrappers are implemented
+      as setf methods on the getter function, providing a lispy interface
+      to the foreign code.
+    </p>
+
+    <div class="targetlang">
+    <pre>
+user&gt; (load "globalvar.dll")
+; Foreign loading globalvar.dll.
+t
+user&gt; (load "globalvar.cl")
+; Loading c:\mikel\src\swig\test\globalvar.cl
+t
+user&gt; 
+globalvar&gt; (globalvar.nnn::global_var)
+2
+globalvar&gt; (globalvar.nnn::glob_float)
+2.0
+globalvar&gt; (setf (globalvar.nnn::glob_float) 3.0)
+3.0
+globalvar&gt; (globalvar.nnn::glob_float)
+3.0
+    </pre>
+    </div>
+
+<H3><a name="Allegrocl_nn18"></a>16.3.4 Enumerations</H3>
+
+
+    <p>
+      In C, an enumeration value is an integer value, while in C++ an
+      enumeration value is implicitly convertible to an integer value,
+      but can also be distinguished by it's enum type. For each enum
+      declaration a def-foreign-type is generated, assigning the enum
+      a default type of :int. Users may adjust the foreign type of
+      enums via SWIG <tt>typemaps</tt>.
+    </p>
+
+    <p>
+      Enum values are a bit trickier as they can be initialized using
+      any valid C/C++ expression. In C with the -nocwrap command-line option,
+      we handle the typical cases (simple integer initialization) and
+      generate a defconstant form for each enum value. This has the advantage
+      of it not being necessary to probe into foreign space to retrieve enum
+      values. When generating a .cxx wrapper file, a more general solution is
+      employed. A wrapper variable is created in the module_wrap.cxx file, and
+      a ff:def-foreign-variable call is generated to retrieve it's value into lisp. 
+    </p>
+
+    <p>For example, the following header file
+      <div class="code">enum.h:
+      <pre>
+enum COL { RED, GREEN, BLUE };	
+enum FOO { FOO1 = 10, FOO2, FOO3 };
+      </pre>
+      </div>
+      <p>
+      In -nocwrap mode, generates
+      </p>
+      <div class="targetlang">enum.cl:
+      <pre>
+(swig-def-foreign-type "COL" :int)
+(swig-defconstant "RED" 0)
+(swig-defconstant "GREEN" (+ #.(swig-insert-id "RED" () :type :constant) 1))
+(swig-defconstant "BLUE" (+ #.(swig-insert-id "GREEN" () :type :constant) 1))
+
+(swig-def-foreign-type "FOO" :int)
+(swig-defconstant "FOO1" 10)
+(swig-defconstant "FOO2" (+ #.(swig-insert-id "FOO1" () :type :constant) 1))
+(swig-defconstant "FOO3" (+ #.(swig-insert-id "FOO2" () :type :constant) 1))
+      </pre>
+      </div>
+
+    <p>And when generating a .cxx wrapper
+      <div class="code">enum_wrap.cxx:
+      <pre>
+EXPORT const int ACL_ENUM___RED__SWIG_0 = RED;
+EXPORT const int ACL_ENUM___GREEN__SWIG_0 = GREEN;
+EXPORT const int ACL_ENUM___BLUE__SWIG_0 = BLUE;
+EXPORT const int ACL_ENUM___FOO1__SWIG_0 = FOO1;
+EXPORT const int ACL_ENUM___FOO2__SWIG_0 = FOO2;
+EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3;
+      </pre>
+      </div>
+    <p>
+    and
+    </p>
+      <div class="targetlang">enum.cl:
+      <pre>
+(swig-def-foreign-type "COL" :int)
+(swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
+(swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
+(swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
+
+(swig-def-foreign-type "FOO" :int)
+(swig-defvar "FOO1" "ACL_ENUM___FOO1__SWIG_0" :type :constant)
+(swig-defvar "FOO2" "ACL_ENUM___FOO2__SWIG_0" :type :constant)
+(swig-defvar "FOO3" "ACL_ENUM___FOO3__SWIG_0" :type :constant)
+
+      </pre>
+      </div>
+
+<H3><a name="Allegrocl_nn19"></a>16.3.5 Arrays</H3>
+
+
+    <p>
+    One limitation in the Allegro CL foreign-types module, is that,
+    without macrology, expressions may not be used to specify the
+    dimensions of an array declaration. This is not a horrible
+    drawback unless it is necessary to allocate foreign structures
+    based on the array declaration using ff:allocate-fobject. When it
+    can be determined that an array bound is a valid numeric value,
+    SWIG will include this in the generated array declaration on the
+    lisp side, otherwise the value will be included, but commented out.
+    </p>
+
+    <p>
+      Below is a comprehensive example, showing a number of legal
+      C/C++ array declarations and how they are translated
+      into foreign-type specifications in the generated lisp code.
+    </p>
+    <div class="code">array.h
+    <pre>
+#define MAX_BUF_SIZE 1024
+
+namespace FOO {
+  int global_var1[13];
+  float global_var2[MAX_BUF_SIZE];
+
+}
+
+enum COLOR { RED = 10, GREEN = 20, BLUE, PURPLE = 50, CYAN };
+
+namespace BAR {
+  char global_var3[MAX_BUF_SIZE + 1];
+  float global_var4[MAX_BUF_SIZE][13];
+  signed short global_var5[MAX_BUF_SIZE + MAX_BUF_SIZE];
+
+  int enum_var5[GREEN];
+  int enum_var6[CYAN];
+
+  COLOR enum_var7[CYAN][MAX_BUF_SIZE];
+}
+    </pre>
+    </div>
+
+    <p>
+    Generates:
+    </p>
+
+    <div class="targetlang">array.cl
+    <pre>
+(in-package #.*swig-module-name*)
+
+(swig-defpackage ("FOO"))
+(swig-defpackage ("BAR"))
+
+(swig-in-package ())
+(swig-def-foreign-type "COLOR" :int)
+(swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
+(swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
+(swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
+(swig-defvar "PURPLE" "ACL_ENUM___PURPLE__SWIG_0" :type :constant)
+(swig-defvar "CYAN" "ACL_ENUM___CYAN__SWIG_0" :type :constant)
+
+(swig-in-package ())
+
+(swig-defconstant "MAX_BUF_SIZE" 1024)
+(swig-in-package ("FOO"))
+
+(swig-defun ("global_var1" "ACL_FOO__global_var1_get__SWIG_0" :type :getter)
+  (:void)
+  (:returning ((* :int) )
+   :strings-convert t)
+  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
+
+
+(swig-defun ("global_var2" "ACL_FOO__global_var2_set__SWIG_0" :type :setter)
+  ((global_var2  (:array :float 1024) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 global_var2))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-in-package ())
+(swig-in-package ("BAR"))
+(swig-defun ("global_var3" "ACL_BAR__global_var3_set__SWIG_0" :type :setter)
+  ((global_var3  (:array :char #|1024+1|#) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 global_var3))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("global_var4" "ACL_BAR__global_var4_set__SWIG_0" :type :setter)
+  ((global_var4  (:array (:array :float 13) 1024) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 global_var4))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("global_var4" "ACL_BAR__global_var4_get__SWIG_0" :type :getter)
+  (:void)
+  (:returning ((* (:array :float 13)) )
+   :strings-convert t)
+  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
+
+
+(swig-defun ("global_var5" "ACL_BAR__global_var5_set__SWIG_0" :type :setter)
+  ((global_var5  (:array :short #|1024+1024|#) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 global_var5))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("enum_var5" "ACL_BAR__enum_var5_set__SWIG_0" :type :setter)
+  ((enum_var5  (:array :int #|GREEN|#) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 enum_var5))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("enum_var6" "ACL_BAR__enum_var6_set__SWIG_0" :type :setter)
+  ((enum_var6  (:array :int #|CYAN|#) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 enum_var6))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("enum_var7" "ACL_BAR__enum_var7_set__SWIG_0" :type :setter)
+  ((enum_var7  (:array (:array #.(swig-insert-id "COLOR" ()) 1024) #|CYAN|#) ))
+  (:returning (:void )
+   :strings-convert t)
+  (let ((SWIG_arg0 enum_var7))
+  (swig-ff-call SWIG_arg0)))
+
+
+(swig-defun ("enum_var7" "ACL_BAR__enum_var7_get__SWIG_0" :type :getter)
+  (:void)
+  (:returning ((* (:array #.(swig-insert-id "COLOR" ()) 1024)) )
+   :strings-convert t)
+  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
+    </pre>
+    </div>
+
+<H3><a name="Allegrocl_nn20"></a>16.3.6 Classes and Structs and Unions (oh my!)</H3>
+
+
+<H4><a name="Allegrocl_nn21"></a>16.3.6.1 CLOS wrapping of</H4>
+
+
+    <p>
+      Classes, unions, and structs are all treated the same way by the
+      interface generator. For any of these objects, a
+      def-foreign-type and a defclass form are generated.  For every
+      function that returns an object (or pointer/reference) of C/C++
+      type <tt>X</tt>, the wrapping defun (or defmethod) on the Lisp
+      side will automatically wrap the pointer returned in an instance
+      of the apropriate class. This makes it much easier to write and
+      debug code than if pointers were passed around as a jumble of
+      integer values.
+    </p>
+
+<H4><a name="Allegrocl_nn22"></a>16.3.6.2 CLOS Inheritance</H4>
+
+
+    <p>
+      The CLOS class schema generated by the interface mirrors the
+      inheritance of the classes in foreign code, with the
+      ff:foreign-pointer class at its root. ff:foreign-pointer is a thin
+      wrapper for pointers that is made available by the foreign function
+      interface. It's key benefit is that it may be passed as an argument
+      to any ff:def-foreign-call that is expecting a pointer as the
+      parameter.
+    </p>
+
+<H4><a name="Allegrocl_nn23"></a>16.3.6.3 Member fields and functions</H4>
+
+
+    <p>
+      All public fields will have accessor getter/setter functions
+      generated for them, as appropriate. All public member functions
+      will have wrapper functions generated.
+    </p>
+
+    <p>
+      We currently ignore anything that isn't <tt>public</tt> (i.e.
+      <tt>private</tt> or <tt>protected</tt>), because the C++ compiler
+      won't allow the wrapper functions to access such fields. Likewise,
+      the interface does nothing for <tt>friend</tt> directives, 
+    </p>
+
+<H4><a name="Allegrocl_nn24"></a>16.3.6.4 Why not directly access C++ classes using foreign types?</H4>
+
+
+    <p>
+      The def-foreign-type generated by the SWIG interface is
+      currently incomplete. We can reliably generate the object layout
+      of simple structs and unions; they can be allocated via
+      ff:allocate-fobject, and their member variables accessed
+      directly using the various ff:fslot-value-* functions. However,
+      the layout of C++ classes is more complicated. Different
+      compilers adjust class layout based on inheritance patterns, and
+      the presence of virtual member functions. The size of member
+      function pointers vary across compilers as well. As a result, it
+      is recommended that users of any generated interface not attempt
+      to access C++ instances via the foreign type system, but instead
+      use the more robust wrapper functions. 
+    </p>
+
+<H3><a name="Allegrocl_nn25"></a>16.3.7 Templates</H3>
+
+
+    
+<H4><a name="Allegrocl_nn26"></a>16.3.7.1 Generating wrapper code for templates</H4>
+
+
+	<p>
+	SWIG provides support for dealing with templates, but by
+	default, it will not generate any member variable or function
+	wrappers for templated classes. In order to create these
+	wrappers, you need to explicitly tell SWIG to instantiate
+	them. This is done via the 
+	<a href="SWIGPlus.html#SWIGPlus_nn30"><tt>%template</tt></a>
+	directive.
+	</p>
+
+<H4><a name="Allegrocl_nn27"></a>16.3.7.2 Implicit Template instantiation</H4>
+
+
+	<p>
+	While no wrapper code is generated for accessing member
+	variables, or calling member functions, type code is generated
+	to include these templated classes in the foreign-type and CLOS
+	class schema.
+	</p>
+
+<H3><a name="Allegrocl_nn28"></a>16.3.8 Typedef, Templates, and Synonym Types</H3>
+
+
+    <p>
+      In C/C++ it is possible, via typedef, to have many names refer to
+      the same <tt>type</tt>. In general, this is not a problem, though
+      it can lead to confusion.  Assume the below C++ header file:
+    </p>
+
+    <div class="code">synonyms.h
+    <pre>
+class A { 
+   int x;
+   int y;
+};
+
+typedef A Foo;
+
+A *xxx(int i);         /* sets A-&gt;x = A-&gt;y = i */
+Foo *yyy(int i);       /* sets Foo-&gt;x = Foo-&gt;y = i */
+
+int zzz(A *inst = 0);  /* return inst-&gt;x + inst-&gt;y */
+    </pre>
+    </div>
+
+    <p>
+      The function <tt>zzz</tt> is an overloaded functions; the
+      foreign function call to it will be wrapped in a
+      generic-function whose argument will be checked against a type
+      of <tt>A</tt>. Assuming a simple implementation, a call
+      to <tt>xxx(1)</tt> will return a pointer to an A object, which
+      will be wrapped in a CLOS instance of class <tt>A</tt>, and a
+      call to <tt>yyy(1)</tt> will result in a CLOS instance of
+      type <tt>Foo</tt> being returned.  Without establishing a clear
+      type relationship between <tt>Foo</tt> and <tt>A</tt>, an
+      attempt to call <tt>zzz(yyy(1))</tt> will result in an error.
+    </p>
+
+    <p>
+      We resolve this issue, by noting synonym relationships between
+      types while generating the interface. A Primary type is selected
+      (more on this below) from the candidate list of synonyms. For
+      all other synonyms, intead of generating a distinct CLOS class
+      definition, we generate a form that expands to:
+    </p>
+      <div class="targetlang">
+	<tt>(setf (find-class &lt;synonym&gt;) &lt;primary&gt;)</tt>
+      </div>
+    <p>
+      The result is that all references to synonym types in foreign
+      code, are wrapped in the same CLOS wrapper, and, in particular,
+      method specialization in wrapping generic functions works as 
+      expected.
+    </p>
+
+    <p>
+      Given the above header file, synonym.h, a Lisp session would
+      appear as follows:
+    </p>
+    <div class="targetlang">
+    <pre>
+CL-USER&gt; (load "synonym.dll")
+; Foreign loading synonym.dll.
+t
+CL-USER&gt; (load "synonym.cl")
+; Loading c:\mikel\src\swig\test\synonym.cl
+t
+CL-USER&gt; 
+synonym&gt; (setf a (xxx 3))
+#&lt;A nil #x3261a0 @ #x207299da&gt;
+synonym&gt; (setf foo (yyy 10))
+#&lt;A nil #x3291d0 @ #x2072e982&gt;
+synonym&gt; (zzz a)
+6
+synonym&gt; (zzz foo)
+20
+synonym&gt; 
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn29"></a>16.3.8.1 Choosing a primary type</H4>
+
+
+    <p>
+      The choice of a primary type is selected by the following
+      criteria from a set of synonym types.
+    </p>
+      <ul>
+	<li>
+	  If a synonym type has a class definition, it is the primary type.
+	</li>
+	<li>
+	  If a synonym type is a class template and has been explicitly
+	  instantiated via <tt>%template</tt>, it is the primary type.
+	</li>
+	<li>
+	  For all other sets of synonymous types, the synonym which is
+	  parsed first becomes the primary type.
+	</li>
+      </ul>
+
+<H3><a name="Allegrocl_nn30"></a>16.3.9 Function overloading/Parameter defaulting</H3>
+
+
+    <p>
+      For each possible argument combination, a distinct wrapper
+      function is created in the .cxx file. On the Lisp side, a
+      generic functions is defined for each possible arity the
+      overloaded/defaulted call may have. Each distinct wrapper is
+      then called from within a defmethod on the appropriate generic
+      function. These are further wrapped inside a dispatch function
+      that checks the number of arguments it is called with and passes
+      them via apply to the appropriate generic-function. This allows
+      for a single entry point to overloaded functions on the lisp
+      side.
+    </p>
+
+    <p>Example:
+    </p>
+    <div class="code">overload.h:
+    <pre>
+
+class A {
+ public:
+  int x;
+  int y;
+};
+
+float xxx(int i, int x = 0);   /* return i * x */
+float xxx(A *inst, int x);     /* return x + A-&gt;x + A-&gt;y */
+    </pre>
+    </div>
+
+    <p>Creates the following three wrappers, for each of the possible argument
+      combinations
+    </p>
+    <div class="code">overload_wrap.cxx
+    <pre>
+EXPORT void ACL___delete_A__SWIG_0 (A *larg1) {
+    A *arg1 = (A *) 0 ;
+    
+    arg1 = larg1;
+    try {
+        delete arg1;
+        
+    } catch (...) {
+        
+    }
+}
+
+
+EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
+    float lresult = (float)0 ;
+    int arg1 ;
+    int arg2 ;
+    float result;
+    
+    arg1 = larg1;
+    arg2 = larg2;
+    try {
+        result = (float)xxx(arg1,arg2);
+        
+        lresult = result;
+        return lresult;
+    } catch (...) {
+        return (float)0;
+    }
+}
+
+
+EXPORT float ACL___xxx__SWIG_1 (int larg1) {
+    float lresult = (float)0 ;
+    int arg1 ;
+    float result;
+    
+    arg1 = larg1;
+    try {
+        result = (float)xxx(arg1);
+        
+        lresult = result;
+        return lresult;
+    } catch (...) {
+        return (float)0;
+    }
+}
+
+
+EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
+    float lresult = (float)0 ;
+    A *arg1 = (A *) 0 ;
+    int arg2 ;
+    float result;
+    
+    arg1 = larg1;
+    arg2 = larg2;
+    try {
+        result = (float)xxx(arg1,arg2);
+        
+        lresult = result;
+        return lresult;
+    } catch (...) {
+        return (float)0;
+    }
+}
+    </pre>
+    </div>
+
+    <p>
+      And the following foreign-function-call and method definitions on the
+      lisp side:
+    </p>
+    <div class="targetlang">overload.cl
+    <pre>
+(swig-defmethod ("xxx" "ACL___xxx__SWIG_0" :type :function :arity 2)
+  ((PARM0_i cl:integer :int )
+   (PARM1_x cl:integer :int ))
+  (:returning (:float )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_i))
+  (let ((SWIG_arg1 PARM1_x))
+  (swig-ff-call SWIG_arg0 SWIG_arg1))))
+
+(swig-defmethod ("xxx" "ACL___xxx__SWIG_1" :type :function :arity 1)
+  ((PARM0_i cl:integer :int ))
+  (:returning (:float )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_i))
+  (swig-ff-call SWIG_arg0)))
+
+(swig-defmethod ("xxx" "ACL___xxx__SWIG_2" :type :function :arity 2)
+  ((PARM0_inst #.(swig-insert-id "A" () :type :class) (* #.(swig-insert-id "A" ())) )
+   (PARM1_x cl:integer :int ))
+  (:returning (:float )
+   :strings-convert t)
+  (let ((SWIG_arg0 PARM0_inst))
+  (let ((SWIG_arg1 PARM1_x))
+  (swig-ff-call SWIG_arg0 SWIG_arg1))))
+
+(swig-dispatcher ("xxx" :type :function :arities (1 2)))
+    </pre>
+    </div>
+
+    <p>And their usage in a sample lisp session:
+    </p>
+    <div class="targetlang">
+    <pre>
+overload&gt; (setf a (new_A))
+#&lt;A nil #x329268 @ #x206cf612&gt;
+overload&gt; (setf (A_x a) 10)
+10
+overload&gt; (setf (A_y a) 20)
+20
+overload&gt; (xxx 1)
+0.0
+overload&gt; (xxx 3 10)
+30.0
+overload&gt; (xxx a 1)
+31.0
+overload&gt; (xxx a 2)
+32.0
+overload&gt; 
+    </pre>
+    </div>
+
+<H3><a name="Allegrocl_nn31"></a>16.3.10 Operator wrapping and Operator overloading</H3>
+
+
+    <p>
+      Wrappers to defined C++ Operators are automatically renamed, using
+      <tt>%rename</tt>, to the following defaults:
+    </p>
+    <div class="code">
+    <pre>
+/* name conversion for overloaded operators. */
+#ifdef __cplusplus
+%rename(__add__)	     *::operator+;
+%rename(__pos__)	     *::operator+();
+%rename(__pos__)	     *::operator+() const;
+
+%rename(__sub__)	     *::operator-;
+%rename(__neg__)	     *::operator-() const;
+%rename(__neg__)	     *::operator-();
+
+%rename(__mul__)	     *::operator*;
+%rename(__deref__)	     *::operator*();
+%rename(__deref__)	     *::operator*() const;
+
+%rename(__div__)	     *::operator/;
+%rename(__mod__)	     *::operator%;
+%rename(__logxor__)	     *::operator^;
+%rename(__logand__)	     *::operator&amp;;
+%rename(__logior__)	     *::operator|;
+%rename(__lognot__)	     *::operator~();
+%rename(__lognot__)	     *::operator~() const;
+
+%rename(__not__)	     *::operator!();
+%rename(__not__)	     *::operator!() const;
+
+%rename(__assign__)	     *::operator=;
+
+%rename(__add_assign__)      *::operator+=;
+%rename(__sub_assign__)	     *::operator-=;
+%rename(__mul_assign__)	     *::operator*=;
+%rename(__div_assign__)	     *::operator/=;
+%rename(__mod_assign__)	     *::operator%=;
+%rename(__logxor_assign__)   *::operator^=;
+%rename(__logand_assign__)   *::operator&amp;=;
+%rename(__logior_assign__)   *::operator|=;
+
+%rename(__lshift__)	     *::operator&lt;&lt;;
+%rename(__lshift_assign__)   *::operator&lt;&lt;=;
+%rename(__rshift__)	     *::operator&gt;&gt;;
+%rename(__rshift_assign__)   *::operator&gt;&gt;=;
+
+%rename(__eq__)		     *::operator==;
+%rename(__ne__)		     *::operator!=;
+%rename(__lt__)		     *::operator&lt;;
+%rename(__gt__)		     *::operator&gt;;
+%rename(__lte__)	     *::operator&lt;=;
+%rename(__gte__)	     *::operator&gt;=;
+
+%rename(__and__)	     *::operator&amp;&amp;;
+%rename(__or__)		     *::operator||;
+
+%rename(__preincr__)	     *::operator++();
+%rename(__postincr__)	     *::operator++(int);
+%rename(__predecr__)	     *::operator--();
+%rename(__postdecr__)	     *::operator--(int);
+
+%rename(__comma__)	     *::operator,();
+%rename(__comma__)	     *::operator,() const;
+
+%rename(__member_ref__)      *::operator-&gt;;
+%rename(__member_func_ref__) *::operator-&gt;*;
+
+%rename(__funcall__)	     *::operator();
+%rename(__aref__)	     *::operator[];
+    </pre>
+    </div>
+
+    <p>
+      Name mangling occurs on all such renamed identifiers, so that wrapper name
+      generated by <tt>B::operator=</tt> will be <tt>B___eq__</tt>, i.e.
+      <tt>&lt;class-or-namespace&gt;_</tt> has been added. Users may modify
+      these default names by adding <tt>%rename</tt> directives in their own .i files.
+    </p>
+
+    <p>
+      Operator overloading can be achieved by adding functions based
+      on the mangled names of the function. In the following example,
+      a class B is defined with a Operator== method defined. The
+      swig <tt>%extend</tt> directive is used to add an overload method
+      on Operator==.
+    </p>
+
+    <div class="code">opoverload.h
+    <pre>
+class B {
+ public:
+  int x;
+  int y;
+  bool operator==(B const&amp; other) const;
+};
+    </pre>
+    </div>
+
+    <p>
+    and
+    </p>
+    <div class="code">opoverload.i
+    <pre>
+%module opoverload
+
+%{
+#include &lt;fstream&gt;
+#include "opoverload.h"
+%}
+
+%{
+bool B___eq__(B const *inst, int const x)
+{
+  // insert the function definition into the wrapper code before
+  // the wrapper for it.
+  // ... do stuff ...
+}
+%}
+
+%include "opoverload.h"
+
+%extend B {
+ public:
+  bool __eq__(int const x) const;
+};
+    </pre>
+    </div>
+
+    <p>
+      Either operator can be called via a single call
+      to the dispatch function:
+    </p>
+    <div class="targetlang">
+    <pre>
+opoverload&gt; (B___eq__ x1 x2)
+nil
+opoverload&gt; (B___eq__ x1 3)
+nil
+opoverload&gt; 
+    </pre>
+    </div>
+
+<H3><a name="Allegrocl_nn32"></a>16.3.11 Varargs</H3>
+
+
+    <p>
+      Variable length argument lists are not supported, by default. If
+      such a function is encountered, a warning will generated to
+      stderr. Varargs are supported via the SWIG <tt>%vararg</tt>
+      directive. This directive allows you to specify a (finite)
+      argument list which will be inserted into the wrapper in place
+      of the variable length argument indicator.  As an example,
+      consider the function <tt>printf()</tt>. It's declaration would
+      appear as follows:
+    </p>
+
+    <p>
+      See the following section
+      on <a href="Varargs.html#Varargs">Variable Length arguments</a>
+      provides examples on how <tt>%vararg</tt> can be used, along
+      with other ways such functions can be wrapped.
+    </p>
+
+<H3><a name="Allegrocl_nn33"></a>16.3.12 C++ Exceptions</H3>
+
+
+    <p>
+      Each C++ wrapper includes a handler to catch any exceptions that may
+      be thrown while in foreign code. This helps prevent simple C++ errors
+      from killing the entire lisp process. There is currently no mechanism
+      to have these exceptions forwarded to the lisp condition system, nor
+      has any explicit support of the exception related SWIG typemaps been
+      implemented.
+    </p>
+
+<H3><a name="Allegrocl_nn34"></a>16.3.13 Pass by value, pass by reference</H3>
+
+
+    <p>
+      Allegro CL does not support the passing of non-primitive foreign
+      structures by value. As a result, SWIG must automatically detect
+      and convert function parameters and return values to pointers
+      whenever necessary. This is done via the use of <tt>typemaps</tt>,
+      and should not require any fine tuning by the user, even for
+      newly defined types.
+    </p>
+
+<H2><a name="Allegrocl_nn35"></a>16.4 Typemaps</H2>
+
+
+<p>
+  SWIG Typemaps provide a powerful tool for automatically generating
+  code to handle various menial tasks required of writing an interface
+  to foreign code. The purpose of this section is to describe each of
+  the typemaps used by the Allegro CL module. Please read the chapter
+  on <a href="Typemaps.html#Typemaps">Typemaps</a> for more information.
+</p>
+
+<H3><a name="Allegrocl_nn36"></a>16.4.1 Code Generation in the C++ Wrapper</H3>
+
+
+    
+    <p>
+      Every C++ wrapper generated by SWIG takes the following form:
+    </p>
+
+    <div class="diagram">
+    <pre>
+return-val wrapper-name(parm0, parm1, ..., parmN)
+{
+   return-val lresult;   /* return value from wrapper */
+   &lt;local-declaration&gt;
+   ... results;          /* return value from function call */
+
+   &lt;binding locals to parameters&gt;
+
+   try {
+      result = function-name(local0, local1, ..., localN);
+
+      &lt;convert and bind result to lresult&gt;
+
+      return lresult;
+   catch (...) {
+      return (int)0;
+   }
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn37"></a>16.4.1.1 IN Typemap</H4>
+
+
+    <p>
+      the <tt>in</tt> typemap is used to generate code to convert parameters
+      passed to C++ wrapper functions into the arguments desired for the
+      call being wrapped. That is, it fills in the code for the 
+      <tt>&lt;binding locals to parameters&gt;</tt> section above. We
+      use this map to automatically convert parameters passed by
+      reference to the wrapper function into by-value arguments for
+      the wrapped call, and also to convert boolean values, which are
+      passed as integers from lisp (by default), into the appropriate
+      type for the language of code being wrapped.
+    </p>
+
+    <p>These are the default specifications for the IN typemap. Here,
+      <tt>$input</tt> refers to the parameter code is being generated
+      for, and <tt>$1</tt> is the local variable to which it is
+      being assigned. The default settings of this typemap are as follows:
+    </p>
+      
+    <div class="code">
+    <pre>
+%typemap(in) bool                          "$1 = (bool)$input;";
+%typemap(in) char, unsigned char, signed char,
+             short, signed short, unsigned short,
+             int, signed int, unsigned int,
+             long, signed long, unsigned long,
+             float, double, long double, char *, void *, void,
+             enum SWIGTYPE, SWIGTYPE *,
+             SWIGTYPE[ANY], SWIGTYPE &amp;     "$1 = $input;";
+%typemap(in) SWIGTYPE                      "$1 = *$input;";
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn38"></a>16.4.1.2 OUT Typemap</H4>
+
+
+    <p>
+      The <tt>out</tt> typemap is used to generate code to form the
+      return value of the wrapper from the return value of the wrapped
+      function. This code is placed in the &lt;convert and bind result to lresult&gt;
+      section of the above code diagram. It's default mapping is as follows:
+    </p>
+
+    <div class="code">
+    <pre>
+%typemap(out) bool                          "$result = (int)$1;";
+%typemap(out) char, unsigned char, signed char,
+              short, signed short, unsigned short,
+              int, signed int, unsigned int,
+              long, signed long, unsigned long,
+              float, double, long double, char *, void *, void,
+              enum SWIGTYPE, SWIGTYPE *,
+              SWIGTYPE[ANY], SWIGTYPE &amp;    "$result = $1;";
+%typemap(out) SWIGTYPE                     "$result = new $1_type($1);";
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn39"></a>16.4.1.3 CTYPE Typemap</H4>
+
+
+    <p>
+      This typemap is not used for code generation, but purely for the
+      transformation of types in the parameter list of the wrapper function.
+      It's primary use is to handle by-value to by-reference conversion in the
+      wrappers parameter list. Its default settings are:
+    </p>
+
+    <div class="code">
+    <pre>
+%typemap(ctype) bool                       "int";
+%typemap(ctype) char, unsigned char, signed char,
+                short, signed short, unsigned short,
+                int, signed int, unsigned int,
+                long, signed long, unsigned long,
+                float, double, long double, char *, void *, void,
+                enum SWIGTYPE, SWIGTYPE *,
+                SWIGTYPE[ANY], SWIGTYPE &amp;  "$1_ltype";
+%typemap(ctype) SWIGTYPE                   "$&amp;1_type";
+    </pre>
+    </div>
+
+    <p>
+      These three typemaps are specifically employed by the the
+      Allegro CL interface generator. SWIG also implements a number of
+      other typemaps that can be used for generating code in the C/C++
+      wrappers. You can read about
+      these <a href="Typemaps.html#Typemaps_nn25">common typemaps</a> here.
+    </p>
+
+<H3><a name="Allegrocl_nn40"></a>16.4.2 Code generation in Lisp wrappers</H3>
+
+
+    <p>
+      A number of custom typemaps have also been added to facilitate
+      the generation of code in the lisp side of the interface. These
+      are described below. The basic code generation structure is
+      applied as a series of nested expressions, one for each
+      parameter, then one for manipulating the return value, and last,
+      the foreign function call itself.
+    </p>
+
+    <p>
+      Note that the typemaps below use fully qualified symbols where
+      necessary. Users writing their own typemaps should do likewise. 
+      See the explanation in the last paragraph of 
+      <a href="#Allegrocl_nn15">16.3.1 Namespaces</a> for details.
+    </p>
+
+<H4><a name="Allegrocl_nn41"></a>16.4.2.1 LIN Typemap</H4>
+
+
+    <p>
+      The LIN typemap allows for the manipulating the lisp objects
+      passed as arguments to the wrapping defun before passing them to
+      the foreign function call. For example, when passing lisp
+      strings to foreign code, it is often necessary to copy the
+      string into a foreign structure of type (:char *) of appropriate
+      size, and pass this copy to the foreign call. Using the LIN
+      typemap, one could arrange for the stack-allocation of a foreign
+      char array, copy your string into it, and not have to worry
+      about freeing the copy after the function returns. 
+    </p>
+
+    <p>The LIN typemap accepts the following <tt>$variable</tt> references.
+    </p>
+      <ul>
+	<li><tt>$in</tt> - expands to the name of the parameter being
+	  applied to this typemap
+	</li>
+	<li><tt>$out</tt> - expands to the name of the local variable
+	  assigned to this typemap
+	</li>
+	<li><tt>$in_fftype</tt> - the foreign function type of the C type.</li>
+	<li><tt>$*in_fftype</tt> - the foreign function type of the C type
+	  with one pointer removed. If there is no pointer, then $*in_fftype
+	  is the same as $in_fftype.
+	</li>
+	<li><tt>$body</tt> - very important. Instructs SWIG where
+	  subsequent code generation steps should be inserted into the
+	  current typemap.  Leaving out a <tt>$body</tt> reference
+	  will result in lisp wrappers that do very little by way of
+	  calling into foreign code. Not recommended.
+	</li>
+      </ul>
+      
+    <div class="code">
+    <pre>
+%typemap(lin)	SWIGTYPE 	"(cl:let (($out $in))\n  $body)";
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn42"></a>16.4.2.2 LOUT Typemap</H4>
+
+
+    <p>
+      The LOUT typemap is the means by which we effect the wrapping of
+      foreign pointers in CLOS instances. It is applied after all LIN
+      typemaps, and immediately before the actual foreign-call.
+    </p>
+
+    <p>The LOUT typemap uses the following $variable
+    </p>
+      <ul>
+	<li><tt>$lclass</tt> - Expands to the CLOS class that
+	  represents foreign-objects of the return type matching this
+	  typemap.
+	</li>
+	<li><tt>$body</tt> - Same as for the LIN map. Place this
+	  variable where you want the foreign-function call to occur.
+	</li>
+	<li><tt>$ldestructor</tt> - Expands to the symbol naming the destructor for this
+	  class ($lclass) of object. Allows you to insert finalization or automatic garbage
+	  collection into the wrapper code (see default mappings below).
+	</li>
+      </ul>
+
+    <div class="code">
+    <pre>
+%typemap(lout) bool, char, unsigned char, signed char,
+               short, signed short, unsigned short,
+               int, signed int, unsigned int,
+               long, signed long, unsigned long,
+               float, double, long double, char *, void *, void,
+               enum SWIGTYPE    "$body";
+%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *,
+               SWIGTYPE &amp;       "(cl:make-instance '$lclass :foreign-address $body)";
+%typemap(lout) SWIGTYPE    "(cl:let* ((address $body)\n
+                            (ACL_result (cl:make-instance '$lclass :foreign-address address)))\n
+                            (cl:unless (cl::zerop address)\n
+                            (excl:schedule-finalization ACL_result #'$ldestructor))\n
+                             ACL_result)";
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn43"></a>16.4.2.3 FFITYPE Typemap</H4>
+
+
+    
+    <p>
+      The FFITYPE typemap works as a helper for a body of code that
+      converts C/C++ type specifications into Allegro CL foreign-type
+      specifications. These foreign-type specifications appear in
+      ff:def-foreing-type declarations, and in the argument list and
+      return values of ff:def-foreign-calls. You would modify this
+      typemap if you want to change how the FFI passes through
+      arguments of a given type. For example, if you know that a
+      particular compiler represents booleans as a single byte, you
+      might add an entry for:
+    </p>
+
+    <div class="code">
+    <pre>
+%typemap(ffitype) bool ":unsigned-char";
+    </pre>
+    </div>
+
+    <p>
+      Note that this typemap is pure type transformation, and is not
+      used in any code generations step the way the LIN and LOUT
+      typemaps are. The default mappings for this typemap are:
+    </p>
+
+    <div class="code">
+    <pre>
+%typemap(ffitype) bool ":int";
+%typemap(ffitype) char ":char";
+%typemap(ffitype) unsigned char ":unsigned-char";
+%typemap(ffitype) signed char ":char";
+%typemap(ffitype) short, signed short ":short";
+%typemap(ffitype) unsigned short ":unsigned-short";
+%typemap(ffitype) int, signed int ":int";
+%typemap(ffitype) unsigned int ":unsigned-int";
+%typemap(ffitype) long, signed long ":long";
+%typemap(ffitype) unsigned long ":unsigned-long";
+%typemap(ffitype) float ":float";
+%typemap(ffitype) double ":double";
+%typemap(ffitype) char * "(* :char)";
+%typemap(ffitype) void * "(* :void)";
+%typemap(ffitype) void ":void";
+%typemap(ffitype) enum SWIGTYPE ":int";
+%typemap(ffitype) SWIGTYPE &amp; "(* :void)";
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn44"></a>16.4.2.4 LISPTYPE Typemap</H4>
+
+
+    <p>
+      This is another type only transformation map, and is used to
+      provide the lisp-type, which is the optional third argument in
+      argument specifier in a ff:def-foreign-call form. Specifying a
+      lisp-type allows the foreign call to perform type checking on
+      the arguments passed in. The default entries in this typemap are:
+    </p>
+
+    <div class="code">
+    <pre>
+%typemap(lisptype) bool "cl:boolean";
+%typemap(lisptype) char "cl:character";
+%typemap(lisptype) unsigned char "cl:integer";
+%typemap(lisptype) signed char "cl:integer";
+    </pre>
+    </div>
+
+<H4><a name="Allegrocl_nn45"></a>16.4.2.5 LISPCLASS Typemap</H4>
+
+
+    <p>
+      The LISPCLASS typemap is used to generate the method signatures
+      for the generic-functions which wrap overloaded functions and
+      functions with defaulted arguments. The default entries are:
+    </p>
+
+    <div class="code">
+    <pre>
+%typemap(lispclass) bool "t";
+%typemap(lispclass) char "cl:character";
+%typemap(lispclass) unsigned char, signed char,
+                    short, signed short, unsigned short,
+                    int, signed int, unsigned int,
+                    long, signed long, unsigned long,
+                    enum SWIGTYPE       "cl:integer";
+%typemap(lispclass) float "cl:single-float";
+%typemap(lispclass) double "cl:double-float";
+%typemap(lispclass) char * "cl:string";
+    </pre>
+    </div>
+
+<H3><a name="Allegrocl_nn46"></a>16.4.3 Modifying SWIG behavior using typemaps</H3>
+
+
+    <p>
+      The following example shows how we made use of the above
+      typemaps to add support for the wchar_t type. 
+    </p>
+
+    <div class="code">
+    <pre>
+%typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; };
+
+%typemap(in)        wchar_t "$1 = $input;";
+%typemap(lin)       wchar_t "(cl:let (($out (cl:char-code $in)))\n  $body)";
+%typemap(lin)       wchar_t* "(excl:with-native-string
+                                         ($out $in
+                                          :external-format #+little-endian :fat-le 
+                                                           #-little-endian :fat)\n
+                                 $body)"
+
+%typemap(out)       wchar_t "$result = $1;";
+%typemap(lout)      wchar_t "(cl:code-char $body)";
+%typemap(lout)      wchar_t* "(excl:native-to-string $body
+                                          :external-format #+little-endian :fat-le
+                                                           #-little-endian :fat)";
+
+%typemap(ffitype)   wchar_t ":unsigned-short";
+%typemap(lisptype)  wchar_t "";
+%typemap(ctype)     wchar_t "wchar_t";
+%typemap(lispclass) wchar_t "cl:character";
+%typemap(lispclass) wchar_t* "cl:string";
+    </pre>
+    </div>
+
+<H2><a name="Allegrocl_nn47"></a>16.5 Identifier Converter functions</H2>
+
+
+<H3><a name="Allegrocl_nn48"></a>16.5.1 Creating symbols in the lisp environment</H3>
+
+
+<p>
+  Various symbols must be generated in the lisp environment to which
+  class definitions, functions, constants, variables, etc. must be
+  bound. Rather than force a particular convention for naming these
+  symbols, an identifier (to symbol) conversion function is used. A
+  user-defined identifier-converter can then implement any symbol
+  naming, case-modifying, scheme desired.
+</p>
+
+<p>
+  In generated SWIG code, whenever some interface object must be
+  referenced by its lisp symbol, a macro is inserted that calls the
+  identifier-converter function to generate the appropriate symbol
+  reference. It is therefore expected that the identifier-converter
+  function reliably return the same (eq) symbol given the same set
+  of arguments.
+</p>
+
+<H3><a name="Allegrocl_nn49"></a>16.5.2 Existing identifier-converter functions</H3>
+
+
+  <p>Two basic identifier routines have been defined.
+<H4><a name="Allegrocl_nn50"></a>16.5.2.1 identifier-convert-null</H4>
+
+
+    <p>
+      No modification of the identifier string is performed. Based on
+      other arguments, the identifier may be concatenated with other
+      strings, from which a symbol will be created.
+    </p>
+
+<H4><a name="Allegrocl_nn51"></a>16.5.2.2 identifier-convert-lispify</H4>
+
+
+    <p>
+      All underscores in the identifier string are converted to
+      hyphens. Otherwise, identifier-convert-lispify performs the
+      same symbol transformations.
+    </p>
+
+<H4><a name="Allegrocl_nn52"></a>16.5.2.3 Default identifier to symbol conversions</H4>
+
+
+    <p>
+      Check the definitions of the above two default
+      identifier-converters in <tt>Lib/allegrocl/allegrocl.swg</tt> for
+      default naming conventions.
+    </p>
+
+<H3><a name="Allegrocl_nn53"></a>16.5.3 Defining your own identifier-converter</H3>
+
+
+<p>
+  A user-defined identifier-converter function should conform to the following
+  specification:
+</p>
+
+<div class="targetlang">
+<pre>
+(defun identifier-convert-fn (id &amp;key type class arity) ...body...)
+result ==&gt; symbol or (setf symbol)
+</pre>
+</div>
+
+<p>The <tt>ID</tt> argument is a string representing an identifier in the
+foreign environment.
+</p>
+
+<p>
+The :type keyword argument provides more information on the type of
+identifier. It's value is a symbol. This allows the
+identifier-converter to apply different heuristics when mapping
+different types of identifiers to symbols. SWIG will generate calls
+to your identifier-converter using the following types.
+</p>
+
+<ul>
+  <li>:class - names a CLOS class.</li>
+  <li>:constant - names a defconstant</li>
+  <li>:constructor - names a function for creating a foreign object</li>
+  <li>:destructor - names a function for freeing a foreign object</li>
+  <li>:function - names a CLOS wrapping defmethod or defun.</li>
+  <li>:ff-operator - names a foreign call defined via ff:def-foreign-call</li>
+  <li>:getter - getter function</li>
+  <li>:namespace - names a C++ namespace</li>
+  <li>:setter - names a setter function. May return a (setf symbol) reference</li>
+  <li>:operator - names a C++ operator, such as Operator=, Operator*.</li>
+  <li>:slot - names a slot in a struct/class/union declaration.</li>
+  <li>:type - names a foreign-type defined via ff:def-foreign-type.</li>
+  <li>:variable - names a variable defined via ff:def-foreign-variable.</li>
+</ul>
+
+<p>
+The :class keyword argument is a string naming a foreign
+class. When non-nil, it indicates that the current identifier has
+scope in the specified class.
+</p>
+
+<p>
+The :arity keyword argument only appears in swig:swig-defmethod forms
+generated for overloaded functions. It's value is an integer
+indicating the number of arguments passed to the routine indicated by
+this identifier.
+</p>
+
+<H3><a name="Allegrocl_nn54"></a>16.5.4 Instructing SWIG to use a particular identifier-converter</H3>
+
+
+<p>
+  By default, SWIG will use identifier-converter-null. To specify
+  another convert function, use the <tt>-identifier-converter</tt>
+  command-line argument. The value should be a string naming the
+  function you wish the interface to use instead, when generating
+  symbols. ex:
+</p>
+
+<div class="code">
+<pre>
+% swig -allegrocl -c++ -module mymodule -identifier-converter my-identifier-converter
+</pre>
+</div>
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Arguments.html b/trunk/Doc/Manual/Arguments.html
new file mode 100644
index 0000000..af87804
--- /dev/null
+++ b/trunk/Doc/Manual/Arguments.html
@@ -0,0 +1,498 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Argument Handling</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Arguments"></a>9 Argument Handling</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Arguments_nn2">The typemaps.i library</a>
+<ul>
+<li><a href="#Arguments_nn3">Introduction</a>
+<li><a href="#Arguments_nn4">Input parameters</a>
+<li><a href="#Arguments_nn5">Output parameters</a>
+<li><a href="#Arguments_nn6">Input/Output parameters</a>
+<li><a href="#Arguments_nn7">Using different names</a>
+</ul>
+<li><a href="#Arguments_nn8">Applying constraints to input values</a>
+<ul>
+<li><a href="#Arguments_nn9">Simple constraint example</a>
+<li><a href="#Arguments_nn10">Constraint methods</a>
+<li><a href="#Arguments_nn11">Applying constraints to new datatypes</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<b>Disclaimer: This chapter is under construction.</b>
+
+<p>
+In Chapter 3, SWIG's treatment of basic datatypes and pointers was
+described.  In particular, primitive types such as <tt>int</tt> and
+<tt>double</tt> are mapped to corresponding types in the target
+language.  For everything else, pointers are used to refer to
+structures, classes, arrays, and other user-defined datatypes.
+However, in certain applications it is desirable to change SWIG's
+handling of a specific datatype. For example, you might want to
+return multiple values through the arguments of a function.  This chapter
+describes some of the techniques for doing this.
+</p>
+
+<H2><a name="Arguments_nn2"></a>9.1 The typemaps.i library</H2>
+
+
+<p>
+This section describes the <tt>typemaps.i</tt> library file--commonly used to
+change certain properties of argument conversion.
+</p>
+
+<H3><a name="Arguments_nn3"></a>9.1.1 Introduction</H3>
+
+
+<p>
+Suppose you had a C function like this:
+</p>
+
+<div class="code"><pre>
+void add(double a, double b, double *result) {
+	*result = a + b;
+}
+</pre></div>
+
+<p>
+From reading the source code, it is clear that the function is storing
+a value in the <tt>double *result</tt> parameter.   However, since SWIG
+does not examine function bodies, it has no way to know that this is
+the underlying behavior.
+</p>
+
+<p>
+One way to deal with this is to use the 
+<tt>typemaps.i</tt> library file and write interface code like this:
+</p>
+
+<div class="code"><pre>
+// Simple example using typemaps
+%module example
+%include "typemaps.i"
+
+%apply double *OUTPUT { double *result };
+%inlne %{
+extern void add(double a, double b, double *result);
+%}
+</pre></div>
+
+<p>
+The <tt>%apply</tt> directive tells SWIG that you are going to apply
+a special type handling rule to a type. The "<tt>double *OUTPUT</tt>" specification is the
+name of a rule that defines how to return an output value from an argument of type
+<tt>double *</tt>. This rule gets applied to all of the datatypes
+listed in curly braces-- in this case "<tt>double *result</tt>".</p>
+
+<p>
+When the resulting module is created, you can now use the function
+like this (shown for Python):
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; a = add(3,4)
+&gt;&gt;&gt; print a
+7
+&gt;&gt;&gt;
+</pre></div>
+
+<p>
+In this case, you can see how the output value normally returned in
+the third argument has magically been transformed into a function
+return value.  Clearly this makes the function much easier to use
+since it is no longer necessary to manufacture a special <tt>double
+*</tt> object and pass it to the function somehow.
+</p>
+
+<p>
+Once a typemap has been applied to a type, it stays in effect for all future occurrences
+of the type and name.  For example, you could write the following:
+</p>
+
+<div class="code"><pre>
+%module example
+%include "typemaps.i"
+
+%apply double *OUTPUT { double *result };
+
+%inline %{
+extern void add(double a, double b, double *result);
+extern void sub(double a, double b, double *result);
+extern void mul(double a, double b, double *result);
+extern void div(double a, double b, double *result);
+%}
+...
+</pre></div>
+
+<p>
+In this case, the <tt>double *OUTPUT</tt> rule is applied to all of the functions that follow.
+</p>
+
+<p>
+Typemap transformations can even be extended to multiple return values.
+For example, consider this code:
+</p>
+
+<div class="code">
+<pre>
+%include "typemaps.i"
+%apply int *OUTPUT { int *width, int *height };
+
+// Returns a pair (width,height)
+void getwinsize(int winid, int *width, int *height);
+</pre>
+</div>
+
+<p>
+In this case, the function returns multiple values, allowing it to be used like this:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; w,h = genwinsize(wid)
+&gt;&gt;&gt; print w
+400
+&gt;&gt;&gt; print h
+300
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+It should also be noted that although the <tt>%apply</tt> directive is
+used to associate typemap rules to datatypes, you can also use the
+rule names directly in arguments.  For example, you could write this:
+</p>
+
+<div class="code"><pre>
+// Simple example using typemaps
+%module example
+%include "typemaps.i"
+
+%{
+extern void add(double a, double b, double *OUTPUT);
+%}
+extern void add(double a, double b, double *OUTPUT);
+</pre></div>
+
+<p>
+Typemaps stay in effect until they are explicitly deleted or redefined to something
+else.   To clear a typemap, the <tt>%clear</tt> directive should be used.  For example:
+</p>
+
+<div class="code">
+<pre>
+%clear double *result;      // Remove all typemaps for double *result
+</pre>
+</div>
+
+<H3><a name="Arguments_nn4"></a>9.1.2 Input parameters</H3>
+
+
+<p>
+The following typemaps instruct SWIG that a pointer really only holds a single
+input value:
+</p>
+
+<div class="code"><pre>
+int *INPUT		
+short *INPUT
+long *INPUT
+unsigned int *INPUT
+unsigned short *INPUT
+unsigned long *INPUT
+double *INPUT
+float *INPUT
+</pre></div>
+
+<p>
+When used, it allows values to be passed instead of pointers.  For example, consider this
+function:
+</p>
+
+<div class="code"><pre>
+double add(double *a, double *b) {
+	return *a+*b;
+}
+</pre></div>
+
+<p>
+Now, consider this SWIG interface:
+</p>
+
+<div class="code"><pre>
+%module example
+%include "typemaps.i"
+...
+%{
+extern double add(double *, double *);
+%}
+extern double add(double *INPUT, double *INPUT);
+
+</pre></div>
+
+<p>
+When the function is used in the scripting language interpreter, it will work like this:
+</p>
+
+<div class="targetlang"><pre>
+result = add(3,4)
+</pre></div>
+
+<H3><a name="Arguments_nn5"></a>9.1.3 Output parameters</H3>
+
+
+<p>
+The following typemap rules tell SWIG that pointer is the output value of a
+function. When used, you do not need to supply the argument when
+calling the function. Instead, one or more output values are returned. 
+</p>
+
+<div class="code"><pre>
+int *OUTPUT
+short *OUTPUT
+long *OUTPUT
+unsigned int *OUTPUT
+unsigned short *OUTPUT
+unsigned long *OUTPUT
+double *OUTPUT
+float *OUTPUT
+
+</pre></div>
+<p>
+These methods can be used as shown in an earlier example. For example, if you have this C function :</p>
+
+<div class="code"><pre>
+void add(double a, double b, double *c) {
+	*c = a+b;
+}
+</pre></div>
+
+<p>
+A SWIG interface file might look like this :</p>
+
+<div class="code"><pre>
+%module example
+%include "typemaps.i"
+...
+%inline %{
+extern void add(double a, double b, double *OUTPUT);
+%}
+
+</pre></div>
+
+<p>
+In this case, only a single output value is returned, but this is not
+a restriction.  An arbitrary number of output values can be returned by applying
+the output rules to more than one argument (as shown previously).
+</p>
+
+<p>
+If the function also returns a value, it is returned along with the argument. For example,
+if you had this:
+</p>
+
+<div class="code"><pre>
+extern int foo(double a, double b, double *OUTPUT);
+</pre></div>
+
+<p>
+The function will return two values like this:
+</p>
+
+<div class="targetlang">
+<pre>
+iresult, dresult = foo(3.5, 2)
+</pre>
+</div>
+
+<H3><a name="Arguments_nn6"></a>9.1.4 Input/Output parameters</H3>
+
+
+<p>
+When a pointer serves as both an input and output value you can use
+the following typemaps :</p>
+
+<div class="code"><pre>
+int *INOUT
+short *INOUT
+long *INOUT
+unsigned int *INOUT
+unsigned short *INOUT
+unsigned long *INOUT
+double *INOUT
+float *INOUT
+
+</pre></div>
+
+<p>
+A C function that uses this might be something like this:</p>
+
+<div class="code"><pre>
+void negate(double *x) {
+	*x = -(*x);
+}
+
+</pre></div>
+
+<p>
+To make x function as both and input and output value, declare the
+function like this in an interface file :</p>
+
+<div class="code"><pre>
+%module example
+%include typemaps.i
+...
+%{
+extern void negate(double *);
+%}
+extern void negate(double *INOUT);
+
+</pre></div>
+
+<p>
+Now within a script, you can simply call the function normally :</p>
+
+<div class="targetlang"><pre>
+a = negate(3);         # a = -3 after calling this
+</pre></div>
+
+<p>
+One subtle point of the <tt>INOUT</tt> rule is that many scripting languages
+enforce mutability constraints on primitive objects (meaning that simple objects
+like integers and strings aren't supposed to change).   Because of this, you can't
+just modify the object's value in place as the underlying C function does in this example.
+Therefore, the <tt>INOUT</tt> rule returns the modified value as a new object
+rather than directly overwriting the value of the original input object.
+</p>
+
+<p>
+<b>Compatibility note :</b> The <tt>INOUT</tt> rule used to be known as <tt>BOTH</tt> in earlier versions of
+SWIG.  Backwards compatibility is preserved, but deprecated.
+</p>
+
+<H3><a name="Arguments_nn7"></a>9.1.5 Using different names</H3>
+
+
+<p>
+As previously shown, the <tt>%apply</tt> directive can be used to apply the <tt>INPUT</tt>, <tt>OUTPUT</tt>, and
+<tt>INOUT</tt> typemaps to different argument names.  For example:
+</p>
+
+<div class="code"><pre>
+// Make double *result an output value
+%apply double *OUTPUT { double *result };
+
+// Make Int32 *in an input value
+%apply int *INPUT { Int32 *in };
+
+// Make long *x inout
+%apply long *INOUT {long *x};
+
+</pre></div>
+
+<p>
+To clear a rule, the <tt>%clear</tt> directive is used:
+</p>
+
+<div class="code"><pre>
+%clear double *result;
+%clear Int32 *in, long *x;
+</pre></div>
+
+<p>
+Typemap declarations are lexically scoped so a typemap takes effect from the point of definition to the end of the
+file or a matching <tt>%clear</tt> declaration.
+</p>
+
+<H2><a name="Arguments_nn8"></a>9.2 Applying constraints to input values</H2>
+
+
+<p>
+In addition to changing the handling of various input values, it is
+also possible to use typemaps to apply constraints. For example, maybe you want to
+insure that a value is positive, or that a pointer is non-NULL. This
+can be accomplished including the <tt>constraints.i</tt> library file.
+</p>
+
+<H3><a name="Arguments_nn9"></a>9.2.1 Simple constraint example</H3>
+
+
+<p>
+The constraints library is best illustrated by the following interface
+file :</p>
+
+<div class="code"><pre>
+// Interface file with constraints
+%module example
+%include "constraints.i"
+
+double exp(double x);
+double log(double POSITIVE);         // Allow only positive values
+double sqrt(double NONNEGATIVE);     // Non-negative values only
+double inv(double NONZERO);          // Non-zero values
+void   free(void *NONNULL);          // Non-NULL pointers only
+
+</pre></div>
+
+<p>
+The behavior of this file is exactly as you would expect. If any of
+the arguments violate the constraint condition, a scripting language
+exception will be raised. As a result, it is possible to catch bad
+values, prevent mysterious program crashes and so on.</p>
+
+<H3><a name="Arguments_nn10"></a>9.2.2 Constraint methods</H3>
+
+
+<p>
+The following constraints are currently available</p>
+
+<div class="code"><pre>
+POSITIVE                     Any number &gt; 0 (not zero)
+NEGATIVE                     Any number &lt; 0 (not zero)
+NONNEGATIVE                  Any number &gt;= 0
+NONPOSITIVE                  Any number &lt;= 0
+NONZERO                      Nonzero number
+NONNULL                      Non-NULL pointer (pointers only).
+
+</pre></div>
+
+<H3><a name="Arguments_nn11"></a>9.2.3 Applying constraints to new datatypes</H3>
+
+
+<p>
+The constraints library only supports the primitive C datatypes, but it
+is easy to apply it to new datatypes using <tt>%apply</tt>. For
+example :</p>
+
+<div class="code"><pre>
+// Apply a constraint to a Real variable
+%apply Number POSITIVE { Real in };
+
+// Apply a constraint to a pointer type
+%apply Pointer NONNULL { Vector * };
+
+</pre></div>
+
+<p>
+The special types of "Number" and "Pointer" can be applied to any
+numeric and pointer variable type respectively. To later remove a
+constraint, the <tt>%clear</tt> directive can be used :</p>
+
+<div class="code"><pre>
+%clear Real in;
+%clear Vector *;
+</pre></div>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/CSharp.html b/trunk/Doc/Manual/CSharp.html
new file mode 100644
index 0000000..97cb754
--- /dev/null
+++ b/trunk/Doc/Manual/CSharp.html
@@ -0,0 +1,2032 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and C#</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+<body bgcolor="#FFFFFF">
+<H1><a name="CSharp"></a>17 SWIG and C#</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#csharp_introduction">Introduction</a>
+<li><a href="#csharp_differences_java">Differences to the Java module</a>
+<li><a href="#csharp_exceptions">C# Exceptions</a>
+<ul>
+<li><a href="#csharp_exception_example_check_typemap">C# exception example using "check" typemap</a>
+<li><a href="#csharp_exception_example_percent_exception">C# exception example using %exception</a>
+<li><a href="#csharp_exception_example_exception_specifications">C# exception example using exception specifications</a>
+<li><a href="#csharp_custom_application_exception">Custom C# ApplicationException example</a>
+</ul>
+<li><a href="#csharp_directors">C# Directors</a>
+<ul>
+<li><a href="#csharp_directors_example">Directors example</a>
+<li><a href="#csharp_directors_implementation">Directors implementation</a>
+<li><a href="#csharp_director_caveats">Director caveats</a>
+</ul>
+<li><a href="#csharp_typemap_examples">C# Typemap examples</a>
+<ul>
+<li><a href="#csharp_memory_management_member_variables">Memory management when returning references to member variables</a>
+<li><a href="#csharp_memory_management_objects">Memory management for objects passed to the C++ layer</a>
+<li><a href="#csharp_date_marshalling">Date marshalling using the csin typemap and associated attributes</a>
+<li><a href="#csharp_date_properties">A date example demonstrating marshalling of C# properties</a>
+<li><a href="#csharp_partial_classes">Turning wrapped classes into partial classes</a>
+<li><a href="#csharp_extending_proxy_class">Extending proxy classes with additional C# code</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<H2><a name="csharp_introduction"></a>17.1 Introduction</H2>
+
+
+<p>
+The purpose of the C# module is to offer an automated way of accessing existing C/C++ code from .NET languages.
+The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interface to access natively compiled C/C++ code.
+The PInvoke interface has been chosen over Microsoft's Managed C++ interface as it is portable to both Microsoft Windows and non-Microsoft platforms.
+PInvoke is part of the ECMA/ISO C# specification.
+It is also better suited for robust production environments due to the Managed C++ flaw called the
+<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vcconMixedDLLLoadingProblem.asp">Mixed DLL Loading Problem</a>.
+Swig C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using
+<a href="http://www.mono-project.com/">Mono</a> and <a href="http://www.dotgnu.org/pnet.html">Portable.NET</a>.
+</p>
+
+<p>
+To get the most out of this chapter an understanding of interop is required.
+The <a href="http://msdn.microsoft.com">Microsoft Developer Network (MSDN)</a> has a good reference guide in a section titled "Interop Marshaling".
+Monodoc, available from the Mono project, has a very useful section titled <a href="http://www.mono-project.com/Interop_with_Native_Libraries">Interop with native libraries</a>.
+</p>
+
+<H2><a name="csharp_differences_java"></a>17.2 Differences to the Java module</H2>
+
+
+<p>
+The C# module is very similar to the Java module, so until some more complete documentation has been written,
+please use the <a href="Java.html#Java">Java documentation</a> as a guide to using SWIG with C#.
+The C# module has the same major SWIG features as the Java module.
+The rest of this section should be read in conjunction with the Java documentation as it lists the main differences.
+
+The most notable differences to Java are the following:
+<ul>
+
+<li>
+When invoking SWIG use the <tt>-csharp</tt> command line option instead of <tt>-java</tt>.
+</li>
+
+<li>
+The <tt>-nopgcpp</tt> command line option does not exist.
+</li>
+
+<li>
+The <tt>-package</tt> command line option does not exist.
+</li>
+
+<li>
+The <tt>-namespace &lt;name&gt;</tt> commandline option will generate all code into the namespace specified by <tt>&lt;name&gt;</tt>.
+C# supports nested namespaces that are not lexically nested, so nested namespaces will of course also work. For example:
+<tt>-namespace com.bloggs.widget</tt>, will generate code into C# namespaces:
+
+<div class="code"><pre>
+namespace com.bloggs.widget {
+  ...
+}
+</pre></div>
+</li>
+
+<li>
+The <tt>-dllimport &lt;name&gt;</tt> commandline option specifies the name of the DLL for the <tt>DllImport</tt> attribute for every PInvoke method. If this commandline option is not given, the <tt>DllImport</tt> DLL name is the same as the module name. This option is useful for when one wants to invoke SWIG multiple times on different modules, yet compile all the resulting code into a single DLL.
+</li>
+
+<li>
+C/C++ variables are wrapped with C# properties and not JavaBean style getters and setters.
+</li>
+
+<li>
+Global constants are generated into the module class. There is no constants interface.
+</li>
+
+<li>
+There is no implementation for type unsafe enums - not deemed necessary.
+</li>
+
+<li>
+The default enum wrapping approach is proper C# enums, not typesafe enums.
+<br>
+Note that %csconst(0) will be ignored when wrapping C/C++ enums with proper C# enums.
+This is because C# enum items must be initialised from a compile time constant.
+If an enum item has an initialiser and the initialiser doesn't compile as C# code,
+then the %csconstvalue directive must be used as %csconst(0) will have no effect.
+If it was used, it would generate an illegal runtime initialisation via a PInvoke call.
+</li>
+
+<li>
+C# doesn't support the notion of throws clauses.
+Therefore there is no 'throws' typemap attribute support for adding exception classes to a throws clause.
+Likewise there is no need for an equivalent to <tt>%javaexception</tt>.
+In fact, throwing C# exceptions works quite differently, see <a href="CSharp.html#csharp_exceptions">C# Exceptions></a> below.
+</li>
+
+<li>
+The majority of the typemaps are in csharp.swg, not java.swg.
+</li>
+
+<li>
+<p>Typemap equivalent names:</p>
+
+<div class="code"><pre>
+jni                         -&gt; ctype
+jtype                       -&gt; imtype
+jstype                      -&gt; cstype
+javain                      -&gt; csin
+javaout                     -&gt; csout
+javadirectorin              -&gt; csdirectorin
+javadirectorout             -&gt; csdirectorout
+javainterfaces              -&gt; csinterfaces and csinterfaces_derived
+javabase                    -&gt; csbase
+javaclassmodifiers          -&gt; csclassmodifiers
+javacode                    -&gt; cscode
+javaimports                 -&gt; csimports
+javabody                    -&gt; csbody
+javafinalize                -&gt; csfinalize
+javadestruct                -&gt; csdestruct
+javadestruct_derived        -&gt; csdestruct_derived
+</pre></div>
+
+</li>
+
+<li>
+<p>Additional typemaps:</p>
+
+<div class="code"><pre>
+csvarin                     C# code property set typemap
+csvarout                    C# code property get typemap
+csattributes                C# attributes for attaching to proxy classes/enums
+</pre></div>
+
+</li>
+
+<li>
+<p>Feature equivalent names:</p>
+<div class="code"><pre>
+%javaconst                  -&gt; %csconst
+%javaconstvalue             -&gt; %csconstvalue
+%javamethodmodifiers        -&gt; %csmethodmodifiers
+</pre></div>
+</li>
+
+<li>
+<p>Pragma equivalent names:</p>
+<div class="code"><pre>
+%pragma(java)               -&gt; %pragma(csharp)
+jniclassbase                -&gt; imclassbase
+jniclassclassmodifiers      -&gt; imclassclassmodifiers
+jniclasscode                -&gt; imclasscode
+jniclassimports             -&gt; imclassimports
+jniclassinterfaces          -&gt; imclassinterfaces
+</pre></div>
+</li>
+
+<li>
+<p>Special variable equivalent names:</p>
+<div class="code"><pre>
+$javaclassname              -&gt; $csclassname
+$&amp;javaclassname             -&gt; $&amp;csclassname
+$*javaclassname             -&gt; $*csclassname
+$javainput                  -&gt; $csinput
+$jnicall                    -&gt; $imcall
+</pre></div>
+</li>
+
+<li>
+<p>
+Unlike the "javain" typemap, the "csin" typemap does not support the 'pgcpp' attribute as the C# module does not have a premature garbage collection prevention parameter. The "csin" typemap supports an additional optional attribute called 'cshin'. It should contain the parameter type and name whenever a <a href="Java.html#java_constructor_helper_function">constructor helper function</a> is generated due to the 'pre' or 'post' attributes. Note that 'pre', 'post' and 'cshin' attributes are not used for marshalling the property set. Please see the <a href="#csharp_date_marshalling">Date marshalling example</a> and <a href="#CSharp.html#csharp_date_properties">Date marshalling of properties example</a> for further understanding.
+</p>
+</li>
+
+<li>
+<p>
+Support for asymmetric type marshalling. The 'ctype', 'imtype' and 'cstype' typemaps support an optional <tt>out</tt> attribute which is used for output types.
+If this typemap attribute is specified, then the type specified in the attribute is used for output types and
+the type specified in the typemap itself is used for the input type.
+If this typemap attribute is not specified, then the type used for both input and output is the type specified in the typemap.
+An example shows that <tt>char *</tt> could be marshalled in different ways, 
+</p>
+
+<div class="code">
+<pre>
+%typemap(imtype, out="IntPtr") char * "string"
+char * function(char *);
+</pre>
+</div>
+
+<p>
+The output type is thus IntPtr and the input type is string. The resulting intermediary C# code is:
+</p>
+
+<div class="code">
+<pre>
+public static extern IntPtr function(string jarg1);
+</pre>
+</div>
+
+</li>
+
+<li>
+<p>
+Support for type attributes.
+The 'imtype' and 'cstype' typemaps can have an optional <tt>inattributes</tt> and <tt>outattributes</tt> typemap attribute.
+There are C# attributes and typemap attributes, don't get confused!!
+The C# attributes specified in these typemap attributes are generated wherever the type is used in the C# wrappers.
+These can be used to specify any C# attribute associated with a C/C++ type, but are more typically used for the C# <tt>MarshalAs</tt> attribute.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(imtype,
+         inattributes="[MarshalAs(UnmanagedType.LPStr)]",
+         outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"
+
+const char * GetMsg() {}
+void SetMsg(const char *msg) {}
+</pre>
+</div>
+
+<p>
+The intermediary class will then have the marshalling as specified by everything in the 'imtype' typemap:
+</p>
+
+<div class="code">
+<pre>
+class examplePINVOKE {
+  ...
+  [DllImport("example", EntryPoint="CSharp_GetMsg")]
+  [return: MarshalAs(UnmanagedType.LPStr)]
+  public static extern String GetMsg();
+
+  [DllImport("example", EntryPoint="CSharp_SetMsg")]
+  public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
+}
+</pre>
+</div>
+
+<p>
+Note that the <tt>DllImport</tt> attribute is always generated, irrespective of any additional attributes specified.
+</p>
+
+<p>
+These attributes are associated with the C/C++ parameter type or return type, which is subtly different to 
+the attribute features and typemaps covered next.
+Note that all these different C# attributes can be combined so that a method has more than one attribute.
+</p>
+</li>
+
+<li>
+<p>
+Support for attaching C# attributes to wrapped methods and variables.
+This is done using the <tt>%csattributes</tt> feature, see <a href="Customization.html#features">%feature directives</a>.
+Note that C# attributes are attached to proxy classes and enums using the <tt>csattributes</tt> typemap.
+For example, imagine we have a custom attribute class, <tt>ThreadSafeAttribute</tt>, for labelling thread safety.
+The following SWIG code shows how to attach this C# attribute to some methods and the class declaration itself:
+</p>
+
+<div class="code">
+<pre>
+%typemap(csattributes) AClass          "[ThreadSafe]"
+%csattributes AClass::AClass(double d) "[ThreadSafe(false)]"
+%csattributes AClass::AMethod()        "[ThreadSafe(true)]"
+
+%inline %{
+class AClass {
+public:
+  AClass(double a) {}
+  void AMethod() {}
+};
+%}
+</pre>
+</div>
+
+<p>
+will generate a C# proxy class:
+</p>
+
+<div class="code">
+<pre>
+[ThreadSafe]
+public class AClass : IDisposable {
+  ...
+  [ThreadSafe(false)]
+  public AClass(double a) ...
+
+  [ThreadSafe(true)]
+  public void AMethod() ...
+}
+</pre>
+</div>
+
+<p>
+If C# attributes need adding to the <tt>set</tt> or <tt>get</tt> part of C# properties, when wrapping C/C++ variables,
+they can be added using the 'csvarin' and 'csvarout' typemaps respectively.
+Note that the type used for the property is specified in the 'cstype' typemap.
+If the 'out' attribute exists in this typemap, then the type used is from the 'out' attribute.
+</p>
+</li>
+
+<li>
+<p>
+The intermediary classname has <tt>PINVOKE</tt> appended after the module name instead of <tt>JNI</tt>, for example <tt>modulenamePINVOKE</tt>.
+</p>
+</li>
+
+<li>
+<p>
+The <tt>%csmethodmodifiers</tt> feature can also be applied to variables as well as methods.
+In addition to the default <tt>public</tt> modifier that SWIG generates when <tt>%csmethodmodifiers</tt> is not
+specified, the feature will also replace the <tt>virtual</tt>/<tt>new</tt>/<tt>override</tt> modifiers that SWIG thinks is appropriate.
+This feature is useful for some obscure cases where SWIG might get the <tt>virtual</tt>/<tt>new</tt>/<tt>override</tt> modifiers incorrect, for example with multiple inheritance.
+</p>
+</li>
+
+<li>
+<a name="csharp_module_directive"></a>
+<p>
+The name of the intermediary class can be changed from its default, that is, the module name with PINVOKE appended after it. 
+The module directive attribute <tt>imclassname</tt> is used to achieve this:
+</p>
+
+<div class="code">
+<pre>
+%module (imclassname="name") modulename
+</pre>
+</div>
+
+<p>
+If <tt>name</tt> is the same as <tt>modulename</tt> then the module class name gets changed
+from <tt>modulename</tt> to <tt>modulenameModule</tt>.
+</p>
+</li>
+
+<li>
+There is no additional 'premature garbage collection prevention parameter' as the marshalling of the <tt>HandleRef</tt> object
+takes care of ensuring a reference to the proxy class is held until the unmanaged call completed.
+</li>
+
+</ul>
+
+<p>
+<b><tt>$dllimport</tt></b><br>
+This is a C# only special variable that can be used in typemaps, pragmas, features etc.
+The special variable will get translated into the value specified by the <tt>-dllimport</tt> commandline option
+if specified, otherwise it is equivalent to the <b>$module</b> special variable.
+</p>
+
+<p>
+<b><tt>$imclassname</tt></b><br>
+This special variable expands to the intermediary class name. For C# this is usually the same as '$modulePINVOKE' ('$moduleJNI' for Java),
+unless the imclassname attribute is specified in the <a href="CSharp.html#csharp_module_directive">%module directive</a>.
+</p>
+
+<p>
+The directory <tt>Examples/csharp</tt> has a number of simple examples. 
+Visual Studio .NET 2003 solution and project files are available for compiling with the Microsoft .NET C# compiler on Windows.
+If your SWIG installation went well on a Unix environment and your C# compiler was detected, you should be able to type <tt>make</tt> in each example directory, 
+then <tt>ilrun runme.exe</tt> (Portable.NET C# compiler) or <tt>mono runme.exe</tt> (Mono C# compiler) to run the examples.
+Windows users can also get the examples working using a
+<a href="http://www.cygwin.com">Cygwin</a> or <a href="http://www.mingw.org">MinGW</a> environment for automatic configuration of the example makefiles.
+Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path. 
+
+<H2><a name="csharp_exceptions"></a>17.3 C# Exceptions</H2>
+
+
+<p>
+It is possible to throw a C# Exception from C/C++ code.
+SWIG already provides the framework for throwing C# exceptions if it is able to detect that a C++ exception could be thrown.
+Automatically detecting that a C++ exception could be thrown is only possible when a C++ exception specification is used,
+see <a href="SWIGPlus.html#SWIGPlus_exception_specifications">Exception specifications</a>. 
+The <a href="Customization.html#exception">Exception handling with %exception</a> section details the <tt>%exception</tt> feature.
+Customised code for handling exceptions with or without a C++ exception specification is possible and the details follow.
+However anyone wishing to do this should be familiar with the contents of the sections referred to above.
+</p>
+
+<p>
+Unfortunately a C# exception cannot simply be thrown from unmanaged code for a variety of reasons.
+Most notably being that throwing a C# exception results in exceptions being thrown across the C PInvoke interface and C does not understand exceptions.
+The design revolves around a C# exception being constructed and stored as a pending exception, to be thrown only when the unmanaged code has completed.
+Implementing this is a tad involved and there are thus some unusual typemap constructs.
+Some practical examples follow and they should be read in conjunction with the rest of this section.
+</p>
+
+<p>
+First some details about the design that must be followed.
+Each typemap or feature that generates <b>unmanaged code</b> supports an attribute called <tt>canthrow</tt>.
+This is simply a flag which when set indicates that the code in the typemap/feature has code which might want to throw a C# exception.
+The code in the typemap/feature can then raise a C# exception by calling one of the C functions,
+<tt>SWIG_CSharpSetPendingException()</tt> or <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>.
+When called, the function makes a callback into the managed world via a delegate.
+The callback creates and stores an exception ready for throwing when the unmanaged code has finished.
+The typemap/feature unmanaged code is then expected to force an immediate return from the unmanaged wrapper function,
+so that the pending managed exception can then be thrown.
+The support code has been carefully designed to be efficient as well as thread-safe.
+However to achieve the goal of efficiency requires some optional code generation in the <b>managed code</b> typemaps.
+Code to check for pending exceptions is generated if and only if the unmanaged code has code to set a pending exception,
+that is if the <tt>canthrow</tt> attribute is set.
+The optional managed code is generated using the <tt>excode</tt> typemap attribute and <tt>$excode</tt> special variable in the relevant managed code typemaps.
+Simply, if any relevant unmanaged code has the <tt>canthrow</tt> attribute set, then any occurrences of <tt>$excode</tt>
+is replaced with the code in the <tt>excode</tt> attribute.
+If the <tt>canthrow</tt> attribute is not set, then any occurrences of <tt>$excode</tt> are replaced with nothing.
+</p>
+
+<p>
+The prototypes for the <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> functions are
+</p>
+
+<div class="code">
+<pre>
+static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
+                                           const char *msg);
+
+static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
+                                                   const char *msg,
+                                                   const char *param_name);
+</pre>
+</div>
+
+<p>
+The first parameter defines which .NET exceptions can be thrown:
+</p>
+
+<div class="code">
+<pre>
+typedef enum {
+  SWIG_CSharpApplicationException,
+  SWIG_CSharpArithmeticException,
+  SWIG_CSharpDivideByZeroException,
+  SWIG_CSharpIndexOutOfRangeException,
+  SWIG_CSharpInvalidCastException,
+  SWIG_CSharpInvalidOperationException,
+  SWIG_CSharpIOException,
+  SWIG_CSharpNullReferenceException,
+  SWIG_CSharpOutOfMemoryException,
+  SWIG_CSharpOverflowException,
+  SWIG_CSharpSystemException
+} SWIG_CSharpExceptionCodes;
+
+typedef enum {
+  SWIG_CSharpArgumentException,
+  SWIG_CSharpArgumentNullException,
+  SWIG_CSharpArgumentOutOfRangeException,
+} SWIG_CSharpExceptionArgumentCodes;
+</pre>
+</div>
+
+<p>
+where, for example, <tt>SWIG_CSharpApplicationException</tt> corresponds to the .NET exception, <tt>ApplicationException</tt>.
+The <tt>msg</tt> and <tt>param_name</tt> parameters contain the C# exception message and parameter name associated with the exception.
+</p>
+
+
+<p>
+The <tt>%exception</tt> feature in C# has the <tt>canthrow</tt> attribute set.
+The <tt>%csnothrowexception</tt> feature is like <tt>%exception</tt>, but it does not have the <tt>canthrow</tt> attribute
+set so should only be used when a C# exception is not created.
+</p>
+
+
+<H3><a name="csharp_exception_example_check_typemap"></a>17.3.1 C# exception example using "check" typemap</H3>
+
+
+<p>
+Lets say we have the following simple C++ method:
+</p>
+
+
+<div class="code">
+<pre>
+void positivesonly(int number);
+</pre>
+</div>
+
+<p>
+and we want to check that the input <tt>number</tt> is always positive and if not throw a C# <tt>ArgumentOutOfRangeException</tt>.
+The "check" typemap is designed for checking input parameters. Below you will see the <tt>canthrow</tt> attribute is set because
+the code contains a call to <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>. The full example follows:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+%typemap(check, canthrow=1) int number %{
+if ($1 &lt; 0) {
+  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
+                                         "only positive numbers accepted", "number");
+  return $null;
+}
+// SWIGEXCODE is a macro used by many other csout typemaps
+%define SWIGEXCODE
+ "\n    if ($modulePINVOKE.SWIGPendingException.Pending)"
+ "\n      throw $modulePINVOKE.SWIGPendingException.Retrieve();"
+%enddef
+%typemap(csout, excode=SWIGEXCODE) void {
+    $imcall;$excode
+  }
+%}
+
+%inline %{
+
+void positivesonly(int number) {
+}
+
+%}
+</pre>
+</div>
+
+<p>
+When the following C# code is executed:
+</p>
+
+<div class="code">
+<pre>
+public class runme {
+    static void Main() {
+      example.positivesonly(-1);
+    }
+}
+</pre>
+</div>
+
+<p>
+The exception is thrown:
+</p>
+
+<div class="code">
+<pre>
+Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
+Parameter name: number
+in &lt;0x00034&gt; example:positivesonly (int)
+in &lt;0x0000c&gt; runme:Main ()
+</pre>
+</div>
+
+<p>
+Now let's analyse the generated code to gain a fuller understanding of the typemaps. The generated unmanaged C++ code is:
+</p>
+
+
+<div class="code">
+<pre>
+SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
+    int arg1 ;
+    
+    arg1 = (int)jarg1; 
+    
+    if (arg1 &lt; 0) {
+        SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
+                                               "only positive numbers accepted", "number");
+        return ;
+    }
+    
+    positivesonly(arg1);
+    
+}
+</pre>
+</div>
+
+<p>
+This largely comes from the "check" typemap. The managed code in the module class is:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static void positivesonly(int number) {
+    examplePINVOKE.positivesonly(number);
+    if (examplePINVOKE.SWIGPendingException.Pending)
+      throw examplePINVOKE.SWIGPendingException.Retrieve();
+  }
+
+}
+</pre>
+</div>
+
+<p>
+This comes largely from the "csout" typemap. 
+</p>
+
+<p>
+The "csout" typemap is the same as the default void "csout" typemap so is not strictly necessary for the example.
+However, it is shown to demonstrate what managed output code typemaps should contain,
+that is, a <tt>$excode</tt> special variable and an <tt>excode</tt> attribute.
+Also note that <tt>$excode</tt> is expanded into the code held in the <tt>excode</tt> attribute.
+The <tt>$imcall</tt> as always expands into <tt>examplePINVOKE.positivesonly(number)</tt>.
+The exception support code in the intermediary class, <tt>examplePINVOKE</tt>, is not shown, but is contained within the inner classes,
+<tt>SWIGPendingException</tt> and <tt>SWIGExceptionHelper</tt> and is always generated.
+These classes can be seen in any of the generated wrappers.
+However, all that is required of a user is as demonstrated in the "csin" typemap above.
+That is, is to check <tt>SWIGPendingException.Pending</tt> and to throw the exception returned by <tt>SWIGPendingException.Retrieve()</tt>.
+</p>
+
+<p>
+If the "check" typemap did not exist, then
+the following module class would instead be generated:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static void positivesonly(int number) {
+    examplePINVOKE.positivesonly(number);
+  }
+
+}
+</pre>
+</div>
+
+<p>
+Here we see the pending exception checking code is omitted.
+In fact, the code above would be generated if the <tt>canthrow</tt> attribute was not in the "check" typemap, such as:
+</p>
+
+<div class="code">
+<pre>
+%typemap(check) int number %{
+if ($1 &lt; 0) {
+  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
+                                         "only positive numbers accepted", "number");
+  return $null;
+}
+%}
+</pre>
+</div>
+
+<p>
+Note that if SWIG detects you have used <tt>SWIG_CSharpSetPendingException()</tt> or <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>
+without setting the <tt>canthrow</tt> attribute you will get a warning message similar to
+</p>
+
+<div class="code">
+<pre>
+example.i:21: Warning(845): Unmanaged code contains a call to a SWIG_CSharpSetPendingException
+method and C# code does not handle pending exceptions via the canthrow attribute.
+</pre>
+</div>
+<p>
+Actually it will issue this warning for any function beginning with <tt>SWIG_CSharpSetPendingException</tt>.
+</P>
+
+<H3><a name="csharp_exception_example_percent_exception"></a>17.3.2 C# exception example using %exception</H3>
+
+
+<p>
+Let's consider a similar, but more common example that throws a C++ exception from within a wrapped function.
+We can use <tt>%exception</tt> as mentioned in <a href="Customization.html#exception">Exception handling with %exception</a>.
+</p>
+
+<div class="code">
+<pre>
+%exception negativesonly(int value) %{
+try {
+  $action
+} catch (std::out_of_range e) {
+  SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
+}
+%}
+
+%inline %{
+#include &lt;stdexcept&gt;
+void negativesonly(int value) {
+  if (value &gt;= 0)
+    throw std::out_of_range("number should be negative");
+}
+%}
+</pre>
+</div>
+
+<p>
+The generated unmanaged code this time catches the C++ exception and converts it into a C# <tt>ApplicationException</tt>.
+</p>
+
+<div class="code">
+<pre>
+SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
+    int arg1 ;
+    
+    arg1 = (int)jarg1; 
+    
+    try {
+        negativesonly(arg1);
+        
+    } catch (std::out_of_range e) {
+        SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
+        return ;
+    }
+    
+}
+</pre>
+</div>
+
+<p>
+The managed code generated does check for the pending exception as mentioned earlier as the C# version of <tt>%exception</tt> has the <tt>canthrow</tt> attribute set by default:
+</p>
+
+<div class="code">
+<pre>
+  public static void negativesonly(int value) {
+    examplePINVOKE.negativesonly(value);
+    if (examplePINVOKE.SWIGPendingException.Pending)
+      throw examplePINVOKE.SWIGPendingException.Retrieve();
+  }
+</pre>
+</div>
+
+<H3><a name="csharp_exception_example_exception_specifications"></a>17.3.3 C# exception example using exception specifications</H3>
+
+
+<p>
+When C++ exception specifications are used, SWIG is able to detect that the method might throw an exception.
+By default SWIG will automatically generate code to catch the exception and convert it into a managed <tt>ApplicationException</tt>,
+as defined by the default "throws" typemaps.
+The following example has a user supplied "throws" typemap which is used whenever an exception specification contains a <tt>std::out_of_range</tt>,
+such as the <tt>evensonly</tt> method below.
+</p>
+
+<div class="code">
+<pre>
+%typemap(throws, canthrow=1) std::out_of_range {
+  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
+  return $null;
+}
+
+%inline %{
+#include &lt;stdexcept&gt;
+void evensonly(int input) throw (std::out_of_range) {
+  if (input%2 != 0)
+    throw std::out_of_range("number is not even");
+}
+%}
+</pre>
+</div>
+
+<p>
+Note that the type for the throws typemap is the type in the exception specification.
+SWIG generates a try catch block with the throws typemap code in the catch handler.
+</p>
+
+<div class="code">
+<pre>
+SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
+    int arg1 ;
+    
+    arg1 = (int)jarg1; 
+    try {
+        evensonly(arg1);
+    }
+    catch(std::out_of_range &amp;_e) {
+      {
+          SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&amp;_e)-&gt;what(), NULL);
+          return ;
+      }
+    }
+    
+}
+</pre>
+</div>
+
+<p>
+Multiple catch handlers are generated should there be more than one exception specifications declared.
+</p>
+
+<H3><a name="csharp_custom_application_exception"></a>17.3.4 Custom C# ApplicationException example</H3>
+
+
+<p>
+This example involves a user defined exception.
+The conventional .NET exception handling approach is to create a custom <tt>ApplicationException</tt> and throw it in your application.
+The goal in this example is to convert the STL <tt>std::out_of_range</tt> exception into one of these custom .NET exceptions.
+</p>
+
+
+<p>
+The default exception handling is quite easy to use as the <tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>
+methods are provided by SWIG.
+However, for a custom C# exception, the boiler plate code that supports these functions needs replicating.
+In essence this consists of some C/C++ code and C# code.
+The C/C++ code can be generated into the wrapper file using the <tt>%insert(runtime)</tt> directive and
+the C# code can be generated into the intermediary class using the <tt>imclasscode</tt> pragma as follows:
+
+</p>
+
+<div class="code">
+<pre>
+%insert(runtime) %{
+  // Code to handle throwing of C# CustomApplicationException from C/C++ code.
+  // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
+  // and the equivalent customExceptionCallback instance is customDelegate
+  typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
+  CSharpExceptionCallback_t customExceptionCallback = NULL;
+
+  extern "C" SWIGEXPORT
+  void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
+    customExceptionCallback = customCallback;
+  }
+
+  // Note that SWIG detects any method calls named starting with
+  // SWIG_CSharpSetPendingException for warning 845
+  static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
+    customExceptionCallback(msg);
+  }
+%}
+
+%pragma(csharp) imclasscode=%{
+  class CustomExceptionHelper {
+    // C# delegate for the C/C++ customExceptionCallback
+    public delegate void CustomExceptionDelegate(string message);
+    static CustomExceptionDelegate customDelegate =
+                                   new CustomExceptionDelegate(SetPendingCustomException);
+
+    [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
+    public static extern
+           void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
+
+    static void SetPendingCustomException(string message) {
+      SWIGPendingException.Set(new CustomApplicationException(message));
+    }
+
+    static CustomExceptionHelper() {
+      CustomExceptionRegisterCallback(customDelegate);
+    }
+  }
+  static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
+%}
+</pre>
+</div>
+
+<p>
+The method stored in the C# delegate instance, <tt>customDelegate</tt> is what gets called by the C/C++ callback.
+However, the equivalent to the C# delegate, that is the C/C++ callback, needs to be assigned before any unmanaged code is executed.
+This is achieved by putting the initialisation code in the intermediary class.
+Recall that the intermediary class contains all the PInvoke methods, so the static variables in the intermediary class will be initialised
+before any of the PInvoke methods in this class are called.
+The <tt>exceptionHelper</tt> static variable ensures the C/C++ callback is initialised with the value in <tt>customDelegate</tt> by calling
+the <tt>CustomExceptionRegisterCallback</tt> method in the <tt>CustomExceptionHelper</tt> static constructor.
+Once this has been done, unmanaged code can make callbacks into the managed world as <tt>customExceptionCallback</tt> will be initialised with a valid callback/delegate.
+Any calls to <tt>SWIG_CSharpSetPendingExceptionCustom()</tt> will make the callback to create the pending exception in the same way that
+<tt>SWIG_CSharpSetPendingException()</tt> and <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> does.
+In fact the method has been similarly named so that SWIG can issue the warning about missing <tt>canthrow</tt> attributes as discussed earlier.
+It is an invaluable warning as it is easy to forget the <tt>canthrow</tt> attribute when writing typemaps/features.
+</p>
+
+<p>
+The <tt>SWIGPendingException</tt> helper class is not shown, but is generated as an inner class into the intermediary class.
+It stores the pending exception in Thread Local Storage so that the exception handling mechanism is thread safe.
+</p>
+
+<p>
+The boiler plate code above must be used in addition to a handcrafted <tt>CustomApplicationException</tt>:
+</p>
+
+<div class="code">
+<pre>
+// Custom C# Exception
+class CustomApplicationException : System.ApplicationException {
+  public CustomApplicationException(string message) 
+    : base(message) {
+  }
+}
+</pre>
+</div>
+
+<p>
+and the SWIG interface code:
+</p>
+
+<div class="code">
+<pre>
+%typemap(throws, canthrow=1) std::out_of_range {
+  SWIG_CSharpSetPendingExceptionCustom($1.what());
+  return $null;
+}
+
+%inline %{
+void oddsonly(int input) throw (std::out_of_range) {
+  if (input%2 != 1)
+    throw std::out_of_range("number is not odd");
+}
+%}
+</pre>
+</div>
+
+<p>
+The "throws" typemap now simply calls our new <tt>SWIG_CSharpSetPendingExceptionCustom()</tt> function so that the exception can be caught, as such:
+</p>
+
+<div class="code">
+<pre>
+try {
+  example.oddsonly(2);
+} catch (CustomApplicationException e) {
+  ...
+}
+</pre>
+</div>
+
+<H2><a name="csharp_directors"></a>17.4 C# Directors</H2>
+
+
+<p>
+The SWIG directors feature adds extra code to the generated C# proxy classes that enable these classes to be used in cross-language polymorphism.
+Essentially, it enables unmanaged C++ code to call back into managed code for virtual methods so that a C# class can derive from a wrapped C++ class.
+</p>
+
+<p>
+The following sections provide information on the C# director implementation and contain most of the information required to use the C# directors.
+However, the <a href="Java.html#java_directors">Java directors</a> section should also be read in order to gain more insight into directors.
+</p>
+
+<H3><a name="csharp_directors_example"></a>17.4.1 Directors example</H3>
+
+
+<p>
+Imagine we are wrapping a C++ base class, <tt>Base</tt>, from which we would like to inherit in C#.
+Such a class is shown below as well as another class, <tt>Caller</tt>, which calls the virtual method <tt>UIntMethod</tt>
+from pure unmanaged C++ code.
+</p>
+
+
+<div class="code">
+<pre>
+// file: example.h
+class Base {
+public:
+  virtual ~Base() {}
+
+  virtual unsigned int UIntMethod(unsigned int x) {
+    std::cout &lt;&lt; "Base - UIntMethod(" &lt;&lt; x &lt;&lt; ")" &lt;&lt; std::endl;
+    return x;
+  }
+  virtual void BaseBoolMethod(const Base &amp;b, bool flag) {}
+};
+
+class Caller {
+public:
+  Caller(): m_base(0) {}
+  ~Caller() { delBase(); }
+  void set(Base *b) { delBase(); m_base = b; }
+  void reset() { m_base = 0; }
+  unsigned int UIntMethodCall(unsigned int x) { return m_base-&gt;UIntMethod(x); }
+
+private:
+  Base *m_base;
+  void delBase() { delete m_base; m_base = 0; }
+};
+</pre>
+</div>
+
+<p>
+The director feature is turned off by default and the following simple interface file shows how directors are enabled
+for the class <tt>Base</tt>.
+</p>
+
+<div class="code">
+<pre>
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%feature("director") Base;
+
+%include "example.h"
+</pre>
+</div>
+
+<p>
+The following is a C# class inheriting from <tt>Base</tt>:
+</p>
+
+<div class="code">
+<pre>
+public class CSharpDerived : Base
+{
+  public override uint UIntMethod(uint x)
+  {
+    Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
+    return x;
+  }
+}
+</pre>
+</div>
+
+<p>
+The <tt>Caller</tt> class can demonstrate the <tt>UIntMethod</tt> method being called from unmanaged code using the following C# code:
+</p>
+
+<div class="targetlang">
+<pre>
+public class runme
+{
+  static void Main() 
+  {
+    Caller myCaller = new Caller();
+
+    // Test pure C++ class
+    using (Base myBase = new Base())
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    // Test director / C# derived class
+    using (Base myBase = new CSharpDerived())
+    {
+      makeCalls(myCaller, myBase);
+    }
+  }
+
+  static void makeCalls(Caller myCaller, Base myBase)
+  {
+    myCaller.set(myBase);
+    myCaller.UIntMethodCall(123);
+    myCaller.reset();
+  }
+}
+</pre>
+</div>
+
+<p>
+If the above is run, the output is then:
+</p>
+
+<div class="shell">
+<pre>
+Base - UIntMethod(123)
+CSharpDerived - UIntMethod(123)
+</pre>
+</div>
+
+<H3><a name="csharp_directors_implementation"></a>17.4.2 Directors implementation</H3>
+
+
+<p>
+The previous section demonstrated a simple example where the virtual <tt>UIntMethod</tt> method was called from
+C++ code, even when the overridden method is implemented in C#.
+The intention of this section is to gain an insight into how the director feature works. 
+It shows the generated code for the two virtual methods, <tt>UIntMethod</tt> and <tt>BaseBoolMethod</tt>,
+when the director feature is enabled for the <tt>Base</tt> class.
+</p>
+
+<p>
+Below is the generated C# <tt>Base</tt> director class.
+</p>
+
+<div class="code">
+<pre>
+using System;
+using System.Runtime.InteropServices;
+
+public class Base : IDisposable {
+  private HandleRef swigCPtr;
+  protected bool swigCMemOwn;
+
+  internal Base(IntPtr cPtr, bool cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = new HandleRef(this, cPtr);
+  }
+
+  internal static HandleRef getCPtr(Base obj) {
+    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
+  }
+
+  ~Base() {
+    Dispose();
+  }
+
+  public virtual void Dispose() {
+    lock(this) {
+      if(swigCPtr.Handle != IntPtr.Zero &amp;&amp; swigCMemOwn) {
+        swigCMemOwn = false;
+        examplePINVOKE.delete_Base(swigCPtr);
+      }
+      swigCPtr = new HandleRef(null, IntPtr.Zero);
+      GC.SuppressFinalize(this);
+    }
+  }
+
+  public virtual uint UIntMethod(uint x) {
+    uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
+    return ret;
+  }
+
+  public virtual void BaseBoolMethod(Base b, bool flag) {
+    examplePINVOKE.Base_BaseBoolMethod(swigCPtr, Base.getCPtr(b), flag);
+    if (examplePINVOKE.SWIGPendingException.Pending)
+      throw examplePINVOKE.SWIGPendingException.Retrieve();
+  }
+
+  public Base() : this(examplePINVOKE.new_Base(), true) {
+    SwigDirectorConnect();
+  }
+
+  private void SwigDirectorConnect() {
+    if (SwigDerivedClassHasMethod("UIntMethod", swigMethodTypes0))
+      swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod);
+    if (SwigDerivedClassHasMethod("BaseBoolMethod", swigMethodTypes1))
+      swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod);
+    examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
+  }
+
+  private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
+    System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
+    bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
+    return hasDerivedMethod;
+  }
+
+  private uint SwigDirectorUIntMethod(uint x) {
+    return UIntMethod(x);
+  }
+
+  private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
+    BaseBoolMethod(new Base(b, false), flag);
+  }
+
+  internal delegate uint SwigDelegateBase_0(uint x);
+  internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);
+
+  private SwigDelegateBase_0 swigDelegate0;
+  private SwigDelegateBase_1 swigDelegate1;
+
+  private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
+  private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
+}
+</pre>
+</div>
+
+<p>
+Everything from the <tt>SwigDirectorConnect()</tt> method and below is code that is only generated when
+directors are enabled.
+The design comprises a C# delegate being initialised for each virtual method on construction of the class.
+Let's examine the <tt>BaseBoolMethod</tt>.
+</p>
+
+<p>
+In the <tt>Base</tt> constructor a call is made to <tt>SwigDirectorConnect()</tt> which contains the initialisation code for all the virtual methods.
+It uses a support method, <tt>SwigDerivedClassHasMethod()</tt>, which simply uses reflection to determine if the named method,
+BaseBoolMethod, with the list of required parameter types, exists in a subclass.
+If it does not exist, the delegate is not initialised as there is no need for unmanaged code to call back into managed C# code.
+However, if there is an overridden method in any subclass, the delegate is required. 
+It is then initialised to the <tt>SwigDirectorBaseBoolMethod</tt> which in turn will call <tt>BaseBoolMethod</tt> if invoked.
+The delegate is not initialised to the <tt>BaseBoolMethod</tt> directly as quite often types will need marshalling from the unmanaged type
+to the managed type in which case an intermediary method (<tt>SwigDirectorBaseBoolMethod</tt>) is required for the marshalling.
+In this case, the C# <tt>Base</tt> class needs to be created from the unmanaged <tt>IntPtr</tt> type.
+</p>
+
+<p>
+The last thing that <tt>SwigDirectorConnect()</tt> does is to pass the delegates to the unmanaged code.
+It calls the intermediary method <tt>Base_director_connect()</tt> which is really a call to the C function <tt>CSharp_Base_director_connect()</tt>.
+This method simply maps each C# delegate onto a C function pointer.
+</p>
+
+<div class="code">
+<pre>
+SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg, 
+                                        SwigDirector_Base::SWIG_Callback0_t callback0,
+                                        SwigDirector_Base::SWIG_Callback1_t callback1) {
+  Base *obj = (Base *)objarg;
+  SwigDirector_Base *director = dynamic_cast&lt;SwigDirector_Base *&gt;(obj);
+  if (director) {
+    director-&gt;swig_connect_director(callback0, callback1);
+  }
+}
+
+class SwigDirector_Base : public Base, public Swig::Director {
+public:
+    SwigDirector_Base();
+    virtual unsigned int UIntMethod(unsigned int x);
+    virtual ~SwigDirector_Base();
+    virtual void BaseBoolMethod(Base const &amp;b, bool flag);
+
+    typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int);
+    typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int);
+    void swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
+                               SWIG_Callback1_t callbackBaseBoolMethod);
+
+private:
+    SWIG_Callback0_t swig_callbackUIntMethod;
+    SWIG_Callback1_t swig_callbackBaseBoolMethod;
+    void swig_init_callbacks();
+};
+
+void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
+                                              SWIG_Callback1_t callbackBaseBoolMethod) {
+  swig_callbackUIntMethod = callbackUIntMethod;
+  swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
+}
+</pre>
+</div>
+
+<p>
+Note that for each director class SWIG creates an unmanaged director class for making the callbacks. For example <tt>Base</tt> has <tt>SwigDirector_Base</tt> and <tt>SwigDirector_Base</tt>
+is derived from <tt>Base</tt>.
+Should a C# class be derived from <tt>Base</tt>, the underlying C++ <tt>SwigDirector_Base</tt> is created rather than <tt>Base</tt>.
+The <tt>SwigDirector_Base</tt> class then implements all the virtual methods, redirecting calls up to managed code if the callback/delegate is non-zero.
+The implementation of <tt>SwigDirector_Base::BaseBoolMethod</tt> shows this - the callback is made by invoking the <tt>swig_callbackBaseBoolMethod</tt> function pointer:
+</p>
+
+<div class="code">
+<pre>
+void SwigDirector_Base::BaseBoolMethod(Base const &amp;b, bool flag) {
+  void * jb = 0 ;
+  unsigned int jflag  ;
+  
+  if (!swig_callbackBaseBoolMethod) {
+    Base::BaseBoolMethod(b,flag);
+    return;
+  } else {
+    jb = (Base *) &amp;b; 
+    jflag = flag;
+    swig_callbackBaseBoolMethod(jb, jflag);
+  }
+}
+</pre>
+</div>
+
+<H3><a name="csharp_director_caveats"></a>17.4.3 Director caveats</H3>
+
+
+<p>
+There is a subtle gotcha with directors.
+If default parameters are used, it is recommended to follow a pattern of always calling a single method in any C# derived class.
+An example will clarify this and the reasoning behind the recommendation. Consider the following C++ class wrapped as a director class:
+</p>
+
+<div class="code">
+<pre>
+class Defaults {
+public:
+  virtual ~Defaults();
+  virtual void DefaultMethod(int a=-100);
+};
+</pre>
+</div>
+
+<p>
+Recall that C++ methods with default parameters generate overloaded methods for each defaulted parameter, so a C# derived class can be created
+with two <tt>DefaultMethod</tt> override methods:
+</p>
+
+<div class="code">
+<pre>
+public class CSharpDefaults : Defaults
+{
+  public override void DefaultMethod()
+  {
+    DefaultMethod(-100); // note C++ default value used
+  }
+  public override void DefaultMethod(int x)
+  {
+  }
+}
+</pre>
+</div>
+
+<p>
+It may not be clear at first, but should a user intend to call <tt>CSharpDefaults.DefaultMethod()</tt> from C++, a call is actually made to <tt>CSharpDefaults.DefaultMethod(int)</tt>.
+This is because the initial call is made in C++ and therefore the <tt>DefaultMethod(int)</tt> method will be called as is expected with C++ calls to methods with defaults,
+with the default being set to -100.
+The callback/delegate matching this method is of course the overloaded method <tt>DefaultMethod(int)</tt>.
+However, a call from C# to <tt>CSharpDefaults.DefaultMethod()</tt> will of course call this exact method and in order for behaviour to be consistent with calls from C++, the implementation
+should pass the call on to <tt>CSharpDefaults.DefaultMethod(int)</tt>using the C++ default value, as shown above.
+</p>
+
+<H2><a name="csharp_typemap_examples"></a>17.5 C# Typemap examples</H2>
+
+
+This section includes a few examples of typemaps.  For more examples, you
+might look at the files "<tt>csharp.swg</tt>" and "<tt>typemaps.i</tt>" in
+the SWIG library.
+
+
+<H3><a name="csharp_memory_management_member_variables"></a>17.5.1 Memory management when returning references to member variables</H3>
+
+
+<p>
+This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable.
+The example is a direct equivalent to this <a href="Java.html#java_memory_management_objects">Java equivalent</a>.
+</p>
+
+<p>
+Consider the following C++ code:
+</p>
+
+<div class="code">
+<pre>
+struct Wheel {
+  int size;
+  Wheel(int sz) : size(sz) {}
+};
+
+class Bike {
+  Wheel wheel;
+public:
+  Bike(int val) : wheel(val) {}
+  Wheel&amp; getWheel() { return wheel; }
+};
+</pre>
+</div>
+
+<p>
+and the following usage from C# after running the code through SWIG:
+</p>
+
+
+<div class="code">
+<pre>
+      Wheel wheel = new Bike(10).getWheel();
+      Console.WriteLine("wheel size: " + wheel.size);
+      // Simulate a garbage collection
+      System.GC.Collect();
+      System.GC.WaitForPendingFinalizers();
+      Console.WriteLine("wheel size: " + wheel.size);
+</pre>
+</div>
+
+<p>
+Don't be surprised that if the resulting output gives strange results such as...
+</p>
+
+<div class="shell">
+<pre>
+wheel size: 10
+wheel size: 135019664
+</pre>
+</div>
+
+<p>
+What has happened here is the garbage collector has collected the <tt>Bike</tt> instance as it doesn't think it is needed any more.
+The proxy instance, <tt>wheel</tt>, contains a reference to memory that was deleted when the <tt>Bike</tt> instance was collected.
+In order to prevent the garbage collector from collecting the <tt>Bike</tt> instance a reference to the <tt>Bike</tt> must
+be added to the <tt>wheel</tt> instance. You can do this by adding the reference when the <tt>getWheel()</tt> method
+is called using the following typemaps.
+</p>
+
+
+<div class="code">
+<pre>
+%typemap(cscode) Wheel %{
+  // Ensure that the GC doesn't collect any Bike instance set from C#
+  private Bike bikeReference;
+  internal void addReference(Bike bike) {
+    bikeReference = bike;
+  }
+%}
+
+// Add a C# reference to prevent premature garbage collection and resulting use
+// of dangling C++ pointer. Intended for methods that return pointers or
+// references to a member variable.
+%typemap(csout, excode=SWIGEXCODE) Wheel&amp; getWheel {
+    IntPtr cPtr = $imcall;$excode
+    $csclassname ret = null;
+    if (cPtr != IntPtr.Zero) {
+      ret = new $csclassname(cPtr, $owner);
+      ret.addReference(this);
+    }
+    return ret;
+  }
+</pre>
+</div>
+
+<p>
+The code in the first typemap gets added to the <tt>Wheel</tt> proxy class.
+The code in the second typemap constitutes the bulk of the code in the generated <tt>getWheel()</tt> function:
+</p>
+
+<div class="code">
+<pre>
+public class Wheel : IDisposable {
+  ...
+  // Ensure that the GC doesn't collect any Bike instance set from C#
+  private Bike bikeReference;
+  internal void addReference(Bike bike) {
+    bikeReference = bike;
+  }
+}
+
+public class Bike : IDisposable {
+  ...
+  public Wheel getWheel() {
+    IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
+    Wheel ret = null;
+    if (cPtr != IntPtr.Zero) {
+      ret = new Wheel(cPtr, false);
+      ret.addReference(this);
+    }
+    return ret;
+  }
+}
+</pre>
+</div>
+
+<p>
+Note the <tt>addReference</tt> call.
+</p>
+
+<H3><a name="csharp_memory_management_objects"></a>17.5.2 Memory management for objects passed to the C++ layer</H3>
+
+
+<p>
+The example is a direct equivalent to this <a href="Java.html#java_memory_management_objects">Java equivalent</a>.
+Managing memory can be tricky when using C++ and C# proxy classes.
+The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope
+after the function has returned. Consider the following two C++ classes:
+</p>
+
+<div class="code">
+<pre>
+struct Element {
+  int value;
+  Element(int val) : value(val) {}
+};
+class Container {
+  Element* element;
+public:
+  Container() : element(0) {}
+  void setElement(Element* e) { element = e; }
+  Element* getElement() { return element; }
+};
+</pre>
+</div>
+
+<p>
+and usage from C++
+</p>
+
+<div class="code">
+<pre>
+    Container container;
+    Element element(20);
+    container.setElement(&amp;element);
+    cout &lt;&lt; "element.value: " &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
+</pre>
+</div>
+
+<p>
+and more or less equivalent usage from C#
+</p>
+
+<div class="code">
+<pre>
+      Container container = new Container();
+      Element element = new Element(20);
+      container.setElement(element);
+</pre>
+</div>
+
+<p>
+The C++ code will always print out 20, but the value printed out may not be this in the C# equivalent code.
+In order to understand why, consider a garbage collection occuring...
+</p>
+
+<div class="code">
+<pre>
+      Container container = new Container();
+      Element element = new Element(20);
+      container.setElement(element);
+      Console.WriteLine("element.value: " + container.getElement().value);
+      // Simulate a garbage collection
+      System.GC.Collect();
+      System.GC.WaitForPendingFinalizers();
+      Console.WriteLine("element.value: " + container.getElement().value);
+</pre>
+</div>
+
+<p>
+The temporary element created with <tt>new Element(20)</tt> could get garbage collected
+which ultimately means the <tt>container</tt> variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20.
+One solution is to add in the appropriate references in the C# layer...
+</p>
+
+<div class="code">
+<pre>
+public class Container : IDisposable {
+
+  ...
+
+  // Ensure that the GC doesn't collect any Element set from C#
+  // as the underlying C++ class stores a shallow copy
+  private Element elementReference;
+  private HandleRef getCPtrAndAddReference(Element element) {
+    elementReference = element;
+    return Element.getCPtr(element);
+  }
+
+  public void setElement(Element e) {
+    examplePINVOKE.Container_setElement(swigCPtr, getCPtrAndAddReference(e));
+  }
+}
+</pre>
+</div>
+
+<p>
+The following typemaps will generate the desired code.
+The 'csin' typemap matches the input parameter type for the <tt>setElement</tt> method.
+The 'cscode' typemap simply adds in the specified code into the C# proxy class.
+</p>
+
+<div class="code">
+<pre>
+%typemap(csin) Element *e "getCPtrAndAddReference($csinput)"
+
+%typemap(cscode) Container %{
+  // Ensure that the GC doesn't collect any Element set from C#
+  // as the underlying C++ class stores a shallow copy
+  private Element elementReference;
+  private HandleRef getCPtrAndAddReference(Element element) {
+    elementReference = element;
+    return Element.getCPtr(element);
+  }
+%}
+</pre>
+</div>
+
+
+<H3><a name="csharp_date_marshalling"></a>17.5.3 Date marshalling using the csin typemap and associated attributes</H3>
+
+
+<p>
+The <a href="Java.html#nan_exception_typemap">NaN Exception example</a> is a simple example of the "javain" typemap and its 'pre' attribute.
+This example demonstrates how a C++ date class, say <tt>CDate</tt>, can be mapped onto the standard .NET date class,
+<tt>System.DateTime</tt> by using the 'pre', 'post' and 'pgcppname' attributes of the "csin" typemap (the C# equivalent to the "javain" typemap).
+The example is an equivalent to the <a href="Java.html#java_date_marshalling">Java Date marshalling example</a>.
+The idea is that the <tt>System.DateTime</tt> is used wherever the C++ API uses a <tt>CDate</tt>.
+Let's assume the code being wrapped is as follows:
+</p>
+
+<div class="code">
+<pre>
+class CDate {
+public:
+  CDate(int year, int month, int day);
+  int getYear();
+  int getMonth();
+  int getDay();
+  ...
+};
+struct Action {
+  static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
+  Action(const CDate &amp;date, CDate &amp;dateOut);
+};
+</pre>
+</div>
+
+<p>
+Note that <tt>dateIn</tt> is const and therefore read only and <tt>dateOut</tt> is a non-const output type.
+</p>
+
+<p>
+First let's look at the code that is generated by default, where the C# proxy class <tt>CDate</tt> is used in the proxy interface:
+</p>
+
+<div class="code">
+<pre>
+public class Action : IDisposable {
+  ...
+  public Action(CDate dateIn, CDate dateOut) 
+      : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
+    if (examplePINVOKE.SWIGPendingException.Pending) 
+      throw examplePINVOKE.SWIGPendingException.Retrieve();
+  }
+
+  public int doSomething(CDate dateIn, CDate dateOut) {
+    int ret = examplePINVOKE.Action_doSomething(swigCPtr, 
+                                                CDate.getCPtr(dateIn), 
+                                                CDate.getCPtr(dateOut));
+    if (examplePINVOKE.SWIGPendingException.Pending) 
+      throw examplePINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+}
+</pre>
+</div>
+
+<p>
+The <tt>CDate &amp;</tt> and <tt>const CDate &amp;</tt> C# code is generated from the following two default typemaps:
+</p>
+
+<div class="code">
+<pre>
+%typemap(cstype) SWIGTYPE &amp; "$csclassname"
+%typemap(csin) SWIGTYPE &amp; "$csclassname.getCPtr($csinput)"
+</pre>
+</div>
+
+<p>
+where '$csclassname' is translated into the proxy class name, <tt>CDate</tt> and '$csinput' is translated into the name of the parameter, eg <tt>dateIn</tt>.
+From C#, the intention is then to call into a modifed API with something like:
+</p>
+
+<div class="code">
+<pre>
+System.DateTime dateIn = new System.DateTime(2011, 4, 13);
+System.DateTime dateOut = new System.DateTime();
+
+// Note in calls below, dateIn remains unchanged and dateOut 
+// is set to a new value by the C++ call
+Action action = new Action(dateIn, out dateOut);
+dateIn = new System.DateTime(2012, 7, 14);
+</pre>
+</div>
+
+<p>
+To achieve this mapping, we need to alter the default code generation slightly so that at the C# layer, 
+a <tt>System.DateTime</tt> is converted into a <tt>CDate</tt>. 
+The intermediary layer will still take a pointer to the underlying <tt>CDate</tt> class.
+The typemaps to achieve this are shown below.
+</p>
+
+<div class="code">
+<pre>
+%typemap(cstype) const CDate&amp; "System.DateTime"
+%typemap(csin, 
+         pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);")
+         const CDate &amp;
+         "$csclassname.getCPtr(temp$csinput)"
+
+%typemap(cstype) CDate&amp; "out System.DateTime"
+%typemap(csin, 
+         pre="    CDate temp$csinput = new CDate();", 
+         post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
+              " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", 
+         cshin="out $csinput") CDate &amp;
+         "$csclassname.getCPtr(temp$csinput)"
+
+</pre>
+</div>
+
+<p>
+The resulting generated proxy code in the <tt>Action</tt> class follows:
+ </p>
+
+<div class="code">
+<pre>
+public class Action : IDisposable {
+  ...
+  public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
+    CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
+    CDate tempdateOut = new CDate();
+    try {
+      int ret = examplePINVOKE.Action_doSomething(swigCPtr, 
+                                                  CDate.getCPtr(tempdateIn), 
+                                                  CDate.getCPtr(tempdateOut));
+      if (examplePINVOKE.SWIGPendingException.Pending) 
+        throw examplePINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } finally {
+      dateOut = new System.DateTime(tempdateOut.getYear(), 
+                                    tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
+    }
+  }
+
+  static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
+    CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
+    CDate tempdateOut = new CDate();
+    try {
+      return examplePINVOKE.new_Action(CDate.getCPtr(tempdateIn), CDate.getCPtr(tempdateOut));
+    } finally {
+      dateOut = new System.DateTime(tempdateOut.getYear(), 
+                                    tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
+    }
+  }
+
+  public Action(System.DateTime dateIn, out System.DateTime dateOut) 
+      : this(Action.SwigConstructAction(dateIn, out dateOut), true) {
+    if (examplePINVOKE.SWIGPendingException.Pending) 
+      throw examplePINVOKE.SWIGPendingException.Retrieve();
+  }
+}
+</pre>
+</div>
+
+<p>
+A few things to note:
+</p>
+<ul>
+  <li> The "cstype" typemap has changed the parameter type to <tt>System.DateTime</tt> instead of the default generated <tt>CDate</tt> proxy.
+  <li> The non-const <tt>CDate &amp;</tt> type is marshalled as a reference parameter in C# as the date cannot be explicitly set once the object has been created, so a new object is created instead.
+  <li> The code in the 'pre' attribute appears before the intermediary call (<tt>examplePINVOKE.new_Action</tt> / <tt>examplePINVOKE.Action_doSomething</tt>).
+  <li> The code in the 'post' attribute appears after the intermediary call.
+  <li> A try .. finally block is generated with the intermediary call in the try block and 'post' code in the finally block.
+  The alternative of just using a temporary variable for the return value from the intermediary call and the 'post' code being inserted before the
+  return statement is not possible given that the intermediary call and method return comes from a single source (the "csout" typemap).
+  <li> The temporary variables in the "csin" typemaps are called <tt>temp$csin</tt>, where "$csin" is replaced with the parameter name.
+  "$csin" is used to mangle the variable name so that more than one <tt>CDate &amp;</tt> type can be used as a parameter in a method, otherwise two or 
+  more local variables with the same name would be generated.
+  <li> The use of the "csin" typemap causes a constructor helper function (<tt>SwigConstructAction</tt>) to be generated.
+  This allows C# code to be called before the intermediary call made in the constructor initialization list.
+  <li> The 'cshin' attribute is required for the <tt>SwigConstructAction</tt> constructor helper function so that the 2nd parameter is declared as <tt>out dateOut</tt> instead of just <tt>dateOut</tt>.
+</ul>
+
+<p>
+So far we have considered the date as an input only and an output only type.
+Now let's consider <tt>CDate *</tt> used as an input/output type. Consider the following C++ function which modifies the date passed in:
+</p>
+
+<div class="code">
+<pre>
+void addYears(CDate *pDate, int years) {
+  *pDate = CDate(pDate-&gt;getYear() + years, pDate-&gt;getMonth(), pDate-&gt;getDay());
+}
+</pre>
+</div>
+
+<p>
+If usage of <tt>CDate *</tt> commonly follows this input/output pattern, usage from C# like the following
+</p>
+
+<div class="code">
+<pre>
+System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
+example.addYears(ref christmasEve, 10); // christmasEve now contains 2010-12-24
+</pre>
+</div>
+
+<p>
+will be possible with the following <tt>CDate *</tt> typemaps
+</p>
+
+<div class="code">
+<pre>
+%typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"
+
+%typemap(csin,
+         pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
+         post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
+              " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", 
+         cshin="ref $csinput") CDate *
+         "$csclassname.getCPtr(temp$csinput)"
+</pre>
+</div>
+
+<p>
+Globals are wrapped by the module class and for a module called example, the typemaps result in the following code:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static void addYears(ref System.DateTime pDate, int years) {
+    CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day);
+    try {
+      examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
+    } finally {
+      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
+    }
+  }
+  ...
+}
+</pre>
+</div>
+
+<H3><a name="csharp_date_properties"></a>17.5.4 A date example demonstrating marshalling of C# properties</H3>
+
+
+<p>
+The previous section looked at converting a C++ date class to <tt>System.DateTime</tt> for parameters.
+This section extends this idea so that the correct marshalling is obtained when wrapping C++ variables.
+Consider the same <tt>CDate</tt> class from the previous section and a global variable:
+</p>
+
+<div class="code">
+<pre>
+CDate ImportantDate = CDate(1999, 12, 31);
+</pre>
+</div>
+
+<p>
+The aim is to use <tt>System.DateTime</tt> from C# when accessing this date as shown in the following usage where the module name is 'example':
+</p>
+
+<div class="code">
+<pre>
+example.ImportantDate = new System.DateTime(2000, 11, 22);
+System.DateTime importantDate = example.ImportantDate;
+Console.WriteLine("Important date: " + importantDate);
+</pre>
+</div>
+
+<p>
+When SWIG wraps a variable that is a class/struct/union, it is wrapped using a pointer to the type for the reasons given in <a href="SWIG.html#SWIG_structure_data_members">Stucture data members</a>.
+The typemap type required is thus <tt>CDate *</tt>. Given that the previous section already designed <tt>CDate *</tt> typemaps, we'll use those same typemaps plus the 'csvarin' and 'csvarout' typemaps.
+
+<div class="code">
+<pre>
+%typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"
+
+%typemap(csin,
+         pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
+         post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
+              " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", 
+         cshin="ref $csinput") CDate *
+         "$csclassname.getCPtr(temp$csinput)"
+
+%typemap(csvarin, excode=SWIGEXCODE2) CDate * %{
+    /* csvarin typemap code */
+    set {
+      CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);
+      $imcall;$excode
+    } %}
+
+%typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
+    /* csvarout typemap code */
+    get {
+      IntPtr cPtr = $imcall;
+      CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
+      return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
+                                 0, 0, 0);
+    } %}
+</pre>
+</div>
+
+<p>
+For a module called example, the typemaps result in the following code:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static System.DateTime ImportantDate {
+    /* csvarin typemap code */
+    set {
+      CDate tempvalue = new CDate(value.Year, value.Month, value.Day);
+      examplePINVOKE.ImportantDate_set(CDate.getCPtr(tempvalue));
+    } 
+    /* csvarout typemap code */
+    get {
+      IntPtr cPtr = examplePINVOKE.ImportantDate_get();
+      CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false);
+      return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
+                                 0, 0, 0);
+    } 
+  }
+  ...
+}
+</pre>
+</div>
+
+<p>
+Some points to note:
+</p>
+
+<ul>
+  <li>The property set comes from the 'csvarin' typemap and the property get comes from the 'csvarout' typemap.
+  <li>The type used for the property comes from the 'cstype' typemap. This particular example has the 'out' attribute set in the typemap and as it is specified, it is used in preference to the type in the typemap body. This is because the type in the 'out' attribute can never include modifiers such as 'ref', thereby avoiding code such as <tt>public static ref System.DateTime ImportantDate { ...</tt>, which would of course not compile.
+  <li>The <tt>$excode</tt> special variable expands to nothing as there are no exception handlers specified in any of the unmanaged code typemaps (in fact the marshalling was done using the default unmanaged code typemaps.)
+  <li>The <tt>$imcall</tt> typemap expands to the appropriate intermediary method call in the <tt>examplePINVOKE</tt> class.
+  <li>The <tt>$csinput</tt> special variable in the 'csin' typemap always expands to <tt>value</tt> for properties. In this case <tt>$csclassname.getCPtr(temp$csinput)</tt> expands to <tt>CDate.getCPtr(tempvalue)</tt>.
+  <li>The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and these are all ignored in the property set. The code in these attributes must instead be replicated within the 'csvarin' typemap. The line creating the <tt>temp$csinput</tt> variable is such an example; it is identical to what is in the 'pre' attribute.
+</ul>
+
+
+<H3><a name="csharp_partial_classes"></a>17.5.5 Turning wrapped classes into partial classes</H3>
+
+
+<p>
+C# supports the notion of partial classes whereby a class definition can be split into more than one file.
+It is possible to turn the wrapped C++ class into a partial C# class using the <tt>csclassmodifiers</tt> typemap.
+Consider a C++ class called <tt>ExtendMe</tt>:
+</p>
+
+<div class="code">
+<pre>
+class ExtendMe {
+public:
+  int Part1() { return 1; }
+};
+</pre>
+</div>
+
+<p>
+The default C# proxy class generated is:
+</p>
+
+<div class="code">
+<pre>
+public class ExtendMe : IDisposable {
+  ...
+  public int Part1() {
+    ...
+  }
+}
+</pre>
+</div>
+
+<p>
+The default csclassmodifiers typemap shipped with SWIG is
+</p>
+
+<div class="code">
+<pre>
+%typemap(csclassmodifiers) SWIGTYPE "public class"
+</pre>
+</div>
+
+<p>
+Note that the type used is the special catch all type <tt>SWIGTYPE</tt>.
+If instead we use the following typemap to override this for just the <tt>ExtendMe</tt> class:
+</p>
+
+<div class="code">
+<pre>
+%typemap(csclassmodifiers) ExtendMe "public partial class"
+</pre>
+</div>
+
+<p>
+The C# proxy class becomes a partial class:
+</p>
+
+<div class="code">
+<pre>
+public partial class ExtendMe : IDisposable {
+  ...
+  public int Part1() {
+    ...
+  }
+}
+</pre>
+</div>
+
+<p>
+You can then of course declare another part of the partial class elsewhere, for example:
+</p>
+
+<div class="code">
+<pre>
+public partial class ExtendMe : IDisposable {
+  public int Part2() {
+    return 2;
+  }
+}
+</pre>
+</div>
+
+<p>
+and compile the following code:
+</p>
+
+<div class="code">
+<pre>
+ExtendMe em = new ExtendMe();
+Console.WriteLine("part1: {0}", em.Part1());
+Console.WriteLine("part2: {0}", em.Part2());
+</pre>
+</div>
+
+<p>
+demonstrating that the class contains methods calling both unmanaged code - <tt>Part1()</tt> and managed code - <tt>Part2()</tt>.
+The following example is an alternative approach to adding managed code to the generated proxy class.
+</p>
+
+<H3><a name="csharp_extending_proxy_class"></a>17.5.6 Extending proxy classes with additional C# code</H3>
+
+
+<p>
+The previous example showed how to use partial classes to add functionality to a generated C# proxy class.
+It is also possible to extend a wrapped struct/class with C/C++ code by using the <a href="SWIGPlus.html#SWIGPlus_class_extension">%extend directive</a>.
+A third approach is to add some C# methods into the generated proxy class with the <tt>cscode</tt> typemap.
+If we declare the following typemap before SWIG parses the <tt>ExtendMe</tt> class used in the previous example
+</p>
+
+<div class="code">
+<pre>
+%typemap(cscode) ExtendMe %{
+  public int Part3() {
+    return 3;
+  }
+%}
+
+</pre>
+</div>
+
+<p>
+The generated C# proxy class will instead be:
+</p>
+
+<div class="code">
+<pre>
+public class ExtendMe : IDisposable {
+  ...
+  public int Part3() {
+    return 3;
+  }
+  public int Part1() {
+    ...
+  }
+}
+</pre>
+</div>
+
+</body>
+</html>
+
diff --git a/trunk/Doc/Manual/Chicken.html b/trunk/Doc/Manual/Chicken.html
new file mode 100644
index 0000000..bd1b3d9
--- /dev/null
+++ b/trunk/Doc/Manual/Chicken.html
@@ -0,0 +1,598 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<!-- Hand-written HTML -->
+<html>
+<head>
+<title>SWIG and Chicken</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+
+<H1><a name="Chicken"></a>18 SWIG and Chicken</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Chicken_nn2">Preliminaries</a>
+<ul>
+<li><a href="#Chicken_nn3">Running SWIG in C mode</a>
+<li><a href="#Chicken_nn4">Running SWIG in C++ mode</a>
+</ul>
+<li><a href="#Chicken_nn5">Code Generation</a>
+<ul>
+<li><a href="#Chicken_nn6">Naming Conventions</a>
+<li><a href="#Chicken_nn7">Modules</a>
+<li><a href="#Chicken_nn8">Constants and Variables</a>
+<li><a href="#Chicken_nn9">Functions</a>
+<li><a href="#Chicken_nn10">Exceptions</a>
+</ul>
+<li><a href="#Chicken_nn11">TinyCLOS</a>
+<li><a href="#Chicken_nn12">Linkage</a>
+<ul>
+<li><a href="#Chicken_nn13">Static binary or shared library linked at compile time</a>
+<li><a href="#Chicken_nn14">Building chicken extension libraries</a>
+<li><a href="#Chicken_nn15">Linking multiple SWIG modules with TinyCLOS</a>
+</ul>
+<li><a href="#Chicken_nn16">Typemaps</a>
+<li><a href="#Chicken_nn17">Pointers</a>
+<ul>
+<li><a href="#collection">Garbage collection</a>
+</ul>
+<li><a href="#Chicken_nn18">Unsupported features and known problems</a>
+<ul>
+<li><a href="#Chicken_nn19">TinyCLOS problems with Chicken version &lt;= 1.92</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+    <p>
+      This chapter describes SWIG's support of CHICKEN.  CHICKEN is a
+      Scheme-to-C compiler supporting most of the language features as
+      defined in the <i>Revised^5 Report on Scheme</i>.  Its main
+      attributes are that it
+    </p>
+
+      <ol>
+	<li>generates portable C code</li>
+	<li>includes a customizable interpreter</li>
+	<li>links to C libraries with a simple Foreign Function Interface</li>
+	<li>supports full tail-recursion and first-class continuations</li>
+      </ol>
+
+    <p>
+      When confronted with a large C library, CHICKEN users can use
+      SWIG to generate CHICKEN wrappers for the C library.  However,
+      the real advantages of using SWIG with CHICKEN are its
+      <strong>support for C++</strong> -- object-oriented code is
+      difficult to wrap by hand in CHICKEN -- and its <strong>typed
+      pointer representation</strong>, essential for C and C++
+      libraries involving structures or classes.
+
+    </p>
+
+<H2><a name="Chicken_nn2"></a>18.1 Preliminaries</H2>
+
+
+    <p>
+      CHICKEN support was introduced to SWIG in version 1.3.18.  SWIG
+      relies on some recent additions to CHICKEN, which are only
+      present in releases of CHICKEN with version number
+      <strong>greater than or equal to 1.89</strong>.  
+      To use a chicken version between 1.40 and 1.89, see the <a href="#collection">Garbage collection</a>
+      section below.
+    </p>
+
+      <p>
+      You may want to look at any of the examples in Examples/chicken/
+      or Examples/GIFPlot/Chicken for the basic steps to run SWIG
+      CHICKEN.
+      </p>
+
+<H3><a name="Chicken_nn3"></a>18.1.1 Running SWIG in C mode</H3>
+
+
+      <p>
+      To run SWIG CHICKEN in C mode, use
+      the -chicken option.
+      </p>
+
+      <div class="shell">
+	<pre>% swig -chicken example.i</pre>
+      </div>
+
+      <p>
+      To allow the wrapper to take advantage of future CHICKEN code
+      generation improvements, part of the wrapper is direct CHICKEN
+      function calls (<tt>example_wrap.c</tt>) and part is CHICKEN
+      Scheme (<tt>example.scm</tt>).  The basic Scheme code must
+      be compiled to C using your system's CHICKEN compiler or
+      both files can be compiled directly using the much simpler <tt>csc</tt>.
+      </p>
+
+      <div class="shell">
+<pre>
+% chicken example.scm -output-file oexample.c
+</pre>
+      </div>
+
+      <p>
+      So for the C mode of SWIG CHICKEN, <tt>example_wrap.c</tt> and
+      <tt>oexample.c</tt> are the files that must be compiled to
+      object files and linked into your project.
+      </p>
+
+<H3><a name="Chicken_nn4"></a>18.1.2 Running SWIG in C++ mode</H3>
+
+
+      <p>
+      To run SWIG CHICKEN in C++ mode, use
+      the -chicken -c++ option.
+      </p>
+
+      <div class="shell">
+	<pre>% swig -chicken -c++ example.i</pre>
+      </div>
+
+      <p>
+      This will generate <tt>example_wrap.cxx</tt> and
+      <tt>example.scm</tt>.  The basic Scheme code must be
+      compiled to C using your system's CHICKEN compiler or
+      both files can be compiled directly using the much simpler <tt>csc</tt>.
+      </p>
+
+      <div class="shell">
+	<pre>% chicken example.scm -output-file oexample.c</pre>
+      </div>
+
+      <p>
+      So for the C++ mode of SWIG CHICKEN, <tt>example_wrap.cxx</tt>
+      and <tt>oexample.c</tt> are the files that must be compiled to
+      object files and linked into your project.
+      </p>
+
+<H2><a name="Chicken_nn5"></a>18.2 Code Generation</H2>
+
+
+<H3><a name="Chicken_nn6"></a>18.2.1 Naming Conventions</H3>
+
+
+    <p>
+      Given a C variable, function or constant declaration named
+      <tt>Foo_Bar</tt>, the declaration will be available
+      in CHICKEN as an identifier ending with
+      <tt>Foo-Bar</tt>.  That is, an underscore is converted
+      to a dash.
+    </p>
+
+    <p>
+      You may control what the CHICKEN identifier will be by using the
+      <tt>%rename</tt> SWIG directive in the SWIG interface file.
+    </p>
+
+<H3><a name="Chicken_nn7"></a>18.2.2 Modules</H3>
+
+
+      <p>
+      The name of the module must be declared one of two ways:
+      <ul>
+	<li>Placing <tt>%module example</tt> in the SWIG interface
+	  file.</li>
+	<li>Using <tt>-module example</tt> on the SWIG command
+	  line.</li>
+      </ul>
+
+      <p>
+      The generated example.scm file then exports <code>(declare (unit modulename))</code>.
+      If you do not want SWIG to export the <code>(declare (unit modulename))</code>, pass
+      the -nounit option to SWIG.
+
+    <p>
+      CHICKEN will be able to access the module using the <code>(declare
+	(uses <i>modulename</i>))</code> CHICKEN Scheme form.
+    </p>
+
+<H3><a name="Chicken_nn8"></a>18.2.3 Constants and Variables</H3>
+
+
+    <p>
+      Constants may be created using any of the four constructs in
+      the interface file:
+    </p>
+      <ol>
+	<li><code>#define MYCONSTANT1 ...</code></li>
+	<li><code>%constant int MYCONSTANT2 = ...</code></li>
+	<li><code>const int MYCONSTANT3 = ...</code></li>
+	<li><code>enum { MYCONSTANT4  = ... };</code></li>
+      </ol>
+
+    <p>
+      In all cases, the constants may be accessed from within CHICKEN
+      using the form <tt>(MYCONSTANT1)</tt>; that is, the constants
+      may be accessed using the read-only parameter form.
+    </p>
+
+    <p>
+      Variables are accessed using the full parameter form.
+      For example, to set the C variable "int my_variable;", use the
+      Scheme form <tt>(my-variable 2345)</tt>.  To get the C variable,
+      use <tt>(my-variable)</tt>.
+    </p>
+
+    <p>
+      The <tt>%feature("constasvar")</tt> can be applied to any constant
+      or immutable variable.  Instead of exporting the constant as
+      a function that must be called, the constant will appear as a
+      scheme variable.  This causes the generated .scm file to just contain the code
+      <tt>(set! MYCONSTANT1 (MYCONSTANT1))</tt>. See 
+      <a href="Customization.html#features">Features and the %feature directive</a>
+      for info on how to apply the %feature.
+    </p>
+
+<H3><a name="Chicken_nn9"></a>18.2.4 Functions</H3>
+
+
+    <p>
+      C functions declared in the SWIG interface file will have
+      corresponding CHICKEN Scheme procedures.  For example, the C
+      function "int sqrt(double x);" will be available using the
+      Scheme form <tt>(sqrt 2345.0)</tt>.  A <code>void</code> return
+      value will give C_SCHEME_UNDEFINED as a result.
+    </p>
+    <p>
+      A function may return more than one value by using the
+      <code>OUTPUT</code> specifier (see Lib/chicken/typemaps.i).
+      They will be returned as multiple values using <code>(values)</code> if there is more than one
+      result (that is, a non-void return value and at least one argout
+      parameter, or a void return value and at least two argout
+      parameters).  The return values can then be accessed with <code>(call-with-values)</code>.
+    </p>
+
+<H3><a name="Chicken_nn10"></a>18.2.5 Exceptions</H3>
+
+
+     <p>The SWIG chicken module has support for exceptions thrown from
+     C or C++ code to be caught in scheme.  
+     See <a href="Customization.html#exception">Exception handling with %exception</a>
+     for more information about declaring exceptions in the interface file.
+     </p>
+
+     <p>Chicken supports both the <code>SWIG_exception(int code, const char *msg)</code> interface
+     as well as a <code>SWIG_ThrowException(C_word val)</code> function for throwing exceptions from
+     inside the %exception blocks.  <code>SWIG_exception</code> will throw a list consisting of the code
+     (as an integer) and the message.  Both of these will throw an exception using <code>(abort)</code>,
+     which can be handled by <code>(handle-exceptions)</code>.  See
+     <a href="http://www.call-with-current-continuation.org/manual/Exceptions.html#Exceptions">Chicken manual on Exceptions</a>
+     and <a href="http://srfi.schemers.org/srfi-12/srfi-12.html">SFRI-12</a>.  Since the exception values are thrown
+     directly, if <code>(condition-case)</code> is used to catch an exception the exception will come through in the <code>val ()</code> case.
+     </p>
+
+     <p>The following simple module</p>
+     
+<div class="code"><pre>
+%module exception_test
+
+%inline %{
+  void test_throw(int i) throws (int) { 
+    if (i == 1) throw 15; 
+  }
+%}
+</pre></div>
+
+     <p>could be run with</p>
+
+<div class="targetlang"><pre>
+(handle-exceptions exvar 
+  (if (= exvar 15)
+    (print "Correct!") 
+    (print "Threw something else " exvar))
+  (test-throw 1))
+</pre></div>
+
+
+<H2><a name="Chicken_nn11"></a>18.3 TinyCLOS</H2>
+
+
+      <p>
+      The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as:
+	"Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a
+	metaobject protocol. The implementation is even simpler than
+	the simple CLOS found in `The Art of the Metaobject Protocol,'
+	weighing in at around 850 lines of code, including (some)
+	comments and documentation."
+      </p>
+
+      <p>
+      Almost all good Scheme books describe how to use metaobjects and
+      generic procedures to implement an object-oriented Scheme
+      system.  Please consult a Scheme book if you are unfamiliar
+      with the concept.
+      </p>
+
+      <p>
+
+      CHICKEN has a modified version of TinyCLOS, which SWIG CHICKEN
+      uses if the -proxy argument is given.  If -proxy is passed, then
+      the generated example.scm file will contain TinyCLOS class definitions.
+      A class named Foo is declared as &lt;Foo&gt;, and each member variable
+      is allocated a slot.  Member functions are exported as generic functions.
+
+      <p>
+      
+      Primitive symbols and functions (the interface that would be presented if
+      -proxy was not passed) are hidden and no longer accessible.  If the -unhideprimitive
+      command line argument is passed to SWIG, then the primitive symbols will be
+      available, but each will be prefixed by the string "primitive:"
+
+      <p>
+
+      The exported symbol names can be controlled with the -closprefix and -useclassprefix arguments.
+      If -useclassprefix is passed to SWIG, every member function will be generated with the class name
+      as a prefix.  If the -closprefix mymod: argument is passed to SWIG, then the exported functions will
+      be prefixed by the string "mymod:".  If -useclassprefix is passed, -closprefix is ignored.
+      
+      </p>
+
+<H2><a name="Chicken_nn12"></a>18.4 Linkage</H2>
+
+
+    <p>
+      Please refer to <em>CHICKEN - A practical and portable Scheme
+      system - User's manual</em> for detailed help on how to link
+      object files to create a CHICKEN Scheme program.  Briefly, to
+      link object files, be sure to add <tt>`chicken-config
+      -extra-libs -libs`</tt> or <tt>`chicken-config -shared
+      -extra-libs -libs`</tt>to your linker options.  Use the
+      <tt>-shared</tt> option if you want to create a dynamically
+      loadable module.  You might also want to use the much simpler
+      <tt>csc</tt> or <tt>csc.bat</tt>.
+    </p>
+
+    <p>Each scheme file that is generated
+   by SWIG contains <code>(declare (uses <i>modname</i>))</code>.  This means that to load the
+   module from scheme code, the code must include <code>(declare (uses <i>modname</i>))</code>.
+   </p>
+
+
+<H3><a name="Chicken_nn13"></a>18.4.1 Static binary or shared library linked at compile time</H3>
+
+
+   <p>We can easily use csc to build a static binary.</p>
+
+<div class="shell">
+<pre>
+$ swig -chicken example.i
+$ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example
+$ ./example
+</pre>
+</div>
+
+<p>Similar to the above, any number of <tt>module.scm</tt> files could be compiled
+into a shared library, and then that shared library linked when compiling the
+main application.</p>
+
+<div class="shell">
+<pre>
+$ swig -chicken example.i
+$ csc -sv example.scm example_wrap.c example_impl.c -o example.so
+</pre>
+</div>
+
+<p>The <tt>example.so</tt> file can then linked with <tt>test_script.scm</tt> when it
+is compiled, in which case <tt>test_script.scm</tt> must have <code>(declare (uses example))</code>.
+Multiple SWIG modules could have been linked into <tt>example.so</tt> and each
+one accessed with a <code>(declare (uses ... ))</code>.
+</p>
+
+<div class="shell">
+<pre>
+$ csc -v test_script.scm -lexample
+</pre>
+</div>
+
+<p>An alternative is that the test_script.scm can have the code <code>(load-library 'example "example.so")</code>,
+in which case the test script does not need to be linked with example.so.  The test_script.scm file can then
+be run with <tt>csi</tt>.
+</p>
+
+<H3><a name="Chicken_nn14"></a>18.4.2 Building chicken extension libraries</H3>
+
+
+<p>Building a shared library like in the above section only works if the library
+is linked at compile time with a script containing <code>(declare (uses ...))</code> or is
+loaded explicitly with <code>(load-library 'example "example.so")</code>. It is
+not the format that CHICKEN expects for extension libraries and eggs.  The problem is the
+<code>(declare (unit <i>modname</i>))</code> inside the <tt>modname.scm</tt> file.  There are
+two possible solutions to this.</p>
+
+<p>First, SWIG accepts a <tt>-nounit</tt> argument, in which case the <code>(declare (unit <i>modname</i>))</code>
+is not generated.  Then, the <tt>modname.scm</tt> and <tt>modname_wrap.c</tt> files <b>must</b> be compiled into
+their own shared library.</p>
+
+<div class="shell">
+<pre>
+$ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so
+</pre>
+</div>
+
+<p>This library can then be loaded by scheme code with the <code>(require 'modname)</code> function.
+See <a href="http://www.call-with-current-continuation.org/manual/Loading-extension-libraries.html">
+Loading-extension-libraries</a> in the eval unit inside the CHICKEN manual for more information.</p>
+
+<p>Another alternative is to run SWIG normally and create a scheme file that contains <code>(declare (uses <i>modname</i>))</code>
+and then compile that file into the shared library as well.  For example, inside the <tt>mod_load.scm</tt> file,</p>
+
+<div class="targetlang">
+<pre>
+(declare (uses mod1))
+(declare (uses mod2))
+</pre>
+</div>
+
+<p>Which would then be compiled with</p>
+
+<div class="shell">
+<pre>
+$ swig -chicken mod1.i
+$ swig -chicken mod2.i
+$ csc -sv mod_load.scm mod1.scm mod2.scm mod1_wrap.c mod2_wrap.c mod1_impl.c mod2_impl.c -o mod.so
+</pre>
+</div>
+
+<p>Then the extension library can be loaded with <code>(require 'mod)</code>.  As we can see here,
+<tt>mod_load.scm</tt> contains the code that gets executed when the module is loaded.  All this code
+does is load both mod1 and mod2.  As we can see, this technique is more useful when you want to
+combine a few SWIG modules into one chicken extension library, especially if modules are related by
+<code>%import</code></p>
+
+<p>In either method, the files that are compiled into the shared library could also be
+packaged into an egg.  The <tt>mod1_wrap.c</tt> and <tt>mod2_wrap.c</tt> files that are created by SWIG
+are stand alone and do not need SWIG to be installed to be compiled.  Thus the egg could be
+distributed and used by anyone, even if SWIG is not installed.</p>
+
+<p>See the <tt>Examples/chicken/egg</tt> directory in the SWIG source for an example that builds
+two eggs, one using the first method and one using the second method.</p>
+
+<H3><a name="Chicken_nn15"></a>18.4.3 Linking multiple SWIG modules with TinyCLOS</H3>
+
+
+<p>Linking together multiple modules that share type information using the <code>%import</code>
+directive while also using <tt>-proxy</tt> is more complicated.  For example, if <tt>mod2.i</tt> imports <tt>mod1.i</tt>, then the
+<tt>mod2.scm</tt> file contains references to symbols declared in <tt>mod1.scm</tt>,
+and thus a <code>(declare (uses <i>mod1</i>))</code> or <code>(require '<i>mod1</i>)</code> must be exported
+to the top of <tt>mod2.scm</tt>.  By default, when SWIG encounters an <code>%import "modname.i"</code> directive,
+it exports <code>(declare (uses <i>modname</i>))</code> into the scm file.  This works fine unless mod1 was compiled with
+the <tt>-nounit</tt> argument or was compiled into an extension library with other modules under a different name.</p>
+
+<p>One option is to override the automatic generation of <code>(declare (uses mod1))</code>
+by passing the <tt>-noclosuses</tt> option to SWIG when compiling <tt>mod2.i</tt>.
+SWIG then provides the <code>%insert(closprefix) %{ %}</code> directive.  Any scheme code inside that directive is inserted into the
+generated .scm file, and if <tt>mod1</tt> was compiled with <tt>-nounit</tt>, the directive should contain <code>(require 'mod1)</code>.
+This option allows for mixed loading as well, where some modules are imported with <code>(declare (uses <i>modname</i>))</code>
+(which means they were compiled without -nounit) and some are imported with <code>(require 'modname)</code>.</p>
+
+<p>The other option is to use the second idea in the above section.  Compile all the modules normally, without any
+<code>%insert(closprefix)</code>, <tt>-nounit</tt>, or <tt>-noclosuses</tt>.  Then the modules will import each other correctly
+with <code>(declare (uses ...))</code>.
+To create an extension library or an egg, just create a <tt>module_load.scm</tt> file that <code>(declare (uses ...))</code>
+all the modules.</p>
+
+<H2><a name="Chicken_nn16"></a>18.5 Typemaps</H2>
+
+
+    <p>
+      The Chicken module handles all types via typemaps. This information is
+      read from <code>Lib/chicken/typemaps.i</code> and
+      <code>Lib/chicken/chicken.swg</code>.
+    </p>
+
+<H2><a name="Chicken_nn17"></a>18.6 Pointers</H2>
+
+
+    <p>
+      For pointer types, SWIG uses CHICKEN tagged pointers.
+
+      A tagged pointer is an ordinary CHICKEN pointer with an
+      extra slot for a void *.  With SWIG
+      CHICKEN, this void * is a pointer to a type-info
+      structure.  So each pointer used as input or output from
+      the SWIG-generated CHICKEN wrappers will have type
+      information attached to it.  This will let the wrappers
+      correctly determine which method should be called
+      according to the object type hierarchy exposed in the SWIG
+      interface files.
+    </p>
+    <p>
+      To construct a Scheme object from a C pointer, the wrapper code
+      calls the function 
+      <code>SWIG_NewPointerObj(void *ptr, swig_type_info *type, int owner)</code>,
+      The function that calls <code>SWIG_NewPointerObj</code> must have a variable declared
+      <code>C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);</code>
+      It is ok to call <code>SWIG_NewPointerObj</code> more than once, 
+      just make sure known_space has enough space for all the created pointers.
+    </p>
+    <p>
+      To get the pointer represented by a CHICKEN tagged pointer, the
+      wrapper code calls the function 
+      <code>SWIG_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags)</code>,
+      passing a pointer to a struct representing the expected pointer
+      type. flags is either zero or SWIG_POINTER_DISOWN (see below).
+    </p>
+
+<H3><a name="collection"></a>18.6.1 Garbage collection</H3>
+
+
+  <p>If the owner flag passed to <code>SWIG_NewPointerObj</code> is 1, <code>NewPointerObj</code> will add a
+     finalizer to the type which will call the destructor or delete method of
+     that type.  The destructor and delete functions are no longer exported for
+     use in scheme code, instead SWIG and chicken manage pointers.
+  In situations where SWIG knows that a function is returning a type that should
+  be garbage collected, SWIG will automatically set the owner flag to 1.  For other functions,
+  the <code>%newobject</code> directive must be specified for functions whose return values
+  should be garbage collected.  See 
+  <a href="Customization.html#ownership">Object ownership and %newobject</a> for more information.
+  </p>
+
+  <p>In situations where a C or C++ function will assume ownership of a pointer, and thus
+  chicken should no longer garbage collect it, SWIG provides the <code>DISOWN</code> input typemap.
+  After applying this typemap (see the <a href="Typemaps.html">Typemaps chapter</a> for more information on how to apply typemaps),
+  any pointer that gets passed in will no longer be garbage collected.  
+  An object is disowned by passing the <code>SWIG_POINTER_DISOWN</code> flag to <code>SWIG_ConvertPtr</code>.
+  <b>Warning:</b> Since the lifetime of the object is now controlled by the underlying code, the object might
+  get deleted while the scheme code still holds a pointer to it.  Further use of this pointer
+  can lead to a crash.
+  </p>
+
+  <p>Adding a finalizer function from C code was added to chicken in the 1.89 release, so garbage collection
+  does not work for chicken versions below 1.89.  If you would like the SWIG generated code to work with
+  chicken 1.40 to 1.89, pass the <code>-nocollection</code> argument to SWIG.  This will not export code
+  inside the _wrap.c file to register finalizers, and will then export destructor functions which
+  must be called manually.
+  </p>
+
+<H2><a name="Chicken_nn18"></a>18.7 Unsupported features and known problems</H2>
+
+
+    <ul>
+      <li>No director support.</li>
+      <li>No support for c++ standard types like std::vector.</li>
+      <li>The TinyCLOS wrappers for overloaded functions will not work correctly when using 
+          <a href="SWIGPlus.html#SWIGPlus_default_args">%feature(compactdefaultargs)</a>.</li>
+    </ul>
+
+<H3><a name="Chicken_nn19"></a>18.7.1 TinyCLOS problems with Chicken version &lt;= 1.92</H3>
+
+
+    <p>In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods
+    with different number of specializers: TinyCLOS assumes that every method added to a generic function
+    will have the same number of specializers. SWIG generates functions with different lengths of specializers
+    when C/C++ functions are overloaded.  For example, the code</p>
+
+<div class="code">
+<pre>
+class Foo {};
+int foo(int a, Foo *b);
+int foo(int a);
+</pre></div>
+
+<p>will produce scheme code</p>
+
+<div class="targetlang">
+<pre>
+(define-method (foo (arg0 &lt;top&gt;) (arg1 &lt;Foo&gt;)) (<i>call primitive function</i>))
+(define-method (foo (arg0 &lt;top&gt;)) (<i>call primitive function</i>))
+</pre></div>
+
+<p>Using unpatched TinyCLOS, the second <code>(define-method)</code> will replace the first one,
+so calling <code>(foo 3 f)</code> will produce an error.</p>
+
+<p>There are three solutions to this.  The easist is to upgrade to the latest Chicken version.  Otherwise, the
+file <tt>Lib/chicken/tinyclos-multi-generic.patch</tt> in the SWIG source contains a patch against
+tinyclos.scm inside the 1.92 chicken source to add support into TinyCLOS for multi-argument generics.  (This patch was accepted into Chicken)
+This requires chicken to be rebuilt and custom install of chicken.  An alternative is the <tt>Lib/chicken/multi-generic.scm</tt>
+file in the SWIG source.  This file can be loaded after TinyCLOS is loaded, and it will override some functions
+inside TinyCLOS to correctly support multi-argument generics.  Please see the comments at the top of both files for more information.</p>
+
+  </body>
+</html>
diff --git a/trunk/Doc/Manual/Contents.html b/trunk/Doc/Manual/Contents.html
new file mode 100644
index 0000000..961b4c8
--- /dev/null
+++ b/trunk/Doc/Manual/Contents.html
@@ -0,0 +1,1540 @@
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<HTML>
+<HEAD>
+<TITLE>SWIG Users Manual</TITLE>
+</HEAD>
+<BODY BGCOLOR="#ffffff">
+<H1>SWIG Users Manual</H1>
+
+<p>
+
+<h3><a href="Preface.html#Preface">1 Preface</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Preface.html#Preface_nn2">Introduction</a>
+<li><a href="Preface.html#Preface_nn3">Special Introduction for Version 1.3</a>
+<li><a href="Preface.html#Preface_nn4">SWIG Versions</a>
+<li><a href="Preface.html#Preface_nn5">SWIG resources</a>
+<li><a href="Preface.html#Preface_nn6">Prerequisites</a>
+<li><a href="Preface.html#Preface_nn7">Organization of this manual</a>
+<li><a href="Preface.html#Preface_nn8">How to avoid reading the manual</a>
+<li><a href="Preface.html#Preface_nn9">Backwards Compatibility</a>
+<li><a href="Preface.html#Preface_nn10">Credits</a>
+<li><a href="Preface.html#Preface_nn11">Bug reports</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Introduction.html#Introduction">2 Introduction</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Introduction.html#Introduction_nn2">What is SWIG?</a>
+<li><a href="Introduction.html#Introduction_nn3">Why use SWIG?</a>
+<li><a href="Introduction.html#Introduction_nn4">A SWIG example</a>
+<ul>
+<li><a href="Introduction.html#Introduction_nn5">SWIG interface file</a>
+<li><a href="Introduction.html#Introduction_nn6">The swig command</a>
+<li><a href="Introduction.html#Introduction_nn7">Building a Perl5 module</a>
+<li><a href="Introduction.html#Introduction_nn8">Building a Python module</a>
+<li><a href="Introduction.html#Introduction_nn9">Shortcuts</a>
+</ul>
+<li><a href="Introduction.html#Introduction_nn10">Supported C/C++ language features</a>
+<li><a href="Introduction.html#Introduction_nn11">Non-intrusive interface building</a>
+<li><a href="Introduction.html#Introduction_build_system">Incorporating SWIG into a build system</a>
+<li><a href="Introduction.html#Introduction_nn12">Hands off code generation</a>
+<li><a href="Introduction.html#Introduction_nn13">SWIG and freedom</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Windows.html#Windows">3 Getting started on Windows </a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Windows.html#Windows_installation">Installation on Windows</a>
+<ul>
+<li><a href="Windows.html#Windows_executable">Windows Executable</a>
+</ul>
+<li><a href="Windows.html#Windows_examples">SWIG Windows Examples</a>
+<ul>
+<li><a href="Windows.html#Windows_visual_studio">Instructions for using the Examples with Visual Studio</a>
+<ul>
+<li><a href="Windows.html#Windows_csharp">C#</a>
+<li><a href="Windows.html#Windows_java">Java</a>
+<li><a href="Windows.html#Windows_perl">Perl</a>
+<li><a href="Windows.html#Windows_python">Python</a>
+<li><a href="Windows.html#Windows_tcl">TCL</a>
+<li><a href="Windows.html#Windows_r">R</a>
+<li><a href="Windows.html#Windows_ruby">Ruby</a>
+</ul>
+<li><a href="Windows.html#Windows_other_compilers">Instructions for using the Examples with other compilers</a>
+</ul>
+<li><a href="Windows.html#Windows_cygwin_mingw">SWIG on Cygwin and MinGW</a>
+<ul>
+<li><a href="Windows.html#Windows_swig_exe">Building swig.exe on Windows</a>
+<ul>
+<li><a href="Windows.html#Windows_mingw_msys">Building swig.exe using MinGW and MSYS</a>
+<li><a href="Windows.html#Windows_cygwin">Building swig.exe using Cygwin</a>
+<li><a href="Windows.html#Windows_building_alternatives">Building swig.exe alternatives</a>
+</ul>
+<li><a href="Windows.html#Windows_examples_cygwin">Running the examples on Windows using Cygwin</a>
+</ul>
+<li><a href="Windows.html#Windows_interface_file">Microsoft extensions and other Windows quirks</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Scripting.html#Scripting">4 Scripting Languages</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Scripting.html#Scripting_nn2">The two language view of the world</a>
+<li><a href="Scripting.html#Scripting_nn3">How does a scripting language talk to C?</a>
+<ul>
+<li><a href="Scripting.html#Scripting_nn4">Wrapper functions</a>
+<li><a href="Scripting.html#Scripting_nn5">Variable linking</a>
+<li><a href="Scripting.html#Scripting_nn6">Constants</a>
+<li><a href="Scripting.html#Scripting_nn7">Structures and classes</a>
+<li><a href="Scripting.html#Scripting_nn8">Proxy classes</a>
+</ul>
+<li><a href="Scripting.html#Scripting_nn9">Building scripting language extensions</a>
+<ul>
+<li><a href="Scripting.html#Scripting_nn10">Shared libraries and dynamic loading</a>
+<li><a href="Scripting.html#Scripting_nn11">Linking with shared libraries</a>
+<li><a href="Scripting.html#Scripting_nn12">Static linking</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="SWIG.html#SWIG">5 SWIG Basics</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="SWIG.html#SWIG_nn2">Running SWIG</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn3">Input format</a>
+<li><a href="SWIG.html#output">SWIG Output</a>
+<li><a href="SWIG.html#SWIG_nn5">Comments</a>
+<li><a href="SWIG.html#SWIG_nn6">C Preprocessor</a>
+<li><a href="SWIG.html#SWIG_nn7">SWIG Directives</a>
+<li><a href="SWIG.html#SWIG_nn8">Parser Limitations</a>
+</ul>
+<li><a href="SWIG.html#SWIG_nn9">Wrapping Simple C Declarations</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn10">Basic Type Handling</a>
+<li><a href="SWIG.html#SWIG_nn11">Global Variables</a>
+<li><a href="SWIG.html#SWIG_nn12">Constants</a>
+<li><a href="SWIG.html#SWIG_nn13">A brief word about <tt>const</tt></a>
+<li><a href="SWIG.html#SWIG_nn14">A cautionary tale of <tt>char *</tt></a>
+</ul>
+<li><a href="SWIG.html#SWIG_nn15">Pointers and complex objects</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn16">Simple pointers</a>
+<li><a href="SWIG.html#SWIG_nn17">Run time pointer type checking</a>
+<li><a href="SWIG.html#SWIG_nn18">Derived types, structs, and classes</a>
+<li><a href="SWIG.html#SWIG_nn19">Undefined datatypes</a>
+<li><a href="SWIG.html#SWIG_nn20">Typedef</a>
+</ul>
+<li><a href="SWIG.html#SWIG_nn21">Other Practicalities</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn22">Passing structures by value</a>
+<li><a href="SWIG.html#SWIG_nn23">Return by value</a>
+<li><a href="SWIG.html#SWIG_nn24">Linking to structure variables</a>
+<li><a href="SWIG.html#SWIG_nn25">Linking to <tt>char *</tt></a>
+<li><a href="SWIG.html#SWIG_nn26">Arrays</a>
+<li><a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a>
+<li><a href="SWIG.html#SWIG_rename_ignore">Renaming and ignoring declarations</a>
+<li><a href="SWIG.html#SWIG_default_args">Default/optional arguments</a>
+<li><a href="SWIG.html#SWIG_nn30">Pointers to functions and callbacks</a>
+</ul>
+<li><a href="SWIG.html#SWIG_nn31">Structures and unions</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn32">Typedef and structures</a>
+<li><a href="SWIG.html#SWIG_nn33">Character strings and structures</a>
+<li><a href="SWIG.html#SWIG_nn34">Array members</a>
+<li><a href="SWIG.html#SWIG_structure_data_members">Structure data members</a>
+<li><a href="SWIG.html#SWIG_nn36">C constructors and destructors </a>
+<li><a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>
+<li><a href="SWIG.html#SWIG_nested_structs">Nested structures</a>
+<li><a href="SWIG.html#SWIG_nn39">Other things to note about structure wrapping</a>
+</ul>
+<li><a href="SWIG.html#SWIG_nn40">Code Insertion</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn41">The output of SWIG</a>
+<li><a href="SWIG.html#SWIG_nn42">Code insertion blocks</a>
+<li><a href="SWIG.html#SWIG_nn43">Inlined code blocks</a>
+<li><a href="SWIG.html#SWIG_nn44">Initialization blocks</a>
+</ul>
+<li><a href="SWIG.html#SWIG_nn45">An Interface Building Strategy</a>
+<ul>
+<li><a href="SWIG.html#SWIG_nn46">Preparing a C program for SWIG</a>
+<li><a href="SWIG.html#SWIG_nn47">The SWIG interface file</a>
+<li><a href="SWIG.html#SWIG_nn48">Why use separate interface files?</a>
+<li><a href="SWIG.html#SWIG_nn49">Getting the right header files</a>
+<li><a href="SWIG.html#SWIG_nn50">What to do with main()</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="SWIGPlus.html#SWIGPlus">6 SWIG and C++</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="SWIGPlus.html#SWIGPlus_nn2">Comments on C++ Wrapping</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn3">Approach</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn4">Supported C++ features</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn5">Command line options and compilation</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn38">Proxy classes</a>
+<ul>
+<li><a href="SWIGPlus.html#SWIGPlus_nn39">Construction of proxy classes</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn40">Resource management in proxies</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn41">Language specific details</a>
+</ul>
+<li><a href="SWIGPlus.html#SWIGPlus_nn6">Simple C++ wrapping</a>
+<ul>
+<li><a href="SWIGPlus.html#SWIGPlus_nn7">Constructors and destructors</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn8">Default constructors, copy constructors and implicit destructors</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn9">When constructor wrappers aren't created</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn10">Copy constructors</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn11">Member functions</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn12">Static members</a>
+<li><a href="SWIGPlus.html#SWIGPlus_member_data">Member data</a>
+</ul>
+<li><a href="SWIGPlus.html#SWIGPlus_default_args">Default arguments</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn15">Protection</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn16">Enums and constants</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn17">Friends</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn18">References and pointers</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn19">Pass and return by value</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn20">Inheritance</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn21">A brief discussion of multiple inheritance, pointers,  and type checking</a>
+<li><a href="SWIGPlus.html#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a>
+<ul>
+<li><a href="SWIGPlus.html#SWIGPlus_nn24">Dispatch function generation</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn25">Ambiguity in Overloading</a>
+<li><a href="SWIGPlus.html#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn27">Comments on overloading</a>
+</ul>
+<li><a href="SWIGPlus.html#SWIGPlus_nn28">Wrapping overloaded operators</a>
+<li><a href="SWIGPlus.html#SWIGPlus_class_extension">Class extension</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn30">Templates</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn31">Namespaces</a>
+<li><a href="SWIGPlus.html#SWIGPlus_renaming_templated_types_namespaces">Renaming templated types in namespaces</a>
+<li><a href="SWIGPlus.html#SWIGPlus_exception_specifications">Exception specifications</a>
+<li><a href="SWIGPlus.html#SWIGPlus_catches">Exception handling with %catches</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn33">Pointers to Members</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn34">Smart pointers and operator-&gt;()</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn35">Using declarations and inheritance</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nested_classes">Nested classes</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn37">A brief rant about const-correctness</a>
+<li><a href="SWIGPlus.html#SWIGPlus_nn42">Where to go for more information</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Preprocessor.html#Preprocessor">7 Preprocessing</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Preprocessor.html#Preprocessor_nn2">File inclusion</a>
+<li><a href="Preprocessor.html#Preprocessor_nn3">File imports</a>
+<li><a href="Preprocessor.html#Preprocessor_condition_compilation">Conditional Compilation</a>
+<li><a href="Preprocessor.html#Preprocessor_nn5">Macro Expansion</a>
+<li><a href="Preprocessor.html#Preprocessor_nn6">SWIG Macros</a>
+<li><a href="Preprocessor.html#Preprocessor_nn7">C99 and GNU Extensions</a>
+<li><a href="Preprocessor.html#Preprocessor_nn8">Preprocessing and %{ ... %} &amp; " ... " delimiters</a>
+<li><a href="Preprocessor.html#Preprocessor_nn9">Preprocessing and { ... } delimiters</a>
+<li><a href="Preprocessor.html#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</a>
+<li><a href="Preprocessor.html#Preprocessor_nn10">Viewing preprocessor output</a>
+<li><a href="Preprocessor.html#Preprocessor_warning_error">The #error and #warning directives</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Library.html#Library">8 SWIG library</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Library.html#Library_nn2">The %include directive and library search path</a>
+<li><a href="Library.html#Library_nn3">C Arrays and Pointers</a>
+<ul>
+<li><a href="Library.html#Library_nn4">cpointer.i</a>
+<li><a href="Library.html#Library_nn5">carrays.i</a>
+<li><a href="Library.html#Library_nn6">cmalloc.i</a>
+<li><a href="Library.html#Library_nn7">cdata.i</a>
+</ul>
+<li><a href="Library.html#Library_nn8">C String Handling</a>
+<ul>
+<li><a href="Library.html#Library_nn9">Default string handling</a>
+<li><a href="Library.html#Library_nn10">Passing binary data</a>
+<li><a href="Library.html#Library_nn11">Using %newobject to release memory</a>
+<li><a href="Library.html#Library_nn12">cstring.i</a>
+</ul>
+<li><a href="Library.html#Library_stl_cpp_library">STL/C++ Library</a>
+<ul>
+<li><a href="Library.html#Library_nn14">std_string.i</a>
+<li><a href="Library.html#Library_nn15">std_vector.i</a>
+<li><a href="Library.html#Library_stl_exceptions">STL exceptions</a>
+</ul>
+<li><a href="Library.html#Library_nn16">Utility Libraries</a>
+<ul>
+<li><a href="Library.html#Library_nn17">exception.i</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Arguments.html#Arguments">9 Argument Handling</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Arguments.html#Arguments_nn2">The typemaps.i library</a>
+<ul>
+<li><a href="Arguments.html#Arguments_nn3">Introduction</a>
+<li><a href="Arguments.html#Arguments_nn4">Input parameters</a>
+<li><a href="Arguments.html#Arguments_nn5">Output parameters</a>
+<li><a href="Arguments.html#Arguments_nn6">Input/Output parameters</a>
+<li><a href="Arguments.html#Arguments_nn7">Using different names</a>
+</ul>
+<li><a href="Arguments.html#Arguments_nn8">Applying constraints to input values</a>
+<ul>
+<li><a href="Arguments.html#Arguments_nn9">Simple constraint example</a>
+<li><a href="Arguments.html#Arguments_nn10">Constraint methods</a>
+<li><a href="Arguments.html#Arguments_nn11">Applying constraints to new datatypes</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Typemaps.html#Typemaps">10 Typemaps</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn2">Introduction</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn3">Type conversion</a>
+<li><a href="Typemaps.html#Typemaps_nn4">Typemaps</a>
+<li><a href="Typemaps.html#Typemaps_nn5">Pattern matching</a>
+<li><a href="Typemaps.html#Typemaps_nn6">Reusing typemaps</a>
+<li><a href="Typemaps.html#Typemaps_nn7">What can be done with typemaps?</a>
+<li><a href="Typemaps.html#Typemaps_nn8">What can't be done with typemaps?</a>
+<li><a href="Typemaps.html#Typemaps_nn9">The rest of this chapter</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_nn10">Typemap specifications</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn11">Defining a typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn12">Typemap scope</a>
+<li><a href="Typemaps.html#Typemaps_nn13">Copying a typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn14">Deleting a typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn15">Placement of typemaps</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_nn16">Pattern matching rules</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn17">Basic matching rules</a>
+<li><a href="Typemaps.html#Typemaps_nn18">Typedef reductions</a>
+<li><a href="Typemaps.html#Typemaps_nn19">Default typemaps</a>
+<li><a href="Typemaps.html#Typemaps_mixed_default">Mixed default typemaps</a>
+<li><a href="Typemaps.html#Typemaps_nn20">Multi-arguments typemaps</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_nn21">Code generation rules</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn22">Scope</a>
+<li><a href="Typemaps.html#Typemaps_nn23">Declaring new local variables</a>
+<li><a href="Typemaps.html#Typemaps_special_variables">Special variables</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_nn25">Common typemap methods</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn26">"in" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn27">"typecheck" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn28">"out" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn29">"arginit" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn30">"default" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn31">"check" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn32">"argout" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn33">"freearg" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn34">"newfree" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn35">"memberin" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn36">"varin" typemap</a>
+<li><a href="Typemaps.html#Typemaps_nn37">"varout" typemap</a>
+<li><a href="Typemaps.html#throws_typemap">"throws" typemap</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_nn39">Some typemap examples</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn40">Typemaps for arrays</a>
+<li><a href="Typemaps.html#Typemaps_nn41">Implementing constraints with typemaps</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_nn43">Typemaps for multiple languages</a>
+<li><a href="Typemaps.html#Typemaps_optimal">Optimal code generation when returning by value</a>
+<li><a href="Typemaps.html#Typemaps_nn42">Multi-argument typemaps</a>
+<li><a href="Typemaps.html#runtime_type_checker">The run-time type checker</a>
+<ul>
+<li><a href="Typemaps.html#Typemaps_nn45">Implementation</a>
+<li><a href="Typemaps.html#Typemaps_nn46">Usage</a>
+</ul>
+<li><a href="Typemaps.html#Typemaps_overloading">Typemaps and overloading</a>
+<li><a href="Typemaps.html#Typemaps_nn48">More about <tt>%apply</tt> and <tt>%clear</tt></a>
+<li><a href="Typemaps.html#Typemaps_nn49">Reducing wrapper code size</a>
+<li><a href="Typemaps.html#Typemaps_nn47">Passing data between typemaps</a>
+<li><a href="Typemaps.html#Typemaps_nn51">Where to go for more information?</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Customization.html#Customization">11 Customization Features</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Customization.html#exception">Exception handling with %exception</a>
+<ul>
+<li><a href="Customization.html#Customization_nn3">Handling exceptions in C code</a>
+<li><a href="Customization.html#Customization_nn4">Exception handling with longjmp()</a>
+<li><a href="Customization.html#Customization_nn5">Handling C++ exceptions</a>
+<li><a href="Customization.html#Customization_allowexcept">Exception handlers for variables</a>
+<li><a href="Customization.html#Customization_nn6">Defining different exception handlers</a>
+<li><a href="Customization.html#Customization_exception_special_variables">Special variables for %exception</a>
+<li><a href="Customization.html#Customization_nn7">Using The SWIG exception library</a>
+</ul>
+<li><a href="Customization.html#ownership">Object ownership and %newobject</a>
+<li><a href="Customization.html#features">Features and the %feature directive</a>
+<ul>
+<li><a href="Customization.html#Customization_feature_attributes">Feature attributes</a>
+<li><a href="Customization.html#Customization_feature_flags">Feature flags</a>
+<li><a href="Customization.html#Customization_clearing_features">Clearing features</a>
+<li><a href="Customization.html#Customization_features_default_args">Features and default arguments</a>
+<li><a href="Customization.html#features_example">Feature example</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Contract.html#Contract">12 Contracts</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Contract.html#Contract_nn2">The %contract directive</a>
+<li><a href="Contract.html#Contract_nn3">%contract and classes</a>
+<li><a href="Contract.html#Contract_nn4">Constant aggregation and %aggregate_check</a>
+<li><a href="Contract.html#Contract_nn5">Notes</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Varargs.html#Varargs">13 Variable Length Arguments</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Varargs.html#Varargs_nn2">Introduction</a>
+<li><a href="Varargs.html#Varargs_nn3">The Problem</a>
+<li><a href="Varargs.html#Varargs_nn4">Default varargs support</a>
+<li><a href="Varargs.html#Varargs_nn5">Argument replacement using %varargs</a>
+<li><a href="Varargs.html#Varargs_nn6">Varargs and typemaps</a>
+<li><a href="Varargs.html#Varargs_nn7">Varargs wrapping with libffi</a>
+<li><a href="Varargs.html#Varargs_nn8">Wrapping of va_list</a>
+<li><a href="Varargs.html#Varargs_nn9">C++ Issues</a>
+<li><a href="Varargs.html#Varargs_nn10">Discussion</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Warnings.html#Warnings">14 Warning Messages</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Warnings.html#Warnings_nn2">Introduction</a>
+<li><a href="Warnings.html#Warnings_suppression">Warning message suppression</a>
+<li><a href="Warnings.html#Warnings_nn4">Enabling extra warnings</a>
+<li><a href="Warnings.html#Warnings_nn5">Issuing a warning message</a>
+<li><a href="Warnings.html#Warnings_symbolic_symbols">Symbolic symbols</a>
+<li><a href="Warnings.html#Warnings_nn6">Commentary</a>
+<li><a href="Warnings.html#Warnings_nn7">Warnings as errors</a>
+<li><a href="Warnings.html#Warnings_nn8">Message output format</a>
+<li><a href="Warnings.html#Warnings_nn9">Warning number reference</a>
+<ul>
+<li><a href="Warnings.html#Warnings_nn10">Deprecated features (100-199)</a>
+<li><a href="Warnings.html#Warnings_nn11">Preprocessor (200-299)</a>
+<li><a href="Warnings.html#Warnings_nn12">C/C++ Parser (300-399)</a>
+<li><a href="Warnings.html#Warnings_nn13">Types and typemaps (400-499) </a>
+<li><a href="Warnings.html#Warnings_nn14">Code generation (500-599)</a>
+<li><a href="Warnings.html#Warnings_nn15">Language module specific (800-899) </a>
+<li><a href="Warnings.html#Warnings_nn16">User defined (900-999)</a>
+</ul>
+<li><a href="Warnings.html#Warnings_nn17">History</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Modules.html#Modules">15 Working with Modules</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Modules.html#Modules_nn1">Basics</a>
+<li><a href="Modules.html#Modules_nn2">The SWIG runtime code</a>
+<li><a href="Modules.html#external_run_time">External access to the runtime</a>
+<li><a href="Modules.html#Modules_nn4">A word of caution about static libraries</a>
+<li><a href="Modules.html#Modules_nn5">References</a>
+<li><a href="Modules.html#Modules_nn6">Reducing the wrapper file size</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Allegrocl.html#Allegrocl">16 SWIG and Allegro Common Lisp</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn2">Basics</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn3">Running Swig</a>
+<li><a href="Allegrocl.html#Allegrocl_nn4">Command Line Options</a>
+<li><a href="Allegrocl.html#Allegrocl_nn5">Inserting user code into generated files</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn6">Wrapping Overview</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn7">Function Wrapping</a>
+<li><a href="Allegrocl.html#Allegrocl_nn8">Foreign Wrappers</a>
+<li><a href="Allegrocl.html#Allegrocl_nn9">FFI Wrappers</a>
+<li><a href="Allegrocl.html#Allegrocl_nn10">Non-overloaded Defuns</a>
+<li><a href="Allegrocl.html#Allegrocl_nn11">Overloaded Defuns</a>
+<li><a href="Allegrocl.html#Allegrocl_nn12">What about constant and variable access?</a>
+<li><a href="Allegrocl.html#Allegrocl_nn13">Object Wrapping</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn14">Wrapping Details</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn15">Namespaces</a>
+<li><a href="Allegrocl.html#Allegrocl_nn16">Constants</a>
+<li><a href="Allegrocl.html#Allegrocl_nn17">Variables</a>
+<li><a href="Allegrocl.html#Allegrocl_nn18">Enumerations</a>
+<li><a href="Allegrocl.html#Allegrocl_nn19">Arrays</a>
+<li><a href="Allegrocl.html#Allegrocl_nn20">Classes and Structs and Unions (oh my!)</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn21">CLOS wrapping of</a>
+<li><a href="Allegrocl.html#Allegrocl_nn22">CLOS Inheritance</a>
+<li><a href="Allegrocl.html#Allegrocl_nn23">Member fields and functions</a>
+<li><a href="Allegrocl.html#Allegrocl_nn24">Why not directly access C++ classes using foreign types?</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn25">Templates</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn26">Generating wrapper code for templates</a>
+<li><a href="Allegrocl.html#Allegrocl_nn27">Implicit Template instantiation</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn28">Typedef, Templates, and Synonym Types</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn29">Choosing a primary type</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn30">Function overloading/Parameter defaulting</a>
+<li><a href="Allegrocl.html#Allegrocl_nn31">Operator wrapping and Operator overloading</a>
+<li><a href="Allegrocl.html#Allegrocl_nn32">Varargs</a>
+<li><a href="Allegrocl.html#Allegrocl_nn33">C++ Exceptions</a>
+<li><a href="Allegrocl.html#Allegrocl_nn34">Pass by value, pass by reference</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn35">Typemaps</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn36">Code Generation in the C++ Wrapper</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn37">IN Typemap</a>
+<li><a href="Allegrocl.html#Allegrocl_nn38">OUT Typemap</a>
+<li><a href="Allegrocl.html#Allegrocl_nn39">CTYPE Typemap</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn40">Code generation in Lisp wrappers</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn41">LIN Typemap</a>
+<li><a href="Allegrocl.html#Allegrocl_nn42">LOUT Typemap</a>
+<li><a href="Allegrocl.html#Allegrocl_nn43">FFITYPE Typemap</a>
+<li><a href="Allegrocl.html#Allegrocl_nn44">LISPTYPE Typemap</a>
+<li><a href="Allegrocl.html#Allegrocl_nn45">LISPCLASS Typemap</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn46">Modifying SWIG behavior using typemaps</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn47">Identifier Converter functions</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn48">Creating symbols in the lisp environment</a>
+<li><a href="Allegrocl.html#Allegrocl_nn49">Existing identifier-converter functions</a>
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn50">identifier-convert-null</a>
+<li><a href="Allegrocl.html#Allegrocl_nn51">identifier-convert-lispify</a>
+<li><a href="Allegrocl.html#Allegrocl_nn52">Default identifier to symbol conversions</a>
+</ul>
+<li><a href="Allegrocl.html#Allegrocl_nn53">Defining your own identifier-converter</a>
+<li><a href="Allegrocl.html#Allegrocl_nn54">Instructing SWIG to use a particular identifier-converter</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="CSharp.html#CSharp">17 SWIG and C#</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="CSharp.html#csharp_introduction">Introduction</a>
+<li><a href="CSharp.html#csharp_differences_java">Differences to the Java module</a>
+<li><a href="CSharp.html#csharp_exceptions">C# Exceptions</a>
+<ul>
+<li><a href="CSharp.html#csharp_exception_example_check_typemap">C# exception example using "check" typemap</a>
+<li><a href="CSharp.html#csharp_exception_example_percent_exception">C# exception example using %exception</a>
+<li><a href="CSharp.html#csharp_exception_example_exception_specifications">C# exception example using exception specifications</a>
+<li><a href="CSharp.html#csharp_custom_application_exception">Custom C# ApplicationException example</a>
+</ul>
+<li><a href="CSharp.html#csharp_directors">C# Directors</a>
+<ul>
+<li><a href="CSharp.html#csharp_directors_example">Directors example</a>
+<li><a href="CSharp.html#csharp_directors_implementation">Directors implementation</a>
+<li><a href="CSharp.html#csharp_director_caveats">Director caveats</a>
+</ul>
+<li><a href="CSharp.html#csharp_typemap_examples">C# Typemap examples</a>
+<ul>
+<li><a href="CSharp.html#csharp_memory_management_member_variables">Memory management when returning references to member variables</a>
+<li><a href="CSharp.html#csharp_memory_management_objects">Memory management for objects passed to the C++ layer</a>
+<li><a href="CSharp.html#csharp_date_marshalling">Date marshalling using the csin typemap and associated attributes</a>
+<li><a href="CSharp.html#csharp_date_properties">A date example demonstrating marshalling of C# properties</a>
+<li><a href="CSharp.html#csharp_partial_classes">Turning wrapped classes into partial classes</a>
+<li><a href="CSharp.html#csharp_extending_proxy_class">Extending proxy classes with additional C# code</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Chicken.html#Chicken">18 SWIG and Chicken</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Chicken.html#Chicken_nn2">Preliminaries</a>
+<ul>
+<li><a href="Chicken.html#Chicken_nn3">Running SWIG in C mode</a>
+<li><a href="Chicken.html#Chicken_nn4">Running SWIG in C++ mode</a>
+</ul>
+<li><a href="Chicken.html#Chicken_nn5">Code Generation</a>
+<ul>
+<li><a href="Chicken.html#Chicken_nn6">Naming Conventions</a>
+<li><a href="Chicken.html#Chicken_nn7">Modules</a>
+<li><a href="Chicken.html#Chicken_nn8">Constants and Variables</a>
+<li><a href="Chicken.html#Chicken_nn9">Functions</a>
+<li><a href="Chicken.html#Chicken_nn10">Exceptions</a>
+</ul>
+<li><a href="Chicken.html#Chicken_nn11">TinyCLOS</a>
+<li><a href="Chicken.html#Chicken_nn12">Linkage</a>
+<ul>
+<li><a href="Chicken.html#Chicken_nn13">Static binary or shared library linked at compile time</a>
+<li><a href="Chicken.html#Chicken_nn14">Building chicken extension libraries</a>
+<li><a href="Chicken.html#Chicken_nn15">Linking multiple SWIG modules with TinyCLOS</a>
+</ul>
+<li><a href="Chicken.html#Chicken_nn16">Typemaps</a>
+<li><a href="Chicken.html#Chicken_nn17">Pointers</a>
+<ul>
+<li><a href="Chicken.html#collection">Garbage collection</a>
+</ul>
+<li><a href="Chicken.html#Chicken_nn18">Unsupported features and known problems</a>
+<ul>
+<li><a href="Chicken.html#Chicken_nn19">TinyCLOS problems with Chicken version &lt;= 1.92</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Guile.html#Guile">19 SWIG and Guile</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Guile.html#Guile_nn2">Meaning of "Module"</a>
+<li><a href="Guile.html#Guile_nn3">Using the SCM or GH Guile API</a>
+<li><a href="Guile.html#Guile_nn4">Linkage</a>
+<ul>
+<li><a href="Guile.html#Guile_nn5">Simple Linkage</a>
+<li><a href="Guile.html#Guile_nn6">Passive Linkage</a>
+<li><a href="Guile.html#Guile_nn7">Native Guile Module Linkage</a>
+<li><a href="Guile.html#Guile_nn8">Old Auto-Loading Guile Module Linkage</a>
+<li><a href="Guile.html#Guile_nn9">Hobbit4D Linkage</a>
+</ul>
+<li><a href="Guile.html#Guile_nn10">Underscore Folding</a>
+<li><a href="Guile.html#Guile_nn11">Typemaps</a>
+<li><a href="Guile.html#Guile_nn12">Representation of pointers as smobs</a>
+<ul>
+<li><a href="Guile.html#Guile_nn13">GH Smobs</a>
+<li><a href="Guile.html#Guile_nn14">SCM Smobs</a>
+<li><a href="Guile.html#Guile_nn15">Garbage Collection</a>
+</ul>
+<li><a href="Guile.html#Guile_nn16">Exception Handling</a>
+<li><a href="Guile.html#Guile_nn17">Procedure documentation</a>
+<li><a href="Guile.html#Guile_nn18">Procedures with setters</a>
+<li><a href="Guile.html#Guile_nn19">GOOPS Proxy Classes</a>
+<ul>
+<li><a href="Guile.html#Guile_nn20">Naming Issues</a>
+<li><a href="Guile.html#Guile_nn21">Linking</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Java.html#Java">20 SWIG and Java</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Java.html#java_overview">Overview</a>
+<li><a href="Java.html#java_preliminaries">Preliminaries</a>
+<ul>
+<li><a href="Java.html#running_swig">Running SWIG</a>
+<li><a href="Java.html#java_commandline">Additional Commandline Options</a>
+<li><a href="Java.html#getting_right_headers">Getting the right header files</a>
+<li><a href="Java.html#compiling_dynamic">Compiling a dynamic module</a>
+<li><a href="Java.html#using_module">Using your module</a>
+<li><a href="Java.html#dynamic_linking_problems">Dynamic linking problems</a>
+<li><a href="Java.html#compilation_problems_cpp">Compilation problems and compiling with C++</a>
+<li><a href="Java.html#building_windows">Building on Windows</a>
+<ul>
+<li><a href="Java.html#visual_studio">Running SWIG from Visual Studio</a>
+<li><a href="Java.html#nmake">Using NMAKE</a>
+</ul>
+</ul>
+<li><a href="Java.html#java_basic_tour">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="Java.html#module_packages_classes">Modules, packages and generated Java classes</a>
+<li><a href="Java.html#functions">Functions</a>
+<li><a href="Java.html#global_variables">Global variables</a>
+<li><a href="Java.html#constants">Constants</a>
+<li><a href="Java.html#enumerations">Enumerations</a>
+<ul>
+<li><a href="Java.html#anonymous_enums">Anonymous enums</a>
+<li><a href="Java.html#typesafe_enums">Typesafe enums</a>
+<li><a href="Java.html#proper_enums">Proper Java enums</a>
+<li><a href="Java.html#typeunsafe_enums">Type unsafe enums</a>
+<li><a href="Java.html#simple_enums">Simple enums</a>
+</ul>
+<li><a href="Java.html#pointers">Pointers</a>
+<li><a href="Java.html#structures">Structures</a>
+<li><a href="Java.html#classes">C++ classes</a>
+<li><a href="Java.html#inheritance">C++ inheritance</a>
+<li><a href="Java.html#pointers_refs_arrays">Pointers, references, arrays and pass by value</a>
+<ul>
+<li><a href="Java.html#null_pointers">Null pointers</a>
+</ul>
+<li><a href="Java.html#overloaded_functions">C++ overloaded functions</a>
+<li><a href="Java.html#java_default_arguments">C++ default arguments</a>
+<li><a href="Java.html#namespaces">C++ namespaces</a>
+<li><a href="Java.html#templates">C++ templates</a>
+<li><a href="Java.html#smart_pointers">C++ Smart Pointers</a>
+</ul>
+<li><a href="Java.html#further_details">Further details on the generated Java classes</a>
+<ul>
+<li><a href="Java.html#imclass">The intermediary JNI class</a>
+<ul>
+<li><a href="Java.html#imclass_pragmas">The intermediary JNI class pragmas</a>
+</ul>
+<li><a href="Java.html#java_module_class">The Java module class</a>
+<ul>
+<li><a href="Java.html#module_class_pragmas">The Java module class pragmas</a>
+</ul>
+<li><a href="Java.html#java_proxy_classes">Java proxy classes</a>
+<ul>
+<li><a href="Java.html#memory_management">Memory management</a>
+<li><a href="Java.html#inheritance_mirroring">Inheritance</a>
+<li><a href="Java.html#proxy_classes_gc">Proxy classes and garbage collection</a>
+<li><a href="Java.html#java_pgcpp">The premature garbage collection prevention parameter for proxy class marshalling</a>
+<li><a href="Java.html#java_multithread_libraries">Single threaded applications and thread safety</a>
+</ul>
+<li><a href="Java.html#type_wrapper_classes">Type wrapper classes</a>
+<li><a href="Java.html#enum_classes">Enum classes</a>
+<ul>
+<li><a href="Java.html#typesafe_enums_classes">Typesafe enum classes</a>
+<li><a href="Java.html#proper_enums_classes">Proper Java enum classes</a>
+<li><a href="Java.html#typeunsafe_enums_classes">Type unsafe enum classes</a>
+</ul>
+</ul>
+<li><a href="Java.html#java_directors">Cross language polymorphism using directors</a>
+<ul>
+<li><a href="Java.html#java_enabling_directors">Enabling directors</a>
+<li><a href="Java.html#java_directors_classes">Director classes</a>
+<li><a href="Java.html#java_directors_overhead">Overhead and code bloat</a>
+<li><a href="Java.html#java_directors_example">Simple directors example</a>
+<li><a href="Java.html#java_directors_threading">Director threading issues</a>
+</ul>
+<li><a href="Java.html#java_allprotected">Accessing protected members</a>
+<li><a href="Java.html#common_customization">Common customization features</a>
+<ul>
+<li><a href="Java.html#helper_functions">C/C++ helper functions</a>
+<li><a href="Java.html#class_extension">Class extension with %extend</a>
+<li><a href="Java.html#exception_handling">Exception handling with %exception and %javaexception</a>
+<li><a href="Java.html#method_access">Method access with %javamethodmodifiers</a>
+</ul>
+<li><a href="Java.html#tips_techniques">Tips and techniques</a>
+<ul>
+<li><a href="Java.html#input_output_parameters">Input and output parameters using primitive pointers and references</a>
+<li><a href="Java.html#simple_pointers">Simple pointers</a>
+<li><a href="Java.html#c_arrays">Wrapping C arrays with Java arrays</a>
+<li><a href="Java.html#unbounded_c_arrays">Unbounded C Arrays</a>
+<li><a href="Java.html#java_heap_allocations">Overriding new and delete to allocate from Java heap</a>
+</ul>
+<li><a href="Java.html#java_typemaps">Java typemaps</a>
+<ul>
+<li><a href="Java.html#default_primitive_type_mappings">Default primitive type mappings</a>
+<li><a href="Java.html#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a>
+<li><a href="Java.html#jvm64">Sixty four bit JVMs</a>
+<li><a href="Java.html#what_is_typemap">What is a typemap?</a>
+<li><a href="Java.html#typemaps_c_to_java_types">Typemaps for mapping C/C++ types to Java types</a>
+<li><a href="Java.html#typemap_attributes">Java typemap attributes</a>
+<li><a href="Java.html#special_variables">Java special variables</a>
+<li><a href="Java.html#typemaps_for_c_and_cpp">Typemaps for both C and C++ compilation</a>
+<li><a href="Java.html#java_code_typemaps">Java code typemaps</a>
+<li><a href="Java.html#java_directors_typemaps">Director specific typemaps</a>
+</ul>
+<li><a href="Java.html#typemap_examples">Typemap Examples</a>
+<ul>
+<li><a href="Java.html#simpler_enum_classes">Simpler Java enums for enums without initializers</a>
+<li><a href="Java.html#exception_typemap">Handling C++ exception specifications as Java exceptions</a>
+<li><a href="Java.html#nan_exception_typemap">NaN Exception - exception handling for a particular type</a>
+<li><a href="Java.html#converting_java_string_arrays">Converting Java String arrays to char ** </a>
+<li><a href="Java.html#expanding_java_object">Expanding a Java object to multiple arguments</a>
+<li><a href="Java.html#using_typemaps_return_arguments">Using typemaps to return arguments</a>
+<li><a href="Java.html#adding_downcasts">Adding Java downcasts to polymorphic return types</a>
+<li><a href="Java.html#adding_equals_method">Adding an equals method to the Java classes</a>
+<li><a href="Java.html#void_pointers">Void pointers and a common Java base class</a>
+<li><a href="Java.html#struct_pointer_pointer">Struct pointer to pointer</a>
+<li><a href="Java.html#java_memory_management_member_variables">Memory management when returning references to member variables</a>
+<li><a href="Java.html#java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
+<li><a href="Java.html#java_date_marshalling">Date marshalling using the javain typemap and associated attributes</a>
+</ul>
+<li><a href="Java.html#java_directors_faq">Living with Java Directors</a>
+<li><a href="Java.html#odds_ends">Odds and ends</a>
+<ul>
+<li><a href="Java.html#javadoc_comments">JavaDoc comments</a>
+<li><a href="Java.html#functional_interface">Functional interface without proxy classes</a>
+<li><a href="Java.html#using_own_jni_functions">Using your own JNI functions</a>
+<li><a href="Java.html#performance">Performance concerns and hints</a>
+<li><a href="Java.html#java_debugging">Debugging</a>
+</ul>
+<li><a href="Java.html#java_examples">Examples</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Lisp.html#Lisp">21 SWIG and Common Lisp</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Lisp.html#Lisp_nn2">Allegro Common Lisp</a>
+<li><a href="Lisp.html#Lisp_nn3">Common Foreign Function Interface(CFFI)</a>
+<ul>
+<li><a href="Lisp.html#Lisp_nn4">Additional Commandline Options </a>
+<li><a href="Lisp.html#Lisp_nn5">Generating CFFI bindings</a>
+<li><a href="Lisp.html#Lisp_nn6">Generating CFFI bindings for C++ code</a>
+<li><a href="Lisp.html#Lisp_nn7">Inserting user code into generated files</a>
+</ul>
+<li><a href="Lisp.html#Lisp_nn8">CLISP</a>
+<ul>
+<li><a href="Lisp.html#Lisp_nn9">Additional Commandline Options </a>
+<li><a href="Lisp.html#Lisp_nn10">Details on CLISP bindings</a>
+</ul>
+<li><a href="Lisp.html#Lisp_nn11">UFFI </a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Lua.html#Lua">22 SWIG and Lua</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Lua.html#Lua_nn2">Preliminaries</a>
+<li><a href="Lua.html#Lua_nn3">Running SWIG</a>
+<ul>
+<li><a href="Lua.html#Lua_nn4">Compiling and Linking and Interpreter</a>
+<li><a href="Lua.html#Lua_nn5">Compiling a dynamic module</a>
+<li><a href="Lua.html#Lua_nn6">Using your module</a>
+</ul>
+<li><a href="Lua.html#Lua_nn7">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="Lua.html#Lua_nn8">Modules</a>
+<li><a href="Lua.html#Lua_nn9">Functions</a>
+<li><a href="Lua.html#Lua_nn10">Global variables</a>
+<li><a href="Lua.html#Lua_nn11">Constants and enums</a>
+<li><a href="Lua.html#Lua_nn12">Pointers</a>
+<li><a href="Lua.html#Lua_nn13">Structures</a>
+<li><a href="Lua.html#Lua_nn14">C++ classes</a>
+<li><a href="Lua.html#Lua_nn15">C++ inheritance</a>
+<li><a href="Lua.html#Lua_nn16">Pointers, references, values, and arrays</a>
+<li><a href="Lua.html#Lua_nn17">C++ overloaded functions</a>
+<li><a href="Lua.html#Lua_nn18">C++ operators</a>
+<li><a href="Lua.html#Lua_nn19">Class extension with %extend</a>
+<li><a href="Lua.html#Lua_nn20">C++ templates</a>
+<li><a href="Lua.html#Lua_nn21">C++ Smart Pointers</a>
+<li><a href="Lua.html#Lua_nn22">C++ Exceptions</a>
+<li><a href="Lua.html#Lua_nn23">Writing your own custom wrappers</a>
+<li><a href="Lua.html#Lua_nn24">Adding additional Lua code</a>
+</ul>
+<li><a href="Lua.html#Lua_nn25">Details on the Lua binding</a>
+<ul>
+<li><a href="Lua.html#Lua_nn26">Binding global data into the module.</a>
+<li><a href="Lua.html#Lua_nn27">Userdata and Metatables</a>
+<li><a href="Lua.html#Lua_nn28">Memory management</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Modula3.html#Modula3">23 SWIG and Modula-3</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Modula3.html#modula3_overview">Overview</a>
+<ul>
+<li><a href="Modula3.html#whyscripting">Why not scripting ?</a>
+<li><a href="Modula3.html#whymodula3">Why Modula-3 ?</a>
+<li><a href="Modula3.html#whycpp">Why C / C++ ?</a>
+<li><a href="Modula3.html#whyswig">Why SWIG ?</a>
+</ul>
+<li><a href="Modula3.html#conception">Conception</a>
+<ul>
+<li><a href="Modula3.html#cinterface">Interfaces to C libraries</a>
+<li><a href="Modula3.html#cppinterface">Interfaces to C++ libraries</a>
+</ul>
+<li><a href="Modula3.html#preliminaries">Preliminaries</a>
+<ul>
+<li><a href="Modula3.html#compilers">Compilers</a>
+<li><a href="Modula3.html#commandline">Additional Commandline Options</a>
+</ul>
+<li><a href="Modula3.html#modula3_typemaps">Modula-3 typemaps</a>
+<ul>
+<li><a href="Modula3.html#inoutparam">Inputs and outputs</a>
+<li><a href="Modula3.html#ordinals">Subranges, Enumerations, Sets</a>
+<li><a href="Modula3.html#class">Objects</a>
+<li><a href="Modula3.html#imports">Imports</a>
+<li><a href="Modula3.html#exceptions">Exceptions</a>
+<li><a href="Modula3.html#typemap_example">Example</a>
+</ul>
+<li><a href="Modula3.html#hints">More hints to the generator</a>
+<ul>
+<li><a href="Modula3.html#features">Features</a>
+<li><a href="Modula3.html#pragmas">Pragmas</a>
+</ul>
+<li><a href="Modula3.html#remarks">Remarks</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Mzscheme.html#Mzscheme">24 SWIG and MzScheme</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Mzscheme.html#MzScheme_nn2">Creating native MzScheme structures</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Ocaml.html#Ocaml">25 SWIG and Ocaml</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn2">Preliminaries</a>
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn3">Running SWIG</a>
+<li><a href="Ocaml.html#Ocaml_nn4">Compiling the code</a>
+<li><a href="Ocaml.html#Ocaml_nn5">The camlp4 module</a>
+<li><a href="Ocaml.html#Ocaml_nn6">Using your module</a>
+<li><a href="Ocaml.html#Ocaml_nn7">Compilation problems and compiling with C++</a>
+</ul>
+<li><a href="Ocaml.html#Ocaml_nn8">The low-level Ocaml/C interface</a>
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn9">The generated module</a>
+<li><a href="Ocaml.html#Ocaml_nn10">Enums</a>
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn11">Enum typing in Ocaml</a>
+</ul>
+<li><a href="Ocaml.html#Ocaml_nn12">Arrays</a>
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn13">Simple types of bounded arrays</a>
+<li><a href="Ocaml.html#Ocaml_nn14">Complex and unbounded arrays</a>
+<li><a href="Ocaml.html#Ocaml_nn15">Using an object</a>
+<li><a href="Ocaml.html#Ocaml_nn16">Example typemap for a function taking float * and int</a>
+</ul>
+<li><a href="Ocaml.html#Ocaml_nn17">C++ Classes</a>
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn18">STL vector and string Example</a>
+<li><a href="Ocaml.html#Ocaml_nn19">C++ Class Example</a>
+<li><a href="Ocaml.html#Ocaml_nn20">Compiling the example</a>
+<li><a href="Ocaml.html#Ocaml_nn21">Sample Session</a>
+</ul>
+<li><a href="Ocaml.html#Ocaml_nn22">Director Classes</a>
+<ul>
+<li><a href="Ocaml.html#Ocaml_nn23">Director Introduction</a>
+<li><a href="Ocaml.html#Ocaml_nn24">Overriding Methods in Ocaml</a>
+<li><a href="Ocaml.html#Ocaml_nn25">Director Usage Example</a>
+<li><a href="Ocaml.html#Ocaml_nn26">Creating director objects</a>
+<li><a href="Ocaml.html#Ocaml_nn27">Typemaps for directors, <tt>directorin, directorout, directorargout</tt></a>
+<li><a href="Ocaml.html#Ocaml_nn28"><tt>directorin</tt> typemap</a>
+<li><a href="Ocaml.html#Ocaml_nn29"><tt>directorout</tt> typemap</a>
+<li><a href="Ocaml.html#Ocaml_nn30"><tt>directorargout</tt> typemap</a>
+</ul>
+<li><a href="Ocaml.html#Ocaml_nn31">Exceptions</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Octave.html#Octave">26 SWIG and Octave</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Octave.html#Octave_nn2">Preliminaries</a>
+<li><a href="Octave.html#Octave_nn3">Running SWIG</a>
+<ul>
+<li><a href="Octave.html#Octave_nn5">Compiling a dynamic module</a>
+<li><a href="Octave.html#Octave_nn6">Using your module</a>
+</ul>
+<li><a href="Octave.html#Octave_nn7">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="Octave.html#Octave_nn8">Modules</a>
+<li><a href="Octave.html#Octave_nn9">Functions</a>
+<li><a href="Octave.html#Octave_nn10">Global variables</a>
+<li><a href="Octave.html#Octave_nn11">Constants and enums</a>
+<li><a href="Octave.html#Octave_nn12">Pointers</a>
+<li><a href="Octave.html#Octave_nn13">Structures and C++ classes</a>
+<li><a href="Octave.html#Octave_nn15">C++ inheritance</a>
+<li><a href="Octave.html#Octave_nn17">C++ overloaded functions</a>
+<li><a href="Octave.html#Octave_nn18">C++ operators</a>
+<li><a href="Octave.html#Octave_nn19">Class extension with %extend</a>
+<li><a href="Octave.html#Octave_nn20">C++ templates</a>
+<li><a href="Octave.html#Octave_nn21">C++ Smart Pointers</a>
+<li><a href="Octave.html#Octave_nn22">Directors (calling Octave from C++ code)</a>
+<li><a href="Octave.html#Octave_nn23">Threads</a>
+<li><a href="Octave.html#Octave_nn24">Memory management</a>
+<li><a href="Octave.html#Octave_nn25">STL support</a>
+<li><a href="Octave.html#Octave_nn26">Matrix typemaps</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Perl5.html#Perl5">27 SWIG and Perl5</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Perl5.html#Perl5_nn2">Overview</a>
+<li><a href="Perl5.html#Perl5_nn3">Preliminaries</a>
+<ul>
+<li><a href="Perl5.html#Perl5_nn4">Getting the right header files</a>
+<li><a href="Perl5.html#Perl5_nn5">Compiling a dynamic module</a>
+<li><a href="Perl5.html#Perl5_nn6">Building a dynamic module with MakeMaker</a>
+<li><a href="Perl5.html#Perl5_nn7">Building a static version of Perl</a>
+<li><a href="Perl5.html#Perl5_nn8">Using the module</a>
+<li><a href="Perl5.html#Perl5_nn9">Compilation problems and compiling with C++</a>
+<li><a href="Perl5.html#Perl5_nn10">Compiling for 64-bit platforms</a>
+</ul>
+<li><a href="Perl5.html#Perl5_nn11">Building Perl Extensions under Windows</a>
+<ul>
+<li><a href="Perl5.html#Perl5_nn12">Running SWIG from Developer Studio</a>
+<li><a href="Perl5.html#Perl5_nn13">Using other compilers</a>
+</ul>
+<li><a href="Perl5.html#Perl5_nn14">The low-level interface</a>
+<ul>
+<li><a href="Perl5.html#Perl5_nn15">Functions</a>
+<li><a href="Perl5.html#Perl5_nn16">Global variables</a>
+<li><a href="Perl5.html#Perl5_nn17">Constants</a>
+<li><a href="Perl5.html#Perl5_nn18">Pointers</a>
+<li><a href="Perl5.html#Perl5_nn19">Structures</a>
+<li><a href="Perl5.html#Perl5_nn20">C++ classes</a>
+<li><a href="Perl5.html#Perl5_nn21">C++ classes and type-checking</a>
+<li><a href="Perl5.html#Perl5_nn22">C++ overloaded functions</a>
+<li><a href="Perl5.html#Perl5_nn23">Operators</a>
+<li><a href="Perl5.html#Perl5_nn24">Modules and packages</a>
+</ul>
+<li><a href="Perl5.html#Perl5_nn25">Input and output parameters</a>
+<li><a href="Perl5.html#Perl5_nn26">Exception handling </a>
+<li><a href="Perl5.html#Perl5_nn27">Remapping datatypes with typemaps</a>
+<ul>
+<li><a href="Perl5.html#Perl5_nn28">A simple typemap example</a>
+<li><a href="Perl5.html#Perl5_nn29">Perl5 typemaps</a>
+<li><a href="Perl5.html#Perl5_nn30">Typemap variables</a>
+<li><a href="Perl5.html#Perl5_nn31">Useful functions</a>
+</ul>
+<li><a href="Perl5.html#Perl5_nn32">Typemap Examples</a>
+<ul>
+<li><a href="Perl5.html#Perl5_nn33">Converting a Perl5 array to a char ** </a>
+<li><a href="Perl5.html#Perl5_nn34">Return values </a>
+<li><a href="Perl5.html#Perl5_nn35">Returning values from arguments</a>
+<li><a href="Perl5.html#Perl5_nn36">Accessing array structure members</a>
+<li><a href="Perl5.html#Perl5_nn37">Turning Perl references into C pointers</a>
+<li><a href="Perl5.html#Perl5_nn38">Pointer handling</a>
+</ul>
+<li><a href="Perl5.html#Perl5_nn39">Proxy classes</a>
+<ul>
+<li><a href="Perl5.html#Perl5_nn40">Preliminaries</a>
+<li><a href="Perl5.html#Perl5_nn41">Structure and class wrappers</a>
+<li><a href="Perl5.html#Perl5_nn42">Object Ownership</a>
+<li><a href="Perl5.html#Perl5_nn43">Nested Objects</a>
+<li><a href="Perl5.html#Perl5_nn44">Proxy Functions</a>
+<li><a href="Perl5.html#Perl5_nn45">Inheritance</a>
+<li><a href="Perl5.html#Perl5_nn46">Modifying the proxy methods</a>
+</ul>
+<li><a href="Perl5.html#Perl5_nn47">Adding additional Perl code</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Php.html#Php">28 SWIG and PHP</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Php.html#Php_nn1">Generating PHP Extensions</a>
+<ul>
+<li><a href="Php.html#Php_nn1_1">Building a loadable extension</a>
+<li><a href="Php.html#Php_nn1_2">Building extensions into PHP</a>
+<li><a href="Php.html#Php_nn1_3">Using PHP Extensions</a>
+</ul>
+<li><a href="Php.html#Php_nn2">Basic PHP interface</a>
+<ul>
+<li><a href="Php.html#Php_nn2_1">Constants</a>
+<li><a href="Php.html#Php_nn2_2">Global Variables</a>
+<li><a href="Php.html#Php_nn2_3">Functions</a>
+<li><a href="Php.html#Php_nn2_4">Overloading</a>
+<li><a href="Php.html#Php_nn2_5">Pointers and References</a>
+<li><a href="Php.html#Php_nn2_6">Structures and C++ classes</a>
+<ul>
+<li><a href="Php.html#Php_nn2_6_1">Using <tt>-noproxy</tt></a>
+<li><a href="Php.html#Php_nn2_6_2">Constructors and Destructors</a>
+<li><a href="Php.html#Php_nn2_6_3">Static Member Variables</a>
+<li><a href="Php.html#Php_nn2_6_4">Static Member Functions</a>
+</ul>
+<li><a href="Php.html#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Pike.html#Pike">29 SWIG and Pike</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Pike.html#Pike_nn2">Preliminaries</a>
+<ul>
+<li><a href="Pike.html#Pike_nn3">Running SWIG</a>
+<li><a href="Pike.html#Pike_nn4">Getting the right header files</a>
+<li><a href="Pike.html#Pike_nn5">Using your module</a>
+</ul>
+<li><a href="Pike.html#Pike_nn6">Basic C/C++ Mapping</a>
+<ul>
+<li><a href="Pike.html#Pike_nn7">Modules</a>
+<li><a href="Pike.html#Pike_nn8">Functions</a>
+<li><a href="Pike.html#Pike_nn9">Global variables</a>
+<li><a href="Pike.html#Pike_nn10">Constants and enumerated types</a>
+<li><a href="Pike.html#Pike_nn11">Constructors and Destructors</a>
+<li><a href="Pike.html#Pike_nn12">Static Members</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Python.html#Python">30 SWIG and Python</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Python.html#Python_nn2">Overview</a>
+<li><a href="Python.html#Python_nn3">Preliminaries</a>
+<ul>
+<li><a href="Python.html#Python_nn4">Running SWIG</a>
+<li><a href="Python.html#Python_nn6">Using distutils</a>
+<li><a href="Python.html#Python_nn7">Hand compiling a dynamic module</a>
+<li><a href="Python.html#Python_nn8">Static linking</a>
+<li><a href="Python.html#Python_nn9">Using your module</a>
+<li><a href="Python.html#Python_nn10">Compilation of C++ extensions</a>
+<li><a href="Python.html#Python_nn11">Compiling for 64-bit platforms</a>
+<li><a href="Python.html#Python_nn12">Building Python Extensions under Windows</a>
+</ul>
+<li><a href="Python.html#Python_nn13">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="Python.html#Python_nn14">Modules</a>
+<li><a href="Python.html#Python_nn15">Functions</a>
+<li><a href="Python.html#Python_nn16">Global variables</a>
+<li><a href="Python.html#Python_nn17">Constants and enums</a>
+<li><a href="Python.html#Python_nn18">Pointers</a>
+<li><a href="Python.html#Python_nn19">Structures</a>
+<li><a href="Python.html#Python_nn20">C++ classes</a>
+<li><a href="Python.html#Python_nn21">C++ inheritance</a>
+<li><a href="Python.html#Python_nn22">Pointers, references, values, and arrays</a>
+<li><a href="Python.html#Python_nn23">C++ overloaded functions</a>
+<li><a href="Python.html#Python_nn24">C++ operators</a>
+<li><a href="Python.html#Python_nn25">C++ namespaces</a>
+<li><a href="Python.html#Python_nn26">C++ templates</a>
+<li><a href="Python.html#Python_nn27">C++ Smart Pointers</a>
+<li><a href="Python.html#Python_nn27a">C++ Reference Counted Objects (ref/unref)</a>
+</ul>
+<li><a href="Python.html#Python_nn28">Further details on the Python class interface</a>
+<ul>
+<li><a href="Python.html#Python_nn29">Proxy classes</a>
+<li><a href="Python.html#Python_nn30">Memory management</a>
+<li><a href="Python.html#Python_nn31">Python 2.2 and classic classes</a>
+</ul>
+<li><a href="Python.html#directors">Cross language polymorphism</a>
+<ul>
+<li><a href="Python.html#Python_nn33">Enabling directors</a>
+<li><a href="Python.html#Python_nn34">Director classes</a>
+<li><a href="Python.html#Python_nn35">Ownership and object destruction</a>
+<li><a href="Python.html#Python_nn36">Exception unrolling</a>
+<li><a href="Python.html#Python_nn37">Overhead and code bloat</a>
+<li><a href="Python.html#Python_nn38">Typemaps</a>
+<li><a href="Python.html#Python_nn39">Miscellaneous</a>
+</ul>
+<li><a href="Python.html#Python_nn40">Common customization features</a>
+<ul>
+<li><a href="Python.html#Python_nn41">C/C++ helper functions</a>
+<li><a href="Python.html#Python_nn42">Adding additional Python code</a>
+<li><a href="Python.html#Python_nn43">Class extension with %extend</a>
+<li><a href="Python.html#Python_nn44">Exception handling with %exception</a>
+</ul>
+<li><a href="Python.html#Python_nn45">Tips and techniques</a>
+<ul>
+<li><a href="Python.html#Python_nn46">Input and output parameters</a>
+<li><a href="Python.html#Python_nn47">Simple pointers</a>
+<li><a href="Python.html#Python_nn48">Unbounded C Arrays</a>
+<li><a href="Python.html#Python_nn49">String handling</a>
+<li><a href="Python.html#Python_nn50">Arrays</a>
+<li><a href="Python.html#Python_nn51">String arrays</a>
+<li><a href="Python.html#Python_nn52">STL wrappers</a>
+</ul>
+<li><a href="Python.html#Python_nn53">Typemaps</a>
+<ul>
+<li><a href="Python.html#Python_nn54">What is a typemap?</a>
+<li><a href="Python.html#Python_nn55">Python typemaps</a>
+<li><a href="Python.html#Python_nn56">Typemap variables</a>
+<li><a href="Python.html#Python_nn57">Useful Python Functions</a>
+</ul>
+<li><a href="Python.html#Python_nn58">Typemap Examples</a>
+<ul>
+<li><a href="Python.html#Python_nn59">Converting  Python list to a char ** </a>
+<li><a href="Python.html#Python_nn60">Expanding a Python object into multiple arguments</a>
+<li><a href="Python.html#Python_nn61">Using typemaps to return arguments</a>
+<li><a href="Python.html#Python_nn62">Mapping Python tuples into small arrays</a>
+<li><a href="Python.html#Python_nn63">Mapping sequences to C arrays</a>
+<li><a href="Python.html#Python_nn64">Pointer handling</a>
+</ul>
+<li><a href="Python.html#Python_nn65">Docstring Features</a>
+<ul>
+<li><a href="Python.html#Python_nn66">Module docstring</a>
+<li><a href="Python.html#Python_nn67">%feature("autodoc")</a>
+<ul>
+<li><a href="Python.html#Python_nn68">%feature("autodoc", "0")</a>
+<li><a href="Python.html#Python_nn69">%feature("autodoc", "1")</a>
+<li><a href="Python.html#Python_nn70">%feature("autodoc", "docstring")</a>
+</ul>
+<li><a href="Python.html#Python_nn71">%feature("docstring")</a>
+</ul>
+<li><a href="Python.html#Python_nn72">Python Packages</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Ruby.html#Ruby">31 SWIG and Ruby</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Ruby.html#Ruby_nn2">Preliminaries</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn3">Running SWIG</a>
+<li><a href="Ruby.html#Ruby_nn4">Getting the right header files</a>
+<li><a href="Ruby.html#Ruby_nn5">Compiling a dynamic module</a>
+<li><a href="Ruby.html#Ruby_nn6">Using your module</a>
+<li><a href="Ruby.html#Ruby_nn7">Static linking</a>
+<li><a href="Ruby.html#Ruby_nn8">Compilation of C++ extensions</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn10">Running SWIG from Developer Studio</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn11">The Ruby-to-C/C++ Mapping</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn12">Modules</a>
+<li><a href="Ruby.html#Ruby_nn13">Functions</a>
+<li><a href="Ruby.html#Ruby_nn14">Variable Linking</a>
+<li><a href="Ruby.html#Ruby_nn15">Constants</a>
+<li><a href="Ruby.html#Ruby_nn16">Pointers</a>
+<li><a href="Ruby.html#Ruby_nn17">Structures</a>
+<li><a href="Ruby.html#Ruby_nn18">C++ classes</a>
+<li><a href="Ruby.html#Ruby_nn19">C++ Inheritance</a>
+<li><a href="Ruby.html#Ruby_nn20">C++ Overloaded Functions</a>
+<li><a href="Ruby.html#Ruby_nn21">C++ Operators</a>
+<li><a href="Ruby.html#Ruby_nn22">C++ namespaces</a>
+<li><a href="Ruby.html#Ruby_nn23">C++ templates</a>
+<li><a href="Ruby.html#Ruby_nn23_1">C++ Standard Template Library (STL)</a>
+<li><a href="Ruby.html#C_STL_Functors">C++ STL Functors</a>
+<li><a href="Ruby.html#Ruby_C_Iterators">C++ STL Iterators</a>
+<li><a href="Ruby.html#Ruby_nn24">C++ Smart Pointers</a>
+<li><a href="Ruby.html#Ruby_nn25">Cross-Language Polymorphism</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn26">Exception Unrolling</a>
+</ul>
+</ul>
+<li><a href="Ruby.html#Ruby_nn27">Naming</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn28">Defining Aliases</a>
+<li><a href="Ruby.html#Ruby_nn29">Predicate Methods</a>
+<li><a href="Ruby.html#Ruby_nn30">Bang Methods</a>
+<li><a href="Ruby.html#Ruby_nn31">Getters and Setters</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn32">Input and output parameters</a>
+<li><a href="Ruby.html#Ruby_nn33">Exception handling </a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn34">Using the %exception directive </a>
+<li><a href="Ruby.html#Ruby_nn34_2">Handling Ruby Blocks </a>
+<li><a href="Ruby.html#Ruby_nn35">Raising exceptions </a>
+<li><a href="Ruby.html#Ruby_nn36">Exception classes </a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn37">Typemaps</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn38">What is a typemap?</a>
+<li><a href="Ruby.html#Ruby_Typemap_scope">Typemap scope</a>
+<li><a href="Ruby.html#Ruby_Copying_a_typemap">Copying a typemap</a>
+<li><a href="Ruby.html#Ruby_Deleting_a_typemap">Deleting a typemap</a>
+<li><a href="Ruby.html#Ruby_Placement_of_typemaps">Placement of typemaps</a>
+<li><a href="Ruby.html#Ruby_nn39">Ruby typemaps</a>
+<ul>
+<li><a href="Ruby.html#Ruby_in_typemap">&nbsp;"in" typemap</a>
+<li><a href="Ruby.html#Ruby_typecheck_typemap">"typecheck" typemap</a>
+<li><a href="Ruby.html#Ruby_out_typemap">&nbsp;"out" typemap</a>
+<li><a href="Ruby.html#Ruby_arginit_typemap">"arginit" typemap</a>
+<li><a href="Ruby.html#Ruby_default_typemap">"default" typemap</a>
+<li><a href="Ruby.html#Ruby_check_typemap">"check" typemap</a>
+<li><a href="Ruby.html#Ruby_argout_typemap_">"argout" typemap</a>
+<li><a href="Ruby.html#Ruby_freearg_typemap_">"freearg" typemap</a>
+<li><a href="Ruby.html#Ruby_newfree_typemap">"newfree" typemap</a>
+<li><a href="Ruby.html#Ruby_memberin_typemap">"memberin" typemap</a>
+<li><a href="Ruby.html#Ruby_varin_typemap">"varin" typemap</a>
+<li><a href="Ruby.html#Ruby_varout_typemap_">"varout" typemap</a>
+<li><a href="Ruby.html#Ruby_throws_typemap">"throws" typemap</a>
+<li><a href="Ruby.html#Ruby_directorin_typemap">directorin typemap</a>
+<li><a href="Ruby.html#Ruby_directorout_typemap">directorout typemap</a>
+<li><a href="Ruby.html#Ruby_directorargout_typemap">directorargout typemap</a>
+<li><a href="Ruby.html#Ruby_ret_typemap">ret typemap</a>
+<li><a href="Ruby.html#Ruby_globalin_typemap">globalin typemap</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn40">Typemap variables</a>
+<li><a href="Ruby.html#Ruby_nn41">Useful Functions</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn42">C Datatypes to Ruby Objects</a>
+<li><a href="Ruby.html#Ruby_nn43">Ruby Objects to C Datatypes</a>
+<li><a href="Ruby.html#Ruby_nn44">Macros for VALUE</a>
+<li><a href="Ruby.html#Ruby_nn45">Exceptions</a>
+<li><a href="Ruby.html#Ruby_nn46">Iterators</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn47">Typemap Examples</a>
+<li><a href="Ruby.html#Ruby_nn48">Converting a Ruby array to a char **</a>
+<li><a href="Ruby.html#Ruby_nn49">Collecting arguments in a hash</a>
+<li><a href="Ruby.html#Ruby_nn50">Pointer handling</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn51">Ruby Datatype Wrapping</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn52">Example: STL Vector to Ruby Array</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn65">Docstring Features</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn66">Module docstring</a>
+<li><a href="Ruby.html#Ruby_nn67">%feature("autodoc")</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn68">%feature("autodoc", "0")</a>
+<li><a href="Ruby.html#Ruby_autodoc1">%feature("autodoc", "1")</a>
+<li><a href="Ruby.html#Ruby_autodoc2">%feature("autodoc", "2")</a>
+<li><a href="Ruby.html#Ruby_feature_autodoc3">%feature("autodoc", "3")</a>
+<li><a href="Ruby.html#Ruby_nn70">%feature("autodoc", "docstring")</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn71">%feature("docstring")</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn53">Advanced Topics</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn54">Operator overloading</a>
+<li><a href="Ruby.html#Ruby_nn55">Creating Multi-Module Packages</a>
+<li><a href="Ruby.html#Ruby_nn56">Specifying Mixin Modules</a>
+</ul>
+<li><a href="Ruby.html#Ruby_nn57">Memory Management</a>
+<ul>
+<li><a href="Ruby.html#Ruby_nn58">Mark and Sweep Garbage Collector </a>
+<li><a href="Ruby.html#Ruby_nn59">Object Ownership</a>
+<li><a href="Ruby.html#Ruby_nn60">Object Tracking</a>
+<li><a href="Ruby.html#Ruby_nn61">Mark Functions</a>
+<li><a href="Ruby.html#Ruby_nn62">Free Functions</a>
+<li><a href="Ruby.html#Ruby_nn63">Embedded Ruby and the C++ Stack</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Tcl.html#Tcl">32 SWIG and Tcl</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Tcl.html#Tcl_nn2">Preliminaries</a>
+<ul>
+<li><a href="Tcl.html#Tcl_nn3">Getting the right header files</a>
+<li><a href="Tcl.html#Tcl_nn4">Compiling a dynamic module</a>
+<li><a href="Tcl.html#Tcl_nn5">Static linking</a>
+<li><a href="Tcl.html#Tcl_nn6">Using your module</a>
+<li><a href="Tcl.html#Tcl_nn7">Compilation of C++ extensions</a>
+<li><a href="Tcl.html#Tcl_nn8">Compiling for 64-bit platforms</a>
+<li><a href="Tcl.html#Tcl_nn9">Setting a package prefix</a>
+<li><a href="Tcl.html#Tcl_nn10">Using namespaces</a>
+</ul>
+<li><a href="Tcl.html#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</a>
+<ul>
+<li><a href="Tcl.html#Tcl_nn12">Running SWIG from Developer Studio</a>
+<li><a href="Tcl.html#Tcl_nn13">Using NMAKE</a>
+</ul>
+<li><a href="Tcl.html#Tcl_nn14">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="Tcl.html#Tcl_nn15">Modules</a>
+<li><a href="Tcl.html#Tcl_nn16">Functions</a>
+<li><a href="Tcl.html#Tcl_nn17">Global variables</a>
+<li><a href="Tcl.html#Tcl_nn18">Constants and enums</a>
+<li><a href="Tcl.html#Tcl_nn19">Pointers</a>
+<li><a href="Tcl.html#Tcl_nn20">Structures</a>
+<li><a href="Tcl.html#Tcl_nn21">C++ classes</a>
+<li><a href="Tcl.html#Tcl_nn22">C++ inheritance</a>
+<li><a href="Tcl.html#Tcl_nn23">Pointers, references, values, and arrays</a>
+<li><a href="Tcl.html#Tcl_nn24">C++ overloaded functions</a>
+<li><a href="Tcl.html#Tcl_nn25">C++ operators</a>
+<li><a href="Tcl.html#Tcl_nn26">C++ namespaces</a>
+<li><a href="Tcl.html#Tcl_nn27">C++ templates</a>
+<li><a href="Tcl.html#Tcl_nn28">C++ Smart Pointers</a>
+</ul>
+<li><a href="Tcl.html#Tcl_nn29">Further details on the Tcl class interface</a>
+<ul>
+<li><a href="Tcl.html#Tcl_nn30">Proxy classes</a>
+<li><a href="Tcl.html#Tcl_nn31">Memory management</a>
+</ul>
+<li><a href="Tcl.html#Tcl_nn32">Input and output parameters</a>
+<li><a href="Tcl.html#Tcl_nn33">Exception handling </a>
+<li><a href="Tcl.html#Tcl_nn34">Typemaps</a>
+<ul>
+<li><a href="Tcl.html#Tcl_nn35">What is a typemap?</a>
+<li><a href="Tcl.html#Tcl_nn36">Tcl typemaps</a>
+<li><a href="Tcl.html#Tcl_nn37">Typemap variables</a>
+<li><a href="Tcl.html#Tcl_nn38">Converting  a Tcl list to a char ** </a>
+<li><a href="Tcl.html#Tcl_nn39">Returning values in arguments</a>
+<li><a href="Tcl.html#Tcl_nn40">Useful functions</a>
+<li><a href="Tcl.html#Tcl_nn41">Standard  typemaps</a>
+<li><a href="Tcl.html#Tcl_nn42">Pointer handling</a>
+</ul>
+<li><a href="Tcl.html#Tcl_nn43">Turning a SWIG module into a Tcl Package.</a>
+<li><a href="Tcl.html#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</a>
+<ul>
+<li><a href="Tcl.html#Tcl_nn45">Proxy classes</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="R.html#R">33 SWIG and R</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="R.html#R_nn2">Bugs</a>
+<li><a href="R.html#R_nn3">Using R and SWIG</a>
+<li><a href="R.html#R_nn4">Precompiling large R files</a>
+<li><a href="R.html#R_nn5">General policy</a>
+<li><a href="R.html#R_language_conventions">Language conventions</a>
+<li><a href="R.html#R_nn6">C++ classes</a>
+<li><a href="R.html#R_nn7">Enumerations</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+<h3><a href="Extending.html#Extending">34 Extending SWIG to support new languages</a></h3>
+
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="Extending.html#Extending_nn2">Introduction</a>
+<li><a href="Extending.html#Extending_nn3">Prerequisites</a>
+<li><a href="Extending.html#Extending_nn4">The Big Picture</a>
+<li><a href="Extending.html#Extending_nn5">Execution Model</a>
+<ul>
+<li><a href="Extending.html#Extending_nn6">Preprocessing</a>
+<li><a href="Extending.html#Extending_nn7">Parsing</a>
+<li><a href="Extending.html#Extending_nn8">Parse Trees</a>
+<li><a href="Extending.html#Extending_nn9">Attribute namespaces</a>
+<li><a href="Extending.html#Extending_nn10">Symbol Tables</a>
+<li><a href="Extending.html#Extending_nn11">The %feature directive</a>
+<li><a href="Extending.html#Extending_nn12">Code Generation</a>
+<li><a href="Extending.html#Extending_nn13">SWIG and XML</a>
+</ul>
+<li><a href="Extending.html#Extending_nn14">Primitive Data Structures</a>
+<ul>
+<li><a href="Extending.html#Extending_nn15">Strings</a>
+<li><a href="Extending.html#Extending_nn16">Hashes</a>
+<li><a href="Extending.html#Extending_nn17">Lists</a>
+<li><a href="Extending.html#Extending_nn18">Common operations</a>
+<li><a href="Extending.html#Extending_nn19">Iterating over Lists and Hashes</a>
+<li><a href="Extending.html#Extending_nn20">I/O</a>
+</ul>
+<li><a href="Extending.html#Extending_nn21">Navigating and manipulating parse trees</a>
+<li><a href="Extending.html#Extending_nn22">Working with attributes</a>
+<li><a href="Extending.html#Extending_nn23">Type system</a>
+<ul>
+<li><a href="Extending.html#Extending_nn24">String encoding of types</a>
+<li><a href="Extending.html#Extending_nn25">Type construction</a>
+<li><a href="Extending.html#Extending_nn26">Type tests</a>
+<li><a href="Extending.html#Extending_nn27">Typedef and inheritance</a>
+<li><a href="Extending.html#Extending_nn28">Lvalues</a>
+<li><a href="Extending.html#Extending_nn29">Output functions</a>
+</ul>
+<li><a href="Extending.html#Extending_nn30">Parameters</a>
+<li><a href="Extending.html#Extending_nn31">Writing a Language Module</a>
+<ul>
+<li><a href="Extending.html#Extending_nn32">Execution model</a>
+<li><a href="Extending.html#Extending_nn33">Starting out</a>
+<li><a href="Extending.html#Extending_nn34">Command line options</a>
+<li><a href="Extending.html#Extending_nn35">Configuration and preprocessing</a>
+<li><a href="Extending.html#Extending_nn36">Entry point to code generation</a>
+<li><a href="Extending.html#Extending_nn37">Module I/O and wrapper skeleton</a>
+<li><a href="Extending.html#Extending_nn38">Low-level code generators</a>
+<li><a href="Extending.html#Extending_nn39">Configuration files</a>
+<li><a href="Extending.html#Extending_nn40">Runtime support</a>
+<li><a href="Extending.html#Extending_nn41">Standard library files</a>
+<li><a href="Extending.html#Extending_nn42">Examples and test cases</a>
+<li><a href="Extending.html#Extending_nn43">Documentation</a>
+<li><a href="Extending.html#Extending_prerequisites">Prerequisites for adding a new language module to the SWIG distribution</a>
+<li><a href="Extending.html#Extending_coding_style_guidelines">Coding style guidelines</a>
+</ul>
+<li><a href="Extending.html#Extending_nn44">Typemaps</a>
+<ul>
+<li><a href="Extending.html#Extending_nn45">Proxy classes</a>
+</ul>
+<li><a href="Extending.html#Extending_nn46">Guide to parse tree nodes</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+</BODY>
+</HTML>
+
diff --git a/trunk/Doc/Manual/Contract.html b/trunk/Doc/Manual/Contract.html
new file mode 100644
index 0000000..de390fb
--- /dev/null
+++ b/trunk/Doc/Manual/Contract.html
@@ -0,0 +1,274 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Contract Checking</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Contract"></a>12 Contracts</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Contract_nn2">The %contract directive</a>
+<li><a href="#Contract_nn3">%contract and classes</a>
+<li><a href="#Contract_nn4">Constant aggregation and %aggregate_check</a>
+<li><a href="#Contract_nn5">Notes</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+A common problem that arises when wrapping C libraries is that of maintaining
+reliability and checking for errors.  The fact of the matter is that many
+C programs are notorious for not providing error checks.  Not only that, 
+when you expose the internals of an application as a library, it
+often becomes possible to crash it simply by providing bad inputs or
+using it in a way that wasn't intended.
+</p>
+
+<p>
+This chapter describes SWIG's support for software contracts.  In the context
+of SWIG, a contract can be viewed as a runtime constraint that is attached
+to a declaration.  For example, you can easily attach argument checking rules,
+check the output values of a function and more. 
+When one of the rules is violated by a script, a runtime exception is 
+generated rather than having the program continue to execute.
+</p>
+
+<H2><a name="Contract_nn2"></a>12.1 The %contract directive</H2>
+
+
+<p>
+Contracts are added to a declaration using the %contract directive.  Here
+is a simple example:
+</p>
+
+<div class="code">
+<pre>
+%contract sqrt(double x) {
+require:
+    x &gt;= 0;
+ensure:
+    sqrt &gt;= 0;
+}
+
+...
+double sqrt(double);
+</pre>
+</div>
+
+<p>
+In this case, a contract is being added to the <tt>sqrt()</tt> function.
+The <tt>%contract</tt> directive must always appear before the declaration
+in question.  Within the contract there are two sections, both of which
+are optional.  The <tt>require:</tt>
+section specifies conditions that must hold before the function is called.  
+Typically, this is used to check argument values.   The <tt>ensure:</tt> section
+specifies conditions that must hold after the function is called.  This is
+often used to check return values or the state of the program.  In both
+cases, the conditions that must hold must be specified as boolean expressions.
+</p>
+
+<p>
+In the above example, we're simply making sure that sqrt() returns a non-negative
+number (if it didn't, then it would be broken in some way).
+</p>
+
+<p>
+Once a contract has been specified, it modifies the behavior of the
+resulting module.  For example:
+</p>
+
+<div class="shell">
+<pre>
+&gt;&gt;&gt; example.sqrt(2)
+1.4142135623730951
+&gt;&gt;&gt; example.sqrt(-2)
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+RuntimeError: Contract violation: require: (arg1&gt;=0)
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<H2><a name="Contract_nn3"></a>12.2 %contract and classes</H2>
+
+
+<p>
+The <tt>%contract</tt> directive can also be applied to class methods and constructors.  For example:
+</p>
+
+<div class="code">
+<pre>
+%contract Foo::bar(int x, int y) {
+require:
+   x &gt; 0;
+ensure:
+   bar &gt; 0;
+}
+
+%contract Foo::Foo(int a) {
+require:
+   a &gt; 0;
+}
+
+class Foo {
+public:
+    Foo(int);
+    int bar(int, int);
+};
+</pre>
+</div>
+
+<p>
+The way in which <tt>%contract</tt> is applied is exactly the same as the <tt>%feature</tt> directive. 
+Thus, any contract that you specified for a base class will also be attached to inherited methods.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Spam : public Foo {
+public:
+   int bar(int,int);    // Gets contract defined for Foo::bar(int,int)
+};
+</pre>
+</div>
+
+<p>
+In addition to this, separate contracts can be applied to both the base class and a derived class.  For example:
+</p>
+
+<div class="code">
+<pre>
+%contract Foo::bar(int x, int) {
+require:
+    x &gt; 0;
+}
+
+%contract Spam::bar(int, int y) {
+require:
+    y &gt; 0;
+}
+
+class Foo {
+public:
+    int bar(int,int);   // Gets Foo::bar contract.
+};
+
+class Spam : public Foo {
+public:
+     int bar(int,int);   // Gets Foo::bar and Spam::bar contract
+};
+</pre>
+</div>
+
+<p>
+When more than one contract is applied, the conditions specified in a
+"require:" section are combined together using a logical-AND operation.
+In other words conditions specified for the base class and conditions
+specified for the derived class all must hold.  In the above example,
+this means that both the arguments to <tt>Spam::bar</tt> must be positive.
+</p>
+
+<H2><a name="Contract_nn4"></a>12.3 Constant aggregation and %aggregate_check</H2>
+
+
+<p>
+Consider an interface file that contains the following code:
+</p>
+
+<div class="code">
+<pre>
+#define  UP     1
+#define  DOWN   2
+#define  RIGHT  3
+#define  LEFT   4
+
+void move(SomeObject *, int direction, int distance);
+</pre>
+</div>
+
+<p>
+One thing you might want to do is impose a constraint on the direction parameter to
+make sure it's one of a few accepted values.  To do that, SWIG provides an easy to
+use macro %aggregate_check() that works like this:
+</p>
+
+<div class="code">
+<pre>
+%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);
+</pre>
+</div>
+
+<p>
+This merely defines a utility function of the form
+</p>
+
+<div class="code">
+<pre>
+int check_direction(int x);
+</pre>
+</div>
+
+<p>
+That checks the argument x to see if it is one of the values listed.   This utility 
+function can be used in contracts.  For example:
+</p>
+
+<div class="code">
+<pre>
+%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
+
+%contract move(SomeObject *, int direction, in) {
+require:
+     check_direction(direction);
+}
+
+#define  UP     1
+#define  DOWN   2
+#define  RIGHT  3
+#define  LEFT   4
+
+void move(SomeObject *, int direction, int distance);
+</pre>
+</div>
+
+<p>
+Alternatively, it can be used in typemaps and other directives.  For example:
+</p>
+
+<div class="code">
+<pre>
+%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
+
+%typemap(check) int direction {
+    if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction");
+}
+
+#define  UP     1
+#define  DOWN   2
+#define  RIGHT  3
+#define  LEFT   4
+
+void move(SomeObject *, int direction, int distance);
+</pre>
+</div>
+
+<p>
+Regrettably, there is no automatic way to perform similar checks with enums values.  Maybe in a future
+release.
+</p>
+
+<H2><a name="Contract_nn5"></a>12.4 Notes</H2>
+
+
+<p>
+Contract support was implemented by Songyan (Tiger) Feng and first appeared
+in SWIG-1.3.20.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Customization.html b/trunk/Doc/Manual/Customization.html
new file mode 100644
index 0000000..e9d70e3
--- /dev/null
+++ b/trunk/Doc/Manual/Customization.html
@@ -0,0 +1,1133 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Customization Features</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Customization"></a>11 Customization Features</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#exception">Exception handling with %exception</a>
+<ul>
+<li><a href="#Customization_nn3">Handling exceptions in C code</a>
+<li><a href="#Customization_nn4">Exception handling with longjmp()</a>
+<li><a href="#Customization_nn5">Handling C++ exceptions</a>
+<li><a href="#Customization_allowexcept">Exception handlers for variables</a>
+<li><a href="#Customization_nn6">Defining different exception handlers</a>
+<li><a href="#Customization_exception_special_variables">Special variables for %exception</a>
+<li><a href="#Customization_nn7">Using The SWIG exception library</a>
+</ul>
+<li><a href="#ownership">Object ownership and %newobject</a>
+<li><a href="#features">Features and the %feature directive</a>
+<ul>
+<li><a href="#Customization_feature_attributes">Feature attributes</a>
+<li><a href="#Customization_feature_flags">Feature flags</a>
+<li><a href="#Customization_clearing_features">Clearing features</a>
+<li><a href="#Customization_features_default_args">Features and default arguments</a>
+<li><a href="#features_example">Feature example</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+In many cases, it is desirable to change the default wrapping of
+particular declarations in an interface.  For example, you might want
+to provide hooks for catching C++ exceptions, add assertions, or
+provide hints to the underlying code generator.  This chapter
+describes some of these customization techniques.  First, a discussion
+of exception handling is presented.  Then, a more general-purpose
+customization mechanism known as "features" is described.
+</p>
+
+<H2><a name="exception"></a>11.1 Exception handling with %exception</H2>
+
+
+<p>
+The <tt>%exception</tt> directive allows you to define a general purpose exception
+handler. For example, you can specify the following:
+</p>
+
+<div class="code"><pre>
+%exception {
+    try {
+        $action
+    }
+    catch (RangeError) {
+        PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
+        return NULL;
+    }
+}
+</pre></div>
+
+<p>
+When defined, the code enclosed in braces is inserted directly into the low-level wrapper
+functions.  The special variable <tt>$action</tt> is one of a few
+<a href="Customization.html#Customization_exception_special_variables">%exception special variable</a>
+supported and gets replaced with the actual operation
+to be performed (a function call, method invocation, attribute access, etc.).  An exception handler
+remains in effect until it is explicitly deleted.  This is done by using either <tt>%exception</tt> 
+or <tt>%noexception</tt> with no code. For example:
+</p>
+
+<div class="code"><pre>
+%exception;   // Deletes any previously defined handler
+</pre></div>
+
+<p>
+<b>Compatibility note:</b>  Previous versions of SWIG used a special directive <tt>%except</tt>
+for exception handling.   That directive is deprecated--<tt>%exception</tt>
+provides the same functionality, but is substantially more flexible.
+</p>
+
+<H3><a name="Customization_nn3"></a>11.1.1 Handling exceptions in C code</H3>
+
+
+<p>
+C has no formal exception handling mechanism so there are several approaches that might be
+used.  A somewhat common technique is to simply set a special error code.  For example:
+</p>
+
+<div class="code"><pre>
+/* File : except.c */
+
+static char error_message[256];
+static int error_status = 0;
+
+void throw_exception(char *msg) {
+	strncpy(error_message,msg,256);
+	error_status = 1;
+}
+
+void clear_exception() {
+	error_status = 0;
+}
+char *check_exception() {
+	if (error_status) return error_message;
+	else return NULL;
+}
+
+</pre></div>
+
+<p>
+To use these functions, functions simply call
+<tt>throw_exception()</tt> to indicate an error occurred. For example
+:</p>
+
+<div class="code"><pre>
+double inv(double x) {
+	if (x != 0) return 1.0/x;
+	else {
+		throw_exception("Division by zero");
+		return 0;
+	}
+}
+
+</pre></div>
+
+<p>
+To catch the exception, you can write a simple exception handler such
+as the following (shown for Perl5) :</p>
+
+<div class="code"><pre>
+%exception {
+    char *err;
+    clear_exception();
+    $action
+    if ((err = check_exception())) {
+       croak(err);
+    }
+}
+</pre></div>
+
+<p>
+In this case, when an error occurs, it is translated into a Perl error.
+Each target language has its own approach to creating a runtime error/exception in
+and for Perl it is the <tt>croak</tt> method shown above.
+</p>
+
+<H3><a name="Customization_nn4"></a>11.1.2 Exception handling with longjmp()</H3>
+
+
+<p>
+Exception handling can also be added to C code using the
+<tt>&lt;setjmp.h&gt;</tt> library.  Here is a minimalistic implementation that
+relies on the C preprocessor :
+</p>
+
+<div class="code"><pre>
+/* File : except.c
+   Just the declaration of a few global variables we're going to use */
+
+#include &lt;setjmp.h&gt;
+jmp_buf exception_buffer;
+int exception_status;
+
+/* File : except.h */
+#include &lt;setjmp.h&gt;
+extern jmp_buf exception_buffer;
+extern int exception_status;
+
+#define try if ((exception_status = setjmp(exception_buffer)) == 0)
+#define catch(val) else if (exception_status == val)
+#define throw(val) longjmp(exception_buffer,val)
+#define finally else
+
+/* Exception codes */
+
+#define RangeError     1
+#define DivisionByZero 2
+#define OutOfMemory    3
+
+</pre></div>
+
+<p>
+Now, within a C program, you can do the following :</p>
+
+<div class="code"><pre>
+double inv(double x) {
+	if (x) return 1.0/x;
+	else throw(DivisionByZero);
+}
+
+</pre></div>
+
+<p>
+Finally, to create a SWIG exception handler, write the following :</p>
+
+<div class="code"><pre>
+%{
+#include "except.h"
+%}
+
+%exception {
+	try {
+		$action
+	} catch(RangeError) {
+		croak("Range Error");
+	} catch(DivisionByZero) {
+		croak("Division by zero");
+	} catch(OutOfMemory) {
+		croak("Out of memory");
+	} finally {
+		croak("Unknown exception");
+	}
+}
+</pre></div>
+
+<p>
+Note: This implementation is only intended to illustrate the general idea.  To make it work better, you'll need to
+modify it to handle nested <tt>try</tt> declarations.
+</p>
+
+<H3><a name="Customization_nn5"></a>11.1.3 Handling C++ exceptions</H3>
+
+
+<p>
+Handling C++ exceptions is also straightforward.  For example: 
+</p>
+
+<div class="code"><pre>
+%exception {
+	try {
+		$action
+	} catch(RangeError) {
+		croak("Range Error");
+	} catch(DivisionByZero) {
+		croak("Division by zero");
+	} catch(OutOfMemory) {
+		croak("Out of memory");
+	} catch(...) {
+		croak("Unknown exception");
+	}
+}
+
+</pre></div>
+
+<p>
+The exception types need to be declared as classes elsewhere, possibly
+in a header file :</p>
+
+<div class="code"><pre>
+class RangeError {};
+class DivisionByZero {};
+class OutOfMemory {};
+</pre>
+</div>
+
+<H3><a name="Customization_allowexcept"></a>11.1.4 Exception handlers for variables</H3>
+
+
+<p>
+By default all variables will ignore <tt>%exception</tt>, so it is effectively turned off for all variables wrappers.
+This applies to global variables, member variables and static member variables.
+The approach is certainly a logical one when wrapping variables in C.
+However, in C++, it is quite possible for an exception to be thrown while the variable is being assigned.
+To ensure <tt>%exception</tt> is used when wrapping variables, it needs to be 'turned on' using the <tt>%allowexception</tt> feature.
+Note that <tt>%allowexception</tt> is just a macro for <tt>%feature("allowexcept")</tt>, that is, it is a feature called "allowexcept".
+Any variable which has this feature attached to it, will then use the <tt>%exception</tt> feature, but of course,
+only if there is a <tt>%exception</tt> attached to the variable in the first place.
+The <tt>%allowexception</tt> feature works like any other feature and so can be used globally or for selective variables.
+</p>
+
+<div class="code">
+<pre>
+%allowexception;                // turn on globally
+%allowexception Klass::MyVar;   // turn on for a specific variable
+
+%noallowexception Klass::MyVar; // turn off for a specific variable
+%noallowexception;              // turn off globally
+</pre>
+</div>
+
+<H3><a name="Customization_nn6"></a>11.1.5 Defining different exception handlers</H3>
+
+
+<p>
+By default, the <tt>%exception</tt> directive creates an exception
+handler that is used for all wrapper functions that follow it.  Unless
+there is a well-defined (and simple) error handling mechanism in place,
+defining one universal exception handler may be unwieldy and result
+in excessive code bloat since the handler is inlined into each wrapper function.
+</p>
+
+<p>
+To fix this, you can be more selective about how you use the
+<tt>%exception</tt> directive.  One approach is to only place it around
+critical pieces of code.  For example:
+</p>
+
+<div class="code"><pre>
+%exception {
+	... your exception handler ...
+}
+/* Define critical operations that can throw exceptions here */
+
+%exception;
+
+/* Define non-critical operations that don't throw exceptions */
+</pre></div>
+
+<p>
+More precise control over exception handling can be obtained by attaching an exception handler
+to specific declaration name. For example:
+</p>
+
+<div class="code">
+<pre>
+%exception allocate {
+    try {
+        $action
+    } 
+    catch (MemoryError) {
+        croak("Out of memory");
+    }
+}
+</pre>
+</div>
+
+<p>
+In this case, the exception handler is only attached to declarations
+named "allocate".  This would include both global and member
+functions.  The names supplied to <tt>%exception</tt> follow the same
+rules as for <tt>%rename</tt> described in the section on 
+<a href="SWIGPlus.html#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>.
+For example, if you wanted to define
+an exception handler for a specific class, you might write this:
+</p>
+
+<div class="code">
+<pre>
+%exception Object::allocate {
+    try {
+        $action
+    } 
+    catch (MemoryError) {
+        croak("Out of memory");
+    }
+}
+</pre>
+</div>
+
+<p>
+When a class prefix is supplied, the exception handler is applied to the corresponding declaration
+in the specified class as well as for identically named functions appearing in derived classes.  
+</p>
+
+<p>
+<tt>%exception</tt> can even be used to pinpoint a precise declaration when overloading is used. For example:
+</p>
+
+<div class="code">
+<pre>
+%exception Object::allocate(int) {
+    try {
+        $action
+    } 
+    catch (MemoryError) {
+        croak("Out of memory");
+    }
+}
+</pre>
+</div>
+
+<p>
+Attaching exceptions to specific declarations is a good way to reduce code bloat.  It can also be a useful way 
+to attach exceptions to specific parts of a header file. For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include "someheader.h"
+%}
+
+// Define a few exception handlers for specific declarations
+%exception Object::allocate(int) {
+    try {
+        $action
+    } 
+    catch (MemoryError) {
+        croak("Out of memory");
+    }
+}
+
+%exception Object::getitem {
+    try {
+       $action
+    }
+    catch (RangeError) {
+       croak("Index out of range");
+    }
+}
+...
+// Read a raw header file
+%include "someheader.h"
+</pre>
+</div>
+
+<p>
+<b>Compatibility note:</b> The <tt>%exception</tt> directive replaces
+the functionality provided by the deprecated "except" typemap.
+The typemap would allow exceptions to be thrown in the target 
+language based on the return type of a function and 
+was intended to be a mechanism for pinpointing specific
+declarations.  However, it never really worked that well and the new
+%exception directive is much better.
+</p>
+
+<H3><a name="Customization_exception_special_variables"></a>11.1.6 Special variables for %exception</H3>
+
+
+<p>
+The %exception directive supports a few special variables which are placeholders for
+code substitution.
+The following table shows the available special variables and details what the special
+variables are replaced with.
+</p>
+
+<table summary="Special variables for %exception">
+
+<tr>
+<td>$action</td>
+<td>The actual operation to be performed (a function call, method invocation, variable access, etc.)</td>
+</tr>
+
+<tr>
+<td>$symname</td>
+<td>The symbol name used internally by SWIG</td>
+</tr>
+
+<tr>
+<td>$overname</td>
+<td>The extra mangling used in the symbol name for overloaded method. Expands to nothing if the wrapped method is not overloaded.</td>
+</tr>
+
+<tr>
+<td>$wrapname</td>
+<td>The language specific wrapper name (usually a C function name exported from the shared object/dll)</td>
+</tr>
+
+<tr>
+<td>$decl</td>
+<td>The fully qualified C/C++ declaration of the method being wrapped without the return type</td>
+</tr>
+
+<tr>
+<td>$fulldecl</td>
+<td>The fully qualified C/C++ declaration of the method being wrapped including the return type</td>
+</tr>
+
+</table>
+
+<p>
+The special variables are often used in situations where method calls are logged. Exactly which form of the method call needs logging is up to individual requirements, but the example code below shows all the possible expansions, plus how an exception message could be tailored to show the C++ method declaration:
+</p>
+
+<div class="code"><pre>
+%exception Special::something {
+  log("symname: $symname");
+  log("overname: $overname");
+  log("wrapname: $wrapname");
+  log("decl: $decl");
+  log("fulldecl: $fulldecl");
+  try {
+    $action
+  } 
+  catch (MemoryError) {
+      croak("Out of memory in $decl");
+  }
+}
+void log(const char *message);
+struct Special {
+  void something(const char *c);
+  void something(int i);
+};
+</pre></div>
+
+<p>
+Below shows the expansions for the 1st of the overloaded <tt>something</tt> wrapper methods for Perl:
+</p>
+
+<div class="code"><pre>
+  log("symname: Special_something");
+  log("overname: __SWIG_0");
+  log("wrapname: _wrap_Special_something__SWIG_0");
+  log("decl: Special::something(char const *)");
+  log("fulldecl: void Special::something(char const *)");
+  try {
+    (arg1)-&gt;something((char const *)arg2);
+  } 
+  catch (MemoryError) {
+    croak("Out of memory in Special::something(char const *)");
+  }
+</pre></div>
+
+
+<H3><a name="Customization_nn7"></a>11.1.7 Using The SWIG exception library</H3>
+
+
+<p>
+The <tt>exception.i</tt> library file provides support for creating
+language independent exceptions in your interfaces.  To use it, simply
+put an "<tt>%include exception.i</tt>" in your interface file.  This
+creates a function<tt> SWIG_exception()</tt> that can be used to raise
+common scripting language exceptions in a portable manner.  For example :</p>
+
+<div class="code"><pre>
+// Language independent exception handler
+%include exception.i       
+
+%exception {
+    try {
+        $action
+    } catch(RangeError) {
+        SWIG_exception(SWIG_ValueError, "Range Error");
+    } catch(DivisionByZero) {
+        SWIG_exception(SWIG_DivisionByZero, "Division by zero");
+    } catch(OutOfMemory) {
+        SWIG_exception(SWIG_MemoryError, "Out of memory");
+    } catch(...) {
+        SWIG_exception(SWIG_RuntimeError,"Unknown exception");
+    }
+}
+
+</pre></div>
+
+<p>
+As arguments, <tt>SWIG_exception()</tt> takes an error type code (an
+integer) and an error message string.  The currently supported error
+types are :</p>
+
+<div class="diagram"><pre>
+SWIG_UnknownError
+SWIG_IOError
+SWIG_RuntimeError
+SWIG_IndexError
+SWIG_TypeError
+SWIG_DivisionByZero
+SWIG_OverflowError
+SWIG_SyntaxError
+SWIG_ValueError
+SWIG_SystemError
+SWIG_AttributeError
+SWIG_MemoryError
+SWIG_NullReferenceError
+</pre></div>
+
+<p>
+Since the <tt>SWIG_exception()</tt> function is defined at the C-level
+it can be used elsewhere in SWIG. This includes typemaps and helper
+functions.  
+</p>
+
+<H2><a name="ownership"></a>11.2 Object ownership and %newobject</H2>
+
+
+<p>
+A common problem in some applications is managing proper ownership of objects.  For
+example, consider a function like this:
+</p>
+
+<div class="code">
+<pre>
+Foo *blah() {
+   Foo *f = new Foo();
+   return f;
+}
+</pre>
+</div>
+
+<p>
+If you wrap the function <tt>blah()</tt>, SWIG has no idea that the
+return value is a newly allocated object.  As a result, the resulting
+extension module may produce a memory leak (SWIG is conservative and
+will never delete objects unless it knows for certain that the
+returned object was newly created).
+</p>
+
+<p>
+To fix this, you can provide an extra hint to the code generator using
+the <tt>%newobject</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%newobject blah;
+Foo *blah();
+</pre>
+</div>
+
+<p>
+<tt>%newobject</tt> works exactly like <tt>%rename</tt> and <tt>%exception</tt>.  In other words,
+you can attach it to class members and parameterized declarations as before.  For example:
+</p>
+
+<div class="code">
+<pre>
+%newobject ::blah();                   // Only applies to global blah
+%newobject Object::blah(int,double);   // Only blah(int,double) in Object
+%newobject *::copy;                    // Copy method in all classes
+...
+</pre>
+</div>
+
+<p>
+When <tt>%newobject</tt> is supplied, many language modules will
+arrange to take ownership of the return value.  This allows the value
+to be automatically garbage-collected when it is no longer in use.  However,
+this depends entirely on the target language (a language module may also choose to ignore
+the <tt>%newobject</tt> directive).
+</p>
+
+<p>
+Closely related to <tt>%newobject</tt> is a special typemap.  The "newfree" typemap
+can be used to deallocate a newly allocated return value.  It is only available on
+methods for which <tt>%newobject</tt> has been applied and is commonly used to clean-up string
+results.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(newfree) char * "free($1);";
+...
+%newobject strdup;
+...
+char *strdup(const char *s);
+</pre>
+</div>
+
+<p>
+In this case, the result of the function is a string in the target language.  Since this string
+is a copy of the original result, the data returned by <tt>strdup()</tt> is no longer needed.  
+The "newfree" typemap in the example simply releases this memory.
+</p>
+
+<p>
+As a complement to the <tt>%newobject</tt>, from SWIG 1.3.28, you can
+use the <tt>%delobject</tt> directive. For example, if you have two
+methods, one to create objects and one to destroy them, you can use:
+</p>
+
+<div class="code">
+<pre>
+%newobject create_foo;
+%delobject destroy_foo;
+...
+Foo *create_foo();
+void destroy_foo(Foo *foo);
+</pre>
+</div>
+
+<p> or in a member method as: </p>
+<div class="code">
+<pre>
+%delobject Foo::destroy;
+
+class Foo {
+public:
+  void destroy() { delete this;}
+
+private:
+  ~Foo();
+};
+</pre>
+</div>
+
+<p>
+<tt>%delobject</tt> instructs SWIG that the first argument passed to
+the method will be destroyed, and therefore, the target language
+should not attempt to deallocate it twice. This is similar to use the
+DISOWN typemap in the first method argument, and in fact, it also
+depends on the target language on implementing the 'disown' mechanism
+properly.
+</p>
+
+<p>
+<b>Compatibility note:</b>  Previous versions of SWIG had a special <tt>%new</tt> directive.  However, unlike <tt>%newobject</tt>,
+it only applied to the next declaration.  For example:
+</p>
+
+<div class="code">
+<pre>
+%new char *strdup(const char *s);
+</pre>
+</div>
+
+<p>
+For now this is still supported but is deprecated.  
+</p>
+
+<p>
+<b>How to shoot yourself in the foot:</b>  The <tt>%newobject</tt> directive is not a declaration modifier like the old
+<tt>%new</tt> directive.   Don't write code like this:
+</p>
+
+<div class="code">
+<pre>
+%newobject
+char *strdup(const char *s);
+</pre>
+</div>
+<p>
+The results might not be what you expect.
+</p>
+
+<H2><a name="features"></a>11.3 Features and the %feature directive</H2>
+
+
+<p>
+Both <tt>%exception</tt> and <tt>%newobject</tt> are examples of a
+more general purpose customization mechanism known as "features."  A
+feature is simply a user-definable property that is attached to
+specific declarations.  Features are attached
+using the <tt>%feature</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") Object::allocate {
+    try {
+        $action
+    } 
+    catch (MemoryError) {
+        croak("Out of memory");
+    }
+}
+
+%feature("new","1") *::copy;
+</pre>
+</div>
+
+<p>
+In fact, the <tt>%exception</tt> and <tt>%newobject</tt> directives are really nothing more than macros 
+involving <tt>%feature</tt>:
+</p>
+
+<div class="code">
+<pre>
+#define %exception %feature("except")
+#define %newobject %feature("new","1")
+</pre>
+</div>
+
+<p>
+The name matching rules outlined in the <a href="SWIGPlus.html#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
+section applies to all <tt>%feature</tt> directives.
+In fact the the <tt>%rename</tt> directive is just a special form of <tt>%feature</tt>. 
+The matching rules mean that features are very flexible and can be applied with
+pinpoint accuracy to specific declarations if needed.
+Additionally, if no declaration name is given, a global feature is said to be defined.
+This feature is then
+attached to <em>every</em> declaration that follows.  This is how global exception handlers
+are defined.  For example:
+</p>
+
+<div class="code">
+<pre>
+/* Define a global exception handler */
+%feature("except") {
+   try {
+     $action
+   }
+   ...
+}
+
+... bunch of declarations ...
+</pre>
+</div>
+
+<p>
+The <tt>%feature</tt> directive can be used with different syntax.
+The following are all equivalent:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") Object::method { $action };
+%feature("except") Object::method %{ $action %};
+%feature("except") Object::method " $action ";
+%feature("except","$action") Object::method;
+</pre>
+</div>
+
+<p>
+The syntax in the first variation will generate the <tt>{ }</tt> delimiters used whereas the other variations will not.
+</p>
+
+<H3><a name="Customization_feature_attributes"></a>11.3.1 Feature attributes</H3>
+
+
+<p>
+The <tt>%feature</tt> directive also accepts XML style attributes in the same way that typemaps do.
+Any number of attributes can be specified.
+The following is the generic syntax for features:
+</p>
+
+<div class="code">
+<pre>
+%feature("name","value", attribute1="AttributeValue1") symbol;
+%feature("name", attribute1="AttributeValue1") symbol {value};
+%feature("name", attribute1="AttributeValue1") symbol %{value%};
+%feature("name", attribute1="AttributeValue1") symbol "value";
+</pre>
+</div>
+
+<p>
+More than one attribute can be specified using a comma separated list. 
+The Java module is an example that uses attributes in <tt>%feature("except")</tt>.
+The <tt>throws</tt> attribute specifies the name of a Java class to add to a proxy method's throws clause.
+In the following example, <tt>MyExceptionClass</tt> is the name of the Java class for adding to the throws clause.
+</p>
+
+<div class="code">
+<pre>
+%feature("except", throws="MyExceptionClass") Object::method { 
+   try {
+     $action
+   } catch (...) {
+     ... code to throw a MyExceptionClass Java exception ...
+   }
+};
+</pre>
+</div>
+
+<p>
+Further details can be obtained from the <a href="Java.html#exception_handling">Java exception handling</a> section.
+</p>
+
+<H3><a name="Customization_feature_flags"></a>11.3.2 Feature flags</H3>
+
+
+<p>
+Feature flags are used to enable or disable a particular feature. Feature flags are a common but simple usage of <tt>%feature</tt>
+and the feature value should be either <tt>1</tt> to enable or <tt>0</tt> to disable the feature. 
+</p>
+
+<div class="code">
+<pre>
+%feature("featurename")          // enables feature
+%feature("featurename", "1")     // enables feature
+%feature("featurename", "x")     // enables feature
+%feature("featurename", "0")     // disables feature
+%feature("featurename", "")      // clears feature
+</pre>
+</div>
+
+<p>
+Actually any value other than zero will enable the feature.
+Note that if the value is omitted completely, the default value becomes <tt>1</tt>, thereby enabling the feature.
+A feature is cleared by specifying no value, see <a href="#Customization_clearing_features">Clearing features</a>.
+The <tt>%immutable</tt> directive described in the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section,
+is just a macro for <tt>%feature("immutable")</tt>, and can be used to demonstrates feature flags:
+</p>
+
+<div class="code">
+<pre>
+                                // features are disabled by default
+int red;                        // mutable
+
+%feature("immutable");          // global enable
+int orange;                     // immutable
+
+%feature("immutable","0");      // global disable
+int yellow;                     // mutable
+
+%feature("immutable","1");      // another form of global enable
+int green;                      // immutable
+
+%feature("immutable","");       // clears the global feature
+int blue;                       // mutable
+</pre>
+</div>
+
+<p>
+Note that features are disabled by default and must be explicitly enabled either globally or by specifying a targeted declaration.
+The above intersperses SWIG directives with C code. Of course you can target features explicitly, so the above could also be rewritten as:
+</p>
+
+<div class="code">
+<pre>
+%feature("immutable","1") orange;
+%feature("immutable","1") green;
+int red;                        // mutable
+int orange;                     // immutable
+int yellow;                     // mutable
+int green;                      // immutable
+int blue;                       // mutable
+</pre>
+</div>
+
+<p>
+The above approach allows for the C declarations to be separated from the SWIG directives for when the C declarations are parsed from a C header file.
+The logic above can of course be inverted and rewritten as:
+</p>
+
+<div class="code">
+<pre>
+%feature("immutable","1");
+%feature("immutable","0") red;
+%feature("immutable","0") yellow;
+%feature("immutable","0") blue;
+int red;                        // mutable
+int orange;                     // immutable
+int yellow;                     // mutable
+int green;                      // immutable
+int blue;                       // mutable
+</pre>
+</div>
+
+<p>
+As hinted above for <tt>%immutable</tt>, most feature flags can also be specified via alternative syntax. The alternative syntax is just a macro
+in the <tt>swig.swg</tt> Library file. The following shows the alternative syntax for the imaginary <tt>featurename</tt> feature:
+</p>
+
+<div class="code">
+<pre>
+%featurename       // equivalent to %feature("featurename", "1") ie enables feature
+%nofeaturename     // equivalent to %feature("featurename", "0") ie disables feature
+%clearfeaturename  // equivalent to %feature("featurename", "")  ie clears feature
+</pre>
+</div>
+
+<p>
+The concept of clearing features is discussed next.
+</p>
+
+<H3><a name="Customization_clearing_features"></a>11.3.3 Clearing features</H3>
+
+
+<p>
+A feature stays in effect until it is explicitly cleared.  A feature is cleared by
+supplying a <tt>%feature</tt> directive with no value.  For example <tt>%feature("name","")</tt>.
+A cleared feature means that any feature exactly matching any previously defined feature is no longer used in the name matching rules.
+So if a feature is cleared, it might mean that another name matching rule will apply.
+To clarify, let's consider the <tt>except</tt> feature again (<tt>%exception</tt>):
+</p>
+
+<div class="code">
+<pre>
+// Define global exception handler
+%feature("except") {
+    try {
+        $action
+    } catch (...) {
+        croak("Unknown C++ exception");
+    }
+}
+
+// Define exception handler for all clone methods to log the method calls
+%feature("except") *::clone() {
+    try {
+        logger.info("$action");
+        $action
+    } catch (...) {
+        croak("Unknown C++ exception");
+    }
+}
+
+... initial set of class declarations with clone methods ...
+
+// clear the previously defined feature
+%feature("except","") *::clone();
+
+... final set of class declarations with clone methods ...
+</pre>
+</div>
+
+<p>
+In the above scenario, the initial set of clone methods will log all method invocations from the target language.
+This specific feature is cleared for the final set of clone methods.
+However, these clone methods will still have an exception handler (without logging) as the next best feature match for them is the global exception handler.
+</p>
+
+<p>
+Note that clearing a feature is not always the same as disabling it.
+Clearing the feature above with <tt>%feature("except","") *::clone()</tt> is not the same as specifying
+<tt>%feature("except","0") *::clone()</tt>. The former will disable the feature for clone methods -
+the feature is still a better match than the global feature.
+If on the other hand, no global exception handler had been defined at all,
+then clearing the feature would be the same as disabling it as no other feature would have matched.
+</p>
+
+<p>
+Note that the feature must match exactly for it to be cleared by any previously defined feature.
+For example the following attempt to clear the initial feature will not work:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") clone() { logger.info("$action"); $action }
+%feature("except","") *::clone();
+</pre>
+</div>
+
+<p>
+but this will:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") clone() { logger.info("$action"); $action }
+%feature("except","") clone();
+</pre>
+</div>
+
+<H3><a name="Customization_features_default_args"></a>11.3.4 Features and default arguments</H3>
+
+
+<p>
+SWIG treats methods with default arguments as separate overloaded methods as detailed
+in the <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a> section.
+Any <tt>%feature</tt> targeting a method with default arguments
+will apply to all the extra overloaded methods that SWIG generates if the
+default arguments are specified in the feature. If the default arguments are
+not specified in the feature, then the feature will match that exact
+wrapper method only and not the extra overloaded methods that SWIG generates.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") void hello(int i=0, double d=0.0) { ... }
+void hello(int i=0, double d=0.0);
+</pre>
+</div>
+
+<p>
+will apply the feature to all three wrapper methods, that is:
+</p>
+
+<div class="code">
+<pre>
+void hello(int i, double d);
+void hello(int i);
+void hello();
+</pre>
+</div>
+
+<p>
+If the default arguments are not specified in the feature:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") void hello(int i, double d) { ... }
+void hello(int i=0, double d=0.0);
+</pre>
+</div>
+
+<p>
+then the feature will only apply to this wrapper method:
+</p>
+
+<div class="code">
+<pre>
+void hello(int i, double d);
+</pre>
+</div>
+
+<p>
+and not these wrapper methods:
+</p>
+
+<div class="code">
+<pre>
+void hello(int i);
+void hello();
+</pre>
+</div>
+
+<p>
+If <a href="SWIGPlus.html#SWIGPlus_default_args">compactdefaultargs</a> are being used, then the difference between
+specifying or not specifying default arguments in a feature is not applicable as just one wrapper is generated.
+</p>
+
+<p>
+<b>Compatibility note:</b> The different behaviour of features specified with or without default arguments was introduced
+in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.
+</p>
+
+<H3><a name="features_example"></a>11.3.5 Feature example</H3>
+
+
+<p>
+As has been shown earlier, the intended use for the <tt>%feature</tt> directive is as a highly flexible customization mechanism that can be used to annotate
+declarations with additional information for use by specific target language modules.  Another example is
+in the Python module. You might use <tt>%feature</tt> to rewrite proxy/shadow class code as follows:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%rename(bar_id) bar(int,double);
+
+// Rewrite bar() to allow some nice overloading
+
+%feature("shadow") Foo::bar(int) %{
+def bar(*args):
+    if len(args) == 3:
+         return apply(examplec.Foo_bar_id,args)
+    return apply(examplec.Foo_bar,args)
+%}
+    
+class Foo {
+public:
+    int bar(int x);
+    int bar(int x, double y);
+}
+</pre>
+</div>
+
+<p>
+Further details of <tt>%feature</tt> usage is described in the documentation for specific language modules.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Extending.html b/trunk/Doc/Manual/Extending.html
new file mode 100644
index 0000000..588912b
--- /dev/null
+++ b/trunk/Doc/Manual/Extending.html
@@ -0,0 +1,3779 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Extending SWIG to support new languages</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Extending"></a>34 Extending SWIG to support new languages</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Extending_nn2">Introduction</a>
+<li><a href="#Extending_nn3">Prerequisites</a>
+<li><a href="#Extending_nn4">The Big Picture</a>
+<li><a href="#Extending_nn5">Execution Model</a>
+<ul>
+<li><a href="#Extending_nn6">Preprocessing</a>
+<li><a href="#Extending_nn7">Parsing</a>
+<li><a href="#Extending_nn8">Parse Trees</a>
+<li><a href="#Extending_nn9">Attribute namespaces</a>
+<li><a href="#Extending_nn10">Symbol Tables</a>
+<li><a href="#Extending_nn11">The %feature directive</a>
+<li><a href="#Extending_nn12">Code Generation</a>
+<li><a href="#Extending_nn13">SWIG and XML</a>
+</ul>
+<li><a href="#Extending_nn14">Primitive Data Structures</a>
+<ul>
+<li><a href="#Extending_nn15">Strings</a>
+<li><a href="#Extending_nn16">Hashes</a>
+<li><a href="#Extending_nn17">Lists</a>
+<li><a href="#Extending_nn18">Common operations</a>
+<li><a href="#Extending_nn19">Iterating over Lists and Hashes</a>
+<li><a href="#Extending_nn20">I/O</a>
+</ul>
+<li><a href="#Extending_nn21">Navigating and manipulating parse trees</a>
+<li><a href="#Extending_nn22">Working with attributes</a>
+<li><a href="#Extending_nn23">Type system</a>
+<ul>
+<li><a href="#Extending_nn24">String encoding of types</a>
+<li><a href="#Extending_nn25">Type construction</a>
+<li><a href="#Extending_nn26">Type tests</a>
+<li><a href="#Extending_nn27">Typedef and inheritance</a>
+<li><a href="#Extending_nn28">Lvalues</a>
+<li><a href="#Extending_nn29">Output functions</a>
+</ul>
+<li><a href="#Extending_nn30">Parameters</a>
+<li><a href="#Extending_nn31">Writing a Language Module</a>
+<ul>
+<li><a href="#Extending_nn32">Execution model</a>
+<li><a href="#Extending_nn33">Starting out</a>
+<li><a href="#Extending_nn34">Command line options</a>
+<li><a href="#Extending_nn35">Configuration and preprocessing</a>
+<li><a href="#Extending_nn36">Entry point to code generation</a>
+<li><a href="#Extending_nn37">Module I/O and wrapper skeleton</a>
+<li><a href="#Extending_nn38">Low-level code generators</a>
+<li><a href="#Extending_nn39">Configuration files</a>
+<li><a href="#Extending_nn40">Runtime support</a>
+<li><a href="#Extending_nn41">Standard library files</a>
+<li><a href="#Extending_nn42">Examples and test cases</a>
+<li><a href="#Extending_nn43">Documentation</a>
+<li><a href="#Extending_prerequisites">Prerequisites for adding a new language module to the SWIG distribution</a>
+<li><a href="#Extending_coding_style_guidelines">Coding style guidelines</a>
+</ul>
+<li><a href="#Extending_nn44">Typemaps</a>
+<ul>
+<li><a href="#Extending_nn45">Proxy classes</a>
+</ul>
+<li><a href="#Extending_nn46">Guide to parse tree nodes</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<H2><a name="Extending_nn2"></a>34.1 Introduction</H2>
+
+
+<p>
+This chapter describes SWIG's internal organization and the process by which
+new target languages can be developed.    First, a brief word of warning---SWIG
+is continually evolving.
+The information in this chapter is mostly up to
+date, but changes are ongoing.   Expect a few inconsistencies.
+</p>
+
+<p>
+Also, this chapter is not meant to be a hand-holding tutorial.  As a starting point,
+you should probably look at one of SWIG's existing modules.
+</p>
+
+<H2><a name="Extending_nn3"></a>34.2 Prerequisites</H2>
+
+
+<p>
+In order to extend SWIG, it is useful to have the following background:
+</p>
+
+<ul>
+<li>An understanding of the C API for the target language.
+<li>A good grasp of the C++ type system.
+<li>An understanding of typemaps and some of SWIG's advanced features.
+<li>Some familiarity with writing C++ (language modules are currently written in C++).
+</ul>
+
+<p>
+Since SWIG is essentially a specialized C++ compiler, it may be useful
+to have some prior experience with compiler design (perhaps even a
+compilers course) to better understand certain parts of the system.  A
+number of books will also be useful.  For example, "The C Programming
+Language" by Kernighan and Ritchie (a.k.a, "K&amp;R") and the C++ standard,
+"ISO/IEC 14882 Programming Languages - C++" will be of great use.
+</p>
+
+<p>
+Also, it is useful to keep in mind that SWIG primarily operates as an
+extension of the C++ <em>type</em> system.  At first glance, this might not be
+obvious, but almost all SWIG directives as well as the low-level generation of
+wrapper code are driven by C++ datatypes.
+</p>
+
+<H2><a name="Extending_nn4"></a>34.3 The Big Picture</H2>
+
+
+<p>
+SWIG is a special purpose compiler that parses C++ declarations to
+generate wrapper code.  To make this conversion possible, SWIG makes
+three fundamental extensions to the C++ language:
+</p>
+
+<ul>
+<li><b>Typemaps</b>. Typemaps are used to define the
+conversion/marshalling behavior of specific C++ datatypes.  All type conversion in SWIG is
+based on typemaps.  Furthermore, the association of typemaps to datatypes utilizes an advanced pattern matching
+mechanism that is fully integrated with the C++ type system.
+</li>
+
+<li><b>Declaration Annotation</b>. To customize wrapper code
+generation, most declarations can be annotated with special features.
+For example, you can make a variable read-only, you can ignore a
+declaration, you can rename a member function, you can add exception
+handling, and so forth.  Virtually all of these customizations are built on top of a low-level
+declaration annotator that can attach arbitrary attributes to any declaration.
+Code generation modules can look for these attributes to guide the wrapping process.
+</li>
+
+<li><b>Class extension</b>. SWIG allows classes and structures to be extended with new
+methods and attributes (the <tt>%extend</tt> directive).   This has the effect of altering
+the API in the target language and can be used to generate OO interfaces to C libraries.
+</ul>
+
+<p>
+It is important to emphasize that virtually all SWIG features reduce to one of these three
+fundamental concepts.  The type system and pattern matching rules also play a critical
+role in making the system work.  For example, both typemaps and declaration annotation are
+based on pattern matching and interact heavily with the underlying type system.
+</p>
+
+<H2><a name="Extending_nn5"></a>34.4 Execution Model</H2>
+
+
+<p>
+When you run SWIG on an interface, processing is handled in stages by a series of system components:
+</p>
+
+<ul>
+<li>An integrated C preprocessor reads a collection of configuration
+files and the specified interface file into memory.  The preprocessor
+performs the usual functions including macro expansion and file
+inclusion.   However, the preprocessor also performs some transformations of the
+interface.  For instance, <tt>#define</tt> statements are sometimes transformed into
+<tt>%constant</tt> declarations.  In addition, information related to file/line number
+tracking is inserted.
+</li>
+
+<li>A C/C++ parser reads the preprocessed input and generates a full
+parse tree of all of the SWIG directives and C declarations found.
+The parser is responsible for many aspects of the system including
+renaming, declaration annotation, and template expansion.  However, the parser
+does not produce any output nor does it interact with the target
+language module as it runs.  SWIG is not a one-pass compiler.
+</li>
+
+<li>A type-checking pass is made. This adjusts all of the C++ typenames to properly
+handle namespaces, typedefs, nested classes, and other issues related to type scoping.
+</li>
+
+<li>A semantic pass is made on the parse tree to collect information
+related to properties of the C++ interface.  For example, this pass
+would determine whether or not a class allows a default constructor.
+</li>
+
+<li>A code generation pass is made using a specific target language
+module.  This phase is responsible for generating the actual wrapper
+code.  All of SWIG's user-defined modules are invoked during this
+latter stage of compilation.
+</li>
+</ul>
+
+<p>
+The next few sections briefly describe some of these stages.
+</p>
+
+<H3><a name="Extending_nn6"></a>34.4.1 Preprocessing</H3>
+
+
+<p>
+The preprocessor plays a critical role in the SWIG implementation.  This is because a lot
+of SWIG's processing and internal configuration is managed not by code written in C, but
+by configuration files in the SWIG library.  In fact, when you
+run SWIG, parsing starts with a small interface file like this (note: this explains
+the cryptic error messages that new users sometimes get when SWIG is misconfigured or installed
+incorrectly):
+</p>
+
+<div class="code">
+<pre>
+%include "swig.swg"             // Global SWIG configuration
+%include "<em>langconfig.swg</em>"       // Language specific configuration
+%include "yourinterface.i"      // Your interface file
+</pre>
+</div>
+
+<p>
+The <tt>swig.swg</tt> file contains global configuration information.  In addition, this file
+defines many of SWIG's standard directives as macros.  For instance, part of
+of <tt>swig.swg</tt> looks like this:
+</p>
+
+<div class="code">
+<pre>
+...
+/* Code insertion directives such as %wrapper %{ ... %} */
+
+#define %init        %insert("init")
+#define %wrapper     %insert("wrapper")
+#define %header      %insert("header")
+#define %runtime     %insert("runtime")
+
+/* Access control directives */
+
+#define %immutable   %feature("immutable","1")
+#define %mutable     %feature("immutable")
+
+/* Directives for callback functions */
+
+#define %callback(x) %feature("callback") `x`;
+#define %nocallback  %feature("callback");
+
+/* %ignore directive */
+
+#define %ignore         %rename($ignore)
+#define %ignorewarn(x)  %rename("$ignore:" x)
+...
+</pre>
+</div>
+
+<p>
+The fact that most of the standard SWIG directives are macros is
+intended to simplify the implementation of the internals.  For instance,
+rather than having to support dozens of special directives, it is
+easier to have a few basic primitives such as <tt>%feature</tt> or
+<tt>%insert</tt>.
+</p>
+
+<p>
+The <em><tt>langconfig.swg</tt></em> file is supplied by the target
+language. This file contains language-specific configuration
+information.  More often than not, this file provides run-time wrapper
+support code (e.g., the type-checker) as well as a collection of
+typemaps that define the default wrapping behavior.  Note: the name of this
+file depends on the target language and is usually something like <tt>python.swg</tt>
+or <tt>perl5.swg</tt>.
+</p>
+
+<p>
+As a debugging aide, the text that SWIG feeds to its C++ parser can be
+obtained by running <tt>swig -E interface.i</tt>.  This output
+probably isn't too useful in general, but it will show how macros have
+been expanded as well as everything else that goes into the low-level
+construction of the wrapper code.
+</p>
+
+<H3><a name="Extending_nn7"></a>34.4.2 Parsing</H3>
+
+
+<p>
+The current C++ parser handles a subset of C++.  Most incompatibilities with C are due to
+subtle aspects of how SWIG parses declarations.  Specifically, SWIG expects all C/C++ declarations to follow this general form:
+</p>
+
+<div class="diagram">
+<pre>
+<em>storage</em> <em>type</em> <em>declarator</em> <em>initializer</em>;
+</pre>
+</div>
+
+<p>
+<tt><em>storage</em></tt> is a keyword such as <tt>extern</tt>,
+<tt>static</tt>, <tt>typedef</tt>, or <tt>virtual</tt>.  <tt><em>type</em></tt> is a primitive
+datatype such as <tt>int</tt> or <tt>void</tt>.   <tt><em>type</em></tt> may be optionally
+qualified with a qualifier such as <tt>const</tt> or <tt>volatile</tt>. <tt><em>declarator</em></tt>
+is a name with additional type-construction modifiers attached to it (pointers, arrays, references,
+functions, etc.).  Examples of declarators include <tt>*x</tt>, <tt>**x</tt>, <tt>x[20]</tt>, and
+<tt>(*x)(int,double)</tt>.   The <tt><em>initializer</em></tt> may be a value assigned using <tt>=</tt> or
+body of code enclosed in braces <tt>{ ... }</tt>.
+</p>
+
+<p>
+This declaration format covers most common C++ declarations. However, the C++ standard
+is somewhat more flexible in the placement of the parts.  For example, it is technically legal, although
+uncommon to write something like <tt>int typedef const a</tt> in your program.   SWIG simply
+doesn't bother to deal with this case.
+</p>
+
+<p>
+The other significant difference between C++ and SWIG is in the
+treatment of typenames.  In C++, if you have a declaration like this,
+</p>
+
+<div class="code">
+<pre>
+int blah(Foo *x, Bar *y);
+</pre>
+</div>
+
+<p>
+it won't parse correctly unless <tt>Foo</tt> and <tt>Bar</tt> have
+been previously defined as types either using a <tt>class</tt>
+definition or a <tt>typedef</tt>.  The reasons for this are subtle,
+but this treatment of typenames is normally integrated at the level of the C
+tokenizer---when a typename appears, a different token is returned to the parser
+instead of an identifier.
+</p>
+
+<p>
+SWIG does not operate in this manner--any legal identifier can be used
+as a type name.  The reason for this is primarily motivated by the use
+of SWIG with partially defined data.  Specifically,
+SWIG is supposed to be easy to use on interfaces with missing type information.
+</p>
+
+<p>
+Because of the different treatment of typenames, the most serious
+limitation of the SWIG parser is that it can't process type declarations where
+an extra (and unnecessary) grouping operator is used.  For example:
+</p>
+
+<div class="code">
+<pre>
+int (x);         /* A variable x */
+int (y)(int);    /* A function y */
+</pre>
+</div>
+
+<p>
+The placing of extra parentheses in type declarations like this is
+already recognized by the C++ community as a potential source of
+strange programming errors. For example, Scott Meyers "Effective STL"
+discusses this problem in a section on avoiding C++'s "most vexing
+parse."
+</p>
+
+<p>
+The parser is also unable to handle declarations with no return type or bare argument names.
+For example, in an old C program, you might see things like this:
+</p>
+
+<div class="code">
+<pre>
+foo(a,b) {
+...
+}
+</pre>
+</div>
+
+<p>
+In this case, the return type as well as the types of the arguments
+are taken by the C compiler to be an <tt>int</tt>.  However, SWIG
+interprets the above code as an abstract declarator for a function
+returning a <tt>foo</tt> and taking types <tt>a</tt> and <tt>b</tt> as
+arguments).
+</p>
+
+<H3><a name="Extending_nn8"></a>34.4.3 Parse Trees</H3>
+
+
+<p>
+The SWIG parser produces a complete parse tree of the input file before any wrapper code
+is actually generated.  Each item in the tree is known as a "Node".   Each node is identified
+by a symbolic tag.   Furthermore, a node may have an arbitrary number of children.
+The parse tree structure and tag names of an interface can be displayed using <tt>swig -debug-tags</tt>.
+For example:
+</p>
+
+<div class="shell">
+<pre>
+$ <b>swig -c++ -python -debug-tags example.i</b>
+ . top (example.i:1)
+ . top . include (example.i:1)
+ . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:71)
+ . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:71)
+ . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:83)
+ . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:83)
+ . top . include (example.i:4)
+ . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:7)
+ . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:8)
+ . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/python/python.swg:19)
+...
+ . top . include (example.i:6)
+ . top . include . module (example.i:2)
+ . top . include . insert (example.i:6)
+ . top . include . include (example.i:9)
+ . top . include . include . class (example.h:3)
+ . top . include . include . class . access (example.h:4)
+ . top . include . include . class . constructor (example.h:7)
+ . top . include . include . class . destructor (example.h:10)
+ . top . include . include . class . cdecl (example.h:11)
+ . top . include . include . class . cdecl (example.h:11)
+ . top . include . include . class . cdecl (example.h:12)
+ . top . include . include . class . cdecl (example.h:13)
+ . top . include . include . class . cdecl (example.h:14)
+ . top . include . include . class . cdecl (example.h:15)
+ . top . include . include . class (example.h:18)
+ . top . include . include . class . access (example.h:19)
+ . top . include . include . class . cdecl (example.h:20)
+ . top . include . include . class . access (example.h:21)
+ . top . include . include . class . constructor (example.h:22)
+ . top . include . include . class . cdecl (example.h:23)
+ . top . include . include . class . cdecl (example.h:24)
+ . top . include . include . class (example.h:27)
+ . top . include . include . class . access (example.h:28)
+ . top . include . include . class . cdecl (example.h:29)
+ . top . include . include . class . access (example.h:30)
+ . top . include . include . class . constructor (example.h:31)
+ . top . include . include . class . cdecl (example.h:32)
+ . top . include . include . class . cdecl (example.h:33)
+</pre>
+</div>
+
+<p>
+Even for the most simple interface, the parse tree structure is larger than you might expect.  For example, in the
+above output, a substantial number of nodes are actually generated by the <tt>python.swg</tt> configuration file
+which defines typemaps and other directives.   The contents of the user-supplied input file don't appear until the end
+of the output.
+</p>
+
+<p>
+The contents of each parse tree node consist of a collection of attribute/value
+pairs.  Internally, the nodes are simply represented by hash tables.  A display of
+the entire parse-tree structure can be obtained using <tt>swig -dump_tree</tt>. 
+There are a number of other parse tree display options, for example, <tt>swig -debug-module &lt;n&gt;</tt> will
+avoid displaying system parse information and only display the parse tree pertaining to the user's module at
+stage <tt>n</tt> of processing.
+</p>
+
+<div class="shell">
+<pre>
+$ swig -c++ -python -debug-module 4 example.i
+      +++ include ----------------------------------------
+      | name         - "example.i"
+
+            +++ module ----------------------------------------
+            | name         - "example"
+            |
+            +++ insert ----------------------------------------
+            | code         - "\n#include \"example.h\"\n"
+            |
+            +++ include ----------------------------------------
+            | name         - "example.h"
+
+                  +++ class ----------------------------------------
+                  | abstract     - "1"
+                  | sym:name     - "Shape"
+                  | name         - "Shape"
+                  | kind         - "class"
+                  | symtab       - 0x40194140
+                  | sym:symtab   - 0x40191078
+
+                        +++ access ----------------------------------------
+                        | kind         - "public"
+                        |
+                        +++ constructor ----------------------------------------
+                        | sym:name     - "Shape"
+                        | name         - "Shape"
+                        | decl         - "f()."
+                        | code         - "{\n    nshapes++;\n  }"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ destructor ----------------------------------------
+                        | sym:name     - "~Shape"
+                        | name         - "~Shape"
+                        | storage      - "virtual"
+                        | code         - "{\n    nshapes--;\n  }"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "x"
+                        | name         - "x"
+                        | decl         - ""
+                        | type         - "double"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "y"
+                        | name         - "y"
+                        | decl         - ""
+                        | type         - "double"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "move"
+                        | name         - "move"
+                        | decl         - "f(double,double)."
+                        | parms        - double ,double
+                        | type         - "void"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "area"
+                        | name         - "area"
+                        | decl         - "f(void)."
+                        | parms        - void
+                        | storage      - "virtual"
+                        | value        - "0"
+                        | type         - "double"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "perimeter"
+                        | name         - "perimeter"
+                        | decl         - "f(void)."
+                        | parms        - void
+                        | storage      - "virtual"
+                        | value        - "0"
+                        | type         - "double"
+                        | sym:symtab   - 0x40194140
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "nshapes"
+                        | name         - "nshapes"
+                        | decl         - ""
+                        | storage      - "static"
+                        | type         - "int"
+                        | sym:symtab   - 0x40194140
+                        |
+                  +++ class ----------------------------------------
+                  | sym:name     - "Circle"
+                  | name         - "Circle"
+                  | kind         - "class"
+                  | bases        - 0x40194510
+                  | symtab       - 0x40194538
+                  | sym:symtab   - 0x40191078
+
+                        +++ access ----------------------------------------
+                        | kind         - "private"
+                        |
+                        +++ cdecl ----------------------------------------
+                        | name         - "radius"
+                        | decl         - ""
+                        | type         - "double"
+                        |
+                        +++ access ----------------------------------------
+                        | kind         - "public"
+                        |
+                        +++ constructor ----------------------------------------
+                        | sym:name     - "Circle"
+                        | name         - "Circle"
+                        | parms        - double
+                        | decl         - "f(double)."
+                        | code         - "{ }"
+                        | sym:symtab   - 0x40194538
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "area"
+                        | name         - "area"
+                        | decl         - "f(void)."
+                        | parms        - void
+                        | storage      - "virtual"
+                        | type         - "double"
+                        | sym:symtab   - 0x40194538
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "perimeter"
+                        | name         - "perimeter"
+                        | decl         - "f(void)."
+                        | parms        - void
+                        | storage      - "virtual"
+                        | type         - "double"
+                        | sym:symtab   - 0x40194538
+                        |
+                  +++ class ----------------------------------------
+                  | sym:name     - "Square"
+                  | name         - "Square"
+                  | kind         - "class"
+                  | bases        - 0x40194760
+                  | symtab       - 0x40194788
+                  | sym:symtab   - 0x40191078
+
+                        +++ access ----------------------------------------
+                        | kind         - "private"
+                        |
+                        +++ cdecl ----------------------------------------
+                        | name         - "width"
+                        | decl         - ""
+                        | type         - "double"
+                        |
+                        +++ access ----------------------------------------
+                        | kind         - "public"
+                        |
+                        +++ constructor ----------------------------------------
+                        | sym:name     - "Square"
+                        | name         - "Square"
+                        | parms        - double
+                        | decl         - "f(double)."
+                        | code         - "{ }"
+                        | sym:symtab   - 0x40194788
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "area"
+                        | name         - "area"
+                        | decl         - "f(void)."
+                        | parms        - void
+                        | storage      - "virtual"
+                        | type         - "double"
+                        | sym:symtab   - 0x40194788
+                        |
+                        +++ cdecl ----------------------------------------
+                        | sym:name     - "perimeter"
+                        | name         - "perimeter"
+                        | decl         - "f(void)."
+                        | parms        - void
+                        | storage      - "virtual"
+                        | type         - "double"
+                        | sym:symtab   - 0x40194788
+</pre>
+</div>
+
+<H3><a name="Extending_nn9"></a>34.4.4 Attribute namespaces</H3>
+
+
+<p>
+Attributes of parse tree nodes are often prepended with a namespace qualifier.
+For example, the attributes
+<tt>sym:name</tt> and <tt>sym:symtab</tt> are attributes related to
+symbol table management and are prefixed with <tt>sym:</tt>.  As a
+general rule, only those attributes which are directly related to the raw declaration
+appear without a prefix (type, name, declarator, etc.).
+</p>
+
+<p>
+Target language modules may add additional attributes to nodes to assist the generation
+of wrapper code.  The convention for doing this is to place these attributes in a namespace
+that matches the name of the target language.  For example, <tt>python:foo</tt> or
+<tt>perl:foo</tt>.
+</p>
+
+<H3><a name="Extending_nn10"></a>34.4.5 Symbol Tables</H3>
+
+
+<p>
+During parsing, all symbols are managed in the space of the target
+language.  The <tt>sym:name</tt> attribute of each node contains the symbol name
+selected by the parser.  Normally, <tt>sym:name</tt> and <tt>name</tt>
+are the same.  However, the <tt>%rename</tt> directive can be used to
+change the value of <tt>sym:name</tt>.  You can see the effect of
+<tt>%rename</tt> by trying it on a simple interface and dumping the
+parse tree.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(foo_i) foo(int);
+%rename(foo_d) foo(double);
+
+void foo(int);
+void foo(double);
+void foo(Bar *b);
+</pre>
+</div>
+
+<p>
+There are various <tt>debug-</tt> options that can be useful for debugging and analysing the parse tree.
+For example, the <tt>debug-top &lt;n&gt;</tt> or <tt>debug-module &lt;n&gt;</tt> options will
+dump the entire/top of the parse tree or the module subtree at one of the four <tt>n</tt> stages of processing.
+The parse tree can be viewed after the final stage of processing by running SWIG:
+</p>
+
+<div class="shell">
+<pre>
+$ swig -debug-top 4 example.i
+...
+            +++ cdecl ----------------------------------------
+            | sym:name     - "foo_i"
+            | name         - "foo"
+            | decl         - "f(int)."
+            | parms        - int
+            | type         - "void"
+            | sym:symtab   - 0x40165078
+            |
+            +++ cdecl ----------------------------------------
+            | sym:name     - "foo_d"
+            | name         - "foo"
+            | decl         - "f(double)."
+            | parms        - double
+            | type         - "void"
+            | sym:symtab   - 0x40165078
+            |
+            +++ cdecl ----------------------------------------
+            | sym:name     - "foo"
+            | name         - "foo"
+            | decl         - "f(p.Bar)."
+            | parms        - Bar *
+            | type         - "void"
+            | sym:symtab   - 0x40165078
+</pre>
+</div>
+
+<p>
+All symbol-related conflicts and complaints about overloading are based on <tt>sym:name</tt> values.
+For instance, the following example uses <tt>%rename</tt> in reverse to generate a name clash.
+</p>
+
+<div class="code">
+<pre>
+%rename(foo) foo_i(int);
+%rename(foo) foo_d(double;
+
+void foo_i(int);
+void foo_d(double);
+void foo(Bar *b);
+</pre>
+</div>
+
+<p>
+When you run SWIG on this you now get:
+</p>
+
+<div class="shell">
+<pre>
+$ ./swig example.i
+example.i:6. Overloaded declaration ignored.  foo_d(double )
+example.i:5. Previous declaration is foo_i(int )
+example.i:7. Overloaded declaration ignored.  foo(Bar *)
+example.i:5. Previous declaration is foo_i(int )
+</pre>
+</div>
+
+<H3><a name="Extending_nn11"></a>34.4.6 The %feature directive</H3>
+
+
+<p>
+A number of SWIG directives such as <tt>%exception</tt> are implemented using the
+low-level <tt>%feature</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%feature("except") getitem(int) {
+  try {
+     $action
+  } catch (badindex) {
+     ...
+  }
+}
+
+...
+class Foo {
+public:
+    Object *getitem(int index) throws(badindex);
+    ...
+};
+</pre>
+</div>
+
+<p>
+The behavior of <tt>%feature</tt> is very easy to describe--it simply
+attaches a new attribute to any parse tree node that matches the
+given prototype.   When a feature is added, it shows up as an attribute in the <tt>feature:</tt> namespace.
+You can see this when running with the <tt>-debug-top 4</tt> option.   For example:
+</p>
+
+<div class="shell">
+<pre>
+ +++ cdecl ----------------------------------------
+ | sym:name     - "getitem"
+ | name         - "getitem"
+ | decl         - "f(int).p."
+ | parms        - int
+ | type         - "Object"
+ | feature:except - "{\n    try {\n       $action\n    } catc..."
+ | sym:symtab   - 0x40168ac8
+ |
+</pre>
+</div>
+
+<p>
+Feature names are completely arbitrary and a target language module can be
+programmed to respond to any feature name that it wants to recognize.  The 
+data stored in a feature attribute is usually just a raw unparsed string.   
+For example, the exception code above is simply
+stored without any modifications.
+</p>
+
+<H3><a name="Extending_nn12"></a>34.4.7 Code Generation</H3>
+
+
+<p>
+Language modules work by defining handler functions that know how to respond to
+different types of parse-tree nodes.  These handlers simply look at the
+attributes of each node in order to produce low-level code.
+</p>
+
+<p>
+In reality, the generation of code is somewhat more subtle than simply
+invoking handler functions.  This is because parse-tree nodes might be
+transformed. For example, suppose you are wrapping a class like this:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    virtual int *bar(int x);
+};
+</pre>
+</div>
+
+<p>
+When the parser constructs a node for the member <tt>bar</tt>, it creates a raw "cdecl" node with the following
+attributes:
+</p>
+
+<div class="diagram">
+<pre>
+nodeType    : cdecl
+name        : bar
+type        : int
+decl        : f(int).p
+parms       : int x
+storage     : virtual
+sym:name    : bar
+</pre>
+</div>
+
+<p>
+To produce wrapper code, this "cdecl" node undergoes a number of transformations.  First, the node is recognized as a function declaration.   This adjusts some of the type information--specifically, the declarator is joined with the base datatype to produce this:
+</p>
+
+<div class="diagram">
+<pre>
+nodeType    : cdecl
+name        : bar
+type        : p.int        &lt;-- Notice change in return type
+decl        : f(int).p
+parms       : int x
+storage     : virtual
+sym:name    : bar
+</pre>
+</div>
+
+<p>
+Next, the context of the node indicates that the node is really a
+member function.  This produces a transformation to a low-level
+accessor function like this:
+</p>
+
+<div class="diagram">
+<pre>
+nodeType    : cdecl
+name        : bar
+type        : int.p
+decl        : f(int).p
+parms       : Foo *self, int x            &lt;-- Added parameter
+storage     : virtual
+wrap:action : result = (arg1)-&gt;bar(arg2)  &lt;-- Action code added
+sym:name    : Foo_bar                     &lt;-- Symbol name changed
+</pre>
+</div>
+
+<p>
+In this transformation, notice how an additional parameter was added
+to the parameter list and how the symbol name of the node has suddenly
+changed into an accessor using the naming scheme described in the
+"SWIG Basics" chapter.  A small fragment of "action" code has also
+been generated--notice how the <tt>wrap:action</tt> attribute defines
+the access to the underlying method.  The data in this transformed
+node is then used to generate a wrapper.
+</p>
+
+<p>
+Language modules work by registering handler functions for dealing with
+various types of nodes at different stages of transformation.   This is done by
+inheriting from a special <tt>Language</tt> class and defining a collection
+of virtual methods.   For example, the Python module defines a class as
+follows:
+</p>
+
+<div class="code">
+<pre>
+class PYTHON : public Language {
+protected:
+public :
+  virtual void main(int, char *argv[]);
+  virtual int  top(Node *);
+  virtual int  functionWrapper(Node *);
+  virtual int  constantWrapper(Node *);
+  virtual int  variableWrapper(Node *);
+  virtual int  nativeWrapper(Node *);
+  virtual int  membervariableHandler(Node *);
+  virtual int  memberconstantHandler(Node *);
+  virtual int  memberfunctionHandler(Node *);
+  virtual int  constructorHandler(Node *);
+  virtual int  destructorHandler(Node *);
+  virtual int  classHandler(Node *);
+  virtual int  classforwardDeclaration(Node *);
+  virtual int  insertDirective(Node *);
+  virtual int  importDirective(Node *);
+};
+</pre>
+</div>
+
+<p>
+The role of these functions is described shortly.
+</p>
+
+<H3><a name="Extending_nn13"></a>34.4.8 SWIG and XML</H3>
+
+
+<p>
+Much of SWIG's current parser design was originally motivated by
+interest in using XML to represent SWIG parse trees.  Although XML is
+not currently used in any direct manner, the parse tree structure, use
+of node tags, attributes, and attribute namespaces are all influenced
+by aspects of XML parsing.  Therefore, in trying to understand SWIG's
+internal data structures, it may be useful to keep XML in the back of
+your mind as a model.
+</p>
+
+<H2><a name="Extending_nn14"></a>34.5 Primitive Data Structures</H2>
+
+
+<p>
+Most of SWIG is constructed using three basic data structures:
+strings, hashes, and lists.  These data structures are dynamic in same way as
+similar structures found in many scripting languages.  For instance,
+you can have containers (lists and hash tables) of mixed types and
+certain operations are polymorphic.
+</p>
+
+<p>
+This section briefly describes the basic structures so that later
+sections of this chapter make more sense.
+</p>
+
+<p>
+When describing the low-level API, the following type name conventions are
+used:
+</p>
+
+<ul>
+<li><tt>String</tt>.  A string object.
+<li><tt>Hash</tt>. A hash object.
+<li><tt>List</tt>. A list object.
+<li><tt>String_or_char</tt>. A string object or a <tt>char *</tt>.
+<li><tt>Object_or_char</tt>. An object or a <tt>char *</tt>.
+<li><tt>Object</tt>.  Any object (string, hash, list, etc.)
+</ul>
+
+<p>
+In most cases, other typenames in the source are aliases for one of these
+primitive types.   Specifically:
+</p>
+
+<div class="code">
+<pre>
+typedef String SwigType;
+typedef Hash   Parm;
+typedef Hash   ParmList;
+typedef Hash   Node;
+typedef Hash   Symtab;
+typedef Hash   Typetab;
+</pre>
+</div>
+
+<H3><a name="Extending_nn15"></a>34.5.1 Strings</H3>
+
+
+<p>
+<b><tt>String *NewString(const String_or_char *val)</tt></b>
+</p>
+
+<div class="indent">
+Creates a new string with initial value <tt>val</tt>. <tt>val</tt> may
+be a <tt>char *</tt> or another <tt>String</tt> object.   If you want
+to create an empty string, use "" for val.
+</div>
+
+<p>
+<b><tt>String *NewStringf(const char *fmt, ...)</tt></b>
+</p>
+
+<div class="indent">
+Creates a new string whose initial value is set according to a C <tt>printf</tt> style
+format string in <tt>fmt</tt>.   Additional arguments follow depending
+on <tt>fmt</tt>.
+</div>
+
+<p>
+<b><tt>String *Copy(String *s)</tt></b>
+</p>
+
+<div class="indent">
+Make a copy of the string <tt>s</tt>.
+</div>
+
+<p>
+<b><tt>void Delete(String *s)</tt></b>
+</p>
+
+<div class="indent">
+Deletes <tt>s</tt>.
+</div>
+
+<p>
+<b><tt>int Len(String_or_char *s)</tt></b>
+</p>
+
+<div class="indent">
+Returns the length of the string.
+</div>
+
+<p>
+<b><tt>char *Char(String_or_char *s)</tt></b>
+</p>
+
+<div class="indent">
+Returns a pointer to the first character in a string.
+</div>
+
+<p>
+<b><tt>void Append(String *s, String_or_char *t)</tt></b>
+</p>
+
+<div class="indent">
+Appends <tt>t</tt> to the end of string <tt>s</tt>.
+</div>
+
+<p>
+<b><tt>void Insert(String *s, int pos, String_or_char *t)</tt></b>
+</p>
+
+<div class="indent">
+Inserts <tt>t</tt> into <tt>s</tt> at position <tt>pos</tt>.  The contents
+of <tt>s</tt> are shifted accordingly.    The special value <tt>DOH_END</tt>
+can be used for <tt>pos</tt> to indicate insertion at the end of the string (appending).
+</div>
+
+<p>
+<b><tt>int Strcmp(const String_or_char *s, const String_or_char *t)</tt></b>
+</p>
+
+<div class="indent">
+Compare strings <tt>s</tt> and <tt>t</tt>.   Same as the C <tt>strcmp()</tt>
+function.
+</div>
+
+<p>
+<b><tt>int Strncmp(const String_or_char *s, const String_or_char *t, int len)</tt></b>
+</p>
+
+<div class="indent">
+Compare the first <tt>len</tt> characters of strings <tt>s</tt> and <tt>t</tt>.   Same as the C <tt>strncmp()</tt>
+function.
+</div>
+
+<p>
+<b><tt>char *Strstr(const String_or_char *s, const String_or_char *pat)</tt></b>
+</p>
+
+<div class="indent">
+Returns a pointer to the first occurrence of <tt>pat</tt> in <tt>s</tt>.
+Same as the C <tt>strstr()</tt> function.
+</div>
+
+<p>
+<b><tt>char *Strchr(const String_or_char *s, char ch)</tt></b>
+</p>
+
+<div class="indent">
+Returns a pointer to the first occurrence of character <tt>ch</tt> in <tt>s</tt>.
+Same as the C <tt>strchr()</tt> function.
+</div>
+
+<p>
+<b><tt>void Chop(String *s)</tt></b>
+</p>
+
+<div class="indent">
+Chops trailing whitespace off the end of <tt>s</tt>.
+</div>
+
+<p>
+<b><tt>int Replace(String *s, const String_or_char *pat, const String_or_char *rep, int flags)</tt></b>
+</p>
+
+<div class="indent">
+<p>
+Replaces the pattern <tt>pat</tt> with <tt>rep</tt> in string <tt>s</tt>.
+<tt>flags</tt> is a combination of the following flags:</p>
+
+<div class="code">
+<pre>
+DOH_REPLACE_ANY       - Replace all occurrences
+DOH_REPLACE_ID        - Valid C identifiers only
+DOH_REPLACE_NOQUOTE   - Don't replace in quoted strings
+DOH_REPLACE_FIRST     - Replace first occurrence only.
+</pre>
+</div>
+
+<p>
+Returns the number of replacements made (if any).
+</p>
+
+</div>
+
+<H3><a name="Extending_nn16"></a>34.5.2 Hashes</H3>
+
+
+<p>
+<b><tt>Hash *NewHash()</tt></b>
+</p>
+
+<div class="indent">
+Creates a new empty hash table.
+</div>
+
+<p>
+<b><tt>Hash *Copy(Hash *h)</tt></b>
+</p>
+
+<div class="indent">
+Make a shallow copy of the hash <tt>h</tt>.
+</div>
+
+<p>
+<b><tt>void Delete(Hash *h)</tt></b>
+</p>
+
+<div class="indent">
+Deletes <tt>h</tt>.
+</div>
+
+<p>
+<b><tt>int Len(Hash *h)</tt></b>
+</p>
+
+<div class="indent">
+Returns the number of items in <tt>h</tt>.
+</div>
+
+<p>
+<b><tt>Object *Getattr(Hash *h, String_or_char *key)</tt></b>
+</p>
+
+<div class="indent">
+Gets an object from <tt>h</tt>.  <tt>key</tt> may be a string or
+a simple <tt>char *</tt> string.   Returns NULL if not found.
+</div>
+
+<p>
+<b><tt>int Setattr(Hash *h, String_or_char *key, Object_or_char *val)</tt></b>
+</p>
+
+<div class="indent">
+Stores <tt>val</tt> in <tt>h</tt>. <tt>key</tt> may be a string or
+a simple <tt>char *</tt>. If <tt>val</tt> is not a standard
+object (String, Hash, or List) it is assumed to be a <tt>char *</tt> in which
+case it is used to construct a <tt>String</tt> that is stored in the hash.
+If <tt>val</tt> is NULL, the object is deleted. Increases the reference count
+of <tt>val</tt>.   Returns 1 if this operation replaced an existing hash entry,
+0 otherwise.
+</div>
+
+<p>
+<b><tt>int Delattr(Hash *h, String_or_char *key)</tt></b>
+</p>
+
+<div class="indent">
+Deletes the hash item referenced by <tt>key</tt>.  Decreases the
+reference count on the corresponding object (if any).  Returns 1
+if an object was removed, 0 otherwise.
+</div>
+
+<p>
+<b><tt>List *Keys(Hash *h)</tt></b>
+</p>
+
+<div class="indent">
+Returns the list of hash table keys.
+</div>
+
+
+<H3><a name="Extending_nn17"></a>34.5.3 Lists</H3>
+
+
+<p>
+<b><tt>List *NewList()</tt></b>
+</p>
+
+<div class="indent">
+Creates a new empty list.
+</div>
+
+<p>
+<b><tt>List *Copy(List *x)</tt></b>
+</p>
+
+<div class="indent">
+Make a shallow copy of the List <tt>x</tt>.
+</div>
+
+<p>
+<b><tt>void Delete(List *x)</tt></b>
+</p>
+
+<div class="indent">
+Deletes <tt>x</tt>.
+</div>
+
+<p>
+<b><tt>int Len(List *x)</tt></b>
+</p>
+
+<div class="indent">
+Returns the number of items in <tt>x</tt>.
+</div>
+
+<p>
+<b><tt>Object *Getitem(List *x, int n)</tt></b>
+</p>
+
+<div class="indent">
+Returns an object from <tt>x</tt> with index <tt>n</tt>.  If <tt>n</tt> is
+beyond the end of the list, the last item is returned. If <tt>n</tt> is
+negative, the first item is returned.
+</div>
+
+<p>
+<b><tt>int *Setitem(List *x, int n, Object_or_char *val)</tt></b>
+</p>
+
+<div class="indent">
+Stores <tt>val</tt> in <tt>x</tt>.
+If <tt>val</tt> is not a standard
+object (String, Hash, or List) it is assumed to be a <tt>char *</tt> in which
+case it is used to construct a <tt>String</tt> that is stored in the list.
+<tt>n</tt> must be in range.  Otherwise, an assertion will be raised.
+</div>
+
+<p>
+<b><tt>int *Delitem(List *x, int n)</tt></b>
+</p>
+
+<div class="indent">
+Deletes item <tt>n</tt> from the list, shifting items down if necessary.
+To delete the last item in the list, use the special value <tt>DOH_END</tt>
+for <tt>n</tt>.
+</div>
+
+<p>
+<b><tt>void Append(List *x, Object_or_char *t)</tt></b>
+</p>
+
+<div class="indent">
+Appends <tt>t</tt> to the end of <tt>x</tt>.  If <tt>t</tt> is not
+a standard object, it is assumed to be a <tt>char *</tt> and is
+used to create a String object.
+</div>
+
+<p>
+<b><tt>void Insert(String *s, int pos, Object_or_char *t)</tt></b>
+</p>
+
+<div class="indent">
+Inserts <tt>t</tt> into <tt>s</tt> at position <tt>pos</tt>.  The contents
+of <tt>s</tt> are shifted accordingly.    The special value <tt>DOH_END</tt>
+can be used for <tt>pos</tt> to indicate insertion at the end of the list (appending).
+If <tt>t</tt> is not a standard object, it is assumed to be a <tt>char *</tt>
+and is used to create a String object.
+</div>
+
+<H3><a name="Extending_nn18"></a>34.5.4 Common operations</H3>
+
+
+The following operations are applicable to all datatypes.
+
+<p>
+<b><tt>Object *Copy(Object *x)</tt></b>
+</p>
+
+<div class="indent">
+Make a copy of the object <tt>x</tt>.
+</div>
+
+<p>
+<b><tt>void Delete(Object *x)</tt></b>
+</p>
+
+<div class="indent">
+Deletes <tt>x</tt>.
+</div>
+
+<p>
+<b><tt>void Setfile(Object *x, String_or_char *f)</tt></b>
+</p>
+
+<div class="indent">
+Sets the filename associated with <tt>x</tt>.  Used to track
+objects and report errors.
+</div>
+
+<p>
+<b><tt>String *Getfile(Object *x)</tt></b>
+</p>
+
+<div class="indent">
+Gets the filename associated with <tt>x</tt>.
+</div>
+
+<p>
+<b><tt>void Setline(Object *x, int n)</tt></b>
+</p>
+
+<div class="indent">
+Sets the line number associated with <tt>x</tt>.  Used to track
+objects and report errors.
+</div>
+
+<p>
+<b><tt>int Getline(Object *x)</tt></b>
+</p>
+
+<div class="indent">
+Gets the line number associated with <tt>x</tt>.
+</div>
+
+<H3><a name="Extending_nn19"></a>34.5.5 Iterating over Lists and Hashes</H3>
+
+
+To iterate over the elements of a list or a hash table, the following functions are used:
+
+<p>
+<b><tt>Iterator First(Object *x)</tt></b>
+</p>
+
+<div class="indent">
+Returns an iterator object that points to the first item in a list or hash table.  The
+<tt>item</tt> attribute of the Iterator object is a pointer to the item.  For hash tables, the <tt>key</tt> attribute
+of the Iterator object additionally points to the corresponding Hash table key.  The <tt>item</tt> and <tt>key</tt> attributes
+are NULL if the object contains no items or if there are no more items.
+</div>
+
+<p>
+<b><tt>Iterator Next(Iterator i)</tt></b>
+</p>
+
+<div class="indent">
+<p>Returns an iterator that points to the next item in a list or hash table.
+
+Here are two examples of iteration:</p>
+
+<div class="code">
+<pre>
+List *l = (some list);
+Iterator i;
+
+for (i = First(l); i.item; i = Next(i)) {
+    Printf(stdout,"%s\n", i.item);
+}
+
+Hash *h = (some hash);
+Iterator j;
+
+for (j = First(j); j.item; j= Next(j)) {
+    Printf(stdout,"%s : %s\n", j.key, j.item);
+}
+</pre>
+</div>
+
+</div>
+
+<H3><a name="Extending_nn20"></a>34.5.6 I/O</H3>
+
+
+Special I/O functions are used for all internal I/O.  These operations
+work on C <tt>FILE *</tt> objects, String objects, and special <tt>File</tt> objects
+(which are merely a wrapper around <tt>FILE *</tt>).
+
+<p>
+<b><tt>int Printf(String_or_FILE *f, const char *fmt, ...)</tt></b>
+</p>
+
+<div class="indent">
+Formatted I/O.   Same as the C <tt>fprintf()</tt> function except that output
+can also be directed to a string object.  Note:  the <tt>%s</tt> format
+specifier works with both strings and <tt>char *</tt>.  All other format
+operators have the same meaning.
+</div>
+
+<p>
+<b><tt>int Printv(String_or_FILE *f, String_or_char *arg1,..., NULL)</tt></b>
+</p>
+
+<div class="indent">
+Prints a variable number of strings arguments to the output.  The last
+argument to this function must be NULL.   The other arguments can either
+be <tt>char *</tt> or string objects.
+</div>
+
+<p>
+<b><tt>int Putc(int ch, String_or_FILE *f)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>fputc()</tt> function.
+</div>
+
+<p>
+<b><tt>int Write(String_or_FILE *f, void *buf, int len)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>write()</tt> function.
+</div>
+
+<p>
+<b><tt>int Read(String_or_FILE *f, void *buf, int maxlen)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>read()</tt> function.
+</div>
+
+<p>
+<b><tt>int Getc(String_or_FILE *f)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>fgetc()</tt> function.
+</div>
+
+<p>
+<b><tt>int Ungetc(int ch, String_or_FILE *f)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>ungetc()</tt> function.
+</div>
+
+<p>
+<b><tt>int Seek(String_or_FILE *f, int offset, int whence)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>seek()</tt> function.  <tt>offset</tt> is the number
+of bytes.  <tt>whence</tt> is one of <tt>SEEK_SET</tt>,<tt>SEEK_CUR</tt>,
+or <tt>SEEK_END</tt>..
+</div>
+
+<p>
+<b><tt>long Tell(String_or_FILE *f)</tt></b>
+</p>
+
+<div class="indent">
+Same as the C <tt>tell()</tt> function.
+</div>
+
+<p>
+<b><tt>File *NewFile(const char *filename, const char *mode)</tt></b>
+</p>
+
+<div class="indent">
+Create a File object using the <tt>fopen()</tt> library call.  This
+file differs from <tt>FILE *</tt> in that it can be placed in the standard
+SWIG containers (lists, hashes, etc.).
+</div>
+
+<p>
+<b><tt>File *NewFileFromFile(FILE *f)</tt></b>
+</p>
+
+<div class="indent">
+Create a File object wrapper around an existing <tt>FILE *</tt> object.
+</div>
+
+<p>
+<b><tt>int Close(String_or_FILE *f)</tt></b>
+</p>
+
+<div class="indent">
+<p>Closes a file.  Has no effect on strings.</p>
+
+<p>
+The use of the above I/O functions and strings play a critical role in SWIG.   It is
+common to see small code fragments of code generated using code like this:
+</p>
+
+<div class="code">
+<pre>
+/* Print into a string */
+String *s = NewString("");
+Printf(s,"Hello\n");
+for (i = 0; i &lt; 10; i++) {
+    Printf(s,"%d\n", i);
+}
+...
+/* Print string into a file */
+Printf(f, "%s\n", s);
+</pre>
+</div>
+
+<p>
+Similarly, the preprocessor and parser all operate on string-files.
+</p>
+
+</div>
+
+<H2><a name="Extending_nn21"></a>34.6 Navigating and manipulating parse trees</H2>
+
+
+Parse trees are built as collections of hash tables.   Each node is a hash table in which
+arbitrary attributes can be stored.  Certain attributes in the hash table provide links to
+other parse tree nodes.   The following macros can be used to move around the parse tree.
+
+<p>
+<b><tt>String *nodeType(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+Returns the node type tag as a string.  The returned string indicates the type of parse
+tree node.
+</div>
+
+<p>
+<b><tt>Node *nextSibling(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+Returns the next node in the parse tree.  For example, the next C declaration.
+</div>
+
+<p>
+<b><tt>Node *previousSibling(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+Returns the previous node in the parse tree.  For example, the previous C declaration.
+</div>
+
+<p>
+<b><tt>Node *firstChild(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+Returns the first child node.  For example, if <tt>n</tt> was a C++ class node, this would
+return the node for the first class member.
+</div>
+
+<p>
+<b><tt>Node *lastChild(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+Returns the last child node.   You might use this if you wanted to append a new
+node to the of a class.
+</div>
+
+<p>
+<b><tt>Node *parentNode(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+Returns the parent of node <tt>n</tt>.  Use this to move up the pass tree.
+</div>
+
+<p>
+The following macros can be used to change all of the above attributes.
+Normally, these functions are only used by the parser.  Changing them without
+knowing what you are doing is likely to be dangerous.
+</p>
+
+<p>
+<b><tt>void set_nodeType(Node *n, const String_or_char)</tt></b>
+</p>
+
+<div class="indent">
+Change the node type.
+tree node.
+</div>
+
+<p>
+<b><tt>void set_nextSibling(Node *n, Node *s)</tt></b>
+</p>
+
+<div class="indent">
+Set the next sibling.
+</div>
+
+<p>
+<b><tt>void set_previousSibling(Node *n, Node *s)</tt></b>
+</p>
+
+<div class="indent">
+Set the previous sibling.
+</div>
+
+<p>
+<b><tt>void set_firstChild(Node *n, Node *c)</tt></b>
+</p>
+
+<div class="indent">
+Set the first child node.
+</div>
+
+<p>
+<b><tt>void set_lastChild(Node *n, Node *c)</tt></b>
+</p>
+
+<div class="indent">
+Set the last child node.
+</div>
+
+<p>
+<b><tt>void set_parentNode(Node *n, Node *p)</tt></b>
+</p>
+
+<div class="indent">
+Set the parent node.
+</div>
+
+<p>
+The following utility functions are used to alter the parse tree (at your own risk)
+</p>
+
+<p>
+<b><tt>void appendChild(Node *parent, Node *child)</tt></b>
+</p>
+
+<div class="indent">
+Append a child to <tt>parent</tt>.  The appended node becomes the last child.
+</div>
+
+<p>
+<b><tt>void deleteNode(Node *node)</tt></b>
+</p>
+
+<div class="indent">
+Deletes a node from the parse tree.  Deletion reconnects siblings and properly updates
+the parent so that sibling nodes are unaffected.
+</div>
+
+<H2><a name="Extending_nn22"></a>34.7 Working with attributes</H2>
+
+
+<p>
+Since parse tree nodes are just hash tables, attributes are accessed using the <tt>Getattr()</tt>,
+<tt>Setattr()</tt>, and <tt>Delattr()</tt> operations.  For example:
+</p>
+
+<div class="code">
+<pre>
+int functionHandler(Node *n) {
+    String *name    = Getattr(n,"name");
+    String *symname = Getattr(n,"sym:name");
+    SwigType *type  = Getattr(n,"type");
+    ...
+}
+</pre>
+</div>
+
+<p>
+New attributes can be freely attached to a node as needed.   However, when new attributes
+are attached during code generation, they should be prepended with a namespace prefix.
+For example:
+</p>
+
+<div class="code">
+<pre>
+...
+Setattr(n,"python:docstring", doc);     /* Store docstring */
+...
+</pre>
+</div>
+
+<p>
+A quick way to check the value of an attribute is to use the <tt>checkAttribute()</tt> function like this:
+</p>
+
+<div class="code">
+<pre>
+if (checkAttribute(n,"storage","virtual")) {
+   /* n is virtual */
+   ...
+}
+</pre>
+</div>
+
+<p>
+Changing the values of existing attributes is allowed and is sometimes done to implement
+node transformations.   However, if a function/method modifies a node, it is required to restore
+modified attributes to their original values.  To simplify the task of saving/restoring attributes,
+the following functions are used:
+</p>
+
+<p>
+<b><tt>int Swig_save(const char *ns, Node *n, const char *name1, const char *name2, ..., NIL)</tt></b>
+</p>
+
+<div class="indent">
+Saves a copy of attributes <tt>name1</tt>, <tt>name2</tt>, etc. from node <tt>n</tt>.
+Copies of the attributes are actually resaved in the node in a different namespace which is
+set by the <tt>ns</tt> argument.   For example, if you call <tt>Swig_save("foo",n,"type",NIL)</tt>,
+then the "type" attribute will be copied and saved as "foo:type".  The namespace name itself is stored in
+the "view" attribute of the node.  If necessary, this can be examined to find out where previous
+values of attributes might have been saved.
+</div>
+
+<p>
+<b><tt>int Swig_restore(Node *n)</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Restores the attributes saved by the previous call to <tt>Swig_save()</tt>.  Those
+attributes that were supplied to <tt>Swig_save()</tt> will be restored to their
+original values.
+</p>
+
+<p>
+The <tt>Swig_save()</tt> and <tt>Swig_restore()</tt> functions must always be used as a pair.
+That is, every call to <tt>Swig_save()</tt> must have a matching call to <tt>Swig_restore()</tt>.
+Calls can be nested if necessary.  Here is an example that shows how the functions might be used:
+</p>
+
+<div class="code">
+<pre>
+int variableHandler(Node *n) {
+    Swig_save("variableHandler",n,"type","sym:name",NIL);
+    String *symname = Getattr(n,"sym:name");
+    SwigType *type  = Getattr(n,"type");
+    ...
+    Append(symname,"_global");         // Change symbol name
+    SwigType_add_pointer(type);        // Add pointer
+    ...
+    generate wrappers
+    ...
+    Swig_restore(n);                  // Restore original values
+    return SWIG_OK;
+}
+</pre>
+</div>
+
+</div>
+
+<p>
+<b><tt>int Swig_require(const char *ns, Node *n, const char *name1, const char *name2, ..., NIL)</tt></b>
+</p>
+
+<div class="indent">
+This is an enhanced version of <tt>Swig_save()</tt> that adds error checking.  If an attribute
+name is not present in <tt>n</tt>, a failed assertion results and SWIG terminates with a fatal
+error.  Optionally, if an attribute name is specified as "*<em>name</em>", a copy of the
+attribute is saved as with <tt>Swig_save()</tt>.  If an attribute is specified as "?<em>name</em>",
+the attribute is optional.   <tt>Swig_restore()</tt> must always be called after using this
+function.
+</div>
+
+<H2><a name="Extending_nn23"></a>34.8 Type system</H2>
+
+
+<p>
+SWIG implements the complete C++ type system including typedef, inheritance,
+pointers, references, and pointers to members.   A detailed discussion of
+type theory is impossible here.   However, let's cover the highlights.
+</p>
+
+<H3><a name="Extending_nn24"></a>34.8.1 String encoding of types</H3>
+
+
+<p>
+All types in SWIG consist of a base datatype and a collection of type
+operators that are applied to the base.   A base datatype is almost
+always some kind of primitive type such as <tt>int</tt> or <tt>double</tt>.
+The operators consist of things like pointers, references, arrays, and so forth.
+Internally, types are represented as strings that are constructed in a very
+precise manner.  Here are some examples:
+</p>
+
+<div class="diagram">
+<pre>
+C datatype                     SWIG encoding (strings)
+-----------------------------  --------------------------
+int                            "int"
+int *                          "p.int"
+const int *                    "p.q(const).int"
+int (*x)(int,double)           "p.f(int,double).int"
+int [20][30]                   "a(20).a(30).int"
+int (F::*)(int)                "m(F).f(int).int"
+vector&lt;int&gt; *                  "p.vector&lt;(int)&gt;"
+</pre>
+</div>
+
+<p>
+Reading the SWIG encoding is often easier than figuring out the C code---just
+read it from left to right.  For a type of "p.f(int,double).int" is
+a "pointer to a function(int,double) that returns int".
+</p>
+
+<p>
+The following operator encodings are used in type strings:
+</p>
+
+<div class="diagram">
+<pre>
+Operator              Meaning
+-------------------   -------------------------------
+p.                    Pointer to
+a(n).                 Array of dimension n
+r.                    C++ reference
+m(class).             Member pointer to class
+f(args).              Function.
+q(qlist).             Qualifiers
+</pre>
+</div>
+
+<p>
+In addition, type names may be parameterized by templates.  This is
+represented by enclosing the template parameters in <tt>&lt;(
+... )&gt;</tt>.  Variable length arguments are represented by the
+special base type of <tt>v(...)</tt>.
+</p>
+
+<p>
+If you want to experiment with type encodings, the raw type strings can
+be inserted into an interface file using backticks `` wherever a type
+is expected.  For instance, here is
+an extremely perverted example:
+</p>
+
+<div class="diagram">
+<pre>
+`p.a(10).p.f(int,p.f(int).int)` foo(int, int (*x)(int));
+</pre>
+</div>
+
+<p>
+This corresponds to the immediately obvious C declaration:
+</p>
+
+<div class="diagram">
+<pre>
+(*(*foo(int,int (*)(int)))[10])(int,int (*)(int));
+</pre>
+</div>
+
+<p>
+Aside from the potential use of this declaration on a C programming quiz,
+it motivates the use of the special SWIG encoding of types.   The SWIG
+encoding is much easier to work with because types can be easily examined,
+modified, and constructed using simple string operations (comparison,
+substrings, concatenation, etc.).   For example, in the parser, a declaration
+like this
+</p>
+
+<div class="code">
+<pre>
+int *a[30];
+</pre>
+</div>
+
+<p>
+is processed in a few pieces.  In this case, you have the base type
+"<tt>int</tt>" and the declarator of type "<tt>a(30).p.</tt>".  To
+make the final type, the two parts are just joined together using
+string concatenation.
+</p>
+
+<H3><a name="Extending_nn25"></a>34.8.2 Type construction</H3>
+
+
+<p>
+The following functions are used to construct types.  You should use
+these functions instead of trying to build the type strings yourself.
+</p>
+
+<p>
+<b><tt>void SwigType_add_pointer(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Adds a pointer to <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_del_pointer(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Removes a single pointer from <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_add_reference(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Adds a reference to <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_add_array(SwigType *ty, String_or_char *dim)</tt></b>
+</p>
+
+<div class="indent">
+Adds an array with dimension <tt>dim</tt> to <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_del_array(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Removes a single array dimension from <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>int SwigType_array_ndim(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Returns number of array dimensions of <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>String* SwigType_array_getdim(SwigType *ty,int n)</tt></b>
+</p>
+
+<div class="indent">
+Returns <tt>n</tt>th array dimension of <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_array_setdim(SwigType *ty, int n, const String_or_char *rep)</tt></b>
+</p>
+
+<div class="indent">
+Sets <tt>n</tt>th array dimensions of <tt>ty</tt> to <tt>rep</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_add_qualifier(SwigType *ty, String_or_char *q)</tt></b>
+</p>
+
+<div class="indent">
+Adds a type qualifier <tt>q</tt> to <tt>ty</tt>.  <tt>q</tt> is typically
+<tt>"const"</tt> or <tt>"volatile"</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_add_memberpointer(SwigType *ty, String_or_char *cls)</tt></b>
+</p>
+
+<div class="indent">
+Adds a pointer to a member of class <tt>cls</tt> to <tt>ty</tt>.
+</div>
+
+<p>
+<b><tt>void SwigType_add_function(SwigType *ty, ParmList *p)</tt></b>
+</p>
+
+<div class="indent">
+Adds a function to <tt>ty</tt>.  <tt>p</tt> is a linked-list of parameter
+nodes as generated by the parser. See the section on parameter lists
+for details about the representation.
+</div>
+
+<p>
+<b><tt>void SwigType_add_template(SwigType *ty, ParmList *p)</tt></b>
+</p>
+
+<div class="indent">
+Adds a template to <tt>ty</tt>.  <tt>p</tt> is a linked-list of parameter
+nodes as generated by the parser. See the section on parameter lists
+for details about the representation.
+</div>
+
+<p>
+<b><tt>SwigType *SwigType_pop(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Removes the last type constructor from <tt>ty</tt> and returns it.
+<tt>ty</tt> is modified.
+</div>
+
+<p>
+<b><tt>void SwigType_push(SwigType *ty, SwigType *op)</tt></b>
+</p>
+
+<div class="indent">
+Pushes the type operators in <tt>op</tt> onto type <tt>ty</tt>.  The
+opposite of <tt>SwigType_pop()</tt>.
+</div>
+
+<p>
+<b><tt>SwigType *SwigType_pop_arrays(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Removes all leading array operators from <tt>ty</tt> and returns them.
+<tt>ty</tt> is modified.   For example, if <tt>ty</tt> is <tt>"a(20).a(10).p.int"</tt>,
+then this function would return <tt>"a(20).a(10)."</tt> and modify <tt>ty</tt>
+so that it has the value <tt>"p.int"</tt>.
+</div>
+
+<p>
+<b><tt>SwigType *SwigType_pop_function(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Removes a function operator from <tt>ty</tt> including any qualification.
+<tt>ty</tt> is modified.   For example, if <tt>ty</tt> is <tt>"f(int).int"</tt>,
+then this function would return <tt>"f(int)."</tt> and modify <tt>ty</tt>
+so that it has the value <tt>"int"</tt>.
+</div>
+
+<p>
+<b><tt>SwigType *SwigType_base(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Returns the base type of a type.  For example, if <tt>ty</tt> is
+<tt>"p.a(20).int"</tt>, this function would return <tt>"int"</tt>.
+<tt>ty</tt> is unmodified.
+</div>
+
+<p>
+<b><tt>SwigType *SwigType_prefix(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Returns the prefix of a type. For example, if <tt>ty</tt> is
+<tt>"p.a(20).int"</tt>, this function would return <tt>"p.a(20)."</tt>.
+<tt>ty</tt> is unmodified.
+</div>
+
+<H3><a name="Extending_nn26"></a>34.8.3 Type tests</H3>
+
+
+<p>
+The following functions can be used to test properties of a datatype.
+</p>
+
+<p>
+<b><tt>int SwigType_ispointer(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a standard pointer.
+</div>
+
+<p>
+<b><tt>int SwigType_ismemberpointer(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a member pointer.
+</div>
+
+<p>
+<b><tt>int SwigType_isreference(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a C++ reference.
+</div>
+
+<p>
+<b><tt>int SwigType_isarray(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is an array.
+</div>
+
+<p>
+<b><tt>int SwigType_isfunction(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a function.
+</div>
+
+<p>
+<b><tt>int SwigType_isqualifier(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a qualifier.
+</div>
+
+<p>
+<b><tt>int SwigType_issimple(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a simple type.  No operators applied.
+</div>
+
+<p>
+<b><tt>int SwigType_isconst(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a const type.
+</div>
+
+<p>
+<b><tt>int SwigType_isvarargs(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a varargs type.
+</div>
+
+<p>
+<b><tt>int SwigType_istemplate(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> is a templatized type.
+</div>
+
+<H3><a name="Extending_nn27"></a>34.8.4 Typedef and inheritance</H3>
+
+
+<p>
+The behavior of <tt>typedef</tt> declaration is to introduce a type alias.
+For instance, <tt>typedef int Integer</tt> makes the identifier
+<tt>Integer</tt> an alias for <tt>int</tt>.  The treatment of typedef in
+SWIG is somewhat complicated due to the pattern matching rules that get applied
+in typemaps and the fact that SWIG prefers to generate wrapper code
+that closely matches the input to simplify debugging (a user will see the
+typedef names used in their program instead of the low-level primitive C
+datatypes).
+</p>
+
+<p>
+To handle <tt>typedef</tt>, SWIG builds a collection of trees containing typedef relations. For example,
+</p>
+
+<div class="code">
+<pre>
+typedef int Integer;
+typedef Integer *IntegerPtr;
+typedef int Number;
+typedef int Size;
+</pre>
+</div>
+
+<p>
+produces two trees like this:
+</p>
+
+<div class="diagram">
+<pre>
+                 int               p.Integer
+               ^  ^  ^                 ^
+              /   |   \                |
+             /    |    \               |
+        Integer  Size   Number    IntegerPtr
+</pre>
+</div>
+
+<p>
+To resolve a single typedef relationship, the following function is used:
+</p>
+
+<p>
+<b><tt>SwigType *SwigType_typedef_resolve(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Checks if <tt>ty</tt> can be reduced to a new type via typedef.  If so,
+returns the new type.  If not, returns NULL.
+</div>
+
+<p>
+Typedefs are only resolved in simple typenames that appear in a type.
+For example, the type base name and in function parameters.   When
+resolving types, the process starts in the leaf nodes and moves up
+the tree towards the root.   Here are a few examples that show how it works:
+</p>
+
+<div class="diagram">
+<pre>
+Original type            After typedef_resolve()
+------------------------ -----------------------
+Integer                  int
+a(30).Integer            int
+p.IntegerPtr             p.p.Integer
+p.p.Integer              p.p.int
+</pre>
+</div>
+
+<p>
+For complicated types, the process can be quite involved.  Here is the
+reduction of a function pointer:
+</p>
+
+<div class="diagram">
+<pre>
+p.f(Integer, p.IntegerPtr, Size).Integer          : Start
+p.f(Integer, p.IntegerPtr, Size).int
+p.f(int, p.IntegerPtr, Size).int
+p.f(int, p.p.Integer, Size).int
+p.f(int, p.p.int, Size).int
+p.f(int, p.p.int, int).int                        : End
+</pre>
+</div>
+
+<p>
+Two types are equivalent if their full type reductions are the same.
+The following function will fully reduce a datatype:
+</p>
+
+<p>
+<b><tt>SwigType *SwigType_typedef_resolve_all(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Fully reduces <tt>ty</tt> according to typedef rules.  Resulting datatype
+will consist only of primitive typenames.
+</div>
+
+<H3><a name="Extending_nn28"></a>34.8.5 Lvalues</H3>
+
+
+<p>
+When generating wrapper code, it is necessary to emit datatypes that can
+be used on the left-hand side of an assignment operator (an lvalue). However,
+not all C datatypes can be used in this way---especially arrays and
+const-qualified types.  To generate a type that can be used as an lvalue,
+use the following function:
+</p>
+
+<p>
+<b><tt>SwigType *SwigType_ltype(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Converts type <tt>ty</tt> to a type that can be used as an lvalue in
+assignment.  The resulting type is stripped of qualifiers and arrays are
+converted to a pointers.
+</div>
+
+<p>
+The creation of lvalues is fully aware of typedef and other aspects
+of the type system.  Therefore, the creation of an lvalue may result in
+unexpected results.  Here are a few examples:
+</p>
+
+<div class="code">
+<pre>
+typedef double Matrix4[4][4];
+Matrix4 x;    // type = 'Matrix4', ltype='p.a(4).double'
+
+typedef const char * Literal;
+Literal y;    // type = 'Literal', ltype='p.char'
+</pre>
+</div>
+
+<H3><a name="Extending_nn29"></a>34.8.6 Output functions</H3>
+
+
+<p>
+The following functions produce strings that are suitable for output.
+</p>
+
+<p>
+<b><tt>String *SwigType_str(SwigType *ty, String_or_char *id = 0)</tt></b>
+</p>
+
+<div class="indent">
+Generates a C string for a datatype.  <tt>id</tt> is an optional declarator.
+For example, if <tt>ty</tt> is "p.f(int).int" and <tt>id</tt> is "foo", then
+this function produces "<tt>int (*foo)(int)</tt>".   This function is
+used to convert string-encoded types back into a form that is valid C syntax.
+</div>
+
+<p>
+<b><tt>String *SwigType_lstr(SwigType *ty, String_or_char *id = 0)</tt></b>
+</p>
+
+<div class="indent">
+This is the same as <tt>SwigType_str()</tt> except that the result
+is generated from the type's lvalue (as generated from SwigType_ltype).
+</div>
+
+<p>
+<b><tt>String *SwigType_lcaststr(SwigType *ty, String_or_char *id = 0)</tt></b>
+</p>
+
+<div class="indent">
+Generates a casting operation that converts from type <tt>ty</tt> to its
+lvalue.  <tt>id</tt> is an optional name to include in the cast.  For example,
+if <tt>ty</tt> is "<tt>q(const).p.char</tt>" and <tt>id</tt> is "<tt>foo</tt>",
+this function produces the string "<tt>(char *) foo</tt>".
+</div>
+
+<p>
+<b><tt>String *SwigType_rcaststr(SwigType *ty, String_or_char *id = 0)</tt></b>
+</p>
+
+<div class="indent">
+Generates a casting operation that converts from a type's lvalue to a
+type equivalent to <tt>ty</tt>. <tt>id</tt> is an optional name to
+include in the cast.  For example, if <tt>ty</tt> is
+"<tt>q(const).p.char</tt>" and <tt>id</tt> is "<tt>foo</tt>", this
+function produces the string "<tt>(const char *) foo</tt>".
+</div>
+
+<p>
+<b><tt>String *SwigType_manglestr(SwigType *ty)</tt></b>
+</p>
+
+<div class="indent">
+Generates a mangled string encoding of type <tt>ty</tt>.   The
+mangled string only contains characters that are part of a valid
+C identifier.   The resulting string is used in various parts of
+SWIG, but is most commonly associated with type-descriptor objects
+that appear in wrappers (e.g., <tt>SWIGTYPE_p_double</tt>).
+</div>
+
+<H2><a name="Extending_nn30"></a>34.9 Parameters</H2>
+
+
+<p>
+Several type-related functions involve parameter lists.  These include
+functions and templates.  Parameter list are represented as a list of
+nodes with the following attributes:
+</p>
+
+<div class="diagram">
+<pre>
+"type"        -  Parameter type  (required)
+"name"        -  Parameter name  (optional)
+"value"       -  Initializer     (optional)
+</pre>
+</div>
+
+<p>
+Typically parameters are denoted in the source by using a typename of
+<tt>Parm *</tt> or <tt>ParmList *</tt>.  To walk a parameter list, simply use
+code like this:
+</p>
+
+<div class="diagram">
+<pre>
+Parm *parms;
+Parm *p;
+for (p = parms; p; p = nextSibling(p)) {
+    SwigType *type  = Getattr(p,"type");
+    String   *name  = Getattr(p,"name");
+    String   *value = Getattr(p,"value");
+    ...
+}
+</pre>
+</div>
+
+<p>
+Note: this code is exactly the same as what you would use to walk parse tree nodes.
+</p>
+
+<p>
+An empty list of parameters is denoted by a NULL pointer.
+</p>
+
+<p>
+Since parameter lists are fairly common, the following utility functions are provided
+to manipulate them:
+</p>
+
+<p>
+<b><tt>Parm  *CopyParm(Parm *p);</tt></b>
+</p>
+
+<div class="indent">
+Copies a single parameter.
+</div>
+
+<p>
+<b><tt>ParmList  *CopyParmList(ParmList *p);</tt></b>
+</p>
+
+<div class="indent">
+Copies an entire list of parameters.
+</div>
+
+<p>
+<b><tt>int ParmList_len(ParmList *p);</tt></b>
+</p>
+
+<div class="indent">
+Returns the number of parameters in a parameter list.
+</div>
+
+<p>
+<b><tt>String *ParmList_str(ParmList *p);</tt></b>
+</p>
+
+<div class="indent">
+Converts a parameter list into a C string.  For example,
+produces a string like "<tt>(int *p, int n, double x);</tt>".
+</div>
+
+<p>
+<b><tt>String *ParmList_protostr(ParmList *p);</tt></b>
+</p>
+
+<div class="indent">
+The same as <tt>ParmList_str()</tt> except that parameter names are not
+included.  Used to emit prototypes.
+</div>
+
+<p>
+<b><tt>int ParmList_numrequired(ParmList *p);</tt></b>
+</p>
+
+<div class="indent">
+Returns the number of required (non-optional) arguments in <tt>p</tt>.
+</div>
+
+<H2><a name="Extending_nn31"></a>34.10 Writing a Language Module</H2>
+
+
+<p>
+One of the easiest routes to supporting a new language module is to copy an already
+supported language module implementation and modify it.
+Be sure to choose a language that is similar in nature to the new language.
+All language modules follow a similar structure and 
+this section briefly outlines the steps needed to create a bare-bones
+language module from scratch.
+Since the code is relatively easy to read, this section
+describes the creation of a minimal Python module.   You should be able to extrapolate
+this to other languages.
+</p>
+
+<H3><a name="Extending_nn32"></a>34.10.1 Execution model</H3>
+
+
+<p>
+Code generation modules are defined by inheriting from the <tt>Language</tt> class,
+currently defined in the <tt>Source/Modules</tt> directory of SWIG.  Starting from
+the parsing of command line options, all aspects of code generation are controlled by
+different methods of the <tt>Language</tt> that must be defined by your module.
+</p>
+
+<H3><a name="Extending_nn33"></a>34.10.2 Starting out</H3>
+
+
+<p>
+To define a new language module, first create a minimal implementation using
+this example as a guide:
+</p>
+
+<div class="code">
+<pre>
+#include "swigmod.h"
+
+class PYTHON : public Language {
+public:
+
+  virtual void main(int argc, char *argv[]) {
+    printf("I'm the Python module.\n");
+  }
+
+  virtual int top(Node *n) {
+    printf("Generating code.\n");
+    return SWIG_OK;
+  }
+
+};
+
+extern "C" Language *
+swig_python(void) {
+  return new PYTHON();
+}
+</pre>
+</div>
+
+<p>
+The "swigmod.h" header file contains, among other things, the declaration
+of the <tt>Language</tt> base class and so you should include it at the top
+of your language module's source file. Similarly, the "swigconfig.h" header
+file contains some other useful definitions that you may need. Note that you
+should <em>not</em> include any header files that are installed with the
+target language. That is to say, the implementation of the SWIG Python module
+shouldn't have any dependencies on the Python header files. The wrapper code
+generated by SWIG will almost always depend on some language-specific C/C++
+header files, but SWIG itself does not.
+</p>
+
+<p>
+Give your language class a reasonable name, usually the same as the target language.
+By convention, these class names are all uppercase (e.g. "PYTHON" for the Python
+language module) but this is not a requirement. This class will ultimately consist
+of a number of overrides of the virtual functions declared in the <tt>Language</tt>
+base class, in addition to any language-specific member functions and data you
+need. For now, just use the dummy implementations shown above.
+</p>
+
+<p>
+The language module ends with a factory function, <tt>swig_python()</tt>, that simply
+returns a new instance of the language class. As shown, it should be declared with the
+<tt>extern "C"</tt> storage qualifier so that it can be called from C code. It should
+also return a pointer to the base class (<tt>Language</tt>) so that only the interface
+(and not the implementation) of your language module is exposed to the rest of SWIG.
+</p>
+
+<p>
+Save the code for your language module in a file named "<tt>python.cxx</tt>" and.
+place this file in the <tt>Source/Modules</tt> directory of the SWIG distribution.
+To ensure that your module is compiled into SWIG along with the other language modules,
+modify the file <tt>Source/Modules/Makefile.am</tt> to include the additional source
+files.  In addition, modify the file <tt>Source/Modules/swigmain.cxx</tt>
+with an additional command line option that activates the module. Read the source---it's straightforward.
+</p>
+
+<p>
+Next, at the top level of the SWIG distribution, re-run the <tt>autogen.sh</tt> script
+to regenerate the various build files:
+</p>
+
+<div class="shell">
+<pre>
+$ <b>./autogen.sh</b>
+</pre>
+</div>
+
+<p>
+Next re-run <tt>configure</tt> to regenerate all of the Makefiles:
+</p>
+
+<div class="shell">
+<pre>
+$ <b>./configure</b>
+</pre>
+</div>
+
+<p>
+Finally, rebuild SWIG with your module added:
+</p>
+
+<div class="shell">
+<pre>
+$ <b>make</b>
+</pre>
+</div>
+
+<p>
+Once it finishes compiling, try running SWIG with the command-line option
+that activates your module. For example, <tt>swig -python foo.i</tt>. The
+messages from your new module should appear.
+</p>
+
+<H3><a name="Extending_nn34"></a>34.10.3 Command line options</H3>
+
+
+<p>
+When SWIG starts, the command line options are passed to your language module.  This occurs
+before any other processing occurs (preprocessing, parsing, etc.).   To capture the
+command line options, simply use code similar to this:
+</p>
+
+<div class="code">
+<pre>
+void Language::main(int argc, char *argv[]) {
+  for (int i = 1; i &lt; argc; i++) {
+      if (argv[i]) {
+          if(strcmp(argv[i],"-interface") == 0) {
+            if (argv[i+1]) {
+              interface = NewString(argv[i+1]);
+              Swig_mark_arg(i);
+              Swig_mark_arg(i+1);
+              i++;
+            } else {
+              Swig_arg_error();
+            }
+	  } else if (strcmp(argv[i],"-globals") == 0) {
+	    if (argv[i+1]) {
+	      global_name = NewString(argv[i+1]);
+	      Swig_mark_arg(i);
+	      Swig_mark_arg(i+1);
+	      i++;
+	    } else {
+	      Swig_arg_error();
+	    }
+	  } else if ( (strcmp(argv[i],"-proxy") == 0)) {
+	    proxy_flag = 1;
+	    Swig_mark_arg(i);
+	  } else if (strcmp(argv[i],"-keyword") == 0) {
+	    use_kw = 1;
+	    Swig_mark_arg(i);
+	  } else if (strcmp(argv[i],"-help") == 0) {
+	    fputs(usage,stderr);
+	  }
+          ...
+      }
+  }
+}
+</pre>
+</div>
+
+<p>
+The exact set of options depends on what you want to do in your module.   Generally,
+you would use the options to change code generation modes or to print diagnostic information.
+</p>
+
+<p>
+If a module recognizes an option, it should always call <tt>Swig_mark_arg()</tt>
+to mark the option as valid.   If you forget to do this, SWIG will terminate with an
+unrecognized command line option error.
+</p>
+
+<H3><a name="Extending_nn35"></a>34.10.4 Configuration and preprocessing</H3>
+
+
+<p>
+In addition to looking at command line options, the <tt>main()</tt> method is responsible
+for some initial configuration of the SWIG library and preprocessor.   To do this,
+insert some code like this:
+</p>
+
+<div class="code">
+<pre>
+void main(int argc, char *argv[]) {
+   ... command line options ...
+
+   /* Set language-specific subdirectory in SWIG library */
+   SWIG_library_directory("python");
+
+   /* Set language-specific preprocessing symbol */
+   Preprocessor_define("SWIGPYTHON 1", 0);
+
+   /* Set language-specific configuration file */
+   SWIG_config_file("python.swg");
+
+   /* Set typemap language (historical) */
+   SWIG_typemap_lang("python");
+}
+</pre>
+</div>
+
+<p>
+The above code does several things--it registers the name of the
+language module with the core, it supplies some preprocessor macro definitions
+for use in input files (so that they can determine the target language), and
+it registers a start-up file.   In this case, the file <tt>python.swg</tt> will
+be parsed before any part of the user-supplied input file.
+</p>
+
+<p>
+Before proceeding any further, create a directory for your module in the SWIG
+library (The <tt>Lib</tt> directory).   Now, create a configuration file in the
+directory.  For example, <tt>python.swg</tt>.
+</p>
+
+<p>
+Just to review, your language module should now consist of two files--
+an implementation file <tt>python.cxx</tt> and a configuration file
+<tt>python.swg</tt>.
+</p>
+
+<H3><a name="Extending_nn36"></a>34.10.5 Entry point to code generation</H3>
+
+
+<p>
+SWIG is a multi-pass compiler.  Once the <tt>main()</tt> method has
+been invoked, the language module does not execute again until
+preprocessing, parsing, and a variety of semantic analysis passes have
+been performed.  When the core is ready to start generating wrappers,
+it invokes the <tt>top()</tt> method of your language class.  The
+argument to <tt>top</tt> is a single parse tree node that corresponds to
+the top of the entire parse tree.
+</p>
+
+<p>
+To get the code generation process started, the <tt>top()</tt> procedure needs
+to do several things:
+</p>
+
+<ul>
+<li>Initialize the wrapper code output.
+<li>Set the module name.
+<li>Emit common initialization code.
+<li>Emit code for all of the child nodes.
+<li>Finalize the wrapper module and cleanup.
+</ul>
+
+<p>
+An outline of <tt>top()</tt> might be as follows:
+</p>
+
+<div class="code">
+<pre>
+int Python::top(Node *n) {
+
+   /* Get the module name */
+   String *module = Getattr(n,"name");
+
+   /* Get the output file name */
+   String *outfile = Getattr(n,"outfile");
+
+   /* Initialize I/O (see next section) */
+   ...
+
+   /* Output module initialization code */
+   ...
+
+   /* Emit code for children */
+   Language::top(n);
+
+   ...
+   /* Cleanup files */
+   ...
+
+   return SWIG_OK;
+}
+</pre>
+</div>
+
+<H3><a name="Extending_nn37"></a>34.10.6 Module I/O and wrapper skeleton</H3>
+
+
+<!-- please report bugs in this section to mgossage -->
+
+
+<p>
+Within SWIG wrappers, there are four main sections. These are (in order)
+</p>
+
+<ul>
+<li>runtime: This section has most of the common SWIG runtime code
+<li>header: This section holds declarations and inclusions from the .i file
+<li>wrapper: This section holds all the wrappering code
+<li>init: This section holds the module initalisation function
+(the entry point for the interpreter)
+</ul>
+<p>
+Different parts of the SWIG code will fill different sections,
+then upon completion of the wrappering all the sections will be saved
+to the wrapper file.
+</p>
+<p>
+To perform this will require several additions to the code in various places,
+such as:
+</p>
+
+<div class="code">
+<pre>
+class PYTHON : public Language {
+protected:
+   /* General DOH objects used for holding the strings */
+   File *f_runtime;
+   File *f_header;
+   File *f_wrappers;
+   File *f_init;
+
+public:
+   ...
+
+};
+
+int Python::top(Node *n) {
+
+   ...
+
+   /* Initialize I/O */
+   f_runtime = NewFile(outfile, "w");
+   if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+   }
+   f_init = NewString("");
+   f_header = NewString("");
+   f_wrappers = NewString("");
+
+   /* Register file targets with the SWIG file handler */
+   Swig_register_filebyname("header", f_header);
+   Swig_register_filebyname("wrapper", f_wrappers);
+   Swig_register_filebyname("runtime", f_runtime);
+   Swig_register_filebyname("init", f_init);
+
+   /* Output module initialization code */
+   ...
+
+   /* Emit code for children */
+   Language::top(n);
+
+   ...
+   /* Write all to the file */
+   Dump(f_header, f_runtime);
+   Dump(f_wrappers, f_runtime);
+   Wrapper_pretty_print(f_init, f_runtime);
+
+   /* Cleanup files */
+   Delete(f_header);
+   Delete(f_wrappers);
+   Delete(f_init);
+   Close(f_runtime);
+   Delete(f_runtime);
+
+   return SWIG_OK;
+}
+</pre>
+</div>
+
+<p>
+Using this to process a file will generate a wrapper file, however the
+wrapper will only consist of the common SWIG code as well as any inline
+code which was written in the .i file. It does not contain any wrappers for
+any of the functions or classes.
+</p>
+
+<p>
+The code to generate the wrappers are the various member functions, which
+currently have not been touched. We will look at <tt>functionWrapper()</tt> as this
+is the most commonly used function. In fact many of the other wrapper routines
+will call this to do their work.
+</p>
+<p>
+A simple modification to write some basic details to the wrapper looks like this:
+</p>
+
+<div class="code">
+<pre>
+int Python::functionWrapper(Node *n) {
+  /* Get some useful attributes of this function */
+  String   *name   = Getattr(n,"sym:name");
+  SwigType *type   = Getattr(n,"type");
+  ParmList *parms  = Getattr(n,"parms");
+  String   *parmstr= ParmList_str_defaultargs(parms); // to string
+  String   *func   = SwigType_str(type, NewStringf("%s(%s)", name, parmstr));
+  String   *action = Getattr(n,"wrap:action");
+
+  Printf(f_wrappers,"functionWrapper   : %s\n", func);
+  Printf(f_wrappers,"           action : %s\n", action);
+  return SWIG_OK;
+}
+</pre>
+</div>
+
+<p>
+This will now produce some useful information within your wrapper file.
+</p>
+
+<div class="shell">
+<pre>
+functionWrapper   : void delete_Shape(Shape *self)
+           action : delete arg1;
+
+functionWrapper   : void Shape_x_set(Shape *self,double x)
+           action : if (arg1) (arg1)-&gt;x = arg2;
+
+functionWrapper   : double Shape_x_get(Shape *self)
+           action : result = (double) ((arg1)-&gt;x);
+
+functionWrapper   : void Shape_y_set(Shape *self,double y)
+           action : if (arg1) (arg1)-&gt;y = arg2;
+...
+</pre>
+</div>
+
+<H3><a name="Extending_nn38"></a>34.10.7 Low-level code generators</H3>
+
+
+<!-- please report bugs in this section to mgossage -->
+
+<p>
+As ingenious as SWIG is, and despite all its capabilities and the power of
+its parser, the Low-level code generation takes a lot of work to write
+properly. Mainly because every language insists on its own manner of
+interfacing to C/C++. To write the code generators you will need a good
+understanding of how to manually write an interface to your chosen
+language, so make sure you have your documentation handy.
+</p>
+<p>
+At this point it is also probably a good idea to take a very simple file
+(just one function), and try letting SWIG generate wrappers for many
+different languages. Take a look at all of the wrappers generated, and decide
+which one looks closest to the language you are trying to wrap.
+This may help you to decide which code to look at.
+</p>
+<p>
+In general most language wrappers look a little like this:
+</p>
+<div class="code">
+<pre>
+/* wrapper for TYPE3 some_function(TYPE1,TYPE2); */
+RETURN_TYPE _wrap_some_function(ARGS){
+  TYPE1 arg1;
+  TYPE2 arg2;
+  TYPE3 result;
+
+  if(ARG1 is not of TYPE1) goto fail;
+  arg1=(convert ARG1);
+  if(ARG2 is not of TYPE2) goto fail;
+  arg2=(convert ARG2);
+
+  result=some_function(arg1,arg2);
+
+  convert 'result' to whatever the language wants;
+
+  do any tidy up;
+
+  return ALL_OK;
+
+  fail:
+  do any tidy up;
+  return ERROR;
+}
+</pre>
+</div>
+
+<p>
+Yes, it is rather vague and not very clear. But each language works differently
+so this will have to do for now.
+</p>
+<p>
+Tackling this problem will be done in two stages:
+</p>
+<ul>
+<li>The skeleton: the function wrapper, and call, but without the conversion
+<li>The conversion: converting the arguments to-from what the language wants
+</ul>
+<p>
+The first step will be done in the code, the second will be done in typemaps.
+</p>
+<p>
+Our first step will be to write the code for <tt>functionWrapper()</tt>. What is
+shown below is <b>NOT</b> the solution, merely a step in the right direction.
+There are a lot of issues to address.
+</p>
+<ul>
+<li>Variable length and default parameters
+<li>Typechecking and number of argument checks
+<li>Overloaded functions
+<li>Inout and Output only arguments
+</ul>
+<div class="code">
+<pre>
+virtual int functionWrapper(Node *n) {
+  /* get useful atributes */
+  String   *name   = Getattr(n,"sym:name");
+  SwigType *type   = Getattr(n,"type");
+  ParmList *parms  = Getattr(n,"parms");
+  ...
+
+  /* create the wrapper object */
+  Wrapper *wrapper = NewWrapper();
+
+  /* create the functions wrappered name */
+  String *wname = Swig_name_wrapper(iname);
+
+  /* deal with overloading */
+  ....
+
+  /* write the wrapper function definition */
+  Printv(wrapper-&gt;def,"RETURN_TYPE ", wname, "(ARGS) {",NIL);
+
+  /* if any additional local variable needed, add them now */
+  ...
+
+  /* write the list of locals/arguments required */
+  emit_args(type, parms, wrapper);
+
+  /* check arguments */
+  ...
+
+  /* write typemaps(in) */
+  ....
+
+  /* write constriants */
+  ....
+
+  /* Emit the function call */
+  emit_action(n,wrapper);
+
+  /* return value if necessary  */
+  ....
+
+  /* write typemaps(out) */
+  ....
+
+  /* add cleanup code */
+  ....
+
+  /* Close the function(ok) */
+  Printv(wrapper-&gt;code, "return ALL_OK;\n", NIL);
+
+  /* add the failure cleanup code */
+  ...
+
+  /* Close the function(error) */
+  Printv(wrapper-&gt;code, "return ERROR;\n", "}\n", NIL);
+
+  /* final substititions if applicable */
+  ...
+
+  /* Dump the function out */
+  Wrapper_print(wrapper,f_wrappers);
+
+  /* tidy up */
+  Delete(wname);
+  DelWrapper(wrapper);
+
+  return SWIG_OK;
+}
+</pre>
+</div>
+
+<p>
+Executing this code will produce wrappers which have our basic skeleton
+but without the typemaps, there is still work to do.
+</p>
+
+
+<H3><a name="Extending_nn39"></a>34.10.8 Configuration files</H3>
+
+
+<!-- please report bugs in this section to ttn -->
+
+<p>
+At the time of this writing, SWIG supports nearly a dozen languages,
+which means that for continued sanity in maintaining the configuration
+files, the language modules need to follow some conventions.  These are
+outlined here along with the admission that, yes it is ok to violate
+these conventions in minor ways, as long as you know where to apply the
+proper kludge to keep the overall system regular and running.
+Engineering is the art of compromise, see...
+</p>
+
+<p>
+Much of the maintenance regularity depends on choosing a suitable
+nickname for your language module (and then using it in a controlled
+way).  Nicknames should be all lower case letters with an optional
+numeric suffix (no underscores, no dashes, no spaces).  Some examples
+are: <TT>foo</TT>, <TT>bar</TT>, <TT>qux99</TT>.
+</p>
+
+<p>
+The numeric suffix variant, as in the last example, is somewhat tricky
+to work with because sometimes people expect to refer to the language
+without this number but sometimes that number is extremely relevant
+(especially when it corresponds to language implementation versions with
+incompatible interfaces).  New language modules that unavoidably require
+a numeric suffix in their nickname should include that number in all
+uses, or be prepared to kludge.
+</p>
+
+<p>
+The nickname is used in four places:
+</p>
+
+<TABLE summary="nickname table">
+<TR><TD><B>usage</B></TD><TD><B>transform</B></TD></TR>
+<TR><TD>"skip" tag</TD><TD>(none)</TD></TR>
+<TR><TD>Examples/ subdir name</TD><TD>(none)</TD></TR>
+<TR><TD>Examples/GIFPlot/ subdir name</TD>
+    <TD>capitalize (upcase first letter)</TD></TR>
+<TR><TD>Examples/test-suite/ subdir name</TD><TD>(none)</TD></TR>
+<!-- add more uses here (remember to adjust header) -->
+</TABLE>
+
+<p>
+As you can see, most usages are direct.
+</p>
+
+<dl>
+
+<dt> <b>configure.in</b>
+<dd> This file is processed by
+
+<p>
+<A HREF="http://www.gnu.org/software/autoconf/">autoconf</A>
+to generate the <TT>configure</TT> script.  This is where you
+need to add shell script fragments and autoconf macros to detect the
+presence of whatever development support your language module requires,
+typically directories where headers and libraries can be found, and/or
+utility programs useful for integrating the generated wrapper code.
+</p>
+
+<p>
+Use the <TT>AC_ARG_WITH</TT>, <TT>AC_MSG_CHECKING</TT>, <TT>AC_SUBST</TT>
+macros and so forth (see other languages for examples).  Avoid using the
+<TT>[</TT> and <TT>]</TT> character in shell script fragments.  The
+variable names passed to <TT>AC_SUBST</TT> should begin with the nickname,
+entirely upcased.
+</p>
+
+<p>
+At the end of the new section is the place to put the aforementioned
+nickname kludges (should they be needed).  See Perl5 and Php4 for
+examples of what to do.  [If this is still unclear after you've read
+the code, ping me and I'll expand on this further.  --ttn]
+</p>
+
+<dt> <b>Makefile.in</b>
+<dd>
+
+<p>
+Some of the variables AC_SUBSTituted are essential to the
+support of your language module.  Fashion these into a shell script
+"test" clause and assign that to a skip tag using "-z" and "-o":
+</p>
+
+<div class="code"><tt>
+skip-qux99 = [ -z "@QUX99INCLUDE@" -o -z "@QUX99LIBS" ]
+</tt></div>
+
+<p>
+This means if those vars should ever be empty, qux99 support should
+be considered absent and so it would be a good idea to skip actions that
+might rely on it.
+</p>
+
+<p>
+Here is where you may also define an alias (but then you'll need to
+kludge --- don't do this):
+</p>
+
+<div class="code"><tt>
+skip-qux = $(skip-qux99)
+</tt></div>
+
+<p>
+Lastly, you need to modify each of <TT>check-aliveness</TT>,
+<TT>check-examples</TT>, <TT>check-test-suite</TT>,
+<TT>check-gifplot</TT> (all targets) and <TT>lib-languages</TT> (var).
+Use the nickname for these, not the alias.
+Note that you can do this even before you have any tests or examples
+set up; the Makefile rules do some sanity checking and skip around
+these kinds of problems.
+</p>
+
+<dt> <b>Examples/Makefile.in</b>
+<dd> Nothing special here; see comments at top the of this file
+and look to the existing languages for examples.
+
+<dt> <b>Examples/qux99/check.list</b>
+<dd> Do <TT>cp ../python/check.list .</TT> and modify to taste.
+One subdir per line.
+
+<dt> <b>Examples/GIFPlot/Qux99/check.list</b>
+<dd> Do <TT>cp ../Python/check.list .</TT> and modify to taste.
+One subdir per line.
+
+<dt> <b>Lib/qux99/extra-install.list</b>
+<dd> If you add your language to the top-level Makefile.in var
+<TT>lib-languages</TT>, then <TT>make install</TT> will install
+all <TT>*.i</TT> and <TT>*.swg</TT> files from the language-specific
+subdirectory of <TT>Lib</TT>.  Use (optional) file
+<TT>extra-install.list</TT> in that directory to name
+additional files to install (see ruby for example).
+
+<dt> <b>Source/Modules/Makefile.am</b>
+<dd> Add appropriate files to this Automake file. That's it!
+
+<p>
+When you have modified these files, please make sure that the new language module is completely
+ignored if it is not installed and detected on a box, that is, <tt>make check-examples</tt> and <tt>make check-test-suite</tt>
+politely displays the ignoring language message.
+</p>
+
+</dl>
+
+
+<H3><a name="Extending_nn40"></a>34.10.9 Runtime support</H3>
+
+
+<p>
+Discuss the kinds of functions typically needed for SWIG runtime support (e.g.
+<tt>SWIG_ConvertPtr()</tt> and <tt>SWIG_NewPointerObj()</tt>) and the names of
+the SWIG files that implement those functions.
+</p>
+
+<H3><a name="Extending_nn41"></a>34.10.10 Standard library files</H3>
+
+
+<p>
+The standard library files that most languages supply keeps growing as SWIG matures.
+The following are the minimum that are usually supported:
+</p>
+
+<ul>
+<li> typemaps.i </li>
+<li> std_string.i </li>
+<li> std_vector.i </li>
+<li> stl.i </li>
+</ul>
+
+<p>
+Please copy these and modify for any new language.
+</p>
+
+<H3><a name="Extending_nn42"></a>34.10.11 Examples and test cases</H3>
+
+
+<p>
+Each of the language modules provides one or more examples. These examples
+are used to demonstrate different features of the language module to SWIG
+end-users, but you'll find that they're useful during development and testing
+of your language module as well. You can use examples from the existing SWIG
+language modules for inspiration.
+</p>
+
+<p>
+Each example is self-contained and consists of (at least) a <tt>Makefile</tt>,
+a SWIG interface file for the example module, and a 'runme' script that demonstrates
+the functionality for that module. All of these files are stored in the same
+subdirectory under the <tt>Examples/[lang]</tt> directory.
+There are two classic examples which should be the first to convert to a new
+language module. These are the "simple" C example and the "class" C++ example.
+These can be found, for example for Python, in
+<tt>Examples/python/simple</tt> and <tt>Examples/python/class</tt>.
+</p>
+
+<p>
+By default, all of the examples are built and run when the user types
+<tt>make check</tt>. To ensure that your examples are automatically run
+during this process, see the section on <a href="#n37a">configuration
+files</a>.
+</p>
+
+<H3><a name="Extending_nn43"></a>34.10.12 Documentation</H3>
+
+
+<p>
+Don't forget to write end-user documentation for your language module. Currently,
+each language module has a dedicated chapter 
+You shouldn't rehash things that are already covered in sufficient
+detail in the <a href="SWIG.html#SWIG">SWIG Basics</a> and <a href="SWIGPlus.html#SWIGPlus">SWIG
+and C++</a> chapters. There is no fixed format for <em>what</em>, exactly, you should
+document about your language module, but you'll obviously want to cover issues that
+are unique to your language.
+</p>
+
+<p>
+Some topics that you'll want to be sure to address include:
+</p>
+
+<ul>
+<li> Command line options unique to your language module.
+<li> Non-obvious mappings between C/C++ and target language concepts.
+     For example, if your target language provides a single floating
+     point type, it should be no big surprise to find that C/C++
+     <tt>float</tt> and <tt>double</tt> types are mapped to it. On the other
+     hand, if your target language doesn't provide support for "classes"
+     or something similar, you'd want to discuss how C++ classes are handled.
+<li> How to compile the SWIG-generated wrapper code into shared libraries
+     that can actually be used. For some languages, there are well-defined
+     procedures for doing this, but for others it's an ad hoc process.
+     Provide as much detail as appropriate, and links to other resources
+     if available.
+</ul>
+
+<H3><a name="Extending_prerequisites"></a>34.10.13 Prerequisites for adding a new language module to the SWIG distribution</H3>
+
+
+<p>
+If you wish for a new language module to be distributed with SWIG,
+which we encourage for all popular languages, there are a few requirements.
+While we appreciate that getting all aspects of a new language working
+won't happen at the outset, there are a set of minimum requirements before
+a module can be committed into the SVN repository for distribution with future
+versions of SWIG. The following are really a summary of this whole section with
+details being outlined earlier on.
+</p>
+
+<ol>
+  <li>
+  Demonstrate basic C code working by porting the "simple" example including
+  a runtime test, see for example <tt>Examples/python/simple</tt>.
+  </li>
+  <li>
+  Demonstrate basic C++ code working by porting the "class" example including
+  a runtime test, see for example <tt>Examples/python/class</tt>.
+  </li>
+  <li>
+  Modify <tt>configure.in</tt>, <tt>Makefile.in</tt> and <tt>Examples/Makefile.in</tt> to run
+  these examples. Please make sure that if the new language is not
+  installed properly on a box, <tt>make -k check</tt> should still work by
+  skipping the tests and examples for the new language module.
+  </li>
+  <li>
+  Get the test-suite running for the new language (<tt>make check-[lang]-test-suite</tt>).
+  While the test-suite tests many corner cases,
+  we'd expect the majority of it to work by compiling the generated code
+  correctly as most of the corner cases are covered in the SWIG core. Get
+  at least one C and one C++ runtime test running in the test-suite.
+  </li>
+  <li>
+  Provide a chapter in the html documentation on the basics of using
+  the language module.
+  </li>
+  <li>
+  Ensure your source code is formatted according to the <a href="#Extending_coding_style_guidelines">coding style guidelines</a>.
+  </li>
+  <li>
+  Finally, email the SWIG developers with a patch and a demonstration of
+  commitment to maintaining the language module,
+  certainly in the short term and ideally long term.
+  </li>
+</ol>
+
+<p>
+Once accepted into SVN, development efforts should concentrate on
+getting the entire test-suite to work with plenty of runtime tests.
+Runtime tests should be for existing testcases and new test cases 
+should be added should there be an area not already covered by 
+the existing tests.
+</p>
+
+<H3><a name="Extending_coding_style_guidelines"></a>34.10.14 Coding style guidelines</H3>
+
+
+<p>
+The coding guidelines for the C/C++ source code are pretty much K&amp;R C style.
+The style can be inferred from the existing code base and is
+largely dictated by the <tt>indent</tt> code beautifier tool set to K&amp;R style.
+The code can formatted using the make targets in the Source directory.
+Below is an example of how to format the emit.cxx file:
+</p>
+
+<blockquote>
+<pre>
+$ cd Source
+$ make beautify-file INDENTFILE=Modules/emit.cxx
+</pre>
+</blockquote>
+
+<p>
+Of particular note is indentation is set to 2 spaces and a tab is used instead of 8 spaces.
+The generated C/C++ code should also follow this style as close as possible. However, tabs
+should be avoided as unlike the SWIG developers, users will never have consistent tab settings.
+</p>
+
+<H2><a name="Extending_nn44"></a>34.11 Typemaps</H2>
+
+
+<H3><a name="Extending_nn45"></a>34.11.1 Proxy classes</H3>
+
+
+<H2><a name="Extending_nn46"></a>34.12 Guide to parse tree nodes</H2>
+
+
+<p>
+This section describes the different parse tree nodes and their attributes.
+</p>
+
+<p>
+<b>cdecl</b>
+</p>
+
+<p>
+Describes general C declarations including variables, functions, and typedefs.
+A declaration is parsed as "storage T D" where storage is a storage class, T is a base type,
+and D is a declarator.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Declarator name
+"type"          - Base type T
+"decl"          - Declarator type (abstract)
+"storage"       - Storage class (static, extern, typedef, etc.)
+"parms"         - Function parameters (if a function)
+"code"          - Function body code (if supplied)
+"value"         - Default value (if supplied)
+</pre>
+
+</div>
+
+<p>
+<b>constructor</b>
+</p>
+
+<p>
+C++ constructor declaration.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of constructor
+"parms"         - Parameters
+"decl"          - Declarator (function with parameters)
+"code"          - Function body code (if any)
+"feature:new"   - Set to indicate return of new object.
+</pre>
+</div>
+
+
+<p>
+<b>destructor</b>
+</p>
+
+<p>
+C++ destructor declaration.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of destructor
+"code"          - Function body code (if any)
+"storage"       - Storage class (set if virtual)
+"value"         - Default value (set if pure virtual).
+</pre>
+</div>
+
+
+<p>
+<b>access</b>
+</p>
+
+<p>
+C++ access change.
+</p>
+
+<div class="diagram">
+<pre>
+"kind"          - public, protected, private
+</pre>
+</div>
+
+
+<p>
+<b>constant</b>
+</p>
+
+<p>
+Constant created by %constant or #define.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of constant.
+"type"          - Base type.
+"value"         - Value.
+"storage"       - Set to %constant
+"feature:immutable" - Set to indicate read-only
+</pre>
+</div>
+
+<p>
+<b>class</b>
+</p>
+
+<p>
+C++ class definition or C structure definition.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of the class.
+"kind"          - Class kind ("struct", "union", "class")
+"symtab"        - Enclosing symbol table.
+"tdname"        - Typedef name. Use for typedef struct { ... } A.
+"abstract"      - Set if class has pure virtual methods.
+"baselist"      - List of base class names.
+"storage"       - Storage class (if any)
+"unnamed"       - Set if class is unnamed.
+</pre>
+</div>
+
+
+<p>
+<b>enum</b>
+</p>
+
+<p>
+Enumeration.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of the enum (if supplied).
+"storage"       - Storage class (if any)
+"tdname"        - Typedef name (typedef enum { ... } name).
+"unnamed"       - Set if enum is unnamed.
+</pre>
+</div>
+
+
+<p>
+<b>enumitem</b>
+</p>
+
+<p>
+Enumeration value.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of the enum value.
+"type"          - Type (integer or char)
+"value"         - Enum value (if given)
+"feature:immutable" - Set to indicate read-only
+</pre>
+</div>
+
+<p>
+<b>namespace</b>
+</p>
+
+<p>
+C++ namespace.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of the namespace.
+"symtab"        - Symbol table for enclosed scope.
+"unnamed"       - Set if unnamed namespace
+"alias"         - Alias name. Set for namespace A = B;
+</pre>
+</div>
+
+
+<p>
+<b>using</b>
+</p>
+
+<p>
+C++ using directive.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of the object being referred to.
+"uname"         - Qualified name actually given to using.
+"node"          - Node being referenced.
+"namespace"     - Namespace name being reference (using namespace name)
+</pre>
+</div>
+
+
+<p>
+<b>classforward</b>
+</p>
+
+<p>
+A forward C++ class declaration.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Name of the class.
+"kind"          - Class kind ("union", "struct", "class")
+</pre>
+</div>
+
+
+<p>
+<b>insert</b>
+</p>
+
+<p>
+Code insertion directive.  For example, %{ ... %} or
+%insert(section).
+</p>
+
+<div class="diagram">
+<pre>
+"code"          - Inserted code
+"section"       - Section name ("header", "wrapper", etc.)
+</pre>
+</div>
+
+<p>
+<b>top</b>
+</p>
+
+<p>
+Top of the parse tree.
+</p>
+
+<div class="diagram">
+<pre>
+"module"        - Module name
+</pre>
+</div>
+
+<p>
+<b>extend</b>
+</p>
+
+<p>
+%extend directive.
+</p>
+
+<div class="diagram">
+<pre>
+"name"          - Module name
+"symtab"        - Symbol table of enclosed scope.
+</pre>
+</div>
+
+<p>
+<b>apply</b>
+</p>
+
+<p>
+%apply pattern { patternlist }.
+</p>
+
+<div class="diagram">
+<pre>
+"pattern"       - Source pattern.
+"symtab"        - Symbol table of enclosed scope.
+</pre>
+</div>
+
+<p>
+<b>clear</b>
+</p>
+
+<p>
+%clear patternlist;
+</p>
+
+<div class="diagram">
+<pre>
+"firstChild"    - Patterns to clear
+</pre>
+</div>
+
+<p>
+<b>include</b>
+</p>
+
+<p>
+%include directive.
+</p>
+
+<div class="diagram">
+<pre>
+"name"         - Filename
+"firstChild"   - Children
+</pre>
+</div>
+
+<p>
+<b>import</b>
+</p>
+
+<p>
+%import directive.
+</p>
+
+<div class="diagram">
+<pre>
+"name"         - Filename
+"firstChild"   - Children
+</pre>
+</div>
+
+
+<p>
+<b>module</b>
+</p>
+
+<p>
+%module directive.
+</p>
+
+<div class="diagram">
+<pre>
+"name"         - Name of the module
+</pre>
+</div>
+
+
+<p>
+<b>typemap</b>
+</p>
+
+<p>
+%typemap directive.
+</p>
+
+<div class="diagram">
+<pre>
+"method"       - Typemap method name.
+"code"         - Typemap code.
+"kwargs"       - Keyword arguments (if any)
+"firstChild"   - Typemap patterns
+</pre>
+</div>
+
+<p>
+<b>typemapcopy</b>
+</p>
+
+<p>
+%typemap directive with copy.
+</p>
+
+<div class="diagram">
+<pre>
+"method"       - Typemap method name.
+"pattern"      - Typemap source pattern.
+"firstChild"   - Typemap patterns
+</pre>
+</div>
+
+
+<p>
+<b>typemapitem</b>
+</p>
+
+<p>
+%typemap pattern. Used with %apply, %clear, %typemap.
+</p>
+
+<div class="diagram">
+<pre>
+"pattern"      - Typemap pattern (a parameter list)
+"parms"        - Typemap parameters.
+</pre>
+</div>
+
+<p>
+<b>types</b>
+</p>
+
+<p>
+%types directive.
+</p>
+
+<div class="diagram">
+<pre>
+"parms"        - List of parameter types.
+"convcode"     - Code which replaces the default casting / conversion code
+</pre>
+</div>
+
+
+<p>
+<b>extern</b>
+</p>
+
+<p>
+extern "X" { ... } declaration.
+</p>
+
+<div class="diagram">
+<pre>
+"name"       - Name "C", "Fortran", etc.
+</pre>
+</div>
+
+
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Guile.html b/trunk/Doc/Manual/Guile.html
new file mode 100644
index 0000000..20ab716
--- /dev/null
+++ b/trunk/Doc/Manual/Guile.html
@@ -0,0 +1,895 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<!-- Hand-written HTML -->
+<html>
+<head>
+<title>SWIG and Guile</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+
+<H1><a name="Guile"></a>19 SWIG and Guile</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Guile_nn2">Meaning of "Module"</a>
+<li><a href="#Guile_nn3">Using the SCM or GH Guile API</a>
+<li><a href="#Guile_nn4">Linkage</a>
+<ul>
+<li><a href="#Guile_nn5">Simple Linkage</a>
+<li><a href="#Guile_nn6">Passive Linkage</a>
+<li><a href="#Guile_nn7">Native Guile Module Linkage</a>
+<li><a href="#Guile_nn8">Old Auto-Loading Guile Module Linkage</a>
+<li><a href="#Guile_nn9">Hobbit4D Linkage</a>
+</ul>
+<li><a href="#Guile_nn10">Underscore Folding</a>
+<li><a href="#Guile_nn11">Typemaps</a>
+<li><a href="#Guile_nn12">Representation of pointers as smobs</a>
+<ul>
+<li><a href="#Guile_nn13">GH Smobs</a>
+<li><a href="#Guile_nn14">SCM Smobs</a>
+<li><a href="#Guile_nn15">Garbage Collection</a>
+</ul>
+<li><a href="#Guile_nn16">Exception Handling</a>
+<li><a href="#Guile_nn17">Procedure documentation</a>
+<li><a href="#Guile_nn18">Procedures with setters</a>
+<li><a href="#Guile_nn19">GOOPS Proxy Classes</a>
+<ul>
+<li><a href="#Guile_nn20">Naming Issues</a>
+<li><a href="#Guile_nn21">Linking</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This section details guile-specific support in SWIG.
+
+<H2><a name="Guile_nn2"></a>19.1 Meaning of "Module"</H2>
+
+
+<p>
+There are three different concepts of "module" involved, defined
+separately for SWIG, Guile, and Libtool.  To avoid horrible confusion,
+we explicitly prefix the context, e.g., "guile-module".
+
+<H2><a name="Guile_nn3"></a>19.2 Using the SCM or GH Guile API</H2>
+
+
+<p>The guile module can currently export wrapper files that use the guile GH interface or the
+SCM interface. This is controlled by an argument passed to swig.  The "-gh" argument causes swig
+to output GH code, and the "-scm" argument causes swig to output SCM code.  Right now the "-scm" argument
+is the default.  The "-scm" wrapper generation assumes a guile version &gt;= 1.6 and has several advantages over
+the "-gh" wrapper generation including garbage collection and GOOPS support.
+The "-gh" wrapper generation can be used for older versions of guile.
+The guile GH wrapper code generation is depreciated and the
+SCM interface is the default.  The SCM and GH interface differ greatly in how they store
+pointers and have completely different run-time code. See below for more info.  
+
+<p>The GH interface to guile is deprecated.  Read more about why in the 
+<a href="http://www.gnu.org/software/guile/docs/guile-ref/GH-deprecation.html">Guile manual</a>.
+The idea of the GH interface was to provide a high level API that other languages and projects
+could adopt.  This was a good idea, but didn't pan out well for general development.  But for the
+specific, minimal uses that the SWIG typemaps put the GH interface to use is ideal for
+using a high level API.  So even though the GH interface is depreciated, SWIG will continue to use
+the GH interface and provide mappings from the GH interface to whatever API we need.
+We can maintain this mapping where guile failed because SWIG uses a small subset of all the GH functions 
+which map easily.  All the guile typemaps like typemaps.i and std_vector.i
+will continue to use the GH functions to do things like create lists of values, convert strings to
+integers, etc.  Then every language module will define a mapping between the GH interface and 
+whatever custom API the language uses.  This is currently implemented by the guile module to use
+the SCM guile API rather than the GH guile API.  
+For example, here are some of the current mapping file for the SCM API</p>
+
+<div class="code"><pre>
+
+#define gh_append2(a, b) scm_append(scm_listify(a, b, SCM_UNDEFINED)) 
+#define gh_apply(a, b) scm_apply(a, b, SCM_EOL) 
+#define gh_bool2scm SCM_BOOL 
+#define gh_boolean_p SCM_BOOLP 
+#define gh_car SCM_CAR 
+#define gh_cdr SCM_CDR 
+#define gh_cons scm_cons 
+#define gh_double2scm scm_make_real 
+...
+</pre></div>
+
+<p>This file is parsed by SWIG at wrapper generation time, so every reference to a gh_ function is replaced
+by a scm_ function in the wrapper file.  Thus the gh_ function calls will never be seen in the wrapper;
+the wrapper will look exactly like it was generated
+for the specific API.  Currently only the guile language module has created a mapping policy from gh_ to scm_,
+but there is no reason other languages (like mzscheme or chicken) couldn't also use this.  
+If that happens, there is A LOT less code duplication in the standard typemaps.</p>
+
+<H2><a name="Guile_nn4"></a>19.3 Linkage</H2>
+
+
+<p>
+Guile support is complicated by a lack of user community cohesiveness,
+which manifests in multiple shared-library usage conventions.  A set of
+policies implementing a usage convention is called a <b>linkage</b>.
+
+<H3><a name="Guile_nn5"></a>19.3.1 Simple Linkage</H3>
+
+
+<p>
+The default linkage is the simplest; nothing special is done.  In this
+case the function <code>SWIG_init()</code> is exported. Simple linkage
+can be used in several ways:
+</p>
+
+<ul>
+<li><b>Embedded Guile, no modules.</b> You want to embed a Guile
+interpreter into your program; all bindings made by SWIG shall show up
+in the root module. Then call <code>SWIG_init()</code> in the
+<code>inner_main()</code> function.  See the "simple" and "matrix" examples under
+<code>Examples/guile</code>.
+
+<li><p><b>Dynamic module mix-in.</b> You want to create a Guile module
+using <code>define-module</code>, containing both Scheme code and
+bindings made by SWIG; you want to load the SWIG modules as shared
+libraries into Guile.</p>
+<div class="targetlang">
+<pre>
+(define-module (my module))
+(define my-so (dynamic-link "./example.so"))
+(dynamic-call "SWIG_init" my-so) ; make SWIG bindings
+;; Scheme definitions can go here
+</pre>
+</div>
+
+<p>
+Newer Guile versions provide a shorthand for <code>dynamic-link</code>
+and <code>dynamic-call</code>:
+</p>
+
+<div class="targetlang">
+<pre>
+(load-extension "./example.so" "SWIG_init")
+</pre>
+</div>
+
+<p>
+You need to explicitly export those bindings made by SWIG that you
+want to import into other modules:
+</p>
+
+<div class="targetlang">
+<pre>
+(export foo bar)
+</pre>
+</div>
+
+<p>
+In this example, the procedures <code>foo</code> and <code>bar</code>
+would be exported.  Alternatively, you can export all bindings with the
+following module-system hack:
+</p>
+
+<div class="targetlang">
+<pre>
+(module-map (lambda (sym var)
+	      (module-export! (current-module) (list sym)))
+	    (current-module))
+</pre>
+</div>
+
+<p>SWIG can also generate this Scheme stub (from
+<code>define-module</code> up to <code>export</code>)
+semi-automagically if you pass it the command-line argument
+<code>-scmstub</code>.  The code will be exported in a file called
+<code><i>module</i>.scm</code> in the directory specified by <code>-outdir</code>
+or the current directory if <code>-outdir</code> is not specified.  
+Since SWIG doesn't know how
+to load your extension module (with <code>dynamic-link</code> or
+<code>load-extension</code>), you need to supply this
+information by including a directive like this in the interface file:
+</p>
+
+<div class="code">
+<pre>
+%scheme %{ (load-extension "./example.so" "SWIG_init") %}
+</pre>
+</div>
+
+<p>
+(The <code>%scheme</code> directive allows to insert arbitrary Scheme
+code into the generated file <code><var>module.scm</var></code>; it is
+placed between the <code>define-module</code> form and the
+<code>export</code> form.)
+</p>
+</ul>
+
+<p>If you want to include several SWIG modules, you would need to rename
+<code>SWIG_init</code> via a preprocessor define to avoid symbol
+clashes. For this case, however, passive linkage is available.
+
+<H3><a name="Guile_nn6"></a>19.3.2 Passive Linkage</H3>
+
+
+<p>Passive linkage is just like simple linkage, but it generates an
+initialization function whose name is derived from the module and
+package name (see below). 
+
+<p>You should use passive linkage rather than simple linkage when you
+are using multiple modules.
+
+<H3><a name="Guile_nn7"></a>19.3.3 Native Guile Module Linkage</H3>
+
+
+<p>SWIG can also generate wrapper code that does all the Guile module
+declarations on its own if you pass it the <code>-Linkage
+module</code> command-line option. This requires Guile 1.5.0 or later.
+
+<p>The module name is set with the <code>-package</code> and
+<code>-module</code> command-line options. Suppose you want to define
+a module with name <code>(my lib foo)</code>; then you would have to
+pass the options <code>-package <var>my</var>/<var>lib</var> -module
+<var>foo</var></code>. Note that the last part of the name can also be set
+via the SWIG directive <code>%module</code>. 
+
+<p>You can use this linkage in several ways:
+
+<ul>
+<li><b>Embedded Guile with SWIG modules.</b> You want to embed a Guile
+interpreter into your program; the SWIG bindings shall be put into
+different modules. Simply call the function 
+<code>scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>
+in the <code>inner_main()</code> function.
+
+<li><b>Dynamic Guile modules.</b> You want to load the SWIG modules as
+shared libraries into Guile; all bindings are automatically put in
+newly created Guile modules. 
+<div class="targetlang">
+<pre>
+(define my-so (dynamic-link "./foo.so"))
+;; create new module and put bindings there:
+(dynamic-call "scm_init_my_modules_foo_module" my-so) 
+</pre>
+</div>
+Newer Guile versions have a shorthand procedure for this:
+<div class="targetlang">
+<pre>
+(load-extension "./foo.so" "scm_init_my_modules_foo_module")
+</pre>
+</div>
+</ul>
+
+<H3><a name="Guile_nn8"></a>19.3.4 Old Auto-Loading Guile Module Linkage</H3>
+
+
+<p>Guile used to support an autoloading facility for object-code
+modules. This support has been marked deprecated in version 1.4.1 and
+is going to disappear sooner or later. SWIG still supports building
+auto-loading modules if you pass it the <code>-Linkage ltdlmod</code>
+command-line option.
+
+<p>Auto-loading worked like this: Suppose a module with name <code>(my
+lib foo)</code> is required and not loaded yet.  Guile will then search
+all directories in its search path
+for a Scheme file <code>my/modules/foo.scm</code> or a shared library
+<code><var>my</var>/<var>modules</var>/lib<var>foo</var>.so</code> (or
+<code><var>my</var>/<var>modules</var>/lib<var>foo</var>.la</code>; 
+see the GNU libtool documentation). If a
+shared library is found that contains the symbol
+<code>scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>, 
+the library is loaded, and the function at that symbol is called with
+no arguments in order to initialize the module.
+
+<p>When invoked with the <code>-Linkage ltdlmod</code> command-line
+option, SWIG generates an exported module initialization function with
+an appropriate name. 
+
+
+<H3><a name="Guile_nn9"></a>19.3.5 Hobbit4D Linkage</H3>
+
+
+<p>
+The only other linkage supported at this time creates shared object
+libraries suitable for use by hobbit's <code>(hobbit4d link)</code>
+guile module.  This is called the "hobbit" linkage, and requires also
+using the "-package" command line option to set the part of the module
+name before the last symbol.  For example, both command lines:
+</p>
+
+<div class="shell">
+<pre>
+swig -guile -package my/lib foo.i
+swig -guile -package my/lib -module foo foo.i
+</pre>
+</div>
+
+<p>
+would create module <code>(my lib foo)</code> (assuming in the first
+case foo.i declares the module to be "foo").  The installed files are
+my/lib/libfoo.so.X.Y.Z and friends.  This scheme is still very
+experimental; the (hobbit4d link) conventions are not well understood.
+</p>
+
+<H2><a name="Guile_nn10"></a>19.4 Underscore Folding</H2>
+
+
+<p>
+Underscores are converted to dashes in identifiers.  Guile support may
+grow an option to inhibit this folding in the future, but no one has
+complained so far.
+
+<p>You can use the SWIG directives <code>%name</code> and
+<code>%rename</code> to specify the Guile name of the wrapped
+functions and variables (see CHANGES).
+
+<H2><a name="Guile_nn11"></a>19.5 Typemaps</H2>
+
+
+<p>
+The Guile module handles all types via typemaps. This
+information is read from <code>Lib/guile/typemaps.i</code>. 
+
+Some non-standard typemap substitutions are supported:
+<ul>
+<li><code>$descriptor</code> expands to a type descriptor for use with
+the <code>SWIG_NewPointerObj()</code> and
+<code>SWIG_ConvertPtr</code> functions.
+<li>For pointer types, <code>$*descriptor</code> expands to a
+descriptor for the direct base type (i.e., one pointer is stripped),
+whereas <code>$basedescriptor</code> expands to a
+descriptor for the base type (i.e., all pointers are stripped).
+</ul>
+
+<p>A function returning <code>void</code> (more precisely, a function
+whose <code>out</code> typemap returns <code>SCM_UNSPECIFIED</code>) is
+treated as returning no values. In <code>argout</code> typemaps, one
+can use the macro <code>GUILE_APPEND_RESULT</code> in order to append
+a value to the list of function return values.
+
+<p>Multiple values can be passed up to Scheme in one of three ways:
+<ul>
+<li><p><em>Multiple values as lists.</em> 
+By default, if more than one value is to
+be returned, a list of the values is created and returned; to switch
+back to this behavior, use</p>
+
+<div class="code">
+<pre>
+%values_as_list;</pre>
+</div>
+
+<li><p><em>Multiple values as vectors.</em>
+By issuing 
+</p>
+
+<div class="code">
+<pre>
+%values_as_vector;</pre>
+</div>
+
+<p>
+vectors instead of lists will be used.
+<li><p><em>Multiple values for multiple-value continuations.</em>
+<strong>This is the most elegant way.</strong> By issuing 
+</p>
+
+<div class="code">
+<pre>
+%multiple_values;</pre>
+</div>
+
+<p>
+multiple values are passed to the multiple-value
+continuation, as created by <code>call-with-values</code> or the
+convenience macro <code>receive</code>. The latter is available if you
+issue <code>(use-modules (srfi srfi-8))</code>. Assuming that your
+<code>divide</code> function 
+wants to return two values, a quotient and a remainder, you can write: 
+</p>
+
+<div class="targetlang">
+<pre>
+(receive (quotient remainder)
+    (divide 35 17)
+  <var>body</var>...)
+</pre>
+</div>
+
+<p>
+In <code><var>body</var></code>, the first result of
+<code>divide</code> will be bound to the variable
+<code>quotient</code>, and the second result to <code>remainder</code>.
+</p>
+
+</ul>
+
+<p>
+See also the "multivalue" example.
+</p>
+
+<p>Constants are exported as a function that returns the value.  The
+%feature("constasvar") can be applied to any constant, immutable variable, or enum.
+Instead of exporting the constant as a function that must be called, the
+constant will appear as a scheme variable. See
+<a href="Customization.html#features">Features and the %feature directive</a>
+for info on how to apply the %feature.</p>
+
+<H2><a name="Guile_nn12"></a>19.6 Representation of pointers as smobs</H2>
+
+
+<p>
+For pointer types, SWIG uses Guile smobs. SWIG smobs print
+like this: <code>#&lt;swig struct xyzzy * 0x1234affe&gt;</code>  Two of
+them are <code>equal?</code> if and only if they have the same type
+and value.
+
+<p>
+To construct a Scheme object from a C pointer, the wrapper code calls
+the function <code>SWIG_NewPointerObj()</code>, passing a pointer to a
+struct representing the pointer type. The type index to store in the
+upper half of the CAR is read from this struct.
+To get the pointer represented by a smob, the wrapper code calls the
+function <code>SWIG_ConvertPtr()</code>, passing a pointer to a struct
+representing the expected pointer type.  See also 
+<a href="Typemaps.html#runtime_type_checker">The run-time type checker</a>.
+If the Scheme object passed was not a SWIG smob representing a compatible
+pointer, a <code>wrong-type-arg</code> exception is raised.
+
+<H3><a name="Guile_nn13"></a>19.6.1 GH Smobs</H3>
+
+
+<p>
+In earlier versions of SWIG, C pointers were represented as Scheme
+strings containing a hexadecimal rendering of the pointer value and a
+mangled type name.  As Guile allows registering user types, so-called
+"smobs" (small objects), a much cleaner representation has been
+implemented now.  The details will be discussed in the following.
+</p>
+
+<p> A smob is a cons cell where the lower half of the CAR contains the smob type
+tag, while the upper half of the CAR and the whole CDR are available. Every
+module creates its own smob type in the clientdata field of the module. So the
+lower 16 bits of the car of the smob store the tag and the upper 16 bits store
+the index this type is in the array. We can then, given a smob, find its
+swig_type_info struct by using the tag (lower 16 bits of car) to find which
+module this type is in (since each tag is unique for the module). Then we use
+the upper 16 bits to index into the array of types attached to this module.
+Looking up the module from the tag is worst case O(# of modules) but average
+case O(1). This is because the modules are stored in a circularly linked list,
+and when we start searching the modules for the tag, we start looking with the
+module that the function doing the lookup is in. SWIG_Guile_ConvertPtr() takes
+as its first argument the swig_module_info * of the calling function, which is
+where we start comparing tags. Most types will be looked up in the same module
+that created them, so the first module we check will most likely be correct.
+Once we have a swig_type_info structure, we loop through the linked list of
+casts, using pointer comparisons.</p>
+
+<H3><a name="Guile_nn14"></a>19.6.2 SCM Smobs</H3>
+
+
+<p>The SCM interface (using the "-scm" argument to swig) uses swigrun.swg.
+The whole type system, when it is first initialized, creates two smobs named "swig" and "collected_swig".
+The swig smob is used for non-garbage collected smobs, while the collected_swig smob is used as described
+below.  Each smob has the same format, which is a double cell created by SCM_NEWSMOB2()
+The first word of data is the pointer to the object and the second word of data is the swig_type_info *
+structure describing this type.  This is a lot easier than the GH interface above because we can store
+a pointer to the type info structure right in the type.  With the GH interface, there was not enough
+room in the smob to store two whole words of data so we needed to store part of the "swig_type_info address"
+in the smob tag.  If a generated GOOPS module has been loaded, smobs will be wrapped by the corresponding
+GOOPS class.</p>
+
+
+<H3><a name="Guile_nn15"></a>19.6.3 Garbage Collection</H3>
+
+
+<p>Garbage collection is a feature of the new SCM interface, and it is automatically included
+if you pass the "-scm" flag to swig.  Thus the swig garbage collection support requires guile &gt;1.6.
+Garbage collection works like this.  Every swig_type_info structure stores in its clientdata field a pointer
+to the destructor for this type.  The destructor is the generated wrapper around the delete function.
+So swig still exports a wrapper for the destructor, it just does not call scm_c_define_gsubr() for
+the wrapped delete function.  So the only way to delete an object is from the garbage collector, since the
+delete function is not available to scripts.  How swig determines if a type should be garbage collected
+is exactly like described in <a href="Customization.html#ownership">
+Object ownership and %newobject</a> in the SWIG manual.  All typemaps use an $owner var, and
+the guile module replaces $owner with 0 or 1 depending on feature:new.</p>
+
+<H2><a name="Guile_nn16"></a>19.7 Exception Handling</H2>
+
+
+<p>
+SWIG code calls <code>scm_error</code> on exception, using the following
+mapping:
+
+<div class="code">
+<pre>
+      MAP(SWIG_MemoryError,	"swig-memory-error");
+      MAP(SWIG_IOError,		"swig-io-error");
+      MAP(SWIG_RuntimeError,	"swig-runtime-error");
+      MAP(SWIG_IndexError,	"swig-index-error");
+      MAP(SWIG_TypeError,	"swig-type-error");
+      MAP(SWIG_DivisionByZero,	"swig-division-by-zero");
+      MAP(SWIG_OverflowError,	"swig-overflow-error");
+      MAP(SWIG_SyntaxError,	"swig-syntax-error");
+      MAP(SWIG_ValueError,	"swig-value-error");
+      MAP(SWIG_SystemError,	"swig-system-error");
+</pre>
+</div>
+
+<p>
+The default when not specified here is to use "swig-error".
+See Lib/exception.i for details.
+
+<H2><a name="Guile_nn17"></a>19.8 Procedure documentation</H2>
+
+
+<p>If invoked with the command-line option <code>-procdoc
+<var>file</var></code>, SWIG creates documentation strings for the
+generated wrapper functions, describing the procedure signature and
+return value, and writes them to <var>file</var>. You need Guile 1.4
+or later to make use of the documentation files.
+
+<p>SWIG can generate documentation strings in three formats, which are
+selected via the command-line option <code>-procdocformat
+<var>format</var></code>:
+<ul>
+<li><code>guile-1.4</code> (default): Generates a format suitable for Guile 1.4.
+<li><code>plain</code>: Generates a format suitable for Guile 1.4.1 and
+later.
+<li><code>texinfo</code>: Generates texinfo source, which must be run
+through texinfo in order to get a format suitable for Guile 1.4.1 and
+later.
+</ul>
+
+<p>You need to register the generated documentation file with Guile
+like this:
+
+<div class="targetlang">
+<pre>
+(use-modules (ice-9 documentation))
+(set! documentation-files 
+      (cons "<var>file</var>" documentation-files))
+</pre>
+</div>
+
+<p>Documentation strings can be configured using the Guile-specific
+typemap argument <code>doc</code>. See <code>Lib/guile/typemaps.i</code> for
+details.
+
+<H2><a name="Guile_nn18"></a>19.9 Procedures with setters</H2>
+
+
+<p>For global variables, SWIG creates a single wrapper procedure
+<code>(<var>variable</var> :optional value)</code>, which is used for
+both getting and setting the value. For struct members, SWIG creates
+two wrapper procedures <code>(<var>struct</var>-<var>member</var>-get
+pointer)</code> and <code>(<var>struct-member</var>-set pointer value)</code>.
+
+<p>If invoked with the command-line option <code>-emit-setters</code>
+(<em>recommended</em>),
+SWIG will additionally create procedures with setters. For global
+variables, the procedure-with-setter <code><var>variable</var></code>
+is created, so you can use <code>(<var>variable</var>)</code> to get
+the value and <code>(set! (<var>variable</var>)
+<var>value</var>)</code> to set it. For struct members, the
+procedure-with-setter <code><var>struct</var>-<var>member</var></code>
+is created, so you can use <code>(<var>struct</var>-<var>member</var>
+<var>pointer</var>)</code> to get the value and <code>(set!
+(<var>struct</var>-<var>member</var> <var>pointer</var>)
+<var>value</var>)</code> to set it.
+
+<p>If invoked with the command-line option <code>-only-setters</code>,
+SWIG will <em>only</em> create procedures with setters, i.e., for
+struct members, the procedures <code>(<var>struct</var>-<var>member</var>-get
+pointer)</code> and <code>(<var>struct-member</var>-set pointer
+value)</code> are <em>not</em> generated.
+
+<H2><a name="Guile_nn19"></a>19.10 GOOPS Proxy Classes</H2>
+
+
+<p>SWIG can also generate classes and generic functions for use with
+Guile's Object-Oriented Programming System (GOOPS).  GOOPS is a
+sophisticated object system in the spirit of the Common Lisp Object
+System (CLOS).
+
+<p>GOOPS support is
+only available with the new SCM interface (enabled with the
+<code>-scm</code> command-line option of SWIG).  To enable GOOPS
+support, pass the <code>-proxy</code> argument to
+swig.  This will export the GOOPS wrapper definitions into the
+<code><i>module</i>.scm</code> file in the directory specified by -outdir or the
+current directory.  GOOPS support requires either passive or module linkage.</p>
+
+<p>The generated file will contain definitions of GOOPS classes mimicking the C++ class hierarchy.
+<p>Enabling GOOPS support implies <code>-emit-setters</code>.
+
+<p>If <code>-emit-slot-accessors</code> is also passed as an argument,
+then the generated file will contain accessor methods for all the
+slots in the classes and for global variables.  The input class</p>
+<div class="code"><pre>
+  class Foo {
+    public:
+      Foo(int i) : a(i) {}
+      int a;
+      int getMultBy(int i) { return a * i; }
+      Foo getFooMultBy(int i) { return Foo(a * i); }
+  }; 
+  Foo getFooPlus(int i) { return Foo(a + i); }
+</pre></div>
+
+<p>
+will produce (if <code>-emit-slot-accessors</code> is not passed as a parameter)
+</p>
+
+<div class="targetlang"><pre>
+(define-class &lt;Foo&gt; (&lt;swig&gt;)
+  (a #:allocation #:swig-virtual 
+     #:slot-ref primitive:Foo-a-get 
+     #:slot-set! primitive:Foo-a-set)
+  #:metaclass &lt;swig-metaclass&gt;
+  #:new-function primitive:new-Foo
+)
+(define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
+  (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
+(define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
+  (make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))
+
+(define-method (getFooPlus i)
+  (make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))
+
+(export &lt;Foo&gt; getMultBy getFooMultBy getFooPlus )
+</pre></div>
+
+<p>
+and will produce (if <code>-emit-slot-accessors</code> is passed as a parameter)
+</p>
+
+<div class="targetlang"><pre>
+(define-class &lt;Foo&gt; (&lt;swig&gt;)
+  (a #:allocation #:swig-virtual 
+     #:slot-ref primitive:Foo-a-get 
+     #:slot-set! primitive:Foo-a-set 
+     <b>#:accessor a</b>)
+  #:metaclass &lt;swig-metaclass&gt;
+  #:new-function primitive:new-Foo
+)
+(define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
+  (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
+(define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
+  (make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))
+
+(define-method (getFooPlus i)
+  (make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))
+
+(export &lt;Foo&gt; <b>a</b> getMultBy getFooMultBy getFooPlus )
+</pre></div>
+
+<p>
+which can then be used by this code
+</p>
+
+<div class="targetlang"><pre>
+;; not using getters and setters
+(define foo (make &lt;Foo&gt; #:args '(45)))
+(slot-ref foo 'a)
+(slot-set! foo 'a 3)
+(getMultBy foo 4)
+(define foo2 (getFooMultBy foo 7))
+(slot-ref foo 'a)
+(slot-ref (getFooPlus foo 4) 'a)
+
+;; using getters and setters
+(define foo (make &lt;Foo&gt; #:args '(45)))
+(a foo)
+(set! (a foo) 5)
+(getMultBy foo 4)
+(a (getFooMultBy foo 7))
+</pre></div>
+
+<p>Notice that constructor arguments are passed as a list after the <code>#:args</code> keyword.  Hopefully in
+the future the following will be valid <code>(make &lt;Foo&gt; #:a 5 #:b 4)</code></p>
+
+<p>Also note that the order the declarations occur in the .i file make a difference.  For example,
+</p>
+
+<div class="code"><pre>
+%module test
+
+%{ #include "foo.h" %}
+
+%inline %{
+  int someFunc(Foo &amp;a) {
+    ...
+  }
+%}
+
+%include "foo.h"
+</pre></div>
+
+<p>
+This is a valid SWIG file it will work as you think it will for primitive support, but the generated
+GOOPS file will be broken.  Since the <code>someFunc</code> definition is parsed by SWIG before all the
+declarations in foo.h, the generated GOOPS file will contain the definition of <code>someFunc()</code>
+before the definition of &lt;Foo&gt;.  The generated GOOPS file would look like
+</p>
+
+<div class="targetlang"><pre>
+;;...
+
+(define-method (someFunc (swig_smob &lt;Foo&gt;))
+  (primitive:someFunc (slot-ref swig_smob 'smob)))
+
+;;...
+
+(define-class &lt;Foo&gt; (&lt;swig&gt;)
+  ;;...
+)
+
+;;...
+</pre></div>
+
+<p>
+Notice that &lt;Foo&gt; is used before it is defined.  The fix is to just put the 
+<code>%import "foo.h"</code> before the <code>%inline</code> block.
+</p>
+
+<H3><a name="Guile_nn20"></a>19.10.1 Naming Issues</H3>
+
+
+<p>As you can see in the example above, there are potential naming conflicts.  The default exported
+accessor for the <code>Foo::a</code> variable is named <code>a</code>.  The name of the wrapper global 
+function is <code>getFooPlus</code>.
+If the <code>-useclassprefix</code> option is passed to swig, the name of all accessors and member 
+functions will be prepended with the class name.  So the accessor will be called <code>Foo-a</code> and 
+the member functions will be called <code>Foo-getMultBy</code>.  Also, if the 
+<code>-goopsprefix goops:</code> argument is passed to swig, every identifier will be prefixed by 
+<code>goops:</code></p>
+
+<p>Two guile-modules are created by SWIG.  The first module contains the primitive definitions
+of all the wrapped functions and variables, and is located either in the _wrap.cxx file (with <code>-Linkage
+module</code>) or in the scmstub file (if <code>-Linkage passive -scmstub</code>).  The name of this 
+guile-module is the swig-module name (given on the command line with the -module argument or with the 
+%module directive) concatenated with the string "-primitive".  For
+example, if <code>%module Test</code> is set in the swig interface file, the name of the guile-module in 
+the scmstub or <code>-Linkage module</code> will be <code>Test-primitive</code>.  Also, the scmstub
+file will be named <code>Test-primitive.scm</code>.
+The string "primitive" can be changed by the <code>-primsuffix</code> swig
+argument.  So the same interface, with the <code>-primsuffix base</code> will produce a module called 
+<code>Test-base</code>. 
+The second generated guile-module contains all the GOOPS class definitions and is located in
+a file named <i>module</i>.scm in the directory specified with -outdir or the current directory.
+The name of this guile-module is the name of the
+swig-module (given on the command line or with the <code>%module</code> directive).
+In the previous example, the GOOPS definitions will be in a file named Test.scm.</p>
+
+<p>Because of the naming conflicts, you can't in general use both the <code>-primitive</code> and the GOOPS 
+guile-modules at the same time.  To do this, you need to rename the exported symbols from one or both 
+guile-modules.  For example,</p>
+<div class="targetlang"><pre>
+(use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
+(use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))
+</pre></div>
+
+<p>TODO: Renaming class name prefixes?</p>
+
+<H3><a name="Guile_nn21"></a>19.10.2 Linking</H3>
+
+
+<p>The guile-modules generated above all need to be linked together.  GOOPS support requires
+either passive or module linkage.  The exported GOOPS guile-module will be the name of the swig-module
+and should be located in a file called <i>Module</i>.scm.  This should be installed on the autoload
+path for guile, so that <code>(use-modules (<i>Package Module</i>))</code> will load everything needed.
+Thus, the top of the GOOPS guile-module will contain code to load everything needed by the interface 
+(the shared library, the scmstub module, etc.).
+The <code>%goops</code> directive inserts arbitrary code into the generated GOOPS guile-module, and
+should be used to load the dependent libraries.</p>
+
+<p>This breaks up into three cases</p>
+<ul>
+<li><b>Passive Linkage without -scmstub</b>:  Note that this linkage style has the potential for naming
+conflicts, since the primitive exported function and variable names are not wrapped in a guile-module
+and might conflict with names from the GOOPS guile-module (see above).  Pass the -goopsprefix
+argument to solve this problem.  If the <code>-exportprimitive</code> option is passed to SWIG the
+<code>(export ...)</code> code that would be exported into the scmstub file is exported at the bottom 
+of the generated GOOPS guile-module.
+The <code>%goops</code> directive should contain code to load the .so library.
+
+<div class="code"><pre>
+%goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
+</pre></div>
+
+<p>
+Produces the following code at the top of the generated GOOPS guile-module 
+(with the <code>-package my/modules -module foo</code> command line arguments)
+</p>
+
+<div class="targetlang"><pre>
+(define-module (my modules foo))
+
+;; %goops directive goes here
+(load-extension "./foo.so" "scm_init_my_modules_foo_module") 
+
+(use-modules (oop goops) (Swig common))
+</pre></div>
+</li>
+
+<li><p><b>Passive Linkage with -scmstub</b>: Here, the name of the scmstub file should be
+<code>Module-primitive.scm</code> (with <i>primitive</i> replaced with whatever is given with the <code>-primsuffix</code>
+argument.  The code to load the <code>.so</code> library should be located in the <code>%scheme</code> directive, 
+which will then be added to the scmstub file.
+Swig will automatically generate the line <code>(use-modules (<i>Package</i> <i>Module-primitive</i>))</code>
+into the GOOPS guile-module.  So if <i>Module-primitive.scm</i> is on the autoload path for guile, the
+<code>%goops</code> directive can be empty.  Otherwise, the <code>%goops</code> directive should contain 
+whatever code is needed to load the <i>Module-primitive.scm</i> file into guile.</p>
+
+<div class="targetlang"><pre>
+%scheme %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
+// only include the following definition if (my modules foo) cannot
+// be loaded automatically
+%goops %{ 
+  (primitive-load "/path/to/foo-primitive.scm") 
+  (primitive-load "/path/to/Swig/common.scm")
+%}
+</pre></div>
+
+<p>
+Produces the following code at the top of the generated GOOPS guile-module
+</p>
+
+<div class="targetlang"><pre>
+(define-module (my modules foo))
+
+;; %goops directive goes here (if any)
+(primitive-load "/path/to/foo-primitive.scm")
+(primitive-load "/path/to/Swig/common.scm")
+
+(use-modules (oop goops) (Swig common))
+(use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
+                                                       'primitive:)))
+
+</pre></div>
+</li>
+
+<li><p><b>Module Linkage</b>: This is very similar to passive linkage with a scmstub file.
+Swig will also automatically generate the line <code>(use-modules 
+(<i>Package</i> <i>Module-primitive</i>))</code> into the GOOPS guile-module.  Again the <code>%goops</code>
+directive should contain whatever code is needed to get that module loaded into guile.</p>
+
+<div class="code"><pre>
+%goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
+</pre></div>
+
+<p>
+Produces the following code at the top of the generated GOOPS guile-module
+</p>
+
+<div class="targetlang"><pre>
+(define-module (my modules foo))
+
+;; %goops directive goes here (if any)
+(load-extension "./foo.so" "scm_init_my_modules_foo_module") 
+
+(use-modules (oop goops) (Swig common))
+(use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
+                                                         'primitive:)))
+
+</pre></div>
+</li>
+</ul>
+
+<p><b>(Swig common)</b>: The generated GOOPS guile-module also imports definitions from the 
+(Swig common) guile-module.
+This module is included with SWIG and should be installed by SWIG into the autoload path for
+guile (based on the configure script and whatever arguments are passed).  If it is not, then the
+<code>%goops</code> directive also needs to contain code to load the <code>common.scm</code> file
+into guile.  Also note that if you are trying to install the generated wrappers on a computer without
+SWIG installed, you will need to include the common.swg file along with the install.</p>
+
+<p><b>Multiple Modules</b>:  Type dependencies between modules is supported.  For example, if
+<code>mod1</code> includes definitions of some classes, and <code>mod2</code> includes some classes
+derived from classes in <code>mod1</code>, the generated GOOPS file for <code>mod2</code> will declare
+the correct superclasses.  The only problem is that since <code>mod2</code> uses symbols from
+<code>mod1</code>, the <code>mod2</code> GOOPS file must include a <code>(use-modules (mod2))</code>.
+Currently, SWIG does not automatically export this line;  it must be included in the <code>%goops</code>
+directive of <code>mod2</code>.  Maybe in the future SWIG can detect dependencies and export this line.
+(how do other language modules handle this problem?)</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Introduction.html b/trunk/Doc/Manual/Introduction.html
new file mode 100644
index 0000000..491204d
--- /dev/null
+++ b/trunk/Doc/Manual/Introduction.html
@@ -0,0 +1,461 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Introduction</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Introduction"></a>2 Introduction</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Introduction_nn2">What is SWIG?</a>
+<li><a href="#Introduction_nn3">Why use SWIG?</a>
+<li><a href="#Introduction_nn4">A SWIG example</a>
+<ul>
+<li><a href="#Introduction_nn5">SWIG interface file</a>
+<li><a href="#Introduction_nn6">The swig command</a>
+<li><a href="#Introduction_nn7">Building a Perl5 module</a>
+<li><a href="#Introduction_nn8">Building a Python module</a>
+<li><a href="#Introduction_nn9">Shortcuts</a>
+</ul>
+<li><a href="#Introduction_nn10">Supported C/C++ language features</a>
+<li><a href="#Introduction_nn11">Non-intrusive interface building</a>
+<li><a href="#Introduction_build_system">Incorporating SWIG into a build system</a>
+<li><a href="#Introduction_nn12">Hands off code generation</a>
+<li><a href="#Introduction_nn13">SWIG and freedom</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<H2><a name="Introduction_nn2"></a>2.1 What is SWIG?</H2>
+
+
+<p>
+SWIG is a software development tool that simplifies the task of
+interfacing different languages to C and C++ programs.  In a
+nutshell, SWIG is a compiler that takes C declarations and creates
+the wrappers needed to access those declarations from other languages including
+including Perl, Python, Tcl, Ruby, Guile, and Java.  SWIG normally
+requires no modifications to existing code and can often be used to
+build a usable interface in only a few minutes.  Possible applications
+of SWIG include:
+</p>
+
+<ul>
+<li>Building interpreted interfaces to existing C programs.
+<li>Rapid prototyping and application development.
+<li>Interactive debugging.
+<li>Reengineering or refactoring of legacy software into a scripting language components.
+<li>Making a graphical user interface (using Tk for example).
+<li>Testing of C libraries and programs (using scripts).
+<li>Building high performance C modules for scripting languages.
+<li>Making C programming more enjoyable (or tolerable depending on your point of view).
+<li>Impressing your friends.
+<li>Obtaining vast sums of research funding (although obviously not applicable to the author).
+</ul>
+
+<p>
+SWIG was originally designed to make it extremely easy for scientists
+and engineers to build extensible scientific software without having to get a
+degree in software engineering.  Because of this, the use of
+SWIG tends to be somewhat informal and ad-hoc (e.g., SWIG does not
+require users to provide formal interface specifications as you would find in
+a dedicated IDL compiler).  Although
+this style of development isn't appropriate for every
+project, it is particularly well suited to software development in the
+small; especially the research and development work that is commonly found
+in scientific and engineering projects.
+
+<H2><a name="Introduction_nn3"></a>2.2 Why use SWIG?</H2>
+
+
+<p>
+As stated in the previous section, the primary purpose of SWIG is to simplify
+the task of integrating C/C++ with other programming languages.  However, why would
+anyone want to do that?   To answer that question, it is useful to list a few strengths
+of C/C++ programming:
+</p>
+
+<ul>
+<li>Excellent support for writing programming libraries.
+<li>High performance (number crunching, data processing, graphics, etc.).
+<li>Systems programming and systems integration.
+<li>Large user community and software base.
+</ul>
+
+<p>
+Next, let's list a few problems with C/C++ programming
+</p>
+
+<ul>
+<li>Writing a user interface is rather painful (i.e., consider programming with MFC, X11, GTK, or any number
+of other libraries).
+<li>Testing is time consuming (the compile/debug cycle).
+<li>Not easy to reconfigure or customize without recompilation.
+<li>Modularization can be tricky.
+<li>Security concerns (buffer overflow for instance).
+</ul>
+<p>
+To address these limitations, many programmers have arrived at the
+conclusion that it is much easier to use different programming
+languages for different tasks.  For instance, writing a graphical user
+interface may be significantly easier in a scripting language like
+Python or Tcl (consider the reasons why millions of programmers have used languages like
+Visual Basic if you need more proof). An interactive interpreter might also serve as a
+useful debugging and testing tool.  Other languages like Java might
+greatly simplify the task of writing distributed computing software.
+The key point is that different programming languages offer different
+strengths and weaknesses.  Moreover, it is extremely unlikely that any
+programming is ever going to be perfect.  Therefore, by combining
+languages together, you can utilize the best features of each language
+and greatly simplify certain aspects of software development.
+</p>
+
+<p>
+From the standpoint of C/C++, a lot of people use SWIG because they want to break
+out of the traditional monolithic C programming model which usually results
+in programs that resemble this:
+
+<ul>
+<li>A collection of functions and variables that do something useful.
+<li>A <tt>main()</tt> program that starts everything.
+<li>A horrible collection of hacks that form some kind of user interface (but 
+which no-one really wants to touch).
+</ul>
+<p>
+Instead of going down that route, incorporating C/C++ into a higher level language
+often results in a more modular design, less code, better flexibility, and increased
+programmer productivity.   
+</p>
+
+<p>
+SWIG tries to make the problem of C/C++ integration as painless as possible.
+This allows you to focus on the underlying C
+program and using the high-level language interface, but not
+the tedious and complex chore of making the two languages talk to each
+other.  At the same time, SWIG recognizes that all applications are different.  Therefore,
+it provides a wide variety of customization features that let you change almost
+every aspect of the language bindings.  This is the main reason why SWIG has such a large
+user manual ;-).
+
+<H2><a name="Introduction_nn4"></a>2.3 A SWIG example</H2>
+
+
+<p>
+The best way to illustrate SWIG is with a simple example. Consider the
+following C code:
+</p>
+
+<div class="code"><pre>
+/* File : example.c */
+
+double  My_variable  = 3.0;
+
+/* Compute factorial of n */
+int  fact(int n) {
+	if (n &lt;= 1) return 1;
+	else return n*fact(n-1);
+}
+
+/* Compute n mod m */
+int my_mod(int n, int m) {
+	return(n % m);
+}
+</pre></div>
+
+<p>
+Suppose that you wanted to access these functions and the global
+variable <tt>My_variable</tt> from Tcl.  You start by making a SWIG
+interface file as shown below (by convention, these files carry a .i
+suffix) :
+
+<H3><a name="Introduction_nn5"></a>2.3.1 SWIG interface file</H3>
+
+
+<div class="code"><pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+extern double My_variable;
+extern int    fact(int);
+extern int    my_mod(int n, int m);
+%}
+
+extern double My_variable;
+extern int    fact(int);
+extern int    my_mod(int n, int m);
+</pre></div>
+
+<p>
+The interface file contains ANSI C function prototypes and variable
+declarations.  The <tt>%module</tt> directive defines the name of the
+module that will be created by SWIG.  The <tt>%{,%}</tt> block
+provides a location for inserting additional code such as C header
+files or additional C declarations.
+
+<H3><a name="Introduction_nn6"></a>2.3.2 The swig command</H3>
+
+
+<p>
+SWIG is invoked using the <tt>swig</tt> command. We can use this to
+build a Tcl module (under Linux) as follows :
+</p>
+
+<div class="shell"><pre>
+unix &gt; <b>swig -tcl example.i</b>
+unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</b>
+unix &gt; <b>gcc -shared example.o example_wrap.o -o example.so</b>
+unix &gt; <b>tclsh</b>
+% <b>load ./example.so</b>
+% <b>fact 4</b>
+24
+% <b>my_mod 23 7</b>
+2
+% <b>expr $My_variable + 4.5</b>
+7.5
+%
+</pre></div>
+	<p>
+
+The <tt>swig</tt> command produced a new file called
+<tt>example_wrap.c</tt> that should be compiled along with the
+<tt>example.c</tt> file.  Most operating systems and scripting
+languages now support dynamic loading of modules.  In our example, our
+Tcl module has been compiled into a shared library that can be loaded
+into Tcl.  When loaded, Tcl can now access the functions
+and variables declared in the SWIG interface.  A look at the file
+<tt>example_wrap.c</tt> reveals a hideous mess.  However, you 
+almost never need to worry about it.
+
+<H3><a name="Introduction_nn7"></a>2.3.3 Building a Perl5 module</H3>
+
+
+<p>
+Now, let's turn these functions into a Perl5 module. Without making
+any changes type the following (shown for Solaris):
+</p>
+
+<div class="shell"><pre>
+unix &gt; <b>swig -perl5 example.i</b>
+unix &gt; <b>gcc -c example.c example_wrap.c \
+	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
+unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>		# This is for Solaris
+unix &gt; <b>perl5.003
+use example;
+print example::fact(4), "\n";
+print example::my_mod(23,7), "\n";
+print $example::My_variable + 4.5, "\n";
+&lt;ctrl-d&gt;</b>
+24
+2
+7.5
+unix &gt;
+</pre></div>
+
+
+<H3><a name="Introduction_nn8"></a>2.3.4 Building a Python module</H3>
+
+
+<p>
+Finally, let's build a module for Python (shown for Irix).
+</p>
+
+<div class="shell"><pre>
+unix &gt; <b>swig -python example.i</b>
+unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</b>
+unix &gt; <b>gcc -shared example.o example_wrap.o -o _example.so</b>
+unix &gt; <b>python</b>
+Python 2.0 (#6, Feb 21 2001, 13:29:45)
+[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
+Type "copyright", "credits" or "license" for more information.     
+&gt;&gt;&gt; <b>import example</b>
+&gt;&gt;&gt; <b>example.fact(4)</b>
+24
+&gt;&gt;&gt; <b>example.my_mod(23,7)</b>
+2
+&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
+7.5
+</pre></div>
+
+<H3><a name="Introduction_nn9"></a>2.3.5 Shortcuts</H3>
+
+
+<p>
+To the truly lazy programmer, one may wonder why we needed the extra
+interface file at all. As it turns out, you can often do without
+it. For example, you could also build a Perl5 module by just running
+SWIG on the C header file and specifying a module name as follows
+</p>
+
+<div class="shell"><pre>
+unix &gt; <b>swig -perl5 -module example example.h</b>
+unix &gt; <b>gcc -c example.c example_wrap.c \
+	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
+unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>
+unix &gt; <b>perl5.003
+use example;
+print example::fact(4), "\n";
+print example::my_mod(23,7), "\n";
+print $example::My_variable + 4.5, "\n";
+&lt;ctrl-d&gt;</b>
+24
+2
+7.5
+</pre></div>
+
+<H2><a name="Introduction_nn10"></a>2.4 Supported C/C++ language features</H2>
+
+
+<p>
+A primary goal of the SWIG project is to make the language binding
+process extremely easy.  Although a few simple examples have been shown,
+SWIG is quite capable in supporting most of C++.  Some of the
+major features include:
+</p>
+
+<ul>
+<li>Full C99 preprocessing.
+<li>All ANSI C and C++ datatypes.
+<li>Functions, variables, and constants.
+<li>Classes.
+<li>Single and multiple inheritance.
+<li>Overloaded functions and methods.
+<li>Overloaded operators.
+<li>C++ templates (including member templates, specialization, and partial specialization).
+<li>Namespaces.
+<li>Variable length arguments.
+<li>C++ smart pointers.
+</ul>
+
+<p>
+Currently, the only major C++ feature not supported is nested classes--a limitation
+that will be removed in a future release.
+</p>
+
+<p>
+It is important to stress that SWIG is not a simplistic C++ lexing
+tool like several apparently similar wrapper generation tools.  SWIG
+not only parses C++, it implements the full C++ type system and it is
+able to understand C++ semantics.  SWIG generates its wrappers with
+full knowledge of this information.  As a result, you will find SWIG
+to be just as capable of dealing with nasty corner cases as it is in
+wrapping simple C++ code.  In fact, SWIG is able handle C++ code that
+stresses the very limits of many C++ compilers.
+
+
+<H2><a name="Introduction_nn11"></a>2.5 Non-intrusive interface building</H2>
+
+
+<p>
+When used as intended, SWIG requires minimal (if any) modification to
+existing C or C++ code. This makes SWIG extremely easy to use with existing
+packages and promotes software reuse and modularity. By making
+the C/C++ code independent of the high level interface, you can change the
+interface and reuse the code in other applications.   It is also
+possible to support different types of interfaces depending on the application.
+</p>
+
+<H2><a name="Introduction_build_system"></a>2.6 Incorporating SWIG into a build system</H2>
+
+
+<p>
+SWIG is a command line tool and as such can be incorporated into any build system that supports invoking external tools/compilers.
+SWIG is most commonly invoked from within a Makefile, but is also known to be invoked from from popular IDEs such as 
+Microsoft Visual Studio.
+</p>
+
+<p>
+If you are using the GNU Autotools 
+(<a href="http://www.gnu.org/software/autoconf">Autoconf</a>/
+<a href="http://www.gnu.org/software/automake">Automake</a>/
+<a href="http://www.gnu.org/software/libtool">Libtool</a>)
+to configure SWIG use in your project, the SWIG Autoconf macros can be used.
+The primary macro is <tt>ac_pkg_swig</tt>, see
+<a href="http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html">http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html</a>.
+The <tt>ac_python_devel</tt> macro is also helpful for generating Python extensions. See the 
+<a href="http://www.gnu.org/software/ac-archive/htmldoc/index.html">Autoconf Macro Archive</a>
+for further information on this and other Autoconf macros.
+</p>
+
+<p>
+There is growing support for SWIG in some build tools, for example <a href="http://www.cmake.org">CMake</a>
+is a cross-platform, open-source build manager with built in support for SWIG. CMake can detect the SWIG executable
+and many of the target language libraries for linking against.
+CMake knows how to build shared libraries and loadable modules on many different operating systems.
+This allows easy cross platform SWIG development.  It also can generate the custom commands necessary for
+driving SWIG from IDE's and makefiles.  All of this can be done from a single cross platform input file.
+The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i:
+</p>
+
+<div class="code"><pre>
+
+# This is a CMake example for Python
+
+FIND_PACKAGE(SWIG REQUIRED)
+INCLUDE(${SWIG_USE_FILE})
+
+FIND_PACKAGE(PythonLibs)
+INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
+
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
+
+SET(CMAKE_SWIG_FLAGS "")
+
+SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
+SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
+SWIG_ADD_MODULE(example python example.i example.cxx)
+SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
+
+</pre></div>
+<p>
+The above example will generate native build files such as makefiles, nmake files and Visual Studio projects
+which will invoke SWIG and compile the generated C++ files into _example.so (UNIX) or _example.dll (Windows).
+</p>
+
+<H2><a name="Introduction_nn12"></a>2.7 Hands off code generation</H2>
+
+
+<p>
+SWIG is designed to produce working code that needs no
+hand-modification (in fact, if you look at the output, you probably
+won't want to modify it). You should think of your target language interface being
+defined entirely by the input to SWIG, not the resulting output
+file. While this approach may limit flexibility for hard-core hackers,
+it allows others to forget about the low-level implementation
+details.
+</p>
+
+<H2><a name="Introduction_nn13"></a>2.8 SWIG and freedom</H2>
+
+
+<p>
+No, this isn't a special section on the sorry state of world politics.
+However, it may be useful to know that SWIG was written with a
+certain "philosophy" about programming---namely that programmers are
+smart and that tools should just stay out of their way.  Because of
+that, you will find that SWIG is extremely permissive in what it lets
+you get away with. In fact, you can use SWIG to go well beyond
+"shooting yourself in the foot" if dangerous programming is your goal.
+On the other hand, this kind of freedom may be exactly what is needed
+to work with complicated and unusual C/C++ applications.
+</p>
+
+<p>
+Ironically, the freedom that SWIG provides is countered by an
+extremely conservative approach to code generation. At it's core, SWIG
+tries to distill even the most advanced C++ code down to a small
+well-defined set of interface building techniques based on ANSI C
+programming.  Because of this, you will find that SWIG interfaces can
+be easily compiled by virtually every C/C++ compiler and that they can
+be used on any platform.  Again, this is an important part of staying out 
+of the programmer's way----the last thing any developer wants to do is
+to spend their time debugging the output of a tool that relies on 
+non-portable or unreliable programming features.
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Java.html b/trunk/Doc/Manual/Java.html
new file mode 100644
index 0000000..164fc21
--- /dev/null
+++ b/trunk/Doc/Manual/Java.html
@@ -0,0 +1,7731 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Java</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+<body bgcolor="#FFFFFF">
+<H1><a name="Java"></a>20 SWIG and Java</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#java_overview">Overview</a>
+<li><a href="#java_preliminaries">Preliminaries</a>
+<ul>
+<li><a href="#running_swig">Running SWIG</a>
+<li><a href="#java_commandline">Additional Commandline Options</a>
+<li><a href="#getting_right_headers">Getting the right header files</a>
+<li><a href="#compiling_dynamic">Compiling a dynamic module</a>
+<li><a href="#using_module">Using your module</a>
+<li><a href="#dynamic_linking_problems">Dynamic linking problems</a>
+<li><a href="#compilation_problems_cpp">Compilation problems and compiling with C++</a>
+<li><a href="#building_windows">Building on Windows</a>
+<ul>
+<li><a href="#visual_studio">Running SWIG from Visual Studio</a>
+<li><a href="#nmake">Using NMAKE</a>
+</ul>
+</ul>
+<li><a href="#java_basic_tour">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="#module_packages_classes">Modules, packages and generated Java classes</a>
+<li><a href="#functions">Functions</a>
+<li><a href="#global_variables">Global variables</a>
+<li><a href="#constants">Constants</a>
+<li><a href="#enumerations">Enumerations</a>
+<ul>
+<li><a href="#anonymous_enums">Anonymous enums</a>
+<li><a href="#typesafe_enums">Typesafe enums</a>
+<li><a href="#proper_enums">Proper Java enums</a>
+<li><a href="#typeunsafe_enums">Type unsafe enums</a>
+<li><a href="#simple_enums">Simple enums</a>
+</ul>
+<li><a href="#pointers">Pointers</a>
+<li><a href="#structures">Structures</a>
+<li><a href="#classes">C++ classes</a>
+<li><a href="#inheritance">C++ inheritance</a>
+<li><a href="#pointers_refs_arrays">Pointers, references, arrays and pass by value</a>
+<ul>
+<li><a href="#null_pointers">Null pointers</a>
+</ul>
+<li><a href="#overloaded_functions">C++ overloaded functions</a>
+<li><a href="#java_default_arguments">C++ default arguments</a>
+<li><a href="#namespaces">C++ namespaces</a>
+<li><a href="#templates">C++ templates</a>
+<li><a href="#smart_pointers">C++ Smart Pointers</a>
+</ul>
+<li><a href="#further_details">Further details on the generated Java classes</a>
+<ul>
+<li><a href="#imclass">The intermediary JNI class</a>
+<ul>
+<li><a href="#imclass_pragmas">The intermediary JNI class pragmas</a>
+</ul>
+<li><a href="#java_module_class">The Java module class</a>
+<ul>
+<li><a href="#module_class_pragmas">The Java module class pragmas</a>
+</ul>
+<li><a href="#java_proxy_classes">Java proxy classes</a>
+<ul>
+<li><a href="#memory_management">Memory management</a>
+<li><a href="#inheritance_mirroring">Inheritance</a>
+<li><a href="#proxy_classes_gc">Proxy classes and garbage collection</a>
+<li><a href="#java_pgcpp">The premature garbage collection prevention parameter for proxy class marshalling</a>
+<li><a href="#java_multithread_libraries">Single threaded applications and thread safety</a>
+</ul>
+<li><a href="#type_wrapper_classes">Type wrapper classes</a>
+<li><a href="#enum_classes">Enum classes</a>
+<ul>
+<li><a href="#typesafe_enums_classes">Typesafe enum classes</a>
+<li><a href="#proper_enums_classes">Proper Java enum classes</a>
+<li><a href="#typeunsafe_enums_classes">Type unsafe enum classes</a>
+</ul>
+</ul>
+<li><a href="#java_directors">Cross language polymorphism using directors</a>
+<ul>
+<li><a href="#java_enabling_directors">Enabling directors</a>
+<li><a href="#java_directors_classes">Director classes</a>
+<li><a href="#java_directors_overhead">Overhead and code bloat</a>
+<li><a href="#java_directors_example">Simple directors example</a>
+<li><a href="#java_directors_threading">Director threading issues</a>
+</ul>
+<li><a href="#java_allprotected">Accessing protected members</a>
+<li><a href="#common_customization">Common customization features</a>
+<ul>
+<li><a href="#helper_functions">C/C++ helper functions</a>
+<li><a href="#class_extension">Class extension with %extend</a>
+<li><a href="#exception_handling">Exception handling with %exception and %javaexception</a>
+<li><a href="#method_access">Method access with %javamethodmodifiers</a>
+</ul>
+<li><a href="#tips_techniques">Tips and techniques</a>
+<ul>
+<li><a href="#input_output_parameters">Input and output parameters using primitive pointers and references</a>
+<li><a href="#simple_pointers">Simple pointers</a>
+<li><a href="#c_arrays">Wrapping C arrays with Java arrays</a>
+<li><a href="#unbounded_c_arrays">Unbounded C Arrays</a>
+<li><a href="#java_heap_allocations">Overriding new and delete to allocate from Java heap</a>
+</ul>
+<li><a href="#java_typemaps">Java typemaps</a>
+<ul>
+<li><a href="#default_primitive_type_mappings">Default primitive type mappings</a>
+<li><a href="#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a>
+<li><a href="#jvm64">Sixty four bit JVMs</a>
+<li><a href="#what_is_typemap">What is a typemap?</a>
+<li><a href="#typemaps_c_to_java_types">Typemaps for mapping C/C++ types to Java types</a>
+<li><a href="#typemap_attributes">Java typemap attributes</a>
+<li><a href="#special_variables">Java special variables</a>
+<li><a href="#typemaps_for_c_and_cpp">Typemaps for both C and C++ compilation</a>
+<li><a href="#java_code_typemaps">Java code typemaps</a>
+<li><a href="#java_directors_typemaps">Director specific typemaps</a>
+</ul>
+<li><a href="#typemap_examples">Typemap Examples</a>
+<ul>
+<li><a href="#simpler_enum_classes">Simpler Java enums for enums without initializers</a>
+<li><a href="#exception_typemap">Handling C++ exception specifications as Java exceptions</a>
+<li><a href="#nan_exception_typemap">NaN Exception - exception handling for a particular type</a>
+<li><a href="#converting_java_string_arrays">Converting Java String arrays to char ** </a>
+<li><a href="#expanding_java_object">Expanding a Java object to multiple arguments</a>
+<li><a href="#using_typemaps_return_arguments">Using typemaps to return arguments</a>
+<li><a href="#adding_downcasts">Adding Java downcasts to polymorphic return types</a>
+<li><a href="#adding_equals_method">Adding an equals method to the Java classes</a>
+<li><a href="#void_pointers">Void pointers and a common Java base class</a>
+<li><a href="#struct_pointer_pointer">Struct pointer to pointer</a>
+<li><a href="#java_memory_management_member_variables">Memory management when returning references to member variables</a>
+<li><a href="#java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
+<li><a href="#java_date_marshalling">Date marshalling using the javain typemap and associated attributes</a>
+</ul>
+<li><a href="#java_directors_faq">Living with Java Directors</a>
+<li><a href="#odds_ends">Odds and ends</a>
+<ul>
+<li><a href="#javadoc_comments">JavaDoc comments</a>
+<li><a href="#functional_interface">Functional interface without proxy classes</a>
+<li><a href="#using_own_jni_functions">Using your own JNI functions</a>
+<li><a href="#performance">Performance concerns and hints</a>
+<li><a href="#java_debugging">Debugging</a>
+</ul>
+<li><a href="#java_examples">Examples</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes SWIG's support of Java. 
+It covers most SWIG features, but certain low-level details are covered in less depth than in earlier chapters. 
+</p>
+
+
+<H2><a name="java_overview"></a>20.1 Overview</H2>
+
+
+<p>
+The 100% Pure Java effort is a commendable concept, however in the real world programmers often either need to re-use their existing code or in some situations 
+want to take advantage of Java but are forced into using some native (C/C++) code.
+The Java extension to SWIG makes it very easy to plumb in existing C/C++ code for access from Java, as SWIG writes the Java Native Interface (JNI) code for you. 
+It is different to using the 'javah' tool as SWIG will wrap existing C/C++ code, whereas javah takes 'native' Java function declarations and creates C/C++ function prototypes.
+SWIG wraps C/C++ code using Java proxy classes and is very useful if you want to have access to large amounts of C/C++ code from Java.
+If only one or two JNI functions are needed then using SWIG may be overkill.
+SWIG enables a Java program to easily call into C/C++ code from Java.
+Historically, SWIG was not able to generate any code to call into Java code from C++.
+However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods.
+</p>
+
+<p>
+Java is one of the few non-scripting language modules in SWIG.
+As SWIG utilizes the type safety that the Java language offers, it takes a somewhat different approach to that used for scripting languages.
+In particular runtime type checking and the runtime library are not used by Java.
+This should be borne in mind when reading the rest of the SWIG documentation.
+This chapter on Java is relatively self contained and will provide you with nearly everything you need for using SWIG and Java.
+However, the "<a href="SWIG.html#SWIG">SWIG Basics</a>" chapter will be a useful read in conjunction with this one.
+</p>
+
+<p>
+This chapter starts with a few practicalities on running SWIG and compiling the generated code.
+If you are looking for the minimum amount to read, have a look at the sections up to and including the
+<a href="#java_basic_tour">tour of basic C/C++ wrapping</a> section which explains how to call the various C/C++ code constructs from Java.
+Following this section are details of the C/C++ code and Java classes that SWIG generates.
+Due to the complexities of C and C++ there are different ways in which C/C++ code could be wrapped and called from Java.
+SWIG is a powerful tool and the rest of the chapter details how the default code wrapping can be tailored.
+Various customisation tips and techniques using SWIG directives are covered.
+The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
+</p>
+
+<H2><a name="java_preliminaries"></a>20.2 Preliminaries</H2>
+
+
+<p>
+SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and should also work with any later versions.
+Given the choice, you should probably use the latest version of Sun's JDK. 
+The SWIG Java module is known to work using Sun's JVM on Solaris, Linux and the various flavours of Microsoft Windows including Cygwin. 
+The Kaffe JVM is known to give a few problems and at the time of writing was not a fully fledged JVM with full JNI support. 
+The generated code is also known to work on vxWorks using WindRiver's PJava 3.1. 
+The best way to determine whether your combination of operating system and JDK will work is to test the examples and test-suite that comes with SWIG. 
+Run <tt>make -k check</tt> from the SWIG root directory after installing SWIG on Unix systems. </p>
+
+<p>
+The Java module requires your system to support shared libraries and dynamic loading. 
+This is the commonly used method to load JNI code so your system will more than likely support this.</p>
+
+<H3><a name="running_swig"></a>20.2.1 Running SWIG</H3>
+
+
+<p>
+Suppose that you defined a SWIG module such as the following:
+</p>
+
+<div class="code">
+<pre>
+/* File: example.i */
+%module test
+%{
+#include "stuff.h"
+%}
+int fact(int n);
+</pre>
+</div>
+
+
+<p>
+To build a Java module, run SWIG using the <tt>-java</tt> option :</p>
+
+<div class="code"><pre>
+%swig -java example.i
+</pre></div>
+
+<p>
+If building C++, add the <tt>-c++</tt> option:
+</p>
+
+<div class="code"><pre>
+$ swig -c++ -java example.i
+</pre></div>
+
+<p>
+This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
+<tt>example_wrap.cxx</tt> and numerous Java files.   The generated
+C/C++ source file contains the JNI wrapper code that needs to be compiled and linked with the
+rest of your C/C++ application. 
+</p>
+
+<p>
+The name of the wrapper file is derived from the name of the input file.  For example, if the
+input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
+To change this, you can use the <tt>-o</tt> option. 
+It is also possible to change the <a href="SWIG.html#output">output directory </a> that the Java files are generated into using <tt>-outdir</tt>.
+</p>
+
+<p>
+The following sections have further practical examples and details on how you might go about
+compiling and using the generated files.
+</p>
+
+<H3><a name="java_commandline"></a>20.2.2 Additional Commandline Options</H3>
+
+
+<p>
+The following table list the additional commandline options available for the Java module. They can also be seen by using: 
+</p>
+
+<div class="code"><pre>
+swig -java -help 
+</pre></div>
+
+<table summary="Java specific options">
+<tr>
+<th>Java specific options</th>
+</tr>
+
+<tr>
+<td>-nopgcpp</td>
+<td>suppress the premature garbage collection prevention parameter</td>
+</tr>
+
+<tr>
+<td>-noproxy</td>
+<td>generate the low-level functional interface instead of proxy classes </td>
+</tr>
+
+<tr>
+<td>-package &lt;name&gt;</td>
+<td>set name of the Java package to &lt;name&gt;</td>
+</tr>
+
+</table>
+
+<p>
+Their use will become clearer by the time you have finished reading this section on SWIG and Java.
+</p>
+
+<H3><a name="getting_right_headers"></a>20.2.3 Getting the right header files</H3>
+
+
+<p>
+In order to compile the C/C++ wrappers, the compiler needs the <tt>jni.h</tt> and <tt>jni_md.h</tt> header files which are part of the JDK. 
+They are usually in directories like this:</p>
+
+<div class="code"><pre>
+/usr/java/include
+/usr/java/include/&lt;operating_system&gt;
+</pre></div>
+
+<p>
+The exact location may vary on your machine, but the above locations are typical. </p>
+
+<H3><a name="compiling_dynamic"></a>20.2.4 Compiling a dynamic module</H3>
+
+
+<p>
+The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. 
+To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):</p>
+
+<div class="code"><pre>
+$ swig -java example.i
+$ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
+$ ld -G example_wrap.o  -o libexample.so
+</pre></div>
+
+<p>
+The exact commands for doing this vary from platform to platform. 
+However, SWIG tries to guess the right options when it is installed.  Therefore, 
+you may want to start with one of the examples in the <tt>Examples/java</tt> 
+directory.   If that doesn't work, you will need to read the man-pages for
+your compiler and linker to get the right set of options.  You might also
+check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
+additional information.
+<a href="http://weblogs.java.net/blog/kellyohair/archive/2006/01/compilation_of.html">JNI compilation</a>
+is a useful reference for compiling on different platforms.
+</p>
+
+<p>
+<b>Important</b> <br>
+If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The GCC optimisations have become 
+more aggressive from gcc-4.0 onwards and will result in code that fails with strict aliasing optimisations turned on. See the <a href="#typemaps_c_to_java_types">C/C++ to Java typemaps</a> section for more details.
+</p>
+
+<p>
+The name of the shared library output file is important. 
+If the name of your SWIG module is "<tt>example</tt>", the name of the corresponding shared library file should be "<tt>libexample.so</tt>" (or equivalent depending on your machine, see <a href="#dynamic_linking_problems">Dynamic linking problems</a> for more information). 
+The name of the module is specified using the <tt>%module</tt> directive or<tt> -module</tt> command line option.</p>
+
+<H3><a name="using_module"></a>20.2.5 Using your module</H3>
+
+
+<p>
+To load your shared native library module in Java, simply use Java's <tt>System.loadLibrary</tt> method in a Java class:</p>
+
+<div class="code"><pre>
+// main.java
+
+public class main {
+  static {
+    System.loadLibrary("example");
+  }
+
+  public static void main(String argv[]) {
+    System.out.println(example.fact(4));
+  }
+}
+</pre></div>
+
+<p>
+Compile all the Java files and run:
+</p>
+
+<div class="code"><pre>
+$ javac *.java
+$ java main
+24
+$
+</pre></div>
+
+<p>
+If it doesn't work have a look at the following section which discusses problems loading the shared library.
+</p>
+
+<H3><a name="dynamic_linking_problems"></a>20.2.6 Dynamic linking problems</H3>
+
+
+<p>
+As shown in the previous section the code to load a native library (shared library) is <tt>System.loadLibrary("name")</tt>. 
+This can fail with an UnsatisfiedLinkError exception and can be due to a number of reasons.
+</p>
+
+<p>
+You may get an exception similar to this:
+</p>
+
+<div class="code"><pre>
+$ java main
+Exception in thread "main" java.lang.UnsatisfiedLinkError: no example in java.library.path
+        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
+        at java.lang.Runtime.loadLibrary0(Runtime.java:749)
+        at java.lang.System.loadLibrary(System.java:820)
+        at main.&lt;clinit&gt;(main.java:5)
+</pre></div>
+
+<p>
+The most common cause for this is an incorrect naming of the native library for the name passed to the <tt>loadLibrary</tt> function. 
+The string passed to the <tt>loadLibrary</tt> function must not include the file extension name in the string, that is <i>.dll</i> or <i>.so</i>. 
+The string must be <i>name</i> and not <i>libname</i> for all platforms. 
+On Windows the native library must then be called <i>name.dll</i> and on most Unix systems it must be called <i>libname.so</i>. 
+</p>
+
+<p>
+Another common reason for the native library not loading is because it is not in your path. 
+On Windows make sure the <i>path</i> environment variable contains the path to the native library. 
+On Unix make sure that your <i>LD_LIBRARY_PATH</i> contains the path to the native library. 
+Adding paths to <i>LD_LIBRARY_PATH</i> can slow down other programs on your system so you may want to consider alternative approaches.
+For example you could recompile your native library with extra path information using <tt>-rpath</tt> if you're using GNU, see the GNU linker documentation (<tt>ld</tt> man page).
+You could use a command such as <tt>ldconfig</tt> (Linux) or
+<tt>crle</tt> (Solaris) to add additional search paths to the default
+system configuration (this requires root access and you will need to read the man pages).
+</p>
+
+<p>
+The native library will also not load if there are any unresolved symbols in the compiled C/C++ code. 
+The following exception is indicative of this:
+</p>
+
+<div class="code"><pre>
+$ java main
+Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined
+symbol: fact
+        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
+        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
+        at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
+        at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
+        at java.lang.System.loadLibrary(System.java, Compiled Code)
+        at main.&lt;clinit&gt;(main.java:5)
+$
+</pre></div>
+
+<p>
+This error usually indicates that you forgot to include some object files or libraries in the linking of the native library file.  
+Make sure you compile both the SWIG wrapper file and the code you are wrapping into the native library file.  
+Also make sure you pass all of the required libraries to the linker.  
+The <tt>java -verbose:jni</tt> commandline switch is also a great way to get more information on unresolved symbols.
+One last piece of advice is to beware of the common faux pas of having more than one native library version in your path.
+</p>
+
+<p>
+In summary, ensure that you are using the correct C/C++ compiler and linker combination and options for successful native library loading. 
+If you are using the examples that ship with SWIG, then the Examples/Makefile must have these set up correctly for your system. 
+The SWIG installation package makes a best attempt at getting these correct but does not get it right 100% of the time.
+The <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> also has some settings for commonly used compiler and operating system combinations.
+The following section also contains some C++ specific linking problems and solutions.
+</p>
+
+
+<H3><a name="compilation_problems_cpp"></a>20.2.7 Compilation problems and compiling with C++</H3>
+
+
+<p>
+On most machines, shared library files should be linked using the C++
+compiler.  For example:
+</p>
+
+<div class="code"><pre>
+% swig -c++ -java example.i
+% g++ -c -fpic example.cxx
+% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/
+j2sdk1.4.1/include/linux
+% g++ -shared example.o example_wrap.o -o libexample.so
+</pre></div>
+
+<p>
+In addition to this, you may need to include additional library
+files to make it work.  For example, if you are using the Sun C++ compiler on
+Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
+</p>
+
+<div class="code"><pre>
+% swig -c++ -java example.i
+% CC -c example.cxx
+% CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
+% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun
+</pre></div>
+
+<p>
+If you aren't entirely sure about the linking for C++, you
+might look at an existing C++ program.  On many Unix machines, the
+<tt>ldd</tt> command will list library dependencies.  This should give
+you some clues about what you might have to include when you link your
+shared library. For example:
+</p>
+
+<div class="code">
+<pre>
+$ ldd swig
+        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
+        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
+        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
+        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
+$
+</pre>
+</div>
+
+<p>
+Finally make sure the version of JDK header files matches the version of Java that you are running as incompatibilities could lead to compilation problems or unpredictable behaviour.
+</p>
+
+
+<H3><a name="building_windows"></a>20.2.8 Building on Windows</H3>
+
+
+<p>
+Building on Windows is roughly similar to the process used with Unix.  
+You will want to produce a DLL that can be loaded by the Java Virtual Machine.  
+This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers.  
+In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.</p>
+
+<H4><a name="visual_studio"></a>20.2.8.1 Running SWIG from Visual Studio</H4>
+
+
+<p>
+If you are developing your application within Microsoft Visual studio, SWIG can be invoked as a custom build option. 
+The Examples\java directory has a few <a href="Windows.html#Windows_examples">Windows Examples</a> containing Visual Studio project (.dsp) files.
+The process to re-create the project files for a C project are roughly:</p>
+
+<ul>
+<li>Open up a new workspace and use the AppWizard to select a DLL project.
+<li>Add both the SWIG interface file (the .i file), any supporting C files, and the name of the wrapper file that will be created by SWIG (ie. <tt>example_wrap.c</tt>).   
+Don't worry if the wrapper file doesn't exist yet--Visual Studio will keep a reference to it.
+<li>Select the SWIG interface file and go to the settings menu. Under settings, select the "Custom Build" option.
+<li>Enter "SWIG" in the description field.
+<li>Enter "<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
+<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
+<li>Next, select the settings for the entire project and go to C/C++ tab and select the Preprocessor category . Add the include directories to the JNI header files under "Additional include directories", eg "C:\jdk1.3\include,C:\jdk1.3\include\win32".
+<li>Next, select the settings for the entire project and go to Link tab and select the General category. Set the name of the output file to match the name of your Java module (ie. example.dll).
+<li>Next, select the example.c and example_wrap.c files and go to the C/C++ tab and select the Precompiled Headers tab in the project settings. Disabling precompiled headers for these files will overcome any precompiled header errors while building.
+<li>Finally, add the java compilation as a post build rule in the Post-build step tab in project settings, eg, "c:\jdk1.3\bin\javac *.java" 
+<li>Build your project.
+</ul>
+
+<p>
+Note: If using C++, choose a C++ suffix for the wrapper file, for example <tt>example_wrap.cxx</tt>.
+Use <tt>_wrap.cxx</tt> instead of <tt>_wrap.c</tt> in the instructions above and add -c++ when invoking swig.
+</p>
+
+<p>
+Now, assuming all went well, SWIG will be automatically invoked when you build your project.  
+When doing a build, any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file.
+</p>
+
+<p>
+The Java classes that SWIG output should also be compiled into .class files. 
+To run the native code in the DLL (example.dll), make sure that it is in your path then run your Java program which uses it, as described in the previous section. 
+If the library fails to load have a look at <a href="#dynamic_linking_problems">Dynamic linking problems</a>.
+</p>
+
+<H4><a name="nmake"></a>20.2.8.2 Using NMAKE</H4>
+
+
+<p>
+Alternatively, a Makefile for use by NMAKE can be written.   
+Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path.   
+Now, just write a short Makefile like this :</p>
+
+<div class="code"><pre>
+# Makefile for using SWIG and Java for C code
+
+SRCS          = example.c
+IFILE         = example
+INTERFACE     = $(IFILE).i
+WRAPFILE      = $(IFILE)_wrap.c
+
+# Location of the Visual C++ tools (32 bit assumed)
+
+TOOLS         = c:\msdev
+TARGET        = example.dll
+CC            = $(TOOLS)\bin\cl.exe
+LINK          = $(TOOLS)\bin\link.exe
+INCLUDE32     = -I$(TOOLS)\include
+MACHINE       = IX86
+
+# C Library needed to build a DLL
+
+DLLIBC        = msvcrt.lib oldnames.lib  
+
+# Windows libraries that are apparently needed
+WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib
+
+# Libraries common to all DLLs
+LIBS          = $(DLLIBC) $(WINLIB) 
+
+# Linker options
+LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \
+             /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
+
+# C compiler flags
+
+CFLAGS        = /Z7 /Od /c /nologo
+JAVA_INCLUDE    = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32
+
+java::
+	swig -java -o $(WRAPFILE) $(INTERFACE)
+	$(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
+	set LIB=$(TOOLS)\lib
+	$(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
+	javac *.java
+</pre></div>
+
+<p>
+To build the DLL and compile the java code, run NMAKE (you may need to run <tt>vcvars32</tt> first). 
+This is a pretty simplistic Makefile, but hopefully its enough to get you started.
+Of course you may want to make changes for it to work for C++ by adding in the -c++ command line switch for swig and replacing .c with .cxx.
+</p>
+
+
+<H2><a name="java_basic_tour"></a>20.3 A tour of basic C/C++ wrapping</H2>
+
+
+<p>
+By default, SWIG attempts to build a natural Java interface
+to your C/C++ code.  Functions are wrapped as functions, classes are wrapped as classes, 
+variables are wrapped with JavaBean type getters and setters and so forth.
+This section briefly covers the essential aspects of this wrapping.
+</p>
+
+<H3><a name="module_packages_classes"></a>20.3.1 Modules, packages and generated Java classes</H3>
+
+
+<p>
+The SWIG <tt>%module</tt> directive specifies the name of the Java
+module. When you specify `<tt>%module example</tt>', the <i>module name</i>
+determines the name of some of the generated files in the module.
+The generated code consists of a <i>module class</i> file <tt>example.java</tt>, an
+<i>intermediary JNI class</i> file, <tt>exampleJNI.java</tt> as well as numerous other Java <i>proxy class</i> files.
+Each proxy class is named after the structs, unions and classes you are wrapping.
+You may also get a <i>constants interface</i> file if you are wrapping any unnamed enumerations or constants, for example <tt>exampleConstants.java</tt>.
+When choosing a module name, make sure you don't use the same name as one of the generated
+proxy class files nor a Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy class, for 
+example a pointer to a primitive type. In these situations a <i>type wrapper class</i> is generated.
+Wrapping an enum generates an <i>enum class</i>, either a proper Java enum or a Java class that simulates the enums pattern.
+Details of all these generated classes will unfold as you read this section.
+</p>
+
+<p>
+The JNI (C/C++) code is generated into a file which also contains the module name, for example <tt>example_wrap.cxx</tt>
+or <tt>example_wrap.c</tt>. These C or C++ files complete the contents of the module.
+</p>
+
+<p>
+The generated Java classes can be placed into a Java package by using the <tt>-package</tt> commandline option.
+This is often combined with the <tt>-outdir</tt> to specify a package directory for generating the Java files.
+</p>
+
+<div class="code"><pre>
+swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
+</pre></div>
+
+SWIG won't create the directory, so make sure it exists beforehand.
+
+<H3><a name="functions"></a>20.3.2 Functions</H3>
+
+
+<p>
+There is no such thing as a global Java function so global C functions are wrapped as static methods in 
+the module class. For example,
+</p>
+
+<div class="code"><pre>
+%module example
+int fact(int n);
+
+</pre></div>
+
+<p>
+creates a static function that works exactly like you think it might:</p>
+
+<div class="code"><pre>
+public class example {
+  public static int fact(int n) {
+    // makes call using JNI to the C function
+  }
+}
+</pre></div>
+
+
+<p>
+The Java class <tt>example</tt> is the <i>module class</i>. The function can be used as follows from Java:</p>
+
+<div class="code"><pre>
+System.out.println(example.fact(4));
+</pre></div>
+
+
+<H3><a name="global_variables"></a>20.3.3 Global variables</H3>
+
+
+<p>
+C/C++ global variables are fully supported by SWIG.  
+Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. 
+Again because there is no such thing as a
+Java global variable, access to C/C++ global variables is done through static getter and setter functions in the module class.
+</p>
+
+<div class="code"><pre>
+// SWIG interface file with global variables
+%module example
+...
+%inline %{
+extern int My_variable;
+extern double density;
+%}
+...
+</pre></div>
+
+<p>
+Now in Java :</p>
+
+<div class="code"><pre>
+// Print out value of a C global variable
+System.out.println("My_variable = " + example.getMy_variable());
+// Set the value of a C global variable
+example.setDensity(0.8442);
+</pre></div>
+
+<p>
+The value returned by the getter will always be up to date even if the value is changed in C. 
+Note that the getters and setters produced follow the JavaBean property design pattern. 
+That is the first letter of the variable name is capitalized and preceded with set or get.
+If you have the misfortune of wrapping two variables that differ only in the capitalization of their first letters,
+use %rename to change one of the variable names. For example:
+</p>
+
+<div class="code"><pre>
+%rename Clash RenamedClash;
+float Clash;
+int clash;
+</pre></div>
+
+<p>
+If a variable is declared as <tt>const</tt>, it is wrapped as a read-only variable.  
+That is only a getter is produced.
+</p>
+
+<p>
+To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable;
+extern char *path;
+%mutable;
+</pre>
+</div>
+
+<p>
+The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
+<tt>%mutable</tt>.
+See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
+</p>
+
+<p>
+If you just want to make a specific variable immutable, supply a declaration name.  For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable path;
+...
+extern char *path;      // Read-only (due to %immutable)
+</pre>
+</div>
+
+
+<H3><a name="constants"></a>20.3.4 Constants</H3>
+
+
+<p>
+C/C++ constants are wrapped as Java static final variables.
+To create a constant, use <tt>#define</tt> or the
+<tt>%constant</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+#define PI 3.14159
+#define VERSION "1.0"
+%constant int FOO = 42;
+%constant const char *path = "/usr/local";
+</pre>
+</div>
+
+<p>
+By default the generated static final variables are initialized by making a JNI call to get their value.
+The constants are generated into the constants interface and look like this:
+</p>
+
+<div class="code"><pre>
+public interface exampleConstants {
+  public final static double PI = exampleJNI.PI_get();
+  public final static String VERSION = exampleJNI.VERSION_get();
+  public final static int FOO = exampleJNI.FOO_get();
+  public final static String path = exampleJNI.path_get();
+}
+</pre></div>
+
+<p>
+Note that SWIG has inferred the C type and used an appropriate Java type that will fit the range of all possible values for the C type.
+By default SWIG generates <b>runtime constants</b>. They are not <b>compiler constants</b> that can, for example, be used 
+in a switch statement. This can be changed by using the <tt>%javaconst(flag)</tt> directive. It works like all
+the other <a href="Customization.html#features">%feature directives</a>. The default is <tt>%javaconst(0)</tt>. 
+It is possible to initialize all wrapped constants from pure Java code by placing a <tt>%javaconst(1)</tt> <b>before</b> SWIG parses the constants.
+Putting it at the top of your interface file would ensure this.
+Here is an example:
+</p>
+
+<div class="code"><pre>
+%javaconst(1);
+%javaconst(0) BIG;
+%javaconst(0) LARGE;
+
+#define EXPRESSION (0x100+5)
+#define BIG 1000LL
+#define LARGE 2000ULL
+</pre></div>
+
+<p>
+generates:
+</p>
+
+<div class="code"><pre>
+public interface exampleConstants {
+  public final static int EXPRESSION = (0x100+5);
+  public final static long BIG = exampleJNI.BIG_get();
+  public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get();
+}
+</pre></div>
+
+<p>
+Note that SWIG has inferred the C <tt>long long</tt> type from <tt>BIG</tt> and used an appropriate Java type (<tt>long</tt>) as
+a Java <tt>long</tt> is the smallest sized Java type that will take all possible values for a C <tt>long long</tt>.
+Similarly for <tt>LARGE</tt>.
+</p>
+
+<p>
+Be careful using the <tt>%javaconst(1)</tt> directive as not all C code will compile as Java code. For example neither the 
+<tt>1000LL</tt> value for <tt>BIG</tt> nor <tt>2000ULL</tt> for <tt>LARGE</tt> above would generate valid Java code. 
+The example demonstrates how you can target particular constants (<tt>BIG</tt> and <tt>LARGE</tt>) with <tt>%javaconst</tt>.
+SWIG doesn't use <tt>%javaconst(1)</tt> as the default as it tries to generate code that will always compile.
+However, using a <tt>%javaconst(1)</tt> at the top of your interface file is strongly recommended as the preferred compile time constants
+will be generated and most C constants will compile as Java code and in any case the odd constant that doesn't can be fixed using <tt>%javaconst(0)</tt>.
+</p>
+
+<p>
+There is an alternative directive which can be used for these rare constant values that won't compile as Java code.
+This is the <tt>%javaconstvalue(value)</tt> directive, where <tt>value</tt> is a Java code replacement for the C constant and can be either a string or a number.
+This is useful if you do not want to use either the parsed C value nor a JNI call,
+such as when the C parsed value will not compile as Java code and a compile time constant is required.
+The same example demonstrates this:
+</p>
+
+<div class="code"><pre>
+%javaconst(1);
+%javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE;
+%javaconstvalue(1000) BIG;
+
+#define EXPRESSION (0x100+5)
+#define BIG 1000LL
+#define LARGE 2000ULL
+</pre></div>
+
+<p>
+Note the string quotes for <tt>"2000"</tt> are escaped. The following is then generated:
+</p>
+
+<div class="code"><pre>
+public interface exampleConstants {
+  public final static int EXPRESSION = (0x100+5);
+  public final static long BIG = 1000;
+  public final static java.math.BigInteger LARGE = new java.math.BigInteger("2000");
+}
+</pre></div>
+
+<p>
+Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
+will be accessed using a getter as described in the previous section.  They
+are not wrapped as constants.
+The exception to this rule are static const integral values defined within a class/struct, where they are wrapped as constants, eg:.
+</p>
+
+<div class="code"><pre>
+struct Maths {
+  static const int FIVE = 5;
+};
+</pre></div>
+
+
+<p>
+<b>Compatibility Note:</b> In SWIG-1.3.19 and earlier releases, the constants were generated into the module class and the constants interface didn't exist.
+Backwards compatibility is maintained as the module class implements the constants interface (even though some consider this type of interface implementation to be bad practice):
+</p>
+
+<div class="code"><pre>
+public class example implements exampleConstants {
+}
+</pre></div>
+
+<p>
+You thus have the choice of accessing these constants from either the module class or the constants interface, for example,
+<tt>example.EXPRESSION</tt> or <tt>exampleConstants.EXPRESSION</tt>.
+Or if you decide this practice isn't so bad and your own class implements <tt>exampleConstants</tt>, you can of course just use <tt>EXPRESSION</tt>.
+</p>
+
+
+<H3><a name="enumerations"></a>20.3.5 Enumerations</H3>
+
+
+<p>
+SWIG handles both named and unnamed (anonymous) enumerations.
+There is a choice of approaches to wrapping named C/C++ enums.
+This is due to historical reasons as SWIG's initial support for enums was limited and Java did not originally have support for enums.
+Each approach has advantages and disadvantages and it is important for the user to decide which is the most appropriate solution.
+There are four approaches of which the first is the default approach based on the so called Java typesafe enum pattern.
+The second generates proper Java enums.
+The final two approaches use simple integers for each enum item.
+Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.
+</p>
+
+<H4><a name="anonymous_enums"></a>20.3.5.1 Anonymous enums</H4>
+
+
+<p>
+There is no name for anonymous enums and so they are handled like constants. For example:
+</p>
+
+<div class="code">
+<pre>
+enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+is wrapped into the constants interface, in a similar manner as constants (see previous section):
+</p>
+
+<div class="code"><pre>
+public interface exampleConstants {
+  public final static int ALE = exampleJNI.ALE_get();
+  public final static int LAGER = exampleJNI.LAGER_get();
+  public final static int STOUT = exampleJNI.STOUT_get();
+  public final static int PILSNER = exampleJNI.PILSNER_get();
+  public final static int PILZ = exampleJNI.PILZ_get();
+}
+</pre></div>
+
+<p>
+The <tt>%javaconst(flag)</tt> and <tt>%javaconstvalue(value)</tt> directive introduced in the previous section on constants can also be used with enums.
+As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
+However, it is strongly recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
+interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
+Using <tt>%javaconst(1)</tt> will ensure compile time constants are generated, thereby allowing the enum values to be used in Java switch statements. 
+Example usage:
+</p>
+
+<div class="code">
+<pre>
+%javaconst(1);
+%javaconst(0) PILSNER;
+enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+generates:
+</p>
+
+<div class="code"><pre>
+public interface exampleConstants {
+  public final static int ALE = 0;
+  public final static int LAGER = 10;
+  public final static int STOUT = LAGER + 1;
+  public final static int PILSNER = exampleJNI.PILSNER_get();
+  public final static int PILZ = PILSNER;
+}
+</pre></div>
+
+<p>
+As in the case of constants, you can access them through either the module class or the constants interface, for example, <tt>example.ALE</tt> or <tt>exampleConstants.ALE</tt>.
+</p>
+
+
+<H4><a name="typesafe_enums"></a>20.3.5.2 Typesafe enums</H4>
+
+
+<p>
+This is the default approach to wrapping named enums.
+The typesafe enum pattern is a relatively well known construct to work around the lack of enums in versions of Java prior to JDK 1.5.
+It basically defines a class for the enumeration and permits a limited number of final static instances of the class.
+Each instance equates to an enum item within the enumeration.
+The implementation is in the "enumtypesafe.swg" file.
+Let's look at an example:
+</p>
+
+<div class="code">
+<pre>
+%include "enumtypesafe.swg" // optional as typesafe enums are the default
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>will generate:</p>
+
+<div class="code">
+<pre>
+public final class Beverage {
+  public final static Beverage ALE = new Beverage("ALE");
+  public final static Beverage LAGER = new Beverage("LAGER", exampleJNI.LAGER_get());
+  public final static Beverage STOUT = new Beverage("STOUT");
+  public final static Beverage PILSNER = new Beverage("PILSNER");
+  public final static Beverage PILZ = new Beverage("PILZ", exampleJNI.PILZ_get());
+  [... additional support methods omitted for brevity ...]
+}
+</pre>
+</div>
+
+<p>
+See <a href="#typesafe_enums_classes">Typesafe enum classes</a> to see the omitted support methods.
+Note that the enum item with an initializer (LAGER) is initialized with the enum value obtained via a JNI call.
+However, as with anonymous enums and constants, use of the <tt>%javaconst</tt> directive is strongly recommended to change this behaviour:
+</p>
+
+<div class="code">
+<pre>
+%include "enumtypesafe.swg" // optional as typesafe enums are the default
+%javaconst(1);
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+will generate:
+</p>
+
+<div class="code">
+<pre>
+public final class Beverage {
+  public final static Beverage ALE = new Beverage("ALE");
+  public final static Beverage LAGER = new Beverage("LAGER", 10);
+  public final static Beverage STOUT = new Beverage("STOUT");
+  public final static Beverage PILSNER = new Beverage("PILSNER");
+  public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
+  [... additional support methods omitted for brevity ...]
+}
+</pre>
+</div>
+
+<p>
+The generated code is easier to read and more efficient as a true constant is used instead of a JNI call.
+As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
+However, it is recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
+interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
+The <tt>%javaconstvalue(value)</tt> directive can also be used for typesafe enums.
+Note that global enums are generated into a Java class within whatever package you are using.
+C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.
+</p>
+
+<p>
+Typesafe enums have their advantages over using plain integers in that they they can be used in a typesafe manner.
+However, there are limitations. For example, they cannot be used in switch statements and serialization is an issue.
+Please look at the following references for further information: 
+
+<a href="http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums">Replace Enums with Classes</a> in <i>Effective Java Programming</i> on the Sun website,
+<a href="http://www.javaworld.com/javaworld/jw-07-1997/jw-07-enumerated.html">Create enumerated constants in Java</a> JavaWorld article,
+<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip133.html">Java Tip 133: More on typesafe enums</a> and
+<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip122.html">Java Tip 122: Beware of Java typesafe enumerations</a> JavaWorld tips.
+</p>
+
+<p>
+Note that the syntax required for using typesafe enums is the same as that for proper Java enums.
+This is useful during the period that a project has to support legacy versions of Java.
+When upgrading to JDK 1.5 or later, proper Java enums could be used instead, without users having to change their code.
+The following section details proper Java enum generation.
+</p>
+
+<H4><a name="proper_enums"></a>20.3.5.3 Proper Java enums</H4>
+
+
+<p>
+Proper Java enums were only introduced in JDK 1.5 so this approach is only compatible with more recent versions of Java.
+Java enums have been designed to overcome all the limitations of both typesafe and type unsafe enums
+and should be the choice solution, provided older versions of Java do not have to be supported.
+In this approach, each named C/C++ enum is wrapped by a Java enum.
+Java enums, by default, do not support enums with initializers.
+Java enums are in many respects similar to Java classes in that they can be customised with additional methods.
+SWIG takes advantage of this feature to facilitate wrapping C/C++ enums that have initializers.
+In order to wrap all possible C/C++ enums using proper Java enums, the "enums.swg" file must be used.
+Let's take a look at an example.
+</p>
+
+<div class="code">
+<pre>
+%include "enums.swg"
+%javaconst(1);
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+will generate:
+</p>
+
+<div class="code">
+<pre>
+public enum Beverage {
+  ALE,
+  LAGER(10),
+  STOUT,
+  PILSNER,
+  PILZ(PILSNER);
+  [... additional support methods omitted for brevity ...]
+}
+</pre>
+</div>
+
+<p>
+See <a href="#proper_enums_classes">Proper Java enum classes</a> to see the omitted support methods.
+The generated Java enum has numerous additional methods to support enums with initializers, such as <tt>LAGER</tt> above.
+Note that as with the typesafe enum pattern, enum items with initializers are by default initialized with the enum value obtained via a JNI call.
+However, this is not the case above as we have used the recommended <tt>%javaconst(1)</tt> to avoid the JNI call.
+The <tt>%javaconstvalue(value)</tt> directive covered in the <a href="#constants">Constants</a> section can also be used for proper Java enums.
+</p>
+
+<p>
+The additional support methods need not be generated if none of the enum items have initializers and this is covered later in the 
+<a href="#simpler_enum_classes">Simpler Java enums for enums without initializers</a> section.
+</p>
+
+<H4><a name="typeunsafe_enums"></a>20.3.5.4 Type unsafe enums</H4>
+
+
+<p>
+In this approach each enum item in a named enumeration is wrapped as a static final integer in a class named after the C/C++ enum name.
+This is a commonly used pattern in Java to simulate C/C++ enums, but it is not typesafe.
+However, the main advantage over the typesafe enum pattern is enum items can be used in switch statements.
+In order to use this approach, the "enumtypeunsafe.swg" file must be used.
+Let's take a look at an example.
+</p>
+
+<div class="code">
+<pre>
+%include "enumtypeunsafe.swg"
+%javaconst(1);
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+will generate:
+</p>
+
+<div class="code">
+<pre>
+public final class Beverage {
+  public final static int ALE = 0;
+  public final static int LAGER = 10;
+  public final static int STOUT = LAGER + 1;
+  public final static int PILSNER = STOUT + 1;
+  public final static int PILZ = PILSNER;
+}
+</pre>
+</div>
+
+<p>
+As is the case previously, the default is <tt>%javaconst(0)</tt> as not all C/C++ values will compile as Java code.
+However, again it is recommended to add in a <tt>%javaconst(1)</tt> directive.
+and the <tt>%javaconstvalue(value)</tt> directive covered in the <a href="#constants">Constants</a> section can also be used for type unsafe enums.
+Note that global enums are generated into a Java class within whatever package you are using.
+C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.
+</p>
+
+<p>
+Note that unlike typesafe enums, this approach requires users to mostly use different syntax compared with proper Java enums.
+Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.
+</p>
+
+<H4><a name="simple_enums"></a>20.3.5.5 Simple enums</H4>
+
+
+<p>
+This approach is similar to the type unsafe approach.
+Each enum item is also wrapped as a static final integer.
+However, these integers are not generated into a class named after the C/C++ enum.
+Instead, global enums are generated into the constants interface.
+Also, enums defined in a C++ class have their enum items generated directly into the Java proxy class rather than an inner class within the Java proxy class.
+In fact, this approach is effectively wrapping the enums as if they were anonymous enums and the resulting code is as per <a href="#anonymous_enums">anonymous enums</a>.
+The implementation is in the "enumsimple.swg" file.
+</p>
+
+<p>
+<b>Compatibility Note:</b>
+SWIG-1.3.21 and earlier versions wrapped all enums using this approach.
+The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.
+</p>
+
+<H3><a name="pointers"></a>20.3.6 Pointers</H3>
+
+
+<p>
+C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no problem working with
+incomplete type information.  Here is a rather simple interface:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+FILE *fopen(const char *filename, const char *mode);
+int fputs(const char *, FILE *);
+int fclose(FILE *);
+</pre>
+</div>
+
+<p>
+When wrapped, you will be able to use the functions in a natural way from Java. For example:
+</p>
+
+<div class="code">
+<pre>
+SWIGTYPE_p_FILE f = example.fopen("junk","w");
+example.fputs("Hello World\n", f);
+example.fclose(f);
+</pre>
+</div>
+
+<p>
+C pointers in the Java module are stored in a Java <tt>long</tt> and cross the JNI boundary held within this 64 bit number.
+Many other SWIG language modules use an encoding of the pointer in a string. 
+These scripting languages use the SWIG runtime type checker for dynamic type checking as they do not support static type checking by a compiler.
+In order to implement static type checking of pointers within Java, they are wrapped by a simple Java class. 
+In the example above the <tt>FILE *</tt> pointer is wrapped with a <i>type wrapper class </i> 
+called <tt>SWIGTYPE_p_FILE</tt>.
+</p>
+
+<p>
+Once obtained, a type wrapper object can be freely passed around to different C functions that
+expect to receive an object of that type.  The only thing you can't do is 
+dereference the pointer from Java. Of course, that isn't much of a concern in this example.
+</p>
+
+<p>
+As much as you might be inclined to modify a pointer value directly
+from Java, don't.  The value is not necessarily the
+same as the logical memory address of the underlying object.  The value will
+vary depending on the native byte-ordering of the platform (i.e.,
+big-endian vs. little-endian).  
+Most JVMs are 32 bit applications so any JNI code must also be compiled as 32 bit. 
+The net result is pointers in JNI code are also 32 bits and 
+are stored in the high order 4 bytes on big-endian machines and in the low order 4 bytes on little-endian machines. 
+By design it is also not possible to manually cast
+a pointer to a new type by using Java casts as it is particularly dangerous especially when
+casting C++ objects.  If you need to cast a pointer or
+change its value, consider writing some helper functions instead.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+/* C-style cast */
+Bar *FooToBar(Foo *f) {
+   return (Bar *) f;
+}
+
+/* C++-style cast */
+Foo *BarToFoo(Bar *b) {
+   return dynamic_cast&lt;Foo*&gt;(b);
+}
+
+Foo *IncrFoo(Foo *f, int i) {
+    return f+i;
+}
+%}
+</pre>
+</div>
+
+<p>
+Also, if working with C++, you should always try
+to use the new C++ style casts.  For example, in the above code, the
+C-style cast may return a bogus result whereas as the C++-style cast will return
+a NULL pointer if the conversion can't be performed.
+</p>
+
+<H3><a name="structures"></a>20.3.7 Structures</H3>
+
+
+<p>
+If you wrap a C structure, it is wrapped by a Java class with getters and setters for access to the
+member variables. For example,
+</p>
+
+<div class="code"><pre>
+struct Vector {
+	double x,y,z;
+};
+
+</pre></div>
+
+<p>
+is used as follows:
+</p>
+
+<div class="code"><pre>
+Vector v = new Vector();
+v.setX(3.5);
+v.setY(7.2);
+double x = v.getX();
+double y = v.getY();
+</pre></div>
+
+<p>
+The variable setters and getters are also based on the JavaBean design pattern already covered under the Global variables section.
+Similar access is provided for unions and the public data members of C++ classes.</p>
+
+<p>
+This object is actually an instance of a Java class that has been wrapped around a pointer to the C structure.  
+This instance doesn't actually do anything--it just serves as a proxy.
+The pointer to the C object is held in the Java proxy class in much the same way as pointers are held by type wrapper classes.
+Further details about Java proxy classes are covered a little later.
+</p>
+
+<p>
+<tt>const</tt> members of a structure are read-only. Data members
+can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   ...
+   %immutable;
+   int x;        /* Read-only members */
+   char *name;
+   %mutable;
+   ...
+};
+</pre>
+</div>
+
+<p>
+When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
+dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
+SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
+released and a new value created.   If this is not the behavior you want, you will have to use
+a typemap (described later).
+</p>
+
+<p>
+If a structure contains arrays, access to those arrays is managed through pointers.  For
+example, consider this:
+</p>
+
+<div class="code">
+<pre>
+struct Bar {
+    int  x[16];
+};
+</pre>
+</div>
+
+<p>
+If accessed in Java, you will see behavior like this:
+</p>
+
+<div class="code">
+<pre>
+Bar b = new Bar();
+SWIGTYPE_p_int x = b.getX();
+</pre>
+</div>
+
+<p>
+This pointer can be passed around to functions that expect to receive
+an <tt>int *</tt> (just like C).   You can also set the value of an array member using
+another pointer.  For example:
+</p>
+
+<div class="code">
+<pre>
+Bar b = new Bar();
+SWIGTYPE_p_int x = b.getX();
+Bar c = new Bar();
+c.setX(x);                    // Copy contents of b.x to c.x
+</pre>
+</div>
+
+<p>
+For array assignment (setters not getters), SWIG copies the entire contents of the array starting with the data pointed
+to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
+no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
+fault or access violation.
+The default wrapping makes it hard to set or get just one element of the array and so array access from Java is somewhat limited.
+This can be changed easily though by using the approach outlined later in the <a href="#c_arrays">Wrapping C arrays with Java arrays</a> and
+<a href="#unbounded_c_arrays">Unbounded C Arrays</a> sections.
+</p>
+
+<p>
+When a member of a structure is itself a structure, it is handled as a
+pointer.  For example, suppose you have two structures like this:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   int a;
+};
+
+struct Bar {
+   Foo f;
+};
+</pre>
+</div>
+
+<p>
+Now, suppose that you access the <tt>f</tt> member of <tt>Bar</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+Bar b = new Bar();
+Foo x = b.getF();
+</pre>
+</div>
+
+<p>
+In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
+This is the same value as generated by this C code:
+</p>
+
+<div class="code">
+<pre>
+Bar b;
+Foo *x = &amp;b-&gt;f;       /* Points inside b */
+</pre>
+</div>
+
+<p>
+Because the pointer points inside the structure, you can modify the contents and 
+everything works just like you would expect. For example:
+</p>
+
+<div class="code">
+<pre>
+Bar b = new Bar();
+b.getF().setA(3);   // Modify b.f.a
+Foo x = b.getF();                   
+x.setA(3);          // Modify x.a - this is the same as b.f.a
+</pre>
+</div>
+
+
+<H3><a name="classes"></a>20.3.8 C++ classes</H3>
+
+
+<p>
+C++ classes are wrapped by Java classes as well. For example, if you have this class,
+</p>
+
+<div class="code"><pre>
+class List {
+public:
+  List();
+  ~List();
+  int  search(char *item);
+  void insert(char *item);
+  void remove(char *item);
+  char *get(int n);
+  int  length;
+};
+</pre></div>
+
+<p>
+you can use it in Java like this:
+</p>
+
+<div class="code"><pre>
+List l = new List();
+l.insert("Ale");
+l.insert("Stout");
+l.insert("Lager");
+String item = l.get(2);
+int length = l.getLength();
+</pre></div>
+
+<p>
+Class data members are accessed in the same manner as C structures.  
+</p>
+
+<p>
+Static class members are unsurprisingly wrapped as static members of the Java class:
+</p>
+
+<div class="code">
+<pre>
+class Spam {
+public:
+   static void foo();
+   static int bar;
+};
+</pre>
+</div>
+
+<p>
+The static members work like any other Java static member:
+</p>
+
+<div class="code">
+<pre>
+Spam.foo();
+int bar = Spam.getBar();
+</pre>
+</div>
+
+
+<H3><a name="inheritance"></a>20.3.9 C++ inheritance</H3>
+
+
+<p>
+SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
+classes like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+...
+};
+
+class Bar : public Foo {
+...
+};
+</pre>
+</div>
+
+<p>
+those classes are wrapped into a hierarchy of Java classes that reflect the same inheritance
+structure:
+</p>
+
+<div class="code">
+<pre>
+Bar b = new Bar();
+Class c = b.getClass();
+System.out.println(c.getSuperclass().getName());
+</pre>
+</div>
+
+<p>
+will of course display:
+</p>
+
+<div class="code"><pre>
+Foo
+</pre></div>
+
+
+<p>
+Furthermore, if you have functions like this
+</p>
+
+<div class="code">
+<pre>
+void spam(Foo *f);
+</pre>
+</div>
+
+<p>
+then the Java function <tt>spam()</tt> accepts instances of <tt>Foo</tt> or instances of any other proxy classes derived from <tt>Foo</tt>.
+</p>
+
+<p>
+Note that Java does not support multiple inheritance so any multiple inheritance in the C++ code is not going to work. 
+A warning is given when multiple inheritance is detected and only the first base class is used. 
+</p>
+
+<H3><a name="pointers_refs_arrays"></a>20.3.10 Pointers, references, arrays and pass by value</H3>
+
+
+<p>
+In C++, there are many different ways a function might receive
+and manipulate objects.  For example:
+</p>
+
+<div class="code">
+<pre>
+void spam1(Foo *x);      // Pass by pointer
+void spam2(Foo &amp;x);      // Pass by reference
+void spam3(Foo x);       // Pass by value
+void spam4(Foo x[]);     // Array of objects
+</pre>
+</div>
+
+<p>
+In Java, there is no detailed distinction like this--specifically,
+there are only instances of classes.  There are no pointers nor references.
+Because of this, SWIG unifies all of these types
+together in the wrapper code.  For instance, if you actually had the
+above functions, it is perfectly legal to do this from Java:
+</p>
+
+<div class="code">
+<pre>
+Foo f = new Foo();  // Create a Foo
+example.spam1(f);   // Ok. Pointer
+example.spam2(f);   // Ok. Reference
+example.spam3(f);   // Ok. Value.
+example.spam4(f);   // Ok. Array (1 element)
+</pre>
+</div>
+
+<p>
+Similar behavior occurs for return values.  For example, if you had
+functions like this,
+</p>
+
+<div class="code">
+<pre>
+Foo *spam5();
+Foo &amp;spam6();
+Foo  spam7();
+</pre>
+</div>
+
+<p>
+then all three functions will return a pointer to some <tt>Foo</tt> object.
+Since the third function (spam7) returns a value, newly allocated memory is used 
+to hold the result and a pointer is returned (Java will release this memory 
+when the returned object's finalizer is run by the garbage collector).
+</p>
+
+<H4><a name="null_pointers"></a>20.3.10.1 Null pointers</H4>
+
+
+<p>
+Working with null pointers is easy. 
+A Java <tt>null</tt> can be used whenever a method expects a proxy class or typewrapper class.
+However, it is not possible to pass null to C/C++ functions that take parameters by value or by reference. 
+If you try you will get a NullPointerException.
+</p>
+
+<div class="code">
+<pre>
+example.spam1(null);   // Pointer - ok
+example.spam2(null);   // Reference - NullPointerException
+example.spam3(null);   // Value - NullPointerException
+example.spam4(null);   // Array - ok
+</pre>
+</div>
+
+<p>
+For <tt>spam1</tt> and <tt>spam4</tt> above the Java <tt>null</tt> gets translated into a NULL pointer for passing to the C/C++ function. 
+The converse also occurs, that is, NULL pointers are translated into <tt>null</tt> Java objects when returned from a C/C++ function.
+</p>
+
+<H3><a name="overloaded_functions"></a>20.3.11 C++ overloaded functions</H3>
+
+
+<p>
+C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
+if you have two functions like this:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+void foo(int);
+void foo(char *c);
+</pre>
+</div>
+
+<p>
+You can use them in Java in a straightforward manner:
+</p>
+
+<div class="code">
+<pre>
+example.foo(3);           // foo(int)
+example.foo("Hello");     // foo(char *c)
+</pre>
+</div>
+
+<p>
+Similarly, if you have a class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+    Foo(const Foo &amp;);
+    ...
+};
+</pre>
+</div>
+
+<p>
+you can write Java code like this:
+</p>
+
+<div class="code">
+<pre>
+Foo f = new Foo();        // Create a Foo
+Foo g = new Foo(f);       // Copy f
+</pre>
+</div>
+
+<p>
+Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
+cannot disambiguate as there can be more than one C++ type mapping onto a single Java type. For example:
+</p>
+
+<div class="code">
+<pre>
+void spam(int);
+void spam(unsigned short);
+</pre>
+</div>
+
+<p>
+Here both int and unsigned short map onto a Java int. 
+Here is another example:
+</p>
+
+<div class="code">
+<pre>
+void foo(Bar *b);
+void foo(Bar &amp;b);
+</pre>
+</div>
+
+<p>
+If declarations such as these appear, you will get a warning message like this:
+</p>
+
+<div class="code">
+<pre>
+example.i:12: Warning(515): Overloaded method spam(unsigned short) ignored.
+Method spam(int) at example.i:11 used.
+</pre>
+</div>
+
+<p>
+To fix this, you either need to either <a href="SWIG.html#SWIG_rename_ignore">rename or ignore</a> one of the methods.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(spam_ushort) spam(unsigned short);
+...
+void spam(int);    
+void spam(unsigned short);   // Now renamed to spam_ushort
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+%ignore spam(unsigned short);
+...
+void spam(int);    
+void spam(unsigned short);   // Ignored
+</pre>
+</div>
+
+<H3><a name="java_default_arguments"></a>20.3.12 C++ default arguments</H3>
+
+
+<p>
+Any function with a default argument is wrapped by generating an additional function for each argument that is defaulted.
+For example, if we have the following C++:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+void defaults(double d=10.0, int i=0);
+</pre>
+</div>
+
+<p>
+The following methods are generated in the Java module class:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static void defaults(double d, int i) { ... }
+  public static void defaults(double d) { ... }
+  public static void defaults() { ... }
+}
+</pre>
+</div>
+
+<p>
+It is as if SWIG had parsed three separate overloaded methods.
+The same approach is taken for static methods, constructors and member methods.
+</p>
+
+<p>
+<b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped these with a
+single wrapper method and so the default values could not be taken advantage of from Java.
+Further details on default arguments and how to restore this approach are given in the more general 
+<a href="SWIGPlus.html#SWIGPlus_default_args">Default arguments</a> section.
+</p>
+
+
+<H3><a name="namespaces"></a>20.3.13 C++ namespaces</H3>
+
+
+<p>
+SWIG is aware of C++ namespaces, but namespace names do not appear in
+the module nor do namespaces result in a module that is broken up into
+submodules or packages.  For example, if you have a file like this,
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+namespace foo {
+   int fact(int n);
+   struct Vector {
+       double x,y,z;
+   };
+};
+</pre>
+</div>
+
+<p>
+it works in Java as follows:
+</p>
+
+<div class="code">
+<pre>
+int f = example.fact(3);
+Vector v = new Vector();
+v.setX(3.4);
+double y = v.getY();
+</pre>
+</div>
+
+<p>
+If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
+For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(Bar_spam) Bar::spam;
+
+namespace Foo {
+    int spam();
+}
+
+namespace Bar {
+    int spam();
+}
+</pre>
+</div>
+
+<p>
+If you have more than one namespace and you want to keep their
+symbols separate, consider wrapping them as separate SWIG modules.
+Each SWIG module can be placed into a separate package.
+</p>
+
+<H3><a name="templates"></a>20.3.14 C++ templates</H3>
+
+
+<p>
+C++ templates don't present a huge problem for SWIG.  However, in order
+to create wrappers, you have to tell SWIG to create wrappers for a particular
+template instantiation.  To do this, you use the <tt>%template</tt> directive.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include &lt;utility&gt;
+%}
+
+template&lt;class T1, class T2&gt;
+struct pair {
+   typedef T1 first_type;
+   typedef T2 second_type;
+   T1 first;
+   T2 second;
+   pair();
+   pair(const T1&amp;, const T2&amp;);
+  ~pair();
+};
+
+%template(pairii) pair&lt;int,int&gt;;
+</pre>
+</div>
+
+<p>
+In Java:
+</p>
+
+<div class="code">
+<pre>
+pairii p = new pairii(3,4);
+int first = p.getFirst();
+int second = p.getSecond();
+</pre>
+</div>
+
+<p>
+Obviously, there is more to template wrapping than shown in this example.
+More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.   
+</p>
+
+<H3><a name="smart_pointers"></a>20.3.15 C++ Smart Pointers</H3>
+
+
+<p>
+In certain C++ programs, it is common to use classes that have been wrapped by
+so-called "smart pointers."   Generally, this involves the use of a template class
+that implements <tt>operator-&gt;()</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T&gt; class SmartPtr {
+   ...
+   T *operator-&gt;();
+   ...
+}
+</pre>
+</div>
+
+<p>
+Then, if you have a class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int bar();
+};
+</pre>
+</div>
+
+<p>
+A smart pointer would be used in C++ as follows:
+</p>
+
+<div class="code">
+<pre>
+SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
+...
+p-&gt;x = 3;                        // Foo::x
+int y = p-&gt;bar();                // Foo::bar
+</pre>
+</div>
+
+<p>
+To wrap this in Java, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
+<tt>Foo</tt> object.  Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+...
+%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
+...
+</pre>
+</div>
+
+<p>
+Now, in Java, everything should just "work":
+</p>
+
+<div class="code">
+<pre>
+SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
+p.setX(3);                           // Foo::x
+int y = p.bar();                     // Foo::bar
+</pre>
+</div>
+
+<p>
+If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
+simply use the <tt>__deref__()</tt> method.  For example:
+</p>
+
+<div class="code">
+<pre>
+Foo f = p.__deref__();               // Returns underlying Foo *
+</pre>
+</div>
+
+<H2><a name="further_details"></a>20.4 Further details on the generated Java classes</H2>
+
+
+<p>
+In the previous section, a high-level view of Java wrapping was
+presented.  A key component of this wrapping is that structures and
+classes are wrapped by Java proxy classes and type wrapper classes are used
+in situations where no proxies are generated.  This provides a very
+natural, type safe Java interface to the C/C++ code and fits in with the Java programming paradigm.
+However, a number of low-level details were omitted.  This section provides a brief overview
+of how the proxy classes work and then covers the type wrapper classes.
+Finally enum classes are covered.
+First, the crucial intermediary JNI class is considered.
+</p>
+
+<H3><a name="imclass"></a>20.4.1 The intermediary JNI class</H3>
+
+
+<p>
+In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
+details of low-level structure and class wrapping are described.  To summarize those chapters, if you
+have a global function and class like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int spam(int num, Foo* foo);
+};
+void egg(Foo* chips);
+</pre>
+</div>
+
+<p>
+then SWIG transforms the class into a set of low-level procedural wrappers.
+These procedural wrappers essentially perform the equivalent of this C++ code:
+</p>
+
+<div class="code">
+<pre>
+Foo *new_Foo() {
+    return new Foo();
+}
+void delete_Foo(Foo *f) {
+    delete f;
+}
+int Foo_x_get(Foo *f) {
+    return f-&gt;x;
+}
+void Foo_x_set(Foo *f, int value) {
+    f-&gt;x = value;
+}
+int Foo_spam(Foo *f, int num, Foo* foo) {
+    return f-&gt;spam(num, foo);
+}
+</pre>
+</div>
+
+<p>
+These procedural function names don't actually exist, but their functionality appears inside the generated
+JNI functions. The JNI functions have to follow a particular naming convention so the function names are actually:
+</p>
+
+<div class="code">
+<pre>
+SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
+SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
+                                                    jlong jarg1);
+SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls,
+                                                    jlong jarg1, jobject jarg1_, jint jarg2);
+SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls,
+                                                    jlong jarg1, jobject jarg1_);
+SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls,
+                                                  jlong jarg1, jobject jarg1_, jint jarg2,
+                                                  jlong jarg3, jobject jarg3_);
+SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls,
+                                            jlong jarg1, jobject jarg1_);
+</pre>
+</div>
+
+<p>
+For every JNI C function there has to be a static native Java function. These appear in the intermediary JNI class:
+</p>
+
+<div class="code">
+<pre>
+class exampleJNI {
+  public final static native long new_Foo();
+  public final static native void delete_Foo(long jarg1);
+  public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2);
+  public final static native int Foo_x_get(long jarg1, Foo jarg1_);
+  public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2,
+                                          long jarg3, Foo jarg3_);
+  public final static native void egg(long jarg1, Foo jarg1_);
+}
+</pre>
+</div>
+
+<p>
+This class contains the complete Java - C/C++ interface so all function calls go via this class. 
+As this class acts as a go-between for all JNI calls to C/C++ code from the Java <a href="#java_proxy_classes">proxy classes</a>, <a href="#type_wrapper_classes">type wrapper classes</a> and <a href="#java_module_class">module class</a>, it is known as the intermediary JNI class.
+</p>
+
+<p>
+You may notice that SWIG uses a Java long wherever a pointer or class object needs to be marshalled across the Java-C/C++ boundary.
+This approach leads to minimal JNI code which makes for better performance as JNI code involves a lot of string manipulation.
+SWIG favours generating Java code over JNI code as Java code is compiled into byte code and avoids the costly string operations needed in JNI code.
+This approach has a downside though as the proxy class might get collected before the native method has completed.
+You might notice above that there is an additional parameters with a underscore postfix, eg <tt>jarg1_</tt>.
+These are added in order to prevent <a href="#java_pgcpp">premature garbage collection when marshalling proxy classes</a>.
+</p>
+
+<p>
+The functions in the intermediary JNI class cannot be accessed outside of its package. Access to them is gained through the module class for globals otherwise the appropriate proxy class.
+</p>
+
+<a name="java_module_directive"></a>
+<p>
+The name of the intermediary JNI class can be changed from its default, that is, the module name with JNI appended after it. 
+The module directive attribute <tt>jniclassname</tt> is used to achieve this:
+</p>
+
+<div class="code">
+<pre>
+%module (jniclassname="name") modulename
+</pre>
+</div>
+
+<p>
+If <tt>name</tt> is the same as <tt>modulename</tt> then the module class name gets changed
+from <tt>modulename</tt> to <tt>modulenameModule</tt>.
+</p>
+
+<H4><a name="imclass_pragmas"></a>20.4.1.1 The intermediary JNI class pragmas</H4>
+
+
+<p>
+The intermediary JNI class can be tailored through the use of pragmas, but is not commonly done. The pragmas for this class are:
+</p>
+
+<table BORDER summary="Intermediary JNI class pragmas">
+<tr VALIGN=TOP>
+<td><b>Pragma</b></td>
+<td><b>Description</b></td>
+</tr>
+
+<tr>
+    <td>jniclassbase            </td> <td>Base class for the intermediary JNI class</td>
+</tr>
+<tr>
+    <td>jniclassclassmodifiers  </td> <td>Class modifiers and class type for the intermediary JNI class</td>
+</tr>
+<tr>
+    <td>jniclasscode            </td> <td>Java code is copied verbatim into the intermediary JNI class</td>
+</tr>
+<tr>
+    <td>jniclassimports         </td> <td>Java code, usually one or more import statements, placed before the intermediary JNI class definition</td>
+</tr>
+<tr>
+    <td>jniclassinterfaces      </td> <td>Comma separated interface classes for the intermediary JNI class</td>
+</tr>
+</table>
+
+<p>
+The pragma code appears in the generated intermediary JNI class where you would expect:
+</p>
+
+<div class="code">
+<pre>
+[ jniclassimports pragma ]
+[ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
+                                          implements [ jniclassinterfaces pragma ] {
+[ jniclasscode pragma ]
+... SWIG generated native methods ...
+}
+</pre>
+</div>
+
+<p>
+The <tt>jniclasscode</tt> pragma is quite useful for adding in a static block for loading the shared library / dynamic link library and demonstrates how pragmas work:
+</p>
+
+<div class="code">
+<pre>
+%pragma(java) jniclasscode=%{
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. \n" + e);
+      System.exit(1);
+    }
+  }
+%}
+</pre>
+</div>
+
+<p>
+Pragmas will take either <tt>""</tt> or <tt>%{ %}</tt> as delimiters. 
+For example, let's change the intermediary JNI class access to public. 
+</p>
+
+<div class="code">
+<pre>
+%pragma(java) jniclassclassmodifiers="public class"
+</pre>
+</div>
+
+<p>
+All the methods in the intermediary JNI class will then be callable outside of the package as the method modifiers are public by default.
+</p>
+
+<H3><a name="java_module_class"></a>20.4.2 The Java module class</H3>
+
+
+<p>
+All global functions and variable getters/setters appear in the module class. For our example, there is just one function:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static void egg(Foo chips) {
+    exampleJNI.egg(Foo.getCPtr(chips), chips);
+  }
+}
+</pre>
+</div>
+
+<p>
+The module class is necessary as there is no such thing as a global in Java so all the C globals are put into this class. They are generated as static functions and so must be accessed as such by using the module name in the static function call:
+</p>
+
+<div class="code">
+<pre>
+example.egg(new Foo());
+</pre>
+</div>
+
+<p>
+The primary reason for having the module class wrapping the calls in the intermediary JNI class is to implement static type checking. In this case only a <tt>Foo</tt> can be passed to the <tt>egg</tt> function, whereas any <tt>long</tt> can be passed to the <tt>egg</tt> function in the intermediary JNI class.
+</p>
+
+<H4><a name="module_class_pragmas"></a>20.4.2.1 The Java module class pragmas</H4>
+
+
+<p>
+The module class can be tailored through the use of pragmas, in the same manner as the intermediary JNI class. The pragmas are similarly named and are used in the same way. The complete list follows:
+</p>
+
+<table BORDER summary="Java module class pragmas">
+<tr VALIGN=TOP>
+<td><b>Pragma</b></td>
+<td><b>Description</b></td>
+</tr>
+<tr>
+    <td>modulebase            </td> <td>Base class for the module class</td>
+</tr>
+<tr>
+    <td>moduleclassmodifiers  </td> <td>Class modifiers and class type for the module class</td>
+</tr>
+<tr>
+    <td>modulecode            </td> <td>Java code is copied verbatim into the module class</td>
+</tr>
+<tr>
+    <td>moduleimports         </td> <td>Java code, usually one or more import statements, placed before the module class definition</td>
+</tr>
+<tr>
+    <td>moduleinterfaces      </td> <td>Comma separated interface classes for the module class</td>
+</tr>
+
+</table>
+
+
+<p>
+The pragma code appears in the generated module class like this:
+</p>
+
+<div class="code">
+<pre>
+[ moduleimports pragma ]
+[ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
+                                      implements [ moduleinterfaces pragma ] {
+[ modulecode pragma ]
+... SWIG generated wrapper functions ...
+}
+</pre>
+</div>
+
+<p>
+See <a href="#imclass_pragmas">The intermediary JNI class pragmas</a> section for further details on using pragmas.
+</p>
+
+
+<H3><a name="java_proxy_classes"></a>20.4.3 Java proxy classes</H3>
+
+
+<p>
+A Java proxy class is generated for each structure, union or C++ class that is wrapped.
+Proxy classes have also been called <a href="http://java.sun.com/developer/JDCTechTips/2001/tt0612.html#tip2">peer classes</a>.
+The default proxy class for our previous example looks like this:
+</p>
+
+<div class="code">
+<pre>
+public class Foo {
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  protected Foo(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr(Foo obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+
+  protected void finalize() {
+    delete();
+  }
+
+  public synchronized void delete() {
+    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
+      swigCMemOwn = false;
+      exampleJNI.delete_Foo(swigCPtr);
+    }
+    swigCPtr = 0;
+  }
+
+  public void setX(int value) {
+    exampleJNI.Foo_x_set(swigCPtr, this, value);
+  }
+
+  public int getX() {
+    return exampleJNI.Foo_x_get(swigCPtr, this);
+  }
+
+  public int spam(int num, Foo foo) {
+    return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo);
+  }
+
+  public Foo() {
+    this(exampleJNI.new_Foo(), true);
+  }
+
+}
+</pre>
+</div>
+
+
+<p>
+This class merely holds a pointer to the underlying C++ object (<tt>swigCPtr</tt>).
+It also contains all the methods in the C++ class it is proxying plus getters and setters for public
+member variables. These functions call the native methods in the intermediary JNI class. 
+The advantage of having this extra layer is the type safety that the proxy class functions offer. 
+It adds static type checking which leads to fewer surprises at runtime. 
+For example, you can see that if you attempt to use the <tt> spam() </tt> 
+function it will only compile when the parameters passed are an <tt>int</tt> and a <tt>Foo</tt>. 
+From a user's point of view, it makes the class work as if it were a Java class:
+</p>
+
+<div class="code">
+<pre>
+Foo f = new Foo();
+f.setX(3);
+int y = f.spam(5, new Foo());
+</pre>
+</div>
+
+<H4><a name="memory_management"></a>20.4.3.1 Memory management</H4>
+
+
+<p>
+Each proxy class has an ownership flag <tt>swigCMemOwn</tt>.   The value of this
+flag determines who is responsible for deleting the underlying C++ object.   If set to <tt>true</tt>,
+the proxy class's finalizer will destroy the C++ object when the proxy class is 
+garbage collected.   If set to false, then the destruction of the proxy class has no effect on the C++ object.
+</p>
+
+<p>
+When an object is created by a constructor or returned by value, Java automatically takes
+ownership of the result. 
+On the other hand, when pointers or references are returned to Java, there is often no way to know where
+they came from.  Therefore, the ownership is set to false.  For example:
+</p>
+
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+    Foo bar1();
+    Foo &amp;bar2();
+    Foo *bar2();
+};
+</pre>
+</div>
+
+<p>
+In Java:
+</p>
+
+<div class="code">
+<pre>
+Foo f = new Foo();   //  f.swigCMemOwn = true
+Foo f1 = f.bar1();   // f1.swigCMemOwn = true
+Foo f2 = f.bar2();   // f2.swigCMemOwn = false
+Foo f3 = f.bar3();   // f3.swigCMemOwn = false
+</pre>
+</div>
+
+<p>
+This behavior for pointers and references is especially important for classes that act as containers.  
+For example, if a method returns a pointer to an object
+that is contained inside another object, you definitely don't want
+Java to assume ownership and destroy it!
+</p>
+
+<p>
+For the most part, memory management issues remain hidden.  However,
+there are situations where you might have to manually
+change the ownership of an object.  For instance, consider code like this:
+</p>
+
+<div class="code">
+<pre>
+class Obj {};
+class Node {
+   Obj *value;
+public:
+   void set_value(Obj *v) { value = v; }
+};
+</pre>
+</div>
+
+<p>
+Now, consider the following Java code:
+</p>
+
+<div class="code">
+<pre>
+Node n = new Node();    // Create a node
+{
+  Obj o = new Obj();    // Create an object
+  n.set_value(o);       // Set value
+}                       // o goes out of scope
+</pre>
+</div>
+
+<p>
+In this case, the Node <tt>n</tt> is holding a reference to
+<tt>o</tt> internally.  However, SWIG has no way to know that this
+has occurred.  The Java proxy class still thinks that it has ownership of 
+<tt>o</tt>.  As <tt>o</tt> has gone out of scope, it could be garbage collected in which case the C++ destructor
+will be invoked and <tt>n</tt> will then be holding a stale-pointer to <tt>o</tt>.  If
+you're lucky, you will only get a segmentation fault.
+</p>
+
+<p>
+To work around this, the ownership flag of <tt>o</tt> needs changing to <tt>false</tt>. 
+The ownership flag is a private member variable of the proxy class so this is not possible without some customization of the proxy class. 
+This can be achieved by using a typemap to customise the proxy class with pure Java code as detailed later in the section on 
+<a href="#java_typemaps">Java typemaps</a>.
+</p>
+
+<p>
+Sometimes a function will create memory and return a pointer to a newly allocated object. 
+SWIG has no way of knowing this so by default the proxy class does not manage the returned object.
+However, you can tell the proxy class to manage the memory if you specify the <tt>%newobject</tt> directive. Consider:
+</p>
+
+<div class="code">
+<pre>
+class Obj {...};
+class Factory {
+public:
+    static Obj *createObj() { return new Obj(); }
+};
+</pre>
+</div>
+
+<p>
+If we call the factory function, then we have to manually delete the memory:
+</p>
+
+<div class="code">
+<pre>
+Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
+...
+obj.delete();
+</pre>
+</div>
+
+<p>
+Now add in the %newobject directive:
+</p>
+
+<div class="code">
+<pre>
+%newobject Factory::createObj();
+
+class Obj {...};
+class Factory {
+public:
+    static Obj *createObj() { return new Obj(); }
+};
+</pre>
+</div>
+
+<p>
+A call to <tt>delete()</tt> is no longer necessary as the garbage collector will make the C++ destructor call because <tt>swigCMemOwn</tt> is now true.
+</p>
+
+<div class="code">
+<pre>
+Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
+...
+</pre>
+</div>
+
+<p>
+Some memory management issues are quite tricky to fix and may only be noticeable after using for a long time.
+One such issue is premature garbage collection of an object created from Java and resultant usage from C++ code.
+The section on typemap examples cover two such scenarios, 
+<a href="#java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
+and 
+<a href="#java_memory_management_member_variables">Memory management when returning references to member variables</a>
+</p>
+
+
+<H4><a name="inheritance_mirroring"></a>20.4.3.2 Inheritance</H4>
+
+
+<p>
+Java proxy classes will mirror C++ inheritance chains. For example, given the base class <tt>Base</tt> and its derived class <tt>Derived</tt>:
+</p>
+
+<div class="code"><pre>
+class Base {
+public:
+  virtual double foo();
+};
+
+class Derived : public Base {
+public:
+  virtual double foo();
+};
+</pre></div>
+
+<p>
+The base class is generated much like any other proxy class seen so far:
+</p>
+
+<div class="code"><pre>
+public class Base {
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  protected Base(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr(Base obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+
+  protected void finalize() {
+    delete();
+  }
+
+  public synchronized void delete() {
+    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
+      swigCMemOwn = false;
+      exampleJNI.delete_Base(swigCPtr);
+    }
+    swigCPtr = 0;
+  }
+
+  public double foo() {
+    return exampleJNI.Base_foo(swigCPtr, this);
+  }
+
+  public Base() {
+    this(exampleJNI.new_Base(), true);
+  }
+
+}
+</pre></div>
+
+<p>
+The <tt>Derived</tt> class extends <tt>Base</tt> mirroring the C++ class inheritance hierarchy. 
+</p>
+
+<div class="code"><pre>
+public class Derived extends Base {
+  private long swigCPtr;
+
+  protected Derived(long cPtr, boolean cMemoryOwn) {
+    super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr(Derived obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+
+  protected void finalize() {
+    delete();
+  }
+
+  public synchronized void delete() {
+    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
+      swigCMemOwn = false;
+      exampleJNI.delete_Derived(swigCPtr);
+    }
+    swigCPtr = 0;
+    super.delete();
+  }
+
+  public double foo() {
+    return exampleJNI.Derived_foo(swigCPtr, this);
+  }
+
+  public Derived() {
+    this(exampleJNI.new_Derived(), true);
+  }
+
+}
+</pre></div>
+
+<p>
+Note the memory ownership is controlled by the base class. 
+However each class in the inheritance hierarchy has its own pointer value which is obtained during construction. 
+The <tt>SWIGDerivedUpcast()</tt> call converts the pointer from a <tt>Derived *</tt> to a <tt>Base *</tt>.
+This is a necessity as C++ compilers are free to implement pointers in the inheritance hierarchy with different values. 
+</p>
+
+<p>
+It is of course possible to extend <tt>Base</tt> using your own Java classes. 
+If <tt>Derived</tt> is provided by the C++ code, you could for example add in a pure Java class <tt>Extended</tt> derived from <tt>Base</tt>. 
+There is a caveat and that is any C++ code will not know about your pure Java class <tt>Extended</tt> so this type of derivation is restricted.
+However, true cross language polymorphism can be achieved using the <a href="#java_directors">directors</a> feature.
+</p>
+
+
+<H4><a name="proxy_classes_gc"></a>20.4.3.3 Proxy classes and garbage collection</H4>
+
+
+<p>
+By default each proxy class has a <tt>delete()</tt> and a <tt>finalize()</tt> method. 
+The <tt>finalize()</tt> method calls <tt>delete()</tt> which frees any malloc'd memory for wrapped C structs or calls the C++ class destructors. 
+The idea is for <tt>delete()</tt> to be called when you have finished with the C/C++ object. 
+Ideally you need not call <tt>delete()</tt>, but rather leave it to the garbage collector to call it from the finalizer. 
+When a program exits, the garbage collector does not guarantee to call all finalizers. 
+An insight into the reasoning behind this can be obtained from <a href="http://www.hpl.hp.com/techreports/2002/HPL-2002-335.html">Hans Boehm's Destructors, Finalizers, and Synchronization</a> paper.
+Depending on what the finalizers do and which operating system you use, this may or may not be a problem. 
+</p>
+
+<p>
+If the <tt>delete()</tt> call into JNI code is just for memory handling, there is not a problem when run on most operating systems, for example Windows and Unix. 
+Say your JNI code creates memory on the heap which your finalizers should clean up, the finalizers may or may not be called before the program exits. 
+In Windows and Unix all memory that a process uses is returned to the system on exit, so this isn't a problem. 
+This is not the case in some operating systems like vxWorks. 
+If however, your finalizer calls into JNI code invoking the C++ destructor which in turn releases a TCP/IP socket for example, there is no guarantee that it will be released. 
+Note that with long running programs the garbage collector will eventually run, thereby calling any unreferenced object's finalizers.
+</p>
+
+<p>
+Some not so ideal solutions are:
+</p>
+
+<ol>
+<li><p>
+Call the <tt>System.runFinalizersOnExit(true)</tt> or <tt>Runtime.getRuntime().runFinalizersOnExit(true)</tt> to ensure the finalizers are called before the program exits. The catch is that this is a deprecated function call as the documentation says: </p>
+<div class="code"><i>
+This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.
+</i></div> 
+<p>In many cases you will be lucky and find that it works, but it is not to be advocated. 
+Have a look at <a href="http://java.sun.com">Sun's Java web site</a> and search for <tt>runFinalizersOnExit</tt>.
+</p></li>
+
+<li><p>
+From jdk1.3 onwards a new function, <tt>addShutdownHook()</tt>, was introduced which is guaranteed to be called when your program exits. 
+You can encourage the garbage collector to call the finalizers, for example, add this static block to the class that has the <tt>main()</tt> function: </p>
+<div class="code"><pre>
+  static {
+    Runtime.getRuntime().addShutdownHook( 
+      new Thread() {
+        public void run() { System.gc(); System.runFinalization(); }
+      }
+    );
+  }
+</pre></div>
+<p>Although this usually works, the documentation doesn't guarantee that <tt>runFinalization()</tt> will actually call the finalizers. 
+As the the shutdown hook is guaranteed you could also make a JNI call to clean up any resources that are being tracked by the C/C++ code.</p>
+</li>
+
+<li>
+<p>Call the <tt>delete()</tt> function manually which will immediately invoke the C++ destructor. 
+As a suggestion it may be a good idea to set the object to null so that should the object be inadvertently used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null C pointer. 
+For example given a SWIG generated class A:</p>
+<div class="code"><pre>
+A myA = new A();
+// use myA ...
+myA.delete();
+// any use of myA here would crash the JVM 
+myA=null;
+// any use of myA here would cause a Java null pointer exception to be thrown
+</pre></div>
+
+<p>
+The SWIG generated code ensures that the memory is not deleted twice, in the event the finalizers get called in addition to the manual <tt>delete()</tt> call.
+</p>
+</li>
+
+<li>
+<p>
+Write your own object manager in Java. 
+You could derive all SWIG classes from a single base class which could track which objects have had their finalizers run, then call the rest of them on program termination.
+The section on <a href="#java_typemaps">Java typemaps</a> details how to specify a pure Java base class.
+</p>
+</li>
+</ol>
+
+<p>
+See the <a href="http://www.devx.com/Java/Article/30192">How to Handle Java Finalization's Memory-Retention Issues</a> article for alternative approaches to managing memory by avoiding finalizers altogether.
+</p>
+
+<H4><a name="java_pgcpp"></a>20.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling</H4>
+
+
+<p>
+As covered earlier, the C/C++ struct/class pointer is stored in the proxy class as a Java long and when needed is passed
+into the native method where it is cast into the appropriate type.
+This approach provides very fast marshalling but could be susceptible to premature garbage collection.
+Consider the following C++ code:
+</p>
+
+<div class="code"><pre>
+class Wibble {
+};
+void wobble(Wibble &amp;w);
+</pre></div>
+
+<p>
+The module class contains the Java wrapper for the global <tt>wobble</tt> method:
+</p>
+
+<div class="code"><pre>
+public class example {
+  ...
+  public static void wobble(Wibble w) {
+    exampleJNI.wobble(Wibble.getCPtr(w), w);
+  }
+}
+</pre></div>
+
+<p>
+where <tt>example</tt> is the name of the module. 
+All native methods go through the intermediary class which has the native method declared as such:
+</p>
+
+<div class="code"><pre>
+public class exampleJNI {
+  ...
+  public final static native void wobble(long jarg1, Wibble jarg1_);
+}
+</pre></div>
+
+<p>
+The second parameter, <tt>jarg1_</tt>, is the premature garbage collection prevention parameter and is added to the native method parameter list whenever a C/C++ struct or class is marshalled as a Java long.
+In order to understand why, consider the alternative where the intermediary class method is declared without the additional parameter:
+</p>
+
+<div class="code"><pre>
+public class exampleJNI {
+  ...
+  public final static native void wobble(long jarg1);
+}
+</pre></div>
+
+<p>
+and the following simple call to <tt>wobble</tt>:
+</p>
+
+<div class="code"><pre>
+{
+  Wibble w = new Wibble();
+  example.wobble(w);
+}
+</pre></div>
+
+<p>
+The hotspot compiler effectively sees something like:
+</p>
+
+<div class="code"><pre>
+{
+  Wibble w = new Wibble();
+  long w_ptr = Wibble.getCPtr(w);
+  // w is no longer reachable
+  exampleJNI.wobble(w_ptr);
+}
+</pre></div>
+
+<p>
+The <tt>Wibble</tt> object is no longer reachable after the point shown as in this bit of code, the <tt>Wibble</tt> object is not referenced again after this point.
+This means that it is a candidate for garbage collection.
+Should <tt>wobble</tt> be a long running method, it is quite likely that the finalizer for the <tt>Wibble</tt> instance will be called.
+This in turn will call its underlying C++ destructor which 
+is obviously disastrous while the method <tt>wobble</tt> is running using this object.
+Even if <tt>wobble</tt> is not a long running method, it is possible for the <tt>Wibble</tt> instance to be finalized.
+By passing the <tt>Wibble</tt> instance into the native method, it will not be finalized as the JVM guarantees not to
+finalize any objects until the native method returns.
+Effectively, the code then becomes
+</p>
+
+<div class="code"><pre>
+{
+  Wibble w = new Wibble();
+  long w_ptr = Wibble.getCPtr(w);
+  exampleJNI.wobble(w_ptr, w);
+  // w is no longer reachable
+}
+</pre></div>
+
+<p>
+and therefore there is no possibility of premature garbage collection. In practice, this premature garbage collection was only ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's client JVM from jdk-1.6 onwards.
+</p>
+
+<p>
+The premature garbage collection prevention parameter for proxy classes is generated by default whenever proxy classes are passed by value, reference or with a pointer.
+The additional parameters do impose a slight performance overhead and the parameter generation can be suppressed globally with the <tt>-nopgcpp</tt> commandline option.
+More selective suppression is possible with the 'nopgcpp' attribute in the "jtype" <a href="#java_typemaps">Java typemap</a>.
+The attribute is a flag and so should be set to "1" to enable the suppression, or it can be omitted or set to "0" to disable.
+For example:
+</p>
+
+<div class="code"><pre>
+%typemap(jtype, nopgcpp="1") Wibble &amp; "long"
+</pre></div>
+
+<p>
+<b>Compatibility note:</b> The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.
+</p>
+
+<H4><a name="java_multithread_libraries"></a>20.4.3.5 Single threaded applications and thread safety</H4>
+
+
+<p>
+Single threaded Java applications using JNI need to consider thread safety.
+The same applies for the C# module where the .NET wrappers use PInvoke.
+Consider the C++ class:
+</p>
+
+<div class="code"><pre>
+class Test {
+  string str;
+public:
+  Test() : str("initial") {}
+};
+</pre></div>
+
+<p>
+and the Java proxy class generated by SWIG:
+</p>
+
+<div class="code"><pre>
+public class Test {
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  protected Test(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr(Test obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+
+  protected void finalize() {
+    delete();
+  }
+
+  // Call C++ destructor
+  public synchronized void delete() {
+    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
+      swigCMemOwn = false;
+      exampleJNI.delete_Test(swigCPtr);
+    }
+    swigCPtr = 0;
+  }
+
+  // Call C++ constructor
+  public Test() {
+    this(exampleJNI.new_Test(), true);
+  }
+
+}
+</pre></div>
+
+
+<p>
+It has two methods that call JNI methods, namely, <tt>exampleJNI.new_Test()</tt> for the C++ constructor and <tt>exampleJNI.delete_Test()</tt> for the C++ destructor. 
+If the garbage collector collects an instance of this class, ie <tt>delete()</tt> is not explicitly called, then the C++ destructor will be run in a different thread to the main thread. 
+This is because when an object is marked for garbage collection, any objects with finalizers are added to a finalization queue 
+and the objects in the finalization queue have their <tt>finalize()</tt> methods run in a separate finalization thread. 
+Therefore, if the C memory allocator is not thread safe, then the heap will get corrupted sooner or later, when a concurrent C++ delete and new are executed. 
+It is thus essential, even in single threaded usage, to link to the C multi-thread runtime libraries,
+for example, use the /MD option for Visual C++ on Windows.
+Alternatively, lock all access to C++ functions that have heap allocation/deallocation. 
+</p>
+
+<p>
+Note that some of the STL in Visual C++ 6 is not thread safe, so although code might be linked to the multithread runtime libraries, undefined behaviour might still occur in a single threaded Java program.
+Similarly some older versions of Sun Studio have bugs in the multi-threaded implementation of the std::string class and so will lead to undefined behaviour in these supposedly single threaded Java applications.
+</p>
+
+<p>
+The following innocuous Java usage of Test is an example that will crash very quickly on a multiprocessor machine if the JNI compiled code is linked against the single thread C runtime libraries.
+</p>
+ 
+<div class="code"><pre>
+for (int i=0; i&lt;100000; i++) {
+  System.out.println("Iteration " + i);
+  for (int k=0; k&lt;10; k++) {
+    Test test = new Test();
+  }
+  System.gc();
+}
+</pre></div>
+ 
+
+<H3><a name="type_wrapper_classes"></a>20.4.4 Type wrapper classes</H3>
+
+
+<p>
+The generated type wrapper class, for say an <tt>int *</tt>, looks like this:
+</p>
+
+<div class="code"><pre>
+public class SWIGTYPE_p_int {
+  private long swigCPtr;
+
+  protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
+    swigCPtr = cPtr;
+  }
+
+  protected SWIGTYPE_p_int() {
+    swigCPtr = 0;
+  }
+
+  protected static long getCPtr(SWIGTYPE_p_int obj) {
+    return obj.swigCPtr;
+  }
+}
+</pre></div>
+
+<p>
+The methods do not have public access, so by default it is impossible to do anything with objects of this class other than 
+pass them around. The methods in the class are part of the inner workings of SWIG. 
+If you need to mess around with pointers you will have to use some typemaps specific to the Java module to achieve this.
+The section on <a href="#java_typemaps">Java typemaps</a> details how to modify the generated code.
+</p>
+
+<p>
+Note that if you use a pointer or reference to a proxy class in a function then no type wrapper class is generated because the proxy class can be used
+as the function parameter. If however,  you need anything more complicated like a pointer to a pointer to a proxy class then a typewrapper class
+is generated for your use. 
+</p>
+
+<p>
+Note that SWIG generates a type wrapper class and not a proxy class when it has not parsed the definition of a type that gets used. 
+For example, say SWIG has not parsed the definition of <tt>class Snazzy</tt> because it is in a header file that you may have forgotten to use the <tt>%include</tt> directive on.
+Should SWIG parse <tt>Snazzy *</tt> being used in a function parameter, it will then generates a type wrapper class around a <tt>Snazzy</tt> pointer.
+Also recall from earlier that SWIG will use a pointer when a class is passed by value or by reference:
+</p>
+
+<div class="code">
+<pre>
+void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
+</pre>
+</div>
+
+<p>
+Should SWIG not know anything about <tt>Snazzy</tt> then a <tt>SWIGTYPE_p_Snazzy</tt> must be used for all 3 parameters in the <tt>spam</tt> function.
+The Java function generated is:
+</p>
+
+<div class="code">
+<pre>
+public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
+ ...
+}
+</pre>
+</div>
+
+<p>
+Note that typedefs are tracked by SWIG and the typedef name is used to construct the type wrapper class name. For example, consider the case where <tt>Snazzy</tt> is a typedef to an <tt>int</tt> which SWIG does parse:
+</p>
+
+
+<div class="code">
+<pre>
+typedef int Snazzy;
+void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
+</pre>
+</div>
+
+<p>
+Because the typedefs have been tracked the Java function generated is:
+</p>
+
+<div class="code">
+<pre>
+public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
+</pre>
+</div>
+
+
+<H3><a name="enum_classes"></a>20.4.5 Enum classes</H3>
+
+
+<p>
+SWIG can generate three types of enum classes.
+The <a href="#enumerations">Enumerations</a> section discussed these but omitted all the details.
+The following sub-sections detail the various types of enum classes that can be generated.
+</p>
+
+<H4><a name="typesafe_enums_classes"></a>20.4.5.1 Typesafe enum classes</H4>
+
+
+<p>
+The following example demonstrates the typesafe enum classes which SWIG generates:
+</p>
+
+<div class="code">
+<pre>
+%include "enumtypesafe.swg"
+%javaconst(1);
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+The following is the code that SWIG generates:
+</p>
+
+<div class="code">
+<pre>
+public final class Beverage {
+  public final static Beverage ALE = new Beverage("ALE");
+  public final static Beverage LAGER = new Beverage("LAGER", 10);
+  public final static Beverage STOUT = new Beverage("STOUT");
+  public final static Beverage PILSNER = new Beverage("PILSNER");
+  public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
+
+  public final int swigValue() {
+    return swigValue;
+  }
+
+  public String toString() {
+    return swigName;
+  }
+
+  public static Beverage swigToEnum(int swigValue) {
+    if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
+        swigValues[swigValue].swigValue == swigValue)
+      return swigValues[swigValue];
+    for (int i = 0; i &lt; swigValues.length; i++)
+      if (swigValues[i].swigValue == swigValue)
+        return swigValues[i];
+    throw new IllegalArgumentException("No enum " + Beverage.class + " with value " +
+                                                                         swigValue);
+  }
+
+  private Beverage(String swigName) {
+    this.swigName = swigName;
+    this.swigValue = swigNext++;
+  }
+
+  private Beverage(String swigName, int swigValue) {
+    this.swigName = swigName;
+    this.swigValue = swigValue;
+    swigNext = swigValue+1;
+  }
+
+  private Beverage(String swigName, Beverage swigEnum) {
+    this.swigName = swigName;
+    this.swigValue = swigEnum.swigValue;
+    swigNext = this.swigValue+1;
+  }
+
+  private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ };
+  private static int swigNext = 0;
+  private final int swigValue;
+  private final String swigName;
+}
+</pre>
+</div>
+
+<p>
+As can be seen, there are a fair number of support methods for the typesafe enum pattern.
+The typesafe enum pattern involves creating a fixed number of static instances of the enum class.
+The constructors are private to enforce this.
+Three constructors are available - two for C/C++ enums with an initializer and one for those without an initializer.
+Note that the two enums with initializers, <tt>LAGER</tt> and <tt>PILZ</tt>, each call one the two different initializer constructors.
+In order to use one of these typesafe enums, the <tt>swigToEnum</tt> static method must be called to return a reference to one of the static instances.
+The JNI layer returns the enum value from the C/C++ world as an integer and this method is used to find the appropriate Java enum static instance.
+The <tt>swigValue</tt> method is used for marshalling in the other direction.
+The <tt>toString</tt> method is overridden so that the enum name is available.
+</p>
+
+<H4><a name="proper_enums_classes"></a>20.4.5.2 Proper Java enum classes</H4>
+
+
+<p>
+The following example demonstrates the Java enums approach:
+</p>
+
+<div class="code">
+<pre>
+%include "enums.swg"
+%javaconst(1);
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+SWIG will generate the following Java enum:
+</p>
+
+<div class="code">
+<pre>
+public enum Beverage {
+  ALE,
+  LAGER(10),
+  STOUT,
+  PILSNER,
+  PILZ(PILSNER);
+
+  public final int swigValue() {
+    return swigValue;
+  }
+
+  public static Beverage swigToEnum(int swigValue) {
+    Beverage[] swigValues = Beverage.class.getEnumConstants();
+    if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
+        swigValues[swigValue].swigValue == swigValue)
+      return swigValues[swigValue];
+    for (Beverage swigEnum : swigValues)
+      if (swigEnum.swigValue == swigValue)
+        return swigEnum;
+    throw new IllegalArgumentException("No enum " + Beverage.class +
+                                       " with value " + swigValue);
+  }
+
+  private Beverage() {
+    this.swigValue = SwigNext.next++;
+  }
+
+  private Beverage(int swigValue) {
+    this.swigValue = swigValue;
+    SwigNext.next = swigValue+1;
+  }
+
+  private Beverage(Beverage swigEnum) {
+    this.swigValue = swigEnum.swigValue;
+    SwigNext.next = this.swigValue+1;
+  }
+
+  private final int swigValue;
+
+  private static class SwigNext {
+    private static int next = 0;
+  }
+}
+</pre>
+</div>
+
+<p>
+The enum items appear first.
+Like the typesafe enum pattern, the constructors are private.
+The constructors are required to handle C/C++ enums with initializers.
+The <tt>next</tt> variable is in the <tt>SwigNext</tt> inner class rather than in the enum class as static primitive variables cannot be modified from within enum constructors.
+Marshalling between Java enums and the C/C++ enum integer value is handled via the <tt>swigToEnum</tt> and <tt>swigValue</tt> methods.
+All the constructors and methods in the Java enum are required just to handle C/C++ enums with initializers.
+These needn't be generated if the enum being wrapped does not have any initializers and the 
+<a href="#simpler_enum_classes">Simpler Java enums for enums without initializers</a> section describes how typemaps can be used to achieve this.
+</p>
+
+<H4><a name="typeunsafe_enums_classes"></a>20.4.5.3 Type unsafe enum classes</H4>
+
+
+<p>
+The following example demonstrates type unsafe enums:
+</p>
+
+<div class="code">
+<pre>
+%include "enumtypeunsafe.swg"
+%javaconst(1);
+enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
+</pre>
+</div>
+
+<p>
+SWIG will generate the following simple class:
+</p>
+
+<div class="code">
+<pre>
+public final class Beverage {
+  public final static int ALE = 0;
+  public final static int LAGER = 10;
+  public final static int STOUT = LAGER + 1;
+  public final static int PILSNER = STOUT + 1;
+  public final static int PILZ = PILSNER;
+}
+</pre>
+</div>
+
+<H2><a name="java_directors"></a>20.5 Cross language polymorphism using directors</H2>
+
+
+<p>
+Proxy classes provide a natural, object-oriented way to wrap C++ classes.
+as described earlier, each proxy instance has an associated C++ instance, and method calls from Java to the proxy are passed to the C++ instance transparently via C wrapper functions.
+</p>
+
+<p>
+This arrangement is asymmetric in the sense that no corresponding mechanism exists to pass method calls down the inheritance chain from C++ to Java. 
+In particular, if a C++ class has been extended in Java (by deriving from the proxy class), these classes will not be visible from C++ code. 
+Virtual method calls from C++ are thus not able to access the lowest implementation in the inheritance chain.
+</p>
+
+<p>
+SWIG can address this problem and make the relationship between C++ classes and proxy classes more symmetric. 
+To achieve this goal, new classes called directors are introduced at the bottom of the C++ inheritance chain. 
+The job of the directors is to route method calls correctly, either to C++ implementations higher in the inheritance chain or to Java implementations lower in the inheritance chain. 
+The upshot is that C++ classes can be extended in Java and from C++ these extensions look exactly like native C++ classes. 
+Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.
+</p>
+
+<H3><a name="java_enabling_directors"></a>20.5.1 Enabling directors</H3>
+
+
+<p>
+The director feature is disabled by default.
+To use directors you must make two changes to the interface file.
+First, add the "directors" option to the %module directive, like this:
+</p>
+
+<div class="code">
+<pre>
+%module(directors="1") modulename
+</pre>
+</div>
+
+<p>
+Without this option no director code will be generated.
+Second, you must use the %feature("director") directive to tell SWIG which classes and methods should get directors.
+The %feature directive can be applied globally, to specific classes, and to specific methods, like this:
+</p>
+
+<div class="code">
+<pre>
+// generate directors for all classes that have virtual methods
+%feature("director");         
+
+// generate directors for all virtual methods in class Foo
+%feature("director") Foo;      
+
+// generate a director for just Foo::bar()
+%feature("director") Foo::bar; 
+</pre>
+</div>
+
+<p>
+You can use the %feature("nodirector") directive to turn off directors for specific classes or methods.
+So for example,
+</p>
+
+<div class="code">
+<pre>
+%feature("director") Foo;
+%feature("nodirector") Foo::bar;
+</pre>
+</div>
+
+<p>
+will generate directors for all virtual methods of class Foo except bar().  
+</p>
+
+<p>
+Directors can also be generated implicitly through inheritance. 
+In the following, class Bar will get a director class that handles the methods one() and two() (but not three()):
+</p>
+
+<div class="code">
+<pre>
+%feature("director") Foo;
+class Foo {
+public:
+    virtual void one();
+    virtual void two();
+};
+
+class Bar: public Foo {
+public:
+    virtual void three();
+};
+</pre>
+</div>
+
+<H3><a name="java_directors_classes"></a>20.5.2 Director classes</H3>
+
+
+<p>
+For each class that has directors enabled, SWIG generates a new class that derives from both the class in question and a special <tt>Swig::Director</tt> class. 
+These new classes, referred to as director classes, can be loosely thought of as the C++ equivalent of the Java proxy classes.
+The director classes store a pointer to their underlying Java proxy classes.
+</p>
+
+<p>
+For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the original C++ class as the director's base class.
+By default, a director class extends all virtual methods in the inheritance chain of its base class (see the preceding section for how to modify this behavior).
+Thus all virtual method calls, whether they originate in C++ or in Java via proxy classes, eventually end up in at the implementation in the director class.
+The job of the director methods is to route these method calls to the appropriate place in the inheritance chain.
+By "appropriate place" we mean the method that would have been called if the C++ base class and its Java derived classes were seamlessly integrated.
+That seamless integration is exactly what the director classes provide, transparently skipping over all the messy JNI glue code that binds the two languages together.
+</p>
+
+<p>
+In reality, the "appropriate place" is one of only two possibilities: C++ or Java.
+Once this decision is made, the rest is fairly easy.
+If the correct implementation is in C++, then the lowest implementation of the method in the C++ inheritance chain is called explicitly.
+If the correct implementation is in Java, the Java API is used to call the method of the underlying Java object 
+(after which the usual virtual method resolution in Java automatically finds the right implementation).
+</p>
+
+
+<H3><a name="java_directors_overhead"></a>20.5.3 Overhead and code bloat</H3>
+
+
+<p>
+Enabling directors for a class will generate a new director method for every virtual method in the class' inheritance chain.
+This alone can generate a lot of code bloat for large hierarchies.
+Method arguments that require complex conversions to and from Java types can result in large director methods.
+For this reason it is recommended that directors are selectively enabled only for specific classes that are likely to be extended in Java and used in C++.
+</p>
+
+<p>
+Although directors make it natural to mix native C++ objects with Java objects (as director objects),
+one should be aware of the obvious fact that method calls to Java objects from C++ will be much slower than calls to C++ objects.
+Additionally, compared to classes that do not use directors, the call routing in the director methods adds a small overhead.
+This situation can be optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in Java.
+</p>
+
+
+<H3><a name="java_directors_example"></a>20.5.4 Simple directors example</H3>
+
+
+<p>
+Consider the following SWIG interface file:
+</p>
+
+<div class="code">
+<pre>
+%module(directors="1") example;
+
+%feature("director") DirectorBase;
+
+class DirectorBase {
+public:
+  virtual ~DirectorBase() {}
+  virtual void upcall_method() {}
+};
+
+void callup(DirectorBase *director) {
+  director-&gt;upcall_method();
+}
+</pre>
+</div>
+
+<p>
+The following <code>DirectorDerived</code> Java class is derived from the Java proxy class <code>DirectorBase</code> and overrides <code>upcall_method()</code>.
+When C++ code invokes <code>upcall_method()</code>, the SWIG-generated C++ code redirects the call via JNI to the Java <code>DirectorDerived</code> subclass.
+Naturally, the SWIG generated C++ code and the generated Java intermediate class marshal and convert arguments between C++ and Java when needed.
+</p>
+
+<div class="code">
+<pre>
+public class DirectorDerived extends DirectorBase {
+  public DirectorDerived() {
+  }
+
+  public void upcall_method() {
+    System.out.println("DirectorDerived::upcall_method() invoked.");
+  }
+}
+</pre>
+</div>
+
+<p>
+Running the following Java code
+</p>
+
+<div class="code">
+<pre>
+DirectorDerived director = new DirectorDerived();
+example.callup(director);
+</pre>
+</div>
+
+<p>
+will result in the following being output:
+</p>
+
+<div class="code">
+<pre>
+DirectorDerived::upcall_method() invoked.
+</pre>
+</div>
+
+<H3><a name="java_directors_threading"></a>20.5.5 Director threading issues</H3>
+
+
+<p>
+Depending on your operating system and version of Java and how you are using threads, you might find the JVM hangs on exit.
+There are a couple of solutions to try out. The preferred solution requires jdk-1.4 and later and uses <tt>AttachCurrentThreadAsDaemon</tt> instead of <tt>AttachCurrentThread</tt> whenever a call into the JVM is required. This can be enabled by defining the SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro when compiling the C++ wrapper code. For older JVMs define SWIG_JAVA_NO_DETACH_CURRENT_THREAD instead, to avoid the <tt>DetachCurrentThread</tt> call but this will result in a memory leak instead. For further details inspect the source code in the java/director.swg library file.
+</p>
+
+<p>
+Macros can be defined on the commandline when compiling your C++ code, or alternatively added to the C++ wrapper file as shown below:
+</p>
+
+<div class="code">
+<pre>
+%insert("runtime") %{
+#define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
+%}
+</pre>
+</div>
+
+<H2><a name="java_allprotected"></a>20.6 Accessing protected members</H2>
+
+
+<p>
+When using directors, the protected virtual methods are also wrapped. 
+These methods are wrapped with a protected Java proxy method, so the only way that Java code can access these is from within a Java class derived from the director class.
+</p>
+
+<p>
+Members which are protected and non-virtual can also be accessed when using the 'allprotected' mode.
+The allprotected mode requires directors and is turned on by setting the <tt>allprotected</tt> option in addition to the <tt>directors</tt> option in the %module directive, like this:
+</p>
+
+<div class="code">
+<pre>
+%module(directors="1", allprotected="1") modulename
+</pre>
+</div>
+
+<p>
+Protected member variables and methods (both static and non-static) will then be wrapped with protected access in the Java proxy class.
+</p>
+
+<p>
+<b>Note:</b> Neither the directors option nor the allprotected mode support types defined with protected scope.
+This includes any enums or typedefs declared in the protected section of the C++ class.
+</p>
+
+<p>
+The following simple example is a class with numerous protected members, including the constructor and destructor:
+</p>
+
+<div class="code">
+<pre>
+%module(directors="1", allprotected="1") example
+
+%feature("director") ProtectedBase;
+
+// Ignore use of unsupported types (those defined in the protected section)
+%ignore ProtectedBase::typedefs;
+
+%inline %{
+
+class ProtectedBase {
+protected:
+  ProtectedBase() {}
+  virtual ~ProtectedBase() {}
+  virtual void virtualMethod() const {}
+  void nonStaticMethod(double d) const {}
+  static void staticMethod(int i) {}
+  int instanceMemberVariable;
+  static int staticMemberVariable;
+
+  // unsupported: types defined with protected access and the methods/variables which use them
+  typedef int IntegerType;
+  IntegerType typedefs(IntegerType it) { return it; }
+};
+int ProtectedBase::staticMemberVariable = 10;
+
+%}
+
+</pre>
+</div>
+
+<p>
+Note that the <tt>IntegerType</tt> has protected scope and the members which use this type must be ignored as they cannot be wrapped.
+</p>
+
+<p>
+The proxy methods are protected, so the only way the protected members can be accessed is within a class that derives from the director class, such as the following:
+</p>
+
+<div class="code">
+<pre>
+class MyProtectedBase extends ProtectedBase
+{
+  public MyProtectedBase() {
+  }
+
+  public void accessProtected() {
+    virtualMethod();
+    nonStaticMethod(1.2);
+    staticMethod(99);
+
+    setInstanceMemberVariable(5);
+    int i = getInstanceMemberVariable();
+
+    setStaticMemberVariable(10);
+    i = getStaticMemberVariable();
+  }
+}
+</pre>
+</div>
+
+
+
+<H2><a name="common_customization"></a>20.7 Common customization features</H2>
+
+
+<p>
+An earlier section presented the absolute basics of C/C++ wrapping. If you do nothing
+but feed SWIG a header file, you will get an interface that mimics the behavior
+described.  However, sometimes this isn't enough to produce a nice module.  Certain
+types of functionality might be missing or the interface to certain functions might
+be awkward.  This section describes some common SWIG features that are used
+to improve the interface to existing C/C++ code.
+</p>
+
+<H3><a name="helper_functions"></a>20.7.1 C/C++ helper functions</H3>
+
+
+<p>
+Sometimes when you create a module, it is missing certain bits of functionality. For
+example, if you had a function like this
+</p>
+
+<div class="code">
+<pre>
+typedef struct Image {...};
+void set_transform(Image *im, double m[4][4]);
+</pre>
+</div>
+
+<p>
+it would be accessible from Java, but there may be no easy way to call it.
+The problem here is that a type wrapper class is generated for the two dimensional array parameter so
+there is no easy way to construct and manipulate a suitable
+<tt>double [4][4]</tt> value.   To fix this, you can write some extra C helper
+functions.  Just use the <tt>%inline</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
+double (*new_mat44())[4] {
+   return (double (*)[4]) malloc(16*sizeof(double));
+}
+void free_mat44(double (*x)[4]) {
+   free(x);
+}
+void mat44_set(double x[4][4], int i, int j, double v) {
+   x[i][j] = v;
+}
+double mat44_get(double x[4][4], int i, int j) {
+   return x[i][j];
+}
+%}
+</pre>
+</div>
+
+<p>
+From Java, you could then write code like this:
+</p>
+
+<div class="code">
+<pre>
+Image im = new Image();
+SWIGTYPE_p_a_4__double a = example.new_mat44();
+example.mat44_set(a,0,0,1.0);
+example.mat44_set(a,1,1,1.0);
+example.mat44_set(a,2,2,1.0);
+...
+example.set_transform(im,a);
+example.free_mat44(a);
+</pre>
+</div>
+
+<p>
+Admittedly, this is not the most elegant looking approach.  However, it works and it wasn't too
+hard to implement.  It is possible to improve on this using Java code, typemaps, and other
+customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.  
+</p>
+
+<H3><a name="class_extension"></a>20.7.2 Class extension with %extend</H3>
+
+
+<p>
+One of the more interesting features of SWIG is that it can extend
+structures and classes with new methods or constructors.
+Here is a simple example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include "someheader.h"
+%}
+
+struct Vector {
+   double x,y,z;
+};
+
+%extend Vector {
+   char *toString() {
+       static char tmp[1024];
+       sprintf(tmp,"Vector(%g,%g,%g)", $self-&gt;x,$self-&gt;y,$self-&gt;z);
+       return tmp;
+   }
+   Vector(double x, double y, double z) {
+       Vector *v = (Vector *) malloc(sizeof(Vector));
+       v-&gt;x = x;
+       v-&gt;y = y;
+       v-&gt;z = z;
+       return v;
+   }
+};
+</pre>
+</div>
+
+<p>
+Now, in Java
+</p>
+
+<div class="code">
+<pre>
+Vector v = new Vector(2,3,4);
+System.out.println(v);
+</pre>
+</div>
+
+<p>
+will display
+</p>
+
+<div class="code">
+<pre>
+Vector(2,3,4)
+</pre>
+</div>
+
+<p>
+<tt>%extend</tt> works with both C and C++ code.  It does not modify the underlying object
+in any way---the extensions only show up in the Java interface.
+</p>
+
+<H3><a name="exception_handling"></a>20.7.3 Exception handling with %exception and %javaexception</H3>
+
+
+<p>
+If a C or C++ function throws an error, you may want to convert that error into a Java
+exception. To do this, you can use the <tt>%exception</tt> directive.  The <tt>%exception</tt> directive
+simply lets you rewrite part of the generated wrapper code to include an error check.
+It is detailed in full in the <a href="Customization.html#exception">Exception handling with %exception</a> section.
+</p>
+
+<p>
+In C, a function often indicates an error by returning a status code (a negative number
+or a NULL pointer perhaps).  Here is a simple example of how you might handle that:
+</p>
+
+<div class="code">
+<pre>
+%exception malloc {
+  $action
+  if (!result) {
+    jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/OutOfMemoryError");
+    (*jenv)-&gt;ThrowNew(jenv, clazz, "Not enough memory");
+    return $null;
+  }
+}
+void *malloc(size_t nbytes);
+</pre>
+</div>
+
+<p>
+In Java,
+</p>
+
+<div class="code">
+<pre>
+SWIGTYPE_p_void a = example.malloc(2000000000);
+</pre>
+</div>
+
+<p>
+will produce a familiar looking Java exception:
+</p>
+
+<div class="code">
+<pre>
+Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory
+        at exampleJNI.malloc(Native Method)
+        at example.malloc(example.java:16)
+        at main.main(main.java:112)
+</pre>
+</div>
+
+<p>
+If a library provides some kind of general error handling framework, you can also use
+that.  For example:
+</p>
+
+<div class="code">
+<pre>
+%exception malloc {
+  $action
+  if (err_occurred()) {
+    jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/OutOfMemoryError");
+    (*jenv)-&gt;ThrowNew(jenv, clazz, "Not enough memory");
+    return $null;
+  }
+}
+void *malloc(size_t nbytes);
+</pre>
+</div>
+
+<p>
+If no declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
+The <tt> $action </tt> is a SWIG special variable and is replaced by the C/C++ function call being wrapped.
+The <tt> return $null; </tt> handles all native method return types, namely those that have a void return and those that do not. 
+This is useful for typemaps that will be used in native method returning all return types. 
+See the section on
+<a href="#special_variables">Java special variables</a> for further explanation.
+</p>
+
+<p>
+C++ exceptions are also easy to handle.  
+We can catch the C++ exception and rethrow it as a Java exception like this:</p>
+
+<div class="code">
+<pre>
+%exception getitem {
+  try {
+     $action
+  } catch (std::out_of_range &amp;e) {
+    jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
+    jenv-&gt;ThrowNew(clazz, "Range error");
+    return $null;
+   }
+}
+
+class FooClass {
+public:
+     FooClass *getitem(int index);      // Might throw std::out_of_range exception
+     ...
+};
+</pre>
+</div>
+
+<p>
+In the example above, <tt>java.lang.Exception</tt> is a checked exception class and so ought to be declared in the throws clause of <tt>getitem</tt>.
+Classes can be specified for adding to the throws clause using <tt>%javaexception(classes)</tt> instead of <tt>%exception</tt>,
+where <tt>classes</tt> is a string containing one or more comma separated Java classes.
+The <tt>%nojavaexception</tt> feature is the equivalent to <tt>%noexception</tt> and clears previously declared exception handlers.
+</p>
+
+<div class="code">
+<pre>
+%javaexception("java.lang.Exception") getitem {
+  try {
+     $action
+  } catch (std::out_of_range &amp;e) {
+    jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
+    jenv-&gt;ThrowNew(clazz, "Range error");
+    return $null;
+   }
+}
+
+class FooClass {
+public:
+     FooClass *getitem(int index);      // Might throw std::out_of_range exception
+     ...
+};
+</pre>
+</div>
+
+<p>
+The generated proxy method now generates a throws clause containing <tt>java.lang.Exception</tt>:
+</p>
+
+<div class="code">
+<pre>
+public class FooClass {
+  ...
+  public FooClass getitem(int index) throws java.lang.Exception { ... }
+  ...
+}
+</pre>
+</div>
+
+
+<p>
+The examples above first use the C JNI calling syntax then the C++ JNI calling syntax. The C++ calling syntax will not compile as C and also vice versa.
+It is however possible to write JNI calls which will compile under both C and C++ and is covered in the <a href="#typemaps_for_c_and_c++">Typemaps for both C and C++ compilation</a> section. 
+</p>
+
+<p>
+The language-independent <tt>exception.i</tt> library file can also be used
+to raise exceptions.  See the <a href="Library.html#Library">SWIG Library</a> chapter.
+The typemap example <a href="#exception_typemap">Handling C++ exception specifications as Java exceptions</a> provides further exception handling capabilities.
+</p>
+
+<H3><a name="method_access"></a>20.7.4 Method access with %javamethodmodifiers</H3>
+
+
+<p>
+A Java feature called <tt>%javamethodmodifiers</tt> can be used to change the method modifiers from the default <tt>public</tt>. It applies to both module class methods and proxy class methods. For example:
+</p>
+
+<div class="code">
+<pre>
+%javamethodmodifiers protect_me() "protected";
+void protect_me();
+</pre>
+</div>
+
+<p>
+Will produce the method in the module class with protected access.
+</p>
+
+<div class="code">
+<pre>
+protected static void protect_me() {
+  exampleJNI.protect_me();
+}
+</pre>
+</div>
+
+<H2><a name="tips_techniques"></a>20.8 Tips and techniques</H2>
+
+
+<p>
+Although SWIG is largely automatic, there are certain types of wrapping problems that
+require additional user input.    Examples include dealing with output parameters,
+strings and arrays.   This chapter discusses the common techniques for
+solving these problems.
+</p>
+
+<H3><a name="input_output_parameters"></a>20.8.1 Input and output parameters using primitive pointers and references</H3>
+
+
+<p>
+A common problem in some C programs is handling parameters passed as simple pointers or references.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+void add(int x, int y, int *result) {
+   *result = x + y;
+}
+</pre>
+</div>
+
+<p>
+or perhaps
+</p>
+
+<div class="code">
+<pre>
+int sub(int *x, int *y) {
+   return *x-*y;
+}
+</pre>
+</div>
+
+<p>
+The <tt>typemaps.i</tt> library file will help in these situations.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+void add(int, int, int *OUTPUT);
+int  sub(int *INPUT, int *INPUT);
+</pre>
+</div>
+
+<p>
+In Java, this allows you to pass simple values.  For example:
+</p>
+
+<div class="code">
+<pre>
+int result = example.sub(7,4);
+System.out.println("7 - 4 = " + result);
+int[] sum = {0};
+example.add(3,4,sum);
+System.out.println("3 + 4 = " + sum[0]);
+</pre>
+</div>
+
+<p>
+Which will display:
+</p>
+
+<div class="code"> <pre>
+7 - 4 = 3
+3 + 4 = 7
+</pre></div>
+
+<p>
+Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
+and how the <tt>OUTPUT</tt> parameter will return the result in the first element of the integer array.
+</p>
+
+<p>
+If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
+directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+%apply int *OUTPUT { int *result };
+%apply int *INPUT  { int *x, int *y};
+
+void add(int x, int y, int *result);
+int  sub(int *x, int *y);
+</pre>
+</div>
+
+<p>
+If a function mutates one of its parameters like this,
+</p>
+
+<div class="code">
+<pre>
+void negate(int *x) {
+   *x = -(*x);
+}
+</pre>
+</div>
+
+<p>
+you can use <tt>INOUT</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+%include "typemaps.i"
+...
+void negate(int *INOUT);
+</pre>
+</div>
+
+<p>
+In Java, the input parameter is the first element in a 1 element array and is replaced by the output of the function. For example:
+</p>
+
+<div class="code">
+<pre>
+int[] neg = {3};
+example.negate(neg);
+System.out.println("Negative of 3 = " + neg[0]);
+</pre>
+</div>
+
+<p>
+And no prizes for guessing the output:
+</p>
+
+<div class="code"><pre>
+Negative of 3 = -3
+</pre></div>
+
+<p>
+These typemaps can also be applied to C++ references. 
+The above examples would work the same if they had been defined using references instead of pointers.
+For example, the Java code to use the <tt>negate</tt> function would be the same if it were defined either as it is above: 
+</p>
+
+<div class="code">
+<pre>
+void negate(int *INOUT);
+</pre>
+</div>
+
+<p>
+or using a reference:
+</p>
+
+<div class="code">
+<pre>
+void negate(int &amp;INOUT);
+</pre>
+</div>
+
+<p>
+Note: Since most Java primitive types are immutable and are passed by value, it is not possible to
+perform in-place modification of a type passed as a parameter.
+</p>
+
+<p>
+Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
+Writing a function like this
+</p>
+
+<div class="code">
+<pre>
+void foo(Bar *OUTPUT);
+</pre>
+</div>
+
+<p>
+will not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
+</p>
+
+<H3><a name="simple_pointers"></a>20.8.2 Simple pointers</H3>
+
+
+<p>
+If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> another approach to using 
+<tt>typemaps.i</tt> is to use the <tt>cpointer.i</tt> pointer library file.    For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "cpointer.i"
+
+%inline %{
+extern void add(int x, int y, int *result);
+%}
+
+%pointer_functions(int, intp);
+</pre>
+</div>
+
+<p>
+The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create,
+destroy, copy, assign, and dereference a pointer.  In this case, the functions are as follows:
+</p>
+
+<div class="code">
+<pre>
+int  *new_intp();
+int  *copy_intp(int *x);
+void  delete_intp(int *x);
+void  intp_assign(int *x, int value);
+int   intp_value(int *x);
+</pre>
+</div>
+
+<p>
+In Java, you would use the functions like this:
+</p>
+
+<div class="code">
+<pre>
+SWIGTYPE_p_int intPtr = example.new_intp();
+example.add(3,4,intPtr);
+int result = example.intp_value(intPtr);
+System.out.println("3 + 4 = " + result);
+</pre>
+</div>
+
+<p>
+If you replace <tt>%pointer_functions(int,intp)</tt> by <tt>%pointer_class(int,intp)</tt>, the interface is more class-like.
+</p>
+
+<div class="code">
+<pre>
+intp intPtr = new intp();
+example.add(3,4,intPtr.cast());
+int result = intPtr.value();
+System.out.println("3 + 4 = " + result);
+</pre>
+</div>
+
+<p>
+See the <a href="Library.html#Library">SWIG Library</a> chapter for further details.
+</p>
+
+<H3><a name="c_arrays"></a>20.8.3 Wrapping C arrays with Java arrays</H3>
+
+
+<p>
+SWIG can wrap arrays in a more natural Java manner than the default by using the <tt>arrays_java.i</tt> library file. 
+Let's consider an example:
+</p>
+
+<div class="code">
+<pre>
+%include "arrays_java.i";
+int array[4];
+void populate(int x[]) {
+    int i;
+    for (i=0; i&lt;4; i++)
+        x[i] = 100 + i;
+}
+</pre>
+</div>
+
+<p>
+These one dimensional arrays can then be used as if they were Java arrays:
+</p>
+
+<div class="code">
+<pre>
+int[] array = new int[4];
+example.populate(array);
+
+System.out.print("array: ");
+for (int i=0; i&lt;array.length; i++)
+    System.out.print(array[i] + " ");
+
+example.setArray(array);
+
+int[] global_array = example.getArray();
+
+System.out.print("\nglobal_array: ");
+for (int i=0; i&lt;array.length; i++)
+    System.out.print(global_array[i] + " ");
+</pre>
+</div>
+
+<p>
+Java arrays are always passed by reference, so any changes a function makes to the array will be seen by the calling function. 
+Here is the output after running this code:
+</p>
+
+<div class="code">
+<pre>
+array: 100 101 102 103
+global_array: 100 101 102 103
+</pre>
+</div>
+
+<p>
+Note that for assigning array variables the length of the C variable is used, so it is possible to use a Java array that is bigger than the C code will cope with.
+Only the number of elements in the C array will be used.
+However, if the Java array is not large enough then you are likely to get a segmentation fault or access violation, just like you would in C.
+When arrays are used in functions like <tt>populate</tt>, the size of the C array passed to the function is determined by the size of the Java array.
+</p>
+
+<p>
+Please be aware that the typemaps in this library are not efficient as all the elements are copied from the Java array to a C array whenever the array is passed to and from JNI code.
+There is an alternative approach using the SWIG array library and this is covered in the next section.
+</p>
+
+<H3><a name="unbounded_c_arrays"></a>20.8.4 Unbounded C Arrays</H3>
+
+
+<p>
+Sometimes a C function expects an array to be passed as a pointer.  For example,
+</p>
+
+<div class="code">
+<pre>
+int sumitems(int *first, int nitems) {
+    int i, sum = 0;
+    for (i = 0; i &lt; nitems; i++) {
+        sum += first[i];
+    }
+    return sum;
+}
+</pre>
+</div>
+
+<p>
+One of the ways to wrap this is to apply the Java array typemaps that come in the <tt>arrays_java.i</tt> library file:
+</p>
+
+<div class="code">
+<pre>
+%include "arrays_java.i"
+%apply int[] {int *};
+</pre>
+</div>
+
+<p>
+The <tt>ANY</tt> size will ensure the typemap is applied to arrays of all sizes.
+You could narrow the typemap matching rules by specifying a particular array size.
+Now you can use a pure Java array and pass it to the C code:
+</p>
+
+<div class="code">
+<pre>
+int[] array = new int[10000000];          // Array of 10-million integers
+for (int i=0; i&lt;array.length; i++) {      // Set some values
+  array[i] = i;
+}
+int sum = example.sumitems(array,10000);
+System.out.println("Sum = " + sum);
+</pre>
+</div>
+
+<p>
+and the sum would be displayed:
+</p>
+
+<div class="code">
+<pre>
+Sum = 49995000
+</pre>
+</div>
+
+<p>
+This approach is probably the most natural way to use arrays.
+However, it suffers from performance problems when using large arrays as a lot of copying
+of the elements occurs in transferring the array from the Java world to the C++ world.
+An alternative approach to using Java arrays for C arrays is to use an alternative SWIG library file <tt>carrays.i</tt>.
+This approach can be more efficient for large arrays as the array is accessed one element at a time.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%include "carrays.i"
+%array_functions(int, intArray);
+</pre>
+</div>
+
+<p>
+The <tt>%array_functions(type,name)</tt> macro generates four helper functions that can be used to create and
+destroy arrays and operate on elements.  In this case, the functions are as follows:
+</p>
+
+<div class="code">
+<pre>
+int *new_intArray(int nelements);
+void delete_intArray(int *x);
+int intArray_getitem(int *x, int index);
+void intArray_setitem(int *x, int index, int value);
+</pre>
+</div>
+
+<p>
+In Java, you would use the functions like this:
+</p>
+
+<div class="code">
+<pre>
+SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
+for (int i=0; i&lt;10000; i++) {                           // Set some values
+    example.intArray_setitem(array,i,i);
+}
+int sum = example.sumitems(array,10000);
+System.out.println("Sum = " + sum);
+</pre>
+</div>
+
+<p>
+If you replace <tt>%array_functions(int,intp)</tt> by <tt>%array_class(int,intp)</tt>, the interface is more class-like
+and a couple more helper functions are available for casting between the array and the type wrapper class.
+</p>
+
+<div class="code">
+<pre>
+%include "carrays.i"
+%array_class(int, intArray);
+</pre>
+</div>
+
+<p>
+The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
+can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
+For instance, you will be able to do this in Java:
+</p>
+
+<div class="code">
+<pre>
+intArray array = new intArray(10000000);  // Array of 10-million integers
+for (int i=0; i&lt;10000; i++) {             // Set some values
+    array.setitem(i,i);
+}
+int sum = example.sumitems(array.cast(),10000);
+System.out.println("Sum = " + sum);
+</pre>
+</div>
+
+<p>
+The array "object" created by <tt>%array_class()</tt> does not
+encapsulate pointers inside a special array object.  In fact, there is
+no bounds checking or safety of any kind (just like in C).  Because of
+this, the arrays created by this library are extremely low-level
+indeed.  You can't iterate over them nor can you even query their
+length.  In fact, any valid memory address can be accessed if you want
+(negative indices, indices beyond the end of the array, etc.).
+Needless to say, this approach is not going to suit all applications.
+On the other hand, this low-level approach is extremely efficient and
+well suited for applications in which you need to create buffers,
+package binary data, etc.
+</p>
+
+<H3><a name="java_heap_allocations"></a>20.8.5 Overriding new and delete to allocate from Java heap</H3>
+
+
+<p>
+Unlike some languages supported by SWIG, Java has a true garbage collection
+subsystem.  Other languages will free SWIG wrapped objects when their reference
+count reaches zero.  Java only schedules these objects for finalization, which
+may not occur for some time.  Because SWIG objects are allocated on the C
+heap, Java users may find the JVM memory use 
+quickly exceeds the assigned limits, as memory fills with unfinalized proxy
+objects.  Forcing garbage collection is clearly an undesirable solution.
+</p>
+
+<p>
+An elegant fix for C++ users is to override new and delete using the following
+code (here shown included in a SWIG interface file)
+</p>
+
+<div class="code">
+<pre>
+/* File: java_heap.i */
+%module test
+%{
+#include &lt;stdexcept&gt;
+#include "jni.h"
+
+/**
+ *  A stash area embedded in each allocation to hold java handles
+ */
+struct Jalloc {
+  jbyteArray jba;
+  jobject ref;
+};
+
+static JavaVM *cached_jvm = 0;
+
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
+  cached_jvm = jvm;
+  return JNI_VERSION_1_2;
+}
+
+static JNIEnv * JNU_GetEnv() {
+  JNIEnv *env;
+  jint rc = cached_jvm-&gt;GetEnv((void **)&amp;env, JNI_VERSION_1_2);
+  if (rc == JNI_EDETACHED)
+    throw std::runtime_error("current thread not attached");
+  if (rc == JNI_EVERSION)
+    throw std::runtime_error("jni version not supported");
+  return env;
+}
+
+void * operator new(size_t t) {
+  if (cached_jvm != 0) {
+    JNIEnv *env = JNU_GetEnv();
+    jbyteArray jba = env-&gt;NewByteArray((int) t + sizeof(Jalloc));
+    if (env-&gt;ExceptionOccurred())
+      throw bad_alloc();
+    void *jbuffer = static_cast&lt;void *&gt;(env-&gt;GetByteArrayElements(jba, 0));
+    if (env-&gt;ExceptionOccurred())
+      throw bad_alloc();
+    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(jbuffer);
+    pJalloc-&gt;jba = jba;
+    /* Assign a global reference so byte array will persist until delete'ed */
+    pJalloc-&gt;ref = env-&gt;NewGlobalRef(jba);
+    if (env-&gt;ExceptionOccurred())
+      throw bad_alloc();
+    return static_cast&lt;void *&gt;(static_cast&lt;char *&gt;(jbuffer) + sizeof(Jalloc));
+  }
+  else { /* JNI_OnLoad not called, use malloc and mark as special */
+    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(malloc((int) t + sizeof(Jalloc)));
+    if (!pJalloc)
+      throw bad_alloc();
+    pJalloc-&gt;ref = 0;
+    return static_cast&lt;void *&gt;(
+        static_cast&lt;char *&gt;(static_cast&lt;void *&gt;(pJalloc)) + sizeof(Jalloc));
+  }
+}
+
+void operator delete(void *v) {
+  if (v != 0) {
+    void *buffer = static_cast&lt;void *&gt;( static_cast&lt;char *&gt;(v) - sizeof(Jalloc));
+    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(buffer);
+    if (pJalloc-&gt;ref) {
+      JNIEnv *env = JNU_GetEnv();
+      env-&gt;DeleteGlobalRef(pJalloc-&gt;ref);
+      env-&gt;ReleaseByteArrayElements(pJalloc-&gt;jba, static_cast&lt;jbyte *&gt;(buffer), 0);
+    }
+    else {
+      free(buffer);
+    }
+  }
+}
+%}
+...
+</pre>
+</div>
+
+<p>
+This code caches the Java environment during initialization,
+and when new is called, a Java ByteArray is allocated to provide the
+SWIG objects with space in the Java heap.  This has the combined
+effect of re-asserting the Java virtual machine's limit on memory allocation,
+and puts additional pressure on the garbage collection system to run more
+frequently.
+This code is made slightly more complicated because allowances must be made
+if new is called before the JNI_OnLoad is executed.  This can happen during
+static class initialization, for example.  
+</p>
+
+<p>
+Unfortunately, because most Java implementations call malloc and free, this
+solution will not work for C wrapped structures.  However, you are free to
+make functions that allocate and free memory from the Java heap using this
+model and use these functions in place of malloc and free in your own
+code.
+</p>
+
+<H2><a name="java_typemaps"></a>20.9 Java typemaps</H2>
+
+
+<p>
+This section describes how you can modify SWIG's default wrapping behavior
+for various C/C++ datatypes using the <tt>%typemap</tt> directive.   
+You are advised to be familiar with the the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+While not absolutely essential knowledge, this section assumes some familiarity with the Java Native Interface (JNI). 
+JNI documentation can be consulted either online at <a href="http://java.sun.com">Sun's Java web site</a> or from a good JNI book. 
+The following two books are recommended:</p>
+
+<ul>
+<li> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. Publisher: Prentice Hall. ISBN: 0-13-679895-0.  </li>
+<li> Title: 'The Java Native Interface: Programmer's Guide and Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN: 0-201-32577-2.  Also available <a href="http://java.sun.com/docs/books/jni">online</a> at the Sun Developer Network.</li>
+</ul>
+
+<p>
+Before proceeding, it should be stressed that typemaps are not a required 
+part of using SWIG---the default wrapping behavior is enough in most cases.
+Typemaps are only used if you want to change some aspect of the generated code.
+
+<H3><a name="default_primitive_type_mappings"></a>20.9.1 Default primitive type mappings</H3>
+
+
+<p>
+The following table lists the default type mapping from Java to C/C++.</p>
+
+<table BORDER summary="Default primitive type mappings">
+<tr>
+<td><b>C/C++ type</b></td>
+<td><b>Java type</b></td>
+<td><b>JNI type</b></td>
+</tr>
+
+<tr>
+<td>bool<br> const bool &amp; </td>
+<td>boolean</td>
+<td>jboolean</td>
+</tr>
+
+<tr>
+<td>char<br>const char &amp;</td>
+<td>char</td>
+<td>jchar</td>
+</tr>
+
+<tr>
+<td>signed char<br>const signed char &amp;</td>
+<td>byte</td>
+<td>jbyte</td>
+</tr>
+
+<tr>
+<td>unsigned char<br>const unsigned char &amp;</td>
+<td>short</td>
+<td>jshort</td>
+</tr>
+
+<tr>
+<td>short<br>const short &amp;</td>
+<td>short</td>
+<td>jshort</td>
+</tr>
+
+<tr>
+<td>unsigned short<br> const unsigned short &amp;</td>
+<td>int</td>
+<td>jint</td>
+</tr>
+
+<tr>
+<td>int<br> const int &amp;</td>
+<td>int</td>
+<td>jint</td>
+</tr>
+
+<tr>
+<td>unsigned int<br> const unsigned int &amp;</td>
+<td>long</td>
+<td>jlong</td>
+</tr>
+
+<tr>
+<td>long<br>const long &amp;</td>
+<td>int</td>
+<td>jint</td>
+</tr>
+
+<tr>
+<td>unsigned long<br>const unsigned long &amp;</td>
+<td>long</td>
+<td>jlong</td>
+</tr>
+
+<tr>
+<td>long long<br> const long long &amp;</td>
+<td>long</td>
+<td>jlong</td>
+</tr>
+
+<tr>
+<td>unsigned long long<br>const unsigned long long &amp;</td>
+<td>java.math.BigInteger</td>
+<td>jobject</td>
+</tr>
+
+<tr>
+<td>float<br>const float &amp;</td>
+<td>float</td>
+<td>jfloat</td>
+</tr>
+
+<tr>
+<td>double<br> const double &amp;</td>
+<td>double</td>
+<td>jdouble</td>
+</tr>
+
+<tr>
+<td>char *<br>char []</td>
+<td>String</td>
+<td>jstring</td>
+</tr>
+
+</table>
+
+<p>
+Note that SWIG wraps the C <tt>char</tt> type as a character. Pointers and arrays of this type are wrapped as strings. 
+The <tt>signed char</tt> type can be used if you want to treat <tt>char</tt> as a signed number rather than a character.
+Also note that all const references to primitive types are treated as if they are passed by value.
+</p>
+
+<p>
+Given the following C function:
+</p>
+
+<div class="code"> <pre>
+void func(unsigned short a, char *b, const long &amp;c, unsigned long long d);
+</pre> </div>
+
+<p>
+The module class method would be:
+</p>
+
+<div class="code"> <pre>
+public static void func(int a, String b, int c, java.math.BigInteger d) {...}
+</pre> </div>
+
+<p>
+The intermediary JNI class would use the same types:
+</p>
+
+<div class="code"> <pre>
+public final static native void func(int jarg1, String jarg2, int jarg3,
+                                     java.math.BigInteger jarg4);
+</pre> </div>
+
+<p>
+and the JNI function would look like this:
+</p>
+
+<div class="code"> <pre>
+SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
+                jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
+</pre> </div>
+
+<p>
+The mappings for C <tt>int</tt> and C <tt>long</tt> are appropriate for 32 bit applications which are used in the 32 bit JVMs. 
+There is no perfect mapping between Java and C as Java doesn't support all the unsigned C data types. 
+However, the mappings allow the full range of values for each C type from Java. 
+</p>
+
+
+<H3><a name="Java_default_non_primitive_typemaps"></a>20.9.2 Default typemaps for non-primitive types</H3>
+
+
+<p>
+The previous section covered the primitive type mappings.
+Non-primitive types such as classes and structs are mapped using pointers on the C/C++ side and storing the pointer into a Java <tt>long</tt> variable which is held by
+the proxy class or type wrapper class. This applies whether the type is marshalled as a pointer, by reference or by value.
+It also applies for any unknown/incomplete types which use type wrapper classes.
+</p>
+
+<p>
+So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit Java <tt>long</tt> type and therefore the JNI type is a <tt>jlong</tt>.
+The Java type is either the proxy class or type wrapper class.
+</p>
+
+<H3><a name="jvm64"></a>20.9.3 Sixty four bit JVMs</H3>
+
+
+<p>
+If you are using a 64 bit JVM you may have to override the C long, but probably not C int default mappings. 
+Mappings will be system dependent, for example long will need remapping on Unix LP64 systems (long, pointer 64 bits, int 32 bits), but not on 
+Microsoft 64 bit Windows which will be using a P64 IL32 (pointer 64 bits and int, long 32 bits) model. 
+This may be automated in a future version of SWIG. 
+Note that the Java write once run anywhere philosophy holds true for all pure Java code when moving to a 64 bit JVM. 
+Unfortunately it won't of course hold true for JNI code.
+</p>
+
+
+<H3><a name="what_is_typemap"></a>20.9.4 What is a typemap?</H3>
+
+
+<p>
+A typemap is nothing more than a code generation rule that is attached to 
+a specific C datatype.   For example, to convert integers from Java to C,
+you might define a typemap like this:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int {
+  $1 = $input;
+  printf("Received an integer : %d\n",  $1);
+}
+%inline %{
+extern int fact(int nonnegative);
+%}
+</pre></div>
+
+<p>
+Typemaps are always associated with some specific aspect of code generation.
+In this case, the "in" method refers to the conversion of input arguments
+to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
+will be applied.  The supplied C code is used to convert values.  In this
+code a number of special variables prefaced by a <tt>$</tt> are used.  The
+<tt>$1</tt> variable is a placeholder for a local variable of type <tt>int</tt>.
+The <tt>$input</tt> variable contains the Java data, the JNI <tt>jint</tt> in this case.
+</p>
+
+<p>
+When this example is compiled into a Java module, it can be used as follows:
+</p>
+
+<div class="code"><pre>
+System.out.println(example.fact(6));
+</pre></div>
+
+<p>
+and the output will be:
+</p>
+
+<div class="code"><pre>
+Received an integer : 6
+720
+</pre></div>
+
+<p>
+In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
+You can refine this by supplying an optional parameter name.  For example:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int nonnegative {
+  $1 = $input;
+  printf("Received an integer : %d\n",  $1);
+}
+
+%inline %{
+extern int fact(int nonnegative);
+%}
+</pre></div>
+
+<p>
+In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
+</p>
+
+<p>
+The application of a typemap to specific datatypes and argument names involves
+more than simple text-matching--typemaps are fully integrated into the
+SWIG C++ type-system.   When you define a typemap for <tt>int</tt>, that typemap
+applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
+the typemap system follows <tt>typedef</tt> declarations.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int nonnegative {
+  $1 = $input;
+  printf("Received an integer : %d\n",  $1);
+}
+%inline %{
+typedef int Integer;
+extern int fact(Integer nonnegative);    // Above typemap is applied
+%}
+</pre>
+</div>
+
+<p>
+However, the matching of <tt>typedef</tt> only occurs in one direction.  If you
+defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
+type <tt>int</tt>.
+</p>
+
+<p>
+Typemaps can also be defined for groups of consecutive arguments.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (char *str, int len) {
+...
+};
+
+int count(char c, char *str, int len);
+</pre>
+</div>
+
+<p>
+When a multi-argument typemap is defined, the arguments are always handled as a single
+Java parameter.  This allows the function to be used like this (notice how the length
+parameter is omitted):
+</p>
+
+<div class="code">
+<pre>
+int c = example.count('e',"Hello World");
+</pre>
+</div>
+
+<H3><a name="typemaps_c_to_java_types"></a>20.9.5 Typemaps for mapping C/C++ types to Java types</H3>
+
+
+<p>
+The typemaps available to the Java module include the common typemaps listed in the main typemaps section. 
+There are a number of additional typemaps which are necessary for using SWIG with Java.
+The most important of these implement the mapping of C/C++ types to Java types:
+</p>
+
+<br>&nbsp;
+<table BORDER summary="Typemap mappings for C/C++ types to Java types">
+<tr>
+<td><b>Typemap</b></td>
+
+<td><b>Description</b></td>
+</tr>
+
+<tr>
+<td>jni</td>
+<td>JNI C types. These provide the default mapping of types from C/C++ to JNI for use in the JNI (C/C++) code.</td>
+</tr>
+
+<tr>
+<td>jtype</td>
+<td>Java intermediary types. These provide the default mapping of types from C/C++ to Java for use in the native functions in the intermediary JNI class. The type must be the equivalent Java type for the JNI C type specified in the "jni" typemap.</td>
+</tr>
+
+<tr>
+<td>jstype</td>
+<td>Java types. These provide the default mapping of types from C/C++ to Java for use in the Java module class, proxy classes and type wrapper classes.</td>
+</tr>
+
+<tr>
+<td>javain</td>
+<td>Conversion from jstype to jtype. 
+    These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
+    to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
+    In other words the typemap provides the conversion to the native method call parameter types.</td>
+</tr>
+
+<tr>
+<td>javaout</td>
+<td>Conversion from jtype to jstype.
+    These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
+    the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
+    In other words the typemap provides the conversion from the native method call return type. </td>
+</tr>
+
+<tr>
+<td>javadirectorin</td>
+<td>Conversion from jtype to jstype for director methods.
+    These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
+    the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
+    This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
+    See <a href="#java_directors_typemaps">Director typemaps</a>.  </td>
+</tr>
+
+<tr>
+<td>javadirectorout</td>
+<td>Conversion from jstype to jtype for director methods.
+    These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
+    to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
+    This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
+    See <a href="#java_directors_typemaps">Director typemaps</a>.  </td>
+</tr>
+
+<tr>
+<td>directorin</td>
+<td>Conversion from C++ type to jni type for director methods.
+  These are C++ typemaps which convert the parameters used in the C++ director method to the appropriate JNI intermediary type.
+  The conversion is done in JNI code prior to calling the Java function from the JNI code.
+  See <a href="#java_directors_typemaps">Director typemaps</a>. </td>
+</tr>
+
+<tr>
+<td>directorout</td>
+<td>Conversion from jni type to C++ type for director methods.
+  These are C++ typemaps which convert the JNI return type used in the C++ director method to the appropriate C++ return type.
+  The conversion is done in JNI code after calling the Java function from the JNI code.
+  See <a href="#java_directors_typemaps">Director typemaps</a>. </td>
+</tr>
+
+</table>
+
+<p>
+If you are writing your own typemaps to handle a particular type, you will normally have to write a collection of them. 
+The default typemaps are in "<tt>java.swg</tt>" and so might be a good place for finding typemaps to base any new ones on.
+</p>
+
+<p>
+The "jni", "jtype" and "jstype" typemaps are usually defined together to handle the Java to C/C++ type mapping.
+An "in" typemap should be accompanied by a "javain" typemap and likewise an "out" typemap by a "javaout" typemap.
+If an "in" typemap is written, a "freearg" and "argout" typemap may also need to be written
+as some types have a default "freearg" and/or "argout" typemap which may need overriding. 
+The "freearg" typemap sometimes releases memory allocated by the "in" typemap. 
+The "argout" typemap sometimes sets values in function parameters which are passed by reference in Java. 
+</p>
+
+<p>
+Note that the "in" typemap marshals the JNI type held in the "jni" typemap to the real C/C++ type and for the opposite direction,
+the "out" typemap marshals the real C/C++ type to the JNI type held in the "jni" typemap.
+For <a href="#Java_default_non_primitive_typemaps">non-primitive types</a> 
+the "in" and "out" typemaps are responsible for casting between the C/C++ pointer and the 64 bit <tt>jlong</tt> type.
+There is no portable way to cast a pointer into a 64 bit integer type and the approach taken by SWIG is mostly portable, but breaks C/C++ aliasing rules.
+In summary, these rules state that a pointer to any type must never be dereferenced by a pointer to any other incompatible type.
+The following code snippet might aid in understand aliasing rules better:
+</p>
+
+<div class="code"><pre>
+    short a;
+    short* pa = 0;
+    int i = 0x1234;
+
+    a = (short)i;    /* okay */
+    a = *(short*)&amp;i; /* breaks aliasing rules */
+</pre></div>
+
+<p>
+An email posting, <a href="http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html">Aliasing, pointer casts and gcc 3.3</a> elaborates further on the subject.
+In SWIG, the "in" and "out" typemaps for pointers are typically
+</p>
+
+<div class="code"><pre>
+    %typemap(in) struct Foo * %{
+      $1 = *(struct Foo **)&amp;$input; /* cast jlong into C ptr */
+    %}
+    %typemap(out) struct Bar * %{
+      *(struct Bar **)&amp;$result = $1; /* cast C ptr into jlong */
+    %} 
+    struct Bar {...};
+    struct Foo {...};
+    struct Bar * FooBar(struct Foo *f);
+</pre></div>
+
+<p>
+resulting in the following code which breaks the aliasing rules:
+</p>
+
+<div class="code"><pre>
+SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls,
+                                                jlong jarg1, jobject jarg1_) {
+  jlong jresult = 0 ;
+  struct Foo *arg1 = (struct Foo *) 0 ;
+  struct Bar *result = 0 ;
+  
+  (void)jenv;
+  (void)jcls;
+  (void)jarg1_;
+  arg1 = *(struct Foo **)&amp;jarg1; 
+  result = (struct Bar *)FooBar(arg1);
+  *(struct Bar **)&amp;jresult = result; 
+  return jresult;
+}
+</pre></div>
+
+<p>
+If you are using gcc as your C compiler, you might get a "dereferencing type-punned pointer will break strict-aliasing rules" warning about this.
+Please see <a href="#compiling_dynamic">Compiling a dynamic module</a> to avoid runtime problems with these strict aliasing rules.
+</p>
+
+<p>
+The default code generated by SWIG for the Java module comes from the typemaps in the "<tt>java.swg</tt>" library file which implements the 
+<a href="#default_primitive_type_mappings">Default primitive type mappings</a> and 
+<a href="#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a> covered earlier.
+There are other type mapping typemaps in the Java library. 
+These are listed below:
+</p>
+
+<br>&nbsp;
+<table BORDER summary="Java library typemap mappings">
+<tr VALIGN=TOP>
+<td><b>C Type</b></td>
+<td><b>Typemap</b></td>
+<td><b>File</b></td>
+<td><b>Kind</b></td>
+<td><b>Java Type</b></td>
+<td><b>Function</b></td>
+</tr>
+
+<tr>
+<td>primitive pointers and references</td>
+<td>INPUT</td>
+<td>typemaps.i</td>
+<td>input</td>
+<td>Java basic types</td>
+<td>Allows values to be used for C functions taking pointers for data input.
+
+<tr>
+<td>primitive pointers and references</td>
+<td>OUTPUT</td>
+<td>typemaps.i</td>
+<td>output</td>
+<td>Java basic type arrays</td>
+<td>Allows values held within an array to be used for C functions taking pointers for data output.
+
+<tr>
+<td>primitive pointers and references</td>
+<td>INOUT</td>
+<td>typemaps.i</td>
+<td>input<br>output</td>
+<td>Java basic type arrays</td>
+<td>Allows values held within an array to be used for C functions taking pointers for data input and output.
+
+<tr>
+<td>string <br>wstring</td>
+<td>[unnamed]</td>
+<td>std_string.i</td>
+<td>input<br> output</td>
+<td>String</td>
+<td>Use for std::string mapping to Java String.</td>
+</tr>
+
+<tr>
+<td>arrays of primitive types</td>
+<td>[unnamed]</td>
+<td>arrays_java.i</td>
+<td>input<br> output</td>
+<td>arrays of primitive Java types</td>
+<td>Use for mapping C arrays to Java arrays.</td>
+</tr>
+
+<tr>
+<td>arrays of classes/structs/unions</td>
+<td>JAVA_ARRAYSOFCLASSES macro</td>
+<td>arrays_java.i</td>
+<td>input<br> output</td>
+<td>arrays of proxy classes</td>
+<td>Use for mapping C arrays to Java arrays.</td>
+</tr>
+
+<tr>
+<td>arrays of enums</td>
+<td>ARRAYSOFENUMS</td>
+<td>arrays_java.i</td>
+<td>input<br> output</td>
+<td>int[]</td>
+<td>Use for mapping C arrays to Java arrays (typeunsafe and simple enum wrapping approaches only).</td>
+</tr>
+
+<tr VALIGN=TOP>
+<td>char *</td>
+<td>BYTE</td>
+<td>various.i</td>
+<td>input</td>
+<td>byte[]</td>
+
+<td VALIGN=TOP>Java byte array is converted to char array</td>
+</tr>
+
+<tr>
+<td>char **</td>
+<td>STRING_ARRAY</td>
+<td>various.i</td>
+<td>input<br> output</td>
+<td>String[]</td>
+<td>Use for mapping NULL terminated arrays of C strings to Java String arrays</td>
+</tr>
+
+</table>
+
+<H3><a name="typemap_attributes"></a>20.9.6 Java typemap attributes</H3>
+
+
+<p>
+There are a few additional typemap attributes that the Java module supports.
+</p>
+
+<p>
+The first of these is the 'throws' attribute.
+The throws attribute is optional and specified after the typemap name and contains one or more comma separated classes for adding to the throws clause for any methods that use that typemap.
+It is analogous to the <a href="#exception_handling">%javaexception</a> feature's throws attribute.
+</p>
+
+<div class="code">
+<pre>
+%typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... }
+</pre>
+</div>
+
+<p>
+The attribute is necessary for supporting Java checked exceptions and can be added to just about any typemap.
+The list of typemaps include all the C/C++ (JNI) typemaps in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter and the
+Java specific typemaps listed in <a href="#typemaps_c_to_java_types">the previous section</a>, barring
+the "jni", "jtype" and "jstype" typemaps as they could never contain code to throw an exception.
+</p>
+
+<p>
+The throws clause is generated for the proxy method as well as the JNI method in the JNI intermediary class.
+If a method uses more than one typemap and each of those typemaps have classes specified in the throws clause,
+the union of the exception classes is added to the throws clause ensuring there are no duplicate classes.
+See the <a href="#nan_exception_typemap">NaN exception example</a> for further usage.
+</p>
+
+<p>
+The "jtype" typemap has the optional 'nopgcpp' attribute which can be used to suppress the generation of the <a href="java_pgcpp">premature garbage collection prevention parameter</a>.
+</p>
+
+<p>
+The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' attributes. These are used for generating code before and after the JNI call in the proxy class or module class. The 'pre' attribute contains code that is generated before the JNI call and the 'post' attribute contains code generated after the JNI call. The 'pgcppname' attribute is used to change the <a href="java_pgcpp">premature garbage collection prevention parameter</a> name passed to the JNI function. This is sometimes needed when the 'pre' typemap creates a temporary variable which is then passed to the JNI function.
+</p>
+
+<p>
+<a name="java_constructor_helper_function"></a>
+Note that when the 'pre' or 'post' attributes are specified and the associated type is used in a constructor, a constructor helper function is generated. This is necessary as the Java proxy constructor wrapper makes a call to a support constructor using a <i>this</i> call. In Java the <i>this</i> call must be the first statement in the constructor body. The constructor body thus calls the helper function and the helper function instead makes the JNI call, ensuring the 'pre' code is called before the JNI call is made. There is a <a href="#java_date_marshalling">Date marshalling</a> example showing 'pre', 'post' and 'pgcppname' attributes in action.
+</p>
+
+<H3><a name="special_variables"></a>20.9.7 Java special variables</H3>
+
+
+<p>
+The standard SWIG special variables are available for use within typemaps as described in the <a href="Typemaps.html#Typemaps">Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>,<tt>$result</tt> etc.
+</p>
+
+<p>
+The Java module uses a few additional special variables:
+</p>
+
+<p>
+<b><tt>$javaclassname</tt></b><br>
+This special variable works like the other <a href="Typemaps.html#Typemaps_special_variables">special variables</a>
+and <tt>$javaclassname</tt> is similar to <tt>$1_type</tt>. It expands to the class name for use in Java given a pointer. 
+SWIG wraps unions, structs and classes using pointers and in this case it expands to the Java proxy class name.
+For example, <tt>$javaclassname</tt> is replaced by the proxy classname <tt>Foo</tt> when wrapping a <tt>Foo *</tt> and 
+<tt>$&amp;javaclassname</tt> expands to the proxy classname when wrapping the C/C++ type <tt>Foo</tt> and <tt>$*javaclassname</tt>
+expands to the proxy classname when wrapping <tt>Foo *&amp;</tt>.
+If the type does not have an associated proxy class, it expands to the type wrapper class name, for example,
+<tt>SWIGTYPE_p_unsigned_short</tt> is generated when wrapping <tt>unsigned short *</tt>.
+</p>
+
+<p>
+<b><tt>$null </tt></b><br>
+Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:
+</p>
+
+<div class="code"><pre>
+%typemap(check) int * %{ 
+  if (error) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
+    return $null;
+  }
+%}
+</pre></div>
+
+<p>
+If the typemap gets put into a function with void as return, $null will expand to nothing:
+</p>
+
+<div class="code"><pre>
+SWIGEXPORT void JNICALL Java_jnifn(...) {
+    if (error) {
+      SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
+      return ;
+    }
+  ...
+}
+</pre></div>
+
+<p>
+otherwise $null expands to <i>NULL</i>
+</p>
+
+<div class="code"><pre>
+SWIGEXPORT jobject JNICALL Java_jnifn(...) {
+    if (error) {
+      SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
+      return NULL;
+    }
+  ...
+}
+</pre></div>
+
+<p>
+<b><tt>$javainput, $jnicall and $owner</tt></b><br>
+The $javainput special variable is used in "javain" typemaps and $jnicall and $owner are used in "javaout" typemaps.
+$jnicall is analogous to $action in %exception. It is replaced by the call to the native method in the intermediary JNI class.
+$owner is replaced by either <tt>true</tt> if %newobject has been used, otherwise <tt>false</tt>.
+$javainput is analogous to the $input special variable. It is replaced by the parameter name.
+</p>
+
+<p>
+Here is an example:
+</p>
+
+<div class="code"><pre>
+%typemap(javain) Class "Class.getCPtr($javainput)"
+%typemap(javain) unsigned short "$javainput"
+%typemap(javaout) Class * {
+    return new Class($jnicall, $owner);
+  }
+
+%inline %{
+    class Class {...};
+    Class * bar(Class cls, unsigned short ush) { return new Class(); };
+%}
+</pre></div>
+
+<p>
+The generated proxy code is then:
+</p>
+
+<div class="code"><pre>
+public static Class bar(Class cls, int ush) {
+  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
+}
+</pre></div>
+
+<p>
+Here $javainput has been replaced by <tt>cls</tt> and <tt>ush</tt>. $jnicall has been replaced by 
+the native method call, <tt>exampleJNI.bar(...)</tt> and $owner has been replaced by <tt>false</tt>.
+If %newobject is used by adding the following at the beginning of our example:
+</p>
+
+<div class="code"><pre>
+%newobject bar(Class cls, unsigned short ush);
+</pre></div>
+
+<p>
+The generated code constructs the return type using <tt>true</tt> indicating the proxy class <tt>Class</tt> is responsible for destroying the C++ memory allocated for it in <tt>bar</tt>:
+</p>
+
+<div class="code"><pre>
+public static Class bar(Class cls, int ush) {
+  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
+}
+</pre></div>
+
+<p>
+<b><tt>$static</tt></b><br>
+This special variable expands to either <i>static</i> or nothing depending on whether the class is an inner Java class or not.
+It is used in the "javaclassmodifiers" typemap so that global classes can be wrapped as Java proxy classes and nested C++ classes/enums
+can be wrapped with the Java equivalent, that is, static inner proxy classes.
+</p>
+
+<p>
+<b><tt>$jniinput, $javacall and $packagepath</tt></b><br>
+These special variables are used in the directors typemaps. See <a href="#java_directors_typemaps">Director specific typemaps</a> for details.
+</p>
+
+<p>
+<b><tt>$module</tt></b><br>
+This special variable expands to the module name, as specified by <tt>%module</tt> or the <tt>-module</tt> commandline option.
+</p>
+
+<p>
+<b><tt>$imclassname</tt></b><br>
+This special variable expands to the intermediary class name. Usually this is the same as '$moduleJNI',
+unless the jniclassname attribute is specified in the <a href="Java.html#java_module_directive">%module directive</a>.
+</p>
+
+<H3><a name="typemaps_for_c_and_cpp"></a>20.9.8 Typemaps for both C and C++ compilation</H3>
+
+
+<p>
+JNI calls must be written differently depending on whether the code is being compiled as C or C++. 
+For example C compilation requires the pointer to a function pointer struct member syntax like
+</p>
+
+<div class="code"><pre>
+const jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/String");
+</pre></div>
+
+<p>
+whereas C++ code compilation of the same function call is a member function call using a class pointer like
+</p>
+
+<div class="code"><pre>
+const jclass clazz = jenv-&gt;FindClass("java/lang/String");
+</pre></div>
+
+<p>
+To enable typemaps to be used for either C or C++ compilation, a set of JCALLx macros have been defined in Lib/java/javahead.swg, 
+where x is the number of arguments in the C++ version of the JNI call. 
+The above JNI calls would be written in a typemap like this
+</p>
+
+<div class="code"><pre>
+const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
+</pre></div>
+
+<p>
+Note that the SWIG preprocessor expands these into the appropriate C or C++ JNI calling convention. 
+The C calling convention is emitted by default and the C++ calling convention is emitted when using the -c++ SWIG commandline option. 
+If you do not intend your code to be targeting both C and C++ then your typemaps can use the appropriate JNI calling convention and need not use the JCALLx macros.
+</p>
+
+
+<H3><a name="java_code_typemaps"></a>20.9.9 Java code typemaps</H3>
+
+
+<p>
+Most of SWIG's typemaps are used for the generation of C/C++ code. 
+The typemaps in this section are used solely for the generation of Java code. 
+Elements of proxy classes and type wrapper classes come from the following typemaps (the defaults).
+</p>
+
+<p><tt>%typemap(javabase)</tt></p>
+<div class="indent">
+base (extends) for Java class: empty default
+<br>
+Note that this typemap accepts a <tt>replace</tt> attribute as an optional flag. When set to "1", it will replace/override any C++ base classes
+that might have been parsed. If this flag is not specified and there are C++ base classes, then a multiple inheritance warning
+is issued and the code in the typemap is ignored.
+</div>
+
+<p><tt>%typemap(javabody)</tt></p>
+<div class="indent">
+  the essential support body for proxy classes (proxy base classes only), typewrapper classes and enum classes.
+  Default contains extra constructors, memory ownership control member variables (<tt>swigCMemOwn</tt>, <tt>swigCPtr</tt>), the <tt>getCPtr</tt> method etc.
+</div>
+
+<p><tt>%typemap(javabody_derived)</tt></p>
+<div class="indent">
+  the essential support body for proxy classes (derived classes only).
+  Same as "javabody" typemap, but only used for proxy derived classes.
+</div>
+
+<p><tt>%typemap(javaclassmodifiers)</tt></p>
+<div class="indent">
+class modifiers for the Java class: default is "public class"
+</div>
+
+<p><tt>%typemap(javacode)</tt></p>
+<div class="indent">
+Java code is copied verbatim to the Java class: empty default
+</div>
+
+<p><tt>%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized")</tt> <br></p>
+<div class="indent">
+destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
+used for all proxy classes except those which have a base class
+: default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
+<br>
+<br>
+Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
+The method modifiers are also configurable via the <tt>methodmodifiers</tt> attribute.
+</div>
+
+<p><tt>%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized")</tt></p>
+<div class="indent">
+destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
+same as "javadestruct" but only used for derived proxy classes
+: default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
+<br>
+<br>
+Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
+The method modifiers are also configurable via the <tt>methodmodifiers</tt> attribute.
+</div>
+
+<p><tt>%typemap(javaimports)</tt></p>
+<div class="indent">
+import statements for Java class: empty default
+</div>
+
+<p><tt>%typemap(javainterfaces)</tt></p>
+<div class="indent">
+interfaces (extends) for Java class: empty default
+</div>
+
+<p><tt>%typemap(javafinalize)</tt></p>
+<div class="indent">
+the <tt>finalize()</tt> method (proxy classes only): default calls the <tt>delete()</tt> method
+</div>
+
+<p>
+<b>Compatibility Note:</b> In SWIG-1.3.21 and earlier releases, typemaps called "javagetcptr" and "javaptrconstructormodifiers" were available.
+These are deprecated and the "javabody" typemap can be used instead.
+</p>
+
+<p>
+In summary the contents of the typemaps make up a proxy class like this:
+</p>
+
+<div class="code">
+<pre>
+[ javaimports typemap ]
+[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
+                                             implements [ javainterfaces typemap ] {
+[ javabody or javabody_derived typemap ]
+[ javafinalize typemap ]
+public synchronized void <i>delete</i>() [ javadestruct OR javadestruct_derived typemap ]
+[ javacode typemap ]
+... proxy functions ...
+}
+</pre>
+</div>
+
+<p>
+Note the <tt><i>delete</i>()</tt> methodname and method modifiers are configurable, see "javadestruct" and "javadestruct_derived" typemaps above.
+</p>
+
+<p>
+The type wrapper class is similar in construction:
+</p>
+
+<div class="code">
+<pre>
+[ javaimports typemap ]
+[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
+                                             implements [ javainterfaces typemap ] {
+[ javabody typemap ]
+[ javacode typemap ]
+}
+</pre>
+</div>
+
+<p>The enum class is also similar in construction:</p>
+<div class="code">
+<pre>
+[ javaimports typemap ]
+[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
+                                             implements [ javainterfaces typemap ] {
+... Enum values ...
+[ javabody typemap ]
+[ javacode typemap ]
+}
+</pre>
+</div>
+
+<p>
+The "javaimports" typemap is ignored if the enum class is wrapped by an inner Java class, that is when wrapping an enum declared within a C++ class.
+</p>
+
+<p>
+The defaults can be overridden to tailor these classes.
+Here is an example which will change the <tt>getCPtr</tt> method and constructor from the default protected access to public access. 
+This has a practical application if you are invoking SWIG more than once and generating the wrapped classes into different packages in each invocation.
+If the classes in one package are using the classes in another package, then these methods need to be public.
+</p>
+
+<div class="code">
+<pre>
+%typemap(javabody) SWIGTYPE %{
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  public $javaclassname(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  public static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+</pre>
+</div>
+
+<p>
+The typemap code is the same that is in "<tt>java.swg</tt>", barring the two method modifiers.
+Note that <tt>SWIGTYPE</tt> will target all proxy classes, but not the type wrapper classes.
+Also the above typemap is only used for proxy classes that are potential base classes.
+To target proxy classes that are derived from a wrapped class as well, the "javabody_derived" typemap should also be overridden.
+</p>
+
+<p>
+For the typemap to be used in all type wrapper classes, all the different types that type wrapper classes could be used for should be targeted:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javabody) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+  private long swigCPtr;
+
+  public $javaclassname(long cPtr, boolean bFutureUse) {
+    swigCPtr = cPtr;
+  }
+
+  protected $javaclassname() {
+    swigCPtr = 0;
+  }
+
+  public static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+</pre>
+</div>
+
+<p>
+Again this is the same that is in "<tt>java.swg</tt>", barring the method modifier for <tt>getCPtr</tt>.
+</p>
+
+<H3><a name="java_directors_typemaps"></a>20.9.10 Director specific typemaps</H3>
+
+
+<p>
+The Java directors feature requires the "javadirectorin", "javadirectorout", "directorin" and the "directorout" typemaps in order to work properly.
+The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes.
+</p>
+
+<p><tt>%typemap(directorin)</tt></p>
+<div class="indent">
+
+<p>
+The "directorin" typemap is used for converting arguments in the C++ director class to the appropriate JNI type before the upcall to Java.
+This typemap also specifies the JNI field descriptor for the type in the "descriptor" attribute.
+For example, integers are converted as follows:
+</p>
+
+<div class="code">
+<pre>
+%typemap(directorin,descriptor="I") int "$input = (jint) $1;"
+</pre>
+</div>
+
+<p>
+<code>$input</code> is the SWIG name of the JNI temporary variable passed to Java in the upcall.
+The <code>descriptor="I"</code> will put an <code>I</code> into the JNI field descriptor that identifies the Java method that will be called from C++.
+For more about JNI field descriptors and their importance, refer to the <a href="#java_typemaps">JNI documentation mentioned earlier</a>.
+A typemap for C character strings is:
+</p>
+
+<div class="code">
+<pre>
+%typemap(directorin,descriptor="Ljava/lang/String;") char *
+  %{ $input = jenv-&gt;NewStringUTF($1); %}
+</pre>
+</div>
+
+
+<p>
+User-defined types have the default "descriptor" attribute "<code>L$packagepath/$javaclassname;</code>" where <code>$packagepath</code> 
+is the package name passed from the SWIG command line and <code>$javaclassname</code> is the Java proxy class' name.
+If the <tt>-package</tt> commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor.
+<b>Do not forget the terminating ';' for JNI field descriptors starting with 'L'.</b>
+If the ';' is left out, Java will generate a "method not found" runtime error.
+</p>
+</div>
+
+
+<p><tt>%typemap(directorout)</tt></p>
+<div class="indent">
+
+<p>
+The "directorout" typemap is used for converting the JNI return type in the C++ director class to the appropriate C++ type after the upcall to Java.
+For example, integers are converted as follows:
+</p>
+
+<div class="code">
+<pre>
+%typemap(directorout) int %{ $result = (int)$input; %}
+</pre>
+</div>
+
+<p>
+<code>$input</code> is the SWIG name of the JNI temporary variable returned from Java after the upcall.
+<code>$result</code> is the resulting output.
+A typemap for C character strings is:
+</p>
+
+<div class="code">
+<pre>
+%typemap(directorout) char * {
+  $1 = 0;
+  if ($input) {
+    $result = (char *)jenv-&gt;GetStringUTFChars($input, 0);
+    if (!$1) return $null;
+  }
+}
+</pre>
+</div>
+
+</div>
+
+
+<p><tt>%typemap(javadirectorin)</tt></p>
+<div class="indent">
+
+<p>
+Conversion from jtype to jstype for director methods.
+These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
+the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
+This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
+</p>
+
+<p>
+For primitive types, this typemap is usually specified as:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javadirectorin) int "$jniinput"
+</pre>
+</div>
+
+<p>
+The <code>$jniinput</code> special variable is analogous to <code>$javainput</code> special variable.
+It is replaced by the input parameter name.
+</p>
+
+</div>
+
+
+<p><tt>%typemap(javadirectorout)</tt></p>
+<div class="indent">
+
+<p>
+Conversion from jstype to jtype for director methods.
+These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
+to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
+This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
+</p>
+
+<p>
+For primitive types, this typemap is usually specified as:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javadirectorout) int "$javacall"
+</pre>
+</div>
+
+<p>
+The <code>$javacall</code> special variable is analogous to the <code>$jnicall</code> special variable.
+It is replaced by the call to the target Java method.
+The target method is the method in the Java proxy class which overrides the virtual C++ method in the C++ base class.
+</p>
+
+</div>
+
+<p><tt>%typemap(javapackage)</tt></p>
+<div class="indent">
+
+
+<p>
+The "javapackage" typemap is optional; it serves to identify a class's Java package.
+This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file.
+For example:
+</p>
+
+<div class="code">
+<pre>
+// class Foo is handled in a different interface file:
+%import "Foo.i"
+
+%feature("director") Example;
+
+%inline {
+  class Bar { };
+
+  class Example {
+  public:
+    virtual ~Example();
+    void     ping(Foo *arg1, Bar *arg2);
+  };
+}
+</pre>
+</div>
+
+<p>
+Assume that the Foo class is part of the Java package <i>com.wombat.foo</i> but the above interface file is part of the Java package <i>com.wombat.example</i>.
+Without the "javapackage" typemap, SWIG will assume that the Foo class belongs to <i>com.wombat.example</i> class.
+The corrected interface file looks like:
+</p>
+
+<div class="code">
+<pre>
+// class Foo is handled in a different interface file:
+%import "Foo.i"
+%typemap("javapackage") Foo, Foo *, Foo &amp; "com.wombat.foo";
+%feature("director") Example;
+
+%inline {
+  class Bar { };
+
+  class Example {
+  public:
+    virtual ~Example();
+    void     ping(Foo *arg1, Bar *arg2);
+  };
+}
+</pre>
+</div>
+
+<p>
+SWIG looks up the package based on the <b>actual</b> type (plain Foo, Foo pointer and Foo reference), so it is important to associate all three types with the desired package.
+Practically speaking, you should create a separate SWIG interface file, which is %import-ed into each SWIG interface file, when you have multiple Java packages.
+Note the helper macros below, <code>OTHER_PACKAGE_SPEC</code> and <code>ANOTHER_PACKAGE_SPEC</code>, which reduce the amount of extra typing.
+"<code>TYPE...</code>" is useful when passing templated types to the macro, since multiargument template types appear to the SWIG preprocessor as multiple macro arguments.
+</p>
+
+<div class="code">
+<pre>
+%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;
+                                            "package.for.most.classes";
+
+%define OTHER_PACKAGE_SPEC(TYPE...)
+%typemap("javapackage") TYPE, TYPE *, TYPE &amp; "package.for.other.classes";
+%enddef
+
+%define ANOTHER_PACKAGE_SPEC(TYPE...)
+%typemap("javapackage") TYPE, TYPE *, TYPE &amp; "package.for.another.set";
+%enddef
+
+OTHER_PACKAGE_SPEC(Package_2_class_one)
+ANOTHER_PACKAGE_SPEC(Package_3_class_two)
+/* etc */
+</pre>
+</div>
+
+<p>
+The basic strategy here is to provide a default package typemap for the majority of the classes, only providing "javapackage" typemaps for the exceptions.
+</p>
+
+</div>
+
+<H2><a name="typemap_examples"></a>20.10 Typemap Examples</H2>
+
+
+<p>
+This section includes a few examples of typemaps.  For more examples, you
+might look at the files "<tt>java.swg</tt>" and "<tt>typemaps.i</tt>" in
+the SWIG library.
+</p>
+
+
+<H3><a name="simpler_enum_classes"></a>20.10.1 Simpler Java enums for enums without initializers</H3>
+
+
+<p>
+The default <a href="#proper_enums_classes">Proper Java enums</a> approach to wrapping enums is somewhat verbose.
+This is to handle all possible C/C++ enums, in particular enums with initializers.
+The generated code can be simplified if the enum being wrapped does not have any initializers.
+</p>
+
+<p>
+The following shows how to remove the support methods that are generated by default and instead use the methods in the Java
+enum base class <tt>java.lang.Enum</tt> and <tt>java.lang.Class</tt> for marshalling enums between C/C++ and Java.
+The type used for the typemaps below is <tt>enum SWIGTYPE</tt> which is the default type used for all enums.
+The "enums.swg" file should be examined in order to see the original overridden versions of the typemaps.
+</p>
+
+<div class="code">
+<pre>
+%include "enums.swg"
+
+%typemap(javain) enum SWIGTYPE "$javainput.ordinal()"
+%typemap(javaout) enum SWIGTYPE {
+    return $javaclassname.class.getEnumConstants()[$jnicall];
+  }
+%typemap(javabody) enum SWIGTYPE ""
+
+%inline %{
+  enum HairType { blonde, ginger, brunette };
+  void setHair(HairType h);
+  HairType getHair();
+%}
+</pre>
+</div>
+
+<p>
+SWIG will generate the following Java enum, which is somewhat simpler than the default:
+</p>
+
+<div class="code">
+<pre>
+public enum HairType {
+  blonde,
+  ginger,
+  brunette;
+}
+</pre>
+</div>
+
+<p>
+and the two Java proxy methods will be:
+</p>
+
+<div class="code">
+<pre>
+public static void setHair(HairType h) {
+  exampleJNI.setHair(h.ordinal());
+}
+
+public static HairType getHair() {
+  return HairType.class.getEnumConstants()[exampleJNI.getHair()];
+}
+</pre>
+</div>
+
+<p>
+For marshalling Java enums to C/C++ enums, the <tt>ordinal</tt> method is used to convert the
+Java enum into an integer value for passing to the JNI layer, see the "javain" typemap.
+For marshalling C/C++ enums to Java enums, the C/C++ enum value is cast to an integer in the C/C++ typemaps (not shown).
+This integer value is then used to index into the array of enum constants that the Java language provides.
+See the <tt>getEnumConstants</tt> method in the "javaout" typemap.
+</p>
+
+<p>
+These typemaps can often be used as the default for wrapping enums as in many cases there won't be any enum initializers.
+In fact a good strategy is to always use these typemaps and to specifically handle enums with initializers using %apply.
+This would be done by using the original versions of these typemaps in "enums.swg" under another typemap name for applying using %apply.
+</p>
+
+
+<H3><a name="exception_typemap"></a>20.10.2 Handling C++ exception specifications as Java exceptions</H3>
+
+
+<p>
+This example demonstrates various ways in which C++ exceptions can be tailored and converted into Java exceptions.
+Let's consider a simple file class <tt>SimpleFile</tt> and an exception class <tt>FileException</tt> which it may throw on error:
+</p>
+
+<div class="code">
+<pre>
+%include "std_string.i" // for std::string typemaps
+#include &lt;string&gt;
+
+class FileException {
+  std::string message;
+public:
+  FileException(const std::string&amp; msg) : message(msg) {}
+  std::string what() {
+    return message;
+  }
+};
+
+class SimpleFile {
+  std::string filename;
+public:
+  SimpleFile(const std::string&amp; filename) : filename(filename) {}
+  void open() throw(FileException) {
+  ...
+  }
+};
+</pre>
+</div>
+
+<p>
+As the <tt>open</tt> method has a C++ exception specification, SWIG will parse this and know that the method can throw an exception.
+The <a href="Typemaps.html#throws_typemap">"throws" typemap</a> is then used when SWIG encounters an exception specification.
+The default generic "throws" typemap looks like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(throws) SWIGTYPE, SWIGTYPE &amp;, SWIGTYPE *, SWIGTYPE [ANY] %{
+  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
+                          "C++ $1_type exception thrown");
+  return $null;
+%}
+</pre>
+</div>
+
+<p>
+Basically SWIG will generate a C++ try catch block and the body of the "throws" typemap constitutes the catch block.
+The above typemap calls a SWIG supplied method which throws a <tt>java.lang.RuntimeException</tt>.
+This exception class is a runtime exception and therefore not a checked exception.
+If, however, we wanted to throw a checked exception, say <tt>java.io.IOException</tt>, then we could use the following typemap:
+</p>
+
+<div class="code">
+<pre>
+%typemap(throws, throws="java.io.IOException") FileException {
+  jclass excep = jenv-&gt;FindClass("java/io/IOException");
+  if (excep)
+    jenv-&gt;ThrowNew(excep, $1.what().c_str());
+  return $null;
+}
+</pre>
+</div>
+
+<p>
+Note that this typemap uses the 'throws' <a href="#typemap_attributes">typemap attribute</a> to ensure a throws clause is generated.
+The generated proxy method then specifies the checked exception by containing <tt>java.io.IOException</tt> in the throws clause:
+</p>
+
+<div class="code">
+<pre>
+public class SimpleFile {
+  ...
+  public void open() throws java.io.IOException { ... }
+}
+</pre>
+</div>
+
+<p>
+Lastly, if you don't want to map your C++ exception into one of the standard Java exceptions, the C++ class can be wrapped and turned into a custom Java exception class.
+If we go back to our example, the first thing we must do is get SWIG to wrap <tt>FileException</tt> and ensure that it derives from <tt>java.lang.Exception</tt>.
+Additionally, we might want to override the <tt>java.lang.Exception.getMessage()</tt> method.
+The typemaps to use then are as follows:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javabase) FileException "java.lang.Exception";
+%typemap(javacode) FileException %{
+  public String getMessage() {
+    return what();
+  }
+%}
+</pre>
+</div>
+
+<p>
+This generates:
+</p>
+
+<div class="code">
+<pre>
+public class FileException extends java.lang.Exception {
+  ...
+  public String getMessage() {
+    return what();
+  }
+
+  public FileException(String msg) { ... }
+
+  public String what() {
+    return exampleJNI.FileException_what(swigCPtr, this);
+  }
+}
+</pre>
+</div>
+
+<p>
+We could alternatively have used <tt>%rename</tt> to rename <tt>what()</tt> into <tt>getMessage()</tt>.
+</p>
+
+
+<H3><a name="nan_exception_typemap"></a>20.10.3 NaN Exception - exception handling for a particular type</H3>
+
+
+<p>
+A Java exception can be thrown from any Java or JNI code.
+Therefore, as most typemaps contain either Java or JNI code, just about any typemap could throw an exception.
+The following example demonstrates exception handling on a type by type basis by checking for 'Not a number' (NaN) whenever a parameter of type <tt>float</tt> is wrapped.
+</p>
+
+<p>
+Consider the following C++ code:
+</p>
+
+<div class="code">
+<pre>
+bool calculate(float first, float second);
+</pre>
+</div>
+
+<p>
+To validate every <tt>float</tt> being passed to C++, we could precede the code being wrapped by the following typemap which throws a runtime exception whenever the <tt>float</tt> is 'Not a Number':
+</p>
+
+<div class="code">
+<pre>
+%module example
+%typemap(javain) float "$module.CheckForNaN($javainput)"
+%pragma(java) modulecode=%{
+  /** Simply returns the input value unless it is not a number,
+      whereupon an exception is thrown. */
+  static protected float CheckForNaN(float num) {
+    if (Float.isNaN(num))
+      throw new RuntimeException("Not a number");
+    return num;
+  }
+%}
+</pre>
+</div>
+
+<p>
+Note that the <tt>CheckForNaN</tt> support method has been added to the module class using the <tt>modulecode</tt> pragma.
+The following shows the generated code of interest:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  ...
+
+  /** Simply returns the input value unless it is not a number,
+      whereupon an exception is thrown. */
+  static protected float CheckForNaN(float num) {
+    if (Float.isNaN(num))
+      throw new RuntimeException("Not a number");
+    return num;
+  }
+
+  public static boolean calculate(float first, float second) {
+    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
+  }
+}
+</pre>
+</div>
+
+<p>
+Note that the "javain" typemap is used for every occurrence of a <tt>float</tt> being used as an input.
+Of course, we could have targeted the typemap at a particular parameter by using <tt>float first</tt>, say, instead of just <tt>float</tt>.
+</p>
+
+<p>
+The exception checking could alternatively have been placed into the 'pre' attribute that the "javain" typemap supports.
+The "javain" typemap above could be replaced with the following:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javain, pre="    $module.CheckForNaN($javainput);") float "$javainput"
+</pre>
+</div>
+
+<p>
+which would modify the <tt>calculate</tt> function to instead be generated as:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  ...
+  public static boolean calculate(float first, float second) {
+    example.CheckForNaN(first);
+    example.CheckForNaN(second);
+    {
+      return exampleJNI.calculate(first, second);
+    }
+  }
+}
+</pre>
+</div>
+
+<p>
+See the <a href="#java_date_marshalling">Date marshalling example</a> for an example using further "javain" typemap attributes.
+</p>
+
+<p>
+If we decide that what we actually want is a checked exception instead of a runtime exception, we can change this easily enough.
+The proxy method that uses <tt>float</tt> as an input, must then add the exception class to the throws clause.
+SWIG can handle this as it supports the 'throws' <a href="#typemap_attributes">typemap attribute</a> for specifying classes for the throws clause.
+Thus we can modify the pragma and the typemap for the throws clause:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)"
+%pragma(java) modulecode=%{
+  /** Simply returns the input value unless it is not a number,
+      whereupon an exception is thrown. */
+  static protected float CheckForNaN(float num) throws java.lang.Exception {
+    if (Float.isNaN(num))
+      throw new RuntimeException("Not a number");
+    return num;
+  }
+%}
+</pre>
+</div>
+
+<p>
+The <tt>calculate</tt> method now has a throws clause and even though the typemap is used twice for both <tt>float first</tt> and <tt>float second</tt>,
+the throws clause contains a single instance of <tt>java.lang.Exception</tt>:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  ...
+
+  /** Simply returns the input value unless it is not a number,
+      whereupon an exception is thrown. */
+  static protected float CheckForNaN(float num) throws java.lang.Exception {
+    if (Float.isNaN(num))
+      throw new RuntimeException("Not a number");
+    return num;
+  }
+
+  public static boolean calculate(float first, float second) throws java.lang.Exception {
+    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
+  }
+}
+</pre>
+</div>
+
+<p>
+If we were a martyr to the JNI cause, we could replace the succinct code within the "javain" typemap with a few pages of JNI code.
+If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.
+</p>
+
+<H3><a name="converting_java_string_arrays"></a>20.10.4 Converting Java String arrays to char ** </H3>
+
+
+<p>
+A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings.   
+The following SWIG interface file allows a Java String array to be used as a <tt>char **</tt> object.
+</p>
+
+<div class="code"><pre>
+%module example
+
+/* This tells SWIG to treat char ** as a special case when used as a parameter
+   in a function call */
+%typemap(in) char ** (jint size) {
+    int i = 0;
+    size = (*jenv)-&gt;GetArrayLength(jenv, $input);
+    $1 = (char **) malloc((size+1)*sizeof(char *));
+    /* make a copy of each string */
+    for (i = 0; i&lt;size; i++) {
+        jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
+        const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
+        $1[i] = malloc((strlen(c_string)+1)*sizeof(char));
+        strcpy($1[i], c_string);
+        (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
+        (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
+    }
+    $1[i] = 0;
+}
+
+/* This cleans up the memory we malloc'd before the function call */
+%typemap(freearg) char ** {
+    int i;
+    for (i=0; i&lt;size$argnum-1; i++)
+      free($1[i]);
+    free($1);
+}
+
+/* This allows a C function to return a char ** as a Java String array */
+%typemap(out) char ** {
+    int i;
+    int len=0;
+    jstring temp_string;
+    const jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/String");
+
+    while ($1[len]) len++;    
+    jresult = (*jenv)-&gt;NewObjectArray(jenv, len, clazz, NULL);
+    /* exception checking omitted */
+
+    for (i=0; i&lt;len; i++) {
+      temp_string = (*jenv)-&gt;NewStringUTF(jenv, *result++);
+      (*jenv)-&gt;SetObjectArrayElement(jenv, jresult, i, temp_string);
+      (*jenv)-&gt;DeleteLocalRef(jenv, temp_string);
+    }
+}
+
+/* These 3 typemaps tell SWIG what JNI and Java types to use */
+%typemap(jni) char ** "jobjectArray"
+%typemap(jtype) char ** "String[]"
+%typemap(jstype) char ** "String[]"
+
+/* These 2 typemaps handle the conversion of the jtype to jstype typemap type
+   and vice versa */
+%typemap(javain) char ** "$javainput"
+%typemap(javaout) char ** {
+    return $jnicall;
+  }
+
+/* Now a few test functions */
+%inline %{
+
+int print_args(char **argv) {
+    int i = 0;
+    while (argv[i]) {
+         printf("argv[%d] = %s\n", i, argv[i]);
+         i++;
+    }
+    return i;
+}
+
+char **get_args() {
+  static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
+  return &amp;values[0];
+}
+
+%}
+</pre></div>
+
+<p>
+Note that the 'C' JNI calling convention is used. 
+Checking for any thrown exceptions after JNI function calls has been omitted. 
+When this module is compiled, our wrapped C functions can be used by the following Java program:
+</p>
+
+<div class="code"><pre>
+// File main.java
+
+public class main {
+
+  static {
+    try {
+     System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. " + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    String animals[] = {"Cat","Dog","Cow","Goat"};
+    example.print_args(animals);
+    String args[] = example.get_args();
+    for (int i=0; i&lt;args.length; i++)
+        System.out.println(i + ":" + args[i]);
+  }
+}
+</pre></div>
+
+<p>
+When compiled and run we get:
+</p>
+
+<div class="code"><pre>
+$ java main
+argv[0] = Cat
+argv[1] = Dog
+argv[2] = Cow
+argv[3] = Goat
+0:Dave
+1:Mike
+2:Susan
+3:John
+4:Michelle
+</pre></div>
+
+<p>
+In the example, a few different typemaps are used.  The "in" typemap is
+used to receive an input argument and convert it to a C array.  Since dynamic
+memory allocation is used to allocate memory for the array, the
+"freearg" typemap is used to later release this memory after the execution of
+the C function. The "out" typemap is used for function return values.
+Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify
+what Java types to use.
+</p>
+
+<H3><a name="expanding_java_object"></a>20.10.5 Expanding a Java object to multiple arguments</H3>
+
+
+<p>
+Suppose that you had a collection of C functions with arguments
+such as the following:
+</p>
+
+<div class="code">
+<pre>
+int foo(int argc, char **argv);
+</pre>
+</div>
+
+<p>
+In the previous example, a typemap was written to pass a Java String array as the <tt>char **argv</tt>.  This
+allows the function to be used from Java as follows:
+</p>
+
+<div class="code">
+<pre>
+example.foo(4, new String[]{"red", "green", "blue", "white"});
+</pre>
+</div>
+
+<p>
+Although this works, it's a little awkward to specify the argument count.  To fix this, a multi-argument
+typemap can be defined.  This is not very difficult--you only have to make slight modifications to the
+previous example's typemaps:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (int argc, char **argv) {
+    int i = 0;
+    $1 = (*jenv)-&gt;GetArrayLength(jenv, $input);
+    $2 = (char **) malloc(($1+1)*sizeof(char *));
+    /* make a copy of each string */
+    for (i = 0; i&lt;$1; i++) {
+        jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
+        const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
+        $2[i] = malloc((strlen(c_string)+1)*sizeof(char));
+        strcpy($2[i], c_string);
+        (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
+        (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
+    }
+    $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char **argv) {
+    int i;
+    for (i=0; i&lt;$1-1; i++)
+      free($2[i]);
+    free($2);
+}
+
+%typemap(jni) (int argc, char **argv) "jobjectArray"
+%typemap(jtype) (int argc, char **argv) "String[]"
+%typemap(jstype) (int argc, char **argv) "String[]"
+
+%typemap(javain) (int argc, char **argv) "$javainput"
+</pre>
+</div>
+
+<p>
+When writing a multiple-argument typemap, each of the types is referenced by a variable such 
+as <tt>$1</tt> or <tt>$2</tt>.   The typemap code simply fills in the appropriate values from
+the supplied Java parameter.
+</p>
+
+<p>
+With the above typemap in place, you will find it no longer necessary
+to supply the argument count.  This is automatically set by the typemap code.  For example:
+</p>
+
+<div class="code">
+<pre>
+example.foo(new String[]{"red", "green", "blue", "white"});
+</pre>
+</div>
+
+
+<H3><a name="using_typemaps_return_arguments"></a>20.10.6 Using typemaps to return arguments</H3>
+
+
+<p>
+A common problem in some C programs is that values may be returned in function parameters rather than in the return value of a function. 
+The <tt>typemaps.i</tt> file defines INPUT, OUTPUT and INOUT typemaps which can be used to solve some instances of this problem. 
+This library file uses an array as a means of moving data to and from Java when wrapping a C function that takes non const pointers or non const references as parameters.
+</p>
+ 
+<p>
+Now we are going to outline an alternative approach to using arrays for C pointers. 
+The INOUT typemap uses a <tt>double[]</tt> array for receiving and returning the <tt>double*</tt> parameters. 
+In this approach we are able to use a Java class <tt>myDouble</tt> instead of <tt>double[]</tt> arrays where the C pointer <tt>double*</tt> is required.
+</p>
+
+<p>
+Here is our example function:
+</p>
+
+<div class="code"><pre>
+/* Returns a status value and two values in out1 and out2 */
+int spam(double a, double b, double *out1, double *out2);
+</pre></div>
+
+<p>
+If we define a structure <tt>MyDouble</tt> containing a <tt>double</tt> member variable and use some typemaps we can solve this problem. For example we could put the following through SWIG:
+</p>
+
+<div class="code"><pre>
+%module example
+
+/* Define a new structure to use instead of double * */
+%inline %{
+typedef struct {
+    double value;
+} MyDouble;
+%}
+
+
+%{
+/* Returns a status value and two values in out1 and out2 */
+int spam(double a, double b, double *out1, double *out2) {
+  int status = 1;
+  *out1 = a*10.0;
+  *out2 = b*100.0;
+  return status;
+};
+%}
+
+/* 
+This typemap will make any double * function parameters with name <tt>OUTVALUE</tt> take an
+argument of MyDouble instead of double *. This will 
+allow the calling function to read the double * value after returning from the function.
+*/
+%typemap(in) double *OUTVALUE {
+    jclass clazz = jenv-&gt;FindClass("MyDouble");
+    jfieldID fid = jenv-&gt;GetFieldID(clazz, "swigCPtr", "J");
+    jlong cPtr = jenv-&gt;GetLongField($input, fid);
+    MyDouble *pMyDouble = NULL;
+    *(MyDouble **)&amp;pMyDouble = *(MyDouble **)&amp;cPtr;
+    $1 = &amp;pMyDouble-&gt;value;
+}
+
+%typemap(jtype) double *OUTVALUE "MyDouble"
+%typemap(jstype) double *OUTVALUE "MyDouble"
+%typemap(jni) double *OUTVALUE "jobject"
+
+%typemap(javain) double *OUTVALUE "$javainput"
+
+/* Now we apply the typemap to the named variables */
+%apply double *OUTVALUE { double *out1, double *out2 };
+int spam(double a, double b, double *out1, double *out2);
+</pre></div>
+
+<p>
+Note that the C++ JNI calling convention has been used this time and so must be compiled as C++ and the -c++ commandline must be passed to SWIG. 
+JNI error checking has been omitted for clarity.
+</p>
+
+<p>
+What the typemaps do are make the named <tt>double*</tt> function parameters use our new <tt>MyDouble</tt> wrapper structure. 
+The "in" typemap takes this structure, gets the C++ pointer to it, takes the <tt>double value</tt> member variable and passes it to the C++ <tt>spam</tt> function. 
+In Java, when the function returns, we use the SWIG created <tt>getValue()</tt> function to get the output value. 
+The following Java program demonstrates this:
+</p>
+
+<div class="code"><pre>
+// File: main.java
+
+public class main {
+
+  static {
+    try {
+      System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. " + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    MyDouble out1 = new MyDouble();
+    MyDouble out2 = new MyDouble();
+    int ret = example.spam(1.2, 3.4, out1, out2);
+    System.out.println(ret + "  " + out1.getValue() + "  " + out2.getValue());
+  }
+}
+</pre></div>
+
+<p>
+When compiled and run we get:
+</p>
+
+<div class="code"><pre>
+$ java main
+1 12.0  340.0
+</pre></div>
+
+<H3><a name="adding_downcasts"></a>20.10.7 Adding Java downcasts to polymorphic return types</H3>
+
+
+<p>
+SWIG support for polymorphism works in that the appropriate virtual function is called. However, the default generated code does not allow for downcasting. 
+Let's examine this with the following code:
+</p>
+
+<div class="code"><pre>
+%include "std_string.i"
+
+#include &lt;iostream&gt;
+using namespace std;
+class Vehicle {
+public:
+    virtual void start() = 0;
+...
+};
+
+class Ambulance : public Vehicle {
+    string vol;
+public:
+    Ambulance(string volume) : vol(volume) {}
+    virtual void start() {
+        cout &lt;&lt; "Ambulance started" &lt;&lt; endl;
+    }
+    void sound_siren() {
+        cout &lt;&lt; vol &lt;&lt; " siren sounded!" &lt;&lt; endl;
+    }
+...
+};
+
+Vehicle *vehicle_factory() {
+    return new Ambulance("Very loud");
+}
+</pre></div>
+
+<p>
+If we execute the following Java code:
+</p>
+
+<div class="code"><pre>
+Vehicle vehicle = example.vehicle_factory();
+vehicle.start();
+
+Ambulance ambulance = (Ambulance)vehicle;
+ambulance.sound_siren();
+</pre></div>
+
+<p>
+We get:
+</p>
+
+<div class="code"><pre>
+Ambulance started
+java.lang.ClassCastException
+        at main.main(main.java:16)
+</pre></div>
+
+<p>
+Even though we know from examination of the C++ code that <tt>vehicle_factory</tt> returns an object of type <tt>Ambulance</tt>, 
+we are not able to use this knowledge to perform the downcast in Java.
+This occurs because the runtime type information is not completely passed from C++ to Java when returning the type from <tt>vehicle_factory()</tt>.
+Usually this is not a problem as virtual functions do work by default, such as in the case of <tt>start()</tt>. 
+There are a few solutions to getting downcasts to work.
+</p>
+
+<p>
+The first is not to use a Java cast but a call to C++ to make the cast. Add this to your code:
+</p>
+
+<div class="code"><pre>
+%exception Ambulance::dynamic_cast(Vehicle *vehicle) {
+    $action
+    if (!result) {
+        jclass excep = jenv-&gt;FindClass("java/lang/ClassCastException");
+        if (excep) {
+            jenv-&gt;ThrowNew(excep, "dynamic_cast exception");
+        }
+    }
+}
+%extend Ambulance {
+    static Ambulance *dynamic_cast(Vehicle *vehicle) {
+        return dynamic_cast&lt;Ambulance *&gt;(vehicle);
+    }
+};
+</pre></div>
+
+<p>
+It would then be used from Java like this
+</p>
+
+<div class="code"><pre>
+Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
+ambulance.sound_siren();
+</pre></div>
+
+<p>
+Should <tt>vehicle</tt> not be of type <tt>ambulance</tt> then a Java <tt>ClassCastException</tt> is thrown.
+The next solution is a purer solution in that Java downcasts can be performed on the types.
+Add the following before the definition of <tt>vehicle_factory</tt>:
+</p>
+
+<div class="code"><pre>
+%typemap(out) Vehicle * {
+    Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
+    *(Ambulance **)&amp;$result = downcast;
+}
+
+%typemap(javaout) Vehicle * {
+    return new Ambulance($jnicall, $owner);
+  }
+</pre></div>
+
+<p>
+Here we are using our knowledge that <tt>vehicle_factory</tt> always returns type <tt>Ambulance</tt> so that the Java proxy is created as a type <tt>Ambulance</tt>.
+If <tt>vehicle_factory</tt> can manufacture any type of <tt>Vehicle</tt> and we want to be able to downcast using Java casts for any of these types, then a different approach is needed.
+Consider expanding our example with a new Vehicle type and a more flexible factory function:
+</p>
+
+<div class="code"><pre>
+class FireEngine : public Vehicle {
+public:
+    FireEngine() {}
+    virtual void start() {
+        cout &lt;&lt; "FireEngine started" &lt;&lt; endl;
+    }
+    void roll_out_hose() {
+        cout &lt;&lt; "Hose rolled out" &lt;&lt; endl;
+    }
+ ...
+};
+Vehicle *vehicle_factory(int vehicle_number) {
+    if (vehicle_number == 0)
+        return new Ambulance("Very loud");
+    else
+        return new FireEngine();
+}
+</pre></div>
+
+<p>
+To be able to downcast with this sort of Java code:
+</p>
+
+<div class="code"><pre>
+FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
+fireengine.roll_out_hose();
+Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
+ambulance.sound_siren();
+</pre></div>
+
+<p>
+the following typemaps targeted at the <tt>vehicle_factory</tt> function will achieve this. 
+Note that in this case, the Java class is constructed using JNI code rather than passing a pointer across the JNI boundary in a Java long for construction in Java code.
+</p>
+
+<div class="code"><pre>
+%typemap(jni) Vehicle *vehicle_factory "jobject"
+%typemap(jtype) Vehicle *vehicle_factory "Vehicle"
+%typemap(jstype) Vehicle *vehicle_factory "Vehicle"
+%typemap(javaout) Vehicle *vehicle_factory {
+    return $jnicall;
+  }
+
+%typemap(out) Vehicle *vehicle_factory {
+    Ambulance *ambulance = dynamic_cast&lt;Ambulance *&gt;($1);
+    FireEngine *fireengine = dynamic_cast&lt;FireEngine *&gt;($1);
+    if (ambulance) {
+        // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
+        jclass clazz = jenv-&gt;FindClass("Ambulance");
+        if (clazz) {
+            jmethodID mid = jenv-&gt;GetMethodID(clazz, "&lt;init&gt;", "(JZ)V");
+            if (mid) {
+                jlong cptr = 0;
+                *(Ambulance **)&amp;cptr = ambulance; 
+                $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
+            }
+        }
+    } else if (fireengine) {
+        // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
+        jclass clazz = jenv-&gt;FindClass("FireEngine");
+        if (clazz) {
+            jmethodID mid = jenv-&gt;GetMethodID(clazz, "&lt;init&gt;", "(JZ)V");
+            if (mid) {
+                jlong cptr = 0;
+                *(FireEngine **)&amp;cptr = fireengine; 
+                $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
+            }
+        }
+    }
+    else {
+        cout &lt;&lt; "Unexpected type " &lt;&lt; endl;
+    }
+
+    if (!$result)
+        cout &lt;&lt; "Failed to create new java object" &lt;&lt; endl;
+}
+</pre></div>
+
+<p>
+Better error handling would need to be added into this code. 
+There are other solutions to this problem, but this last example demonstrates some more involved JNI code.
+SWIG usually generates code which constructs the proxy classes using Java code as it is easier to handle error conditions and is faster. 
+Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.
+</p>
+
+<H3><a name="adding_equals_method"></a>20.10.8 Adding an equals method to the Java classes</H3>
+
+
+<p>
+When a pointer is returned from a JNI function, it is wrapped using a new Java proxy class or type wrapper class. 
+Even when the pointers are the same, it will not be possible to know that the two Java classes containing those pointers are actually the same object.
+It is common in Java to use the <tt>equals()</tt> method to check whether two objects are equivalent.
+The <tt>equals()</tt> method is usually accompanied by a <tt>hashCode()</tt> method in order to fulfill
+the requirement that the hash code is equal for equal objects.
+Pure Java code methods like these can be easily added:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javacode) SWIGTYPE %{
+  public boolean equals(Object obj) {
+    boolean equal = false;
+    if (obj instanceof $javaclassname)
+      equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
+    return equal;
+  }
+  public int hashCode() {
+     return (int)getPointer();
+  }
+%}
+
+class Foo { };
+Foo* returnFoo(Foo *foo) { return foo; }
+</pre>
+</div>
+
+<p>
+The following would display <tt>false</tt> without the <tt>javacode</tt> typemap above. With the typemap defining the <tt>equals</tt> method the result is <tt>true</tt>.
+</p>
+
+<div class="code">
+<pre>
+Foo foo1 = new Foo();
+Foo foo2 = example.returnFoo(foo1);
+System.out.println("foo1? " + foo1.equals(foo2));
+</pre>
+</div>
+
+
+<H3><a name="void_pointers"></a>20.10.9 Void pointers and a common Java base class</H3>
+
+
+<p>
+One might wonder why the common code that SWIG emits for the proxy and type wrapper classes is not pushed into a base class. 
+The reason is that although <tt>swigCPtr</tt> could be put into a common base class for all classes 
+wrapping C structures, it would not work for C++ classes involved in an inheritance chain.
+Each class derived from a base needs a separate <tt>swigCPtr</tt> because C++ compilers sometimes use a different pointer value when casting a derived class to a base.
+Additionally as Java only supports single inheritance, it would not be possible to derive wrapped classes from your own pure Java classes if the base class has been 'used up' by SWIG.
+However, you may want to move some of the common code into a base class. 
+Here is an example which uses a common base class for all proxy classes and type wrapper classes:
+</p>
+
+<div class="code">
+<pre>
+%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
+                                                         SWIGTYPE (CLASS::*) "SWIG"
+
+%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
+                                                         SWIGTYPE (CLASS::*) %{
+  protected long getPointer() {
+    return swigCPtr;
+  }
+%}
+</pre>
+</div>
+
+<p>
+Define new base class called SWIG:
+</p>
+
+<div class="code">
+<pre>
+public abstract class SWIG {
+  protected abstract long getPointer();
+
+  public boolean equals(Object obj) {
+    boolean equal = false;
+    if (obj instanceof SWIG)
+      equal = (((SWIG)obj).getPointer() == this.getPointer());
+    return equal;
+  }
+  
+  SWIGTYPE_p_void getVoidPointer() {
+    return new SWIGTYPE_p_void(getPointer(), false);
+  }
+}
+</pre>
+</div>
+
+<p>
+This example contains some useful functionality which you may want in your code. 
+</p>
+
+<ul>
+    <li> It has an <tt>equals()</tt> method. Unlike the previous example, the method code isn't replicated in all classes.
+    <li> It also has a function which effectively implements a cast from the type of the proxy/type wrapper class to a void pointer. This is necessary for passing a proxy class or a type wrapper class to a function that takes a void pointer.
+</ul>
+
+<H3><a name="struct_pointer_pointer"></a>20.10.10 Struct pointer to pointer</H3>
+
+
+<p>
+Pointers to pointers are often used as output parameters in C factory type functions.
+These are a bit more tricky to handle.
+Consider the following situation where a <tt>Butler</tt> can be hired and fired:
+</p>
+
+<div class="code">
+<pre>
+typedef struct {
+  int hoursAvailable;
+  char *greeting;
+} Butler;
+
+// Note: HireButler will allocate the memory 
+// The caller must free the memory by calling FireButler()!!
+extern int HireButler(Butler **ppButler);
+extern void FireButler(Butler *pButler);
+</pre>
+</div>
+
+<p>
+C code implementation:
+</p>
+
+<div class="code">
+<pre>
+int HireButler(Butler **ppButler) {
+  Butler *pButler = (Butler *)malloc(sizeof(Butler));
+  pButler-&gt;hoursAvailable = 24;
+  pButler-&gt;greeting = (char *)malloc(32);
+  strcpy(pButler-&gt;greeting, "At your service Sir");
+  *ppButler = pButler;
+  return 1;
+}
+void FireButler(Butler *pButler) {
+  free(pButler-&gt;greeting);
+  free(pButler);
+}
+</pre>
+</div>
+
+<p>
+Let's take two approaches to wrapping this code.
+The first is to provide a functional interface, much like the original C interface.
+The following Java code shows how we intend the code to be used:
+</p>
+
+<div class="code">
+<pre>
+    Butler jeeves = new Butler();
+    example.HireButler(jeeves);
+    System.out.println("Greeting:     " + jeeves.getGreeting());
+    System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
+    example.FireButler(jeeves);
+</pre>
+</div>
+
+<p>
+Resulting in the following output when run:
+</p>
+
+<div class="shell">
+<pre>
+Greeting:     At your service Sir
+Availability: 24 hours per day
+</pre>
+</div>
+
+<p>
+Note the usage is very much like it would be used if we were writing C code, that is, explicit memory management is needed.
+No C memory is allocated in the construction of the <tt>Butler</tt> proxy class and 
+the proxy class will not destroy the underlying C memory when it is collected.
+A number of typemaps and features are needed to implement this approach. 
+The following interface file code should be placed before SWIG parses the above C code.
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+// Do not generate the default proxy constructor or destructor
+%nodefaultctor Butler;
+%nodefaultdtor Butler;
+
+// Add in pure Java code proxy constructor
+%typemap(javacode) Butler %{
+  /** This constructor creates the proxy which initially does not create nor own any C memory */
+  public Butler() {
+    this(0, false);
+  }
+%}
+
+// Type typemaps for marshalling Butler **
+%typemap(jni) Butler ** "jobject"
+%typemap(jtype) Butler ** "Butler"
+%typemap(jstype) Butler ** "Butler"
+
+// Typemaps for Butler ** as a parameter output type
+%typemap(in) Butler ** (Butler *ppButler = 0) %{
+  $1 = &amp;ppButler;
+%}
+%typemap(argout) Butler ** {
+  // Give Java proxy the C pointer (of newly created object)
+  jclass clazz = (*jenv)-&gt;FindClass(jenv, "Butler");
+  jfieldID fid = (*jenv)-&gt;GetFieldID(jenv, clazz, "swigCPtr", "J");
+  jlong cPtr = 0;
+  *(Butler **)&amp;cPtr = *$1;
+  (*jenv)-&gt;SetLongField(jenv, $input, fid, cPtr);
+}
+%typemap(javain) Butler ** "$javainput"
+</pre>
+</div>
+
+<p>
+Note that the JNI code sets the proxy's <tt>swigCPtr</tt> member variable to point to the newly created object.
+The <tt>swigCMemOwn</tt> remains unchanged (at false), so that the proxy does not own the memory.
+</p>
+
+<p>
+Note: The old %nodefault directive disabled the default constructor
+and destructor at the same time. This is unsafe in most of the cases,
+and you can use the explicit %nodefaultctor and %nodefaultdtor
+directives to achieve the same result if needed.
+</p>
+
+<p>
+The second approach offers a more object oriented interface to the Java user.
+We do this by making the Java proxy class's
+constructor call the <tt>HireButler()</tt> method to create the underlying C object.
+Additionally we get the proxy to take ownership of the memory so that the
+finalizer will call the <tt>FireButler()</tt> function.
+The proxy class will thus take ownership of the memory and clean it up when no longer needed.
+We will also prevent the user from being able to explicitly call the <tt>HireButler()</tt> and <tt>FireButler()</tt> functions.
+Usage from Java will simply be:
+</p>
+
+<div class="code">
+<pre>
+Butler jeeves = new Butler();
+System.out.println("Greeting:     " + jeeves.getGreeting());
+System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
+</pre>
+</div>
+
+<p>
+Note that the Butler class is used just like any other Java class and no extra coding by the user needs to be written to 
+clear up the underlying C memory as the finalizer will be called by the garbage collector which in turn will call the <tt>FireButler()</tt> function.
+To implement this, we use the above interface file code but remove the <tt>javacode</tt> typemap and add the following:
+</p>
+
+<div class="code">
+<pre>
+// Don't expose the memory allocation/de-allocation functions
+%ignore FireButler(Butler *pButler);
+%ignore HireButler(Butler **ppButler);
+
+// Add in a custom proxy constructor and destructor
+%extend Butler {
+  Butler() {
+    Butler *pButler = 0;
+    HireButler(&amp;pButler);
+    return pButler;
+  }
+  ~Butler() {
+     FireButler($self);
+   }
+}
+</pre>
+</div>
+
+<p>
+Note that the code in <tt>%extend</tt> is using a C++ type constructor and destructor, yet the generated code will still compile as C code,
+see <a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>.
+The C functional interface has been completely morphed into an object-oriented interface and
+the Butler class would behave much like any pure Java class and feel more natural to Java users.
+</p>
+
+<H3><a name="java_memory_management_member_variables"></a>20.10.11 Memory management when returning references to member variables</H3>
+
+
+<p>
+This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable.
+</p>
+
+<p>
+Consider the following C++ code:
+</p>
+
+<div class="code">
+<pre>
+struct Wheel {
+  int size;
+  Wheel(int sz) : size(sz) {}
+};
+
+class Bike {
+  Wheel wheel;
+public:
+  Bike(int val) : wheel(val) {}
+  Wheel&amp; getWheel() { return wheel; }
+};
+</pre>
+</div>
+
+<p>
+and the following usage from Java after running the code through SWIG:
+</p>
+
+
+<div class="code">
+<pre>
+    Wheel wheel = new Bike(10).getWheel();
+    System.out.println("wheel size: " + wheel.getSize());
+    // Simulate a garbage collection
+    System.gc();
+    System.runFinalization();
+    System.out.println("wheel size: " + wheel.getSize());
+</pre>
+</div>
+
+<p>
+Don't be surprised that if the resulting output gives strange results such as...
+</p>
+
+<div class="shell">
+<pre>
+wheel size: 10
+wheel size: 135019664
+</pre>
+</div>
+
+<p>
+What has happened here is the garbage collector has collected the <tt>Bike</tt> instance as it doesn't think it is needed any more.
+The proxy instance, <tt>wheel</tt>, contains a reference to memory that was deleted when the <tt>Bike</tt> instance was collected.
+In order to prevent the garbage collector from collecting the <tt>Bike</tt> instance a reference to the <tt>Bike</tt> must
+be added to the <tt>wheel</tt> instance. You can do this by adding the reference when the <tt>getWheel()</tt> method
+is called using the following typemaps.
+</p>
+
+
+<div class="code">
+<pre>
+%typemap(javacode) Wheel %{
+  // Ensure that the GC doesn't collect any Bike instance set from Java
+  private Bike bikeReference;
+  protected void addReference(Bike bike) {
+    bikeReference = bike;
+  }
+%}
+
+// Add a Java reference to prevent premature garbage collection and resulting use
+// of dangling C++ pointer. Intended for methods that return pointers or
+// references to a member variable.
+%typemap(javaout) Wheel&amp; getWheel {
+    long cPtr = $jnicall;
+    $javaclassname ret = null;
+    if (cPtr != 0) {
+      ret = new $javaclassname(cPtr, $owner);
+      ret.addReference(this);
+    }
+    return ret;
+  }
+</pre>
+</div>
+
+<p>
+The code in the first typemap gets added to the <tt>Wheel</tt> proxy class.
+The code in the second typemap constitutes the bulk of the code in the generated <tt>getWheel()</tt> function:
+</p>
+
+<div class="code">
+<pre>
+public class Wheel {
+  ...
+  // Ensure that the GC doesn't collect any bike set from Java 
+  private Bike bikeReference;
+  protected void addReference(Bike bike) {
+    bikeReference = bike;
+  }
+}
+
+public class Bike {
+  ...
+  public Wheel getWheel() {
+    long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
+    Wheel ret = null;
+    if (cPtr != 0) {
+      ret = new Wheel(cPtr, false);
+      ret.addReference(this);
+    }
+    return ret;
+  }
+}
+</pre>
+</div>
+
+<p>
+Note the <tt>addReference</tt> call.
+</p>
+
+<H3><a name="java_memory_management_objects"></a>20.10.12 Memory management for objects passed to the C++ layer</H3>
+
+
+<p>
+Managing memory can be tricky when using C++ and Java proxy classes.
+The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope
+after the function has returned. Consider the following two C++ classes:
+</p>
+
+<div class="code">
+<pre>
+struct Element {
+  int value;
+  Element(int val) : value(val) {}
+};
+class Container {
+  Element* element;
+public:
+  Container() : element(0) {}
+  void setElement(Element* e) { element = e; }
+  Element* getElement() { return element; }
+};
+</pre>
+</div>
+
+<p>
+and usage from C++
+</p>
+
+<div class="code">
+<pre>
+    Container container;
+    Element element(20);
+    container.setElement(&amp;element);
+    cout &lt;&lt; "element.value: " &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
+</pre>
+</div>
+
+<p>
+and more or less equivalent usage from Java
+</p>
+
+<div class="code">
+<pre>
+    Container container = new Container();
+    container.setElement(new Element(20));
+    System.out.println("element value: " + container.getElement().getValue());
+</pre>
+</div>
+
+<p>
+The C++ code will always print out 20, but the value printed out may not be this in the Java equivalent code.
+In order to understand why, consider a garbage collection occuring...
+</p>
+
+<div class="code">
+<pre>
+    Container container = new Container();
+    container.setElement(new Element(20));
+    // Simulate a garbage collection
+    System.gc();
+    System.runFinalization();
+    System.out.println("element value: " + container.getElement().getValue());
+</pre>
+</div>
+
+<p>
+The temporary element created with <tt>new Element(20)</tt> could get garbage collected
+which ultimately means the <tt>container</tt> variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20.
+One solution is to add in the appropriate references in the Java layer...
+</p>
+
+<div class="code">
+<pre>
+public class Container {
+
+  ...
+
+  // Ensure that the GC doesn't collect any Element set from Java
+  // as the underlying C++ class stores a shallow copy
+  private Element elementReference;
+  private long getCPtrAndAddReference(Element element) {
+    elementReference = element;
+    return Element.getCPtr(element);
+  }
+
+  public void setElement(Element e) {
+    exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e);
+  }
+}
+</pre>
+</div>
+
+<p>
+The following typemaps will generate the desired code.
+The 'javain' typemap matches the input parameter type for the <tt>setElement</tt> method.
+The 'javacode' typemap simply adds in the specified code into the Java proxy class.
+</p>
+
+<div class="code">
+<pre>
+%typemap(javain) Element *e "getCPtrAndAddReference($javainput)"
+
+%typemap(javacode) Container %{
+  // Ensure that the GC doesn't collect any element set from Java
+  // as the underlying C++ class stores a shallow copy
+  private Element elementReference;
+  private long getCPtrAndAddReference(Element element) {
+    elementReference = element;
+    return Element.getCPtr(element);
+  }
+%}
+</pre>
+</div>
+
+
+<H3><a name="java_date_marshalling"></a>20.10.13 Date marshalling using the javain typemap and associated attributes</H3>
+
+
+<p>
+The <a href="#nan_exception_typemap">NaN Exception example</a> is a simple example of the "javain" typemap and its 'pre' attribute.
+This example demonstrates how a C++ date class, say <tt>CDate</tt>, can be mapped onto the standard Java date class,
+<tt>java.util.GregorianCalendar</tt> by using the 'pre', 'post' and 'pgcppname' attributes of the "javain" typemap.
+The idea is that the <tt>GregorianCalendar</tt> is used wherever the C++ API uses a <tt>CDate</tt>.
+Let's assume the code being wrapped is as follows:
+</p>
+
+<div class="code">
+<pre>
+class CDate {
+public:
+  CDate(int year, int month, int day);
+  int getYear();
+  int getMonth();
+  int getDay();
+  ...
+};
+struct Action {
+  static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
+  Action(const CDate &amp;date, CDate &amp;dateOut);
+};
+</pre>
+</div>
+
+<p>
+Note that <tt>dateIn</tt> is const and therefore read only and <tt>dateOut</tt> is a non-const output type.
+</p>
+
+<p>
+First let's look at the code that is generated by default, where the Java proxy class <tt>CDate</tt> is used in the proxy interface:
+</p>
+
+<div class="code">
+<pre>
+public class Action {
+  ...
+  public static int doSomething(CDate dateIn, CDate dateOut) {
+    return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, 
+                                         CDate.getCPtr(dateOut), dateOut);
+  }
+
+  public Action(CDate date, CDate dateOut) {
+    this(exampleJNI.new_Action(CDate.getCPtr(date), date, 
+                               CDate.getCPtr(dateOut), dateOut), true);
+  }
+}
+</pre>
+</div>
+
+<p>
+The <tt>CDate &amp;</tt> and <tt>const CDate &amp;</tt> Java code is generated from the following two default typemaps:
+</p>
+
+<div class="code">
+<pre>
+%typemap(jstype) SWIGTYPE &amp; "$javaclassname"
+%typemap(javain) SWIGTYPE &amp; "$javaclassname.getCPtr($javainput)"
+</pre>
+</div>
+
+<p>
+where '$javaclassname' is translated into the proxy class name, <tt>CDate</tt> and '$javainput' is translated into the name of the parameter, eg <tt>dateIn</tt>.
+From Java, the intention is then to call into a modifed API with something like:
+</p>
+
+<div class="code">
+<pre>
+java.util.GregorianCalendar calendarIn = 
+    new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0);
+java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar();
+
+// Note in calls below, calendarIn remains unchanged and calendarOut 
+// is set to a new value by the C++ call
+Action.doSomething(calendarIn, calendarOut);
+Action action = new Action(calendarIn, calendarOut);
+</pre>
+</div>
+
+<p>
+To achieve this mapping, we need to alter the default code generation slightly so that at the Java layer, 
+a <tt>GregorianCalendar</tt> is converted into a <tt>CDate</tt>. 
+The JNI intermediary layer will still take a pointer to the underlying <tt>CDate</tt> class.
+The typemaps to achieve this are shown below.
+</p>
+
+<div class="code">
+<pre>
+%typemap(jstype) const CDate&amp; "java.util.GregorianCalendar"
+%typemap(javain, 
+         pre="    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
+             "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", 
+         pgcppname="temp$javainput") const CDate &amp;
+         "$javaclassname.getCPtr(temp$javainput)"
+
+%typemap(jstype) CDate&amp; "java.util.Calendar"
+%typemap(javain, 
+         pre="    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
+             "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", 
+         post="      $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), "
+              "temp$javainput.getDay(), 0, 0, 0);", 
+         pgcppname="temp$javainput") CDate &amp;
+         "$javaclassname.getCPtr(temp$javainput)"
+</pre>
+</div>
+
+<p>
+The resulting generated proxy code in the <tt>Action</tt> class follows:
+ </p>
+
+<div class="code">
+<pre>
+public class Action {
+  ...
+  public static int doSomething(java.util.GregorianCalendar dateIn, 
+                                java.util.Calendar dateOut) {
+    CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), 
+                                 dateIn.get(java.util.Calendar.MONTH), 
+                                 dateIn.get(java.util.Calendar.DATE));
+    CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
+                                  dateOut.get(java.util.Calendar.MONTH), 
+                                  dateOut.get(java.util.Calendar.DATE));
+    try {
+      return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, 
+                                           CDate.getCPtr(tempdateOut), tempdateOut);
+    } finally {
+      dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
+    }
+  }
+
+  static private long SwigConstructAction(java.util.GregorianCalendar date, 
+                                          java.util.Calendar dateOut) {
+    CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), 
+                               date.get(java.util.Calendar.MONTH), 
+                               date.get(java.util.Calendar.DATE));
+    CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
+                                  dateOut.get(java.util.Calendar.MONTH), 
+                                  dateOut.get(java.util.Calendar.DATE));
+    try {
+      return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, 
+                                   CDate.getCPtr(tempdateOut), tempdateOut);
+    } finally {
+      dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
+    }
+  }
+
+  public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
+    this(Action.SwigConstructAction(date, dateOut), true);
+  }
+}
+</pre>
+</div>
+
+<p>
+A few things to note:
+</p>
+<ul>
+  <li> The "javatype" typemap has changed the parameter type to <tt>java.util.GregorianCalendar</tt> or <tt>java.util.Calendar</tt> instead of the default generated <tt>CDate</tt> proxy.
+  <li> The code in the 'pre' attribute appears before the JNI call (<tt>exampleJNI.new_Action</tt> / <tt>exampleJNI.Action_doSomething</tt>).
+  <li> The code in the 'post' attribute appears after the JNI call.
+  <li> A try .. finally block is generated with the JNI call in the try block and 'post' code in the finally block.
+  The alternative of just using a temporary variable for the return value from the JNI call and the 'post' code being generated before the
+  return statement is not possible given that the JNI call is in one line and comes from the "javaout" typemap.
+  <li> The temporary variables in the "javain" typemaps are called <tt>temp$javain</tt>, where "$javain" is replaced with the parameter name.
+  "$javain" is used to mangle the variable name so that more than one <tt>CDate &amp;</tt> type can be used as a parameter in a method, otherwise two or 
+  more local variables with the same name would be generated.
+  <li> The use of the "javain" typemap causes a constructor helper function (<tt>SwigConstructAction</tt>) to be generated.
+  This allows Java code to be called before the JNI call and is required as the Java compiler won't compile code inserted before the 'this' call.
+  <li> The 'pgcppname' attribute is used to modify the object being passed as the <a href="#java_pgcpp">premature garbage collection prevention parameter</a> (the 2nd and 4th parameters in the JNI calls).
+</ul>
+
+
+
+
+<H2><a name="java_directors_faq"></a>20.11 Living with Java Directors</H2>
+
+
+<p>
+  This section is intended to address frequently asked questions and frequently encountered problems when using Java directors.
+</p>
+
+<ol>
+  <li><i>When my program starts up, it complains that </i>method_foo<i> cannot
+  be found in a Java method called </i>swig_module_init<i>. How do I fix
+  this?</i>
+
+  <p>
+  Open up the C++ wrapper source code file and look for <code>"method_foo"</code> (include the double quotes, they are important!)
+  Look at the JNI field descriptor and make sure that each class that occurs in the descriptor has the correct package name in front of it.
+  If the package name is incorrect, put a "javapackage" typemap in your SWIG interface file.
+  </p>
+  </li>
+
+  <li><i>I'm compiling my code and I'm using templates. I provided a
+  javapackage typemap, but SWIG doesn't generate the right JNI field
+  descriptor.</i>
+  <p>
+  Use the template's renamed name as the argument to the "javapackage" typemap:
+  </p>
+<div class="code">
+<pre>
+%typemap(javapackage)  std::vector&lt;int&gt;  "your.package.here"
+%template(VectorOfInt) std::vector&lt;int&gt;;
+</pre>
+</div>
+  </li>
+
+  <li><p><i>When I pass class pointers or references through a C++ upcall and I
+  try to type cast them, Java complains with a ClassCastException. What am I
+  doing wrong?</i></p>
+  <p>
+  Normally, a non-director generated Java proxy class creates temporary Java objects as follows:
+  </p>
+<div class="code">
+<pre>
+public static void MyClass_method_upcall(MyClass self, long jarg1)
+{
+  Foo darg1 = new Foo(jarg1, false);
+
+  self.method_upcall(darg1);
+}
+</pre>
+</div>
+  <p>Unfortunately, this loses the Java type information that is part of the underlying Foo director proxy class's Java object pointer causing the type cast to fail.
+  The SWIG Java module's director code attempts to correct the problem, <b>but only for director-enabled classes</b>, since the director class retains a global reference to its Java object.
+  Thus, for director-enabled classes <b>and only for director-enabled classes</b>, the generated proxy Java code looks something like:
+  </p>
+
+<div class="code">
+<pre>
+public static void MyClass_method_upcall(MyClass self, long jarg1,
+                                         Foo jarg1_object)
+{
+  Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));
+
+  self.method_upcall(darg1);
+}
+</pre>
+</div>
+
+  <p>
+  When you import a SWIG interface file containing class definitions, the classes you want to be director-enabled must be have the <code>feature("director")</code> enabled for type symmetry to work.
+  This applies even when the class being wrapped isn't a director-enabled class but takes parameters that are director-enabled classes.
+  </p>
+
+  <p>
+  The current "type symmetry" design will work for simple C++ inheritance, but will most likely fail for anything more complicated such as tree or diamond C++ inheritance hierarchies.
+  Those who are interested in challenging problems are more than welcome to hack the <code>Java::Java_director_declaration</code> method in <code>Source/Modules/java.cxx</code>.
+  </p>
+  <p>
+  If all else fails, you can use the downcastXXXXX() method to attempt to recover the director class's Java object pointer.
+  For the Java Foo proxy class, the Foo director class's java object pointer can be accessed through the javaObjectFoo() method.
+  The generated method's signature is:
+  </p>
+
+<div class="code">
+<pre>
+  public static Foo javaObjectFoo(Foo obj);
+</pre>
+</div>
+
+<p>
+  From your code, this method is invoked as follows:
+</p>
+
+<div class="code">
+<pre>
+public class MyClassDerived {
+  public void method_upcall(Foo foo_object)
+  {
+    FooDerived    derived = (foo_object != null ?
+                 (FooDerived) Foo.downcastFoo(foo_object) : null);
+    /* rest of your code here */
+  }
+}
+</pre>
+</div>
+
+<p>
+  An good approach for managing downcasting is placing a static method in each derived class that performs the downcast from the superclass, e.g.,
+</p>
+
+<div class="code">
+<pre>
+public class FooDerived extends Foo {
+  /* ... */
+  public static FooDerived downcastFooDerived(Foo foo_object)
+  {
+    try {
+     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
+    }
+
+    catch (ClassCastException exc) {
+      // Wasn't a FooDerived object, some other subclass of Foo
+      return null;
+    }
+  }
+}
+</pre>
+</div>
+
+<p>
+  Then change the code in MyClassDerived as follows:
+</p>
+
+<div class="code">
+<pre>
+public class MyClassDerived extends MyClass {
+  /* ... */
+  public void method_upcall(Foo foo_object)
+  {
+    FooDerived    derived = FooDerived.downcastFooDerived(foo_object);
+    /* rest of your code here */
+  }
+}
+</pre>
+</div>
+  </li>
+
+  <li><p><i>Why isn't the proxy class declared abstract? Why aren't the director
+  upcall methods in the proxy class declared abstract?</i></p>
+
+  <p>
+  Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.)
+  Create an abstract Java subclass that inherits from the director-enabled class instead.
+  Using the previous Foo class example:
+  </p>
+
+<div class="code">
+<pre>
+public abstract class UserVisibleFoo extends Foo {
+  /** Make sure user overrides this method, it's where the upcall
+   * happens.
+   */
+  public abstract void method_upcall(Foo foo_object);
+
+  /// Downcast from Foo to UserVisibleFoo
+  public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
+  {
+    try {
+     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
+    }
+
+    catch (ClassCastException exc) {
+      // Wasn't a FooDerived object, some other subclass of Foo
+      return null;
+    }
+  }
+}
+</pre>
+</div>
+  <p>This doesn't prevent the user from creating subclasses derived from Foo, however, UserVisibleFoo provides the safety net that reminds the user to override the <code>method_upcall()</code> method.</p>
+  </li>
+</ol>
+
+<H2><a name="odds_ends"></a>20.12 Odds and ends</H2>
+
+
+<H3><a name="javadoc_comments"></a>20.12.1 JavaDoc comments</H3>
+
+
+<p>
+The SWIG documentation system is currently deprecated. 
+When it is resurrected JavaDoc comments will be fully supported. 
+If you can't wait for the full documentation system a couple of workarounds are available. 
+The <tt>%javamethodmodifiers</tt> feature can be used for adding proxy class method comments and module class method comments. 
+The "javaimports" typemap can be hijacked for adding in proxy class JavaDoc comments. 
+The <tt>jniclassimports</tt> or <tt>jniclassclassmodifiers</tt> pragmas can also be used for adding intermediary JNI class comments and likewise the <tt>moduleimports</tt> or <tt>moduleclassmodifiers</tt> pragmas for the module class. 
+Here is an example adding in a proxy class and method comment:
+</p>
+
+<div class="code">
+<pre>
+%javamethodmodifiers Barmy::lose_marbles() "
+  /**
+    * Calling this method will make you mad.
+    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
+    */
+  public";
+
+%typemap(javaimports) Barmy "
+/** The crazy class. Use as a last resort. */"
+
+class Barmy {
+public:
+  void lose_marbles() {}
+};
+</pre>
+</div>
+
+<p>
+Note the "public" added at the end of the <tt>%javamethodmodifiers</tt> as this is the default for this feature. 
+The generated proxy class with JavaDoc comments is then as follows:
+</p>
+
+<div class="code">
+<pre>
+/** The crazy class. Use as a last resort. */
+public class Barmy {
+...
+  /**
+    * Calling this method will make you mad.
+    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
+    */
+  public void lose_marbles() {
+    ...
+  }
+...
+}
+</pre>
+</div>
+
+
+
+<H3><a name="functional_interface"></a>20.12.2 Functional interface without proxy classes</H3>
+
+
+<p>
+It is possible to run SWIG in a mode that does not produce proxy classes by using the -noproxy commandline option.
+The interface is rather primitive when wrapping structures or classes and is accessed through function calls to the module class.
+All the functions in the module class are wrapped by functions with identical names as those in the intermediary JNI class.
+</p>
+
+<p>
+Consider the example we looked at when examining proxy classes:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int spam(int num, Foo* foo);
+};
+</pre>
+</div>
+
+<p>
+When using <tt>-noproxy</tt>, type wrapper classes are generated instead of proxy classes.
+Access to all the functions and variables is through a C like set of functions where the first parameter passed is the pointer to the class, that is an instance of a type wrapper class.
+Here is what the module class looks like:
+</p>
+
+<div class="code">
+<pre>
+public class example {
+  public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...}
+  public static int Foo_x_get(SWIGTYPE_p_Foo self) {...}
+  public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
+  public static SWIGTYPE_p_Foo new_Foo() {...}
+  public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
+}
+</pre>
+</div>
+
+<p>
+This approach is not nearly as natural as using proxy classes as the functions need to be used like this:
+</p>
+
+<div class="code">
+<pre>
+SWIGTYPE_p_Foo foo = example.new_Foo();
+example.Foo_x_set(foo, 10);
+int var = example.Foo_x_get(foo);
+example.Foo_spam(foo, 20, foo);
+example.delete_Foo(foo);
+</pre>
+</div>
+
+<p>
+Unlike proxy classes, there is no attempt at tracking memory.
+All destructors have to be called manually for example the <tt>delete_Foo(foo)</tt> call above.
+</p>
+
+
+<H3><a name="using_own_jni_functions"></a>20.12.3 Using your own JNI functions</H3>
+
+
+<p>
+You may have some hand written JNI functions that you want to use in addition to the SWIG generated JNI functions.
+Adding these to your SWIG generated package is possible using the <tt>%native</tt> directive.
+If you don't want SWIG to wrap your JNI function then of course you can simply use the <tt>%ignore</tt> directive.
+However, if you want SWIG to generate just the Java code for a JNI function then use the <tt>%native</tt> directive.
+The C types for the parameters and return type must be specified in place of the JNI types and the function name must be the native method name.
+For example:
+</p>
+
+<div class="code"><pre>
+%native (HandRolled) void HandRolled(int, char *);
+%{
+JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
+                                                              jlong, jstring);
+%}
+</pre></div>
+
+<p>
+No C JNI function will be generated and the <tt>Java_packageName_moduleName_HandRolled</tt> function will be accessible using the SWIG generated Java native method call in the intermediary JNI class which will look like this:
+</p>
+
+<div class="code"><pre>
+  public final static native void HandRolled(int jarg1, String jarg2);
+</pre></div>
+
+<p>
+and as usual this function is wrapped by another which for a global C function would appear in the module class:
+</p>
+
+<div class="code"><pre>
+  public static void HandRolled(int arg0, String arg1) {
+    exampleJNI.HandRolled(arg0, arg1);
+  }
+</pre></div>
+
+<p>
+The <tt>packageName</tt> and <tt>moduleName</tt> must of course be correct else you will get linker errors when the JVM dynamically loads the JNI function.
+You may have to add in some "jtype", "jstype", "javain" and "javaout" typemaps when wrapping some JNI types.
+Here the default typemaps work for <tt>int</tt> and <tt>char *</tt>.
+</p>
+
+<p>
+In summary the <tt>%native</tt> directive is telling SWIG to generate the Java code to access the JNI C code, but not the JNI C function itself.
+This directive is only really useful if you want to mix your own hand crafted JNI code and the SWIG generated code into one Java class or package.
+</p>
+
+
+<H3><a name="performance"></a>20.12.4 Performance concerns and hints</H3>
+
+
+<p>
+If you're directly manipulating huge arrays of complex objects from Java, performance may suffer greatly when using the array functions in <tt>arrays_java.i</tt>.
+Try and minimise the expensive JNI calls to C/C++ functions, perhaps by using temporary Java variables instead of accessing the information directly from the C/C++ object.
+</p>
+
+<p>
+Java classes without any finalizers generally speed up code execution as there is less for the garbage collector to do. Finalizer generation can be stopped by using an empty <tt>javafinalize</tt> typemap: 
+</p>
+
+<div class="code"><pre>
+%typemap(javafinalize) SWIGTYPE ""
+</pre></div>
+
+<p>
+However, you will have to be careful about memory management and make sure that you code in a call to the <tt>delete()</tt> member function. 
+This method normally calls the C++ destructor or <tt>free()</tt> for C code.
+</p>
+
+<H3><a name="java_debugging"></a>20.12.5 Debugging</H3>
+
+
+<p>
+The generated code can be debugged using both a Java debugger and a C++ debugger using the usual debugging techniques.
+Breakpoints can be set in either Java or C++ code and so both can be debugged simultaneously.
+Most debuggers do not understand both Java and C++, with one noteable exception of Sun Studio, 
+where it is possible to step from Java code into a JNI method within one environment.
+</p>
+
+<p>
+Alternatively, debugging can involve placing debug printout statements in the JNI layer using the <tt>%exception</tt> directive.
+See the <a href="Customization.html#Customization_exception_special_variables">special variables for %exception</a> section.
+Many of the default typemaps can also be overidden and modified for adding in extra logging/debug display information.
+</p>
+
+<p>
+The <tt>-Xcheck:jni</tt> and <tt>-Xcheck:nabounds</tt> Java executable options are useful for debugging to make sure the JNI code is behaving.
+The -verbose:jni and -verbose:gc are also useful options for monitoring code behaviour.
+</p>
+
+
+<H2><a name="java_examples"></a>20.13 Examples</H2>
+
+
+<p>
+The directory Examples/java has a number of further examples. 
+Take a look at these if you want to see some of the techniques described in action.
+The Examples/index.html file in the parent directory contains the SWIG Examples Documentation and is a useful starting point. 
+If your SWIG installation went well Unix users should be able to type <tt>make</tt> in each example directory, then <tt>java main</tt> to see them running.
+For the benefit of Windows users, there are also Visual C++ project files in a couple of the <a href="Windows.html#Windows_examples">Windows Examples</a>.
+There are also many regression tests in the Examples/test-suite directory.
+Many of these have runtime tests in the java subdirectory.
+</p>
+
+</body>
+</html>
+
diff --git a/trunk/Doc/Manual/Library.html b/trunk/Doc/Manual/Library.html
new file mode 100644
index 0000000..586e1ec
--- /dev/null
+++ b/trunk/Doc/Manual/Library.html
@@ -0,0 +1,1779 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG Library</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Library"></a>8 SWIG library</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Library_nn2">The %include directive and library search path</a>
+<li><a href="#Library_nn3">C Arrays and Pointers</a>
+<ul>
+<li><a href="#Library_nn4">cpointer.i</a>
+<li><a href="#Library_nn5">carrays.i</a>
+<li><a href="#Library_nn6">cmalloc.i</a>
+<li><a href="#Library_nn7">cdata.i</a>
+</ul>
+<li><a href="#Library_nn8">C String Handling</a>
+<ul>
+<li><a href="#Library_nn9">Default string handling</a>
+<li><a href="#Library_nn10">Passing binary data</a>
+<li><a href="#Library_nn11">Using %newobject to release memory</a>
+<li><a href="#Library_nn12">cstring.i</a>
+</ul>
+<li><a href="#Library_stl_cpp_library">STL/C++ Library</a>
+<ul>
+<li><a href="#Library_nn14">std_string.i</a>
+<li><a href="#Library_nn15">std_vector.i</a>
+<li><a href="#Library_stl_exceptions">STL exceptions</a>
+</ul>
+<li><a href="#Library_nn16">Utility Libraries</a>
+<ul>
+<li><a href="#Library_nn17">exception.i</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+To help build extension modules, SWIG is packaged with a library of
+support files that you can include in your own interfaces.  These
+files often define new SWIG directives or provide utility
+functions that can be used to access parts of the standard C and C++ libraries.
+This chapter provides a reference to the current set of supported library files.
+</p>
+
+<p>
+<b>Compatibility note:</b> Older versions of SWIG included a number of
+library files for manipulating pointers, arrays, and other structures.  Most
+these files are now deprecated and have been removed from the distribution.
+Alternative libraries provide similar functionality.  Please read this chapter
+carefully if you used the old libraries.
+</p>
+
+<H2><a name="Library_nn2"></a>8.1 The %include directive and library search path</H2>
+
+
+<p>
+Library files are included using the <tt>%include</tt> directive.
+When searching for files, directories are searched in the following order:
+</p>
+
+<ul>
+<li>The current directory
+<li>Directories specified with the <tt>-I</tt> command line option
+<li>.<tt>/swig_lib</tt>
+<li>SWIG library install location as reported by <tt>swig -swiglib</tt>, for example <tt>/usr/local/share/swig/1.3.30</tt>
+<li>On Windows, a directory <tt>Lib</tt> relative to the location of <tt>swig.exe</tt> is also searched.
+</ul>
+
+<p>
+Within each directory, SWIG first looks for a subdirectory corresponding to a target language (e.g., <tt>python</tt>,
+<tt>tcl</tt>, etc.).   If found, SWIG will search the language specific directory first.  This allows
+for language-specific implementations of library files.
+</p>
+
+<p>
+You can ignore the installed SWIG library by setting the <tt>SWIG_LIB</tt> environment variable.
+Set the environment variable to hold an alternative library directory.
+</p>
+
+<p>
+The directories that are searched are displayed when using <tt>-verbose</tt> commandline option.
+</p>
+
+<H2><a name="Library_nn3"></a>8.2 C Arrays and Pointers</H2>
+
+
+<p>
+This section describes library modules for manipulating low-level C arrays and pointers.
+The primary use of these modules is in supporting C declarations that manipulate bare
+pointers such as <tt>int *</tt>, <tt>double *</tt>, or <tt>void *</tt>.  The modules can be
+used to allocate memory, manufacture pointers, dereference memory, and wrap
+pointers as class-like objects.   Since these functions provide direct access to
+memory, their use is potentially unsafe and you should exercise caution.
+</p>
+
+<H3><a name="Library_nn4"></a>8.2.1 cpointer.i</H3>
+
+
+<p>
+The <tt>cpointer.i</tt> module defines macros that can be used to used
+to generate wrappers around simple C pointers.  The primary use of
+this module is in generating pointers to primitive datatypes such as
+<tt>int</tt> and <tt>double</tt>.
+</p>
+
+<p>
+<b><tt>%pointer_functions(type,name)</tt></b>
+</p>
+
+<div class="indent">
+<p>Generates a collection of four functions for manipulating a pointer <tt>type *</tt>:</p>
+
+<p>
+<tt>type *new_name()</tt>
+</p>
+
+<div class="indent"><p>
+Creates a new object of type <tt>type</tt> and returns a pointer to it.  In C, the
+object is created using <tt>calloc()</tt>. In C++, <tt>new</tt> is used.
+</p></div>
+
+<p>
+<tt>type *copy_name(type value)</tt>
+</p>
+
+<div class="indent"><p>
+Creates a new object of type <tt>type</tt> and returns a pointer to it.
+An initial value is set by copying it from <tt>value</tt>. In C, the
+object is created using <tt>calloc()</tt>. In C++, <tt>new</tt> is used.
+</p></div>
+
+<p>
+<tt>type *delete_name(type *obj)</tt>
+</p>
+
+<div class="indent"><p>
+Deletes an object type <tt>type</tt>.
+</p></div>
+
+<p>
+<tt>void name_assign(type *obj, type value)</tt>
+</p>
+
+<div class="indent"><p>
+Assigns <tt>*obj = value</tt>.
+</p></div>
+
+<p>
+<tt>type name_value(type *obj)</tt>
+</p>
+
+<div class="indent"><p>
+Returns the value of <tt>*obj</tt>.
+</p></div>
+
+<p>
+When using this macro, <tt>type</tt> may be any type and <tt>name</tt> must be a legal identifier in the target
+language.  <tt>name</tt> should not correspond to any other name used in the interface file.
+</p>
+
+
+<p>
+Here is a simple example of using <tt>%pointer_functions()</tt>:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "cpointer.i"
+
+/* Create some functions for working with "int *" */
+%pointer_functions(int, intp);
+
+/* A function that uses an "int *" */
+void add(int x, int y, int *result);
+</pre>
+</div>
+
+<p>
+Now, in Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; c = example.new_intp()     # Create an "int" for storing result
+&gt;&gt;&gt; example.add(3,4,c)         # Call function
+&gt;&gt;&gt; example.intp_value(c)      # Dereference
+7
+&gt;&gt;&gt; example.delete_intp(c)     # Delete
+</pre>
+</div>
+
+</div>
+
+<p>
+<b><tt>%pointer_class(type,name)</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Wraps a pointer of <tt>type *</tt> inside a class-based interface.  This
+interface is as follows:
+</p>
+
+<div class="code">
+<pre>
+struct name {
+   name();                            // Create pointer object
+  ~name();                            // Delete pointer object
+   void assign(type value);           // Assign value
+   type value();                      // Get value
+   type *cast();                      // Cast the pointer to original type
+   static name *frompointer(type *);  // Create class wrapper from existing
+                                      // pointer
+};
+</pre>
+</div>
+
+<p>
+When using this macro, <tt>type</tt> is restricted to a simple type
+name like <tt>int</tt>, <tt>float</tt>, or <tt>Foo</tt>.  Pointers and
+other complicated types are not allowed.  <tt>name</tt> must be a
+valid identifier not already in use.  When a pointer is wrapped as a class,
+the "class"  may be transparently passed to any function that expects the pointer.
+</p>
+
+<p>
+If the target language does not support proxy classes, the use of this macro will produce the example
+same functions as <tt>%pointer_functions()</tt> macro.
+</p>
+
+
+<p>
+It should be noted that the class interface does introduce a new object or wrap a pointer inside a special
+structure.  Instead, the raw pointer is used directly.
+</p>
+
+
+
+<p>
+Here is the same example using a class instead:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "cpointer.i"
+
+/* Wrap a class interface around an "int *" */
+%pointer_class(int, intp);
+
+/* A function that uses an "int *" */
+void add(int x, int y, int *result);
+</pre>
+</div>
+
+<p>
+Now, in Python (using proxy classes)
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; c = example.intp()         # Create an "int" for storing result
+&gt;&gt;&gt; example.add(3,4,c)         # Call function
+&gt;&gt;&gt; c.value()                  # Dereference
+7
+</pre>
+</div>
+
+<p>
+Of the two macros, <tt>%pointer_class</tt> is probably the most convenient when working with simple
+pointers.  This is because the pointers are access like objects and they can be easily garbage collected
+(destruction of the pointer object destroys the underlying object).
+</p>
+
+</div>
+
+<p>
+<b><tt>%pointer_cast(type1, type2, name)</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Creates a casting function that converts <tt>type1</tt> to <tt>type2</tt>.  The name of the function is <tt>name</tt>.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%pointer_cast(int *, unsigned int *, int_to_uint);
+</pre>
+</div>
+
+<p>
+In this example,  the function <tt>int_to_uint()</tt> would be used to cast types in the target language.
+</p>
+
+</div>
+
+<p>
+<b>Note:</b> None of these macros can be used to safely work with strings (<tt>char *</tt> or <tt>char **</tt>).
+</p>
+
+<P>
+<b>Note:</b> When working with simple pointers, typemaps can often be used to provide more seamless operation.
+</p>
+
+<H3><a name="Library_nn5"></a>8.2.2 carrays.i</H3>
+
+
+<p>
+This module defines macros that assist in wrapping ordinary C pointers as arrays.
+The module does not provide any safety or an extra layer of wrapping--it merely
+provides functionality for creating, destroying, and modifying the contents of
+raw C array data.
+</p>
+
+<p>
+<b><tt>%array_functions(type,name)</tt></b>
+</p>
+
+<div class="indent">
+<p>Creates four functions.</p>
+
+<p>
+<tt>type *new_name(int nelements)</tt>
+</p>
+
+<div class="indent"><p>
+Creates a new array of objects of type <tt>type</tt>.   In C, the array is allocated using
+<tt>calloc()</tt>.  In C++, <tt>new []</tt> is used.
+</p></div>
+
+<p>
+<tt>type *delete_name(type *ary)</tt>
+</p>
+
+<div class="indent"><p>
+Deletes an array. In C, <tt>free()</tt> is used.  In C++, <tt>delete []</tt> is used.
+</p></div>
+
+<p>
+<tt>type name_getitem(type *ary, int index)</tt>
+</p>
+
+<div class="indent"><p>
+Returns the value <tt>ary[index]</tt>.
+</p></div>
+
+<p>
+<tt>void name_setitem(type *ary, int index, type value)</tt>
+</p>
+
+<div class="indent"><p>
+Assigns <tt>ary[index] = value</tt>.
+</p></div>
+
+<p>
+When using this macro, <tt>type</tt> may be any type and <tt>name</tt>
+must be a legal identifier in the target language.  <tt>name</tt>
+should not correspond to any other name used in the interface file.
+</p>
+
+<p>
+Here is an example of <tt>%array_functions()</tt>.  Suppose you had a
+function like this:
+</p>
+
+<div class="code">
+<pre>
+void print_array(double x[10]) {
+   int i;
+   for (i = 0; i &lt; 10; i++) {
+      printf("[%d] = %g\n", i, x[i]);
+   }
+}
+</pre>
+</div>
+
+<p>
+To wrap it, you might write this:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+%include "carrays.i"
+%array_functions(double, doubleArray);
+
+void print_array(double x[10]);
+</pre>
+</div>
+
+<p>
+Now, in a scripting language, you might write this:
+</p>
+
+<div class="code">
+<pre>
+a = new_doubleArray(10)           # Create an array
+for i in range(0,10):
+    doubleArray_setitem(a,i,2*i)  # Set a value
+print_array(a)                    # Pass to C
+delete_doubleArray(a)             # Destroy array
+</pre>
+</div>
+
+</div>
+
+<b><tt>%array_class(type,name)</tt></b>
+<div class="indent">
+
+<p>
+Wraps a pointer of <tt>type *</tt> inside a class-based interface.  This
+interface is as follows:
+</p>
+
+<div class="code">
+<pre>
+struct name {
+   name(int nelements);                  // Create an array
+  ~name();                               // Delete array
+   type getitem(int index);              // Return item
+   void setitem(int index, type value);  // Set item
+   type *cast();                         // Cast to original type
+   static name *frompointer(type *);     // Create class wrapper from
+                                         // existing pointer
+};
+</pre>
+</div>
+
+<p>
+When using this macro, <tt>type</tt> is restricted to a simple type
+name like <tt>int</tt> or <tt>float</tt>. Pointers and
+other complicated types are not allowed.  <tt>name</tt> must be a
+valid identifier not already in use.  When a pointer is wrapped as a class,
+it can be transparently passed to any function that expects the pointer.
+</p>
+
+
+<p>
+When combined with proxy classes, the <tt>%array_class()</tt> macro can be especially useful.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "carrays.i"
+%array_class(double, doubleArray);
+
+void print_array(double x[10]);
+</pre>
+</div>
+
+<p>
+Allows you to do this:
+</p>
+
+<div class="code">
+<pre>
+import example
+c = example.doubleArray(10)  # Create double[10]
+for i in range(0,10):
+    c[i] = 2*i               # Assign values
+example.print_array(c)       # Pass to C
+</pre>
+</div>
+
+</div>
+
+<p>
+<b>Note:</b> These macros do not encapsulate C arrays inside a special data structure
+or proxy. There is no bounds checking or safety of any kind.   If you want this,
+you should consider using a special array object rather than a bare pointer.
+</p>
+
+<p>
+<b>Note:</b> <tt>%array_functions()</tt> and <tt>%array_class()</tt> should not be
+used with types of <tt>char</tt> or <tt>char *</tt>.
+</p>
+
+<H3><a name="Library_nn6"></a>8.2.3 cmalloc.i</H3>
+
+
+<p>
+This module defines macros for wrapping the low-level C memory allocation functions
+<tt>malloc()</tt>, <tt>calloc()</tt>, <tt>realloc()</tt>, and <tt>free()</tt>.
+</p>
+
+<p>
+<b><tt>%malloc(type [,name=type])</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Creates a wrapper around <tt>malloc()</tt> with the following prototype:
+</p>
+
+<div class="code"><pre>
+<em>type</em> *malloc_<em>name</em>(int nbytes = sizeof(<em>type</em>));
+</pre>
+</div>
+
+<p>
+If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>nbytes</tt> is required.
+The <tt>name</tt> parameter only needs to be specified when wrapping a type that
+is not a valid identifier (e.g., "<tt>int *</tt>", "<tt>double **</tt>", etc.).
+</p>
+
+</div>
+
+<p>
+<b><tt>%calloc(type [,name=type])</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Creates a wrapper around <tt>calloc()</tt> with the following prototype:
+</p>
+
+<div class="code"><pre>
+<em>type</em> *calloc_<em>name</em>(int nobj =1, int sz = sizeof(<em>type</em>));
+</pre>
+</div>
+
+<p>
+If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>sz</tt> is required.
+</p>
+
+</div>
+
+<p>
+<b><tt>%realloc(type [,name=type])</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Creates a wrapper around <tt>realloc()</tt> with the following prototype:
+</p>
+
+<div class="code"><pre>
+<em>type</em> *realloc_<em>name</em>(<em>type</em> *ptr, int nitems);
+</pre>
+</div>
+
+<p>
+Note: unlike the C <tt>realloc()</tt>, the wrapper generated by this macro implicitly includes the
+size of the corresponding type.   For example, <tt>realloc_int(p, 100)</tt> reallocates <tt>p</tt> so that
+it holds 100 integers.
+</p>
+
+</div>
+
+<p>
+<b><tt>%free(type [,name=type])</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Creates a wrapper around <tt>free()</tt> with the following prototype:
+</p>
+
+<div class="code"><pre>
+void free_<em>name</em>(<em>type</em> *ptr);
+</pre>
+</div>
+</div>
+
+<p>
+<b><tt>%sizeof(type [,name=type])</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Creates the constant:
+</p>
+
+<div class="code"><pre>
+%constant int sizeof_<em>name</em> = sizeof(<em>type</em>);
+</pre>
+</div>
+</div>
+
+<p>
+<b><tt>%allocators(type [,name=type])</tt></b>
+</p>
+
+<div class="indent"><p>
+Generates wrappers for all five of the above operations.
+</p></div>
+
+<p>
+Here is a simple example that illustrates the use of these macros:
+</p>
+
+<div class="code">
+<pre>
+// SWIG interface
+%module example
+%include "cmalloc.i"
+
+%malloc(int);
+%free(int);
+
+%malloc(int *, intp);
+%free(int *, intp);
+
+%allocators(double);
+</pre>
+</div>
+
+<p>
+Now, in a script:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; from example import *
+&gt;&gt;&gt; a = malloc_int()
+&gt;&gt;&gt; a
+'_000efa70_p_int'
+&gt;&gt;&gt; free_int(a)
+&gt;&gt;&gt; b = malloc_intp()
+&gt;&gt;&gt; b
+'_000efb20_p_p_int'
+&gt;&gt;&gt; free_intp(b)
+&gt;&gt;&gt; c = calloc_double(50)
+&gt;&gt;&gt; c
+'_000fab98_p_double'
+&gt;&gt;&gt; c = realloc_double(100000)
+&gt;&gt;&gt; free_double(c)
+&gt;&gt;&gt; print sizeof_double
+8
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<H3><a name="Library_nn7"></a>8.2.4 cdata.i</H3>
+
+
+<p>
+The <tt>cdata.i</tt> module defines functions for converting raw C data to and from strings
+in the target language.  The primary applications of this module would be packing/unpacking of
+binary data structures---for instance, if you needed to extract data from a buffer.
+The target language must support strings with embedded binary data
+in order for this to work.
+</p>
+
+<p>
+<b><tt>char *cdata(void *ptr, int nbytes)</tt></b>
+</p>
+
+<div class="indent"><p>
+Converts <tt>nbytes</tt> of data at <tt>ptr</tt> into a string.   <tt>ptr</tt> can be any
+pointer.
+</p></div>
+
+<p>
+<b><tt>void memmove(void *ptr, char *s)</tt></b>
+</p>
+
+<div class="indent"><p>
+Copies all of the string data in <tt>s</tt> into the memory pointed to by
+<tt>ptr</tt>.  The string may contain embedded NULL bytes.  The length of
+the string is implicitly determined in the underlying wrapper code.
+</p></div>
+
+<p>
+One use of these functions is packing and unpacking data from memory.
+Here is a short example:
+</p>
+
+<div class="code">
+<pre>
+// SWIG interface
+%module example
+%include "carrays.i"
+%include "cdata.i"
+
+%array_class(int, intArray);
+</pre>
+</div>
+
+<p>
+Python example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = intArray(10)
+&gt;&gt;&gt; for i in range(0,10):
+...    a[i] = i
+&gt;&gt;&gt; b = cdata(a,40)
+&gt;&gt;&gt; b
+'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04
+\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t'
+&gt;&gt;&gt; c = intArray(10)
+&gt;&gt;&gt; memmove(c,b)
+&gt;&gt;&gt; print c[4]
+4
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Since the size of data is not always known, the following macro is also defined:
+</p>
+
+<p>
+<b><tt>%cdata(type [,name=type])</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Generates the following function for extracting C data for a given type.
+</p>
+
+<div class="code">
+<pre>
+char *cdata_<em>name</em>(type* ptr, int nitems)
+</pre>
+</div>
+
+<p>
+<tt>nitems</tt> is the number of items of the given type to extract.
+</p>
+
+</div>
+
+<p>
+<b>Note:</b> These functions provide direct access to memory and can be used to overwrite data.
+Clearly they are unsafe.
+</p>
+
+<H2><a name="Library_nn8"></a>8.3 C String Handling</H2>
+
+
+<p>
+A common problem when working with C programs is dealing with
+functions that manipulate raw character data using <tt>char *</tt>.
+In part, problems arise because there are different interpretations of
+<tt>char *</tt>---it could be a NULL-terminated string or it could
+point to binary data.  Moreover, functions that manipulate raw strings
+may mutate data, perform implicit memory allocations, or utilize
+fixed-sized buffers.
+</p>
+
+<p>
+The problems (and perils) of using <tt>char *</tt> are
+well-known. However, SWIG is not in the business of enforcing
+morality.  The modules in this section provide basic functionality
+for manipulating raw C strings.
+</p>
+
+<H3><a name="Library_nn9"></a>8.3.1 Default string handling</H3>
+
+
+<p>
+Suppose you have a C function with this prototype:
+</p>
+
+<div class="code">
+<pre>
+char *foo(char *s);
+</pre>
+</div>
+
+<p>
+The default wrapping behavior for this function is to set <tt>s</tt>
+to a raw <tt>char *</tt> that refers to the internal string data in the
+target language.  In other words, if you were using a language like Tcl,
+and you wrote this,
+</p>
+
+<div class="code">
+<pre>
+% foo Hello
+</pre>
+</div>
+
+<p>
+then <tt>s</tt> would point to the representation of "Hello" inside
+the Tcl interpreter.  When returning a <tt>char *</tt>, SWIG assumes
+that it is a NULL-terminated string and makes a copy of it.  This
+gives the target language its own copy of the result.
+</p>
+
+<p>
+There are obvious problems with the default behavior.  First, since
+a <tt>char *</tt> argument points to data inside the target language, it is
+<b>NOT</b> safe for a function to modify this data (doing so may corrupt the
+interpreter and lead to a crash).  Furthermore, the default behavior does
+not work well with binary data. Instead, strings are assumed to be NULL-terminated.
+</p>
+
+<H3><a name="Library_nn10"></a>8.3.2 Passing binary data</H3>
+
+
+<p>
+If you have a function that expects binary data,
+</p>
+
+<div class="code">
+<pre>
+int parity(char *str, int len, int initial);
+</pre>
+</div>
+
+<p>
+you can wrap the parameters <tt>(char *str, int len)</tt> as a single
+argument using a typemap.   Just do this:
+</p>
+
+<div class="code">
+<pre>
+%apply (char *STRING, int LENGTH) { (char *str, int len) };
+...
+int parity(char *str, int len, int initial);
+</pre>
+</div>
+
+<p>
+Now, in the target language, you can use binary string data like this:
+</p>
+
+<div class="code">
+<pre>
+&gt;&gt;&gt; s = "H\x00\x15eg\x09\x20"
+&gt;&gt;&gt; parity(s,0)
+</pre>
+</div>
+
+<p>
+In the wrapper function, the passed string will be expanded to a pointer and length parameter.
+</p>
+
+<H3><a name="Library_nn11"></a>8.3.3 Using %newobject to release memory</H3>
+
+
+<p>
+If you have a function that allocates memory like this,
+</p>
+
+<div class="code">
+<pre>
+char *foo() {
+   char *result = (char *) malloc(...);
+   ...
+   return result;
+}
+</pre>
+</div>
+
+<p>
+then the SWIG generated wrappers will have a memory leak--the returned data will be copied
+into a string object and the old contents ignored.
+</p>
+
+<p>
+To fix the memory leak, use the <tt>%newobject</tt> directive.
+</p>
+
+<div class="code">
+<pre>
+%newobject foo;
+...
+char *foo();
+</pre>
+</div>
+
+<p>
+This will release the result.
+</p>
+
+<H3><a name="Library_nn12"></a>8.3.4 cstring.i</H3>
+
+
+<p>
+The <tt>cstring.i</tt> library file provides a collection of macros
+for dealing with functions that either mutate string arguments or
+which try to output string data through their arguments.  An
+example of such a function might be this rather questionable
+implementation:
+</p>
+
+<div class="code">
+<pre>
+void get_path(char *s) {
+    // Potential buffer overflow---uh, oh.
+    sprintf(s,"%s/%s", base_directory, sub_directory);
+}
+...
+// Somewhere else in the C program
+{
+    char path[1024];
+    ...
+    get_path(path);
+    ...
+}
+</pre>
+</div>
+
+<p>
+(Off topic rant: If your program really has functions like this, you
+would be well-advised to replace them with safer alternatives
+involving bounds checking).
+</p>
+
+<p>
+The macros defined in this module all expand to various combinations of
+typemaps.  Therefore, the same pattern matching rules and ideas apply.
+</p>
+
+<p>
+<b>%cstring_bounded_output(parm, maxsize)</b>
+</p>
+
+<div class="indent">
+
+<p>
+Turns parameter <tt><em>parm</em></tt> into an output value.  The
+output string is assumed to be NULL-terminated and smaller than
+<tt><em>maxsize</em></tt> characters.  Here is an example:
+</p>
+
+<div class="code">
+<pre>
+%cstring_bounded_output(char *path, 1024);
+...
+void get_path(char *path);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; get_path()
+/home/beazley/packages/Foo/Bar
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Internally, the wrapper function allocates a small buffer (on the stack) of the
+requested size and passes it as the pointer value.  Data stored in the buffer is then
+returned as a function return value.
+If the function already returns a value, then the return value and the output string
+are returned together (multiple return values).  <b>If more than <tt><em>maxsize</em></tt>
+bytes are written, your program will crash with a buffer overflow!</b>
+</p>
+
+</div>
+
+<p>
+<b>%cstring_chunk_output(parm, chunksize)</b>
+</p>
+
+<div class="indent">
+
+<p>
+Turns parameter <tt><em>parm</em></tt> into an output value.  The
+output string is always <tt><em>chunksize</em></tt> and may contain
+binary data.  Here is an example:
+</p>
+
+<div class="code">
+<pre>
+%cstring_chunk_output(char *packet, PACKETSIZE);
+...
+void get_packet(char *packet);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; get_packet()
+'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This macro is essentially identical to <tt>%cstring_bounded_output</tt>.  The
+only difference is that the result is always <tt><em>chunksize</em></tt> characters.
+Furthermore, the result can contain binary data.
+<b>If more than <tt><em>maxsize</em></tt>
+bytes are written, your program will crash with a buffer overflow!</b>
+</p>
+
+</div>
+
+<p>
+<b>%cstring_bounded_mutable(parm, maxsize)</b>
+</p>
+
+<div class="indent">
+
+<p>
+Turns parameter <tt><em>parm</em></tt> into a mutable string argument.
+The input string is assumed to be NULL-terminated and smaller than
+<tt><em>maxsize</em></tt> characters. The output string is also assumed
+to be NULL-terminated and less than <tt><em>maxsize</em></tt> characters.
+</p>
+
+<div class="code">
+<pre>
+%cstring_bounded_mutable(char *ustr, 1024);
+...
+void make_upper(char *ustr);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; make_upper("hello world")
+'HELLO WORLD'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Internally, this macro is almost exactly the same as
+<tt>%cstring_bounded_output</tt>.  The only difference is that the
+parameter accepts an input value that is used to initialize the
+internal buffer. It is important to emphasize that this function
+does not mutate the string value passed---instead it makes a copy of the
+input value, mutates it, and returns it as a result.
+<b>If more than <tt><em>maxsize</em></tt> bytes are
+written, your program will crash with a buffer overflow!</b>
+</p>
+
+</div>
+
+<p>
+<b>%cstring_mutable(parm [, expansion])</b>
+</p>
+
+<div class="indent">
+
+<p>
+Turns parameter <tt><em>parm</em></tt> into a mutable string argument.
+The input string is assumed to be NULL-terminated.  An optional
+parameter <tt><em>expansion</em></tt> specifies the number of
+extra characters by which the string might grow when it is modified.
+The output string is assumed to be NULL-terminated and less than
+the size of the input string plus any expansion characters.
+</p>
+
+<div class="code">
+<pre>
+%cstring_mutable(char *ustr);
+...
+void make_upper(char *ustr);
+
+%cstring_mutable(char *hstr, HEADER_SIZE);
+...
+void attach_header(char *hstr);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; make_upper("hello world")
+'HELLO WORLD'
+&gt;&gt;&gt; attach_header("Hello world")
+'header: Hello world'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This macro differs from <tt>%cstring_bounded_mutable()</tt> in that a
+buffer is dynamically allocated (on the heap using
+<tt>malloc/new</tt>).  This buffer is always large enough to store a
+copy of the input value plus any expansion bytes that might have been
+requested.
+It is important to emphasize that this function
+does not directly mutate the string value passed---instead it makes a copy of the
+input value, mutates it, and returns it as a result.
+<b>If the function expands the result by more than <tt><em>expansion</em></tt> extra
+bytes, then the program will crash with a buffer overflow!</b>
+</p>
+
+</div>
+
+
+<p>
+<b>%cstring_output_maxsize(parm, maxparm)</b>
+</p>
+
+<div class="indent">
+
+<p>
+This macro is used to handle bounded character output functions where
+both a <tt>char *</tt> and a maximum length parameter are provided.
+As input, a user simply supplies the maximum length.
+The return value is assumed to be a NULL-terminated string.
+</p>
+
+<div class="code">
+<pre>
+%cstring_output_maxsize(char *path, int maxpath);
+...
+void get_path(char *path, int maxpath);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; get_path(1024)
+'/home/beazley/Packages/Foo/Bar'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This macro provides a safer alternative for functions that need to
+write string data into a buffer.  User supplied buffer size is
+used to dynamically allocate memory on heap.  Results are placed
+into that buffer and returned as a string object.
+</p>
+
+</div>
+
+
+
+<p>
+<b>%cstring_output_withsize(parm, maxparm)</b>
+</p>
+
+<div class="indent">
+
+<p>
+This macro is used to handle bounded character output functions where
+both a <tt>char *</tt> and a pointer <tt>int *</tt> are passed.  Initially,
+the <tt>int *</tt> parameter points to a value containing the maximum size.
+On return, this value is assumed to contain the actual number of bytes.
+As input, a user simply supplies the maximum length.  The output value is a
+string that may contain binary data.
+</p>
+
+<div class="code">
+<pre>
+%cstring_output_withsize(char *data, int *maxdata);
+...
+void get_data(char *data, int *maxdata);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; get_data(1024)
+'x627388912'
+&gt;&gt;&gt; get_data(1024)
+'xyzzy'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This macro is a somewhat more powerful version of <tt>%cstring_output_chunk()</tt>.  Memory
+is dynamically allocated and can be arbitrary large.  Furthermore, a function can control
+how much data is actually returned by changing the value of the <tt>maxparm</tt> argument.
+</p>
+
+</div>
+
+
+<p>
+<b>%cstring_output_allocate(parm, release)</b>
+</p>
+
+<div class="indent">
+
+<p>
+This macro is used to return strings that are allocated within the program and
+returned in a parameter of type <tt>char **</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+void foo(char **s) {
+    *s = (char *) malloc(64);
+    sprintf(*s, "Hello world\n");
+}
+</pre>
+</div>
+
+<p>
+The returned string is assumed to be NULL-terminated.  <tt><em>release</em></tt>
+specifies how the allocated memory is to be released (if applicable).  Here is an
+example:
+</p>
+
+<div class="code">
+<pre>
+%cstring_output_allocate(char **s, free(*$1));
+...
+void foo(char **s);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo()
+'Hello world\n'
+&gt;&gt;&gt;
+</pre>
+</div>
+</div>
+
+
+<p>
+<b>%cstring_output_allocate_size(parm, szparm, release)</b>
+</p>
+
+<div class="indent">
+
+<p>
+This macro is used to return strings that are allocated within the program and
+returned in two parameters of type <tt>char **</tt> and <tt>int *</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+void foo(char **s, int *sz) {
+    *s = (char *) malloc(64);
+    *sz = 64;
+    // Write some binary data
+    ...
+}
+</pre>
+</div>
+
+<p>
+The returned string may contain binary data. <tt><em>release</em></tt>
+specifies how the allocated memory is to be released (if applicable).  Here is an
+example:
+</p>
+
+<div class="code">
+<pre>
+%cstring_output_allocate_size(char **s, int *slen, free(*$1));
+...
+void foo(char **s, int *slen);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo()
+'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This is the safest and most reliable way to return binary string data in
+SWIG.  If you have functions that conform to another prototype, you might
+consider wrapping them with a helper function.   For example, if you had this:
+</p>
+
+<div class="code">
+<pre>
+char  *get_data(int *len);
+</pre>
+</div>
+
+<p>
+You could wrap it with a function like this:
+</p>
+
+<div class="code">
+<pre>
+void my_get_data(char **result, int *len) {
+   *result = get_data(len);
+}
+</pre>
+</div>
+</div>
+
+<p>
+<b>Comments:</b>
+</p>
+
+<ul>
+<li>Support for the <tt>cstring.i</tt> module depends on the target language. Not all
+SWIG modules currently support this library.
+</li>
+
+<li>Reliable handling of raw C strings is a delicate topic.  There are many ways
+to accomplish this in SWIG.  This library provides support for a few common techniques.
+</li>
+
+<li>If used in C++, this library uses <tt>new</tt> and <tt>delete []</tt> for memory
+allocation.  If using ANSI C, the library uses <tt>malloc()</tt> and <tt>free()</tt>.
+</li>
+
+<li>Rather than manipulating <tt>char *</tt> directly, you might consider using a special string
+structure or class instead.
+</li>
+</ul>
+
+<H2><a name="Library_stl_cpp_library"></a>8.4 STL/C++ Library</H2>
+
+
+<p>
+The library modules in this section provide access to parts of the standard C++ library including the STL.
+SWIG support for the STL is an ongoing effort. Support is quite comprehensive for some language modules
+but some of the lesser used modules do not have quite as much library code written.
+</p>
+
+<p>
+The following table shows which C++ classes are supported and the equivalent SWIG interface library file for the C++ library.
+</p>
+
+<table BORDER summary="SWIG C++ library files">
+<tr VALIGN=TOP>
+<td><b>C++ class</b></td>
+<td><b>C++ Library file</b></td>
+<td><b>SWIG Interface library file</b></td>
+</tr>
+
+<tr> <td>std::deque</td>           <td>deque</td>             <td>std_deque.i</td> </tr>
+<tr> <td>std::list</td>           <td>list</td>             <td>std_list.i</td> </tr>
+<tr> <td>std::map</td>           <td>map</td>             <td>std_map.i</td> </tr>
+<tr> <td>std::pair</td>           <td>utility</td>             <td>std_pair.i</td> </tr>
+<tr> <td>std::set</td>           <td>set</td>             <td>std_set.i</td> </tr>
+<tr> <td>std::string</td>           <td>string</td>             <td>std_string.i</td> </tr>
+<tr> <td>std::vector</td>           <td>vector</td>             <td>std_vector.i</td> </tr>
+
+</table>
+
+<p>
+The list is by no means complete; some language modules support a subset of the above and some support additional STL classes.
+Please look for the library files in the appropriate language library directory.
+</p>
+
+
+<H3><a name="Library_nn14"></a>8.4.1 std_string.i</H3>
+
+
+<p>
+The <tt>std_string.i</tt> library provides typemaps for converting C++ <tt>std::string</tt>
+objects to and from strings in the target scripting language.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "std_string.i"
+
+std::string foo();
+void        bar(const std::string &amp;x);
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+x = foo();                # Returns a string object
+bar("Hello World");       # Pass string as std::string
+</pre>
+</div>
+
+<p>
+A common problem that people encounter is that of classes/structures
+containing a <tt>std::string</tt>. This can be overcome by defining a typemap.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "std_string.i"
+
+%apply const std::string&amp; {std::string* foo};
+
+struct my_struct
+{
+  std::string foo;
+};
+</pre>
+</div>
+
+<p>
+In the target language:
+</p>
+
+<div class="targetlang">
+<pre>
+x = my_struct();
+x.foo="Hello World";      # assign with string
+print x.foo;              # print as string
+</pre>
+</div>
+
+<p>
+This module only supports types <tt>std::string</tt> and
+<tt>const std::string &amp;</tt>.    Pointers and non-const references
+are left unmodified and returned as SWIG pointers.
+</p>
+
+<p>
+This library file is fully aware of C++ namespaces.  If you export <tt>std::string</tt> or rename
+it with a typedef, make sure you include those declarations in your interface.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "std_string.i"
+
+using namespace std;
+typedef std::string String;
+...
+void foo(string s, const String &amp;t);     // std_string typemaps still applied
+</pre>
+</div>
+
+<p>
+<b>Note:</b> The <tt>std_string</tt> library is incompatible with Perl on some platforms.
+We're looking into it.
+</p>
+
+<H3><a name="Library_nn15"></a>8.4.2 std_vector.i</H3>
+
+
+<p>
+The <tt>std_vector.i</tt> library provides support for the C++ <tt>vector</tt> class in the STL.
+Using this library involves the use of the <tt>%template</tt> directive.  All you need to do is to
+instantiate different versions of <tt>vector</tt> for the types that you want to use.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "std_vector.i"
+
+namespace std {
+   %template(vectori) vector&lt;int&gt;;
+   %template(vectord) vector&lt;double&gt;;
+};
+</pre>
+</div>
+
+<p>
+When a template <tt>vector&lt;X&gt;</tt> is instantiated a number of things happen:
+</p>
+
+<ul>
+<li>A class that exposes the C++ API is created in the target language .
+This can be used to create objects, invoke methods, etc.  This class is
+currently a subset of the real STL vector class.
+</li>
+
+<li>Input typemaps are defined for <tt>vector&lt;X&gt;</tt>, <tt>const vector&lt;X&gt; &amp;</tt>, and
+<tt>const vector&lt;X&gt; *</tt>.  For each of these, a pointer <tt>vector&lt;X&gt; *</tt> may be passed or
+a native list object in the target language.
+</li>
+
+<li>An output typemap is defined for <tt>vector&lt;X&gt;</tt>.  In this case, the values in the
+vector are expanded into a list object in the target language.
+</li>
+
+<li>For all other variations of the type, the wrappers expect to receive a <tt>vector&lt;X&gt; *</tt>
+object in the usual manner.
+</li>
+
+<li>An exception handler for <tt>std::out_of_range</tt> is defined.
+</li>
+
+<li>Optionally, special methods for indexing, item retrieval, slicing, and element assignment
+may be defined.  This depends on the target language.
+</li>
+</ul>
+
+<p>
+To illustrate the use of this library, consider the following functions:
+</p>
+
+<div class="code">
+<pre>
+/* File : example.h */
+
+#include &lt;vector&gt;
+#include &lt;algorithm&gt;
+#include &lt;functional&gt;
+#include &lt;numeric&gt;
+
+double average(std::vector&lt;int&gt; v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) {
+    std::vector&lt;double&gt; w(v);
+    for (unsigned int i=0; i&lt;w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector&lt;double&gt;&amp; v) {
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides&lt;double&gt;(),2.0));
+}
+</pre>
+</div>
+
+<p>
+To wrap with SWIG, you might write the following:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+// Instantiate templates used by example
+namespace std {
+   %template(IntVector) vector&lt;int&gt;;
+   %template(DoubleVector) vector&lt;double&gt;;
+}
+
+// Include the header file with above prototypes
+%include "example.h"
+</pre>
+</div>
+
+<p>
+Now, to illustrate the behavior in the scripting interpreter, consider this Python example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; from example import *
+&gt;&gt;&gt; iv = IntVector(4)         # Create an vector&lt;int&gt;
+&gt;&gt;&gt; for i in range(0,4):
+...      iv[i] = i
+&gt;&gt;&gt; average(iv)               # Call method
+1.5
+&gt;&gt;&gt; average([0,1,2,3])        # Call with list
+1.5
+&gt;&gt;&gt; half([1,2,3])             # Half a list
+(0.5,1.0,1.5)
+&gt;&gt;&gt; halve_in_place([1,2,3])   # Oops
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+TypeError: Type error. Expected _p_std__vectorTdouble_t
+&gt;&gt;&gt; dv = DoubleVector(4)
+&gt;&gt;&gt; for i in range(0,4):
+...       dv[i] = i
+&gt;&gt;&gt; halve_in_place(dv)       # Ok
+&gt;&gt;&gt; for i in dv:
+...       print i
+...
+0.0
+0.5
+1.0
+1.5
+&gt;&gt;&gt; dv[20] = 4.5
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+  File "example.py", line 81, in __setitem__
+    def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args)
+IndexError: vector index out of range
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This library module is fully aware of C++ namespaces.  If you use vectors with other names,
+make sure you include the appropriate <tt>using</tt> or typedef directives.  For example:
+</p>
+
+<div class="code">
+<pre>
+%include "std_vector.i"
+
+namespace std {
+    %template(IntVector) vector&lt;int&gt;;
+}
+
+using namespace std;
+typedef std::vector Vector;
+
+void foo(vector&lt;int&gt; *x, const Vector &amp;x);
+</pre>
+</div>
+
+<p>
+<b>Note:</b> This module makes use of several advanced SWIG features including templatized typemaps
+and template partial specialization.  If you are trying to wrap other C++ code with templates, you
+might look at the code contained in <tt>std_vector.i</tt>.  Alternatively, you can show them the code
+if you want to make their head explode.
+</p>
+
+<p>
+<b>Note:</b> This module is defined for all SWIG target languages.  However argument conversion
+details and the public API exposed to the interpreter vary.
+</p>
+
+<p>
+<b>Note:</b> <tt>std_vector.i</tt> was written by Luigi "The Amazing" Ballabio.
+</p>
+
+
+<H3><a name="Library_stl_exceptions"></a>8.4.3 STL exceptions</H3>
+
+
+<p>
+Many of the STL wrapper functions add parameter checking and will throw a language dependent error/exception
+should the values not be valid. The classic example is array bounds checking.
+The library wrappers are written to throw a C++ exception in the case of error.
+The C++ exception in turn gets converted into an appropriate error/exception for the target language.
+By and large this handling should not need customising, however, customisation can easily be achieved by supplying appropriate "throws" typemaps.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "std_vector.i"
+%typemap(throws) std::out_of_range {
+  // custom exception handler
+}
+%template(VectInt) std::vector&lt;int&gt;;
+</pre>
+</div>
+
+<p>
+The custom exception handler might, for example, log the exception then convert it into a specific error/exception for the target language.
+</p>
+
+<p>
+When using the STL it is advisable to add in an exception handler to catch all STL exceptions.
+The <tt>%exception</tt> directive can be used by placing the following code before any other methods or libraries to be wrapped:
+</p>
+
+<div class="code">
+<pre>
+%include "exception.i"
+
+%exception {
+  try {
+    $action
+  } catch (const std::exception&amp; e) {
+    SWIG_exception(SWIG_RuntimeError, e.what());
+  }
+}
+</pre>
+</div>
+
+<p>
+Any thrown STL exceptions will then be gracefully handled instead of causing a crash.
+</p>
+
+
+<H2><a name="Library_nn16"></a>8.5 Utility Libraries</H2>
+
+
+<H3><a name="Library_nn17"></a>8.5.1 exception.i</H3>
+
+
+<p>
+The <tt>exception.i</tt> library provides a language-independent function for raising a run-time
+exception in the target language. This library is largely used by the SWIG library writers.
+If possible, use the error handling scheme available to your target language as there is greater
+flexibility in what errors/exceptions can be thrown.
+</p>
+
+<p>
+<b><tt>SWIG_exception(int code, const char *message)</tt></b>
+</p>
+
+<div class="indent">
+
+<p>
+Raises an exception in the target language.  <tt>code</tt> is one of the following symbolic
+constants:
+</p>
+
+<div class="code">
+<pre>
+SWIG_MemoryError
+SWIG_IOError
+SWIG_RuntimeError
+SWIG_IndexError
+SWIG_TypeError
+SWIG_DivisionByZero
+SWIG_OverflowError
+SWIG_SyntaxError
+SWIG_ValueError
+SWIG_SystemError
+</pre>
+</div>
+
+<p>
+<tt>message</tt> is a string indicating more information about the problem.
+</p>
+
+</div>
+
+<p>
+The primary use of this module is in writing language-independent exception handlers.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%include "exception.i"
+%exception std::vector::getitem {
+    try {
+        $action
+    } catch (std::out_of_range&amp; e) {
+        SWIG_exception(SWIG_IndexError,const_cast&lt;char*&gt;(e.what()));
+    }
+}
+</pre>
+</div>
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Lisp.html b/trunk/Doc/Manual/Lisp.html
new file mode 100644
index 0000000..ca2d041
--- /dev/null
+++ b/trunk/Doc/Manual/Lisp.html
@@ -0,0 +1,802 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Common Lisp</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Lisp_nn1"></a>21 SWIG and Common Lisp</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Lisp_nn2">Allegro Common Lisp</a>
+<li><a href="#Lisp_nn3">Common Foreign Function Interface(CFFI)</a>
+<ul>
+<li><a href="#Lisp_nn4">Additional Commandline Options </a>
+<li><a href="#Lisp_nn5">Generating CFFI bindings</a>
+<li><a href="#Lisp_nn6">Generating CFFI bindings for C++ code</a>
+<li><a href="#Lisp_nn7">Inserting user code into generated files</a>
+</ul>
+<li><a href="#Lisp_nn8">CLISP</a>
+<ul>
+<li><a href="#Lisp_nn9">Additional Commandline Options </a>
+<li><a href="#Lisp_nn10">Details on CLISP bindings</a>
+</ul>
+<li><a href="#Lisp_nn11">UFFI </a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+      Common Lisp is a high-level, all-purpose, object-oriented,
+      dynamic, functional programming language with long history. 
+      Common Lisp is used in many fields, ranging from web development to
+      finance, and also common in computer science education.
+      There are more than 9 different implementations of common lisp which
+      are available, all have different foreign function
+      interfaces. SWIG currently supports only the Allegro Common
+      Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI
+      foreign function interfaces.  
+</p>
+<H2><a name="Lisp_nn2"></a>21.1 Allegro Common Lisp</H2>
+
+
+<p>
+  Allegro Common Lisp support in SWIG has been updated to include
+  support for both C and C++. You can read about the interface
+  <a href="Allegrocl.html#Allegrocl_nn1">here</a>
+</p>
+
+<H2><a name="Lisp_nn3"></a>21.2 Common Foreign Function Interface(CFFI)</H2>
+
+
+<p>
+      CFFI, the Common Foreign Function Interface, is a portable foreign
+      function interface for ANSI Common Lisp systems, similar in
+      spirit to UFFI. Unlike UFFI, CFFI requires only a small set of
+      low-level functionality from the Lisp implementation, such as
+      calling a foreign function by name, allocating foreign memory,
+      and dereferencing pointers.  
+</p>
+
+<p>
+      To run the cffi module of SWIG requires very little effort, you
+      just need to run:
+</p>
+<div class="code"><pre>
+swig -cffi -module <i>module-name</i>   <i>file-name</i> 
+
+</pre></div>
+
+<p>
+      But a better was of using all the power of SWIG is to write SWIG
+      interface files. Below we will explain how to write interface
+      files and the various things which you can do with them.
+</p>
+
+<H3><a name="Lisp_nn4"></a>21.2.1 Additional Commandline Options </H3>
+
+
+<p>
+The following table list the additional commandline options available for the CLISP module. They can also be seen by using: 
+</p>
+
+<div class="code"><pre>
+swig -cffi -help 
+</pre></div>
+<br/>
+
+<table summary="CFFI specific options">
+<tr>
+ <th> CFFI specific options</th>
+</tr>
+
+<tr>
+<td>-generate-typedef</td>
+<td>If this option is given then defctype will be used to generate<br\>
+      shortcuts according to the typedefs in the input.
+</td>
+</tr>
+
+<tr>
+<td>-[no]cwrap</td>
+<td>Turn on or turn off generation of an intermediate C file when<br\>
+    creating a C interface. By default this is only done for C++ code.
+</td>
+</tr>
+
+<tr>
+<td>-[no]swig-lisp</td>
+<td>Turns on or off generation of code for helper lisp macro, functions,
+      etc. which SWIG uses while generating wrappers. These macros, functions
+      may still be used by generated wrapper code.
+</td>
+</tr>
+
+</table>
+
+<H3><a name="Lisp_nn5"></a>21.2.2 Generating CFFI bindings</H3>
+
+
+As we mentioned earlier the ideal way to use SWIG is to use interface
+    files. To illustrate the use of it, lets assume that we have a
+    file named <i>test.h</i> with the following C code:
+
+<div class="code"><pre>
+#define y 5
+#define x (y &gt;&gt;  1)
+
+typedef int days;
+
+struct bar {
+  short p, q;
+    char a, b;
+    int *z[1000];
+    struct bar * n;
+};
+  
+struct   bar * my_struct;
+
+struct foo {
+    int a;
+    struct foo * b[100];
+  
+};
+
+int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p);
+
+int func123(div_t * p,int **q[100],int r[][1000][10]);
+
+void lispsort_double (int n, double * array);
+
+enum color { RED, BLUE, GREEN};
+</pre></div>
+
+Corresponding to this we will write a simple interface file:
+<div class="code"><pre>
+%module test
+
+%include "test.h"
+
+</pre></div>
+
+The generated SWIG Code will be:
+
+<div class="targetlang"><pre>
+;;;SWIG wrapper code starts here
+
+(cl:defmacro defanonenum (&amp;body enums)
+   "Converts anonymous enums to defconstants."
+  `(cl:progn ,@(cl:loop for value in enums
+                        for index = 0 then (cl:1+ index)
+                        when (cl:listp value) do (cl:setf index (cl:second value)
+                                                          value (cl:first value))
+                        collect `(cl:defconstant ,value ,index))))
+
+(cl:eval-when (:compile-toplevel :load-toplevel)
+  (cl:unless (cl:fboundp 'swig-lispify)
+    (cl:defun swig-lispify (name flag cl:&amp;optional (package cl:*package*))
+      (cl:labels ((helper (lst last rest cl:&amp;aux (c (cl:car lst)))
+                    (cl:cond
+                      ((cl:null lst)
+                       rest)
+                      ((cl:upper-case-p c)
+                       (helper (cl:cdr lst) 'upper
+                               (cl:case last
+                                 ((lower digit) (cl:list* c #\- rest))
+                                 (cl:t (cl:cons c rest)))))
+                      ((cl:lower-case-p c)
+                       (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest)))
+                      ((cl:digit-char-p c)
+                       (helper (cl:cdr lst) 'digit 
+                               (cl:case last
+                                 ((upper lower) (cl:list* c #\- rest))
+                                 (cl:t (cl:cons c rest)))))
+                      ((cl:char-equal c #\_)
+                       (helper (cl:cdr lst) '_ (cl:cons #\- rest)))
+                      (cl:t
+                       (cl:error "Invalid character: ~A" c)))))
+        (cl:let ((fix (cl:case flag
+                        ((constant enumvalue) "+")
+                        (variable "*")
+                        (cl:t ""))))
+          (cl:intern
+           (cl:concatenate
+            'cl:string
+            fix
+            (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
+            fix)
+           package))))))
+
+;;;SWIG wrapper code ends here
+
+
+(cl:defconstant y 5)
+
+(cl:defconstant x (cl:ash 5 -1))
+
+(cffi:defcstruct bar
+	(p :short)
+	(q :short)
+	(a :char)
+	(b :char)
+	(z :pointer)
+	(n :pointer))
+
+(cffi:defcvar ("my_struct" my_struct)
+ :pointer)
+
+(cffi:defcstruct foo
+	(a :int)
+	(b :pointer))
+
+(cffi:defcfun ("pointer_func" pointer_func) :int
+  (ClosureFun :pointer)
+  (p :int))
+
+(cffi:defcfun ("func123" func123) :int
+  (p :pointer)
+  (q :pointer)
+  (r :pointer))
+
+(cffi:defcfun ("lispsort_double" lispsort_double) :void
+  (n :int)
+  (array :pointer))
+
+(cffi:defcenum color
+	:RED
+	:BLUE
+	:GREEN)
+</pre></div>
+
+<p>
+   The <i>SWIG wrapper</i> code refers to the special code which SWIG
+    may need to use while wrapping C code. You can turn on/off the
+    generation of this code by using the <i>-[no]swig-lisp</i>
+    option. You must have noticed that SWIG goes one extra step to
+    ensure that CFFI does not do automatic lispification of the C
+    function names. The reason SWIG does this is because quite often
+    developers want to build a nice CLOS based lispy API, and this one
+    to one correspondence between C function names and lisp function
+    name helps.
+</p>
+   
+<p> Maybe you want to have your own convention for generating lisp
+      function names for corresponding C function names, or you just
+      want to lispify the names, also, before we forget you want to
+      export the generated lisp names. To do this, we will use the
+      SWIG <a
+        href="Customization.html#features">feature directive</a>. 
+Let's edit the interface file such that the C type "div_t*" is changed
+      to Lisp type ":my-pointer", we lispify all names, 
+      export everything, and do some more stuff.
+
+</p>
+<div class="code"><pre>
+%module test
+
+%typemap(cin) div_t* ":my-pointer";
+
+%feature("intern_function","1");
+%feature("export");
+
+%feature("inline") lispsort_double;
+
+%feature("intern_function", "my-lispify") lispsort_double;
+%rename func123 renamed_cool_func;
+%ignore "pointer_func";
+
+%include "test.h"
+
+</pre></div>
+
+<p>
+The <i>typemap(cin)</i> ensures that for all arguments which are input
+    to C with the type "div_t*", the ":my-pointer" type be
+    used. Similarly  <i>typemap(cout)</i> are used for all types which
+    are returned from C.
+</p>
+<p>
+The feature <i>intern_function</i> ensures that all C names are
+      interned using the <b>swig-lispify</b> function. The "1" given
+      to the feature is optional. The use of feature like
+      <i>%feature("intern_function","1");</i> globally enables
+      interning for everything. If you want to target a single
+      function, or declaration then use the targeted version of
+      feature, <i>%feature("intern_function", "my-lispify")
+        lispsort_double;</i>, here we are using an additional feature
+      which allows us to use our lispify function.
+</p>
+<p>The <i>export</i> feature allows us to export the symbols. The <i>inline</i>
+      feature declaims the declared function as inline. The <i>rename</i>
+      directive allows us to change the name(it is useful when
+      generating C wrapper code for handling overloaded
+      functions). The <i>ignore</i> directive ignores a certain
+      declaration. 
+</p>
+<p>There are several other things which are possible, to see some
+      example of usage of SWIG look at the Lispbuilder and wxCL
+      projects. The generated code with 'noswig-lisp' option is:
+</p>
+
+<div class="targetlang"><pre>
+(cl:defconstant #.(swig-lispify "y" 'constant) 5)
+
+(cl:export '#.(swig-lispify "y" 'constant))
+
+(cl:defconstant #.(swig-lispify "x" 'constant) (cl:ash 5 -1))
+
+(cl:export '#.(swig-lispify "x" 'constant))
+
+(cffi:defcstruct #.(swig-lispify "bar" 'classname)
+	(#.(swig-lispify "p" 'slotname) :short)
+	(#.(swig-lispify "q" 'slotname) :short)
+	(#.(swig-lispify "a" 'slotname) :char)
+	(#.(swig-lispify "b" 'slotname) :char)
+	(#.(swig-lispify "z" 'slotname) :pointer)
+	(#.(swig-lispify "n" 'slotname) :pointer))
+
+(cl:export '#.(swig-lispify "bar" 'classname))
+
+(cl:export '#.(swig-lispify "p" 'slotname))
+
+(cl:export '#.(swig-lispify "q" 'slotname))
+
+(cl:export '#.(swig-lispify "a" 'slotname))
+
+(cl:export '#.(swig-lispify "b" 'slotname))
+
+(cl:export '#.(swig-lispify "z" 'slotname))
+
+(cl:export '#.(swig-lispify "n" 'slotname))
+
+(cffi:defcvar ("my_struct" #.(swig-lispify "my_struct" 'variable))
+ :pointer)
+
+(cl:export '#.(swig-lispify "my_struct" 'variable))
+
+(cffi:defcstruct #.(swig-lispify "foo" 'classname)
+	(#.(swig-lispify "a" 'slotname) :int)
+	(#.(swig-lispify "b" 'slotname) :pointer))
+
+(cl:export '#.(swig-lispify "foo" 'classname))
+
+(cl:export '#.(swig-lispify "a" 'slotname))
+
+(cl:export '#.(swig-lispify "b" 'slotname))
+
+(cffi:defcfun ("renamed_cool_func" #.(swig-lispify "renamed_cool_func" 'function)) :int
+  (p :my-pointer)
+  (q :pointer)
+  (r :pointer))
+
+(cl:export '#.(swig-lispify "renamed_cool_func" 'function))
+
+(cl:declaim (cl:inline #.(my-lispify "lispsort_double" 'function)))
+
+(cffi:defcfun ("lispsort_double" #.(my-lispify "lispsort_double" 'function)) :void
+  (n :int)
+  (array :pointer))
+
+(cl:export '#.(my-lispify "lispsort_double" 'function))
+
+(cffi:defcenum #.(swig-lispify "color" 'enumname)
+	#.(swig-lispify "RED" 'enumvalue :keyword)
+	#.(swig-lispify "BLUE" 'enumvalue :keyword)
+	#.(swig-lispify "GREEN" 'enumvalue :keyword))
+
+(cl:export '#.(swig-lispify "color" 'enumname))
+
+</pre></div>
+
+<H3><a name="Lisp_nn6"></a>21.2.3 Generating CFFI bindings for C++ code</H3>
+
+
+<p>This feature to SWIG (for CFFI) is very new and still far from
+    complete. Pitch in with your patches, bug reports and feature
+    requests to improve it.
+</p>
+<p> Generating bindings for C++ code, requires <i>-c++</i> option to be
+      present and it first generates C binding which will wrap the C++
+      code, and then generates the 
+      corresponding CFFI wrapper code. In the generated C wrapper
+      code, you will often want to put your own C code, such as the
+      code to include various files. This can be done by making use of
+      "%{" and "%}" as shown below.
+</p> 
+<div class="code"><pre>
+%{
+ #include "Test/test.h"
+%}
+</pre></div>
+<p>
+Also, while parsing the C++ file and generating C wrapper code SWIG
+    may need to be able to understand various symbols used in other
+    header files. To help SWIG in doing this while ensuring that
+    wrapper code is generated for the target file, use the "import"
+    directive. The "include" directive specifies the target file for
+    which wrapper code will be generated.
+</p>
+<div class="code"><pre>
+
+%import "ancillary/header.h"
+
+%include "target/header.h"
+
+</pre></div>
+Various features which were available for C headers can also be used
+    here. The target header which we are going to use here is:
+<div class="code"><pre>
+namespace OpenDemo {
+  class Test
+    {
+    public:
+        float x;
+        // constructors
+        Test (void) {x = 0;}
+        Test (float X) {x = X;}
+
+        // vector addition
+        Test operator+ (const Test&amp; v) const {return Test (x+v.x);}
+
+      // length squared
+        float lengthSquared (void) const {return this-&gt;dot (*this);}
+
+        static float distance (const Test&amp; a, const Test&amp; b){return(a-b).length();}
+
+        inline Test parallelComponent (const Test&amp; unitBasis) const {
+          return unitBasis * projection;
+        }
+
+        Test setYtoZero (void) const {return Test (this-&gt;x);}
+
+        static const Test zero;
+    };
+
+
+   inline Test operator* (float s, const Test&amp; v) {return v*s;}
+
+
+    inline std::ostream&amp; operator&lt;&lt; (std::ostream&amp; o, const Test&amp; v)
+    {
+        return o &lt;&lt; "(" &lt;&lt; v.x &lt;&lt; ")";
+    }
+
+
+    inline Test RandomUnitVectorOnXZPlane (void)
+    {
+        return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
+    }
+}
+</pre></div>
+<p>The interface used is: </p>
+<div class="code"><pre>
+%module test
+%include "test.cpp"
+</pre></div>
+
+SWIG generates 3 files, the first one is a C wrap which we don't show,
+    the second is the plain CFFI wrapper which is as shown below:
+<div class="targetlang"><pre>
+(cffi:defcfun ("_wrap_Test_x_set" Test_x_set) :void
+  (self :pointer)
+  (x :float))
+
+(cffi:defcfun ("_wrap_Test_x_get" Test_x_get) :float
+  (self :pointer))
+
+(cffi:defcfun ("_wrap_new_Test__SWIG_0" new_Test) :pointer)
+
+(cffi:defcfun ("_wrap_new_Test__SWIG_1" new_Test) :pointer
+  (X :float))
+
+(cffi:defcfun ("_wrap_Test___add__" Test___add__) :pointer
+  (self :pointer)
+  (v :pointer))
+
+(cffi:defcfun ("_wrap_Test_lengthSquared" Test_lengthSquared) :float
+  (self :pointer))
+
+(cffi:defcfun ("_wrap_Test_distance" Test_distance) :float
+  (a :pointer)
+  (b :pointer))
+
+(cffi:defcfun ("_wrap_Test_parallelComponent" Test_parallelComponent) :pointer
+  (self :pointer)
+  (unitBasis :pointer))
+
+(cffi:defcfun ("_wrap_Test_setYtoZero" Test_setYtoZero) :pointer
+  (self :pointer))
+
+(cffi:defcvar ("Test_zero" Test_zero)
+ :pointer)
+
+(cffi:defcfun ("_wrap_delete_Test" delete_Test) :void
+  (self :pointer))
+
+(cffi:defcfun ("_wrap___mul__" __mul__) :pointer
+  (s :float)
+  (v :pointer))
+
+(cffi:defcfun ("_wrap___lshift__" __lshift__) :pointer
+  (o :pointer)
+  (v :pointer))
+
+(cffi:defcfun ("_wrap_RandomUnitVectorOnXZPlane" RandomUnitVectorOnXZPlane) :pointer)
+</pre></div>
+
+The output is pretty good but it fails in disambiguating overloaded
+    functions such as the constructor, in this case. One way of
+    resolving this problem is to make the interface use the rename
+    directiv, but hopefully there are better solutions.
+ In addition SWIG also generates, a CLOS file
+
+
+<div class="targetlang"><pre>
+(clos:defclass test()
+  ((ff :reader ff-pointer)))
+
+(clos:defmethod (cl:setf x) (arg0 (obj test))
+  (Test_x_set (ff-pointer obj) arg0))
+
+(clos:defmethod x ((obj test))
+  (Test_x_get (ff-pointer obj)))
+
+(cl:shadow "+")
+(clos:defmethod + ((obj test) (self test) (v test))
+  (Test___add__ (ff-pointer obj) (ff-pointer self) (ff-pointer v)))
+
+(clos:defmethod length-squared ((obj test) (self test))
+  (Test_lengthSquared (ff-pointer obj) (ff-pointer self)))
+
+(clos:defmethod parallel-component ((obj test) (self test) (unitBasis test))
+  (Test_parallelComponent (ff-pointer obj) (ff-pointer self) (ff-pointer unitBasis)))
+
+(clos:defmethod set-yto-zero ((obj test) (self test))
+  (Test_setYtoZero (ff-pointer obj) (ff-pointer self)))
+</pre></div>
+
+<p>I agree that the CFFI C++ module needs lot more work. But I hope it
+    provides a starting point, on which you can base your work of
+    importing C++ libraries to Lisp. 
+</p>
+<p>
+If you have any questions, suggestions, patches, etc., related to CFFI
+      module feel free to contact us on the SWIG mailing list, and
+      also please add a "[CFFI]" tag in the subject line.
+
+<H3><a name="Lisp_nn7"></a>21.2.4 Inserting user code into generated files</H3>
+
+
+<p>
+It is often necessary to <a href="SWIG.html#SWIG_nn40">include user-defined code</a> 
+into the automatically generated interface files. For example, when building
+a C++ interface, example_wrap.cxx will likely not compile unless
+you add a <tt>#include "header.h"</tt> directive. This can be done
+using the SWIG <tt>%insert(section) %{ ...code... %}</tt> directive:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+%insert("runtime") %{
+#include "header.h"
+%}
+
+%include "header.h"
+
+int fact(int n);
+</pre>
+</div>
+
+<p>
+Additional sections have been added for inserting into the
+generated lisp interface file:
+</p>
+<ul>
+  <li><tt>lisphead</tt> - inserts before type declarations</li>
+  <li><tt>swiglisp</tt> - inserts after type declarations according to
+    where it appears in the .i file</li>
+</ul>
+<p>
+Note that the block <tt>%{ ... %}</tt> is effectively a shortcut for
+<tt>%insert("runtime") %{ ... %}</tt>.
+</p>
+
+
+<H2><a name="Lisp_nn8"></a>21.3 CLISP</H2>
+
+
+<p>
+<a href="http://clisp.cons.org">CLISP</a> is a feature-loaded
+      implementation of common lisp which is portable across most of the
+      operating system environments and hardware. CLISP includes an
+      interpreter, a compiler, a debugger, CLOS, MOP, a foreign
+      language interface, i18n, regular expressions, a socket
+      interface, and more. An X11 interface is available through CLX,
+      Garnet and CLUE/CLIO. Command line editing is provided by
+      readline. CLISP runs Maxima, ACL2 and many other Common Lisp
+      packages.
+</p>
+<p>
+      To run the clisp module of SWIG requires very little effort, you
+      just need to execute:
+</p>
+<div class="code"><pre>
+swig -clisp -module <i>module-name</i>   <i>file-name</i> 
+
+</pre></div>
+
+<p>
+    Because of the high level nature of the CLISP FFI, the bindings
+    generated by SWIG may not be absolutely correct, and you may need
+    to modify them. The good thing is that you don't need to complex 
+    interface file for the CLISP module. The CLISP module tries to
+    produce code which is both human readable and easily modifyable.
+</p>
+<H3><a name="Lisp_nn9"></a>21.3.1 Additional Commandline Options </H3>
+
+
+<p>
+The following table list the additional commandline options available for the CLISP module. They can also be seen by using: 
+</p>
+
+<div class="code"><pre>
+swig -clisp -help 
+</pre></div>
+<br/>
+<table summary="CLISP specific options">
+<tr>
+<th>CLISP specific options</th>
+</tr>
+
+<tr>
+<td>-extern-all</td>
+<td>If this option is given then clisp definitions for all the functions<br/>
+and global variables will be created otherwise only definitions for<br/>
+	    externed functions and variables are created. 
+</td>
+</tr>
+
+<tr>
+<td>-generate-typedef</td>
+<td>If this option is given then def-c-type will be used to generate<br/>
+	    shortcuts according to the typedefs in the input.
+</td>
+</tr>
+
+</table>
+
+<H3><a name="Lisp_nn10"></a>21.3.2 Details on CLISP bindings</H3>
+
+
+<p>
+As mentioned earlier the CLISP bindings generated by SWIG may need
+	some modifications. The clisp module creates a lisp file with
+	the same name as the module name. This
+	lisp file contains a 'defpackage' declaration, with the
+	package name same as the module name. This package uses the
+	'common-lisp' and 'ffi' packages. Also, package exports all
+	the functions, structures and variables for which an ffi
+	binding was generated.<br/>
+     After generating the defpackage statement, the clisp module also
+	sets the default language.
+
+<div class="targetlang"><pre>
+(defpackage :test
+    (:use :common-lisp :ffi)
+  (:export
+   :make-bar
+   :bar-x
+   :bar-y
+   :bar-a
+   :bar-b
+   :bar-z
+   :bar-n
+   :pointer_func
+   :func123
+   :make-cfunr
+   :lispsort_double
+   :test123))
+
+(in-package :test)
+
+(default-foreign-language :stdc)
+</pre></div>
+<p>
+The ffi wrappers for functions and variables are generated as shown
+      below. When functions have arguments of type "double * array",
+      SWIG doesn't knows whether it is an 'out' argument or it is
+      an array which will be passed, so SWIG plays it safe by
+      declaring it as an '(array (ffi:c-ptr DOUBLE-FLOAT))'. For
+      arguments of type "int **z[100]" where SWIG has more
+      information, i.e., it knows that 'z' is an array of pointers to
+      pointers of integers, SWIG defines it to be '(z (ffi:c-ptr
+      (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))'  
+</p>
+<div class="code"><pre>
+extern "C" {
+int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y);
+
+int func123(div_t * x,int **z[100],int y[][1000][10]);
+
+void lispsort_double (int n, double * array);
+
+void test123(float x , double y);
+
+}
+</pre></div>
+<div class="targetlang"><pre>
+(ffi:def-call-out pointer_func
+    (:name "pointer_func")
+  (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL))
+						      (arg1 (ffi:c-pointer NIL))
+						      (arg2 (ffi:c-pointer NIL)))
+					  (:return-type NIL)))
+	      (y ffi:int))
+  (:return-type ffi:int)
+  (:library +library-name+))
+
+(ffi:def-call-out func123
+    (:name "func123")
+  (:arguments (x (ffi:c-pointer div_t))
+	      (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))
+	      (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10))))))
+  (:return-type ffi:int)
+  (:library +library-name+))
+
+
+(ffi:def-call-out lispsort_double
+    (:name "lispsort_double")
+  (:arguments (n ffi:int)
+	      (array (ffi:c-ptr DOUBLE-FLOAT)))
+  (:return-type NIL)
+  (:library +library-name+))
+
+(ffi:def-call-out test123
+    (:name "test")
+  (:arguments (x SINGLE-FLOAT)
+	      (y DOUBLE-FLOAT))
+  (:return-type NIL)
+  (:library +library-name+))
+
+</pre></div>
+
+<p>
+The module also handles strutcures and #define constants as shown
+      below. SWIG automatically adds the constructors and accessors
+    created for the struct to the list of symbols exported by the
+      package.
+</p>
+<div class="code"><pre>
+struct bar {
+    short x, y;
+    char a, b;
+    int *z[1000];
+    struct bar * n;
+};
+
+#define max 1000
+</pre></div>
+<div class="targetlang"><pre>
+(ffi:def-c-struct bar
+    (x :type ffi:short)
+  (y :type ffi:short)
+  (a :type character)
+  (b :type character)
+  (z :type (ffi:c-array (ffi:c-ptr ffi:int) 1000))
+  (n :type (ffi:c-pointer bar)))
+
+(defconstant max 1000)
+
+</pre></div>
+
+<H2><a name="Lisp_nn11"></a>21.4 UFFI </H2>
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Lua.html b/trunk/Doc/Manual/Lua.html
new file mode 100644
index 0000000..4ebf023
--- /dev/null
+++ b/trunk/Doc/Manual/Lua.html
@@ -0,0 +1,1322 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Lua</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Lua_nn1"></a>22 SWIG and Lua</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Lua_nn2">Preliminaries</a>
+<li><a href="#Lua_nn3">Running SWIG</a>
+<ul>
+<li><a href="#Lua_nn4">Compiling and Linking and Interpreter</a>
+<li><a href="#Lua_nn5">Compiling a dynamic module</a>
+<li><a href="#Lua_nn6">Using your module</a>
+</ul>
+<li><a href="#Lua_nn7">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="#Lua_nn8">Modules</a>
+<li><a href="#Lua_nn9">Functions</a>
+<li><a href="#Lua_nn10">Global variables</a>
+<li><a href="#Lua_nn11">Constants and enums</a>
+<li><a href="#Lua_nn12">Pointers</a>
+<li><a href="#Lua_nn13">Structures</a>
+<li><a href="#Lua_nn14">C++ classes</a>
+<li><a href="#Lua_nn15">C++ inheritance</a>
+<li><a href="#Lua_nn16">Pointers, references, values, and arrays</a>
+<li><a href="#Lua_nn17">C++ overloaded functions</a>
+<li><a href="#Lua_nn18">C++ operators</a>
+<li><a href="#Lua_nn19">Class extension with %extend</a>
+<li><a href="#Lua_nn20">C++ templates</a>
+<li><a href="#Lua_nn21">C++ Smart Pointers</a>
+<li><a href="#Lua_nn22">C++ Exceptions</a>
+<li><a href="#Lua_nn23">Writing your own custom wrappers</a>
+<li><a href="#Lua_nn24">Adding additional Lua code</a>
+</ul>
+<li><a href="#Lua_nn25">Details on the Lua binding</a>
+<ul>
+<li><a href="#Lua_nn26">Binding global data into the module.</a>
+<li><a href="#Lua_nn27">Userdata and Metatables</a>
+<li><a href="#Lua_nn28">Memory management</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). Its also a <em>really</em> tiny language, less than 6000 lines of code, which compiles to &lt;100 kilobytes of binary code. It can be found at <a href="http://www.lua.org">http://www.lua.org</a>
+</p>
+<H2><a name="Lua_nn2"></a>22.1 Preliminaries</H2>
+
+
+<p>
+The current SWIG implementation is designed to work with Lua 5.0.x and Lua 5.1.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. ((Currently SWIG generated code has only been tested on Windows with MingW, though given the nature of Lua, is should not have problems on other OS's)). It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms).
+</p>
+<H2><a name="Lua_nn3"></a>22.2 Running SWIG</H2>
+
+
+<p>
+Suppose that you defined a SWIG module such as the following:
+</p>
+<div class="code"><pre>
+%module example
+%{
+#include "example.h"
+%}
+int gcd(int x, int y);
+extern double Foo;
+</pre></div>
+<p>
+To build a Lua module, run SWIG using the <tt>-lua</tt> option.
+</p>
+<div class="shell"><pre>
+$ swig -lua example.i
+</pre></div>
+<p>
+If building a C++ extension, add the <tt>-c++</tt> option:
+</p>
+<div class="shell"><pre>
+$ swig -c++ -lua example.i
+</pre></div>
+<p>
+This creates a C/C++ source file <tt>example_wrap.c</tt> or <tt>example_wrap.cxx</tt>. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module.
+</p>
+<p>
+The name of the wrapper file is derived from the name of the input file. For example, if the input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>. To change this, you can use the -o option. The wrappered module will export one function <tt>"int luaopen_example(lua_State* L)"</tt> which must be called to register the module with the Lua interpreter. The name "luaopen_example" depends upon the name of the module.
+</p>
+<H3><a name="Lua_nn4"></a>22.2.1 Compiling and Linking and Interpreter</H3>
+
+
+<p>
+Normally Lua is embedded into another program and will be statically linked. An extremely simple stand-alone interpreter (<tt>min.c</tt>) is given below:
+</p>
+<div class="code"><pre>
+#include &lt;stdio.h&gt;
+#include "lua.h"
+#include "lualib.h"
+#include "lauxlib.h"
+
+extern int luaopen_example(lua_State* L); // declare the wrapped module
+
+int main(int argc,char* argv[])
+{
+ lua_State *L;
+ if (argc&lt;2)
+ {
+  printf("%s: &lt;filename.lua&gt;\n",argv[0]);
+  return 0;
+ }
+ L=lua_open();
+ luaopen_base(L);	// load basic libs (eg. print)
+ luaopen_example(L);	// load the wrappered module
+ if (luaL_loadfile(L,argv[1])==0) // load and run the file
+  lua_pcall(L,0,0,0);
+ else
+  printf("unable to load %s\n",argv[1]);
+ lua_close(L);
+ return 0;
+}
+</pre></div>
+<p>
+A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example",luaopen_example}</tt>, at the relevant place.
+</p>
+<p>
+The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this:
+</p>
+<div class="shell"><pre>
+$ swig -lua example.i -o example_wrap.c
+$ gcc -I/usr/include/lua -c min.c -o min.o
+$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
+$ gcc -c example.c -o example.o
+$ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
+</pre></div>
+
+<H3><a name="Lua_nn5"></a>22.2.2 Compiling a dynamic module</H3>
+
+
+<p>
+Most, but not all platforms support the dynamic loading of modules (Windows &amp; Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the same wrapper can  be used. The commands will be something like this:
+</p>
+<div class="shell"><pre>
+$ swig -lua example.i -o example_wrap.c
+$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
+$ gcc -c example.c -o example.o
+$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
+</pre></div>
+<p>
+The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x. The loading is extremely simple.
+</p>
+<div class="targetlang"><pre>
+require("example")
+</pre></div>
+<p>
+For those using Lua 5.0.x, you will also need an interpreter with the loadlib function (such as the default interpreter compiled with Lua). In order to dynamically load a module you must call the loadlib function with two parameters: the filename of the shared library, and the function exported by SWIG. Calling loadlib should return the function, which you then call to initialise the module
+</p>
+<div class="targetlang"><pre>
+my_init=loadlib("example.so","luaopen_example") -- for Unix/Linux
+--my_init=loadlib("example.dll","luaopen_example") -- for Windows
+assert(my_init) -- name sure its not nil
+my_init()       -- call the init fn of the lib
+</pre></div>
+<p>
+Or can be done in a single line of Lua code
+</p>
+<div class="targetlang"><pre>
+assert(loadlib("example.so","luaopen_example"))()
+</pre></div>
+
+
+<p>
+If the code didn't work, don't panic. The best thing to do is to copy the module and your interpreter into a single directory and then execute the interpreter and try to manually load the module (take care, all this code is case sensitive).
+</p>
+<div class="targetlang"><pre>
+a,b,c=package.loadlib("example.so","luaopen_example") -- for Unix/Linux
+--a,b,c=package.loadlib("example.dll","luaopen_example") -- for Windows
+print(a,b,c)
+</pre></div>
+<p>
+Note: for Lua 5.0:<br>
+The loadlib() function is in the global namespace, not in package. So its just loadlib().
+</p>
+<p>
+if 'a' is a function, this its all working fine, all you need to do is call it
+</p>
+<div class="targetlang"><pre>
+  a()
+</pre></div>
+<p>
+to load your library which will add a table 'example' with all the functions added.
+</p>
+<p>
+If it doesn't work, look at the error messages, in particular mesage 'b'<br>
+<tt>  The specified module could not be found.</tt><br>
+Means that is cannot find the module, check your the location and spelling of the module.<br>
+<tt>  The specified procedure could not be found.</tt><br>
+Means that it loaded the module, but cannot find the named function. Again check the spelling, and if possible check to make sure the functions were exported correctly.<br>
+<tt>  'loadlib' not installed/supported</tt><br>
+Is quite obvious (Go back and consult the Lua documents on how to enable loadlib for your platform).
+</p>
+
+
+
+<H3><a name="Lua_nn6"></a>22.2.3 Using your module</H3>
+
+
+<p>
+Assuming all goes well, you will be able to this:
+</p>
+<div class="targetlang"><pre>
+$ ./my_lua
+&gt; print(example.gcd(4,6))
+2
+&gt; print(example.Foo)
+3
+&gt; example.Foo=4
+&gt; print(example.Foo)
+4
+&gt;
+</pre></div>
+
+<H2><a name="Lua_nn7"></a>22.3 A tour of basic C/C++ wrapping</H2>
+
+
+<p>
+By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.
+</p>
+<H3><a name="Lua_nn8"></a>22.3.1 Modules</H3>
+
+
+<p>
+The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.
+</p>
+<H3><a name="Lua_nn9"></a>22.3.2 Functions</H3>
+
+
+<p>
+ Global functions are wrapped as new Lua built-in functions. For example,
+</p>
+<div class="code"><pre>
+%module example
+int fact(int n);</pre></div>
+<p>
+creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does:
+</p>
+
+<div class="targetlang"><pre>
+&gt; print example.fact(4)
+24
+&gt;
+</pre></div>
+<p>
+To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care.
+</p>
+<div class="targetlang"><pre>
+&gt; for k,v in pairs(example) do _G[k]=v end
+&gt; print(fact(4))
+24
+&gt;
+</pre></div>
+<p>
+It is also possible to rename the module with an assignment.
+</p>
+<div class="targetlang"><pre>
+&gt; e=example
+&gt; print(e.fact(4))
+24
+&gt; print(example.fact(4))
+24
+</pre></div>
+
+<H3><a name="Lua_nn10"></a>22.3.3 Global variables</H3>
+
+
+<p>
+ Global variables (which are linked to C code) are supported, and appear to be just another variable in Lua. However the actual mechanism is more complex. Given a global variable:
+</p>
+
+<div class="code"><pre>%module example
+extern double Foo;
+</pre></div>
+<p>
+SWIG will effectively generate two functions <tt>example.Foo_set()</tt> and <tt>example.Foo_get()</tt>. It then adds a metatable to the table 'example' to call these functions at the correct time (when you attempt to set or get examples.Foo). Therefore if you were to attempt to assign the global to another variable, you will get a local copy within the interpreter, which is no longer linked to the C code.
+</p>
+
+<div class="targetlang"><pre>
+&gt; print(example.Foo)
+3
+&gt; c=example.Foo   -- c is a COPY of example.Foo, not the same thing
+&gt; example.Foo=4
+&gt; print(c)
+3
+&gt; c=5 -- this will not effect the original example.Foo
+&gt; print(example.Foo,c)
+4    5
+</pre></div>
+<p>
+Its is therefore not possible to 'move' the global variable into the global namespace as it is with functions. It is however, possible to rename the module with an assignment, to make it more convenient.
+</p>
+<div class="targetlang"><pre>
+&gt; e=example
+&gt; -- e and example are the same table
+&gt; -- so e.Foo and example.Foo are the same thing
+&gt; example.Foo=4
+&gt; print(e.Foo)
+4
+</pre></div>
+<p>
+If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Lua error. Given a global variable:
+</p>
+
+<div class="code"><pre>%module example
+%immutable;
+extern double Foo;
+%mutable;
+</pre></div>
+<p>
+SWIG will allow the the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
+</p>
+<div class="targetlang"><pre>
+&gt; print(e.Foo) -- reading works ok
+4
+&gt; example.Foo=40 -- but writing does not
+This variable is immutable
+stack traceback:
+        [C]: ?
+        [C]: ?
+        stdin:1: in main chunk
+        [C]: ?
+</pre></div>
+<p>
+For those people who would rather that SWIG silently ignore the setting of immutables (as previous versions of the Lua bindings did), adding a <tt>-DSWIGLUA_IGNORE_SET_IMMUTABLE</tt> compile option will remove this.
+</p>
+<p>
+Unlike earlier versions of the binding, it is now possible to add new functions or variables to the module, just as if it were a normal table. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so.
+</p>
+<div class="targetlang"><pre>
+&gt; -- example.PI does not exist
+&gt; print(example.PI)
+nil
+&gt; example.PI=3.142 -- new value added
+&gt; print(example.PI)
+3.142
+</pre></div>
+
+<H3><a name="Lua_nn11"></a>22.3.4 Constants and enums</H3>
+
+
+<p>
+Because Lua doesn't really have the concept of constants, C/C++ constants are not really constant in Lua. They are actually just a copy of the value into the Lua interpreter. Therefore they can be changed just as any other value. For example given some constants:
+</p>
+<div class="code"><pre>%module example
+%constant int ICONST=42;
+#define    SCONST      "Hello World"
+enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
+</pre></div>
+<p>
+This is 'effectively' converted into the following Lua code:
+</p>
+<div class="targetlang"><pre>
+example.ICONST=42
+example.SCONST="Hello World"
+example.SUNDAY=0
+....
+</pre></div>
+<p>
+Constants are not guaranteed to remain constant in Lua. The name of the constant could be accidentally reassigned to refer to some other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.
+</p>
+<H3><a name="Lua_nn12"></a>22.3.5 Pointers</H3>
+
+
+<p>
+C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the &lt;file.h&gt; interface:
+</p>
+<div class="code"><pre>%module example
+
+FILE *fopen(const char *filename, const char *mode);
+int fputs(const char *, FILE *);
+int fclose(FILE *);
+</pre></div>
+<p>
+When wrapped, you will be able to use the functions in a natural way from Lua. For example:
+</p>
+<div class="targetlang"><pre>
+&gt; f=example.fopen("junk","w")
+&gt; example.fputs("Hello World",f)
+&gt; example.fclose(f)
+</pre></div>
+<p>
+Unlike many scripting languages, Lua has had support for pointers to C/C++ object built in for a long time. They are called 'userdata'. Unlike many other SWIG versions which use some kind of encoded character string, all objects will be represented as a userdata. The SWIG-Lua bindings provides a special function <tt>swig_type()</tt>, which if given a userdata object will return the type of object pointed to as a string (assuming it was a SWIG wrappered object).
+</p>
+<div class="targetlang"><pre>
+&gt; print(f)
+userdata: 003FDA80
+&gt; print(swig_type(f))
+FILE * -- its a FILE*
+</pre></div>
+<p>
+Lua enforces the integrity of its userdata, so it is virtually impossible to corrupt the data. But as the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes &amp; structs (see below). One final note: if a function returns a NULL pointer, this is not encoded as a userdata, but as a Lua nil.
+</p>
+<div class="targetlang"><pre>
+&gt; f=example.fopen("not there","r") -- this will return a NULL in C
+&gt; print(f)
+nil
+</pre></div>
+
+<H3><a name="Lua_nn13"></a>22.3.6 Structures</H3>
+
+
+<p>
+ If you wrap a C structure, it is also mapped to a Lua userdata. By adding a metatable to the userdata, this provides a very natural interface. For example,
+</p>
+<div class="code"><pre>struct Point{
+  int x,y;
+};
+</pre></div>
+<p>
+is used as follows:
+</p>
+<div class="targetlang"><pre>
+&gt; p=example.new_Point()
+&gt; p.x=3
+&gt; p.y=5
+&gt; print(p.x,p.y)
+3       5
+&gt;
+</pre></div>
+<p>
+Similar access is provided for unions and the data members of C++ classes.<br>
+C structures are created using a function <tt>new_Point()</tt>, but for C++ classes are created using just the name <tt>Point()</tt>.
+</p>
+<p>
+If you print out the value of p in the above example, you will see something like this:
+</p>
+<div class="targetlang"><pre>
+&gt; print(p)
+userdata: 003FA320
+</pre></div>
+<p>
+Like the pointer in the previous section, this is held as a userdata. However, additional features have been added to make this more usable. SWIG effectivly creates some accessor/mutator functions to get and set the data. These functions will be added to the userdata's metatable. This provides the natural access to the member variables that were shown above (see end of the document for full details).
+</p>
+<p>
+<tt>const</tt> members of a structure are read-only. Data members can also be forced to be read-only using the immutable directive. As with other immutable's, setting attempts will be cause an error. For example:
+</p>
+<div class="code"><pre>struct Foo {
+   ...
+   %immutable;
+   int x;        // Read-only members
+   char *name;
+   %mutable;
+   ...
+};
+</pre></div>
+<p>
+The mechanism for managing char* members as well as array members is similar to other languages. It is somewhat cumbersome and should probably be better handled by defining of typemaps (described later).
+</p>
+<p>
+When a member of a structure is itself a structure, it is handled as a pointer. For example, suppose you have two structures like this:
+</p>
+
+<div class="code"><pre>struct Foo {
+   int a;
+};
+
+struct Bar {
+   Foo f;
+};
+</pre></div>
+<p>
+Now, suppose that you access the f attribute of Bar like this:
+</p>
+<div class="targetlang"><pre>
+&gt; b = Bar()
+&gt; x = b.f
+</pre></div>
+<p>
+In this case, x is a pointer that points to the Foo that is inside b. This is the same value as generated by this C code:
+</p>
+<div class="code"><pre>
+Bar b;
+Foo *x = &amp;b-&gt;f;       // Points inside b
+</pre></div>
+<p>
+Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:
+</p>
+<div class="targetlang"><pre>
+&gt; b = Bar()
+&gt; b.f.a = 3               -- Modify attribute of structure member
+&gt; x = b.f
+&gt; x.a = 3                 -- Modifies the same structure
+</pre></div>
+
+<H3><a name="Lua_nn14"></a>22.3.7 C++ classes</H3>
+
+
+<p>
+C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
+</p>
+<div class="code"><pre>class List {
+public:
+  List();
+  ~List();
+  int  search(char *item);
+  void insert(char *item);
+  void remove(char *item);
+  char *get(int n);
+  int  length;
+};
+</pre></div>
+<p>
+you can use it in Lua like this:
+</p>
+<div class="targetlang"><pre>
+&gt; l = example.List()
+&gt; l:insert("Ale")
+&gt; l:insert("Stout")
+&gt; l:insert("Lager")
+&gt; print(l:get(1))
+Stout
+&gt; print(l:length)
+3
+&gt;
+</pre></div>
+<p>
+(Note: for calling methods of a class, you use <tt>class:method(args)</tt>, not <tt>class.method(args)</tt>, its an easy mistake to make. However for data attributes it is <tt>class.attribute</tt>)
+</p>
+<p>
+Class data members are accessed in the same manner as C structures. Static class members present a special problem for Lua, as Lua doesn't have support for such features. Therefore, SWIG generates wrappers that try to work around some of these issues. To illustrate, suppose you have a class like this:
+</p>
+<div class="targetlang"><pre>class Spam {
+public:
+   static void foo();
+   static int bar;
+
+};
+</pre></div>
+<p>
+In Lua, the static members can be accessed as follows:
+</p>
+<div class="code"><pre>
+&gt; example.Spam_foo()            -- calling Spam::foo()
+&gt; a=example.Spam_bar            -- reading Spam::bar 
+&gt; example.Spam_bar=b            -- writing to Spam::bar
+</pre></div>
+<p>
+It is not (currently) possible to access static members of an instance:
+</p>
+<div class="targetlang"><pre>
+&gt; s=example.Spam()      -- s is a Spam instance
+&gt; s.foo()                       -- Spam::foo() via an instance
+                                -- does NOT work
+</pre></div>
+
+<H3><a name="Lua_nn15"></a>22.3.8 C++ inheritance</H3>
+
+
+<p>
+SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
+</p>
+<div class="code"><pre>class Foo {
+...
+};
+
+class Bar : public Foo {
+...
+};
+</pre></div>
+<p>
+And if you have functions like this
+</p>
+<div class="code"><pre>void spam(Foo *f);
+</pre></div>
+<p>
+then the function <tt>spam()</tt> accepts a Foo pointer or a pointer to any class derived from Foo.
+</p>
+<p>
+It is safe to use multiple inheritance with SWIG.
+</p>
+<H3><a name="Lua_nn16"></a>22.3.9 Pointers, references, values, and arrays</H3>
+
+
+<p>
+In C++, there are many different ways a function might receive and manipulate objects. For example:
+</p>
+<div class="code"><pre>void spam1(Foo *x);      // Pass by pointer
+void spam2(Foo &amp;x);      // Pass by reference
+void spam3(Foo x);       // Pass by value
+void spam4(Foo x[]);     // Array of objects
+</pre></div>
+<p>
+In SWIG, there is no detailed distinction like this--specifically, there are only "objects". There are no pointers, references, arrays, and so forth. Because of this, SWIG unifies all of these types together in the wrapper code. For instance, if you actually had the above functions, it is perfectly legal to do this:
+</p>
+<div class="targetlang"><pre>
+&gt; f = Foo()           -- Create a Foo
+&gt; spam1(f)            -- Ok. Pointer
+&gt; spam2(f)            -- Ok. Reference
+&gt; spam3(f)            -- Ok. Value.
+&gt; spam4(f)            -- Ok. Array (1 element)
+</pre></div>
+<p>
+Similar behaviour occurs for return values. For example, if you had functions like this,
+</p>
+<div class="code"><pre>Foo *spam5();
+Foo &amp;spam6();
+Foo  spam7();
+</pre></div>
+<p>
+then all three functions will return a pointer to some Foo object. Since the third function (spam7) returns a value, newly allocated memory is used to hold the result and a pointer is returned (Lua will release this memory when the return value is garbage collected). The other two are pointers which are assumed to be managed by the C code and so will not be garbage collected.
+</p>
+<H3><a name="Lua_nn17"></a>22.3.10 C++ overloaded functions</H3>
+
+
+<p>
+C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
+</p>
+<div class="code"><pre>void foo(int);
+void foo(char *c);
+</pre></div>
+<p>
+You can use them in Lua in a straightforward manner:
+</p>
+<div class="targetlang"><pre>
+&gt; foo(3)           -- foo(int)
+&gt; foo("Hello")     -- foo(char *c)
+</pre></div>
+<p>
+However due to Lua's coercion mechanism is can sometimes do strange things.
+</p>
+<div class="targetlang"><pre>
+&gt; foo("3")           -- "3" can be coerced into an int, so it calls foo(int)!
+</pre></div>
+<p>
+As this coercion mechanism is an integral part of Lua, there is no easy way to get around this other than renaming of functions (see below).
+</p>
+<p>
+Similarly, if you have a class like this,
+</p>
+<div class="code"><pre>class Foo {
+public:
+    Foo();
+    Foo(const Foo &amp;);
+    ...
+};
+</pre></div>
+<p>
+you can write Lua code like this:
+</p>
+<div class="targetlang"><pre>
+&gt; f = Foo()          -- Create a Foo
+&gt; g = Foo(f)         -- Copy f
+</pre></div>
+<p>
+Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:
+</p>
+<div class="code"><pre>void spam(int);
+void spam(short);
+</pre></div>
+<p>
+or
+</p>
+<DIV CLASS="CODE"><PRE>VOID FOO(bAR *B);
+void foo(Bar &amp;b);
+</pre></div>
+<p>
+If declarations such as these appear, you will get a warning message like this:
+</p>
+<div class="shell"><pre>
+example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
+at example.i:11.
+</pre></div>
+<p>
+ To fix this, you either need to ignore or rename one of the methods. For example:
+</p>
+<div class="code"><pre>%rename(spam_short) spam(short);
+...
+void spam(int);
+void spam(short);   // Accessed as spam_short
+</pre></div>
+<p>
+or
+</p>
+<div class="code"><pre>%ignore spam(short);
+...
+void spam(int);
+void spam(short);   // Ignored
+</pre></div>
+<p>
+SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.
+</p>
+<p>
+Please refer to the "SWIG and C++" chapter for more information about overloading.
+</p>
+<p>
+Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.
+</p>
+<H3><a name="Lua_nn18"></a>22.3.11 C++ operators</H3>
+
+
+<p>
+Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
+</p>
+<div class="code"><pre>class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &amp;operator=(const Complex &amp;c);
+  Complex operator+(const Complex &amp;c) const;
+  Complex operator-(const Complex &amp;c) const;
+  Complex operator*(const Complex &amp;c) const;
+  Complex operator-() const;
+
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+</pre></div>
+<p>
+When wrapped, it works like you expect:
+</p>
+<div class="targetlang"><pre>
+&gt; c = Complex(3,4)
+&gt; d = Complex(7,8)
+&gt; e = c + d
+&gt; e:re()
+10.0
+&gt; e:im()
+12.0
+</pre></div>
+<p>
+One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this
+</p>
+<div class="targetlang"><pre>class Complex {
+...
+friend Complex operator+(double, const Complex &amp;c);
+...
+};
+</pre></div>
+<p>
+then SWIG doesn't know what to do with the friend function--in fact, it simply ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example:
+</p>
+<div class="targetlang"><pre>%rename(Complex_add_dc) operator+(double, const Complex &amp;);
+...
+Complex operator+(double, const Complex &amp;c);
+</pre></div>
+<p>
+There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive. Keep reading.
+</p>
+<p>
+Also, be aware that certain operators don't map cleanly to Lua, and some Lua operators don't map cleanly to C++ operators. For instance, overloaded assignment operators don't map to Lua semantics and will be ignored, and C++ doesn't support Lua's concatenation operator (<tt>..</tt>).
+</p>
+<p>
+In order to keep maximum compatibility within the different languages in SWIG, the Lua bindings uses the same set of operator names as python. Although internally it renames the functions to something else (on order to work with Lua).
+<p>
+The current list of operators which can be overloaded (and the alternative function names) are:<ul>
+<li><tt>__add__</tt> operator+
+<li><tt>__sub__</tt> operator-
+<li><tt>__mul__</tt> operator *
+<li><tt>__div__</tt> operator/
+<li><tt>__neg__</tt> unary minus
+<li><tt>__call__</tt> operator<tt>()</tt> (often used in functor classes)
+<li><tt>__pow__</tt> the exponential fn (no C++ equivalent, Lua uses <tt>^</tt>)
+<li><tt>__concat__</tt> the concatenation operator (SWIG maps C++'s <tt>~</tt> to Lua's <tt>..</tt>)
+<li><tt>__eq__</tt> operator<tt>==</tt>
+<li><tt>__lt__</tt> operator<tt>&lt;</tt>
+<li><tt>__le__</tt> operator<tt>&lt;=</tt>
+</ul>
+<p>
+Note: in Lua, only the equals, less than, and less than equals operators are defined. The other operators (!=,&gt;,&gt;=) are achieved by using a logical not applied to the results of other operators.
+</p>
+<p>
+The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul>
+<li>++ and --<li>+=,-=,*= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul>
+<p>
+SWIG also accepts the <tt>__str__()</tt> member function which converts an object to a string. This function should return a const char*, preferably to static memory. This will be used for the <tt>print()</tt> and <tt>tostring()</tt> functions in Lua. Assuming the complex class has a function
+</p>
+<div class="code"><pre>const char* __str__()
+{
+        static char buffer[255];
+        sprintf(buffer,"Complex(%g,%g)",this-&gt;re(),this-&gt;im());
+        return buffer;
+}
+</pre></div>
+<p>
+Then this will support the following code in Lua
+</p>
+<div class="targetlang"><pre>
+&gt; c = Complex(3,4)
+&gt; d = Complex(7,8)
+&gt; e = c + d
+&gt; print(e)
+Complex(10,12)
+&gt; s=tostring(e) -- s is the number in string form
+&gt; print(s)
+Complex(10,12)
+</pre></div>
+<p>
+It is also possible to overload the operator<tt>[]</tt>, but currently this cannot be automatically performed. To overload the operator<tt>[]</tt> you need to provide two functions, <tt>__getitem__()</tt> and <tt>__setitem__()</tt>
+</p>
+<div class="code"><pre>class Complex
+{
+        //....
+        double __getitem__(int i)const; // i is the index, returns the data
+        void __setitem__(int i,double d); // i is the index, d is the data
+};
+</pre></div>
+
+<H3><a name="Lua_nn19"></a>22.3.12 Class extension with %extend</H3>
+
+
+<p>
+ One of the more interesting features of SWIG is that it can extend structures and classes with new methods. In the previous section, the Complex class would have benefited greatly from an __str__() method as well as some repairs to the operator overloading. It can also be used to add additional functions to the class if they are needed.
+</p>
+<p>
+Take the original Complex class
+</p>
+<div class="code"><pre>class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &amp;operator=(const Complex &amp;c);
+  Complex operator+(const Complex &amp;c) const;
+  Complex operator-(const Complex &amp;c) const;
+  Complex operator*(const Complex &amp;c) const;
+  Complex operator-() const;
+
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+</pre></div>
+<p>
+Now we extend it with some new code
+</p>
+<div class="code"><pre>%extend Complex {
+   const char *__str__() {
+       static char tmp[1024];
+       sprintf(tmp,"Complex(%g,%g)", $self-&gt;re(),$self-&gt;im());
+       return tmp;
+   }
+   bool operator==(const Complex&amp; c)
+   {    return ($self-&gt;re()==c.re() &amp;&amp; $self-&gt;im()==c.im();}
+};
+</pre></div>
+<p>
+Now, in Lua
+</p>
+<div class="targetlang"><pre>
+&gt; c = Complex(3,4)
+&gt; d = Complex(7,8)
+&gt; e = c + d
+&gt; print(e)      -- print uses __str__ to get the string form to print
+Complex(10,12)
+&gt; print(e==Complex(10,12))      -- testing the == operator
+true
+&gt; print(e!=Complex(12,12))  -- the != uses the == operator
+true
+</pre></div>
+<p>
+Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the '$self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).
+</p>
+<H3><a name="Lua_nn20"></a>22.3.13 C++ templates</H3>
+
+
+<p>
+ C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the template directive. For example:
+</p>
+<div class="code"><pre>%module example
+%{
+#include "pair.h"
+%}
+
+template&lt;class T1, class T2&gt;
+struct pair {
+   typedef T1 first_type;
+   typedef T2 second_type;
+   T1 first;
+   T2 second;
+   pair();
+   pair(const T1&amp;, const T2&amp;);
+  ~pair();
+};
+
+%template(pairii) pair&lt;int,int&gt;;
+</pre></div>
+<p>
+In Lua:
+</p>
+<div class="targetlang"><pre>
+&gt; p = example.pairii(3,4)
+&gt; print(p.first,p.second)
+3    4
+</pre></div>
+<p>
+Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.
+</p>
+<H3><a name="Lua_nn21"></a>22.3.14 C++ Smart Pointers</H3>
+
+
+<p>
+ In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator-&gt;() like this:
+</p>
+<div class="code"><pre>template&lt;class T&gt; class SmartPtr {
+   ...
+   T *operator-&gt;();
+   ...
+}
+</pre></div>
+<p>
+Then, if you have a class like this,
+</p>
+<div class="code"><pre>class Foo {
+public:
+     int x;
+     int bar();
+};
+</pre></div>
+<p>
+A smart pointer would be used in C++ as follows:
+</p>
+<div class="code"><pre>SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
+...
+p-&gt;x = 3;                        // Foo::x
+int y = p-&gt;bar();                // Foo::bar
+</pre></div>
+<p>
+To wrap this, simply tell SWIG about the SmartPtr class and the low-level Foo object. Make sure you instantiate SmartPtr using template if necessary. For example:
+</p>
+<div class="code"><pre>%module example
+...
+%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
+...
+</pre></div>
+<p>
+Now, in Lua, everything should just "work":
+</p>
+<div class="targetlang"><pre>
+&gt; p = example.CreateFoo()          -- Create a smart-pointer somehow
+&gt; p.x = 3                          -- Foo::x
+&gt; print(p:bar())                   -- Foo::bar
+</pre></div>
+<p>
+If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method. For example:
+</p>
+<div class="targetlang"><pre>
+&gt; f = p:__deref__()     -- Returns underlying Foo *
+</pre></div>
+
+<H3><a name="Lua_nn22"></a>22.3.15 C++ Exceptions</H3>
+
+
+<p>
+Lua does not natively support exceptions, but it has errors which are similar. When a Lua function terminates with an error
+it returns one value back to the caller. SWIG automatically maps any basic type which is thrown into a Lua error.
+Therefore for a function:
+</p>
+<div class="code"><pre>
+int message() throw(const char *) {
+  throw("I died.");
+  return 1;
+}
+</pre></div>
+<p>
+SWIG will automatically convert this to a Lua error.
+</p>
+
+<div class="targetlang"><pre>
+> message()
+I died.
+stack traceback:
+        [C]: in function 'message'
+        stdin:1: in main chunk
+        [C]: ?
+>
+</pre></div>
+
+<p>
+If you want to catch an exception, you must use either pcall() or xpcall(), which are documented in the Lua manual.
+Using xpcall will allow you to obtain additional debug information (such as a stacktrace).
+</p>
+
+<div class="targetlang"><pre>
+> function a() b() end -- function a() calls function b()
+> function b() message() end -- function b() calls C++ function message(), which throws 
+> ok,res=pcall(a)  -- call the function
+> print(ok,res)
+false   I died.
+> ok,res=xpcall(a,debug.traceback)  -- call the function
+> print(ok,res)
+false   I died.
+stack traceback:
+        [C]: in function 'message'
+        runme.lua:70: in function 'b'
+        runme.lua:67: in function &lt;runme.lua:66&gt;
+        [C]: in function 'xpcall'
+        runme.lua:95: in main chunk
+        [C]: ?
+</pre></div>
+
+<p>
+SWIG is able to throw numeric types, enums, chars, char*'s and std::string's without problem.
+However its not so simple for to throw objects. 
+Thrown objects are not valid outside the 'catch' block. Therefore they cannot be
+returned to the interpreter. 
+The obvious ways to overcome this would be to either return a copy of the object, or so convert the object to a string and
+return that. Though it seems obvious to perform the former, in some cases this is not possible, most notably when
+SWIG has no information about the object, or the object is not copyable/creatable.
+</p>
+<p>
+Therefore by default SWIG converts all thrown object into strings and returns them. So given a function:
+</p>
+
+<div class="code"><pre>
+void throw_A() throw(A*) {
+  throw new A();
+}
+</pre></div>
+<p>
+SWIG will just convert it (poorly) to a string and use that as its error. (Yes its not that useful, but it always works).
+</p>
+
+<div class="targetlang"><pre>
+> throw_A()
+object exception:A *
+stack traceback:
+        [C]: in function 'unknown'
+        stdin:1: in main chunk
+        [C]: ?
+>
+</pre></div>
+<p>
+To get a more useful behaviour out of SWIG you must either: provide a way to convert your exceptions into strings, or
+throw objects which can be copied.
+</p>
+<p>
+SWIG has typemaps for std::exception and its children already written, so a function which throws any of these will
+automatically have its exception converted into an error string.
+</p>
+<p>
+If you have your own class which you want output as a string you will need to add a typemap something like this:
+</p>
+<div class="code"><pre>
+%typemap(throws) my_except
+%{ 
+  lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message
+  SWIG_fail; // trigger the error handler
+%}
+</pre></div>
+<p>
+If you wish your exception to be returned to the interpreter, it must firstly be copyable. Then you must have and additional
+<tt>%apply</tt> statement, to inform SWIG to return a copy of this object to the interpreter. For example:
+</p>
+<div class="code"><pre>
+%apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
+
+class Exc {
+public:
+  Exc(int c, const char *m) {
+    code = c;
+    strncpy(msg,m,256);
+  }
+  int code;
+  char msg[256];
+};
+
+void throw_exc() throw(Exc) {
+  throw(Exc(42,"Hosed"));
+} 
+</pre></div>
+<p>
+Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
+</p>
+<div class="targetlang"><pre>
+> ok,res=pcall(throw_exc)
+> print(ok)
+false
+> print(res)
+userdata: 0003D880
+> print(res.code,res.msg)
+42      Hosed
+>
+</pre></div>
+
+<p>
+Note: is is also possible (though tedious) to have a function throw several different kinds of exceptions. To process this
+will require a pcall, followed by a set of if statements checking the type of the error.
+</p>
+<p>
+All of this code assumes that your C++ code uses exception specification (which a lot doesn't).
+If it doesn't consult the "<a href="SWIGPlus.html#SWIGPlus_catches">Exception handling with %catches</a>" section
+and the "<a href="Customization.html#exception">Exception handling with %exception</a>" section, for more details on how to
+add exception specification to functions or globally (respectively).
+</p>
+
+
+<H3><a name="Lua_nn23"></a>22.3.16 Writing your own custom wrappers</H3>
+
+
+<p>
+Sometimes, it may be neccesary to add your own special functions, which bypass the normal SWIG wrappering method, and just use the native Lua API calls. These 'native' functions allow direct adding of your own code into the module. This is performed with the <tt>%native</tt> directive as follows:
+</p>
+<div class="code"><pre>%native(my_func) int native_function(lua_State*L);  // registers native_function() with SWIG
+...
+%{
+int native_function(lua_State*L) // my native code
+{
+ ...
+}
+%}
+</pre></div>
+<p>
+The <tt>%native</tt> directive in the above example, tells SWIG that there is a function <tt>int native_function(lua_State*L);</tt> which is to be added into the module under the name '<tt>my_func</tt>'. SWIG will not add any wrappering for this function, beyond adding it into the function table. How you write your code is entirely up to you.
+</p>
+
+<H3><a name="Lua_nn24"></a>22.3.17 Adding additional Lua code</H3>
+
+
+<p>
+As well as adding additional C/C++ code, its also possible to add your own Lua code to the module as well.
+This code is executed once all other initialisation, including the %init code has been called.
+</p>
+<p>
+The directive <tt>%luacode</tt> adds code into the module which is executed upon loading. Normally you would
+use this to add your own functions to the module. Though you could easily perform other tasks.
+</p>
+<div class="code"><pre>%module example;
+
+%luacode {
+  function example.greet() 
+    print "hello world" 
+  end
+
+  print "Module loaded ok"
+}
+...
+%}
+</pre></div>
+<p>
+Notice that the code is not part of the module table. Therefore any references to the module must have the 
+module name added.
+</p>
+<p>
+Should there be an error in the Lua code, this will <em>not</em> stop loading of the module.
+The default behaviour of SWIG is to print a error message to stderr and then continue. 
+It is possible to change this behaviour by using a <tt>#define SWIG_DOSTRING_FAIL(STR)</tt> to
+define a different behaviour should the code fail.
+</p>
+<p>
+Good uses for this feature is adding of new code, or writing helper functions to simplify some of the code.
+See Examples/lua/arrays for an example of this code.
+</p>
+
+<H2><a name="Lua_nn25"></a>22.4 Details on the Lua binding</H2>
+
+
+<p>
+ In the previous section, a high-level view of Lua wrapping was presented. Obviously a lot of stuff happens behind the scenes to make this happen. This section will explain some of the low-level details on how this is achieved.
+</p>
+<p>
+ <i>If you just want to use SWIG and don't care how it works, then stop reading here. This is going into the guts of the code and how it works. Its mainly for people who need to know whats going on within the code.
+ </i>
+</p>
+
+<H3><a name="Lua_nn26"></a>22.4.1 Binding global data into the module.</H3>
+
+
+<p>
+Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
+</p>
+<div class="code"><pre>%module example;
+extern double Foo;
+</pre></div>
+<p>
+SWIG will effectively generate the pair of functions
+</p>
+<div class="code"><pre>void Foo_set(double);
+double Foo_get();
+</pre></div>
+<p>
+At initialisation time, it will then add to the interpreter a table called 'example', which represents the module. It will then add all its functions to the module. (Note: older versions of SWIG actually added the Foo_set() and Foo_get() functions, current implementation does not add these functions any more.) But it also adds a metatable to this table, which has two functions (<tt>__index</tt> and <tt>__newindex</tt>) as well as two tables (<tt>.get</tt> and <tt>.set</tt>) The following Lua code will show these hidden features.
+</p>
+<div class="targetlang"><pre>
+&gt; print(example)
+table: 003F8F90
+&gt; m=getmetatable(example)
+&gt; table.foreach(m,print)
+.set    table: 003F9088
+.get    table: 003F9038
+__index function: 003F8FE0
+__newindex      function: 003F8FF8
+&gt; g=m['.get']
+&gt; table.foreach(g,print)
+Foo     function: 003FAFD8
+&gt;
+</pre></div>
+<p>
+The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set,Foo_get)
+</p>
+<p>
+The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
+</p>
+<div class="targetlang"><pre>
+function __index(mod,name)
+        local g=getmetatable(mod)['.get'] -- gets the table
+        if not g then return nil end
+        local f=g[name] -- looks for the function
+        -- calls it &amp; returns the value
+        if type(f)=="function" then return f() end
+        return nil
+end
+
+function __newindex(mod,name,value)
+        local s=getmetatable(mod)['.set'] -- gets the table
+        if not s then return end
+        local f=s[name] -- looks for the function
+        -- calls it to set the value
+        if type(f)=="function" then f(value)
+        else rawset(mod,name,value) end
+end
+</pre></div>
+<p>
+That way when you call '<tt>a=example.Foo</tt>', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code '<tt>example.Foo=10</tt>', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.
+</p>
+<H3><a name="Lua_nn27"></a>22.4.2 Userdata and Metatables</H3>
+
+
+<p>
+As mentioned earlier, classes and structures, are all held as pointer, using the Lua 'userdata' structure. This structure is actually a pointer to a C structure 'swig_lua_userdata', which contains the pointer to the data, a pointer to the swig_type_info (an internal SWIG struct) and a flag which marks if the object is to be disposed of when the interpreter no longer needs it. The actual accessing of the object is done via the metatable attached to this userdata.
+</p>
+<p>
+The metatable is a Lua 5.0 feature (which is also why SWIG cannot wrap Lua 4.0). Its a table which holds a list of functions, operators and attributes. This is what gives the userdata the feeling that it is a real object and not just a hunk of memory.
+</p>
+<p>
+Given a class
+</p>
+<div class="code"><pre>%module excpp;
+
+class Point
+{
+public:
+ int x,y;
+ Point(){x=y=0;}
+ ~Point(){}
+ virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);}
+};
+</pre></div>
+<p>
+SWIG will create a module excpp, with all the various function inside. However to allow the intuitive use of the userdata is also creates up a set of metatables. As seen in the above section on global variables, use of the metatables allows for wrappers to be used intuitively. To save effort, the code creates one metatable per class and stores it inside Lua's registry. Then when an new object is instantiated, the metatable is found in the registry and the userdata associated to the metatable. Currently derived classes make a complete copy of the base classes table and then add on their own additional function.
+</p>
+<p>
+Some of the internals can be seen by looking at a classes metatable.
+</p>
+<div class="targetlang"><pre>
+&gt; p=excpp.Point()
+&gt; print(p)
+userdata: 003FDB28
+&gt; m=getmetatable(p)
+&gt; table.foreach(m,print)
+.type   Point
+__gc    function: 003FB6C8
+__newindex      function: 003FB6B0
+__index function: 003FB698
+.get    table: 003FB4D8
+.set    table: 003FB500
+.fn     table: 003FB528
+</pre></div>
+<p>
+The '.type' attribute is the name of the class. The '.get' and '.set' tables work in a similar manner to the modules, the main difference is the '.fn' table which also holds all the member functions. (The '__gc' function is the classes destructor function)
+</p>
+<p>
+The Lua equivalent of the code for enabling functions looks a little like this
+</p>
+<div class="targetlang"><pre>
+function __index(obj,name)
+        local m=getmetatable(obj) -- gets the metatable
+        if not m then return nil end
+        local g=m['.get'] -- gets the attribute table
+        if not g then return nil end
+        local f=g[name] -- looks for the get_attribute function
+        -- calls it &amp; returns the value
+        if type(f)=="function" then return f() end
+        -- ok, so it not an attribute, maybe its a function
+        local fn=m['.fn'] -- gets the function table
+        if not fn then return nil end
+        local f=fn[name] -- looks for the function
+        -- if found the fn then return the function
+        -- so the interpreter can call it
+        if type(f)=="function" then return f end
+        return nil
+end
+</pre></div>
+<p>
+So when 'p:Print()' is called, the __index looks on the object metatable for a 'Print' attribute, then looks for a 'Print' function. When it finds the function, it returns the function, and then interpreter can call 'Point_Print(p)'
+</p>
+<p>
+In theory, you can play with this usertable &amp; add new features, but remember that it is a shared table between all instances of one class, and you could very easily corrupt the functions in all the instances.
+</p>
+<p>
+Note: Both the opaque structures (like the FILE*) and normal wrappered classes/structs use the same 'swig_lua_userdata' structure. Though the opaque structures has do not have a metatable attached, or any information on how to dispose of them when the interpreter has finished with them.
+</p>
+<p>
+Note: Operator overloads are basically done in the same way, by adding functions such as '__add' &amp; '__call' to the classes metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.
+</p>
+<H3><a name="Lua_nn28"></a>22.4.3 Memory management</H3>
+
+
+<p>
+Lua is very helpful with the memory management. The 'swig_lua_userdata' is fully managed by the interpreter itself. This means that neither the C code nor the Lua code can damage it. Once a piece of userdata has no references to it, it is not instantly collected, but will be collected when Lua deems is necessary. (You can force collection by calling the Lua function <tt>collectgarbage()</tt>). Once the userdata is about to be free'ed, the interpreter will check the userdata for a metatable and for a function '__gc'. If this exists this is called. For all complete types (ie normal wrappered classes &amp; structs) this should exist. The '__gc' function will check the 'swig_lua_userdata' to check for the 'own' field and if this is true (which is will be for all owned data's) it will then call the destructor on the pointer.
+</p>
+<p>
+It is currently not recommended to edit this field or add some user code, to change the behaviour. Though for those who wish to try, here is where to look.
+</p>
+<p>
+It is also currently not possible to change the ownership flag on the data (unlike most other scripting languages, Lua does not permit access to the data from within the interpreter)
+</p>
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Makefile b/trunk/Doc/Manual/Makefile
new file mode 100644
index 0000000..1923c2c
--- /dev/null
+++ b/trunk/Doc/Manual/Makefile
@@ -0,0 +1,63 @@
+# Makefile for generating the SWIG documentation
+#
+# Note that the htmldoc package needs to be installed, but requires patching (using the
+# margin-left.patch file from this directory) in order to correctly generate the pdf docs.
+# The .html files are first processed and updated with chapter numbering and anchor names
+# are added to the HTML headings using the python scripts. The htmldoc program is then
+# used to generate the PDF document and single page HTML version of the documentation.
+# HTML TIDY (package also known as tidy) is also required and is used as an aid to HTML
+# validation.
+#
+# Additional html validation can be done using the validate target.
+#
+
+# Note the # and " are escaped
+HTMLDOC_OPTIONS = "--book --toclevels 4 --no-numbered --toctitle \"Table of Contents\" --title --titleimage swig16.png --linkcolor \#0000ff --linkstyle underline --size Universal --left 0.50in --right 0.50in --top 0.50in --bottom 0.50in --header .t. --footer h.1 --nup 1 --tocheader .t. --tocfooter ..i --portrait --color --no-pscommands --no-xrxcomments --compression=1 --jpeg=0 --fontsize 10.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 10.0 --headfootfont Helvetica --charset iso-8859-1 --links --no-embedfonts --pagemode outline --pagelayout single --firstpage c1 --pageeffect none --pageduration 10 --effectduration 1.0 --no-encryption --permissions all  --owner-password \"\"  --user-password \"\" --browserwidth 680"
+
+.PHONY: maketoc check generate all clean validate test
+
+all: maketoc check generate
+
+maketoc:
+	python maketoc.py
+
+# Use htmltidy to warn about some HTML errors. Note that it is not used to clean/tidy the HTML,
+# it is just used as a primitive HTML checker.
+check:
+	  tidy -errors --gnu-emacs yes -quiet index.html
+	  tidy -errors --gnu-emacs yes -quiet Sections.html
+	  all=`sed '/^#/d' chapters`; for a in $$all; do tidy -errors --gnu-emacs yes -quiet $$a; done;
+
+generate: swightml.book swigpdf.book
+	htmldoc --batch swightml.book || true
+	htmldoc --batch swigpdf.book || true
+	python fixstyle.py SWIGDocumentation.html
+
+swigpdf.book:
+	echo "#HTMLDOC 1.8.24" > swigpdf.book
+	echo -t pdf13 -f SWIGDocumentation.pdf $(HTMLDOC_OPTIONS) --stylesheet style.css >> swigpdf.book
+	echo "Sections.html" >> swigpdf.book
+	cat chapters >> swigpdf.book
+
+swightml.book:
+	echo "#HTMLDOC 1.8.24" > swightml.book
+	echo -t html -f SWIGDocumentation.html $(HTMLDOC_OPTIONS) >> swightml.book
+	echo "Sections.html" >> swightml.book
+	cat chapters >> swightml.book
+
+clean:
+	rm -f swightml.book
+	rm -f swigpdf.book
+	rm -f SWIGDocumentation.html
+	rm -f SWIGDocumentation.pdf
+	rm -f *.bak
+
+test:
+	  grep "href=\".*\.html\"" index.html
+	  grep "href=\".*\.html\"" Sections.html
+	  all=`sed '/^#/d' chapters`; for a in $$all; do grep -l "href=\".*\.html\"" $$a; done;
+
+# Validating using the WDG offline validator - http://www.htmlhelp.com/tools/validator/offline/
+validate:
+	  all=`sed '/^#/d' chapters`; for a in $$all; do validate --emacs $$a; done;
+
diff --git a/trunk/Doc/Manual/Modula3.html b/trunk/Doc/Manual/Modula3.html
new file mode 100644
index 0000000..ff70fc1
--- /dev/null
+++ b/trunk/Doc/Manual/Modula3.html
@@ -0,0 +1,1067 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Modula-3</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+<body bgcolor="#FFFFFF">
+<H1><a name="Modula3"></a>23 SWIG and Modula-3</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#modula3_overview">Overview</a>
+<ul>
+<li><a href="#whyscripting">Why not scripting ?</a>
+<li><a href="#whymodula3">Why Modula-3 ?</a>
+<li><a href="#whycpp">Why C / C++ ?</a>
+<li><a href="#whyswig">Why SWIG ?</a>
+</ul>
+<li><a href="#conception">Conception</a>
+<ul>
+<li><a href="#cinterface">Interfaces to C libraries</a>
+<li><a href="#cppinterface">Interfaces to C++ libraries</a>
+</ul>
+<li><a href="#preliminaries">Preliminaries</a>
+<ul>
+<li><a href="#compilers">Compilers</a>
+<li><a href="#commandline">Additional Commandline Options</a>
+</ul>
+<li><a href="#modula3_typemaps">Modula-3 typemaps</a>
+<ul>
+<li><a href="#inoutparam">Inputs and outputs</a>
+<li><a href="#ordinals">Subranges, Enumerations, Sets</a>
+<li><a href="#class">Objects</a>
+<li><a href="#imports">Imports</a>
+<li><a href="#exceptions">Exceptions</a>
+<li><a href="#typemap_example">Example</a>
+</ul>
+<li><a href="#hints">More hints to the generator</a>
+<ul>
+<li><a href="#features">Features</a>
+<li><a href="#pragmas">Pragmas</a>
+</ul>
+<li><a href="#remarks">Remarks</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes SWIG's support of
+<a href="http://www.m3.org/">Modula-3</a>.
+You should be familiar with the
+<a href="SWIG.html#SWIG">basics</a>
+of SWIG,
+especially
+<a href="Typemaps.html">typemaps</a>.
+</p>
+
+<H2><a name="modula3_overview"></a>23.1 Overview</H2>
+
+
+<p>
+The Modula-3 support is very basic and highly experimental!
+Many features are still not designed satisfyingly
+and I need more discussion about the odds and ends.
+Don't rely on any feature, incompatible changes are likely in the future!
+The Modula-3 generator was already useful for interfacing
+to the libraries
+</p>
+
+<ol>
+<li>
+<a href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/plplot/">
+PLPlot
+</a>
+</li>
+<li>
+<a href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/fftw/">
+FFTW
+</a> .
+</li>
+</ol>
+
+
+<p>
+I took some more time to explain
+why I think it's right what I'm doing.
+So the introduction got a bit longer than it should ...  ;-)
+</p>
+
+
+<H3><a name="whyscripting"></a>23.1.1 Why not scripting ?</H3>
+
+
+<p>
+SWIG started as wrapper from the fast compiled languages C and C++
+to high level scripting languages like Python.
+Although scripting languages are designed
+to make programming life easier
+by hiding machine internals from the programmer
+there are several aspects of today's scripting languages
+that are unfavourable in my opinion.
+</p>
+
+<p>
+Besides C, C++, Cluster (a Modula derivate for Amiga computers)
+I evaluated several scripting like languages in the past:
+Different dialects of BASIC,
+Perl, ARexx (a variant of Rexx for Amiga computers),
+shell scripts.
+I found them too inconsistent,
+too weak in distinguishing types,
+too weak in encapsulating pieces of code.
+Eventually I have started several projects in Python
+because of the fine syntax.
+But when projects became larger
+I lost the track.
+I got convinced that one can not have
+maintainable code in a language
+that is not statically typed.
+In fact the main advantages of scripting languages
+e.g. matching regular expressions,
+complex built-in datatypes like lists, dictionaries,
+are not advantages of the language itself
+but can be provided by function libraries.
+</p>
+
+<H3><a name="whymodula3"></a>23.1.2 Why Modula-3 ?</H3>
+
+
+<p>
+Modula-3 is a compiler language
+in the tradition of Niklaus Wirth's Modula 2,
+which is in turn a successor of the popular Pascal.
+I have chosen Modula-3
+because of its
+logical syntax,
+strong modularization,
+the type system which is very detailed
+for machine types compared to other languages.
+Of course it supports all of the modern games
+like exceptions, objects, garbage collection, threads.
+While C++ programmers must
+control three languages,
+namely the preprocessor, C and ++,
+Modula-3 is made in one go
+and the language definition is really compact.
+</p>
+
+<p>
+On the one hand Modula-3 can be safe
+(but probably less efficient) in normal modules
+while providing much static and dynamic safety.
+On the other hand you can write efficient
+but less safe code in the style of C
+within <tt>UNSAFE</tt> modules.
+</p>
+
+<p>
+Unfortunately Modula's safety and strength
+requires more writing than scripting languages do.
+Today if I want to safe characters
+I prefer Haskell (similar to OCAML) -
+it's statically typed, too.
+</p>
+
+
+<H3><a name="whycpp"></a>23.1.3 Why C / C++ ?</H3>
+
+
+<p>
+Although it is no problem to write Modula-3 programs
+that performs as fast as C
+most libraries are not written in Modula-3 but in C.
+Fortunately the binary interface of most function libraries
+can be addressed by Modula-3.
+Even more fortunately even non-C libraries may provide C header files.
+This is where SWIG becomes helpful.
+</p>
+
+<H3><a name="whyswig"></a>23.1.4 Why SWIG ?</H3>
+
+
+<p>
+The C headers and the possibility to interface to C libraries
+still leaves the work for you
+to write Modula-3 interfaces to them.
+To make things comfortable you will also need
+wrappers that convert between high-level features of Modula-3
+(garbage collecting, exceptions)
+and the low level of the C libraries.
+</p>
+
+<p>
+SWIG converts C headers to Modula-3 interfaces for you.
+You could call the C functions without loss
+of efficiency but it won't be joy
+because you could not pass <tt>TEXT</tt>s
+or open arrays and
+you would have to process error return codes
+rather then exceptions.
+But using some typemaps SWIG will also generate
+wrappers that bring the whole Modula-3 comfort to you.
+If the library API is ill designed
+writing appropriate typemaps can be still time-consuming.
+E.g. C programmers are very creative to work-around
+missing data types like (real) enumerations and sets.
+You should turn such work-arounds back to the Modula-3 way
+otherwise you lose static safety and consistency.
+</p>
+
+<p>
+
+But you have still a problem:
+C library interfaces are often ill.
+They lack for certain information
+because C compilers wouldn't care about.
+You should integrate detailed type information
+by adding <tt>typedef</tt>s and <tt>const</tt>s
+and you should persuade the C library programmer
+to add this information to his interface.
+Only this way other language users can benefit from your work
+and only this way you can easily update your interfaces
+when a new library version is released.
+
+You will realise that writing <b>good</b> SWIG interfaces
+is very costly and it will only amortise
+when considering evolving libraries.
+</p>
+
+
+<p>
+Without SWIG you would probably never consider
+to call C++ libraries from Modula-3.
+But with SWIG this is worth a consideration.
+SWIG can write C wrappers to C++ functions and object methods
+that may throw exceptions.
+In fact it breaks down C++ libraries to C interfaces
+which can be in turn called from Modula-3.
+To make it complete you can hide the C interface
+with Modula-3 classes and exceptions.
+</p>
+
+<p>
+Although SWIG does the best it can do
+it can only serve as a one-way strategy.
+That means you can use C++ libraries
+with Modula-3 (even with call back functions),
+but it's certainly not possible to smoothly
+integrate Modula-3 code into a C / C++ project.
+</p>
+
+
+<H2><a name="conception"></a>23.2 Conception</H2>
+
+
+<H3><a name="cinterface"></a>23.2.1 Interfaces to C libraries</H3>
+
+
+<p>
+Modula-3 has an integrated support for calling C functions.
+This is also extensively used by the standard Modula-3 libraries
+to call OS functions.
+The Modula-3 part of SWIG and the corresponding SWIG library
+<a href="../../Lib/modula3/modula3.swg"><tt>modula3.swg</tt></a>
+contain code that uses these features.
+Because of the built-in support there is no need
+for calling the SWIG kernel to generate wrappers written in C.
+All conversion and argument checking can be done in Modula-3
+and the interfacing is quite efficient.
+All you have to do is to write pieces of Modula-3 code
+that SWIG puts together.
+</p>
+
+<table border summary="Modula-3 C library support">
+<tr><th colspan=2>C library support integrated in Modula-3<th></tr>
+<tr>
+<td>Pragma <tt>&lt;* EXTERNAL *&gt;</tt></td>
+<td>Precedes a declaration of a PROCEDURE that is implemented
+in an external library instead of a Modula-3 module.</td>
+</tr>
+<tr>
+<td>Pragma <tt>&lt;* CALLBACK *&gt;</tt></td>
+<td>Precedes a declaration of a PROCEDURE that should be called
+by external library code.</td>
+</tr>
+<tr>
+<td>Module <tt>Ctypes</tt></td>
+<td>Contains Modula-3 types that match some basic C types.</td>
+</tr>
+<tr>
+<td>Module <tt>M3toC</tt></td>
+<td>Contains routines that convert between Modula-3's <tt>TEXT</tt> type
+and C's <tt>char *</tt> type.</td>
+</tr>
+</table>
+
+<p>
+In each run of SWIG the Modula-3 part
+generates several files:
+</p>
+<table border summary="Modula-3 generated files">
+<tr>
+  <th>Module name scheme</th>
+  <th>Identifier for <tt>%insert</tt></th>
+  <th>Description</th>
+</tr>
+<tr>
+  <td>Module<tt>Raw.i3</tt></td>
+  <td><tt>m3rawintf</tt></td>
+  <td>Declaration of types that are equivalent to those of the C library,
+      <tt>EXTERNAL</tt> procedures as interface to the C library functions</td>
+</tr>
+<tr>
+  <td>Module<tt>Raw.m3</tt></td>
+  <td><tt>m3rawimpl</tt></td>
+  <td>Almost empty.</td>
+</tr>
+<tr>
+  <td>Module<tt>.i3</tt></td>
+  <td><tt>m3wrapintf</tt></td>
+  <td>Declaration of comfortable wrappers to the C library functions.</td>
+</tr>
+<tr>
+  <td>Module<tt>.m3</tt></td>
+  <td><tt>m3wrapimpl</tt></td>
+  <td>Implementation of the wrappers that
+      convert between Modula-3 and C types,
+      check for validity of values,
+      hand-over resource management to the garbage collector using <tt>WeakRef</tt>s
+      and raises exceptions.</td>
+</tr>
+<tr>
+  <td><tt>m3makefile</tt></td>
+  <td><tt>m3makefile</tt></td>
+  <td>Add the modules above to the Modula-3 project and
+      specify the name of the Modula-3 wrapper library
+      to be generated.
+
+    Today I'm not sure if it is a good idea
+    to create a <tt>m3makefile</tt> in each run,
+    because SWIG must be started for each Modula-3 module it creates.
+    Thus the m3makefile is overwritten each time. :-(
+  </td>
+</tr>
+</table>
+
+<p>
+Here's a scheme of how the function calls to Modula-3 wrappers
+are redirected to C library functions:
+</p>
+
+<table summary="Modula-3 C library">
+<tr>
+  <td align=center>
+    Modula-3 wrapper<br>
+    Module<tt>.i3</tt><br>
+    generated by Modula-3 part of SWIG
+  </td>
+  <td></td>
+  <td align=center></td>
+</tr>
+<tr>
+  <td align=center>
+    <!-- pre tag overrides centering -->
+    |<br>
+    v
+  </td>
+  <td></td>
+  <td align=center></td>
+</tr>
+<tr>
+  <td align=center>
+    Modula-3 interface to C<br>
+    Module<tt>Raw.i3</tt><br>
+    generated by Modula-3 part of SWIG
+  </td>
+  <td>--&gt;</td>
+  <td align=center>
+    C library
+  </td>
+</tr>
+</table>
+
+
+<p>
+I have still no good conception how one can split C library interfaces
+into type oriented interfaces.
+A Module in Modula-3 represents an Abstract DataType
+(or call it a static classes, i.e. a class without virtual methods).
+E.g. if you have a principal type, say <tt>Database</tt>,
+it is good Modula-3 style to set up one Module with the name <tt>Database</tt>
+where the database type is declared with the name <tt>T</tt>
+and where all functions are declared that operates on it.
+</p>
+
+<p>
+The normal operation of SWIG is to generate a fixed set of files per call.
+To generate multiple modules one has to write one SWIG interface
+(different SWIG interfaces can share common data) per module.
+Identifiers belonging to a different module may ignored (<tt>%ignore</tt>)
+and the principal type must be renamed (<tt>%typemap</tt>).
+</p>
+
+
+<H3><a name="cppinterface"></a>23.2.2 Interfaces to C++ libraries</H3>
+
+
+<p>
+Interfaces to C++ files are much more complicated and
+there are some more design decisions that are not made, yet.
+Modula-3 has no support for C++ functions
+but C++ compilers should support generating C++ functions
+with a C interface.
+</p>
+
+<p>
+Here's a scheme of how the function calls to Modula-3 wrappers
+a redirected to C library functions:
+</p>
+
+<table summary="Modula-3 C++ library">
+<tr>
+  <td align=center>
+    Modula-3 wrapper<br>
+    Module<tt>.i3</tt><br>
+    generated by Modula-3 part of SWIG
+  </td>
+  <td></td>
+  <td align=center>C++ library</td>
+</tr>
+<tr>
+  <td align=center>
+    <!-- pre tag overrides centering -->
+    |<br>
+    v
+  </td>
+  <td></td>
+  <td align=center>
+    ^<br>
+    |
+  </td>
+</tr>
+<tr>
+  <td align=center>
+    Modula-3 interface to C<br>
+    Module<tt>Raw.i3</tt><br>
+    generated by Modula-3 part of SWIG
+  </td>
+  <td>--&gt;</td>
+  <td align=center>
+    C interface to C++<br>
+    module<tt>_wrap.cxx</tt><br>
+    generated by the SWIG core
+  </td>
+</tr>
+</table>
+
+<p>
+Wrapping C++ libraries arises additional problems:
+</p>
+<ul>
+<li>
+Is it sensible to wrap C++ classes with Modula-3 classes?
+</li>
+<li>
+How to find the wrapping Modula-3 class
+for a class pointer that is returned by a C++ routine?
+</li>
+<li>
+How to deal with multiple inheritance
+which was neglected for Modula-3 for good reasons?
+</li>
+<li>
+Is it possible to sub-class C++ classes with Modula-3 code?
+This issue is addressed by directors,
+a feature that was experimentally added to some Language modules
+like
+<a href="Java.html#java_directors">Java</a> and
+<a href="Python.html#directors">Python</a>.
+</li>
+<li>
+How to manage storage with the garbage collector of Modula-3?
+Support for
+<a href="Customization.html#ownership">
+<tt>%newobject</tt> and <tt>%typemap(newfree)</tt></a>
+isn't implemented, yet.
+What's about resources that are managed by the garbage collector
+but shall be passed back to the storage management of the C++ library?
+This is a general issue which is not solved in a satisfying fashion
+as far as I know.
+</li>
+<li>
+How to turn C++ exceptions into Modula-3 exceptions?
+There's also no support for
+<a href="Customization.html#exception">
+<tt>%exception</tt></a>, yet.
+</li>
+</ul>
+
+<p>
+Be warned:
+There is no C++ library I wrote a SWIG interface for,
+so I'm not sure if this is possible or sensible, yet.
+</p>
+
+<H2><a name="preliminaries"></a>23.3 Preliminaries</H2>
+
+
+<H3><a name="compilers"></a>23.3.1 Compilers</H3>
+
+
+<p>
+There are different Modula-3 compilers around:
+cm3, pm3, ezm3, Klagenfurth Modula-3, Cambridge Modula-3.
+SWIG itself does not contain compiler specific code
+but the library file
+<a href="../../Lib/modula3/modula3.swg"><tt>modula3.swg</tt></a>
+may do so.
+For testing examples I use Critical Mass cm3.
+</p>
+
+
+<H3><a name="commandline"></a>23.3.2 Additional Commandline Options</H3>
+
+
+<p>
+There are some experimental command line options
+that prevent SWIG from generating interface files.
+Instead files are emitted that may assist you
+when writing SWIG interface files.
+</p>
+
+<table border summary="Modula-3 specific options">
+<tr>
+<th>Modula-3 specific options</th>
+<th>Description</th>
+</tr>
+
+<tr>
+<td valign=top>-generateconst &lt;file&gt;</td>
+<td>
+Disable generation of interfaces and wrappers.
+Instead write code for computing numeric values of constants
+to the specified file.
+<br>
+C code may contain several constant definitions
+written as preprocessor macros.
+Other language modules of SWIG use
+compute-once-use-readonly variables or
+functions to wrap such definitions.
+All of them can invoke C code dynamically
+for computing the macro values.
+But if one wants to turn them into Modula-3
+integer constants, enumerations or set types,
+the values of these expressions has to be known statically.
+Although definitions like <tt>(1 &lt;&lt; FLAG_MAXIMIZEWINDOW)</tt>
+must be considered as good C style
+they are hard to convert to Modula-3
+since the value computation can use every feature of C.
+<br>
+Thus I implemented these switch
+to extract all constant definitions
+and write a C program that output the values of them.
+It works for numeric constants only
+and treats all of them as <tt>double</tt>.
+Future versions may generate a C++ program
+that can detect the type of the macros
+by overloaded output functions.
+Then strings can also be processed.
+</td>
+</tr>
+
+<tr>
+<td valign=top>-generaterename &lt;file&gt;</td>
+<td>
+Disable generation of interfaces and wrappers.
+Instead generate suggestions for <tt>%rename</tt>.
+<br>
+C libraries use a naming style
+that is neither homogeneous nor similar to that of Modula-3.
+C function names often contain a prefix denoting the library
+and some name components separated by underscores
+or capitalization changes.
+To get library interfaces that are really Modula-3 like
+you should rename the function names with the <tt>%rename</tt> directive.
+This switch outputs a list of such directives
+with a name suggestion generated by a simple heuristic.
+</td>
+</tr>
+
+<tr>
+<td valign=top>-generatetypemap &lt;file&gt;</td>
+<td>
+Disable generation of interfaces and wrappers.
+Instead generate templates for some basic typemaps.
+</td>
+</tr>
+</table>
+
+<H2><a name="modula3_typemaps"></a>23.4 Modula-3 typemaps</H2>
+
+
+<H3><a name="inoutparam"></a>23.4.1 Inputs and outputs</H3>
+
+
+<p>
+Each C procedure has a bunch of inputs and outputs.
+Inputs are passed as function arguments,
+outputs are updated referential arguments and
+the function value.
+</p>
+
+<p>
+Each C type can have several typemaps
+that apply only in case if a type is used
+for an input argument, for an output argument,
+or for a return value.
+A further typemap may specify
+the direction that is used for certain parameters.
+I have chosen this separation
+in order to be able to write general typemaps for the typemap library
+<a href="../../Lib/modula3/modula3.swg"><tt>modula3.swg</tt></a>
+.
+In the library code the final usage of the type is not known.
+Using separate typemaps for each possible use
+allows appropriate definitions for each case.
+If these pre-definitions are fine
+then the direction of the function parameter
+is the only hint the user must give.
+</p>
+
+<p>
+The typemaps specific to Modula-3 have a common name scheme:
+A typemap name starts with "m3",
+followed by "raw" or "wrap"
+depending on whether it controls the generation
+of the Module<tt>Raw.i3</tt> or the Module<tt>.i3</tt>, respectively.
+It follows an "in" for typemaps applied to input argument,
+"out" for output arguments, "arg" for all kind of arguments,
+"ret" for returned values.
+</p>
+
+<p>
+The main task of SWIG is to build wrapper function,
+i.e. functions that convert values between C and Modula-3
+and call the corresponding C function.
+Modula-3 wrapper functions generated by SWIG
+consist of the following parts:
+</p>
+<ul>
+<li>Generate <tt>PROCEDURE</tt> signature.</li>
+<li>Declare local variables.</li>
+<li>Convert input values from Modula-3 to C.</li>
+<li>Check for input value integrity.</li>
+<li>Call the C function.</li>
+<li>Check returned values, e.g. error codes.</li>
+<li>Convert and write back values into Modula-3 records.</li>
+<li>Free temporary storage.</li>
+<li>Return values.</li>
+</ul>
+
+<table border summary="Modula-3 typemaps">
+<tr>
+  <th>Typemap</th>
+  <th>Example</th>
+  <th>Description</th>
+</tr>
+<tr>
+  <td>m3wrapargvar</td>
+  <td><tt>$1: INTEGER := $1_name;</tt></td>
+  <td>
+    Declaration of some variables needed for temporary results.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapargconst</td>
+  <td><tt>$1 = "$1_name";</tt></td>
+  <td>
+    Declaration of some constant, maybe for debug purposes.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapargraw</td>
+  <td><tt>ORD($1_name)</tt></td>
+  <td>
+    The expression that should be passed as argument to the raw Modula-3 interface function.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapargdir</td>
+  <td><tt>out</tt></td>
+  <td>
+    Referential arguments can be used for input, output, update.
+    ???
+  </td>
+</tr>
+<tr>
+  <td>m3wrapinmode</td>
+  <td><tt>READONLY</tt></td>
+  <td>
+    One of Modula-3 parameter modes
+    <tt>VALUE</tt> (or empty),
+    <tt>VAR</tt>,
+    <tt>READONLY</tt>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapinname</td>
+  <td></td>
+  <td>
+    New name of the input argument.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapintype</td>
+  <td></td>
+  <td>
+    Modula-3 type of the input argument.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapindefault</td>
+  <td></td>
+  <td>
+    Default value of the input argument
+  </td>
+</tr>
+<tr>
+  <td>m3wrapinconv</td>
+  <td><tt>$1 := M3toC.SharedTtoS($1_name);</tt></td>
+  <td>
+    Statement for converting the Modula-3 input value to C compliant value.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapincheck</td>
+  <td><tt>IF Text.Length($1_name) &gt; 10 THEN RAISE E("str too long"); END;</tt></td>
+  <td>
+    Check the integrity of the input value.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapoutname</td>
+  <td></td>
+  <td>
+    Name of the <tt>RECORD</tt> field to be used for returning multiple values.
+    This applies to referential output arguments that shall be turned
+    into return values.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapouttype</td>
+  <td></td>
+  <td>
+    Type of the value that is returned instead of a referential output argument.
+  </td>
+</tr>
+<tr>
+  <td>m3wrapoutconv</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapoutcheck</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapretraw</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapretname</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wraprettype</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapretvar</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapretconv</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapretcheck</td>
+  <td></td>
+  <td>
+  </td>
+</tr>
+<tr>
+  <td>m3wrapfreearg</td>
+  <td><tt>M3toC.FreeSharedS(str,arg1);</tt></td>
+  <td>
+    Free resources that were temporarily used in the wrapper.
+    Since this step should never be skipped,
+    SWIG will put it in the <tt>FINALLY</tt> branch
+    of a <tt>TRY .. FINALLY</tt> structure.
+  </td>
+</tr>
+</table>
+
+
+<H3><a name="ordinals"></a>23.4.2 Subranges, Enumerations, Sets</H3>
+
+
+<p>
+Subranges, enumerations, and sets are machine oriented types
+that make Modula very strong and expressive compared
+with the type systems of many other languages.
+</p>
+
+<ul>
+<li>
+Subranges are used for statically restricted choices of integers.
+</li>
+<li>
+Enumerations are used for named choices.
+</li>
+<li>
+Sets are commonly used for flag (option) sets.
+</li>
+</ul>
+
+<p>
+Using them extensively makes Modula code very safe and readable.
+</p>
+
+<p>
+C supports enumerations, too, but they are not as safe as the ones of Modula.
+Thus they are abused for many things:
+For named choices, for integer constant definitions, for sets.
+To make it complete every way of defining a value in C
+(<tt>#define</tt>, <tt>const int</tt>, <tt>enum</tt>)
+is somewhere used for defining something
+that must be handled completely different in Modula-3
+(<tt>INTEGER</tt>, enumeration, <tt>SET</tt>).
+</p>
+
+<p>
+I played around with several <tt>%feature</tt>s and <tt>%pragma</tt>s
+that split the task up into converting
+the C bit patterns (integer or bit set)
+into Modula-3 bit patterns (integer or bit set)
+and change the type as requested.
+See the corresponding
+<a href="../../Examples/modula3/enum/example.i">example</a>.
+This is quite messy and not satisfying.
+So the best what you can currently do is
+to rewrite constant definitions manually.
+Though this is a tedious work
+that I'd like to automate.
+</p>
+
+
+<H3><a name="class"></a>23.4.3 Objects</H3>
+
+
+<p>
+Declarations of C++ classes are mapped to <tt>OBJECT</tt> types
+while it is tried to retain the access hierarchy
+"public - protected - private" using partial revelation.
+Though the
+<a href="../../Examples/modula3/class/example.i">implementation</a>
+is not really useful, yet.
+</p>
+
+
+<H3><a name="imports"></a>23.4.4 Imports</H3>
+
+
+<p>
+Pieces of Modula-3 code provided by typemaps
+may contain identifiers from foreign modules.
+If the typemap <tt>m3wrapinconv</tt> for <tt>blah *</tt>
+contains code using the function <tt>M3toC.SharedTtoS</tt>
+you may declare <tt>%typemap("m3wrapinconv:import") blah * %{M3toC%}</tt>.
+Then the module <tt>M3toC</tt> is imported
+if the <tt>m3wrapinconv</tt> typemap for <tt>blah *</tt>
+is used at least once.
+Use <tt>%typemap("m3wrapinconv:import") blah * %{MyConversions AS M3toC%}</tt>
+if you need module renaming.
+Unqualified import is not supported.
+</p>
+
+<p>
+It is cumbersome to add this typemap to each piece of Modula-3 code.
+It is especially useful when writing general typemaps
+for the typemap library
+<a href="../../Lib/modula3/modula3.swg"><tt>modula3.swg</tt></a>
+.
+For a monolithic module you might be better off
+if you add the imports directly:
+</p>
+
+<div class="code">
+<pre>
+%insert(m3rawintf) %{
+IMPORT M3toC;
+%}
+</pre></div>
+
+
+<H3><a name="exceptions"></a>23.4.5 Exceptions</H3>
+
+
+<p>
+Modula-3 provides another possibility
+of an output of a function: exceptions.
+</p>
+
+<p>
+Any piece of Modula-3 code that SWIG inserts
+due to a typemap can raise an exception.
+This way you can also convert an error code
+from a C function into a Modula-3 exception.
+</p>
+
+<p>
+The <tt>RAISES</tt> clause is controlled
+by typemaps with the <tt>throws</tt> extension.
+If the typemap <tt>m3wrapinconv</tt> for <tt>blah *</tt>
+contains code that may raise the exceptions <tt>OSError.E</tt>
+you should declare
+<tt>%typemap("m3wrapinconv:throws") blah * %{OSError.E%}</tt>.
+</p>
+
+<H3><a name="typemap_example"></a>23.4.6 Example</H3>
+
+
+<p>
+The generation of wrappers in Modula-3 needs very fine control
+to take advantage of the language features.
+Here is an example of a generated wrapper
+where almost everything is generated by a typemap:
+</p>
+
+<div class="code"><pre>
+<I>         (* %relabel  m3wrapinmode m3wrapinname m3wrapintype  m3wrapindefault *)</I>
+  PROCEDURE Name     (READONLY       str       :    TEXT    :=      ""       )
+<I>              (* m3wrapoutcheck:throws *)</I>
+     : NameResult RAISES {E} =
+    CONST
+      arg1name = "str";                  <I>(* m3wrapargconst *)</I>
+    VAR
+      arg0   : C.char_star;              <I>(* m3wrapretvar *)</I>
+      arg1   : C.char_star;              <I>(* m3wrapargvar *)</I>
+      arg2   : C.int;
+      result : RECORD
+<I>           (*m3wrapretname  m3wraprettype*)</I>
+                 unixPath : TEXT;
+<I>           (*m3wrapoutname  m3wrapouttype*)</I>
+                 checksum : CARDINAL;
+               END;
+    BEGIN
+      TRY
+        arg1 := M3toC.SharedTtoS(str);   <I>(* m3wrapinconv *)</I>
+        IF Text.Length(arg1) &gt; 10 THEN   <I>(* m3wrapincheck *)</I>
+          RAISE E("str too long");
+        END;
+<I> (* m3wrapretraw           m3wrapargraw *)</I>
+        arg0 := MessyToUnix  (arg1,   arg2);
+        result.unixPath := M3toC.CopyStoT(arg0);  <I>(* m3wrapretconv *)</I>
+        result.checksum := arg2;         <I>(* m3wrapoutconv *)</I>
+        IF result.checksum = 0 THEN      <I>(* m3wrapoutcheck *)</I>
+          RAISE E("invalid checksum");
+        END;
+      FINALLY
+        M3toC.FreeSharedS(str,arg1);     <I>(* m3wrapfreearg *)</I>
+      END;
+    END Name;
+</pre></div>
+
+
+<H2><a name="hints"></a>23.5 More hints to the generator</H2>
+
+
+<H3><a name="features"></a>23.5.1 Features</H3>
+
+
+<table border summary="Modula-3 features">
+<tr>
+  <th>Feature</th>
+  <th>Example</th>
+  <th>Description</th>
+</tr>
+<tr>
+  <td>multiretval</td>
+  <td><tt>%m3multiretval get_box;</tt> or
+      <tt>%feature("modula3:multiretval") get_box;</tt></td>
+  <td>Let the denoted function return a <tt>RECORD</tt>
+      rather than a plain value.
+      This <tt>RECORD</tt> contains all arguments with "out" direction
+      including the return value of the C function (if there is one).
+      If more than one argument is "out"
+      then the function <b>must</b> have the <tt>multiretval</tt> feature activated,
+      but it is explicitly requested from the user to prevent mistakes.</td>
+</tr>
+<tr>
+  <td>constnumeric</td>
+  <td><tt>%constnumeric(12) twelve;</tt> or
+      <tt>%feature("constnumeric","12") twelve;</tt></td>
+  <td>This feature can be used to tell Modula-3's back-end of SWIG
+      the value of an identifier.
+      This is necessary in the cases
+      where it was defined by a non-trivial C expression.
+      This feature is used by the
+      <tt>-generateconst</tt> <a href="#options">option</a>.
+      In future it may be generalized to other kind of values
+      such as strings.
+      </td>
+</tr>
+</table>
+
+<H3><a name="pragmas"></a>23.5.2 Pragmas</H3>
+
+
+<table border summary="Modula-3 pragmas">
+<tr>
+  <th>Pragma</th>
+  <th>Example</th>
+  <th>Description</th>
+</tr>
+<tr>
+  <td>unsafe</td>
+  <td><tt>%pragma(modula3) unsafe="true";</tt></td>
+  <td>Mark the raw interface modules as <tt>UNSAFE</tt>.
+      This will be necessary in many cases.</td>
+</tr>
+<tr>
+  <td>library</td>
+  <td><tt>%pragma(modula3) library="m3fftw";</tt></td>
+  <td>Specifies the library name for the wrapper library to be created.
+      It should be distinct from the name of the library to be wrapped.</td>
+</tr>
+</table>
+
+<H2><a name="remarks"></a>23.6 Remarks</H2>
+
+
+<ul>
+<li>
+The Modula-3 part of SWIG doesn't try to generate nicely formatted code.
+Use <tt>m3pp</tt> to postprocess the Modula files,
+it does a very good job here.
+</li>
+</ul>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Modules.html b/trunk/Doc/Manual/Modules.html
new file mode 100644
index 0000000..8971324
--- /dev/null
+++ b/trunk/Doc/Manual/Modules.html
@@ -0,0 +1,259 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Working with Modules</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Modules"></a>15 Working with Modules</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Modules_nn1">Basics</a>
+<li><a href="#Modules_nn2">The SWIG runtime code</a>
+<li><a href="#external_run_time">External access to the runtime</a>
+<li><a href="#Modules_nn4">A word of caution about static libraries</a>
+<li><a href="#Modules_nn5">References</a>
+<li><a href="#Modules_nn6">Reducing the wrapper file size</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+When first working with SWIG, users commonly start by creating a
+single module.  That is, you might define a single SWIG interface that
+wraps some set of C/C++ code.  You then compile all of the generated
+wrapper code into a module and use it.   For large applications, however,
+this approach is problematic---the size of the generated wrapper code
+can be rather large.  Moreover, it is probably easier to manage the
+target language interface when it is broken up into smaller pieces.
+</p>
+
+<p>
+This chapter describes the problem of using SWIG in programs
+where you want to create a collection of modules.
+</p>
+
+<H2><a name="Modules_nn1"></a>15.1 Basics</H2>
+
+
+<p>
+The basic usage case with multiple modules is when modules do not have
+cross-references (ie. when wrapping multiple independent C APIs). In that case,
+swig input files should just work out of the box - you simply create multiple
+wrapper .cxx files, link them into your application, and insert/load each in the
+scripting language runtime as you would do for the single module case.
+</p>
+
+<p>
+A bit more complex is the case in which modules need to share information.
+For example, when one module extends the class of the another by deriving from
+it:
+</p>
+
+<div class="code"><pre>
+%module base
+
+%inline %{
+class base {
+public:
+       int foo(void);
+};
+%}
+</pre></div>
+&nbsp;
+<div class="code"><pre>
+%module derived
+
+%import "base.i"
+
+%inline %{
+class derived : public base {
+public:
+       int bar(void);
+};
+%}
+</pre></div>
+
+<p>To create the wrapper properly, module <tt>derived</tt> needs to know the
+<tt>base</tt> class and that it's interface is covered in another module. The
+line <tt>%import "base.i"</tt> lets SWIG know exactly that. The common mistake here is
+to <tt>%import</tt> the <tt>.h</tt> file instead of the <tt>.i</tt>, which sadly won't do the trick. Another issue
+to take care of is that multiple dependent wrappers should not be linked/loaded
+in parallel from multiple threads as SWIG provides no locking - for more on that
+issue, read on.</p>
+
+<H2><a name="Modules_nn2"></a>15.2 The SWIG runtime code</H2>
+
+
+<p>
+Many of SWIG's target languages generate a set of functions commonly known as
+the "SWIG runtime." These functions are primarily related to the runtime type
+system which checks pointer types and performs other tasks such as proper
+casting of pointer values in C++. As a general rule, the statically typed target
+languages, such as Java, use the language's built in static type checking and
+have no need for a SWIG runtime. All the dynamically typed / interpreted
+languages rely on the SWIG runtime.
+</p>
+
+<p>
+The runtime functions are private to each SWIG-generated module. That is, the
+runtime functions are declared with "static" linkage and are visible only to the
+wrapper functions defined in that module. The only problem with this approach is
+that when more than one SWIG module is used in the same application, those
+modules often need to share type information. This is especially true for C++
+programs where SWIG must collect and share information about inheritance
+relationships that cross module boundaries.
+</p>
+
+<p>
+To solve the problem of sharing information across modules, a pointer to the
+type information is stored in a global variable in the target language
+namespace. During module initialization, type information is loaded into the
+global data structure of type information from all modules.
+</p>
+
+<p>
+There are a few trade offs with this approach. This type information is global
+across all SWIG modules loaded, and can cause type conflicts between modules
+that were not designed to work together. To solve this approach, the SWIG
+runtime code uses a define SWIG_TYPE_TABLE to provide a unique type table. This
+behavior can be enabled when compiling the generated _wrap.cxx or _wrap.c file
+by adding -DSWIG_TYPE_TABLE=myprojectname to the command line argument.
+</p>
+
+<p>
+Then, only modules compiled with SWIG_TYPE_TABLE set to myprojectname will share
+type information. So if your project has three modules, all three should be
+compiled with -DSWIG_TYPE_TABLE=myprojectname, and then these three modules will
+share type information. But any other project's types will not interfere or
+clash with the types in your module.
+</p>
+
+<p>
+Another issue relating to the global type table is thread safety. If two modules
+try and load at the same time, the type information can become corrupt. SWIG
+currently does not provide any locking, and if you use threads, you must make
+sure that modules are loaded serially. Be careful if you use threads and the
+automatic module loading that some scripting languages provide. One solution is
+to load all modules before spawning any threads, or use SWIG_TYPE_TABLE to
+separate type tables so they do not clash with each other.
+</p>
+
+<p>
+Lastly, SWIG uses a #define SWIG_RUNTIME_VERSION, located in Lib/swigrun.swg and
+near the top of every generated module. This number gets incremented when the
+data structures change, so that SWIG modules generated with different versions
+can peacefully coexist. So the type structures are separated by the
+(SWIG_TYPE_TABLE, SWIG_RUNTIME_VERSION) pair, where by default SWIG_TYPE_TABLE
+is empty. Only modules compiled with the same pair will share type information.
+</p>
+
+<H2><a name="external_run_time"></a>15.3 External access to the runtime</H2>
+
+
+<p>As described in <a href="Typemaps.html#runtime_type_checker">The run-time type checker</a>,
+the functions <tt>SWIG_TypeQuery</tt>, <tt>SWIG_NewPointerObj</tt>, and others sometimes need
+to be called.  Calling these functions from a typemap is supported, since the typemap code
+is embedded into the <tt>_wrap.c</tt> file, which has those declarations available.  If you need
+to call the SWIG run-time functions from another C file, there is one header you need
+to include.  To generate the header that needs to be included, run the following command:
+
+<div class="shell"><pre>
+$ swig -python -external-runtime &lt;filename&gt;
+</pre></div>
+
+<p>The filename argument is optional and if it is not passed, then the default filename will
+be something like <tt>swigpyrun.h</tt>, depending on the language.  This header file should
+be treated like any of the other _wrap.c output files, and should be regenerated when the
+_wrap files are.  After including this header, your code will be able to call <tt>SWIG_TypeQuery</tt>,
+<tt>SWIG_NewPointerObj</tt>, <tt>SWIG_ConvertPtr</tt> and others.  The exact argument parameters
+for these functions might differ between language modules; please check the language module chapters
+for more information.</p>
+
+<p>Inside this header the functions are declared static and are included inline into the file,
+and thus the file does not need to be linked against any SWIG libraries or code (you might still
+need to link against the language libraries like libpython-2.3).  Data is shared between this
+file and the _wrap.c files through a global variable in the scripting language.  It is also
+possible to copy this header file along with the generated wrapper files into your own package,
+so that you can distribute a package that can be compiled without SWIG installed (this works
+because the header file is self-contained, and does not need to link with anything).</p>
+
+<p>
+This header will also use the -DSWIG_TYPE_TABLE described above, so when
+compiling any code which includes the generated header file should define the
+SWIG_TYPE_TABLE to be the same as the module whose types you are trying to
+access.
+</p>
+
+<H2><a name="Modules_nn4"></a>15.4 A word of caution about static libraries</H2>
+
+
+<p>
+When working with multiple SWIG modules, you should take care not to use static
+libraries.  For example, if you have a static library <tt>libfoo.a</tt> and you link a collection
+of SWIG modules with that library, each module will get its own private copy of the library code inserted
+into it. This is very often <b>NOT</b> what you want and it can lead to unexpected or bizarre program
+behavior. When working with dynamically loadable modules, you should try to work exclusively with shared libraries.
+</p>
+
+<H2><a name="Modules_nn5"></a>15.5 References</H2>
+
+
+<p>
+Due to the complexity of working with shared libraries and multiple modules, it might be a good idea to consult
+an outside reference.  John Levine's "Linkers and Loaders" is highly recommended.
+</p>
+
+<H2><a name="Modules_nn6"></a>15.6 Reducing the wrapper file size</H2>
+
+
+<p>
+Using multiple modules with the <tt>%import</tt> directive is the most common approach to modularising large projects.
+In this way a number of different wrapper files can be generated, thereby avoiding the generation of a single large wrapper file.
+There are a couple of alternative solutions for reducing the size of a wrapper file through the use of command line options and features.
+</p>
+
+<p>
+<b>-fcompact</b><br>
+This command line option will compact the size of the wrapper file without changing the code generated into the wrapper file.
+It simply removes blank lines and joins lines of code together.
+This is useful for compilers that have a maximum file size that can be handled.
+</p>
+
+<p>
+<b>-fvirtual</b><br>
+This command line option will remove the generation of superfluous virtual method wrappers.
+Consider the following inheritance hierarchy:
+</p>
+
+<div class="code">
+<pre>
+struct Base {
+  virtual void method();
+  ...
+};
+
+struct Derived : Base {
+  virtual void method();
+  ...
+};
+</pre>
+</div>
+
+<p>
+Normally wrappers are generated for both methods, whereas this command line option will suppress the generation of a wrapper for <tt>Derived::method</tt>.
+Normal polymorphic behaviour remains as <tt>Derived::method</tt> will still be called should you have
+a <tt>Derived</tt> instance and call the wrapper for <tt>Base::method</tt>.
+</p>
+
+<p>
+<b>%feature("compactdefaultargs")</b><br>
+This feature can reduce the number of wrapper methods when wrapping methods with default arguments. The section on <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a> discusses the feature and its limitations.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Mzscheme.html b/trunk/Doc/Manual/Mzscheme.html
new file mode 100644
index 0000000..6991683
--- /dev/null
+++ b/trunk/Doc/Manual/Mzscheme.html
@@ -0,0 +1,71 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<!-- Hand-written HTML -->
+<html>
+<head>
+<title>SWIG and MzScheme</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+
+<H1><a name="MzScheme"></a>24 SWIG and MzScheme</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#MzScheme_nn2">Creating native MzScheme structures</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This section contains information on SWIG's support of MzScheme.
+
+<H2><a name="MzScheme_nn2"></a>24.1 Creating native MzScheme structures</H2>
+
+
+<p>
+Example interface file:
+</p>
+
+<div class="code">
+<pre>
+/* define a macro for the struct creation */
+%define handle_ptr(TYPE,NAME)
+%typemap(argout) TYPE *NAME{
+    Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
+    SWIG_APPEND_VALUE(o);
+}
+
+%typemap(in,numinputs=0) TYPE *NAME (TYPE temp) {
+    $1 = &amp;temp;
+}
+%enddef
+
+/* setup the typemaps for the pointer to an output parameter cntrs */
+handle_ptr(struct diag_cntrs, cntrs);
+</pre>
+</div>
+
+<p>
+Then in scheme, you can use regular struct access procedures like
+</p>
+
+<div class="code">
+<pre>
+	; suppose a function created a struct foo as 
+	; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
+	; Then you can do
+	(format "0x~x" (diag-cntrs-field1 foo))
+	(format "0x~x" (diag-cntrs-field2 foo))
+	;etc...
+</pre>
+</div>
+
+<p>
+That's pretty much it. It works with nested structs as well. 
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Ocaml.html b/trunk/Doc/Manual/Ocaml.html
new file mode 100644
index 0000000..79ede44
--- /dev/null
+++ b/trunk/Doc/Manual/Ocaml.html
@@ -0,0 +1,991 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>SWIG and Ocaml</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+  <body bgcolor="#ffffff">
+          <a name="n1"></a>         
+<H1><a name="Ocaml"></a>25 SWIG and Ocaml</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Ocaml_nn2">Preliminaries</a>
+<ul>
+<li><a href="#Ocaml_nn3">Running SWIG</a>
+<li><a href="#Ocaml_nn4">Compiling the code</a>
+<li><a href="#Ocaml_nn5">The camlp4 module</a>
+<li><a href="#Ocaml_nn6">Using your module</a>
+<li><a href="#Ocaml_nn7">Compilation problems and compiling with C++</a>
+</ul>
+<li><a href="#Ocaml_nn8">The low-level Ocaml/C interface</a>
+<ul>
+<li><a href="#Ocaml_nn9">The generated module</a>
+<li><a href="#Ocaml_nn10">Enums</a>
+<ul>
+<li><a href="#Ocaml_nn11">Enum typing in Ocaml</a>
+</ul>
+<li><a href="#Ocaml_nn12">Arrays</a>
+<ul>
+<li><a href="#Ocaml_nn13">Simple types of bounded arrays</a>
+<li><a href="#Ocaml_nn14">Complex and unbounded arrays</a>
+<li><a href="#Ocaml_nn15">Using an object</a>
+<li><a href="#Ocaml_nn16">Example typemap for a function taking float * and int</a>
+</ul>
+<li><a href="#Ocaml_nn17">C++ Classes</a>
+<ul>
+<li><a href="#Ocaml_nn18">STL vector and string Example</a>
+<li><a href="#Ocaml_nn19">C++ Class Example</a>
+<li><a href="#Ocaml_nn20">Compiling the example</a>
+<li><a href="#Ocaml_nn21">Sample Session</a>
+</ul>
+<li><a href="#Ocaml_nn22">Director Classes</a>
+<ul>
+<li><a href="#Ocaml_nn23">Director Introduction</a>
+<li><a href="#Ocaml_nn24">Overriding Methods in Ocaml</a>
+<li><a href="#Ocaml_nn25">Director Usage Example</a>
+<li><a href="#Ocaml_nn26">Creating director objects</a>
+<li><a href="#Ocaml_nn27">Typemaps for directors, <tt>directorin, directorout, directorargout</tt></a>
+<li><a href="#Ocaml_nn28"><tt>directorin</tt> typemap</a>
+<li><a href="#Ocaml_nn29"><tt>directorout</tt> typemap</a>
+<li><a href="#Ocaml_nn30"><tt>directorargout</tt> typemap</a>
+</ul>
+<li><a href="#Ocaml_nn31">Exceptions</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+                This chapter describes SWIG's
+support of Ocaml.  Ocaml     is a relatively recent addition to the ML family,
+and is a recent   addition     to SWIG.  It's the second compiled, typed
+language to be added.    Ocaml   has  widely acknowledged benefits for engineers,
+mostly derived  from  a sophisticated    type system, compile-time checking
+which eliminates  several  classes of  common  programming errors, and good
+native performance.   While  all of this  is wonderful,  there are well-written
+C and C++ libraries  that  Ocaml users  will want to  take advantage of as
+part of their arsenal  (such  as SSL and  gdbm), as well  as their own mature
+C and C++ code.  SWIG  allows   this code  to be used in  a natural, type-safe
+way with Ocaml, by  providing   the necessary,   but repetitive  glue code
+which creates and uses Ocaml values  to communicate   with C and C++ code.
+ In addition, SWIG also produces the needed Ocaml source   that binds
+variants, functions,  classes, etc.
+</p>
+
+<p>
+If you're not familiar with the Objective Caml language, you can visit
+<a href="http://www.ocaml.org/">The Ocaml Website</a>.
+</p>
+
+<H2><a name="Ocaml_nn2"></a>25.1 Preliminaries</H2>
+
+
+<p>
+                  SWIG 1.3 works with Ocaml 3.04 and above.  Given the choice,
+   you  should  use the latest stable release.  The SWIG Ocaml module has
+been   tested  on Linux (x86,PPC,Sparc) and Cygwin on Windows.  The
+best  way to determine    whether your system will work is to compile the
+examples  and test-suite  which  come with SWIG.  You can do this by running
+<tt>make  check</tt> from  the  SWIG root directory after installing SWIG.
+ The Ocaml  module has been  tested using the system's dynamic linking  (the
+usual -lxxx  against libxxx.so, as well as with Gerd Stolpmann's 
+<a
+ href="http://www.ocaml-programming.de/packages/documentation/dl/">Dl package 
+</a>.  The ocaml_dynamic and ocaml_dynamic_cpp targets in the
+file Examples/Makefile illustrate how to compile and link SWIG modules that
+will be loaded dynamically.  This has only been tested on Linux so far.
+</p>
+
+<H3><a name="Ocaml_nn3"></a>25.1.1 Running SWIG</H3>
+
+
+<p>
+                  The basics of getting a SWIG Ocaml module up and running
+ can   be  seen  from one of SWIG's example Makefiles, but is also described
+ here.   To  build  an Ocaml module, run SWIG using the <tt>-ocaml</tt>
+option. 
+</p>
+
+<div class="code">                                    
+  <pre>
+%swig -ocaml example.i
+  </pre>
+</div>
+                         
+<p> This will produce 3 files. The file <tt>example_wrap.c</tt> contains
+all of the C code needed to build an Ocaml module.  To build the module,
+you will compile the file  <tt>example_wrap.c</tt> with <tt>ocamlc</tt> or
+<tt>ocamlopt</tt> to create the needed .o file.  You will need to compile
+the resulting .ml and .mli files as well, and do the final link with -custom
+(not needed for native link). </p>
+               
+<H3><a name="Ocaml_nn4"></a>25.1.2 Compiling the code</H3>
+
+
+<p>
+The O'Caml SWIG module now requires you to compile a module (<tt>Swig</tt>) 
+separately.  In addition to aggregating common SWIG functionality, the Swig
+module contains the data structure that represents C/C++ values.  This allows
+easier data sharing between modules if two or more are combined, because
+the type of each SWIG'ed module's c_obj is derived from Swig.c_obj_t.  This
+also allows SWIG to acquire new conversions painlessly, as well as giving
+the user more freedom with respect to custom typing.
+
+                  Use <tt>ocamlc</tt> or <tt>ocamlopt</tt> to compile your
+ SWIG   interface   like:             
+</p>
+                       
+<div class="code">                                    
+  <pre>
+% swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
+% ocamlc -c swig.mli ; ocamlc -c swig.ml
+% ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c
+% ocamlc -c example.mli
+% ocamlc -c example.ml
+  </pre>
+</div>
+                         
+<p> <tt>ocamlc</tt> is aware of .c files and knows how to handle them. Unfortunately,
+      it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked
+     in C++ mode, you must: </p>
+                       
+<div class="code">                                    
+  <pre>
+% cp example_wrap.cxx example_wrap.cxx.c<br>% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c<br>% ...<br>
+  </pre>
+</div>
+
+<H3><a name="Ocaml_nn5"></a>25.1.3 The camlp4 module</H3>
+
+
+<p>
+The camlp4 module (swigp4.ml -&gt; swigp4.cmo) contains a simple rewriter which
+makes C++ code blend more seamlessly with objective caml code.  It's use is
+optional, but encouraged.  The source file is included in the Lib/ocaml
+directory of the SWIG source distribution.  You can checkout this file with 
+<tt>"swig -ocaml -co swigp4.ml"</tt>.  You should compile the file with 
+<tt>"ocamlc -I `camlp4 -where` -pp 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"</tt>
+</p>
+
+<p>
+The basic principle of the module is to recognize certain non-caml expressions
+and convert them for use with C++ code as interfaced by SWIG.  The camlp4
+module is written to work with generated SWIG interfaces, and probably isn't
+great to use with anything else.
+</p>
+
+<p>
+Here are the main rewriting rules:
+</p>
+
+<table border="1" summary="Rewriting rules">
+<tr><th>Input</th><th>Rewritten to</th></tr>
+<tr><td>f'( ... ) as in<br> atoi'("0") or<br> _exit'(0)</td>
+<td>f(C_list [ ... ]) as in<br> atoi (C_list [ C_string "0" ]) or<br> _exit (C_list [ C_int 0 ])</td></tr>
+<tr><td>object -&gt; method ( ... )</td><td>(invoke object) "method" (C_list [ ... ])</td></tr>
+<tr><td>
+object <i>'binop</i> argument as in<br>
+a '+= b</td>
+<td>
+(invoke object) "+=" argument as in<br>
+(invoke a) "+=" b<td></tr>
+<tr><th colspan=2>Note that because camlp4 always recognizes &lt;&lt; 
+and &gt;&gt;, they are replaced by lsl and lsr in operator names.
+<tr><td>
+<i>'unop</i> object as in<br>
+'! a
+</td><td>
+(invoke a) "!" C_void</td></tr>
+<tr><td>
+<b>Smart pointer access like this</b><br>
+object '-&gt; method ( args )<br>
+</td><td>
+(invoke (invoke object "-&gt;" C_void))
+</td></tr>
+<tr><td>
+<b>Invoke syntax</b><br>
+object . '( ... )
+</td><td>
+(invoke object) "()" (C_list [ ... ])
+</td></tr>
+<tr><td>
+<b>Array syntax</b><br>
+object '[ 10 ]
+</td><td>
+(invoke object) "[]" (C_int 10)
+</td></tr>
+<tr><td>
+<b>Assignment syntax</b><br>
+let a = '10 and b = '"foo" and c = '1.0 and d = 'true
+</td><td>
+let a = C_int 10 and b = C_string "foo" and c = C_double 1.0 and d = C_bool true
+</td></tr>
+<tr><td>
+<b>Cast syntax</b><br>
+let a = _atoi '("2") as int<br>
+let b = (getenv "PATH") to string<br>
+This works for int, string, float, bool
+</td><td>
+let a = get_int (_atoi (C_string "2"))<br>
+let b = C_string (getenv "PATH")
+</td></tr>
+</table>
+
+<H3><a name="Ocaml_nn6"></a>25.1.4 Using your module</H3>
+
+
+<p>
+You can test-drive your module by building a
+toplevel ocaml interpreter.  Consult the ocaml manual for details.
+</p>
+  
+<p>
+When linking any ocaml bytecode with your module, use the -custom
+      option to build your functions into the primitive list. This
+      option is not needed when you build native code.
+</p>
+
+<H3><a name="Ocaml_nn7"></a>25.1.5 Compilation problems and compiling with C++</H3>
+
+
+<p>
+As mentioned above, .cxx files need special
+handling to be compiled with <tt>ocamlc</tt>.  Other than that, C code
+that uses <tt>class</tt> as a non-keyword, and C code that is too
+liberal with pointer types may not compile under the C++ compiler.
+Most code meant to be compiled as C++ will not have problems.
+</p>
+
+<H2><a name="Ocaml_nn8"></a>25.2 The low-level Ocaml/C interface</H2>
+
+
+<p>
+In order to provide access to overloaded functions, and
+provide sensible outputs from them, all C entities are represented as
+members of the c_obj type:
+</p>
+
+<p>
+In the code as seen by the typemap
+writer, there is a value, swig_result, that always contains the
+current return data.  It is a list, and must be appended with the
+caml_list_append function, or with functions and macros provided by
+objective caml.<br>
+</p>
+                 
+<div class="code"><pre>
+type c_obj =
+    C_void
+  | C_bool of bool
+  | C_char of char
+  | C_uchar of char
+  | C_short of int
+  | C_ushort of int
+  | C_int of int
+  | C_uint of int32
+  | C_int32 of int32
+  | C_int64 of int64
+  | C_float of float
+  | C_double of float
+  | C_ptr of int64 * int64
+  | C_array of c_obj array
+  | C_list of c_obj list
+  | C_obj of (string -&gt; c_obj -&gt; c_obj)
+  | C_string of string
+  | C_enum of c_enum_t
+</pre></div>
+
+<p>
+        A few functions exist which generate and return these:
+</p>
+               
+<ul>
+          <li>caml_ptr_val receives a c_obj and returns a void *. &nbsp;This
+  should   be used for all pointer purposes.</li>
+          <li>caml_long_val receives a c_obj and returns a long. &nbsp;This 
+ should   be used for most integral purposes.<br>
+          </li>
+          <li>caml_val_ptr receives a void * and returns a c_obj.</li>
+          <li>caml_val_bool receives a C int and returns a c_obj representing 
+  it's  bool value.</li>
+          <li>caml_val_(u)?(char|short|int|long|float|double) receives an 
+appropriate    C value and returns a c_obj representing it.</li>
+          <li>caml_val_string receives a char * and returns a string value.</li>
+          <li>caml_val_string_len receives a char * and a length and returns
+  a  string  value.</li>
+          <li>caml_val_obj receives a void * and an object type and returns 
+ a  C_obj,  which contains a closure giving method access.</li>
+               
+</ul>
+
+<p>
+Because of this style, a typemap can return any kind of value it
+wants    from  a function. &nbsp;This enables out typemaps and inout typemaps
+to  work  well.  &nbsp;The one thing to remember about outputting values
+is that  you  must append them to the return list with swig_result = caml_list_append(swig_result,v).
+</p>
+
+<p>
+&nbsp;This function will return a new list that has your element
+    appended.  Upon return to caml space, the fnhelper function
+    beautifies the result.  A list containing a single item degrades to
+    only that item (i.e. [ C_int 3 ] -&gt; C_int 3), and a list
+    containing more than one item is wrapped in C_list (i.e. [ C_char
+    'a' ; C_char 'b' -&gt; C_list [ C_char 'a' ; C_char b
+    ]). &nbsp;This is in order to make return values easier to handle
+    when functions have only one return value, such as constructors,
+    and operators. &nbsp;In addition, string, pointer, and object
+    values are interchangeable with respect to caml_ptr_val, so you can
+    allocate memory as caml strings and still use the resulting
+    pointers for C purposes, even using them to construct simple objects
+    on.  Note, though, that foreign C++ code does not respect the garbage
+    collector, although the SWIG interface does.</p>
+
+    <p>
+    The wild card type that you can use in lots of different ways is
+    C_obj.  It allows you to wrap any type of thing you like as an
+    object using the same mechanism that the ocaml module
+    does. &nbsp;When evaluated in caml_ptr_val, the returned value is
+    the result of a call to the object's "&amp;" operator, taken as a pointer.
+    </p>
+    <p>
+    You should only construct values using objective caml, or using the
+    functions caml_val_* functions provided as static functions to a SWIG
+    ocaml module, as well as the caml_list_* functions.  These functions
+    provide everything a typemap needs to produce values.  In addition,
+    value items pass through directly, but you must make your own type
+    signature for a function that uses value in this way.
+    </p>
+
+<H3><a name="Ocaml_nn9"></a>25.2.1 The generated module</H3>
+
+
+<p>
+The SWIG <tt>%module</tt> directive specifies the name of the Ocaml
+module to be generated.  If you specified `<tt>%module example</tt>',
+then your Ocaml code will be accessible in the module Example.  The
+module name is always capitalized as is the ocaml convention.  Note
+that you must not use any Ocaml keyword to name your module.  Remember
+that the keywords are not the same as the C++ ones.
+</p>
+
+<p>
+You can introduce extra code into the output wherever you like with SWIG.
+These are the places you can introduce code:
+<table border="1" summary="Extra code sections">
+<tr><td>"header"</td><td>This code is inserted near the beginning of the 
+C wrapper file, before any function definitions.</td></tr>
+<tr><td>"wrapper"</td><td>This code is inserted in the function definition
+section.</td></tr>
+<tr><td>"runtime"</td><td>This code is inserted near the end of the C wrapper
+file.</td></tr>
+<tr><td>"mli"</td><td>This code is inserted into the caml interface file.
+Special signatures should be inserted here.
+</td></tr>
+<tr><td>"ml"</td><td>This code is inserted in the caml code defining the 
+interface to your C code.  Special caml code, as well as any initialization
+which should run when the module is loaded may be inserted here.
+</td></tr>   
+<tr><td>"classtemplate"</td><td>The "classtemplate" place is special because
+it describes the output SWIG will generate for class definitions.
+</td></tr>
+</table>
+               
+<H3><a name="Ocaml_nn10"></a>25.2.2 Enums</H3>
+
+
+<p>
+SWIG will wrap enumerations as polymorphic variants in the output
+Ocaml code, as above in C_enum.&nbsp; In order to support all
+C++-style uses of enums, the function int_to_enum and enum_to_int are
+provided for ocaml code to produce and consume these values as
+integers.  &nbsp;Other than that, correct uses of enums will not have
+a problem. &nbsp;Since enum labels may overlap between enums, the
+enum_to_int and int_to_enum functions take an enum type label as an
+argument.  Example:
+</p>
+
+<div class="code"><pre>
+%module enum_test
+%{
+enum c_enum_type { a = 1, b, c = 4, d = 8 };
+%}
+enum c_enum_type { a = 1, b, c = 4, d = 8 };
+</pre></div>
+
+<p>               
+The output mli contains:
+</p>          
+
+<div class="code"><pre>
+type c_enum_type = [
+  `unknown
+| `c_enum_type
+]
+type c_enum_tag = [
+  `int of int
+| `a
+| `b
+| `c
+| `d
+]
+val int_to_enum c_enum_type -&gt; int -&gt; c_obj
+val enum_to_int c_enum_type -&gt; c_obj -&gt; c_obj
+</pre>
+     </div>
+
+<p>
+   So it's possible to do this:   
+</p>
+
+<div class="code">      
+  <pre>
+bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
+bash-2.05a$ ./enum_test_top 
+        Objective Caml version 3.04
+
+# open Enum_test ;;
+# let x = C_enum `a ;;
+val x : Enum_test.c_obj = C_enum `a
+# enum_to_int `c_enum_type x ;;
+- : Enum_test.c_obj = C_int 1
+# int_to_enum `c_enum_type 4 ;;
+- : Enum_test.c_obj = C_enum `c
+</pre>
+  </div>
+
+<H4><a name="Ocaml_nn11"></a>25.2.2.1 Enum typing in Ocaml</H4>
+
+
+<p>
+The ocaml SWIG module now has support for loading and using multiple SWIG
+modules at the same time.  This enhances modularity, but presents problems
+when used with a language which assumes that each module's types are complete
+at compile time.  In order to achieve total soundness enum types are now
+isolated per-module.  The type issue matters when values are shared between
+functions imported from different modules.  You must convert values to master
+values using the swig_val function before sharing them with another module.
+</p>
+
+<H3><a name="Ocaml_nn12"></a>25.2.3 Arrays</H3>
+
+
+<H4><a name="Ocaml_nn13"></a>25.2.3.1 Simple types of bounded arrays</H4>
+
+
+<p>
+SWIG has support for array types, but you generally will need to provide
+a typemap to handle them.  You can currently roll your own, or expand
+some of the macros provided (but not included by default) with the SWIG
+distribution.
+</p>
+
+<p>
+By including "carray.i", you will get access to some macros that help you
+create typemaps for array types fairly easily. 
+</p>
+
+<p>
+<tt>%make_simple_array_typemap</tt> is the easiest way to get access to
+arrays of simple types with known bounds in your code, but this only works
+for arrays whose bounds are completely specified.
+</p>
+
+<H4><a name="Ocaml_nn14"></a>25.2.3.2 Complex and unbounded arrays</H4>
+
+
+<p>
+Unfortunately, unbounded arrays and pointers can't be handled in a
+completely general way by SWIG, because the end-condition of such an
+array can't be predicted.  In some cases, it will be by consent
+(e.g. an array of four or more chars), sometimes by explicit length
+(char *buffer, int len), and sometimes by sentinel value (0,-1,etc.).
+SWIG can't predict which of these methods will be used in the array,
+so you have to specify it for yourself in the form of a typemap.
+</p>
+
+<H4><a name="Ocaml_nn15"></a>25.2.3.3 Using an object</H4>
+
+
+<p>
+It's possible to use C++ to your advantage by creating a simple object that
+provides access to your array.  This may be more desirable in some cases,
+since the object can provide bounds checking, etc., that prevents crashes.
+</p>
+
+<p>
+Consider writing an object when the ending condition of your array is complex,
+such as using a required sentinel, etc.
+</p>
+
+<H4><a name="Ocaml_nn16"></a>25.2.3.4 Example typemap for a function taking float * and int</H4>
+
+
+<p>
+This is a simple example <tt>in</tt> typemap for an array of float, where the
+length of the array is specified as an extra parameter.  Other such typemaps
+will work similarly.  In the example, the function printfloats is called with
+a float array, and specified length.  The actual length reported in the len
+argument is the length of the array passed from ocaml, making passing an array
+into this type of function convenient.
+</p>
+
+<table border="1" bgcolor="#dddddd" summary="float * and int typemap example">
+<tr><th><center>tarray.i</center></th></tr>
+<tr><td><pre>
+%module tarray
+%{
+#include &lt;stdio.h&gt;
+
+void printfloats( float *tab, int len ) {
+	int i;
+
+	for( i = 0; i &lt; len; i++ ) {
+		printf( "%f ", tab[i] );
+	}
+
+	printf( "\n" );  
+}
+%}
+
+%typemap(in) (float *tab, int len) {
+    int i;
+    /* $*1_type */
+    $2 = caml_array_len($input);
+    $1 = ($*1_type *)malloc( $2 * sizeof( float ) );
+    for( i = 0; i &lt; $2; i++ ) {
+        $1[i] = caml_double_val(caml_array_nth($input,i));
+    }
+}
+
+void printfloats( float *tab, int len );
+</pre></td></tr>
+<tr><th>Sample Run</th></tr>
+<tr><td><pre>
+# open Tarray ;;
+# _printfloats (C_array [| C_double 1.0 ; C_double 3.0 ; C_double 5.6666 |]) ;;
+1.000000 3.000000 5.666600
+- : Tarray.c_obj = C_void
+</pre></td></tr></table>
+
+
+<H3><a name="Ocaml_nn17"></a>25.2.4 C++ Classes</H3>
+
+
+<p>
+C++ classes, along with structs and unions are represented by C_obj
+(string -&gt; c_obj -&gt; c_obj) wrapped closures. &nbsp;These objects
+contain a method list, and a type, which allow them to be used like
+C++ objects.  When passed into typemaps that use pointers, they
+degrade to pointers through their "&amp;" method. &nbsp;Every method
+an object has is represented as a string in the object's method table,
+and each method table exists in memory only once.  &nbsp;In addition
+to any other operators an object might have, certain builtin ones are
+provided by SWIG:  (all of these take no arguments (C_void))
+</p>
+
+<table summary="SWIG provided operators">
+<tr><td>"~"</td><td>Delete this object</td></tr>
+<tr><td>"&amp;"</td><td>Return an ordinary C_ptr value representing this 
+object's address</td></tr>
+<tr><td>"sizeof"</td><td>If enabled with ("sizeof"="1") on the module node,
+return the object's size in char.</td></tr>
+<tr><td>":methods"</td><td>Returns a list of strings containing the names of
+the methods this object contains</td></tr>
+<tr><td>":classof"</td><td>Returns the name of the class this object belongs 
+to.</td></tr>
+<tr><td>":parents"</td><td>Returns a list of all direct parent classes which
+have been wrapped by SWIG.</td></tr>
+<tr><td>"::[parent-class]"</td><td>Returns a view of the object as the
+indicated parent class.  This is mainly used internally by the SWIG module,
+but may be useful to client programs.</td></tr>
+<tr><td>"[member-variable]"</td><td>Each member variable is wrapped as a
+method with an optional parameter.  
+Called with one argument, the member variable is set to the value of the 
+argument.  With zero arguments, the value is returned.
+</td></tr>
+</table>
+
+<p>
+Note that this string belongs to the wrapper object, and not
+the underlying pointer, so using create_[x]_from_ptr alters the
+returned value for the same object.
+</p>
+
+<H4><a name="Ocaml_nn18"></a>25.2.4.1 STL vector and string Example</H4>
+
+
+<p>
+Standard typemaps are now provided for STL vector and string.  More are in
+the works.  STL strings are passed just like normal strings, and returned
+as strings.  STL string references don't mutate the original string, (which
+might be surprising), because Ocaml strings are mutable but have fixed
+length.  Instead, use multiple returns, as in the argout_ref example.
+</p>
+
+<table border="1" bgcolor="#dddddd" summary="STL vector and string example">
+<tr><th><center>example.i</center></th></tr>
+<tr><td><pre>
+%module example
+%{
+#include "example.h"
+%}
+
+%include stl.i
+
+namespace std {
+        %template(StringVector) std::vector &lt; string &gt;;
+};
+
+%include example.h
+</pre></td></tr>
+<tr><td><font size="-1"><i>This example is in Examples/ocaml/stl
+</i></font></td></tr>
+</table>
+
+<p>
+Since there's a makefile in that directory, the example is easy to build.
+</p>
+
+<p>
+Here's a sample transcript of an interactive session using a string vector
+after making a toplevel (make toplevel).  This example uses the camlp4 
+module.
+</p>
+
+<div class="code"><pre>
+bash-2.05a$ ./example_top 
+        Objective Caml version 3.06
+
+        Camlp4 Parsing version 3.06
+
+# open Swig ;;
+# open Example ;;
+# let x = new_StringVector '() ;;
+val x : Example.c_obj = C_obj &lt;fun&gt;
+# x -&gt; ":methods" () ;;
+- : Example.c_obj =
+C_list
+ [C_string "nop"; C_string "size"; C_string "empty"; C_string "clear";
+  C_string "push_back"; C_string "[]"; C_string "="; C_string "set";
+  C_string "~"; C_string "&amp;"; C_string ":parents"; C_string ":classof";
+  C_string ":methods"]
+# x -&gt; push_back ("foo") ;;
+- : Example.c_obj = C_void
+# x -&gt; push_back ("bar") ;;
+- : Example.c_obj = C_void
+# x -&gt; push_back ("baz") ;;
+- : Example.c_obj = C_void
+# x '[1] ;;
+- : Example.c_obj = C_string "bar"
+# x -&gt; set (1,"spam") ;;
+- : Example.c_obj = C_void
+# x '[1] ;;
+- : Example.c_obj = C_string "spam"
+# for i = 0 to (x -&gt; size() as int) - 1 do 
+    print_endline ((x '[i to int]) as string) 
+  done ;;
+foo
+bar
+baz
+- : unit = ()
+# 
+</pre></div>
+
+<H4><a name="Ocaml_nn19"></a>25.2.4.2 C++ Class Example</H4>
+
+
+<p>
+Here's a simple example using Trolltech's Qt Library:
+</p>
+
+<table border="1" bgcolor="#dddddd" summary="Qt Library example">
+  <tr><th><center>qt.i</center></th></tr>
+<tr><td><pre>
+%module qt
+%{
+#include &lt;qapplication.h&gt;
+#include &lt;qpushbutton.h&gt;
+%}
+class QApplication {
+public:
+        QApplication( int argc, char **argv );
+        void setMainWidget( QWidget *widget );
+        void exec();
+};
+
+class QPushButton {
+public:
+        QPushButton( char *str, QWidget *w );
+        void resize( int x, int y );
+        void show();
+};
+</pre></td></tr></table>
+
+<H4><a name="Ocaml_nn20"></a>25.2.4.3 Compiling the example</H4>
+
+
+<div class="code"><pre>
+bash-2.05a$ QTPATH=/your/qt/path
+bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
+bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml
+bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml
+bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include  qt.i
+bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
+bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c 
+bash-2.05a$ ocamlc -c qt.mli
+bash-2.05a$ ocamlc -c qt.ml
+bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
+  camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \
+  -L$QTPATH/lib -cclib -lqt
+</pre></div>
+
+<H4><a name="Ocaml_nn21"></a>25.2.4.4 Sample Session</H4>
+
+
+<div class="code"><pre>
+bash-2.05a$ ./qt_top 
+        Objective Caml version 3.06
+
+        Camlp4 Parsing version 3.06
+
+# open Swig ;;
+# open Qt ;;
+# let a = new_QApplication '(0,0) ;;
+val a : Qt.c_obj = C_obj &lt;fun&gt;
+# let hello = new_QPushButton '("hi",0) ;;
+val hello : Qt.c_obj = C_obj &lt;fun&gt;
+# hello -&gt; resize (100,30) ;;
+- : Qt.c_obj = C_void
+# hello -&gt; show () ;;
+- : Qt.c_obj = C_void
+# a -&gt; exec () ;;
+</pre></div>
+
+<p>
+Assuming you have a working installation of QT, you will see a window
+containing the string "hi" in a button.  
+</p>
+
+<H3><a name="Ocaml_nn22"></a>25.2.5 Director Classes</H3>
+
+
+<H4><a name="Ocaml_nn23"></a>25.2.5.1 Director Introduction</H4>
+
+
+<p>
+Director classes are classes which allow Ocaml code to override the public
+methods of a C++ object.  This facility allows the user to use C++ libraries
+that require a derived class to provide application specific functionality in
+the context of an application or utility framework.
+</p>
+
+<p>
+You can turn on director classes by using an optional module argument like
+this:
+</p>
+
+<div class="code"><pre>
+%module(directors="1")
+
+...
+
+// Turn on the director class for a specific class like this:
+%feature("director")
+class foo {
+  ...
+};
+</pre></div>
+
+<H4><a name="Ocaml_nn24"></a>25.2.5.2 Overriding Methods in Ocaml</H4>
+
+
+<p>
+Because the Ocaml language module treats C++ method calls as calls to a
+certain function, all you need to do is to define the function that will
+handle the method calls in terms of the public methods of the object, and
+any other relevant information.  The function <tt>new_derived_object</tt>
+uses a stub class to call your methods in place of the ones provided by the
+underlying implementation.  The object you receive is the underlying object,
+so you are free to call any methods you want from within your derived method.
+Note that calls to the underlying object do not invoke Ocaml code.  You need
+to handle that yourself.
+</p>
+
+<p>
+<tt>new_derived_object</tt> receives your function, the function that creates
+the underlying object, and any constructor arguments, and provides an
+object that you can use in any usual way.  When C++ code calls one of the
+object's methods, the object invokes the Ocaml function as if it had been
+invoked from Ocaml, allowing any method definitions to override the C++ ones.
+</p>
+
+<p>
+In this example, I'll examine the objective caml code involved in providing
+an overloaded class.  This example is contained in Examples/ocaml/shapes.
+</p>
+
+<H4><a name="Ocaml_nn25"></a>25.2.5.3 Director Usage Example</H4>
+
+
+<table border="1" bgcolor="#dddddd" summary="Director usage example">
+<tr><th><center>example_prog.ml</center>
+</th></tr>
+<tr><td><pre>
+open Swig
+open Example
+
+...
+
+let triangle_class pts ob meth args =
+  match meth with
+      "cover" -&gt;
+        (match args with
+             C_list [ x_arg ; y_arg ] -&gt;
+	     let xa = x_arg as float
+	     and ya = y_arg as float in
+	       (point_in_triangle pts xa ya) to bool
+           | _ -&gt; raise (Failure "cover needs two double arguments."))
+    | _ -&gt; (invoke ob) meth args ;;
+
+let triangle =
+  new_derived_object 
+    new_shape
+    (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
+    '() ;;
+
+let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;;
+</pre></td></tr>
+</table>
+
+<p>
+This is the meat of what you need to do.  The actual "class" definition
+containing the overloaded method is defined in the function triangle_class.
+This is a lot like the class definitions emitted by SWIG, if you look at
+example.ml, which is generated when SWIG consumes example.i.  Basically,
+you are given the arguments as a c_obj and the method name as a string, and
+you must intercept the method you are interested in and provide whatever
+return value you need.  Bear in mind that the underlying C++ code needs the
+right return type, or an exception will be thrown.  This exception will
+generally be Failure, or NotObject.  You must call other ocaml methods that
+you rely on yourself.  Due to the way directors are implemented, method
+calls on your object from with ocaml code will always invoke C++ methods
+even if they are overridden in ocaml.
+</p>
+
+<p>
+In the example, the draw_shape_coverage function plots the indicated number
+of points as either covered (<tt>x</tt>) or uncovered ( ) between
+0 and 1 on the X and Y axes.  Your shape implementation can provide any
+coverage map it likes, as long as it responds to the "cover" method call
+with a boolean return (the underlying method returns bool).  This might allow
+a tricky shape implementation, such as a boolean combination, to be expressed
+in a more effortless style in ocaml, while leaving the "engine" part of the
+program in C++.
+</p>
+
+<H4><a name="Ocaml_nn26"></a>25.2.5.4 Creating director objects</H4>
+
+
+<p>
+The definition of the actual object triangle can be described this way:
+</p>
+
+<div class="code"><pre>
+let triangle =
+  new_derived_object 
+    new_shape
+    (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
+    '()
+</pre></div>
+
+<p>
+The first argument to <tt>new_derived_object</tt>, new_shape is the method
+which returns a shape instance.  This function will be invoked with the 
+third argument will be appended to the argument list [ C_void ].  In the
+example, the actual argument list is sent as (C_list [ C_void ; C_void ]).
+The augmented constructor for a director class needs the first argument
+to determine whether it is being constructed as a derived object, or as
+an object of the indicated type only (in this case <tt>shape</tt>).  The
+Second argument is a closure that will be added to the final C_obj.  
+</p>
+
+<p>
+The actual object passed to the self parameter of the director object will
+be a C_director_core, containing a c_obj option ref and a c_obj.  The
+c_obj provided is the same object that will be returned from new_derived
+object, that is, the object exposing the overridden methods.  The other part
+is an option ref that will have its value extracted before becoming the
+<tt>ob</tt> parameter of your class closure.  This ref will contain
+<tt>None</tt> if the C++ object underlying is ever destroyed, and will
+consequently trigger an exception when any method is called on the object
+after that point (the actual raise is from an inner function used by
+new_derived_object, and throws NotObject).  This prevents a deleted C++
+object from causing a core dump, as long as the object is destroyed
+properly.
+</p>
+
+<H4><a name="Ocaml_nn27"></a>25.2.5.5 Typemaps for directors, <tt>directorin, directorout, directorargout</tt></H4>
+
+
+<p>
+Special typemaps exist for use with directors, the <tt>directorin, directorout, directorargout</tt>
+are used in place of <tt>in, out, argout</tt> typemaps, except that their
+direction is reversed.  They provide for you to provide argout values, as
+well as a function return value in the same way you provide function arguments,
+and to receive arguments the same way you normally receive function returns.
+</p>
+
+<H4><a name="Ocaml_nn28"></a>25.2.5.6 <tt>directorin</tt> typemap</H4>
+
+
+<p>
+The <tt>directorin</tt> typemap is used when you will receive arguments from a call
+made by C++ code to you, therefore, values will be translated from C++ to
+ocaml.  You must provide some valid C_obj value.  This is the value your ocaml
+code receives when you are called.  In general, a simple <tt>directorin</tt> typemap
+can use the same body as a simple <tt>out</tt> typemap.
+</p>
+
+<H4><a name="Ocaml_nn29"></a>25.2.5.7 <tt>directorout</tt> typemap</H4>
+
+
+<p>
+The <tt>directorout</tt> typemap is used when you will send an argument from your
+code back to the C++ caller.  That is; directorout specifies a function return
+conversion.  You can usually use the same body as an <tt>in</tt> typemap
+for the same type, except when there are special requirements for object
+ownership, etc.
+</p>
+
+<H4><a name="Ocaml_nn30"></a>25.2.5.8 <tt>directorargout</tt> typemap</H4>
+
+
+<p>
+C++ allows function arguments which are by pointer (*) and by reference (&amp;)
+to receive a value from the called function, as well as sending one there.
+Sometimes, this is the main purpose of the argument given.  <tt>directorargout</tt>
+typemaps allow your caml code to emulate this by specifying additional return
+values to be put into the output parameters.  The SWIG ocaml module is a bit
+loose in order to make code easier to write.  In this case, your return to
+the caller must be a list containing the normal function return first, followed
+by any argout values in order.  These argout values will be taken from the
+list and assigned to the values to be returned to C++ through directorargout typemaps.
+In the event that you don't specify all of the necessary values, integral
+values will read zero, and struct or object returns have undefined results.
+</p>
+
+<H3><a name="Ocaml_nn31"></a>25.2.6 Exceptions</H3>
+
+
+<p>
+Catching exceptions is now supported using SWIG's %exception feature.  A simple
+but not too useful example is provided by the throw_exception testcase in
+Examples/test-suite.  You can provide your own exceptions, too.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Octave.html b/trunk/Doc/Manual/Octave.html
new file mode 100644
index 0000000..97e1be1
--- /dev/null
+++ b/trunk/Doc/Manual/Octave.html
@@ -0,0 +1,836 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Octave</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+
+<body bgcolor="#ffffff">
+
+<H1><a name="Octave"></a>26 SWIG and Octave</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Octave_nn2">Preliminaries</a>
+<li><a href="#Octave_nn3">Running SWIG</a>
+<ul>
+<li><a href="#Octave_nn5">Compiling a dynamic module</a>
+<li><a href="#Octave_nn6">Using your module</a>
+</ul>
+<li><a href="#Octave_nn7">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="#Octave_nn8">Modules</a>
+<li><a href="#Octave_nn9">Functions</a>
+<li><a href="#Octave_nn10">Global variables</a>
+<li><a href="#Octave_nn11">Constants and enums</a>
+<li><a href="#Octave_nn12">Pointers</a>
+<li><a href="#Octave_nn13">Structures and C++ classes</a>
+<li><a href="#Octave_nn15">C++ inheritance</a>
+<li><a href="#Octave_nn17">C++ overloaded functions</a>
+<li><a href="#Octave_nn18">C++ operators</a>
+<li><a href="#Octave_nn19">Class extension with %extend</a>
+<li><a href="#Octave_nn20">C++ templates</a>
+<li><a href="#Octave_nn21">C++ Smart Pointers</a>
+<li><a href="#Octave_nn22">Directors (calling Octave from C++ code)</a>
+<li><a href="#Octave_nn23">Threads</a>
+<li><a href="#Octave_nn24">Memory management</a>
+<li><a href="#Octave_nn25">STL support</a>
+<li><a href="#Octave_nn26">Matrix typemaps</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+         Octave is a high-level language intended for numerical programming that is mostly compatible with MATLAB.
+More information can be found at <a href="http://www.octave.org">www.octave.org</a>. 
+</p>
+
+<p>
+     This chapter is intended to give an introduction to using the module. You should also read the SWIG documentation that is not specific to Octave.
+Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).
+</p>
+
+<H2><a name="Octave_nn2"></a>26.1 Preliminaries</H2>
+
+
+<p>
+The current SWIG implemention is based on Octave 2.9.12. Support for other versions (in particular the recent 3.0) has not been tested, nor has support for any OS other than Linux.
+</p>
+
+<H2><a name="Octave_nn3"></a>26.2 Running SWIG</H2>
+
+
+<p>
+Let's start with a very simple SWIG interface file:
+</p>
+
+<div class="code"><pre>%module example
+%{
+#include "example.h"
+%}
+int gcd(int x, int y);
+extern double Foo; </pre></div>
+
+<p>
+To build an Octave module, run SWIG using the <tt>-octave</tt> option. The <tt>-c++</tt> option is required (for now) as Octave itself is written in C++ and thus the wrapper code must also be. 
+</p>
+
+<div class="shell"><pre>$ swig -octave -c++ example.i </pre></div>
+
+<p>
+This creates a C/C++ source file <tt>example_wrap.cxx</tt>. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.
+</p>
+
+<p>
+The swig command line has a number of options you can use, like to redirect it's output. Use <tt>swig --help</tt> to learn about these.
+</p>
+
+<H3><a name="Octave_nn5"></a>26.2.1 Compiling a dynamic module</H3>
+
+
+<p>
+Octave modules are DLLs/shared objects having the ".oct" suffix.
+Building an oct file is usually done with the mkoctfile command (either within Octave itself, or from the shell). For example,
+</p>
+
+<div class="shell"><pre>
+$ swig -octave -c++ example.i -o example_wrap.cxx
+$ mkoctfile example_wrap.cxx example.c
+</pre></div>
+
+<p>
+        where example.c is the file containing the gcd() implementation. 
+</p>
+
+<p>
+        mkoctfile can also be used to extract the build parameters required to invoke the compiler and linker yourself. See the Octave manual and mkoctfile man page. 
+</p>
+
+<p>
+        mkoctfile will produce example.oct, which contains the compiled extension module. Loading it into Octave is then a matter of invoking 
+</p>
+
+          <div class="targetlang"><pre>octave:1&gt; example</pre></div>
+
+<H3><a name="Octave_nn6"></a>26.2.2 Using your module</H3>
+
+
+<p>
+Assuming all goes well, you will be able to do this: 
+        <br>
+</p>
+
+          <div class="targetlang"><pre>$ octave -q
+octave:1&gt; example
+octave:2&gt; example.gcd(4,6)
+ans =  2
+octave:3&gt; example.cvar.Foo
+ans =  3
+octave:4&gt; example.cvar.Foo=4;
+octave:5&gt; example.cvar.Foo
+ans =  4 </pre></div>
+
+<H2><a name="Octave_nn7"></a>26.3 A tour of basic C/C++ wrapping</H2>
+
+
+<H3><a name="Octave_nn8"></a>26.3.1 Modules</H3>
+
+
+<p>
+The SWIG module directive specifies the name of the Octave module. If you specify `module example', then in Octave everything in the module will be accessible under "example", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name.
+</p>
+
+<p>
+When Octave is asked to invoke <tt>example</tt>, it will try to find the .m or .oct file that defines the function "example". It will thusly find example.oct, that upon loading will register all of the module's symbols.
+</p>
+
+<p>
+Giving this function a parameter "global" will cause it to load all symbols into the global namespace in addition to the <tt>example</tt> namespace. For example: 
+</p>
+
+    <div class="targetlang"><pre>$ octave -q
+octave:1&gt; example("global")
+octave:2&gt; gcd(4,6)
+ans =  2
+octave:3&gt; cvar.Foo
+ans =  3
+octave:4&gt; cvar.Foo=4;
+octave:5&gt; cvar.Foo
+ans =  4 
+</pre></div>
+<p>
+     It is also possible to rename the module namespace with an assignment, as in: <br>
+    <div class="targetlang"><pre>octave:1&gt; example;
+octave:2&gt; c=example;
+octave:3&gt; c.gcd(10,4)
+ans =  2 </pre></div>
+
+<p>
+All global variables are put into the cvar namespace object. This is accessible either as <tt>my_module.cvar</tt>, or just <tt>cvar</tt> (if the module is imported into the global namespace).
+</p>
+<p>
+One can also rename it by simple assignment, e.g.,
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; some_vars = cvar;
+</pre></div>
+
+<H3><a name="Octave_nn9"></a>26.3.2 Functions</H3>
+
+
+<p>
+Global functions are wrapped as new Octave built-in functions. For example, 
+</p>
+
+      <div class="code"><pre>&#037;module example
+int fact(int n); </pre></div>
+
+<p>
+     creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does: 
+</p>
+
+    <div class="targetlang"><pre>octave:1&gt; example.fact(4)
+24 </pre></div>
+
+<H3><a name="Octave_nn10"></a>26.3.3 Global variables</H3>
+
+
+<p>
+     Global variables are a little special in Octave. Given a global variable: 
+</p>
+
+    <div class="code"><pre>%module example
+extern double Foo;
+      </pre></div>
+
+<p>
+    To expose variables, SWIG actually generates two functions, to get and set the value. In this case, Foo_set and Foo_set would be generated. SWIG then automatically calls these functions when you get and set the variable-- in the former case creating a local copy in the interpreter of the C variables, and in the latter case copying an interpreter variables onto the C variable. 
+</p>
+
+    <div class="targetlang"><pre>octave:1&gt; example;
+octave:2&gt; c=example.cvar.Foo
+c =  3
+octave:3&gt; example.cvar.Foo=4;
+octave:4&gt; c
+c =  3
+octave:5&gt; example.cvar.Foo
+ans =  4</pre></div>
+
+<p>
+If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Octave error. Given a global variable: 
+</p>
+
+    <div class="code"><pre>%module example
+%immutable;
+extern double Foo;
+%mutable;
+</pre></div>
+
+<p>
+     SWIG will allow the the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called. 
+</p>
+
+    <div class="targetlang"><pre>octave:1&gt; example
+octave:2&gt; example.Foo=4
+error: attempt to set immutable member variable
+error: assignment failed, or no method for `swig_type = scalar'
+error: evaluating assignment expression near line 2, column 12 </pre></div>
+
+<p>
+    It is possible to add new functions or variables to the module. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so. 
+</p>
+
+    <div class="targetlang"><pre>octave:1&gt; example;
+octave:2&gt; example.PI=3.142;
+octave:3&gt; example.PI
+ans =  3.1420 </pre></div>
+
+<H3><a name="Octave_nn11"></a>26.3.4 Constants and enums</H3>
+
+
+<p>
+     Because Octave doesn't really have the concept of constants, C/C++ constants are not really constant in Octave. They are actually just a copy of the value into the Octave interpreter. Therefore they can be changed just as any other value. For example given some constants: 
+</p>
+
+    <div class="code"><pre>%module example
+%constant int ICONST=42;
+#define    SCONST      "Hello World"
+enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
+</pre></div>
+
+<p>
+    This is 'effectively' converted into the following Octave code: 
+</p>
+
+    <div class="targetlang"><pre>example.ICONST=42
+example.SCONST="Hello World"
+example.SUNDAY=0
+.... </pre></div>
+
+<H3><a name="Octave_nn12"></a>26.3.5 Pointers</H3>
+
+
+<p>
+      C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the &lt;file.h&gt; interface:
+       C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the &lt;file.h&gt; interface:
+</p>
+
+<div class="code"><pre>%module example
+FILE *fopen(const char *filename, const char *mode);
+int fputs(const char *, FILE *);
+int fclose(FILE *);
+</pre></div>
+
+<p>
+When wrapped, you will be able to use the functions in a natural way from Octave. For example:
+</p>
+
+<div class="targetlang"><pre>
+octave:1&gt; example;
+octave:2&gt; f=example.fopen("w","junk");
+octave:3&gt; example.fputs("Hello world",f);
+octave:4&gt; example.fclose(f);
+</pre></div>
+
+<p>
+     Simply printing the value of a wrapped C++ type will print it's typename. E.g., 
+</p>
+
+    <div class="targetlang"><pre>octave:1&gt; example;
+octave:2&gt; f=example.fopen("junk","w");
+octave:3&gt; f
+f =
+
+{
+  _p_FILE, ptr = 0x9b0cd00
+} </pre></div>
+
+<p>
+    As the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes and structs (see below).
+</p>
+
+    <div class="targetlang"><pre>octave:1&gt; example;
+octave:2&gt; f=example.fopen("not there","r");
+error: value on right hand side of assignment is undefined
+error: evaluating assignment expression near line 2, column 2 </pre></div>
+
+<H3><a name="Octave_nn13"></a>26.3.6 Structures and C++ classes</H3>
+
+
+<p>
+     SWIG wraps C structures and C++ classes by using a special Octave type called a <tt>swig_ref</tt>. A <tt>swig_ref</tt> contains a reference to one or more instances of C/C++ objects, or just the type information for an object.
+For each wrapped structure and class, a <tt>swig_ref</tt> will be exposed that has the name of the type. When invoked as a function, it creates a new object of its type and returns a <tt>swig_ref</tt> that points to that instance. This provides a very natural interface. For example, 
+</p>
+
+    <div class="code"><pre>struct Point{
+  int x,y;
+};
+</pre></div>
+
+<p>
+    is used as follows: 
+</p>
+
+    <div class="targetlang">
+      <pre>octave:1&gt; example;
+octave:2&gt; p=example.Point();
+octave:3&gt; p.x=3;
+octave:4&gt; p.y=5;
+octave:5&gt; p.x, p.y
+ans =  3
+ans =  5 
+</pre></div>
+<p>
+In C++, invoking the type object in this way calls the object's constructor.
+<tt>swig_ref</tt> objects can also be acquired by having a wrapped function return a pointer, reference, or value of a non-primitive type. 
+</p>
+<p>
+The swig_ref type handles indexing operations such that usage maps closely to what you would have in C/C++. 
+Structure members are accessed as in the above example, by calling set and get methods for C++ variables. 
+
+Methods also work as expected. For example, code wrapped in the following way
+</p>
+
+    <div class="code"><pre>class Point{
+public:
+  int x,y;
+  Point(int _x,int _y) : x(_x),y(_y) {}
+  double distance(const Point&amp; rhs) {
+    return sqrt(pow(x-rhs.x,2)+pow(y-rhs.y,2));
+  }
+  void set(int _x,int _y) {
+    x=_x; y=_y;
+  }
+};
+</pre></div>
+<p>
+can be used from Octave like this
+</p>
+    <div class="targetlang">
+      <pre>octave:1&gt; example;
+octave:2&gt; p1=example.Point(3,5);
+octave:3&gt; p2=example.Point(1,2);
+octave:4&gt; p1.distance(p2)
+ans =  3.6056
+</pre></div>
+<p>
+By using the <tt>swig_this()</tt> and <tt>swig_type()</tt> functions, one can discover the pointers to and types of the underlying C/C++ object.
+</p>
+
+    <div class="targetlang">
+      <pre>
+octave:5> swig_this(p1)
+ans = 162504808
+octave:6> swig_type(p1)
+ans = Point
+</pre></div>
+<p>
+Note that <tt>swig_ref</tt> is a reference-counted pointer to a C/C++ object/type, and as such has pass-by-reference semantics. For example if one has a allocated a single object but has two <tt>swig_ref</tt>'s pointing to it, modifying the object through either of them will change the single allocated object.
+This differs from the usual pass-by-value (copy-on-write) semantics that Octave maintains for built-in types. For example, in the following snippet, modifying <tt>b</tt> does not modify <tt>a</tt>,
+</p>
+
+    <div class="targetlang">
+      <pre>
+octave:7> a=struct('x',4)
+a =
+{
+  x =  4
+}
+
+octave:8> b=a
+b =
+{
+  x =  4
+}
+
+octave:9> b.y=4
+b =
+{
+  x =  4
+  y =  4
+}
+
+octave:10> a
+a =
+{
+  x =  4
+}
+</pre></div>
+<p>
+However, when dealing with wrapped objects, one gets the behavior
+</p>
+
+    <div class="targetlang">
+      <pre>
+octave:2> a=Point(3,5)
+a =
+
+{
+  Point, ptr = 0x9afbbb0
+}
+
+octave:3> b=a
+b =
+
+{
+  Point, ptr = 0x9afbbb0
+}
+
+octave:4> b.set(2,1);
+octave:5> b.x, b.y
+ans =  2
+ans =  1
+octave:6> a.x, a.y
+ans =  2
+ans =  1
+</pre></div>
+
+<p>
+Depending on the ownership setting of a <tt>swig_ref</tt>, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.
+</p>
+
+<H3><a name="Octave_nn15"></a>26.3.7 C++ inheritance</H3>
+
+
+<p>
+Single and multiple inheritance are fully supported. The <tt>swig_ref</tt> type carries type information along with any C++ object pointer it holds.
+This information contains the full class hierarchy. When an indexing operation (such as a method invocation) occurs, 
+the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the <tt>swig_ref</tt>.
+</p>
+
+<H3><a name="Octave_nn17"></a>26.3.8 C++ overloaded functions</H3>
+
+
+<p>
+Overloaded functions are supported, and handled as in other modules. That is, 
+each overload is wrapped separately (under internal names), and a dispatch function is also emitted under the external/visible name.
+The dispatch function selects which overload to call (if any) based on the passed arguments.
+<tt>typecheck</tt> typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.
+</p>
+
+<H3><a name="Octave_nn18"></a>26.3.9 C++ operators</H3>
+
+
+<p>
+C++ operator overloading is supported, in a way similar to other modules.
+The <tt>swig_ref</tt> type supports all unary and binary operators between itself and all other types that exist in the system at module load time. When an operator is used (where one of the operands is a <tt>swig_ref</tt>), the runtime routes the call to either a member function of the given object, or to a global function whose named is derived from the types of the operands (either both or just the lhs or rhs).
+</p>
+<p>
+For example, if <tt>a</tt> and <tt>b</tt> are SWIG variables in Octave, <tt>a+b</tt> becomes <tt>a.__add(b)</tt>. The wrapper is then free to implement __add to do whatever it wants. A wrapper may define the <tt>__add</tt> function manually, %rename some other function to it, or %rename a C++ operator to it.
+</p>
+<p>
+By default the C++ operators are renamed to their corresponding Octave operators. So without doing any work, the following interface
+</p>
+<div class="code"><pre>
+%inline {
+struct A {
+  int value;
+  A(int _value) : value(_value) {}
+  A operator+ (const A&amp; x) {
+    return A(value+x.value);
+  }
+};
+}
+</pre></div>
+<p>
+is usable from Octave like this:
+</p>
+<div class="targetlang"><pre>
+a=A(2), b=A(3), c=a+b
+assert(c.value==5);
+</pre></div>
+<p>
+Octave operators are mapped in the following way:
+</p>
+<div class="code"><pre>
+__brace      a{args}
+__brace_asgn a{args} = rhs
+__paren      a(args)
+__paren_asgn a(args) = rhs
+__str        generates string rep
+__not        !a
+__uplus      +a
+__uminus     -a
+__transpose  a.'
+__hermitian  a'
+__incr       a++
+__decr       a--
+__add        a + b
+__sub        a - b
+__mul        a * b
+__div        a / b
+__pow        a ^ b
+__ldiv       a \ b
+__lshift     a << b
+__rshift     a >> b
+__lt         a < b
+__le         a <= b
+__eq         a == b
+__ge         a >= b
+__gt         a > b
+__ne         a != b
+__el_mul     a .* b
+__el_div     a ./ b
+__el_pow     a .^ b
+__el_ldiv    a .\ b
+__el_and     a &amp; b
+__el_or      a | b
+</pre></div>
+<p>
+On the C++ side, the default mappings are as follows:
+</p>
+<div class="code"><pre>
+%rename(__add)       *::operator+;
+%rename(__add)       *::operator+();
+%rename(__add)       *::operator+() const;
+%rename(__sub)       *::operator-;
+%rename(__uminus)    *::operator-();
+%rename(__uminus)    *::operator-() const;
+%rename(__mul)       *::operator*;
+%rename(__div)       *::operator/;
+%rename(__mod)       *::operator%;
+%rename(__lshift)    *::operator<<;
+%rename(__rshift)    *::operator>>;
+%rename(__el_and)    *::operator&amp;&amp;;
+%rename(__el_or)     *::operator||;
+%rename(__xor)       *::operator^;
+%rename(__invert)    *::operator~;
+%rename(__lt)        *::operator<;
+%rename(__le)        *::operator<=;
+%rename(__gt)        *::operator>;
+%rename(__ge)        *::operator>=;
+%rename(__eq)        *::operator==;
+%rename(__ne)        *::operator!=;
+%rename(__not)       *::operator!;
+%rename(__incr)      *::operator++;
+%rename(__decr)      *::operator--;
+%rename(__paren)     *::operator();
+%rename(__brace)     *::operator[];
+</pre></div>
+
+<H3><a name="Octave_nn19"></a>26.3.10 Class extension with %extend</H3>
+
+
+<p>
+The %extend directive works the same as in other modules.
+</p>
+<p>
+You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the <tt>octave_value::{is_string,string_value,print}</tt> functions are routed to a special method <tt>__str</tt> that can be defined inside an %extend.
+</p>
+<div class="code"><pre>
+%extend A {
+string __str() {
+  stringstream sout;
+  sout&lt;&lt;$self->value;
+  return sout.str();
+}
+}
+</pre></div>
+<p>
+Then in Octave one gets,
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; a=A(4);
+octave:2&gt; a
+a = 4
+octave:3&gt; printf("%s\n",a);
+4
+octave:4&gt; a.__str()
+4
+</pre></div>
+<H3><a name="Octave_nn20"></a>26.3.11 C++ templates</H3>
+
+
+<p>
+C++ class and function templates are fully supported as in other modules, in that the %template directive may used to create explicit instantiations of templated types.
+For example, function templates can be instantiated as follows:
+</p>
+
+<div class="code"><pre>%module example
+%inline {
+ template&lt;class __scalar&gt;
+   __scalar mul(__scalar a,__scalar b) {
+   return a*b;
+ }
+}
+%include &lt;std_complex.i&gt;
+%template(mul) mul&lt;std::complex&lt;double&gt; &gt;
+%template(mul) mul&lt;double&gt;
+</pre></div>
+<p>
+and then used from Octave
+</p>
+
+<div class="targetlang"><pre>
+octave:1> mul(4,3)
+ans =  12
+octave:2> mul(4.2,3.6)
+ans =  15.120
+octave:3> mul(3+4i,10+2i)
+ans =  22 + 46i
+</pre></div>
+
+<p>
+Similarly, class templates can be instantiated as in the following example,
+</p>
+
+<div class="code"><pre>%module example
+%include &lt;std_complex.i&gt;
+%include &lt;std_string.i&gt;
+%inline {
+  #include &lt;sstream&gt;
+  template&lt;class __scalar&gt; class sum {
+    __scalar s;
+  public:
+    sum(__scalar _s=0) : s(_s) {}
+    sum&amp; add(__scalar _s) {
+      s+=_s;
+      return *this;
+    }
+    std::string __str() const {
+      std::stringstream sout;
+      sout&lt;&lt;s;
+      return sout.str();
+    }
+  };
+}
+%template(sum_complex) sum&lt;std::complex&lt;double&gt; &gt;;
+%template(sum_double) sum&lt;double&gt;;
+</pre></div>
+
+<p>
+and then used from Octave
+</p>
+
+<div class="targetlang"><pre>
+octave:2> a=sum_complex(2+3i);
+octave:3> a.add(2)
+ans =
+
+(4,3)
+octave:4> a.add(3+i)
+ans =
+
+(7,4)
+</pre></div>
+
+
+<H3><a name="Octave_nn21"></a>26.3.12 C++ Smart Pointers</H3>
+
+
+<p>
+C++ smart pointers are fully supported as in other modules.
+</p>
+
+<H3><a name="Octave_nn22"></a>26.3.13 Directors (calling Octave from C++ code)</H3>
+
+
+<p>
+There is full support for SWIG Directors, which permits Octave code to subclass C++ classes, and implement their virtual methods.
+</p>
+<p>
+Octave has no direct support for object oriented programming, however the <tt>swig_ref</tt> type provides some of this support. You can manufacture a <tt>swig_ref</tt> using the <tt>subclass</tt> function (provided by the SWIG/Octave runtime).
+</p>
+<p>
+For example,
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; a=subclass();
+octave:2&gt; a.my_var = 4;
+octave:3&gt; a.my_method = @(self) printf("my_var = ",self.my_var);
+octave:4&gt; a.my_method();
+my_var = 4
+</pre></div>
+<p>
+<tt>subclass()</tt> can also be used to subclass one or more C++ types. Suppose you have an interface defined by
+</p>
+<div class="code"><pre>
+%inline {
+class A {
+public:
+  virtual my_method() {
+    printf("c-side routine called\n");
+  }
+};
+void call_your_method(A&amp; a) {
+  a.my_method();
+}
+}
+</pre></div>
+<p>
+Then from Octave you can say:
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; B=@() subclass(A(),@my_method);
+octave:2&gt; function my_method(self)
+octave:3&gt;   printf("octave-side routine called\n");
+octave:4&gt; end
+octave:5&gt; call_your_method(B());
+octave-side routine called
+</pre></div>
+<p>
+or more concisely,
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; B=@() subclass(A(),'my_method',@(self) printf("octave-side routine called\n"));
+octave:2&gt; call_your_method(B());
+octave-side routine called
+</pre></div>
+<p>
+Note that you have to enable directors via the %feature directive (see other modules for this).
+</p>
+<p>
+<tt>subclass()</tt> will accept any number of C++ bases or other <tt>subclass()</tt>'ed objects, <tt>(string,octave_value)</tt> pairs, and <tt>function_handles</tt>. In the first case, these are taken as base classes; in the second case, as named members (either variables or functions, depending on whether the given value is a function handle); in the third case, as member functions whose name is taken from the given function handle. E.g.,
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; B=@(some_var=2) subclass(A(),'some_var',some_var,@some_func,'another_func',@(self) do_stuff())
+</pre></div>
+<p>
+You can also assign non-C++ member variables and functions after construct time. There is no support for non-C++ static members.
+</p>
+<p>
+There is limited support for explicitly referencing C++ bases. So, in the example above, we could have
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; B=@() subclass(A(),@my_method);
+octave:2&gt; function my_method(self)
+octave:3&gt;   self.A.my_method();
+octave:4&gt;   printf("octave-side routine called\n");
+octave:5&gt; end
+octave:6&gt; call_your_method(B());
+c-side routine called
+octave-side routine called
+</pre></div>
+
+<H3><a name="Octave_nn23"></a>26.3.14 Threads</H3>
+
+
+<p>
+The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.
+</p>
+
+<H3><a name="Octave_nn24"></a>26.3.15 Memory management</H3>
+
+
+<p>
+As noted above, <tt>swig_ref</tt> represents a reference counted pointer to a C/C++-side object. It also contains a flag indicating whether Octave or the C/C++ code owns the object. If Octave owns it, any destructors will be called when the reference count reaches zero. If the C/C++ side owns the object, then destructors will not be called when the reference count goes to zero.
+</p>
+<p>
+For example,
+<div class="code"><pre>
+%inline {
+class A {
+public:
+  A() { printf("A constructing\n"); }
+  ~A() { printf("A destructing\n"); }
+};
+}
+</pre></div>
+<p>
+Would produce this behavior in Octave:
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; a=A();
+A constructing
+octave:2&gt; b=a;
+octave:3&gt; clear a;
+octave:4&gt; b=4;
+A destructing
+</pre></div>
+<p>
+The %newobject directive may be used to control this behavior for pointers returned from functions.
+<p>
+In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/<tt>subclass()</tt>'ing).
+</p>
+
+<H3><a name="Octave_nn25"></a>26.3.16 STL support</H3>
+
+
+<p>
+This is some skeleton support for various STL containers.
+</p>
+
+<H3><a name="Octave_nn26"></a>26.3.17 Matrix typemaps</H3>
+
+
+<p>
+Octave provides a rich set of classes for dealing with matrices. Currently there are no built-in typemaps to deal with those. However, these are relatively straight forward for users to add themselves (see the docs on typemaps). Without much work (a single typemap decl-- say, 5 lines of code in the interface file), it would be possible to have a function
+</p>
+<div class="code"><pre>
+double my_det(const double* mat,int m,int n);
+</pre></div>
+<p>
+that is accessed from Octave as,
+</p>
+<div class="targetlang"><pre>
+octave:1&gt; my_det(rand(4));
+ans = -0.18388
+</pre></div>
+
+    <tt><br></tt>
+  </body>
+</html>
diff --git a/trunk/Doc/Manual/Perl5.html b/trunk/Doc/Manual/Perl5.html
new file mode 100644
index 0000000..b7cdaf0
--- /dev/null
+++ b/trunk/Doc/Manual/Perl5.html
@@ -0,0 +1,2988 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Perl5</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Perl5"></a>27 SWIG and Perl5</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Perl5_nn2">Overview</a>
+<li><a href="#Perl5_nn3">Preliminaries</a>
+<ul>
+<li><a href="#Perl5_nn4">Getting the right header files</a>
+<li><a href="#Perl5_nn5">Compiling a dynamic module</a>
+<li><a href="#Perl5_nn6">Building a dynamic module with MakeMaker</a>
+<li><a href="#Perl5_nn7">Building a static version of Perl</a>
+<li><a href="#Perl5_nn8">Using the module</a>
+<li><a href="#Perl5_nn9">Compilation problems and compiling with C++</a>
+<li><a href="#Perl5_nn10">Compiling for 64-bit platforms</a>
+</ul>
+<li><a href="#Perl5_nn11">Building Perl Extensions under Windows</a>
+<ul>
+<li><a href="#Perl5_nn12">Running SWIG from Developer Studio</a>
+<li><a href="#Perl5_nn13">Using other compilers</a>
+</ul>
+<li><a href="#Perl5_nn14">The low-level interface</a>
+<ul>
+<li><a href="#Perl5_nn15">Functions</a>
+<li><a href="#Perl5_nn16">Global variables</a>
+<li><a href="#Perl5_nn17">Constants</a>
+<li><a href="#Perl5_nn18">Pointers</a>
+<li><a href="#Perl5_nn19">Structures</a>
+<li><a href="#Perl5_nn20">C++ classes</a>
+<li><a href="#Perl5_nn21">C++ classes and type-checking</a>
+<li><a href="#Perl5_nn22">C++ overloaded functions</a>
+<li><a href="#Perl5_nn23">Operators</a>
+<li><a href="#Perl5_nn24">Modules and packages</a>
+</ul>
+<li><a href="#Perl5_nn25">Input and output parameters</a>
+<li><a href="#Perl5_nn26">Exception handling </a>
+<li><a href="#Perl5_nn27">Remapping datatypes with typemaps</a>
+<ul>
+<li><a href="#Perl5_nn28">A simple typemap example</a>
+<li><a href="#Perl5_nn29">Perl5 typemaps</a>
+<li><a href="#Perl5_nn30">Typemap variables</a>
+<li><a href="#Perl5_nn31">Useful functions</a>
+</ul>
+<li><a href="#Perl5_nn32">Typemap Examples</a>
+<ul>
+<li><a href="#Perl5_nn33">Converting a Perl5 array to a char ** </a>
+<li><a href="#Perl5_nn34">Return values </a>
+<li><a href="#Perl5_nn35">Returning values from arguments</a>
+<li><a href="#Perl5_nn36">Accessing array structure members</a>
+<li><a href="#Perl5_nn37">Turning Perl references into C pointers</a>
+<li><a href="#Perl5_nn38">Pointer handling</a>
+</ul>
+<li><a href="#Perl5_nn39">Proxy classes</a>
+<ul>
+<li><a href="#Perl5_nn40">Preliminaries</a>
+<li><a href="#Perl5_nn41">Structure and class wrappers</a>
+<li><a href="#Perl5_nn42">Object Ownership</a>
+<li><a href="#Perl5_nn43">Nested Objects</a>
+<li><a href="#Perl5_nn44">Proxy Functions</a>
+<li><a href="#Perl5_nn45">Inheritance</a>
+<li><a href="#Perl5_nn46">Modifying the proxy methods</a>
+</ul>
+<li><a href="#Perl5_nn47">Adding additional Perl code</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+<b>Caution: This chapter is under repair!</b>
+</p>
+
+<p>
+This chapter describes SWIG's support of Perl5. Although the Perl5
+module is one of the earliest SWIG modules, it has continued to evolve
+and has been improved greatly with the help of SWIG users. For the
+best results, it is recommended that SWIG be used with Perl5.003 or
+later. Earlier versions are problematic and SWIG generated extensions
+may not compile or run correctly.
+</p>
+
+<H2><a name="Perl5_nn2"></a>27.1 Overview</H2>
+
+
+<p>
+To build Perl extension modules, SWIG uses a layered approach.  At
+the lowest level, simple procedural wrappers are generated for
+functions, classes, methods, and other declarations in the input file.
+Then, for structures and classes, an optional collection of Perl
+proxy classes can be generated in order to provide a more natural object oriented Perl
+interface. These proxy classes simply build upon the low-level interface.
+</p>
+
+<p>
+In describing the Perl interface, this chapter begins by covering the
+essentials. First, the problem of configuration, compiling,
+and installing Perl modules is discussed.  Next, the low-level
+procedural interface is presented.  Finally, proxy classes are
+described.  Advanced customization features, typemaps, and other
+options are found near the end of the chapter.
+</p>
+
+<H2><a name="Perl5_nn3"></a>27.2 Preliminaries</H2>
+
+
+<p>
+To build a Perl5 module, run Swig using the <tt>-perl</tt> option as
+follows :
+</p>
+
+<div class="code"><pre>
+swig -perl example.i
+
+</pre></div>
+
+<p>
+This produces two files. The first file, <tt>example_wrap.c</tt>
+contains all of the C code needed to build a Perl5 module. The second
+file, <tt>example.pm</tt> contains supporting Perl code needed to
+properly load the module.
+</p>
+
+<p>
+To build the module, you will need to compile the file
+<tt>example_wrap.c</tt> and link it with the rest of your program.
+</p>
+
+<H3><a name="Perl5_nn4"></a>27.2.1 Getting the right header files</H3>
+
+
+<p>
+In order to compile, SWIG extensions need the following Perl5 header files :</p>
+
+<div class="code"><pre>
+#include "Extern.h"
+#include "perl.h"
+#include "XSUB.h"
+</pre></div>
+
+<p>
+These are typically located in a directory like this</p>
+
+<div class="code"><pre>
+/usr/lib/perl5/5.00503/i386-linux/CORE
+</pre></div>
+
+<p>
+The SWIG configuration script automatically tries to locate this directory so
+that it can compile examples.  However, if you need to find out where the directory is
+loaded, an easy way to find out is to run Perl itself.
+</p>
+
+<div class="code">
+<pre>
+% perl -e 'use Config; print $Config{archlib};'
+/usr/lib/perl5/5.00503/i386-linux
+</pre>
+</div>
+
+<H3><a name="Perl5_nn5"></a>27.2.2 Compiling a dynamic module</H3>
+
+
+<p>
+The preferred approach to building an extension module is to compile it into
+a shared object file or DLL.   To do this, you will need to compile your program
+using commands like this (shown for Linux):
+</p>
+
+<div class="code"><pre>
+$ swig -perl example.i
+% gcc example.c
+% gcc -c example_wrap.c -I/usr/lib/perl5/5.00503/i386-linux/CORE -Dbool=char
+% gcc -shared example.o example_wrap.o -o example.so
+</pre></div>
+
+<p>
+The exact compiler options vary from platform to platform. 
+SWIG tries to guess the right options when it is installed.  Therefore, 
+you may want to start with one of the examples in the <tt>SWIG/Examples/perl5</tt> 
+directory.   If that doesn't work, you will need to read the man-pages for
+your compiler and linker to get the right set of options.  You might also
+check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
+additional information.
+</p>
+
+<p>
+When linking the module, the name of the shared object file must match the module name used in
+the SWIG interface file. If you used `<tt>%module example</tt>', then
+the target should be named `<tt>example.so</tt>',
+`<tt>example.sl</tt>', or the appropriate dynamic module name on your system.
+</p>
+
+<H3><a name="Perl5_nn6"></a>27.2.3 Building a dynamic module with MakeMaker</H3>
+
+
+<p>
+It is also possible to use Perl to build dynamically loadable modules
+for you using the MakeMaker utility.  To do this, write a Perl
+script such as the following :</p>
+
+<div class="targetlang"><pre>
+# File : Makefile.PL
+use ExtUtils::MakeMaker;
+WriteMakefile(
+	`NAME'    =&gt; `example',                  # Name of package
+	`LIBS'    =&gt; [`-lm'],                    # Name of custom libraries
+	`OBJECT'  =&gt; `example.o example_wrap.o'  # Object files
+);
+
+</pre></div>
+
+<p>
+Now, to build a module, simply follow these steps :</p>
+
+<div class="code"><pre>
+% perl Makefile.PL
+% make
+% make install
+</pre></div>
+
+<p>
+If you are planning to distribute a SWIG-generated module, this is
+the preferred approach to compilation.  More information about MakeMaker can be
+found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen,
+and Randal Schwartz.</p>
+
+<H3><a name="Perl5_nn7"></a>27.2.4 Building a static version of Perl</H3>
+
+
+<p>
+If you machine does not support dynamic loading or if you've tried to
+use it without success, you can build a new version of the Perl
+interpreter with your SWIG extensions added to it. To build a static
+extension, you first need to invoke SWIG as follows :</p>
+
+<div class="code"><pre>
+% swig -perl -static example.i
+</pre></div>
+
+<p>
+By default SWIG includes code for dynamic loading, but the
+<tt>-static</tt> option takes it out.</p>
+
+<p>
+Next, you will need to supply a <tt>main()</tt> function that
+initializes your extension and starts the Perl interpreter. While,
+this may sound daunting, SWIG can do this for you automatically as
+follows :</p>
+
+<div class="targetlang"><pre>
+%module example
+
+%inline %{
+extern double My_variable;
+extern int fact(int);
+%}
+
+// Include code for rebuilding Perl
+%include perlmain.i
+</pre></div>
+
+<p>
+The same thing can be accomplished by running SWIG as follows :</p>
+
+<div class="code"><pre>
+% swig -perl -static -lperlmain.i example.i
+</pre></div>
+
+<p>
+The <tt>perlmain.i</tt> file inserts Perl's <tt>main()</tt> function
+into the wrapper code and automatically initializes the SWIG generated
+module. If you just want to make a quick a dirty module, this may be
+the easiest way. By default, the <tt>perlmain.i</tt> code does not
+initialize any other Perl extensions. If you need to use other
+packages, you will need to modify it appropriately. You can do this by
+just copying <tt>perlmain.i</tt> out of the SWIG library, placing it
+in your own directory, and modifying it to suit your purposes.</p>
+
+<p>
+To build your new Perl executable, follow the exact same procedure as
+for a dynamic module, but change the link line to something like this:
+</p>
+
+<div class="code"><pre>
+% gcc example.o example_wrap.o -L/usr/lib/perl5/5.00503/i386-linux/CORE \
+	-lperl -lsocket -lnsl -lm -o myperl
+</pre></div>
+
+<p>
+This will produce a new version of Perl called <tt>myperl</tt>. It
+should be functionality identical to Perl with your C/C++ extension
+added to it.  Depending on your machine, you may need to link with
+additional libraries such as <tt>-lsocket, -lnsl, -ldl</tt>, etc.
+</p>
+
+<H3><a name="Perl5_nn8"></a>27.2.5 Using the module</H3>
+
+
+<p>
+To use the module, simply use the Perl <tt>use</tt> statement.  If
+all goes well, you will be able to do this:
+</p>
+
+<div class="targetlang"><pre>
+$ perl
+use example;
+print example::fact(4),"\n";
+24
+</pre></div>
+
+<p>
+A common error received by first-time users is the following:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+Can't locate example.pm in @INC (@INC contains: /usr/lib/perl5/5.00503/i386-lin
+ux /usr/lib/perl5/5.00503 /usr/lib/perl5/site_perl/5.005/i386-linux /usr/lib/pe
+rl5/site_perl/5.005 .) at - line 1.
+BEGIN failed--compilation aborted at - line 1.
+</pre>
+</div>
+
+<p>
+This error is almost caused when the name of the shared object file you created doesn't match the module name
+you specified with the <tt>%module</tt> directive.  
+</p>
+
+<p>
+A somewhat related, but slightly different error is this:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+Can't find 'boot_example' symbol in ./example.so
+ at - line 1
+BEGIN failed--compilation aborted at - line 1.
+</pre>
+</div>
+
+<p>
+This error is generated because Perl can't locate the module bootstrap function in the
+SWIG extension module.  This could be caused by a mismatch between the module name and the shared library name.
+However, another possible cause is forgetting to link the SWIG-generated wrapper code with the rest
+of your application when you linked the extension module.
+</p>
+
+<p>
+Another common error is the following:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+Can't load './example.so' for module example: ./example.so: 
+undefined symbol: Foo at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169.
+
+ at - line 1
+BEGIN failed--compilation aborted at - line 1.
+</pre>
+</div>
+
+<p>
+This error usually indicates that you forgot to include some object
+files or libraries in the linking of the shared library file.  Make
+sure you compile both the SWIG wrapper file and your original program
+into a shared library file.  Make sure you pass all of the required libraries
+to the linker.  
+</p>
+
+<p>
+Sometimes unresolved symbols occur because a wrapper has been created
+for a function that doesn't actually exist in a library.  This usually
+occurs when a header file includes a declaration for a function that
+was never actually implemented or it was removed from a library
+without updating the header file.  To fix this, you can either edit
+the SWIG input file to remove the offending declaration or you can use
+the <tt>%ignore</tt> directive to ignore the declaration.  Better yet,
+update the header file so that it doesn't have an undefined declaration.
+</p>
+
+<p>
+Finally, suppose that your extension module is linked with another library like this:
+</p>
+
+<div class="code">
+<pre>
+$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
+      -o example.so
+</pre>
+</div>
+
+<p>
+If the <tt>foo</tt> library is compiled as a shared library, you might get the following
+error when you try to use your module:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+Can't load './example.so' for module example: libfoo.so: cannot open shared object file: 
+No such file or directory at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169.
+
+ at - line 1
+BEGIN failed--compilation aborted at - line 1.
+&gt;&gt;&gt;                 
+</pre>
+</div>
+
+<p>
+This error is generated because the dynamic linker can't locate the
+<tt>libfoo.so</tt> library.  When shared libraries are loaded, the
+system normally only checks a few standard locations such as
+<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>.   To get the loader to look in other
+locations, there are several things you can do.  First, you can recompile your extension
+module with extra path information. For example, on Linux you can do this:
+</p>
+
+<div class="code">
+<pre>
+$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
+      <b>-Xlinker -rpath /home/beazley/projects/lib \</b>
+      -o example.so
+</pre>
+</div>
+
+<p>
+Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
+variable to include the directory with your shared libraries.  If
+setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
+can introduce a noticeable performance impact on all other
+applications that you run.  To set it only for Perl, you might want
+to do this instead:
+</p>
+
+<div class="code">
+<pre>
+$ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
+</pre>
+</div>
+
+<p>
+Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
+<tt>crle</tt> (Solaris) to add additional search paths to the default
+system configuration (this requires root access and you will need to
+read the man pages).
+</p>
+
+<H3><a name="Perl5_nn9"></a>27.2.6 Compilation problems and compiling with C++</H3>
+
+
+<p>
+Compilation of C++ extensions has traditionally been a tricky problem.
+Since the Perl interpreter is written in C, you need to take steps to
+make sure C++ is properly initialized and that modules are compiled
+correctly.
+</p>
+
+<p>
+On most machines, C++ extension modules should be linked using the C++
+compiler.  For example:
+</p>
+
+<div class="code"><pre>
+% swig -c++ -perl example.i
+% g++ -c example.cxx
+% g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
+% <b>g++ -shared example.o example_wrap.o -o example.so</b>
+</pre></div>
+
+<p>
+In addition to this, you may need to include additional library
+files to make it work.  For example, if you are using the Sun C++ compiler on
+Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
+</p>
+
+<div class="code"><pre>
+% swig -c++ -perl example.i
+% g++ -c example.cxx
+% g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
+% g++ -shared example.o example_wrap.o -o example.so <b>-lCrun</b>
+</pre></div>
+
+<p>
+Of course, the names of the extra libraries are completely non-portable---you will 
+probably need to do some experimentation.
+</p>
+
+<p>
+Another possible compile problem comes from recent versions of Perl (5.8.0) and the GNU tools.
+If you see errors having to do with _crypt_struct, that means _GNU_SOURCE is not defined and
+it needs to be.  So you should compile the wrapper like:
+</p>
+
+<div class="code"><pre>
+% g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
+</pre></div>
+
+<p>
+-D_GNU_SOURCE is also included in the Perl ccflags, which can be found by running
+</p>
+
+<div class="code"><pre>
+% perl -e 'use Config; print $Config{ccflags};'
+</pre></div>
+
+<p>
+So you could also compile the wrapper like
+</p>
+
+<div class="code"><pre>
+% g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
+`perl -e 'use Config; print $Config{ccflags}'`
+</pre></div>
+
+<p>
+Sometimes people have suggested that it is necessary to relink the
+Perl interpreter using the C++ compiler to make C++ extension modules work.
+In the experience of this author, this has never actually appeared to be
+necessary on most platforms.   Relinking the interpreter with C++ really only includes the 
+special run-time libraries described above---as long as you link your extension 
+modules with these libraries, it should not be necessary to rebuild Perl.
+</p>
+
+<p>
+If you aren't entirely sure about the linking of a C++ extension, you
+might look at an existing C++ program.  On many Unix machines, the
+<tt>ldd</tt> command will list library dependencies.  This should give
+you some clues about what you might have to include when you link your
+extension module. For example, notice the first line of output here:
+</p>
+
+<div class="code">
+<pre>
+$ ldd swig
+        <b>libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</b>
+        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
+        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
+        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
+$
+</pre>
+</div>
+
+<p>
+If linking wasn't enough of a problem, another major complication of C++ is that it does not
+define any sort of standard for binary linking of libraries.  This
+means that C++ code compiled by different compilers will not link
+together properly as libraries nor is the memory layout of classes and
+data structures implemented in any kind of portable manner.  In a
+monolithic C++ program, this problem may be unnoticed.  However, in Perl, it
+is possible for different extension modules to be compiled with
+different C++ compilers.  As long as these modules are self-contained,
+this probably won't matter.  However, if these modules start sharing data,
+you will need to take steps to avoid segmentation faults and other
+erratic program behavior.   Also, be aware that certain C++ features, especially RTTI,
+can behave strangely when working with multiple modules.
+</p>
+
+<p>
+It should be noted that you may get a lot of error messages
+about the `<tt>bool</tt>' datatype when compiling a C++ Perl module. If
+you experience this problem, you can try the following :</p>
+
+<ul>
+<li>Use <tt>-DHAS_BOOL</tt> when compiling the SWIG wrapper code
+<li>Or use <tt>-Dbool=char</tt> when compiling.
+</ul>
+
+<p>
+Finally, recent versions of Perl (5.8.0) have namespace conflict problems.  Perl defines a bunch
+of short macros to make the Perl API function names shorter.  For example, in 
+/usr/lib/perl/5.8.0/CORE/embed.h there is a line:
+</p>
+
+<div class="code"><pre>
+#define do_open Perl_do_open
+</pre></div>
+
+<p>
+The problem is, in the &lt;iostream&gt; header from GNU libstdc++v3 there is a private 
+function named do_open.  If &lt;iostream&gt; is included after the perl headers, then
+the Perl macro causes the iostream do_open to be renamed, which causes compile errors.
+Hopefully in the future Perl will support a PERL_NO_SHORT_NAMES flag, but for now the 
+only solution is to undef the macros that conflict.  Lib/perl5/noembed.h in the SWIG 
+source has a list of macros that are known to conflict with either standard headers or
+other headers.  But if you get macro type conflicts from other macros not included
+in Lib/perl5/noembed.h while compiling the wrapper, you will
+have to find the macro that conflicts and add an #undef into the .i file.  Please report
+any conflicting macros you find to <a href="http://www.swig.org/mail.html">swig-user mailing list</a>.
+</p>
+
+<H3><a name="Perl5_nn10"></a>27.2.7 Compiling for 64-bit platforms</H3>
+
+
+<p>
+On platforms that support 64-bit applications (Solaris, Irix, etc.),
+special care is required when building extension modules.  On these
+machines, 64-bit applications are compiled and linked using a different
+set of compiler/linker options.  In addition, it is not generally possible to mix 
+32-bit and 64-bit code together in the same application.
+</p>
+
+<p>
+To utilize 64-bits, the Perl executable will need to be recompiled
+as a 64-bit application.  In addition, all libraries, wrapper code,
+and every other part of your application will need to be compiled for
+64-bits.  If you plan to use other third-party extension modules, they
+will also have to be recompiled as 64-bit extensions.
+</p>
+
+<p>
+If you are wrapping commercial software for which you have no source
+code, you will be forced to use the same linking standard as used by
+that software.  This may prevent the use of 64-bit extensions.  It may
+also introduce problems on platforms that support more than one
+linking standard (e.g., -o32 and -n32 on Irix).
+</p>
+
+<H2><a name="Perl5_nn11"></a>27.3 Building Perl Extensions under Windows</H2>
+
+
+<p>
+Building a SWIG extension to Perl under Windows is roughly
+similar to the process used with Unix.  Normally, you will want to
+produce a DLL that can be loaded into the Perl interpreter.  This
+section assumes you are using SWIG with Microsoft Visual C++
+although the procedure may be similar with other compilers.  
+</p>
+
+<H3><a name="Perl5_nn12"></a>27.3.1 Running SWIG from Developer Studio</H3>
+
+
+<p>
+If you are developing your application within Microsoft developer
+studio, SWIG can be invoked as a custom build option.  The process
+roughly requires these steps :</p>
+
+<ul>
+<li>Open up a new workspace and use the AppWizard to select a DLL
+project.
+
+<li>Add both the SWIG interface file (the .i file), any supporting C
+files, and the name of the wrapper file that will be created by SWIG
+(ie. <tt>example_wrap.c</tt>).  Note : If using C++, choose a
+different suffix for the wrapper file such as
+<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
+exist yet--Developer studio will keep a reference to it around.
+
+<li>Select the SWIG interface file and go to the settings menu.  Under
+settings, select the "Custom Build" option.
+
+<li>Enter "SWIG" in the description field.
+
+<li>Enter "<tt>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
+$(InputPath)</tt>" in the "Build command(s) field"
+
+<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>xx" in the "Output
+files(s) field".
+
+<li>Next, select the settings for the entire project and go to
+"C++:Preprocessor". Add the include directories for your Perl 5
+installation under "Additional include directories".
+
+<li>Define the symbols WIN32 and MSWIN32 under preprocessor options.
+If using the ActiveWare port, also define the symbol PERL_OBJECT.
+Note that all extensions to the ActiveWare port must be compiled with
+the C++ compiler since Perl has been encapsulated in a C++ class.
+
+<li>Finally, select the settings for the entire project and go to
+"Link Options".  Add the Perl library file to your link libraries.
+For example "perl.lib".  Also, set the name of the output file to
+match the name of your Perl module (ie. example.dll).
+
+<li>Build your project.
+</ul>
+
+<p>
+Now, assuming you made it this far, SWIG will be automatically invoked when
+you build your project.  Any changes made to the interface file will
+result in SWIG being automatically invoked to produce a new version of
+the wrapper file.  To run your new Perl extension, simply run Perl and
+use the use command as normal. For example :
+</p>
+
+<div class="targetlang"><pre>
+DOS &gt; perl
+use example;
+$a = example::fact(4);
+print "$a\n";
+
+</pre></div>
+
+<H3><a name="Perl5_nn13"></a>27.3.2 Using other compilers</H3>
+
+
+<p>
+SWIG is known to work with Cygwin and may work with other compilers on Windows.
+For general hints and suggestions refer to the <a href="Windows.html#Windows">Windows</a> chapter.
+</p>
+
+<H2><a name="Perl5_nn14"></a>27.4 The low-level interface</H2>
+
+
+<p>
+At its core, the Perl module uses a simple low-level interface
+to C function, variables, constants, and classes.  This low-level interface
+can be used to control your application.  However, it is also used to
+construct more user-friendly proxy classes as described in the next section.
+</p>
+
+<H3><a name="Perl5_nn15"></a>27.4.1 Functions</H3>
+
+
+<p>
+C functions are converted into new Perl built-in commands (or
+subroutines). For example:
+</p>
+
+<div class="targetlang"><pre>
+%module example
+int fact(int a);
+...
+</pre></div>
+
+<p>
+Now, in Perl:
+</p>
+
+<div class="targetlang"><pre>
+use example;
+$a = &amp;example::fact(2);
+</pre></div>
+
+<H3><a name="Perl5_nn16"></a>27.4.2 Global variables</H3>
+
+
+<p>
+Global variables are handled using Perl's magic
+variable mechanism.   SWIG generates a pair of functions
+that intercept read/write operations and attaches them to a Perl variable with
+the same name as the C global variable. Thus, an interface like this </p>
+
+<div class="targetlang"><pre>
+%module example;
+...
+double Spam;
+...
+</pre></div>
+
+<p>
+is accessed as follows :</p>
+
+<div class="targetlang"><pre>
+use example;
+print $example::Spam,"\n";
+$example::Spam = $example::Spam + 4
+# ... etc ...
+
+</pre></div>
+
+<p>
+If a variable is declared as <tt>const</tt>, it is wrapped as a
+read-only variable.  Attempts to modify its value will result in an
+error.
+</p>
+
+<p>
+To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable;
+extern char *path;
+%mutable;
+</pre>
+</div>
+
+<p>
+The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
+<tt>%mutable</tt>.
+See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
+</p>
+
+<p>
+It is also possible to tag a specific variable as read-only like this:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable path; 
+...
+...
+extern char *path;       // Declared later in the input
+</pre>
+</div>
+
+<H3><a name="Perl5_nn17"></a>27.4.3 Constants</H3>
+
+
+<p>
+Constants are wrapped as read-only Perl variables.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+#define FOO 42
+</pre>
+</div>
+
+<p>
+In Perl:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+print $example::FOO,"\n";    # OK
+$example::FOO = 2;           # Error
+</pre>
+</div>
+
+<H3><a name="Perl5_nn18"></a>27.4.4 Pointers</H3>
+
+
+<p>
+SWIG represents pointers as blessed references.  A blessed reference
+is the same as a Perl reference except that it has additional
+information attached to it indicating what kind of reference it
+is. That is, if you have a C declaration like this :</p>
+
+<div class="code"><pre>
+Matrix *new_Matrix(int n, int m);
+</pre></div>
+
+<p>
+The module returns a value generated as follows:
+</p>
+
+<div class="targetlang"><pre>
+$ptr = new_Matrix(int n, int m);     # Save pointer return result
+bless $ptr, "p_Matrix";              # Bless it as a pointer to Matrix
+</pre></div>
+
+<p>
+SWIG uses the "blessing" to check the datatype of various pointers.
+In the event of a mismatch, an error or warning message is
+generated.</p>
+
+<p>
+To check to see if a value is the NULL pointer, use the
+<tt>defined()</tt> command :</p>
+
+<div class="targetlang"><pre>
+if (defined($ptr)) {
+	print "Not a NULL pointer.";
+} else {
+	print "Is a NULL pointer.";
+}
+
+</pre></div>
+
+<p>
+To create a NULL pointer, you should pass the <tt>undef </tt>value to
+a function.
+</p>
+
+<p>
+The "value" of a Perl reference is not the same as the underlying C
+pointer that SWIG wrapper functions return.  Suppose that <tt>$a</tt>
+and <tt>$b</tt> are two references that point to the same C object.
+In general, <tt>$a</tt> and <tt>$b</tt> will be different--since they
+are different references.  Thus, it is a mistake to check the equality
+of <tt>$a </tt>and <tt>$b</tt> to check the equality of two C
+pointers.  The correct method to check equality of C pointers is to
+dereference them as follows :
+</p>
+
+<div class="targetlang"><pre>
+if ($$a == $$b) {
+	print "a and b point to the same thing in C";
+} else {
+	print "a and b point to different objects.";
+}
+
+</pre></div>
+
+<p>
+As much as you might be inclined to modify a pointer value directly
+from Perl, don't.  Manipulating pointer values is architecture dependent and
+could cause your program to crash.  Similarly, don't try to manually cast
+a pointer to a new type by reblessing a pointer.  This 
+may not work like you expect and it is particularly dangerous when
+casting C++ objects. If you need to cast a pointer or
+change its value, consider writing some helper functions instead.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+/* C-style cast */
+Bar *FooToBar(Foo *f) {
+   return (Bar *) f;
+}
+
+/* C++-style cast */
+Foo *BarToFoo(Bar *b) {
+   return dynamic_cast&lt;Foo*&gt;(b);
+}
+
+Foo *IncrFoo(Foo *f, int i) {
+    return f+i;
+}
+%}
+</pre>
+</div>
+
+<p>
+Also, if working with C++, you should always try
+to use the new C++ style casts.  For example, in the above code, the
+C-style cast may return a bogus result whereas as the C++-style cast will return
+<tt>NULL</tt> if the conversion can't be performed.
+</p>
+
+<p>
+<b>Compatibility Note:</b> In earlier versions, SWIG tried to preserve the same pointer naming conventions
+as XS and <tt>xsubpp</tt>.  Given the advancement of the SWIG typesystem and the growing differences between 
+SWIG and XS, this is no longer supported.
+</p>
+
+<H3><a name="Perl5_nn19"></a>27.4.5 Structures</H3>
+
+
+<p>
+Access to the contents of a structure are provided through a set of low-level
+accessor functions as described in the "SWIG Basics" chapter.  For example,
+</p>
+
+<div class="code"><pre>
+struct Vector {
+	double x,y,z;
+};
+</pre></div>
+
+<p>
+gets mapped into the following collection of accessor functions:
+</p>
+
+<div class="code"><pre>
+struct Vector *new_Vector();
+void           delete_Vector(Vector *v);
+double         Vector_x_get(Vector *obj)
+void           Vector_x_set(Vector *obj, double x)
+double         Vector_y_get(Vector *obj)
+void           Vector_y_set(Vector *obj, double y)
+double         Vector_z_get(Vector *obj)
+void           Vector_z_set(Vector *obj, double z)
+
+</pre></div>
+
+<p>
+These functions are then used to access structure data from Perl as follows:
+</p>
+
+<div class="targetlang"><pre>
+$v = example::new_Vector();
+print example::Vector_x_get($v),"\n";    # Get x component
+example::Vector_x_set($v,7.8);          # Change x component
+</pre></div>
+
+<p>
+Similar access is provided for unions and the data members of C++ classes.
+</p>
+
+<p>
+<tt>const</tt> members of a structure are read-only. Data members
+can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   ...
+   %immutable;
+   int x;        /* Read-only members */
+   char *name;
+   %mutable;
+   ...
+};
+</pre>
+</div>
+
+<p>
+When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
+dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
+SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
+released and a new value created.   If this is not the behavior you want, you will have to use
+a typemap (described later).
+</p>
+
+<p>
+Array members are normally wrapped as read-only.   For example,
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   int  x[50];
+};
+</pre>
+</div>
+
+<p>
+produces a single accessor function like this:
+</p>
+
+<div class="code">
+<pre>
+int *Foo_x_get(Foo *self) {
+    return self-&gt;x;
+};
+</pre>
+</div>
+
+<p>
+If you want to set an array member, you will need to supply a "memberin" typemap
+described later in this chapter.  As a special case, SWIG does generate
+code to set array members of type <tt>char</tt> (allowing you to store a Python
+string in the structure).
+</p>
+
+<p>
+When structure members are wrapped, they are handled as pointers.   For example,
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   ...
+};
+
+struct Bar {
+   Foo f;
+};
+</pre>
+</div>
+
+<p>
+generates accessor functions such as this:
+</p>
+
+<div class="code">
+<pre>
+Foo *Bar_f_get(Bar *b) {
+    return &amp;b-&gt;f;
+}
+
+void Bar_f_set(Bar *b, Foo *val) {
+    b-&gt;f = *val;
+}
+</pre>
+</div>
+
+
+<H3><a name="Perl5_nn20"></a>27.4.6 C++ classes</H3>
+
+
+<p>
+C++ classes are wrapped by building a set of low level accessor functions. 
+Consider the following class :
+</p>
+
+<div class="code"><pre>
+class List {
+public:
+  List();
+  ~List();
+  int  search(char *item);
+  void insert(char *item);
+  void remove(char *item);
+  char *get(int n);
+  int  length;
+static void print(List *l);
+};
+</pre></div>
+
+<p>
+When wrapped by SWIG, the following functions are created :
+</p>
+
+<div class="code"><pre>
+List    *new_List();
+void     delete_List(List *l);
+int      List_search(List *l, char *item);
+void     List_insert(List *l, char *item);
+void     List_remove(List *l, char *item);
+char    *List_get(List *l, int n);
+int      List_length_get(List *l);
+void     List_length_set(List *l, int n);
+void     List_print(List *l);
+
+</pre></div>
+
+<p>
+In Perl, these functions are used in a straightforward manner:
+</p>
+
+<div class="targetlang"><pre>
+use example;
+$l = example::new_List();
+example::List_insert($l,"Ale");
+example::List_insert($l,"Stout");
+example::List_insert($l,"Lager")
+example::List_print($l)
+Lager
+Stout
+Ale
+print example::List_length_get($l),"\n";
+3
+</pre></div>
+
+<p>
+At this low level, C++ objects are really just typed pointers.  Member
+functions are accessed by calling a C-like wrapper with an instance pointer
+as the first argument.   Although this interface is fairly primitive, it
+provides direct access to C++ objects.  A higher level interface using Perl proxy classes
+can be built using these low-level accessors.  This is described shortly.
+</p>
+
+<H3><a name="Perl5_nn21"></a>27.4.7 C++ classes and type-checking</H3>
+
+
+<p>
+The SWIG type-checker is fully aware of C++ inheritance.  Therefore, if you have
+classes like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+...
+};
+
+class Bar : public Foo {
+...
+};
+</pre>
+</div>
+
+<p>
+and a function
+</p>
+
+<div class="code">
+<pre>
+void spam(Foo *f);
+</pre>
+</div>
+
+<p>
+then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
+If necessary, the type-checker also adjusts the value of the pointer (as is necessary when
+multiple inheritance is used).
+</p>
+
+<H3><a name="Perl5_nn22"></a>27.4.8 C++ overloaded functions</H3>
+
+
+<p>
+If you have a C++ program with overloaded functions or methods, you will need to disambiguate
+those methods using <tt>%rename</tt>.   For example:
+</p>
+
+<div class="code">
+<pre>
+/* Forward renaming declarations */
+%rename(foo_i) foo(int); 
+%rename(foo_d) foo(double);
+...
+void foo(int);           // Becomes 'foo_i'
+void foo(char *c);       // Stays 'foo' (not renamed)
+
+class Spam {
+public:
+   void foo(int);      // Becomes 'foo_i'
+   void foo(double);   // Becomes 'foo_d'
+   ...
+};
+</pre>
+</div>
+
+<p>
+Now, in Perl, the methods are accessed as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+example::foo_i(3);
+$s = example::new_Spam();
+example::Spam_foo_i($s,3);
+example::Spam_foo_d($s,3.14);
+</pre>
+</div>
+
+<p>
+Please refer to the "SWIG Basics" chapter for more information. 
+</p>
+
+<H3><a name="Perl5_nn23"></a>27.4.9 Operators</H3>
+
+
+    <p>
+As of version 1.3.27 SWIG automatically renames the most common C++ operators, and maps them into the perl module with the proper 'use overload ...' so you don't need to do any work.
+    </p>
+
+    <p>
+The following C++ operators are currently supported by the Perl module:
+    </p>
+
+    <ul>
+<li>operator++	 </li>
+<li>operator--	 </li>
+<li>operator+	 </li>
+<li>operator-	 </li>
+<li>operator*	 </li>
+<li>operator/	 </li>
+<li>operator==	 </li>
+<li>operator!=	 </li>
+<li>operator%	 </li>
+<li>operator&gt;	 </li>
+<li>operator&lt;	 </li>
+<li>operator and </li>
+<li>operator or  </li>
+    </ul>
+
+<H3><a name="Perl5_nn24"></a>27.4.10 Modules and packages</H3>
+
+
+<p>
+When you create a SWIG extension, everything gets placed into
+a single Perl module. The name of the module is determined by the
+<tt>%module</tt> directive. To use the module, do the following :
+</p>
+
+<div class="targetlang"><pre>
+% perl5
+use example;                      # load the example module
+print example::fact(4),"\n"       # Call a function in it
+24
+</pre></div>
+
+<p>
+Usually, a module consists of a collection of code that is contained
+within a single file. A package, on the other hand, is the Perl
+equivalent of a namespace. A package is a lot like a module, except
+that it is independent of files. Any number of files may be part of
+the same package--or a package may be broken up into a collection of
+modules if you prefer to think about it in this way.
+</p>
+
+<p>
+SWIG installs its functions into a package with the same name as
+the module. </p>
+
+<p>
+<b>Incompatible Change:</b> previous versions of SWIG enabled you to
+change the name of the package by using the -package option, this
+feature has been removed in order to properly support modules that
+used nested namespaces, e.g. Foo::Bar::Baz. To give your module a
+nested namespace simply provide the fully qualified name in your
+%module directive: </p>
+
+<div class="code"><pre>
+%module "Foo::Bar::Baz"
+</pre></div>
+
+<p>
+<b>NOTE:</b> the double quotes are necessary.
+</p>
+
+<p>
+      Using the <tt>package</tt> option of the <tt>%module</tt> directive allows
+      you to specify what Perl namespace that the module will be living in when
+      installed.  This is useful in the situation where a module maintainer
+      wants to split a large module into smaller pieces to make maintenance
+      easier, but doesn't want to have that affect the module name used by
+      applications. So for example, if I wanted to split <tt>XML::Xerces</tt>
+      into <tt>XML::Xerces::SAX</tt>, etc. , but I wanted all the applications
+      to be able to access the classes using the <tt>XML::Xerces</tt> namespace
+      I could use:
+
+</p>
+
+<div class="code">
+<pre>
+%module(package="XML::Xerces") "XML::Xerces::SAX
+</pre>
+</div>
+
+<p>
+      And now all the applications could use the class
+      <tt>XML::Xerces::SAXParser</tt>. Without the <tt>package</tt> directive
+      splitting the module would force applications to use the class
+      <tt>XML::Xerces::SAX::SAXParser</tt>. This could break compatibility for
+      existing applications that are already using the class under the name
+      <tt>XML::Xerces::SAXParser</tt>.
+    </p>
+
+<!--
+<p>
+This can be changed by giving SWIG the -package
+option :
+</p>
+
+<div class="code"><pre>
+% swig -perl -package Foo example.i
+</pre></div>
+
+<p>
+In this case, you still create a module called `<tt>example</tt>' exactly as before, but
+all of the functions in that module will be installed into the package
+`<tt>Foo</tt>.' For example :
+</p>
+
+<div class="targetlang"><pre>
+use example;   # Load the module like before
+print Foo::fact(4),"\n";        # Call a function in package FooBar
+</pre></div>
+-->
+
+<H2><a name="Perl5_nn25"></a>27.5 Input and output parameters</H2>
+
+
+<p>
+A common problem in some C programs is handling parameters passed as simple pointers.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+void add(int x, int y, int *result) {
+   *result = x + y;
+}
+</pre>
+</div>
+
+<p>
+or perhaps
+</p>
+
+<div class="code">
+<pre>
+int sub(int *x, int *y) {
+   return *x+*y;
+}
+</pre>
+</div>
+
+<p>
+The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+void add(int, int, int *OUTPUT);
+int  sub(int *INPUT, int *INPUT);
+</pre>
+</div>
+
+<p>
+In Perl, this allows you to pass simple values.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+$a = example::add(3,4);
+print "$a\n";
+7
+$b = example::sub(7,4);
+print "$b\n";
+3
+</pre>
+</div>
+
+<p>
+Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
+and how the <tt>OUTPUT</tt> parameter creates a return result.
+</p>
+
+<p>
+If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
+directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+%apply int *OUTPUT { int *result };
+%apply int *INPUT  { int *x, int *y};
+
+void add(int x, int y, int *result);
+int  sub(int *x, int *y);
+</pre>
+</div>
+
+<p>
+If a function mutates one of its parameters like this,
+</p>
+
+<div class="code">
+<pre>
+void negate(int *x) {
+   *x = -(*x);
+}
+</pre>
+</div>
+
+<p>
+you can use <tt>INOUT</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+%include "typemaps.i"
+...
+void negate(int *INOUT);
+</pre>
+</div>
+
+<p>
+In Perl, a mutated parameter shows up as a return value.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+$a = example::negate(3);
+print "$a\n";
+-3
+</pre>
+</div>
+
+<p>
+The most common use of these special typemap rules is to handle functions that
+return more than one value.   For example, sometimes a function returns a result
+as well as a special error code:
+</p>
+
+<div class="code">
+<pre>
+/* send message, return number of bytes sent, along with success code */
+int send_message(char *text, int len, int *success);
+</pre>
+</div>
+
+<p>
+To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+%apply int *OUTPUT { int *success };
+...
+int send_message(char *text, int *success);
+</pre>
+</div>
+
+<p>
+When used in Perl, the function will return multiple values.  
+</p>
+
+<div class="targetlang">
+<pre>
+($bytes, $success) = example::send_message("Hello World");
+</pre>
+</div>
+
+<p>
+Another common use of multiple return values are in query functions.  For example:
+</p>
+
+<div class="code">
+<pre>
+void get_dimensions(Matrix *m, int *rows, int *columns);
+</pre>
+</div>
+
+<p>
+To wrap this, you might use the following:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+%apply int *OUTPUT { int *rows, int *columns };
+...
+void get_dimensions(Matrix *m, int *rows, *columns);
+</pre>
+</div>
+
+<p>
+Now, in Perl:
+</p>
+
+<div class="targetlang">
+<pre>
+($r,$c) = example::get_dimensions($m);
+</pre>
+</div>
+
+<p>
+In certain cases, it is possible to treat Perl references as C pointers.  To do this, use the <tt>REFERENCE</tt> typemap.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include typemaps.i
+
+void add(int x, int y, int *REFERENCE);
+</pre>
+</div>
+
+<p>
+In Perl:
+</p>
+
+<div class="targetlang">
+<pre>
+use example;
+$c = 0.0;
+example::add(3,4,\$c);
+print "$c\n";
+7
+</pre>
+</div>
+
+<p>
+<b>Note:</b> The <tt>REFERENCE</tt> feature is only currently supported for numeric types (integers and floating point).
+</p>
+
+<H2><a name="Perl5_nn26"></a>27.6 Exception handling </H2>
+
+
+<p>
+The SWIG <tt>%exception</tt> directive can be used to create a
+user-definable exception handler for converting exceptions in your
+C/C++ program into Perl exceptions.  The chapter on customization features
+contains more details, but suppose you have a C++ class like the
+following :
+</p>
+
+<div class="code"><pre>
+class RangeError {};   // Used for an exception
+
+class DoubleArray {
+  private:
+    int n;
+    double *ptr;
+  public:
+    // Create a new array of fixed size
+    DoubleArray(int size) {
+      ptr = new double[size];
+      n = size;
+    }
+    // Destroy an array
+    ~DoubleArray() {
+       delete ptr;
+    }
+    // Return the length of the array
+    int   length() {
+      return n;
+    }
+
+    // Get an item from the array and perform bounds checking.
+    double getitem(int i) {
+      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
+        return ptr[i];
+      else
+        throw RangeError();
+    }
+
+    // Set an item in the array and perform bounds checking.
+    void setitem(int i, double val) {
+      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
+        ptr[i] = val;
+      else {
+        throw RangeError();
+      }
+    }
+  };
+</pre></div>
+
+<p>
+Since several methods in this class can throw an exception
+for an out-of-bounds access, you might want to catch
+this in the Perl extension by writing the following in an
+interface file:
+</p>
+
+<div class="code"><pre>
+%exception {
+  try {
+    $action
+  }
+  catch (RangeError) {
+    croak("Array index out-of-bounds");
+  }
+}
+
+class DoubleArray {
+...
+};
+</pre></div>
+
+<p>
+The exception handling code is inserted directly into generated wrapper
+functions.  The <tt>$action</tt> variable is replaced with the C/C++
+code being executed by the wrapper.  When an exception handler
+is defined, errors can be caught and used to gracefully generate a Perl error
+instead of forcing the entire program to terminate with an uncaught error.
+</p>
+
+<p>
+As shown, the exception handling code will be added to every wrapper function.
+Since this is somewhat inefficient.  You might consider refining the 
+exception handler to only apply to specific methods like this:
+</p>
+
+<div class="code">
+<pre>
+%exception getitem {
+  try {
+    $action
+  }
+  catch (RangeError) {
+    croak("Array index out-of-bounds");
+  }
+}
+
+%exception setitem {
+  try {
+    $action
+  }
+  catch (RangeError) {
+    croak("Array index out-of-bounds");
+  }
+}
+</pre>
+</div>
+
+<p>
+In this case, the exception handler is only attached to methods and functions
+named <tt>getitem</tt> and <tt>setitem</tt>.
+</p>
+
+<p>
+If you had a lot of different methods, you can avoid extra typing by using a macro.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%define RANGE_ERROR
+{
+  try {
+    $action
+  }
+  catch (RangeError) {
+    croak("Array index out-of-bounds");
+  }
+}
+%enddef
+
+%exception getitem RANGE_ERROR;
+%exception setitem RANGE_ERROR;
+</pre>
+</div>
+
+<p>
+Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
+See the chapter on "<a href="Customization.html#Customization">Customization features</a>" for more examples.
+</p>
+
+<p>
+<b>Compatibility note:</b> In SWIG1.1, exceptions were defined using the older <tt>%except</tt> directive:
+</p>
+
+<div class="code">
+<pre>
+%except(python) {
+  try {
+    $function
+  }
+  catch (RangeError) {
+    croak("Array index out-of-bounds");
+  }
+}
+</pre>
+</div>
+
+<p>
+This is still supported, but it is deprecated.  The newer <tt>%exception</tt> directive provides the same
+functionality, but it has additional capabilities that make it more powerful.
+</p>
+
+<H2><a name="Perl5_nn27"></a>27.7 Remapping datatypes with typemaps</H2>
+
+
+<p>
+This section describes how you can modify SWIG's default wrapping behavior
+for various C/C++ datatypes using the <tt>%typemap</tt> directive.   This
+is an advanced topic that assumes familiarity with the Perl C API as well
+as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+</p>
+
+<p>
+Before proceeding, it should be stressed that typemaps are <em>not</em> a required 
+part of using SWIG---the default wrapping behavior is enough in most cases.
+Typemaps are only used if you want to change some aspect of the primitive
+C-Perl interface.
+</p>
+
+<H3><a name="Perl5_nn28"></a>27.7.1 A simple typemap example</H3>
+
+
+<p>
+A typemap is nothing more than a code generation rule that is attached to 
+a specific C datatype.   For example, to convert integers from Perl to C,
+you might define a typemap like this:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int {
+	$1 = (int) SvIV($input);
+	printf("Received an integer : %d\n", $1);
+}
+...
+%inline %{
+extern int fact(int n);
+%}
+
+</pre></div>
+
+<p>
+Typemaps are always associated with some specific aspect of code generation.
+In this case, the "in" method refers to the conversion of input arguments
+to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
+will be applied.  The supplied C code is used to convert values.  In this
+code a number of special variable prefaced by a <tt>$</tt> are used.  The
+<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
+The <tt>$input</tt> variable is the input object (usually a <tt>SV *</tt>).
+</p>
+
+<p>
+When this example is used in Perl5, it will operate as follows :
+</p>
+
+<div class="targetlang"><pre>
+use example;
+$n = example::fact(6);
+print "$n\n";
+...
+
+Output :
+Received an integer : 6
+720
+</pre></div>
+
+<p>
+The application of a typemap to specific datatypes and argument names involves
+more than simple text-matching--typemaps are fully integrated into the
+SWIG type-system.   When you define a typemap for <tt>int</tt>, that typemap
+applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
+the typemap system follows <tt>typedef</tt> declarations.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+%typemap(in) int n {
+	$1 = (int) SvIV($input);
+	printf("n = %d\n",$1);
+}
+%inline %{
+typedef int Integer;
+extern int fact(Integer n);    // Above typemap is applied
+%}
+</pre>
+</div>
+
+<p>
+It should be noted that the matching of <tt>typedef</tt> only occurs in one direction.  If you
+defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
+type <tt>int</tt>.
+</p>
+
+<p>
+Typemaps can also be defined for groups of consecutive arguments.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+%typemap(in) (char *str, unsigned len) {
+    $1 = SvPV($input,$2);
+};
+
+int count(char c, char *str, unsigned len);
+</pre>
+</div>
+
+<p>
+When a multi-argument typemap is defined, the arguments are always handled as a single
+Perl object.  This allows the function to be used like this (notice how the length
+parameter is omitted):
+</p>
+
+<div class="targetlang">
+<pre>
+example::count("e","Hello World");
+1
+&gt;&gt;&gt;
+</pre>
+</div>
+
+
+<H3><a name="Perl5_nn29"></a>27.7.2 Perl5 typemaps</H3>
+
+
+<p>
+The previous section illustrated an "in" typemap for converting Perl objects to C.
+A variety of different typemap methods are defined by the Perl module.  For example,
+to convert a C integer back into a Perl object, you might define an "out" typemap
+like this:
+</p>
+
+
+<div class="targetlang">
+<pre>
+%typemap(out) int {
+    $result = sv_newmortal();
+    set_setiv($result, (IV) $1);
+    argvi++;
+}
+</pre>
+</div>
+
+<p>
+The following typemap methods are available:
+</p>
+
+<p>
+<tt>%typemap(in)</tt>
+</p>
+
+<div class="indent">
+Converts Perl5 object to input function arguments.
+</div>
+
+<p>
+<tt>%typemap(out)</tt>
+</p>
+
+<div class="indent">
+Converts function return value to a Perl5 value.
+</div>
+
+<p>
+<tt>%typemap(varin)</tt>
+</p>
+
+<div class="indent">
+Converts a Perl5 object to a global variable.
+</div>
+
+<p>
+<tt>%typemap(varout)</tt>
+</p>
+
+<div class="indent">
+Converts a global variable to a Perl5 object.
+</div>
+
+<p>
+<tt>%typemap(freearg)</tt>
+</p>
+
+<div class="indent">
+Cleans up a function argument after a function call
+</div>
+
+<p>
+<tt>%typemap(argout)</tt>
+</p>
+
+<div class="indent">
+Output argument handling
+</div>
+
+<p>
+<tt>%typemap(ret)</tt>
+</p>
+
+<div class="indent">
+Clean up return value from a function.
+</div>
+
+<p>
+<tt>%typemap(memberin)</tt>
+</p>
+
+<div class="indent">
+Setting of C++ member data (all languages).
+</div>
+
+<p>
+<tt>%typemap(memberout)</tt>
+</p>
+
+<div class="indent">
+Return of C++ member data (all languages).
+</div>
+
+<p>
+<tt>%typemap(check)</tt>
+</p>
+
+<div class="indent">
+Check value of input parameter.
+</div>
+
+<H3><a name="Perl5_nn30"></a>27.7.3 Typemap variables</H3>
+
+
+<p>
+Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
+A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+This is a list of the most common variables:
+</p>
+
+<p>
+<tt>$1</tt>
+</p>
+
+<div class="indent">
+A C local variable corresponding to the actual type specified in the
+<tt>%typemap</tt> directive.  For input values, this is a C local variable
+that's supposed to hold an argument value.  For output values, this is
+the raw result that's supposed to be returned to Perl.
+</div>
+
+<p>
+<tt>$input</tt>
+</p>
+
+<div class="indent">
+A Perl object holding the value of an argument of variable value.
+</div>
+
+<p>
+<tt>$result</tt>
+</p>
+
+<div class="indent">
+A Perl object that holds the result to be returned to Perl.
+</div>
+
+<p>
+<tt>$1_name</tt>
+</p>
+
+<div class="indent">
+The parameter name that was matched. 
+</div>
+
+<p>
+<tt>$1_type</tt>
+</p>
+
+<div class="indent">
+The actual C datatype matched by the typemap.
+</div>
+
+<p>
+<tt>$1_ltype</tt>
+</p>
+
+<div class="indent">
+An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
+a C assignment operation).  This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
+All arguments and local variables in wrapper functions are declared using this type so that their values can be
+properly assigned.
+</div>
+
+<p>
+<tt>$symname</tt>
+</p>
+
+<div class="indent">
+The Perl name of the wrapper function being created.
+</div>
+
+<H3><a name="Perl5_nn31"></a>27.7.4 Useful functions</H3>
+
+
+<p>
+When writing typemaps, it is necessary to work directly with Perl5
+objects.  This, unfortunately, can be a daunting task.  Consult the
+"perlguts" man-page for all of the really ugly details.  A short
+summary of commonly used functions is provided here for reference.  It
+should be stressed that SWIG can be used quite effectively without
+knowing any of these details--especially now that there are typemap
+libraries that can already been written.
+</p>
+
+<p>
+<b>Perl Integer Functions</b>
+</p>
+
+<div class="code">
+<pre>
+int   SvIV(SV *);
+void  sv_setiv(SV *sv, IV value);
+SV   *newSViv(IV value);
+int   SvIOK(SV *);
+</pre>
+</div>
+
+<p>
+<b>Perl Floating Point Functions</b>
+</p>
+
+<div class="code">
+<pre>
+double SvNV(SV *);
+void   sv_setnv(SV *, double value);
+SV    *newSVnv(double value);
+int    SvNOK(SV *);
+</pre>
+</div>
+
+<p>
+<b>Perl String Functions</b>
+</p>
+
+<div class="code">
+<pre>
+char     *SvPV(SV *, STRLEN len);
+void      sv_setpv(SV *, char *val);
+void      sv_setpvn(SV *, char *val, STRLEN len);
+SV       *newSVpv(char *value, STRLEN len);
+int       SvPOK(SV *);
+void      sv_catpv(SV *, char *);
+void      sv_catpvn(SV *, char *, STRLEN);
+</pre>
+</div>
+
+<p>
+<b>Perl References</b>
+</p>
+
+<div class="code">
+<pre>
+void      sv_setref_pv(SV *, char *, void *ptr);
+int       sv_isobject(SV *);
+SV       *SvRV(SV *);
+int       sv_isa(SV *, char *0;
+</pre>
+</div>
+
+
+<H2><a name="Perl5_nn32"></a>27.8 Typemap Examples</H2>
+
+
+<p>
+This section includes a few examples of typemaps.  For more examples, you
+might look at the files "<tt>perl5.swg</tt>" and "<tt>typemaps.i</tt>" in
+the SWIG library.
+</p>
+
+<H3><a name="Perl5_nn33"></a>27.8.1 Converting a Perl5 array to a char ** </H3>
+
+
+<p>
+A common problem in many C programs is the processing of command line
+arguments, which are usually passed in an array of NULL terminated
+strings.  The following SWIG interface file allows a Perl5 array
+reference to be used as a char ** datatype.
+</p>
+
+<div class="code"><pre>
+%module argv
+
+// This tells SWIG to treat char ** as a special case
+%typemap(in) char ** {
+	AV *tempav;
+	I32 len;
+	int i;
+	SV  **tv;
+	if (!SvROK($input))
+	    croak("Argument $argnum is not a reference.");
+        if (SvTYPE(SvRV($input)) != SVt_PVAV)
+	    croak("Argument $argnum is not an array.");
+        tempav = (AV*)SvRV($input);
+	len = av_len(tempav);
+	$1 = (char **) malloc((len+2)*sizeof(char *));
+	for (i = 0; i &lt;= len; i++) {
+	    tv = av_fetch(tempav, i, 0);	
+	    $1[i] = (char *) SvPV(*tv,PL_na);
+        }
+	$1[i] = NULL;
+};
+
+// This cleans up the char ** array after the function call
+%typemap(freearg) char ** {
+	free($1);
+}
+
+// Creates a new Perl array and places a NULL-terminated char ** into it
+%typemap(out) char ** {
+	AV *myav;
+	SV **svs;
+	int i = 0,len = 0;
+	/* Figure out how many elements we have */
+	while ($1[len])
+	   len++;
+	svs = (SV **) malloc(len*sizeof(SV *));
+	for (i = 0; i &lt; len ; i++) {
+	    svs[i] = sv_newmortal();
+	    sv_setpv((SV*)svs[i],$1[i]);
+	};
+	myav =	av_make(len,svs);
+	free(svs);
+        $result = newRV((SV*)myav);
+        sv_2mortal($result);
+        argvi++;
+}
+
+// Now a few test functions
+%inline %{
+int print_args(char **argv) {
+    int i = 0;
+    while (argv[i]) {
+         printf("argv[%d] = %s\n", i,argv[i]);
+         i++;
+    }
+    return i;
+}
+
+// Returns a char ** list 
+char **get_args() {
+    static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
+    return &amp;values[0];
+}
+%}
+
+</pre></div>
+
+<p>
+When this module is compiled, the wrapped C functions can be used in a
+Perl script as follows :
+</p>
+
+<div class="targetlang"><pre>
+use argv;
+@a = ("Dave", "Mike", "John", "Mary");           # Create an array of strings
+argv::print_args(\@a);                           # Pass it to our C function
+$b = argv::get_args();                           # Get array of strings from C
+print @$b,"\n";                                  # Print it out
+</pre></div>
+
+
+<H3><a name="Perl5_nn34"></a>27.8.2 Return values </H3>
+
+
+<p>
+Return values are placed on the argument stack of each wrapper
+function.  The current value of the argument stack pointer is
+contained in a variable <tt>argvi</tt>.  Whenever a new output value
+is added, it is critical that this value be incremented.  For multiple
+output values, the final value of <tt>argvi</tt> should be the total
+number of output values.
+</p>
+
+<p>
+The total number of return values should not exceed the number of
+input values unless you explicitly extend the argument stack.  This
+can be done using the <tt>EXTEND()</tt> macro as in :
+</p>
+
+<div class="code"><pre>
+%typemap(argout) int *OUTPUT {
+	if (argvi &gt;= items) {            
+		EXTEND(sp,1);              /* Extend the stack by 1 object */
+	}
+	$result = sv_newmortal();
+	sv_setiv($target,(IV) *($1));
+	argvi++;
+}
+</pre></div>
+
+<H3><a name="Perl5_nn35"></a>27.8.3 Returning values from arguments</H3>
+
+
+<p>
+Sometimes it is desirable for a function to return a value in one of
+its arguments.  This example describes the implementation of the <tt>OUTPUT</tt> typemap.
+</p>
+
+<div class="code"><pre>
+%module return
+
+// This tells SWIG to treat an double * argument with name 'OutDouble' as
+// an output value.  
+
+%typemap(argout) double *OUTPUT {
+	$result = sv_newmortal();
+	sv_setnv($result, *$input);
+	argvi++;                     /* Increment return count -- important! */
+}
+
+// We don't care what the input value is. Ignore, but set to a temporary variable
+
+%typemap(in,numinputs=0) double *OUTPUT(double junk) {
+	$1 = &amp;junk;
+}
+
+// Now a function to test it
+%{
+/* Returns the first two input arguments */
+int multout(double a, double b, double *out1, double *out2) {
+	*out1 = a;
+	*out2 = b;
+	return 0;
+};
+%}
+
+// If we name both parameters OutDouble both will be output
+
+int multout(double a, double b, double *OUTPUT, double *OUTPUT);
+...
+</pre></div>
+
+<p>
+When this function is called, the output arguments are appended to the stack used
+to return results.  This shows up an array in Perl.
+For example :
+</p>
+
+<div class="targetlang"><pre>
+@r = multout(7,13);
+print "multout(7,13) = @r\n";
+($x,$y) = multout(7,13);
+</pre></div>
+
+<H3><a name="Perl5_nn36"></a>27.8.4 Accessing array structure members</H3>
+
+
+<p>
+Consider the following data structure :
+</p>
+
+<div class="code"><pre>
+#define SIZE  8
+typedef struct {
+    int   values[SIZE];
+    ...
+} Foo;
+
+</pre></div>
+
+<p>
+By default, SWIG doesn't know how to the handle the values structure
+member it's an array, not a pointer.  In this case, SWIG makes the array member
+read-only.   Reading will simply return a pointer to the first item in the array.
+To make the member writable, a "memberin" typemap can be used.
+</p>
+
+<div class="code"><pre>
+%typemap(memberin) int [SIZE] {
+    int i;
+    for (i = 0; i &lt; SIZE; i++) {
+        $1[i] = $input[i];
+    }
+}
+
+</pre></div>
+
+<p>
+Whenever a <tt>int [SIZE]</tt> member is encountered in a structure
+or class, this typemap provides a safe mechanism for setting its
+value.  
+</p>
+
+<p>
+As in the previous example, the typemap can be generalized for any dimension.
+For example:
+</p>
+
+<div class="code"><pre>
+%typemap(memberin) int [ANY] {
+   int i;
+   for (i = 0; i &lt; $1_dim0; i++) {
+      $1[i] = $input[i];
+   }
+}
+</pre></div>
+
+<p>
+When setting structure members, the input object is always assumed to
+be a C array of values that have already been converted from the
+target language.  Because of this, the <tt>memberin</tt> typemap is
+almost always combined with the use of an "in" typemap.  For example,
+the "in" typemap in the previous section would be used to convert an
+<tt>int[]</tt> array to C whereas the "memberin" typemap would be used
+to copy the converted array into a C data structure.
+</p>
+
+<H3><a name="Perl5_nn37"></a>27.8.5 Turning Perl references into C pointers</H3>
+
+
+<p>
+A frequent confusion on the SWIG mailing list is errors caused by the
+mixing of Perl references and C pointers.  For example, suppose you
+have a C function that modifies its arguments like this :
+</p>
+
+<div class="code"><pre>
+void add(double a, double b, double *c) {
+	*c = a + b;
+}
+</pre></div>
+
+<p>
+A common misinterpretation of this function is the following Perl script :
+</p>
+
+<div class="targetlang"><pre>
+# Perl script
+$a = 3.5;
+$b = 7.5;
+$c = 0.0;          # Output value
+add($a,$b,\$c);    # Place result in c (Except that it doesn't work)
+</pre></div>
+
+<p>
+To make this work with a reference, you can use a typemap such as this:
+</p>
+
+<div class="code"><pre>
+%typemap(in) double * (double dvalue) {
+  SV* tempsv;
+  if (!SvROK($input)) {
+    croak("expected a reference\n");
+  }
+  tempsv = SvRV($input);
+  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
+    croak("expected a double reference\n");
+  }
+  dvalue = SvNV(tempsv);
+  $1 = &amp;dvalue;
+}
+
+%typemap(argout) double * {
+  SV *tempsv;
+  tempsv = SvRV($input);
+  sv_setnv(tempsv, *$1);
+}
+</pre></div>
+
+<p>
+Now, if you place this before the add function, you can do this :
+</p>
+
+<div class="targetlang"><pre>
+$a = 3.5;
+$b = 7.5;
+$c = 0.0;
+add($a,$b,\$c);            # Now it works!
+print "$c\n";
+
+</pre></div>
+
+<H3><a name="Perl5_nn38"></a>27.8.6 Pointer handling</H3>
+
+
+<p>
+Occasionally, it might be necessary to convert pointer values that have
+been stored using the SWIG typed-pointer representation.  To convert a pointer from Perl to C, the following
+function is used:
+</p>
+
+<p>
+<tt>
+int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int flags)
+</tt>
+</p>
+
+<div class="indent">
+Converts a Perl object <tt>obj</tt> to a C pointer.  The result of the conversion is placed
+into the pointer located at <tt>ptr</tt>.  <tt>ty</tt> is a SWIG type descriptor structure.
+<tt>flags</tt> is used to handle error checking and other aspects of conversion. <tt>flags</tt> is
+currently undefined and reserved for future expansion.  Returns 0 on success and -1 on error.
+</div>
+
+<p>
+<tt>
+void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int flags)</tt>
+</p>
+
+<div class="indent">
+Creates a new Perl pointer object.  <tt>obj</tt> is a Perl SV that has been initialized to hold the result,
+<tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
+describes the type, and <tt>flags</tt> is a flag that controls properties of the conversion.  <tt>flags</tt> is currently undefined
+and reserved.
+</div>
+
+<p>
+Both of these functions require the use of a special SWIG
+type-descriptor structure.  This structure contains information about
+the mangled name of the datatype, type-equivalence information, as
+well as information about converting pointer values under C++
+inheritance.   For a type of <tt>Foo *</tt>, the type descriptor structure
+is usually accessed as follows:
+</p>
+
+<div class="code">
+<pre>
+Foo *f;
+if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
+
+SV *sv = sv_newmortal();
+SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
+</pre>
+</div>
+
+<p>
+In a typemap, the type descriptor should always be accessed using the special typemap
+variable <tt>$1_descriptor</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Foo * {
+   if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
+}
+</pre>
+</div>
+
+<p>
+If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Foo * {
+   if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
+}
+</pre>
+</div>
+
+<H2><a name="Perl5_nn39"></a>27.9 Proxy classes</H2>
+
+
+<p>
+<b>Out of date. Needs update.</b>
+</p>
+
+<p>
+Using the low-level procedural interface, SWIG can also construct a
+high-level object oriented interface to C structures and C++ classes.
+This is done by constructing a Perl proxy class (also known as a shadow class)
+that provides an OO wrapper
+to the underlying code.  This section describes the implementation
+details of the proxy interface.
+</p>
+
+<H3><a name="Perl5_nn40"></a>27.9.1 Preliminaries</H3>
+
+
+<p>
+Proxy classes, are generated by default. If you want to turn them off, use the <tt>-noproxy</tt> command line option.
+For example:
+</p>
+
+<div class="code">
+<pre>
+$ swig -c++ -perl -noproxy example.i
+</pre>
+</div>
+
+<p>
+When proxy classes are used, SWIG moves all of the low-level procedural wrappers to
+another package name.  By default, this package is named 'modulec' where 'module' is the name of the module
+you provided with the <tt>%module</tt> directive.  Then, in place of the original module, 
+SWIG creates a collection of high-level Perl wrappers.  In your scripts, you will use these
+high level wrappers.  The wrappers, in turn, interact with the low-level procedural module.
+</p>
+
+<H3><a name="Perl5_nn41"></a>27.9.2 Structure and class wrappers</H3>
+
+
+<p>
+Suppose you have the following SWIG interface file :
+</p>
+
+<div class="code"><pre>
+%module example
+struct Vector {
+	Vector(double x, double y, double z);
+	~Vector();
+	double x,y,z;
+};
+
+</pre></div>
+
+<p>
+When wrapped, SWIG creates the following set of low-level accessor
+functions as described in previous sections.
+</p>
+
+<div class="code"><pre>
+Vector *new_Vector(double x, double y, double z);
+void    delete_Vector(Vector *v);
+double  Vector_x_get(Vector *v);
+double  Vector_x_set(Vector *v, double value);
+double  Vector_y_get(Vector *v);
+double  Vector_y_set(Vector *v, double value);
+double  Vector_z_get(Vector *v);
+double  Vector_z_set(Vector *v, double value);
+
+</pre></div>
+
+<p>
+However, when proxy classes are enabled, these accessor functions are
+wrapped inside a Perl class like this:
+</p>
+
+<div class="targetlang"><pre>
+package example::Vector;
+@ISA = qw( example );
+%OWNER = ();
+%BLESSEDMEMBERS = ();
+
+sub new () {
+    my $self = shift;
+    my @args = @_;
+    $self = vectorc::new_Vector(@args);
+    return undef if (!defined($self));
+    bless $self, "example::Vector";
+    $OWNER{$self} = 1;
+    my %retval;
+    tie %retval, "example::Vector", $self;
+    return bless \%retval,"Vector";
+}
+
+sub DESTROY {
+    return unless $_[0]-&gt;isa('HASH');
+    my $self = tied(%{$_[0]});
+    delete $ITERATORS{$self};
+    if (exists $OWNER{$self}) {
+	 examplec::delete_Vector($self));
+	 delete $OWNER{$self};
+}
+
+sub FETCH {
+    my ($self,$field) = @_;
+    my $member_func = "vectorc::Vector_${field}_get";
+    my $val = &amp;$member_func($self);
+    if (exists $BLESSEDMEMBERS{$field}) {
+        return undef if (!defined($val));
+        my %retval;
+        tie %retval,$BLESSEDMEMBERS{$field},$val;
+        return bless \%retval, $BLESSEDMEMBERS{$field};
+    }
+    return $val;
+}
+
+sub STORE {
+    my ($self,$field,$newval) = @_;
+    my $member_func = "vectorc::Vector_${field}_set";
+    if (exists $BLESSEDMEMBERS{$field}) {
+        &amp;$member_func($self,tied(%{$newval}));
+    } else {
+        &amp;$member_func($self,$newval);
+    }
+}
+</pre></div>
+
+<p>
+Each structure or class is mapped into a Perl package of the same
+name. The C++ constructors and destructors are mapped into
+constructors and destructors for the package and are always named
+"new" and "DESTROY".  The constructor always returns a tied hash
+table.  This hash table is used to access the member variables of a
+structure in addition to being able to invoke member functions.  The
+<tt>%OWNER</tt> and <tt>%BLESSEDMEMBERS</tt> hash tables are used
+internally and described shortly.
+</p>
+
+<p>
+To use our new proxy class we can simply do the following:
+</p>
+
+<div class="targetlang"><pre>
+# Perl code using Vector class
+$v = new Vector(2,3,4);
+$w = Vector-&gt;new(-1,-2,-3);
+
+# Assignment of a single member
+$v-&gt;{x} = 7.5;
+
+# Assignment of all members
+%$v = ( x=&gt;3,
+	 y=&gt;9,
+	 z=&gt;-2);
+
+# Reading members
+$x = $v-&gt;{x};
+
+# Destruction
+$v-&gt;DESTROY();
+
+</pre></div>
+
+<H3><a name="Perl5_nn42"></a>27.9.3 Object Ownership</H3>
+
+
+<p>
+In order for proxy classes to work properly, it is necessary for Perl
+to manage some mechanism of object ownership.  Here's the crux of the
+problem---suppose you had a function like this :
+</p>
+
+<div class="code"><pre>
+Vector *Vector_get(Vector *v, int index) {
+	return &amp;v[i];
+}
+</pre></div>
+
+<p>
+This function takes a Vector pointer and returns a pointer to another
+Vector.  Such a function might be used to manage arrays or lists of
+vectors (in C).  Now contrast this function with the constructor for a
+Vector object :
+</p>
+
+<div class="code"><pre>
+Vector *new_Vector(double x, double y, double z) {
+	Vector *v;
+	v = new Vector(x,y,z);        // Call C++ constructor
+	return v;
+}
+</pre></div>
+
+<p>
+Both functions return a Vector, but the constructor is returning a
+brand-new Vector while the other function is returning a Vector that
+was already created (hopefully).  In Perl, both vectors will be
+indistinguishable---clearly a problem considering that we would
+probably like the newly created Vector to be destroyed when we are
+done with it.
+</p>
+
+<p>
+To manage these problems, each class contains two methods that access
+an internal hash table called <tt>%OWNER</tt>.  This hash keeps a list
+of all of the objects that Perl knows that it has created.  This
+happens in two cases: (1) when the constructor has been called, and
+(2) when a function implicitly creates a new object (as is done when
+SWIG needs to return a complex datatype by value).  When the
+destructor is invoked, the Perl proxy class module checks the
+<tt>%OWNER</tt> hash to see if Perl created the object.  If so, the
+C/C++ destructor is invoked.  If not, we simply destroy the Perl
+object and leave the underlying C object alone (under the assumption
+that someone else must have created it).
+</p>
+
+<p>
+This scheme works remarkably well in practice but it isn't foolproof.
+In fact, it will fail if you create a new C object in Perl, pass it on
+to a C function that remembers the object, and then destroy the
+corresponding Perl object (this situation turns out to come up
+frequently when constructing objects like linked lists and trees).
+When C takes possession of an object, you can change Perl's ownership
+by simply deleting the object from the <tt>%OWNER</tt> hash.  This is
+done using the <tt>DISOWN </tt>method.
+</p>
+
+<div class="targetlang"><pre>
+# Perl code to change ownership of an object
+$v = new Vector(x,y,z);
+$v-&gt;DISOWN();     
+</pre></div>
+
+<p>
+To acquire ownership of an object, the <tt>ACQUIRE</tt> method can be used.
+</p>
+
+<div class="targetlang"><pre>
+# Given Perl ownership of a file
+$u = Vector_get($v);
+$u-&gt;ACQUIRE();
+
+</pre></div>
+
+<p>
+As always, a little care is in order.  SWIG does not provide reference
+counting, garbage collection, or advanced features one might find in
+sophisticated languages.
+</p>
+
+<H3><a name="Perl5_nn43"></a>27.9.4 Nested Objects</H3>
+
+
+<p>
+Suppose that we have a new object that looks like this :
+</p>
+
+<div class="code"><pre>
+struct Particle {
+	Vector r;
+	Vector v;
+	Vector f;
+	int	type;
+}
+
+</pre></div>
+
+<p>
+In this case, the members of the structure are complex objects that
+have already been encapsulated in a Perl proxy class.  To handle
+these correctly, we use the <tt>%BLESSEDMEMBERS</tt> hash which would
+look like this (along with some supporting code) :
+</p>
+
+<div class="targetlang"><pre>
+package Particle;
+...
+%BLESSEDMEMBERS = (
+	r =&gt; `Vector',
+	v =&gt; `Vector',
+	f =&gt; `Vector',
+);
+
+</pre></div>
+
+<p>
+When fetching members from the structure, <tt>%BLESSEDMEMBERS</tt> is
+checked.  If the requested field is present, we create a tied-hash
+table and return it.  If not, we just return the corresponding member
+unmodified.
+</p>
+
+<p>
+This implementation allows us to operate on nested structures as follows :
+</p>
+
+<div class="targetlang"><pre>
+# Perl access of nested structure
+$p = new Particle();
+$p-&gt;{f}-&gt;{x} = 0.0;
+%${$p-&gt;{v}} = ( x=&gt;0, y=&gt;0, z=&gt;0);         
+</pre></div>
+
+<H3><a name="Perl5_nn44"></a>27.9.5 Proxy Functions</H3>
+
+
+<p>
+When functions take arguments involving a complex object, it is
+sometimes necessary to write a proxy function.  For example :
+</p>
+
+<div class="code"><pre>
+double dot_product(Vector *v1, Vector *v2);
+</pre></div>
+
+<p>
+Since Vector is an object already wrapped into a proxy class, we need
+to modify this function to accept arguments that are given in the form
+of tied hash tables.  This is done by creating a Perl function like
+this :
+</p>
+
+<div class="targetlang"><pre>
+sub dot_product {
+    my @args = @_;
+    $args[0] = tied(%{$args[0]});         # Get the real pointer values
+    $args[1] = tied(%{$args[1]});
+    my $result = vectorc::dot_product(@args);
+    return $result;
+}
+</pre></div>
+
+<p>
+This function replaces the original function, but operates in an
+identical manner.
+</p>
+
+<H3><a name="Perl5_nn45"></a>27.9.6 Inheritance</H3>
+
+
+<p>
+Simple C++ inheritance is handled using the Perl <tt>@ISA</tt> array
+in each class package. For example, if you have the following
+interface file :
+</p>
+
+<div class="code"><pre>
+// shapes.i
+// SWIG interface file for shapes class
+%module shapes
+%{
+#include "shapes.h"
+%}
+
+class Shape {
+public:
+	virtual double area() = 0;
+	virtual double perimeter() = 0;
+	void    set_location(double x, double y);
+};
+class Circle : public Shape {
+public:
+	Circle(double radius);
+	~Circle();
+	double area();
+	double perimeter();
+};
+class Square : public Shape {
+public:
+	Square(double size);
+	~Square();
+	double area();
+	double perimeter();
+}
+
+</pre></div>
+
+<p>
+The resulting, Perl wrapper class will create the following code :
+</p>
+
+<div class="targetlang"><pre>
+Package Shape;
+@ISA = (shapes);
+...
+Package Circle;
+@ISA = (shapes Shape);
+...
+Package Square;
+@ISA = (shapes Shape);
+
+</pre></div>
+
+<p>
+The <tt>@ISA</tt> array determines where to look for methods of a
+particular class.  In this case, both the <tt>Circle</tt> and
+<tt>Square</tt> classes inherit functions from <tt>Shape</tt> so we'll
+want to look in the <tt>Shape</tt> base class for them.  All classes
+also inherit from the top-level module <tt>shapes</tt>.  This is
+because certain common operations needed to implement proxy classes
+are implemented only once and reused in the wrapper code for various
+classes and structures.
+</p>
+
+<p>
+Since SWIG proxy classes are implemented in Perl, it is easy to
+subclass from any SWIG generated class.  To do this, simply put the
+name of a SWIG class in the <tt>@ISA</tt> array for your new
+class. However, be forewarned that this is not a trivial problem.  In
+particular, inheritance of data members is extremely tricky (and I'm
+not even sure if it really works).
+</p>
+
+<H3><a name="Perl5_nn46"></a>27.9.7 Modifying the proxy methods</H3>
+
+
+<p>
+It is possible to override the SWIG generated proxy/shadow methods, using <tt>%feature("shadow")</tt>.
+It works like all the other <a href="Customization.html#features">%feature directives</a>.
+Here is a simple example showing how to add some Perl debug code to the constructor:
+</p>
+
+<div class="targetlang"><pre>
+/* Let's make the constructor of the class Square more verbose */
+%feature("shadow") Square(double w)
+%{
+  sub new {
+    my $pkg = shift;
+    my $self = examplec::new_Square(@_);
+    print STDERR "Constructed an @{[ref($self)]}\n";
+    bless $self, $pkg if defined($self);
+  }
+%}
+
+class Square {
+public:
+  Square(double w);
+  ...
+};
+</pre></div>
+
+<H2><a name="Perl5_nn47"></a>27.10 Adding additional Perl code</H2>
+
+
+<p>
+If writing support code in C isn't enough, it is also possible to write code in
+Perl.  This code gets inserted in to the <tt>.pm</tt> file created by SWIG.   One
+use of Perl code might be to supply a high-level interface to certain functions.
+For example:
+</p>
+
+<div class="code">
+<pre>
+void set_transform(Image *im, double x[4][4]);
+
+...
+/* Rewrite the high level interface to set_transform */
+%perlcode %{
+sub set_transform
+{
+  my ($im, $x) = @_;
+  my $a = new_mat44();
+  for (my $i = 0; $i &lt; 4, $i++)
+  {
+    for (my $j = 0; $j &lt; 4, $j++)
+    {
+      mat44_set($a, $i, $j, $x-&gt;[i][j])
+      }
+  }
+  example.set_transform($im, $a);
+  free_mat44($a);
+}
+%}
+</pre>
+</div>
+
+<p>
+In this example, <tt>set_transform()</tt> provides a high-level Perl interface built on top of
+low-level helper functions.  For example, this code now seems to work:
+</p>
+
+<div class="targetlang">
+<pre>
+my $a =
+  [[1,0,0,0],
+   [0,1,0,0],
+   [0,0,1,0],
+   [0,0,0,1]];
+set_transform($im, $a);
+</pre>
+</div>
+
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Php.html b/trunk/Doc/Manual/Php.html
new file mode 100644
index 0000000..6b654fd
--- /dev/null
+++ b/trunk/Doc/Manual/Php.html
@@ -0,0 +1,1013 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<!-- Hand crafted HTML -->
+<html>
+<head>
+<title>SWIG and PHP</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Php"></a>28 SWIG and PHP</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Php_nn1">Generating PHP Extensions</a>
+<ul>
+<li><a href="#Php_nn1_1">Building a loadable extension</a>
+<li><a href="#Php_nn1_2">Building extensions into PHP</a>
+<li><a href="#Php_nn1_3">Using PHP Extensions</a>
+</ul>
+<li><a href="#Php_nn2">Basic PHP interface</a>
+<ul>
+<li><a href="#Php_nn2_1">Constants</a>
+<li><a href="#Php_nn2_2">Global Variables</a>
+<li><a href="#Php_nn2_3">Functions</a>
+<li><a href="#Php_nn2_4">Overloading</a>
+<li><a href="#Php_nn2_5">Pointers and References</a>
+<li><a href="#Php_nn2_6">Structures and C++ classes</a>
+<ul>
+<li><a href="#Php_nn2_6_1">Using <tt>-noproxy</tt></a>
+<li><a href="#Php_nn2_6_2">Constructors and Destructors</a>
+<li><a href="#Php_nn2_6_3">Static Member Variables</a>
+<li><a href="#Php_nn2_6_4">Static Member Functions</a>
+</ul>
+<li><a href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+<b>Caution: This chapter (and module!) is still under construction</b>
+</p>
+
+<p>
+In this chapter, we discuss SWIG's support of PHP.  The PHP module
+was extensively rewritten in release 1.3.26, and although it is
+significantly more functional, it still does not implement all the
+features available in some of the other languages.
+</p>
+
+<p>
+The examples and test cases have been developed with PHP4.  Release
+1.3.30 added support for generating PHP5 class wrappers for C++
+libraries.
+</p>
+
+<p>
+In order to use this module, you will need to have a copy of the PHP4 or PHP5
+include files to compile the SWIG generated files.  If you installed
+PHP from a binary package, you may need to install a "php-dev" or "php-devel"
+package for these to be installed.  You can find out where these files are
+by running <tt>php-config --includes</tt>.  To use the built PHP module you
+will need either the php binary or the Apache php module. If you want to build
+your extension into php directly, you will need the complete PHP source tree
+available.
+</p>
+
+<H2><a name="Php_nn1"></a>28.1 Generating PHP Extensions</H2>
+
+
+<p>
+To build a PHP extension, run swig using the <tt>-php</tt> option as
+follows:
+</p>
+
+<div class="code"><pre>
+swig -php example.i
+</pre></div>
+
+<p>
+This will produce 3 files example_wrap.c, php_example.h and
+example.php. The first file, <tt>example_wrap.c</tt> contains all of
+the C code needed to build a PHP extension. The second file,
+<tt>php_example.h</tt> contains the header information needed if
+you wish to statically link the extension into the php interpreter.
+The third file,
+<tt>example.php</tt> can be included by PHP scripts.  It attempts to
+dynamically load the extension and contains extra php code specified
+in the interface file.  If wrapping C++ code for PHP5, it will
+also contain PHP5 class wrappers.
+</p>
+
+<p>
+Swig can generate PHP extensions from C++ libraries as well when
+given the <tt>-c++</tt> option.  The support for C++ is discussed in
+more detail in <a href="#Php_nn2_6">section 27.2.6</a>.
+</p>
+
+<p>
+The usual (and recommended) way is to build the extension as a separate
+dynamically loaded module. You can then specify that this be loaded
+automatically in <tt>php.ini</tt> or load it explicitly for any script which
+needs it.
+</p>
+
+<p>
+It is also possible to rebuild PHP from source so that your module is
+statically linked into the php executable/library.  This is a lot more
+work, and also requires a full rebuild of PHP to update your module,
+and it doesn't play nicely with package system.  We don't recommend
+this approach, but if you really want to do this, the <tt>-phpfull</tt>
+command line argument to swig may be of use - see below for details.
+</p>
+
+<H3><a name="Php_nn1_1"></a>28.1.1 Building a loadable extension</H3>
+
+
+<p>
+To build your module as a dynamically loadable extension, use compilation
+commands like these (if you aren't using GCC, the commands will be different,
+and there may be so variation between platforms - these commands should at
+least work for Linux though):
+</p>
+
+<div class="code"><pre>
+	gcc `php-config --includes` -fpic -c example_wrap.c
+	gcc -shared example_wrap.o -o example.so
+</pre></div>
+
+<p>
+There is a deprecated <tt>-make</tt> command line argument to swig which will
+generate an additional file <tt>makefile</tt> which can usually build the
+extension (at least on some UNIX platforms), but the Makefile generated isn't
+very flexible, and the commands required are trivial so it is simpler to just
+add them to your Makefile or other build system directly.  We recommend that
+you don't use <tt>-make</tt> and it's likely to be removed at some point.
+</p>
+
+<H3><a name="Php_nn1_2"></a>28.1.2 Building extensions into PHP</H3>
+
+
+<p>
+Note that we don't recommend this approach - it's cleaner and simpler to
+use dynamically loadable modules, which are supported by all modern OSes.
+Support for this may be discontinued entirely in the future.
+</p>
+
+<p>
+It is possible to rebuild PHP itself with your module statically linked
+in.  To do this, you can use the <tt>-phpfull</tt> command line option to
+swig.  Using this option will generate three additional files.  The first
+extra file, <tt>config.m4</tt> contains the m4 and shell code needed to
+enable the extension as part of the PHP build process. The second
+extra file, <tt>Makefile.in</tt> contains the information needed to
+build the final Makefile after substitutions. The third and final
+extra file, <tt>CREDITS</tt> should contain the credits for the
+extension.
+</p>
+
+<p>
+To build with phpize, after you have run swig you will need to run the
+'phpize' command (installed as part of php) in the same
+directory. This re-creates the php build environment in that
+directory. It also creates a configure file which includes the shell
+code from the config.m4 that was generated by SWIG, this configure
+script will accept a command line argument to enable the extension to
+be run (by default the command line argument is --enable-modulename,
+however you can edit the config.m4 file before running phpize to
+accept --with-modulename. You can also add extra tests in config.m4 to
+check that a correct library version is installed or correct header
+files are included, etc, but you must edit this file before running
+phpize.) You can also get SWIG to generate simple extra tests for
+libraries and header files for you.
+</p>
+
+<div class="code"><pre>
+	swig -php -phpfull
+</pre></div>
+
+<p>
+If you depend on source files not generated by SWIG, before generating
+the configure file, you may need to edit the <tt>Makefile.in</tt>
+file. This contains the names of the source files to compile (just the
+wrapper file by default) and any additional libraries needed to be
+linked in. If there are extra C files to compile, you will need to add
+them to the <tt>Makefile.in</tt>, or add the names of libraries if they are
+needed.  In simple cases SWIG is pretty good at generating a complete
+<tt>Makefile.in</tt> and <tt>config.m4</tt> which need no further editing.
+</p>
+
+<p>
+You then run the configure script with the command line argument needed
+to enable the extension. Then run make, which builds the extension.
+The extension object file will be left in the modules sub directory, you can
+move it to wherever it is convenient to call from your php script. 
+</p>
+
+<p>
+When using <tt>-phpfull</tt>, swig also accepts the following
+additional optional arguments:
+</p>
+<ul>
+<li><tt>-withincs "&lt;incs&gt;"</tt> Adds include files to the config.m4 file.
+<li><tt>-withlibs "&lt;libs&gt;"</tt> Links with the specified libraries.
+<li><tt>-withc "&lt;files&gt;"</tt> Compiles and links the additional specified C files.
+<li><tt>-withcxx "&lt;files&gt;"</tt> Compiles and links the additional specified C++ files.
+</ul>
+
+<p>
+After running swig with the <tt>-phpfull</tt> switch, you will be left with a shockingly
+similar set of files to the previous build process. However you will then need
+to move these files to a subdirectory within the php source tree, this subdirectory you will need to create under the ext directory, with the name of the extension (e.g. <tt>mkdir php-4.0.6/ext/modulename</tt>).
+</p>
+
+<p>
+After moving the files into this directory, you will need to run the 'buildall'
+script in the php source directory. This rebuilds the configure script 
+and includes the extra command line arguments from the module you have added. 
+</p>
+
+<p>
+Before running the generated configure file, you may need to edit the <tt>
+Makefile.in</tt>. This contains the names of the source files to compile (
+just the wrapper file by default) and any additional libraries needed to
+link in. If there are extra C files to compile you will need to add them
+to the Makefile, or add the names of libraries if they are needed.
+In most cases <tt>Makefile.in</tt> will be complete, especially if you 
+make use of <tt>-withlibs</tt> and <tt>-withincs</tt>
+</p>
+
+<div class="code"><pre>
+	swig -php -phpfull -withlibs "xapian omquery" --withincs "om.h"
+</pre></div>
+
+<p>
+Will include in the <tt>config.m4</tt> and <tt>Makefile.in</tt> search for
+<tt>libxapian.a</tt> or <tt>libxapian.so</tt> and search for
+<tt>libomquery.a</tt> or <tt>libomquery.so</tt> as well as a 
+search for <tt>om.h</tt>.
+</p>
+
+<p>
+You then need to run the configure command and pass the necessary command
+line arguments to enable your module (by default this is --enable-modulename,
+but this can be changed by editing the config.m4 file in the modules directory
+before running the buildall script. In addition, extra tests can be added to
+the config.m4 file to ensure the correct libraries and header files are 
+installed.)
+</p>
+
+<p>
+Once configure has completed, you can run make to build php. If this all
+compiles correctly, you should end up with a php executable/library
+which contains your new module. You can test it with a php script which
+does not have the 'dl' command as used above.
+</p>
+
+<H3><a name="Php_nn1_3"></a>28.1.3 Using PHP Extensions</H3>
+
+
+<p>
+To test the extension from a PHP script, you need to load it first. You
+can load it for every script by adding this line the <tt>[PHP]</tt> section of
+<tt>php.ini</tt>:
+</p>
+
+<div class="code"><pre>
+	extension=/path/to/modulename.so
+</pre></div>
+
+<p>
+Alternatively, you can load it explicitly only for scripts which need it
+by adding this line:
+</p>
+
+<div class="code"><pre>
+	dl("/path/to/modulename.so");	// Load the module
+</pre></div>
+
+<p>
+to the start of each PHP file.  SWIG also generates a php module, which
+attempts to do the <tt>dl()</tt> call for you:
+</p>
+
+<div class="code"><pre>
+	include("example.php");
+</pre></div>
+
+<H2><a name="Php_nn2"></a>28.2 Basic PHP interface</H2>
+
+
+<p>
+It is important to understand that PHP uses a single global namespace
+into which all symbols from extension modules are loaded.  It is quite
+possible for names of symbols in one extension module to clash with
+other symbols unless care is taken to <tt>%rename</tt> them.
+</p>
+
+<H3><a name="Php_nn2_1"></a>28.2.1 Constants</H3>
+
+
+<p>
+These work in much the same way as in C/C++, constants can be defined
+by using either the normal C pre-processor declarations, or the
+<tt>%constant</tt> SWIG directive.  These will then be available from
+your PHP script as a PHP constant, (i.e. no dollar sign is needed to
+access them.) For example, with a swig interface file like this,
+</p>
+
+<div class="code"><pre>
+%module example
+
+#define PI 3.14159
+
+%constant int E  = 2.71828
+</pre>
+</div>
+
+<p>
+you can access the constants in your php script like this,
+</p>
+
+<div class="code"><pre>
+include("example.php");
+
+echo "PI = " . PI . "\n";
+
+echo "E = " . E . "\n";
+
+</pre>
+</div>
+
+<p>
+There are two peculiarities with using constants in PHP. The first is that
+if you try to use an undeclared constant, it will evaluate to a string
+set to the constant's name. For example,
+</p>
+
+<div class="code"><pre>
+%module example
+
+#define EASY_TO_MISPELL	0
+</pre>
+</div>
+
+<p>
+accessed incorrectly in PHP,
+</p>
+
+<div class="code">
+<pre>
+include("example.php");
+
+if(EASY_TO_MISPEL) {
+	....
+} else {
+	....
+}
+
+</pre>
+</div>
+
+<p>
+will issue a warning about the undeclared constant, but will then
+evaluate it and turn it into a string ('EASY_TO_MISPEL'), which
+evaluates to true, rather than the value of the constant which would
+be false. This is a feature!
+</p>
+
+<p>
+The second 'feature' is that although constants are case sensitive (by
+default), you cannot declare a constant twice with alternative
+cases. E.g.,
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+#define TEST	Hello
+#define Test	World
+</pre>
+</div>
+
+<p>
+accessed from PHP,
+</p>
+
+<div class="code">
+<pre>
+include("example.php");
+
+echo TEST, Test;
+</pre>
+</div>
+
+<p>
+will output "Hello Test" rather than "Hello World". This is because
+internally, all constants are stored in a hash table by their lower
+case name, so 'TEST' and 'Test' will map to the same hash element
+('Test'). But, because we declared them case sensitive, the Zend
+engine will test if the case matches with the case the constant was
+declared with first.
+</p>
+
+<p>
+So, in the example above, the TEST constant was declared first, and
+will be stored under the hash element 'test'. The 'Test' constant will
+also map to the same hash element 'test', but will not overwrite
+it. When called from the script, the TEST constant will again be
+mapped to the hash element 'test' so the constant will be
+retrieved. The case will then be checked, and will match up, so the
+value ('Hello') will be returned. When 'Test' is evaluated, it will
+also map to the same hash element 'test'. The same constant will be
+retrieved, this time though the case check will fail as 'Test' !=
+'TEST'. So PHP will assume that Test is a undeclared constant, and as
+explained above, will return it as a string set to the constant name
+('Test'). Hence the script above will print 'Hello Test'. If they were
+declared non-case sensitive, the output would be 'Hello Hello', as
+both point to the same value, without the case test taking place.  (
+Apologies, this paragraph needs rewriting to make some sense. )
+</p>
+
+<H3><a name="Php_nn2_2"></a>28.2.2 Global Variables</H3>
+
+
+<p>
+Because PHP does not provide a mechanism to intercept access and
+assignment of global variables, global variables are supported through
+the use of automatically generated accessor functions.
+</p>
+
+<div class="code"><pre>
+%module example;
+
+%inline %{
+  double seki = 2;
+  void print_seki() {
+    zend_printf("seki is now %f\n",seki);
+  }
+%}
+</pre></div>
+
+<p>
+is accessed as follows:
+</p>
+
+<div class="code"><pre>
+include("example.php");
+print seki_get();
+seki_set( seki_get() * 2);	# The C variable is now 4.
+print seki_get();
+</pre></div>
+
+<p>
+SWIG supports global variables of all C datatypes including pointers
+and complex objects.  Additional types can be supported by using the
+<tt>varinit</tt> typemap.
+</p>
+
+<p>
+SWIG honors the <tt>%immutable</tt> modifier by not generating code
+for the <tt>_set</tt> method.  This provides read-only access to the
+variable from the php script.  Attempting to access the <tt>_set</tt>
+method will result in a php fatal error because the function is
+undefined.
+</p>
+
+<p>
+At this time SWIG does not support custom accessor methods.
+</p>
+
+<H3><a name="Php_nn2_3"></a>28.2.3 Functions</H3>
+
+
+<p>
+C functions are converted into PHP functions. Default/optional arguments are
+also allowed. An interface file like this :
+</p>
+
+<div class="code"><pre>
+%module example
+int foo(int a);
+double bar(double, double b = 3.0);
+...
+</pre></div>
+
+<p>
+Will be accessed in PHP like this :
+</p>
+
+<div class="code"><pre>
+include("example.php");
+$a = foo(2);
+$b = bar(3.5, -1.5);
+$c = bar(3.5);		# Use default argument for 2nd parameter
+
+</pre></div>
+
+<!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
+<p>
+Because PHP is a dynamically typed language, the default typemaps
+used for simple types will attempt to coerce the arguments into the appropriate type.  That is the following invocations are equivalent:
+</p>
+
+<div class="code"><pre>
+$a = foo(2);
+$a = foo("2");
+$a = foo(2.0);
+</pre></div>
+
+<p>
+Functions are invoked using pass by value semantics like all of PHP.
+This means the conversion which automatically takes place when
+invoking a swig wrapped method does not change the native type of the
+argument variable.
+</p>
+<div class="code"><pre>
+$s = "2 A string representing two";
+$a = foo($s);  # invokes 'foo(2)';
+print $s;      # The value of $s was not changed.
+</pre></div>
+-->
+
+
+<H3><a name="Php_nn2_4"></a>28.2.4 Overloading</H3>
+
+
+<p>
+Although PHP does not support overloading functions natively, swig
+will generate dispatch functions which will use <tt>%typecheck</tt>
+typemaps to allow overloading.  This dispatch function's operation and
+precedence is described in <a
+href="TypemapsSWIGPlus.html#SWIGPlus_overloaded_methods">Wrapping
+Overloaded Functions and Methods</a>.
+</p>
+
+<!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
+<p>
+Because PHP4 is a dynamically typed language, simple values can be
+silently converted from one type to another.  For example, integers,
+doubles and strings silently convert to each other depending on
+context.  This situation make overloading slightly problematic because
+given the following function:
+</p>
+
+<div class="code"><pre>
+void doit( int i );
+void doit( double i );
+</pre></div>
+
+<p>
+it is questionable which to invoke when <tt>doit("2");</tt> is used in
+PHP.  The string <tt>"2"</tt> simultaneously represents the integer
+<tt>2</tt> and the double <tt>2.0</tt>.
+</p>
+
+<p>
+In order to provide the most natural experience to PHP programmers,
+the default <tt>%typecheck</tt> implemented in <tt>php4.swg</tt>
+allows any simple type (integer, double, string) in PHP to be used for
+any simple C type (int, double, char *).  The function selected then
+depends only on the argument type precedence defined by SWIG.
+</p>
+
+<p>
+It should be noted that <tt>SWIGTYPE</tt> references and pointers will
+not be silently converted.  So these two functions:
+</p>
+
+<div class="code"><pre>
+void doit( const Vector &amp; );
+void doit( int i );
+</pre></div>
+
+<p>
+Cause less confusion and <tt>doit("2");</tt> will invoke the function
+taking the integer argument.
+</p>
+-->
+
+<H3><a name="Php_nn2_5"></a>28.2.5 Pointers and References</H3>
+
+
+<p>
+Pointers to C/C++ objects are represented
+as PHP resources, rather like MySQL connection handles.
+</p>
+
+<p>
+There are multiple ways to wrap pointers to simple types.  Given the
+following C method:
+</p>
+
+<div class="code"><pre>
+  void add( int *in1, int *in2, int *result);
+</pre></div>
+
+<p>
+One can include <b>cpointer.i</b> to generate PHP wrappers to <tt>int
+*</tt>.
+</p>
+
+<div class="code"><pre>
+%module example
+%include cpointer.i
+%pointer_functions(int,intp)
+
+void add( int *in1, int *in2, int *result);
+</pre></div>
+
+<p>
+This will result in the following usage in PHP:
+</p>
+
+<div class="code"><pre>
+&lt;?php
+
+include("example.php");
+
+$in1=copy_intp(3);
+$in2=copy_intp(5);
+$result=new_intp();
+
+add( $in1, $in2, $result );
+
+echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n";
+?&gt;
+</pre></div>
+
+<p>
+An alternative would be to use the include <b>typemaps.i</b> which
+defines named typemaps for INPUT, OUTPUT and INOUT variables.  One
+needs to either <tt>%apply</tt> the appropriate typemap or adjust the
+parameter names as appropriate.
+</p>
+
+<div class="code"><pre>
+%module example
+%include typemaps.i
+
+void add( int *INPUT, int *INPUT, int *OUTPUT);
+
+</pre></div>
+
+<p>
+This will result in the following usage in PHP:
+</p>
+
+<div class="code"><pre>
+&lt;?php
+
+include("example.php");
+
+$in1 = 3;
+$in2 = 5;
+$result= add($in1,$in2);  # Note using variables for the input is unnecessary.
+
+echo "The sum $in1 + $in2 = $result\n";
+?&gt;
+</pre></div>
+
+<p>
+Because PHP has a native concept of reference, it may seem more natural
+to the PHP developer to use references to pass pointers.  To enable
+this, one needs to include <b>phppointers.i</b> which defines the
+named typemap REFERENCE.
+</p>
+
+<div class="code"><pre>
+%module example
+%include phppointers.i
+
+void add( int *REF, int *REF, int *REF);
+
+</pre></div>
+
+<p>
+This will result in the following usage in PHP:
+</p>
+
+<div class="code"><pre>
+&lt;?php
+
+include("example.php");
+
+$in1 = 3;
+$in2 = 5;
+$result = 0;
+add(&amp;$in1,&amp;$in2,&amp;$result);
+
+echo "The sum $in1 + $in2 = $result\n";
+?&gt;
+</pre></div>
+
+<p>
+It is important to note that a php variable which is NULL when passed
+by reference would end up passing a NULL pointer into the function.
+In PHP, an unassigned variable (i.e. where the first reference to the
+variable is not an assignment) is
+NULL.  In the above example, if any of the three variables had not
+been assigned, a NULL pointer would have been passed into
+<tt>add</tt>.  Depending on the implementation of the function, this
+may or may not be a good thing.
+</p>
+
+<p>
+We chose to allow passing NULL pointers into functions because that is
+sometimes required in C libraries.  A NULL pointer can be created in
+PHP in a number of ways: by using <tt>unset</tt> on an existing
+variable, or assigning <tt>NULL</tt> to a variable.
+</p>
+
+<H3><a name="Php_nn2_6"></a>28.2.6 Structures and C++ classes</H3>
+
+
+<p>
+SWIG defaults to wrapping C++ structs and classes with PHP classes.  This
+requires SWIG to generate different code for PHP4 and PHP5, so you must
+specify which you want using <tt>-php4</tt> or <tt>-php5</tt> (currently
+<tt>-php</tt> generates PHP4 class wrappers for compatibility with
+SWIG 1.3.29 and earlier, but this may change in the future).
+</p>
+
+<p>
+PHP4 classes are implemented entirely using the Zend C API so
+no additional php code is generated.  For PHP5, a PHP wrapper
+class is generated which calls a set of flat functions wrapping the C++ class.
+In many cases the PHP4 and PHP5 wrappers will behave the same way,
+but the PHP5 ones make use of better PHP5's better OO functionality
+where appropriate.
+</p>
+
+<p>
+This interface file
+</p>
+
+<div class="code"><pre>
+%module vector
+
+class Vector {
+public:
+	double x,y,z;
+	Vector();
+	~Vector();
+	double magnitude();
+};
+
+struct Complex {
+ double re, im;
+};
+</pre></div>
+
+<p>
+Would be used in the following way from either PHP4 or PHP5:
+</p>
+
+<div class="code"><pre>
+&lt;?php
+  require "vector.php";
+
+  $v = new Vector();
+  $v-&gt;x = 3;
+  $v-&gt;y = 4;
+  $v-&gt;z = 5;
+
+  echo "Magnitude of ($v-&gt;x,$v-&gt;y,$v-&gt;z) = " . $v-&gt;magnitude() . "\n";
+
+  $v = NULL;   # destructor called.
+
+  $c = new Complex();
+
+  $c-&gt;re = 0;
+  $c-&gt;im = 0;
+
+  # $c destructor called when $c goes out of scope.
+?&gt;
+</pre></div>
+
+<p>
+Member variables and methods are accessed using the <tt>-&gt;</tt> operator.
+</p>
+
+<H4><a name="Php_nn2_6_1"></a>28.2.6.1 Using <tt>-noproxy</tt></H4>
+
+
+<p>
+The <tt>-noproxy</tt> option flattens the object structure and
+generates collections of named functions (these are the functions
+which the PHP5 class wrappers call).  The above example results
+in the following PHP functions:
+</p>
+
+<div class="code"><pre>
+new_Vector();
+Vector_x_set($obj,$d);
+Vector_x_get($obj);
+Vector_y_set($obj,$d);
+Vector_y_get($obj);
+Vector_z_set($obj,$d);
+Vector_z_get($obj);
+Vector_magnitude($obj);
+new_Complex();
+Complex_re_set($obj,$d);
+Complex_re_get($obj);
+Complex_im_set($obj,$d);
+Complex_im_get($obj);
+</pre></div>
+
+<H4><a name="Php_nn2_6_2"></a>28.2.6.2 Constructors and Destructors</H4>
+
+
+<p>
+The constructor is called when <tt>new Object()</tt> (or
+<tt>new_Object()</tt> if using <tt>-noproxy</tt>) is used to create an
+instance of the object. If multiple constructors are defined for an
+object, function overloading will be used to determine which
+constructor to execute.
+</p>
+
+<p>
+Because PHP uses reference counting to manage resources, simple
+assignment of one variable to another such as:
+</p>
+
+<div class="code"><pre>
+$ref = $v;
+</pre></div>
+
+<p>
+causes the symbol <tt>$ref</tt> to refer to the same underlying object
+as <tt>$v</tt>.  This does not result in a call to the C++ copy
+constructor or copy assignment operator.
+</p>
+
+<p>
+One can force execution of the copy constructor by using:
+</p>
+<div class="code"><pre>
+$o_copy = new Object($o);
+</pre></div>
+
+<p>
+Destructors are automatically called when all variables referencing
+the instance are reassigned or go out of scope.  The destructor is not
+available to be called manually.  To force a destructor to be called
+the programmer can either reassign the variable or call
+<tt>unset($v)</tt>
+</p>
+
+<H4><a name="Php_nn2_6_3"></a>28.2.6.3 Static Member Variables</H4>
+
+
+<p>
+Static member variables are not supported in PHP4, and it does not
+appear to be possible to intercept accesses to static member variables
+in PHP5. Therefore, static member variables are
+wrapped using a class function with the same name, which
+returns the current value of the class variable. For example
+</p>
+
+<div class="code"><pre>
+%module example
+
+class Ko {
+	static int threats;
+};
+
+</pre></div>
+
+<p>
+would be accessed in PHP as,
+</p>
+
+<div class="code"><pre>
+include("example.php");
+
+echo "There has now been " . Ko::threats() . " threats\n";
+
+</pre></div>
+
+<p>
+To set the static member variable, pass the value as the argument to the class
+function, e.g.
+</p>
+
+<div class="code"><pre>
+
+Ko::threats(10);
+
+echo "There has now been " . Ko::threats() . " threats\n";
+
+</pre></div>
+<H4><a name="Php_nn2_6_4"></a>28.2.6.4 Static Member Functions</H4>
+
+
+<p>
+Static member functions are supported in PHP using the
+<tt>class::function()</tt> syntax.  For example
+</p>
+
+<div class="code"><pre>
+%module example
+class Ko {
+  static void threats();
+};
+</pre></div>
+
+would be executed in PHP as,
+<div class="code"><pre>
+include("example.php");
+Ko::threats();
+</pre></div>
+
+
+<H3><a name="Php_nn2_7"></a>28.2.7 PHP Pragmas, Startup and Shutdown code</H3>
+
+
+<p>
+Note: Currently pragmas for PHP need to be specified using
+<tt>%pragma(php4)</tt> but also apply for PHP5!  This is just a historical
+oddity because SWIG's PHP support predates PHP5.
+</p>
+
+<p>
+To place PHP code in the generated "example.php" file one can use the
+<b>code</b> pragma. The code is inserted after loading the shared
+object.
+</p>
+
+<div class="code"><pre>
+%module example
+%pragma(php4) code="
+# This code is inserted into example.php
+echo \"example.php execution\\n\";
+"
+</pre></div>
+
+<p>
+Results in the following in "example.php"
+</p>
+
+<div class="code"><pre>
+# This code is inserted into example.php
+echo "example.php execution\n";
+</pre></div>
+
+<p>
+The <b>include</b> pragma is a short cut to add include statements to
+the example.php file.
+</p>
+
+<div class="code"><pre>
+%module example
+%pragma(php4) code="
+include \"include.php\";
+"
+%pragma(php) include="include.php"   // equivalent.
+</pre></div>
+
+<p>
+The <b>phpinfo</b> pragma inserts code in the
+<tt>PHP_MINFO_FUNCTION</tt> which is called from PHP's
+phpinfo() function.
+</p>
+
+<div class="code"><pre>
+%module example;
+%pragma(php4) phpinfo="
+  zend_printf("An example of PHP support through SWIG\n");
+  php_info_print_table_start();
+  php_info_print_table_header(2, \"Directive\", \"Value\");
+  php_info_print_table_row(2, \"Example support\", \"enabled\");
+  php_info_print_table_end();
+"
+</pre></div>
+
+<p>
+To insert code into the <tt>PHP_MINIT_FUNCTION</tt>, one can use
+either <tt>%init</tt> or <tt>%minit</tt>.
+</p>
+
+<div class="code"><pre>
+%module example;
+%init {
+  zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
+}
+%minit {
+  zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
+}
+</pre></div>
+
+<p>
+To insert code into the <tt>PHP_MSHUTDOWN_FUNCTION</tt>, one can use
+either <tt>%init</tt> or <tt>%minit</tt>.
+</p>
+
+<div class="code"><pre>
+%module example;
+%mshutdown {
+  zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n");
+}
+</pre></div>
+
+<p>
+The <tt>%rinit</tt> and <tt>%rshutdown</tt> statements insert code
+into the request init and shutdown code respectively.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Pike.html b/trunk/Doc/Manual/Pike.html
new file mode 100644
index 0000000..3e39d40
--- /dev/null
+++ b/trunk/Doc/Manual/Pike.html
@@ -0,0 +1,245 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Pike</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Pike"></a>29 SWIG and Pike</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Pike_nn2">Preliminaries</a>
+<ul>
+<li><a href="#Pike_nn3">Running SWIG</a>
+<li><a href="#Pike_nn4">Getting the right header files</a>
+<li><a href="#Pike_nn5">Using your module</a>
+</ul>
+<li><a href="#Pike_nn6">Basic C/C++ Mapping</a>
+<ul>
+<li><a href="#Pike_nn7">Modules</a>
+<li><a href="#Pike_nn8">Functions</a>
+<li><a href="#Pike_nn9">Global variables</a>
+<li><a href="#Pike_nn10">Constants and enumerated types</a>
+<li><a href="#Pike_nn11">Constructors and Destructors</a>
+<li><a href="#Pike_nn12">Static Members</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes SWIG support for Pike. As of this writing, the
+SWIG  Pike module is still under development and is not considered
+ready for prime  time. The Pike module is being developed against the
+Pike 7.4.10 release  and may not be compatible with previous versions
+of Pike.
+</p>
+
+<p>
+This chapter covers most SWIG features, but certain low-level details
+are  covered in less depth than in earlier chapters.  At the very
+least, make sure you read the "<a href="SWIG.html#SWIG">SWIG Basics</a>"
+chapter.<br>
+</p>
+
+<H2><a name="Pike_nn2"></a>29.1 Preliminaries</H2>
+
+
+<H3><a name="Pike_nn3"></a>29.1.1 Running SWIG</H3>
+
+
+<p>
+Suppose that you defined a SWIG module such as the following:
+</p>
+
+<div class="code">
+  <pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>int fact(int n);<br></pre>
+</div>
+
+<p>
+To build a C extension module for Pike, run SWIG using the <tt>-pike</tt> option :
+</p>
+
+<div class="code">
+  <pre>$ <b>swig -pike example.i</b><br></pre>
+</div>
+
+<p>
+If you're building a C++ extension, be sure to add the <tt>-c++</tt> option:
+</p>
+
+<div class="code">
+  <pre>$ <b>swig -c++ -pike example.i</b><br></pre>
+</div>
+
+<p>
+This creates a single source file named <tt>example_wrap.c</tt> (or <tt>example_wrap.cxx</tt>, if you
+ran SWIG with the <tt>-c++</tt> option).
+The SWIG-generated source file contains the low-level wrappers that need
+to be compiled and linked with the rest of your C/C++ application to
+create an extension module.
+</p>
+
+<p>
+The name of the wrapper file is derived from the name of the input
+file.  For example, if the input file is <tt>example.i</tt>, the name
+of the wrapper file is <tt>example_wrap.c</tt>. To change this, you
+can use the <tt>-o</tt> option:
+</p>
+
+<div class="code">
+  <pre>$ <b>swig -pike -o pseudonym.c example.i</b><br></pre>
+</div>
+<H3><a name="Pike_nn4"></a>29.1.2 Getting the right header files</H3>
+
+
+<p>
+In order to compile the C/C++ wrappers, the compiler needs to know the
+path to the Pike header files. These files are usually contained in a
+directory such as
+</p>
+
+<div class="code">
+  <pre>/usr/local/pike/7.4.10/include/pike<br></pre>
+</div>
+
+<p>
+There doesn't seem to be any way to get Pike itself to reveal the
+location of these files, so you may need to hunt around for them.
+You're looking for files with the names <tt>global.h</tt>, <tt>program.h</tt>
+and so on.
+</p>
+
+<H3><a name="Pike_nn5"></a>29.1.3 Using your module</H3>
+
+
+<p>
+To use your module, simply use Pike's <tt>import</tt> statement:
+</p>
+
+<div class="code"><pre>
+$ <b>pike</b>
+Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend)
+&gt; <b>import example;</b>
+&gt; <b>fact(4);</b>
+(1) Result: 24
+</pre></div>
+
+<H2><a name="Pike_nn6"></a>29.2 Basic C/C++ Mapping</H2>
+
+
+<H3><a name="Pike_nn7"></a>29.2.1 Modules</H3>
+
+
+<p>
+All of the code for a given SWIG module is wrapped into a single Pike
+module. Since the name of the shared library that implements your
+module ultimately determines the module's name (as far as Pike is
+concerned), SWIG's <tt>%module</tt> directive doesn't really have any
+significance.
+</p>
+
+<H3><a name="Pike_nn8"></a>29.2.2 Functions</H3>
+
+
+<p>
+Global functions are wrapped as new Pike built-in functions. For
+example,
+</p>
+
+<div class="code"><pre>
+%module example
+
+int fact(int n);
+</pre></div>
+
+<p>
+creates a new built-in function <tt>example.fact(n)</tt> that works
+exactly as you'd expect it to:
+</p>
+
+<div class="code"><pre>
+&gt; <b>import example;</b>
+&gt; <b>fact(4);</b>
+(1) Result: 24
+</pre></div>
+
+<H3><a name="Pike_nn9"></a>29.2.3 Global variables</H3>
+
+
+<p>
+Global variables are currently wrapped as a pair of of functions, one to get
+the current value of the variable and another to set it. For example, the
+declaration
+</p>
+
+<div class="code"><pre>
+%module example
+
+double Foo;
+</pre></div>
+
+<p>
+will result in two functions, <tt>Foo_get()</tt> and <tt>Foo_set()</tt>:
+</p>
+
+<div class="code"><pre>
+&gt; <b>import example;</b>
+&gt; <b>Foo_get();</b>
+(1) Result: 3.000000
+&gt; <b>Foo_set(3.14159);</b>
+(2) Result: 0
+&gt; <b>Foo_get();</b>
+(3) Result: 3.141590
+</pre></div>
+
+<H3><a name="Pike_nn10"></a>29.2.4 Constants and enumerated types</H3>
+
+
+<p>
+Enumerated types in C/C++ declarations are wrapped as Pike constants,
+not as Pike enums.
+</p>
+
+<H3><a name="Pike_nn11"></a>29.2.5 Constructors and Destructors</H3>
+
+
+<p>
+Constructors are wrapped as <tt>create()</tt> methods, and destructors are
+wrapped as <tt>destroy()</tt> methods, for Pike classes.
+</p>
+
+<H3><a name="Pike_nn12"></a>29.2.6 Static Members</H3>
+
+
+<p>
+Since Pike doesn't support static methods or data for Pike classes, static
+member functions in your C++ classes are wrapped as regular functions and
+static member variables are wrapped as pairs of functions (one to get the
+value of the static member variable, and another to set it). The names of
+these functions are prepended with the name of the class.
+For example, given this C++ class declaration:
+</p>
+
+<div class="code"><pre>
+class Shape
+{
+public:
+    static void print();
+    static int nshapes;
+};
+</pre></div>
+
+<p>
+SWIG will generate a <tt>Shape_print()</tt> method that invokes the static
+<tt>Shape::print()</tt> member function, as well as a pair of methods,
+<tt>Shape_nshapes_get()</tt> and <tt>Shape_nshapes_set()</tt>, to get and set
+the value of <tt>Shape::nshapes</tt>.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Preface.html b/trunk/Doc/Manual/Preface.html
new file mode 100644
index 0000000..630657a
--- /dev/null
+++ b/trunk/Doc/Manual/Preface.html
@@ -0,0 +1,251 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Preface</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Preface"></a>1 Preface</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Preface_nn2">Introduction</a>
+<li><a href="#Preface_nn3">Special Introduction for Version 1.3</a>
+<li><a href="#Preface_nn4">SWIG Versions</a>
+<li><a href="#Preface_nn5">SWIG resources</a>
+<li><a href="#Preface_nn6">Prerequisites</a>
+<li><a href="#Preface_nn7">Organization of this manual</a>
+<li><a href="#Preface_nn8">How to avoid reading the manual</a>
+<li><a href="#Preface_nn9">Backwards Compatibility</a>
+<li><a href="#Preface_nn10">Credits</a>
+<li><a href="#Preface_nn11">Bug reports</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<H2><a name="Preface_nn2"></a>1.1 Introduction</H2>
+
+
+<p>
+SWIG (Simplified Wrapper and Interface Generator) is a software development tool for building scripting language
+interfaces to C and C++ programs.  Originally developed in 1995, SWIG was
+first used by scientists in the Theoretical Physics Division at Los Alamos National Laboratory for
+building user interfaces to simulation codes running on the Connection
+Machine 5 supercomputer. In this environment, scientists needed to
+work with huge amounts of simulation data, complex hardware, and a
+constantly changing code base. The use of a scripting language
+interface provided a simple yet highly flexible foundation for solving these
+types of problems.  SWIG simplifies development by largely automating
+the task of scripting language integration--allowing developers and users
+to focus on more important problems.
+</p>
+
+<p>
+Although SWIG was originally developed for scientific applications, it
+has since evolved into a general purpose tool that is used in a wide
+variety of applications--in fact almost anything where C/C++ programming
+is involved.
+
+<H2><a name="Preface_nn3"></a>1.2 Special Introduction for Version 1.3</H2>
+
+
+<p>
+Since SWIG was released in 1996, its user base and applicability has
+continued to grow. Although its rate of development has varied, an
+active development effort has continued to make improvements to the
+system.  Today, nearly a dozen developers are working to create
+SWIG-2.0---a system that aims to provide wrapping support for nearly
+all of the ANSI C++ standard and approximately ten target languages
+including Guile, Java, Mzscheme, Ocaml, Perl, Pike, PHP, Python, Ruby,
+and Tcl.
+</p>
+
+<H2><a name="Preface_nn4"></a>1.3 SWIG Versions</H2>
+
+
+<p>
+For several years, the most stable version of SWIG has been release
+1.1p5. Starting with version 1.3, a new version numbering scheme has
+been adopted.  Odd version numbers (1.3, 1.5, etc.) represent
+development versions of SWIG.  Even version numbers (1.4, 1.6, etc.)
+represent stable releases.  Currently, developers are working to
+create a stable SWIG-2.0 release.  Don't let the development status 
+of SWIG-1.3 scare you---it is much more stable (and capable) than SWIG-1.1p5.
+</p>
+
+<H2><a name="Preface_nn5"></a>1.4 SWIG resources</H2>
+
+
+<p>
+The official location of SWIG related material is
+</p>
+
+<div class="shell"><pre>
+<a href="http://www.swig.org">http://www.swig.org</a>
+</pre></div>
+
+<p>
+This site contains the latest version of the software, users guide,
+and information regarding bugs, installation problems, and
+implementation tricks. 
+
+<p>
+You can also subscribe to the swig-user mailing list by visiting the page
+</p>
+
+<div class="shell"><pre>
+<a href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</a>
+</pre></div>
+
+<p>
+The mailing list often discusses some of the more technical aspects of
+SWIG along with information about beta releases and future work.
+</p>
+
+<p>
+SVN access to the latest version of SWIG is also available.  More information 
+about this can be obtained at:
+</p>
+
+<div class="shell"><pre>
+<a href="http://www.swig.org/svn.html">http://www.swig.org/svn.html</a>
+</pre></div>
+
+
+<H2><a name="Preface_nn6"></a>1.5 Prerequisites</H2>
+
+
+<p>
+This manual assumes that you know how to write C/C++ programs and that you
+have at least heard of scripting languages such as 
+Tcl, Python, and Perl. A detailed knowledge of these scripting
+languages is not required although some familiarity won't
+hurt. No prior experience with building C extensions to these
+languages is required---after all, this is what SWIG does automatically.
+However, you should be reasonably familiar with the use of
+compilers, linkers, and makefiles since making
+scripting language extensions is somewhat more complicated than
+writing a normal C program.
+</p>
+
+<p>
+Recent SWIG releases have become significantly more capable in
+their C++ handling--especially support for advanced features like
+namespaces, overloaded operators, and templates.  Whenever possible,
+this manual tries to cover the technicalities of this interface.
+However, this isn't meant to be a tutorial on C++ programming.   For many
+of the gory details, you will almost certainly want to consult a good C++ reference.  If you don't program
+in C++, you may just want to skip those parts of the manual.
+
+<H2><a name="Preface_nn7"></a>1.6 Organization of this manual</H2>
+
+
+<p>
+The first few chapters of this manual describe SWIG in general and
+provide an overview of its capabilities. The remaining chapters are
+devoted to specific SWIG language modules and are self
+contained. Thus, if you are using SWIG to build Python interfaces, you
+can probably skip to that chapter and find almost everything you need
+to know.   Caveat: we are currently working on a documentation rewrite and many
+of the older language module chapters are still somewhat out of date.
+</p>
+
+<H2><a name="Preface_nn8"></a>1.7 How to avoid reading the manual</H2>
+
+
+<p>
+If you hate reading manuals, glance at the "Introduction" which
+contains a few simple examples. These
+examples contain about 95% of everything you need to know to use
+SWIG. After that, simply use the language-specific chapters as a reference.
+The SWIG distribution also comes with a large directory of
+examples that illustrate different topics.
+</p>
+
+<H2><a name="Preface_nn9"></a>1.8 Backwards Compatibility</H2>
+
+
+<p>
+If you are a previous user of SWIG, don't expect recent versions of
+SWIG to provide backwards compatibility.  In fact, backwards
+compatibility issues may arise even between successive 1.3.x releases.
+Although these incompatibilities are regrettable, SWIG-1.3 is an active
+development project.  The primary goal of this effort is to make SWIG
+better---a process that would simply be impossible if the developers
+are constantly bogged down with backwards compatibility issues.
+</p>
+
+<p>
+On a positive note, a few incompatibilities are a small price to pay
+for the large number of new features that have been
+added---namespaces, templates, smart pointers, overloaded methods,
+operators, and more.
+</p>
+
+
+<p>
+If you need to work with different versions of SWIG and backwards
+compatibility is an issue, you can use the SWIG_VERSION preprocessor
+symbol which holds the version of SWIG being executed.
+SWIG_VERSION is a hexadecimal integer such as 0x010311 (corresponding to SWIG-1.3.11).
+This can be used in an interface file to define different typemaps, take
+advantage of different features etc:
+</p>
+
+<div class="code"><pre>
+#if SWIG_VERSION &gt;= 0x010311
+/* Use some fancy new feature */
+#endif
+</pre></div>
+
+<p>
+Note: The version symbol is not defined in the generated SWIG
+wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.
+</p>
+
+<H2><a name="Preface_nn10"></a>1.9 Credits</H2>
+
+
+<p>
+SWIG is an unfunded project that would not be possible without the
+contributions of many people.  Most recent SWIG development has been
+supported by Matthias K&ouml;ppe, William Fulton, Lyle Johnson,
+Richard Palmer, Thien-Thi Nguyen, Jason Stewart, Loic Dachary, Masaki
+Fukushima, Luigi Ballabio, Sam Liddicott, Art Yerkes, Marcelo Matus, 
+Harco de Hilster, John Lenz, and Surendra Singhi.
+</p>
+
+<p>
+Historically, the following people contributed to early versions of SWIG.
+Peter Lomdahl, Brad Holian, Shujia Zhou, Niels Jensen, and Tim Germann
+at Los Alamos National Laboratory were the first users. Patrick
+Tullmann at the University of Utah suggested the idea of automatic
+documentation generation. John Schmidt and Kurtis Bleeker at the
+University of Utah tested out the early versions.  Chris Johnson
+supported SWIG's developed at the University of Utah. John Buckman,
+Larry Virden, and Tom Schwaller provided valuable input on the first
+releases and improving the portability of SWIG. David Fletcher and
+Gary Holt have provided a great deal of input on improving SWIG's
+Perl5 implementation. Kevin Butler contributed the first Windows NT
+port.
+
+<H2><a name="Preface_nn11"></a>1.10 Bug reports</H2>
+
+
+<p>
+Although every attempt has been made to make SWIG bug-free, we are also trying
+to make feature improvements that may introduce bugs.
+To report a bug, either send mail to the SWIG developer
+list at the <a href="http://www.swig.org/mail.html">swig-devel mailing list</a> or report a bug
+at the <a href="http://www.swig.org/bugs.html">SWIG bug tracker</a>. In your report, be as specific as
+possible, including (if applicable), error messages, tracebacks (if a
+core dump occurred), corresponding portions of the SWIG interface file
+used, and any important pieces of the SWIG generated wrapper code.  We
+can only fix bugs if we know about them.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Preprocessor.html b/trunk/Doc/Manual/Preprocessor.html
new file mode 100644
index 0000000..a454c81
--- /dev/null
+++ b/trunk/Doc/Manual/Preprocessor.html
@@ -0,0 +1,490 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG Preprocessor</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Preprocessor"></a>7 Preprocessing</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Preprocessor_nn2">File inclusion</a>
+<li><a href="#Preprocessor_nn3">File imports</a>
+<li><a href="#Preprocessor_condition_compilation">Conditional Compilation</a>
+<li><a href="#Preprocessor_nn5">Macro Expansion</a>
+<li><a href="#Preprocessor_nn6">SWIG Macros</a>
+<li><a href="#Preprocessor_nn7">C99 and GNU Extensions</a>
+<li><a href="#Preprocessor_nn8">Preprocessing and %{ ... %} &amp; " ... " delimiters</a>
+<li><a href="#Preprocessor_nn9">Preprocessing and { ... } delimiters</a>
+<li><a href="#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</a>
+<li><a href="#Preprocessor_nn10">Viewing preprocessor output</a>
+<li><a href="#Preprocessor_warning_error">The #error and #warning directives</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+SWIG includes its own enhanced version of the C preprocessor.  The preprocessor
+supports the standard preprocessor directives and macro expansion rules.
+However, a number of modifications and enhancements have been made.  This
+chapter describes some of these modifications.
+</p>
+
+<H2><a name="Preprocessor_nn2"></a>7.1 File inclusion</H2>
+
+
+<p>
+To include another file into a SWIG interface, use the <tt>%include</tt> directive
+like this:
+</p>
+
+<div class="code">
+<pre>
+%include "pointer.i"
+</pre>
+</div>
+
+<p>
+Unlike, <tt>#include</tt>, <tt>%include</tt> includes each file once (and will not
+reload the file on subsequent <tt>%include</tt> declarations).  Therefore, it
+is not necessary to use include-guards in SWIG interfaces.
+</p>
+
+<p>
+By default, the <tt>#include</tt> is ignored unless you run SWIG with the
+<tt>-includeall</tt> option.   The reason for ignoring traditional includes
+is that you often don't want SWIG to try and wrap everything included
+in standard header system headers and auxiliary files.
+
+<H2><a name="Preprocessor_nn3"></a>7.2 File imports</H2>
+
+
+<p>
+SWIG provides another file inclusion directive with the <tt>%import</tt> directive.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%import "foo.i"
+</pre>
+</div>
+
+<p>
+The purpose of <tt>%import</tt> is to collect certain information from another 
+SWIG interface file or a header file without actually generating any wrapper code.
+Such information generally includes type declarations (e.g., <tt>typedef</tt>) as well as
+C++ classes that might be used as base-classes for class declarations in the interface.
+The use of <tt>%import</tt> is also important when SWIG is used to generate
+extensions as a collection of related modules.   This is an advanced topic and is described
+in a later chapter.
+</p>
+
+<P>
+The <tt>-importall</tt> directive tells SWIG to follow all <tt>#include</tt> statements
+as imports.    This might be useful if you want to extract type definitions from system 
+header files without generating any wrappers.
+
+<H2><a name="Preprocessor_condition_compilation"></a>7.3 Conditional Compilation</H2>
+
+
+<p>
+SWIG fully supports the use of <tt>#if</tt>, <tt>#ifdef</tt>,
+<tt>#ifndef</tt>, <tt>#else</tt>, <tt>#endif</tt> to conditionally
+include parts of an interface.  The following symbols are predefined
+by SWIG when it is parsing the interface:
+</p>
+
+<div class="code"><pre>
+SWIG                            Always defined when SWIG is processing a file
+SWIGIMPORTED                    Defined when SWIG is importing a file with <tt>%import</tt>
+SWIGMAC                         Defined when running SWIG on the Macintosh
+SWIGWIN                         Defined when running SWIG under Windows
+SWIG_VERSION                    Hexadecimal number containing SWIG version,
+                                such as 0x010311 (corresponding to SWIG-1.3.11).
+
+SWIGCHICKEN                     Defined when using CHICKEN
+SWIGCSHARP                      Defined when using C#
+SWIGGUILE                       Defined when using Guile
+SWIGJAVA                        Defined when using Java
+SWIGLUA                         Defined when using Lua
+SWIGMODULA3                     Defined when using Modula-3
+SWIGMZSCHEME                    Defined when using Mzscheme        
+SWIGOCAML                       Defined when using Ocaml
+SWIGPERL                        Defined when using Perl
+SWIGPERL5                       Defined when using Perl5
+SWIGPHP                         Defined when using PHP
+SWIGPHP4                        Defined when using PHP4
+SWIGPHP5                        Defined when using PHP5
+SWIGPIKE                        Defined when using Pike
+SWIGPYTHON                      Defined when using Python
+SWIGRUBY                        Defined when using Ruby
+SWIGSEXP                        Defined when using S-expressions
+SWIGTCL                         Defined when using Tcl
+SWIGTCL8                        Defined when using Tcl8.0
+SWIGXML                         Defined when using XML
+</pre></div>
+
+<p>
+In addition, SWIG defines the following set of standard C/C++ macros:
+</p>
+
+<div class="code">
+<pre>
+__LINE__                        Current line number
+__FILE__                        Current file name
+__STDC__                        Defined to indicate ANSI C
+__cplusplus                     Defined when -c++ option used
+</pre>
+</div>
+
+<p>
+Interface files can look at these symbols as necessary to change the
+way in which an interface is generated or to mix SWIG directives with
+C code. These symbols are also defined within the C code generated by
+SWIG (except for the symbol `<tt>SWIG</tt>' which is only defined
+within the SWIG compiler).
+</p>
+
+<H2><a name="Preprocessor_nn5"></a>7.4 Macro Expansion</H2>
+
+
+<p>
+Traditional preprocessor macros can be used in SWIG interfaces.  Be aware that the <tt>#define</tt> statement
+is also used to try and detect constants.  Therefore, if you have something like this in your file,
+</p>
+
+<div class="code">
+<pre>
+#ifndef _FOO_H 1
+#define _FOO_H 1
+...
+#endif
+</pre>
+</div>
+
+<p>
+you may get some extra constants such as <tt>_FOO_H</tt> showing up in the scripting interface.
+</p>
+
+<p>
+More complex macros can be defined in the standard way. For example:
+</p>
+
+<div class="code">
+<pre>
+#define EXTERN extern
+#ifdef __STDC__
+#define _ANSI(args)   (args)
+#else
+#define _ANSI(args) ()
+#endif
+</pre>
+</div>
+
+<p>
+The following operators can appear in macro definitions:
+</p>
+
+<ul>
+<li><tt>#x</tt><br>
+Converts macro argument <tt>x</tt> to a string surrounded by double quotes ("x").
+</li>
+
+<li><tt>x ## y</tt><br>
+Concatenates x and y together to form <tt>xy</tt>.
+</li>
+
+<li><tt>`x`</tt><br>
+If <tt>x</tt> is a string surrounded by double quotes, do nothing.  Otherwise, turn into a string
+like <tt>#x</tt>.  This is a non-standard SWIG extension.
+</li>
+</ul>
+
+<H2><a name="Preprocessor_nn6"></a>7.5 SWIG Macros</H2>
+
+
+<p>
+SWIG provides an enhanced macro capability with the <tt>%define</tt> and <tt>%enddef</tt> directives. 
+For example:
+</p>
+
+<div class="code">
+<pre>
+%define ARRAYHELPER(type,name)
+%inline %{
+type *new_ ## name (int nitems) {
+   return (type *) malloc(sizeof(type)*nitems);
+}
+void delete_ ## name(type *t) {
+   free(t);
+}
+type name ## _get(type *t, int index) {
+   return t[index];
+}
+void name ## _set(type *t, int index, type val) {
+   t[index] = val;
+}
+%}
+%enddef
+
+ARRAYHELPER(int, IntArray)
+ARRAYHELPER(double, DoubleArray)
+</pre>
+</div>
+
+<p>
+The primary purpose of <tt>%define</tt> is to define large macros of code.  Unlike normal C preprocessor
+macros, it is not necessary to terminate each line with a continuation character (\)--the macro definition
+extends to the first occurrence of <tt>%enddef</tt>.    Furthermore, when such macros are expanded,
+they are reparsed through the C preprocessor.  Thus, SWIG macros can contain all other preprocessor
+directives except for nested <tt>%define</tt> statements.
+</p>
+
+<p>
+The SWIG macro capability is a very quick and easy way to generate large amounts of code.  In fact,
+many of SWIG's advanced features and libraries are built using this mechanism (such as C++ template
+support).
+</p>
+
+<H2><a name="Preprocessor_nn7"></a>7.6 C99 and GNU Extensions</H2>
+
+
+<p>
+SWIG-1.3.12 and newer releases support variadic preprocessor macros.  For example:
+</p>
+
+<div class="code">
+<pre>
+#define DEBUGF(fmt,...)   fprintf(stderr,fmt,__VA_ARGS__)
+</pre>
+</div>
+
+<p>
+When used, any extra arguments to <tt>...</tt> are placed into the
+special variable <tt>__VA_ARGS__</tt>.   This also works with special SWIG
+macros defined using <tt>%define</tt>.
+</p>
+
+<p>
+SWIG allows a variable number of arguments to be empty.  However, this often results
+in an extra comma (,) and syntax error in the resulting expansion. For example:
+</p>
+
+<div class="code">
+<pre>
+DEBUGF("hello");   --&gt; fprintf(stderr,"hello",);
+</pre>
+</div>
+
+<p>
+To get rid of the extra comma, use <tt>##</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+#define DEBUGF(fmt,...)   fprintf(stderr,fmt, ##__VA_ARGS__)
+</pre>
+</div>
+
+<p>
+SWIG also supports GNU-style variadic macros.    For example:
+</p>
+
+<div class="code">
+<pre>
+#define DEBUGF(fmt, args...)  fprintf(stdout,fmt,args)
+</pre>
+</div>
+
+<p>
+<b>Comment:</b> It's not entirely clear how variadic macros might be useful to
+interface building.   However, they are used internally to implement a number of
+SWIG directives and are provided to make SWIG more compatible with C99 code.
+</p>
+
+<H2><a name="Preprocessor_nn8"></a>7.7 Preprocessing and %{ ... %} &amp; " ... " delimiters</H2>
+
+
+<p>
+The SWIG preprocessor does not process any text enclosed in a code block %{ ... %}.  Therefore,
+if you write code like this,
+</p>
+
+<div class="code">
+<pre>
+%{
+#ifdef NEED_BLAH
+int blah() {
+   ...
+}
+#endif
+%}
+</pre>
+</div>
+
+<p>
+the contents of the <tt>%{ ... %}</tt> block are copied without
+modification to the output (including all preprocessor directives).
+</p>
+
+<H2><a name="Preprocessor_nn9"></a>7.8 Preprocessing and { ... } delimiters</H2>
+
+
+<p>
+SWIG always runs the preprocessor on text appearing inside <tt>{ ... }</tt>.  However,
+sometimes it is desirable to make a preprocessor directive pass through to the output
+file.  For example:
+</p>
+
+<div class="code">
+<pre>
+%extend Foo {
+   void bar() {
+      #ifdef DEBUG
+       printf("I'm in bar\n");
+      #endif
+   }
+}
+</pre>
+</div>
+
+<p>
+By default, SWIG will interpret the <tt>#ifdef DEBUG</tt> statement.   However, if you really wanted that code
+to actually go into the wrapper file, prefix the preprocessor directives with <tt>%</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+%extend Foo {
+   void bar() {
+      %#ifdef DEBUG
+       printf("I'm in bar\n");
+      %#endif
+   }
+}
+</pre>
+</div>
+
+<p>
+SWIG will strip the extra <tt>%</tt> and leave the preprocessor directive in the code.
+</p>
+
+<H2><a name="Preprocessor_typemap_delimiters"></a>7.9 Preprocessor and Typemaps</H2>
+
+
+<p>
+<a href="Typemaps.html">Typemaps</a> support a special attribute called <tt>noblock</tt> where the { ... } delimiters can be used,
+but the delimiters are not actually generated into the code.
+The effect is then similar to using "" or %{ %} delimiters but the code <b>is</b> run through the preprocessor. For example:
+</p>
+
+<div class="code">
+<pre>
+#define SWIG_macro(CAST) (CAST)$input
+%typemap(in) Int {$1= SWIG_macro(int);}
+</pre>
+</div>
+
+<p>
+might generate
+</p>
+
+<div class="code">
+<pre>
+  {
+    arg1=(int)jarg1;
+  }
+</pre>
+</div>
+
+<p>
+whereas
+</p>
+
+<div class="code">
+<pre>
+#define SWIG_macro(CAST) (CAST)$input
+%typemap(in,noblock=1) Int {$1= SWIG_macro(int);}
+</pre>
+</div>
+
+<p>
+might generate
+</p>
+
+<div class="code">
+<pre>
+  arg1=(int)jarg1;
+</pre>
+</div>
+
+<p>
+and
+</p>
+
+<div class="code">
+<pre>
+#define SWIG_macro(CAST) (CAST)$input
+%typemap(in) Int %{$1=SWIG_macro(int);%}
+</pre>
+</div>
+
+<p>
+would generate
+</p>
+
+<div class="code">
+<pre>
+  arg1=SWIG_macro(int);
+</pre>
+</div>
+
+
+<H2><a name="Preprocessor_nn10"></a>7.10 Viewing preprocessor output</H2>
+
+
+<p>
+Like many compilers, SWIG supports a <tt>-E</tt> command line option to display the output from the preprocessor.
+When the <tt>-E</tt> switch is used, SWIG will not generate any wrappers.
+Instead the results after the preprocessor has run are displayed.
+This might be useful as an aid to debugging and viewing the results of macro expansions.
+</p>
+
+<H2><a name="Preprocessor_warning_error"></a>7.11 The #error and #warning directives</H2>
+
+
+<p>
+SWIG supports the commonly used <tt>#warning</tt> and <tt>#error</tt> preprocessor directives.
+The <tt>#warning</tt> directive will cause SWIG to issue a warning then continue processing.
+The <tt>#error</tt> directive will cause SWIG to exit with a fatal error.
+Example usage:
+</p>
+
+<div class="code">
+<pre>
+#error "This is a fatal error message"
+#warning "This is a warning message"
+</pre>
+</div>
+
+<p>
+The <tt>#error</tt> behaviour can be made to work like <tt>#warning</tt> if the <tt>-cpperraswarn</tt>
+commandline option is used. Alternatively, the <tt>#pragma</tt> directive can be used to the same effect, for example:
+</p>
+
+<div class="code">
+<pre>
+  /* Modified behaviour: #error does not cause SWIG to exit with error */
+  #pragma SWIG cpperraswarn=1
+  /* Normal behaviour: #error does cause SWIG to exit with error */
+  #pragma SWIG cpperraswarn=0
+</pre>
+</div>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Python.html b/trunk/Doc/Manual/Python.html
new file mode 100644
index 0000000..62b72fa
--- /dev/null
+++ b/trunk/Doc/Manual/Python.html
@@ -0,0 +1,4964 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Python</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Python"></a>30 SWIG and Python</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Python_nn2">Overview</a>
+<li><a href="#Python_nn3">Preliminaries</a>
+<ul>
+<li><a href="#Python_nn4">Running SWIG</a>
+<li><a href="#Python_nn6">Using distutils</a>
+<li><a href="#Python_nn7">Hand compiling a dynamic module</a>
+<li><a href="#Python_nn8">Static linking</a>
+<li><a href="#Python_nn9">Using your module</a>
+<li><a href="#Python_nn10">Compilation of C++ extensions</a>
+<li><a href="#Python_nn11">Compiling for 64-bit platforms</a>
+<li><a href="#Python_nn12">Building Python Extensions under Windows</a>
+</ul>
+<li><a href="#Python_nn13">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="#Python_nn14">Modules</a>
+<li><a href="#Python_nn15">Functions</a>
+<li><a href="#Python_nn16">Global variables</a>
+<li><a href="#Python_nn17">Constants and enums</a>
+<li><a href="#Python_nn18">Pointers</a>
+<li><a href="#Python_nn19">Structures</a>
+<li><a href="#Python_nn20">C++ classes</a>
+<li><a href="#Python_nn21">C++ inheritance</a>
+<li><a href="#Python_nn22">Pointers, references, values, and arrays</a>
+<li><a href="#Python_nn23">C++ overloaded functions</a>
+<li><a href="#Python_nn24">C++ operators</a>
+<li><a href="#Python_nn25">C++ namespaces</a>
+<li><a href="#Python_nn26">C++ templates</a>
+<li><a href="#Python_nn27">C++ Smart Pointers</a>
+<li><a href="#Python_nn27a">C++ Reference Counted Objects (ref/unref)</a>
+</ul>
+<li><a href="#Python_nn28">Further details on the Python class interface</a>
+<ul>
+<li><a href="#Python_nn29">Proxy classes</a>
+<li><a href="#Python_nn30">Memory management</a>
+<li><a href="#Python_nn31">Python 2.2 and classic classes</a>
+</ul>
+<li><a href="#directors">Cross language polymorphism</a>
+<ul>
+<li><a href="#Python_nn33">Enabling directors</a>
+<li><a href="#Python_nn34">Director classes</a>
+<li><a href="#Python_nn35">Ownership and object destruction</a>
+<li><a href="#Python_nn36">Exception unrolling</a>
+<li><a href="#Python_nn37">Overhead and code bloat</a>
+<li><a href="#Python_nn38">Typemaps</a>
+<li><a href="#Python_nn39">Miscellaneous</a>
+</ul>
+<li><a href="#Python_nn40">Common customization features</a>
+<ul>
+<li><a href="#Python_nn41">C/C++ helper functions</a>
+<li><a href="#Python_nn42">Adding additional Python code</a>
+<li><a href="#Python_nn43">Class extension with %extend</a>
+<li><a href="#Python_nn44">Exception handling with %exception</a>
+</ul>
+<li><a href="#Python_nn45">Tips and techniques</a>
+<ul>
+<li><a href="#Python_nn46">Input and output parameters</a>
+<li><a href="#Python_nn47">Simple pointers</a>
+<li><a href="#Python_nn48">Unbounded C Arrays</a>
+<li><a href="#Python_nn49">String handling</a>
+<li><a href="#Python_nn50">Arrays</a>
+<li><a href="#Python_nn51">String arrays</a>
+<li><a href="#Python_nn52">STL wrappers</a>
+</ul>
+<li><a href="#Python_nn53">Typemaps</a>
+<ul>
+<li><a href="#Python_nn54">What is a typemap?</a>
+<li><a href="#Python_nn55">Python typemaps</a>
+<li><a href="#Python_nn56">Typemap variables</a>
+<li><a href="#Python_nn57">Useful Python Functions</a>
+</ul>
+<li><a href="#Python_nn58">Typemap Examples</a>
+<ul>
+<li><a href="#Python_nn59">Converting  Python list to a char ** </a>
+<li><a href="#Python_nn60">Expanding a Python object into multiple arguments</a>
+<li><a href="#Python_nn61">Using typemaps to return arguments</a>
+<li><a href="#Python_nn62">Mapping Python tuples into small arrays</a>
+<li><a href="#Python_nn63">Mapping sequences to C arrays</a>
+<li><a href="#Python_nn64">Pointer handling</a>
+</ul>
+<li><a href="#Python_nn65">Docstring Features</a>
+<ul>
+<li><a href="#Python_nn66">Module docstring</a>
+<li><a href="#Python_nn67">%feature("autodoc")</a>
+<ul>
+<li><a href="#Python_nn68">%feature("autodoc", "0")</a>
+<li><a href="#Python_nn69">%feature("autodoc", "1")</a>
+<li><a href="#Python_nn70">%feature("autodoc", "docstring")</a>
+</ul>
+<li><a href="#Python_nn71">%feature("docstring")</a>
+</ul>
+<li><a href="#Python_nn72">Python Packages</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+<b>Caution: This chapter is under repair!</b>
+</p>
+
+<p>
+This chapter describes SWIG's support of Python.  SWIG is compatible
+with most recent Python versions including Python 2.2 as well as older
+versions dating back to Python 1.5.2.  For the best results, consider using Python
+2.0 or newer.
+</p>
+
+<p>
+This chapter covers most SWIG features, but certain low-level details
+are covered in less depth than in earlier chapters.  At the
+very least, make sure you read the "<a href="SWIG.html#SWIG">SWIG
+Basics</a>" chapter.
+</p>
+
+<H2><a name="Python_nn2"></a>30.1 Overview</H2>
+
+
+<p>
+To build Python extension modules, SWIG uses a layered approach in which
+parts of the extension module are defined in C and other parts are 
+defined in Python.  The C layer contains low-level wrappers whereas Python code
+is used to define high-level features.
+</p>
+
+<p>
+This layered approach recognizes the fact that certain aspects of
+extension building are better accomplished in each language (instead
+of trying to do everything in C or C++). Furthermore, by generating code in both
+languages, you get a lot more flexibility since you can enhance the extension
+module with support code in either language.
+</p>
+
+<p>
+In describing the Python interface, this chapter starts by covering the
+basics of configuration, compiling, and installing Python modules.
+Next, the Python interface to common C and C++ programming features is
+described.  Advanced customization features such as typemaps are then
+described followed by a discussion of low-level implementation
+details.
+</p>
+
+<H2><a name="Python_nn3"></a>30.2 Preliminaries</H2>
+
+
+<H3><a name="Python_nn4"></a>30.2.1 Running SWIG</H3>
+
+
+<p>
+Suppose that you defined a SWIG module such as the following:
+</p>
+
+<div class="code">
+<pre>
+/* File: example.i */
+%module example
+
+%{
+#define SWIG_FILE_WITH_INIT
+#include "example.h"
+%}
+
+int fact(int n);
+</pre>
+</div>
+
+<p>
+The <tt> #define SWIG_FILE_WITH_INIT </tt> line inserts a macro that specifies that the
+resulting C file should be built as a python extension, inserting the module
+<tt>init</tt> code. This <tt>.i</tt> file wraps the following simple C file:
+</p>
+
+<div class="code">
+<pre>
+/* File: example.c */
+
+#include "example.h"
+
+int fact(int n) {
+    if (n &lt; 0){ /* This should probably return an error, but this is simpler */
+        return 0;
+    }
+    if (n == 0) {
+        return 1;
+    }
+    else {
+        /* testing for overflow would be a good idea here */
+        return n * fact(n-1);
+    }
+}
+
+</pre>
+</div>
+
+<p>
+With the header file:
+</p>
+
+<div class="code">
+<pre>
+/* File: example.h */
+
+int fact(int n);
+</pre>
+</div>
+
+<p>
+To build a Python module, run SWIG using the <tt>-python</tt> option:
+</p>
+
+<div class="shell"><pre>
+$ swig -python example.i
+</pre></div>
+
+<p>
+If building a C++ extension, add the <tt>-c++</tt> option:
+</p>
+
+<div class="shell"><pre>
+$ swig -c++ -python example.i
+</pre></div>
+
+<p>
+This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
+<tt>example_wrap.cxx</tt> and a Python source file <tt>example.py</tt>.   The generated C
+source file contains the low-level wrappers that need to be compiled and linked with the
+rest of your C/C++ application to create an extension module. The Python source file
+contains high-level support code. This is the file that you will import to use the module.
+</p>
+
+<p>
+The name of the wrapper file is derived from the name of the input file.  For example, if the
+input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
+To change this, you can use the <tt>-o</tt> option.   The name of the Python file is derived
+from the module name specified with <tt>%module</tt>.  If the module name is <tt>example</tt>,
+then a file <tt>example.py</tt> is created.
+</p>
+
+<p>
+The following sections have further practical examples and details on
+how you might go about compiling and using the generated files.
+</p>
+
+<H3><a name="Python_nn6"></a>30.2.2 Using distutils</H3>
+
+
+<p>
+The preferred approach to building an extension module for python is to compile it with
+distutils, which comes with all recent versions of python
+(<a href="http://docs.python.org/dist/dist.html">Distutils Docs</a>).
+</p>
+
+<p>
+Distutils takes care of making sure that your extension is built with all the correct
+flags, headers, etc. for the version of Python it is run with. Distutils will compile your
+extension into a shared object file or DLL (<tt>.so</tt> on Linux, <tt>.pyd</tt> on
+Windows, etc). In addition, distutils can handle installing your package into
+site-packages, if that is desired. A configuration file (conventionally called: <tt>setup.py</tt>)
+describes the extension (and related python modules). The distutils will
+then generate all the right compiler directives to build it for you.
+</p>
+
+<p>
+Here is a sample <tt>setup.py</tt> file for the above example:
+</p>
+
+<div class="code">
+<pre>
+#!/usr/bin/env python
+
+"""
+setup.py file for SWIG example
+"""
+
+from distutils.core import setup, Extension
+
+
+example_module = Extension('_example',
+                           sources=['example_wrap.c', 'example.c'],
+                           )
+
+setup (name = 'example',
+       version = '0.1',
+       author      = "SWIG Docs",
+       description = """Simple swig example from docs""",
+       ext_modules = [example_module],
+       py_modules = ["example"],
+       )
+</pre>
+</div>
+
+<p>
+In this example, the line: <tt>example_module = Extension(....)</tt> creates an Extension
+module object, defining the name as <tt>_example</tt>, and using the source code files:
+<tt>example_wrap.c</tt>, generated by swig, and <tt>example.c</tt>, your original c
+source. The swig (and other python extension modules) tradition is for the compiled
+extension to have the name of the python portion, prefixed by an underscore. If the name
+of your python module is "<tt>example.py</tt>", then the name of the corresponding object file
+will be"<tt>_example.so</tt>"
+</p>
+
+<p>
+The <tt>setup</tt> call then sets up distutils to build your package, defining
+some meta data, and passing in your extension module object.
+Once this is saved as <tt>setup.py</tt>, you can build your extension with these commands:
+</p>
+
+<div class="shell"><pre>
+$ swig -python example.i
+$ python setup.py build_ext --inplace
+</pre></div>
+
+<p>
+And a .so, or .pyd or... will be created for you. It will build a version that matches the
+python that you run the command with. Taking apart the command line:
+</p>
+
+<ul>
+<li> <tt>python</tt> -- the version of python you want to build for
+<li> <tt>setup.py</tt> -- the name of your setup script (it can be called anything, but
+     setup.py is the tradition)
+<li> <tt>build_ext</tt> -- telling distutils to build extensions
+<li> <tt>--inplace</tt> -- this tells distutils to put the extension lib in the current dir.
+     Other wise, it will put it inside a build hierarchy, and you'd have to move it to use it.
+</ul>
+
+<p>
+The distutils have many other features, consult the python distutils docs for details.
+</p>
+
+<p>
+This same approach works on all platforms if the appropriate compiler is installed. (it
+can even build extensions to the standard Windows Python using MingGW)
+</p>
+
+<H3><a name="Python_nn7"></a>30.2.3 Hand compiling a dynamic module</H3>
+
+
+<p>
+While the preferred approach to building an extension module is to use the distutils, some
+people like to integrate building extensions with a larger build system, and thus may wish
+to compile their modules without the distutils. To do this, you need to compile your
+program using commands like this (shown for Linux):
+</p>
+
+<div class="shell"><pre>
+$ swig -python example.i
+$ gcc -c -fPIC example.c
+$ gcc -c -fPIC example_wrap.c -I/usr/local/include/python2.0
+$ gcc -shared example.o example_wrap.o -o _example.so
+</pre></div>
+
+<p>
+The exact commands for doing this vary from platform to platform. 
+However, SWIG tries to guess the right options when it is installed.  Therefore, 
+you may want to start with one of the examples in the <tt>SWIG/Examples/python</tt> 
+directory.   If that doesn't work, you will need to read the man-pages for
+your compiler and linker to get the right set of options.  You might also
+check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
+additional information.
+</p>
+
+<p>
+When linking the module, <b>the name of the output file has to match the name
+of the module prefixed by an underscore</b>.  If the name of your module is "<tt>example</tt>", then the
+name of the corresponding object file should be
+"<tt>_example.so</tt>" or "<tt>_examplemodule.so</tt>".
+The name of the module is specified using the <tt>%module</tt> directive or the 
+<tt> -module</tt> command line option.
+</p>
+
+<p>
+<b>Compatibility Note:</b> In SWIG-1.3.13 and earlier releases, module
+names did not include the leading underscore.  This is because modules
+were normally created as C-only extensions without the extra Python
+support file (instead, creating Python code was supported as an optional
+feature).  This has been changed in SWIG-1.3.14 and is consistent with
+other Python extension modules.  For example, the <tt>socket</tt>
+module actually consists of two files; <tt>socket.py</tt> and
+<tt>_socket.so</tt>.  Many other built-in Python modules follow a similar convention.
+</p>
+
+
+<H3><a name="Python_nn8"></a>30.2.4 Static linking</H3>
+
+
+<p>
+An alternative approach to dynamic linking is to rebuild the Python
+interpreter with your extension module added to it.  In the past,
+this approach was sometimes necessary due to limitations in dynamic loading
+support on certain machines.  However, the situation has improved greatly
+over the last few years and you should not consider this approach 
+unless there is really no other option.
+</p>
+
+<p>
+The usual procedure for adding a new module to Python involves finding
+the Python source, adding an entry to the <tt>Modules/Setup</tt> file,
+and rebuilding the interpreter using the Python Makefile.  However,
+newer Python versions have changed the build process.  You may need to edit
+the 'setup.py' file in the Python distribution instead.
+</p>
+
+<p>
+In earlier versions of SWIG, the <tt>embed.i</tt> library file could be used to
+rebuild the interpreter.  For example:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%inline %{
+extern int fact(int);
+extern int mod(int, int);
+extern double My_variable;
+%}
+
+%include embed.i       // Include code for a static version of Python
+
+</pre></div>
+
+<p>
+The <tt>embed.i</tt> library file includes supporting code that
+contains everything needed to rebuild Python. To rebuild the interpreter,
+you simply do something like this:
+</p>
+
+<div class="shell"><pre>
+$ swig -python example.i
+$ gcc example.c example_wrap.c \
+        -Xlinker -export-dynamic \
+        -DHAVE_CONFIG_H -I/usr/local/include/python2.1 \
+	-I/usr/local/lib/python2.1/config \
+	-L/usr/local/lib/python2.1/config -lpython2.1 -lm -ldl \
+	-o mypython
+
+</pre></div>
+<p>
+You will need to supply the same libraries that were used to build Python the first
+time.  This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
+and <tt>-lpthread</tt>.  Assuming this actually works, the new version of Python
+should be identical to the default version except that your extension module will be
+a built-in part of the interpreter.
+</p>
+
+<p>
+<b>Comment:</b> In practice, you should probably try to avoid static
+linking if possible. Some programmers may be inclined
+to use static linking in the interest of getting better performance.
+However, the performance gained by static linking tends to be rather
+minimal in most situations (and quite frankly not worth the extra
+hassle in the opinion of this author). 
+</p>
+
+<p>
+<b>Compatibility note:</b> The <tt>embed.i</tt> library file is
+deprecated and has not been maintained for several years.  Even though it
+appears to "work" with Python 2.1, no future support is guaranteed.
+If using static linking, you might want to rely on a different approach
+(perhaps using distutils).
+</p>
+
+<H3><a name="Python_nn9"></a>30.2.5 Using your module</H3>
+
+
+<p>
+To use your module, simply use the Python <tt>import</tt> statement. If
+all goes well, you will be able to this:
+</p>
+
+<div class="targetlang"><pre>
+$ python
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; example.fact(4)
+24
+&gt;&gt;&gt;
+</pre></div>
+
+<p>
+A common error received by first-time users is the following:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+  File "example.py", line 2, in ?
+    import _example
+ImportError: No module named _example
+</pre>
+</div>
+
+<p>
+If you get this message, it means that you either forgot to compile the wrapper
+code into an extension module or you didn't give the extension module the right
+name.  Make sure that you compiled the wrappers into a module called <tt>_example.so</tt>.  And
+don't forget the leading underscore (_).
+</p>
+
+<p>
+Another possible error is the following:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+ImportError: dynamic module does not define init function (init_example)
+&gt;&gt;&gt;                                                               
+</pre>
+</div>
+
+<p>
+This error is almost always caused when a bad name is given to the shared object file. 
+For example, if you created a file <tt>example.so</tt> instead of <tt>_example.so</tt> you would 
+get this error.  Alternatively, this error could arise if the name of the module is
+inconsistent with the module name supplied with the <tt>%module</tt> directive.
+Double-check the interface to make sure the module name and the shared object
+filename match.  Another possible cause of this error is forgetting to link the SWIG-generated
+wrapper code with the rest of your application when creating the extension module.
+</p>
+
+<p>
+Another common error is something similar to the following:
+</p>
+
+<div class="targetlang">
+<pre>
+Traceback (most recent call last):
+  File "example.py", line 3, in ?
+    import example
+ImportError: ./_example.so: undefined symbol: fact
+</pre>
+</div>
+
+<p>
+This error usually indicates that you forgot to include some object
+files or libraries in the linking of the shared library file.  Make
+sure you compile both the SWIG wrapper file and your original program
+into a shared library file.  Make sure you pass all of the required libraries
+to the linker.  
+</p>
+
+<p>
+Sometimes unresolved symbols occur because a wrapper has been created
+for a function that doesn't actually exist in a library.  This usually
+occurs when a header file includes a declaration for a function that
+was never actually implemented or it was removed from a library
+without updating the header file.  To fix this, you can either edit
+the SWIG input file to remove the offending declaration or you can use
+the <tt>%ignore</tt> directive to ignore the declaration.
+</p>
+
+<p>
+Finally, suppose that your extension module is linked with another library like this:
+</p>
+
+<div class="shell">
+<pre>
+$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <b>-lfoo</b> \
+      -o _example.so
+</pre>
+</div>
+
+<p>
+If the <tt>foo</tt> library is compiled as a shared library, you might encounter the following
+problem when you try to use your module:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+ImportError: libfoo.so: cannot open shared object file: No such file or directory
+&gt;&gt;&gt;                 
+</pre>
+</div>
+
+<p>
+This error is generated because the dynamic linker can't locate the
+<tt>libfoo.so</tt> library.  When shared libraries are loaded, the
+system normally only checks a few standard locations such as
+<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>.   To fix this problem,
+there are several things you can do.  First, you can recompile your extension
+module with extra path information. For example, on Linux you can do this:
+</p>
+
+<div class="shell">
+<pre>
+$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
+      <b>-Xlinker -rpath /home/beazley/projects/lib </b> \
+      -o _example.so
+</pre>
+</div>
+
+<p>
+Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
+include the directory with your shared libraries. 
+If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
+a noticeable performance impact on all other applications that you run.
+To set it only for Python, you might want to do this instead:
+</p>
+
+<div class="shell">
+<pre>
+$ env LD_LIBRARY_PATH=/home/beazley/projects/lib python
+</pre>
+</div>
+
+<p>
+Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
+<tt>crle</tt> (Solaris) to add additional search paths to the default
+system configuration (this requires root access and you will need to
+read the man pages).
+</p>
+
+<H3><a name="Python_nn10"></a>30.2.6 Compilation of C++ extensions</H3>
+
+
+<p>
+Compilation of C++ extensions has traditionally been a tricky problem.
+Since the Python interpreter is written in C, you need to take steps to
+make sure C++ is properly initialized and that modules are compiled
+correctly. This should be a non-issue if you're using distutils, as
+it takes care of all that for you. The following is included for
+historical reasons, and in case you need to compile on your own.
+</p>
+
+<p>
+On most machines, C++ extension modules should be linked using the C++
+compiler.  For example:
+</p>
+
+<div class="shell"><pre>
+$ swig -c++ -python example.i
+$ g++ -c example.cxx
+$ g++ -c example_wrap.cxx -I/usr/local/include/python2.0
+$ g++ -shared example.o example_wrap.o -o _example.so
+</pre></div>
+
+<p>
+On some platforms, you could also need to generate
+position-independent code (PIC), by using a compiler option such as -fPIC.
+Notably, the x86_64 (Opteron and EM64T) platform requires it, and when
+using the GNU Compiler Suite, you will need to modify the previous example
+as follows:
+</p>
+
+<div class="shell"><pre>
+$ swig -c++ -python example.i
+$ g++ -fPIC -c example.cxx
+$ g++ -fPIC -c example_wrap.cxx -I/usr/local/include/python2.0
+$ g++ -shared example.o example_wrap.o -o _example.so
+</pre></div>
+
+<p>
+In addition to this, you may need to include additional library
+files to make it work.  For example, if you are using the Sun C++ compiler on
+Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
+</p>
+
+<div class="shell"><pre>
+$ swig -c++ -python example.i
+$ CC -c example.cxx
+$ CC -c example_wrap.cxx -I/usr/local/include/python2.0
+$ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun
+</pre></div>
+
+<p>
+Of course, the extra libraries to use are completely non-portable---you will 
+probably need to do some experimentation.
+</p>
+
+<p>
+Sometimes people have suggested that it is necessary to relink the
+Python interpreter using the C++ compiler to make C++ extension modules work.
+In the experience of this author, this has never actually appeared to be
+necessary.   Relinking the interpreter with C++ really only includes the 
+special run-time libraries described above---as long as you link your extension 
+modules with these libraries, it should not be necessary to rebuild Python.
+</p>
+
+<p>
+If you aren't entirely sure about the linking of a C++ extension, you
+might look at an existing C++ program.  On many Unix machines, the
+<tt>ldd</tt> command will list library dependencies.  This should give
+you some clues about what you might have to include when you link your
+extension module. For example:
+</p>
+
+<div class="shell">
+<pre>
+$ ldd swig
+        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
+        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
+        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
+        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
+</pre>
+</div>
+
+<p>
+As a final complication, a major weakness of C++ is that it does not
+define any sort of standard for binary linking of libraries.  This
+means that C++ code compiled by different compilers will not link
+together properly as libraries nor is the memory layout of classes and
+data structures implemented in any kind of portable manner.  In a
+monolithic C++ program, this problem may be unnoticed.  However, in Python, it
+is possible for different extension modules to be compiled with
+different C++ compilers.  As long as these modules are self-contained,
+this probably won't matter.  However, if these modules start sharing data,
+you will need to take steps to avoid segmentation faults and other
+erratic program behavior.   If working with lots of software components, you
+might want to investigate using a more formal standard such as COM.
+</p>
+
+<H3><a name="Python_nn11"></a>30.2.7 Compiling for 64-bit platforms</H3>
+
+
+<p>
+On platforms that support 64-bit applications (Solaris, Irix, etc.),
+special care is required when building extension modules.  On these
+machines, 64-bit applications are compiled and linked using a different
+set of compiler/linker options.  In addition, it is not generally possible to mix 
+32-bit and 64-bit code together in the same application.
+</p>
+
+<p>
+To utilize 64-bits, the Python executable will need to be recompiled
+as a 64-bit application.  In addition, all libraries, wrapper code,
+and every other part of your application will need to be compiled for
+64-bits.  If you plan to use other third-party extension modules, they
+will also have to be recompiled as 64-bit extensions.
+</p>
+
+<p>
+If you are wrapping commercial software for which you have no source
+code, you will be forced to use the same linking standard as used by
+that software.  This may prevent the use of 64-bit extensions.  It may
+also introduce problems on platforms that support more than one
+linking standard (e.g., -o32 and -n32 on Irix).
+</p>
+
+<p> On the Linux x86_64 platform (Opteron or EM64T), besides of the
+required compiler option -fPIC discussed above, you will need to be
+careful about the libraries you link with or the library path you
+use. In general, a Linux distribution will have two set of libraries,
+one for native x86_64 programs (under /usr/lib64), and another for 32
+bits compatibility (under /usr/lib). Also, the compiler options -m32
+and -m64 allow you to choose the desired binary format for your python
+extension.
+</p>
+
+<H3><a name="Python_nn12"></a>30.2.8 Building Python Extensions under Windows</H3>
+
+
+<p>
+Building a SWIG extension to Python under Windows is roughly similar to
+the process used with Unix. Using the distutils, it is essentially
+identical. If you have the same version of the MS compiler that Python
+was built with (the python2.4 and python2.5 distributed by python.org
+are built with Visual Studio 2003), the standard <tt> python setup.py
+build </tt> should just work.
+</p>
+
+<p>
+As of python2.5, the distutils support building extensions with MingGW out
+of the box. Following the instruction here:
+<a href="http://boodebr.org/main/python/build-windows-extensions">Building
+Python extensions for Windows with only free tools</a> should get you started.
+</p>
+
+<p>
+If you need to build it on your own, the following notes are provided:
+</p>
+
+<p>
+You will need to create a DLL that can be loaded into the interpreter. 
+This section briefly describes the use of SWIG with Microsoft Visual
+C++.   As a starting point, many of SWIG's examples include project
+files.  You might want to take a quick look at these in addition to
+reading this section.
+</p>
+
+<p>
+In Developer Studio, SWIG should be invoked as a custom build option.
+This is usually done as follows:
+</p>
+
+<ul>
+<li>Open up a new workspace and use the AppWizard to select a DLL
+project.
+
+<li>Add both the SWIG interface file (the .i file), any supporting C
+files, and the name of the wrapper file that will be created by SWIG
+(ie. <tt>example_wrap.c</tt>).  Note : If using C++, choose a
+different suffix for the wrapper file such as
+<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
+exist yet--Developer Studio keeps a reference to it.
+
+<li>Select the SWIG interface file and go to the settings menu.  Under
+settings, select the "Custom Build" option.
+
+<li>Enter "SWIG" in the description field.
+
+<li>Enter "<tt>swig -python -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
+
+<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
+
+<li>Next, select the settings for the entire project and go to
+"C++:Preprocessor". Add the include directories for your Python
+installation under "Additional include directories".
+
+<li>Define the symbol  __WIN32__ under preprocessor options.  
+
+<li>Finally, select the settings for the entire project and go to
+"Link Options".  Add the Python library file to your link libraries.
+For example "python21.lib".  Also, set the name of the output file to
+match the name of your Python module, ie. _example.pyd - Note that _example.dll also worked with Python-2.4 and earlier.
+
+<li>Build your project.
+</ul>
+
+<p>
+If all went well, SWIG will be automatically invoked whenever
+you build your project.  Any changes made to the interface file will
+result in SWIG being automatically executed to produce a new version of
+the wrapper file. 
+</p>
+
+<p>
+To run your new Python extension, simply run Python
+and use the <tt>import</tt> command as normal. For example :
+</p>
+
+<div class="targetlang"><pre>
+$ python
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; print example.fact(4)
+24
+&gt;&gt;&gt;
+</pre></div>
+
+<p>
+If you get an <tt>ImportError</tt> exception when importing the module, you may
+have forgotten to include additional library files when you built your module.
+If you get an access violation or some kind of general protection fault 
+immediately upon import, you have a more serious problem.   This 
+is often caused by linking your extension module against the wrong 
+set of Win32 debug or thread libraries.  You will have to fiddle around with
+the build options of project to try and track this down.
+</p>
+
+<p>
+Some users have reported success in building extension modules using Cygwin
+and other compilers.  However, the problem of building usable DLLs with these
+compilers tends to be rather problematic.  For the latest information,
+you may want to consult the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">
+SWIG Wiki</a>.
+</p>
+
+
+<H2><a name="Python_nn13"></a>30.3 A tour of basic C/C++ wrapping</H2>
+
+
+<p>
+By default, SWIG tries to build a very natural Python interface
+to your C/C++ code.  Functions are wrapped as functions, classes are wrapped as classes, and so forth.
+This section briefly covers the essential aspects of this wrapping.
+</p>
+
+<H3><a name="Python_nn14"></a>30.3.1 Modules</H3>
+
+
+<p>
+The SWIG <tt>%module</tt> directive specifies the name of the Python
+module. If you specify `<tt>%module example</tt>', then everything is
+wrapped into a Python '<tt>example</tt>' module.  Underneath the covers,
+this module consists of a Python source file <tt>example.py</tt> and a low-level
+extension module <tt>_example.so</tt>. When choosing a
+module name, make sure you don't use the same name as a built-in
+Python command or standard module name.  
+</p>
+
+<H3><a name="Python_nn15"></a>30.3.2 Functions</H3>
+
+
+<p>
+Global functions are wrapped as new Python built-in functions.  For example,
+</p>
+
+<div class="code"><pre>
+%module example
+int fact(int n);
+</pre></div>
+
+<p>
+creates a built-in function <tt>example.fact(n)</tt> that works exactly
+like you think it does:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; print example.fact(4)
+24
+&gt;&gt;&gt;
+</pre></div>
+
+<H3><a name="Python_nn16"></a>30.3.3 Global variables</H3>
+
+
+<p>
+C/C++ global variables are fully supported by SWIG.  However, the underlying
+mechanism is somewhat different than you might expect due to the way that
+Python assignment works.  When you type the following in Python
+</p>
+
+<div class="targetlang"><pre>
+a = 3.4
+</pre></div>
+
+<p>
+"a" becomes a name for an object containing the value 3.4. If you later type
+</p>
+
+<div class="targetlang"><pre>
+b = a
+</pre></div>
+
+<p>
+then "a" and "b" are both names for the object containing the value
+3.4. Thus, there is only one object containing 3.4 and "a"
+and "b" are both names that refer to it. This is quite
+different than C where a variable name refers to a memory location in which
+a value is stored (and assignment copies data into that location). 
+Because of this, there is no direct way to map variable 
+assignment in C to variable assignment in Python.
+</p>
+
+<p>
+To provide access to C global variables, SWIG creates a special
+object called `<tt>cvar</tt>' that is added to each SWIG generated
+module. Global variables are then accessed as attributes of this object.
+For example, consider this interface
+</p>
+
+<div class="code"><pre>
+// SWIG interface file with global variables
+%module example
+...
+%inline %{
+extern int My_variable;
+extern double density;
+%}
+...
+</pre></div>
+<p>
+Now look at the Python interface:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; # Print out value of a C global variable
+&gt;&gt;&gt; print example.cvar.My_variable
+4
+&gt;&gt;&gt; # Set the value of a C global variable
+&gt;&gt;&gt; example.cvar.density = 0.8442
+&gt;&gt;&gt; # Use in a math operation
+&gt;&gt;&gt; example.cvar.density = example.cvar.density*1.10
+</pre></div>
+
+<p>
+If you make an error in variable assignment, you will receive an
+error message.  For example:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; example.cvar.density = "Hello"
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+TypeError: C variable 'density (double )'
+&gt;&gt;&gt; 
+</pre></div>
+
+<p>
+If a variable is declared as <tt>const</tt>, it is wrapped as a
+read-only variable.  Attempts to modify its value will result in an
+error.
+</p>
+
+<p>
+To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable;
+extern char *path;
+%mutable;
+</pre>
+</div>
+
+<p>
+The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
+<tt>%mutable</tt>.
+See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
+</p>
+
+<p>
+If you just want to make a specific variable immutable, supply a declaration name.  For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable path;
+...
+extern char *path;      // Read-only (due to %immutable)
+</pre>
+</div>
+
+<p>
+If you would like to access variables using a name other than "<tt>cvar</tt>", it can be
+changed using the <tt>-globals</tt> option :
+</p>
+
+<div class="shell"><pre>
+$ swig -python -globals myvar example.i
+</pre></div>
+
+<p>
+Some care is in order when importing multiple SWIG modules.
+If you use the "<tt>from &lt;file&gt; import *</tt>" style of
+importing, you will get a name clash on the variable `<tt>cvar</tt>'
+and you will only be able to access global variables from the last
+module loaded. To prevent this, you might consider renaming
+<tt>cvar</tt> or making it private to the module by giving it a name
+that starts with a leading underscore. SWIG does not create <tt>cvar</tt>
+if there are no global variables in a module.
+</p>
+
+<H3><a name="Python_nn17"></a>30.3.4 Constants and enums</H3>
+
+
+<p>
+C/C++ constants are installed as Python objects containing the
+appropriate value.  To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
+<tt>%constant</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+#define PI 3.14159
+#define VERSION "1.0"
+
+enum Beverage { ALE, LAGER, STOUT, PILSNER };
+
+%constant int FOO = 42;
+%constant const char *path = "/usr/local";
+</pre>
+</div>
+
+<p>
+For enums, make sure that the definition of the enumeration actually appears in a header
+file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
+also telling the C compiler about it, the wrapper code won't compile.
+</p>
+
+<p>
+Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
+will be accessed using the <tt>cvar</tt> object described in the previous section.  They
+are not wrapped as constants.   For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
+</p>
+
+<p>
+Constants are not guaranteed to remain constant in Python---the name
+of the constant could be accidentally reassigned to refer to some
+other object.  Unfortunately, there is no easy way for SWIG to
+generate code that prevents this.  You will just have to be careful.
+</p>
+
+<H3><a name="Python_nn18"></a>30.3.5 Pointers</H3>
+
+
+<p>
+C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no
+problem working with incomplete type information.  Here is a rather
+simple interface:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+FILE *fopen(const char *filename, const char *mode);
+int fputs(const char *, FILE *);
+int fclose(FILE *);
+</pre>
+</div>
+
+<p>
+When wrapped, you will be able to use the functions in a natural way from Python. For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; f = example.fopen("junk","w")
+&gt;&gt;&gt; example.fputs("Hello World\n", f)
+&gt;&gt;&gt; example.fclose(f)
+</pre>
+</div>
+
+<p>
+If this makes you uneasy, rest assured that there is no
+deep magic involved.  Underneath the covers, pointers to C/C++ objects are
+simply represented as opaque values using an especial python container object:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; print f
+&lt;Swig Object at _08a71808_p_FILE&gt;
+</pre></div>
+
+<p>
+This pointer value can be freely passed around to different C functions that
+expect to receive an object of type <tt>FILE *</tt>.  The only thing you can't do is 
+dereference the pointer from Python. Of course, that isn't much of a concern in this example.
+</p>
+
+<p>
+In older versions of Swig (1.3.22 or older), pointers were represented
+using a plain string object. If you have an old package that still
+requires that representation, or you just feel nostalgic, you can
+always retrieve it by casting the pointer object to a string:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; print str(f)
+_c0671108_p_FILE
+</pre></div>
+
+<p>
+Also, if you need to pass the raw pointer value to some external
+python library, you can do it by casting the pointer object to an
+integer:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; print int(f)
+135833352
+</pre></div>
+
+<p>
+However, the inverse operation is not possible, i.e., you can't build
+a Swig pointer object from a raw integer value.
+</p>
+
+<p>
+Note also that the '0' or NULL pointer is always represented by
+<tt>None</tt>, no matter what type swig is addressing. In the
+previous example, you can call:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; example.fclose(None)
+</pre>
+</div>
+
+<p>
+and that will be equivalent to the following, but not really useful, C
+code:
+</p>
+
+<div class="code">
+<pre>
+FILE *f = NULL;
+fclose(f);
+</pre>
+</div>
+
+<p>
+As much as you might be inclined to modify a pointer value directly
+from Python, don't.  The hexadecimal encoding is not necessarily the
+same as the logical memory address of the underlying object.  Instead
+it is the raw byte encoding of the pointer value.  The encoding will
+vary depending on the native byte-ordering of the platform (i.e.,
+big-endian vs. little-endian).  Similarly, don't try to manually cast
+a pointer to a new type by simply replacing the type-string.  This may
+not work like you expect, it is particularly dangerous when casting
+C++ objects.  If you need to cast a pointer or change its value,
+consider writing some helper functions instead.  For example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+/* C-style cast */
+Bar *FooToBar(Foo *f) {
+   return (Bar *) f;
+}
+
+/* C++-style cast */
+Foo *BarToFoo(Bar *b) {
+   return dynamic_cast&lt;Foo*&gt;(b);
+}
+
+Foo *IncrFoo(Foo *f, int i) {
+    return f+i;
+}
+%}
+</pre>
+</div>
+
+<p>
+Also, if working with C++, you should always try
+to use the new C++ style casts.  For example, in the above code, the
+C-style cast may return a bogus result whereas as the C++-style cast will return
+<tt>None</tt> if the conversion can't be performed.
+</p>
+
+<H3><a name="Python_nn19"></a>30.3.6 Structures</H3>
+
+
+<p>
+If you wrap a C structure, it is wrapped by a Python class.  This provides
+a very natural interface.  For example,
+</p>
+
+<div class="code"><pre>
+struct Vector {
+	double x,y,z;
+};
+
+</pre></div>
+
+<p>
+is used as follows:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; v = example.Vector()
+&gt;&gt;&gt; v.x = 3.5
+&gt;&gt;&gt; v.y = 7.2
+&gt;&gt;&gt; print v.x, v.y, v.z
+7.8 -4.5 0.0
+&gt;&gt;&gt; 
+</pre></div>
+
+<p>
+Similar access is provided for unions and the data members of C++ classes.
+</p>
+
+<p>
+If you print out the value of <tt>v</tt> in the above example, you will see
+something like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; print v
+&lt;C Vector instance at _18e31408_p_Vector&gt;
+</pre>
+</div>
+
+<p>
+This object is actually a Python instance that has been wrapped around a pointer to the low-level
+C structure.  This instance doesn't actually do anything--it just serves as a proxy.
+The pointer to the C object can be found in the the <tt>.this</tt>
+attribute.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; print v.this
+_18e31408_p_Vector
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Further details about the Python proxy class are covered a little later.
+</p>
+
+<p>
+<tt>const</tt> members of a structure are read-only. Data members
+can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   ...
+   %immutable;
+   int x;        /* Read-only members */
+   char *name;
+   %mutable;
+   ...
+};
+</pre>
+</div>
+
+<p>
+When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
+dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
+SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
+released and a new value created.   If this is not the behavior you want, you will have to use
+a typemap (described later).
+</p>
+
+<p>
+If a structure contains arrays, access to those arrays is managed through pointers.  For
+example, consider this:
+</p>
+
+<div class="code">
+<pre>
+struct Bar {
+    int  x[16];
+};
+</pre>
+</div>
+
+<p>
+If accessed in Python, you will see behavior like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; b = example.Bar()
+&gt;&gt;&gt; print b.x
+_801861a4_p_int
+&gt;&gt;&gt; 
+</pre>
+</div>
+
+<p>
+This pointer can be passed around to functions that expect to receive
+an <tt>int *</tt> (just like C).   You can also set the value of an array member using
+another pointer.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; c = example.Bar()
+&gt;&gt;&gt; c.x = b.x             # Copy contents of b.x to c.x
+</pre>
+</div>
+
+<p>
+For array assignment, SWIG copies the entire contents of the array starting with the data pointed
+to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
+no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
+fault or access violation.
+</p>
+
+<p>
+When a member of a structure is itself a structure, it is handled as a
+pointer.  For example, suppose you have two structures like this:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   int a;
+};
+
+struct Bar {
+   Foo f;
+};
+</pre>
+</div>
+
+<p>
+Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; b = Bar()
+&gt;&gt;&gt; x = b.f
+</pre>
+</div>
+
+<p>
+In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
+This is the same value as generated by this C code:
+</p>
+
+<div class="code">
+<pre>
+Bar b;
+Foo *x = &amp;b-&gt;f;       /* Points inside b */
+</pre>
+</div>
+
+<p>
+Because the pointer points inside the structure, you can modify the contents and 
+everything works just like you would expect. For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; b = Bar()
+&gt;&gt;&gt; b.f.a = 3               # Modify attribute of structure member
+&gt;&gt;&gt; x = b.f                   
+&gt;&gt;&gt; x.a = 3                 # Modifies the same structure
+</pre>
+</div>
+
+<H3><a name="Python_nn20"></a>30.3.7 C++ classes</H3>
+
+
+<p>
+C++ classes are wrapped by Python classes as well. For example, if you have this class,
+</p>
+
+<div class="code"><pre>
+class List {
+public:
+  List();
+  ~List();
+  int  search(char *item);
+  void insert(char *item);
+  void remove(char *item);
+  char *get(int n);
+  int  length;
+};
+</pre></div>
+
+<p>
+you can use it in Python like this:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; l = example.List()
+&gt;&gt;&gt; l.insert("Ale")
+&gt;&gt;&gt; l.insert("Stout")
+&gt;&gt;&gt; l.insert("Lager")
+&gt;&gt;&gt; l.get(1)
+'Stout'
+&gt;&gt;&gt; print l.length
+3
+&gt;&gt;&gt;
+</pre></div>
+
+<p>
+Class data members are accessed in the same manner as C structures.  
+</p>
+
+<p>
+Static class members present a special problem for Python.  Prior to Python-2.2, 
+Python classes had no support for static methods and no version of Python
+supports static member variables in a manner that SWIG can utilize.  Therefore, 
+SWIG generates wrappers that try to work around some of these issues.  To illustrate,
+suppose you have a class like this:
+</p>
+
+<div class="code">
+<pre>
+class Spam {
+public:
+   static void foo();
+   static int bar;
+
+};
+</pre>
+</div>
+
+<p>
+In Python, the static member can be access in three different ways:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; example.Spam_foo()    # Spam::foo()
+&gt;&gt;&gt; s = example.Spam()
+&gt;&gt;&gt; s.foo()               # Spam::foo() via an instance
+&gt;&gt;&gt; example.Spam.foo()    # Spam::foo(). Python-2.2 only
+</pre>
+</div>
+
+<p>
+The first two methods of access are supported in all versions of Python.  The
+last technique is only available in Python-2.2 and later versions.
+</p>
+
+<p>
+Static member variables are currently accessed as global variables.  This means,
+they are accessed through <tt>cvar</tt> like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; print example.cvar.Spam_bar
+7
+</pre>
+</div>
+
+<H3><a name="Python_nn21"></a>30.3.8 C++ inheritance</H3>
+
+
+<p>
+SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
+classes like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+...
+};
+
+class Bar : public Foo {
+...
+};
+</pre>
+</div>
+
+<p>
+those classes are wrapped into a hierarchy of Python classes that reflect the same inheritance
+structure.   All of the usual Python utility functions work normally:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; b = Bar()
+&gt;&gt;&gt; instance(b,Foo)
+1
+&gt;&gt;&gt; issubclass(Bar,Foo)
+1
+&gt;&gt;&gt; issubclass(Foo,Bar)
+0
+</pre>
+</div>
+
+<p>
+Furthermore, if you have functions like this
+</p>
+
+<div class="code">
+<pre>
+void spam(Foo *f);
+</pre>
+</div>
+
+<p>
+then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
+</p>
+
+<p>
+It is safe to use multiple inheritance with SWIG.
+</p>
+
+<H3><a name="Python_nn22"></a>30.3.9 Pointers, references, values, and arrays</H3>
+
+
+<p>
+In C++, there are many different ways a function might receive
+and manipulate objects.  For example:
+</p>
+
+<div class="code">
+<pre>
+void spam1(Foo *x);      // Pass by pointer
+void spam2(Foo &amp;x);      // Pass by reference
+void spam3(const Foo &amp;x);// Pass by const reference
+void spam4(Foo x);       // Pass by value
+void spam5(Foo x[]);     // Array of objects
+</pre>
+</div>
+
+<p>
+In Python, there is no detailed distinction like this--specifically,
+there are only "objects".  There are no pointers, references, arrays,
+and so forth.  Because of this, SWIG unifies all of these types
+together in the wrapper code.  For instance, if you actually had the
+above functions, it is perfectly legal to do this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = Foo()           # Create a Foo
+&gt;&gt;&gt; spam1(f)            # Ok. Pointer
+&gt;&gt;&gt; spam2(f)            # Ok. Reference
+&gt;&gt;&gt; spam3(f)            # Ok. Const reference
+&gt;&gt;&gt; spam4(f)            # Ok. Value.
+&gt;&gt;&gt; spam5(f)            # Ok. Array (1 element)
+</pre>
+</div>
+
+<p>
+Similar behavior occurs for return values.  For example, if you had
+functions like this,
+</p>
+
+<div class="code">
+<pre>
+Foo *spam6();
+Foo &amp;spam7();
+Foo  spam8();
+const Foo &amp;spam9();
+</pre>
+</div>
+
+<p>
+then all three functions will return a pointer to some <tt>Foo</tt> object.
+Since the third function (spam8) returns a value, newly allocated memory is used 
+to hold the result and a pointer is returned (Python will release this memory 
+when the return value is garbage collected). The fourth case (spam9)
+which returns a const reference, in most of the cases will be 
+treated as a returning value, and it will follow the same
+allocation/deallocation process.
+</p>
+
+<H3><a name="Python_nn23"></a>30.3.10 C++ overloaded functions</H3>
+
+
+<p>
+C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
+if you have two functions like this:
+</p>
+
+<div class="code">
+<pre>
+void foo(int);
+void foo(char *c);
+</pre>
+</div>
+
+<p>
+You can use them in Python in a straightforward manner:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo(3)           # foo(int)
+&gt;&gt;&gt; foo("Hello")     # foo(char *c)
+</pre>
+</div>
+
+<p>
+Similarly, if you have a class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+    Foo(const Foo &amp;);
+    ...
+};
+</pre>
+</div>
+
+<p>
+you can write Python code like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = Foo()          # Create a Foo
+&gt;&gt;&gt; g = Foo(f)         # Copy f
+</pre>
+</div>
+
+<p>
+Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
+can't disambiguate. For example:
+</p>
+
+<div class="code">
+<pre>
+void spam(int);
+void spam(short);
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+void foo(Bar *b);
+void foo(Bar &amp;b);
+</pre>
+</div>
+
+<p>
+If declarations such as these appear, you will get a warning message like this:
+</p>
+
+<div class="shell">
+<pre>
+example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
+at example.i:11.
+</pre>
+</div>
+
+<p>
+To fix this, you either need to ignore or rename one of the methods.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(spam_short) spam(short);
+...
+void spam(int);    
+void spam(short);   // Accessed as spam_short
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+%ignore spam(short);
+...
+void spam(int);    
+void spam(short);   // Ignored
+</pre>
+</div>
+
+<p>
+SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
+declarations according to a set of type-precedence rules.    The order in which declarations appear
+in the input does not matter except in situations where ambiguity arises--in this case, the
+first declaration takes precedence.
+</p>
+
+<p>
+Please refer to the "SWIG and C++" chapter for more information about overloading. 
+</p>
+
+<H3><a name="Python_nn24"></a>30.3.11 C++ operators</H3>
+
+
+<p>
+Certain C++ overloaded operators can be handled automatically by SWIG.  For example,
+consider a class like this:
+</p>
+
+<div class="code">
+<pre>
+class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &amp;operator=(const Complex &amp;c);
+
+  Complex operator+=(const Complex &amp;c) const;
+  Complex operator+(const Complex &amp;c) const;
+  Complex operator-(const Complex &amp;c) const;
+  Complex operator*(const Complex &amp;c) const;
+  Complex operator-() const;
+  
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+</pre>
+</div>
+
+<p>
+When wrapped, it works like you expect:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; c = Complex(3,4)
+&gt;&gt;&gt; d = Complex(7,8)
+&gt;&gt;&gt; e = c + d
+&gt;&gt;&gt; e.re()
+10.0
+&gt;&gt;&gt; e.im()
+12.0
+&gt;&gt;&gt; c += d
+&gt;&gt;&gt; c.re()
+10.0
+&gt;&gt;&gt; c.im()
+12.0
+
+</pre>
+</div>
+
+<p>
+One restriction with operator overloading support is that SWIG is not
+able to fully handle operators that aren't defined as part of the class.
+For example, if you had code like this
+</p>
+
+<div class="code">
+<pre>
+class Complex {
+...
+friend Complex operator+(double, const Complex &amp;c);
+...
+};
+</pre>
+</div>
+
+<p>
+then SWIG ignores it and issues a warning.   You can still wrap the operator,
+but you may have to encapsulate it in a special function.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(Complex_add_dc) operator+(double, const Complex &amp;);
+</pre>
+</div>
+
+<p>
+There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
+Keep reading.
+</p>
+
+<p>
+Also, be aware that certain operators don't map cleanly to Python.  For instance,
+overloaded assignment operators don't map to Python semantics and will be ignored.
+</p>
+
+<H3><a name="Python_nn25"></a>30.3.12 C++ namespaces</H3>
+
+
+<p>
+SWIG is aware of C++ namespaces, but namespace names do not appear in
+the module nor do namespaces result in a module that is broken up into
+submodules or packages.  For example, if you have a file like this,
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+namespace foo {
+   int fact(int n);
+   struct Vector {
+       double x,y,z;
+   };
+};
+</pre>
+</div>
+
+<p>
+it works in Python as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; example.fact(3)
+6
+&gt;&gt;&gt; v = example.Vector()
+&gt;&gt;&gt; v.x = 3.4
+&gt;&gt;&gt; print v.y
+0.0
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
+For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(Bar_spam) Bar::spam;
+
+namespace Foo {
+    int spam();
+}
+
+namespace Bar {
+    int spam();
+}
+</pre>
+</div>
+
+<p>
+If you have more than one namespace and your want to keep their
+symbols separate, consider wrapping them as separate SWIG modules.
+For example, make the module name the same as the namespace and create
+extension modules for each namespace separately.  If your program
+utilizes thousands of small deeply nested namespaces each with
+identical symbol names, well, then you get what you deserve.
+</p>
+
+<H3><a name="Python_nn26"></a>30.3.13 C++ templates</H3>
+
+
+<p>
+C++ templates don't present a huge problem for SWIG.  However, in order
+to create wrappers, you have to tell SWIG to create wrappers for a particular
+template instantiation.  To do this, you use the <tt>%template</tt> directive.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include "pair.h"
+%}
+
+template&lt;class T1, class T2&gt;
+struct pair {
+   typedef T1 first_type;
+   typedef T2 second_type;
+   T1 first;
+   T2 second;
+   pair();
+   pair(const T1&amp;, const T2&amp;);
+  ~pair();
+};
+
+%template(pairii) pair&lt;int,int&gt;;
+</pre>
+</div>
+
+<p>
+In Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; p = example.pairii(3,4)
+&gt;&gt;&gt; p.first
+3
+&gt;&gt;&gt; p.second
+4
+</pre>
+</div>
+
+<p>
+Obviously, there is more to template wrapping than shown in this example.
+More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.  
+Some more complicated
+examples will appear later.
+</p>
+
+<H3><a name="Python_nn27"></a>30.3.14 C++ Smart Pointers</H3>
+
+
+<p>
+In certain C++ programs, it is common to use classes that have been wrapped by
+so-called "smart pointers."   Generally, this involves the use of a template class
+that implements <tt>operator-&gt;()</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T&gt; class SmartPtr {
+   ...
+   T *operator-&gt;();
+   ...
+}
+</pre>
+</div>
+
+<p>
+Then, if you have a class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int bar();
+};
+</pre>
+</div>
+
+<p>
+A smart pointer would be used in C++ as follows:
+</p>
+
+<div class="code">
+<pre>
+SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
+...
+p-&gt;x = 3;                        // Foo::x
+int y = p-&gt;bar();                // Foo::bar
+</pre>
+</div>
+
+<p>
+To wrap this in Python, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
+<tt>Foo</tt> object.  Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+...
+%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
+...
+</pre>
+</div>
+
+<p>
+Now, in Python, everything should just "work":
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; p = example.CreateFoo()          # Create a smart-pointer somehow
+&gt;&gt;&gt; p.x = 3                          # Foo::x
+&gt;&gt;&gt; p.bar()                          # Foo::bar
+</pre>
+</div>
+
+<p>
+If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
+simply use the <tt>__deref__()</tt> method.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = p.__deref__()     # Returns underlying Foo *
+</pre>
+</div>
+
+
+<H3><a name="Python_nn27a"></a>30.3.15 C++ Reference Counted Objects (ref/unref)</H3>
+
+
+<p>
+Another usual idiom in C++ is the use of reference counted
+objects. Consider for example:
+
+<div class="code">
+<pre>
+class RCObj  {
+  // implement the ref counting mechanism
+  int add_ref();
+  int del_ref();
+  int ref_count();
+
+public:
+  virtual ~RCObj() = 0;
+
+  int ref() const {
+    return add_ref();
+  }
+
+  int unref() const   {
+    if (ref_count() == 0 || del_ref() == 0 ) {
+	delete this;
+	return 0;
+      } 
+    return ref_count();
+  }
+};
+
+
+class A : RCObj {
+public:
+  A();
+  int foo();
+};
+
+
+class B {
+  A *_a;
+
+public:
+  B(A *a) : _a(a) { 
+    a-&gt;ref(); 
+  }
+
+  ~B() { 
+    a-&gt;unref(); 
+  }
+};
+
+int main() {
+  A *a  = new A();
+  a-&gt;ref();           // 'a' is ref here
+
+  B *b1 = new B(a);   // 'a' is ref here
+  if (1 + 1 == 2) {
+    B *b2 = new B(a); // 'a' is ref here
+    delete b2;        // 'a' is unref, but not deleted   
+  }
+
+  delete b1;          // 'a' is unref, but not deleted   
+  a-&gt;unref();         // 'a' is unref and deleted
+}
+</pre>
+</div>
+
+<p>
+In the example above, the 'A' class instance 'a' is a reference counted
+object, which can't be deleted arbitrarily since it is shared between
+the objects 'b1' and 'b2'. 'A' is derived from an Reference Counted
+Object 'RCObj', which implements the ref/unref idiom.
+</p>
+
+<p>
+To tell SWIG that 'RCObj' and all its derived classes are reference
+counted objects, you use the "ref" and "unref" features, or
+<tt>%ref</tt> and <tt>%unref</tt> directives (since 1.3.28). For example:
+</p>
+
+
+<div class="code">
+<pre>
+%module example
+...
+
+%feature("ref")   RCObj "$this-&gt;ref();"
+%feature("unref") RCObj "$this-&gt;unref();"
+
+%include "rcobj.h"
+%include "A.h"
+...
+</pre>
+</div>
+
+or, using the directive form:
+
+
+<div class="code">
+<pre>
+%module example
+...
+
+%ref   RCObj "$this-&gt;ref();"
+%unref RCObj "$this-&gt;unref();"
+
+%include "rcobj.h"
+%include "A.h"
+...
+</pre>
+</div>
+
+
+
+<p>
+where the code passed to the "ref" and "unref" features will be
+executed as needed whenever a new object is passed to python, or when
+python tries to release the shadow object instance, respectively. 
+</p>
+
+<p> 
+In the python side, the use of a reference counted object is not
+different than any other regular instance:
+</p>
+
+<div class="targetlang">
+<pre>
+def create_A():
+  a = A()         # SWIG ref 'a' (new object is passed to python)
+  b1 = B(a)       # C++  ref 'a'
+  if 1 + 1 == 2:
+     b2 = B(a)    # C++ ref 'a'
+  return a        # 'b1' and 'b2' are released, C++ unref 'a' twice
+
+a = create_A()   
+exit              # 'a' is released, SWIG unref 'a'
+</pre>
+</div>
+
+<p>
+Note that the user doesn't explicitly need to call 'a-&gt;ref()' nor 'a-&gt;unref()'
+(as neither 'delete a'). Instead, SWIG take cares of executing the "ref"
+and "unref" codes as needed.  If the user doesn't specify the
+"ref/unref" features, SWIG will produce a code equivalent to define
+them as:
+</p>
+
+<div class="code">
+<pre>
+%feature("ref")   ""
+%feature("unref") "delete $this;"
+</pre>
+</div>
+
+<p>
+In other words, SWIG will not do anything special when a new object
+is passed to python, and it will always 'delete' the object when
+python releases the proxy instance.
+</p>
+
+
+<H2><a name="Python_nn28"></a>30.4 Further details on the Python class interface</H2>
+
+
+<p>
+In the previous section, a high-level view of Python wrapping was
+presented.  A key component of this wrapping is that structures and
+classes are wrapped by Python proxy classes.  This provides a very
+natural Python interface and allows SWIG to support a number of
+advanced features such as operator overloading.   However, a number
+of low-level details were omitted.  This section provides a brief overview
+of how the proxy classes work.
+</p>
+
+<H3><a name="Python_nn29"></a>30.4.1 Proxy classes</H3>
+
+
+<p>
+In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
+details of low-level structure and class wrapping are described.  To summarize those chapters, if you
+have a class like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int spam(int);
+     ...
+</pre>
+</div>
+
+<p>
+then SWIG transforms it into a set of low-level procedural wrappers. For example:
+</p>
+
+<div class="code">
+<pre>
+Foo *new_Foo() {
+    return new Foo();
+}
+void delete_Foo(Foo *f) {
+    delete f;
+}
+int Foo_x_get(Foo *f) {
+    return f-&gt;x;
+}
+void Foo_x_set(Foo *f, int value) {
+    f-&gt;x = value;
+}
+int Foo_spam(Foo *f, int arg1) {
+    return f-&gt;spam(arg1);
+}
+</pre>
+</div>
+
+<p>
+These wrappers can be found in the low-level extension module (e.g., <tt>_example</tt>).
+</p>
+
+<p>
+Using these wrappers, SWIG generates a high-level Python proxy class (also known as a shadow class) like this (shown 
+for Python 2.2):
+</p>
+
+<div class="targetlang">
+<pre>
+import _example
+
+class Foo(object):
+     def __init__(self):
+         self.this = _example.new_Foo()
+         self.thisown = 1
+     def __del__(self):
+         if self.thisown:
+               _example.delete_Foo(self.this)
+     def spam(self,arg1):
+         return _example.Foo_spam(self.this,arg1)
+     x = property(_example.Foo_x_get, _example.Foo_x_set)
+</pre>
+</div>
+
+<p>
+This class merely holds a pointer to the underlying C++ object (<tt>.this</tt>) and dispatches methods and 
+member variable access to that object using the low-level accessor functions.   From a user's point of
+view, it makes the class work normally:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = example.Foo()
+&gt;&gt;&gt; f.x = 3
+&gt;&gt;&gt; y = f.spam(5)
+</pre>
+</div>
+
+<p>
+The fact that the class has been wrapped by a real Python class offers certain advantages.  For instance,
+you can attach new Python methods to the class and you can even inherit from it (something not supported
+by Python built-in types until Python 2.2).
+</p>
+
+<H3><a name="Python_nn30"></a>30.4.2 Memory management</H3>
+
+
+<p>
+Associated with proxy object, is an ownership flag <tt>.thisown</tt>   The value of this
+flag determines who is responsible for deleting the underlying C++ object.   If set to 1,
+the Python interpreter will destroy the C++ object when the proxy class is 
+garbage collected.   If set to 0 (or if the attribute is missing), then the destruction
+of the proxy class has no effect on the C++ object.
+</p>
+
+<p>
+When an object is created by a constructor or returned by value, Python automatically takes
+ownership of the result.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+    Foo bar();
+};
+</pre>
+</div>
+
+<p>
+In Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = Foo()
+&gt;&gt;&gt; f.thisown
+1
+&gt;&gt;&gt; g = f.bar()
+&gt;&gt;&gt; g.thisown
+1
+</pre>
+</div>
+
+<p>
+On the other hand, when pointers are returned to Python, there is often no way to know where
+they came from.  Therefore, the ownership is set to zero.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    ...
+    Foo *spam();
+    ...
+};
+</pre>
+</div>
+
+<br>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = Foo()
+&gt;&gt;&gt; s = f.spam()
+&gt;&gt;&gt; print s.thisown
+0
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+This behavior is especially important for classes that act as
+containers.  For example, if a method returns a pointer to an object
+that is contained inside another object, you definitely don't want
+Python to assume ownership and destroy it!
+</p>
+
+<p>
+A good way to indicate that ownership should be set for a returned pointer
+is to use the <a href="Library.html#Library_nn11">%newobject directive</a>.
+</p>
+
+<p>
+Related to containers, ownership issues can arise whenever an object is assigned to a member
+or global variable.  For example, consider this interface:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+struct Foo {
+    int  value;
+    Foo  *next;
+};
+
+Foo *head = 0;
+</pre>
+</div>
+
+<p>
+When wrapped in Python, careful observation will reveal that ownership changes whenever an object
+is assigned to a global variable.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = example.Foo()
+&gt;&gt;&gt; f.thisown
+1
+&gt;&gt;&gt; example.cvar.head = f           
+&gt;&gt;&gt; f.thisown
+0
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+In this case, C is now holding a reference to the object---you probably don't want Python to destroy it.
+Similarly, this occurs for members.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = example.Foo()
+&gt;&gt;&gt; g = example.Foo()
+&gt;&gt;&gt; f.thisown
+1
+&gt;&gt;&gt; g.thisown
+1
+&gt;&gt;&gt; f.next = g
+&gt;&gt;&gt; g.thisown
+0
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+For the most part, memory management issues remain hidden.  However,
+there are occasionally situations where you might have to manually
+change the ownership of an object.  For instance, consider code like this:
+</p>
+
+<div class="code">
+<pre>
+class Node {
+   Object *value;
+public:
+   void set_value(Object *v) { value = v; }
+   ...
+};
+</pre>
+</div>
+
+<p>
+Now, consider the following Python code:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; v = Object()           # Create an object
+&gt;&gt;&gt; n = Node()             # Create a node
+&gt;&gt;&gt; n.set_value(v)         # Set value
+&gt;&gt;&gt; v.thisown
+1
+&gt;&gt;&gt; del v
+</pre>
+</div>
+
+<p>
+In this case, the object <tt>n</tt> is holding a reference to
+<tt>v</tt> internally.  However, SWIG has no way to know that this
+has occurred.  Therefore, Python still thinks that it has ownership of the
+object.  Should the proxy object be destroyed, then the C++ destructor
+will be invoked and <tt>n</tt> will be holding a stale-pointer.  If
+you're lucky, you will only get a segmentation fault.
+</p>
+
+<p>
+To work around this, it is always possible to flip the ownership flag. For example,
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; v.thisown = 0
+</pre>
+</div>
+
+<p>
+It is also possible to deal with situations like this using
+typemaps--an advanced topic discussed later.
+</p>
+
+<H3><a name="Python_nn31"></a>30.4.3 Python 2.2 and classic classes</H3>
+
+
+<p>
+SWIG makes every attempt to preserve backwards compatibility with
+older versions of Python to the extent that it is possible.  However,
+in Python-2.2, an entirely new type of class system was introduced.
+This new-style class system offers many enhancements including static
+member functions, properties (managed attributes), and class methods.
+Details about all of these changes can be found on <a
+href="//www.python.org">www.python.org</a> and is not repeated here.
+</p>
+
+<p>
+To address differences between Python versions, SWIG currently emits
+dual-mode proxy class wrappers.  In Python-2.2 and newer releases,
+these wrappers encapsulate C++ objects in new-style classes that take
+advantage of new features (static methods and properties).  However,
+if these very same wrappers are imported into an older version of Python, 
+old-style classes are used instead.
+</p>
+
+<p>
+This dual-nature of the wrapper code means that you can create extension
+modules with SWIG and those modules will work with all versions of Python
+ranging from Python-1.4 to the very latest release.  Moreover, the wrappers take
+advantage of Python-2.2 features when available.
+</p>
+
+<p>
+For the most part, the interface presented to users is the same regardless
+of what version of Python is used.  The only incompatibility lies in the handling
+of static member functions.  In Python-2.2, they can be accessed via the
+class itself.  In Python-2.1 and earlier, they have to be accessed as a global
+function or through an instance (see the earlier section).
+</p>
+
+<H2><a name="directors"></a>30.5 Cross language polymorphism</H2>
+
+
+<p>
+Proxy classes provide a more natural, object-oriented way to access
+extension classes. As described above, each proxy instance has an
+associated C++ instance, and method calls to the proxy are passed to the
+C++ instance transparently via C wrapper functions.
+</p>
+
+<p>
+This arrangement is asymmetric in the sense that no corresponding
+mechanism exists to pass method calls down the inheritance chain from
+C++ to Python. In particular, if a C++ class has been extended in Python
+(by extending the proxy class), these extensions will not be visible
+from C++ code. Virtual method calls from C++ are thus not able access
+the lowest implementation in the inheritance chain.
+</p>
+
+<p>
+Changes have been made to SWIG 1.3.18 to address this problem and
+make the relationship between C++ classes and proxy classes more
+symmetric. To achieve this goal, new classes called directors are
+introduced at the bottom of the C++ inheritance chain. The job of the
+directors is to route method calls correctly, either to C++
+implementations higher in the inheritance chain or to Python
+implementations lower in the inheritance chain. The upshot is that C++
+classes can be extended in Python and from C++ these extensions look
+exactly like native C++ classes. Neither C++ code nor Python code needs
+to know where a particular method is implemented: the combination of
+proxy classes, director classes, and C wrapper functions takes care of
+all the cross-language method routing transparently.
+</p>
+
+<H3><a name="Python_nn33"></a>30.5.1 Enabling directors</H3>
+
+
+<p>
+The director feature is disabled by default.  To use directors you
+must make two changes to the interface file.  First, add the "directors"
+option to the %module directive, like this:
+</p>
+
+<div class="code">
+<pre>
+%module(directors="1") modulename
+</pre>
+</div>
+
+<p>
+Without this option no director code will be generated.  Second, you
+must use the %feature("director") directive to tell SWIG which classes 
+and methods should get directors.  The %feature directive can be applied 
+globally, to specific classes, and to specific methods, like this:
+</p>
+
+<div class="code">
+<pre>
+// generate directors for all classes that have virtual methods
+%feature("director");         
+
+// generate directors for all virtual methods in class Foo
+%feature("director") Foo;      
+
+// generate a director for just Foo::bar()
+%feature("director") Foo::bar; 
+</pre>
+</div>
+
+<p>
+You can use the %feature("nodirector") directive to turn off
+directors for specific classes or methods.  So for example,
+</p>
+
+<div class="code">
+<pre>
+%feature("director") Foo;
+%feature("nodirector") Foo::bar;
+</pre>
+</div>
+
+<p>
+will generate directors for all virtual methods of class Foo except
+bar().  
+</p>
+
+<p>
+Directors can also be generated implicitly through inheritance. 
+In the following, class Bar will get a director class that handles
+the methods one() and two() (but not three()):
+</p>
+
+<div class="code">
+<pre>
+%feature("director") Foo;
+class Foo {
+public:
+    Foo(int foo);
+    virtual void one();
+    virtual void two();
+};
+
+class Bar: public Foo {
+public:
+    virtual void three();
+};
+</pre>
+</div>
+
+<p>
+then at the python side you can define
+</p>
+
+<div class="targetlang">
+<pre>
+import mymodule
+
+class MyFoo(mymodule.Foo):
+  def __init__(self, foo):
+     mymodule.Foo(self, foo)  
+
+  def one(self):
+     print "one from python"
+</pre>
+</div>
+
+
+<H3><a name="Python_nn34"></a>30.5.2 Director classes</H3>
+
+
+ 
+
+
+<p>
+For each class that has directors enabled, SWIG generates a new class
+that derives from both the class in question and a special
+<tt>Swig::Director</tt> class. These new classes, referred to as director
+classes, can be loosely thought of as the C++ equivalent of the Python
+proxy classes. The director classes store a pointer to their underlying
+Python object and handle various issues related to object ownership.
+Indeed, this is quite similar to the "this" and "thisown" members of the
+Python proxy classes.
+</p>
+
+<p>
+For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the
+original C++ class as the director's base class. By default, a director
+class extends all virtual methods in the inheritance chain of its base
+class (see the preceding section for how to modify this behavior).
+Thus all virtual method calls, whether they originate in C++ or in
+Python via proxy classes, eventually end up in at the implementation in
+the director class. The job of the director methods is to route these
+method calls to the appropriate place in the inheritance chain. By
+"appropriate place" we mean the method that would have been called if
+the C++ base class and its extensions in Python were seamlessly
+integrated. That seamless integration is exactly what the director
+classes provide, transparently skipping over all the messy extension API
+glue that binds the two languages together.
+</p>
+
+<p>
+In reality, the "appropriate place" is one of only two possibilities:
+C++ or Python. Once this decision is made, the rest is fairly easy. If
+the correct implementation is in C++, then the lowest implementation of
+the method in the C++ inheritance chain is called explicitly. If the
+correct implementation is in Python, the Python API is used to call the
+method of the underlying Python object (after which the usual virtual
+method resolution in Python automatically finds the right
+implementation).
+</p>
+
+<p>
+Now how does the director decide which language should handle the method call?
+The basic rule is to handle the method in Python, unless there's a good
+reason not to. The reason for this is simple: Python has the most
+"extended" implementation of the method. This assertion is guaranteed,
+since at a minimum the Python proxy class implements the method. If the
+method in question has been extended by a class derived from the proxy
+class, that extended implementation will execute exactly as it should.
+If not, the proxy class will route the method call into a C wrapper
+function, expecting that the method will be resolved in C++. The wrapper
+will call the virtual method of the C++ instance, and since the director
+extends this the call will end up right back in the director method. Now
+comes the "good reason not to" part. If the director method were to blindly
+call the Python method again, it would get stuck in an infinite loop. We avoid this
+situation by adding special code to the C wrapper function that tells
+the director method to not do this. The C wrapper function compares the
+pointer to the Python object that called the wrapper function to the
+pointer stored by the director. If these are the same, then the C
+wrapper function tells the director to resolve the method by calling up
+the C++ inheritance chain, preventing an infinite loop.
+</p>
+
+<p>
+One more point needs to be made about the relationship between director
+classes and proxy classes. When a proxy class instance is created in
+Python, SWIG creates an instance of the original C++ class and assigns
+it to <tt>.this</tt>. This is exactly what happens without directors and
+is true even if directors are enabled for the particular class in
+question. When a class <i>derived</i> from a proxy class is created,
+however, SWIG then creates an instance of the corresponding C++ director
+class. The reason for this difference is that user-defined subclasses
+may override or extend methods of the original class, so the director
+class is needed to route calls to these methods correctly. For
+unmodified proxy classes, all methods are ultimately implemented in C++
+so there is no need for the extra overhead involved with routing the
+calls through Python.
+</p>
+
+<H3><a name="Python_nn35"></a>30.5.3 Ownership and object destruction</H3>
+
+
+<p>
+Memory management issues are slightly more complicated with directors
+than for proxy classes alone. Python instances hold a pointer to the
+associated C++ director object, and the director in turn holds a pointer
+back to the Python object. By default, proxy classes own their C++
+director object and take care of deleting it when they are garbage
+collected.
+</p>
+
+<p>
+This relationship can be reversed by calling the special
+<tt>__disown__()</tt> method of the proxy class. After calling this
+method, the <tt>.thisown</tt> flag is set to zero, and the director
+class increments the reference count of the Python object. When the
+director class is deleted it decrements the reference count. Assuming no
+outstanding references to the Python object remain, the Python object
+will be destroyed at the same time. This is a good thing, since
+directors and proxies refer to each other and so must be created and
+destroyed together. Destroying one without destroying the other will
+likely cause your program to segfault.
+</p>
+
+<p>
+To help ensure that no references to the Python object remain after
+calling <tt>__disown__()</tt>, this method returns a weak reference to
+the Python object. Weak references are only available in Python versions
+2.1 and higher, so for older versions you must explicitly delete all
+references. Here is an example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    ...
+};
+class FooContainer {
+public:
+    void addFoo(Foo *);
+    ...
+};
+</pre>
+</div>
+
+<br>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; c = FooContainer()
+&gt;&gt;&gt; a = Foo().__disown()__
+&gt;&gt;&gt; c.addFoo(a)
+&gt;&gt;&gt; b = Foo()
+&gt;&gt;&gt; b = b.__disown()__
+&gt;&gt;&gt; c.addFoo(b)
+&gt;&gt;&gt; c.addFoo(Foo().__disown()__)
+</pre>
+</div>
+
+<p>
+In this example, we are assuming that FooContainer will take care of
+deleting all the Foo pointers it contains at some point.  Note that no hard
+references to the Foo objects remain in Python.
+</p>
+
+<H3><a name="Python_nn36"></a>30.5.4 Exception unrolling</H3>
+
+
+<p>
+With directors routing method calls to Python, and proxies routing them
+to C++, the handling of exceptions is an important concern. By default, the
+directors ignore exceptions that occur during method calls that are
+resolved in Python. To handle such exceptions correctly, it is necessary
+to temporarily translate them into C++ exceptions. This can be done with
+the %feature("director:except") directive. The following code should
+suffice in most cases:
+</p>
+
+<div class="code">
+<pre>
+%feature("director:except") {
+    if ($error != NULL) {
+        throw Swig::DirectorMethodException();
+    }
+}
+</pre>
+</div>
+
+<p>
+This code will check the Python error state after each method call from
+a director into Python, and throw a C++ exception if an error occurred.
+This exception can be caught in C++ to implement an error handler.
+Currently no information about the Python error is stored in the
+Swig::DirectorMethodException object, but this will likely change in
+the future.
+</p>
+
+<p>
+It may be the case that a method call originates in Python, travels up
+to C++ through a proxy class, and then back into Python via a director
+method. If an exception occurs in Python at this point, it would be nice
+for that exception to find its way back to the original caller. This can
+be done by combining a normal %exception directive with the
+<tt>director:except</tt> handler shown above. Here is an example of a
+suitable exception handler:
+</p>
+
+<div class="code">
+<pre>
+%exception {
+    try { $action }
+    catch (Swig::DirectorException &amp;e) { SWIG_fail; }
+}
+</pre>
+</div>
+
+<p>
+The class Swig::DirectorException used in this example is actually a
+base class of Swig::DirectorMethodException, so it will trap this
+exception. Because the Python error state is still set when
+Swig::DirectorMethodException is thrown, Python will register the
+exception as soon as the C wrapper function returns.
+</p>
+
+<H3><a name="Python_nn37"></a>30.5.5 Overhead and code bloat</H3>
+
+
+<p>
+Enabling directors for a class will generate a new director method for
+every virtual method in the class' inheritance chain. This alone can
+generate a lot of code bloat for large hierarchies. Method arguments
+that require complex conversions to and from target language types can
+result in large director methods. For this reason it is recommended that
+you selectively enable directors only for specific classes that are
+likely to be extended in Python and used in C++.
+</p>
+
+<p>
+Compared to classes that do not use directors, the call routing in the
+director methods does add some overhead. In particular, at least one
+dynamic cast and one extra function call occurs per method call from
+Python. Relative to the speed of Python execution this is probably
+completely negligible. For worst case routing, a method call that
+ultimately resolves in C++ may take one extra detour through Python in
+order to ensure that the method does not have an extended Python
+implementation. This could result in a noticeable overhead in some cases.
+</p>
+
+<p>
+Although directors make it natural to mix native C++ objects with Python
+objects (as director objects) via a common base class pointer, one
+should be aware of the obvious fact that method calls to Python objects
+will be much slower than calls to C++ objects. This situation can be
+optimized by selectively enabling director methods (using the %feature
+directive) for only those methods that are likely to be extended in
+Python.
+</p>
+
+<H3><a name="Python_nn38"></a>30.5.6 Typemaps</H3>
+
+
+<p>
+Typemaps for input and output of most of the basic types from director
+classes have been written. These are roughly the reverse of the usual
+input and output typemaps used by the wrapper code. The typemap
+operation names are 'directorin', 'directorout', and 'directorargout'.
+The director code does not currently use any of the other kinds of typemaps.
+It is not clear at this point which kinds are appropriate and
+need to be supported.
+</p>
+
+
+<H3><a name="Python_nn39"></a>30.5.7 Miscellaneous</H3>
+
+
+<p>
+Director typemaps for STL classes are in place, and hence you should
+be able to use std::vector, std::string, etc., as you would any other type.
+</p>
+
+<p>
+<b>Note:</b> The director typemaps for return types based in const
+references, such as 
+
+<div class="code">
+<pre>
+class Foo {
+&hellip;
+    virtual const int&amp; bar();
+&hellip;
+};
+</pre>
+</div>
+
+<p>
+will work only for simple call scenarios. Usually the resulting code
+is neither thread or reentrant safe. Hence, the user is advised to
+avoid returning const references in director methods. For example,
+the user could modify the method interface to use lvalue return
+types, wherever possible, for example
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+&hellip;
+    virtual int bar();
+&hellip;
+};
+</pre>
+</div>
+
+<p>
+If that is not possible, the user should avoid enabling the
+director feature for reentrant, recursive or threaded member
+methods that return const references.
+</p>
+
+
+<H2><a name="Python_nn40"></a>30.6 Common customization features</H2>
+
+
+<p>
+The last section presented the absolute basics of C/C++ wrapping. If
+you do nothing but feed SWIG a header file, you will get an interface
+that mimics the behavior described.  However, sometimes this isn't
+enough to produce a nice module.  Certain types of functionality might
+be missing or the interface to certain functions might be awkward.
+This section describes some common SWIG features that are used to
+improve your the interface to an extension module.
+</p>
+
+<H3><a name="Python_nn41"></a>30.6.1 C/C++ helper functions</H3>
+
+
+<p>
+Sometimes when you create a module, it is missing certain bits of functionality. For
+example, if you had a function like this
+</p>
+
+<div class="code">
+<pre>
+void set_transform(Image *im, double m[4][4]);
+</pre>
+</div>
+
+<p>
+it would be accessible from Python, but there may be no easy way to call it.
+For example, you might get errors like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = [
+...   [1,0,0,0],
+...   [0,1,0,0],
+...   [0,0,1,0],
+...   [0,0,0,1]]
+&gt;&gt;&gt; set_transform(im,a)
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+TypeError: Type error. Expected _p_a_4__double
+</pre>
+</div>
+
+<p>
+The problem here is that there is no easy way to construct and manipulate a suitable
+<tt>double [4][4]</tt> value to use.   To fix this, you can write some extra C helper
+functions.  Just use the <tt>%inline</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
+double (*new_mat44())[4] {
+   return (double (*)[4]) malloc(16*sizeof(double));
+}
+void free_mat44(double (*x)[4]) {
+   free(x);
+}
+void mat44_set(double x[4][4], int i, int j, double v) {
+   x[i][j] = v;
+}
+double mat44_get(double x[4][4], int i, int j) {
+   return x[i][j];
+}
+%}
+</pre>
+</div>
+
+<p>
+From Python, you could then write code like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = new_mat44()
+&gt;&gt;&gt; mat44_set(a,0,0,1.0)
+&gt;&gt;&gt; mat44_set(a,1,1,1.0)
+&gt;&gt;&gt; mat44_set(a,2,2,1.0)
+...
+&gt;&gt;&gt; set_transform(im,a)
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Admittedly, this is not the most elegant looking approach.  However, it works and it wasn't too
+hard to implement.  It is possible to clean this up using Python code, typemaps, and other
+customization features as covered in later sections.
+</p>
+
+<H3><a name="Python_nn42"></a>30.6.2 Adding additional Python code</H3>
+
+
+<p>
+If writing support code in C isn't enough, it is also possible to write code in
+Python.  This code gets inserted in to the <tt>.py</tt> file created by SWIG.   One
+use of Python code might be to supply a high-level interface to certain functions.
+For example:
+</p>
+
+<div class="code">
+<pre>
+void set_transform(Image *im, double x[4][4]);
+
+...
+/* Rewrite the high level interface to set_transform */
+%pythoncode %{
+def set_transform(im,x):
+   a = new_mat44()
+   for i in range(4):
+       for j in range(4):
+           mat44_set(a,i,j,x[i][j])
+   _example.set_transform(im,a)
+   free_mat44(a)
+%}
+</pre>
+</div>
+
+<p>
+In this example, <tt>set_transform()</tt> provides a high-level Python interface built on top of
+low-level helper functions.  For example, this code now seems to work:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = [
+...   [1,0,0,0],
+...   [0,1,0,0],
+...   [0,0,1,0],
+...   [0,0,0,1]]
+&gt;&gt;&gt; set_transform(im,a)
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Admittedly, this whole scheme for wrapping the two-dimension array
+argument is rather ad-hoc. Besides, shouldn't a Python list or a
+Numeric Python array just work normally?  We'll get to those examples
+soon enough.  For now, think of this example as an illustration of
+what can be done without having to rely on any of the more advanced
+customization features.
+</p>
+
+<p>Sometimes you may want to replace or modify the wrapper function
+that SWIG creates in the proxy <tt>.py</tt> file.  The Python module
+in SWIG provides some features that enable you do do this.  First, to
+entirely replace a proxy function you can use
+<tt>%feature("shadow")</tt>.  For example:</p>
+
+<div class="code">
+<pre>
+%module example
+
+// Rewrite bar() python code
+
+%feature("shadow") Foo::bar(int) %{
+def bar(*args):
+    #do something before
+    $action
+    #do something after
+%}
+    
+class Foo {
+public:
+    int bar(int x);
+}
+</pre>
+</div>
+
+<p> where <tt>$action</tt> will be replaced by the call to
+the C/C++ proper method. 
+</p>
+
+<p>
+Often the proxy function created by SWIG is fine, but you simply want
+to add code to it without touching the rest of the generated function
+body.  For these cases SWIG provides the <tt>pythonprepend</tt> and
+<tt>pythonappend</tt> features which do exactly as their names suggest.  The
+<tt>pythonprepend</tt> feature will insert its value at the beginning of the
+proxy function, and <tt>pythonappend</tt> will insert code at the end of the
+proxy, just before the return statement.
+</p>
+
+
+<div class="code">
+<pre>
+%module example
+
+// Add python code to bar() 
+
+%feature("pythonprepend") Foo::bar(int) %{
+   #do something before C++ call
+%}
+
+%feature("pythonappend") Foo::bar(int) %{
+   #do something after C++ call
+%}
+
+    
+class Foo {
+public:
+    int bar(int x);
+}
+</pre>
+</div>
+
+<p>
+Notes: Usually the <tt>pythonappend</tt> and <tt>pythonprepend</tt>
+features are safer to use than the <tt>shadow</tt> feature. Also, from
+SWIG version 1.3.28 you can use the directive forms
+<tt>%pythonappend</tt>  and <tt>%pythonprepend</tt> as follows:</p>
+
+
+<div class="code">
+<pre>
+%module example
+
+// Add python code to bar() 
+
+%pythonprepend Foo::bar(int) %{
+   #do something before C++ call
+%}
+
+%pythonappend Foo::bar(int) %{
+   #do something after C++ call
+%}
+
+    
+class Foo {
+public:
+    int bar(int x);
+}
+</pre>
+</div>
+
+
+
+
+<H3><a name="Python_nn43"></a>30.6.3 Class extension with %extend</H3>
+
+
+<p>
+One of the more interesting features of SWIG is that it can extend
+structures and classes with new methods--at least in the Python interface.
+Here is a simple example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include "someheader.h"
+%}
+
+struct Vector {
+   double x,y,z;
+};
+
+%extend Vector {
+   char *__str__() {
+       static char tmp[1024];
+       sprintf(tmp,"Vector(%g,%g,%g)", $self-&gt;x,$self-&gt;y,$self-&gt;z);
+       return tmp;
+   }
+   Vector(double x, double y, double z) {
+       Vector *v = (Vector *) malloc(sizeof(Vector));
+       v-&gt;x = x;
+       v-&gt;y = y;
+       v-&gt;z = z;
+       return v;
+   }
+};
+</pre>
+</div>
+
+<p>
+Now, in Python
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; v = example.Vector(2,3,4)
+&gt;&gt;&gt; print v
+Vector(2,3,4)
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+<tt>%extend</tt> can be used for many more tasks than this.  
+For example, if you wanted to overload a Python operator, you might do this:
+</p>
+
+<div class="code">
+<pre>
+%extend Vector {
+    Vector __add__(Vector *other) {
+         Vector v;
+         v.x = $self-&gt;x + other-&gt;x;
+         v.y = $self-&gt;y + other-&gt;y;
+         v.z = $self-&gt;z + other-&gt;z;
+         return v;
+    }
+};
+</pre>
+</div>
+
+<p>
+Use it like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; v = example.Vector(2,3,4)
+&gt;&gt;&gt; w = example.Vector(10,11,12)
+&gt;&gt;&gt; print v+w
+Vector(12,14,16)
+&gt;&gt;&gt; 
+</pre>
+</div>
+
+<p>
+<tt>%extend</tt> works with both C and C++ code.  It does not modify the underlying object
+in any way---the extensions only show up in the Python interface.
+</p>
+
+<H3><a name="Python_nn44"></a>30.6.4 Exception handling with %exception</H3>
+
+
+<p>
+If a C or C++ function throws an error, you may want to convert that error into a Python
+exception. To do this, you can use the <tt>%exception</tt> directive.  <tt>%exception</tt>
+simply lets you rewrite part of the generated wrapper code to include an error check.
+</p>
+
+<p>
+In C, a function often indicates an error by returning a status code (a negative number
+or a NULL pointer perhaps).  Here is a simple example of how you might handle that:
+</p>
+
+<div class="code">
+<pre>
+%exception malloc {
+  $action
+  if (!result) {
+     PyErr_SetString(PyExc_MemoryError,"Not enough memory");
+     return NULL;
+  }
+}
+void *malloc(size_t nbytes);
+</pre>
+</div>
+
+<p>
+In Python,
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = example.malloc(2000000000)
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+MemoryError: Not enough memory
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+If a library provides some kind of general error handling framework, you can also use
+that.  For example:
+</p>
+
+<div class="code">
+<pre>
+%exception {
+   $action
+   if (err_occurred()) {
+      PyErr_SetString(PyExc_RuntimeError, err_message());
+      return NULL;
+   }
+}
+</pre>
+</div>
+
+<p>
+No declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
+</p>
+
+<p>
+C++ exceptions are also easy to handle.  For example, you can write code like this:
+</p>
+
+<div class="code">
+<pre>
+%exception getitem {
+   try {
+      $action
+   } catch (std::out_of_range &amp;e) {
+      PyErr_SetString(PyExc_IndexError, const_cast&lt;char*&gt;(e.what()));
+      return NULL;
+   }
+}
+
+class Base {
+public:
+     Foo *getitem(int index);      // Exception handled added
+     ...
+};
+</pre>
+</div>
+
+<p>
+When raising a Python exception from C, use the <tt>PyErr_SetString()</tt>
+function as shown above.  The following exception types can be used as the first argument.
+</p>
+
+<div class="code">
+<pre>
+PyExc_ArithmeticError
+PyExc_AssertionError
+PyExc_AttributeError
+PyExc_EnvironmentError
+PyExc_EOFError
+PyExc_Exception
+PyExc_FloatingPointError
+PyExc_ImportError
+PyExc_IndexError
+PyExc_IOError
+PyExc_KeyError
+PyExc_KeyboardInterrupt
+PyExc_LookupError
+PyExc_MemoryError
+PyExc_NameError
+PyExc_NotImplementedError
+PyExc_OSError
+PyExc_OverflowError
+PyExc_RuntimeError
+PyExc_StandardError
+PyExc_SyntaxError
+PyExc_SystemError
+PyExc_TypeError
+PyExc_UnicodeError
+PyExc_ValueError
+PyExc_ZeroDivisionError
+</pre>
+</div>
+
+<p>
+The language-independent <tt>exception.i</tt> library file can also be used
+to raise exceptions.  See the <a href="Library.html#Library">SWIG Library</a> chapter.
+</p>
+
+<H2><a name="Python_nn45"></a>30.7 Tips and techniques</H2>
+
+
+<p>
+Although SWIG is largely automatic, there are certain types of wrapping problems that
+require additional user input.    Examples include dealing with output parameters,
+strings, binary data, and arrays.   This chapter discusses the common techniques for
+solving these problems.
+</p>
+
+<H3><a name="Python_nn46"></a>30.7.1 Input and output parameters</H3>
+
+
+<p>
+A common problem in some C programs is handling parameters passed as simple pointers.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+void add(int x, int y, int *result) {
+   *result = x + y;
+}
+</pre>
+</div>
+
+<p>
+or perhaps
+</p>
+
+<div class="code">
+<pre>
+int sub(int *x, int *y) {
+   return *x-*y;
+}
+</pre>
+</div>
+
+<p>
+The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+void add(int, int, int *OUTPUT);
+int  sub(int *INPUT, int *INPUT);
+</pre>
+</div>
+
+<p>
+In Python, this allows you to pass simple values.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = add(3,4)
+&gt;&gt;&gt; print a
+7
+&gt;&gt;&gt; b = sub(7,4)
+&gt;&gt;&gt; print b
+3
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
+and how the <tt>OUTPUT</tt> parameter creates a return result.
+</p>
+
+<p>
+If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
+directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+%apply int *OUTPUT { int *result };
+%apply int *INPUT  { int *x, int *y};
+
+void add(int x, int y, int *result);
+int  sub(int *x, int *y);
+</pre>
+</div>
+
+<p>
+If a function mutates one of its parameters like this,
+</p>
+
+<div class="code">
+<pre>
+void negate(int *x) {
+   *x = -(*x);
+}
+</pre>
+</div>
+
+<p>
+you can use <tt>INOUT</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+%include "typemaps.i"
+...
+void negate(int *INOUT);
+</pre>
+</div>
+
+<p>
+In Python, a mutated parameter shows up as a return value.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = negate(3)
+&gt;&gt;&gt; print a
+-3
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Note: Since most primitive Python objects are immutable, it is not possible to
+perform in-place modification of a Python object passed as a parameter.
+</p>
+
+<p>
+The most common use of these special typemap rules is to handle functions that
+return more than one value.   For example, sometimes a function returns a result
+as well as a special error code:
+</p>
+
+<div class="code">
+<pre>
+/* send message, return number of bytes sent, along with success code */
+int send_message(char *text, int len, int *success);
+</pre>
+</div>
+
+<p>
+To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+%apply int *OUTPUT { int *success };
+...
+int send_message(char *text, int *success);
+</pre>
+</div>
+
+<p>
+When used in Python, the function will return multiple values.  
+</p>
+
+<div class="targetlang">
+<pre>
+bytes, success = send_message("Hello World")
+if not success:
+    print "Whoa!"
+else:
+    print "Sent", bytes
+</pre>
+</div>
+
+<p>
+Another common use of multiple return values are in query functions.  For example:
+</p>
+
+<div class="code">
+<pre>
+void get_dimensions(Matrix *m, int *rows, int *columns);
+</pre>
+</div>
+
+<p>
+To wrap this, you might use the following:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+%apply int *OUTPUT { int *rows, int *columns };
+...
+void get_dimensions(Matrix *m, int *rows, *columns);
+</pre>
+</div>
+
+<p>
+Now, in Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; r,c = get_dimensions(m)
+</pre>
+</div>
+
+<p>
+Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
+Writing a function like this
+</p>
+
+<div class="code">
+<pre>
+void foo(Bar *OUTPUT);
+</pre>
+</div>
+
+<p>
+may not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
+</p>
+
+<H3><a name="Python_nn47"></a>30.7.2 Simple pointers</H3>
+
+
+<p>
+If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> and you don't want to use
+<tt>typemaps.i</tt>, consider using the <tt>cpointer.i</tt> library file.    For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "cpointer.i"
+
+%inline %{
+extern void add(int x, int y, int *result);
+%}
+
+%pointer_functions(int, intp);
+</pre>
+</div>
+
+<p>
+The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create,
+destroy, copy, assign, and dereference a pointer.  In this case, the functions are as follows:
+</p>
+
+<div class="code">
+<pre>
+int  *new_intp();
+int  *copy_intp(int *x);
+void  delete_intp(int *x);
+void  intp_assign(int *x, int value);
+int   intp_value(int *x);
+</pre>
+</div>
+
+<p>
+In Python, you would use the functions like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; result = new_intp()
+&gt;&gt;&gt; print result
+_108fea8_p_int
+&gt;&gt;&gt; add(3,4,result)
+&gt;&gt;&gt; print intp_value(result)
+7
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+If you replace <tt>%pointer_functions()</tt> by <tt>%pointer_class(type,name)</tt>, the interface is more class-like.
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; result = intp()
+&gt;&gt;&gt; add(3,4,result)
+&gt;&gt;&gt; print result.value()
+7
+</pre>
+</div>
+
+<p>
+See the <a href="Library.html#Library">SWIG Library</a> chapter for further details.
+</p>
+
+<H3><a name="Python_nn48"></a>30.7.3 Unbounded C Arrays</H3>
+
+
+<p>
+Sometimes a C function expects an array to be passed as a pointer.  For example,
+</p>
+
+<div class="code">
+<pre>
+int sumitems(int *first, int nitems) {
+    int i, sum = 0;
+    for (i = 0; i &lt; nitems; i++) {
+        sum += first[i];
+    }
+    return sum;
+}
+</pre>
+</div>
+
+<p>
+To wrap this into Python, you need to pass an array pointer as the first argument. 
+A simple way to do this is to use the <tt>carrays.i</tt> library file.  For example:
+</p>
+
+<div class="code">
+<pre>
+%include "carrays.i"
+%array_class(int, intArray);
+</pre>
+</div>
+
+<p>
+The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
+can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
+For instance, you will be able to do this in Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = intArray(10000000)         # Array of 10-million integers
+&gt;&gt;&gt; for i in xrange(10000):        # Set some values
+...     a[i] = i
+&gt;&gt;&gt; sumitems(a,10000)
+49995000
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+The array "object" created by <tt>%array_class()</tt> does not
+encapsulate pointers inside a special array object.  In fact, there is
+no bounds checking or safety of any kind (just like in C).  Because of
+this, the arrays created by this library are extremely low-level
+indeed.  You can't iterate over them nor can you even query their
+length.  In fact, any valid memory address can be accessed if you want
+(negative indices, indices beyond the end of the array, etc.).
+Needless to say, this approach is not going to suit all applications.
+On the other hand, this low-level approach is extremely efficient and
+well suited for applications in which you need to create buffers,
+package binary data, etc.
+</p>
+
+<H3><a name="Python_nn49"></a>30.7.4 String handling</H3>
+
+
+<p>
+If a C function has an argument of <tt>char *</tt>, then a Python string
+can be passed as input.  For example:
+</p>
+
+<div class="code">
+<pre>
+// C
+void foo(char *s);
+</pre>
+</div>
+
+<div class="targetlang">
+<pre>
+# Python
+&gt;&gt;&gt; foo("Hello")
+</pre>
+</div>
+
+<p>
+When a Python string is passed as a parameter, the C function receives a pointer to the raw
+data contained in the string.  Since Python strings are immutable, it is illegal
+for your program to change the value.  In fact, doing so will probably crash the Python
+interpreter.
+</p>
+
+<p>
+If your program modifies the input parameter or uses it to return data, consider
+using the <tt>cstring.i</tt> library file described in the <a href="Library.html#Library">SWIG Library</a> chapter.
+</p>
+
+<p>
+When functions return a <tt>char *</tt>, it is assumed to be a NULL-terminated string. 
+Data is copied into a new Python string and returned.
+</p>
+
+<p>
+If your program needs to work with binary data, you can use a typemap
+to expand a Python string into a pointer/length argument pair.   As luck would have it, 
+just such a typemap is already defined. Just do this:
+</p>
+
+<div class="code">
+<pre>
+%apply (char *STRING, int LENGTH) { (char *data, int size) };
+...
+int parity(char *data, int size, int initial);
+</pre>
+</div>
+
+<p>
+Now in Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; parity("e\x09ffss\x00\x00\x01\nx", 0)
+</pre>
+</div>
+
+<p>
+If you need to return binary data, you might use the
+<tt>cstring.i</tt> library file.  The <tt>cdata.i</tt> library can
+also be used to extra binary data from arbitrary pointers.
+</p>
+
+<H3><a name="Python_nn50"></a>30.7.5 Arrays</H3>
+
+
+<H3><a name="Python_nn51"></a>30.7.6 String arrays</H3>
+
+
+<H3><a name="Python_nn52"></a>30.7.7 STL wrappers</H3>
+
+
+<H2><a name="Python_nn53"></a>30.8 Typemaps</H2>
+
+
+<p>
+This section describes how you can modify SWIG's default wrapping behavior
+for various C/C++ datatypes using the <tt>%typemap</tt> directive.   This
+is an advanced topic that assumes familiarity with the Python C API as well
+as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+</p>
+
+<p>
+Before proceeding, it should be stressed that typemaps are not a required 
+part of using SWIG---the default wrapping behavior is enough in most cases.
+Typemaps are only used if you want to change some aspect of the primitive
+C-Python interface or if you want to elevate your guru status.
+</p>
+
+<H3><a name="Python_nn54"></a>30.8.1 What is a typemap?</H3>
+
+
+<p>
+A typemap is nothing more than a code generation rule that is attached to 
+a specific C datatype.   For example, to convert integers from Python to C,
+you might define a typemap like this:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int {
+	$1 = (int) PyLong_AsLong($input);
+	printf("Received an integer : %d\n",$1);
+}
+%inline %{
+extern int fact(int n);
+%}
+</pre></div>
+
+<p>
+Typemaps are always associated with some specific aspect of code generation.
+In this case, the "in" method refers to the conversion of input arguments
+to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
+will be applied.  The supplied C code is used to convert values.  In this
+code a number of special variable prefaced by a <tt>$</tt> are used.  The
+<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
+The <tt>$input</tt> variable is the input object of type <tt>PyObject *</tt>.
+</p>
+
+<p>
+When this example is compiled into a Python module, it operates as follows:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; from example import *
+&gt;&gt;&gt; fact(6)
+Received an integer : 6
+720
+</pre></div>
+
+<p>
+In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
+You can refine this by supplying an optional parameter name.  For example:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int nonnegative {
+	$1 = (int) PyLong_AsLong($input);
+        if ($1 &lt; 0) {
+           PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value.");
+           return NULL;
+        }
+}
+%inline %{
+extern int fact(int nonnegative);
+%}
+</pre></div>
+
+<p>
+In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
+</p>
+
+<p>
+The application of a typemap to specific datatypes and argument names involves
+more than simple text-matching--typemaps are fully integrated into the
+SWIG C++ type-system.   When you define a typemap for <tt>int</tt>, that typemap
+applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
+the typemap system follows <tt>typedef</tt> declarations.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int n {
+	$1 = (int) PyLong_AsLong($input);
+	printf("n = %d\n",$1);
+}
+%inline %{
+typedef int Integer;
+extern int fact(Integer n);    // Above typemap is applied
+%}
+</pre>
+</div>
+
+<p>
+Typemaps can also be defined for groups of consecutive arguments.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (char *str, int len) {
+    $1 = PyString_AsString($input);
+    $2 = PyString_Size($input);
+};
+
+int count(char c, char *str, int len);
+</pre>
+</div>
+
+<p>
+When a multi-argument typemap is defined, the arguments are always handled as a single
+Python object.  This allows the function to be used like this (notice how the length
+parameter is omitted):
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; example.count('e','Hello World')
+1
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<H3><a name="Python_nn55"></a>30.8.2 Python typemaps</H3>
+
+
+<p>
+The previous section illustrated an "in" typemap for converting Python objects to C.
+A variety of different typemap methods are defined by the Python module.  For example,
+to convert a C integer back into a Python object, you might define an "out" typemap
+like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(out) int {
+    $result = PyInt_FromLong((long) $1);
+}
+</pre>
+</div>
+
+<p>
+A detailed list of available methods can be found in the "<a
+href="Typemaps.html#Typemaps">Typemaps</a>" chapter.  
+</p>
+
+<p>
+However, the best source of typemap information (and examples) is
+probably the Python module itself.  In fact, all of SWIG's default
+type handling is defined by typemaps.  You can view these typemaps by
+looking at the files in the SWIG library. Just take into account that
+in the latest versions of swig (1.3.22+), the library files are not
+very pristine clear for the casual reader, as they used to be. The
+extensive use of macros and other ugly techniques in the latest
+version produce a very powerful and consistent python typemap library,
+but at the cost of simplicity and pedagogic value.
+</p>
+
+<p>
+To learn how to write a simple or your first typemap, you better take
+a look at the SWIG library version 1.3.20 or so.
+</p>
+
+
+<H3><a name="Python_nn56"></a>30.8.3 Typemap variables</H3>
+
+
+<p>
+Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
+A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+This is a list of the most common variables:
+</p>
+
+<p>
+<tt>$1</tt>
+</p>
+
+<div class="indent">
+A C local variable corresponding to the actual type specified in the
+<tt>%typemap</tt> directive.  For input values, this is a C local variable
+that's supposed to hold an argument value.  For output values, this is
+the raw result that's supposed to be returned to Python.
+</div>
+
+<p>
+<tt>$input</tt>
+</p>
+
+<div class="indent">
+ A <tt>PyObject *</tt> holding a raw Python object with an argument or variable value.
+</div>
+
+<p>
+<tt>$result</tt>
+</p>
+
+<div class="indent">
+A <tt>PyObject *</tt> that holds the result to be returned to Python.
+</div>
+
+<p>
+<tt>$1_name</tt>
+</p>
+
+<div class="indent">
+The parameter name that was matched. 
+</div>
+
+<p>
+<tt>$1_type</tt>
+</p>
+
+<div class="indent">
+The actual C datatype matched by the typemap.
+</div>
+
+<p>
+<tt>$1_ltype</tt>
+</p>
+
+<div class="indent">
+An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
+a C assignment operation).  This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
+All arguments and local variables in wrapper functions are declared using this type so that their values can be
+properly assigned.
+</div>
+
+<p>
+<tt>$symname</tt>
+</p>
+
+<div class="indent">
+The Python name of the wrapper function being created.
+</div>
+
+<H3><a name="Python_nn57"></a>30.8.4 Useful Python Functions</H3>
+
+
+<p>
+When you write a typemap, you usually have to work directly with Python objects.
+The following functions may prove to be useful.
+</p>
+
+<p>
+<b>Python Integer Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyInt_FromLong(long l);
+long      PyInt_AsLong(PyObject *);
+int       PyInt_Check(PyObject *);
+</pre>
+</div>
+
+<p>
+<b>Python Floating Point Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyFloat_FromDouble(double);
+double    PyFloat_AsDouble(PyObject *);
+int       PyFloat_Check(PyObject *);
+</pre>
+</div>
+
+<p>
+<b>Python String Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyString_FromString(char *);
+PyObject *PyString_FromStringAndSize(char *, lint len);
+int       PyString_Size(PyObject *);
+char     *PyString_AsString(PyObject *);
+int       PyString_Check(PyObject *);
+</pre>
+</div>
+
+<p>
+<b>Python List Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyList_New(int size);
+int       PyList_Size(PyObject *list);
+PyObject *PyList_GetItem(PyObject *list, int i);
+int       PyList_SetItem(PyObject *list, int i, PyObject *item);
+int       PyList_Insert(PyObject *list, int i, PyObject *item);
+int       PyList_Append(PyObject *list, PyObject *item);
+PyObject *PyList_GetSlice(PyObject *list, int i, int j);
+int       PyList_SetSlice(PyObject *list, int i, int , PyObject *list2);
+int       PyList_Sort(PyObject *list);
+int       PyList_Reverse(PyObject *list);
+PyObject *PyList_AsTuple(PyObject *list);
+int       PyList_Check(PyObject *);
+</pre>
+</div>
+
+<p>
+<b>Python Tuple Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyTuple_New(int size);
+int       PyTuple_Size(PyObject *);
+PyObject *PyTuple_GetItem(PyObject *, int i);
+int       PyTuple_SetItem(PyObject *, int i, PyObject *item);
+PyObject *PyTuple_GetSlice(PyObject *t, int i, int j);
+int       PyTuple_Check(PyObject *);
+</pre>
+</div>
+
+<p>
+<b>Python Dictionary Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyDict_New();
+int       PyDict_Check(PyObject *);
+int       PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val);
+int       PyDict_SetItemString(PyObject *p, const char *key, PyObject *val);
+int       PyDict_DelItem(PyObject *p, PyObject *key);
+int       PyDict_DelItemString(PyObject *p, char *key);
+PyObject* PyDict_Keys(PyObject *p);
+PyObject* PyDict_Values(PyObject *p);
+PyObject* PyDict_GetItem(PyObject *p, PyObject *key);
+PyObject* PyDict_GetItemString(PyObject *p, const char *key);
+int       PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue);
+Py_ssize_t PyDict_Size(PyObject *p);
+int       PyDict_Update(PyObject *a, PyObject *b);
+int       PyDict_Merge(PyObject *a, PyObject *b, int override);
+PyObject* PyDict_Items(PyObject *p);
+</pre>
+</div>
+
+<p>
+<b>Python File Conversion Functions</b>
+</p>
+
+<div class="code">
+<pre>
+PyObject *PyFile_FromFile(FILE *f);
+FILE     *PyFile_AsFile(PyObject *);
+int       PyFile_Check(PyObject *);
+</pre>
+</div>
+
+<p>
+<b>Abstract Object Interface</b>
+</p>
+
+<div class="code">
+<pre>
+write me
+</pre>
+</div>
+
+<H2><a name="Python_nn58"></a>30.9 Typemap Examples</H2>
+
+
+<p>
+This section includes a few examples of typemaps.  For more examples, you
+might look at the files "<tt>python.swg</tt>" and "<tt>typemaps.i</tt>" in
+the SWIG library.
+</p>
+
+<H3><a name="Python_nn59"></a>30.9.1 Converting  Python list to a char ** </H3>
+
+
+<p>
+A common problem in many C programs is the processing of command line
+arguments, which are usually passed in an array of NULL terminated
+strings.  The following SWIG interface file allows a Python list
+object to be used as a <tt>char **</tt> object.
+</p>
+
+<div class="code"><pre>
+%module argv
+
+// This tells SWIG to treat char ** as a special case
+%typemap(in) char ** {
+  /* Check if is a list */
+  if (PyList_Check($input)) {
+    int size = PyList_Size($input);
+    int i = 0;
+    $1 = (char **) malloc((size+1)*sizeof(char *));
+    for (i = 0; i &lt; size; i++) {
+      PyObject *o = PyList_GetItem($input,i);
+      if (PyString_Check(o))
+	$1[i] = PyString_AsString(PyList_GetItem($input,i));
+      else {
+	PyErr_SetString(PyExc_TypeError,"list must contain strings");
+	free($1);
+	return NULL;
+      }
+    }
+    $1[i] = 0;
+  } else {
+    PyErr_SetString(PyExc_TypeError,"not a list");
+    return NULL;
+  }
+}
+
+// This cleans up the char ** array we malloc'd before the function call
+%typemap(freearg) char ** {
+  free((char *) $1);
+}
+
+// Now a test function
+%inline %{
+int print_args(char **argv) {
+    int i = 0;
+    while (argv[i]) {
+         printf("argv[%d] = %s\n", i,argv[i]);
+         i++;
+    }
+    return i;
+}
+%}
+
+</pre></div>
+
+<p>
+When this module is compiled, the wrapped C function now operates as
+follows :
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; from argv import *
+&gt;&gt;&gt; print_args(["Dave","Mike","Mary","Jane","John"])
+argv[0] = Dave
+argv[1] = Mike
+argv[2] = Mary
+argv[3] = Jane
+argv[4] = John
+5
+</pre></div>
+
+<p>
+In the example, two different typemaps are used.  The "in" typemap is
+used to receive an input argument and convert it to a C array.  Since dynamic
+memory allocation is used to allocate memory for the array, the
+"freearg" typemap is used to later release this memory after the execution of
+the C function. 
+</p>
+
+<H3><a name="Python_nn60"></a>30.9.2 Expanding a Python object into multiple arguments</H3>
+
+
+<p>
+Suppose that you had a collection of C functions with arguments
+such as the following:
+</p>
+
+<div class="code">
+<pre>
+int foo(int argc, char **argv);
+</pre>
+</div>
+
+<p>
+In the previous example, a typemap was written to pass a Python list as the <tt>char **argv</tt>.  This
+allows the function to be used from Python as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo(4, ["foo","bar","spam","1"])
+</pre>
+</div>
+
+<p>
+Although this works, it's a little awkward to specify the argument count.  To fix this, a multi-argument
+typemap can be defined.  This is not very difficult--you only have to make slight modifications to the
+previous example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (int argc, char **argv) {
+  /* Check if is a list */
+  if (PyList_Check($input)) {
+    int i;
+    $1 = PyList_Size($input);
+    $2 = (char **) malloc(($1+1)*sizeof(char *));
+    for (i = 0; i &lt; $1; i++) {
+      PyObject *o = PyList_GetItem($input,i);
+      if (PyString_Check(o))
+	$2[i] = PyString_AsString(PyList_GetItem($input,i));
+      else {
+	PyErr_SetString(PyExc_TypeError,"list must contain strings");
+	free($2);
+	return NULL;
+      }
+    }
+    $2[i] = 0;
+  } else {
+    PyErr_SetString(PyExc_TypeError,"not a list");
+    return NULL;
+  }
+}
+
+%typemap(freearg) (int argc, char **argv) {
+  free((char *) $2);
+}
+</pre>
+</div>
+
+<p>
+When writing a multiple-argument typemap, each of the types is referenced by a variable such 
+as <tt>$1</tt> or <tt>$2</tt>.   The typemap code simply fills in the appropriate values from
+the supplied Python object.
+</p>
+
+<p>
+With the above typemap in place, you will find it no longer necessary
+to supply the argument count.  This is automatically set by the typemap code.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo(["foo","bar","spam","1"])
+</pre>
+</div>
+
+<H3><a name="Python_nn61"></a>30.9.3 Using typemaps to return arguments</H3>
+
+
+<p>
+A common problem in some C programs is that values may be returned in
+arguments rather than in the return value of a function.  For example:
+</p>
+
+<div class="code"><pre>
+/* Returns a status value and two values in out1 and out2 */
+int spam(double a, double b, double *out1, double *out2) {
+	... Do a bunch of stuff ...
+	*out1 = result1;
+	*out2 = result2;
+	return status;
+};
+
+</pre></div>
+
+<p>
+A typemap can be used to handle this case as follows :
+</p>
+
+<div class="code"><pre>
+%module outarg
+
+// This tells SWIG to treat an double * argument with name 'OutValue' as
+// an output value.  We'll append the value to the current result which 
+// is guaranteed to be a List object by SWIG.
+
+%typemap(argout) double *OutValue {
+    PyObject *o, *o2, *o3;
+    o = PyFloat_FromDouble(*$1);
+    if ((!$result) || ($result == Py_None)) {
+        $result = o;
+    } else {
+        if (!PyTuple_Check($result)) {
+            PyObject *o2 = $result;
+            $result = PyTuple_New(1);
+            PyTuple_SetItem(target,0,o2);
+        }
+        o3 = PyTuple_New(1);
+        PyTuple_SetItem(o3,0,o);
+        o2 = $result;
+        $result = PySequence_Concat(o2,o3);
+        Py_DECREF(o2);
+        Py_DECREF(o3);
+    }
+}
+
+int spam(double a, double b, double *OutValue, double *OutValue);
+
+</pre></div>
+
+<p>
+The typemap works as follows.  First, a check is made to see if any previous result
+exists.  If so, it is turned into a tuple and the new output value is concatenated to it.
+Otherwise, the result is returned normally.   For the sample function <tt>spam()</tt>, there
+are three output values--meaning that the function will return a 3-tuple of the results.
+</p>
+
+<p>
+As written, the function must accept 4 arguments as input values,
+last two being pointers to doubles.  If these arguments are only used to hold output values (and have
+no meaningful input value), an additional typemap can be written.  For example:
+</p>
+
+<div class="code"><pre>
+%typemap(in,numinputs=0) double *OutValue(double temp) {
+    $1 = &amp;temp;
+}
+
+</pre></div>
+
+<p>
+By specifying numinputs=0,  the input value is ignored.  However, since the argument still has to be set to
+some meaningful value before calling C, it is set to point to a local variable <tt>temp</tt>.  When the function
+stores its output value, it will simply be placed in this local variable.  As a result, the
+function can now be used as follows:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; a = spam(4,5)
+&gt;&gt;&gt; print a
+(0, 2.45, 5.0)
+&gt;&gt;&gt; x,y,z = spam(4,5)
+&gt;&gt;&gt;
+</pre></div>
+
+<H3><a name="Python_nn62"></a>30.9.4 Mapping Python tuples into small arrays</H3>
+
+
+<p>
+In some applications, it is sometimes desirable to pass small arrays
+of numbers as arguments. For example :
+</p>
+
+<div class="code"><pre>
+extern void set_direction(double a[4]);       // Set direction vector
+</pre></div>
+
+<p>
+This too, can be handled used typemaps as follows :
+</p>
+
+<div class="code"><pre>
+// Grab a 4 element array as a Python 4-tuple
+%typemap(in) double[4](double temp[4]) {   // temp[4] becomes a local variable
+  int i;
+  if (PyTuple_Check($input)) {
+    if (!PyArg_ParseTuple($input,"dddd",temp,temp+1,temp+2,temp+3)) {
+      PyErr_SetString(PyExc_TypeError,"tuple must have 4 elements");
+      return NULL;
+    }
+    $1 = &amp;temp[0];
+  } else {
+    PyErr_SetString(PyExc_TypeError,"expected a tuple.");
+    return NULL;
+  }
+}
+
+</pre></div>
+
+<p>
+This allows our <tt>set_direction</tt> function to be called from
+Python as follows :
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; set_direction((0.5,0.0,1.0,-0.25))
+</pre></div>
+
+<p>
+Since our mapping copies the contents of a Python tuple into a C
+array, such an approach would not be recommended for huge arrays, but
+for small structures, this approach works fine.
+</p>
+
+<H3><a name="Python_nn63"></a>30.9.5 Mapping sequences to C arrays</H3>
+
+
+<p>
+Suppose that you wanted to generalize the previous example to handle C
+arrays of different sizes.  To do this, you might write a typemap as follows:
+</p>
+
+<div class="code"><pre>
+// Map a Python sequence into any sized C double array
+%typemap(in) double[ANY](double temp[$1_dim0]) {
+  int i;
+  if (!PySequence_Check($input)) {
+      PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
+      return NULL;
+  }
+  if (PyObject_Length($input) != $1_dim0) {
+      PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements");
+      return NULL;
+  }
+  for (i =0; i &lt; $1_dim0; i++) {
+      PyObject *o = PySequence_GetItem($input,i);
+      if (!PyFloat_Check(o)) {
+         Py_XDECREF(o);
+         PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats");
+         return NULL;
+      }
+      temp[i] = PyFloat_AsDouble(o);
+      Py_DECREF(o);
+  }
+  $1 = &amp;temp[0];
+}
+</pre>
+</div>
+
+<p>
+In this case, the variable <tt>$1_dim0</tt> is expanded to match the
+array dimensions actually used in the C code. This allows the typemap
+to be applied to types such as:
+</p>
+
+<div class="code">
+<pre>
+void foo(double x[10]);
+void bar(double a[4], double b[8]);
+</pre>
+</div>
+
+<p>
+Since the above typemap code gets inserted into every wrapper function where used, it might make sense
+to use a helper function instead.  This will greatly reduce the amount of wrapper code.  For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+static int convert_darray(PyObject *input, double *ptr, int size) {
+  int i;
+  if (!PySequence_Check(input)) {
+      PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
+      return 0;
+  }
+  if (PyObject_Length(input) != size) {
+      PyErr_SetString(PyExc_ValueError,"Sequence size mismatch");
+      return 0;
+  }
+  for (i =0; i &lt; size; i++) {
+      PyObject *o = PySequence_GetItem(input,i);
+      if (!PyFloat_Check(o)) {
+         Py_XDECREF(o);
+         PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats");
+         return 0;
+      }
+      ptr[i] = PyFloat_AsDouble(o);
+      Py_DECREF(o);
+  }
+  return 1;
+}
+%}
+
+%typemap(in) double [ANY](double temp[$1_dim0]) {
+   if (!convert_darray($input,temp,$1_dim0))) {
+      return NULL;
+   }
+   $1 = &amp;temp[0];
+}
+</pre>
+</div>
+
+<H3><a name="Python_nn64"></a>30.9.6 Pointer handling</H3>
+
+
+<p>
+Occasionally, it might be necessary to convert pointer values that have
+been stored using the SWIG typed-pointer representation.  Since there are
+several ways in which pointers can be represented, the following two
+functions are used to safely perform this conversion:
+</p>
+
+<p>
+<tt>
+int SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags)</tt>
+</p>
+
+<div class="indent">
+Converts a Python object <tt>obj</tt> to a C pointer.  The result of the conversion is placed
+into the pointer located at <tt>ptr</tt>.  <tt>ty</tt> is a SWIG type descriptor structure.
+<tt>flags</tt> is used to handle error checking and other aspects of conversion.  It is the
+bitwise-or of several flag values including <tt>SWIG_POINTER_EXCEPTION</tt> and
+<tt>SWIG_POINTER_DISOWN</tt>.   The first flag makes the function raise an exception on type
+error.  The second flag additionally
+steals ownership of an object. Returns 0 on success and -1 on error.
+</div>
+
+<p>
+<tt>
+PyObject *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</tt>
+</p>
+
+<div class="indent">
+Creates a new Python pointer object.  <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
+describes the type, and <tt>own</tt> is a flag that indicates whether or not Python should take ownership of the
+pointer.
+</div>
+
+<p>
+Both of these functions require the use of a special SWIG
+type-descriptor structure.  This structure contains information about
+the mangled name of the datatype, type-equivalence information, as
+well as information about converting pointer values under C++
+inheritance.   For a type of <tt>Foo *</tt>, the type descriptor structure
+is usually accessed as follows:
+</p>
+
+<div class="code">
+<pre>
+Foo *f;
+if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, SWIG_POINTER_EXCEPTION) == -1)
+  return NULL;
+
+PyObject *obj;
+obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
+</pre>
+</div>
+
+<p>
+In a typemap, the type descriptor should always be accessed using the special typemap
+variable <tt>$1_descriptor</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Foo * {
+if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,SWIG_POINTER_EXCEPTION)) == -1)
+  return NULL;
+}
+</pre>
+</div>
+
+<p>
+If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Foo * {
+if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 
+                                               SWIG_POINTER_EXCEPTION)) == -1)
+  return NULL;
+}
+</pre>
+</div>
+
+<p>
+Although the pointer handling functions are primarily intended for
+manipulating low-level pointers, both functions are fully aware of
+Python proxy classes.  Specifically,
+<tt>SWIG_ConvertPtr()</tt> will retrieve a pointer from any object
+that has a <tt>this</tt> attribute.  In addition,
+<tt>SWIG_NewPointerObj()</tt> can automatically generate a proxy
+class object (if applicable).
+</p>
+
+
+
+<H2><a name="Python_nn65"></a>30.10 Docstring Features</H2>
+
+
+<p>
+Using docstrings in Python code is becoming more and more important
+and more tools are coming on the scene that take advantage of them,
+everything from full-blown documentation generators to class browsers
+and popup call-tips in Python-aware IDEs.  Given the way that SWIG
+generates the proxy code by default, your users will normally get
+something like <tt>"function_name(*args)"</tt> in the popup calltip of
+their IDE which is next to useless when the real function prototype
+might be something like this:
+</p>
+
+<div class="code">
+<pre>
+bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
+</pre>
+</div>
+
+<p>
+The features described in this section make it easy for you to add
+docstrings to your modules, functions and methods that can then be
+used by the various tools out there to make the programming experience
+of your users much simpler.
+</p>
+
+
+<H3><a name="Python_nn66"></a>30.10.1 Module docstring</H3>
+
+
+<p>
+Python allows a docstring at the beginning of the <tt>.py</tt> file
+before any other statements, and it is typically used to give a
+general description of the entire module.  SWIG supports this by
+setting an option of the <tt>%module</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module(docstring="This is the example module's docstring") example
+</pre>
+</div>
+
+<p>
+When you have more than just a line or so then you can retain the easy
+readability of the <tt>%module</tt> directive by using a macro.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%define DOCSTRING
+"The `XmlResource` class allows program resources defining menus, 
+layout of controls on a panel, etc. to be loaded from an XML file."
+%enddef
+
+%module(docstring=DOCSTRING) xrc
+</pre>
+</div>
+
+
+<H3><a name="Python_nn67"></a>30.10.2 %feature("autodoc")</H3>
+
+
+<p>
+As alluded to above SWIG will generate all the function and method
+proxy wrappers with just "*args" (or "*args, **kwargs" if the -keyword
+option is used) for a parameter list and will then sort out the
+individual parameters in the C wrapper code.  This is nice and simple
+for the wrapper code, but makes it difficult to be programmer and tool
+friendly as anyone looking at the <tt>.py</tt> file will not be able
+to find out anything about the parameters that the functions accept.
+</p>
+
+<p>But since SWIG does know everything about the function it is
+possible to generate a docstring containing the parameter types, names
+and default values. Since many of the docstring tools are adopting a
+standard of recognizing if the first thing in the docstring is a
+function prototype then using that instead of what they found from
+introspection, then life is good once more.
+
+<p>SWIG's Python module provides support for the "autodoc" feature,
+which when attached to a node in the parse tree will cause a docstring
+to be generated that includes the name of the function, parameter
+names, default values if any, and return type if any. There are also
+three options for autodoc controlled by the value given to the
+feature, described below.
+
+<H4><a name="Python_nn68"></a>30.10.2.1 %feature("autodoc", "0")</H4>
+
+
+<p>
+When the "0" option is given then the types of the parameters will
+<em>not</em> be included in the autodoc string.  For example, given
+this function prototype:
+</p>
+
+<div class="code">
+<pre>
+%feature("autodoc", "0");
+bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
+</pre>
+</div>
+
+<p>
+Then Python code like this will be generated:
+</p>
+
+<div class="targetlang">
+<pre>
+def function_name(*args, **kwargs):
+    """function_name(x, y, foo=None, bar=None) -&gt; bool"""
+    ...
+</pre>
+</div>
+
+
+<H4><a name="Python_nn69"></a>30.10.2.2 %feature("autodoc", "1")</H4>
+
+
+<p>
+When the "1" option is used then the parameter types <em>will</em> be
+used in the autodoc string.  In addition, an attempt is made to
+simplify the type name such that it makes more sense to the Python
+user.  Pointer, reference and const info is removed,
+<tt>%rename</tt>'s are evaluated, etc.  (This is not always
+successful, but works most of the time.  See the next section for what
+to do when it doesn't.)  Given the example above, then turning on the
+parameter types with the "1" option will result in Python code like
+this:
+</p>
+
+<div class="targetlang">
+<pre>
+def function_name(*args, **kwargs):
+    """function_name(int x, int y, Foo foo=None, Bar bar=None) -&gt; bool"""
+    ...
+</pre>
+</div>
+
+
+
+<H4><a name="Python_nn70"></a>30.10.2.3 %feature("autodoc", "docstring")</H4>
+
+
+<p>
+Finally, there are times when the automatically generated autodoc
+string will make no sense for a Python programmer, particularly when a
+typemap is involved.  So if you give an explicit value for the autodoc
+feature then that string will be used in place of the automatically
+generated string.  For example:
+</p>
+
+<div class="code">
+<pre>
+%feature("autodoc", "GetPosition() -&gt; (x, y)") GetPosition;
+void GetPosition(int* OUTPUT, int* OUTPUT);
+</pre>
+</div>
+
+
+<H3><a name="Python_nn71"></a>30.10.3 %feature("docstring")</H3>
+
+
+<p>
+In addition to the autodoc strings described above, you can also
+attach any arbitrary descriptive text to a node in the parse tree with
+the "docstring" feature.  When the proxy module is generated then any
+docstring associated with classes, function or methods are output.
+If an item already has an autodoc string then it is combined with the
+docstring and they are output together.  If the docstring is all on a
+single line then it is output like this::
+</p>
+
+<div class="targetlang">
+<pre>
+"""This is the docstring"""
+</pre>
+</div>
+
+<p>
+Otherwise, to aid readability it is output like this:
+</p>
+
+<div class="targetlang">
+<pre>
+"""
+This is a multi-line docstring
+with more than one line.
+"""
+</pre>
+</div>
+
+<H2><a name="Python_nn72"></a>30.11 Python Packages</H2>
+
+
+<p>
+Using the <tt>package</tt> option of the <tt>%module</tt> directive
+allows you to specify what Python package that the module will be
+living in when installed. 
+</p>
+
+<div class="code">
+<pre>
+%module(package="wx") xrc
+</pre>
+</div>
+
+<p>
+This is useful when the <tt>.i</tt> file is <tt>%import</tt>ed by
+another <tt>.i</tt> file.  By default SWIG will assume that the
+importer is able to find the importee with just the module name, but
+if they live in separate Python packages then that won't work.
+However if the importee specifies what its package is with the
+<tt>%module</tt> option then the Python code generated for the
+importer will use that package name when importing the other module
+and also in base class declarations, etc. if the package name is
+different than its own.
+</p>
+
+
+</body>
+</html>
+
+<!--  LocalWords:  polymorphism Typemaps STL typemap typemaps Docstring autodoc
+ -->
+<!--  LocalWords:  docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker
+ -->
+<!--  LocalWords:  examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket
+ -->
+<!--  LocalWords:  lnsl lpthread distutils enums namespaces
+ -->
diff --git a/trunk/Doc/Manual/R.html b/trunk/Doc/Manual/R.html
new file mode 100644
index 0000000..3b37d53
--- /dev/null
+++ b/trunk/Doc/Manual/R.html
@@ -0,0 +1,160 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and R</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="R"></a>33 SWIG and R</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#R_nn2">Bugs</a>
+<li><a href="#R_nn3">Using R and SWIG</a>
+<li><a href="#R_nn4">Precompiling large R files</a>
+<li><a href="#R_nn5">General policy</a>
+<li><a href="#R_language_conventions">Language conventions</a>
+<li><a href="#R_nn6">C++ classes</a>
+<li><a href="#R_nn7">Enumerations</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+R is a GPL'ed open source statistical and plotting environment.
+Information about R can be found at <a
+href="http://www.r-project.org/">www.r-project.org</a>.
+
+The R bindings are under active development.  They have been used to
+compile and run an R interface to QuantLib running on Mandriva Linux
+with gcc. The R bindings also work on Microsoft Windows using Visual C++.
+</p>
+
+<H2><a name="R_nn2"></a>33.1 Bugs</H2>
+
+
+<p>
+Currently the following features are not implemented or broken:
+</p>
+
+<ul>
+<li>Garbage collection of created objects
+<li>C Array wrappings
+</ul>
+
+<H2><a name="R_nn3"></a>33.2 Using R and SWIG</H2>
+
+
+<p>
+To use R and SWIG in C mode, execute the following commands where
+example.c is the name of the file with the functions in them
+</p>
+
+<div class="shell">
+<pre>
+swig -r example.i
+PKG_LIBS="example.c" R CMD SHLIB example_wrap.c
+</pre>
+</div>
+
+<p>
+The corresponding comments for C++ mode are
+</p>
+
+<div class="shell">
+<pre>
+swig -c++ -r -o example_wrap.cpp example.i
+PKG_LIBS="example.cxx" R CMD SHLIB example_wrap.cpp
+</pre>
+</div>
+
+<p>
+Note that R is sensitive to the name of the file and to the file
+extension in C and C++ mode.  The name of the wrapper file must be the
+name of the library.  Also in C++ mode, the file extension must be .cpp
+rather than .cxx for the R compile command to recognize it.
+</p>
+
+<p>
+The commands produces two files.  A dynamic shared object file called
+example.so, or example.dll, and an R wrapper file called example.R.  To load these
+files, start up R and type in the following commands
+</p>
+
+<div class="shell">
+<pre>
+dyn.load(paste("example", .Platform$dynlib.ext, sep=""))
+source("example.R")
+cacheMetaData(1)
+</pre>
+</div>
+
+The cacheMetaData(1) will cause R to refresh its object tables.
+Without it, inheritance of wrapped objects may fail.
+
+<p>
+These two files can be loaded in any order
+</p>
+
+<H2><a name="R_nn4"></a>33.3 Precompiling large R files</H2>
+
+
+In cases where the R file is large, one make save a lot of loading
+time by precompiling the R wrapper.  This can be done by creating the
+file makeRData.R which contains the following
+
+<pre>
+source('BigFile.R')
+save(list=ls(all=TRUE),file="BigFile.RData", compress=TRUE)
+q(save="no")
+</pre>
+
+This will generate a compiled R file called BigFile.RData that
+will save a large amount of loading time.
+
+
+
+<H2><a name="R_nn5"></a>33.4 General policy</H2>
+
+
+<p>
+The general policy of the module is to treat the C/C++ as a basic
+wrapping over the underlying functions and rely on the R type system
+to provide R syntax.
+</p>
+
+<H2><a name="R_language_conventions"></a>33.5 Language conventions</H2>
+
+
+<p>
+getitem and setitem use C++ conventions (i.e. zero based indices). [<-
+and [ are overloaded to allow for R syntax (one based indices and
+slices)
+</p>
+
+<H2><a name="R_nn6"></a>33.6 C++ classes</H2>
+
+
+<p>
+C++ objects are implemented as external pointer objects with the class
+being the mangled name of the class. The C++ classes are encapsulated
+as an SEXP with an external pointer type. The class is the mangled
+name of the class. The nice thing about R is that is allows you to
+keep track of the pointer object which removes the necessity for a lot
+of the proxy class baggage you see in other languages.
+</p>
+
+<H2><a name="R_nn7"></a>33.7 Enumerations</H2>
+
+
+<p>
+enumerations are characters which are then converted back and forth to
+ints before calling the C routines. All of the enumeration code is
+done in R.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/README b/trunk/Doc/Manual/README
new file mode 100644
index 0000000..f01013d
--- /dev/null
+++ b/trunk/Doc/Manual/README
@@ -0,0 +1,21 @@
+This directory contains the HTML for the SWIG users manual.
+
+All of this HTML is hand-written.  However, section numbering, indices,
+and the table of contents is generated automatically by the 'maketoc.py'
+script. The Makefile has further information on how the various alternative
+forms of the documentation is generated from the hand-written HTML.
+
+There are 4 types of boxes that code or whatever can be inside:
+  - <div class="shell">...</div>
+    This is for text that shows the output of running commands on the shell.
+  - <div class="code">...</div>
+    This is for either C, C++, or SWIG code
+  - <div class="targetlang">...</div>
+    This is for code in a target scripting language
+  - <div class="diagram">...</div>
+    This is for text that is not code or a shell
+
+The general format is
+<div class="foo"><pre>
+whatever here
+</pre></div>
diff --git a/trunk/Doc/Manual/Ruby.html b/trunk/Doc/Manual/Ruby.html
new file mode 100644
index 0000000..9cd83d4
--- /dev/null
+++ b/trunk/Doc/Manual/Ruby.html
@@ -0,0 +1,10745 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+
+
+
+
+  
+
+
+  
+  
+  
+  
+  
+  
+  
+  <title>SWIG and Ruby</title>
+  <link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+
+<body style="background-color: rgb(255, 255, 255);">
+
+
+
+
+
+<H1><a name="Ruby"></a>31 SWIG and Ruby</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Ruby_nn2">Preliminaries</a>
+<ul>
+<li><a href="#Ruby_nn3">Running SWIG</a>
+<li><a href="#Ruby_nn4">Getting the right header files</a>
+<li><a href="#Ruby_nn5">Compiling a dynamic module</a>
+<li><a href="#Ruby_nn6">Using your module</a>
+<li><a href="#Ruby_nn7">Static linking</a>
+<li><a href="#Ruby_nn8">Compilation of C++ extensions</a>
+</ul>
+<li><a href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</a>
+<ul>
+<li><a href="#Ruby_nn10">Running SWIG from Developer Studio</a>
+</ul>
+<li><a href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</a>
+<ul>
+<li><a href="#Ruby_nn12">Modules</a>
+<li><a href="#Ruby_nn13">Functions</a>
+<li><a href="#Ruby_nn14">Variable Linking</a>
+<li><a href="#Ruby_nn15">Constants</a>
+<li><a href="#Ruby_nn16">Pointers</a>
+<li><a href="#Ruby_nn17">Structures</a>
+<li><a href="#Ruby_nn18">C++ classes</a>
+<li><a href="#Ruby_nn19">C++ Inheritance</a>
+<li><a href="#Ruby_nn20">C++ Overloaded Functions</a>
+<li><a href="#Ruby_nn21">C++ Operators</a>
+<li><a href="#Ruby_nn22">C++ namespaces</a>
+<li><a href="#Ruby_nn23">C++ templates</a>
+<li><a href="#Ruby_nn23_1">C++ Standard Template Library (STL)</a>
+<li><a href="#C_STL_Functors">C++ STL Functors</a>
+<li><a href="#Ruby_C_Iterators">C++ STL Iterators</a>
+<li><a href="#Ruby_nn24">C++ Smart Pointers</a>
+<li><a href="#Ruby_nn25">Cross-Language Polymorphism</a>
+<ul>
+<li><a href="#Ruby_nn26">Exception Unrolling</a>
+</ul>
+</ul>
+<li><a href="#Ruby_nn27">Naming</a>
+<ul>
+<li><a href="#Ruby_nn28">Defining Aliases</a>
+<li><a href="#Ruby_nn29">Predicate Methods</a>
+<li><a href="#Ruby_nn30">Bang Methods</a>
+<li><a href="#Ruby_nn31">Getters and Setters</a>
+</ul>
+<li><a href="#Ruby_nn32">Input and output parameters</a>
+<li><a href="#Ruby_nn33">Exception handling </a>
+<ul>
+<li><a href="#Ruby_nn34">Using the %exception directive </a>
+<li><a href="#Ruby_nn34_2">Handling Ruby Blocks </a>
+<li><a href="#Ruby_nn35">Raising exceptions </a>
+<li><a href="#Ruby_nn36">Exception classes </a>
+</ul>
+<li><a href="#Ruby_nn37">Typemaps</a>
+<ul>
+<li><a href="#Ruby_nn38">What is a typemap?</a>
+<li><a href="#Ruby_Typemap_scope">Typemap scope</a>
+<li><a href="#Ruby_Copying_a_typemap">Copying a typemap</a>
+<li><a href="#Ruby_Deleting_a_typemap">Deleting a typemap</a>
+<li><a href="#Ruby_Placement_of_typemaps">Placement of typemaps</a>
+<li><a href="#Ruby_nn39">Ruby typemaps</a>
+<ul>
+<li><a href="#Ruby_in_typemap">&nbsp;"in" typemap</a>
+<li><a href="#Ruby_typecheck_typemap">"typecheck" typemap</a>
+<li><a href="#Ruby_out_typemap">&nbsp;"out" typemap</a>
+<li><a href="#Ruby_arginit_typemap">"arginit" typemap</a>
+<li><a href="#Ruby_default_typemap">"default" typemap</a>
+<li><a href="#Ruby_check_typemap">"check" typemap</a>
+<li><a href="#Ruby_argout_typemap_">"argout" typemap</a>
+<li><a href="#Ruby_freearg_typemap_">"freearg" typemap</a>
+<li><a href="#Ruby_newfree_typemap">"newfree" typemap</a>
+<li><a href="#Ruby_memberin_typemap">"memberin" typemap</a>
+<li><a href="#Ruby_varin_typemap">"varin" typemap</a>
+<li><a href="#Ruby_varout_typemap_">"varout" typemap</a>
+<li><a href="#Ruby_throws_typemap">"throws" typemap</a>
+<li><a href="#Ruby_directorin_typemap">directorin typemap</a>
+<li><a href="#Ruby_directorout_typemap">directorout typemap</a>
+<li><a href="#Ruby_directorargout_typemap">directorargout typemap</a>
+<li><a href="#Ruby_ret_typemap">ret typemap</a>
+<li><a href="#Ruby_globalin_typemap">globalin typemap</a>
+</ul>
+<li><a href="#Ruby_nn40">Typemap variables</a>
+<li><a href="#Ruby_nn41">Useful Functions</a>
+<ul>
+<li><a href="#Ruby_nn42">C Datatypes to Ruby Objects</a>
+<li><a href="#Ruby_nn43">Ruby Objects to C Datatypes</a>
+<li><a href="#Ruby_nn44">Macros for VALUE</a>
+<li><a href="#Ruby_nn45">Exceptions</a>
+<li><a href="#Ruby_nn46">Iterators</a>
+</ul>
+<li><a href="#Ruby_nn47">Typemap Examples</a>
+<li><a href="#Ruby_nn48">Converting a Ruby array to a char **</a>
+<li><a href="#Ruby_nn49">Collecting arguments in a hash</a>
+<li><a href="#Ruby_nn50">Pointer handling</a>
+<ul>
+<li><a href="#Ruby_nn51">Ruby Datatype Wrapping</a>
+</ul>
+<li><a href="#Ruby_nn52">Example: STL Vector to Ruby Array</a>
+</ul>
+<li><a href="#Ruby_nn65">Docstring Features</a>
+<ul>
+<li><a href="#Ruby_nn66">Module docstring</a>
+<li><a href="#Ruby_nn67">%feature("autodoc")</a>
+<ul>
+<li><a href="#Ruby_nn68">%feature("autodoc", "0")</a>
+<li><a href="#Ruby_autodoc1">%feature("autodoc", "1")</a>
+<li><a href="#Ruby_autodoc2">%feature("autodoc", "2")</a>
+<li><a href="#Ruby_feature_autodoc3">%feature("autodoc", "3")</a>
+<li><a href="#Ruby_nn70">%feature("autodoc", "docstring")</a>
+</ul>
+<li><a href="#Ruby_nn71">%feature("docstring")</a>
+</ul>
+<li><a href="#Ruby_nn53">Advanced Topics</a>
+<ul>
+<li><a href="#Ruby_nn54">Operator overloading</a>
+<li><a href="#Ruby_nn55">Creating Multi-Module Packages</a>
+<li><a href="#Ruby_nn56">Specifying Mixin Modules</a>
+</ul>
+<li><a href="#Ruby_nn57">Memory Management</a>
+<ul>
+<li><a href="#Ruby_nn58">Mark and Sweep Garbage Collector </a>
+<li><a href="#Ruby_nn59">Object Ownership</a>
+<li><a href="#Ruby_nn60">Object Tracking</a>
+<li><a href="#Ruby_nn61">Mark Functions</a>
+<li><a href="#Ruby_nn62">Free Functions</a>
+<li><a href="#Ruby_nn63">Embedded Ruby and the C++ Stack</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>This chapter describes SWIG's support of Ruby.</p>
+
+
+
+
+
+<H2><a name="Ruby_nn2"></a>31.1 Preliminaries</H2>
+
+
+<p> SWIG 1.3 is known to work with Ruby versions 1.6 and later.
+Given the choice, you should use the latest stable version of Ruby. You
+should also determine if your system supports shared libraries and
+dynamic loading. SWIG will work with or without dynamic loading, but
+the compilation process will vary. </p>
+
+
+
+
+
+<p>This chapter covers most SWIG features, but in less depth than
+is found in earlier chapters. At the very least, make sure you also
+read the "<a href="SWIG.html#SWIG">SWIG Basics</a>"
+chapter. It is also assumed that the reader has a basic understanding
+of Ruby. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn3"></a>31.1.1 Running SWIG</H3>
+
+
+<p> To build a Ruby module, run SWIG using the <tt>-ruby</tt>
+option:</p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -ruby example.i</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If building a C++ extension, add the <tt>-c++</tt>
+option: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -c++ -ruby example.i</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> This creates a file <tt>example_wrap.c</tt> (<tt>example_wrap.cxx</tt>
+if compiling a C++ extension) that contains all of the code needed to
+build a Ruby extension module. To finish building the module, you need
+to compile this file and link it with the rest of your program. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn4"></a>31.1.2 Getting the right header files</H3>
+
+
+<p> In order to compile the wrapper code, the compiler needs the <tt>ruby.h</tt>
+header file. This file is usually contained in a directory such as </p>
+
+
+
+
+
+<div class="code shell diagram">
+<pre>/usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h<br>/usr/local/lib/ruby/1.6/i686-linux/ruby.h<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The exact location may vary on your machine, but the above
+location is typical. If you are not entirely sure where Ruby is
+installed, you can run Ruby to find out. For example: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>ruby -e 'puts $:.join("\n")'</b><br>/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux<br>/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux .<br> </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn5"></a>31.1.3 Compiling a dynamic module</H3>
+
+
+<p> Ruby extension modules are typically compiled into shared
+libraries that the interpreter loads dynamically at runtime. Since the
+exact commands for doing this vary from platform to platform, your best
+bet is to follow the steps described in the <tt>README.EXT</tt>
+file from the Ruby distribution: </p>
+
+
+
+
+
+<ol>
+
+
+
+
+
+  <li>
+    
+    
+    
+    
+    <p>Create a file called <tt>extconf.rb</tt> that
+looks like the following:</p>
+
+
+
+
+
+    
+    
+    
+    
+    <div class="code targetlang">
+    
+    
+    
+    
+    <pre>require 'mkmf'<br>create_makefile('example')<br></pre>
+
+
+
+
+
+    </div>
+
+
+
+
+
+  </li>
+
+
+
+
+
+  <li>
+    
+    
+    
+    
+    <p>Type the following to build the extension:</p>
+
+
+
+
+
+    
+    
+    
+    
+    <div class="code shell">
+    
+    
+    
+    
+    <pre>$ <b>ruby extconf.rb</b><br>$ <b>make</b><br>$ <b>make install</b>
+    </pre>
+
+
+
+
+
+    </div>
+
+
+
+
+
+  </li>
+
+
+
+
+
+</ol>
+
+
+
+
+
+<p> Of course, there is the problem that mkmf does not work
+correctly on all platforms, e.g, HPUX. If you need to add your own make
+rules to the file that <tt>extconf.rb</tt> produces, you
+can add this: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>open("Makefile", "a") { |mf|<br> puts &lt;&lt;EOM<br> # Your make rules go here<br> EOM<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> to the end of the <tt>extconf.rb</tt> file. If
+for some reason you don't want to use the standard approach, you'll
+need to determine the correct compiler and linker flags for your build
+platform. For example, a typical sequence of commands for the Linux
+operating system would look something like this: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -ruby example.i</b><br>$ <b>gcc -c example.c</b><br>$ <b>gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux</b> <br>$ <b>gcc -shared example.o example_wrap.o -o example.so</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> For other platforms it may be necessary to compile with the <tt>-fPIC</tt>
+option to generate position-independent code. If in doubt, consult the
+manual pages for your compiler and linker to determine the correct set
+of options. You might also check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a>
+for additional information. </p>
+
+<H3><a name="Ruby_nn6"></a>31.1.4 Using your module</H3>
+
+
+<p> Ruby <i>module</i> names must be capitalized,
+but the convention for Ruby <i>feature</i> names is to use
+lowercase names. So, for example, the <b>Etc</b> extension
+module is imported by requiring the <b>etc</b> feature: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre># The feature name begins with a lowercase letter...<br>require 'etc'<br><br># ... but the module name begins with an uppercase letter<br>puts "Your login name: #{Etc.getlogin}"<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To stay consistent with this practice, you should always
+specify a <b>lowercase</b> module name with SWIG's <tt>%module</tt>
+directive. SWIG will automatically correct the resulting Ruby module
+name for your extension. So for example, a SWIG interface file that
+begins with: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> will result in an extension module using the feature name
+"example" and Ruby module name "Example". </p>
+
+
+
+
+
+<H3><a name="Ruby_nn7"></a>31.1.5 Static linking</H3>
+
+
+<p> An alternative approach to dynamic linking is to rebuild the
+Ruby interpreter with your extension module added to it. In the past,
+this approach was sometimes necessary due to limitations in dynamic
+loading support on certain machines. However, the situation has
+improved greatly over the last few years and you should not consider
+this approach unless there is really no other option. </p>
+
+
+
+
+
+<p>The usual procedure for adding a new module to Ruby involves
+finding the Ruby source, adding an entry to the <tt>ext/Setup</tt>
+file, adding your directory to the list of extensions in the file, and
+finally rebuilding Ruby. </p>
+
+
+
+<H3><a name="Ruby_nn8"></a>31.1.6 Compilation of C++ extensions</H3>
+
+
+<p> On most machines, C++ extension modules should be linked
+using the C++ compiler. For example: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -c++ -ruby example.i</b><br>$ <b>g++ -c example.cxx</b><br>$ <b>g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux</b><br>$ <b>g++ -shared example.o example_wrap.o -o example.so</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If you've written an <tt>extconf.rb</tt> script
+to automatically generate a <tt>Makefile</tt> for your C++
+extension module, keep in mind that (as of this writing) Ruby still
+uses <tt>gcc</tt> and not <tt>g++</tt> as its
+linker. As a result, the required C++ runtime library support will not
+be automatically linked into your extension module and it may fail to
+load on some platforms. A workaround for this problem is use the <tt>mkmf</tt>
+module's <tt>append_library()</tt> method to add one of
+the C++ runtime libraries to the list of libraries linked into your
+extension, e.g. </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>require 'mkmf'<br>$libs = append_library($libs, "supc++")<br>create_makefile('example')<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H2><a name="Ruby_nn9"></a>31.2 Building Ruby Extensions under Windows 95/NT</H2>
+
+
+<p> Building a SWIG extension to Ruby under Windows 95/NT is
+roughly similar to the process used with Unix. Normally, you will want
+to produce a DLL that can be loaded into the Ruby interpreter. For all
+recent versions of Ruby, the procedure described above (i.e. using an <tt>extconf.rb</tt>
+script) will work with Windows as well; you should be able to build
+your code into a DLL by typing: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>C:\swigtest&gt; <b>ruby extconf.rb</b><br>C:\swigtest&gt; <b>nmake</b><br>C:\swigtest&gt; <b>nmake install</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The remainder of this section covers the process of compiling
+SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within
+the Developer Studio IDE, instead of using the command line tools). In
+order to build extensions, you may need to download the source
+distribution to the Ruby package, as you will need the Ruby header
+files. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn10"></a>31.2.1 Running SWIG from Developer Studio</H3>
+
+
+<p> If you are developing your application within Microsoft
+developer studio, SWIG can be invoked as a custom build option. The
+process roughly follows these steps : </p>
+
+
+
+
+
+<ul>
+
+
+
+
+
+  <li> Open up a new workspace and use the AppWizard to select a
+DLL project. </li>
+
+
+
+
+
+  <li> Add both the SWIG interface file (the .i file), any
+supporting C files, and the name of the wrapper file that will be
+created by SWIG (i.e. <tt>example_wrap.c</tt>). Note : If
+using C++, choose a different suffix for the wrapper file such as <tt>example_wrap.cxx</tt>.
+Don't worry if the wrapper file doesn't exist yet--Developer Studio
+will keep a reference to it around. </li>
+
+
+
+
+
+  <li> Select the SWIG interface file and go to the settings
+menu. Under settings, select the "Custom Build" option. </li>
+
+
+
+
+
+  <li> Enter "SWIG" in the description field. </li>
+
+
+
+
+
+  <li> Enter "<tt>swig -ruby -o
+$(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build
+command(s) field". You may have to include the path to swig.exe. </li>
+
+
+
+
+
+  <li> Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>"
+in the "Output files(s) field". </li>
+
+
+
+
+
+  <li> Next, select the settings for the entire project and go to
+the C/C++ tab and select the Preprocessor category. Add NT=1 to the
+Preprocessor definitions. This must be set else you will get
+compilation errors. Also add IMPORT to the preprocessor definitions,
+else you may get runtime errors. Also add the include directories for
+your Ruby installation under "Additional include directories". </li>
+
+
+
+
+
+  <li> Next, select the settings for the entire project and go to
+the Link tab and select the General category. Set the name of the
+output file to match the name of your Ruby module (i.e.. example.dll).
+Next add the Ruby library file to your link libraries under
+Object/Library modules. For example "mswin32-ruby16.lib. You also need
+to add the path to the library under the Input tab - Additional library
+path. </li>
+
+
+
+
+
+  <li> Build your project. </li>
+
+
+
+
+
+</ul>
+
+
+
+
+
+<p> Now, assuming all went well, SWIG will be automatically
+invoked when you build your project. Any changes made to the interface
+file will result in SWIG being automatically invoked to produce a new
+version of the wrapper file. To run your new Ruby extension, simply run
+Ruby and use the <tt>require</tt> command as normal. For
+example if you have this ruby file run.rb:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre># file: run.rb<br>require 'Example'<br><br># Call a c function<br>print "Foo = ", Example.Foo, "\n"<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Ensure the dll just built is in your path or current
+directory, then run the Ruby script from the DOS/Command prompt: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>C:\swigtest&gt; <b>ruby run.rb</b><br>Foo = 3.0<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H2><a name="Ruby_nn11"></a>31.3 The Ruby-to-C/C++ Mapping</H2>
+
+
+<p> This section describes the basics of how SWIG maps C or C++
+declarations in your SWIG interface files to Ruby constructs. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn12"></a>31.3.1 Modules</H3>
+
+
+<p> The SWIG <tt>%module</tt> directive specifies
+the name of the Ruby module. If you specify: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> then everything is wrapped into a Ruby module named <tt>Example</tt>
+that is nested directly under the global module. You can specify a more
+deeply nested module by specifying the fully-qualified module name in
+quotes, e.g. </p>
+
+
+
+
+
+<div class="code">
+<pre>%module "foo::bar::spam"</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> An alternate method of specifying a nested module name is to
+use the <span style="font-family: monospace;">-prefix</span>
+option on the SWIG command line. The prefix that you specify with this
+option will be prepended to the module name specified with the <span style="font-family: monospace;">%module</span>
+directive in your SWIG interface file. So for example, this declaration
+at the top of your SWIG interface file:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%module "foo::bar::spam"</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> will result in a nested module name of <span style="font-family: monospace;">Foo::Bar::Spam</span>,
+but you can achieve the <span style="font-style: italic;">same</span>
+effect by specifying:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%module spam</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> and then running SWIG with the <span style="font-family: monospace;">-prefix</span> command
+line option:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -ruby -prefix "foo::bar::" example.i</b></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Starting with SWIG 1.3.20, you can also choose to wrap
+everything into the global module by specifying the <tt>-globalmodule</tt>
+option on the SWIG command line, i.e. </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -ruby -globalmodule example.i</b></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note that this does not relieve you of the requirement of
+specifying the SWIG module name with the <tt>%module</tt>
+directive (or the <tt>-module</tt> command-line option) as
+described earlier. </p>
+
+
+
+
+
+<p>When choosing a module name, do not use the same name as a
+built-in Ruby command or standard module name, as the results may be
+unpredictable. Similarly, if you're using the <tt>-globalmodule</tt>
+option to wrap everything into the global module, take care that the
+names of your constants, classes and methods don't conflict with any of
+Ruby's built-in names. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn13"></a>31.3.2 Functions</H3>
+
+
+<p> Global functions are wrapped as Ruby module methods. For
+example, given the SWIG interface file <tt>example.i</tt>:
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>int fact(int n);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> and C source file <tt>example.c</tt>: </p>
+
+
+
+
+
+<div class="code">
+<pre>int fact(int n) {<br> if (n == 0)<br> return 1;<br> return (n * fact(n-1));<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> SWIG will generate a method <i>fact</i> in the <i>Example</i>
+module that can be used like so: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>Example.fact(4)</b><br>24<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn14"></a>31.3.3 Variable Linking</H3>
+
+
+<p> C/C++ global variables are wrapped as a pair of singleton
+methods for the module: one to get the value of the global variable and
+one to set it. For example, the following SWIG interface file declares
+two global variables: </p>
+
+
+
+
+
+<div class="code">
+<pre>// SWIG interface file with global variables<br>%module example<br>...<br>%inline %{<br>extern int variable1;<br>extern double Variable2;<br>%}<br>...<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Now look at the Ruby interface:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>Example.variable1 = 2</b><br>2<br>irb(main):003:0&gt; <b>Example.Variable2 = 4 * 10.3</b><br>41.2<br>irb(main):004:0&gt; <b>Example.Variable2</b><br>41.2<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If you make an error in variable assignment, you will receive
+an error message. For example: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):005:0&gt; <b>Example.Variable2 = "hello"</b><br>TypeError: no implicit conversion to float from string<br>from (irb):5:in `Variable2='<br>from (irb):5<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If a variable is declared as <tt>const</tt>, it
+is wrapped as a read-only variable. Attempts to modify its value will
+result in an error. </p>
+
+
+
+
+
+<p>To make ordinary variables read-only, you can also use the <tt>%immutable</tt>
+directive. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%immutable;<br>%inline %{<br>extern char *path;<br>%}<br>%mutable;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The <tt>%immutable</tt> directive stays in
+effect until it is explicitly disabled using <tt>%mutable</tt>.
+</p>
+
+
+
+
+
+<H3><a name="Ruby_nn15"></a>31.3.4 Constants</H3>
+
+
+<p> C/C++ constants are wrapped as module constants initialized
+to the appropriate value. To create a constant, use <tt>#define</tt>
+or the <tt>%constant</tt> directive. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>#define PI 3.14159<br>#define VERSION "1.0"<br><br>%constant int FOO = 42;<br>%constant const char *path = "/usr/local";<br><br>const int BAR = 32;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Remember to use the :: operator in Ruby to get at these
+constant values, e.g. </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>Example::PI</b><br>3.14159<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn16"></a>31.3.5 Pointers</H3>
+
+
+<p> "Opaque" pointers to arbitrary C/C++ types (i.e. types that
+aren't explicitly declared in your SWIG interface file) are wrapped as
+data objects. So, for example, consider a SWIG interface file
+containing only the declarations: </p>
+
+
+
+
+
+<div class="code">
+<pre>Foo *get_foo();<br>void set_foo(Foo *foo);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> For this case, the <i>get_foo()</i> method
+returns an instance of an internally generated Ruby class: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>foo = Example::get_foo()</b><br>#&lt;SWIG::TYPE_p_Foo:0x402b1654&gt;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> A <tt>NULL</tt> pointer is always represented by
+the Ruby <tt>nil</tt> object. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn17"></a>31.3.6 Structures</H3>
+
+
+<p> C/C++ structs are wrapped as Ruby classes, with accessor
+methods (i.e. "getters" and "setters") for all of the struct members.
+For example, this struct declaration: </p>
+
+
+
+
+
+<div class="code">
+<pre>struct Vector {<br> double x, y;<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> gets wrapped as a <tt>Vector</tt> class, with
+Ruby instance methods <tt>x</tt>, <tt> x=</tt>,
+<tt>y</tt> and <tt>y=</tt>. These methods can
+be used to access structure data from Ruby as follows: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>f = Example::Vector.new</b><br>#&lt;Example::Vector:0x4020b268&gt;<br>irb(main):003:0&gt; <b>f.x = 10</b><br>nil<br>irb(main):004:0&gt; <b>f.x</b><br>10.0<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Similar access is provided for unions and the public data
+members of C++ classes.</p>
+
+
+
+
+
+<p><tt>const</tt> members of a structure are
+read-only. Data members can also be forced to be read-only using the <tt>%immutable</tt>
+directive (in C++, <tt>private</tt> may also be used). For
+example: </p>
+
+
+
+
+
+<div class="code">
+<pre>struct Foo {<br> ...<br> %immutable;<br> int x; /* Read-only members */<br> char *name;<br> %mutable;<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> When <tt>char *</tt> members of a structure are
+wrapped, the contents are assumed to be dynamically allocated using <tt>malloc</tt>
+or <tt>new</tt> (depending on whether or not SWIG is run
+with the <tt>-c++</tt> option). When the structure member
+is set, the old contents will be released and a new value created. If
+this is not the behavior you want, you will have to use a typemap
+(described shortly). </p>
+
+
+
+
+
+<p>Array members are normally wrapped as read-only. For example,
+this code: </p>
+
+
+
+
+
+<div class="code">
+<pre>struct Foo {<br> int x[50];<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> produces a single accessor function like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>int *Foo_x_get(Foo *self) {<br> return self-&gt;x;<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If you want to set an array member, you will need to supply a
+"memberin" typemap described in the <a href="#ruby_cpp_smart_pointers">section on typemaps</a>.
+As a special case, SWIG does generate code to set array members of type
+<tt>char</tt> (allowing you to store a Ruby string in the
+structure). </p>
+
+
+
+
+
+<p>When structure members are wrapped, they are handled as
+pointers. For example, </p>
+
+
+
+
+
+<div class="code">
+<pre>struct Foo {<br> ...<br>};<br><br>struct Bar {<br> Foo f;<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> generates accessor functions such as this: </p>
+
+
+
+
+
+<div class="code">
+<pre>Foo *Bar_f_get(Bar *b) {<br> return &amp;b-&gt;f;<br>}<br><br>void Bar_f_set(Bar *b, Foo *val) {<br> b-&gt;f = *val;<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn18"></a>31.3.7 C++ classes</H3>
+
+
+<p> Like structs, C++ classes are wrapped by creating a new Ruby
+class of the same name with accessor methods for the public class
+member data. Additionally, public member functions for the class are
+wrapped as Ruby instance methods, and public static member functions
+are wrapped as Ruby singleton methods. So, given the C++ class
+declaration: </p>
+
+
+
+
+
+<div class="code">
+<pre>class List {<br>public:<br> List();<br> ~List();<br> int search(char *item);<br> void insert(char *item);<br> void remove(char *item);<br> char *get(int n);<br> int length;<br> static void print(List *l);<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> SWIG would create a <tt>List</tt> class with: </p>
+
+
+
+
+
+<ul>
+
+
+
+
+
+  <li> instance methods <i>search</i>, <i>insert</i>,
+    <i>remove</i>, and <i>get</i>; </li>
+
+
+
+
+
+  <li> instance methods <i>length</i> and <i>length=</i>
+(to get and set the value of the <i>length</i> data
+member); and, </li>
+
+
+
+
+
+  <li> a <i>print</i> singleton method for the
+class. </li>
+
+
+
+
+
+</ul>
+
+
+
+
+
+<p> In Ruby, these functions are used as follows: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>require 'Example'<br><br>l = Example::List.new<br><br>l.insert("Ale")<br>l.insert("Stout")<br>l.insert("Lager")<br>Example.print(l)<br>l.length()<br>----- produces the following output <br>Lager<br>Stout<br>Ale<br>3<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn19"></a>31.3.8 C++ Inheritance</H3>
+
+
+<p> The SWIG type-checker is fully aware of C++ inheritance.
+Therefore, if you have classes like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>class Parent {<br> ...<br>};<br><br>class Child : public Parent {<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> those classes are wrapped into a hierarchy of Ruby classes
+that reflect the same inheritance structure. All of the usual Ruby
+utility methods work normally: </p>
+
+
+
+
+
+<div class="code">
+<pre>irb(main):001:0&gt; <b>c = Child.new</b><br>#&lt;Bar:0x4016efd4&gt;<br>irb(main):002:0&gt; <b>c.instance_of? Child</b><br>true<br>irb(main):003:0&gt; <b>b.instance_of? Parent</b><br>false<br>irb(main):004:0&gt; <b>b.is_a? Child</b><br>true<br>irb(main):005:0&gt; <b>b.is_a? Parent</b><br>true<br>irb(main):006:0&gt; <b>Child &lt; Parent</b><br>true<br>irb(main):007:0&gt; <b>Child &gt; Parent</b><br>false<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Furthermore, if you have a function like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>void spam(Parent *f);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> then the function <tt>spam()</tt> accepts <tt>Parent</tt>*
+or a pointer to any class derived from <tt>Parent</tt>. </p>
+
+
+
+
+
+<p>Until recently, the Ruby module for SWIG didn't support
+multiple inheritance, and this is still the default behavior. This
+doesn't mean that you can't wrap C++ classes which inherit from
+multiple base classes; it simply means that only the <b>first</b>
+base class listed in the class declaration is considered, and any
+additional base classes are ignored. As an example, consider a SWIG
+interface file with a declaration like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> For this case, the resulting Ruby class (<tt>Derived</tt>)
+will only consider <tt>Base1</tt> as its superclass. It
+won't inherit any of <tt>Base2</tt>'s member functions or
+data and it won't recognize <tt>Base2</tt> as an
+"ancestor" of <tt>Derived</tt> (i.e. the <em>is_a?</em>
+relationship would fail). When SWIG processes this interface file,
+you'll see a warning message like: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>example.i:5: Warning(802): Warning for Derived: Base Base2 ignored.<br>Multiple inheritance is not supported in Ruby.<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Starting with SWIG 1.3.20, the Ruby module for SWIG provides
+limited support for multiple inheritance. Because the approach for
+dealing with multiple inheritance introduces some limitations, this is
+an optional feature that you can activate with the <tt>-minherit</tt>
+command-line option: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -c++ -ruby -minherit example.i</b></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Using our previous example, if your SWIG interface file
+contains a declaration like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> and you run SWIG with the <tt>-minherit</tt>
+command-line option, then you will end up with a Ruby class <tt>Derived</tt>
+that appears to "inherit" the member data and functions from both <tt>Base1</tt>
+and <tt>Base2</tt>. What actually happens is that three
+different top-level classes are created, with Ruby's <tt>Object</tt>
+class as their superclass. Each of these classes defines a nested
+module named <tt>Impl</tt>, and it's in these nested <tt>Impl</tt>
+modules that the actual instance methods for the classes are defined,
+i.e. </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>class Base1<br> module Impl<br> # Define Base1 methods here<br> end<br> include Impl<br>end<br><br>class Base2<br> module Impl<br> # Define Base2 methods here<br> end<br> include Impl<br>end<br><br>class Derived<br> module Impl<br> include Base1::Impl<br> include Base2::Impl<br> # Define Derived methods here<br> end<br> include Impl<br>end<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Observe that after the nested <tt>Impl</tt>
+module for a class is defined, it is mixed-in to the class itself. Also
+observe that the <tt>Derived::Impl</tt> module first
+mixes-in its base classes' <tt>Impl</tt> modules, thus
+"inheriting" all of their behavior. </p>
+
+
+
+
+
+<p>The primary drawback is that, unlike the default mode of
+operation, neither <tt>Base1</tt> nor <tt>Base2</tt>
+is a true superclass of <tt>Derived</tt> anymore: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>obj = Derived.new<br>obj.is_a? Base1 # this will return false...<br>obj.is_a? Base2 # ... and so will this<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In most cases, this is not a serious problem since objects of
+type <tt>Derived</tt> will otherwise behave as though they
+inherit from both <tt>Base1</tt> and <tt>Base2</tt>
+(i.e. they exhibit <a href="http://c2.com/cgi/wiki?DuckTyping">"Duck
+Typing"</a>). </p>
+
+
+
+
+
+<H3><a name="Ruby_nn20"></a>31.3.9 C++ Overloaded Functions</H3>
+
+
+<p> C++ overloaded functions, methods, and constructors are
+mostly supported by SWIG. For example, if you have two functions like
+this: </p>
+
+
+
+
+
+<div class="code">
+<pre>void foo(int);<br>void foo(char *c);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> You can use them in Ruby in a straightforward manner: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>foo(3)</b> # foo(int)<br>irb(main):002:0&gt; <b>foo("Hello")</b> # foo(char *c)<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Similarly, if you have a class like this,</p>
+
+
+
+
+
+<div class="code">
+<pre>class Foo {<br>public:<br> Foo();<br> Foo(const Foo &amp;);<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>you can write Ruby code like this:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>f = Foo.new</b> # Create a Foo<br>irb(main):002:0&gt; <b>g = Foo.new(f)</b> # Copy f<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Overloading support is not quite as flexible as in C++.
+Sometimes there are methods that SWIG can't disambiguate. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>void spam(int);<br>void spam(short);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>or</p>
+
+
+
+
+
+<div class="code">
+<pre>void foo(Bar *b);<br>void foo(Bar &amp;b);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If declarations such as these appear, you will get a warning
+message like this: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)<br>at example.i:11.<br> </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To fix this, you either need to ignore or rename one of the
+methods. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%rename(spam_short) spam(short);<br>...<br>void spam(int); <br>void spam(short); // Accessed as spam_short<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>or</p>
+
+
+
+
+
+<div class="code">
+<pre>%ignore spam(short);<br>...<br>void spam(int); <br>void spam(short); // Ignored<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> SWIG resolves overloaded functions and methods using a
+disambiguation scheme that ranks and sorts declarations according to a
+set of type-precedence rules. The order in which declarations appear in
+the input does not matter except in situations where ambiguity
+arises--in this case, the first declaration takes precedence. </p>
+
+
+
+
+
+<p>Please refer to the <a href="SWIGPlus.html#SWIGPlus">"SWIG
+and C++"</a> chapter for more information about overloading. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn21"></a>31.3.10 C++ Operators</H3>
+
+
+<p> For the most part, overloaded operators are handled
+automatically by SWIG and do not require any special treatment on your
+part. So if your class declares an overloaded addition operator, e.g. </p>
+
+
+
+
+
+<div class="code">
+<pre>class Complex {<br> ...<br> Complex operator+(Complex &amp;);<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> the resulting Ruby class will also support the addition (+)
+method correctly. </p>
+
+
+
+
+
+<p>For cases where SWIG's built-in support is not sufficient, C++
+operators can be wrapped using the <tt>%rename</tt>
+directive (available on SWIG 1.3.10 and later releases). All you need
+to do is give the operator the name of a valid Ruby identifier. For
+example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%rename(add_complex) operator+(Complex &amp;, Complex &amp;);<br>...<br>Complex operator+(Complex &amp;, Complex &amp;);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Now, in Ruby, you can do this:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>a = Example::Complex.new(2, 3)<br>b = Example::Complex.new(4, -1)<br>c = Example.add_complex(a, b)<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> More details about wrapping C++ operators into Ruby operators
+is discussed in the <a href="#ruby_operator_overloading">section
+on operator overloading</a>. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn22"></a>31.3.11 C++ namespaces</H3>
+
+
+<p> SWIG is aware of C++ namespaces, but namespace names do not
+appear in the module nor do namespaces result in a module that is
+broken up into submodules or packages. For example, if you have a file
+like this, </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>namespace foo {<br> int fact(int n);<br> struct Vector {<br> double x,y,z;<br> };<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>it works in Ruby as follows:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>Example.fact(3)</b><br>6<br>irb(main):003:0&gt; <b>v = Example::Vector.new</b><br>#&lt;Example::Vector:0x4016f4d4&gt;<br>irb(main):004:0&gt; <b>v.x = 3.4</b><br>3.4<br>irb(main):004:0&gt; <b>v.y</b><br>0.0<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If your program has more than one namespace, name conflicts
+(if any) can be resolved using <tt>%rename</tt> For
+example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%rename(Bar_spam) Bar::spam;<br><br>namespace Foo {<br> int spam();<br>}<br><br>namespace Bar {<br> int spam();<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If you have more than one namespace and your want to keep
+their symbols separate, consider wrapping them as separate SWIG
+modules. For example, make the module name the same as the namespace
+and create extension modules for each namespace separately. If your
+program utilizes thousands of small deeply nested namespaces each with
+identical symbol names, well, then you get what you deserve. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn23"></a>31.3.12 C++ templates</H3>
+
+
+<p> C++ templates don't present a huge problem for SWIG. However,
+in order to create wrappers, you have to tell SWIG to create wrappers
+for a particular template instantiation. To do this, you use the <tt>%template</tt>
+directive. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>%{<br>#include "pair.h"<br>%}<br><br>template&lt;class T1, class T2&gt;<br>struct pair {<br> typedef T1 first_type;<br> typedef T2 second_type;<br> T1 first;<br> T2 second;<br> pair();<br> pair(const T1&amp;, const T2&amp;);<br> ~pair();<br>};<br><br>%template(Pairii) pair&lt;int,int&gt;;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In Ruby:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>p = Example::Pairii.new(3, 4)</b><br>#&lt;Example:Pairii:0x4016f4df&gt;<br>irb(main):003:0&gt; <b>p.first</b><br>3<br>irb(main):004:0&gt; <b>p.second</b><br>4<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn23_1"></a>31.3.13 C++ Standard Template Library (STL)</H3>
+
+
+<p> On a related note, the standard SWIG library contains a
+number of modules that provide typemaps for standard C++ library
+classes (such as <tt>std::pair</tt>, <tt>std::string</tt>
+and <tt>std::vector</tt>). These library modules don't
+provide wrappers around the templates themselves, but they do make it
+convenient for users of your extension module to pass Ruby objects
+(such as arrays and strings) to wrapped C++ code that expects instances
+of standard C++ templates. For example, suppose the C++ library you're
+wrapping has a function that expects a vector of floats: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>float sum(const std::vector&lt;float&gt;&amp; values);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Rather than go through the hassle of writing an "in" typemap
+to convert an array of Ruby numbers into a
+std::vector&lt;float&gt;, you can just use the <tt>std_vector.i</tt>
+module from the standard SWIG library: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br><b>%include std_vector.i</b><br>float sum(const std::vector&lt;float&gt;&amp; values);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Ruby's STL wrappings provide additional methods to make them
+behave more similarly to Ruby's native classes.</p>
+
+
+
+
+
+<p>Thus, you can do, for example:</p>
+
+
+
+
+
+<div class="targetlang">
+<pre>v = IntVector.new<span class="targetlang"><br>v &lt;&lt; 2</span><span class="targetlang"><br>v &lt;&lt; 3<br>v &lt;&lt; 4<br>v.each { |x| puts x }<br><span style="font-weight: bold;"><br>=&gt; 2</span><br style="font-weight: bold;"><span style="font-weight: bold;">3</span><br style="font-weight: bold;"><span style="font-weight: bold;">4<br></span>v.delete_if { |x| x == 3 }<br><span style="font-weight: bold;">=&gt; [2,4]</span></span></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>The SWIG Ruby module provides also the ability for all the STL
+containers to carry around Ruby native objects (Fixnum, Classes, etc)
+making them act almost like Ruby's own Array, Hash, etc. &nbsp; To
+do
+that, you need to define a container that contains a swig::GC_VALUE,
+like:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="code">%module
+nativevector<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+%{<br>
+
+
+
+
+
+std::vector&lt; swig::GC_VALUE &gt; NativeVector;<br>
+
+
+
+
+
+%}<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+%template(NativeVector) std::vector&lt; swig::GC_VALUE &gt;;<br>
+
+
+
+
+
+</div>
+
+
+
+
+
+<br>
+
+
+
+
+
+<p>This vector can then contain any Ruby object, making them
+almost identical to Ruby's own Array class.</p>
+
+
+
+
+
+<div class="targetlang"><span style="font-family: monospace;">require 'nativevector'</span><br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">include NativeVector</span><br style="font-family: monospace;">
+
+
+
+
+
+<br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">v = NativeVector.new</span><br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">v &lt;&lt; 1</span><br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">v &lt;&lt;
+[1,2]</span><br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">v &lt;&lt;
+'hello'</span><br style="font-family: monospace;">
+
+
+
+
+
+<br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">class A; end</span><br style="font-family: monospace;">
+
+
+
+
+
+<br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">v &lt;&lt;
+A.new</span><br style="font-family: monospace;">
+
+
+
+
+
+<br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-family: monospace;">puts v</span><br style="font-family: monospace;">
+
+
+
+
+
+<span style="font-weight: bold; font-family: monospace;">=&gt;
+[1, [1,2], 'hello',&nbsp;#&lt;A:0x245325&gt;]</span></div>
+
+
+
+
+
+<br>
+
+
+
+
+
+<p>Obviously, there is a lot more to template wrapping than
+shown in these examples. More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>
+chapter.</p>
+
+
+
+
+
+<H3><a name="C_STL_Functors"></a>31.3.14 C++ STL Functors</H3>
+
+
+<p>Some containers in the STL allow you to modify their default
+behavior by using so called functors or function objects.
+&nbsp;Functors are often just a very simple struct with<span style="font-family: monospace;"> operator()</span>
+redefined or an actual C/C++ function. &nbsp;This allows you, for
+example, to always keep the sort order of a STL container to your
+liking.</p>
+
+
+
+
+
+<p>The Ruby STL mappings allows you to modify those containers
+that
+support functors using Ruby procs or methods, instead.
+&nbsp;Currently,
+this includes <span style="font-family: monospace;">std::set</span>,
+<span style="font-family: monospace;">set::map</span>,
+<span style="font-family: monospace;">std::multiset</span>
+and <span style="font-family: monospace;">std::multimap</span>.</p>
+
+
+
+
+
+<p>The functors in swig are called<span style="font-family: monospace;"> swig::UnaryFunction</span>
+and <span style="font-family: monospace;">swig::BinaryFunction</span>.<br>
+
+
+
+
+
+For C++ predicates (ie. functors that must return bool as a result) <span style="font-family: monospace;">swig::UnaryPredicate</span>
+and <span style="font-family: monospace;">swig::BinaryPredicate</span>
+are provided.</p>
+
+
+
+
+
+<p>As an example, if given this swig file:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="code">%module
+intset;<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+%include std_set.i<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+%typemap(IntSet)&nbsp; std::set&lt; int, swig::BinaryPredicate
+&gt;;</div>
+
+
+
+
+
+<p>You can then use the set from Ruby with or without a proc
+object as a predicate:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="targetlang">require
+'intset'<br>
+
+
+
+
+
+include Intset<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+# Default sorting behavior defined in C++<br>
+
+
+
+
+
+a = IntSet.new<br>
+
+
+
+
+
+a &lt;&lt; 1<br>
+
+
+
+
+
+a &lt;&lt; 2<br>
+
+
+
+
+
+a &lt;&lt; 3<br>
+
+
+
+
+
+a<br>
+
+
+
+
+
+<span style="font-weight: bold;">=&gt;
+&nbsp;[1,2,3]</span><br>
+
+
+
+
+
+<br>
+
+
+
+
+
+# Custom sorting behavior defined by a Ruby proc
+<div><span class="targetlang">b = IntSet.new( proc {
+|a,b| a &gt; b } )</span><br>
+
+
+
+
+
+b&nbsp;&lt;&lt; 1<br>
+
+
+
+
+
+b&nbsp;&lt;&lt; 2<br>
+
+
+
+
+
+b&nbsp;&lt;&lt; 3<br>
+
+
+
+
+
+b<br style="font-weight: bold;">
+
+
+
+
+
+<span style="font-weight: bold;">=&gt;
+&nbsp;[3,2,1]</span> </div>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_C_Iterators"></a>31.3.15 C++ STL Iterators</H3>
+
+
+<p>The STL is well known for the use of iterators. &nbsp;There
+are a number of iterators possible with different properties, but in
+general there are two main categories: const iterators and non-const
+iterators. &nbsp;The const iterators can access and not modify the
+values they point at, while the non-const iterators can both read and
+modify the values.</p>
+
+
+
+
+
+<p>The Ruby STL wrappings support both type of iterators by using
+a proxy class in-between. &nbsp;This proxy class is <span style="font-family: monospace;">swig::Iterator or
+swig::ConstIterator. &nbsp;</span>Derived from them are template
+classes that need to be initialized with the actual iterator for the
+container you are wrapping and often times with the beginning and
+ending points of the iteration range.&nbsp;</p>
+
+
+
+
+
+<p>The SWIG STL library already provides typemaps to all the
+standard containers to do this wrapping automatically for you, but if
+you have your own STL-like iterator, you will need to write your own
+typemap for them.&nbsp;&nbsp;For out typemaps, the special functions <span style="font-family: monospace;">make_const_iterator</span> and <span style="font-family: monospace;">make_nonconst_iterator</span> are provided.</p>
+
+<p>These can be used either like:</p>
+
+<div style="font-family: monospace;" class="code">make_const_iterator( iterator, rubyclass );<br>
+
+make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );</div>
+
+
+
+
+
+<p>The iterators support a <span style="font-family: monospace;">next()</span> and <span style="font-family: monospace;">previous()&nbsp;</span>member function to
+just change the iterator without returning anything. &nbsp;<span style="font-family: monospace;">previous()</span>
+should obviously only be used for bidirectional iterators. &nbsp;You
+can also advance the iterator multiple steps by using standard math
+operations like <span style="font-family: monospace;">+=</span>.</p>
+
+<p>The
+value&nbsp;the iterator points at can be accessed with <span style="font-family: monospace;">value()</span> -- this is equivalent to dereferencing it with <span style="font-family: monospace;">*i</span>.
+&nbsp; For non-const iterators, a <span style="font-family: monospace;">value=()</span> function
+is also provided which allows you to change the value pointed by the
+iterator. &nbsp;This is equivalent to the C++ construct of dereferencing and assignment, like <span style="font-family: monospace;">*i = something</span>.&nbsp;</p>
+
+
+
+
+
+<p>Thus, given say a vector class of doubles defined as:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="code"><span class="code">%module doublevector</span><br class="code">
+
+
+
+
+
+<span class="code"><br>
+
+
+
+
+
+%include std_vector.i</span><br class="code">
+
+
+
+
+
+<span class="code"><br>
+
+
+
+
+
+%template(DoubleVector) std::vector&lt;double&gt;;</span></div>
+
+
+
+
+
+<p>Its iterator can then be used from Ruby like:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="targetlang">require
+'doublevector'<br>
+
+
+
+
+
+include Doublevector<br>
+
+<br>
+
+
+
+
+
+v = DoubleVector.new<br>
+
+
+
+
+
+v &lt;&lt; 1<br>
+
+
+
+
+
+v &lt;&lt; 2<br>
+
+
+
+
+
+v &lt;&lt; 3<br>
+
+<br>
+
+#<br>
+
+# an elaborate and less efficient way of doing v.map! { |x| x+2 }<br>
+
+#<br>
+
+
+
+
+
+i = v.begin<br>
+
+
+
+
+
+e = v.end<br>
+
+
+
+
+
+while i != e<br>
+
+
+
+
+
+&nbsp; val = i.value<br>
+
+
+
+
+
+&nbsp; val += 2<br>
+
+
+
+
+
+&nbsp; i.value = val<br>
+
+
+
+
+
+&nbsp; i.next<br>
+
+
+
+
+
+end<br>
+
+
+
+
+i<br>
+
+
+
+
+<span style="font-weight: bold;">&gt;&gt; [3, 4, 5 ]</span></div>
+
+
+
+
+
+<br>
+
+<p>If you'd rather have STL classes without any iterators, you should define<span style="font-family: monospace;"> -DSWIG_NO_EXPORT_ITERATOR_METHODS </span>when running swig.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn24"></a>31.3.16 C++ Smart Pointers</H3>
+
+
+<p> In certain C++ programs, it is common to use classes that
+have been wrapped by so-called "smart pointers." Generally, this
+involves the use of a template class that implements <tt>operator-&gt;()</tt>
+like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>template&lt;class T&gt; class SmartPtr {<br> ...<br> T *operator-&gt;();<br> ...<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Then, if you have a class like this,</p>
+
+
+
+
+
+<div class="code">
+<pre>class Foo {<br>public:<br> int x;<br> int bar();<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>A smart pointer would be used in C++ as follows:</p>
+
+
+
+
+
+<div class="code">
+<pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)<br>...<br>p-&gt;x = 3; // Foo::x<br>int y = p-&gt;bar(); // Foo::bar<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To wrap this in Ruby, simply tell SWIG about the <tt>SmartPtr</tt>
+class and the low-level <tt>Foo</tt> object. Make sure you
+instantiate <tt>SmartPtr</tt> using <tt>%template</tt>
+if necessary. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br>...<br>%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;<br>...<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Now, in Ruby, everything should just "work":</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>p = Example::CreateFoo()</b> # Create a smart-pointer somehow<br>#&lt;Example::SmartPtrFoo:0x4016f4df&gt;<br>irb(main):002:0&gt; <b>p.x = 3</b> # Foo::x<br>3<br>irb(main):003:0&gt; <b>p.bar()</b> # Foo::bar<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If you ever need to access the underlying pointer returned by
+<tt>operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt>
+method. For example: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):004:0&gt; <b>f = p.__deref__()</b> # Returns underlying Foo *<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn25"></a>31.3.17 Cross-Language Polymorphism</H3>
+
+
+<p> SWIG's Ruby module supports cross-language polymorphism
+(a.k.a. the "directors" feature) similar to that for SWIG's Python
+module. Rather than duplicate the information presented in the <a href="Ruby">Python</a> chapter, this
+section just notes the differences that you need to be aware of when
+using this feature with Ruby. </p>
+
+
+
+
+
+<H4><a name="Ruby_nn26"></a>31.3.17.1 Exception Unrolling</H4>
+
+
+<p> Whenever a C++ director class routes one of its virtual
+member function calls to a Ruby instance method, there's always the
+possibility that an exception will be raised in the Ruby code. By
+default, those exceptions are ignored, which simply means that the
+exception will be exposed to the Ruby interpreter. If you would like to
+change this behavior, you can use the <tt>%feature("director:except")</tt>
+directive to indicate what action should be taken when a Ruby exception
+is raised. The following code should suffice in most cases: </p>
+
+
+
+
+
+<div class="code">
+<pre>%feature("director:except") {<br> throw Swig::DirectorMethodException($error);<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> When this feature is activated, the call to the Ruby instance
+method is "wrapped" using the <tt>rb_rescue2()</tt>
+function from Ruby's C API. If any Ruby exception is raised, it will be
+caught here and a C++ exception is raised in its place. </p>
+
+
+
+
+
+<H2><a name="Ruby_nn27"></a>31.4 Naming</H2>
+
+
+<p>Ruby has several common naming conventions. Constants are
+generally
+in upper case, module and class names are in camel case and methods are
+in lower case with underscores. For example: </p>
+
+
+
+
+
+<div class="code">
+<ul>
+
+
+
+
+
+  <li><strong>MATH::PI</strong> is a constant name</li>
+
+
+
+
+
+  <li><strong>MyClass</strong> is a class name</li>
+
+
+
+
+
+  <li><strong>my_method</strong> is a method name</li>
+
+
+
+
+
+</ul>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Prior to version 1.3.28, SWIG did not support these Ruby
+conventions. The only modifications it made to names was to capitalize
+the first letter of constants (which includes module and class names).</p>
+
+
+
+
+
+<p>SWIG 1.3.28 introduces the new -autorename command line
+parameter.
+When this parameter is specified, SWIG will automatically change
+constant, class and method names to conform with the standard Ruby
+naming conventions. For example: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -ruby -autorename example.i</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>To disable renaming use the -noautorename command line option.</p>
+
+
+
+
+
+<p>Since this change significantly changes the wrapper code
+generated
+by SWIG, it is turned off by default in SWIG 1.3.28. However, it is
+planned to become the default option in future releases.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn28"></a>31.4.1 Defining Aliases</H3>
+
+
+<p> It's a fairly common practice in the Ruby built-ins and
+standard library to provide aliases for method names. For example, <em>Array#size</em>
+is an alias for <em>Array#length</em>. If you would like
+to provide an alias for one of your class' instance methods, one
+approach is to use SWIG's <tt>%extend</tt> directive to
+add a new method of the aliased name that calls the original function.
+For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>class MyArray {<br>public:<br> // Construct an empty array<br> MyArray();<br> <br> // Return the size of this array<br> size_t length() const;<br>};<br><br>%extend MyArray {<br> // MyArray#size is an alias for MyArray#length<br> size_t size() const {<br> return $self-&gt;length();<br> }<br>}<br> </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> A better solution is to use the <tt>%alias</tt>
+directive (unique to SWIG's Ruby module). The previous example could
+then be rewritten as: </p>
+
+
+
+
+
+<div class="code">
+<pre>// MyArray#size is an alias for MyArray#length<br>%alias MyArray::length "size";<br><br>class MyArray {<br>public:<br> // Construct an empty array<br> MyArray();<br> <br> // Return the size of this array<br> size_t length() const;<br>};<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Multiple aliases can be associated with a method by providing
+a comma-separated list of aliases to the <tt>%alias</tt>
+directive, e.g. </p>
+
+
+
+
+
+<div class="code">
+<pre>%alias MyArray::length "amount,quantity,size";</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> From an end-user's standpoint, there's no functional
+difference between these two approaches; i.e. they should get the same
+result from calling either <em>MyArray#size</em> or <em>MyArray#length</em>.
+However, when the <tt>%alias</tt> directive is used, SWIG
+doesn't need to generate all of the wrapper code that's usually
+associated with added methods like our <em>MyArray::size()</em>
+example. </p>
+
+
+
+
+
+<p>Note that the <tt>%alias</tt> directive is
+implemented using SWIG's "features" mechanism and so the same name
+matching rules used for other kinds of features apply (see the chapter
+on <a href="Customization.html#Customization">"Customization
+Features"</a>) for more details).</p>
+
+
+
+
+
+<H3><a name="Ruby_nn29"></a>31.4.2 Predicate Methods</H3>
+
+
+<p> Ruby methods that return a boolean value and end in a
+question mark
+are known as predicate methods. Examples of predicate methods in
+standard Ruby classes include <em>Array#empty?</em> (which
+returns <tt>true</tt> for an array containing no elements)
+and <em>Object#instance_of?</em> (which returns <tt>true</tt>
+if the object is an instance of the specified class). For consistency
+with Ruby conventions, methods that return boolean values should be
+marked as predicate methods.</p>
+
+
+
+
+
+<p>One cumbersome solution to this problem is to rename the
+method (using SWIG's <tt>%rename</tt> directive) and
+provide a custom typemap that converts the function's actual return
+type to Ruby's <tt>true</tt> or <tt>false</tt>.
+For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%rename("is_it_safe?") is_it_safe();<br><br>%typemap(out) int is_it_safe <br> "$result = ($1 != 0) ? Qtrue : Qfalse;";<br><br>int is_it_safe();<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> A better solution is to use the <tt>%predicate</tt>
+directive (unique to SWIG's Ruby module) to designate a method as a
+predicate method. For the previous example, this would look like: </p>
+
+
+
+
+
+<div class="code">
+<pre>%predicate is_it_safe();<br><br>int is_it_safe();<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>This method would be invoked from Ruby code like this:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):001:0&gt; <b>Example::is_it_safe?</b><br>true<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The <tt>%predicate</tt> directive is implemented
+using SWIG's "features" mechanism and so the same name matching rules
+used for other kinds of features apply (see the chapter on <a href="Customization.html#Customization">"Customization
+Features"</a>) for more details). </p>
+
+
+
+
+
+<H3><a name="Ruby_nn30"></a>31.4.3 Bang Methods</H3>
+
+
+<p> Ruby methods that modify an object in-place and end in an
+exclamation mark are known as bang methods. An example of a bang method
+is <em>Array#sort!</em> which changes the ordering of
+items in an array. Contrast this with <em>Array#sort</em>,
+which returns a copy of the array with the items sorted instead of
+modifying the original array. For consistency with Ruby conventions,
+methods that modify objects in place should be marked as bang methods.</p>
+
+
+
+
+
+<p>Bang methods can be marked using the <tt>%bang</tt>
+directive which is unique to the Ruby module and was introduced in SWIG
+1.3.28. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%bang sort!(arr);<br><br>int sort(int arr[]); </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>This method would be invoked from Ruby code like this:</p>
+
+
+
+
+
+<div class="code">
+<pre>irb(main):001:0&gt; <b>Example::sort!(arr)</b></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The <tt>%bang</tt> directive is implemented
+using SWIG's "features" mechanism and so the same name matching rules
+used for other kinds of features apply (see the chapter on <a href="Customization.html#Customization">"Customization
+Features"</a>) for more details). </p>
+
+
+
+
+
+<H3><a name="Ruby_nn31"></a>31.4.4 Getters and Setters</H3>
+
+
+<p> Often times a C++ library will expose properties through
+getter and setter methods. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>class Foo {<br>	Foo() {}<br><br> int getValue() { return value_; }<br><br> void setValue(int value) { value_ = value; }<br><br>private:<br> int value_;<br>};</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>By default, SWIG will expose these methods to Ruby as <tt>get_value</tt>
+and <tt>set_value.</tt> However, it more natural for these
+methods to be exposed in Ruby as <tt>value</tt> and <tt>value=.
+</tt> That allows the methods to be used like this:</p>
+
+
+
+
+
+<div class="code">
+<pre>irb(main):001:0&gt; <b>foo = Foo.new()</b><br>irb(main):002:0&gt; <b>foo.value = 5</b><br>irb(main):003:0&gt; <b>puts foo.value</b></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> This can be done by using the %rename directive:</p>
+
+
+
+
+
+<div class="code">
+<pre>%rename("value") Foo::getValue();<br>%rename("value=") Foo::setValue(int value);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>&nbsp;</p>
+
+
+
+
+
+<H2><a name="Ruby_nn32"></a>31.5 Input and output parameters</H2>
+
+
+<p> A common problem in some C programs is handling parameters
+passed as simple pointers. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>void add(int x, int y, int *result) {<br> *result = x + y;<br>}<br>or<br>int sub(int *x, int *y) {<br> return *x-*y;<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The easiest way to handle these situations is to use the <tt>typemaps.i</tt>
+file. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module Example<br>%include "typemaps.i"<br><br>void add(int, int, int *OUTPUT);<br>int sub(int *INPUT, int *INPUT);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In Ruby, this allows you to pass simple values. For example:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>a = Example.add(3,4)<br>puts a<br>7<br>b = Example.sub(7,4)<br>puts b<br>3<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Notice how the <tt>INPUT</tt> parameters allow
+integer values to be passed instead of pointers and how the <tt>OUTPUT</tt>
+parameter creates a return result. </p>
+
+
+
+
+
+<p>If you don't want to use the names <tt>INPUT</tt>
+or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
+directive. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module Example<br>%include "typemaps.i"<br><br>%apply int *OUTPUT { int *result };<br>%apply int *INPUT { int *x, int *y};<br><br>void add(int x, int y, int *result);<br>int sub(int *x, int *y);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> If a function mutates one of its parameters like this, </p>
+
+
+
+
+
+<div class="code">
+<pre>void negate(int *x) {<br> *x = -(*x);<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>you can use <tt>INOUT</tt> like this:</p>
+
+
+
+
+
+<div class="code">
+<pre>%include "typemaps.i"<br>...<br>void negate(int *INOUT);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In Ruby, a mutated parameter shows up as a return value. For
+example:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>a = Example.negate(3)<br>print a<br>-3<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The most common use of these special typemap rules is to
+handle functions that return more than one value. For example,
+sometimes a function returns a result as well as a special error code: </p>
+
+
+
+
+
+<div class="code">
+<pre>/* send message, return number of bytes sent, success code, and error_code */<br>int send_message(char *text, int *success, int *error_code);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To wrap such a function, simply use the <tt>OUTPUT</tt>
+rule above. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br>%include "typemaps.i"<br>...<br>int send_message(char *, int *OUTPUT, int *OUTPUT);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> When used in Ruby, the function will return an array of
+multiple values. </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>bytes, success, error_code = send_message("Hello World")<br>if not success<br> print "error #{error_code} : in send_message"<br>else<br> print "Sent", bytes<br>end<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Another way to access multiple return values is to use the <tt>%apply</tt>
+rule. In the following example, the parameters rows and columns are
+related to SWIG as <tt>OUTPUT</tt> values through the use
+of <tt>%apply</tt> </p>
+
+
+
+
+
+<div class="code">
+<pre>%module Example<br>%include "typemaps.i"<br>%apply int *OUTPUT { int *rows, int *columns };<br>...<br>void get_dimensions(Matrix *m, int *rows, int*columns);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In Ruby:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>r, c = Example.get_dimensions(m)<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H2><a name="Ruby_nn33"></a>31.6 Exception handling </H2>
+
+
+<H3><a name="Ruby_nn34"></a>31.6.1 Using the %exception directive </H3>
+
+
+<p>The SWIG <tt>%exception</tt> directive can be
+used to define a user-definable exception handler that can convert
+C/C++ errors into Ruby exceptions. The chapter on <a href="Customization.html#Customization">Customization
+Features</a> contains more details, but suppose you have a C++
+class like the following : </p>
+
+
+
+
+
+<div class="code">
+<pre>class DoubleArray {<br> private:<br> int n;<br> double *ptr;<br> public:<br> // Create a new array of fixed size<br> DoubleArray(int size) {<br> ptr = new double[size];<br> n = size;<br> }<br><br> // Destroy an array<br> ~DoubleArray() {<br> delete ptr;<br> } <br><br> // Return the length of the array<br> int length() {<br> return n;<br> }<br><br> // Get an array item and perform bounds checking.<br> double getitem(int i) {<br> if ((i &gt;= 0) &amp;&amp; (i &lt; n))<br> return ptr[i];<br> else<br> throw RangeError();<br> }<br><br> // Set an array item and perform bounds checking.<br> void setitem(int i, double val) {<br> if ((i &gt;= 0) &amp;&amp; (i &lt; n))<br> ptr[i] = val;<br> else {<br> throw RangeError();<br> }<br> }<br> };<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Since several methods in this class can throw an exception
+for an out-of-bounds access, you might want to catch this in the Ruby
+extension by writing the following in an interface file: </p>
+
+
+
+
+
+<div class="code">
+<pre>%exception {<br> try {<br> $action<br> }<br> catch (const RangeError&amp;) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error.");<br> }<br>}<br><br>class DoubleArray {<br> ...<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The exception handling code is inserted directly into
+generated wrapper functions. When an exception handler is defined,
+errors can be caught and used to gracefully raise a Ruby exception
+instead of forcing the entire program to terminate with an uncaught
+error. </p>
+
+
+
+
+
+<p>As shown, the exception handling code will be added to every
+wrapper function. Because this is somewhat inefficient, you might
+consider refining the exception handler to only apply to specific
+methods like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>%exception getitem {<br> try {<br> $action<br> }<br> catch (const RangeError&amp;) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error in getitem.");<br> }<br>}<br><br>%exception setitem {<br> try {<br> $action<br> }<br> catch (const RangeError&amp;) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error in setitem.");<br> }<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In this case, the exception handler is only attached to
+methods and functions named <tt>getitem</tt> and <tt>setitem</tt>.
+</p>
+
+
+
+
+
+<p>Since SWIG's exception handling is user-definable, you are not
+limited to C++ exception handling. See the chapter on <a href="Customization.html#Customization">Customization
+Features</a> for more examples.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn34_2"></a>31.6.2 Handling Ruby Blocks </H3>
+
+
+<p>One of the highlights of Ruby and most of its standard library
+is
+the use of blocks, which allow the easy creation of continuations and
+other niceties. &nbsp;Blocks in ruby are also often used to
+simplify the passing of many arguments to a class.</p>
+
+
+
+
+
+<p>In order to make your class constructor support blocks, you
+can take advantage of the %exception directive, which will get run
+after the C++ class' constructor was called.&nbsp;</p>
+
+
+
+
+
+<p>For example, this yields the class over after its
+construction:
+<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code">
+<pre>class Window<br>{<br>public:<br> Window(int x, int y, int w, int h);<br>// .... other methods here ....<br>};<br><br>// Add support for yielding self in the Class' constructor.<br>%exception Window::Window {<br> $action<br> if (rb_block_given_p()) {<br> rb_yield(self);<br> }<br>}</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Then, in ruby, it can be used like:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="targetlang">Window.new(0,0,360,480)
+{ |w|<br>
+
+
+
+
+
+&nbsp;&nbsp;&nbsp; w.color = Fltk::RED<br>
+
+
+
+
+
+&nbsp;&nbsp;&nbsp; w.border = false<br>
+
+
+
+
+
+<span class="targetlang">}</span></div>
+
+
+
+
+
+<br>
+
+
+
+
+
+<p>For other methods, you can usually use a dummy parameter with
+a special in typemap, like:</p>
+
+
+
+
+
+<div class="code" style="font-family: monospace;">//<br>
+
+
+
+
+
+// original function was:<br>
+
+
+
+
+
+//<br>
+
+
+
+
+
+// void func(int x);<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+%typemap(in,numinputs=0) int RUBY_YIELD_SELF {<br>
+
+
+
+
+
+&nbsp; &nbsp; &nbsp;if ( !rb_block_given_p() )<br>
+
+
+
+
+
+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
+rb_raise("No block given");<br>
+
+
+
+
+
+&nbsp; &nbsp; &nbsp;return rb_yield(self);<br>
+
+
+
+
+
+}<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+%extend {<br>
+
+
+
+
+
+&nbsp; &nbsp; &nbsp; &nbsp; void func(int x, int
+RUBY_YIELD_SELF );<br>
+
+
+
+
+
+}</div>
+
+
+
+
+
+<p>For more information on typemaps, see <a href="#Ruby_nn37">Typemaps</a>.</p>
+
+
+<H3><a name="Ruby_nn35"></a>31.6.3 Raising exceptions </H3>
+
+
+<p>There are three ways to raise exceptions from C++ code to
+Ruby. </p>
+
+
+
+
+
+<p>The first way is to use <tt>SWIG_exception(int code,
+const char *msg)</tt>. The following table shows the mappings
+from SWIG error codes to Ruby exceptions:</p>
+
+
+
+
+
+<div class="diagram">
+<table class="diagram" summary="Mapping between SWIG error codes and Ruby exceptions." border="1" width="80%">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_MemoryError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eNoMemError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_IOError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eIOError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_RuntimeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eRuntimeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_IndexError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eIndexError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_TypeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eTypeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_DivisionByZero</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eZeroDivError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_OverflowError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eRangeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_SyntaxError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eSyntaxError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_ValueError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eArgError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_SystemError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eFatal</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_AttributeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eRuntimeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_NullReferenceError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eNullReferenceError*</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_ObjectPreviouslyDeletedError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eObjectPreviouslyDeleted*</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td class="diagram" style="font-family: monospace;">
+      
+      
+      
+      
+      <div>SWIG_UnknownError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+      <td style="font-family: monospace;">
+      
+      
+      
+      
+      <div>rb_eRuntimeError</div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr class="diagram" style="font-family: monospace;">
+
+
+
+
+
+      <td colspan="2">
+      
+      
+      
+      
+      <div>* These error classes are created by
+SWIG and are not built-in Ruby exception classes </div>
+
+
+
+
+
+      </td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>The second way to raise errors is to use <tt>SWIG_Raise(obj,
+type, desc)</tt>.
+Obj is a C++ instance of an exception class, type is a string
+specifying the type of exception (for example, "MyError") and desc is
+the SWIG description of the exception class. For example: </p>
+
+
+
+
+
+<div style="font-family: monospace;" class="code">
+%raise(SWIG_NewPointerObj(e,
+SWIGTYPE_p_AssertionFailedException,
+0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);</div>
+
+
+
+
+
+<p>This is useful when you want to pass the current exception
+object
+directly to Ruby, particularly when the object is an instance of class
+marked as an <tt>%exceptionclass</tt> (see the next
+section for more information).</p>
+
+
+
+
+
+<p>Last, you can raise an exception by directly calling Ruby's C
+api. This is done by invoking the <tt>rb_raise()</tt>
+function. The first argument passed to <tt>rb_raise()</tt>
+is the exception type. You can raise a custom exception type or one of
+the built-in Ruby exception types.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn36"></a>31.6.4 Exception classes </H3>
+
+
+<p>Starting with SWIG 1.3.28, the Ruby module supports the <tt>%exceptionclass</tt>
+directive, which is used to identify C++ classes that are used as
+exceptions. Classes that are marked with the <tt>%exceptionclass</tt>
+directive are exposed in Ruby as child classes of <tt>rb_eRuntimeError</tt>.
+This allows C++ exceptions to be directly mapped to Ruby exceptions,
+providing for a more natural integration between C++ code and Ruby code.</p>
+
+
+
+
+
+<div class="code">
+<pre>	%exceptionclass CustomError;<br>	<br>	%inline %{<br>	class CustomError { };<br>	<br>	class Foo { <br>	public:<br>	void test() { throw CustomError; }<br>	};<br>	}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>From Ruby you can now call this method like this: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>foo = Foo.new<br>begin<br> foo.test()<br>rescue CustomError =&gt; e<br> puts "Caught custom error"<br>end </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>For another example look at swig/Examples/ruby/exception_class.<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<H2><a name="Ruby_nn37"></a>31.7 Typemaps</H2>
+
+
+<p> This section describes how you can modify SWIG's default
+wrapping behavior for various C/C++ datatypes using the <tt>%typemap</tt>
+directive. This is an advanced topic that assumes familiarity with the
+Ruby C API as well as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>"
+chapter.&nbsp;
+</p>
+
+
+
+
+
+<p>Before proceeding, it should be stressed that typemaps are not
+a required part of using SWIG---the default wrapping behavior is enough
+in most cases. Typemaps are only used if you want to change some aspect
+of the primitive C-Ruby interface.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn38"></a>31.7.1 What is a typemap?</H3>
+
+
+<p> A typemap is nothing more than a code generation rule that is
+attached to a specific C datatype. The general form of this declaration
+is as follows ( parts enclosed in [...] are optional
+):&nbsp;&nbsp; &nbsp;</p>
+
+
+
+
+
+<div class="code"><span style="font-family: monospace;" class="code">%typemap( method [, modifiers...] ) typelist
+code; </span></div>
+
+
+
+
+
+<p><em> method</em> is a simply a name that specifies
+what kind of typemap is being defined. It is usually a name like <tt>"in"</tt>,
+<tt>"out"</tt>, or <tt>"argout"</tt> (or its
+director variations). The purpose of these methods is described later.</p>
+
+
+
+
+
+<p><em> modifiers</em> is an optional comma separated
+list of <tt>
+name="value"</tt> values. These are sometimes to attach extra
+information to a typemap and is often target-language dependent.</p>
+
+
+
+
+
+<p><em> typelist</em> is a list of the C++ type
+patterns that the typemap will match. The general form of this list is
+as follows:</p>
+
+
+
+
+
+<div class="diagram">
+<pre>typelist : typepattern [, typepattern, typepattern, ... ] ;<br><br>typepattern : type [ (parms) ]<br> | type name [ (parms) ]<br> | ( typelist ) [ (parms) ]<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Each type pattern is either a simple type, a simple type and
+argument name, or a list of types in the case of multi-argument
+typemaps. In addition, each type pattern can be parameterized with a
+list of temporary variables (parms). The purpose of these variables
+will be explained shortly.</p>
+
+
+
+
+
+<p><em>code</em> specifies the C code used in the
+typemap. It can take any one of the following forms:</p>
+
+
+
+
+
+<div class="diagram">
+<pre>code : { ... }<br> | " ... "<br> | %{ ... %}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>For example, to convert integers
+from Ruby to C, you might define a typemap like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>%typemap(in) int {<br> $1 = (int) NUM2INT($input);<br> printf("Received an integer : %d\n",$1);<br>}<br><br>%inline %{<br>extern int fact(int n);<br>%}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Typemaps are always associated with some specific aspect of
+code generation. In this case, the "in" method refers to the conversion
+of input arguments to C/C++. The datatype <tt>int</tt> is
+the datatype to which the typemap will be applied. The supplied C code
+is used to convert values. In this code a number of special variables
+prefaced by a <tt>$</tt> are used. The <tt>$1</tt>
+variable is placeholder for a local variable of type <tt>int</tt>.
+The <tt>$input</tt> variable is the input Ruby object. </p>
+
+
+
+
+
+<p>When this example is compiled into a Ruby module, the
+following sample code: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>require 'example'<br><br>puts Example.fact(6)<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>prints the result:</p>
+
+
+
+
+
+<div class="code shell">
+<pre>Received an integer : 6<br>720<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In this example, the typemap is applied to all occurrences of
+the <tt>int</tt> datatype. You can refine this by
+supplying an optional parameter name. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>%typemap(in) int n {<br> $1 = (int) NUM2INT($input);<br> printf("n = %d\n",$1);<br>}<br><br>%inline %{<br>extern int fact(int n);<br>%}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In this case, the typemap code is only attached to arguments
+that exactly match "<tt>int n</tt>". </p>
+
+
+
+
+
+<p>The application of a typemap to specific datatypes and
+argument names involves more than simple text-matching--typemaps are
+fully integrated into the SWIG type-system. When you define a typemap
+for <tt>int</tt>, that typemap applies to <tt>int</tt>
+and qualified variations such as <tt>const int</tt>. In
+addition, the typemap system follows <tt>typedef</tt>
+declarations. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) int n {<br> $1 = (int) NUM2INT($input);<br> printf("n = %d\n",$1);<br>}<br><br>typedef int Integer;<br>extern int fact(Integer n); // Above typemap is applied<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> However, the matching of <tt>typedef</tt> only
+occurs in one direction. If you defined a typemap for <tt>Integer</tt>,
+it is not applied to arguments of type <tt>int</tt>. </p>
+
+
+
+
+
+<p>Typemaps can also be defined for groups of consecutive
+arguments. For example: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (char *str, int len) {<br> $1 = STR2CSTR($input);<br> $2 = (int) RSTRING($input)-&gt;len;<br>};<br><br>int count(char c, char *str, int len);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> When a multi-argument typemap is defined, the arguments are
+always handled as a single Ruby object. This allows the function <tt>count</tt>
+to be used as follows (notice how the length parameter is omitted): </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>puts Example.count('o','Hello World')<br>2<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_Typemap_scope"></a>31.7.2 Typemap scope</H3>
+
+
+<p> Once defined, a typemap remains in effect for all of the
+declarations that follow. A typemap may be redefined for different
+sections of an input file. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>// typemap1<br>%typemap(in) int {<br>...<br>}<br><br>int fact(int); // typemap1<br>int gcd(int x, int y); // typemap1<br><br>// typemap2<br>%typemap(in) int {<br>...<br>}<br><br>int isprime(int); // typemap2<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> One exception to the typemap scoping rules pertains to the <tt>
+%extend</tt> declaration. <tt>%extend</tt> is used
+to attach new declarations to a class or structure definition. Because
+of this, all of the declarations in an <tt>%extend</tt>
+block are subject to the typemap rules that are in effect at the point
+where the class itself is defined. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>class Foo {<br> ...<br>};<br><br>%typemap(in) int {<br> ...<br>}<br><br>%extend Foo {<br> int blah(int x); // typemap has no effect. Declaration is attached to Foo which <br> // appears before the %typemap declaration.<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_Copying_a_typemap"></a>31.7.3 Copying a typemap</H3>
+
+
+<p> A typemap is copied by using assignment. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) Integer = int;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> or this:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) Integer, Number, int32_t = int;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Types are often managed by a collection of different
+typemaps. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) int { ... }<br>%typemap(out) int { ... }<br>%typemap(varin) int { ... }<br>%typemap(varout) int { ... }<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To copy all of these typemaps to a new type, use <tt>%apply</tt>.
+For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%apply int { Integer }; // Copy all int typemaps to Integer<br>%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The patterns for <tt>%apply</tt> follow the same
+rules as for <tt>
+%typemap</tt>. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%apply int *output { Integer *output }; // Typemap with name<br>%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_Deleting_a_typemap"></a>31.7.4 Deleting a typemap</H3>
+
+
+<p> A typemap can be deleted by simply defining no code. For
+example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) int; // Clears typemap for int<br>%typemap(in) int, long, short; // Clears typemap for int, long, short<br>%typemap(in) int *output; <br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The <tt>%clear</tt> directive clears all
+typemaps for a given type. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%clear int; // Removes all types for int<br>%clear int *output, long *output;<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p><b> Note:</b> Since SWIG's default behavior is
+defined by typemaps, clearing a fundamental type like <tt>int</tt>
+will make that type unusable unless you also define a new set of
+typemaps immediately after the clear operation.</p>
+
+
+
+
+
+<H3><a name="Ruby_Placement_of_typemaps"></a>31.7.5 Placement of typemaps</H3>
+
+
+<p> Typemap declarations can be declared in the global scope,
+within a C++ namespace, and within a C++ class. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) int {<br> ...<br>}<br><br>namespace std {<br> class string;<br> %typemap(in) string {<br> ...<br> }<br>}<br><br>class Bar {<br>public:<br> typedef const int &amp; const_reference;<br> %typemap(out) const_reference {<br> ...<br> }<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> When a typemap appears inside a namespace or class, it stays
+in effect until the end of the SWIG input (just like before). However,
+the typemap takes the local scope into account. Therefore, this code</p>
+
+
+
+
+
+<div class="code">
+<pre>namespace std {<br> class string;<br> %typemap(in) string {<br> ...<br> }<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> is really defining a typemap for the type <tt>std::string</tt>.
+You could have code like this:</p>
+
+
+
+
+
+<div class="code">
+<pre>namespace std {<br> class string;<br> %typemap(in) string { /* std::string */<br> ...<br> }<br>}<br><br>namespace Foo {<br> class string;<br> %typemap(in) string { /* Foo::string */<br> ...<br> }<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In this case, there are two completely distinct typemaps that
+apply to two completely different types (<tt>std::string</tt>
+and <tt>
+Foo::string</tt>).</p>
+
+
+
+
+
+<p> It should be noted that for scoping to work, SWIG has to know
+that <tt>
+string</tt> is a typename defined within a particular namespace.
+In this example, this is done using the class declaration <tt>class
+string</tt>
+.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn39"></a>31.7.6 Ruby typemaps</H3>
+
+
+<p>The following list details all of the typemap methods that
+can be used by the Ruby module: </p>
+
+
+
+
+
+<H4><a name="Ruby_in_typemap"></a>31.7.6.1 &nbsp;"in" typemap</H4>
+
+
+<p>Converts Ruby objects to input
+function arguments. For example:
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) int {<br> $1 = NUM2INT($input);<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The following special variables are available:</p>
+
+
+
+
+
+<div class="diagram">
+<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - in typemap">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$input </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Input object
+holding value to be converted.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$symname </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of
+function/method being wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1...n </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Argument being
+sent to the function</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_name </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of the
+argument (if provided)</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_type </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The actual C
+datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_ltype </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The assignable
+version of the C datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> This is probably the most commonly redefined typemap because
+it can be used to implement customized conversions.</p>
+
+
+
+
+
+<p> In addition, the "in" typemap allows the number of converted
+arguments to be specified. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>// Ignored argument.<br>%typemap(in, numinputs=0) int *out (int temp) {<br> $1 = &amp;temp;<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> At this time, only zero or one arguments may be converted.</p>
+
+
+
+
+
+<H4><a name="Ruby_typecheck_typemap"></a>31.7.6.2 "typecheck" typemap</H4>
+
+
+<p> The "typecheck" typemap is used to support overloaded
+functions and methods. It merely checks an argument to see whether or
+not it matches a specific type. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {<br> $1 = FIXNUM_P($input) ? 1 : 0;<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> For typechecking, the $1 variable is always a simple integer
+that is set to 1 or 0 depending on whether or not the input argument is
+the correct type.</p>
+
+
+
+
+
+<p> If you define new "in" typemaps<em> and</em> your
+program uses overloaded methods, you should also define a collection of
+"typecheck" typemaps. More details about this follow in a later section
+on "Typemaps and Overloading."</p>
+
+
+
+
+
+<H4><a name="Ruby_out_typemap"></a>31.7.6.3 &nbsp;"out" typemap</H4>
+
+
+<p>Converts return value of a C function
+to a Ruby object.</p>
+
+
+
+
+
+<div class="code"><tt><br>
+
+
+
+
+
+%typemap(out) int {<br>
+
+
+
+
+
+&nbsp; &nbsp;$result = INT2NUM( $1 );<br>
+
+
+
+
+
+}<br>
+
+
+
+
+
+</tt></div>
+
+
+
+
+
+<p> The following special variables are available.</p>
+
+
+
+
+
+<div class="diagram">
+<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - out typemap">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$result </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Result object
+returned to target language.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$symname </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of
+function/method being wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1...n </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Argument being
+wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_name </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of the
+argument (if provided)</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_type </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The actual C
+datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_ltype </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The assignable
+version of the C datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<br>
+
+
+
+
+
+<H4><a name="Ruby_arginit_typemap"></a>31.7.6.4 "arginit" typemap</H4>
+
+
+<p> The "arginit" typemap is used to set the initial value of a
+function argument--before any conversion has occurred. This is not
+normally necessary, but might be useful in highly specialized
+applications. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>// Set argument to NULL before any conversion occurs<br>%typemap(arginit) int *data {<br> $1 = NULL;<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_default_typemap"></a>31.7.6.5 "default" typemap</H4>
+
+
+<p> The "default" typemap is used to turn an argument into a
+default argument. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(default) int flags {<br> $1 = DEFAULT_FLAGS;<br>}<br>...<br>int foo(int x, int y, int flags);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The primary use of this typemap is to either change the
+wrapping of default arguments or specify a default argument in a
+language where they aren't supported (like C). Target languages that do
+not support optional arguments, such as Java and C#, effectively ignore
+the value specified by this typemap as all arguments must be given.</p>
+
+
+
+
+
+<p> Once a default typemap has been applied to an argument, all
+arguments that follow must have default values. See the <a href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#SWIG_default_args">
+Default/optional arguments</a> section for further information on
+default argument wrapping.</p>
+
+
+
+
+
+<H4><a name="Ruby_check_typemap"></a>31.7.6.6 "check" typemap</H4>
+
+
+<p> The "check" typemap is used to supply value checking code
+during argument conversion. The typemap is applied<em> after</em>
+arguments have been converted. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(check) int positive {<br> if ($1 &lt;= 0) {<br> SWIG_exception(SWIG_ValueError,"Expected positive value.");<br> }<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_argout_typemap_"></a>31.7.6.7 "argout" typemap</H4>
+
+
+<p> The "argout" typemap is used to return values from arguments.
+This is most commonly used to write wrappers for C/C++ functions that
+need to return multiple values. The "argout" typemap is almost always
+combined with an "in" typemap---possibly to ignore the input value. For
+example:</p>
+
+
+
+
+
+<div class="code">
+<pre>/* Set the input argument to point to a temporary variable */<br>%typemap(in, numinputs=0) int *out (int temp) {<br> $1 = &amp;temp;<br>}<br><br>%typemap(argout, fragment="output_helper") int *out {<br> // Append output value $1 to $result (assuming a single integer in this case)<br> $result = output_helper( $result, INT2NUM(*$1) );<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The following special variables are available.</p>
+
+
+
+
+
+<div class="diagram">
+<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - argout typemap">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$result </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Result object
+returned to target language.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$input </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The original
+input object passed.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$symname </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of
+function/method being wrapped.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The code supplied to the "argout" typemap is always placed
+after the "out" typemap. If multiple return values are used, the extra
+return values are often appended to return value of the function.</p>
+
+
+
+
+
+<p>Output helper is a fragment that usually defines a macro to
+some function like SWIG_Ruby_AppendOutput.</p>
+
+
+
+
+
+<p> See the <tt>typemaps.i</tt> library for examples.</p>
+
+
+
+
+
+<H4><a name="Ruby_freearg_typemap_"></a>31.7.6.8 "freearg" typemap</H4>
+
+
+<p> The "freearg" typemap is used to cleanup argument data. It is
+only used when an argument might have allocated resources that need to
+be cleaned up when the wrapper function exits. The "freearg" typemap
+usually cleans up argument resources allocated by the "in" typemap. For
+example:</p>
+
+
+
+
+
+<div class="code">
+<pre>// Get a list of integers<br>%typemap(in) int *items {<br> int nitems = Length($input); <br> $1 = (int *) malloc(sizeof(int)*nitems);<br>}<br>// Free the list <br>%typemap(freearg) int *items {<br> free($1);<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> The "freearg" typemap inserted at the end of the wrapper
+function, just before control is returned back to the target language.
+This code is also placed into a special variable <tt>$cleanup</tt>
+that may be used in other typemaps whenever a wrapper function needs to
+abort prematurely.</p>
+
+
+
+
+
+<H4><a name="Ruby_newfree_typemap"></a>31.7.6.9 "newfree" typemap</H4>
+
+
+<p> The "newfree" typemap is used in conjunction with the <tt>%newobject</tt>
+directive and is used to deallocate memory used by the return result of
+a function. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(newfree) string * {<br> delete $1;<br>}<br>%typemap(out) string * {<br> $result = PyString_FromString($1-&gt;c_str());<br>}<br>...<br><br>%newobject foo;<br>...<br>string *foo();<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> See <a href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#ownership">Object
+ownership and %newobject</a> for further details.</p>
+
+
+
+
+
+<H4><a name="Ruby_memberin_typemap"></a>31.7.6.10 "memberin" typemap</H4>
+
+
+<p> The "memberin" typemap is used to copy data from<em> an
+already converted input value</em> into a structure member. It is
+typically used to handle array members and other special cases. For
+example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(memberin) int [4] {<br> memmove($1, $input, 4*sizeof(int));<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> It is rarely necessary to write "memberin" typemaps---SWIG
+already provides a default implementation for arrays, strings, and
+other objects.</p>
+
+
+
+
+
+<H4><a name="Ruby_varin_typemap"></a>31.7.6.11 "varin" typemap</H4>
+
+
+<p> The "varin" typemap is used to convert objects in the target
+language to C for the purposes of assigning to a C/C++ global variable.
+This is implementation specific.</p>
+
+
+
+
+
+<H4><a name="Ruby_varout_typemap_"></a>31.7.6.12 "varout" typemap</H4>
+
+
+<p> The "varout" typemap is used to convert a C/C++ object to an
+object in the target language when reading a C/C++ global variable.
+This is implementation specific.</p>
+
+
+
+
+
+<H4><a name="Ruby_throws_typemap"></a>31.7.6.13 "throws" typemap</H4>
+
+
+<p> The "throws" typemap is only used when SWIG parses a C++
+method with an exception specification or has the <tt>%catches</tt>
+feature attached to the method. It provides a default mechanism for
+handling C++ methods that have declared the exceptions they will throw.
+The purpose of this typemap is to convert a C++ exception into an error
+or exception in the target language. It is slightly different to the
+other typemaps as it is based around the exception type rather than the
+type of a parameter or variable. For example:</p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(throws) const char * %{<br> rb_raise(rb_eRuntimeError, $1);<br> SWIG_fail;<br>%}<br>void bar() throw (const char *);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> As can be seen from the generated code below, SWIG generates
+an exception handler with the catch block comprising the "throws"
+typemap content.</p>
+
+
+
+
+
+<div class="code">
+<pre>...<br>try {<br> bar();<br>}<br>catch(char const *_e) {<br> rb_raise(rb_eRuntimeError, _e);<br> SWIG_fail;<br>}<br>...<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note that if your methods do not have an exception
+specification yet they do throw exceptions, SWIG cannot know how to
+deal with them. For a neat way to handle these, see the <a href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#exception">Exception
+handling with %exception</a> section.</p>
+
+
+
+
+
+<H4><a name="Ruby_directorin_typemap"></a>31.7.6.14 directorin typemap</H4>
+
+
+<p>Converts C++ objects in director
+member functions to ruby objects.&nbsp;It is roughly the opposite
+of the "in" typemap, making its typemap rule often similar to the "out"
+typemap.
+</p>
+
+
+
+
+
+<div class="code"><tt><br>
+
+
+
+
+
+%typemap(directorin) int {<br>
+
+
+
+
+
+&nbsp; &nbsp; &nbsp;$result = INT2NUM($1);<br>
+
+
+
+
+
+}<br>
+
+
+
+
+
+</tt></div>
+
+
+
+
+
+<p> The following special variables are available.</p>
+
+
+
+
+
+<div class="diagram">
+<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - directorin typemap">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$result </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Result object
+returned to target language.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$symname </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of
+function/method being wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1...n </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Argument being
+wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_name </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of the
+argument (if provided)</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_type </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The actual C
+datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_ltype </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The assignable
+version of the C datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">this </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> C++ this,
+referring to the class itself.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_directorout_typemap"></a>31.7.6.15 directorout typemap</H4>
+
+
+<p>Converts Ruby objects in director
+member functions to C++ objects. &nbsp;It is roughly the opposite
+of the "out" typemap, making its rule often similar to the "in"
+typemap.
+</p>
+
+
+
+
+
+<div class="code"><tt style="font-family: monospace;"><br>
+
+
+
+
+
+%typemap(directorout) int {</tt><tt><br>
+
+
+
+
+
+&nbsp; &nbsp;$result =&nbsp;NUM2INT($1);</tt><br>
+
+
+
+
+
+<tt style="font-family: monospace;">}<br>
+
+
+
+
+
+</tt></div>
+
+
+
+
+
+<p> The following special variables are available:</p>
+
+
+
+
+
+<div class="diagram">
+<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - directorout typemap">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$symname </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of
+function/method being wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1...n </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Argument being
+sent to the function</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_name </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> Name of the
+argument (if provided)</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_type </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The actual C
+datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_ltype </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> The assignable
+version of the C datatype matched by the typemap.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">this </td>
+
+
+
+
+
+      <td style="font-family: monospace;"> C++ this,
+referring to the class itself.</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Currently, the directorout nor the out typemap support the
+option&nbsp;<span style="font-family: monospace;">numoutputs</span>,
+but the Ruby module provides that functionality through a %feature
+directive. &nbsp;Thus, a function can be made to return "nothing"
+if you do:</p>
+
+
+
+
+
+<div style="font-family: monospace;" class="code">%feature("numoutputs","0")
+MyClass::function;</div>
+
+
+
+
+
+<p>This feature can be useful if a function returns a status
+code, which you want to discard but still use the typemap to raise an
+exception.<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<H4><a name="Ruby_directorargout_typemap"></a>31.7.6.16 directorargout typemap</H4>
+
+
+<p>Output argument processing in director
+member functions.</p>
+
+
+
+
+
+<div class="code"><tt style="font-family: monospace;">%typemap(directorargout,
+fragment="output_helper") int {</tt><tt><br>
+
+
+
+
+
+$result = output_helper( $result, NUM2INT($1) );</tt><br>
+
+
+
+
+
+<tt style="font-family: monospace;">}</tt></div>
+
+
+
+
+
+<p> The following special variables are available:</p>
+
+
+
+
+
+<div class="diagram">
+<table style="text-align: left; width: 100%;" border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorargout typemap">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$result</td>
+
+
+
+
+
+      <td style="font-family: monospace;">Result that the
+director function returns</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$symname</td>
+
+
+
+
+
+      <td style="font-family: monospace;">name of the
+function/method being wrapped</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1...n</td>
+
+
+
+
+
+      <td style="font-family: monospace;">Argument being
+sent to the function</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_name</td>
+
+
+
+
+
+      <td style="font-family: monospace;">Name of the
+argument (if provided)</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_type</td>
+
+
+
+
+
+      <td style="font-family: monospace;">The actual C
+datatype matched by the typemap</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">$1_ltype</td>
+
+
+
+
+
+      <td style="font-family: monospace;">The assignable
+version of the C datatype matched by the typemap</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td style="font-family: monospace;">this</td>
+
+
+
+
+
+      <td style="font-family: monospace;">C++ this,
+referring to the instance of the class itself</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_ret_typemap"></a>31.7.6.17 ret typemap</H4>
+
+
+<p>Cleanup of function return values
+</p>
+
+
+
+
+
+<H4><a name="Ruby_globalin_typemap"></a>31.7.6.18 globalin typemap</H4>
+
+
+<p>Setting of C global variables
+</p>
+
+
+
+
+
+<H3><a name="Ruby_nn40"></a>31.7.7 Typemap variables</H3>
+
+
+<p>
+Within a typemap, a number of special variables prefaced with a <tt>$</tt>
+may appear. A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+This is a list of the most common variables:
+</p>
+
+
+
+
+
+<p><tt>$1</tt> </p>
+
+
+
+
+
+<div class="indent">A C local variable corresponding to
+the actual type specified in the <tt>%typemap</tt>
+directive. For input values, this is a C local variable that is
+supposed to hold an argument value. For output values, this is the raw
+result that is supposed to be returned to Ruby. </div>
+
+
+
+
+
+<p><tt>$input</tt></p>
+
+
+
+
+
+<div class="indent">A <tt>VALUE</tt> holding
+a raw Ruby object with an argument or variable value. </div>
+
+
+
+
+
+<p><tt>$result</tt></p>
+
+
+
+
+
+<div class="indent">A <tt>VALUE</tt> that
+holds the result to be returned to Ruby. </div>
+
+
+
+
+
+<p><tt>$1_name</tt></p>
+
+
+
+
+
+<div class="indent">The parameter name that was matched. </div>
+
+
+
+
+
+<p><tt>$1_type</tt></p>
+
+
+
+
+
+<div class="indent">The actual C datatype matched by the
+typemap. </div>
+
+
+
+
+
+<p><tt>$1_ltype</tt></p>
+
+
+
+
+
+<div class="indent">An assignable version of the datatype
+matched by the typemap (a type that can appear on the left-hand-side of
+a C assignment operation). This type is stripped of qualifiers and may
+be an altered version of <tt>$1_type</tt>. All arguments
+and local variables in wrapper functions are declared using this type
+so that their values can be properly assigned. </div>
+
+
+
+
+
+<p><tt>$symname</tt></p>
+
+
+
+
+
+<div class="indent">The Ruby name of the wrapper function
+being created. </div>
+
+
+
+
+
+<H3><a name="Ruby_nn41"></a>31.7.8 Useful Functions</H3>
+
+
+<p> When you write a typemap, you usually have to work directly
+with Ruby objects. The following functions may prove to be useful.
+(These functions plus many more can be found in <a href="http://www.rubycentral.com/book"><em>Programming
+Ruby</em></a>, by David Thomas and Andrew Hunt.)&nbsp;</p>
+<p>In addition, we list equivalent functions that Swig defines, which
+provide a language neutral conversion (these functions are defined for
+each swig language supported). &nbsp;If you are trying to create a swig
+file that will work under multiple languages, it is recommended you
+stick to the swig functions instead of the native Ruby functions.
+&nbsp;That should help you avoid having to rewrite a lot of typemaps
+across multiple languages.</p>
+
+
+
+
+
+
+
+
+
+
+<H4><a name="Ruby_nn42"></a>31.7.8.1 C Datatypes to Ruby Objects</H4>
+
+
+<div class="diagram">
+<table style="width: 100%;" border="1" cellpadding="2" cellspacing="2" summary="Datatypes">
+
+  <tbody>
+    <tr>
+      <th style="font-weight: bold;">RUBY</th>
+      <th style="font-weight: bold;">Swig</th>
+      <td></td>
+    </tr>
+    <tr>
+      <td style="font-family: monospace;">INT2NUM(long or int) </td>
+      <td style="font-family: monospace;">SWIG_From_int(int x)</td>
+      <td> int to Fixnum or Bignum</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">INT2FIX(long or int) </td>
+      <td style="font-family: monospace;"></td>
+      <td> int to Fixnum (faster than INT2NUM)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">CHR2FIX(char) </td>
+      <td style="font-family: monospace;">SWIG_From_char(char x)</td>
+      <td> char to Fixnum</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">rb_str_new2(char*) </td>
+      <td style="font-family: monospace;">SWIG_FromCharPtrAndSize(char*, size_t)</td>
+      <td> char* to String</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">rb_float_new(double) </td>
+      <td style="font-family: monospace;">SWIG_From_double(double),<br>
+SWIG_From_float(float)</td>
+      <td>float/double to Float</td>
+    </tr>
+
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_nn43"></a>31.7.8.2 Ruby Objects to C Datatypes</H4>
+
+
+<p>Here, while the Ruby versions return the value directly, the SWIG
+versions do not, but return a status value to indicate success (<span style="font-family: monospace;">SWIG_OK</span>). While more akward to use, this allows you to write typemaps that report more helpful error messages, like:</p>
+<div style="font-family: monospace;" class="code"><br>
+%typemap(in) size_t (int ok)<br>
+&nbsp; <br>
+&nbsp; ok = SWIG_AsVal_size_t($input, &amp;$1);<br>
+&nbsp; if (!SWIG_IsOK(ok)) {<br>
+&nbsp;&nbsp;&nbsp; SWIG_exception_fail(SWIG_ArgError(ok),
+Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input
+));<br>
+&nbsp; &nbsp;}<br>
+<br>
+} </div>
+<div style="font-family: monospace;">&nbsp;&nbsp;</div>
+<div class="diagram">
+<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Ruby objects">
+
+  <tbody>
+    <tr>
+      <td style="font-family: monospace;">int NUM2INT(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_int(VALUE, int*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">int FIX2INT(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_int(VALUE, int*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">unsigned int NUM2UINT(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">unsigned int FIX2UINT(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">long NUM2LONG(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_long(VALUE, long*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">long FIX2LONG(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_long(VALUE, long*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">unsigned long FIX2ULONG(Numeric)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">char NUM2CHR(Numeric or String)</td>
+      <td style="font-family: monospace;">SWIG_AsVal_char(VALUE, int*)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">char * STR2CSTR(String)</td>
+      <td style="font-family: monospace;">SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)</td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">char * rb_str2cstr(String, int*length)</td>
+      <td style="font-family: monospace;"></td>
+    </tr>
+
+    <tr>
+      <td style="font-family: monospace;">double NUM2DBL(Numeric)</td>
+      <td style="font-family: monospace;">(double) SWIG_AsVal_int(VALUE) or similar</td>
+    </tr>
+
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_nn44"></a>31.7.8.3 Macros for VALUE</H4>
+
+
+<p> <tt>RSTRING_LEN(str)</tt> </p>
+
+
+
+
+
+<div class="indent">length of the Ruby string</div>
+
+
+
+
+
+<p><tt>RSTRING_PTR(str)</tt></p>
+
+
+
+
+
+<div class="indent">pointer to string storage</div>
+
+
+
+
+
+<p><tt>RARRAY_LEN(arr)</tt></p>
+
+
+
+
+
+<div class="indent">length of the Ruby array</div>
+
+
+
+
+
+<p><tt>RARRAY(arr)-&gt;capa</tt></p>
+
+
+
+
+
+<div class="indent">capacity of the Ruby array</div>
+
+
+
+
+
+<p><tt>RARRAY_PTR(arr)</tt></p>
+
+
+
+
+
+<div class="indent">pointer to array storage</div>
+
+
+
+
+
+<H4><a name="Ruby_nn45"></a>31.7.8.4 Exceptions</H4>
+
+
+<p> <tt>void rb_raise(VALUE exception, const char *fmt,
+...)</tt> </p>
+
+
+
+
+
+<div class="indent"> Raises an exception. The given format
+string <i>fmt</i> and remaining arguments are interpreted
+as with <tt>printf()</tt>. </div>
+
+
+
+
+
+<p><tt>void rb_fatal(const char *fmt, ...)</tt></p>
+
+
+
+
+
+<div class="indent"> Raises a fatal exception, terminating
+the process. No rescue blocks are called, but ensure blocks will be
+called. The given format string <i>fmt</i> and remaining
+arguments are interpreted as with <tt>printf()</tt>. </div>
+
+
+
+
+
+<p><tt>void rb_bug(const char *fmt, ...)</tt></p>
+
+
+
+
+
+<div class="indent"> Terminates the process immediately --
+no handlers of any sort will be called. The given format string <i>fmt</i>
+and remaining arguments are interpreted as with <tt>printf()</tt>.
+You should call this function only if a fatal bug has been exposed. </div>
+
+
+
+
+
+<p><tt>void rb_sys_fail(const char *msg)</tt></p>
+
+
+
+
+
+<div class="indent"> Raises a platform-specific exception
+corresponding to the last known system error, with the given string <i>msg</i>.
+</div>
+
+
+
+
+
+<p><tt>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args,
+VALUE(*rescue)(VALUE, VALUE), VALUE rargs)</tt></p>
+
+
+
+
+
+<div class="indent"> Executes <i>body</i>
+with the given <i>args</i>. If a <tt>StandardError</tt>
+exception is raised, then execute <i>rescue</i> with the
+given <i>rargs</i>. </div>
+
+
+
+
+
+<p><tt>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args,
+VALUE(*ensure)(VALUE), VALUE eargs)</tt></p>
+
+
+
+
+
+<div class="indent"> Executes <i>body</i>
+with the given <i>args</i>. Whether or not an exception is
+raised, execute <i>ensure</i> with the given <i>rargs</i>
+after <i>body</i> has completed. </div>
+
+
+
+
+
+<p><tt>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args,
+int *result)</tt></p>
+
+
+
+
+
+<div class="indent"> Executes <i>body</i>
+with the given <i>args</i> and returns nonzero in result
+if any exception was raised. </div>
+
+
+
+
+
+<p><tt>void rb_notimplement()</tt></p>
+
+
+
+
+
+<div class="indent"> Raises a <tt>NotImpError</tt>
+exception to indicate that the enclosed function is not implemented
+yet, or not available on this platform. </div>
+
+
+
+
+
+<p><tt>void rb_exit(int status)</tt></p>
+
+
+
+
+
+<div class="indent"> Exits Ruby with the given <i>status</i>.
+Raises a <tt>SystemExit</tt> exception and calls
+registered exit functions and finalizers. </div>
+
+
+
+
+
+<p><tt>void rb_warn(const char *fmt, ...)</tt></p>
+
+
+
+
+
+<div class="indent"> Unconditionally issues a warning
+message to standard error. The given format string <i>fmt</i>
+and remaining arguments are interpreted as with <tt>printf()</tt>.
+</div>
+
+
+
+
+
+<p><tt>void rb_warning(const char *fmt, ...)</tt></p>
+
+
+
+
+
+<div class="indent"> Conditionally issues a warning
+message to standard error if Ruby was invoked with the <tt>-w</tt>
+flag. The given format string <i>fmt</i> and remaining
+arguments are interpreted as with <tt>printf()</tt>. </div>
+
+
+
+
+
+<H4><a name="Ruby_nn46"></a>31.7.8.5 Iterators</H4>
+
+
+<p> <tt>void rb_iter_break()</tt> </p>
+
+
+
+
+
+<div class="indent"> Breaks out of the enclosing iterator
+block. </div>
+
+
+
+
+
+<p><tt>VALUE rb_each(VALUE obj)</tt></p>
+
+
+
+
+
+<div class="indent"> Invokes the <tt>each</tt>
+method of the given <i>obj</i>. </div>
+
+
+
+
+
+<p><tt>VALUE rb_yield(VALUE arg)</tt></p>
+
+
+
+
+
+<div class="indent"> Transfers execution to the iterator
+block in the current context, passing <i>arg</i> as an
+argument. Multiple values may be passed in an array. </div>
+
+
+
+
+
+<p><tt>int rb_block_given_p()</tt></p>
+
+
+
+
+
+<div class="indent"> Returns <tt>true</tt> if
+<tt>yield</tt> would execute a block in the current
+context; that is, if a code block was passed to the current method and
+is available to be called. </div>
+
+
+
+
+
+<p><tt>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args,
+VALUE (*block)(VALUE, VALUE), VALUE arg2)</tt></p>
+
+
+
+
+
+<div class="indent"> Invokes <i>method</i>
+with argument <i>args</i> and block <i>block</i>.
+A <tt>yield</tt> from that method will invoke <i>block</i>
+with the argument given to <tt>yield</tt>, and a second
+argument <i>arg2</i>. </div>
+
+
+
+
+
+<p><tt>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE,
+VALUE), VALUE value)</tt></p>
+
+
+
+
+
+<div class="indent"> Equivalent to Ruby's <tt>catch</tt>.
+</div>
+
+
+
+
+
+<p><tt>void rb_throw(const char *tag, VALUE value)</tt></p>
+
+
+
+
+
+<div class="indent"> Equivalent to Ruby's <tt>throw</tt>.
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn47"></a>31.7.9 Typemap Examples</H3>
+
+
+<p> This section includes a few examples of typemaps. For more
+examples, you might look at the examples in the <tt>Example/ruby</tt>
+directory. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn48"></a>31.7.10 Converting a Ruby array to a char **</H3>
+
+
+<p> A common problem in many C programs is the processing of
+command line arguments, which are usually passed in an array of <tt>NULL</tt>
+terminated strings. The following SWIG interface file allows a Ruby
+Array instance to be used as a <tt>char **</tt> object. </p>
+
+
+
+
+
+<div class="code">
+<pre>%module argv<br><br>// This tells SWIG to treat char ** as a special case<br>%typemap(in) char ** {<br> /* Get the length of the array */<br> int size = RARRAY($input)-&gt;len; <br> int i;<br> $1 = (char **) malloc((size+1)*sizeof(char *));<br> /* Get the first element in memory */<br> VALUE *ptr = RARRAY($input)-&gt;ptr; <br> for (i=0; i &lt; size; i++, ptr++)<br> /* Convert Ruby Object String to char* */<br> $1[i]= STR2CSTR(*ptr); <br> $1[i]=NULL; /* End of list */<br>}<br><br>// This cleans up the char ** array created before <br>// the function call<br><br>%typemap(freearg) char ** {<br> free((char *) $1);<br>}<br><br>// Now a test function<br>%inline %{<br>int print_args(char **argv) {<br> int i = 0;<br> while (argv[i]) {<br> printf("argv[%d] = %s\n", i,argv[i]);<br> i++;<br> }<br> return i;<br>}<br>%}<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> When this module is compiled, the wrapped C function now
+operates as follows : </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>require 'Argv'<br>Argv.print_args(["Dave","Mike","Mary","Jane","John"])<br>argv[0] = Dave<br>argv[1] = Mike<br>argv[2] = Mary<br>argv[3] = Jane<br>argv[4] = John<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In the example, two different typemaps are used. The "in"
+typemap is used to receive an input argument and convert it to a C
+array. Since dynamic memory allocation is used to allocate memory for
+the array, the "freearg" typemap is used to later release this memory
+after the execution of the C function. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn49"></a>31.7.11 Collecting arguments in a hash</H3>
+
+
+<p> Ruby's solution to the "keyword arguments" capability of some
+other languages is to allow the programmer to pass in one or more
+key-value pairs as arguments to a function. All of those key-value
+pairs are collected in a single <tt>Hash</tt> argument
+that's presented to the function. If it makes sense, you might want to
+provide similar functionality for your Ruby interface. For example,
+suppose you'd like to wrap this C function that collects information
+about people's vital statistics: </p>
+
+
+
+
+
+<div class="code">
+<pre>void setVitalStats(const char *person, int nattributes, const char **names, int *values);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> and you'd like to be able to call it from Ruby by passing in
+an arbitrary number of key-value pairs as inputs, e.g. </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>setVitalStats("Fred",<br> 'weight' =&gt; 270,<br>	'age' =&gt; 42<br>	)<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To make this work, you need to write a typemap that expects a
+Ruby <tt>Hash</tt> as its input and somehow extracts the
+last three arguments (<i>nattributes</i>, <i>names</i>
+and <i>values</i>) needed by your C function. Let's start
+with the basics: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br>}<br> </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> This <tt>%typemap</tt> directive tells SWIG that
+we want to match any function declaration that has the specified types
+and names of arguments somewhere in the argument list. The fact that we
+specified the argument names (<i>nattributes</i>, <i>names</i>
+and <i>values</i>) in our typemap is significant; this
+ensures that SWIG won't try to apply this typemap to <i>other</i>
+functions it sees that happen to have a similar declaration with
+different argument names. The arguments that appear in the second set
+of parentheses (<i>keys_arr</i>, <i>i</i>, <i>key</i>
+and <i>val</i>) define local variables that our typemap
+will need. </p>
+
+
+
+
+
+<p>Since we expect the input argument to be a <tt>Hash</tt>,
+let's next add a check for that: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> <b>Check_Type($input, T_HASH);</b><br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> <tt>Check_Type()</tt> is just a macro (defined
+in the Ruby header files) that confirms that the input argument is of
+the correct type; if it isn't, an exception will be raised. </p>
+
+
+
+
+
+<p>The next task is to determine how many key-value pairs are
+present in the hash; we'll assign this number to the first typemap
+argument (<tt>$1</tt>). This is a little tricky since the
+Ruby/C API doesn't provide a public function for querying the size of a
+hash, but we can get around that by calling the hash's <i>size</i>
+method directly and converting its result to a C <tt>int</tt>
+value: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> <b>$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));</b><br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> So now we know the number of attributes. Next we need to
+initialize the second and third typemap arguments (i.e. the two C
+arrays) to <tt>NULL</tt> and set the stage for extracting
+the keys and values from the hash: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> <b>$2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> }</b><br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> There are a number of ways we could extract the keys and
+values from the input hash, but the simplest approach is to first call
+the hash's <i>keys</i> method (which returns a Ruby array
+of the keys) and then start looping over the elements in that array: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> <b>keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> }</b><br>}<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Recall that <i>keys_arr</i> and <i>i</i>
+are local variables for this typemap. For each element in the <i>keys_arr</i>
+array, we want to get the key itself, as well as the value
+corresponding to that key in the hash: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> <b>key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);</b><br>}<br>}<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To be safe, we should again use the <tt>Check_Type()</tt>
+macro to confirm that the key is a <tt>String</tt> and the
+value is a <tt>Fixnum</tt>: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);<br> <b>Check_Type(key, T_STRING);<br> Check_Type(val, T_FIXNUM);</b><br>}<br>}<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Finally, we can convert these Ruby objects into their C
+equivalents and store them in our local C arrays: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);<br> Check_Type(key, T_STRING);<br> Check_Type(val, T_FIXNUM);<br> <b>$2[i] = STR2CSTR(key);<br> $3[i] = NUM2INT(val);</b><br>}<br>}<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> We're not done yet. Since we used <tt>malloc()</tt>
+to dynamically allocate the memory used for the <i>names</i>
+and <i>values</i> arguments, we need to provide a
+corresponding "freearg" typemap to free that memory so that there is no
+memory leak. Fortunately, this typemap is a lot easier to write: </p>
+
+
+
+
+
+<div class="code">
+<pre>%typemap(freearg) (int nattributes, const char **names, const int *values) {<br> free((void *) $2);<br> free((void *) $3);<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> All of the code for this example, as well as a sample Ruby
+program that uses the extension, can be found in the <tt>Examples/ruby/hashargs</tt>
+directory of the SWIG distribution. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn50"></a>31.7.12 Pointer handling</H3>
+
+
+<p> Occasionally, it might be necessary to convert pointer values
+that have been stored using the SWIG typed-pointer representation.
+Since there are several ways in which pointers can be represented, the
+following two functions are used to safely perform this conversion: </p>
+
+
+
+
+
+<p><tt>int SWIG_ConvertPtr(VALUE obj, void **ptr,
+swig_type_info *ty, int flags)</tt> </p>
+
+
+
+
+
+<div class="indent">Converts a Ruby object <i>obj</i>
+to a C pointer whose address is <i>ptr</i> (i.e. <i>ptr</i>
+is a pointer to a pointer). The third argument, <i>ty</i>,
+is a pointer to a SWIG type descriptor structure. If <i>ty</i>
+is not <tt>NULL</tt>, that type information is used to
+validate type compatibility and other aspects of the type conversion.
+If <i>flags</i> is non-zero, any type errors encountered
+during this validation result in a Ruby <tt>TypeError</tt>
+exception being raised; if <i>flags</i> is zero, such type
+errors will cause <tt>SWIG_ConvertPtr()</tt> to return -1
+but not raise an exception. If <i>ty</i> is <tt>NULL</tt>,
+no type-checking is performed. </div>
+
+
+
+
+
+<p> <tt>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info
+*ty, int own)</tt> </p>
+
+
+
+
+
+<div class="indent">Creates a new Ruby pointer object.
+Here, <i>ptr</i> is the pointer to convert, <i>ty</i>
+is the SWIG type descriptor structure that describes the type, and <i>own</i>
+is a flag that indicates whether or not Ruby should take ownership of
+the pointer (i.e. whether Ruby should free this data when the
+corresponding Ruby instance is garbage-collected). </div>
+
+
+
+
+
+<p> Both of these functions require the use of a special SWIG
+type-descriptor structure. This structure contains information about
+the mangled name of the datatype, type-equivalence information, as well
+as information about converting pointer values under C++ inheritance.
+For a type of <tt>Foo *</tt>, the type descriptor
+structure is usually accessed as follows: </p>
+
+
+
+
+
+<div class="indent code">
+<pre>Foo *foo;<br>SWIG_ConvertPtr($input, (void **) &amp;foo, SWIGTYPE_p_Foo, 1);<br><br>VALUE obj;<br>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> In a typemap, the type descriptor should always be accessed
+using the special typemap variable <tt>$1_descriptor</tt>.
+For example: </p>
+
+
+
+
+
+<div class="indent code">
+<pre>%typemap(in) Foo * {<br> SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 1);<br>}<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_nn51"></a>31.7.12.1 Ruby Datatype Wrapping</H4>
+
+
+<p> <tt>VALUE Data_Wrap_Struct(VALUE class, void
+(*mark)(void *), void (*free)(void *), void *ptr)</tt> </p>
+
+
+
+
+
+<div class="indent">Given a pointer <i>ptr</i>
+to some C data, and the two garbage collection routines for this data (<i>mark</i>
+and <i>free</i>), return a <tt>VALUE</tt> for
+the Ruby object. </div>
+
+
+
+
+
+<p><tt>VALUE Data_Make_Struct(VALUE class, <i>c-type</i>,
+void (*mark)(void *), void (*free)(void *), <i>c-type</i>
+*ptr)</tt></p>
+
+
+
+
+
+<div class="indent">Allocates a new instance of a C data
+type <i>c-type</i>, assigns it to the pointer <i>ptr</i>,
+then wraps that pointer with <tt>Data_Wrap_Struct()</tt>
+as above. </div>
+
+
+
+
+
+<p><tt>Data_Get_Struct(VALUE obj, <i>c-type</i>,
+<i>c-type</i> *ptr)</tt></p>
+
+
+
+
+
+<div class="indent">Retrieves the original C pointer of
+type <i>c-type</i> from the data object <i>obj</i>
+and assigns that pointer to <i>ptr</i>. </div>
+
+
+
+
+
+<H3><a name="Ruby_nn52"></a>31.7.13 Example: STL Vector to Ruby Array</H3>
+
+
+<p>Another use for macros and type maps is to create a Ruby array
+from a STL vector of pointers. In essence, copy of all the pointers in
+the vector into a Ruby array. The use of the macro is to make the
+typemap so generic that any vector with pointers can use the type map.
+The following is an example of how to construct this type of
+macro/typemap and should give insight into constructing similar
+typemaps for other STL structures: </p>
+
+
+
+
+
+<div class="code">
+<pre>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {<br> VALUE arr = rb_ary_new2($1-&gt;size());<br> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));<br> $result = arr;<br>}<br>%typemap(out) vectorclassname, const vectorclassname {<br> VALUE arr = rb_ary_new2($1.size());<br> vectorclassname::iterator i = $1.begin(), iend = $1.end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));<br> $result = arr;<br>}<br>%enddef<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note, that the "<tt>c ## classname.klass"</tt> is
+used in the preprocessor step to determine the actual object from the
+class name. </p>
+
+
+
+
+
+<p>To use the macro with a class Foo, the following is used: </p>
+
+
+
+
+
+<div class="code">
+<pre>PTR_VECTOR_TO_RUBY_ARRAY(vector&lt;foo *=""&gt;, Foo)<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> It is also possible to create a STL vector of Ruby objects: </p>
+
+
+
+
+
+<div class="code">
+<pre>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)<br>%typemap(in) vectorclassname &amp;, const vectorclassname &amp; {<br> Check_Type($input, T_ARRAY);<br> vectorclassname *vec = new vectorclassname;<br> int len = RARRAY($input)-&gt;len;<br> for (int i=0; i!=len; i++) {<br> VALUE inst = rb_ary_entry($input, i);<br> //The following _should_ work but doesn't on HPUX<br> // Check_Type(inst, T_DATA);<br> classname *element = NULL;<br> Data_Get_Struct(inst, classname, element);<br> vec-&gt;push_back(element);<br> }<br> $1 = vec;<br>}<br><br>%typemap(freearg) vectorclassname &amp;, const vectorclassname &amp; {<br> delete $1;<br>}<br>%enddef<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> It is also possible to create a Ruby array from a vector of
+static data types: </p>
+
+
+
+
+
+<div class="code">
+<pre>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {<br> VALUE arr = rb_ary_new2($1-&gt;size()); <br> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));<br> $result = arr;<br>}<br>%typemap(out) vectorclassname, const vectorclassname {<br> VALUE arr = rb_ary_new2($1.size()); <br> vectorclassname::iterator i = $1.begin(), iend = $1.end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));<br> $result = arr;<br>}<br>%enddef<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<br>
+
+
+
+
+
+Note that this is mostly an example of typemaps. If you want to use the
+STL with ruby, you are advised to use the standard swig STL library,
+which does much more than this. &nbsp;Refer to the section called
+the<a href="#Ruby_nn23_1"> C++ Standard Template Library</a>.<br>
+
+
+
+
+
+<H2><a name="Ruby_nn65"></a>31.8 Docstring Features</H2>
+
+
+<p>
+Using ri and rdoc web pages in Ruby libraries is a common practice.
+Given the way that SWIG generates the extensions by default, your users
+will normally not get
+any documentation for it, even if they run 'rdoc' on the resulting .c
+or .cxx file.</p>
+
+
+
+
+
+<p>The features described in this section make it easy for you to
+add
+rdoc strings to your modules, functions and methods that can then be
+read by Ruby's rdoc tool to generate html web pages, ri documentation,
+Windows chm file and an .xml description.</p>
+
+
+
+
+
+<p>rdoc can then be run from a console or shell window on a swig
+generated file.&nbsp;</p>
+
+
+
+
+
+<p>For example, to generate html web pages from a C++ file, you'd
+do:&nbsp;</p>
+
+
+
+
+
+<div class="code shell"><span style="font-family: monospace; font-weight: bold;">
+$
+rdoc&nbsp;-E cxx=c -f html file_wrap.cxx</span></div>
+
+
+
+
+
+<p>To
+generate ri documentation from a c wrap file, you could do:</p>
+
+
+
+
+
+<div class="code shell"><span style="font-family: monospace; font-weight: bold;">$ rdoc
+-r&nbsp;file_wrap.c</span>
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn66"></a>31.8.1 Module docstring</H3>
+
+
+<p>
+Ruby allows a docstring at the beginning of the&nbsp;file
+before any other statements, and it is typically used to give a
+general description of the entire module. SWIG supports this by
+setting an option of the <tt>%module</tt> directive. For
+example:
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%module(docstring="This is the example module's docstring") example<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>
+When you have more than just a line or so then you can retain the easy
+readability of the <tt>%module</tt> directive by using a
+macro. For example:
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%define DOCSTRING<br>"The `XmlResource` class allows program resources defining menus, <br>layout of controls on a panel, etc. to be loaded from an XML file."<br>%enddef<br><br>%module(docstring=DOCSTRING) xrc<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn67"></a>31.8.2 %feature("autodoc")</H3>
+
+
+<p>Since SWIG does know everything about the function it wraps,
+it is possible to generate an rdoc containing the parameter types,
+names
+and default values. Since Ruby ships with one of the best documentation
+systems of any language, it makes sense to take advantage of it.
+</p>
+
+
+
+
+
+<p>SWIG's Ruby module provides support for the "autodoc"
+feature,
+which when attached to a node in the parse tree will cause an rdoc
+comment
+to be generated in the wrapper file that includes the name of the
+function, parameter
+names, default values if any, and return type if any. There are also
+several options for autodoc controlled by the value given to the
+feature, described below.
+</p>
+
+
+
+
+
+<H4><a name="Ruby_nn68"></a>31.8.2.1 %feature("autodoc", "0")</H4>
+
+
+<p>
+When the "0" option is given then the types of the parameters will
+<em>not</em> be included in the autodoc string. For
+example, given
+this function prototype:
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%feature("autodoc", "0");<br>bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>
+Then Ruby code like this will be generated:
+</p>
+
+
+
+
+
+<div class="targetlang">
+<pre>function_name(x, y, foo=nil, bar=nil) -&gt; bool<br> ...<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_autodoc1"></a>31.8.2.2 %feature("autodoc", "1")</H4>
+
+
+<p>
+When the "1" option is used then the parameter types <em>will</em>
+be used in the rdoc string. In addition, an attempt is made to
+simplify the type name such that it makes more sense to the Ruby
+user. Pointer, reference and const info is removed,
+<tt>%rename</tt>'s are evaluated, etc. (This is not always
+successful, but works most of the time. See the next section for what
+to do when it doesn't.) Given the example above, then turning on the
+parameter types with the "1" option will result in rdoc code like
+this:
+</p>
+
+
+
+
+
+<div class="targetlang">
+<pre>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool<br> ...<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_autodoc2"></a>31.8.2.3 %feature("autodoc", "2")</H4>
+
+
+<p>
+When the "2" option is used then the parameter types will not
+be
+used in the rdoc string. However, they will be listed in full after the
+function. &nbsp;Given the example above, then turning on the
+parameter types with the "2" option will result in Ruby code like
+this:
+</p>
+
+
+
+
+
+<H4><a name="Ruby_feature_autodoc3"></a>31.8.2.4 %feature("autodoc", "3")</H4>
+
+
+<p>
+When the "3" option is used then the function will be documented using
+a combination of "1" and "2" above. &nbsp;Given the example above,
+then turning on the
+parameter types with the "2" option will result in Ruby code like
+this:
+</p>
+
+
+
+
+
+<div class="targetlang">
+<pre>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool<br><br>Parameters:<br>	x - int<br>	y - int<br>	foo - Foo<br>	bar - Bar<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H4><a name="Ruby_nn70"></a>31.8.2.5 %feature("autodoc", "docstring")</H4>
+
+
+<p>
+Finally, there are times when the automatically generated autodoc
+string will make no sense for a Ruby programmer, particularly when a
+typemap is involved. So if you give an explicit value for the autodoc
+feature then that string will be used in place of the automatically
+generated string. For example:
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%feature("autodoc", "GetPosition() -&gt; (x, y)") GetPosition;<br>void GetPosition(int* OUTPUT, int* OUTPUT);<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn71"></a>31.8.3 %feature("docstring")</H3>
+
+
+<p>
+In addition to the autodoc strings described above, you can also
+attach any arbitrary descriptive text to a node in the parse tree with
+the "docstring" feature. When the proxy module is generated then any
+docstring associated with classes, function or methods are output.
+If an item already has an autodoc string then it is combined with the
+docstring and they are output together. </p>
+
+
+
+
+
+<H2><a name="Ruby_nn53"></a>31.9 Advanced Topics</H2>
+
+
+<H3><a name="Ruby_nn54"></a>31.9.1 Operator overloading</H3>
+
+
+<p> SWIG allows operator overloading with, by using the <tt>%extend</tt>
+or <tt>%rename</tt> commands in SWIG and the following
+operator names (derived from Python): </p>
+
+
+
+
+
+<div class="code diagram">
+<table style="width: 100%; font-family: monospace;" border="1" cellpadding="2" cellspacing="2" summary="operator names">
+
+
+
+
+
+  <tbody>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td><b> General</b></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__repr__ </td>
+
+
+
+
+
+      <td> inspect</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__str__ </td>
+
+
+
+
+
+      <td> to_s</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__cmp__ </td>
+
+
+
+
+
+      <td> &lt;=&gt;</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__hash__ </td>
+
+
+
+
+
+      <td> hash</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__nonzero__ </td>
+
+
+
+
+
+      <td> nonzero?</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td><b> Callable</b></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__call__ </td>
+
+
+
+
+
+      <td> call</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td><b> Collection</b></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__len__ </td>
+
+
+
+
+
+      <td> length</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__getitem__ </td>
+
+
+
+
+
+      <td> []</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__setitem__ </td>
+
+
+
+
+
+      <td> []=</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td><b> Numeric</b></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__add__ </td>
+
+
+
+
+
+      <td> +</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__sub__ </td>
+
+
+
+
+
+      <td> -</td>
+
+
+
+
+
+      <td></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__mul__ </td>
+
+
+
+
+
+      <td> *</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__div__ </td>
+
+
+
+
+
+      <td> /</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__mod__ </td>
+
+
+
+
+
+      <td> %</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__divmod__ </td>
+
+
+
+
+
+      <td> divmod</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__pow__ </td>
+
+
+
+
+
+      <td> **</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__lshift__ </td>
+
+
+
+
+
+      <td> &lt;&lt;</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__rshift__ </td>
+
+
+
+
+
+      <td> &gt;&gt;</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__and__ </td>
+
+
+
+
+
+      <td> &amp;</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__xor__ </td>
+
+
+
+
+
+      <td> ^</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__or__ </td>
+
+
+
+
+
+      <td> |</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__neg__ </td>
+
+
+
+
+
+      <td> -@</td>
+
+
+
+
+
+      <td></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__pos__ </td>
+
+
+
+
+
+      <td> +@</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__abs__ </td>
+
+
+
+
+
+      <td> abs</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__invert__ </td>
+
+
+
+
+
+      <td> ~</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__int__ </td>
+
+
+
+
+
+      <td> to_i</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__float__ </td>
+
+
+
+
+
+      <td> to_f</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__coerce__ </td>
+
+
+
+
+
+      <td> coerce</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td><b>Additions in 1.3.13 </b></td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__lt__ </td>
+
+
+
+
+
+      <td> &lt;</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__le__ </td>
+
+
+
+
+
+      <td> &lt;=</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__eq__ </td>
+
+
+
+
+
+      <td> ==</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__gt__ </td>
+
+
+
+
+
+      <td> &gt;</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+    <tr>
+
+
+
+
+
+      <td>__ge__ </td>
+
+
+
+
+
+      <td> &gt;=</td>
+
+
+
+
+
+    </tr>
+
+
+
+
+
+  
+  
+  
+  
+  </tbody>
+</table>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note that although SWIG supports the <tt>__eq__</tt>
+magic method name for defining an equivalence operator, there is no
+separate method for handling <i>inequality</i> since Ruby
+parses the expression <i>a != b</i> as <i>!(a == b)</i>.
+</p>
+
+
+
+
+
+<H3><a name="Ruby_nn55"></a>31.9.2 Creating Multi-Module Packages</H3>
+
+
+<p> The chapter on <a href="Modules.html">Working
+with Modules</a> discusses the basics of creating multi-module
+extensions with SWIG, and in particular the considerations for sharing
+runtime type information among the different modules. </p>
+
+
+
+
+
+<p>As an example, consider one module's interface file (<tt>shape.i</tt>)
+that defines our base class: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module shape<br><br>%{<br>#include "Shape.h"<br>%}<br><br>class Shape {<br>protected:<br> double xpos;<br> double ypos;<br>protected:<br> Shape(double x, double y);<br>public:<br> double getX() const;<br> double getY() const;<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> We also have a separate interface file (<tt>circle.i</tt>)
+that defines a derived class: </p>
+
+
+
+
+
+<div class="code">
+<pre>%module circle<br><br>%{<br>#include "Shape.h"<br>#include "Circle.h"<br>%}<br><br>// Import the base class definition from Shape module<br>%import shape.i<br><br>class Circle : public Shape {<br>protected:<br> double radius;<br>public:<br> Circle(double x, double y, double r);<br> double getRadius() const;<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> We'll start by building the <b>Shape</b>
+extension module: </p>
+
+
+
+
+
+<div class="code shell">
+<pre>$ <b>swig -c++ -ruby shape.i</b>
+</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> SWIG generates a wrapper file named <tt>shape_wrap.cxx</tt>.
+To compile this into a dynamically loadable extension for Ruby, prepare
+an <tt>extconf.rb</tt> script using this template: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>require 'mkmf'<br><br># Since the SWIG runtime support library for Ruby<br># depends on the Ruby library, make sure it's in the list<br># of libraries.<br>$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])<br><br># Create the makefile<br>create_makefile('shape')<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Run this script to create a <tt>Makefile</tt>
+and then type <tt>make</tt> to build the shared library: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <b>ruby extconf.rb</b><br>creating Makefile<br>$ <b>make</b><br>g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \<br>-I. -c shape_wrap.cxx<br>gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \<br>-lruby -lruby -lc<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note that depending on your installation, the outputs may be
+slightly different; these outputs are those for a Linux-based
+development environment. The end result should be a shared library
+(here, <tt>shape.so</tt>) containing the extension module
+code. Now repeat this process in a separate directory for the <b>Circle</b>
+module: </p>
+
+
+
+
+
+<ol>
+
+
+
+
+
+  <li> Run SWIG to generate the wrapper code (<tt>circle_wrap.cxx</tt>);
+  </li>
+
+
+
+
+
+  <li> Write an <tt>extconf.rb</tt> script that your
+end-users can use to create a platform-specific <tt>Makefile</tt>
+for the extension; </li>
+
+
+
+
+
+  <li> Build the shared library for this extension by typing <tt>make</tt>.
+  </li>
+
+
+
+
+
+</ol>
+
+
+
+
+
+<p> Once you've built both of these extension modules, you can
+test them interactively in IRB to confirm that the <tt>Shape</tt>
+and <tt>Circle</tt> modules are properly loaded and
+initialized: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'shape'</b><br>true<br>irb(main):002:0&gt; <b>require 'circle'</b><br>true<br>irb(main):003:0&gt; <b>c = Circle::Circle.new(5, 5, 20)</b><br>#&lt;Circle::Circle:0xa097208&gt;<br>irb(main):004:0&gt; <b>c.kind_of? Shape::Shape</b><br>true<br>irb(main):005:0&gt; <b>c.getX()</b><br>5.0<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<H3><a name="Ruby_nn56"></a>31.9.3 Specifying Mixin Modules</H3>
+
+
+<p> The Ruby language doesn't support multiple inheritance, but
+it does allow you to mix one or more modules into a class using Ruby's <tt>include</tt>
+method. For example, if you have a Ruby class that defines an <em>each</em>
+instance method, e.g. </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>class Set<br> def initialize<br> @members = []<br> end<br> <br> def each<br> @members.each { |m| yield m }<br> end<br>end<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> then you can mix-in Ruby's <tt>Enumerable</tt>
+module to easily add a lot of functionality to your class: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>class Set<br> <b>include Enumerable</b><br>def initialize<br>@members = []<br>end<br>def each<br>@members.each { |m| yield m }<br>end<br>end<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> To get the same benefit for your SWIG-wrapped classes, you
+can use the <tt>%mixin</tt> directive to specify the names
+of one or more modules that should be mixed-in to a class. For the
+above example, the SWIG interface specification might look like this: </p>
+
+
+
+
+
+<div class="code">
+<pre>%mixin Set "Enumerable";<br><br>class Set {<br>public:<br> // Constructor<br> Set();<br> <br> // Iterates through set members<br> void each();<br>};<br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Multiple modules can be mixed into a class by providing a
+comma-separated list of module names to the <tt>%mixin</tt>
+directive, e.g. </p>
+
+
+
+
+
+<div class="code">
+<pre>%mixin Set "Fee,Fi,Fo,Fum";</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note that the <tt>%mixin</tt> directive is
+implemented using SWIG's "features" mechanism and so the same name
+matching rules used for other kinds of features apply (see the chapter
+on <a href="Customization.html#Customization">"Customization
+Features"</a>) for more details). </p>
+
+
+
+
+
+<H2><a name="Ruby_nn57"></a>31.10 Memory Management</H2>
+
+
+<p>One of the most common issues in generating SWIG bindings for
+Ruby is proper memory management. The key to proper memory management
+is clearly defining whether a wrapper Ruby object owns the underlying C
+struct or C++ class. There are two possibilities:</p>
+
+
+
+
+
+<ul>
+
+
+
+
+
+  <li> The Ruby object is responsible for freeing the C struct or
+C++ object </li>
+
+
+
+
+
+  <li> The Ruby object should not free the C struct or C++ object
+because it will be freed by the underlying C or C++ code</li>
+
+
+
+
+
+</ul>
+
+
+
+
+
+<p>To complicate matters, object ownership may transfer from Ruby
+to C++ (or vice versa) depending on what function or methods are
+invoked. Clearly, developing a SWIG wrapper requires a thorough
+understanding of how the underlying library manages memory.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn58"></a>31.10.1 Mark and Sweep Garbage Collector </H3>
+
+
+<p>Ruby uses a mark and sweep garbage collector. When the garbage
+collector runs, it finds all the "root" objects, including local
+variables, global variables, global constants, hardware registers and
+the C stack. For each root object, the garbage collector sets its mark
+flag to true and calls <tt>rb_gc_mark</tt> on the object.
+The job of <tt>rb_gc_mark</tt> is to recursively mark all
+the objects that a Ruby object has a reference to (ignoring those
+objects that have already been marked). Those objects, in turn, may
+reference other objects. This process will continue until all active
+objects have been "marked." After the mark phase comes the sweep phase.
+In the sweep phase, all objects that have not been marked will be
+garbage collected. For more information about the Ruby garbage
+collector please refer to <a href="http://rubygarden.org/ruby/ruby?GCAndExtensions"> <span style="text-decoration: underline;">http://rubygarden.org/ruby/ruby?GCAndExtensions</span></a>.</p>
+
+
+
+
+
+<p>The Ruby C/API provides extension developers two hooks into
+the garbage collector - a "mark" function and a "sweep" function. By
+default these functions are set to NULL.</p>
+
+
+
+
+
+<p>If a C struct or C++ class references any other Ruby objects,
+then it must provide a "mark" function. The "mark" function should
+identify any referenced Ruby objects by calling the rb_gc_mark function
+for each one. Unsurprisingly, this function will be called by the Ruby
+garbage during the "mark" phase.</p>
+
+
+
+
+
+<p>During the sweep phase, Ruby destroys any unused objects. If
+any memory has been allocated in creating the underlying C struct or
+C++ struct, then a "free" function must be defined that deallocates
+this memory. </p>
+
+
+
+
+
+<H3><a name="Ruby_nn59"></a>31.10.2 Object Ownership</H3>
+
+
+<p>As described above, memory management depends on clearly
+defining who is responsible for freeing the underlying C struct or C++
+class. If the Ruby object is responsible for freeing the C++ object,
+then a "free" function must be registered for the object. If the Ruby
+object is not responsible for freeing the underlying memory, then a
+"free" function must not be registered for the object.</p>
+
+
+
+
+
+<p>For the most part, SWIG takes care of memory management
+issues. The rules it uses are:</p>
+
+
+
+
+
+<ul>
+
+
+
+
+
+  <li> When calling a C++ object's constructor from Ruby, SWIG
+will assign a "free" function thereby making the Ruby object
+responsible for freeing the C++ object</li>
+
+
+
+
+
+  <li> When calling a C++ member function that returns a pointer,
+SWIG will not assign a "free" function thereby making the underlying
+library responsible for freeing the object.</li>
+
+
+
+
+
+</ul>
+
+
+
+
+
+<p>To make this clearer, let's look at an example. Assume we have
+a Foo and a Bar class. </p>
+
+
+
+
+
+<div class="code">
+<pre>/* File "RubyOwernshipExample.h" */<br><br>class Foo<br>{<br>public:<br> Foo() {}<br> ~Foo() {}<br>};<br><br>class Bar<br>{<br> Foo *foo_;<br>public:<br> Bar(): foo_(new Foo) {}<br> ~Bar() { delete foo_; }<br> Foo* get_foo() { return foo_; }<br> Foo* get_new_foo() { return new Foo; }<br> void set_foo(Foo *foo) { delete foo_; foo_ = foo; }<br>};<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>First, consider this Ruby code: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>foo = Foo.new</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In this case, the Ruby code calls the underlying <tt>Foo</tt>
+C++ constructor, thus creating a new <tt>foo</tt> object.
+By default, SWIG will assign the new Ruby object a "free" function.
+When the Ruby object is garbage collected, the "free" function will be
+called. It in turn will call <tt>Foo's</tt> destructor.</p>
+
+
+
+
+
+<p>Next, consider this code: </p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>bar = Bar.new<br>foo = bar.get_foo()</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In this case, the Ruby code calls a C++ member function, <tt>get_foo</tt>.
+By default, SWIG will not assign the Ruby object a "free" function.
+Thus, when the Ruby object is garbage collected the underlying C++ <tt>foo</tt>
+object is not affected.</p>
+
+
+
+
+
+<p>Unfortunately, the real world is not as simple as the examples
+above. For example:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>bar = Bar.new<br>foo = bar.get_new_foo()</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>In this case, the default SWIG behavior for calling member
+functions is incorrect. The Ruby object should assume ownership of the
+returned object. This can be done by using the %newobject directive.
+See <a href="file:///d:/msys/1.0/src/SWIG/Doc/Manual/Customization.html#ownership">
+Object ownership and %newobject</a> for more information. </p>
+
+
+
+
+
+<p>The SWIG default mappings are also incorrect in this case:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>foo = Foo.new<br>bar = Bar.new<br>bar.set_foo(foo)</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Without modification, this code will cause a segmentation
+fault. When the Ruby <tt>foo</tt> object goes out of
+scope, it will free the underlying C++ <tt>foo</tt>
+object. However, when the Ruby bar object goes out of scope, it will
+call the C++ bar destructor which will also free the C++ <tt>foo</tt>
+object. The problem is that object ownership is transferred from the
+Ruby object to the C++ object when the <tt>set_foo</tt>
+method is called. This can be done by using the special DISOWN type
+map, which was added to the Ruby bindings in SWIG-1.3.26.</p>
+
+
+
+
+
+<p>Thus, a correct SWIG interface file correct mapping for these
+classes is:</p>
+
+
+
+
+
+<div class="code">
+<pre>/* File RubyOwnershipExample.i */<br><br>%module RubyOwnershipExample<br><br>%{<br>#include "RubyOwnershipExample.h"<br>%}<br><br>class Foo<br>{<br>public:<br> Foo();<br> ~Foo();<br>};<br><br>class Bar<br>{<br> Foo *foo_;<br>public:<br> Bar();<br> ~Bar();<br> Foo* get_foo();<br><br><span style="font-weight: bold;"> %newobject get_new_foo;</span><br> Foo* get_new_foo();<br><br><span style="font-weight: bold;"> %apply SWIGTYPE *DISOWN {Foo *foo};</span><br> void set_foo(Foo *foo);<br><span style="font-weight: bold;"> %clear Foo *foo;</span><br>};<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<br>
+
+
+
+
+
+<p> This code can be seen in swig/examples/ruby/tracking.</p>
+
+
+
+
+
+<br>
+
+
+
+
+
+<H3><a name="Ruby_nn60"></a>31.10.3 Object Tracking</H3>
+
+
+<p>The remaining parts of this section will use the class library
+shown below to illustrate different memory management techniques. The
+class library models a zoo and the animals it contains. </p>
+
+
+
+
+
+<div class="code">
+<pre>%module zoo<br><br>%{<br>#include &lt;string&gt;<br>#include &lt;vector&gt;<br><br>#include "zoo.h"<br>%}<br><br>class Animal<br>{<br>private:<br> typedef std::vector&lt;Animal*&gt; AnimalsType;<br> typedef AnimalsType::iterator IterType;<br>protected:<br> AnimalsType animals;<br>protected:<br> std::string name_;<br>public:<br> // Construct an animal with this name<br> Animal(const char* name) : name_(name) {}<br> <br> // Return the animal's name<br> const char* get_name() const { return name.c_str(); }<br>};<br><br>class Zoo<br>{<br>protected:<br> std::vector&lt;animal *=""&gt; animals;<br> <br>public:<br> // Construct an empty zoo<br> Zoo() {}<br> <br> /* Create a new animal. */<br> static Animal* Zoo::create_animal(const char* name)<br> {<br> return new Animal(name);<br> }<br><br> // Add a new animal to the zoo<br> void add_animal(Animal* animal) {<br> animals.push_back(animal); <br> }<br><br> Animal* remove_animal(size_t i) {<br> Animal* result = this-&gt;animals[i];<br> IterType iter = this-&gt;animals.begin();<br> std::advance(iter, i);<br> this-&gt;animals.erase(iter);<br><br> return result;<br> }<br> <br> // Return the number of animals in the zoo<br> size_t get_num_animals() const {<br> return animals.size(); <br> }<br> <br> // Return a pointer to the ith animal<br> Animal* get_animal(size_t i) const {<br> return animals[i]; <br> }<br>};<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Let's say you SWIG this code and then run IRB:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be3820&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>=&gt; "tiger1"<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0a60&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo.get_num_animals()</span><br>=&gt; 1<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2bd4a18&gt;<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>=&gt; "tiger1"<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=&gt; false<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Pay particular attention to the code <tt>tiger1.equal?(tiger2)</tt>.
+Note that the two Ruby objects are not the same - but they reference
+the same underlying C++ object. This can cause problems. For example:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>irb(main):010:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):011:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):012:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>After the the garbage collector runs, as a result of our call
+to <tt>GC.start</tt>, calling<tt>tiger2.get_name()</tt>
+causes a segmentation fault. The problem is that when <tt>tiger1</tt>
+is garbage collected, it frees the underlying C++ object. Thus, when <tt>tiger2</tt>
+calls the <tt>get_name()</tt> method it invokes it on a
+destroyed object.</p>
+
+
+
+
+
+<p>This problem can be avoided if SWIG enforces a one-to-one
+mapping between Ruby objects and C++ classes. This can be done via the
+use of the <tt>%trackobjects</tt> functionality available
+in SWIG-1.3.26. and later.</p>
+
+
+
+
+
+<p>When the <tt>%trackobjects</tt> is turned on,
+SWIG automatically keeps track of mappings between C++ objects and Ruby
+objects. Note that enabling object tracking causes a slight performance
+degradation. Test results show this degradation to be about 3% to 5%
+when creating and destroying 100,000 animals in a row.</p>
+
+
+
+
+
+<p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>,
+it uses the same name matching rules as other kinds of features (see
+the chapter on <a href="Customization.html#Customization">
+"Customization Features"</a>) . Thus it can be applied on a
+class-by-class basis if needed. To fix the example above:</p>
+
+
+
+
+
+<br>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br><span style="font-weight: bold;">/* Tell SWIG that create_animal creates a new object */</span><br><span style="font-weight: bold;">%newobject Zoo::create_animal;</span><br><br><span style="font-weight: bold;">/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */</span><br style="font-weight: bold;"><span style="font-weight: bold;">%trackobjects;</span><br><br>%include "example.h"</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>When this code runs we see:<br>
+
+
+
+
+
+<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be37d8&gt;<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0a18&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2be37d8&gt;<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=&gt; true<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):010:0&gt; <span style="font-weight: bold;">tiger.get_name()</span><br>=&gt; "tiger1"<br>irb(main):011:0&gt;<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>For those who are interested, object tracking is implemented
+by storing Ruby objects in a hash table and keying them on C++
+pointers. The underlying API is:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code">
+<pre>static void SWIG_RubyAddTracking(void* ptr, VALUE object);<br>static VALUE SWIG_RubyInstanceFor(void* ptr) ;<br>static void SWIG_RubyRemoveTracking(void* ptr);<br>static void SWIG_RubyUnlinkObjects(void* ptr);</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>When an object is created, SWIG will automatically call the <tt>SWIG_RubyAddTracking</tt>
+method. Similarly, when an object is deleted, SWIG will call the <tt>SWIG_RubyRemoveTracking</tt>.
+When an object is returned to Ruby from C++, SWIG will use the <tt>SWIG_RubyInstanceFor</tt>
+method to ensure a one-to-one mapping from Ruby to C++ objects. Last,
+the <tt>RubyUnlinkObjects</tt> method unlinks a Ruby
+object from its underlying C++ object.</p>
+
+
+
+
+
+<p>In general, you will only need to use the <tt>SWIG_RubyInstanceFor</tt>,
+which is required for implementing mark functions as shown below.
+However, if you implement your own free functions (see below) you may
+also have to call the<tt> SWIG_RubyRemoveTracking</tt> and <tt>RubyUnlinkObjects</tt>
+methods.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn61"></a>31.10.4 Mark Functions</H3>
+
+
+<p>With a bit more testing, we see that our class library still
+has problems. For example:<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="targetlang">
+<pre>$ <b>irb</b><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; tiger1 = <span style="font-weight: bold;">Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bea6a8&gt;<br><br>irb(main):003:0&gt; zoo = <span style="font-weight: bold;">Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be7960&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>(irb):12: [BUG] Segmentation fault</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>The problem is that Ruby does not know that the <tt>zoo</tt>
+object contains a reference to a Ruby object. Thus, when Ruby garbage
+collects <span style="font-family: monospace;">tiger1</span>
+it frees the underlying C++ object.</p>
+
+
+
+
+
+<p>This can be fixed by implementing a <tt>mark</tt>
+function as described above in the <a href="Ruby.html#Ruby_nn52">Mark
+and Sweep Garbage Collector</a> section. You can specify a mark
+function by using the <tt>%markfunc</tt> directive. Since
+the <tt>%markfunc</tt> directive is implemented using
+SWIG's' "features" mechanism it uses the same name matching rules as
+other kinds of features (see the chapter on <a href="Customization.html#Customization">"Customization
+Features"</a> for more details). </p>
+
+
+
+
+
+<p>A <tt>mark</tt> function takes a single argument,
+which is a pointer to the C++ object being marked; it should, in turn,
+call <tt>rb_gc_mark()</tt> for any instances that are
+reachable from the current object. The mark function for our <tt>
+Zoo</tt> class should therefore loop over all of the C++ animal
+objects in the zoo object, look up their Ruby object equivalent, and
+then call <tt>rb_gc_mark()</tt>. One possible
+implementation is:</p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>/* Keep track of mappings between C/C++ structs/classes<br> and Ruby objects so we can implement a mark function. */<br><span style="font-weight: bold;">%trackobjects;</span><br><br>/* Specify the mark function */<br><span style="font-weight: bold;">%markfunc Zoo "mark_Zoo";</span><br><br>%include "example.h"<br><br>%header %{<br><br>static void mark_Zoo(void* ptr) {<br> Zoo* zoo = (Zoo*) ptr;<br><br> /* Loop over each object and tell the garbage collector<br> that we are holding a reference to them. */<br> int count = zoo-&gt;get_num_animals();<br><br> for(int i = 0; i &lt; count; ++i) {<br> Animal* animal = zoo-&gt;get_animal(i);<br> VALUE object = SWIG_RubyInstanceFor(animal);<br><br> if (object != Qnil) {<br> rb_gc_mark(object);<br> }<br> }<br>}<br>%}<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p> Note the <tt>mark</tt> function is dependent on
+the <tt>SWIG_RUBY_InstanceFor</tt> method, and thus
+requires that <tt>%trackobjects</tt> is enabled. For more
+information, please refer to the track_object.i test case in the SWIG
+test suite.</p>
+
+
+
+
+
+<p>When this code is compiled we now see:</p>
+
+
+
+
+
+<div class="targetlang">
+<pre>$ <b>irb<br></b>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1=Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be1780&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2bde9c0&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):010:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br>irb(main):014:0&gt; <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;<br><br>irb(main):015:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>=&gt; "tiger1"<br>irb(main):016:0&gt;<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<br>
+
+
+
+
+
+<p>This code can be seen in swig/examples/ruby/mark_function.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn62"></a>31.10.5 Free Functions</H3>
+
+
+<p>By default, SWIG creates a "free" function that is called when
+a Ruby object is garbage collected. The free function simply calls the
+C++ object's destructor.</p>
+
+
+
+
+
+<p>However, sometimes an appropriate destructor does not exist or
+special processing needs to be performed before the destructor is
+called. Therefore, SWIG allows you to manually specify a "free"
+function via the use of the <tt>%freefunc</tt> directive.
+The <tt>%freefunc</tt> directive is implemented using
+SWIG's' "features" mechanism and so the same name matching rules used
+for other kinds of features apply (see the chapter on <a href="Customization.html#Customization">"Customization
+Features"</a>) for more details).</p>
+
+
+
+
+
+<p>IMPORTANT ! - If you define your own free function, then you
+must ensure that you call the underlying C++ object's destructor. In
+addition, if object tracking is activated for the object's class, you
+must also call the <tt>SWIG_RubyRemoveTracking</tt>
+function (of course call this before you destroy the C++ object). Note
+that it is harmless to call this method if object tracking if off so it
+is advised to always call it.</p>
+
+
+
+
+
+<p>Note there is a subtle interaction between object ownership
+and free functions. A custom defined free function will only be called
+if the Ruby object owns the underlying C++ object. This also to Ruby
+objects which are created, but then transfer ownership to C++ objects
+via the use of the <tt>disown</tt> typemap described
+above. </p>
+
+
+
+
+
+<p>To show how to use the <tt>%freefunc</tt>
+directive, let's slightly change our example. Assume that the zoo
+object is responsible for freeing animal that it contains. This means
+that the <span style="font-family: monospace;">Zoo::add_animal</span>
+function should be marked with a <span style="font-family: monospace;">DISOWN</span> typemap
+and the destructor should be updated as below::</p>
+
+
+
+
+
+<div class="code">
+<pre>Zoo::~Zoo() {<br> IterType iter = this-&gt;animals.begin();<br> IterType end = this-&gt;animals.end();<br><br> for(iter; iter != end; ++iter) {<br> Animal* animal = *iter;<br> delete animal;<br> }<br>}</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>When we use these objects in IRB we see:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre class="targetlang"><span style="font-weight: bold;">$irb</span><br>irb(main):002:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bda760&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo = nil</span><br>=&gt; nil<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br><br></pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>The error happens because the C++ <tt>animal</tt>
+object is freed when the <tt>zoo</tt> object is freed.
+Although this error is unavoidable, we can at least prevent the
+segmentation fault. To do this requires enabling object tracking and
+implementing a custom free function that calls the <tt>SWIG_RubyUnlinkObjects</tt>
+function for each animal object that is destroyed. The <tt>SWIG_RubyUnlinkObjects</tt>
+function notifies SWIG that a Ruby object's underlying C++ object is no
+longer valid. Once notified, SWIG will intercept any calls from the
+existing Ruby object to the destroyed C++ object and raise an exception.<br>
+
+
+
+
+
+</p>
+
+
+
+
+
+<div class="code">
+<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>/* Specify that ownership is transferred to the zoo<br>	when calling add_animal */<br>%apply SWIGTYPE *DISOWN { Animal* animal };<br><br>/* Track objects */<br>%trackobjects;<br><br>/* Specify the mark function */<br>%freefunc Zoo "free_Zoo";<br><br>%include "example.h"<br><br>%header %{<br> static void free_Zoo(void* ptr) {<br> Zoo* zoo = (Zoo*) ptr;<br><br> /* Loop over each animal */<br> int count = zoo-&gt;get_num_animals();<br><br> for(int i = 0; i &lt; count; ++i) {<br> /* Get an animal */<br> Animal* animal = zoo-&gt;get_animal(i);<br><br> /* Unlink the Ruby object from the C++ object */<br> SWIG_RubyUnlinkObjects(animal);<br><br> /* Now remove the tracking for this animal */<br> SWIG_RubyRemoveTracking(animal);<br> }<br><br> /* Now call SWIG_RemoveMapping for the zoo */<br> SWIG_RemoveMapping(ptr);<br> <br> /* Now free the zoo which will free the animals it contains */<br> delete zoo;<br> }<br>%} </pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Now when we use these objects in IRB we see:</p>
+
+
+
+
+
+<div class="code targetlang">
+<pre><span style="font-weight: bold;">$irb</span><br>irb(main):002:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bda760&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo = nil</span><br>=&gt; nil<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>RuntimeError: This Animal * already released<br> from (irb):10:in `get_name'<br> from (irb):10<br>irb(main):011:0&gt;</pre>
+
+
+
+
+
+</div>
+
+
+
+
+
+<p>Notice that SWIG can now detect the underlying C++ object has
+been freed, and thus raises a runtime exception.</p>
+
+
+
+
+
+<p>This code can be seen in swig/examples/ruby/free_function.</p>
+
+
+
+
+
+<H3><a name="Ruby_nn63"></a>31.10.6 Embedded Ruby and the C++ Stack</H3>
+
+
+<p>As has been said, the Ruby GC runs and marks objects before
+its
+sweep phase. &nbsp;When the garbage collector is called, it will
+also
+try to mark any Ruby objects (VALUE) it finds in the machine registers
+and in the C++ stack.</p>
+
+
+
+
+
+<p>The stack is basically the history of the functions that have
+been
+called and also contains local variables, such as the ones you define
+whenever you do inside a function:</p>
+
+
+
+
+
+<div class="diagram">VALUE obj; </div>
+
+
+
+
+
+<p>For ruby to determine where its stack space begins, during
+initialization a normal Ruby interpreter will call the ruby_init()
+function which in turn will call a function called Init_stack or
+similar. &nbsp;This function will store a pointer to the location
+where
+the stack points at at that point in time.</p>
+
+
+
+
+
+<p>ruby_init() is presumed to always be called within the main()
+function of your program and whenever the GC is called, ruby will
+assume that the memory between the current location in memory and the
+pointer that was stored previously represents the stack, which may
+contain local (and temporary) VALUE ruby objects. &nbsp; Ruby will
+then be careful not to remove any of those objects in that location.</p>
+
+
+
+
+
+<p>So far so good. &nbsp;For a normal Ruby session, all the
+above is
+completely transparent and magic to the extensions developer.
+&nbsp;&nbsp;</p>
+
+
+
+
+
+<p>However, with an embedded Ruby, it may not always be possible
+to
+modify main() to make sure ruby_init() is called there. &nbsp; As
+such,
+ruby_init() will likely end up being called from within some other
+function. &nbsp;This can lead Ruby to measure incorrectly where the
+stack begins and&nbsp;can result in Ruby incorrectly collecting
+those
+temporary VALUE objects that are created once another&nbsp;function
+is
+called. &nbsp;The end result: random crashes and segmentation
+faults.</p>
+
+
+
+
+
+<p>This problem will often be seen in director functions that are
+used for callbacks, for example. &nbsp;</p>
+
+
+
+
+
+<p>To solve the problem, SWIG can now generate code with director
+functions&nbsp;containing the optional macros SWIG_INIT_STACK and
+SWIG_RELEASE_STACK. &nbsp; These macros will try to force Ruby to
+reinitiliaze the beginning of the stack&nbsp;the first time a
+director
+function is called. &nbsp;This will lead Ruby to measure and not
+collect any VALUE objects defined from that point on. &nbsp;</p>
+
+
+
+
+
+<p>To mark functions to either reset the ruby stack or not, you
+can use:</p>
+
+
+
+
+
+<div class="indent code" style="font-family: monospace;">%initstack
+&nbsp; Class::memberfunction; &nbsp;// only re-init the stack
+in this director method<br>
+
+
+
+
+
+%ignorestack Class::memberfunction; &nbsp;// do not re-init the
+stack in this director method<br>
+
+
+
+
+
+%initstack &nbsp; Class; &nbsp; &nbsp; &nbsp;
+&nbsp; &nbsp; &nbsp; &nbsp; // init the stack on all
+the methods of this class<br>
+
+
+
+
+
+%initstack; &nbsp; // all director functions will
+re-init the stack</div>
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/SWIG.html b/trunk/Doc/Manual/SWIG.html
new file mode 100644
index 0000000..c22d81c
--- /dev/null
+++ b/trunk/Doc/Manual/SWIG.html
@@ -0,0 +1,3039 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG Basics</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="SWIG"></a>5 SWIG Basics</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#SWIG_nn2">Running SWIG</a>
+<ul>
+<li><a href="#SWIG_nn3">Input format</a>
+<li><a href="#output">SWIG Output</a>
+<li><a href="#SWIG_nn5">Comments</a>
+<li><a href="#SWIG_nn6">C Preprocessor</a>
+<li><a href="#SWIG_nn7">SWIG Directives</a>
+<li><a href="#SWIG_nn8">Parser Limitations</a>
+</ul>
+<li><a href="#SWIG_nn9">Wrapping Simple C Declarations</a>
+<ul>
+<li><a href="#SWIG_nn10">Basic Type Handling</a>
+<li><a href="#SWIG_nn11">Global Variables</a>
+<li><a href="#SWIG_nn12">Constants</a>
+<li><a href="#SWIG_nn13">A brief word about <tt>const</tt></a>
+<li><a href="#SWIG_nn14">A cautionary tale of <tt>char *</tt></a>
+</ul>
+<li><a href="#SWIG_nn15">Pointers and complex objects</a>
+<ul>
+<li><a href="#SWIG_nn16">Simple pointers</a>
+<li><a href="#SWIG_nn17">Run time pointer type checking</a>
+<li><a href="#SWIG_nn18">Derived types, structs, and classes</a>
+<li><a href="#SWIG_nn19">Undefined datatypes</a>
+<li><a href="#SWIG_nn20">Typedef</a>
+</ul>
+<li><a href="#SWIG_nn21">Other Practicalities</a>
+<ul>
+<li><a href="#SWIG_nn22">Passing structures by value</a>
+<li><a href="#SWIG_nn23">Return by value</a>
+<li><a href="#SWIG_nn24">Linking to structure variables</a>
+<li><a href="#SWIG_nn25">Linking to <tt>char *</tt></a>
+<li><a href="#SWIG_nn26">Arrays</a>
+<li><a href="#SWIG_readonly_variables">Creating read-only variables</a>
+<li><a href="#SWIG_rename_ignore">Renaming and ignoring declarations</a>
+<li><a href="#SWIG_default_args">Default/optional arguments</a>
+<li><a href="#SWIG_nn30">Pointers to functions and callbacks</a>
+</ul>
+<li><a href="#SWIG_nn31">Structures and unions</a>
+<ul>
+<li><a href="#SWIG_nn32">Typedef and structures</a>
+<li><a href="#SWIG_nn33">Character strings and structures</a>
+<li><a href="#SWIG_nn34">Array members</a>
+<li><a href="#SWIG_structure_data_members">Structure data members</a>
+<li><a href="#SWIG_nn36">C constructors and destructors </a>
+<li><a href="#SWIG_adding_member_functions">Adding member functions to C structures</a>
+<li><a href="#SWIG_nested_structs">Nested structures</a>
+<li><a href="#SWIG_nn39">Other things to note about structure wrapping</a>
+</ul>
+<li><a href="#SWIG_nn40">Code Insertion</a>
+<ul>
+<li><a href="#SWIG_nn41">The output of SWIG</a>
+<li><a href="#SWIG_nn42">Code insertion blocks</a>
+<li><a href="#SWIG_nn43">Inlined code blocks</a>
+<li><a href="#SWIG_nn44">Initialization blocks</a>
+</ul>
+<li><a href="#SWIG_nn45">An Interface Building Strategy</a>
+<ul>
+<li><a href="#SWIG_nn46">Preparing a C program for SWIG</a>
+<li><a href="#SWIG_nn47">The SWIG interface file</a>
+<li><a href="#SWIG_nn48">Why use separate interface files?</a>
+<li><a href="#SWIG_nn49">Getting the right header files</a>
+<li><a href="#SWIG_nn50">What to do with main()</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes the basic operation of SWIG, the structure of its
+input files, and how it handles standard ANSI C declarations.  C++ support is
+described in the next chapter.  However, C++ programmers should still read this
+chapter to understand the basics.
+Specific details about each target language are described in later
+chapters. 
+</p>
+
+<H2><a name="SWIG_nn2"></a>5.1 Running SWIG</H2>
+
+
+<p>
+To run SWIG, use the <tt>swig</tt> command with options options and a filename like this:
+</p>
+
+<div class="shell"><pre>
+swig [ <em>options</em> ] filename
+</pre></div>
+
+<p>
+where <tt>filename</tt> is a SWIG interface file or a C/C++ header file.
+Below is a subset of <em>options</em> that can be used.
+Additional options are also defined for each target language.  A full list
+can be obtained by typing <tt>swig -help</tt> or <tt>swig
+-<em>lang</em> -help</tt>.
+</p>
+
+<div class="shell"><pre>
+-allegrocl            Generate ALLEGROCL wrappers
+-chicken              Generate CHICKEN wrappers
+-clisp                Generate CLISP wrappers
+-cffi                 Generate CFFI wrappers
+-csharp               Generate C# wrappers
+-guile                Generate Guile wrappers
+-java                 Generate Java wrappers
+-lua                  Generate Lua wrappers
+-modula3              Generate Modula 3 wrappers
+-mzscheme             Generate Mzscheme wrappers
+-ocaml                Generate Ocaml wrappers
+-perl                 Generate Perl wrappers
+-php4                 Generate PHP4 wrappers
+-php5                 Generate PHP5 wrappers
+-pike                 Generate Pike wrappers
+-python               Generate Python wrappers
+-r                    Generate R (aka GNU S) wrappers
+-ruby                 Generate Ruby wrappers
+-sexp                 Generate Lisp S-Expressions wrappers
+-tcl                  Generate Tcl wrappers
+-uffi                 Generate Common Lisp / UFFI wrappers
+-xml                  Generate XML wrappers
+
+-c++                  Enable C++ parsing
+-D<em>symbol</em>              Define a preprocessor symbol
+-Fstandard            Display error/warning messages in commonly used format
+-Fmicrosoft           Display error/warning messages in Microsoft format
+-help                 Display all options
+-I<em>dir</em>                 Add a directory to the file include path
+-l<em>file</em>                Include a SWIG library file.
+-module <em>name</em>          Set the name of the SWIG module
+-o <em>outfile</em>            Name of output file
+-outdir <em>dir</em>           Set language specific files output directory
+-swiglib              Show location of SWIG library
+-version              Show SWIG version number
+
+</pre></div>
+
+<H3><a name="SWIG_nn3"></a>5.1.1 Input format</H3>
+
+
+<p>
+As input, SWIG expects a file containing ANSI C/C++ declarations and
+special SWIG directives.  More often than not, this is a special SWIG
+interface file which is usually denoted with a special <tt>.i</tt> or
+<tt>.swg</tt> suffix.  In certain cases, SWIG can be used directly on
+raw header files or source files.  However, this is not the most
+typical case and there are several reasons why you might not want to
+do this (described later).
+</p>
+
+<p>
+The most common format of a SWIG interface is as follows:
+</p>
+
+<div class="code"><pre>
+%module mymodule 
+%{
+#include "myheader.h"
+%}
+// Now list ANSI C/C++ declarations
+int foo;
+int bar(int x);
+...
+</pre></div>
+<p>
+The name of the module is supplied using the special <tt>%module</tt>
+directive (or the <tt>-module</tt> command line option).  This
+directive must appear at the beginning of the file and is used to name
+the resulting extension module (in addition, this name often defines
+a namespace in the target language).  If the module name is supplied on the
+command line, it overrides the name specified with the
+<tt>%module</tt> directive.
+</p>
+
+<p>
+Everything in the <tt>%{ ... %}</tt> block is simply copied verbatim
+to the resulting wrapper file created by SWIG.  This section is almost
+always used to include header files and other declarations that are
+required to make the generated wrapper code compile.  It is important
+to emphasize that just because you include a declaration in a SWIG
+input file, that declaration does <em>not</em> automatically appear in
+the generated wrapper code---therefore you need to make sure you
+include the proper header files in the <tt>%{ ... %}</tt> section.  It
+should be noted that the text enclosed in <tt>%{ ... %}</tt> is not
+parsed or interpreted by SWIG.  The <tt>%{...%}</tt> syntax and
+semantics in SWIG is analogous to that of the declarations section
+used in input files to parser generation tools such as yacc or bison.
+</p>
+
+<H3><a name="output"></a>5.1.2 SWIG Output</H3>
+
+
+<p>
+The output of SWIG is a C/C++ file that contains all of the wrapper
+code needed to build an extension module.  SWIG may generate some
+additional files depending on the target language. By default, an input file
+with the name <tt>file.i</tt> is transformed into a file
+<tt>file_wrap.c</tt> or <tt>file_wrap.cxx</tt> (depending on whether
+or not the <tt>-c++</tt> option has been used).  The name of the
+output file can be changed using the <tt>-o</tt> option.  In certain
+cases, file suffixes are used by the compiler to determine the source
+language (C, C++, etc.). Therefore, you have to use the
+<tt>-o</tt> option to change the suffix of the SWIG-generated wrapper
+file if you want something different than the default. For example:
+</p>
+
+<div class="shell"><pre>
+$ swig -c++ -python -o example_wrap.cpp example.i
+</pre></div>
+
+<p>
+The C/C++ output file created by SWIG often
+contains everything that is needed to construct a extension module
+for the target scripting language. SWIG is not a stub compiler nor is it
+usually necessary to edit the output file (and if you look at the output,
+you probably won't want to).      To build the final extension module, the
+SWIG output file is compiled and linked with the rest of your C/C++
+program to create a shared library. 
+</p>
+
+<p>
+Many target languages will also generate proxy class files in the
+target language. The default output directory for these language 
+specific files is the same directory as the generated C/C++ file. This can
+can be modified using the <tt>-outdir</tt> option. For example:
+</p>
+
+<div class="shell"><pre>
+$ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
+</pre></div>
+<p>
+If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the following
+will be generated:</p>
+<div class="shell"><pre>
+cppfiles/example_wrap.cpp
+pyfiles/example.py
+</pre></div>
+
+<H3><a name="SWIG_nn5"></a>5.1.3 Comments</H3>
+
+
+<p>
+C and C++ style comments may appear anywhere in interface files.  In
+previous versions of SWIG, comments were used to generate
+documentation files. However, this feature is currently under repair
+and will reappear in a later SWIG release.
+</p>
+
+<H3><a name="SWIG_nn6"></a>5.1.4 C Preprocessor</H3>
+
+
+<p>
+Like C, SWIG preprocesses all input files through an enhanced version
+of the C preprocessor.  All standard preprocessor features are
+supported including file inclusion, conditional compilation and
+macros. However, <tt>#include</tt> statements are ignored unless the
+<tt>-includeall</tt> command line option has been supplied.  The
+reason for disabling includes is that SWIG is sometimes used to
+process raw C header files.  In this case, you usually only want the
+extension module to include functions in the supplied header file
+rather than everything that might be included by that header file
+(i.e., system headers, C library functions, etc.).
+</p>
+
+<p>
+It should also be noted that the SWIG preprocessor skips all text
+enclosed inside a <tt>%{...%}</tt> block.  In addition, the
+preprocessor includes a number of macro handling enhancements that
+make it more powerful than the normal C preprocessor.  These
+extensions are described in the "<a href="Preprocessor.html#Preprocessor">Preprocessor</a>" chapter.
+</p>
+
+<H3><a name="SWIG_nn7"></a>5.1.5 SWIG Directives</H3>
+
+
+<p>
+Most of SWIG's operation is controlled by special directives that are
+always preceded by a "<tt>%</tt>" to distinguish them from normal C
+declarations. These directives are used to give SWIG hints or to alter
+SWIG's parsing behavior in some manner.   
+</p>
+
+<p>
+Since SWIG directives are not legal C syntax, it is generally not
+possible to include them in header files.  However, SWIG directives can be
+included in C header files using conditional compilation like this:
+</p>
+
+<div class="code"><pre>
+/* header.h  --- Some header file */
+
+/* SWIG directives -- only seen if SWIG is running */ 
+#ifdef SWIG
+%module foo
+#endif
+</pre>
+</div>
+
+<p>
+<tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
+it is parsing an input file.
+</p>
+
+<H3><a name="SWIG_nn8"></a>5.1.6 Parser Limitations</H3>
+
+
+<p>
+Although SWIG can parse most C/C++ declarations, it does not
+provide a complete C/C++ parser implementation.  Most of these
+limitations pertain to very complicated type declarations and certain
+advanced C++ features.  Specifically, the following features are not
+currently supported:
+</p>
+
+<ul>
+<li>Non-conventional type declarations.
+For example, SWIG does not support declarations such as the following
+(even though this is legal C):
+
+<div class="code">
+<pre>
+/* Non-conventional placement of storage specifier (extern) */
+const int extern Number;
+
+/* Extra declarator grouping */
+Matrix (foo);    // A global variable
+
+/* Extra declarator grouping in parameters */
+void bar(Spam (Grok)(Doh));
+
+</pre>
+</div>
+
+<p>
+In practice, few (if any) C programmers actually write code like
+this since this style is never featured in programming books.  However,
+if you're feeling particularly obfuscated, you can certainly break SWIG (although why would you want to?).
+</p>
+</li>
+
+<li>Running SWIG on C++ source files (what would appear in a .C or .cxx file) 
+is not recommended.  Even though SWIG can parse C++ class declarations,
+it ignores declarations that are decoupled from their
+original class definition (the declarations are parsed, but a lot of warning
+messages may be generated).  For example:
+
+<div class="code">
+<pre>
+/* Not supported by SWIG */
+int foo::bar(int) {
+    ... whatever ...
+}
+</pre>
+</div>
+</li>
+
+<li>Certain advanced features of C++ such as nested classes 
+are not yet supported. Please see the section on using SWIG
+with C++ for more information.
+</ul>
+
+<p>
+In the event of a parsing error, conditional compilation can be used to skip
+offending code.  For example:
+</p>
+
+<div class="code">
+<pre>
+#ifndef SWIG
+... some bad declarations ...
+#endif
+</pre>
+</div>
+<p>
+Alternatively, you can just delete the offending code from the interface file.
+</p>
+
+<p>
+One of the reasons why SWIG does not provide a full C++ parser
+implementation is that it has been designed to work with incomplete
+specifications and to be very permissive in its handling of C/C++
+datatypes (e.g., SWIG can generate interfaces even when there are
+missing class declarations or opaque datatypes).  Unfortunately, this
+approach makes it extremely difficult to implement certain parts of a
+C/C++ parser as most compilers use type information to assist in the
+parsing of more complex declarations (for the truly curious, the
+primary complication in the implementation is that the SWIG parser
+does not utilize a separate <em>typedef-name</em> terminal symbol as
+described on p. 234 of K&amp;R).
+</p>
+
+<H2><a name="SWIG_nn9"></a>5.2 Wrapping Simple C Declarations</H2>
+
+
+<p>
+SWIG wraps simple C declarations by creating an interface that closely matches
+the way in which the declarations would be used in a C program.
+For example, consider the following interface file:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%inline %{
+extern double sin(double x);
+extern int strcmp(const char *, const char *);
+extern int Foo;
+%}
+#define STATUS 50
+#define VERSION "1.1"
+</pre></div>
+<p>
+In this file, there are two functions <tt>sin()</tt> and <tt>strcmp()</tt>,
+a global variable <tt>Foo</tt>, and two constants <tt>STATUS</tt> and
+<tt>VERSION</tt>.  When SWIG creates an extension module, these
+declarations are accessible as scripting language functions, variables, and
+constants respectively.  For example, in Tcl:
+</p>
+
+<div class="targetlang"><pre>
+% sin 3
+5.2335956
+% strcmp Dave Mike
+-1
+% puts $Foo
+42
+% puts $STATUS
+50
+% puts $VERSION
+1.1
+</pre></div>
+<p>
+Or in Python:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; example.sin(3)
+5.2335956
+&gt;&gt;&gt; example.strcmp('Dave','Mike')
+-1
+&gt;&gt;&gt; print example.cvar.Foo
+42
+&gt;&gt;&gt; print example.STATUS
+50
+&gt;&gt;&gt; print example.VERSION
+1.1
+</pre></div>
+<p>
+Whenever possible, SWIG creates an interface that closely matches the underlying C/C++
+code. However, due to subtle differences between languages, run-time
+environments, and semantics, it is not always possible to do so.   The
+next few sections describes various aspects of this mapping.
+</p>
+
+<H3><a name="SWIG_nn10"></a>5.2.1 Basic Type Handling</H3>
+
+
+<p>
+In order to build an interface, SWIG has to convert C/C++ datatypes to
+equivalent types in the target language.  Generally,
+scripting languages provide a more limited set of primitive types than C.
+Therefore, this conversion process involves a certain amount of type
+coercion.
+</p>
+
+<p>
+Most scripting languages provide a single integer type that is implemented using
+the <tt>int</tt> or <tt>long</tt> datatype in C.   The following list shows
+all of the C datatypes that SWIG will convert to and from integers in the target language:
+</p>
+
+<div class="code"><pre>
+int
+short
+long
+unsigned
+signed
+unsigned short
+unsigned long
+unsigned char
+signed char
+bool
+</pre></div>
+
+<p>
+When an integral value is converted from C, a cast is used to convert it to
+the representation in the target language.
+Thus, a 16 bit short in C may be promoted to a 32 bit integer.  When integers are 
+converted in the other direction, the value is cast back into the original C type.  
+If the value is too large to fit, it is silently truncated.
+<!-- Dave: Maybe we should fix this -->
+</p>
+
+<p>
+<tt>unsigned char</tt> and <tt>signed char</tt> are special cases that
+are handled as small 8-bit integers. Normally, the <tt>char</tt>
+datatype is mapped as a one-character ASCII string. </p>
+
+<p>
+The <tt>bool</tt> datatype is cast to and from an integer value of 0
+and 1 unless the target language provides a special boolean type.</p>
+
+<p>
+Some care is required when working with large integer values. Most
+scripting languages use 32-bit integers so mapping a 64-bit long
+integer may lead to truncation errors. Similar problems may arise with
+32 bit unsigned integers (which may appear as large negative
+numbers). As a rule of thumb, the <tt>int</tt> datatype and all
+variations of <tt>char</tt> and <tt>short</tt> datatypes are safe to
+use. For <tt>unsigned int</tt> and <tt>long</tt> datatypes, you will
+need to carefully check the correct operation of your program after
+it has been wrapped with SWIG.
+</p>
+
+<p>
+Although the SWIG parser supports the <tt>long long</tt> datatype, not
+all language modules support it.  This is because <tt>long long</tt>
+usually exceeds the integer precision available in the target
+language.  In certain modules such as Tcl and Perl5, <tt>long
+long</tt> integers are encoded as strings. This allows the full range
+of these numbers to be represented.  However, it does not allow
+<tt>long long</tt> values to be used in arithmetic expressions.  It
+should also be noted that although <tt>long long</tt> is part
+of the ISO C99 standard, it is not universally supported by all C
+compilers.  Make sure you are using a compiler that supports <tt>long
+long</tt> before trying to use this type with SWIG.
+</p>
+
+<p>
+SWIG recognizes the following floating point types :</p>
+
+<div class="code"><pre>
+float
+double
+</pre></div>
+
+<p>
+Floating point numbers are mapped to and from the natural
+representation of floats in the target language. This is almost always
+a C <tt>double</tt>. The rarely used datatype of <tt>long double</tt>
+is not supported by SWIG.</p>
+
+<p>
+The <tt>char</tt> datatype is mapped into a NULL terminated ASCII
+string with a single character. When used in a scripting language it
+shows up as a tiny string containing the character value. When
+converting the value back into C, SWIG takes a character string
+from the scripting language and strips off the first character as the
+char value. Thus if the value "foo" is assigned to a
+<tt>char</tt> datatype, it gets the value `f'.</p>
+
+<p>
+The <tt>char *</tt> datatype is handled as a NULL-terminated ASCII
+string. SWIG maps this into a 8-bit character string in the target
+scripting language. SWIG converts character strings in the target
+language to NULL terminated strings before passing them into
+C/C++. The default handling of these strings does not allow them to
+have embedded NULL bytes.  Therefore, the <tt>char *</tt> datatype is
+not generally suitable for passing binary data.  However, it is
+possible to change this behavior by defining a SWIG typemap.  See the chapter
+on <a href="Typemaps.html#Typemaps">Typemaps</a> for details about this.
+</p>
+
+<p>
+At this time, SWIG provides limited support for Unicode and
+wide-character strings (the C <tt>wchar_t</tt> type).  
+Some languages provide typemaps for wchar_t, but bear in mind these
+might not be portable across different operating systems.  This is a
+delicate topic that is poorly understood by many programmers and not
+implemented in a consistent manner across languages.  For those
+scripting languages that provide Unicode support, Unicode strings are
+often available in an 8-bit representation such as UTF-8 that can be
+mapped to the <tt>char *</tt> type (in which case the SWIG interface
+will probably work).  If the program you are wrapping uses Unicode,
+there is no guarantee that Unicode characters in the target language
+will use the same internal representation (e.g., UCS-2 vs. UCS-4).
+You may need to write some special conversion functions.
+</p>
+
+<H3><a name="SWIG_nn11"></a>5.2.2 Global Variables</H3>
+
+
+<p>
+Whenever possible, SWIG maps C/C++ global variables into scripting language
+variables.  For example,
+</p>
+
+<div class="code"><pre>
+%module example
+double foo;
+
+</pre></div>
+<p>
+results in a scripting language variable like this:
+</p>
+
+<div class="code"><pre>
+# Tcl
+set foo [3.5]                   ;# Set foo to 3.5
+puts $foo                       ;# Print the value of foo
+
+# Python
+cvar.foo = 3.5                  # Set foo to 3.5
+print cvar.foo                  # Print value of foo
+
+# Perl
+$foo = 3.5;                     # Set foo to 3.5
+print $foo,"\n";                # Print value of foo
+
+# Ruby
+Module.foo = 3.5               # Set foo to 3.5
+print Module.foo, "\n"         # Print value of foo
+</pre></div>
+<p>
+Whenever the scripting language variable is used, the underlying C
+global variable is accessed.  Although SWIG makes every
+attempt to make global variables work like scripting language
+variables, it is not always possible to do so.  For instance, in
+Python, all global variables must be accessed through a special
+variable object known as <tt>cvar</tt> (shown above).  In Ruby, variables are
+accessed as attributes of the module. Other languages may
+convert variables to a pair of accessor functions.  For example, the
+Java module generates a pair of functions <tt>double get_foo()</tt>
+and <tt>set_foo(double val)</tt> that are used to manipulate the
+value.
+</p>
+
+<p>
+Finally, if a global variable has been declared as <tt>const</tt>, it
+only supports read-only access.  Note: this behavior is new to SWIG-1.3.
+Earlier versions of SWIG incorrectly handled <tt>const</tt> and created
+constants instead.
+</p>
+
+<H3><a name="SWIG_nn12"></a>5.2.3 Constants</H3>
+
+
+<p>
+Constants can be created using <tt>#define</tt>, enumerations,
+or a special <tt>%constant</tt> directive.  The following
+interface file shows a few valid constant declarations :</p>
+
+<div class="code"><pre>
+#define I_CONST       5               // An integer constant
+#define PI            3.14159         // A Floating point constant
+#define S_CONST       "hello world"   // A string constant
+#define NEWLINE       '\n'            // Character constant
+
+enum boolean {NO=0, YES=1};
+enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
+             SEP, OCT, NOV, DEC};
+%constant double BLAH = 42.37;
+#define F_CONST (double) 5            // A floating pointer constant with cast
+#define PI_4 PI/4
+#define FLAGS 0x04 | 0x08 | 0x40
+
+</pre></div>
+<p>
+In <tt>#define</tt> declarations, the type of a constant is inferred
+by syntax. For example, a number with a decimal point is assumed to be
+floating point.  In addition, SWIG must be able to fully resolve all
+of the symbols used in a <tt>#define</tt> in order for a constant to
+actually be created.  This restriction is necessary because
+<tt>#define</tt> is also used to define preprocessor macros that are
+definitely not meant to be part of the scripting language interface.
+For example:
+</p>
+
+<div class="code">
+<pre>
+#define EXTERN extern
+
+EXTERN void foo();
+</pre>
+</div>
+<p>
+In this case, you probably don't want to create a constant called 
+<tt>EXTERN</tt> (what would the value be?).  In general,
+SWIG will not create constants for macros unless the value can
+be completely determined by the preprocessor.  For instance, in the above example,
+the declaration
+</p>
+
+<div class="code">
+<pre>
+#define PI_4  PI/4
+</pre>
+</div>
+<p>
+defines a constant because <tt>PI</tt> was already defined as a
+constant and the value is known.
+</p>
+
+<p>
+The use of constant expressions is allowed, but SWIG does not evaluate
+them. Rather, it passes them through to the output file and lets the C
+compiler perform the final evaluation (SWIG does perform a limited
+form of type-checking however).</p>
+
+<p>
+For enumerations, it is critical that the original enum definition be
+included somewhere in the interface file (either in a header file or
+in the <tt>%{,%}</tt> block). SWIG only translates the enumeration
+into code needed to add the constants to a scripting language. It
+needs the original enumeration declaration in order to get the correct
+enum values as assigned by the C compiler.
+</p>
+
+<p>
+The <tt>%constant</tt> directive is used to more precisely create
+constants corresponding to different C datatypes.  Although it is not
+usually not needed for simple values, it is more useful when working
+with pointers and other more complex datatypes.  Typically, <tt>%constant</tt>
+is only used when you want to add constants to the scripting language
+interface that are not defined in the original header file. 
+</p>
+
+<H3><a name="SWIG_nn13"></a>5.2.4 A brief word about <tt>const</tt></H3>
+
+
+<p>
+A common confusion with C programming is the semantic meaning of the
+<tt>const</tt> qualifier in declarations--especially when it is mixed
+with pointers and other type modifiers. In fact, previous versions of SWIG
+handled <tt>const</tt> incorrectly--a situation that SWIG-1.3.7 and newer
+releases have fixed.
+</p>
+
+<p>
+Starting with SWIG-1.3, all variable declarations, regardless of any
+use of <tt>const</tt>, are wrapped as global variables.  If a
+declaration happens to be declared as <tt>const</tt>, it is wrapped as
+a read-only variable. To tell if a variable is <tt>const</tt> or not,
+you need to look at the right-most occurrence of the <tt>const</tt>
+qualifier (that appears before the variable name).  If the right-most
+<tt>const</tt> occurs after all other type modifiers (such as
+pointers), then the variable is <tt>const</tt>.  Otherwise, it is not.
+</p>
+
+<p>
+Here are some examples of <tt>const</tt> declarations.
+</p>
+
+<div class="code">
+<pre>
+const char a;           // A constant character
+char const b;           // A constant character (the same)
+char *const c;          // A constant pointer to a character
+const char *const d;    // A constant pointer to a constant character
+</pre>
+</div>
+<p>
+Here is an example of a declaration that is not <tt>const</tt>:
+</p>
+
+<div class="code">
+<pre>
+const char *e;          // A pointer to a constant character.  The pointer
+                        // may be modified.
+</pre>
+</div>
+<p>
+In this case, the pointer <tt>e</tt> can change---it's only the value
+being pointed to that is read-only.
+</p>
+
+<p>
+<b>Compatibility Note:</b> One reason for changing SWIG to handle
+<tt>const</tt> declarations as read-only variables is that there are
+many situations where the value of a <tt>const</tt> variable might
+change.  For example, a library might export a symbol as
+<tt>const</tt> in its public API to discourage modification, but still
+allow the value to change through some other kind of internal
+mechanism.  Furthermore, programmers often overlook the fact that with
+a constant declaration like <tt>char *const</tt>, the underlying data
+being pointed to can be modified--it's only the pointer itself that is
+constant.  In an embedded system, a <tt>const</tt> declaration might
+refer to a read-only memory address such as the location of a
+memory-mapped I/O device port (where the value changes, but writing to
+the port is not supported by the hardware).  Rather than trying to
+build a bunch of special cases into the <tt>const</tt> qualifier, the
+new interpretation of <tt>const</tt> as "read-only" is simple and
+exactly matches the actual semantics of <tt>const</tt> in C/C++.  If
+you really want to create a constant as in older versions of SWIG, use
+the <tt>%constant</tt> directive instead.  For example:
+</p>
+
+<div class="code">
+<pre>
+%constant double PI = 3.14159;
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+#ifdef SWIG
+#define const %constant
+#endif
+const double foo = 3.4;
+const double bar = 23.4;
+const int    spam = 42;
+#ifdef SWIG
+#undef const
+#endif
+...
+
+</pre>
+</div>
+
+<H3><a name="SWIG_nn14"></a>5.2.5 A cautionary tale of <tt>char *</tt></H3>
+
+
+<p>
+Before going any further, there is one bit of caution involving
+<tt>char *</tt> that must now be mentioned.  When strings are passed
+from a scripting language to a C <tt>char *</tt>, the pointer usually
+points to string data stored inside the interpreter.  It is almost
+always a really bad idea to modify this data.  Furthermore, some
+languages may explicitly disallow it.  For instance, in Python,
+strings are supposed be immutable.   If you violate this, you will probably
+receive a vast amount of wrath when you unleash your module on the world.
+</p>
+
+<p>
+The primary source of problems are functions that might modify string data in place.
+A classic example would be a function like this:
+</p>
+
+<div class="code">
+<pre>
+char *strcat(char *s, const char *t)
+</pre>
+</div>
+
+<p>
+Although SWIG will certainly generate a wrapper for this, its behavior
+will be undefined.  In fact, it will probably cause your application
+to crash with a segmentation fault or other memory related problem.
+This is because <tt>s</tt> refers to some internal data in the target
+language---data that you shouldn't be touching.
+</p>
+
+<p>
+The bottom line: don't rely on <tt>char *</tt> for anything other than read-only 
+input values.   However, it must be noted that you could change the behavior of SWIG
+using <a href="Typemaps.html#Typemaps">typemaps</a>.  
+</p>
+
+<H2><a name="SWIG_nn15"></a>5.3 Pointers and complex objects</H2>
+
+
+<p>
+Most C programs manipulate arrays, structures, and other types of objects.  This section
+discusses the handling of these datatypes.
+</p>
+
+<H3><a name="SWIG_nn16"></a>5.3.1 Simple pointers</H3>
+
+
+<p>
+Pointers to primitive C datatypes such as </p>
+
+<div class="code"><pre>
+int *
+double ***
+char **
+</pre></div>
+<p>
+are fully supported by SWIG.  Rather than trying to convert the data being pointed to into a scripting
+representation, SWIG simply encodes the pointer itself into a
+representation that contains the actual value of the pointer and a type-tag.
+Thus, the SWIG representation of the above
+pointers (in Tcl), might look like this:</p>
+
+<div class="targetlang"><pre>
+_10081012_p_int
+_1008e124_ppp_double
+_f8ac_pp_char
+</pre></div>
+
+<p>
+A NULL pointer is represented by the string "NULL" or the value 0
+encoded with type information.</p>
+
+<p>
+All pointers are treated as opaque objects by SWIG. Thus, a pointer
+may be returned by a function and passed around to other C functions
+as needed.  For all practical purposes, the scripting language
+interface works in exactly the same way as you would use the
+pointer in a C program.  The only difference is that there is no mechanism for
+dereferencing the pointer since this would require the target language
+to understand the memory layout of the underlying object.
+</p>
+
+<p>
+The scripting language representation of a pointer value should never be
+manipulated directly.   Even though the values shown look like hexadecimal
+addresses, the numbers used may differ from the actual machine address (e.g.,
+on little-endian machines, the digits may appear in reverse order).
+Furthermore, SWIG does not
+normally map pointers into high-level objects such as associative
+arrays or lists (for example, converting an
+<tt>int *</tt> into an list of integers). There are several reasons
+why SWIG does not do this:</p>
+
+<ul>
+<li>There is not enough information in a C declaration to properly map
+pointers into higher level constructs. For example, an <tt>int *</tt>
+may indeed be an array of integers, but if it contains ten million
+elements, converting it into a list object is probably a bad idea.
+</li>
+
+<li>The underlying semantics associated with a pointer is not known
+by SWIG.   For instance, an <tt>int *</tt> might not be an array at all--perhaps it
+is an output value!
+</li>
+
+<li>By handling all pointers in a consistent manner, the implementation of SWIG is greatly
+simplified and less prone to error.
+</li>
+</ul>
+
+<H3><a name="SWIG_nn17"></a>5.3.2 Run time pointer type checking</H3>
+
+
+<p>
+By allowing pointers to be manipulated from a scripting language, extension modules
+effectively bypass compile-time type checking in the C/C++
+compiler.  To prevent errors, a type signature is encoded into all
+pointer values and is used to perform run-time type checking.  This
+type-checking process is an integral part of SWIG and can not be
+disabled or modified without using typemaps (described in later
+chapters).
+</p>
+
+<p>
+Like C, <tt>void *</tt> matches any kind of pointer.  Furthermore,
+<tt>NULL</tt> pointers can be passed to any function that expects to
+receive a pointer.  Although this has the potential to cause a crash,
+<tt>NULL</tt> pointers are also sometimes used
+as sentinel values or to denote a missing/empty value.  Therefore,
+SWIG leaves NULL pointer checking up to the application.
+</p>
+
+<H3><a name="SWIG_nn18"></a>5.3.3 Derived types, structs, and classes</H3>
+
+
+<p>
+For everything else (structs, classes, arrays, etc...) SWIG applies a
+very simple rule :</p>
+
+<center>
+<b>Everything else is a pointer</b>
+</center>
+
+<p>
+In other words, SWIG manipulates everything else by reference. This
+model makes sense because most C/C++ programs make heavy use of
+pointers and SWIG can use the type-checked pointer mechanism already
+present for handling pointers to basic datatypes.</p>
+
+<p>
+Although this probably sounds complicated, it's really quite
+simple. Suppose you have an interface file like this :</p>
+
+<div class="code"><pre>
+%module fileio
+FILE *fopen(char *, char *);
+int fclose(FILE *);
+unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
+unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
+void *malloc(int nbytes);
+void free(void *);
+
+</pre></div>
+
+<p>
+In this file, SWIG doesn't know what a <tt>FILE</tt> is, but since it's used
+as a pointer, so it doesn't really matter what it is. If you wrapped
+this module into Python, you can use the functions just like you
+expect :</p>
+
+<div class="targetlang"><pre>
+# Copy a file 
+def filecopy(source,target):
+	f1 = fopen(source,"r")
+	f2 = fopen(target,"w")
+	buffer = malloc(8192)
+	nbytes = fread(buffer,8192,1,f1)
+	while (nbytes &gt; 0):
+		fwrite(buffer,8192,1,f2)
+		nbytes = fread(buffer,8192,1,f1)
+	free(buffer)
+
+</pre></div>
+
+<p>
+In this case <tt>f1</tt>,<tt> f2</tt>, and <tt>buffer</tt> are all
+opaque objects containing C pointers. It doesn't matter what value
+they contain--our program works just fine without this knowledge.</p>
+
+<H3><a name="SWIG_nn19"></a>5.3.4 Undefined datatypes</H3>
+
+
+<p>
+When SWIG encounters an undeclared datatype, it automatically assumes
+that it is a structure or class. For example, suppose the following
+function appeared in a SWIG input file:</p>
+
+<div class="code"><pre>
+void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
+</pre></div>
+
+<p>
+SWIG has no idea what a "<tt>Matrix</tt>" is.  However, it is obviously
+a pointer to something so SWIG generates a wrapper using its generic pointer
+handling code. 
+</p>
+
+<p>
+Unlike C or C++, SWIG does not actually care whether <tt>Matrix</tt>
+has been previously defined in the interface file or not.  This
+allows SWIG to generate interfaces from
+only partial or limited information. In some cases, you may not care
+what a <tt>Matrix</tt> really is as long as you can pass an opaque reference to
+one around in the scripting language interface.
+</p>
+
+<p>
+An important detail to mention is that SWIG will gladly generate
+wrappers for an interface when there are unspecified type names.
+However, <b>all unspecified types are internally handled as pointers
+to structures or classes!</b> For example, consider the following declaration:
+</p>
+
+<div class="code">
+<pre>
+void foo(size_t num);
+</pre>
+</div>
+
+<p>
+If <tt>size_t</tt> is undeclared, SWIG generates wrappers
+that expect to receive a type of <tt>size_t *</tt> (this mapping is described shortly).
+As a result, the scripting interface might behave strangely.  For example:
+</p>
+
+<div class="code">
+<pre>
+foo(40);
+TypeError: expected a _p_size_t.
+</pre>
+</div>
+
+<p>
+The only way to fix this problem is to make sure you properly declare type names using
+<tt>typedef</tt>.
+</p>
+
+<!-- We might want to add an error reporting flag to swig -->
+
+<H3><a name="SWIG_nn20"></a>5.3.5 Typedef</H3>
+
+
+<p>
+Like C, <tt>typedef</tt> can be used to define new type names in SWIG. For example:
+</p>
+
+<div class="code"><pre>
+typedef unsigned int size_t;
+</pre></div>
+
+<p>
+<tt>typedef</tt> definitions appearing in a SWIG interface
+are not propagated to the generated wrapper code.  Therefore, they
+either need to be defined in an included header file or placed in the
+declarations section like this:
+</p>
+
+<div class="code">
+<pre>
+%{
+/* Include in the generated wrapper file */
+typedef unsigned int size_t;
+%}
+/* Tell SWIG about it */
+typedef unsigned int size_t;
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+typedef unsigned int size_t;
+%}
+</pre>
+</div>
+
+<p>
+In certain cases, you might be able to include other header files to collect type information.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%import "sys/types.h"
+</pre>
+</div>
+
+<p>
+In this case, you might run SWIG as follows:
+</p>
+
+<div class="shell">
+<pre>
+$ swig -I/usr/include -includeall example.i
+</pre>
+</div>
+
+<p>
+It should be noted that your mileage will vary greatly here.
+System headers are notoriously complicated and may rely upon a variety
+of non-standard C coding extensions (e.g., such as special directives
+to GCC).  Unless you exactly specify the right include directories and
+preprocessor symbols, this may not work correctly (you will have to
+experiment).
+</p>
+
+<p>
+SWIG tracks <tt>typedef</tt> declarations and uses this information
+for run-time type checking. For instance, if you use the above <tt>typedef</tt> and
+had the following function declaration:
+</p>
+
+<div class="code">
+<pre>
+void foo(unsigned int *ptr);
+</pre>
+</div>
+
+<p>
+The corresponding wrapper function will accept arguments of
+type <tt>unsigned int *</tt> or <tt>size_t *</tt>.
+</p>
+
+<H2><a name="SWIG_nn21"></a>5.4 Other Practicalities</H2>
+
+
+<p>
+So far, this chapter has presented almost everything you need to know to use SWIG
+for simple interfaces. However, some C programs use idioms that are somewhat
+more difficult to map to a scripting language interface.  This section describes
+some of these issues.
+</p>
+
+<H3><a name="SWIG_nn22"></a>5.4.1 Passing structures by value</H3>
+
+
+<p>
+Sometimes a C function takes structure parameters that are passed
+by value.  For example, consider the following function:
+</p>
+
+<div class="code"><pre>
+double dot_product(Vector a, Vector b);
+</pre></div>
+
+<p>
+To deal with this, SWIG transforms the function to use pointers by
+creating a wrapper equivalent to the following:
+</p>
+
+<div class="code"><pre>
+double wrap_dot_product(Vector *a, Vector *b) {
+    Vector x = *a;
+    Vector y = *b;
+    return dot_product(x,y);
+}
+</pre></div>
+
+<p>
+In the target language, the <tt>dot_product()</tt> function now accepts pointers
+to Vectors instead of Vectors.  For the most part, this transformation
+is transparent so you might not notice.
+</p>
+
+<H3><a name="SWIG_nn23"></a>5.4.2 Return by value</H3>
+
+
+<p>
+C functions that return structures or classes datatypes by value are more difficult
+to handle. Consider the following function:</p>
+
+<div class="code"><pre>
+Vector cross_product(Vector v1, Vector v2);
+</pre></div>
+
+<p>
+This function wants to return <tt>Vector</tt>, but SWIG only really supports
+pointers.  As a result, SWIG creates a wrapper like this:
+</p>
+
+<div class="code"><pre>
+Vector *wrap_cross_product(Vector *v1, Vector *v2) {
+        Vector x = *v1;
+        Vector y = *v2;
+        Vector *result;
+        result = (Vector *) malloc(sizeof(Vector));
+        *(result) = cross(x,y);
+        return result;
+}
+</pre></div>
+
+<p>
+or if SWIG was run with the <tt>-c++</tt> option:</p>
+
+<div class="code"><pre>
+Vector *wrap_cross(Vector *v1, Vector *v2) {
+        Vector x = *v1;
+        Vector y = *v2;
+        Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
+        return result;
+}
+</pre></div>
+
+<p>
+In both cases, SWIG allocates a new object and returns a reference to it. It
+is up to the user to delete the returned object when it is no longer
+in use. Clearly, this will leak memory if you are unaware of the implicit
+memory allocation and don't take steps to free the result.  That said, it should be
+noted that some language modules can now automatically track newly created objects and
+reclaim memory for you.  Consult the documentation for each language module for more details.
+</p>
+
+<p>
+It should also be noted that the handling of pass/return by value in
+C++ has some special cases.  For example, the above code fragments
+don't work correctly if <tt>Vector</tt> doesn't define a default
+constructor.  The section on SWIG and C++ has more information about this case.
+</p>
+
+<H3><a name="SWIG_nn24"></a>5.4.3 Linking to structure variables</H3>
+
+
+<p>
+When global variables or class members involving structures are
+encountered, SWIG handles them as pointers. For example, a global
+variable like this</p>
+
+<div class="code"><pre>
+Vector unit_i;
+</pre></div>
+
+<p>
+gets mapped to an underlying pair of set/get functions like this :</p>
+
+<div class="code"><pre>
+Vector *unit_i_get() {
+	return &amp;unit_i;
+}
+void unit_i_set(Vector *value) {
+	unit_i = *value;
+}
+</pre></div>
+
+<p>
+Again some caution is in order. A global variable created in this
+manner will show up as a pointer in the target scripting language. It
+would be an extremely bad idea to free or destroy such a pointer.    Also,
+C++ classes must supply a properly defined copy constructor in order for
+assignment to work correctly.
+</p>
+
+<H3><a name="SWIG_nn25"></a>5.4.4 Linking to <tt>char *</tt></H3>
+
+
+<p>
+When a global variable of type <tt>char *</tt> appears, SWIG uses <tt>malloc()</tt> or
+<tt>new</tt> to allocate memory for the new value.   Specifically, if you have a variable
+like this
+</p>
+
+<div class="code">
+<pre>
+char *foo;
+</pre>
+</div>
+
+<p>
+SWIG generates the following code:
+</p>
+
+<div class="code">
+<pre>
+/* C mode */
+void foo_set(char *value) {
+   if (foo) free(foo);
+   foo = (char *) malloc(strlen(value)+1);
+   strcpy(foo,value);
+}
+
+/* C++ mode.  When -c++ option is used */
+void foo_set(char *value) {
+   if (foo) delete [] foo;
+   foo = new char[strlen(value)+1];
+   strcpy(foo,value);
+}
+</pre>
+</div>
+
+<p>
+If this is not the behavior that you want, consider making the variable read-only using the
+<tt>%immutable</tt> directive.  Alternatively, you might write a short assist-function to set the value
+exactly like you want.  For example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+  void set_foo(char *value) {
+       strncpy(foo,value, 50);
+   }
+%}
+</pre>
+</div>
+
+<p>
+Note: If you write an assist function like this, you will have to call
+it as a function from the target scripting language (it does not work
+like a variable).  For example, in Python you will have to write:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; set_foo("Hello World")
+</pre>
+</div>
+
+<p>
+A common mistake with <tt>char *</tt> variables is to link to a variable declared like this:
+</p>
+
+<div class="code">
+<pre>
+char *VERSION = "1.0";
+</pre>
+</div>
+
+<p>
+In this case, the variable will be readable, but any attempt to change
+the value results in a segmentation or general protection fault.  This
+is due to the fact that SWIG is trying to release the old value using
+<tt>free</tt> or <tt>delete</tt> when the string literal value currently assigned to the variable wasn't
+allocated using <tt>malloc()</tt> or <tt>new</tt>.
+To fix this behavior, you can
+either mark the variable as read-only, write a typemap (as described in Chapter 6), 
+or write a special set function as shown.  Another alternative is to declare the
+variable as an array:
+</p>
+
+<div class="code">
+<pre>
+char VERSION[64] = "1.0";
+</pre>
+</div>
+
+<p>
+When variables of type <tt>const char *</tt> are declared, SWIG still generates functions for setting and
+getting the value.  However, the default behavior does <em>not</em> release the previous contents (resulting in
+a possible memory leak).  In fact, you may get a warning message such as this when wrapping such a variable:
+</p>
+
+<div class="shell">
+<pre>
+example.i:20. Typemap warning. Setting const char * variable may leak memory
+</pre>
+</div>
+
+<p>
+The reason for this behavior is that <tt>const char *</tt> variables are often used to point to string literals.
+For example:
+</p>
+
+<div class="code">
+<pre>
+const char *foo = "Hello World\n";
+</pre>
+</div>
+
+<p>
+Therefore, it's a really bad idea to call <tt>free()</tt> on such a
+pointer.  On the other hand, it <em>is</em> legal to change the
+pointer to point to some other value.  When setting a variable of this
+type, SWIG allocates a new string (using malloc or new) and changes
+the pointer to point to the new value.  However, repeated
+modifications of the value will result in a memory leak since the old
+value is not released. 
+</p>
+
+
+
+
+<H3><a name="SWIG_nn26"></a>5.4.5 Arrays</H3>
+
+
+<p>
+Arrays are fully supported by SWIG, but they are always handled as pointers instead
+of mapping them to a special array object or list in the target language.  Thus, the
+following declarations :</p>
+
+<div class="code"><pre>
+int foobar(int a[40]);
+void grok(char *argv[]);
+void transpose(double a[20][20]);
+</pre></div>
+
+<p>
+are processed as if they were really declared like this:
+</p>
+
+<div class="code"><pre>
+int foobar(int *a);
+void grok(char **argv);
+void transpose(double (*a)[20]);
+</pre></div>
+
+<p>
+Like C, SWIG does not perform array bounds checking.  
+It is up to the
+user to make sure the pointer points a suitably allocated region of memory. 
+</p>
+
+<p>
+Multi-dimensional arrays are transformed into a pointer to an array of one less
+dimension.  For example:
+</p>
+
+<div class="code">
+<pre>
+int [10];         // Maps to int *
+int [10][20];     // Maps to int (*)[20]
+int [10][20][30]; // Maps to int (*)[20][30]
+</pre>
+</div>
+
+<p>
+It is important to note that in the C type system, a multidimensional
+array <tt>a[][]</tt> is <b>NOT</b> equivalent to a single pointer
+<tt>*a</tt> or a double pointer such as <tt>**a</tt>.  Instead, a
+pointer to an array is used (as shown above) where the actual value of
+the pointer is the starting memory location of the array.  The
+reader is strongly advised to dust off their C book and re-read the
+section on arrays before using them with SWIG.
+</p>
+
+<p>
+Array variables are supported, but are read-only by default.  For example:
+</p>
+
+<div class="code">
+<pre>
+int   a[100][200];
+</pre>
+</div>
+
+<p>
+In this case, reading the variable 'a' returns a pointer of type <tt>int (*)[200]</tt>
+that points to the first element of the array <tt>&amp;a[0][0]</tt>.  Trying to modify 'a' results
+in an error.  This is because SWIG does not know how to copy data from the target
+language into the array.   To work around this limitation, you may want to write
+a few simple assist functions like this:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+void a_set(int i, int j, int val) {
+   a[i][j] = val;
+}
+int a_get(int i, int j) {
+   return a[i][j];
+}
+%}
+</pre>
+</div>
+
+<p>
+To dynamically create arrays of various sizes and shapes, it may be useful to write
+some helper functions in your interface.  For example:
+</p>
+
+<div class="code">
+<pre>
+// Some array helpers
+%inline %{
+  /* Create any sort of [size] array */
+  int *int_array(int size) {
+     return (int *) malloc(size*sizeof(int));
+  }
+  /* Create a two-dimension array [size][10] */
+  int (*int_array_10(int size))[10] {
+     return (int (*)[10]) malloc(size*10*sizeof(int));
+  }
+%}
+</pre>
+</div>
+
+<p>
+Arrays of <tt>char</tt> are handled as a special case by SWIG.  In this case, strings in the
+target language can be stored in the array.  For example, if you have a declaration like this,
+</p>
+
+<div class="code">
+<pre>
+char pathname[256];
+</pre>
+</div>
+
+<p>
+SWIG generates functions for both getting and setting the value that are equivalent to the following
+code:
+</p>
+
+<div class="code">
+<pre>
+char *pathname_get() {
+   return pathname;
+}
+void pathname_set(char *value) {
+   strncpy(pathname,value,256);
+}
+</pre>
+</div>
+
+<p>
+In the target language, the value can be set like a normal variable.
+</p>
+
+<H3><a name="SWIG_readonly_variables"></a>5.4.6 Creating read-only variables</H3>
+
+
+<p>
+A read-only variable can be created by using the <tt>%immutable</tt>
+directive as shown :</p>
+
+<div class="code"><pre>
+// File : interface.i
+
+int 	a; 			// Can read/write
+%immutable;
+int	b,c,d			// Read only variables
+%mutable;
+double	x,y			// read/write
+</pre></div>
+
+<p>
+The <tt>%immutable</tt> directive enables read-only mode until it is
+explicitly disabled using the <tt>%mutable</tt> directive.  As an alternative to turning
+read-only mode off and on like this, individual declarations can also be tagged as
+immutable.  For example:
+</p>
+
+<div class="code"><pre>
+%immutable x;                   // Make x read-only
+...
+double x;                       // Read-only (from earlier %immutable directive)
+double y;                       // Read-write
+...
+</pre></div>
+
+<p>
+The <tt>%mutable</tt> and <tt>%immutable</tt> directives are actually 
+<a href="Customization.html#features">%feature directives</a> defined like this:
+</p>
+
+<div class="code"><pre>
+#define %immutable   %feature("immutable")
+#define %mutable     %feature("immutable","")
+</pre></div>
+
+<p>
+If you wanted to make all wrapped variables read-only, barring one or two, it might be easier to take this approach:
+</p>
+
+<div class="code"><pre>
+%immutable;                     // Make all variables read-only
+%feature("immutable","0") x;    // except, make x read/write
+...
+double x;
+double y;
+double z;
+...
+</pre></div>
+
+<p>
+Read-only variables are also created when declarations are declared as <tt>const</tt>.
+For example:
+</p>
+
+<div class="code">
+<pre>
+const int foo;               /* Read only variable */
+char * const version="1.0";  /* Read only variable */
+</pre></div>
+
+<p>
+<b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
+<tt>%readonly</tt> and <tt>%readwrite</tt>.   Although these directives still work, they
+generate a warning message.   Simply change the directives to <tt>%immutable;</tt> and
+<tt>%mutable;</tt> to silence the warning.  Don't forget the extra semicolon!
+</p>
+
+<H3><a name="SWIG_rename_ignore"></a>5.4.7 Renaming and ignoring declarations</H3>
+
+
+<p>
+Normally, the name of a C declaration is used when that declaration is
+wrapped into the target language. However, this may generate a
+conflict with a keyword or already existing function in the scripting
+language. To resolve a name conflict, you can use the <tt>%rename</tt>
+directive as shown :</p>
+
+<div class="code"><pre>
+// interface.i
+
+%rename(my_print) print;
+extern void print(char *);
+
+%rename(foo) a_really_long_and_annoying_name;
+extern int a_really_long_and_annoying_name;
+
+</pre></div>
+
+<p>
+SWIG still calls the correct C function, but in this case the
+function <tt>print()</tt> will really be called "<tt>my_print()</tt>"
+in the target language. </p>
+
+<p>
+The placement of the <tt>%rename</tt> directive is arbitrary as long as it appears
+before the declarations to be renamed.  A common technique is to write code for
+wrapping a header file like this:
+</p>
+
+<div class="code"><pre>
+// interface.i
+
+%rename(my_print) print;
+%rename(foo) a_really_long_and_annoying_name;
+
+%include "header.h"
+</pre></div>
+
+<p>
+<tt>%rename </tt>applies a renaming operation to all future
+occurrences of a name. The renaming applies to functions, variables,
+class and structure names, member functions, and member data. For
+example, if you had two-dozen C++ classes, all with a member function
+named `print' (which is a keyword in Python), you could rename them
+all to `output' by specifying :</p>
+
+<div class="code"><pre>
+%rename(output) print; // Rename all `print' functions to `output'
+</pre></div>
+
+<p>
+SWIG does not normally perform any checks to see if the functions it wraps are
+already defined in the target scripting language. However, if you are
+careful about namespaces and your use of modules, you can usually
+avoid these problems.</p>
+
+<p>
+Closely related to <tt>%rename</tt> is the <tt>%ignore</tt> directive.  <tt>%ignore</tt> instructs SWIG
+to ignore declarations that match a given identifier.  For example:
+</p>
+
+<div class="code">
+<pre>
+%ignore print;         // Ignore all declarations named print
+%ignore _HAVE_FOO_H;   // Ignore an include guard constant
+...
+%include "foo.h"       // Grab a header file
+...
+</pre>
+</div>
+
+<p>
+Any function, variable etc which matches <tt>%ignore</tt> will not be wrapped and therefore will not be available from the target language.
+A common usage of <tt>%ignore</tt> is to selectively remove certain declarations from a header file without having
+to add conditional compilation to the header.   However, it should be stressed that this only works for simple
+declarations.  If you need to remove a whole section of problematic code, the SWIG preprocessor should be used instead.
+</p>
+
+<p>
+More powerful variants of <tt>%rename</tt> and <tt>%ignore</tt> directives can be used to help 
+wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the 
+<a href="SWIGPlus.html#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section in the C++ chapter.
+</p>
+
+<p>
+<b>Compatibility note: </b> Older versions of SWIG provided a special <tt>%name</tt> directive for renaming declarations.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%name(output) extern void print(char *);
+</pre>
+</div>
+
+<p>
+This directive is still supported, but it is deprecated and should probably be avoided.  The <tt>%rename</tt>
+directive is more powerful and better supports wrapping of raw header file information.
+</p>
+
+<H3><a name="SWIG_default_args"></a>5.4.8 Default/optional arguments</H3>
+
+
+<p>
+SWIG supports default arguments in both C and C++ code.  For example:
+</p>
+
+<div class="code"><pre>
+int plot(double x, double y, int color=WHITE);
+</pre></div>
+
+<p>
+In this case, SWIG generates wrapper code where the
+default arguments are optional in the target language. For example, this function could be
+used in Tcl as follows :</p>
+
+<div class="targetlang"><pre>
+% plot -3.4 7.5 				# Use default value
+% plot -3.4 7.5 10				# set color to 10 instead
+
+</pre></div>
+
+<p>
+Although the ANSI C standard does not allow default arguments, default
+arguments specified in a SWIG interface work with both C and C++.
+</p>
+
+<p>
+<b>Note:</b> There is a subtle semantic issue concerning the use 
+of default arguments and the SWIG generated wrapper code.  When default
+arguments are used in C code, the default values are emitted into the wrappers and the
+function is invoked with a full set of arguments. This is different to when wrapping C++
+where an overloaded wrapper method is generated for each defaulted argument.
+Please refer to the section on <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a>
+in the C++ chapter for further details.
+</p>
+
+<H3><a name="SWIG_nn30"></a>5.4.9 Pointers to functions and callbacks</H3>
+
+
+<p>
+Occasionally, a C library may include functions that expect to receive
+pointers to functions--possibly to serve as callbacks. SWIG
+provides full support for function pointers provided that the callback
+functions are defined in C and not in the target language.  For example,
+consider a function like this:
+</p>
+
+<div class="code"><pre>
+int binary_op(int a, int b, int (*op)(int,int));
+</pre></div>
+
+<p>
+When you first wrap something like this into an extension module, you
+may find the function to be impossible to use.  For instance, in Python:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; def add(x,y):
+...     return x+y
+...
+&gt;&gt;&gt; binary_op(3,4,add)
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+TypeError: Type error. Expected _p_f_int_int__int
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+The reason for this error is that SWIG doesn't know how to map a scripting
+language function into a C callback.  However, existing C functions can
+be used as arguments provided you install them as constants.
+One way to do this is to use the <tt>%constant</tt> directive like this:
+</p>
+
+<div class="code"><pre>
+/* Function with a callback */
+int binary_op(int a, int b, int (*op)(int,int));
+
+/* Some callback functions */
+%constant int add(int,int);
+%constant int sub(int,int);
+%constant int mul(int,int);
+</pre></div>
+
+<p>
+In this case, <tt>add</tt>, <tt>sub</tt>, and <tt>mul</tt> become function pointer
+constants in the target scripting language.  This allows you to use them as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; binary_op(3,4,add)
+7
+&gt;&gt;&gt; binary_op(3,4,mul)
+12
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Unfortunately, by declaring the callback functions as constants, they are no longer accessible
+as functions. For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; add(3,4)
+Traceback (most recent call last):
+  File "&lt;stdin&gt;", line 1, in ?
+TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+If you want to make a function available as both a callback function and a function, you
+can use the <tt>%callback</tt> and <tt>%nocallback</tt> directives like this:
+</p>
+
+<div class="code">
+<pre>
+/* Function with a callback */
+int binary_op(int a, int b, int (*op)(int,int));
+
+/* Some callback functions */
+%callback("%s_cb");
+int add(int,int);
+int sub(int,int);
+int mul(int,int);
+%nocallback;
+</pre></div>
+
+<p>
+The argument to <tt>%callback</tt> is a printf-style format string that
+specifies the naming convention for the callback constants (<tt>%s</tt> gets replaced
+by the function name).  The callback mode remains in effect until it is explicitly
+disabled using <tt>%nocallback</tt>.  When you do this, the interface now works as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; binary_op(3,4,add_cb)
+7
+&gt;&gt;&gt; binary_op(3,4,mul_cb)
+12
+&gt;&gt;&gt; add(3,4)
+7
+&gt;&gt;&gt; mul(3,4)
+12
+</pre>
+</div>
+
+<p>
+Notice that when the function is used as a callback, special names
+such as <tt>add_cb</tt> is used instead.  To call the function
+normally, just use the original function name such as <tt>add()</tt>.
+</p>
+
+<p>
+SWIG provides a number of extensions to standard C printf formatting
+that may be useful in this context.  For instance, the following
+variation installs the callbacks as all upper-case constants such as
+<tt>ADD</tt>, <tt>SUB</tt>, and <tt>MUL</tt>:
+</p>
+
+<div class="code"><pre>
+/* Some callback functions */
+%callback("%(upper)s");
+int add(int,int);
+int sub(int,int);
+int mul(int,int);
+%nocallback;
+</pre></div>
+
+<p>
+A format string of <tt>"%(lower)s"</tt> converts all characters to lower-case.
+A string of <tt>"%(title)s"</tt> capitalizes the first character and converts the
+rest to lower case.
+</p>
+
+<p>
+And now, a final note about function pointer support.  Although SWIG
+does not normally allow callback functions to be written in the target language, this
+can be accomplished with the use of typemaps and other advanced SWIG features.
+This is described in a later chapter.
+</p>
+
+<H2><a name="SWIG_nn31"></a>5.5 Structures and unions</H2>
+
+
+<p>
+This section describes the behavior of SWIG when processing ANSI C structures and union declarations.  Extensions to
+handle C++ are described in the next section.
+</p>
+
+<p>
+If SWIG encounters the definition of a structure or union, it
+creates a set of accessor functions. Although SWIG does not need
+structure definitions to build an interface, providing definitions
+make it possible to access structure members. The accessor functions
+generated by SWIG simply take a pointer to an object and allow access
+to an individual member. For example, the declaration :</p>
+
+<div class="code"><pre>
+struct Vector {
+	double x,y,z;
+}
+
+</pre></div>
+
+<p>
+gets transformed into the following set of accessor functions :</p>
+
+<div class="code"><pre>
+double Vector_x_get(struct Vector *obj) {
+	return obj-&gt;x;
+}
+double Vector_y_get(struct Vector *obj) { 
+	return obj-&gt;y;
+}
+double Vector_z_get(struct Vector *obj) { 
+	return obj-&gt;z;
+}
+void Vector_x_set(struct Vector *obj, double value) {
+	obj-&gt;x = value;
+}
+void Vector_y_set(struct Vector *obj, double value) {
+	obj-&gt;y = value;
+}
+void Vector_z_set(struct Vector *obj, double value) {
+	obj-&gt;z = value;
+}
+</pre></div>
+
+<p>
+In addition, SWIG creates default constructor and destructor functions if none are
+defined in the interface.  For example:
+</p>
+
+<div class="code"><pre>
+struct Vector *new_Vector() {
+    return (Vector *) calloc(1,sizeof(struct Vector));
+}
+void delete_Vector(struct Vector *obj) {
+    free(obj);
+}
+</pre>
+</div>
+
+<p>
+Using these low-level accessor functions, an object can be minimally manipulated from the target
+language using code like this:
+</p>
+
+<div class="code">
+<pre>
+v = new_Vector()
+Vector_x_set(v,2)
+Vector_y_set(v,10)
+Vector_z_set(v,-5)
+...
+delete_Vector(v)
+</pre>
+</div>
+
+<p>
+However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.
+</p>
+
+<H3><a name="SWIG_nn32"></a>5.5.1 Typedef and structures</H3>
+
+
+<p>
+SWIG supports the following construct which is quite common in C
+programs :</p>
+
+<div class="code"><pre>
+typedef struct {
+	double x,y,z;
+} Vector;
+
+</pre></div>
+
+<p>
+When encountered, SWIG assumes that the name of the object is `Vector'
+and creates accessor functions like before.  The only difference is
+that the use of <tt>typedef</tt> allows SWIG to drop the
+<tt>struct</tt> keyword on its generated code. For example:
+</p>
+
+<div class="code">
+<pre>
+double Vector_x_get(Vector *obj) {
+	return obj-&gt;x;
+}
+</pre>
+</div>
+
+<p>
+If two different names are used like this :</p>
+
+<div class="code"><pre>
+typedef struct vector_struct {
+	double x,y,z;
+} Vector;
+
+</pre></div>
+
+<p>
+the name <tt>Vector</tt> is used instead of <tt>vector_struct</tt> since
+this is more typical C programming style. If declarations defined later in the interface use the type <tt>struct
+vector_struct</tt>, SWIG knows that this is the same as
+<tt>Vector</tt> and it generates the appropriate type-checking code.
+</p>
+
+<H3><a name="SWIG_nn33"></a>5.5.2 Character strings and structures</H3>
+
+
+<p>
+Structures involving character strings require some care. SWIG assumes
+that all members of type <tt>char *</tt> have been dynamically
+allocated using <tt>malloc()</tt> and that they are NULL-terminated
+ASCII strings. When such a member is modified, the previously contents
+will be released, and the new contents allocated. For example :</p>
+
+<div class="code"><pre>
+%module mymodule
+...
+struct Foo {
+	char *name;
+	...
+}
+
+</pre></div>
+
+<p>
+This results in the following accessor functions :</p>
+
+<div class="code"><pre>
+char *Foo_name_get(Foo *obj) {
+	return Foo-&gt;name;
+}
+
+char *Foo_name_set(Foo *obj, char *c) {
+	if (obj-&gt;name) free(obj-&gt;name);
+	obj-&gt;name = (char *) malloc(strlen(c)+1);
+	strcpy(obj-&gt;name,c);
+	return obj-&gt;name;
+}
+</pre></div>
+
+<p>
+If this behavior differs from what you need in your applications,
+the SWIG "memberin" typemap can be used to change it.  See the
+typemaps chapter for further details.
+</p>
+
+<p>
+Note: If the <tt>-c++</tt> option is used, <tt>new</tt> and <tt>delete</tt> are used to
+perform memory allocation.
+</p>
+
+<H3><a name="SWIG_nn34"></a>5.5.3 Array members</H3>
+
+
+<p>
+Arrays may appear as the members of structures, but they will be
+read-only. SWIG will write an accessor function that returns the
+pointer to the first element of the array, but will not write a
+function to change the contents of the array itself. 
+When this
+situation is detected, SWIG may generate a warning message such as the
+following :</p>
+
+<div class="shell"><pre>
+interface.i:116. Warning. Array member will be read-only
+</pre></div>
+
+<p>
+To eliminate the warning message, typemaps can be used, but this is
+discussed in a later chapter.  In many cases, the warning message is
+harmless.
+</p>
+
+<H3><a name="SWIG_structure_data_members"></a>5.5.4 Structure data members</H3>
+
+
+<p>
+Occasionally, a structure will contain data members that are themselves structures.  For example:
+</p>
+
+<div class="code">
+<pre>
+typedef struct Foo {
+   int x;
+} Foo;
+
+typedef struct Bar {
+   int y;
+   Foo f;           /* struct member */
+} Bar;
+</pre>
+</div>
+
+<p>
+When a structure member is wrapped, it is handled as a pointer, unless the <tt>%naturalvar</tt> directive
+is used where it is handled more like a C++ reference (see <a href="SWIGPlus.html#SWIGPlus_member_data">C++ Member data</a>).
+The accessors to the member variable as a pointer is effectively wrapped as follows:
+</p>
+
+<div class="code">
+<pre>
+Foo *Bar_f_get(Bar *b) {
+   return &amp;b-&gt;f;
+}
+void Bar_f_set(Bar *b, Foo *value) {
+   b-&gt;f = *value;
+}
+</pre>
+</div>
+
+<p>
+The reasons for this are somewhat subtle but have to do with the
+problem of modifying and accessing data inside the data member.  For
+example, suppose you wanted to modify the value of <tt>f.x</tt> 
+of a <tt>Bar</tt> object like this:
+</p>
+
+<div class="code">
+<pre>
+Bar *b;
+b-&gt;f.x = 37;
+</pre>
+</div>
+
+<p>
+Translating this assignment to function calls (as would be used inside the scripting
+language interface) results in the following code:
+</p>
+
+<div class="code">
+<pre>
+Bar *b;
+Foo_x_set(Bar_f_get(b),37);
+</pre>
+</div>
+
+<p>
+In this code, if the <tt>Bar_f_get()</tt> function were to return a <tt>Foo</tt> instead of a
+<tt>Foo *</tt>, then the resulting modification would be applied to a <em>copy</em> of <tt>f</tt> and not
+the data member <tt>f</tt> itself.  Clearly that's not what you want!
+</p>
+
+<p>
+It should be noted that this transformation to pointers only occurs if SWIG knows that a data member
+is a structure or class.   For instance, if you had a structure like this,
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   WORD   w;
+};
+</pre>
+</div>
+
+<p>
+and nothing was known about <tt>WORD</tt>, then SWIG will generate more normal accessor functions
+like this:
+</p>
+
+<div class="code">
+<pre>
+WORD Foo_w_get(Foo *f) {
+    return f-&gt;w;
+}
+void Foo_w_set(FOO *f, WORD value) {
+    f-&gt;w = value;
+}
+</pre>
+</div>
+
+
+<p>
+<b>Compatibility Note: </b>  SWIG-1.3.11 and earlier releases transformed all non-primitive member datatypes
+to pointers.  Starting in SWIG-1.3.12,  this transformation <em>only</em> occurs if a datatype is known to be a structure,
+class, or union.    This is unlikely to break existing code.  However, if you need to tell SWIG that an undeclared
+datatype is really a struct, simply use a forward struct declaration such as <tt>"struct Foo;"</tt>.
+</p>
+
+<H3><a name="SWIG_nn36"></a>5.5.5 C constructors and destructors </H3>
+
+
+<p>
+When wrapping structures, it is generally useful to have a mechanism
+for creating and destroying objects.  If you don't do anything, SWIG
+will automatically generate functions for creating and destroying
+objects using <tt>malloc()</tt> and <tt>free()</tt>.  Note: the use of
+<tt>malloc()</tt> only applies when SWIG is used on C code (i.e., when the
+<tt>-c++</tt> option  is <em>not</em> supplied on the command line).  C++ is handled
+differently.
+</p>
+
+<p>
+If you don't want SWIG to generate default constructors for your
+interfaces, you can use the <tt>%nodefaultctor</tt> directive or the
+<tt>-nodefaultctor</tt> command line option.  For example:
+</p>
+
+<div class="shell"><pre>
+swig -nodefaultctor example.i 
+</pre></div>
+
+<p>
+or
+</p>
+
+<div class="code"><pre>
+%module foo
+...
+%nodefaultctor;        // Don't create default constructors
+... declarations ...
+%clearnodefaultctor;   // Re-enable default constructors
+</pre></div>
+
+<p>
+If you need more precise control, <tt>%nodefaultctor</tt> can selectively target individual structure 
+definitions.  For example:
+</p>
+
+<div class="code">
+<pre>
+%nodefaultctor Foo;      // No default constructor for Foo
+...
+struct Foo {             // No default constructor generated.
+};
+
+struct Bar {             // Default constructor generated.
+};
+</pre>
+</div>
+
+
+<p>
+Since ignoring the implicit or default destructors most of the times
+produce memory leaks, SWIG will always try to generate them. If
+needed, however, you can selectively disable the generation of the
+default/implicit destructor by using <tt>%nodefaultdtor </tt>
+</p>
+
+<div class="code">
+<pre>
+%nodefaultdtor Foo; // No default/implicit destructor for Foo
+...
+struct Foo {              // No default destructor is generated.
+};
+
+struct Bar {              // Default destructor generated.
+};
+</pre>
+</div>
+
+
+
+<p>
+<b>Compatibility note:</b> Prior to SWIG-1.3.7, SWIG did not generate default constructors
+or destructors unless you explicitly turned them on using <tt>-make_default</tt>. 
+However, it appears that most users want to have constructor and destructor functions so it
+has now been enabled as the default behavior.
+</p>
+
+<p>
+<b>Note:</b> There are also the <tt>-nodefault</tt> option and
+<tt>%nodefault</tt> directive, which disable both the default or
+implicit destructor generation. This could lead to memory leaks across 
+the target languages, and is highly recommended you don't use them.
+</p>
+
+
+<H3><a name="SWIG_adding_member_functions"></a>5.5.6 Adding member functions to C structures</H3>
+
+
+<p>
+Most languages provide a mechanism for creating classes and
+supporting object oriented programming. From a C standpoint, object
+oriented programming really just boils down to the process of
+attaching functions to structures. These functions normally operate
+on an instance of the structure (or object).  Although there is a
+natural mapping of C++ to such a scheme, there is no direct mechanism
+for utilizing it with C code. However, SWIG provides a special
+<tt>%extend</tt> directive that makes it possible to attach
+methods to C structures for purposes of building an object oriented
+interface. Suppose you have a C header file with
+the following declaration :</p>
+
+<div class="code"><pre>
+/* file : vector.h */
+...
+typedef struct {
+	double x,y,z;
+} Vector;
+
+</pre></div>
+
+<p>
+You can make a <tt>Vector</tt> look a lot like a class by writing a SWIG interface like this:
+</p>
+
+<div class="code"><pre>
+// file : vector.i
+%module mymodule
+%{
+#include "vector.h"
+%}
+
+%include vector.h            // Just grab original C header file
+%extend Vector {             // Attach these functions to struct Vector
+	Vector(double x, double y, double z) {
+		Vector *v;
+		v = (Vector *) malloc(sizeof(Vector));
+		v-&gt;x = x;
+		v-&gt;y = y;
+		v-&gt;z = z;
+		return v;
+	}
+	~Vector() {
+		free($self);
+	}
+	double magnitude() {
+		return sqrt($self-&gt;x*$self-&gt;x+$self-&gt;y*$self-&gt;y+$self-&gt;z*$self-&gt;z);
+	}
+	void print() {
+		printf("Vector [%g, %g, %g]\n", $self-&gt;x,$self-&gt;y,$self-&gt;z);
+	}
+};
+
+</pre></div>
+
+<p>
+Note the usage of the <tt>$self</tt> special variable.
+Its usage is identical to a C++ 'this' pointer and should be used whenever access to the struct instance is required.
+</p>
+
+<p>
+Now, when used with proxy classes in Python, you can do things like
+this :</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; v = Vector(3,4,0)                 # Create a new vector
+&gt;&gt;&gt; print v.magnitude()                # Print magnitude
+5.0
+&gt;&gt;&gt; v.print()                  # Print it out
+[ 3, 4, 0 ]
+&gt;&gt;&gt; del v                      # Destroy it
+</pre></div>
+
+<p>
+The <tt>%extend</tt> directive can also be used inside the definition
+of the Vector structure. For example:</p>
+
+<div class="code"><pre>
+// file : vector.i
+%module mymodule
+%{
+#include "vector.h"
+%}
+
+typedef struct {
+	double x,y,z;
+	%extend {
+		Vector(double x, double y, double z) { ... }
+		~Vector() { ... }
+		...
+	}
+} Vector;
+</pre></div>
+
+<p>
+Finally, <tt>%extend</tt> can be used to access externally written
+functions provided they follow the naming convention used in this
+example :</p>
+
+<div class="code"><pre>
+/* File : vector.c */
+/* Vector methods */
+#include "vector.h"
+Vector *new_Vector(double x, double y, double z) {
+	Vector *v;
+	v = (Vector *) malloc(sizeof(Vector));
+	v-&gt;x = x;
+	v-&gt;y = y;
+	v-&gt;z = z;
+	return v;
+}
+void delete_Vector(Vector *v) {
+	free(v);
+}
+
+double Vector_magnitude(Vector *v) {
+	return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
+}
+
+// File : vector.i
+// Interface file
+%module mymodule
+%{
+#include "vector.h"
+%}
+
+typedef struct {
+	double x,y,z;
+	%extend {
+                Vector(int,int,int); // This calls new_Vector()
+               ~Vector();            // This calls delete_Vector()
+		double magnitude();  // This will call Vector_magnitude()
+		...
+	}
+} Vector;
+</pre>
+</div>
+
+<p>
+A little known feature of the <tt>%extend</tt> directive is that
+it can also be used to add synthesized attributes or to modify the
+behavior of existing data attributes.  For example, suppose you wanted
+to make <tt>magnitude</tt> a read-only attribute of <tt>Vector</tt>
+instead of a method.  To do this, you might write some code like this:
+</p>
+
+<div class="code">
+<pre>
+// Add a new attribute to Vector
+%extend Vector {
+    const double magnitude;
+}
+// Now supply the implementation of the Vector_magnitude_get function
+%{
+const double Vector_magnitude_get(Vector *v) {
+  return (const double) return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
+}
+%}
+
+</pre>
+</div>
+
+<p>
+Now, for all practical purposes, <tt>magnitude</tt> will appear like an attribute
+of the object.
+</p>
+
+<p>
+A similar technique can also be used to work with problematic data members.
+For example, consider this interface:
+</p>
+
+<div class="code">
+<pre>
+struct Person {
+   char name[50];
+   ...
+}
+</pre>
+</div>
+
+<p>
+By default, the <tt>name</tt> attribute is read-only because SWIG does not
+normally know how to modify arrays.  However, you can rewrite the interface
+as follows to change this:
+</p>
+
+<div class="code">
+<pre>
+struct Person {
+    %extend {
+       char *name;
+    }
+...
+}
+
+// Specific implementation of set/get functions
+%{
+char *Person_name_get(Person *p) {
+   return p-&gt;name;
+}
+void Person_name_set(Person *p, char *val) {
+   strncpy(p-&gt;name,val,50);
+}
+%}
+</pre>
+</div>
+
+<p>
+Finally, it should be stressed that even though <tt>%extend</tt>
+can be used to add new data members, these new members can not require
+the allocation of additional storage in the object (e.g., their values must
+be entirely synthesized from existing attributes of the structure).
+</p>
+
+<p>
+<b>Compatibility note:</b>  The <tt>%extend</tt> directive is a new
+name for the <tt>%addmethods</tt> directive.  Since <tt>%addmethods</tt> could
+be used to extend a structure with more than just methods, a more suitable
+directive name has been chosen.
+</p>
+
+<H3><a name="SWIG_nested_structs"></a>5.5.7 Nested structures</H3>
+
+
+<p>
+Occasionally, a C program will involve structures like this :</p>
+
+<div class="code"><pre>
+typedef struct Object {
+	int objtype;
+	union {
+		int 	ivalue;
+		double	dvalue;
+		char	*strvalue;
+		void	*ptrvalue;
+	} intRep;
+} Object;
+
+</pre></div>
+
+<p>
+When SWIG encounters this, it performs a structure splitting operation
+that transforms the declaration into the equivalent of the
+following:</p>
+
+<div class="code"><pre>
+typedef union {
+	int 		ivalue;
+	double		dvalue;
+	char		*strvalue;
+	void		*ptrvalue;
+} Object_intRep;
+
+typedef struct Object {
+	int objType;
+	Object_intRep intRep;
+} Object;
+
+</pre></div>
+
+<p>
+SWIG will then create an <tt>Object_intRep</tt> structure for use inside
+the interface file. Accessor functions will be created for both
+structures. In this case, functions like this would be created :</p>
+
+<div class="code"><pre>
+Object_intRep *Object_intRep_get(Object *o) {
+	return (Object_intRep *) &amp;o-&gt;intRep;
+}
+int Object_intRep_ivalue_get(Object_intRep *o) {
+	return o-&gt;ivalue;
+}
+int Object_intRep_ivalue_set(Object_intRep *o, int value) {
+	return (o-&gt;ivalue = value);
+}
+double Object_intRep_dvalue_get(Object_intRep *o) {
+	return o-&gt;dvalue;
+}
+... etc ...
+
+</pre></div>
+
+<p>
+Although this process is a little hairy, it works like you would expect in the
+target scripting language--especially when proxy classes are used.  For instance, in Perl:
+</p>
+
+<div class="targetlang"><pre>
+# Perl5 script for accessing nested member
+$o = CreateObject();                    # Create an object somehow
+$o-&gt;{intRep}-&gt;{ivalue} = 7              # Change value of o.intRep.ivalue
+</pre></div>
+
+<p>
+If you have a lot nested structure declarations, it is
+advisable to double-check them after running SWIG. Although,
+there is a good chance that they will work, you may have to
+modify the interface file in certain cases.
+
+<H3><a name="SWIG_nn39"></a>5.5.8 Other things to note about structure wrapping</H3>
+
+
+<p>
+SWIG doesn't care if the declaration of a structure in a <tt>.i</tt> file exactly matches
+that used in the underlying C code (except in the case of nested
+structures). For this reason, there are no problems omitting
+problematic members or simply omitting the structure definition
+altogether. If you are happy passing pointers around, this can
+be done without ever giving SWIG a structure definition.</p>
+
+<p>
+Starting with SWIG1.3, a number of improvements have been made to SWIG's
+code generator. Specifically, even though structure access has been described
+in terms of high-level accessor functions such as this,
+</p>
+
+<div class="code">
+<pre>
+double Vector_x_get(Vector *v) {
+   return v-&gt;x;
+}
+</pre>
+</div>
+
+<p>
+most of the generated code is actually inlined directly into wrapper
+functions.  Therefore, no function <tt>Vector_x_get()</tt> actually
+exists in the generated wrapper file.  For example, when creating a Tcl module,
+the following function is generated instead:
+</p>
+
+<div class="code">
+<pre>
+static int
+_wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, 
+                   int objc, Tcl_Obj *CONST objv[]) {
+    struct Vector *arg1 ;
+    double result ;
+    
+    if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&amp;arg0,
+                     SWIGTYPE_p_Vector) == TCL_ERROR)
+         return TCL_ERROR;
+    result = (double ) (arg1-&gt;x);
+    Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result));
+    return TCL_OK;
+}
+</pre>
+</div>
+
+<p>
+The only exception to this rule are methods defined with <tt>%extend</tt>.  In this
+case, the added code is contained in a separate function.
+</p>
+
+<p>
+Finally, it is important to note that most language modules may choose to
+build a more advanced interface. Although you may never use the low-level
+interface described here, most of SWIG's language modules use it in
+some way or another.
+</p>
+
+<H2><a name="SWIG_nn40"></a>5.6 Code Insertion</H2>
+
+
+<p>
+Sometimes it is necessary to insert special code into the resulting
+wrapper file generated by SWIG.  For example, you may want to include
+additional C code to perform initialization or other operations.
+There are four common ways to insert code, but it's useful to know how the
+output of SWIG is structured first.</p>
+
+<H3><a name="SWIG_nn41"></a>5.6.1 The output of SWIG</H3>
+
+
+<p>
+When SWIG creates its output file, it is broken up into four sections
+corresponding to runtime code, headers, wrapper functions, and module
+initialization code (in that order).   
+</p>
+
+<ul>
+<li><b>Runtime code</b>.  <br>
+This code is internal to SWIG and is used to include
+type-checking and other support functions that are used by the rest of the module.
+</li>
+
+<li><b>Header section</b>.  <br>
+This is user-defined support code that has been included by 
+the <tt>%{ ... %}</tt> directive.  Usually this consists of header files and 
+other helper functions.
+</li>
+
+<li><b>Wrapper code</b>.  <br>
+These are the wrappers generated automatically by SWIG.
+</li>
+
+<li><b>Module initialization</b>.  <br>
+The function generated by SWIG to initialize
+the module upon loading.
+</li>
+</ul>
+
+<H3><a name="SWIG_nn42"></a>5.6.2 Code insertion blocks</H3>
+
+
+<p>
+Code is inserted into the appropriate code section by using one
+of the following code insertion directives:
+</p>
+
+<div class="code">
+<pre>
+%runtime %{
+   ... code in runtime section ...
+%}
+
+%header %{
+   ... code in header section ...
+%}
+
+%wrapper %{
+   ... code in wrapper section ...
+%}
+
+%init %{
+   ... code in init section ...
+%}
+</pre>
+</div>
+
+<p>
+The bare <tt>%{ ... %}</tt> directive is a shortcut that is the same as
+<tt>%header %{ ... %}</tt>.
+</p>
+
+<p>
+Everything in a code insertion block is copied verbatim into the output file and is 
+not parsed by SWIG.   Most SWIG input files have at least one such block to include header
+files and support C code.  Additional code blocks may be placed anywhere in a
+SWIG file as needed. </p>
+
+<div class="code"><pre>
+%module mymodule
+%{
+#include "my_header.h"
+%}
+... Declare functions here
+%{
+
+void some_extra_function() {
+  ...
+}
+%}
+</pre></div>
+
+<p>
+A common use for code blocks is to write "helper" functions. These
+are functions that are used specifically for the purpose of building
+an interface, but which are generally not visible to the normal C
+program. For example :</p>
+
+<div class="code"><pre>
+%{
+/* Create a new vector */
+static Vector *new_Vector() {
+	return (Vector *) malloc(sizeof(Vector));
+}
+
+%}
+// Now wrap it 
+Vector *new_Vector();
+</pre></div>
+
+<H3><a name="SWIG_nn43"></a>5.6.3 Inlined code blocks</H3>
+
+
+<p>
+Since the process of writing helper functions is fairly common,
+there is a special inlined form of code block that is used as follows
+:</p>
+
+<div class="code"><pre>
+%inline %{
+/* Create a new vector */
+Vector *new_Vector() {
+	return (Vector *) malloc(sizeof(Vector));
+}
+%}
+
+</pre></div>
+
+<p>
+The <tt>%inline</tt> directive inserts all of the code that follows
+verbatim into the header portion of an interface file. The code is
+then parsed by both the SWIG preprocessor and parser.
+Thus, the above example creates a new command <tt>new_Vector</tt> using only one
+declaration. Since the code inside an <tt>%inline %{ ... %}</tt> block
+is given to both the C compiler and SWIG, it is illegal to include any
+SWIG directives inside a <tt>%{ ... %}</tt> block.</p>
+
+<H3><a name="SWIG_nn44"></a>5.6.4 Initialization blocks</H3>
+
+
+<p>
+When code is included in the <tt>%init</tt> section, it is copied directly into the 
+module initialization function.  For example, if you needed to perform some extra
+initialization on module loading, you could write this:
+</p>
+
+<div class="code"><pre>
+%init %{
+	init_variables();
+%}
+</pre></div>
+
+<H2><a name="SWIG_nn45"></a>5.7 An Interface Building Strategy</H2>
+
+
+<p>
+This section describes the general approach for building interface
+with SWIG. The specifics related to a particular scripting language
+are found in later chapters.</p>
+
+<H3><a name="SWIG_nn46"></a>5.7.1 Preparing a C program for SWIG</H3>
+
+
+<p>
+SWIG doesn't require modifications to your C code, but if you feed it
+a collection of raw C header files or source code, the results might
+not be what you expect---in fact, they might be awful. Here's a series
+of steps you can follow to make an interface for a C program :</p>
+
+<ul>
+<li>Identify the functions that you want to wrap. It's probably not
+necessary to access every single function in a C program--thus, a
+little forethought can dramatically simplify the resulting scripting
+language interface. C header files are particularly good source for
+finding things to wrap.
+
+<li>Create a new interface file to describe the scripting language
+interface to your program.
+
+<li>Copy the appropriate declarations into the interface file or use
+SWIG's <tt>%include</tt> directive to process an entire C
+source/header file. 
+
+<li>Make sure everything in the interface file uses ANSI C/C++syntax.
+
+<li>Make sure all necessary `<tt>typedef</tt>' declarations and
+type-information is available in the interface file.
+
+<li>If your program has a main() function, you may need to rename it
+(read on).
+
+<li>Run SWIG and compile.
+</ul>
+
+<p>
+Although this may sound complicated, the process turns out to be
+fairly easy once you get the hang of it. 
+</p>
+
+<p>
+In the process of building an interface, SWIG may encounter syntax errors or
+other problems.  The best way to deal with this is to simply copy the offending
+code into a separate interface file and edit it.   However, the SWIG developers
+have worked very hard to improve the SWIG parser--you should report parsing errors
+to the <a href="http://www.swig.org/mail.html">swig-devel mailing list</a> or to the 
+<a href="http://www.swig.org/bugs.html">SWIG bug tracker</a>.
+</p>
+
+<H3><a name="SWIG_nn47"></a>5.7.2 The SWIG interface file</H3>
+
+
+<p>
+The preferred method of using SWIG is to generate separate interface
+file. Suppose you have the following C header file :</p>
+
+<div class="code"><pre>
+/* File : header.h */
+
+#include &lt;stdio.h&gt;
+#include &lt;math.h&gt;
+
+extern int foo(double);
+extern double bar(int, int);
+extern void dump(FILE *f);
+
+</pre></div>
+
+<p>
+A typical SWIG interface file for this header file would look like the
+following :</p>
+
+<div class="code"><pre>
+/* File : interface.i */
+%module mymodule
+%{
+#include "header.h"
+%}
+extern int foo(double);
+extern double bar(int, int);
+extern void dump(FILE *f);
+
+</pre></div>
+
+<p>
+Of course, in this case, our header file is pretty simple so we could
+have made an interface file like this as well:</p>
+
+<div class="code"><pre>
+/* File : interface.i */
+%module mymodule
+%include header.h
+</pre></div>
+
+<p>
+Naturally, your mileage may vary.</p>
+
+<H3><a name="SWIG_nn48"></a>5.7.3 Why use separate interface files?</H3>
+
+
+<p>
+Although SWIG can parse many header files, it is more common to write a
+special <tt>.i</tt> file defining the interface to a package. There
+are several reasons why you might want to do this:
+</p>
+
+<ul>
+<li>It is rarely necessary to access every single function in a large
+package. Many C functions might have little or no use in a scripted
+environment. Therefore, why wrap them?
+
+<li>Separate interface files provide an opportunity to provide more
+precise rules about how an interface is to be constructed.
+
+<li>Interface files can provide more structure and organization.
+
+<li>SWIG can't parse certain definitions that appear in header
+files. Having a separate file allows you to eliminate or work around
+these problems.
+
+<li>Interface files provide a more precise definition of what the interface
+is. Users wanting to extend the system can go to the interface file
+and immediately see what is available without having to dig it out of
+header files.
+</ul>
+
+<H3><a name="SWIG_nn49"></a>5.7.4 Getting the right header files</H3>
+
+
+<p>
+Sometimes, it is necessary to use certain header files in order for
+the code generated by SWIG to compile properly. Make sure you
+include certain header files by using a <tt>%{,%}</tt> block like this:
+</p>
+
+<div class="code"><pre>
+%module graphics
+%{
+#include &lt;GL/gl.h&gt;
+#include &lt;GL/glu.h&gt;
+%}
+
+// Put rest of declarations here
+...
+</pre></div>
+
+<H3><a name="SWIG_nn50"></a>5.7.5 What to do with main()</H3>
+
+
+<p>
+If your program defines a <tt>main()</tt> function, you may need to
+get rid of it or rename it in order to use a scripting language. Most
+scripting languages define their own <tt>main()</tt> procedure that
+is called instead. <tt>main()</tt> also makes no sense when
+working with dynamic loading. There are a few approaches to solving
+the <tt>main()</tt> conflict :</p>
+
+<ul>
+<li>Get rid of <tt>main()</tt> entirely. 
+
+<li>Rename <tt>main()</tt> to something else. You can do this by
+compiling your C program with an option like <tt>-Dmain=oldmain</tt>.
+
+<li>Use conditional compilation to only include <tt>main()</tt> when
+not using a scripting language.
+</ul>
+
+<p>
+Getting rid of <tt>main()</tt> may cause potential initialization
+problems of a program. To handle this problem, you may consider
+writing a special function called <tt>program_init()</tt> that
+initializes your program upon startup. This function could then be
+called either from the scripting language as the first operation, or
+when the SWIG generated module is loaded.</p>
+
+<p>
+As a general note, many C programs only use the <tt>main()</tt>
+function to parse command line options and to set parameters. However,
+by using a scripting language, you are probably trying to create a
+program that is more interactive. In many cases, the old
+<tt>main()</tt> program can be completely replaced by a Perl, Python,
+or Tcl script.</p>
+
+<p>
+<b>Note:</b> If some cases, you might be inclined to create a
+scripting language wrapper for <tt>main()</tt>.  If you do this, the
+compilation will probably work and your module might even load
+correctly.  The only trouble is that when you call your
+<tt>main()</tt> wrapper, you will find that it actually invokes the
+<tt>main()</tt> of the scripting language interpreter itself!    This behavior
+is a side effect of the symbol binding mechanism used in the dynamic linker.
+The bottom line: don't do this.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/SWIGPlus.html b/trunk/Doc/Manual/SWIGPlus.html
new file mode 100644
index 0000000..ef7487f
--- /dev/null
+++ b/trunk/Doc/Manual/SWIGPlus.html
@@ -0,0 +1,4843 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and C++</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="SWIGPlus"></a>6 SWIG and C++</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#SWIGPlus_nn2">Comments on C++ Wrapping</a>
+<li><a href="#SWIGPlus_nn3">Approach</a>
+<li><a href="#SWIGPlus_nn4">Supported C++ features</a>
+<li><a href="#SWIGPlus_nn5">Command line options and compilation</a>
+<li><a href="#SWIGPlus_nn38">Proxy classes</a>
+<ul>
+<li><a href="#SWIGPlus_nn39">Construction of proxy classes</a>
+<li><a href="#SWIGPlus_nn40">Resource management in proxies</a>
+<li><a href="#SWIGPlus_nn41">Language specific details</a>
+</ul>
+<li><a href="#SWIGPlus_nn6">Simple C++ wrapping</a>
+<ul>
+<li><a href="#SWIGPlus_nn7">Constructors and destructors</a>
+<li><a href="#SWIGPlus_nn8">Default constructors, copy constructors and implicit destructors</a>
+<li><a href="#SWIGPlus_nn9">When constructor wrappers aren't created</a>
+<li><a href="#SWIGPlus_nn10">Copy constructors</a>
+<li><a href="#SWIGPlus_nn11">Member functions</a>
+<li><a href="#SWIGPlus_nn12">Static members</a>
+<li><a href="#SWIGPlus_member_data">Member data</a>
+</ul>
+<li><a href="#SWIGPlus_default_args">Default arguments</a>
+<li><a href="#SWIGPlus_nn15">Protection</a>
+<li><a href="#SWIGPlus_nn16">Enums and constants</a>
+<li><a href="#SWIGPlus_nn17">Friends</a>
+<li><a href="#SWIGPlus_nn18">References and pointers</a>
+<li><a href="#SWIGPlus_nn19">Pass and return by value</a>
+<li><a href="#SWIGPlus_nn20">Inheritance</a>
+<li><a href="#SWIGPlus_nn21">A brief discussion of multiple inheritance, pointers,  and type checking</a>
+<li><a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a>
+<ul>
+<li><a href="#SWIGPlus_nn24">Dispatch function generation</a>
+<li><a href="#SWIGPlus_nn25">Ambiguity in Overloading</a>
+<li><a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
+<li><a href="#SWIGPlus_nn27">Comments on overloading</a>
+</ul>
+<li><a href="#SWIGPlus_nn28">Wrapping overloaded operators</a>
+<li><a href="#SWIGPlus_class_extension">Class extension</a>
+<li><a href="#SWIGPlus_nn30">Templates</a>
+<li><a href="#SWIGPlus_nn31">Namespaces</a>
+<li><a href="#SWIGPlus_renaming_templated_types_namespaces">Renaming templated types in namespaces</a>
+<li><a href="#SWIGPlus_exception_specifications">Exception specifications</a>
+<li><a href="#SWIGPlus_catches">Exception handling with %catches</a>
+<li><a href="#SWIGPlus_nn33">Pointers to Members</a>
+<li><a href="#SWIGPlus_nn34">Smart pointers and operator-&gt;()</a>
+<li><a href="#SWIGPlus_nn35">Using declarations and inheritance</a>
+<li><a href="#SWIGPlus_nested_classes">Nested classes</a>
+<li><a href="#SWIGPlus_nn37">A brief rant about const-correctness</a>
+<li><a href="#SWIGPlus_nn42">Where to go for more information</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes SWIG's support for wrapping C++.  As a prerequisite,
+you should first read the chapter <a href="SWIG.html#SWIG">SWIG Basics</a> to see
+how SWIG wraps ANSI C.  Support for C++ builds upon ANSI C
+wrapping and that material will be useful in understanding this chapter.
+</p>
+
+<H2><a name="SWIGPlus_nn2"></a>6.1 Comments on C++ Wrapping</H2>
+
+
+<p>
+Because of its complexity and the fact that C++ can be
+difficult to integrate with itself let alone other languages, SWIG 
+only provides support for a subset of C++ features.   Fortunately, 
+this is now a rather large subset.  
+</p>
+
+<p>
+In part, the problem with C++ wrapping is that there is no
+semantically obvious (or automatic ) way to map many of its advanced
+features into other languages.  As a simple example, consider the
+problem of wrapping C++ multiple inheritance to a target language with
+no such support.  Similarly, the use of overloaded operators and
+overloaded functions can be problematic when no such capability exists
+in a target language.
+</p>
+
+<p>
+A more subtle issue with C++ has to do with the way that some C++
+programmers think about programming libraries.  In the world of SWIG,
+you are really trying to create binary-level software components for
+use in other languages.  In order for this to work, a "component" has
+to contain real executable instructions and there has to be some kind
+of binary linking mechanism for accessing its functionality.  In
+contrast, C++ has increasingly relied upon generic programming and
+templates for much of its functionality.
+Although templates are a powerful feature, they are largely orthogonal
+to the whole notion of binary components and libraries.  For example,
+an STL <tt>vector</tt> does not define any kind of binary object for
+which SWIG can just create a wrapper.  To further complicate matters,
+these libraries often utilize a lot of behind the scenes magic in
+which the semantics of seemingly basic operations (e.g., pointer
+dereferencing, procedure call, etc.) can be changed in dramatic and
+sometimes non-obvious ways.  Although this "magic" may present few
+problems in a C++-only universe, it greatly complicates the problem of
+crossing language boundaries and provides many opportunities to shoot
+yourself in the foot.  You will just have to be careful.
+</p>
+
+<H2><a name="SWIGPlus_nn3"></a>6.2 Approach</H2>
+
+
+<p>
+To wrap C++, SWIG uses a layered approach to code generation.  
+At the lowest level, SWIG generates a collection of procedural ANSI-C style
+wrappers.   These wrappers take care of basic type conversion,
+type checking, error handling, and other low-level details of the C++ binding.
+These wrappers are also sufficient to bind C++ into any target language
+that supports built-in procedures.   In some sense, you might view this
+layer of wrapping as providing a C library interface to C++.
+On top of the low-level procedural (flattened) interface, SWIG generates proxy classes 
+that provide a natural object-oriented (OO) interface to the underlying code.  The proxy classes are typically
+written in the target language itself.  For instance, in Python, a real
+Python class is used to provide a wrapper around the underlying C++ object.
+</p>
+
+<p>
+It is important to emphasize that SWIG takes a deliberately
+conservative and non-intrusive approach to C++ wrapping. SWIG does not
+encapsulate C++ classes inside a special C++ adaptor, it does not rely
+upon templates, nor does it add in additional C++ inheritance when
+generating wrappers.  The last thing that most C++ programs need is
+even more compiler magic.  Therefore, SWIG tries to maintain a very
+strict and clean separation between the implementation of your C++
+application and the resulting wrapper code. You might say that SWIG
+has been written to follow the principle of least surprise--it does
+not play sneaky tricks with the C++ type system, it doesn't mess with
+your class hierarchies, and it doesn't introduce new semantics.
+Although this approach might not provide the most seamless integration
+with C++, it is safe, simple, portable, and debuggable.
+</p>
+
+<p>
+Some of this chapter focuses on the low-level procedural interface to
+C++ that is used as the foundation for all language modules.  Keep in
+mind that the target languages also provide the high-level OO interface via
+proxy classes.  More detailed coverage can be found in the documentation
+for each target language.
+</p>
+
+<H2><a name="SWIGPlus_nn4"></a>6.3 Supported C++ features</H2>
+
+
+<p>
+SWIG currently supports most C++ features including the following:</p>
+
+<ul>
+<li>Classes
+<li>Constructors and destructors
+<li>Virtual functions
+<li>Public inheritance (including multiple inheritance)
+<li>Static functions
+<li>Function and method overloading
+<li>Operator overloading for many standard operators
+<li>References
+<li>Templates (including specialization and member templates)
+<li>Pointers to members
+<li>Namespaces
+<li>Default parameters
+<li>Smart pointers
+</ul>
+
+<p>
+The following C++ features are not currently supported:</p>
+
+<ul>
+<li>Overloaded versions of certain operators (new, delete, etc.)
+<li>Nested classes, see <a href="#SWIGPlus_nested_classes">Nested classes</a> for workarounds.
+</ul>
+
+<p>
+As a rule of thumb, SWIG should not be used on raw C++ source files, use header files only.
+</p>
+
+<p>
+SWIG's C++ support is an ongoing project so some of these limitations may be lifted
+in future releases.  However, we make no promises.  Also, submitting a bug report is a very
+good way to get problems fixed (wink).
+</p>
+
+<H2><a name="SWIGPlus_nn5"></a>6.4 Command line options and compilation</H2>
+
+
+<p>
+When wrapping C++ code, it is critical that SWIG be called with the
+`<tt>-c++</tt>' option. This changes the way a number of critical
+features such as memory management are handled. It
+also enables the recognition of C++ keywords. Without the <tt>-c++</tt>
+flag, SWIG will either issue a warning or a large number of syntax
+errors if it encounters C++ code in an interface file.</p>
+
+<p>
+When compiling and linking the resulting wrapper file,  it is normal
+to use the C++ compiler.  For example:
+</p>
+
+<div class="shell">
+<pre>
+$ swig -c++ -tcl example.i
+$ c++ -c example_wrap.cxx 
+$ c++ example_wrap.o $(OBJS) -o example.so
+</pre>
+</div>
+
+<p>
+Unfortunately, the process varies slightly on each platform.  Make sure
+you refer to the documentation on each target language for further
+details.  The SWIG Wiki also has further details.
+</p>
+
+<b>Compatibility Note:</b> Early versions of SWIG generated just a flattened low-level C style API to C++ classes by default.
+The <tt>-noproxy</tt> commandline option is recognised by many target languages and will generate just this
+interface as in earlier versions.
+
+<H2><a name="SWIGPlus_nn38"></a>6.5 Proxy classes</H2>
+
+
+<p>
+In order to provide a natural mapping from C++ classes to the target language classes, SWIG's target
+languages mostly wrap C++ classes with special proxy classes.  These
+proxy classes are typically implemented in the target language itself.
+For example, if you're building a Python module, each C++ class is
+wrapped by a Python proxy class.  Or if you're building a Java module, each
+C++ class is wrapped by a Java proxy class.  
+</p>
+
+<H3><a name="SWIGPlus_nn39"></a>6.5.1 Construction of proxy classes</H3>
+
+
+<p>
+Proxy classes are always constructed as an extra layer of wrapping that uses low-level
+accessor functions.  To illustrate, suppose you had a
+C++ class like this:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+      Foo();
+     ~Foo();
+      int  bar(int x);
+      int  x;
+};
+</pre>
+</div>
+
+<p>
+Using C++ as pseudocode, a proxy class looks something like this:
+</p>
+
+<div class="code">
+<pre>
+class FooProxy {
+private:
+      Foo    *self;
+public:
+      FooProxy() {
+            self = new_Foo();
+      }
+     ~FooProxy() {
+            delete_Foo(self);
+      }
+      int bar(int x) {
+            return Foo_bar(self,x);
+      }
+      int x_get() {
+            return Foo_x_get(self);
+      }
+      void x_set(int x) {
+            Foo_x_set(self,x);
+      }
+};
+</pre>
+</div>
+
+<p>
+Of course, always keep in mind that the real proxy class is written in the target language.
+For example, in Python, the proxy might look roughly like this:
+</p>
+
+<div class="targetlang">
+<pre>
+class Foo:
+    def __init__(self):
+         self.this = new_Foo()
+    def __del__(self):
+         delete_Foo(self.this)
+    def bar(self,x):
+         return Foo_bar(self.this,x)
+    def __getattr__(self,name):
+         if name == 'x':
+              return Foo_x_get(self.this)
+         ...
+    def __setattr__(self,name,value):
+         if name == 'x':
+              Foo_x_set(self.this,value)
+         ...
+</pre>
+</div>
+
+<p>
+Again, it's important to emphasize that the low-level accessor functions are always used by the
+proxy classes.
+Whenever possible, proxies try to take advantage of language features that are similar to C++.  This
+might include operator overloading,  exception handling, and other features.
+</p>
+
+<H3><a name="SWIGPlus_nn40"></a>6.5.2 Resource management in proxies</H3>
+
+
+<p>
+A major issue with proxies concerns the memory management of wrapped objects.   Consider the following
+C++ code:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+      Foo();
+     ~Foo();
+      int bar(int x);
+      int x;
+};
+
+class Spam {
+public:
+      Foo *value;
+      ...
+};
+</pre>
+</div>
+
+<p>
+Consider some script code that uses these classes:
+</p>
+
+<div class="targetlang">
+<pre>
+f = Foo()               # Creates a new Foo
+s = Spam()              # Creates a new Spam
+s.value = f             # Stores a reference to f inside s
+g = s.value             # Returns stored reference
+g = 4                   # Reassign g to some other value
+del f                   # Destroy f 
+</pre>
+</div>
+
+<p>
+Now, ponder the resulting memory management issues.  When objects are
+created in the script, the objects are wrapped by newly created proxy
+classes.  That is, there is both a new proxy class instance and a new
+instance of the underlying C++ class.  In this example, both
+<tt>f</tt> and <tt>s</tt> are created in this way.  However, the
+statement <tt>s.value</tt> is rather curious---when executed, a
+pointer to <tt>f</tt> is stored inside another object.  This means
+that the scripting proxy class <em>AND</em> another C++ class share a
+reference to the same object.  To make matters even more interesting,
+consider the statement <tt>g = s.value</tt>.  When executed, this
+creates a new proxy class <tt>g</tt> that provides a wrapper around the
+C++ object stored in <tt>s.value</tt>.  In general, there is no way to
+know where this object came from---it could have been created by the
+script, but it could also have been generated internally.  In this
+particular example, the assignment of <tt>g</tt> results in a second
+proxy class for <tt>f</tt>.  In other words, a reference to <tt>f</tt>
+is now shared by two proxy classes <em>and</em> a C++ class.   
+</p>
+
+<p>
+Finally, consider what happens when objects are destroyed.  In the
+statement, <tt>g=4</tt>, the variable <tt>g</tt> is reassigned.  In
+many languages, this makes the old value of <tt>g</tt> available for
+garbage collection.  Therefore, this causes one of the proxy classes
+to be destroyed.  Later on, the statement <tt>del f</tt> destroys the
+other proxy class.  Of course, there is still a reference to the
+original object stored inside another C++ object.  What happens to it?
+Is the object still valid?
+</p>
+
+<p>
+To deal with memory management problems, proxy classes provide an API
+for controlling ownership.  In C++ pseudocode, ownership control might look
+roughly like this:
+</p>
+
+<div class="code">
+<pre>
+class FooProxy {
+public:
+      Foo    *self;
+      int     thisown;
+
+      FooProxy() {
+            self = new_Foo();
+            thisown = 1;       // Newly created object
+      }
+     ~FooProxy() {
+            if (thisown) delete_Foo(self);
+      }
+      ...
+      // Ownership control API
+      void disown() {
+           thisown = 0;
+      }
+      void acquire() {
+           thisown = 1;
+      }
+};
+
+class FooPtrProxy: public FooProxy {
+public:
+      FooPtrProxy(Foo *s) {
+          self = s;
+          thisown = 0;
+      }
+};
+
+class SpamProxy {
+     ...
+     FooProxy *value_get() {
+          return FooPtrProxy(Spam_value_get(self));
+     }
+     void value_set(FooProxy *v) {
+          Spam_value_set(self,v-&gt;self);
+          v-&gt;disown();
+     }
+     ...
+};
+</pre>
+</div>
+
+<p>
+Looking at this code, there are a few central features:
+</p>
+
+<ul>
+<li>Each proxy class keeps an extra flag to indicate ownership.  C++ objects are only destroyed
+if the ownership flag is set.
+</li>
+
+<li>When new objects are created in the target language, the ownership flag is set.
+</li>
+
+<li>When a reference to an internal C++ object is returned, it is wrapped by a proxy
+class, but the proxy class does not have ownership.  
+</li>
+
+<li>In certain cases, ownership is adjusted.  For instance, when a value is assigned to the member of
+a class, ownership is lost.
+</li>
+
+<li>Manual ownership control is provided by special <tt>disown()</tt> and <tt>acquire()</tt> methods.
+</li>
+</ul>
+
+<p>
+Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle
+every possible memory management problem.  However, proxies do provide a mechanism for manual control that
+can be used (if necessary) to address some of the more tricky memory management problems.
+</p>
+
+<H3><a name="SWIGPlus_nn41"></a>6.5.3 Language specific details</H3>
+
+
+<p>
+Language specific details on proxy classes are contained in the chapters describing each target language.  This
+chapter has merely introduced the topic in a very general way.
+</p>
+
+<H2><a name="SWIGPlus_nn6"></a>6.6 Simple C++ wrapping</H2>
+
+
+<p>
+The following code shows a SWIG interface file for a simple C++
+class.</p>
+
+<div class="code"><pre>
+%module list
+%{
+#include "list.h"
+%}
+
+// Very simple C++ example for linked list
+
+class List {
+public:
+  List();
+  ~List();
+  int  search(char *value);
+  void insert(char *);
+  void remove(char *);
+  char *get(int n);
+  int  length;
+static void print(List *l);
+};
+</pre></div>
+
+<p>
+To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style
+accessor functions which are then used by the proxy classes.
+</p>
+
+<H3><a name="SWIGPlus_nn7"></a>6.6.1 Constructors and destructors</H3>
+
+
+<p>
+C++ constructors and destructors are translated into accessor
+functions such as the following :</p>
+
+<div class="code"><pre>
+List * new_List(void) {
+	return new List;
+}
+void delete_List(List *l) {
+	delete l;
+}
+
+</pre></div>
+
+<H3><a name="SWIGPlus_nn8"></a>6.6.2 Default constructors, copy constructors and implicit destructors</H3>
+
+
+<p>
+Following the C++ rules for implicit constructor and destructors, SWIG
+will automatically assume there is one even when they are not
+explicitly declared in the class interface.
+</p>
+
+<p>
+In general then:
+</p>
+
+<ul>
+<li>
+If a C++ class does not declare any explicit constructor, SWIG will
+automatically generate a wrapper for one.
+</li>
+
+<li>
+If a C++ class does not declare an explicit copy constructor, SWIG will
+automatically generate a wrapper for one if the <tt>%copyctor</tt> is used.
+</li>
+
+<li>
+If a C++ class does not declare an explicit destructor, SWIG will
+automatically generate a wrapper for one.
+</li>
+</ul>
+
+<p>
+ And as in C++, a few rules that alters the previous behavior:
+</p>
+
+<ul>
+<li>A default constructor is not created if a class already defines a constructor with arguments.
+</li>
+
+<li>Default constructors are not generated for classes with pure virtual methods or for classes that
+inherit from an abstract class, but don't provide definitions for all of the pure methods.
+</li>
+
+<li>A default constructor is not created unless all base classes support a 
+default constructor. 
+</li>
+
+<li>Default constructors and implicit destructors are not created if a class
+defines them in a <tt>private</tt> or <tt>protected</tt> section.
+</li>
+
+<li>Default constructors and implicit destructors are not created if any base
+class defines a non-public default constructor or destructor.
+</li>
+</ul>
+
+<p>
+SWIG should never generate a default constructor, copy constructor or
+default destructor wrapper for a class in which it is illegal to do so.  In
+some cases, however, it could be necessary (if the complete class
+declaration is not visible from SWIG, and one of the above rules is
+violated) or desired (to reduce the size of the final interface) by
+manually disabling the implicit constructor/destructor generation.
+</p>
+
+<p>
+To manually disable these, the <tt>%nodefaultctor</tt> and <tt>%nodefaultdtor</tt>
+<a href="Customization.html#Customization_feature_flags">feature flag</a> directives
+can be used. Note that these directives only affects the
+implicit generation, and they have no effect if the default/copy
+constructors or destructor are explicitly declared in the class
+interface.
+</p>
+
+<p>
+For example:
+</p>
+
+<div class="code">
+<pre>
+%nodefaultctor Foo;  // Disable the default constructor for class Foo.
+class Foo {          // No default constructor is generated, unless one is declared
+...
+};
+class Bar {          // A default constructor is generated, if possible
+...
+};
+</pre>
+</div>
+
+<p>
+The directive <tt>%nodefaultctor</tt> can also be applied "globally", as in:
+</p>
+
+<div class="code">
+<pre>
+%nodefaultctor; // Disable creation of default constructors
+class Foo {     // No default constructor is generated, unless one is declared
+...
+};
+class Bar {   
+public:
+  Bar();        // The default constructor is generated, since one is declared
+};
+%clearnodefaultctor; // Enable the creation of default constructors again
+</pre>
+</div>
+
+<p>
+The corresponding <tt>%nodefaultdtor</tt> directive can be used
+to disable the generation of the default or implicit destructor, if
+needed. Be aware, however, that this could lead to memory leaks in the
+target language. Hence, it is recommended to use this directive only
+in well known cases. For example:
+</p>
+
+<div class="code">
+<pre>
+%nodefaultdtor Foo;   // Disable the implicit/default destructor for class Foo.
+class Foo {           // No destructor is generated, unless one is declared
+...
+};
+</pre>
+</div>
+
+<p>
+<b>Compatibility Note:</b> The generation of default
+constructors/implicit destructors was made the default behavior in SWIG
+1.3.7. This may break certain older modules, but the old behavior can
+be easily restored using <tt>%nodefault</tt> or the
+<tt>-nodefault</tt> command line option.  Furthermore, in order for
+SWIG to properly generate (or not generate) default constructors, it
+must be able to gather information from both the <tt>private</tt> and
+<tt>protected</tt> sections (specifically, it needs to know if a private or
+protected constructor/destructor is defined).   In older versions of
+SWIG, it was fairly common to simply remove or comment out
+the private and protected sections of a class due to parser limitations.
+However, this removal may now cause SWIG to erroneously generate constructors
+for classes that define a constructor in those sections.  Consider restoring
+those sections in the interface or using <tt>%nodefault</tt> to fix the problem.
+</p>
+
+<p>
+<b>Note:</b> The <tt>%nodefault</tt>
+directive/<tt>-nodefault</tt> options described above, which disable both the default
+constructor and the implicit destructors, could lead to memory
+leaks, and so it is strongly recommended to not use them.
+</p>
+
+
+<H3><a name="SWIGPlus_nn9"></a>6.6.3 When constructor wrappers aren't created</H3>
+
+
+<p>
+If a class defines a constructor, SWIG normally tries to generate a wrapper for it.  However, SWIG will 
+not generate a constructor wrapper if it thinks that it will result in illegal wrapper code.  There are really
+two cases where this might show up.
+</p>
+
+<p>
+First, SWIG won't generate wrappers for protected or private constructors.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+protected:
+     Foo();         // Not wrapped.
+public:
+      ...
+};
+</pre>
+</div>
+
+<p>
+Next, SWIG won't generate wrappers for a class if it appears to be abstract--that is, it has undefined
+pure virtual methods.  Here are some examples:
+</p>
+
+<div class="code">
+<pre>
+class Bar {
+public:
+     Bar();               // Not wrapped.  Bar is abstract.
+     virtual void spam(void) = 0; 
+};
+
+class Grok : public Bar {
+public:
+      Grok();            // Not wrapped. No implementation of abstract spam().
+};
+</pre>
+</div>
+
+<p>
+Some users are surprised (or confused) to find missing constructor wrappers in their interfaces.  In almost 
+all cases, this is caused when classes are determined to be abstract.   To see if this is the case, run SWIG with
+all of its warnings turned on:
+</p>
+
+<div class="shell">
+<pre>
+% swig -Wall -python module.i
+</pre>
+</div>
+
+<p>
+In this mode, SWIG will issue a warning for all abstract classes.   It is possible to force a class to be
+non-abstract using this:
+</p>
+
+<div class="code">
+<pre>
+%feature("notabstract") Foo;
+
+class Foo : public Bar {
+public:
+     Foo();    // Generated no matter what---not abstract. 
+     ...
+};
+</pre>
+</div>
+
+<p>
+More information about <tt>%feature</tt> can be found in the <a href="Customization.html#Customization">Customization features</a> chapter.
+</p>
+
+<H3><a name="SWIGPlus_nn10"></a>6.6.4 Copy constructors</H3>
+
+
+<p>
+If a class defines more than one constructor, its behavior depends on the capabilities of the
+target language.  If overloading is supported, the copy constructor is accessible using
+the normal constructor function.  For example, if you have this:
+</p>
+
+<div class="code">
+<pre>
+class List {
+public:
+    List();    
+    List(const List &amp;);      // Copy constructor
+    ...
+};
+</pre>
+</div>
+
+<p>
+then the copy constructor can be used as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+x = List()               # Create a list
+y = List(x)              # Copy list x
+</pre>
+</div>
+
+<p>
+If the target language does not support overloading, then the copy constructor is available
+through a special function like this:
+</p>
+
+<div class="code">
+<pre>
+List *copy_List(List *f) {
+    return new List(*f);
+}
+</pre>
+</div>
+
+<p>
+<b>Note:</b> For a class <tt>X</tt>, SWIG only treats a constructor as
+a copy constructor if it can be applied to an object of type
+<tt>X</tt> or <tt>X *</tt>.  If more than one copy constructor is
+defined, only the first definition that appears is used as the copy
+constructor--other definitions will result in a name-clash.
+Constructors such as <tt>X(const X &amp;)</tt>, <tt>X(X &amp;)</tt>, and
+<tt>X(X *)</tt> are handled as copy constructors in SWIG.
+</p>
+
+<p>
+<b>Note:</b> SWIG does <em>not</em> generate a copy constructor
+wrapper unless one is explicitly declared in the class.  This differs
+from the treatment of default constructors and destructors.
+However, copy constructor wrappers can be generated if using the <tt>copyctor</tt>
+<a href="Customization.html#Customization_feature_flags">feature flag</a>. For example:
+</p>
+
+<div class="code">
+<pre>
+%copyctor List;
+
+class List {
+public:
+    List();    
+};
+</pre>
+</div>
+
+<p>
+Will generate a copy constructor wrapper for <tt>List</tt>.
+</p>
+
+<p>
+<b>Compatibility note:</b> Special support for copy constructors was
+not added until SWIG-1.3.12.  In previous versions, copy constructors
+could be wrapped, but they had to be renamed.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+  %name(CopyFoo) Foo(const Foo &amp;);
+    ...
+};
+</pre>
+</div>
+
+<p>
+For backwards compatibility, SWIG does not perform any special
+copy-constructor handling if the constructor has been manually
+renamed.  For instance, in the above example, the name of the
+constructor is set to <tt>new_CopyFoo()</tt>.   This is the same as in 
+older versions.
+</p>
+
+<H3><a name="SWIGPlus_nn11"></a>6.6.5 Member functions</H3>
+
+
+<p>
+All member functions are roughly translated into accessor functions like this :</p>
+
+<div class="code"><pre>
+int List_search(List *obj, char *value) {
+	return obj-&gt;search(value);
+}
+
+</pre></div>
+
+<p>
+This translation is the same even if the member function has been
+declared as <tt>virtual</tt>.
+</p>
+
+<p>
+It should be noted that SWIG does not <em>actually</em> create a C accessor
+function in the code it generates.  Instead, member access such as
+<tt>obj-&gt;search(value)</tt> is directly inlined into the generated
+wrapper functions.  However, the name and calling convention of the
+low-level procedural wrappers match the accessor function prototype described above.
+</p>
+
+<H3><a name="SWIGPlus_nn12"></a>6.6.6 Static members</H3>
+
+
+<p>
+Static member functions are called directly without making any special
+transformations. For example, the static member function
+<tt>print(List *l)</tt> directly invokes <tt>List::print(List *l)</tt>
+in the generated wrapper code.
+</p>
+
+<H3><a name="SWIGPlus_member_data"></a>6.6.7 Member data</H3>
+
+
+<p>
+Member data is handled in exactly the same manner as for C
+structures. A pair of accessor functions are effectively created. For example
+:</p>
+
+<div class="code"><pre>
+int List_length_get(List *obj) {
+	return obj-&gt;length;
+}
+int List_length_set(List *obj, int value) {
+	obj-&gt;length = value;
+	return value;
+}
+
+</pre></div>
+
+<p>
+A read-only member can be created using the <tt>%immutable</tt> and <tt>%mutable</tt> 
+<a href="Customization.html#Customization_feature_flags">feature flag</a> directive.
+For example, we probably wouldn't want
+the user to change the length of a list so we could do the following
+to make the value available, but read-only.</p>
+
+<div class="code"><pre>
+class List {
+public:
+...
+%immutable;
+	int length;
+%mutable;
+...
+};
+</pre></div>
+
+<p>
+Alternatively, you can specify an immutable member in advance like this:
+</p>
+
+<div class="code">
+<pre>
+%immutable List::length;
+...
+class List {
+   ...
+   int length;         // Immutable by above directive
+   ...
+};
+</pre>
+</div>
+
+<p>
+Similarly, all data attributes declared as <tt>const</tt> are wrapped as read-only members.
+</p>
+
+<p>
+There are some subtle issues when wrapping data members that are
+themselves classes.  For instance, if you had another class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    List items;
+    ...
+</pre>
+</div>
+
+<p>
+then the low-level accessor to the <tt>items</tt> member actually uses pointers. For example:
+</p>
+
+<div class="code">
+<pre>
+List *Foo_items_get(Foo *self) {
+    return &amp;self-&gt;items;
+}
+void Foo_items_set(Foo *self, List *value) {
+    self-&gt;items = *value;
+}
+</pre>
+</div>
+
+<p>
+More information about this can be found in the SWIG Basics chapter,
+<a href="SWIG.html#SWIG_structure_data_members">Structure data members</a> section. 
+</p>
+
+<p>
+The wrapper code to generate the accessors for classes comes from the pointer typemaps. 
+This can be somewhat unnatural for some types.
+For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language,
+rather than a pointer to this class.
+The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps.
+It is the <tt>%naturalvar</tt> directive and is used as follows:
+</p>
+
+<div class="code">
+<pre>
+// All List variables will use const List&amp; typemaps
+%naturalvar List;
+
+// Only Foo::myList will use const List&amp; typemaps
+%naturalvar Foo::myList;
+struct Foo {
+  List myList;
+};
+
+// All variables will use const reference typemaps
+%naturalvar;
+</pre>
+</div>
+
+<p>
+The observant reader will notice that <tt>%naturalvar</tt> works like any other
+<a href="Customization.html#Customization_feature_flags">feature flag</a> directive,
+except it can also be attached to class types.
+The first of the example usages above show <tt>%naturalvar</tt> attaching to the <tt>List</tt> class.
+Effectively this feature changes the way accessors are generated to the following:
+</p>
+
+<div class="code">
+<pre>
+const List &amp;Foo_items_get(Foo *self) {
+    return self-&gt;items;
+}
+void Foo_items_set(Foo *self, const List &amp;value) {
+    self-&gt;items = value;
+}
+</pre>
+</div>
+
+<p>
+In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps.
+A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates
+to a NULL pointer and thereby preventing any potential NULL pointer dereferences.
+The <tt>%naturalvar</tt> feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.
+</p>
+
+<p>
+Other alternatives for turning this feature on globally are to use the <tt>swig -naturalvar</tt> commandline option 
+or the module mode option, <tt>%module(naturalvar=1)</tt>
+</p>
+
+<p>
+<b>Compatibility note:</b> The <tt>%naturalvar</tt> feature was introduced in SWIG-1.3.28, prior to which it was necessary to manually apply the const reference
+typemaps, eg <tt>%apply const std::string &amp; { std::string * }</tt>, but this example would also apply the typemaps to methods taking a <tt>std::string</tt> pointer.
+</p>
+
+<p>
+<b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
+<tt>%readonly</tt> and <tt>%readwrite</tt>.   Although these directives still work, they
+generate a warning message.   Simply change the directives to <tt>%immutable;</tt> and
+<tt>%mutable;</tt> to silence the warning.  Don't forget the extra semicolon!
+</p>
+
+<p>
+<b>Compatibility note:</b> Prior to SWIG-1.3.12, all members of unknown type were
+wrapped into accessor functions using pointers.  For example, if you had a structure
+like this
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   size_t  len;
+};
+</pre>
+</div>
+
+<p>
+and nothing was known about <tt>size_t</tt>, then accessors would be
+written to work with <tt>size_t *</tt>.  Starting in SWIG-1.3.12, this
+behavior has been modified.  Specifically, pointers will <em>only</em>
+be used if SWIG knows that a datatype corresponds to a structure or
+class.  Therefore, the above code would be wrapped into accessors
+involving <tt>size_t</tt>.  This change is subtle, but it smooths over
+a few problems related to structure wrapping and some of SWIG's
+customization features.
+</p>
+
+<H2><a name="SWIGPlus_default_args"></a>6.7 Default arguments</H2>
+
+
+<p>
+SWIG will wrap all types of functions that have default arguments. For example member functions:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    void bar(int x, int y = 3, int z = 4);
+};
+</pre>
+</div>
+
+<p>
+SWIG handles default arguments by generating an extra overloaded method for each defaulted argument.
+SWIG is effectively handling methods with default arguments as if it was wrapping the equivalent overloaded methods.
+Thus for the example above, it is as if we had instead given the following to SWIG:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    void bar(int x, int y, int z);
+    void bar(int x, int y);
+    void bar(int x);
+};
+</pre>
+</div>
+
+<p>
+The wrappers produced are exactly the same as if the above code was instead fed into SWIG.
+Details of this are covered later in the <a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a> section.
+This approach allows SWIG to wrap all possible default arguments, but can be verbose.
+For example if a method has ten default arguments, then eleven wrapper methods are generated.
+</p>
+
+<p>
+Please see the <a href="Customization.html#Customization_features_default_args">Features and default arguments</a>
+section for more information on using <tt>%feature</tt> with functions with default arguments.
+The <a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section 
+also deals with using <tt>%rename</tt> and <tt>%ignore</tt> on methods with default arguments.
+If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a <tt>typecheck</tt> typemap.
+See the <a href="Typemaps.html#Typemaps_overloading">Typemaps and overloading</a> section for details or otherwise
+use the <tt>compactdefaultargs</tt> feature flag as mentioned below.
+</p>
+
+<p>
+<b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently.
+Instead a single wrapper method was generated and the default values were copied into the C++ wrappers
+so that the method being wrapped was then called with all the arguments specified.
+If the size of the wrappers are a concern then this approach to wrapping methods with default arguments
+can be re-activated by using the <tt>compactdefaultargs</tt> 
+<a href="Customization.html#Customization_feature_flags">feature flag</a>.
+</p>
+
+<div class="code">
+<pre>
+%feature("compactdefaultargs") Foo::bar;
+class Foo {
+public:
+    void bar(int x, int y = 3, int z = 4);
+};
+</pre>
+</div>
+
+
+<p>
+This is great for reducing the size of the wrappers, but the caveat is it does not work for the statically typed languages,
+such as C# and Java,
+which don't have optional arguments in the language, 
+Another restriction of this feature is that it cannot handle default arguments that are not public.
+The following example illustrates this:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+private:
+   static const int spam;
+public:
+   void bar(int x, int y = spam);   // Won't work with %feature("compactdefaultargs") -
+                                    // private default value
+};
+</pre>
+</div>
+
+<p>
+This produces uncompileable wrapper code because default values in C++ are
+evaluated in the same scope as the member function whereas SWIG
+evaluates them in the scope of a wrapper function (meaning that the
+values have to be public). 
+</p>
+
+<p>
+This feature is automatically turned on when wrapping <a href="SWIG.html#SWIG_default_args">C code with default arguments</a>
+and whenever keyword arguments (kwargs) are specified for either C or C++ code.
+Keyword arguments are a language feature of some scripting languages, for example Ruby and Python.
+SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used.
+</p>
+
+<H2><a name="SWIGPlus_nn15"></a>6.8 Protection</H2>
+
+
+<p>
+ SWIG wraps class members that are public following the C++
+ conventions, i.e., by explicit public declaration or by the use of
+ the <tt> using</tt> directive. In general, anything specified in a
+ private or protected section will be ignored, although the internal
+ code generator sometimes looks at the contents of the private and
+ protected sections so that it can properly generate code for default
+ constructors and destructors. Directors could also modify the way
+ non-public virtual protected members are treated.
+</p>
+
+<p>
+By default, members of a class definition are assumed to be private
+until you explicitly give a `<tt>public:</tt>' declaration (This is
+the same convention used by C++).
+</p>
+
+<H2><a name="SWIGPlus_nn16"></a>6.9 Enums and constants</H2>
+
+
+<p>
+Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter.
+However, many languages map enums and constants in a class definition 
+into constants with the classname as a prefix. For example :</p>
+
+<div class="code"><pre>
+class Swig {
+public:
+	enum {ALE, LAGER, PORTER, STOUT};
+};
+
+</pre></div>
+<p>
+Generates the following set of constants in the target scripting language :</p>
+
+<div class="targetlang"><pre>
+Swig_ALE = Swig::ALE
+Swig_LAGER = Swig::LAGER
+Swig_PORTER = Swig::PORTER
+Swig_STOUT = Swig::STOUT
+
+</pre></div>
+
+<p>
+Members declared as <tt>const</tt> are wrapped as read-only members and do not create constants.
+</p>
+
+<H2><a name="SWIGPlus_nn17"></a>6.10 Friends</H2>
+
+
+<p>
+Friend declarations are recognised by SWIG. For example, if
+you have this code:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     ...
+     friend void blah(Foo *f);
+     ...
+};
+</pre>
+</div>
+
+<p>
+then the <tt>friend</tt> declaration does result in a wrapper code
+equivalent to one generated for the following declaration
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    ...
+};
+
+void blah(Foo *f);    
+</pre>
+</div>
+
+<p>
+A friend declaration, as in C++, is understood to be in the same scope
+where the class is declared, hence, you can have
+</p>
+
+<div class="code">
+<pre>
+
+%ignore bar::blah(Foo *f);
+
+namespace bar {
+
+  class Foo {
+  public:
+     ...
+     friend void blah(Foo *f);
+     ...
+  };
+}
+</pre>
+</div>
+
+<p>
+and a wrapper for the method 'blah' will not be generated.
+</p>
+
+<H2><a name="SWIGPlus_nn18"></a>6.11 References and pointers</H2>
+
+
+<p>
+C++ references are supported, but SWIG transforms them back into pointers. For example,
+a declaration like this :</p>
+
+<div class="code"><pre>
+class Foo {
+public:
+	double bar(double &amp;a);
+}
+</pre></div>
+
+<p>
+has a low-level accessor
+</p>
+
+<div class="code"><pre>
+double Foo_bar(Foo *obj, double *a) {
+	obj-&gt;bar(*a);
+}
+</pre></div>
+
+<p>
+As a special case, most language modules pass <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>,
+<tt>float</tt>, etc.) by value instead of pointers.  For example, if you have a function like this,
+</p>
+
+<div class="code">
+<pre>
+void foo(const int &amp;x);
+</pre>
+</div>
+
+<p>
+it is called from a script as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+foo(3)              # Notice pass by value
+</pre>
+</div>
+
+<p>
+Functions that return a reference are remapped to return a pointer instead.
+For example:
+</p>
+
+<div class="code"><pre>
+class Bar {
+public:
+     Foo &amp;spam();
+};
+</pre>
+</div>
+
+<p>
+Generates an accessor like this:
+</p>
+
+<div class="code">
+<pre>
+Foo *Bar_spam(Bar *obj) {
+   Foo &amp;result = obj-&gt;spam();
+   return &amp;result;
+}
+</pre>
+</div>
+
+<p>
+However, functions that return <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, etc.) normally
+return the result as a value rather than a pointer.  For example, a function like this,
+</p>
+
+<div class="code">
+<pre>
+const int &amp;bar();
+</pre>
+</div>
+
+<p>
+will return integers such as 37 or 42 in the target scripting language rather than a pointer to an integer.
+</p>
+
+<P>
+Don't return references to objects allocated as local variables on the
+stack.  SWIG doesn't make a copy of the objects so this will probably
+cause your program to crash.
+
+
+
+<p>
+<b>Note:</b> The special treatment for references to primitive datatypes is necessary to provide
+more seamless integration with more advanced C++ wrapping applications---especially related to 
+templates and the STL.  This was first added in SWIG-1.3.12.
+</p>
+
+
+<H2><a name="SWIGPlus_nn19"></a>6.12 Pass and return by value</H2>
+
+
+<p>
+Occasionally, a C++ program will pass and return class objects by value.  For example, a function
+like this might appear:
+</p>
+
+<div class="code">
+<pre>
+Vector cross_product(Vector a, Vector b);
+</pre>
+</div>
+
+<p>
+If no information is supplied about <tt>Vector</tt>, SWIG creates a wrapper function similar to the
+following:
+</p>
+
+<div class="code">
+<pre>
+Vector *wrap_cross_product(Vector *a, Vector *b) {
+   Vector x = *a;
+   Vector y = *b;
+   Vector r = cross_product(x,y);
+   return new Vector(r);
+}</pre>
+</div>
+
+<p>
+In order for the wrapper code to compile, <tt>Vector</tt> must define a copy constructor and a 
+default constructor.
+</p>
+
+<p>
+If <tt>Vector</tt> is defined as a class in the interface, but it does not
+support a default constructor, SWIG changes the wrapper code by encapsulating
+the arguments inside a special C++ template wrapper class, through a process
+called the "Fulton Transform".  This produces a wrapper that looks like this:
+</p>
+
+<div class="code">
+<pre>
+Vector cross_product(Vector *a, Vector *b) {
+   SwigValueWrapper&lt;Vector&gt; x = *a;
+   SwigValueWrapper&lt;Vector&gt; y = *b;
+   SwigValueWrapper&lt;Vector&gt; r = cross_product(x,y);
+   return new Vector(r);
+}
+</pre>
+</div>
+
+<p>
+This transformation is a little sneaky, but it provides support for
+pass-by-value even when a class does not provide a default constructor
+and it makes it possible to properly support a number of SWIG's
+customization options.  The definition of <tt>SwigValueWrapper</tt>
+can be found by reading the SWIG wrapper code. This class is really nothing more than a thin
+wrapper around a pointer. 
+</p>
+
+<p>
+Although SWIG usually detects the classes to which the Fulton Transform should
+be applied, in some situations it's necessary to override it.  That's done with
+<tt>%feature("valuewrapper")</tt> to ensure it is used and <tt>%feature("novaluewrapper")</tt>
+to ensure it is not used:
+</p>
+
+<div class="code"><pre>
+%feature("novaluewrapper") A;    
+class A;
+
+%feature("valuewrapper") B;
+struct B { 
+    B();
+    // ....
+};   
+</pre></div>
+
+<p>
+It is well worth considering turning this feature on for classes that do have a default constructor. 
+It will remove a redundant constructor call at the point of the variable declaration in the wrapper, 
+so will generate notably better performance for large objects or for classes with expensive construction.
+Alternatively consider returning a reference or a pointer.
+</p>
+
+<p>
+<b>Note:</b> this transformation has no effect on typemaps
+or any other part of SWIG---it should be transparent except that you
+may see this code when reading the SWIG output file.
+</p>
+
+<p>
+<b>
+Note: </b>This template transformation is new in SWIG-1.3.11 and may be refined in
+future SWIG releases.  In practice, it is only absolutely necessary to do this for
+classes that don't define a default constructor.  
+</p>
+
+<p>
+<b>Note:</b> The use of this template only occurs when objects are passed or returned by value.
+It is not used for C++ pointers or references.
+</p>
+
+<H2><a name="SWIGPlus_nn20"></a>6.13 Inheritance</H2>
+
+
+<p>
+SWIG supports C++ inheritance of classes and allows both single and
+multiple inheritance, as limited or allowed by the target
+language. The SWIG type-checker knows about the relationship between
+base and derived classes and allows pointers to any object of a
+derived class to be used in functions of a base class. The
+type-checker properly casts pointer values and is safe to use with
+multiple inheritance.
+</p>
+
+<p> SWIG treats private or protected inheritance as close to the C++
+spirit, and target language capabilities, as possible. In most
+cases, this means that SWIG will parse the non-public inheritance
+declarations, but that will have no effect in the generated code,
+besides the implicit policies derived for constructor and
+destructors. 
+</p>
+
+
+<p>
+The following example shows how SWIG handles inheritance. For clarity,
+the full C++ code has been omitted.</p>
+
+<div class="code"><pre>
+// shapes.i
+%module shapes
+%{
+#include "shapes.h"
+%}
+
+class Shape {
+public:
+        double x,y;
+	virtual double area() = 0;
+	virtual double perimeter() = 0;
+	void    set_location(double x, double y);
+};
+class Circle : public Shape {
+public:
+	Circle(double radius);
+	~Circle();
+	double area();
+	double perimeter();
+};
+class Square : public Shape {
+public:
+	Square(double size);
+	~Square();
+	double area();
+	double perimeter();
+}
+</pre></div>
+
+<p>
+When wrapped into Python, we can perform the following operations (shown using the low level Python accessors):
+</p>
+
+<div class="targetlang"><pre>
+$ python
+&gt;&gt;&gt; import shapes
+&gt;&gt;&gt; circle = shapes.new_Circle(7)
+&gt;&gt;&gt; square = shapes.new_Square(10)
+&gt;&gt;&gt; print shapes.Circle_area(circle)
+153.93804004599999757
+&gt;&gt;&gt; print shapes.Shape_area(circle)
+153.93804004599999757
+&gt;&gt;&gt; print shapes.Shape_area(square)
+100.00000000000000000
+&gt;&gt;&gt; shapes.Shape_set_location(square,2,-3)
+&gt;&gt;&gt; print shapes.Shape_perimeter(square)
+40.00000000000000000
+&gt;&gt;&gt;
+</pre></div>
+
+<p>
+In this example,  Circle and Square objects have been created.  Member
+functions can be invoked on each object by making calls to
+<tt>Circle_area</tt>, <tt>Square_area</tt>, and so on. However, the same
+results can be accomplished by simply using the <tt>Shape_area</tt>
+function on either object.
+</p>
+
+<p>
+One important point concerning inheritance is that the low-level
+accessor functions are only generated for classes in which they are
+actually declared.  For instance, in the above example, the method
+<tt>set_location()</tt> is only accessible as
+<tt>Shape_set_location()</tt> and not as
+<tt>Circle_set_location()</tt> or <tt>Square_set_location()</tt>.  Of
+course, the <tt>Shape_set_location()</tt> function will accept any
+kind of object derived from Shape.  Similarly, accessor functions for
+the attributes <tt>x</tt> and <tt>y</tt> are generated as
+<tt>Shape_x_get()</tt>, <tt>Shape_x_set()</tt>,
+<tt>Shape_y_get()</tt>, and <tt>Shape_y_set()</tt>.  Functions such as
+<tt>Circle_x_get()</tt> are not available--instead you should use
+<tt>Shape_x_get()</tt>.
+</p>
+
+<p>
+Note that there is a one to one correlation between the low-level accessor functions and
+the proxy methods and therefore there is also a one to one correlation between
+the C++ class methods and the generated proxy class methods.
+</p>
+
+<p>
+<b>Note:</b>  For the best results, SWIG requires all
+base classes to be defined in an interface.  Otherwise, you may get a
+warning message like this:
+</p>
+
+<div class="shell">
+<pre>
+example.i:18: Warning(401): Nothing known about base class 'Foo'. Ignored.
+</pre>
+</div>
+
+<p>
+If any base class is undefined, SWIG still generates correct type
+relationships.  For instance, a function accepting a <tt>Foo *</tt>
+will accept any object derived from <tt>Foo</tt> regardless of whether
+or not SWIG actually wrapped the <tt>Foo</tt> class.  If you really
+don't want to generate wrappers for the base class, but you want to
+silence the warning, you might consider using the <tt>%import</tt>
+directive to include the file that defines <tt>Foo</tt>.
+<tt>%import</tt> simply gathers type information, but doesn't generate
+wrappers.  Alternatively, you could just define <tt>Foo</tt> as an empty class
+in the SWIG interface or use
+<a href="Warnings.html#Warnings_suppression">warning suppression</a>.
+</p>
+
+<p>
+<b>Note:</b> <tt>typedef</tt>-names <em>can</em> be used as base classes.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+...
+};
+
+typedef Foo FooObj;
+class Bar : public FooObj {     // Ok.  Base class is Foo
+...
+};
+</pre>
+</div>
+
+<p>
+Similarly, <tt>typedef</tt> allows unnamed structures to be used as base classes. For example:
+</p>
+
+<div class="code">
+<pre>
+typedef struct {
+   ...
+} Foo;
+
+class Bar : public Foo {    // Ok. 
+...
+};
+</pre>
+</div>
+
+<p>
+<b>Compatibility Note:</b> Starting in version 1.3.7, SWIG only
+generates low-level accessor wrappers for the declarations that are
+actually defined in each class.  This differs from SWIG1.1 which used
+to inherit all of the declarations defined in base classes and
+regenerate specialized accessor functions such as
+<tt>Circle_x_get()</tt>, <tt>Square_x_get()</tt>,
+<tt>Circle_set_location()</tt>, and <tt>Square_set_location()</tt>.
+This behavior resulted in huge amounts of replicated code for large
+class hierarchies and made it awkward to build applications spread
+across multiple modules (since accessor functions are duplicated in
+every single module).  It is also unnecessary to have such wrappers
+when advanced features like proxy classes are used.  
+
+<b>Note:</b> Further optimizations are enabled when using the
+<tt>-fvirtual</tt> option, which avoids the regenerating of wrapper
+functions for virtual members that are already defined in a base
+class.
+</p>
+
+<H2><a name="SWIGPlus_nn21"></a>6.14 A brief discussion of multiple inheritance, pointers,  and type checking</H2>
+
+
+<p>
+When a target scripting language refers to a C++ object, it normally
+uses a tagged pointer object that contains both the value of the
+pointer and a type string.  For example, in Tcl, a C++ pointer might
+be encoded as a string like this:
+</p>
+
+<div class="diagram">
+<pre>
+_808fea88_p_Circle
+</pre>
+</div>
+
+<p>
+A somewhat common question is whether or not the type-tag could be safely
+removed from the pointer.  For instance, to get better performance, could you
+strip all type tags and just use simple integers instead?
+</p>
+
+<p>
+In general, the answer to this question is no.  In the wrappers, all
+pointers are converted into a common data representation in the target
+language.  Typically this is the equivalent of casting a pointer to <tt>void *</tt>.
+This means that any C++ type information associated with the pointer is
+lost in the conversion.
+</p>
+
+<p>
+The problem with losing type information is that it is needed to
+properly support many advanced C++ features--especially multiple
+inheritance.  For example, suppose you had code like this:
+</p>
+
+<div class="code">
+<pre>
+class A {
+public:
+   int x;
+};
+
+class B {
+public:
+   int y;
+};
+
+class C : public A, public B {
+};
+
+int A_function(A *a) {
+   return a-&gt;x;
+}
+
+int B_function(B *b) {
+   return b-&gt;y;
+}
+</pre>
+</div>
+
+<p>
+Now, consider the following code that uses <tt>void *</tt>.
+</p>
+
+<div class="code">
+<pre>
+C *c = new C();
+void *p = (void *) c;
+...
+int x = A_function((A *) p);
+int y = B_function((B *) p);
+</pre>
+</div>
+
+<p>
+In this code, both <tt>A_function()</tt> and <tt>B_function()</tt> may
+legally accept an object of type <tt>C *</tt> (via inheritance).
+However, one of the functions will always return the wrong result when
+used as shown. The reason for this is that even though <tt>p</tt>
+points to an object of type <tt>C</tt>, the casting operation doesn't
+work like you would expect.  Internally, this has to do with the data
+representation of <tt>C</tt>. With multiple inheritance, the data from
+each base class is stacked together.  For example:
+</p>
+
+<div class="diagram">
+<pre>
+             ------------    &lt;--- (C *),  (A *)
+            |     A      |
+            |------------|   &lt;--- (B *)
+            |     B      |
+             ------------   
+</pre>
+</div>
+
+<p>
+Because of this stacking, a pointer of type <tt>C *</tt> may change
+value when it is converted to a <tt>A *</tt> or <tt>B *</tt>.
+However, this adjustment does <em>not</em> occur if you are converting from a
+<tt>void *</tt>.
+</p>
+
+<p>
+The use of type tags marks all pointers with the real type of the
+underlying object.  This extra information is then used by SWIG
+generated wrappers to correctly cast pointer values under inheritance
+(avoiding the above problem). 
+</p>
+
+<p>
+Some of the language modules are able to solve the problem by storing multiple instances of the pointer, for example, <tt>A *</tt>,
+in the A proxy class as well as <tt>C *</tt> in the C proxy class. The correct cast can then be made by choosing the correct <tt>void *</tt>
+pointer to use and is guaranteed to work as the cast to a void pointer and back to the same type does not lose any type information:
+</p>
+
+<div class="code">
+<pre>
+C *c = new C();
+void *p = (void *) c;
+void *pA = (void *) c;
+void *pB = (void *) c;
+...
+int x = A_function((A *) pA);
+int y = B_function((B *) pB);
+</pre>
+</div>
+
+<p>
+In practice, the pointer is held as an integral number in the target language proxy class.
+</p>
+
+<H2><a name="SWIGPlus_overloaded_methods"></a>6.15 Wrapping Overloaded Functions and Methods</H2>
+
+
+<p>
+In many language modules, SWIG provides partial support for overloaded functions, methods, and
+constructors.  For example, if you supply SWIG with overloaded functions like this:
+</p>
+
+<div class="code">
+<pre>
+void foo(int x) {
+   printf("x is %d\n", x);
+}
+void foo(char *x) {
+   printf("x is '%s'\n", x);
+}
+</pre>
+</div>
+
+<p>
+The function is used in a completely natural way.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo(3)
+x is 3
+&gt;&gt;&gt; foo("hello")
+x is 'hello'
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Overloading works in a similar manner for methods and constructors.  For example if you have
+this code,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     Foo();
+     Foo(const Foo &amp;);   // Copy constructor
+     void bar(int x);
+     void bar(char *s, int y);
+};
+</pre>
+</div>
+
+<p>
+it might be used like this
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = Foo()          # Create a Foo
+&gt;&gt;&gt; f.bar(3)
+&gt;&gt;&gt; g = Foo(f)         # Copy Foo
+&gt;&gt;&gt; f.bar("hello",2)
+</pre>
+</div>
+
+<H3><a name="SWIGPlus_nn24"></a>6.15.1 Dispatch function generation</H3>
+
+
+<p>
+The implementation of overloaded functions and methods is somewhat
+complicated due to the dynamic nature of scripting languages.  Unlike
+C++, which binds overloaded methods at compile time, SWIG must
+determine the proper function as a runtime check for scripting language targets. This check is
+further complicated by the typeless nature of certain scripting languages. For instance,
+in Tcl, all types are simply strings.  Therefore, if you have two overloaded functions
+like this,
+</p>
+
+<div class="code">
+<pre>
+void foo(char *x);
+void foo(int x);
+</pre>
+</div>
+
+<p>
+the order in which the arguments are checked plays a rather critical role.
+</p>
+
+<p>
+For statically typed languages, SWIG uses the language's method overloading mechanism.
+To implement overloading for the scripting languages, SWIG generates a dispatch function that checks the
+number of passed arguments and their types.  To create this function, SWIG
+first examines all of the overloaded methods and ranks them according
+to the following rules:
+</p>
+
+<ol>
+<li><b>Number of required arguments.</b> Methods are sorted by increasing number of
+required arguments.
+</li>
+<li><p><b>Argument type precedence.</b>  All C++ datatypes are assigned a numeric type precedence value
+(which is determined by the language module).</p>
+
+<div class="diagram">
+<pre>
+Type              Precedence
+----------------  ----------
+TYPE *            0     (High)
+void *            20
+Integers          40
+Floating point    60
+char              80
+Strings           100   (Low)
+</pre>
+</div>
+
+<p>
+Using these precedence values, overloaded methods with the same number of required arguments are sorted in increased
+order of precedence values.
+</p>
+</li>
+</ol>
+
+<p>
+This may sound very confusing, but an example will help.  Consider the following collection of
+overloaded methods:
+</p>
+
+<div class="code">
+<pre>
+void foo(double);
+void foo(int);
+void foo(Bar *);
+void foo();
+void foo(int x, int y, int z, int w);
+void foo(int x, int y, int z = 3);
+void foo(double x, double y);
+void foo(double x, Bar *z);
+</pre>
+</div>
+
+<p>
+The first rule simply ranks the functions by required argument count.
+This would produce the following list:
+</p>
+
+<div class="diagram">
+<pre>
+rank
+-----
+[0]   foo()
+[1]   foo(double);
+[2]   foo(int);
+[3]   foo(Bar *);
+[4]   foo(int x, int y, int z = 3);
+[5]   foo(double x, double y)
+[6]   foo(double x, Bar *z)
+[7]   foo(int x, int y, int z, int w);
+</pre>
+</div>
+
+<p>
+The second rule, simply refines the ranking by looking at argument type precedence values.
+</p>
+
+<div class="diagram">
+<pre>
+rank
+-----
+[0]   foo()
+[1]   foo(Bar *);
+[2]   foo(int);
+[3]   foo(double);
+[4]   foo(int x, int y, int z = 3);
+[5]   foo(double x, Bar *z)
+[6]   foo(double x, double y)
+[7]   foo(int x, int y, int z, int w);
+</pre>
+</div>
+
+<p>
+Finally, to generate the dispatch function, the arguments passed to an overloaded method are simply
+checked in the same order as they appear in this ranking.
+</p>
+
+<p>
+If you're still confused, don't worry about it---SWIG is probably doing the right thing.
+</p>
+
+<H3><a name="SWIGPlus_nn25"></a>6.15.2 Ambiguity in Overloading</H3>
+
+
+<p>
+Regrettably, SWIG is not able to support every possible use of valid C++ overloading.  Consider
+the following example:
+</p>
+
+<div class="code">
+<pre>
+void foo(int x);
+void foo(long x);
+</pre>
+</div>
+
+<p>
+In C++, this is perfectly legal.  However, in a scripting language, there is generally only one kind of integer
+object.  Therefore, which one of these functions do you pick?   Clearly, there is no way to truly make a distinction 
+just by looking at the value of the integer itself (<tt>int</tt> and <tt>long</tt> may even be the same precision).   
+Therefore, when SWIG encounters this situation, it may generate a warning message like this for scripting languages:
+</p>
+
+<div class="shell">
+<pre>
+example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.
+</pre>
+</div>
+
+<p>
+or for statically typed languages like Java:
+</p>
+
+<div class="shell">
+<pre>
+example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
+at example.i:3 used.
+</pre>
+</div>
+
+<p>
+This means that the second overloaded function will be inaccessible
+from a scripting interface or the method won't be wrapped at all. 
+This is done as SWIG does not know how to disambiguate it from an earlier method.
+</p>
+
+<p>
+Ambiguity problems are known to arise in the following situations:
+</p>
+
+<ul>
+<li>Integer conversions.   Datatypes such as <tt>int</tt>, <tt>long</tt>, and <tt>short</tt> cannot be disambiguated in some languages. Shown above.
+</li>
+
+<li>Floating point conversion.  <tt>float</tt> and <tt>double</tt> can not be disambiguated in some languages.
+</li>
+
+<li>Pointers and references. For example, <tt>Foo *</tt> and <tt>Foo &amp;</tt>.
+</li>
+
+<li>Pointers and arrays.  For example, <tt>Foo *</tt> and <tt>Foo [4]</tt>.
+</li>
+
+<li>Pointers and instances.  For example, <tt>Foo</tt> and <tt>Foo *</tt>.  Note: SWIG converts all
+instances to pointers.
+</li>
+
+<li>Qualifiers.  For example, <tt>const Foo *</tt> and <tt>Foo *</tt>.
+</li>
+
+<li>Default vs. non default arguments.   For example, <tt>foo(int a, int b)</tt> and <tt>foo(int a, int b = 3)</tt>.
+</li>
+</ul>
+
+<p>
+When an ambiguity arises, methods are checked in the same order as they appear in the interface file.
+Therefore, earlier methods will shadow methods that appear later.  
+</p>
+
+<p>
+When wrapping an overloaded function, there is a chance that you will get an error message like this:
+</p>
+
+<div class="shell">
+<pre>
+example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
+rule for 'int').
+</pre>
+</div>
+
+<p>
+This error means that the target language module supports overloading,
+but for some reason there is no type-checking rule that can be used to
+generate a working dispatch function.  The resulting behavior is then
+undefined.  You should report this as a bug to the
+<a href="http://www.swig.org/bugs.html">SWIG bug tracking database</a>.
+</p>
+
+<p>
+If you get an error message such as the following,
+</p>
+
+<div class="shell">
+<pre>
+foo.i:6. Overloaded declaration ignored.  Spam::foo(double )
+foo.i:5. Previous declaration is Spam::foo(int )
+foo.i:7. Overloaded declaration ignored.  Spam::foo(Bar *,Spam *,int )
+foo.i:5. Previous declaration is Spam::foo(int )
+</pre>
+</div>
+
+<p>
+it means that the target language module has not yet implemented support for overloaded
+functions and methods.  The only way to fix the problem is to read the next section.
+</p>
+
+<H3><a name="ambiguity_resolution_renaming"></a>6.15.3 Ambiguity resolution and renaming</H3>
+
+
+<p>
+If an ambiguity in overload resolution occurs or if a module doesn't
+allow overloading, there are a few strategies for dealing with the
+problem.  First, you can tell SWIG to ignore one of the methods.  This
+is easy---simply use the <tt>%ignore</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%ignore foo(long);
+
+void foo(int);
+void foo(long);       // Ignored.  Oh well.
+</pre>
+</div>
+
+<p>
+The other alternative is to rename one of the methods.  This can be
+done using <tt>%rename</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename("foo_short") foo(short);
+%rename(foo_long) foo(long);
+
+void foo(int);
+void foo(short);      // Accessed as foo_short()
+void foo(long);       // Accessed as foo_long()
+</pre>
+</div>
+
+<p>
+Note that the quotes around the new name are optional, however,
+should the new name be a C/C++ keyword they would be essential in order to avoid a parsing error.
+The <tt>%ignore</tt> and <tt>%rename</tt> directives are both rather powerful
+in their ability to match declarations.    When used in their simple form, they apply to
+both global functions and methods.  For example:
+</p>
+
+<div class="code">
+<pre>
+/* Forward renaming declarations */
+%rename(foo_i) foo(int); 
+%rename(foo_d) foo(double);
+...
+void foo(int);           // Becomes 'foo_i'
+void foo(char *c);       // Stays 'foo' (not renamed)
+
+class Spam {
+public:
+   void foo(int);      // Becomes 'foo_i'
+   void foo(double);   // Becomes 'foo_d'
+   ...
+};
+</pre>
+</div>
+
+<p>
+If you only want the renaming to apply to a certain scope, the C++ scope resolution operator (::) can be used.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(foo_i) ::foo(int);      // Only rename foo(int) in the global scope.
+                                // (will not rename class members)
+
+%rename(foo_i) Spam::foo(int);  // Only rename foo(int) in class Spam
+</pre>
+</div>
+
+<p>
+When a renaming operator is applied to a class as in <tt>Spam::foo(int)</tt>, it is applied to
+that class and all derived classes.   This can be used to apply a consistent renaming across
+an entire class hierarchy with only a few declarations.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(foo_i) Spam::foo(int);
+%rename(foo_d) Spam::foo(double);
+
+class Spam {
+public:
+   virtual void foo(int);      // Renamed to foo_i
+   virtual void foo(double);   // Renamed to foo_d
+   ...
+};
+
+class Bar : public Spam {
+public:
+   virtual void foo(int);      // Renamed to foo_i
+   virtual void foo(double);   // Renamed to foo_d
+...
+};
+
+class Grok : public Bar {
+public:
+   virtual void foo(int);      // Renamed to foo_i
+   virtual void foo(double);   // Renamed to foo_d
+...
+};
+</pre>
+</div>
+
+<p>
+It is also possible to include <tt>%rename</tt> specifications in the
+class definition itself. For example:
+</p>
+
+<div class="code">
+<pre>
+class Spam {
+   %rename(foo_i) foo(int);
+   %rename(foo_d) foo(double);
+public:
+   virtual void foo(int);      // Renamed to foo_i
+   virtual void foo(double);   // Renamed to foo_d
+   ...
+};
+
+class Bar : public Spam {
+public:
+   virtual void foo(int);      // Renamed to foo_i
+   virtual void foo(double);   // Renamed to foo_d
+...
+};
+</pre>
+</div>
+
+<p>
+In this case, the <tt>%rename</tt> directives still get applied across the entire 
+inheritance hierarchy, but it's no longer necessary to explicitly specify the
+class prefix <tt>Spam::</tt>. 
+</p>
+
+<p>
+A special form of <tt>%rename</tt> can be used to apply a renaming just to class
+members (of all classes):
+</p>
+
+<div class="code">
+<pre>
+%rename(foo_i) *::foo(int);   // Only rename foo(int) if it appears in a class.
+</pre>
+</div>
+
+<p>
+Note: the <tt>*::</tt> syntax is non-standard C++, but the '*' is meant to be a
+wildcard that matches any class name (we couldn't think of a better
+alternative so if you have a better idea, send email to
+the <a href="http://www.swig.org/mail.html">swig-devel mailing list</a>.
+</p>
+
+<p>
+Although this discussion has primarily focused on <tt>%rename</tt> all of the same rules
+also apply to <tt>%ignore</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%ignore foo(double);          // Ignore all foo(double)
+%ignore Spam::foo;            // Ignore foo in class Spam
+%ignore Spam::foo(double);    // Ignore foo(double) in class Spam
+%ignore *::foo(double);       // Ignore foo(double) in all classes
+</pre>
+</div>
+
+<p>
+When applied to a base class, <tt>%ignore</tt> forces all definitions in derived classes
+to disappear. For example, <tt>%ignore Spam::foo(double)</tt> will eliminate <tt>foo(double)</tt> in
+<tt>Spam</tt> and all classes derived from <tt>Spam</tt>.
+</p>
+
+<p>
+<b>Notes on %rename and %ignore:</b>
+</p>
+
+<ul>
+<li><p>Since, the <tt>%rename</tt> declaration is used to declare a renaming in advance, it can be
+placed at the start of an interface file.  This makes it possible to apply a consistent name
+resolution without having to modify header files. For example:</p>
+
+<div class="code">
+<pre>
+%module foo
+
+/* Rename these overloaded functions */
+%rename(foo_i) foo(int); 
+%rename(foo_d) foo(double);
+
+%include "header.h"
+</pre>
+</div>
+</li>
+
+<li><p>The scope qualifier (::) can also be used on simple names.  For example:</p>
+<div class="code">
+<pre>
+%rename(bar) ::foo;       // Rename foo to bar in global scope only
+%rename(bar) Spam::foo;   // Rename foo to bar in class Spam only
+%rename(bar) *::foo;      // Rename foo in classes only
+</pre>
+</div>
+</li>
+
+<li><p>Name matching tries to find the most specific match that is
+defined.  A qualified name such as <tt>Spam::foo</tt> always has
+higher precedence than an unqualified name <tt>foo</tt>.
+<tt>Spam::foo</tt> has higher precedence than <tt>*::foo</tt> and
+<tt>*::foo</tt> has higher precedence than <tt>foo</tt>.  A
+parameterized name has higher precedence than an unparameterized name
+within the same scope level.  However, an unparameterized name with a
+scope qualifier has higher precedence than a parameterized name in
+global scope (e.g., a renaming of <tt>Spam::foo</tt> takes precedence
+over a renaming of <tt>foo(int)</tt>).</p>
+</li>
+
+<li><p>
+The order in which <tt>%rename</tt> directives are defined does not matter
+as long as they appear before the declarations to be renamed.  Thus, there is no difference
+between saying:</p>
+
+<div class="code">
+<pre>
+%rename(bar) foo;
+%rename(foo_i) Spam::foo(int);
+%rename(Foo) Spam::foo;
+</pre>
+</div>
+
+<p>
+and this
+</p>
+
+<div class="code">
+<pre>
+%rename(Foo) Spam::foo;
+%rename(bar) foo;
+%rename(foo_i) Spam::foo(int);
+</pre>
+</div>
+
+<p>
+(the declarations are not stored in a linked list and order has no
+importance).  Of course, a repeated <tt>%rename</tt> directive will
+change the setting for a previous <tt>%rename</tt> directive if exactly the 
+same name, scope,  and parameters are supplied.
+</p>
+</li>
+
+<li>For multiple inheritance where renaming rules are defined for multiple base classes,
+the first renaming rule found on a depth-first traversal of the class hierarchy 
+is used.
+</li>
+
+<li><p>The name matching rules strictly follow member qualification rules.
+For example, if you have a class like this:</p>
+
+<div class="code">
+<pre>
+class Spam {
+public:
+   ...
+   void bar() const;
+   ...
+};
+</pre>
+</div>
+
+<p>
+the declaration
+</p>
+
+<div class="code">
+<pre>
+%rename(name) Spam::bar();
+</pre>
+</div>
+
+<p>
+will not apply as there is no unqualified member <tt>bar()</tt>. The following will apply as
+the qualifier matches correctly:
+</p>
+
+<div class="code">
+<pre>
+%rename(name) Spam::bar() const;
+</pre>
+</div>
+
+<p>
+An often overlooked C++ feature is that classes can define two different overloaded members
+that differ only in their qualifiers, like this:
+</p>
+
+<div class="code">
+<pre>
+class Spam {
+public:
+   ...
+   void bar();         // Unqualified member
+   void bar() const;   // Qualified member
+   ...
+};
+</pre>
+</div>
+
+<p>
+%rename can then be used to target each of the overloaded methods individually. 
+For example we can give them separate names in the target language:
+</p>
+
+<div class="code">
+<pre>
+%rename(name1) Spam::bar();
+%rename(name2) Spam::bar() const;
+</pre>
+</div>
+
+<p>
+Similarly, if you
+merely wanted to ignore one of the declarations, use <tt>%ignore</tt>
+with the full qualification.  For example, the following directive
+would tell SWIG to ignore the <tt>const</tt> version of <tt>bar()</tt>
+above:
+</p>
+
+<div class="code">
+<pre>
+%ignore Spam::bar() const;   // Ignore bar() const, but leave other bar() alone
+</pre>
+</div>
+
+</li>
+
+<li><p>
+Currently no resolution is performed in order to match function parameters. This means function parameter types must match exactly.
+For example, namespace qualifiers and typedefs will not work. The following usage of typedefs demonstrates this:
+
+<div class="code">
+<pre>
+typedef int Integer;
+
+%rename(foo_i) foo(int);
+
+class Spam {
+public:
+   void foo(Integer);  // Stays 'foo' (not renamed)
+};
+class Ham {
+public:
+   void foo(int);      // Renamed to foo_i
+};
+</pre>
+</div>
+
+<li><p>
+The name matching rules also use default arguments for finer control when wrapping methods that have default arguments.
+Recall that methods with default arguments are wrapped as if the equivalent overloaded methods had been parsed
+(<a href="#SWIGPlus_default_args">Default arguments</a> section).
+Let's consider the following example class:</p>
+
+<div class="code">
+<pre>
+class Spam {
+public:
+   ...
+   void bar(int i=-1, double d=0.0);
+   ...
+};
+</pre>
+</div>
+
+<p>
+The following <tt>%rename</tt> will match exactly and apply to all the target language overloaded methods because the declaration with the default arguments
+exactly matches the wrapped method:
+</p>
+
+<div class="code">
+<pre>
+%rename(newbar) Spam::bar(int i=-1, double d=0.0);
+</pre>
+</div>
+
+<p>
+The C++ method can then be called from the target language with the new name no matter how many arguments are specified, for example:
+<tt>newbar(2, 2.0)</tt>, <tt>newbar(2)</tt> or <tt>newbar()</tt>.
+However, if the <tt>%rename</tt> does not contain the default arguments, it will only apply to the single equivalent target language overloaded method.
+So if instead we have:
+</p>
+
+<div class="code">
+<pre>
+%rename(newbar) Spam::bar(int i, double d);
+</pre>
+</div>
+
+<p>
+The C++ method must then be called from the target language with the new name <tt>newbar(2, 2.0)</tt> when both arguments are supplied
+or with the original name as <tt>bar(2)</tt> (one argument) or <tt>bar()</tt> (no arguments).
+In fact it is possible to use <tt>%rename</tt> on the equivalent overloaded methods, to rename all the equivalent overloaded methods:
+</p>
+
+<div class="code">
+<pre>
+%rename(bar_2args)   Spam::bar(int i, double d);
+%rename(bar_1arg)    Spam::bar(int i);
+%rename(bar_default) Spam::bar();
+</pre>
+</div>
+
+<p>
+Similarly, the extra overloaded methods can be selectively ignored using <tt>%ignore</tt>.
+</p>
+
+<p>
+<b>Compatibility note:</b>  The <tt>%rename</tt> directive introduced the default argument matching rules in SWIG-1.3.23 at the same time as the changes
+to wrapping methods with default arguments was introduced.
+</p>
+
+</li>
+
+</ul>
+
+<H3><a name="SWIGPlus_nn27"></a>6.15.4 Comments on overloading</H3>
+
+
+<p>
+Support for overloaded methods was first added in SWIG-1.3.14.   The implementation
+is somewhat unusual when compared to similar tools.  For instance, the order in which
+declarations appear is largely irrelevant in SWIG.   Furthermore, SWIG does not rely
+upon trial execution or exception handling to figure out which method to invoke. 
+</p>
+
+<p>
+Internally, the overloading mechanism is completely configurable by the target language
+module.  Therefore, the degree of overloading support may vary from language to language. 
+As a general rule, statically typed languages like Java are able to provide more support
+than dynamically typed languages like Perl, Python, Ruby, and Tcl.
+</p>
+
+<H2><a name="SWIGPlus_nn28"></a>6.16 Wrapping overloaded operators</H2>
+
+
+<p>
+C++ overloaded operator declarations can be wrapped. 
+For example, consider a class like this:
+</p>
+
+<div class="code">
+<pre>
+class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &amp;operator=(const Complex &amp;c) {
+    rpart = c.rpart;
+    ipart = c.ipart;
+    return *this;
+  }
+  Complex operator+(const Complex &amp;c) const {
+    return Complex(rpart+c.rpart, ipart+c.ipart);
+  }
+  Complex operator-(const Complex &amp;c) const {
+    return Complex(rpart-c.rpart, ipart-c.ipart);
+  }
+  Complex operator*(const Complex &amp;c) const {
+    return Complex(rpart*c.rpart - ipart*c.ipart,
+		   rpart*c.ipart + c.rpart*ipart);
+  }
+  Complex operator-() const {
+    return Complex(-rpart, -ipart);
+  }
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+</pre>
+</div>
+
+<p>
+When operator declarations appear, they are handled in
+<em>exactly</em> the same manner as regular methods.  However, the
+names of these methods are set to strings like "<tt>operator +</tt>"
+or "<tt>operator -</tt>".  The problem with these names is that they
+are illegal identifiers in most scripting languages.  For instance,
+you can't just create a method called "<tt>operator +</tt>" in
+Python--there won't be any way to call it.
+</p>
+
+<p>
+Some language modules already know how to automatically handle certain
+operators (mapping them into operators in the target language).
+However, the underlying implementation of this is really managed in a
+very general way using the <tt>%rename</tt> directive.  For example,
+in Python a declaration similar to this is used:
+</p>
+
+<div class="code">
+<pre>
+%rename(__add__) Complex::operator+;
+</pre>
+</div>
+
+<p>
+This binds the + operator to a method called <tt>__add__</tt> (which
+is conveniently the same name used to implement the Python + operator). 
+Internally, the generated wrapper code for a wrapped operator will look
+something like this pseudocode:
+</p>
+
+<div class="code">
+<pre>
+_wrap_Complex___add__(args) {
+   ... get args ...
+   obj-&gt;operator+(args);
+   ...
+}
+</pre>
+</div>
+
+<p>
+When used in the target language, it may now be possible to use the overloaded
+operator normally. For example:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; a = Complex(3,4)
+&gt;&gt;&gt; b = Complex(5,2)
+&gt;&gt;&gt; c = a + b           # Invokes __add__ method
+</pre>
+</div>
+
+<p>
+It is important to realize that there is nothing magical happening
+here.  The <tt>%rename</tt> directive really only picks a valid method
+name.  If you wrote this:
+</p>
+
+<div class="code">
+<pre>
+%rename(add) operator+;
+</pre>
+</div>
+
+<p>
+The resulting scripting interface might work like this:
+</p>
+
+<div class="targetlang">
+<pre>
+a = Complex(3,4)
+b = Complex(5,2)
+c = a.add(b)      # Call a.operator+(b)
+</pre>
+</div>
+
+<p>
+All of the techniques described to deal with overloaded functions also
+apply to operators.  For example:
+</p>
+
+<div class="code">
+<pre>
+%ignore Complex::operator=;             // Ignore = in class Complex
+%ignore *::operator=;                   // Ignore = in all classes
+%ignore operator=;                      // Ignore = everywhere.
+
+%rename(__sub__) Complex::operator-; 
+%rename(__neg__) Complex::operator-();  // Unary - 
+</pre>
+</div>
+
+<p>
+The last part of this example illustrates how multiple definitions of
+the <tt>operator-</tt> method might be handled.
+</p>
+
+<p>
+Handling operators in this manner is mostly straightforward.  However, there are a few subtle
+issues to keep in mind:
+</p>
+
+<ul>
+<li><p>In C++, it is fairly common to define different versions of the operators to account for
+different types.  For example, a class might also include a friend function like this:</p>
+
+<div class="code">
+<pre>
+class Complex {
+public:
+  friend Complex operator+(Complex &amp;, double);
+};
+Complex operator+(Complex &amp;, double);
+</pre>
+</div>
+
+<p>
+SWIG simply ignores all <tt>friend</tt> declarations.  Furthermore, it
+doesn't know how to associate the associated <tt>operator+</tt> with
+the class (because it's not a member of the class).
+</p>
+
+<p>
+It's still possible to make a wrapper for this operator, but you'll
+have to handle it like a normal function. For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(add_complex_double) operator+(Complex &amp;, double);
+</pre>
+</div>
+</li>
+
+<li><p>Certain operators are ignored by default. For instance, <tt>new</tt> and <tt>delete</tt> operators
+are ignored as well as conversion operators.
+</p></li>
+
+<li>The semantics of certain C++ operators may not match those in the target language.
+</li>
+</ul>
+
+<H2><a name="SWIGPlus_class_extension"></a>6.17 Class extension</H2>
+
+
+<p>
+New methods can be added to a class using the <tt>%extend</tt>
+directive. This directive is primarily used in conjunction with proxy
+classes to add additional functionality to an existing class. For
+example :
+</p>
+
+<div class="code"><pre>
+%module vector
+%{
+#include "vector.h"
+%}
+
+class Vector {
+public:
+	double x,y,z;
+	Vector();
+	~Vector();
+	... bunch of C++ methods ...
+	%extend {
+		char *__str__() {
+			static char temp[256];
+			sprintf(temp,"[ %g, %g, %g ]", $self-&gt;x,$self-&gt;y,$self-&gt;z);
+			return &amp;temp[0];
+		}
+	}
+};
+</pre></div>
+
+<p>
+This code adds a<tt> __str__</tt> method to our class for producing a
+string representation of the object. In Python, such a method would
+allow us to print the value of an object using the <tt>print</tt>
+command.
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt;
+&gt;&gt;&gt; v = Vector();
+&gt;&gt;&gt; v.x = 3
+&gt;&gt;&gt; v.y = 4
+&gt;&gt;&gt; v.z = 0
+&gt;&gt;&gt; print(v)
+[ 3.0, 4.0, 0.0 ]
+&gt;&gt;&gt;
+
+</pre></div>
+
+<p>
+The C++ 'this' pointer is often needed to access member variables, methods etc.
+The <tt>$self</tt> special variable should be used wherever you could use 'this'.
+The example above demonstrates this for accessing member variables.
+Note that the members dereferenced by <tt>$self</tt> must be public members as the code is ultimately generated
+into a global function and so will not have any access to non-public members.
+The implicit 'this' pointer that is present in C++ methods is not present in <tt>%extend</tt> methods.
+In order to access anything in the extended class or its base class, an explicit 'this' is required.
+The following example shows how one could access base class members:
+</p>
+
+<div class="code"><pre>
+struct Base {
+  virtual void method(int v) {
+    ...
+  }
+  int value;
+};
+struct Derived : Base {
+};
+%extend Derived {
+  virtual void method(int v) {
+    $self-&gt;Base::method(v); // akin to this-&gt;Base::method(v);
+    $self-&gt;value = v;       // akin to this-&gt;value = v;
+    ...
+  }
+}
+</pre></div>
+
+<p>
+The<tt> %extend</tt> directive follows all of the same conventions
+as its use with C structures. Please refer to the <a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>
+section for further details.
+</p>
+
+<p>
+<b>Compatibility note:</b>  The <tt>%extend</tt> directive is a new
+name for the <tt>%addmethods</tt> directive in SWIG1.1.  Since <tt>%addmethods</tt> could
+be used to extend a structure with more than just methods, a more suitable
+directive name has been chosen.
+</p>
+
+<H2><a name="SWIGPlus_nn30"></a>6.18 Templates</H2>
+
+
+<p>
+Template type names may appear anywhere a type
+is expected in an interface file.  For example:
+</p>
+
+<div class="code">
+<pre>
+void foo(vector&lt;int&gt; *a, int n);
+void bar(list&lt;int,100&gt; *x);
+</pre>
+</div>
+
+<p>
+There are some restrictions on the use of non-type arguments.  Simple literals
+are supported, and so are some constant expressions.  However, use of '&lt;'
+and '&gt;' within a constant expressions currently is not supported by SWIG
+('&lt;=' and '&gt;=' are though).  For example:
+</p>
+
+<div class="code">
+<pre>
+void bar(list&lt;int,100&gt; *x);                // OK
+void bar(list&lt;int,2*50&gt; *x);               // OK
+void bar(list&lt;int,(2&gt;1 ? 100 : 50)&gt; *x)    // Not supported
+</pre>
+</div>
+
+<p>
+The type system is smart enough to figure out clever games
+you might try to play with <tt>typedef</tt>.  For instance, consider this code:
+</p>
+
+<div class="code">
+<pre>
+typedef int Integer;
+void foo(vector&lt;int&gt; *x, vector&lt;Integer&gt; *y);
+</pre>
+</div>
+
+<p>
+In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type
+as <tt>vector&lt;int&gt;</tt>.  The wrapper for <tt>foo()</tt> will
+accept either variant.
+</p>
+
+<p>
+Starting with SWIG-1.3.7, simple C++ template declarations can also be
+wrapped.  SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things
+you need to know about template wrapping.  First, a bare C++ template
+does not define any sort of runnable object-code for which SWIG can
+normally create a wrapper.  Therefore, in order to wrap a template,
+you need to give SWIG information about a particular template
+instantiation (e.g., <tt>vector&lt;int&gt;</tt>,
+<tt>array&lt;double&gt;</tt>, etc.).  Second, an instantiation name
+such as <tt>vector&lt;int&gt;</tt> is generally not a valid identifier
+name in most target languages.  Thus, you will need to give the
+template instantiation a more suitable name such as <tt>intvector</tt>
+when creating a wrapper.
+</p>
+
+<p>
+To illustrate, consider the following template definition:
+</p>
+
+<div class="code"><pre>
+template&lt;class T&gt; class List {
+private:
+    T *data;
+    int nitems;
+    int maxitems;
+public:
+    List(int max) {
+      data = new T [max];
+      nitems = 0;
+      maxitems = max;
+    }
+    ~List() {
+      delete [] data;
+    };
+    void append(T obj) {
+      if (nitems &lt; maxitems) {
+        data[nitems++] = obj;
+      }
+    }
+    int length() {
+      return nitems;
+    }
+    T get(int n) {
+      return data[n];
+    }
+};
+</pre></div>
+
+<p>
+By itself, this template declaration is useless--SWIG simply ignores it
+because it doesn't know how to generate any code until unless a definition of
+<tt>T</tt> is provided.
+</p>
+
+<p>
+One way to create wrappers for a specific template instantiation is to simply
+provide an expanded version of the class directly like this:
+</p>
+
+<div class="code">
+<pre>
+%rename(intList) List&lt;int&gt;;       // Rename to a suitable identifier
+class List&lt;int&gt; {
+private:
+    int *data;
+    int nitems;
+    int maxitems;
+public:
+    List(int max);
+    ~List();
+    void append(int obj);
+    int length();
+    int get(int n);
+};
+</pre>
+</div>
+
+
+<p>
+The <tt>%rename</tt> directive is needed to give the template class an appropriate identifier
+name in the target language (most languages would not recognize C++ template syntax as a valid
+class name).  The rest of the code is the same as what would appear in a normal
+class definition.
+</p>
+
+<p>
+Since manual expansion of templates gets old in a hurry, the <tt>%template</tt> directive can
+be used to create instantiations of a template class.  Semantically, <tt>%template</tt> is
+simply a shortcut---it expands template code in exactly the same way as shown above.  Here
+are some examples:
+</p>
+
+<div class="code">
+<pre>
+/* Instantiate a few different versions of the template */
+%template(intList) List&lt;int&gt;;
+%template(doubleList) List&lt;double&gt;;
+</pre>
+</div>
+
+<p>
+The argument to <tt>%template()</tt> is the name of the instantiation
+in the target language.  The name you choose should not conflict with
+any other declarations in the interface file with one exception---it
+is okay for the template name to match that of a typedef declaration.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%template(intList) List&lt;int&gt;;
+...
+typedef List&lt;int&gt; intList;    // OK
+</pre>
+</div>
+
+<p>
+SWIG can also generate wrappers for function templates using a similar technique.
+For example:
+</p>
+
+<div class="code">
+<pre>
+// Function template
+template&lt;class T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
+
+// Make some different versions of this function
+%template(maxint) max&lt;int&gt;;
+%template(maxdouble) max&lt;double&gt;;
+</pre>
+</div>
+
+<p>
+In this case, <tt>maxint</tt> and <tt>maxdouble</tt> become unique names for specific 
+instantiations of the function.
+</p>
+
+<p>
+The number of arguments supplied to <tt>%template</tt> should match that in the
+original template definition.  Template default arguments are supported.  For example:
+</p>
+
+<div class="code">
+<pre>
+template vector&lt;typename T, int max=100&gt; class vector {
+...
+};
+
+%template(intvec) vector&lt;int&gt;;           // OK
+%template(vec1000) vector&lt;int,1000&gt;;     // OK
+</pre>
+</div>
+
+<p>
+The <tt>%template</tt> directive should not be used to wrap the same
+template instantiation more than once in the same scope.  This will
+generate an error.  For example:
+</p>
+
+<div class="code">
+<pre>
+%template(intList) List&lt;int&gt;;
+%template(Listint) List&lt;int&gt;;    // Error.   Template already wrapped.
+</pre>
+</div>
+
+<p>
+This error is caused because the template expansion results in two
+identical classes with the same name.  This generates a symbol table
+conflict.  Besides, it probably more efficient to only wrap a specific
+instantiation only once in order to reduce the potential for code
+bloat.
+</p>
+
+<p>
+Since the type system knows how to handle <tt>typedef</tt>, it is
+generally not necessary to instantiate different versions of a template
+for typenames that are equivalent.  For instance, consider this code:
+</p>
+
+<div class="code">
+<pre>
+%template(intList) vector&lt;int&gt;;
+typedef int Integer;
+...
+void foo(vector&lt;Integer&gt; *x);
+</pre>
+</div>
+
+<p>
+In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type as
+<tt>vector&lt;int&gt;</tt>.  Any use of <tt>Vector&lt;Integer&gt;</tt> is mapped back to the 
+instantiation of <tt>vector&lt;int&gt;</tt> created earlier.  Therefore, it is
+not necessary to instantiate a new class for the type <tt>Integer</tt> (doing so is
+redundant and will simply result in code bloat).
+</p>
+
+<p>
+When a template is instantiated using <tt>%template</tt>, information
+about that class is saved by SWIG and used elsewhere in the program.
+For example, if you wrote code like this,
+</p>
+
+<div class="code">
+<pre>
+...
+%template(intList) List&lt;int&gt;;
+...
+class UltraList : public List&lt;int&gt; {
+   ...
+};
+</pre>
+</div>
+
+<p>
+then SWIG knows that <tt>List&lt;int&gt;</tt> was already wrapped as a class called 
+<tt>intList</tt> and arranges to handle the inheritance correctly.    If, on the other hand,
+nothing is known about <tt>List&lt;int&gt;</tt>, you will get a warning message similar to this:
+</p>
+
+<div class="shell">
+<pre>
+example.h:42. Nothing known about class 'List&lt;int &gt;' (ignored). 
+example.h:42. Maybe you forgot to instantiate 'List&lt;int &gt;' using %template. 
+</pre>
+</div>
+
+<p>
+If a template class inherits from another template class, you need to
+make sure that base classes are instantiated before derived classes.
+For example:
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T&gt; class Foo {
+...
+};
+
+template&lt;class T&gt; class Bar : public Foo&lt;T&gt; {
+...
+};
+
+// Instantiate base classes first 
+%template(intFoo) Foo&lt;int&gt;;
+%template(doubleFoo) Foo&lt;double&gt;;
+
+// Now instantiate derived classes
+%template(intBar) Bar&lt;int&gt;;
+%template(doubleBar) Bar&lt;double&gt;;
+</pre>
+</div>
+
+<p>
+The order is important since SWIG uses the instantiation names to
+properly set up the inheritance hierarchy in the resulting wrapper
+code (and base classes need to be wrapped before derived classes).
+Don't worry--if you get the order wrong, SWIG should generate a warning message.
+</p>
+
+<p>
+Occasionally, you may need to tell SWIG about base classes that are defined by templates,
+but which aren't supposed to be wrapped.  Since SWIG is not able to automatically
+instantiate templates for this purpose, you must do it manually.  To do this, simply
+use <tt>%template</tt> with no name.  For example:
+</p>
+
+<div class="code">
+<pre>
+// Instantiate traits&lt;double,double&gt;, but don't wrap it.
+%template() traits&lt;double,double&gt;;
+</pre>
+</div>
+
+<p>
+If you have to instantiate a lot of different classes for many different types,
+you might consider writing a SWIG macro.  For example:
+</p>
+
+<div class="code">
+<pre>
+%define TEMPLATE_WRAP(prefix, T...) 
+%template(prefix ## Foo) Foo&lt;T &gt;;
+%template(prefix ## Bar) Bar&lt;T &gt;;
+...
+%enddef
+
+TEMPLATE_WRAP(int, int)
+TEMPLATE_WRAP(double, double)
+TEMPLATE_WRAP(String, char *)
+TEMPLATE_WRAP(PairStringInt, std::pair&lt;string, int&gt;)
+...
+</pre>
+</div>
+
+<p>
+Note the use of a vararg macro for the type T. If this wasn't used, the comma in the templated type in the last example would not be possible.
+</p>
+
+<p>
+The SWIG template mechanism <em>does</em> support specialization. For instance, if you define
+a class like this,
+</p>
+
+<div class="code">
+<pre>
+template&lt;&gt; class List&lt;int&gt; {
+private:
+    int *data;
+    int nitems;
+    int maxitems;
+public:
+    List(int max);
+    ~List();
+    void append(int obj);
+    int length();
+    int get(int n);
+};
+</pre>
+</div>
+
+<p>
+then SWIG will use this code whenever the user expands <tt>List&lt;int&gt;</tt>.   In practice,
+this may have very little effect on the underlying wrapper code since
+specialization is often used to provide slightly modified method bodies (which
+are ignored by SWIG).  However, special SWIG
+directives such as <tt>%typemap</tt>, <tt>%extend</tt>, and so forth can be attached
+to a specialization to provide customization for specific types.
+</p>
+
+<p>
+Partial template specialization is partially supported by SWIG.   For example, this
+code defines a template that is applied when the template argument is a pointer.
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T&gt; class List&lt;T*&gt; {
+private:
+    T *data;
+    int nitems;
+    int maxitems;
+public:
+    List(int max);
+    ~List();
+    void append(int obj);
+    int length();
+    T get(int n);
+};
+</pre>
+</div>
+
+<p>
+SWIG should be able to handle most simple uses of partial specialization.  However, it may fail
+to match templates properly in more complicated cases.  For example, if you have this code,
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T1, class T2&gt; class Foo&lt;T1, T2 *&gt; { };
+</pre>
+</div>
+
+<p>
+SWIG isn't able to match it properly for instantiations like <tt>Foo&lt;int *, int *&gt;</tt>.
+This problem is not due to parsing, but due to the fact that SWIG does not currently implement all
+of the C++ argument deduction rules.
+</p>
+
+<p>
+Member function templates are supported.  The underlying principle is the same
+as for normal templates--SWIG can't create a wrapper unless you provide
+more information about types.  For example, a class with a member template might
+look like this:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     template&lt;class T&gt; void bar(T x, T y) { ... };
+     ...
+};
+</pre>
+</div>
+
+<p>
+To expand the template, simply use <tt>%template</tt> inside the class.
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     template&lt;class T&gt; void bar(T x, T y) { ... };
+     ...
+     %template(barint)    bar&lt;int&gt;;
+     %template(bardouble) bar&lt;double&gt;;
+};
+</pre>
+</div>
+
+<p>
+Or, if you want to leave the original class definition alone, just do this:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     template&lt;class T&gt; void bar(T x, T y) { ... };
+     ...
+};
+...
+%extend Foo {
+     %template(barint)    bar&lt;int&gt;;
+     %template(bardouble) bar&lt;double&gt;;
+};
+</pre>
+</div>
+
+<p>
+or simply
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     template&lt;class T&gt; void bar(T x, T y) { ... };
+     ...
+};
+...
+
+%template(bari) Foo::bar&lt;int&gt;;
+%template(bard) Foo::bar&lt;double&gt;;
+</pre>
+</div>
+
+<p>
+In this case, the <tt>%extend</tt> directive is not needed, and
+<tt>%template</tt> does the exactly same job, i.e., it adds two new
+methods to the Foo class. 
+</p>
+
+
+<p>
+Note: because of the way that templates are handled, the <tt>%template</tt> directive
+must always appear <em>after</em> the definition of the template to be expanded.
+</p>
+
+<p>
+Now, if your target language supports overloading, you can even try
+</p>
+
+<div class="code">
+<pre>
+%template(bar) Foo::bar&lt;int&gt;;
+%template(bar) Foo::bar&lt;double&gt;;
+</pre>
+</div>
+
+<p>
+and since the two new wrapped methods have the same name 'bar', they will be
+overloaded, and when called, the correct method will be dispatched
+depending on the argument type.
+</p>
+
+
+<p>
+When used with members, the <tt>%template</tt> directive may be placed in another
+template class.  Here is a slightly perverse example:
+</p>
+
+<div class="code">
+<pre>
+// A template
+template&lt;class T&gt; class Foo {
+public:
+     // A member template
+     template&lt;class S&gt; T bar(S x, S y) { ... };
+     ...
+};
+
+// Expand a few member templates
+%extend Foo {
+  %template(bari) bar&lt;int&gt;;
+  %template(bard) bar&lt;double&gt;;
+}
+
+// Create some wrappers for the template
+%template(Fooi) Foo&lt;int&gt;;
+%template(Food) Foo&lt;double&gt;;
+</pre>
+</div>
+
+<p>
+Miraculously, you will find that each expansion of <tt>Foo</tt> has member
+functions <tt>bari()</tt> and <tt>bard()</tt> added.
+</p>
+
+<p>
+A common use of member templates is to define constructors for copies
+and conversions. For example:
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T1, class T2&gt; struct pair {
+   T1 first;
+   T2 second;
+   pair() : first(T1()), second(T2()) { }
+   pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { }
+   template&lt;class U1, class U2&gt; pair(const pair&lt;U1,U2&gt; &amp;x) 
+                                        : first(x.first),second(x.second) { }
+};
+</pre>
+</div>
+
+<p>
+This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored
+unless you explicitly expand it.  To do that, you could expand a few versions of the constructor
+in the template class itself.  For example:
+</p>
+
+<div class="code">
+<pre>
+%extend pair {
+   %template(pair) pair&lt;T1,T2&gt;;        // Generate default copy constructor
+};
+</pre>
+</div>
+
+<p>
+When using <tt>%extend</tt> in this manner, notice how you can still use the template parameters in
+the original template definition. 
+</p>
+
+<p>
+Alternatively, you could expand the constructor template in selected instantiations. For example:
+</p>
+
+<div class="code">
+<pre>
+// Instantiate a few versions
+%template(pairii) pair&lt;int,int&gt;;
+%template(pairdd) pair&lt;double,double&gt;;
+
+// Create a default constructor only 
+%extend pair&lt;int,int&gt; {
+   %template(paird) pair&lt;int,int&gt;;         // Default constructor
+};
+
+// Create default and conversion constructors 
+%extend pair&lt;double,double&gt; {
+   %template(paird) pair&lt;double,dobule&gt;;   // Default constructor
+   %template(pairc) pair&lt;int,int&gt;;         // Conversion constructor
+};
+</pre>
+</div>
+
+
+<p>And if your target language supports overloading, then you can try
+instead:
+</p>
+
+<div class="code">
+<pre>
+// Create default and conversion constructors 
+%extend pair&lt;double,double&gt; {
+   %template(pair) pair&lt;double,dobule&gt;;   // Default constructor
+   %template(pair) pair&lt;int,int&gt;;         // Conversion constructor
+};
+</pre>
+</div>
+
+<p>
+In this case, the default and conversion constructors have the same
+name. Hence, Swig will overload them and define an unique visible
+constructor, that will dispatch the proper call depending on the argument
+type.
+</p>
+
+<p>
+If all of this isn't quite enough and you really want to make
+someone's head explode, SWIG directives such as
+<tt>%rename</tt>, <tt>%extend</tt>, and <tt>%typemap</tt> can be
+included directly in template definitions.  For example:
+</p>
+
+<div class="code"><pre>
+// File : list.h
+template&lt;class T&gt; class List {
+   ...
+public:
+    %rename(__getitem__) get(int);
+    List(int max);
+    ~List();
+    ...
+    T get(int index);
+    %extend {
+        char *__str__() {
+            /* Make a string representation */
+            ...
+        }
+    }
+};
+</pre></div>
+
+<p>
+In this example, the extra SWIG directives are propagated to <em>every</em> template 
+instantiation.  
+</p>
+
+<p>
+It is also possible to separate these declarations from the template class.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(__getitem__) List::get;
+%extend List {
+    char *__str__() {
+        /* Make a string representation */
+        ...
+    }
+    /* Make a copy */
+    T *__copy__() {
+       return new List&lt;T&gt;(*$self);
+    }
+};
+
+...
+template&lt;class T&gt; class List {
+    ...
+    public:
+    List() { };
+    T get(int index);
+    ...
+};
+</pre>
+</div>
+
+<p>
+When <tt>%extend</tt> is decoupled from the class definition, it is
+legal to use the same template parameters as provided in the class definition.
+These are replaced when the template is expanded.
+In addition, the <tt>%extend</tt> directive can be used to add
+additional methods to a specific instantiation. For example:
+</p>
+
+<div class="code">
+<pre>
+%template(intList) List&lt;int&gt;;
+
+%extend List&lt;int&gt; {
+    void blah() {
+          printf("Hey, I'm an List&lt;int&gt;!\n");
+    }
+};
+</pre>
+</div>
+
+<p>
+SWIG even supports overloaded templated functions.  As usual the <tt>%template</tt> directive
+is used to wrap templated functions. For example:
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T&gt; void foo(T x) { };
+template&lt;class T&gt; void foo(T x, T y) { };
+
+%template(foo) foo&lt;int&gt;;
+</pre>
+</div>
+
+<p>
+This will generate two overloaded wrapper methods, the first will take a single integer as an argument
+and the second will take two integer arguments.
+</p>
+
+<p>
+Needless to say, SWIG's template support provides plenty of
+opportunities to break the universe.  That said, an important final
+point is that <b>SWIG does not perform extensive error checking of
+templates!</b> Specifically, SWIG does not perform type checking nor
+does it check to see if the actual contents of the template
+declaration make any sense.  Since the C++ compiler will hopefully
+check this when it compiles the resulting wrapper file, there is no
+practical reason for SWIG to duplicate this functionality (besides,
+none of the SWIG developers are masochistic enough to want to
+implement this right now).
+</p>
+
+<p>
+<b>Compatibility Note</b>:  The first implementation of template support relied heavily on
+macro expansion in the preprocessor.  Templates have been more tightly integrated into 
+the parser and type system in SWIG-1.3.12 and the preprocessor is no longer used. Code
+that relied on preprocessing features in template expansion will no longer work.  However,
+SWIG still allows the # operator to be used to generate a string from a template argument.
+</p>
+
+<p>
+<b>Compatibility Note</b>: In earlier versions of SWIG, the <tt>%template</tt> directive
+introduced a new class name.  This name could then be used with other directives.  For example:
+</p>
+
+<div class="code">
+<pre>
+%template(vectori) vector&lt;int&gt;;
+%extend vectori {
+    void somemethod() { }
+};
+</pre>
+</div>
+
+<p>
+This behavior is no longer supported.  Instead, you should use the original template name
+as the class name.  For example:
+</p>
+
+<div class="code">
+<pre>
+%template(vectori) vector&lt;int&gt;;
+%extend vector&lt;int&gt; {
+    void somemethod() { }
+};
+</pre>
+</div>
+
+<p>
+Similar changes apply to typemaps and other customization features.
+</p>
+
+<H2><a name="SWIGPlus_nn31"></a>6.19 Namespaces</H2>
+
+
+<p>
+Support for C++ namespaces is a relatively late addition to SWIG,
+first appearing in SWIG-1.3.12.  Before describing the implementation,
+it is worth noting that the semantics of C++ namespaces is extremely
+non-trivial--especially with regard to the C++ type system and class
+machinery.  At a most basic level, namespaces are sometimes used to 
+encapsulate common functionality.  For example:
+</p>
+
+<div class="code">
+<pre>
+namespace math {
+   double sin(double);
+   double cos(double);
+
+   class Complex {
+      double im,re;
+   public:
+      ...
+   };
+   ...
+};
+</pre>
+</div>
+
+<p>
+Members of the namespace are accessed in C++ by prepending the namespace prefix
+to names. For example:
+</p>
+
+<div class="code">
+<pre>
+double x = math::sin(1.0);
+double magnitude(math::Complex *c);
+math::Complex c;
+...
+</pre>
+</div>
+
+<p>
+At this level, namespaces are relatively easy to manage.  However, things start to get 
+very ugly when you throw in the other ways a namespace can be used.  For example,
+selective symbols can be exported from a namespace with <tt>using</tt>.
+</p>
+
+<div class="code">
+<pre>
+using math::Complex;
+double magnitude(Complex *c);       // Namespace prefix stripped
+</pre>
+</div>
+
+<p>
+Similarly, the contents of an entire namespace can be made available like this:
+</p>
+
+<div class="code">
+<pre>
+using namespace math;
+double x = sin(1.0);
+double magnitude(Complex *c);
+</pre>
+</div>
+
+<p>
+Alternatively, a namespace can be aliased:
+</p>
+
+<div class="code">
+<pre>
+namespace M = math;
+double x = M::sin(1.0);
+double magnitude(M::Complex *c);
+</pre>
+</div>
+
+<p>
+Using combinations of these features, it is possible to write head-exploding code like this:
+</p>
+
+<div class="code">
+<pre>
+namespace A {
+  class Foo {
+  };
+}
+
+namespace B {
+   namespace C {
+      using namespace A;
+   }
+   typedef C::Foo FooClass;
+}
+
+namespace BIGB = B;
+
+namespace D {
+   using BIGB::FooClass;
+   class Bar : public FooClass {
+   }
+};
+
+class Spam : public D::Bar {
+};
+
+void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
+          BIGB::C::Foo *e, D::FooClass *f);
+
+</pre>
+</div>
+
+<p>
+Given the possibility for such perversion, it's hard to imagine how
+every C++ programmer might want such code wrapped into the target
+language.  Clearly this code defines three different classes.  However, one
+of those classes is accessible under at least six different names!
+</p>
+
+<p>
+SWIG fully supports C++ namespaces in its internal type system and
+class handling code.  If you feed SWIG the above code, it will be
+parsed correctly, it will generate compilable wrapper code, and it
+will produce a working scripting language module.  However, the
+default wrapping behavior is to flatten namespaces in the target
+language.  This means that the contents of all namespaces are merged
+together in the resulting scripting language module.  For example, if
+you have code like this,
+</p>
+
+<div class="code">
+<pre>
+%module foo
+namespace foo {
+   void bar(int);
+   void spam();
+}
+
+namespace bar {
+   void blah();
+}
+
+</pre>
+</div>
+
+<p>
+then SWIG simply creates three wrapper functions <tt>bar()</tt>,
+<tt>spam()</tt>, and <tt>blah()</tt> in the target language.  SWIG
+does not prepend the names with a namespace prefix nor are the
+functions packaged in any kind of nested scope.
+</p>
+
+<p>
+There is some rationale for taking this approach.  Since C++
+namespaces are often used to define modules in C++, there is a natural
+correlation between the likely contents of a SWIG module and the contents of
+a namespace.  For instance, it would not be unreasonable to assume
+that a programmer might make a separate extension module for each C++
+namespace.  In this case, it would be redundant to prepend everything
+with an additional namespace prefix when the module itself already
+serves as a namespace in the target language.   Or put another way, if 
+you want SWIG to keep namespaces separate, simply wrap each namespace with its
+own SWIG interface.
+</p>
+
+<p>
+Because namespaces are flattened, it is possible for symbols defined in different
+namespaces to generate a name conflict in the target language. For example:
+</p>
+
+<div class="code">
+<pre>
+namespace A {
+   void foo(int);
+}
+namespace B {
+   void foo(double);
+}
+</pre>
+</div>
+
+<p>
+When this conflict occurs, you will get an error message that resembles this:
+</p>
+
+<div class="shell">
+<pre>
+example.i:26. Error. 'foo' is multiply defined in the generated module.
+example.i:23. Previous declaration of 'foo'
+</pre>
+</div>
+
+<p>
+To resolve this error, simply use <tt>%rename</tt> to disambiguate the declarations.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(B_foo) B::foo;
+...
+namespace A {
+   void foo(int);
+}
+namespace B {
+   void foo(double);     // Gets renamed to B_foo
+}
+</pre>
+</div>
+
+<p>
+Similarly, <tt>%ignore</tt> can be used to ignore declarations.
+</p>
+
+<p>
+<tt>using</tt> declarations do not have any effect on the generated wrapper
+code. They are ignored by SWIG language modules and they do not result in any
+code.  However, these declarations <em>are</em> used by the internal type
+system to track type-names. Therefore, if you have code like this:
+</p>
+
+<div class="code">
+<pre>
+namespace A {
+   typedef int Integer;
+}
+using namespace A;
+void foo(Integer x);
+</pre>
+</div>
+
+<p>
+SWIG knows that <tt>Integer</tt> is the same as <tt>A::Integer</tt> which
+is the same as <tt>int</tt>.  
+</p>
+
+<P>
+Namespaces may be combined with templates.  If necessary, the
+<tt>%template</tt> directive can be used to expand a template defined
+in a different namespace.  For example:
+</p>
+
+<div class="code">
+<pre>
+namespace foo {
+    template&lt;typename T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
+}
+
+using foo::max;
+
+%template(maxint)   max&lt;int&gt;;           // Okay.
+%template(maxfloat) foo::max&lt;float&gt;;    // Okay (qualified name).
+
+namespace bar {
+    using namespace foo;
+    %template(maxdouble)  max&lt;double&gt;;    // Okay.
+}
+</pre>
+</div>
+
+<p>
+The combination of namespaces and other SWIG directives may introduce subtle scope-related problems. 
+The key thing to keep in mind is that all SWIG generated wrappers are produced
+in the <em>global</em> namespace.   Symbols from other namespaces are always accessed using fully
+qualified names---names are never imported into the global space unless the interface happens to
+do so with a <tt>using</tt> declaration.  In almost all cases, SWIG adjusts typenames and symbols
+to be fully qualified.  However, this is not done in code fragments such as function bodies,
+typemaps, exception handlers, and so forth.  For example, consider the following:
+</p>
+
+<div class="code">
+<pre>
+namespace foo {
+    typedef int Integer;
+    class bar {
+    public:
+       ...
+    };
+}
+
+%extend foo::bar {
+   Integer add(Integer x, Integer y) {
+       Integer r = x + y;        // Error. Integer not defined in this scope
+       return r;
+   }
+};
+</pre>
+</div>
+
+<p>
+In this case, SWIG correctly resolves the added method parameters and return type to
+<tt>foo::Integer</tt>.  However, since function bodies aren't parsed and such code is
+emitted in the global namespace, this code produces a compiler error about <tt>Integer</tt>. 
+To fix the problem, make sure you use fully qualified names.  For example:
+</p>
+
+<div class="code">
+<pre>
+%extend foo::bar {
+   Integer add(Integer x, Integer y) {
+       foo::Integer r = x + y;        // Ok.
+       return r;
+   }
+};
+</pre>
+</div>
+
+<p>
+<b>Note:</b> SWIG does <em>not</em> propagate <tt>using</tt> declarations to
+the resulting wrapper code.   If these declarations appear in an interface,
+they should <em>also</em> appear in any header files that might have been 
+included in a <tt>%{ ... %}</tt> section.  In other words, don't insert extra
+<tt>using</tt> declarations into a SWIG interface unless they also appear
+in the underlying C++ code.
+</p>
+
+<p>
+<b>Note:</b> Code inclusion directives such as <tt>%{ ... %}</tt> or
+<tt>%inline %{ ... %}</tt> should not be placed inside a namespace declaration.  
+The code emitted by these directives will not be enclosed in a namespace and
+you may get very strange results.  If you need to use namespaces with
+these directives, consider the following:
+</p>
+
+<div class="code">
+<pre>
+// Good version
+%inline %{
+namespace foo {
+     void bar(int) { ... }
+     ...
+}
+%}
+
+// Bad version.  Emitted code not placed in namespace.
+namespace foo {
+%inline %{
+     void bar(int) { ... }   /* I'm bad */
+     ...
+%}
+}
+</pre>
+</div>
+
+<p>
+<b>Note:</b> When the <tt>%extend</tt> directive is used inside a namespace, the namespace name is
+included in the generated functions. For example, if you have code like this,
+</p>
+
+<div class="code">
+<pre>
+namespace foo {
+   class bar {
+   public:
+        %extend {
+           int blah(int x);
+        };
+   };
+}
+</pre>
+</div>
+
+<p>
+the added method <tt>blah()</tt> is mapped to a function <tt>int foo_bar_blah(foo::bar *self, int x)</tt>.
+This function resides in the global namespace.
+</p>
+
+<p>
+<b>Note:</b> Although namespaces are flattened in the target language, the SWIG generated wrapper
+code observes the same namespace conventions as used in the input file.  Thus, if there are no symbol
+conflicts in the input, there will be no conflicts in the generated code. 
+</p>
+
+<p>
+<b>Note:</b> In the same way that no resolution is performed on parameters, a conversion operator name must match exactly to how it is defined. Do not change the qualification of the operator. For example, suppose you had an interface like this:
+</p>
+
+<div class="code">
+<pre>
+namespace foo {
+   class bar;
+   class spam {
+   public:
+        ...
+        operator bar();      // Conversion of spam -&gt; bar
+        ...
+   };
+}
+</pre>
+</div>
+
+<p>
+The following is how the feature is expected to be written for a successful match:
+</p>
+
+<div class="code">
+<pre>
+%rename(tofoo) foo::spam::operator bar();
+</pre>
+</div>
+
+<p>
+The following does not work as no namespace resolution is performed in the matching of conversion operator names:
+</p>
+
+<div class="code">
+<pre>
+%rename(tofoo) foo::spam::operator <b>foo::</b>bar();
+</pre>
+</div>
+
+<p>
+Note, however, that if the operator is defined using a qualifier in its name, then the feature must use it too...
+</p>
+
+<div class="code">
+<pre>
+%rename(tofoo) foo::spam::operator bar();      // will not match
+%rename(tofoo) foo::spam::operator foo::bar(); // will match
+namespace foo {
+   class bar;
+   class spam {
+   public:
+        ...
+        operator foo::bar();
+        ...
+   };
+}
+</pre>
+</div>
+
+<p>
+<b>Compatibility Note:</b> Versions of SWIG prior to 1.3.32 were inconsistent in this approach. A fully qualified name was usually required, but would not work in some situations.
+</p>
+
+
+<p>
+<b>Note:</b> The flattening of namespaces is only intended to serve as
+a basic namespace implementation.  
+None of the target language modules are currently programmed
+with any namespace awareness.   In the future, language modules may or may not provide
+more advanced namespace support.
+</p>
+
+<H2><a name="SWIGPlus_renaming_templated_types_namespaces"></a>6.20 Renaming templated types in namespaces</H2>
+
+
+<p>
+As has been mentioned, when %rename includes parameters, the parameter types must match exactly (no typedef or namespace resolution is performed).
+SWIG treats templated types slightly differently and has an additional matching rule so unlike non-templated types, an exact match is not always required.
+If the fully qualified templated type is specified, it will have a higher precedence over the generic template type.
+In the example below, the generic template type is used to rename to <tt>bbb</tt> and the fully qualified type is used to rename to <tt>ccc</tt>.
+</p>
+
+<div class="code">
+<pre>
+%rename(bbb) Space::ABC::aaa(T t);                       // will match but with lower precedence than ccc
+%rename(ccc) Space::ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
+
+namespace Space {
+  class XYZ {};
+  template&lt;typename T&gt; struct ABC {
+    void aaa(T t) {}
+  };
+}
+%template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
+</pre>
+</div>
+
+<p>
+It should now be apparent that there are many ways to achieve a renaming with %rename. This is demonstrated
+by the following two examples, which are effectively the same as the above example.
+Below shows how %rename can be placed inside a namespace.
+</p>
+
+<div class="code">
+<pre>
+namespace Space {
+  %rename(bbb) ABC::aaa(T t);                       // will match but with lower precedence than ccc
+  %rename(ccc) ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
+  %rename(ddd) ABC&lt;Space::XYZ&gt;::aaa(XYZ t);         // will not match
+}
+
+namespace Space {
+  class XYZ {};
+  template&lt;typename T&gt; struct ABC {
+    void aaa(T t) {}
+  };
+}
+%template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
+</pre>
+</div>
+
+<p>
+Note that <tt>ddd</tt> does not match as there is no namespace resolution for parameter types and the fully qualified type must be specified for template type expansion.
+The following example shows how %rename can be placed within %extend.
+</p>
+
+<div class="code">
+<pre>
+namespace Space {
+  %extend ABC {
+    %rename(bbb) aaa(T t);           // will match but with lower precedence than ccc
+  }
+  %extend ABC&lt;Space::XYZ&gt; {
+    %rename(ccc) aaa(Space::XYZ t);  // will match but with higher precedence than bbb
+    %rename(ddd) aaa(XYZ t);         // will not match
+  }
+}
+
+namespace Space {
+  class XYZ {};
+  template&lt;typename T&gt; struct ABC {
+    void aaa(T t) {}
+  };
+}
+%template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
+</pre>
+</div>
+
+
+<H2><a name="SWIGPlus_exception_specifications"></a>6.21 Exception specifications</H2>
+
+
+<p>
+When C++ programs utilize exceptions, exceptional behavior is sometimes specified as
+part of a function or method declaration.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Error { };
+
+class Foo {
+public:
+    ...
+    void blah() throw(Error);
+    ...
+};
+</pre>
+</div>
+
+<p>
+If an exception specification is used, SWIG automatically generates
+wrapper code for catching the indicated exception and, when possible,
+rethrowing it into the target language, or converting it into an error
+in the target language otherwise. For example, in Python, you can
+write code like this:
+</p>
+
+<div class="targetlang">
+<pre>
+f = Foo()
+try:
+    f.blah()
+except Error,e:
+     # e is a wrapped instance of "Error"
+</pre>
+</div>
+
+<p>
+Details of how to tailor code for handling the caught C++ exception and converting it into the target language's exception/error handling mechanism
+is outlined in the <a href="Typemaps.html#throws_typemap">"throws" typemap</a> section.
+</p>
+
+<p>
+Since exception specifications are sometimes only used sparingly, this alone may not be enough to
+properly handle C++ exceptions. To do that, a different set of special SWIG directives are used.
+Consult the "<a href="Customization.html#exception">Exception handling with %exception</a>" section for details.
+The next section details a way of simulating an exception specification or replacing an existing one.
+</p>
+
+<H2><a name="SWIGPlus_catches"></a>6.22 Exception handling with %catches</H2>
+
+
+<p>
+Exceptions are automatically handled for methods with an exception specification.
+Similar handling can be achieved for methods without exception specifications through the <tt>%catches</tt> feature.
+It is also possible to replace any declared exception specification using the <tt>%catches</tt> feature.
+In fact, <tt>%catches</tt> uses the same <a href="Typemaps.html#throws_typemap">"throws" typemaps</a> that SWIG uses for exception specifications in handling exceptions.
+The <tt>%catches</tt> feature must contain a list of possible types that can be thrown.
+For each type that is in the list, SWIG will generate a catch handler, in the same way that it would for types declared in the exception specification.
+Note that the list can also include the catch all specification "...".
+For example,
+</p>
+
+<div class="code">
+<pre>
+struct EBase { virtual ~EBase(); };
+struct Error1 : EBase { };
+struct Error2 : EBase { };
+struct Error3 : EBase { };
+struct Error4 : EBase { };
+
+%catches(Error1,Error2,...) Foo::bar();
+%catches(EBase) Foo::blah();
+
+class Foo {
+public:
+    ...
+    void bar();
+    void blah() throw(Error1,Error2,Error3,Error4);
+    ...
+};
+</pre>
+</div>
+
+<p>
+For the <tt>Foo::bar()</tt> method, which can throw anything,
+SWIG will generate catch handlers for <tt>Error1</tt>, <tt>Error2</tt> as well as a catch all handler (...).
+Each catch handler will convert the caught exception and convert it into a target language error/exception.
+The catch all handler will convert the caught exception into an unknown error/exception.
+</p>
+
+<p>
+Without the <tt>%catches</tt> feature being attached to <tt>Foo::blah()</tt>,
+SWIG will generate catch handlers for all of the types in the exception specification, that is, <tt>Error1, Error2, Error3, Error4</tt>.
+However, with the <tt>%catches</tt> feature above,
+just a single catch handler for the base class, <tt>EBase</tt> will be generated to convert the C++ exception into a target language error/exception.
+</p>
+
+
+<H2><a name="SWIGPlus_nn33"></a>6.23 Pointers to Members</H2>
+
+
+<p>
+Starting with SWIG-1.3.7, there is limited parsing support for pointers to C++ class members.
+For example:
+</p>
+
+<div class="code">
+<pre>
+double do_op(Object *o, double (Object::*callback)(double,double));
+extern double (Object::*fooptr)(double,double);
+%constant double (Object::*FOO)(double,double) = &amp;Object::foo;
+</pre>
+</div>
+
+<p>
+Although these kinds of pointers can be parsed and represented by the
+SWIG type system, few language modules know how to handle them due to
+implementation differences from standard C pointers.  Readers are
+<em>strongly</em> advised to consult an advanced text such as the "The
+Annotated C++ Manual" for specific details.
+</p>
+
+<p>
+When pointers to members are supported, the pointer value might appear as a special
+string like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; print example.FOO
+_ff0d54a800000000_m_Object__f_double_double__double
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+In this case, the hexadecimal digits represent the entire value of the
+pointer which is usually the contents of a small C++ structure on most
+machines.
+</p>
+
+<p>
+SWIG's type-checking mechanism is also more limited when working with
+member pointers.  Normally SWIG tries to keep track of inheritance
+when checking types.  However, no such support is currently provided
+for member pointers.
+</p>
+
+<H2><a name="SWIGPlus_nn34"></a>6.24 Smart pointers and operator-&gt;()</H2>
+
+
+<p>
+In some C++ programs, objects are often encapsulated by smart-pointers
+or proxy classes.   This is sometimes done to implement automatic memory management (reference counting) or
+persistence. Typically a smart-pointer is defined by a template class where
+the <tt>-&gt;</tt> operator has been overloaded.  This class is then wrapped
+around some other class.  For example:
+</p>
+
+<div class="code">
+<pre>
+// Smart-pointer class
+template&lt;class T&gt; class SmartPtr {
+    T *pointee;
+public:
+    ...
+    T *operator-&gt;() {
+        return pointee;
+    }
+    ...
+};
+
+// Ordinary class
+class Foo_Impl {
+public:
+    int x;
+    virtual void bar();
+    ...
+};
+
+// Smart-pointer wrapper
+typedef SmartPtr&lt;Foo_Impl&gt; Foo;
+
+// Create smart pointer Foo
+Foo make_Foo() {
+    return SmartPtr(new Foo_Impl());
+}
+
+// Do something with smart pointer Foo
+void do_something(Foo f) {
+    printf("x = %d\n", f-&gt;x);
+    f-&gt;bar();
+}
+</pre>
+</div>
+
+<p>
+A key feature of this approach is that by defining
+<tt>operator-&gt;</tt> the methods and attributes of the object
+wrapped by a smart pointer are transparently accessible.  For example,
+expressions such as these (from the previous example),
+</p>
+
+<div class="code">
+<pre>
+f-&gt;x
+f-&gt;bar()
+</pre>
+</div>
+
+<p>
+are transparently mapped to the following
+</p>
+
+<div class="code">
+<pre>
+(f.operator-&gt;())-&gt;x;
+(f.operator-&gt;())-&gt;bar();
+</pre>
+</div>
+
+<p>
+When generating wrappers, SWIG tries to emulate this functionality to
+the extent that it is possible.  To do this, whenever
+<tt>operator-&gt;()</tt> is encountered in a class, SWIG looks at its
+returned type and uses it to generate wrappers for accessing
+attributes of the underlying object.  For example, wrapping the above
+code produces wrappers like this:
+</p>
+
+<div class="code">
+<pre>
+int Foo_x_get(Foo *f) {
+   return (*f)-&gt;x;
+}
+void Foo_x_set(Foo *f, int value) {
+   (*f)-&gt;x = value;
+}
+void Foo_bar(Foo *f) {
+   (*f)-&gt;bar();
+}
+</pre>
+</div>
+
+<p>
+These wrappers take a smart-pointer instance as an argument, but
+dereference it in a way to gain access to the object returned by
+<tt>operator-&gt;()</tt>.  You should carefully compare these wrappers
+to those in the first part of this chapter (they are slightly
+different).
+</p>
+
+<p>
+The end result is that access looks very similar to C++.  For
+example, you could do this in Python:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = make_Foo()
+&gt;&gt;&gt; print f.x
+0
+&gt;&gt;&gt; f.bar()
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+When generating wrappers through a smart-pointer, SWIG tries to
+generate wrappers for all methods and attributes that might be
+accessible through <tt>operator-&gt;()</tt>.  This includes any methods
+that might be accessible through inheritance.   However, there are a number of restrictions:
+</p>
+
+<ul>
+<li>Member variables and methods are wrapped through a smart
+pointer. Enumerations, constructors, and destructors are not wrapped.
+</li>
+
+<li><p>If the smart-pointer class and the underlying object both define a method or
+variable of the same name, then the smart-pointer version has precedence.   For
+example, if you have this code</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    int x;
+};
+
+class Bar {
+public:
+    int x;       
+    Foo *operator-&gt;();
+};
+</pre>
+</div>
+
+<p>
+then the wrapper for <tt>Bar::x</tt> accesses the <tt>x</tt> defined in <tt>Bar</tt>, and 
+not the <tt>x</tt> defined in <tt>Foo</tt>.</p>
+</li>
+</ul>
+
+<p>
+If your intent is to only expose the smart-pointer class in the interface, it is not necessary to wrap both
+the smart-pointer class and the class for the underlying object.  However, you must still tell SWIG about both
+classes if you want the technique described in this section to work.   To only generate wrappers for the
+smart-pointer class, you can use the %ignore directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%ignore Foo;
+class Foo {       // Ignored
+};
+
+class Bar {
+public:
+   Foo *operator-&gt;();
+   ...
+};
+</pre>
+</div>
+
+<p>
+Alternatively, you can import the definition of <tt>Foo</tt> from a separate file using
+<tt>%import</tt>.
+</p>
+ 
+<p>
+<b>Note:</b> When a class defines <tt>operator-&gt;()</tt>, the operator itself is wrapped
+as a method <tt>__deref__()</tt>.  For example:
+</p>
+
+<div class="targetlang">
+<pre>
+f = Foo()               # Smart-pointer
+p = f.__deref__()       # Raw pointer from operator-&gt;
+</pre>
+</div>
+
+<p>
+<b>Note:</b> To disable the smart-pointer behavior, use <tt>%ignore</tt> to ignore
+<tt>operator-&gt;()</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%ignore Bar::operator-&gt;;
+</pre>
+</div>
+
+<p>
+<b>Note:</b> Smart pointer support was first added in SWIG-1.3.14.
+</p>
+
+
+<H2><a name="SWIGPlus_nn35"></a>6.25 Using declarations and inheritance</H2>
+
+
+<p>
+<tt>using</tt> declarations are sometimes used to adjust access to members of
+base classes.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+      int  blah(int x);
+};
+
+class Bar {
+public:
+      double blah(double x);
+};
+
+class FooBar : public Foo, public Bar {
+public:
+      using Foo::blah;  
+      using Bar::blah;
+      char *blah(const char *x);
+};
+</pre>
+</div>
+
+<p>
+In this example, the <tt>using</tt> declarations make different
+versions of the overloaded <tt>blah()</tt> method accessible from the
+derived class.  For example:
+</p>
+
+<div class="code">
+<pre>
+FooBar *f;
+f-&gt;blah(3);         // Ok. Invokes Foo::blah(int)
+f-&gt;blah(3.5);       // Ok. Invokes Bar::blah(double)
+f-&gt;blah("hello");   // Ok. Invokes FooBar::blah(const char *);
+</pre>
+</div>
+
+<p>
+SWIG emulates the same functionality when creating wrappers.  For example, if
+you wrap this code in Python, the module works just like you would expect:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; f = example.FooBar()
+&gt;&gt;&gt; f.blah(3)
+&gt;&gt;&gt; f.blah(3.5)
+&gt;&gt;&gt; f.blah("hello")
+</pre>
+</div>
+
+<p>
+<tt>using</tt> declarations can also be used to change access when applicable.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+protected:
+    int x;
+    int blah(int x);
+};
+
+class Bar : public Foo {
+public:
+    using Foo::x;       // Make x public
+    using Foo::blah;    // Make blah public
+};
+</pre>
+</div>
+
+<p>
+This also works in SWIG---the exposed declarations will be wrapped normally.
+</p>
+
+<p>
+When <tt>using</tt> declarations are used as shown in these examples, declarations
+from the base classes are copied into the derived class and wrapped normally.  When
+copied, the declarations retain any properties that might have been attached using
+<tt>%rename</tt>, <tt>%ignore</tt>, or <tt>%feature</tt>.  Thus, if a method is
+ignored in a base class, it will also be ignored by a <tt>using</tt> declaration.
+</p>
+
+<p>
+Because a <tt>using</tt> declaration does not provide fine-grained
+control over the declarations that get imported, it may be difficult
+to manage such declarations in applications that make heavy use of
+SWIG customization features.  If you can't get <tt>using</tt> to work
+correctly, you can always change the interface to the following:
+</p>
+
+<div class="code">
+<pre>
+
+class FooBar : public Foo, public Bar {
+public:
+#ifndef SWIG
+      using Foo::blah;  
+      using Bar::blah;
+#else
+      int blah(int x);         // explicitly tell SWIG about other declarations
+      double blah(double x);
+#endif
+
+      char *blah(const char *x);
+};
+</pre>
+</div>
+
+<p>
+<b>Notes:</b>
+</p>
+
+<ul>
+<li><p>If a derived class redefines a method defined in a base class, then a <tt>using</tt> declaration
+won't cause a conflict.  For example:</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+       int blah(int );
+       double blah(double);
+};
+
+class Bar : public Foo {
+public:
+       using Foo::blah;    // Only imports blah(double);
+       int blah(int);
+};
+</pre>
+</div>
+
+<li><p>Resolving ambiguity in overloading may prevent declarations from being
+imported by <tt>using</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(blah_long) Foo::blah(long);
+class Foo {
+public:
+     int blah(int);
+     long blah(long);  // Renamed to blah_long
+};
+
+class Bar : public Foo {
+public:
+     using Foo::blah;     // Only imports blah(int)
+     double blah(double x);
+};
+</pre>
+</div>
+</ul>
+
+<H2><a name="SWIGPlus_nested_classes"></a>6.26 Nested classes</H2>
+
+
+<p>
+There is limited support for nested structs and unions when wrapping C code, see <a href="SWIG.html#SWIG_nested_structs">Nested structures</a> for further details.
+However, there is no nested class/struct/union support when wrapping C++ code (using the -c++ commandline option).
+This may be added at a future date, however, until then some of the following workarounds can be applied.
+</p>
+
+<p>
+It might be possible to use partial class information.  Since
+SWIG does not need the entire class specification to work, conditional
+compilation can be used to comment out the problematic nested class definition, you might do this:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+#ifndef SWIG
+   class Bar {
+   public:
+     ...
+   };
+#endif
+   Foo();
+  ~Foo();
+   ...
+};
+</pre>
+</div>
+
+<p>
+The next workaround assumes you cannot modify the source code as was done above and it provides a solution for methods that use nested class types.
+Imagine we are wrapping the <tt>Outer</tt> class which contains a nested class <tt>Inner</tt>:
+</p>
+
+<div class="code">
+<pre>
+// File outer.h
+class Outer {
+public:
+  class Inner {
+    public:
+      int var;
+      Inner(int v = 0) : var(v) {}
+  };
+  void method(Inner inner);
+};
+</pre>
+</div>
+
+<p>
+The following interface file works around SWIG nested class limitations by redefining the nested class as a global class.
+A typedef for the compiler is also required in order for the generated wrappers to compile.
+</p>
+
+<div class="code">
+<pre>
+// File : example.i
+%module example
+
+// Suppress SWIG warning
+#pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
+
+// Redefine nested class in global scope in order for SWIG to generate
+// a proxy class. Only SWIG parses this definition.
+class Inner {
+  public:
+    int var;
+    Inner(int v = 0) : var(v) {}
+};
+
+%{
+#include "outer.h"
+%}
+%include "outer.h"
+
+%{
+// SWIG thinks that Inner is a global class, so we need to trick the C++
+// compiler into understanding this so called global type.
+typedef Outer::Inner Inner;
+%}
+
+</pre>
+</div>
+
+<p>
+The downside to this approach is having to maintain two definitions of <tt>Inner</tt>, the real one and the one in the interface file that SWIG parses.
+</p>
+
+<H2><a name="SWIGPlus_nn37"></a>6.27 A brief rant about const-correctness</H2>
+
+
+<p>
+A common issue when working with C++ programs is dealing with all
+possible ways in which the <tt>const</tt> qualifier (or lack thereof)
+will break your program, all programs linked against your program, and
+all programs linked against those programs.  
+</p>
+
+<p>
+Although SWIG knows how to correctly deal with <tt>const</tt> in its
+internal type system and it knows how to generate wrappers that are
+free of const-related warnings, SWIG does not make any attempt to preserve 
+const-correctness in the target language.  Thus, it is possible to
+pass <tt>const</tt> qualified objects to non-const methods and functions.
+For example, consider the following code in C++:
+</p>
+
+<div class="code">
+<pre>
+const Object * foo();
+void bar(Object *);
+
+...
+// C++ code
+void blah() {
+   bar(foo());         // Error: bar discards const
+};
+</pre>
+</div>
+
+<p>
+Now, consider the behavior when wrapped into a Python module:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; bar(foo())         # Okay
+&gt;&gt;&gt; 
+</pre>
+</div>
+
+<p>
+Although this is clearly a violation of the C++ type-system, fixing
+the problem doesn't seem to be worth the added implementation
+complexity that would be required to support it in the SWIG run-time type
+system.  There are no plans to change this in future releases
+(although we'll never rule anything out entirely).
+</p>
+
+<p>
+The bottom line is that this particular issue does not appear to be a problem
+for most SWIG projects.    Of course, you might want to consider
+using another tool if maintaining constness is the most important part
+of your project.
+</p>
+
+<H2><a name="SWIGPlus_nn42"></a>6.28 Where to go for more information</H2>
+
+
+<p>
+If you're wrapping serious C++ code, you might want to pick up a copy
+of "The Annotated C++ Reference Manual" by Ellis and Stroustrup.  This
+is the reference document we use to guide a lot of SWIG's C++ support.
+</p>
+
+</body>
+</html>
+
+<!--  LocalWords:  destructors Enums Namespaces const SWIG's STL OO adaptor tcl
+ -->
+<!--  LocalWords:  debuggable cxx OBJS Wiki accessor nodefault makedefault
+ -->
+<!--  LocalWords:  notabstract CopyFoo
+ -->
diff --git a/trunk/Doc/Manual/Scripting.html b/trunk/Doc/Manual/Scripting.html
new file mode 100644
index 0000000..e6a2eee
--- /dev/null
+++ b/trunk/Doc/Manual/Scripting.html
@@ -0,0 +1,474 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Scripting Languages</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Scripting"></a>4 Scripting Languages</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Scripting_nn2">The two language view of the world</a>
+<li><a href="#Scripting_nn3">How does a scripting language talk to C?</a>
+<ul>
+<li><a href="#Scripting_nn4">Wrapper functions</a>
+<li><a href="#Scripting_nn5">Variable linking</a>
+<li><a href="#Scripting_nn6">Constants</a>
+<li><a href="#Scripting_nn7">Structures and classes</a>
+<li><a href="#Scripting_nn8">Proxy classes</a>
+</ul>
+<li><a href="#Scripting_nn9">Building scripting language extensions</a>
+<ul>
+<li><a href="#Scripting_nn10">Shared libraries and dynamic loading</a>
+<li><a href="#Scripting_nn11">Linking with shared libraries</a>
+<li><a href="#Scripting_nn12">Static linking</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter provides a brief overview of scripting language extension
+programming and the mechanisms by which scripting language interpreters
+access C and C++ code.
+</p>
+
+<H2><a name="Scripting_nn2"></a>4.1 The two language view of the world</H2>
+
+
+<p>
+When a scripting language is used to control a C program, the
+resulting system tends to look as follows:
+</p>
+
+<center><img src="ch2.1.png" alt="Scripting language input - C/C++ functions output"></center>
+
+<p>
+In this programming model, the scripting language interpreter is used
+for high level control whereas the underlying functionality of the
+C/C++ program is accessed through special scripting language
+"commands."  If you have ever tried to write your own simple command
+interpreter, you might view the scripting language approach
+to be a highly advanced implementation of that.  Likewise, 
+If you have ever used a package such as MATLAB or IDL, it is a
+very similar model--the interpreter executes user commands and
+scripts.  However, most of the underlying functionality is written in
+a low-level language like C or Fortran.
+</p>
+
+<p>
+The two-language model of computing is extremely powerful because it
+exploits the strengths of each language. C/C++ can be used for maximal
+performance and complicated systems programming tasks. Scripting
+languages can be used for rapid prototyping, interactive debugging,
+scripting, and access to high-level data structures such associative
+arrays. </p>
+
+<H2><a name="Scripting_nn3"></a>4.2 How does a scripting language talk to C?</H2>
+
+
+<p>
+Scripting languages are built around a parser that knows how
+to execute commands and scripts.  Within this parser, there is a
+mechanism for executing commands and accessing variables.
+Normally, this is used to implement the builtin features
+of the language.  However, by extending the interpreter, it is usually 
+possible to add new commands and variables.   To do this,
+most languages define a special API for adding new commands.
+Furthermore, a special foreign function interface defines how these
+new commands are supposed to hook into the interpreter.
+</p>
+
+<p>
+Typically, when you add a new command to a scripting interpreter
+you need to do two things; first you need to write a special
+"wrapper" function that serves as the glue between the interpreter
+and the underlying C function.  Then you need to give the interpreter
+information about the wrapper by providing details about the name of the
+function, arguments, and so forth.  The next few sections illustrate
+the process.
+</p>
+
+<H3><a name="Scripting_nn4"></a>4.2.1 Wrapper functions</H3>
+
+
+<p>
+Suppose you have an ordinary C function like this :</p>
+
+<div class="code"><pre>
+int fact(int n) {
+	if (n &lt;= 1) return 1;
+	else return n*fact(n-1);
+}
+</pre></div>
+
+<p>
+In order to access this function from a scripting language, it is
+necessary to write a special "wrapper" function that serves as the
+glue between the scripting language and the underlying C function. A
+wrapper function must do three things :</p>
+
+<ul>
+<li>Gather function arguments and make sure they are valid.
+<li>Call the C function.
+<li>Convert the return value into a form recognized by the scripting language.
+</ul>
+
+<p>
+As an example, the Tcl wrapper function for the <tt>fact()</tt>
+function above example might look like the following : </p>
+
+<div class="code"><pre>
+int wrap_fact(ClientData clientData, Tcl_Interp *interp,
+		int argc, char *argv[]) {
+	int result;
+	int arg0;
+	if (argc != 2) {
+		interp-&gt;result = "wrong # args";
+		return TCL_ERROR;
+	}
+	arg0 = atoi(argv[1]);
+	result = fact(arg0);
+	sprintf(interp-&gt;result,"%d", result);
+	return TCL_OK;
+}
+
+</pre></div>
+
+<p>
+Once you have created a wrapper function, the final step is to tell the
+scripting language about the new function. This is usually done in an
+initialization function called by the language when the module is
+loaded. For example, adding the above function to the Tcl interpreter
+requires code like the following :</p>
+
+<div class="code"><pre>
+int Wrap_Init(Tcl_Interp *interp) {
+	Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL,
+				(Tcl_CmdDeleteProc *) NULL);
+	return TCL_OK;
+}
+</pre></div>
+
+<p>
+When executed, Tcl will now have a new command called "<tt>fact</tt>"
+that you can use like any other Tcl command.</p>
+
+<p>
+Although the process of adding a new function to Tcl has been
+illustrated, the procedure is almost identical for Perl and
+Python. Both require special wrappers to be written and both need
+additional initialization code. Only the specific details are
+different.</p>
+
+<H3><a name="Scripting_nn5"></a>4.2.2 Variable linking</H3>
+
+
+<p>
+Variable linking refers to the problem of mapping a 
+C/C++ global variable to a variable in the scripting
+language interpreter. For example, suppose you had the following
+variable:</p>
+
+<div class="code"><pre>
+double Foo = 3.5;
+</pre></div>
+
+<p>
+It might be nice to access it from a script as follows (shown for Perl):</p>
+
+<div class="targetlang"><pre>
+$a = $Foo * 2.3;   # Evaluation
+$Foo = $a + 2.0;   # Assignment
+</pre></div>
+
+<p>
+To provide such access, variables are commonly manipulated using a
+pair of get/set functions.  For example, whenever the value of a
+variable is read, a "get" function is invoked.  Similarly, whenever
+the value of a variable is changed, a "set" function is called.
+</p>
+
+<p>
+In many languages, calls to the get/set functions can be attached to
+evaluation and assignment operators.  Therefore, evaluating a variable
+such as <tt>$Foo</tt> might implicitly call the get function.  Similarly, 
+typing <tt>$Foo = 4</tt> would call the underlying set function to change
+the value.
+</p>
+
+<H3><a name="Scripting_nn6"></a>4.2.3 Constants</H3>
+
+
+<p>
+In many cases, a C program or library may define a large collection of
+constants.  For example:
+</p>
+
+<div class="code"><pre>
+#define RED   0xff0000
+#define BLUE  0x0000ff
+#define GREEN 0x00ff00
+</pre></div>
+<p>
+To make constants available, their values can be stored in scripting
+language variables such as <tt>$RED</tt>, <tt>$BLUE</tt>, and
+<tt>$GREEN</tt>.  Virtually all scripting languages provide C
+functions for creating variables so installing constants is usually
+a trivial exercise.
+</p>
+
+<H3><a name="Scripting_nn7"></a>4.2.4 Structures and classes</H3>
+
+
+<p>
+Although scripting languages have no trouble accessing simple
+functions and variables, accessing C/C++ structures and classes
+present a different problem.  This is because the implementation
+of structures is largely related to the problem of 
+data representation and layout.  Furthermore, certain language features
+are difficult to map to an interpreter.  For instance, what
+does C++ inheritance mean in a Perl interface?
+</p>
+
+<p>
+The most straightforward technique for handling structures is to
+implement a collection of accessor functions that hide the underlying
+representation of a structure.  For example, 
+</p>
+
+<div class="code"><pre>
+struct Vector {
+	Vector();
+	~Vector();
+	double x,y,z;
+};
+
+</pre></div>
+
+<p>
+can be transformed into the following set of functions :
+</p>
+
+<div class="code"><pre>
+Vector *new_Vector();
+void delete_Vector(Vector *v);
+double Vector_x_get(Vector *v);
+double Vector_y_get(Vector *v);
+double Vector_z_get(Vector *v);
+void Vector_x_set(Vector *v, double x);
+void Vector_y_set(Vector *v, double y);
+void Vector_z_set(Vector *v, double z);
+
+</pre></div>
+<p>
+Now, from an interpreter these function might be used as follows:
+</p>
+
+<div class="targetlang"><pre>
+% set v [new_Vector]
+% Vector_x_set $v 3.5
+% Vector_y_get $v
+% delete_Vector $v
+% ...
+</pre></div>
+
+<p>
+Since accessor functions provide a mechanism for accessing the
+internals of an object, the interpreter does not need to know anything
+about the actual representation of a <tt>Vector</tt>.
+</p>
+
+<H3><a name="Scripting_nn8"></a>4.2.5 Proxy classes</H3>
+
+
+<p>
+In certain cases, it is possible to use the low-level accessor functions
+to create a proxy class, also known as a shadow class.
+A proxy class is a special kind of object that gets created
+in a scripting language to access a C/C++ class (or struct) in a way
+that looks like the original structure (that is, it proxies the real
+C++ class). For example, if you
+have the following C definition :</p>
+
+<div class="code"><pre>
+class Vector {
+public:
+	Vector();
+	~Vector();
+	double x,y,z;
+};
+</pre></div>
+
+<p>
+A proxy classing mechanism would allow you to access the structure in
+a more natural manner from the interpreter. For example, in Python, you might want to do this:
+</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; v = Vector()
+&gt;&gt;&gt; v.x = 3
+&gt;&gt;&gt; v.y = 4
+&gt;&gt;&gt; v.z = -13
+&gt;&gt;&gt; ...
+&gt;&gt;&gt; del v
+</pre></div>
+
+<p>
+Similarly, in Perl5 you may want the interface to work like this:</p>
+
+<div class="targetlang"><pre>
+$v = new Vector;
+$v-&gt;{x} = 3;
+$v-&gt;{y} = 4;
+$v-&gt;{z} = -13;
+
+</pre></div>
+<p>
+Finally, in Tcl :
+</p>
+
+<div class="targetlang"><pre>
+Vector v
+v configure -x 3 -y 4 -z 13
+
+</pre></div>
+
+<p>
+When proxy classes are used, two objects are at really work--one in
+the scripting language, and an underlying C/C++ object. Operations
+affect both objects equally and for all practical purposes, it appears
+as if you are simply manipulating a C/C++ object. 
+</p>
+
+<H2><a name="Scripting_nn9"></a>4.3 Building scripting language extensions</H2>
+
+
+<p>
+The final step in using a scripting language with your C/C++
+application is adding your extensions to the scripting language
+itself. There are two primary approaches for doing
+this. The preferred technique is to build a dynamically loadable
+extension in the form a shared library.  Alternatively, you can
+recompile the scripting language interpreter with your extensions
+added to it.
+</p>
+
+<H3><a name="Scripting_nn10"></a>4.3.1 Shared libraries and dynamic loading</H3>
+
+
+<p>
+To create a shared library or DLL, you often need to look at the
+manual pages for your compiler and linker.  However, the procedure
+for a few common machines is shown below:</p>
+
+<div class="shell"><pre>
+# Build a shared library for Solaris
+gcc -c example.c example_wrap.c -I/usr/local/include
+ld -G example.o example_wrap.o -o example.so
+
+# Build a shared library for Linux
+gcc -fpic -c example.c example_wrap.c -I/usr/local/include
+gcc -shared example.o example_wrap.o -o example.so
+
+# Build a shared library for Irix
+gcc -c example.c example_wrap.c -I/usr/local/include
+ld -shared example.o example_wrap.o -o example.so
+
+</pre></div>
+
+<p>
+To use your shared library, you simply use the corresponding command
+in the scripting language (load, import, use, etc...). This will
+import your module and allow you to start using it. For example:
+</p>
+
+<div class="targetlang"><pre>
+% load ./example.so
+% fact 4
+24
+%
+</pre></div>
+
+<p>
+When working with C++ codes, the process of building shared libraries
+may be more complicated--primarily due to the fact that C++ modules may need
+additional code in order to operate correctly. On many machines, you
+can build a shared C++ module by following the above procedures, but
+changing the link line to the following :</p>
+
+<div class="shell"><pre>
+c++ -shared example.o example_wrap.o -o example.so
+</pre></div>
+
+<H3><a name="Scripting_nn11"></a>4.3.2 Linking with shared libraries</H3>
+
+
+<p>
+When building extensions as shared libraries, it is not uncommon for
+your extension to rely upon other shared libraries on your machine. In
+order for the extension to work, it needs to be able to find all of
+these libraries at run-time. Otherwise, you may get an error such as
+the following :</p>
+
+<div class="targetlang"><pre>
+&gt;&gt;&gt; import graph
+Traceback (innermost last):
+  File "&lt;stdin&gt;", line 1, in ?
+  File "/home/sci/data1/beazley/graph/graph.py", line 2, in ?
+    import graphc
+ImportError:  1101:/home/sci/data1/beazley/bin/python: rld: Fatal Error: cannot 
+successfully map soname 'libgraph.so' under any of the filenames /usr/lib/libgraph.so:/
+lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so:
+&gt;&gt;&gt;
+</pre></div>
+<p>
+
+What this error means is that the extension module created by SWIG
+depends upon a shared library called "<tt>libgraph.so</tt>" that the
+system was unable to locate. To fix this problem, there are a few
+approaches you can take.</p>
+
+<ul>
+<li>Link your extension and explicitly tell the linker where the
+required libraries are located. Often times, this can be done with a
+special linker flag such as <tt>-R</tt>, <tt>-rpath</tt>, etc. This
+is not implemented in a standard manner so read the man pages for your
+linker to find out more about how to set the search path for shared
+libraries.
+
+<li>Put shared libraries in the same directory as the executable. This
+technique is sometimes required for correct operation on non-Unix
+platforms.
+
+<li>Set the UNIX environment variable <tt>LD_LIBRARY_PATH</tt> to the
+directory where shared libraries are located before running Python.
+Although this is an easy solution, it is not recommended.  Consider setting
+the path using linker options instead.
+
+</ul>
+
+<H3><a name="Scripting_nn12"></a>4.3.3 Static linking</H3>
+
+
+<p>
+With static linking, you rebuild the scripting language interpreter
+with extensions. The process usually involves compiling a short main
+program that adds your customized commands to the language and starts
+the interpreter.  You then link your program with a library to produce
+a new scripting language executable.
+</p>
+
+<p>
+Although static linking is supported on all platforms, this is not
+the preferred technique for building scripting language
+extensions.  In fact, there are very few practical reasons for doing this--consider
+using shared libraries instead.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Sections.html b/trunk/Doc/Manual/Sections.html
new file mode 100644
index 0000000..9f235b6
--- /dev/null
+++ b/trunk/Doc/Manual/Sections.html
@@ -0,0 +1,85 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG-1.3 Documentation</title>
+</head>
+<body bgcolor="#ffffff">
+<H1><a name="Sections"></a>SWIG-1.3 Development Documentation</H1>
+
+Last update : SWIG-1.3.36 (24 June 2008)
+
+<H2>Sections</H2>
+
+<p>
+The SWIG documentation is being updated to reflect new SWIG
+features and enhancements.  However, this update process is not quite
+finished--there is a lot of old SWIG-1.1 documentation and it is taking
+some time to update all of it.  Please pardon our dust (or volunteer
+to help!).
+</p>
+
+<H3>SWIG Core Documentation</H3>
+<ul>
+<li><a href="Preface.html#Preface">Preface</a></li>
+<li><a href="Introduction.html#Introduction">Introduction</a></li>
+<li><a href="Windows.html#Windows">Getting started on Windows</a></li>
+<li><a href="Scripting.html#Scripting">Scripting</a></li>
+<li><a href="SWIG.html#SWIG">SWIG Basics</a> (Read this!)</li>
+<li><a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a></li>
+<li><a href="Preprocessor.html#Preprocessor">The SWIG preprocessor</a></li>
+<li><a href="Library.html#Library">The SWIG Library</a></li>
+<li><a href="Arguments.html#Arguments">Argument handling</a></li>
+<li><a href="Typemaps.html#Typemaps">Typemaps</a></li>
+<li><a href="Customization.html#Customization">Customization features</a></li>
+<li><a href="Contract.html#Contract">Contracts</a></li>
+<li><a href="Varargs.html#Varargs">Variable length arguments</a></li>
+<li><a href="Warnings.html#Warnings">Warning messages</a></li>
+<li><a href="Modules.html#Modules">Working with Modules</a></li>
+</ul>
+
+<H3>Language Module Documentation</H3>
+
+<ul>
+<li><a href="Allegrocl.html#Allegrocl_nn1">Allegro CL support</a></li>
+<li><a href="CSharp.html#CSharp">C# support</a></li>
+<li><a href="Chicken.html#Chicken">Chicken support</a></li>
+<li><a href="Guile.html#Guile">Guile support</a></li>
+<li><a href="Java.html#Java">Java support</a></li>
+<li><a href="Lua.html#Lua_nn1">Lua support</a></li>
+<li><a href="Lisp.html#Lisp_nn1">Common Lisp support</a></li>
+<li><a href="Modula3.html#Modula3">Modula3 support</a></li>
+<li><a href="Mzscheme.html#MzScheme">MzScheme support</a></li>
+<li><a href="Ocaml.html#Ocaml">Ocaml support</a></li>
+<li><a href="Octave.html#Octave">Octave support</a></li>
+<li><a href="Perl5.html#Perl5">Perl5 support</a></li>
+<li><a href="Php.html#Php">PHP support</a></li>
+<li><a href="Pike.html#Pike">Pike support</a></li>
+<li><a href="Python.html#Python">Python support</a></li>
+<li><a href="Ruby.html#Ruby">Ruby support</a></li>
+<li><a href="R.html#R">R support</a></li>
+<li><a href="Tcl.html#Tcl">Tcl support</a></li>
+</ul>
+
+<H3>Developer Documentation</H3>
+
+<ul>
+<li><a href="Extending.html#Extending">Extending SWIG</a></li>
+</ul>
+
+<H3>Documentation that has not yet been updated</H3>
+
+<p>
+This documentation has not been completely updated from SWIG-1.1, but most of the topics
+still apply to the current release.  Make sure you read the
+<a href="SWIG.html#SWIG">SWIG Basics</a> chapter before reading
+any of these chapters.  Also, SWIG-1.3.10 features extensive changes to the 
+implementation of typemaps.   Make sure you read the <a href="Typemaps.html#Typemaps">Typemaps</a> 
+chapter above if you are using this feature.
+</p>
+
+<ul>
+<li><a href="Advanced.html#Advanced">Advanced topics</a>  (see <a href="Modules.html#Modules">Modules</a> for updated information).</li>
+</ul>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Tcl.html b/trunk/Doc/Manual/Tcl.html
new file mode 100644
index 0000000..e837a5b
--- /dev/null
+++ b/trunk/Doc/Manual/Tcl.html
@@ -0,0 +1,3413 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG and Tcl</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Tcl"></a>32 SWIG and Tcl</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Tcl_nn2">Preliminaries</a>
+<ul>
+<li><a href="#Tcl_nn3">Getting the right header files</a>
+<li><a href="#Tcl_nn4">Compiling a dynamic module</a>
+<li><a href="#Tcl_nn5">Static linking</a>
+<li><a href="#Tcl_nn6">Using your module</a>
+<li><a href="#Tcl_nn7">Compilation of C++ extensions</a>
+<li><a href="#Tcl_nn8">Compiling for 64-bit platforms</a>
+<li><a href="#Tcl_nn9">Setting a package prefix</a>
+<li><a href="#Tcl_nn10">Using namespaces</a>
+</ul>
+<li><a href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</a>
+<ul>
+<li><a href="#Tcl_nn12">Running SWIG from Developer Studio</a>
+<li><a href="#Tcl_nn13">Using NMAKE</a>
+</ul>
+<li><a href="#Tcl_nn14">A tour of basic C/C++ wrapping</a>
+<ul>
+<li><a href="#Tcl_nn15">Modules</a>
+<li><a href="#Tcl_nn16">Functions</a>
+<li><a href="#Tcl_nn17">Global variables</a>
+<li><a href="#Tcl_nn18">Constants and enums</a>
+<li><a href="#Tcl_nn19">Pointers</a>
+<li><a href="#Tcl_nn20">Structures</a>
+<li><a href="#Tcl_nn21">C++ classes</a>
+<li><a href="#Tcl_nn22">C++ inheritance</a>
+<li><a href="#Tcl_nn23">Pointers, references, values, and arrays</a>
+<li><a href="#Tcl_nn24">C++ overloaded functions</a>
+<li><a href="#Tcl_nn25">C++ operators</a>
+<li><a href="#Tcl_nn26">C++ namespaces</a>
+<li><a href="#Tcl_nn27">C++ templates</a>
+<li><a href="#Tcl_nn28">C++ Smart Pointers</a>
+</ul>
+<li><a href="#Tcl_nn29">Further details on the Tcl class interface</a>
+<ul>
+<li><a href="#Tcl_nn30">Proxy classes</a>
+<li><a href="#Tcl_nn31">Memory management</a>
+</ul>
+<li><a href="#Tcl_nn32">Input and output parameters</a>
+<li><a href="#Tcl_nn33">Exception handling </a>
+<li><a href="#Tcl_nn34">Typemaps</a>
+<ul>
+<li><a href="#Tcl_nn35">What is a typemap?</a>
+<li><a href="#Tcl_nn36">Tcl typemaps</a>
+<li><a href="#Tcl_nn37">Typemap variables</a>
+<li><a href="#Tcl_nn38">Converting  a Tcl list to a char ** </a>
+<li><a href="#Tcl_nn39">Returning values in arguments</a>
+<li><a href="#Tcl_nn40">Useful functions</a>
+<li><a href="#Tcl_nn41">Standard  typemaps</a>
+<li><a href="#Tcl_nn42">Pointer handling</a>
+</ul>
+<li><a href="#Tcl_nn43">Turning a SWIG module into a Tcl Package.</a>
+<li><a href="#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</a>
+<ul>
+<li><a href="#Tcl_nn45">Proxy classes</a>
+</ul>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+<b>Caution: This chapter is under repair!</b>
+</p>
+
+<p>
+This chapter discusses SWIG's support of Tcl. SWIG currently requires
+Tcl 8.0 or a later release.   Earlier releases of SWIG supported Tcl 7.x, but
+this is no longer supported.
+</p>
+
+<H2><a name="Tcl_nn2"></a>32.1 Preliminaries</H2>
+
+
+<p>
+To build a Tcl module, run SWIG using the <tt>-tcl</tt> option :
+</p>
+
+<div class="code"><pre>
+$ swig -tcl example.i
+</pre></div>
+
+<p>
+If building a C++ extension, add the <tt>-c++</tt> option:
+</p>
+
+<div class="code"><pre>
+$ swig -c++ -tcl example.i
+</pre></div>
+
+<p>
+This creates a file <tt>example_wrap.c</tt> or
+<tt>example_wrap.cxx</tt> that contains all of the code needed to
+build a Tcl extension module.  To finish building the module, you 
+need to compile this file and link it with the rest of your program.
+</p>
+
+<H3><a name="Tcl_nn3"></a>32.1.1 Getting the right header files</H3>
+
+
+<p>
+In order to compile the wrapper code, the compiler needs the <tt>tcl.h</tt> header file.
+This file is usually contained in the directory
+</p>
+
+<div class="code"><pre>
+/usr/local/include
+</pre></div>
+
+<p>
+Be aware that some Tcl versions install this header file with a version number attached to it.  If
+this is the case, you should probably make a symbolic link so that <tt>tcl.h</tt> points to the correct
+header file.
+</p>
+
+<H3><a name="Tcl_nn4"></a>32.1.2 Compiling a dynamic module</H3>
+
+
+<p>
+The preferred approach to building an extension module is to compile it into
+a shared object file or DLL.   To do this, you will need to compile your program
+using commands like this (shown for Linux):
+</p>
+
+<div class="code"><pre>
+$ swig -tcl example.i
+$ gcc -c example.c
+$ gcc -c example_wrap.c -I/usr/local/include
+$ gcc -shared example.o example_wrap.o -o example.so
+</pre></div>
+
+<p>
+The exact commands for doing this vary from platform to platform. 
+SWIG tries to guess the right options when it is installed.  Therefore, 
+you may want to start with one of the examples in the <tt>SWIG/Examples/tcl</tt> 
+directory.   If that doesn't work, you will need to read the man-pages for
+your compiler and linker to get the right set of options.  You might also
+check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
+additional information.
+</p>
+
+<p>
+When linking the module, the name of the output file has to match the name
+of the module.  If the name of your SWIG module is "<tt>example</tt>", the
+name of the corresponding object file should be
+"<tt>example.so</tt>".
+The name of the module is specified using the <tt>%module</tt> directive or the 
+<tt> -module</tt> command line option.
+</p>
+
+<H3><a name="Tcl_nn5"></a>32.1.3 Static linking</H3>
+
+
+<p>
+An alternative approach to dynamic linking is to rebuild the Tcl
+interpreter with your extension module added to it.  In the past,
+this approach was sometimes necessary due to limitations in dynamic loading
+support on certain machines.  However, the situation has improved greatly
+over the last few years and you should not consider this approach 
+unless there is really no other option.
+</p>
+
+<p>
+The usual procedure for adding a new module to Tcl involves writing a
+special function <tt>Tcl_AppInit()</tt> and using it to initialize the interpreter and
+your module.  With SWIG, the <tt>tclsh.i</tt> and <tt>wish.i</tt> library files
+can be used to rebuild the <tt>tclsh</tt> and <tt>wish</tt> interpreters respectively.
+For example:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%inline %{
+extern int fact(int);
+extern int mod(int, int);
+extern double My_variable;
+%}
+
+%include tclsh.i       // Include code for rebuilding tclsh
+
+</pre></div>
+
+<p>
+The <tt>tclsh.i</tt> library file includes supporting code that
+contains everything needed to rebuild tclsh. To rebuild the interpreter,
+you simply do something like this:
+</p>
+
+<div class="code"><pre>
+$ swig -tcl example.i
+$ gcc example.c example_wrap.c \
+        -Xlinker -export-dynamic \
+        -DHAVE_CONFIG_H -I/usr/local/include/ \
+	-L/usr/local/lib -ltcl -lm -ldl \
+	-o mytclsh
+
+</pre></div>
+
+<p>
+You will need to supply the same libraries that were used to build Tcl the first
+time.  This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
+and <tt>-lpthread</tt>.  If this actually works, the new version of Tcl
+should be identical to the default version except that your extension module will be
+a built-in part of the interpreter.
+</p>
+
+<p>
+<b>Comment:</b> In practice, you should probably try to avoid static
+linking if possible. Some programmers may be inclined
+to use static linking in the interest of getting better performance.
+However, the performance gained by static linking tends to be rather
+minimal in most situations (and quite frankly not worth the extra
+hassle in the opinion of this author). 
+</p>
+
+<H3><a name="Tcl_nn6"></a>32.1.4 Using your module</H3>
+
+
+<p>
+To use your module, simply use the Tcl <tt>load</tt> command.  If
+all goes well, you will be able to this:
+</p>
+
+<div class="code"><pre>
+$ tclsh
+% load ./example.so
+% fact 4
+24
+%
+</pre></div>
+
+<p>
+A common error received by first-time users is the following:
+</p>
+
+<div class="code">
+<pre>
+% load ./example.so
+couldn't find procedure Example_Init
+% 
+</pre>
+</div>
+
+<p>
+This error is almost always caused when the name of the shared object file doesn't
+match the name of the module supplied using the SWIG <tt>%module</tt> directive.
+Double-check the interface to make sure the module name and the shared object
+file match.  Another possible cause of this error is forgetting to link the SWIG-generated
+wrapper code with the rest of your application when creating the extension module.
+</p>
+
+<p>
+Another common error is something similar to the following:
+</p>
+
+<div class="code">
+<pre>
+% load ./example.so
+couldn't load file "./example.so": ./example.so: undefined symbol: fact
+% 
+</pre>
+</div>
+
+<p>
+This error usually indicates that you forgot to include some object
+files or libraries in the linking of the shared library file.  Make
+sure you compile both the SWIG wrapper file and your original program
+into a shared library file.  Make sure you pass all of the required libraries
+to the linker.  
+</p>
+
+<p>
+Sometimes unresolved symbols occur because a wrapper has been created
+for a function that doesn't actually exist in a library.  This usually
+occurs when a header file includes a declaration for a function that
+was never actually implemented or it was removed from a library
+without updating the header file.  To fix this, you can either edit
+the SWIG input file to remove the offending declaration or you can use
+the <tt>%ignore</tt> directive to ignore the declaration.
+</p>
+
+<p>
+Finally, suppose that your extension module is linked with another library like this:
+</p>
+
+<div class="code">
+<pre>
+$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
+      -o example.so
+</pre>
+</div>
+
+<p>
+If the <tt>foo</tt> library is compiled as a shared library, you might get the following
+problem when you try to use your module:
+</p>
+
+<div class="code">
+<pre>
+% load ./example.so
+couldn't load file "./example.so": libfoo.so: cannot open shared object file:
+No such file or directory
+%        
+</pre>
+</div>
+
+<p>
+This error is generated because the dynamic linker can't locate the
+<tt>libfoo.so</tt> library.  When shared libraries are loaded, the
+system normally only checks a few standard locations such as
+<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>.   To fix this problem,
+there are several things you can do.  First, you can recompile your extension
+module with extra path information. For example, on Linux you can do this:
+</p>
+
+<div class="code">
+<pre>
+$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
+      -Xlinker -rpath /home/beazley/projects/lib \
+      -o example.so
+</pre>
+</div>
+
+<p>
+Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
+include the directory with your shared libraries. 
+If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
+a noticeable performance impact on all other applications that you run.
+To set it only for Tcl, you might want to do this instead:
+</p>
+
+<div class="code">
+<pre>
+$ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
+</pre>
+</div>
+
+<p>
+Finally, you can use a command such as <tt>ldconfig</tt> to add additional search paths
+to the default system configuration (this requires root access and you will need to read
+the man pages). 
+</p>
+
+<H3><a name="Tcl_nn7"></a>32.1.5 Compilation of C++ extensions</H3>
+
+
+<p>
+Compilation of C++ extensions has traditionally been a tricky problem.
+Since the Tcl interpreter is written in C, you need to take steps to
+make sure C++ is properly initialized and that modules are compiled
+correctly.
+</p>
+
+<p>
+On most machines, C++ extension modules should be linked using the C++
+compiler.  For example:
+</p>
+
+<div class="code"><pre>
+% swig -c++ -tcl example.i
+% g++ -c example.cxx
+% g++ -c example_wrap.cxx -I/usr/local/include
+% g++ -shared example.o example_wrap.o -o example.so
+</pre></div>
+
+<p>
+In addition to this, you may need to include additional library
+files to make it work.  For example, if you are using the Sun C++ compiler on
+Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
+</p>
+
+<div class="code"><pre>
+% swig -c++ -tcl example.i
+% CC -c example.cxx
+% CC -c example_wrap.cxx -I/usr/local/include
+% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
+</pre></div>
+
+<p>
+Of course, the extra libraries to use are completely non-portable---you will 
+probably need to do some experimentation.
+</p>
+
+<p>
+Sometimes people have suggested that it is necessary to relink the
+Tcl interpreter using the C++ compiler to make C++ extension modules work.
+In the experience of this author, this has never actually appeared to be
+necessary.   Relinking the interpreter with C++ really only includes the 
+special run-time libraries described above---as long as you link your extension 
+modules with these libraries, it should not be necessary to rebuild Tcl.
+</p>
+
+<p>
+If you aren't entirely sure about the linking of a C++ extension, you
+might look at an existing C++ program.  On many Unix machines, the
+<tt>ldd</tt> command will list library dependencies.  This should give
+you some clues about what you might have to include when you link your
+extension module. For example:
+</p>
+
+<div class="code">
+<pre>
+$ ldd swig
+        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
+        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
+        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
+        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
+$
+</pre>
+</div>
+
+<p>
+As a final complication, a major weakness of C++ is that it does not
+define any sort of standard for binary linking of libraries.  This
+means that C++ code compiled by different compilers will not link
+together properly as libraries nor is the memory layout of classes and
+data structures implemented in any kind of portable manner.  In a
+monolithic C++ program, this problem may be unnoticed.  However, in Tcl, it
+is possible for different extension modules to be compiled with
+different C++ compilers.  As long as these modules are self-contained,
+this probably won't matter.  However, if these modules start sharing data,
+you will need to take steps to avoid segmentation faults and other
+erratic program behavior.   If working with lots of software components, you
+might want to investigate using a more formal standard such as COM.
+</p>
+
+<H3><a name="Tcl_nn8"></a>32.1.6 Compiling for 64-bit platforms</H3>
+
+
+<p>
+On platforms that support 64-bit applications (Solaris, Irix, etc.),
+special care is required when building extension modules.  On these
+machines, 64-bit applications are compiled and linked using a different
+set of compiler/linker options.  In addition, it is not generally possible to mix 
+32-bit and 64-bit code together in the same application.
+</p>
+
+<p>
+To utilize 64-bits, the Tcl executable will need to be recompiled
+as a 64-bit application.  In addition, all libraries, wrapper code,
+and every other part of your application will need to be compiled for
+64-bits.  If you plan to use other third-party extension modules, they
+will also have to be recompiled as 64-bit extensions.
+</p>
+
+<p>
+If you are wrapping commercial software for which you have no source
+code, you will be forced to use the same linking standard as used by
+that software.  This may prevent the use of 64-bit extensions.  It may
+also introduce problems on platforms that support more than one
+linking standard (e.g., -o32 and -n32 on Irix).
+</p>
+
+<H3><a name="Tcl_nn9"></a>32.1.7 Setting a package prefix</H3>
+
+
+<p>
+To avoid namespace problems, you can instruct SWIG to append a package
+prefix to all of your functions and variables. This is done using the
+-prefix option as follows :
+</p>
+
+<div class="code"><pre>
+swig -tcl -prefix Foo example.i
+</pre></div>
+
+<p>
+If you have a function "<tt>bar</tt>" in the SWIG file, the prefix
+option will append the prefix to the name when creating a command and
+call it "<tt>Foo_bar</tt>".
+</p>
+
+<H3><a name="Tcl_nn10"></a>32.1.8 Using namespaces</H3>
+
+
+<p>
+Alternatively, you can have SWIG install your module into a Tcl
+namespace by specifying the <tt>-namespace</tt> option :
+</p>
+
+<div class="code"><pre>
+swig -tcl -namespace example.i
+</pre></div>
+
+<p>
+By default, the name of the namespace will be the same as the module
+name, but you can override it using the <tt>-prefix</tt> option.
+</p>
+
+<p>
+When the<tt> -namespace</tt> option is used, objects in the module
+are always accessed with the namespace name such as <tt>Foo::bar</tt>.
+</p>
+
+<H2><a name="Tcl_nn11"></a>32.2 Building Tcl/Tk Extensions under Windows 95/NT</H2>
+
+
+<p>
+Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
+similar to the process used with Unix.  Normally, you will want to
+produce a DLL that can be loaded into tclsh or wish.  This section
+covers the process of using SWIG with Microsoft Visual C++.
+although the procedure may be similar with other compilers.
+</p>
+
+<H3><a name="Tcl_nn12"></a>32.2.1 Running SWIG from Developer Studio</H3>
+
+
+<p>
+If you are developing your application within Microsoft developer
+studio, SWIG can be invoked as a custom build option.  The process
+roughly follows these steps :
+</p>
+
+<ul>
+<li>Open up a new workspace and use the AppWizard to select a DLL project.
+
+<li>Add both the SWIG interface file (the .i file), any supporting C
+files, and the name of the wrapper file that will be created by SWIG
+(ie. <tt>example_wrap.c</tt>).  Note : If using C++, choose a
+different suffix for the wrapper file such as
+<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
+exist yet--Developer studio will keep a reference to it around.
+
+<li>Select the SWIG interface file and go to the settings menu.  Under
+settings, select the "Custom Build" option.
+
+<li>Enter "SWIG" in the description field.
+
+<li>Enter "<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c
+$(InputPath)</tt>" in the "Build command(s) field"
+
+<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
+
+<li>Next, select the settings for the entire project and go to
+"C++:Preprocessor". Add the include directories for your Tcl
+installation under "Additional include directories".
+
+<li>Finally, select the settings for the entire project and go to
+"Link Options".  Add the Tcl library file to your link libraries.  For
+example "<tt>tcl80.lib</tt>".  Also, set the name of the output file
+to match the name of your Tcl module (ie. example.dll).
+
+<li>Build your project.
+</ul>
+
+<p>
+Now, assuming all went well, SWIG will be automatically invoked when
+you build your project.  Any changes made to the interface file will
+result in SWIG being automatically invoked to produce a new version of
+the wrapper file.  To run your new Tcl extension, simply run
+<tt>tclsh</tt> or <tt>wish</tt> and use the <tt>load</tt> command.
+For example :
+</p>
+
+<div class="code"><pre>
+MSDOS &gt; tclsh80
+% load example.dll
+% fact 4
+24
+%
+</pre></div>
+
+<H3><a name="Tcl_nn13"></a>32.2.2 Using NMAKE</H3>
+
+
+<p>
+Alternatively, SWIG extensions can be built by writing a Makefile for
+NMAKE.  To do this, make sure the environment variables for MSVC++ are
+available and the MSVC++ tools are in your path.  Now, just write a
+short Makefile like this :
+</p>
+
+<div class="code"><pre>
+# Makefile for building various SWIG generated extensions
+
+SRCS          = example.c
+IFILE         = example
+INTERFACE     = $(IFILE).i
+WRAPFILE      = $(IFILE)_wrap.c
+
+# Location of the Visual C++ tools (32 bit assumed)
+
+TOOLS         = c:\msdev
+TARGET        = example.dll
+CC            = $(TOOLS)\bin\cl.exe
+LINK          = $(TOOLS)\bin\link.exe
+INCLUDE32     = -I$(TOOLS)\include
+MACHINE       = IX86
+
+# C Library needed to build a DLL
+
+DLLIBC        = msvcrt.lib oldnames.lib  
+
+# Windows libraries that are apparently needed
+WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib 
+winspool.lib
+
+# Libraries common to all DLLs
+LIBS          = $(DLLIBC) $(WINLIB) 
+
+# Linker options
+LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
+MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
+
+# C compiler flags
+
+CFLAGS    = /Z7 /Od /c /nologo
+TCL_INCLUDES  = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
+TCLLIB        = d:\tcl8.0a2\win\tcl80.lib
+
+tcl::
+	..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
+	$(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
+	set LIB=$(TOOLS)\lib
+	$(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
+
+</pre></div>
+
+<p>
+To build the extension, run NMAKE (you may need to run vcvars32
+first).  This is a pretty minimal Makefile, but hopefully its enough
+to get you started.  With a little practice, you'll be making lots of
+Tcl extensions.
+</p>
+
+<H2><a name="Tcl_nn14"></a>32.3 A tour of basic C/C++ wrapping</H2>
+
+
+<p>
+By default, SWIG tries to build a very natural Tcl interface to your
+C/C++ code.  Functions are wrapped as functions, classes are wrapped
+in an interface that mimics the style of Tk widgets and [incr Tcl]
+classes.  This section briefly covers the essential aspects of this
+wrapping.
+</p>
+
+<H3><a name="Tcl_nn15"></a>32.3.1 Modules</H3>
+
+
+<p>
+The SWIG <tt>%module</tt> directive specifies the name of the Tcl
+module. If you specify `<tt>%module example</tt>', then everything is
+compiled into an extension module <tt>example.so</tt>. When choosing a
+module name, make sure you don't use the same name as a built-in
+Tcl command.
+</p>
+
+<p>
+One pitfall to watch out for is module names involving numbers.  If
+you specify a module name like <tt>%module md5</tt>, you'll find that the
+load command no longer seems to work:
+</p>
+
+<div class="code">
+<pre>
+% load ./md5.so
+couldn't find procedure Md_Init
+</pre>
+</div>
+
+<p>
+To fix this, supply an extra argument to <tt>load</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+% load ./md5.so md5
+</pre>
+</div>
+
+<H3><a name="Tcl_nn16"></a>32.3.2 Functions</H3>
+
+
+<p>
+Global functions are wrapped as new Tcl built-in commands.  For example,
+</p>
+
+<div class="code"><pre>
+%module example
+int fact(int n);
+</pre></div>
+
+<p>
+creates a built-in function <tt>fact</tt> that works exactly
+like you think it does:
+</p>
+
+<div class="code"><pre>
+% load ./example.so
+% fact 4
+24
+% set x [fact 6]
+%
+</pre></div>
+
+<H3><a name="Tcl_nn17"></a>32.3.3 Global variables</H3>
+
+
+<p>
+C/C++ global variables are wrapped by Tcl global variables.  For example:
+</p>
+
+<div class="code"><pre>
+// SWIG interface file with global variables
+%module example
+...
+%inline %{
+extern double density;
+%}
+...
+</pre></div>
+
+<p>
+Now look at the Tcl interface:
+</p>
+
+<div class="code"><pre>
+% puts $density          # Output value of C global variable
+1.0
+% set density 0.95       # Change value
+</pre></div>
+
+<p>
+If you make an error in variable assignment, you will get an
+error message.  For example:
+</p>
+
+<div class="code"><pre>
+% set density "hello"
+can't set "density": Type error. expected a double.
+%
+</pre></div>
+
+<p>
+If a variable is declared as <tt>const</tt>, it is wrapped as a
+read-only variable.  Attempts to modify its value will result in an
+error.
+</p>
+
+<p>
+To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable;
+extern char *path;
+%mutable;
+</pre>
+</div>
+
+<p>
+The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
+<tt>%mutable</tt>.
+See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
+</p>
+
+<p>
+If you just want to make a specific variable immutable, supply a declaration name.  For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+extern char *path;
+%}
+%immutable path;
+...
+extern char *path;      // Read-only (due to %immutable)
+</pre>
+</div>
+
+<H3><a name="Tcl_nn18"></a>32.3.4 Constants and enums</H3>
+
+
+<p>
+C/C++ constants are installed as global Tcl variables containing the
+appropriate value.  To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
+<tt>%constant</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+#define PI 3.14159
+#define VERSION "1.0"
+
+enum Beverage { ALE, LAGER, STOUT, PILSNER };
+
+%constant int FOO = 42;
+%constant const char *path = "/usr/local";
+</pre>
+</div>
+
+<p>
+For enums, make sure that the definition of the enumeration actually appears in a header
+file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
+also telling the C compiler about it, the wrapper code won't compile.
+</p>
+
+<p>
+Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
+will be accessed using the <tt>cvar</tt> object described in the previous section.  They
+are not wrapped as constants.   For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
+</p>
+
+<p>
+Constants are not guaranteed to remain constant in Tcl---the value
+of the constant could be accidentally reassigned.You will just have to be careful.
+</p>
+
+<p>
+A peculiarity of installing constants as variables is that it is necessary to use the Tcl <tt>global</tt> statement to
+access constants in procedure bodies.  For example:
+</p>
+
+<div class="code">
+<pre>
+proc blah {} {
+   global FOO
+   bar $FOO
+}
+</pre>
+</div>
+
+<p>
+If a program relies on a lot of constants, this can be extremely annoying.  To fix the problem, consider using the
+following typemap rule:
+</p>
+
+<div class="code">
+<pre>
+%apply int CONSTANT { int x };
+#define FOO 42
+...
+void bar(int x);
+</pre>
+</div>
+
+<p>
+When applied to an input argument, the <tt>CONSTANT</tt> rule allows a constant to be passed to a function using
+its actual value or a symbolic identifier name.  For example:
+</p>
+
+<div class="code">
+<pre>
+proc blah {} {
+   bar FOO
+}
+</pre>
+</div>
+
+<p>
+When an identifier name is given, it is used to perform an implicit hash-table lookup of the value during argument 
+conversion.  This allows the <tt>global</tt> statement to be omitted.
+</p>
+
+<H3><a name="Tcl_nn19"></a>32.3.5 Pointers</H3>
+
+
+<p>
+C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no problem working with
+incomplete type information.  Here is a rather simple interface:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+FILE *fopen(const char *filename, const char *mode);
+int fputs(const char *, FILE *);
+int fclose(FILE *);
+</pre>
+</div>
+
+<p>
+When wrapped, you will be able to use the functions in a natural way from Tcl. 
+For example:
+</p>
+
+<div class="code">
+<pre>
+% load ./example.so
+% set f [fopen junk w]
+% fputs "Hello World\n" $f
+% fclose $f
+</pre>
+</div>
+
+<p>
+If this makes you uneasy, rest assured that there is no
+deep magic involved.  Underneath the covers, pointers to C/C++ objects are
+simply represented as opaque values--normally an encoded character
+string like this:
+</p>
+
+<div class="code"><pre>
+% puts $f
+_c0671108_p_FILE
+% 
+</pre></div>
+
+<p>
+This pointer value can be freely passed around to different C functions that
+expect to receive an object of type <tt>FILE *</tt>.  The only thing you can't do is 
+dereference the pointer from Tcl.
+</p>
+
+<p>
+The NULL pointer is represented by the string <tt>NULL</tt>.
+</p>
+
+<p>
+As much as you might be inclined to modify a pointer value directly
+from Tcl, don't.  The hexadecimal encoding is not necessarily the
+same as the logical memory address of the underlying object.  Instead
+it is the raw byte encoding of the pointer value.  The encoding will
+vary depending on the native byte-ordering of the platform (i.e.,
+big-endian vs. little-endian).  Similarly, don't try to manually cast
+a pointer to a new type by simply replacing the type-string.  This
+may not work like you expect and it is particularly dangerous when
+casting C++ objects. If you need to cast a pointer or
+change its value, consider writing some helper functions instead.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%inline %{
+/* C-style cast */
+Bar *FooToBar(Foo *f) {
+   return (Bar *) f;
+}
+
+/* C++-style cast */
+Foo *BarToFoo(Bar *b) {
+   return dynamic_cast&lt;Foo*&gt;(b);
+}
+
+Foo *IncrFoo(Foo *f, int i) {
+    return f+i;
+}
+%}
+</pre>
+</div>
+
+<p>
+Also, if working with C++, you should always try
+to use the new C++ style casts.  For example, in the above code, the
+C-style cast may return a bogus result whereas as the C++-style cast will return
+<tt>None</tt> if the conversion can't be performed.
+</p>
+
+<H3><a name="Tcl_nn20"></a>32.3.6 Structures</H3>
+
+
+<p>
+If you wrap a C structure, it is wrapped by a Tcl interface that somewhat resembles a Tk widget.
+This provides a very natural interface.  For example,
+</p>
+
+<div class="code"><pre>
+struct Vector {
+	double x,y,z;
+};
+
+</pre></div>
+
+<p>
+is used as follows:
+</p>
+
+<div class="code"><pre>
+% Vector v
+% v configure -x 3.5 -y 7.2
+% puts "[v cget -x] [v cget -y] [v cget -z]"
+3.5 7.2 0.0
+% 
+</pre></div>
+
+<p>
+Similar access is provided for unions and the data members of C++ classes.
+</p>
+
+<p>
+In the above example, <tt>v</tt> is a name that's used for the object.  However,
+underneath the covers, there's a pointer to a raw C structure.  This can be obtained
+by looking at the <tt>-this</tt> attribute.  For example:
+</p>
+
+<div class="code">
+<pre>
+% puts [v cget -this]
+_88e31408_p_Vector
+</pre>
+</div>
+
+<p>
+Further details about the relationship between the Tcl and the underlying C structure
+are covered a little later.
+</p>
+
+<p>
+<tt>const</tt> members of a structure are read-only. Data members
+can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   ...
+   %immutable;
+   int x;        /* Read-only members */
+   char *name;
+   %mutable;
+   ...
+};
+</pre>
+</div>
+
+<p>
+When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
+dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
+SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
+released and a new value created.   If this is not the behavior you want, you will have to use
+a typemap (described later).
+</p>
+
+<p>
+If a structure contains arrays, access to those arrays is managed through pointers.  For
+example, consider this:
+</p>
+
+<div class="code">
+<pre>
+struct Bar {
+    int  x[16];
+};
+</pre>
+</div>
+
+<p>
+If accessed in Tcl, you will see behavior like this:
+</p>
+
+<div class="code">
+<pre>
+% Bar b
+% puts [b cget -x]
+_801861a4_p_int
+% 
+</pre>
+</div>
+
+<p>
+This pointer can be passed around to functions that expect to receive
+an <tt>int *</tt> (just like C).   You can also set the value of an array member using
+another pointer.  For example:
+</p>
+
+<div class="code">
+<pre>
+% Bar c
+% c configure -x [b cget -x]   # Copy contents of b.x to c.x
+</pre>
+</div>
+
+<p>
+For array assignment, SWIG copies the entire contents of the array starting with the data pointed
+to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
+no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
+fault or access violation.
+</p>
+
+<p>
+When a member of a structure is itself a structure, it is handled as a
+pointer.  For example, suppose you have two structures like this:
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+   int a;
+};
+
+struct Bar {
+   Foo f;
+};
+</pre>
+</div>
+
+<p>
+Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+% Bar b
+% set x [b cget -f]
+</pre>
+</div>
+
+<p>
+In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
+This is the same value as generated by this C code:
+</p>
+
+<div class="code">
+<pre>
+Bar b;
+Foo *x = &amp;b-&gt;f;       /* Points inside b */
+</pre>
+</div>
+
+<p>
+However, one peculiarity of accessing a substructure like this is that the returned
+value does work quite like you might expect.  For example:
+</p>
+
+<div class="code">
+<pre>
+% Bar b
+% set x [b cget -f]
+% x cget -a
+invalid command name "x"
+</pre>
+</div>
+
+<p>
+This is because the returned value was not created in a normal way from the interpreter (x is 
+not a command object). To make it function normally, just
+evaluate the variable like this:
+</p>
+
+<div class="code">
+<pre>
+% Bar b
+% set x [b cget -f]
+% $x cget -a
+0
+%
+</pre>
+</div>
+
+<p>
+In this example, <tt>x</tt> points inside the original structure.  This means that modifications
+work just like you would expect.  For example:
+</p>
+
+<div class="code">
+<pre>
+
+% Bar b
+% set x [b cget -f]
+% $x configure -a 3            # Modifies contents of f (inside b)
+% [b cget -f] -configure -a 3  # Same thing
+</pre>
+</div>
+
+<p>
+In many of these structure examples, a simple name like "v" or "b" has been given
+to wrapped structures.  If necessary, this name can be passed to functions
+that expect to receive an object.  For example, if you have a function like this,
+</p>
+
+<div class="code">
+<pre>
+void blah(Foo *f);
+</pre>
+</div>
+
+<p>
+you can call the function in Tcl as follows:
+</p>
+
+<div class="code">
+<pre>
+% Foo x            # Create a Foo object 
+% blah x           # Pass the object to a function
+</pre>
+</div>
+
+<p>
+It is also possible to call the function using the raw pointer value. For
+instance:
+</p>
+
+<div class="code">
+<pre>
+% blah [x cget -this]   # Pass object to a function
+</pre>
+</div>
+
+<p>
+It is also possible to create and use objects using variables.  For example:
+</p>
+
+<div class="code">
+<pre>
+% set b [Bar]            # Create a Bar
+% $b cget -f             # Member access
+% puts $b
+_108fea88_p_Bar
+%
+</pre>
+</div>
+
+<p>
+Finally, to destroy objects created from Tcl, you can either let the object
+name go out of scope or you can explicitly delete the object.  For example:
+</p>
+
+<div class="code">
+<pre>
+% Foo f                 # Create object f
+% rename f ""
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+% Foo f                 # Create object f
+% f -delete
+</pre>
+</div>
+
+<p>
+Note: Tcl only destroys the underlying object if it has ownership.  See the
+memory management section that appears shortly.
+</p>
+
+<H3><a name="Tcl_nn21"></a>32.3.7 C++ classes</H3>
+
+
+<p>
+C++ classes are wrapped as an extension of structure wrapping. For example, if you have this class,
+</p>
+
+<div class="code"><pre>
+class List {
+public:
+  List();
+  ~List();
+  int  search(char *item);
+  void insert(char *item);
+  void remove(char *item);
+  char *get(int n);
+  int  length;
+};
+</pre></div>
+
+<p>
+you can use it in Tcl like this:
+</p>
+
+<div class="code"><pre>
+% List x
+% x insert Ale
+% x insert Stout
+% x insert Lager
+% x get 1
+Stout
+% puts [l cget -length]
+3
+%
+</pre></div>
+
+<p>
+Class data members are accessed in the same manner as C structures.  
+</p>
+
+<p>
+Static class members are accessed as global functions or variables.
+To illustrate, suppose you have a class like this:
+</p>
+
+<div class="code">
+<pre>
+class Spam {
+public:
+   static void foo();
+   static int bar;
+
+};
+</pre>
+</div>
+
+<p>
+In Tcl, the static member is accessed as follows:
+</p>
+
+<div class="code">
+<pre>
+% Spam_foo        # Spam::foo()
+% puts $Spam_bar  # Spam::bar
+</pre>
+</div>
+
+<H3><a name="Tcl_nn22"></a>32.3.8 C++ inheritance</H3>
+
+
+<p>
+SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
+classes like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+...
+};
+
+class Bar : public Foo {
+...
+};
+</pre>
+</div>
+
+<p>
+An object of type <tt>Bar</tt> can be used where a <tt>Foo</tt> is expected.  For
+example, if you have this function:
+</p>
+
+<div class="code">
+<pre>
+void spam(Foo *f);
+</pre>
+</div>
+
+<p>
+then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
+For instance:
+</p>
+
+<div class="code">
+<pre>
+% Foo f      # Create a Foo
+% Bar b      # Create a Bar
+% spam f     # OK
+% spam b     # OK
+</pre>
+</div>
+
+<p>
+It is safe to use multiple inheritance with SWIG.
+</p>
+
+<H3><a name="Tcl_nn23"></a>32.3.9 Pointers, references, values, and arrays</H3>
+
+
+<p>
+In C++, there are many different ways a function might receive
+and manipulate objects.  For example:
+</p>
+
+<div class="code">
+<pre>
+void spam1(Foo *x);      // Pass by pointer
+void spam2(Foo &amp;x);      // Pass by reference
+void spam3(Foo x);       // Pass by value
+void spam4(Foo x[]);     // Array of objects
+</pre>
+</div>
+
+<p>
+In Tcl, there is no detailed distinction like this.
+Because of this, SWIG unifies all of these types
+together in the wrapper code.  For instance, if you actually had the
+above functions, it is perfectly legal to do this:
+</p>
+
+<div class="code">
+<pre>
+% Foo f             # Create a Foo
+% spam1 f           # Ok. Pointer
+% spam2 f           # Ok. Reference
+% spam3 f           # Ok. Value.
+% spam4 f           # Ok. Array (1 element)
+</pre>
+</div>
+
+<p>
+Similar behavior occurs for return values.  For example, if you had
+functions like this,
+</p>
+
+<div class="code">
+<pre>
+Foo *spam5();
+Foo &amp;spam6();
+Foo  spam7();
+</pre>
+</div>
+
+<p>
+then all three functions will return a pointer to some <tt>Foo</tt> object.
+Since the third function (spam7) returns a value, newly allocated memory is used 
+to hold the result and a pointer is returned (Tcl will release this memory 
+when the return value is garbage collected).
+</p>
+
+<H3><a name="Tcl_nn24"></a>32.3.10 C++ overloaded functions</H3>
+
+
+<p>
+C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
+if you have two functions like this:
+</p>
+
+<div class="code">
+<pre>
+void foo(int);
+void foo(char *c);
+</pre>
+</div>
+
+<p>
+You can use them in Tcl in a straightforward manner:
+</p>
+
+<div class="code">
+<pre>
+% foo 3            # foo(int)
+% foo Hello        # foo(char *c)
+</pre>
+</div>
+
+<p>
+Similarly, if you have a class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+    Foo(const Foo &amp;);
+    ...
+};
+</pre>
+</div>
+
+<p>
+you can write Tcl code like this:
+</p>
+
+<div class="code">
+<pre>
+% Foo f                # Create a Foo
+% Foo g f              # Copy f
+</pre>
+</div>
+
+<p>
+Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
+can't disambiguate. For example:
+</p>
+
+<div class="code">
+<pre>
+void spam(int);
+void spam(short);
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+void foo(Bar *b);
+void foo(Bar &amp;b);
+</pre>
+</div>
+
+<p>
+If declarations such as these appear, you will get a warning message like this:
+</p>
+
+<div class="code">
+<pre>
+example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
+at example.i:11.
+</pre>
+</div>
+
+<p>
+To fix this, you either need to ignore or rename one of the methods.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(spam_short) spam(short);
+...
+void spam(int);    
+void spam(short);   // Accessed as spam_short
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+%ignore spam(short);
+...
+void spam(int);    
+void spam(short);   // Ignored
+</pre>
+</div>
+
+<p>
+SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
+declarations according to a set of type-precedence rules.    The order in which declarations appear
+in the input does not matter except in situations where ambiguity arises--in this case, the
+first declaration takes precedence.
+</p>
+
+<p>
+Please refer to the "SWIG and C++" chapter for more information about overloading. 
+</p>
+
+<H3><a name="Tcl_nn25"></a>32.3.11 C++ operators</H3>
+
+
+<p>
+Certain C++ overloaded operators can be handled automatically by SWIG.  For example,
+consider a class like this:
+</p>
+
+<div class="code">
+<pre>
+class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &amp;operator=(const Complex &amp;c);
+  Complex operator+(const Complex &amp;c) const;
+  Complex operator-(const Complex &amp;c) const;
+  Complex operator*(const Complex &amp;c) const;
+  Complex operator-() const;
+  
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+</pre>
+</div>
+
+<p>
+When wrapped, it works like this:
+</p>
+
+<div class="code">
+<pre>
+% Complex c 3 4
+% Complex d 7 8
+% set e [c + d]
+% $e re
+10.0
+% $e im
+12.0
+</pre>
+</div>
+
+<p>
+It should be stressed that operators in SWIG have no relationship to operators
+in Tcl.  In fact, the only thing that's happening here is that an operator like
+<tt>operator +</tt> has been renamed to a method <tt>+</tt>.    Therefore, the
+statement <tt>[c + d]</tt> is really just invoking the <tt>+</tt> method on <tt>c</tt>.
+When more than operator is defined (with different arguments), the standard
+method overloading facilities are used.  Here is a rather odd looking example:
+</p>
+
+<div class="code">
+<pre>
+% Complex c 3 4
+% Complex d 7 8
+% set e [c - d]       # operator-(const Complex &amp;)
+% puts "[$e re] [$e im]"
+10.0 12.0
+% set f [c -]         # operator-()
+% puts "[$f re] [$f im]"
+-3.0 -4.0
+%
+</pre>
+</div>
+
+<p>
+One restriction with operator overloading support is that SWIG is not
+able to fully handle operators that aren't defined as part of the class.
+For example, if you had code like this
+</p>
+
+<div class="code">
+<pre>
+class Complex {
+...
+friend Complex operator+(double, const Complex &amp;c);
+...
+};
+</pre>
+</div>
+
+<p>
+then SWIG doesn't know what to do with the friend function--in fact,
+it simply ignores it and issues a warning.   You can still wrap the operator,
+but you may have to encapsulate it in a special function.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(Complex_add_dc) operator+(double, const Complex &amp;);
+...
+Complex operator+(double, const Complex &amp;c);
+</pre>
+</div>
+
+<p>
+There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
+Keep reading.
+</p>
+
+<H3><a name="Tcl_nn26"></a>32.3.12 C++ namespaces</H3>
+
+
+<p>
+SWIG is aware of C++ namespaces, but namespace names do not appear in
+the module nor do namespaces result in a module that is broken up into
+submodules or packages.  For example, if you have a file like this,
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+namespace foo {
+   int fact(int n);
+   struct Vector {
+       double x,y,z;
+   };
+};
+</pre>
+</div>
+
+<p>
+it works in Tcl as follows:
+</p>
+
+<div class="code">
+<pre>
+% load ./example.so
+% fact 3
+6
+% Vector v
+% v configure -x 3.4
+</pre>
+</div>
+
+<p>
+If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
+For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(Bar_spam) Bar::spam;
+
+namespace Foo {
+    int spam();
+}
+
+namespace Bar {
+    int spam();
+}
+</pre>
+</div>
+
+<p>
+If you have more than one namespace and your want to keep their
+symbols separate, consider wrapping them as separate SWIG modules.
+For example, make the module name the same as the namespace and create
+extension modules for each namespace separately.  If your program
+utilizes thousands of small deeply nested namespaces each with
+identical symbol names, well, then you get what you deserve.
+</p>
+
+<H3><a name="Tcl_nn27"></a>32.3.13 C++ templates</H3>
+
+
+<p>
+C++ templates don't present a huge problem for SWIG.  However, in order
+to create wrappers, you have to tell SWIG to create wrappers for a particular
+template instantiation.  To do this, you use the <tt>%template</tt> directive.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%{
+#include "pair.h"
+%}
+
+template&lt;class T1, class T2&gt;
+struct pair {
+   typedef T1 first_type;
+   typedef T2 second_type;
+   T1 first;
+   T2 second;
+   pair();
+   pair(const T1&amp;, const T2&amp;);
+  ~pair();
+};
+
+%template(pairii) pair&lt;int,int&gt;;
+</pre>
+</div>
+
+<p>
+In Tcl:
+</p>
+
+<div class="code">
+<pre>
+% pairii p 3 4
+% p cget -first
+3
+% p cget -second
+4
+</pre>
+</div>
+
+<p>
+Obviously, there is more to template wrapping than shown in this example.
+More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.   Some more complicated
+examples will appear later.
+</p>
+
+<H3><a name="Tcl_nn28"></a>32.3.14 C++ Smart Pointers</H3>
+
+
+<p>
+In certain C++ programs, it is common to use classes that have been wrapped by
+so-called "smart pointers."   Generally, this involves the use of a template class
+that implements <tt>operator-&gt;()</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+template&lt;class T&gt; class SmartPtr {
+   ...
+   T *operator-&gt;();
+   ...
+}
+</pre>
+</div>
+
+<p>
+Then, if you have a class like this,
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int bar();
+};
+</pre>
+</div>
+
+<p>
+A smart pointer would be used in C++ as follows:
+</p>
+
+<div class="code">
+<pre>
+SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
+...
+p-&gt;x = 3;                        // Foo::x
+int y = p-&gt;bar();                // Foo::bar
+</pre>
+</div>
+
+<p>
+To wrap this in Tcl, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
+<tt>Foo</tt> object.  Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+...
+%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
+...
+</pre>
+</div>
+
+<p>
+Now, in Tcl, everything should just "work":
+</p>
+
+<div class="code">
+<pre>
+% set p [CreateFoo]                  # Create a smart-pointer somehow
+% $p configure -x 3                  # Foo::x
+% $p bar                             # Foo::bar
+</pre>
+</div>
+
+<p>
+If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
+simply use the <tt>__deref__()</tt> method.  For example:
+</p>
+
+<div class="code">
+<pre>
+% set f [$p __deref__]    # Returns underlying Foo *
+</pre>
+</div>
+
+<H2><a name="Tcl_nn29"></a>32.4 Further details on the Tcl class interface</H2>
+
+
+<p>
+In the previous section, a high-level view of Tcl wrapping was
+presented.  A key component of this wrapping is that structures and
+classes are wrapped by Tcl class-like objects. This provides a very
+natural Tcl interface and allows SWIG to support a number of
+advanced features such as operator overloading.   However, a number
+of low-level details were omitted.  This section provides a brief overview
+of how the proxy classes work.
+</p>
+
+<H3><a name="Tcl_nn30"></a>32.4.1 Proxy classes</H3>
+
+
+<p>
+In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
+details of low-level structure and class wrapping are described.  To summarize those chapters, if you
+have a class like this
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+     int x;
+     int spam(int);
+     ...
+</pre>
+</div>
+
+<p>
+then SWIG transforms it into a set of low-level procedural wrappers. For example:
+</p>
+
+<div class="code">
+<pre>
+Foo *new_Foo() {
+    return new Foo();
+}
+void delete_Foo(Foo *f) {
+    delete f;
+}
+int Foo_x_get(Foo *f) {
+    return f-&gt;x;
+}
+void Foo_x_set(Foo *f, int value) {
+    f-&gt;x = value;
+}
+int Foo_spam(Foo *f, int arg1) {
+    return f-&gt;spam(arg1);
+}
+</pre>
+</div>
+
+<p>
+These wrappers are actually found in the Tcl extension module.  For example, you can certainly do this:
+</p>
+
+<div class="code">
+<pre>
+% load ./example.so
+% set f [new_Foo]
+% Foo_x_get $f
+0
+% Foo_spam $f 3
+1
+%
+</pre>
+</div>
+
+<p>
+However, in addition to this, the classname <tt>Foo</tt> is used as an object constructor
+function.   This allows objects to be encapsulated objects that look a lot like Tk widgets
+as shown in the last section.
+</p>
+
+<H3><a name="Tcl_nn31"></a>32.4.2 Memory management</H3>
+
+
+<p>
+Associated with each wrapped object, is an ownership flag <tt>thisown</tt>   The value of this
+flag determines who is responsible for deleting the underlying C++ object.  If set to 1,
+the Tcl interpreter destroys the C++ object when the proxy class is 
+garbage collected.   If set to 0 (or if the attribute is missing), then the destruction
+of the proxy class has no effect on the C++ object.
+</p>
+
+<p>
+When an object is created by a constructor or returned by value, Tcl automatically takes
+ownership of the result.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    Foo();
+    Foo bar();
+};
+</pre>
+</div>
+
+<p>
+In Tcl:
+</p>
+
+<div class="code">
+<pre>
+% Foo f
+% f cget -thisown
+1
+% set g [f bar]
+% $g cget -thisown
+1
+</pre>
+</div>
+
+<p>
+On the other hand, when pointers are returned to Tcl, there is often no way to know where
+they came from.  Therefore, the ownership is set to zero.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+public:
+    ...
+    Foo *spam();
+    ...
+};
+</pre>
+</div>
+
+<br>
+
+<div class="code">
+<pre>
+% Foo f
+% set s [f spam]
+% $s cget -thisown
+0
+% 
+</pre>
+</div>
+
+<p>
+This behavior is especially important for classes that act as
+containers.  For example, if a method returns a pointer to an object
+that is contained inside another object, you definitely don't want
+Tcl to assume ownership and destroy it!
+</p>
+
+<p>
+Related to containers, ownership issues can arise whenever an object is assigned to a member
+or global variable.  For example, consider this interface:
+</p>
+
+<div class="code">
+<pre>
+%module example
+
+struct Foo {
+    int  value;
+    Foo  *next;
+};
+
+Foo *head = 0;
+</pre>
+</div>
+
+<p>
+When wrapped in Tcl, careful observation will reveal that ownership changes whenever an object
+is assigned to a global variable.  For example:
+</p>
+
+<div class="code">
+<pre>
+% Foo f
+% f cget -thisown
+1
+% set head f
+% f cget -thisown
+0
+</pre>
+</div>
+
+<p>
+In this case, C is now holding a reference to the object---you probably don't want Tcl to destroy it.
+Similarly, this occurs for members.  For example:
+</p>
+
+<div class="code">
+<pre>
+% Foo f
+% Foo g
+% f cget -thisown
+1
+% g cget -thisown
+1
+% f configure -next g
+% g cget -thisown 
+0
+%
+</pre>
+</div>
+
+<p>
+For the most part, memory management issues remain hidden.  However,
+there are occasionally situations where you might have to manually
+change the ownership of an object.  For instance, consider code like this:
+</p>
+
+<div class="code">
+<pre>
+class Node {
+   Object *value;
+public:
+   void set_value(Object *v) { value = v; }
+   ...
+};
+</pre>
+</div>
+
+<p>
+Now, consider the following Tcl code:
+</p>
+
+<div class="code">
+<pre>
+% Object v                 # Create an object
+% Node n                   # Create a node
+% n setvalue v             # Set value
+% v cget -thisown
+1
+% 
+</pre>
+</div>
+
+<p>
+In this case, the object <tt>n</tt> is holding a reference to
+<tt>v</tt> internally.  However, SWIG has no way to know that this
+has occurred.  Therefore, Tcl still thinks that it has ownership of the
+object.  Should the proxy object be destroyed, then the C++ destructor
+will be invoked and <tt>n</tt> will be holding a stale-pointer.  If
+you're lucky, you will only get a segmentation fault.
+</p>
+
+<p>
+To work around this, it is always possible to flip the ownership flag. For example,
+</p>
+
+<div class="code">
+<pre>
+% v -disown              # Give ownership to C/C++
+% v -acquire             # Acquire ownership
+</pre>
+</div>
+
+<p>
+It is also possible to deal with situations like this using
+typemaps--an advanced topic discussed later.
+</p>
+
+
+<H2><a name="Tcl_nn32"></a>32.5 Input and output parameters</H2>
+
+
+<p>
+A common problem in some C programs is handling parameters passed as simple pointers.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+void add(int x, int y, int *result) {
+   *result = x + y;
+}
+</pre>
+</div>
+
+<p>
+or perhaps
+</p>
+
+<div class="code">
+<pre>
+int sub(int *x, int *y) {
+   return *x+*y;
+}
+</pre>
+</div>
+
+<p>
+The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+void add(int, int, int *OUTPUT);
+int  sub(int *INPUT, int *INPUT);
+</pre>
+</div>
+
+<p>
+In Tcl, this allows you to pass simple values instead of pointer.  For example:
+</p>
+
+<div class="code">
+<pre>
+set a [add 3 4]
+puts $a
+7
+</pre>
+</div>
+
+<p>
+Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
+and how the <tt>OUTPUT</tt> parameter creates a return result.
+</p>
+
+<p>
+If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
+directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+
+%apply int *OUTPUT { int *result };
+%apply int *INPUT  { int *x, int *y};
+
+void add(int x, int y, int *result);
+int  sub(int *x, int *y);
+</pre>
+</div>
+
+<p>
+If a function mutates one of its parameters like this,
+</p>
+
+<div class="code">
+<pre>
+void negate(int *x) {
+   *x = -(*x);
+}
+</pre>
+</div>
+
+<p>
+you can use <tt>INOUT</tt> like this:
+</p>
+
+<div class="code">
+<pre>
+%include "typemaps.i"
+...
+void negate(int *INOUT);
+</pre>
+</div>
+
+<p>
+In Tcl, a mutated parameter shows up as a return value.  For example:
+</p>
+
+<div class="code">
+<pre>
+set a [negate 3]
+puts $a
+-3
+</pre>
+</div>
+
+<p>
+The most common use of these special typemap rules is to handle functions that
+return more than one value.   For example, sometimes a function returns a result
+as well as a special error code:
+</p>
+
+<div class="code">
+<pre>
+/* send message, return number of bytes sent, along with success code */
+int send_message(char *text, int len, int *success);
+</pre>
+</div>
+
+<p>
+To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+%apply int *OUTPUT { int *success };
+...
+int send_message(char *text, int *success);
+</pre>
+</div>
+
+<p>
+When used in Tcl, the function will return multiple values as a list.  
+</p>
+
+<div class="code">
+<pre>
+set r [send_message "Hello World"]
+set bytes [lindex $r 0]
+set success [lindex $r 1]
+</pre>
+</div>
+
+<p>
+Another common use of multiple return values are in query functions.  For example:
+</p>
+
+<div class="code">
+<pre>
+void get_dimensions(Matrix *m, int *rows, int *columns);
+</pre>
+</div>
+
+<p>
+To wrap this, you might use the following:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%include "typemaps.i"
+%apply int *OUTPUT { int *rows, int *columns };
+...
+void get_dimensions(Matrix *m, int *rows, *columns);
+</pre>
+</div>
+
+<p>
+Now, in Perl:
+</p>
+
+<div class="code">
+<pre>
+set dim [get_dimensions $m]
+set r  [lindex $dim 0]
+set c  [lindex $dim 1]
+</pre>
+</div>
+
+<H2><a name="Tcl_nn33"></a>32.6 Exception handling </H2>
+
+
+<p>
+The <tt>%exception</tt> directive can be used to create a user-definable
+exception handler in charge of converting exceptions in your C/C++
+program into Tcl exceptions.  The chapter on customization features
+contains more details, but suppose you extended the array example into
+a C++ class like the following :
+</p>
+
+<div class="code"><pre>
+class RangeError {};   // Used for an exception
+
+class DoubleArray {
+  private:
+    int n;
+    double *ptr;
+  public:
+    // Create a new array of fixed size
+    DoubleArray(int size) {
+      ptr = new double[size];
+      n = size;
+    }
+    // Destroy an array
+    ~DoubleArray() {
+       delete ptr;
+    }
+    // Return the length of the array
+    int   length() {
+      return n;
+    }
+
+    // Get an item from the array and perform bounds checking.
+    double getitem(int i) {
+      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
+        return ptr[i];
+      else
+        throw RangeError();
+    }
+
+    // Set an item in the array and perform bounds checking.
+    void setitem(int i, double val) {
+      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
+        ptr[i] = val;
+      else {
+        throw RangeError();
+      }
+    }
+  };
+</pre></div>
+
+<p>
+The functions associated with this class can throw a C++ range
+exception for an out-of-bounds array access.  We can catch this in our
+Tcl extension by specifying the following in an interface file :
+</p>
+
+<div class="code"><pre>
+%exception {
+  try {
+    $action                // Gets substituted by actual function call
+  }
+  catch (RangeError) {
+    Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
+    return TCL_ERROR;
+  }
+}
+</pre></div>
+
+<p>
+As shown, the exception handling code will be added to every wrapper function.
+Since this is somewhat inefficient.  You might consider refining the 
+exception handler to only apply to specific methods like this:
+</p>
+
+<div class="code">
+<pre>
+%exception getitem {
+  try {
+    $action
+  }
+  catch (RangeError) {
+    Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
+    return TCL_ERROR;
+  }
+}
+
+%exception setitem {
+  try {
+    $action
+  }
+  catch (RangeError) {
+    Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
+    return TCL_ERROR;
+  }
+}
+</pre>
+</div>
+
+<p>
+In this case, the exception handler is only attached to methods and functions
+named <tt>getitem</tt> and <tt>setitem</tt>.
+</p>
+
+<p>
+If you had a lot of different methods, you can avoid extra typing by using a macro.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%define RANGE_ERROR
+{
+  try {
+    $action
+  }
+  catch (RangeError) {
+    Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
+    return TCL_ERROR;
+  }
+}
+%enddef
+
+%exception getitem RANGE_ERROR;
+%exception setitem RANGE_ERROR;
+</pre>
+</div>
+
+<p>
+Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
+See the chapter on "<a href="Customization.html#Customization">Customization Features</a>" for more examples.
+</p>
+
+<H2><a name="Tcl_nn34"></a>32.7 Typemaps</H2>
+
+
+<p>
+This section describes how you can modify SWIG's default wrapping behavior
+for various C/C++ datatypes using the <tt>%typemap</tt> directive.   This
+is an advanced topic that assumes familiarity with the Tcl C API as well
+as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+</p>
+
+<p>
+Before proceeding, it should be stressed that typemaps are not a required 
+part of using SWIG---the default wrapping behavior is enough in most cases.
+Typemaps are only used if you want to change some aspect of the primitive
+C-Tcl interface.
+</p>
+
+<H3><a name="Tcl_nn35"></a>32.7.1 What is a typemap?</H3>
+
+
+<p>
+A typemap is nothing more than a code generation rule that is attached to 
+a specific C datatype.   For example, to convert integers from Tcl to C,
+you might define a typemap like this:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int {
+        if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
+	printf("Received an integer : %d\n",$1);
+}
+%inline %{
+extern int fact(int n);
+%}
+</pre></div>
+
+<p>
+Typemaps are always associated with some specific aspect of code generation.
+In this case, the "in" method refers to the conversion of input arguments
+to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
+will be applied.  The supplied C code is used to convert values.  In this
+code a number of special variable prefaced by a <tt>$</tt> are used.  The
+<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
+The <tt>$input</tt> variable is the input object of type <tt>Tcl_Obj *</tt>.
+</p>
+
+<p>
+When this example is compiled into a Tcl module, it operates as follows:
+</p>
+
+<div class="code"><pre>
+% load ./example.so
+% fact 6
+Received an integer : 6
+720
+</pre></div>
+
+<p>
+In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
+You can refine this by supplying an optional parameter name.  For example:
+</p>
+
+<div class="code"><pre>
+%module example
+
+%typemap(in) int n {
+        if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
+	printf("n = %d\n",$1);
+}
+%inline %{
+extern int fact(int n);
+%}
+</pre></div>
+
+<p>
+In this case, the typemap code is only attached to arguments that exactly match <tt>int n</tt>.
+</p>
+
+<p>
+The application of a typemap to specific datatypes and argument names involves
+more than simple text-matching--typemaps are fully integrated into the
+SWIG type-system.   When you define a typemap for <tt>int</tt>, that typemap
+applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
+the typemap system follows <tt>typedef</tt> declarations.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int n {
+        if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
+	printf("n = %d\n",$1);
+}
+%inline %{
+typedef int Integer;
+extern int fact(Integer n);    // Above typemap is applied
+%}
+</pre>
+</div>
+
+<p>
+However, the matching of <tt>typedef</tt> only occurs in one direction.  If you
+defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
+type <tt>int</tt>.
+</p>
+
+<p>
+Typemaps can also be defined for groups of consecutive arguments.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (char *str, int len) {
+    $1 = Tcl_GetStringFromObj($input,&amp;$2);
+};
+
+int count(char c, char *str, int len);
+</pre>
+</div>
+
+<p>
+When a multi-argument typemap is defined, the arguments are always handled as a single
+Tcl object.  This allows the function to be used like this (notice how the length
+parameter is omitted):
+</p>
+
+<div class="code">
+<pre>
+% count e "Hello World"
+1
+</pre>
+</div>
+
+<H3><a name="Tcl_nn36"></a>32.7.2 Tcl typemaps</H3>
+
+
+<p>
+The previous section illustrated an "in" typemap for converting Tcl objects to C.
+A variety of different typemap methods are defined by the Tcl module.  For example,
+to convert a C integer back into a Tcl object, you might define an "out" typemap
+like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(out) int {
+    Tcl_SetObjResult(interp,Tcl_NewIntObj($1));
+}
+</pre>
+</div>
+
+<p>
+The following list details all of the typemap methods that can be used by the Tcl module:
+</p>
+
+<p>
+<tt>%typemap(in)</tt>
+</p>
+
+<div class="indent">
+Converts Tcl objects to input function arguments
+</div>
+
+<p>
+<tt>%typemap(out)</tt>
+</p>
+
+<div class="indent">
+Converts return value of a C function to a Tcl object
+</div>
+
+<p>
+<tt>%typemap(varin)</tt>
+</p>
+
+<div class="indent">
+Assigns a C global variable from a Tcl object
+</div>
+
+<p>
+<tt>%typemap(varout)</tt>
+</p>
+
+<div class="indent">
+Returns a C global variable as a Tcl object
+</div>
+
+<p>
+<tt>%typemap(freearg)</tt>
+</p>
+
+<div class="indent">
+Cleans up a function argument (if necessary)
+</div>
+
+<p>
+<tt>%typemap(argout)</tt>
+</p>
+
+<div class="indent">
+Output argument processing
+</div>
+
+<p>
+<tt>%typemap(ret)</tt>
+</p>
+
+<div class="indent">
+Cleanup of function return values
+</div>
+
+<p>
+<tt>%typemap(consttab)</tt>
+</p>
+
+<div class="indent">
+Creation of Tcl constants (constant table)
+</div>
+
+<p>
+<tt>%typemap(constcode)</tt> 
+</p>
+
+<div class="indent">
+Creation of Tcl constants (init function)
+</div>
+
+<p>
+<tt>%typemap(memberin)</tt>
+</p>
+
+<div class="indent">
+Setting of structure/class member data
+</div>
+
+<p>
+<tt>%typemap(globalin)</tt>
+</p>
+
+<div class="indent">
+Setting of C global variables
+</div>
+
+<p>
+<tt>%typemap(check)</tt>
+</p>
+
+<div class="indent">
+Checks function input values.
+</div>
+
+<p>
+<tt>%typemap(default)</tt>
+</p>
+
+<div class="indent">
+Set a default value for an argument (making it optional).
+</div>
+
+<p>
+<tt>%typemap(arginit)</tt>
+</p>
+
+<div class="indent">
+Initialize an argument to a value before any conversions occur.
+</div>
+
+<p>
+Examples of these methods will appear shortly.
+</p>
+
+<H3><a name="Tcl_nn37"></a>32.7.3 Typemap variables</H3>
+
+
+<p>
+Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
+A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
+This is a list of the most common variables:
+</p>
+
+<p>
+<tt>$1</tt>
+</p>
+
+<div class="indent">
+A C local variable corresponding to the actual type specified in the
+<tt>%typemap</tt> directive.  For input values, this is a C local variable
+that's supposed to hold an argument value.  For output values, this is
+the raw result that's supposed to be returned to Tcl.
+</div>
+
+<p>
+<tt>$input</tt>
+</p>
+
+<div class="indent">
+ A <tt>Tcl_Obj *</tt> holding a raw Tcl object with an argument or variable value.
+</div>
+
+<p>
+<tt>$result</tt>
+</p>
+
+<div class="indent">
+A <tt>Tcl_Obj *</tt> that holds the result to be returned to Tcl.
+</div>
+
+<p>
+<tt>$1_name</tt>
+</p>
+
+<div class="indent">
+The parameter name that was matched. 
+</div>
+
+<p>
+<tt>$1_type</tt>
+</p>
+
+<div class="indent">
+The actual C datatype matched by the typemap.
+</div>
+
+<p>
+<tt>$1_ltype</tt>
+</p>
+
+<div class="indent">
+An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
+a C assignment operation).  This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
+All arguments and local variables in wrapper functions are declared using this type so that their values can be
+properly assigned.
+</div>
+
+<p>
+<tt>$symname</tt>
+</p>
+
+<div class="indent">
+The Tcl name of the wrapper function being created.
+</div>
+
+<H3><a name="Tcl_nn38"></a>32.7.4 Converting  a Tcl list to a char ** </H3>
+
+
+<p>
+A common problem in many C programs is the processing of command line
+arguments, which are usually passed in an array of NULL terminated
+strings.  The following SWIG interface file allows a Tcl list to be
+used as a <tt>char **</tt> object.
+</p>
+
+<div class="code"><pre>
+%module argv
+
+// This tells SWIG to treat char ** as a special case
+%typemap(in) char ** {
+     Tcl_Obj **listobjv;
+     int       nitems;
+     int       i;
+     if (Tcl_ListObjGetElements(interp, $input, &amp;nitems, &amp;listobjv) == TCL_ERROR) {
+        return TCL_ERROR;
+     }
+     $1 = (char **) malloc((nitems+1)*sizeof(char *));
+     for (i = 0; i &lt; nitems; i++) {
+        $1[i] = Tcl_GetStringFromObj(listobjv[i],0);
+     }
+     $1[i] = 0;
+}
+
+// This gives SWIG some cleanup code that will get called after the function call
+%typemap(freearg) char ** {
+     if ($1) {
+        free($1);
+     }
+}
+
+// Now a test functions
+%inline %{
+int print_args(char **argv) {
+    int i = 0;
+    while (argv[i]) {
+         printf("argv[%d] = %s\n", i,argv[i]);
+         i++;
+    }
+    return i;
+}
+%}
+%include tclsh.i
+
+</pre></div>
+
+<p>
+In Tcl:
+</p>
+
+<div class="code"><pre>
+% print_args {John Guido Larry}
+argv[0] = John
+argv[1] = Guido
+argv[2] = Larry
+3
+</pre></div>
+
+<H3><a name="Tcl_nn39"></a>32.7.5 Returning values in arguments</H3>
+
+
+<p>
+The "argout" typemap can be used to return a value originating from a
+function argument. For example :
+</p>
+
+<div class="code"><pre>
+// A typemap defining how to return an argument by appending it to the result
+%typemap(argout) double *outvalue {
+     Tcl_Obj *o = Tcl_NewDoubleObj($1);
+     Tcl_ListObjAppendElement(interp,$result,o);
+}
+
+// A typemap telling SWIG to ignore an argument for input
+// However, we still need to pass a pointer to the C function
+%typemap(in,numinputs=0) double *outvalue (double temp) {
+     $1 = &amp;temp;
+}
+
+// Now a function returning two values
+int mypow(double a, double b, double *outvalue) {
+        if ((a &lt; 0) || (b &lt; 0)) return -1;
+        *outvalue = pow(a,b);
+        return 0;
+};
+</pre></div>
+
+<p>
+When wrapped, SWIG matches the <tt>argout</tt> typemap to the
+"<tt>double *outvalue</tt>" argument. The numinputs=0 specification tells SWIG
+to simply ignore this argument when generating wrapper code.  As a
+result, a Tcl function using these typemaps will work like this :
+</p>
+
+<div class="code"><pre>
+% mypow 2 3     # Returns two values, a status value and the result
+0 8
+%
+</pre></div>
+
+<H3><a name="Tcl_nn40"></a>32.7.6 Useful functions</H3>
+
+
+<p>
+The following tables provide some functions that may be useful in
+writing Tcl typemaps. 
+</p>
+
+<p>
+<b>Integers</b>
+</p>
+
+<div class="code">
+<pre>
+Tcl_Obj   *Tcl_NewIntObj(int Value);
+void       Tcl_SetIntObj(Tcl_Obj *obj, int Value);
+int        Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip);
+</pre>
+</div>
+
+<p>
+<b>Floating Point</b>
+</p>
+
+<div class="code">
+<pre>
+Tcl_Obj  *Tcl_NewDoubleObj(double Value);
+void      Tcl_SetDoubleObj(Tcl_Obj *obj, double value);
+int       Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);
+</pre>
+</div>
+
+<p>
+<b>Strings</b>
+</p>
+
+<div class="code">
+<pre>
+Tcl_Obj  *Tcl_NewStringObj(char *str, int len);
+void      Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len);
+char     *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len);
+void      Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
+</pre>
+</div>
+
+<p>
+<b>Lists</b>
+</p>
+
+<div class="code">
+<pre>
+Tcl_Obj  *Tcl_NewListObj(int objc, Tcl_Obj *objv);
+int       Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr);
+int       Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element);
+int       Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr,
+                                 Tcl_Obj ***objvPtr);
+int       Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr);
+int       Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index,
+                           Tcl_Obj_Obj **objptr);
+int       Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count,
+                             int objc, Tcl_Obj *objv);
+</pre>
+</div>
+
+<p>
+<b>Objects</b>
+</p>
+
+<div class="code">
+<pre>
+Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj);
+void     Tcl_IncrRefCount(Tcl_Obj *obj);
+void     Tcl_DecrRefCount(Tcl_Obj *obj);
+int      Tcl_IsShared(Tcl_Obj *obj);
+</pre>
+</div>
+
+<H3><a name="Tcl_nn41"></a>32.7.7 Standard  typemaps</H3>
+
+
+<p>
+The following typemaps show how to convert a few common kinds of
+objects between Tcl and C (and to give a better idea of how typemaps
+work)
+</p>
+
+
+<p>
+<b>Integer conversion</b>
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int, short, long {
+   int temp;
+   if (Tcl_GetIntFromObj(interp, $input, &amp;temp) == TCL_ERROR)
+      return TCL_ERROR;
+   $1 = ($1_ltype) temp;
+}
+</pre>
+</div>
+
+<br>
+
+<div class="code">
+<pre>
+%typemap(out) int, short, long {
+   Tcl_SetIntObj($result,(int) $1);
+}
+</pre>
+</div>
+
+<p>
+<b>Floating point conversion</b>
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) float, double {
+   double temp;
+   if (Tcl_GetDoubleFromObj(interp, $input, &amp;temp) == TCL_ERROR)
+       return TCL_ERROR;
+   $1 = ($1_ltype) temp;
+}
+</pre>
+</div>
+
+<br>
+
+<div class="code">
+<pre>
+%typemap(out) float, double {
+   Tcl_SetDoubleObj($result, $1);
+}
+</pre>
+</div>
+
+<p>
+<b>String Conversion</b>
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) char * {
+   int len;
+   $1 = Tcl_GetStringFromObj(interp, &amp;len);
+   }
+}
+</pre>
+</div>
+
+<br>
+
+<div class="code">
+<pre>
+%typemap(out) char * {
+   Tcl_SetStringObj($result,$1);
+}
+</pre>
+</div>
+
+<H3><a name="Tcl_nn42"></a>32.7.8 Pointer handling</H3>
+
+
+<p>
+SWIG pointers are mapped into Tcl strings containing the
+hexadecimal value and type.  The following functions can be used to
+create and read pointer values.
+</p>
+
+<p>
+<tt>
+int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info *ty, int flags)</tt>
+</p>
+
+<div class="indent">
+Converts a Tcl object <tt>obj</tt> to a C pointer.  The result of the conversion is placed
+into the pointer located at <tt>ptr</tt>.  <tt>ty</tt> is a SWIG type descriptor structure.
+<tt>flags</tt> is used to handle error checking and other aspects of conversion.  It is currently
+reserved for future expansion. Returns 0 on success and -1 on error.
+</div>
+
+<p>
+<tt>
+Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int flags)</tt>
+</p>
+
+<div class="indent">
+Creates a new Tcl pointer object.  <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
+describes the type, and <tt>own</tt> is a flag reserved for future expansion.
+</div>
+
+<p>
+Both of these functions require the use of a special SWIG
+type-descriptor structure.  This structure contains information about
+the mangled name of the datatype, type-equivalence information, as
+well as information about converting pointer values under C++
+inheritance.   For a type of <tt>Foo *</tt>, the type descriptor structure
+is usually accessed as follows:
+</p>
+
+<div class="indent">
+<pre>
+Foo *f;
+if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
+
+Tcl_Obj *;
+obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
+</pre>
+</div>
+
+<p>
+In a typemap, the type descriptor should always be accessed using the special typemap
+variable <tt>$1_descriptor</tt>.  For example:
+</p>
+
+<div class="indent">
+<pre>
+%typemap(in) Foo * {
+   if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
+}
+</pre>
+</div>
+
+<p>
+If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
+For example:
+</p>
+
+<div class="indent">
+<pre>
+%typemap(in) Foo * {
+   if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
+}
+</pre>
+</div>
+
+<H2><a name="Tcl_nn43"></a>32.8 Turning a SWIG module into a Tcl Package.</H2>
+
+
+<p>
+Tcl 7.4 introduced the idea of an extension package.  By default, SWIG
+generates all of the code necessary to create a package. To set the package version,
+simply use the <tt>-pkgversion</tt> option. For example:
+</p>
+
+<div class="code">
+<pre>
+% swig -tcl -pkgversion 2.3 example.i
+</pre>
+</div>
+
+<p>
+After building the SWIG generated module, you need to execute
+the "<tt>pkg_mkIndex</tt>" command inside tclsh.  For example :
+</p>
+
+<div class="code"><pre>
+unix &gt; tclsh
+% pkg_mkIndex . example.so
+% exit
+</pre></div>
+
+<p>
+This creates a file "<tt>pkgIndex.tcl</tt>" with information about the
+package.  To use your package, you now need to move it to its own
+subdirectory which has the same name as the package. For example :
+</p>
+
+<div class="code"><pre>
+./example/
+	   pkgIndex.tcl           # The file created by pkg_mkIndex
+	   example.so             # The SWIG generated module
+</pre></div>
+
+<p>
+Finally, assuming that you're not entirely confused at this point,
+make sure that the example subdirectory is visible from the
+directories contained in either the <tt>tcl_library</tt> or
+<tt>auto_path</tt> variables.  At this point you're ready to use the
+package as follows :
+</p>
+
+<div class="code"><pre>
+unix &gt; tclsh
+% package require example
+% fact 4
+24
+%
+</pre></div>
+
+<p>
+If  you're working with an example in the current directory and this doesn't work, do this instead :
+</p>
+
+<div class="code"><pre>
+unix &gt; tclsh
+% lappend auto_path .
+% package require example
+% fact 4
+24
+</pre></div>
+
+<p>
+As a final note, most SWIG examples do not yet use the
+<tt>package</tt> commands. For simple extensions it may be easier just
+to use the <tt>load</tt> command instead.
+</p>
+
+<H2><a name="Tcl_nn44"></a>32.9 Building new kinds of Tcl interfaces (in Tcl)</H2>
+
+
+<p>
+One of the most interesting aspects of Tcl and SWIG is that you can
+create entirely new kinds of Tcl interfaces in Tcl using the low-level
+SWIG accessor functions.  For example, suppose you had a library of
+helper functions to access arrays :
+</p>
+
+<div class="code"><pre>
+/* File : array.i */
+%module array
+
+%inline %{
+double *new_double(int size) {
+        return (double *) malloc(size*sizeof(double));
+}
+void delete_double(double *a) {
+        free(a);
+}
+double get_double(double *a, int index) {
+        return a[index];
+}
+void set_double(double *a, int index, double val) {
+        a[index] = val;
+}
+int *new_int(int size) {
+        return (int *) malloc(size*sizeof(int));
+}
+void delete_int(int *a) {
+        free(a);
+}
+int get_int(int *a, int index) {
+        return a[index];
+}
+int set_int(int *a, int index, int val) {
+        a[index] = val;
+}
+%}
+
+</pre></div>
+
+<p>
+While these could be called directly, we could also write a Tcl script
+like this :
+</p>
+
+<div class="code"><pre>
+proc Array {type size} {
+    set ptr [new_$type $size]
+    set code {
+        set method [lindex $args 0]
+        set parms [concat $ptr [lrange $args 1 end]]
+        switch $method {
+            get {return [eval "get_$type $parms"]}
+            set {return [eval "set_$type $parms"]}
+            delete {eval "delete_$type $ptr; rename $ptr {}"}
+        }
+    }
+    # Create a procedure
+    uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}"
+    return $ptr
+}
+</pre></div>
+
+<p>
+Our script allows easy array access as follows :
+</p>
+
+<div class="code"><pre>
+set a [Array double 100]                   ;# Create a double [100]
+for {set i 0} {$i &lt; 100} {incr i 1} {      ;# Clear the array
+	$a set $i 0.0
+}
+$a set 3 3.1455                            ;# Set an individual element
+set b [$a get 10]                          ;# Retrieve an element
+
+set ia [Array int 50]                      ;# Create an int[50]
+for {set i 0} {$i &lt; 50} {incr i 1} {       ;# Clear it
+	$ia set $i 0
+}
+$ia set 3 7                                ;# Set an individual element
+set ib [$ia get 10]                        ;# Get an individual element
+
+$a delete                                  ;# Destroy a
+$ia delete                                 ;# Destroy ia
+</pre></div>
+
+<p>
+The cool thing about this approach is that it makes a common interface
+for two different types of arrays.  In fact, if we were to add more C
+datatypes to our wrapper file, the Tcl code would work with those as
+well--without modification.  If an unsupported datatype was requested,
+the Tcl code would simply return with an error so there is very little
+danger of blowing something up (although it is easily accomplished
+with an out of bounds array access).
+</p>
+
+<H3><a name="Tcl_nn45"></a>32.9.1 Proxy classes</H3>
+
+
+<p>
+A similar approach can be applied to proxy classes (also known as
+shadow classes).  The following
+example is provided by Erik Bierwagen and Paul Saxe.  To use it, run
+SWIG with the <tt>-noobject</tt> option (which disables the builtin
+object oriented interface).  When running Tcl, simply source this
+file.  Now, objects can be used in a more or less natural fashion.
+</p>
+
+<div class="code"><pre>
+# swig_c++.tcl
+# Provides a simple object oriented interface using
+# SWIG's low level interface.
+#
+
+proc new {objectType handle_r args} {
+    # Creates a new SWIG object of the given type,
+    # returning a handle in the variable "handle_r".
+    #
+    # Also creates a procedure for the object and a trace on
+    # the handle variable that deletes the object when the
+    # handle variable is overwritten or unset
+    upvar $handle_r handle
+    #
+    # Create the new object
+    #
+    eval set handle \[new_$objectType $args\]
+    #
+    # Set up the object procedure
+    #
+    proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args"
+    #
+    # And the trace ...
+    #
+    uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}"
+    #
+    # Return the handle so that 'new' can be used as an argument to a procedure
+    #
+    return $handle
+}
+
+proc deleteObject {objectType handle name element op} {
+    #
+    # Check that the object handle has a reasonable form
+    #
+    if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
+        error "deleteObject: not a valid object handle: $handle"
+    }
+    #
+    # Remove the object procedure
+    #
+    catch {rename $handle {}}
+    #
+    # Delete the object
+    #
+    delete_$objectType $handle
+}
+
+proc delete {handle_r} {
+    #
+    # A synonym for unset that is more familiar to C++ programmers
+    #
+    uplevel unset $handle_r
+}
+</pre></div>
+
+<p>
+To use this file, we simply source it and execute commands such as
+"new" and "delete" to manipulate objects.  For example :
+</p>
+
+<div class="code"><pre>
+// list.i
+%module List
+%{
+#include "list.h"
+%}
+
+// Very simple C++ example
+
+class List {
+public:
+  List();  // Create a new list
+  ~List(); // Destroy a list
+  int  search(char *value);
+  void insert(char *);  // Insert a new item into the list
+  void remove(char *);  // Remove item from list
+  char *get(int n);     // Get the nth item in the list
+  int  length;          // The current length of the list
+static void print(List *l);  // Print out the contents of the list
+};
+</pre></div>
+
+<p>
+Now a Tcl script using the interface...
+</p>
+
+<div class="code"><pre>
+load ./list.so list       ; # Load the module
+source swig_c++.tcl       ; # Source the object file
+
+new List l
+$l insert Dave
+$l insert John
+$l insert Guido
+$l remove Dave
+puts $l length_get
+
+delete l
+</pre></div>
+
+<p>
+The cool thing about this example is that it works with any C++ object
+wrapped by SWIG and requires no special compilation.  Proof that a
+short, but clever Tcl script can be combined with SWIG to do many
+interesting things.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Typemaps.html b/trunk/Doc/Manual/Typemaps.html
new file mode 100644
index 0000000..d0011e0
--- /dev/null
+++ b/trunk/Doc/Manual/Typemaps.html
@@ -0,0 +1,3919 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Typemaps</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Typemaps"></a>10 Typemaps</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Typemaps_nn2">Introduction</a>
+<ul>
+<li><a href="#Typemaps_nn3">Type conversion</a>
+<li><a href="#Typemaps_nn4">Typemaps</a>
+<li><a href="#Typemaps_nn5">Pattern matching</a>
+<li><a href="#Typemaps_nn6">Reusing typemaps</a>
+<li><a href="#Typemaps_nn7">What can be done with typemaps?</a>
+<li><a href="#Typemaps_nn8">What can't be done with typemaps?</a>
+<li><a href="#Typemaps_nn9">The rest of this chapter</a>
+</ul>
+<li><a href="#Typemaps_nn10">Typemap specifications</a>
+<ul>
+<li><a href="#Typemaps_nn11">Defining a typemap</a>
+<li><a href="#Typemaps_nn12">Typemap scope</a>
+<li><a href="#Typemaps_nn13">Copying a typemap</a>
+<li><a href="#Typemaps_nn14">Deleting a typemap</a>
+<li><a href="#Typemaps_nn15">Placement of typemaps</a>
+</ul>
+<li><a href="#Typemaps_nn16">Pattern matching rules</a>
+<ul>
+<li><a href="#Typemaps_nn17">Basic matching rules</a>
+<li><a href="#Typemaps_nn18">Typedef reductions</a>
+<li><a href="#Typemaps_nn19">Default typemaps</a>
+<li><a href="#Typemaps_mixed_default">Mixed default typemaps</a>
+<li><a href="#Typemaps_nn20">Multi-arguments typemaps</a>
+</ul>
+<li><a href="#Typemaps_nn21">Code generation rules</a>
+<ul>
+<li><a href="#Typemaps_nn22">Scope</a>
+<li><a href="#Typemaps_nn23">Declaring new local variables</a>
+<li><a href="#Typemaps_special_variables">Special variables</a>
+</ul>
+<li><a href="#Typemaps_nn25">Common typemap methods</a>
+<ul>
+<li><a href="#Typemaps_nn26">"in" typemap</a>
+<li><a href="#Typemaps_nn27">"typecheck" typemap</a>
+<li><a href="#Typemaps_nn28">"out" typemap</a>
+<li><a href="#Typemaps_nn29">"arginit" typemap</a>
+<li><a href="#Typemaps_nn30">"default" typemap</a>
+<li><a href="#Typemaps_nn31">"check" typemap</a>
+<li><a href="#Typemaps_nn32">"argout" typemap</a>
+<li><a href="#Typemaps_nn33">"freearg" typemap</a>
+<li><a href="#Typemaps_nn34">"newfree" typemap</a>
+<li><a href="#Typemaps_nn35">"memberin" typemap</a>
+<li><a href="#Typemaps_nn36">"varin" typemap</a>
+<li><a href="#Typemaps_nn37">"varout" typemap</a>
+<li><a href="#throws_typemap">"throws" typemap</a>
+</ul>
+<li><a href="#Typemaps_nn39">Some typemap examples</a>
+<ul>
+<li><a href="#Typemaps_nn40">Typemaps for arrays</a>
+<li><a href="#Typemaps_nn41">Implementing constraints with typemaps</a>
+</ul>
+<li><a href="#Typemaps_nn43">Typemaps for multiple languages</a>
+<li><a href="#Typemaps_optimal">Optimal code generation when returning by value</a>
+<li><a href="#Typemaps_nn42">Multi-argument typemaps</a>
+<li><a href="#runtime_type_checker">The run-time type checker</a>
+<ul>
+<li><a href="#Typemaps_nn45">Implementation</a>
+<li><a href="#Typemaps_nn46">Usage</a>
+</ul>
+<li><a href="#Typemaps_overloading">Typemaps and overloading</a>
+<li><a href="#Typemaps_nn48">More about <tt>%apply</tt> and <tt>%clear</tt></a>
+<li><a href="#Typemaps_nn49">Reducing wrapper code size</a>
+<li><a href="#Typemaps_nn47">Passing data between typemaps</a>
+<li><a href="#Typemaps_nn51">Where to go for more information?</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+<b>Disclaimer: This chapter is under construction!</b>
+</p>
+
+<H2><a name="Typemaps_nn2"></a>10.1 Introduction</H2>
+
+
+<p>
+Chances are, you are reading this chapter for one of two reasons; you
+either want to customize SWIG's behavior or you overheard someone
+mumbling some incomprehensible drivel about "typemaps" and you asked
+yourself "typemaps, what are those?"  That said, let's start with a
+short disclaimer that "typemaps" are an advanced customization feature
+that provide direct access to SWIG's low-level code generator. Not
+only that, they are an integral part of the SWIG C++ type system (a
+non-trivial topic of its own).  Typemaps are generally
+<em>not</em> a required part of using SWIG.  Therefore, you might want
+to re-read the earlier chapters if you have found your way to this
+chapter with only a vague idea of what SWIG already does by default.
+</p>
+
+<H3><a name="Typemaps_nn3"></a>10.1.1 Type conversion</H3>
+
+
+<p>
+One of the most important problems in wrapper code generation is the
+conversion of datatypes between programming languages.  Specifically,
+for every C/C++ declaration, SWIG must somehow generate wrapper code
+that allows values to be passed back and forth between languages.
+Since every programming language represents data differently, this is
+not a simple of matter of simply linking code together with the
+C linker.  Instead, SWIG has to know something about how data is
+represented in each language and how it can be manipulated.
+</p>
+
+<p>
+To illustrate, suppose you had a simple C function like this:
+</p>
+
+<div class="code">
+<pre>
+int factorial(int n);
+</pre>
+</div>
+
+<p>
+To access this function from Python, a pair of Python API functions
+are used to convert integer values.  For example:
+</p>
+
+<div class="code">
+<pre>
+long PyInt_AsLong(PyObject *obj);      /* Python --&gt; C */
+PyObject *PyInt_FromLong(long x);      /* C --&gt; Python */
+</pre>
+</div>
+
+<p>
+The first function is used to convert the input argument from a Python integer object
+to C <tt>long</tt>.  The second function is used to convert a value from C back into a Python integer object. 
+</p>
+
+<p>
+Inside the wrapper function, you might see these functions used like this:
+</p>
+
+<div class="code">
+<pre>
+PyObject *wrap_factorial(PyObject *self, PyObject *args) {
+    int       arg1;
+    int       result;
+    PyObject *obj1;
+    PyObject *resultobj;
+
+    if (!PyArg_ParseTuple("O:factorial", &amp;obj1)) return NULL;
+    <b>arg1 = PyInt_AsLong(obj1);</b>
+    result = factorial(arg1);
+    <b>resultobj = PyInt_FromLong(result);</b>
+    return resultobj;
+}
+</pre>
+</div>
+
+<p>
+Every target language supported by SWIG has functions that work in a similar manner.  For example, in
+Perl, the following functions are used:
+</p>
+
+<div class="code">
+<pre>
+IV SvIV(SV *sv);                     /* Perl --&gt; C */
+void sv_setiv(SV *sv, IV val);       /* C --&gt; Perl */
+</pre>
+</div>
+
+<p>
+In Tcl:
+</p>
+
+<div class="code">
+<pre>
+int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value);
+Tcl_Obj *Tcl_NewIntObj(long value);
+</pre>
+</div>
+
+<p>
+The precise details are not so important.  What is important is that
+all of the underlying type conversion is handled by collections of
+utility functions and short bits of C code like this---you simply have
+to read the extension documentation for your favorite language to know
+how it works (an exercise left to the reader).
+</p>
+
+<H3><a name="Typemaps_nn4"></a>10.1.2 Typemaps</H3>
+
+
+<p>
+Since type handling is so central to wrapper code generation, SWIG
+allows it to be completely defined (or redefined) by the user.  To do this,
+a special <tt>%typemap</tt> directive is used.  For example:
+</p>
+
+<div class="code">
+<pre>
+/* Convert from Python --&gt; C */
+%typemap(in) int {
+    $1 = PyInt_AsLong($input);
+}
+
+/* Convert from C --&gt; Python */
+%typemap(out) int {
+    $result = PyInt_FromLong($1);
+}
+</pre>
+</div>
+
+<p>
+At first glance, this code will look a little confusing.
+However, there is really not much to it.  The first typemap (the "in"
+typemap) is used to convert a value from the target language to C.  The second
+typemap (the "out" typemap) is used to convert in the other
+direction. The content of each typemap is a small fragment of C code
+that is inserted directly into the SWIG generated wrapper functions.  Within
+this code, a number of special variables prefixed with a $ are expanded.  These are
+really just placeholders for C variables that are generated in the course
+of creating the wrapper function. In this case, <tt>$input</tt> refers to an
+input object that needs to be converted to C and <tt>$result</tt>
+refers to an object that is going to be returned by a wrapper
+function.  <tt>$1</tt> refers to a C variable that has the same type as
+specified in the typemap declaration (an <tt>int</tt> in this
+example).
+</p>
+
+<p>
+A short example might make this a little more clear.  If you were wrapping a
+function like this:
+</p>
+
+<div class="code">
+<pre>
+int gcd(int x, int y);
+</pre>
+</div>
+
+<p>
+A wrapper function would look approximately like this:
+</p>
+
+<div class="code">
+<pre>
+PyObject *wrap_gcd(PyObject *self, PyObject *args) {
+   int arg1;
+   int arg2;
+   int result;
+   PyObject *obj1;
+   PyObject *obj2;
+   PyObject *resultobj;
+
+   if (!PyArg_ParseTuple("OO:gcd", &amp;obj1, &amp;obj2)) return NULL;
+
+   /* "in" typemap, argument 1 */<b>   
+   {
+      arg1 = PyInt_AsLong(obj1);
+   }
+</b>
+   /* "in" typemap, argument 2 */<b>
+   {
+      arg2 = PyInt_AsLong(obj2);
+   }
+</b>
+   result = gcd(arg1,arg2);
+
+   /* "out" typemap, return value */<b>
+   {
+      resultobj = PyInt_FromLong(result);
+   }
+</b>
+   return resultobj;
+}
+</pre>
+</div>
+
+<p>
+In this code, you can see how the typemap code has been inserted into
+the function.  You can also see how the special $ variables have been
+expanded to match certain variable names inside the wrapper function.  This is really the
+whole idea behind typemaps--they simply let you insert arbitrary code into different 
+parts of the generated wrapper functions.   Because arbitrary code can be inserted, it
+possible to completely change the way in which values are converted.
+</p>
+
+<H3><a name="Typemaps_nn5"></a>10.1.3 Pattern matching</H3>
+
+
+<p>
+As the name implies, the purpose of a typemap is to "map" C datatypes to 
+types in the target language.   Once a typemap is defined for a C datatype,
+it is applied to all future occurrences of that type in the input file.  For example:
+</p>
+
+<div class="code">
+<pre>
+/* Convert from Perl --&gt; C */
+%typemap(in) <b>int</b> {
+   $1 = SvIV($input);
+}
+
+...
+int factorial(<b>int</b> n);
+int gcd(<b>int</b> x, <b>int</b> y);
+int count(char *s, char *t, <b>int</b> max);
+</pre>
+</div>
+
+<p>
+The matching of typemaps to C datatypes is more than a simple textual match.  In fact,
+typemaps are fully built into the underlying type system.  Therefore, typemaps are
+unaffected by <tt>typedef</tt>, namespaces, and other declarations that might hide the
+underlying type.  For example, you could have code like this:
+</p>
+
+<div class="code">
+<pre>
+/* Convert from Ruby--&gt; C */
+%typemap(in) <b>int</b> {
+   $1 = NUM2INT($input);
+}
+...
+typedef int Integer;
+namespace foo {
+    typedef Integer Number;
+};
+
+int foo(<b>int</b> x);
+int bar(<b>Integer</b> y);
+int spam(<b>foo::Number</b> a, <b>foo::Number</b> b);
+</pre>
+</div>
+
+<p>
+In this case, the typemap is still applied to the proper arguments even though typenames don't always
+match the text "int".  This ability to track types is a critical part of SWIG--in fact, all
+of the target language modules work merely define a set of typemaps for the basic types.  Yet, it
+is never necessary to write new typemaps for typenames introduced by <tt>typedef</tt>.
+</p>
+
+<p>
+In addition to tracking typenames, typemaps may also be specialized to match against a specific argument name.  For
+example, you could write a typemap like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) <b>double nonnegative</b> {
+   $1 = PyFloat_AsDouble($input);
+   if ($1 &lt; 0) {
+        PyErr_SetString(PyExc_ValueError,"argument must be nonnegative.");
+        return NULL;
+   }
+}
+
+...
+double sin(double x);
+double cos(double x);
+double sqrt(<b>double nonnegative</b>);
+
+typedef double Real;
+double log(<b>Real nonnegative</b>);
+...
+</pre>
+</div>
+
+<p>
+For certain tasks such as input argument conversion, typemaps can be defined for sequences of
+consecutive arguments.    For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (<b>char *str, int len</b>) {
+    $1 = PyString_AsString($input);   /* char *str */
+    $2 = PyString_Size($input);       /* int len   */
+}
+...
+int count(<b>char *str, int len</b>, char c);
+</pre>
+</div>
+
+<p>
+In this case, a single input object is expanded into a pair of C arguments.  This example also
+provides a hint to the unusual variable naming scheme involving <tt>$1</tt>, <tt>$2</tt>, and so forth.
+</p>
+
+<H3><a name="Typemaps_nn6"></a>10.1.4 Reusing typemaps</H3>
+
+
+<p>
+Typemaps are normally defined for specific type and argument name patterns.  However, typemaps can also 
+be copied and reused.  One way to do this is to use assignment like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Integer = int;   
+%typemap(in) (char *buffer, int size) = (char *str, int len);
+</pre>
+</div>
+
+<p>
+A more general form of copying is found in the <tt>%apply</tt> directive like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int {
+   /* Convert an integer argument */
+   ...
+}
+%typemap(out) int {
+   /* Return an integer value */
+   ...
+}
+
+/* Apply all of the integer typemaps to size_t */
+%apply int { size_t };    
+</pre>
+</div>
+
+<p>
+<tt>%apply</tt> merely takes <em>all</em> of the typemaps that are defined for one type and
+applies them to other types.  Note: you can include a comma separated set of types in the 
+<tt>{ ... }</tt> part of <tt>%apply</tt>.
+</p>
+
+<p>
+It should be noted that it is not necessary to copy typemaps for types that are related by <tt>typedef</tt>.
+For example, if you have this,
+</p>
+
+<div class="code">
+<pre>
+typedef int size_t;
+</pre>
+</div>
+
+<p>
+then SWIG already knows that the <tt>int</tt> typemaps apply.  You don't have to do anything.
+</p>
+
+<H3><a name="Typemaps_nn7"></a>10.1.5 What can be done with typemaps?</H3>
+
+
+<p>
+The primary use of typemaps is for defining wrapper generation behavior at the level
+of individual C/C++ datatypes.  There are currently six general categories of problems that
+typemaps address:
+</p>
+
+<p>
+<b>Argument handling</b>
+</p>
+
+<div class="code">
+<pre>
+int foo(<b>int x, double y, char *s</b>);
+</pre>
+</div>
+
+<ul>
+<li>Input argument conversion ("in" typemap).</li>
+<li>Input argument type checking ("typecheck" typemap).</li>
+<li>Output argument handling ("argout" typemap).</li>
+<li>Input argument value checking ("check" typemap).</li>
+<li>Input argument initialization ("arginit" typemap).</li>
+<li>Default arguments ("default" typemap).</li>
+<li>Input argument resource management ("freearg" typemap).</li>
+</ul>
+
+<p>
+<b>Return value handling</b>
+</p>
+
+<div class="code">
+<pre>
+<b>int</b> foo(int x, double y, char *s);
+</pre>
+</div>
+
+<ul>
+<li>Function return value conversion ("out" typemap).</li>
+<li>Return value resource management ("ret" typemap).</li>
+<li>Resource management for newly allocated objects ("newfree" typemap).</li>
+</ul>
+
+<p>
+<b>Exception handling</b>
+</p>
+
+<div class="code">
+<pre>
+<b>int</b> foo(int x, double y, char *s) throw(<b>MemoryError, IndexError</b>);
+</pre>
+</div>
+
+<ul>
+<li>Handling of C++ exception specifications. ("throw" typemap).</li>
+</ul>
+
+<p>
+<b>Global variables</b>
+</p>
+
+<div class="code">
+<pre>
+<b>int foo;</b>
+</pre>
+</div>
+
+<ul>
+<li>Assignment of a global variable. ("varin" typemap).</li>
+<li>Reading a global variable. ("varout" typemap).</li>
+</ul>
+
+<p>
+<b>Member variables</b>
+</p>
+
+<div class="code">
+<pre>
+struct Foo {
+    <b>int x[20]</b>;
+};
+</pre>
+</div>
+
+<ul>
+<li>Assignment of data to a class/structure member. ("memberin" typemap).</li>
+</ul>
+
+<p>
+<b>Constant creation</b>
+</p>
+
+<div class="code">
+<pre>
+#define FOO 3
+%constant int BAR = 42;
+enum { ALE, LAGER, STOUT };
+</pre>
+</div>
+
+<ul>
+<li>Creation of constant values. ("consttab" or "constcode" typemap).</li>
+</ul>
+
+<p>
+Details of each of these typemaps will be covered shortly.  Also, certain language modules may define additional
+typemaps that expand upon this list.  For example, the Java module defines a variety of typemaps for controlling additional
+aspects of the Java bindings.  Consult language specific documentation for further details.
+</p>
+
+<H3><a name="Typemaps_nn8"></a>10.1.6 What can't be done with typemaps?</H3>
+
+
+<p>
+Typemaps can't be used to define properties that apply to C/C++ declarations as a whole.  For example,
+suppose you had a declaration like this,
+</p>
+
+<div class="code">
+<pre>
+Foo *make_Foo();
+</pre>
+</div>
+
+<p>
+and you wanted to tell SWIG that <tt>make_Foo()</tt> returned a newly
+allocated object (for the purposes of providing better memory
+management).  Clearly, this property of <tt>make_Foo()</tt> is
+<em>not</em> a property that would be associated with the datatype
+<tt>Foo *</tt> by itself.  Therefore, a completely different SWIG
+customization mechanism (<tt>%feature</tt>) is used for this purpose.  Consult the <a
+href="Customization.html#Customization">Customization Features</a> chapter for more
+information about that.
+</p>
+
+<p>
+Typemaps also can't be used to rearrange or transform the order of arguments.  For example,
+if you had a function like this:
+</p>
+
+<div class="code">
+<pre>
+void foo(int, char *);
+</pre>
+</div>
+
+<p>
+you can't use typemaps to interchange the arguments, allowing you to call the
+function like this:
+</p>
+
+<div class="targetlang">
+<pre>
+foo("hello",3)          # Reversed arguments
+</pre>
+</div>
+
+<p>
+If you want to change the calling conventions of a function, write a helper
+function instead.  For example:
+</p>
+
+<div class="code">
+<pre>
+%rename(foo) wrap_foo;
+%inline %{
+void wrap_foo(char *s, int x) {
+   foo(x,s);
+}
+%}
+</pre>
+</div>
+
+<H3><a name="Typemaps_nn9"></a>10.1.7 The rest of this chapter</H3>
+
+
+<p>
+The rest of this chapter provides detailed information for people who
+want to write new typemaps.  This information is of particular importance to anyone
+who intends to write a new SWIG target language module.  Power users can also
+use this information to write application specific type conversion rules.
+</p>
+
+<p>
+Since typemaps are strongly tied to the underlying C++ type system,
+subsequent sections assume that you are reasonably familiar with the
+basic details of values, pointers, references, arrays, type qualifiers
+(e.g., <tt>const</tt>), structures, namespaces, templates, and memory
+management in C/C++.   If not, you would be well-advised to consult a copy 
+of "The C Programming Language" by Kernighan and Ritchie or 
+"The C++ Programming Language" by Stroustrup before going any further.
+</p>
+
+<H2><a name="Typemaps_nn10"></a>10.2 Typemap specifications</H2>
+
+
+<p>
+This section describes the behavior of the <tt>%typemap</tt> directive itself.
+</p>
+
+<H3><a name="Typemaps_nn11"></a>10.2.1 Defining a typemap</H3>
+
+
+<p>
+New typemaps are defined using the <tt>%typemap</tt> declaration.  The general form of
+this declaration is as follows (parts enclosed in [ ... ] are optional):
+</p>
+
+<div class="code">
+<pre>
+%typemap(<em>method</em> [, <em>modifiers</em>]) <em>typelist</em> <em>code</em> ;
+</pre>
+</div>
+
+<p>
+<em>method</em> is a simply a name that specifies what kind of typemap is being defined.  It
+is usually a name like <tt>"in"</tt>, <tt>"out"</tt>, or <tt>"argout"</tt>.   The purpose of
+these methods is described later.
+</p>
+
+<p>
+<em>modifiers</em> is an optional comma separated list of <tt>name="value"</tt> values.  These
+are sometimes to attach extra information to a typemap and is often target-language dependent.
+</p>
+
+<p>
+<em>typelist</em> is a list of the C++ type patterns that the typemap will match.   The general form of
+this list is as follows:
+</p>
+
+<div class="diagram">
+<pre>
+typelist    :  typepattern [, typepattern, typepattern, ... ] ;
+
+typepattern :  type [ (parms) ]
+            |  type name [ (parms) ]
+            |  ( typelist ) [ (parms) ]
+
+</pre>
+</div>
+
+<p>
+Each type pattern is either a simple type, a simple type and argument name, or a list of types in the
+case of multi-argument typemaps. In addition, each type pattern can be parameterized with a list of temporary
+variables (parms).   The purpose of these variables will be explained shortly.
+</p>
+
+<p><em>code</em> specifies the code used in the typemap.
+Usually this is C/C++ code, but in the statically typed target languages, such as Java and C#, this can contain target language code for certain typemaps.
+It can take any one of the following forms:
+</p>
+
+<div class="diagram">
+<pre>
+code       : { ... }
+           | " ... "
+           | %{ ... %}
+</pre>
+</div>
+
+<p>
+Note that the preprocessor will expand code within the {} delimiters, but not in the last two styles of delimiters,
+see <a href="Preprocessor.html#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</a>.
+Here are some examples of valid typemap specifications:
+</p>
+
+<div class="code">
+<pre>
+/* Simple typemap declarations */
+%typemap(in) int {
+   $1 = PyInt_AsLong($input);
+}
+%typemap(in) int "$1 = PyInt_AsLong($input);";
+%typemap(in) int %{ 
+   $1 = PyInt_AsLong($input);
+%}
+
+/* Typemap with extra argument name */
+%typemap(in) int nonnegative {
+   ...
+}
+
+/* Multiple types in one typemap */
+%typemap(in) int, short, long { 
+   $1 = SvIV($input);
+}
+
+/* Typemap with modifiers */
+%typemap(in,doc="integer") int "$1 = gh_scm2int($input);";
+
+/* Typemap applied to patterns of multiple arguments */
+%typemap(in) (char *str, int len),
+             (char *buffer, int size)
+{
+   $1 = PyString_AsString($input);
+   $2 = PyString_Size($input);
+}
+
+/* Typemap with extra pattern parameters */
+%typemap(in, numinputs=0) int *output (int temp),
+                          long *output (long temp)
+{
+   $1 = &amp;temp;
+}
+</pre>
+</div>
+
+<p>
+Admittedly, it's not the most readable syntax at first glance.  However, the purpose of the
+individual pieces will become clear.
+</p>
+
+<H3><a name="Typemaps_nn12"></a>10.2.2 Typemap scope</H3>
+
+
+<p>
+Once defined, a typemap remains in effect for all of the declarations that follow.  A typemap may be redefined for
+different sections of an input file.  For example:
+</p>
+
+<div class="code">
+<pre>
+// typemap1
+%typemap(in) int {
+...
+}
+
+int fact(int);                    // typemap1
+int gcd(int x, int y);            // typemap1
+
+// typemap2
+%typemap(in) int {
+...
+}
+
+int isprime(int);                 // typemap2
+</pre>
+</div>
+
+<p>
+One exception to the typemap scoping rules pertains to the <tt>%extend</tt> declaration.  <tt>%extend</tt> is used to attach
+new declarations to a class or structure definition.  Because of this, all of the declarations in an <tt>%extend</tt> block are
+subject to the typemap rules that are in effect at the point where the class itself is defined.  For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+   ...
+};
+
+%typemap(in) int {
+ ...
+}
+
+%extend Foo {
+   int blah(int x);    // typemap has no effect.  Declaration is attached to Foo which 
+                       // appears before the %typemap declaration.
+};
+</pre>
+</div>
+
+<H3><a name="Typemaps_nn13"></a>10.2.3 Copying a typemap</H3>
+
+
+<p>
+A typemap is copied by using assignment.   For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Integer = int;
+</pre>
+</div>
+
+<p>
+or this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Integer, Number, int32_t = int;
+</pre>
+</div>
+
+<p>
+Types are often managed by a collection of different typemaps.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in)     int { ... }
+%typemap(out)    int { ... }
+%typemap(varin)  int { ... }
+%typemap(varout) int { ... }
+</pre>
+</div>
+
+<p>
+To copy all of these typemaps to a new type, use <tt>%apply</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+%apply int { Integer };            // Copy all int typemaps to Integer
+%apply int { Integer, Number };    // Copy all int typemaps to both Integer and Number
+</pre>
+</div>
+
+<p>
+The patterns for <tt>%apply</tt> follow the same rules as for <tt>%typemap</tt>. For example:
+</p>
+
+<div class="code">
+<pre>
+%apply int *output { Integer *output };                    // Typemap with name
+%apply (char *buf, int len) { (char *buffer, int size) };  // Multiple arguments
+</pre>
+</div>
+
+<H3><a name="Typemaps_nn14"></a>10.2.4 Deleting a typemap</H3>
+
+
+<p>
+A typemap can be deleted by simply defining no code.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int;               // Clears typemap for int
+%typemap(in) int, long, short;  // Clears typemap for int, long, short
+%typemap(in) int *output;       
+</pre>
+</div>
+
+<p>
+The <tt>%clear</tt> directive clears all typemaps for a given type.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%clear int;                     // Removes all types for int
+%clear int *output, long *output;
+</pre>
+</div>
+
+<p>
+<b>Note:</b> Since SWIG's default behavior is defined by typemaps, clearing a fundamental type like
+<tt>int</tt> will make that type unusable unless you also define a new set of typemaps immediately
+after the clear operation.
+</p>
+
+<H3><a name="Typemaps_nn15"></a>10.2.5 Placement of typemaps</H3>
+
+
+<p>
+Typemap declarations can be declared in the global scope, within a C++ namespace, and within a C++ class.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int {
+   ...
+}
+
+namespace std {
+    class string;
+    %typemap(in) string {
+        ...
+    }
+}
+
+class Bar {
+public:
+    typedef const int &amp; const_reference;
+    %typemap(out) const_reference {
+         ...
+    }
+};
+</pre>
+</div>
+
+<p>
+When a typemap appears inside a namespace or class, it stays in effect until the end of the SWIG input 
+(just like before). However, the typemap takes the local scope into account.   Therefore, this
+code
+</p>
+
+<div class="code">
+<pre>
+namespace std {
+    class string;
+    %typemap(in) string {
+       ...
+    }
+}
+</pre>
+</div>
+
+<p>
+is really defining a typemap for the type <tt>std::string</tt>.   You could have code like this:
+</p>
+
+<div class="code">
+<pre>
+namespace std {
+    class string;
+    %typemap(in) string {          /* std::string */
+       ...
+    }
+}
+
+namespace Foo {
+    class string;
+    %typemap(in) string {          /* Foo::string */
+       ...
+    }
+}
+</pre>
+</div>
+
+<p>
+In this case, there are two completely distinct typemaps that apply to two completely different
+types (<tt>std::string</tt> and <tt>Foo::string</tt>).
+</p>
+
+<p>
+It should be noted that for scoping to work, SWIG has to know that <tt>string</tt> is a typename defined
+within a particular namespace.  In this example, this is done using the class declaration <tt>class string</tt>.
+</p>
+
+<H2><a name="Typemaps_nn16"></a>10.3 Pattern matching rules</H2>
+
+
+<p>
+The section describes the pattern matching rules by which C datatypes are associated with typemaps.
+</p>
+
+<H3><a name="Typemaps_nn17"></a>10.3.1 Basic matching rules</H3>
+
+
+<p>
+Typemaps are matched using both a type and a name (typically the name of a argument).  For a given
+<tt>TYPE NAME</tt> pair, the following rules are applied, in order, to find a match.  The first typemap found
+is used.
+</p>
+
+<ul>
+<li>Typemaps that exactly match <tt>TYPE</tt> and <tt>NAME</tt>.
+<li>Typemaps that exactly match <tt>TYPE</tt> only.
+</ul>
+
+<p>
+If <tt>TYPE</tt> includes qualifiers (const, volatile, etc.), they are stripped and the following
+checks are made:
+</p>
+
+<ul>
+<li>Typemaps that match the stripped <tt>TYPE</tt> and <tt>NAME</tt>.
+<Li>Typemaps that match the stripped <tt>TYPE</tt> only.
+</ul>
+
+<p>
+If <tt>TYPE</tt> is an array.  The following transformation is made:
+</p>
+
+<ul>
+<li>Replace all dimensions to <tt>[ANY]</tt> and look for a generic array typemap.
+</ul>
+
+<p>
+To illustrate, suppose that you had a function like this:
+</p>
+
+<div class="code">
+<pre>
+int foo(const char *s);
+</pre>
+</div>
+
+<p>
+To find a typemap for the argument <tt>const char *s</tt>, SWIG will search for the following typemaps:
+</p>
+
+<div class="diagram">
+<pre>
+const char *s           Exact type and name match
+const char *            Exact type match
+char *s                 Type and name match (stripped qualifiers)
+char *                  Type match (stripped qualifiers)
+</pre>
+</div>
+
+<p>
+When more than one typemap rule might be defined, only the first match
+found is actually used.  Here is an example that
+shows how some of the basic rules are applied:
+</p>
+
+<div class="code"><pre>
+%typemap(in) int *x {
+   ... typemap 1
+}
+
+%typemap(in) int * {
+   ... typemap 2
+}
+
+%typemap(in) const int *z {
+   ... typemap 3
+}
+
+%typemap(in) int [4] {
+   ... typemap 4
+}
+
+%typemap(in) int [ANY] {
+   ... typemap 5
+}
+
+void A(int *x);        // int *x rule    (typemap 1)
+void B(int *y);        // int * rule     (typemap 2)
+void C(const int *x);  // int *x rule    (typemap 1)
+void D(const int *z);  // int * rule     (typemap 3)
+void E(int x[4]);      // int [4] rule   (typemap 4)
+void F(int x[1000]);   // int [ANY] rule (typemap 5)
+</pre>
+</div>
+
+<H3><a name="Typemaps_nn18"></a>10.3.2 Typedef reductions</H3>
+
+
+<p>
+If no match is found using the rules in the previous section, SWIG
+applies a typedef reduction to the type and repeats the typemap search
+for the reduced type.   To illustrate, suppose you had code like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int {
+   ... typemap 1
+}
+
+typedef int Integer;
+void blah(Integer x);
+</pre>
+</div>
+
+<p>
+To find the typemap for <tt>Integer x</tt>, SWIG will first search for the following
+typemaps:
+</p>
+
+<div class="diagram">
+<pre>
+Integer x
+Integer
+</pre>
+</div>
+
+<p>
+Finding no match, it then applies a reduction <tt>Integer -&gt; int</tt> to the type and
+repeats the search.
+</p>
+
+<div class="diagram">
+<pre>
+int x
+int      --&gt; match: typemap 1
+</pre>
+</div>
+
+<p>
+Even though two types might be the same via typedef, SWIG allows typemaps to be defined 
+for each typename independently.  This allows for interesting customization possibilities based
+solely on the typename itself.  For example, you could write code like this:
+</p>
+
+<div class="code">
+<pre>
+typedef double  pdouble;     // Positive double
+
+// typemap 1
+%typemap(in) double {
+   ... get a double ...
+}
+// typemap 2
+%typemap(in) pdouble {
+   ... get a positive double ...
+}
+double sin(double x);           // typemap 1
+pdouble sqrt(pdouble x);        // typemap 2
+</pre>
+</div>
+
+<p>
+When reducing the type, only one typedef reduction is applied at a
+time.  The search process continues to apply reductions until a
+match is found or until no more reductions can be made.
+</p>
+
+<p>
+For complicated types, the reduction process can generate a long list of patterns.  Consider the following:
+</p>
+
+<div class="code">
+<pre>
+typedef int Integer;
+typedef Integer Row4[4];
+void foo(Row4 rows[10]);
+</pre>
+</div>
+
+<p>
+To find a match for the <tt>Row4 rows[10]</tt> argument, SWIG would
+check the following patterns, stopping only when it found a match:
+</p>
+
+<div class="code">
+<pre>
+Row4 rows[10]
+Row4 [10]
+Row4 rows[ANY]
+Row4 [ANY]
+
+# Reduce Row4 --&gt; Integer[4]
+Integer rows[10][4]
+Integer [10][4]
+Integer rows[ANY][ANY]
+Integer [ANY][ANY]
+
+# Reduce Integer --&gt; int
+int rows[10][4]
+int [10][4]
+int rows[ANY][ANY]
+int [ANY][ANY]
+</pre>
+</div>
+
+<p>
+For parameterized types like templates, the situation is even more complicated.  Suppose you had some declarations
+like this:
+</p>
+
+<div class="code">
+<pre>
+typedef int Integer;
+typedef foo&lt;Integer,Integer&gt; fooii;
+void blah(fooii *x);
+</pre>
+</div>
+
+<p>
+In this case, the following typemap patterns are searched for the argument <tt>fooii *x</tt>:
+</p>
+
+<div class="code">
+<pre>
+fooii *x
+fooii *
+
+# Reduce fooii --&gt; foo&lt;Integer,Integer&gt;
+foo&lt;Integer,Integer&gt; *x
+foo&lt;Integer,Integer&gt; *
+
+# Reduce Integer -&gt; int
+foo&lt;int, Integer&gt; *x
+foo&lt;int, Integer&gt; *
+
+# Reduce Integer -&gt; int
+foo&lt;int, int&gt; *x
+foo&lt;int, int&gt; *
+</pre>
+</div>
+
+<p>
+Typemap reductions are always applied to the left-most type that appears.  Only when no reductions can be made to the left-most
+type are reductions made to other parts of the type.   This behavior means that you could define a typemap for
+<tt>foo&lt;int,Integer&gt;</tt>, but a typemap for <tt>foo&lt;Integer,int&gt;</tt> would never be matched.  Admittedly, this
+is rather esoteric--there's little practical reason to write a typemap quite like that.  Of course, you could rely on this
+to confuse your coworkers even more.
+</p>
+
+<H3><a name="Typemaps_nn19"></a>10.3.3 Default typemaps</H3>
+
+
+<p>
+Most SWIG language modules use typemaps to define the default behavior of the C primitive types.  This
+is entirely straightforward.  For example, a set of typemaps are written like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int   "convert an int";
+%typemap(in) short "convert a short";
+%typemap(in) float "convert a float";
+...
+</pre>
+</div>
+
+<p>
+Since typemap matching follows all <tt>typedef</tt> declarations, any sort of type that is
+mapped to a primitive type through <tt>typedef</tt> will be picked up by one of these primitive typemaps.
+</p>
+
+<p>
+The default behavior for pointers, arrays, references, and other kinds of types are handled by
+specifying rules for variations of the reserved <tt>SWIGTYPE</tt> type.   For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) SWIGTYPE *            { ... default pointer handling ...         }
+%typemap(in) SWIGTYPE &amp;            { ... default reference handling ...       }
+%typemap(in) SWIGTYPE []           { ... default array handling ...           }
+%typemap(in) enum SWIGTYPE         { ... default handling for enum values ... }
+%typemap(in) SWIGTYPE (CLASS::*)   { ... default pointer member handling ...  } 
+</pre>
+</div>
+
+<p>
+These rules match any kind of pointer, reference, or array--even when
+multiple levels of indirection or multiple array dimensions are used.
+Therefore, if you wanted to change SWIG's default handling for all
+types of pointers, you would simply redefine the rule for <tt>SWIGTYPE
+*</tt>.
+</p>
+
+<p>
+Finally, the following typemap rule is used to match against simple types that don't match any other rules:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) SWIGTYPE   { ... handle an unknown type ... }
+</pre>
+</div>
+
+<p>
+This typemap is important because it is the rule that gets triggered
+when call or return by value is used.  For instance, if you have a
+declaration like this:
+</p>
+
+<div class="code">
+<pre>
+double dot_product(Vector a, Vector b);
+</pre>
+</div>
+
+<p>
+The <tt>Vector</tt> type will usually just get matched against
+<tt>SWIGTYPE</tt>. The default implementation of <tt>SWIGTYPE</tt> is
+to convert the value into pointers (as described in chapter 3).
+</p>
+
+<p>
+By redefining <tt>SWIGTYPE</tt> it may be possible to implement other
+behavior.  For example, if you cleared all typemaps for
+<tt>SWIGTYPE</tt>, SWIG simply won't wrap any unknown datatype (which might
+be useful for debugging).   Alternatively, you might modify SWIGTYPE to marshal
+objects into strings instead of converting them to pointers.
+</p>
+
+<p>
+The best way to explore the default typemaps is to look at the ones
+already defined for a particular language module.  Typemaps
+definitions are usually found in the SWIG library in a file such as
+<tt>python.swg</tt>, <tt>tcl8.swg</tt>, etc.
+</p>
+
+<H3><a name="Typemaps_mixed_default"></a>10.3.4 Mixed default typemaps</H3>
+
+
+<p>
+The default typemaps described above can be mixed with <tt>const</tt> and with each other.
+For example the <tt>SWIGTYPE *</tt> typemap is for default pointer handling, but if a <tt>const SWIGTYPE *</tt> typemap
+is defined it will be used instead for constant pointers. Some further examples follow:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) enum SWIGTYPE &amp;        { ... enum references ...                       }
+%typemap(in) const enum SWIGTYPE &amp;  { ... const enum references ...                 }
+%typemap(in) SWIGTYPE *&amp;            { ... pointers passed by reference ...          }
+%typemap(in) SWIGTYPE * const &amp;     { ... constant pointers passed by reference ... }
+%typemap(in) SWIGTYPE[ANY][ANY]     { ... 2D arrays ...                             }
+</pre>
+</div>
+
+<p>
+Note that the the typedef reduction described earlier is also used with these mixed default typemaps.
+For example, say the following typemaps are defined and SWIG is looking for the best match for the enum shown below:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) const Hello &amp;          { ... }
+%typemap(in) const enum SWIGTYPE &amp;  { ... }
+%typemap(in) enum SWIGTYPE &amp;        { ... }
+%typemap(in) SWIGTYPE &amp;             { ... }
+%typemap(in) SWIGTYPE               { ... }
+
+enum Hello {};
+const Hello &amp;hi;
+</pre>
+</div>
+
+<p>
+The typemap at the top of the list will be chosen, not because it is defined first, but because it is the closest match for the type being wrapped.
+If any of the typemaps in the above list were not defined, then the next one on the list would have precedence.
+In other words the typemap chosen is the closest explicit match.
+</p>
+
+<p>
+<b>Compatibility note: </b> The mixed default typemaps were introduced in SWIG-1.3.23, but were not used much in this version.
+Expect to see them being used more and more within the various libraries in later versions of SWIG.
+</p>
+
+
+<H3><a name="Typemaps_nn20"></a>10.3.5 Multi-arguments typemaps</H3>
+
+
+<p>
+When multi-argument typemaps are specified, they take precedence over
+any typemaps specified for a single type.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (char *buffer, int len) {
+   // typemap 1
+}
+
+%typemap(in) char *buffer {
+   // typemap 2
+}
+
+void foo(char *buffer, int len, int count); // (char *buffer, int len)
+void bar(char *buffer, int blah);           // char *buffer
+</pre>
+</div>
+
+<p>
+Multi-argument typemaps are also more restrictive in the way that they are matched.
+Currently, the first argument follows the matching rules described in the previous section,
+but all subsequent arguments must match exactly.
+</p>
+
+
+<H2><a name="Typemaps_nn21"></a>10.4 Code generation rules</H2>
+
+
+<p>
+This section describes rules by which typemap code is inserted into
+the generated wrapper code.
+</p>
+
+<H3><a name="Typemaps_nn22"></a>10.4.1 Scope</H3>
+
+
+<p>
+When a typemap is defined like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int {
+   $1 = PyInt_AsLong($input);
+}
+</pre>
+</div>
+
+<p>
+the typemap code is inserted into the wrapper function using a new block scope.  In other words, the
+wrapper code will look like this:
+</p>
+
+<div class="code">
+<pre>
+wrap_whatever() {
+    ...
+    // Typemap code
+    {                    
+       arg1 = PyInt_AsLong(obj1);
+    }
+    ...
+}
+</pre>
+</div>
+
+<p>
+Because the typemap code is enclosed in its own block, it is legal to declare temporary variables
+for use during typemap execution.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) short {
+   long temp;          /* Temporary value */
+   if (Tcl_GetLongFromObj(interp, $input, &amp;temp) != TCL_OK) {
+      return TCL_ERROR;
+   }
+   $1 = (short) temp;
+}
+</pre>
+</div>
+
+<p>
+Of course, any variables that you declare inside a typemap are destroyed as soon as the typemap
+code has executed (they are not visible to other parts of the wrapper function or other typemaps
+that might use the same variable names).
+</p>
+
+<p>
+Occasionally, typemap code will be specified using a few alternative forms.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int "$1 = PyInt_AsLong($input);";
+%typemap(in) int %{
+$1 = PyInt_AsLong($input);
+%}
+</pre>
+</div>
+
+<p>
+These two forms are mainly used for cosmetics--the specified code is not enclosed inside
+a block scope when it is emitted.   This sometimes results in a less complicated looking wrapper function.
+</p>
+
+<H3><a name="Typemaps_nn23"></a>10.4.2 Declaring new local variables</H3>
+
+
+<p>
+Sometimes it is useful to declare a new local variable that exists
+within the scope of the entire wrapper function.  A good example of this
+might be an application in which you wanted to marshal strings.   Suppose
+you had a C++ function like this
+</p>
+
+<div class="code">
+<pre>
+int foo(std::string *s);
+</pre>
+</div>
+
+<p>
+and you wanted to pass a native string in the target language as an argument.   For instance,
+in Perl, you wanted the function to work like this:
+</p>
+
+<div class="targetlang">
+<pre>
+$x = foo("Hello World");
+</pre>
+</div>
+
+<p>
+To do this, you can't just pass a raw Perl string as the <tt>std::string *</tt> argument. 
+Instead, you have to create a temporary <tt>std::string</tt> object, copy the Perl string data into it, and
+then pass a pointer to the object.   To do this, simply specify the typemap with an extra parameter like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) std::string * <b>(std::string temp)</b> {
+    unsigned int len;
+    char        *s;
+    s = SvPV($input,len);         /* Extract string data */
+    temp.assign(s,len);           /* Assign to temp */
+    $1 = &amp;temp;                   /* Set argument to point to temp */
+}
+</pre>
+</div>
+
+<p>
+In this case, <tt>temp</tt> becomes a local variable in
+the scope of the entire wrapper function.  For example:
+</p>
+
+<div class="code">
+<pre>
+wrap_foo() {
+   std::string temp;    &lt;--- Declaration of temp goes here
+   ...
+
+   /* Typemap code */
+   {
+      ...
+      temp.assign(s,len);
+      ...
+   } 
+   ...
+}
+</pre>
+</div>
+
+<p>
+When you set <tt>temp</tt> to a value, it
+persists for the duration of the wrapper function and gets
+cleaned up automatically on exit. 
+</p>
+
+<p>
+It is perfectly safe to use more than one typemap involving local
+variables in the same declaration. For example, you could declare a
+function as :</p>
+
+<div class="code"><pre>
+void foo(std::string *x, std::string *y, std::string *z);
+</pre></div>
+
+<p>
+This is safely handled because SWIG actually renames all local
+variable references by appending an argument number suffix.  Therefore, the
+generated code would actually look like this:
+</p>
+
+<div class="code">
+<pre>
+wrap_foo() {
+   int *arg1;    /* Actual arguments */
+   int *arg2;
+   int *arg3;
+   std::string temp1;    /* Locals declared in the typemap */
+   std::string temp2;
+   std::string temp3;
+   ...
+   {
+       char *s;
+       unsigned int len;
+       ...
+       temp1.assign(s,len);
+       arg1 = *temp1;
+   }
+   {
+       char *s;
+       unsigned int len;
+       ...
+       temp2.assign(s,len);
+       arg2 = &amp;temp2;
+   }
+   {
+       char *s;
+       unsigned int len;
+       ...
+       temp3.assign(s,len);
+       arg3 = &amp;temp3;
+   }
+   ...
+}
+</pre>
+</div>
+
+<p>
+Some typemaps do not recognize local variables (or they may simply not
+apply). At this time, only typemaps that apply to argument conversion support this.
+</p>
+
+<p>
+<b>Note:</b>
+</p>
+
+<p>
+When declaring a typemap for multiple types, 
+each type must have its own local variable declaration.
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) const std::string *, std::string * (std::string temp) // NO!
+// only std::string * has a local variable
+// const std::string * does not (oops)
+....
+
+%typemap(in) const std::string * (std::string temp), std::string * (std::string temp) // Correct
+....
+</pre>
+</div>
+
+
+<H3><a name="Typemaps_special_variables"></a>10.4.3 Special variables</H3>
+
+
+<p>
+Within all typemaps, the following special variables are expanded.
+</p>
+
+<center>
+<table border=1 summary="Typemap special variables">
+<tr><th>Variable</th><th>Meaning</th></tr>
+
+<tr>
+<td>$<em>n</em></td>
+<td>
+A C local variable corresponding to type <em>n</em> in the typemap
+pattern.
+</td>
+</tr>
+
+<tr>
+<td>$argnum</td>
+<td>Argument number.  Only available in typemaps related to argument conversion</td>
+</tr>
+
+<tr>
+<td>$<em>n</em>_name</td>
+<td>Argument name</td>
+</tr>
+
+<tr>
+<td>$<em>n</em>_type</td>
+<td>Real C datatype of type <em>n</em>.</td>
+</tr>
+
+<tr>
+<td>$<em>n</em>_ltype</td>
+<td>ltype of type <em>n</em></td>
+</tr>
+
+<tr>
+<td>$<em>n</em>_mangle</td>
+<td>Mangled form of type <em>n</em>.  For example <tt>_p_Foo</tt></td>
+</tr>
+
+<tr>
+<td>$<em>n</em>_descriptor</td>
+<td>Type descriptor structure for type <em>n</em>.  For example
+<tt>SWIGTYPE_p_Foo</tt>.  This is primarily used when interacting with the
+run-time type checker (described later).</td>
+</tr>
+
+
+<tr>
+<td>$*<em>n</em>_type</td>
+<td>Real C datatype of type <em>n</em> with one pointer removed.</td>
+</tr>
+
+<tr>
+<td>$*<em>n</em>_ltype</td>
+<td>ltype of type <em>n</em> with one pointer removed.</td>
+</tr>
+
+<tr>
+<td>$*<em>n</em>_mangle</td>
+<td>Mangled form of type <em>n</em> with one pointer removed. </td>
+</tr>
+
+<tr>
+<td>$*<em>n</em>_descriptor</td>
+<td>Type descriptor structure for type <em>n</em> with one pointer removed.
+</tr>
+
+
+<tr>
+<td>$&amp;<em>n</em>_type</td>
+<td>Real C datatype of type <em>n</em> with one pointer added.</td>
+</tr>
+
+<tr>
+<td>$&amp;<em>n</em>_ltype</td>
+<td>ltype of type <em>n</em> with one pointer added.</td>
+</tr>
+
+<tr>
+<td>$&amp;<em>n</em>_mangle</td>
+<td>Mangled form of type <em>n</em> with one pointer added.</td>
+</tr>
+
+<tr>
+<td>$&amp;<em>n</em>_descriptor</td>
+<td>Type descriptor structure for type <em>n</em> with one pointer added.
+</tr>
+
+<tr>
+<td>$<em>n</em>_basetype</td>
+<td>Base typename with all pointers and qualifiers stripped.
+</td>
+</tr>
+
+</table>
+</center>
+
+<p>
+Within the table, $<em>n</em> refers to a specific type within the typemap specification.  For example,
+if you write this
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int *INPUT {
+
+}
+</pre>
+</div>
+
+<p>
+then $1 refers to <tt>int *INPUT</tt>.  If you have a typemap like this,
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (int argc, char *argv[]) {
+  ...
+}
+</pre>
+</div>
+
+<p>
+then $1 refers to <tt>int argc</tt> and $2 refers to <tt>char *argv[]</tt>.
+</p>
+
+<p>
+Substitutions related to types and names always fill in values from the actual code that was matched.
+This is useful when a typemap might match multiple C datatype.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in)  int, short, long {
+   $1 = ($1_ltype) PyInt_AsLong($input);
+}
+</pre>
+</div>
+
+<p>
+In this case, <tt>$1_ltype</tt> is replaced with the datatype that is actually matched.
+</p>
+
+
+<p>
+When typemap code is emitted, the C/C++ datatype of the special variables <tt>$1</tt> and 
+<tt>$2</tt> is always an "ltype."   An "ltype" is simply a type that can legally appear
+on the left-hand side of a C assignment operation.   Here are a few examples of types
+and ltypes:
+</p>
+
+<div class="diagram">
+<pre>
+type              ltype
+------            ----------------
+int               int
+const int         int
+const int *       int *
+int [4]           int *
+int [4][5]        int (*)[5]
+</pre>
+</div>
+
+<p>
+In most cases a ltype is simply the C datatype with qualifiers stripped off.  In addition,
+arrays are converted into pointers.
+</p>
+
+<p>
+Variables such as <tt>$&amp;1_type</tt> and <tt>$*1_type</tt> are used to
+safely modify the type by removing or adding pointers.  Although not
+needed in most typemaps, these substitutions are sometimes needed to properly
+work with typemaps that convert values between pointers and values.  
+</p>
+
+<p>
+If necessary, type related substitutions can also be used when declaring locals.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int * ($*1_type temp) {
+    temp = PyInt_AsLong($input);
+    $1 = &amp;temp;
+}
+</pre>
+</div>
+
+<p>
+There is one word of caution about declaring local variables in this manner. If you declare a local variable
+using a type substitution such as <tt>$1_ltype temp</tt>, it won't work like you expect for arrays and certain
+kinds of pointers.   For example, if you wrote this,
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int [10][20] {
+   $1_ltype temp;
+}
+</pre>
+</div>
+
+<p>
+then the declaration of <tt>temp</tt> will be expanded as 
+</p>
+
+<div class="code">
+<pre>
+int (*)[20] temp;
+</pre>
+</div>
+
+<p>
+This is illegal C syntax and won't compile.  There is currently no
+straightforward way to work around this problem in SWIG due to the way
+that typemap code is expanded and processed.  However, one possible workaround
+is to simply pick an alternative type such as <tt>void *</tt> and use
+casts to get the correct type when needed.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int [10][20] {
+   void *temp;
+   ...
+   (($1_ltype) temp)[i][j] = x;    /* set a value */
+   ...
+}
+</pre>
+</div>
+
+<p>
+Another approach, which only works for arrays is to use the <tt>$1_basetype</tt> substitution.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int [10][20] {
+   $1_basetype temp[10][20];
+   ...
+   temp[i][j] = x;    /* set a value */
+   ...
+}
+</pre>
+</div>
+
+<H2><a name="Typemaps_nn25"></a>10.5 Common typemap methods</H2>
+
+
+<p>
+The set of typemaps recognized by a language module may vary.  However,
+the following typemap methods are nearly universal:
+</p>
+
+<H3><a name="Typemaps_nn26"></a>10.5.1 "in" typemap</H3>
+
+
+<p>
+The "in" typemap is used to convert function arguments from the target language
+to C.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int {
+   $1 = PyInt_AsLong($input);
+}
+</pre>
+</div>
+
+<p>
+The following special variables are available:
+</p>
+
+<div class="code">
+<pre>
+$input            - Input object holding value to be converted.
+$symname          - Name of function/method being wrapped
+</pre>
+</div>
+
+<p>
+This is probably the most commonly redefined typemap because it can be used
+to implement customized conversions.
+</p>
+
+<p>
+In addition, the "in" typemap allows the number of converted arguments to be
+specified.  The <tt>numinputs</tt> attributes facilitates this. For example:
+</p>
+
+<div class="code">
+<pre>
+// Ignored argument.
+%typemap(in, numinputs=0) int *out (int temp) {
+    $1 = &amp;temp;
+}
+</pre>
+</div>
+
+<p>
+At this time, only zero or one arguments may be converted. 
+When <tt>numinputs</tt> is set to 0, the argument is effectively ignored and cannot be supplied from the target language. 
+The argument is still required when making the C/C++ call and the above typemap
+shows the value used is instead obtained from a locally declared variable called <tt>temp</tt>.
+Usually <tt>numinputs</tt> is not specified, whereupon the default value is 1, that is, there is a one to one mapping of the number of arguments when used from the target language to the C/C++ call. 
+<a href="#Typemaps_multi_argument_typemaps">Multi-argument typemaps</a> provide a similar concept where the number of arguments mapped from the target language to C/C++ can be changed for more tha multiple adjacent C/C++ arguments.
+</p>
+
+<p>
+<b>Compatibility note: </b> Specifying <tt>numinputs=0</tt>
+is the same as the old "ignore" typemap.
+</p>
+
+<H3><a name="Typemaps_nn27"></a>10.5.2 "typecheck" typemap</H3>
+
+
+<p>
+The "typecheck" typemap is used to support overloaded functions and methods.  It merely checks an argument
+to see whether or not it matches a specific type.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
+   $1 = PyInt_Check($input) ? 1 : 0;
+}
+</pre>
+</div>
+
+<p>
+For typechecking, the $1 variable is always a simple integer that is set to 1 or 0 depending on whether or not
+the input argument is the correct type.
+</p>
+
+<p>
+If you define new "in" typemaps <em>and</em> your program uses overloaded methods, you should also define a collection of
+"typecheck" typemaps.  More details about this follow in a later section on "Typemaps and Overloading."
+</p>
+
+<H3><a name="Typemaps_nn28"></a>10.5.3 "out" typemap</H3>
+
+
+<p>
+The "out" typemap is used to convert function/method return values from C
+into the target language.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(out) int {
+   $result = PyInt_FromLong($1);
+}
+</pre>
+</div>
+
+<p>
+The following special variables are available.
+</p>
+
+<div class="code">
+<pre>
+$result           - Result object returned to target language.
+$symname          - Name of function/method being wrapped
+</pre>
+</div>
+
+<p>
+The "out" typemap supports an optional attribute flag called "optimal". This is for code optimisation and is detailed in the <a href="#Typemaps_optimal">Optimal code generation when returning by value</a> section.
+</p>
+
+<H3><a name="Typemaps_nn29"></a>10.5.4 "arginit" typemap</H3>
+
+
+<p>
+The "arginit" typemap is used to set the initial value of a function
+argument--before any conversion has occurred.   This is not normally
+necessary, but might be useful in highly specialized applications.
+For example:
+</p>
+
+<div class="code">
+<pre>
+// Set argument to NULL before any conversion occurs
+%typemap(arginit) int *data {
+   $1 = NULL;
+}
+</pre>
+</div>
+
+<H3><a name="Typemaps_nn30"></a>10.5.5 "default" typemap</H3>
+
+
+<p>
+The "default" typemap is used to turn an argument into a default
+argument.   For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(default) int flags {
+   $1 = DEFAULT_FLAGS;
+}
+...
+int foo(int x, int y, int flags);
+</pre>
+</div>
+
+<p>
+The primary use of this typemap is to either change the wrapping of
+default arguments or specify a default argument in a language where
+they aren't supported (like C). Target languages that do not support
+optional arguments, such as Java and C#, effectively ignore the value specified
+by this typemap as all arguments must be given.
+</p>
+
+<p>
+Once a default typemap has been applied to an argument, all arguments
+that follow must have default values.
+See the <a href="SWIG.html#SWIG_default_args">Default/optional arguments</a> section
+for further information on default argument wrapping.
+</p>
+
+<H3><a name="Typemaps_nn31"></a>10.5.6 "check" typemap</H3>
+
+
+<p>
+The "check" typemap is used to supply value checking code during argument
+conversion.  The typemap is applied <em>after</em> arguments have been
+converted.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(check) int positive {
+   if ($1 &lt;= 0) {
+       SWIG_exception(SWIG_ValueError,"Expected positive value.");
+   }
+}
+</pre>
+</div>
+
+<H3><a name="Typemaps_nn32"></a>10.5.7 "argout" typemap</H3>
+
+
+<p>
+The "argout" typemap is used to return values from arguments.  This
+is most commonly used to write wrappers for C/C++ functions that need
+to return multiple values.   The "argout" typemap is almost always combined
+with an "in" typemap---possibly to ignore the input value.  For example:
+</p>
+
+<div class="code">
+<pre>
+/* Set the input argument to point to a temporary variable */
+%typemap(in, numinputs=0) int *out (int temp) {
+   $1 = &amp;temp;
+}
+
+%typemap(argout) int *out {
+   // Append output value $1 to $result
+   ...
+}
+</pre>
+</div>
+
+<p>
+The following special variables are available.
+</p>
+
+<div class="diagram">
+<pre>
+$result           - Result object returned to target language.
+$input            - The original input object passed.
+$symname          - Name of function/method being wrapped
+</pre>
+</div>
+
+<p>
+The code supplied to the "argout" typemap is always placed after
+the "out" typemap.  If multiple return values are used, the extra
+return values are often appended to return value of the function.
+</p>
+
+<p>
+See the <tt>typemaps.i</tt> library for examples.
+</p>
+
+<H3><a name="Typemaps_nn33"></a>10.5.8 "freearg" typemap</H3>
+
+
+<p>
+The "freearg" typemap is used to cleanup argument data.  It is only
+used when an argument might have allocated resources that need to be
+cleaned up when the wrapper function exits.  The "freearg" typemap
+usually cleans up argument resources allocated by the "in" typemap.  
+For example:
+</p>
+
+<div class="code">
+<pre>
+// Get a list of integers
+%typemap(in) int *items {
+   int nitems = Length($input);    
+   $1 = (int *) malloc(sizeof(int)*nitems);
+}
+// Free the list 
+%typemap(freearg) int *items {
+   free($1);
+}
+</pre>
+</div>
+
+<p>
+The "freearg" typemap inserted at the end of the wrapper function,
+just before control is returned back to the target language.  This
+code is also placed into a special variable <tt>$cleanup</tt> that may
+be used in other typemaps whenever a wrapper function needs to abort
+prematurely.
+</p>
+
+<H3><a name="Typemaps_nn34"></a>10.5.9 "newfree" typemap</H3>
+
+
+<p>
+The "newfree" typemap is used in conjunction with the <tt>%newobject</tt>
+directive and is used to deallocate memory used by the return result 
+of a function.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(newfree) string * {
+   delete $1;
+}
+%typemap(out) string * {
+   $result = PyString_FromString($1-&gt;c_str());
+}
+...
+
+%newobject foo;
+...
+string *foo();
+</pre>
+</div>
+
+<p>
+See <a href="Customization.html#ownership">Object ownership and %newobject</a> for further details.
+</p>
+
+<H3><a name="Typemaps_nn35"></a>10.5.10 "memberin" typemap</H3>
+
+
+<p>
+The "memberin" typemap is used to copy data from <em>an already converted input value</em>
+into a structure member.  It is typically used to handle array members and other special
+cases.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(memberin) int [4] {
+   memmove($1, $input, 4*sizeof(int));
+}
+</pre>
+</div>
+
+<p>
+It is rarely necessary to write "memberin" typemaps---SWIG already provides
+a default implementation for arrays, strings, and other objects.
+</p>
+
+<H3><a name="Typemaps_nn36"></a>10.5.11 "varin" typemap</H3>
+
+
+<p>
+The "varin" typemap is used to convert objects in the target language to C for the
+purposes of assigning to a C/C++ global variable.    This is implementation specific.
+</p>
+
+<H3><a name="Typemaps_nn37"></a>10.5.12 "varout" typemap</H3>
+
+
+<p>
+The "varout" typemap is used to convert a C/C++ object to an object in the target
+language when reading a C/C++ global variable.  This is implementation specific.
+</p>
+
+<H3><a name="throws_typemap"></a>10.5.13 "throws" typemap</H3>
+
+
+<p>
+The "throws" typemap is only used when SWIG parses a C++ method with an exception specification or has the <tt>%catches</tt> feature attached to the method.
+It provides a default mechanism for handling C++ methods that have declared the exceptions they will throw.
+The purpose of this typemap is to convert a C++ exception into an error or exception in the target language.
+It is slightly different to the other typemaps as it is based around the exception type rather than the type of a parameter or variable.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(throws) const char * %{
+  PyErr_SetString(PyExc_RuntimeError, $1);
+  SWIG_fail;
+%}
+void bar() throw (const char *);
+</pre>
+</div>
+
+<p>
+As can be seen from the generated code below, SWIG generates an exception handler
+with the catch block comprising the "throws" typemap content.
+</p>
+
+<div class="code">
+<pre>
+...
+try {
+    bar();
+}
+catch(char const *_e) {
+    PyErr_SetString(PyExc_RuntimeError, _e);
+    SWIG_fail;
+    
+}
+...
+</pre>
+</div>
+
+<p>
+Note that if your methods do not have an exception specification yet they do throw exceptions, SWIG cannot know how to deal with them.
+For a neat way to handle these, see the <a href="Customization.html#exception">Exception handling with %exception</a> section.
+</p>
+
+<H2><a name="Typemaps_nn39"></a>10.6 Some typemap examples</H2>
+
+
+<p>
+This section contains a few examples.  Consult language module documentation
+for more examples.
+</p>
+
+<H3><a name="Typemaps_nn40"></a>10.6.1 Typemaps for arrays</H3>
+
+
+<p>
+A common use of typemaps is to provide support for C arrays appearing both as
+arguments to functions and as structure members.
+</p>
+
+<p>
+For example, suppose you had a function like this:
+</p>
+
+<div class="code">
+<pre>
+void set_vector(int type, float value[4]);
+</pre>
+</div>
+
+<p>
+If you wanted to handle <tt>float value[4]</tt> as a list of floats, you might write a typemap
+similar to this:
+</p>
+
+<div class="code">
+<pre>
+
+%typemap(in) float value[4] (float temp[4]) {
+  int i;
+  if (!PySequence_Check($input)) {
+    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
+    return NULL;
+  }
+  if (PySequence_Length($input) != 4) {
+    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements");
+    return NULL;
+  }
+  for (i = 0; i &lt; 4; i++) {
+    PyObject *o = PySequence_GetItem($input,i);
+    if (PyNumber_Check(o)) {
+      temp[i] = (float) PyFloat_AsDouble(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
+      return NULL;
+    }
+  }
+  $1 = temp;
+}
+</pre>
+</div>
+
+<p>
+In this example, the variable <tt>temp</tt> allocates a small array on the
+C stack.  The typemap then populates this array and passes it to the underlying C function.
+</p>
+
+<p>
+When used from Python, the typemap allows the following type of function call:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; set_vector(type, [ 1, 2.5, 5, 20 ])
+</pre>
+</div>
+
+<p>
+If you wanted to generalize the typemap to apply to arrays of all dimensions you might write this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) float value[ANY] (float temp[$1_dim0]) {
+  int i;
+  if (!PySequence_Check($input)) {
+    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
+    return NULL;
+  }
+  if (PySequence_Length($input) != $1_dim0) {
+    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
+    return NULL;
+  }
+  for (i = 0; i &lt; $1_dim0; i++) {
+    PyObject *o = PySequence_GetItem($input,i);
+    if (PyNumber_Check(o)) {
+      temp[i] = (float) PyFloat_AsDouble(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
+      return NULL;
+    }
+  }
+  $1 = temp;
+}
+</pre>
+</div>
+
+<p>
+In this example, the special variable <tt>$1_dim0</tt> is expanded with the actual
+array dimensions.   Multidimensional arrays can be matched in a similar manner.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
+   ... convert a 2d array ...
+}
+</pre>
+</div>
+
+<p>
+For large arrays, it may be impractical to allocate storage on the stack using a temporary variable
+as shown.   To work with heap allocated data, the following technique can be used.
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) float value[ANY] {
+  int i;
+  if (!PySequence_Check($input)) {
+    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
+    return NULL;
+  }
+  if (PySequence_Length($input) != $1_dim0) {
+    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
+    return NULL;
+  }
+  $1 = (float *) malloc($1_dim0*sizeof(float));
+  for (i = 0; i &lt; $1_dim0; i++) {
+    PyObject *o = PySequence_GetItem($input,i);
+    if (PyNumber_Check(o)) {
+      $1[i] = (float) PyFloat_AsDouble(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
+      free($1);
+      return NULL;
+    }
+  }
+}
+%typemap(freearg) float value[ANY] {
+   if ($1) free($1);
+}
+</pre>
+</div>
+
+<p>
+In this case, an array is allocated using <tt>malloc</tt>.   The <tt>freearg</tt> typemap is then used
+to release the argument after the function has been called.
+</p>
+
+<p>
+Another common use of array typemaps is to provide support for array structure members.
+Due to subtle differences between pointers and arrays in C, you can't just "assign" to
+a array structure member.  Instead, you have to explicitly copy elements into the array.
+For example, suppose you had a structure like this:
+</p>
+
+<div class="code"><pre>
+struct SomeObject {
+	float  value[4];
+        ...
+};
+</pre></div>
+
+<p>
+When SWIG runs, it won't produce any code to set the <tt>vec</tt> member.
+You may even get a warning message like this:
+</p>
+
+<div class="shell"><pre>
+swig -python  example.i
+Generating wrappers for Python
+example.i:10.  Warning. Array member value will be read-only.
+</pre></div>
+
+<p>
+These warning messages indicate that SWIG does not know how you want
+to set the <tt>vec</tt> field.
+</p>
+
+<p>
+To fix this, you can supply a special "memberin" typemap like this:
+</p>
+
+<div class="code"><pre>
+%typemap(memberin) float [ANY] {
+  int i;
+  for (i = 0; i &lt; $1_dim0; i++) {
+      $1[i] = $input[i];
+  }
+}
+</pre></div>
+
+<p>
+The memberin typemap is used to set a structure member from data that has already been converted
+from the target language to C.  In this case, <tt>$input</tt> is the local variable in which 
+converted input data is stored.   This typemap then copies this data into the structure. 
+</p>
+
+<p>
+When combined with the earlier typemaps for arrays, the combination of the "in" and "memberin" typemap allows
+the following usage:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; s = SomeObject()
+&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
+</pre>
+</div>
+
+<p>
+Related to structure member input, it may be desirable to return structure members as a new kind of
+object.  For example, in this example, you will get very odd program behavior where the structure member
+can be set nicely, but reading the member simply returns a pointer:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; s = SomeObject()
+&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
+&gt;&gt;&gt; print s.x
+_1008fea8_p_float
+&gt;&gt;&gt; 
+</pre>
+</div>
+
+<p>
+To fix this, you can write an "out" typemap.   For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(out) float [ANY] {
+  int i;
+  $result = PyList_New($1_dim0);
+  for (i = 0; i &lt; $1_dim0; i++) {
+    PyObject *o = PyFloat_FromDouble((double) $1[i]);
+    PyList_SetItem($result,i,o);
+  }
+}
+</pre>
+</div>
+
+<p>
+Now, you will find that member access is quite nice:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; s = SomeObject()
+&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
+&gt;&gt;&gt; print s.x
+[ 1, 2.5, 5, 10]
+</pre>
+</div>
+
+<p>
+<b>Compatibility Note:</b>  SWIG1.1 used to provide a special "memberout" typemap.  However, it was mostly
+useless and has since been eliminated.   To return structure members, simply use the "out" typemap.
+</p>
+
+<H3><a name="Typemaps_nn41"></a>10.6.2 Implementing constraints with typemaps</H3>
+
+
+<p>
+One particularly interesting application of typemaps is the
+implementation of argument constraints. This can be done with the
+"check" typemap. When used, this allows you to provide code for
+checking the values of function arguments. For example :</p>
+
+<div class="code"><pre>
+%module math
+
+%typemap(check) double posdouble {
+	if ($1 &lt; 0) {
+		croak("Expecting a positive number");
+	}
+}
+
+...
+double sqrt(double posdouble);
+
+</pre></div>
+
+<p>
+This provides a sanity check to your wrapper function. If a negative
+number is passed to this function, a Perl exception will be raised and
+your program terminated with an error message.</p>
+
+<p>
+This kind of checking can be particularly useful when working with
+pointers. For example :</p>
+
+<div class="code"><pre>
+%typemap(check) Vector * {
+    if ($1 == 0) {
+        PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed");
+        return NULL;
+   }
+}
+
+</pre></div>
+
+<p>
+will prevent any function involving a <tt>Vector *</tt> from accepting
+a NULL pointer. As a result, SWIG can often prevent a potential
+segmentation faults or other run-time problems by raising an exception
+rather than blindly passing values to the underlying C/C++ program.</p>
+
+<p>
+Note: A more advanced constraint checking system is in development.  Stay tuned.
+</p>
+
+<H2><a name="Typemaps_nn43"></a>10.7 Typemaps for multiple languages</H2>
+
+
+<p>
+The code within typemaps is usually language dependent,
+however, many languages support the same typemaps.
+In order to distinguish typemaps across different languages, the preprocessor should be used.
+For example, the "in" typemap for Perl and Ruby could be written as:
+</p>
+
+<div class="code"><pre>
+#if defined(SWIGPERL)
+  %typemap(in) int "$1 = ($1_ltype) SvIV($input);"
+#elif defined(SWIGRUBY)
+  %typemap(in) int "$1 = NUM2INT($input);"
+#else
+  #warning no "in" typemap defined
+#endif
+</pre></div>
+
+<p>
+The full set of language specific macros is defined in the <a href="Preprocessor.html#Preprocessor_condition_compilation">Conditional Compilation</a> section.
+The example above also shows a common approach of issuing a warning for an as yet unsupported language.
+</p>
+
+<p>
+<b>Compatibility note: </b> In SWIG-1.1 different languages could be distinguished with the language name being put within the <tt>%typemap</tt> directive, for example, <br>
+<tt>%typemap(ruby,in) int "$1 = NUM2INT($input);"</tt>.
+</p>
+
+<H2><a name="Typemaps_optimal"></a>10.8 Optimal code generation when returning by value</H2>
+
+
+<p>
+The "out" typemap is the main typemap for return types.
+This typemap supports an optional attribute flag called "optimal", which is for reducing 
+temporary variables and the amount of generated code.
+It only really makes a difference when returning objects by value and it cannot always be used, 
+as explained later on.
+</p>
+
+<p>
+When a function returns an object by value, SWIG generates code that instantiates the default
+type on the stack then assigns the value returned by the function call to it.
+A copy of this object is then made on the heap and this is what is ultimately stored and
+used from the target language.
+This will be clearer considering an example.
+Consider running the following code through SWIG:
+</p>
+
+<div class="code">
+<pre>
+%typemap(out) SWIGTYPE %{
+  $result = new $1_ltype((const $1_ltype &amp;)$1);
+%}
+
+%inline %{
+#include &lt;iostream&gt;
+using namespace std;
+
+struct XX {
+  XX() { cout &lt;&lt; "XX()" &lt;&lt; endl; }
+  XX(int i) { cout &lt;&lt; "XX(" &lt;&lt; i &lt;&lt; ")" &lt;&lt; endl; }
+  XX(const XX &amp;other) { cout &lt;&lt; "XX(const XX &amp;)" &lt;&lt; endl; }
+  XX &amp; operator =(const XX &amp;other) { cout &lt;&lt; "operator=(const XX &amp;)" &lt;&lt; endl; return *this; }
+  ~XX() { cout &lt;&lt; "~XX()" &lt;&lt; endl; }
+  static XX create() { 
+    return XX(0);
+  }
+};
+%}
+</pre>
+</div>
+
+<p>
+The "out" typemap shown is the default typemap for C# when returning by objects by value.
+When making a call to <tt>XX::create()</tt> from C#, the output is as follows:
+</p>
+
+<div class="targetlang">
+<pre>
+XX()
+XX(0)
+operator=(const XX &amp;)
+~XX()
+XX(const XX &amp;)
+~XX()
+~XX()
+</pre>
+</div>
+
+<p>
+Note that three objects are being created as well as an assignment.
+Wouldn't it be great if the <tt>XX::create()</tt> method was the only time a constructor was called?
+As the method returns by value, this is asking a lot and the code that SWIG generates by default
+makes it impossible for the compiler to make this type of optimisation.
+However, this is where the "optimal" attribute in the "out" typemap can help out.
+If the typemap code is kept the same and just the "optimal" attribute specified like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(out, optimal="1") SWIGTYPE %{
+  $result = new $1_ltype((const $1_ltype &amp;)$1);
+%}
+</pre>
+</div>
+
+<p>
+then when the code is run again, the output is simply:
+</P>
+
+<div class="targetlang">
+<pre>
+XX(0)
+~XX()
+</pre>
+</div>
+
+<p>
+How the "optimal" attribute works is best explained using the generated code.
+Without "optimal", the generated code is:
+</p>
+
+<div class="code">
+<pre>
+SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
+  void * jresult ;
+  XX result;
+  result = XX::create();
+  jresult = new XX((const XX &amp;)result);
+  return jresult;
+}
+
+</pre>
+</div>
+
+<p>
+With the "optimal" attribute, the code is:
+</p>
+
+<div class="code">
+<pre>
+SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
+  void * jresult ;
+  jresult = new XX((const XX &amp;)XX::create());
+  return jresult;
+}
+</pre>
+</div>
+
+<p>
+The major difference is the <tt>result</tt> temporary variable holding the value returned from <tt>XX::create()</tt> is no longer generated and instead the copy constructor call is made directly from
+the value returned by <tt>XX::create()</tt>.
+With modern compiler optimisations turned on, the copy is not actually done, in fact the object is never created
+on the stack in <tt>XX::create()</tt> at all, it is simply created directly on the heap.
+In the first instance, the <tt>$1</tt> special variable in the typemap is expanded into <tt>result</tt>.
+In the second instance, <tt>$1</tt> is expanded into <tt>XX::create()</tt> and this is essentially
+what the "optimal" attribute is telling SWIG to do.
+</p>
+
+<p>
+This kind of optimisation is not turned on by default as it has a number of restrictions.
+Firstly, some code cannot be condensed into a simple call for passing into the copy constructor.
+One common occurrence is when <a href="Customization.html#exception">%exception</a> is used.
+Consider adding the following <tt>%exception</tt> to the example:
+</p>
+
+<div class="code">
+<pre>
+%exception XX::create() %{
+try {
+  $action
+} catch(const std::exception &amp;e) {
+  cout &lt;&lt; e.what() &lt;&lt; endl;
+}
+%}
+</pre>
+</div>
+
+<p>
+SWIG can detect when the "optimal" attribute cannot be used and will ignore it and in this case will issue the following warning:
+</p>
+
+<div class="targetlang">
+<pre>
+example.i:28: Warning(474): Method XX::create() usage of the optimal attribute in the out 
+typemap at example.i:14 ignored as the following cannot be used to generate optimal code: 
+try {
+  result = XX::create();
+} catch(const std::exception &amp;e) {
+  cout &lt;&lt; e.what() &lt;&lt; endl;
+}
+</pre>
+</div>
+
+<p>
+It should be clear that the above code cannot be used as the argument to the copy constructor call, ie for the <tt>$1</tt> substitution.
+</p>
+
+<p>
+Secondly, if the typemaps uses <tt>$1</tt> more than once, then multiple calls to the wrapped function
+will be made. Obviously that is not very optimal.
+In fact SWIG attempts to detect this and will issue a warning something like:
+</p>
+
+<div class="targetlang">
+<pre>
+example.i:21: Warning(475): Multiple calls to XX::create() might be generated due to 
+optimal attribute usage in the out typemap at example.i:7.
+</pre>
+</div>
+
+<p>
+However, it doesn't always get it right, for example when <tt>$1</tt> is within some commented out code.
+</p>
+
+<H2><a name="Typemaps_multi_argument_typemaps"></a>10.9 Multi-argument typemaps</H2>
+
+
+<p>
+So far, the typemaps presented have focused on the problem of dealing with
+single values.  For example, converting a single input object to a single argument
+in a function call.   However, certain conversion problems are difficult to handle
+in this manner.   As an example, consider the example at the very beginning of this
+chapter:
+</p>
+
+<div class="code">
+<pre>
+int foo(int argc, char *argv[]);
+</pre>
+</div>
+
+<p>
+Suppose that you wanted to wrap this function so that it accepted a single
+list of strings like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; foo(["ale","lager","stout"])
+</pre>
+</div>
+
+<p>
+To do this, you not only need to map a list of strings to <tt> char *argv[]</tt>, but the
+value of <tt>int argc</tt> is implicitly determined by the length of the list.   Using only simple
+typemaps, this type of conversion is possible, but extremely painful.  Therefore, SWIG1.3 
+introduces the notion of multi-argument typemaps.
+</p>
+
+<p>
+A multi-argument typemap is a conversion rule that specifies how to
+convert a <em>single</em> object in the target language to set of
+consecutive function arguments in C/C++.   For example, the following multi-argument
+maps perform the conversion described for the above example: 
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (int argc, char *argv[]) {
+  int i;
+  if (!PyList_Check($input)) {
+    PyErr_SetString(PyExc_ValueError, "Expecting a list");
+    return NULL;
+  }
+  $1 = PyList_Size($input);
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i &lt; $1; i++) {
+    PyObject *s = PyList_GetItem($input,i);
+    if (!PyString_Check(s)) {
+        free($2);
+        PyErr_SetString(PyExc_ValueError, "List items must be strings");
+        return NULL;
+    }
+    $2[i] = PyString_AsString(s);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char *argv[]) {
+   if ($2) free($2);
+}
+</pre>
+</div>
+
+<p>
+A multi-argument map is always specified by surrounding the arguments with parentheses as shown.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (int argc, char *argv[]) { ... }
+</pre>
+</div>
+
+<p>
+Within the typemap code, the variables <tt>$1</tt>, <tt>$2</tt>, and so forth refer to each type
+in the map.  All of the usual substitutions apply--just use the appropriate <tt>$1</tt> or <tt>$2</tt>
+prefix on the variable name (e.g., <tt>$2_type</tt>, <tt>$1_ltype</tt>, etc.)
+</p>
+
+<p>
+Multi-argument typemaps always have precedence over simple typemaps and SWIG always performs longest-match searching.
+Therefore, you will get the following behavior:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int argc                              { ... typemap 1 ... }
+%typemap(in) (int argc, char *argv[])              { ... typemap 2 ... }
+%typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... }
+
+int foo(int argc, char *argv[]);                   // Uses typemap 2
+int bar(int argc, int x);                          // Uses typemap 1
+int spam(int argc, char *argv[], char *env[]);     // Uses typemap 3
+</pre>
+</div>
+
+<p>
+It should be stressed that multi-argument typemaps can appear anywhere in a function declaration and can
+appear more than once.  For example, you could write this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (int scount, char *swords[]) { ... }
+%typemap(in) (int wcount, char *words[]) { ... }
+
+void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);
+</pre>
+</div>
+
+<p>
+Other directives such as <tt>%apply</tt> and <tt>%clear</tt> also work with multi-argument maps.  For example:
+</p>
+
+<div class="code">
+<pre>
+%apply (int argc, char *argv[]) {
+    (int scount, char *swords[]),
+    (int wcount, char *words[])
+};
+...
+%clear (int scount, char *swords[]), (int wcount, char *words[]);
+...
+</pre>
+</div>
+
+<p>
+Although multi-argument typemaps may seem like an exotic, little used feature, there
+are several situations where they make sense.  First, suppose you wanted to wrap
+functions similar to the low-level <tt>read()</tt> and <tt>write()</tt> system calls.
+For example:
+</p>
+
+<div class="code">
+<pre>
+typedef unsigned int size_t;
+
+int read(int fd, void *rbuffer, size_t len);
+int write(int fd, void *wbuffer, size_t len);
+</pre>
+</div>
+
+<p>
+As is, the only way to use the functions would be to allocate memory and pass some kind of pointer
+as the second argument---a process that might require the use of a helper function.  However, using
+multi-argument maps, the functions can be transformed into something more natural.  For example, you 
+might write typemaps like this:
+</p>
+
+<div class="code">
+<pre>
+// typemap for an outgoing buffer
+%typemap(in) (void *wbuffer, size_t len) {
+   if (!PyString_Check($input)) {
+       PyErr_SetString(PyExc_ValueError, "Expecting a string");
+       return NULL;
+   }
+   $1 = (void *) PyString_AsString($input);
+   $2 = PyString_Size($input);
+}
+
+// typemap for an incoming buffer
+%typemap(in) (void *rbuffer, size_t len) {
+   if (!PyInt_Check($input)) {
+       PyErr_SetString(PyExc_ValueError, "Expecting an integer");
+       return NULL;
+   }
+   $2 = PyInt_AsLong($input);
+   if ($2 &lt; 0) {
+       PyErr_SetString(PyExc_ValueError, "Positive integer expected");
+       return NULL;
+   }
+   $1 = (void *) malloc($2);
+}
+
+// Return the buffer.  Discarding any previous return result
+%typemap(argout) (void *rbuffer, size_t len) {
+   Py_XDECREF($result);   /* Blow away any previous result */
+   if (result &lt; 0) {      /* Check for I/O error */
+       free($1);
+       PyErr_SetFromErrno(PyExc_IOError);
+       return NULL;
+   }
+   $result = PyString_FromStringAndSize($1,result);
+   free($1);
+}
+</pre>
+</div>
+
+<p>
+(note: In the above example, <tt>$result</tt> and <tt>result</tt> are two different variables.
+<tt>result</tt> is the real C datatype that was returned by the function.  <tt>$result</tt> is the
+scripting language object being returned to the interpreter.).
+</p>
+
+<p>
+Now, in a script, you can write code that simply passes buffers as strings like this:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; f = example.open("Makefile")
+&gt;&gt;&gt; example.read(f,40)
+'TOP        = ../..\nSWIG       = $(TOP)/.'
+&gt;&gt;&gt; example.read(f,40)
+'./swig\nSRCS       = example.c\nTARGET    '
+&gt;&gt;&gt; example.close(f)
+0
+&gt;&gt;&gt; g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644)
+&gt;&gt;&gt; example.write(g,"Hello world\n")
+12
+&gt;&gt;&gt; example.write(g,"This is a test\n")
+15
+&gt;&gt;&gt; example.close(g)
+0
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+A number of multi-argument typemap problems also arise in libraries that
+perform matrix-calculations--especially if they are mapped onto low-level Fortran
+or C code. For example, you might have a function like this:
+</p>
+
+<div class="code">
+<pre>
+int is_symmetric(double *mat, int rows, int columns);
+</pre>
+</div>
+
+<p>
+In this case, you might want to pass some kind of higher-level object as an matrix.  To do
+this, you could write a multi-argument typemap like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (double *mat, int rows, int columns) {
+    MatrixObject *a;
+    a = GetMatrixFromObject($input);     /* Get matrix somehow */
+
+    /* Get matrix properties */
+    $1 = GetPointer(a);
+    $2 = GetRows(a);
+    $3 = GetColumns(a);
+}
+</pre>
+</div>
+
+<p>
+This kind of technique can be used to hook into scripting-language matrix packages such as
+Numeric Python.  However, it should also be stressed that some care is in order.  For example,
+when crossing languages you may need to worry about issues such as row-major vs. column-major
+ordering (and perform conversions if needed).
+</p>
+
+<H2><a name="runtime_type_checker"></a>10.10 The run-time type checker</H2>
+
+
+<p>
+Most scripting languages need type information at run-time.  This type information
+can include how to construct types, how to garbage collect types, and the inheritance
+relationships between types.  If the language interface does not provide its own type
+information storage, the generated SWIG code needs to provide it.
+</p>
+
+<p>
+Requirements for the type system:
+</p>
+<ul>
+<li>Store inheritance and type equivalence information and be able to correctly 
+re-create the type pointer.</li>
+<li>Share type information between modules.</li>
+<li>Modules can be loaded in any order, irregardless of actual type
+dependency.</li>
+<li>Avoid the use of dynamically allocated memory, and library/system calls in general.</li>
+<li>Provide a reasonably fast implementation, minimizing the lookup time for all
+language modules.</li>
+<li>Custom, language specific information can be attached to types.</li>
+<li>Modules can be unloaded from the type system.</li>
+</ul>
+
+<H3><a name="Typemaps_nn45"></a>10.10.1 Implementation</H3>
+
+
+<p>
+The run-time type checker is used by many, but not all, of SWIG's supported target languages.
+The run-time type checker features
+are not required and are thus not used for strongly typed languages such as Java and C#.
+The scripting and scheme based languages rely on it and it forms
+a critical part of SWIG's operation for these languages.
+</p>
+
+<p>
+When pointers, arrays, and objects are wrapped by SWIG, they are normally converted
+into typed pointer objects.  For example, an instance of <tt>Foo *</tt> might be
+a string encoded like this:
+</p>
+
+<div class="diagram">
+<pre>
+_108e688_p_Foo
+</pre>
+</div>
+
+<p>
+At a basic level, the type checker simply restores some type-safety to
+extension modules.  However, the type checker is also responsible for
+making sure that wrapped C++ classes are handled
+correctly---especially when inheritance is used.   This is especially
+important when an extension module makes use of multiple inheritance.
+For example:
+</p>
+
+<div class="code">
+<pre>
+class Foo {
+   int x;
+};
+
+class Bar {
+   int y;
+};
+
+class FooBar : public Foo, public Bar {
+   int z;
+};
+</pre>
+</div>
+
+<p>
+When the class <tt>FooBar</tt> is organized in memory, it contains the contents
+of the classes <tt>Foo</tt> and <tt>Bar</tt> as well as its own data members.  For example:
+</p>
+
+<div class="diagram">
+<pre>
+FooBar --&gt; | -----------|  &lt;-- Foo
+           |   int x    |
+           |------------|  &lt;-- Bar
+           |   int y    |
+           |------------|
+           |   int z    |
+           |------------|
+</pre>
+</div>
+
+<p>
+Because of the way that base class data is stacked together, the
+casting of a <tt>Foobar *</tt> to either of the base classes may
+change the actual value of the pointer.  This means that it is
+generally not safe to represent pointers using a simple integer or a
+bare <tt>void *</tt>---type tags are needed to implement correct
+handling of pointer values (and to make adjustments when needed).   
+</p>
+
+<p>
+In the wrapper code generated for each language, pointers are handled through
+the use of special type descriptors and conversion functions.  For example,
+if you look at the wrapper code for Python, you will see code like this:
+</p>
+
+<div class="code">
+<pre>
+if ((SWIG_ConvertPtr(obj0,(void **) &amp;arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;
+</pre>
+</div>
+
+<p>
+In this code, <tt>SWIGTYPE_p_Foo</tt> is the type descriptor that
+describes <tt>Foo *</tt>.  The type descriptor is actually a pointer to a 
+structure that contains information about the type name to use in the
+target language, a list of equivalent typenames (via typedef or
+inheritance), and pointer value handling information (if applicable).
+The <tt>SWIG_ConvertPtr()</tt> function is simply a utility function
+that takes a pointer object in the target language and a
+type-descriptor objects and uses this information to generate a C++
+pointer.  However, the exact name and calling conventions of the conversion
+function depends on the target language (see language specific chapters for details). 
+</p>
+
+<p>
+The actual type code is in swigrun.swg, and gets inserted near the top of the generated
+swig wrapper file.  The phrase "a type X that can cast into a type Y" means
+that given a type X, it can be converted into a type Y.  In other words, X is a derived
+class of Y or X is a typedef of Y.  The structure to store type information looks like this:
+</p>
+
+<div class="code">
+<pre>
+/* Structure to store information on one type */
+typedef struct swig_type_info {
+  const char *name;             /* mangled name of this type */
+  const char *str;              /* human readable name for this type */
+  swig_dycast_func dcast;       /* dynamic cast function down a hierarchy */
+  struct swig_cast_info *cast;  /* Linked list of types that can cast into this type */
+  void *clientdata;             /* Language specific type data */
+} swig_type_info;
+
+/* Structure to store a type and conversion function used for casting */
+typedef struct swig_cast_info {
+  swig_type_info *type;          /* pointer to type that is equivalent to this type */
+  swig_converter_func converter; /* function to cast the void pointers */
+  struct swig_cast_info *next;   /* pointer to next cast in linked list */
+  struct swig_cast_info *prev;   /* pointer to the previous cast */
+} swig_cast_info;
+</pre>
+</div>
+
+<p>
+Each <tt>swig_type_info</tt> stores a linked list of types that it is equivalent to.  Each entry in this
+doubly linked list stores a pointer back to another swig_type_info structure,
+along with a pointer to a conversion function.  This conversion function is used
+to solve the above problem of the FooBar class, correctly returning a pointer to
+the type we want.
+</p>
+
+<p>
+The basic problem we need to solve is verifying and building arguments passed to functions.
+So going back to the <tt>SWIG_ConvertPtr()</tt> function example from above, we are
+expecting a <tt>Foo *</tt> and need to
+check if <tt>obj0</tt> is in fact a <tt>Foo *</tt>.  From before, <tt>SWIGTYPE_p_Foo</tt> is just
+a pointer to the <tt>swig_type_info</tt> structure describing <tt>Foo *</tt>.  So we loop through the
+linked list of <tt>swig_cast_info</tt> structures attached to <tt>SWIGTYPE_p_Foo</tt>.  If we see that the type of <tt>obj0</tt> is in the
+linked list, we pass the object through the associated conversion function and
+then return a positive.  If we reach the end of the linked list without a match,
+then <tt>obj0</tt> can not be converted to a <tt>Foo *</tt> and an error is generated.
+</p>
+
+<p>
+Another issue needing to be addressed is sharing type information between multiple modules.
+More explicitly, we need
+to have ONE <tt>swig_type_info</tt> for each type.  If two modules both use the type, the
+second module loaded must lookup and use the swig_type_info structure from the module already loaded.
+Because no dynamic memory is used and the circular dependencies of the
+casting information, loading the type information is somewhat tricky, and not explained here.
+A complete description is in the <tt>Lib/swiginit.swg</tt> file (and near the top of any generated file).
+</p>
+
+<p>
+Each module has one swig_module_info structure which looks like this:
+</p>
+
+<div class="code">
+<pre>
+/* Structure used to store module information
+ * Each module generates one structure like this, and the runtime collects
+ * all of these structures and stores them in a circularly linked list.*/
+typedef struct swig_module_info {
+  swig_type_info **types;         /* Array of pointers to swig_type_info structs in this module */
+  int size;                       /* Number of types in this module */
+  struct swig_module_info *next;  /* Pointer to next element in circularly linked list */
+  swig_type_info **type_initial;  /* Array of initially generated type structures */
+  swig_cast_info **cast_initial;  /* Array of initially generated casting structures */
+  void *clientdata;               /* Language specific module data */
+} swig_module_info;
+</pre>
+</div>
+
+<p>
+Each module stores an array of pointers to <tt>swig_type_info</tt> structures and the number of
+types in this module.  So when a second module is loaded, it finds the <tt>swig_module_info</tt>
+structure for the first module and searches the array of types. If any of its own
+types are in the first module and have already been loaded, it uses those <tt>swig_type_info</tt>
+structures rather than creating new ones.  These <tt>swig_module_info</tt> 
+structures are chained together in a circularly linked list.
+</p>
+
+<H3><a name="Typemaps_nn46"></a>10.10.2 Usage</H3>
+
+
+<p>This section covers how to use these functions from typemaps.  To learn how to
+call these functions from external files (not the generated _wrap.c file), see
+the <a href="Modules.html#external_run_time">External access to the run-time system</a>
+section.</p>
+
+<p>When pointers are converted in a typemap, the typemap code often looks
+similar to this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Foo * {
+  if ((SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor)) == -1) return NULL;
+}
+</pre>
+</div>
+
+<p>
+The most critical part is the typemap is the use of the <tt>$1_descriptor</tt>
+special variable.  When placed in a typemap, this is expanded into the
+<tt>SWIGTYPE_*</tt> type descriptor object above.  As a general rule,
+you should always use <tt>$1_descriptor</tt> instead of trying to
+hard-code the type descriptor name directly.
+</p>
+
+<p>
+There is another reason why you should always use the
+<tt>$1_descriptor</tt> variable.  When this special variable is
+expanded, SWIG marks the corresponding type as "in use."  When
+type-tables and type information is emitted in the wrapper file,
+descriptor information is only generated for those datatypes that were
+actually used in the interface.  This greatly reduces the size of the
+type tables and improves efficiency. 
+</p>
+
+<p>
+Occasionally, you might need to write a typemap that needs to convert
+pointers of other types.  To handle this, a special macro substitution
+<tt>$descriptor(type)</tt> can be used to generate the SWIG type
+descriptor name for any C datatype.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) Foo * {
+  if ((SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor)) == -1) {
+     Bar *temp;
+     if ((SWIG_ConvertPtr($input, (void **) &amp;temp, <b>$descriptor(Bar *)</b>) == -1) {
+         return NULL;
+     }
+     $1 = (Foo *) temp;
+  }
+}
+</pre>
+</div>
+
+<p>
+The primary use of <tt>$descriptor(type)</tt> is when writing typemaps for container
+objects and other complex data structures.  There are some restrictions on the argument---namely it must
+be a fully defined C datatype.  It can not be any of the special typemap variables.
+</p>
+
+<p>
+In certain cases, SWIG may not generate type-descriptors like you expect.  For example,
+if you are converting pointers in some non-standard way or working with an unusual
+combination of interface files and modules, you may find that SWIG omits information
+for a specific type descriptor.  To fix this, you may need to use the <tt>%types</tt> directive.
+For example:
+</p>
+
+<div class="code">
+<pre>
+%types(int *, short *, long *, float *, double *);
+</pre>
+</div>
+
+<p>
+When <tt>%types</tt> is used, SWIG generates type-descriptor
+information even if those datatypes never appear elsewhere in the
+interface file.
+</p>
+
+<p>
+Further details about the run-time type checking can be found in the documentation for
+individual language modules.   Reading the source code may also help.  The file
+<tt>Lib/swigrun.swg</tt> in the SWIG library contains all of the source code for 
+type-checking.  This code is also included in every generated wrapped file so you
+probably just look at the output of SWIG to get a better sense for how types are
+managed.
+</p>
+
+<H2><a name="Typemaps_overloading"></a>10.11 Typemaps and overloading</H2>
+
+
+<p>
+In many target languages, SWIG fully supports C++ overloaded methods and functions.   For example,
+if you have a collection of functions like this:
+</p>
+
+<div class="code">
+<pre>
+int foo(int x);
+int foo(double x);
+int foo(char *s, int y);
+</pre>
+</div>
+
+<p>
+You can access the functions in a normal way from the scripting interpreter:
+</p>
+
+<div class="targetlang">
+<pre>
+# Python
+foo(3)           # foo(int)
+foo(3.5)         # foo(double)
+foo("hello",5)   # foo(char *, int)
+
+# Tcl
+foo 3            # foo(int)
+foo 3.5          # foo(double)
+foo hello 5      # foo(char *, int)
+</pre>
+</div>
+
+<p>
+To implement overloading, SWIG generates a separate wrapper function for each overloaded method.
+For example, the above functions would produce something roughly like this:
+</p>
+
+<div class="code">
+<pre>
+// wrapper pseudocode
+_wrap_foo_0(argc, args[]) {       // foo(int)
+   int arg1;
+   int result;
+   ...
+   arg1 = FromInteger(args[0]);
+   result = foo(arg1);
+   return ToInteger(result);
+}
+
+_wrap_foo_1(argc, args[]) {       // foo(double)
+   double arg1;
+   int result;
+   ...
+   arg1 = FromDouble(args[0]);
+   result = foo(arg1);
+   return ToInteger(result);
+}
+
+_wrap_foo_2(argc, args[]) {       // foo(char *, int)
+   char *arg1;
+   int   arg2;
+   int result;
+   ...
+   arg1 = FromString(args[0]);
+   arg2 = FromInteger(args[1]);
+   result = foo(arg1,arg2);
+   return ToInteger(result);
+}
+
+</pre>
+</div>
+
+<p>
+Next, a dynamic dispatch function is generated:
+</p>
+
+<div class="code">
+<pre>
+_wrap_foo(argc, args[]) {
+   if (argc == 1) {
+       if (IsInteger(args[0])) {
+           return _wrap_foo_0(argc,args);
+       } 
+       if (IsDouble(args[0])) {
+           return _wrap_foo_1(argc,args);
+       }
+   }
+   if (argc == 2) {
+       if (IsString(args[0]) &amp;&amp; IsInteger(args[1])) {
+          return _wrap_foo_2(argc,args);
+       }
+   }
+   error("No matching function!\n");
+}
+</pre>
+</div>
+
+<p>
+The purpose of the dynamic dispatch function is to select the appropriate C++ function based on 
+argument types---a task that must be performed at runtime in most of SWIG's target languages.
+</p>
+
+<p>
+The generation of the dynamic dispatch function is a relatively tricky affair.  Not only must input typemaps
+be taken into account (these typemaps can radically change the types of arguments accepted), but overloaded
+methods must also be sorted and checked in a very specific order to resolve potential ambiguity.   A high-level
+overview of this ranking process is found in the "<a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>" chapter.    What isn't mentioned in that chapter
+is the mechanism by which it is implemented---as a collection of typemaps.
+</p>
+
+<p>
+To support dynamic dispatch, SWIG first defines a general purpose type hierarchy as follows:
+</p>
+
+<div class="diagram">
+<pre>
+Symbolic Name                   Precedence Value
+------------------------------  ------------------
+SWIG_TYPECHECK_POINTER           0  
+SWIG_TYPECHECK_VOIDPTR           10 
+SWIG_TYPECHECK_BOOL              15 
+SWIG_TYPECHECK_UINT8             20 
+SWIG_TYPECHECK_INT8              25 
+SWIG_TYPECHECK_UINT16            30 
+SWIG_TYPECHECK_INT16             35 
+SWIG_TYPECHECK_UINT32            40 
+SWIG_TYPECHECK_INT32             45 
+SWIG_TYPECHECK_UINT64            50 
+SWIG_TYPECHECK_INT64             55 
+SWIG_TYPECHECK_UINT128           60 
+SWIG_TYPECHECK_INT128            65 
+SWIG_TYPECHECK_INTEGER           70 
+SWIG_TYPECHECK_FLOAT             80 
+SWIG_TYPECHECK_DOUBLE            90 
+SWIG_TYPECHECK_COMPLEX           100 
+SWIG_TYPECHECK_UNICHAR           110 
+SWIG_TYPECHECK_UNISTRING         120 
+SWIG_TYPECHECK_CHAR              130 
+SWIG_TYPECHECK_STRING            140 
+SWIG_TYPECHECK_BOOL_ARRAY        1015 
+SWIG_TYPECHECK_INT8_ARRAY        1025 
+SWIG_TYPECHECK_INT16_ARRAY       1035 
+SWIG_TYPECHECK_INT32_ARRAY       1045 
+SWIG_TYPECHECK_INT64_ARRAY       1055 
+SWIG_TYPECHECK_INT128_ARRAY      1065 
+SWIG_TYPECHECK_FLOAT_ARRAY       1080 
+SWIG_TYPECHECK_DOUBLE_ARRAY      1090 
+SWIG_TYPECHECK_CHAR_ARRAY        1130 
+SWIG_TYPECHECK_STRING_ARRAY      1140 
+</pre>
+</div>
+
+<p>
+(These precedence levels are defined in <tt>swig.swg</tt>, a library file that's included by all target language modules.)
+</p>
+
+<p>
+In this table, the precedence-level determines the order in which types are going to be checked.  Low values
+are always checked before higher values.  For example, integers are checked before floats, single values are checked
+before arrays, and so forth.
+</p>
+
+<p>
+Using the above table as a guide, each target language defines a collection of "typecheck" typemaps. 
+The follow excerpt from the Python module illustrates this:
+</p>
+
+<div class="code">
+<pre>
+/* Python type checking rules */
+/* Note:  %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 int, short, long,
+ 	 unsigned int, unsigned short, unsigned long,
+	 signed char, unsigned char,
+	 long long, unsigned long long,
+	 const int &amp;, const short &amp;, const long &amp;,
+ 	 const unsigned int &amp;, const unsigned short &amp;, const unsigned long &amp;,
+	 const long long &amp;, const unsigned long long &amp;,
+	 enum SWIGTYPE,
+         bool, const bool &amp; 
+{
+  $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE)
+	float, double,
+	const float &amp;, const double &amp;
+{
+  $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_CHAR) char {
+  $1 = (PyString_Check($input) &amp;&amp; (PyString_Size($input) == 1)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char * {
+  $1 = PyString_Check($input) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [] {
+  void *ptr;
+  if (SWIG_ConvertPtr($input, (void **) &amp;ptr, $1_descriptor, 0) == -1) {
+    $1 = 0;
+    PyErr_Clear();
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
+  void *ptr;
+  if (SWIG_ConvertPtr($input, (void **) &amp;ptr, $&amp;1_descriptor, 0) == -1) {
+    $1 = 0;
+    PyErr_Clear();
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  if (SWIG_ConvertPtr($input, (void **) &amp;ptr, 0, 0) == -1) {
+    $1 = 0;
+    PyErr_Clear();
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) PyObject *
+{
+  $1 = ($input != 0);
+}
+</pre>
+</div>
+
+<p>
+It might take a bit of contemplation, but this code has merely organized all of the basic C++ types, provided some simple type-checking
+code, and assigned each type a precedence value.
+</p>
+
+<p>
+Finally, to generate the dynamic dispatch function, SWIG uses the following algorithm:
+</p>
+
+<ul>
+<li>Overloaded methods are first sorted by the number of required arguments.</li>
+<li>Methods with the same number of arguments are then sorted by precedence values of argument types.</li>
+<li>Typecheck typemaps are then emitted to produce a dispatch function that checks arguments in the correct order.</li>
+</ul>
+
+<p>
+If you haven't written any typemaps of your own, it is unnecessary to worry about the typechecking rules.
+However, if you have written new input typemaps, you might have to supply a typechecking rule as well.
+An easy way to do this is to simply copy one of the existing typechecking rules. 
+Here is an example,
+</p>
+
+<div class="code">
+<pre>
+// Typemap for a C++ string
+%typemap(in) std::string {
+    if (PyString_Check($input)) {
+         $1 = std::string(PyString_AsString($input));
+     } else {
+         SWIG_exception(SWIG_TypeError, "string expected");
+     }
+}
+// Copy the typecheck code for "char *".  
+%typemap(typecheck) std::string = char *;
+</pre>
+</div>
+
+<p>
+The bottom line:  If you are writing new typemaps and you are using overloaded methods, you will probably 
+have to write typecheck code or copy existing code.   Since this is a relatively new SWIG feature, there are
+few examples to work with.  However, you might look at some of the existing library files likes 'typemaps.i' for
+a guide.
+</p>
+
+<p>
+<b>Notes:</b>
+</p>
+
+<ul>
+<li>Typecheck typemaps are not used for non-overloaded methods.  Because of this, it is
+still always necessary to check types in any "in" typemaps.
+</li>
+
+<li>The dynamic dispatch process is only meant to be a heuristic.  There are many corner
+cases where SWIG simply can't disambiguate types to the same degree as C++.   The only way to
+resolve this ambiguity is to use the %rename directive to rename one of the overloaded methods (effectively
+eliminating overloading).
+</li>
+
+<li>
+Typechecking may be partial.  For example, if working with arrays, the typecheck code might 
+simply check the type of the first array element and use that to dispatch to the correct function.
+Subsequent "in" typemaps would then perform more extensive type-checking.
+</li>
+
+<li>Make sure you read the section on overloading in the "<a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>" chapter.
+</li>
+</ul>
+
+<H2><a name="Typemaps_nn48"></a>10.12 More about <tt>%apply</tt> and <tt>%clear</tt></H2>
+
+
+<p>
+In order to implement certain kinds of program behavior, it is sometimes necessary to
+write sets of typemaps.  For example, to support output arguments, one often writes
+a set of typemaps like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in,numinputs=0) int *OUTPUT (int temp) {
+   $1 = &amp;temp;
+}
+%typemap(argout) int *OUTPUT {
+   // return value somehow
+}
+</pre>
+</div>
+
+<p>
+To make it easier to apply the typemap to different argument types and names, the <tt>%apply</tt> directive
+performs a copy of all typemaps from one type to another.  For example, if you specify this,
+</p>
+
+<div class="code">
+<pre>
+%apply int *OUTPUT { int *retvalue, int32 *output };
+</pre>
+</div>
+
+<p>
+then all of the <tt>int *OUTPUT</tt> typemaps are copied to <tt>int *retvalue</tt> and <tt>int32 *output</tt>.
+</p>
+
+<p>
+However, there is a subtle aspect of <tt>%apply</tt> that needs more description.  Namely, <tt>%apply</tt> does not
+overwrite a typemap rule if it is already defined for the target datatype.   This behavior allows you to do two things:
+</p>
+
+<ul>
+<li>You can specialize parts of a complex typemap rule by first defining a few typemaps and then using
+<tt>%apply</tt> to incorporate the remaining pieces.
+</li>
+
+<li>Sets of different typemaps can be applied to the same datatype using repeated <tt>%apply</tt> directives.
+</li>
+</ul>
+
+<p>
+For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int *INPUT (int temp) {
+   temp = ... get value from $input ...;
+   $1 = &amp;temp;
+}
+
+%typemap(check) int *POSITIVE {
+   if (*$1 &lt;= 0) {
+      SWIG_exception(SWIG_ValueError,"Expected a positive number!\n");
+      return NULL;
+   }
+}
+
+...
+%apply int *INPUT     { int *invalue };
+%apply int *POSITIVE  { int *invalue };
+</pre>
+</div>
+
+<p>
+Since <tt>%apply</tt> does not overwrite or replace any existing rules, the only way to reset behavior is to
+use the <tt>%clear</tt> directive.  <tt>%clear</tt> removes all typemap rules defined for a specific datatype.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+%clear int *invalue;
+</pre>
+</div>
+
+<H2><a name="Typemaps_nn49"></a>10.13 Reducing wrapper code size</H2>
+
+
+<p>
+Since the code supplied to a typemap is inlined directly into wrapper functions, typemaps can result
+in a tremendous amount of code bloat.  For example, consider this typemap for an array:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) float [ANY] {
+  int i;
+  if (!PySequence_Check($input)) {
+    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
+    return NULL;
+  }
+  if (PySequence_Length($input) != $1_dim0) {
+    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
+    return NULL;
+  }
+  $1 = (float) malloc($1_dim0*sizeof(float));
+  for (i = 0; i &lt; $1_dim0; i++) {
+    PyObject *o = PySequence_GetItem($input,i);
+    if (PyNumber_Check(o)) {
+      $1[i] = (float) PyFloat_AsDouble(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
+      free(result);
+      return NULL;
+    }
+  }
+}
+</pre>
+</div>
+
+<p>
+If you had a large interface with hundreds of functions all accepting
+array parameters, this typemap would be replicated
+repeatedly--generating a huge amount of code.  A better approach might
+be to consolidate some of the typemap into a function.  For example:
+</p>
+
+<div class="code">
+<pre>
+%{
+/* Define a helper function */
+static float *
+convert_float_array(PyObject *input, int size) {
+  int i;
+  float *result;
+  if (!PySequence_Check(input)) {
+    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
+    return NULL;
+  }
+  if (PySequence_Length(input) != size) {
+    PyErr_SetString(PyExc_ValueError,"Size mismatch. ");
+    return NULL;
+  }
+  result = (float) malloc(size*sizeof(float));
+  for (i = 0; i &lt; size; i++) {
+    PyObject *o = PySequence_GetItem(input,i);
+    if (PyNumber_Check(o)) {
+      result[i] = (float) PyFloat_AsDouble(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
+      free(result);       
+      return NULL;
+    }
+  }
+  return result;
+}
+%}
+
+%typemap(in) float [ANY] {
+    $1 = convert_float_array($input, $1_dim0);
+    if (!$1) return NULL;
+}
+%}
+</pre>
+</div>
+
+<H2><a name="Typemaps_nn47"></a>10.14 Passing data between typemaps</H2>
+
+
+<p>
+It is also important to note that the primary use of local variables
+is to create stack-allocated objects for temporary use inside a
+wrapper function (this is faster and less-prone to error than
+allocating data on the heap).  In general, the variables are not intended
+to pass information between different types of typemaps.  However, this
+can be done if you realize that local names have the argument number appended
+to them.  For example, you could do this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) int *(int temp) {
+   temp = (int) PyInt_AsLong($input);
+   $1 = &amp;temp;
+}
+
+%typemap(argout) int * {
+   PyObject *o = PyInt_FromLong(temp$argnum);
+   ...
+}
+</pre>
+</div>
+
+<p>
+In this case, the <tt>$argnum</tt> variable is expanded into the argument
+number.  Therefore, the code will reference the appropriate local
+such as <tt>temp1</tt> and <tt>temp2</tt>.   It should be noted that there are 
+plenty of opportunities to break the universe here and that accessing locals
+in this manner should probably be avoided.  At the very least, you should make
+sure that the typemaps sharing information have exactly the same types and names.
+</p>
+
+
+<H2><a name="Typemaps_nn51"></a>10.15 Where to go for more information?</H2>
+
+
+<p>
+The
+best place to find out more information about writing typemaps is to
+look in the SWIG library.  Most language modules define all of their
+default behavior using typemaps.  These are found in files such as
+<tt>python.swg</tt>, <tt>perl5.swg</tt>, <tt>tcl8.swg</tt> and so
+forth.  The <tt>typemaps.i</tt> file in the library also contains
+numerous examples.   You should look at these files to get a feel
+for how to define typemaps of your own.
+Some of the language modules support additional typemaps and further
+information is available in the individual chapters for each target language.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Varargs.html b/trunk/Doc/Manual/Varargs.html
new file mode 100644
index 0000000..f40a1ff
--- /dev/null
+++ b/trunk/Doc/Manual/Varargs.html
@@ -0,0 +1,925 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Variable Length Arguments</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Varargs"></a>13 Variable Length Arguments</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Varargs_nn2">Introduction</a>
+<li><a href="#Varargs_nn3">The Problem</a>
+<li><a href="#Varargs_nn4">Default varargs support</a>
+<li><a href="#Varargs_nn5">Argument replacement using %varargs</a>
+<li><a href="#Varargs_nn6">Varargs and typemaps</a>
+<li><a href="#Varargs_nn7">Varargs wrapping with libffi</a>
+<li><a href="#Varargs_nn8">Wrapping of va_list</a>
+<li><a href="#Varargs_nn9">C++ Issues</a>
+<li><a href="#Varargs_nn10">Discussion</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+<b>(a.k.a, "The horror. The horror.")</b>
+</p>
+
+<p>
+This chapter describes the problem of wrapping functions that take a
+variable number of arguments. For instance, generating wrappers for
+the C <tt>printf()</tt> family of functions.
+</p>
+
+<p>
+This topic is sufficiently advanced to merit its own chapter.  In
+fact, support for varargs is an often requested feature that was first
+added in SWIG-1.3.12.  Most other wrapper generation tools have
+wisely chosen to avoid this issue.
+</p>
+
+<H2><a name="Varargs_nn2"></a>13.1 Introduction</H2>
+
+
+<p>
+Some C and C++ programs may include functions that accept a variable
+number of arguments.  For example, most programmers are
+familiar with functions from the C library such as the following:
+</p>
+
+<div class="code">
+<pre>
+int printf(const char *fmt, ...)
+int fprintf(FILE *, const char *fmt, ...);
+int sprintf(char *s, const char *fmt, ...);
+</pre>
+</div>
+
+<p>
+Although there is probably little practical purpose in wrapping these
+specific C library functions in a scripting language (what would be the
+point?), a library may include its own set of special functions based
+on a similar API. For example:
+</p>
+
+<div class="code">
+<pre>
+int  traceprintf(const char *fmt, ...);
+</pre>
+</div>
+
+<p>
+In this case, you may want to have some kind of access from the target language.
+</p>
+
+<p>
+Before describing the SWIG implementation, it is important to discuss
+the common uses of varargs that you are likely to encounter in real
+programs.  Obviously, there are the <tt>printf()</tt> style output
+functions as shown.  Closely related to this would be
+<tt>scanf()</tt> style input functions that accept a format string and a
+list of pointers into which return values are placed.  However, variable
+length arguments are also sometimes used to write functions that accept a
+NULL-terminated list of pointers.  A good example of this would 
+be a function like this:
+</p>
+
+<div class="code">
+<pre>
+int execlp(const char *path, const char *arg1, ...);
+...
+
+/* Example */
+execlp("ls","ls","-l",NULL);
+</pre>
+</div>
+
+<p>
+In addition, varargs is sometimes used to fake default arguments in older
+C libraries.   For instance, the low level <tt>open()</tt> system call
+is often declared as a varargs function so that it will accept two
+or three arguments:
+</p>
+
+<div class="code">
+<pre>
+int open(const char *path, int oflag, ...);
+...
+
+/* Examples */
+f = open("foo", O_RDONLY);
+g = open("bar", O_WRONLY | O_CREAT, 0644);
+</pre>
+</div>
+
+<p>
+Finally, to implement a varargs function, recall that you have to use
+the C library functions defined in <tt>&lt;stdarg.h&gt;</tt>.  For
+example:
+</p>
+
+<div class="code">
+<pre>
+List make_list(const char *s, ...) {
+    va_list ap;
+    List    x;
+    ...
+    va_start(ap, s);
+    while (s) {
+       x.append(s);
+       s = va_arg(ap, const char *);
+    }
+    va_end(ap);
+    return x;
+}
+</pre>
+</div>
+
+<H2><a name="Varargs_nn3"></a>13.2 The Problem</H2>
+
+
+<p>
+Generating wrappers for a variable length argument function presents a
+number of special challenges.  Although C provides support for
+implementing functions that receive variable length arguments, there
+are no functions that can go in the other direction.  Specifically,
+you can't write a function that dynamically creates a list of
+arguments and which invokes a varargs function on your behalf.
+</p>
+
+<p>
+Although it is possible to write functions that accept the special
+type <tt>va_list</tt>, this is something entirely different.  You
+can't take a <tt>va_list</tt> structure and pass it in place of the
+variable length arguments to another varargs function.  It just
+doesn't work.
+</p>
+
+<p>
+The reason this doesn't work has to do with the way that function
+calls get compiled. For example, suppose that your program has a function call like this:
+</p>
+
+<div class="code">
+<pre>
+printf("Hello %s. Your number is %d\n", name, num);
+</pre>
+</div>
+
+<p>
+When the compiler looks at this, it knows that you are calling
+<tt>printf()</tt> with exactly three arguments.  Furthermore, it knows
+that the number of arguments as well are their types and sizes is
+<em>never</em> going to change during program execution.  Therefore,
+this gets turned to machine code that sets up a three-argument stack
+frame followed by a call to <tt>printf()</tt>.
+</p>
+
+<p>
+In contrast, suppose you attempted to make some kind of wrapper around
+<tt>printf()</tt> using code like this:
+</p>
+
+<div class="code">
+<pre>
+int wrap_printf(const char *fmt, ...) {
+   va_list ap;
+   va_start(ap,fmt);
+   ...
+   printf(fmt,ap);
+   ...
+   va_end(ap);
+};
+</pre>
+</div>
+
+<p>
+Although this code might compile, it won't do what you expect. This is
+because the call to <tt>printf()</tt> is compiled as a procedure call
+involving only two arguments.  However, clearly a two-argument
+configuration of the call stack is completely wrong if your intent is
+to pass an arbitrary number of arguments to the real
+<tt>printf()</tt>.  Needless to say, it won't work.
+</p>
+
+<p>
+Unfortunately, the situation just described is exactly the problem
+faced by wrapper generation tools.  In general, the number of passed
+arguments will not be known until run-time.  To make matters even
+worse, you won't know the types and sizes of arguments until run-time
+as well.  Needless to say, there is no obvious way to make the C
+compiler generate code for a function call involving an unknown number
+of arguments of unknown types.
+</p>
+
+<p>
+In theory, it <em>is</em> possible to write a wrapper that does the right thing.
+However, this involves knowing the underlying ABI for the target platform and language
+as well as writing special purpose code that manually constructed the call stack before 
+making a procedure call.  Unfortunately, both of these tasks require the use of inline
+assembly code.  Clearly, that's the kind of solution you would much rather avoid.
+</p>
+
+<p>
+With this nastiness in mind, SWIG provides a number of solutions to the varargs 
+wrapping problem.  Most of these solutions are compromises that provide limited
+varargs support without having to resort to assembly language.   However, SWIG
+can also support real varargs wrapping (with stack-frame manipulation) if you
+are willing to get hands dirty.  Keep reading.
+</p>
+
+<H2><a name="Varargs_nn4"></a>13.3 Default varargs support</H2>
+
+
+<p>
+When variable length arguments appear in an interface, the default
+behavior is to drop the variable argument list entirely, replacing
+them with a single NULL pointer.  For example, if you had this
+function,
+</p>
+
+<div class="code">
+<pre>
+void traceprintf(const char *fmt, ...);
+</pre>
+</div>
+
+<p>
+it would be wrapped as if it had been declared as follows:
+</p>
+
+<div class="code">
+<pre>
+void traceprintf(const char *fmt);
+</pre>
+</div>
+
+<p>
+When the function is called inside the wrappers, it is called as follows:
+</p>
+
+<div class="code">
+<pre>
+traceprintf(arg1, NULL);
+</pre>
+</div>
+
+<p>
+Arguably, this approach seems to defeat the whole point of variable length arguments.  However,
+this actually provides enough support for many simple kinds of varargs functions to still be useful.  For
+instance, you could make function calls like this (in Python):
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; traceprintf("Hello World")
+&gt;&gt;&gt; traceprintf("Hello %s. Your number is %d\n" % (name, num))
+</pre>
+</div>
+
+<p>
+Notice how string formatting is being done in Python instead of C. 
+</p>
+
+<H2><a name="Varargs_nn5"></a>13.4 Argument replacement using %varargs</H2>
+
+
+<p>
+Instead of dropping the variable length arguments, an alternative approach is to replace
+<tt>(...)</tt> with a set of suitable arguments.   SWIG provides a special <tt>%varargs</tt> directive 
+that can be used to do this.  For example,
+</p>
+
+<div class="code">
+<pre>
+%varargs(int mode = 0) open;
+...
+int open(const char *path, int oflags, ...);
+</pre>
+</div>
+
+<p>
+is equivalent to this:
+</p>
+
+<div class="code">
+<pre>
+int open(const char *path, int oflags, int mode = 0);
+</pre>
+</div>
+
+<p>
+In this case, <tt>%varargs</tt> is simply providing more specific information about the
+extra arguments that might be passed to a function.  
+If the parameters to a varargs function are of uniform type, <tt>%varargs</tt> can also
+accept a numerical argument count as follows:
+</p>
+
+<div class="code">
+<pre>
+%varargs(10,char *arg = NULL) execlp;
+...
+int execlp(const char *path, const char *arg1, ...);
+</pre>
+</div>
+
+<p>
+This would wrap <tt>execlp()</tt> as a function that accepted up to 10 optional arguments.
+Depending on the application, this may be more than enough for practical purposes.
+</p>
+
+<p>
+Argument replacement is most appropriate in cases where the types of
+the extra arguments is uniform and the maximum number of arguments is
+known.  When replicated argument replacement is used, at least one extra
+argument is added to the end of the arguments when making the function call. 
+This argument serves as a sentinel to make sure the list is properly terminated.
+It has the same value as that supplied to the <tt>%varargs</tt> directive.
+</p>
+
+<p>
+Argument replacement is not as useful when working with functions that accept
+mixed argument types such as <tt>printf()</tt>.  Providing general purpose
+wrappers to such functions presents special problems (covered shortly).  
+</p>
+
+<H2><a name="Varargs_nn6"></a>13.5 Varargs and typemaps</H2>
+
+
+<p>
+Variable length arguments may be used in typemap specifications.  For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (...) {
+    // Get variable length arguments (somehow)
+    ...
+}
+
+%typemap(in) (const char *fmt, ...) {
+    // Multi-argument typemap
+}
+</pre>
+</div>
+
+<p>
+However, this immediately raises the question of what "type" is actually used
+to represent <tt>(...)</tt>.  For lack of a better alternative, the type of
+<tt>(...)</tt> is set to <tt>void *</tt>.  Since there is no
+way to dynamically pass arguments to a varargs function (as previously described),
+the <tt>void *</tt> argument value is intended to serve as a place holder
+for storing some kind of information about the extra arguments (if any).  In addition, the
+default behavior of SWIG is to pass the <tt>void *</tt> value as an argument to
+the function.  Therefore, you could use the pointer to hold a valid argument value if you wanted.
+</p>
+
+<p>
+To illustrate, here is a safer version of wrapping <tt>printf()</tt> in Python:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (const char *fmt, ...) {
+    $1 = "%s";                                /* Fix format string to %s */
+    $2 = (void *) PyString_AsString($input);  /* Get string argument */
+};
+...
+int printf(const char *fmt, ...);
+</pre>
+</div>
+
+<p>
+In this example, the format string is implicitly set to <tt>"%s"</tt>.
+This prevents a program from passing a bogus format string to the
+extension.  Then, the passed input object is decoded and placed in the
+<tt>void *</tt> argument defined for the <tt>(...)</tt> argument.  When the
+actual function call is made, the underlying wrapper code will look roughly
+like this:
+</p>
+
+<div class="code">
+<pre>
+wrap_printf() {
+   char *arg1;
+   void *arg2;
+   int   result;
+
+   arg1 = "%s";
+   arg2 = (void *) PyString_AsString(arg2obj);
+   ...
+   result = printf(arg1,arg2);
+   ...
+}
+</pre>
+</div>
+
+<p>
+Notice how both arguments are passed to the function and it does what you
+would expect. 
+</p>
+
+<p>
+The next example illustrates a more advanced kind of varargs typemap.
+Disclaimer: this requires special support in the target language module and is not
+guaranteed to work with all SWIG modules at this time.  It also starts to illustrate
+some of the more fundamental problems with supporting varargs in more generality.
+</p>
+
+<p>
+If a typemap is defined for any form of <tt>(...)</tt>, many SWIG
+modules will generate wrappers that accept a variable number of
+arguments as input and will make these arguments available in some
+form.  The precise details of this depends on the language module
+being used (consult the appropriate chapter for more details).
+However, suppose that you wanted to create a Python wrapper for the
+<tt>execlp()</tt> function shown earlier.  To do this using a typemap
+instead of using <tt>%varargs</tt>, you might first write a typemap
+like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in) (...)(char *args[10]) {
+    int i;
+    int argc;
+    for (i = 0; i &lt; 10; i++) args[i] = 0;
+    argc = PyTuple_Size(varargs);
+    if (argc &gt; 10) {
+       PyErr_SetString(PyExc_ValueError,"Too many arguments");
+       return NULL;
+    }
+    for (i = 0; i &lt; argc; i++) {
+       PyObject *o = PyTuple_GetItem(varargs,i);
+       if (!PyString_Check(o)) {
+           PyErr_SetString(PyExc_ValueError,"Expected a string");
+           return NULL;
+       }
+       args[i] = PyString_AsString(o);
+    }
+    $1 = (void *) args;
+}
+</pre>
+</div>
+
+<p>
+In this typemap, the special variable <tt>varargs</tt> is a tuple
+holding all of the extra arguments passed (this is specific to the
+Python module).  The typemap then pulls this apart and sticks the
+values into the array of strings <tt>args</tt>.  Then, the array is
+assigned to <tt>$1</tt> (recall that this is the <tt>void *</tt>
+variable corresponding to <tt>(...)</tt>).  However, this assignment
+is only half of the picture----clearly this alone is not enough to
+make the function work.  To patch everything up, you have to rewrite the
+underlying action code using the <tt>%feature</tt> directive like
+this:
+</p>
+
+<div class="code">
+<pre>
+%feature("action") execlp {
+   char *args = (char **) arg3;
+   result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4],
+                   args[5],args[6],args[7],args[8],args[9], NULL);
+}
+
+int execlp(const char *path, const char *arg, ...);
+</pre>
+</div>
+
+<p>
+This patches everything up and creates a function that more or less
+works.  However, don't try explaining this to your coworkers unless
+you know for certain that they've had several cups of coffee.  If you
+really want to elevate your guru status and increase your job
+security, continue to the next section.
+</p>
+
+<H2><a name="Varargs_nn7"></a>13.6 Varargs wrapping with libffi</H2>
+
+
+<p>
+All of the previous examples have relied on features of SWIG that are
+portable and which don't rely upon any low-level machine-level
+details.  In many ways, they have all dodged the real issue of variable
+length arguments by recasting a varargs function into some weaker variation
+with a fixed number of arguments of known types.  In many cases, this
+works perfectly fine.  However, if you want more generality than this,
+you need to bring out some bigger guns.
+</p>
+
+<p>
+One way to do this is to use a special purpose library such as libffi
+(<a
+href="http://sources.redhat.com/libffi/">http://sources.redhat.com/libffi</a>).
+libffi is a library that allows you to dynamically construct
+call-stacks and invoke procedures in a relatively platform independent
+manner.  Details about the library can be found in the libffi
+distribution and are not repeated here.
+</p>
+
+<p>
+To illustrate the use of libffi, suppose that you <em>really</em> wanted to create a
+wrapper for <tt>execlp()</tt> that accepted <em>any</em> number of
+arguments.  To do this, you might make a few adjustments to the previous
+example. For example:
+</p>
+
+<div class="code">
+<pre>
+/* Take an arbitrary number of extra arguments and place into an array
+   of strings */
+
+%typemap(in) (...) {
+   char **argv;
+   int    argc;
+   int    i;
+
+   argc = PyTuple_Size(varargs);
+   argv = (char **) malloc(sizeof(char *)*(argc+1));
+   for (i = 0; i &lt; argc; i++) {
+      PyObject *o = PyTuple_GetItem(varargs,i);
+      if (!PyString_Check(o)) {
+          PyErr_SetString(PyExc_ValueError,"Expected a string");
+	  free(argv);
+          return NULL;
+      }
+      argv[i] = PyString_AsString(o);
+   }
+   argv[i] = NULL;
+   $1 = (void *) argv;
+}
+
+/* Rewrite the function call, using libffi */    
+
+%feature("action") execlp {
+  int       i, vc;
+  ffi_cif   cif;
+  ffi_type  **types;
+  void      **values;
+  char      **args;
+
+  vc = PyTuple_Size(varargs);
+  types  = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *));
+  values = (void **) malloc((vc+3)*sizeof(void *));
+  args   = (char **) arg3;
+
+  /* Set up path parameter */
+  types[0] = &amp;ffi_type_pointer;
+  values[0] = &amp;arg1;
+  
+  /* Set up first argument */
+  types[1] = &amp;ffi_type_pointer;
+  values[1] = &amp;arg2;
+
+  /* Set up rest of parameters */
+  for (i = 0; i &lt;= vc; i++) {
+    types[2+i] = &amp;ffi_type_pointer;
+    values[2+i] = &amp;args[i];
+  }
+  if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+3,
+                   &amp;ffi_type_uint, types) == FFI_OK) {
+    ffi_call(&amp;cif, (void (*)()) execlp, &amp;result, values);
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
+    free(types);
+    free(values);
+    free(arg3);
+    return NULL;
+  }
+  free(types);
+  free(values);
+  free(arg3);
+}
+
+/* Declare the function. Whew! */
+int execlp(const char *path, const char *arg1, ...);
+</pre>
+</div>
+
+<p>
+Looking at this example, you may start to wonder if SWIG is making
+life any easier.  Given the amount of code involved, you might also wonder
+why you didn't just write a hand-crafted wrapper!  Either that or you're wondering
+"why in the hell am I trying to wrap this varargs function in the 
+first place?!?"  Obviously, those are questions you'll have to answer for yourself.
+</p>
+
+<p>
+As a more extreme example of libffi, here is some code that attempts to wrap <tt>printf()</tt>,
+</p>
+
+<div class="code">
+<pre>
+/* A wrapper for printf() using libffi */
+
+%{
+/* Structure for holding passed arguments after conversion */
+  typedef struct {
+    int type;
+    union {
+      int    ivalue;
+      double dvalue;
+      void   *pvalue;
+    } val;
+  } vtype;
+  enum { VT_INT, VT_DOUBLE, VT_POINTER };
+%}
+
+%typemap(in) (const char *fmt, ...) {
+  vtype *argv;
+  int    argc;
+  int    i;
+
+  /* Format string */
+  $1 = PyString_AsString($input);
+
+  /* Variable length arguments */
+  argc = PyTuple_Size(varargs);
+  argv = (vtype *) malloc(argc*sizeof(vtype));
+  for (i = 0; i &lt; argc; i++) {
+    PyObject *o = PyTuple_GetItem(varargs,i);
+    if (PyInt_Check(o)) {
+      argv[i].type = VT_INT;
+      argv[i].val.ivalue = PyInt_AsLong(o);
+    } else if (PyFloat_Check(o)) {
+      argv[i].type = VT_DOUBLE;
+      argv[i].val.dvalue = PyFloat_AsDouble(o);
+    } else if (PyString_Check(o)) {
+      argv[i].type = VT_POINTER;
+      argv[i].val.pvalue = (void *) PyString_AsString(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
+      free(argv);
+      return NULL;
+    }
+  }
+  $2 = (void *) argv;
+}
+
+/* Rewrite the function call using libffi */    
+%feature("action") printf {
+  int       i, vc;
+  ffi_cif   cif;
+  ffi_type  **types;
+  void      **values;
+  vtype     *args;
+
+  vc = PyTuple_Size(varargs);
+  types  = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *));
+  values = (void **) malloc((vc+1)*sizeof(void *));
+  args   = (vtype *) arg2;
+
+  /* Set up fmt parameter */
+  types[0] = &amp;ffi_type_pointer;
+  values[0] = &amp;arg1;
+
+  /* Set up rest of parameters */
+  for (i = 0; i &lt; vc; i++) {
+    switch(args[i].type) {
+    case VT_INT:
+      types[1+i] = &amp;ffi_type_uint;
+      values[1+i] = &amp;args[i].val.ivalue;
+      break;
+    case VT_DOUBLE:
+      types[1+i] = &amp;ffi_type_double;
+      values[1+i] = &amp;args[i].val.dvalue;
+      break;
+    case VT_POINTER:
+      types[1+i] = &amp;ffi_type_pointer;
+      values[1+i] = &amp;args[i].val.pvalue;
+      break;
+    default:
+      abort();    /* Whoa! We're seriously hosed */
+      break;   
+    }
+  }
+  if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+1,
+                   &amp;ffi_type_uint, types) == FFI_OK) {
+    ffi_call(&amp;cif, (void (*)()) printf, &amp;result, values);
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
+    free(types);
+    free(values);
+    free(args);
+    return NULL;
+  }
+  free(types);
+  free(values);
+  free(args);
+}
+
+/* The function */
+int printf(const char *fmt, ...);
+</pre>
+</div>
+
+<p>
+Much to your amazement, it even seems to work if you try it:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; import example
+&gt;&gt;&gt; example.printf("Grade: %s   %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60)
+Grade: Dave   47/60 = 78.33%
+&gt;&gt;&gt;
+</pre>
+</div>
+
+<p>
+Of course, there are still some limitations to consider:
+</p>
+
+<div class="targetlang">
+<pre>
+&gt;&gt;&gt; example.printf("la de da de da %s", 42)
+Segmentation fault (core dumped)
+</pre>
+</div>
+
+<p>
+And, on this note, we leave further exploration of libffi to the reader as an exercise.  Although Python has been used as an example,
+most of the techniques in this section can be extrapolated to other language modules with a bit of work.   The only
+details you need to know is how the extra arguments are accessed in each target language.  For example, in the Python
+module, we used the special <tt>varargs</tt> variable to get these arguments.  Modules such as Tcl8 and Perl5 simply
+provide an argument number for the first extra argument.  This can be used to index into an array of passed arguments to get
+values.   Please consult the chapter on each language module for more details.
+</p>
+
+<H2><a name="Varargs_nn8"></a>13.7 Wrapping of va_list</H2>
+
+
+<p>
+Closely related to variable length argument wrapping, you may encounter functions that accept a parameter
+of type <tt>va_list</tt>.  For example:
+</p>
+
+<div class="code">
+<pre>
+int vfprintf(FILE *f, const char *fmt, va_list ap);
+</pre>
+</div>
+
+<p>
+As far as we know, there is no obvious way to wrap these functions
+with SWIG.  This is because there is no documented way to assemble the
+proper va_list structure (there are no C library functions to do it
+and the contents of va_list are opaque).  Not only that, the contents
+of a <tt>va_list</tt> structure are closely tied to the underlying
+call-stack.  It's not clear that exporting a <tt>va_list</tt> would
+have any use or that it would work at all.
+</p>
+
+<H2><a name="Varargs_nn9"></a>13.8 C++ Issues</H2>
+
+
+<p>
+Wrapping of C++ member functions that accept a variable number of
+arguments presents a number of challenges.   By far, the easiest way to
+handle this is to use the <tt>%varargs</tt> directive.   This is portable
+and it fully supports classes much like the <tt>%rename</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%varargs (10, char * = NULL) Foo::bar;
+
+class Foo {
+public:
+     virtual void bar(char *arg, ...);   // gets varargs above
+};
+
+class Spam: public Foo {
+public:
+     virtual void bar(char *arg, ...);   // gets varargs above
+};
+</pre>
+</div>
+
+<p>
+<tt>%varargs</tt> also works with constructors, operators, and any
+other C++ programming construct that accepts variable arguments.
+</p>
+
+<p>
+Doing anything more advanced than this is likely to involve a serious
+world of pain.  In order to use a library like libffi, you will need
+to know the underlying calling conventions and details of the C++ ABI.  For
+instance, the details of how <tt>this</tt> is passed to member
+functions as well as any hidden arguments that might be used to pass
+additional information.  These details are implementation specific and
+may differ between compilers and even different versions of the same
+compiler.  Also, be aware that invoking a member function is further
+complicated if it is a virtual method.  In this case,
+invocation might require a table lookup to obtain the proper function address
+(although you might be able to obtain an address by casting a bound
+pointer to a pointer to function as described in the C++ ARM section
+18.3.4).
+</p>
+
+<p>
+If you do decide to change the underlying action code, be aware that SWIG
+always places the <tt>this</tt> pointer in <tt>arg1</tt>.   Other arguments
+are placed in <tt>arg2</tt>, <tt>arg3</tt>, and so forth.  For example:
+</p>
+
+<div class="code">
+<pre>
+%feature("action") Foo::bar {
+   ...
+   result = arg1-&gt;bar(arg2, arg3, etc.);
+   ...
+}
+</pre>
+</div>
+
+<p>
+Given the potential to shoot yourself in the foot, it is probably easier to reconsider your
+design or to provide an alternative interface using a helper function than it is to create a
+fully general wrapper to a varargs C++ member function.
+</p>
+
+<H2><a name="Varargs_nn10"></a>13.9 Discussion</H2>
+
+
+<p>
+This chapter has provided a number of techniques that can be used to address the problem of variable length
+argument wrapping.  If you care about portability and ease of use, the <tt>%varargs</tt> directive is
+probably the easiest way to tackle the problem.   However, using typemaps, it is possible to do some very advanced
+kinds of wrapping.
+</p>
+
+<p>
+One point of discussion concerns the structure of the libffi examples in the previous section.  Looking
+at that code, it is not at all clear that this is the easiest way to solve the problem.  However, there 
+are a number of subtle aspects of the solution to consider--mostly concerning the way in which the
+problem has been decomposed.   First, the example is structured in a way that tries to maintain separation
+between wrapper-specific information and the declaration of the function itself.   The idea here is that
+you might structure your interface like this:
+</p>
+
+<div class="code">
+<pre>
+%typemap(const char *fmt, ...) {
+   ...
+}
+%feature("action") traceprintf {
+   ...
+}
+
+/* Include some header file with traceprintf in it */
+%include "someheader.h"
+</pre>
+</div>
+
+<p>
+Second, careful scrutiny will reveal that the typemaps involving <tt>(...)</tt> have nothing
+whatsoever to do with the libffi library.  In fact, they are generic with respect to the way in which
+the function is actually called.   This decoupling means that it will be much easier to consider
+other library alternatives for making the function call.  For instance, if libffi wasn't supported on a certain
+platform, you might be able to use something else instead.  You could use conditional compilation
+to control this:
+</p>
+
+<div class="code">
+<pre>
+#ifdef USE_LIBFFI
+%feature("action") printf {
+   ...
+}
+#endif
+#ifdef USE_OTHERFFI
+%feature("action") printf {
+...
+}
+#endif
+</pre>
+</div>
+
+<p>
+Finally, even though you might be inclined to just write a hand-written wrapper for varargs functions,
+the techniques used in the previous section have the advantage of being compatible with all other features
+of SWIG such as exception handling.
+</p>
+
+<p>
+As a final word, some C programmers seem to have the assumption that
+the wrapping of variable length argument functions is an easily solved
+problem.  However, this section has hopefully dispelled some of these
+myths.  All things being equal, you are better off avoiding variable
+length arguments if you can.  If you can't avoid them, please consider
+some of the simple solutions first.  If you can't live with a simple
+solution, proceed with caution.  At the very least, make sure you
+carefully read the section "A7.3.2 Function Calls" in Kernighan and
+Ritchie and make sure you fully understand the parameter passing conventions used for varargs.
+Also, be aware of the platform dependencies and reliability issues that
+this will introduce.  Good luck.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Warnings.html b/trunk/Doc/Manual/Warnings.html
new file mode 100644
index 0000000..0b3cb37
--- /dev/null
+++ b/trunk/Doc/Manual/Warnings.html
@@ -0,0 +1,580 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Warning Messages</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Warnings"></a>14 Warning Messages</H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Warnings_nn2">Introduction</a>
+<li><a href="#Warnings_suppression">Warning message suppression</a>
+<li><a href="#Warnings_nn4">Enabling extra warnings</a>
+<li><a href="#Warnings_nn5">Issuing a warning message</a>
+<li><a href="#Warnings_symbolic_symbols">Symbolic symbols</a>
+<li><a href="#Warnings_nn6">Commentary</a>
+<li><a href="#Warnings_nn7">Warnings as errors</a>
+<li><a href="#Warnings_nn8">Message output format</a>
+<li><a href="#Warnings_nn9">Warning number reference</a>
+<ul>
+<li><a href="#Warnings_nn10">Deprecated features (100-199)</a>
+<li><a href="#Warnings_nn11">Preprocessor (200-299)</a>
+<li><a href="#Warnings_nn12">C/C++ Parser (300-399)</a>
+<li><a href="#Warnings_nn13">Types and typemaps (400-499) </a>
+<li><a href="#Warnings_nn14">Code generation (500-599)</a>
+<li><a href="#Warnings_nn15">Language module specific (800-899) </a>
+<li><a href="#Warnings_nn16">User defined (900-999)</a>
+</ul>
+<li><a href="#Warnings_nn17">History</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<H2><a name="Warnings_nn2"></a>14.1 Introduction</H2>
+
+
+<p>
+During compilation, SWIG may generate a variety of warning messages.  For example:
+</p>
+
+<div class="shell">
+<pre>
+example.i:16: Warning(501): Overloaded declaration ignored.  bar(double)
+example.i:15: Warning(501): Previous declaration is bar(int)
+</pre>
+</div>
+
+<p>
+Typically, warning messages indicate non-fatal problems with the input
+where the generated wrapper code will probably compile, but it may not
+work like you expect.
+</p>
+
+<H2><a name="Warnings_suppression"></a>14.2 Warning message suppression</H2>
+
+
+<p>
+All warning messages have a numeric code that is shown in the warning message itself.
+To suppress the printing of a warning message, a number of techniques can be used.
+First, you can run SWIG with the <tt>-w</tt> command line option. For example:
+</p>
+
+<div class="shell">
+<pre>
+% swig -python -w501 example.i
+% swig -python -w501,505,401 example.i
+</pre>
+</div>
+
+<p>
+Alternatively, warnings can be suppressed by inserting a special preprocessor pragma
+into the input file:
+</p>
+
+<div class="code">
+<pre>
+%module example
+#pragma SWIG nowarn=501
+#pragma SWIG nowarn=501,505,401
+</pre>
+</div>
+
+<p>
+Finally, code-generation warnings can be disabled on a declaration by declaration basis using
+the <tt>%warnfilter</tt> directive.  For example:
+</p>
+
+<div class="code">
+<pre>
+%module example
+%warnfilter(501) foo;
+...
+int foo(int);
+int foo(double);              // Silently ignored.
+</pre>
+</div>
+
+<p>
+The <tt>%warnfilter</tt> directive has the same semantics as other declaration modifiers like 
+<tt>%rename</tt>, <tt>%ignore</tt> and <tt>%feature</tt>, see the 
+<a href="Customization.html#features">%feature directive</a> section.  For example, if you wanted to
+suppress a warning for a method in a class hierarchy, you could do this:
+</p>
+
+<div class="code">
+<pre>
+%warnfilter(501) Object::foo;
+class Object {
+public:
+   int foo(int);
+   int foo(double);      // Silently ignored
+   ...
+};
+
+class Derived : public Object {
+public:
+   int foo(int);
+   int foo(double);      // Silently ignored
+   ...
+};
+</pre>
+</div>
+
+<p>
+Warnings can be suppressed for an entire class by supplying a class name.  For example:
+</p>
+
+<div class="code">
+<pre>
+%warnfilter(501) Object;
+
+class Object {
+public:
+   ...                      // All 501 warnings ignored in class
+};
+</pre>
+</div>
+
+<p>
+There is no option to suppress all SWIG warning messages.  The warning messages are there
+for a reason---to tell you that something may be <em>broken</em> in
+your interface.  Ignore the warning messages at your own peril.
+</p>
+
+
+<H2><a name="Warnings_nn4"></a>14.3 Enabling extra warnings</H2>
+
+
+<p>
+Some warning messages are disabled by default and are generated only
+to provide additional diagnostics.  These warnings can be turned on using the
+<tt>-Wextra</tt> option. For example:
+</p>
+
+<div class="shell">
+<pre>
+% swig -Wextra -python example.i
+</pre>
+</div>
+
+<p>
+To selectively turn on extra warning messages, you can use the directives and options in the
+previous section--simply add a "+" to all warning numbers.  For example:
+</p>
+
+<div class="shell">
+<pre>
+% swig -w+309,+452 example.i
+</pre>
+</div>
+
+<p>
+or in your interface file use either
+</p>
+
+<div class="code">
+<pre>
+#pragma SWIG nowarn=+309,+452
+</pre>
+</div>
+
+<p>
+or
+</p>
+
+<div class="code">
+<pre>
+%warnfilter(+309,+452) foo;
+</pre>
+</div>
+
+<p>
+Note: selective enabling of warnings with <tt>%warnfilter</tt> overrides any global settings you might have
+made using <tt>-w</tt> or <tt>#pragma</tt>.
+</p>
+
+<p>
+You can of course also enable all warnings and suppress a select few, for example:
+</p>
+
+<div class="shell">
+<pre>
+% swig -Wextra -w309,452 example.i
+</pre>
+</div>
+
+<p>
+The warnings on the right take precedence over the warnings on the left, so in the above example <tt>-Wextra</tt> adds numerous warnings including 452, but then <tt>-w309,452</tt> overrides this and so 452 is suppressesed.
+</p>
+
+<p>
+If you would like all warnings to appear, regardless of the warning filters used, then use the <tt>-Wall</tt> option.
+The <tt>-Wall</tt> option also turns on the extra warnings that <tt>-Wextra</tt> adds, however, it is subtely different. 
+When <tt>-Wall</tt> is used, it also disables all other warning filters, 
+that is, any warnings suppressed or added in <tt>%warnfilter</tt>, <tt>#pragma SWIG nowarn</tt> 
+or the <tt>-w</tt> option.
+</p>
+
+<H2><a name="Warnings_nn5"></a>14.4 Issuing a warning message</H2>
+
+
+<p>
+Warning messages can be issued from an interface file using a number of directives.  The
+<tt>%warn</tt> directive is the most simple:
+</p>
+
+<div class="code">
+<pre>
+%warn "900:This is your last warning!"
+</pre>
+</div>
+
+<p>
+All warning messages are optionally prefixed by the warning number to use.  If you are generating
+your own warnings, make sure you don't use numbers defined in the table at the end of this section.
+</p>
+
+<p>
+The <tt>%ignorewarn</tt> directive is the same as <tt>%ignore</tt> except that it issues a
+warning message whenever a matching declaration is found. For example:
+</p>
+
+<div class="code">
+<pre>
+%ignorewarn("362:operator= ignored") operator=;
+</pre>
+</div>
+
+<p>
+Warning messages can be associated with typemaps using the
+<tt>warning</tt> attribute of a typemap declaration. For example:
+</p>
+
+<div class="code">
+<pre>
+%typemap(in, warning="901:You are really going to regret this") blah * {
+   ...
+}
+</pre>
+</div>
+
+<p>
+In this case, the warning message will be printed whenever the typemap is actually used.
+</p>
+
+<H2><a name="Warnings_symbolic_symbols"></a>14.5 Symbolic symbols</H2>
+
+
+<p>
+The <tt>swigwarn.swg</tt> file that is installed with SWIG contains symbol constants that could also be
+used in <tt>%warnfilter</tt> and <tt>#pragma SWIG nowarn</tt>.
+For example this file contains the following line:
+</p>
+
+<div class="code">
+<pre>
+%define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef
+</pre>
+</div>
+
+<p>
+so <tt>SWIGWARN_TYPE_UNDEFINED_CLASS</tt> could be used instead of 401, for example:
+</p>
+
+<div class="code">
+<pre>
+#pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS
+</pre>
+</div>
+
+<p>
+or 
+</p>
+
+<div class="code">
+<pre>
+%warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo;
+</pre>
+</div>
+
+<H2><a name="Warnings_nn6"></a>14.6 Commentary</H2>
+
+
+<p>
+The ability to suppress warning messages is really only provided for
+advanced users and is not recommended in normal use.  You are advised
+to modify your interface to fix the problems highlighted by the warnings
+wherever possible instead of suppressing warnings.
+</p>
+
+<p>
+Certain types of SWIG problems are errors.  These usually arise due to
+parsing errors (bad syntax) or semantic problems for which there is
+no obvious recovery.  There is no mechanism for suppressing error
+messages.
+</p>
+
+<H2><a name="Warnings_nn7"></a>14.7 Warnings as errors</H2>
+
+
+<p>
+Warnings can be handled as errors by using the <tt>-Werror</tt> command line
+option. This will cause SWIG to exit with a non successful exit code if a
+warning is encountered.
+</p>
+
+<H2><a name="Warnings_nn8"></a>14.8 Message output format</H2>
+
+
+<p>
+The output format for both warnings and errors can be selected for
+integration with your favourite IDE/editor. Editors and IDEs can usually parse 
+error messages and if in the appropriate format will easily take you 
+directly to the source of the error. The standard format is used by 
+default except on Windows where the Microsoft format is used by default.
+These can be overridden using command line options, for example:
+</p>
+
+<div class="shell"><pre>
+$ swig -python -Fstandard example.i
+example.i:4: Syntax error in input.
+$ swig -python -Fmicrosoft example.i
+example.i(4): Syntax error in input.
+</pre></div>
+
+<H2><a name="Warnings_nn9"></a>14.9 Warning number reference</H2>
+
+
+<H3><a name="Warnings_nn10"></a>14.9.1 Deprecated features (100-199)</H3>
+
+
+<ul>
+<li>101. Deprecated <tt>%extern</tt> directive.
+<li>102. Deprecated <tt>%val</tt> directive.
+<li>103. Deprecated <tt>%out</tt> directive.
+<li>104. Deprecated <tt>%disabledoc</tt> directive.
+<li>105. Deprecated <tt>%enabledoc</tt> directive.
+<li>106. Deprecated <tt>%doconly</tt> directive.
+<li>107. Deprecated <tt>%style</tt> directive.
+<li>108. Deprecated <tt>%localstyle</tt> directive.
+<li>109. Deprecated <tt>%title</tt> directive.
+<li>110. Deprecated <tt>%section</tt> directive.
+<li>111. Deprecated <tt>%subsection</tt> directive.
+<li>112. Deprecated <tt>%subsubsection</tt> directive.
+<li>113. Deprecated <tt>%addmethods</tt> directive.
+<li>114. Deprecated <tt>%readonly</tt> directive.
+<li>115. Deprecated <tt>%readwrite</tt> directive.
+<li>116. Deprecated <tt>%except</tt> directive.
+<li>117. Deprecated <tt>%new</tt> directive.
+<li>118. Deprecated <tt>%typemap(except)</tt>.
+<li>119. Deprecated <tt>%typemap(ignore)</tt>.
+<li>120. Deprecated command line option (-runtime, -noruntime).
+<li>121. Deprecated <tt>%name</tt> directive.
+</ul>
+
+<H3><a name="Warnings_nn11"></a>14.9.2 Preprocessor (200-299)</H3>
+
+
+<ul>
+<li>201. Unable to find 'filename'.
+<li>202. Could not evaluate 'expr'.
+</ul>
+
+<H3><a name="Warnings_nn12"></a>14.9.3 C/C++ Parser (300-399)</H3>
+
+
+<ul>
+<li>301. <tt>class</tt> keyword used, but not in C++ mode.
+<li>302. Identifier '<em>name</em>' redefined (ignored).
+<li>303. <tt>%extend</tt> defined for an undeclared class '<em>name</em>'.
+<li>304. Unsupported constant value (ignored).
+<li>305. Bad constant value (ignored).
+<li>306. '<em>identifier</em>' is private in this context.
+<li>307. Can't set default argument value (ignored)
+<li>308. Namespace alias '<em>name</em>' not allowed here. Assuming '<em>name</em>'
+<li>309. [private | protected] inheritance ignored.
+<li>310. Template '<em>name</em>' was already wrapped as '<em>name</em>' (ignored)
+<li>311. Template partial specialization not supported.
+<li>312. Nested classes not currently supported (ignored).
+<li>313. Unrecognized extern type "<em>name</em>" (ignored).
+<li>314. '<em>identifier</em>' is a <em>lang</em> keyword.
+<li>315. Nothing known about '<em>identifier</em>'.
+<li>316. Repeated %module directive.
+<li>317. Specialization of non-template '<em>name</em>'.
+<li>318. Instantiation of template <em>name</em> is ambiguous. Using <em>templ</em> at <em>file</em>:<em>line</em>
+<li>319. No access specifier given for base class <em>name</em> (ignored).
+<li>320. Explicit template instantiation ignored.
+<li>321. <em>identifier</em> conflicts with a built-in name.
+<li>322. Redundant redeclaration of '<em>name</em>'.
+<li>350. operator new ignored.
+<li>351. operator delete ignored.
+<li>352. operator+ ignored.
+<li>353. operator- ignored.
+<li>354. operator* ignored.
+<li>355. operator/ ignored.
+<li>356. operator% ignored.
+<li>357. operator^ ignored.
+<li>358. operator&amp; ignored.
+<li>359. operator| ignored.
+<li>360. operator~ ignored.
+<li>361. operator! ignored.
+<li>362. operator= ignored.
+<li>363. operator&lt; ignored.
+<li>364. operator&gt; ignored.
+<li>365. operator+= ignored.
+<li>366. operator-= ignored.
+<li>367. operator*= ignored.
+<li>368. operator/= ignored.
+<li>369. operator%= ignored.
+<li>370. operator^= ignored.
+<li>371. operator&amp;= ignored.
+<li>372. operator|= ignored.
+<li>373. operator&lt;&lt; ignored.
+<li>374. operator&gt;&gt;ignored.
+<li>375. operator&lt;&lt;= ignored.
+<li>376. operator&gt;&gt;= ignored.
+<li>377. operator== ignored.
+<li>378. operator!= ignored.
+<li>379. operator&lt;= ignored.
+<li>380. operator&gt;= ignored.
+<li>381. operator&amp;&amp; ignored.
+<li>382. operator|| ignored.
+<li>383. operator++ ignored.
+<li>384. operator-- ignored.
+<li>385. operator, ignored.
+<li>386. operator-&lt;* ignored.
+<li>387. operator-&lt; ignored.
+<li>388. operator() ignored.
+<li>389. operator[] ignored.
+<li>390. operator+ ignored (unary).
+<li>391. operator- ignored (unary).
+<li>392. operator* ignored (unary).
+<li>393. operator&amp; ignored (unary).
+<li>394. operator new[] ignored.
+<li>395. operator delete[] ignored.
+</ul>
+
+<H3><a name="Warnings_nn13"></a>14.9.4 Types and typemaps (400-499) </H3>
+
+
+<ul>
+<li>401. Nothing known about class 'name'. Ignored.
+<li>402. Base class 'name' is incomplete.
+<li>403. Class 'name' might be abstract.
+<li>450. Deprecated typemap feature ($source/$target).
+<li>451. Setting const char * variable may leak memory.
+<li>452. Reserved
+<li>453. Can't apply (pattern). No typemaps are defined.
+<li>460. Unable to use type <em>type</em> as a function argument.
+<li>461. Unable to use return type <em>type</em> in function <em>name</em>.
+<li>462. Unable to set variable of type <em>type</em>.
+<li>463. Unable to read variable of type <em>type</em>.
+<li>464. Unsupported constant value.
+<li>465. Unable to handle type <em>type</em>.
+<li>466. Unsupported variable type <em>type</em>.
+<li>467. Overloaded <em>declaration</em> not supported (no type checking rule for '<em>type</em>')
+<li>468. No 'throw' typemap defined for exception type <em>type</em>
+<li>469. No or improper directorin typemap defined for <em>type</em>
+<li>470. Thread/reentrant unsafe wrapping, consider returning by value instead.
+<li>471. Unable to use return type <em>type</em> in director method
+<li>474. Method <em>method</em> usage of the optimal attribute in the out typemap at <em>file</em>:<em>line</em> ignored as the following cannot be used to generate optimal code: <em>code</em>
+<li>475. Multiple calls to <em>method</em> might be generated due to optimal attribute usage in the out typemap at <em>file</em>:<em>line</em>.
+</ul>
+
+
+
+<H3><a name="Warnings_nn14"></a>14.9.5 Code generation (500-599)</H3>
+
+
+<ul>
+<li>501. Overloaded declaration ignored. <em>decl</em>
+<li>502. Overloaded constructor ignored. <em>decl</em>
+<li>503. Can't wrap '<em>identifier</em>' unless renamed to a valid identifier.
+<li>504. Function <em>name</em> must have a return type.
+<li>505. Variable length arguments discarded.
+<li>506. Can't wrap varargs with keyword arguments enabled.
+<li>507. Adding native function <em>name</em> not supported (ignored).
+<li>508. Declaration of '<em>name</em>' shadows declaration accessible via operator-&gt;() at <em>file:line</em>.
+<li>509. Overloaded <em>declaration</em> is shadowed by <em>declaration</em> at <em>file</em>:<em>line</em>.
+<li>510. Friend function '<em>name</em>' ignored.
+<li>511. Can't use keyword arguments with overloaded functions.
+<li>512. Overloaded <em>declaration</em> const ignored. Non-const method at <em>file</em>:<em>line</em> used.
+<li>513. Can't generate wrappers for unnamed struct/class.
+<li>514. 
+<li>515. 
+<li>516. Overloaded method <em>declaration</em> ignored. Method <em>declaration</em> at <em>file</em>:<em>line</em> used.
+<li>517. 
+<li>518. Portability warning: File <em>file1</em> will be overwritten by <em>file2</em> on case insensitive filesystems such as Windows' FAT32 and NTFS unless the class/module name is renamed.
+<li>519. %template() contains no name. Template method ignored: <em>declaration</em>
+</ul>
+
+<H3><a name="Warnings_nn15"></a>14.9.6 Language module specific (800-899) </H3>
+
+
+<ul>
+<li>801. Wrong name (corrected to '<em>name</em>').  (Ruby).
+</ul>
+
+<ul>
+<li>810. No jni typemap defined for <em>type</em>  (Java).
+<li>811. No jtype typemap defined for <em>type</em>  (Java).
+<li>812. No jstype typemap defined for <em>type</em>  (Java).
+<li>813. Warning for <em>classname</em>: Base <em>baseclass</em> ignored. Multiple inheritance is not supported in Java.   (Java).
+<li>814. 
+<li>815. No javafinalize typemap defined for <em>type</em>  (Java).
+<li>816. No javabody typemap defined for <em>type</em>  (Java).
+<li>817. No javaout typemap defined for <em>type</em>  (Java).
+<li>818. No javain typemap defined for <em>type</em>  (Java).
+<li>819. No javadirectorin typemap defined for <em>type</em>  (Java).
+<li>820. No javadirectorout typemap defined for <em>type</em>  (Java).
+<li>821. 
+<li>822. Covariant return types not supported in Java. Proxy method will return <em>basetype</em>  (Java).
+<li>823. No javaconstruct typemap defined for <em>type</em>  (Java).
+<li>824. Missing JNI descriptor in directorin typemap defined for <em>type</em> (Java).
+</ul>
+
+<ul>
+<li>830. No ctype typemap defined for <em>type</em>  (C#).
+<li>831. No cstype typemap defined for <em>type</em>  (C#).
+<li>832. No cswtype typemap defined for <em>type</em>  (C#).
+<li>833. Warning for <em>classname</em>: Base <em>baseclass</em> ignored. Multiple inheritance is not supported in C#.   (C#).
+<li>834. 
+<li>835. No csfinalize typemap defined for <em>type</em>  (C#).
+<li>836. No csbody typemap defined for <em>type</em>  (C#).
+<li>837. No csout typemap defined for <em>type</em>  (C#).
+<li>838. No csin typemap defined for <em>type</em>  (C#).
+<li>839. 
+<li>840. 
+<li>841. 
+<li>842. Covariant return types not supported in C#. Proxy method will return <em>basetype</em>  (C#).
+<li>843. No csconstruct typemap defined for <em>type</em>  (C#).
+<li>844. C# exception may not be thrown - no $excode or excode attribute in <em>typemap</em> typemap. (C#).
+<li>845. Unmanaged code contains a call to a SWIG_CSharpSetPendingException method and C# code does not handle pending exceptions via the canthrow attribute. (C#).
+</ul>
+
+<ul>
+<li>870. Warning for <em>classname</em>: Base <em>baseclass</em> ignored. Multiple inheritance is not supported in Php4.   (Php).
+<li>871. Unrecognized pragma <em>pragma</em>.   (Php).
+</ul>
+
+<H3><a name="Warnings_nn16"></a>14.9.7 User defined (900-999)</H3>
+
+
+<p>
+These numbers can be used by your own application.
+</p>
+
+<H2><a name="Warnings_nn17"></a>14.10 History</H2>
+
+
+<p>
+The ability to control warning messages was first added to SWIG-1.3.12.
+</p>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/Windows.html b/trunk/Doc/Manual/Windows.html
new file mode 100644
index 0000000..8a718ff
--- /dev/null
+++ b/trunk/Doc/Manual/Windows.html
@@ -0,0 +1,377 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Getting started on Windows</title>
+<link rel="stylesheet" type="text/css" href="style.css">
+</head>
+
+<body bgcolor="#ffffff">
+<H1><a name="Windows"></a>3 Getting started on Windows </H1>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#Windows_installation">Installation on Windows</a>
+<ul>
+<li><a href="#Windows_executable">Windows Executable</a>
+</ul>
+<li><a href="#Windows_examples">SWIG Windows Examples</a>
+<ul>
+<li><a href="#Windows_visual_studio">Instructions for using the Examples with Visual Studio</a>
+<ul>
+<li><a href="#Windows_csharp">C#</a>
+<li><a href="#Windows_java">Java</a>
+<li><a href="#Windows_perl">Perl</a>
+<li><a href="#Windows_python">Python</a>
+<li><a href="#Windows_tcl">TCL</a>
+<li><a href="#Windows_r">R</a>
+<li><a href="#Windows_ruby">Ruby</a>
+</ul>
+<li><a href="#Windows_other_compilers">Instructions for using the Examples with other compilers</a>
+</ul>
+<li><a href="#Windows_cygwin_mingw">SWIG on Cygwin and MinGW</a>
+<ul>
+<li><a href="#Windows_swig_exe">Building swig.exe on Windows</a>
+<ul>
+<li><a href="#Windows_mingw_msys">Building swig.exe using MinGW and MSYS</a>
+<li><a href="#Windows_cygwin">Building swig.exe using Cygwin</a>
+<li><a href="#Windows_building_alternatives">Building swig.exe alternatives</a>
+</ul>
+<li><a href="#Windows_examples_cygwin">Running the examples on Windows using Cygwin</a>
+</ul>
+<li><a href="#Windows_interface_file">Microsoft extensions and other Windows quirks</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+<p>
+This chapter describes SWIG usage on Microsoft Windows. 
+Installing SWIG and running the examples is covered as well as building the SWIG executable.
+Usage within the Unix like environments MinGW and Cygwin is also detailed.
+</p>
+
+
+<H2><a name="Windows_installation"></a>3.1 Installation on Windows</H2>
+
+
+<p>
+SWIG does not come with the usual Windows type installation program, however it is quite easy to get started. The main steps are:
+</p>
+<ul>
+        <li>Download the swigwin zip package from the <a href="http://www.swig.org">SWIG website</a> and unzip into a directory. This is all that needs downloading for the Windows platform.
+        <li>Set environment variables as described in the <a href="#Windows_examples">SWIG Windows Examples</a> section in order to run examples using Visual C++.
+</ul>
+
+<H3><a name="Windows_executable"></a>3.1.1 Windows Executable</H3>
+
+
+<p>
+The swigwin distribution contains the SWIG Windows executable, swig.exe, which will run on 32 bit versions of Windows, ie Windows 95/98/ME/NT/2000/XP. 
+If you want to build your own swig.exe have a look at <a href="#Windows_swig_exe">Building swig.exe on Windows</a>.
+</p>
+
+
+<H2><a name="Windows_examples"></a>3.2 SWIG Windows Examples</H2>
+
+
+<p>
+Using Microsoft Visual C++ is the most common approach to compiling and linking SWIG's output. 
+The Examples directory has a few Visual C++ project files (.dsp files). 
+These were produced by Visual C++ 6, although they should also work in Visual C++ 5. 
+Later versions of Visual Studio should also be able to open and convert these project files.
+The C# examples come with .NET 2003 solution (.sln) and project files instead of Visual C++ 6 project files.
+The project files have been set up to execute SWIG in a custom build rule for the SWIG interface (.i) file. 
+Alternatively run the <a href="#Windows_examples_cygwin">examples using Cygwin</a>.
+
+<p>
+More information on each of the examples is available with the examples distributed with SWIG (Examples/index.html).
+
+<H3><a name="Windows_visual_studio"></a>3.2.1 Instructions for using the Examples with Visual Studio</H3>
+
+
+<p>
+Ensure the SWIG executable is as supplied in the SWIG root directory in order for the examples to work. 
+Most languages require some environment variables to be set <b>before</b> running Visual C++. 
+Note that Visual C++ must be re-started to pick up any changes in environment variables. 
+Open up an example .dsp file, Visual C++ will create a workspace for you (.dsw file). 
+Ensure the Release build is selected then do a Rebuild All from the Build menu.
+The required environment variables are displayed with their current values.
+</p>
+<p>
+The list of required environment variables for each module language is also listed below.
+They are usually set from the Control Panel and System properties, but this depends on which flavour of Windows you are running.
+If you don't want to use environment variables then change all occurrences of the environment variables in the .dsp files with hard coded values.
+If you are interested in how the project files are set up there is explanatory information in some of the language module's documentation.
+</p>
+
+<H4><a name="Windows_csharp"></a>3.2.1.1 C#</H4>
+
+
+<p>
+The C# examples do not require any environment variables to be set as a C# project file is included.
+Just open up the .sln solution file in Visual Studio .NET 2003 or later, select Release Build, and do a Rebuild All from the Build menu.
+The accompanying C# and C++ project files are automatically used by the solution file.
+</p>
+
+
+<H4><a name="Windows_java"></a>3.2.1.2 Java</H4>
+
+
+<p>
+<b><tt>JAVA_INCLUDE</tt></b> : Set this to the directory containing jni.h<br>
+<b><tt>JAVA_BIN</tt></b> : Set this to the bin directory containing javac.exe<p>
+Example using JDK1.3:<br>
+<tt>
+JAVA_INCLUDE: D:\jdk1.3\include<br>
+JAVA_BIN: D:\jdk1.3\bin<br>
+</tt>
+</p>
+
+
+<H4><a name="Windows_perl"></a>3.2.1.3 Perl</H4>
+
+
+<p>
+<b><tt>PERL5_INCLUDE</tt></b> : Set this to the directory containing perl.h<br>
+<b><tt>PERL5_LIB</tt></b> : Set this to the Perl library including path for linking<p>
+Example using nsPerl 5.004_04:<p>
+<tt>
+PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE<br>
+PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib<br>
+</tt>
+</p>
+
+
+<H4><a name="Windows_python"></a>3.2.1.4 Python</H4>
+
+
+<p>
+<b><tt>PYTHON_INCLUDE</tt></b> : Set this to the directory that contains python.h<br>
+<b><tt>PYTHON_LIB</tt></b> : Set this to the python library including path for linking<p>
+Example using Python 2.1.1:<br>
+<tt>
+PYTHON_INCLUDE: D:\python21\include<br>
+PYTHON_LIB: D:\python21\libs\python21.lib<br>
+</tt>
+</p>
+
+
+<H4><a name="Windows_tcl"></a>3.2.1.5 TCL</H4>
+
+
+<p>
+<b><tt>TCL_INCLUDE</tt></b> : Set this to the directory containing tcl.h<br>
+<b><tt>TCL_LIB</tt></b> : Set this to the TCL library including path for linking<p>
+Example using ActiveTcl 8.3.3.3	<br>
+<tt>
+TCL_INCLUDE: D:\tcl\include<br>
+TCL_LIB: D:\tcl\lib\tcl83.lib<br>
+</tt>
+</p>
+
+
+<H4><a name="Windows_r"></a>3.2.1.6 R</H4>
+
+
+<p>
+<b><tt>R_INCLUDE</tt></b> : Set this to the directory containing R.h<br>
+<b><tt>R_LIB</tt></b> : Set this to the R library (Rdll.lib) including path for linking. The library needs to be built as described in the R README.packages file (the pexports.exe approach is the easiest).<p>
+Example using R 2.5.1:<br>
+<tt>
+R_INCLUDE: C:\Program Files\R\R-2.5.1\include<br>
+R_LIB: C:\Program Files\R\R-2.5.1\bin\Rdll.lib<br>
+</tt>
+</p>
+
+
+<H4><a name="Windows_ruby"></a>3.2.1.7 Ruby</H4>
+
+
+<p>
+<b><tt>RUBY_INCLUDE</tt></b> : Set this to the directory containing ruby.h<br>
+<b><tt>RUBY_LIB</tt></b> : Set this to the ruby library including path for linking<p>
+Example using Ruby 1.6.4:<br>
+<tt>
+RUBY_INCLUDE: D:\ruby\lib\ruby\1.6\i586-mswin32<br>
+RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib<br>
+</tt>
+</p>
+
+
+<H3><a name="Windows_other_compilers"></a>3.2.2 Instructions for using the Examples with other compilers</H3>
+
+
+<p>
+If you do not have access to Visual C++ you will have to set up project files / Makefiles for your chosen compiler. There is a section in each of the language modules detailing what needs setting up using Visual C++ which may be of some guidance. Alternatively you may want to use Cygwin as described in the following section.
+</p>
+
+<H2><a name="Windows_cygwin_mingw"></a>3.3 SWIG on Cygwin and MinGW</H2>
+
+
+<p>
+SWIG can also be compiled and run using <a href="http://www.cygwin.com">Cygwin</a> or <a href="http://www.mingw.org">MinGW</a> which provides a Unix like front end to Windows and comes free with gcc, an ANSI C/C++ compiler. However, this is not a recommended approach as the prebuilt executable is supplied. 
+</p>
+
+<H3><a name="Windows_swig_exe"></a>3.3.1 Building swig.exe on Windows</H3>
+
+
+<p>
+If you want to replicate the build of swig.exe that comes with the download, follow the MinGW instructions below.
+This is not necessary to use the supplied swig.exe. 
+This information is provided for those that want to modify the SWIG source code in a Windows environment. 
+Normally this is not needed, so most people will want to ignore this section. 
+</p>
+
+<H4><a name="Windows_mingw_msys"></a>3.3.1.1 Building swig.exe using MinGW and MSYS</H4>
+
+
+<p>
+The short abbreviated instructions follow...
+</p>
+
+<ul>
+    <li>Install MinGW and MSYS from the <a href="http://www.mingw.org">MinGW</a> site. This provides a Unix environment on Windows.
+    <li>Follow the usual Unix instructions in the README file in the SWIG root directory to build swig.exe from the MinGW command prompt.
+</ul>
+
+<p>
+The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from SVN follow...
+Note that the instructions for obtaining SWIG from SVN are also online at <a href="http://www.swig.org/svn.html">SWIG SVN</a>.
+</p>
+
+<p>
+<b>Pitfall note:</b>
+Execute the steps in the order shown and don't use spaces in path names. In fact it is best to use the default installation directories.
+</p>
+
+<ol>
+  <li>
+  Download the following packages from the <a href="http://www.mingw.org/download.shtml">MinGW download page</a>
+  or <a href="http://sourceforge.net/project/showfiles.php?group_id=2435">MinGW SourceForge download page</a>.
+  Note that at the time of writing, the majority of these are in the Current
+  release list and some are in the Snapshot or Previous release list.
+  <ul>
+    <li>MinGW-3.1.0-1.exe</li>
+    <li>MSYS-1.0.11-2004.04.30-1.exe</li>
+    <li>msysDTK-1.0.1.exe</li>
+    <li>bison-2.0-MSYS.tar.gz</li>
+    <li>msys-autoconf-2.59.tar.bz2</li>
+    <li>msys-automake-1.8.2.tar.bz2</li>
+  </ul>
+  </li>
+
+  <li>
+  Install MinGW-3.1.0-1.exe (C:\MinGW is default location.)
+  </li>
+
+  <li>
+  Install MSYS-1.0.11-2004.04.30-1.exe. Make sure you install it on the same
+  windows drive letter as MinGW (C:\msys\1.0 is default).
+  In the post install script,
+  <ul>
+    <li>Answer y to the "do you wish to continue with the post install?"</li>
+    <li>Answer y to the "do you have MinGW installed?"</li>
+    <li>Type in the the folder in which you installed MinGW (C:/MinGW is default)</li>
+  </ul>
+  </li>
+
+  <li>
+  Install msysDTK-1.0.1.exe to the same folder that you installed MSYS (C:\msys\1.0 is default).
+  </li>
+
+  <li>
+  Copy the followig to the MSYS install folder (C:\msys\1.0 is default):
+  <ul>
+    <li>msys-automake-1.8.2.tar.bz2</li>
+    <li>msys-autoconf-2.59.tar.bz2</li>
+    <li>bison-2.0-MSYS.tar.gz</li>
+  </ul>
+  </li>
+
+  <li>
+  Start the MSYS command prompt and execute:
+<div class="shell"><pre>
+cd /
+tar -jxf msys-automake-1.8.2.tar.bz2 
+tar -jxf msys-autoconf-2.59.tar.bz2
+tar -zxf bison-2.0-MSYS.tar.gz   
+</pre></div>
+  </li>
+
+  <li>
+  To get the latest SWIG SVN (version from Subversion source control), type in the following:
+<div class="shell"><pre>
+mkdir /usr/src
+cd /usr/src
+svn co https://swig.svn.sourceforge.net/svnroot/swig/trunk swig
+</pre></div>
+
+  <b>Pitfall note:</b>
+If you want to check out SWIG to a different folder to the proposed
+/usr/src/swig, do not use MSYS emulated windows drive letters, because
+the autotools will fail miserably on those.
+  </li>
+
+  <li>
+  You are now ready to build SWIG. Execute the following commands to build swig.exe:
+<div class="shell"><pre>
+cd /usr/src/swig
+./autogen.sh
+./configure
+make
+</pre></div>
+  </li>
+</ol>
+
+
+<H4><a name="Windows_cygwin"></a>3.3.1.2 Building swig.exe using Cygwin</H4>
+
+
+<p>
+Note that SWIG can also be built using Cygwin.
+However, SWIG will then require the Cygwin DLL when executing. 
+Follow the Unix instructions in the README file in the SWIG root directory.
+Note that the Cygwin environment will also allow one to regenerate the autotool generated files which are supplied with the release distribution. 
+These files are generated using the <tt>autogen.sh</tt> script and will only need regenerating in circumstances such as changing the build system.
+</p>
+
+<H4><a name="Windows_building_alternatives"></a>3.3.1.3 Building swig.exe alternatives</H4>
+
+
+<p>
+If you don't want to install Cygwin or MinGW, use a different compiler to build 
+SWIG. For example, all the source code files can be added to a Visual C++ project 
+file in order to build swig.exe from the Visual C++ IDE.
+</p>
+
+
+<H3><a name="Windows_examples_cygwin"></a>3.3.2 Running the examples on Windows using Cygwin</H3>
+
+
+<p>
+The examples and test-suite work as successfully on Cygwin as on any other Unix operating system. 
+The modules which are known to work are Python, Tcl, Perl, Ruby, Java and C#.
+Follow the Unix instructions in the README file in the SWIG root directory to build the examples.
+</p>
+
+<H2><a name="Windows_interface_file"></a>3.4 Microsoft extensions and other Windows quirks</H2>
+
+
+<p>
+A common problem when using SWIG on Windows are the Microsoft function calling conventions which are not in the C++ standard.
+SWIG parses ISO C/C++ so cannot deal with proprietary conventions such as <tt>__declspec(dllimport)</tt>, <tt>__stdcall</tt> etc.
+There is a Windows interface file, <tt>windows.i</tt>, to deal with these calling conventions though.
+The file also contains typemaps for handling commonly used Windows specific types such as <tt>__int64</tt>, <tt>BOOL</tt>, <tt>DWORD</tt> etc.
+Include it like you would any other interface file, for example:
+</p>
+
+<div class="code"><pre>
+%include &lt;windows.i&gt;
+
+__declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);
+</pre></div>
+
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/ch11.1.png b/trunk/Doc/Manual/ch11.1.png
new file mode 100644
index 0000000..2cc2bec
--- /dev/null
+++ b/trunk/Doc/Manual/ch11.1.png
Binary files differ
diff --git a/trunk/Doc/Manual/ch11.2.png b/trunk/Doc/Manual/ch11.2.png
new file mode 100644
index 0000000..e6d1b55
--- /dev/null
+++ b/trunk/Doc/Manual/ch11.2.png
Binary files differ
diff --git a/trunk/Doc/Manual/ch11.3.png b/trunk/Doc/Manual/ch11.3.png
new file mode 100644
index 0000000..54ee724
--- /dev/null
+++ b/trunk/Doc/Manual/ch11.3.png
Binary files differ
diff --git a/trunk/Doc/Manual/ch12.1.png b/trunk/Doc/Manual/ch12.1.png
new file mode 100644
index 0000000..2072f06
--- /dev/null
+++ b/trunk/Doc/Manual/ch12.1.png
Binary files differ
diff --git a/trunk/Doc/Manual/ch2.1.png b/trunk/Doc/Manual/ch2.1.png
new file mode 100644
index 0000000..1f5800e
--- /dev/null
+++ b/trunk/Doc/Manual/ch2.1.png
Binary files differ
diff --git a/trunk/Doc/Manual/ch9.table.2.png b/trunk/Doc/Manual/ch9.table.2.png
new file mode 100644
index 0000000..ac6647e
--- /dev/null
+++ b/trunk/Doc/Manual/ch9.table.2.png
Binary files differ
diff --git a/trunk/Doc/Manual/chapters b/trunk/Doc/Manual/chapters
new file mode 100644
index 0000000..55a0aec
--- /dev/null
+++ b/trunk/Doc/Manual/chapters
@@ -0,0 +1,35 @@
+Preface.html
+Introduction.html
+Windows.html
+Scripting.html
+SWIG.html
+SWIGPlus.html
+Preprocessor.html
+Library.html
+Arguments.html
+Typemaps.html
+Customization.html
+Contract.html
+Varargs.html
+Warnings.html
+Modules.html
+Allegrocl.html
+CSharp.html
+Chicken.html
+Guile.html
+Java.html
+Lisp.html
+Lua.html
+Modula3.html
+Mzscheme.html
+Ocaml.html
+Octave.html
+Perl5.html
+Php.html
+Pike.html
+Python.html
+Ruby.html
+Tcl.html
+R.html
+Extending.html
+
diff --git a/trunk/Doc/Manual/fixstyle.py b/trunk/Doc/Manual/fixstyle.py
new file mode 100644
index 0000000..1007d59
--- /dev/null
+++ b/trunk/Doc/Manual/fixstyle.py
@@ -0,0 +1,25 @@
+#!/usr/bin/python
+
+# Adds the SWIG stylesheet to the generated documentation on a single page
+
+import sys
+import string
+
+filename = sys.argv[1]
+
+data = open(filename).read()
+open(filename+".bak","w").write(data)
+
+swigstyle = "\n" + open("style.css").read()
+
+lines = data.splitlines()
+result = [ ]
+for s in lines:
+	if s == "<STYLE TYPE=\"text/css\"><!--":
+		result.append(s + swigstyle)
+	else:
+		result.append(s)
+
+data = "\n".join(result)
+
+open(filename,"w").write(data)
diff --git a/trunk/Doc/Manual/index.html b/trunk/Doc/Manual/index.html
new file mode 100644
index 0000000..8560a91
--- /dev/null
+++ b/trunk/Doc/Manual/index.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>SWIG-1.3 Documentation</title>
+</head>
+<body bgcolor="#ffffff">
+<H1><a name="index"></a>SWIG-1.3 Development Documentation</h1>
+
+The SWIG documentation is available in one of the following formats.
+<ul>
+<li>HTML documentation with one chapter per page. 
+Please start with either the <a href="Sections.html#Sections">Sections summary</a> or the <a href="Contents.html#Contents">Detailed table of contents</a>.</li>
+<li>HTML documentation on a <a href="SWIGDocumentation.html">single HTML page</a>.</li>
+<li><a href="SWIGDocumentation.pdf">PDF document</a>.</li>
+</ul>
+
+</body>
+</html>
diff --git a/trunk/Doc/Manual/makechap.py b/trunk/Doc/Manual/makechap.py
new file mode 100644
index 0000000..4dd048c
--- /dev/null
+++ b/trunk/Doc/Manual/makechap.py
@@ -0,0 +1,213 @@
+#!/usr/local/bin/python
+
+###############################################################################
+# Takes a chapter as input and adds internal links and numbering to all
+# of the H1, H2, H3, H4 and H5 sections.
+#
+# Every heading HTML tag (H1, H2 etc) is given an autogenerated name to link
+# to. However, if the name is not an autogenerated name from a previous run,
+# it will be kept. If it is autogenerated, it might change on subsequent runs
+# of this program. Thus if you want to create links to one of the headings,
+# then change the heading link name to something that does not look like an
+# autogenerated link name.
+###############################################################################
+
+import sys
+import re
+import string
+
+###############################################################################
+# Functions
+###############################################################################
+
+# Regexs for <a name="..."></a>
+alink = re.compile(r"<a *name *= *\"(.*)\"></a>", re.IGNORECASE)
+heading = re.compile(r"(_nn\d)", re.IGNORECASE)
+
+def getheadingname(m):
+    autogeneratedheading = True;
+    if m.group(1) != None:
+        amatch = alink.match(m.group(1))
+        if amatch:
+            # A non-autogenerated heading - keep it
+            headingname = amatch.group(1)
+            autogeneratedheading = heading.match(headingname)
+    if autogeneratedheading:
+        # The heading name was either non-existent or autogenerated,
+        # We can create a new heading / change the existing heading
+        headingname = "%s_nn%d" % (filenamebase, nameindex)
+    return headingname
+
+###############################################################################
+# Main program
+###############################################################################
+
+if len(sys.argv) != 3:
+    print "usage: makechap.py filename num"
+    sys.exit(1)
+
+filename = sys.argv[1]
+filenamebase = string.split(filename,".")[0]
+num      = int(sys.argv[2])
+
+section = 0
+subsection = 0
+subsubsection = 0
+nameindex = 0
+
+name = ""
+
+# Regexs for <h1>,... <h5> sections
+
+h1 = re.compile(r".*?<H1>(<a.*a>)*[\d\.\s]*(.*?)</H1>", re.IGNORECASE)
+h2 = re.compile(r".*?<H2>(<a.*a>)*[\d\.\s]*(.*?)</H2>", re.IGNORECASE)
+h3 = re.compile(r".*?<H3>(<a.*a>)*[\d\.\s]*(.*?)</H3>", re.IGNORECASE)
+h4 = re.compile(r".*?<H4>(<a.*a>)*[\d\.\s]*(.*?)</H4>", re.IGNORECASE)
+h5 = re.compile(r".*?<H5>(<a.*a>)*[\d\.\s]*(.*?)</H5>", re.IGNORECASE)
+
+data = open(filename).read()            # Read data
+open(filename+".bak","w").write(data)   # Make backup
+
+lines = data.splitlines()
+result = [ ] # This is the result of postprocessing the file
+index = "<!-- INDEX -->\n<div class=\"sectiontoc\">\n" # index contains the index for adding at the top of the file. Also printed to stdout.
+
+skip = 0
+skipspace = 0
+
+for s in lines:
+    if s == "<!-- INDEX -->":
+        if not skip:
+            skip = 1
+        else:
+            skip = 0
+        continue;
+    if skip:
+        continue
+
+    if not s and skipspace:
+        continue
+
+    if skipspace:
+        result.append("")
+        result.append("")
+        skipspace = 0
+    
+    m = h1.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        headingname = getheadingname(m)
+        result.append("""<H1><a name="%s"></a>%d %s</H1>""" % (headingname,num,prevheadingtext))
+        result.append("@INDEX@")
+        section = 0
+        subsection = 0
+        subsubsection = 0
+        subsubsubsection = 0
+        name = prevheadingtext
+        skipspace = 1
+        continue
+    m = h2.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        section += 1
+        headingname = getheadingname(m)
+        result.append("""<H2><a name="%s"></a>%d.%d %s</H2>""" % (headingname,num,section, prevheadingtext))
+
+        if subsubsubsection:
+            index += "</ul>\n"
+        if subsubsection:
+            index += "</ul>\n"
+        if subsection:
+            index += "</ul>\n"
+        if section == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        subsection = 0
+        subsubsection = 0
+        subsubsubsection = 0
+        skipspace = 1        
+        continue
+    m = h3.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        subsection += 1
+        headingname = getheadingname(m)
+        result.append("""<H3><a name="%s"></a>%d.%d.%d %s</H3>""" % (headingname,num,section, subsection, prevheadingtext))
+
+        if subsubsubsection:
+            index += "</ul>\n"
+        if subsubsection:
+            index += "</ul>\n"
+        if subsection == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        subsubsection = 0
+        skipspace = 1        
+        continue
+    m = h4.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        subsubsection += 1
+
+        headingname = getheadingname(m)
+        result.append("""<H4><a name="%s"></a>%d.%d.%d.%d %s</H4>""" % (headingname,num,section, subsection, subsubsection, prevheadingtext))
+
+        if subsubsubsection:
+            index += "</ul>\n"
+        if subsubsection == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        subsubsubsection = 0
+        skipspace = 1        
+        continue
+    m = h5.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        subsubsubsection += 1
+        headingname = getheadingname(m)
+        result.append("""<H5><a name="%s"></a>%d.%d.%d.%d.%d %s</H5>""" % (headingname,num,section, subsection, subsubsection, subsubsubsection, prevheadingtext))
+
+        if subsubsubsection == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        skipspace = 1
+        continue
+    
+    result.append(s)
+
+if subsubsubsection:
+    index += "</ul>\n"
+
+if subsubsection:
+    index += "</ul>\n"
+
+if subsection:
+    index += "</ul>\n"
+
+if section:
+    index += "</ul>\n"
+
+index += "</div>\n<!-- INDEX -->\n"
+
+data = "\n".join(result)
+
+data = data.replace("@INDEX@",index) + "\n";
+
+# Write the file back out
+open(filename,"w").write(data)
+
+# Print the TOC data to stdout correcting the anchor links for external referencing
+
+index = index.replace("<li><a href=\"#","<li><a href=\"%s#" % filename)
+print """<h3><a href="%s#%s">%d %s</a></h3>\n""" % (filename,filenamebase,num,name)
+print index
+
diff --git a/trunk/Doc/Manual/maketoc.py b/trunk/Doc/Manual/maketoc.py
new file mode 100644
index 0000000..c78bcfd
--- /dev/null
+++ b/trunk/Doc/Manual/maketoc.py
@@ -0,0 +1,37 @@
+#!/usr/local/bin/python
+
+import sys
+import os
+chs = open("chapters").readlines()
+
+f = open("Contents.html","w")
+print >>f, """
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<HTML>
+<HEAD>
+<TITLE>SWIG Users Manual</TITLE>
+</HEAD>
+<BODY BGCOLOR="#ffffff">
+<H1>SWIG Users Manual</H1>
+
+<p>
+"""
+
+f.close()
+
+num = 1
+
+for c in chs:
+    c = c.strip()
+    print "Processing %s" % c
+    if c:
+        os.system("python makechap.py %s %d >> Contents.html" % (c,num))
+    num += 1
+    
+f = open("Contents.html","a")
+print >>f, """
+</BODY>
+</HTML>
+"""
+
+
diff --git a/trunk/Doc/Manual/margin-left.patch b/trunk/Doc/Manual/margin-left.patch
new file mode 100644
index 0000000..70f087b
--- /dev/null
+++ b/trunk/Doc/Manual/margin-left.patch
@@ -0,0 +1,269 @@
+#
+# Patch managed by http://www.holgerschurig.de/patcher.html
+#
+# This patch is against htmldoc 1.8.24, and it hacks in support for
+# correctly indenting the <div class=""> sections in the SWIG manual.
+# This patch should only be used until the 1.9 branch of htmldoc
+# stabalizes, since the 1.9 branch includes true CSS1 support.
+#
+# This patch only affects the PDF generation, an unpatched htmldoc
+# creates the one-page html documentation just fine.
+#
+--- htmldoc-1.8.24/htmldoc/ps-pdf.cxx~margin-left
++++ htmldoc-1.8.24/htmldoc/ps-pdf.cxx
+@@ -158,6 +158,7 @@
+ #  undef page_t
+ #endif // __hpux
+ 
++extern int lookup_div_class(uchar *);
+ 
+ /*
+  * Constants...
+@@ -4188,9 +4189,24 @@
+             para->child = para->last_child = NULL;
+           }
+ 
+-          parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,
++	  {
++            int num_indent = 0;
++            uchar *cname;
++
++            if (cname = htmlGetVariable(t, (uchar *)"class")) {
++                    num_indent = lookup_div_class(cname);
++                    *left += 5.0f * num_indent;
++                    *x = *left;
++            }
++
++            parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,
+ 	            needspace);
+ 
++            if (num_indent > 0) {
++                *left -= 5.0f * num_indent;
++            }
++          }
++
+           if (para->child != NULL)
+           {
+             parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);
+--- htmldoc-1.8.24/htmldoc/htmldoc.cxx~margin-left
++++ htmldoc-1.8.24/htmldoc/htmldoc.cxx
+@@ -62,6 +62,8 @@
+ const char *__XOS2RedirRoot(const char *);
+ }
+ #endif
++
++extern void parse_style(char *);
+  
+ 
+ /*
+@@ -2140,6 +2142,10 @@
+     }
+     else if (strcmp(temp, "--cookies") == 0)
+       file_cookies(temp2);
++    else if (strcmp(temp, "--stylesheet") == 0)
++    {
++      parse_style(temp2);
++    }
+   }
+ }
+ 
+--- /dev/null
++++ htmldoc-1.8.24/htmldoc/style.cxx
+@@ -0,0 +1,185 @@
++/* Extreamly simple parsing routines for CSS style sheets.
++ * We only parse div.class { } sections, and only look
++ * for margin-left: <num>em;
++ *
++ * Copyright (C) 2005 John Lenz <lenz@cs.wisc.edu>
++ *
++ * Released under GNU GPL v2 or above.
++ */
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <fcntl.h>
++#include <string.h>
++#include <ctype.h>
++
++#include "types.h"
++
++#define BUFF_SIZE 512
++
++struct div_entry {
++	uchar class_name[BUFF_SIZE];
++	int indent;
++	struct div_entry *next;
++};
++
++static struct div_entry *head = 0;
++
++/* These are the parsing states */
++#define IGNORE_TILL_SEMI 	0
++#define IGNORE_TILL_CLOSE_BRACE	1
++#define READING_DIV		2
++#define READING_CLASS		3
++#define READING_ATTRIBUTE	4
++#define READING_NUM		5
++#define CHECKING_ONLY_DIV	6
++
++static int at_eof = 0;
++
++static int strucmp(uchar *a, uchar *b) {
++	int i;
++	for (i = 0; a[i] && b[i]; i++) {
++		if (a[i] < b[i]) return -1;
++		if (a[i] > b[i]) return 1;
++	}
++	/* This isn't right, but who cares...*/
++	if (a[i] || b[i]) return 1;
++	return 0;
++}
++
++static int read_word(FILE *f, const char *word) {
++	char c;
++	for (int idx = 0; word[idx]; idx++) {
++		c = getc(f);
++		if (c == EOF) {
++			at_eof = 1;
++			return 0;
++		}
++		if (c != word[idx])
++			return 0;
++	}
++	return 1;
++}
++
++int lookup_div_class(uchar *name) {
++	struct div_entry *node = head;
++
++	while (node) {
++		if (strucmp(node->class_name, name) == 0)
++			return node->indent;
++		node = node->next;
++	}
++
++	return 0;
++}
++
++void parse_style(char *fname) {
++	FILE *f;
++	char c;
++	int state;
++	struct div_entry *cur = 0;
++	int class_idx = 0;
++	char num[BUFF_SIZE];
++	int num_idx = 0;
++	
++	if (!fname) return;
++
++	f = fopen(fname, "r");
++	if (!f) {
++		fprintf(stderr, "Unable to parse style\n");
++		return;
++	}
++
++	state = READING_DIV;
++	while (!at_eof && (c = getc(f)) != EOF) {
++		switch (state) {
++			
++		case IGNORE_TILL_SEMI:
++			if (c == ';')
++				state = READING_ATTRIBUTE;
++			break;
++
++		case IGNORE_TILL_CLOSE_BRACE:
++			if (c == '}')
++				state = READING_DIV;
++			break;
++
++		case READING_DIV:
++			if (c != ' ' && c != '\t' && c != '\n') {
++				if (c == 'd' && read_word(f, "iv.")) {
++					state = READING_CLASS;
++					cur = (struct div_entry *) malloc(sizeof(struct div_entry));
++					memset(cur, 0, sizeof(struct div_entry));
++					class_idx = 0;
++				} else
++					state = IGNORE_TILL_CLOSE_BRACE;
++			}
++			break;
++				
++		case READING_CLASS:
++			if (isalpha(c)) {
++				if (class_idx >= BUFF_SIZE-1) {
++					fprintf(stderr, "class size %s too long\n", cur->class_name);
++					free(cur);
++					state = IGNORE_TILL_CLOSE_BRACE;
++				} else {
++					cur->class_name[class_idx++] = c;
++				}
++			} else {
++				if (c == '{') {
++					cur->next = head;
++					head = cur;
++					state = READING_ATTRIBUTE;
++				} else
++					state = CHECKING_ONLY_DIV;
++			}
++			break;
++
++		case READING_ATTRIBUTE:
++			if (c != ' ' && c != '\t' && c != '\n') {
++				if (c == '}')
++					state = READING_DIV;
++				else {
++					if (c == 'm' && read_word(f, "argin-left:")) {
++						num_idx = 0;
++						memset(num, 0, sizeof(num));
++						state = READING_NUM;
++					} else {
++						state = IGNORE_TILL_SEMI;
++					}
++				}
++			}
++			break;
++
++		case READING_NUM:
++			if (isdigit(c)) {
++				if (num_idx >= BUFF_SIZE - 1) {
++					fprintf(stderr, "Number too long\n");
++					state = IGNORE_TILL_SEMI;
++				} else {
++					num[num_idx++] = c;
++				}
++			} else if (c != ' ' && c != '\t') {
++				if (num_idx > 0 && c == 'e' && read_word(f, "m"))
++						cur->indent = atoi(num);
++				state = IGNORE_TILL_SEMI;
++			}
++			break;
++
++		case CHECKING_ONLY_DIV:
++			if (c != ' ' && c != '\t' && c != '\n') {
++				if (c == '{') {
++					cur->next = head;
++					head = cur;
++					state = READING_ATTRIBUTE;
++				} else {
++					free(cur);
++					state = IGNORE_TILL_CLOSE_BRACE;
++				}
++			}
++			break;
++		}
++	}
++
++	fclose(f);
++}
+--- htmldoc-1.8.24/htmldoc/Makefile~margin-left
++++ htmldoc-1.8.24/htmldoc/Makefile
+@@ -35,7 +35,7 @@
+ 
+ OBJS	=	gui.o file.o html.o htmldoc.o htmllib.o htmlsep.o http.o \
+ 		http-addr.o http-support.o image.o iso8859.o license.o md5.o \
+-		progress.o ps-pdf.o rc4.o snprintf.o string.o toc.o util.o
++		progress.o ps-pdf.o rc4.o snprintf.o string.o toc.o util.o style.o
+ 
+ 
+ #
+
diff --git a/trunk/Doc/Manual/style.css b/trunk/Doc/Manual/style.css
new file mode 100644
index 0000000..02329e5
--- /dev/null
+++ b/trunk/Doc/Manual/style.css
@@ -0,0 +1,84 @@
+div.sectiontoc {
+  border-style: dotted;
+  border-width: 2px;
+  padding: 2pt;
+}
+
+h2 { 
+  padding: 3px;
+  color: #000000;
+  border-bottom: 2px 
+  solid #dddddd; 
+}
+
+h3, h4 {
+  margin-left: 1em;
+}
+
+p,li,table,dl {
+  margin-left: 2em;
+  margin-right: 2em;
+}
+
+div.indent {
+  margin-left: 4em;
+  margin-right: 4em;
+}
+
+div.code {
+  border-style: solid; 
+  border-width: 1px; 
+  padding: 2pt; 
+  margin-left: 4em;
+  margin-right: 4em;
+  background-color: #F0FFFF;
+}
+
+div.targetlang {
+  border-style: solid; 
+  border-width: 1px; 
+  padding: 2pt; 
+  margin-left: 4em;
+  margin-right: 4em;
+  background-color: #d7f6bb;
+}
+
+
+div.shell {
+  border-style: solid; 
+  border-width: 1px; 
+  padding: 2pt; 
+  margin-left: 4em;
+  margin-right: 4em;
+  background-color: #DCDCDC;
+}
+
+div.diagram {
+  border-style: solid; 
+  border-width: 1px; 
+  padding: 2pt; 
+  margin-left: 4em;
+  margin-right: 4em;
+  background-color: #FFEBCD;
+}
+
+ul li p {
+  margin-left: 0;
+  margin-right: 0;
+}
+
+ol li p {
+  margin-left: 0;
+  margin-right: 0;
+}
+
+dl dd p {
+  margin-left: 0;
+  margin-right: 0;
+}
+
+div.indent p {
+  margin-left: 0;
+  margin-right: 0;
+}
+
diff --git a/trunk/Doc/Manual/swig16.png b/trunk/Doc/Manual/swig16.png
new file mode 100755
index 0000000..73f3adc
--- /dev/null
+++ b/trunk/Doc/Manual/swig16.png
Binary files differ
diff --git a/trunk/Doc/README b/trunk/Doc/README
new file mode 100644
index 0000000..1104281
--- /dev/null
+++ b/trunk/Doc/README
@@ -0,0 +1,5 @@
+Doc/Manual    -  Latest version of the SWIG user manual
+Doc/Devel     -  Developer documentation concerning SWIG internals.
+                 (not necessarily up to date)
+
+          
\ No newline at end of file
diff --git a/trunk/Examples/GIFPlot/Chicken/check.list b/trunk/Examples/GIFPlot/Chicken/check.list
new file mode 100644
index 0000000..e75ee58
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/check.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+full
+simple
diff --git a/trunk/Examples/GIFPlot/Chicken/full/Makefile b/trunk/Examples/GIFPlot/Chicken/full/Makefile
new file mode 100644
index 0000000..2ae4fd7
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/full/Makefile
@@ -0,0 +1,28 @@
+TOP         = ../../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = gifplot.i
+SRCS        = 
+CXXSRCS     = 
+TARGET      = gifplot
+INCLUDE     = -I. -I../../Include
+SWIGOPT     = -I../../Include
+CFLAGS      = 
+VARIANT     = 
+LIBS        = -L../.. -lgifplot -lm
+
+# comment the following two lines to build a dynamic so file
+CHICKEN_MAIN = test-gifplot.scm
+VARIANT      = _static
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f gifplot.scm image.gif
+	rm -f $(TARGET)
diff --git a/trunk/Examples/GIFPlot/Chicken/full/README b/trunk/Examples/GIFPlot/Chicken/full/README
new file mode 100644
index 0000000..e5ddd7a
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/full/README
@@ -0,0 +1,6 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The Scheme program 'test-gifplot.scm' does something a 
+little more interesting.  You'll have to go look at the header file to
+get a complete listing of the functions.
+
+`make' will build a static binary.  Run ./gifplot to test it.
diff --git a/trunk/Examples/GIFPlot/Chicken/full/cmap b/trunk/Examples/GIFPlot/Chicken/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Chicken/full/gifplot.i b/trunk/Examples/GIFPlot/Chicken/full/gifplot.i
new file mode 100644
index 0000000..f674186
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/full/gifplot.i
@@ -0,0 +1,26 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+/* Pixel is typedef'd to unsigned char, and SWIG will translate this
+   type into Scheme characters. We would like to translate Pixels to
+   Scheme integers instead, so: */
+
+SIMPLE_TYPEMAP(Pixel, C_unfix, C_fix, C_swig_is_fixnum, (int), 0);
+
+%{
+static Pixel int_to_Pixel (int v) { return (Pixel) v; }
+%}
+extern Pixel int_to_Pixel (int v);
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Chicken/full/test-gifplot.scm b/trunk/Examples/GIFPlot/Chicken/full/test-gifplot.scm
new file mode 100644
index 0000000..c290af5
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/full/test-gifplot.scm
@@ -0,0 +1,66 @@
+;;; Plot a 3D function
+
+(declare (uses gifplot))
+
+;; Here is the function to plot
+(define (func x y)
+  (* 5
+     (cos (* 2 (sqrt (+ (* x x) (* y y)))))
+     (exp (* -0.3 (sqrt (+ (* x x) (* y y)))))))
+
+;; Here are some plotting parameters
+(define xmin -5.0)
+(define xmax  5.0)
+(define ymin -5.0)
+(define ymax  5.0)
+(define zmin -5.0)
+(define zmax  5.0)
+
+;; Grid resolution
+(define nxpoints  60)
+(define nypoints  60)
+
+(define cmap (gifplot:new-ColorMap "cmap"))
+(define frame (gifplot:new-FrameBuffer 500 500))
+(gifplot:FrameBuffer-clear frame (gifplot:BLACK))
+
+(define p3 (gifplot:new-Plot3D frame xmin ymin zmin xmax ymax zmax))
+(gifplot:Plot3D-lookat p3 (* 2 (- zmax zmin)))
+(gifplot:Plot3D-autoperspective p3 40.0)
+(gifplot:Plot3D-rotu p3 60.0)
+(gifplot:Plot3D-rotr p3 30.0)
+(gifplot:Plot3D-rotd p3 10.0)
+
+(define (drawsolid)
+  (gifplot:Plot3D-clear p3 (gifplot:BLACK))
+  (gifplot:Plot3D-start p3)
+  (let ((dx (/ (- xmax xmin) nxpoints))
+	(dy (/ (- ymax ymin) nypoints))
+	(cscale (/ 240 (- zmax zmin))))
+    (let x-loop ((x xmin) (i 0))
+      (cond
+       ((< i nxpoints)
+	(let y-loop ((y ymin) (j 0))
+	  (cond
+	   ((< j nypoints)
+	    (let* ((z1 (func x y))
+		   (z2 (func (+ x dx) y))
+		   (z3 (func (+ x dx) (+ y dy)))
+		   (z4 (func x (+ y dy)))
+		   (c1 (* cscale (- z1 zmin)))
+		   (c2 (* cscale (- z2 zmin)))
+		   (c3 (* cscale (- z3 zmin)))
+		   (c4 (* cscale (- z4 zmin)))
+		   (cc (/ (+ c1 c2 c3 c4) 4))
+		   (c  (inexact->exact (round (max (min cc 239) 0)))))
+	      (gifplot:Plot3D-solidquad p3 x y z1 (+ x dx) y z2 (+ x dx) (+ y dy)
+				z3 x (+ y dy) z4 
+                                (gifplot:int->Pixel (+ c 16))))
+	    (y-loop (+ y dy) (+ j 1)))))
+	(x-loop (+ x dx) (+ i 1)))))))
+
+(display "Making a nice 3D plot...\n")
+(drawsolid)
+
+(gifplot:FrameBuffer-writeGIF frame cmap "image.gif")
+(display "Wrote image.gif\n")
diff --git a/trunk/Examples/GIFPlot/Chicken/simple/Makefile b/trunk/Examples/GIFPlot/Chicken/simple/Makefile
new file mode 100644
index 0000000..484e583
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/simple/Makefile
@@ -0,0 +1,28 @@
+TOP         = ../../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = simple.i
+SRCS        = 
+CXXSRCS     = 
+TARGET      = simple
+INCLUDE     = -I. -I../../Include
+SWIGOPT     = -I../../Include
+CFLAGS      = 
+VARIANT     = 
+LIBS        = -L../.. -lgifplot -lm
+
+# comment the following two lines to build a dynamic so file
+CHICKEN_MAIN = test-simple.scm
+VARIANT      = _static
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f simple.scm image.gif
+	rm -f $(TARGET)
diff --git a/trunk/Examples/GIFPlot/Chicken/simple/README b/trunk/Examples/GIFPlot/Chicken/simple/README
new file mode 100644
index 0000000..3b138f3
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  
+
+`make' will build an exe.  Run ./simple to test it.
diff --git a/trunk/Examples/GIFPlot/Chicken/simple/simple.i b/trunk/Examples/GIFPlot/Chicken/simple/simple.i
new file mode 100644
index 0000000..23ac8a8
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/simple/simple.i
@@ -0,0 +1,34 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned int Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants, which we redefine (from gifplot.h) so
+   that SWIG sees them */
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
diff --git a/trunk/Examples/GIFPlot/Chicken/simple/test-simple.scm b/trunk/Examples/GIFPlot/Chicken/simple/test-simple.scm
new file mode 100644
index 0000000..43250d8
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Chicken/simple/test-simple.scm
@@ -0,0 +1,29 @@
+;;; Draw some simple shapes
+
+(declare (uses simple))
+
+(display "Drawing some basic shapes\n")
+
+(define cmap (simple:new-ColorMap #f))
+(define f (simple:new-FrameBuffer 400 400))
+
+;; Clear the picture
+(simple:FrameBuffer-clear f (simple:BLACK))
+
+;; Make a red box
+(simple:FrameBuffer-box f 40 40 200 200 (simple:RED))
+
+;; Make a blue circle
+(simple:FrameBuffer-circle f 200 200 40 (simple:BLUE))
+
+;; Make green line
+(simple:FrameBuffer-line f 10 390 390 200 (simple:GREEN))
+
+;; Write an image out to disk
+
+(simple:FrameBuffer-writeGIF f cmap "image.gif")
+(display "Wrote image.gif\n")
+
+(simple:delete-FrameBuffer f)
+(simple:delete-ColorMap cmap)
+
diff --git a/trunk/Examples/GIFPlot/Common-Lisp/full/cmap b/trunk/Examples/GIFPlot/Common-Lisp/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Common-Lisp/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Common-Lisp/full/gifplot.i b/trunk/Examples/GIFPlot/Common-Lisp/full/gifplot.i
new file mode 100644
index 0000000..e5c15aa
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Common-Lisp/full/gifplot.i
@@ -0,0 +1,21 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+/* Pixel is typedef'd to unsigned char, and SWIG will translate this
+   type into Scheme characters. We would like to translate Pixels to
+   Scheme integers instead, so: */
+
+SIMPLE_MAP(Pixel, gh_scm2int, gh_int2scm, integer);
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Common-Lisp/full/runme.lisp b/trunk/Examples/GIFPlot/Common-Lisp/full/runme.lisp
new file mode 100644
index 0000000..48f8042
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Common-Lisp/full/runme.lisp
@@ -0,0 +1,59 @@
+;;; Plot a 3D function
+
+;; Here is the function to plot
+(defun func (x y)
+  (* 5
+     (cos (* 2 (sqrt (+ (* x x) (* y y)))))
+     (exp (* -0.3 (sqrt (+ (* x x) (* y y)))))))
+
+;; Here are some plotting parameters
+(defvar xmin -5D0)
+(defvar xmax  5D0)
+(defvar ymin -5D0)
+(defvar ymax  5D0)
+(defvar zmin -5D0)
+(defvar zmax  5D0)
+
+;; Grid resolution
+(defvar nxpoints  60)
+(defvar nypoints  60)
+
+(defun drawsolid (p3)
+  (Plot3D-clear p3 0)
+  (Plot3D-start p3)
+  (let ((dx (/ (- xmax xmin) nxpoints))
+	(dy (/ (- ymax ymin) nypoints))
+	(cscale (/ 240 (- zmax zmin))))
+    (loop for x from xmin by dx
+	  repeat nxpoints
+	  do (loop for y from ymin by dy
+		   repeat nypoints
+		   do (let* ((z1 (func x y))
+			     (z2 (func (+ x dx) y))
+			     (z3 (func (+ x dx) (+ y dy)))
+			     (z4 (func x (+ y dy)))
+			     (c1 (* cscale (- z1 zmin)))
+			     (c2 (* cscale (- z2 zmin)))
+			     (c3 (* cscale (- z3 zmin)))
+			     (c4 (* cscale (- z4 zmin)))
+			     (cc (/ (+ c1 c2 c3 c4) 4))
+			     (c  (round (max (min cc 239) 0))))
+			(Plot3D-solidquad p3 x y z1 (+ x dx) y z2 (+ x dx) (+ y dy)
+					  z3 x (+ y dy) z4 (+ c 16)))))))
+
+(defun action (cmap-filename)
+  (let ((cmap (new-ColorMap cmap-filename))
+	(frame (new-FrameBuffer 500 500)))
+    (format t "Making a nice 3D plot...~%")
+    (FrameBuffer-clear frame 0)
+    (let ((p3 (new-Plot3D frame xmin ymin zmin xmax ymax zmax)))
+      (Plot3D-lookat p3 (* 2 (- zmax zmin)))
+      (Plot3D-autoperspective p3 40D0)
+      (Plot3D-rotu p3 60D0)
+      (Plot3D-rotr p3 30D0)
+      (Plot3D-rotd p3 10D0)
+      (drawsolid p3))
+    (FrameBuffer-writeGIF frame cmap "/tmp/image.gif")
+    (format t "Wrote image.gif~%")))
+
+
diff --git a/trunk/Examples/GIFPlot/Guile/check.list b/trunk/Examples/GIFPlot/Guile/check.list
new file mode 100644
index 0000000..e75ee58
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/check.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+full
+simple
diff --git a/trunk/Examples/GIFPlot/Guile/full/Makefile b/trunk/Examples/GIFPlot/Guile/full/Makefile
new file mode 100644
index 0000000..1fcdf58
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/full/Makefile
@@ -0,0 +1,28 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+
+all:: static
+
+dynamic:: 
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile
+
+static::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Guile/full/README b/trunk/Examples/GIFPlot/Guile/full/README
new file mode 100644
index 0000000..9780988
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The Scheme program 'runme.scm' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Guile/full/cmap b/trunk/Examples/GIFPlot/Guile/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Guile/full/gifplot.i b/trunk/Examples/GIFPlot/Guile/full/gifplot.i
new file mode 100644
index 0000000..e5c15aa
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/full/gifplot.i
@@ -0,0 +1,21 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+/* Pixel is typedef'd to unsigned char, and SWIG will translate this
+   type into Scheme characters. We would like to translate Pixels to
+   Scheme integers instead, so: */
+
+SIMPLE_MAP(Pixel, gh_scm2int, gh_int2scm, integer);
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Guile/full/runme.scm b/trunk/Examples/GIFPlot/Guile/full/runme.scm
new file mode 100644
index 0000000..0ffe921
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/full/runme.scm
@@ -0,0 +1,66 @@
+;;; Plot a 3D function
+
+;; Use the wrapped GIFPlot library
+(use-modules (gifplot))
+
+;; Here is the function to plot
+(define (func x y)
+  (* 5
+     (cos (* 2 (sqrt (+ (* x x) (* y y)))))
+     (exp (* -0.3 (sqrt (+ (* x x) (* y y)))))))
+
+;; Here are some plotting parameters
+(define xmin -5.0)
+(define xmax  5.0)
+(define ymin -5.0)
+(define ymax  5.0)
+(define zmin -5.0)
+(define zmax  5.0)
+
+;; Grid resolution
+(define nxpoints  60)
+(define nypoints  60)
+
+(define cmap (new-ColorMap "cmap"))
+(define frame (new-FrameBuffer 500 500))
+(FrameBuffer-clear frame (BLACK))
+
+(define p3 (new-Plot3D frame xmin ymin zmin xmax ymax zmax))
+(Plot3D-lookat p3 (* 2 (- zmax zmin)))
+(Plot3D-autoperspective p3 40)
+(Plot3D-rotu p3 60)
+(Plot3D-rotr p3 30)
+(Plot3D-rotd p3 10)
+
+(define (drawsolid)
+  (Plot3D-clear p3 (BLACK))
+  (Plot3D-start p3)
+  (let ((dx (/ (- xmax xmin) nxpoints))
+	(dy (/ (- ymax ymin) nypoints))
+	(cscale (/ 240 (- zmax zmin))))
+    (let x-loop ((x xmin) (i 0))
+      (cond
+       ((< i nxpoints)
+	(let y-loop ((y ymin) (j 0))
+	  (cond
+	   ((< j nypoints)
+	    (let* ((z1 (func x y))
+		   (z2 (func (+ x dx) y))
+		   (z3 (func (+ x dx) (+ y dy)))
+		   (z4 (func x (+ y dy)))
+		   (c1 (* cscale (- z1 zmin)))
+		   (c2 (* cscale (- z2 zmin)))
+		   (c3 (* cscale (- z3 zmin)))
+		   (c4 (* cscale (- z4 zmin)))
+		   (cc (/ (+ c1 c2 c3 c4) 4))
+		   (c  (round (max (min cc 239) 0))))
+	      (Plot3D-solidquad p3 x y z1 (+ x dx) y z2 (+ x dx) (+ y dy)
+				z3 x (+ y dy) z4 (+ c 16)))
+	    (y-loop (+ y dy) (+ j 1)))))
+	(x-loop (+ x dx) (+ i 1)))))))
+
+(display "Making a nice 3D plot...\n")
+(drawsolid)
+
+(FrameBuffer-writeGIF frame cmap "image.gif")
+(display "Wrote image.gif\n")
diff --git a/trunk/Examples/GIFPlot/Guile/simple/Makefile b/trunk/Examples/GIFPlot/Guile/simple/Makefile
new file mode 100644
index 0000000..7986214
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/simple/Makefile
@@ -0,0 +1,28 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    =
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all:: static
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile
+
+static::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Guile/simple/README b/trunk/Examples/GIFPlot/Guile/simple/README
new file mode 100644
index 0000000..1925efa
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/simple/README
@@ -0,0 +1,11 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  
+
+`make' will build a version of Guile which defines an additional
+module (simple).  Run `./simple-guile -s runme.scm' to test it.
+
+`make dynamic' will build a dynamically loadable module, which can be
+loaded from any Guile interpreter.  Run `guile -s runme.scm' to test
+it.  The `use-modules' call in `runme.scm' dynamically loads the
+module. 
diff --git a/trunk/Examples/GIFPlot/Guile/simple/runme.scm b/trunk/Examples/GIFPlot/Guile/simple/runme.scm
new file mode 100644
index 0000000..40ec181
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/simple/runme.scm
@@ -0,0 +1,30 @@
+;;; Draw some simple shapes
+
+;; Use the wrapped GIFPlot library
+(use-modules (simple))
+
+(display "Drawing some basic shapes\n")
+
+(define cmap (new-ColorMap))
+(define f (new-FrameBuffer 400 400))
+
+;; Clear the picture
+(FrameBuffer-clear f (BLACK))
+
+;; Make a red box
+(FrameBuffer-box f 40 40 200 200 (RED))
+
+;; Make a blue circle
+(FrameBuffer-circle f 200 200 40 (BLUE))
+
+;; Make green line
+(FrameBuffer-line f 10 390 390 200 (GREEN))
+
+;; Write an image out to disk
+
+(FrameBuffer-writeGIF f cmap "image.gif")
+(display "Wrote image.gif\n")
+
+(delete-FrameBuffer f)
+(delete-ColorMap cmap)
+
diff --git a/trunk/Examples/GIFPlot/Guile/simple/simple.i b/trunk/Examples/GIFPlot/Guile/simple/simple.i
new file mode 100644
index 0000000..86eaabd
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Guile/simple/simple.i
@@ -0,0 +1,34 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned int Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
diff --git a/trunk/Examples/GIFPlot/Include/gifplot.h b/trunk/Examples/GIFPlot/Include/gifplot.h
new file mode 100644
index 0000000..85e4c10
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Include/gifplot.h
@@ -0,0 +1,333 @@
+/* ----------------------------------------------------------------------------- 
+ * gifplot.h
+ *
+ *     Main header file for the GIFPlot library.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <float.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#ifndef GIFPLOT_H
+
+#ifdef SWIG
+%nodefault;
+#endif
+
+/* Pixel is 8-bits */
+
+typedef unsigned char Pixel;
+typedef float Zvalue;
+
+/* ------------------------------------------------------------------------
+   ColorMap
+
+   Definition and methods for colormaps
+   ------------------------------------------------------------------------ */
+
+typedef struct ColorMap {
+  unsigned char          *cmap;
+  char                   *name;
+} ColorMap;
+
+extern ColorMap *new_ColorMap(char *filename);
+extern void      delete_ColorMap(ColorMap *c);
+extern void      ColorMap_default(ColorMap *c);
+extern void      ColorMap_assign(ColorMap *c, int index, int r, int g, int b);
+extern int       ColorMap_getitem(ColorMap *c, int index);
+extern void      ColorMap_setitem(ColorMap *c, int index, int value);
+extern int       ColorMap_write(ColorMap *c, char *filename);
+
+/* Some default colors */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+/*-------------------------------------------------------------------------
+  FrameBuffer
+
+  This structure defines a simple 8 bit framebuffer.  
+  ------------------------------------------------------------------------- */
+
+typedef struct FrameBuffer {
+  Pixel         **pixels;
+  Zvalue        **zbuffer;
+  unsigned int    height;
+  unsigned int    width;
+  int             xmin;      /* These are used for clipping */
+  int             ymin;
+  int             xmax;
+  int             ymax;
+} FrameBuffer;
+
+#define ZMIN  1e+36
+
+/* FrameBuffer Methods */
+
+extern FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+extern void         delete_FrameBuffer(FrameBuffer *frame);
+extern int          FrameBuffer_resize(FrameBuffer *frame, int width, int height);
+extern void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+extern void         FrameBuffer_plot(FrameBuffer *frame, int x, int y, Pixel color);
+extern void         FrameBuffer_horizontal(FrameBuffer *frame, int xmin, int xmax, int y, Pixel color);
+extern void         FrameBuffer_horizontalinterp(FrameBuffer *f, int xmin, int xmax, int y,  Pixel c1, Pixel c2);
+extern void         FrameBuffer_vertical(FrameBuffer *frame, int ymin, int ymax, int x, Pixel color);
+extern void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+extern void         FrameBuffer_solidbox(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+extern void         FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4);
+extern void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+extern void         FrameBuffer_solidcircle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+extern void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+extern void         FrameBuffer_setclip(FrameBuffer *frame, int xmin, int ymin, int xmax, int ymax);
+extern void         FrameBuffer_noclip(FrameBuffer *frame);
+extern int          FrameBuffer_makeGIF(FrameBuffer *frame, ColorMap *cmap, void *buffer, unsigned int maxsize);
+extern int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+extern void         FrameBuffer_zresize(FrameBuffer *f, int width, int height);
+extern void         FrameBuffer_zclear(FrameBuffer *f);
+extern void         FrameBuffer_solidtriangle(FrameBuffer *f, int x1, int y1, int x2, int y2, int x3, int y3, Pixel c);
+extern void         FrameBuffer_interptriangle(FrameBuffer *f, int tx1, int ty1, Pixel c1,
+                                               int tx2, int ty2, Pixel c2, int tx3, int ty3, Pixel c3);
+
+#define  HORIZONTAL  1
+#define  VERTICAL    2
+
+extern void         FrameBuffer_drawchar(FrameBuffer *frame, int x, int y, int fgcolor, int bgcolor, char chr, int orientation);
+extern void         FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, int bgcolor, char *text, int orientation);
+
+/* ------------------------------------------------------------------------
+   PixMap
+
+   The equivalent of "bit-maps".
+   ------------------------------------------------------------------------ */
+
+typedef struct PixMap {
+  int    width;
+  int    height;
+  int    centerx;
+  int    centery;
+  int   *map;
+} PixMap;
+
+/* PIXMAP methods */
+
+extern PixMap   *new_PixMap(int width, int height, int centerx, int centery);
+extern void      delete_PixMap(PixMap *pm);
+extern void      PixMap_set(PixMap *pm, int x, int y, int pix);
+extern void      FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor);
+
+#define   GIFPLOT_TRANSPARENT  0
+#define   GIFPLOT_FOREGROUND   1
+#define   GIFPLOT_BACKGROUND   2
+
+/* ------------------------------------------------------------------------
+   Plot2D
+
+   Definition and methods for 2D plots.
+   ------------------------------------------------------------------------ */
+
+typedef struct Plot2D {
+  FrameBuffer    *frame;        /* what frame buffer are we using     */
+  int             view_xmin;    /* Minimum coordinates of view region */
+  int             view_ymin;    
+  int             view_xmax;    /* Maximum coordinates of view region */
+  int             view_ymax;    
+  double          xmin;         /* Minimum coordinates of plot region */
+  double          ymin;
+  double          xmax;         /* Maximum coordinates of plot region */
+  double          ymax;
+  int             xscale;       /* Type of scaling (LINEAR, LOG, etc..) */
+  int             yscale;       
+  double          dx;           /* Private scaling parameters         */
+  double          dy;
+} Plot2D;
+
+/* 2D Plot methods */
+
+extern Plot2D  *new_Plot2D(FrameBuffer *frame,double xmin,double ymin, double xmax, double ymax);
+extern void     delete_Plot2D(Plot2D *p2);
+extern Plot2D  *Plot2D_copy(Plot2D *p2);
+extern void     Plot2D_clear(Plot2D *p2, Pixel c);
+extern void     Plot2D_setview(Plot2D *p2, int vxmin, int vymin, int vxmax, int vymax);
+extern void     Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax);
+extern void     Plot2D_setscale(Plot2D *p2, int xscale, int yscale);
+extern void     Plot2D_plot(Plot2D *p2, double x, double y, Pixel color);
+extern void     Plot2D_box(Plot2D *p2, double x1, double y1,  double x2, double y2, Pixel color);
+extern void     Plot2D_solidbox(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color);
+extern void     Plot2D_interpbox(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4);
+extern void     Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color);
+extern void     Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color);
+extern void     Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color);
+extern void     Plot2D_start(Plot2D *p2);
+extern void     Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor);
+extern void     Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel c);
+extern void     Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel c);
+extern void     Plot2D_triangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c);
+extern void     Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c);
+extern void     Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1,
+                                                  double x2, double y2, Pixel c2,
+                                                  double x3, double y3, Pixel c3);
+
+#define LINEAR     10
+#define LOG        11
+
+/* -----------------------------------------------------------------------
+   Matrix
+   
+   Operations on 4x4 transformation matrices and vectors.
+   Matrices are represented as a double array of 16 elements
+   ----------------------------------------------------------------------- */
+
+typedef  double *Matrix;
+typedef struct GL_Vector {
+  double x;
+  double y;
+  double z;
+  double w;
+} GL_Vector;
+
+extern Matrix new_Matrix();
+extern void   delete_Matrix(Matrix a);
+extern Matrix Matrix_copy(Matrix a);
+extern void   Matrix_multiply(Matrix a, Matrix b, Matrix c);
+extern void   Matrix_identity(Matrix a);
+extern void   Matrix_zero(Matrix a);
+extern void   Matrix_transpose(Matrix a, Matrix result);
+extern void   Matrix_invert(Matrix a, Matrix inva);
+extern void   Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t);
+extern void   Matrix_transform4(Matrix a, double rx, double ry, double rz,
+				double rw, GL_Vector *t);
+
+extern void   Matrix_print(Matrix a);
+extern void   Matrix_translate(Matrix a, double tx, double ty, double tz);
+extern void   Matrix_rotatex(Matrix a, double deg);
+extern void   Matrix_rotatey(Matrix a, double deg);
+extern void   Matrix_rotatez(Matrix a, double deg);
+
+/* -----------------------------------------------------------------------
+   Plot3D
+
+   Data Structure for 3-D plots
+   ------------------------------------------------------------------------ */
+
+typedef struct Plot3D {
+  FrameBuffer   *frame;      /* Frame buffer being used */
+  int            view_xmin;  /* Viewing region */
+  int            view_ymin;
+  int            view_xmax;
+  int            view_ymax;
+  double         xmin;       /* Bounding box */
+  double         ymin;
+  double         zmin;
+  double         xmax;
+  double         ymax;
+  double         zmax;
+  double         xcenter;    /* Center point */
+  double         ycenter;
+  double         zcenter;
+  double         fovy;       /* Field of view */
+  double         aspect;     /* Aspect ratio  */
+  double         znear;      /* near "clipping" plane */
+  double         zfar;       /* far "clipping" plane */
+  Matrix         center_mat; /* Matrix used for centering the model */
+  Matrix         model_mat;  /* Model rotation matrix */
+  Matrix         view_mat;   /* Viewing matrix */
+  Matrix         fullmodel_mat;  /* Full model matrix.  Used by sphere plot */
+  Matrix         trans_mat;  /* Total transformation matrix */
+  double         lookatz;    /* Where is the z-lookat point */
+  double         xshift;     /* Used for translation and stuff */
+  double         yshift;
+  double         zoom;
+  int            width;
+  int            height;
+  int            pers_mode;  /* Perspective mode (private) */
+  double         ortho_left,ortho_right,ortho_bottom,ortho_top;
+} Plot3D;
+
+extern Plot3D *new_Plot3D(FrameBuffer *frame, double xmin, double ymin, double zmin,
+			  double xmax, double ymax, double zmax);
+extern void   delete_Plot3D(Plot3D *p3);
+extern Plot3D *Plot3D_copy(Plot3D *p3);
+extern void   Plot3D_clear(Plot3D *p3, Pixel Color);
+extern void   Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar);
+extern void   Plot3D_ortho(Plot3D *p3, double left, double right, double top, double bottom);
+extern void   Plot3D_lookat(Plot3D *p3, double z);
+extern void   Plot3D_autoperspective(Plot3D *p3, double fovy);
+extern void   Plot3D_autoortho(Plot3D *p3);
+extern void   Plot3D_rotx(Plot3D *p3, double deg);
+extern void   Plot3D_roty(Plot3D *p3, double deg);
+extern void   Plot3D_rotz(Plot3D *p3, double deg);
+extern void   Plot3D_rotl(Plot3D *p3, double deg);
+extern void   Plot3D_rotr(Plot3D *p3, double deg);
+extern void   Plot3D_rotd(Plot3D *p3, double deg);
+extern void   Plot3D_rotu(Plot3D *p3, double deg);
+extern void   Plot3D_rotc(Plot3D *p3, double deg);
+extern void   Plot3D_zoom(Plot3D *p3, double percent);
+extern void   Plot3D_left(Plot3D *p3, double percent);
+extern void   Plot3D_right(Plot3D *p3, double percent);
+extern void   Plot3D_down(Plot3D *p3, double percent);
+extern void   Plot3D_up(Plot3D *p3, double percent);
+extern void   Plot3D_center(Plot3D *p3, double cx, double cy);
+
+extern void   Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel Color);
+
+extern void   Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax);
+extern void   Plot3D_start(Plot3D *p3);
+extern void   Plot3D_line(Plot3D *p3, double x1, double y1, double z1,
+			 double x2, double y2, double z2, Pixel color);
+extern void   Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1,
+		     double x2, double y2, double z2,
+		     double x3, double y3, double z3, Pixel color);
+extern void   Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1,
+		     double x2, double y2, double z2,
+		     double x3, double y3, double z3, Pixel color);
+
+extern void Plot3D_interptriangle(Plot3D *p3,
+			   double x1, double y1, double z1, Pixel c1,
+			   double x2, double y2, double z2, Pixel c2,
+			   double x3, double y3, double z3, Pixel c3);
+
+extern void   Plot3D_quad(Plot3D *p3, double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color);
+
+extern void   Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color);
+
+extern void   Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1,
+		       double x2, double y2, double z2, Pixel c2,
+		       double x3, double y3, double z3, Pixel c3,
+		       double x4, double y4, double z4, Pixel c4);
+
+
+extern void   Plot3D_solidsphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c);
+
+extern void   Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c, Pixel bc);
+
+extern PixMap  PixMap_SQUARE;
+extern PixMap  PixMap_TRIANGLE;
+extern PixMap  PixMap_CROSS;
+
+#endif
+#define GIFPLOT_H
+
+
+
diff --git a/trunk/Examples/GIFPlot/Interface/gifplot.i b/trunk/Examples/GIFPlot/Interface/gifplot.i
new file mode 100644
index 0000000..fdf661c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Interface/gifplot.i
@@ -0,0 +1,264 @@
+//
+// Graphics module
+//
+%module gifplot
+%{
+#include "gifplot.h"
+%}
+
+#if defined(SWIGJAVA ) || defined(SWIGPHP)
+  %rename(make_default) ColorMap::default();
+#endif
+
+%rename(__getitem__)  ColorMap::getitem(int index);
+%rename(__setitem__)  ColorMap::setitem(int index, int value);
+
+/* Pixel is 8-bits */
+
+typedef unsigned char Pixel;
+typedef float Zvalue;
+
+/* ------------------------------------------------------------------------
+   ColorMap
+
+   Definition and methods for colormaps
+   ------------------------------------------------------------------------ */
+
+typedef struct ColorMap {
+  char          *name;
+
+//
+// %extend adds some C methods to this structure to make it
+// look like a C++ class in Python.
+// These are really named things like ColorMap_default, ColorMap_assign, etc...
+
+  %extend {
+    ColorMap(char *filename);
+    ~ColorMap();
+    void        default();
+    void        assign(int index,int r, int g, int b);
+    int getitem(int index);
+    void setitem(int index, int value);
+    int         write(char *filename);
+  }
+} ColorMap;
+
+/* Some default colors */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+/*-------------------------------------------------------------------------
+  FrameBuffer
+
+  This structure defines a simple 8 bit framebuffer.  
+  ------------------------------------------------------------------------- */
+
+typedef struct FrameBuffer {
+  unsigned int    height;
+  unsigned int    width;
+  int             xmin;      /* These are used for clipping */
+  int             ymin;
+  int             xmax;
+  int             ymax;
+  %extend {
+    FrameBuffer(unsigned int width, unsigned int height);
+    ~FrameBuffer();
+    void resize(int width, int height);
+    void clear(Pixel color);
+    void plot(int x, int y, Pixel color);
+    void horizontal(int xmin, int xmax, int y, Pixel color);
+    void horizontalinterp(int xmin, int xmax, int y,  Pixel c1, Pixel c2);
+    void vertical(int ymin, int ymax, int x, Pixel color);
+    void box(int x1, int y1,  int x2, int y2, Pixel color);
+    void solidbox(int x1, int y1, int x2, int y2, Pixel color);
+    void interpbox(int x1, int y1, int x2, int y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4);
+    void circle(int x1, int y1, int radius, Pixel color);
+    void solidcircle(int x1, int y1, int radius, Pixel color);
+    void line(int x1, int y1, int x2, int y2, Pixel color);
+    void setclip(int xmin, int ymin, int xmax, int ymax);
+    void noclip();
+    int  makeGIF(ColorMap *cmap, void *buffer, unsigned int maxsize);
+    void zresize(int width, int height);
+    void zclear();
+    void drawchar(int x, int y, int fgcolor, int bgcolor, char chr, int orientation);
+    void drawstring(int x, int y, int fgcolor, int bgcolor, char *text, int orientation);
+    void drawpixmap(PixMap *pm, int x, int y, int fgcolor, int bgcolor);
+    int  writeGIF(ColorMap *cmap, char *filename);	
+  }
+} FrameBuffer;
+
+#define  HORIZONTAL  1
+#define  VERTICAL    2
+
+/* --------------------------------------------------------------------------
+   PixMap
+
+   The equivalent of "bit-maps".
+   -------------------------------------------------------------------------- */
+
+/* PIXMAP methods */
+
+extern PixMap   *new_PixMap(int width, int height, int centerx, int centery);
+extern void      delete_PixMap(PixMap *pm);
+extern void      PixMap_set(PixMap *pm, int x, int y, int pix);
+
+#define   GIFPLOT_TRANSPARENT  0
+#define   GIFPLOT_FOREGROUND   1
+#define   GIFPLOT_BACKGROUND   2
+
+/* --------------------------------------------------------------------------
+   Plot2D
+
+   Definition and methods for 2D plots.
+   --------------------------------------------------------------------------- */
+
+typedef struct Plot2D {
+  FrameBuffer     *frame;
+  int             view_xmin;    /* Minimum coordinates of view region */
+  int             view_ymin;    
+  int             view_xmax;    /* Maximum coordinates of view region */
+  int             view_ymax;    
+  double          xmin;         /* Minimum coordinates of plot region */
+  double          ymin;
+  double          xmax;         /* Maximum coordinates of plot region */
+  double          ymax;
+  int             xscale;       /* Type of scaling (LINEAR, LOG, etc..) */
+  int             yscale;       
+  %extend {
+       Plot2D(FrameBuffer *frame,double xmin,double ymin,  double xmax, double ymax);
+       ~Plot2D();
+       Plot2D  *copy();
+       void     clear(Pixel c);
+       void     setview(int vxmin, int vymin, int vxmax, int vymax);
+       void     setrange(double xmin, double ymin, double xmax, double ymax);
+       void     setscale(int xscale, int yscale);
+       void     plot(double x, double y, Pixel color);
+       void     box(double x1, double y1, double x2, double y2, Pixel color);
+       void     solidbox(double x1, double y1,	double x2, double y2, Pixel color);
+       void     interpbox(double x1, double y1, double x2, double y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4);
+
+       void     circle(double x, double y, double radius, Pixel color);
+       void     solidcircle(double x, double y,  double radius, Pixel color);
+       void     line(double x1, double y1,  double x2, double y2, Pixel color);
+       void     start();
+       void     drawpixmap(PixMap *pm, double x, double y, Pixel color, Pixel bgcolor);
+       void     xaxis(double x, double y, double xtick, int ticklength, Pixel color);
+       void     yaxis(double x, double y, double ytick, int ticklength, Pixel color);
+       void     triangle(double x1, double y1, double x2, double y2, double x3, double y3, Pixel c);
+
+       void     solidtriangle(double x1, double y1, double x2, double y2, double x3, double y3, Pixel c);
+
+       void     interptriangle(double x1, double y1, Pixel c1,
+			   double x2, double y2, Pixel c2,
+			   double x3, double y3, Pixel c3);
+
+  }
+} Plot2D;
+
+#define LINEAR     10
+#define LOG        11
+
+/* ------------------------------------------------------------------------------
+   Plot3D
+
+   Data Structure for 3-D plots
+   ------------------------------------------------------------------------------ */
+
+typedef struct Plot3D {
+  FrameBuffer    *frame;
+  int            view_xmin;  /* Viewing region */
+  int            view_ymin;
+  int            view_xmax;
+  int            view_ymax;
+  double         xmin;       /* Bounding box */
+  double         ymin;
+  double         zmin;
+  double         xmax;
+  double         ymax;
+  double         zmax;
+  double         xcenter;    /* Center point */
+  double         ycenter;
+  double         zcenter;
+  double         fovy;       /* Field of view */
+  double         aspect;     /* Aspect ratio  */
+  double         znear;      /* near "clipping" plane */
+  double         zfar;       /* far "clipping" plane */
+  double         lookatz;    /* Where is the z-lookat point */
+  double         xshift;     /* Used for translation and stuff */
+  double         yshift;
+  %extend {
+    Plot3D(FrameBuffer *frame, double xmin, double ymin, double zmin, double xmax, double ymax, double zmax);
+    ~Plot3D();
+    Plot3D *copy();
+    void   clear(Pixel bgcolor);
+    void   perspective( double fovy, double znear, double zfar);
+    void   lookat( double z);
+    void   autoperspective( double fovy);
+    void   ortho(double left, double right, double bottom, double top);
+    void   autoortho();
+    void   rotx( double deg);
+    void   roty( double deg);
+    void   rotz( double deg);
+    void   rotl( double deg);
+    void   rotr( double deg);
+    void   rotd( double deg);
+    void   rotu( double deg);
+    void   rotc( double deg);
+    void   zoom( double percent);
+    void   left( double percent);
+    void   right( double percent);
+    void   down( double percent);
+    void   up( double percent);
+    void   center( double cx, double cy);
+    void   plot( double x, double y, double z, Pixel Color);
+    void   setview( int vxmin, int vymin, int vxmax, int vymax);
+    void   start();
+    void   line( double x1, double y1, double z1,
+		 double x2, double y2, double z2, Pixel color);
+    void   triangle( double x1, double y1, double z1,
+		     double x2, double y2, double z2,
+		     double x3, double y3, double z3, Pixel color);
+    void   solidtriangle( double x1, double y1, double z1,
+			  double x2, double y2, double z2,
+			  double x3, double y3, double z3, Pixel color);
+    void interptriangle(double x1, double y1, double z1, Pixel c1,
+			double x2, double y2, double z2, Pixel c2,
+			double x3, double y3, double z3, Pixel c3);
+    void   quad( double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color);
+    void   solidquad( double x1, double y1, double z1,
+		      double x2, double y2, double z2,
+		      double x3, double y3, double z3,
+		      double x4, double y4, double z4,
+		      Pixel color);
+    void   interpquad( double x1, double y1, double z1, Pixel c1,
+		       double x2, double y2, double z2, Pixel c2,
+		       double x3, double y3, double z3, Pixel c3,
+		       double x4, double y4, double z4, Pixel c4);
+    void   solidsphere( double x, double y, double z, double radius,Pixel c);
+    void   outlinesphere( double x, double y, double z, double radius,Pixel c, Pixel bc);
+  }
+} Plot3D;
+
+#ifndef SWIGJAVA
+/* These directives create constants of a specific type.  They
+   do not correspond to any C variable or declared constant in the
+   header file */
+%constant PixMap * SQUARE = &PixMap_SQUARE;
+%constant PixMap * TRIANGLE = &PixMap_TRIANGLE;
+%constant PixMap * CROSS = &PixMap_CROSS;
+#endif
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Java/check.list b/trunk/Examples/GIFPlot/Java/check.list
new file mode 100644
index 0000000..13de977
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/check.list
@@ -0,0 +1,4 @@
+# see top-level Makefile.in
+full
+shadow
+simple
diff --git a/trunk/Examples/GIFPlot/Java/full/Makefile b/trunk/Examples/GIFPlot/Java/full/Makefile
new file mode 100644
index 0000000..8f16723
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/full/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include -noproxy
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Java/full/README b/trunk/Examples/GIFPlot/Java/full/README
new file mode 100644
index 0000000..f536864
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The program 'main.java' does something a little more 
+interesting. After doing a make, run it using 'java main'. You'll have to go 
+look at the header file to get a complete listing of the functions.
+
+Note the differences in the main.java files between this example and the  
+'full' example. This example does not use shadow classes.
+
diff --git a/trunk/Examples/GIFPlot/Java/full/cmap b/trunk/Examples/GIFPlot/Java/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Java/full/gifplot.i b/trunk/Examples/GIFPlot/Java/full/gifplot.i
new file mode 100644
index 0000000..5a7f500
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Java/full/main.java b/trunk/Examples/GIFPlot/Java/full/main.java
new file mode 100644
index 0000000..8fb65c8
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/full/main.java
@@ -0,0 +1,75 @@
+// Plot a 3D function
+import java.lang.Math;
+
+public class main {
+
+  static {
+    try {
+        System.loadLibrary("gifplot");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    
+    // Here are some plotting parameters
+    double xmin = -5.0;
+    double xmax =  5.0;
+    double ymin = -5.0;
+    double ymax =  5.0;
+    double zmin = -5.0;
+    double zmax =  5.0;
+    
+    // Grid resolution
+    int nxpoints =  60;
+    int nypoints =  60;
+    
+    SWIGTYPE_p_ColorMap cmap  = gifplot.new_ColorMap("cmap");
+    SWIGTYPE_p_FrameBuffer frame = gifplot.new_FrameBuffer(500,500);
+    gifplot.FrameBuffer_clear(frame,(short)gifplot.BLACK);
+    
+    SWIGTYPE_p_Plot3D p3    = gifplot.new_Plot3D(frame,xmin,ymin,zmin,xmax,ymax,zmax);
+    gifplot.Plot3D_lookat(p3,2*(zmax-zmin));
+    gifplot.Plot3D_autoperspective(p3,40);
+    gifplot.Plot3D_rotu(p3,60);
+    gifplot.Plot3D_rotr(p3,30);
+    gifplot.Plot3D_rotd(p3,10);
+    
+    System.out.println( "Making a nice 3D plot..." );
+    gifplot.Plot3D_clear(p3,(short)gifplot.BLACK);
+    gifplot.Plot3D_start(p3);
+    double dx = 1.0*(xmax-xmin)/nxpoints;
+    double dy = 1.0*(ymax-ymin)/nypoints;
+    double cscale = 240.0/(zmax-zmin);
+    double x = xmin;
+    for (int i = 0; i < nxpoints; i++) {
+      double y = ymin;
+      for (int j = 0; j < nypoints; j++) {
+        double z1 = func(x,y);
+        double z2 = func(x+dx,y);
+        double z3 = func(x+dx,y+dy);
+        double z4 = func(x,y+dy);
+        double c1 = cscale*(z1-zmin);
+        double c2 = cscale*(z2-zmin);
+        double c3 = cscale*(z3-zmin);
+        double c4 = cscale*(z4-zmin);
+        double c = (c1+c2+c3+c4)/4;
+        if (c < 0) c = 0;
+        if (c > 239) c = 239;
+        gifplot.Plot3D_solidquad(p3,x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,(short)(c+16));
+        y = y + dy;
+      }
+      x = x + dx;
+    }
+
+    gifplot.FrameBuffer_writeGIF(frame,cmap,"image.gif");
+    System.out.println( "Wrote image.gif" );
+  } 
+
+  // Here is the function to plot
+  public static double func(double x, double y) {
+    return 5*java.lang.Math.cos(2*java.lang.Math.sqrt(x*x+y*y))*java.lang.Math.exp(-0.3*java.lang.Math.sqrt(x*x+y*y));
+  }
+}
diff --git a/trunk/Examples/GIFPlot/Java/shadow/Makefile b/trunk/Examples/GIFPlot/Java/shadow/Makefile
new file mode 100644
index 0000000..e513b9b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/shadow/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Interface
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Java/shadow/README b/trunk/Examples/GIFPlot/Java/shadow/README
new file mode 100644
index 0000000..4adbde3
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/shadow/README
@@ -0,0 +1,5 @@
+This example uses the file in ../../Interface/gifplot.i to build
+an interface with shadow classes.  After doing a make, run the program main, ie: 'java main'.
+
+Note the differences in the main.java files between this example and the  
+'full' example. This example uses the shadow classes.
diff --git a/trunk/Examples/GIFPlot/Java/shadow/cmap b/trunk/Examples/GIFPlot/Java/shadow/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/shadow/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Java/shadow/main.java b/trunk/Examples/GIFPlot/Java/shadow/main.java
new file mode 100644
index 0000000..fbcf6e7
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/shadow/main.java
@@ -0,0 +1,76 @@
+// Plot a 3D function
+
+import java.lang.Math;
+
+public class main {
+
+  static {
+    try {
+        System.loadLibrary("gifplot");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    
+    // Here are some plotting parameters
+    double xmin = -5.0;
+    double xmax =  5.0;
+    double ymin = -5.0;
+    double ymax =  5.0;
+    double zmin = -5.0;
+    double zmax =  5.0;
+    
+    // Grid resolution
+    int nxpoints =  60;
+    int nypoints =  60;
+    
+    ColorMap cmap = new ColorMap("cmap");
+    FrameBuffer frame = new FrameBuffer(500,500);
+    frame.clear((short)gifplot.BLACK);
+    
+    Plot3D p3 = new Plot3D(frame,xmin,ymin,zmin,xmax,ymax,zmax);
+    p3.lookat(2*(zmax-zmin));
+    p3.autoperspective(40);
+    p3.rotu(60);
+    p3.rotr(30);
+    p3.rotd(10);
+    
+    System.out.println( "Making a nice 3D plot..." );
+    p3.clear((short)gifplot.BLACK);
+    p3.start();
+    double dx = 1.0*(xmax-xmin)/nxpoints;
+    double dy = 1.0*(ymax-ymin)/nypoints;
+    double cscale = 240.0/(zmax-zmin);
+    double x = xmin;
+    for (int i = 0; i < nxpoints; i++) {
+      double y = ymin;
+      for (int j = 0; j < nypoints; j++) {
+        double z1 = func(x,y);
+        double z2 = func(x+dx,y);
+        double z3 = func(x+dx,y+dy);
+        double z4 = func(x,y+dy);
+        double c1 = cscale*(z1-zmin);
+        double c2 = cscale*(z2-zmin);
+        double c3 = cscale*(z3-zmin);
+        double c4 = cscale*(z4-zmin);
+        double c = (c1+c2+c3+c4)/4;
+        if (c < 0) c = 0;
+        if (c > 239) c = 239;
+        p3.solidquad(x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,(short)(c+16));
+        y = y + dy;
+      }
+      x = x + dx;
+    }
+
+    frame.writeGIF(cmap,"image.gif");
+    System.out.println( "Wrote image.gif" );
+  } 
+
+  // Here is the function to plot
+  public static double func(double x, double y) {
+    return 5*java.lang.Math.cos(2*java.lang.Math.sqrt(x*x+y*y))*java.lang.Math.exp(-0.3*java.lang.Math.sqrt(x*x+y*y));
+  }
+}
diff --git a/trunk/Examples/GIFPlot/Java/simple/Makefile b/trunk/Examples/GIFPlot/Java/simple/Makefile
new file mode 100644
index 0000000..d707fd4
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/simple/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -noproxy
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Java/simple/README b/trunk/Examples/GIFPlot/Java/simple/README
new file mode 100644
index 0000000..1fb8453
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  After doing a make, run the java program, ie 'java main'.
+
+
diff --git a/trunk/Examples/GIFPlot/Java/simple/main.java b/trunk/Examples/GIFPlot/Java/simple/main.java
new file mode 100644
index 0000000..b165a4b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/simple/main.java
@@ -0,0 +1,41 @@
+
+public class main {
+
+  static {
+    try {
+        System.loadLibrary("simple");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // Draw some simple shapes
+    System.out.println( "Drawing some basic shapes" );
+    
+    SWIGTYPE_p_ColorMap cmap = simple.new_ColorMap(null);
+    SWIGTYPE_p_FrameBuffer f    = simple.new_FrameBuffer(400,400);
+    
+    // Clear the picture
+    simple.FrameBuffer_clear(f,(short)simple.BLACK);
+    
+    // Make a red box
+    simple.FrameBuffer_box(f,40,40,200,200,(short)simple.RED);
+    
+    // Make a blue circle
+    simple.FrameBuffer_circle(f,200,200,40,(short)simple.BLUE);
+    
+    // Make green line
+    simple.FrameBuffer_line(f,10,390,390,200, (short)simple.GREEN);
+    
+    // Write an image out to disk
+    
+    simple.FrameBuffer_writeGIF(f,cmap,"image.gif");
+    System.out.println( "Wrote image.gif" );
+    
+    simple.delete_FrameBuffer(f);
+    simple.delete_ColorMap(cmap);
+    }
+}
diff --git a/trunk/Examples/GIFPlot/Java/simple/simple.i b/trunk/Examples/GIFPlot/Java/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Java/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Lib/Makefile.in b/trunk/Examples/GIFPlot/Lib/Makefile.in
new file mode 100644
index 0000000..9db828e
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/Makefile.in
@@ -0,0 +1,22 @@
+CC      = @CC@
+CCSHARED= @CCSHARED@ 
+INCLUDES= -I../Include
+CFLAGS  = -O
+SRCS    = frame.c color.c plot2d.c plot3d.c font.c pixmap.c matrix.c gif.c
+OBJS    = $(SRCS:.c=.@OBJEXT@)
+AR      = @AR@
+RANLIB  = @RANLIB@
+TARGET  = ../libgifplot.a
+
+.c.@OBJEXT@: 
+	$(CC) $(CCSHARED) $(INCLUDES) $(CFLAGS) -c -o $*.@OBJEXT@ $<
+
+all:  $(OBJS)
+	@rm -f ../libgifplot.a
+	$(AR) cr $(TARGET) $(OBJS)
+	$(RANLIB) $(TARGET)
+
+clean:
+	rm -f *.@OBJEXT@ *~ $(TARGET)
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Lib/color.c b/trunk/Examples/GIFPlot/Lib/color.c
new file mode 100644
index 0000000..a4eaf28
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/color.c
@@ -0,0 +1,140 @@
+/* ----------------------------------------------------------------------------- 
+ * color.c
+ *
+ *     Colormaps
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define COLORMAP
+#include "gifplot.h"
+#include <string.h>
+
+/* ------------------------------------------------------------------------
+   ColorMap *new_ColorMap(char *filename)
+
+   Read a colormap from a file.
+   ------------------------------------------------------------------------ */
+
+ColorMap *new_ColorMap(char *filename) {
+  ColorMap *c;
+  FILE *cm;
+  void ColorMap_default(ColorMap *);
+  
+  if (!filename) {
+    c = (ColorMap *) malloc(sizeof(ColorMap));
+    c->cmap = (unsigned char *) malloc(768*sizeof(char));
+    c->name = 0;
+    ColorMap_default(c);
+    return c;
+  }
+  if (strlen(filename) == 0) {
+    c = (ColorMap *) malloc(sizeof(ColorMap));
+    c->cmap = (unsigned char *) malloc(768*sizeof(char));
+    ColorMap_default(c);
+    return c;
+  }
+  if ((cm = fopen(filename,"rb")) == NULL) {
+    return (ColorMap *) 0;
+  }
+  c = (ColorMap *) malloc(sizeof(ColorMap));
+  c->cmap = (unsigned char *) malloc(768*sizeof(char));
+  if (fread(c->cmap, 768, 1, cm) != 1) {
+    free((char *)c->cmap);
+    free((char *)c);
+    fclose(cm);
+    return (ColorMap *) 0;
+  }
+  fclose(cm);
+  c->name = (char *) malloc(strlen(filename)+1);
+  strcpy(c->name, filename);
+  ColorMap_default(c);
+  return c;
+}
+
+/* --------------------------------------------------------------------------
+   delete_ColorMap(ColorMap *cm)
+
+   Destroy a ColorMap
+   -------------------------------------------------------------------------- */
+
+void delete_ColorMap(ColorMap *cm) {
+  if (cm) {
+    free((char *)cm->cmap);
+    if (cm->name)
+      free((char *)cm->name);
+    free((char *)cm);
+  }
+}
+
+/* --------------------------------------------------------------------------
+   ColorMap_default(ColorMap *cm)
+
+   This function fills in default values for the first 8 entries of the
+   colormap.  These are *fixed* values---used internally.
+   -------------------------------------------------------------------------- */
+
+void ColorMap_default(ColorMap *cm) {
+  unsigned char *r,*g,*b;
+  if (cm) {
+    r = cm->cmap;
+    g = cm->cmap+256;
+    b = cm->cmap+512;
+
+    r[0] = 0;   g[0] = 0;   b[0] = 0;      /* BLACK */
+    r[1] = 255; g[1] = 255; b[1] = 255;    /* WHITE */
+    r[2] = 255; g[2] = 0;   b[2] = 0;      /* RED   */
+    r[3] = 0;   g[3] = 255; b[3] = 0;      /* GREEN */
+    r[4] = 0;   g[4] = 0;   b[4] = 255;    /* BLUE  */
+    r[5] = 255; g[5] = 255; b[5] = 0;      /* YELLOW */
+    r[6] = 0;   g[6] = 255; b[6] = 255;    /* CYAN   */
+    r[7] = 255; g[7] = 0;   b[7] = 255;    /* MAGENTA */
+  }
+}
+
+void ColorMap_assign(ColorMap *cm, int index, int r, int g, int b) {
+  unsigned char *rb,*gb,*bb;
+
+  rb = cm->cmap;
+  gb = cm->cmap+256;
+  bb = cm->cmap+512;
+
+  rb[index] = r;
+  gb[index] = g;
+  bb[index] = b;
+}
+
+int ColorMap_getitem(ColorMap *cm, int index) {
+  if ((index < 0) && (index >= 768)) return -1;
+  return cm->cmap[index];
+}
+
+void ColorMap_setitem(ColorMap *cm, int index, int value) {
+  if ((index < 0) && (index >= 768)) return;
+  cm->cmap[index]=value;
+}  
+
+/* --------------------------------------------------------------------
+   ColorMap_write(ColorMap *cm, char *filename)
+
+   Write out a colormap to disk.
+   -------------------------------------------------------------------- */
+
+int ColorMap_write(ColorMap *cm, char *filename) {
+
+  FILE *f;
+  if (!cm) return -1;
+  if (!filename) return -1;
+  if (strlen(filename) == 0) return -1;
+
+  f = fopen(filename,"w");
+  
+  fwrite(cm->cmap,768,1,f);
+  fclose(f);
+  return 0;
+}
+
+#undef COLORMAP
diff --git a/trunk/Examples/GIFPlot/Lib/font.c b/trunk/Examples/GIFPlot/Lib/font.c
new file mode 100644
index 0000000..b30ee9b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/font.c
@@ -0,0 +1,705 @@
+/* ----------------------------------------------------------------------------- 
+ * font.c
+ *
+ *     Some basic fonts.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define FONT
+#include "gifplot.h"
+
+static char Char_A[80] = "\
+...x....\
+...x....\
+..x.x...\
+..x.x...\
+.x...x..\
+.xxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+........";
+
+static char Char_B[80] = "\
+xxxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+xxxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+xxxxxx..\
+........";
+
+static char Char_C[80] = "\
+..xxxx..\
+.x....x.\
+x.......\
+x.......\
+x.......\
+x.......\
+x.......\
+.x....x.\
+..xxxx..\
+........";
+
+static char Char_D[80] = "\
+xxxxx...\
+x....x..\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x....x..\
+xxxxx...\
+........";
+static char Char_E[80] = "\
+xxxxxxx.\
+x.......\
+x.......\
+x.......\
+xxxxx...\
+x.......\
+x.......\
+x.......\
+xxxxxxx.\
+........";
+static char Char_F[80] = "\
+xxxxxxx.\
+x.......\
+x.......\
+x.......\
+xxxxx...\
+x.......\
+x.......\
+x.......\
+x.......\
+........";
+static char Char_G[80] = "\
+.xxxxx..\
+x.....x.\
+x.......\
+x.......\
+x...xxx.\
+x.....x.\
+x.....x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_H[80] = "\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+xxxxxxx.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+........";
+static char Char_I[80] = "\
+xxxxxxx.\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+xxxxxxx.\
+........";
+static char Char_J[80] = "\
+......x.\
+......x.\
+......x.\
+......x.\
+......x.\
+......x.\
+x.....x.\
+.x...x..\
+..xxx...\
+........";
+static char Char_K[80] = "\
+x.....x.\
+x....x..\
+x...x...\
+x..x....\
+xxx.....\
+x..x....\
+x...x...\
+x....x..\
+x.....x.\
+........";
+static char Char_L[80] = "\
+x.......\
+x.......\
+x.......\
+x.......\
+x.......\
+x.......\
+x.......\
+x.......\
+xxxxxxx.\
+........";
+static char Char_M[80] = "\
+x.....x.\
+xx...xx.\
+xx...xx.\
+x.x.x.x.\
+x.x.x.x.\
+x..x..x.\
+x..x..x.\
+x.....x.\
+x.....x.\
+........";
+static char Char_N[80] = "\
+x.....x.\
+xx....x.\
+x.x...x.\
+x.x...x.\
+x..x..x.\
+x...x.x.\
+x...x.x.\
+x....xx.\
+x.....x.\
+........";
+static char Char_O[80] = "\
+.xxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_P[80] = "\
+xxxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+xxxxxx..\
+x.......\
+x.......\
+x.......\
+x.......\
+........";
+static char Char_Q[80] = "\
+.xxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x...x.x.\
+x....x..\
+.xxxx.x.\
+........";
+static char Char_R[80] = "\
+xxxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+xxxxxx..\
+x..x....\
+x...x...\
+x....x..\
+x.....x.\
+........";
+static char Char_S[80] = "\
+.xxxxx..\
+x.....x.\
+x.......\
+x.......\
+.xxxxx..\
+......x.\
+......x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_T[80] = "\
+xxxxxxx.\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+........";
+static char Char_U[80] = "\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_V[80] = "\
+x.....x.\
+x.....x.\
+.x...x..\
+.x...x..\
+..x.x...\
+..x.x...\
+...x....\
+...x....\
+...x....\
+........";
+static char Char_W[80] = "\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x.....x.\
+x..x..x.\
+x..x..x.\
+x.x.x.x.\
+.x...x..\
+........";
+static char Char_X[80] = "\
+x.....x.\
+x.....x.\
+.x...x..\
+..x.x...\
+...x....\
+..x.x...\
+.x...x..\
+x.....x.\
+x.....x.\
+........";
+static char Char_Y[80] = "\
+x.....x.\
+x.....x.\
+.x...x..\
+..x.x...\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+........";
+static char Char_Z[80] = "\
+xxxxxxx.\
+......x.\
+.....x..\
+....x...\
+...x....\
+..x.....\
+.x......\
+x.......\
+xxxxxxx.\
+........";
+static char Char_0[80] = "\
+.xxxxx..\
+x....xx.\
+x...x.x.\
+x..x..x.\
+x..x..x.\
+x.x...x.\
+x.x...x.\
+xx....x.\
+.xxxxx..\
+........";
+static char Char_1[80] = "\
+...x....\
+..xx....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+...x....\
+..xxx...\
+........";
+static char Char_2[80] = "\
+..xxxx..\
+.x....x.\
+x.....x.\
+.....x..\
+....x...\
+...x....\
+..x.....\
+.x......\
+xxxxxxx.\
+........";
+static char Char_3[80] = "\
+.xxxxx..\
+x.....x.\
+......x.\
+......x.\
+...xxx..\
+......x.\
+......x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_4[80] = "\
+....xx..\
+...x.x..\
+..x..x..\
+.x...x..\
+xxxxxxx.\
+.....x..\
+.....x..\
+.....x..\
+.....x..\
+........";
+static char Char_5[80] = "\
+xxxxxxx.\
+x.......\
+x.......\
+x.......\
+xxxxxx..\
+......x.\
+......x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_6[80] = "\
+....xxx.\
+..xx....\
+.x......\
+x.......\
+x.xxx...\
+xx...x..\
+x.....x.\
+.x...x..\
+..xxx...\
+........";
+static char Char_7[80] = "\
+xxxxxxx.\
+x.....x.\
+.....x..\
+....x...\
+...x....\
+..x.....\
+.x......\
+x.......\
+x.......\
+........";
+static char Char_8[80] = "\
+.xxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+.xxxxx..\
+x.....x.\
+x.....x.\
+x.....x.\
+.xxxxx..\
+........";
+static char Char_9[80] = "\
+..xxxx..\
+.x....x.\
+x.....x.\
+x....xx.\
+.xxxx.x.\
+......x.\
+......x.\
+....xx..\
+.xxx....\
+........";
+static char Char_MINUS[80] = "\
+........\
+........\
+........\
+........\
+.xxxxxx.\
+........\
+........\
+........\
+........\
+........";
+static char Char_PLUS[80] = "\
+........\
+........\
+...x....\
+...x....\
+.xxxxx..\
+...x....\
+...x....\
+........\
+........\
+........";
+static char Char_EQUAL[80] = "\
+........\
+........\
+........\
+.xxxxx..\
+........\
+.xxxxx..\
+........\
+........\
+........\
+........";
+static char Char_LPAREN[80] = "\
+....x...\
+...x....\
+..x.....\
+.x......\
+.x......\
+.x......\
+..x.....\
+...x....\
+....x...\
+........";
+static char Char_RPAREN[80] = "\
+...x....\
+....x...\
+.....x..\
+......x.\
+......x.\
+......x.\
+.....x..\
+....x...\
+...x....\
+........";
+static char Char_QUOTE[80] = "\
+..x.x...\
+..x.x...\
+........\
+........\
+........\
+........\
+........\
+........\
+........\
+........";
+static char Char_COLON[80] = "\
+........\
+........\
+...xx...\
+...xx...\
+........\
+...xx...\
+...xx...\
+........\
+........\
+........";
+static char Char_PERIOD[80] = "\
+........\
+........\
+........\
+........\
+........\
+........\
+........\
+...xx...\
+...xx...\
+........";
+static char Char_COMMA[80] = "\
+........\
+........\
+........\
+........\
+........\
+........\
+...xx...\
+...xx...\
+....x...\
+...x....";
+
+static char Char_SLASH[80] = "\
+........\
+......x.\
+.....x..\
+....x...\
+...x....\
+..x.....\
+.x......\
+x.......\
+........\
+........";
+
+static char Char_SPACE[80] = "\
+........\
+........\
+........\
+........\
+........\
+........\
+........\
+........\
+........\
+........";
+
+static char  *GP_Font[128];
+static int    InitGP_Font = 0;
+
+static void initGP_Fonts(void) {
+
+  int i;
+  for (i = 0; i < 128; i++)
+    GP_Font[i] = (char *) 0;
+  
+  GP_Font['A'] = GP_Font['a'] = Char_A;
+  GP_Font['B'] = GP_Font['b'] = Char_B;
+  GP_Font['C'] = GP_Font['c'] = Char_C;
+  GP_Font['D'] = GP_Font['d'] = Char_D;
+  GP_Font['E'] = GP_Font['e'] = Char_E;
+  GP_Font['F'] = GP_Font['f'] = Char_F;
+  GP_Font['G'] = GP_Font['g'] = Char_G;
+  GP_Font['H'] = GP_Font['h'] = Char_H;
+  GP_Font['I'] = GP_Font['i'] = Char_I;
+  GP_Font['J'] = GP_Font['j'] = Char_J;
+  GP_Font['K'] = GP_Font['k'] = Char_K;
+  GP_Font['L'] = GP_Font['l'] = Char_L;
+  GP_Font['M'] = GP_Font['m'] = Char_M;
+  GP_Font['N'] = GP_Font['n'] = Char_N;
+  GP_Font['O'] = GP_Font['o'] = Char_O;
+  GP_Font['P'] = GP_Font['p'] = Char_P;
+  GP_Font['Q'] = GP_Font['q'] = Char_Q;
+  GP_Font['R'] = GP_Font['r'] = Char_R;
+  GP_Font['S'] = GP_Font['s'] = Char_S;
+  GP_Font['T'] = GP_Font['t'] = Char_T;
+  GP_Font['U'] = GP_Font['u'] = Char_U;
+  GP_Font['V'] = GP_Font['v'] = Char_V;
+  GP_Font['W'] = GP_Font['w'] = Char_W;
+  GP_Font['X'] = GP_Font['x'] = Char_X;
+  GP_Font['Y'] = GP_Font['y'] = Char_Y;
+  GP_Font['Z'] = GP_Font['z'] = Char_Z;
+  GP_Font['0'] = Char_0;
+  GP_Font['1'] = Char_1;
+  GP_Font['2'] = Char_2;
+  GP_Font['3'] = Char_3;
+  GP_Font['4'] = Char_4;
+  GP_Font['5'] = Char_5;
+  GP_Font['6'] = Char_6;
+  GP_Font['7'] = Char_7;
+  GP_Font['8'] = Char_8;
+  GP_Font['9'] = Char_9;
+  GP_Font['.'] = Char_PERIOD;
+  GP_Font[','] = Char_COMMA;
+  GP_Font['='] = Char_EQUAL;
+  GP_Font['-'] = Char_MINUS;
+  GP_Font['+'] = Char_PLUS;
+  GP_Font['\"'] = Char_QUOTE;
+  GP_Font['('] = Char_LPAREN;
+  GP_Font[')'] = Char_RPAREN;
+  GP_Font[':'] = Char_COLON;
+  GP_Font['/'] = Char_SLASH;
+  GP_Font[' '] = Char_SPACE;
+  InitGP_Font = 1;
+}
+
+/* -----------------------------------------------------------------------
+   void FrameBuffer_drawchar(FrameBuffer *f, int x, int y, Pixel fgcolor, Pixel bgcolor, char chr, int orientation)
+
+   Draws a character at location x, y with given color and orientation parameters.
+   Orientation can either be HORIZONTAL or VERTICAL
+   ----------------------------------------------------------------------- */
+void FrameBuffer_drawchar(FrameBuffer *f, int x, int y, int fgcolor,
+			  int bgcolor, char chr, int orientation) {
+
+  Pixel c, bc,*p,*p1;
+  char *ch;
+  int i,j;
+  int xpixels,ypixels;
+
+  if (!InitGP_Font) initGP_Fonts();
+  
+  c =  (Pixel) fgcolor;
+  bc = (Pixel) bgcolor;
+  xpixels = f->width;
+  ypixels = f->height;
+
+  if (orientation == HORIZONTAL) {
+    if ((x < f->xmin) || (x > f->xmax-8) ||
+	(y < f->ymin) || (y > f->ymax-10)) return;
+  
+    ch = GP_Font[(int) chr];
+    if (!ch) return;
+    p = &f->pixels[y+9][x];
+    for (i = 0; i < 10; i++) {
+      p1 = p;
+      for (j = 0; j< 8; j++) {
+	if (*(ch++) == 'x') *p= c;
+	else if (bgcolor >= 0)
+	  *p = bc;
+	p++;
+      }
+      p = (p1 - xpixels);
+    }
+  } else {
+    if ((x < f->xmin+10) || (x >= f->xmax) ||
+	(y < f->ymin) || (y > f->ymax-8)) return;
+  
+    ch = GP_Font[(int) chr];
+    if (!ch) return;
+    p = &f->pixels[y][x-9];
+    for (i = 0; i < 10; i++) {
+      p1 = p;
+      for (j = 0; j< 8; j++) {
+	if (*(ch++) == 'x') *p= c;
+	else if (bgcolor >= 0)
+	  *p = bc;
+	p+=xpixels;
+      }
+      p = p1 + 1;
+    }
+  }    
+}
+
+/* ----------------------------------------------------------------------
+   void FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor,
+                               int bgcolor, char *text, int orientation)
+
+   Draws an ASCII string on the framebuffer.   Can be oriented either horizontally
+   or vertically.  
+   ---------------------------------------------------------------------- */
+
+void FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, int bgcolor, char *text, int orientation) {
+
+  char *c;
+  int  x1, y1;
+  int xpixels, ypixels;
+  
+  x1 = x;
+  y1 = y;
+  xpixels = f->width;
+  ypixels = f->height;
+  c = text;
+  while (*c) {
+    if (*c == '\n') {
+      if (orientation == HORIZONTAL) {
+	x1 = x; y1= y1- 10*xpixels;
+      } else {
+	y1 = y; x1= x1 + 10*ypixels;
+      }
+    } else {
+      FrameBuffer_drawchar(f, x1,y1,fgcolor, bgcolor,*c, orientation);
+      if (orientation == HORIZONTAL) {
+	x1+=8;
+	if (x1 >= (xpixels-8)) {
+	  x1 = x; y1= y1- 10;}
+	if (y1 < 0) return;
+      } else {
+	y1 += 8;
+	if (y1 >= (ypixels-8)) {
+	  y1 = y; x1 = x1 + 10;}
+	if (x1 > (xpixels-10)) return;
+      }
+    }
+    c++;
+  }
+}
+
+
+  
+  
+  
+  
+  
+
diff --git a/trunk/Examples/GIFPlot/Lib/frame.c b/trunk/Examples/GIFPlot/Lib/frame.c
new file mode 100644
index 0000000..e006f0d
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/frame.c
@@ -0,0 +1,924 @@
+/* ----------------------------------------------------------------------------- 
+ * frame.c
+ *
+ *     Frame buffer management
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define FRAME
+#include "gifplot.h"
+#include <float.h>
+
+/* ------------------------------------------------------------------------
+   FrameBuffer *new_FrameBuffer(int width, int height)
+
+   Creates a new framebuffer for storing data.
+   ------------------------------------------------------------------------ */
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height) {
+
+  FrameBuffer *f;
+  int  FrameBuffer_resize(FrameBuffer *f, int width, int height);
+
+  /* Create a new frame buffer */
+  
+  f = (FrameBuffer *) malloc(sizeof(FrameBuffer));
+  f->pixels = (Pixel **) 0;
+  f->zbuffer = (Zvalue **) 0;
+  /* Set its size */
+  
+  if (FrameBuffer_resize(f, width, height) == -1) {
+    free((char *) f);
+    return (FrameBuffer *) 0;
+  }
+
+  f->xmin = 0;
+  f->ymin = 0;
+  f->xmax = width;
+  f->ymax = height;
+  return f;
+}
+
+/* ------------------------------------------------------------------------
+   void delete_FrameBuffer(FrameBuffer *f)
+
+   Destroys the given framebuffer
+   ------------------------------------------------------------------------ */
+
+void delete_FrameBuffer(FrameBuffer *f) {
+
+  if (f) {
+    if (f->pixels) {
+      free((char *) f->pixels[0]);
+      free((char *) f->pixels);
+    }
+    if (f->zbuffer) {
+      free((char *) f->zbuffer[0]);
+      free((char *) f->zbuffer);
+    }
+    free((char *)f);
+  }
+}
+
+/* ------------------------------------------------------------------------
+   int *FrameBuffer_resize(FrameBuffer *f, int width, int height)
+
+   Resize the given framebuffer. Returns 0 on success, -1 on failure.
+   ------------------------------------------------------------------------ */
+
+int FrameBuffer_resize(FrameBuffer *f, int width, int height) {
+  int i;
+  if ((f) && (width > 0) && (height > 0)) {
+    if (f->pixels) {
+      free((char *)f->pixels[0]);
+      free((char *)f->pixels);
+    }
+    f->pixels = (Pixel **) malloc (height*sizeof(Pixel *));
+    if (!f->pixels) return -1;
+    f->pixels[0] = (Pixel *) malloc(height*width*sizeof(Pixel));
+    if (!f->pixels[0]) {
+      free((char *)f->pixels);
+      return -1;
+    }
+    for (i = 0; i < height; i++) 
+      f->pixels[i] = f->pixels[0] + i*width;
+    f->width = width;
+    f->height = height;
+    if (f->zbuffer) {
+      FrameBuffer_zresize(f,width,height);
+    }
+    return 0;
+  } else {
+    return -1;
+  }
+}
+
+/* ------------------------------------------------------------------------
+   void FrameBuffer_clear(FrameBuffer *f, Pixel color)
+
+   Clears the current FrameBuffer
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_clear(FrameBuffer *f, Pixel color) {
+  Pixel *p;
+  unsigned int i;
+  p = &f->pixels[0][0];
+
+  for (i = 0; i < f->width*f->height; i++, p++)
+    *p = color;
+}
+
+/* ------------------------------------------------------------------------
+   void FrameBuffer_plot(FrameBuffer *f, int x1, int y1, Pixel color)
+
+   Plots a point and does a bounds check.
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_plot(FrameBuffer *f, int x1, int y1, Pixel color) {
+
+  if ((x1 < f->xmin) || (x1 >= f->xmax) || (y1 < f->ymin) || (y1 >= f->ymax))
+    return;
+  f->pixels[y1][x1] = color;
+
+}
+
+/* ------------------------------------------------------------------------
+   FrameBuffer_horizontal(Framebuffer *f, int xmin, int xmax, int y, Pixel color)
+
+   Draw a horizontal line (clipped)
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_horizontal(FrameBuffer *f, int xmin, int xmax, int y, Pixel color) {
+  
+  Pixel *p;
+  int    i;
+  
+  if ((y < f->ymin) || (y >= f->ymax)) return;
+  if (xmin < f->xmin) xmin = f->xmin;
+  if (xmax >= f->xmax) xmax = f->xmax - 1;
+
+  p = &f->pixels[y][xmin];
+  for (i = xmin; i <= xmax; i++, p++)
+    *p = color;
+
+}
+
+/* ------------------------------------------------------------------------
+   FrameBuffer_horizontalinterp(Framebuffer *f, int xmin, int xmax, int y,
+                                Pixel c1, Pixel c2)
+
+   Draw a horizontal line (clipped) with color interpolation.
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_horizontalinterp(FrameBuffer *f, int xmin, int xmax, int y,
+				  Pixel c1, Pixel c2) {
+  
+  Pixel *p;
+  int    i;
+  double mc;
+  int    x1;
+  if ((y < f->ymin) || (y >= f->ymax)) return;
+
+  x1 = xmin;
+  if (xmin < f->xmin) xmin = f->xmin;
+  if (xmax >= f->xmax) xmax = f->xmax - 1;
+  if (xmax < f->xmin) return;
+  if (xmin >= f->xmax) return;
+
+  if (xmin != xmax)
+    mc = (double)(c2 - c1)/(double) (xmax - xmin);
+  else
+    mc = 0.0;
+
+  p = &f->pixels[y][xmin];
+  for (i = xmin; i <= xmax; i++, p++) 
+    *p = (Pixel) (mc*(i-x1) + c1);
+  
+}
+
+
+/* ------------------------------------------------------------------------
+   FrameBuffer_vertical(Framebuffer *f, int xmin, int xmax, int y, Pixel color)
+
+   Draw a Vertical line (clipped)
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_vertical(FrameBuffer *f, int ymin, int ymax, int x, Pixel color) {
+  
+  Pixel *p;
+  int    i;
+  
+  if ((x < f->xmin) || (x >= f->xmax)) return;
+  if (ymax < f->ymin) return;
+  if (ymin > f->ymax) return;
+  if (ymin < f->ymin) ymin = f->ymin;
+  if (ymax >= f->ymax) ymax = f->ymax - 1;
+
+  p = &f->pixels[ymin][x];
+  for (i = 0; i <= (ymax - ymin); i++, p+=f->width)
+    *p = color;
+
+}
+  
+/* ------------------------------------------------------------------------
+   void FrameBuffer_box(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color)
+
+   Makes an outline box.
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_box(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color) {
+
+  int  xt, yt;
+
+  /* Make sure points are in correct order */
+
+  if (x2 < x1) {
+    xt = x2;
+    x2 = x1;
+    x1 = xt;
+  }
+  if (y2 < y1) {
+    yt = y2;
+    y2 = y1;
+    y1 = yt;
+  }
+
+  /* Draw lower edge */
+
+  FrameBuffer_horizontal(f,x1,x2,y1,color);
+
+  /* Draw upper edge */
+
+  FrameBuffer_horizontal(f,x1,x2,y2,color);
+
+  /* Draw left side */
+
+  FrameBuffer_vertical(f,y1,y2,x1,color);
+
+  /* Draw right side */
+
+  FrameBuffer_vertical(f,y1,y2,x2,color);
+  
+}
+
+/* ------------------------------------------------------------------------
+   void FrameBuffer_solidbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color)
+
+   Makes an solid box.
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_solidbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel color) {
+
+  int  xt, yt;
+
+  /* Make sure points are in correct order */
+
+  if (x2 < x1) {
+    xt = x2;
+    x2 = x1;
+    x1 = xt;
+  }
+  if (y2 < y1) {
+    yt = y2;
+    y2 = y1;
+    y1 = yt;
+  }
+
+  /* Now perform some clipping */
+
+  if (y1 < f->ymin) y1 = f->ymin;
+  if (y2 >= f->ymax) y2 = f->ymax - 1;
+
+  /* Fill it in using horizontal lines */
+  
+  for (yt = y1; yt <= y2; yt++)
+    FrameBuffer_horizontal(f,x1,x2,yt,color);
+
+}
+
+/* ------------------------------------------------------------------------
+   void FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2
+                              Pixel c1, Pixel c2, Pixel c3, Pixel c4)
+
+   Makes a box with interpolated color.   Colors are assigned as follows :
+   (x1,y1) = c1
+   (x1,y2) = c2
+   (x2,y1) = c3
+   (x2,y2) = c4
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2,
+			   Pixel c1, Pixel c2, Pixel c3, Pixel c4) {
+
+  int  xt, yt;
+  Pixel ct;
+  double  mc1,mc2;
+  int  ystart;
+  /* Make sure points are in correct order */
+
+  if (x2 < x1) {
+    xt = x2;
+    x2 = x1;
+    x1 = xt;
+    ct = c1;
+    c1 = c3;
+    c3 = ct;
+    ct = c2;
+    c2 = c4;
+    c4 = ct;
+  }
+  if (y2 < y1) {
+    yt = y2;
+    y2 = y1;
+    y1 = yt;
+    ct = c1;
+    c1 = c2;
+    c2 = ct;
+    ct = c3;
+    c3 = c4;
+    c4 = ct;
+  }
+
+  /* Now perform some clipping */
+
+  ystart = y1;
+  mc1 = (double) (c2 - c1)/(double) (y2 - y1);
+  mc2 = (double) (c4 - c3)/(double) (y2 - y1);
+  if (y1 < f->ymin) y1 = f->ymin;
+  if (y2 >= f->ymax) y2 = f->ymax - 1;
+
+  /* Fill it in using horizontal lines */
+  
+  for (yt = y1; yt <= y2; yt++)
+    FrameBuffer_horizontalinterp(f,x1,x2,yt,(Pixel) ((mc1*(yt - ystart)) + c1),
+				  (Pixel) ((mc2*(yt-ystart))+c3));
+
+}
+
+/* ---------------------------------------------------------------------------
+   FrameBuffer_line(FrameBuffer *f, int x1, int y1, int x2, int y2, color)
+
+   Draws a line on the framebuffer using the Bresenham line algorithm.  The
+   line is clipped to fit within the current view window.
+   ---------------------------------------------------------------------------- */
+
+void FrameBuffer_line(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel c) {
+
+  int  dx,dy,dxneg,dyneg, inc1,inc2,di;
+  int  x, y, xpixels, ypixels, xt, yt;
+  Pixel *p;
+  double m;
+  int  end1 = 0, end2 = 0;
+  
+  /* Need to figure out where in the heck this line is */
+
+  dx = x2 - x1;
+  dy = y2 - y1;
+
+  if (dx == 0) {
+    /* Draw a Vertical Line */
+    if (y1 < y2)
+      FrameBuffer_vertical(f,y1,y2,x1,c);
+    else
+      FrameBuffer_vertical(f,y2,y1,x1,c);
+    return;
+  }
+  if (dy == 0) {
+    /* Draw a Horizontal Line */
+    if (x1 < x2)
+      FrameBuffer_horizontal(f,x1,x2,y1,c);
+    else
+      FrameBuffer_horizontal(f,x2,x1,y1,c);
+    return;
+  }
+
+  /* Figure out where in the heck these lines are using the
+     Cohen-Sutherland Line Clipping Scheme. */
+
+  end1 = ((x1 - f->xmin) < 0) |
+    (((f->xmax- 1 - x1) < 0) << 1) |
+    (((y1 - f->ymin) < 0) << 2) |
+    (((f->ymax-1 - y1) < 0) << 3);
+
+  end2 = ((x2 - f->xmin) < 0) |
+    (((f->xmax-1 - x2) < 0) << 1) |
+    (((y2 - f->ymin) < 0) << 2) |
+    (((f->ymax-1 - y2) < 0) << 3);
+
+  if (end1 & end2) return;      /* Nope : Not visible */
+
+  /* Make sure points have a favorable orientation */
+  
+  if (x1 > x2) {
+    xt = x1;
+    x1 = x2;
+    x2 = xt;
+    yt = y1;
+    y1 = y2;
+    y2 = yt;
+  }
+  
+  /* Clip against the boundaries */
+  m = (y2 - y1)/(double) (x2-x1);
+  if (x1 < f->xmin) {
+    y1 = (int) ((f->xmin - x1)*m + y1);
+    x1 = (int) f->xmin;
+  }
+  if (x2 >= f->xmax) {
+    y2 = (int) ((f->xmax -1 -x1)*m + y1);
+    x2 = (int) (f->xmax - 1);
+  }
+
+  if (y1 > y2) {
+    xt = x1;
+    x1 = x2;
+    x2 = xt;
+    yt = y1;
+    y1 = y2;
+    y2 = yt;
+  }
+
+  m = 1/m;
+  if (y1 < f->ymin) {
+    x1 = (int) ((f->ymin - y1)*m + x1);
+    y1 = (int) f->ymin;
+  }
+  if (y2 >= f->ymax) {
+    x2 = (int) ((f->ymax-1-y1)*m + x1);
+    y2 = (int) (f->ymax-1);
+  }
+
+  if ((x1 < f->xmin) || (x1 >= f->xmax) || (y1 < f->ymin) || (y1 >= f->ymax) ||
+      (x2 < f->xmin) || (x2 >= f->xmax) || (y2 < f->ymin) || (y2 >= f->ymax)) return;
+
+  dx = x2 - x1;
+  dy = y2 - y1;
+  xpixels = f->width;
+  ypixels = f->height;
+  
+  dxneg = (dx < 0) ? 1 : 0;
+  dyneg = (dy < 0) ? 1 : 0;
+  
+  dx = abs(dx);
+  dy = abs(dy);
+  if (dx >= dy) {
+    /* Slope between -1 and 1. */
+    if (dxneg) {
+      x = x1;
+      y = y1;
+      x1 = x2;
+      y1 = y2;
+      x2 = x;
+      y2 = y;
+      dyneg = !dyneg;
+    }
+    inc1 = 2*dy;
+    inc2 = 2*(dy-dx);
+    di = 2*dy-dx;
+
+    /* Draw a line using x as independent variable */
+    
+    p = &f->pixels[y1][x1];
+    x = x1;
+    while (x <= x2) {
+      *(p++) = c;
+      if (di < 0) {
+	di = di + inc1;
+      } else {
+	if (dyneg) {
+	  p = p - xpixels;
+	  di = di + inc2;
+	} else {
+	  p = p + xpixels;
+	  di = di + inc2;
+	}
+      }
+      x++;
+    }
+  } else {
+    /* Slope < -1 or > 1 */
+    if (dyneg) {
+      x = x1;
+      y = y1;
+      x1 = x2;
+      y1 = y2;
+      x2 = x;
+      y2 = y;
+      dxneg = !dxneg;
+    }
+    inc1 = 2*dx;
+    inc2 = 2*(dx-dy);
+    di = 2*dx-dy;
+
+    /* Draw a line using y as independent variable */
+    
+    p = &f->pixels[y1][x1];
+    y = y1;
+    while (y <= y2) {
+      *p = c;
+      p = p + xpixels;
+      if (di < 0) {
+	di = di + inc1;
+      } else {
+	if (dxneg) {
+	  p = p - 1;
+	  di = di + inc2;
+	} else {
+	  p = p + 1;
+	  di = di + inc2;
+	}
+      }
+      y++;
+    }
+  }    
+}
+
+
+/* -------------------------------------------------------------------------
+   FrameBuffer_circle(FrameBuffer f, int xc, int yc, int radius, Pixel c)
+
+   Create an outline circle
+   ------------------------------------------------------------------------- */
+
+#define plot_circle(x,y,c) \
+   if ((x >= xmin) && (x < xmax) && \
+       (y >= ymin) && (y < ymax)) \
+        pixels[y][x] = c;
+	
+void FrameBuffer_circle(FrameBuffer *f, int xc, int yc, int radius, Pixel c) {
+
+  int xpixels, ypixels, x, y, p;
+  int xmin, ymin, xmax, ymax;
+  Pixel **pixels;
+
+  if (radius <= 0) return;
+  xpixels = f->width;
+  ypixels = f->height;
+  pixels = f->pixels;
+  xmin = f->xmin;
+  ymin = f->ymin;
+  xmax = f->xmax;
+  ymax = f->ymax;
+  x = 0;
+  y = radius;
+  p = 3-2*radius;
+  while (x <= y) {
+    plot_circle(xc+x,yc+y,c);
+    plot_circle(xc-x,yc+y,c);
+    plot_circle(xc+x,yc-y,c);
+    plot_circle(xc-x,yc-y,c);
+    plot_circle(xc+y,yc+x,c);
+    plot_circle(xc-y,yc+x,c);
+    plot_circle(xc+y,yc-x,c);
+    plot_circle(xc-y,yc-x,c);
+    if (p < 0) p = p + 4*x + 6;
+    else {
+      p = p + 4*(x-y) + 10;
+      y = y -1;
+    }
+    x++;
+  }
+}
+
+
+/* -------------------------------------------------------------------------
+   FrameBuffer_solidcircle(FrameBuffer f, int xc, int yc, int radius, Pixel c)
+
+   Create an filled circle
+   ------------------------------------------------------------------------- */
+
+       
+#define fill_circle(x,y,c) \
+       x1 = xc - x; \
+       x2 = xc + x; \
+       FrameBuffer_horizontal(f,x1,x2,y,c);
+	
+void FrameBuffer_solidcircle(FrameBuffer *f, int xc, int yc, int radius, Pixel c) {
+
+  int xpixels, ypixels, x, y, p;
+  int x1,x2;
+  int xmin, ymin, xmax, ymax;
+  Pixel **pixels;
+
+  if (radius <= 0) return;
+  xpixels = f->width;
+  ypixels = f->height;
+  pixels = f->pixels;
+  xmin = f->xmin;
+  ymin = f->ymin;
+  xmax = f->xmax;
+  ymax = f->ymax;
+  x = 0;
+  y = radius;
+  p = 3-2*radius;
+  while (x <= y) {
+    fill_circle(x,yc+y,c);
+    fill_circle(x,yc-y,c);
+    fill_circle(y,yc+x,c);
+    fill_circle(y,yc-x,c);
+    if (p < 0) p = p + 4*x + 6;
+    else {
+      p = p + 4*(x-y) + 10;
+      y = y -1;
+    }
+    x++;
+  }
+}
+
+/* ------------------------------------------------------------------------
+   void FrameBuffer_setclip(f,xmin,ymin,xmax,ymax)
+
+   Set clipping region for plotting
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_setclip(FrameBuffer *f, int xmin, int ymin, int xmax, int ymax) {
+
+  if (xmin >= xmax) return;
+  if (ymin >= ymax) return;
+
+  if (xmin < 0) xmin = 0;
+  if (ymin < 0) ymin = 0;
+  if (xmax > (int) f->width) xmax = f->width;
+  if (ymax > (int) f->height) ymax = f->height;
+
+  f->xmin = xmin;
+  f->ymin = ymin;
+  f->xmax = xmax;
+  f->ymax = ymax;
+}
+
+/* ------------------------------------------------------------------------
+   void FrameBuffer_noclip(f)
+
+   Disable clipping region
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_noclip(FrameBuffer *f) {
+  f->xmin = 0;
+  f->ymin = 0;
+  f->xmax = f->width;
+  f->ymax = f->height;
+}
+
+
+/* ------------------------------------------------------------------------
+   FrameBuffer_zresize(FrameBuffer *f, int width, int height)
+
+   This function resizes the framebuffer's zbuffer.  If none exist, it
+   creates a new one.
+   ------------------------------------------------------------------------ */
+
+void FrameBuffer_zresize(FrameBuffer *f, int width, int height) {
+  int i;
+
+  if (f->zbuffer) {
+    free((char *)f->zbuffer[0]);
+    free((char *)f->zbuffer);
+  }
+  f->zbuffer = (Zvalue **) malloc(height*sizeof(Zvalue *));
+  f->zbuffer[0] = (Zvalue *) malloc(height*width*sizeof(Zvalue));
+  for (i = 0; i < height; i++)
+    f->zbuffer[i] = f->zbuffer[0]+i*width;
+}
+
+/* ------------------------------------------------------------------------
+   FrameBuffer_zclear(FrameBuffer *f)
+
+   Clears the z-buffer for a particular frame.   Sets all of the z-values to
+   ZMIN.
+   ------------------------------------------------------------------------- */
+
+void FrameBuffer_zclear(FrameBuffer *f) {
+  unsigned int i,j;
+  if (f) {
+    if (f->zbuffer) {
+      for (i = 0; i < f->width; i++)
+	for (j = 0; j < f->height; j++)
+	  f->zbuffer[j][i] = ZMIN;
+    }
+  }
+}
+   
+
+
+/* -------------------------------------------------------------------------
+   FrameBuffer_solidtriangle(FrameBuffer *f, int tx1, int ty2, 
+                                 int tx2, int ty2, 
+				 int tx3, int ty3, Pixel color) 
+
+   This function draws a 2D filled triangle.   
+
+   General idea :
+         1.   Transform the three points into screen coordinates
+	 2.   Order three points vertically on screen.
+	 3.   Check for degenerate cases (where 3 points are colinear).
+	 4.   Fill in the resulting triangle using horizontal lines.
+   -------------------------------------------------------------------------- */
+
+void FrameBuffer_solidtriangle(FrameBuffer *f, int tx1, int ty1, 
+			       int tx2, int ty2,
+			       int tx3, int ty3, Pixel color) {
+  int        tempx, tempy;
+  double     m1,m2,m3;
+  int        y;
+  int        ix1, ix2;
+
+  /* Figure out which point has the greatest "y" value */
+
+  if (ty2 > ty1) {   /* Swap points 1 and 2 if 2 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tx1 = tx2;
+    ty1 = ty2;
+    tx2 = tempx;
+    ty2 = tempy;
+  }
+  if (ty3 > ty1) {  /* Swap points 1 and 3 if 3 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tx1 = tx3;
+    ty1 = ty3;
+    tx3 = tempx;
+    ty3 = tempy;
+  }
+  if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ 
+    tempx = tx2;
+    tempy = ty2;
+    tx2 = tx3;
+    ty2 = ty3;
+    tx3 = tempx;
+    ty3 = tempy;
+  }
+
+  /* Points are now order so that t_1 is the highest point, t_2 is the
+     middle point, and t_3 is the lowest point */
+
+  /* Check for degenerate cases here */
+
+  if ((ty1 == ty2) && (ty2 == ty3)) {
+
+    /* Points are aligned horizontally.   Handle as a special case */
+    /* Just draw three lines using the outline color */
+
+    FrameBuffer_line(f,tx1,ty1,tx2,ty2,color);
+    FrameBuffer_line(f,tx1,ty1,tx3,ty3,color);
+    FrameBuffer_line(f,tx2,ty2,tx3,ty3,color);
+
+  } else {
+
+    if (ty2 < ty1) {
+      /* First process line segments between (x1,y1)-(x2,y2)
+	 And between (x1,y1),(x3,y3) */
+
+      m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1);
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+
+      y = ty1;
+      while (y >= ty2) {
+	/* Calculate x values from slope */
+	ix1 = (int) (m1*(y-ty1)+0.5) + tx1;
+	ix2 = (int) (m2*(y-ty1)+0.5) + tx1;
+	if (ix1 > ix2) 
+	  FrameBuffer_horizontal(f,ix2,ix1,y,color);
+	else
+	  FrameBuffer_horizontal(f,ix1,ix2,y,color);
+	y--;
+      }
+    }
+    if (ty3 < ty2) {
+      /* Draw lower half of the triangle */
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2);
+      y = ty2;
+      while (y >= ty3) {
+	ix1 = (int) (m3*(y-ty2)+0.5)+tx2;
+	ix2 = (int) (m2*(y-ty1)+0.5)+tx1;
+	if (ix1 > ix2)
+	  FrameBuffer_horizontal(f,ix2,ix1,y,color);
+	else
+	  FrameBuffer_horizontal(f,ix1,ix2,y,color);
+	y--;
+      }
+    }
+  }
+}
+
+/* -------------------------------------------------------------------------
+   FrameBuffer_interptriangle(FrameBuffer *f,
+   int tx1, int ty2, Pixel c1,
+   int tx2, int ty2, Pixel c2,
+   int tx3, int ty3, Pixel c3)
+
+   This function draws a filled triangle with color
+   interpolation.  
+
+   General idea :
+         1.   Transform the three points into screen coordinates
+	 2.   Order three points vertically on screen.
+	 3.   Check for degenerate cases (where 3 points are colinear).
+	 4.   Fill in the resulting triangle using horizontal lines.
+	 5.   Colors are interpolated between end points
+   -------------------------------------------------------------------------- */
+
+void FrameBuffer_interptriangle(FrameBuffer *f,
+				int tx1, int ty1, Pixel c1,
+				int tx2, int ty2, Pixel c2,
+				int tx3, int ty3, Pixel c3) {
+  int        tempx, tempy;
+  double     m1,m2,m3;
+  double     mc1,mc2,mc3;
+  Pixel      ic1,ic2,tempc;
+  int        y;
+  int        ix1, ix2;
+
+  /* Figure out which point has the greatest "y" value */
+
+  if (ty2 > ty1) {   /* Swap points 1 and 2 if 2 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tempc = c1;
+    tx1 = tx2;
+    ty1 = ty2;
+    c1 = c2;
+    tx2 = tempx;
+    ty2 = tempy;
+    c2 = tempc;
+  }
+  if (ty3 > ty1) {  /* Swap points 1 and 3 if 3 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tempc = c1;
+    tx1 = tx3;
+    ty1 = ty3;
+    c1 = c3;
+    tx3 = tempx;
+    ty3 = tempy;
+    c3 = tempc;
+  }
+  if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ 
+    tempx = tx2;
+    tempy = ty2;
+    tempc = c2;
+    tx2 = tx3;
+    ty2 = ty3;
+    c2 = c3;
+    tx3 = tempx;
+    ty3 = tempy;
+    c3 = tempc;
+  }
+
+  /* Points are now order so that t_1 is the highest point, t_2 is the
+     middle point, and t_3 is the lowest point */
+
+  /* Check for degenerate cases here */
+
+  if ((ty1 == ty2) && (ty2 == ty3)) {
+
+    /* Points are aligned horizontally.   Handle as a special case */
+    /* Just draw three lines using the outline color */
+
+    if (tx2 > tx1)
+      FrameBuffer_horizontalinterp(f,tx1,tx2,ty1,c1,c2);
+    else
+      FrameBuffer_horizontalinterp(f,tx2,tx1,ty1,c2,c1);
+    if (tx3 > tx1)
+      FrameBuffer_horizontalinterp(f,tx1,tx3,ty1,c1,c3);
+    else
+      FrameBuffer_horizontalinterp(f,tx3,tx1,ty1,c3,c1);
+    if (tx3 > tx2)
+      FrameBuffer_horizontalinterp(f,tx2,tx3,ty2,c2,c3);
+    else
+      FrameBuffer_horizontalinterp(f,tx3,tx2,ty2,c3,c2);
+    
+  } else {
+
+    /* First process line segments between (x1,y1)-(x2,y2)
+       And between (x1,y1),(x3,y3) */
+
+    if (ty2 < ty1) {
+      m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1);
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      mc1 = (c2 - c1)/(double) (ty2 - ty1);
+      mc2 = (c3 - c1)/(double) (ty3 - ty1);
+
+      y = ty1;
+      while (y >= ty2) {
+	/* Calculate x values from slope */
+	ix1 = (int) (m1*(y-ty1)+0.5) + tx1;
+	ix2 = (int) (m2*(y-ty1)+0.5) + tx1;
+	ic1 = (int) (mc1*(y-ty1) + c1);
+	ic2 = (int) (mc2*(y-ty1) + c1);
+	if (ix1 > ix2) 
+	  FrameBuffer_horizontalinterp(f,ix2,ix1,y,ic2,ic1);
+	else
+	  FrameBuffer_horizontalinterp(f,ix1,ix2,y,ic1,ic2);
+	y--;
+      }
+    }
+    if (ty3 < ty2) {
+      /* Draw lower half of the triangle */
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      mc2 = (c3 - c1)/(double) (ty3 - ty1);
+      m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2);
+      mc3 = (c3 - c2)/(double) (ty3 - ty2);
+      y = ty2;
+      while (y >= ty3) {
+	ix1 = (int) (m3*(y-ty2)+0.5)+tx2;
+	ix2 = (int) (m2*(y-ty1)+0.5)+tx1;
+	ic1 = (int) (mc3*(y-ty2)+c2);
+	ic2 = (int) (mc2*(y-ty1)+c1);
+	if (ix1 > ix2)
+	  FrameBuffer_horizontalinterp(f,ix2,ix1,y,ic2,ic1);
+	else
+	  FrameBuffer_horizontalinterp(f,ix1,ix2,y,ic1,ic2);
+	y--;
+      }
+    }
+  }
+}
+
+
diff --git a/trunk/Examples/GIFPlot/Lib/gif.c b/trunk/Examples/GIFPlot/Lib/gif.c
new file mode 100644
index 0000000..a0cfca1
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/gif.c
@@ -0,0 +1,668 @@
+
+/**********************************************************************
+ * GIFPlot 0.0
+ * 
+ * Dave Beazley
+ * 
+ * Department of Computer Science        Theoretical Division (T-11)        
+ * University of Utah                    Los Alamos National Laboratory     
+ * Salt Lake City, Utah 84112            Los Alamos, New Mexico  87545      
+ * beazley@cs.utah.edu                   beazley@lanl.gov                   
+ *
+ * Copyright (c) 1996
+ * The Regents of the University of California and the University of Utah
+ * All Rights Reserved
+ *
+ * Permission is hereby granted, without written agreement and without
+ * license or royalty fees, to use, copy, modify, and distribute this
+ * software and its documentation for any purpose, provided that 
+ * (1) The above copyright notice and the following two paragraphs
+ * appear in all copies of the source code and (2) redistributions
+ * including binaries reproduces these notices in the supporting
+ * documentation.   Substantial modifications to this software may be
+ * copyrighted by their authors and need not follow the licensing terms
+ * described here, provided that the new terms are clearly indicated in
+ * all files where they apply.
+ * 
+ * IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE 
+ * UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
+ * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
+ * EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH
+ * SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, 
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND 
+ * THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE,
+ * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ **************************************************************************/
+
+/*******************************************************************
+ * Creates a GIF format file.  
+ *
+ * Dave Beazley (T-11)
+ * August 11, 1995
+ *
+ * Rather than writing directly to files, this module fills out
+ * output buffer.
+ * 
+ * Note : To save memory, this routine uses approximately 50K of the
+ * output buffer as temporary storage (for hash tables and compression codes).
+ * The remainder of the output buffer is used to store the final image.
+ * This feature allows GIF images to be created with no additional
+ * memory overhead.
+ *
+ * -- Revision History 
+ * $Log$
+ * Revision 1.2  2003/09/01 16:23:31  beazley
+ * Restored the 'mojo'.
+ *
+ * Revision 1.2  1996/09/25 22:39:30  dmb
+ * Fixed prototypes and use of void pointers for compatibility with the Cray T3D
+ *
+ * Revision 1.1  1996/09/10 17:44:00  dmb
+ * Initial revision
+ *
+ * Revision 1.2  1995/08/31 14:46:07  beazley
+ * Minor changes to support comments and a few bug fixes.
+ *
+ *
+ ******************************************************************/
+
+
+/*
+ * xvgifwr.c  -  handles writing of GIF files.  based on flgife.c and
+ *               flgifc.c from the FBM Library, by Michael Maudlin
+ *
+ * Contains: 
+ *   WriteGIF(fp, pic, ptype, w, h, rmap, gmap, bmap, numcols, colorstyle,
+ *            comment)
+ *
+ * Note: slightly brain-damaged, in that it'll only write non-interlaced 
+ *       GIF files (in the interests of speed, or something)
+ *
+ */
+
+
+
+/*****************************************************************
+ * Portions of this code Copyright (C) 1989 by Michael Mauldin.
+ * Permission is granted to use this file in whole or in
+ * part for any purpose, educational, recreational or commercial,
+ * provided that this copyright notice is retained unchanged.
+ * This software is available to all free of charge by anonymous
+ * FTP and in the UUNET archives.
+ *
+ *
+ * Authors:  Michael Mauldin (mlm@cs.cmu.edu)
+ *           David Rowley (mgardi@watdcsu.waterloo.edu)
+ *
+ * Based on: compress.c - File compression ala IEEE Computer, June 1984.
+ *
+ *	Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
+ *	Jim McKie               (decvax!mcvax!jim)
+ *	Steve Davies            (decvax!vax135!petsd!peora!srd)
+ *	Ken Turkowski           (decvax!decwrl!turtlevax!ken)
+ *	James A. Woods          (decvax!ihnp4!ames!jaw)
+ *	Joe Orost               (decvax!vax135!petsd!joe)
+ *****************************************************************/
+
+#include "gifplot.h"
+#include <string.h> 
+typedef long int        count_int;
+typedef unsigned char   byte;
+
+static int  gif_error;
+static unsigned char *op;
+static int  Width, Height;
+static int  curx, cury;
+static int  Interlace;
+
+static void putgifword(int);
+static void compress(int, byte **, int);
+static void output_GIF(int);
+static void cl_block(void);
+static void cl_hash(count_int);
+static void char_init(void);
+static void char_out(int);
+static void flush_char(void);
+static void *OutBuffer;
+static int   OutBufSize;
+static FrameBuffer *GIF_frame;
+
+static unsigned char pc2nc[256],r1[256],g1[256],b1[256];
+
+/*************************************************************/
+int FrameBuffer_makeGIF(FrameBuffer *f, ColorMap *c, void *outbuffer, unsigned int outbufsize)
+{
+  int   RWidth, RHeight;
+  int   LeftOfs, TopOfs;
+  int   ColorMapSize, InitCodeSize, Background, BitsPerPixel;
+  int   i,j,nc;
+  char *rmap, *gmap, *bmap;
+  char *cmap;
+  int   count;
+
+  Interlace = 0;
+  Background = 0;
+  OutBuffer = outbuffer;
+  OutBufSize = outbufsize;
+  GIF_frame = f;
+  cmap = (char *) c->cmap;
+  
+  op = (unsigned char *) outbuffer;
+  gif_error = 0;
+  for (i=0; i<256; i++) { pc2nc[i] = r1[i] = g1[i] = b1[i] = 0; }
+
+  /* compute number of unique colors */
+  nc = 0;
+  rmap = &cmap[0];
+  gmap = &cmap[256];
+  bmap = &cmap[512];
+
+  for (i=0; i<256; i++) {
+    /* see if color #i is already used */
+    for (j=0; j<i; j++) {
+      if (rmap[i] == rmap[j] && gmap[i] == gmap[j] && 
+	  bmap[i] == bmap[j]) break;
+    }
+
+    if (j==i) {  /* wasn't found */
+      pc2nc[i] = nc;
+      r1[nc] = rmap[i];
+      g1[nc] = gmap[i];
+      b1[nc] = bmap[i];
+      nc++;
+    }
+    else pc2nc[i] = pc2nc[j];
+  }
+
+  /* figure out 'BitsPerPixel' */
+  for (i=1; i<8; i++)
+    if ( (1<<i) >= nc) break;
+  
+  BitsPerPixel = i;
+
+  ColorMapSize = 1 << BitsPerPixel;
+	
+  RWidth  = Width  = f->width;
+  RHeight = Height = f->height;
+  LeftOfs = TopOfs = 0;
+
+  if (BitsPerPixel <= 1) InitCodeSize = 2;
+                    else InitCodeSize = BitsPerPixel;
+
+  curx = 0;
+  cury = f->height - 1;
+
+  strcpy((char *) op,"GIF89a");        /* Put in GIF magic number */
+  op+=6;
+  putgifword(RWidth);           /* screen descriptor */
+  putgifword(RHeight);
+
+  i = 0x80;	                 /* Yes, there is a color map */
+  i |= (8-1)<<4;                 /* OR in the color resolution (hardwired 8) */
+  i |= (BitsPerPixel - 1);       /* OR in the # of bits per pixel */
+  *(op++) = i;
+  *(op++) = Background;          /* background color */
+  *(op++) = 0;
+  for (i=0; i<ColorMapSize; i++) {       /* write out Global colormap */
+    *(op++) = r1[i];
+    *(op++) = g1[i];
+    *(op++) = b1[i];
+  }
+
+  *(op++) = ',';                /* image separator */
+
+  /* Write the Image header */
+  putgifword(LeftOfs);
+  putgifword(TopOfs);
+  putgifword(Width);
+  putgifword(Height);
+  *(op++) = 0;
+  *(op++) = InitCodeSize;
+
+  compress(InitCodeSize+1, f->pixels, f->width*f->height);
+
+  *(op++) = 0;
+  *(op++) = ';';
+  
+  count = (op - (unsigned char *) OutBuffer);
+  if (gif_error) return -1;
+  else return count;
+}
+
+/******************************/
+static void putgifword(w)
+int w;
+{
+  /* writes a 16-bit integer in GIF order (LSB first) */
+  *(op++) = w & 0xff;
+  *(op++) = (w>>8)&0xff;
+}
+
+/***********************************************************************/
+
+
+static unsigned long cur_accum = 0;
+static int           cur_bits = 0;
+
+
+
+
+#define GP_BITS	12    /* BITS was already defined on some systems */
+
+#define HSIZE  5003            /* 80% occupancy */
+
+typedef unsigned char   char_type;
+
+static int n_bits;                    /* number of bits/code */
+static int maxbits = GP_BITS;         /* user settable max # bits/code */
+static int maxcode;                   /* maximum code, given n_bits */
+static int maxmaxcode = 1 << GP_BITS; /* NEVER generate this */
+
+#define MAXCODE(n_bits)     ( (1 << (n_bits)) - 1)
+
+static  count_int      *htab;
+static  unsigned short *codetab;
+static  GIFOutBufSize;
+
+/* static  count_int      htab [HSIZE];
+static  unsigned short codetab [HSIZE]; */
+
+#define HashTabOf(i)   htab[i]
+#define CodeTabOf(i)   codetab[i]
+
+static int hsize = HSIZE;            /* for dynamic table sizing */
+
+/*
+ * To save much memory, we overlay the table used by compress() with those
+ * used by decompress().  The tab_prefix table is the same size and type
+ * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
+ * get this from the beginning of htab.  The output stack uses the rest
+ * of htab, and contains characters.  There is plenty of room for any
+ * possible stack (stack used to be 8000 characters).
+ */
+
+#define tab_prefixof(i) CodeTabOf(i)
+#define tab_suffixof(i)        ((char_type *)(htab))[i]
+#define de_stack               ((char_type *)&tab_suffixof(1<<GP_BITS))
+
+static int free_ent = 0;                  /* first unused entry */
+
+/*
+ * block compression parameters -- after all codes are used up,
+ * and compression rate changes, start over.
+ */
+static int clear_flg = 0;
+
+static long int out_count = 0;           /* # of codes output (for debugging) */
+
+/*
+ * compress stdin to stdout
+ *
+ * Algorithm:  use open addressing double hashing (no chaining) on the 
+ * prefix code / next character combination.  We do a variant of Knuth's
+ * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
+ * secondary probe.  Here, the modular division first probe is gives way
+ * to a faster exclusive-or manipulation.  Also do block compression with
+ * an adaptive reset, whereby the code table is cleared when the compression
+ * ratio decreases, but after the table fills.  The variable-length output
+ * codes are re-sized at this point, and a special CLEAR code is generated
+ * for the decompressor.  Late addition:  construct the table according to
+ * file size for noticeable speed improvement on small files.  Please direct
+ * questions about this implementation to ames!jaw.
+ */
+
+static int g_init_bits;
+
+static int ClearCode;
+static int EOFCode;
+
+
+/********************************************************/
+static void compress(init_bits, data, len)
+         int   init_bits;
+         unsigned char **data;
+         int   len;
+{
+  register long fcode;
+  register int i = 0;
+  register int c;
+  register int ent;
+  register int disp;
+  register int hsize_reg;
+  register int hshift;
+  int      code_count = 0;
+
+  /* Use the output buffer as temporary storage for GIF data */
+
+  if (OutBufSize < HSIZE*(sizeof(count_int) + sizeof(unsigned short))) {
+    gif_error =1;
+    return;
+  }
+
+  /* Put htab and codetab arrays into the output buffer */
+
+  GIFOutBufSize = OutBufSize - HSIZE*(sizeof(count_int) + sizeof(unsigned short)) - 16;
+  GIFOutBufSize = GIFOutBufSize & (~0x3);       /* Make sure it's double word alligned */
+
+  htab = (count_int *) ((char *) OutBuffer + GIFOutBufSize);
+  codetab = (unsigned short *) ((char *) OutBuffer + GIFOutBufSize + HSIZE*sizeof(count_int));
+
+  /*
+   * Set up the globals:  g_init_bits - initial number of bits
+   *                      g_outfile   - pointer to output file
+   */
+  g_init_bits = init_bits;
+
+
+  /* initialize 'compress' globals */
+  maxbits = GP_BITS;
+  maxmaxcode = 1<<GP_BITS;
+  memset(htab,0,sizeof(htab));
+  memset(codetab,0,sizeof(codetab));
+  hsize = HSIZE;
+  free_ent = 0;
+  clear_flg = 0;
+  out_count = 0;
+  cur_accum = 0;
+  cur_bits = 0;
+
+  /*
+   * Set up the necessary values
+   */
+  out_count = 0;
+  clear_flg = 0;
+  maxcode = MAXCODE(n_bits = g_init_bits);
+
+  ClearCode = (1 << (init_bits - 1));
+  EOFCode = ClearCode + 1;
+  free_ent = ClearCode + 2;
+
+  char_init();
+  ent = pc2nc[data[cury][curx]];
+  curx++;
+  if (curx >= GIF_frame->width) {
+    curx = 0;
+    cury--;
+  }
+  len--;
+
+  hshift = 0;
+  for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
+    hshift++;
+  hshift = 8 - hshift;                /* set hash code range bound */
+
+  hsize_reg = hsize;
+  cl_hash( (count_int) hsize_reg);            /* clear hash table */
+
+  output_GIF(ClearCode);
+  while (len) {
+    c = pc2nc[data[cury][curx]];
+    curx++;
+    if (curx >= GIF_frame->width) {
+      curx = 0;
+      cury--;
+    }
+    len--;
+
+    fcode = (long) ( ( (long) c << maxbits) + ent);
+       i = (((int) c << hshift) ^ ent);    /* xor hashing */
+
+    if ( HashTabOf (i) == fcode ) {
+      ent = CodeTabOf (i);
+      continue;
+    }
+
+    if ( (long)HashTabOf (i) < 0 )      /* empty slot */
+      goto nomatch;
+
+    disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
+    if ( i == 0 )
+      disp = 1;
+
+probe:
+    if ( (i -= disp) < 0 )
+      i += hsize_reg;
+
+    if ( HashTabOf (i) == fcode ) {
+      ent = CodeTabOf (i);
+      continue;
+    }
+
+    if ( (long)HashTabOf (i) >= 0 ) 
+      goto probe;
+
+nomatch:
+    output_GIF(ent);
+    out_count++;
+    ent = c;
+
+    if ( free_ent < maxmaxcode ) {
+      CodeTabOf (i) = free_ent++; /* code -> hashtable */
+      HashTabOf (i) = fcode;
+    }
+    else
+      cl_block();
+
+  }
+  /* Put out the final code */
+  output_GIF(ent);
+  output_GIF(EOFCode);
+}
+
+
+/*****************************************************************
+ * TAG( output_GIF )
+ *
+ * Output the given code.
+ * Inputs:
+ *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
+ *              that n_bits =< (long)wordsize - 1.
+ * Outputs:
+ *      Outputs code to the file.
+ * Assumptions:
+ *      Chars are 8 bits long.
+ * Algorithm:
+ *      Maintain a BITS character long buffer (so that 8 codes will
+ * fit in it exactly).  Use the VAX insv instruction to insert each
+ * code in turn.  When the buffer fills up empty it and start over.
+ */
+
+static
+unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
+                                  0x001F, 0x003F, 0x007F, 0x00FF,
+                                  0x01FF, 0x03FF, 0x07FF, 0x0FFF,
+                                  0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
+
+static void output_GIF(code)
+int code;
+{
+  cur_accum &= masks[cur_bits];
+
+  if (cur_bits > 0)
+    cur_accum |= ((long)code << cur_bits);
+  else
+    cur_accum = code;
+	
+  cur_bits += n_bits;
+
+  while( cur_bits >= 8 ) {
+    char_out( (int) (cur_accum & 0xff) );
+    cur_accum >>= 8;
+    cur_bits -= 8;
+  }
+
+  /*
+   * If the next entry is going to be too big for the code size,
+   * then increase it, if possible.
+   */
+
+  if (free_ent > maxcode || clear_flg) {
+
+    if( clear_flg ) {
+      maxcode = MAXCODE (n_bits = g_init_bits);
+      clear_flg = 0;
+    }
+    else {
+      n_bits++;
+      if ( n_bits == maxbits )
+	maxcode = maxmaxcode;
+      else
+	maxcode = MAXCODE(n_bits);
+    }
+  }
+	
+  if( code == EOFCode ) {
+    /* At EOF, write the rest of the buffer */
+    while( cur_bits > 0 ) {
+      char_out( (int)(cur_accum & 0xff) );
+      cur_accum >>= 8;
+      cur_bits -= 8;
+    }
+
+    flush_char();
+  }
+}
+
+
+/********************************/
+static void cl_block ()             /* table clear for block compress */
+{
+  /* Clear out the hash table */
+
+  cl_hash ( (count_int) hsize );
+  free_ent = ClearCode + 2;
+  clear_flg = 1;
+
+  output_GIF(ClearCode);
+}
+
+
+/********************************/
+static void cl_hash(hsize)          /* reset code table */
+register count_int hsize;
+{
+  register count_int *htab_p = htab+hsize;
+  register long i;
+  register long m1 = -1;
+
+  i = hsize - 16;
+  do {                            /* might use Sys V memset(3) here */
+    *(htab_p-16) = m1;
+    *(htab_p-15) = m1;
+    *(htab_p-14) = m1;
+    *(htab_p-13) = m1;
+    *(htab_p-12) = m1;
+    *(htab_p-11) = m1;
+    *(htab_p-10) = m1;
+    *(htab_p-9) = m1;
+    *(htab_p-8) = m1;
+    *(htab_p-7) = m1;
+    *(htab_p-6) = m1;
+    *(htab_p-5) = m1;
+    *(htab_p-4) = m1;
+    *(htab_p-3) = m1;
+    *(htab_p-2) = m1;
+    *(htab_p-1) = m1;
+    htab_p -= 16;
+  } while ((i -= 16) >= 0);
+
+  for ( i += 16; i > 0; i-- )
+    *--htab_p = m1;
+}
+
+
+/******************************************************************************
+ *
+ * GIF Specific routines
+ *
+ ******************************************************************************/
+
+/*
+ * Number of characters so far in this 'packet'
+ */
+static int a_count;
+
+/*
+ * Set up the 'byte output' routine
+ */
+static void char_init()
+{
+	a_count = 0;
+}
+
+/*
+ * Define the storage for the packet accumulator
+ */
+static char accum[ 256 ];
+
+/*
+ * Add a character to the end of the current packet, and if it is 254
+ * characters, flush the packet to disk.
+ */
+static void char_out(c)
+int c;
+{
+  accum[ a_count++ ] = c;
+  if( a_count >= 254 ) 
+    flush_char();
+}
+
+/*
+ * Flush the packet to disk, and reset the accumulator
+ */
+static void flush_char()
+{
+  if (gif_error) return;
+  if( a_count > 0 ) {
+    *(op++) = a_count;
+    memcpy(op,accum,a_count);
+    op+=a_count;
+    a_count = 0;
+    
+    if (op > (unsigned char *) ((char *) OutBuffer + (GIFOutBufSize - 2048))) {
+      gif_error = 1;
+    }
+  } 
+}	
+
+
+/* ----------------------------------------------------------------------
+   int FrameBuffer_writeGIF(char *filename)
+   
+   Write a GIF file to filename
+   ----------------------------------------------------------------------- */
+
+int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename) {
+
+  FILE *file;
+  void *buffer;
+  int nbytes;
+  int bufsize;
+
+  file = fopen(filename,"wb");
+  if (file == NULL) return -1;
+
+  bufsize = (f->width*f->height*3)/2;
+  buffer = (void *) malloc(bufsize);
+  nbytes = FrameBuffer_makeGIF(f,c,buffer,bufsize);
+  if (nbytes == -1) { 
+    free(buffer);
+    fclose(file);
+    return -1;
+  }
+  fwrite(buffer,nbytes,1,file);
+  fclose(file);
+  free(buffer);
+  return 0;
+}
+
+    
+  
+  
+  
diff --git a/trunk/Examples/GIFPlot/Lib/matrix.c b/trunk/Examples/GIFPlot/Lib/matrix.c
new file mode 100644
index 0000000..ef0cf3a
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/matrix.c
@@ -0,0 +1,343 @@
+/* ----------------------------------------------------------------------------- 
+ * matrix.c
+ *
+ *     Some 4x4 matrix operations
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define MATRIX
+#include "gifplot.h"
+#include <math.h>
+
+/* ------------------------------------------------------------------------
+   Matrix new_Matrix()
+
+   Create a new 4x4 matrix.
+   ------------------------------------------------------------------------ */
+Matrix
+new_Matrix() {
+  Matrix m;
+  m = (Matrix) malloc(16*sizeof(double));
+  return m;
+}
+
+/* ------------------------------------------------------------------------
+   delete_Matrix(Matrix *m);
+
+   Destroy a matrix
+   ------------------------------------------------------------------------ */
+
+void
+delete_Matrix(Matrix m) {
+  if (m)
+    free((char *) m);
+}
+
+/* ------------------------------------------------------------------------
+   Matrix Matrix_copy(Matrix a)
+
+   Makes a copy of matrix a and returns it.
+   ------------------------------------------------------------------------ */
+
+Matrix Matrix_copy(Matrix a) {
+  int i;
+  Matrix r = 0;
+  if (a) {
+    r = new_Matrix();
+    if (r) {
+      for (i = 0; i < 16; i++)
+	r[i] = a[i];
+    }
+  }
+  return r;
+}
+    
+/* ------------------------------------------------------------------------
+   Matrix_multiply(Matrix a, Matrix b, Matrix c)
+
+   Multiplies a*b = c
+   c may be one of the source matrices
+   ------------------------------------------------------------------------ */
+void
+Matrix_multiply(Matrix a, Matrix b, Matrix c) {
+  double temp[16];
+  int    i,j,k;
+
+  for (i =0; i < 4; i++)
+    for (j = 0; j < 4; j++) {
+      temp[i*4+j] = 0.0;
+      for (k = 0; k < 4; k++) 
+	temp[i*4+j] += a[i*4+k]*b[k*4+j];
+    }
+  for (i = 0; i < 16; i++)
+    c[i] = temp[i];
+}
+  
+/* ------------------------------------------------------------------------
+   Matrix_identity(Matrix a)
+
+   Puts an identity matrix in matrix a
+   ------------------------------------------------------------------------ */
+
+void
+Matrix_identity(Matrix a) {
+  int i;
+  for (i = 0; i < 16; i++) a[i] = 0;
+  a[0] = 1;
+  a[5] = 1;
+  a[10] = 1;
+  a[15] = 1;
+}
+
+/* ------------------------------------------------------------------------
+   Matrix_zero(Matrix a)
+   
+   Puts a zero matrix in matrix a
+   ------------------------------------------------------------------------ */
+void
+Matrix_zero(Matrix a) {
+  int i;
+  for (i = 0; i < 16; i++) a[i] = 0;
+}
+
+/* ------------------------------------------------------------------------
+   Matrix_transpose(Matrix a, Matrix result)
+
+   Transposes matrix a and puts it in result.
+   ------------------------------------------------------------------------ */
+void
+Matrix_transpose(Matrix a, Matrix result) {
+  double temp[16];
+  int i,j;
+
+  for (i = 0; i < 4; i++)
+    for (j = 0; j < 4; j++) 
+      temp[4*i+j] = a[4*j+i];
+
+  for (i = 0; i < 16; i++)
+    result[i] = temp[i];
+}
+
+
+/* ------------------------------------------------------------------------
+   Matrix_gauss(Matrix a, Matrix b)
+
+   Solves ax=b for x, using Gaussian elimination. Destroys a.
+   Really only used for calculating inverses of 4x4 transformation
+   matrices.
+   ------------------------------------------------------------------------ */
+
+void Matrix_gauss(Matrix a, Matrix b) {
+  int ipiv[4], indxr[4], indxc[4];
+  int i,j,k,l,ll;
+  int irow=0, icol=0;
+  double big, pivinv;
+  double dum;
+  for (j = 0; j < 4; j++)
+    ipiv[j] = 0;
+  for (i = 0; i < 4; i++) {
+    big = 0;
+    for (j = 0; j < 4; j++) {
+      if (ipiv[j] != 1) {
+	for (k = 0; k < 4; k++) {
+	  if (ipiv[k] == 0) {
+	    if (fabs(a[4*j+k]) >= big) {
+	      big = fabs(a[4*j+k]);
+	      irow = j;
+	      icol = k;
+	    }
+	  } else if (ipiv[k] > 1)
+	    return;  /* Singular matrix */
+	}
+      }
+    }
+    ipiv[icol] = ipiv[icol]+1;
+    if (irow != icol) {
+      for (l = 0; l < 4; l++) {
+	dum = a[4*irow+l];
+	a[4*irow+l] = a[4*icol+l];
+	a[4*icol+l] = dum;
+      }
+      for (l = 0; l < 4; l++) {
+	dum = b[4*irow+l];
+	b[4*irow+l] = b[4*icol+l];
+	b[4*icol+l] = dum;
+      }
+    }
+    indxr[i] = irow;
+    indxc[i] = icol;
+    if (a[4*icol+icol] == 0) return;
+    pivinv = 1.0/a[4*icol+icol];
+    a[4*icol+icol] = 1.0;
+    for (l = 0; l < 4; l++)
+      a[4*icol+l] = a[4*icol+l]*pivinv;
+    for (l = 0; l < 4; l++)
+      b[4*icol+l] = b[4*icol+l]*pivinv;
+    for (ll = 0; ll < 4; ll++) {
+      if (ll != icol) {
+	dum = a[4*ll+icol];
+	a[4*ll+icol] = 0;
+	for (l = 0; l < 4; l++)
+	  a[4*ll+l] = a[4*ll+l] - a[4*icol+l]*dum;
+	for (l = 0; l < 4; l++)
+	  b[4*ll+l] = b[4*ll+l] - b[4*icol+l]*dum;
+      }
+    }
+  }
+  for (l = 3; l >= 0; l--) {
+    if (indxr[l] != indxc[l]) {
+      for (k = 0; k < 4; k++) {
+	dum = a[4*k+indxr[l]];
+	a[4*k+indxr[l]] = a[4*k+indxc[l]];
+	a[4*k+indxc[l]] = dum;
+      }
+    }
+  }
+}
+
+/* ------------------------------------------------------------------------
+   Matrix_invert(Matrix a, Matrix inva)
+
+   Inverts Matrix a and places the result in inva.
+   Relies on the Gaussian Elimination code above. (See Numerical recipes).
+   ------------------------------------------------------------------------ */
+void
+Matrix_invert(Matrix a, Matrix inva) {
+
+  double  temp[16];
+  int     i;
+
+  for (i = 0; i < 16; i++)
+    temp[i] = a[i];
+  Matrix_identity(inva);
+  Matrix_gauss(temp,inva);
+}
+    
+/* ------------------------------------------------------------------------
+   Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t)
+
+   Transform a vector.    a*r ----> t
+   ------------------------------------------------------------------------ */
+
+void   Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t) {
+
+  double  rx, ry, rz, rw;
+
+  rx = r->x;
+  ry = r->y;
+  rz = r->z;
+  rw = r->w;
+  t->x = a[0]*rx + a[1]*ry + a[2]*rz + a[3]*rw;
+  t->y = a[4]*rx + a[5]*ry + a[6]*rz + a[7]*rw;
+  t->z = a[8]*rx + a[9]*ry + a[10]*rz + a[11]*rw;
+  t->w = a[12]*rx + a[13]*ry + a[14]*rz + a[15]*rw;
+}
+
+/* ------------------------------------------------------------------------
+   Matrix_transform4(Matrix a, double x, double y, double z, double w, GL_Vector *t)
+
+   Transform a vector from a point specified as 4 doubles
+   ------------------------------------------------------------------------ */
+
+void   Matrix_transform4(Matrix a, double rx, double ry, double rz, double rw,
+			 GL_Vector *t) {
+
+  t->x = a[0]*rx + a[1]*ry + a[2]*rz + a[3]*rw;
+  t->y = a[4]*rx + a[5]*ry + a[6]*rz + a[7]*rw;
+  t->z = a[8]*rx + a[9]*ry + a[10]*rz + a[11]*rw;
+  t->w = a[12]*rx + a[13]*ry + a[14]*rz + a[15]*rw;
+}
+
+/* ---------------------------------------------------------------------
+   Matrix_translate(Matrix a, double tx, double ty, double tz)
+
+   Put a translation matrix in Matrix a
+   ---------------------------------------------------------------------- */
+
+void Matrix_translate(Matrix a, double tx, double ty, double tz) {
+  Matrix_identity(a);
+  a[3] = tx;
+  a[7] = ty;
+  a[11] = tz;
+  a[15] = 1;
+}
+
+/* -----------------------------------------------------------------------
+   Matrix_rotatex(Matrix a, double deg)
+
+   Produce an x-rotation matrix for given angle in degrees.
+   ----------------------------------------------------------------------- */
+void
+Matrix_rotatex(Matrix a, double deg) {
+  double r;
+
+  r = 3.1415926*deg/180.0;
+  Matrix_zero(a);
+  a[0] = 1.0;
+  a[5] = cos(r);
+  a[6] = -sin(r);
+  a[9] = sin(r);
+  a[10] = cos(r);
+  a[15] = 1.0;
+}
+
+/* -----------------------------------------------------------------------
+   Matrix_rotatey(Matrix a, double deg)
+
+   Produce an y-rotation matrix for given angle in degrees.
+   ----------------------------------------------------------------------- */
+void
+Matrix_rotatey(Matrix a, double deg) {
+  double r;
+
+  r = 3.1415926*deg/180.0;
+  Matrix_zero(a);
+  a[0] = cos(r);
+  a[2] = sin(r);
+  a[5] = 1.0;
+  a[8] = -sin(r);
+  a[10] = cos(r);
+  a[15] = 1;
+  
+}
+/* -----------------------------------------------------------------------
+   Matrix_RotateZ(Matrix a, double deg)
+
+   Produce an z-rotation matrix for given angle in degrees.
+   ----------------------------------------------------------------------- */
+void
+Matrix_rotatez(Matrix a, double deg) {
+  double r;
+
+  r = 3.1415926*deg/180.0;
+  Matrix_zero(a);
+  a[0] = cos(r);
+  a[1] = -sin(r);
+  a[4] = sin(r);
+  a[5] = cos(r);
+  a[10] = 1.0;
+  a[15] = 1.0;
+}
+
+
+/* A debugging routine */
+
+void Matrix_set(Matrix a, int i, int j, double val) {
+  a[4*j+i] = val;
+}
+
+void Matrix_print(Matrix a) {
+  int i,j;
+  for (i = 0; i < 4; i++) {
+    for (j = 0; j < 4; j++) {
+      fprintf(stdout,"%10f ",a[4*i+j]);
+    }
+    fprintf(stdout,"\n");
+  }
+  fprintf(stdout,"\n");
+}
+
diff --git a/trunk/Examples/GIFPlot/Lib/pixmap.c b/trunk/Examples/GIFPlot/Lib/pixmap.c
new file mode 100644
index 0000000..a55cf04
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/pixmap.c
@@ -0,0 +1,159 @@
+/* ----------------------------------------------------------------------------- 
+ * pixmap.c
+ *
+ *     Pixel maps (i.e., bitmaps)
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define PIXMAP
+#include "gifplot.h"
+
+/* -----------------------------------------------------------------------
+   PixMap *new_PixMap(int width, int height, int centerx, int centery)
+
+   Create a new pixmap of given size
+   ----------------------------------------------------------------------- */
+PixMap *new_PixMap(int width, int height, int centerx, int centery) {
+  PixMap *pm;
+  if ((width > 0) && (height > 0)) {
+    pm = (PixMap *) malloc(sizeof(PixMap));
+    pm->width = width;
+    pm->height = height;
+    pm->centerx = centerx;
+    pm->centery = centery;
+    pm->map = (int *) malloc(height*width*sizeof(int));
+    return pm;
+  }
+  return (PixMap *) 0;
+}
+
+/* --------------------------------------------------------------------------
+   void delete_PixMap(PixMap *pm)
+
+   Destroy a pixmap
+   -------------------------------------------------------------------------- */
+
+void delete_PixMap(PixMap *pm) {
+  if (pm) {
+    free((char *) pm->map);
+    free((char *) pm);
+  }
+}
+
+/* ---------------------------------------------------------------------------
+   void PixMap_set(PixMap *pm, int x, int y, int pix)
+
+   Set a pixel in the bitmap
+   --------------------------------------------------------------------------- */
+void
+PixMap_set(PixMap *pm, int x, int y, int pix) {
+  if ((x < 0) || (x>=pm->width)) return;
+  if ((y < 0) || (y>=pm->height)) return;
+
+  pm->map[pm->width*y + x] = pix;
+}
+
+/* -----------------------------------------------------------------------------
+   void FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor) 
+
+   Draw a pixmap onto the framebuffer.   This is somewhat optimized for speed.
+   ------------------------------------------------------------------------------ */
+
+void
+FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor) {
+
+  int startx, starty;         /* Starting location on framebuffer */
+  int startpixx = 0, startpixy = 0;   /* Starting location in pixmap      */
+  int endx, endy;             /* Ending location on framebuffer   */
+  int i,j, px, py;
+  int c;
+  
+  startx = x - pm->centerx;
+  starty = y + pm->centery;
+  endx = startx + pm->width;
+  endy = starty - pm->height;
+
+  /* Figure out if we need to clip */
+
+  if (startx < f->xmin) {
+    startpixx = f->xmin - startx;
+    startx = f->xmin;
+  }
+  if (starty >= f->ymax) {
+    startpixy = starty - f->ymax;
+    starty = f->ymax-1;
+  }
+  if (endx >= f->xmax) {
+    endx = f->xmax-1;
+  }
+  if (endy < f->ymin) {
+    endy = f->ymin;
+  }
+  py = startpixy;
+  for (j = starty; j >= endy; j--) {
+    px = startpixx;
+    for (i = startx; i < endx; i++) {
+      c = pm->map[py*pm->width + px];
+      switch (c) {
+      case GIFPLOT_FOREGROUND:
+	f->pixels[j][i] = fgcolor;
+	break;
+      case GIFPLOT_BACKGROUND:
+	f->pixels[j][i] = bgcolor;
+	break;
+      default:
+	break;
+      }
+      px++;
+    }
+    py++;
+  }
+}
+
+/**************************************************************************
+ * Some common PixMaps  (for plotting)
+ *
+ **************************************************************************/
+
+int _SQUARE_MAP[] = {
+  0,1,1,1,1,1,1,1,
+  0,1,1,1,1,1,1,1,
+  0,1,1,1,1,1,1,1,
+  0,1,1,1,1,1,1,1,
+  0,1,1,1,1,1,1,1,
+  0,1,1,1,1,1,1,1,
+  0,1,1,1,1,1,1,1,
+  0,0,0,0,0,0,0,0 };
+
+PixMap  PixMap_SQUARE = { 8,8,4,4, _SQUARE_MAP};
+
+int _TRIANGLE_MAP[] = {
+  0,0,0,1,0,0,0,0,
+  0,0,0,1,0,0,0,0,
+  0,0,1,1,1,0,0,0,
+  0,0,1,1,1,0,0,0,
+  0,1,1,1,1,1,0,0,
+  0,1,1,1,1,1,0,0,
+  1,1,1,1,1,1,1,0,
+  0,0,0,0,0,0,0,0 };
+
+PixMap  PixMap_TRIANGLE = { 8,8,4,4,_TRIANGLE_MAP};
+
+int _CROSS_MAP[] = {
+  0,0,0,1,0,0,0,0,
+  0,0,0,1,0,0,0,0,
+  0,0,0,1,0,0,0,0,
+  1,1,1,1,1,1,1,0,
+  0,0,0,1,0,0,0,0,
+  0,0,0,1,0,0,0,0,
+  0,0,0,1,0,0,0,0,
+  0,0,0,0,0,0,0,0 };
+
+PixMap  PixMap_CROSS = { 8,8,4,4,_CROSS_MAP};
+
+  
+      
diff --git a/trunk/Examples/GIFPlot/Lib/plot2d.c b/trunk/Examples/GIFPlot/Lib/plot2d.c
new file mode 100644
index 0000000..e78107b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/plot2d.c
@@ -0,0 +1,445 @@
+/* ----------------------------------------------------------------------------- 
+ * plot2d.c
+ *
+ *     2-Dimensional plotting
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define PLOT2D
+
+#include "gifplot.h"
+
+/* ------------------------------------------------------------------------
+   Plot2D *new_Plot2D(FrameBuffer *frame, xmin, ymin, xmax, ymax)
+
+   Create a new 2D plot with given minimum and maximum coordinates.
+   ------------------------------------------------------------------------ */
+Plot2D  *new_Plot2D(FrameBuffer *frame,double xmin,double ymin,double xmax,double ymax) {
+  Plot2D  *p2;
+  if (frame) {
+    if (xmax <= xmin) return (Plot2D *) 0;
+    if (ymax <= ymin) return (Plot2D *) 0;
+    p2 = (Plot2D *) malloc(sizeof(Plot2D));
+    p2->frame = frame;
+    p2->xmin = xmin;
+    p2->ymin = ymin;
+    p2->xmax = xmax;
+    p2->ymax = ymax;
+    p2->view_xmin = 0;
+    p2->view_xmax = frame->width;
+    p2->view_ymin = 0;
+    p2->view_ymax = frame->height;
+    p2->xscale = LINEAR;
+    p2->yscale = LINEAR;
+    p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin);
+    p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin);
+    return p2;
+  }
+  return (Plot2D *) 0;
+}
+
+/* ----------------------------------------------------------------------------
+   delete_Plot2D(Plot2D *p2)
+
+   Delete a 2D plot
+   ---------------------------------------------------------------------------- */
+void
+delete_Plot2D(Plot2D *p2) {
+  if (p2)
+    free((char *) p2);
+}
+
+/* -----------------------------------------------------------------------------
+   Plot2D *Plot2D_copy(Plot2D *p2)
+
+   Makes a copy of the Plot2D data structure.
+   ----------------------------------------------------------------------------- */
+
+Plot2D *Plot2D_copy(Plot2D *p2) {
+  Plot2D *c2;
+  if (p2) {
+    c2 = (Plot2D *) malloc(sizeof(Plot2D));
+    if (c2) {
+      c2->frame = p2->frame;
+      c2->view_xmin = p2->view_xmin;
+      c2->view_ymin = p2->view_ymin;
+      c2->view_xmax = p2->view_xmax;
+      c2->view_ymax = p2->view_ymax;
+      c2->xmin = p2->xmin;
+      c2->ymin = p2->ymin;
+      c2->xmax = p2->xmax;
+      c2->ymax = p2->ymax;
+      c2->xscale = p2->xscale;
+      c2->yscale = p2->yscale;
+      c2->dx = p2->dx;
+      c2->dy = p2->dy;
+    }
+    return c2;
+  } else {
+    return (Plot2D *) 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+   Plot2D_clear(Plot2D *p2, Pixel c)
+
+   Clear the region assigned to this plot to the given color.
+   -------------------------------------------------------------------------- */
+
+void Plot2D_clear(Plot2D *p2, Pixel c) {
+  int i,j;
+  for (i = p2->view_xmin; i < p2->view_xmax; i++)
+    for (j = p2->view_ymin; j < p2->view_ymax; j++) {
+      p2->frame->pixels[j][i] = c;
+    }
+}
+
+/* ------------------------------------------------------------------------------
+   Plot2D_setview
+
+   Sets the plot region on the framebuffer
+   ------------------------------------------------------------------------------ */
+
+void
+Plot2D_setview(Plot2D *p2, int vxmin, int vymin, int vxmax, int vymax) {
+  if (p2) {
+    p2->view_xmin = vxmin;
+    p2->view_ymin = vymin;
+    p2->view_xmax = vxmax;
+    p2->view_ymax = vymax;
+    p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin);
+    p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin);
+    FrameBuffer_setclip(p2->frame,vxmin,vymin,vxmax,vymax);
+  }
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax)
+
+   Sets the plotting range.
+   ------------------------------------------------------------------------------- */
+
+void
+Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax) {
+  if (p2) {
+    p2->xmin = xmin;
+    p2->ymin = ymin;
+    p2->xmax = xmax;
+    p2->ymax = ymax;
+    p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin);
+    p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin);
+  }
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_setscale(Plot2D *p2, int xscale, int yscale)
+
+   Sets the plotting scaling method
+   ------------------------------------------------------------------------------- */
+
+void
+Plot2D_setscale(Plot2D *p2, int xscale, int yscale) {
+  if (p2) {
+    p2->xscale = xscale;
+    p2->yscale = yscale;
+  }
+}
+
+/* ----------------------------------------------------------------------------
+   Plot2D_transform(Plot2D *p2, double x, double y, int *px, int *py)
+   
+   Transforms x,y into screen coordinates px and py.  Result is returned
+   in px and py.  Rounds to the nearest pixel instead of truncating.
+   ----------------------------------------------------------------------------- */
+
+void
+Plot2D_transform(Plot2D *p2, double x, double y, int *px, int *py) {
+  if (p2) {
+    *px = p2->view_xmin + (int) (p2->dx*(x-p2->xmin) + 0.5);
+    *py = p2->view_ymin + (int) (p2->dy*(y-p2->ymin) + 0.5);
+  }
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_plot(Plot2D *p2, double x, double y, Pixel color)
+
+   Plot a 2D Point of a given color
+   ------------------------------------------------------------------------------- */
+void
+Plot2D_plot(Plot2D *p2, double x, double y, Pixel color) {
+  int px, py;
+
+  Plot2D_transform(p2,x,y,&px,&py);
+  FrameBuffer_plot(p2->frame, px, py, color);
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_box(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel Color)
+
+   Plot an outline box on the 2D plot
+   ------------------------------------------------------------------------------- */
+void
+Plot2D_box(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color) {
+  int ix1, ix2,iy1, iy2;
+
+  Plot2D_transform(p2,x1,y1,&ix1,&iy1);
+  Plot2D_transform(p2,x2,y2,&ix2,&iy2);
+  FrameBuffer_box(p2->frame,ix1,iy1,ix2,iy2,color);
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_solidbox(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel Color)
+
+   Plot a solid box box on the 2D plot
+   ------------------------------------------------------------------------------- */
+void
+Plot2D_solidbox(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color) {
+  int ix1, ix2,iy1, iy2;
+
+  Plot2D_transform(p2,x1,y1,&ix1,&iy1);
+  Plot2D_transform(p2,x2,y2,&ix2,&iy2);
+  FrameBuffer_solidbox(p2->frame,ix1,iy1,ix2,iy2,color);
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_interpbox(Plot2D *p2, double x1, double y1, double x2, double y2,
+                    Pixel c1, Pixel c2, Pixel c3, Pixel c4)
+
+   Plot a color-interpolated box on the 2D plot
+   ------------------------------------------------------------------------------- */
+void
+Plot2D_interpbox(Plot2D *p2, double x1, double y1,double x2, double y2,
+		 Pixel c1, Pixel c2, Pixel c3, Pixel c4) {
+  int ix1, ix2,iy1, iy2;
+
+  Plot2D_transform(p2,x1,y1,&ix1,&iy1);
+  Plot2D_transform(p2,x2,y2,&ix2,&iy2);
+  FrameBuffer_interpbox(p2->frame,ix1,iy1,ix2,iy2,c1,c2,c3,c4);
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color)
+
+   Make an outline circle on the 2D plot.
+   ------------------------------------------------------------------------------- */
+void
+Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color) {
+  int ix, iy, ir;
+
+  Plot2D_transform(p2,x,y,&ix,&iy);
+  ir = p2->dx * radius;        /* This is really incorrect. Will need ellipse */
+  if (ir > 1) 
+    FrameBuffer_circle(p2->frame,ix,iy,ir,color);
+  else
+    FrameBuffer_plot(p2->frame,ix,iy,color);
+  
+}
+  
+/* -------------------------------------------------------------------------------
+   Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color)
+
+   Make an solid circle on the 2D plot.
+   ------------------------------------------------------------------------------- */
+void
+Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color) {
+  int ix, iy, ir;
+
+  Plot2D_transform(p2,x,y,&ix,&iy);
+  ir = p2->dx * radius;        /* This is really incorrect. Will need ellipse */
+  if (ir > 1) 
+    FrameBuffer_solidcircle(p2->frame,ix,iy,ir,color);
+  else
+    FrameBuffer_plot(p2->frame,ix,iy,color);
+}
+
+/* -------------------------------------------------------------------------------
+   Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color)
+
+   Draw a line
+   ------------------------------------------------------------------------------- */
+
+void
+Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color) {
+  int ix1, ix2, iy1, iy2;
+
+  Plot2D_transform(p2,x1,y1,&ix1,&iy1);
+  Plot2D_transform(p2,x2,y2,&ix2,&iy2);
+  FrameBuffer_line(p2->frame,ix1,iy1,ix2,iy2,color);
+}
+
+
+
+/* -------------------------------------------------------------------------------
+   Plot2D_start(Plot2D *p2)
+
+   This should be called before starting to make a 2D plot. It will change
+   the viewport coordinates for the framebuffer and do other stuff.
+   ------------------------------------------------------------------------------- */
+
+void Plot2D_start(Plot2D *p2) {
+  if (p2) {
+    FrameBuffer_setclip(p2->frame, p2->view_xmin,p2->view_ymin,p2->view_xmax, p2->view_ymax);
+    p2->dx = (p2->view_xmax - p2->view_xmin)/(p2->xmax - p2->xmin);
+    p2->dy = (p2->view_ymax - p2->view_ymin)/(p2->ymax - p2->ymin);
+  }
+}
+
+/* --------------------------------------------------------------------------
+   void Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor)
+
+   Draw a pixel map at the given coordinates.  (Used for putting symbols on 2D
+   plots).
+   -------------------------------------------------------------------------- */
+void
+Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor) {
+  int ix, iy;
+
+  Plot2D_transform(p2,x,y,&ix,&iy);
+  FrameBuffer_drawpixmap(p2->frame,pm,ix,iy,color,bgcolor);
+}
+
+/* ----------------------------------------------------------------------------
+   void Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel color)
+
+   Draw an X axis bar at location x,y with ticks spaced every xtick units.
+   Ticks are spaced starting at "x"
+   ----------------------------------------------------------------------------- */
+
+void Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel color) {
+  int ix, iy,iy2;
+  double xt;
+
+  /* Draw a line fox the axis */
+  
+  Plot2D_line(p2,p2->xmin,y,p2->xmax,y,color);
+  xt = x;
+  while (xt >= p2->xmin) {
+    Plot2D_transform(p2,xt,y,&ix,&iy);
+    iy2 = iy+ticklength;
+    iy = iy-ticklength;
+    FrameBuffer_line(p2->frame,ix,iy,ix,iy2,color);
+    xt = xt - xtick;
+  }
+  xt = x + xtick;
+  while (xt < p2->xmax) {
+    Plot2D_transform(p2,xt,y,&ix,&iy);
+    iy2 = iy+ticklength;
+    iy = iy-ticklength;
+    FrameBuffer_line(p2->frame,ix,iy,ix,iy2,color);
+    xt = xt + xtick;
+  }
+}
+
+
+/* ----------------------------------------------------------------------------
+   void Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel c)
+
+   Draw an Y axis bar at location x,y with ticks spaced every xtick units.
+   Ticks are spaced starting at "y"
+   ----------------------------------------------------------------------------- */
+
+void Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel color) {
+  int ix, iy, ix2;
+  double yt;
+
+  /* Draw a line fox the axis */
+  
+  Plot2D_line(p2,x,p2->ymin,x,p2->ymax,color);
+  yt = y;
+  while (yt >= p2->ymin) {
+    Plot2D_transform(p2,x,yt,&ix,&iy);
+    ix2 = ix+ticklength;
+    ix = ix-ticklength;
+    FrameBuffer_line(p2->frame,ix,iy,ix2,iy,color);
+    yt = yt - ytick;
+  }
+  yt = y + ytick;
+  while (yt < p2->ymax) {
+    Plot2D_transform(p2,x,yt,&ix,&iy);
+    ix2 = ix+ticklength;
+    ix = ix-ticklength;
+    FrameBuffer_line(p2->frame,ix,iy,ix2,iy,color);
+    yt = yt + ytick;
+  }
+}
+
+
+/* -------------------------------------------------------------------------
+   Plot2D_triangle(Plot2D *p2, double x1, double y1, 
+                               double x2, double y2, 
+			       double x3, double y3, 
+			       Pixel fillcolor)
+
+   This function draws a 2D outline triangle.
+   -------------------------------------------------------------------------- */
+
+void Plot2D_triangle(Plot2D *p2, double x1, double y1,
+		     double x2, double y2, 
+		     double x3, double y3, Pixel color) {
+
+  Plot2D_line(p2,x1,y1,x2,y2,color);
+  Plot2D_line(p2,x2,y2,x3,y3,color);
+  Plot2D_line(p2,x3,y3,x1,y1,color);
+
+}
+
+
+/* -------------------------------------------------------------------------
+   Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, 
+                               double x2, double y2, 
+			       double x3, double y3, 
+			       Pixel color)
+
+   This function draws a 2D filled triangle.    Can be used to
+   draw other primitives such as quadralaterals, etc...
+
+   -------------------------------------------------------------------------- */
+
+void Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, 
+
+			  double x2, double y2, 
+			  double x3, double y3, Pixel color) {
+
+  int        tx1, tx2, tx3, ty1, ty2, ty3;
+  
+  /* Transform the three points into screen coordinates */
+
+  Plot2D_transform(p2,x1,y1,&tx1,&ty1);
+  Plot2D_transform(p2,x2,y2,&tx2,&ty2);
+  Plot2D_transform(p2,x3,y3,&tx3,&ty3);
+
+  FrameBuffer_solidtriangle(p2->frame,tx1,ty1,tx2,ty2,tx3,ty3,color);
+  
+}    
+
+/* -------------------------------------------------------------------------
+   Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1,
+                               double x2, double y2, Pixel c2,
+			       double x3, double y3, Pixel c3);
+
+   This function draws a 2D filled triangle with color interpolation.
+   Can be used to draw other primitives such as quadralaterals, etc...
+   -------------------------------------------------------------------------- */
+
+void Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1,
+			   double x2, double y2, Pixel c2,
+			   double x3, double y3, Pixel c3) {
+
+  int        tx1, tx2, tx3, ty1, ty2, ty3;
+  
+  /* Transform the three points into screen coordinates */
+
+  Plot2D_transform(p2,x1,y1,&tx1,&ty1);
+  Plot2D_transform(p2,x2,y2,&tx2,&ty2);
+  Plot2D_transform(p2,x3,y3,&tx3,&ty3);
+
+  FrameBuffer_interptriangle(p2->frame,tx1,ty1,c1,tx2,ty2,c2,tx3,ty3,c3);
+  
+}    
+  
+  
+
diff --git a/trunk/Examples/GIFPlot/Lib/plot3d.c b/trunk/Examples/GIFPlot/Lib/plot3d.c
new file mode 100644
index 0000000..387e420
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Lib/plot3d.c
@@ -0,0 +1,2181 @@
+/* ----------------------------------------------------------------------------- 
+ * plot3d.c
+ *
+ *     Three-dimensional plotting.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#define PLOT3D
+#include "gifplot.h"
+#include <math.h>
+#include <float.h>
+
+#define ORTHO        1
+#define PERSPECTIVE  2
+/* ------------------------------------------------------------------------
+   Plot3D *new_Plot3D(FrameBuffer *f, double xmin, double ymin, double zmin,
+   double xmax, double ymax, double zmax)
+
+   Creates a new 3D plot.  Min and max coordinates are primarily used to
+   pick some default parameters.  Returns NULL on failure
+   ------------------------------------------------------------------------- */
+
+Plot3D *new_Plot3D(FrameBuffer *f, double xmin, double ymin, double zmin,
+		   double xmax, double ymax, double zmax) {
+
+  Plot3D  *p3;
+  void Plot3D_maketransform(Plot3D *p3);
+  
+  /* Check to make sure the framebuffer and min/max parameters are valid */
+
+  if (!f) return (Plot3D *) 0;
+  if ((xmin > xmax) || (ymin > ymax) || (zmin > zmax)) return (Plot3D *) 0;
+
+  p3 = (Plot3D *) malloc(sizeof(Plot3D));
+  p3->frame = f;
+  p3->xmin = xmin;
+  p3->ymin = ymin;
+  p3->zmin = zmin;
+  p3->xmax = xmax;
+  p3->ymax = ymax;
+  p3->zmax = zmax;
+
+  /* Set view region to the entire size of the framebuffer */
+
+  p3->view_xmin = 0;
+  p3->view_ymin = 0;
+  p3->view_xmax = f->width;
+  p3->view_ymax = f->height;
+  p3->width = f->width;
+  p3->height = f->height;
+  
+  /* Calculate a center point based off the min and max coordinates given */
+
+  p3->xcenter = (xmax - xmin)/2.0 + xmin;
+  p3->ycenter = (ymax - ymin)/2.0 + ymin;
+  p3->zcenter = (zmax - zmin)/2.0 + zmin;
+
+  /* Calculate the aspect ratio of the viewing region */
+
+  p3->aspect = (double) f->width/(double) f->height;
+
+  /* Set default view parameters */
+  p3->xshift = 1.0;
+  p3->yshift = 1.0;
+  p3->zoom   = 0.5;
+  p3->fovy   = 40.0;         /* 40 degree field of view */
+
+  /* Create matrices */
+
+  p3->model_mat = new_Matrix();
+  p3->view_mat = new_Matrix();
+  p3->center_mat = new_Matrix();
+  p3->fullmodel_mat = new_Matrix();
+  p3->trans_mat = new_Matrix();
+  p3->pers_mode = ORTHO;
+
+  FrameBuffer_zresize(p3->frame,p3->width, p3->height);
+  Matrix_identity(p3->view_mat);
+  Matrix_identity(p3->model_mat);
+  Matrix_translate(p3->center_mat, -p3->xcenter,-p3->ycenter,-p3->zcenter);
+  Plot3D_maketransform(p3);
+  return p3;
+}
+
+/* ---------------------------------------------------------------------
+   delete_Plot3D(Plot3D *p3)
+
+   Deletes a 3D plot
+   --------------------------------------------------------------------- */
+
+void delete_Plot3D(Plot3D *p3) {
+  if (p3) {
+    delete_Matrix(p3->view_mat);
+    delete_Matrix(p3->model_mat);
+    delete_Matrix(p3->trans_mat);
+    free((char *) p3);
+  }
+}
+
+/* ---------------------------------------------------------------------
+   Plot3D *Plot3D_copy(Plot3D *p3)
+
+   This makes a copy of the 3D plot structure and returns a pointer to it.
+   --------------------------------------------------------------------- */
+
+Plot3D *Plot3D_copy(Plot3D *p3) {
+  Plot3D *c3;
+  if (p3) {
+    c3 = (Plot3D *) malloc(sizeof(Plot3D));
+    if (c3) {
+      c3->frame = p3->frame;
+      c3->view_xmin = p3->view_xmin;
+      c3->view_ymin = p3->view_ymin;
+      c3->view_xmax = p3->view_xmax;
+      c3->view_ymax = p3->view_ymax;
+      c3->xmin = p3->xmin;
+      c3->ymin = p3->ymin;
+      c3->zmin = p3->zmin;
+      c3->xmax = p3->xmax;
+      c3->ymax = p3->ymax;
+      c3->zmax = p3->zmax;
+      c3->xcenter = p3->xcenter;
+      c3->ycenter = p3->ycenter;
+      c3->zcenter = p3->zcenter;
+      c3->fovy = p3->fovy;
+      c3->aspect = p3->aspect;
+      c3->znear = p3->znear;
+      c3->zfar = p3->zfar;
+      c3->center_mat = Matrix_copy(p3->center_mat);
+      c3->model_mat = Matrix_copy(p3->model_mat);
+      c3->view_mat = Matrix_copy(p3->view_mat);
+      c3->fullmodel_mat = Matrix_copy(p3->fullmodel_mat);
+      c3->trans_mat = Matrix_copy(p3->trans_mat);
+      c3->lookatz = p3->lookatz;
+      c3->xshift = p3->xshift;
+      c3->yshift = p3->yshift;
+      c3->zoom = p3->zoom;
+      c3->width = p3->width;
+      c3->height = p3->height;
+      c3->pers_mode = p3->pers_mode;
+    }
+    return c3;
+  } else {
+    return (Plot3D *) 0;
+  }
+}
+
+/* ----------------------------------------------------------------------
+   Plot3D_clear(Plot3D *p3, Pixel bgcolor)
+
+   Clear the pixel and zbuffer only for the view region of this image.
+   ---------------------------------------------------------------------- */
+void
+Plot3D_clear(Plot3D *p3, Pixel bgcolor) {
+  int i,j;
+
+  for (i = p3->view_xmin; i < p3->view_xmax; i++)
+    for (j = p3->view_ymin; j < p3->view_ymax; j++) {
+      p3->frame->pixels[j][i] = bgcolor;
+      p3->frame->zbuffer[j][i] = ZMIN;
+    }
+}
+
+/* ---------------------------------------------------------------------
+   Plot3D_maketransform(Plot3D *p3)
+
+   This function builds the total 3D transformation matrix from a
+   collection of components.
+
+   Trans = View * Rotation * Center
+
+   Where View is the viewing transformation matrix, Rotation is the
+   model rotation matrix, Center is the translation matrix used to
+   center the Model at the origin.
+   --------------------------------------------------------------------- */
+
+void
+Plot3D_maketransform(Plot3D *p3) {
+
+  Matrix_multiply(p3->model_mat,p3->center_mat, p3->fullmodel_mat);
+  Matrix_multiply(p3->view_mat,p3->fullmodel_mat, p3->trans_mat);
+}
+   
+/* ---------------------------------------------------------------------
+   Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar)
+
+   Sets up the perspective viewing transformation.   Assumes "lookat"
+   has already been called.
+   --------------------------------------------------------------------- */
+
+void
+Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar) {
+  double theta;
+  double mat[16];
+
+  p3->fovy = fovy;
+  p3->znear = znear;
+  p3->zfar = zfar;
+
+  theta = 3.1415926*fovy/180.0;
+
+  Matrix_identity(mat);
+  mat[0] = cos(theta/2.0)/(sin(theta/2.0)*p3->aspect);
+  mat[5] = cos(theta/2.0)/(sin(theta/2.0));
+  mat[10] = -(zfar + znear)/(zfar-znear);
+  mat[14] = -1.0;
+  mat[11] = -(2*zfar*znear)/(zfar - znear);
+  mat[15] = 0.0;
+
+  /* Update the view transformation matrix */
+  
+  Matrix_multiply(mat,p3->view_mat,p3->view_mat);
+
+  /* Update the global transformation matrix */
+  
+  Plot3D_maketransform(p3);
+  p3->pers_mode = PERSPECTIVE;
+
+}
+
+/* ---------------------------------------------------------------------
+   Plot3D_lookat(Plot3D *p3, double z)
+
+   A greatly simplified version of (lookat).  Specifies the position
+   of the viewpoint. (can be used for moving image in or out).
+
+   Destroys the current viewing transformation matrix, so it will have
+   to be recalculated.
+   --------------------------------------------------------------------- */
+  
+void
+Plot3D_lookat(Plot3D *p3, double z) {
+  if (p3) {
+    Matrix_translate(p3->view_mat, 0,0,-z);
+    p3->lookatz = z;
+    Plot3D_maketransform(p3);
+  }
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_autoperspective(Plot3D *p3, double fovy)
+
+   Automatically figures out a semi-decent viewpoint given the
+   min,max parameters currently set for this image
+   ------------------------------------------------------------------------- */
+
+void
+Plot3D_autoperspective(Plot3D *p3, double fovy) {
+
+  /* Make a perspective transformation matrix for this system */
+
+  double  zfar;
+  double  znear;
+  double  d, dmax;
+  double  cx,cy,cz;
+  double  xmin,xmax,ymin,ymax,zmin,zmax;
+
+  xmin = p3->xmin;
+  ymin = p3->ymin;
+  zmin = p3->zmin;
+  xmax = p3->xmax;
+  ymax = p3->ymax;
+  zmax = p3->zmax;
+  cx = p3->xcenter;
+  cy = p3->ycenter;
+  cz = p3->zcenter;
+  
+  /* Calculate longest point from center point */
+
+  dmax = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz);
+  d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz);
+  if (d > dmax) dmax = d;
+  d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz);
+  if (d > dmax) dmax = d;
+  d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz);
+  if (d > dmax) dmax = d;
+  d = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+  d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+  d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+  d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+
+  dmax = sqrt(dmax);
+  d = p3->lookatz;
+  
+  znear = d - dmax;
+  zfar = znear+1.5*dmax;
+  Plot3D_perspective(p3, fovy,znear,zfar);
+  
+}
+
+   
+/* ---------------------------------------------------------------------
+   Plot3D_ortho(Plot3D *p3, double left, double right, double bottom, double top)
+
+   Sets up an orthographic viewing transformation.   
+   --------------------------------------------------------------------- */
+
+void
+Plot3D_ortho(Plot3D *p3, double left, double right, double bottom, double top) {
+
+
+  Matrix_identity(p3->view_mat);
+  p3->view_mat[0] = (2.0/(right - left))/p3->aspect;
+  p3->view_mat[5] = 2.0/(top - bottom);
+  p3->view_mat[10] = -1;
+  p3->view_mat[15] = 1.0;
+  p3->view_mat[3] = -(right+left)/(right-left);
+  p3->view_mat[7] = -(top+bottom)/(top-bottom);
+
+  /* Update the global transformation matrix */
+  
+  Plot3D_maketransform(p3);
+  p3->pers_mode = ORTHO;
+  p3->ortho_left = left;
+  p3->ortho_right = right;
+  p3->ortho_bottom = bottom;
+  p3->ortho_top = top;
+
+}
+
+/* ---------------------------------------------------------------------
+   Plot3D_autoortho(Plot3D *p3)
+
+   Automatically pick an orthographic projection that's probably
+   pretty good.
+   --------------------------------------------------------------------- */
+
+void
+Plot3D_autoortho(Plot3D *p3) {
+
+  /* Make a perspective transformation matrix for this system */
+
+  double  d, dmax;
+  double  cx,cy,cz;
+  double  xmin,xmax,ymin,ymax,zmin,zmax;
+
+  xmin = p3->xmin;
+  ymin = p3->ymin;
+  zmin = p3->zmin;
+  xmax = p3->xmax;
+  ymax = p3->ymax;
+  zmax = p3->zmax;
+  cx = p3->xcenter;
+  cy = p3->ycenter;
+  cz = p3->zcenter;
+  
+  /* Calculate longest point from center point */
+
+  dmax = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz);
+  d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmin-cz)*(zmin-cz);
+  if (d > dmax) dmax = d;
+  d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz);
+  if (d > dmax) dmax = d;
+  d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmin-cz)*(zmin-cz);
+  if (d > dmax) dmax = d;
+  d = (xmin-cx)*(xmin-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+  d = (xmax-cx)*(xmax-cx) + (ymin-cy)*(ymin-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+  d = (xmin-cx)*(xmin-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+  d = (xmax-cx)*(xmax-cx) + (ymax-cy)*(ymax-cy) + (zmax-cz)*(zmax-cz);
+  if (d > dmax) dmax = d;
+
+  dmax = sqrt(dmax);
+
+  Plot3D_ortho(p3,-dmax,dmax,-dmax,dmax);
+  
+}
+
+
+
+/* -------------------------------------------------------------------------
+   Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax)
+
+   Sets the viewport for this 3D graph.  Will recalculate all of the
+   local viewing transformation matrices accordingly.
+   ------------------------------------------------------------------------- */
+void
+Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax) {
+  if (p3) {
+    if ((vxmin > vxmax) || (vymin >vymax)) return;
+    p3->view_xmin = vxmin;
+    p3->view_ymin = vymin;
+    p3->view_xmax = vxmax;
+    p3->view_ymax = vymax;
+    p3->width = (vxmax - vxmin);
+    p3->height = (vymax - vymin);
+    p3->aspect = (double) p3->width/(double) p3->height;
+
+    /* Fix up the viewing transformation matrix */
+
+    if (p3->pers_mode == PERSPECTIVE) {
+      Plot3D_lookat(p3,p3->lookatz);
+      Plot3D_perspective(p3,p3->fovy,p3->znear,p3->zfar);
+    } else {
+      Plot3D_ortho(p3,p3->ortho_left,p3->ortho_right,p3->ortho_bottom, p3->ortho_top);
+    }
+    FrameBuffer_setclip(p3->frame,vxmin,vymin,vxmax,vymax);
+  }
+}
+
+/* ---------------------------------------------------------------------------
+   Plot2D_start(Plot2D *p3)
+
+   Set up viewing region and other parameters for this image.
+   --------------------------------------------------------------------------- */
+
+void
+Plot3D_start(Plot3D *p3) {
+  if (p3)
+    FrameBuffer_setclip(p3->frame, p3->view_xmin,p3->view_ymin,p3->view_xmax, p3->view_ymax);
+
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel Color)
+
+   Plot a 3D point
+   ------------------------------------------------------------------------- */
+   
+void
+Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel color) { 
+
+  GL_Vector t;
+  int      ix, iy;
+  double   invw;
+  FrameBuffer *f;
+  
+  /* Perform a transformation */
+
+  Matrix_transform4(p3->trans_mat,x,y,z,1,&t);
+
+  /* Scale the coordinates into unit cube */
+  
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+#ifdef GL_DEBUG
+  fprintf(stdout,"t.x = %g,   t.y = %g,    t.z = %g\n", t.x,t.y,t.z);
+#endif
+  /* Calculate the x and y coordinates */
+
+  ix = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5); 
+  iy = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5); 
+
+  if ((ix >= 0) && (ix < p3->width) &&
+      (iy >= 0) && (ix < p3->height)) {
+    ix += p3->view_xmin;
+    iy += p3->view_ymin;
+    f = p3->frame;
+    if (t.z <= f->zbuffer[iy][ix]) {
+      f->pixels[iy][ix] = color;
+      f->zbuffer[iy][ix] = t.z;
+    }
+  }
+}
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotx(Plot3D *p3, double deg)
+
+   Rotate the model around its x axis.
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotx(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatex(temp,deg);         /* Construct a x rotation matrix */
+  Matrix_multiply(p3->model_mat,temp,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+
+/* ----------------------------------------------------------------------
+   Plot3D_roty(Plot3D *p3, double deg)
+
+   Rotate the model around its y axis.
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_roty(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatey(temp,deg);         /* Construct a y rotation matrix */
+  Matrix_multiply(p3->model_mat,temp,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotz(Plot3D *p3, double deg)
+
+   Rotate the model around its z axis.
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotz(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatez(temp,deg);         /* Construct a z rotation matrix */
+  Matrix_multiply(p3->model_mat,temp,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotd(Plot3D *p3, double deg)
+
+   Rotate the model down
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotd(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatex(temp,deg);         /* Construct a x rotation matrix */
+  Matrix_multiply(temp, p3->model_mat,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+    
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotu(Plot3D *p3, double deg)
+
+   Rotate the model up
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotu(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatex(temp,-deg);         /* Construct a x rotation matrix */
+  Matrix_multiply(temp,p3->model_mat,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotr(Plot3D *p3, double deg)
+
+   Rotate the model down
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotr(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatey(temp,deg);         /* Construct a y rotation matrix */
+  Matrix_multiply(temp, p3->model_mat,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+    
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotl(Plot3D *p3, double deg)
+
+   Rotate the model left
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotl(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatey(temp,-deg);         /* Construct a y rotation matrix */
+  Matrix_multiply(temp,p3->model_mat,p3->model_mat);
+  Plot3D_maketransform(p3);
+
+}
+
+
+/* ----------------------------------------------------------------------
+   Plot3D_rotc(Plot3D *p3, double deg)
+
+   Rotate the model around center point
+   ---------------------------------------------------------------------- */
+
+void
+Plot3D_rotc(Plot3D *p3, double deg) {
+  double temp[16];
+
+  Matrix_rotatez(temp,-deg);         /* Construct a z rotation matrix */
+  Matrix_multiply(temp,p3->model_mat,p3->model_mat);
+  Plot3D_maketransform(p3);
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_zoom(Plot3D *p3, double percent)
+
+   Zooms in or out the current image.   percent defines a percentage of
+   zoom.
+
+   Zooming is actually done by adjusting the perspective field of view
+   instead of scaling the model or moving in the viewpoint.    This
+   seems to work the best.
+   ------------------------------------------------------------------------- */
+
+void
+Plot3D_zoom(Plot3D *p3, double percent) {
+
+  double scale;
+  double dx;
+  if (percent <= 0) return;
+  scale = percent/100.0;
+
+  dx = (1.0/scale - 1.0)/(2*p3->zoom); /* Don't even ask where this came from */
+  p3->xshift += dx;
+  p3->yshift += dx;
+  p3->zoom = p3->zoom*scale;
+
+#ifdef OLD
+  p3->fovy = p3->fovy*scale;
+  if (p3->fovy > 170.0) p3->fovy = 170.0;
+  if (p3->fovy == 0) p3->fovy = 0.0001;
+  Plot3D_lookat(p3,p3->lookatz);
+  Plot3D_perspective(p3,p3->fovy,p3->znear,p3->zfar);
+#endif
+}
+
+/* --------------------------------------------------------------------------
+   Plot3D_left(Plot3D *p3, double s)
+
+   Shifts the image to the left by s units.   This is a little funky.
+
+   s is scaled so that s = 100 equals one full screen.
+   -------------------------------------------------------------------------- */
+void
+Plot3D_left(Plot3D *p3, double s) {
+  p3->xshift -= (s/100.0)/p3->zoom;
+}
+
+/* --------------------------------------------------------------------------
+   Plot3D_right(Plot3D *p3, double s)
+
+   Shifts the image to the right by s units. 
+
+   s is scaled so that s = 100 equals one full screen.
+   -------------------------------------------------------------------------- */
+void
+Plot3D_right(Plot3D *p3, double s) {
+  p3->xshift += (s/100.0)/p3->zoom;
+}
+
+/* --------------------------------------------------------------------------
+   Plot3D_up(Plot3D *p3, double s)
+
+   Shifts the image up left by s units.
+
+   s is scaled so that s = 100 equals one full screen.
+   -------------------------------------------------------------------------- */
+void
+Plot3D_up(Plot3D *p3, double s) {
+  p3->yshift += (s/100.0)/p3->zoom;
+}
+
+/* --------------------------------------------------------------------------
+   Plot3D_down(Plot3D *p3, double s)
+
+   Shifts the image down by s units.  
+
+   s is scaled so that s = 100 equals one full screen.
+   -------------------------------------------------------------------------- */
+void
+Plot3D_down(Plot3D *p3, double s) {
+  p3->yshift -= (s/100.0)/p3->zoom;
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_center(Plot3D *p3, double cx, double cy)
+
+   Centers the image on a point in the range (0,0) - (100,100)
+   ------------------------------------------------------------------------- */
+void
+Plot3D_center(Plot3D *p3, double cx, double cy) {
+  Plot3D_left(p3,cx-50);
+  Plot3D_down(p3,cy-50);
+}
+
+
+
+/***************************************************************************
+ *                       3d Primitives                                     *
+ ***************************************************************************/
+
+/* -------------------------------------------------------------------------
+   Plot3D_horizontal(Plot3D *p3, int xmin, int xmax, int y, double z1, double z2, Pixel color)
+
+   Draws a "Horizontal" line on the framebuffer between two screen coordinates,
+   but also supplies z-values and zbuffering.   This function probably isn't
+   too useful by itself, but will be used by a number of other primitives.
+   -------------------------------------------------------------------------- */
+
+void Plot3D_horizontal(Plot3D *p3, int xmin, int xmax, int y, Zvalue z1, Zvalue z2, Pixel color) {
+  Pixel  *p;
+  FrameBuffer *f;
+  int     i;
+  Zvalue  *zbuf,z,mz;
+  int     startx, endx;
+
+  f = p3->frame;
+  if ((y < f->ymin) || (y >= f->ymax)) return;
+  if (xmin > f->xmax) return;
+  if (xmin < f->xmin) startx = f->xmin;
+  else startx = xmin;
+  if (xmax < f->xmin) return;
+  if (xmax >= f->xmax) endx = f->xmax - 1;
+  else endx = xmax;
+
+  /* Calculate z slope */
+
+  if (xmax != xmin) {
+    mz = (Zvalue) ((double) (z2 - z1)/(double) (xmax - xmin));
+  } else {
+    mz = 0;
+  }
+
+  /* Draw it */
+  
+  p = &f->pixels[y][startx];
+  zbuf = &f->zbuffer[y][startx];
+  z = (Zvalue) (mz*(startx-xmin) + z1);
+  for (i = startx; i <= endx; i++, p++, zbuf++,z+=mz) {
+    if (z <= *zbuf) {
+      *p = color;
+      *zbuf = z;
+    }
+  }
+}
+
+
+/* -------------------------------------------------------------------------
+   Plot3D_vertical(Plot3D *p3, int ymin, int ymax, int x, double z1, double z2, Pixel color)
+
+   Draws a "Vertical" line on the framebuffer between two screen coordinates,
+   but also supplies z-values and zbuffering.   This function probably isn't
+   too useful by itself, but will be used by a number of other primitives.
+   -------------------------------------------------------------------------- */
+
+void Plot3D_vertical(Plot3D *p3, int ymin, int ymax, int x, Zvalue z1, Zvalue z2, Pixel color) {
+  Pixel  *p;
+  FrameBuffer *f;
+  int     i;
+  Zvalue  *zbuf,z,mz;
+  int     starty, endy;
+
+  f = p3->frame;
+  if ((x < f->xmin) || (x >= f->xmax)) return;
+  if (ymin >= f->ymax) return;
+  if (ymin < f->ymin) starty = f->ymin;
+  else starty = ymin;
+  if (ymax < f->ymin) return;
+  if (ymax >= f->ymax) endy = f->ymax - 1;
+  else endy = ymax;
+
+  /* Calculate z slope */
+
+  mz = (double) (z2 - z1)/(double) (ymax - ymin);
+
+  /* Draw it */
+  
+  p = &f->pixels[starty][x];
+  zbuf = &f->zbuffer[starty][x];
+  for (i = starty; i <= endy; i++, p+=f->width, zbuf+=f->width) {
+    z = (Zvalue) (mz*(i-ymin) + z1);
+    if (z <= *zbuf) {
+      *p = color;
+      *zbuf = z;
+    }
+  }
+}
+
+/* -------------------------------------------------------------------------------
+   Plot3D_linetransform(Plot3D *p3, int x1, int y1, Zvalue z1,
+                                    int x2, int y2, Zvalue z2, Pixel c)
+
+   Draw a 3D line between points that have already been transformed into
+   3D space.
+
+   Uses a Bresenham line algorithm, but with linear interpolation between
+   Zvalues.
+   ------------------------------------------------------------------------------- */
+   
+void
+Plot3D_linetransform(Plot3D *p3, int x1, int y1, Zvalue z1, int x2, int y2, Zvalue z2, Pixel c) {
+
+  int       orig_x1, orig_y1, orig_x2,orig_y2;
+  Zvalue    zt;
+  
+  /* Bresenham line drawing parameters */
+  FrameBuffer *f;
+  int  dx,dy,dxneg,dyneg, inc1,inc2,di;
+  int  x, y, xpixels, ypixels, xt, yt;
+  Pixel *p;
+  double m;
+  int  end1 = 0, end2 = 0;
+  Zvalue  *zbuf,mz,z;
+
+  f = p3->frame;
+    
+  /* Need to figure out where in the heck this line is */
+
+  dx = x2 - x1;
+  dy = y2 - y1;
+
+  if ((dx == 0) && (dy == 0)) {
+    if ((x1 < f->xmin) || (x1 >= f->xmax) ||
+	(y1 < f->ymin) || (y1 >= f->ymax)) return;
+    if (z1 <= f->zbuffer[y1][x1]) {
+      f->pixels[y1][x1] = c;
+    }
+    return;
+  }
+  if (dx == 0) {
+    /* Draw a Vertical Line */
+    if (y1 < y2)
+      Plot3D_vertical(p3,y1,y2,x1,z1,z2,c);
+    else
+      Plot3D_vertical(p3,y2,y1,x1,z2,z1,c);
+    return;
+  }
+  if (dy == 0) {
+    /* Draw a Horizontal Line */
+    if (x1 < x2)
+      Plot3D_horizontal(p3,x1,x2,y1,z1,z2,c);
+    else
+      Plot3D_horizontal(p3,x2,x1,y1,z2,z1,c);
+    return;
+  }
+
+  /* Figure out where in the heck these lines are using the
+     Cohen-Sutherland Line Clipping Scheme. */
+
+  end1 = ((x1 - f->xmin) < 0) |
+    (((f->xmax- 1 - x1) < 0) << 1) |
+    (((y1 - f->ymin) < 0) << 2) |
+    (((f->ymax-1 - y1) < 0) << 3);
+
+  end2 = ((x2 - f->xmin) < 0) |
+    (((f->xmax-1 - x2) < 0) << 1) |
+    (((y2 - f->ymin) < 0) << 2) |
+    (((f->ymax-1 - y2) < 0) << 3);
+
+  if (end1 & end2) return;      /* Nope : Not visible */
+  
+  /* Make sure points have a favorable orientation */
+  
+  if (x1 > x2) {
+    xt = x1;
+    x1 = x2;
+    x2 = xt;
+    yt = y1;
+    y1 = y2;
+    y2 = yt;
+    zt = z1;
+    z1 = z2;
+    z2 = zt;
+  }
+
+  /* Save original points before we clip them off */
+  orig_x1 = x1;
+  orig_y1 = y1;
+  orig_x2 = x2;
+  orig_y2 = y2;
+  
+  /* Clip against the boundaries */
+  m = (y2 - y1)/(double) (x2-x1);
+  if (x1 < f->xmin) {
+    y1 = (f->xmin - x1)*m + y1;
+    x1 = f->xmin;
+  }
+  if (x2 >= f->xmax) {
+    y2 = (f->xmax -1 -x1)*m + y1;
+    x2 = f->xmax - 1;
+  }
+
+  if (y1 > y2) {
+    xt = x1;
+    x1 = x2;
+    x2 = xt;
+    yt = y1;
+    y1 = y2;
+    y2 = yt;
+    zt = z1;
+    z1 = z2;
+    z2 = zt;
+
+    /* Swap original points */
+
+    xt = orig_x1;
+    orig_x1 = orig_x2;
+    orig_x2 = xt;
+    yt = orig_y1;
+    orig_y1 = orig_y2;
+    orig_y2 = yt;
+  }
+
+  m = 1/m;
+  if (y1 < f->ymin) {
+    x1 = (f->ymin - y1)*m + x1;
+    y1 = f->ymin;
+  }
+  if (y2 >= f->ymax) {
+    x2 = (f->ymax-1-y1)*m + x1;
+    y2 = f->ymax-1;
+  }
+
+  if ((x1 < f->xmin) || (x1 >= f->xmax) || (y1 < f->ymin) || (y1 >= f->ymax) ||
+      (x2 < f->xmin) || (x2 >= f->xmax) || (y2 < f->ymin) || (y2 >= f->ymax)) return;
+
+  dx = x2 - x1;
+  dy = y2 - y1;
+  xpixels = f->width;
+  ypixels = f->height;
+  
+  dxneg = (dx < 0) ? 1 : 0;
+  dyneg = (dy < 0) ? 1 : 0;
+  
+  dx = abs(dx);
+  dy = abs(dy);
+  if (dx >= dy) {
+    /* Slope between -1 and 1. */
+    mz = (z2 - z1)/(orig_x2 - orig_x1);    /* Z interpolation slope */
+    if (dxneg) {
+      x = x1;
+      y = y1;
+      x1 = x2;
+      y1 = y2;
+      x2 = x;
+      y2 = y;
+      dyneg = !dyneg;
+    }
+    inc1 = 2*dy;
+    inc2 = 2*(dy-dx);
+    di = 2*dy-dx;
+
+    /* Draw a line using x as independent variable */
+    
+    p = &f->pixels[y1][x1];
+    zbuf = &f->zbuffer[y1][x1];
+    x = x1;
+    while (x <= x2) {
+      /* Do a z-buffer check */
+      z = mz*(x-orig_x1)+z1;
+      if (z <= *zbuf){
+	*p = c;
+	*zbuf = z;
+      }
+      p++;
+      zbuf++;
+      if (di < 0) {
+	di = di + inc1;
+      } else {
+	if (dyneg) {
+	  p = p - xpixels;
+	  zbuf = zbuf - xpixels;
+	  di = di + inc2;
+	} else {
+	  p = p + xpixels;
+	  zbuf = zbuf + xpixels;
+	  di = di + inc2;
+	}
+      }
+      x++;
+    }
+  } else {
+    /* Slope < -1 or > 1 */
+    mz = (z2 - z1)/(double) (orig_y2 - orig_y1);
+    if (dyneg) {
+      x = x1;
+      y = y1;
+      x1 = x2;
+      y1 = y2;
+      x2 = x;
+      y2 = y;
+      dxneg = !dxneg;
+    }
+    inc1 = 2*dx;
+    inc2 = 2*(dx-dy);
+    di = 2*dx-dy;
+
+    /* Draw a line using y as independent variable */
+    
+    p = &f->pixels[y1][x1];
+    zbuf = &f->zbuffer[y1][x1];
+    y = y1;
+    while (y <= y2) {
+      /* Do a z-buffer check */
+      z = mz*(y-orig_y1)+z1;
+      if (z <= *zbuf) {
+	*p = c;
+	*zbuf = z;
+      }
+      p = p + xpixels;
+      zbuf = zbuf + xpixels;
+      if (di < 0) {
+	di = di + inc1;
+      } else {
+	if (dxneg) {
+	  p = p - 1;
+	  zbuf = zbuf - 1;
+	  di = di + inc2;
+	} else {
+	  p = p + 1;
+	  zbuf = zbuf + 1;
+	  di = di + inc2;
+	}
+      }
+      y++;
+    }
+  }    
+}
+
+/* ---------------------------------------------------------------------------
+   Plot3D_line(Plot3D *p3, double x1, double y1, double z1, double x2, double y2, double z2,int color)
+
+   Draws a line in 3D space.   This is done as follows (for lack of a better
+   method).
+
+   1.  The points (x1,y1,z1) and (x2,y2,z2) are transformed into screen coordinates
+   2.  We draw the line using a modified Bresenham line algorithm.
+   3.  Zbuffer values are linearly interpolated between the two points.
+   ---------------------------------------------------------------------------- */
+
+void
+Plot3D_line(Plot3D *p3, double fx1, double fy1, double fz1, double fx2, double fy2,
+	    double fz2, Pixel c) {
+
+  /* 3D Transformation parameters */
+  GL_Vector t;
+  double    invw;
+  int       x1,y1,x2,y2;
+  Zvalue    z1,z2;
+  
+  /* Transform the two points into screen coordinates */
+  
+  Matrix_transform4(p3->trans_mat,fx1,fy1,fz1,1,&t);  /* Point 1 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  x1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  y1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  z1 = t.z;
+  
+  Matrix_transform4(p3->trans_mat,fx2,fy2,fz2,1,&t);  /* Point 2 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  x2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  y2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  z2 = t.z;
+  Plot3D_linetransform(p3,x1,y1,z1,x2,y2,z2,c);
+}
+
+
+/* -------------------------------------------------------------------------
+   Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1,
+                               double x2, double y2, double z2,
+			       double x3, double y3, double z3,
+			       Pixel fillcolor)
+
+   This function draws a 3D z-buffered outline triangle.
+   -------------------------------------------------------------------------- */
+
+void Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1,
+		     double x2, double y2, double z2,
+		     double x3, double y3, double z3, Pixel color) {
+
+  int        tx1, tx2, tx3, ty1, ty2, ty3;
+  Zvalue     tz1, tz2, tz3;
+  GL_Vector  t;
+  double     invw;
+  
+  /* Transform the three points into screen coordinates */
+
+  Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t);  /* Point 1 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz1 = (Zvalue) t.z;
+  
+  Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t);  /* Point 2 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz2 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz3 = (Zvalue) t.z;
+
+
+  Plot3D_linetransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,color);
+  Plot3D_linetransform(p3,tx1,ty1,tz1,tx3,ty3,tz3,color);
+  Plot3D_linetransform(p3,tx2,ty2,tz2,tx3,ty3,tz3,color);
+}
+
+
+/* -------------------------------------------------------------------------
+   Plot3D_solidtriangletransform(Plot3D *p3, int tx1, int ty2, Zvalue tz1,
+                                 int tx2, int ty2, Zvalue tz2,
+				 int tx3, int ty3, Zvalue tz3, Pixel color) 
+
+   This function draws a 3D z-buffered filled triangle.   Assumes three
+   points have already been transformed into screen coordinates.
+
+   General idea :
+         1.   Transform the three points into screen coordinates
+	 2.   Order three points vertically on screen.
+	 3.   Check for degenerate cases (where 3 points are colinear).
+	 4.   Fill in the resulting triangle using horizontal lines.
+   -------------------------------------------------------------------------- */
+
+void Plot3D_solidtriangletransform(Plot3D *p3, int tx1, int ty1, Zvalue tz1,
+				   int tx2, int ty2, Zvalue tz2,
+				   int tx3, int ty3, Zvalue tz3, Pixel color) {
+  int        tempx, tempy;
+  Zvalue     tempz;
+  double     m1,m2,m3, mz1, mz2, mz3;
+  int        y;
+  int        ix1, ix2;
+  Zvalue     zz1, zz2;
+  FrameBuffer *f;
+  register   double fy1,fy2;
+  register   Zvalue fz1,fz2;
+
+  f = p3->frame;
+
+  /* Check for degenerate cases here */
+
+  if ((ty1 == ty2) && (ty2 == ty3)) {
+    if (tx2 < tx1) {   /* Swap points 1 and 2 if 2 is higher */
+      tempx = tx1;
+      tempz = tz1;
+      tx1 = tx2;
+      tz1 = tz2;
+      tx2 = tempx;
+      tz2 = tempz;
+    }
+    if (tx3 < tx1) {  /* Swap points 1 and 3 if 3 is higher */
+      tempx = tx1;
+      tempz = tz1;
+      tx1 = tx3;
+      tz1 = tz3;
+      tx3 = tempx;
+      tz3 = tempz;
+    }
+    if (tx3 < tx2) { /* Swap points 2 and 3 if 3 is higher */ 
+      tempx = tx2;
+      tempz = tz2;
+      tx2 = tx3;
+      tz2 = tz3;
+      tx3 = tempx;
+      tz3 = tempz;
+    }
+
+    /* Points are aligned horizontally.   Handle as a special case */
+    /* Just draw three lines using the outline color */
+
+    Plot3D_horizontal(p3,tx1,tx2,ty1,tz1,tz3,color);
+
+    /*    Plot3D_linetransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,color);
+    Plot3D_linetransform(p3,tx1,ty1,tz1,tx3,ty3,tz3,color);
+    Plot3D_linetransform(p3,tx2,ty2,tz2,tx3,ty3,tz3,color);
+    */
+
+    return;
+  }
+
+  /* Figure out which point has the greatest "y" value */
+
+  if (ty2 > ty1) {   /* Swap points 1 and 2 if 2 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tempz = tz1;
+    tx1 = tx2;
+    ty1 = ty2;
+    tz1 = tz2;
+    tx2 = tempx;
+    ty2 = tempy;
+    tz2 = tempz;
+  }
+  if (ty3 > ty1) {  /* Swap points 1 and 3 if 3 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tempz = tz1;
+    tx1 = tx3;
+    ty1 = ty3;
+    tz1 = tz3;
+    tx3 = tempx;
+    ty3 = tempy;
+    tz3 = tempz;
+  }
+  if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ 
+    tempx = tx2;
+    tempy = ty2;
+    tempz = tz2;
+    tx2 = tx3;
+    ty2 = ty3;
+    tz2 = tz3;
+    tx3 = tempx;
+    ty3 = tempy;
+    tz3 = tempz;
+  }
+
+  /* Points are now order so that t_1 is the highest point, t_2 is the
+     middle point, and t_3 is the lowest point */
+
+    if (ty2 < ty1) {
+      /* First process line segments between (x1,y1)-(x2,y2)
+	 And between (x1,y1),(x3,y3) */
+
+      m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1);
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      mz1 = (tz2 - tz1)/(double) (ty2 - ty1);
+      mz2 = (tz3 - tz1)/(double) (ty3 - ty1);
+
+      y = ty1;
+      fy1 = m1*(y-ty1)+0.5 + tx1;
+      fy2 = m2*(y-ty1)+0.5 + tx1;
+      fz1 = mz1*(y-ty1) + tz1;
+      fz2 = mz2*(y-ty1) + tz1;
+      while (y >= ty2) {
+	/* Replace with bresenham scheme */
+	/* Calculate x values from slope */
+	ix1 = (int) fy1;
+	ix2 = (int) fy2;
+	zz1 = fz1;
+	zz2 = fz2;
+	fy1-= m1;
+	fy2-= m2;
+	fz1-= mz1;
+	fz2-= mz2;
+	if (ix1 > ix2) 
+	  Plot3D_horizontal(p3,ix2,ix1,y,zz2,zz1,color);
+	else
+	  Plot3D_horizontal(p3,ix1,ix2,y,zz1,zz2,color);
+	y--;
+      }
+    }
+    if (ty3 < ty2) {
+      /* Draw lower half of the triangle */
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2);
+      mz2 = (tz3 - tz1)/(double) (ty3 - ty1);
+      mz3 = (tz3 - tz2)/(double) (ty3 - ty2);
+      y = ty2;
+      while (y >= ty3) {
+	ix1 = (int) (m3*(y-ty2)+0.5)+tx2;
+	ix2 = (int) (m2*(y-ty1)+0.5)+tx1;
+	zz1 = mz3*(y-ty2)+tz2;
+	zz2 = mz2*(y-ty1)+tz1;
+	if (ix1 > ix2)
+	  Plot3D_horizontal(p3,ix2,ix1,y,zz2,zz1,color);
+	else
+	  Plot3D_horizontal(p3,ix1,ix2,y,zz1,zz2,color);
+	y--;
+      }
+    }
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1,
+                               double x2, double y2, double z2,
+			       double x3, double y3, double z3,
+			       Pixel color)
+
+   This function draws a 3D z-buffered filled triangle.    Can be used to
+   draw other primitives such as quadralaterals, etc...
+
+   This function simply transforms the given points and calls
+   Plot3D_SolidTriangleTransform().
+   -------------------------------------------------------------------------- */
+
+void Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1,
+			  double x2, double y2, double z2,
+			  double x3, double y3, double z3, Pixel color) {
+
+  int        tx1, tx2, tx3, ty1, ty2, ty3;
+  Zvalue     tz1, tz2, tz3;
+  GL_Vector  t;
+  double     invw;
+  Matrix     a;
+  register double     xshift, yshift, zoom, width, height, view_xmin, view_ymin;
+
+  a = p3->trans_mat;
+  xshift = p3->xshift;
+  yshift = p3->yshift;
+  zoom = p3->zoom;
+  height = p3->height;
+  width = p3->width;
+  view_xmin = p3->view_xmin;
+  view_ymin = p3->view_ymin;
+
+  /* Transform the three points into screen coordinates */
+
+  t.w = a[12]*x1 + a[13]*y1 + a[14]*z1 + a[15];
+  invw = 1.0/t.w;
+  t.x = (a[0]*x1 + a[1]*y1 + a[2]*z1 + a[3])*invw;
+  t.y = (a[4]*x1 + a[5]*y1 + a[6]*z1 + a[7])*invw;
+  t.z = (a[8]*x1 + a[9]*y1 + a[10]*z1 + a[11])*invw;
+
+  tx1 = (int) ((t.x +xshift)*zoom*width + 0.5) + view_xmin; 
+  ty1 = (int) ((t.y +yshift)*zoom*height + 0.5) + view_ymin;
+  tz1 = (Zvalue) t.z;
+
+
+  t.w = a[12]*x2 + a[13]*y2 + a[14]*z2 + a[15];
+  invw = 1.0/t.w;
+  t.x = (a[0]*x2 + a[1]*y2 + a[2]*z2 + a[3])*invw;
+  t.y = (a[4]*x2 + a[5]*y2 + a[6]*z2 + a[7])*invw;
+  t.z = (a[8]*x2 + a[9]*y2 + a[10]*z2 + a[11])*invw;
+  tx2 = (int) ((t.x +xshift)*zoom*width + 0.5) + view_xmin; 
+  ty2 = (int) ((t.y +yshift)*zoom*height + 0.5) + view_ymin;
+  tz2 = (Zvalue) t.z;
+
+  t.w = a[12]*x3 + a[13]*y3 + a[14]*z3 + a[15];
+  invw = 1.0/t.w;
+  t.x = (a[0]*x3 + a[1]*y3 + a[2]*z3 + a[3])*invw;
+  t.y = (a[4]*x3 + a[5]*y3 + a[6]*z3 + a[7])*invw;
+  t.z = (a[8]*x3 + a[9]*y3 + a[10]*z3 + a[11])*invw;
+  tx3 = (int) ((t.x +xshift)*zoom*width + 0.5) + view_xmin; 
+  ty3 = (int) ((t.y +yshift)*zoom*height + 0.5) + view_ymin;
+  tz3 = (Zvalue) t.z;
+
+  Plot3D_solidtriangletransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,tx3,ty3,tz3,color); 
+  
+}    
+
+
+/* -------------------------------------------------------------------------
+   Plot3D_horizontalinterp(Plot3D *p3, int xmin, int xmax, int y,
+                           double z1, double z2, Pixel c1, Pixel c2)
+
+   Draws a "Horizontal" line on the framebuffer between two screen coordinates,
+   but also supplies z-values and zbuffering.  Performs a color interpolation
+   between c1 and c2.  This is primarily used by the SolidTriangleInterp()
+   function to give the illusion of smooth surfaces.
+   -------------------------------------------------------------------------- */
+
+void Plot3D_horizontalinterp(Plot3D *p3, int xmin, int xmax, int y,
+			     Zvalue z1, Zvalue z2, Pixel c1, Pixel c2) {
+  Pixel  *p;
+  FrameBuffer *f;
+  int     i;
+  Zvalue  *zbuf,z,mz;
+  double   mc;
+  int     startx, endx;
+  double   invdx;
+  
+  f = p3->frame;
+  if ((y < f->ymin) || (y >= f->ymax)) return;
+  if (xmin >= f->xmax) return;
+  if (xmin < f->xmin) startx = f->xmin;
+  else startx = xmin;
+  if (xmax < f->xmin) return;
+  if (xmax >= f->xmax) endx = f->xmax - 1;
+  else endx = xmax;
+
+  /* Calculate z slope */
+  if (xmax != xmin) {
+    invdx = 1.0/(double) (xmax-xmin);
+  } else {
+    invdx = 0;
+  }
+
+  mz = (Zvalue) (z2 - z1)*invdx;
+
+  /* Calculate c slope */
+
+  mc = (double) (c2 - c1)*invdx;
+    
+  /* Draw it */
+  
+  p = &f->pixels[y][startx];
+  zbuf = &f->zbuffer[y][startx];
+  for (i = startx; i <= endx; i++, p++, zbuf++) {
+    z = (Zvalue) (mz*(i-xmin) + z1);
+    if (z <= *zbuf) {
+      *p = (Pixel) (mc*(i-xmin)+c1);
+      *zbuf = z;
+    }
+  }
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_interptriangletransform(Plot3D *p3,
+                                  int tx1, int ty2, Zvalue tz1, Pixel c1,
+                                  int tx2, int ty2, Zvalue tz2, Pixel c2,
+				  int tx3, int ty3, Zvalue tz3, Pixel c3)
+
+   This function draws a 3D z-buffered filled triangle with color
+   interpolation.   Assumes three points have already been transformed
+   into screen coordinates.
+
+   General idea :
+         1.   Transform the three points into screen coordinates
+	 2.   Order three points vertically on screen.
+	 3.   Check for degenerate cases (where 3 points are colinear).
+	 4.   Fill in the resulting triangle using horizontal lines.
+	 5.   Colors are interpolated between end points
+   -------------------------------------------------------------------------- */
+
+void Plot3D_interptriangletransform(Plot3D *p3,
+				    int tx1, int ty1, Zvalue tz1, Pixel c1,
+				    int tx2, int ty2, Zvalue tz2, Pixel c2,
+				    int tx3, int ty3, Zvalue tz3, Pixel c3) {
+  int        tempx, tempy;
+  Zvalue     tempz;
+  double     m1,m2,m3, mz1, mz2, mz3;
+  double     mc1,mc2,mc3;
+  Pixel      ic1,ic2,tempc;
+  int        y;
+  int        ix1, ix2;
+  Zvalue     zz1, zz2;
+  FrameBuffer *f;
+  
+  f = p3->frame;
+
+  /* Figure out which point has the greatest "y" value */
+
+  if (ty2 > ty1) {   /* Swap points 1 and 2 if 2 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tempz = tz1;
+    tempc = c1;
+    tx1 = tx2;
+    ty1 = ty2;
+    tz1 = tz2;
+    c1 = c2;
+    tx2 = tempx;
+    ty2 = tempy;
+    tz2 = tempz;
+    c2 = tempc;
+  }
+  if (ty3 > ty1) {  /* Swap points 1 and 3 if 3 is higher */
+    tempx = tx1;
+    tempy = ty1;
+    tempz = tz1;
+    tempc = c1;
+    tx1 = tx3;
+    ty1 = ty3;
+    tz1 = tz3;
+    c1 = c3;
+    tx3 = tempx;
+    ty3 = tempy;
+    tz3 = tempz;
+    c3 = tempc;
+  }
+  if (ty3 > ty2) { /* Swap points 2 and 3 if 3 is higher */ 
+    tempx = tx2;
+    tempy = ty2;
+    tempz = tz2;
+    tempc = c2;
+    tx2 = tx3;
+    ty2 = ty3;
+    tz2 = tz3;
+    c2 = c3;
+    tx3 = tempx;
+    ty3 = tempy;
+    tz3 = tempz;
+    c3 = tempc;
+  }
+
+  /* Points are now order so that t_1 is the highest point, t_2 is the
+     middle point, and t_3 is the lowest point */
+
+  /* Check for degenerate cases here */
+
+  if ((ty1 == ty2) && (ty2 == ty3)) {
+
+    /* Points are aligned horizontally.   Handle as a special case */
+    /* Just draw three lines using the outline color */
+
+    if (tx2 > tx1)
+      Plot3D_horizontalinterp(p3,tx1,tx2,ty1,tz1,tz2,c1,c2);
+    else
+      Plot3D_horizontalinterp(p3,tx2,tx1,ty1,tz2,tz1,c2,c1);
+    if (tx3 > tx1)
+      Plot3D_horizontalinterp(p3,tx1,tx3,ty1,tz1,tz3,c1,c3);
+    else
+      Plot3D_horizontalinterp(p3,tx3,tx1,ty1,tz3,tz1,c3,c1);
+    if (tx3 > tx2)
+      Plot3D_horizontalinterp(p3,tx2,tx3,ty2,tz2,tz3,c2,c3);
+    else
+      Plot3D_horizontalinterp(p3,tx3,tx2,ty2,tz3,tz2,c3,c2);
+    
+  } else {
+
+    /* First process line segments between (x1,y1)-(x2,y2)
+       And between (x1,y1),(x3,y3) */
+
+    if (ty2 < ty1) {
+      m1 = (double) (tx2 - tx1)/(double) (ty2 - ty1);
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      mz1 = (tz2 - tz1)/(double) (ty2 - ty1);
+      mz2 = (tz3 - tz1)/(double) (ty3 - ty1);
+      mc1 = (c2 - c1)/(double) (ty2 - ty1);
+      mc2 = (c3 - c1)/(double) (ty3 - ty1);
+
+      y = ty1;
+      while (y >= ty2) {
+	/* Calculate x values from slope */
+	ix1 = (int) (m1*(y-ty1)+0.5) + tx1;
+	ix2 = (int) (m2*(y-ty1)+0.5) + tx1;
+	zz1 = mz1*(y-ty1) + tz1;
+	zz2 = mz2*(y-ty1) + tz1;
+	ic1 = mc1*(y-ty1) + c1;
+	ic2 = mc2*(y-ty1) + c1;
+	if (ix1 > ix2) 
+	  Plot3D_horizontalinterp(p3,ix2,ix1,y,zz2,zz1,ic2,ic1);
+	else
+	  Plot3D_horizontalinterp(p3,ix1,ix2,y,zz1,zz2,ic1,ic2);
+	y--;
+      }
+    }
+    if (ty3 < ty2) {
+      /* Draw lower half of the triangle */
+      m2 = (double) (tx3 - tx1)/(double) (ty3 - ty1);
+      mz2 = (tz3 - tz1)/(double) (ty3 - ty1);
+      mc2 = (c3 - c1)/(double) (ty3 - ty1);
+      m3 = (double) (tx3 - tx2)/(double)(ty3 - ty2);
+      mz3 = (tz3 - tz2)/(double) (ty3 - ty2);
+      mc3 = (c3 - c2)/(double) (ty3 - ty2);
+      y = ty2;
+      while (y >= ty3) {
+	ix1 = (int) (m3*(y-ty2)+0.5)+tx2;
+	ix2 = (int) (m2*(y-ty1)+0.5)+tx1;
+	zz1 = mz3*(y-ty2)+tz2;
+	zz2 = mz2*(y-ty1)+tz1;
+	ic1 = mc3*(y-ty2)+c2;
+	ic2 = mc2*(y-ty1)+c1;
+	if (ix1 > ix2)
+	  Plot3D_horizontalinterp(p3,ix2,ix1,y,zz2,zz1,ic2,ic1);
+	else
+	  Plot3D_horizontalinterp(p3,ix1,ix2,y,zz1,zz2,ic1,ic2);
+	y--;
+      }
+    }
+  }
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_interptriangle(Plot3D *p3,
+                         double x1, double y1, double z1, Pixel c1,
+			 double x2, double y2, double z2, Pixel c2,
+			 double x3, double y3, double z3, Pixel c3)
+
+   This function draws a 3D z-buffered filled triangle with color
+   interpolation.
+
+   This function simply transforms the given points and calls
+   Plot3D_InterpTriangleTransform().
+   -------------------------------------------------------------------------- */
+
+void Plot3D_interptriangle(Plot3D *p3,
+			   double x1, double y1, double z1, Pixel c1,
+			   double x2, double y2, double z2, Pixel c2,
+			   double x3, double y3, double z3, Pixel c3) {
+
+  int        tx1, tx2, tx3, ty1, ty2, ty3;
+  Zvalue     tz1, tz2, tz3;
+  GL_Vector  t;
+  double     invw;
+  
+  /* Transform the three points into screen coordinates */
+
+  Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t);  /* Point 1 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz1 = (Zvalue) t.z;
+  
+  Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t);  /* Point 2 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz2 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz3 = (Zvalue) t.z;
+
+  Plot3D_interptriangletransform(p3,tx1,ty1,tz1,c1,tx2,ty2,tz2,c2,tx3,ty3,tz3,c3);
+}    
+
+/* -------------------------------------------------------------------------
+   Plot3D_quad(Plot3D *p3, double x1, double y1, double z1,
+                           double x2, double y2, double z2,
+    		           double x3, double y3, double z3,
+			   double x4, double y4, double z4,
+ 		           Pixel fillcolor)
+
+   This function draws a 3D outlined Quadralateral.  Used primarily for
+   drawing meshes and other things.
+
+   Plotting is done in the following order :
+       (x1,y1,z1)  --> (x2,y2,z2)
+       (x2,y2,z2)  --> (x3,y3,z3)
+       (x3,y3,z3)  --> (x4,y4,z4)
+       (x4,y4,z4)  --> (x1,y1,z1)
+   -------------------------------------------------------------------------- */
+
+void Plot3D_quad(Plot3D *p3, double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color) {
+
+  int        tx1, tx2, tx3, tx4, ty1, ty2, ty3, ty4;
+  Zvalue     tz1, tz2, tz3, tz4;
+  GL_Vector  t;
+  double     invw;
+  
+  /* Transform the three points into screen coordinates */
+
+  Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t);  /* Point 1 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz1 = (Zvalue) t.z;
+  
+  Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t);  /* Point 2 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz2 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz3 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x4,y4,z4,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx4 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty4 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz4 = (Zvalue) t.z;
+
+  Plot3D_linetransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,color);
+  Plot3D_linetransform(p3,tx2,ty2,tz2,tx3,ty3,tz3,color);
+  Plot3D_linetransform(p3,tx3,ty3,tz3,tx4,ty4,tz4,color);
+  Plot3D_linetransform(p3,tx4,ty4,tz4,tx1,ty1,tz1,color);
+  
+}
+
+
+/* -------------------------------------------------------------------------
+   Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1,
+                           double x2, double y2, double z2,
+    		           double x3, double y3, double z3,
+			   double x4, double y4, double z4,
+ 		           Pixel fillcolor)
+
+   This function draws a 3D solid Quadralateral. Uses the function
+   Plot3D_SolidTriangleTransform() to fill in the region.
+
+   Plotting is done in the following order :
+       (x1,y1,z1)  --> (x2,y2,z2)
+       (x2,y2,z2)  --> (x3,y3,z3)
+       (x3,y3,z3)  --> (x4,y4,z4)
+       (x4,y4,z4)  --> (x1,y1,z1)
+   -------------------------------------------------------------------------- */
+
+void Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color) {
+
+  int        tx1, tx2, tx3, tx4, ty1, ty2, ty3, ty4;
+  Zvalue     tz1, tz2, tz3, tz4;
+  GL_Vector  t;
+  double     invw;
+  
+  /* Transform the three points into screen coordinates */
+
+  Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t);  /* Point 1 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz1 = (Zvalue) t.z;
+  
+  Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t);  /* Point 2 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz2 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz3 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x4,y4,z4,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx4 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty4 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz4 = (Zvalue) t.z;
+
+  Plot3D_solidtriangletransform(p3,tx1,ty1,tz1,tx2,ty2,tz2,tx3,ty3,tz3,color);
+  Plot3D_solidtriangletransform(p3,tx1,ty1,tz1,tx4,ty4,tz4,tx3,ty3,tz3,color);
+}
+
+/* -------------------------------------------------------------------------
+   Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1,
+                           double x2, double y2, double z2, Pixel c2,
+    		           double x3, double y3, double z3, Pixel c3,
+			   double x4, double y4, double z4, Pixel c4)
+
+   This function draws a 3D color-interpolated Quadralateral. Uses the function
+   Plot3D_InterpTriangleTransform() to fill in the region.
+
+   Plotting is done in the following order :
+       (x1,y1,z1)  --> (x2,y2,z2)
+       (x2,y2,z2)  --> (x3,y3,z3)
+       (x3,y3,z3)  --> (x4,y4,z4)
+       (x4,y4,z4)  --> (x1,y1,z1)
+   -------------------------------------------------------------------------- */
+
+void Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1,
+		       double x2, double y2, double z2, Pixel c2,
+		       double x3, double y3, double z3, Pixel c3,
+		       double x4, double y4, double z4, Pixel c4) {
+
+
+  int        tx1, tx2, tx3, tx4, ty1, ty2, ty3, ty4;
+  Zvalue     tz1, tz2, tz3, tz4;
+  GL_Vector  t;
+  double     invw;
+  
+  /* Transform the three points into screen coordinates */
+
+  Matrix_transform4(p3->trans_mat,x1,y1,z1,1,&t);  /* Point 1 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx1 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty1 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz1 = (Zvalue) t.z;
+  
+  Matrix_transform4(p3->trans_mat,x2,y2,z2,1,&t);  /* Point 2 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx2 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty2 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz2 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x3,y3,z3,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx3 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty3 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz3 = (Zvalue) t.z;
+
+  Matrix_transform4(p3->trans_mat,x4,y4,z4,1,&t);  /* Point 3 */
+  invw = 1.0/t.w;
+  t.x = t.x *invw;
+  t.y = t.y *invw;
+  t.z = t.z *invw;
+  tx4 = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty4 = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz4 = (Zvalue) t.z;
+
+  Plot3D_interptriangletransform(p3,tx1,ty1,tz1,c1,tx2,ty2,tz2,c2,tx3,ty3,tz3,c3);
+  Plot3D_interptriangletransform(p3,tx1,ty1,tz1,c1,tx4,ty4,tz4,c4,tx3,ty3,tz3,c3);
+  
+}
+
+/* --------------------------------------------------------------------------
+   Plot3D_solidsphere(Plot3 *p3, double x, double y, double z, double radius,
+                      Pixel c)
+
+   Makes a 3D sphere at x,y,z with given radius and color. 
+
+   Basic strategy :
+      1.  Transform point to screen coordinates
+      2.  Figure out what the radius is in screen coordinates
+      3.  Use bresenham algorithm for large spheres
+      4.  Use bitmaps for small spheres
+   -------------------------------------------------------------------------- */
+
+/* This is used to fill in spheres */
+static int s_xmin;
+static int s_ymin;
+static int s_xmax;
+static int s_ymax;
+static Pixel **s_pixels;
+static Zvalue **s_zbuffer;
+
+void Plot3D_spherehorizontal(int xmin, int xmax, int y, Zvalue z, Pixel color) {
+  int     i;
+  int     startx, endx;
+  Pixel   *p;
+  Zvalue  *zbuf;
+  
+  if ((y < s_ymin) || (y >= s_ymax)) return;
+  if (xmin < s_xmin) startx = s_xmin;
+  else startx = xmin;
+  if (xmax >= s_xmax) endx = s_xmax - 1;
+  else endx = xmax;
+
+  /* Draw it */
+  
+  p = &s_pixels[y][xmin];
+  zbuf = &s_zbuffer[y][xmin];
+  for (i = startx; i <= endx; i++, p++, zbuf++) {
+    if (z <= *zbuf) {
+      *p = color;
+      *zbuf = z;
+    }
+  }
+}
+
+void Plot3D_solidsphere(Plot3D *p3, double x, double y, double z, double radius,
+			Pixel c) {
+
+  GL_Vector  t,r;
+  double     rad;
+  int        tx,ty, irad;
+  Zvalue     tz;
+  double     invw;
+  int        ix, iy, ix1,ix2,p;
+  FrameBuffer *f;
+
+  /* First transform the point into model coordinates */
+
+  Matrix_transform4(p3->fullmodel_mat,x,y,z,1,&t);  
+
+  /* Now transform two points in order to find proper sphere radius */
+
+  Matrix_transform4(p3->view_mat,t.x+radius,t.y,t.z,t.w,&r);  /* transform radius */
+  Matrix_transform4(p3->view_mat,t.x,t.y,t.z,t.w,&t);
+
+  invw = 1.0/t.w;
+  t.x = t.x*invw;
+  t.y = t.y*invw;
+  t.z = t.z*invw;
+  invw = 1.0/r.w;
+  r.x = r.x*invw;
+  r.y = r.y*invw;
+  r.z = r.z*invw;
+  invw = 1.0/r.w;
+  
+  rad = fabs(t.x - r.x);
+  
+  /* Transform everything into screen coordinates */
+  
+  tx = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz = (Zvalue) t.z;
+  irad = (int) (p3->zoom*(rad*p3->width + 0.5));
+
+  /* This is only a temporary solution (maybe). */
+         
+#define fill_zcircle(x,y,c) \
+  ix1 = tx - x; \
+  ix2 = tx + x; \
+  if (ix1 < s_xmin) ix1 = s_xmin; \
+  if (ix2 >= s_xmax) ix2 = s_xmax; \
+  Plot3D_spherehorizontal(ix1,ix2,y,tz,c);
+  
+  f = p3->frame;
+  s_xmin = f->xmin;
+  s_ymin = f->ymin;
+  s_xmax = f->xmax;
+  s_ymax = f->ymax;
+  s_pixels = f->pixels;
+  s_zbuffer = f->zbuffer;
+  if (irad <= 1) {
+    /* Plot a single pixel */
+    if ((tx >= f->xmin) && (tx < f->xmax)) {
+      if ((ty >= f->ymin) && (ty <f->ymax)) {
+        if (tz <= f->zbuffer[ty][tx]) {
+	  f->pixels[ty][tx] = c;
+	  f->zbuffer[ty][tx] = tz;
+	}
+      }
+    }
+    return;
+  }
+  ix = 0;
+  iy = irad;
+  p = 3-2*irad;
+  while (ix <= iy) {
+    fill_zcircle(ix,ty+iy,c);
+    fill_zcircle(ix,ty-iy,c);
+    fill_zcircle(iy,ty+ix,c);
+    fill_zcircle(iy,ty-ix,c);
+    if (p < 0) p = p + 4*ix + 6;
+    else {
+      p = p + 4*(ix-iy) + 10;
+      iy = iy -1;
+    }
+    ix++;
+  }
+}
+
+
+/* --------------------------------------------------------------------
+   Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z,
+                        double radius, Pixel color, Pixel bc)
+
+   Draws an outlined sphere.
+   -------------------------------------------------------------------- */
+
+void Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z,
+			  double radius, Pixel c, Pixel bc)
+{
+  GL_Vector  t,r;
+  double     rad;
+  int        tx,ty, irad;
+  Zvalue     tz;
+  double     invw;
+  int        ix, iy, ix1,ix2,p;
+  
+  FrameBuffer *f;
+
+  /* First transform the point into model coordinates */
+
+  Matrix_transform4(p3->fullmodel_mat,x,y,z,1,&t);  
+
+  /* Now transform two points in order to find proper sphere radius */
+
+  Matrix_transform4(p3->view_mat,t.x+radius,t.y,t.z,t.w,&r);  /* transform radius */
+  Matrix_transform4(p3->view_mat,t.x,t.y,t.z,t.w,&t);
+
+  invw = 1.0/t.w;
+  t.x = t.x*invw;
+  t.y = t.y*invw;
+  t.z = t.z*invw;
+  invw = 1.0/r.w;
+  r.x = r.x*invw;
+  r.y = r.y*invw;
+  r.z = r.z*invw;
+  invw = 1.0/r.w;
+  
+  rad = fabs(t.x - r.x);
+  
+  /* Transform everything into screen coordinates */
+  
+  tx = (int) ((t.x +p3->xshift)*p3->zoom*p3->width + 0.5) + p3->view_xmin; 
+  ty = (int) ((t.y +p3->yshift)*p3->zoom*p3->height + 0.5) + p3->view_ymin;
+  tz = (Zvalue) t.z;
+  irad = (int) (p3->zoom*(rad*p3->width + 0.5));
+
+  /* This is only a temporary solution (maybe). */
+#define plot_zcircle(x,y,c) \
+   if ((x >= s_xmin) && (x < s_xmax) && \
+       (y >= s_ymin) && (y < s_ymax)) {\
+         if (tz <= s_zbuffer[y][x]) { \
+             s_pixels[y][x] = c; \
+	     s_zbuffer[y][x] = tz; } \
+   }
+     
+  f = p3->frame;
+  s_xmin = f->xmin;
+  s_ymin = f->ymin;
+  s_xmax = f->xmax;
+  s_ymax = f->ymax;
+  s_pixels = f->pixels;
+  s_zbuffer = f->zbuffer;
+  
+  if (irad <= 1) {
+    /* Plot a single pixel */
+    if ((tx >= f->xmin) && (tx < f->xmax)) {
+      if ((ty >= f->ymin) && (ty <f->ymax)) {
+        if (tz <= f->zbuffer[ty][tx]) {
+	  f->pixels[ty][tx] = c;
+	  f->zbuffer[ty][tx] = tz;
+	}
+      }
+    }
+    return;
+  }
+  ix = 0;
+  iy = irad;
+  p = 3-2*irad;
+  while (ix <= iy) {
+    fill_zcircle(ix,ty+iy,c);
+    fill_zcircle(ix,ty-iy,c);
+    fill_zcircle(iy,ty+ix,c);
+    fill_zcircle(iy,ty-ix,c);
+    
+    plot_zcircle(tx+ix,ty+iy,bc);
+    plot_zcircle(tx-ix,ty+iy,bc);
+    plot_zcircle(tx+ix,ty-iy,bc);
+    plot_zcircle(tx-ix,ty-iy,bc);
+    plot_zcircle(tx+iy,ty+ix,bc);
+    plot_zcircle(tx-iy,ty+ix,bc);
+    plot_zcircle(tx+iy,ty-ix,bc);
+    plot_zcircle(tx-iy,ty-ix,bc);
+    if (p < 0) p = p + 4*ix + 6;
+    else {
+      p = p + 4*(ix-iy) + 10;
+      iy = iy -1;
+    }
+    ix++;
+  }
+}
+
+/* QUAD Test
+   Test out quad functions for graphing */
+
+double zf(double x, double y) {
+  return cos(sqrt(x*x + y*y)*10.0)/(sqrt(x*x+y*y)+1);
+}
+
+void Quad_Test(Plot3D *p3, int npoints) {
+  int i,j;
+  double dx;
+  double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,za;
+  int c;
+  dx = 2.0/npoints;
+
+  
+  for (i = 0; i < npoints; i++)
+    for (j = 0; j < npoints; j++) {
+      x1 = i*dx + -1.0;
+      y1 = j*dx + -1.0;
+      x2 = x1 + dx;
+      x3 = x1 + dx;
+      x4 = x1;
+      y2 = y1;
+      y3 = y1 + dx;
+      y4 = y1 + dx;
+      z1 = zf(x1,y1);
+      z2 = zf(x2,y2);
+      z3 = zf(x3,y3);
+      z4 = zf(x4,y4);
+      za = 0.25*(z1+z2+z3+z4);
+      c = 16+((za + 1)*120);
+      if (c > 254) c = 254;
+      Plot3D_quad(p3,x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,(Pixel) c);
+    }
+}
+
+
+void Quad_SolidTest(Plot3D *p3, int npoints) {
+  int i,j;
+  double dx;
+  double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,za;
+  int c;
+  dx = 2.0/npoints;
+
+  
+  for (i = 0; i < npoints; i++)
+    for (j = 0; j < npoints; j++) {
+      x1 = i*dx + -1.0;
+      y1 = j*dx + -1.0;
+      x2 = x1 + dx;
+      x3 = x1 + dx;
+      x4 = x1;
+      y2 = y1;
+      y3 = y1 + dx;
+      y4 = y1 + dx;
+      z1 = zf(x1,y1);
+      z2 = zf(x2,y2);
+      z3 = zf(x3,y3);
+      z4 = zf(x4,y4);
+      za = 0.25*(z1+z2+z3+z4);
+      c = 16+((za + 1)*120);
+      if (c > 254) c = 254;
+      Plot3D_solidquad(p3,x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4,(Pixel) c);
+    }
+}
+
+
+
+void Quad_InterpTest(Plot3D *p3, int npoints) {
+  int i,j;
+  double dx;
+  double x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4;
+  int c1,c2,c3,c4;
+  dx = 2.0/npoints;
+
+  
+  for (i = 0; i < npoints; i++)
+    for (j = 0; j < npoints; j++) {
+      x1 = i*dx + -1.0;
+      y1 = j*dx + -1.0;
+      x2 = x1 + dx;
+      x3 = x1 + dx;
+      x4 = x1;
+      y2 = y1;
+      y3 = y1 + dx;
+      y4 = y1 + dx;
+      z1 = zf(x1,y1);
+      z2 = zf(x2,y2);
+      z3 = zf(x3,y3);
+      z4 = zf(x4,y4);
+      c1 = 16+((z1 + 1)*120);
+      c2 = 16+((z2 + 1)*120);
+      c3 = 16+((z3 + 1)*120);
+      c4 = 16+((z4 + 1)*120);
+      if (c1 > 254) c1 = 254;
+      if (c2 > 254) c2 = 254;
+      if (c3 > 254) c3 = 254;
+      if (c4 > 254) c4 = 254;
+      Plot3D_interpquad(p3,x1,y1,z1,(Pixel) c1,x2,y2,z2,(Pixel) c2,x3,y3,z3,(Pixel) c3,x4,y4,z4,(Pixel) c4);
+    }
+}
+
+
+
+  
+  
+  
+   
+
+
+  
+  
+  
diff --git a/trunk/Examples/GIFPlot/Makefile.in b/trunk/Examples/GIFPlot/Makefile.in
new file mode 100644
index 0000000..4e51360
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Makefile.in
@@ -0,0 +1,23 @@
+prefix      = @prefix@
+exec_prefix = @exec_prefix@
+RANLIB      = @RANLIB@
+OPT         =
+
+INSTALL        = ../install-sh -c
+INSTALL_DATA   = ${INSTALL} -m 644
+SHELL          = /bin/sh
+
+all:	
+	cd Lib && $(MAKE) OPT="$(OPT)"
+
+install: 
+	$(INSTALL_DATA) Include/gifplot.h $(prefix)/include/gifplot.h
+	$(INSTALL_DATA) libgifplot.a $(exec_prefix)/lib/libgifplot.a
+	$(RANLIB) $(exec_prefix)/lib/libgifplot.a
+
+clean::
+	rm -f *.@OBJEXT@ *~ libgifplot.a *_wrap* *_man*
+	cd Lib && $(MAKE) clean
+	rm -f config.log config.status config.cache
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Ocaml/check.list b/trunk/Examples/GIFPlot/Ocaml/check.list
new file mode 100644
index 0000000..e75ee58
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/check.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+full
+simple
diff --git a/trunk/Examples/GIFPlot/Ocaml/full/Makefile b/trunk/Examples/GIFPlot/Ocaml/full/Makefile
new file mode 100644
index 0000000..4f35c43
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/full/Makefile
@@ -0,0 +1,33 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include
+SRCS       = 
+TARGET     = gifcaml
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+MLFILE     = gifplot.ml
+IOBJS      = runme.cmo
+PROGFILE   = runme.ml
+
+all:: static
+
+static::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_static
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_dynamic
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Ocaml/full/README b/trunk/Examples/GIFPlot/Ocaml/full/README
new file mode 100644
index 0000000..4a2b400
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The ocaml program 'runme.ml' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Ocaml/full/cmap b/trunk/Examples/GIFPlot/Ocaml/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Ocaml/full/gifplot.i b/trunk/Examples/GIFPlot/Ocaml/full/gifplot.i
new file mode 100644
index 0000000..22f4df6
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+%}
+
+typedef int Pixel;
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Ocaml/full/runme.ml b/trunk/Examples/GIFPlot/Ocaml/full/runme.ml
new file mode 100644
index 0000000..0dfa985
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/full/runme.ml
@@ -0,0 +1,87 @@
+(* Plot a 3D Function *)
+
+(* Use the wrapped GIFPlot library *)
+open Swig
+open Gifplot
+open Int32
+
+(* Here is the function to plot *)
+let func x y = 
+  5.0 *. 
+    (cos (2.0 *. (sqrt (x *. x) +. (y *. y)))) *.
+    (exp (-0.3 *. (sqrt (x *. x) +. (y *. y)))) 
+
+(* Here are some plotting parameters *)
+
+let xmin = -5.0
+let xmax =  5.0
+let ymin = -5.0
+let ymax =  5.0
+let zmin = -5.0
+let zmax =  5.0
+
+(* Grid resolution *)
+let nxpoints = 60
+let nypoints = 60
+
+let cmap = _new_ColorMap (C_string "cmap")
+let frame = _new_FrameBuffer (C_list [ C_int 500 ;
+				      C_int 500 ]) 
+let _ = _FrameBuffer_clear (C_list [ frame ; _BLACK C_void ])
+
+let p2 = _new_Plot3D (C_list [ frame ; 
+			       C_float xmin ; C_float ymin ; C_float zmin ; 
+			       C_float xmax ; C_float ymax ; C_float zmax ])
+let _ = _Plot3D_lookat (C_list [ p2 ; C_float (2.0 *. (zmax -. zmin)) ])
+let _ = _Plot3D_autoperspective (C_list [ p2 ; C_float 40.0 ])
+let _ = _Plot3D_rotu (C_list [ p2 ; C_float 60.0 ])
+let _ = _Plot3D_rotr (C_list [ p2 ; C_float 30.0 ])
+let _ = _Plot3D_rotd (C_list [ p2 ; C_float 10.0 ])
+
+let drawsolid () =
+  begin
+    _Plot3D_clear (C_list [ p2 ; _BLACK C_void ]) ;
+    _Plot3D_start p2 ;
+    let dx = ((xmax -. xmin) /. (float_of_int nxpoints))
+    and dy = ((ymax -. ymin) /. (float_of_int nypoints)) 
+    and cscale = (240.0 /. (zmax -. zmin)) in
+    let rec x_loop x i =
+      if i < nxpoints then
+	begin
+	  let rec y_loop y j =
+	    begin
+	      if j < nypoints then
+		let z1 = func x y
+		and z2 = func (x +. dx) y
+		and z3 = func (x +. dx) (y +. dy)
+		and z4 = func x (y +. dy) in
+		let c1 = cscale *. (z1 -. zmin)
+		and c2 = cscale *. (z2 -. zmin)
+		and c3 = cscale *. (z3 -. zmin)
+		and c4 = cscale *. (z4 -. zmin) in
+		let cc = (c1 +. c2 +. c3 +. c4) /. 4.0 in
+		let c =  (max (min (int_of_float cc) 239) 0) in
+		  _Plot3D_solidquad 
+		    (C_list (p2 ::
+			       (List.map 
+				  (fun x -> C_float x)
+				  [ x ; y ; z1 ;
+				    (x +. dx) ; y ; z2 ;
+				    (x +. dx) ; (y +. dy) ; z3 ;
+				    x ; (y +. dx) ; z4 ;
+				    (float_of_int (c + 16)) ]))) ;
+		  y_loop (y +. dy) (j + 1) 
+	    end in
+	  begin
+	    y_loop ymin 0 ;
+	    x_loop (x +. dx) (i + 1)
+	  end 
+	end in
+    x_loop xmin 0
+  end
+
+let _ = print_endline "Making a nice 3D plot..."
+let _ = drawsolid ()
+
+let _ = _FrameBuffer_writeGIF (C_list [ frame ; cmap ; C_string "image.gif" ])
+let _ = print_endline "Write image.gif"
diff --git a/trunk/Examples/GIFPlot/Ocaml/simple/Makefile b/trunk/Examples/GIFPlot/Ocaml/simple/Makefile
new file mode 100644
index 0000000..50492ef
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/simple/Makefile
@@ -0,0 +1,33 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include
+SRCS       = 
+TARGET     = gifsimple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+MLFILE     = simple.ml
+IOBJS      = simple_wrap.o simple.cmo runme.cmo
+PROGFILE   = runme.ml
+
+all:: static
+
+static::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_static
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile TOP='$(TOP)' \
+	IOBJS='$(IOBJS)' PROGFILE='$(PROGFILE)' \
+	SRCS='$(SRCS)' SWIG='$(SWIG)' MLFILE='$(MLFILE)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ocaml_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Ocaml/simple/cmap b/trunk/Examples/GIFPlot/Ocaml/simple/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/simple/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Ocaml/simple/runme.ml b/trunk/Examples/GIFPlot/Ocaml/simple/runme.ml
new file mode 100644
index 0000000..3b6602c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/simple/runme.ml
@@ -0,0 +1,35 @@
+(* Draw some simple shapes *)
+
+(* Use the wrapped GIFPlot library *)
+open Swig
+open Simple
+open Int32
+
+let _ = print_endline "Drawing some basic shapes"
+
+let cmap = _new_ColorMap (C_string "cmap")
+let f = _new_FrameBuffer (C_list [ C_int 400 ; C_int 400 ])
+
+(* Clear the picture *)
+let _ = _FrameBuffer_clear (C_list [ f ; _BLACK C_void ])
+
+(* Make a red box *)
+let _ = _FrameBuffer_box 
+	  (C_list [ f ; C_int 40 ; C_int 40 ; C_int 200 ; C_int 200 ; _RED C_void ])
+
+(* Make a blue circle *)
+let _ = _FrameBuffer_circle 
+	  (C_list [ f ; C_int 200 ; C_int 200 ; C_int 40 ; _BLUE C_void ])
+
+(* Make green line *)
+let _ = _FrameBuffer_line 
+	  (C_list [ f ; C_int 10 ; C_int 390 ; C_int 390 ; C_int 200 ; _GREEN C_void ])
+
+(* Write an image out to disk *)
+
+let _ = _FrameBuffer_writeGIF (C_list [ f ; cmap ; C_string "image.gif" ])
+let _ = print_endline "Wrote image.gif"
+
+let _ = _delete_FrameBuffer f
+let _ = _delete_ColorMap cmap
+
diff --git a/trunk/Examples/GIFPlot/Ocaml/simple/simple.i b/trunk/Examples/GIFPlot/Ocaml/simple/simple.i
new file mode 100644
index 0000000..33297f4
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ocaml/simple/simple.i
@@ -0,0 +1,33 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef int Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
diff --git a/trunk/Examples/GIFPlot/Perl5/check.list b/trunk/Examples/GIFPlot/Perl5/check.list
new file mode 100644
index 0000000..13de977
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/check.list
@@ -0,0 +1,4 @@
+# see top-level Makefile.in
+full
+shadow
+simple
diff --git a/trunk/Examples/GIFPlot/Perl5/full/Makefile b/trunk/Examples/GIFPlot/Perl5/full/Makefile
new file mode 100644
index 0000000..0e0878d
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/full/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include -noproxy
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Perl5/full/README b/trunk/Examples/GIFPlot/Perl5/full/README
new file mode 100644
index 0000000..05c685a
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The script 'runme.pl' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Perl5/full/cmap b/trunk/Examples/GIFPlot/Perl5/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Perl5/full/gifplot.i b/trunk/Examples/GIFPlot/Perl5/full/gifplot.i
new file mode 100644
index 0000000..5a7f500
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Perl5/full/runme.pl b/trunk/Examples/GIFPlot/Perl5/full/runme.pl
new file mode 100644
index 0000000..77fd321
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/full/runme.pl
@@ -0,0 +1,68 @@
+# Plot a 3D function
+use gifplot;
+package gifplot;
+
+# Here is the function to plot
+sub func {
+    my $x = shift;
+    my $y = shift;
+    return 5*cos(2*sqrt($x*$x+$y*$y))*exp(-0.3*sqrt($x*$x+$y*$y));
+}
+
+# Here are some plotting parameters
+$xmin = -5.0;
+$xmax =  5.0;
+$ymin = -5.0;
+$ymax =  5.0;
+$zmin = -5.0;
+$zmax =  5.0;
+
+# Grid resolution
+$nxpoints =  60;
+$nypoints =  60;
+
+$cmap  = new_ColorMap("cmap");
+$frame = new_FrameBuffer(500,500);
+FrameBuffer_clear($frame,$BLACK);
+
+$p3    = new_Plot3D($frame,$xmin,$ymin,$zmin,$xmax,$ymax,$zmax);
+Plot3D_lookat($p3,2*($zmax-$zmin));
+Plot3D_autoperspective($p3,40);
+Plot3D_rotu($p3,60);
+Plot3D_rotr($p3,30);
+Plot3D_rotd($p3,10);
+
+sub drawsolid {
+    Plot3D_clear($p3,$BLACK);
+    Plot3D_start($p3);
+    my $dx = 1.0*($xmax-$xmin)/$nxpoints;
+    my $dy = 1.0*($ymax-$ymin)/$nypoints;
+    my $cscale = 240.0/($zmax-$zmin);
+    my $x = $xmin;
+    for ($i = 0; $i < $nxpoints; $i++) {
+	my $y = $ymin;
+	for ($j = 0; $j < $nypoints; $j++) {
+	    my $z1 = func($x,$y);
+	    my $z2 = func($x+$dx,$y);
+	    my $z3 = func($x+$dx,$y+$dy);
+	    my $z4 = func($x,$y+$dy);
+	    my $c1 = $cscale*($z1-$zmin);
+	    my $c2 = $cscale*($z2-$zmin);
+	    my $c3 = $cscale*($z3-$zmin);
+	    my $c4 = $cscale*($z4-$zmin);
+	    my $c = ($c1+$c2+$c3+$c4)/4;
+	    if ($c < 0) { $c = 0; }
+	    if ($c > 239) { $c = 239; }
+	    Plot3D_solidquad($p3,$x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16);
+	    $y = $y + $dy;
+	}
+	$x = $x + $dx;
+    }
+}
+
+print "Making a nice 3D plot...\n";
+drawsolid();
+
+FrameBuffer_writeGIF($frame,$cmap,"image.gif");
+print "Wrote image.gif\n";
+
diff --git a/trunk/Examples/GIFPlot/Perl5/shadow/Makefile b/trunk/Examples/GIFPlot/Perl5/shadow/Makefile
new file mode 100644
index 0000000..c5cb7ae
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/shadow/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Interface
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Perl5/shadow/README b/trunk/Examples/GIFPlot/Perl5/shadow/README
new file mode 100644
index 0000000..ab12e34
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/shadow/README
@@ -0,0 +1,2 @@
+This example use the file in ../../Interface/gifplot.i to build
+an interface with shadow classes.  Run the script 'runme.pl'.
diff --git a/trunk/Examples/GIFPlot/Perl5/shadow/cmap b/trunk/Examples/GIFPlot/Perl5/shadow/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/shadow/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Perl5/shadow/runme.pl b/trunk/Examples/GIFPlot/Perl5/shadow/runme.pl
new file mode 100644
index 0000000..c396251
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/shadow/runme.pl
@@ -0,0 +1,68 @@
+# Plot a 3D function
+use gifplot;
+package gifplot;
+
+# Here is the function to plot
+sub func {
+    my $x = shift;
+    my $y = shift;
+    return 5*cos(2*sqrt($x*$x+$y*$y))*exp(-0.3*sqrt($x*$x+$y*$y));
+}
+
+# Here are some plotting parameters
+$xmin = -5.0;
+$xmax =  5.0;
+$ymin = -5.0;
+$ymax =  5.0;
+$zmin = -5.0;
+$zmax =  5.0;
+
+# Grid resolution
+$nxpoints =  60;
+$nypoints =  60;
+
+$cmap  = new gifplot::ColorMap("cmap");
+$frame = new gifplot::FrameBuffer(500,500);
+$frame->clear($BLACK);
+
+$p3    = new gifplot::Plot3D($frame,$xmin,$ymin,$zmin,$xmax,$ymax,$zmax);
+$p3->lookat(2*($zmax-$zmin));
+$p3->autoperspective(40);
+$p3->rotu(60);
+$p3->rotr(30);
+$p3->rotd(10);
+
+sub drawsolid {
+    $p3->clear($BLACK);
+    $p3->start();
+    my $dx = 1.0*($xmax-$xmin)/$nxpoints;
+    my $dy = 1.0*($ymax-$ymin)/$nypoints;
+    my $cscale = 240.0/($zmax-$zmin);
+    my $x = $xmin;
+    for ($i = 0; $i < $nxpoints; $i++) {
+	my $y = $ymin;
+	for ($j = 0; $j < $nypoints; $j++) {
+	    my $z1 = func($x,$y);
+	    my $z2 = func($x+$dx,$y);
+	    my $z3 = func($x+$dx,$y+$dy);
+	    my $z4 = func($x,$y+$dy);
+	    my $c1 = $cscale*($z1-$zmin);
+	    my $c2 = $cscale*($z2-$zmin);
+	    my $c3 = $cscale*($z3-$zmin);
+	    my $c4 = $cscale*($z4-$zmin);
+	    my $c = ($c1+$c2+$c3+$c4)/4;
+	    if ($c < 0) { $c = 0; }
+	    if ($c > 239) { $c = 239; }
+	    $p3->solidquad($x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16);
+	    $y = $y + $dy;
+	}
+	$x = $x + $dx;
+    }
+}
+
+print "Making a nice 3D plot...\n";
+drawsolid();
+
+$frame->writeGIF($cmap,"image.gif");
+print "Wrote image.gif\n";
+
diff --git a/trunk/Examples/GIFPlot/Perl5/simple/Makefile b/trunk/Examples/GIFPlot/Perl5/simple/Makefile
new file mode 100644
index 0000000..36a8fa9
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/simple/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    =
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Perl5/simple/README b/trunk/Examples/GIFPlot/Perl5/simple/README
new file mode 100644
index 0000000..c2c799a
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  The script 'runme.pl' runs the example.
+
+
diff --git a/trunk/Examples/GIFPlot/Perl5/simple/runme.pl b/trunk/Examples/GIFPlot/Perl5/simple/runme.pl
new file mode 100644
index 0000000..f28255e
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/simple/runme.pl
@@ -0,0 +1,28 @@
+# Draw some simple shapes
+print "Drawing some basic shapes\n";
+
+use simple;
+
+$cmap = simple::new_ColorMap();
+$f    = simple::new_FrameBuffer(400,400);
+
+# Clear the picture
+simple::FrameBuffer_clear($f,$simple::BLACK);
+
+# Make a red box
+simple::FrameBuffer_box($f,40,40,200,200,$simple::RED);
+
+# Make a blue circle
+simple::FrameBuffer_circle($f,200,200,40,$simple::BLUE);
+
+# Make green line
+simple::FrameBuffer_line($f,10,390,390,200, $simple::GREEN);
+
+# Write an image out to disk
+
+simple::FrameBuffer_writeGIF($f,$cmap,"image.gif");
+print "Wrote image.gif\n";
+
+simple::delete_FrameBuffer($f);
+simple::delete_ColorMap($cmap);
+
diff --git a/trunk/Examples/GIFPlot/Perl5/simple/simple.i b/trunk/Examples/GIFPlot/Perl5/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Perl5/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Php4/check.list b/trunk/Examples/GIFPlot/Php4/check.list
new file mode 100644
index 0000000..e75ee58
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/check.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+full
+simple
diff --git a/trunk/Examples/GIFPlot/Php4/full/Makefile b/trunk/Examples/GIFPlot/Php4/full/Makefile
new file mode 100644
index 0000000..3aa632b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/full/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include -noproxy
+SRCS       =
+TARGET     = php_gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php4
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f *.gif
+	rm -f php_gifplot.h
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Php4/full/README b/trunk/Examples/GIFPlot/Php4/full/README
new file mode 100644
index 0000000..f8d38d9
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/full/README
@@ -0,0 +1,4 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The script 'runme.php3' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
diff --git a/trunk/Examples/GIFPlot/Php4/full/cmap b/trunk/Examples/GIFPlot/Php4/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Php4/full/gifplot.i b/trunk/Examples/GIFPlot/Php4/full/gifplot.i
new file mode 100644
index 0000000..5a7f500
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Php4/full/runme.php4 b/trunk/Examples/GIFPlot/Php4/full/runme.php4
new file mode 100644
index 0000000..de5371e
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/full/runme.php4
@@ -0,0 +1,78 @@
+<?
+
+# Plot a 3D function
+require "gifplot.php";
+
+# Here is the function to plot
+function func($x, $y) {
+    return 5*cos(2*sqrt($x*$x+$y*$y))*exp(-0.3*sqrt($x*$x+$y*$y));
+}
+
+# Here are some plotting parameters
+$xmin = -5.0;
+$xmax =  5.0;
+$ymin = -5.0;
+$ymax =  5.0;
+$zmin = -5.0;
+$zmax =  5.0;
+
+# Grid resolution
+$nxpoints =  60;
+$nypoints =  60;
+
+$cmap  = new_ColorMap("cmap");
+$frame = new_FrameBuffer(500,500);
+FrameBuffer_clear($frame, BLACK);
+
+$p3    = new_Plot3D($frame,$xmin,$ymin,$zmin,$xmax,$ymax,$zmax);
+Plot3D_lookat($p3, 2*($zmax-$zmin));
+Plot3D_autoperspective($p3, 40);
+Plot3D_rotu($p3, 60);
+Plot3D_rotr($p3, 30);
+Plot3D_rotd($p3, 10);
+
+function drawsolid() {
+	global $p3;
+	global $xmax;
+	global $xmin;
+	global $ymax;
+	global $ymin;
+	global $zmin;
+	global $zmax;
+	global $nxpoints;
+	global $nypoints;
+
+    Plot3D_clear($p3, BLACK);
+    Plot3D_start($p3);
+    $dx = 1.0*($xmax-$xmin)/$nxpoints;
+    $dy = 1.0*($ymax-$ymin)/$nypoints;
+    $cscale = 240.0/($zmax-$zmin);
+    $x = $xmin;
+    for ($i = 0; $i < $nxpoints; $i++) {
+	$y = $ymin;
+	for ($j = 0; $j < $nypoints; $j++) {
+	    $z1 = func($x,$y);
+	    $z2 = func($x+$dx,$y);
+	    $z3 = func($x+$dx,$y+$dy);
+	    $z4 = func($x,$y+$dy);
+	    $c1 = $cscale*($z1-$zmin);
+	    $c2 = $cscale*($z2-$zmin);
+	    $c3 = $cscale*($z3-$zmin);
+	    $c4 = $cscale*($z4-$zmin);
+	    $c = ($c1+$c2+$c3+$c4)/4;
+	    if ($c < 0) { $c = 0; }
+	    if ($c > 239) { $c = 239; }
+	    Plot3D_solidquad($p3, $x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16);
+	    $y = $y + $dy;
+	}
+	$x = $x + $dx;
+    }
+}
+
+print "Making a nice 3D plot...\n";
+drawsolid();
+
+FrameBuffer_writeGIF($frame, $cmap,"image.gif");
+print "Wrote image.gif\n";
+
+?>
diff --git a/trunk/Examples/GIFPlot/Php4/shadow/Makefile b/trunk/Examples/GIFPlot/Php4/shadow/Makefile
new file mode 100644
index 0000000..5627e53
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/shadow/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Interface
+SRCS       =
+TARGET     = php_gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot -lm
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php4
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Php4/shadow/README b/trunk/Examples/GIFPlot/Php4/shadow/README
new file mode 100644
index 0000000..3e91f7d
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/shadow/README
@@ -0,0 +1,2 @@
+This example use the file in ../../Interface/gifplot.i to build
+an interface with shadow classes.  Run the script 'runme.php3'.
diff --git a/trunk/Examples/GIFPlot/Php4/shadow/cmap b/trunk/Examples/GIFPlot/Php4/shadow/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/shadow/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Php4/shadow/runme.php4 b/trunk/Examples/GIFPlot/Php4/shadow/runme.php4
new file mode 100644
index 0000000..3dffba0
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/shadow/runme.php4
@@ -0,0 +1,79 @@
+<?
+
+# Plot a 3D function
+include("gifplot.php");
+
+# Here is the function to plot
+function func($x, $y) {
+    return 5*cos(2*sqrt($x*$x+$y*$y))*exp(-0.3*sqrt($x*$x+$y*$y));
+}
+
+# Here are some plotting parameters
+$xmin = -5.0;
+$xmax =  5.0;
+$ymin = -5.0;
+$ymax =  5.0;
+$zmin = -5.0;
+$zmax =  5.0;
+
+# Grid resolution
+$nxpoints =  60;
+$nypoints =  60;
+
+$cmap  = new ColorMap("cmap");
+$frame = new FrameBuffer(500,500);
+$frame->clear(BLACK);
+
+
+$p3    = new Plot3D($frame,$xmin,$ymin,$zmin,$xmax,$ymax,$zmax);
+$p3->lookat(2*($zmax-$zmin));
+$p3->autoperspective(40);
+$p3->rotu(60);
+$p3->rotr(30);
+$p3->rotd(10);
+
+function drawsolid() {
+	global $xmax;
+	global $xmin;
+	global $ymax;
+	global $ymin;
+	global $zmin;
+	global $zmax;
+	global $nxpoints;
+	global $nypoints;
+	global $p3;
+
+    $p3->clear(BLACK);
+    $p3->start();
+    $dx = 1.0*($xmax-$xmin)/$nxpoints;
+    $dy = 1.0*($ymax-$ymin)/$nypoints;
+    $cscale = 240.0/($zmax-$zmin);
+    $x = $xmin;
+    for ($i = 0; $i < $nxpoints; $i++) {
+	$y = $ymin;
+	for ($j = 0; $j < $nypoints; $j++) {
+	    $z1 = func($x,$y);
+	    $z2 = func($x+$dx,$y);
+	    $z3 = func($x+$dx,$y+$dy);
+	    $z4 = func($x,$y+$dy);
+	    $c1 = $cscale*($z1-$zmin);
+	    $c2 = $cscale*($z2-$zmin);
+	    $c3 = $cscale*($z3-$zmin);
+	    $c4 = $cscale*($z4-$zmin);
+	    $c = ($c1+$c2+$c3+$c4)/4;
+	    if ($c < 0) { $c = 0; }
+	    if ($c > 239) { $c = 239; }
+	    $p3->solidquad($x,$y,$z1,$x+$dx,$y,$z2,$x+$dx,$y+$dy,$z3,$x,$y+$dy,$z4,$c+16);
+	    $y = $y + $dy;
+	}
+	$x = $x + $dx;
+    }
+}
+
+print "Making a nice 3D plot...\n";
+drawsolid();
+
+$frame->writeGIF($cmap,"image.gif");
+print "Wrote image.gif\n";
+
+?>
diff --git a/trunk/Examples/GIFPlot/Php4/simple/Makefile b/trunk/Examples/GIFPlot/Php4/simple/Makefile
new file mode 100644
index 0000000..6903bec
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/simple/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -noproxy
+SRCS       =
+TARGET     = php_simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php4
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f *.gif
+	rm -f php_simple.h
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Php4/simple/README b/trunk/Examples/GIFPlot/Php4/simple/README
new file mode 100644
index 0000000..c2c799a
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  The script 'runme.pl' runs the example.
+
+
diff --git a/trunk/Examples/GIFPlot/Php4/simple/runme.php4 b/trunk/Examples/GIFPlot/Php4/simple/runme.php4
new file mode 100644
index 0000000..cf21a09
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/simple/runme.php4
@@ -0,0 +1,32 @@
+<?
+
+# Draw some simple shapes
+print "Drawing some basic shapes\n";
+
+require "simple.php";
+
+$cmap = new_ColorMap();
+$f    = new_FrameBuffer(400,400);
+
+# Clear the picture
+FrameBuffer_clear($f,BLACK);
+
+# Make a red box
+FrameBuffer_box($f,40,40,200,200,RED);
+
+# Make a blue circle
+FrameBuffer_circle($f,200,200,40,BLUE);
+
+# Make green line
+FrameBuffer_line($f,10,390,390,200, GREEN);
+
+# Write an image out to disk
+
+FrameBuffer_writeGIF($f,$cmap,"image.gif");
+print "Wrote image.gif\n";
+
+delete_FrameBuffer($f);
+delete_ColorMap($cmap);
+
+?>
+
diff --git a/trunk/Examples/GIFPlot/Php4/simple/simple.i b/trunk/Examples/GIFPlot/Php4/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Php4/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Pike/check.list b/trunk/Examples/GIFPlot/Pike/check.list
new file mode 100644
index 0000000..d38998c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Pike/check.list
@@ -0,0 +1,2 @@
+# see top-level Makefile.in
+simple
diff --git a/trunk/Examples/GIFPlot/Pike/simple/Makefile b/trunk/Examples/GIFPlot/Pike/simple/Makefile
new file mode 100644
index 0000000..d339e03
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Pike/simple/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    =
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Pike/simple/README b/trunk/Examples/GIFPlot/Pike/simple/README
new file mode 100644
index 0000000..177b363
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Pike/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  The script 'runme.pike' runs the example.
+
+
diff --git a/trunk/Examples/GIFPlot/Pike/simple/runme.pike b/trunk/Examples/GIFPlot/Pike/simple/runme.pike
new file mode 100644
index 0000000..0e70235
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Pike/simple/runme.pike
@@ -0,0 +1,30 @@
+int main()
+{
+  // Draw some simple shapes
+  write("Drawing some basic shapes\n");
+
+   .simple.ColorMap cmap = .simple.new_ColorMap();
+   .simple.FrameBuffer f = .simple.new_FrameBuffer(400, 400);
+
+  // Clear the picture
+  .simple.FrameBuffer_clear(f, .simple.BLACK);
+
+  // Make a red box
+  .simple.FrameBuffer_box(f, 40, 40, 200, 200, .simple.RED);
+
+  // Make a blue circle
+  .simple.FrameBuffer_circle(f, 200, 200, 40, .simple.BLUE);
+
+  // Make green line
+  .simple.FrameBuffer_line(f, 10, 390, 390, 200, .simple.GREEN);
+
+  // Write an image out to disk
+  .simple.FrameBuffer_writeGIF(f, cmap, "image.gif");
+  write("Wrote image.gif\n");
+
+  .simple.delete_FrameBuffer(f);
+  .simple.delete_ColorMap(cmap);
+  
+  return 0;
+}
+
diff --git a/trunk/Examples/GIFPlot/Pike/simple/simple.i b/trunk/Examples/GIFPlot/Pike/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Pike/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Python/check.list b/trunk/Examples/GIFPlot/Python/check.list
new file mode 100644
index 0000000..13de977
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/check.list
@@ -0,0 +1,4 @@
+# see top-level Makefile.in
+full
+shadow
+simple
diff --git a/trunk/Examples/GIFPlot/Python/full/Makefile b/trunk/Examples/GIFPlot/Python/full/Makefile
new file mode 100644
index 0000000..ae927b7
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/full/Makefile
@@ -0,0 +1,25 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include 
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Python/full/README b/trunk/Examples/GIFPlot/Python/full/README
new file mode 100644
index 0000000..52971e4
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The script 'runme.py' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Python/full/cmap b/trunk/Examples/GIFPlot/Python/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Python/full/gifplot.i b/trunk/Examples/GIFPlot/Python/full/gifplot.i
new file mode 100644
index 0000000..5a7f500
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Python/full/runme.py b/trunk/Examples/GIFPlot/Python/full/runme.py
new file mode 100644
index 0000000..cb324c8
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/full/runme.py
@@ -0,0 +1,64 @@
+# Plot a 3D function
+# This example uses the low-level C interface.
+
+from _gifplot import *
+from math import *
+
+# Here is the function to plot
+def func(x,y):
+	return 5*cos(2*sqrt(x*x+y*y))*exp(-0.3*sqrt(x*x+y*y))
+
+# Here are some plotting parameters
+xmin = -5.0
+xmax =  5.0
+ymin = -5.0
+ymax =  5.0
+zmin = -5.0
+zmax =  5.0
+
+# Grid resolution
+nxpoints =  60
+nypoints =  60
+
+cmap  = new_ColorMap("cmap")
+frame = new_FrameBuffer(500,500)
+FrameBuffer_clear(frame,BLACK)
+
+p3    = new_Plot3D(frame,xmin,ymin,zmin,xmax,ymax,zmax)
+Plot3D_lookat(p3,2*max([xmax-xmin,ymax-ymin,zmax-zmin]))
+Plot3D_autoperspective(p3,40)
+Plot3D_rotu(p3,60)
+Plot3D_rotr(p3,30)
+Plot3D_rotd(p3,10)
+
+def drawsolid():
+	Plot3D_clear(p3,BLACK)
+	Plot3D_start(p3)
+	dx = 1.0*(xmax-xmin)/nxpoints
+	dy = 1.0*(ymax-ymin)/nypoints
+	cscale = 240.0/(zmax-zmin)
+	x = xmin
+	for i in xrange(0,nxpoints):
+		y = ymin
+		for j in xrange(0,nypoints):
+			z1 = func(x,y)
+			z2 = func(x+dx,y)
+			z3 = func(x+dx,y+dy)
+			z4 = func(x,y+dy)
+			c1 = cscale*(z1-zmin)
+			c2 = cscale*(z2-zmin)
+			c3 = cscale*(z3-zmin)
+			c4 = cscale*(z4-zmin)
+			c = int((c1+c2+c3+c4)/4)
+			if (c < 0) : c = 0
+			if c > 239 : c = 239
+			Plot3D_solidquad(p3,x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16)
+			y = y + dy		
+		x = x + dx
+
+print "Making a nice 3D plot..."
+drawsolid()
+
+FrameBuffer_writeGIF(frame,cmap,"image.gif")
+print "Wrote image.gif"
+
diff --git a/trunk/Examples/GIFPlot/Python/shadow/Makefile b/trunk/Examples/GIFPlot/Python/shadow/Makefile
new file mode 100644
index 0000000..1f50148
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/shadow/Makefile
@@ -0,0 +1,25 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Interface
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Python/shadow/README b/trunk/Examples/GIFPlot/Python/shadow/README
new file mode 100644
index 0000000..aa761e2
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/shadow/README
@@ -0,0 +1,8 @@
+This example illustrates Python shadow classes. Take a look at
+the file GIFPlot/Interface/gifplot.i
+
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Python/shadow/cmap b/trunk/Examples/GIFPlot/Python/shadow/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/shadow/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Python/shadow/runme.py b/trunk/Examples/GIFPlot/Python/shadow/runme.py
new file mode 100644
index 0000000..d914601
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/shadow/runme.py
@@ -0,0 +1,62 @@
+# Plot a 3D function
+import gifplot
+from math import *
+
+# Here is the function to plot
+def func(x,y):
+	return 5*cos(2*sqrt(x*x+y*y))*exp(-0.3*sqrt(x*x+y*y))
+
+# Here are some plotting parameters
+xmin = -5.0
+xmax =  5.0
+ymin = -5.0
+ymax =  5.0
+zmin = -5.0
+zmax =  5.0
+
+# Grid resolution
+nxpoints =  60
+nypoints =  60
+
+cmap  = gifplot.ColorMap("cmap")
+frame = gifplot.FrameBuffer(500,500)
+frame.clear(gifplot.BLACK)
+
+p3    = gifplot.Plot3D(frame,xmin,ymin,zmin,xmax,ymax,zmax)
+p3.lookat(2*max([xmax-xmin,ymax-ymin,zmax-zmin]))
+p3.autoperspective(40)
+p3.rotu(60)
+p3.rotr(30)
+p3.rotd(10)
+
+def drawsolid():
+	p3.clear(gifplot.BLACK)
+	p3.start()
+	dx = 1.0*(xmax-xmin)/nxpoints
+	dy = 1.0*(ymax-ymin)/nypoints
+	cscale = 240.0/(zmax-zmin)
+	x = xmin
+	for i in xrange(0,nxpoints):
+		y = ymin
+		for j in xrange(0,nypoints):
+			z1 = func(x,y)
+			z2 = func(x+dx,y)
+			z3 = func(x+dx,y+dy)
+			z4 = func(x,y+dy)
+			c1 = cscale*(z1-zmin)
+			c2 = cscale*(z2-zmin)
+			c3 = cscale*(z3-zmin)
+			c4 = cscale*(z4-zmin)
+			c = int((c1+c2+c3+c4)/4)
+			if (c < 0) : c = 0
+			if c > 239 : c = 239
+			p3.solidquad(x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16)
+			y = y + dy		
+		x = x + dx
+
+print "Making a nice 3D plot..."
+drawsolid()
+
+frame.writeGIF(cmap,"image.gif")
+print "Wrote image.gif"
+
diff --git a/trunk/Examples/GIFPlot/Python/simple/Makefile b/trunk/Examples/GIFPlot/Python/simple/Makefile
new file mode 100644
index 0000000..5eb0344
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/simple/Makefile
@@ -0,0 +1,25 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    =
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Python/simple/README b/trunk/Examples/GIFPlot/Python/simple/README
new file mode 100644
index 0000000..22152c6
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  The script 'runme.py' runs the example.
+
+
diff --git a/trunk/Examples/GIFPlot/Python/simple/runme.py b/trunk/Examples/GIFPlot/Python/simple/runme.py
new file mode 100644
index 0000000..dade677
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/simple/runme.py
@@ -0,0 +1,27 @@
+# Draw some simple shapes
+print "Drawing some basic shapes"
+import simple
+
+cmap = simple.new_ColorMap()
+f    = simple.new_FrameBuffer(400,400)
+
+# Clear the picture
+simple.FrameBuffer_clear(f,simple.BLACK)
+
+# Make a red box
+simple.FrameBuffer_box(f,40,40,200,200,simple.RED)
+
+# Make a blue circle
+simple.FrameBuffer_circle(f,200,200,40,simple.BLUE)
+
+# Make green line
+simple.FrameBuffer_line(f,10,390,390,200, simple.GREEN)
+
+# Write an image out to disk
+
+simple.FrameBuffer_writeGIF(f,cmap,"image.gif")
+print "Wrote image.gif"
+
+simple.delete_FrameBuffer(f)
+simple.delete_ColorMap(cmap)
+
diff --git a/trunk/Examples/GIFPlot/Python/simple/simple.i b/trunk/Examples/GIFPlot/Python/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Python/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/README b/trunk/Examples/GIFPlot/README
new file mode 100644
index 0000000..ac1025a
--- /dev/null
+++ b/trunk/Examples/GIFPlot/README
@@ -0,0 +1,59 @@
+GIFPlot
+=======
+
+To illustrate various SWIG features, the following examples involve
+building an interface to a small, but somewhat useful graphics library
+for creating 2D and 3D images in the form of GIF files.  The Perl,
+Python, Tcl, Java, Ruby etc. directories contain various examples specific to
+those languages.
+
+This library was originally developed as part of the SPaSM molecular
+dynamics project at Los Alamos National Laboratory.  However, due to
+patent enforcement issues related to LZW encoding and a general lack
+of time on the part of the author, the library was never officially
+released.  On the plus side, a number of people have found it to be a
+useful easter egg within the SWIG distribution :-).
+
+<LEGAL>
+DUE TO PATENT RESTRICTIONS ON THE LZW COMPRESSION ALGORITHM, THIS
+LIBRARY ONLY PRODUCES UNCOMPRESSED GIF FILES.  SO THERE.
+</LEGAL>
+
+Building the Library
+====================
+
+In order to run the examples, it is first necessary to build the GIFPlot
+C library.  To do this, simply run make:
+
+	make
+
+Running the Examples
+====================
+
+Once the library has been built, go to your chosen language directory,
+that is, Perl, Python, Tcl, Java, Ruby etc. Each example should have a
+README file with a description.
+
+Each example can be compiled using the makefile in each example directory. This
+makefile uses the top level makefile in the "Examples" directory of the distribution.
+If the example doesn't compile, you will need to adjust the settings in this file.
+
+Documentation
+=============
+
+Read the source Luke.   The examples should be pretty much self-explanatory.
+The header file Include/gifplot.h contains the full API.
+
+The original documentation for the library can be found online at:
+
+          http://www.dabeaz.com/gifplot/index.html
+
+
+Let me know what you think!
+===========================
+If you found this example to be useful, confusing, or otherwise, I would like to know
+about it.   Suggestions for improvement are welcome.
+
+-- Dave (dave@dabeaz.com)
+
+
diff --git a/trunk/Examples/GIFPlot/Ruby/check.list b/trunk/Examples/GIFPlot/Ruby/check.list
new file mode 100644
index 0000000..13de977
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/check.list
@@ -0,0 +1,4 @@
+# see top-level Makefile.in
+full
+shadow
+simple
diff --git a/trunk/Examples/GIFPlot/Ruby/full/Makefile b/trunk/Examples/GIFPlot/Ruby/full/Makefile
new file mode 100644
index 0000000..5af8bc8
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/full/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Ruby/full/README b/trunk/Examples/GIFPlot/Ruby/full/README
new file mode 100644
index 0000000..22af6cb
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The script 'runme.rb' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Ruby/full/cmap b/trunk/Examples/GIFPlot/Ruby/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Ruby/full/gifplot.i b/trunk/Examples/GIFPlot/Ruby/full/gifplot.i
new file mode 100644
index 0000000..5a7f500
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Ruby/full/runme.rb b/trunk/Examples/GIFPlot/Ruby/full/runme.rb
new file mode 100644
index 0000000..5c118b2
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/full/runme.rb
@@ -0,0 +1,66 @@
+# Plot a 3D function
+require 'gifplot'
+include Gifplot
+include Math
+
+# Here is the function to plot
+def func(x,y)
+  return 5*cos(2*sqrt(x*x+y*y))*exp(-0.3*sqrt(x*x+y*y))
+end
+
+# Here are some plotting parameters
+XMIN = -5.0
+XMAX =  5.0
+YMIN = -5.0
+YMAX =  5.0
+ZMIN = -5.0
+ZMAX =  5.0
+
+# Grid resolution
+NXPOINTS =  60
+NYPOINTS =  60
+
+cmap  = new_ColorMap("cmap")
+frame = new_FrameBuffer(500,500)
+FrameBuffer_clear(frame,BLACK)
+
+P3    = new_Plot3D(frame,XMIN,YMIN,ZMIN,XMAX,YMAX,ZMAX)
+Plot3D_lookat(P3,2*[XMAX-XMIN,YMAX-YMIN,ZMAX-ZMIN].max)
+Plot3D_autoperspective(P3,40)
+Plot3D_rotu(P3,60)
+Plot3D_rotr(P3,30)
+Plot3D_rotd(P3,10)
+
+def drawsolid()
+  Plot3D_clear(P3,BLACK)
+  Plot3D_start(P3)
+  dx = 1.0*(XMAX-XMIN)/NXPOINTS
+  dy = 1.0*(YMAX-YMIN)/NYPOINTS
+  cscale = 240.0/(ZMAX-ZMIN)
+  x = XMIN
+  for i in 0...NXPOINTS
+    y = YMIN
+    for j in 0...NYPOINTS
+      z1 = func(x,y)
+      z2 = func(x+dx,y)
+      z3 = func(x+dx,y+dy)
+      z4 = func(x,y+dy)
+      c1 = cscale*(z1-ZMIN)
+      c2 = cscale*(z2-ZMIN)
+      c3 = cscale*(z3-ZMIN)
+      c4 = cscale*(z4-ZMIN)
+      c = (c1+c2+c3+c4)/4
+      c = 0 if (c < 0)
+      c = 239 if c > 239
+      Plot3D_solidquad(P3,x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16)
+      y = y + dy
+    end
+    x = x + dx
+  end
+end
+
+puts "Making a nice 3D plot..."
+drawsolid()
+
+FrameBuffer_writeGIF(frame,cmap,"image.gif")
+puts "Wrote image.gif"
diff --git a/trunk/Examples/GIFPlot/Ruby/shadow/Makefile b/trunk/Examples/GIFPlot/Ruby/shadow/Makefile
new file mode 100644
index 0000000..ea382ea
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/shadow/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Interface
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Ruby/shadow/README b/trunk/Examples/GIFPlot/Ruby/shadow/README
new file mode 100644
index 0000000..7a33e13
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/shadow/README
@@ -0,0 +1,5 @@
+This example illustrates Ruby shadow classes. Take a look at
+the file GIFPlot/Interface/gifplot.i
+
+Actually Ruby module of SWIG needs no shadow class.  But this example
+is named "shadow" in order to be consistent with other languages.
diff --git a/trunk/Examples/GIFPlot/Ruby/shadow/cmap b/trunk/Examples/GIFPlot/Ruby/shadow/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/shadow/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Ruby/shadow/runme.rb b/trunk/Examples/GIFPlot/Ruby/shadow/runme.rb
new file mode 100644
index 0000000..0afccee
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/shadow/runme.rb
@@ -0,0 +1,66 @@
+# Plot a 3D function
+require 'gifplot'
+include Math
+
+# Here is the function to plot
+def func(x,y)
+  return 5*cos(2*sqrt(x*x+y*y))*exp(-0.3*sqrt(x*x+y*y))
+end
+
+# Here are some plotting parameters
+XMIN = -5.0
+XMAX =  5.0
+YMIN = -5.0
+YMAX =  5.0
+ZMIN = -5.0
+ZMAX =  5.0
+
+# Grid resolution
+NXPOINTS =  60
+NYPOINTS =  60
+
+cmap  = Gifplot::ColorMap.new("cmap")
+frame = Gifplot::FrameBuffer.new(500,500)
+frame.clear(Gifplot::BLACK)
+
+P3    = Gifplot::Plot3D.new(frame,XMIN,YMIN,ZMIN,XMAX,YMAX,ZMAX)
+P3.lookat(2*[XMAX-XMIN,YMAX-YMIN,ZMAX-ZMIN].max)
+P3.autoperspective(40)
+P3.rotu(60)
+P3.rotr(30)
+P3.rotd(10)
+
+def drawsolid()
+  P3.clear(Gifplot::BLACK)
+  P3.start()
+  dx = 1.0*(XMAX-XMIN)/NXPOINTS
+  dy = 1.0*(YMAX-YMIN)/NYPOINTS
+  cscale = 240.0/(ZMAX-ZMIN)
+  x = XMIN
+  for i in 0...NXPOINTS
+    y = YMIN
+    for j in 0...NYPOINTS
+      z1 = func(x,y)
+      z2 = func(x+dx,y)
+      z3 = func(x+dx,y+dy)
+      z4 = func(x,y+dy)
+      c1 = cscale*(z1-ZMIN)
+      c2 = cscale*(z2-ZMIN)
+      c3 = cscale*(z3-ZMIN)
+      c4 = cscale*(z4-ZMIN)
+      c = (c1+c2+c3+c4)/4
+      c = 0 if (c < 0)
+      c = 239 if c > 239
+      P3.solidquad(x,y,z1,x+dx,y,z2,x+dx,y+dy,z3,x,y+dy,z4,c+16)
+      y = y + dy
+    end
+    x = x + dx
+  end
+end
+
+puts "Making a nice 3D plot..."
+drawsolid()
+
+frame.writeGIF(cmap,"image.gif")
+puts "Wrote image.gif"
+
diff --git a/trunk/Examples/GIFPlot/Ruby/simple/Makefile b/trunk/Examples/GIFPlot/Ruby/simple/Makefile
new file mode 100644
index 0000000..f7ca1a7
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/simple/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    =
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Ruby/simple/README b/trunk/Examples/GIFPlot/Ruby/simple/README
new file mode 100644
index 0000000..9b51038
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  The script 'runme.rb' runs the example.
+
+
diff --git a/trunk/Examples/GIFPlot/Ruby/simple/runme.rb b/trunk/Examples/GIFPlot/Ruby/simple/runme.rb
new file mode 100644
index 0000000..e8bf5a4
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/simple/runme.rb
@@ -0,0 +1,27 @@
+# Draw some simple shapes
+puts "Drawing some basic shapes"
+require 'simple'
+
+cmap = Simple.new_ColorMap()
+f    = Simple.new_FrameBuffer(400,400)
+
+# Clear the picture
+Simple.FrameBuffer_clear(f,Simple::BLACK)
+
+# Make a red box
+Simple.FrameBuffer_box(f,40,40,200,200,Simple::RED)
+
+# Make a blue circle
+Simple.FrameBuffer_circle(f,200,200,40,Simple::BLUE)
+
+# Make green line
+Simple.FrameBuffer_line(f,10,390,390,200, Simple::GREEN)
+
+# Write an image out to disk
+
+Simple.FrameBuffer_writeGIF(f,cmap,"image.gif")
+puts "Wrote image.gif"
+
+Simple.delete_FrameBuffer(f)
+Simple.delete_ColorMap(cmap)
+
diff --git a/trunk/Examples/GIFPlot/Ruby/simple/simple.i b/trunk/Examples/GIFPlot/Ruby/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Ruby/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Tcl/check.list b/trunk/Examples/GIFPlot/Tcl/check.list
new file mode 100644
index 0000000..2b6e3d2
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/check.list
@@ -0,0 +1,4 @@
+# see top-level Makefile.in
+full
+mandel
+simple
diff --git a/trunk/Examples/GIFPlot/Tcl/full/Makefile b/trunk/Examples/GIFPlot/Tcl/full/Makefile
new file mode 100644
index 0000000..0c016e3
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/full/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Include
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = gifplot.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Tcl/full/README b/trunk/Examples/GIFPlot/Tcl/full/README
new file mode 100644
index 0000000..bdba4e8
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/full/README
@@ -0,0 +1,8 @@
+This example runs the entire gifplot.h header file through SWIG without
+any changes.  The script 'runme.tcl' does something a little more 
+interesting.   You'll have to go look at the header file to get a complete
+listing of the functions.
+
+
+
+
diff --git a/trunk/Examples/GIFPlot/Tcl/full/cmap b/trunk/Examples/GIFPlot/Tcl/full/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/full/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Tcl/full/gifplot.i b/trunk/Examples/GIFPlot/Tcl/full/gifplot.i
new file mode 100644
index 0000000..5a7f500
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/full/gifplot.i
@@ -0,0 +1,15 @@
+/* Oh what the heck, let's just grab the whole darn header file
+   and see what happens. */
+
+%module gifplot
+%{
+
+/* Note: You still need this part because the %include directive
+   merely causes SWIG to interpret the contents of a file.  It doesn't
+   include the right include headers for the resulting C code */
+
+#include "gifplot.h"
+
+%}
+
+%include gifplot.h
diff --git a/trunk/Examples/GIFPlot/Tcl/full/runme.tcl b/trunk/Examples/GIFPlot/Tcl/full/runme.tcl
new file mode 100644
index 0000000..f469e71
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/full/runme.tcl
@@ -0,0 +1,67 @@
+# Plot a 3D function
+
+catch { load ./gifplot[info sharedlibextension] gifplot}
+
+# Here is the function to plot
+proc func { x y } {
+    return [expr { 5*cos(2*sqrt($x*$x+$y*$y))*exp(-0.3*sqrt($x*$x+$y*$y)) }]
+}
+
+# Here are some plotting parameters
+set xmin  -5.0
+set xmax   5.0
+set ymin  -5.0
+set ymax   5.0
+set zmin  -5.0
+set zmax   5.0
+
+# Grid resolution
+set nxpoints  60
+set nypoints  60
+
+set cmap [new_ColorMap cmap]
+set frame [new_FrameBuffer 500 500]
+FrameBuffer_clear $frame $BLACK
+
+set p3 [new_Plot3D $frame $xmin $ymin $zmin $xmax $ymax $zmax ]
+Plot3D_lookat $p3 [expr {2*($zmax-$zmin)}]
+Plot3D_autoperspective $p3 40
+Plot3D_rotu $p3 60
+Plot3D_rotr $p3 30
+Plot3D_rotd $p3 10
+
+proc drawsolid { } {
+    global xmin ymin zmin xmax ymax zmax nxpoints nypoints p3 BLACK
+    Plot3D_clear $p3 $BLACK
+    Plot3D_start $p3
+    set dx [expr {1.0*($xmax-$xmin)/$nxpoints}]
+    set dy [expr {1.0*($ymax-$ymin)/$nypoints}]
+    set cscale [expr {240.0/($zmax-$zmin)}]
+    set x $xmin
+    for {set i 0} {$i < $nxpoints} {incr i 1} {
+	set y $ymin
+	for {set j 0} {$j < $nypoints} {incr j 1} {
+	    set z1  [func $x $y]
+	    set z2  [func [expr {$x+$dx}] $y]
+	    set z3  [func [expr {$x+$dx}] [expr {$y+$dy}]]
+	    set z4  [func $x [expr {$y+$dy}]]
+	    set c1  [expr {$cscale*($z1-$zmin)}]
+	    set c2  [expr {$cscale*($z2-$zmin)}]
+	    set c3  [expr {$cscale*($z3-$zmin)}]
+	    set c4  [expr {$cscale*($z4-$zmin)}]
+	    set c [expr {int(($c1+$c2+$c3+$c4)/4)}]
+	    if {$c < 0} { set c 0 }
+	    if {$c > 239} { set c 239 }
+	    Plot3D_solidquad $p3 $x $y $z1 [expr {$x+$dx}] $y $z2 [expr {$x+$dx}] [expr {$y+$dy}] $z3 $x [expr {$y+$dy}] $z4 [expr {$c+16}]
+	    set y [expr {$y + $dy}]
+	}
+	set x [expr {$x + $dx}]
+    }
+}
+
+puts "Making a nice 3D plot..."
+drawsolid
+
+FrameBuffer_writeGIF $frame $cmap "image.gif"
+puts "Wrote image.gif"
+
diff --git a/trunk/Examples/GIFPlot/Tcl/mandel/Makefile b/trunk/Examples/GIFPlot/Tcl/mandel/Makefile
new file mode 100644
index 0000000..9280d7b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/mandel/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    = -I../../Interface
+SRCS       =
+TARGET     = gifplot
+INTERFACE  = mandel.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mywish' INTERFACE='$(INTERFACE)' wish
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Tcl/mandel/README b/trunk/Examples/GIFPlot/Tcl/mandel/README
new file mode 100644
index 0000000..a533d09
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/mandel/README
@@ -0,0 +1,6 @@
+Kill lots of time exploring the Mandelbrot set.  This example uses
+the full SWIG interface file located in ../../Interface.  To run
+the program, type 'wish mandel.tcl'.
+
+
+
diff --git a/trunk/Examples/GIFPlot/Tcl/mandel/cmap b/trunk/Examples/GIFPlot/Tcl/mandel/cmap
new file mode 100644
index 0000000..a20c331
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/mandel/cmap
Binary files differ
diff --git a/trunk/Examples/GIFPlot/Tcl/mandel/display.tcl b/trunk/Examples/GIFPlot/Tcl/mandel/display.tcl
new file mode 100644
index 0000000..89eedf0
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/mandel/display.tcl
@@ -0,0 +1,68 @@
+# Tcl code to display a image in a widget
+
+set __imageno 0
+
+proc dismiss {t i} {
+    destroy $t
+    image delete $i
+}
+
+proc BoxInit { c p2 mxmin mymin mxmax mymax func } {
+    bind $c <Button-1> {BoxBegin %W %x %y}
+    bind $c <B1-Motion> {BoxDrag %W %x %y}
+    bind $c <ButtonRelease-1> "BoxFinish %W %x %y $p2 $mxmin $mymin $mxmax $mymax $func"
+}
+
+proc BoxBegin {w x y} {
+    global box
+    set box(anchor) [list $x $y]
+    catch {unset box(last)}
+}
+
+proc BoxDrag { w x y} {
+    global  box
+    catch {$w delete $box(last)}
+    set box(last) [eval {$w create rect} $box(anchor) {$x $y -tag box -outline white}]
+}
+
+proc BoxFinish {w x y p2 mxmin mymin mxmax mymax func } {
+    global box
+    set start $box(anchor)
+    set x1 [lrange $start 0 0]
+    set y1 [lrange $start 1 1]
+    catch {$w delete $box(last)}
+# Call the handler function
+    $func $p2 $mxmin $mymin $mxmax $mymax $x1 $y1 $x $y
+}
+
+proc display_image {filename p2 handler} {
+    global __imageno __images
+    set i [image create photo -file $filename]
+    set tl .image$__imageno
+    toplevel $tl 
+    frame $tl.img
+    frame $tl.button
+
+    set width [image width $i]
+    set height [image height $i]
+    canvas $tl.img.c -width [expr {$width+0}] -height [expr {$height+0}]
+    pack $tl.img.c
+    $tl.img.c create image 0 0 -image $i -anchor nw 
+    label $tl.button.label -text $filename 
+    pack $tl.button.label -side left
+    button $tl.button.dismiss -text "Dismiss" -command "dismiss $tl $i" -width 10 
+    pack $tl.button.dismiss -side right
+    pack $tl.img $tl.button -side top -fill x   
+    BoxInit $tl.img.c $p2 [$p2 cget -xmin] [$p2 cget -ymin] [$p2 cget -xmax] [$p2 cget -ymax] $handler
+    bind $tl <Key-q> "dismiss $tl $i"
+    bind $tl <Key-Escape> "dismiss $tl $i"
+
+    # Bind some actions to the canvas
+
+    incr __imageno 1
+}
+
+proc test {} {
+    puts "hello"
+}
+
diff --git a/trunk/Examples/GIFPlot/Tcl/mandel/mandel.i b/trunk/Examples/GIFPlot/Tcl/mandel/mandel.i
new file mode 100644
index 0000000..0b19f47
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/mandel/mandel.i
@@ -0,0 +1,47 @@
+// Special module to run the mandlebrot set
+%module gifplot
+%include gifplot.i
+
+%inline %{
+
+void mandel(Plot2D *p2, int tol) {
+	double scalingx;
+	double scalingy;
+	double zr,zi,ztr,zti,cr,ci;
+	double cscale;
+	int    i,j,n;
+	FrameBuffer *f;
+
+	f = p2->frame;
+	scalingx = (p2->xmax-p2->xmin)/f->width;
+	scalingy = (p2->ymax-p2->ymin)/f->height;
+	
+	cscale = 239.0/tol;
+	printf("working...\n");
+	for (i = 0; i < f->width; i++) {
+	  for (j = 0; j < f->height; j++) {
+	    zr = scalingx*i + p2->xmin;
+	    zi = scalingy*j + p2->ymin;
+	    cr = zr;
+	    ci = zi;
+	    n = 0;
+	    while (n < tol) {
+	      ztr = zr*zr-zi*zi + cr;
+	      zti = 2*zr*zi + ci;
+	      zr = ztr;
+	      zi = zti;
+	      if (ztr*ztr + zti*zti > 20) break;
+	      n = n + 1;
+	    }
+	    
+	    if (n >= tol) FrameBuffer_plot(f,i,j,BLACK);
+	    else FrameBuffer_plot(f,i,j,16+(int) (n*cscale));
+	  }
+	  if ((i % 10) == 0) printf("%d\n",i);
+	}
+
+}
+		
+%}
+	
+
diff --git a/trunk/Examples/GIFPlot/Tcl/mandel/mandel.tcl b/trunk/Examples/GIFPlot/Tcl/mandel/mandel.tcl
new file mode 100644
index 0000000..3e1600b
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/mandel/mandel.tcl
@@ -0,0 +1,170 @@
+catch { load ./gifplot[info sharedlibextension] }
+source display.tcl
+set tcl_precision 17
+set f [FrameBuffer -args 400 400]
+set cmap [ColorMap -args cmap]
+set p2 [Plot2D -args $f -3 -2 1 2]
+
+set xmin -3
+set xmax 1
+set ymin -2.0
+set ymax 2.0
+set tolerance 240
+set filename mandel.gif
+
+# Make a plot from the above parms
+
+proc make_plot {} {
+    global p2 cmap tolerance
+    global xmin ymin xmax ymax filename
+    $p2 setrange $xmin $ymin $xmax $ymax
+    $p2 start
+    . config -cursor watch
+    update
+    mandel $p2 $tolerance
+    . config -cursor arrow
+    [$p2 cget -frame] writeGIF $cmap $filename
+    display_image $filename $p2 set_zoom
+}
+
+
+# Take some screen coordinates and set global min and max values 
+
+proc set_zoom {p2 mxmin mymin mxmax mymax x1 y1 x2 y2} {
+    global xmin ymin xmax ymax
+
+    set frame [$p2 cget -frame]
+    set width [$frame cget -width]
+    set height [$frame cget -height]
+
+    if {$x1 < 0} {set x1 0}
+    if {$x1 > ($width)} {set x1 $width}
+    if {$x2 < 0} {set x2 0}
+    if {$x2 > ($width)} {set x2 $width}
+    if {$x1 < $x2} {set ixmin $x1; set ixmax $x2} {set ixmin $x2; set ixmax $x1}
+
+    if {$y1 < 0} {set y1 0}
+    if {$y1 > ($height)} {set y1 $height}
+    if {$y2 < 0} {set y2 0}
+    if {$y2 > ($height)} {set y2 $height}
+    if {$y1 < $y2} {set iymin $y1; set iymax $y2} {set iymin $y2; set iymax $y1}
+
+    # Now determine new min and max values based on screen location
+
+    set xmin [expr {$mxmin + ($mxmax-$mxmin)*($ixmin)/($width)}]
+    set xmax [expr {$mxmin + ($mxmax-$mxmin)*($ixmax)/($width)}]
+    set ymin [expr {$mymin + ($mymax-$mymin)*(($height)-($iymax))/($height)}]
+    set ymax [expr {$mymin + ($mymax-$mymin)*(($height)-($iymin))/($height)}]
+
+    catch {make_plot}
+}
+
+# Box drag constrained to a square
+proc BoxDrag { w x y} {
+    global box
+    catch {$w delete $box(last)}
+    set x1 [lrange $box(anchor) 0 0]
+    set y1 [lrange $box(anchor) 1 1]
+    set dx [expr {$x - $x1}]
+    set dy [expr {$y - $y1}]
+    if {abs($dy) > abs($dx)} {set dx $dy}
+    set newx [expr {$x1 + $dx}]
+    set newy [expr {$y1 + $dx}]
+    set box(last) [eval {$w create rect} $box(anchor) {$newx $newy -tag box -outline white}]
+}
+
+
+proc BoxFinish {w x y p2 mxmin mymin mxmax mymax func } {
+    global box
+    set start $box(anchor)
+    set x1 [lrange $box(anchor) 0 0]
+    set y1 [lrange $box(anchor) 1 1]
+    set dx [expr {$x - $x1}]
+    set dy [expr {$y - $y1}]
+    if {($dx == 0) || ($dy == 0)} {
+	catch {$w delete $box(last)}
+	return
+    }
+    if {abs($dy) > abs($dx)} {set dx $dy}
+    set newx [expr {$x1 + $dx}]
+    set newy [expr {$y1 + $dx}]
+    $w config -cursor watch
+    update
+# Call the handler function
+    $func $p2 $mxmin $mymin $mxmax $mymax $x1 $y1 $newx $newy
+    catch {$w delete $box(last)}
+    $w config -cursor arrow
+}
+
+
+# Create a few frames
+
+wm title . Mandelbrot
+frame .title -relief groove -borderwidth 1
+label .title.name -text "Mandelbrot Set" 
+button .title.quit -text "Quit" -command "exit"
+button .title.about -text "About" -command "about"
+pack .title.name -side left
+pack .title.quit .title.about -side right
+
+frame .func -relief groove -borderwidth 1
+
+frame .func.xrange
+label .func.xrange.xrlabel -text "X range" -width 12
+entry .func.xrange.xmin -textvar xmin -width 8
+label .func.xrange.xtolabel -text "to"
+entry .func.xrange.xmax -textvar xmax -width 8
+pack  .func.xrange.xrlabel .func.xrange.xmin .func.xrange.xtolabel .func.xrange.xmax -side left
+
+frame .func.yrange
+label .func.yrange.yrlabel -text "Y range" -width 12
+entry .func.yrange.ymin -textvar ymin -width 8
+label .func.yrange.ytolabel -text "to"
+entry .func.yrange.ymax -textvar ymax -width 8
+pack  .func.yrange.yrlabel .func.yrange.ymin .func.yrange.ytolabel .func.yrange.ymax -side left
+
+frame .func.npoints 
+label .func.npoints.label -text "Tolerance " -width 12
+entry .func.npoints.npoints -textvar tolerance -width 8
+scale .func.npoints.scale -from 0 -to 2500 -variable tolerance -orient horizontal -showvalue false \
+                          -sliderlength 13 -bigincrement 10 -resolution 10
+pack .func.npoints.label .func.npoints.npoints .func.npoints.scale -side left
+
+pack .func.xrange .func.yrange .func.npoints -side top -fill x
+
+# Filename dialog
+
+frame .save -relief groove -borderwidth 1
+
+frame .save.file
+label .save.file.label -text "Save as" -width 12
+entry .save.file.filename -textvar filename -width 20
+pack .save.file.label .save.file.filename -side left
+pack .save.file -side left -fill x
+button .save.go -text "Plot" -command "make_plot"
+pack .save.go -side right
+
+bind .save.file.filename <Return> {make_plot}
+
+pack .title .func .save -side top -fill both
+
+proc about { } {
+    toplevel .about -width 350
+
+    message .about.m -text "\
+Mandelbrot Set\n\n\
+Copyright (c) 1997\n\
+Dave Beazley\n\
+University of Utah\n\n\
+Creates a plot of the Mandelbrot set.  Any displayed image can be zoomed by clicking and \
+dragging.  Although the main calculation is written in C, it may take awhile for each \
+image to be calculated (be patient).   Image quality can be improved at the expense of speed \
+by increasing the tolerance value.\n"
+
+button .about.okay -text "Ok" -command {destroy .about}
+
+pack .about.m .about.okay -side top
+focus .about.okay
+}
+
+make_plot
diff --git a/trunk/Examples/GIFPlot/Tcl/simple/Makefile b/trunk/Examples/GIFPlot/Tcl/simple/Makefile
new file mode 100644
index 0000000..752d79c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/simple/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../../..
+SWIG       = $(TOP)/../swig
+SWIGOPT    =
+SRCS       =
+TARGET     = simple
+INTERFACE  = simple.i
+LIBS       = -L../.. -lgifplot
+INCLUDES   = -I../../Include
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	INCLUDES='$(INCLUDES)' LIBS='$(LIBS)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+	rm -f *.gif
+
+check: all
diff --git a/trunk/Examples/GIFPlot/Tcl/simple/README b/trunk/Examples/GIFPlot/Tcl/simple/README
new file mode 100644
index 0000000..d6b291c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/simple/README
@@ -0,0 +1,5 @@
+This is a very minimalistic example in which just a few functions
+and constants from library are wrapped and used to draw some simple
+shapes.  The script 'runme.tcl' runs the example.
+
+
diff --git a/trunk/Examples/GIFPlot/Tcl/simple/runme.tcl b/trunk/Examples/GIFPlot/Tcl/simple/runme.tcl
new file mode 100644
index 0000000..e3f4126
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/simple/runme.tcl
@@ -0,0 +1,27 @@
+# Draw some simple shapes
+puts "Drawing some basic shapes"
+
+catch { load ./simple[info sharedlibextension] simple}
+
+set cmap [new_ColorMap]
+set f    [new_FrameBuffer 400 400]
+
+# Clear the picture
+FrameBuffer_clear $f $BLACK
+
+# Make a red box
+FrameBuffer_box $f 40 40 200 200 $RED
+
+# Make a blue circle
+FrameBuffer_circle $f 200 200 40 $BLUE
+
+# Make green line
+FrameBuffer_line $f 10 390 390 200 $GREEN
+
+# Write an image out to disk
+FrameBuffer_writeGIF $f $cmap image.gif
+puts "Wrote image.gif"
+
+delete_FrameBuffer $f
+delete_ColorMap $cmap
+
diff --git a/trunk/Examples/GIFPlot/Tcl/simple/simple.i b/trunk/Examples/GIFPlot/Tcl/simple/simple.i
new file mode 100644
index 0000000..457bc4c
--- /dev/null
+++ b/trunk/Examples/GIFPlot/Tcl/simple/simple.i
@@ -0,0 +1,38 @@
+/* This example shows a very simple interface wrapping a few 
+   primitive declarations */
+
+%module simple
+%{
+#include "gifplot.h"
+%}
+
+typedef unsigned char Pixel;
+
+/* Here are a few useful functions */
+
+ColorMap    *new_ColorMap(char *filename = 0);
+void         delete_ColorMap(ColorMap *cmap);
+
+FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+void         delete_FrameBuffer(FrameBuffer *frame);
+void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+
+/* And some useful constants */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+
+
+
+
diff --git a/trunk/Examples/Makefile.in b/trunk/Examples/Makefile.in
new file mode 100644
index 0000000..dd334c2
--- /dev/null
+++ b/trunk/Examples/Makefile.in
@@ -0,0 +1,1091 @@
+# ------------------------------------------------------------
+# SWIG Examples Makefile
+#
+# This file is used by the examples to build modules.  Assuming
+# you ran configure, this file will probably work.  However,
+# it's not perfect so you might need to do some hand tweaking.
+#
+# Other notes:
+#
+# 1.   Take a look at the prefixes below.   Since SWIG works with
+#      multiple target languages, you may need to find out where
+#      certain packages have been installed.   Set the prefixes
+#      accordingly.
+#
+# 2.   To use this makefile, simply set SRCS, INTERFACE, INCLUDES, LIBS,
+#      TARGET, and do a
+#           $(MAKE) -f Makefile.template.in SRCS='$(SRCS)' \
+#           INCLUDES='$(INCLUDES) LIBS='$(LIBS)' INTERFACE='$(INTERFACE)' \
+#           TARGET='$(TARGET)' method
+#
+#      'method' describes what is being built.
+#---------------------------------------------------------------
+
+TARGET     =
+CC         = @CC@
+CXX        = @CXX@
+CFLAGS     = @PLATFLAGS@
+prefix     = @prefix@
+exec_prefix= @exec_prefix@
+SRCS       =
+INCLUDES   =
+LIBS       =
+INTERFACE  =
+SWIGOPT    =
+SWIG       = swig
+
+LIBM       = @LIBM@
+LIBC       = @LIBC@
+LIBCRYPT   = @LIBCRYPT@
+SYSLIBS    = $(LIBM) $(LIBC) $(LIBCRYPT)
+LIBPREFIX  =
+
+# RUNTOOL is for use with runtime tools, eg set it to valgrind
+RUNTOOL    =
+# COMPILETOOL is a way to run the compiler under another tool, or more commonly just to stop the compiler executing
+COMPILETOOL=
+
+# X11 options
+
+XLIB       = @XLIBSW@
+XINCLUDE   = @XINCLUDES@
+
+IWRAP      = $(INTERFACE:.i=_wrap.i)
+ISRCS      = $(IWRAP:.i=.c)
+ICXXSRCS   = $(IWRAP:.i=.cxx)
+IOBJS      = $(IWRAP:.i=.@OBJEXT@)
+
+##################################################################
+# Dynamic loading for C++
+# If you are going to be building dynamic loadable modules in C++,
+# you may need to edit this line appropriately.
+#
+# This line works for g++, but I'm not sure what it might be
+# for other C++ compilers
+##################################################################
+
+CPP_DLLIBS = #-L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \
+             -L/usr/local/lib -lg++ -lstdc++ -lgcc
+
+# Solaris workshop 5.0 
+# CPP_DLLIBS = -L/opt/SUNWspro/lib -lCrun
+
+# Symbols used for using shared libraries
+SO=		@SO@
+LDSHARED=	@LDSHARED@
+CCSHARED=	@CCSHARED@
+CXXSHARED=      @CXXSHARED@
+
+# This is used for building shared libraries with a number of C++
+# compilers.   If it doesn't work,  comment it out.
+@TRYLINKINGWITHCXX@
+
+OBJS      = $(SRCS:.c=.@OBJEXT@) $(CXXSRCS:.cxx=.@OBJEXT@)
+
+##################################################################
+#####                       Tcl/Tk                          ######
+##################################################################
+
+# Set these to your local copy of Tcl/Tk.
+
+TCL_INCLUDE = @TCLINCLUDE@
+TCL_LIB     = @TCLLIB@
+TCL_OPTS    = @LIBS@
+TK_OPTS     = -ltk -ltcl @LIBS@
+
+# Extra Tcl specific dynamic linking options
+TCL_DLNK   = @TCLDYNAMICLINKING@
+TCL_SO     = @TCL_SO@
+
+# -----------------------------------------------------------
+# Build a new version of the tclsh shell
+# -----------------------------------------------------------
+
+
+tclsh: $(SRCS)
+	$(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACE)
+	$(CC) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \
+	$(TCL_LIB)  $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET)
+
+tclsh_cpp: $(SRCS)
+	$(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACE)
+	$(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \
+	$(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET)
+
+# -----------------------------------------------------------
+# Build a new copy of wish
+# -----------------------------------------------------------
+
+wish: $(SRCS)
+	$(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACE)
+	$(CC) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \
+	$(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET)
+
+
+wish_cpp: $(SRCS)
+	$(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -lwish.i $(INTERFACE)
+	$(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \
+	$(XINCLUDE) $(TCL_LIB) $(TK_OPTS) $(XLIB) $(LIBS) $(SYSLIBS) -o $(TARGET)
+
+# -----------------------------------------------------------
+# Build a Tcl dynamic loadable module (you might need to tweak this)
+# -----------------------------------------------------------
+
+tcl:  $(SRCS)
+	$(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO)
+
+# -----------------------------------------------------------
+# Build a Tcl7.5 dynamic loadable module for C++
+# -----------------------------------------------------------
+
+tcl_cpp: $(SRCS)
+	$(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO)
+
+# -----------------------------------------------------------------
+# Cleaning the Tcl examples
+# -----------------------------------------------------------------
+
+tcl_clean:
+	rm -f *_wrap* *~ .~* mytclsh@EXEEXT@ 
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                       PERL 5                          ######
+##################################################################
+
+# You need to set this variable to the Perl5 directory containing the
+# files "perl.h", "EXTERN.h" and "XSUB.h".   With Perl5.003, it's
+# usually something like /usr/local/lib/perl5/arch-osname/5.003/CORE.
+
+PERL5_INCLUDE= @PERL5EXT@
+
+# Extra Perl specific dynamic linking options
+PERL5_DLNK   = @PERL5DYNAMICLINKING@
+PERL5_CCFLAGS = @PERL5CCFLAGS@
+
+# ----------------------------------------------------------------
+# Build a Perl5 dynamically loadable module (C)
+# ----------------------------------------------------------------
+
+perl5: $(SRCS)
+	$(SWIG) -perl5 $(SWIGOPT) $(INTERFACE)
+	$(CC) -c -Dbool=char $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) -I$(PERL5_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PERL5_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# ----------------------------------------------------------------
+# Build a Perl5 dynamically loadable module (C++)
+# ----------------------------------------------------------------
+
+perl5_cpp: $(SRCS)
+	$(SWIG) -perl5 -c++ $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) -I$(PERL5_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# ----------------------------------------------------------------
+# Build a module from existing XS C source code.   (ie. from xsubpp).
+# ----------------------------------------------------------------
+perl5_xs: $(SRCS)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(INCLUDES) -I$(PERL5_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(LIBS) -o $(TARGET)$(SO)
+
+# ----------------------------------------------------------------
+# Build a statically linked Perl5 executable
+# ----------------------------------------------------------------
+
+PERL5_LIB    = -L$(PERL5_INCLUDE) -l@PERL5LIB@ @LIBS@ $(SYSLIBS)
+
+perl5_static: $(SRCS)
+	$(SWIG) -perl5 -static -lperlmain.i $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS) -Dbool=char $(SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET)
+
+perl5_static_cpp: $(SRCS)
+	$(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET)
+
+# -----------------------------------------------------------------
+# Cleaning the Perl5 examples
+# -----------------------------------------------------------------
+
+perl5_clean:
+	rm -f *_wrap* *~ .~* myperl@EXEEXT@ *.pm
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                       PYTHON                          ######
+##################################################################
+
+# Make sure these locate your Python installation
+PYTHON_INCLUDE= $(DEFS) @PYINCLUDE@
+PYTHON_LIB    = @PYLIB@
+
+# Extra Python specific dynamic linking options
+PYTHON_DLNK   = @PYTHONDYNAMICLINKING@
+PYTHON_SO     = @PYTHON_SO@
+
+# ----------------------------------------------------------------
+# Build a C dynamically loadable module
+# ----------------------------------------------------------------
+
+python: $(SRCS)
+	$(SWIG) -python $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(PYTHON_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO)
+
+# -----------------------------------------------------------------
+# Build a C++ dynamically loadable module
+# -----------------------------------------------------------------
+
+python_cpp: $(SRCS)
+	$(SWIG) -c++ -python $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO)
+
+# -----------------------------------------------------------------
+# Build statically linked Python interpreter
+#
+# These should only be used in conjunction with the %include embed.i
+# library file
+# -----------------------------------------------------------------
+
+#TKINTER = -L/usr/X11R6.3/lib -L/usr/local/compat/lib -ltk4.0 -ltcl7.4 -lX11
+TKINTER =
+PYTHON_LIBOPTS = @PYLINK@ @LIBS@ $(TKINTER) $(SYSLIBS)
+
+python_static: $(SRCS)
+	$(SWIG) -python -lembed.i $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \
+	$(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET)
+
+python_static_cpp: $(SRCS)
+	$(SWIG) -c++ -python -lembed.i $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \
+	$(PYTHON_INCLUDE) $(LIBS)  -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET)
+
+# -----------------------------------------------------------------
+# Cleaning the python examples
+# -----------------------------------------------------------------
+
+python_clean:
+	rm -f *_wrap* *~ .~* mypython@EXEEXT@ *.pyc
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@ *@PYTHON_SO@
+
+##################################################################
+#####                       OCTAVE                          ######
+##################################################################
+
+# Make sure these locate your Octave installation
+OCTAVE_INCLUDE= $(DEFS) @OCTAVEEXT@
+OCTAVE_LIB    = 
+
+# Extra Octave specific dynamic linking options
+OCTAVE_DLNK   = @OCTAVEDYNAMICLINKING@
+OCTAVE_SO     = @OCTAVE_SO@
+
+# ----------------------------------------------------------------
+# Build a C dynamically loadable module
+# ----------------------------------------------------------------
+
+octave: $(SRCS)
+	$(SWIG) -octave $(SWIGOPT) $(INTERFACE)
+	$(CXX) -g -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE)
+	$(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(INCLUDES) $(OCTAVE_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO)
+
+# -----------------------------------------------------------------
+# Build a C++ dynamically loadable module
+# -----------------------------------------------------------------
+
+octave_cpp: $(SRCS)
+	$(SWIG) -c++ -octave $(SWIGOPT) $(INTERFACE)
+	$(CXX) -g -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE)
+	$(CXXSHARED) -g $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO)
+
+# -----------------------------------------------------------------
+# Cleaning the octave examples
+# -----------------------------------------------------------------
+
+octave_clean:
+	rm -f *_wrap* *~ .~* myoctave@EXEEXT@ *.pyc
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@ *@OCTAVE_SO@
+
+##################################################################
+#####                       GUILE                           ######
+##################################################################
+
+# Make sure these locate your Guile installation
+GUILE_INCLUDE = @GUILEINCLUDE@
+GUILE_LIB     = @GUILELIB@
+GUILE_SO      = @GUILE_SO@
+GUILE_LIBPREFIX = lib
+
+#------------------------------------------------------------------
+# Build a dynamically loaded module with passive linkage and the scm interface
+#------------------------------------------------------------------
+guile: $(SRCS)
+	$(SWIG) -guile -scm -Linkage passive $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ISRCS) $(SRCS)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO)
+
+guile_cpp: $(SRCS)
+	$(SWIG) -c++ -guile -scm -Linkage passive $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO)
+
+guile_externalhdr:
+	$(SWIG) -guile -external-runtime $(TARGET)
+
+#------------------------------------------------------------------
+# Build a dynamically loaded module with passive linkage and the gh interface
+#------------------------------------------------------------------
+guile_gh: $(SRCS)
+	$(SWIG) -guile -gh -Linkage passive $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ISRCS) $(SRCS)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO)
+
+guile_gh_cpp: $(SRCS)
+	$(SWIG) -c++ -guile -gh -Linkage passive $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO)
+
+# -----------------------------------------------------------------
+# Build a dynamically loadable module with passive linkage
+# -----------------------------------------------------------------
+
+guile_passive: $(SRCS)
+	$(SWIG) -guile -Linkage passive $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ISRCS) $(SRCS)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO)
+
+guile_passive_cpp: $(SRCS)
+	$(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO)
+
+# -----------------------------------------------------------------
+# Build statically linked Guile interpreter
+# -----------------------------------------------------------------
+
+GUILE_LIBOPTS = @GUILELINK@ @LIBS@ $(SYSLIBS)
+
+guile_static: $(SRCS)
+	$(SWIG) -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) \
+	  -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \
+	  $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile
+
+guile_static_cpp: $(SRCS)
+	$(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \
+	  -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \
+	  $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile
+
+guile_simple: $(SRCS)
+	$(SWIG) -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) \
+	  $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile
+
+guile_simple_cpp: $(SRCS)
+	$(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \
+	  $(GUILE_INCLUDE) $(LIBS) -L$(GUILE_LIB) $(GUILE_LIBOPTS) -o $(TARGET)-guile
+
+# -----------------------------------------------------------------
+# Cleaning the Guile examples
+# -----------------------------------------------------------------
+
+guile_clean:
+	rm -f *_wrap* *~ .~* my-guile@EXEEXT@ $(TARGET)@EXEEXT@
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@GUILE_SO@
+
+##################################################################
+#####                       JAVA                            ######
+##################################################################
+
+# You need to set this variable to the java directories containing the
+# files "jni.h" and "md.h"
+# usually something like /usr/java/include and /usr/java/include/<arch-osname>.
+JAVA_INCLUDE= @JAVAINC@
+
+# Extra Java specific dynamic linking options
+JAVA_DLNK  = @JAVADYNAMICLINKING@
+JAVA_LIBPREFIX = @JAVALIBRARYPREFIX@
+JAVASO =@JAVASO@
+JAVALDSHARED = @JAVALDSHARED@
+JAVACXXSHARED = @JAVACXXSHARED@
+JAVACFLAGS = @JAVACFLAGS@
+
+# ----------------------------------------------------------------
+# Build a java dynamically loadable module (C)
+# ----------------------------------------------------------------
+
+java: $(SRCS)
+	$(SWIG) -java $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE)
+	$(JAVALDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO)
+
+# ----------------------------------------------------------------
+# Build a java dynamically loadable module (C++)
+# ----------------------------------------------------------------
+
+java_cpp: $(SRCS)
+	$(SWIG) -java -c++ $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE)
+	$(JAVACXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO)
+
+# -----------------------------------------------------------------
+# Cleaning the java examples
+# -----------------------------------------------------------------
+
+java_clean:
+	rm -f *_wrap* *~ .~* *.class `find . -name \*.java | grep -v main.java`
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@JAVASO@
+
+##################################################################
+#####                      MODULA3                          ######
+##################################################################
+
+MODULA3_INCLUDE= @MODULA3INC@
+
+# ----------------------------------------------------------------
+# Build a modula3 dynamically loadable module (C)
+# ----------------------------------------------------------------
+
+modula3: $(SRCS)
+	$(SWIG) -modula3 $(SWIGOPT) $(INTERFACE)
+#	$(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) \
+#       $(OBJS) $(IOBJS) $(LIBS)
+
+modula3_cpp: $(SRCS)
+	$(SWIG) -modula3 -c++ $(SWIGOPT) $(INTERFACE)
+
+# -----------------------------------------------------------------
+# Cleaning the modula3 examples
+# -----------------------------------------------------------------
+
+modula3_clean:
+	rm -f *_wrap* *.i3 *.m3
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                       MZSCHEME                        ######
+##################################################################
+
+MZC = test -n "@MZC@" && @MZC@
+MZDYNOBJ = @MZDYNOBJ@
+MZSCHEME_SO = @MZSCHEME_SO@
+
+# ----------------------------------------------------------------
+# Build a C/C++ dynamically loadable module
+# ----------------------------------------------------------------
+
+mzscheme: $(SRCS)
+	$(SWIG) -mzscheme $(SWIGOPT) $(INTERFACE)
+	$(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ISRCS) $(SRCS)
+	$(MZC) --ld $(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS)
+
+mzscheme_cpp: $(SRCS)
+	$(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACE)
+	$(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCS) $(CXXSRCS)
+	$(CXXSHARED) $(CFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) 
+
+# -----------------------------------------------------------------
+# Cleaning the mzscheme examples
+# -----------------------------------------------------------------
+
+mzscheme_clean:
+	rm -f *_wrap* *~ .~* 
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                          Ocaml                         #####
+##################################################################
+
+OCC=@OCAMLC@
+OCAMLDLGEN=@OCAMLDLGEN@
+OCAMLFIND=@OCAMLFIND@
+OCAMLMKTOP=@OCAMLMKTOP@ $(SWIGWHERE)
+NOLINK ?= false
+OCAMLPP= -pp "camlp4o ./swigp4.cmo"
+OCAMLCORE=\
+	rm -rf swig.mli swig.ml swigp4.ml && \
+	$(SWIG) -ocaml -co swig.mli 2>/dev/null &&  \
+	$(SWIG) -ocaml -co swig.ml 2>/dev/null &&  \
+	$(SWIG) -ocaml -co swigp4.ml 2>/dev/null &&  \
+	$(OCC) -c swig.mli &&  \
+	$(OCC) -c swig.ml &&  \
+	$(OCC) -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" \
+		-c swigp4.ml
+
+ocaml_static: $(SRCS)
+	$(OCAMLCORE)
+	$(SWIG) -ocaml $(SWIGOPT) $(INTERFACE)
+	$(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS)
+	$(OCC) -g -c $(INTERFACE:%.i=%.mli)
+	$(OCC) -g -c $(INTERFACE:%.i=%.ml)
+	test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \
+		$(OCC) $(OCAMLPP) -c $(PROGFILE)
+	$(NOLINK) || $(OCC) -g -ccopt -g -cclib -g -custom -o $(TARGET) \
+		swig.cmo \
+		$(INTERFACE:%.i=%.cmo) \
+		$(PROGFILE:%.ml=%.cmo) \
+		$(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) -cclib "$(LIBS)"
+
+ocaml_dynamic: $(SRCS)
+	$(OCAMLCORE)
+	$(SWIG) -ocaml $(SWIGOPT) $(INTERFACE)
+	$(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS)
+	$(CXXSHARED) $(CFLAGS) $(CCSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \
+		$(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) $(LIBS)
+	$(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \
+		$(INTERFACE:%.i=%_dynamic.ml)
+	mv $(INTERFACE:%.i=%_dynamic.ml) $(INTERFACE:%.i=%.ml)
+	rm $(INTERFACE:%.i=%.mli)
+	$(OCAMLFIND) $(OCC) -g -c -package dl $(INTERFACE:%.i=%.ml)
+	test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \
+		$(OCC) $(OCAMLPP) -c $(PROGFILE)
+	$(NOLINK) || $(OCAMLFIND) \
+		$(OCC) -g -ccopt -g -cclib -g -custom -o $(TARGET) \
+		swig.cmo \
+		-package dl -linkpkg \
+		$(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo)
+
+ocaml_static_toplevel: $(SRCS)
+	$(OCAMLCORE)
+	$(SWIG) -ocaml $(SWIGOPT) $(INTERFACE)
+	$(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS)
+	$(OCC) -g -c $(INTERFACE:%.i=%.mli)
+	$(OCC) -g -c $(INTERFACE:%.i=%.ml)
+	test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \
+		$(OCC) $(OCAMLPP) -c $(PROGFILE)
+	$(NOLINK) || $(OCAMLMKTOP) \
+		swig.cmo \
+		-I `camlp4 -where` camlp4o.cma swigp4.cmo \
+		-g -ccopt -g -cclib -g -custom -o $(TARGET)_top \
+		$(INTERFACE:%.i=%.cmo) \
+		$(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) -cclib "$(LIBS)"
+
+ocaml_static_cpp: $(SRCS)
+	$(OCAMLCORE)
+	$(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACE)
+	cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c)
+	$(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \
+		$(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS)
+	$(OCC) -g -c $(INTERFACE:%.i=%.mli)
+	$(OCC) -g -c $(INTERFACE:%.i=%.ml)
+	test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \
+		$(OCC) $(OCAMLPP) -c $(PROGFILE)
+	$(NOLINK) || $(OCC) -g -ccopt -g -cclib -g -custom -o $(TARGET) \
+		swig.cmo \
+		$(INTERFACE:%.i=%.cmo) \
+		$(PROGFILE:%.ml=%.cmo) \
+		$(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \
+		-cclib "$(LIBS)" -cc '$(CXX)' 
+
+ocaml_static_cpp_toplevel: $(SRCS)
+	$(OCAMLCORE)
+	$(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACE)
+	cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c)
+	$(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \
+		$(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS)
+	$(OCC) -g -c $(INTERFACE:%.i=%.mli)
+	$(OCC) -g -c $(INTERFACE:%.i=%.ml)
+	test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \
+		$(OCC) $(OCAMLPP) -c $(PROGFILE)
+	$(NOLINK) || $(OCAMLMKTOP) \
+		swig.cmo \
+		-I `camlp4 -where` camlp4o.cma swigp4.cmo \
+		-g -ccopt -g -cclib -g -custom -o $(TARGET)_top \
+		$(INTERFACE:%.i=%.cmo) \
+		$(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \
+		-cclib "$(LIBS)" -cc '$(CXX)' 
+
+ocaml_dynamic_cpp: $(SRCS)
+	$(OCAMLCORE)
+	$(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACE)
+	cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c)
+	$(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \
+		$(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) -ccopt -fPIC
+	$(CXXSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \
+		$(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \
+		$(CPP_DLLIBS) $(LIBS)
+	$(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \
+		$(INTERFACE:%.i=%_dynamic.ml)
+	mv $(INTERFACE:%.i=%_dynamic.ml) $(INTERFACE:%.i=%.ml)
+	rm $(INTERFACE:%.i=%.mli)
+	$(OCAMLFIND) $(OCC) -g -c -package dl $(INTERFACE:%.i=%.ml)
+	test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \
+		$(OCC) $(OCAMLPP) -c $(PROGFILE)
+	$(NOLINK) || $(OCAMLFIND) \
+		swig.cmo \
+		$(OCC) -cclib -export-dynamic -g -ccopt -g -cclib -g -custom \
+		-o $(TARGET) \
+		-package dl -linkpkg \
+		$(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo) -cc '$(CXX)'
+
+ocaml_clean:
+	rm -f *_wrap* *~ .~* *.cmo *.cmi $(MLFILE) $(MLFILE)i swig.mli swig.cmi swig.ml swig.cmo swigp4.ml swigp4.cmo
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                       RUBY                            ######
+##################################################################
+
+# Make sure these locate your Ruby installation
+RUBY_CFLAGS= @RUBYCCDLFLAGS@ $(DEFS)
+RUBY_INCLUDE= @RUBYINCLUDE@
+RUBY_LIB     = @RUBYLIB@
+RUBY_DLNK = @RUBYDYNAMICLINKING@
+
+# ----------------------------------------------------------------
+# Build a C dynamically loadable module
+# ----------------------------------------------------------------
+
+ruby: $(SRCS)
+	$(SWIG) -ruby $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(RUBY_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# -----------------------------------------------------------------
+# Build a C++ dynamically loadable module
+# -----------------------------------------------------------------
+
+ruby_cpp: $(SRCS)
+	$(SWIG) -c++ -ruby $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# -----------------------------------------------------------------
+# Build statically linked Ruby interpreter
+#
+# These should only be used in conjunction with the %include embed.i
+# library file
+# -----------------------------------------------------------------
+
+RUBY_LIBOPTS = @RUBYLINK@ @LIBS@ $(SYSLIBS)
+
+ruby_static: $(SRCS)
+	$(SWIG) -ruby -lembed.i $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \
+	$(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET)
+
+ruby_cpp_static: $(SRCS)
+	$(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \
+	$(RUBY_INCLUDE) $(LIBS)  -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET)
+
+
+# -----------------------------------------------------------------
+# Cleaning the Ruby examples
+# -----------------------------------------------------------------
+
+ruby_clean:
+	rm -f *_wrap* *~ .~* myruby@EXEEXT@ *.pm
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                       PHP                             ######
+##################################################################
+
+# -------------------------------------------------------------------
+# Build a PHP4 dynamically loadable module (C)
+# -------------------------------------------------------------------
+
+PHP4_INCLUDE = @PHP4INC@
+PHP4_SO      = @PHP4_SO@
+
+php4: $(SRCS)
+	$(SWIG) -php5 $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(PHP4_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP4_SO)
+
+# --------------------------------------------------------------------
+# Build a PHP4 dynamically loadable module (C++)
+# --------------------------------------------------------------------
+
+php4_cpp: $(SRCS)
+	$(SWIG) -php5 -cppext cxx -c++ $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP4_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP4_SO)
+
+# -----------------------------------------------------------------
+# Running a PHP4 example
+# -----------------------------------------------------------------
+
+PHP4=@PHP4@
+SCRIPT ?= runme.php4
+
+php4_run:
+	env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PHP4) -n -q -d extension_dir=. $(SCRIPT)
+
+# -----------------------------------------------------------------
+# Cleaning the PHP4 examples
+# -----------------------------------------------------------------
+
+php4_clean:
+	rm -f *_wrap* *~ .~* example.php php_example.h
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                       Pike                            ######
+##################################################################
+
+# Make sure these locate your Pike installation
+PIKE_CFLAGS  = @PIKECCDLFLAGS@ -DHAVE_CONFIG_H
+PIKE_INCLUDE = @PIKEINCLUDE@
+PIKE_LIB     = @PIKELIB@
+PIKE_DLNK    = @PIKEDYNAMICLINKING@
+
+# ----------------------------------------------------------------
+# Build a C dynamically loadable module
+# ----------------------------------------------------------------
+
+pike: $(SRCS)
+	$(SWIG) -pike $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(PIKE_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# -----------------------------------------------------------------
+# Build a C++ dynamically loadable module
+# -----------------------------------------------------------------
+
+pike_cpp: $(SRCS)
+	$(SWIG) -c++ -pike $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# -----------------------------------------------------------------
+# Build statically linked Pike interpreter
+#
+# These should only be used in conjunction with the %include embed.i
+# library file
+# -----------------------------------------------------------------
+
+PIKE_LIBOPTS = @PIKELINK@ @LIBS@ $(SYSLIBS)
+
+pike_static: $(SRCS)
+	$(SWIG) -pike -lembed.i $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \
+	$(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET)
+
+pike_cpp_static: $(SRCS)
+	$(SWIG) -c++ -pike -lembed.i $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \
+	$(PIKE_INCLUDE) $(LIBS)  -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET)
+
+# -----------------------------------------------------------------
+# Cleaning the Pike examples
+# -----------------------------------------------------------------
+
+pike_clean:
+	rm -f *_wrap* *~ .~* mypike@EXEEXT@ 
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+
+##################################################################
+#####                      Chicken                          ######
+##################################################################
+
+CHICKEN = @CHICKEN@
+CHICKEN_CSC = @CHICKEN_CSC@
+CHICKEN_LIBOPTS = @CHICKENLIB@  $(SYSLIBS)
+CHICKEN_SHAREDLIBOPTS = @CHICKENSHAREDLIB@  $(SYSLIBS)
+CHICKEN_CFLAGS = @CHICKENOPTS@
+CHICKENOPTS = -quiet
+CHICKEN_MAIN =
+
+# SWIG produces $(ISRCS) (the C wrapper file) 
+# and $(CHICKEN_GENERATED_SCHEME) (the Scheme wrapper file):
+CHICKEN_GENERATED_SCHEME = $(INTERFACE:.i=.scm)
+CHICKEN_COMPILED_SCHEME = $(INTERFACE:.i=_chicken.c)
+CHICKEN_COMPILED_OBJECT = $(CHICKEN_COMPILED_SCHEME:.c=.@OBJEXT@)
+
+# flags for the main chicken sources (only used when compiling staticly)
+CHICKEN_COMPILED_MAIN = $(CHICKEN_MAIN:.scm=_chicken.c)
+CHICKEN_COMPILED_MAIN_OBJECT = $(CHICKEN_COMPILED_MAIN:.c=.@OBJEXT@)
+
+# -----------------------------------------------------------------
+# Build a CHICKEN dynamically loadable module
+# -----------------------------------------------------------------
+
+# This is the old way to build chicken, but it does not work correctly with exceptions
+chicken_direct: $(SRCS)
+	$(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACE)
+	$(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \
+		-dynamic -feature chicken-compile-shared \
+		-output-file $(CHICKEN_COMPILED_SCHEME)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \
+		$(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCS) $(CHICKEN_COMPILED_SCHEME)
+	$(LDSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \
+		$(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+chicken_direct_cpp: $(CXXSRCS) $(CHICKSRCS)
+	$(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACE)
+	$(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \
+		-dynamic -feature chicken-compile-shared \
+		-output-file $(CHICKEN_COMPILED_SCHEME)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \
+		$(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(CHICKEN_COMPILED_SCHEME)
+	$(CXXSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \
+		$(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+# -----------------------------------------------------------------
+# Build statically linked CHICKEN interpreter
+# -----------------------------------------------------------------
+
+# The following two targets are also used by the test suite
+chicken_static: $(SRCS) $(CHICKSRCS)
+	$(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACE)
+	$(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \
+		-output-file $(CHICKEN_COMPILED_SCHEME)
+	$(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \
+		-output-file $(CHICKEN_MAIN:.scm=_chicken.c)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \
+		$(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCS) \
+		$(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN)
+	$(CC) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \
+		$(OBJS) $(IOBJS) $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET)
+
+chicken_static_cpp: $(CXXSRCS) $(CHICKSRCS)
+	$(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACE)
+	$(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \
+		-output-file $(CHICKEN_COMPILED_SCHEME)
+	$(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \
+		-output-file $(CHICKEN_MAIN:.scm=_chicken.c)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \
+		$(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) \
+		$(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN)
+	$(CXX) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \
+		$(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET)
+
+# ----------------------------------------------------------------
+# Build a shared library using csc
+# ----------------------------------------------------------------
+
+chicken:
+	$(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACE)
+	$(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCS) $(ISRCS) -o $(TARGET)$(SO)
+
+chicken_cpp:
+	$(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACE)
+	$(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCS) $(ICXXSRCS) $(CXXSRCS) -o $(TARGET)$(SO)
+
+chicken_externalhdr:
+	$(SWIG) -chicken -external-runtime $(TARGET)
+
+chicken_clean:
+	rm -f *_wrap* *~ .~* *_chicken*
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                      CSHARP                           ######
+##################################################################
+
+# Extra CSharp specific dynamic linking options
+CSHARP_DLNK  = @CSHARPDYNAMICLINKING@
+CSHARP_LIBPREFIX = @CSHARPLIBRARYPREFIX@
+CSHARPCOMPILER = @CSHARPCOMPILER@
+CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@
+CSHARPCFLAGS = @CSHARPCFLAGS@
+CSHARPSO = @CSHARPSO@
+
+# ----------------------------------------------------------------
+# Build a CSharp dynamically loadable module (C)
+# ----------------------------------------------------------------
+
+csharp: $(SRCS)
+	$(SWIG) -csharp $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO)
+
+# ----------------------------------------------------------------
+# Build a CSharp dynamically loadable module (C++)
+# ----------------------------------------------------------------
+
+csharp_cpp: $(SRCS)
+	$(SWIG) -csharp -c++ $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO)
+
+# ----------------------------------------------------------------
+# Compile CSharp files
+# ----------------------------------------------------------------
+
+csharp_compile: $(SRCS)
+	$(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPSRCS)
+
+# -----------------------------------------------------------------
+# Cleaning the CSharp examples
+# -----------------------------------------------------------------
+
+csharp_clean:
+	rm -f *_wrap* *~ .~* runme runme.exe *.exe.mdb gc.log `find . -name \*.cs | grep -v runme.cs`
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@CSHARPSO@
+
+##################################################################
+#####                      LUA                              ######
+##################################################################
+
+# lua flags
+LUA_INCLUDE= @LUAFLAGS@
+LUA_LIB    = @LUALINK@
+
+# Extra specific dynamic linking options
+LUA_DLNK   = @LUADYNAMICLINKING@
+LUA_SO     = @LUA_SO@
+
+# Extra code for lua static link
+LUA_INTERP     = ../lua.c
+
+# ----------------------------------------------------------------
+# Build a C dynamically loadable module
+# ----------------------------------------------------------------
+
+lua: $(SRCS)
+	$(SWIG) -lua $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(LUA_INCLUDE)
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) -o $(LIBPREFIX)$(TARGET)$(LUA_SO)
+
+# -----------------------------------------------------------------
+# Build a C++ dynamically loadable module
+# -----------------------------------------------------------------
+
+lua_cpp: $(SRCS)
+	$(SWIG) -c++ -lua $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(LUA_INCLUDE)
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO)
+
+# -----------------------------------------------------------------
+# Build statically linked Lua interpreter
+# -----------------------------------------------------------------
+
+lua_static: $(SRCS)
+	$(SWIG) -lua -module example $(SWIGOPT) $(INTERFACE)
+	$(CC) $(CFLAGS)  $(ISRCS) $(SRCS) $(LUA_INTERP) $(INCLUDES) \
+	$(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET)
+
+lua_static_cpp: $(SRCS)
+	$(SWIG) -c++ -lua -module example $(SWIGOPT) $(INTERFACE)
+	$(CXX) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(LUA_INTERP) $(INCLUDES) \
+	$(LUA_INCLUDE) $(LIBS)  $(LUA_LIB) -o $(TARGET)
+
+# -----------------------------------------------------------------
+# Cleaning the lua examples
+# -----------------------------------------------------------------
+
+lua_clean:
+	rm -f *_wrap* *~ .~* mylua@EXEEXT@
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                   ALLEGRO CL                          ######
+##################################################################
+
+allegrocl: $(SRCS)
+	$(SWIG) -allegrocl -cwrap $(SWIGOPT) $(INTERFACE)
+	$(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) 
+	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+allegrocl_cpp: $(SRCS)
+	$(SWIG) -c++ -allegrocl $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) 
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+allegrocl_clean:
+	rm -f *_wrap* *~ .~*
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                      CLISP                            ######
+##################################################################
+
+clisp: $(SRCS)
+	$(SWIG) -clisp $(SWIGOPT) $(INTERFACE)
+
+clisp_cpp: $(SRCS)
+	$(SWIG) -c++ -clisp $(SWIGOPT) $(INTERFACE)
+
+clisp_clean:
+	rm -f *_wrap* *~ .~*
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                      CFFI                             ######
+##################################################################
+
+cffi: $(SRCS)
+	$(SWIG) -cffi $(SWIGOPT) $(INTERFACE)
+#	$(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) 
+#	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+cffi_cpp: $(SRCS)
+	$(SWIG) -c++ -cffi $(SWIGOPT) $(INTERFACE)
+	$(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) 
+	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+cffi_clean:
+	rm -f *_wrap* *~ .~*
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                      UFFI                             ######
+##################################################################
+
+uffi: $(SRCS)
+	$(SWIG) -uffi $(SWIGOPT) $(INTERFACE)
+#	$(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) 
+#	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+uffi_cpp: $(SRCS)
+	$(SWIG) -c++ -uffi $(SWIGOPT) $(INTERFACE)
+#	$(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) 
+#	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
+
+uffi_clean:
+	rm -f *_wrap* *~ .~*
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@
+
+##################################################################
+#####                      R                                ######
+##################################################################
+
+R = R
+RCXXSRCS = $(INTERFACE:.i=_wrap.cpp) #Need to use _wrap.cpp for R build system as it does not understand _wrap.cxx
+RRSRC = $(INTERFACE:.i=.R)
+
+r: $(SRCS)
+	$(SWIG) -r $(SWIGOPT) $(INTERFACE)
+	+( PKG_LIBS="$(SRCS)" PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) )
+
+r_cpp: $(CXXSRCS)
+	$(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACE)
+	+( PKG_LIBS="$(CXXSRCS)" PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) )
+
+r_clean:
+	rm -f *_wrap* *~ .~*
+	rm -f core @EXTRA_CLEAN@
+	rm -f *.@OBJEXT@ *@SO@ NAMESPACE
+	rm -f $(RRSRC) runme.Rout .RData
+
diff --git a/trunk/Examples/README b/trunk/Examples/README
new file mode 100644
index 0000000..0747547
--- /dev/null
+++ b/trunk/Examples/README
@@ -0,0 +1,49 @@
+SWIG Examples
+
+The "perl5", "python", "tcl", "guile", "java", "mzscheme", "ruby", and
+"chicken" directories contain a number of simple examples that are
+primarily used for testing. The "GIFPlot" directory contains a more
+complicated example that illustrates some of SWIG's more advanced
+capabilities.
+
+The file 'index.html' is the top of a hyperlinked document that
+contains information about all of the examples along with various
+notes related to each example.
+
+The Examples directory is currently quite incomplete because it
+is being reorganized.  A more complete set of examples can be found
+in the SWIG1.1p5 distribution (most of which should still work with
+SWIG1.3).
+
+Note: All of the examples rely upon the Makefile in this directory.
+You may need to edit it to reflect the configuration of your machine
+in case the configure script guesses incorrect settings.
+
+
+*** Special note concering C++ ***
+
+The configure script is currently unable to handle all of the possible
+options for producing dynamically loadable C++ extensions.  Here are
+the rules of thumb for making C++ work:
+
+ -  Try using the C++ as the linker for the shared library.  For example:
+
+         g++ -shared $(OBJS) -o module.so
+
+ -  If that doesn't work, you may need to explicitly link against some
+    kind of C++ runtime library.  For example:
+
+         ld -G $(OBJS) -L/opt/SUNWspro/lib -lCrun -o module.so
+
+    This can be set by modifying the setting of CPP_DLLIBS in the
+    Makefile.
+
+
+*** Special note for SWIG Maintainers ***
+
+When you add an example, consider arranging for the example to be also
+useful as part of the SWIG testing framework.  To do this, include in
+the example makefile a target "check" ("check: all" is sufficient for a
+first pass), and add an invocation to ../Makefile.in under target
+"check-examples" (or whatever is appropriate).  Later, we can add or
+expand the actions under target "check" to do more in-depth testing.
diff --git a/trunk/Examples/chicken/README b/trunk/Examples/chicken/README
new file mode 100644
index 0000000..d4f91ba
--- /dev/null
+++ b/trunk/Examples/chicken/README
@@ -0,0 +1,12 @@
+This directory contains examples for CHICKEN.
+
+class       -- illustrates the proxy class C++ interface
+constants   -- handling #define and %constant literals
+egg         -- examples of building chicken extension libraries
+multimap    -- typemaps with multiple sub-types
+overload    -- C++ function overloading
+simple      -- the simple example from the user manual
+zlib        -- a wrapping of the zlib compression library
+
+You should be able to run make in each of the examples.  By default, a shared
+library will be built.  Run make check to execute the test.
diff --git a/trunk/Examples/chicken/check.list b/trunk/Examples/chicken/check.list
new file mode 100644
index 0000000..9ea022b
--- /dev/null
+++ b/trunk/Examples/chicken/check.list
@@ -0,0 +1,6 @@
+# see top-level Makefile.in
+class
+constants
+multimap
+overload
+simple
diff --git a/trunk/Examples/chicken/class/Makefile b/trunk/Examples/chicken/class/Makefile
new file mode 100644
index 0000000..1261ec5
--- /dev/null
+++ b/trunk/Examples/chicken/class/Makefile
@@ -0,0 +1,38 @@
+TOP         = ../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = example.i
+SRCS        = 
+CXXSRCS     = example.cxx
+TARGET      = class
+INCLUDE     =
+SWIGOPT     =
+CFLAGS      = 
+VARIANT     =
+
+# uncomment the following lines to build a static exe (only pick one of the CHICKEN_MAIN lines)
+#CHICKEN_MAIN = test-lowlevel-class.scm
+#CHICKEN_MAIN = test-tinyclos-class.scm
+#VARIANT      = _static
+
+all:: $(TARGET) $(TARGET)_proxy
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp
+
+$(TARGET)_proxy: $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT) -proxy' TARGET='$(TARGET)_proxy' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f example.scm
+	rm -f $(TARGET)
+
+check::
+	env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH csi test-lowlevel-class.scm
+	env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH csi test-tinyclos-class.scm
diff --git a/trunk/Examples/chicken/class/example.cxx b/trunk/Examples/chicken/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/chicken/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/chicken/class/example.h b/trunk/Examples/chicken/class/example.h
new file mode 100644
index 0000000..210ba98
--- /dev/null
+++ b/trunk/Examples/chicken/class/example.h
@@ -0,0 +1,46 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+
+  enum SomeEnum {
+    First = 0,
+    Second,
+    Third,
+    Last = 1000
+  };
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/chicken/class/example.i b/trunk/Examples/chicken/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/chicken/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/chicken/class/test-lowlevel-class.scm b/trunk/Examples/chicken/class/test-lowlevel-class.scm
new file mode 100644
index 0000000..7c59c0a
--- /dev/null
+++ b/trunk/Examples/chicken/class/test-lowlevel-class.scm
@@ -0,0 +1,76 @@
+;; This file illustrates the low-level C++ interface generated
+;; by SWIG.
+
+(load-library 'example "class.so")
+(declare (uses example))
+
+;; ----- Object creation -----
+
+(display "Creating some objects:\n")
+(define c (new-Circle 10.0))
+(display "    Created circle ")
+(display c)
+(display "\n")
+(define s (new-Square 10.0))
+(display "    Created square ")
+(display s)
+(display "\n")
+
+;; ----- Access a static member -----
+
+(display "\nA total of ")
+(display (Shape-nshapes))
+(display " shapes were created\n")
+
+;; ----- Member data access -----
+
+;; Set the location of the object
+
+(Shape-x-set c 20.0)
+(Shape-y-set c 30.0)
+
+(Shape-x-set s -10.0)
+(Shape-y-set s 5.0)
+
+(display "\nHere is their current position:\n")
+(display "    Circle = (")
+(display (Shape-x-get c))
+(display ", ")
+(display (Shape-y-get c))
+(display ")\n")
+(display "    Square = (")
+(display (Shape-x-get s))
+(display ", ")
+(display (Shape-y-get s))
+(display ")\n")
+
+;; ----- Call some methods -----
+
+(display "\nHere are some properties of the shapes:\n")
+(let
+    ((disp (lambda (o)
+             (display "   ")
+             (display o)
+             (display "\n")
+             (display "        area      = ")
+             (display (Shape-area o))
+             (display "\n")
+             (display "        perimeter = ")
+             (display (Shape-perimeter o))
+             (display "\n"))))
+  (disp c)
+  (disp s))
+
+(display "\nGuess I'll clean up now\n")
+
+;; Note: this invokes the virtual destructor
+(set! c #f)
+(set! s #f)
+(gc #t)
+
+(set! s 3)
+(display (Shape-nshapes))
+(display " shapes remain\n")
+(display "Goodbye\n")
+
+(exit)
diff --git a/trunk/Examples/chicken/class/test-tinyclos-class.scm b/trunk/Examples/chicken/class/test-tinyclos-class.scm
new file mode 100644
index 0000000..5ba1d6a
--- /dev/null
+++ b/trunk/Examples/chicken/class/test-tinyclos-class.scm
@@ -0,0 +1,76 @@
+;; This file illustrates the proxy C++ interface generated
+;; by SWIG.
+
+(load-library 'example "class_proxy.so")
+(declare (uses example))
+(declare (uses tinyclos))
+
+;; ----- Object creation -----
+
+(display "Creating some objects:\n")
+(define c (make <Circle> 10.0))
+(display "    Created circle ")
+(display c)
+(display "\n")
+(define s (make <Square> 10.0))
+(display "    Created square ")
+(display s)
+(display "\n")
+
+;; ----- Access a static member -----
+
+(display "\nA total of ")
+(display (Shape-nshapes))
+(display " shapes were created\n")
+
+;; ----- Member data access -----
+
+;; Set the location of the object
+
+(slot-set! c 'x 20.0)
+(slot-set! c 'y 30.0)
+
+(slot-set! s 'x -10.0)
+(slot-set! s 'y 5.0)
+
+(display "\nHere is their current position:\n")
+(display "    Circle = (")
+(display (slot-ref c 'x))
+(display ", ")
+(display (slot-ref c 'y))
+(display ")\n")
+(display "    Square = (")
+(display (slot-ref s 'x))
+(display ", ")
+(display (slot-ref s 'y))
+(display ")\n")
+
+;; ----- Call some methods -----
+
+(display "\nHere are some properties of the shapes:\n")
+(let
+    ((disp (lambda (o)
+             (display "   ")
+             (display o)
+             (display "\n")
+             (display "        area      = ")
+             (display (area o))
+             (display "\n")
+             (display "        perimeter = ")
+             (display (perimeter o))
+             (display "\n"))))
+  (disp c)
+  (disp s))
+
+(display "\nGuess I'll clean up now\n")
+
+;; Note: Invoke the virtual destructors by forcing garbage collection
+(set! c 77)
+(set! s 88)
+(gc #t)
+
+(display (Shape-nshapes))
+(display " shapes remain\n")
+(display "Goodbye\n")
+
+(exit)
diff --git a/trunk/Examples/chicken/constants/Makefile b/trunk/Examples/chicken/constants/Makefile
new file mode 100644
index 0000000..81308fc
--- /dev/null
+++ b/trunk/Examples/chicken/constants/Makefile
@@ -0,0 +1,30 @@
+TOP         = ../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = example.i
+SRCS        =
+CXXSRCS     = 
+TARGET      = constants
+INCLUDE     =
+SWIGOPT     = 
+CFLAGS      = 
+VARIANT     = 
+
+# uncomment the following two lines to build a static exe
+#CHICKEN_MAIN = test-constants.scm
+#VARIANT      = _static
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f example.scm
+	rm -f $(TARGET)
+
+check::
+	csi test-constants.scm
diff --git a/trunk/Examples/chicken/constants/example.i b/trunk/Examples/chicken/constants/example.i
new file mode 100644
index 0000000..0995c19
--- /dev/null
+++ b/trunk/Examples/chicken/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants.  Remember that
+   CHICKEN is normally case-insensitive, so don't rely on differing
+   case to differentiate variable names */
+
+%constant int iconstX = 37;
+%constant double fconstX = 3.14;
diff --git a/trunk/Examples/chicken/constants/test-constants.scm b/trunk/Examples/chicken/constants/test-constants.scm
new file mode 100644
index 0000000..1b10b26
--- /dev/null
+++ b/trunk/Examples/chicken/constants/test-constants.scm
@@ -0,0 +1,16 @@
+;; feel free to uncomment and comment sections
+
+(load-library 'example "./constants.so")
+
+(display "starting test ... you will see 'finished' if successful.\n")
+(or (= (ICONST) 42) (exit 1))
+(or (< (abs (- (FCONST) 2.1828)) 0.00001) (exit 1))
+(or (char=? (CCONST) #\x) (exit 1))
+(or (char=? (CCONST2) #\newline) (exit 1))
+(or (string=? (SCONST) "Hello World") (exit 1))
+(or (string=? (SCONST2) "\"Hello World\"") (exit 1))
+(or (< (abs (- (EXPR) (+ (ICONST) (* 3 (FCONST))))) 0.00001) (exit 1))
+(or (= (iconstX) 37) (exit 1))
+(or (< (abs (- (fconstX) 3.14)) 0.00001) (exit 1))
+(display "finished test.\n")
+(exit 0)
diff --git a/trunk/Examples/chicken/egg/Makefile b/trunk/Examples/chicken/egg/Makefile
new file mode 100644
index 0000000..bdf71b1
--- /dev/null
+++ b/trunk/Examples/chicken/egg/Makefile
@@ -0,0 +1,39 @@
+SWIG = ../../../preinst-swig
+
+all: single multi
+
+# This creates an egg which contains only the single module.  Any additional implementation files
+# that implement the interface being wrapped should also be added to this egg
+single: single_wrap.cxx
+	mkdir -p eggs
+	tar czf eggs/single.egg single.setup single.scm single_wrap.cxx
+	rm -f single.scm single_wrap.cxx
+
+# complie the single module with -nounit
+single_wrap.cxx: single.i
+	$(SWIG) -chicken -c++ -proxy -nounit single.i
+
+# Now build both mod1 and mod2 into a single egg
+multi: mod1_wrap.cxx mod2_wrap.cxx
+	mkdir -p eggs
+	tar czf eggs/multi.egg multi.setup multi_init.scm mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx
+	rm -f mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx
+
+mod1_wrap.cxx: mod1.i
+	$(SWIG) -chicken -c++ -proxy mod1.i
+
+mod2_wrap.cxx: mod2.i
+	$(SWIG) -chicken -c++ -proxy mod2.i
+
+clean:
+	rm -rf eggs
+
+# this part is for testing...
+setup:
+	cd eggs && \
+	mkdir -p install && \
+	chicken-setup -repository `pwd`/install single.egg && \
+	chicken-setup -repository `pwd`/install multi.egg
+
+check:
+	cd eggs/install && csi ../../test.scm
diff --git a/trunk/Examples/chicken/egg/README b/trunk/Examples/chicken/egg/README
new file mode 100644
index 0000000..b5df0e6
--- /dev/null
+++ b/trunk/Examples/chicken/egg/README
@@ -0,0 +1,19 @@
+These examples show how to build a chicken extension module in the form of an
+egg.  There are two eggs that get built, single.egg which contains a single
+module which is built with -nounit and multi.egg, which contains two modules
+mod1 and mod2.  These are built normally, and multi_init.scm loads them both.
+Read section "17.4.2 Building chicken extension libraries" in the manual
+for a description of these two techniques.
+
+To build:
+
+$ make
+$ make setup
+$ make run
+
+$ make clean
+
+The eggs are built into an eggs subdirectory, because chicken-setup has
+problems installing eggs when there are other files named similar in
+the same directory.  The make setup step runs chicken-setup to install
+the eggs into the eggs/install directory.
diff --git a/trunk/Examples/chicken/egg/mod1.i b/trunk/Examples/chicken/egg/mod1.i
new file mode 100644
index 0000000..6a2940b
--- /dev/null
+++ b/trunk/Examples/chicken/egg/mod1.i
@@ -0,0 +1,8 @@
+%module mod1
+
+%inline %{
+class Bar {
+  public:
+    int b;
+};
+%}
diff --git a/trunk/Examples/chicken/egg/mod2.i b/trunk/Examples/chicken/egg/mod2.i
new file mode 100644
index 0000000..e9ae4a6
--- /dev/null
+++ b/trunk/Examples/chicken/egg/mod2.i
@@ -0,0 +1,17 @@
+%module mod2
+
+%import "mod1.i"
+
+%{
+class Bar {
+  public:
+    int b;
+};
+%}
+
+%inline %{
+  class Bar2 : public Bar {
+    public:
+      int c;
+  };
+%}
diff --git a/trunk/Examples/chicken/egg/multi.setup b/trunk/Examples/chicken/egg/multi.setup
new file mode 100644
index 0000000..95aeb00
--- /dev/null
+++ b/trunk/Examples/chicken/egg/multi.setup
@@ -0,0 +1,2 @@
+(run (csc -s -o multi.so multi_init.scm mod1.scm mod1_wrap.cxx mod2.scm mod2_wrap.cxx))
+(install-extension 'multi '("multi.so"))
diff --git a/trunk/Examples/chicken/egg/multi_init.scm b/trunk/Examples/chicken/egg/multi_init.scm
new file mode 100644
index 0000000..600491d
--- /dev/null
+++ b/trunk/Examples/chicken/egg/multi_init.scm
@@ -0,0 +1,2 @@
+(declare (uses mod1))
+(declare (uses mod2))
diff --git a/trunk/Examples/chicken/egg/single.i b/trunk/Examples/chicken/egg/single.i
new file mode 100644
index 0000000..46266b4
--- /dev/null
+++ b/trunk/Examples/chicken/egg/single.i
@@ -0,0 +1,8 @@
+%module single
+
+%inline %{
+class Foo {
+  public:
+    int a;
+};
+%}
diff --git a/trunk/Examples/chicken/egg/single.setup b/trunk/Examples/chicken/egg/single.setup
new file mode 100644
index 0000000..4b503ec
--- /dev/null
+++ b/trunk/Examples/chicken/egg/single.setup
@@ -0,0 +1,2 @@
+(run (csc -s -o single.so single.scm single_wrap.cxx))
+(install-extension 'single '("single.so"))
diff --git a/trunk/Examples/chicken/egg/test.scm b/trunk/Examples/chicken/egg/test.scm
new file mode 100644
index 0000000..4ec94ed
--- /dev/null
+++ b/trunk/Examples/chicken/egg/test.scm
@@ -0,0 +1,18 @@
+(require-extension single)
+(require-extension multi)
+
+(define f (make <Foo>))
+(slot-set! f 'a 3)
+(print (slot-ref f 'a))
+
+(define b (make <Bar>))
+(slot-set! b 'b 2)
+(print (slot-ref b 'b))
+
+(define b2 (make <Bar2>))
+(slot-set! b2 'b 4)
+(slot-set! b2 'c 6)
+(print (slot-ref b2 'b))
+(print (slot-ref b2 'c))
+
+(exit 0)
diff --git a/trunk/Examples/chicken/multimap/Makefile b/trunk/Examples/chicken/multimap/Makefile
new file mode 100644
index 0000000..dace61a
--- /dev/null
+++ b/trunk/Examples/chicken/multimap/Makefile
@@ -0,0 +1,30 @@
+TOP         = ../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = example.i
+SRCS        = example.c
+CXXSRCS     = 
+TARGET      = multimap
+INCLUDE     =
+SWIGOPT     = 
+CFLAGS      = 
+VARIANT     = 
+
+# uncomment the following two lines to build a static exe
+#CHICKEN_MAIN = test-multimap.scm
+#VARIANT      = _static
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f example.scm
+	rm -f $(TARGET)
+
+check::
+	env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH csi test-multimap.scm
diff --git a/trunk/Examples/chicken/multimap/example.c b/trunk/Examples/chicken/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/chicken/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/chicken/multimap/example.i b/trunk/Examples/chicken/multimap/example.i
new file mode 100644
index 0000000..02567f4
--- /dev/null
+++ b/trunk/Examples/chicken/multimap/example.i
@@ -0,0 +1,96 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+%include typemaps.i
+
+extern int    gcd(int x, int y);
+
+%typemap(in) (int argc, char *argv[]) {
+  int i;
+  if (!C_swig_is_vector ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a vector");
+  }
+  $1 = C_header_size ($input);
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i < $1; i++) {
+    C_word o = C_block_item ($input, i);
+    if (!C_swig_is_string (o)) {
+      char err[50];
+      free($2);
+      sprintf (err, "$input[%d] is not a string", i);
+      swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, err);
+    }
+    $2[i] = C_c_string (o);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char *argv[]) {
+  free($2);
+}
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string");
+  }	
+  $1 = C_c_string ($input);
+  $2 = C_header_size ($input);
+}
+
+extern int count(char *bytes, int len, char c);
+
+
+/* This example shows how to wrap a function that mutates a string */
+
+%typemap(in) (char *str, int len) 
+%{  if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string");
+  }
+  $2 = C_header_size ($input);
+  $1 = (char *) malloc ($2+1);
+  memmove ($1, C_c_string ($input), $2);
+%}
+
+/* Return the mutated string as a new object.  Notice the if MANY construct ... they must be at column 0. */
+
+%typemap(argout) (char *str, int len) (C_word *scmstr) 
+%{  scmstr = C_alloc (C_SIZEOF_STRING ($2));
+  SWIG_APPEND_VALUE(C_string (&scmstr, $2, $1));
+  free ($1);
+%}
+
+extern void capitalize (char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+  double a = $1*$1 + $2*$2;
+  if (a > 1.0) {
+    SWIG_exception (SWIG_ValueError, "cx and cy must be in unit circle");
+  }
+}
+
+extern void circle (double cx, double cy);
+
+/* Test out multiple return values */
+
+extern int squareCubed (int n, int *OUTPUT);
+%{
+/* Returns n^3 and set n2 to n^2 */
+int squareCubed (int n, int *n2) {
+  *n2 = n * n;
+  return (*n2) * n;
+};
+%}
diff --git a/trunk/Examples/chicken/multimap/test-multimap.scm b/trunk/Examples/chicken/multimap/test-multimap.scm
new file mode 100644
index 0000000..3a6b46e
--- /dev/null
+++ b/trunk/Examples/chicken/multimap/test-multimap.scm
@@ -0,0 +1,59 @@
+;; run with './multimap test-multimap.scm'
+;; feel free to uncomment and comment sections
+
+(load-library 'example "multimap.so")
+
+(display "(gcd 90 12): ")
+(display (gcd 90 12))
+(display "\n")
+
+(display "(circle 0.5 0.5): ")
+(display (circle 0.5 0.5))
+(display "\n")
+
+(display "(circle 1.0 1.0): ")
+(handle-exceptions exvar
+  (if (= (car exvar) 9)
+    (display "success: exception thrown")
+    (display "an incorrect exception was thrown"))
+  (begin
+    (circle 1.0 1.0)
+    (display "an exception was not thrown when it should have been")))
+(display "\n")
+
+(display "(circle 1 1): ")
+(handle-exceptions exvar
+  (if (= (car exvar) 9)
+    (display "success: exception thrown")
+    (display "an incorrect exception was thrown"))
+  (begin
+    (circle 1 1)
+    (display "an exception was not thrown when it should have been")))
+(display "\n")
+
+(display "(capitalize \"will this be all capital letters?\"): ")
+(display (capitalize "will this be all capital letters?"))
+(display "\n")
+
+(display "(count \"jumpity little spider\" #\\t): ")
+(display (count "jumpity little spider" #\t))
+(display "\n")
+
+(display "(gcdmain '#(\"hi\" \"there\")): ")
+(display (gcdmain '#("hi" "there")))
+(display "\n")
+
+(display "(gcdmain '#(\"gcd\" \"9\" \"28\")): ")
+(gcdmain '#("gcd" "9" "28"))
+(display "\n")
+
+(display "(gcdmain '#(\"gcd\" \"12\" \"90\")): ")
+(gcdmain '#("gcd" "12" "90"))
+(display "\n")
+
+(display "squarecubed 3: ")
+(call-with-values (lambda() (squareCubed 3)) 
+		  (lambda (a b) (printf "~A ~A" a b)))
+(display "\n")
+
+(exit)
diff --git a/trunk/Examples/chicken/overload/Makefile b/trunk/Examples/chicken/overload/Makefile
new file mode 100644
index 0000000..48ec43a
--- /dev/null
+++ b/trunk/Examples/chicken/overload/Makefile
@@ -0,0 +1,30 @@
+TOP         = ../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = example.i
+SRCS        = 
+CXXSRCS     = example.cxx
+TARGET      = overload
+INCLUDE     =
+SWIGOPT     = -proxy -unhideprimitive
+CFLAGS      = 
+VARIANT     = 
+
+# uncomment the following lines to build a static exe
+#CHICKEN_MAIN = test-overload.scm
+#VARIANT      = _static
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f example.scm
+	rm -f $(TARGET)
+
+check::
+	env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH csi test-overload.scm
diff --git a/trunk/Examples/chicken/overload/README b/trunk/Examples/chicken/overload/README
new file mode 100644
index 0000000..9487c3f
--- /dev/null
+++ b/trunk/Examples/chicken/overload/README
@@ -0,0 +1,2 @@
+Overloading example from Chapter 5.14 of SWIG Core Documentation for
+version 1.3.
diff --git a/trunk/Examples/chicken/overload/example.cxx b/trunk/Examples/chicken/overload/example.cxx
new file mode 100644
index 0000000..65e7439
--- /dev/null
+++ b/trunk/Examples/chicken/overload/example.cxx
@@ -0,0 +1,33 @@
+/* File : example.c */
+
+#include "example.h"
+#include <stdio.h>
+
+void foo(int x) {
+  printf("x is %d\n", x);
+}
+
+void foo(char *x) {
+  printf("x is '%s'\n", x);
+}
+
+Foo::Foo () {
+  myvar = 55;
+  printf ("Foo constructor called\n");
+}
+
+Foo::Foo (const Foo &) {
+  myvar = 66;
+  printf ("Foo copy constructor called\n");
+}
+
+void Foo::bar (int x) {
+  printf ("Foo::bar(x) method ... \n");
+  printf("x is %d\n", x);
+}
+
+void Foo::bar (char *s, int y) {
+  printf ("Foo::bar(s,y) method ... \n");
+  printf ("s is '%s'\n", s);
+  printf ("y is %d\n", y);
+}
diff --git a/trunk/Examples/chicken/overload/example.h b/trunk/Examples/chicken/overload/example.h
new file mode 100644
index 0000000..1c135d5
--- /dev/null
+++ b/trunk/Examples/chicken/overload/example.h
@@ -0,0 +1,14 @@
+/* File : example.h */
+
+extern void foo (int x);
+extern void foo (char *x);
+
+class Foo {
+ private:
+  int myvar;
+ public:
+  Foo();
+  Foo(const Foo &);   // Copy constructor
+  void bar(int x);
+  void bar(char *s, int y);
+};
diff --git a/trunk/Examples/chicken/overload/example.i b/trunk/Examples/chicken/overload/example.i
new file mode 100644
index 0000000..23a2998
--- /dev/null
+++ b/trunk/Examples/chicken/overload/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let "Foo" objects be converted back and forth from TinyCLOS into
+   low-level CHICKEN SWIG procedures */
+
+%typemap(clos_in) Foo * = SIMPLE_CLOS_OBJECT *;
+%typemap(clos_out) Foo * = SIMPLE_CLOS_OBJECT *;
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/chicken/overload/test-overload.scm b/trunk/Examples/chicken/overload/test-overload.scm
new file mode 100644
index 0000000..168490f
--- /dev/null
+++ b/trunk/Examples/chicken/overload/test-overload.scm
@@ -0,0 +1,45 @@
+;; This file demonstrates the overloading capabilities of SWIG
+
+(load-library 'example "overload.so")
+
+;; Low level
+;; ---------
+
+(display "
+Trying low level code ...
+  (foo 1)
+  (foo \"some string\")
+  (define A-FOO (new-Foo))
+  (define ANOTHER-FOO (new-Foo A-FOO)) ;; copy constructor
+  (Foo-bar A-FOO 2)
+  (Foo-bar ANOTHER-FOO \"another string\" 3)
+")
+
+(primitive:foo 1)
+(primitive:foo "some string")
+(define A-FOO (slot-ref (primitive:new-Foo) 'swig-this))
+(define ANOTHER-FOO (slot-ref (primitive:new-Foo A-FOO) 'swig-this)) ;; copy constructor
+(primitive:Foo-bar A-FOO 2)
+(primitive:Foo-bar ANOTHER-FOO "another string" 3)
+
+;; TinyCLOS
+;; --------
+
+(display "
+Trying TinyCLOS code ...
+  (+foo+ 1)
+  (+foo+ \"some string\")
+  (define A-FOO (make <Foo>))
+  (define ANOTHER-FOO (make <Foo> A-FOO)) ;; copy constructor
+  (-bar- A-FOO 2)
+  (-bar- ANOTHER-FOO \"another string\" 3)
+")
+
+(foo 1)
+(foo "some string")
+(define A-FOO (make <Foo>))
+(define ANOTHER-FOO (make <Foo> A-FOO)) ;; copy constructor
+(bar A-FOO 2)
+(bar ANOTHER-FOO "another string" 3)
+
+(exit)
diff --git a/trunk/Examples/chicken/simple/Makefile b/trunk/Examples/chicken/simple/Makefile
new file mode 100644
index 0000000..bb78142
--- /dev/null
+++ b/trunk/Examples/chicken/simple/Makefile
@@ -0,0 +1,30 @@
+TOP         = ../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = example.i
+SRCS        = example.c
+CXXSRCS     = 
+TARGET      = simple
+INCLUDE     =
+SWIGOPT     = 
+CFLAGS      = 
+VARIANT     = 
+
+# uncomment the following two lines to build a static exe
+#CHICKEN_MAIN = test-simple.scm
+#VARIANT      = _static
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f example.scm example-generic.scm example-clos.scm
+	rm -f $(TARGET)
+
+check::
+	env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH csi test-simple.scm
diff --git a/trunk/Examples/chicken/simple/README b/trunk/Examples/chicken/simple/README
new file mode 100644
index 0000000..07e8da0
--- /dev/null
+++ b/trunk/Examples/chicken/simple/README
@@ -0,0 +1 @@
+Simple example from users manual.
diff --git a/trunk/Examples/chicken/simple/example.c b/trunk/Examples/chicken/simple/example.c
new file mode 100644
index 0000000..f2b0747
--- /dev/null
+++ b/trunk/Examples/chicken/simple/example.c
@@ -0,0 +1,24 @@
+/* Simple example from documentation */
+/* File : example.c */
+
+#include <time.h>
+
+double My_variable = 3.0;
+
+/* Compute factorial of n */
+int fact(int n) {
+  if (n <= 1) return 1;
+  else return n*fact(n-1);
+}
+
+/* Compute n mod m */
+int my_mod(int n, int m) {
+  return (n % m);
+}
+
+
+char *get_time() {
+    long            ltime;
+    time(&ltime);
+    return ctime(&ltime);
+}
diff --git a/trunk/Examples/chicken/simple/example.i b/trunk/Examples/chicken/simple/example.i
new file mode 100644
index 0000000..5b3e955
--- /dev/null
+++ b/trunk/Examples/chicken/simple/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+%}
+
+%include typemaps.i
+
+%rename(mod) my_mod;
+
+%inline %{
+extern double My_variable;
+extern int    fact(int);
+extern int    my_mod(int n, int m);
+extern char   *get_time();
+%}
diff --git a/trunk/Examples/chicken/simple/test-simple.scm b/trunk/Examples/chicken/simple/test-simple.scm
new file mode 100644
index 0000000..05aa870
--- /dev/null
+++ b/trunk/Examples/chicken/simple/test-simple.scm
@@ -0,0 +1,28 @@
+;; feel free to uncomment and comment sections
+(load-library 'example "simple.so")
+
+(display "(My-variable): ")
+(display (My-variable))
+(display "\n")
+
+(display "(My-variable 3.141259): ")
+(display (My-variable 3.141259))
+(display "\n")
+
+(display "(My-variable): ")
+(display (My-variable))
+(display "\n")
+
+(display "(fact 5): ")
+(display (fact 5))
+(display "\n")
+
+(display "(mod 75 7): ")
+(display (mod 75 7))
+(display "\n")
+
+(display "(get-time): ")
+(display (get-time))
+(display "\n")
+
+(exit)
diff --git a/trunk/Examples/chicken/zlib/Makefile b/trunk/Examples/chicken/zlib/Makefile
new file mode 100644
index 0000000..7207014
--- /dev/null
+++ b/trunk/Examples/chicken/zlib/Makefile
@@ -0,0 +1,28 @@
+TOP         = ../..
+SWIG        = $(TOP)/../preinst-swig
+INTERFACE   = example.i
+SRCS        =
+CXXSRCS     = 
+TARGET      = zlib
+INCLUDE     =
+SWIGOPT     = -I/usr/include
+CFLAGS      = 
+VARIANT     = 
+LIBS        = -lz
+VARIANT     = _direct
+
+all:: $(TARGET)
+
+$(TARGET): $(INTERFACE) $(SRCS)
+	$(MAKE) -f $(TOP)/Makefile \
+		SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' \
+		INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='$(TARGET)' \
+		SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile chicken_clean
+	rm -f example.scm
+	rm -f $(TARGET)
+
+check::
+	csi test-zlib.scm
diff --git a/trunk/Examples/chicken/zlib/README.html b/trunk/Examples/chicken/zlib/README.html
new file mode 100644
index 0000000..b082a31
--- /dev/null
+++ b/trunk/Examples/chicken/zlib/README.html
@@ -0,0 +1,1666 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+<html>
+  <head>
+    <title>zlib - Chicken - SWIG example</title>
+  </head>
+  <body>
+    <center><h1>zlib - Chicken - SWIG</h1></center>
+
+    <h2>Table of Contents</h2>
+    <a href="#build">Building the example</a><br>
+    <a href="#zlibh">zlib.h</a><br>
+    <a href="#devel">How the zlib wrapper was developed</a><br>
+
+    <center><h2><a name="build">Building the example</a></h2></center>
+
+    zlib must be installed for this example to work.<br>
+
+    Just type <code>make</code> to build this example.<br>
+
+    If zlib is not installed in /usr/lib and /usr/include, then do
+    something similar to the following:
+
+    <blockquote>
+      <pre>make SWIGOPT="-I/usr/local/include" LIBS="-L/usr/local/lib -lz"</pre>
+    </blockquote>
+
+    <center><h2><a name="zlibh">zlib.h</a></h2></center>
+    <blockquote>
+      <pre>
+<font color="blue">001:</font> /* zlib.h -- interface of the 'zlib' general purpose compression library
+<font color="blue">002:</font>   version 1.1.4, March 11th, 2002
+<font color="blue">003:</font> 
+<font color="blue">004:</font>   Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler
+<font color="blue">005:</font> 
+<font color="blue">006:</font>   This software is provided 'as-is', without any express or implied
+<font color="blue">007:</font>   warranty.  In no event will the authors be held liable for any damages
+<font color="blue">008:</font>   arising from the use of this software.
+<font color="blue">009:</font> 
+<font color="blue">010:</font>   Permission is granted to anyone to use this software for any purpose,
+<font color="blue">011:</font>   including commercial applications, and to alter it and redistribute it
+<font color="blue">012:</font>   freely, subject to the following restrictions:
+<font color="blue">013:</font> 
+<font color="blue">014:</font>   1. The origin of this software must not be misrepresented; you must not
+<font color="blue">015:</font>      claim that you wrote the original software. If you use this software
+<font color="blue">016:</font>      in a product, an acknowledgment in the product documentation would be
+<font color="blue">017:</font>      appreciated but is not required.
+<font color="blue">018:</font>   2. Altered source versions must be plainly marked as such, and must not be
+<font color="blue">019:</font>      misrepresented as being the original software.
+<font color="blue">020:</font>   3. This notice may not be removed or altered from any source distribution.
+<font color="blue">021:</font> 
+<font color="blue">022:</font>   Jean-loup Gailly        Mark Adler
+<font color="blue">023:</font>   jloup@gzip.org          madler@alumni.caltech.edu
+<font color="blue">024:</font> 
+<font color="blue">025:</font> 
+<font color="blue">026:</font>   The data format used by the zlib library is described by RFCs (Request for
+<font color="blue">027:</font>   Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
+<font color="blue">028:</font>   (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+<font color="blue">029:</font> */
+<font color="blue">030:</font> 
+<font color="blue">031:</font> #ifndef _ZLIB_H
+<font color="blue">032:</font> #define _ZLIB_H
+<font color="blue">033:</font> 
+<font color="blue">034:</font> #include "zconf.h"
+<font color="blue">035:</font> 
+<font color="blue">036:</font> #ifdef __cplusplus
+<font color="blue">037:</font> extern "C" {
+<font color="blue">038:</font> #endif
+<font color="blue">039:</font> 
+<font color="blue">040:</font> #define ZLIB_VERSION "1.1.4"
+<font color="blue">041:</font> 
+<font color="blue">042:</font> /* 
+<font color="blue">043:</font>      The 'zlib' compression library provides in-memory compression and
+<font color="blue">044:</font>   decompression functions, including integrity checks of the uncompressed
+<font color="blue">045:</font>   data.  This version of the library supports only one compression method
+<font color="blue">046:</font>   (deflation) but other algorithms will be added later and will have the same
+<font color="blue">047:</font>   stream interface.
+<font color="blue">048:</font> 
+<font color="blue">049:</font>      Compression can be done in a single step if the buffers are large
+<font color="blue">050:</font>   enough (for example if an input file is mmap'ed), or can be done by
+<font color="blue">051:</font>   repeated calls of the compression function.  In the latter case, the
+<font color="blue">052:</font>   application must provide more input and/or consume the output
+<font color="blue">053:</font>   (providing more output space) before each call.
+<font color="blue">054:</font> 
+<font color="blue">055:</font>      The library also supports reading and writing files in gzip (.gz) format
+<font color="blue">056:</font>   with an interface similar to that of stdio.
+<font color="blue">057:</font> 
+<font color="blue">058:</font>      The library does not install any signal handler. The decoder checks
+<font color="blue">059:</font>   the consistency of the compressed data, so the library should never
+<font color="blue">060:</font>   crash even in case of corrupted input.
+<font color="blue">061:</font> */
+<font color="blue">062:</font> 
+<font color="blue"><a name="l63">063:</a></font> typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
+<font color="blue">064:</font> typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
+<font color="blue">065:</font> 
+<font color="blue">066:</font> struct internal_state;
+<font color="blue">067:</font> 
+<font color="blue">068:</font> typedef struct z_stream_s {
+<font color="blue">069:</font>     Bytef    *next_in;  /* next input byte */
+<font color="blue">070:</font>     uInt     avail_in;  /* number of bytes available at next_in */
+<font color="blue">071:</font>     uLong    total_in;  /* total nb of input bytes read so far */
+<font color="blue">072:</font> 
+<font color="blue">073:</font>     Bytef    *next_out; /* next output byte should be put there */
+<font color="blue">074:</font>     uInt     avail_out; /* remaining free space at next_out */
+<font color="blue">075:</font>     uLong    total_out; /* total nb of bytes output so far */
+<font color="blue">076:</font> 
+<font color="blue">077:</font>     char     *msg;      /* last error message, NULL if no error */
+<font color="blue"><a name="l78">078:</a></font>     struct internal_state FAR *state; /* not visible by applications */
+<font color="blue">079:</font> 
+<font color="blue"><a name="l80">080:</a></font>     alloc_func zalloc;  /* used to allocate the internal state */
+<font color="blue">081:</font>     free_func  zfree;   /* used to free the internal state */
+<font color="blue">082:</font>     voidpf     opaque;  /* private data object passed to zalloc and zfree */
+<font color="blue">083:</font> 
+<font color="blue">084:</font>     int     data_type;  /* best guess about the data type: ascii or binary */
+<font color="blue">085:</font>     uLong   adler;      /* adler32 value of the uncompressed data */
+<font color="blue">086:</font>     uLong   reserved;   /* reserved for future use */
+<font color="blue">087:</font> } z_stream;
+<font color="blue">088:</font> 
+<font color="blue">089:</font> typedef z_stream FAR *z_streamp;
+<font color="blue">090:</font> 
+<font color="blue">091:</font> /*
+<font color="blue">092:</font>    The application must update next_in and avail_in when avail_in has
+<font color="blue">093:</font>    dropped to zero. It must update next_out and avail_out when avail_out
+<font color="blue">094:</font>    has dropped to zero. The application must initialize zalloc, zfree and
+<font color="blue">095:</font>    opaque before calling the init function. All other fields are set by the
+<font color="blue">096:</font>    compression library and must not be updated by the application.
+<font color="blue">097:</font> 
+<font color="blue">098:</font>    The opaque value provided by the application will be passed as the first
+<font color="blue">099:</font>    parameter for calls of zalloc and zfree. This can be useful for custom
+<font color="blue">100:</font>    memory management. The compression library attaches no meaning to the
+<font color="blue">101:</font>    opaque value.
+<font color="blue">102:</font> 
+<font color="blue">103:</font>    zalloc must return Z_NULL if there is not enough memory for the object.
+<font color="blue">104:</font>    If zlib is used in a multi-threaded application, zalloc and zfree must be
+<font color="blue">105:</font>    thread safe.
+<font color="blue">106:</font> 
+<font color="blue">107:</font>    On 16-bit systems, the functions zalloc and zfree must be able to allocate
+<font color="blue">108:</font>    exactly 65536 bytes, but will not be required to allocate more than this
+<font color="blue">109:</font>    if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
+<font color="blue">110:</font>    pointers returned by zalloc for objects of exactly 65536 bytes *must*
+<font color="blue">111:</font>    have their offset normalized to zero. The default allocation function
+<font color="blue">112:</font>    provided by this library ensures this (see zutil.c). To reduce memory
+<font color="blue">113:</font>    requirements and avoid any allocation of 64K objects, at the expense of
+<font color="blue">114:</font>    compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
+<font color="blue">115:</font> 
+<font color="blue">116:</font>    The fields total_in and total_out can be used for statistics or
+<font color="blue">117:</font>    progress reports. After compression, total_in holds the total size of
+<font color="blue">118:</font>    the uncompressed data and may be saved for use in the decompressor
+<font color="blue">119:</font>    (particularly if the decompressor wants to decompress everything in
+<font color="blue">120:</font>    a single step).
+<font color="blue">121:</font> */
+<font color="blue">122:</font> 
+<font color="blue">123:</font>                         /* constants */
+<font color="blue">124:</font> 
+<font color="blue">125:</font> #define Z_NO_FLUSH      0
+<font color="blue">126:</font> #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
+<font color="blue">127:</font> #define Z_SYNC_FLUSH    2
+<font color="blue">128:</font> #define Z_FULL_FLUSH    3
+<font color="blue">129:</font> #define Z_FINISH        4
+<font color="blue">130:</font> /* Allowed flush values; see deflate() below for details */
+<font color="blue">131:</font> 
+<font color="blue">132:</font> #define Z_OK            0
+<font color="blue">133:</font> #define Z_STREAM_END    1
+<font color="blue">134:</font> #define Z_NEED_DICT     2
+<font color="blue">135:</font> #define Z_ERRNO        (-1)
+<font color="blue">136:</font> #define Z_STREAM_ERROR (-2)
+<font color="blue">137:</font> #define Z_DATA_ERROR   (-3)
+<font color="blue">138:</font> #define Z_MEM_ERROR    (-4)
+<font color="blue">139:</font> #define Z_BUF_ERROR    (-5)
+<font color="blue">140:</font> #define Z_VERSION_ERROR (-6)
+<font color="blue">141:</font> /* Return codes for the compression/decompression functions. Negative
+<font color="blue">142:</font>  * values are errors, positive values are used for special but normal events.
+<font color="blue">143:</font>  */
+<font color="blue">144:</font> 
+<font color="blue">145:</font> #define Z_NO_COMPRESSION         0
+<font color="blue">146:</font> #define Z_BEST_SPEED             1
+<font color="blue">147:</font> #define Z_BEST_COMPRESSION       9
+<font color="blue">148:</font> #define Z_DEFAULT_COMPRESSION  (-1)
+<font color="blue">149:</font> /* compression levels */
+<font color="blue">150:</font> 
+<font color="blue">151:</font> #define Z_FILTERED            1
+<font color="blue">152:</font> #define Z_HUFFMAN_ONLY        2
+<font color="blue">153:</font> #define Z_DEFAULT_STRATEGY    0
+<font color="blue">154:</font> /* compression strategy; see deflateInit2() below for details */
+<font color="blue">155:</font> 
+<font color="blue">156:</font> #define Z_BINARY   0
+<font color="blue">157:</font> #define Z_ASCII    1
+<font color="blue">158:</font> #define Z_UNKNOWN  2
+<font color="blue">159:</font> /* Possible values of the data_type field */
+<font color="blue">160:</font> 
+<font color="blue">161:</font> #define Z_DEFLATED   8
+<font color="blue">162:</font> /* The deflate compression method (the only one supported in this version) */
+<font color="blue">163:</font> 
+<font color="blue">164:</font> #define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
+<font color="blue">165:</font> 
+<font color="blue">166:</font> #define zlib_version zlibVersion()
+<font color="blue">167:</font> /* for compatibility with versions &lt; 1.0.2 */
+<font color="blue">168:</font> 
+<font color="blue">169:</font>                         /* basic functions */
+<font color="blue">170:</font> 
+<font color="blue">171:</font> ZEXTERN const char * ZEXPORT zlibVersion OF((void));
+<font color="blue">172:</font> /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+<font color="blue">173:</font>    If the first character differs, the library code actually used is
+<font color="blue">174:</font>    not compatible with the zlib.h header file used by the application.
+<font color="blue">175:</font>    This check is automatically made by deflateInit and inflateInit.
+<font color="blue">176:</font>  */
+<font color="blue">177:</font> 
+<font color="blue">178:</font> /* 
+<font color="blue">179:</font> ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
+<font color="blue">180:</font> 
+<font color="blue">181:</font>      Initializes the internal stream state for compression. The fields
+<font color="blue">182:</font>    zalloc, zfree and opaque must be initialized before by the caller.
+<font color="blue">183:</font>    If zalloc and zfree are set to Z_NULL, deflateInit updates them to
+<font color="blue">184:</font>    use default allocation functions.
+<font color="blue">185:</font> 
+<font color="blue">186:</font>      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+<font color="blue">187:</font>    1 gives best speed, 9 gives best compression, 0 gives no compression at
+<font color="blue">188:</font>    all (the input data is simply copied a block at a time).
+<font color="blue">189:</font>    Z_DEFAULT_COMPRESSION requests a default compromise between speed and
+<font color="blue">190:</font>    compression (currently equivalent to level 6).
+<font color="blue">191:</font> 
+<font color="blue">192:</font>      deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
+<font color="blue">193:</font>    enough memory, Z_STREAM_ERROR if level is not a valid compression level,
+<font color="blue">194:</font>    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+<font color="blue">195:</font>    with the version assumed by the caller (ZLIB_VERSION).
+<font color="blue">196:</font>    msg is set to null if there is no error message.  deflateInit does not
+<font color="blue">197:</font>    perform any compression: this will be done by deflate().
+<font color="blue">198:</font> */
+<font color="blue">199:</font> 
+<font color="blue">200:</font> 
+<font color="blue">201:</font> ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
+<font color="blue">202:</font> /*
+<font color="blue">203:</font>     deflate compresses as much data as possible, and stops when the input
+<font color="blue">204:</font>   buffer becomes empty or the output buffer becomes full. It may introduce some
+<font color="blue">205:</font>   output latency (reading input without producing any output) except when
+<font color="blue">206:</font>   forced to flush.
+<font color="blue">207:</font> 
+<font color="blue">208:</font>     The detailed semantics are as follows. deflate performs one or both of the
+<font color="blue">209:</font>   following actions:
+<font color="blue">210:</font> 
+<font color="blue">211:</font>   - Compress more input starting at next_in and update next_in and avail_in
+<font color="blue">212:</font>     accordingly. If not all input can be processed (because there is not
+<font color="blue">213:</font>     enough room in the output buffer), next_in and avail_in are updated and
+<font color="blue">214:</font>     processing will resume at this point for the next call of deflate().
+<font color="blue">215:</font> 
+<font color="blue">216:</font>   - Provide more output starting at next_out and update next_out and avail_out
+<font color="blue">217:</font>     accordingly. This action is forced if the parameter flush is non zero.
+<font color="blue">218:</font>     Forcing flush frequently degrades the compression ratio, so this parameter
+<font color="blue">219:</font>     should be set only when necessary (in interactive applications).
+<font color="blue">220:</font>     Some output may be provided even if flush is not set.
+<font color="blue">221:</font> 
+<font color="blue">222:</font>   Before the call of deflate(), the application should ensure that at least
+<font color="blue">223:</font>   one of the actions is possible, by providing more input and/or consuming
+<font color="blue">224:</font>   more output, and updating avail_in or avail_out accordingly; avail_out
+<font color="blue">225:</font>   should never be zero before the call. The application can consume the
+<font color="blue">226:</font>   compressed output when it wants, for example when the output buffer is full
+<font color="blue">227:</font>   (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
+<font color="blue">228:</font>   and with zero avail_out, it must be called again after making room in the
+<font color="blue">229:</font>   output buffer because there might be more output pending.
+<font color="blue">230:</font> 
+<font color="blue">231:</font>     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+<font color="blue">232:</font>   flushed to the output buffer and the output is aligned on a byte boundary, so
+<font color="blue">233:</font>   that the decompressor can get all input data available so far. (In particular
+<font color="blue">234:</font>   avail_in is zero after the call if enough output space has been provided
+<font color="blue">235:</font>   before the call.)  Flushing may degrade compression for some compression
+<font color="blue">236:</font>   algorithms and so it should be used only when necessary.
+<font color="blue">237:</font> 
+<font color="blue">238:</font>     If flush is set to Z_FULL_FLUSH, all output is flushed as with
+<font color="blue">239:</font>   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+<font color="blue">240:</font>   restart from this point if previous compressed data has been damaged or if
+<font color="blue">241:</font>   random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+<font color="blue">242:</font>   the compression.
+<font color="blue">243:</font> 
+<font color="blue">244:</font>     If deflate returns with avail_out == 0, this function must be called again
+<font color="blue">245:</font>   with the same value of the flush parameter and more output space (updated
+<font color="blue">246:</font>   avail_out), until the flush is complete (deflate returns with non-zero
+<font color="blue">247:</font>   avail_out).
+<font color="blue">248:</font> 
+<font color="blue">249:</font>     If the parameter flush is set to Z_FINISH, pending input is processed,
+<font color="blue">250:</font>   pending output is flushed and deflate returns with Z_STREAM_END if there
+<font color="blue">251:</font>   was enough output space; if deflate returns with Z_OK, this function must be
+<font color="blue">252:</font>   called again with Z_FINISH and more output space (updated avail_out) but no
+<font color="blue">253:</font>   more input data, until it returns with Z_STREAM_END or an error. After
+<font color="blue">254:</font>   deflate has returned Z_STREAM_END, the only possible operations on the
+<font color="blue">255:</font>   stream are deflateReset or deflateEnd.
+<font color="blue">256:</font>   
+<font color="blue">257:</font>     Z_FINISH can be used immediately after deflateInit if all the compression
+<font color="blue">258:</font>   is to be done in a single step. In this case, avail_out must be at least
+<font color="blue">259:</font>   0.1% larger than avail_in plus 12 bytes.  If deflate does not return
+<font color="blue">260:</font>   Z_STREAM_END, then it must be called again as described above.
+<font color="blue">261:</font> 
+<font color="blue">262:</font>     deflate() sets strm-&gt;adler to the adler32 checksum of all input read
+<font color="blue">263:</font>   so far (that is, total_in bytes).
+<font color="blue">264:</font> 
+<font color="blue">265:</font>     deflate() may update data_type if it can make a good guess about
+<font color="blue">266:</font>   the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
+<font color="blue">267:</font>   binary. This field is only for information purposes and does not affect
+<font color="blue">268:</font>   the compression algorithm in any manner.
+<font color="blue">269:</font> 
+<font color="blue">270:</font>     deflate() returns Z_OK if some progress has been made (more input
+<font color="blue">271:</font>   processed or more output produced), Z_STREAM_END if all input has been
+<font color="blue">272:</font>   consumed and all output has been produced (only when flush is set to
+<font color="blue">273:</font>   Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+<font color="blue">274:</font>   if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
+<font color="blue">275:</font>   (for example avail_in or avail_out was zero).
+<font color="blue">276:</font> */
+<font color="blue">277:</font> 
+<font color="blue">278:</font> 
+<font color="blue">279:</font> ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
+<font color="blue">280:</font> /*
+<font color="blue">281:</font>      All dynamically allocated data structures for this stream are freed.
+<font color="blue">282:</font>    This function discards any unprocessed input and does not flush any
+<font color="blue">283:</font>    pending output.
+<font color="blue">284:</font> 
+<font color="blue">285:</font>      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+<font color="blue">286:</font>    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+<font color="blue">287:</font>    prematurely (some input or output was discarded). In the error case,
+<font color="blue">288:</font>    msg may be set but then points to a static string (which must not be
+<font color="blue">289:</font>    deallocated).
+<font color="blue">290:</font> */
+<font color="blue">291:</font> 
+<font color="blue">292:</font> 
+<font color="blue">293:</font> /* 
+<font color="blue">294:</font> ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
+<font color="blue">295:</font> 
+<font color="blue">296:</font>      Initializes the internal stream state for decompression. The fields
+<font color="blue">297:</font>    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+<font color="blue">298:</font>    the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
+<font color="blue">299:</font>    value depends on the compression method), inflateInit determines the
+<font color="blue">300:</font>    compression method from the zlib header and allocates all data structures
+<font color="blue">301:</font>    accordingly; otherwise the allocation will be deferred to the first call of
+<font color="blue">302:</font>    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
+<font color="blue">303:</font>    use default allocation functions.
+<font color="blue">304:</font> 
+<font color="blue">305:</font>      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+<font color="blue">306:</font>    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+<font color="blue">307:</font>    version assumed by the caller.  msg is set to null if there is no error
+<font color="blue">308:</font>    message. inflateInit does not perform any decompression apart from reading
+<font color="blue">309:</font>    the zlib header if present: this will be done by inflate().  (So next_in and
+<font color="blue">310:</font>    avail_in may be modified, but next_out and avail_out are unchanged.)
+<font color="blue">311:</font> */
+<font color="blue">312:</font> 
+<font color="blue">313:</font> 
+<font color="blue">314:</font> ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
+<font color="blue">315:</font> /*
+<font color="blue">316:</font>     inflate decompresses as much data as possible, and stops when the input
+<font color="blue">317:</font>   buffer becomes empty or the output buffer becomes full. It may some
+<font color="blue">318:</font>   introduce some output latency (reading input without producing any output)
+<font color="blue">319:</font>   except when forced to flush.
+<font color="blue">320:</font> 
+<font color="blue">321:</font>   The detailed semantics are as follows. inflate performs one or both of the
+<font color="blue">322:</font>   following actions:
+<font color="blue">323:</font> 
+<font color="blue">324:</font>   - Decompress more input starting at next_in and update next_in and avail_in
+<font color="blue">325:</font>     accordingly. If not all input can be processed (because there is not
+<font color="blue">326:</font>     enough room in the output buffer), next_in is updated and processing
+<font color="blue">327:</font>     will resume at this point for the next call of inflate().
+<font color="blue">328:</font> 
+<font color="blue">329:</font>   - Provide more output starting at next_out and update next_out and avail_out
+<font color="blue">330:</font>     accordingly.  inflate() provides as much output as possible, until there
+<font color="blue">331:</font>     is no more input data or no more space in the output buffer (see below
+<font color="blue">332:</font>     about the flush parameter).
+<font color="blue">333:</font> 
+<font color="blue">334:</font>   Before the call of inflate(), the application should ensure that at least
+<font color="blue">335:</font>   one of the actions is possible, by providing more input and/or consuming
+<font color="blue">336:</font>   more output, and updating the next_* and avail_* values accordingly.
+<font color="blue">337:</font>   The application can consume the uncompressed output when it wants, for
+<font color="blue">338:</font>   example when the output buffer is full (avail_out == 0), or after each
+<font color="blue">339:</font>   call of inflate(). If inflate returns Z_OK and with zero avail_out, it
+<font color="blue">340:</font>   must be called again after making room in the output buffer because there
+<font color="blue">341:</font>   might be more output pending.
+<font color="blue">342:</font> 
+<font color="blue">343:</font>     If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
+<font color="blue">344:</font>   output as possible to the output buffer. The flushing behavior of inflate is
+<font color="blue">345:</font>   not specified for values of the flush parameter other than Z_SYNC_FLUSH
+<font color="blue">346:</font>   and Z_FINISH, but the current implementation actually flushes as much output
+<font color="blue">347:</font>   as possible anyway.
+<font color="blue">348:</font> 
+<font color="blue">349:</font>     inflate() should normally be called until it returns Z_STREAM_END or an
+<font color="blue">350:</font>   error. However if all decompression is to be performed in a single step
+<font color="blue">351:</font>   (a single call of inflate), the parameter flush should be set to
+<font color="blue">352:</font>   Z_FINISH. In this case all pending input is processed and all pending
+<font color="blue">353:</font>   output is flushed; avail_out must be large enough to hold all the
+<font color="blue">354:</font>   uncompressed data. (The size of the uncompressed data may have been saved
+<font color="blue">355:</font>   by the compressor for this purpose.) The next operation on this stream must
+<font color="blue">356:</font>   be inflateEnd to deallocate the decompression state. The use of Z_FINISH
+<font color="blue">357:</font>   is never required, but can be used to inform inflate that a faster routine
+<font color="blue">358:</font>   may be used for the single inflate() call.
+<font color="blue">359:</font> 
+<font color="blue">360:</font>      If a preset dictionary is needed at this point (see inflateSetDictionary
+<font color="blue">361:</font>   below), inflate sets strm-adler to the adler32 checksum of the
+<font color="blue">362:</font>   dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise 
+<font color="blue">363:</font>   it sets strm-&gt;adler to the adler32 checksum of all output produced
+<font color="blue">364:</font>   so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
+<font color="blue">365:</font>   an error code as described below. At the end of the stream, inflate()
+<font color="blue">366:</font>   checks that its computed adler32 checksum is equal to that saved by the
+<font color="blue">367:</font>   compressor and returns Z_STREAM_END only if the checksum is correct.
+<font color="blue">368:</font> 
+<font color="blue">369:</font>     inflate() returns Z_OK if some progress has been made (more input processed
+<font color="blue">370:</font>   or more output produced), Z_STREAM_END if the end of the compressed data has
+<font color="blue">371:</font>   been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+<font color="blue">372:</font>   preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+<font color="blue">373:</font>   corrupted (input stream not conforming to the zlib format or incorrect
+<font color="blue">374:</font>   adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
+<font color="blue">375:</font>   (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
+<font color="blue">376:</font>   enough memory, Z_BUF_ERROR if no progress is possible or if there was not
+<font color="blue">377:</font>   enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
+<font color="blue">378:</font>   case, the application may then call inflateSync to look for a good
+<font color="blue">379:</font>   compression block.
+<font color="blue">380:</font> */
+<font color="blue">381:</font> 
+<font color="blue">382:</font> 
+<font color="blue">383:</font> ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
+<font color="blue">384:</font> /*
+<font color="blue">385:</font>      All dynamically allocated data structures for this stream are freed.
+<font color="blue">386:</font>    This function discards any unprocessed input and does not flush any
+<font color="blue">387:</font>    pending output.
+<font color="blue">388:</font> 
+<font color="blue">389:</font>      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
+<font color="blue">390:</font>    was inconsistent. In the error case, msg may be set but then points to a
+<font color="blue">391:</font>    static string (which must not be deallocated).
+<font color="blue">392:</font> */
+<font color="blue">393:</font> 
+<font color="blue">394:</font>                         /* Advanced functions */
+<font color="blue">395:</font> 
+<font color="blue">396:</font> /*
+<font color="blue">397:</font>     The following functions are needed only in some special applications.
+<font color="blue">398:</font> */
+<font color="blue">399:</font> 
+<font color="blue">400:</font> /*   
+<font color="blue">401:</font> ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
+<font color="blue">402:</font>                                      int  level,
+<font color="blue">403:</font>                                      int  method,
+<font color="blue">404:</font>                                      int  windowBits,
+<font color="blue">405:</font>                                      int  memLevel,
+<font color="blue">406:</font>                                      int  strategy));
+<font color="blue">407:</font> 
+<font color="blue">408:</font>      This is another version of deflateInit with more compression options. The
+<font color="blue">409:</font>    fields next_in, zalloc, zfree and opaque must be initialized before by
+<font color="blue">410:</font>    the caller.
+<font color="blue">411:</font> 
+<font color="blue">412:</font>      The method parameter is the compression method. It must be Z_DEFLATED in
+<font color="blue">413:</font>    this version of the library.
+<font color="blue">414:</font> 
+<font color="blue">415:</font>      The windowBits parameter is the base two logarithm of the window size
+<font color="blue">416:</font>    (the size of the history buffer).  It should be in the range 8..15 for this
+<font color="blue">417:</font>    version of the library. Larger values of this parameter result in better
+<font color="blue">418:</font>    compression at the expense of memory usage. The default value is 15 if
+<font color="blue">419:</font>    deflateInit is used instead.
+<font color="blue">420:</font> 
+<font color="blue">421:</font>      The memLevel parameter specifies how much memory should be allocated
+<font color="blue">422:</font>    for the internal compression state. memLevel=1 uses minimum memory but
+<font color="blue">423:</font>    is slow and reduces compression ratio; memLevel=9 uses maximum memory
+<font color="blue">424:</font>    for optimal speed. The default value is 8. See zconf.h for total memory
+<font color="blue">425:</font>    usage as a function of windowBits and memLevel.
+<font color="blue">426:</font> 
+<font color="blue">427:</font>      The strategy parameter is used to tune the compression algorithm. Use the
+<font color="blue">428:</font>    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+<font color="blue">429:</font>    filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
+<font color="blue">430:</font>    string match).  Filtered data consists mostly of small values with a
+<font color="blue">431:</font>    somewhat random distribution. In this case, the compression algorithm is
+<font color="blue">432:</font>    tuned to compress them better. The effect of Z_FILTERED is to force more
+<font color="blue">433:</font>    Huffman coding and less string matching; it is somewhat intermediate
+<font color="blue">434:</font>    between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
+<font color="blue">435:</font>    the compression ratio but not the correctness of the compressed output even
+<font color="blue">436:</font>    if it is not set appropriately.
+<font color="blue">437:</font> 
+<font color="blue">438:</font>       deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+<font color="blue">439:</font>    memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
+<font color="blue">440:</font>    method). msg is set to null if there is no error message.  deflateInit2 does
+<font color="blue">441:</font>    not perform any compression: this will be done by deflate().
+<font color="blue">442:</font> */
+<font color="blue">443:</font>                             
+<font color="blue">444:</font> ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
+<font color="blue">445:</font>                                              const Bytef *dictionary,
+<font color="blue">446:</font>                                              uInt  dictLength));
+<font color="blue">447:</font> /*
+<font color="blue">448:</font>      Initializes the compression dictionary from the given byte sequence
+<font color="blue">449:</font>    without producing any compressed output. This function must be called
+<font color="blue">450:</font>    immediately after deflateInit, deflateInit2 or deflateReset, before any
+<font color="blue">451:</font>    call of deflate. The compressor and decompressor must use exactly the same
+<font color="blue">452:</font>    dictionary (see inflateSetDictionary).
+<font color="blue">453:</font> 
+<font color="blue">454:</font>      The dictionary should consist of strings (byte sequences) that are likely
+<font color="blue">455:</font>    to be encountered later in the data to be compressed, with the most commonly
+<font color="blue">456:</font>    used strings preferably put towards the end of the dictionary. Using a
+<font color="blue">457:</font>    dictionary is most useful when the data to be compressed is short and can be
+<font color="blue">458:</font>    predicted with good accuracy; the data can then be compressed better than
+<font color="blue">459:</font>    with the default empty dictionary.
+<font color="blue">460:</font> 
+<font color="blue">461:</font>      Depending on the size of the compression data structures selected by
+<font color="blue">462:</font>    deflateInit or deflateInit2, a part of the dictionary may in effect be
+<font color="blue">463:</font>    discarded, for example if the dictionary is larger than the window size in
+<font color="blue">464:</font>    deflate or deflate2. Thus the strings most likely to be useful should be
+<font color="blue">465:</font>    put at the end of the dictionary, not at the front.
+<font color="blue">466:</font> 
+<font color="blue">467:</font>      Upon return of this function, strm-&gt;adler is set to the Adler32 value
+<font color="blue">468:</font>    of the dictionary; the decompressor may later use this value to determine
+<font color="blue">469:</font>    which dictionary has been used by the compressor. (The Adler32 value
+<font color="blue">470:</font>    applies to the whole dictionary even if only a subset of the dictionary is
+<font color="blue">471:</font>    actually used by the compressor.)
+<font color="blue">472:</font> 
+<font color="blue">473:</font>      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+<font color="blue">474:</font>    parameter is invalid (such as NULL dictionary) or the stream state is
+<font color="blue">475:</font>    inconsistent (for example if deflate has already been called for this stream
+<font color="blue">476:</font>    or if the compression method is bsort). deflateSetDictionary does not
+<font color="blue">477:</font>    perform any compression: this will be done by deflate().
+<font color="blue">478:</font> */
+<font color="blue">479:</font> 
+<font color="blue">480:</font> ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
+<font color="blue">481:</font>                                     z_streamp source));
+<font color="blue">482:</font> /*
+<font color="blue">483:</font>      Sets the destination stream as a complete copy of the source stream.
+<font color="blue">484:</font> 
+<font color="blue">485:</font>      This function can be useful when several compression strategies will be
+<font color="blue">486:</font>    tried, for example when there are several ways of pre-processing the input
+<font color="blue">487:</font>    data with a filter. The streams that will be discarded should then be freed
+<font color="blue">488:</font>    by calling deflateEnd.  Note that deflateCopy duplicates the internal
+<font color="blue">489:</font>    compression state which can be quite large, so this strategy is slow and
+<font color="blue">490:</font>    can consume lots of memory.
+<font color="blue">491:</font> 
+<font color="blue">492:</font>      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+<font color="blue">493:</font>    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+<font color="blue">494:</font>    (such as zalloc being NULL). msg is left unchanged in both source and
+<font color="blue">495:</font>    destination.
+<font color="blue">496:</font> */
+<font color="blue">497:</font> 
+<font color="blue">498:</font> ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
+<font color="blue">499:</font> /*
+<font color="blue">500:</font>      This function is equivalent to deflateEnd followed by deflateInit,
+<font color="blue">501:</font>    but does not free and reallocate all the internal compression state.
+<font color="blue">502:</font>    The stream will keep the same compression level and any other attributes
+<font color="blue">503:</font>    that may have been set by deflateInit2.
+<font color="blue">504:</font> 
+<font color="blue">505:</font>       deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+<font color="blue">506:</font>    stream state was inconsistent (such as zalloc or state being NULL).
+<font color="blue">507:</font> */
+<font color="blue">508:</font> 
+<font color="blue">509:</font> ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
+<font color="blue">510:</font> 				      int level,
+<font color="blue">511:</font> 				      int strategy));
+<font color="blue">512:</font> /*
+<font color="blue">513:</font>      Dynamically update the compression level and compression strategy.  The
+<font color="blue">514:</font>    interpretation of level and strategy is as in deflateInit2.  This can be
+<font color="blue">515:</font>    used to switch between compression and straight copy of the input data, or
+<font color="blue">516:</font>    to switch to a different kind of input data requiring a different
+<font color="blue">517:</font>    strategy. If the compression level is changed, the input available so far
+<font color="blue">518:</font>    is compressed with the old level (and may be flushed); the new level will
+<font color="blue">519:</font>    take effect only at the next call of deflate().
+<font color="blue">520:</font> 
+<font color="blue">521:</font>      Before the call of deflateParams, the stream state must be set as for
+<font color="blue">522:</font>    a call of deflate(), since the currently available input may have to
+<font color="blue">523:</font>    be compressed and flushed. In particular, strm-&gt;avail_out must be non-zero.
+<font color="blue">524:</font> 
+<font color="blue">525:</font>      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+<font color="blue">526:</font>    stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
+<font color="blue">527:</font>    if strm-&gt;avail_out was zero.
+<font color="blue">528:</font> */
+<font color="blue">529:</font> 
+<font color="blue">530:</font> /*   
+<font color="blue">531:</font> ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
+<font color="blue">532:</font>                                      int  windowBits));
+<font color="blue">533:</font> 
+<font color="blue">534:</font>      This is another version of inflateInit with an extra parameter. The
+<font color="blue">535:</font>    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+<font color="blue">536:</font>    before by the caller.
+<font color="blue">537:</font> 
+<font color="blue">538:</font>      The windowBits parameter is the base two logarithm of the maximum window
+<font color="blue">539:</font>    size (the size of the history buffer).  It should be in the range 8..15 for
+<font color="blue">540:</font>    this version of the library. The default value is 15 if inflateInit is used
+<font color="blue">541:</font>    instead. If a compressed stream with a larger window size is given as
+<font color="blue">542:</font>    input, inflate() will return with the error code Z_DATA_ERROR instead of
+<font color="blue">543:</font>    trying to allocate a larger window.
+<font color="blue">544:</font> 
+<font color="blue">545:</font>       inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+<font color="blue">546:</font>    memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
+<font color="blue">547:</font>    memLevel). msg is set to null if there is no error message.  inflateInit2
+<font color="blue">548:</font>    does not perform any decompression apart from reading the zlib header if
+<font color="blue">549:</font>    present: this will be done by inflate(). (So next_in and avail_in may be
+<font color="blue">550:</font>    modified, but next_out and avail_out are unchanged.)
+<font color="blue">551:</font> */
+<font color="blue">552:</font> 
+<font color="blue">553:</font> ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
+<font color="blue">554:</font>                                              const Bytef *dictionary,
+<font color="blue">555:</font>                                              uInt  dictLength));
+<font color="blue">556:</font> /*
+<font color="blue">557:</font>      Initializes the decompression dictionary from the given uncompressed byte
+<font color="blue">558:</font>    sequence. This function must be called immediately after a call of inflate
+<font color="blue">559:</font>    if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
+<font color="blue">560:</font>    can be determined from the Adler32 value returned by this call of
+<font color="blue">561:</font>    inflate. The compressor and decompressor must use exactly the same
+<font color="blue">562:</font>    dictionary (see deflateSetDictionary).
+<font color="blue">563:</font> 
+<font color="blue">564:</font>      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+<font color="blue">565:</font>    parameter is invalid (such as NULL dictionary) or the stream state is
+<font color="blue">566:</font>    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+<font color="blue">567:</font>    expected one (incorrect Adler32 value). inflateSetDictionary does not
+<font color="blue">568:</font>    perform any decompression: this will be done by subsequent calls of
+<font color="blue">569:</font>    inflate().
+<font color="blue">570:</font> */
+<font color="blue">571:</font> 
+<font color="blue">572:</font> ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+<font color="blue">573:</font> /* 
+<font color="blue">574:</font>     Skips invalid compressed data until a full flush point (see above the
+<font color="blue">575:</font>   description of deflate with Z_FULL_FLUSH) can be found, or until all
+<font color="blue">576:</font>   available input is skipped. No output is provided.
+<font color="blue">577:</font> 
+<font color="blue">578:</font>     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+<font color="blue">579:</font>   if no more input was provided, Z_DATA_ERROR if no flush point has been found,
+<font color="blue">580:</font>   or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
+<font color="blue">581:</font>   case, the application may save the current current value of total_in which
+<font color="blue">582:</font>   indicates where valid compressed data was found. In the error case, the
+<font color="blue">583:</font>   application may repeatedly call inflateSync, providing more input each time,
+<font color="blue">584:</font>   until success or end of the input data.
+<font color="blue">585:</font> */
+<font color="blue">586:</font> 
+<font color="blue">587:</font> ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
+<font color="blue">588:</font> /*
+<font color="blue">589:</font>      This function is equivalent to inflateEnd followed by inflateInit,
+<font color="blue">590:</font>    but does not free and reallocate all the internal decompression state.
+<font color="blue">591:</font>    The stream will keep attributes that may have been set by inflateInit2.
+<font color="blue">592:</font> 
+<font color="blue">593:</font>       inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+<font color="blue">594:</font>    stream state was inconsistent (such as zalloc or state being NULL).
+<font color="blue">595:</font> */
+<font color="blue">596:</font> 
+<font color="blue">597:</font> 
+<font color="blue">598:</font>                         /* utility functions */
+<font color="blue">599:</font> 
+<font color="blue">600:</font> /*
+<font color="blue">601:</font>      The following utility functions are implemented on top of the
+<font color="blue">602:</font>    basic stream-oriented functions. To simplify the interface, some
+<font color="blue">603:</font>    default options are assumed (compression level and memory usage,
+<font color="blue">604:</font>    standard memory allocation functions). The source code of these
+<font color="blue">605:</font>    utility functions can easily be modified if you need special options.
+<font color="blue">606:</font> */
+<font color="blue">607:</font> 
+<font color="blue">608:</font> ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
+<font color="blue">609:</font>                                  const Bytef *source, uLong sourceLen));
+<font color="blue">610:</font> /*
+<font color="blue">611:</font>      Compresses the source buffer into the destination buffer.  sourceLen is
+<font color="blue">612:</font>    the byte length of the source buffer. Upon entry, destLen is the total
+<font color="blue">613:</font>    size of the destination buffer, which must be at least 0.1% larger than
+<font color="blue">614:</font>    sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
+<font color="blue">615:</font>    compressed buffer.
+<font color="blue">616:</font>      This function can be used to compress a whole file at once if the
+<font color="blue">617:</font>    input file is mmap'ed.
+<font color="blue">618:</font>      compress returns Z_OK if success, Z_MEM_ERROR if there was not
+<font color="blue">619:</font>    enough memory, Z_BUF_ERROR if there was not enough room in the output
+<font color="blue">620:</font>    buffer.
+<font color="blue">621:</font> */
+<font color="blue">622:</font> 
+<font color="blue">623:</font> ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
+<font color="blue">624:</font>                                   const Bytef *source, uLong sourceLen,
+<font color="blue">625:</font>                                   int level));
+<font color="blue">626:</font> /*
+<font color="blue">627:</font>      Compresses the source buffer into the destination buffer. The level
+<font color="blue">628:</font>    parameter has the same meaning as in deflateInit.  sourceLen is the byte
+<font color="blue">629:</font>    length of the source buffer. Upon entry, destLen is the total size of the
+<font color="blue">630:</font>    destination buffer, which must be at least 0.1% larger than sourceLen plus
+<font color="blue">631:</font>    12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
+<font color="blue">632:</font> 
+<font color="blue">633:</font>      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+<font color="blue">634:</font>    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+<font color="blue">635:</font>    Z_STREAM_ERROR if the level parameter is invalid.
+<font color="blue">636:</font> */
+<font color="blue">637:</font> 
+<font color="blue">638:</font> ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
+<font color="blue">639:</font>                                    const Bytef *source, uLong sourceLen));
+<font color="blue">640:</font> /*
+<font color="blue">641:</font>      Decompresses the source buffer into the destination buffer.  sourceLen is
+<font color="blue">642:</font>    the byte length of the source buffer. Upon entry, destLen is the total
+<font color="blue">643:</font>    size of the destination buffer, which must be large enough to hold the
+<font color="blue">644:</font>    entire uncompressed data. (The size of the uncompressed data must have
+<font color="blue">645:</font>    been saved previously by the compressor and transmitted to the decompressor
+<font color="blue">646:</font>    by some mechanism outside the scope of this compression library.)
+<font color="blue">647:</font>    Upon exit, destLen is the actual size of the compressed buffer.
+<font color="blue">648:</font>      This function can be used to decompress a whole file at once if the
+<font color="blue">649:</font>    input file is mmap'ed.
+<font color="blue">650:</font> 
+<font color="blue">651:</font>      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+<font color="blue">652:</font>    enough memory, Z_BUF_ERROR if there was not enough room in the output
+<font color="blue">653:</font>    buffer, or Z_DATA_ERROR if the input data was corrupted.
+<font color="blue">654:</font> */
+<font color="blue">655:</font> 
+<font color="blue">656:</font> 
+<font color="blue">657:</font> typedef voidp gzFile;
+<font color="blue">658:</font> 
+<font color="blue">659:</font> ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
+<font color="blue">660:</font> /*
+<font color="blue">661:</font>      Opens a gzip (.gz) file for reading or writing. The mode parameter
+<font color="blue">662:</font>    is as in fopen ("rb" or "wb") but can also include a compression level
+<font color="blue">663:</font>    ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
+<font color="blue">664:</font>    Huffman only compression as in "wb1h". (See the description
+<font color="blue">665:</font>    of deflateInit2 for more information about the strategy parameter.)
+<font color="blue">666:</font> 
+<font color="blue">667:</font>      gzopen can be used to read a file which is not in gzip format; in this
+<font color="blue">668:</font>    case gzread will directly read from the file without decompression.
+<font color="blue">669:</font> 
+<font color="blue">670:</font>      gzopen returns NULL if the file could not be opened or if there was
+<font color="blue">671:</font>    insufficient memory to allocate the (de)compression state; errno
+<font color="blue">672:</font>    can be checked to distinguish the two cases (if errno is zero, the
+<font color="blue">673:</font>    zlib error is Z_MEM_ERROR).  */
+<font color="blue">674:</font> 
+<font color="blue">675:</font> ZEXTERN gzFile ZEXPORT gzdopen  OF((int fd, const char *mode));
+<font color="blue">676:</font> /*
+<font color="blue">677:</font>      gzdopen() associates a gzFile with the file descriptor fd.  File
+<font color="blue">678:</font>    descriptors are obtained from calls like open, dup, creat, pipe or
+<font color="blue">679:</font>    fileno (in the file has been previously opened with fopen).
+<font color="blue">680:</font>    The mode parameter is as in gzopen.
+<font color="blue">681:</font>      The next call of gzclose on the returned gzFile will also close the
+<font color="blue">682:</font>    file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
+<font color="blue">683:</font>    descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
+<font color="blue">684:</font>      gzdopen returns NULL if there was insufficient memory to allocate
+<font color="blue">685:</font>    the (de)compression state.
+<font color="blue">686:</font> */
+<font color="blue">687:</font> 
+<font color="blue">688:</font> ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
+<font color="blue">689:</font> /*
+<font color="blue">690:</font>      Dynamically update the compression level or strategy. See the description
+<font color="blue">691:</font>    of deflateInit2 for the meaning of these parameters.
+<font color="blue">692:</font>      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+<font color="blue">693:</font>    opened for writing.
+<font color="blue">694:</font> */
+<font color="blue">695:</font> 
+<font color="blue">696:</font> ZEXTERN int ZEXPORT    gzread  OF((gzFile file, voidp buf, unsigned len));
+<font color="blue">697:</font> /*
+<font color="blue">698:</font>      Reads the given number of uncompressed bytes from the compressed file.
+<font color="blue">699:</font>    If the input file was not in gzip format, gzread copies the given number
+<font color="blue">700:</font>    of bytes into the buffer.
+<font color="blue">701:</font>      gzread returns the number of uncompressed bytes actually read (0 for
+<font color="blue">702:</font>    end of file, -1 for error). */
+<font color="blue">703:</font> 
+<font color="blue">704:</font> ZEXTERN int ZEXPORT    gzwrite OF((gzFile file, 
+<font color="blue">705:</font> 				   const voidp buf, unsigned len));
+<font color="blue">706:</font> /*
+<font color="blue">707:</font>      Writes the given number of uncompressed bytes into the compressed file.
+<font color="blue">708:</font>    gzwrite returns the number of uncompressed bytes actually written
+<font color="blue">709:</font>    (0 in case of error).
+<font color="blue">710:</font> */
+<font color="blue">711:</font> 
+<font color="blue">712:</font> ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
+<font color="blue">713:</font> /*
+<font color="blue">714:</font>      Converts, formats, and writes the args to the compressed file under
+<font color="blue">715:</font>    control of the format string, as in fprintf. gzprintf returns the number of
+<font color="blue">716:</font>    uncompressed bytes actually written (0 in case of error).
+<font color="blue">717:</font> */
+<font color="blue">718:</font> 
+<font color="blue">719:</font> ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
+<font color="blue">720:</font> /*
+<font color="blue">721:</font>       Writes the given null-terminated string to the compressed file, excluding
+<font color="blue">722:</font>    the terminating null character.
+<font color="blue">723:</font>       gzputs returns the number of characters written, or -1 in case of error.
+<font color="blue">724:</font> */
+<font color="blue">725:</font> 
+<font color="blue">726:</font> ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
+<font color="blue">727:</font> /*
+<font color="blue">728:</font>       Reads bytes from the compressed file until len-1 characters are read, or
+<font color="blue">729:</font>    a newline character is read and transferred to buf, or an end-of-file
+<font color="blue">730:</font>    condition is encountered.  The string is then terminated with a null
+<font color="blue">731:</font>    character.
+<font color="blue">732:</font>       gzgets returns buf, or Z_NULL in case of error.
+<font color="blue">733:</font> */
+<font color="blue">734:</font> 
+<font color="blue">735:</font> ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
+<font color="blue">736:</font> /*
+<font color="blue">737:</font>       Writes c, converted to an unsigned char, into the compressed file.
+<font color="blue">738:</font>    gzputc returns the value that was written, or -1 in case of error.
+<font color="blue">739:</font> */
+<font color="blue">740:</font> 
+<font color="blue">741:</font> ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
+<font color="blue">742:</font> /*
+<font color="blue">743:</font>       Reads one byte from the compressed file. gzgetc returns this byte
+<font color="blue">744:</font>    or -1 in case of end of file or error.
+<font color="blue">745:</font> */
+<font color="blue">746:</font> 
+<font color="blue">747:</font> ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
+<font color="blue">748:</font> /*
+<font color="blue">749:</font>      Flushes all pending output into the compressed file. The parameter
+<font color="blue">750:</font>    flush is as in the deflate() function. The return value is the zlib
+<font color="blue">751:</font>    error number (see function gzerror below). gzflush returns Z_OK if
+<font color="blue">752:</font>    the flush parameter is Z_FINISH and all output could be flushed.
+<font color="blue">753:</font>      gzflush should be called only when strictly necessary because it can
+<font color="blue">754:</font>    degrade compression.
+<font color="blue">755:</font> */
+<font color="blue">756:</font> 
+<font color="blue">757:</font> ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
+<font color="blue">758:</font> 				      z_off_t offset, int whence));
+<font color="blue">759:</font> /* 
+<font color="blue">760:</font>       Sets the starting position for the next gzread or gzwrite on the
+<font color="blue">761:</font>    given compressed file. The offset represents a number of bytes in the
+<font color="blue">762:</font>    uncompressed data stream. The whence parameter is defined as in lseek(2);
+<font color="blue">763:</font>    the value SEEK_END is not supported.
+<font color="blue">764:</font>      If the file is opened for reading, this function is emulated but can be
+<font color="blue">765:</font>    extremely slow. If the file is opened for writing, only forward seeks are
+<font color="blue">766:</font>    supported; gzseek then compresses a sequence of zeroes up to the new
+<font color="blue">767:</font>    starting position.
+<font color="blue">768:</font> 
+<font color="blue">769:</font>       gzseek returns the resulting offset location as measured in bytes from
+<font color="blue">770:</font>    the beginning of the uncompressed stream, or -1 in case of error, in
+<font color="blue">771:</font>    particular if the file is opened for writing and the new starting position
+<font color="blue">772:</font>    would be before the current position.
+<font color="blue">773:</font> */
+<font color="blue">774:</font> 
+<font color="blue">775:</font> ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
+<font color="blue">776:</font> /*
+<font color="blue">777:</font>      Rewinds the given file. This function is supported only for reading.
+<font color="blue">778:</font> 
+<font color="blue">779:</font>    gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+<font color="blue">780:</font> */
+<font color="blue">781:</font> 
+<font color="blue">782:</font> ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+<font color="blue">783:</font> /*
+<font color="blue">784:</font>      Returns the starting position for the next gzread or gzwrite on the
+<font color="blue">785:</font>    given compressed file. This position represents a number of bytes in the
+<font color="blue">786:</font>    uncompressed data stream.
+<font color="blue">787:</font> 
+<font color="blue">788:</font>    gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+<font color="blue">789:</font> */
+<font color="blue">790:</font> 
+<font color="blue">791:</font> ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+<font color="blue">792:</font> /*
+<font color="blue">793:</font>      Returns 1 when EOF has previously been detected reading the given
+<font color="blue">794:</font>    input stream, otherwise zero.
+<font color="blue">795:</font> */
+<font color="blue">796:</font> 
+<font color="blue">797:</font> ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
+<font color="blue">798:</font> /*
+<font color="blue">799:</font>      Flushes all pending output if necessary, closes the compressed file
+<font color="blue">800:</font>    and deallocates all the (de)compression state. The return value is the zlib
+<font color="blue">801:</font>    error number (see function gzerror below).
+<font color="blue">802:</font> */
+<font color="blue">803:</font> 
+<font color="blue">804:</font> ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
+<font color="blue">805:</font> /*
+<font color="blue">806:</font>      Returns the error message for the last error which occurred on the
+<font color="blue">807:</font>    given compressed file. errnum is set to zlib error number. If an
+<font color="blue">808:</font>    error occurred in the file system and not in the compression library,
+<font color="blue">809:</font>    errnum is set to Z_ERRNO and the application may consult errno
+<font color="blue">810:</font>    to get the exact error code.
+<font color="blue">811:</font> */
+<font color="blue">812:</font> 
+<font color="blue">813:</font>                         /* checksum functions */
+<font color="blue">814:</font> 
+<font color="blue">815:</font> /*
+<font color="blue">816:</font>      These functions are not related to compression but are exported
+<font color="blue">817:</font>    anyway because they might be useful in applications using the
+<font color="blue">818:</font>    compression library.
+<font color="blue">819:</font> */
+<font color="blue">820:</font> 
+<font color="blue">821:</font> ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
+<font color="blue">822:</font> 
+<font color="blue">823:</font> /*
+<font color="blue">824:</font>      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+<font color="blue">825:</font>    return the updated checksum. If buf is NULL, this function returns
+<font color="blue">826:</font>    the required initial value for the checksum.
+<font color="blue">827:</font>    An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+<font color="blue">828:</font>    much faster. Usage example:
+<font color="blue">829:</font> 
+<font color="blue">830:</font>      uLong adler = adler32(0L, Z_NULL, 0);
+<font color="blue">831:</font> 
+<font color="blue">832:</font>      while (read_buffer(buffer, length) != EOF) {
+<font color="blue">833:</font>        adler = adler32(adler, buffer, length);
+<font color="blue">834:</font>      }
+<font color="blue">835:</font>      if (adler != original_adler) error();
+<font color="blue">836:</font> */
+<font color="blue">837:</font> 
+<font color="blue">838:</font> ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
+<font color="blue">839:</font> /*
+<font color="blue">840:</font>      Update a running crc with the bytes buf[0..len-1] and return the updated
+<font color="blue">841:</font>    crc. If buf is NULL, this function returns the required initial value
+<font color="blue">842:</font>    for the crc. Pre- and post-conditioning (one's complement) is performed
+<font color="blue">843:</font>    within this function so it shouldn't be done by the application.
+<font color="blue">844:</font>    Usage example:
+<font color="blue">845:</font> 
+<font color="blue">846:</font>      uLong crc = crc32(0L, Z_NULL, 0);
+<font color="blue">847:</font> 
+<font color="blue">848:</font>      while (read_buffer(buffer, length) != EOF) {
+<font color="blue">849:</font>        crc = crc32(crc, buffer, length);
+<font color="blue">850:</font>      }
+<font color="blue">851:</font>      if (crc != original_crc) error();
+<font color="blue">852:</font> */
+<font color="blue">853:</font> 
+<font color="blue">854:</font> 
+<font color="blue">855:</font>                         /* various hacks, don't look :) */
+<font color="blue">856:</font> 
+<font color="blue">857:</font> /* deflateInit and inflateInit are macros to allow checking the zlib version
+<font color="blue">858:</font>  * and the compiler's view of z_stream:
+<font color="blue">859:</font>  */
+<font color="blue">860:</font> ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
+<font color="blue">861:</font>                                      const char *version, int stream_size));
+<font color="blue">862:</font> ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
+<font color="blue">863:</font>                                      const char *version, int stream_size));
+<font color="blue">864:</font> ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
+<font color="blue">865:</font>                                       int windowBits, int memLevel,
+<font color="blue">866:</font>                                       int strategy, const char *version,
+<font color="blue">867:</font>                                       int stream_size));
+<font color="blue">868:</font> ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
+<font color="blue">869:</font>                                       const char *version, int stream_size));
+<font color="blue"><a name="initmacros">870:</a></font> #define deflateInit(strm, level) \
+<font color="blue">871:</font>         deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
+<font color="blue">872:</font> #define inflateInit(strm) \
+<font color="blue">873:</font>         inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
+<font color="blue">874:</font> #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+<font color="blue">875:</font>         deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+<font color="blue">876:</font>                       (strategy),           ZLIB_VERSION, sizeof(z_stream))
+<font color="blue">877:</font> #define inflateInit2(strm, windowBits) \
+<font color="blue">878:</font>         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
+<font color="blue">879:</font> 
+<font color="blue">880:</font> 
+<font color="blue">881:</font> #if !defined(_Z_UTIL_H) &amp;&amp; !defined(NO_DUMMY_DECL)
+<font color="blue">882:</font>     struct internal_state {int dummy;}; /* hack for buggy compilers */
+<font color="blue">883:</font> #endif
+<font color="blue">884:</font> 
+<font color="blue">885:</font> ZEXTERN const char   * ZEXPORT zError           OF((int err));
+<font color="blue">886:</font> ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
+<font color="blue">887:</font> ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+<font color="blue">888:</font> 
+<font color="blue">889:</font> #ifdef __cplusplus
+<font color="blue">890:</font> }
+<font color="blue">891:</font> #endif
+<font color="blue">892:</font> 
+<font color="blue">893:</font> #endif /* _ZLIB_H */
+      </pre>
+    </blockquote>
+
+    <center><h2><a name="devel">How the zlib wrapper was developed</a></h2></center>
+
+    <h3>Attempt #1</h3>
+    <blockquote>
+      <pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+%include "zlib.h"
+      </pre>
+    </blockquote>
+
+    The result is:
+
+    <blockquote>
+      <pre>
+% swig -chicken -I/usr/include example.i
+<a href="#l63">/usr/include/zlib.h:63</a>: Syntax error in input.
+<a href="#l78">/usr/include/zlib.h:78</a>: Syntax error in input.
+<a href="#l80">/usr/include/zlib.h:80</a>: Syntax error in input.
+      </pre>
+    </blockquote>
+
+    The first problem we see is that the macro <code>OF(...)</code> is
+    not defined.
+
+    <h3>Attempt #2</h3>
+
+    We make sure to include <tt>zconf.h</tt> so that SWIG can see the
+    definition of <code>OF(...)</code>.  We try again.
+
+    <blockquote>
+      <pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+<font color="red">%include "zconf.h"</font>
+%include "zlib.h"
+      </pre>
+    </blockquote>
+
+    The result is:
+
+    <blockquote>
+      <pre>
+% swig -chicken -I/usr/include example.i
+      </pre>
+    </blockquote>
+
+    This seems to work!  But we should take a peek inside the generated
+    <tt>example_wrap.c</tt> to see what the names of the Scheme
+    procedures will be.
+
+    <blockquote>
+      <pre>
+% grep C_intern example_wrap.c
+  C_word err = C_intern2 (&amp;a, errorhook);
+    sym = C_intern (&amp;a, 21, "example:max-mem-level");
+    sym = C_intern (&amp;a, 17, "example:max-wbits");
+    sym = C_intern (&amp;a, 16, "example:seek-set");
+    sym = C_intern (&amp;a, 16, "example:seek-cur");
+    sym = C_intern (&amp;a, 16, "example:seek-end");
+    sym = C_intern (&amp;a, 20, "example:zlib-version");
+    sym = C_intern (&amp;a, 28, "example:z-stream-next-in-set");
+    sym = C_intern (&amp;a, 28, "example:z-stream-next-in-get");
+    sym = C_intern (&amp;a, 29, "example:z-stream-avail-in-set");
+    sym = C_intern (&amp;a, 29, "example:z-stream-avail-in-get");
+    sym = C_intern (&amp;a, 29, "example:z-stream-total-in-set");
+    sym = C_intern (&amp;a, 29, "example:z-stream-total-in-get");
+    sym = C_intern (&amp;a, 29, "example:z-stream-next-out-set");
+    sym = C_intern (&amp;a, 29, "example:z-stream-next-out-get");
+    sym = C_intern (&amp;a, 30, "example:z-stream-avail-out-set");
+    sym = C_intern (&amp;a, 30, "example:z-stream-avail-out-get");
+    sym = C_intern (&amp;a, 30, "example:z-stream-total-out-set");
+    sym = C_intern (&amp;a, 30, "example:z-stream-total-out-get");
+    sym = C_intern (&amp;a, 24, "example:z-stream-msg-set");
+    sym = C_intern (&amp;a, 24, "example:z-stream-msg-get");
+    sym = C_intern (&amp;a, 26, "example:z-stream-state-set");
+    sym = C_intern (&amp;a, 26, "example:z-stream-state-get");
+    sym = C_intern (&amp;a, 27, "example:z-stream-zalloc-set");
+    sym = C_intern (&amp;a, 27, "example:z-stream-zalloc-get");
+    sym = C_intern (&amp;a, 26, "example:z-stream-zfree-set");
+    sym = C_intern (&amp;a, 26, "example:z-stream-zfree-get");
+    sym = C_intern (&amp;a, 27, "example:z-stream-opaque-set");
+    sym = C_intern (&amp;a, 27, "example:z-stream-opaque-get");
+    sym = C_intern (&amp;a, 30, "example:z-stream-data-type-set");
+    sym = C_intern (&amp;a, 30, "example:z-stream-data-type-get");
+    sym = C_intern (&amp;a, 26, "example:z-stream-adler-set");
+    sym = C_intern (&amp;a, 26, "example:z-stream-adler-get");
+    sym = C_intern (&amp;a, 29, "example:z-stream-reserved-set");
+    sym = C_intern (&amp;a, 29, "example:z-stream-reserved-get");
+    sym = C_intern (&amp;a, 20, "example:new-z-stream");
+    sym = C_intern (&amp;a, 23, "example:delete-z-stream");
+    sym = C_intern (&amp;a, 18, "example:z-no-flush");
+    sym = C_intern (&amp;a, 23, "example:z-partial-flush");
+    sym = C_intern (&amp;a, 20, "example:z-sync-flush");
+    sym = C_intern (&amp;a, 20, "example:z-full-flush");
+    sym = C_intern (&amp;a, 16, "example:z-finish");
+    sym = C_intern (&amp;a, 12, "example:z-ok");
+    sym = C_intern (&amp;a, 20, "example:z-stream-end");
+    sym = C_intern (&amp;a, 19, "example:z-need-dict");
+    sym = C_intern (&amp;a, 15, "example:z-errno");
+    sym = C_intern (&amp;a, 22, "example:z-stream-error");
+    sym = C_intern (&amp;a, 20, "example:z-data-error");
+    sym = C_intern (&amp;a, 19, "example:z-mem-error");
+    sym = C_intern (&amp;a, 19, "example:z-buf-error");
+    sym = C_intern (&amp;a, 23, "example:z-version-error");
+    sym = C_intern (&amp;a, 24, "example:z-no-compression");
+    sym = C_intern (&amp;a, 20, "example:z-best-speed");
+    sym = C_intern (&amp;a, 26, "example:z-best-compression");
+    sym = C_intern (&amp;a, 29, "example:z-default-compression");
+    sym = C_intern (&amp;a, 18, "example:z-filtered");
+    sym = C_intern (&amp;a, 22, "example:z-huffman-only");
+    sym = C_intern (&amp;a, 26, "example:z-default-strategy");
+    sym = C_intern (&amp;a, 16, "example:z-binary");
+    sym = C_intern (&amp;a, 15, "example:z-ascii");
+    sym = C_intern (&amp;a, 17, "example:z-unknown");
+    sym = C_intern (&amp;a, 18, "example:z-deflated");
+    sym = C_intern (&amp;a, 14, "example:z-null");
+    sym = C_intern (&amp;a, 19, "example:zlibversion");
+    sym = C_intern (&amp;a, 15, "example:deflate");
+    sym = C_intern (&amp;a, 18, "example:deflateend");
+    sym = C_intern (&amp;a, 15, "example:inflate");
+    sym = C_intern (&amp;a, 18, "example:inflateend");
+    sym = C_intern (&amp;a, 28, "example:deflatesetdictionary");
+    sym = C_intern (&amp;a, 19, "example:deflatecopy");
+    sym = C_intern (&amp;a, 20, "example:deflatereset");
+    sym = C_intern (&amp;a, 21, "example:deflateparams");
+    sym = C_intern (&amp;a, 28, "example:inflatesetdictionary");
+    sym = C_intern (&amp;a, 19, "example:inflatesync");
+    sym = C_intern (&amp;a, 20, "example:inflatereset");
+    sym = C_intern (&amp;a, 16, "example:compress");
+    sym = C_intern (&amp;a, 17, "example:compress2");
+    sym = C_intern (&amp;a, 18, "example:uncompress");
+    sym = C_intern (&amp;a, 14, "example:gzopen");
+    sym = C_intern (&amp;a, 15, "example:gzdopen");
+    sym = C_intern (&amp;a, 19, "example:gzsetparams");
+    sym = C_intern (&amp;a, 14, "example:gzread");
+    sym = C_intern (&amp;a, 15, "example:gzwrite");
+    sym = C_intern (&amp;a, 16, "example:gzprintf");
+    sym = C_intern (&amp;a, 14, "example:gzputs");
+    sym = C_intern (&amp;a, 14, "example:gzgets");
+    sym = C_intern (&amp;a, 14, "example:gzputc");
+    sym = C_intern (&amp;a, 14, "example:gzgetc");
+    sym = C_intern (&amp;a, 15, "example:gzflush");
+    sym = C_intern (&amp;a, 14, "example:gzseek");
+    sym = C_intern (&amp;a, 16, "example:gzrewind");
+    sym = C_intern (&amp;a, 14, "example:gztell");
+    sym = C_intern (&amp;a, 13, "example:gzeof");
+    sym = C_intern (&amp;a, 15, "example:gzclose");
+    sym = C_intern (&amp;a, 15, "example:gzerror");
+    sym = C_intern (&amp;a, 15, "example:adler32");
+    sym = C_intern (&amp;a, 13, "example:crc32");
+    sym = C_intern (&amp;a, 20, "example:deflateinit-");
+    sym = C_intern (&amp;a, 20, "example:inflateinit-");
+    sym = C_intern (&amp;a, 21, "example:deflateinit2-");
+    sym = C_intern (&amp;a, 21, "example:inflateinit2-");
+    sym = C_intern (&amp;a, 32, "example:internal-state-dummy-set");
+    sym = C_intern (&amp;a, 32, "example:internal-state-dummy-get");
+    sym = C_intern (&amp;a, 26, "example:new-internal-state");
+    sym = C_intern (&amp;a, 29, "example:delete-internal-state");
+    sym = C_intern (&amp;a, 14, "example:zerror");
+    sym = C_intern (&amp;a, 24, "example:inflatesyncpoint");
+    sym = C_intern (&amp;a, 21, "example:get-crc-table");
+      </pre>
+    </blockquote>
+
+    In fact, we want the Scheme procedure names to begin with
+    <code>zlib</code> instead of <code>example</code>.  For
+    <code>example:zlib-version</code>, we want
+    <code>zlib-version</code>.  And we want dashes when the case
+    switches to/from upper/lowercase; ex. the function
+    <code>deflateEnd()</code> should be the Scheme procedure
+    <code>zlib-deflate-end</code>.
+
+    <h3>Attempt #3</h3>
+
+    We make sure to add <tt>-prefix zlib -mixed</tt> to the
+    <tt>swig</tt> command line, and we rename
+    <code>ZLIB_VERSION</code> to <code>VERSION</code>.  We try again.
+
+    <blockquote>
+      <pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+<font color="red">%rename(VERSION) ZLIB_VERSION;</font>
+
+%include "zconf.h"
+%include "zlib.h"
+      </pre>
+    </blockquote>
+
+    The result is:
+
+    <blockquote>
+      <pre>
+% swig -chicken <font color="red">-prefix zlib -mixed</font> -I/usr/include example.i
+% grep C_intern example_wrap.c
+  C_word err = C_intern2 (&amp;a, errorhook);
+    sym = C_intern (&amp;a, 18, "zlib:max-mem-level");
+    sym = C_intern (&amp;a, 14, "zlib:max-wbits");
+    sym = C_intern (&amp;a, 13, "zlib:seek-set");
+    sym = C_intern (&amp;a, 13, "zlib:seek-cur");
+    sym = C_intern (&amp;a, 13, "zlib:seek-end");
+    sym = C_intern (&amp;a, 12, "zlib:version");
+    sym = C_intern (&amp;a, 25, "zlib:z-stream-next-in-set");
+    sym = C_intern (&amp;a, 25, "zlib:z-stream-next-in-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-avail-in-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-avail-in-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-total-in-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-total-in-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-next-out-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-next-out-get");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-avail-out-set");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-avail-out-get");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-total-out-set");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-total-out-get");
+    sym = C_intern (&amp;a, 21, "zlib:z-stream-msg-set");
+    sym = C_intern (&amp;a, 21, "zlib:z-stream-msg-get");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-state-set");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-state-get");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-zalloc-set");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-zalloc-get");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-zfree-set");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-zfree-get");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-opaque-set");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-opaque-get");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-data-type-set");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-data-type-get");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-adler-set");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-adler-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-reserved-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-reserved-get");
+    sym = C_intern (&amp;a, 17, "zlib:new-z-stream");
+    sym = C_intern (&amp;a, 20, "zlib:delete-z-stream");
+    sym = C_intern (&amp;a, 15, "zlib:z-no-flush");
+    sym = C_intern (&amp;a, 20, "zlib:z-partial-flush");
+    sym = C_intern (&amp;a, 17, "zlib:z-sync-flush");
+    sym = C_intern (&amp;a, 17, "zlib:z-full-flush");
+    sym = C_intern (&amp;a, 13, "zlib:z-finish");
+    sym = C_intern (&amp;a, 9, "zlib:z-ok");
+    sym = C_intern (&amp;a, 17, "zlib:z-stream-end");
+    sym = C_intern (&amp;a, 16, "zlib:z-need-dict");
+    sym = C_intern (&amp;a, 12, "zlib:z-errno");
+    sym = C_intern (&amp;a, 19, "zlib:z-stream-error");
+    sym = C_intern (&amp;a, 17, "zlib:z-data-error");
+    sym = C_intern (&amp;a, 16, "zlib:z-mem-error");
+    sym = C_intern (&amp;a, 16, "zlib:z-buf-error");
+    sym = C_intern (&amp;a, 20, "zlib:z-version-error");
+    sym = C_intern (&amp;a, 21, "zlib:z-no-compression");
+    sym = C_intern (&amp;a, 17, "zlib:z-best-speed");
+    sym = C_intern (&amp;a, 23, "zlib:z-best-compression");
+    sym = C_intern (&amp;a, 26, "zlib:z-default-compression");
+    sym = C_intern (&amp;a, 15, "zlib:z-filtered");
+    sym = C_intern (&amp;a, 19, "zlib:z-huffman-only");
+    sym = C_intern (&amp;a, 23, "zlib:z-default-strategy");
+    sym = C_intern (&amp;a, 13, "zlib:z-binary");
+    sym = C_intern (&amp;a, 12, "zlib:z-ascii");
+    sym = C_intern (&amp;a, 14, "zlib:z-unknown");
+    sym = C_intern (&amp;a, 15, "zlib:z-deflated");
+    sym = C_intern (&amp;a, 11, "zlib:z-null");
+    sym = C_intern (&amp;a, 17, "zlib:zlib-version");
+    sym = C_intern (&amp;a, 12, "zlib:deflate");
+    sym = C_intern (&amp;a, 16, "zlib:deflate-end");
+    sym = C_intern (&amp;a, 12, "zlib:inflate");
+    sym = C_intern (&amp;a, 16, "zlib:inflate-end");
+    sym = C_intern (&amp;a, 27, "zlib:deflate-set-dictionary");
+    sym = C_intern (&amp;a, 17, "zlib:deflate-copy");
+    sym = C_intern (&amp;a, 18, "zlib:deflate-reset");
+    sym = C_intern (&amp;a, 19, "zlib:deflate-params");
+    sym = C_intern (&amp;a, 27, "zlib:inflate-set-dictionary");
+    sym = C_intern (&amp;a, 17, "zlib:inflate-sync");
+    sym = C_intern (&amp;a, 18, "zlib:inflate-reset");
+    sym = C_intern (&amp;a, 13, "zlib:compress");
+    sym = C_intern (&amp;a, 14, "zlib:compress2");
+    sym = C_intern (&amp;a, 15, "zlib:uncompress");
+    sym = C_intern (&amp;a, 11, "zlib:gzopen");
+    sym = C_intern (&amp;a, 12, "zlib:gzdopen");
+    sym = C_intern (&amp;a, 16, "zlib:gzsetparams");
+    sym = C_intern (&amp;a, 11, "zlib:gzread");
+    sym = C_intern (&amp;a, 12, "zlib:gzwrite");
+    sym = C_intern (&amp;a, 13, "zlib:gzprintf");
+    sym = C_intern (&amp;a, 11, "zlib:gzputs");
+    sym = C_intern (&amp;a, 11, "zlib:gzgets");
+    sym = C_intern (&amp;a, 11, "zlib:gzputc");
+    sym = C_intern (&amp;a, 11, "zlib:gzgetc");
+    sym = C_intern (&amp;a, 12, "zlib:gzflush");
+    sym = C_intern (&amp;a, 11, "zlib:gzseek");
+    sym = C_intern (&amp;a, 13, "zlib:gzrewind");
+    sym = C_intern (&amp;a, 11, "zlib:gztell");
+    sym = C_intern (&amp;a, 10, "zlib:gzeof");
+    sym = C_intern (&amp;a, 12, "zlib:gzclose");
+    sym = C_intern (&amp;a, 12, "zlib:gzerror");
+    sym = C_intern (&amp;a, 12, "zlib:adler32");
+    sym = C_intern (&amp;a, 10, "zlib:crc32");
+    sym = C_intern (&amp;a, 18, "zlib:deflate-init-");
+    sym = C_intern (&amp;a, 18, "zlib:inflate-init-");
+    sym = C_intern (&amp;a, 19, "zlib:deflate-init2-");
+    sym = C_intern (&amp;a, 19, "zlib:inflate-init2-");
+    sym = C_intern (&amp;a, 29, "zlib:internal-state-dummy-set");
+    sym = C_intern (&amp;a, 29, "zlib:internal-state-dummy-get");
+    sym = C_intern (&amp;a, 23, "zlib:new-internal-state");
+    sym = C_intern (&amp;a, 26, "zlib:delete-internal-state");
+    sym = C_intern (&amp;a, 12, "zlib:ze-rror");
+    sym = C_intern (&amp;a, 23, "zlib:inflate-sync-point");
+    sym = C_intern (&amp;a, 18, "zlib:get-crc-table");
+      </pre>
+    </blockquote>
+
+    Much better.  The only problem is the identifier
+    <code>zlib:ze-rror</code>, and we are missing
+    <code>zlib:deflate-init</code> and <code>zlib:inflate-init</code>
+    because they are defined as macros (see <a
+      href="#initmacros">macro definitions</a>).
+
+    <h3>Attempt #4</h3>
+
+    We make sure to rename <code>zError</code> to
+    <code>z_error</code>, and we inline some helper functions for the
+    <code>zlib:...-init</code> macros.  We try again.
+
+    <blockquote>
+      <pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+%rename(VERSION) ZLIB_VERSION;
+<font color="red">%rename(z_error) zError;</font>
+
+%include "zconf.h"
+%include "zlib.h"
+
+<font color="red">%inline %{
+/* %inline blocks are seen by SWIG and are inserted into the header
+   portion of example_wrap.c, so that they are also seen by the C
+   compiler. */
+int deflate_init(z_streamp strm, int level) {
+  return deflateInit(strm,level); /* call macro */
+}
+int inflate_init(z_streamp strm) {
+  return inflateInit(strm); /* call macro */
+}
+%}
+</font>
+
+      </pre>
+    </blockquote>
+
+    The result is:
+
+    <blockquote>
+      <pre>
+% swig -chicken -prefix zlib -mixed -I/usr/include example.i
+% grep C_intern example_wrap.c
+  C_word err = C_intern2 (&amp;a, errorhook);
+    sym = C_intern (&amp;a, 18, "zlib:max-mem-level");
+    sym = C_intern (&amp;a, 14, "zlib:max-wbits");
+    sym = C_intern (&amp;a, 13, "zlib:seek-set");
+    sym = C_intern (&amp;a, 13, "zlib:seek-cur");
+    sym = C_intern (&amp;a, 13, "zlib:seek-end");
+    sym = C_intern (&amp;a, 12, "zlib:version");
+    sym = C_intern (&amp;a, 25, "zlib:z-stream-next-in-set");
+    sym = C_intern (&amp;a, 25, "zlib:z-stream-next-in-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-avail-in-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-avail-in-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-total-in-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-total-in-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-next-out-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-next-out-get");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-avail-out-set");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-avail-out-get");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-total-out-set");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-total-out-get");
+    sym = C_intern (&amp;a, 21, "zlib:z-stream-msg-set");
+    sym = C_intern (&amp;a, 21, "zlib:z-stream-msg-get");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-state-set");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-state-get");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-zalloc-set");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-zalloc-get");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-zfree-set");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-zfree-get");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-opaque-set");
+    sym = C_intern (&amp;a, 24, "zlib:z-stream-opaque-get");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-data-type-set");
+    sym = C_intern (&amp;a, 27, "zlib:z-stream-data-type-get");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-adler-set");
+    sym = C_intern (&amp;a, 23, "zlib:z-stream-adler-get");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-reserved-set");
+    sym = C_intern (&amp;a, 26, "zlib:z-stream-reserved-get");
+    sym = C_intern (&amp;a, 17, "zlib:new-z-stream");
+    sym = C_intern (&amp;a, 20, "zlib:delete-z-stream");
+    sym = C_intern (&amp;a, 15, "zlib:z-no-flush");
+    sym = C_intern (&amp;a, 20, "zlib:z-partial-flush");
+    sym = C_intern (&amp;a, 17, "zlib:z-sync-flush");
+    sym = C_intern (&amp;a, 17, "zlib:z-full-flush");
+    sym = C_intern (&amp;a, 13, "zlib:z-finish");
+    sym = C_intern (&amp;a, 9, "zlib:z-ok");
+    sym = C_intern (&amp;a, 17, "zlib:z-stream-end");
+    sym = C_intern (&amp;a, 16, "zlib:z-need-dict");
+    sym = C_intern (&amp;a, 12, "zlib:z-errno");
+    sym = C_intern (&amp;a, 19, "zlib:z-stream-error");
+    sym = C_intern (&amp;a, 17, "zlib:z-data-error");
+    sym = C_intern (&amp;a, 16, "zlib:z-mem-error");
+    sym = C_intern (&amp;a, 16, "zlib:z-buf-error");
+    sym = C_intern (&amp;a, 20, "zlib:z-version-error");
+    sym = C_intern (&amp;a, 21, "zlib:z-no-compression");
+    sym = C_intern (&amp;a, 17, "zlib:z-best-speed");
+    sym = C_intern (&amp;a, 23, "zlib:z-best-compression");
+    sym = C_intern (&amp;a, 26, "zlib:z-default-compression");
+    sym = C_intern (&amp;a, 15, "zlib:z-filtered");
+    sym = C_intern (&amp;a, 19, "zlib:z-huffman-only");
+    sym = C_intern (&amp;a, 23, "zlib:z-default-strategy");
+    sym = C_intern (&amp;a, 13, "zlib:z-binary");
+    sym = C_intern (&amp;a, 12, "zlib:z-ascii");
+    sym = C_intern (&amp;a, 14, "zlib:z-unknown");
+    sym = C_intern (&amp;a, 15, "zlib:z-deflated");
+    sym = C_intern (&amp;a, 11, "zlib:z-null");
+    sym = C_intern (&amp;a, 17, "zlib:zlib-version");
+    sym = C_intern (&amp;a, 12, "zlib:deflate");
+    sym = C_intern (&amp;a, 16, "zlib:deflate-end");
+    sym = C_intern (&amp;a, 12, "zlib:inflate");
+    sym = C_intern (&amp;a, 16, "zlib:inflate-end");
+    sym = C_intern (&amp;a, 27, "zlib:deflate-set-dictionary");
+    sym = C_intern (&amp;a, 17, "zlib:deflate-copy");
+    sym = C_intern (&amp;a, 18, "zlib:deflate-reset");
+    sym = C_intern (&amp;a, 19, "zlib:deflate-params");
+    sym = C_intern (&amp;a, 27, "zlib:inflate-set-dictionary");
+    sym = C_intern (&amp;a, 17, "zlib:inflate-sync");
+    sym = C_intern (&amp;a, 18, "zlib:inflate-reset");
+    sym = C_intern (&amp;a, 13, "zlib:compress");
+    sym = C_intern (&amp;a, 14, "zlib:compress2");
+    sym = C_intern (&amp;a, 15, "zlib:uncompress");
+    sym = C_intern (&amp;a, 11, "zlib:gzopen");
+    sym = C_intern (&amp;a, 12, "zlib:gzdopen");
+    sym = C_intern (&amp;a, 16, "zlib:gzsetparams");
+    sym = C_intern (&amp;a, 11, "zlib:gzread");
+    sym = C_intern (&amp;a, 12, "zlib:gzwrite");
+    sym = C_intern (&amp;a, 13, "zlib:gzprintf");
+    sym = C_intern (&amp;a, 11, "zlib:gzputs");
+    sym = C_intern (&amp;a, 11, "zlib:gzgets");
+    sym = C_intern (&amp;a, 11, "zlib:gzputc");
+    sym = C_intern (&amp;a, 11, "zlib:gzgetc");
+    sym = C_intern (&amp;a, 12, "zlib:gzflush");
+    sym = C_intern (&amp;a, 11, "zlib:gzseek");
+    sym = C_intern (&amp;a, 13, "zlib:gzrewind");
+    sym = C_intern (&amp;a, 11, "zlib:gztell");
+    sym = C_intern (&amp;a, 10, "zlib:gzeof");
+    sym = C_intern (&amp;a, 12, "zlib:gzclose");
+    sym = C_intern (&amp;a, 12, "zlib:gzerror");
+    sym = C_intern (&amp;a, 12, "zlib:adler32");
+    sym = C_intern (&amp;a, 10, "zlib:crc32");
+    sym = C_intern (&amp;a, 18, "zlib:deflate-init-");
+    sym = C_intern (&amp;a, 18, "zlib:inflate-init-");
+    sym = C_intern (&amp;a, 19, "zlib:deflate-init2-");
+    sym = C_intern (&amp;a, 19, "zlib:inflate-init2-");
+    sym = C_intern (&amp;a, 29, "zlib:internal-state-dummy-set");
+    sym = C_intern (&amp;a, 29, "zlib:internal-state-dummy-get");
+    sym = C_intern (&amp;a, 23, "zlib:new-internal-state");
+    sym = C_intern (&amp;a, 26, "zlib:delete-internal-state");
+    sym = C_intern (&amp;a, 12, "zlib:z-error");
+    sym = C_intern (&amp;a, 23, "zlib:inflate-sync-point");
+    sym = C_intern (&amp;a, 18, "zlib:get-crc-table");
+    sym = C_intern (&amp;a, 17, "zlib:deflate-init");
+    sym = C_intern (&amp;a, 17, "zlib:inflate-init");
+      </pre>
+    </blockquote>
+
+    Perfect!  Now let's integrate this zlib extension into a
+    CHICKEN interpreter.  To save some time, in this
+    Examples/chicken/zlib directory:
+    <ol>
+      <li>Backup the original <tt>example.i</tt>.</li>
+      <li>Copy and paste the <tt>example.i</tt> text from above and
+	put it into the file called <tt>example.i</tt></li>
+      <li>Run 'make' as per <a href="#build">Building the
+	  example</a>.</li>
+      <li>Run the resultant executable <tt>zlib</tt>.</li>
+    </ol>
+
+    The interpreter interaction is as follows:
+
+    <blockquote>
+      <pre>
+% ./zlib
+zlib
+
+  A SWIG example for the CHICKEN compiler
+  Author: Jonah Beckford, February 2003
+
+Scheme Procedures:
+
+zlib:max-mem-level
+zlib:max-wbits
+zlib:seek-set
+zlib:seek-cur
+zlib:seek-end
+zlib:version
+zlib:z-stream-next-in-set
+zlib:z-stream-next-in-get
+zlib:z-stream-avail-in-set
+...
+zlib:get-crc-table
+zlib:deflate-init
+zlib:inflate-init
+; This is the CHICKEN interpreter - Version 0, Build 1095 - windows-cygwin-x86
+; (c)2000-2003 Felix L. Winkelmann
+&gt;&gt;&gt; (define s (zlib:new-z-stream))
+&gt;&gt;&gt; s
+#&lt;tagged pointer #&lt;c++ "z_stream *"&gt;(#&lt;pointer 6d9290&gt;)&gt;
+&gt;&gt;&gt; (zlib:z-stream-next-in-get s)
+#f
+&gt;&gt;&gt; (zlib:z-stream-next-in-set s "some dummy stream data")
+Error: Type error. Expected _p_Bytef: "bad argument type"
+&gt;&gt;&gt; (exit)
+      </pre>
+    </blockquote>
+
+    Apparently we cannot use Scheme strings as <code>Bytef *</code>.  The SWIG
+    manual shows many ways how to handle strings and byte arrays, but
+    to be simplistic, let's just make the <code>Bytef *</code> look
+    like a <code>char *</code>, which is automatically handled as a
+    string by SWIG CHICKEN.
+
+    <h3>Attempt #5</h3>
+
+    We make sure to add an %apply construct so that <code>Bytef
+    *</code> is handled the same as <code>char *</code> to SWIG.  We
+    try again.
+
+    <blockquote>
+      <pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+%rename(VERSION) ZLIB_VERSION;
+%rename(z_error) zError;
+<font color="red">%apply char * { Bytef * };</font>
+
+%include "zconf.h"
+%include "zlib.h"
+
+%inline %{
+/* %inline blocks are seen by SWIG and are inserted into the header
+   portion of example_wrap.c, so that they are also seen by the C
+   compiler. */
+int deflate_init(z_streamp strm, int level) {
+  return deflateInit(strm,level); /* call macro */
+}
+int inflate_init(z_streamp strm) {
+  return inflateInit(strm); /* call macro */
+}
+%}
+      </pre>
+    </blockquote>
+
+    Build the example once more.<br>
+
+    The interpreter interaction is as follows:
+
+    <blockquote>
+      <pre>
+% ./zlib
+zlib
+
+  A SWIG example for the CHICKEN compiler
+  Author: Jonah Beckford, February 2003
+
+Scheme Procedures:
+
+zlib:max-mem-level
+zlib:max-wbits
+zlib:seek-set
+zlib:seek-cur
+zlib:seek-end
+zlib:version
+zlib:z-stream-next-in-set
+zlib:z-stream-next-in-get
+zlib:z-stream-avail-in-set
+...
+zlib:get-crc-table
+zlib:deflate-init
+zlib:inflate-init
+; This is the CHICKEN interpreter - Version 0, Build 1095 - windows-cygwin-x86
+; (c)2000-2003 Felix L. Winkelmann
+&gt;&gt;&gt; (define s (zlib:new-z-stream))
+<em>Init zstream</em>
+&gt;&gt;&gt; (zlib:z-stream-zalloc-set s #f) 
+&gt;&gt;&gt; (zlib:z-stream-zfree-set s #f)
+&gt;&gt;&gt; (zlib:z-stream-opaque-set s #f)
+&gt;&gt;&gt; (zlib:deflate-init s (zlib:z-default-compression))
+0
+<em>Deflate something small so we don't need to loop/stream data</em>
+&gt;&gt;&gt; (define in "some dummy data")
+&gt;&gt;&gt; (define out (make-string 1000))
+&gt;&gt;&gt; (zlib:z-stream-next-in-set s in)
+&gt;&gt;&gt; (zlib:z-stream-avail-in-set s (string-length in))
+&gt;&gt;&gt; (zlib:z-stream-next-out-set s out)
+&gt;&gt;&gt; (zlib:z-stream-avail-out-set s (string-length out))
+&gt;&gt;&gt; (zlib:deflate s (zlib:z-finish))
+1 <em>;; (zlib:z-stream-end) == 1, which is good</em>
+&gt;&gt;&gt; (zlib:z-stream-total-out-get s)
+23.
+&gt;&gt;&gt; out
+"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        "
+      </pre>
+    </blockquote>
+
+    We see the problem ... the compression is occurring as it should,
+    but we cannot see any of the compressed output.  This is because
+    when SWIG CHICKEN passes a Scheme string to a C function, it
+    duplicates the string before calling the C function.  We want to
+    save the memory address that
+    <code>zlib:z-stream-next-out-set</code> is using, so we can
+    display this later.  While we are at it, we can foresee that
+    <code>compress</code>, <code>compress2</code> and
+    <code>uncompress</code> will all need some finessing to work with
+    mutating strings.
+
+    <h3>Attempt #6</h3>
+
+    When we have to finesse strings, we must use typemaps.  As well,
+    we define some functions to save and restore the
+    <code>next_out</code> element.  We try again.
+
+    <blockquote>
+      <pre>
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+%rename(VERSION) ZLIB_VERSION;
+%rename(z_error) zError;
+%apply char * { Bytef * };
+	<font color="red">
+/* Allow the sourceLen to be automatically filled in from the length
+   of the 'source' string */
+%typemap(in) (const Bytef *source, uLong sourceLen)
+%{  if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string");
+  }
+  $2 = (uLong) C_header_size ($input);
+  $1 = C_c_string ($input);
+%}
+
+/* Allocate space the size of which is determined by the Scheme
+   integer argument, and make a temporary integer so we can set
+   destLen. */
+%typemap(in) (Bytef *dest, uLongf *destLen) (uLong len)
+%{  if (!C_swig_is_fixnum ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a integer");
+  }
+  len = (uLong) C_unfix ($input);
+  $2 = &amp;len;
+  $1 = (char *) malloc (*$2);
+%}
+
+/* Return the mutated string as a new object. */
+%typemap(argout) (Bytef *dest, uLongf *destLen) 
+(C_word *scmstr) 
+%{  scmstr = C_alloc (C_SIZEOF_STRING (*$2));
+  SWIG_APPEND_VALUE(C_string (&amp;scmstr, *$2, $1));
+  free ($1);
+%}
+	</font>
+%include "zconf.h"
+%include "zlib.h"
+	<font color="red">
+/* Ignore destLen as an input argument, and make a temporary integer so
+   we can set destLen. */
+%typemap(in, numinputs=0) uLongf *destLen (uLong len)
+"$1 = &amp;len;";
+
+/* Return a sized string as a new object. */
+%typemap(argout)
+(void *outstr, uLongf *destLen) (C_word *scmstr) 
+%{  scmstr = C_alloc (C_SIZEOF_STRING (*$2));
+  SWIG_APPEND_VALUE(C_string (&amp;scmstr, *$2, $1));
+%}
+	</font>
+%inline %{
+/* %inline blocks are seen by SWIG and are inserted into the header
+   portion of example_wrap.c, so that they are also seen by the C
+   compiler. */
+int deflate_init(z_streamp strm, int level) {
+  return deflateInit(strm,level); /* call macro */
+}
+int inflate_init(z_streamp strm) {
+  return inflateInit(strm); /* call macro */
+}
+<font color="red">void* z_stream_save_next_out(z_streamp strm) {
+  return (void*) strm-&gt;next_out;
+}
+void z_stream_get_next_chunk(z_streamp strm, void *outstr, uLongf *destLen) {
+  *destLen = strm-&gt;next_out - (Bytef*)outstr;
+}</font>
+%}
+      </pre>
+    </blockquote>
+
+    And that's it.  Try building the entire example from the
+    Makefile.  Run <tt>./zlib test-zlib.scm</tt> to test it out.
+
+  </body>
+</html>
diff --git a/trunk/Examples/chicken/zlib/example.i b/trunk/Examples/chicken/zlib/example.i
new file mode 100644
index 0000000..dd962ad
--- /dev/null
+++ b/trunk/Examples/chicken/zlib/example.i
@@ -0,0 +1,76 @@
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+#include "zlib.h"
+%}
+
+%include typemaps.i
+
+%rename(VERSION) ZLIB_VERSION;
+%rename(z_error) zError;
+%apply char * { Bytef * };
+
+/* Allow the sourceLen to be automatically filled in from the length
+   of the 'source' string */
+%typemap(in) (const Bytef *source, uLong sourceLen)
+%{  if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a string");
+  }
+  $2 = (uLong) C_header_size ($input);
+  $1 = C_c_string ($input);
+%}
+
+/* Allocate space the size of which is determined by the Scheme
+   integer argument, and make a temporary integer so we can set
+   destLen. */
+%typemap(in) (Bytef *dest, uLongf *destLen) (uLong len)
+%{  if (!C_swig_is_fixnum ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument $input is not a integer");
+  }
+  len = (uLong) C_unfix ($input);
+  $2 = &len;
+  $1 = (char *) malloc (*$2);
+%}
+
+/* Return the mutated string as a new object. */
+%typemap(argout) (Bytef *dest, uLongf *destLen) 
+(C_word *scmstr) 
+%{  scmstr = C_alloc (C_SIZEOF_STRING (*$2));
+  SWIG_APPEND_VALUE(C_string (&scmstr, *$2, $1));
+  free ($1);
+%}
+
+%include "zconf.h"
+%include "zlib.h"
+
+/* Ignore destLen as an input argument, and make a temporary integer so
+   we can set destLen. */
+%typemap(numinputs=0) uLongf *destLen (uLong len)
+"$1 = &len;";
+
+/* Return a sized string as a new object. */
+%typemap(argout)
+(void *outstr, uLongf *destLen) (C_word *scmstr) 
+%{  scmstr = C_alloc (C_SIZEOF_STRING (*$2));
+  SWIG_APPEND_VALUE(C_string (&scmstr, *$2, $1));
+%}
+
+%inline %{
+/* %inline blocks are seen by SWIG and are inserted into the header
+   portion of example_wrap.c, so that they are also seen by the C
+   compiler. */
+int deflate_init(z_streamp strm, int level) {
+  return deflateInit(strm,level); /* call macro */
+}
+int inflate_init(z_streamp strm) {
+  return inflateInit(strm); /* call macro */
+}
+void* z_stream_save_next_out(z_streamp strm) {
+  return (void*) strm->next_out;
+}
+void z_stream_get_next_chunk(z_streamp strm, void *outstr, uLongf *destLen) {
+  *destLen = strm->next_out - (Bytef*)outstr;
+}
+%}
+
diff --git a/trunk/Examples/chicken/zlib/test-zlib.scm b/trunk/Examples/chicken/zlib/test-zlib.scm
new file mode 100644
index 0000000..a13d801
--- /dev/null
+++ b/trunk/Examples/chicken/zlib/test-zlib.scm
@@ -0,0 +1,41 @@
+(load-library 'example "./zlib.so")
+
+;; Init zstream
+(define s (new-z-stream))
+(z-stream-zalloc-set s #f)
+(z-stream-zfree-set s #f)
+(z-stream-opaque-set s #f)
+(deflate-init s (Z-DEFAULT-COMPRESSION))
+
+;; Deflate something small so we don't need to loop/stream data
+(define in "some pony et jumping et jack et flash et had a jack pony")
+(define out (make-string 1000))
+(printf "to be compressed: ~A~%to be compressed bytes: ~A~%~%" in (string-length in))
+(z-stream-next-in-set s in)
+(z-stream-avail-in-set s (string-length in))
+(z-stream-next-out-set s out)
+(z-stream-avail-out-set s (string-length out))
+(let*
+    ((saved-out (z-stream-save-next-out s))
+     (ret (deflate s (Z-FINISH))))
+  (cond
+   ((= ret (Z-STREAM-END))
+    (printf "deflated properly!~%compressed bytes: ~A~%compressed stream: ~A~%" 
+            (z-stream-total-out-get s) (z-stream-get-next-chunk s saved-out)))
+   ((= ret (Z-OK))
+    (display "only partial deflation ... not enough output space\n"))
+   (else
+    (printf "deflate error(~D): ~A ~%" ret (z-stream-msg-get s)))))
+
+;; Use simple compress routine, and set max output size to 100
+(newline)
+(call-with-values (lambda () (compress 100 in))
+  (lambda (ret compressed)
+    (cond
+     ((= ret (Z-OK))
+      (printf "compressed properly!~%compressed bytes: ~A~%compressed stream: ~A~%"
+              (string-length compressed) compressed))
+     (else
+      (printf "compress error(~D): ~A ~%" ret (z-error ret))))))
+
+(exit 0)
diff --git a/trunk/Examples/contract/simple_c/example.c b/trunk/Examples/contract/simple_c/example.c
new file mode 100644
index 0000000..85a3e14
--- /dev/null
+++ b/trunk/Examples/contract/simple_c/example.c
@@ -0,0 +1,11 @@
+#include <stdio.h>
+
+int Circle (int x, int y, int radius) {
+  /* Draw Circle */
+  printf("Drawing the circle...\n");
+  /* Return -1 to test contract post assertion */
+  if (radius == 2)
+    return -1;
+  else
+    return 1;
+}
diff --git a/trunk/Examples/contract/simple_c/example.i b/trunk/Examples/contract/simple_c/example.i
new file mode 100644
index 0000000..49df09a
--- /dev/null
+++ b/trunk/Examples/contract/simple_c/example.i
@@ -0,0 +1,19 @@
+/* File : example.i */
+
+/* Basic C example for swig contract */
+/* Tiger, University of Chicago, 2003 */
+
+%module example
+
+%contract Circle (int x, int y, int radius) {
+require:
+     x      >= 0;
+     y      >= 0;
+     radius >  x;
+ensure:
+     Circle >= 0;
+}
+
+%inline %{
+extern int Circle (int x, int y, int radius);
+%}
diff --git a/trunk/Examples/contract/simple_c/runme1.py b/trunk/Examples/contract/simple_c/runme1.py
new file mode 100644
index 0000000..abd8df6
--- /dev/null
+++ b/trunk/Examples/contract/simple_c/runme1.py
@@ -0,0 +1,17 @@
+import example 
+# Call the Circle() function correctly
+
+x = 1;
+y = 1;
+r = 3;
+
+c = example.Circle(x, y, r)
+
+# test post-assertion
+x = 1;
+y = 1;
+r = 2;
+
+c = example.Circle(x, y, r)
+
+print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c)
diff --git a/trunk/Examples/contract/simple_c/runme2.py b/trunk/Examples/contract/simple_c/runme2.py
new file mode 100644
index 0000000..48d4a3f
--- /dev/null
+++ b/trunk/Examples/contract/simple_c/runme2.py
@@ -0,0 +1,20 @@
+import example 
+
+# Call the Circle() function correctly
+
+x = 1;
+y = 1;
+r = 3;
+
+c = example.Circle(x, y, r)
+
+print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c)
+
+# test pre-assertion
+x = 1;
+y = -1;
+r = 3;
+
+c = example.Circle(x, y, r)
+
+print "The return value of Circle(%d, %d, %d) is %d" % (x,y,r,c)
diff --git a/trunk/Examples/contract/simple_cxx/example.cxx b/trunk/Examples/contract/simple_cxx/example.cxx
new file mode 100644
index 0000000..e3dd2ca
--- /dev/null
+++ b/trunk/Examples/contract/simple_cxx/example.cxx
@@ -0,0 +1,30 @@
+#include "example.h"
+
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  /* return -1 is to test post-assertion */
+  if (radius == 1)
+    return -1;
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/contract/simple_cxx/example.h b/trunk/Examples/contract/simple_cxx/example.h
new file mode 100644
index 0000000..64b7684
--- /dev/null
+++ b/trunk/Examples/contract/simple_cxx/example.h
@@ -0,0 +1,34 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
diff --git a/trunk/Examples/contract/simple_cxx/example.i b/trunk/Examples/contract/simple_cxx/example.i
new file mode 100644
index 0000000..9b47409
--- /dev/null
+++ b/trunk/Examples/contract/simple_cxx/example.i
@@ -0,0 +1,28 @@
+%module example
+
+%contract Circle::Circle(double radius) {
+require:
+    radius > 0;
+}
+
+%contract Circle::area(void) {
+ensure:
+    area > 0;
+}
+
+%contract Shape::move(double dx, double dy) {
+require:
+    dx > 0;
+}
+
+/* should be no effect, since there is no move() for class Circle */
+%contract Circle::move(double dx, double dy) {
+require:
+    dy > 1;
+}
+
+# include must be after contracts
+%{
+#include "example.h"
+%}
+%include "example.h"
diff --git a/trunk/Examples/contract/simple_cxx/runme1.py b/trunk/Examples/contract/simple_cxx/runme1.py
new file mode 100644
index 0000000..9028d02
--- /dev/null
+++ b/trunk/Examples/contract/simple_cxx/runme1.py
@@ -0,0 +1,33 @@
+import example 
+
+# Create the Circle object
+
+r = 2;
+print "  Creating circle (radium: %d) :" % r
+c = example.Circle(r)
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+print "  Here is its current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+
+# ----- Call some methods -----
+
+print "\n  Here are some properties of the Circle:"
+print "    area      = ", c.area()
+print "    perimeter = ", c.perimeter()
+dx = 1;
+dy = 1;
+print "    Moving with (%d, %d)..." % (dx, dy)
+c.move(dx, dy)
+
+del c
+
+print "==================================="
+
+# test construction */
+r = -1;
+print "  Creating circle (radium: %d) :" % r 
+c = example.Circle(r)
diff --git a/trunk/Examples/contract/simple_cxx/runme2.py b/trunk/Examples/contract/simple_cxx/runme2.py
new file mode 100644
index 0000000..5f9c0df
--- /dev/null
+++ b/trunk/Examples/contract/simple_cxx/runme2.py
@@ -0,0 +1,44 @@
+import example 
+
+# Create the Circle object
+
+r = 2;
+print "  Creating circle (radium: %d) :" % r
+c = example.Circle(r)
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+print "  Here is its current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+
+# ----- Call some methods -----
+
+print "\n  Here are some properties of the Circle:"
+print "    area      = ", c.area()
+print "    perimeter = ", c.perimeter()
+dx = 1;
+dy = 1;
+print "    Moving with (%d, %d)..." % (dx, dy)
+c.move(dx, dy)
+
+del c
+
+print "==================================="
+
+# test area function */
+r = 1;
+print "  Creating circle (radium: %d) :" % r 
+c = example.Circle(r)
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+print "  Here is its current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+
+# ----- Call some methods -----
+
+print "\n  Here are some properties of the Circle:"
+print "    area      = ", c.area()
diff --git a/trunk/Examples/contract/simple_cxx/runme3.py b/trunk/Examples/contract/simple_cxx/runme3.py
new file mode 100644
index 0000000..a663732
--- /dev/null
+++ b/trunk/Examples/contract/simple_cxx/runme3.py
@@ -0,0 +1,57 @@
+import example 
+
+# Create the Circle object
+
+r = 2;
+print "  Creating circle (radium: %d) :" % r
+c = example.Circle(r)
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+print "  Here is its current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+
+# ----- Call some methods -----
+
+print "\n  Here are some properties of the Circle:"
+print "    area      = ", c.area()
+print "    perimeter = ", c.perimeter()
+dx = 1;
+dy = 1;
+print "    Moving with (%d, %d)..." % (dx, dy)
+c.move(dx, dy)
+
+del c
+
+print "==================================="
+
+# test move function */
+r = 2;
+print "  Creating circle (radium: %d) :" % r 
+c = example.Circle(r)
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+print "  Here is its current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+
+# ----- Call some methods -----
+
+print "\n  Here are some properties of the Circle:"
+print "    area      = ", c.area()
+print "    perimeter = ", c.perimeter()
+
+# no error for Circle's pre-assertion
+dx = 1;
+dy = -1;
+print "    Moving with (%d, %d)..." % (dx, dy)
+c.move(dx, dy)
+
+# error with Shape's pre-assertion
+dx = -1;
+dy = 1;
+print "    Moving with (%d, %d)..." % (dx, dy)
+c.move(dx, dy)
diff --git a/trunk/Examples/csharp/callback/Makefile b/trunk/Examples/csharp/callback/Makefile
new file mode 100644
index 0000000..51b163b
--- /dev/null
+++ b/trunk/Examples/csharp/callback/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -debug -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/callback/example-cs.csproj b/trunk/Examples/csharp/callback/example-cs.csproj
new file mode 100644
index 0000000..5fc3452
--- /dev/null
+++ b/trunk/Examples/csharp/callback/example-cs.csproj
@@ -0,0 +1,99 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "Callback.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "Caller.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/callback/example-vc.vcproj b/trunk/Examples/csharp/callback/example-vc.vcproj
new file mode 100644
index 0000000..7c0b8ef
--- /dev/null
+++ b/trunk/Examples/csharp/callback/example-vc.vcproj
@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath="example.cxx">
+			</File>
+			<File
+				RelativePath="example_wrap.cxx">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath="example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/callback/example.cxx b/trunk/Examples/csharp/callback/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/csharp/callback/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/csharp/callback/example.h b/trunk/Examples/csharp/callback/example.h
new file mode 100644
index 0000000..38d25a0
--- /dev/null
+++ b/trunk/Examples/csharp/callback/example.h
@@ -0,0 +1,24 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+
+class Callback {
+public:
+	virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; }
+	virtual void run() { std::cout << "Callback::run()" << std::endl; }
+};
+
+
+class Caller {
+private:
+	Callback *_callback;
+public:
+	Caller(): _callback(0) {}
+	~Caller() { delCallback(); }
+	void delCallback() { delete _callback; _callback = 0; }
+	void setCallback(Callback *cb) { delCallback(); _callback = cb; }
+	void resetCallback() { _callback = 0; }
+	void call() { if (_callback) _callback->run(); }
+};
+
diff --git a/trunk/Examples/csharp/callback/example.i b/trunk/Examples/csharp/callback/example.i
new file mode 100644
index 0000000..90beda0
--- /dev/null
+++ b/trunk/Examples/csharp/callback/example.i
@@ -0,0 +1,13 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_string.i"
+
+/* turn on director wrapping Callback */
+%feature("director") Callback;
+
+%include "example.h"
+
diff --git a/trunk/Examples/csharp/callback/example.sln b/trunk/Examples/csharp/callback/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/callback/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/callback/runme.cs b/trunk/Examples/csharp/callback/runme.cs
new file mode 100644
index 0000000..a104b1a
--- /dev/null
+++ b/trunk/Examples/csharp/callback/runme.cs
@@ -0,0 +1,46 @@
+using System;
+
+public class runme
+{
+  static void Main() 
+  {
+    Console.WriteLine("Adding and calling a normal C++ callback");
+    Console.WriteLine("----------------------------------------");
+
+    Caller caller = new Caller();
+    using (Callback callback = new Callback())
+    {
+      caller.setCallback(callback);
+      caller.call();
+      caller.resetCallback();
+    }
+
+    Console.WriteLine();
+    Console.WriteLine("Adding and calling a C# callback");
+    Console.WriteLine("------------------------------------");
+
+    using (Callback callback = new CSharpCallback())
+    {
+      caller.setCallback(callback);
+      caller.call();
+      caller.resetCallback();
+    }
+
+    Console.WriteLine();
+    Console.WriteLine("C# exit");
+  }
+}
+
+public class CSharpCallback : Callback
+{
+  public CSharpCallback()
+    : base()
+  {
+  }
+
+  public override void run()
+  {
+    Console.WriteLine("CSharpCallback.run()");
+  }
+}
+
diff --git a/trunk/Examples/csharp/check.list b/trunk/Examples/csharp/check.list
new file mode 100644
index 0000000..c4d9240
--- /dev/null
+++ b/trunk/Examples/csharp/check.list
@@ -0,0 +1,10 @@
+# see top-level Makefile.in
+callback
+class
+enum
+extend
+funcptr
+reference
+simple
+template
+variables
diff --git a/trunk/Examples/csharp/class/Makefile b/trunk/Examples/csharp/class/Makefile
new file mode 100644
index 0000000..20f0dd5
--- /dev/null
+++ b/trunk/Examples/csharp/class/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/class/example-cs.csproj b/trunk/Examples/csharp/class/example-cs.csproj
new file mode 100644
index 0000000..0b9ea2e
--- /dev/null
+++ b/trunk/Examples/csharp/class/example-cs.csproj
@@ -0,0 +1,104 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "Circle.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "Shape.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "Square.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/class/example-vc.vcproj b/trunk/Examples/csharp/class/example-vc.vcproj
new file mode 100644
index 0000000..7c0b8ef
--- /dev/null
+++ b/trunk/Examples/csharp/class/example-vc.vcproj
@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath="example.cxx">
+			</File>
+			<File
+				RelativePath="example_wrap.cxx">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath="example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/class/example.cxx b/trunk/Examples/csharp/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/csharp/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/csharp/class/example.h b/trunk/Examples/csharp/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/csharp/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/csharp/class/example.i b/trunk/Examples/csharp/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/csharp/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/csharp/class/example.sln b/trunk/Examples/csharp/class/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/class/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/class/runme.cs b/trunk/Examples/csharp/class/runme.cs
new file mode 100644
index 0000000..9088031
--- /dev/null
+++ b/trunk/Examples/csharp/class/runme.cs
@@ -0,0 +1,66 @@
+// This example illustrates how C++ classes can be used from C# using SWIG.
+// The C# class gets mapped onto the C++ class and behaves as if it is a C# class.
+
+using System;
+
+public class runme
+{
+    static void Main() 
+    {
+        // ----- Object creation -----
+
+        Console.WriteLine( "Creating some objects:" );
+
+        using (Square s = new Square(10))
+        using (Circle c = new Circle(10))
+        {
+            Console.WriteLine( "    Created circle " + c );
+            Console.WriteLine( "    Created square " + s );
+
+            // ----- Access a static member -----
+
+            Console.WriteLine( "\nA total of " + Shape.nshapes + " shapes were created" );
+
+            // ----- Member data access -----
+
+            // Notice how we can do this using functions specific to
+            // the 'Circle' class.
+            c.x = 20;
+            c.y = 30;
+
+            // Now use the same functions in the base class
+            Shape shape = s;
+            shape.x = -10;
+            shape.y = 5;
+
+            Console.WriteLine( "\nHere is their current position:" );
+            Console.WriteLine( "    Circle = (" + c.x + " " + c.y + ")" );
+            Console.WriteLine( "    Square = (" + s.x + " " + s.y + ")" );
+
+            // ----- Call some methods -----
+
+            Console.WriteLine( "\nHere are some properties of the shapes:" );
+            Shape[] shapes = {c,s};
+            //            for (int i=0; i<shapes.Size; i++)
+            for (int i=0; i<2; i++)
+            {
+                Console.WriteLine( "   " + shapes[i].ToString() );
+                Console.WriteLine( "        area      = " + shapes[i].area() );
+                Console.WriteLine( "        perimeter = " + shapes[i].perimeter() );
+            }
+
+            // Notice how the area() and perimeter() functions really
+            // invoke the appropriate virtual method on each object.
+
+            // ----- Delete everything -----
+
+            Console.WriteLine( "\nGuess I'll clean up now" );
+
+        }
+        // Note: when this using scope is exited the C# Dispose() methods 
+        // are called which in turn call the C++ destructors
+
+        Console.WriteLine( Shape.nshapes + " shapes remain" );
+        Console.WriteLine( "Goodbye" );
+    }
+}
diff --git a/trunk/Examples/csharp/enum/Makefile b/trunk/Examples/csharp/enum/Makefile
new file mode 100644
index 0000000..20f0dd5
--- /dev/null
+++ b/trunk/Examples/csharp/enum/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/enum/example-cs.csproj b/trunk/Examples/csharp/enum/example-cs.csproj
new file mode 100644
index 0000000..9d37ce2
--- /dev/null
+++ b/trunk/Examples/csharp/enum/example-cs.csproj
@@ -0,0 +1,99 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "color.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "Foo.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/enum/example-vc.vcproj b/trunk/Examples/csharp/enum/example-vc.vcproj
new file mode 100644
index 0000000..7c0b8ef
--- /dev/null
+++ b/trunk/Examples/csharp/enum/example-vc.vcproj
@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath="example.cxx">
+			</File>
+			<File
+				RelativePath="example_wrap.cxx">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath="example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/enum/example.cxx b/trunk/Examples/csharp/enum/example.cxx
new file mode 100644
index 0000000..df7bb63
--- /dev/null
+++ b/trunk/Examples/csharp/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.cxx */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/csharp/enum/example.h b/trunk/Examples/csharp/enum/example.h
new file mode 100644
index 0000000..9119cd9
--- /dev/null
+++ b/trunk/Examples/csharp/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE=10, WARP=20, LUDICROUS=30 };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/csharp/enum/example.i b/trunk/Examples/csharp/enum/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/csharp/enum/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/csharp/enum/example.sln b/trunk/Examples/csharp/enum/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/enum/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/enum/runme.cs b/trunk/Examples/csharp/enum/runme.cs
new file mode 100644
index 0000000..42ba896
--- /dev/null
+++ b/trunk/Examples/csharp/enum/runme.cs
@@ -0,0 +1,31 @@
+using System;
+
+public class runme
+{
+    static void Main() 
+    {
+        // Print out the value of some enums
+        Console.WriteLine("*** color ***");
+        Console.WriteLine("    " + color.RED + " = " + (int)color.RED);
+        Console.WriteLine("    " + color.BLUE + " = " + (int)color.BLUE);
+        Console.WriteLine("    " + color.GREEN + " = " + (int)color.GREEN);
+
+        Console.WriteLine("\n*** Foo::speed ***");
+        Console.WriteLine("    Foo::" + Foo.speed.IMPULSE + " = " + (int)Foo.speed.IMPULSE);
+        Console.WriteLine("    Foo::" + Foo.speed.WARP + " = " + (int)Foo.speed.WARP);
+        Console.WriteLine("    Foo::" + Foo.speed.LUDICROUS + " = " + (int)Foo.speed.LUDICROUS);
+
+        Console.WriteLine("\nTesting use of enums with functions\n");
+
+        example.enum_test(color.RED, Foo.speed.IMPULSE);
+        example.enum_test(color.BLUE, Foo.speed.WARP);
+        example.enum_test(color.GREEN, Foo.speed.LUDICROUS);
+
+        Console.WriteLine( "\nTesting use of enum with class method" );
+        Foo f = new Foo();
+
+        f.enum_test(Foo.speed.IMPULSE);
+        f.enum_test(Foo.speed.WARP);
+        f.enum_test(Foo.speed.LUDICROUS);
+    }
+}
diff --git a/trunk/Examples/csharp/extend/Makefile b/trunk/Examples/csharp/extend/Makefile
new file mode 100644
index 0000000..20f0dd5
--- /dev/null
+++ b/trunk/Examples/csharp/extend/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/extend/example-cs.csproj b/trunk/Examples/csharp/extend/example-cs.csproj
new file mode 100644
index 0000000..4e88746
--- /dev/null
+++ b/trunk/Examples/csharp/extend/example-cs.csproj
@@ -0,0 +1,104 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "Employee.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "EmployeeList.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "Manager.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/extend/example-vc.vcproj b/trunk/Examples/csharp/extend/example-vc.vcproj
new file mode 100644
index 0000000..7c0b8ef
--- /dev/null
+++ b/trunk/Examples/csharp/extend/example-vc.vcproj
@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath="example.cxx">
+			</File>
+			<File
+				RelativePath="example_wrap.cxx">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath="example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/extend/example.cxx b/trunk/Examples/csharp/extend/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/csharp/extend/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/csharp/extend/example.h b/trunk/Examples/csharp/extend/example.h
new file mode 100644
index 0000000..b27ab97
--- /dev/null
+++ b/trunk/Examples/csharp/extend/example.h
@@ -0,0 +1,56 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+#include <vector>
+#include <string>
+#include <cmath>
+
+class Employee {
+private:
+	std::string name;
+public:
+	Employee(const char* n): name(n) {}
+	virtual std::string getTitle() { return getPosition() + " " + getName(); }
+	virtual std::string getName() { return name; }
+	virtual std::string getPosition() const { return "Employee"; }
+	virtual ~Employee() { printf("~Employee() @ %p\n", this); }
+};
+
+
+class Manager: public Employee {
+public:
+	Manager(const char* n): Employee(n) {}
+	virtual std::string getPosition() const { return "Manager"; }
+};
+
+
+class EmployeeList {
+	std::vector<Employee*> list;
+public:
+	EmployeeList() {
+		list.push_back(new Employee("Bob"));
+		list.push_back(new Employee("Jane"));
+		list.push_back(new Manager("Ted"));
+	}
+	void addEmployee(Employee *p) {
+		list.push_back(p);
+		std::cout << "New employee added.   Current employees are:" << std::endl;
+		std::vector<Employee*>::iterator i;
+		for (i=list.begin(); i!=list.end(); i++) {
+			std::cout << "  " << (*i)->getTitle() << std::endl;
+		}
+	}
+	const Employee *get_item(int i) {
+		return list[i];
+	}
+	~EmployeeList() { 
+		std::vector<Employee*>::iterator i;
+		std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl;
+		for (i=list.begin(); i!=list.end(); i++) {
+			delete *i;
+		}
+		std::cout << "~EmployeeList empty." << std::endl;
+	}
+};
+
diff --git a/trunk/Examples/csharp/extend/example.i b/trunk/Examples/csharp/extend/example.i
new file mode 100644
index 0000000..c8ec32e
--- /dev/null
+++ b/trunk/Examples/csharp/extend/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+%include "std_string.i"
+
+/* turn on director wrapping for Manager */
+%feature("director") Employee;
+%feature("director") Manager;
+
+%include "example.h"
+
diff --git a/trunk/Examples/csharp/extend/example.sln b/trunk/Examples/csharp/extend/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/extend/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/extend/runme.cs b/trunk/Examples/csharp/extend/runme.cs
new file mode 100644
index 0000000..825dcdb
--- /dev/null
+++ b/trunk/Examples/csharp/extend/runme.cs
@@ -0,0 +1,77 @@
+// This file illustrates the cross language polymorphism using directors.
+
+using System;
+
+// CEO class, which overrides Employee::getPosition().
+
+class CEO : Manager {
+  public CEO(String name) : base(name) {
+  }
+  public override String getPosition() {
+    return "CEO";
+  }
+  // Public method to stop the SWIG proxy base class from thinking it owns the underlying C++ memory.
+  public void disownMemory() {
+    swigCMemOwn = false; 
+  } 
+}
+
+
+public class runme
+{
+  static void Main() 
+  {
+    // Create an instance of CEO, a class derived from the C# proxy of the 
+    // underlying C++ class. The calls to getName() and getPosition() are standard,
+    // the call to getTitle() uses the director wrappers to call CEO.getPosition().
+
+    CEO e = new CEO("Alice");
+    Console.WriteLine( e.getName() + " is a " + e.getPosition() );
+    Console.WriteLine( "Just call her \"" + e.getTitle() + "\"" );
+    Console.WriteLine( "----------------------" );
+
+    // Create a new EmployeeList instance.  This class does not have a C++
+    // director wrapper, but can be used freely with other classes that do.
+
+    using (EmployeeList list = new EmployeeList()) {
+
+    // EmployeeList owns its items, so we must surrender ownership of objects we add.
+    e.disownMemory();
+    list.addEmployee(e);
+    Console.WriteLine( "----------------------" );
+
+    // Now we access the first four items in list (three are C++ objects that
+    // EmployeeList's constructor adds, the last is our CEO). The virtual
+    // methods of all these instances are treated the same. For items 0, 1, and
+    // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls
+    // getPosition which resolves in C#. The call to getPosition is
+    // slightly different, however, because of the overidden getPosition() call, since
+    // now the object reference has been "laundered" by passing through
+    // EmployeeList as an Employee*. Previously, C# resolved the call
+    // immediately in CEO, but now C# thinks the object is an instance of
+    // class Employee. So the call passes through the
+    // Employee proxy class and on to the C wrappers and C++ director,
+    // eventually ending up back at the C# CEO implementation of getPosition().
+    // The call to getTitle() for item 3 runs the C++ Employee::getTitle()
+    // method, which in turn calls getPosition(). This virtual method call
+    // passes down through the C++ director class to the C# implementation
+    // in CEO. All this routing takes place transparently.
+
+    Console.WriteLine( "(position, title) for items 0-3:" );
+
+    Console.WriteLine( "  " + list.get_item(0).getPosition() + ", \"" + list.get_item(0).getTitle() + "\"" );
+    Console.WriteLine( "  " + list.get_item(1).getPosition() + ", \"" + list.get_item(1).getTitle() + "\"" );
+    Console.WriteLine( "  " + list.get_item(2).getPosition() + ", \"" + list.get_item(2).getTitle() + "\"" );
+    Console.WriteLine( "  " + list.get_item(3).getPosition() + ", \"" + list.get_item(3).getTitle() + "\"" );
+    Console.WriteLine( "----------------------" );
+
+    // The using statement ensures the EmployeeList.Dispose() will be called, which will delete all the Employee*
+    // items it contains. The last item is our CEO, which gets destroyed as well.
+    }
+    Console.WriteLine( "----------------------" );
+
+    // All done.
+
+    Console.WriteLine( "C# exit" );
+  }
+}
diff --git a/trunk/Examples/csharp/funcptr/Makefile b/trunk/Examples/csharp/funcptr/Makefile
new file mode 100644
index 0000000..2233004
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/funcptr/example-cs.csproj b/trunk/Examples/csharp/funcptr/example-cs.csproj
new file mode 100644
index 0000000..5ff0d9d
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/example-cs.csproj
@@ -0,0 +1,94 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "SWIGTYPE_p_f_int_int__int.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/funcptr/example-vc.vcproj b/trunk/Examples/csharp/funcptr/example-vc.vcproj
new file mode 100644
index 0000000..03047bf
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/example-vc.vcproj
@@ -0,0 +1,160 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath=".\example.c">
+			</File>
+			<File
+				RelativePath=".\example_wrap.c">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath=".\example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -csharp &quot;$(InputPath)&quot;
+@echo off
+"
+					Outputs="$(InputName)_wrap.c"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -csharp &quot;$(InputPath)&quot;
+@echo off
+"
+					Outputs="$(InputName)_wrap.c"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/funcptr/example.c b/trunk/Examples/csharp/funcptr/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/csharp/funcptr/example.h b/trunk/Examples/csharp/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/csharp/funcptr/example.i b/trunk/Examples/csharp/funcptr/example.i
new file mode 100644
index 0000000..8b3bef6
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/csharp/funcptr/example.sln b/trunk/Examples/csharp/funcptr/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/funcptr/runme.cs b/trunk/Examples/csharp/funcptr/runme.cs
new file mode 100644
index 0000000..ba2e228
--- /dev/null
+++ b/trunk/Examples/csharp/funcptr/runme.cs
@@ -0,0 +1,27 @@
+
+using System;
+using System.Reflection;
+
+public class runme {
+
+  public static void Main(String[] args) {
+
+
+    int a = 37;
+    int b = 42;
+
+    // Now call our C function with a bunch of callbacks
+
+    Console.WriteLine( "Trying some C callback functions" );
+    Console.WriteLine( "    a        = " + a );
+    Console.WriteLine( "    b        = " + b );
+    Console.WriteLine( "    ADD(a,b) = " + example.do_op(a,b,example.ADD) );
+    Console.WriteLine( "    SUB(a,b) = " + example.do_op(a,b,example.SUB) );
+    Console.WriteLine( "    MUL(a,b) = " + example.do_op(a,b,example.MUL) );
+
+    Console.WriteLine( "Here is what the C callback function classes are called in C#" );
+    Console.WriteLine( "    ADD      = " + example.ADD.GetType() );
+    Console.WriteLine( "    SUB      = " + example.SUB.GetType() );
+    Console.WriteLine( "    MUL      = " + example.MUL.GetType() );
+  }
+}
diff --git a/trunk/Examples/csharp/reference/Makefile b/trunk/Examples/csharp/reference/Makefile
new file mode 100644
index 0000000..20f0dd5
--- /dev/null
+++ b/trunk/Examples/csharp/reference/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/reference/example-cs.csproj b/trunk/Examples/csharp/reference/example-cs.csproj
new file mode 100644
index 0000000..e55912b
--- /dev/null
+++ b/trunk/Examples/csharp/reference/example-cs.csproj
@@ -0,0 +1,99 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "Vector.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "VectorArray.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/reference/example-vc.vcproj b/trunk/Examples/csharp/reference/example-vc.vcproj
new file mode 100644
index 0000000..7c0b8ef
--- /dev/null
+++ b/trunk/Examples/csharp/reference/example-vc.vcproj
@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath="example.cxx">
+			</File>
+			<File
+				RelativePath="example_wrap.cxx">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath="example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/reference/example.cxx b/trunk/Examples/csharp/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/csharp/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/csharp/reference/example.h b/trunk/Examples/csharp/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/csharp/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/csharp/reference/example.i b/trunk/Examples/csharp/reference/example.i
new file mode 100644
index 0000000..6daa3b1
--- /dev/null
+++ b/trunk/Examples/csharp/reference/example.i
@@ -0,0 +1,46 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/csharp/reference/example.sln b/trunk/Examples/csharp/reference/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/reference/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/reference/runme.cs b/trunk/Examples/csharp/reference/runme.cs
new file mode 100644
index 0000000..499ddea
--- /dev/null
+++ b/trunk/Examples/csharp/reference/runme.cs
@@ -0,0 +1,73 @@
+// This example illustrates the manipulation of C++ references in C#.
+
+using System;
+
+public class runme {
+
+  public static void Main() 
+  {
+    Console.WriteLine( "Creating some objects:" );
+    Vector a = new Vector(3,4,5);
+    Vector b = new Vector(10,11,12);
+    
+    Console.WriteLine( "    Created " + a.print() );
+    Console.WriteLine( "    Created " + b.print() );
+    
+    // ----- Call an overloaded operator -----
+    
+    // This calls the wrapper we placed around
+    //
+    //      operator+(const Vector &a, const Vector &) 
+    //
+    // It returns a new allocated object.
+    
+    Console.WriteLine( "Adding a+b" );
+    Vector c = example.addv(a,b);
+    Console.WriteLine( "    a+b = " + c.print() );
+    
+    // Note: Unless we free the result, a memory leak will occur if the -noproxy commandline
+    // is used as the proxy classes define finalizers which call the Dispose() method. When
+    // -noproxy is not specified the memory management is controlled by the garbage collector.
+    // You can still call Dispose(). It will free the c++ memory immediately, but not the 
+    // C# memory! You then must be careful not to call any member functions as it will 
+    // use a NULL c pointer on the underlying c++ object. We set the C# object to null
+    // which will then throw a C# exception should we attempt to use it again.
+    c.Dispose();
+    c = null;
+    
+    // ----- Create a vector array -----
+    
+    Console.WriteLine( "Creating an array of vectors" );
+    VectorArray va = new VectorArray(10);
+    Console.WriteLine( "    va = " + va.ToString() );
+    
+    // ----- Set some values in the array -----
+    
+    // These operators copy the value of Vector a and Vector b to the vector array
+    va.set(0,a);
+    va.set(1,b);
+    
+    // This works, but it would cause a memory leak if -noproxy was used!
+    
+    va.set(2,example.addv(a,b));
+    
+
+    // Get some values from the array
+    
+    Console.WriteLine( "Getting some array values" );
+    for (int i=0; i<5; i++)
+        Console.WriteLine( "    va(" + i + ") = " + va.get(i).print() );
+    
+    // Watch under resource meter to check on this
+    Console.WriteLine( "Making sure we don't leak memory." );
+    for (int i=0; i<1000000; i++)
+        c = va.get(i%10);
+    
+    // ----- Clean up -----
+    // This could be omitted. The garbage collector would then clean up for us.
+    Console.WriteLine( "Cleaning up" );
+    va.Dispose();
+    a.Dispose();
+    b.Dispose();
+  }
+}
diff --git a/trunk/Examples/csharp/simple/Makefile b/trunk/Examples/csharp/simple/Makefile
new file mode 100644
index 0000000..2233004
--- /dev/null
+++ b/trunk/Examples/csharp/simple/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/simple/example-cs.csproj b/trunk/Examples/csharp/simple/example-cs.csproj
new file mode 100644
index 0000000..d801057
--- /dev/null
+++ b/trunk/Examples/csharp/simple/example-cs.csproj
@@ -0,0 +1,89 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/simple/example-vc.vcproj b/trunk/Examples/csharp/simple/example-vc.vcproj
new file mode 100644
index 0000000..14f5004
--- /dev/null
+++ b/trunk/Examples/csharp/simple/example-vc.vcproj
@@ -0,0 +1,222 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8.00"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\example.c"
+				>
+			</File>
+			<File
+				RelativePath=".\example_wrap.c"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+		</Filter>
+		<File
+			RelativePath=".\example.i"
+			>
+			<FileConfiguration
+				Name="Debug|Win32"
+				>
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...&#x0D;&#x0A;echo on&#x0D;&#x0A;..\..\..\swig.exe -csharp &quot;$(InputPath)&quot;&#x0D;&#x0A;@echo off&#x0D;&#x0A;"
+					Outputs="$(InputName)_wrap.c"
+				/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32"
+				>
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...&#x0D;&#x0A;echo on&#x0D;&#x0A;..\..\..\swig.exe -csharp &quot;$(InputPath)&quot;&#x0D;&#x0A;@echo off&#x0D;&#x0A;"
+					Outputs="$(InputName)_wrap.c"
+				/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/simple/example.c b/trunk/Examples/csharp/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/csharp/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/csharp/simple/example.i b/trunk/Examples/csharp/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/csharp/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/csharp/simple/example.sln b/trunk/Examples/csharp/simple/example.sln
new file mode 100644
index 0000000..9967f7e
--- /dev/null
+++ b/trunk/Examples/csharp/simple/example.sln
@@ -0,0 +1,26 @@
+Microsoft Visual Studio Solution File, Format Version 9.00
+# Visual C++ Express 2005
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Release|Win32 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug|Win32.ActiveCfg = Debug|Any CPU
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release|Win32.ActiveCfg = Release|Any CPU
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug|Win32.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release|Win32.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/simple/runme.cs b/trunk/Examples/csharp/simple/runme.cs
new file mode 100644
index 0000000..26106c6
--- /dev/null
+++ b/trunk/Examples/csharp/simple/runme.cs
@@ -0,0 +1,25 @@
+using System;
+
+public class runme
+{
+    static void Main() 
+    {
+        // Call our gcd() function
+
+        int x = 42;
+        int y = 105;
+        int g = example.gcd(x,y);
+        Console.WriteLine("The gcd of " + x + " and " + y + " is " + g);
+
+        // Manipulate the Foo global variable
+
+        // Output its current value
+        Console.WriteLine("Foo = " + example.Foo);
+
+        // Change its value
+        example.Foo = 3.1415926;
+
+        // See if the change took effect
+        Console.WriteLine("Foo = " + example.Foo);
+    }
+}
diff --git a/trunk/Examples/csharp/template/Makefile b/trunk/Examples/csharp/template/Makefile
new file mode 100644
index 0000000..3f3bbe6
--- /dev/null
+++ b/trunk/Examples/csharp/template/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    =
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/template/example-cs.csproj b/trunk/Examples/csharp/template/example-cs.csproj
new file mode 100644
index 0000000..b51122b
--- /dev/null
+++ b/trunk/Examples/csharp/template/example-cs.csproj
@@ -0,0 +1,109 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "SWIGTYPE_p_double.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "SWIGTYPE_p_int.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "vecdouble.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "vecint.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/template/example-vc.vcproj b/trunk/Examples/csharp/template/example-vc.vcproj
new file mode 100644
index 0000000..867e694
--- /dev/null
+++ b/trunk/Examples/csharp/template/example-vc.vcproj
@@ -0,0 +1,157 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath="example_wrap.cxx">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+			<File
+				RelativePath="example.h">
+			</File>
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off
+"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -c++ -csharp &quot;$(InputPath)&quot;
+@echo off
+"
+					Outputs="$(InputName)_wrap.cxx"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/template/example.h b/trunk/Examples/csharp/template/example.h
new file mode 100644
index 0000000..7401df6
--- /dev/null
+++ b/trunk/Examples/csharp/template/example.h
@@ -0,0 +1,32 @@
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %extend {
+    T getitem(int index) {
+      return $self->get(index);
+    }
+    void setitem(int index, T val) {
+      $self->set(index,val);
+    }
+  }
+#endif
+};
+
diff --git a/trunk/Examples/csharp/template/example.i b/trunk/Examples/csharp/template/example.i
new file mode 100644
index 0000000..8f94c4d
--- /dev/null
+++ b/trunk/Examples/csharp/template/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
diff --git a/trunk/Examples/csharp/template/example.sln b/trunk/Examples/csharp/template/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/template/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/template/runme.cs b/trunk/Examples/csharp/template/runme.cs
new file mode 100644
index 0000000..b2a8e6a
--- /dev/null
+++ b/trunk/Examples/csharp/template/runme.cs
@@ -0,0 +1,39 @@
+// This example illustrates how C++ templates can be used from C#.
+
+using System;
+
+public class runme {
+
+  public static void Main() 
+  {
+    // Call some templated functions
+    Console.WriteLine(example.maxint(3,7));
+    Console.WriteLine(example.maxdouble(3.14,2.18));
+    
+    // Create some class
+    
+    vecint iv = new vecint(100);
+    vecdouble dv = new vecdouble(1000);
+    
+    for (int i=0; i<100; i++)
+        iv.setitem(i,2*i);
+    
+    for (int i=0; i<1000; i++)
+          dv.setitem(i, 1.0/(i+1));
+    
+    {
+        int sum = 0;
+        for (int i=0; i<100; i++)
+            sum = sum + iv.getitem(i);
+
+        Console.WriteLine(sum);
+    }
+    
+    {
+        double sum = 0.0;
+        for (int i=0; i<1000; i++)
+            sum = sum + dv.getitem(i);
+        Console.WriteLine(sum);
+    }
+  }
+}
diff --git a/trunk/Examples/csharp/variables/Makefile b/trunk/Examples/csharp/variables/Makefile
new file mode 100644
index 0000000..2233004
--- /dev/null
+++ b/trunk/Examples/csharp/variables/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+CSHARPSRCS = *.cs
+CSHARPFLAGS= -nologo -out:runme.exe
+
+all::	csharp
+
+csharp::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp
+	$(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile csharp_clean
+
+check: all
diff --git a/trunk/Examples/csharp/variables/example-cs.csproj b/trunk/Examples/csharp/variables/example-cs.csproj
new file mode 100644
index 0000000..f0e0159
--- /dev/null
+++ b/trunk/Examples/csharp/variables/example-cs.csproj
@@ -0,0 +1,99 @@
+<VisualStudioProject>
+    <CSHARP
+        ProjectType = "Local"
+        ProductVersion = "7.10.3077"
+        SchemaVersion = "2.0"
+        ProjectGuid = "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+    >
+        <Build>
+            <Settings
+                ApplicationIcon = ""
+                AssemblyKeyContainerName = ""
+                AssemblyName = "runme"
+                AssemblyOriginatorKeyFile = ""
+                DefaultClientScript = "JScript"
+                DefaultHTMLPageLayout = "Grid"
+                DefaultTargetSchema = "IE50"
+                DelaySign = "false"
+                OutputType = "Exe"
+                PreBuildEvent = ""
+                PostBuildEvent = ""
+                RootNamespace = "runme"
+                RunPostBuildEvent = "OnBuildSuccess"
+                StartupObject = ""
+            >
+                <Config
+                    Name = "Debug"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "DEBUG;TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "true"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "false"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+                <Config
+                    Name = "Release"
+                    AllowUnsafeBlocks = "false"
+                    BaseAddress = "285212672"
+                    CheckForOverflowUnderflow = "false"
+                    ConfigurationOverrideFile = ""
+                    DefineConstants = "TRACE"
+                    DocumentationFile = ""
+                    DebugSymbols = "false"
+                    FileAlignment = "4096"
+                    IncrementalBuild = "false"
+                    NoStdLib = "false"
+                    NoWarn = ""
+                    Optimize = "true"
+                    OutputPath = ".\"
+                    RegisterForComInterop = "false"
+                    RemoveIntegerChecks = "false"
+                    TreatWarningsAsErrors = "false"
+                    WarningLevel = "4"
+                />
+            </Settings>
+            <References/>
+        </Build>
+        <Files>
+            <Include>
+                <File
+                    RelPath = "example.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "examplePINVOKE.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "runme.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "SWIGTYPE_p_int.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+                <File
+                    RelPath = "SWIGTYPE_p_Point.cs"
+                    SubType = "Code"
+                    BuildAction = "Compile"
+                />
+            </Include>
+        </Files>
+    </CSHARP>
+</VisualStudioProject>
+
diff --git a/trunk/Examples/csharp/variables/example-vc.vcproj b/trunk/Examples/csharp/variables/example-vc.vcproj
new file mode 100644
index 0000000..be0dfc7
--- /dev/null
+++ b/trunk/Examples/csharp/variables/example-vc.vcproj
@@ -0,0 +1,157 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="example-vc"
+	ProjectGUID="{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/example-vc.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;EXAMPLEVC_EXPORTS"
+				RuntimeLibrary="0"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				OutputFile="example.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/example-vc.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
+			<File
+				RelativePath=".\example.c">
+			</File>
+			<File
+				RelativePath=".\example_wrap.c">
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
+		</Filter>
+		<File
+			RelativePath=".\example.i">
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -csharp &quot;$(InputPath)&quot;
+@echo off
+"
+					Outputs="$(InputName)_wrap.c"/>
+			</FileConfiguration>
+			<FileConfiguration
+				Name="Release|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					CommandLine="echo Invoking SWIG...
+echo on
+..\..\..\swig.exe -csharp &quot;$(InputPath)&quot;
+@echo off
+"
+					Outputs="$(InputName)_wrap.c"/>
+			</FileConfiguration>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
diff --git a/trunk/Examples/csharp/variables/example.c b/trunk/Examples/csharp/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/csharp/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/csharp/variables/example.h b/trunk/Examples/csharp/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/csharp/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/csharp/variables/example.i b/trunk/Examples/csharp/variables/example.i
new file mode 100644
index 0000000..591b871
--- /dev/null
+++ b/trunk/Examples/csharp/variables/example.i
@@ -0,0 +1,49 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/csharp/variables/example.sln b/trunk/Examples/csharp/variables/example.sln
new file mode 100644
index 0000000..28b9851
--- /dev/null
+++ b/trunk/Examples/csharp/variables/example.sln
@@ -0,0 +1,30 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "example-cs", "example-cs.csproj", "{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{C2302635-D489-4678-96B4-70F5309DCBE6} = {C2302635-D489-4678-96B4-70F5309DCBE6}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example-vc", "example-vc.vcproj", "{C2302635-D489-4678-96B4-70F5309DCBE6}"
+	ProjectSection(ProjectDependencies) = postProject
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfiguration) = preSolution
+		Debug = Debug
+		Release = Release
+	EndGlobalSection
+	GlobalSection(ProjectConfiguration) = postSolution
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.ActiveCfg = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Debug.Build.0 = Debug|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.ActiveCfg = Release|.NET
+		{C17D27DF-4C57-4625-AEE0-A40C4F48FF1A}.Release.Build.0 = Release|.NET
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.ActiveCfg = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Debug.Build.0 = Debug|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.ActiveCfg = Release|Win32
+		{C2302635-D489-4678-96B4-70F5309DCBE6}.Release.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+	EndGlobalSection
+	GlobalSection(ExtensibilityAddIns) = postSolution
+	EndGlobalSection
+EndGlobal
diff --git a/trunk/Examples/csharp/variables/runme.cs b/trunk/Examples/csharp/variables/runme.cs
new file mode 100644
index 0000000..3d19b6a
--- /dev/null
+++ b/trunk/Examples/csharp/variables/runme.cs
@@ -0,0 +1,82 @@
+// This example illustrates global variable access from C#.
+
+using System;
+using System.Reflection;
+
+public class runme {
+
+  public static void Main() {
+
+    // Try to set the values of some global variables
+
+    example.ivar   =  42;
+    example.svar   = -31000;
+    example.lvar   =  65537;
+    example.uivar  =  123456;
+    example.usvar  =  61000;
+    example.ulvar  =  654321;
+    example.scvar  =  -13;
+    example.ucvar  =  251;
+    example.cvar   =  'S';
+    example.fvar   =  (float)3.14159;
+    example.dvar   =  2.1828;
+    example.strvar =  "Hello World";
+    example.iptrvar= example.new_int(37);
+    example.ptptr  = example.new_Point(37,42);
+    example.name   = "Bill";
+
+    // Now print out the values of the variables
+
+    Console.WriteLine( "Variables (values printed from C#)" );
+
+    Console.WriteLine( "ivar      =" + example.ivar );
+    Console.WriteLine( "svar      =" + example.svar );
+    Console.WriteLine( "lvar      =" + example.lvar );
+    Console.WriteLine( "uivar     =" + example.uivar );
+    Console.WriteLine( "usvar     =" + example.usvar );
+    Console.WriteLine( "ulvar     =" + example.ulvar );
+    Console.WriteLine( "scvar     =" + example.scvar );
+    Console.WriteLine( "ucvar     =" + example.ucvar );
+    Console.WriteLine( "fvar      =" + example.fvar );
+    Console.WriteLine( "dvar      =" + example.dvar );
+    Console.WriteLine( "cvar      =" + example.cvar );
+    Console.WriteLine( "strvar    =" + example.strvar );
+    Console.WriteLine( "cstrvar   =" + example.cstrvar );
+    Console.WriteLine( "iptrvar   =" + example.iptrvar );
+    Console.WriteLine( "name      =" + example.name );
+    Console.WriteLine( "ptptr     =" + example.ptptr + example.Point_print(example.ptptr) );
+    Console.WriteLine( "pt        =" + example.pt + example.Point_print(example.pt) );
+
+    Console.WriteLine( "\nVariables (values printed from C)" );
+
+    example.print_vars();
+
+    Console.WriteLine( "\nNow I'm going to try and modify some read only variables" );
+    Console.WriteLine( "\nChecking that the read only variables are readonly..." );
+
+    example ex = new example();
+    Type t = ex.GetType();
+
+    Console.WriteLine( "     'path'" );
+    PropertyInfo pi = t.GetProperty("path");
+    if (pi.CanWrite)
+      Console.WriteLine("Oh dear this variable is not read only\n");
+    else
+      Console.WriteLine("Good.");
+
+    Console.WriteLine( "     'status'" );
+    pi = t.GetProperty("status");
+    if (pi.CanWrite)
+      Console.WriteLine("Oh dear this variable is not read only");
+    else
+      Console.WriteLine("Good.");
+
+    Console.WriteLine( "\nI'm going to try and update a structure variable.\n" );
+
+    example.pt = example.ptptr;
+
+    Console.WriteLine( "The new value is" );
+    example.pt_print();
+    Console.WriteLine( "You should see the value" + example.Point_print(example.ptptr) );
+  }
+}
diff --git a/trunk/Examples/guile/Makefile.in b/trunk/Examples/guile/Makefile.in
new file mode 100644
index 0000000..a110955
--- /dev/null
+++ b/trunk/Examples/guile/Makefile.in
@@ -0,0 +1,40 @@
+# Makefile for Guile.  Used by all of the example programs.
+
+subdirs		= simple matrix port constants multimap multivalue
+
+top_srcdir	= @top_srcdir@
+SWIG		= ../$(top_srcdir)/preinst-swig
+CC		= @CC@
+CXX		= @CXX@
+CFLAGS		= @PLATFLAGS@
+GUILEINCLUDE	= @GUILEINCLUDE@
+GUILELINK	= @GUILELINK@
+SWIGOPT		=
+
+WRAP		= $(IFILE:.i=_wrap.c)
+CXXWRAP		= $(IFILE:.i=_wrap.cxx)
+
+SO		= @SO@
+
+all:
+	for d in $(subdirs) ; do (cd $$d ; $(MAKE)) ; done
+
+clean::
+	for d in $(subdirs) ; do (cd $$d ; $(MAKE) clean) ; done
+	rm -f *~ .~*
+
+guile_clean:
+	rm -f *.@OBJEXT@ *$(SO) *_wrap* *~ .~* core my-guile $(TARGET)
+
+# This is meant to be used w/ "make -f ../Makefile" from subdirs.
+# Doesn't make sense to use it from here.
+
+sub-all::
+	$(SWIG) -guile $(SWIGOPT) $(IFILE)
+	$(CC) $(CFLAGS) -o $(TARGET) $(SRCS) $(WRAP) $(GUILEINCLUDE) $(GUILELINK)
+
+sub-all-cxx::
+	$(SWIG) -c++ -guile $(SWIGOPT) $(IFILE)
+	$(CXX) $(CFLAGS) -o $(TARGET) $(SRCS) $(CXXWRAP) $(GUILEINCLUDE) $(GUILELINK)
+
+# Makefile ends here
diff --git a/trunk/Examples/guile/README b/trunk/Examples/guile/README
new file mode 100644
index 0000000..acec777
--- /dev/null
+++ b/trunk/Examples/guile/README
@@ -0,0 +1,17 @@
+This directory contains examples for Guile.
+
+constants   -- handling #define and %constant literals
+matrix      -- a very simple Matrix example
+multimap    -- typemaps with multiple sub-types
+multivalue  -- using the %values_as_list directive
+port        -- scheme ports as temporary FILE streams
+simple      -- the simple example from the user manual
+std_vector  -- C++ STL vector<int> and vector<double>
+
+
+Note that the examples in this directory build a special version of
+Guile which includes the wrapped functions in the top-level module.
+
+If you want to put the wrapped functions into an own module,
+statically or dynamically linked, see the Examples/GIFPlot/Guile
+directory.
diff --git a/trunk/Examples/guile/check.list b/trunk/Examples/guile/check.list
new file mode 100644
index 0000000..d35b2d6
--- /dev/null
+++ b/trunk/Examples/guile/check.list
@@ -0,0 +1,7 @@
+# see top-level Makefile.in
+constants
+matrix
+simple
+port
+multimap
+multivalue
diff --git a/trunk/Examples/guile/constants/Makefile b/trunk/Examples/guile/constants/Makefile
new file mode 100644
index 0000000..70243c7
--- /dev/null
+++ b/trunk/Examples/guile/constants/Makefile
@@ -0,0 +1,17 @@
+SRCS   = 
+TARGET = my-guile
+IFILE  = example.i
+MKDIR  = ..
+
+all::
+	$(MAKE) -f $(MKDIR)/Makefile		\
+		SRCS='$(SRCS)'			\
+		TARGET=$(TARGET)		\
+		IFILE=$(IFILE)			\
+	    sub-all
+
+clean::
+	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: all
+	./my-guile -s constants.scm
diff --git a/trunk/Examples/guile/constants/constants.scm b/trunk/Examples/guile/constants/constants.scm
new file mode 100644
index 0000000..5220150
--- /dev/null
+++ b/trunk/Examples/guile/constants/constants.scm
@@ -0,0 +1,10 @@
+(or (= (ICONST) 42) (exit 1))
+(or (< (abs (- (FCONST) 2.1828)) 0.00001) (exit 1))
+(or (char=? (CCONST) #\x) (exit 1))
+(or (char=? (CCONST2) #\newline) (exit 1))
+(or (string=? (SCONST) "Hello World") (exit 1))
+(or (string=? (SCONST2) "\"Hello World\"") (exit 1))
+(or (< (abs (- (EXPR) (+ (ICONST) (* 3 (FCONST))))) 0.00001) (exit 1))
+(or (= (iconst) 37) (exit 1))
+(or (< (abs (- (fconst) 3.14)) 0.00001) (exit 1))
+(exit 0)
diff --git a/trunk/Examples/guile/constants/example.i b/trunk/Examples/guile/constants/example.i
new file mode 100644
index 0000000..0b602e5
--- /dev/null
+++ b/trunk/Examples/guile/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+%include guilemain.i
diff --git a/trunk/Examples/guile/matrix/Makefile b/trunk/Examples/guile/matrix/Makefile
new file mode 100644
index 0000000..5df2c65
--- /dev/null
+++ b/trunk/Examples/guile/matrix/Makefile
@@ -0,0 +1,18 @@
+SRCS   = matrix.c vector.c
+TARGET = matrix
+IFILE  = package.i
+MKDIR  = ..
+
+
+all::
+	$(MAKE) -f $(MKDIR)/Makefile		\
+		SRCS='$(SRCS)'			\
+		TARGET=$(TARGET)		\
+		IFILE=$(IFILE)			\
+		MODULE=$(MODULE)		\
+	  sub-all
+
+clean::
+	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: all
diff --git a/trunk/Examples/guile/matrix/README b/trunk/Examples/guile/matrix/README
new file mode 100644
index 0000000..dc19577
--- /dev/null
+++ b/trunk/Examples/guile/matrix/README
@@ -0,0 +1,13 @@
+Matrix example.  To run the example, execute the program 'matrix' and
+type the following :
+
+	(load "matrix.scm")
+	(do-test 0)
+
+Alternatively, use the command-line:
+
+	./matrix -e do-test -s matrix.scm
+
+Or, if your operating system is spiffy enough:
+
+	./matrix.scm
diff --git a/trunk/Examples/guile/matrix/main.c b/trunk/Examples/guile/matrix/main.c
new file mode 100644
index 0000000..88209ae
--- /dev/null
+++ b/trunk/Examples/guile/matrix/main.c
@@ -0,0 +1,24 @@
+#include <tcl.h>
+extern int matrix_init(Tcl_Interp *);    /* Init function from matrix.i */
+
+int main() {
+
+  int        code;
+  char       input[1024];
+  Tcl_Interp *interp;
+  
+  interp = Tcl_CreateInterp();
+
+  /* Initialize the wrappers */
+
+  if (matrix_init(interp) == TCL_ERROR)
+    exit(0);
+  
+  fprintf(stdout,"matrix > ");
+  while(fgets(input, 1024, stdin) != NULL) {
+    code = Tcl_Eval(interp, input);
+    fprintf(stdout,"%s\n",interp->result);
+    fprintf(stdout,"matrix > ");
+  }
+}
+
diff --git a/trunk/Examples/guile/matrix/matrix.c b/trunk/Examples/guile/matrix/matrix.c
new file mode 100644
index 0000000..6ce1009
--- /dev/null
+++ b/trunk/Examples/guile/matrix/matrix.c
@@ -0,0 +1,61 @@
+/*   FILE : matrix.c : some simple 4x4 matrix operations */
+#include <stdlib.h>
+#include <stdio.h>
+
+double **new_matrix() {
+
+  int i;
+  double **M;
+
+  M = (double **) malloc(4*sizeof(double *));
+  M[0] = (double *) malloc(16*sizeof(double));
+  
+  for (i = 0; i < 4; i++) {
+    M[i] = M[0] + 4*i;
+  }
+  return M;
+}
+
+void destroy_matrix(double **M) {
+
+  free(M[0]);
+  free(M);
+
+}
+
+void print_matrix(double **M) {
+
+  int i,j;
+
+  for (i = 0; i < 4; i++) {
+    for (j = 0; j < 4; j++) {
+      printf("%10g ", M[i][j]);
+    }
+    printf("\n");
+  }
+
+}
+
+void mat_mult(double **m1, double **m2, double **m3) {
+
+  int i,j,k;
+  double temp[4][4];
+
+  for (i = 0; i < 4; i++) 
+    for (j = 0; j < 4; j++) {
+      temp[i][j] = 0;
+      for (k = 0; k < 4; k++) 
+	temp[i][j] += m1[i][k]*m2[k][j];
+    }
+
+  for (i = 0; i < 4; i++)
+    for (j = 0; j < 4; j++)
+      m3[i][j] = temp[i][j];
+}
+
+
+
+
+
+
+
diff --git a/trunk/Examples/guile/matrix/matrix.i b/trunk/Examples/guile/matrix/matrix.i
new file mode 100644
index 0000000..d61f0dc
--- /dev/null
+++ b/trunk/Examples/guile/matrix/matrix.i
@@ -0,0 +1,36 @@
+//
+// FILE : matrix.i
+
+%{
+
+void set_m(double **M, int i, int j, double val) {
+  M[i][j] = val;
+}
+
+double get_m(double **M, int i, int j) {
+  return M[i][j];
+}
+%}
+
+%inline {
+/*** Matrix Operations ***/
+
+extern double **new_matrix();
+/* Creates a new matrix and returns a pointer to it */
+
+extern void   destroy_matrix(double **M);
+/* Destroys the matrix M */
+
+extern void print_matrix(double **M);
+/* Prints out the matrix M */
+
+extern void   set_m(double **M, int i, int j, double val);
+/* Sets M[i][j] = val*/
+
+extern double get_m(double **M, int i, int j);
+/* Returns M[i][j] */
+
+extern void   mat_mult(double **a, double **b, double **c);
+/* Multiplies matrix a by b and places the result in c*/
+
+}
diff --git a/trunk/Examples/guile/matrix/matrix.scm b/trunk/Examples/guile/matrix/matrix.scm
new file mode 100755
index 0000000..18e5284
--- /dev/null
+++ b/trunk/Examples/guile/matrix/matrix.scm
@@ -0,0 +1,210 @@
+#!./matrix \
+-e do-test -s
+!#
+;;; Authors: David Beazley <beazley@cs.uchicago.edu>, 1999
+;;;          Martin Froehlich <MartinFroehlich@ACM.org>, 2000
+;;;
+;;; PURPOSE OF THIS FILE: This file is an example for how to use the guile
+;;;   scripting options with a little more than trivial script. Example
+;;;   derived from David Beazley's matrix evaluation example.  David
+;;;   Beazley's annotation: >>Guile script for testing out matrix
+;;;   operations. Disclaimer : I'm not a very good scheme
+;;;   programmer<<. Martin Froehlich's annotation: >>I'm not a very good
+;;;   scheme programmer, too<<.
+;;;
+;;; Explanation: The three lines at the beginning of this script are
+;;; telling the kernel to load the enhanced guile interpreter named
+;;; "matrix"; to execute the function "do-test" (-e option) after loading
+;;; this script (-s option). There are a lot more options wich allow for
+;;; even finer tuning. SEE ALSO: Section "Guile Scripts" in the "Guile
+;;; reference manual -- Part I: Preliminaries".
+;;;
+;;;
+;;; This program is distributed in the hope that it will be useful, but
+;;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+;;; Create a zero matrix
+
+(define (zero M)
+  (define (zero-loop M i j)
+    (if (< i 4)
+	(if (< j 4) (begin
+		      (set-m M i j 0.0)
+		      (zero-loop M i (+ j 1)))
+	    (zero-loop M (+ i 1) 0))))
+  (zero-loop M 0 0))
+
+;;; Create an identity matrix
+
+(define (identity M)
+  (define (iloop M i)
+    (if (< i 4) (begin
+		  (set-m M i i 1.0)
+		  (iloop M (+ i 1)))))
+  (zero M)
+  (iloop M 0))
+
+;;; Rotate around x axis
+
+(define (rotx M r)
+  (define temp (new-matrix))
+  (define rd (/ (* r 3.14159) 180.0))
+  (zero temp)
+  (set-m temp 0 0 1.0)
+  (set-m temp 1 1 (cos rd))
+  (set-m temp 1 2 (- 0 (sin rd)))
+  (set-m temp 2 1 (sin rd))
+  (set-m temp 2 2 (cos rd))
+  (set-m temp 3 3 1.0)
+  (mat-mult M temp M)
+  (destroy-matrix temp))
+
+;;; Rotate around y axis
+
+(define (roty M r)
+  (define temp (new-matrix))
+  (define rd (/ (* r 3.14159) 180.0))
+  (zero temp)
+  (set-m temp 1 1 1.0)
+  (set-m temp 0 0 (cos rd))
+  (set-m temp 0 2 (sin rd))
+  (set-m temp 2 0 (- 0 (sin rd)))
+  (set-m temp 2 2 (cos rd))
+  (set-m temp 3 3 1.0)
+  (mat-mult M temp M)
+  (destroy-matrix temp))
+
+;;; Rotate around z axis
+
+(define (rotz M r)
+  (define temp (new-matrix))
+  (define rd (/ (* r 3.14159) 180.0))
+  (zero temp)
+  (set-m temp 0 0 (cos rd))
+  (set-m temp 0 1 (- 0 (sin rd)))
+  (set-m temp 1 0 (sin rd))
+  (set-m temp 1 1 (cos rd))
+  (set-m temp 2 2 1.0)
+  (set-m temp 3 3 1.0)
+  (mat-mult M temp M)
+  (destroy-matrix temp))
+
+;;; Scale a matrix
+
+(define (scale M s)
+  (define temp (new-matrix))
+  (define (sloop m i s)
+    (if (< i 4) (begin
+		  (set-m m i i s)
+		  (sloop m (+ i 1) s))))
+  (zero temp)
+  (sloop temp 0 s)
+  (mat-mult M temp M)
+  (destroy-matrix temp))
+
+;;; Make a matrix with random elements
+
+(define (randmat M)
+  (define (rand-loop M i j)
+    (if (< i 4)
+	(if (< j 4)
+            (begin
+              (set-m M i j (drand48))
+              (rand-loop M i (+ j 1)))
+	    (rand-loop M (+ i 1) 0))))
+  (rand-loop M 0 0))
+
+;;; stray definitions collected here
+
+(define (rot-test M v t i)
+  (if (< i 360) (begin
+		  (rotx M 1)
+		  (rotz M -0.5)
+		  (transform M v t)
+		  (rot-test M v t (+ i 1)))))
+
+(define (create-matrix)		; Create some matrices
+  (let loop ((i 0) (result '()))
+    (if (< i 200)
+	(loop (+ i 1) (cons (new-matrix) result))
+	result)))
+
+(define (add-mat M ML)
+  (define (add-two m1 m2 i j)
+    (if (< i 4)
+	(if (< j 4)
+            (begin
+              (set-m m1 i j (+ (get-m m1 i j) (get-m m2 i j)))
+              (add-two m1 m2 i (+ j 1)))
+	    (add-two m1 m2 (+ i 1) 0))))
+  (if (null? ML) () (begin
+		      (add-two M (car ML) 0 0)
+		      (add-mat M (cdr ML)))))
+
+(define (cleanup ML)
+  (if (null? ML) () (begin
+		      (destroy-matrix (car ML))
+		      (cleanup (cdr ML)))))
+
+(define (make-random ML)		; Put random values in them
+  (if (null? ML) () (begin
+		      (randmat (car ML))
+		      (make-random (cdr ML)))))
+
+(define (mul-mat m ML)
+  (if (null? ML) () (begin
+		      (mat-mult m (car ML) m)
+		      (mul-mat m (cdr ML)))))
+
+;;; Now we'll hammer on things a little bit just to make
+;;; sure everything works.
+(define M1 (new-matrix))		; a matrix
+(define v (createv 1 2 3 4))		; a vector
+(define t (createv 0 0 0 0))		; the zero-vector
+(define M-list (create-matrix))		; get list of marices
+(define M (new-matrix))			; yet another matrix
+
+(display "variables defined\n")
+(define (do-test x)
+  (display "Testing matrix program...\n")
+
+  (identity M1)
+  (print-matrix M1)
+  (display "Rotate-x 45 degrees\n")
+  (rotx M1 45)
+  (print-matrix M1)
+  (display "Rotate y 30 degrees\n")
+  (roty M1 30)
+  (print-matrix M1)
+  (display "Rotate z 15 degrees\n")
+  (rotz M1 15)
+  (print-matrix M1)
+  (display "Scale 0.5\n")
+  (scale M1 0.5)
+  (print-matrix M1)
+
+  ;; Rotating ...
+  (display "Rotating...\n")
+  (rot-test M1 v t 0)
+  (printv t)
+
+  (make-random M-list)
+
+  (zero M1)
+
+  (display "Adding them together (in Guile)\n")
+
+  (add-mat M1 M-list)
+  (print-matrix M1)
+
+  (display "Doing 200 multiplications (mostly in C)\n")
+  (randmat M)
+
+  (mul-mat M M-list)
+
+  (display "Cleaning up\n")
+
+  (cleanup M-list))
+
+;;; matrix.scm ends here
diff --git a/trunk/Examples/guile/matrix/package.i b/trunk/Examples/guile/matrix/package.i
new file mode 100644
index 0000000..aaa5551
--- /dev/null
+++ b/trunk/Examples/guile/matrix/package.i
@@ -0,0 +1,20 @@
+// FILE : package.i
+// See the SWIG users manual
+
+/*** Matrix and vector package ***/
+
+%module Matrix
+%{
+#include <math.h>
+%}
+
+%include guilemain.i
+%include matrix.i
+%include vector.i
+
+// Include the math library so we can get some random numbers and
+// other stuff
+
+%include math.i
+
+extern double drand48();
diff --git a/trunk/Examples/guile/matrix/vector.c b/trunk/Examples/guile/matrix/vector.c
new file mode 100644
index 0000000..3012993
--- /dev/null
+++ b/trunk/Examples/guile/matrix/vector.c
@@ -0,0 +1,44 @@
+/* File : vector.c */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include "vector.h"
+
+Vector *createv(double x, double y, double z, double w) {
+
+  Vector *n;
+  n = (Vector *) malloc(sizeof(Vector));
+  n->x = x;
+  n->y = y;
+  n->z = z;
+  n->w = w;
+  return n;
+
+}
+
+/* Destroy vector */
+
+void destroyv(Vector *v) {
+  free(v);
+}
+
+/* Print a vector */
+
+void printv(Vector *v) {
+
+  printf("x = %g, y = %g, z = %g, w = %g\n", v->x, v->y, v->z, v->w);
+
+}
+
+/* Do a transformation */
+void transform(double **m, Vector *v, Vector *r) {
+
+  r->x = m[0][0]*v->x + m[0][1]*v->y + m[0][2]*v->z + m[0][3]*v->w;
+  r->y = m[1][0]*v->x + m[1][1]*v->y + m[1][2]*v->z + m[1][3]*v->w;
+  r->z = m[2][0]*v->x + m[2][1]*v->y + m[2][2]*v->z + m[2][3]*v->w;
+  r->w = m[3][0]*v->x + m[3][1]*v->y + m[3][2]*v->z + m[3][3]*v->w;
+
+}
+
+
+
diff --git a/trunk/Examples/guile/matrix/vector.h b/trunk/Examples/guile/matrix/vector.h
new file mode 100644
index 0000000..a6b5f35
--- /dev/null
+++ b/trunk/Examples/guile/matrix/vector.h
@@ -0,0 +1,10 @@
+
+#include <math.h>
+
+typedef struct {
+  double x;
+  double y;
+  double z;
+  double w;
+} Vector;
+
diff --git a/trunk/Examples/guile/matrix/vector.i b/trunk/Examples/guile/matrix/vector.i
new file mode 100644
index 0000000..b6c2ef9
--- /dev/null
+++ b/trunk/Examples/guile/matrix/vector.i
@@ -0,0 +1,22 @@
+//
+// FILE : vector.i
+
+%{
+#include "vector.h"
+%}
+
+%inline {
+
+extern Vector *createv(double x,double y,double z,double w);
+/* Creates a new vector v(x,y,z,w) */
+
+extern void destroyv(Vector *v);
+/* Destroys the vector v */
+
+extern void   printv(Vector *v);
+/* Prints out the vector v */
+
+extern void   transform(double **T, Vector *v, Vector *t);
+/* Transforms vector c to vector t by M*v --> t */
+
+}
diff --git a/trunk/Examples/guile/multimap/Makefile b/trunk/Examples/guile/multimap/Makefile
new file mode 100644
index 0000000..dc9c66d
--- /dev/null
+++ b/trunk/Examples/guile/multimap/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: all
diff --git a/trunk/Examples/guile/multimap/example.c b/trunk/Examples/guile/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/guile/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/guile/multimap/example.i b/trunk/Examples/guile/multimap/example.i
new file mode 100644
index 0000000..7337d1e
--- /dev/null
+++ b/trunk/Examples/guile/multimap/example.i
@@ -0,0 +1,87 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+%include typemaps.i
+
+extern int    gcd(int x, int y);
+
+%typemap(in) (int argc, char *argv[]) {
+  int i;
+  SCM *v;
+  if (!(SCM_NIMP($input) && SCM_VECTORP($input))) {
+    SWIG_exception(SWIG_ValueError, "Expecting a vector");
+    return 0;
+  }
+  $1 = SCM_LENGTH($input);
+  if ($1 == 0) {
+    SWIG_exception(SWIG_ValueError, "Vector must contain at least 1 element");
+  }
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  v = SCM_VELTS($input);
+  for (i = 0; i < $1; i++) {
+    if (!(SCM_NIMP(v[i]) && SCM_STRINGP(v[i]))) {
+      free($2);	
+      SWIG_exception(SWIG_ValueError, "Vector items must be strings");
+      return 0;
+    }
+    $2[i] = SCM_CHARS(v[i]);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char *argv[]) {
+   free($2);
+}
+
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  if (!(SCM_NIMP($input) && SCM_STRINGP($input))) {
+    SWIG_exception(SWIG_ValueError, "Expecting a string");
+  }
+  $1 = SCM_CHARS($input);
+  $2 = SCM_LENGTH($input);
+}
+
+extern int count(char *bytes, int len, char c);
+
+/* This example shows how to wrap a function that mutates a string */
+
+%typemap(in) (char *str, int len) {
+  size_t temp;
+  $1 = gh_scm2newstr($input,&temp);
+  $2 = temp;
+}
+
+/* Return the mutated string as a new object.  */
+
+%typemap(argout) (char *str, int len) {
+  SWIG_APPEND_VALUE(gh_str2scm($1,$2));
+  if ($1) scm_must_free($1);
+}   
+
+extern void capitalize(char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
+   }
+}
+
+extern void circle(double cx, double cy);
+
+
diff --git a/trunk/Examples/guile/multimap/runme.scm b/trunk/Examples/guile/multimap/runme.scm
new file mode 100644
index 0000000..edc1972
--- /dev/null
+++ b/trunk/Examples/guile/multimap/runme.scm
@@ -0,0 +1,30 @@
+;;; Test out some multi-argument typemaps
+
+(use-modules (example))
+
+; Call the GCD function
+
+(define x 42)
+(define y 105)
+(define g (gcd x y))
+
+(display "The gcd of ")
+(display x)
+(display " and ")
+(display y)
+(display " is ")
+(display g)
+(newline)
+
+;  Call the gcdmain() function
+(gcdmain #("gcdmain" "42" "105"))
+
+; Call the count function
+(display (count "Hello World" #\l))
+(newline)
+
+; Call the capitalize function
+(display (capitalize "hello world"))
+(newline)
+
+
diff --git a/trunk/Examples/guile/multivalue/Makefile b/trunk/Examples/guile/multivalue/Makefile
new file mode 100644
index 0000000..dc9c66d
--- /dev/null
+++ b/trunk/Examples/guile/multivalue/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: all
diff --git a/trunk/Examples/guile/multivalue/example.c b/trunk/Examples/guile/multivalue/example.c
new file mode 100644
index 0000000..c9ebad1
--- /dev/null
+++ b/trunk/Examples/guile/multivalue/example.c
@@ -0,0 +1,18 @@
+void divide_l(int a, int b, int *quotient_p, int *remainder_p)
+{
+  *quotient_p = a/b;
+  *remainder_p = a%b;
+}
+
+void divide_v(int a, int b, int *quotient_p, int *remainder_p)
+{
+  *quotient_p = a/b;
+  *remainder_p = a%b;
+}
+
+void divide_mv(int a, int b, int *quotient_p, int *remainder_p)
+{
+  *quotient_p = a/b;
+  *remainder_p = a%b;
+}
+
diff --git a/trunk/Examples/guile/multivalue/example.i b/trunk/Examples/guile/multivalue/example.i
new file mode 100644
index 0000000..1353894
--- /dev/null
+++ b/trunk/Examples/guile/multivalue/example.i
@@ -0,0 +1,32 @@
+/* -*- c -*- */
+
+%module example;
+
+%{
+void divide_l(int a, int b, int *quotient_p, int *remainder_p);
+void divide_v(int a, int b, int *quotient_p, int *remainder_p);
+void divide_mv(int a, int b, int *quotient_p, int *remainder_p);
+%}
+
+/* Multiple values as lists. By default, if more than one value is to
+be returned, a list of the values is created and returned; to switch
+back to this behavior, use: */
+%values_as_list; 
+
+void divide_l(int a, int b, int *OUTPUT, int *OUTPUT);
+
+/* Multiple values as vectors. By issueing: */
+%values_as_vector;
+/* vectors instead of lists will be used. */
+
+void divide_v(int a, int b, int *OUTPUT, int *OUTPUT);
+
+/* Multiple values for multiple-value continuations.
+   (This is the most elegant way.)  By issueing: */
+%multiple_values;
+/* multiple values are passed to the multiple-value
+   continuation, as created by `call-with-values' or the
+   convenience macro `receive'. (See the Scheme file.) */
+
+void divide_mv(int a, int b, int *OUTPUT, int *OUTPUT);
+
diff --git a/trunk/Examples/guile/multivalue/runme.scm b/trunk/Examples/guile/multivalue/runme.scm
new file mode 100644
index 0000000..73eb5af
--- /dev/null
+++ b/trunk/Examples/guile/multivalue/runme.scm
@@ -0,0 +1,66 @@
+;;;; Show the three different ways to deal with multiple return values
+
+(use-modules (example))
+
+;;; Multiple values as lists. By default, if more than one value is to
+;;; be returned, a list of the values is created and returned.  The
+;;; procedure divide-l does so:
+
+(let* ((quotient/remainder (divide-l 37 5))
+       ;; divide-l returns a list of the two values, so get them:
+       (quotient (car quotient/remainder))
+       (remainder (cadr quotient/remainder)))
+  (display "37 divided by 5 is ")
+  (display quotient)
+  (display ", remainder ")
+  (display remainder)
+  (newline))
+
+;;; Multiple values as vectors.  You can get vectors instead of lists
+;;; if you want:
+
+(let* ((quotient-remainder-vector (divide-v 40 7))
+       ;; divide-v returns a vector of two values, so get them:
+       (quotient (vector-ref quotient-remainder-vector 0))
+       (remainder (vector-ref quotient-remainder-vector 1)))
+  (display "40 divided by 7 is ")
+  (display quotient)
+  (display ", remainder ")
+  (display remainder)
+  (newline))
+
+;;; Multiple values for multiple-value continuations. (The most
+;;; elegant way.)  You can get multiple values passed to the
+;;; multiple-value continuation, as created by `call-with-values'.
+
+(call-with-values (lambda ()
+		    ;; the "producer" procedure
+		    (divide-mv 91 13))
+		  (lambda (quotient remainder)
+		    ;; the "consumer" procedure
+		    (display "91 divided by 13 is ")
+		    (display quotient)
+		    (display ", remainder ")
+		    (display remainder)
+		    (newline)))
+
+;;; SRFI-8 has a very convenient macro for this construction:
+
+(use-modules (srfi srfi-8))
+
+;;; If your Guile is too old, you can define the receive macro yourself:
+;;;
+;;; (define-macro (receive vars vals . body)
+;;;  `(call-with-values (lambda () ,vals)
+;;;     (lambda ,vars ,@body)))
+
+(receive (quotient remainder)
+    (divide-mv 111 19) ; the "producer" form
+  ;; In the body, `quotient' and `remainder' are bound to the two
+  ;; values.
+  (display "111 divided by 19 is ")
+  (display quotient)
+  (display ", remainder ")
+  (display remainder)
+  (newline))
+
diff --git a/trunk/Examples/guile/port/Makefile b/trunk/Examples/guile/port/Makefile
new file mode 100644
index 0000000..824f3f8
--- /dev/null
+++ b/trunk/Examples/guile/port/Makefile
@@ -0,0 +1,18 @@
+SRCS   = port.c
+TARGET = port
+IFILE  = port.i
+MKDIR  = ..
+
+
+all::
+	$(MAKE) -f $(MKDIR)/Makefile		\
+		SRCS='$(SRCS)'			\
+		TARGET=$(TARGET)		\
+		IFILE=$(IFILE)			\
+		MODULE=$(MODULE)		\
+	  sub-all
+
+clean::
+	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: all
diff --git a/trunk/Examples/guile/port/README b/trunk/Examples/guile/port/README
new file mode 100644
index 0000000..5ed0199
--- /dev/null
+++ b/trunk/Examples/guile/port/README
@@ -0,0 +1,2 @@
+This example illustrates the translation from Scheme file ports to
+temporary FILE streams. Read the source and run ./port -s port.scm
diff --git a/trunk/Examples/guile/port/port.c b/trunk/Examples/guile/port/port.c
new file mode 100644
index 0000000..95867b6
--- /dev/null
+++ b/trunk/Examples/guile/port/port.c
@@ -0,0 +1,18 @@
+#include <stdio.h>
+#include <errno.h>
+
+void print_int(FILE *f, int i)
+{
+  if (fprintf(f, "%d\n", i)<0)
+    perror("print_int");
+}
+
+int read_int(FILE *f)
+{
+  int i;
+  if (fscanf(f, "%d", &i)!=1) {
+    fprintf(stderr, "read_int: error reading from file\n");
+    perror("read_int");
+  }
+  return i;
+}
diff --git a/trunk/Examples/guile/port/port.i b/trunk/Examples/guile/port/port.i
new file mode 100644
index 0000000..eb75391
--- /dev/null
+++ b/trunk/Examples/guile/port/port.i
@@ -0,0 +1,15 @@
+%module port
+
+%include guilemain.i
+
+/* Include the required FILE * typemaps */
+%include ports.i
+
+%{
+#include <stdio.h>
+%}
+
+%inline %{
+void print_int(FILE *f, int i);
+int read_int(FILE *f);
+%}
diff --git a/trunk/Examples/guile/port/port.scm b/trunk/Examples/guile/port/port.scm
new file mode 100644
index 0000000..68e9b8e
--- /dev/null
+++ b/trunk/Examples/guile/port/port.scm
@@ -0,0 +1,32 @@
+;; Call with standard output
+(print-int (current-output-port) 314159)
+
+;; Redirection to a file. Note that the port is automatically flushed
+;; (via force-output) before calling the C function, and that the C
+;; function gets a temporary "FILE" stream, which is closed after the
+;; call. So you can simply mix Scheme and C output.
+(with-output-to-file "test.out"
+  (lambda ()
+    (display 4711)
+    (newline)
+    (print-int (current-output-port) 314159)
+    (display 815)
+    (newline)))
+
+;; Redirection to a string or soft port won't work --
+;; we can only handle file ports.
+(catch #t
+       (lambda ()
+	 (with-output-to-string
+	   (lambda ()
+	     (print-int (current-output-port) 314159))))
+       (lambda args
+	 (write args) (newline)))
+
+;; Read from a file port. Note that it is a bad idea to mix Scheme and
+;; C input because of buffering.
+(with-input-from-file "test.out"
+  (lambda ()
+    (display (read-int (current-input-port)))
+    (newline)))
+
diff --git a/trunk/Examples/guile/simple/Makefile b/trunk/Examples/guile/simple/Makefile
new file mode 100644
index 0000000..702b5bb
--- /dev/null
+++ b/trunk/Examples/guile/simple/Makefile
@@ -0,0 +1,19 @@
+SRCS   = example.c
+TARGET = my-guile
+IFILE  = example.i
+MKDIR  = ..
+
+all: $(TARGET)
+
+$(TARGET):
+	$(MAKE) -f $(MKDIR)/Makefile		\
+		SRCS='$(SRCS)'			\
+		TARGET=$(TARGET)		\
+		IFILE=$(IFILE)			\
+	    sub-all
+
+clean::
+	$(MAKE) -f $(MKDIR)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: $(TARGET)
+	./$(TARGET) -s example.scm > /dev/null
diff --git a/trunk/Examples/guile/simple/README b/trunk/Examples/guile/simple/README
new file mode 100644
index 0000000..982216e
--- /dev/null
+++ b/trunk/Examples/guile/simple/README
@@ -0,0 +1,9 @@
+A very simple example.
+
+To run it, start the program 'my-guile' and type:
+
+	(load "example.scm")
+
+Alternatively, you can use the shell command:
+
+	./my-guile -s example.scm
diff --git a/trunk/Examples/guile/simple/example.c b/trunk/Examples/guile/simple/example.c
new file mode 100644
index 0000000..dcafc4d
--- /dev/null
+++ b/trunk/Examples/guile/simple/example.c
@@ -0,0 +1,21 @@
+/* Simple example from documentation */
+/* File : example.c */
+
+#include <time.h>
+
+double My_variable = 3.0;
+
+int fact(int n) {
+  if (n <= 1) return 1;
+  else return n*fact(n-1);
+}
+
+int mod(int n, int m) {
+  return (n % m);
+}
+
+char *get_time() {
+  long ltime;
+  time(&ltime);
+  return ctime(&ltime);
+}
diff --git a/trunk/Examples/guile/simple/example.i b/trunk/Examples/guile/simple/example.i
new file mode 100644
index 0000000..1a9930a
--- /dev/null
+++ b/trunk/Examples/guile/simple/example.i
@@ -0,0 +1,14 @@
+/* File : example.i */
+%module Example
+%{
+/* Put headers and other declarations here */
+%}
+
+%inline %{
+extern double My_variable;
+extern int    fact(int);
+extern int    mod(int n, int m);
+extern char  *get_time();
+%}
+
+%include guile/guilemain.i
diff --git a/trunk/Examples/guile/simple/example.scm b/trunk/Examples/guile/simple/example.scm
new file mode 100644
index 0000000..9408b1a
--- /dev/null
+++ b/trunk/Examples/guile/simple/example.scm
@@ -0,0 +1,28 @@
+;;; example.scm
+
+(define (mdisplay-newline . args)       ; does guile-1.3.4 have `format #t'?
+  (for-each display args)
+  (newline))
+
+(mdisplay-newline (get-time) "My variable = " (My-variable))
+
+(do ((i 0 (1+ i)))
+    ((= 14 i))
+  (mdisplay-newline i " factorial is " (fact i)))
+
+(define (mods i imax j jmax)
+  (if (< i imax)
+      (if (< j jmax)
+          (begin
+            (My-variable (+ (My-variable) (mod i j)))
+            (mods i imax (+ j 1) jmax))
+          (mods (+ i 1) imax 1 jmax))))
+
+(mods 1 150 1 150)
+
+(mdisplay-newline "My-variable = " (My-variable))
+
+(exit (and (= 1932053504 (fact 13))
+           (= 745470.0 (My-variable))))
+
+;;; example.scm ends here
diff --git a/trunk/Examples/guile/std_vector/Makefile b/trunk/Examples/guile/std_vector/Makefile
new file mode 100644
index 0000000..2733fb0
--- /dev/null
+++ b/trunk/Examples/guile/std_vector/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean
+
+check: all
diff --git a/trunk/Examples/guile/std_vector/example.h b/trunk/Examples/guile/std_vector/example.h
new file mode 100644
index 0000000..4f0dac7
--- /dev/null
+++ b/trunk/Examples/guile/std_vector/example.h
@@ -0,0 +1,25 @@
+/* File : example.h */
+
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<double> half(const std::vector<double>& v) {
+    std::vector<double> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    // would you believe this is the same as the above?
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+
diff --git a/trunk/Examples/guile/std_vector/example.i b/trunk/Examples/guile/std_vector/example.i
new file mode 100644
index 0000000..aa58b66
--- /dev/null
+++ b/trunk/Examples/guile/std_vector/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+/* instantiate the required template specializations */
+namespace std {
+    %template(IntVector)    vector<int>;
+    %template(DoubleVector) vector<double>;
+}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/guile/std_vector/runme.scm b/trunk/Examples/guile/std_vector/runme.scm
new file mode 100644
index 0000000..77443a1
--- /dev/null
+++ b/trunk/Examples/guile/std_vector/runme.scm
@@ -0,0 +1,54 @@
+;; run with mzscheme -r example.scm
+
+(use-modules (example))
+
+; repeatedly invoke a procedure with v and an index as arguments
+(define (with-vector v proc size-proc)
+  (let ((size (size-proc v)))
+    (define (with-vector-item v i)
+      (if (< i size)
+          (begin
+            (proc v i)
+            (with-vector-item v (+ i 1)))))
+    (with-vector-item v 0)))
+
+(define (with-IntVector v proc)
+  (with-vector v proc IntVector-length))
+(define (with-DoubleVector v proc)
+  (with-vector v proc DoubleVector-length))
+
+(define (print-DoubleVector v)
+  (with-DoubleVector v (lambda (v i) (display (DoubleVector-ref v i)) 
+                                     (display " ")))
+  (newline))
+
+
+; Call average with a Scheme list...
+
+(display (average '(1 2 3 4)))
+(newline)
+
+; ... or a wrapped std::vector<int>
+(define v (new-IntVector 4))
+(with-IntVector v (lambda (v i) (IntVector-set! v i (+ i 1))))
+(display (average v))
+(newline)
+(delete-IntVector v)
+
+; half will return a Scheme vector.
+; Call it with a Scheme vector...
+
+(display (half #(1 1.5 2 2.5 3)))
+(newline)
+
+; ... or a wrapped std::vector<double>
+(define v (new-DoubleVector))
+(map (lambda (i) (DoubleVector-push! v i)) '(1 2 3 4))
+(display (half v))
+(newline)
+
+; now halve a wrapped std::vector<double> in place
+(halve-in-place v)
+(print-DoubleVector v)
+(delete-DoubleVector v)
+
diff --git a/trunk/Examples/index.html b/trunk/Examples/index.html
new file mode 100644
index 0000000..f8b614a
--- /dev/null
+++ b/trunk/Examples/index.html
@@ -0,0 +1,58 @@
+<html>
+<head>
+<title>SWIG Examples</title>
+</head>
+
+<body bgcolor="#ffffff">
+<H1>SWIG Examples</H1>
+
+<p>
+Welcome to the browsable SWIG Examples directory.  This directory contains a 
+collection of examples that illustrate various SWIG features for a variety
+of target languages.  First, it is important to cover a few preliminaries:
+
+<ul>
+<li>All of the examples depend on the file <tt>Examples/Makefile</tt>
+found within the SWIG distribution.  This file is created by
+'configure' and usually requires no modifications.  However, if you
+have an usual installation of packages or experience compilation
+problems, you may need to make a few modifications.
+
+<p>
+<li>The examples directory is a work in progress and will probably remain
+somewhat incomplete.  At this time, the Examples directory is somewhat sparse
+since it is being rewritten and reoganized.
+
+<p>
+<li>
+The SWIG user manual also contains a large variety of examples.
+</ul>
+
+
+<h2>Fundamentals</h2>
+
+Follow one of these links to see some simple examples for a specific target
+language:
+
+<ul>
+<li><a href="python/index.html">Python</a>
+<li><a href="perl5/index.html">Perl5</a>
+<li><a href="tcl/index.html">Tcl</a>
+<li><a href="guile/">Guile</a>
+<li><a href="java/index.html">Java</a>
+<li><a href="mzscheme">Mzscheme</a>
+<li><a href="ruby/index.html">Ruby</a>
+</ul>
+
+If your target platform is Windows, make sure you also see the <a href="../Doc/Manual/Windows.html">Windows</a> page in the main manual.
+
+<h2>Real Life</h2>
+
+The <a href="GIFPlot/">GIFPlot</a> directory contains examples that illustrate the use of SWIG with
+a moderately complex C library for creating GIF images.  Many of these
+examples illustrate more advanced SWIG features.
+
+</body>
+</html>
+
+
diff --git a/trunk/Examples/java/callback/Makefile b/trunk/Examples/java/callback/Makefile
new file mode 100644
index 0000000..14c3017
--- /dev/null
+++ b/trunk/Examples/java/callback/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/callback/example.cxx b/trunk/Examples/java/callback/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/java/callback/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/java/callback/example.h b/trunk/Examples/java/callback/example.h
new file mode 100644
index 0000000..1a0e8c4
--- /dev/null
+++ b/trunk/Examples/java/callback/example.h
@@ -0,0 +1,23 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+
+class Callback {
+public:
+	virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; }
+	virtual void run() { std::cout << "Callback::run()" << std::endl; }
+};
+
+
+class Caller {
+private:
+	Callback *_callback;
+public:
+	Caller(): _callback(0) {}
+	~Caller() { delCallback(); }
+	void delCallback() { delete _callback; _callback = 0; }
+	void setCallback(Callback *cb) { delCallback(); _callback = cb; }
+	void call() { if (_callback) _callback->run(); }
+};
+
diff --git a/trunk/Examples/java/callback/example.i b/trunk/Examples/java/callback/example.i
new file mode 100644
index 0000000..90beda0
--- /dev/null
+++ b/trunk/Examples/java/callback/example.i
@@ -0,0 +1,13 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_string.i"
+
+/* turn on director wrapping Callback */
+%feature("director") Callback;
+
+%include "example.h"
+
diff --git a/trunk/Examples/java/callback/index.html b/trunk/Examples/java/callback/index.html
new file mode 100644
index 0000000..c254520
--- /dev/null
+++ b/trunk/Examples/java/callback/index.html
@@ -0,0 +1,20 @@
+<html>
+<head>
+<title>SWIG:Examples:java:callback</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/extend/</tt>
+<hr>
+
+<H2>Implementing C++ callbacks in Java</H2>
+
+<p>
+This example illustrates how to use directors to implement C++ callbacks in Java.
+</p>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/callback/main.java b/trunk/Examples/java/callback/main.java
new file mode 100644
index 0000000..4800f8c
--- /dev/null
+++ b/trunk/Examples/java/callback/main.java
@@ -0,0 +1,56 @@
+public class main
+{
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String[] args)
+  {
+    System.out.println("Adding and calling a normal C++ callback");
+    System.out.println("----------------------------------------");
+
+    Caller              caller = new Caller();
+    Callback            callback = new Callback();
+    
+    caller.setCallback(callback);
+    caller.call();
+    caller.delCallback();
+
+    callback = new JavaCallback();
+
+    System.out.println();
+    System.out.println("Adding and calling a Java callback");
+    System.out.println("------------------------------------");
+
+    caller.setCallback(callback);
+    caller.call();
+    caller.delCallback();
+
+    // Test that a double delete does not occur as the object has already been deleted from the C++ layer.
+    // Note that the garbage collector can also call the delete() method via the finalizer (callback.finalize())
+    // at any point after here.
+    callback.delete();
+
+    System.out.println();
+    System.out.println("java exit");
+  }
+}
+
+class JavaCallback extends Callback
+{
+  public JavaCallback()
+  {
+    super();
+  }
+
+  public void run()
+  {
+    System.out.println("JavaCallback.run()");
+  }
+}
+
diff --git a/trunk/Examples/java/check.list b/trunk/Examples/java/check.list
new file mode 100644
index 0000000..9728342
--- /dev/null
+++ b/trunk/Examples/java/check.list
@@ -0,0 +1,15 @@
+# see top-level Makefile.in
+callback
+class
+constants
+enum
+extend
+funcptr
+multimap
+native
+pointer
+reference
+simple
+template
+typemap
+variables
diff --git a/trunk/Examples/java/class/Makefile b/trunk/Examples/java/class/Makefile
new file mode 100644
index 0000000..14c3017
--- /dev/null
+++ b/trunk/Examples/java/class/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/class/example.cxx b/trunk/Examples/java/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/java/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/java/class/example.dsp b/trunk/Examples/java/class/example.dsp
new file mode 100644
index 0000000..fbe87e7
--- /dev/null
+++ b/trunk/Examples/java/class/example.dsp
@@ -0,0 +1,162 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# Begin Special Build Tool

+SOURCE="$(InputPath)"

+PostBuild_Desc=Java compile post-build step

+PostBuild_Cmds=echo on	"%JAVA_BIN%\javac" *.java

+# End Special Build Tool

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"example.dll"

+# Begin Special Build Tool

+SOURCE="$(InputPath)"

+PostBuild_Desc=Java compile post-build step

+PostBuild_Cmds=echo on	"%JAVA_BIN%\javac" *.java

+# End Special Build Tool

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo JAVA_INCLUDE: %JAVA_INCLUDE% 

+	echo JAVA_BIN: %JAVA_BIN% 

+	echo on 

+	..\..\..\swig.exe -c++ -java $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo JAVA_INCLUDE: %JAVA_INCLUDE% 

+	echo JAVA_BIN: %JAVA_BIN% 

+	echo on 

+	..\..\..\swig.exe -c++ -java $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/java/class/example.h b/trunk/Examples/java/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/java/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/java/class/example.i b/trunk/Examples/java/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/java/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/java/class/index.html b/trunk/Examples/java/class/index.html
new file mode 100644
index 0000000..e9db7e9
--- /dev/null
+++ b/trunk/Examples/java/class/index.html
@@ -0,0 +1,197 @@
+<html>
+<head>
+<title>SWIG:Examples:java:class</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/class/</tt>
+<hr>
+
+<H2>Wrapping a simple C++ class</H2>
+
+<p>
+This example illustrates the high level form of C++ class wrapping performed
+by SWIG.  In this case, a C++ class has a proxy Java class, which 
+provides access to C++ class members.
+
+<h2>The C++ Code</h2>
+
+Suppose you have some C++ classes described by the following (and admittedly lame) 
+header file:
+
+<blockquote>
+<pre>
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+A simple SWIG interface for this can be built by simply grabbing the header file
+like this:
+
+<blockquote>
+<pre>
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+</pre>
+</blockquote>
+
+Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> option like this:
+<blockquote>
+<pre>
+% swig -c++ -java example.i
+</pre>
+</blockquote>
+
+<h2>A sample Java program</h2>
+
+Click <a href="main.java">here</a> to see a Java program that calls the C++ functions from Java.
+
+<h2>Key points</h2>
+
+<ul>
+<li>To create a new object, you call a constructor like this:
+
+<blockquote>
+<pre>
+Circle c = new Circle(10);
+</pre>
+</blockquote>
+
+<p>
+<li>To access member data, a pair of accessor functions are used.
+For example:
+
+<blockquote>
+<pre>
+c.setX(15);        // Set member data
+x = c.getX();      // Get member data
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a member function, you simply do this
+
+<blockquote>
+<pre>
+System.out.println( "The area is " + c.area() );
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a destructor, simply do this
+
+<blockquote>
+<pre>
+c.delete();     // Deletes a shape
+</pre>
+</blockquote>
+
+<p>
+<li>Static member variables are wrapped with java static get and set access functions.  For example:
+
+<blockquote>
+<pre>
+n = Shape.getNshapes();     // Get a static data member
+Shape.setNshapes(13);       // Set a static data member
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>General Comments</h2>
+
+<ul>
+<li>This high-level interface using proxy classes is not the only way to handle C++ code. 
+A low level interface using c functions to access member variables and member functions is the alternative SWIG
+approach. This entails passing around the c pointer or c++ 'this' pointer and as such it is not difficult to crash the JVM. 
+The abstraction of the underlying pointer by the java proxy classes far better fits the java programming paradigm.
+
+<p>
+<li>SWIG *does* know how to properly perform upcasting of objects in an inheritance
+hierarchy (including multiple inheritance).  However Java classes can only derive from one base class so multiple inheritance
+is not implemented. Java classes can implement more than one interface so there is scope for improvement in the future. 
+
+<p>
+<li>A wide variety of C++ features are not currently supported by SWIG.  Here is the
+short and incomplete list:
+
+<p>
+<ul>
+<li>Overloaded methods and functions.  SWIG wrappers don't know how to resolve name
+conflicts so you must give an alternative name to any overloaded method name using the
+%name directive like this:
+
+<blockquote>
+<pre>
+void foo(int a);  
+%name(foo2) void foo(double a, double b);
+</pre>
+</blockquote>
+
+<p>
+<li>Overloaded operators.  Not supported at all. The only workaround for this is
+to write a helper function. For example:
+
+<blockquote>
+<pre>
+%inline %{
+    Vector *vector_add(Vector *a, Vector *b) {
+          ... whatever ...
+    }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>Namespaces.  Not supported at all. Won't be supported until SWIG2.0 (if at all).
+
+</ul>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/class/main.java b/trunk/Examples/java/class/main.java
new file mode 100644
index 0000000..8ef35db
--- /dev/null
+++ b/trunk/Examples/java/class/main.java
@@ -0,0 +1,70 @@
+// This example illustrates how C++ classes can be used from Java using SWIG.
+// The Java class gets mapped onto the C++ class and behaves as if it is a Java class.
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    // ----- Object creation -----
+    
+    System.out.println( "Creating some objects:" );
+    Circle c = new Circle(10);
+    System.out.println( "    Created circle " + c );
+    Square s = new Square(10);
+    System.out.println( "    Created square " + s );
+    
+    // ----- Access a static member -----
+    
+    System.out.println( "\nA total of " + Shape.getNshapes() + " shapes were created" );
+    
+    // ----- Member data access -----
+    
+    // Notice how we can do this using functions specific to
+    // the 'Circle' class.
+    c.setX(20);
+    c.setY(30);
+    
+    // Now use the same functions in the base class
+    Shape shape = s;
+    shape.setX(-10);
+    shape.setY(5);
+    
+    System.out.println( "\nHere is their current position:" );
+    System.out.println( "    Circle = (" + c.getX() + " " + c.getY() + ")" );
+    System.out.println( "    Square = (" + s.getX() + " " + s.getY() + ")" );
+    
+    // ----- Call some methods -----
+    
+    System.out.println( "\nHere are some properties of the shapes:" );
+    Shape[] shapes = {c,s};
+    for (int i=0; i<shapes.length; i++)
+    {
+          System.out.println( "   " + shapes[i].toString() );
+          System.out.println( "        area      = " + shapes[i].area() );
+          System.out.println( "        perimeter = " + shapes[i].perimeter() );
+    }
+    
+    // Notice how the area() and perimeter() functions really
+    // invoke the appropriate virtual method on each object.
+    
+    // ----- Delete everything -----
+    
+    System.out.println( "\nGuess I'll clean up now" );
+    
+    // Note: this invokes the virtual destructor
+    // You could leave this to the garbage collector
+    c.delete();
+    s.delete();
+    
+    System.out.println( Shape.getNshapes() + " shapes remain" );
+    System.out.println( "Goodbye" );
+  }
+}
diff --git a/trunk/Examples/java/constants/Makefile b/trunk/Examples/java/constants/Makefile
new file mode 100644
index 0000000..2b3d35c
--- /dev/null
+++ b/trunk/Examples/java/constants/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/constants/example.i b/trunk/Examples/java/constants/example.i
new file mode 100644
index 0000000..76665fc
--- /dev/null
+++ b/trunk/Examples/java/constants/example.i
@@ -0,0 +1,30 @@
+/* File : example.i */
+%module example
+
+/* Force the generated Java code to use the C constant values rather than making a JNI call */
+%javaconst(1);
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/java/constants/index.html b/trunk/Examples/java/constants/index.html
new file mode 100644
index 0000000..8367d05
--- /dev/null
+++ b/trunk/Examples/java/constants/index.html
@@ -0,0 +1,52 @@
+<html>
+<head>
+<title>SWIG:Examples:java:constants</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/java/constants/</tt>
+<hr>
+
+<H2>Wrapping C Constants</H2>
+
+<p>
+When SWIG encounters C preprocessor macros and C declarations that look like constants,
+it creates Java constant with an identical value.  Click <a href="example.i">here</a>
+to see a SWIG interface with some constant declarations in it.
+
+
+<h2>Accessing Constants from Java</h2>
+Click <a href="../../../Doc/Manual/Java.html#constants">here</a> for the section on constants in the SWIG and Java documentation.
+<p>
+
+Click <a href="main.java">here</a> to see a Java program that prints out the values
+of the constants contained in the above file.</p>
+<h2>Key points</h2>
+<ul>
+<li>The values of preprocessor macros are converted into Java constants.
+<li>Types are inferred by syntax (e.g., "3" is an integer and "3.5" is a float).
+<li>Character constants such as 'x' are converted into Java strings.
+<li>C string literals such as "Hello World" are converted into Java strings.
+<li>Macros that are not fully defined are simply ignored.  For example:
+<blockquote>
+<pre>
+#define EXTERN extern
+</pre>
+</blockquote>
+is ignored because SWIG has no idea what type of variable this would be.
+
+<p>
+<li>Expressions are allowed provided that all of their components are defined. Otherwise, the constant is ignored.
+
+<li>Certain C declarations involving 'const' are also turned into Java constants. 
+<li>The constants that appear in a SWIG interface file do not have to appear in any sort
+of matching C source file since the creation of a constant does not require linkage
+to a stored value (i.e., a value held in a C global variable or memory location).
+</ul>
+
+<hr>
+
+
+</body>
+</html>
diff --git a/trunk/Examples/java/constants/main.java b/trunk/Examples/java/constants/main.java
new file mode 100644
index 0000000..7130c3d
--- /dev/null
+++ b/trunk/Examples/java/constants/main.java
@@ -0,0 +1,44 @@
+import java.lang.reflect.*;
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    System.out.println("ICONST  = " + example.ICONST + " (should be 42)");
+    System.out.println("FCONST  = " + example.FCONST + " (should be 2.1828)");
+    System.out.println("CCONST  = " + example.CCONST + " (should be 'x')");
+    System.out.println("CCONST2 = " + example.CCONST2 + " (this should be on a new line)");
+    System.out.println("SCONST  = " + example.SCONST + " (should be 'Hello World')");
+    System.out.println("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')");
+    System.out.println("EXPR    = " + example.EXPR +   " (should be 48.5484)");
+    System.out.println("iconst  = " + example.iconst + " (should be 37)");
+    System.out.println("fconst  = " + example.fconst + " (should be 3.14)");
+
+// Use reflection to check if these variables are defined:
+    try
+    {
+        System.out.println("EXTERN = " + example.class.getField("EXTERN") + " (Arg! This shouldn't print anything)");
+    }
+    catch (NoSuchFieldException e)
+    {
+        System.out.println("EXTERN isn't defined (good)");
+    }
+
+    try
+    {
+        System.out.println("FOO    = " + example.class.getField("FOO") + " (Arg! This shouldn't print anything)");
+    }
+    catch (NoSuchFieldException e)
+    {
+        System.out.println("FOO isn't defined (good)");
+    }
+  }
+}
diff --git a/trunk/Examples/java/enum/Makefile b/trunk/Examples/java/enum/Makefile
new file mode 100644
index 0000000..14c3017
--- /dev/null
+++ b/trunk/Examples/java/enum/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/enum/example.cxx b/trunk/Examples/java/enum/example.cxx
new file mode 100644
index 0000000..df7bb63
--- /dev/null
+++ b/trunk/Examples/java/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.cxx */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/java/enum/example.h b/trunk/Examples/java/enum/example.h
new file mode 100644
index 0000000..9119cd9
--- /dev/null
+++ b/trunk/Examples/java/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE=10, WARP=20, LUDICROUS=30 };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/java/enum/example.i b/trunk/Examples/java/enum/example.i
new file mode 100644
index 0000000..fb65689
--- /dev/null
+++ b/trunk/Examples/java/enum/example.i
@@ -0,0 +1,14 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Force the generated Java code to use the C enum values rather than making a JNI call */
+%javaconst(1);
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/java/enum/index.html b/trunk/Examples/java/enum/index.html
new file mode 100644
index 0000000..52c06c5
--- /dev/null
+++ b/trunk/Examples/java/enum/index.html
@@ -0,0 +1,29 @@
+<html>
+<head>
+<title>SWIG:Examples:java:enum</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/enum/</tt>
+<hr>
+
+<H2>Wrapping enumerations</H2>
+
+<p>
+This example tests SWIG's ability to wrap enumerations. 
+SWIG wraps enums in numerous different ways. The default approach is to wrap
+each enum with the typesafe enum pattern. Enums are handled as integers in the JNI layer.
+See the documentation for the other approaches for wrapping enums.
+
+
+<ul>
+<li><a href="example.h">example.h</a>.  Header file containing some enums.
+<li><a href="example.i">example.i</a>.  Interface file.
+<li><a href="main.java">main.java</a>. Sample Java program.
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/enum/main.java b/trunk/Examples/java/enum/main.java
new file mode 100644
index 0000000..8646e00
--- /dev/null
+++ b/trunk/Examples/java/enum/main.java
@@ -0,0 +1,38 @@
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    // Print out the value of some enums
+    System.out.println("*** color ***");
+    System.out.println("    " + color.RED + " = " + color.RED.swigValue());
+    System.out.println("    " + color.BLUE + " = " + color.BLUE.swigValue());
+    System.out.println("    " + color.GREEN + " = " + color.GREEN.swigValue());
+
+    System.out.println("\n*** Foo::speed ***");
+    System.out.println("    Foo::" + Foo.speed.IMPULSE + " = " + Foo.speed.IMPULSE.swigValue());
+    System.out.println("    Foo::" + Foo.speed.WARP + " = " + Foo.speed.WARP.swigValue());
+    System.out.println("    Foo::" + Foo.speed.LUDICROUS + " = " + Foo.speed.LUDICROUS.swigValue());
+
+    System.out.println("\nTesting use of enums with functions\n");
+
+    example.enum_test(color.RED, Foo.speed.IMPULSE);
+    example.enum_test(color.BLUE, Foo.speed.WARP);
+    example.enum_test(color.GREEN, Foo.speed.LUDICROUS);
+
+    System.out.println( "\nTesting use of enum with class method" );
+    Foo f = new Foo();
+
+    f.enum_test(Foo.speed.IMPULSE);
+    f.enum_test(Foo.speed.WARP);
+    f.enum_test(Foo.speed.LUDICROUS);
+  }
+}
diff --git a/trunk/Examples/java/extend/Makefile b/trunk/Examples/java/extend/Makefile
new file mode 100644
index 0000000..14c3017
--- /dev/null
+++ b/trunk/Examples/java/extend/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/extend/example.cxx b/trunk/Examples/java/extend/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/java/extend/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/java/extend/example.h b/trunk/Examples/java/extend/example.h
new file mode 100644
index 0000000..b27ab97
--- /dev/null
+++ b/trunk/Examples/java/extend/example.h
@@ -0,0 +1,56 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+#include <vector>
+#include <string>
+#include <cmath>
+
+class Employee {
+private:
+	std::string name;
+public:
+	Employee(const char* n): name(n) {}
+	virtual std::string getTitle() { return getPosition() + " " + getName(); }
+	virtual std::string getName() { return name; }
+	virtual std::string getPosition() const { return "Employee"; }
+	virtual ~Employee() { printf("~Employee() @ %p\n", this); }
+};
+
+
+class Manager: public Employee {
+public:
+	Manager(const char* n): Employee(n) {}
+	virtual std::string getPosition() const { return "Manager"; }
+};
+
+
+class EmployeeList {
+	std::vector<Employee*> list;
+public:
+	EmployeeList() {
+		list.push_back(new Employee("Bob"));
+		list.push_back(new Employee("Jane"));
+		list.push_back(new Manager("Ted"));
+	}
+	void addEmployee(Employee *p) {
+		list.push_back(p);
+		std::cout << "New employee added.   Current employees are:" << std::endl;
+		std::vector<Employee*>::iterator i;
+		for (i=list.begin(); i!=list.end(); i++) {
+			std::cout << "  " << (*i)->getTitle() << std::endl;
+		}
+	}
+	const Employee *get_item(int i) {
+		return list[i];
+	}
+	~EmployeeList() { 
+		std::vector<Employee*>::iterator i;
+		std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl;
+		for (i=list.begin(); i!=list.end(); i++) {
+			delete *i;
+		}
+		std::cout << "~EmployeeList empty." << std::endl;
+	}
+};
+
diff --git a/trunk/Examples/java/extend/example.i b/trunk/Examples/java/extend/example.i
new file mode 100644
index 0000000..c8ec32e
--- /dev/null
+++ b/trunk/Examples/java/extend/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+%include "std_string.i"
+
+/* turn on director wrapping for Manager */
+%feature("director") Employee;
+%feature("director") Manager;
+
+%include "example.h"
+
diff --git a/trunk/Examples/java/extend/index.html b/trunk/Examples/java/extend/index.html
new file mode 100644
index 0000000..c7c2c12
--- /dev/null
+++ b/trunk/Examples/java/extend/index.html
@@ -0,0 +1,19 @@
+<html>
+<head>
+<title>SWIG:Examples:java:extend</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/extend/</tt>
+<hr>
+
+<H2>Extending a simple C++ class in Java</H2>
+
+<p>
+This example illustrates the extending of a C++ class with cross language polymorphism.
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/extend/main.java b/trunk/Examples/java/extend/main.java
new file mode 100644
index 0000000..ee3a94e
--- /dev/null
+++ b/trunk/Examples/java/extend/main.java
@@ -0,0 +1,88 @@
+// This file illustrates the cross language polymorphism using directors.
+
+
+// CEO class, which overrides Employee::getPosition().
+
+class CEO extends Manager {
+  public CEO(String name) {
+    super(name);
+    }
+  public String getPosition() {
+    return "CEO";
+    }
+  // Public method to stop the SWIG proxy base class from thinking it owns the underlying C++ memory.
+  public void disownMemory() {
+    swigCMemOwn = false; 
+  } 
+}
+
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+
+    // Create an instance of CEO, a class derived from the Java proxy of the 
+    // underlying C++ class. The calls to getName() and getPosition() are standard,
+    // the call to getTitle() uses the director wrappers to call CEO.getPosition().
+
+    CEO e = new CEO("Alice");
+    System.out.println( e.getName() + " is a " + e.getPosition() );
+    System.out.println( "Just call her \"" + e.getTitle() + "\"" );
+    System.out.println( "----------------------" );
+
+
+    // Create a new EmployeeList instance.  This class does not have a C++
+    // director wrapper, but can be used freely with other classes that do.
+
+    EmployeeList list = new EmployeeList();
+
+    // EmployeeList owns its items, so we must surrender ownership of objects we add.
+    e.disownMemory();
+    list.addEmployee(e);
+    System.out.println( "----------------------" );
+
+    // Now we access the first four items in list (three are C++ objects that
+    // EmployeeList's constructor adds, the last is our CEO). The virtual
+    // methods of all these instances are treated the same. For items 0, 1, and
+    // 2, all methods resolve in C++. For item 3, our CEO, getTitle calls
+    // getPosition which resolves in Java. The call to getPosition is
+    // slightly different, however, because of the overidden getPosition() call, since
+    // now the object reference has been "laundered" by passing through
+    // EmployeeList as an Employee*. Previously, Java resolved the call
+    // immediately in CEO, but now Java thinks the object is an instance of
+    // class Employee. So the call passes through the
+    // Employee proxy class and on to the C wrappers and C++ director,
+    // eventually ending up back at the Java CEO implementation of getPosition().
+    // The call to getTitle() for item 3 runs the C++ Employee::getTitle()
+    // method, which in turn calls getPosition(). This virtual method call
+    // passes down through the C++ director class to the Java implementation
+    // in CEO. All this routing takes place transparently.
+
+    System.out.println( "(position, title) for items 0-3:" );
+
+    System.out.println( "  " + list.get_item(0).getPosition() + ", \"" + list.get_item(0).getTitle() + "\"" );
+    System.out.println( "  " + list.get_item(1).getPosition() + ", \"" + list.get_item(1).getTitle() + "\"" );
+    System.out.println( "  " + list.get_item(2).getPosition() + ", \"" + list.get_item(2).getTitle() + "\"" );
+    System.out.println( "  " + list.get_item(3).getPosition() + ", \"" + list.get_item(3).getTitle() + "\"" );
+    System.out.println( "----------------------" );
+
+    // Time to delete the EmployeeList, which will delete all the Employee*
+    // items it contains. The last item is our CEO, which gets destroyed as well.
+    list.delete();
+    System.out.println( "----------------------" );
+
+    // All done.
+
+    System.out.println( "java exit" );
+
+  }
+}
diff --git a/trunk/Examples/java/funcptr/Makefile b/trunk/Examples/java/funcptr/Makefile
new file mode 100644
index 0000000..968c92c
--- /dev/null
+++ b/trunk/Examples/java/funcptr/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/funcptr/example.c b/trunk/Examples/java/funcptr/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/java/funcptr/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/java/funcptr/example.h b/trunk/Examples/java/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/java/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/java/funcptr/example.i b/trunk/Examples/java/funcptr/example.i
new file mode 100644
index 0000000..8b3bef6
--- /dev/null
+++ b/trunk/Examples/java/funcptr/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/java/funcptr/index.html b/trunk/Examples/java/funcptr/index.html
new file mode 100644
index 0000000..0ad2be1
--- /dev/null
+++ b/trunk/Examples/java/funcptr/index.html
@@ -0,0 +1,91 @@
+<html>
+<head>
+<title>SWIG:Examples:java:funcptr</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/funcptr/</tt>
+<hr>
+
+<H2>Pointers to Functions</H2>
+
+<p>
+Okay, just what in the heck does SWIG do with a declaration like this?
+
+<blockquote>
+<pre>
+int do_op(int a, int b, int (*op)(int, int));
+</pre>
+</blockquote>
+
+Well, it creates a wrapper as usual.  Of course, that does raise some
+questions about the third argument (the pointer to a function). 
+
+<p>
+In this case, SWIG will wrap the function pointer as it does for all other
+pointers.  However, in order to actually call this function from a Java program,
+you will need to pass some kind of C function pointer object.  In C,
+this is easy, you just supply a function name as an argument like this:
+
+<blockquote>
+<pre>
+/* Some callback function */
+int add(int a, int b) {
+   return a+b;
+} 
+...
+int r = do_op(x,y,add);
+</pre>
+</blockquote>
+
+To make this work with SWIG, you will need to do a little extra work.  Specifically,
+you need to create some function pointer objects using the %constant directive like this:
+
+<blockquote>
+<pre>
+%constant(int (*)(int,int)) ADD = add;
+</pre>
+</blockquote>
+
+Now, in a Java program, you would do this:
+
+<blockquote>
+<pre>
+int r = do_op(x,y, example.ADD)
+</pre>
+</blockquote>
+where <tt>example</tt> is the module name.
+
+<h2>An Example</h2>
+
+Here are some files that illustrate this with a simple example:
+
+<ul>
+<li><a href="example.c">example.c</a>
+<li><a href="example.h">example.h</a>
+<li><a href="example.i">example.i</a> (SWIG interface)
+<li><a href="main.java">main.java</a> (Sample program)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>The value of a function pointer must correspond to a function written in C or C++.
+It is not possible to pass an arbitrary Java function in as a substitute for a C 
+function pointer.
+
+<p>
+<li>A Java function can be used as a C/C++ callback if you write some
+clever typemaps and are very careful about how you create your extension.
+This is an advanced topic not covered here.
+</ul>
+
+<hr>
+</body>
+</html>
+
+
+
+
diff --git a/trunk/Examples/java/funcptr/main.java b/trunk/Examples/java/funcptr/main.java
new file mode 100644
index 0000000..cf81f92
--- /dev/null
+++ b/trunk/Examples/java/funcptr/main.java
@@ -0,0 +1,33 @@
+
+public class main {
+
+  static {
+    try {
+	System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+
+    int a = 37;
+    int b = 42;
+
+    // Now call our C function with a bunch of callbacks
+
+    System.out.println( "Trying some C callback functions" );
+    System.out.println( "    a        = " + a );
+    System.out.println( "    b        = " + b );
+    System.out.println( "    ADD(a,b) = " + example.do_op(a,b,example.ADD) );
+    System.out.println( "    SUB(a,b) = " + example.do_op(a,b,example.SUB) );
+    System.out.println( "    MUL(a,b) = " + example.do_op(a,b,example.MUL) );
+
+    System.out.println( "Here is what the C callback function classes are called in Java" );
+    System.out.println( "    ADD      = " + example.ADD.getClass().getName() );
+    System.out.println( "    SUB      = " + example.SUB.getClass().getName() );
+    System.out.println( "    MUL      = " + example.MUL.getClass().getName() );
+  }
+}
diff --git a/trunk/Examples/java/index.html b/trunk/Examples/java/index.html
new file mode 100644
index 0000000..d98f9a3
--- /dev/null
+++ b/trunk/Examples/java/index.html
@@ -0,0 +1,65 @@
+<html>
+<head>
+<title>SWIG:Examples:java</title>
+</head>
+
+<body bgcolor="#ffffff">
+<H1>SWIG Java Examples</H1>
+
+<p>
+The following examples illustrate the use of SWIG with Java.
+
+<ul>
+<li><a href="simple/index.html">simple</a>.  A minimal example showing how SWIG can
+be used to wrap a C function, a global variable, and a constant.
+<li><a href="native/index.html">native</a>. Comparing the manual and the SWIG approach to calling native code.
+<li><a href="typemap/index.html">typemap</a>. Modifying the Java module's default behaviour by using typemaps.
+<li><a href="constants/index.html">constants</a>.  This shows how preprocessor macros and
+certain C declarations are turned into constants.
+<li><a href="variables/index.html">variables</a>. An example showing how to access C global variables.
+<li><a href="enum/index.html">enum</a>. Wrapping enumerations.
+<li><a href="class/index.html">class</a>. How to wrap a simple C++ class.
+<li><a href="reference/index.html">reference</a>. C++ references.
+<li><a href="pointer/index.html">pointer</a>. Simple pointer handling.
+<li><a href="template/index.html">template</a>. C++ templates.
+<li><a href="funcptr/index.html">funcptr</a>. Pointers to functions.
+<li><a href="callback/index.html">callback</a>. C++ callbacks using directors.
+<li><a href="extend/index.html">extend</a>. Polymorphism using directors.
+</ul>
+
+<h2>Running the examples</h2>
+Please see the <a href="../../Doc/Manual/Windows.html">Windows</a> page in the main manual for information on using the examples on Windows. <p>
+
+On Unix most of the examples work by making the Makefile before executing the program main.java. The Makefile will output the swig generated JNI c code as well as the Java wrapper classes. Additionally the JNI c/c++ code is compiled into the shared object (dynamic link library) which is needed for dynamic linking to the native code. The Makefiles also compile the Java files using javac. 
+<p>
+Ensure that the dynamic link library file is in the appropriate path before executing the Java program. For example in Unix, libexample.so must be in the LD_LIBRARY_PATH. 
+<p>
+A Unix example:
+<blockquote>
+<pre>
+$ make
+$ export LD_LIBRARY_PATH=. #ksh 
+$ java main
+</pre>
+</blockquote>
+<p>
+
+</ul>
+
+<h2>Compatibility</h2>
+
+The examples have been extensively tested on the following platforms:
+
+<ul>
+<li>Solaris
+<li>Linux
+<li>Cygwin
+<li>Windows
+</ul>
+
+Your mileage may vary.  If you experience a problem, please let us know by 
+contacting us on the <a href="http://www.swig.org/mail.html">mailing lists</a>.
+</body>
+</html>
+
+
diff --git a/trunk/Examples/java/multimap/Makefile b/trunk/Examples/java/multimap/Makefile
new file mode 100644
index 0000000..968c92c
--- /dev/null
+++ b/trunk/Examples/java/multimap/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/multimap/example.c b/trunk/Examples/java/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/java/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/java/multimap/example.dsp b/trunk/Examples/java/multimap/example.dsp
new file mode 100644
index 0000000..8e1f841
--- /dev/null
+++ b/trunk/Examples/java/multimap/example.dsp
@@ -0,0 +1,158 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# Begin Special Build Tool

+SOURCE="$(InputPath)"

+PostBuild_Desc=Java compile post-build step

+PostBuild_Cmds=echo on	"%JAVA_BIN%\javac" *.java

+# End Special Build Tool

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"example.dll"

+# Begin Special Build Tool

+SOURCE="$(InputPath)"

+PostBuild_Desc=Java compile post-build step

+PostBuild_Cmds=echo on	"%JAVA_BIN%\javac" *.java

+# End Special Build Tool

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo JAVA_INCLUDE: %JAVA_INCLUDE% 

+	echo JAVA_BIN: %JAVA_BIN% 

+	echo on 

+	..\..\..\swig.exe -java $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo JAVA_INCLUDE: %JAVA_INCLUDE% 

+	echo JAVA_BIN: %JAVA_BIN% 

+	echo on 

+	..\..\..\swig.exe -java $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/java/multimap/example.i b/trunk/Examples/java/multimap/example.i
new file mode 100644
index 0000000..8d67282
--- /dev/null
+++ b/trunk/Examples/java/multimap/example.i
@@ -0,0 +1,109 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+extern int    gcd(int x, int y);
+
+%typemap(jni) (int argc, char *argv[]) "jobjectArray"
+%typemap(jtype) (int argc, char *argv[]) "String[]"
+%typemap(jstype) (int argc, char *argv[]) "String[]"
+
+%typemap(javain) (int argc, char *argv[]) "$javainput"
+
+%typemap(in) (int argc, char *argv[]) (jstring *jsarray) {
+int i;
+
+  $1 = (*jenv)->GetArrayLength(jenv, $input);
+  if ($1 == 0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
+    return $null;
+  }
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  jsarray = (jstring *) malloc($1*sizeof(jstring));
+  for (i = 0; i < $1; i++) {
+    jsarray[i] = (jstring) (*jenv)->GetObjectArrayElement(jenv, $input, i);
+    $2[i] = (char *) (*jenv)->GetStringUTFChars(jenv, jsarray[i], 0);
+  }
+  $2[i] = 0;
+}
+
+%typemap(argout) (int argc, char *argv[]) "" /* override char *[] default */
+
+%typemap(freearg) (int argc, char *argv[]) {
+int i;
+  for (i = 0; i < $1; i++) {
+    (*jenv)->ReleaseStringUTFChars(jenv, jsarray$argnum[i], $2[i]);
+  }
+  free($2);
+}
+
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(jni) (char *bytes, int len) "jstring"
+%typemap(jtype) (char *bytes, int len) "String"
+%typemap(jstype) (char *bytes, int len) "String"
+
+%typemap(javain) (char *bytes, int len) "$javainput"
+
+%typemap(in) (char *bytes, int len) {
+  $1 = ($1_type)(*jenv)->GetStringUTFChars(jenv, $input, 0);
+  $2 = (*jenv)->GetStringUTFLength(jenv, $input);
+}
+
+%typemap(freearg) (char *bytes, int len) %{
+  (*jenv)->ReleaseStringUTFChars(jenv, $input, $1);
+%}
+
+extern int count(char *bytes, int len, char c);
+
+/* This example shows how to wrap a function that mutates a c string. A one
+ * element Java string array is used so that the string can be returned modified.*/
+
+%typemap(jni) (char *str, int len) "jobjectArray"
+%typemap(jtype) (char *str, int len) "String[]"
+%typemap(jstype) (char *str, int len) "String[]"
+
+%typemap(javain) (char *str, int len) "$javainput"
+
+%typemap(in) (char *str, int len) (jstring js) {
+  int index = 0;
+  js = (jstring) (*jenv)->GetObjectArrayElement(jenv, $input, index);
+  $1 = (char *) (*jenv)->GetStringUTFChars(jenv, js, 0);
+  $2 = (*jenv)->GetStringUTFLength(jenv, js);
+}
+
+/* Return the mutated string as a modified element in the array. */
+%typemap(argout) (char *str, int len) {
+  jstring newstring = (*jenv)->NewStringUTF(jenv, $1);
+  (*jenv)->SetObjectArrayElement(jenv, $input, 0, newstring);
+}
+
+/* Release memory */
+%typemap(freearg) (char *str, int len) {
+  (*jenv)->ReleaseStringUTFChars(jenv, js$argnum, $1);
+}
+
+extern void capitalize(char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, "$1_name and $2_name must be in unit circle");
+    return;
+   }
+}
+
+extern void circle(double cx, double cy);
+
+
diff --git a/trunk/Examples/java/multimap/main.java b/trunk/Examples/java/multimap/main.java
new file mode 100644
index 0000000..331ac6b
--- /dev/null
+++ b/trunk/Examples/java/multimap/main.java
@@ -0,0 +1,40 @@
+
+public class main {
+
+  static {
+    try {
+      System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // Call our gcd() function
+    int x = 42;
+    int y = 105;
+    int g = example.gcd(x,y);
+    System.out.println("The gcd of " + x + " and " + y + " is " + g);
+    
+    // Call the gcdmain() function
+    String[] args = {"gcdmain","42","105"};
+    example.gcdmain(args);
+    
+    // Call the count function
+    System.out.println(example.count("Hello World", 'l'));
+    
+    // Call the capitalize function
+    String[] capitalizeMe = {"hello world"};
+    example.capitalize(capitalizeMe);
+    System.out.println(capitalizeMe[0]);
+  }
+}
+
+
+
+
+
+
+
diff --git a/trunk/Examples/java/native/Makefile b/trunk/Examples/java/native/Makefile
new file mode 100644
index 0000000..92afbd4
--- /dev/null
+++ b/trunk/Examples/java/native/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/native/example.i b/trunk/Examples/java/native/example.i
new file mode 100644
index 0000000..851b6fd
--- /dev/null
+++ b/trunk/Examples/java/native/example.i
@@ -0,0 +1,56 @@
+/* File : example.i */
+%module example
+
+%{
+#include <string.h>
+
+typedef struct point {
+  int x;
+  int y;
+} Point;
+
+
+Point *point_create(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+
+  return p;
+}
+
+static char *point_toString(char *format, Point *p) {
+  static char buf[80];
+
+  sprintf(buf, format, p->x, p->y);
+
+  return buf;
+}
+
+/* this function will be wrapped by SWIG */
+char *point_toString1(Point *p) {
+  return point_toString("(%d,%d)", p);
+}
+
+/* this one we wrapped manually*/
+JNIEXPORT jstring JNICALL Java_exampleJNI_point_1toString2(JNIEnv *jenv, jclass jcls, jlong jpoint) {
+    Point * p;
+    jstring result;
+
+    (void)jcls;
+
+    p = *(Point **)&jpoint;
+
+    result = (*jenv)->NewStringUTF(jenv, point_toString("[%d,%d]", p));
+
+    return result;
+}
+%}
+
+
+Point *point_create(int x, int y);
+char *point_toString1(Point *p);
+
+/* give access to free() for memory cleanup of the malloc'd Point */
+extern void free(void *memblock);
+
+%native(point_toString2) char *point_toString2(Point *p);
diff --git a/trunk/Examples/java/native/index.html b/trunk/Examples/java/native/index.html
new file mode 100644
index 0000000..7ecf129
--- /dev/null
+++ b/trunk/Examples/java/native/index.html
@@ -0,0 +1,33 @@
+<html>
+<head>
+<title>SWIG:Examples:java:native</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/native/</tt>
+<hr>
+
+<H2>SWIG wrapped and manually wrapped functions in Java</H2>
+
+Click <a href="../../../Doc/Manual/Java.html#using_own_jni_functions">here</a> for the relevant section in the SWIG and Java documentation.
+<p>
+This example compares wrapping a c global function using the manual way and the SWIG way.
+</p>
+
+<ul>
+<li><a href="example.i">example.i</a>. Interface file comparing code wrapped by SWIG and wrapped manually. 
+<li><a href="main.java">main.java</a>. Sample Java program showing calls to both manually wrapped and SWIG wrapped c functions.
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>SWIG writes all the awkward JNI code for you. You just have to tell SWIG which functions to wrap.
+<li>If memory is allocated in c it needs to be free'd. A function, such as free(), can be provided with access from Java to free the memory.
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/native/main.java b/trunk/Examples/java/native/main.java
new file mode 100644
index 0000000..f4760bb
--- /dev/null
+++ b/trunk/Examples/java/native/main.java
@@ -0,0 +1,19 @@
+
+public class main {
+
+  static {
+    try {
+	System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    SWIGTYPE_p_Point p = example.point_create(1, 2);
+    System.out.println("auto wrapped  : " + example.point_toString1(p));
+    System.out.println("manual wrapped: " + example.point_toString2(p));
+    example.free(new SWIGTYPE_p_void(SWIGTYPE_p_Point.getCPtr(p), false)); //clean up c allocated memory
+  }
+}
diff --git a/trunk/Examples/java/pointer/Makefile b/trunk/Examples/java/pointer/Makefile
new file mode 100644
index 0000000..968c92c
--- /dev/null
+++ b/trunk/Examples/java/pointer/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/pointer/example.c b/trunk/Examples/java/pointer/example.c
new file mode 100644
index 0000000..b877d9a
--- /dev/null
+++ b/trunk/Examples/java/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/java/pointer/example.i b/trunk/Examples/java/pointer/example.i
new file mode 100644
index 0000000..a8ac794
--- /dev/null
+++ b/trunk/Examples/java/pointer/example.i
@@ -0,0 +1,30 @@
+/* File : example.i */
+%module example
+
+%{
+extern void add(int *, int *, int *);
+extern void sub(int *, int *, int *);
+extern int divide(int, int, int *);
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/java/pointer/index.html b/trunk/Examples/java/pointer/index.html
new file mode 100644
index 0000000..c30d549
--- /dev/null
+++ b/trunk/Examples/java/pointer/index.html
@@ -0,0 +1,165 @@
+<html>
+<head>
+<title>SWIG:Examples:java:pointer</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/java/pointer/</tt>
+<hr>
+
+<H2>Simple Pointer Handling</H2>
+
+<p>
+This example illustrates a couple of techniques for handling
+simple pointers in SWIG.  The prototypical example is a C function
+that operates on pointers such as this:
+
+<blockquote>
+<pre>
+void add(int *x, int *y, int *r) { 
+    *r = *x + *y;
+}
+</pre>
+</blockquote>
+
+By default, SWIG wraps this function exactly as specified and creates
+an interface that expects pointer objects for arguments.  
+SWIG wraps a C pointer with a type wrapper class, for example, SWIGTYPE_p_int for an int*.
+The only problem is how does one go about creating these objects from a Java program?
+<p>
+
+
+<h2>Possible Solutions</h2>
+
+<ul>
+<li>Write some helper functions to explicitly create objects.  For
+example:
+
+<blockquote>
+<pre>
+int *new_int(int ivalue) {
+  int *i = (int *) malloc(sizeof(ivalue));
+  *i = ivalue;
+  return i;
+}
+int get_int(int *i) {
+  return *i;
+}
+
+void delete_int(int *i) {
+  free(i);
+}
+</pre>
+</blockquote>
+
+<p>
+<li>The SWIG pointer library provides an easier way. <br> 
+For example, in the interface file 
+you would do this:
+
+<blockquote>
+<pre>
+%include cpointer.i
+%pointer_functions(int, intp);
+</pre>
+</blockquote>
+
+and from Java you would use pointers like this:
+
+<blockquote>
+<pre>
+SWIGTYPE_p_int a = example.new_intp();
+SWIGTYPE_p_int b = example.new_intp();
+SWIGTYPE_p_int c = example.new_intp();
+example.intp_assign(a,37);
+example.intp_assign(b,42);
+
+// Note that getCPtr() has package access by default
+System.out.println("     a =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(a)));
+System.out.println("     b =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(b)));
+System.out.println("     c =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(c)));
+
+// Call the add() function with some pointers
+example.add(a,b,c);
+
+// Now get the result
+int res = example.intp_value(c);
+System.out.println("     37 + 42 =" + res);
+
+// Clean up the pointers
+example.delete_intp(a);
+example.delete_intp(b);
+example.delete_intp(c);
+</pre>
+</blockquote>
+
+<p>
+<li>Use the SWIG typemap library.  This library allows you to completely
+change the way arguments are processed by SWIG.  For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+void add(int *INPUT, int *INPUT, int *OUTPUT);
+</pre>
+</blockquote>
+
+And in a Java program:
+
+<blockquote>
+<pre>
+int[] r = {0};
+example.sub(37,42,r);
+System.out.println("Result =" + r[0]);
+</pre>
+</blockquote>
+Needless to say, this is substantially easier although a bit unusual.
+
+<p>
+<li>A final alternative is to use the typemaps library in combination
+with the %apply directive.  This allows you to change the names of parameters
+that behave as input or output parameters. For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+%apply int *INPUT {int *x, int *y};
+%apply int *OUTPUT {int *r};
+
+void add(int *x, int *y, int *r);
+void sub(int *x, int *y, int *r);
+void mul(int *x, int *y, int *r);
+... etc ...
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>Example</h2>
+
+The following example illustrates the use of these features for pointer
+extraction.
+
+<ul>
+<li> <a href="example.c">example.c</a>  (C Source)
+<li> <a href="example.i">example.i</a>  (Swig interface)
+<li> <a href="main.java">main.java</a>  (Java program)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>Since pointers are used for so many different things (arrays, output values,
+etc...) the complexity of pointer handling can be as complicated as you want to
+make it.
+
+<p>
+<li>More documentation on the typemaps.i and cpointer.i library files can be
+found in the SWIG user manual.  The files also contain documentation.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/pointer/main.java b/trunk/Examples/java/pointer/main.java
new file mode 100644
index 0000000..e96e02e
--- /dev/null
+++ b/trunk/Examples/java/pointer/main.java
@@ -0,0 +1,55 @@
+
+public class main {
+
+  static {
+    try {
+	System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // First create some objects using the pointer library.
+    System.out.println("Testing the pointer library");
+    SWIGTYPE_p_int a = example.new_intp();
+    SWIGTYPE_p_int b = example.new_intp();
+    SWIGTYPE_p_int c = example.new_intp();
+    example.intp_assign(a,37);
+    example.intp_assign(b,42);
+
+    // Note that getCPtr() has package access by default
+    System.out.println("     a =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(a)));
+    System.out.println("     b =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(b)));
+    System.out.println("     c =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(c)));
+
+    // Call the add() function with some pointers
+    example.add(a,b,c);
+
+    // Now get the result
+    int res = example.intp_value(c);
+    System.out.println("     37 + 42 =" + res);
+
+    // Clean up the pointers
+    example.delete_intp(a);
+    example.delete_intp(b);
+    example.delete_intp(c);
+
+    // Now try the typemap library
+    // Now it is no longer necessary to manufacture pointers.
+    // Instead we use a single element array which in Java is modifiable.
+
+    System.out.println("Trying the typemap library");
+    int[] r = {0};
+    example.sub(37,42,r);
+    System.out.println("     37 - 42 = " + r[0]);
+
+    // Now try the version with return value
+
+    System.out.println("Testing return value");
+    int q = example.divide(42,37,r);
+    System.out.println("     42/37 = " + q + " remainder " + r[0]);
+  }
+}
diff --git a/trunk/Examples/java/reference/Makefile b/trunk/Examples/java/reference/Makefile
new file mode 100644
index 0000000..14c3017
--- /dev/null
+++ b/trunk/Examples/java/reference/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/reference/example.cxx b/trunk/Examples/java/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/java/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/java/reference/example.h b/trunk/Examples/java/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/java/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/java/reference/example.i b/trunk/Examples/java/reference/example.i
new file mode 100644
index 0000000..6daa3b1
--- /dev/null
+++ b/trunk/Examples/java/reference/example.i
@@ -0,0 +1,46 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/java/reference/index.html b/trunk/Examples/java/reference/index.html
new file mode 100644
index 0000000..64b129c
--- /dev/null
+++ b/trunk/Examples/java/reference/index.html
@@ -0,0 +1,147 @@
+<html>
+<head>
+<title>SWIG:Examples:java:reference</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/reference/</tt>
+<hr>
+
+<H2>C++ Reference Handling</H2>
+
+<p>
+This example tests SWIG's handling of C++ references.  Since C++
+references are closely related to pointers (as both refer to a
+location in memory), SWIG simply collapses all references into
+pointers when creating wrappers.
+
+<h2>Some examples</h2>
+
+References are most commonly used as function parameter.  For example,
+you might have an operator like this:
+
+<blockquote>
+<pre>
+Vector operator+(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+or a function:
+
+<blockquote>
+<pre>
+Vector addv(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+In these cases, SWIG transforms everything into a pointer and creates a wrapper
+that looks like this:
+
+<blockquote>
+<pre>
+Vector wrap_addv(Vector *a, Vector *b) {
+    return addv(*a,*b);
+}
+</pre>
+</blockquote>
+
+Occasionally, a reference is used as a return value of a function
+when the return result is to be used as an lvalue in an expression.
+The prototypical example is an operator like this:
+
+<blockquote>
+<pre>
+Vector &amp;operator[](int index);
+</pre>
+</blockquote>
+
+or a method:
+
+<blockquote>
+<pre>
+Vector &amp;get(int index);
+</pre>
+</blockquote>
+
+For functions returning references, a wrapper like this is created:
+
+<blockquote>
+<pre>
+Vector *wrap_Object_get(Object *self, int index) {
+    Vector &amp;result = self-&gt;get(index);
+    return &amp;result;
+}
+</pre>
+</blockquote>
+
+The following <a href="example.h">header file</a> contains some class
+definitions with some operators and use of references.
+
+<h2>SWIG Interface</h2>
+
+SWIG does NOT support overloaded operators so it can not directly build
+an interface to the classes in the above file.   However, a number of workarounds
+can be made.  For example, an overloaded operator can be stuck behind a function
+call such as the <tt>addv()</tt> function above.  Array access can be handled
+with a pair of set/get functions like this:
+
+<blockquote>
+<pre>
+class VectorArray {
+public:
+ ...
+   %addmethods {
+    Vector &amp;get(int index) {
+      return (*self)[index];
+    }
+    void set(int index, Vector &amp;a) {
+      (*self)[index] = a;
+    }
+   }
+   ...
+}
+</pre>
+</blockquote>
+
+Click <a href="example.i">here</a> to see a SWIG interface file with these additions.
+
+<h2>Sample Java program</h2>
+
+Click <a href="main.java">here</a> to see a Java program that manipulates some C++ references.
+
+<h2>Notes:</h2>
+
+<ul>
+<li>C++ references primarily provide notational convenience for C++
+source code.  However, Java only supports the 'x.a' 
+notation so it doesn't much matter.
+
+<p>
+<li>When a program returns a reference, a pointer is returned.
+Unlike return by value, memory is not allocated to hold the
+return result.
+
+<p>
+<li>SWIG has particular trouble handling various combinations of references
+and pointers.  This is side effect of an old parsing scheme and
+type representation that will be replaced in future versions.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/reference/main.java b/trunk/Examples/java/reference/main.java
new file mode 100644
index 0000000..4fd3547
--- /dev/null
+++ b/trunk/Examples/java/reference/main.java
@@ -0,0 +1,79 @@
+// This example illustrates the manipulation of C++ references in Java.
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    System.out.println( "Creating some objects:" );
+    Vector a = new Vector(3,4,5);
+    Vector b = new Vector(10,11,12);
+    
+    System.out.println( "    Created " + a.print() );
+    System.out.println( "    Created " + b.print() );
+    
+    // ----- Call an overloaded operator -----
+    
+    // This calls the wrapper we placed around
+    //
+    //      operator+(const Vector &a, const Vector &) 
+    //
+    // It returns a new allocated object.
+    
+    System.out.println( "Adding a+b" );
+    Vector c = example.addv(a,b);
+    System.out.println( "    a+b = " + c.print() );
+    
+    // Note: Unless we free the result, a memory leak will occur if the -noproxy commandline
+    // is used as the proxy classes define finalizers which call the delete() method. When
+    // -noproxy is not specified the memory management is controlled by the garbage collector.
+    // You can still call delete(). It will free the c++ memory immediately, but not the 
+    // Java memory! You then must be careful not to call any member functions as it will 
+    // use a NULL c pointer on the underlying c++ object. We set the Java object to null
+    // which will then throw a Java exception should we attempt to use it again.
+    c.delete();
+    c = null;
+    
+    // ----- Create a vector array -----
+    
+    System.out.println( "Creating an array of vectors" );
+    VectorArray va = new VectorArray(10);
+    System.out.println( "    va = " + va.toString() );
+    
+    // ----- Set some values in the array -----
+    
+    // These operators copy the value of Vector a and Vector b to the vector array
+    va.set(0,a);
+    va.set(1,b);
+    
+    // This works, but it would cause a memory leak if -noproxy was used!
+    
+    va.set(2,example.addv(a,b));
+    
+
+    // Get some values from the array
+    
+    System.out.println( "Getting some array values" );
+    for (int i=0; i<5; i++)
+        System.out.println( "    va(" + i + ") = " + va.get(i).print() );
+    
+    // Watch under resource meter to check on this
+    System.out.println( "Making sure we don't leak memory." );
+    for (int i=0; i<1000000; i++)
+        c = va.get(i%10);
+    
+    // ----- Clean up -----
+    // This could be omitted. The garbage collector would then clean up for us.
+    System.out.println( "Cleaning up" );
+    va.delete();
+    a.delete();
+    b.delete();
+  }
+}
diff --git a/trunk/Examples/java/simple/Makefile b/trunk/Examples/java/simple/Makefile
new file mode 100644
index 0000000..968c92c
--- /dev/null
+++ b/trunk/Examples/java/simple/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/simple/example.c b/trunk/Examples/java/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/java/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/java/simple/example.dsp b/trunk/Examples/java/simple/example.dsp
new file mode 100644
index 0000000..8e1f841
--- /dev/null
+++ b/trunk/Examples/java/simple/example.dsp
@@ -0,0 +1,158 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# Begin Special Build Tool

+SOURCE="$(InputPath)"

+PostBuild_Desc=Java compile post-build step

+PostBuild_Cmds=echo on	"%JAVA_BIN%\javac" *.java

+# End Special Build Tool

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(JAVA_INCLUDE)" /I "$(JAVA_INCLUDE)\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"example.dll"

+# Begin Special Build Tool

+SOURCE="$(InputPath)"

+PostBuild_Desc=Java compile post-build step

+PostBuild_Cmds=echo on	"%JAVA_BIN%\javac" *.java

+# End Special Build Tool

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo JAVA_INCLUDE: %JAVA_INCLUDE% 

+	echo JAVA_BIN: %JAVA_BIN% 

+	echo on 

+	..\..\..\swig.exe -java $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo JAVA_INCLUDE: %JAVA_INCLUDE% 

+	echo JAVA_BIN: %JAVA_BIN% 

+	echo on 

+	..\..\..\swig.exe -java $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/java/simple/example.i b/trunk/Examples/java/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/java/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/java/simple/index.html b/trunk/Examples/java/simple/index.html
new file mode 100644
index 0000000..a363327
--- /dev/null
+++ b/trunk/Examples/java/simple/index.html
@@ -0,0 +1,108 @@
+<html>
+<head>
+<title>SWIG:Examples:java:simple</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/simple/</tt>
+<hr>
+
+<H2>Simple Java Example</H2>
+
+<p>
+This example illustrates how you can hook Java to a very simple C program containing
+a function and a global variable.
+
+<h2>The C Code</h2>
+
+Suppose you have the following C code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x &gt; 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+Here is a simple SWIG interface file:
+
+<blockquote>
+<pre>
+/* File: example.i */
+%module example
+
+extern int gcd(int x, int y);
+extern double Foo;
+</pre>
+</blockquote>
+
+<h2>Compilation</h2>
+
+<ol>
+<li><tt>swig -java <a href="example.i">example.i</a></tt>
+<p>
+<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
+to create the extension <tt>libexample.so (unix)</tt>. 
+</ol>
+
+<h2>Using the extension</h2>
+
+Click <a href="main.java">here</a> to see a program that calls our C functions from Java.
+<p>
+Compile the java files <tt><a href="example.java">example.java</a></tt> and <tt><a href="main.java">main.java</a></tt>
+to create the class files example.class and main.class before running main in the JVM.  Ensure that the libexample.so file is in your LD_LIBRARY_PATH before running. For example:
+<blockquote>
+<pre>
+export LD_LIBRARY_PATH=. #ksh 
+javac *.java
+java main
+</pre>
+</blockquote>
+
+<h2>Key points</h2>
+
+<ul>
+<li>Use the <tt>loadLibrary</tt> statement from java to load and access the generated java classes. For example:
+<blockquote>
+<pre>
+System.loadLibrary("example");
+</pre>
+</blockquote>
+
+<li>C functions work just like Java functions. For example:
+<blockquote>
+<pre>
+int g = example.gcd(42,105);
+</pre>
+</blockquote>
+
+<li>C global variables are accessed through get and set functions in the module class. For example:
+<blockquote>
+<pre>
+double a = example.get_Foo();
+example.set_Foo(20.0);
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/simple/main.java b/trunk/Examples/java/simple/main.java
new file mode 100644
index 0000000..6d224a4
--- /dev/null
+++ b/trunk/Examples/java/simple/main.java
@@ -0,0 +1,32 @@
+
+public class main {
+
+  static {
+    try {
+	System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    // Call our gcd() function
+    
+    int x = 42;
+    int y = 105;
+    int g = example.gcd(x,y);
+    System.out.println("The gcd of " + x + " and " + y + " is " + g);
+    
+    // Manipulate the Foo global variable
+    
+    // Output its current value
+    System.out.println("Foo = " + example.getFoo());
+    
+    // Change its value
+    example.setFoo(3.1415926);
+    
+    // See if the change took effect
+    System.out.println("Foo = " + example.getFoo());
+  }
+}
diff --git a/trunk/Examples/java/template/Makefile b/trunk/Examples/java/template/Makefile
new file mode 100644
index 0000000..2b3d35c
--- /dev/null
+++ b/trunk/Examples/java/template/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/template/example.h b/trunk/Examples/java/template/example.h
new file mode 100644
index 0000000..7401df6
--- /dev/null
+++ b/trunk/Examples/java/template/example.h
@@ -0,0 +1,32 @@
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %extend {
+    T getitem(int index) {
+      return $self->get(index);
+    }
+    void setitem(int index, T val) {
+      $self->set(index,val);
+    }
+  }
+#endif
+};
+
diff --git a/trunk/Examples/java/template/example.i b/trunk/Examples/java/template/example.i
new file mode 100644
index 0000000..8f94c4d
--- /dev/null
+++ b/trunk/Examples/java/template/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
diff --git a/trunk/Examples/java/template/index.html b/trunk/Examples/java/template/index.html
new file mode 100644
index 0000000..1aebd4c
--- /dev/null
+++ b/trunk/Examples/java/template/index.html
@@ -0,0 +1,102 @@
+<html>
+<head>
+<title>SWIG:Examples:java:template</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/template/</tt>
+<hr>
+
+<H2>C++ template support</H2>
+
+<p>
+This example illustrates how C++ templates can be used from Java using SWIG.
+
+<h2>The C++ Code</h2>
+
+Lets take a templated function and a templated class as follows:
+
+<blockquote>
+<pre>
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a&gt;b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &amp;get(int index) {
+    return v[index];
+  }
+  void set(int index, T &amp;val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %addmethods {
+    T getitem(int index) {
+      return self-&gt;get(index);
+    }
+    void setitem(int index, T val) {
+      self-&gt;set(index,val);
+    }
+  }
+#endif
+};
+</pre>
+</blockquote>
+The %addmethods is used for a neater interface from Java as the functions <tt>get</tt> and <tt>set</tt> use C++ references to primitive types. These are tricky to use from Java as they end up as a pointer in Java (Java long).
+
+<h2>The SWIG interface</h2>
+
+A simple SWIG interface for this can be built by simply grabbing the header file
+like this:
+
+<blockquote>
+<pre>
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+</pre>
+</blockquote>
+
+Note that SWIG parses the templated function <tt>max</tt> and templated class <tt>vector</tt> and so knows about them. However to generate code for use from Java, SWIG has to be told which class/type to use as the template parameter. The SWIG directive %template is used for this.
+
+<h2>A sample Java program</h2>
+
+Click <a href="main.java">here</a> to see a Java program that calls the C++ functions from Java.
+
+<h2>Notes</h2>
+Use templated classes just like you would any other SWIG generated Java class. Use the classnames specified by the %template directive.
+
+<blockquote>
+<pre>
+vecdouble dv = new vecdouble(1000);
+dv.setitem(i, 12.34));
+</pre>
+</blockquote>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/template/main.java b/trunk/Examples/java/template/main.java
new file mode 100644
index 0000000..9129fcf
--- /dev/null
+++ b/trunk/Examples/java/template/main.java
@@ -0,0 +1,45 @@
+// This example illustrates how C++ templates can be used from Java.
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    // Call some templated functions
+    System.out.println(example.maxint(3,7));
+    System.out.println(example.maxdouble(3.14,2.18));
+    
+    // Create some class
+    
+    vecint iv = new vecint(100);
+    vecdouble dv = new vecdouble(1000);
+    
+    for (int i=0; i<100; i++)
+        iv.setitem(i,2*i);
+    
+    for (int i=0; i<1000; i++)
+          dv.setitem(i, 1.0/(i+1));
+    
+    {
+    int sum = 0;
+    for (int i=0; i<100; i++)
+          sum = sum + iv.getitem(i);
+    
+    System.out.println(sum);
+    }
+    
+    {
+    double sum = 0.0;
+    for (int i=0; i<1000; i++)
+          sum = sum + dv.getitem(i);
+    System.out.println(sum);
+    }
+  }
+}
diff --git a/trunk/Examples/java/typemap/Makefile b/trunk/Examples/java/typemap/Makefile
new file mode 100644
index 0000000..92afbd4
--- /dev/null
+++ b/trunk/Examples/java/typemap/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/typemap/example.i b/trunk/Examples/java/typemap/example.i
new file mode 100644
index 0000000..7c97e66
--- /dev/null
+++ b/trunk/Examples/java/typemap/example.i
@@ -0,0 +1,101 @@
+/* File : example.i */
+%module example
+%{
+/*
+   example of a function that returns a value in the char * argument
+   normally used like:
+
+   char buf[bigenough];
+   f1(buf);
+*/
+
+void f1(char *s) {
+  if(s != NULL) {
+    sprintf(s, "hello world");
+  }
+}
+
+void f2(char *s) {
+  f1(s);
+}
+
+void f3(char *s) {
+  f1(s);
+}
+
+%}
+
+/* default behaviour is that of input arg, Java cannot return a value in a 
+ * string argument, so any changes made by f1(char*) will not be seen in the Java
+ * string passed to the f1 function.
+*/
+void f1(char *s);
+
+%include various.i
+
+/* use the BYTE argout typemap to get around this. Changes in the string by 
+ * f2 can be seen in Java. */
+void f2(char *BYTE);
+
+
+
+/* Alternative approach uses a StringBuffer typemap for argout */
+
+/* Define the types to use in the generated JNI C code and Java code */
+%typemap(jni) char *SBUF "jobject"
+%typemap(jtype) char *SBUF "StringBuffer"
+%typemap(jstype) char *SBUF "StringBuffer"
+
+/* How to convert Java(JNI) type to requested C type */
+%typemap(in) char *SBUF {
+
+  $1 = NULL;
+  if($input != NULL) {
+    /* Get the String from the StringBuffer */
+    jmethodID setLengthID;
+    jclass sbufClass = (*jenv)->GetObjectClass(jenv, $input);
+    jmethodID toStringID = (*jenv)->GetMethodID(jenv, sbufClass, "toString", "()Ljava/lang/String;");
+    jstring js = (jstring) (*jenv)->CallObjectMethod(jenv, $input, toStringID);
+
+    /* Convert the String to a C string */
+    const char *pCharStr = (*jenv)->GetStringUTFChars(jenv, js, 0);
+
+    /* Take a copy of the C string as the typemap is for a non const C string */
+    jmethodID capacityID = (*jenv)->GetMethodID(jenv, sbufClass, "capacity", "()I");
+    jint capacity = (*jenv)->CallIntMethod(jenv, $input, capacityID);
+    $1 = (char *) malloc(capacity+1);
+    strcpy($1, pCharStr);
+
+    /* Release the UTF string we obtained with GetStringUTFChars */
+    (*jenv)->ReleaseStringUTFChars(jenv,  js, pCharStr);
+
+    /* Zero the original StringBuffer, so we can replace it with the result */
+    setLengthID = (*jenv)->GetMethodID(jenv, sbufClass, "setLength", "(I)V");
+    (*jenv)->CallVoidMethod(jenv, $input, setLengthID, (jint) 0);
+  }
+}
+
+/* How to convert the C type to the Java(JNI) type */
+%typemap(argout) char *SBUF {
+
+  if($1 != NULL) {
+    /* Append the result to the empty StringBuffer */
+    jstring newString = (*jenv)->NewStringUTF(jenv, $1);
+    jclass sbufClass = (*jenv)->GetObjectClass(jenv, $input);
+    jmethodID appendStringID = (*jenv)->GetMethodID(jenv, sbufClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
+    (*jenv)->CallObjectMethod(jenv, $input, appendStringID, newString);
+
+    /* Clean up the string object, no longer needed */
+    free($1);
+    $1 = NULL;
+  }  
+}
+/* Prevent the default freearg typemap from being used */
+%typemap(freearg) char *SBUF ""
+
+/* Convert the jstype to jtype typemap type */
+%typemap(javain) char *SBUF "$javainput"
+
+/* apply the new typemap to our function */
+void f3(char *SBUF);
+
diff --git a/trunk/Examples/java/typemap/index.html b/trunk/Examples/java/typemap/index.html
new file mode 100644
index 0000000..486aa8e
--- /dev/null
+++ b/trunk/Examples/java/typemap/index.html
@@ -0,0 +1,32 @@
+<html>
+<head>
+<title>SWIG:Examples:java:typemap</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/java/typemap/</tt>
+<hr>
+
+<H2>Typemaps in Java</H2>
+
+<p>
+This example shows how typemaps can be used to modify the default behaviour of the Java SWIG module.
+
+<ul>
+<li><a href="example.i">example.i</a>. Interface file. 
+<li><a href="main.java">main.java</a>. Sample Java program.
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>Shows how to pass strings to Java from c and visa versa.
+<li>Typemaps can modify the default behaviour of the Java SWIG module.
+<li>The default c to java mapping can be modified using typemaps.
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/java/typemap/main.java b/trunk/Examples/java/typemap/main.java
new file mode 100644
index 0000000..bd9a4e1
--- /dev/null
+++ b/trunk/Examples/java/typemap/main.java
@@ -0,0 +1,26 @@
+
+public class main {
+
+  static {
+    try {
+	System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    String s = "brave new world";
+    example.f1(s);
+    System.out.println("f1(String): " + s);
+
+    byte b[] = new byte[25];
+    example.f2(b);
+    System.out.println("f2(byte[]): " + new String(b));
+
+    StringBuffer sb = new StringBuffer(20);
+    example.f3(sb);
+    System.out.println("f3(StringBuffer): " + sb);
+  }
+}
diff --git a/trunk/Examples/java/variables/Makefile b/trunk/Examples/java/variables/Makefile
new file mode 100644
index 0000000..968c92c
--- /dev/null
+++ b/trunk/Examples/java/variables/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::	java
+
+java::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java
+	javac *.java
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile java_clean
+
+check: all
diff --git a/trunk/Examples/java/variables/example.c b/trunk/Examples/java/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/java/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/java/variables/example.h b/trunk/Examples/java/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/java/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/java/variables/example.i b/trunk/Examples/java/variables/example.i
new file mode 100644
index 0000000..591b871
--- /dev/null
+++ b/trunk/Examples/java/variables/example.i
@@ -0,0 +1,49 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/java/variables/index.html b/trunk/Examples/java/variables/index.html
new file mode 100644
index 0000000..05aaa2d
--- /dev/null
+++ b/trunk/Examples/java/variables/index.html
@@ -0,0 +1,85 @@
+<html>
+<head>
+<title>SWIG:Examples:java:variables</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/java/variables/</tt>
+<hr>
+
+<H2>Wrapping C Global Variables</H2>
+
+<p>
+When a C global variable appears in an interface file, SWIG tries to
+wrap it using a technique known as "variable linking."  The idea is
+pretty simple---we try to create a Java variable that magically
+retrieves or updates the value of the underlying C variable when it is
+accessed.  Click <a href="example.i">here</a> to see a SWIG interface with some variable
+declarations in it.
+
+
+<p>Click <a href="../../../Doc/Manual/Java.html#global_variables">here</a> for the section on global variables in the SWIG and Java documentation.</p>
+<h2>Manipulating Variables from Java</h2>
+
+C variables are accessed through getters and setters from Java. Unfortunately this is the only way to get current values from variables because it is not possible to overload the dot operator in Java. All global variables are accessible from the module class. For example if the module class is called 'example', the global variable
+
+<blockquote>
+<pre>
+double foo;
+</pre>
+</blockquote>
+
+will be accessed in the Java module as
+<blockquote>
+<pre>
+example.get_foo();
+example.set_foo(12.3);
+</pre>
+</blockquote>
+
+Click <a href="main.java">here</a> to see the example program that updates and prints
+out the values of the variables using this technique.
+
+<h2>Key points</h2>
+
+<ul>
+<li>When a global variable has the type "<tt>char *</tt>", SWIG manages it as a character
+string.   However, whenever the value of such a variable is set from Java, the old
+value is destroyed using <tt>free()</tt> or <tt>delete</tt> (the choice of which depends
+on whether or not SWIG was run with the -c++ option).
+<li><tt>signed char</tt> and <tt>unsigned char</tt> are handled as small 8-bit integers.
+<li>String array variables such as '<tt>char name[256]</tt>' are managed as Java strings, but
+when setting the value, the result is truncated to the maximum length of the array.  Furthermore, the string is assumed to be null-terminated.
+<li>When structures and classes are used as global variables, they are mapped into pointers.
+Getting the "value" returns a pointer to the global variable.  Setting the value of a structure results in a memory copy from a pointer to the global.
+</ul>
+
+<h2>Creating read-only variables</h2>
+
+The <tt>%immutable</tt> and <tt>%mutable</tt> directives can be used to
+specify a collection of read-only variables.  For example:
+
+<blockquote>
+<pre>
+%immutable;
+int    status;
+double blah;
+...
+%mutable;
+</pre>
+</blockquote>
+
+The <tt>%immutable</tt> directive remains in effect until it is explicitly disabled
+using the <tt>%mutable</tt> directive.
+
+<h2>Comments</h2>
+<ul>
+<li>Management of global variables is one of the most problematic aspects 
+of C/C++ wrapping because the Java interface and resulting memory management
+is much trickier than simply creating a wrapper function.
+</ul>
+
+</body>
+</html>
+<hr>
diff --git a/trunk/Examples/java/variables/main.java b/trunk/Examples/java/variables/main.java
new file mode 100644
index 0000000..92745db
--- /dev/null
+++ b/trunk/Examples/java/variables/main.java
@@ -0,0 +1,97 @@
+// This example illustrates global variable access from Java.
+
+import java.lang.reflect.*;
+
+public class main {
+  static {
+    try {
+        System.loadLibrary("example");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+// Try to set the values of some global variables
+
+    example.setIvar(42);
+    example.setSvar((short)-31000);
+    example.setLvar(65537);
+    example.setUivar(123456);
+    example.setUsvar(61000);
+    example.setUlvar(654321);
+    example.setScvar((byte)-13);
+    example.setUcvar((short)251);
+    example.setCvar('S');
+    example.setFvar((float)3.14159);
+    example.setDvar(2.1828);
+    example.setStrvar("Hello World");
+    example.setIptrvar(example.new_int(37));
+    example.setPtptr(example.new_Point(37,42));
+    example.setName("Bill");
+
+    // Now print out the values of the variables
+
+    System.out.println( "Variables (values printed from Java)" );
+
+    System.out.println( "ivar      =" + example.getIvar() );
+    System.out.println( "svar      =" + example.getSvar() );
+    System.out.println( "lvar      =" + example.getLvar() );
+    System.out.println( "uivar     =" + example.getUivar() );
+    System.out.println( "usvar     =" + example.getUsvar() );
+    System.out.println( "ulvar     =" + example.getUlvar() );
+    System.out.println( "scvar     =" + example.getScvar() );
+    System.out.println( "ucvar     =" + example.getUcvar() );
+    System.out.println( "fvar      =" + example.getFvar() );
+    System.out.println( "dvar      =" + example.getDvar() );
+    System.out.println( "cvar      =" + (char)example.getCvar() );
+    System.out.println( "strvar    =" + example.getStrvar() );
+    System.out.println( "cstrvar   =" + example.getCstrvar() );
+    System.out.println( "iptrvar   =" + Long.toHexString(SWIGTYPE_p_int.getCPtr(example.getIptrvar())) );
+    System.out.println( "name      =" + example.getName() );
+    System.out.println( "ptptr     =" + Long.toHexString(SWIGTYPE_p_Point.getCPtr(example.getPtptr())) + example.Point_print(example.getPtptr()) );
+    System.out.println( "pt        =" + Long.toHexString(SWIGTYPE_p_Point.getCPtr(example.getPt())) + example.Point_print(example.getPt()) );
+
+    System.out.println( "\nVariables (values printed from C)" );
+
+    example.print_vars();
+
+    System.out.println( "\nNow I'm going to try and modify some read only variables" );
+
+    System.out.println( "     Trying to set 'path'" );
+    try {
+        Method m = example.class.getDeclaredMethod("setPath", new Class[] {String.class});
+        m.invoke(example.class, new Object[] {"Whoa!"} );
+        System.out.println( "Hey, what's going on?!?! This shouldn't work" );
+    }
+    catch (NoSuchMethodException e) {
+        System.out.println( "Good." );
+    }
+    catch (Throwable t) {
+        System.out.println( "You shouldn't see this!" );
+    }
+
+    System.out.println( "     Trying to set 'status'" );
+    try {
+        Method m = example.class.getDeclaredMethod("setStatus", new Class[] {Integer.class});
+        m.invoke(example.class, new Object[] {new Integer(0)} );
+        System.out.println( "Hey, what's going on?!?! This shouldn't work" );
+    }
+    catch (NoSuchMethodException e) {
+        System.out.println( "Good." );
+    }
+    catch (Throwable t) {
+        System.out.println( "You shouldn't see this!" );
+    }
+
+    System.out.println( "\nI'm going to try and update a structure variable.\n" );
+
+    example.setPt(example.getPtptr());
+
+    System.out.println( "The new value is" );
+    example.pt_print();
+    System.out.println( "You should see the value" + example.Point_print(example.getPtptr()) );
+  }
+}
diff --git a/trunk/Examples/lua/arrays/Makefile b/trunk/Examples/lua/arrays/Makefile
new file mode 100644
index 0000000..bb9cf0b
--- /dev/null
+++ b/trunk/Examples/lua/arrays/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..

+SWIG       = $(TOP)/../preinst-swig

+SRCS       = example.c

+TARGET     = example

+INTERFACE  = example.i

+

+all::

+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \

+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua

+

+static::

+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \

+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static

+

+clean::

+	$(MAKE) -f $(TOP)/Makefile lua_clean

+

+check: all

diff --git a/trunk/Examples/lua/arrays/example.c b/trunk/Examples/lua/arrays/example.c
new file mode 100644
index 0000000..56c7b19
--- /dev/null
+++ b/trunk/Examples/lua/arrays/example.c
@@ -0,0 +1,25 @@
+/* File : example.c */

+

+#include <stdlib.h>

+

+/* we are using the qsort function, which needs a helper function to sort */

+int compare_int(const void * a, const void * b)

+{

+  return ( *(int*)a - *(int*)b );

+}

+

+void sort_int(int* arr, int len)

+{

+  qsort(arr, len, sizeof(int), compare_int);

+}

+

+// ditto doubles

+int compare_double(const void * a, const void * b)

+{

+  return (int)( *(double*)a - *(double*)b );

+}

+

+void sort_double(double* arr, int len)

+{

+  qsort(arr, len, sizeof(double), compare_double);

+}

diff --git a/trunk/Examples/lua/arrays/example.i b/trunk/Examples/lua/arrays/example.i
new file mode 100644
index 0000000..197a5a2
--- /dev/null
+++ b/trunk/Examples/lua/arrays/example.i
@@ -0,0 +1,42 @@
+/* File : example.i */

+%module example

+

+/* in this file there are two sorting functions

+and three different ways to wrap them.

+

+See the lua code for how they are called

+*/

+

+%include <carrays.i>    // array helpers

+

+// this declares a batch of function for manipulating C integer arrays

+%array_functions(int,int)

+

+// this adds some lua code directly into the module

+// warning: you need the example. prefix if you want it added into the module

+// addmittedly this code is a bit tedious, but its a one off effort

+%luacode {

+function example.sort_int2(t)

+ local len=table.maxn(t) -- the len

+ local arr=example.new_int(len)

+ for i=1,len do

+  example.int_setitem(arr,i-1,t[i]) -- note: C index is one less then lua indea

+ end

+ example.sort_int(arr,len) -- call the fn

+ -- copy back

+ for i=1,len do

+  t[i]=example.int_getitem(arr,i-1) -- note: C index is one less then lua indea

+ end

+ example.delete_int(arr) -- must delete it

+end

+}

+

+// this way uses the SWIG-Lua typemaps to do the conversion for us

+// the %apply command states to apply this wherever the argument signature matches

+%include <typemaps.i>

+%apply (double *INOUT,int) {(double* arr,int len)};

+

+%inline %{

+extern void sort_int(int* arr, int len);

+extern void sort_double(double* arr, int len);

+%}
\ No newline at end of file
diff --git a/trunk/Examples/lua/arrays/runme.lua b/trunk/Examples/lua/arrays/runme.lua
new file mode 100644
index 0000000..b0f5cfc
--- /dev/null
+++ b/trunk/Examples/lua/arrays/runme.lua
@@ -0,0 +1,74 @@
+---- importing ----

+if string.sub(_VERSION,1,7)=='Lua 5.0' then

+	-- lua5.0 doesnt have a nice way to do this

+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')

+	assert(lib)()

+else

+	-- lua 5.1 does

+	require('example')

+end

+

+-- a helper to print a Lua table

+function print_table(t)

+    print(table.concat(t,","))

+end

+

+-- a helper to print a C array

+function print_array(arr,len)

+    for i=0,len-1 do

+        io.write(example.int_getitem(arr,i),",")

+    end

+    io.write("\n")

+end

+

+math.randomseed(0)  -- init random

+

+

+--[[ version 1: passing a C array to the code

+lets test call sort_int()

+this requires a C array, so is the hardest to use]]

+ARRAY_SIZE=10

+arr=example.new_int(ARRAY_SIZE)

+for i=0,ARRAY_SIZE-1 do

+    example.int_setitem(arr,i,math.random(1000))

+end

+print "unsorted"

+print_array(arr,ARRAY_SIZE)

+example.sort_int(arr,ARRAY_SIZE)

+print "sorted"

+print_array(arr,ARRAY_SIZE)

+example.delete_int(arr) -- must delete it

+print ""

+

+--[[ version 2: using %luacode to write a helper

+a simpler way is to use a %luacode

+which is a lua function added into the module

+this can do the conversion for us

+so we can just add a lua table directly

+(what we do is move the lua code into the module instead)

+]]

+t={}

+for i=1,ARRAY_SIZE do

+    t[i]=math.random(1000)

+end

+print "unsorted"

+print_table(t)

+example.sort_int2(t) -- calls lua helper which then calls C

+print "sorted"

+print_table(t)

+print ""

+

+--[[ version 3: use a typemap

+this is the best way

+it uses the SWIG-Lua typemaps to do the work

+one item of note: the typemap creates a copy, rather than edit-in-place]]

+t={}

+for i=1,ARRAY_SIZE do

+    t[i]=math.random(1000)/10

+end

+print "unsorted"

+print_table(t)

+t=example.sort_double(t) -- replace t with the result

+print "sorted"

+print_table(t)

+

diff --git a/trunk/Examples/lua/check.list b/trunk/Examples/lua/check.list
new file mode 100644
index 0000000..6862e44
--- /dev/null
+++ b/trunk/Examples/lua/check.list
@@ -0,0 +1,17 @@
+# see top-level Makefile.in
+arrays
+class
+constants
+dual
+embed
+embed2
+embed3
+exception
+funcptr3
+functest
+functor
+import
+owner
+pointer
+simple
+variables
diff --git a/trunk/Examples/lua/class/Makefile b/trunk/Examples/lua/class/Makefile
new file mode 100644
index 0000000..44888f6
--- /dev/null
+++ b/trunk/Examples/lua/class/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/class/example.cxx b/trunk/Examples/lua/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/lua/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/lua/class/example.h b/trunk/Examples/lua/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/lua/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/lua/class/example.i b/trunk/Examples/lua/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/lua/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/lua/class/runme.lua b/trunk/Examples/lua/class/runme.lua
new file mode 100644
index 0000000..2c3ad8c
--- /dev/null
+++ b/trunk/Examples/lua/class/runme.lua
@@ -0,0 +1,62 @@
+-- file: runme.lua
+
+-- This file illustrates class C++ interface generated
+-- by SWIG.
+
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+----- Object creation -----
+
+print("Creating some objects:")
+c = example.Circle(10)
+print("    Created circle", c)
+s = example.Square(10)
+print("    Created square", s)
+
+----- Access a static member -----
+
+print("\nA total of",example.Shape_nshapes,"shapes were created")
+
+----- Member data access -----
+
+-- Set the location of the object
+
+c.x = 20
+c.y = 30
+
+s.x = -10
+s.y = 5
+
+print("\nHere is their current position:")
+print(string.format("    Circle = (%f, %f)",c.x,c.y))
+print(string.format("    Square = (%f, %f)",s.x,s.y))
+
+----- Call some methods -----
+
+print("\nHere are some properties of the shapes:")
+for _,o in pairs({c,s}) do
+      print("   ", o)
+      print("        area      = ", o:area())
+      print("        perimeter = ", o:perimeter())
+end
+
+print("\nGuess I'll clean up now")
+
+-- Note: this invokes the virtual destructor
+c=nil
+s=nil
+s = 3
+
+-- call gc to make sure they are collected
+collectgarbage()
+
+print(example.Shape_nshapes,"shapes remain")
+print "Goodbye"
diff --git a/trunk/Examples/lua/constants/Makefile b/trunk/Examples/lua/constants/Makefile
new file mode 100644
index 0000000..4204545
--- /dev/null
+++ b/trunk/Examples/lua/constants/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/constants/example.i b/trunk/Examples/lua/constants/example.i
new file mode 100644
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/lua/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/lua/constants/runme.lua b/trunk/Examples/lua/constants/runme.lua
new file mode 100644
index 0000000..751e7d6
--- /dev/null
+++ b/trunk/Examples/lua/constants/runme.lua
@@ -0,0 +1,35 @@
+-- file: example.lua
+
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+print("ICONST  = "..example.ICONST.." (should be 42)")
+print("FCONST  = "..example.FCONST.." (should be 2.1828)")
+print("CCONST  = "..example.CCONST.." (should be 'x')")
+print("CCONST2 = "..example.CCONST2.." (this should be on a new line)")
+print("SCONST  = "..example.SCONST.." (should be 'Hello World')")
+print("SCONST2 = "..example.SCONST2.." (should be '\"Hello World\"')")
+print("EXPR    = "..example.EXPR.." (should be 48.5484)")
+print("iconst  = "..example.iconst.." (should be 37)")
+print("fconst  = "..example.fconst.." (should be 3.14)")
+
+-- helper to check that a fn failed
+function checkfail(fn)
+	if pcall(fn)==true then
+		print("that shouldn't happen, it worked")
+	else
+		print("function failed as expected")
+	end
+end
+
+-- these should fail
+-- example.EXTERN is a nil value, so concatentatin will make it fail
+checkfail(function() print("EXTERN = "..example.EXTERN) end)
+checkfail(function() print("FOO = "..example.FOO) end)
diff --git a/trunk/Examples/lua/dual/Makefile b/trunk/Examples/lua/dual/Makefile
new file mode 100644
index 0000000..b4e28f3
--- /dev/null
+++ b/trunk/Examples/lua/dual/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+TARGET     = dual
+CXXSRCS    = example2_wrap.cxx
+INTERFACE  = dual.i
+LUA_INTERP = dual.cpp
+
+# This is a little different to normal as we need to static link two modules and a custom interpreter
+# We need the external runtime, then swig examples2, and build the module as normal
+all::
+	$(SWIG) -lua -external-runtime
+	$(SWIG) -c++ -lua $(SWIGOPT) example2.i
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+	rm -f swigluarun.h
+
+check: all
+
diff --git a/trunk/Examples/lua/dual/dual.cpp b/trunk/Examples/lua/dual/dual.cpp
new file mode 100644
index 0000000..d2a9eca
--- /dev/null
+++ b/trunk/Examples/lua/dual/dual.cpp
@@ -0,0 +1,109 @@
+/*
+dual.cpp a test for multiple modules and multiple intrepreters staticly linked together.
+
+Earlier version of lua bindings for SWIG would fail if staticly linked.
+
+What is happening is as follows:
+example.i declares a type Foo
+examples2.i declares Bar
+
+The first lua state will load example.i 
+and check to see if types Foo and Bar are registered with it
+(Foo should be & Bar should not)
+
+The second lua state will load example2.i
+and check to see if types Foo and Bar are registered with it
+(Bar should be & Foo should not)
+
+Note: Though both the modules exist and are loaded, they are not linked together,
+as they are connected to seperate lua interpreters.
+
+When the third lua state loads both example.i and example2.i,
+the two modules are now linked together, and all can now find
+both Foo and Bar.
+*/
+
+#include "swigluarun.h"	// the swig runtimes
+
+#include <stdio.h>
+#include <stdlib.h>
+
+// the 2 libraries which are wrappered via SWIG
+extern "C" int luaopen_example(lua_State*L);
+extern "C" int luaopen_example2(lua_State*L);
+
+#define DEBUG(X) {printf(X);fflush(stdout);}
+#define DEBUG2(X,Y) {printf(X,Y);fflush(stdout);}
+#define DEBUG3(X,Y,Z) {printf(X,Y,Z);fflush(stdout);}
+
+void testModule(lua_State *L)
+{
+  swig_type_info *pTypeInfo=0,*pTypeInfo2=0;
+  swig_module_info *pModule=0;
+  pModule=SWIG_GetModule(L);
+  DEBUG2("  SWIG_GetModule() returns %p\n",pModule)
+  if(pModule==0) return;
+  pTypeInfo = SWIG_TypeQuery(L,"Foo *");
+  DEBUG2("  Type (Foo*) is %s\n",pTypeInfo==0?"unknown":"known");
+  DEBUG3("    Module %p typeinfo(Foo*) %p\n",pModule,pTypeInfo);
+  pTypeInfo2 = SWIG_TypeQuery(L,"Bar *");
+  DEBUG2("  Type (Bar*) is %s\n",pTypeInfo2==0?"unknown":"known");
+  DEBUG3("    Module %p typeinfo(Bar*) %p\n",pModule,pTypeInfo2);
+}
+
+int main(int argc,char* argv[])
+{
+  lua_State *L1=0,*L2=0,*L3=0;
+
+  printf("This is a test of having two SWIG'ed modules and three lua states\n"
+	"statically linked together.\n"
+	"Its mainly to check that all the types are correctly managed\n\n");
+	
+  DEBUG("creating lua states(L1,L2,L3)");
+  L1=lua_open();
+  L2=lua_open();
+  L3=lua_open();
+  DEBUG("ok\n\n");
+
+  DEBUG("luaopen_example(L1)..");
+  luaopen_example(L1);
+  DEBUG("ok\n");
+	
+  DEBUG("Testing Module L1\n");
+  DEBUG("This module should know about Foo* but not Bar*\n");
+  testModule(L1);
+  DEBUG("End Testing Module L1\n\n");
+
+  DEBUG("luaopen_example2(L2)..");
+  luaopen_example2(L2);
+  DEBUG("ok\n");
+	
+  DEBUG("Testing Module L2\n");
+  DEBUG("This module should know about Bar* but not Foo*\n");
+  testModule(L2);
+  DEBUG("End Testing Module L2\n\n");
+
+  DEBUG("luaopen_example(L3)..");
+  luaopen_example(L3);
+  DEBUG("ok\n");
+  DEBUG("luaopen_example2(L3)..");
+  luaopen_example2(L3);
+  DEBUG("ok\n");
+
+  DEBUG("Testing Module L3\n");
+  DEBUG("This module should know about Foo* and Bar*\n");
+  testModule(L3);
+  DEBUG("End Testing Module L3\n\n");
+
+  DEBUG("Testing Module L1 again\n");
+  DEBUG("It now should know about Foo* and Bar*\n");
+  testModule(L1);
+  DEBUG("End Testing Module L1 again\n\n");
+
+  DEBUG("close all..");
+  lua_close(L1);
+  lua_close(L2);
+  lua_close(L3);
+  DEBUG("ok, exiting\n");
+  return 0;
+}
diff --git a/trunk/Examples/lua/dual/example.i b/trunk/Examples/lua/dual/example.i
new file mode 100644
index 0000000..5e573dd
--- /dev/null
+++ b/trunk/Examples/lua/dual/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%inline %{
+
+struct Foo{
+  int i;
+};             
+
+%}
diff --git a/trunk/Examples/lua/dual/example2.i b/trunk/Examples/lua/dual/example2.i
new file mode 100644
index 0000000..9449664
--- /dev/null
+++ b/trunk/Examples/lua/dual/example2.i
@@ -0,0 +1,10 @@
+/* File : example2.i */
+%module example2
+
+%inline %{
+
+struct Bar{
+  int i;
+};
+
+%}
diff --git a/trunk/Examples/lua/embed/Makefile b/trunk/Examples/lua/embed/Makefile
new file mode 100644
index 0000000..51d0e61
--- /dev/null
+++ b/trunk/Examples/lua/embed/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+TARGET     = embed
+SRCS      = example.c
+INTERFACE  = example.i
+LUA_INTERP = embed.c
+
+# this is a little different to normal as we have our own special interpreter
+# which we want to static link
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
+
diff --git a/trunk/Examples/lua/embed/embed.c b/trunk/Examples/lua/embed/embed.c
new file mode 100644
index 0000000..55ea099
--- /dev/null
+++ b/trunk/Examples/lua/embed/embed.c
@@ -0,0 +1,85 @@
+/* embed.c a simple test for an embeded interpreter

+ 

+The idea is that we wrapper a few simple function (example.c)

+and write our own app to call it.

+ 

+What it will do is load the wrappered lib, load runme.lua and then call some functions.

+To make life easier, all the printf's have either [C] or [Lua] at the start

+so you can see where they are coming from.

+ 

+We will be using the luaL_dostring()/lua_dostring() function to call into lua 

+ 

+*/

+

+#include <stdlib.h>

+#include <stdio.h>

+

+#include <lua.h>

+#include <lauxlib.h>

+#include <lualib.h>

+

+/* the SWIG wrappered library */

+extern int luaopen_example(lua_State*L);

+

+/* a really simple way of calling lua from C

+ just give it a lua state & a string to execute

+Unfortunately lua keeps changing its API's.

+In lua 5.0.X its lua_dostring()

+In lua 5.1.X its luaL_dostring()

+so we have a few extra compiles

+*/

+int dostring(lua_State *L, char* str) {

+  int ok;

+#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501))

+

+  ok=luaL_dostring(L,str);	/* looks like this is lua 5.1.X or later, good */

+#else

+

+  ok=lua_dostring(L,str);	/* might be lua 5.0.x, using lua_dostring */

+#endif

+

+  if (ok!=0)

+    printf("[C] ERROR in dostring: %s\n",lua_tostring(L,-1));

+  return ok;

+}

+

+

+int main(int argc,char* argv[]) {

+  lua_State *L;

+  int ok;

+  printf("[C] Welcome to the simple embedded lua example\n");

+  printf("[C] We are in C\n");

+  printf("[C] opening a lua state & loading the libraries\n");

+  L=lua_open();

+  luaopen_base(L);

+  luaopen_string(L);

+  luaopen_math(L);

+  printf("[C] now loading the SWIG wrappered library\n");

+  luaopen_example(L);

+  printf("[C] all looks ok\n");

+  printf("\n");

+  printf("[C] lets load the file 'runme.lua'\n");

+  printf("[C] any lua code in this file will be executed\n");

+  if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {

+    printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));

+    exit(3);

+  }

+  printf("[C] We are now back in C, all looks ok\n");

+  printf("\n");

+  printf("[C] lets call the function 'do_tests()'\n");

+  ok=dostring(L,"do_tests()");

+  printf("[C] We are back in C, the dostring() function returned %d\n",ok);

+  printf("\n");

+  printf("[C] Lets call lua again, but create an error\n");

+  ok=dostring(L,"no_such_function()");

+  printf("[C] We are back in C, the dostring() function returned %d\n",ok);

+  printf("[C] it should also have returned 1 and printed an error message\n");

+  printf("\n");

+  printf("[C] Lets call lua again, calling the greeting function\n");

+  ok=dostring(L,"call_greeting()");

+  printf("[C] This was C=>Lua=>C (getting a bit complex)\n");

+  printf("\n");

+  printf("[C] all finished, closing the lua state\n");

+  lua_close(L);

+  return 0;

+}

diff --git a/trunk/Examples/lua/embed/example.c b/trunk/Examples/lua/embed/example.c
new file mode 100644
index 0000000..c6c6d7b
--- /dev/null
+++ b/trunk/Examples/lua/embed/example.c
@@ -0,0 +1,22 @@
+/* File : example.c */

+

+#include <stdio.h>

+

+/* A global variable */

+double Foo = 3.0;

+

+/* Compute the greatest common divisor of positive integers */

+int gcd(int x, int y) {

+  int g;

+  g = y;

+  while (x > 0) {

+    g = x;

+    x = y % x;

+    y = g;

+  }

+  return g;

+}

+

+void greeting() {

+  printf("Hello from the C function 'greeting'\n");

+}

diff --git a/trunk/Examples/lua/embed/example.i b/trunk/Examples/lua/embed/example.i
new file mode 100644
index 0000000..7784b8e
--- /dev/null
+++ b/trunk/Examples/lua/embed/example.i
@@ -0,0 +1,8 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+extern void greeting();
+%}
\ No newline at end of file
diff --git a/trunk/Examples/lua/embed/runme.lua b/trunk/Examples/lua/embed/runme.lua
new file mode 100644
index 0000000..e02fd1d
--- /dev/null
+++ b/trunk/Examples/lua/embed/runme.lua
@@ -0,0 +1,40 @@
+print "[lua] This is runme.lua"
+-- test program for embeded lua
+-- we do not need to load the library, as it was already in the intrepreter
+-- but lets check anyway
+assert(type(example)=='table',"Don't appear to have loaded the example module")
+
+-- a test function to run the tests
+function do_tests()
+	print("[lua] We are now in Lua, inside the do_tests() function")
+	print("[lua] We will be calling example.gcd() and changing example.Foo")
+	-- Call our gcd() function
+	x = 42
+	y = 105
+	g = example.gcd(x,y)
+	print("[lua] The gcd of",x,"and",y,"is",g)
+
+	-- Manipulate the Foo global variable
+
+	-- Output its current value
+	print("[lua] Foo = ", example.Foo)
+
+	-- Change its value
+	example.Foo = 3.1415926
+
+	-- See if the change took effect
+	print("[lua] Foo = ", example.Foo)
+	print("[lua] ending the do_tests() function")
+end
+
+function call_greeting()
+	print("[lua] We are now in Lua, inside the call_greeting() function")
+	example.greeting()
+	print("[lua] ending the call_greeting() function")
+end
+
+
+
+
+
+
diff --git a/trunk/Examples/lua/embed2/Makefile b/trunk/Examples/lua/embed2/Makefile
new file mode 100644
index 0000000..5f267d9
--- /dev/null
+++ b/trunk/Examples/lua/embed2/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+TARGET     = embed2
+SRCS      = example.c
+INTERFACE  = example.i
+LUA_INTERP = embed2.c
+
+# this is a little different to normal as we have our own special interpreter
+# which we want to static link
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
+
diff --git a/trunk/Examples/lua/embed2/embed2.c b/trunk/Examples/lua/embed2/embed2.c
new file mode 100644
index 0000000..dac527e
--- /dev/null
+++ b/trunk/Examples/lua/embed2/embed2.c
@@ -0,0 +1,233 @@
+/* embed2.c some more test for an embeded interpreter

+ 

+This will go a bit further as it will pass values to and from the lua code.

+It uses less of the SWIG code, and more of the raw lua API's

+ 

+What it will do is load the wrappered lib, load runme.lua and then call some functions.

+To make life easier, all the printf's have either [C] or [Lua] at the start

+so you can see where they are coming from.

+ 

+We will be using the luaL_dostring()/lua_dostring() function to call into lua 

+ 

+*/

+

+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */

+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)

+# define _CRT_SECURE_NO_DEPRECATE

+#endif

+

+/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */

+#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)

+# define _SCL_SECURE_NO_DEPRECATE

+#endif

+

+

+#include <stdlib.h>

+#include <stdio.h>

+

+#include <lua.h>

+#include <lauxlib.h>

+#include <lualib.h>

+#include <stdarg.h>

+#include <string.h>

+

+

+/* the SWIG wrappered library */

+extern int luaopen_example(lua_State*L);

+

+/* This is an example of how to call the Lua function

+    int add(int,int) 

+  its very tedious, but gives you an idea of the issues involded.

+  (look below for a better idea)

+*/

+int call_add(lua_State *L,int a,int b,int* res) {

+  int top;

+  /* ok, here we go:

+  push a, push b, call 'add' check & return res

+  */

+  top=lua_gettop(L);  /* for later */

+  lua_pushstring(L, "add");                                  /* function name */

+  lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */

+  if (!lua_isfunction(L,-1)) {

+    printf("[C] error: cannot find function 'add'\n");

+    lua_settop(L,top);  // reset

+    return 0;

+  }

+  lua_pushnumber(L,a);

+  lua_pushnumber(L,b);

+  if (lua_pcall(L, 2, 1, 0) != 0)  /* call function with 2 arguments and 1 result */

+  {

+    printf("[C] error running function `add': %s\n",lua_tostring(L, -1));

+    lua_settop(L,top);  // reset

+    return 0;

+  }

+  // check results

+  if (!lua_isnumber(L,-1)) {

+    printf("[C] error: returned value is not a number\n");

+    lua_settop(L,top);  // reset

+    return 0;

+  }

+  *res=(int)lua_tonumber(L,-1);

+  lua_settop(L,top);  /* reset stack */

+  return 1;   // ok

+}

+

+/* This is a variargs call function for calling from C into Lua.

+Original Code from Programming in Lua (PIL) by Roberto Ierusalimschy

+ISBN 85-903798-1-7 

+http://www.lua.org/pil/25.3.html

+This has been modified slightly to make it compile, and its still a bit rough.

+But it gives the idea of how to make it work.

+*/

+int call_va (lua_State *L,const char *func, const char *sig, ...) {

+  va_list vl;

+  int narg, nres;  /* number of arguments and results */

+  int top;

+  top=lua_gettop(L);  /* for later */

+

+  va_start(vl, sig);

+  lua_getglobal(L, func);  /* get function */

+

+  /* push arguments */

+  narg = 0;

+  while (*sig) {  /* push arguments */

+    switch (*sig++) {

+

+    case 'd':  /* double argument */

+      lua_pushnumber(L, va_arg(vl, double));

+      break;

+

+    case 'i':  /* int argument */

+      lua_pushnumber(L, va_arg(vl, int));

+      break;

+

+    case 's':  /* string argument */

+      lua_pushstring(L, va_arg(vl, char *));

+      break;

+

+    case '>':

+      goto endwhile;

+

+    default:

+      printf("invalid option (%c)\n", *(sig - 1));

+      goto fail;

+    }

+    narg++;

+    /* do we need this?*/

+    /* luaL_checkstack(L, 1, "too many arguments"); */

+  }

+endwhile:

+

+  /* do the call */

+  nres = (int)strlen(sig);  /* number of expected results */

+  if (lua_pcall(L, narg, nres, 0) != 0)  /* do the call */

+  {

+    printf("error running function `%s': %s\n",func, lua_tostring(L, -1));

+    goto fail;

+  }

+

+  /* retrieve results */

+  nres = -nres;  /* stack index of first result */

+  while (*sig) {  /* get results */

+    switch (*sig++) {

+

+    case 'd':  /* double result */

+      if (!lua_isnumber(L, nres)) {

+        printf("wrong result type\n");

+        goto fail;

+      }

+      *va_arg(vl, double *) = lua_tonumber(L, nres);

+      break;

+

+    case 'i':  /* int result */

+      if (!lua_isnumber(L, nres)) {

+        printf("wrong result type\n");

+        goto fail;

+      }

+      *va_arg(vl, int *) = (int)lua_tonumber(L, nres);

+      break;

+

+    case 's':  /* string result */

+      if (!lua_isstring(L, nres)) {

+        printf("wrong result type\n");

+        goto fail;

+      }

+      strcpy(va_arg(vl, char *),lua_tostring(L, nres));/* WARNING possible buffer overflow */

+      break;

+

+    default: {

+        printf("invalid option (%c)", *(sig - 1));

+        goto fail;

+      }

+    }

+    nres++;

+  }

+  va_end(vl);

+

+  lua_settop(L,top);  /* reset stack */

+  return 1; /* ok */

+fail:

+  lua_settop(L,top);  /* reset stack */

+  return 0;   /* error */

+}

+

+int main(int argc,char* argv[]) {

+  lua_State *L;

+  int ok;

+  int res;

+  char str[80];

+  printf("[C] Welcome to the simple embedded Lua example v2\n");

+  printf("[C] We are in C\n");

+  printf("[C] opening a Lua state & loading the libraries\n");

+  L=lua_open();

+  luaopen_base(L);

+  luaopen_string(L);

+  luaopen_math(L);

+  printf("[C] now loading the SWIG wrappered library\n");

+  luaopen_example(L);

+  printf("[C] all looks ok\n");

+  printf("\n");

+  printf("[C] lets load the file 'runme.lua'\n");

+  printf("[C] any lua code in this file will be executed\n");

+  if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {

+    printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));

+    exit(3);

+  }

+  printf("[C] We are now back in C, all looks ok\n");

+  printf("\n");

+  printf("[C] lets call the Lua function 'add(1,1)'\n");

+  printf("[C] using the C function 'call_add'\n");

+  ok=call_add(L,1,1,&res);

+  printf("[C] the function returned %d with value %d\n",ok,res);

+  printf("\n");

+  printf("[C] lets do this rather easier\n");

+  printf("[C] we will call the same Lua function using a generic C function 'call_va'\n");

+  ok=call_va(L,"add","ii>i",1,1,&res);

+  printf("[C] the function returned %d with value %d\n",ok,res);

+  printf("\n");

+  printf("[C] we will now use the same generic C function to call 'append(\"cat\",\"dog\")'\n");

+  ok=call_va(L,"append","ss>s","cat","dog",str);

+  printf("[C] the function returned %d with value %s\n",ok,str);

+  printf("\n");

+  printf("[C] we can also make some bad calls to ensure the code doesn't fail\n");

+  printf("[C] calling adds(1,2)\n");

+  ok=call_va(L,"adds","ii>i",1,2,&res);

+  printf("[C] the function returned %d with value %d\n",ok,res);

+  printf("[C] calling add(1,'fred')\n");

+  ok=call_va(L,"add","is>i",1,"fred",&res);

+  printf("[C] the function returned %d with value %d\n",ok,res);

+  printf("\n");

+  printf("[C] Note: no protection if you mess up the va-args, this is C\n");

+  printf("\n");

+  printf("[C] Finally we will call the wrappered gcd function gdc(6,9):\n");

+  printf("[C] This will pass the values to Lua, then call the wrappered function\n");

+  printf("    Which will get the values from Lua, call the C code \n");

+  printf("    and return the value to Lua and eventually back to C\n");

+  printf("[C] Certainly not the best way to do it :-)\n");

+  ok=call_va(L,"gcd","ii>i",6,9,&res);

+  printf("[C] the function returned %d with value %d\n",ok,res);

+  printf("\n");

+  printf("[C] all finished, closing the lua state\n");

+  lua_close(L);

+  return 0;

+}

diff --git a/trunk/Examples/lua/embed2/example.c b/trunk/Examples/lua/embed2/example.c
new file mode 100644
index 0000000..c6c6d7b
--- /dev/null
+++ b/trunk/Examples/lua/embed2/example.c
@@ -0,0 +1,22 @@
+/* File : example.c */

+

+#include <stdio.h>

+

+/* A global variable */

+double Foo = 3.0;

+

+/* Compute the greatest common divisor of positive integers */

+int gcd(int x, int y) {

+  int g;

+  g = y;

+  while (x > 0) {

+    g = x;

+    x = y % x;

+    y = g;

+  }

+  return g;

+}

+

+void greeting() {

+  printf("Hello from the C function 'greeting'\n");

+}

diff --git a/trunk/Examples/lua/embed2/example.i b/trunk/Examples/lua/embed2/example.i
new file mode 100644
index 0000000..7784b8e
--- /dev/null
+++ b/trunk/Examples/lua/embed2/example.i
@@ -0,0 +1,8 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+extern void greeting();
+%}
\ No newline at end of file
diff --git a/trunk/Examples/lua/embed2/runme.lua b/trunk/Examples/lua/embed2/runme.lua
new file mode 100644
index 0000000..73af9c5
--- /dev/null
+++ b/trunk/Examples/lua/embed2/runme.lua
@@ -0,0 +1,27 @@
+print "[lua] This is runme.lua"
+-- test program for embeded lua
+-- we do not need to load the library, as it was already in the intrepreter
+-- but lets check anyway
+assert(type(example)=='table',"Don't appear to have loaded the example module")
+

+-- note: we will copy the functions from example table into global

+-- this will help us later

+for k,v in pairs(example) do _G[k]=v end

+
+-- our add function

+-- we will be calling this from C
+function add(a,b)

+    print("[lua] this is function add(",a,b,")")

+    c=a+b

+    print("[lua] returning",c)

+    return c

+end
+
+function append(a,b)

+    print("[lua] this is function append(",a,b,")")

+    c=a..b

+    print("[lua] returning",c)

+    return c

+end
+
+
diff --git a/trunk/Examples/lua/embed3/Makefile b/trunk/Examples/lua/embed3/Makefile
new file mode 100644
index 0000000..def3528
--- /dev/null
+++ b/trunk/Examples/lua/embed3/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+TARGET     = embed3
+SRCS      = example.cpp
+INTERFACE  = example.i
+LUA_INTERP = embed3.cpp
+
+# this is a little different to normal as we have our own special interpreter
+# which we want to static link
+# we also need the external runtime, so we can get access to certain internals of SWIG
+all::
+	$(SWIG) -c++ -lua $(SWIGOPT) -external-runtime swigluarun.h
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
+
diff --git a/trunk/Examples/lua/embed3/embed3.cpp b/trunk/Examples/lua/embed3/embed3.cpp
new file mode 100644
index 0000000..c2424f9
--- /dev/null
+++ b/trunk/Examples/lua/embed3/embed3.cpp
@@ -0,0 +1,141 @@
+/* embed3.cpp A C++ embeded interpreter
+ 
+This will register a C++ class with Lua, and then call a Lua function
+passing C++ objects to this function.
+ 
+*/
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
+#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
+# define _SCL_SECURE_NO_DEPRECATE
+#endif
+
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+
+extern "C" {
+#include <lua.h>
+#include <lauxlib.h>
+#include <lualib.h>
+}
+
+#include "swigluarun.h"   // the SWIG external runtime
+
+/* the SWIG wrappered library */
+extern "C" int luaopen_example(lua_State*L);
+
+// the code itself
+#include "example.h"
+
+// this code pushes a C++ pointer as well as the SWIG type onto the Lua stack
+bool push_pointer(lua_State*L, void* ptr, const char* type_name, int owned = 0) {
+  // task 1: get the object 'type' which is registered with SWIG
+  // you need to call SWIG_TypeQuery() with the class name
+  // (normally, just look in the wrapper file to get this)
+  swig_type_info * pTypeInfo = SWIG_TypeQuery(L, type_name);
+  if (pTypeInfo == 0)
+    return false;   // error
+  // task 2: push the pointer to the Lua stack
+  // this requires a pointer & the type
+  // the last param specifies if Lua is responsible for deleting the object
+  SWIG_NewPointerObj(L, ptr, pTypeInfo, owned);
+  return true;
+}
+
+/* This is an example of how to call the Lua function
+    void onEvent(Event e) 
+  its very tedious, but gives you an idea of the issues involed.
+*/
+int call_onEvent(lua_State *L, Event e) {
+  int top;
+  /* ok, here we go:
+  push a, push b, call 'add' check & return res
+  */
+  top = lua_gettop(L);  /* for later */
+  lua_pushstring(L, "onEvent");                                  /* function name */
+  lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */
+  if (!lua_isfunction(L, -1)) {
+    printf("[C++] error: cannot find function 'OnEvent'\n");
+    lua_settop(L, top);  // reset
+    return 0;
+  }
+  // push the event object
+  push_pointer(L, &e, "Event *", 0);
+  if (lua_pcall(L, 1, 0, 0) != 0)  /* call function with 1 arguments and no result */
+  {
+    printf("[C++] error running function `OnEvent': %s\n", lua_tostring(L, -1));
+    lua_settop(L, top);  // reset
+    return 0;
+  }
+  lua_settop(L, top);  /* reset stack */
+  return 1;   // ok
+}
+
+
+int main(int argc, char* argv[]) {
+  printf("[C++] Welcome to the simple embedded Lua example v3\n");
+  printf("[C++] We are in C++\n");
+  printf("[C++] opening a Lua state & loading the libraries\n");
+  lua_State *L = lua_open();
+  luaopen_base(L);
+  luaopen_string(L);
+  luaopen_math(L);
+  printf("[C++] now loading the SWIG wrappered library\n");
+  luaopen_example(L);
+  printf("[C++] all looks ok\n");
+  printf("\n");
+  printf("[C++] lets create an Engine and pass a pointer to Lua\n");
+  Engine engine;
+  /* this code will pass a pointer into lua, but C++ still owns the object
+  this is a little tedious, to do, but lets do it
+  we need to pass the pointer (obviously), the type name 
+  and a flag which states if Lua should delete the pointer once its finished with it
+  The type name is a class name string which is registered with SWIG
+  (normally, just look in the wrapper file to get this)
+  in this case we don't want Lua to delete the pointer so the ownership flag is 0
+  */
+  push_pointer(L,&engine,"Engine *",0);
+  lua_setglobal(L, "pEngine");  // set as global variable
+
+  printf("[C++] now lets load the file 'runme.lua'\n");
+  printf("[C++] any lua code in this file will be executed\n");
+  if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {
+    printf("[C++] ERROR: cannot run lua file: %s", lua_tostring(L, -1));
+    exit(3);
+  }
+  printf("[C++] We are now back in C++, all looks ok\n");
+  printf("\n");
+
+  printf("[C++] Lets call the Lua function onEvent(e)\n");
+  printf("[C++] We will give it different events, as we wish\n");
+  printf("[C++] Starting with STARTUP\n");
+  Event ev;
+  ev.mType = Event::STARTUP;
+  call_onEvent(L, ev);
+  printf("[C++] ok\n");
+  printf("[C++] now we will try MOUSEPRESS,KEYPRESS,MOUSEPRESS\n");
+  ev.mType = Event::MOUSEPRESS;
+  call_onEvent(L, ev);
+  ev.mType = Event::KEYPRESS;
+  call_onEvent(L, ev);
+  ev.mType = Event::MOUSEPRESS;
+  call_onEvent(L, ev);
+  printf("[C++] ok\n");
+  printf("[C++] Finally we will SHUTDOWN\n");
+  ev.mType = Event::SHUTDOWN;
+  call_onEvent(L, ev);
+  printf("[C++] ok\n");
+
+  printf("\n");
+  printf("[C++] all finished, closing the lua state\n");
+  lua_close(L);
+  return 0;
+}
diff --git a/trunk/Examples/lua/embed3/example.cpp b/trunk/Examples/lua/embed3/example.cpp
new file mode 100644
index 0000000..a8264f3
--- /dev/null
+++ b/trunk/Examples/lua/embed3/example.cpp
@@ -0,0 +1,25 @@
+/* File : example.cpp */
+
+#include <stdio.h>
+#include "example.h"
+
+void Engine::start()
+{
+    printf("[C++] Engine::start()\n");
+}
+
+void Engine::stop()
+{
+    printf("[C++] Engine::stop()\n");
+}
+
+void Engine::accelerate(float f)
+{
+    printf("[C++] Engine::accelerate(%f)\n",f);
+}
+
+void Engine::decelerate(float f)
+{
+    printf("[C++] Engine::decelerate(%f)\n",f);
+}
+
diff --git a/trunk/Examples/lua/embed3/example.h b/trunk/Examples/lua/embed3/example.h
new file mode 100644
index 0000000..41c13e9
--- /dev/null
+++ b/trunk/Examples/lua/embed3/example.h
@@ -0,0 +1,24 @@
+/* File : example.h */
+
+/* This is some kind of engine of some kind 
+we will give it some dummy methods for Lua to call*/
+
+class Engine
+{
+public:
+    void start();
+    void stop();
+    void accelerate(float f);
+    void decelerate(float f);
+};
+
+
+/* We also want to pass some events to Lua, so lets have a few classes
+to do this.
+*/
+class Event
+{
+public:
+    enum {STARTUP,KEYPRESS,MOUSEPRESS,SHUTDOWN} mType;
+    // etc
+};
diff --git a/trunk/Examples/lua/embed3/example.i b/trunk/Examples/lua/embed3/example.i
new file mode 100644
index 0000000..032805c
--- /dev/null
+++ b/trunk/Examples/lua/embed3/example.i
@@ -0,0 +1,8 @@
+/* File : example.i */

+%module example

+

+%{

+#include "example.h"

+%}

+

+%include "example.h"

diff --git a/trunk/Examples/lua/embed3/runme.lua b/trunk/Examples/lua/embed3/runme.lua
new file mode 100644
index 0000000..3a44bd2
--- /dev/null
+++ b/trunk/Examples/lua/embed3/runme.lua
@@ -0,0 +1,35 @@
+print "[lua] This is runme.lua"
+-- test program for embeded lua
+-- we do not need to load the library, as it was already in the intrepreter
+-- but lets check anyway
+
+assert(type(example)=='table',"Don't appear to have loaded the example module. Do not run this file directly, run the embed3 executable")
+
+print "[lua] looking to see if we have a pointer to the engine"
+if type(pEngine)=="userdata" then
+    print "[lua] looks good"
+else
+    print "[lua] nope, no signs of it"
+end
+
+
+-- the embed program expects a function void onEvent(Event)
+-- this is it
+
+function onEvent(e)
+    print("[Lua] onEvent with event",e.mType)
+    -- lets do something with the Engine
+    -- nothing clever, but ...
+    if e.mType==example.Event_STARTUP then
+        pEngine:start()
+    elseif e.mType==example.Event_KEYPRESS then
+        pEngine:accelerate(0.4)
+    elseif e.mType==example.Event_MOUSEPRESS then
+        pEngine:decelerate(0.4)
+    elseif e.mType==example.Event_SHUTDOWN then
+        pEngine:stop()
+    else
+        error("unknown event type")
+    end
+    print("[Lua] ending onEvent")
+end
\ No newline at end of file
diff --git a/trunk/Examples/lua/exception/Makefile b/trunk/Examples/lua/exception/Makefile
new file mode 100644
index 0000000..8657f19
--- /dev/null
+++ b/trunk/Examples/lua/exception/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..

+SWIG       = $(TOP)/../preinst-swig

+CXXSRCS    = 

+TARGET     = example

+INTERFACE  = example.i

+LIBS       = -lm

+

+all::

+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \

+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp

+

+static::

+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \

+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static

+

+clean::

+	$(MAKE) -f $(TOP)/Makefile lua_clean

+

+check: all

diff --git a/trunk/Examples/lua/exception/example.h b/trunk/Examples/lua/exception/example.h
new file mode 100644
index 0000000..5148a59
--- /dev/null
+++ b/trunk/Examples/lua/exception/example.h
@@ -0,0 +1,53 @@
+/* File : example.h */

+

+#include <string>

+#ifndef SWIG

+struct A {

+};

+#endif

+

+class Exc {

+public:

+  Exc(int c, const char *m) {

+    code = c;

+    strncpy(msg,m,256);

+  }

+  int code;

+  char msg[256];

+};

+

+#if defined(_MSC_VER)

+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)

+#endif

+

+class Test {

+public:

+  int simple() throw(int&) {

+      throw(37);

+      return 1;

+  }

+  int message() throw(const char *) {

+      throw("I died.");

+      return 1;

+  }

+  int hosed() throw(Exc) {

+      throw(Exc(42,"Hosed"));

+      return 1;

+  } 

+  int unknown() throw(A*) {

+      static A a;

+      throw &a;

+      return 1;

+  }

+  int multi(int x) throw(int, const char *, Exc) {

+     if (x == 1) throw(37);

+     if (x == 2) throw("Bleah!");

+     if (x == 3) throw(Exc(42,"No-go-diggy-die"));

+     return 1;

+  }

+};

+

+#if defined(_MSC_VER)

+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)

+#endif

+

diff --git a/trunk/Examples/lua/exception/example.i b/trunk/Examples/lua/exception/example.i
new file mode 100644
index 0000000..09cd9e8
--- /dev/null
+++ b/trunk/Examples/lua/exception/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */

+%module example

+

+%{

+#include "example.h"

+%}

+

+%include "std_string.i"

+

+// we want to return Exc objects to the interpreter

+// therefore we add this typemap

+// note: only works if Exc is copyable

+%apply SWIGTYPE EXCEPTION_BY_VAL {Exc};

+

+/* Let's just grab the original header file here */

+%include "example.h"

+

diff --git a/trunk/Examples/lua/exception/runme.lua b/trunk/Examples/lua/exception/runme.lua
new file mode 100644
index 0000000..39b2d6d
--- /dev/null
+++ b/trunk/Examples/lua/exception/runme.lua
@@ -0,0 +1,96 @@
+-- file: example.lua

+

+---- importing ----

+if string.sub(_VERSION,1,7)=='Lua 5.0' then

+	-- lua5.0 doesnt have a nice way to do this

+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')

+	assert(lib)()

+else

+	-- lua 5.1 does

+	require('example')

+end

+

+-- throw a lot of exceptions:

+-- you must catch exceptions using pcall and then checking the result

+

+t = example.Test()

+

+print "calling t:unknown()"

+ok,res=pcall(function() t:unknown() end)

+if ok then 

+    print "  that worked! Funny"

+else

+    print("  call failed with error:",res)

+end

+

+print "calling t:simple()"

+ok,res=pcall(function() t:simple() end)

+if ok then 

+    print "  that worked! Funny"

+else

+    print("  call failed with error:",res)

+end

+

+print "calling t:message()"

+ok,res=pcall(function() t:message() end)

+if ok then 

+    print "  that worked! Funny"

+else

+    print("  call failed with error:",res)

+end

+

+print "calling t:hosed()"

+ok,res=pcall(function() t:hosed() end)

+if ok then 

+    print "  that worked! Funny"

+else

+    print("  call failed with error:",res.code,res.msg)

+end

+

+-- this is a rather strange way to perform the multiple catch of exceptions

+print "calling t:mutli()"

+for i=1,3 do

+    ok,res=pcall(function() t:multi(i) end)

+    if ok then

+        print "  that worked! Funny"

+    else

+        if swig_type(res)=="Exc *" then

+            print("  call failed with Exc exception:",res.code,res.msg)

+        else

+            print("  call failed with error:",res)

+        end

+    end

+end

+

+-- this is a bit crazy, but it shows obtaining of the stacktrace

+function a() 

+    b() 

+end

+function b() 

+    t:message()

+end

+print [[

+Now lets call function a()

+ which calls b() 

+ which calls into C++

+ which will throw an exception!]]

+ok,res=pcall(a)

+if ok then 

+    print "  that worked! Funny"

+else

+    print("  call failed with error:",res)

+end

+print "Now lets do the same using xpcall(a,debug.traceback)"

+ok,res=xpcall(a,debug.traceback)

+if ok then 

+    print "  that worked! Funny"

+else

+    print("  call failed with error:",res)

+end

+print "As you can see, the xpcall gives a nice stacktrace to work with"

+

+

+ok,res=pcall(a)

+print(ok,res)

+ok,res=xpcall(a,debug.traceback)

+print(ok,res)

diff --git a/trunk/Examples/lua/funcptr3/Makefile b/trunk/Examples/lua/funcptr3/Makefile
new file mode 100644
index 0000000..ac0fff4
--- /dev/null
+++ b/trunk/Examples/lua/funcptr3/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/funcptr3/example.c b/trunk/Examples/lua/funcptr3/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/lua/funcptr3/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/lua/funcptr3/example.h b/trunk/Examples/lua/funcptr3/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/lua/funcptr3/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/lua/funcptr3/example.i b/trunk/Examples/lua/funcptr3/example.i
new file mode 100644
index 0000000..319b227
--- /dev/null
+++ b/trunk/Examples/lua/funcptr3/example.i
@@ -0,0 +1,69 @@
+/* File : example.i */
+/*
+This demonstrates how to pass a lua function, into some C code and then call it.
+
+There are two examples, the first is as a parameter, the second as a global variable.
+
+*/
+%module example
+%{
+#include "example.h"
+%}
+/* the extra wrappers for lua functions, see SWIG/Lib/lua/lua_fnptr.i for more details */
+%include "lua_fnptr.i"
+
+/* these are a bunch of C functions which we want to be able to call from lua */
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+/* this function takes a lua function as a parameter and calls it.
+As this is takes a lua fn it needs lua code
+*/
+%inline %{
+	
+int callback(int a, int b, SWIGLUA_FN fn)
+{
+	SWIGLUA_FN_GET(fn);
+	lua_pushnumber(fn.L,a);
+	lua_pushnumber(fn.L,b);
+	lua_call(fn.L,2,1);    /* 2 in, 1 out */
+	return (int)luaL_checknumber(fn.L,-1);
+}	
+%}	
+
+/******************
+Second code uses a stored reference.
+*******************/
+
+%inline %{
+/* note: this is not so good to just have it as a raw ref
+ people could set anything to this
+ a better solution would to be to have a fn which wants a SWIGLUA_FN, then
+ checks the type & converts to a SWIGLUA_REF.
+*/	
+SWIGLUA_REF the_func={0,0};
+	
+void call_the_func(int a)
+{
+	int i;
+	if (the_func.L==0){
+		printf("the_func is zero\n");
+		return;
+	}
+	swiglua_ref_get(&the_func);
+	if (!lua_isfunction(the_func.L,-1))
+	{
+		printf("the_func is not a function\n");
+		return;
+	}
+	lua_pop(the_func.L,1); /* tidy stack */
+	for(i=0;i<a;i++)
+	{
+		swiglua_ref_get(&the_func);
+		lua_pushnumber(the_func.L,i);
+		lua_call(the_func.L,1,0);    /* 1 in, 0 out */
+	}
+}	
+
+%}
diff --git a/trunk/Examples/lua/funcptr3/runme.lua b/trunk/Examples/lua/funcptr3/runme.lua
new file mode 100644
index 0000000..b78c504
--- /dev/null
+++ b/trunk/Examples/lua/funcptr3/runme.lua
@@ -0,0 +1,54 @@
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+a = 37
+b = 42
+
+-- Now call our C function
+
+print("Trying some C functions")
+print("    a        =", a)
+print("    b        =", b)
+print("    add(a,b) =", example.add(a,b))
+print("    sub(a,b) =", example.sub(a,b))
+print("    mul(a,b) =", example.mul(a,b))
+
+print("Calling them using the my_func()")
+print("    add(a,b) =", example.callback(a,b,example.add))
+print("    sub(a,b) =", example.callback(a,b,example.sub))
+print("    mul(a,b) =", example.callback(a,b,example.mul))
+
+print("Now let us write our own function")
+function foo(a,b) return 101 end
+print("    foo(a,b) =", example.callback(a,b,foo))
+
+print("Now let us try something that will fail")
+local ok,c=pcall(example.callback,a,b,print)
+if ok==false then
+	print("this failed as expected, error:",c)
+else
+	print("oops, that worked! result:",c)
+end
+
+
+-- part2 stored function
+print("trying a stored fn")
+print("the_func=",example.the_func)
+print("setting to print")
+example.the_func=print
+print("the_func=",example.the_func)
+print("call_the_func(5)")
+example.call_the_func(5)
+
+function bar(i) print("bar",i) end
+print("setting to bar")
+example.the_func=bar
+print("call_the_func(5)")
+example.call_the_func(5)
diff --git a/trunk/Examples/lua/functest/Makefile b/trunk/Examples/lua/functest/Makefile
new file mode 100644
index 0000000..ac0fff4
--- /dev/null
+++ b/trunk/Examples/lua/functest/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/functest/example.c b/trunk/Examples/lua/functest/example.c
new file mode 100644
index 0000000..8eb647f
--- /dev/null
+++ b/trunk/Examples/lua/functest/example.c
@@ -0,0 +1,25 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+int add1(int x, int y)
+{
+   return x+y;
+}
+
+void add2(int x, int *y, int *z)
+{
+   *z = x+*y;
+}
+
+int add3(int x, int y, int *z)
+{
+   *z = x-y;
+   return x+y;
+}
+
+void add4(int x, int *y)
+{
+   *y += x;
+}
diff --git a/trunk/Examples/lua/functest/example.i b/trunk/Examples/lua/functest/example.i
new file mode 100644
index 0000000..631e060
--- /dev/null
+++ b/trunk/Examples/lua/functest/example.i
@@ -0,0 +1,13 @@
+/* File : example.i */
+%module example
+
+%include "typemaps.i" // you must have this for the typemaps for ptrs
+// basic function testing
+//
+%inline %{
+extern int add1(int x, int y);              // return x+y -- basic function test
+extern void add2(int x, int *INPUT, int *OUTPUT); // *z = x+*y  -- argin and argout test
+extern int add3(int x, int y, int *OUTPUT);    // return x+y, *z=x-y -- returning 2 values
+extern void add4(int x, int *INOUT);        // *y += x    -- INOUT dual purpose variable
+%}
+
diff --git a/trunk/Examples/lua/functest/runme.lua b/trunk/Examples/lua/functest/runme.lua
new file mode 100644
index 0000000..65b3cc2
--- /dev/null
+++ b/trunk/Examples/lua/functest/runme.lua
@@ -0,0 +1,20 @@
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+
+x,y = 42,105
+print("add1 - simple arg passing and single return value -- ")
+print(example.add1(x,y))
+print("add2 - pointer arg passing and single return value through pointer arg -- ")
+print(example.add2(x,y))
+print("add3 - simple arg passing and double return value through return and ptr arg -- ")
+print(example.add3(x,y))
+print("add4 - dual use arg and return value -- ")
+print(example.add4(x,y))
diff --git a/trunk/Examples/lua/functor/Makefile b/trunk/Examples/lua/functor/Makefile
new file mode 100644
index 0000000..432bfbe
--- /dev/null
+++ b/trunk/Examples/lua/functor/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/functor/example.i b/trunk/Examples/lua/functor/example.i
new file mode 100644
index 0000000..cc7a679
--- /dev/null
+++ b/trunk/Examples/lua/functor/example.i
@@ -0,0 +1,29 @@
+/* File : example.i */
+%module example
+
+
+%inline %{
+// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514
+template<class T> class Sum {
+   T res;
+public:
+   Sum(T i = 0) : res(i) { }
+   void operator() (T x) { res += x; }
+   T result() const { return res; }
+};
+
+%}
+
+// Rename the application operator to __call.
+// Note: this is normally automatic, but if you had to do it yourself
+// you would use this directive:
+//
+// %rename(__call)	*::operator();	// the fn call operator
+
+// Instantiate a few versions
+%template(intSum) Sum<int>;
+%template(doubleSum) Sum<double>;
+
+
+
+
diff --git a/trunk/Examples/lua/functor/runme.lua b/trunk/Examples/lua/functor/runme.lua
new file mode 100644
index 0000000..adf124a
--- /dev/null
+++ b/trunk/Examples/lua/functor/runme.lua
@@ -0,0 +1,24 @@
+-- Operator overloading example
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+a = example.intSum(0)
+b = example.doubleSum(100.0)
+
+-- Use the objects.  They should be callable just like a normal
+-- lua function.
+
+for i=0,100 do
+    a(i)                -- Note: function call
+    b(math.sqrt(i))     -- Note: function call
+end 
+print("int sum 0..100 is",a:result(),"(expected 5050)")
+print("double sum 0..100 is",b:result(),"(expected ~771.46)")
+
diff --git a/trunk/Examples/lua/import.lua b/trunk/Examples/lua/import.lua
new file mode 100644
index 0000000..b2a40b0
--- /dev/null
+++ b/trunk/Examples/lua/import.lua
@@ -0,0 +1,42 @@
+-- import
+-- the lua 5.0 loading mechanism is rather poor & relies upon the loadlib() fn
+-- the lua 5.1 loading mechanism is simplicity itself
+-- for now we need a bridge which will use the correct verion
+
+function import_5_0(module)
+	-- imports the file into the program
+	-- for a module 'example'
+	-- this must load 'example.dll' or 'example.so'
+	-- and look for the fn 'Example_Init()' (note the capitalisation)
+	if rawget(_G,module)~=nil then return end -- module appears to be loaded
+		
+	-- capitialising the first letter
+	local c=string.upper(string.sub(module,1,1))
+	local fnname=c..string.sub(module,2).."_Init"
+	
+	local suffix,lib
+	-- note: as there seems to be no way in lua to determine the platform
+	-- we will try loading all possible names
+	-- providing one works, we can load
+	for _,suffix in pairs{".dll",".so"} do
+		lib=loadlib(module..suffix,fnname)
+		if lib then -- found
+			break
+		end
+	end
+	assert(lib,"error loading module:"..module)
+	
+	lib() -- execute the function: initalising the lib
+	local m=rawget(_G,module)	-- gets the module object
+	assert(m~=nil,"no module table found")
+end
+
+function import_5_1(module)
+	require(module)
+end
+
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	import=import_5_0
+else
+	import=import_5_1
+end
\ No newline at end of file
diff --git a/trunk/Examples/lua/import/Makefile b/trunk/Examples/lua/import/Makefile
new file mode 100644
index 0000000..8f692d1
--- /dev/null
+++ b/trunk/Examples/lua/import/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+ 
+all::
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' lua_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' lua_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' lua_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' lua_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/import/README b/trunk/Examples/lua/import/README
new file mode 100644
index 0000000..1a52e3c
--- /dev/null
+++ b/trunk/Examples/lua/import/README
@@ -0,0 +1,36 @@
+This example tests the %import directive and working with multiple modules.

+

+Use 'lua runme.lua' to run a test.

+

+Overview:

+---------

+

+The example defines 4 different extension modules--each wrapping

+a separate C++ class.

+

+     base.i     -  Base class

+     foo.i      -  Foo class derived from Base

+     bar.i      -  Bar class derived from Base

+     spam.i     -  Spam class derived from Bar

+

+Each module uses %import to refer to another module.  For

+example, the 'foo.i' module uses '%import base.i' to get

+definitions for its base class.

+

+If everything is okay, all of the modules will load properly and

+type checking will work correctly. Caveat: Some compilers, for example

+gcc-3.2.x, generate broken vtables with the inline methods in this test.

+This is not a SWIG problem and can usually be solved with non-inlined

+destructors compiled into separate shared objects/DLLs.

+

+Unix:

+-----

+- Run make

+- Run the test as described above

+

+Windows:

+--------
+Sorry, no files here.
+If you know how, you could copy the python or ruby example dsw & dsp and try editing that

+
+

diff --git a/trunk/Examples/lua/import/bar.h b/trunk/Examples/lua/import/bar.h
new file mode 100644
index 0000000..1c99f28
--- /dev/null
+++ b/trunk/Examples/lua/import/bar.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Bar : public Base {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual const char * A() const { 
+    return "Bar::A";
+  }
+  const char * B() const {
+    return "Bar::B";
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Bar *fromBase(Base *b) {
+    return dynamic_cast<Bar *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/lua/import/bar.i b/trunk/Examples/lua/import/bar.i
new file mode 100644
index 0000000..5816cbe
--- /dev/null
+++ b/trunk/Examples/lua/import/bar.i
@@ -0,0 +1,9 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+
diff --git a/trunk/Examples/lua/import/base.h b/trunk/Examples/lua/import/base.h
new file mode 100644
index 0000000..fec0f32
--- /dev/null
+++ b/trunk/Examples/lua/import/base.h
@@ -0,0 +1,16 @@
+class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual const char * A() const {
+         return "Base::A";
+     }
+     const char * B() const {
+       return "Base::B";
+     }
+     virtual Base *toBase() {
+       return static_cast<Base *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/lua/import/base.i b/trunk/Examples/lua/import/base.i
new file mode 100644
index 0000000..f6e19ef
--- /dev/null
+++ b/trunk/Examples/lua/import/base.i
@@ -0,0 +1,6 @@
+%module base
+%{
+#include "base.h"
+%}
+
+%include base.h
diff --git a/trunk/Examples/lua/import/foo.h b/trunk/Examples/lua/import/foo.h
new file mode 100644
index 0000000..1abe2c0
--- /dev/null
+++ b/trunk/Examples/lua/import/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Foo : public Base {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual const char * A() const { 
+    return "Foo::A";
+  }
+  const char * B() const {
+    return "Foo::B";
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Foo *fromBase(Base *b) {
+    return dynamic_cast<Foo *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/lua/import/foo.i b/trunk/Examples/lua/import/foo.i
new file mode 100644
index 0000000..27feb2e
--- /dev/null
+++ b/trunk/Examples/lua/import/foo.i
@@ -0,0 +1,8 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
diff --git a/trunk/Examples/lua/import/runme.lua b/trunk/Examples/lua/import/runme.lua
new file mode 100644
index 0000000..9cd7ae0
--- /dev/null
+++ b/trunk/Examples/lua/import/runme.lua
@@ -0,0 +1,103 @@
+# Test various properties of classes defined in separate modules
+
+print("Testing the %import directive")
+
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	function loadit(a)
+		lib=loadlib(a..'.dll','luaopen_'..a) or loadlib(a..'.so','luaopen_'..a)
+		assert(lib)()
+	end
+	loadit('base')
+	loadit('foo')
+	loadit('bar')
+	loadit('spam')
+else
+	-- lua 5.1 does
+	require 'base'
+	require 'foo'
+	require 'bar'
+	require 'spam'
+end
+
+-- Create some objects
+
+print("Creating some objects")
+
+a = base.Base()
+b = foo.Foo()
+c = bar.Bar()
+d = spam.Spam()
+
+-- Try calling some methods
+print("Testing some methods")
+print("Should see 'Base::A' ---> ",a:A())
+print("Should see 'Base::B' ---> ",a:B())
+
+print("Should see 'Foo::A' ---> ",b:A())
+print("Should see 'Foo::B' ---> ",b:B())
+
+print("Should see 'Bar::A' ---> ",c:A())
+print("Should see 'Bar::B' ---> ",c:B())
+
+print("Should see 'Spam::A' ---> ",d:A())
+print("Should see 'Spam::B' ---> ",d:B())
+
+-- Try some casts
+
+print("\nTesting some casts")
+
+x = a:toBase()
+print("Should see 'Base::A' ---> ",x:A())
+print("Should see 'Base::B' ---> ",x:B())
+
+x = b:toBase()
+print("Should see 'Foo::A' ---> ",x:A())
+print("Should see 'Base::B' ---> ",x:B())
+
+x = c:toBase()
+print("Should see 'Bar::A' ---> ",x:A())
+print("Should see 'Base::B' ---> ",x:B())
+
+x = d:toBase()
+print("Should see 'Spam::A' ---> ",x:A())
+print("Should see 'Base::B' ---> ",x:B())
+
+x = d:toBar()
+print("Should see 'Bar::B' ---> ",x:B())
+
+
+print "\nTesting some dynamic casts\n"
+x = d:toBase()
+
+print " Spam -> Base -> Foo : "
+y = foo.Foo_fromBase(x)
+if y then
+      print "bad swig"
+else
+      print "good swig"
+end
+
+print " Spam -> Base -> Bar : "
+y = bar.Bar_fromBase(x)
+if y then
+      print "good swig"
+else
+      print "bad swig"
+end
+      
+print " Spam -> Base -> Spam : "
+y = spam.Spam_fromBase(x)
+if y then
+      print "good swig"
+else
+      print "bad swig"
+end
+
+print " Foo -> Spam : "
+y = spam.Spam_fromBase(b)
+if y then
+      print "bad swig"
+else
+      print "good swig"
+end
diff --git a/trunk/Examples/lua/import/spam.h b/trunk/Examples/lua/import/spam.h
new file mode 100644
index 0000000..57db845
--- /dev/null
+++ b/trunk/Examples/lua/import/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+class Spam : public Bar {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual const char * A() const { 
+    return "Spam::A";
+  }
+  const char * B() const {
+    return "Spam::B";
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  virtual Bar *toBar() {
+    return static_cast<Bar *>(this);
+  }
+  static Spam *fromBase(Base *b) {
+    return dynamic_cast<Spam *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/lua/import/spam.i b/trunk/Examples/lua/import/spam.i
new file mode 100644
index 0000000..d3d9121
--- /dev/null
+++ b/trunk/Examples/lua/import/spam.i
@@ -0,0 +1,9 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+
diff --git a/trunk/Examples/lua/lua.c b/trunk/Examples/lua/lua.c
new file mode 100644
index 0000000..e06e2c5
--- /dev/null
+++ b/trunk/Examples/lua/lua.c
@@ -0,0 +1,439 @@
+/*
+** $Id$
+** Lua stand-alone interpreter
+** See Copyright Notice in lua.h
+*/
+
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define lua_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+/*
+** generic extra include file
+*/
+#ifdef LUA_USERCONFIG
+#include LUA_USERCONFIG
+#endif
+
+
+/*
+** definition of `isatty'
+*/
+#ifdef _POSIX_C_SOURCE
+#include <unistd.h>
+#define stdin_is_tty()	isatty(0)
+#else
+#define stdin_is_tty()	1  /* assume stdin is a tty */
+#endif
+
+
+
+#ifndef PROMPT
+#define PROMPT		"> "
+#endif
+
+
+#ifndef PROMPT2
+#define PROMPT2		">> "
+#endif
+
+#ifndef PROGNAME
+#define PROGNAME	"lua"
+#endif
+
+#ifndef lua_userinit
+#define lua_userinit(L)		openstdlibs(L)
+#endif
+
+
+#ifndef LUA_EXTRALIBS
+#define LUA_EXTRALIBS	/* empty */
+#endif
+
+
+static lua_State *L = NULL;
+
+static const char *progname = PROGNAME;
+
+extern int Example_Init(lua_State* L);
+
+static const luaL_reg lualibs[] = {
+  {"base", luaopen_base},
+  {"table", luaopen_table},
+  {"io", luaopen_io},
+  {"string", luaopen_string},
+  {"math", luaopen_math},
+  {"debug", luaopen_debug},
+  {"loadlib", luaopen_loadlib},
+  /* add your libraries here */
+  {"example", Example_Init},
+  LUA_EXTRALIBS
+  {NULL, NULL}
+};
+
+
+
+static void lstop (lua_State *l, lua_Debug *ar) {
+  (void)ar;  /* unused arg. */
+  lua_sethook(l, NULL, 0, 0);
+  luaL_error(l, "interrupted!");
+}
+
+
+static void laction (int i) {
+  signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
+                              terminate process (default action) */
+  lua_sethook(L, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
+}
+
+
+static void print_usage (void) {
+  fprintf(stderr,
+  "usage: %s [options] [script [args]].\n"
+  "Available options are:\n"
+  "  -        execute stdin as a file\n"
+  "  -e stat  execute string `stat'\n"
+  "  -i       enter interactive mode after executing `script'\n"
+  "  -l name  load and run library `name'\n"
+  "  -v       show version information\n"
+  "  --       stop handling options\n" ,
+  progname);
+}
+
+
+static void l_message (const char *pname, const char *msg) {
+  if (pname) fprintf(stderr, "%s: ", pname);
+  fprintf(stderr, "%s\n", msg);
+}
+
+
+static int report (int status) {
+  const char *msg;
+  if (status) {
+    msg = lua_tostring(L, -1);
+    if (msg == NULL) msg = "(error with no message)";
+    l_message(progname, msg);
+    lua_pop(L, 1);
+  }
+  return status;
+}
+
+
+static int lcall (int narg, int clear) {
+  int status;
+  int base = lua_gettop(L) - narg;  /* function index */
+  lua_pushliteral(L, "_TRACEBACK");
+  lua_rawget(L, LUA_GLOBALSINDEX);  /* get traceback function */
+  lua_insert(L, base);  /* put it under chunk and args */
+  signal(SIGINT, laction);
+  status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
+  signal(SIGINT, SIG_DFL);
+  lua_remove(L, base);  /* remove traceback function */
+  return status;
+}
+
+
+static void print_version (void) {
+  l_message(NULL, LUA_VERSION "  " LUA_COPYRIGHT);
+}
+
+
+static void getargs (char *argv[], int n) {
+  int i;
+  lua_newtable(L);
+  for (i=0; argv[i]; i++) {
+    lua_pushnumber(L, i - n);
+    lua_pushstring(L, argv[i]);
+    lua_rawset(L, -3);
+  }
+  /* arg.n = maximum index in table `arg' */
+  lua_pushliteral(L, "n");
+  lua_pushnumber(L, i-n-1);
+  lua_rawset(L, -3);
+}
+
+
+static int docall (int status) {
+  if (status == 0) status = lcall(0, 1);
+  return report(status);
+}
+
+
+static int file_input (const char *name) {
+  return docall(luaL_loadfile(L, name));
+}
+
+
+static int dostring (const char *s, const char *name) {
+  return docall(luaL_loadbuffer(L, s, strlen(s), name));
+}
+
+
+static int load_file (const char *name) {
+  lua_pushliteral(L, "require");
+  lua_rawget(L, LUA_GLOBALSINDEX);
+  if (!lua_isfunction(L, -1)) {  /* no `require' defined? */
+    lua_pop(L, 1);
+    return file_input(name);
+  }
+  else {
+    lua_pushstring(L, name);
+    return report(lcall(1, 1));
+  }
+}
+
+
+/*
+** this macro can be used by some `history' system to save lines
+** read in manual input
+*/
+#ifndef lua_saveline
+#define lua_saveline(L,line)	/* empty */
+#endif
+
+
+/*
+** this macro defines a function to show the prompt and reads the
+** next line for manual input
+*/
+#ifndef lua_readline
+#define lua_readline(L,prompt)		readline(L,prompt)
+
+/* maximum length of an input line */
+#ifndef MAXINPUT
+#define MAXINPUT	512
+#endif
+
+
+static int readline (lua_State *l, const char *prompt) {
+  static char buffer[MAXINPUT];
+  if (prompt) {
+    fputs(prompt, stdout);
+    fflush(stdout);
+  }
+  if (fgets(buffer, sizeof(buffer), stdin) == NULL)
+    return 0;  /* read fails */
+  else {
+    lua_pushstring(l, buffer);
+    return 1;
+  }
+}
+
+#endif
+
+
+static const char *get_prompt (int firstline) {
+  const char *p = NULL;
+  lua_pushstring(L, firstline ? "_PROMPT" : "_PROMPT2");
+  lua_rawget(L, LUA_GLOBALSINDEX);
+  p = lua_tostring(L, -1);
+  if (p == NULL) p = (firstline ? PROMPT : PROMPT2);
+  lua_pop(L, 1);  /* remove global */
+  return p;
+}
+
+
+static int incomplete (int status) {
+  if (status == LUA_ERRSYNTAX &&
+         strstr(lua_tostring(L, -1), "near `<eof>'") != NULL) {
+    lua_pop(L, 1);
+    return 1;
+  }
+  else
+    return 0;
+}
+
+
+static int load_string (void) {
+  int status;
+  lua_settop(L, 0);
+  if (lua_readline(L, get_prompt(1)) == 0)  /* no input? */
+    return -1;
+  if (lua_tostring(L, -1)[0] == '=') {  /* line starts with `=' ? */
+    lua_pushfstring(L, "return %s", lua_tostring(L, -1)+1);/* `=' -> `return' */
+    lua_remove(L, -2);  /* remove original line */
+  }
+  for (;;) {  /* repeat until gets a complete line */
+    status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
+    if (!incomplete(status)) break;  /* cannot try to add lines? */
+    if (lua_readline(L, get_prompt(0)) == 0)  /* no more input? */
+      return -1;
+    lua_concat(L, lua_gettop(L));  /* join lines */
+  }
+  lua_saveline(L, lua_tostring(L, 1));
+  lua_remove(L, 1);  /* remove line */
+  return status;
+}
+
+
+static void manual_input (void) {
+  int status;
+  const char *oldprogname = progname;
+  progname = NULL;
+  while ((status = load_string()) != -1) {
+    if (status == 0) status = lcall(0, 0);
+    report(status);
+    if (status == 0 && lua_gettop(L) > 0) {  /* any result to print? */
+      lua_getglobal(L, "print");
+      lua_insert(L, 1);
+      if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
+        l_message(progname, lua_pushfstring(L, "error calling `print' (%s)",
+                                               lua_tostring(L, -1)));
+    }
+  }
+  lua_settop(L, 0);  /* clear stack */
+  fputs("\n", stdout);
+  progname = oldprogname;
+}
+
+
+static int handle_argv (char *argv[], int *interactive) {
+  if (argv[1] == NULL) {  /* no more arguments? */
+    if (stdin_is_tty()) {
+      print_version();
+      manual_input();
+    }
+    else
+      file_input(NULL);  /* executes stdin as a file */
+  }
+  else {  /* other arguments; loop over them */
+    int i;
+    for (i = 1; argv[i] != NULL; i++) {
+      if (argv[i][0] != '-') break;  /* not an option? */
+      switch (argv[i][1]) {  /* option */
+        case '-': {  /* `--' */
+          if (argv[i][2] != '\0') {
+            print_usage();
+            return 1;
+          }
+          i++;  /* skip this argument */
+          goto endloop;  /* stop handling arguments */
+        }
+        case '\0': {
+          file_input(NULL);  /* executes stdin as a file */
+          break;
+        }
+        case 'i': {
+          *interactive = 1;
+          break;
+        }
+        case 'v': {
+          print_version();
+          break;
+        }
+        case 'e': {
+          const char *chunk = argv[i] + 2;
+          if (*chunk == '\0') chunk = argv[++i];
+          if (chunk == NULL) {
+            print_usage();
+            return 1;
+          }
+          if (dostring(chunk, "=<command line>") != 0)
+            return 1;
+          break;
+        }
+        case 'l': {
+          const char *filename = argv[i] + 2;
+          if (*filename == '\0') filename = argv[++i];
+          if (filename == NULL) {
+            print_usage();
+            return 1;
+          }
+          if (load_file(filename))
+            return 1;  /* stop if file fails */
+          break;
+        }
+        case 'c': {
+          l_message(progname, "option `-c' is deprecated");
+          break;
+        }
+        case 's': {
+          l_message(progname, "option `-s' is deprecated");
+          break;
+        }
+        default: {
+          print_usage();
+          return 1;
+        }
+      }
+    } endloop:
+    if (argv[i] != NULL) {
+      const char *filename = argv[i];
+      getargs(argv, i);  /* collect arguments */
+      lua_setglobal(L, "arg");
+      return file_input(filename);  /* stop scanning arguments */
+    }
+  }
+  return 0;
+}
+
+
+static void openstdlibs (lua_State *l) {
+  const luaL_reg *lib = lualibs;
+  for (; lib->func; lib++) {
+    lib->func(l);  /* open library */
+    lua_settop(l, 0);  /* discard any results */
+  }
+}
+
+
+static int handle_luainit (void) {
+  const char *init = getenv("LUA_INIT");
+  if (init == NULL) return 0;  /* status OK */
+  else if (init[0] == '@')
+    return file_input(init+1);
+  else
+    return dostring(init, "=LUA_INIT");
+}
+
+
+struct Smain {
+  int argc;
+  char **argv;
+  int status;
+};
+
+
+static int pmain (lua_State *l) {
+  struct Smain *s = (struct Smain *)lua_touserdata(l, 1);
+  int status;
+  int interactive = 0;
+  if (s->argv[0] && s->argv[0][0]) progname = s->argv[0];
+  L = l;
+  lua_userinit(l);  /* open libraries */
+  status = handle_luainit();
+  if (status == 0) {
+    status = handle_argv(s->argv, &interactive);
+    if (status == 0 && interactive) manual_input();
+  }
+  s->status = status;
+  return 0;
+}
+
+
+int main (int argc, char *argv[]) {
+  int status;
+  struct Smain s;
+  lua_State *l = lua_open();  /* create state */
+  if (l == NULL) {
+    l_message(argv[0], "cannot create state: not enough memory");
+    return EXIT_FAILURE;
+  }
+  s.argc = argc;
+  s.argv = argv;
+  status = lua_cpcall(l, &pmain, &s);
+  report(status);
+  lua_close(l);
+  return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
diff --git a/trunk/Examples/lua/owner/Makefile b/trunk/Examples/lua/owner/Makefile
new file mode 100644
index 0000000..1fe68ec
--- /dev/null
+++ b/trunk/Examples/lua/owner/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..

+SWIG       = $(TOP)/../preinst-swig

+CXXSRCS    = example.cxx

+TARGET     = example

+INTERFACE  = example.i

+LIBS       = -lm

+

+all::

+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \

+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp

+

+static::

+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \

+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static

+

+clean::

+	$(MAKE) -f $(TOP)/Makefile lua_clean

+

+check: all

diff --git a/trunk/Examples/lua/owner/example.cxx b/trunk/Examples/lua/owner/example.cxx
new file mode 100644
index 0000000..d6caeef
--- /dev/null
+++ b/trunk/Examples/lua/owner/example.cxx
@@ -0,0 +1,69 @@
+/* File : example.c */

+

+#include "example.h"

+#include <stdio.h>

+

+#define M_PI 3.14159265358979323846

+

+/* Move the shape to a new location */

+void Shape::move(double dx, double dy) {

+  x += dx;

+  y += dy;

+}

+

+int Shape::nshapes = 0;

+

+double Circle::area(void) {

+  return M_PI*radius*radius;

+}

+

+double Circle::perimeter(void) {

+  return 2*M_PI*radius;

+}

+

+double Square::area(void) {

+  return width*width;

+}

+

+double Square::perimeter(void) {

+  return 4*width;

+}

+

+Circle* createCircle(double w)

+{

+    return new Circle(w);

+}

+

+Square* createSquare(double w)

+{

+    return new Square(w);

+}

+

+ShapeOwner::ShapeOwner() {printf("  ShapeOwner(%p)\n",this);}

+ShapeOwner::~ShapeOwner()

+{

+    printf("  ~ShapeOwner(%p)\n",this);

+    for(unsigned i=0;i<shapes.size();i++)

+        delete shapes[i];

+}

+

+void ShapeOwner::add(Shape* ptr) // this method takes ownership of the object

+{

+    shapes.push_back(ptr);

+}

+

+Shape* ShapeOwner::get(int idx) // this pointer is still owned by the class (assessor)

+{

+    if (idx < 0 || idx >= static_cast<int>(shapes.size()))

+        return NULL;

+    return shapes[idx];

+}

+

+Shape* ShapeOwner::remove(int idx) // this method returns memory which must be deleted

+{

+    if (idx < 0 || idx >= static_cast<int>(shapes.size()))

+        return NULL;

+    Shape* ptr=shapes[idx];

+    shapes.erase(shapes.begin()+idx);

+    return ptr;

+}

diff --git a/trunk/Examples/lua/owner/example.h b/trunk/Examples/lua/owner/example.h
new file mode 100644
index 0000000..b005680
--- /dev/null
+++ b/trunk/Examples/lua/owner/example.h
@@ -0,0 +1,54 @@
+/* File : example.h */

+#include <vector>

+

+class Shape {

+public:

+  Shape() {

+    nshapes++;

+  }

+  virtual ~Shape() {

+    nshapes--;

+  };

+  double  x, y;   

+  void    move(double dx, double dy);

+  virtual double area(void) = 0;

+  virtual double perimeter(void) = 0;

+  static  int nshapes;

+};

+

+class Circle : public Shape {

+private:

+  double radius;

+public:

+  Circle(double r) : radius(r) { };

+  virtual double area(void);

+  virtual double perimeter(void);

+};

+

+class Square : public Shape {

+private:

+  double width;

+public:

+  Square(double w) : width(w) { };

+  virtual double area(void);

+  virtual double perimeter(void);

+};

+

+

+Circle* createCircle(double w); // this method creates a new object

+Square* createSquare(double w); // this method creates a new object

+

+class ShapeOwner {

+private:

+    std::vector<Shape*> shapes;

+    ShapeOwner(const ShapeOwner&); // no copying

+    ShapeOwner& operator=(const ShapeOwner&); // no copying

+public:

+    ShapeOwner();

+    ~ShapeOwner();

+    void add(Shape* ptr); // this method takes ownership of the object

+    Shape* get(int idx); // this pointer is still owned by the class (assessor)

+    Shape* remove(int idx); // this method returns memory which must be deleted

+};

+

+  

diff --git a/trunk/Examples/lua/owner/example.i b/trunk/Examples/lua/owner/example.i
new file mode 100644
index 0000000..4e7c331
--- /dev/null
+++ b/trunk/Examples/lua/owner/example.i
@@ -0,0 +1,32 @@
+/* File : example.i */

+%module example

+

+%{

+#include "example.h"

+%}

+

+// before we grab the header file, we must warn SWIG about some of these functions.

+

+// these functions create data, so must be managed

+%newobject createCircle;

+%newobject createSquare;

+

+// this method returns as pointer which must be managed

+%newobject ShapeOwner::remove;

+

+// you cannot use %delobject on ShapeOwner::add()

+// as this disowns the ShapeOwner, not the Shape (oops)

+//%delobject ShapeOwner::add(Shape*); DO NOT USE

+

+// either you can use a new function (such as this)

+/*%delobject add_Shape;

+%inline %{

+void add_Shape(Shape* s,ShapeOwner* own){own->add(s);}

+%}*/

+

+// or a better solution is a typemap

+%apply SWIGTYPE *DISOWN {Shape* ptr};

+

+// now we can grab the header file

+%include "example.h"

+

diff --git a/trunk/Examples/lua/owner/runme.lua b/trunk/Examples/lua/owner/runme.lua
new file mode 100644
index 0000000..d2d8a9c
--- /dev/null
+++ b/trunk/Examples/lua/owner/runme.lua
@@ -0,0 +1,104 @@
+-- Operator overloading example

+---- importing ----

+if string.sub(_VERSION,1,7)=='Lua 5.0' then

+	-- lua5.0 doesnt have a nice way to do this

+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')

+	assert(lib)()

+else

+	-- lua 5.1 does

+	require('example')

+end

+

+print "ok, lets test Lua's ownership of C++ objects"

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")

+

+print "\nLets make a couple"

+a=example.Square(10)

+b=example.Circle(1)

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 2)")

+

+print "\nNote lets use the createX functions"

+c=example.createCircle(5)

+d=example.createSquare(3)

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 4)")

+

+print "\nWe will run the garbage collector & see if they are till here"

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 4)")

+

+print "\nLets get rid of them all, collect garbage & see if they are till here"

+a,b,c,d=nil,nil,nil,nil

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")

+

+print "\nLets start putting stuff into the ShapeOwner"

+print "The ShapeOwner now owns the shapes, but Lua still has pointers to them"

+o=example.ShapeOwner()

+a=example.Square(10)

+b=example.Circle(1)

+o:add(a)

+o:add(b)

+o:add(example.createSquare(5))

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")

+

+print "\nWe will nil our references,run the garbage collector & see if they are till here"

+print "they should be, as the ShapeOwner owns them"

+a,b=nil,nil

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")

+

+print "\nWe will access them and check that they are still valid"

+a=o:get(0)

+b=o:get(1)

+print(" Area's are",a:area(),b:area(),o:get(2):area())

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")

+

+print "\nWe will remove one from the C++ owner & pass its ownership to Lua,"

+print " then check that they are still unchanged"

+a,b=nil,nil

+a=o:remove(0) -- a now owns it

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 3)")

+

+print "\nDelete the ShapeOwner (this should destroy two shapes),"

+print " but we have one left in Lua"

+o=nil

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 1)")

+

+print "\nFinal tidy up "

+a=nil

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")

+

+

+print "Final test, we will create some Shapes & pass them around like mad"

+print "If there is any memory leak, you will see it in the memory usage"

+io.flush()

+sh={}

+-- make some objects

+for i=0,10 do

+    a=example.Circle(i)

+    b=example.Square(i)

+    sh[a]=true

+    sh[b]=true

+end

+o=example.ShapeOwner()

+for i=0,10000 do

+    for k,_ in pairs(sh) do

+        o:add(k)

+    end

+    sh={}   -- clear it

+    while true do

+        a=o:remove(0)

+        if a==nil then break end

+        sh[a]=true

+    end        

+    if i%100==0 then collectgarbage() end

+end

+print "done"

+o,sh=nil,nil

+collectgarbage()

+print("Currently there are",example.Shape_nshapes,"shapes (there should be 0)")

+print "thats all folks!"
\ No newline at end of file
diff --git a/trunk/Examples/lua/pointer/Makefile b/trunk/Examples/lua/pointer/Makefile
new file mode 100644
index 0000000..ac0fff4
--- /dev/null
+++ b/trunk/Examples/lua/pointer/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/pointer/example.c b/trunk/Examples/lua/pointer/example.c
new file mode 100644
index 0000000..b877d9a
--- /dev/null
+++ b/trunk/Examples/lua/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/lua/pointer/example.i b/trunk/Examples/lua/pointer/example.i
new file mode 100644
index 0000000..d49365b
--- /dev/null
+++ b/trunk/Examples/lua/pointer/example.i
@@ -0,0 +1,35 @@
+/* File : example.i */
+%module example
+
+%{
+   #include <stdlib.h>
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+%inline %{
+extern void add(int *x, int *y, int *result);
+%}
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+%{
+extern void sub(int *, int *, int *);
+%}
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+%inline %{
+extern int divide(int n, int d, int *r);
+%}
+
+
+
+
diff --git a/trunk/Examples/lua/pointer/runme.lua b/trunk/Examples/lua/pointer/runme.lua
new file mode 100644
index 0000000..8deee67
--- /dev/null
+++ b/trunk/Examples/lua/pointer/runme.lua
@@ -0,0 +1,48 @@
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+-- First create some objects using the pointer library.
+print("Testing the pointer library")
+a = example.new_intp()
+b = example.new_intp()
+c = example.new_intp()
+example.intp_assign(a,37)
+example.intp_assign(b,42)
+
+print("     a = "..tostring(a))
+print("     b = "..tostring(b))
+print("     c = "..tostring(c))
+
+-- Call the add() function with some pointers
+example.add(a,b,c)
+
+-- Now get the result
+r = example.intp_value(c)
+print("     37 + 42 = "..r)
+
+-- Clean up the pointers
+-- since this is C-style pointers you must clean it up
+example.delete_intp(a)
+example.delete_intp(b)
+example.delete_intp(c)
+
+-- Now try the typemap library
+-- This should be much easier. Now how it is no longer
+-- necessary to manufacture pointers.
+
+print("Trying the typemap library")
+r = example.sub(37,42)
+print("     37 - 42 = "..r)
+
+-- Now try the version with multiple return values
+
+print("Testing multiple return values")
+q,r = example.divide(42,37)
+print("     42/37 = "..q.." remainder "..r)
diff --git a/trunk/Examples/lua/simple/Makefile b/trunk/Examples/lua/simple/Makefile
new file mode 100644
index 0000000..f181818
--- /dev/null
+++ b/trunk/Examples/lua/simple/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/simple/example.c b/trunk/Examples/lua/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/lua/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/lua/simple/example.i b/trunk/Examples/lua/simple/example.i
new file mode 100644
index 0000000..86ae9f3
--- /dev/null
+++ b/trunk/Examples/lua/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
\ No newline at end of file
diff --git a/trunk/Examples/lua/simple/runme.lua b/trunk/Examples/lua/simple/runme.lua
new file mode 100644
index 0000000..1e5a139
--- /dev/null
+++ b/trunk/Examples/lua/simple/runme.lua
@@ -0,0 +1,35 @@
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+-- Call our gcd() function
+x = 42
+y = 105
+g = example.gcd(x,y)
+print("The gcd of",x,"and",y,"is",g)
+
+-- Manipulate the Foo global variable
+
+-- Output its current value
+print("Foo = ", example.Foo)
+
+-- Change its value
+example.Foo = 3.1415926
+
+-- See if the change took effect
+print("Foo = ", example.Foo)
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/lua/variables/Makefile b/trunk/Examples/lua/variables/Makefile
new file mode 100644
index 0000000..f181818
--- /dev/null
+++ b/trunk/Examples/lua/variables/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile lua_clean
+
+check: all
diff --git a/trunk/Examples/lua/variables/example.c b/trunk/Examples/lua/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/lua/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/lua/variables/example.h b/trunk/Examples/lua/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/lua/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/lua/variables/example.i b/trunk/Examples/lua/variables/example.i
new file mode 100644
index 0000000..591b871
--- /dev/null
+++ b/trunk/Examples/lua/variables/example.i
@@ -0,0 +1,49 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/lua/variables/runme.lua b/trunk/Examples/lua/variables/runme.lua
new file mode 100644
index 0000000..05b2d3f
--- /dev/null
+++ b/trunk/Examples/lua/variables/runme.lua
@@ -0,0 +1,81 @@
+---- importing ----
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	-- lua5.0 doesnt have a nice way to do this
+	lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
+	assert(lib)()
+else
+	-- lua 5.1 does
+	require('example')
+end
+
+-- Try to set the values of some global variables
+
+example.ivar   =  42
+example.svar   = -31000
+example.lvar   =  65537
+example.uivar  =  123456
+example.usvar  =  61000
+example.ulvar  =  654321
+example.scvar  =  -13
+example.ucvar  =  251
+example.cvar   =  "S"
+example.fvar   =  3.14159
+example.dvar   =  2.1828
+example.strvar =  "Hello World"
+example.iptrvar= example.new_int(37)
+example.ptptr  = example.new_Point(37,42)
+example.name   = "Bill"
+
+-- Now print out the values of the variables
+
+print("Variables (values printed from Lua)")
+
+print("ivar      =", example.ivar)
+print("svar      =", example.svar)
+print("lvar      =", example.lvar)
+print("uivar     =", example.uivar)
+print("usvar     =", example.usvar)
+print("ulvar     =", example.ulvar)
+print("scvar     =", example.scvar)
+print("ucvar     =", example.ucvar)
+print("fvar      =", example.fvar)
+print("dvar      =", example.dvar)
+print("cvar      =", example.cvar)
+print("strvar    =", example.strvar)
+print("cstrvar   =", example.cstrvar)
+print("iptrvar   =", example.iptrvar)
+print("name      =", example.name)
+print("ptptr     =", example.ptptr, example.Point_print(example.ptptr))
+print("pt        =", example.pt, example.Point_print(example.pt))
+
+print("\nVariables (values printed from C)")
+
+example.print_vars()
+
+print "\nNow I'm going to try and modify some read only variables";
+
+print "     Tring to set 'path' to 'Whoa!'";
+if pcall(function() example.path = "Whoa!" end)==true then
+	print "     Thats funny, it didn't give an error!"
+else
+	print "     It gave an error, as it should"
+end
+print("     Just checking the value: path      =", example.path)
+
+print "     Trying to set 'status' to '0'";
+if pcall(function() example.status = 0 end)==true then
+	print "     Thats funny, it didn't give an error!"
+else
+	print "     It gave an error, as it should"
+end
+print("     Just checking the value: status    =", example.status)
+
+
+print "\nI'm going to try and update a structure variable.\n"
+
+example.pt = example.ptptr
+
+print "The new value is"
+example.pt_print()
+print("You should see the value", example.Point_print(example.ptptr))
+
diff --git a/trunk/Examples/modula3/check.list b/trunk/Examples/modula3/check.list
new file mode 100644
index 0000000..37ac8c1
--- /dev/null
+++ b/trunk/Examples/modula3/check.list
@@ -0,0 +1,7 @@
+# see top-level Makefile.in
+class
+enum
+exception
+reference
+simple
+typemap
diff --git a/trunk/Examples/modula3/class/Makefile b/trunk/Examples/modula3/class/Makefile
new file mode 100644
index 0000000..bf929a0
--- /dev/null
+++ b/trunk/Examples/modula3/class/Makefile
@@ -0,0 +1,25 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+PLATFORM   = LINUXLIBC6
+INTERFACE  = example.i
+SWIGOPT    = -c++
+MODULA3SRCS = *.[im]3
+
+all::	modula3
+
+modula3::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3
+	m3ppinplace $(MODULA3SRCS)
+# compilation of example_wrap.cxx is started by cm3
+#	$(CXX) -c $(TARGET)_wrap.cxx
+	mv example_wrap.cxx m3makefile $(MODULA3SRCS) src/
+	ln -sf ../example.h src/example.h
+	cm3
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile modula3_clean
+
+check: all
diff --git a/trunk/Examples/modula3/class/example.cxx b/trunk/Examples/modula3/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/modula3/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/modula3/class/example.h b/trunk/Examples/modula3/class/example.h
new file mode 100644
index 0000000..9c1f479
--- /dev/null
+++ b/trunk/Examples/modula3/class/example.h
@@ -0,0 +1,44 @@
+/* File : example.h */
+
+class Shape
+{
+public:
+  Shape ()
+  {
+    nshapes++;
+  }
+  virtual ~ Shape ()
+  {
+    nshapes--;
+  };
+  double x, y;
+  void move (double dx, double dy);
+  virtual double area (void) const = 0;
+  virtual double perimeter (void) const = 0;
+protected:
+  static int nshapes;
+};
+
+class Circle:public Shape
+{
+private:
+  double radius;
+public:
+    Circle (double r):radius (r)
+  {
+  };
+  virtual double area (void) const;
+  virtual double perimeter (void) const;
+};
+
+class Square:public Shape
+{
+private:
+  double width;
+public:
+    Square (double w):width (w)
+  {
+  };
+  virtual double area (void) const;
+  virtual double perimeter (void) const;
+};
diff --git a/trunk/Examples/modula3/class/example.i b/trunk/Examples/modula3/class/example.i
new file mode 100644
index 0000000..2fafadb
--- /dev/null
+++ b/trunk/Examples/modula3/class/example.i
@@ -0,0 +1,32 @@
+/* File : example.i */
+%module Example
+
+%{
+#include "example.h"
+%}
+
+%insert(m3makefile) %{template("../swig")
+cxx_source("example_wrap")%}
+
+%typemap(m3rawinmode)    Shape *, Circle *, Square * ""
+%typemap(m3rawrettype)   Shape *, Circle *, Square * "$1_basetype"
+
+%typemap(m3wrapinmode)   Shape *, Circle *, Square * ""
+%typemap(m3wrapargraw)   Shape *, Circle *, Square * "self.cxxObj"
+
+%typemap(m3wrapretvar)   Circle *, Square * "cxxObj : ExampleRaw.$1_basetype;"
+%typemap(m3wrapretraw)   Circle *, Square * "cxxObj"
+%typemap(m3wrapretconv)  Circle *, Square * "NEW($1_basetype,cxxObj:=cxxObj)"
+%typemap(m3wraprettype)  Circle *, Square * "$1_basetype"
+
+/* Should work with and without renaming
+%rename(M3Shape) Shape;
+%rename(M3Circle) Circle;
+%rename(M3Square) Square;
+%typemap(m3wrapintype)   Shape *, Circle *, Square * "M3$1_basetype"
+%typemap(m3wraprettype)  Shape *, Circle *, Square * "M3$1_basetype"
+%typemap(m3wrapretconv)           Circle *, Square * "NEW(M3$1_basetype,cxxObj:=cxxObj)"
+*/
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/trunk/Examples/modula3/class/swig.tmpl b/trunk/Examples/modula3/class/swig.tmpl
new file mode 100644
index 0000000..e3e9bf1
--- /dev/null
+++ b/trunk/Examples/modula3/class/swig.tmpl
@@ -0,0 +1,11 @@
+
+readonly proc cxx_source (X) is
+  local cxxfile = X&".cxx"
+  local objfile = X&".o"
+  %exec("echo $PWD")
+  if stale(objfile,cxxfile)
+    exec("cd",path(),"; g++ -I.. -c -o",objfile,cxxfile)
+  end
+  import_obj(X)
+  %unlink_file(path()&SL&objfile)
+end
diff --git a/trunk/Examples/modula3/enum/Makefile b/trunk/Examples/modula3/enum/Makefile
new file mode 100644
index 0000000..b5bf8f6
--- /dev/null
+++ b/trunk/Examples/modula3/enum/Makefile
@@ -0,0 +1,26 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+CONSTNUMERIC = example_const
+SWIGOPT      = -c++
+MODULA3SRCS  = *.[im]3
+
+all::	modula3
+
+modula3::
+	$(SWIG) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h
+	$(CXX) -Wall $(CONSTNUMERIC).c -o $(CONSTNUMERIC)
+	$(CONSTNUMERIC) >$(CONSTNUMERIC).i
+
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3
+	m3ppinplace $(MODULA3SRCS)
+	mv m3makefile $(MODULA3SRCS) src/
+	cm3
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile modula3_clean
+
+check: all
diff --git a/trunk/Examples/modula3/enum/example.cxx b/trunk/Examples/modula3/enum/example.cxx
new file mode 100644
index 0000000..bd808ff
--- /dev/null
+++ b/trunk/Examples/modula3/enum/example.cxx
@@ -0,0 +1,32 @@
+/* File : example.cxx */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else if (s == HYPER) {
+    printf("HYPER speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  Foo obj;
+  obj.enum_test(s);
+}
diff --git a/trunk/Examples/modula3/enum/example.h b/trunk/Examples/modula3/enum/example.h
new file mode 100644
index 0000000..2f44a6c
--- /dev/null
+++ b/trunk/Examples/modula3/enum/example.h
@@ -0,0 +1,83 @@
+/* File : example.h */
+
+#define PI 3.141
+
+#define DAY_MONDAY    0
+#define DAY_TUESDAY   1
+#define DAY_WEDNESDAY 2
+#define DAY_THURSDAY  3
+#define DAY_FRIDAY    4
+#define DAY_SATURDAY  5
+#define DAY_SUNDAY    6
+
+enum color { BLUE, RED, GREEN };
+
+#define CLB_BLACK   0
+#define CLB_BLUE    1
+#define CLB_RED     2
+#define CLB_MAGENTA 3
+#define CLB_GREEN   4
+#define CLB_CYAN    5
+#define CLB_YELLOW  6
+#define CLB_WHITE   7
+
+/* Using this would be good style
+   which cannot be expected for general C header files.
+   Instead I want to demonstrate how to live without it.
+enum month {
+  MTHF_JANUARY,
+  MTHF_FEBRUARY,
+  MTHF_MARCH,
+  MTHF_APRIL,
+  MTHF_MAY,
+  MTHF_JUNE,
+  MTHF_JULY,
+  MTHF_AUGUST,
+  MTHF_SEPTEMBER,
+  MTHF_OCTOBER,
+  MTHF_NOVEMBER,
+  MTHF_DECEMBER,
+}
+*/
+
+/* Since there are no compile time constants in C / C++
+   it is a common abuse
+   to declare bit set (flag) constants
+   as enumerations. */
+enum calendar {
+  MTHB_JANUARY   = 1 <<  0,     /* 1 << MTHF_JANUARY, */
+  MTHB_FEBRUARY  = 1 <<  1,     /* 1 << MTHF_FEBRUARY, */
+  MTHB_MARCH     = 1 <<  2,     /* 1 << MTHF_MARCH, */
+  MTHB_APRIL     = 1 <<  3,     /* 1 << MTHF_APRIL, */
+  MTHB_MAY       = 1 <<  4,     /* 1 << MTHF_MAY, */
+  MTHB_JUNE      = 1 <<  5,     /* 1 << MTHF_JUNE, */
+  MTHB_JULY      = 1 <<  6,     /* 1 << MTHF_JULY, */
+  MTHB_AUGUST    = 1 <<  7,     /* 1 << MTHF_AUGUST, */
+  MTHB_SEPTEMBER = 1 <<  8,     /* 1 << MTHF_SEPTEMBER, */
+  MTHB_OCTOBER   = 1 <<  9,     /* 1 << MTHF_OCTOBER, */
+  MTHB_NOVEMBER  = 1 << 10,     /* 1 << MTHF_NOVEMBER, */
+  MTHB_DECEMBER  = 1 << 11,     /* 1 << MTHF_DECEMBER, */
+
+  MTHB_SPRING    = MTHB_MARCH     | MTHB_APRIL   | MTHB_MAY,
+  MTHB_SUMMER    = MTHB_JUNE      | MTHB_JULY    | MTHB_AUGUST,
+  MTHB_AUTUMN    = MTHB_SEPTEMBER | MTHB_OCTOBER | MTHB_NOVEMBER,
+  MTHB_WINTER    = MTHB_DECEMBER  | MTHB_JANUARY | MTHB_FEBRUARY,
+};
+
+
+namespace Answer {
+  enum {
+    UNIVERSE_AND_EVERYTHING = 42,
+    SEVENTEEN_AND_FOUR = 21,
+    TWOHUNDRED_PERCENT_OF_NOTHING = 0,
+  };
+
+  class Foo {
+   public:
+    Foo() { }
+    enum speed { IMPULSE  = -2, WARP = 0, HYPER, LUDICROUS = 3};
+    void enum_test(speed s);
+  };
+};
+
+void enum_test(color c, Answer::Foo::speed s);
diff --git a/trunk/Examples/modula3/enum/example.i b/trunk/Examples/modula3/enum/example.i
new file mode 100644
index 0000000..f5947b3
--- /dev/null
+++ b/trunk/Examples/modula3/enum/example.i
@@ -0,0 +1,72 @@
+/* File : example.i */
+%module Example
+
+%{
+#include "example.h"
+%}
+
+%include "example_const.i"
+
+// such features are generated by the following pragmas
+#if 0
+%feature("modula3:enumitem:enum","Days")    DAY_MONDAY;
+%feature("modula3:enumitem:name","monday")  DAY_MONDAY;
+%feature("modula3:enumitem:conv","int:int") DAY_MONDAY;
+
+%feature("modula3:enumitem:enum","Month")     MTHB_JANUARY;
+%feature("modula3:enumitem:name","january")   MTHB_JANUARY;
+%feature("modula3:enumitem:conv","set:int")   MTHB_JANUARY;
+//%feature("modula3:constset:type","MonthSet")      MTHB_JANUARY;  /*type in the constant definition*/
+%feature("modula3:constset:set", "MonthSet")      MTHB_JANUARY;  /*remarks that the 'type' is a set type*/
+%feature("modula3:constset:base","Month")         MTHB_JANUARY;
+%feature("modula3:constset:name","monthsJanuary") MTHB_JANUARY;
+%feature("modula3:constset:conv","set:set")       MTHB_JANUARY;  /*conversion of the bit pattern: no change*/
+
+%feature("modula3:enumitem:enum","Color")     BLUE;
+%feature("modula3:enumitem:name","blue")      BLUE;
+%feature("modula3:enumitem:conv","int:int")   BLUE;
+
+%feature("modula3:constint:type","INTEGER") Foo::IMPULSE;
+%feature("modula3:constint:name","impulse") Foo::IMPULSE;
+%feature("modula3:constint:conv","int:int") Foo::IMPULSE;
+#endif
+
+%rename(pi) PI;
+
+%pragma(modula3) enumitem="prefix=DAY_;int;srcstyle=underscore;Day";
+
+%pragma(modula3) enumitem="enum=color;int;srcstyle=underscore;Color";
+%pragma(modula3) makesetofenum="Color";
+%pragma(modula3) constset="prefix=CLB_;set;srcstyle=underscore,prefix=clb;ColorSet,Color";
+
+%pragma(modula3) enumitem="prefix=MTHB_,enum=calendar;set;srcstyle=underscore;Month";
+%pragma(modula3) makesetofenum="Month";
+%pragma(modula3) constset="prefix=MTHB_,enum=calendar;set;srcstyle=underscore,prefix=monthset;MonthSet,Month";
+
+%pragma(modula3) constint="prefix=Answer::Foo::,enum=Answer::Foo::speed;int;srcstyle=underscore,prefix=speed;INTEGER";
+
+%pragma(modula3) constint="prefix=Answer::,enum=Answer::;int;srcstyle=underscore,prefix=answer;CARDINAL";
+
+%rename(AnswerFoo) Answer::Foo;
+%typemap("m3rawrettype")   Answer::Foo * %{AnswerFoo%}
+%typemap("m3rawintype")    Answer::Foo * %{AnswerFoo%}
+%typemap("m3rawinmode")    Answer::Foo * %{%}
+%typemap("m3wraprettype")  Answer::Foo * %{AnswerFoo%}
+%typemap("m3wrapintype")   Answer::Foo * %{AnswerFoo%}
+%typemap("m3wrapinmode")   Answer::Foo * %{%}
+%typemap("m3wrapargraw")   Answer::Foo * %{self.cxxObj%}
+
+%typemap("m3wrapretvar")   Answer::Foo * %{cxxObj : ExampleRaw.AnswerFoo;%}
+%typemap("m3wrapretraw")   Answer::Foo * %{cxxObj%}
+%typemap("m3wrapretconv")  Answer::Foo * %{NEW(AnswerFoo,cxxObj:=cxxObj)%}
+
+
+%typemap("m3rawintype")        Answer::Foo::speed %{C.int%};
+%typemap("m3rawintype:import") Answer::Foo::speed %{Ctypes AS C%};
+%typemap("m3wrapintype")       Answer::Foo::speed %{[-2..3]%};
+
+%typemap("m3wrapintype")       color %{Color%};
+%typemap("m3wrapargraw")       color %{ORD($1_name)%};
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/trunk/Examples/modula3/exception/Makefile b/trunk/Examples/modula3/exception/Makefile
new file mode 100644
index 0000000..2518a22
--- /dev/null
+++ b/trunk/Examples/modula3/exception/Makefile
@@ -0,0 +1,23 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+MODULA3SRCS = *.[im]3
+MODULA3FLAGS= -o runme
+
+all::	modula3
+
+modula3::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3_cpp
+#	$(MAKE) -f $(TOP)/Makefile MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile
+	m3ppinplace $(MODULA3SRCS)
+	mv m3makefile $(MODULA3SRCS) src/
+	cm3
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile modula3_clean
+
+check: all
diff --git a/trunk/Examples/modula3/exception/example.h b/trunk/Examples/modula3/exception/example.h
new file mode 100644
index 0000000..0e9e0e8
--- /dev/null
+++ b/trunk/Examples/modula3/exception/example.h
@@ -0,0 +1,18 @@
+/* File : example.h */
+
+enum error {OK, OVERFLOW, DIVISION_BY_ZERO, NEGATIVE_RADICAND, NEGATIVE_BASE};
+typedef error errorstate;  /* just to separate the typemaps */
+
+error acc_add (double &x, double y);
+error acc_sub (double &x, double y);
+error acc_mul (double &x, double y);
+error acc_div (double &x, double y);
+
+double op_add (double x, double y, errorstate &err);
+double op_sub (double x, double y, errorstate &err);
+double op_mul (double x, double y, errorstate &err);
+double op_div (double x, double y, errorstate &err);
+double op_sqrt (double x, errorstate &err);
+double op_pow (double x, double y, errorstate &err);
+
+double op_noexc (double x, double y);
diff --git a/trunk/Examples/modula3/exception/example.i b/trunk/Examples/modula3/exception/example.i
new file mode 100644
index 0000000..92a716f
--- /dev/null
+++ b/trunk/Examples/modula3/exception/example.i
@@ -0,0 +1,43 @@
+/* File : example.i */
+%module Example
+
+%{
+#include "example.h"
+%}
+
+%insert(m3wrapintf) %{
+EXCEPTION E(Error);
+%}
+%insert(m3wrapimpl) %{
+IMPORT Ctypes AS C;
+%}
+
+%pragma(modula3) enumitem="enum=error;int;srcstyle=underscore;Error";
+
+%typemap("m3rawintype")   double & %{C.double%};
+%typemap("m3wrapintype")  double & %{LONGREAL%};
+
+%typemap("m3wraprettype") error ""
+%typemap("m3wrapretvar") error "rawerr: C.int;"
+%typemap("m3wrapretraw")  error "rawerr"
+%typemap("m3wrapretcheck:throws") error "E"
+%typemap("m3wrapretcheck") error
+%{VAR err := VAL(rawerr, Error);
+BEGIN
+IF err # Error.ok THEN
+RAISE E(err);
+END;
+END;%}
+
+%typemap("m3rawintype")              errorstate & %{C.int%};
+%typemap("m3wrapintype",numinputs=0) errorstate & %{%};
+%typemap("m3wrapargvar")             errorstate & %{err:C.int:=ORD(Error.ok);%};
+%typemap("m3wrapoutcheck:throws")    errorstate & "E";
+%typemap("m3wrapoutcheck")           errorstate &
+%{IF VAL(err,Error) # Error.ok THEN
+RAISE E(VAL(err,Error));
+END;%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
diff --git a/trunk/Examples/modula3/reference/Makefile b/trunk/Examples/modula3/reference/Makefile
new file mode 100644
index 0000000..b31577a
--- /dev/null
+++ b/trunk/Examples/modula3/reference/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = -c++
+MODULA3SRCS = *.[im]3
+
+all::	modula3
+
+modula3::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3
+	m3ppinplace $(MODULA3SRCS)
+	mv m3makefile $(MODULA3SRCS) src/
+	cm3
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile modula3_clean
+
+check: all
diff --git a/trunk/Examples/modula3/reference/example.cxx b/trunk/Examples/modula3/reference/example.cxx
new file mode 100644
index 0000000..649b016
--- /dev/null
+++ b/trunk/Examples/modula3/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %x (%g,%g,%g)", (int)this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/modula3/reference/example.h b/trunk/Examples/modula3/reference/example.h
new file mode 100644
index 0000000..0a9cd44
--- /dev/null
+++ b/trunk/Examples/modula3/reference/example.h
@@ -0,0 +1,22 @@
+/* File : example.h */
+
+struct Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  Vector operator+(const Vector &b) const;
+  char *print();
+};
+
+struct VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
diff --git a/trunk/Examples/modula3/reference/example.i b/trunk/Examples/modula3/reference/example.i
new file mode 100644
index 0000000..0020909
--- /dev/null
+++ b/trunk/Examples/modula3/reference/example.i
@@ -0,0 +1,32 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module Example
+
+%{
+#include "example.h"
+%}
+
+%pragma(modula3) unsafe="1";
+
+%insert(m3wrapintf) %{FROM ExampleRaw IMPORT Vector, VectorArray;%}
+%insert(m3wrapimpl) %{FROM ExampleRaw IMPORT Vector, VectorArray;%}
+
+%typemap(m3wrapretvar)  Vector %{vec: UNTRACED REF Vector;%}
+%typemap(m3wrapretraw)  Vector %{vec%}
+%typemap(m3wrapretconv) Vector %{vec^%}
+
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(const Vector &a, const Vector &b) {
+  return a+b;
+}
+%}
+
+%rename(Vector_Clear) Vector::Vector();
+%rename(Add) Vector::operator+;
+%rename(GetItem) VectorArray::operator[];
+
+%include "example.h"
diff --git a/trunk/Examples/modula3/simple/Makefile b/trunk/Examples/modula3/simple/Makefile
new file mode 100644
index 0000000..834521f
--- /dev/null
+++ b/trunk/Examples/modula3/simple/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+MODULA3SRCS = *.[im]3
+
+all::	modula3
+
+modula3::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3
+	m3ppinplace $(MODULA3SRCS)
+	mv m3makefile $(MODULA3SRCS) src/
+	cm3
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile modula3_clean
+
+check: all
diff --git a/trunk/Examples/modula3/simple/example.c b/trunk/Examples/modula3/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/modula3/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/modula3/simple/example.i b/trunk/Examples/modula3/simple/example.i
new file mode 100644
index 0000000..1694e6d
--- /dev/null
+++ b/trunk/Examples/modula3/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module Example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/modula3/typemap/Makefile b/trunk/Examples/modula3/typemap/Makefile
new file mode 100644
index 0000000..834521f
--- /dev/null
+++ b/trunk/Examples/modula3/typemap/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+MODULA3SRCS = *.[im]3
+
+all::	modula3
+
+modula3::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3
+	m3ppinplace $(MODULA3SRCS)
+	mv m3makefile $(MODULA3SRCS) src/
+	cm3
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile modula3_clean
+
+check: all
diff --git a/trunk/Examples/modula3/typemap/example.i b/trunk/Examples/modula3/typemap/example.i
new file mode 100644
index 0000000..2f454ef
--- /dev/null
+++ b/trunk/Examples/modula3/typemap/example.i
@@ -0,0 +1,90 @@
+/* File : example.i */
+%module Example
+
+%pragma(modula3) unsafe="true";
+
+%insert(m3wrapintf) %{FROM ExampleRaw IMPORT Window, Point;
+%}
+%insert(m3wrapimpl) %{FROM ExampleRaw IMPORT Window, Point;
+IMPORT M3toC;
+IMPORT Ctypes AS C;
+%}
+
+/* Typemap applied to patterns of multiple arguments */
+
+%typemap(m3rawinmode)   (char *outstr) %{VAR%}
+%typemap(m3rawintype)   (char *outstr) %{CHAR%}
+%typemap(m3wrapinmode)  (char *outstr, int size) %{VAR%}
+%typemap(m3wrapintype)  (char *outstr, int size) %{ARRAY OF CHAR%}
+%typemap(m3wrapargraw)  (char *outstr, int size) %{$1_name[0], NUMBER($1_name)%}
+
+
+%typemap(m3rawinmode)   (const struct Window *) %{READONLY%}
+%typemap(m3wrapinmode)  (const struct Window *) %{READONLY%}
+%typemap(m3rawintype)   (      struct Window *) %{Window%}
+%typemap(m3wrapintype)  (      struct Window *) %{Window%}
+
+%typemap(m3rawinmode)   (const char *str []) %{READONLY%}
+%typemap(m3wrapinmode)  (const char *str []) %{READONLY%}
+%typemap(m3rawintype)   (const char *str []) %{(*ARRAY OF*) C.char_star%}
+%typemap(m3wrapintype)  (const char *str []) %{ARRAY OF TEXT%}
+%typemap(m3wrapargvar)  (const char *str []) %{$1: REF ARRAY OF C.char_star;%}
+%typemap(m3wrapargraw)  (const char *str []) %{$1[0]%}
+%typemap(m3wrapinconv)  (const char *str []) %{$1:= NEW(REF ARRAY OF C.char_star,NUMBER($1_name));
+FOR i:=FIRST($1_name) TO LAST($1_name) DO
+$1[i]:=M3toC.SharedTtoS($1_name[i]);
+END;%}
+%typemap(m3wrapfreearg) (const char *str [])
+%{FOR i:=FIRST($1_name) TO LAST($1_name) DO
+M3toC.FreeSharedS($1_name[i],$1[i]);
+END;%}
+
+%typemap(m3wraprettype) char * %{TEXT%}
+%typemap(m3wrapretvar)  char * %{result_string: C.char_star;%}
+%typemap(m3wrapretraw)  char * %{result_string%}
+%typemap(m3wrapretconv) char * %{M3toC.CopyStoT(result_string)%}
+
+struct Window {
+  char *label;
+  int left,top,width,height;
+};
+
+
+%typemap(m3wrapinname) (int x, int y) %{p%}
+%typemap(m3wrapinmode) (int x, int y) %{READONLY%}
+%typemap(m3wrapintype) (int x, int y) %{Point%}
+%typemap(m3wrapargraw) (int x, int y) %{p.$1_name, p.$2_name%}
+
+%typemap(m3wrapargraw)  (int &x, int &y) %{p.$1_name, p.$2_name%}
+%typemap(m3wrapintype)  (int &x, int &y) %{Point%}
+%typemap(m3wrapoutname) (int &x, int &y) %{p%}
+%typemap(m3wrapouttype) (int &x, int &y) %{Point%}
+%typemap(m3wrapargdir)  (int &x, int &y) "out"
+
+
+%typemap(m3wrapargvar)  int &left, int &top, int &width, int &height "$1:C.int;"
+%typemap(m3wrapargraw)  int &left, int &top, int &width, int &height "$1"
+%typemap(m3wrapoutconv) int &left, int &top, int &width, int &height "$1"
+
+%typemap(m3wrapargdir)  int &left, int &top "out"
+
+%typemap(m3wrapouttype) int &width, int &height "CARDINAL"
+%typemap(m3wrapargdir)  int &width, int &height "out"
+
+struct Point {
+  int x,y;
+};
+
+%m3multiretval get_box;
+
+void  set_label       (      struct Window *win, const char *str, bool activate);
+void  set_multi_label (      struct Window *win, const char *str []);
+void  write_label     (const struct Window *win,       char *outstr, int size);
+int   get_label       (const struct Window *win,       char *outstr, int size);
+char *get_label_ptr   (const struct Window *win);
+void  move(struct Window *win, int x, int y);
+int   get_area(const struct Window *win);
+void  get_box(const struct Window *win, int &left, int &top, int &width, int &height);
+void  get_left(const struct Window *win, int &left);
+void  get_mouse(const struct Window *win, int &x, int &y);
+int   get_attached_data(const struct Window *win, const char *id);
diff --git a/trunk/Examples/mzscheme/check.list b/trunk/Examples/mzscheme/check.list
new file mode 100644
index 0000000..ae728ea
--- /dev/null
+++ b/trunk/Examples/mzscheme/check.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+multimap
+simple
diff --git a/trunk/Examples/mzscheme/multimap/Makefile b/trunk/Examples/mzscheme/multimap/Makefile
new file mode 100644
index 0000000..a3cfb8f
--- /dev/null
+++ b/trunk/Examples/mzscheme/multimap/Makefile
@@ -0,0 +1,13 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' mzscheme
+clean::
+	$(MAKE) -f $(TOP)/Makefile mzscheme_clean
+
+check: all
diff --git a/trunk/Examples/mzscheme/multimap/example.c b/trunk/Examples/mzscheme/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/mzscheme/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/mzscheme/multimap/example.i b/trunk/Examples/mzscheme/multimap/example.i
new file mode 100644
index 0000000..515948a
--- /dev/null
+++ b/trunk/Examples/mzscheme/multimap/example.i
@@ -0,0 +1,91 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+%include typemaps.i
+
+extern int    gcd(int x, int y);
+
+%typemap(in) (int argc, char *argv[]) {
+  int i;
+  Scheme_Object **elms;
+  if (!SCHEME_VECTORP($input)) {
+    scheme_wrong_type("$name","vector",$argnum,argc,argv);
+  }
+  $1 = SCHEME_VEC_SIZE($input);
+  elms = SCHEME_VEC_ELS($input);
+  if ($1 == 0) {
+    scheme_wrong_type("$name","vector",$argnum,argc,argv);
+  }
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i < $1; i++) {
+    if (!SCHEME_STRINGP(elms[i])) {
+      free($2);
+      scheme_wrong_type("$name","vector",$argnum,argc,argv);      
+    }
+    $2[i] = SCHEME_STR_VAL(elms[i]);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char *argv[]) {
+  free($2);
+}
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  if (!SCHEME_STRINGP($input)) {
+     scheme_wrong_type("$name","string",1,argc,argv);
+  }	
+  $1 = SCHEME_STR_VAL($input);
+  $2 = SCHEME_STRLEN_VAL($input);
+}
+
+extern int count(char *bytes, int len, char c);
+
+
+/* This example shows how to wrap a function that mutates a string */
+
+%typemap(in) (char *str, int len) {
+  if (!SCHEME_STRINGP($input)) {
+     scheme_wrong_type("$name","string",1,argc,argv);
+  }	
+  $2 = SCHEME_STRLEN_VAL($input);
+  $1 = (char *) malloc($2+1);
+  memmove($1,SCHEME_STR_VAL($input),$2);
+}
+
+/* Return the mutated string as a new object.  */
+
+%typemap(argout) (char *str, int len) {
+   Scheme_Object *s;
+   s = scheme_make_sized_string($1,$2,1);
+   SWIG_APPEND_VALUE(s);
+   free($1);
+}   
+
+extern void capitalize(char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
+        return NULL;
+   }
+}
+
+extern void circle(double cx, double cy);
+
+
diff --git a/trunk/Examples/mzscheme/multimap/example.scm b/trunk/Examples/mzscheme/multimap/example.scm
new file mode 100644
index 0000000..ac9f642
--- /dev/null
+++ b/trunk/Examples/mzscheme/multimap/example.scm
@@ -0,0 +1,27 @@
+;; run with mzscheme -r example.scm
+
+(load-extension "example.so")
+
+; Call the GCD function
+
+(define x 42)
+(define y 105)
+(define g (gcd x y))
+
+(display "The gcd of ")
+(display x)
+(display " and ")
+(display y)
+(display " is ")
+(display g)
+(newline)
+
+;  Call the gcdmain() function
+(gcdmain #("gcdmain" "42" "105"))
+
+
+(display (count "Hello World" #\l))
+(newline)
+
+(display (capitalize "hello world"))
+(newline)
\ No newline at end of file
diff --git a/trunk/Examples/mzscheme/simple/Makefile b/trunk/Examples/mzscheme/simple/Makefile
new file mode 100644
index 0000000..a3cfb8f
--- /dev/null
+++ b/trunk/Examples/mzscheme/simple/Makefile
@@ -0,0 +1,13 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' mzscheme
+clean::
+	$(MAKE) -f $(TOP)/Makefile mzscheme_clean
+
+check: all
diff --git a/trunk/Examples/mzscheme/simple/README b/trunk/Examples/mzscheme/simple/README
new file mode 100644
index 0000000..07e8da0
--- /dev/null
+++ b/trunk/Examples/mzscheme/simple/README
@@ -0,0 +1 @@
+Simple example from users manual.
diff --git a/trunk/Examples/mzscheme/simple/example.c b/trunk/Examples/mzscheme/simple/example.c
new file mode 100644
index 0000000..f2b0747
--- /dev/null
+++ b/trunk/Examples/mzscheme/simple/example.c
@@ -0,0 +1,24 @@
+/* Simple example from documentation */
+/* File : example.c */
+
+#include <time.h>
+
+double My_variable = 3.0;
+
+/* Compute factorial of n */
+int fact(int n) {
+  if (n <= 1) return 1;
+  else return n*fact(n-1);
+}
+
+/* Compute n mod m */
+int my_mod(int n, int m) {
+  return (n % m);
+}
+
+
+char *get_time() {
+    long            ltime;
+    time(&ltime);
+    return ctime(&ltime);
+}
diff --git a/trunk/Examples/mzscheme/simple/example.i b/trunk/Examples/mzscheme/simple/example.i
new file mode 100644
index 0000000..5b3e955
--- /dev/null
+++ b/trunk/Examples/mzscheme/simple/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+/* Put headers and other declarations here */
+%}
+
+%include typemaps.i
+
+%rename(mod) my_mod;
+
+%inline %{
+extern double My_variable;
+extern int    fact(int);
+extern int    my_mod(int n, int m);
+extern char   *get_time();
+%}
diff --git a/trunk/Examples/mzscheme/simple/example.scm b/trunk/Examples/mzscheme/simple/example.scm
new file mode 100644
index 0000000..8e20345
--- /dev/null
+++ b/trunk/Examples/mzscheme/simple/example.scm
@@ -0,0 +1,24 @@
+;; run with mzscheme -r example.scm
+
+(load-extension "example.so")
+
+(display (get-time))
+
+(printf "My-variable = ~a~n" (my-variable))
+
+(let loop ((i 0))
+  (when (< i 14) (begin (display i)
+			(display " factorial is ")
+			(display (fact i))
+			(newline)
+			(loop (+ i 1)))))
+
+(let loop ((i 1))
+  (when (< i 250)
+	(begin
+	  (let loopi ((j 1))
+	    (when (< j 250) (begin (my-variable (+ (my-variable) (mod i j)))
+				   (loopi (+ j 1)))))
+	  (loop (+ i 1)))))
+
+(printf "My-variable = ~a~n" (my-variable))
diff --git a/trunk/Examples/mzscheme/std_vector/Makefile b/trunk/Examples/mzscheme/std_vector/Makefile
new file mode 100644
index 0000000..e187269
--- /dev/null
+++ b/trunk/Examples/mzscheme/std_vector/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+
+GPP        = `which g++`
+MZC        = test -n "/usr/bin/mzc" && /usr/bin/mzc
+
+all::
+	$(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACE)
+	$(MZC) --compiler $(GPP) ++ccf "-I." --cc example_wrap.cxx
+	$(MZC) --linker $(GPP) --ld $(TARGET).so example_wrap.o 
+	
+clean:
+	$(MAKE) -f $(TOP)/Makefile mzscheme_clean
+
+check: all
diff --git a/trunk/Examples/mzscheme/std_vector/example.h b/trunk/Examples/mzscheme/std_vector/example.h
new file mode 100644
index 0000000..4f0dac7
--- /dev/null
+++ b/trunk/Examples/mzscheme/std_vector/example.h
@@ -0,0 +1,25 @@
+/* File : example.h */
+
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<double> half(const std::vector<double>& v) {
+    std::vector<double> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    // would you believe this is the same as the above?
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+
diff --git a/trunk/Examples/mzscheme/std_vector/example.i b/trunk/Examples/mzscheme/std_vector/example.i
new file mode 100644
index 0000000..aa58b66
--- /dev/null
+++ b/trunk/Examples/mzscheme/std_vector/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+/* instantiate the required template specializations */
+namespace std {
+    %template(IntVector)    vector<int>;
+    %template(DoubleVector) vector<double>;
+}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/mzscheme/std_vector/example.scm b/trunk/Examples/mzscheme/std_vector/example.scm
new file mode 100644
index 0000000..0e4ac3f
--- /dev/null
+++ b/trunk/Examples/mzscheme/std_vector/example.scm
@@ -0,0 +1,54 @@
+;; run with mzscheme -r example.scm
+
+(load-extension "example.so")
+
+; repeatedly invoke a procedure with v and an index as arguments
+(define (with-vector v proc size-proc)
+  (let ((size (size-proc v)))
+    (define (with-vector-item v i)
+      (if (< i size)
+          (begin
+            (proc v i)
+            (with-vector-item v (+ i 1)))))
+    (with-vector-item v 0)))
+
+(define (with-intvector v proc)
+  (with-vector v proc intvector-length))
+(define (with-doublevector v proc)
+  (with-vector v proc doublevector-length))
+
+(define (print-doublevector v)
+  (with-doublevector v (lambda (v i) (display (doublevector-ref v i)) 
+                                     (display " ")))
+  (newline))
+
+
+; Call average with a Scheme list...
+
+(display (average '(1 2 3 4)))
+(newline)
+
+; ... or a wrapped std::vector<int>
+(define v (new-intvector 4))
+(with-intvector v (lambda (v i) (intvector-set! v i (+ i 1))))
+(display (average v))
+(newline)
+(delete-intvector v)
+
+; half will return a Scheme vector.
+; Call it with a Scheme vector...
+
+(display (half #(1 1.5 2 2.5 3)))
+(newline)
+
+; ... or a wrapped std::vector<double>
+(define v (new-doublevector))
+(map (lambda (i) (doublevector-push! v i)) '(1 2 3 4))
+(display (half v))
+(newline)
+
+; now halve a wrapped std::vector<double> in place
+(halve-in-place v)
+(print-doublevector v)
+(delete-doublevector v)
+
diff --git a/trunk/Examples/ocaml/argout_ref/Makefile b/trunk/Examples/ocaml/argout_ref/Makefile
new file mode 100644
index 0000000..8a260fe
--- /dev/null
+++ b/trunk/Examples/ocaml/argout_ref/Makefile
@@ -0,0 +1,27 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+MLFILE     = example.ml
+PROGFILE   = example_prog.ml
+OBJS       = example.o
+
+all:: static 
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_dynamic_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/argout_ref/example.c b/trunk/Examples/ocaml/argout_ref/example.c
new file mode 100644
index 0000000..6f095cd
--- /dev/null
+++ b/trunk/Examples/ocaml/argout_ref/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+extern "C" void factor( int &x, int &y ) {
+    int gcd_xy = gcd( x,y );
+    x /= gcd_xy;
+    y /= gcd_xy;
+}
diff --git a/trunk/Examples/ocaml/argout_ref/example.i b/trunk/Examples/ocaml/argout_ref/example.i
new file mode 100644
index 0000000..a0be05f
--- /dev/null
+++ b/trunk/Examples/ocaml/argout_ref/example.i
@@ -0,0 +1,4 @@
+/* File : example.i */
+%module example
+
+extern "C" void   factor(int &x, int &y);
diff --git a/trunk/Examples/ocaml/argout_ref/example_prog.ml b/trunk/Examples/ocaml/argout_ref/example_prog.ml
new file mode 100644
index 0000000..c6de345
--- /dev/null
+++ b/trunk/Examples/ocaml/argout_ref/example_prog.ml
@@ -0,0 +1,26 @@
+(* example_prog.ml *)
+
+open Swig
+open Example
+
+exception BadReturn
+
+let _ = if Array.length Sys.argv < 3 then
+  begin
+    print_endline 
+      ("Usage: " ^ Sys.argv.(0) ^ " n1 n2\n" ^
+       " Displays the least factors of the numbers that have the same\n" ^
+       " relationship, 16 12 -> 4 3\n") ;
+    exit 0
+  end
+
+let x = int_of_string Sys.argv.(1)
+let y = int_of_string Sys.argv.(2)
+let (xf,yf) = match _factor '((x to int),(y to int)) with
+    C_list [ C_int a ; C_int b ] -> a,b
+  | _ -> raise BadReturn
+let _ = print_endline
+	  ("Factorization of " ^ (string_of_int x) ^ 
+	   " and " ^ (string_of_int y) ^ 
+	   " is " ^ (string_of_int xf) ^ 
+	   " and " ^ (string_of_int yf))
diff --git a/trunk/Examples/ocaml/check.list b/trunk/Examples/ocaml/check.list
new file mode 100644
index 0000000..cbdf270
--- /dev/null
+++ b/trunk/Examples/ocaml/check.list
@@ -0,0 +1,10 @@
+# see top-level Makefile.in
+simple
+std_string
+std_vector
+stl
+argout_ref
+shapes
+contract
+scoped_enum
+string_from_ptr
diff --git a/trunk/Examples/ocaml/contract/Makefile b/trunk/Examples/ocaml/contract/Makefile
new file mode 100644
index 0000000..8e0f2a4
--- /dev/null
+++ b/trunk/Examples/ocaml/contract/Makefile
@@ -0,0 +1,33 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+MLFILE     = example.ml
+PROGFILE   = example_prog.ml
+OBJS       = 
+
+all:: static 
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_dynamic
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static
+
+toplevel::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_toplevel
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/contract/example.i b/trunk/Examples/ocaml/contract/example.i
new file mode 100644
index 0000000..28d9dd7
--- /dev/null
+++ b/trunk/Examples/ocaml/contract/example.i
@@ -0,0 +1,18 @@
+%module example
+%{
+#include <math.h>
+%}
+
+/* File : example.i */
+%module example
+
+%contract cos(double d) {
+require:
+	d >= -3.14159265358979323845254338327950;
+	d < 3.14159265358979323846264338327950;
+ensure:
+	cos >= -1.0;
+	cos <= 1.0;
+}
+
+double cos(double d);
\ No newline at end of file
diff --git a/trunk/Examples/ocaml/contract/example_prog.ml b/trunk/Examples/ocaml/contract/example_prog.ml
new file mode 100644
index 0000000..748109c
--- /dev/null
+++ b/trunk/Examples/ocaml/contract/example_prog.ml
@@ -0,0 +1,7 @@
+open Swig 
+open Example
+
+let _ = print_endline "This won't throw." 
+let _ = Printf.printf "Cos 1.0 is %f\n" (_cos '(1.0) as float)
+let _ = print_endline "This will throw."
+let _ = Printf.printf "Cos 5.0 is %f\n" (_cos '(5.0) as float)
diff --git a/trunk/Examples/ocaml/scoped_enum/Makefile b/trunk/Examples/ocaml/scoped_enum/Makefile
new file mode 100644
index 0000000..45c5edc
--- /dev/null
+++ b/trunk/Examples/ocaml/scoped_enum/Makefile
@@ -0,0 +1,33 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+MLFILE     = example.ml
+PROGFILE   = example_prog.ml
+OBJS       = 
+
+all:: static 
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_dynamic_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp
+
+toplevel::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp_toplevel
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/scoped_enum/README b/trunk/Examples/ocaml/scoped_enum/README
new file mode 100644
index 0000000..88b6693
--- /dev/null
+++ b/trunk/Examples/ocaml/scoped_enum/README
@@ -0,0 +1 @@
+This tests our handling of scoped enums.  Run with argument Tag1 or Tag2.
\ No newline at end of file
diff --git a/trunk/Examples/ocaml/scoped_enum/example.i b/trunk/Examples/ocaml/scoped_enum/example.i
new file mode 100644
index 0000000..de553f8
--- /dev/null
+++ b/trunk/Examples/ocaml/scoped_enum/example.i
@@ -0,0 +1,7 @@
+%module example
+
+%{
+#include "foo.h"
+%}
+
+%include "foo.h"
\ No newline at end of file
diff --git a/trunk/Examples/ocaml/scoped_enum/example_prog.ml b/trunk/Examples/ocaml/scoped_enum/example_prog.ml
new file mode 100644
index 0000000..e19bb34
--- /dev/null
+++ b/trunk/Examples/ocaml/scoped_enum/example_prog.ml
@@ -0,0 +1,4 @@
+open Swig
+open Example
+
+let _ = _f (match Sys.argv.(1) with "Tag1" -> ``Tag1 | _ -> ``Tag2)
diff --git a/trunk/Examples/ocaml/scoped_enum/foo.h b/trunk/Examples/ocaml/scoped_enum/foo.h
new file mode 100644
index 0000000..8238cb6
--- /dev/null
+++ b/trunk/Examples/ocaml/scoped_enum/foo.h
@@ -0,0 +1,5 @@
+namespace foo {
+    enum Bar { Tag1, Tag2 };
+    static void f( Bar b ) { printf( "b = %d\n", (int)b ); }
+}
+
diff --git a/trunk/Examples/ocaml/shapes/Makefile b/trunk/Examples/ocaml/shapes/Makefile
new file mode 100644
index 0000000..31f9934
--- /dev/null
+++ b/trunk/Examples/ocaml/shapes/Makefile
@@ -0,0 +1,34 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    = 
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+MLFILE     = example.ml
+PROGFILE   = example_prog.ml
+OBJS       = example.o
+
+all:: static static_top
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp
+
+static_top::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp_toplevel
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)'
+	MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_dynamic_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/shapes/example.c b/trunk/Examples/ocaml/shapes/example.c
new file mode 100644
index 0000000..bf0fff9
--- /dev/null
+++ b/trunk/Examples/ocaml/shapes/example.c
@@ -0,0 +1,48 @@
+/* File : example.c */
+#include <stdio.h>
+#include "example.h"
+
+shape::~shape() { }
+
+bool shape::cover( double x, double y ) { return false; }
+
+void draw_shape_coverage( shape *s, int div_x, int div_y ) {
+    double i,j;
+
+    for( i = 0; i < 1.0; i += 1.0 / ((float)div_y) ) {
+	for( j = 0; j < 1.0; j += 1.0 / ((float)div_x) ) {
+	    if( s->cover( j,i ) ) putchar( 'x' ); else putchar( ' ' );
+	}
+	printf( "\n" );
+    }
+}
+
+void draw_depth_map( volume *v, int div_x, int div_y ) {
+    double i,j;
+    char depth_map_chars[] = "#*+o;:,. ";
+    double lowbound, highbound;
+    double current = 0.0;
+    bool bounds_set = false;
+
+    for( i = 0; i < 1.0; i += 1.0 / ((float)div_y) ) {
+	for( j = 0; j < 1.0; j += 1.0 / ((float)div_x) ) {
+	    current = v->depth( j,i );
+	    if( !bounds_set ) { 
+		lowbound = current; highbound = current; bounds_set = true;
+	    }
+	    if( current < lowbound ) lowbound = current;
+	    if( current > highbound ) highbound = current;
+	}
+    }
+
+    for( i = 0; i < 1.0; i += 1.0 / ((float)div_y) ) {
+	for( j = 0; j < 1.0; j += 1.0 / ((float)div_x) ) {
+	    current = ((v->depth( j,i ) - lowbound) / 
+		       (highbound - lowbound)) * 8;
+	    putchar(depth_map_chars[(int)current]);
+	}
+	putchar('\n');
+    }
+}
+
+double volume::depth( double x, double y ) { return 0.0; }
diff --git a/trunk/Examples/ocaml/shapes/example.h b/trunk/Examples/ocaml/shapes/example.h
new file mode 100644
index 0000000..4b16444
--- /dev/null
+++ b/trunk/Examples/ocaml/shapes/example.h
@@ -0,0 +1,18 @@
+#ifndef EXAMPLE_H
+#define EXAMPLE_H
+
+class shape {
+public:
+  virtual ~shape();
+  virtual bool cover( double x, double y ); // does this shape cover this point?
+};
+
+class volume {
+public:
+    virtual double depth( double x, double y );
+};
+
+extern void draw_shape_coverage( shape *s, int div_x, int div_y );
+extern void draw_depth_map( volume *v, int div_x, int div_y );
+
+#endif//EXAMPLE_H
diff --git a/trunk/Examples/ocaml/shapes/example.i b/trunk/Examples/ocaml/shapes/example.i
new file mode 100644
index 0000000..ac0fa4a
--- /dev/null
+++ b/trunk/Examples/ocaml/shapes/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module(directors="1") example
+#ifndef SWIGSEXP
+%{
+	#include "example.h"
+%}
+#endif
+
+%feature("director");
+%include "example.h"
diff --git a/trunk/Examples/ocaml/shapes/example_prog.ml b/trunk/Examples/ocaml/shapes/example_prog.ml
new file mode 100644
index 0000000..b9e3515
--- /dev/null
+++ b/trunk/Examples/ocaml/shapes/example_prog.ml
@@ -0,0 +1,76 @@
+(* example_prog.ml *)
+
+open Swig ;;
+open Example ;;
+
+let side_length (ax,ay) (bx,by) =
+  sqrt (((bx -. ax) ** 2.0) +. ((by -. ay) ** 2.0)) ;;
+
+let triangle_area a_pt b_pt c_pt =
+  let a = (side_length a_pt b_pt) 
+  and b = (side_length b_pt c_pt)
+  and c = (side_length c_pt a_pt) in
+  let s = (a +. b +. c) /. 2.0 in
+    sqrt (s *. (s -. a) *. (s -. b) *. (s -. c)) ;;
+
+let point_in_triangle (pta,ptb,ptc) x y =
+  let delta = 0.0000001 in (* Error *)
+  let ptx = (x,y) in
+    begin
+      let a_area = triangle_area pta ptb ptx
+      and b_area = triangle_area ptb ptc ptx
+      and c_area = triangle_area ptc pta ptx
+      and x_area = triangle_area pta ptb ptc in
+      let result = (abs_float (a_area +. b_area +. c_area -. x_area)) < delta
+      in
+	result
+    end ;;
+
+let triangle_class pts ob meth args =
+  match meth with
+      "cover" ->
+	(match args with
+	     C_list [ x_arg ; y_arg ] ->
+	       let xa = x_arg as float 
+	       and ya = y_arg as float in
+		 (point_in_triangle pts xa ya) to bool
+	   | _ -> raise (Failure "cover needs two double arguments."))
+    | _ -> (invoke ob) meth args ;;
+
+let dist (ax,ay) (bx,by) = 
+  let dx = ax -. bx and dy = ay -. by in
+    sqrt ((dx *. dx) +. (dy *. dy))
+
+let waveplot_depth events distance pt =
+  (List.fold_left (+.) 0.0 
+     (List.map 
+	(fun (x,y,d) -> 
+	   let t = dist pt (x,y) in
+	     ((sin t) /. t) *. d)
+	events)) +. distance
+
+let waveplot_class events distance ob meth args =
+  match meth with
+      "depth" ->
+	(match args with
+	     C_list [ x_arg ; y_arg ] ->
+	       let xa = x_arg as float 
+	       and ya = y_arg as float in
+		 (waveplot_depth events distance (xa,ya)) to float
+	   | _ -> raise (Failure "cover needs two double arguments."))
+    | _ -> (invoke ob) meth args ;;
+
+let triangle =
+  new_derived_object 
+    new_shape
+    (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.6)))
+    '() ;;
+
+let waveplot = 
+  new_derived_object
+    new_volume
+    (waveplot_class [ 0.01,0.01,3.0 ; 1.01,-2.01,1.5 ] 5.0)
+    '() ;;
+
+let _ = _draw_shape_coverage '(triangle, 60, 20) ;;
+let _ = _draw_depth_map '(waveplot, 60, 20) ;;
diff --git a/trunk/Examples/ocaml/simple/Makefile b/trunk/Examples/ocaml/simple/Makefile
new file mode 100644
index 0000000..4b85bf3
--- /dev/null
+++ b/trunk/Examples/ocaml/simple/Makefile
@@ -0,0 +1,33 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+MLFILE     = example.ml
+PROGFILE   = example_prog.ml
+OBJS       = example.o
+
+all:: static 
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_dynamic
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static
+
+toplevel::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \
+	PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_toplevel
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/simple/example.c b/trunk/Examples/ocaml/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/ocaml/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/ocaml/simple/example.i b/trunk/Examples/ocaml/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/ocaml/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/ocaml/simple/example_prog.ml b/trunk/Examples/ocaml/simple/example_prog.ml
new file mode 100644
index 0000000..cc3b973
--- /dev/null
+++ b/trunk/Examples/ocaml/simple/example_prog.ml
@@ -0,0 +1,33 @@
+(* example_prog.ml *)
+
+open Swig
+open Example
+
+(* Call our gcd() function *)
+
+exception NoReturn
+
+let x = 42 to int
+let y = 105 to int
+let g = _gcd '(x,y) as int
+let _ = Printf.printf "The gcd of %d and %d is %d\n" (x as int) (y as int) g
+
+(* Manipulate the Foo global variable *)
+
+(* Output its current value *)
+let _ = Printf.printf "Foo = %f\n" (_Foo '() as float)
+
+(* Change its value *)
+let _ = _Foo '(3.1415926)
+
+(* See if the change took effect *)
+let _ = Printf.printf "Foo = %f\n" (_Foo '() as float)
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/ocaml/simple/index.html b/trunk/Examples/ocaml/simple/index.html
new file mode 100644
index 0000000..dace471
--- /dev/null
+++ b/trunk/Examples/ocaml/simple/index.html
@@ -0,0 +1,97 @@
+<html>
+<head>
+<title>SWIG:Examples:python:simple</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/simple/</tt>
+<hr>
+
+<H2>Simple Python Example</H2>
+
+<p>
+This example illustrates how you can hook Python to a very simple C program containing
+a function and a global variable.
+
+<h2>The C Code</h2>
+
+Suppose you have the following C code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x &gt; 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+Here is a simple SWIG interface file:
+
+<blockquote>
+<pre>
+/* File: example.i */
+%module example
+
+extern int gcd(int x, int y);
+extern double Foo;
+</pre>
+</blockquote>
+
+<h2>Compilation</h2>
+
+<ol>
+<li><tt>swig -python <a href="example.i">example.i</a></tt>
+<p>
+<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
+to create the extension <tt>examplemodule.so</tt>. 
+</ol>
+
+<h2>Using the extension</h2>
+
+Click <a href="example.py">here</a> to see a script that calls our C functions from Python.
+
+<h2>Key points</h2>
+
+<ul>
+<li>Use the <tt>import</tt> statement to load your extension module from Python. For example:
+<blockquote>
+<pre>
+import example
+</pre>
+</blockquote>
+
+<li>C functions work just like Python functions. For example:
+<blockquote>
+<pre>
+g = example.gcd(42,105)
+</pre>
+</blockquote>
+
+<li>C global variables are accessed through a special variable called 'cvar'. For example:
+<blockquote>
+<pre>
+a = example.cvar.Foo
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ocaml/std_string/Makefile b/trunk/Examples/ocaml/std_string/Makefile
new file mode 100644
index 0000000..e5a8017
--- /dev/null
+++ b/trunk/Examples/ocaml/std_string/Makefile
@@ -0,0 +1,23 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+PROGFILE   = runme.ml
+
+all default:: static
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_dynamic_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/std_string/README b/trunk/Examples/ocaml/std_string/README
new file mode 100644
index 0000000..5665530
--- /dev/null
+++ b/trunk/Examples/ocaml/std_string/README
@@ -0,0 +1,13 @@
+This example shows how to use both std::string and std::wstring in Ocaml,
+and also demonstrates that one might use this to make a locale-obedient
+Ocaml program.
+
+These are two sample runs; note that the output is different based on the 
+locale chosen to perform the conversion to wchar_t.
+
+bash-2.05a$ ./example ja_JP.EUC-JP
+the original string contains 2              
+the new string contains 1 : [ 29494; ]
+bash-2.05a$ ./example en_US
+the original string contains 2
+the new string contains 2 : [ 205; 177; ]
diff --git a/trunk/Examples/ocaml/std_string/example.h b/trunk/Examples/ocaml/std_string/example.h
new file mode 100644
index 0000000..60de984
--- /dev/null
+++ b/trunk/Examples/ocaml/std_string/example.h
@@ -0,0 +1,36 @@
+/* File : example.h -- stolen from the guile std_vector example */
+
+#include <string>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+#include <stdlib.h>
+#include <locale.h>
+
+std::string from_wstring_with_locale( const std::wstring source,
+				      const std::string locale ) {
+    const char *current_locale = setlocale( LC_CTYPE, locale.c_str() );
+    int required_chars = wcstombs( NULL, source.c_str(), 0 );
+    std::string s;
+    char *temp_chars = new char[required_chars + 1];
+    temp_chars[0] = 0;
+    wcstombs( temp_chars, source.c_str(), required_chars + 1 );
+    s = temp_chars;
+    delete [] temp_chars;
+    setlocale( LC_CTYPE, current_locale );
+    return s;
+}
+
+std::wstring to_wstring_with_locale( const std::string source,
+				     const std::string locale ) {
+    const char *current_locale = setlocale( LC_CTYPE, locale.c_str() );
+    int required_chars = mbstowcs( NULL, source.c_str(), 0 );
+    std::wstring s;
+    wchar_t *temp_chars = new wchar_t[required_chars + 1];
+    temp_chars[0] = 0;
+    mbstowcs( temp_chars, source.c_str(), required_chars + 1 );
+    s = temp_chars;
+    delete [] temp_chars;
+    setlocale( LC_CTYPE, current_locale );
+    return s;
+}
diff --git a/trunk/Examples/ocaml/std_string/example.i b/trunk/Examples/ocaml/std_string/example.i
new file mode 100644
index 0000000..7b144ea
--- /dev/null
+++ b/trunk/Examples/ocaml/std_string/example.i
@@ -0,0 +1,12 @@
+/* -*- C++ -*- */
+/* File : example.i -- stolen from the guile std_vector example */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/trunk/Examples/ocaml/std_string/runme.ml b/trunk/Examples/ocaml/std_string/runme.ml
new file mode 100644
index 0000000..199dbe5
--- /dev/null
+++ b/trunk/Examples/ocaml/std_string/runme.ml
@@ -0,0 +1,24 @@
+(* This example was mostly lifted from the guile example directory *)
+
+open Swig
+open Example
+
+let y = "\205\177"
+let z = _to_wstring_with_locale '((y to string),(Sys.argv.(1) to string))
+
+let _ = 
+  begin
+    print_string "the original string contains " ;
+    print_int (String.length y) ;
+    print_newline () ;
+    
+    print_string "the new string contains " ;
+    print_int (z -> size () as int) ;
+    print_string " : [ " ;
+    for i = 0 to (pred ((z -> size ()) as int)) do
+      print_int ((z '[i to int]) as int) ;
+      print_string "; " ;
+    done ;
+    print_string "]" ;
+    print_newline () ;
+  end    
diff --git a/trunk/Examples/ocaml/std_vector/Makefile b/trunk/Examples/ocaml/std_vector/Makefile
new file mode 100644
index 0000000..e5a8017
--- /dev/null
+++ b/trunk/Examples/ocaml/std_vector/Makefile
@@ -0,0 +1,23 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+PROGFILE   = runme.ml
+
+all default:: static
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_dynamic_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/std_vector/example.h b/trunk/Examples/ocaml/std_vector/example.h
new file mode 100644
index 0000000..b753592
--- /dev/null
+++ b/trunk/Examples/ocaml/std_vector/example.h
@@ -0,0 +1,25 @@
+/* File : example.h -- stolen from the guile std_vector example */
+
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<double> half(const std::vector<double>& v) {
+    std::vector<double> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    // would you believe this is the same as the above?
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+
diff --git a/trunk/Examples/ocaml/std_vector/example.i b/trunk/Examples/ocaml/std_vector/example.i
new file mode 100644
index 0000000..60285e5
--- /dev/null
+++ b/trunk/Examples/ocaml/std_vector/example.i
@@ -0,0 +1,15 @@
+/* -*- C++ -*- */
+/* File : example.i -- stolen from the guile std_vector example */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+/* instantiate the required template specializations */
+%template(IntVector)    std::vector<int>;
+%template(DoubleVector) std::vector<double>;
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/trunk/Examples/ocaml/std_vector/runme.ml b/trunk/Examples/ocaml/std_vector/runme.ml
new file mode 100644
index 0000000..feb70dd
--- /dev/null
+++ b/trunk/Examples/ocaml/std_vector/runme.ml
@@ -0,0 +1,35 @@
+(* This example was mostly lifted from the guile example directory *)
+
+open Swig
+open Example
+
+let with_vector v f =
+  for i = 0 to ((v -> size()) as int) - 1 do
+    f v i
+  done
+
+let print_DoubleVector v =
+  begin
+    with_vector v 
+      (fun v i -> 
+	 print_float ((v '[i to int]) as float) ;
+	 print_string " ") ;
+    print_endline 
+  end
+
+(* Call average with a Ocaml array... *)
+
+let v = new_DoubleVector '()
+let rec fill_dv v x =
+  if x < 0.0001 then v else 
+    begin
+      v -> push_back ((x to float)) ;
+      fill_dv v (x *. x)
+    end
+let _ = fill_dv v 0.999
+let _ = print_DoubleVector v ; print_endline ""
+let u = new_IntVector '()
+let _ = for i = 1 to 4 do
+  u -> push_back ((i to int))
+done
+let _ = (print_float ((_average u) as float) ; print_newline ())
diff --git a/trunk/Examples/ocaml/stl/Makefile b/trunk/Examples/ocaml/stl/Makefile
new file mode 100644
index 0000000..fa4333e
--- /dev/null
+++ b/trunk/Examples/ocaml/stl/Makefile
@@ -0,0 +1,33 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+PROGFILE   = runme.ml
+
+all default:: static
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp
+
+director::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp_director
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp
+
+toplevel::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp_toplevel
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/stl/example.h b/trunk/Examples/ocaml/stl/example.h
new file mode 100644
index 0000000..df5762b
--- /dev/null
+++ b/trunk/Examples/ocaml/stl/example.h
@@ -0,0 +1,17 @@
+/* File : example.h -- stolen from the guile std_vector example */
+
+#include <string>
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+using std::string;
+
+double vec_write(std::vector<string> v) {
+    int n = 0;
+    for( std::vector<string>::iterator i = v.begin();
+	 i != v.end();
+	 i++ )
+	printf( "%04d: %s\n", ++n, i->c_str() );
+}
diff --git a/trunk/Examples/ocaml/stl/example.i b/trunk/Examples/ocaml/stl/example.i
new file mode 100644
index 0000000..19a80a6
--- /dev/null
+++ b/trunk/Examples/ocaml/stl/example.i
@@ -0,0 +1,12 @@
+%module example
+%{
+#include "example.h"
+%}
+
+#define ENABLE_CHARPTR_ARRAY
+#define ENABLE_STRING_VECTOR
+%include stl.i
+
+%feature("director");
+
+%include example.h
diff --git a/trunk/Examples/ocaml/stl/runme.ml b/trunk/Examples/ocaml/stl/runme.ml
new file mode 100644
index 0000000..2fa5d20
--- /dev/null
+++ b/trunk/Examples/ocaml/stl/runme.ml
@@ -0,0 +1,13 @@
+(* This example was mostly lifted from the guile example directory *)
+
+open Swig
+open Example
+
+let v = new_StringVector '() 
+
+let _ = 
+  for i = 0 to (Array.length Sys.argv) - 1 do
+    let str = (Sys.argv.(i)) to string in v -> push_back (str)
+  done
+
+let _ = _vec_write '(v)
diff --git a/trunk/Examples/ocaml/string_from_ptr/Makefile b/trunk/Examples/ocaml/string_from_ptr/Makefile
new file mode 100644
index 0000000..350d973
--- /dev/null
+++ b/trunk/Examples/ocaml/string_from_ptr/Makefile
@@ -0,0 +1,34 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    = -c++
+SRCS       = 
+TARGET     = example
+INTERFACE  = foolib.i
+MLFILE     = foolib.ml
+PROGFILE   = example_prog.ml
+OBJS       = 
+
+all:: static static_top
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp
+
+static_top::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_static_cpp_toplevel
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)'
+	MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \
+	ocaml_dynamic_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/string_from_ptr/example_prog.ml b/trunk/Examples/ocaml/string_from_ptr/example_prog.ml
new file mode 100644
index 0000000..8069dc2
--- /dev/null
+++ b/trunk/Examples/ocaml/string_from_ptr/example_prog.ml
@@ -0,0 +1,23 @@
+(* foo_program.ml -- the program using foolib *)
+
+open Swig    (* Give access to the swig library *)
+open Foolib  (* This is the name of your swig output *)
+
+let results = _foo '()  (* Function names are prefixed with _ in order to make
+			   them lex as identifiers in ocaml.  Consider that
+			   uppercase identifiers are module names in ocaml.
+			   NOTE: the '() syntax is part of swigp4.  You can do:
+		           let results = _foo C_void *)
+
+(* Since your function has a return value in addition to the string output,
+   you'll need to match them as a list *)
+
+let result_string =
+  match results with 
+    C_list [ C_string result_string ; C_int 0 ] -> (* The return value is
+	last when out arguments appear, but this too can be customized.
+	We're also checking that the function succeeded. *)
+      result_string
+  | _ -> raise (Failure "Expected string, int reply from _foo")
+      
+let _ = print_endline result_string
diff --git a/trunk/Examples/ocaml/string_from_ptr/foolib.i b/trunk/Examples/ocaml/string_from_ptr/foolib.i
new file mode 100644
index 0000000..86e0880
--- /dev/null
+++ b/trunk/Examples/ocaml/string_from_ptr/foolib.i
@@ -0,0 +1,16 @@
+%module foolib
+%{
+static int foo( char **buf ) {
+  *buf = "string from c";
+  return 0;
+}
+%}
+
+%typemap(in,numinputs=0) char **buf (char *temp) {
+    $1 = &temp;
+}
+%typemap(argout) char **buf {
+    swig_result = caml_list_append(swig_result,caml_val_string((char *)*$1));
+}
+
+int foo( char **buf );
diff --git a/trunk/Examples/ocaml/strings_test/Makefile b/trunk/Examples/ocaml/strings_test/Makefile
new file mode 100644
index 0000000..8d1f96e
--- /dev/null
+++ b/trunk/Examples/ocaml/strings_test/Makefile
@@ -0,0 +1,28 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+PROGFILE   = runme.ml
+
+all default:: static top
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp
+
+dynamic::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp
+
+top::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	ocaml_static_cpp_toplevel
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean
+
+check: all
diff --git a/trunk/Examples/ocaml/strings_test/example.h b/trunk/Examples/ocaml/strings_test/example.h
new file mode 100644
index 0000000..3417981
--- /dev/null
+++ b/trunk/Examples/ocaml/strings_test/example.h
@@ -0,0 +1,37 @@
+/* -*- mode: c++ -*- */
+/* File : example.h -- Tests all string typemaps */
+
+void takes_std_string( std::string in ) {
+    cout << "takes_std_string( \"" << in << "\" );" << endl;
+}
+
+std::string gives_std_string() {
+    time_t t;
+    
+    return std::string( asctime( localtime( &t ) ) );
+}
+
+void takes_char_ptr( char *p ) {
+    cout << "takes_char_ptr( \"" << p << "\" );" << endl;
+}
+
+char *gives_char_ptr() {
+    return "foo";
+}
+
+void takes_and_gives_std_string( std::string &inout ) {
+    inout.insert( inout.begin(), '[' );
+    inout.insert( inout.end(), ']' );
+}
+
+void takes_and_gives_char_ptr( char *&ptr ) {
+    char *pout = strchr( ptr, '.' );
+    if( pout ) ptr = pout + 1;
+    else ptr = "foo";
+}
+
+/*
+ * Local-Variables:
+ * c-indentation-style: "stroustrup"
+ * End:
+ */
diff --git a/trunk/Examples/ocaml/strings_test/example.i b/trunk/Examples/ocaml/strings_test/example.i
new file mode 100644
index 0000000..be9eabf
--- /dev/null
+++ b/trunk/Examples/ocaml/strings_test/example.i
@@ -0,0 +1,14 @@
+%module example
+%{
+#include <iostream>
+#include <string>
+
+using std::cin;
+using std::cout;
+using std::endl;
+using std::string;
+
+#include "example.h"
+%}
+
+%include example.h
diff --git a/trunk/Examples/ocaml/strings_test/runme.ml b/trunk/Examples/ocaml/strings_test/runme.ml
new file mode 100644
index 0000000..0eb5637
--- /dev/null
+++ b/trunk/Examples/ocaml/strings_test/runme.ml
@@ -0,0 +1,17 @@
+(* This example is meant to reach every case in cstring.i *)
+
+open Swig
+open Example
+
+let _ = _takes_std_string (C_string "foo")
+let _ = print_endline 
+  ("_gives_std_string <<" ^ (get_string (_gives_std_string C_void)) ^ " >>")
+let _ = _takes_char_ptr (C_string "bar")
+let _ = print_endline 
+  ("_gives_char_ptr << " ^ (get_string (_gives_char_ptr C_void)) ^ " >>")
+let _ = print_endline
+  ("_takes_and_gives_std_string << " ^ 
+   (get_string (_takes_and_gives_std_string (C_string "foo"))) ^ " >>")
+let _ = print_endline
+  ("_takes_and_gives_char_ptr << " ^
+   (get_string (_takes_and_gives_char_ptr (C_string "bar.bar"))) ^ " >>")
diff --git a/trunk/Examples/octave/callback/Makefile b/trunk/Examples/octave/callback/Makefile
new file mode 100644
index 0000000..2bce9df
--- /dev/null
+++ b/trunk/Examples/octave/callback/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/callback/example.cxx b/trunk/Examples/octave/callback/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/octave/callback/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/octave/callback/example.h b/trunk/Examples/octave/callback/example.h
new file mode 100644
index 0000000..1a0e8c4
--- /dev/null
+++ b/trunk/Examples/octave/callback/example.h
@@ -0,0 +1,23 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+
+class Callback {
+public:
+	virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; }
+	virtual void run() { std::cout << "Callback::run()" << std::endl; }
+};
+
+
+class Caller {
+private:
+	Callback *_callback;
+public:
+	Caller(): _callback(0) {}
+	~Caller() { delCallback(); }
+	void delCallback() { delete _callback; _callback = 0; }
+	void setCallback(Callback *cb) { delCallback(); _callback = cb; }
+	void call() { if (_callback) _callback->run(); }
+};
+
diff --git a/trunk/Examples/octave/callback/example.i b/trunk/Examples/octave/callback/example.i
new file mode 100644
index 0000000..90beda0
--- /dev/null
+++ b/trunk/Examples/octave/callback/example.i
@@ -0,0 +1,13 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_string.i"
+
+/* turn on director wrapping Callback */
+%feature("director") Callback;
+
+%include "example.h"
+
diff --git a/trunk/Examples/octave/callback/runme.m b/trunk/Examples/octave/callback/runme.m
new file mode 100644
index 0000000..b87925e
--- /dev/null
+++ b/trunk/Examples/octave/callback/runme.m
@@ -0,0 +1,63 @@
+# file: runme.m
+
+# This file illustrates the cross language polymorphism using directors.
+
+example 
+
+OctCallback=@() subclass(example.Callback(), \
+			 'run',@(self) printf("OctCallback.run()\n"));
+
+# Create an Caller instance
+
+caller = example.Caller();
+
+# Add a simple C++ callback (caller owns the callback, so
+# we disown it first)
+
+printf("Adding and calling a normal C++ callback\n");
+printf("----------------------------------------\n");
+
+callback = example.Callback().__disown();
+caller.setCallback(callback);
+caller.call();
+caller.delCallback();
+
+printf("Adding and calling a Octave callback\n");
+printf("------------------------------------\n");
+
+# Add a Octave callback (caller owns the callback, so we
+# disown it first by calling __disown).
+
+caller.setCallback(OctCallback().__disown())
+caller.call();
+caller.delCallback();
+
+printf("Adding and calling another Octave callback\n");
+printf("------------------------------------------\n");
+
+# Let's do the same but use the weak reference this time.
+
+callback = OctCallback().__disown();
+caller.setCallback(callback);
+caller.call();
+caller.delCallback();
+
+# careful-- using callback here may cause problems; octave_swig_type still
+# exists, but is holding a destroyed object (the C++ example.Callback).
+# to manually drop the octave-side reference, you can use
+clear callback;
+
+# Let's call them directly now
+
+printf("Calling Octave and C++ callbacks directly\n");
+printf("------------------------------------------\n");
+
+a = OctCallback();
+a.run();
+a.Callback.run();
+
+
+# All done.
+
+printf("octave exit\n");
+
diff --git a/trunk/Examples/octave/check.list b/trunk/Examples/octave/check.list
new file mode 100644
index 0000000..1e66081
--- /dev/null
+++ b/trunk/Examples/octave/check.list
@@ -0,0 +1,16 @@
+# see top-level Makefile.in
+callback
+class
+constants
+contract
+enum
+extend
+funcptr
+funcptr2
+functor
+operator
+pointer
+reference
+simple
+template
+variables
diff --git a/trunk/Examples/octave/class/Makefile b/trunk/Examples/octave/class/Makefile
new file mode 100644
index 0000000..2bce9df
--- /dev/null
+++ b/trunk/Examples/octave/class/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/class/example.cxx b/trunk/Examples/octave/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/octave/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/octave/class/example.h b/trunk/Examples/octave/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/octave/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/octave/class/example.i b/trunk/Examples/octave/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/octave/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/octave/class/runme.m b/trunk/Examples/octave/class/runme.m
new file mode 100644
index 0000000..c833a70
--- /dev/null
+++ b/trunk/Examples/octave/class/runme.m
@@ -0,0 +1,52 @@
+# file: runme.m
+
+# This file illustrates the proxy class C++ interface generated
+# by SWIG.
+
+example 
+
+# ----- Object creation -----
+
+printf("Creating some objects:\n");
+c = example.Circle(10)
+s = example.Square(10)
+
+# ----- Access a static member -----
+
+printf("\nA total of %i shapes were created\n", example.Shape.nshapes);
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+
+s.x = -10
+s.y = 5
+
+printf("\nHere is their current position:\n");
+printf("    Circle = (%f, %f)\n",c.x,c.y);
+printf("    Square = (%f, %f)\n",s.x,s.y);
+
+# ----- Call some methods -----
+
+printf("\nHere are some properties of the shapes:\n");
+function print_shape(o)
+      o
+      printf("  area      = %f\n", o.area());
+      printf("  perimeter = %f\n", o.perimeter());
+end;
+print_shape(c);
+print_shape(s);
+
+printf("\nGuess I'll clean up now\n");
+
+# Note: this invokes the virtual destructor
+clear c
+clear s
+
+printf("%i shapes remain\n", example.Shape.nshapes);
+printf("Goodbye\n");
+
+
diff --git a/trunk/Examples/octave/constants/Makefile b/trunk/Examples/octave/constants/Makefile
new file mode 100644
index 0000000..4d80c6f
--- /dev/null
+++ b/trunk/Examples/octave/constants/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/constants/example.i b/trunk/Examples/octave/constants/example.i
new file mode 100644
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/octave/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/octave/constants/runme.m b/trunk/Examples/octave/constants/runme.m
new file mode 100644
index 0000000..3228587
--- /dev/null
+++ b/trunk/Examples/octave/constants/runme.m
@@ -0,0 +1,29 @@
+# file: runme.m
+
+example 
+
+printf("ICONST  = %i (should be 42)\n", example.ICONST);
+printf("FCONST  = %f (should be 2.1828)\n", example.FCONST);
+printf("CCONST  = %s (should be 'x')\n", example.CCONST);
+printf("CCONST2 = %s (this should be on a new line)\n", example.CCONST2);
+printf("SCONST  = %s (should be 'Hello World')\n", example.SCONST);
+printf("SCONST2 = %s (should be '\"Hello World\"')\n", example.SCONST2);
+printf("EXPR    = %f (should be 48.5484)\n", example.EXPR);
+printf("iconst  = %i (should be 37)\n", example.iconst);
+printf("fconst  = %f (should be 3.14)\n", example.fconst);
+
+try
+    printf("EXTERN = %s (Arg! This shouldn't printf(anything)\n", example.EXTERN);
+catch
+    printf("EXTERN isn't defined (good)\n");
+end_try_catch
+
+try
+    printf("FOO    = %i (Arg! This shouldn't printf(anything)\n", example.FOO);
+catch
+    printf("FOO isn't defined (good)\n");
+end_try_catch
+
+
+
+
diff --git a/trunk/Examples/octave/contract/Makefile b/trunk/Examples/octave/contract/Makefile
new file mode 100644
index 0000000..627b0a9
--- /dev/null
+++ b/trunk/Examples/octave/contract/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/contract/example.c b/trunk/Examples/octave/contract/example.c
new file mode 100644
index 0000000..1a64454
--- /dev/null
+++ b/trunk/Examples/octave/contract/example.c
@@ -0,0 +1,23 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int fact(int n) {
+  if (n <= 0) return 1;
+  return n*fact(n-1);
+}
+
+
diff --git a/trunk/Examples/octave/contract/example.i b/trunk/Examples/octave/contract/example.i
new file mode 100644
index 0000000..8fd1a80
--- /dev/null
+++ b/trunk/Examples/octave/contract/example.i
@@ -0,0 +1,21 @@
+/* File : example.i */
+%module example
+
+%contract gcd(int x, int y) {
+require:
+	x >= 0;
+	y >= 0;
+}
+
+%contract fact(int n) {
+require:
+	n >= 0;
+ensure:
+	fact >= 1;
+}
+
+%inline %{
+extern int    gcd(int x, int y);
+extern int    fact(int n);
+extern double Foo;
+%}
diff --git a/trunk/Examples/octave/contract/runme.m b/trunk/Examples/octave/contract/runme.m
new file mode 100644
index 0000000..62b7232
--- /dev/null
+++ b/trunk/Examples/octave/contract/runme.m
@@ -0,0 +1,22 @@
+# file: runme.m
+
+example 
+
+# Call our gcd() function
+
+x = 42;
+y = 105;
+g = example.gcd(x,y);
+printf("The gcd of %d and %d is %d\n",x,y,g);
+
+# Manipulate the Foo global variable
+
+# Output its current value
+printf("Foo = %f\n", example.cvar.Foo);
+
+# Change its value
+example.cvar.Foo = 3.1415926;
+
+# See if the change took effect
+printf("Foo = %f\n", example.cvar.Foo);
+
diff --git a/trunk/Examples/octave/enum/Makefile b/trunk/Examples/octave/enum/Makefile
new file mode 100644
index 0000000..2bce9df
--- /dev/null
+++ b/trunk/Examples/octave/enum/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/enum/example.cxx b/trunk/Examples/octave/enum/example.cxx
new file mode 100644
index 0000000..6785e57
--- /dev/null
+++ b/trunk/Examples/octave/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.c */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/octave/enum/example.h b/trunk/Examples/octave/enum/example.h
new file mode 100644
index 0000000..525d62a
--- /dev/null
+++ b/trunk/Examples/octave/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/octave/enum/example.i b/trunk/Examples/octave/enum/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/octave/enum/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/octave/enum/runme.m b/trunk/Examples/octave/enum/runme.m
new file mode 100644
index 0000000..a749e81
--- /dev/null
+++ b/trunk/Examples/octave/enum/runme.m
@@ -0,0 +1,32 @@
+# file: runme.m
+
+example
+
+# ----- Object creation -----
+
+# Print out the value of some enums
+printf("*** color ***\n");
+printf("    RED    = %i\n", example.RED);
+printf("    BLUE   = %i\n", example.BLUE);
+printf("    GREEN  = %i\n", example.GREEN);
+
+printf("\n*** Foo::speed ***\n");
+printf("    Foo_IMPULSE   = %i\n", example.Foo_IMPULSE);
+printf("    Foo_WARP      = %i\n", example.Foo_WARP);
+printf("    Foo_LUDICROUS = %i\n", example.Foo_LUDICROUS);
+
+printf("\nTesting use of enums with functions\n");
+
+example.enum_test(example.RED, example.Foo_IMPULSE);
+example.enum_test(example.BLUE,  example.Foo_WARP);
+example.enum_test(example.GREEN, example.Foo_LUDICROUS);
+example.enum_test(1234,5678)
+
+printf("\nTesting use of enum with class method\n");
+f = example.Foo();
+
+f.enum_test(example.Foo_IMPULSE);
+f.enum_test(example.Foo_WARP);
+f.enum_test(example.Foo_LUDICROUS);
+
+
diff --git a/trunk/Examples/octave/extend/Makefile b/trunk/Examples/octave/extend/Makefile
new file mode 100644
index 0000000..2bce9df
--- /dev/null
+++ b/trunk/Examples/octave/extend/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/extend/example.cxx b/trunk/Examples/octave/extend/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/octave/extend/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/octave/extend/example.h b/trunk/Examples/octave/extend/example.h
new file mode 100644
index 0000000..b27ab97
--- /dev/null
+++ b/trunk/Examples/octave/extend/example.h
@@ -0,0 +1,56 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+#include <vector>
+#include <string>
+#include <cmath>
+
+class Employee {
+private:
+	std::string name;
+public:
+	Employee(const char* n): name(n) {}
+	virtual std::string getTitle() { return getPosition() + " " + getName(); }
+	virtual std::string getName() { return name; }
+	virtual std::string getPosition() const { return "Employee"; }
+	virtual ~Employee() { printf("~Employee() @ %p\n", this); }
+};
+
+
+class Manager: public Employee {
+public:
+	Manager(const char* n): Employee(n) {}
+	virtual std::string getPosition() const { return "Manager"; }
+};
+
+
+class EmployeeList {
+	std::vector<Employee*> list;
+public:
+	EmployeeList() {
+		list.push_back(new Employee("Bob"));
+		list.push_back(new Employee("Jane"));
+		list.push_back(new Manager("Ted"));
+	}
+	void addEmployee(Employee *p) {
+		list.push_back(p);
+		std::cout << "New employee added.   Current employees are:" << std::endl;
+		std::vector<Employee*>::iterator i;
+		for (i=list.begin(); i!=list.end(); i++) {
+			std::cout << "  " << (*i)->getTitle() << std::endl;
+		}
+	}
+	const Employee *get_item(int i) {
+		return list[i];
+	}
+	~EmployeeList() { 
+		std::vector<Employee*>::iterator i;
+		std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl;
+		for (i=list.begin(); i!=list.end(); i++) {
+			delete *i;
+		}
+		std::cout << "~EmployeeList empty." << std::endl;
+	}
+};
+
diff --git a/trunk/Examples/octave/extend/example.i b/trunk/Examples/octave/extend/example.i
new file mode 100644
index 0000000..c8ec32e
--- /dev/null
+++ b/trunk/Examples/octave/extend/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+%include "std_string.i"
+
+/* turn on director wrapping for Manager */
+%feature("director") Employee;
+%feature("director") Manager;
+
+%include "example.h"
+
diff --git a/trunk/Examples/octave/extend/runme.m b/trunk/Examples/octave/extend/runme.m
new file mode 100644
index 0000000..c64c082
--- /dev/null
+++ b/trunk/Examples/octave/extend/runme.m
@@ -0,0 +1,74 @@
+# file: runme.m
+
+# This file illustrates the cross language polymorphism using directors.
+
+example 
+
+
+# CEO class, which overrides Employee::getPosition().
+
+CEO=@(name) subclass(example.Manager(name),'getPosition',@(self) "CEO");
+
+# Create an instance of our employee extension class, CEO. The calls to
+# getName() and getPosition() are standard, the call to getTitle() uses
+# the director wrappers to call CEO.getPosition. e = CEO("Alice")
+
+e = CEO("Alice");
+printf("%s is a %s\n",e.getName(),e.getPosition());
+printf("Just call her \"%s\"\n",e.getTitle());
+printf("----------------------\n");
+
+
+# Create a new EmployeeList instance.  This class does not have a C++
+# director wrapper, but can be used freely with other classes that do.
+
+list = example.EmployeeList();
+
+# EmployeeList owns its items, so we must surrender ownership of objects
+# we add. This involves first calling the __disown__ method to tell the
+# C++ director to start reference counting. We reassign the resulting
+# weakref.proxy to e so that no hard references remain. This can also be
+# done when the object is constructed, as in: e =
+# CEO("Alice").__disown()
+
+e = e.__disown();
+list.addEmployee(e);
+printf("----------------------\n");
+
+# Now we access the first four items in list (three are C++ objects that
+# EmployeeList's constructor adds, the last is our CEO). The virtual
+# methods of all these instances are treated the same. For items 0, 1, and
+# 2, both all methods resolve in C++. For item 3, our CEO, getTitle calls
+# getPosition which resolves in Octave. The call to getPosition is
+# slightly different, however, from the e.getPosition() call above, since
+# now the object reference has been "laundered" by passing through
+# EmployeeList as an Employee*. Previously, Octave resolved the call
+# immediately in CEO, but now Octave thinks the object is an instance of
+# class Employee (actually EmployeePtr). So the call passes through the
+# Employee proxy class and on to the C wrappers and C++ director,
+# eventually ending up back at the CEO implementation of getPosition().
+# The call to getTitle() for item 3 runs the C++ Employee::getTitle()
+# method, which in turn calls getPosition(). This virtual method call
+# passes down through the C++ director class to the Octave implementation
+# in CEO. All this routing takes place transparently.
+
+printf("(position, title) for items 0-3:\n");
+for i=0:3,
+  printf("  %s, \"%s\"\n",list.get_item(i).getPosition(), list.get_item(i).getTitle());
+endfor
+printf("----------------------\n");
+
+# Time to delete the EmployeeList, which will delete all the Employee*
+# items it contains. The last item is our CEO, which gets destroyed as its
+# reference count goes to zero. The Octave destructor runs, and is still
+# able to call self.getName() since the underlying C++ object still
+# exists. After this destructor runs the remaining C++ destructors run as
+# usual to destroy the object.
+
+clear list;
+printf("----------------------\n");
+
+# All done.
+
+printf("octave exit\n");
+
diff --git a/trunk/Examples/octave/funcptr/Makefile b/trunk/Examples/octave/funcptr/Makefile
new file mode 100644
index 0000000..627b0a9
--- /dev/null
+++ b/trunk/Examples/octave/funcptr/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/funcptr/example.c b/trunk/Examples/octave/funcptr/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/octave/funcptr/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/octave/funcptr/example.h b/trunk/Examples/octave/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/octave/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/octave/funcptr/example.i b/trunk/Examples/octave/funcptr/example.i
new file mode 100644
index 0000000..8b3bef6
--- /dev/null
+++ b/trunk/Examples/octave/funcptr/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/octave/funcptr/runme.m b/trunk/Examples/octave/funcptr/runme.m
new file mode 100644
index 0000000..455311c
--- /dev/null
+++ b/trunk/Examples/octave/funcptr/runme.m
@@ -0,0 +1,21 @@
+# file: runme.m
+
+example
+
+a = 37
+b = 42
+
+# Now call our C function with a bunch of callbacks
+
+printf("Trying some C callback functions\n");
+printf("    a        = %i\n", a);
+printf("    b        = %i\n", b);
+printf("    ADD(a,b) = %i\n", example.do_op(a,b,example.ADD));
+printf("    SUB(a,b) = %i\n", example.do_op(a,b,example.SUB));
+printf("    MUL(a,b) = %i\n", example.do_op(a,b,example.MUL));
+
+printf("Here is what the C callback function objects look like in Octave\n");
+example.ADD
+example.SUB
+example.MUL
+
diff --git a/trunk/Examples/octave/funcptr2/Makefile b/trunk/Examples/octave/funcptr2/Makefile
new file mode 100644
index 0000000..627b0a9
--- /dev/null
+++ b/trunk/Examples/octave/funcptr2/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/funcptr2/example.c b/trunk/Examples/octave/funcptr2/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/octave/funcptr2/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/octave/funcptr2/example.h b/trunk/Examples/octave/funcptr2/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/octave/funcptr2/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/octave/funcptr2/example.i b/trunk/Examples/octave/funcptr2/example.i
new file mode 100644
index 0000000..681775a
--- /dev/null
+++ b/trunk/Examples/octave/funcptr2/example.i
@@ -0,0 +1,18 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%callback("%(upper)s");
+int add(int, int);
+int sub(int, int);
+int mul(int, int);
+%nocallback;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/octave/funcptr2/runme.m b/trunk/Examples/octave/funcptr2/runme.m
new file mode 100644
index 0000000..1d3d8f7
--- /dev/null
+++ b/trunk/Examples/octave/funcptr2/runme.m
@@ -0,0 +1,24 @@
+# file: runme.m
+
+example 
+
+a = 37
+b = 42
+
+# Now call our C function with a bunch of callbacks
+
+printf("Trying some C callback functions\n");
+printf("    a        = %i\n", a);
+printf("    b        = %i\n", b);
+printf("    ADD(a,b) = %i\n", example.do_op(a,b,example.ADD));
+printf("    SUB(a,b) = %i\n", example.do_op(a,b,example.SUB));
+printf("    MUL(a,b) = %i\n", example.do_op(a,b,example.MUL));
+
+printf("Here is what the C callback function objects look like in Octave\n");
+example.ADD
+example.SUB
+example.MUL
+
+printf("Call the functions directly...\n");
+printf("    add(a,b) = %i\n", example.add(a,b));
+printf("    sub(a,b) = %i\n", example.sub(a,b));
diff --git a/trunk/Examples/octave/functor/Makefile b/trunk/Examples/octave/functor/Makefile
new file mode 100644
index 0000000..d910de5
--- /dev/null
+++ b/trunk/Examples/octave/functor/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/functor/example.i b/trunk/Examples/octave/functor/example.i
new file mode 100644
index 0000000..2fd3817
--- /dev/null
+++ b/trunk/Examples/octave/functor/example.i
@@ -0,0 +1,29 @@
+/* File : example.i */
+%module example
+
+
+%inline %{
+// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514
+template<class T> class Sum {
+   T res;
+public:
+   Sum(T i = 0) : res(i) { }
+   void operator() (T x) { res += x; }
+   T result() const { return res; }
+};
+
+%}
+
+// Rename the application operator to __call__ for python.
+// Note: this is normally automatic, but if you had to do it yourself
+// you would use this directive:
+//
+// %rename(__call__) *::operator();
+
+// Instantiate a few versions
+%template(intSum) Sum<int>;
+%template(doubleSum) Sum<double>;
+
+
+
+
diff --git a/trunk/Examples/octave/functor/runme.m b/trunk/Examples/octave/functor/runme.m
new file mode 100644
index 0000000..65dabcc
--- /dev/null
+++ b/trunk/Examples/octave/functor/runme.m
@@ -0,0 +1,18 @@
+# Operator overloading example
+example
+
+a = example.intSum(0);
+b = example.doubleSum(100.0);
+
+# Use the objects.  They should be callable just like a normal
+# python function.
+
+for i=0:100-1,
+    a(i);           # Note: function call
+    b(sqrt(i));     # Note: function call
+endfor
+
+a.result()
+b.result()
+
+
diff --git a/trunk/Examples/octave/operator/Makefile b/trunk/Examples/octave/operator/Makefile
new file mode 100644
index 0000000..6e625d5
--- /dev/null
+++ b/trunk/Examples/octave/operator/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).m
+
+check: all
diff --git a/trunk/Examples/octave/operator/example.h b/trunk/Examples/octave/operator/example.h
new file mode 100644
index 0000000..526f262
--- /dev/null
+++ b/trunk/Examples/octave/operator/example.h
@@ -0,0 +1,36 @@
+/* File : example.h */
+#include <math.h>
+
+class ComplexVal {
+private:
+  double rpart, ipart;
+public:
+  ComplexVal(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  ComplexVal(const ComplexVal &c) : rpart(c.rpart), ipart(c.ipart) { }
+  ComplexVal &operator=(const ComplexVal &c) {
+    rpart = c.rpart;
+    ipart = c.ipart;
+    return *this;
+  }
+  ComplexVal operator+(const ComplexVal &c) const {
+    return ComplexVal(rpart+c.rpart, ipart+c.ipart);
+  }
+  ComplexVal operator-(const ComplexVal &c) const {
+    return ComplexVal(rpart-c.rpart, ipart-c.ipart);
+  }
+  ComplexVal operator*(const ComplexVal &c) const {
+    return ComplexVal(rpart*c.rpart - ipart*c.ipart,
+		   rpart*c.ipart + c.rpart*ipart);
+  }
+  ComplexVal operator-() const {
+    return ComplexVal(-rpart, -ipart);
+  }
+  
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+
+
+
+
+  
diff --git a/trunk/Examples/octave/operator/example.i b/trunk/Examples/octave/operator/example.i
new file mode 100644
index 0000000..d4bba5c
--- /dev/null
+++ b/trunk/Examples/octave/operator/example.i
@@ -0,0 +1,24 @@
+/* File : example.i */
+%module example
+#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ
+%{
+#include "example.h"
+%}
+
+/* Now grab the original header file */
+%include "example.h"
+
+/* An output method that turns a complex into a short string */
+%extend ComplexVal {
+   char *__str() {
+       static char temp[512];
+       sprintf(temp,"(%g,%g)", $self->re(), $self->im());
+       return temp;
+   }
+
+   ComplexVal __paren(int j) {
+     return ComplexVal($self->re()*j,$self->im()*j);
+   }
+};
+
+
diff --git a/trunk/Examples/octave/operator/runme.m b/trunk/Examples/octave/operator/runme.m
new file mode 100644
index 0000000..e0f5906
--- /dev/null
+++ b/trunk/Examples/octave/operator/runme.m
@@ -0,0 +1,24 @@
+# Operator overloading example
+example
+
+a = example.ComplexVal(2,3);
+b = example.ComplexVal(-5,10);
+
+printf("a   = %s\n",a);
+printf("b   = %s\n",b);
+
+c = a + b;
+printf("c   = %s\n",c);
+printf("a*b = %s\n",a*b);
+printf("a-c = %s\n",a-c);
+
+e = example.ComplexVal(a-c);
+printf("e   = %s\n",e);
+
+# Big expression
+f = ((a+b)*(c+b*e)) + (-a);
+printf("f   = %s\n",f);
+
+# paren overloading
+printf("a(3)= %s\n",a(3));
+
diff --git a/trunk/Examples/octave/pointer/Makefile b/trunk/Examples/octave/pointer/Makefile
new file mode 100644
index 0000000..627b0a9
--- /dev/null
+++ b/trunk/Examples/octave/pointer/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/pointer/example.c b/trunk/Examples/octave/pointer/example.c
new file mode 100644
index 0000000..b877d9a
--- /dev/null
+++ b/trunk/Examples/octave/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/octave/pointer/example.i b/trunk/Examples/octave/pointer/example.i
new file mode 100644
index 0000000..a8ac794
--- /dev/null
+++ b/trunk/Examples/octave/pointer/example.i
@@ -0,0 +1,30 @@
+/* File : example.i */
+%module example
+
+%{
+extern void add(int *, int *, int *);
+extern void sub(int *, int *, int *);
+extern int divide(int, int, int *);
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/octave/pointer/runme.m b/trunk/Examples/octave/pointer/runme.m
new file mode 100644
index 0000000..c36df72
--- /dev/null
+++ b/trunk/Examples/octave/pointer/runme.m
@@ -0,0 +1,42 @@
+# file: runme.m
+
+example;
+
+# First create some objects using the pointer library.
+printf("Testing the pointer library\n");
+a = example.new_intp();
+b = example.new_intp();
+c = example.new_intp();
+example.intp_assign(a,37);
+example.intp_assign(b,42);
+
+a,b,c
+
+# Call the add() function with some pointers
+example.add(a,b,c);
+
+# Now get the result
+r = example.intp_value(c);
+printf("     37 + 42 = %i\n",r);
+
+# Clean up the pointers
+example.delete_intp(a);
+example.delete_intp(b);
+example.delete_intp(c);
+
+# Now try the typemap library
+# This should be much easier. Now how it is no longer
+# necessary to manufacture pointers.
+
+printf("Trying the typemap library\n");
+r = example.sub(37,42);
+printf("     37 - 42 = %i\n",r);
+
+# Now try the version with multiple return values
+
+printf("Testing multiple return values\n");
+[q,r] = example.divide(42,37);
+printf("     42/37 = %d remainder %d\n",q,r);
+
+
+
diff --git a/trunk/Examples/octave/reference/Makefile b/trunk/Examples/octave/reference/Makefile
new file mode 100644
index 0000000..2bce9df
--- /dev/null
+++ b/trunk/Examples/octave/reference/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/reference/example.cxx b/trunk/Examples/octave/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/octave/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/octave/reference/example.h b/trunk/Examples/octave/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/octave/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/octave/reference/example.i b/trunk/Examples/octave/reference/example.i
new file mode 100644
index 0000000..8c95b32
--- /dev/null
+++ b/trunk/Examples/octave/reference/example.i
@@ -0,0 +1,48 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+%rename(cprint) print;
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/octave/reference/runme.m b/trunk/Examples/octave/reference/runme.m
new file mode 100644
index 0000000..f59c8eb
--- /dev/null
+++ b/trunk/Examples/octave/reference/runme.m
@@ -0,0 +1,63 @@
+# file: runme.m
+
+# This file illustrates the manipulation of C++ references in Octave
+
+example
+
+# ----- Object creation -----
+
+printf("Creating some objects:\n");
+a = example.Vector(3,4,5)
+b = example.Vector(10,11,12)
+
+printf("    Created %s\n",a.cprint());
+printf("    Created %s\n",b.cprint());
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+printf("Adding a+b\n");
+c = example.addv(a,b);
+printf("    a+b = %s\n", c.cprint());
+
+clear c
+
+# ----- Create a vector array -----
+
+# Note: Using the high-level interface here
+printf("Creating an array of vectors\n");
+va = example.VectorArray(10)
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of $a and $b to the vector array
+va.set(0,a);
+va.set(1,b);
+
+va.set(2,example.addv(a,b))
+
+# Get some values from the array
+
+printf("Getting some array values\n");
+for i=0:4,
+    printf("    va(%d) = %s\n",i,va.get(i).cprint());
+end;
+
+# Watch under resource meter to check on this
+printf("Making sure we don't leak memory.\n");
+for i=0:1000000-1,
+    c = va.get(mod(i,10));
+end
+
+# ----- Clean up -----
+printf("Cleaning up\n");
+
+clear va
+clear a
+clear b
+
diff --git a/trunk/Examples/octave/simple/Makefile b/trunk/Examples/octave/simple/Makefile
new file mode 100644
index 0000000..627b0a9
--- /dev/null
+++ b/trunk/Examples/octave/simple/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/simple/example.c b/trunk/Examples/octave/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/octave/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/octave/simple/example.i b/trunk/Examples/octave/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/octave/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/octave/simple/runme.m b/trunk/Examples/octave/simple/runme.m
new file mode 100644
index 0000000..8dc5eaa
--- /dev/null
+++ b/trunk/Examples/octave/simple/runme.m
@@ -0,0 +1,22 @@
+# file: runme.m
+
+example 
+
+# Call our gcd() function
+
+x = 42
+y = 105
+g = example.gcd(x,y)
+printf("The gcd of %d and %d is %d\n",x,y,g);
+
+# Manipulate the Foo global variable
+
+# Output its current value
+example.cvar.Foo
+
+# Change its value
+example.cvar.Foo = 3.1415926
+
+# See if the change took effect
+printf("Foo = %f\n", example.cvar.Foo);
+
diff --git a/trunk/Examples/octave/template/Makefile b/trunk/Examples/octave/template/Makefile
new file mode 100644
index 0000000..3d7445a
--- /dev/null
+++ b/trunk/Examples/octave/template/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/template/example.h b/trunk/Examples/octave/template/example.h
new file mode 100644
index 0000000..7401df6
--- /dev/null
+++ b/trunk/Examples/octave/template/example.h
@@ -0,0 +1,32 @@
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %extend {
+    T getitem(int index) {
+      return $self->get(index);
+    }
+    void setitem(int index, T val) {
+      $self->set(index,val);
+    }
+  }
+#endif
+};
+
diff --git a/trunk/Examples/octave/template/example.i b/trunk/Examples/octave/template/example.i
new file mode 100644
index 0000000..8f94c4d
--- /dev/null
+++ b/trunk/Examples/octave/template/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
diff --git a/trunk/Examples/octave/template/runme.m b/trunk/Examples/octave/template/runme.m
new file mode 100644
index 0000000..a9891d4
--- /dev/null
+++ b/trunk/Examples/octave/template/runme.m
@@ -0,0 +1,37 @@
+# file: runme.m
+
+example
+
+# Call some templated functions
+example.maxint(3,7)
+example.maxdouble(3.14,2.18)
+
+# Create some class
+
+iv = example.vecint(100)
+dv = example.vecdouble(1000)
+
+for i=0:99,
+  iv.setitem(i,2*i);
+end
+
+for i=0:999,
+  dv.setitem(i, 1.0/(i+1));
+end;
+
+sum = 0;
+for i=0:99
+      sum = sum + iv.getitem(i);
+end
+sum
+
+sum = 0.0;
+for i=0:999,
+      sum = sum + dv.getitem(i);
+end
+sum
+
+clear iv
+clear dv
+
+      
diff --git a/trunk/Examples/octave/variables/Makefile b/trunk/Examples/octave/variables/Makefile
new file mode 100644
index 0000000..627b0a9
--- /dev/null
+++ b/trunk/Examples/octave/variables/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myoctave' INTERFACE='$(INTERFACE)' octave_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile octave_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/octave/variables/example.c b/trunk/Examples/octave/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/octave/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/octave/variables/example.h b/trunk/Examples/octave/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/octave/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/octave/variables/example.i b/trunk/Examples/octave/variables/example.i
new file mode 100644
index 0000000..639b6c7
--- /dev/null
+++ b/trunk/Examples/octave/variables/example.i
@@ -0,0 +1,53 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_SWIGTYPELEAK
+
+/* Some global variable declarations */
+%inline %{
+  extern "C" {
+    extern int              ivar;
+    extern short            svar;
+    extern long             lvar;
+    extern unsigned int     uivar;
+    extern unsigned short   usvar;
+    extern unsigned long    ulvar;
+    extern signed char      scvar;
+    extern unsigned char    ucvar;
+    extern char             cvar;
+    extern float            fvar;
+    extern double           dvar;
+    extern char            *strvar;
+    //    extern const char       cstrvar[];
+    extern int             *iptrvar;
+    extern char             name[256];
+
+    extern Point           *ptptr;
+    extern Point            pt;
+  }
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/octave/variables/runme.m b/trunk/Examples/octave/variables/runme.m
new file mode 100644
index 0000000..db88b18
--- /dev/null
+++ b/trunk/Examples/octave/variables/runme.m
@@ -0,0 +1,75 @@
+# file: runme.m
+
+example
+
+# Try to set the values of some global variables
+
+example.cvar.ivar   =  42;
+example.cvar.svar   = -31000;
+example.cvar.lvar   =  65537;
+example.cvar.uivar  =  123456;
+example.cvar.usvar  =  61000;
+example.cvar.ulvar  =  654321;
+example.cvar.scvar  =  -13;
+example.cvar.ucvar  =  251;
+example.cvar.cvar   =  "S";
+example.cvar.fvar   =  3.14159;
+example.cvar.dvar   =  2.1828;
+example.cvar.strvar =  "Hello World";
+example.cvar.iptrvar= example.new_int(37);
+example.cvar.ptptr  = example.new_Point(37,42);
+example.cvar.name   = "Bill";
+
+# Now print out the values of the variables
+
+printf("Variables (values printed from Octave)\n");
+
+printf("ivar      = %i\n", example.cvar.ivar);
+printf("svar      = %i\n", example.cvar.svar);
+printf("lvar      = %i\n", example.cvar.lvar);
+printf("uivar     = %i\n", example.cvar.uivar);
+printf("usvar     = %i\n", example.cvar.usvar);
+printf("ulvar     = %i\n", example.cvar.ulvar);
+printf("scvar     = %i\n", example.cvar.scvar);
+printf("ucvar     = %i\n", example.cvar.ucvar);
+printf("fvar      = %i\n", example.cvar.fvar);
+printf("dvar      = %i\n", example.cvar.dvar);
+printf("cvar      = %s\n", example.cvar.cvar);
+printf("strvar    = %s\n", example.cvar.strvar);
+#printf("cstrvar   = %s\n", example.cvar.cstrvar);
+example.cvar.iptrvar
+printf("name      = %i\n", example.cvar.name);
+printf("ptptr     = %s\n", example.Point_print(example.cvar.ptptr));
+#printf("pt        = %s\n", example.cvar.Point_print(example.cvar.pt));
+
+printf("\nVariables (values printed from C)\n");
+
+example.print_vars();
+
+printf("\nNow I'm going to try and modify some read only variables\n");
+
+printf("     Tring to set 'path'\n");
+try
+    example.cvar.path = "Whoa!";
+    printf("Hey, what's going on?!?! This shouldn't work\n");
+catch
+    printf("Good.\n");
+end_try_catch
+
+printf("     Trying to set 'status'\n");
+try
+    example.cvar.status = 0;
+    printf("Hey, what's going on?!?! This shouldn't work\n");
+catch
+    printf("Good.\n");
+end_try_catch
+
+
+printf("\nI'm going to try and update a structure variable.\n");
+
+example.cvar.pt = example.cvar.ptptr;
+
+printf("The new value is %s\n", example.Point_print(example.cvar.pt));
+
+
+
diff --git a/trunk/Examples/perl5/check.list b/trunk/Examples/perl5/check.list
new file mode 100644
index 0000000..e15f02e
--- /dev/null
+++ b/trunk/Examples/perl5/check.list
@@ -0,0 +1,14 @@
+# see top-level Makefile.in
+class
+constants
+constants2
+funcptr
+import
+java
+multimap
+multiple_inheritance
+pointer
+reference
+simple
+value
+variables
diff --git a/trunk/Examples/perl5/class/Makefile b/trunk/Examples/perl5/class/Makefile
new file mode 100644
index 0000000..f533617
--- /dev/null
+++ b/trunk/Examples/perl5/class/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/class/example.cxx b/trunk/Examples/perl5/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/perl5/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/perl5/class/example.dsp b/trunk/Examples/perl5/class/example.dsp
new file mode 100644
index 0000000..bbdedc0
--- /dev/null
+++ b/trunk/Examples/perl5/class/example.dsp
@@ -0,0 +1,152 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/class/example.h b/trunk/Examples/perl5/class/example.h
new file mode 100644
index 0000000..b0671d5
--- /dev/null
+++ b/trunk/Examples/perl5/class/example.h
@@ -0,0 +1,47 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+typedef Square TSquare;
+class CFoo
+{
+public:
+    static Square MakeSquare(void) {return Square(4.0);};
+    static TSquare MakeTSquare(void) {return Square(4.0);};
+};
+
+
+
+
+  
diff --git a/trunk/Examples/perl5/class/example.i b/trunk/Examples/perl5/class/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/perl5/class/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/perl5/class/index.html b/trunk/Examples/perl5/class/index.html
new file mode 100644
index 0000000..58a50ad
--- /dev/null
+++ b/trunk/Examples/perl5/class/index.html
@@ -0,0 +1,208 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:class</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/perl5/class/</tt>
+<hr>
+
+<H2>Wrapping a simple C++ class</H2>
+
+<p>
+This example illustrates the most primitive form of C++ class wrapping performed
+by SWIG.  In this case, C++ classes are simply transformed into a collection of
+C-style functions that provide access to class members.
+
+<h2>The C++ Code</h2>
+
+Suppose you have some C++ classes described by the following (and admittedly lame) 
+header file:
+
+<blockquote>
+<pre>
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+A simple SWIG interface for this can be built by simply grabbing the header file
+like this:
+
+<blockquote>
+<pre>
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+</pre>
+</blockquote>
+
+Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> option like this:
+<blockquote>
+<pre>
+% swig -c++ -python example.i
+</pre>
+</blockquote>
+
+<h2>A sample Perl script</h2>
+
+Click <a href="runme.pl">here</a> to see a script that calls the C++ functions from Perl.
+
+<h2>Key points</h2>
+
+<ul>
+<li>To create a new object, you call a constructor like this:
+
+<blockquote>
+<pre>
+$c = example::new_Circle(10.0);
+</pre>
+</blockquote>
+
+<p>
+<li>To access member data, a pair of accessor functions are used.
+For example:
+
+<blockquote>
+<pre>
+example::Shape_x_set($c,15);    # Set member data
+$x = example::Shape_x_get($c);   # Get member data
+</pre>
+</blockquote>
+
+Note: when accessing member data, the name of the class in which
+the data member is defined is used.  For example <tt>Shape_x_get()</tt>.
+
+<p>
+<li>To invoke a member function, you simply do this
+
+<blockquote>
+<pre>
+print "The area is ", example::Shape_area($c);
+</pre>
+</blockquote>
+
+<p>
+<li>Type checking knows about the inheritance structure of C++. For example:
+
+<blockquote>
+<pre>
+example::Shape_area($c);       # Works (c is a Shape)
+example::Circle_area($c);      # Works (c is a Circle)
+example::Square_area($c);      # Fails (c is definitely not a Square)
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a destructor, simply do this
+
+<blockquote>
+<pre>
+example::delete_Shape($c);     # Deletes a shape
+</pre>
+</blockquote>
+
+<p>
+<li>Static member variables are wrapped as C global variables.  For example:
+
+<blockquote>
+<pre>
+$n = $example::Shape_nshapes;     # Get a static data member
+$example::Shapes_nshapes = 13;   # Set a static data member
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>General Comments</h2>
+
+<ul>
+<li>This low-level interface is not the only way to handle C++ code.  Proxy classes
+provide a much higher-level interface.
+
+<p>
+<li>SWIG *does* know how to properly perform upcasting of objects in an inheritance
+hierarchy (including multiple inheritance).  Therefore it is perfectly safe to pass
+an object of a derived class to any function involving a base class.
+
+<p>
+<li>A wide variety of C++ features are not currently supported by SWIG.  Here is the
+short and incomplete list:
+
+<p>
+<ul>
+<li>Overloaded methods and functions.  SWIG wrappers don't know how to resolve name
+conflicts so you must give an alternative name to any overloaded method name using the
+%name directive like this:
+
+<blockquote>
+<pre>
+void foo(int a);  
+%name(foo2) void foo(double a, double b);
+</pre>
+</blockquote>
+
+<p>
+<li>Overloaded operators.  Not supported at all. The only workaround for this is
+to write a helper function. For example:
+
+<blockquote>
+<pre>
+%inline %{
+    Vector *vector_add(Vector *a, Vector *b) {
+          ... whatever ...
+    }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>Namespaces.  Not supported at all. Won't be supported until SWIG2.0 (if at all).
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/perl5/class/runme.pl b/trunk/Examples/perl5/class/runme.pl
new file mode 100644
index 0000000..076e143
--- /dev/null
+++ b/trunk/Examples/perl5/class/runme.pl
@@ -0,0 +1,60 @@
+# file: runme.pl
+
+# This file illustrates the low-level C++ interface
+# created by SWIG.  In this case, all of our C++ classes
+# get converted into function calls.
+
+use example;
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = new example::Circle(10);
+print "    Created circle $c\n";
+$s = new example::Square(10);
+print "    Created square $s\n";
+
+# ----- Access a static member -----
+
+print "\nA total of $example::Shape::nshapes shapes were created\n";
+
+# ----- Member data access -----
+
+# Set the location of the object.
+# Note: methods in the base class Shape are used since
+# x and y are defined there.
+
+$c->{x} = 20;
+$c->{y} = 30;
+$s->{x} = -10;
+$s->{y} = 5;
+
+print "\nHere is their current position:\n";
+print "    Circle = (",$c->{x},",", $c->{y},")\n";
+print "    Square = (",$s->{x},",", $s->{y},")\n";
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n";
+foreach $o ($c,$s) {
+      print "    $o\n";
+      print "        area      = ", $o->area(), "\n";
+      print "        perimeter = ", $o->perimeter(), "\n";
+  }
+
+# ----- Delete everything -----
+
+print "\nGuess I'll clean up now\n";
+
+# Note: this invokes the virtual destructor
+
+$c->DESTROY();
+$s->DESTROY();
+
+print $example::Shape::nshapes," shapes remain\n";
+
+$square = example::CFoo::MakeSquare();
+$tsquare = example::CFoo::MakeTSquare();
+print "Areas ", $square->area(), " ", $tsquare->area(),"\n";
+
+print "Goodbye\n";
diff --git a/trunk/Examples/perl5/constants/Makefile b/trunk/Examples/perl5/constants/Makefile
new file mode 100644
index 0000000..576d2a0
--- /dev/null
+++ b/trunk/Examples/perl5/constants/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       =
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    =
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/constants/example.i b/trunk/Examples/perl5/constants/example.i
new file mode 100644
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/perl5/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/perl5/constants/index.html b/trunk/Examples/perl5/constants/index.html
new file mode 100644
index 0000000..f38338b
--- /dev/null
+++ b/trunk/Examples/perl5/constants/index.html
@@ -0,0 +1,53 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:constants</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/perl5/constants/</tt>
+<hr>
+
+<H2>Wrapping C Constants</H2>
+
+<p>
+When SWIG encounters C preprocessor macros and C declarations that look like constants,
+it creates Perl5 variables with an identical value.  Click <a href="example.i">here</a>
+to see a SWIG interface with some constant declarations in it.
+
+<h2>Accessing Constants from Perl</h2>
+
+Click <a href="runme.pl">here</a> to see a script that prints out the values
+of the constants contained in the above file.
+
+<h2>Key points</h2>
+
+<ul>
+<li>The values of preprocessor macros are converted into Perl constants.
+<li>Types are inferred by syntax (e.g., "3" is an integer and "3.5" is a float).
+<li>Character constants such as 'x' are converted into Perl strings.
+<li>C string literals such as "Hello World" are converted into Perl strings.
+<li>Macros that are not fully defined are simply ignored.  For example:
+<blockquote>
+<pre>
+#define EXTERN extern
+</pre>
+</blockquote>
+is ignored because SWIG has no idea what type of variable this would be.
+
+<p>
+<li>Expressions are allowed provided that all of their components are defined. Otherwise, the constant is ignored.
+
+<li>Certain C declarations involving 'const' are also turned into Perl constants. 
+
+<p>
+<li>The constants that appear in a SWIG interface file do not have to appear in any sort
+of matching C source file since the creation of a constant does not require linkage
+to a stored value (i.e., a value held in a C global variable or memory location).
+</ul>
+
+<hr>
+
+
+</body>
+</html>
diff --git a/trunk/Examples/perl5/constants/runme.pl b/trunk/Examples/perl5/constants/runme.pl
new file mode 100644
index 0000000..6e8a6ed
--- /dev/null
+++ b/trunk/Examples/perl5/constants/runme.pl
@@ -0,0 +1,29 @@
+# file: runme.pl
+
+use example;
+
+print "ICONST  = ", $example::ICONST, " (should be 42)\n";
+print "FCONST  = ", $example::FCONST, " (should be 2.1828)\n";
+print "CCONST  = ", $example::CCONST, " (should be 'x')\n";
+print "CCONST2 = ", $example::CCONST2," (this should be on a new line)\n";
+print "SCONST  = ", $example::SCONST, " (should be 'Hello World')\n";
+print "SCONST2 = ", $example::SCONST2, " (should be '\"Hello World\"')\n";
+print "EXPR    = ", $example::EXPR,   " (should be 48.5484)\n";
+print "iconst  = ", $example::iconst, " (should be 37)\n";
+print "fconst  = ", $example::fconst, " (should be 3.14)\n";
+
+
+if ($example::EXTERN) {
+    print "EXTERN = ", example.EXTERN, " (Arg! This shouldn't print anything)\n";
+} else {
+    print "EXTERN isn't defined (good)\n";
+}
+
+if ($example::FOO) {
+    print "FOO    = ", example.FOO, "(Arg! This shouldn't print anything)\n";
+} else {
+    print "FOO isn't defined (good)\n";
+}
+
+
+
diff --git a/trunk/Examples/perl5/constants2/Makefile b/trunk/Examples/perl5/constants2/Makefile
new file mode 100644
index 0000000..4ba4b25
--- /dev/null
+++ b/trunk/Examples/perl5/constants2/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       =
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = -const
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/constants2/example.i b/trunk/Examples/perl5/constants2/example.i
new file mode 100644
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/perl5/constants2/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/perl5/constants2/runme.pl b/trunk/Examples/perl5/constants2/runme.pl
new file mode 100644
index 0000000..d16f3b3
--- /dev/null
+++ b/trunk/Examples/perl5/constants2/runme.pl
@@ -0,0 +1,16 @@
+# file: runme.pl
+
+use example;
+
+print "ICONST  = ", example::ICONST, " (should be 42)\n";
+print "FCONST  = ", example::FCONST, " (should be 2.1828)\n";
+print "CCONST  = ", example::CCONST, " (should be 'x')\n";
+print "CCONST2 = ", example::CCONST2," (this should be on a new line)\n";
+print "SCONST  = ", example::SCONST, " (should be 'Hello World')\n";
+print "SCONST2 = ", example::SCONST2, " (should be '\"Hello World\"')\n";
+print "EXPR    = ", example::EXPR,   " (should be 48.5484)\n";
+print "iconst  = ", example::iconst, " (should be 37)\n";
+print "fconst  = ", example::fconst, " (should be 3.14)\n";
+
+
+
diff --git a/trunk/Examples/perl5/funcptr/Makefile b/trunk/Examples/perl5/funcptr/Makefile
new file mode 100644
index 0000000..ce2bbb5
--- /dev/null
+++ b/trunk/Examples/perl5/funcptr/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/funcptr/example.c b/trunk/Examples/perl5/funcptr/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/perl5/funcptr/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/perl5/funcptr/example.h b/trunk/Examples/perl5/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/perl5/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/perl5/funcptr/example.i b/trunk/Examples/perl5/funcptr/example.i
new file mode 100644
index 0000000..8b3bef6
--- /dev/null
+++ b/trunk/Examples/perl5/funcptr/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/perl5/funcptr/index.html b/trunk/Examples/perl5/funcptr/index.html
new file mode 100644
index 0000000..7333a39
--- /dev/null
+++ b/trunk/Examples/perl5/funcptr/index.html
@@ -0,0 +1,90 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:funcptr</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/perl5/funcptr/</tt>
+<hr>
+
+<H2>Pointers to Functions</H2>
+
+<p>
+Okay, just what in the heck does SWIG do with a declaration like this?
+
+<blockquote>
+<pre>
+int do_op(int a, int b, int (*op)(int, int));
+</pre>
+</blockquote>
+
+Well, it creates a wrapper as usual.  Of course, that does raise some
+questions about the third argument (the pointer to a function). 
+
+<p>
+In this case, SWIG will wrap the function pointer as it does for all other
+pointers.  However, in order to actually call this function from a script,
+you will need to pass some kind of C function pointer object.  In C,
+this is easy, you just supply a function name as an argument like this:
+
+<blockquote>
+<pre>
+/* Some callback function */
+int add(int a, int b) {
+   return a+b;
+} 
+...
+int r = do_op(x,y,add);
+</pre>
+</blockquote>
+
+To make this work with SWIG, you will need to do a little extra work.  Specifically,
+you need to create some function pointer objects using the %constant directive like this:
+
+<blockquote>
+<pre>
+%constant(int (*)(int,int)) ADD = add;
+</pre>
+</blockquote>
+
+Now, in a script, you would do this:
+
+<blockquote>
+<pre>
+$r = do_op($x,$y, $ADD);
+</pre>
+</blockquote>
+
+<h2>An Example</h2>
+
+Here are some files that illustrate this with a simple example:
+
+<ul>
+<li><a href="example.c">example.c</a>
+<li><a href="example.h">example.h</a>
+<li><a href="example.i">example.i</a> (SWIG interface)
+<li><a href="runme.pl">runme.pl</a> (Sample script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>The value of a function pointer must correspond to a function written in C or C++.
+It is not possible to pass an arbitrary Perl function object in as a substitute for a C 
+function pointer.
+
+<p>
+<li>A perl function can be used as a C/C++ callback if you write some
+clever typemaps and are very careful about how you create your extension.
+This is an advanced topic not covered here.
+</ul>
+
+<hr>
+</body>
+</html>
+
+
+
+
diff --git a/trunk/Examples/perl5/funcptr/runme.pl b/trunk/Examples/perl5/funcptr/runme.pl
new file mode 100644
index 0000000..a73b538
--- /dev/null
+++ b/trunk/Examples/perl5/funcptr/runme.pl
@@ -0,0 +1,21 @@
+# file: runme.pl
+
+use example;
+
+$a = 37;
+$b = 42;
+
+# Now call our C function with a bunch of callbacks
+
+print "Trying some C callback functions\n";
+print "    a        = $a\n";
+print "    b        = $b\n";
+print "    ADD(a,b) = ", example::do_op($a,$b,$example::ADD),"\n";
+print "    SUB(a,b) = ", example::do_op($a,$b,$example::SUB),"\n";
+print "    MUL(a,b) = ", example::do_op($a,$b,$example::MUL),"\n";
+
+print "Here is what the C callback function objects look like in Perl\n";
+print "    ADD      = $example::ADD\n";
+print "    SUB      = $example::SUB\n";
+print "    MUL      = $example::MUL\n";
+
diff --git a/trunk/Examples/perl5/import/Makefile b/trunk/Examples/perl5/import/Makefile
new file mode 100644
index 0000000..60dfdfc
--- /dev/null
+++ b/trunk/Examples/perl5/import/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='baseclass' INTERFACE='base.i' perl5_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' perl5_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' perl5_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' perl5_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/import/README b/trunk/Examples/perl5/import/README
new file mode 100644
index 0000000..030a33b
--- /dev/null
+++ b/trunk/Examples/perl5/import/README
@@ -0,0 +1,39 @@
+This example tests the %import directive and working with multiple modules.
+
+Use 'perl runme.pl' to run a test.
+
+Overview:
+---------
+
+The example defines 4 different extension modules--each wrapping
+a separate C++ class.
+
+     base.i     -  Base class
+     foo.i      -  Foo class derived from Base
+     bar.i      -  Bar class derived from Base
+     spam.i     -  Spam class derived from Bar
+
+Each module uses %import to refer to another module.  For
+example, the 'foo.i' module uses '%import base.i' to get
+definitions for its base class.
+
+If everything is okay, all of the modules will load properly and
+type checking will work correctly. Caveat: Some compilers, for example
+gcc-3.2.x, generate broken vtables with the inline methods in this test.
+This is not a SWIG problem and can usually be solved with non-inlined
+destructors compiled into separate shared objects/DLLs.
+
+Unix:
+-----
+- Run make
+- Run the test as described above
+
+Windows:
+--------
+- Use the Visual C++ 6 workspace file (example.dsw). Build the runtime
+  project DLL first followed by the other 4 DLLs as they all have a
+  dependency on the runtime DLL. The Batch build option in the Build menu
+  is usually the easiest way to do this. Only use the Release builds not
+  the Debug builds.
+- Run the test as described above
+
diff --git a/trunk/Examples/perl5/import/bar.dsp b/trunk/Examples/perl5/import/bar.dsp
new file mode 100644
index 0000000..682c217
--- /dev/null
+++ b/trunk/Examples/perl5/import/bar.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="bar" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=bar - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak" CFG="bar - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "bar - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "bar - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"bar.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"bar.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "bar - Win32 Debug"

+# Name "bar - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\bar_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\bar.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\bar.i

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/import/bar.h b/trunk/Examples/perl5/import/bar.h
new file mode 100644
index 0000000..fa4185f
--- /dev/null
+++ b/trunk/Examples/perl5/import/bar.h
@@ -0,0 +1,22 @@
+#include "base.h"
+
+class Bar : public Base {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual void A() { 
+    printf("I'm Bar::A\n");
+  }
+  void B() {
+    printf("I'm Bar::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Bar *fromBase(Base *b) {
+    return dynamic_cast<Bar *>(b);
+  }
+
+};
+
+
diff --git a/trunk/Examples/perl5/import/bar.i b/trunk/Examples/perl5/import/bar.i
new file mode 100644
index 0000000..5816cbe
--- /dev/null
+++ b/trunk/Examples/perl5/import/bar.i
@@ -0,0 +1,9 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+
diff --git a/trunk/Examples/perl5/import/base.dsp b/trunk/Examples/perl5/import/base.dsp
new file mode 100644
index 0000000..7a0ea80
--- /dev/null
+++ b/trunk/Examples/perl5/import/base.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="base" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=base - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak" CFG="base - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "base - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "base - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"baseclass.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"baseclass.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "base - Win32 Debug"

+# Name "base - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\base_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\base.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\base.i

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/import/base.h b/trunk/Examples/perl5/import/base.h
new file mode 100644
index 0000000..5a266f6
--- /dev/null
+++ b/trunk/Examples/perl5/import/base.h
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual void A() {
+         printf("I'm Base::A\n");
+     }
+     void B() {
+       printf("I'm Base::B\n");
+     }
+     virtual Base *toBase() {
+       return static_cast<Base *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/perl5/import/base.i b/trunk/Examples/perl5/import/base.i
new file mode 100644
index 0000000..dc99383
--- /dev/null
+++ b/trunk/Examples/perl5/import/base.i
@@ -0,0 +1,6 @@
+%module baseclass
+%{
+#include "base.h"
+%}
+
+%include base.h
diff --git a/trunk/Examples/perl5/import/example.dsw b/trunk/Examples/perl5/import/example.dsw
new file mode 100644
index 0000000..d395d46
--- /dev/null
+++ b/trunk/Examples/perl5/import/example.dsw
@@ -0,0 +1,65 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00

+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!

+

+###############################################################################

+

+Project: "bar"=.\bar.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "base"=.\base.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "foo"=.\foo.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "spam"=.\spam.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Global:

+

+Package=<5>

+{{{

+}}}

+

+Package=<3>

+{{{

+}}}

+

+###############################################################################

+

diff --git a/trunk/Examples/perl5/import/foo.dsp b/trunk/Examples/perl5/import/foo.dsp
new file mode 100644
index 0000000..7555601
--- /dev/null
+++ b/trunk/Examples/perl5/import/foo.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="foo" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=foo - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak" CFG="foo - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "foo - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "foo - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"foo.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"foo.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "foo - Win32 Debug"

+# Name "foo - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\foo_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\foo.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\foo.i

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/import/foo.h b/trunk/Examples/perl5/import/foo.h
new file mode 100644
index 0000000..dd51840
--- /dev/null
+++ b/trunk/Examples/perl5/import/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Foo : public Base {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual void A() { 
+    printf("I'm Foo::A\n");
+  }
+  void B() {
+    printf("I'm Foo::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Foo *fromBase(Base *b) {
+    return dynamic_cast<Foo *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/perl5/import/foo.i b/trunk/Examples/perl5/import/foo.i
new file mode 100644
index 0000000..27feb2e
--- /dev/null
+++ b/trunk/Examples/perl5/import/foo.i
@@ -0,0 +1,8 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
diff --git a/trunk/Examples/perl5/import/runme.pl b/trunk/Examples/perl5/import/runme.pl
new file mode 100644
index 0000000..1db0807
--- /dev/null
+++ b/trunk/Examples/perl5/import/runme.pl
@@ -0,0 +1,116 @@
+# file: runme.pl
+# Test various properties of classes defined in separate modules
+
+print "Testing the %import directive\n";
+use baseclass;
+use foo;
+use bar;
+use spam;
+
+# Create some objects
+
+print "Creating some objects\n";
+
+$a = new baseclass::Base();
+$b = new foo::Foo();
+$c = new bar::Bar();
+$d = new spam::Spam();
+
+# Try calling some methods
+print "Testing some methods\n";
+print "Should see 'Base::A' ---> ";
+$a->A();
+print "Should see 'Base::B' ---> ";
+$a->B();
+
+print "Should see 'Foo::A' ---> ";
+$b->A();
+print "Should see 'Foo::B' ---> ";
+$b->B();
+
+print "Should see 'Bar::A' ---> ";
+$c->A();
+print "Should see 'Bar::B' ---> ";
+$c->B();
+
+print "Should see 'Spam::A' ---> ";
+$d->A();
+print "Should see 'Spam::B' ---> ";
+$d->B();
+
+# Try some casts
+
+print "\nTesting some casts\n";
+
+$x = $a->toBase();
+print "Should see 'Base::A' ---> ";
+$x->A();
+print "Should see 'Base::B' ---> ";
+$x->B();
+
+$x = $b->toBase();
+print "Should see 'Foo::A' ---> ";
+$x->A();
+
+print "Should see 'Base::B' ---> ";
+$x->B();
+
+$x = $c->toBase();
+print "Should see 'Bar::A' ---> ";
+$x->A();
+
+print "Should see 'Base::B' ---> ";
+$x->B();
+
+$x = $d->toBase();
+print "Should see 'Spam::A' ---> ";
+$x->A();
+
+print "Should see 'Base::B' ---> ";
+$x->B();
+
+$x = $d->toBar();
+print "Should see 'Bar::B' ---> ";
+$x->B();
+
+print "\nTesting some dynamic casts\n";
+$x = $d->toBase();
+
+print " Spam -> Base -> Foo : ";
+$y = foo::Foo::fromBase($x);
+if ($y) {
+    print "bad swig\n";
+} else {
+    print "good swig\n";
+}
+
+print " Spam -> Base -> Bar : ";
+$y = bar::Bar::fromBase($x);
+if ($y) {
+    print "good swig\n";
+} else {
+    print "bad swig\n";
+}
+      
+print " Spam -> Base -> Spam : ";
+$y = spam::Spam::fromBase($x);
+if ($y) {
+    print "good swig\n";
+} else {
+    print "bad swig\n";
+}
+
+print " Foo -> Spam : ";
+#print $b;
+$y = spam::Spam::fromBase($b);
+print $y;
+if ($y) {
+    print "bad swig\n";
+} else {
+    print "good swig\n";
+}
+
+
+
+
+
diff --git a/trunk/Examples/perl5/import/spam.dsp b/trunk/Examples/perl5/import/spam.dsp
new file mode 100644
index 0000000..ed41de3
--- /dev/null
+++ b/trunk/Examples/perl5/import/spam.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="spam" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=spam - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak" CFG="spam - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "spam - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "spam - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"spam.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"spam.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "spam - Win32 Debug"

+# Name "spam - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\spam_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\spam.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\spam.i

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -c++ -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/import/spam.h b/trunk/Examples/perl5/import/spam.h
new file mode 100644
index 0000000..b4e7a26
--- /dev/null
+++ b/trunk/Examples/perl5/import/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+class Spam : public Bar {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual void A() { 
+    printf("I'm Spam::A\n");
+  }
+  void B() {
+    printf("I'm Spam::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  virtual Bar *toBar() {
+    return static_cast<Bar *>(this);
+  }
+  static Spam *fromBase(Base *b) {
+    return dynamic_cast<Spam *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/perl5/import/spam.i b/trunk/Examples/perl5/import/spam.i
new file mode 100644
index 0000000..d3d9121
--- /dev/null
+++ b/trunk/Examples/perl5/import/spam.i
@@ -0,0 +1,9 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+
diff --git a/trunk/Examples/perl5/index.html b/trunk/Examples/perl5/index.html
new file mode 100644
index 0000000..254bd41
--- /dev/null
+++ b/trunk/Examples/perl5/index.html
@@ -0,0 +1,98 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5</title>
+</head>
+
+<body bgcolor="#ffffff">
+<H1>SWIG Perl Examples</H1>
+
+<p>
+The following examples illustrate the use of SWIG with Perl.
+
+<ul>
+<li><a href="simple/index.html">simple</a>.  A minimal example showing how SWIG can
+be used to wrap a C function and a global variable.
+<li><a href="constants/index.html">constants</a>.  This shows how preprocessor macros and
+certain C declarations are turned into constants.
+<li><a href="variables/index.html">variables</a>.  This example shows how to access C global variables from Perl.
+<li><a href="value/index.html">value</a>. How to pass and return structures by value.
+<li><a href="class/index.html">class</a>. How to wrap a simple C++ class.
+<li><a href="reference/index.html">reference</a>. C++ references.
+<li><a href="pointer/index.html">pointer</a>. Simple pointer handling.
+<li><a href="funcptr/index.html">funcptr</a>. Pointers to functions.
+</ul>
+
+<h2>Compilation Issues</h2>
+
+<ul>
+<li>To create a Perl extension, SWIG is run with the following options:
+
+<blockquote>
+<pre>
+% swig -perl5 interface.i
+</pre>
+</blockquote>
+
+<li>The compilation of examples is done using the file <tt>Example/Makefile</tt>.  This
+makefile performs a manual module compilation which is platform specific.  Typically,
+the steps look like this (Linux):
+
+<blockquote>
+<pre>
+% swig -perl5 interface.i
+% gcc -fpic -c -Dbool=char -I/usr/lib/perl5/5.00503/i386-linux/CORE interface_wrap.c
+% gcc -shared interface_wrap.o $(OBJS) -o interface.so 
+% perl
+use interface;
+...
+</pre>
+</blockquote>
+
+<li>The politically "correct" way to compile a Perl extension module is to use MakeMaker
+and related tools (especially if you are considering third-party distribution).  Consult
+a book such as Advanced Perl Programming for details.
+
+</ul>
+
+<h2>Compatibility</h2>
+
+The examples have been extensively tested on the following platforms:
+
+<p>
+<ul>
+<li>Linux
+<li>Solaris
+</ul>
+
+Please see the <a href="../../Doc/Manual/Windows.html">Windows</a> page in the main manual for information on using the examples on Windows. <p>
+
+The most recent version of Perl used for testing is as follows:
+
+<blockquote>
+<pre>
+% perl -version
+This is perl, v5.6.0 built for sun4-solaris
+
+Copyright 1987-2000, Larry Wall
+
+Perl may be copied only under the terms of either the Artistic License or the
+GNU General Public License, which may be found in the Perl 5.0 source kit.
+
+Complete documentation for Perl, including FAQ lists, should be found on
+this system using `man perl' or `perldoc perl'.  If you have access to the
+Internet, point your browser at http://www.perl.com/, the Perl Home Page.
+</pre>
+</blockquote>
+
+<p>
+Due to wide variations in the Perl C API and differences between versions such as the ActivePerl release for Windows,
+the code generated by SWIG is extremely messy.  We have made every attempt to maintain compatibility with
+many Perl releases going as far back as 5.003 and as recent as 5.6.  However, your mileage may vary.
+If you experience a problem, please let us know by 
+contacting us on the <a href="http://www.swig.org/mail.html">mailing lists</a>.
+Better yet, send us a patch.
+
+</body>
+</html>
+
+
diff --git a/trunk/Examples/perl5/inline/Makefile b/trunk/Examples/perl5/inline/Makefile
new file mode 100644
index 0000000..4ac085e
--- /dev/null
+++ b/trunk/Examples/perl5/inline/Makefile
@@ -0,0 +1,7 @@
+all:
+
+run:
+	perl runme.pl
+
+clean:
+	rm -fr _Inline *~
diff --git a/trunk/Examples/perl5/inline/README b/trunk/Examples/perl5/inline/README
new file mode 100644
index 0000000..33be949
--- /dev/null
+++ b/trunk/Examples/perl5/inline/README
@@ -0,0 +1,2 @@
+This example requires the Inline::SWIG package.
+
diff --git a/trunk/Examples/perl5/inline/runme.pl b/trunk/Examples/perl5/inline/runme.pl
new file mode 100644
index 0000000..8b0f089
--- /dev/null
+++ b/trunk/Examples/perl5/inline/runme.pl
@@ -0,0 +1,34 @@
+use Inline SWIG => <<"END_CODE", SWIG_ARGS => '-c++ -proxy', CC => 'g++', LD=>'g++';
+  class Foo {
+  public:
+    int meaning() { return 42; };
+  };
+END_CODE
+
+my $o = new Foo();
+print $o->meaning(),"\n";
+
+use Inline SWIG => ' ', SWIG_INTERFACE => <<"END_CODE", SWIG_ARGS => '-c++', CC => "g++", LD => "g++";
+%include std_string.i
+%inline {
+  template <class Type>
+  class Bar {
+    Type _val;
+  public: 
+    Bar(Type v) : _val(v) {}
+    Type meaning() { return _val; }  
+  };
+}
+%template(Bar_i) Bar<int>;
+%template(Bar_d) Bar<double>;
+%template(Bar_s) Bar<std::string>;
+END_CODE
+
+my $o = new Bar_i(1);
+print $o->meaning(),"\n";
+
+my $o = new Bar_d(2);
+print $o->meaning(),"\n";
+
+my $o = new Bar_s("hello");
+print $o->meaning(),"\n";
diff --git a/trunk/Examples/perl5/java/Example.java b/trunk/Examples/perl5/java/Example.java
new file mode 100644
index 0000000..91ddb1a
--- /dev/null
+++ b/trunk/Examples/perl5/java/Example.java
@@ -0,0 +1,29 @@
+public class Example {
+    public   int      mPublicInt;
+    
+    public Example() {
+	mPublicInt = 0;
+    }
+    
+    public Example(int IntVal) {
+	mPublicInt = IntVal;
+    }
+    
+    
+    public int Add(int a, int b) {
+	return (a+b);
+    }
+    
+    public float Add(float a, float b) {
+	return (a+b);
+    }
+    
+    public String Add(String a, String b) {
+	return (a+b);
+    }
+    
+    public Example Add(Example a, Example b) {
+	return new Example(a.mPublicInt + b.mPublicInt);
+    }
+}
+
diff --git a/trunk/Examples/perl5/java/Makefile b/trunk/Examples/perl5/java/Makefile
new file mode 100644
index 0000000..882eba7
--- /dev/null
+++ b/trunk/Examples/perl5/java/Makefile
@@ -0,0 +1,26 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all:: Example.class
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj" \
+	CXXSHARED="gcj -fpic -shared Example.class" PERL5_CCFLAGS='' PERL5_EXP='' LIBS="-lstdc++" perl5_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+	rm -f *.class Example.h 
+
+check: all
+
+run:
+	perl runme.pl
+
+Example.class: Example.java
+	gcj -fPIC -C -c -g Example.java
+	gcjh  Example
+
diff --git a/trunk/Examples/perl5/java/example.i b/trunk/Examples/perl5/java/example.i
new file mode 100644
index 0000000..a82abb2
--- /dev/null
+++ b/trunk/Examples/perl5/java/example.i
@@ -0,0 +1,10 @@
+%module example
+
+%include <cni.i>
+
+%{
+#include "Example.h"
+%}
+
+
+%include Example.h
diff --git a/trunk/Examples/perl5/java/runme.pl b/trunk/Examples/perl5/java/runme.pl
new file mode 100644
index 0000000..56ad6e4
--- /dev/null
+++ b/trunk/Examples/perl5/java/runme.pl
@@ -0,0 +1,29 @@
+use example;
+
+example::JvCreateJavaVM(undef);
+example::JvAttachCurrentThread(undef, undef);
+
+$e1 = new example::Example(1);
+print $e1->{mPublicInt},"\n";
+
+$e2 = new example::Example(2);
+print $e2->{mPublicInt},"\n";
+
+$i = $e1->Add(1,2);
+print $i,"\n";
+
+$d = $e2->Add(1.0,2.0);
+print $d,"\n";
+
+$d = $e2->Add("1","2");
+print $d,"\n";
+
+$e3 = $e1->Add($e1,$e2);
+print $e3->{mPublicInt},"\n";
+
+
+$s = $e2->Add("a","b");
+print $s,"\n";
+
+
+example::JvDetachCurrentThread()
diff --git a/trunk/Examples/perl5/multimap/Makefile b/trunk/Examples/perl5/multimap/Makefile
new file mode 100644
index 0000000..ce2bbb5
--- /dev/null
+++ b/trunk/Examples/perl5/multimap/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/multimap/example.c b/trunk/Examples/perl5/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/perl5/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/perl5/multimap/example.dsp b/trunk/Examples/perl5/multimap/example.dsp
new file mode 100644
index 0000000..2d29576
--- /dev/null
+++ b/trunk/Examples/perl5/multimap/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/multimap/example.i b/trunk/Examples/perl5/multimap/example.i
new file mode 100644
index 0000000..64eb6a7
--- /dev/null
+++ b/trunk/Examples/perl5/multimap/example.i
@@ -0,0 +1,93 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+%include typemaps.i
+
+extern int    gcd(int x, int y);
+
+%typemap(arginit) (int argc, char *argv[]) "$2 = 0;";
+
+%typemap(in) (int argc, char *argv[]) {
+  AV *tempav;
+  SV **tv;
+  I32 len;
+  int i;
+  if (!SvROK($input)) {
+    SWIG_exception(SWIG_ValueError,"$input is not an array.");
+  }
+  if (SvTYPE(SvRV($input)) != SVt_PVAV) {
+    SWIG_exception(SWIG_ValueError,"$input is not an array.");
+  }
+  tempav = (AV*)SvRV($input);
+  len = av_len(tempav);
+  $1 = (int) len+1;
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i < $1; i++) {
+    tv = av_fetch(tempav, i, 0);
+    $2[i] = (char *) SvPV(*tv,PL_na);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char *argv[]) {
+  free($2);
+}
+
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  STRLEN temp;
+  $1 = (char *) SvPV($input, temp);
+  $2 = (int) temp;
+}
+
+extern int count(char *bytes, int len, char c);
+
+
+/* This example shows how to wrap a function that mutates a string */
+
+%typemap(in) (char *str, int len) {
+  STRLEN templen;
+  char *temp;
+  temp = (char *) SvPV($input,templen);
+  $2 = (int) templen;
+  $1 = (char *) malloc($2+1);
+  memmove($1,temp,$2);
+}
+
+/* Return the mutated string as a new object.  */
+
+%typemap(argout) (char *str, int len) {
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $result = sv_newmortal();
+  sv_setpvn((SV*)ST(argvi++),$1,$2);
+  free($1);
+}   
+
+extern void capitalize(char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
+   }
+}
+
+extern void circle(double cx, double cy);
+
+
diff --git a/trunk/Examples/perl5/multimap/runme.pl b/trunk/Examples/perl5/multimap/runme.pl
new file mode 100644
index 0000000..416055f
--- /dev/null
+++ b/trunk/Examples/perl5/multimap/runme.pl
@@ -0,0 +1,28 @@
+# file: runme.pl
+
+use example;
+
+# Call our gcd() function
+
+$x = 42;
+$y = 105;
+$g = example::gcd($x,$y);
+print "The gcd of $x and $y is $g\n";
+
+# Call the gcdmain() function
+@a = ("gcdmain","42","105");
+example::gcdmain(\@a);
+
+# Call the count function
+print example::count("Hello World", "l"),"\n";
+
+# Call the capitize function
+
+print example::capitalize("hello world"),"\n";
+
+
+
+
+
+
+
diff --git a/trunk/Examples/perl5/multiple_inheritance/Makefile b/trunk/Examples/perl5/multiple_inheritance/Makefile
new file mode 100644
index 0000000..fcca384
--- /dev/null
+++ b/trunk/Examples/perl5/multiple_inheritance/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/multiple_inheritance/example.h b/trunk/Examples/perl5/multiple_inheritance/example.h
new file mode 100644
index 0000000..a8f5448
--- /dev/null
+++ b/trunk/Examples/perl5/multiple_inheritance/example.h
@@ -0,0 +1,31 @@
+/* File : example.h */
+
+#include <iostream>
+
+using namespace std;
+
+class Bar
+{
+ public:
+   virtual void bar () {
+     cout << "bar" << endl;
+   }
+   virtual ~Bar() {}
+};
+
+class Foo
+{
+ public:
+   virtual void foo () {
+     cout << "foo" << endl;
+   }
+   virtual ~Foo() {}
+};
+
+class Foo_Bar : public Foo, public Bar
+{
+ public:
+   virtual void fooBar () {
+     cout << "foobar" << endl;
+   }
+};
diff --git a/trunk/Examples/perl5/multiple_inheritance/example.i b/trunk/Examples/perl5/multiple_inheritance/example.i
new file mode 100644
index 0000000..fbdf724
--- /dev/null
+++ b/trunk/Examples/perl5/multiple_inheritance/example.i
@@ -0,0 +1,9 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/trunk/Examples/perl5/multiple_inheritance/runme.pl b/trunk/Examples/perl5/multiple_inheritance/runme.pl
new file mode 100644
index 0000000..a1130c6
--- /dev/null
+++ b/trunk/Examples/perl5/multiple_inheritance/runme.pl
@@ -0,0 +1,16 @@
+# file: runme.pl
+
+# This file test multiple inheritance
+
+use example;
+
+$foo_Bar = new example::Foo_Bar();
+
+print "must be foo: ";
+$foo_Bar->foo();
+
+print "must be bar: ";
+$foo_Bar->bar();
+
+print "must be foobar: ";
+$foo_Bar->fooBar();
diff --git a/trunk/Examples/perl5/pointer/Makefile b/trunk/Examples/perl5/pointer/Makefile
new file mode 100644
index 0000000..ce2bbb5
--- /dev/null
+++ b/trunk/Examples/perl5/pointer/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/pointer/example.c b/trunk/Examples/perl5/pointer/example.c
new file mode 100644
index 0000000..8762329
--- /dev/null
+++ b/trunk/Examples/perl5/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void subtract(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/perl5/pointer/example.i b/trunk/Examples/perl5/pointer/example.i
new file mode 100644
index 0000000..38c67d7
--- /dev/null
+++ b/trunk/Examples/perl5/pointer/example.i
@@ -0,0 +1,30 @@
+/* File : example.i */
+%module example
+
+%{
+extern void add(int *, int *, int *);
+extern void subtract(int *, int *, int *);
+extern int divide(int, int, int *);
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void subtract(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/perl5/pointer/index.html b/trunk/Examples/perl5/pointer/index.html
new file mode 100644
index 0000000..6f9fd39
--- /dev/null
+++ b/trunk/Examples/perl5/pointer/index.html
@@ -0,0 +1,171 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:pointer</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/perl5/pointer/</tt>
+<hr>
+
+<H2>Simple Pointer Handling</H2>
+
+<p>
+This example illustrates a couple of techniques for handling
+simple pointers in SWIG.  The prototypical example is a C function
+that operates on pointers such as this:
+
+<blockquote>
+<pre>
+void add(int *x, int *y, int *r) { 
+    *r = *x + *y;
+}
+</pre>
+</blockquote>
+
+By default, SWIG wraps this function exactly as specified and creates
+an interface that expects pointer objects for arguments.  The only
+problem is how does one go about creating these objects from a script?
+
+<h2>Possible Solutions</h2>
+
+<ul>
+<li>Write some helper functions to explicitly create objects.  For
+example:
+
+<blockquote>
+<pre>
+int *new_int(int ivalue) {
+  int *i = (int *) malloc(sizeof(ivalue));
+  *i = ivalue;
+  return i;
+}
+int get_int(int *i) {
+  return *i;
+}
+
+void delete_int(int *i) {
+  free(i);
+}
+</pre>
+</blockquote>
+
+Now, in a script you would do this:
+
+<blockquote>
+<pre>
+$a = new_int(37);
+$b = new_int(42);
+$c = new_int(0):
+add($a,$b,$c);
+$r = get_int($c);
+print "Result = $r\n";
+delete_int($a);
+delete_int($b);
+delete_int($c);
+</pre>
+</blockquote>
+
+<p>
+<li>Use the SWIG pointer library.  For example, in the interface file 
+you would do this:
+
+<blockquote>
+<pre>
+%include "pointer.i"
+</pre>
+</blockquote?
+
+and in a script you would do this:
+
+<blockquote>
+<pre>
+$a = ptrcreate("int",37);
+$b = ptrcreate("int",42);
+$c = ptrcreate("int");
+add($a,$b,$c);
+$r = ptrvalue($c);
+print "Result = $r\n";
+ptrfree($a);
+ptrfree($b);
+ptrfree($c);
+</pre>
+</blockquote>
+
+The advantage to using the pointer library is that it unifies some of the helper
+functions behind a common set of names.  For example, the same set of functions work
+with int, double, float, and other fundamental types.
+
+<p>
+<li>Use the SWIG typemap library.  This library allows you to completely
+change the way arguments are processed by SWIG.  For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+void add(int *INPUT, int *INPUT, int *OUTPUT);
+</pre>
+</blockquote>
+
+And in a script:
+
+<blockquote>
+<pre>
+$r = add(37,42);
+print "Result = $r\n";
+</pre>
+</blockquote>
+Needless to say, this is substantially easier.
+
+<p>
+<li>A final alternative is to use the typemaps library in combination
+with the %apply directive.  This allows you to change the names of parameters
+that behave as input or output parameters. For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+%apply int *INPUT {int *x, int *y};
+%apply int *OUTPUT {int *r};
+
+void add(int *x, int *y, int *r);
+void subtract(int *x, int *y, int *r);
+void mul(int *x, int *y, int *r);
+... etc ...
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>Example</h2>
+
+The following example illustrates the use of these features for pointer
+extraction.
+
+<ul>
+<li> <a href="example.c">example.c</a>  (C Source)
+<li> <a href="example.i">example.i</a>  (Swig interface)
+<li> <a href="runme.pl">runme.pl</a> (Perl Script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>Since pointers are used for so many different things (arrays, output values,
+etc...) the complexity of pointer handling can be as complicated as you want to
+make it.
+
+<p>
+<li>More documentation on the typemaps.i and pointer.i library files can be
+found in the SWIG user manual.  The files also contain documentation.
+
+<p>
+<li>The pointer.i library is designed primarily for convenience.  If you
+are concerned about performance, you probably want to use a different
+approach.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/perl5/pointer/runme.pl b/trunk/Examples/perl5/pointer/runme.pl
new file mode 100644
index 0000000..4f0a89e
--- /dev/null
+++ b/trunk/Examples/perl5/pointer/runme.pl
@@ -0,0 +1,44 @@
+# file: runme.pl
+
+use example;
+
+# First create some objects using the pointer library.
+print "Testing the pointer library\n";
+$a = example::new_intp();
+$b = example::new_intp();
+$c = example::new_intp();
+example::intp_assign($a,37);
+example::intp_assign($b,42);
+
+print "     a = $a\n";
+print "     b = $b\n";
+print "     c = $c\n";
+
+# Call the add() function with some pointers
+example::add($a,$b,$c);
+
+# Now get the result
+$r = example::intp_value($c);
+print "     37 + 42 = $r\n";
+
+# Clean up the pointers
+example::delete_intp($a);
+example::delete_intp($b);
+example::delete_intp($c);
+
+# Now try the typemap library
+# This should be much easier. Now how it is no longer
+# necessary to manufacture pointers.
+
+print "Trying the typemap library\n";
+$r = example::subtract(37,42);
+print "     37 - 42 = $r\n";
+
+# Now try the version with multiple return values
+
+print "Testing multiple return values\n";
+($q,$r) = example::divide(42,37);
+print "     42/37 = $q remainder $r\n";
+
+
+
diff --git a/trunk/Examples/perl5/reference/Makefile b/trunk/Examples/perl5/reference/Makefile
new file mode 100644
index 0000000..4a80425
--- /dev/null
+++ b/trunk/Examples/perl5/reference/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = -noproxy 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' SWIGOPT='$(SWIGOPT)' perl5_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' SWIGOPT='$(SWIGOPT)' perl5_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/reference/example.cxx b/trunk/Examples/perl5/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/perl5/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/perl5/reference/example.h b/trunk/Examples/perl5/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/perl5/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/perl5/reference/example.i b/trunk/Examples/perl5/reference/example.i
new file mode 100644
index 0000000..6daa3b1
--- /dev/null
+++ b/trunk/Examples/perl5/reference/example.i
@@ -0,0 +1,46 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/perl5/reference/index.html b/trunk/Examples/perl5/reference/index.html
new file mode 100644
index 0000000..70b4f3d
--- /dev/null
+++ b/trunk/Examples/perl5/reference/index.html
@@ -0,0 +1,146 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:reference</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/perl5/reference/</tt>
+<hr>
+
+<H2>C++ Reference Handling</H2>
+
+<p>
+This example tests SWIG's handling of C++ references.  Since C++
+references are closely related to pointers (as both refer to a
+location in memory), SWIG simply collapses all references into
+pointers when creating wrappers.
+
+<h2>Some examples</h2>
+
+References are most commonly used as function parameter.  For example,
+you might have an operator like this:
+
+<blockquote>
+<pre>
+Vector operator+(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+or a function:
+
+<blockquote>
+<pre>
+Vector addv(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+In these cases, SWIG transforms everything into a pointer and creates a wrapper
+that looks like this:
+
+<blockquote>
+<pre>
+Vector wrap_addv(Vector *a, Vector *b) {
+    return addv(*a,*b);
+}
+</pre>
+</blockquote>
+
+Occasionally, a reference is used as a return value of a function
+when the return result is to be used as an lvalue in an expression.
+The prototypical example is an operator like this:
+
+<blockquote>
+<pre>
+Vector &amp;operator[](int index);
+</pre>
+</blockquote>
+
+or a method:
+
+<blockquote>
+<pre>
+Vector &amp;get(int index);
+</pre>
+</blockquote>
+
+For functions returning references, a wrapper like this is created:
+
+<blockquote>
+<pre>
+Vector *wrap_Object_get(Object *self, int index) {
+    Vector &amp;result = self-&gt;get(index);
+    return &amp;result;
+}
+</pre>
+</blockquote>
+
+The following <a href="example.h">header file</a> contains some class
+definitions with some operators and use of references.
+
+<h2>SWIG Interface</h2>
+
+SWIG does NOT support overloaded operators so it can not directly build
+an interface to the classes in the above file.   However, a number of workarounds
+can be made.  For example, an overloaded operator can be stuck behind a function
+call such as the <tt>addv()</tt> function above.  Array access can be handled
+with a pair of set/get functions like this:
+
+<blockquote>
+<pre>
+class VectorArray {
+public:
+ ...
+   %addmethods {
+    Vector &amp;get(int index) {
+      return (*self)[index];
+    }
+    void set(int index, Vector &amp;a) {
+      (*self)[index] = a;
+    }
+   }
+   ...
+}
+</pre>
+</blockquote>
+
+Click <a href="example.i">here</a> to see a SWIG interface file with these additions.
+
+<h2>Sample Perl script</h2>
+
+Click <a href="runme.pl">here</a> to see a script that manipulates some C++ references.
+
+<h2>Notes:</h2>
+
+<ul>
+<li>C++ references primarily provide notational convenience for C++
+source code.  However, it doesn't much matter to Perl.
+
+<p>
+<li>When a program returns a reference, a pointer is returned.
+Unlike return by value, memory is not allocated to hold the
+return result.
+
+<p>
+<li>SWIG has particular trouble handling various combinations of references
+and pointers.  This is side effect of an old parsing scheme and
+type representation that will be replaced in future versions.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/perl5/reference/runme.pl b/trunk/Examples/perl5/reference/runme.pl
new file mode 100644
index 0000000..41dc0b8
--- /dev/null
+++ b/trunk/Examples/perl5/reference/runme.pl
@@ -0,0 +1,74 @@
+# file: runme.pl
+
+# This file illustrates the manipulation of C++ references in Perl.
+# This uses the low-level interface.  Proxy classes work differently.
+
+use example;
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$a = example::new_Vector(3,4,5);
+$b = example::new_Vector(10,11,12);
+
+print "    Created",example::Vector_print($a),"\n";
+print "    Created",example::Vector_print($b),"\n";
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+print "Adding a+b\n";
+$c = example::addv($a,$b);
+print "    a+b =", example::Vector_print($c),"\n";
+
+# Note: Unless we free the result, a memory leak will occur
+example::delete_Vector($c);
+
+# ----- Create a vector array -----
+
+# Note: Using the high-level interface here
+print "Creating an array of vectors\n";
+$va = example::new_VectorArray(10);
+print "    va = $va\n";
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of $a and $b to the vector array
+example::VectorArray_set($va,0,$a);
+example::VectorArray_set($va,1,$b);
+
+# This will work, but it will cause a memory leak!
+
+example::VectorArray_set($va,2,example::addv($a,$b));
+
+# The non-leaky way to do it
+
+$c = example::addv($a,$b);
+example::VectorArray_set($va,3,$c);
+example::delete_Vector($c);
+
+# Get some values from the array
+
+print "Getting some array values\n";
+for ($i = 0; $i < 5; $i++) {
+    print "    va($i) = ", example::Vector_print(example::VectorArray_get($va,$i)), "\n";
+}
+
+# Watch under resource meter to check on this
+print "Making sure we don't leak memory.\n";
+for ($i = 0; $i < 1000000; $i++) {
+    $c = example::VectorArray_get($va,$i % 10);
+}
+
+# ----- Clean up -----
+print "Cleaning up\n";
+
+example::delete_VectorArray($va);
+example::delete_Vector($a);
+example::delete_Vector($b);
+
diff --git a/trunk/Examples/perl5/simple/Makefile b/trunk/Examples/perl5/simple/Makefile
new file mode 100644
index 0000000..ce2bbb5
--- /dev/null
+++ b/trunk/Examples/perl5/simple/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/simple/example.c b/trunk/Examples/perl5/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/perl5/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/perl5/simple/example.dsp b/trunk/Examples/perl5/simple/example.dsp
new file mode 100644
index 0000000..2d29576
--- /dev/null
+++ b/trunk/Examples/perl5/simple/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PERL5_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PERL5_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PERL5_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PERL5_INCLUDE: %PERL5_INCLUDE% 

+	echo PERL5_LIB: %PERL5_LIB% 

+	echo on 

+	..\..\..\swig -perl5 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/perl5/simple/example.i b/trunk/Examples/perl5/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/perl5/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/perl5/simple/index.html b/trunk/Examples/perl5/simple/index.html
new file mode 100644
index 0000000..7f23053
--- /dev/null
+++ b/trunk/Examples/perl5/simple/index.html
@@ -0,0 +1,99 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:simple</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/perl5/simple/</tt>
+<hr>
+
+<H2>Simple Perl5 Example</H2>
+
+<p>
+This example illustrates how you can hook Perl to a very simple C program containing
+a function and a global variable.
+
+<h2>The C Code</h2>
+
+Suppose you have the following C code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x &gt; 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+Here is a simple SWIG interface file:
+
+<blockquote>
+<pre>
+/* File: example.i */
+%module example
+
+extern int gcd(int x, int y);
+extern double Foo;
+</pre>
+</blockquote>
+
+<h2>Compilation</h2>
+
+<ol>
+<li><tt>swig -perl5 <a href="example.i">example.i</a></tt>
+<p>
+<li>This produces two files: <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.pm">example.pm</a></tt>.
+<p>
+<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
+to create the extension <tt>example.so</tt>. 
+</ol>
+
+<h2>Using the extension</h2>
+
+Click <a href="runme.pl">here</a> to see a script that calls our C functions from Perl.
+
+<h2>Key points</h2>
+
+<ul>
+<li>Use the <tt>use</tt> statement to load your extension module from Perl. For example:
+<blockquote>
+<pre>
+use example;
+</pre>
+</blockquote>
+
+<li>C functions work just like Perl functions. For example:
+<blockquote>
+<pre>
+$g = example::gcd(42,105);
+</pre>
+</blockquote>
+
+<li>C global variables are accessed like ordinary Perl variables. For example:
+<blockquote>
+<pre>
+$a = $example::Foo;
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/perl5/simple/runme.pl b/trunk/Examples/perl5/simple/runme.pl
new file mode 100644
index 0000000..b8655be
--- /dev/null
+++ b/trunk/Examples/perl5/simple/runme.pl
@@ -0,0 +1,23 @@
+#
+# Perl5 script for testing simple example
+
+use example;
+
+# Call our gcd() function
+
+$x = 42;
+$y = 105;
+$g = example::gcd($x,$y);
+print "The gcd of $x and $y is $g\n";
+
+# Manipulate the Foo global variable
+
+# Output its current value
+print "Foo = $example::Foo\n";
+
+# Change its value
+$example::Foo = 3.1415926;
+
+# See if the change took effect
+print "Foo = $example::Foo\n";
+
diff --git a/trunk/Examples/perl5/value/Makefile b/trunk/Examples/perl5/value/Makefile
new file mode 100644
index 0000000..ce2bbb5
--- /dev/null
+++ b/trunk/Examples/perl5/value/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/value/example.c b/trunk/Examples/perl5/value/example.c
new file mode 100644
index 0000000..4ed2fe1
--- /dev/null
+++ b/trunk/Examples/perl5/value/example.c
@@ -0,0 +1,15 @@
+/* File : example.c */
+
+#include "example.h"
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+Vector vector_add(Vector a, Vector b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
diff --git a/trunk/Examples/perl5/value/example.h b/trunk/Examples/perl5/value/example.h
new file mode 100644
index 0000000..212cf4b
--- /dev/null
+++ b/trunk/Examples/perl5/value/example.h
@@ -0,0 +1,5 @@
+/* File : example.h */
+
+typedef struct {
+     double x, y, z;
+} Vector;
diff --git a/trunk/Examples/perl5/value/example.i b/trunk/Examples/perl5/value/example.i
new file mode 100644
index 0000000..98fd60e
--- /dev/null
+++ b/trunk/Examples/perl5/value/example.i
@@ -0,0 +1,32 @@
+// Tests SWIG's handling of pass-by-value for complex datatypes
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Some functions that manipulate Vectors by value */
+%inline %{
+extern double dot_product(Vector a, Vector b);
+extern Vector vector_add(Vector a, Vector b);
+%}
+
+/* Include this because the vector_add() function will leak memory */
+void   free(void *);
+
+/* Some helper functions for our interface */
+%inline %{
+
+Vector *new_Vector(double x, double y, double z) {
+   Vector *v = (Vector *) malloc(sizeof(Vector));
+   v->x = x;
+   v->y = y;
+   v->z = z;
+   return v;
+}
+
+void vector_print(Vector *v) {
+  printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}
+%}
+
diff --git a/trunk/Examples/perl5/value/index.html b/trunk/Examples/perl5/value/index.html
new file mode 100644
index 0000000..62c1a03
--- /dev/null
+++ b/trunk/Examples/perl5/value/index.html
@@ -0,0 +1,126 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:value</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/perl5/value/</tt>
+<hr>
+
+<H2>Passing and Returning Structures by Value</H2>
+
+<p>
+Occasionally, a C program will manipulate structures by value such as shown in the
+following code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+typedef struct Vector {
+   double x, y, z;
+} Vector;
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+Vector vector_add(Vector a, Vector b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+</pre>
+</blockquote>
+
+Since SWIG only knows how to manage pointers to structures (not their internal
+representation), the following translations are made when wrappers are
+created:
+
+<blockquote>
+<pre>
+double wrap_dot_product(Vector *a, Vector *b) {
+    return dot_product(*a,*b);
+}
+
+Vector *wrap_vector_add(Vector *a, Vector *b) {
+    Vector *r = (Vector *) malloc(sizeof(Vector));
+    *r = vector_add(*a,*b);
+    return r;
+}
+</pre>
+</blockquote>
+
+The functions are then called using pointers from the scripting language interface.
+It should also be noted that any function that returns a structure by value results
+in an implicit memory allocation. This will be a memory leak unless you take steps
+to free the result (see below).
+
+<h2>The SWIG interface</h2>
+
+Click <a href="example.i">here</a> to see a SWIG interface file that
+wraps these two functions.  In this file, there are a few essential features:
+
+<ul>
+<li>A wrapper for the <tt>free()</tt> function is created so that we
+can clean up the return result created by <tt>vector_add()</tt>
+function.
+
+<p>
+<li>The %inline directive is used to create a few helper functions for creating new Vector
+objects and to print out the value (for debugging purposes).
+</ul>
+
+<h2>A Perl Script</h2>
+
+Click <a href="runme.pl">here</a> to see a script that uses these functions from Perl.
+
+<h2>Notes</h2>
+
+<ul>
+<li>When the '<tt>-c++</tt>' option is used, the resulting wrapper code for the return value
+changes to the following:
+
+<blockquote>
+<pre>
+Vector *wrap_vector_add(Vector *a, Vector *b) {
+    Vector *r = new Vector(vector_add(*a,*b));
+    return r;
+}
+</pre>
+</blockquote>
+
+Similarly, it would be a mistake to use the <tt>free()</tt> function from C++.  A safer 
+approach would be to write a helper function like this:
+
+<blockquote>
+<pre>
+%inline %{
+   void delete_Vector(Vector *v) {
+       delete v;
+   }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>If you use proxy classes and are careful, the SWIG generated wrappers can automatically
+clean up the result of return-by-reference when the scripting variable goes out of scope.
+
+<p>
+<li>Passing parameters by value like this really isn't the best C programming style.
+If possible, you might change your application to use pointers.
+
+<p>
+<li>Similar translations are made when C++ references are used.
+
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/perl5/value/runme.pl b/trunk/Examples/perl5/value/runme.pl
new file mode 100644
index 0000000..dc2660b
--- /dev/null
+++ b/trunk/Examples/perl5/value/runme.pl
@@ -0,0 +1,38 @@
+# file: runme.pl
+
+use example;
+
+# Create a couple of a vectors
+
+$v = example::new_Vector(1,2,3);
+$w = example::new_Vector(10,11,12);
+
+print "I just created the following vectors\n";
+example::vector_print($v);
+example::vector_print($w);
+
+# Now call some of our functions
+
+print "\nNow I'm going to compute the dot product\n";
+$d = example::dot_product($v,$w);
+print "dot product = $d (should be 68)\n";
+
+# Add the vectors together
+
+print "\nNow I'm going to add the vectors together\n";
+$r = example::vector_add($v,$w);
+example::vector_print($r);
+print "The value should be (11,13,15)\n";
+
+# Now I'd better clean up the return result r
+
+print "\nNow I'm going to clean up the return result\n";
+example::free($r);
+
+print "Good\n";
+
+
+
+
+
+
diff --git a/trunk/Examples/perl5/variables/Makefile b/trunk/Examples/perl5/variables/Makefile
new file mode 100644
index 0000000..ce2bbb5
--- /dev/null
+++ b/trunk/Examples/perl5/variables/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
diff --git a/trunk/Examples/perl5/variables/example.c b/trunk/Examples/perl5/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/perl5/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/perl5/variables/example.h b/trunk/Examples/perl5/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/perl5/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/perl5/variables/example.i b/trunk/Examples/perl5/variables/example.i
new file mode 100644
index 0000000..9d0101c
--- /dev/null
+++ b/trunk/Examples/perl5/variables/example.i
@@ -0,0 +1,51 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_SWIGTYPELEAK
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/perl5/variables/index.html b/trunk/Examples/perl5/variables/index.html
new file mode 100644
index 0000000..e4d426e
--- /dev/null
+++ b/trunk/Examples/perl5/variables/index.html
@@ -0,0 +1,63 @@
+<html>
+<head>
+<title>SWIG:Examples:perl5:variables</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/perl5/variables/</tt>
+<hr>
+
+<H2>Wrapping C Global Variables</H2>
+
+<p>
+When a C global variable appears in an interface file, SWIG tries to
+wrap it using a technique known as "variable linking."  The idea is
+pretty simple---we try to create a Perl variable that magically
+retrieves or updates the value of the underlying C variable when it is
+accessed.  Click <a href="example.i">here</a> to see a SWIG interface with some variable
+declarations in it.
+
+<h2>Manipulating Variables from Perl</h2>
+
+Accessing a C global variable from Perl is easy---just reference it like a normal Perl variable.
+Click <a href="runme.pl">here</a> to see a script that updates and prints some global variables.
+
+<h2>Creating read-only variables</h2>
+
+The <tt>%immutable</tt> and <tt>%mutable</tt> directives can be used to
+specify a collection of read-only variables.  For example:
+
+<blockquote>
+<pre>
+%immutable;
+int    status;
+double blah;
+...
+%mutable;
+</pre>
+</blockquote>
+
+The <tt>%immutable</tt> directive remains in effect until it is explicitly disabled
+using the <tt>%mutable</tt> directive.
+
+
+<h2>Notes:</h2>
+
+<ul>
+<li>When a global variable has the type "<tt>char *</tt>", SWIG manages it as a character
+string.   However, whenever the value of such a variable is set from Perl, the old
+value is destroyed using <tt>free()</tt> or <tt>delete</tt> (the choice of which depends
+on whether or not SWIG was run with the -c++ option).
+<li><tt>signed char</tt> and <tt>unsigned char</tt> are handled as small 8-bit integers.
+<li>String array variables such as '<tt>char name[256]</tt>' are managed as Perl strings, but
+when setting the value, the result is truncated to the maximum length of the array.  Furthermore, the string is assumed to be null-terminated.
+<li>When structures and classes are used as global variables, they are mapped into pointers.
+Getting the "value" returns a pointer to the global variable.  Setting the value of a structure results in a memory copy from a pointer to the global.
+<li>Variables are linked using Perl's magic mechanism.  Take a look at the Advanced Perl Programming book to 
+find out more about this feature.
+</ul>
+
+</body>
+</html>
+<hr>
diff --git a/trunk/Examples/perl5/variables/runme.pl b/trunk/Examples/perl5/variables/runme.pl
new file mode 100644
index 0000000..76e3dc8
--- /dev/null
+++ b/trunk/Examples/perl5/variables/runme.pl
@@ -0,0 +1,73 @@
+# file: runme.pl
+
+use example;
+
+# Try to set the values of some global variables
+
+$example::ivar   =  42;
+$example::svar   = -31000;
+$example::lvar   =  65537;
+$example::uivar  =  123456;
+$example::usvar  =  61000;
+$example::ulvar  =  654321;
+$example::scvar  =  -13;
+$example::ucvar  =  251;
+$example::cvar   =  "S";
+$example::fvar   =  3.14159;
+$example::dvar   =  2.1828;
+$example::strvar =  "Hello World";
+$example::iptrvar= example::new_int(37);
+$example::ptptr  = example::new_Point(37,42);
+$example::name   = "Bill";
+
+# Now print out the values of the variables
+
+print "Variables (values printed from Perl)\n";
+
+print "ivar      = $example::ivar\n";
+print "svar      = $example::svar\n";
+print "lvar      = $example::lvar\n";
+print "uivar     = $example::uivar\n";
+print "usvar     = $example::usvar\n";
+print "ulvar     = $example::ulvar\n";
+print "scvar     = $example::scvar\n";
+print "ucvar     = $example::ucvar\n";
+print "fvar      = $example::fvar\n";
+print "dvar      = $example::dvar\n";
+print "cvar      = $example::cvar\n";
+print "strvar    = $example::strvar\n";
+print "cstrvar   = $example::cstrvar\n";
+print "iptrvar   = $example::iptrvar\n";
+print "name      = $example::name\n";
+print "ptptr     = $example::ptptr", example::Point_print($example::ptptr), "\n";
+print "pt        = $example::pt", example::Point_print($example::pt), "\n";
+
+print "\nVariables (values printed from C)\n";
+
+example::print_vars();
+
+print "\nI'm going to try and update a structure variable.\n";
+
+$example::pt = $example::ptptr;
+
+print "The new value is ";
+example::pt_print();
+print "You should see the value", example::Point_print($example::ptptr), "\n";
+
+
+print "\nNow I'm going to try and modify some read only variables\n";
+
+
+print "     Trying to set 'status'\n";
+eval { $example::status = 0; };
+if (!$@) {
+    die("status");
+}
+print "     get error for 'status'\n";
+
+print "     Tring to set 'path'\n";
+eval { $example::path = "Whoa!";};
+if (!$@) {
+    die("path");
+}
+print "     get error for 'path'\n";
diff --git a/trunk/Examples/perl5/xmlstring/Makefile b/trunk/Examples/perl5/xmlstring/Makefile
new file mode 100644
index 0000000..36143fc
--- /dev/null
+++ b/trunk/Examples/perl5/xmlstring/Makefile
@@ -0,0 +1,23 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lxerces-c -lxerces-depdom -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS=$(LIBS) CXX="g++ -g3" perl5_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile perl5_clean
+
+check: all
+
+
+run:
+	perl runme.pl
diff --git a/trunk/Examples/perl5/xmlstring/example.cxx b/trunk/Examples/perl5/xmlstring/example.cxx
new file mode 100644
index 0000000..370dd9e
--- /dev/null
+++ b/trunk/Examples/perl5/xmlstring/example.cxx
@@ -0,0 +1 @@
+#include "example.h"
diff --git a/trunk/Examples/perl5/xmlstring/example.h b/trunk/Examples/perl5/xmlstring/example.h
new file mode 100644
index 0000000..a1ccf21
--- /dev/null
+++ b/trunk/Examples/perl5/xmlstring/example.h
@@ -0,0 +1,36 @@
+#include <xercesc/util/XMLString.hpp>
+
+
+class XMLChTest 
+{
+  XMLCh *_val;
+  
+public:
+
+  XMLChTest() : _val(0)
+  {
+  }
+
+  void set(const XMLCh *v) 
+  {
+    size_t len = XERCES_CPP_NAMESPACE::XMLString::stringLen(v);
+    delete[] _val;
+    _val = new XMLCh[len + 1];
+    for (int i = 0; i < len; ++i) {
+      _val[i] = v[i];
+    }
+    _val[len] = 0;
+  }
+
+  const XMLCh *get() 
+  {
+    return _val;
+  }
+
+  XMLCh get_first() 
+  {
+    return _val[0];
+  }
+  
+};
+
diff --git a/trunk/Examples/perl5/xmlstring/example.i b/trunk/Examples/perl5/xmlstring/example.i
new file mode 100644
index 0000000..8a9e02e
--- /dev/null
+++ b/trunk/Examples/perl5/xmlstring/example.i
@@ -0,0 +1,10 @@
+%module example
+
+%include <xmlstring.i>
+
+%{
+#include "example.h"
+%}
+
+
+%include example.h
diff --git a/trunk/Examples/perl5/xmlstring/runme.pl b/trunk/Examples/perl5/xmlstring/runme.pl
new file mode 100644
index 0000000..1b223d4
--- /dev/null
+++ b/trunk/Examples/perl5/xmlstring/runme.pl
@@ -0,0 +1,8 @@
+use example;
+
+
+$e1 = new example::XMLChTest();
+$e1->set("hello");
+print $e1->get(),"\n";
+print $e1->get_first(),"\n";
+
diff --git a/trunk/Examples/perl5/xmlstring/xmlstring.i b/trunk/Examples/perl5/xmlstring/xmlstring.i
new file mode 100644
index 0000000..3ef5316
--- /dev/null
+++ b/trunk/Examples/perl5/xmlstring/xmlstring.i
@@ -0,0 +1,111 @@
+%include <perlstrings.swg>
+
+%fragment("<XMLCh.h>","header") 
+%{
+#include <xercesc/util/XMLString.hpp>
+#include <xercesc/util/TransService.hpp>
+#include <xercesc/util/XMLUTF8Transcoder.hpp>
+%}
+
+%fragment("SWIG_UTF8Transcoder","header",fragment="<XMLCh.h>") {
+SWIGINTERN XERCES_CPP_NAMESPACE::XMLTranscoder* 
+SWIG_UTF8Transcoder() {
+  using namespace XERCES_CPP_NAMESPACE;
+  static int init = 0;
+  static XMLTranscoder* UTF8_TRANSCODER  = NULL;
+  static XMLCh* UTF8_ENCODING = NULL;  
+  if (!init) {
+    XMLTransService::Codes failReason;
+    XMLPlatformUtils::Initialize(); // first we must create the transservice
+    UTF8_ENCODING = XMLString::transcode("UTF-8");
+    UTF8_TRANSCODER = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(UTF8_ENCODING,
+									     failReason,
+									     1024);
+    init = 1;
+  }
+  return UTF8_TRANSCODER;
+}
+}
+   
+%fragment("SWIG_AsXMLChPtrAndSize","header",fragment="SWIG_AsCharPtrAndSize",fragment="SWIG_UTF8Transcoder") {
+SWIGINTERN int
+SWIG_AsXMLChPtrAndSize(SV *obj, XMLCh **val, size_t* psize, int *alloc)
+{
+  if (!val) {
+    return SWIG_AsCharPtrAndSize(obj, 0,  0, 0);
+  } else {
+    size_t size;
+    char *cptr = 0;
+    int calloc = SWIG_OLDOBJ;
+    int res = SWIG_AsCharPtrAndSize(obj, &cptr, &size, &calloc);
+    if (SWIG_IsOK(res)) {
+      STRLEN length = size - 1;
+      if (SvUTF8(obj)) {
+	unsigned int charsEaten = 0;
+	unsigned char* sizes = %new_array(size, unsigned char);
+	*val = %new_array(size, XMLCh);
+	unsigned int chars_stored = 
+	  SWIG_UTF8Transcoder()->transcodeFrom((const XMLByte*) cptr,
+					       (unsigned int) length,
+					       (XMLCh*) *val, 
+					       (unsigned int) length,
+					       charsEaten,
+					       (unsigned char*)sizes
+					       );
+	%delete_array(sizes);
+	// indicate the end of the string
+	(*val)[chars_stored] = '\0';
+      } else {
+	*val = XERCES_CPP_NAMESPACE::XMLString::transcode(cptr);
+      }
+      if (psize) *psize = size;
+      if (alloc) *alloc = SWIG_NEWOBJ;
+      if (calloc == SWIG_NEWOBJ) %delete_array(cptr);
+      return SWIG_NEWOBJ;    
+    } else {
+      return res;
+    }
+  }
+}
+}
+
+%fragment("SWIG_FromXMLChPtrAndSize","header",fragment="SWIG_UTF8Transcoder") {
+SWIGINTERNINLINE SV *
+SWIG_FromXMLChPtrAndSize(const XMLCh* input, size_t size)
+{
+  SV *output = sv_newmortal();
+  unsigned int charsEaten = 0;
+  int length  = size;                                        // string length
+  XMLByte* res = %new_array(length * UTF8_MAXLEN, XMLByte);          // output string
+  unsigned int total_chars =
+    SWIG_UTF8Transcoder()->transcodeTo((const XMLCh*) input, 
+				       (unsigned int) length,
+				       (XMLByte*) res,
+				       (unsigned int) length*UTF8_MAXLEN,
+				       charsEaten,
+				       XERCES_CPP_NAMESPACE::XMLTranscoder::UnRep_Throw
+				       );
+  res[total_chars] = '\0';
+  sv_setpv((SV*)output, (char *)res );
+  SvUTF8_on((SV*)output);
+  %delete_array(res);
+  return output;
+}
+}
+
+%init {
+  if (!SWIG_UTF8Transcoder()) {
+    croak("ERROR: XML::Xerces: INIT: Could not create UTF-8 transcoder");
+  }
+}
+
+
+%include <typemaps/strings.swg>
+%typemaps_string(%checkcode(UNISTRING), %checkcode(UNICHAR),
+		 XMLCh, XMLCh,
+		 SWIG_AsXMLChPtrAndSize, 
+		 SWIG_FromXMLChPtrAndSize,
+		 XERCES_CPP_NAMESPACE::XMLString::stringLen,
+		 "<XMLCh.h>", INT_MIN, INT_MAX);
+
+
diff --git a/trunk/Examples/php4/check.list b/trunk/Examples/php4/check.list
new file mode 100644
index 0000000..9daad45
--- /dev/null
+++ b/trunk/Examples/php4/check.list
@@ -0,0 +1,17 @@
+# see top-level Makefile.in
+# (see also top-level configure.in kludge)
+class
+constants
+cpointer
+disown
+enum
+funcptr
+overloading
+pointer
+pragmas
+reference
+proxy
+simple
+sync
+value
+variables
diff --git a/trunk/Examples/php4/class/Makefile b/trunk/Examples/php4/class/Makefile
new file mode 100644
index 0000000..39c4d2f
--- /dev/null
+++ b/trunk/Examples/php4/class/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    = -noproxy
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/class/example.cxx b/trunk/Examples/php4/class/example.cxx
new file mode 100644
index 0000000..f171f10
--- /dev/null
+++ b/trunk/Examples/php4/class/example.cxx
@@ -0,0 +1,39 @@
+/* File : example.c */
+
+#include "example.h"
+#include <math.h>
+#ifndef M_PI
+#  define M_PI 3.14159265358979323846
+#endif
+
+int Shape::get_nshapes() {
+  return nshapes;
+}
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+void Circle::set_radius( double r ) {
+  radius = r;
+}
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/php4/class/example.h b/trunk/Examples/php4/class/example.h
new file mode 100644
index 0000000..02eaf72
--- /dev/null
+++ b/trunk/Examples/php4/class/example.h
@@ -0,0 +1,38 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  }
+  double  x, y;
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+  static  int get_nshapes();
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { }
+  ~Circle() { }
+  void set_radius( double r );
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { }
+  ~Square() { }
+  virtual double area(void);
+  virtual double perimeter(void);
+};
diff --git a/trunk/Examples/php4/class/example.i b/trunk/Examples/php4/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/php4/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/php4/class/runme.php4 b/trunk/Examples/php4/class/runme.php4
new file mode 100644
index 0000000..a9ca657
--- /dev/null
+++ b/trunk/Examples/php4/class/runme.php4
@@ -0,0 +1,64 @@
+<?php
+
+# This file illustrates the low-level C++ interface
+# created by SWIG.  In this case, all of our C++ classes
+# get converted into function calls.
+
+require("example.php");
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = new_Circle(10);
+print "    Created circle $c\n";
+$s = new_Square(10);
+print "    Created square $s\n";
+
+# ----- Access a static member -----
+
+print "\nA total of " . nshapes() . " shapes were created\n";
+
+# ----- Member data access -----
+
+# Set the location of the object.
+# Note: methods in the base class Shape are used since
+# x and y are defined there.
+
+Shape_x_set($c, 20);
+Shape_y_set($c, 30);
+Shape_x_set($s,-10);
+Shape_y_set($s,5);
+
+print "\nHere is their current position:\n";
+print "    Circle = (" . Shape_x_get($c) . "," .  Shape_y_get($c) . ")\n";
+print "    Square = (" . Shape_x_get($s) . "," .  Shape_y_get($s) . ")\n";
+
+# ----- Call some methods -----
+
+# Notice how the Shape_area() and Shape_perimeter() functions really
+# invoke the appropriate virtual method on each object.
+print "\nHere are some properties of the shapes:\n";
+foreach (array($c,$s) as $o) {
+      print "    $o\n";
+      print "        area      = " .  Shape_area($o) .  "\n";
+      print "        perimeter = " .  Shape_perimeter($o) . "\n";
+  }
+
+# ----- Delete everything -----
+
+print "\nGuess I'll clean up now\n";
+
+# Note: this invokes the virtual destructor
+#delete_Shape($c);
+#delete_Shape($s);
+$c = NULL;
+$s = NULL;
+
+# and don't forget the $o from the for loop above.  It still refers to
+# the square.
+$o = NULL;
+
+print nshapes() . " shapes remain\n";
+print "Goodbye\n";
+
+?>
diff --git a/trunk/Examples/php4/constants/Makefile b/trunk/Examples/php4/constants/Makefile
new file mode 100644
index 0000000..aed110e
--- /dev/null
+++ b/trunk/Examples/php4/constants/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       =
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/constants/example.i b/trunk/Examples/php4/constants/example.i
new file mode 100644
index 0000000..0098a89
--- /dev/null
+++ b/trunk/Examples/php4/constants/example.i
@@ -0,0 +1,26 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following statements also produce constants */
+%constant int     iconst = 37;
+%constant double  fconst = 3.14;
+
+
diff --git a/trunk/Examples/php4/constants/runme.php4 b/trunk/Examples/php4/constants/runme.php4
new file mode 100644
index 0000000..cea0648
--- /dev/null
+++ b/trunk/Examples/php4/constants/runme.php4
@@ -0,0 +1,28 @@
+<?php
+
+require "example.php";
+
+print "ICONST  = " . ICONST . " (should be 42)\n";
+print "FCONST  = " . FCONST . " (should be 2.1828)\n";
+print "CCONST  = " . CCONST . " (should be 'x')\n";
+print "CCONST2 = " . CCONST2 . " (this should be on a new line)\n";
+print "SCONST  = " . SCONST . " (should be 'Hello World')\n";
+print "SCONST2 = " . SCONST2 . " (should be '\"Hello World\"')\n";
+print "EXPR    = " . EXPR  . " (should be 48.5484)\n";
+print "iconst  = " . iconst . " (should be 37)\n";
+print "fconst  = " . fconst . " (should be 3.14)\n";
+
+if (EXTERN!="EXTERN") {
+    print "EXTERN = " . EXTERN . " (Arg! This shouldn't print anything)\n";
+} else {
+    print "EXTERN defaults to 'EXTERN', it probably isn't defined (good)\n";
+}
+
+if (FOO!="FOO") {
+    print "FOO    = " . FOO . "(Arg! This shouldn't print anything)\n";
+} else {
+    print "FOO defaults to 'FOO', it probably isn't defined (good)\n";
+}
+
+
+?>
diff --git a/trunk/Examples/php4/cpointer/Makefile b/trunk/Examples/php4/cpointer/Makefile
new file mode 100644
index 0000000..caeec2d
--- /dev/null
+++ b/trunk/Examples/php4/cpointer/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/cpointer/example.c b/trunk/Examples/php4/cpointer/example.c
new file mode 100644
index 0000000..3326dec
--- /dev/null
+++ b/trunk/Examples/php4/cpointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(double *x, double *y, double  *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/php4/cpointer/example.i b/trunk/Examples/php4/cpointer/example.i
new file mode 100644
index 0000000..52e6df1
--- /dev/null
+++ b/trunk/Examples/php4/cpointer/example.i
@@ -0,0 +1,26 @@
+/* File : example.i */
+%module example
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+//%apply int *OUTPUT { int *r };
+//extern int divide(int n, int d, int *r);
+
+
+
+
+
diff --git a/trunk/Examples/php4/cpointer/runme.php4 b/trunk/Examples/php4/cpointer/runme.php4
new file mode 100644
index 0000000..f5ef08a
--- /dev/null
+++ b/trunk/Examples/php4/cpointer/runme.php4
@@ -0,0 +1,45 @@
+<?php
+
+	require "example.php";
+
+	# First create some objects using the pointer library.
+
+	print "Testing the pointer library\n";
+
+	$a = new_intp();
+	$b = new_intp();
+	$c = new_intp();
+	intp_assign($a,37);
+	intp_assign($b,42);
+
+	print "	a = $a\n";
+	print "	b = $b\n";
+	print "	c = $c\n";
+
+	# Call the add() function wuth some pointers
+	add($a,$b,$c);
+
+	# Now get the result
+	$r = intp_value($c);
+
+	print "	38 + 42 = $r\n";
+
+	# Clean up the pointers
+	delete_intp($a);
+	delete_intp($b);
+	delete_intp($c);
+
+	# Now try the typemap library
+	# This should be much easier. Now how it is no longer
+	# necessary to manufacture pointers.
+
+	print "Trying the typemap library\n";
+	$r = sub(37,42);
+	print "	37 - 42 = $r\n";
+
+	# Now try the version with multiple return values
+	# print "Testing multiple return values\n";
+	# ($q,$r) = divide(42,37);
+	# print "	42/37 = $q remainder $r\n";
+
+?>
diff --git a/trunk/Examples/php4/disown/Makefile b/trunk/Examples/php4/disown/Makefile
new file mode 100644
index 0000000..ef3acc7
--- /dev/null
+++ b/trunk/Examples/php4/disown/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/disown/example.cxx b/trunk/Examples/php4/disown/example.cxx
new file mode 100644
index 0000000..6393735
--- /dev/null
+++ b/trunk/Examples/php4/disown/example.cxx
@@ -0,0 +1,51 @@
+/* File : example.c */
+
+#include "example.h"
+#include <math.h>
+#ifndef M_PI
+#  define M_PI 3.14159265358979323846
+#endif
+
+int Shape::get_nshapes() {
+  return nshapes;
+}
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+void Circle::set_radius( double r ) {
+  radius = r;
+}
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
+
+ShapeContainer::~ShapeContainer() {
+  iterator i=shapes.begin();
+  for( iterator i = shapes.begin(); i != shapes.end(); ++i ) {
+    delete *i;
+  }
+}
+
+void
+ShapeContainer::addShape( Shape *s ) {
+  shapes.push_back( s );
+}
diff --git a/trunk/Examples/php4/disown/example.h b/trunk/Examples/php4/disown/example.h
new file mode 100644
index 0000000..985bc33
--- /dev/null
+++ b/trunk/Examples/php4/disown/example.h
@@ -0,0 +1,50 @@
+/* File : example.h */
+
+#include <vector>
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+  static  int get_nshapes();
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  ~Circle() { };
+  void set_radius( double r );
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  ~Square() { }
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class ShapeContainer {
+private:
+  typedef std::vector<Shape*>::iterator iterator;
+  std::vector<Shape*> shapes;
+public:
+  ShapeContainer() : shapes() {};
+  ~ShapeContainer();
+  void addShape( Shape *s );
+};
diff --git a/trunk/Examples/php4/disown/example.i b/trunk/Examples/php4/disown/example.i
new file mode 100644
index 0000000..599f162
--- /dev/null
+++ b/trunk/Examples/php4/disown/example.i
@@ -0,0 +1,12 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%apply SWIGTYPE *DISOWN {(Shape *s)};
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/php4/disown/runme.php4 b/trunk/Examples/php4/disown/runme.php4
new file mode 100644
index 0000000..73d5078
--- /dev/null
+++ b/trunk/Examples/php4/disown/runme.php4
@@ -0,0 +1,49 @@
+<?php
+
+# This file illustrates the low-level C++ interface
+# created by SWIG.  In this case, all of our C++ classes
+# get converted into function calls.
+
+require("example.php");
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = new Circle(10);
+print "    Created circle $c\n";
+$s = new Square(10);
+print "    Created square $s\n";
+
+# ----- Create the ShapeContainer ----
+
+$container = new ShapeContainer();
+
+$container->addShape($c);
+$container->addShape($s);
+
+# ----- Access a static member -----
+
+print "\nA total of " . Shape::nshapes() . " shapes were created\n";
+
+# ----- Delete by the old references -----
+# This should not truely delete the shapes because they are now owned
+# by the ShapeContainer.
+
+print "Delete the old references.";
+
+# Note: this invokes the virtual destructor
+$c = NULL;
+$s = NULL;
+
+print "\nA total of " . Shape::nshapes() . " shapes remain\n";
+
+# ----- Delete by the container -----
+# This should truely delete the shapes
+
+print "Delete the container.";
+$container = NULL;
+print "\nA total of " . Shape::nshapes() . " shapes remain\n";
+
+print "Goodbye\n";
+
+?>
diff --git a/trunk/Examples/php4/enum/Makefile b/trunk/Examples/php4/enum/Makefile
new file mode 100644
index 0000000..39c4d2f
--- /dev/null
+++ b/trunk/Examples/php4/enum/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    = -noproxy
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/enum/example.cxx b/trunk/Examples/php4/enum/example.cxx
new file mode 100644
index 0000000..df7bb63
--- /dev/null
+++ b/trunk/Examples/php4/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.cxx */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/php4/enum/example.h b/trunk/Examples/php4/enum/example.h
new file mode 100644
index 0000000..525d62a
--- /dev/null
+++ b/trunk/Examples/php4/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/php4/enum/example.i b/trunk/Examples/php4/enum/example.i
new file mode 100644
index 0000000..abf2547
--- /dev/null
+++ b/trunk/Examples/php4/enum/example.i
@@ -0,0 +1,12 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/php4/enum/runme.php4 b/trunk/Examples/php4/enum/runme.php4
new file mode 100644
index 0000000..55b0bc4
--- /dev/null
+++ b/trunk/Examples/php4/enum/runme.php4
@@ -0,0 +1,32 @@
+<?php
+
+require "example.php";
+
+# ----- Object creation -----
+
+# Print out the value of some enums
+print "*** color ***";
+print "    RED    =" . RED;
+print "    BLUE   =" . BLUE;
+print "    GREEN  =" . GREEN;
+
+print "\n*** Foo::speed ***";
+print "    Foo_IMPULSE   =" . Foo_IMPULSE;
+print "    Foo_WARP      =" . Foo_WARP;
+print "    Foo_LUDICROUS =" . Foo_LUDICROUS;
+
+print "\nTesting use of enums with functions\n";
+
+enum_test(RED, Foo_IMPULSE);
+enum_test(BLUE, Foo_WARP);
+enum_test(GREEN, Foo_LUDICROUS);
+enum_test(1234,5678);
+
+print "\nTesting use of enum with class method\n";
+$f = new_Foo();
+
+Foo_enum_test($f,Foo_IMPULSE);
+Foo_enum_test($f,Foo_WARP);
+Foo_enum_test($f,Foo_LUDICROUS);
+
+?>
diff --git a/trunk/Examples/php4/funcptr/Makefile b/trunk/Examples/php4/funcptr/Makefile
new file mode 100644
index 0000000..caeec2d
--- /dev/null
+++ b/trunk/Examples/php4/funcptr/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/funcptr/example.c b/trunk/Examples/php4/funcptr/example.c
new file mode 100644
index 0000000..99583b7
--- /dev/null
+++ b/trunk/Examples/php4/funcptr/example.c
@@ -0,0 +1,17 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
diff --git a/trunk/Examples/php4/funcptr/example.h b/trunk/Examples/php4/funcptr/example.h
new file mode 100644
index 0000000..58989db
--- /dev/null
+++ b/trunk/Examples/php4/funcptr/example.h
@@ -0,0 +1,7 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
diff --git a/trunk/Examples/php4/funcptr/example.i b/trunk/Examples/php4/funcptr/example.i
new file mode 100644
index 0000000..39390da
--- /dev/null
+++ b/trunk/Examples/php4/funcptr/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+
diff --git a/trunk/Examples/php4/funcptr/runme.php4 b/trunk/Examples/php4/funcptr/runme.php4
new file mode 100644
index 0000000..712d414
--- /dev/null
+++ b/trunk/Examples/php4/funcptr/runme.php4
@@ -0,0 +1,24 @@
+<?php
+
+require "example.php";
+
+$a = 37;
+$b = 42;
+
+# Now call our C function with a bunch of callbacks
+
+print "Trying some C callback functions\n";
+print "    a        = $a\n";
+print "    b        = $b\n";
+print "    ADD(a,b) = ". do_op($a,$b,ADD)."\n";
+print "    SUB(a,b) = ". do_op($a,$b,SUB)."\n";
+print "    MUL(a,b) = ". do_op($a,$b,MUL)."\n";
+
+print "Here is what the C callback function objects look like in php\n";
+print "Using swig style string pointers as we need them registered as constants\n";
+print "    ADD      = " . ADD . "\n";
+print "    SUB      = " . SUB . "\n";
+print "    MUL      = " . MUL . "\n";
+
+?>
+
diff --git a/trunk/Examples/php4/overloading/Makefile b/trunk/Examples/php4/overloading/Makefile
new file mode 100644
index 0000000..ef3acc7
--- /dev/null
+++ b/trunk/Examples/php4/overloading/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/overloading/example.cxx b/trunk/Examples/php4/overloading/example.cxx
new file mode 100644
index 0000000..fc7aff1
--- /dev/null
+++ b/trunk/Examples/php4/overloading/example.cxx
@@ -0,0 +1,55 @@
+/* File : example.c */
+
+#include "example.h"
+#include <math.h>
+#ifndef M_PI
+#  define M_PI 3.14159265358979323846
+#endif
+
+int Shape::get_nshapes() {
+  return nshapes;
+}
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
+
+char *overloaded(int i) {
+  return "Overloaded with int";
+}
+
+char *overloaded(double d) {
+  return "Overloaded with double";
+}
+
+char *overloaded(const char * str) {
+  return "Overloaded with char *";
+}
+
+char *overloaded( const Circle& ) {
+  return "Overloaded with Circle";
+}
+
+char *overloaded( const Shape& ) {
+  return "Overloaded with Shape";
+}
diff --git a/trunk/Examples/php4/overloading/example.h b/trunk/Examples/php4/overloading/example.h
new file mode 100644
index 0000000..39ccc1c
--- /dev/null
+++ b/trunk/Examples/php4/overloading/example.h
@@ -0,0 +1,46 @@
+/* File : example.h */
+
+#include <stdio.h>
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  }
+  double  x, y;
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+  static  int get_nshapes();
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { }
+  ~Circle() { }
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { }
+  ~Square() { }
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+char *overloaded( int i );
+char *overloaded( double d );
+char *overloaded( const char * str );
+char *overloaded( const Circle& );
+char *overloaded( const Shape& );
+
diff --git a/trunk/Examples/php4/overloading/example.i b/trunk/Examples/php4/overloading/example.i
new file mode 100644
index 0000000..950d254
--- /dev/null
+++ b/trunk/Examples/php4/overloading/example.i
@@ -0,0 +1,8 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include "example.h"
diff --git a/trunk/Examples/php4/overloading/runme.php4 b/trunk/Examples/php4/overloading/runme.php4
new file mode 100644
index 0000000..5aa6904
--- /dev/null
+++ b/trunk/Examples/php4/overloading/runme.php4
@@ -0,0 +1,59 @@
+<?php
+
+# This file illustrates the low-level C++ interface
+# created by SWIG.  In this case, all of our C++ classes
+# get converted into function calls.
+
+include("example.php");
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = new Circle(10);
+print "    Created circle $c\n";
+$s = new Square(10);
+print "    Created square $s\n";
+
+# ----- Access a static member -----
+
+print "\nA total of " . Shape::nshapes() . " shapes were created\n";
+
+# ----- Member data access -----
+
+# Set the location of the object.
+# Note: methods in the base class Shape are used since
+# x and y are defined there.
+
+$c->x = 20;
+$c->y = 30;
+$s->x = -10;
+$s->y = 5;
+
+print "\nHere is their current position:\n";
+print "    Circle = (" . $c->x . "," . $c->y . ")\n";
+print "    Square = (" . $s->x . "," . $s->y . ")\n";
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n";
+foreach (array(1, 2.1, "quick brown fox", $c, $s) as $o) {
+      print "    ".get_class($o)." $o\n";
+      print "        overloaded = " .  overloaded($o) . "\n";
+  }
+
+# Need to unset($o) or else we hang on to a reference to the Square object.
+unset($o);
+
+# ----- Delete everything -----
+
+print "\nGuess I'll clean up now\n";
+
+# Note: this invokes the virtual destructor
+unset($c);
+$s = 42;
+
+print Shape::nshapes() . " shapes remain\n";
+
+print "Goodbye\n";
+
+?>
diff --git a/trunk/Examples/php4/pointer/Makefile b/trunk/Examples/php4/pointer/Makefile
new file mode 100644
index 0000000..caeec2d
--- /dev/null
+++ b/trunk/Examples/php4/pointer/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/pointer/example.c b/trunk/Examples/php4/pointer/example.c
new file mode 100644
index 0000000..3326dec
--- /dev/null
+++ b/trunk/Examples/php4/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(double *x, double *y, double  *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/php4/pointer/example.i b/trunk/Examples/php4/pointer/example.i
new file mode 100644
index 0000000..c14b941
--- /dev/null
+++ b/trunk/Examples/php4/pointer/example.i
@@ -0,0 +1,24 @@
+/* File : example.i */
+%module example
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+%include phppointers.i
+/* First we'll use the pointer library */
+extern void add(double *REF, double *REF, double *REF);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+//%apply int *OUTPUT { int *r };
+//extern int divide(int n, int d, int *r);
+
+
+
+
+
diff --git a/trunk/Examples/php4/pointer/runme.php4 b/trunk/Examples/php4/pointer/runme.php4
new file mode 100644
index 0000000..5e86de6
--- /dev/null
+++ b/trunk/Examples/php4/pointer/runme.php4
@@ -0,0 +1,35 @@
+<?php
+
+	require "example.php";
+
+	# First create some objects using the pointer library.
+
+	print "Testing the pointer library\n";
+
+	$a = 37.145;
+	$b = 42.555;
+	$c = "";  // $c must be defined and not null.
+
+	print "	a = $a\n";
+	print "	b = $b\n";
+	print "	c = $c\n";
+
+	# Call the add() function wuth some pointers
+	add(&$a,&$b,&$c);
+
+	print "	$a + $b = $c\n";
+
+	# Now try the typemap library
+	# This should be much easier. Now how it is no longer
+	# necessary to manufacture pointers.
+
+	print "Trying the typemap library\n";
+	$r = sub(37,42);
+	print "	37 - 42 = $r\n";
+
+	# Now try the version with multiple return values
+	# print "Testing multiple return values\n";
+	# ($q,$r) = divide(42,37);
+	# print "	42/37 = $q remainder $r\n";
+
+?>
diff --git a/trunk/Examples/php4/pragmas/Makefile b/trunk/Examples/php4/pragmas/Makefile
new file mode 100644
index 0000000..aed110e
--- /dev/null
+++ b/trunk/Examples/php4/pragmas/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       =
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/pragmas/example.i b/trunk/Examples/php4/pragmas/example.i
new file mode 100644
index 0000000..289d4ec
--- /dev/null
+++ b/trunk/Examples/php4/pragmas/example.i
@@ -0,0 +1,31 @@
+/* File : example.i */
+%module example
+
+%init{
+  zend_printf("This was %%init\n");
+}
+
+%minit{
+  zend_printf("This was %%minit\n");
+}
+
+%mshutdown{
+  zend_printf("This was %%shutdown\n");
+}
+
+%rinit{
+  zend_printf("This was %%rinit\n");
+}
+
+%rshutdown{
+  zend_printf("This was %%rshutdown\n");
+}
+
+%pragma(php4) include="include.php";
+
+%pragma(php4) code="
+# This code is inserted into example.php
+echo \"this was php4 code\\n\";
+"
+
+%pragma(php4) phpinfo="php_info_print_table_start();"
diff --git a/trunk/Examples/php4/pragmas/include.php b/trunk/Examples/php4/pragmas/include.php
new file mode 100644
index 0000000..e19880a
--- /dev/null
+++ b/trunk/Examples/php4/pragmas/include.php
@@ -0,0 +1,7 @@
+<?php
+
+# This code is inserted into example.php
+echo "this is include.php\n";
+
+
+?>
diff --git a/trunk/Examples/php4/pragmas/runme.php4 b/trunk/Examples/php4/pragmas/runme.php4
new file mode 100755
index 0000000..538548b
--- /dev/null
+++ b/trunk/Examples/php4/pragmas/runme.php4
@@ -0,0 +1,5 @@
+<?php
+
+require "example.php";
+
+?>
diff --git a/trunk/Examples/php4/proxy/Makefile b/trunk/Examples/php4/proxy/Makefile
new file mode 100644
index 0000000..ef3acc7
--- /dev/null
+++ b/trunk/Examples/php4/proxy/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/proxy/example.cxx b/trunk/Examples/php4/proxy/example.cxx
new file mode 100644
index 0000000..94e4a78
--- /dev/null
+++ b/trunk/Examples/php4/proxy/example.cxx
@@ -0,0 +1,43 @@
+/* File : example.c */
+
+#include "example.h"
+#include <math.h>
+#ifndef M_PI
+#  define M_PI 3.14159265358979323846
+#endif
+
+int Shape::get_nshapes() {
+  return nshapes;
+}
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+void Circle::set_radius( double r ) {
+  radius = r;
+}
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
+
+Circle *CircleFactory( double r ) {
+  return new Circle(r);
+}
diff --git a/trunk/Examples/php4/proxy/example.h b/trunk/Examples/php4/proxy/example.h
new file mode 100644
index 0000000..361dff8
--- /dev/null
+++ b/trunk/Examples/php4/proxy/example.h
@@ -0,0 +1,43 @@
+/* File : example.h */
+
+#include <stdio.h>
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+  static  int get_nshapes();
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  ~Circle() { };
+  void set_radius( double r );
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  ~Square() { }
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+Circle *CircleFactory( double r );
+  
diff --git a/trunk/Examples/php4/proxy/example.i b/trunk/Examples/php4/proxy/example.i
new file mode 100644
index 0000000..ce73746
--- /dev/null
+++ b/trunk/Examples/php4/proxy/example.i
@@ -0,0 +1,12 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%newobject CircleFactory;
+%include "example.h"
+
diff --git a/trunk/Examples/php4/proxy/runme.php4 b/trunk/Examples/php4/proxy/runme.php4
new file mode 100644
index 0000000..dea80e3
--- /dev/null
+++ b/trunk/Examples/php4/proxy/runme.php4
@@ -0,0 +1,68 @@
+<?php
+
+# This file illustrates the low-level C++ interface
+# created by SWIG.  In this case, all of our C++ classes
+# get converted into function calls.
+
+include("example.php");
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = CircleFactory(10);
+print "    Created circle $c with area ". $c->area() ."\n";
+$s = new Square(10);
+print "    Created square $s\n";
+
+# ----- Access a static member -----
+
+print "\nA total of " . Shape::nshapes() . " shapes were created\n";
+
+# ----- Member data access -----
+
+# Set the location of the object.
+# Note: methods in the base class Shape are used since
+# x and y are defined there.
+
+$c->x = 20;
+$c->y = 30;
+$s->x = -10;
+$s->y = 5;
+
+print "\nHere is their current position:\n";
+print "    Circle = (" . $c->x . "," . $c->y . ")\n";
+print "    Square = (" . $s->x . "," . $s->y . ")\n";
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n";
+foreach (array($c,$s) as $o) {
+      print "    ".get_class($o)." $o\n";
+      print "        x         = " .  $o->x . "\n";
+      print "        y         = " .  $o->y . "\n";
+      print "        area      = " .  $o->area() . "\n";
+      print "        perimeter = " .  $o->perimeter() . "\n";
+  }
+
+# Need to unset($o) or else we hang on to a reference to the Square object.
+unset($o);
+
+# ----- Delete everything -----
+
+print "\nGuess I'll clean up now\n";
+
+# Note: this invokes the virtual destructor
+unset($c);
+$s = 42;
+
+print Shape::nshapes() . " shapes remain\n";
+
+print "Manually setting nshapes\n";
+
+Shape::nshapes(42);
+
+print Shape::get_nshapes() ." == 42\n";
+
+print "Goodbye\n";
+
+?>
diff --git a/trunk/Examples/php4/reference/BUILD-proxy.sh b/trunk/Examples/php4/reference/BUILD-proxy.sh
new file mode 100755
index 0000000..b1c8c71
--- /dev/null
+++ b/trunk/Examples/php4/reference/BUILD-proxy.sh
@@ -0,0 +1,5 @@
+#! /bin/sh -e
+
+${SWIG:=swig}  -php4 -make -c++ -withcxx example.cxx example.i
+make
+php -d extension_dir=. runme-proxy.php4
diff --git a/trunk/Examples/php4/reference/Makefile b/trunk/Examples/php4/reference/Makefile
new file mode 100644
index 0000000..39c4d2f
--- /dev/null
+++ b/trunk/Examples/php4/reference/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    = -noproxy
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/reference/example.cxx b/trunk/Examples/php4/reference/example.cxx
new file mode 100644
index 0000000..3e13841
--- /dev/null
+++ b/trunk/Examples/php4/reference/example.cxx
@@ -0,0 +1,50 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+  printf("VectorArray new: self=%p\n",this);
+}
+
+VectorArray::~VectorArray() {
+  printf("VectorArray delete: self=%p\n",this);
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  printf("VectorArray: read[%d] self=%p\n",index,this);
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  printf("VectorArray: size %d self=%p\n",maxsize,this);
+  return maxsize;
+}
+
diff --git a/trunk/Examples/php4/reference/example.h b/trunk/Examples/php4/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/php4/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/php4/reference/example.i b/trunk/Examples/php4/reference/example.i
new file mode 100644
index 0000000..55d1828
--- /dev/null
+++ b/trunk/Examples/php4/reference/example.i
@@ -0,0 +1,44 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+ /*  This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      printf("VectorArray extended get: %p %d\n",$self,index);
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
diff --git a/trunk/Examples/php4/reference/runme-proxy.php4 b/trunk/Examples/php4/reference/runme-proxy.php4
new file mode 100644
index 0000000..9d216f7
--- /dev/null
+++ b/trunk/Examples/php4/reference/runme-proxy.php4
@@ -0,0 +1,79 @@
+<?php
+
+# This file illustrates the manipulation of C++ references in Php.
+# This uses the low-level interface.  Proxy classes work differently.
+
+require "example.php";
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$a = new Vector(3,4,5);
+$b = new Vector(10,11,12);
+
+print "    Created a: $a " . $a->print() . "\n";
+print "    Created b: $b " . $b->print() . "\n";
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+print "Adding a+b\n";
+$c = addv($a,$b);
+print "    a+b =". $c->print()."\n";
+
+# Note: Unless we free the result, a memory leak will occur
+$c = 0;
+
+# ----- Create a vector array -----
+
+# Note: Using the high-level interface here
+print "Creating an array of vectors\n";
+$va = new VectorArray(10);
+
+print "    va: $va size=".$va->size()."\n";
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of $a and $b to the vector array
+$va->set(0,$a);
+$va->set(1,$b);
+
+$va->get(0);
+# This will work, but it will cause a memory leak!
+
+$va->set(2,addv($a,$b));
+
+# The non-leaky way to do it
+
+$c = addv($a,$b);
+$va->set(3,$c);
+$c = NULL;
+
+# Get some values from the array
+
+print "Getting some array values\n";
+for ($i = 0; $i < 5; $i++) {
+print "do $i\n";
+    $v = $va->get($i);
+    print "    va($i) = ". $v->print(). "\n";
+}
+
+# Watch under resource meter to check on this
+#print "Making sure we don't leak memory.\n";
+#for ($i = 0; $i < 1000000; $i++) {
+#    $c = VectorArray_get($va,$i % 10);
+#}
+
+# ----- Clean up -----
+print "Cleaning up\n";
+# wants fixing FIXME
+#delete_VectorArray($va);
+#delete_Vector($a);
+#delete_Vector($b);
+
+?>
diff --git a/trunk/Examples/php4/reference/runme.php4 b/trunk/Examples/php4/reference/runme.php4
new file mode 100644
index 0000000..00aaa52
--- /dev/null
+++ b/trunk/Examples/php4/reference/runme.php4
@@ -0,0 +1,78 @@
+<?php
+
+# This file illustrates the manipulation of C++ references in Php.
+# This uses the low-level interface.  Proxy classes work differently.
+
+require "example.php";
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$a = new_Vector(3,4,5);
+$b = new_Vector(10,11,12);
+
+print "    Created a: $a " . Vector_print($a) . "\n";
+print "    Created b: $b " . Vector_print($b) . "\n";
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+print "Adding a+b\n";
+$c = addv($a,$b);
+print "    a+b =". Vector_print($c)."\n";
+
+# Note: Unless we free the result, a memory leak will occur
+$c = None;
+
+# ----- Create a vector array -----
+
+# Note: Using the high-level interface here
+print "Creating an array of vectors\n";
+$va = new_VectorArray(10);
+
+print "    va: $va size=".VectorArray_size($va)."\n";
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of $a and $b to the vector array
+VectorArray_set($va,0,$a);
+VectorArray_set($va,1,$b);
+
+VectorArray_get($va,0);
+# This will work, but it will cause a memory leak!
+
+VectorArray_set($va,2,addv($a,$b));
+
+# The non-leaky way to do it
+
+$c = addv($a,$b);
+VectorArray_set($va,3,$c);
+$c = None;
+
+# Get some values from the array
+
+print "Getting some array values\n";
+for ($i = 0; $i < 5; $i++) {
+print "do $i\n";
+    print "    va($i) = ". Vector_print(VectorArray_get($va,$i)). "\n";
+}
+
+# Watch under resource meter to check on this
+#print "Making sure we don't leak memory.\n";
+#for ($i = 0; $i < 1000000; $i++) {
+#    $c = VectorArray_get($va,$i % 10);
+#}
+
+# ----- Clean up -----
+print "Cleaning up\n";
+# wants fixing FIXME
+$va = None;
+$a = None;
+$b = None;
+
+?>
diff --git a/trunk/Examples/php4/simple/Makefile b/trunk/Examples/php4/simple/Makefile
new file mode 100644
index 0000000..caeec2d
--- /dev/null
+++ b/trunk/Examples/php4/simple/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/simple/example.c b/trunk/Examples/php4/simple/example.c
new file mode 100644
index 0000000..2fe2756
--- /dev/null
+++ b/trunk/Examples/php4/simple/example.c
@@ -0,0 +1,23 @@
+/* File : example.c */
+#include <stdio.h>
+
+/* A global variable */
+double Foo = 3.0;
+
+void print_Foo() {
+   printf("In C, Foo = %f\n",Foo);
+}
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/php4/simple/example.i b/trunk/Examples/php4/simple/example.i
new file mode 100644
index 0000000..af4ff08
--- /dev/null
+++ b/trunk/Examples/php4/simple/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+   extern double Foo;
+%}
+
+extern double Foo;
+void print_Foo();
+int    gcd(int x, int y);
diff --git a/trunk/Examples/php4/simple/runme.php4 b/trunk/Examples/php4/simple/runme.php4
new file mode 100755
index 0000000..0e96fe8
--- /dev/null
+++ b/trunk/Examples/php4/simple/runme.php4
@@ -0,0 +1,25 @@
+<?php
+
+require "example.php";
+
+# Call our gcd() function
+
+$x = "42 aaa";
+$y = 105;
+$g = gcd($x,$y);
+print "The gcd of $x and $y is $g\n";
+
+# Manipulate the Foo global variable
+
+# Output its current value
+print "Foo = " . Foo_get() . "\n";
+
+# Change its value
+Foo_set(3.1415926);
+
+# See if the change took effect ( this isn't a good example for php, see
+#				  manual for why. )
+print "Foo = "  . Foo_get() . "\n";
+print_Foo();
+
+?>
diff --git a/trunk/Examples/php4/sync/Makefile b/trunk/Examples/php4/sync/Makefile
new file mode 100644
index 0000000..ef3acc7
--- /dev/null
+++ b/trunk/Examples/php4/sync/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/sync/example.cxx b/trunk/Examples/php4/sync/example.cxx
new file mode 100644
index 0000000..4737892
--- /dev/null
+++ b/trunk/Examples/php4/sync/example.cxx
@@ -0,0 +1,13 @@
+#include "example.h"
+#include <stdio.h>
+
+int x = 42;
+char *s = "Test";
+
+void Sync::printer(void) {
+
+	printf("The value of global s is %s\n", s);
+	printf("The value of global x is %d\n", x);
+	printf("The value of class s is %s\n", s);
+	printf("The value of class x is %d\n", x);
+};
diff --git a/trunk/Examples/php4/sync/example.h b/trunk/Examples/php4/sync/example.h
new file mode 100644
index 0000000..d67ec21
--- /dev/null
+++ b/trunk/Examples/php4/sync/example.h
@@ -0,0 +1,9 @@
+extern char *s;
+extern int x;
+
+class Sync {
+	public:
+		int x;
+		char *s;
+		void printer(void);
+};
diff --git a/trunk/Examples/php4/sync/example.i b/trunk/Examples/php4/sync/example.i
new file mode 100644
index 0000000..17ff87c
--- /dev/null
+++ b/trunk/Examples/php4/sync/example.i
@@ -0,0 +1,7 @@
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include "example.h"
diff --git a/trunk/Examples/php4/sync/runme.php4 b/trunk/Examples/php4/sync/runme.php4
new file mode 100644
index 0000000..a7c4347
--- /dev/null
+++ b/trunk/Examples/php4/sync/runme.php4
@@ -0,0 +1,15 @@
+<?
+
+// Load module and PHP classes.
+include("example.php");
+
+echo "Got new object\n";
+echo "Got string $s and value $x \n";
+
+$s = new Sync();
+echo "Got new object\n";
+
+$s->printer();
+
+?>
+
diff --git a/trunk/Examples/php4/value/Makefile b/trunk/Examples/php4/value/Makefile
new file mode 100644
index 0000000..cc383ea
--- /dev/null
+++ b/trunk/Examples/php4/value/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    = -noproxy
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/value/example.c b/trunk/Examples/php4/value/example.c
new file mode 100644
index 0000000..3c402a2
--- /dev/null
+++ b/trunk/Examples/php4/value/example.c
@@ -0,0 +1,13 @@
+/* File : example.c */
+
+#include "example.h"
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+void vector_add(Vector a, Vector b, Vector* result) {
+  result->x = a.x + b.x;
+  result->y = a.y + b.y;
+  result->z = a.z + b.z;
+}
diff --git a/trunk/Examples/php4/value/example.h b/trunk/Examples/php4/value/example.h
new file mode 100644
index 0000000..f55752a
--- /dev/null
+++ b/trunk/Examples/php4/value/example.h
@@ -0,0 +1,8 @@
+/* File : example.h */
+
+typedef struct {
+     double x, y, z;
+} Vector;
+
+double dot_product(Vector a, Vector b);
+void vector_add(Vector a, Vector b, Vector* result);
diff --git a/trunk/Examples/php4/value/example.i b/trunk/Examples/php4/value/example.i
new file mode 100644
index 0000000..386fa3b
--- /dev/null
+++ b/trunk/Examples/php4/value/example.i
@@ -0,0 +1,17 @@
+// Tests SWIG's handling of pass-by-value for complex datatypes
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include "example.h"
+
+/* Some helper functions for our interface */
+%inline %{
+
+void vector_print(Vector *v) {
+  printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}
+%}
+
diff --git a/trunk/Examples/php4/value/runme.php4 b/trunk/Examples/php4/value/runme.php4
new file mode 100644
index 0000000..4911537
--- /dev/null
+++ b/trunk/Examples/php4/value/runme.php4
@@ -0,0 +1,43 @@
+<?php
+
+	require "example.php";
+
+
+	$v = new_vector();
+        vector_x_set($v,1.0);
+        vector_y_set($v,2.0);
+        vector_z_set($v,3.0);
+
+	$w = new_vector();
+        vector_x_set($w,10.0);
+        vector_y_set($w,11.0);
+        vector_z_set($w,12.0);
+
+	echo "I just created the following vector\n";
+	vector_print($v);
+	vector_print($w);
+
+	echo "\nNow I'm going to compute the dot product\n";
+
+	$d = dot_product($v, $w);
+
+	echo "dot product = $d (should be 68)\n";
+
+	echo "\nNow I'm going to add the vectors together\n";
+
+        $r = new_vector();
+	vector_add($v, $w, $r);
+
+	vector_print($r);
+
+	echo "The value should be (11,13,15)\n";
+
+	echo "\nNow I'm going to clean up the return result\n";
+
+#	free($r);
+
+	echo "Good\n";
+
+?>
+
+
diff --git a/trunk/Examples/php4/variables/Makefile b/trunk/Examples/php4/variables/Makefile
new file mode 100644
index 0000000..caeec2d
--- /dev/null
+++ b/trunk/Examples/php4/variables/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+LIBS       =
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \
+	php4
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myphp4' INTERFACE='$(INTERFACE)' \
+	php4_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile php4_clean
+	rm -f $(TARGET).php
+
+check: all
+	$(MAKE) -f $(TOP)/Makefile php4_run
diff --git a/trunk/Examples/php4/variables/example.c b/trunk/Examples/php4/variables/example.c
new file mode 100644
index 0000000..3114c7c
--- /dev/null
+++ b/trunk/Examples/php4/variables/example.c
@@ -0,0 +1,95 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[5] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %c%c%c%c%c\n", name[0],name[1],name[2],name[3],name[4]);
+  printf("ptptr     = %p %s\n", ptptr, Point_print( ptptr ) );
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+int value_int(int *value) {
+	return *value;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/php4/variables/example.h b/trunk/Examples/php4/variables/example.h
new file mode 100644
index 0000000..3b3659c
--- /dev/null
+++ b/trunk/Examples/php4/variables/example.h
@@ -0,0 +1,34 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
+/* Some global variable declarations */
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[5];
+
+extern Point           *ptptr;
+extern Point            pt;
+
+extern int  status;
+extern char path[256];
+
+extern void print_vars();
+extern int *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char *Point_print(Point *p);
+extern void pt_print();
diff --git a/trunk/Examples/php4/variables/example.i b/trunk/Examples/php4/variables/example.i
new file mode 100644
index 0000000..3edbb72
--- /dev/null
+++ b/trunk/Examples/php4/variables/example.i
@@ -0,0 +1,44 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Some global variable declarations */
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[5];
+
+extern Point           *ptptr;
+extern Point            pt;
+
+/* Some read-only variables */
+
+%immutable;
+extern int  status;
+extern char path[256];
+%mutable;
+
+/* Some helper functions to make it easier to test */
+extern void  print_vars();
+extern int  *new_int(int value);
+
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+
+
+
+
diff --git a/trunk/Examples/php4/variables/runme.php4 b/trunk/Examples/php4/variables/runme.php4
new file mode 100644
index 0000000..bbfeb61
--- /dev/null
+++ b/trunk/Examples/php4/variables/runme.php4
@@ -0,0 +1,96 @@
+<?php
+
+	require "example.php";
+	echo "\nVariables (values printed from C)\n";
+
+	print_vars();
+
+	echo "Variables (values printed from PHP)\n";
+
+	echo "ivar	= ".ivar_get()."\n";
+	echo "svar	= ".svar_get()."\n";
+	echo "lvar	= ".lvar_get()."\n";
+	echo "uivar	= ".uivar_get()."\n";
+	echo "usvar	= ".usvar_get()."\n";
+	echo "ulvar	= ".ulvar_get()."\n";
+	echo "scvar	= ".scvar_get()."\n";
+	echo "ucvar	= ".ucvar_get()."\n";
+	echo "cvar	= ".cvar_get()."\n";
+	echo "fvar	= ".fvar_get()."\n";
+	echo "dvar	= ".dvar_get()."\n";
+	echo "strvar	= ".strvar_get()."\n";
+	echo "cstrvar	= ".cstrvar_get()."\n";
+	echo "iptrvar	= ".iptrvar_get()."\n";
+	echo "name	= \"".name_get()."\"\n";
+	echo "ptptr	= ".ptptr_get() , point_print(ptptr_get()) , "\n";
+	echo "pt	= ".pt_get(), point_print(pt_get()) , "\n";
+
+	/* Try to set the values of some global variables */
+$a = "42.14";
+
+	ivar_set($a);
+echo "a = $a\n";
+	svar_set(-31000);
+	lvar_set(65537);
+	uivar_set(123456);
+	usvar_set(61000);
+	ulvar_set(654321);
+	scvar_set(-13);
+	ucvar_set(251);
+	cvar_set("S");
+	fvar_set(3.14159);
+	dvar_set(2.1828);
+	strvar_set("Hello World");
+	iptrvar_set(new_int(37));
+	ptptr_set(new_point(37,42));
+	name_set("B");
+
+	echo "Variables (values printed from PHP)\n";
+
+	echo "ivar	= ".ivar_get()."\n";
+	echo "svar	= ".svar_get()."\n";
+	echo "lvar	= ".lvar_get()."\n";
+	echo "uivar	= ".uivar_get()."\n";
+	echo "usvar	= ".usvar_get()."\n";
+	echo "ulvar	= ".ulvar_get()."\n";
+	echo "scvar	= ".scvar_get()."\n";
+	echo "ucvar	= ".ucvar_get()."\n";
+	echo "cvar	= ".cvar_get()."\n";
+	echo "fvar	= ".fvar_get()."\n";
+	echo "dvar	= ".dvar_get()."\n";
+	echo "strvar	= ".strvar_get()."\n";
+	echo "cstrvar	= ".cstrvar_get()."\n";
+	echo "iptrvar	= ".iptrvar_get()."\n";
+	echo "name	= ".name_get()."\n";
+	echo "ptptr	= ".ptptr_get() , point_print(ptptr_get()) , "\n";
+	echo "pt	= ".pt_get(), point_print(pt_get()) , "\n";
+
+	echo "\nVariables (values printed from C)\n";
+
+	print_vars();
+
+	echo "\nI'm going to try and update a structure variable.\n";
+
+	pt_set(ptptr_get());
+
+	echo "The new value is \n";
+
+	pt_print();
+
+	echo "You should see the value", point_print(ptptr_get()), "\n";
+
+	echo "\nNow I'm going to try and modify some read only variables\n";
+
+	echo "Trying to set 'path'\n";
+
+	//path_set("Whoa!");
+	echo "Path = ".path_get()."\n";
+
+	echo "Trying to set 'status'\n";
+
+	/* And this */
+	//status_set(0);
+	echo "Status = ".status_get()."\n";
+
+?>
+
diff --git a/trunk/Examples/php4/variables/runme.php4.old b/trunk/Examples/php4/variables/runme.php4.old
new file mode 100644
index 0000000..9a6bfb3
--- /dev/null
+++ b/trunk/Examples/php4/variables/runme.php4.old
@@ -0,0 +1,80 @@
+<?php
+### THIS VERSION was written for when php global vars fakingly mirrored
+### the wrapped global vars, but it was very inefficient.
+### For now we don't do this (pending some changes to php itself) so
+### we use accessor functions instead; WE KEEP THIS version around ready
+### for when those php changes are made and we can switch back.
+### Specifically we want $_GLOBALS variable overloading like object 
+### property overloading
+
+	require "example.php";
+
+	/* Try to set the values of some global variables */
+
+	$ivar = 42;
+	$svar = -31000;
+	$lvar = 65537;
+	$uivar = 123456;
+	$usvar = 61000;
+	$ulvar = 654321;
+	$scvar = -13;
+	$ucvar = 251;
+	$cvar = "S";
+	$fvar = 3.14159;
+	$dvar = 2.1828;
+	$strvar = "Hello World";
+	$cstrvar = "Goodbye";
+	$iptrvar = new_int(37);
+	$ptptr = new_point(37,42);
+	$name = "Bill";
+
+	echo "Variables (values printed from PHP)\n";
+
+	echo "ivar	= $ivar\n";
+	echo "svar	= $svar\n";
+	echo "lvar	= $lvar\n";
+	echo "uivar	= $uivar\n";
+	echo "usvar	= $usvar\n";
+	echo "ulvar	= $ulvar\n";
+	echo "scvar	= $scvar\n";
+	echo "ucvar	= $ucvar\n";
+	echo "cvar	= $cvar\n";
+	echo "fvar	= $fvar\n";
+	echo "dvar	= $dvar\n";
+	echo "strvar	= $strvar\n";
+	echo "cstrvar	= $cstrvar\n";
+	echo "iptrvar	= $iptrvar\n";
+	echo "name	= $name\n";
+	echo "ptptr	= $ptptr" , point_print($ptptr) , "\n";
+	echo "pt	= $pt" , point_print($pt) , "\n";
+
+	echo "\nVariables (values printed from C)\n";
+
+	print_vars();
+
+	echo "\nI'm going to try and update a structure variable.\n";
+
+	$pt = $ptptr;
+
+	echo "The new value is \n";
+
+	pt_print();
+
+	echo "You should see the value", point_print($ptptr), "\n";
+
+	echo "\nNow I'm going to try and modify some read only variables\n";
+
+	echo "Trying to set 'path'\n";
+
+	/* Sadly this works */
+	$path = "Whoa!";
+	echo "Path = $path\n";
+
+	echo "Trying to set 'status'\n";
+
+	/* And this */
+	$status = 0;
+	echo "Status = $status\n";
+
+?>
+
diff --git a/trunk/Examples/pike/check.list b/trunk/Examples/pike/check.list
new file mode 100644
index 0000000..a8d348b
--- /dev/null
+++ b/trunk/Examples/pike/check.list
@@ -0,0 +1,5 @@
+# see top-level Makefile.in
+class
+constants
+enum
+simple
diff --git a/trunk/Examples/pike/class/Makefile b/trunk/Examples/pike/class/Makefile
new file mode 100755
index 0000000..981ccef
--- /dev/null
+++ b/trunk/Examples/pike/class/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all:
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp
+
+static:
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static
+
+clean:
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+
+check: all
diff --git a/trunk/Examples/pike/class/example.cxx b/trunk/Examples/pike/class/example.cxx
new file mode 100755
index 0000000..c7a3194
--- /dev/null
+++ b/trunk/Examples/pike/class/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.c */
+
+#include "example.h"
+
+#include <stdio.h>
+
+#define M_PI 3.14159265358979323846
+
+// Static member initializer
+int Shape::nshapes = 0;
+
+// Constructor
+Shape::Shape() {
+  nshapes++;
+}
+
+// Move the shape to a new location
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+// Destructor
+Shape::~Shape() {
+  nshapes--;
+}
+
+// Circle area
+double Circle::area() const {
+  return M_PI*radius*radius;
+}
+
+// Circle perimeter
+double Circle::perimeter() const {
+  return 2*M_PI*radius;
+}
+
+// Square area
+double Square::area() const {
+  return width*width;
+}
+
+// Square perimeter
+double Square::perimeter() const {
+  return 4*width;
+}
diff --git a/trunk/Examples/pike/class/example.h b/trunk/Examples/pike/class/example.h
new file mode 100755
index 0000000..f74a4fe
--- /dev/null
+++ b/trunk/Examples/pike/class/example.h
@@ -0,0 +1,35 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape();
+  virtual ~Shape();
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() const = 0;
+  virtual double perimeter() const = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area() const;
+  virtual double perimeter() const;
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area() const;
+  virtual double perimeter() const;
+};
+
+
+
+
+  
diff --git a/trunk/Examples/pike/class/example.i b/trunk/Examples/pike/class/example.i
new file mode 100755
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/pike/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/pike/class/runme.pike b/trunk/Examples/pike/class/runme.pike
new file mode 100755
index 0000000..a637760
--- /dev/null
+++ b/trunk/Examples/pike/class/runme.pike
@@ -0,0 +1,53 @@
+import .example;
+
+int main()
+{
+    // ----- Object creation -----
+
+    write("Creating some objects:\n");
+    Circle c = Circle(10.0);
+    write("    Created circle.\n");
+    Square s = Square(10.0);
+    write("    Created square.\n");
+
+    // ----- Access a static member -----
+
+    write("\nA total of " + Shape_nshapes_get() + " shapes were created\n");
+
+    // ----- Member data access -----
+
+    // Set the location of the object
+
+    c->x_set(20.0);
+    c->y_set(30.0);
+
+    s->x_set(-10.0);
+    s->y_set(5.0);
+
+    write("\nHere is their current position:\n");
+    write("    Circle = (%f, %f)\n", c->x_get(), c->y_get());
+    write("    Square = (%f, %f)\n", s->x_get(), s->y_get());
+
+    // ----- Call some methods -----
+
+    write("\nHere are some properties of the shapes:\n");
+    write("   The circle:\n");
+    write("        area      = %f.\n", c->area());
+    write("        perimeter = %f.\n", c->perimeter());
+    write("   The square:\n");
+    write("        area      = %f.\n", s->area());
+    write("        perimeter = %f.\n", s->perimeter());
+
+    write("\nGuess I'll clean up now\n");
+
+    /* See if we can force 's' to be garbage-collected */
+    s = 0;
+    
+    /* Now we should be down to only 1 shape */
+    write("%d shapes remain\n", Shape_nshapes_get());
+    
+    /* Done */
+    write("Goodbye\n");
+    
+    return 0;
+}
diff --git a/trunk/Examples/pike/constants/Makefile b/trunk/Examples/pike/constants/Makefile
new file mode 100755
index 0000000..7fa4938
--- /dev/null
+++ b/trunk/Examples/pike/constants/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+
+check: all
diff --git a/trunk/Examples/pike/constants/example.i b/trunk/Examples/pike/constants/example.i
new file mode 100755
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/pike/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/pike/constants/runme.pike b/trunk/Examples/pike/constants/runme.pike
new file mode 100755
index 0000000..a8d9f94
--- /dev/null
+++ b/trunk/Examples/pike/constants/runme.pike
@@ -0,0 +1,24 @@
+int main()
+{
+  write("ICONST  = %d (should be 42)\n", .example.ICONST);
+  write("FCONST  = %f (should be 2.1828)\n", .example.FCONST);
+  write("CCONST  = %c (should be 'x')\n", .example.CCONST);
+  write("CCONST2 = %c (this should be on a new line)\n", .example.CCONST2);
+  write("SCONST  = %s (should be 'Hello World')\n", .example.SCONST);
+  write("SCONST2 = %s (should be '\"Hello World\"')\n", .example.SCONST2);
+  write("EXPR    = %f (should be 48.5484)\n", .example.EXPR);
+  write("iconst  = %d (should be 37)\n", .example.iconst);
+  write("fconst  = %f (should be 3.14)\n", .example.fconst);
+
+  if (search(indices(.example), "EXTERN") == -1)
+    write("EXTERN isn't defined (good)\n");
+  else
+    write("EXTERN is defined (bad)\n");
+
+  if (search(indices(.example), "FOO") == -1)
+    write("FOO isn't defined (good)\n");
+  else
+    write("FOO is defined (bad)\n");
+
+  return 0;
+}
diff --git a/trunk/Examples/pike/enum/Makefile b/trunk/Examples/pike/enum/Makefile
new file mode 100644
index 0000000..0ae1021
--- /dev/null
+++ b/trunk/Examples/pike/enum/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+
+check: all
diff --git a/trunk/Examples/pike/enum/README b/trunk/Examples/pike/enum/README
new file mode 100644
index 0000000..055aa9f
--- /dev/null
+++ b/trunk/Examples/pike/enum/README
@@ -0,0 +1,13 @@
+This example will not compile with Pike versions 7.4.20 unless you first
+patch the Pike sources. The problem is for line 91 of Pike's "stralloc.h"
+(usually installed as /usr/local/pike/7.4.10/include/pike/stralloc.h). That
+line reads:
+
+    tmp.ptr=ptr;
+
+but should be patched to read:
+
+    tmp.ptr=(p_wchar0 *) ptr;
+
+This bug has been reported to the Pike developers.
+
diff --git a/trunk/Examples/pike/enum/example.cxx b/trunk/Examples/pike/enum/example.cxx
new file mode 100644
index 0000000..6785e57
--- /dev/null
+++ b/trunk/Examples/pike/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.c */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/pike/enum/example.h b/trunk/Examples/pike/enum/example.h
new file mode 100644
index 0000000..525d62a
--- /dev/null
+++ b/trunk/Examples/pike/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/pike/enum/example.i b/trunk/Examples/pike/enum/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/pike/enum/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/pike/enum/runme.pike b/trunk/Examples/pike/enum/runme.pike
new file mode 100644
index 0000000..4846356
--- /dev/null
+++ b/trunk/Examples/pike/enum/runme.pike
@@ -0,0 +1,28 @@
+int main()
+{
+    write("*** color ***\n");
+    write("    RED    = " + .example.RED + "\n");
+    write("    BLUE   = " + .example.BLUE + "\n");
+    write("    GREEN  = " + .example.GREEN + "\n");
+
+    write("\n*** Foo::speed ***\n");
+    write("    Foo_IMPULSE   = " + .example.Foo.IMPULSE + "\n");
+    write("    Foo_WARP      = " + .example.Foo.WARP + "\n");
+    write("    Foo_LUDICROUS = " + .example.Foo.LUDICROUS + "\n");
+
+    write("\nTesting use of enums with functions\n\n");
+
+    .example.enum_test(.example.RED,   .example.Foo.IMPULSE);
+    .example.enum_test(.example.BLUE,  .example.Foo.WARP);
+    .example.enum_test(.example.GREEN, .example.Foo.LUDICROUS);
+    .example.enum_test(1234, 5678);
+
+    write("\nTesting use of enum with class method\n");
+    .example.Foo f = .example.Foo();
+
+    f->enum_test(.example.Foo.IMPULSE);
+    f->enum_test(.example.Foo.WARP);
+    f->enum_test(.example.Foo.LUDICROUS);
+    
+    return 0;
+}
diff --git a/trunk/Examples/pike/overload/Makefile b/trunk/Examples/pike/overload/Makefile
new file mode 100644
index 0000000..60af005
--- /dev/null
+++ b/trunk/Examples/pike/overload/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lstdc++ -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+
+check: all
diff --git a/trunk/Examples/pike/overload/example.cxx b/trunk/Examples/pike/overload/example.cxx
new file mode 100755
index 0000000..3760fdd
--- /dev/null
+++ b/trunk/Examples/pike/overload/example.cxx
@@ -0,0 +1,115 @@
+#include <iostream>
+
+#include "example.h"
+
+// Overloaded constructors for class Bar
+Bar::Bar() {
+    std::cout << "Called Bar::Bar()" << std::endl;
+}
+
+Bar::Bar(const Bar&) {
+    std::cout << "Called Bar::Bar(const Bar&)" << std::endl;
+}
+
+Bar::Bar(double x) {
+    std::cout << "Called Bar::Bar(double) with x = " << x << std::endl;
+}
+
+Bar::Bar(double x, char *y) {
+    std::cout << "Called Bar::Bar(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl;
+}
+
+Bar::Bar(int x, int y) {
+    std::cout << "Called Bar::Bar(int, int) with x, y = " << x << ", " << y << std::endl;
+}
+
+Bar::Bar(char *x) {
+    std::cout << "Called Bar::Bar(char *) with x = \"" << x << "\"" << std::endl;
+}
+
+Bar::Bar(int x) {
+    std::cout << "Called Bar::Bar(int) with x = " << x << std::endl;
+}
+
+Bar::Bar(long x) {
+    std::cout << "Called Bar::Bar(long) with x = " << x << std::endl;
+}
+
+Bar::Bar(Bar *x) {
+    std::cout << "Called Bar::Bar(Bar *) with x = " << x << std::endl;
+}
+
+// Overloaded member functions
+void Bar::foo(const Bar& x) {
+    std::cout << "Called Bar::foo(const Bar&) with &x = " << &x << std::endl;
+}
+
+void Bar::foo(double x) {
+    std::cout << "Called Bar::foo(double) with x = " << x << std::endl;
+}
+
+void Bar::foo(double x, char *y) {
+    std::cout << "Called Bar::foo(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl;
+}
+
+void Bar::foo(int x, int y) {
+    std::cout << "Called Bar::foo(int, int) with x, y = " << x << ", " << y << std::endl;
+}
+
+void Bar::foo(char *x) {
+    std::cout << "Called Bar::foo(char *) with x = \"" << x << "\"" << std::endl;
+}
+
+void Bar::foo(int x) {
+    std::cout << "Called Bar::foo(int) with x = " << x << std::endl;
+}
+
+void Bar::foo(long x) {
+    std::cout << "Called Bar::foo(long) with x = " << x << std::endl;
+}
+
+void Bar::foo(Bar *x) {
+    std::cout << "Called Bar::foo(Bar *) with x = " << x << std::endl;
+}
+
+void Bar::spam(int x, int y, int z) {
+    std::cout << "Called Bar::spam(int, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl;
+}
+
+void Bar::spam(double x, int y, int z) {
+    std::cout << "Called Bar::spam(double, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl;
+}
+
+// Overloaded global methods
+void foo(const Bar& x) {
+    std::cout << "Called foo(const Bar& x) with &x = " << &x << std::endl;
+}
+
+void foo(double x) {
+    std::cout << "Called foo(double) with x = " << x << std::endl;
+}
+
+void foo(double x, char *y) {
+    std::cout << "Called foo(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl;
+}
+
+void foo(int x, int y) {
+    std::cout << "Called foo(int, int) with x, y = " << x << ", " << y << std::endl;
+}
+
+void foo(char *x) {
+    std::cout << "Called foo(char *) with x = \"" << x << "\"" << std::endl;
+}
+
+void foo(int x) {
+    std::cout << "Called foo(int) with x = " << x << std::endl;
+}
+
+void foo(long x) {
+    std::cout << "Called foo(long) with x = " << x << std::endl;
+}
+
+void foo(Bar *x) {
+    std::cout << "Called foo(Bar *) with x = " << x << std::endl;
+}
+
diff --git a/trunk/Examples/pike/overload/example.h b/trunk/Examples/pike/overload/example.h
new file mode 100755
index 0000000..e47a122
--- /dev/null
+++ b/trunk/Examples/pike/overload/example.h
@@ -0,0 +1,41 @@
+#ifndef EXAMPLE_H
+#define EXAMPLE_H
+
+class Bar {
+public:
+    Bar();
+    Bar(const Bar&);
+    Bar(double);
+    Bar(double, char *);
+    Bar(int, int);
+    Bar(char *);
+    Bar(long);
+    Bar(int);
+    Bar(Bar *);
+
+    void foo(const Bar&);
+    void foo(double);
+    void foo(double, char *);
+    void foo(int, int);
+    void foo(char *);
+    void foo(long);
+    void foo(int);
+    void foo(Bar *);
+    
+    void spam(int x, int y=2, int z=3);
+    void spam(double x, int y=2, int z=3);
+};
+
+void foo(const Bar&);
+void foo(double);
+void foo(double, char *);
+void foo(int, int);
+void foo(char *);
+void foo(int);
+void foo(long);
+void foo(Bar *);
+
+void spam(int x, int y=2, int z=3);
+void spam(double x, int y=2, int z=3);
+
+#endif
diff --git a/trunk/Examples/pike/overload/example.i b/trunk/Examples/pike/overload/example.i
new file mode 100644
index 0000000..ddcd006
--- /dev/null
+++ b/trunk/Examples/pike/overload/example.i
@@ -0,0 +1,28 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/**
+ * These overloaded declarations conflict with other overloads (as far as
+ * SWIG's Ruby module's implementation for overloaded methods is concerned).
+ * One option is use the %rename directive to rename the conflicting methods;
+ * here, we're just using %ignore to avoid wrapping some of the overloaded
+ * functions altogether.
+ */
+
+%ignore Bar;
+
+%ignore Bar::Bar(Bar *);
+%ignore Bar::Bar(long);
+
+%ignore Bar::foo(const Bar&);
+%ignore Bar::foo(long);
+
+%ignore ::foo(const Bar&);
+%ignore ::foo(int);
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/trunk/Examples/pike/overload/runme.pike b/trunk/Examples/pike/overload/runme.pike
new file mode 100644
index 0000000..d30e947
--- /dev/null
+++ b/trunk/Examples/pike/overload/runme.pike
@@ -0,0 +1,83 @@
+// import .example;
+
+int main()
+{
+	// This should invoke foo(double)
+	.example.foo(3.14159);
+
+	// This should invoke foo(double, char *)
+	.example.foo(3.14159, "Pi");
+
+	// This should invoke foo(int, int)
+	.example.foo(3, 4);
+
+	//  This should invoke foo(char *)
+	.example.foo("This is a test");
+
+	// This should invoke foo(long)
+	.example.foo(42);
+
+	/*
+	// This should invoke Bar::Bar() followed by foo(Bar *)
+	foo(Bar.new);
+
+	// Skip a line
+	write("\n");
+
+	// This should invoke Bar::Bar(double)
+	Bar.new(3.14159);
+
+	// This should invoke Bar::Bar(double, char *)
+	Bar.new(3.14159, "Pi");
+
+	// This should invoke Bar::Bar(int, int)
+	Bar.new(3, 4);
+
+	// This should invoke Bar::Bar(char *)
+	Bar.new("This is a test");
+
+	// This should invoke Bar::Bar(int)
+	Bar.new(42);
+
+	// This should invoke Bar::Bar() for the input argument,
+	// followed by Bar::Bar(const Bar&).
+	Bar.new(Bar.new);
+
+	// Skip a line
+	write("\n");
+	*/
+
+	// Construct a new Bar instance (invokes Bar::Bar())
+	/*
+	bar = Bar.new;
+
+	// This should invoke Bar::foo(double)
+	bar.foo(3.14159);
+
+	// This should invoke Bar::foo(double, char *)
+	bar.foo(3.14159, "Pi");
+
+	// This should invoke Bar::foo(int, int)
+	bar.foo(3, 4);
+
+	// This should invoke Bar::foo(char *)
+	bar.foo("This is a test");
+
+	// This should invoke Bar::foo(int)
+	bar.foo(42);
+
+	// This should invoke Bar::Bar() to construct the input
+	// argument, followed by Bar::foo(Bar *).
+	bar.foo(Example::Bar.new);
+
+	// This should invoke Bar::spam(int x, int y, int z)
+	bar.spam(1);
+
+	// This should invoke Bar::spam(double x, int y, int z)
+	bar.spam(3.14159);
+	*/
+
+   	write("Goodbye\n");
+    
+   	return 0;
+}
diff --git a/trunk/Examples/pike/simple/Makefile b/trunk/Examples/pike/simple/Makefile
new file mode 100644
index 0000000..544c97b
--- /dev/null
+++ b/trunk/Examples/pike/simple/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all:
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike
+
+static:
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static
+
+clean:
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+
+check: all
diff --git a/trunk/Examples/pike/simple/example.c b/trunk/Examples/pike/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/pike/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/pike/simple/example.i b/trunk/Examples/pike/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/pike/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/pike/simple/runme.pike b/trunk/Examples/pike/simple/runme.pike
new file mode 100644
index 0000000..a6a78e9
--- /dev/null
+++ b/trunk/Examples/pike/simple/runme.pike
@@ -0,0 +1,20 @@
+int main()
+{
+    /* Call our gcd() function */
+    int x = 42;
+    int y = 105;
+    int g = .example.gcd(x, y);
+    write("The gcd of %d and %d is %d\n", x, y, g);
+
+    /* Manipulate the Foo global variable */
+    /* Output its current value */
+    write("Foo = %f\n", .example->Foo_get());
+
+    /* Change its value */
+    .example->Foo_set(3.1415926);
+
+    /* See if the change took effect */
+    write("Foo = %f\n", .example->Foo_get());
+    
+    return 0;
+}
diff --git a/trunk/Examples/pike/template/Makefile b/trunk/Examples/pike/template/Makefile
new file mode 100755
index 0000000..b3f0129
--- /dev/null
+++ b/trunk/Examples/pike/template/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all:
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp
+
+static:
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static
+
+clean:
+	$(MAKE) -f $(TOP)/Makefile pike_clean
+
+check: all
diff --git a/trunk/Examples/pike/template/example.h b/trunk/Examples/pike/template/example.h
new file mode 100755
index 0000000..7401df6
--- /dev/null
+++ b/trunk/Examples/pike/template/example.h
@@ -0,0 +1,32 @@
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %extend {
+    T getitem(int index) {
+      return $self->get(index);
+    }
+    void setitem(int index, T val) {
+      $self->set(index,val);
+    }
+  }
+#endif
+};
+
diff --git a/trunk/Examples/pike/template/example.i b/trunk/Examples/pike/template/example.i
new file mode 100755
index 0000000..8f94c4d
--- /dev/null
+++ b/trunk/Examples/pike/template/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
diff --git a/trunk/Examples/pike/template/runme.pike b/trunk/Examples/pike/template/runme.pike
new file mode 100755
index 0000000..36825c3
--- /dev/null
+++ b/trunk/Examples/pike/template/runme.pike
@@ -0,0 +1,33 @@
+int main()
+{
+    // Call some templated functions
+    write(sprintf("%d\n", .example.maxint(3, 7)));
+    write(sprintf("%f\n", .example.maxdouble(3.14, 2.18)));
+    
+    // Create some objects
+    .example.vecint iv = .example.vecint(100);
+    .example.vecdouble dv = .example.vecdouble(1000);
+    
+    for (int i = 0; i < 100; i++) {
+        iv->setitem(i, 2*i);
+    }
+
+    for (int i = 0; i < 1000; i++) {
+        dv->setitem(i, 1.0/(i+1));
+    }
+    
+    int isum = 0;
+    for (int i = 0; i < 100; i++) {
+        isum += iv->getitem(i);
+    }
+    
+    write(sprintf("%d\n", isum));
+    
+    float fsum = 0.0;
+    for (int i = 0; i < 1000; i++) {
+        fsum += dv->getitem(i);
+    }
+    write(sprintf("%f\n", fsum));
+    
+    return 0;
+}
diff --git a/trunk/Examples/python/callback/Makefile b/trunk/Examples/python/callback/Makefile
new file mode 100644
index 0000000..ad36d7d
--- /dev/null
+++ b/trunk/Examples/python/callback/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/callback/example.cxx b/trunk/Examples/python/callback/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/python/callback/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/python/callback/example.h b/trunk/Examples/python/callback/example.h
new file mode 100644
index 0000000..1a0e8c4
--- /dev/null
+++ b/trunk/Examples/python/callback/example.h
@@ -0,0 +1,23 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+
+class Callback {
+public:
+	virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; }
+	virtual void run() { std::cout << "Callback::run()" << std::endl; }
+};
+
+
+class Caller {
+private:
+	Callback *_callback;
+public:
+	Caller(): _callback(0) {}
+	~Caller() { delCallback(); }
+	void delCallback() { delete _callback; _callback = 0; }
+	void setCallback(Callback *cb) { delCallback(); _callback = cb; }
+	void call() { if (_callback) _callback->run(); }
+};
+
diff --git a/trunk/Examples/python/callback/example.i b/trunk/Examples/python/callback/example.i
new file mode 100644
index 0000000..90beda0
--- /dev/null
+++ b/trunk/Examples/python/callback/example.i
@@ -0,0 +1,13 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_string.i"
+
+/* turn on director wrapping Callback */
+%feature("director") Callback;
+
+%include "example.h"
+
diff --git a/trunk/Examples/python/callback/index.html b/trunk/Examples/python/callback/index.html
new file mode 100644
index 0000000..e2017ec
--- /dev/null
+++ b/trunk/Examples/python/callback/index.html
@@ -0,0 +1,19 @@
+<html>
+<head>
+<title>SWIG:Examples:python:callback</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/extend/</tt>
+<hr>
+
+<H2>Implementing C++ callbacks in Python</H2>
+
+<p>
+This example illustrates how to use directors to implement C++ callbacks in Python.
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/callback/runme.py b/trunk/Examples/python/callback/runme.py
new file mode 100644
index 0000000..5d93e82
--- /dev/null
+++ b/trunk/Examples/python/callback/runme.py
@@ -0,0 +1,58 @@
+# file: runme.py
+
+# This file illustrates the cross language polymorphism using directors.
+
+import example 
+
+
+# CEO class, which overrides Employee::getPosition().
+
+class PyCallback(example.Callback):
+	def __init__(self):
+		example.Callback.__init__(self)
+	def run(self):
+		print "PyCallback.run()"
+
+# Create an Caller instance
+
+caller = example.Caller()
+
+# Add a simple C++ callback (caller owns the callback, so
+# we disown it first by clearing the .thisown flag).
+
+print "Adding and calling a normal C++ callback"
+print "----------------------------------------"
+
+callback = example.Callback()
+callback.thisown = 0
+caller.setCallback(callback)
+caller.call()
+caller.delCallback();
+
+print
+print "Adding and calling a Python callback"
+print "------------------------------------"
+
+# Add a Python callback (caller owns the callback, so we
+# disown it first by calling __disown__).
+
+caller.setCallback(PyCallback().__disown__())
+caller.call()
+caller.delCallback()
+
+print
+print "Adding and calling another Python callback"
+print "------------------------------------------"
+
+# Lets do the same but use the weak reference this time.
+
+callback = PyCallback().__disown__()
+caller.setCallback(callback)
+caller.call()
+caller.delCallback()
+
+# All done.
+
+print
+print "python exit"
+
diff --git a/trunk/Examples/python/check.list b/trunk/Examples/python/check.list
new file mode 100644
index 0000000..7cfe437
--- /dev/null
+++ b/trunk/Examples/python/check.list
@@ -0,0 +1,29 @@
+# see top-level Makefile.in
+callback
+class
+constants
+contract
+docstrings
+enum
+exception
+exceptproxy
+extend
+funcptr
+funcptr2
+functor
+import
+import_template
+java
+#libffi
+multimap
+operator
+pointer
+reference
+simple
+smartptr
+std_vector
+std_map
+swigrun
+template
+varargs
+variables
diff --git a/trunk/Examples/python/class/Makefile b/trunk/Examples/python/class/Makefile
new file mode 100644
index 0000000..f331b82
--- /dev/null
+++ b/trunk/Examples/python/class/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/class/example.cxx b/trunk/Examples/python/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/python/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/python/class/example.dsp b/trunk/Examples/python/class/example.dsp
new file mode 100644
index 0000000..dccba46
--- /dev/null
+++ b/trunk/Examples/python/class/example.dsp
@@ -0,0 +1,152 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_example.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_example.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/class/example.h b/trunk/Examples/python/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/python/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/python/class/example.i b/trunk/Examples/python/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/python/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/python/class/index.html b/trunk/Examples/python/class/index.html
new file mode 100644
index 0000000..12c5ede
--- /dev/null
+++ b/trunk/Examples/python/class/index.html
@@ -0,0 +1,216 @@
+<html>
+<head>
+<title>SWIG:Examples:python:class</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/class/</tt>
+<hr>
+
+<H2>Wrapping a simple C++ class</H2>
+
+<p>
+This example illustrates the most primitive form of C++ class wrapping performed
+by SWIG.  In this case, C++ classes are simply transformed into a collection of
+C-style functions that provide access to class members.
+
+<h2>The C++ Code</h2>
+
+Suppose you have some C++ classes described by the following (and admittedly lame) 
+header file:
+
+<blockquote>
+<pre>
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+A simple SWIG interface for this can be built by simply grabbing the header file
+like this:
+
+<blockquote>
+<pre>
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+</pre>
+</blockquote>
+
+Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> option like this:
+<blockquote>
+<pre>
+% swig -c++ -python example.i
+</pre>
+</blockquote>
+
+<h2>A sample Python script</h2>
+
+Click <a href="example.py">here</a> to see a script that calls the C++ functions from Python.
+
+<h2>Key points</h2>
+
+<ul>
+<li>To create a new object, you call a constructor like this:
+
+<blockquote>
+<pre>
+c = example.new_Circle(10.0)
+</pre>
+</blockquote>
+
+<p>
+<li>To access member data, a pair of accessor functions are used.
+For example:
+
+<blockquote>
+<pre>
+example.Shape_x_set(c,15)    # Set member data
+x = example.Shape_x_get(c)    # Get member data
+</pre>
+</blockquote>
+
+Note: when accessing member data, the name of the class in which
+the member data was must be used.  In this case, <tt>Shape_x_get()</tt>
+and <tt>Shape_x_set()</tt> are used since 'x' was defined in Shape.
+
+<p>
+<li>To invoke a member function, you simply do this
+
+<blockquote>
+<pre>
+print "The area is ", example.Shape_area(c)
+</pre>
+</blockquote>
+
+<p>
+<li>Type checking knows about the inheritance structure of C++. For example:
+
+<blockquote>
+<pre>
+example.Shape_area(c)       # Works (c is a Shape)
+example.Circle_area(c)      # Works (c is a Circle)
+example.Square_area(c)      # Fails (c is definitely not a Square)
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a destructor, simply do this
+
+<blockquote>
+<pre>
+example.delete_Shape(c)     # Deletes a shape
+</pre>
+</blockquote>
+
+(Note: destructors are currently not inherited. This might change later).
+
+<p>
+<li>Static member variables are wrapped as C global variables.  For example:
+
+<blockquote>
+<pre>
+n = example.cvar.Shape_nshapes     # Get a static data member
+example.cvar.Shapes_nshapes = 13   # Set a static data member
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>General Comments</h2>
+
+<ul>
+<li>This low-level interface is not the only way to handle C++ code.
+Proxy classes provide a much higher-level interface.
+
+<p>
+<li>SWIG *does* know how to properly perform upcasting of objects in
+an inheritance hierarchy (including multiple inheritance).  Therefore
+it is perfectly safe to pass an object of a derived class to any
+function involving a base class.
+
+<p>
+<li>A wide variety of C++ features are not currently supported by SWIG.  Here is the
+short and incomplete list:
+
+<p>
+<ul>
+<li>Overloaded methods and functions.  SWIG wrappers don't know how to resolve name
+conflicts so you must give an alternative name to any overloaded method name using the
+%name directive like this:
+
+<blockquote>
+<pre>
+void foo(int a);  
+%name(foo2) void foo(double a, double b);
+</pre>
+</blockquote>
+
+<p>
+<li>Overloaded operators.  Not supported at all. The only workaround for this is
+to write a helper function. For example:
+
+<blockquote>
+<pre>
+%inline %{
+    Vector *vector_add(Vector *a, Vector *b) {
+          ... whatever ...
+    }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>Namespaces.  Not supported at all. Won't be supported until SWIG2.0 (if at all).
+
+<p>
+<li>Dave's snide remark: Like a large bottle of strong Tequilla, it's better to
+use C++	in moderation.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/class/runme.py b/trunk/Examples/python/class/runme.py
new file mode 100644
index 0000000..f1272ae
--- /dev/null
+++ b/trunk/Examples/python/class/runme.py
@@ -0,0 +1,51 @@
+# file: runme.py
+
+# This file illustrates the proxy class C++ interface generated
+# by SWIG.
+
+import example 
+
+# ----- Object creation -----
+
+print "Creating some objects:"
+c = example.Circle(10)
+print "    Created circle", c
+s = example.Square(10)
+print "    Created square", s
+
+# ----- Access a static member -----
+
+print "\nA total of", example.cvar.Shape_nshapes,"shapes were created"
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+
+s.x = -10
+s.y = 5
+
+print "\nHere is their current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+print "    Square = (%f, %f)" % (s.x,s.y)
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:"
+for o in [c,s]:
+      print "   ", o
+      print "        area      = ", o.area()
+      print "        perimeter = ", o.perimeter()
+
+print "\nGuess I'll clean up now"
+
+# Note: this invokes the virtual destructor
+del c
+del s
+
+s = 3
+print example.cvar.Shape_nshapes,"shapes remain"
+print "Goodbye"
+
diff --git a/trunk/Examples/python/constants/Makefile b/trunk/Examples/python/constants/Makefile
new file mode 100644
index 0000000..01d0f94
--- /dev/null
+++ b/trunk/Examples/python/constants/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/constants/example.i b/trunk/Examples/python/constants/example.i
new file mode 100644
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/python/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/python/constants/index.html b/trunk/Examples/python/constants/index.html
new file mode 100644
index 0000000..35cc0d7
--- /dev/null
+++ b/trunk/Examples/python/constants/index.html
@@ -0,0 +1,67 @@
+<html>
+<head>
+<title>SWIG:Examples:python:constants</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/python/constants/</tt>
+<hr>
+
+<H2>Wrapping C Constants</H2>
+
+<p>
+When SWIG encounters C preprocessor macros and C declarations that look like constants,
+it creates Python variables with an identical value.  Click <a href="example.i">here</a>
+to see a SWIG interface with some constant declarations in it.
+
+<h2>Accessing Constants from Python</h2>
+
+Click <a href="example.py">here</a> to see a script that prints out the values
+of the constants contained in the above file.
+
+<h2>Key points</h2>
+
+<ul>
+<li>The values of preprocessor macros are converted into Python constants.
+<li>Types are inferred by syntax (e.g., "3" is an integer and "3.5" is a float).
+<li>Character constants such as 'x' are converted into Python strings.
+<li>C string literals such as "Hello World" are converted into Python strings.
+<li>Macros that are not fully defined are simply ignored.  For example:
+<blockquote>
+<pre>
+#define EXTERN extern
+</pre>
+</blockquote>
+is ignored because SWIG has no idea what type of variable this would be.
+
+<p>
+<li>Expressions are allowed provided that all of their components are defined. Otherwise, the constant is ignored.
+
+<li>Certain C declarations involving 'const' are also turned into Python constants. 
+<li>The Python variables that SWIG creates are not protected from modification.  For example,
+even if you had this:
+<blockquote>
+<pre>
+#define FOO 73
+</pre>
+</blockquote>
+a user could come along in a script and type
+<blockquote>
+<pre>
+example.FOO = 13
+</pre>
+</blockquote>
+Unfortunately, there's no easy way to prevent this.
+
+<p>
+<li>The constants that appear in a SWIG interface file do not have to appear in any sort
+of matching C source file since the creation of a constant does not require linkage
+to a stored value (i.e., a value held in a C global variable or memory location).
+</ul>
+
+<hr>
+
+
+</body>
+</html>
diff --git a/trunk/Examples/python/constants/runme.py b/trunk/Examples/python/constants/runme.py
new file mode 100644
index 0000000..8d25b87
--- /dev/null
+++ b/trunk/Examples/python/constants/runme.py
@@ -0,0 +1,27 @@
+# file: runme.py
+
+import example 
+
+print "ICONST  =", example.ICONST, "(should be 42)"
+print "FCONST  =", example.FCONST, "(should be 2.1828)"
+print "CCONST  =", example.CCONST, "(should be 'x')"
+print "CCONST2 =", example.CCONST2, "(this should be on a new line)"
+print "SCONST  =", example.SCONST, "(should be 'Hello World')"
+print "SCONST2 =", example.SCONST2, "(should be '\"Hello World\"')"
+print "EXPR    =", example.EXPR,   "(should be 48.5484)"
+print "iconst  =", example.iconst, "(should be 37)"
+print "fconst  =", example.fconst, "(should be 3.14)"
+
+try:
+    print "EXTERN = ", example.EXTERN, "(Arg! This shouldn't print anything)"
+except AttributeError:
+    print "EXTERN isn't defined (good)"
+
+try:
+    print "FOO    = ", example.FOO, "(Arg! This shouldn't print anything)"
+except AttributeError:
+    print "FOO isn't defined (good)"
+
+
+
+
diff --git a/trunk/Examples/python/contract/Makefile b/trunk/Examples/python/contract/Makefile
new file mode 100644
index 0000000..c7b4769
--- /dev/null
+++ b/trunk/Examples/python/contract/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+SWIGOPT    = 
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/contract/example.c b/trunk/Examples/python/contract/example.c
new file mode 100644
index 0000000..1a64454
--- /dev/null
+++ b/trunk/Examples/python/contract/example.c
@@ -0,0 +1,23 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int fact(int n) {
+  if (n <= 0) return 1;
+  return n*fact(n-1);
+}
+
+
diff --git a/trunk/Examples/python/contract/example.dsp b/trunk/Examples/python/contract/example.dsp
new file mode 100644
index 0000000..7a32f4d
--- /dev/null
+++ b/trunk/Examples/python/contract/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_example.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_example.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/contract/example.i b/trunk/Examples/python/contract/example.i
new file mode 100644
index 0000000..8fd1a80
--- /dev/null
+++ b/trunk/Examples/python/contract/example.i
@@ -0,0 +1,21 @@
+/* File : example.i */
+%module example
+
+%contract gcd(int x, int y) {
+require:
+	x >= 0;
+	y >= 0;
+}
+
+%contract fact(int n) {
+require:
+	n >= 0;
+ensure:
+	fact >= 1;
+}
+
+%inline %{
+extern int    gcd(int x, int y);
+extern int    fact(int n);
+extern double Foo;
+%}
diff --git a/trunk/Examples/python/contract/runme.py b/trunk/Examples/python/contract/runme.py
new file mode 100644
index 0000000..d484ae9
--- /dev/null
+++ b/trunk/Examples/python/contract/runme.py
@@ -0,0 +1,30 @@
+# file: runme.py
+
+import example 
+
+# Call our gcd() function
+
+x = 42
+y = 105
+g = example.gcd(x,y)
+print "The gcd of %d and %d is %d" % (x,y,g)
+
+# Manipulate the Foo global variable
+
+# Output its current value
+print "Foo = ", example.cvar.Foo
+
+# Change its value
+example.cvar.Foo = 3.1415926
+
+# See if the change took effect
+print "Foo = ", example.cvar.Foo
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/python/docstrings/Makefile b/trunk/Examples/python/docstrings/Makefile
new file mode 100644
index 0000000..74ab112
--- /dev/null
+++ b/trunk/Examples/python/docstrings/Makefile
@@ -0,0 +1,23 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = -O
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/docstrings/example.cxx b/trunk/Examples/python/docstrings/example.cxx
new file mode 100644
index 0000000..93e6542
--- /dev/null
+++ b/trunk/Examples/python/docstrings/example.cxx
@@ -0,0 +1,4 @@
+#include "example.h"
+
+void Foo::bar() {}
+
diff --git a/trunk/Examples/python/docstrings/example.h b/trunk/Examples/python/docstrings/example.h
new file mode 100644
index 0000000..f44dbc4
--- /dev/null
+++ b/trunk/Examples/python/docstrings/example.h
@@ -0,0 +1,4 @@
+class Foo {
+    public:
+    	void bar();
+};
diff --git a/trunk/Examples/python/docstrings/example.i b/trunk/Examples/python/docstrings/example.i
new file mode 100644
index 0000000..15e08e6
--- /dev/null
+++ b/trunk/Examples/python/docstrings/example.i
@@ -0,0 +1,14 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* %feature("docstring") has to come before the declaration of the method to
+ * SWIG. */
+%feature("docstring") Foo::bar "No comment"
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/python/docstrings/runme.py b/trunk/Examples/python/docstrings/runme.py
new file mode 100644
index 0000000..b6c95e6
--- /dev/null
+++ b/trunk/Examples/python/docstrings/runme.py
@@ -0,0 +1,6 @@
+# file: runme.py
+
+import example 
+
+print "example.Foo.bar.__doc__  =", repr(example.Foo.bar.__doc__), "(Should be 'No comment')"
+
diff --git a/trunk/Examples/python/enum/Makefile b/trunk/Examples/python/enum/Makefile
new file mode 100644
index 0000000..f331b82
--- /dev/null
+++ b/trunk/Examples/python/enum/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/enum/example.cxx b/trunk/Examples/python/enum/example.cxx
new file mode 100644
index 0000000..6785e57
--- /dev/null
+++ b/trunk/Examples/python/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.c */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/python/enum/example.h b/trunk/Examples/python/enum/example.h
new file mode 100644
index 0000000..525d62a
--- /dev/null
+++ b/trunk/Examples/python/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/python/enum/example.i b/trunk/Examples/python/enum/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/python/enum/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/python/enum/index.html b/trunk/Examples/python/enum/index.html
new file mode 100644
index 0000000..776030f
--- /dev/null
+++ b/trunk/Examples/python/enum/index.html
@@ -0,0 +1,35 @@
+<html>
+<head>
+<title>SWIG:Examples:python:enum</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/enum/</tt>
+<hr>
+
+<H2>Wrapping enumerations</H2>
+
+<p>
+This example tests SWIG's ability to wrap enumerations.  By default, SWIG
+converts enumeration specifications into integer constants.  Further use
+of enumerated types are handled as integers.
+
+<ul>
+<li><a href="example.h">example.h</a>.  Header file containing some enums.
+<li><a href="example.i">example.i</a>.  Interface file.
+<li><a href="example.py">example.py</a>. Sample Python script.
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>SWIG allows arbitrary integers to be passed as enum values.  However,
+the result of passing an integer not corresponding to any of the values
+specified in the <tt>enum</tt> specification is undefined.
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/enum/runme.py b/trunk/Examples/python/enum/runme.py
new file mode 100644
index 0000000..10c4a26
--- /dev/null
+++ b/trunk/Examples/python/enum/runme.py
@@ -0,0 +1,31 @@
+# file: runme.py
+
+import example
+
+# ----- Object creation -----
+
+# Print out the value of some enums
+print "*** color ***"
+print "    RED    =", example.RED
+print "    BLUE   =", example.BLUE
+print "    GREEN  =", example.GREEN
+
+print "\n*** Foo::speed ***"
+print "    Foo_IMPULSE   =", example.Foo.IMPULSE
+print "    Foo_WARP      =", example.Foo.WARP
+print "    Foo_LUDICROUS =", example.Foo.LUDICROUS
+
+print "\nTesting use of enums with functions\n"
+
+example.enum_test(example.RED, example.Foo.IMPULSE)
+example.enum_test(example.BLUE,  example.Foo.WARP)
+example.enum_test(example.GREEN, example.Foo.LUDICROUS)
+example.enum_test(1234,5678)
+
+print "\nTesting use of enum with class method"
+f = example.Foo()
+
+f.enum_test(example.Foo.IMPULSE)
+f.enum_test(example.Foo.WARP)
+f.enum_test(example.Foo.LUDICROUS)
+
diff --git a/trunk/Examples/python/exception/Makefile b/trunk/Examples/python/exception/Makefile
new file mode 100644
index 0000000..17c4f30
--- /dev/null
+++ b/trunk/Examples/python/exception/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/exception/example.h b/trunk/Examples/python/exception/example.h
new file mode 100644
index 0000000..8f9a977
--- /dev/null
+++ b/trunk/Examples/python/exception/example.h
@@ -0,0 +1,53 @@
+/* File : example.h */
+
+#include <string>
+#ifndef SWIG
+struct A {
+};
+#endif
+
+class Exc {
+public:
+  Exc(int c, const char *m) {
+    code = c;
+    strncpy(msg,m,256);
+  }
+  int code;
+  char msg[256];
+};
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+class Test {
+public:
+  int simple() throw(int) {
+      throw(37);
+      return 1;
+  }
+  int message() throw(const char *) {
+      throw("I died.");
+      return 1;
+  }
+  int hosed() throw(Exc) {
+      throw(Exc(42,"Hosed"));
+      return 1;
+  } 
+  int unknown() throw(A*) {
+      static A a;
+      throw &a;
+      return 1;
+  }
+  int multi(int x) throw(int, const char *, Exc) {
+     if (x == 1) throw(37);
+     if (x == 2) throw("Bleah!");
+     if (x == 3) throw(Exc(42,"No-go-diggy-die"));
+     return 1;
+  }
+};
+
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
diff --git a/trunk/Examples/python/exception/example.i b/trunk/Examples/python/exception/example.i
new file mode 100644
index 0000000..08672c3
--- /dev/null
+++ b/trunk/Examples/python/exception/example.i
@@ -0,0 +1,12 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include "std_string.i"
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/python/exception/runme.py b/trunk/Examples/python/exception/runme.py
new file mode 100644
index 0000000..7187078
--- /dev/null
+++ b/trunk/Examples/python/exception/runme.py
@@ -0,0 +1,36 @@
+# file: runme.py
+
+# Throw a lot of exceptions
+
+import example
+
+t = example.Test()
+try:
+      t.unknown()
+except RuntimeError,e:
+      print "incomplete type", e.args[0]
+
+try:
+      t.simple()
+except RuntimeError,e:
+      print e.args[0]
+
+try:
+      t.message()
+except RuntimeError,e:
+      print e.args[0]
+
+try:
+      t.hosed()
+except example.Exc,e:
+      print e.code, e.msg
+
+for i in range(1,4):
+      try:
+            t.multi(i)
+      except RuntimeError,e:
+            print e.args[0]
+      except example.Exc,e:
+            print e.code, e.msg
+
+
diff --git a/trunk/Examples/python/exceptproxy/Makefile b/trunk/Examples/python/exceptproxy/Makefile
new file mode 100644
index 0000000..a4f3343
--- /dev/null
+++ b/trunk/Examples/python/exceptproxy/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/exceptproxy/example.h b/trunk/Examples/python/exceptproxy/example.h
new file mode 100644
index 0000000..ec7107a
--- /dev/null
+++ b/trunk/Examples/python/exceptproxy/example.h
@@ -0,0 +1,54 @@
+/* File : example.h */
+
+// A simple exception
+class EmptyError { };
+class FullError { 
+ public:
+  int maxsize;
+  FullError(int m) : maxsize(m) { }
+};
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+template<typename T> class Queue {
+  int maxsize;
+  T   *items;
+  int nitems;
+  int last;
+ public: 
+  Queue(int size) {
+    maxsize = size;
+    items = new T[size];
+    nitems = 0;
+    last = 0;
+  }
+  ~Queue() {
+    delete [] items;
+  }
+  void enqueue(T x) throw(FullError) {
+    if (nitems == maxsize) {
+      throw FullError(maxsize);
+    }
+    items[last] = x;
+    last = (last + 1) % maxsize;
+    nitems++;
+  }
+  T dequeue()  {
+    T x;
+    if (nitems == 0) throw EmptyError();
+    x = items[(last + maxsize - nitems) % maxsize];
+    nitems--;
+    return x;
+  }
+  int length() {
+    return nitems;
+  }
+};
+
+
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
diff --git a/trunk/Examples/python/exceptproxy/example.i b/trunk/Examples/python/exceptproxy/example.i
new file mode 100644
index 0000000..4a1e0ba
--- /dev/null
+++ b/trunk/Examples/python/exceptproxy/example.i
@@ -0,0 +1,114 @@
+/* This is a rather sophisticated example that illustrates exception handling,
+   templates, and proxy classes. 
+
+   (i) The %exception directive is used to attach exception handlers
+       to specific methods.
+
+   (ii) Exception classes are automatically converted to proxy class
+       objects.
+
+   (iii) The %template directive is used to expand the templates
+*/
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Define some exception handlers for specific methods.   In
+   the header file, the enqueue method throws FullError and
+   the dequeue method throws EmptyError.  Since we don't
+   want to define an exception handler for everything, we
+   simply write a handler each method individually.
+
+   Note: the *::enqueue syntax means that we simply define
+   the handler for any class with this method defined.
+*/
+
+/*
+  First we need to 'disable' the default swig throw mechanism for the
+  FullError class. We do this by rethrowing the exception.
+
+  Note that this is necessary since the class appears in a throw
+  declaration:
+
+
+    void enqueue(T x) throw(FullError);
+
+  hence, swig recognizes it as an exception class and it will generate
+  the necessary code to catch it and rethrow it to the python side.
+   
+*/
+%typemap(throws) FullError "(void)$1; throw;";
+
+
+%exception *::enqueue {
+   try {
+      $action
+   } catch(FullError& e) {
+     FullError *ecopy = new FullError(e);
+     PyObject *err = SWIG_NewPointerObj(ecopy, SWIGTYPE_p_FullError, 1);
+     PyErr_SetObject(SWIG_Python_ExceptionType(SWIGTYPE_p_FullError), err);
+     SWIG_fail;
+   }
+}
+
+/* Some notes about the code above:
+
+   (0) $action gets replaced with the actual method call.
+
+   (1) We are going to return a copy of the exception object (FullError)
+       to pass back to the Python interpreter.  This is why the copy
+       constructor is being called.
+
+   (2) The SWIG_NewPointerObj() call automatically wraps the exception object
+       into a proxy class.  The SWIGTYPE_p_FullError is the type-descriptor
+       used for type checking.  The "1" indicates that Python will have
+       ownership of the resulting object.
+
+   (3) The PyErr_SetObject call sets the Python exception.  However,
+       the SWIGTYPE_p_FullError->clientdata reference may not be
+       obvious.  This is actually the Python proxy class object
+       for FullError.  Recall that in Python, exceptions are defined
+       as classes.  Therefore, this works perfectly as the argument to
+       PyErr_SetObject()!   A neat trick perhaps.
+*/
+
+/*
+  Now, the EmpytError doesn't appear in a throw declaration, and hence
+  we need to 'mark' it as an exception class. In python, classes that 
+  are used as exception are 'special', and need to be wrapped as
+  'classic' ones.
+
+  This is a python issue, and if you don't mark the class, you will
+  see 'interesting' behaviours at the python side.
+  
+
+*/
+%exceptionclass EmptyError;
+%exceptionclass FullError;
+
+%exception *::dequeue {
+   try {
+      $action
+   } catch(EmptyError& e) {
+      EmptyError *ecopy = new EmptyError(e);
+      PyObject *err = SWIG_NewPointerObj(ecopy, SWIGTYPE_p_EmptyError, 1);
+      PyErr_SetObject(SWIG_Python_ExceptionType(SWIGTYPE_p_EmptyError), err);
+      SWIG_fail;
+   }
+}
+
+/* Grab the original header file */
+%include "example.h"
+
+/* Instantiate a few templates */
+
+%template(intQueue) Queue<int>;
+%template(doubleQueue) Queue<double>;
+
+
+
+
+
diff --git a/trunk/Examples/python/exceptproxy/runme.py b/trunk/Examples/python/exceptproxy/runme.py
new file mode 100644
index 0000000..a2ae555
--- /dev/null
+++ b/trunk/Examples/python/exceptproxy/runme.py
@@ -0,0 +1,45 @@
+# file: runme.py
+import example
+
+q = example.intQueue(10)
+
+print "Inserting items into intQueue"
+
+try:
+      for i in range(0,100):
+            q.enqueue(i)
+except example.FullError,e:
+      print "Maxsize is", e.maxsize
+
+print "Removing items"
+
+try:
+      while 1:
+            q.dequeue()
+except example.EmptyError,e:
+      pass
+
+
+q = example.doubleQueue(1000)
+
+print "Inserting items into doubleQueue"
+
+try:
+      for i in range(0,10000):
+            q.enqueue(i*1.5)
+except example.FullError,e:
+      print "Maxsize is", e.maxsize
+
+print "Removing items"
+
+try:
+      while 1:
+            q.dequeue()
+except example.EmptyError,e:
+      pass
+
+
+
+
+
+      
diff --git a/trunk/Examples/python/extend/Makefile b/trunk/Examples/python/extend/Makefile
new file mode 100644
index 0000000..ad36d7d
--- /dev/null
+++ b/trunk/Examples/python/extend/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/extend/example.cxx b/trunk/Examples/python/extend/example.cxx
new file mode 100644
index 0000000..450d756
--- /dev/null
+++ b/trunk/Examples/python/extend/example.cxx
@@ -0,0 +1,4 @@
+/* File : example.cxx */
+
+#include "example.h"
+
diff --git a/trunk/Examples/python/extend/example.h b/trunk/Examples/python/extend/example.h
new file mode 100644
index 0000000..b27ab97
--- /dev/null
+++ b/trunk/Examples/python/extend/example.h
@@ -0,0 +1,56 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+#include <vector>
+#include <string>
+#include <cmath>
+
+class Employee {
+private:
+	std::string name;
+public:
+	Employee(const char* n): name(n) {}
+	virtual std::string getTitle() { return getPosition() + " " + getName(); }
+	virtual std::string getName() { return name; }
+	virtual std::string getPosition() const { return "Employee"; }
+	virtual ~Employee() { printf("~Employee() @ %p\n", this); }
+};
+
+
+class Manager: public Employee {
+public:
+	Manager(const char* n): Employee(n) {}
+	virtual std::string getPosition() const { return "Manager"; }
+};
+
+
+class EmployeeList {
+	std::vector<Employee*> list;
+public:
+	EmployeeList() {
+		list.push_back(new Employee("Bob"));
+		list.push_back(new Employee("Jane"));
+		list.push_back(new Manager("Ted"));
+	}
+	void addEmployee(Employee *p) {
+		list.push_back(p);
+		std::cout << "New employee added.   Current employees are:" << std::endl;
+		std::vector<Employee*>::iterator i;
+		for (i=list.begin(); i!=list.end(); i++) {
+			std::cout << "  " << (*i)->getTitle() << std::endl;
+		}
+	}
+	const Employee *get_item(int i) {
+		return list[i];
+	}
+	~EmployeeList() { 
+		std::vector<Employee*>::iterator i;
+		std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl;
+		for (i=list.begin(); i!=list.end(); i++) {
+			delete *i;
+		}
+		std::cout << "~EmployeeList empty." << std::endl;
+	}
+};
+
diff --git a/trunk/Examples/python/extend/example.i b/trunk/Examples/python/extend/example.i
new file mode 100644
index 0000000..c8ec32e
--- /dev/null
+++ b/trunk/Examples/python/extend/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+%include "std_string.i"
+
+/* turn on director wrapping for Manager */
+%feature("director") Employee;
+%feature("director") Manager;
+
+%include "example.h"
+
diff --git a/trunk/Examples/python/extend/index.html b/trunk/Examples/python/extend/index.html
new file mode 100644
index 0000000..959e8c6
--- /dev/null
+++ b/trunk/Examples/python/extend/index.html
@@ -0,0 +1,19 @@
+<html>
+<head>
+<title>SWIG:Examples:python:extend</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/extend/</tt>
+<hr>
+
+<H2>Extending a simple C++ class in Python</H2>
+
+<p>
+This example illustrates the extending of a C++ class with cross language polymorphism.
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/extend/runme.py b/trunk/Examples/python/extend/runme.py
new file mode 100644
index 0000000..240b098
--- /dev/null
+++ b/trunk/Examples/python/extend/runme.py
@@ -0,0 +1,81 @@
+# file: runme.py
+
+# This file illustrates the cross language polymorphism using directors.
+
+import example 
+
+
+# CEO class, which overrides Employee::getPosition().
+
+class CEO(example.Manager):
+	def __init__(self, name):
+		example.Manager.__init__(self, name)
+	def getPosition(self):
+		return "CEO"
+
+
+# Create an instance of our employee extension class, CEO. The calls to
+# getName() and getPosition() are standard, the call to getTitle() uses
+# the director wrappers to call CEO.getPosition. e = CEO("Alice")
+
+e = CEO("Alice")
+print e.getName(), "is a", e.getPosition()
+print "Just call her \"%s\"" % e.getTitle()
+print "----------------------"
+
+
+# Create a new EmployeeList instance.  This class does not have a C++
+# director wrapper, but can be used freely with other classes that do.
+
+list = example.EmployeeList()
+
+# EmployeeList owns its items, so we must surrender ownership of objects
+# we add. This involves first calling the __disown__ method to tell the
+# C++ director to start reference counting. We reassign the resulting
+# weakref.proxy to e so that no hard references remain. This can also be
+# done when the object is constructed, as in: e =
+# CEO("Alice").__disown__()
+
+e = e.__disown__()
+list.addEmployee(e)
+print "----------------------"
+
+# Now we access the first four items in list (three are C++ objects that
+# EmployeeList's constructor adds, the last is our CEO). The virtual
+# methods of all these instances are treated the same. For items 0, 1, and
+# 2, both all methods resolve in C++. For item 3, our CEO, getTitle calls
+# getPosition which resolves in Python. The call to getPosition is
+# slightly different, however, from the e.getPosition() call above, since
+# now the object reference has been "laundered" by passing through
+# EmployeeList as an Employee*. Previously, Python resolved the call
+# immediately in CEO, but now Python thinks the object is an instance of
+# class Employee (actually EmployeePtr). So the call passes through the
+# Employee proxy class and on to the C wrappers and C++ director,
+# eventually ending up back at the CEO implementation of getPosition().
+# The call to getTitle() for item 3 runs the C++ Employee::getTitle()
+# method, which in turn calls getPosition(). This virtual method call
+# passes down through the C++ director class to the Python implementation
+# in CEO. All this routing takes place transparently.
+
+print "(position, title) for items 0-3:"
+
+print "  %s, \"%s\"" % (list.get_item(0).getPosition(), list.get_item(0).getTitle())
+print "  %s, \"%s\"" % (list.get_item(1).getPosition(), list.get_item(1).getTitle())
+print "  %s, \"%s\"" % (list.get_item(2).getPosition(), list.get_item(2).getTitle())
+print "  %s, \"%s\"" % (list.get_item(3).getPosition(), list.get_item(3).getTitle())
+print "----------------------"
+
+# Time to delete the EmployeeList, which will delete all the Employee*
+# items it contains. The last item is our CEO, which gets destroyed as its
+# reference count goes to zero. The Python destructor runs, and is still
+# able to call self.getName() since the underlying C++ object still
+# exists. After this destructor runs the remaining C++ destructors run as
+# usual to destroy the object.
+
+del list
+print "----------------------"
+
+# All done.
+
+print "python exit"
+
diff --git a/trunk/Examples/python/funcptr/Makefile b/trunk/Examples/python/funcptr/Makefile
new file mode 100644
index 0000000..4a1e1bb
--- /dev/null
+++ b/trunk/Examples/python/funcptr/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/funcptr/example.c b/trunk/Examples/python/funcptr/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/python/funcptr/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/python/funcptr/example.h b/trunk/Examples/python/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/python/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/python/funcptr/example.i b/trunk/Examples/python/funcptr/example.i
new file mode 100644
index 0000000..8b3bef6
--- /dev/null
+++ b/trunk/Examples/python/funcptr/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/python/funcptr/index.html b/trunk/Examples/python/funcptr/index.html
new file mode 100644
index 0000000..e41e0db
--- /dev/null
+++ b/trunk/Examples/python/funcptr/index.html
@@ -0,0 +1,90 @@
+<html>
+<head>
+<title>SWIG:Examples:python:funcptr</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/funcptr/</tt>
+<hr>
+
+<H2>Pointers to Functions</H2>
+
+<p>
+Okay, just what in the heck does SWIG do with a declaration like this?
+
+<blockquote>
+<pre>
+int do_op(int a, int b, int (*op)(int, int));
+</pre>
+</blockquote>
+
+Well, it creates a wrapper as usual.  Of course, that does raise some
+questions about the third argument (the pointer to a function). 
+
+<p>
+In this case, SWIG will wrap the function pointer as it does for all other
+pointers.  However, in order to actually call this function from a script,
+you will need to pass some kind of C function pointer object.  In C,
+this is easy, you just supply a function name as an argument like this:
+
+<blockquote>
+<pre>
+/* Some callback function */
+int add(int a, int b) {
+   return a+b;
+} 
+...
+int r = do_op(x,y,add);
+</pre>
+</blockquote>
+
+To make this work with SWIG, you will need to do a little extra work.  Specifically,
+you need to create some function pointer objects using the %constant directive like this:
+
+<blockquote>
+<pre>
+%constant(int (*)(int,int)) ADD = add;
+</pre>
+</blockquote>
+
+Now, in a script, you would do this:
+
+<blockquote>
+<pre>
+r = do_op(x,y, ADD)
+</pre>
+</blockquote>
+
+<h2>An Example</h2>
+
+Here are some files that illustrate this with a simple example:
+
+<ul>
+<li><a href="example.c">example.c</a>
+<li><a href="example.h">example.h</a>
+<li><a href="example.i">example.i</a> (SWIG interface)
+<li><a href="example.py">example.py</a> (Sample script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>The value of a function pointer must correspond to a function written in C or C++.
+It is not possible to pass an arbitrary Python function object in as a substitute for a C 
+function pointer.
+
+<p>
+<li>A python function can be used as a C/C++ callback if you write some
+clever typemaps and are very careful about how you create your extension.
+This is an advanced topic not covered here.
+</ul>
+
+<hr>
+</body>
+</html>
+
+
+
+
diff --git a/trunk/Examples/python/funcptr/runme.py b/trunk/Examples/python/funcptr/runme.py
new file mode 100644
index 0000000..bce0650
--- /dev/null
+++ b/trunk/Examples/python/funcptr/runme.py
@@ -0,0 +1,20 @@
+# file: runme.py
+
+import example 
+
+a = 37
+b = 42
+
+# Now call our C function with a bunch of callbacks
+
+print "Trying some C callback functions"
+print "    a        =", a
+print "    b        =", b
+print "    ADD(a,b) =", example.do_op(a,b,example.ADD)
+print "    SUB(a,b) =", example.do_op(a,b,example.SUB)
+print "    MUL(a,b) =", example.do_op(a,b,example.MUL)
+
+print "Here is what the C callback function objects look like in Python"
+print "    ADD      =", example.ADD
+print "    SUB      =", example.SUB
+print "    MUL      =", example.MUL
diff --git a/trunk/Examples/python/funcptr2/Makefile b/trunk/Examples/python/funcptr2/Makefile
new file mode 100644
index 0000000..4a1e1bb
--- /dev/null
+++ b/trunk/Examples/python/funcptr2/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/funcptr2/example.c b/trunk/Examples/python/funcptr2/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/python/funcptr2/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/python/funcptr2/example.h b/trunk/Examples/python/funcptr2/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/python/funcptr2/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/python/funcptr2/example.i b/trunk/Examples/python/funcptr2/example.i
new file mode 100644
index 0000000..681775a
--- /dev/null
+++ b/trunk/Examples/python/funcptr2/example.i
@@ -0,0 +1,18 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%callback("%(upper)s");
+int add(int, int);
+int sub(int, int);
+int mul(int, int);
+%nocallback;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/python/funcptr2/runme.py b/trunk/Examples/python/funcptr2/runme.py
new file mode 100644
index 0000000..bd58fb6
--- /dev/null
+++ b/trunk/Examples/python/funcptr2/runme.py
@@ -0,0 +1,24 @@
+# file: runme.py
+
+import example 
+
+a = 37
+b = 42
+
+# Now call our C function with a bunch of callbacks
+
+print "Trying some C callback functions"
+print "    a        =", a
+print "    b        =", b
+print "    ADD(a,b) =", example.do_op(a,b,example.ADD)
+print "    SUB(a,b) =", example.do_op(a,b,example.SUB)
+print "    MUL(a,b) =", example.do_op(a,b,example.MUL)
+
+print "Here is what the C callback function objects look like in Python"
+print "    ADD      =", example.ADD
+print "    SUB      =", example.SUB
+print "    MUL      =", example.MUL
+
+print "Call the functions directly..."
+print "    add(a,b) =", example.add(a,b)
+print "    sub(a,b) =", example.sub(a,b)
diff --git a/trunk/Examples/python/functor/Makefile b/trunk/Examples/python/functor/Makefile
new file mode 100644
index 0000000..c455365
--- /dev/null
+++ b/trunk/Examples/python/functor/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/functor/example.i b/trunk/Examples/python/functor/example.i
new file mode 100644
index 0000000..2fd3817
--- /dev/null
+++ b/trunk/Examples/python/functor/example.i
@@ -0,0 +1,29 @@
+/* File : example.i */
+%module example
+
+
+%inline %{
+// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514
+template<class T> class Sum {
+   T res;
+public:
+   Sum(T i = 0) : res(i) { }
+   void operator() (T x) { res += x; }
+   T result() const { return res; }
+};
+
+%}
+
+// Rename the application operator to __call__ for python.
+// Note: this is normally automatic, but if you had to do it yourself
+// you would use this directive:
+//
+// %rename(__call__) *::operator();
+
+// Instantiate a few versions
+%template(intSum) Sum<int>;
+%template(doubleSum) Sum<double>;
+
+
+
+
diff --git a/trunk/Examples/python/functor/runme.py b/trunk/Examples/python/functor/runme.py
new file mode 100644
index 0000000..8fc0f2f
--- /dev/null
+++ b/trunk/Examples/python/functor/runme.py
@@ -0,0 +1,17 @@
+# Operator overloading example
+import example
+import math
+
+a = example.intSum(0)
+b = example.doubleSum(100.0)
+
+# Use the objects.  They should be callable just like a normal
+# python function.
+
+for i in range(0,100):
+    a(i)                # Note: function call
+    b(math.sqrt(i))     # Note: function call
+
+print a.result()
+print b.result()
+
diff --git a/trunk/Examples/python/import/Makefile b/trunk/Examples/python/import/Makefile
new file mode 100644
index 0000000..e00e818
--- /dev/null
+++ b/trunk/Examples/python/import/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+
+all:: 
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	@rm -f foo.py bar.py spam.py base.py
+
+check: all
diff --git a/trunk/Examples/python/import/README b/trunk/Examples/python/import/README
new file mode 100644
index 0000000..5679dbb
--- /dev/null
+++ b/trunk/Examples/python/import/README
@@ -0,0 +1,39 @@
+This example tests the %import directive and working with multiple modules.
+
+Use 'python runme.py' to run a test.
+
+Overview:
+---------
+
+The example defines 4 different extension modules--each wrapping
+a separate C++ class.
+
+     base.i     -  Base class
+     foo.i      -  Foo class derived from Base
+     bar.i      -  Bar class derived from Base
+     spam.i     -  Spam class derived from Bar
+
+Each module uses %import to refer to another module.  For
+example, the 'foo.i' module uses '%import base.i' to get
+definitions for its base class.
+
+If everything is okay, all of the modules will load properly and
+type checking will work correctly. Caveat: Some compilers, for example
+gcc-3.2.x, generate broken vtables with the inline methods in this test.
+This is not a SWIG problem and can usually be solved with non-inlined
+destructors compiled into separate shared objects/DLLs.
+
+Unix:
+-----
+- Run make
+- Run the test as described above
+
+Windows:
+--------
+- Use the Visual C++ 6 workspace file (example.dsw). Build the runtime
+  project DLL first followed by the other 4 DLLs as they all have a
+  dependency on the runtime DLL. The Batch build option in the Build menu
+  is usually the easiest way to do this. Only use the Release builds not
+  the Debug builds.
+- Run the test as described above
+
diff --git a/trunk/Examples/python/import/bar.dsp b/trunk/Examples/python/import/bar.dsp
new file mode 100644
index 0000000..edb4581
--- /dev/null
+++ b/trunk/Examples/python/import/bar.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="bar" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=bar - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak" CFG="bar - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "bar - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "bar - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_bar.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_bar.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "bar - Win32 Debug"

+# Name "bar - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\bar_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\bar.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\bar.i

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/import/bar.h b/trunk/Examples/python/import/bar.h
new file mode 100644
index 0000000..fa4185f
--- /dev/null
+++ b/trunk/Examples/python/import/bar.h
@@ -0,0 +1,22 @@
+#include "base.h"
+
+class Bar : public Base {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual void A() { 
+    printf("I'm Bar::A\n");
+  }
+  void B() {
+    printf("I'm Bar::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Bar *fromBase(Base *b) {
+    return dynamic_cast<Bar *>(b);
+  }
+
+};
+
+
diff --git a/trunk/Examples/python/import/bar.i b/trunk/Examples/python/import/bar.i
new file mode 100644
index 0000000..5816cbe
--- /dev/null
+++ b/trunk/Examples/python/import/bar.i
@@ -0,0 +1,9 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+
diff --git a/trunk/Examples/python/import/base.dsp b/trunk/Examples/python/import/base.dsp
new file mode 100644
index 0000000..0ddb651
--- /dev/null
+++ b/trunk/Examples/python/import/base.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="base" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=base - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak" CFG="base - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "base - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "base - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_base.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_base.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "base - Win32 Debug"

+# Name "base - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\base_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\base.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\base.i

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/import/base.h b/trunk/Examples/python/import/base.h
new file mode 100644
index 0000000..5a266f6
--- /dev/null
+++ b/trunk/Examples/python/import/base.h
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual void A() {
+         printf("I'm Base::A\n");
+     }
+     void B() {
+       printf("I'm Base::B\n");
+     }
+     virtual Base *toBase() {
+       return static_cast<Base *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/python/import/base.i b/trunk/Examples/python/import/base.i
new file mode 100644
index 0000000..f6e19ef
--- /dev/null
+++ b/trunk/Examples/python/import/base.i
@@ -0,0 +1,6 @@
+%module base
+%{
+#include "base.h"
+%}
+
+%include base.h
diff --git a/trunk/Examples/python/import/example.dsw b/trunk/Examples/python/import/example.dsw
new file mode 100644
index 0000000..d395d46
--- /dev/null
+++ b/trunk/Examples/python/import/example.dsw
@@ -0,0 +1,65 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00

+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!

+

+###############################################################################

+

+Project: "bar"=.\bar.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "base"=.\base.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "foo"=.\foo.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "spam"=.\spam.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Global:

+

+Package=<5>

+{{{

+}}}

+

+Package=<3>

+{{{

+}}}

+

+###############################################################################

+

diff --git a/trunk/Examples/python/import/foo.dsp b/trunk/Examples/python/import/foo.dsp
new file mode 100644
index 0000000..86e1169
--- /dev/null
+++ b/trunk/Examples/python/import/foo.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="foo" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=foo - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak" CFG="foo - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "foo - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "foo - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_foo.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_foo.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "foo - Win32 Debug"

+# Name "foo - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\foo_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\foo.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\foo.i

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/import/foo.h b/trunk/Examples/python/import/foo.h
new file mode 100644
index 0000000..dd51840
--- /dev/null
+++ b/trunk/Examples/python/import/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Foo : public Base {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual void A() { 
+    printf("I'm Foo::A\n");
+  }
+  void B() {
+    printf("I'm Foo::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Foo *fromBase(Base *b) {
+    return dynamic_cast<Foo *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/python/import/foo.i b/trunk/Examples/python/import/foo.i
new file mode 100644
index 0000000..27feb2e
--- /dev/null
+++ b/trunk/Examples/python/import/foo.i
@@ -0,0 +1,8 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
diff --git a/trunk/Examples/python/import/runme.py b/trunk/Examples/python/import/runme.py
new file mode 100644
index 0000000..6b800ec
--- /dev/null
+++ b/trunk/Examples/python/import/runme.py
@@ -0,0 +1,111 @@
+# file: runme.py
+# Test various properties of classes defined in separate modules
+
+print "Testing the %import directive"
+import base
+import foo
+import bar
+import spam
+
+# Create some objects
+
+print "Creating some objects"
+
+a = base.Base()
+b = foo.Foo()
+c = bar.Bar()
+d = spam.Spam()
+
+# Try calling some methods
+print "Testing some methods"
+print "",
+print "Should see 'Base::A' ---> ",
+a.A()
+print "Should see 'Base::B' ---> ",
+a.B()
+
+print "Should see 'Foo::A' ---> ",
+b.A()
+print "Should see 'Foo::B' ---> ",
+b.B()
+
+print "Should see 'Bar::A' ---> ",
+c.A()
+print "Should see 'Bar::B' ---> ",
+c.B()
+
+print "Should see 'Spam::A' ---> ",
+d.A()
+print "Should see 'Spam::B' ---> ",
+d.B()
+
+# Try some casts
+
+print "\nTesting some casts\n"
+print "",
+
+x = a.toBase()
+print "Should see 'Base::A' ---> ",
+x.A()
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = b.toBase()
+print "Should see 'Foo::A' ---> ",
+x.A()
+
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = c.toBase()
+print "Should see 'Bar::A' ---> ",
+x.A()
+
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = d.toBase()
+print "Should see 'Spam::A' ---> ",
+x.A()
+
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = d.toBar()
+print "Should see 'Bar::B' ---> ",
+x.B()
+
+print "\nTesting some dynamic casts\n"
+x = d.toBase()
+
+print " Spam -> Base -> Foo : ",
+y = foo.Foo_fromBase(x)
+if y:
+      print "bad swig"
+else:
+      print "good swig"
+
+print " Spam -> Base -> Bar : ",
+y = bar.Bar_fromBase(x)
+if y:
+      print "good swig"
+else:
+      print "bad swig"
+      
+print " Spam -> Base -> Spam : ",
+y = spam.Spam_fromBase(x)
+if y:
+      print "good swig"
+else:
+      print "bad swig"
+
+print " Foo -> Spam : ",
+y = spam.Spam_fromBase(b)
+if y:
+      print "bad swig"
+else:
+      print "good swig"
+
+
+
+
diff --git a/trunk/Examples/python/import/spam.dsp b/trunk/Examples/python/import/spam.dsp
new file mode 100644
index 0000000..7245f7a
--- /dev/null
+++ b/trunk/Examples/python/import/spam.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="spam" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=spam - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak" CFG="spam - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "spam - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "spam - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_spam.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_spam.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "spam - Win32 Debug"

+# Name "spam - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\spam_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\spam.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\spam.i

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -c++ -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/import/spam.h b/trunk/Examples/python/import/spam.h
new file mode 100644
index 0000000..b4e7a26
--- /dev/null
+++ b/trunk/Examples/python/import/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+class Spam : public Bar {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual void A() { 
+    printf("I'm Spam::A\n");
+  }
+  void B() {
+    printf("I'm Spam::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  virtual Bar *toBar() {
+    return static_cast<Bar *>(this);
+  }
+  static Spam *fromBase(Base *b) {
+    return dynamic_cast<Spam *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/python/import/spam.i b/trunk/Examples/python/import/spam.i
new file mode 100644
index 0000000..d3d9121
--- /dev/null
+++ b/trunk/Examples/python/import/spam.i
@@ -0,0 +1,9 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+
diff --git a/trunk/Examples/python/import_template/Makefile b/trunk/Examples/python/import_template/Makefile
new file mode 100644
index 0000000..fa49f31
--- /dev/null
+++ b/trunk/Examples/python/import_template/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	@rm -f foo.py bar.py spam.py base.py
+
+check: all
diff --git a/trunk/Examples/python/import_template/README b/trunk/Examples/python/import_template/README
new file mode 100644
index 0000000..f8cf02d
--- /dev/null
+++ b/trunk/Examples/python/import_template/README
@@ -0,0 +1,30 @@
+This example tests the %import directive and working with multiple modules.
+
+Use 'python runme.py' to run a test.
+
+Overview:
+---------
+
+The example defines 4 different extension modules--each wrapping
+a separate C++ class.
+
+     base.i     -  Base class
+     foo.i      -  Foo class derived from Base
+     bar.i      -  Bar class derived from Base
+     spam.i     -  Spam class derived from Bar
+
+Each module uses %import to refer to another module.  For
+example, the 'foo.i' module uses '%import base.i' to get
+definitions for its base class.
+
+If everything is okay, all of the modules will load properly and
+type checking will work correctly. Caveat: Some compilers, for example
+gcc-3.2.x, generate broken vtables with the inline methods in this test.
+This is not a SWIG problem and can usually be solved with non-inlined
+destructors compiled into separate shared objects/DLLs.
+
+Unix:
+-----
+- Run make
+- Run the test as described above
+
diff --git a/trunk/Examples/python/import_template/bar.h b/trunk/Examples/python/import_template/bar.h
new file mode 100644
index 0000000..500b67a
--- /dev/null
+++ b/trunk/Examples/python/import_template/bar.h
@@ -0,0 +1,22 @@
+#include "base.h"
+
+template<class T> class Bar : public Base<T> {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual void A() { 
+    printf("I'm Bar::A\n");
+  }
+  void B() {
+    printf("I'm Bar::B\n");
+  }
+  virtual Base<T> *toBase() {
+    return static_cast<Base<T> *>(this);
+  }
+  static Bar<T> *fromBase(Base<T> *b) {
+    return dynamic_cast<Bar<T> *>(b);
+  }
+
+};
+
+
diff --git a/trunk/Examples/python/import_template/bar.i b/trunk/Examples/python/import_template/bar.i
new file mode 100644
index 0000000..155c08d
--- /dev/null
+++ b/trunk/Examples/python/import_template/bar.i
@@ -0,0 +1,11 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+%template(intBar) Bar<int>;
+
+
diff --git a/trunk/Examples/python/import_template/base.h b/trunk/Examples/python/import_template/base.h
new file mode 100644
index 0000000..c755a6f
--- /dev/null
+++ b/trunk/Examples/python/import_template/base.h
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+template<class T> class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual void A() {
+         printf("I'm Base::A\n");
+     }
+     void B() {
+       printf("I'm Base::B\n");
+     }
+     virtual Base<T> *toBase() {
+       return static_cast<Base<T> *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/python/import_template/base.i b/trunk/Examples/python/import_template/base.i
new file mode 100644
index 0000000..a6da063
--- /dev/null
+++ b/trunk/Examples/python/import_template/base.i
@@ -0,0 +1,7 @@
+%module base
+%{
+#include "base.h"
+%}
+
+%include base.h
+%template(intBase) Base<int>;
diff --git a/trunk/Examples/python/import_template/foo.h b/trunk/Examples/python/import_template/foo.h
new file mode 100644
index 0000000..3df13d2
--- /dev/null
+++ b/trunk/Examples/python/import_template/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+template<class T> class Foo : public Base<T> {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual void A() { 
+    printf("I'm Foo::A\n");
+  }
+  void B() {
+    printf("I'm Foo::B\n");
+  }
+  virtual Base<T> *toBase() {
+    return static_cast<Base<T> *>(this);
+  }
+  static Foo<T> *fromBase(Base<T> *b) {
+    return dynamic_cast<Foo<T> *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/python/import_template/foo.i b/trunk/Examples/python/import_template/foo.i
new file mode 100644
index 0000000..e271672
--- /dev/null
+++ b/trunk/Examples/python/import_template/foo.i
@@ -0,0 +1,10 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
+%template(intFoo) Foo<int>;
+
diff --git a/trunk/Examples/python/import_template/runme.py b/trunk/Examples/python/import_template/runme.py
new file mode 100644
index 0000000..0d5aded
--- /dev/null
+++ b/trunk/Examples/python/import_template/runme.py
@@ -0,0 +1,111 @@
+# file: runme.py
+# Test various properties of classes defined in separate modules
+
+print "Testing the %import directive with templates"
+import base
+import foo
+import bar
+import spam
+
+# Create some objects
+
+print "Creating some objects"
+
+a = base.intBase()
+b = foo.intFoo()
+c = bar.intBar()
+d = spam.intSpam()
+
+# Try calling some methods
+print "Testing some methods"
+print "",
+print "Should see 'Base::A' ---> ",
+a.A()
+print "Should see 'Base::B' ---> ",
+a.B()
+
+print "Should see 'Foo::A' ---> ",
+b.A()
+print "Should see 'Foo::B' ---> ",
+b.B()
+
+print "Should see 'Bar::A' ---> ",
+c.A()
+print "Should see 'Bar::B' ---> ",
+c.B()
+
+print "Should see 'Spam::A' ---> ",
+d.A()
+print "Should see 'Spam::B' ---> ",
+d.B()
+
+# Try some casts
+
+print "\nTesting some casts\n"
+print "",
+
+x = a.toBase()
+print "Should see 'Base::A' ---> ",
+x.A()
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = b.toBase()
+print "Should see 'Foo::A' ---> ",
+x.A()
+
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = c.toBase()
+print "Should see 'Bar::A' ---> ",
+x.A()
+
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = d.toBase()
+print "Should see 'Spam::A' ---> ",
+x.A()
+
+print "Should see 'Base::B' ---> ",
+x.B()
+
+x = d.toBar()
+print "Should see 'Bar::B' ---> ",
+x.B()
+
+print "\nTesting some dynamic casts\n"
+x = d.toBase()
+
+print " Spam -> Base -> Foo : ",
+y = foo.intFoo_fromBase(x)
+if y:
+      print "bad swig"
+else:
+      print "good swig"
+
+print " Spam -> Base -> Bar : ",
+y = bar.intBar_fromBase(x)
+if y:
+      print "good swig"
+else:
+      print "bad swig"
+      
+print " Spam -> Base -> Spam : ",
+y = spam.intSpam_fromBase(x)
+if y:
+      print "good swig"
+else:
+      print "bad swig"
+
+print " Foo -> Spam : ",
+y = spam.intSpam_fromBase(b)
+if y:
+      print "bad swig"
+else:
+      print "good swig"
+
+
+
+
diff --git a/trunk/Examples/python/import_template/spam.h b/trunk/Examples/python/import_template/spam.h
new file mode 100644
index 0000000..c72f49a
--- /dev/null
+++ b/trunk/Examples/python/import_template/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+template<class T> class Spam : public Bar<T> {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual void A() { 
+    printf("I'm Spam::A\n");
+  }
+  void B() {
+    printf("I'm Spam::B\n");
+  }
+  virtual Base<T> *toBase() {
+    return static_cast<Base<T> *>(this);
+  }
+  virtual Bar<T> *toBar() {
+    return static_cast<Bar<T> *>(this);
+  }
+  static Spam<T> *fromBase(Base<T> *b) {
+    return dynamic_cast<Spam<T> *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/python/import_template/spam.i b/trunk/Examples/python/import_template/spam.i
new file mode 100644
index 0000000..dd94b03
--- /dev/null
+++ b/trunk/Examples/python/import_template/spam.i
@@ -0,0 +1,10 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+%template(intSpam) Spam<int>;
+
diff --git a/trunk/Examples/python/index.html b/trunk/Examples/python/index.html
new file mode 100644
index 0000000..8443a85
--- /dev/null
+++ b/trunk/Examples/python/index.html
@@ -0,0 +1,112 @@
+<html>
+<head>
+<title>SWIG:Examples:python</title>
+</head>
+
+<body bgcolor="#ffffff">
+<H1>SWIG Python Examples</H1>
+
+<p>
+The following examples illustrate the use of SWIG with Python.
+
+<ul>
+<li><a href="simple/index.html">simple</a>.  A minimal example showing how SWIG can
+be used to wrap a C function, a global variable, and a constant.
+<li><a href="constants/index.html">constants</a>.  This shows how preprocessor macros and
+certain C declarations are turned into constants.
+<li><a href="variables/index.html">variables</a>. An example showing how to access C global variables from Python.
+<li><a href="value/index.html">value</a>. How to pass and return structures by value.
+<li><a href="class/index.html">class</a>. Wrapping a simple C++ class.
+<li><a href="reference/index.html">reference</a>. C++ references.
+<li><a href="pointer/index.html">pointer</a>. Simple pointer handling.
+<li><a href="funcptr/index.html">funcptr</a>. Pointers to functions.
+</ul>
+
+<h2>Compilation Issues</h2>
+
+<ul>
+<li>To create a Python extension, SWIG is run with the following options:
+
+<blockquote>
+<pre>
+% swig -python interface.i
+</pre>
+</blockquote>
+
+<li>
+Please see the <a href="../../Doc/Manual/Windows.html">Windows</a> page in the main manual for information on using the examples on Windows. <p>
+</li>
+
+<li>On Unix the compilation of examples is done using the file <tt>Example/Makefile</tt>.  This
+makefile performs a manual module compilation which is platform specific.  Typically,
+the steps look like this (Linux):
+
+<blockquote>
+<pre>
+% swig -python interface.i
+% gcc -fpic -c interface_wrap.c -I/usr/local/include/python1.5
+% gcc -shared interface_wrap.o $(OBJS) -o interfacemodule.so 
+% python
+Python 1.5.2 (#3, Oct  9 1999, 22:09:34)  [GCC 2.95.1 19990816 (release)] on linux2
+Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
+&gt;&gt;&gt; import interface
+&gt;&gt;&gt; interface.blah(...)
+...
+</pre>
+</blockquote>
+
+<li>The politically "correct" way to compile a Python extension is to follow the steps
+described at <a href="http://www.python.org/doc/current/ext/building-on-unix.html">www.python.org</a>
+or in the most excellent (and shamelessly plugged) <a href="http://islab.cs.uchicago.edu/python">Python Essential Reference</a>:
+
+<p>
+<ol>
+<li>Create a file called <tt>Setup</tt> that looks like the following where $(SRCS) is filled
+in with any other source files you need to build the extension:
+
+<blockquote>
+<pre>
+*shared*
+interface interface_wrap.c $(SRCS)
+</pre>
+</blockquote>
+<li>Copy the file <tt>Makefile.pre.in</tt> from the Python distribution.  Usually it's located 
+in the directory <tt>/usr/local/lib/python1.5/config</tt> on a Unix machine.
+
+<p>
+<li>Type the following to build the extension:
+
+<blockquote>
+<pre>
+% make -f Makefile.pre.in boot
+% make
+</pre>
+</blockquote>
+<li> And that's it.   If you are preparing an extension for distribution, you may want
+to look at the <a href="http://www.python.org/sigs/distutils-sig/">distutils</a>.
+</ol>
+</ul>
+
+<h2>Compatibility</h2>
+
+The examples have been extensively tested on the following platforms:
+
+<ul>
+<li>Linux
+<li>Solaris
+</ul>
+
+All of the examples were last tested with the following configuration (9/1/2000):
+
+<ul>
+<li>Sparc Solaris 2.8.
+<li>gcc-2.95.2
+<li>Python 1.6b1.
+</ul>
+
+Your mileage may vary.  If you experience a problem, please let us know by 
+contacting us on the <a href="http://www.swig.org/mail.html">mailing lists</a>.
+</body>
+</html>
+
+
diff --git a/trunk/Examples/python/java/Example.java b/trunk/Examples/python/java/Example.java
new file mode 100644
index 0000000..91ddb1a
--- /dev/null
+++ b/trunk/Examples/python/java/Example.java
@@ -0,0 +1,29 @@
+public class Example {
+    public   int      mPublicInt;
+    
+    public Example() {
+	mPublicInt = 0;
+    }
+    
+    public Example(int IntVal) {
+	mPublicInt = IntVal;
+    }
+    
+    
+    public int Add(int a, int b) {
+	return (a+b);
+    }
+    
+    public float Add(float a, float b) {
+	return (a+b);
+    }
+    
+    public String Add(String a, String b) {
+	return (a+b);
+    }
+    
+    public Example Add(Example a, Example b) {
+	return new Example(a.mPublicInt + b.mPublicInt);
+    }
+}
+
diff --git a/trunk/Examples/python/java/Makefile b/trunk/Examples/python/java/Makefile
new file mode 100644
index 0000000..326a4da
--- /dev/null
+++ b/trunk/Examples/python/java/Makefile
@@ -0,0 +1,25 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all:: Example.class
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj"  \
+	CXXSHARED="gcj -fpic -shared Example.class" DEFS='' LIBS="-lstdc++" python_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+	rm -f *.class Example.h
+
+check: all
+
+
+Example.class: Example.java
+	gcj -fPIC -C -c -g Example.java
+	gcjh  Example
+
diff --git a/trunk/Examples/python/java/example.i b/trunk/Examples/python/java/example.i
new file mode 100644
index 0000000..13d5b5e
--- /dev/null
+++ b/trunk/Examples/python/java/example.i
@@ -0,0 +1,9 @@
+%module example
+%include <cni.i>
+
+%{
+#include "Example.h"
+%}
+
+
+%include Example.h
diff --git a/trunk/Examples/python/java/runme.py b/trunk/Examples/python/java/runme.py
new file mode 100644
index 0000000..0cec8a7
--- /dev/null
+++ b/trunk/Examples/python/java/runme.py
@@ -0,0 +1,16 @@
+from example import *
+
+JvCreateJavaVM(None)
+JvAttachCurrentThread(None, None)
+
+e1 = Example(1)
+e2 = Example(2)
+
+print e1.Add(1,2)
+print e1.Add(1.0,2.0)
+e3 = e1.Add(e1,e2)
+print e3.mPublicInt
+
+print e1.Add("1","2")
+
+JvDetachCurrentThread()
diff --git a/trunk/Examples/python/libffi/Makefile b/trunk/Examples/python/libffi/Makefile
new file mode 100644
index 0000000..8c7edfa
--- /dev/null
+++ b/trunk/Examples/python/libffi/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS='-L/usr/local/lib -lffi' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/libffi/example.i b/trunk/Examples/python/libffi/example.i
new file mode 100644
index 0000000..9a29ec0
--- /dev/null
+++ b/trunk/Examples/python/libffi/example.i
@@ -0,0 +1,176 @@
+/* File : example.i */
+%module example
+
+%{
+#include <unistd.h>
+#include <ffi.h>
+%}
+
+/* A wrapper for execlp() using libffi to handle an arbitrary
+   number of arguments */
+
+%typemap(in) (...) {
+   char **argv;
+   int    argc;
+   int    i;
+
+   argc = PyTuple_Size(varargs);
+   argv = (char **) malloc(sizeof(char *)*(argc+1));
+   for (i = 0; i < argc; i++) {
+      PyObject *o = PyTuple_GetItem(varargs,i);
+      if (!PyString_Check(o)) {
+          PyErr_SetString(PyExc_ValueError,"Expected a string");
+          return NULL;
+      }
+      argv[i] = PyString_AsString(o);
+   }
+   argv[i] = NULL;
+   $1 = (void *) argv;
+}
+
+/* Rewrite the function call, using libffi */    
+%feature("action") execlp {
+  int       i, vc;
+  ffi_cif   cif;
+  ffi_type  **types;
+  void      **values;
+  char      **args;
+
+  vc = PyTuple_Size(varargs);
+  types  = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *));
+  values = (void **) malloc((vc+3)*sizeof(void *));
+  args   = (char **) arg3;
+
+  /* Set up path parameter */
+  types[0] = &ffi_type_pointer;
+  values[0] = &arg1;
+  
+  /* Set up first argument */
+  types[1] = &ffi_type_pointer;
+  values[1] = &arg2;
+
+  /* Set up rest of parameters */
+  for (i = 0; i <= vc; i++) {
+    types[2+i] = &ffi_type_pointer;
+    values[2+i] = &args[i];
+  }
+  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+3,
+                   &ffi_type_uint, types) == FFI_OK) {
+    ffi_call(&cif, (void (*)()) execlp, &result, values);
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
+    free(types);
+    free(values);
+    free(arg3);
+    return NULL;
+  }
+  free(types);
+  free(values);
+  free(arg3);
+}
+
+int execlp(const char *path, const char *arg1, ...);
+
+
+/* A wrapper for printf() using libffi */
+
+%{
+  typedef struct {
+    int type;
+    union {
+      int    ivalue;
+      double dvalue;
+      void   *pvalue;
+    } val;
+  } vtype;
+  enum { VT_INT, VT_DOUBLE, VT_POINTER };
+  %}
+
+%typemap(in) (const char *fmt, ...) {
+  vtype *argv;
+  int    argc;
+  int    i;
+
+  $1 = PyString_AsString($input);
+
+  argc = PyTuple_Size(varargs);
+  argv = (vtype *) malloc(argc*sizeof(vtype));
+  for (i = 0; i < argc; i++) {
+    PyObject *o = PyTuple_GetItem(varargs,i);
+    if (PyInt_Check(o)) {
+      argv[i].type = VT_INT;
+      argv[i].val.ivalue = PyInt_AsLong(o);
+    } else if (PyFloat_Check(o)) {
+      argv[i].type = VT_DOUBLE;
+      argv[i].val.dvalue = PyFloat_AsDouble(o);
+    } else if (PyString_Check(o)) {
+      argv[i].type = VT_POINTER;
+      argv[i].val.pvalue = (void *) PyString_AsString(o);
+    } else {
+      PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
+      free(argv);
+      return NULL;
+    }
+  }
+
+  $2 = (void *) argv;
+}
+
+/* Rewrite the function call, using libffi */    
+%feature("action") printf {
+  int       i, vc;
+  ffi_cif   cif;
+  ffi_type  **types;
+  void      **values;
+  vtype     *args;
+
+  vc = PyTuple_Size(varargs);
+  types  = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *));
+  values = (void **) malloc((vc+1)*sizeof(void *));
+  args   = (vtype *) arg2;
+
+  /* Set up fmt parameter */
+  types[0] = &ffi_type_pointer;
+  values[0] = &arg1;
+
+  /* Set up rest of parameters */
+  for (i = 0; i < vc; i++) {
+    switch(args[i].type) {
+    case VT_INT:
+      types[1+i] = &ffi_type_uint;
+      values[1+i] = &args[i].val.ivalue;
+      break;
+    case VT_DOUBLE:
+      types[1+i] = &ffi_type_double;
+      values[1+i] = &args[i].val.dvalue;
+      break;
+    case VT_POINTER:
+      types[1+i] = &ffi_type_pointer;
+      values[1+i] = &args[i].val.pvalue;
+      break;
+    default:
+      abort();    /* Whoa! We're seriously hosed */
+      break;   
+    }
+  }
+  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+1,
+                   &ffi_type_uint, types) == FFI_OK) {
+    ffi_call(&cif, (void (*)()) printf, &result, values);
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
+    free(types);
+    free(values);
+    free(args);
+    return NULL;
+  }
+  free(types);
+  free(values);
+  free(args);
+}
+
+int printf(const char *fmt, ...);
+
+
+  
+
+
diff --git a/trunk/Examples/python/multimap/Makefile b/trunk/Examples/python/multimap/Makefile
new file mode 100644
index 0000000..4a1e1bb
--- /dev/null
+++ b/trunk/Examples/python/multimap/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/multimap/example.c b/trunk/Examples/python/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/python/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/python/multimap/example.dsp b/trunk/Examples/python/multimap/example.dsp
new file mode 100644
index 0000000..7a32f4d
--- /dev/null
+++ b/trunk/Examples/python/multimap/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_example.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_example.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/multimap/example.i b/trunk/Examples/python/multimap/example.i
new file mode 100644
index 0000000..163d7cc
--- /dev/null
+++ b/trunk/Examples/python/multimap/example.i
@@ -0,0 +1,89 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+%include typemaps.i
+
+extern int    gcd(int x, int y);
+
+%typemap(in,fragment="t_output_helper") (int argc, char *argv[]) {
+  int i;
+  if (!PyList_Check($input)) {
+    SWIG_exception(SWIG_ValueError, "Expecting a list");
+  }
+  $1 = PyList_Size($input);
+  if ($1 == 0) {
+    SWIG_exception(SWIG_ValueError, "List must contain at least 1 element");
+  }
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i < $1; i++) {
+    PyObject *s = PyList_GetItem($input,i);
+    if (!PyString_Check(s)) {
+      free($2);
+      SWIG_exception(SWIG_ValueError, "List items must be strings");
+    }
+    $2[i] = PyString_AsString(s);
+  }
+  $2[i] = 0;
+}
+
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  if (!PyString_Check($input)) {
+    PyErr_SetString(PyExc_ValueError,"Expected a string");
+    return NULL;
+  }
+  $1 = PyString_AsString($input);
+  $2 = PyString_Size($input);
+}
+
+extern int count(char *bytes, int len, char c);
+
+
+/* This example shows how to wrap a function that mutates a string */
+
+/* Since str is modified, we make a copy of the Python object
+   so that we don't violate it's mutability */
+
+%typemap(in) (char *str, int len) {
+   $2 = PyString_Size($input);
+   $1 = (char *) malloc($2+1);
+   memmove($1,PyString_AsString($input),$2);
+}
+
+/* Return the mutated string as a new object.  The t_output_helper
+   function takes an object and appends it to the output object
+   to create a tuple */
+
+%typemap(argout) (char *str, int len) {
+   PyObject *o;
+   o = PyString_FromStringAndSize($1,$2);
+   $result = t_output_helper($result,o);
+   free($1);
+}   
+
+extern void capitalize(char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
+   }
+}
+
+extern void circle(double cx, double cy);
+
+
diff --git a/trunk/Examples/python/multimap/runme.py b/trunk/Examples/python/multimap/runme.py
new file mode 100644
index 0000000..f996ab3
--- /dev/null
+++ b/trunk/Examples/python/multimap/runme.py
@@ -0,0 +1,27 @@
+# file: runme.py
+
+import example 
+
+# Call our gcd() function
+
+x = 42
+y = 105
+g = example.gcd(x,y)
+print "The gcd of %d and %d is %d" % (x,y,g)
+
+# Call the gcdmain() function
+example.gcdmain(["gcdmain","42","105"])
+
+# Call the count function
+print example.count("Hello World", "l")
+
+# Call the capitalize function
+
+print example.capitalize("hello world")
+
+
+
+
+
+
+
diff --git a/trunk/Examples/python/operator/Makefile b/trunk/Examples/python/operator/Makefile
new file mode 100644
index 0000000..c455365
--- /dev/null
+++ b/trunk/Examples/python/operator/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/operator/example.h b/trunk/Examples/python/operator/example.h
new file mode 100644
index 0000000..4da6a23
--- /dev/null
+++ b/trunk/Examples/python/operator/example.h
@@ -0,0 +1,36 @@
+/* File : example.h */
+#include <math.h>
+
+class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &operator=(const Complex &c) {
+    rpart = c.rpart;
+    ipart = c.ipart;
+    return *this;
+  }
+  Complex operator+(const Complex &c) const {
+    return Complex(rpart+c.rpart, ipart+c.ipart);
+  }
+  Complex operator-(const Complex &c) const {
+    return Complex(rpart-c.rpart, ipart-c.ipart);
+  }
+  Complex operator*(const Complex &c) const {
+    return Complex(rpart*c.rpart - ipart*c.ipart,
+		   rpart*c.ipart + c.rpart*ipart);
+  }
+  Complex operator-() const {
+    return Complex(-rpart, -ipart);
+  }
+  
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+
+
+
+
+  
diff --git a/trunk/Examples/python/operator/example.i b/trunk/Examples/python/operator/example.i
new file mode 100644
index 0000000..e37e76b
--- /dev/null
+++ b/trunk/Examples/python/operator/example.i
@@ -0,0 +1,28 @@
+/* File : example.i */
+%module example
+#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ
+%{
+#include "example.h"
+%}
+
+/* This header file is a little tough to handle because it has overloaded
+   operators and constructors.  We're going to try and deal with that here */
+
+/* This turns the copy constructor in a function ComplexCopy() that can
+   be called */
+
+%rename(ComplexCopy) Complex::Complex(Complex const &);
+
+/* Now grab the original header file */
+%include "example.h"
+
+/* An output method that turns a complex into a short string */
+%extend Complex {
+   char *__str__() {
+       static char temp[512];
+       sprintf(temp,"(%g,%g)", $self->re(), $self->im());
+       return temp;
+   }
+};
+
+
diff --git a/trunk/Examples/python/operator/runme.py b/trunk/Examples/python/operator/runme.py
new file mode 100644
index 0000000..3687a38
--- /dev/null
+++ b/trunk/Examples/python/operator/runme.py
@@ -0,0 +1,21 @@
+# Operator overloading example
+import example
+
+a = example.Complex(2,3)
+b = example.Complex(-5,10)
+
+print "a   =",a
+print "b   =",b
+
+c = a + b
+print "c   =",c
+print "a*b =",a*b
+print "a-c =",a-c
+
+e = example.ComplexCopy(a-c)
+print "e   =",e
+
+# Big expression
+f = ((a+b)*(c+b*e)) + (-a)
+print "f   =",f
+
diff --git a/trunk/Examples/python/pointer/Makefile b/trunk/Examples/python/pointer/Makefile
new file mode 100644
index 0000000..4a1e1bb
--- /dev/null
+++ b/trunk/Examples/python/pointer/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/pointer/example.c b/trunk/Examples/python/pointer/example.c
new file mode 100644
index 0000000..b877d9a
--- /dev/null
+++ b/trunk/Examples/python/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/python/pointer/example.i b/trunk/Examples/python/pointer/example.i
new file mode 100644
index 0000000..a8ac794
--- /dev/null
+++ b/trunk/Examples/python/pointer/example.i
@@ -0,0 +1,30 @@
+/* File : example.i */
+%module example
+
+%{
+extern void add(int *, int *, int *);
+extern void sub(int *, int *, int *);
+extern int divide(int, int, int *);
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/python/pointer/index.html b/trunk/Examples/python/pointer/index.html
new file mode 100644
index 0000000..ceef305
--- /dev/null
+++ b/trunk/Examples/python/pointer/index.html
@@ -0,0 +1,171 @@
+<html>
+<head>
+<title>SWIG:Examples:python:pointer</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/python/pointer/</tt>
+<hr>
+
+<H2>Simple Pointer Handling</H2>
+
+<p>
+This example illustrates a couple of techniques for handling
+simple pointers in SWIG.  The prototypical example is a C function
+that operates on pointers such as this:
+
+<blockquote>
+<pre>
+void add(int *x, int *y, int *r) { 
+    *r = *x + *y;
+}
+</pre>
+</blockquote>
+
+By default, SWIG wraps this function exactly as specified and creates
+an interface that expects pointer objects for arguments.  The only
+problem is how does one go about creating these objects from a script?
+
+<h2>Possible Solutions</h2>
+
+<ul>
+<li>Write some helper functions to explicitly create objects.  For
+example:
+
+<blockquote>
+<pre>
+int *new_int(int ivalue) {
+  int *i = (int *) malloc(sizeof(ivalue));
+  *i = ivalue;
+  return i;
+}
+int get_int(int *i) {
+  return *i;
+}
+
+void delete_int(int *i) {
+  free(i);
+}
+</pre>
+</blockquote>
+
+Now, in a script you would do this:
+
+<blockquote>
+<pre>
+a = new_int(37)
+b = new_int(42)
+c = new_int(0)
+add(a,b,c)
+r = get_int(c);
+print "Result =",r
+delete_int(a)
+delete_int(b)
+delete_int(c)
+</pre>
+</blockquote>
+
+<p>
+<li>Use the SWIG pointer library.  For example, in the interface file 
+you would do this:
+
+<blockquote>
+<pre>
+%include "pointer.i"
+</pre>
+</blockquote?
+
+and in a script you would do this:
+
+<blockquote>
+<pre>
+a = ptrcreate("int",37)
+b = ptrcreate("int",42)
+c = ptrcreate("int")
+add(a,b,c)
+r = ptrvalue(c)
+print "Result =",r
+ptrfree(a)
+ptrfree(b)
+ptrfree(c)
+</pre>
+</blockquote>
+
+The advantage to using the pointer library is that it unifies some of the helper
+functions behind a common set of names.  For example, the same set of functions work
+with int, double, float, and other fundamental types.
+
+<p>
+<li>Use the SWIG typemap library.  This library allows you to completely
+change the way arguments are processed by SWIG.  For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+void add(int *INPUT, int *INPUT, int *OUTPUT);
+</pre>
+</blockquote>
+
+And in a script:
+
+<blockquote>
+<pre>
+r = add(37,42)
+print "Result =",r
+</pre>
+</blockquote>
+Needless to say, this is substantially easier.
+
+<p>
+<li>A final alternative is to use the typemaps library in combination
+with the %apply directive.  This allows you to change the names of parameters
+that behave as input or output parameters. For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+%apply int *INPUT {int *x, int *y};
+%apply int *OUTPUT {int *r};
+
+void add(int *x, int *y, int *r);
+void sub(int *x, int *y, int *r);
+void mul(int *x, int *y, int *r);
+... etc ...
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>Example</h2>
+
+The following example illustrates the use of these features for pointer
+extraction.
+
+<ul>
+<li> <a href="example.c">example.c</a>  (C Source)
+<li> <a href="example.i">example.i</a>  (Swig interface)
+<li> <a href="example.py">example.py</a> (Python Script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>Since pointers are used for so many different things (arrays, output values,
+etc...) the complexity of pointer handling can be as complicated as you want to
+make it.
+
+<p>
+<li>More documentation on the typemaps.i and pointer.i library files can be
+found in the SWIG user manual.  The files also contain documentation.
+
+<p>
+<li>The pointer.i library is designed primarily for convenience.  If you
+are concerned about performance, you probably want to use a different
+approach.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/pointer/runme.py b/trunk/Examples/python/pointer/runme.py
new file mode 100644
index 0000000..e38a306
--- /dev/null
+++ b/trunk/Examples/python/pointer/runme.py
@@ -0,0 +1,44 @@
+# file: runme.py
+
+import example;
+
+# First create some objects using the pointer library.
+print "Testing the pointer library";
+a = example.new_intp();
+b = example.new_intp();
+c = example.new_intp();
+example.intp_assign(a,37);
+example.intp_assign(b,42);
+
+print "     a =",a
+print "     b =",b
+print "     c =",c
+
+# Call the add() function with some pointers
+example.add(a,b,c)
+
+# Now get the result
+r = example.intp_value(c)
+print "     37 + 42 =",r
+
+# Clean up the pointers
+example.delete_intp(a)
+example.delete_intp(b)
+example.delete_intp(c)
+
+# Now try the typemap library
+# This should be much easier. Now how it is no longer
+# necessary to manufacture pointers.
+
+print "Trying the typemap library";
+r = example.sub(37,42)
+print "     37 - 42 =",r
+
+# Now try the version with multiple return values
+
+print "Testing multiple return values";
+q,r = example.divide(42,37)
+print "     42/37 = %d remainder %d" % (q,r)
+
+
+
diff --git a/trunk/Examples/python/reference/Makefile b/trunk/Examples/python/reference/Makefile
new file mode 100644
index 0000000..f331b82
--- /dev/null
+++ b/trunk/Examples/python/reference/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/reference/example.cxx b/trunk/Examples/python/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/python/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/python/reference/example.h b/trunk/Examples/python/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/python/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/python/reference/example.i b/trunk/Examples/python/reference/example.i
new file mode 100644
index 0000000..8c95b32
--- /dev/null
+++ b/trunk/Examples/python/reference/example.i
@@ -0,0 +1,48 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+%rename(cprint) print;
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/python/reference/index.html b/trunk/Examples/python/reference/index.html
new file mode 100644
index 0000000..25d4029
--- /dev/null
+++ b/trunk/Examples/python/reference/index.html
@@ -0,0 +1,147 @@
+<html>
+<head>
+<title>SWIG:Examples:python:reference</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/reference/</tt>
+<hr>
+
+<H2>C++ Reference Handling</H2>
+
+<p>
+This example tests SWIG's handling of C++ references.  Since C++
+references are closely related to pointers (as both refer to a
+location in memory), SWIG simply collapses all references into
+pointers when creating wrappers.
+
+<h2>Some examples</h2>
+
+References are most commonly used as function parameter.  For example,
+you might have an operator like this:
+
+<blockquote>
+<pre>
+Vector operator+(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+or a function:
+
+<blockquote>
+<pre>
+Vector addv(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+In these cases, SWIG transforms everything into a pointer and creates a wrapper
+that looks like this:
+
+<blockquote>
+<pre>
+Vector wrap_addv(Vector *a, Vector *b) {
+    return addv(*a,*b);
+}
+</pre>
+</blockquote>
+
+Occasionally, a reference is used as a return value of a function
+when the return result is to be used as an lvalue in an expression.
+The prototypical example is an operator like this:
+
+<blockquote>
+<pre>
+Vector &amp;operator[](int index);
+</pre>
+</blockquote>
+
+or a method:
+
+<blockquote>
+<pre>
+Vector &amp;get(int index);
+</pre>
+</blockquote>
+
+For functions returning references, a wrapper like this is created:
+
+<blockquote>
+<pre>
+Vector *wrap_Object_get(Object *self, int index) {
+    Vector &amp;result = self-&gt;get(index);
+    return &amp;result;
+}
+</pre>
+</blockquote>
+
+The following <a href="example.h">header file</a> contains some class
+definitions with some operators and use of references.
+
+<h2>SWIG Interface</h2>
+
+SWIG does NOT support overloaded operators so it can not directly build
+an interface to the classes in the above file.   However, a number of workarounds
+can be made.  For example, an overloaded operator can be stuck behind a function
+call such as the <tt>addv()</tt> function above.  Array access can be handled
+with a pair of set/get functions like this:
+
+<blockquote>
+<pre>
+class VectorArray {
+public:
+ ...
+   %addmethods {
+    Vector &amp;get(int index) {
+      return (*self)[index];
+    }
+    void set(int index, Vector &amp;a) {
+      (*self)[index] = a;
+    }
+   }
+   ...
+}
+</pre>
+</blockquote>
+
+Click <a href="example.i">here</a> to see a SWIG interface file with these additions.
+
+<h2>Sample Python script</h2>
+
+Click <a href="example.py">here</a> to see a script that manipulates some C++ references.
+
+<h2>Notes:</h2>
+
+<ul>
+<li>C++ references primarily provide notational convenience for C++
+source code.  However, Python only supports the 'x.a' 
+notation so it doesn't much matter.
+
+<p>
+<li>When a program returns a reference, a pointer is returned.
+Unlike return by value, memory is not allocated to hold the
+return result.
+
+<p>
+<li>SWIG has particular trouble handling various combinations of references
+and pointers.  This is side effect of an old parsing scheme and
+type representation that will be replaced in future versions.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/reference/runme.py b/trunk/Examples/python/reference/runme.py
new file mode 100644
index 0000000..a1f5336
--- /dev/null
+++ b/trunk/Examples/python/reference/runme.py
@@ -0,0 +1,63 @@
+# file: runme.py
+
+# This file illustrates the manipulation of C++ references in Python
+
+import example
+
+# ----- Object creation -----
+
+print "Creating some objects:"
+a = example.Vector(3,4,5)
+b = example.Vector(10,11,12)
+
+print "    Created",a.cprint()
+print "    Created",b.cprint()
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+print "Adding a+b"
+c = example.addv(a,b)
+print "    a+b =", c.cprint()
+
+# Note: Unless we free the result, a memory leak will occur
+del c
+
+# ----- Create a vector array -----
+
+# Note: Using the high-level interface here
+print "Creating an array of vectors"
+va = example.VectorArray(10)
+print "    va = ",va
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of $a and $b to the vector array
+va.set(0,a)
+va.set(1,b)
+
+va.set(2,example.addv(a,b))
+
+# Get some values from the array
+
+print "Getting some array values"
+for i in range(0,5):
+    print "    va(%d) = %s" % (i, va.get(i).cprint())
+
+# Watch under resource meter to check on this
+print "Making sure we don't leak memory."
+for i in xrange(0,1000000):
+    c = va.get(i % 10)
+
+# ----- Clean up -----
+print "Cleaning up"
+
+del va
+del a
+del b
+
diff --git a/trunk/Examples/python/simple/Makefile b/trunk/Examples/python/simple/Makefile
new file mode 100644
index 0000000..4a1e1bb
--- /dev/null
+++ b/trunk/Examples/python/simple/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/simple/example.c b/trunk/Examples/python/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/python/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/python/simple/example.dsp b/trunk/Examples/python/simple/example.dsp
new file mode 100644
index 0000000..7a32f4d
--- /dev/null
+++ b/trunk/Examples/python/simple/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_example.pyd" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_example.pyd"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -python $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 

+	echo PYTHON_LIB: %PYTHON_LIB% 

+	echo on 

+	..\..\..\swig -python $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/python/simple/example.i b/trunk/Examples/python/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/python/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/python/simple/index.html b/trunk/Examples/python/simple/index.html
new file mode 100644
index 0000000..dace471
--- /dev/null
+++ b/trunk/Examples/python/simple/index.html
@@ -0,0 +1,97 @@
+<html>
+<head>
+<title>SWIG:Examples:python:simple</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/python/simple/</tt>
+<hr>
+
+<H2>Simple Python Example</H2>
+
+<p>
+This example illustrates how you can hook Python to a very simple C program containing
+a function and a global variable.
+
+<h2>The C Code</h2>
+
+Suppose you have the following C code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x &gt; 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+Here is a simple SWIG interface file:
+
+<blockquote>
+<pre>
+/* File: example.i */
+%module example
+
+extern int gcd(int x, int y);
+extern double Foo;
+</pre>
+</blockquote>
+
+<h2>Compilation</h2>
+
+<ol>
+<li><tt>swig -python <a href="example.i">example.i</a></tt>
+<p>
+<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
+to create the extension <tt>examplemodule.so</tt>. 
+</ol>
+
+<h2>Using the extension</h2>
+
+Click <a href="example.py">here</a> to see a script that calls our C functions from Python.
+
+<h2>Key points</h2>
+
+<ul>
+<li>Use the <tt>import</tt> statement to load your extension module from Python. For example:
+<blockquote>
+<pre>
+import example
+</pre>
+</blockquote>
+
+<li>C functions work just like Python functions. For example:
+<blockquote>
+<pre>
+g = example.gcd(42,105)
+</pre>
+</blockquote>
+
+<li>C global variables are accessed through a special variable called 'cvar'. For example:
+<blockquote>
+<pre>
+a = example.cvar.Foo
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/python/simple/runme.py b/trunk/Examples/python/simple/runme.py
new file mode 100644
index 0000000..d484ae9
--- /dev/null
+++ b/trunk/Examples/python/simple/runme.py
@@ -0,0 +1,30 @@
+# file: runme.py
+
+import example 
+
+# Call our gcd() function
+
+x = 42
+y = 105
+g = example.gcd(x,y)
+print "The gcd of %d and %d is %d" % (x,y,g)
+
+# Manipulate the Foo global variable
+
+# Output its current value
+print "Foo = ", example.cvar.Foo
+
+# Change its value
+example.cvar.Foo = 3.1415926
+
+# See if the change took effect
+print "Foo = ", example.cvar.Foo
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/python/smartptr/Makefile b/trunk/Examples/python/smartptr/Makefile
new file mode 100644
index 0000000..58d1396
--- /dev/null
+++ b/trunk/Examples/python/smartptr/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/smartptr/example.cxx b/trunk/Examples/python/smartptr/example.cxx
new file mode 100644
index 0000000..92a3add
--- /dev/null
+++ b/trunk/Examples/python/smartptr/example.cxx
@@ -0,0 +1,31 @@
+/* File : example.c */
+
+#include "example.h"
+#include <math.h>
+#ifndef M_PI
+#  define M_PI 3.14159265358979323846
+#endif
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area() {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter() {
+  return 2*M_PI*radius;
+}
+
+double Square::area() {
+  return width*width;
+}
+
+double Square::perimeter() {
+  return 4*width;
+}
diff --git a/trunk/Examples/python/smartptr/example.h b/trunk/Examples/python/smartptr/example.h
new file mode 100644
index 0000000..c0f9b1d
--- /dev/null
+++ b/trunk/Examples/python/smartptr/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+  
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+
+
+
+  
diff --git a/trunk/Examples/python/smartptr/example.i b/trunk/Examples/python/smartptr/example.i
new file mode 100644
index 0000000..83da4f1
--- /dev/null
+++ b/trunk/Examples/python/smartptr/example.i
@@ -0,0 +1,20 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+#include "smartptr.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Grab smart pointer template */
+
+%include "smartptr.h"
+
+/* Instantiate smart-pointers */
+
+%template(ShapePtr) SmartPtr<Shape>;
+
+
diff --git a/trunk/Examples/python/smartptr/runme.py b/trunk/Examples/python/smartptr/runme.py
new file mode 100644
index 0000000..5ea1fb9
--- /dev/null
+++ b/trunk/Examples/python/smartptr/runme.py
@@ -0,0 +1,55 @@
+# file: runme.py
+
+# This file illustrates the proxy class C++ interface generated
+# by SWIG.
+
+import example 
+
+# ----- Object creation -----
+
+print "Creating some objects:"
+cc = example.Circle(10)
+c = example.ShapePtr(cc)
+print "    Created circle", c
+ss = example.Square(10)
+s = example.ShapePtr(ss)
+print "    Created square", s
+
+# ----- Access a static member -----
+
+print "\nA total of", example.cvar.Shape_nshapes,"shapes were created"
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+
+s.x = -10
+s.y = 5
+
+print "\nHere is their current position:"
+print "    Circle = (%f, %f)" % (c.x,c.y)
+print "    Square = (%f, %f)" % (s.x,s.y)
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:"
+for o in [c,s]:
+      print "   ", o
+      print "        area      = ", o.area()
+      print "        perimeter = ", o.perimeter()
+
+print "\nGuess I'll clean up now"
+
+# Note: this invokes the virtual destructor
+del c
+del s
+del cc
+del ss
+
+s = 3
+print example.cvar.Shape_nshapes,"shapes remain"
+print "Goodbye"
+
diff --git a/trunk/Examples/python/smartptr/smartptr.h b/trunk/Examples/python/smartptr/smartptr.h
new file mode 100644
index 0000000..2ffa1ca
--- /dev/null
+++ b/trunk/Examples/python/smartptr/smartptr.h
@@ -0,0 +1,13 @@
+template<class T> class SmartPtr {
+public:
+   SmartPtr(T *realPtr = 0) { pointee = realPtr; }
+   T *operator->() const {
+       return pointee;
+   }
+   T &operator*() const {
+      return *pointee;
+   }
+private:
+   T *pointee;
+};
+
diff --git a/trunk/Examples/python/std_map/Makefile b/trunk/Examples/python/std_map/Makefile
new file mode 100644
index 0000000..2d4c1b4
--- /dev/null
+++ b/trunk/Examples/python/std_map/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+run:
+	python runme.py
+
+check: all
diff --git a/trunk/Examples/python/std_map/example.h b/trunk/Examples/python/std_map/example.h
new file mode 100644
index 0000000..79ccc64
--- /dev/null
+++ b/trunk/Examples/python/std_map/example.h
@@ -0,0 +1,17 @@
+/* File : example.h */
+
+#include <map>
+#include <string>
+
+template<class Key, class Value>
+std::map<Key,Value> half_map(const std::map<Key,Value>& v) {
+  typedef typename std::map<Key,Value>::const_iterator iter;  
+  std::map<Key,Value> w;
+  for (iter i = v.begin(); i != v.end(); ++i) {
+    w[i->first] = (i->second)/2;
+  }  
+  return w;
+}
+
+
+
diff --git a/trunk/Examples/python/std_map/example.i b/trunk/Examples/python/std_map/example.i
new file mode 100644
index 0000000..36354a8
--- /dev/null
+++ b/trunk/Examples/python/std_map/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include std_string.i
+%include std_pair.i
+%include std_map.i
+
+/* instantiate the required template specializations */
+namespace std {
+  /* remember to instantiate the key,value pair! */
+  %template(DoubleMap) map<std::string,double>;
+  %template() map<std::string,int>;
+}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+%template(halfd) half_map<std::string,double>;
+%template(halfi) half_map<std::string,int>;
+
+
+%template() std::pair<swig::PyObject_ptr, swig::PyObject_ptr>;
+%template(pymap) std::map<swig::PyObject_ptr, swig::PyObject_ptr>;
diff --git a/trunk/Examples/python/std_map/runme.py b/trunk/Examples/python/std_map/runme.py
new file mode 100644
index 0000000..b521c9c
--- /dev/null
+++ b/trunk/Examples/python/std_map/runme.py
@@ -0,0 +1,82 @@
+# file: runme.py
+
+import example
+
+pmap = example.pymap()
+pmap["hi"] = 1
+pmap["hello"] = 2
+
+
+
+
+dmap = {}
+dmap["hello"] = 1.0
+dmap["hi"] = 2.0
+
+print dmap.items()
+print dmap.keys()
+print dmap.values()
+
+print dmap
+hmap = example.halfd(dmap)
+dmap = hmap
+
+print dmap
+for i in dmap.iterkeys():
+    print "key", i
+
+for i in dmap.itervalues():
+    print "val", i
+
+for k,v in dmap.iteritems():
+    print "item", k,v
+
+dmap = example.DoubleMap()
+dmap["hello"] = 1.0
+dmap["hi"] = 2.0
+
+for i in dmap.iterkeys():
+    print "key", i
+
+for i in dmap.itervalues():
+    print "val", i
+
+for k,v in dmap.iteritems():
+    print "item", k,v
+
+
+print dmap.items()
+print dmap.keys()
+print dmap.values()
+
+hmap = example.halfd(dmap)
+print hmap.keys()
+print hmap.values()
+
+
+
+dmap = {}
+dmap["hello"] = 2
+dmap["hi"] = 4
+
+hmap = example.halfi(dmap)
+print hmap
+print hmap.keys()
+print hmap.values()
+
+
+dmap = hmap
+
+for i in dmap.iterkeys():
+    print "key", i
+
+for i in dmap.itervalues():
+    print "val", i
+
+for i in dmap.iteritems():
+    print "item", i
+
+for k,v in dmap.iteritems():
+    print "item", k,v
+
+print dmap
diff --git a/trunk/Examples/python/std_vector/Makefile b/trunk/Examples/python/std_vector/Makefile
new file mode 100644
index 0000000..a4f3343
--- /dev/null
+++ b/trunk/Examples/python/std_vector/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/std_vector/example.h b/trunk/Examples/python/std_vector/example.h
new file mode 100644
index 0000000..4f0dac7
--- /dev/null
+++ b/trunk/Examples/python/std_vector/example.h
@@ -0,0 +1,25 @@
+/* File : example.h */
+
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<double> half(const std::vector<double>& v) {
+    std::vector<double> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    // would you believe this is the same as the above?
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+
diff --git a/trunk/Examples/python/std_vector/example.i b/trunk/Examples/python/std_vector/example.i
new file mode 100644
index 0000000..aa58b66
--- /dev/null
+++ b/trunk/Examples/python/std_vector/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+/* instantiate the required template specializations */
+namespace std {
+    %template(IntVector)    vector<int>;
+    %template(DoubleVector) vector<double>;
+}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/python/std_vector/runme.py b/trunk/Examples/python/std_vector/runme.py
new file mode 100644
index 0000000..d248ccb
--- /dev/null
+++ b/trunk/Examples/python/std_vector/runme.py
@@ -0,0 +1,36 @@
+# file: runme.py
+
+import example
+
+# Call average with a Python list...
+
+print example.average([1,2,3,4])
+
+# ... or a wrapped std::vector<int>
+
+v = example.IntVector(4)
+for i in range(len(v)):
+      v[i] = i+1
+print example.average(v)
+
+
+# half will return a Python list.
+# Call it with a Python tuple...
+
+print example.half((1.0, 1.5, 2.0, 2.5, 3.0))
+
+# ... or a wrapped std::vector<double>
+
+v = example.DoubleVector()
+for i in [1,2,3,4]:
+      v.append(i)
+print example.half(v)
+
+
+# now halve a wrapped std::vector<double> in place
+
+example.halve_in_place(v)
+for i in range(len(v)):
+      print v[i], "; ",
+print
+
diff --git a/trunk/Examples/python/swigrun/Makefile b/trunk/Examples/python/swigrun/Makefile
new file mode 100644
index 0000000..53bf701
--- /dev/null
+++ b/trunk/Examples/python/swigrun/Makefile
@@ -0,0 +1,24 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(SWIG) -python -external-runtime
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+	rm -f swigpyrun.h
+
+check: all
+
diff --git a/trunk/Examples/python/swigrun/example.cxx b/trunk/Examples/python/swigrun/example.cxx
new file mode 100644
index 0000000..25906a5
--- /dev/null
+++ b/trunk/Examples/python/swigrun/example.cxx
@@ -0,0 +1,20 @@
+/* File : example.cxx */
+
+#include <Python.h>
+#include "swigpyrun.h"
+#include "example.h"
+
+
+Manager* convert_to_Manager(PyObject *py_obj)
+{
+  Manager* c_ptr;
+  swig_type_info *ty = SWIG_TypeQuery("Manager *");
+  printf("manager ty %p \n", ty);
+  if (SWIG_ConvertPtr(py_obj, (void **) &c_ptr, ty, 0) == -1) {
+    c_ptr = 0;
+  } else {
+    Py_XINCREF(py_obj);
+  }
+  return c_ptr;
+}
+
diff --git a/trunk/Examples/python/swigrun/example.h b/trunk/Examples/python/swigrun/example.h
new file mode 100644
index 0000000..69e6fe4
--- /dev/null
+++ b/trunk/Examples/python/swigrun/example.h
@@ -0,0 +1,58 @@
+/* File : example.h */
+
+#include <cstdio>
+#include <iostream>
+#include <vector>
+#include <string>
+#include <cmath>
+
+class Employee {
+private:
+	std::string name;
+public:
+	Employee(const char* n): name(n) {}
+	virtual std::string getTitle() { return getPosition() + " " + getName(); }
+	virtual std::string getName() { return name; }
+	virtual std::string getPosition() const { return "Employee"; }
+	virtual ~Employee() { printf("~Employee() @ %p\n", this); }
+};
+
+
+class Manager: public Employee {
+public:
+	Manager(const char* n): Employee(n) {}
+	virtual std::string getPosition() const { return "Manager"; }
+};
+
+
+class EmployeeList {
+	std::vector<Employee*> list;
+public:
+	EmployeeList() {
+		list.push_back(new Employee("Bob"));
+		list.push_back(new Employee("Jane"));
+		list.push_back(new Manager("Ted"));
+	}
+	void addEmployee(Employee *p) {
+		list.push_back(p);
+		std::cout << "New employee added.   Current employees are:" << std::endl;
+		std::vector<Employee*>::iterator i;
+		for (i=list.begin(); i!=list.end(); i++) {
+			std::cout << "  " << (*i)->getTitle() << std::endl;
+		}
+	}
+	const Employee *get_item(int i) {
+		return list[i];
+	}
+	~EmployeeList() { 
+		std::vector<Employee*>::iterator i;
+		std::cout << "~EmployeeList, deleting " << list.size() << " employees." << std::endl;
+		for (i=list.begin(); i!=list.end(); i++) {
+			delete *i;
+		}
+		std::cout << "~EmployeeList empty." << std::endl;
+	}
+};
+
+Manager* convert_to_Manager(PyObject *obj);
+
diff --git a/trunk/Examples/python/swigrun/example.i b/trunk/Examples/python/swigrun/example.i
new file mode 100644
index 0000000..c8ec32e
--- /dev/null
+++ b/trunk/Examples/python/swigrun/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module(directors="1") example
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+%include "std_string.i"
+
+/* turn on director wrapping for Manager */
+%feature("director") Employee;
+%feature("director") Manager;
+
+%include "example.h"
+
diff --git a/trunk/Examples/python/swigrun/runme.py b/trunk/Examples/python/swigrun/runme.py
new file mode 100644
index 0000000..abcd964
--- /dev/null
+++ b/trunk/Examples/python/swigrun/runme.py
@@ -0,0 +1,28 @@
+# file: runme.py
+
+# This file illustrates the cross language polymorphism using directors.
+
+import example 
+
+
+# CEO class, which overrides Employee::getPosition().
+
+class CEO(example.Manager):
+	def __init__(self, name):
+		example.Manager.__init__(self, name)
+	def getPosition(self):
+		return "CEO"
+	def __del__(self):
+		print "CEO.__del__(),", self.getName()
+		# for proxy class extensions that are not "disowned" and
+		# define a __del__ method, it is very important to call the 
+		# base class __del__.  otherwise the c++ objects will never
+		# be deleted.
+		example.Manager.__del__(self)
+
+
+
+
+e = CEO("Alice")
+m = example.convert_to_Manager(e)
+print m
diff --git a/trunk/Examples/python/template/Makefile b/trunk/Examples/python/template/Makefile
new file mode 100644
index 0000000..a4f3343
--- /dev/null
+++ b/trunk/Examples/python/template/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/template/example.h b/trunk/Examples/python/template/example.h
new file mode 100644
index 0000000..7401df6
--- /dev/null
+++ b/trunk/Examples/python/template/example.h
@@ -0,0 +1,32 @@
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %extend {
+    T getitem(int index) {
+      return $self->get(index);
+    }
+    void setitem(int index, T val) {
+      $self->set(index,val);
+    }
+  }
+#endif
+};
+
diff --git a/trunk/Examples/python/template/example.i b/trunk/Examples/python/template/example.i
new file mode 100644
index 0000000..8f94c4d
--- /dev/null
+++ b/trunk/Examples/python/template/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
diff --git a/trunk/Examples/python/template/runme.py b/trunk/Examples/python/template/runme.py
new file mode 100644
index 0000000..05940bc
--- /dev/null
+++ b/trunk/Examples/python/template/runme.py
@@ -0,0 +1,34 @@
+# file: runme.py
+
+import example
+
+# Call some templated functions
+print example.maxint(3,7)
+print example.maxdouble(3.14,2.18)
+
+# Create some class
+
+iv = example.vecint(100)
+dv = example.vecdouble(1000)
+
+for i in range(0,100):
+      iv.setitem(i,2*i)
+
+for i in range(0,1000):
+      dv.setitem(i, 1.0/(i+1))
+
+sum = 0
+for i in range(0,100):
+      sum = sum + iv.getitem(i)
+
+print sum
+
+sum = 0.0
+for i in range(0,1000):
+      sum = sum + dv.getitem(i)
+print sum
+
+del iv
+del dv
+
+      
diff --git a/trunk/Examples/python/varargs/Makefile b/trunk/Examples/python/varargs/Makefile
new file mode 100644
index 0000000..01d0f94
--- /dev/null
+++ b/trunk/Examples/python/varargs/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/varargs/example.i b/trunk/Examples/python/varargs/example.i
new file mode 100644
index 0000000..6cb88f5
--- /dev/null
+++ b/trunk/Examples/python/varargs/example.i
@@ -0,0 +1,65 @@
+/* File : example.i */
+%module example
+
+%{
+#include <stdarg.h>
+%}
+
+/* This example illustrates SWIG's handling of varargs functions.  
+   By default, variable length arguments are simply ignored.  This
+   is generally appropriate for wrapping I/O functions like printf.
+   You can simply format a string in the scripting language, and
+   pass it directly */
+
+int printf(const char *fmt, ...);
+
+/* Since passing a format string might be dangerous.  Here is a slightly
+   different way of wrapping a printf style function */
+
+#if 1
+/* Replace ... with char *.   */
+%varargs(char *) fprintf;
+
+/* Ignore the format string, but set it to %s */
+%typemap(in,numinputs=0) const char *fmt {
+	$1 = "%s";
+}
+#else
+/* An alternative approach using typemaps */
+%typemap(in) (const char *fmt, ...) {
+   $1 = "%s";
+   $2 = (void *) PyString_AsString($input);
+}
+#endif
+
+/* Typemap just to make the example work */
+%typemap(in) FILE * "$1 = PyFile_AsFile($input);";
+
+int fprintf(FILE *, const char *fmt, ...);
+
+/* Here is somewhat different example.  A variable length argument
+   function that takes a NULL-terminated list of arguments. We
+   can use a slightly different form of %varargs that specifies
+   a default value and a maximum number of arguments.
+ */
+
+/* Maximum of 20 arguments with default value NULL */
+
+%varargs(20, char *x = NULL) printv;
+
+%inline %{
+void printv(char *s, ...) {
+    va_list ap;
+    char *x;
+    fputs(s,stdout);
+    fputc(' ',stdout);
+    va_start(ap, s);
+    while ((x = va_arg(ap, char *))) {
+      fputs(x,stdout);
+      fputc(' ',stdout);
+    }
+    va_end(ap);
+    fputc('\n',stdout);
+}
+%}
+
diff --git a/trunk/Examples/python/varargs/runme.py b/trunk/Examples/python/varargs/runme.py
new file mode 100644
index 0000000..a01cb67
--- /dev/null
+++ b/trunk/Examples/python/varargs/runme.py
@@ -0,0 +1,34 @@
+# file: runme.py
+
+import sys
+import example 
+
+# Call printf
+example.printf("Hello World. I'm printf\n")
+
+# Note: We call printf, but use *python* string formatting
+for i in range(0,10):
+    example.printf("i is %d\n" % i)
+
+# This will probably be garbled because %d is interpreted by C
+example.printf("The value is %d\n")
+
+# Call fprintf
+example.fprintf(sys.stdout,"Hello World. I'm fprintf\n")
+for i in range(0,10):
+    example.fprintf(sys.stdout,"i is %d\n" % i)
+
+# This won't be garbled since %d is not interpreted
+example.fprintf(sys.stdout,"The value is %d\n")
+
+# This function calls our NULL-terminated function
+
+example.printv("Hello","World","this","is","a","test.")
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/python/variables/Makefile b/trunk/Examples/python/variables/Makefile
new file mode 100644
index 0000000..4a1e1bb
--- /dev/null
+++ b/trunk/Examples/python/variables/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='mypython' INTERFACE='$(INTERFACE)' python_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/variables/example.c b/trunk/Examples/python/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/python/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/python/variables/example.h b/trunk/Examples/python/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/python/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/python/variables/example.i b/trunk/Examples/python/variables/example.i
new file mode 100644
index 0000000..9d0101c
--- /dev/null
+++ b/trunk/Examples/python/variables/example.i
@@ -0,0 +1,51 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_SWIGTYPELEAK
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/python/variables/index.html b/trunk/Examples/python/variables/index.html
new file mode 100644
index 0000000..2940d8a
--- /dev/null
+++ b/trunk/Examples/python/variables/index.html
@@ -0,0 +1,100 @@
+<html>
+<head>
+<title>SWIG:Examples:python:variables</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/python/variables/</tt>
+<hr>
+
+<H2>Wrapping C Global Variables</H2>
+
+<p>
+When a C global variable appears in an interface file, SWIG tries to
+wrap it using a technique known as "variable linking."  The idea is
+pretty simple---we try to create a Python variable that magically
+retrieves or updates the value of the underlying C variable when it is
+accessed.  Click <a href="example.i">here</a> to see a SWIG interface with some variable
+declarations in it.
+
+<h2>Manipulating Variables from Python</h2>
+
+Before going any further, it is important to understand some important
+differences between C and Python variables.  In C, a variable is
+simply a name that refers to a specific location in memory.  For
+example, when you declare a global variable '<tt>double a</tt>' you
+know that somewhere in memory, 8 bytes have been set aside to hold a
+<tt>double</tt> and that <tt>a</tt> is bound to this location for the
+life of the program.  In Python, variable creation is nothing more
+than a naming operation.  For example, when you say '<tt>a = 3</tt>',
+'a' becomes a name that refers to some object '3'.  Later on, if you say
+'<tt>a = 7.5</tt>, the name 'a' is bound to an entirely different object
+containing the value '7.5' (the contents of the original object are not
+changed).  The end result of this is that a variable in Python can refer
+to a virtually unlimited number of different objects (memory locations)
+over the lifetime of a program.
+
+<p>
+Because of Python's somewhat unusual variable assignment semantics, it is not
+possible to directly link a C global variable into an equivalent Python variable.
+Instead, all C global variables are accessed as attributes of a special object
+called 'cvar'.  For example, if you had a global variable
+
+<blockquote>
+<pre>
+double foo;
+</pre>
+</blockquote>
+
+it will be accessed in the Python module as <tt>cvar.foo</tt>. Click
+<a href="example.py">here</a> to see a script that updates and prints
+out the values of the variables using this technique.
+
+<h2>Key points</h2>
+
+<ul>
+<li>When a global variable has the type "<tt>char *</tt>", SWIG manages it as a character
+string.   However, whenever the value of such a variable is set from Python, the old
+value is destroyed using <tt>free()</tt> or <tt>delete</tt> (the choice of which depends
+on whether or not SWIG was run with the -c++ option).
+<li><tt>signed char</tt> and <tt>unsigned char</tt> are handled as small 8-bit integers.
+<li>String array variables such as '<tt>char name[256]</tt>' are managed as Python strings, but
+when setting the value, the result is truncated to the maximum length of the array.  Furthermore, the string is assumed to be null-terminated.
+<li>When structures and classes are used as global variables, they are mapped into pointers.
+Getting the "value" returns a pointer to the global variable.  Setting the value of a structure results in a memory copy from a pointer to the global.
+</ul>
+
+<h2>Creating read-only variables</h2>
+
+The <tt>%immutable</tt> and <tt>%mutable</tt> directives can be used to
+specify a collection of read-only variables.  For example:
+
+<blockquote>
+<pre>
+%immutable;
+int    status;
+double blah;
+...
+%mutable;
+</pre>
+</blockquote>
+
+The <tt>%immutable</tt> directive remains in effect until it is explicitly disabled
+using the <tt>%mutable</tt> directive.
+
+<h2>Comments</h2>
+<ul>
+<li>Management of global variables is one of the most problematic aspects 
+of C/C++ wrapping because the scripting interface and resulting memory management
+is much trickier than simply creating a wrapper function.
+<p>
+<li>Because of the potential for a namespace conflict, you should not use
+the <tt>from module import *</tt> statement for a SWIG module with global
+variables.  Doing so will cause a collision on the 'cvar' object should 
+more than one module be loaded in this manner.
+</ul>
+
+</body>
+</html>
+<hr>
diff --git a/trunk/Examples/python/variables/runme.py b/trunk/Examples/python/variables/runme.py
new file mode 100644
index 0000000..b635b98
--- /dev/null
+++ b/trunk/Examples/python/variables/runme.py
@@ -0,0 +1,75 @@
+# file: runme.py
+
+import example
+
+# Try to set the values of some global variables
+
+example.cvar.ivar   =  42
+example.cvar.svar   = -31000
+example.cvar.lvar   =  65537
+example.cvar.uivar  =  123456
+example.cvar.usvar  =  61000
+example.cvar.ulvar  =  654321
+example.cvar.scvar  =  -13
+example.cvar.ucvar  =  251
+example.cvar.cvar   =  "S"
+example.cvar.fvar   =  3.14159
+example.cvar.dvar   =  2.1828
+example.cvar.strvar =  "Hello World"
+example.cvar.iptrvar= example.new_int(37)
+example.cvar.ptptr  = example.new_Point(37,42)
+example.cvar.name   = "Bill"
+
+# Now print out the values of the variables
+
+print "Variables (values printed from Python)"
+
+print "ivar      =", example.cvar.ivar
+print "svar      =", example.cvar.svar
+print "lvar      =", example.cvar.lvar
+print "uivar     =", example.cvar.uivar
+print "usvar     =", example.cvar.usvar
+print "ulvar     =", example.cvar.ulvar
+print "scvar     =", example.cvar.scvar
+print "ucvar     =", example.cvar.ucvar
+print "fvar      =", example.cvar.fvar
+print "dvar      =", example.cvar.dvar
+print "cvar      =", example.cvar.cvar
+print "strvar    =", example.cvar.strvar
+print "cstrvar   =", example.cvar.cstrvar
+print "iptrvar   =", example.cvar.iptrvar
+print "name      =", example.cvar.name
+print "ptptr     =", example.cvar.ptptr, example.Point_print(example.cvar.ptptr)
+print "pt        =", example.cvar.pt, example.Point_print(example.cvar.pt)
+
+print "\nVariables (values printed from C)"
+
+example.print_vars()
+
+print "\nNow I'm going to try and modify some read only variables";
+
+print "     Tring to set 'path'";
+try:
+    example.cvar.path = "Whoa!"
+    print "Hey, what's going on?!?! This shouldn't work"
+except:
+    print "Good."
+
+print "     Trying to set 'status'";
+try:
+    example.cvar.status = 0
+    print "Hey, what's going on?!?! This shouldn't work"
+except:
+    print "Good."
+
+
+print "\nI'm going to try and update a structure variable.\n"
+
+example.cvar.pt = example.cvar.ptptr
+
+print "The new value is"
+example.pt_print()
+print "You should see the value", example.Point_print(example.cvar.ptptr)
+
+
+
diff --git a/trunk/Examples/python/weave/Makefile b/trunk/Examples/python/weave/Makefile
new file mode 100644
index 0000000..822779b
--- /dev/null
+++ b/trunk/Examples/python/weave/Makefile
@@ -0,0 +1,21 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f $(TARGET).py
+
+check: all
diff --git a/trunk/Examples/python/weave/README b/trunk/Examples/python/weave/README
new file mode 100644
index 0000000..a616a4f
--- /dev/null
+++ b/trunk/Examples/python/weave/README
@@ -0,0 +1,25 @@
+This directory contains a simple example to test weave support for
+SWIG wrapped objects.
+
+The weave package provides tools for including C/C++ code in Python
+code. This offers both another level of optimization to those who need
+it, and an easy way to modify and extend any supported extension
+libraries.  Weave automatically builds an extension module from the
+given C/C++ code and runs that.  This can result in very significant
+speedups (of upto 500x) depending on the problem.  Weave also supports
+inlining SWIG-1.3.x wrapped objects.
+
+The example in this directory requires that weave be installed.  Weave
+is distributed as part of SciPy (http://www.scipy.org).  More
+information on Weave may be had from here:
+
+ http://www.scipy.org/documentation/weave
+
+As of November 22, 2004, this example only works with weave from CVS.
+If there is a more recent release of SciPy after this date, it should
+work fine.
+
+
+Also, you need to replace the weave file swigptr2.py by the one
+provided here.
+
diff --git a/trunk/Examples/python/weave/example.h b/trunk/Examples/python/weave/example.h
new file mode 100644
index 0000000..d09d608
--- /dev/null
+++ b/trunk/Examples/python/weave/example.h
@@ -0,0 +1,18 @@
+#ifndef _EXAMPLE_H
+#define _EXAMPLE_H
+
+class Foo {
+ public:
+   int x;
+};
+
+class Bar {
+ public:
+   int y;
+};
+
+class FooBar : public Foo, public Bar {
+ public:
+   int z;
+};
+#endif
diff --git a/trunk/Examples/python/weave/example.i b/trunk/Examples/python/weave/example.i
new file mode 100644
index 0000000..5d71eaa
--- /dev/null
+++ b/trunk/Examples/python/weave/example.i
@@ -0,0 +1,15 @@
+%module(directors="1") example
+
+%{
+#include "example.h"
+%}
+
+%include "std_vector.i"
+
+%director Foo;
+%director Bar;
+%include "example.h"
+
+
+%template(VectorBar) std::vector<Bar*>;
+%template(VectorFoo) std::vector<Foo*>;
diff --git a/trunk/Examples/python/weave/runme.py b/trunk/Examples/python/weave/runme.py
new file mode 100644
index 0000000..529b4fc
--- /dev/null
+++ b/trunk/Examples/python/weave/runme.py
@@ -0,0 +1,72 @@
+"""
+Test weave support for SWIG wrapped objects.
+
+This example requires that one has weave installed.  Weave is
+distributed as part of SciPy (http://www.scipy.org).  More information
+on Weave may be had from here:
+
+ http://www.scipy.org/documentation/weave
+
+As of November 22, 2004, this only works with weave from CVS.  If
+there is a more recent release of SciPy after this date, it should
+work fine.
+
+"""
+
+import example
+import weave
+from weave import converters
+from weave import swig2_spec
+
+# Weave does not support swig2 by default (yet).  So add this to the
+# list of default converters to test.
+converters.default.insert(0, swig2_spec.swig2_converter())
+
+def test():
+    """ A simple test case for weave."""
+    a = example.Foo()
+    a.x = 1
+    b = example.Bar()
+    b.y = 2
+    c = example.FooBar()
+    c.x = 1
+    c.y = 2
+    c.z = 3
+    v = example.VectorBar()
+    v.append(b)
+    v.append(c)
+    d = v[0]
+    e = v[1]
+    v = example.VectorFoo()
+    v.append(a)
+    v.append(c)
+    f = v[0]
+    g = v[1]
+    
+    code = """
+    std::cout << a->x << std::endl;
+    assert(a->x == 1);
+    std::cout << b->y << std::endl;
+    assert(b->y == 2);
+    std::cout << c->x << std::endl;
+    std::cout << c->y << std::endl;
+    std::cout << c->z << std::endl;
+    assert(c->x == 1);
+    assert(c->y == 2);
+    assert(c->z == 3);
+    std::cout << d->y << std::endl;
+    assert(d->y == 2);
+    std::cout << e->y << std::endl;
+    assert(e->y == 2);
+    std::cout << f->x << std::endl;
+    assert(f->x == 1);
+    std::cout << g->x << std::endl;
+    assert(g->x == 1);
+    """
+    weave.inline(code, ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
+                 include_dirs=['.'], 
+                 headers=['"example.h"'],
+                 verbose=2)
+    
+if __name__ == "__main__":
+    test()
diff --git a/trunk/Examples/python/weave/swigptr2.py b/trunk/Examples/python/weave/swigptr2.py
new file mode 100644
index 0000000..7ffe0fb
--- /dev/null
+++ b/trunk/Examples/python/weave/swigptr2.py
@@ -0,0 +1,3556 @@
+# This code allows one to use SWIG wrapped objects from weave.  This
+# code is specific to SWIG-1.3 and above where things are different.
+# The code is basically all copied out from the SWIG wrapper code but
+# it has been hand edited for brevity.
+#
+# Prabhu Ramachandran <prabhu@aero.iitm.ernet.in>
+
+######################################################################
+# This is for SWIG-1.3.x where x < 22.
+# Essentially, SWIG_RUNTIME_VERSION was not yet used.
+swigptr2_code_v0 = """
+
+#include "Python.h"
+
+/*************************************************************** -*- c -*-
+ * python/precommon.swg
+ *
+ * Rename all exported symbols from common.swg, to avoid symbol
+ * clashes if multiple interpreters are included
+ *
+ ************************************************************************/
+
+#define SWIG_TypeCheck       SWIG_Python_TypeCheck
+#define SWIG_TypeCast        SWIG_Python_TypeCast
+#define SWIG_TypeName        SWIG_Python_TypeName
+#define SWIG_TypeQuery       SWIG_Python_TypeQuery
+#define SWIG_PackData        SWIG_Python_PackData 
+#define SWIG_UnpackData      SWIG_Python_UnpackData 
+
+
+/***********************************************************************
+ * common.swg
+ *
+ *     This file contains generic SWIG runtime support for pointer
+ *     type checking as well as a few commonly used macros to control
+ *     external linkage.
+ *
+ * Author : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (c) 1999-2000, The University of Chicago
+ * 
+ * This file may be freely redistributed without license or fee provided
+ * this copyright message remains intact.
+ ************************************************************************/
+
+#include <string.h>
+
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#  if defined(_MSC_VER) || defined(__GNUC__)
+#    if defined(STATIC_LINKED)
+#      define SWIGEXPORT(a) a
+#      define SWIGIMPORT(a) extern a
+#    else
+#      define SWIGEXPORT(a) __declspec(dllexport) a
+#      define SWIGIMPORT(a) extern a
+#    endif
+#  else
+#    if defined(__BORLANDC__)
+#      define SWIGEXPORT(a) a _export
+#      define SWIGIMPORT(a) a _export
+#    else
+#      define SWIGEXPORT(a) a
+#      define SWIGIMPORT(a) a
+#    endif
+#  endif
+#else
+#  define SWIGEXPORT(a) a
+#  define SWIGIMPORT(a) a
+#endif
+
+#ifdef SWIG_GLOBAL
+#  define SWIGRUNTIME(a) SWIGEXPORT(a)
+#else
+#  define SWIGRUNTIME(a) static a
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void *(*swig_converter_func)(void *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
+
+typedef struct swig_type_info {
+  const char             *name;
+  swig_converter_func     converter;
+  const char             *str;
+  void                   *clientdata;
+  swig_dycast_func        dcast;
+  struct swig_type_info  *next;
+  struct swig_type_info  *prev;
+} swig_type_info;
+
+#ifdef SWIG_NOINCLUDE
+
+SWIGIMPORT(swig_type_info *) SWIG_TypeCheck(char *c, swig_type_info *);
+SWIGIMPORT(void *)           SWIG_TypeCast(swig_type_info *, void *);
+SWIGIMPORT(const char *)     SWIG_TypeName(const swig_type_info *);
+SWIGIMPORT(swig_type_info *) SWIG_TypeQuery(const char *);
+SWIGIMPORT(char *)           SWIG_PackData(char *, void *, int);
+SWIGIMPORT(char *)           SWIG_UnpackData(char *, void *, int);
+
+#else
+
+static swig_type_info *swig_type_list = 0;
+
+/* Check the typename */
+SWIGRUNTIME(swig_type_info *) 
+SWIG_TypeCheck(char *c, swig_type_info *ty) {
+  swig_type_info *s;
+  if (!ty) return 0;        /* Void pointer */
+  s = ty->next;             /* First element always just a name */
+  do {
+    if (strcmp(s->name,c) == 0) {
+      if (s == ty->next) return s;
+      /* Move s to the top of the linked list */
+      s->prev->next = s->next;
+      if (s->next) {
+        s->next->prev = s->prev;
+      }
+      /* Insert s as second element in the list */
+      s->next = ty->next;
+      if (ty->next) ty->next->prev = s;
+      ty->next = s;
+      s->prev = ty;
+      return s;
+    }
+    s = s->next;
+  } while (s && (s != ty->next));
+  return 0;
+}
+
+/* Cast a pointer up an inheritance hierarchy */
+SWIGRUNTIME(void *) 
+SWIG_TypeCast(swig_type_info *ty, void *ptr) {
+  if ((!ty) || (!ty->converter)) return ptr;
+  return (*ty->converter)(ptr);
+}
+
+/* Return the name associated with this type */
+SWIGRUNTIME(const char *)
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
+
+/* 
+   Compare two type names skipping the space characters, therefore
+   "char*" == "char *" and "Class<int>" == "Class<int >", etc.
+
+   Return 0 when the two name types are equivalent, as in
+   strncmp, but skipping ' '.
+*/
+static int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+		  const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return *f1 - *f2;
+  }
+  return (l1 - f1) - (l2 - f2);
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+*/
+static int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = SWIG_TypeNameComp(nb, ne, tb, te) == 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+  
+
+/* Search for a swig_type_info structure */
+SWIGRUNTIME(swig_type_info *)
+SWIG_TypeQuery(const char *name) {
+  swig_type_info *ty = swig_type_list;
+  while (ty) {
+    if (ty->str && (SWIG_TypeEquiv(ty->str,name))) return ty;
+    if (ty->name && (strcmp(name,ty->name) == 0)) return ty;
+    ty = ty->prev;
+  }
+  return 0;
+}
+
+/* Pack binary data into a string */
+SWIGRUNTIME(char *)
+SWIG_PackData(char *c, void *ptr, int sz) {
+  static char hex[17] = "0123456789abcdef";
+  int i;
+  unsigned char *u = (unsigned char *) ptr;
+  register unsigned char uu;
+  for (i = 0; i < sz; i++,u++) {
+    uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+
+/* Unpack binary data from a string */
+SWIGRUNTIME(char *)
+SWIG_UnpackData(char *c, void *ptr, int sz) {
+  register unsigned char uu = 0;
+  register int d;
+  unsigned char *u = (unsigned char *) ptr;
+  int i;
+  for (i = 0; i < sz; i++, u++) {
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu = ((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = ((d - ('a'-10)) << 4);
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (d - ('a'-10));
+    *u = uu;
+  }
+  return c;
+}
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/***********************************************************************
+ * python.swg
+ *
+ *     This file contains the runtime support for Python modules
+ *     and includes code for managing global variables and pointer
+ *     type checking.
+ *
+ * Author : David Beazley (beazley@cs.uchicago.edu)
+ ************************************************************************/
+
+#include "Python.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define SWIG_PY_INT     1
+#define SWIG_PY_FLOAT   2
+#define SWIG_PY_STRING  3
+#define SWIG_PY_POINTER 4
+#define SWIG_PY_BINARY  5
+
+/* Flags for pointer conversion */
+
+#define SWIG_POINTER_EXCEPTION     0x1
+#define SWIG_POINTER_DISOWN        0x2
+
+/* Exception handling in wrappers */
+#define SWIG_fail   goto fail
+
+/* Constant information structure */
+typedef struct swig_const_info {
+    int type;
+    char *name;
+    long lvalue;
+    double dvalue;
+    void   *pvalue;
+    swig_type_info **ptype;
+} swig_const_info;
+
+/* Common SWIG API */
+#define SWIG_ConvertPtr(obj, pp, type, flags) \
+  SWIG_Python_ConvertPtr(obj, pp, type, flags)
+#define SWIG_NewPointerObj(p, type, flags) \
+  SWIG_Python_NewPointerObj(p, type, flags)
+#define SWIG_MustGetPtr(p, type, argnum, flags) \
+  SWIG_Python_MustGetPtr(p, type, argnum, flags)
+ 
+
+typedef double (*py_objasdbl_conv)(PyObject *obj);
+
+#ifdef SWIG_NOINCLUDE
+
+SWIGIMPORT(int)               SWIG_Python_ConvertPtr(PyObject *, void **, swig_type_info *, int);
+SWIGIMPORT(PyObject *)        SWIG_Python_NewPointerObj(void *, swig_type_info *,int own);
+SWIGIMPORT(void *)            SWIG_Python_MustGetPtr(PyObject *, swig_type_info *, int, int);
+
+#else
+
+
+/* Convert a pointer value */
+SWIGRUNTIME(int)
+SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
+  swig_type_info *tc;
+  char  *c = 0;
+  static PyObject *SWIG_this = 0;
+  int    newref = 0;
+  PyObject  *pyobj = 0;
+
+  if (!obj) return 0;
+  if (obj == Py_None) {
+    *ptr = 0;
+    return 0;
+  }
+#ifdef SWIG_COBJECT_TYPES
+  if (!(PyCObject_Check(obj))) {
+    if (!SWIG_this)
+      SWIG_this = PyString_FromString("this");
+    pyobj = obj;
+    obj = PyObject_GetAttr(obj,SWIG_this);
+    newref = 1;
+    if (!obj) goto type_error;
+    if (!PyCObject_Check(obj)) {
+      Py_DECREF(obj);
+      goto type_error;
+    }
+  }  
+  *ptr = PyCObject_AsVoidPtr(obj);
+  c = (char *) PyCObject_GetDesc(obj);
+  if (newref) Py_DECREF(obj);
+  goto cobject;
+#else
+  if (!(PyString_Check(obj))) {
+    if (!SWIG_this)
+      SWIG_this = PyString_FromString("this");
+    pyobj = obj;
+    obj = PyObject_GetAttr(obj,SWIG_this);
+    newref = 1;
+    if (!obj) goto type_error;
+    if (!PyString_Check(obj)) {
+      Py_DECREF(obj);
+      goto type_error;
+    }
+  } 
+  c = PyString_AsString(obj);
+  /* Pointer values must start with leading underscore */
+  if (*c != '_') {
+    *ptr = (void *) 0;
+    if (strcmp(c,"NULL") == 0) {
+      if (newref) { Py_DECREF(obj); }
+      return 0;
+    } else {
+      if (newref) { Py_DECREF(obj); }
+      goto type_error;
+    }
+  }
+  c++;
+  c = SWIG_UnpackData(c,ptr,sizeof(void *));
+  if (newref) { Py_DECREF(obj); }
+#endif
+
+#ifdef SWIG_COBJECT_TYPES
+cobject:
+#endif
+
+  if (ty) {
+    tc = SWIG_TypeCheck(c,ty);
+    if (!tc) goto type_error;
+    *ptr = SWIG_TypeCast(tc,(void*) *ptr);
+  }
+
+  if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
+    PyObject *zero = PyInt_FromLong(0);
+    PyObject_SetAttrString(pyobj,(char*)"thisown",zero);
+    Py_DECREF(zero);
+  }
+  return 0;
+
+type_error:
+  PyErr_Clear();
+  if (flags & SWIG_POINTER_EXCEPTION) {
+    if (ty && c) {
+      PyErr_Format(PyExc_TypeError, 
+		   "Type error. Got %s, expected %s",
+		   c, ty->name);
+    } else {
+      PyErr_SetString(PyExc_TypeError,"Expected a pointer");
+    }
+  }
+  return -1;
+}
+
+/* Convert a pointer value, signal an exception on a type mismatch */
+SWIGRUNTIME(void *)
+SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
+  void *result;
+  SWIG_Python_ConvertPtr(obj, &result, ty, flags | SWIG_POINTER_EXCEPTION);
+  return result;
+}
+
+/* Create a new pointer object */
+SWIGRUNTIME(PyObject *)
+SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int own) {
+  PyObject *robj;
+  if (!ptr) {
+    Py_INCREF(Py_None);
+    return Py_None;
+  }
+#ifdef SWIG_COBJECT_TYPES
+  robj = PyCObject_FromVoidPtrAndDesc((void *) ptr, (char *) type->name, NULL);
+#else
+  {
+    char result[1024];
+    char *r = result;
+    *(r++) = '_';
+    r = SWIG_PackData(r,&ptr,sizeof(void *));
+    strcpy(r,type->name);
+    robj = PyString_FromString(result);
+  }
+#endif
+  if (!robj || (robj == Py_None)) return robj;
+  if (type->clientdata) {
+    PyObject *inst;
+    PyObject *args = Py_BuildValue((char*)"(O)", robj);
+    Py_DECREF(robj);
+    inst = PyObject_CallObject((PyObject *) type->clientdata, args);
+    Py_DECREF(args);
+    if (inst) {
+      if (own) {
+        PyObject *n = PyInt_FromLong(1);
+        PyObject_SetAttrString(inst,(char*)"thisown",n);
+        Py_DECREF(n);
+      }
+      robj = inst;
+    }
+  }
+  return robj;
+}
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+"""
+
+
+######################################################################
+# This is for SWIG-1.3.x where x >= 23.
+# SWIG_RUNTIME_VERSION == "1"
+
+# All this does is to include (cut/paste): <swigrun.swg>
+# <python/pyrun.swg> and <runtime.swg>
+swigptr2_code_v1 = """
+/***********************************************************************
+ * swigrun.swg
+ *
+ *     This file contains generic CAPI SWIG runtime support for pointer
+ *     type checking.
+ *
+ ************************************************************************/
+
+/* This should only be incremented when either the layout of swig_type_info changes,
+   or for whatever reason, the runtime changes incompatibly */
+#define SWIG_RUNTIME_VERSION "1"
+
+/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
+#ifdef SWIG_TYPE_TABLE
+#define SWIG_QUOTE_STRING(x) #x
+#define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
+#define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
+#else
+#define SWIG_TYPE_TABLE_NAME
+#endif
+
+#include <string.h>
+
+#ifndef SWIGINLINE
+#if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
+#  define SWIGINLINE inline
+#else
+#  define SWIGINLINE
+#endif
+#endif
+
+/*
+  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
+  creating a static or dynamic library from the swig runtime code.
+  In 99.9% of the cases, swig just needs to declare them as 'static'.
+  
+  But only do this if is strictly necessary, ie, if you have problems
+  with your compiler or so.
+*/
+#ifndef SWIGRUNTIME
+#define SWIGRUNTIME static
+#endif
+#ifndef SWIGRUNTIMEINLINE
+#define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void *(*swig_converter_func)(void *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
+
+typedef struct swig_type_info {
+  const char             *name;
+  swig_converter_func     converter;
+  const char             *str;
+  void                   *clientdata;
+  swig_dycast_func        dcast;
+  struct swig_type_info  *next;
+  struct swig_type_info  *prev;
+} swig_type_info;
+
+/* 
+  Compare two type names skipping the space characters, therefore
+  "char*" == "char *" and "Class<int>" == "Class<int >", etc.
+
+  Return 0 when the two name types are equivalent, as in
+  strncmp, but skipping ' '.
+*/
+SWIGRUNTIME int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+		  const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return *f1 - *f2;
+  }
+  return (l1 - f1) - (l2 - f2);
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+*/
+SWIGRUNTIME int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = SWIG_TypeNameComp(nb, ne, tb, te) == 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+/*
+  Register a type mapping with the type-checking
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeRegisterTL(swig_type_info **tl, swig_type_info *ti) {
+  swig_type_info *tc, *head, *ret, *next;
+  /* Check to see if this type has already been registered */
+  tc = *tl;
+  while (tc) {
+    /* check simple type equivalence */
+    int typeequiv = (strcmp(tc->name, ti->name) == 0);   
+    /* check full type equivalence, resolving typedefs */
+    if (!typeequiv) {
+      /* only if tc is not a typedef (no '|' on it) */
+      if (tc->str && ti->str && !strstr(tc->str,"|")) {
+	typeequiv = SWIG_TypeEquiv(ti->str,tc->str);
+      }
+    }
+    if (typeequiv) {
+      /* Already exists in the table.  Just add additional types to the list */
+      if (ti->clientdata) tc->clientdata = ti->clientdata;
+      head = tc;
+      next = tc->next;
+      goto l1;
+    }
+    tc = tc->prev;
+  }
+  head = ti;
+  next = 0;
+
+  /* Place in list */
+  ti->prev = *tl;
+  *tl = ti;
+
+  /* Build linked lists */
+  l1:
+  ret = head;
+  tc = ti + 1;
+  /* Patch up the rest of the links */
+  while (tc->name) {
+    head->next = tc;
+    tc->prev = head;
+    head = tc;
+    tc++;
+  }
+  if (next) next->prev = head;
+  head->next = next;
+
+  return ret;
+}
+
+/*
+  Check the typename
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeCheck(const char *c, swig_type_info *ty) {
+  swig_type_info *s;
+  if (!ty) return 0;        /* Void pointer */
+  s = ty->next;             /* First element always just a name */
+  do {
+    if (strcmp(s->name,c) == 0) {
+      if (s == ty->next) return s;
+      /* Move s to the top of the linked list */
+      s->prev->next = s->next;
+      if (s->next) {
+        s->next->prev = s->prev;
+      }
+      /* Insert s as second element in the list */
+      s->next = ty->next;
+      if (ty->next) ty->next->prev = s;
+      ty->next = s;
+      s->prev = ty;
+      return s;
+    }
+    s = s->next;
+  } while (s && (s != ty->next));
+  return 0;
+}
+
+/*
+  Cast a pointer up an inheritance hierarchy
+*/
+SWIGRUNTIMEINLINE void *
+SWIG_TypeCast(swig_type_info *ty, void *ptr) {
+  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr);
+}
+
+/* 
+   Dynamic pointer casting. Down an inheritance hierarchy
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
+  swig_type_info *lastty = ty;
+  if (!ty || !ty->dcast) return ty;
+  while (ty && (ty->dcast)) {
+    ty = (*ty->dcast)(ptr);
+    if (ty) lastty = ty;
+  }
+  return lastty;
+}
+
+/*
+  Return the name associated with this type
+*/
+SWIGRUNTIMEINLINE const char *
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
+
+/*
+  Return the pretty name associated with this type,
+  that is an unmangled type name in a form presentable to the user.
+*/
+SWIGRUNTIME const char *
+SWIG_TypePrettyName(const swig_type_info *type) {
+  /* The "str" field contains the equivalent pretty names of the
+     type, separated by vertical-bar characters.  We choose
+     to print the last name, as it is often (?) the most
+     specific. */
+  if (type->str != NULL) {
+    const char *last_name = type->str;
+    const char *s;
+    for (s = type->str; *s; s++)
+      if (*s == '|') last_name = s+1;
+    return last_name;
+  }
+  else
+    return type->name;
+}
+
+/*
+  Search for a swig_type_info structure
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeQueryTL(swig_type_info *tl, const char *name) {
+  swig_type_info *ty = tl;
+  while (ty) {
+    if (ty->str && (SWIG_TypeEquiv(ty->str,name))) return ty;
+    if (ty->name && (strcmp(name,ty->name) == 0)) return ty;
+    ty = ty->prev;
+  }
+  return 0;
+}
+
+/* 
+   Set the clientdata field for a type
+*/
+SWIGRUNTIME void
+SWIG_TypeClientDataTL(swig_type_info *tl, swig_type_info *ti, void *clientdata) {
+  swig_type_info *tc, *equiv;
+  if (ti->clientdata) return;
+  /* if (ti->clientdata == clientdata) return; */
+  ti->clientdata = clientdata;
+  equiv = ti->next;
+  while (equiv) {
+    if (!equiv->converter) {
+      tc = tl;
+      while (tc) {
+        if ((strcmp(tc->name, equiv->name) == 0))
+          SWIG_TypeClientDataTL(tl,tc,clientdata);
+        tc = tc->prev;
+      }
+    }
+    equiv = equiv->next;
+  }
+}
+
+/* 
+   Pack binary data into a string
+*/
+SWIGRUNTIME char *
+SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static char hex[17] = "0123456789abcdef";
+  unsigned char *u = (unsigned char *) ptr;
+  const unsigned char *eu =  u + sz;
+  register unsigned char uu;
+  for (; u != eu; ++u) {
+    uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+
+/* 
+   Unpack binary data from a string
+*/
+SWIGRUNTIME const char *
+SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  register unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    register int d = *(c++);
+    register unsigned char uu = 0;
+    if ((d >= '0') && (d <= '9'))
+      uu = ((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = ((d - ('a'-10)) << 4);
+    else 
+      return (char *) 0;
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (d - ('a'-10));
+    else 
+      return (char *) 0;
+    *u = uu;
+  }
+  return c;
+}
+
+/*
+  This function will propagate the clientdata field of type to any new
+  swig_type_info structures that have been added into the list of
+  equivalent types.  It is like calling SWIG_TypeClientData(type,
+  clientdata) a second time.
+*/
+SWIGRUNTIME void
+SWIG_PropagateClientDataTL(swig_type_info *tl, swig_type_info *type) {
+  swig_type_info *equiv = type->next;
+  swig_type_info *tc;
+  if (!type->clientdata) return;
+  while (equiv) {
+    if (!equiv->converter) {
+      tc = tl;
+      while (tc) {
+        if ((strcmp(tc->name, equiv->name) == 0) && !tc->clientdata)
+          SWIG_TypeClientDataTL(tl,tc, type->clientdata);
+        tc = tc->prev;
+      }
+    }
+    equiv = equiv->next;
+  }
+}
+
+/* 
+   Pack 'void *' into a string buffer.
+*/
+SWIGRUNTIME char *
+SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+  char *r = buff;
+  if ((2*sizeof(void *) + 2) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,&ptr,sizeof(void *));
+  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
+  strcpy(r,name);
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      *ptr = (void *) 0;
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sizeof(void *));
+}
+
+SWIGRUNTIME char *
+SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+  char *r = buff;
+  size_t lname = (name ? strlen(name) : 0);
+  if ((2*sz + 2 + lname) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  if (lname) {
+    strncpy(r,name,lname+1);
+  } else {
+    *r = 0;
+  }
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      memset(ptr,0,sz);
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sz);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/***********************************************************************
+ * pyrun.swg
+ *
+ *     This file contains the runtime support for Python modules
+ *     and includes code for managing global variables and pointer
+ *     type checking.
+ *
+ * Author : David Beazley (beazley@cs.uchicago.edu)
+ ************************************************************************/
+
+/* Common SWIG API */
+#define SWIG_ConvertPtr(obj, pp, type, flags)    SWIG_Python_ConvertPtr(obj, pp, type, flags)
+#define SWIG_NewPointerObj(p, type, flags)       SWIG_Python_NewPointerObj(p, type, flags)
+#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)
+ 
+
+/* Python-specific SWIG API */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty, flags)   SWIG_Python_ConvertPacked(obj, ptr, sz, ty, flags)
+#define SWIG_NewPackedObj(ptr, sz, type)              SWIG_Python_NewPackedObj(ptr, sz, type)
+
+
+/* -----------------------------------------------------------------------------
+ * Pointer declarations
+ * ----------------------------------------------------------------------------- */
+/*
+  Use SWIG_NO_COBJECT_TYPES to force the use of strings to represent
+  C/C++ pointers in the python side. Very useful for debugging, but
+  not always safe.
+*/
+#if !defined(SWIG_NO_COBJECT_TYPES) && !defined(SWIG_COBJECT_TYPES)
+#  define SWIG_COBJECT_TYPES
+#endif
+
+/* Flags for pointer conversion */
+#define SWIG_POINTER_EXCEPTION     0x1
+#define SWIG_POINTER_DISOWN        0x2
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Create a new pointer string 
+ * ----------------------------------------------------------------------------- */
+
+#ifndef SWIG_BUFFER_SIZE
+#define SWIG_BUFFER_SIZE 1024
+#endif
+
+#if defined(SWIG_COBJECT_TYPES)
+#if !defined(SWIG_COBJECT_PYTHON)
+/* -----------------------------------------------------------------------------
+ * Implements a simple Swig Object type, and use it instead of PyCObject
+ * ----------------------------------------------------------------------------- */
+
+typedef struct {
+  PyObject_HEAD
+  void *ptr;
+  const char *desc;
+} PySwigObject;
+
+/* Declarations for objects of type PySwigObject */
+
+SWIGRUNTIME int
+PySwigObject_print(PySwigObject *v, FILE *fp, int flags)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result))) {
+    fputs("<Swig Object at ", fp); fputs(result, fp); fputs(">", fp);
+    return 0; 
+  } else {
+    return 1; 
+  }
+}
+  
+SWIGRUNTIME PyObject *
+PySwigObject_repr(PySwigObject *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  return SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result)) ?
+    PyString_FromFormat("<Swig Object at %s>", result) : 0;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_str(PySwigObject *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  return SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result)) ?
+    PyString_FromString(result) : 0;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_long(PySwigObject *v)
+{
+  return PyLong_FromUnsignedLong((unsigned long) v->ptr);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_oct(PySwigObject *v)
+{
+  char buf[100];
+  unsigned long x = (unsigned long)v->ptr;
+  if (x == 0)
+    strcpy(buf, "0");
+  else
+    PyOS_snprintf(buf, sizeof(buf), "0%lo", x);
+  return PyString_FromString(buf);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_hex(PySwigObject *v)
+{
+  char buf[100];
+  PyOS_snprintf(buf, sizeof(buf), "0x%lx", (unsigned long)v->ptr);
+  return PyString_FromString(buf);
+}
+
+SWIGRUNTIME int
+PySwigObject_compare(PySwigObject *v, PySwigObject *w)
+{
+  int c = strcmp(v->desc, w->desc);
+  if (c) {
+    return c;
+  } else {
+    void *i = v->ptr;
+    void *j = w->ptr;
+    return (i < j) ? -1 : (i > j) ? 1 : 0;
+  }
+}
+
+SWIGRUNTIME void
+PySwigObject_dealloc(PySwigObject *self)
+{
+  PyObject_DEL(self);
+}
+
+SWIGRUNTIME PyTypeObject*
+PySwigObject_GetType() {
+  static char PySwigObject_Type__doc__[] = 
+    "Swig object carries a C/C++ instance pointer";
+  
+  static PyNumberMethods PySwigObject_as_number = {
+    (binaryfunc)0, /*nb_add*/
+    (binaryfunc)0, /*nb_subtract*/
+    (binaryfunc)0, /*nb_multiply*/
+    (binaryfunc)0, /*nb_divide*/
+    (binaryfunc)0, /*nb_remainder*/
+    (binaryfunc)0, /*nb_divmod*/
+    (ternaryfunc)0,/*nb_power*/
+    (unaryfunc)0,  /*nb_negative*/
+    (unaryfunc)0,  /*nb_positive*/
+    (unaryfunc)0,  /*nb_absolute*/
+    (inquiry)0,    /*nb_nonzero*/
+    0,		   /*nb_invert*/
+    0,		   /*nb_lshift*/
+    0,		   /*nb_rshift*/
+    0,		   /*nb_and*/
+    0,		   /*nb_xor*/
+    0,		   /*nb_or*/
+    (coercion)0,   /*nb_coerce*/
+    (unaryfunc)PySwigObject_long, /*nb_int*/
+    (unaryfunc)PySwigObject_long, /*nb_long*/
+    (unaryfunc)0,                 /*nb_float*/
+    (unaryfunc)PySwigObject_oct,  /*nb_oct*/
+    (unaryfunc)PySwigObject_hex,  /*nb_hex*/
+#if PY_VERSION_HEX >= 0x02000000
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ 
+#endif
+  };
+
+  static PyTypeObject PySwigObject_Type = {
+    PyObject_HEAD_INIT(&PyType_Type)
+    0,					/*ob_size*/
+    "PySwigObject",			/*tp_name*/
+    sizeof(PySwigObject),		/*tp_basicsize*/
+    0,					/*tp_itemsize*/
+    /* methods */
+    (destructor)PySwigObject_dealloc,	/*tp_dealloc*/
+    (printfunc)PySwigObject_print,	/*tp_print*/
+    (getattrfunc)0,			/*tp_getattr*/
+    (setattrfunc)0,			/*tp_setattr*/
+    (cmpfunc)PySwigObject_compare,	/*tp_compare*/
+    (reprfunc)PySwigObject_repr,	/*tp_repr*/
+    &PySwigObject_as_number,	        /*tp_as_number*/
+    0,					/*tp_as_sequence*/
+    0,					/*tp_as_mapping*/
+    (hashfunc)0,			/*tp_hash*/
+    (ternaryfunc)0,			/*tp_call*/
+    (reprfunc)PySwigObject_str,		/*tp_str*/
+    /* Space for future expansion */
+    0L,0L,0L,0L,
+    PySwigObject_Type__doc__, 	        /* Documentation string */
+#if PY_VERSION_HEX >= 0x02000000
+    0,                                  /* tp_traverse */
+    0,                                  /* tp_clear */
+#endif
+#if PY_VERSION_HEX >= 0x02010000
+    0,                                  /* tp_richcompare */
+    0,                                  /* tp_weaklistoffset */
+#endif
+#if PY_VERSION_HEX >= 0x02020000
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+    0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+    0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+  };
+
+  return &PySwigObject_Type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_FromVoidPtrAndDesc(void *ptr, const char *desc)
+{
+  PySwigObject *self = PyObject_NEW(PySwigObject, PySwigObject_GetType());
+  if (self == NULL) return NULL;
+  self->ptr = ptr;
+  self->desc = desc;
+  return (PyObject *)self;
+}
+
+SWIGRUNTIMEINLINE void *
+PySwigObject_AsVoidPtr(PyObject *self)
+{
+  return ((PySwigObject *)self)->ptr;
+}
+
+SWIGRUNTIMEINLINE const char *
+PySwigObject_GetDesc(PyObject *self)
+{
+  return ((PySwigObject *)self)->desc;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigObject_Check(PyObject *op) {
+  return ((op)->ob_type == PySwigObject_GetType()) 
+    || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0);
+}
+
+/* -----------------------------------------------------------------------------
+ * Implements a simple Swig Packed type, and use it instead of string
+ * ----------------------------------------------------------------------------- */
+
+typedef struct {
+  PyObject_HEAD
+  void *pack;
+  const char *desc;
+  size_t size;
+} PySwigPacked;
+
+SWIGRUNTIME int
+PySwigPacked_print(PySwigPacked *v, FILE *fp, int flags)
+{
+  char result[SWIG_BUFFER_SIZE];
+  fputs("<Swig Packed ", fp); 
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    fputs("at ", fp); 
+    fputs(result, fp); 
+  }
+  fputs(v->desc,fp); 
+  fputs(">", fp);
+  return 0; 
+}
+  
+SWIGRUNTIME PyObject *
+PySwigPacked_repr(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    return PyString_FromFormat("<Swig Packed at %s%s>", result, v->desc);
+  } else {
+    return PyString_FromFormat("<Swig Packed %s>", v->desc);
+  }  
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_str(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
+    return PyString_FromFormat("%s%s", result, v->desc);
+  } else {
+    return PyString_FromFormat("%s", v->desc);
+  }  
+}
+
+SWIGRUNTIME int
+PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)
+{
+  int c = strcmp(v->desc, w->desc);
+  if (c) {
+    return c;
+  } else {
+    size_t i = v->size;
+    size_t j = w->size;
+    int s = (i < j) ? -1 : (i > j) ? 1 : 0;
+    return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);
+  }
+}
+
+SWIGRUNTIME void
+PySwigPacked_dealloc(PySwigPacked *self)
+{
+  free(self->pack);
+  PyObject_DEL(self);
+}
+
+SWIGRUNTIME PyTypeObject*
+PySwigPacked_GetType() {
+  static char PySwigPacked_Type__doc__[] = 
+    "Swig object carries a C/C++ instance pointer";
+  
+  static PyTypeObject PySwigPacked_Type = {
+    PyObject_HEAD_INIT(&PyType_Type)
+    0,					/*ob_size*/
+    "PySwigPacked",			/*tp_name*/
+    sizeof(PySwigPacked),		/*tp_basicsize*/
+    0,					/*tp_itemsize*/
+    /* methods */
+    (destructor)PySwigPacked_dealloc,	/*tp_dealloc*/
+    (printfunc)PySwigPacked_print,	/*tp_print*/
+    (getattrfunc)0,			/*tp_getattr*/
+    (setattrfunc)0,			/*tp_setattr*/
+    (cmpfunc)PySwigPacked_compare,	/*tp_compare*/
+    (reprfunc)PySwigPacked_repr,	/*tp_repr*/
+    0,	                                /*tp_as_number*/
+    0,					/*tp_as_sequence*/
+    0,					/*tp_as_mapping*/
+    (hashfunc)0,			/*tp_hash*/
+    (ternaryfunc)0,			/*tp_call*/
+    (reprfunc)PySwigPacked_str,		/*tp_str*/
+    /* Space for future expansion */
+    0L,0L,0L,0L,
+    PySwigPacked_Type__doc__, 	        /* Documentation string */
+#if PY_VERSION_HEX >= 0x02000000
+    0,                                  /* tp_traverse */
+    0,                                  /* tp_clear */
+#endif
+#if PY_VERSION_HEX >= 0x02010000
+    0,                                  /* tp_richcompare */
+    0,                                  /* tp_weaklistoffset */
+#endif
+#if PY_VERSION_HEX >= 0x02020000         
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+    0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+    0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+  };
+
+  return &PySwigPacked_Type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_FromDataAndDesc(void *ptr, size_t size, const char *desc)
+{
+  PySwigPacked *self = PyObject_NEW(PySwigPacked, PySwigPacked_GetType());
+  if (self == NULL) {
+    return NULL;
+  } else {
+    void *pack = malloc(size);
+    memcpy(pack, ptr, size);
+    self->pack = pack;
+    self->desc = desc;
+    self->size = size;
+    return (PyObject *) self;
+  }
+}
+
+SWIGRUNTIMEINLINE const char *
+PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
+{
+  PySwigPacked *self = (PySwigPacked *)obj;
+  if (self->size != size) return 0;
+  memcpy(ptr, self->pack, size);
+  return self->desc;
+}
+
+SWIGRUNTIMEINLINE const char *
+PySwigPacked_GetDesc(PyObject *self)
+{
+  return ((PySwigPacked *)self)->desc;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigPacked_Check(PyObject *op) {
+  return ((op)->ob_type == PySwigPacked_GetType()) 
+    || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0);
+}
+
+#else
+/* -----------------------------------------------------------------------------
+ * Use the old Python PyCObject instead of PySwigObject
+ * ----------------------------------------------------------------------------- */
+
+#define PySwigObject_GetDesc(obj)	           PyCObject_GetDesc(obj)
+#define PySwigObject_Check(obj)	           PyCObject_Check(obj)
+#define PySwigObject_AsVoidPtr(obj)	   PyCObject_AsVoidPtr(obj)
+#define PySwigObject_FromVoidPtrAndDesc(p, d)  PyCObject_FromVoidPtrAndDesc(p, d, NULL)
+
+#endif
+
+#endif
+
+/* -----------------------------------------------------------------------------
+ * errors manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIME void
+SWIG_Python_TypeError(const char *type, PyObject *obj)
+{
+  if (type) {
+#if defined(SWIG_COBJECT_TYPES)
+    if (PySwigObject_Check(obj)) {
+      const char *otype = (const char *) PySwigObject_GetDesc(obj);
+      if (otype) {
+	PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received",
+		     type, otype);
+	return;
+      }
+    } else 
+#endif      
+    {
+      const char *otype = (obj ? obj->ob_type->tp_name : 0); 
+      if (otype) {
+	PyObject *str = PyObject_Str(obj);
+	const char *cstr = str ? PyString_AsString(str) : 0;
+	if (cstr) {
+	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
+		       type, otype, cstr);
+	} else {
+	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
+		       type, otype);
+	}
+	Py_DECREF(str);
+	return;
+      }
+    }   
+    PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
+  } else {
+    PyErr_Format(PyExc_TypeError, "unexpected type is received");
+  }
+}
+
+SWIGRUNTIMEINLINE void
+SWIG_Python_NullRef(const char *type)
+{
+  if (type) {
+    PyErr_Format(PyExc_TypeError, "null reference of type '%s' was received",type);
+  } else {
+    PyErr_Format(PyExc_TypeError, "null reference was received");
+  }
+}
+
+SWIGRUNTIME int
+SWIG_Python_AddErrMesg(const char* mesg, int infront)
+{
+  if (PyErr_Occurred()) {
+    PyObject *type = 0;
+    PyObject *value = 0;
+    PyObject *traceback = 0;
+    PyErr_Fetch(&type, &value, &traceback);
+    if (value) {
+      PyObject *old_str = PyObject_Str(value);
+      Py_XINCREF(type);
+      PyErr_Clear();
+      if (infront) {
+	PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
+      } else {
+	PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
+      }
+      Py_DECREF(old_str);
+    }
+    return 1;
+  } else {
+    return 0;
+  }
+}
+
+SWIGRUNTIME int
+SWIG_Python_ArgFail(int argnum)
+{
+  if (PyErr_Occurred()) {
+    /* add information about failing argument */
+    char mesg[256];
+    sprintf(mesg, "argument number %d:", argnum);
+    return SWIG_Python_AddErrMesg(mesg, 1);
+  } else {
+    return 0;
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+/* Convert a pointer value */
+SWIGRUNTIME int
+SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
+  swig_type_info *tc;
+  const char *c = 0;
+  static PyObject *SWIG_this = 0;
+  int    newref = 0;
+  PyObject  *pyobj = 0;
+  void *vptr;
+  
+  if (!obj) return 0;
+  if (obj == Py_None) {
+    *ptr = 0;
+    return 0;
+  }
+
+#ifdef SWIG_COBJECT_TYPES
+  if (!(PySwigObject_Check(obj))) {
+    if (!SWIG_this)
+      SWIG_this = PyString_FromString("this");
+    pyobj = obj;
+    obj = PyObject_GetAttr(obj,SWIG_this);
+    newref = 1;
+    if (!obj) goto type_error;
+    if (!PySwigObject_Check(obj)) {
+      Py_DECREF(obj);
+      goto type_error;
+    }
+  }  
+  vptr = PySwigObject_AsVoidPtr(obj);
+  c = (const char *) PySwigObject_GetDesc(obj);
+  if (newref) { Py_DECREF(obj); }
+  goto type_check;
+#else
+  if (!(PyString_Check(obj))) {
+    if (!SWIG_this)
+      SWIG_this = PyString_FromString("this");
+    pyobj = obj;
+    obj = PyObject_GetAttr(obj,SWIG_this);
+    newref = 1;
+    if (!obj) goto type_error;
+    if (!PyString_Check(obj)) {
+      Py_DECREF(obj);
+      goto type_error;
+    }
+  } 
+  c = PyString_AS_STRING(obj);
+  /* Pointer values must start with leading underscore */
+  c = SWIG_UnpackVoidPtr(c, &vptr, ty->name);
+  if (newref) { Py_DECREF(obj); }
+  if (!c) goto type_error;
+#endif
+
+type_check:
+
+  if (ty) {
+    tc = SWIG_TypeCheck(c,ty);
+    if (!tc) goto type_error;
+    *ptr = SWIG_TypeCast(tc,vptr);
+  }
+
+  if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
+    PyObject_SetAttrString(pyobj,(char*)"thisown",Py_False);
+  }
+  return 0;
+
+type_error:
+  PyErr_Clear();
+  if (pyobj && !obj) {    
+    obj = pyobj;
+    if (PyCFunction_Check(obj)) {
+      /* here we get the method pointer for callbacks */
+      char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
+      c = doc ? strstr(doc, "swig_ptr: ") : 0;
+      if (c) {
+	c = SWIG_UnpackVoidPtr(c + 10, &vptr, ty->name);
+	if (!c) goto type_error;
+	goto type_check;
+      }
+    }
+  }
+  if (flags & SWIG_POINTER_EXCEPTION) {
+    if (ty) {
+      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+    } else {
+      SWIG_Python_TypeError("C/C++ pointer", obj);
+    }
+  }
+  return -1;
+}
+
+/* Convert a pointer value, signal an exception on a type mismatch */
+SWIGRUNTIME void *
+SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
+  void *result;
+  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
+    PyErr_Clear();
+    if (flags & SWIG_POINTER_EXCEPTION) {
+      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+      SWIG_Python_ArgFail(argnum);
+    }
+  }
+  return result;
+}
+
+/* Convert a packed value value */
+SWIGRUNTIME int
+SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty, int flags) {
+  swig_type_info *tc;
+  const char *c = 0;
+
+#if defined(SWIG_COBJECT_TYPES) && !defined(SWIG_COBJECT_PYTHON)
+  c = PySwigPacked_UnpackData(obj, ptr, sz);
+#else
+  if ((!obj) || (!PyString_Check(obj))) goto type_error;
+  c = PyString_AS_STRING(obj);
+  /* Pointer values must start with leading underscore */
+  c = SWIG_UnpackDataName(c, ptr, sz, ty->name);
+#endif
+  if (!c) goto type_error;
+  if (ty) {
+    tc = SWIG_TypeCheck(c,ty);
+    if (!tc) goto type_error;
+  }
+  return 0;
+
+type_error:
+  PyErr_Clear();
+  if (flags & SWIG_POINTER_EXCEPTION) {
+    if (ty) {
+      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+    } else {
+      SWIG_Python_TypeError("C/C++ packed data", obj);
+    }
+  }
+  return -1;
+}  
+
+/* Create a new array object */
+SWIGRUNTIME PyObject *
+SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int own) {
+  PyObject *robj = 0;
+  if (!ptr) {
+    Py_INCREF(Py_None);
+    return Py_None;
+  }
+#ifdef SWIG_COBJECT_TYPES
+  robj = PySwigObject_FromVoidPtrAndDesc((void *) ptr, (char *)type->name);
+#else
+  {
+    char result[SWIG_BUFFER_SIZE];
+    robj = SWIG_PackVoidPtr(result, ptr, type->name, sizeof(result)) ?
+      PyString_FromString(result) : 0;
+  }
+#endif
+  if (!robj || (robj == Py_None)) return robj;
+  if (type->clientdata) {
+    PyObject *inst;
+    PyObject *args = Py_BuildValue((char*)"(O)", robj);
+    Py_DECREF(robj);
+    inst = PyObject_CallObject((PyObject *) type->clientdata, args);
+    Py_DECREF(args);
+    if (inst) {
+      if (own) {
+        PyObject_SetAttrString(inst,(char*)"thisown",Py_True);
+      }
+      robj = inst;
+    }
+  }
+  return robj;
+}
+
+SWIGRUNTIME PyObject *
+SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  PyObject *robj = 0;
+  if (!ptr) {
+    Py_INCREF(Py_None);
+    return Py_None;
+  }
+#if defined(SWIG_COBJECT_TYPES) && !defined(SWIG_COBJECT_PYTHON)
+  robj = PySwigPacked_FromDataAndDesc((void *) ptr, sz, (char *)type->name);
+#else
+  {
+    char result[SWIG_BUFFER_SIZE];
+    robj = SWIG_PackDataName(result, ptr, sz, type->name, sizeof(result)) ?
+      PyString_FromString(result) : 0;
+  }
+#endif
+  return robj;
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Get type list 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_LINK_RUNTIME
+void *SWIG_ReturnGlobalTypeList(void *);
+#endif
+
+SWIGRUNTIME swig_type_info **
+SWIG_Python_GetTypeListHandle() {
+  static void *type_pointer = (void *)0;
+  /* first check if module already created */
+  if (!type_pointer) {
+#ifdef SWIG_LINK_RUNTIME
+    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
+#else
+    type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+				    (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      type_pointer = (void *)0;
+    }
+  }
+#endif
+  return (swig_type_info **) type_pointer;
+}
+
+/*
+  Search for a swig_type_info structure
+ */
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_Python_GetTypeList() {
+  swig_type_info **tlh = SWIG_Python_GetTypeListHandle();
+  return tlh ? *tlh : (swig_type_info*)0;
+}
+
+#define SWIG_Runtime_GetTypeList SWIG_Python_GetTypeList 
+
+#ifdef __cplusplus
+}
+#endif
+
+/* -----------------------------------------------------------------------------*
+   Standard SWIG API for use inside user code.
+ 
+   You need to include in your code as follow:
+
+#include <Python.h>            // or using your favorite language 
+#include <swigrun.swg>
+#include <python/pyrun.swg>    // or using your favorite language 
+#include <runtime.swg>
+ 
+ * -----------------------------------------------------------------------------*/
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_Runtime_TypeQuery(const char *name) {
+  swig_type_info *tl = SWIG_Runtime_GetTypeList();
+  return SWIG_TypeQueryTL(tl, name);
+}
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_Runtime_TypeRegister(swig_type_info *ti) {
+  swig_type_info *tl = SWIG_Runtime_GetTypeList();
+  return SWIG_TypeRegisterTL(&tl, ti);
+}
+
+SWIGRUNTIMEINLINE void
+SWIG_Runtime_TypeClientData(swig_type_info *ti, void *clientdata) {
+  swig_type_info *tl = SWIG_Runtime_GetTypeList();
+  SWIG_TypeClientDataTL(tl, ti, clientdata);
+}
+
+SWIGRUNTIMEINLINE void
+SWIG_Runtime_PropagateClientData(swig_type_info *type) {
+  swig_type_info *tl = SWIG_Runtime_GetTypeList();
+  SWIG_PropagateClientDataTL(tl, type);
+}
+
+#define SWIG_GetTypeList()            SWIG_Runtime_GetTypeList()
+#define SWIG_TypeQuery(name)          SWIG_Runtime_TypeQuery(name)
+#define SWIG_TypeRegister(ti)         SWIG_Runtime_TypeRegister(ti)
+#define SWIG_TypeClientData(ti, cd)   SWIG_Runtime_TypeClientData(ti, cd)
+#define SWIG_PropagateClientData(ti)  SWIG_Runtime_PropagateClientData(ti)
+
+"""
+
+######################################################################
+# This is for SWIG-1.3.x where x >= 25.
+# SWIG_RUNTIME_VERSION == "2"
+
+# All this does is to include the contents of the file generated by
+# this command:
+#   swig -python -external-runtime
+swigptr2_code_v2 = """
+/* ----------------------------------------------------------------------------
+ * This file was automatically generated by SWIG (http://www.swig.org).
+ * Version 1.3.28
+ * 
+ * This file is not intended to be easily readable and contains a number of 
+ * coding conventions designed to improve portability and efficiency. Do not make
+ * changes to this file unless you know what you are doing--modify the SWIG 
+ * interface file instead. 
+ * ----------------------------------------------------------------------------- */
+
+/***********************************************************************
+ *
+ *  This section contains generic SWIG labels for method/variable
+ *  declarations/attributes, and other compiler dependent labels.
+ *
+ ************************************************************************/
+
+/* template workaround for compilers that cannot correctly implement the C++ standard */
+#ifndef SWIGTEMPLATEDISAMBIGUATOR
+# if defined(__SUNPRO_CC)
+#   if (__SUNPRO_CC <= 0x560)
+#     define SWIGTEMPLATEDISAMBIGUATOR template
+#   else
+#     define SWIGTEMPLATEDISAMBIGUATOR 
+#   endif
+# else
+#   define SWIGTEMPLATEDISAMBIGUATOR 
+# endif
+#endif
+
+/* inline attribute */
+#ifndef SWIGINLINE
+# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
+#   define SWIGINLINE inline
+# else
+#   define SWIGINLINE
+# endif
+#endif
+
+/* attribute recognised by some compilers to avoid 'unused' warnings */
+#ifndef SWIGUNUSED
+# if defined(__GNUC__)
+#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+#     define SWIGUNUSED __attribute__ ((__unused__)) 
+#   else
+#     define SWIGUNUSED
+#   endif
+# elif defined(__ICC)
+#   define SWIGUNUSED __attribute__ ((__unused__)) 
+# else
+#   define SWIGUNUSED 
+# endif
+#endif
+
+#ifndef SWIGUNUSEDPARM
+# ifdef __cplusplus
+#   define SWIGUNUSEDPARM(p)
+# else
+#   define SWIGUNUSEDPARM(p) p SWIGUNUSED 
+# endif
+#endif
+
+/* internal SWIG method */
+#ifndef SWIGINTERN
+# define SWIGINTERN static SWIGUNUSED
+#endif
+
+/* internal inline SWIG method */
+#ifndef SWIGINTERNINLINE
+# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
+#endif
+
+/* exporting methods for Windows DLLs */
+#ifndef SWIGEXPORT
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   if defined(STATIC_LINKED)
+#     define SWIGEXPORT
+#   else
+#     define SWIGEXPORT __declspec(dllexport)
+#   endif
+# else
+#   define SWIGEXPORT
+# endif
+#endif
+
+/* calling conventions for Windows */
+#ifndef SWIGSTDCALL
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   define SWIGSTDCALL __stdcall
+# else
+#   define SWIGSTDCALL
+# endif 
+#endif
+
+
+/*  Errors in SWIG */
+#define  SWIG_UnknownError    	   -1 
+#define  SWIG_IOError        	   -2 
+#define  SWIG_RuntimeError   	   -3 
+#define  SWIG_IndexError     	   -4 
+#define  SWIG_TypeError      	   -5 
+#define  SWIG_DivisionByZero 	   -6 
+#define  SWIG_OverflowError  	   -7 
+#define  SWIG_SyntaxError    	   -8 
+#define  SWIG_ValueError     	   -9 
+#define  SWIG_SystemError    	   -10
+#define  SWIG_AttributeError 	   -11
+#define  SWIG_MemoryError    	   -12 
+#define  SWIG_NullReferenceError   -13
+
+
+
+/***********************************************************************
+ * swigrun.swg
+ *
+ *     This file contains generic CAPI SWIG runtime support for pointer
+ *     type checking.
+ *
+ ************************************************************************/
+
+/* This should only be incremented when either the layout of swig_type_info changes,
+   or for whatever reason, the runtime changes incompatibly */
+#define SWIG_RUNTIME_VERSION "2"
+
+/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
+#ifdef SWIG_TYPE_TABLE
+# define SWIG_QUOTE_STRING(x) #x
+# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
+# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
+#else
+# define SWIG_TYPE_TABLE_NAME
+#endif
+
+/*
+  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
+  creating a static or dynamic library from the swig runtime code.
+  In 99.9% of the cases, swig just needs to declare them as 'static'.
+  
+  But only do this if is strictly necessary, ie, if you have problems
+  with your compiler or so.
+*/
+
+#ifndef SWIGRUNTIME
+# define SWIGRUNTIME SWIGINTERN
+#endif
+
+#ifndef SWIGRUNTIMEINLINE
+# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
+#endif
+
+/*  Generic buffer size */
+#ifndef SWIG_BUFFER_SIZE
+# define SWIG_BUFFER_SIZE 1024
+#endif
+
+/* Flags for pointer conversions */
+#define SWIG_POINTER_DISOWN        0x1
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_OWN           0x1
+
+
+/* 
+   Flags/methods for returning states.
+   
+   The swig conversion methods, as ConvertPtr, return and integer 
+   that tells if the conversion was successful or not. And if not,
+   an error code can be returned (see swigerrors.swg for the codes).
+   
+   Use the following macros/flags to set or process the returning
+   states.
+   
+   In old swig versions, you usually write code as:
+
+     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
+       // success code
+     } else {
+       //fail code
+     }
+
+   Now you can be more explicit as:
+
+    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+    } else {
+      // fail code
+    }
+
+   that seems to be the same, but now you can also do
+
+    Type *ptr;
+    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+      if (SWIG_IsNewObj(res) {
+        ...
+	delete *ptr;
+      } else {
+        ...
+      }
+    } else {
+      // fail code
+    }
+    
+   I.e., now SWIG_ConvertPtr can return new objects and you can
+   identify the case and take care of the deallocation. Of course that
+   requires also to SWIG_ConvertPtr to return new result values, as
+
+      int SWIG_ConvertPtr(obj, ptr,...) {         
+        if (<obj is ok>) {			       
+          if (<need new object>) {		       
+            *ptr = <ptr to new allocated object>; 
+            return SWIG_NEWOBJ;		       
+          } else {				       
+            *ptr = <ptr to old object>;	       
+            return SWIG_OLDOBJ;		       
+          } 				       
+        } else {				       
+          return SWIG_BADOBJ;		       
+        }					       
+      }
+
+   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
+   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
+   swig errors code.
+
+   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
+   allows to return the 'cast rank', for example, if you have this
+
+       int food(double)
+       int fooi(int);
+
+   and you call
+ 
+      food(1)   // cast rank '1'  (1 -> 1.0)
+      fooi(1)   // cast rank '0'
+
+   just use the SWIG_AddCast()/SWIG_CheckState()
+
+
+ */
+#define SWIG_OK                    (0) 
+#define SWIG_ERROR                 (-1)
+#define SWIG_IsOK(r)               (r >= 0)
+
+/* The CastRankLimit says how many bits are used for the cast rank */
+#define SWIG_CASTRANKLIMIT         (1 << 8)
+/* The NewMask denotes the object was created (using new/malloc) */
+#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
+/* The TmpMask is for in/out typemaps that use temporal objects */
+#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
+/* Simple returning values */
+#define SWIG_BADOBJ                (SWIG_ERROR)
+#define SWIG_OLDOBJ                (SWIG_OK)
+#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
+#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
+/* Check, add and del mask methods */
+#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
+#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
+#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
+#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
+#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
+#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
+
+
+/* Cast-Rank Mode */
+#if defined(SWIG_CASTRANK_MODE)
+#  ifndef SWIG_TypeRank
+#    define SWIG_TypeRank             unsigned long
+#  endif
+#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
+#    define SWIG_MAXCASTRANK          (2)
+#  endif
+#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
+#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
+SWIGINTERNINLINE int SWIG_AddCast(int r) { 
+  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
+}
+SWIGINTERNINLINE int SWIG_CheckState(int r) { 
+  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; 
+}
+#else /* no cast-rank mode */
+#  define SWIG_AddCast
+#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
+#endif
+
+
+
+
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void *(*swig_converter_func)(void *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
+
+/* Structure to store inforomation on one type */
+typedef struct swig_type_info {
+  const char             *name;			/* mangled name of this type */
+  const char             *str;			/* human readable name of this type */
+  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
+  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
+  void                   *clientdata;		/* language specific type data */
+  int                    owndata;		/* flag if the structure owns the clientdata */
+} swig_type_info;
+
+/* Structure to store a type and conversion function used for casting */
+typedef struct swig_cast_info {
+  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
+  swig_converter_func     converter;		/* function to cast the void pointers */
+  struct swig_cast_info  *next;			/* pointer to next cast in linked list */
+  struct swig_cast_info  *prev;			/* pointer to the previous cast */
+} swig_cast_info;
+
+/* Structure used to store module information
+ * Each module generates one structure like this, and the runtime collects
+ * all of these structures and stores them in a circularly linked list.*/
+typedef struct swig_module_info {
+  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
+  size_t                 size;		        /* Number of types in this module */
+  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
+  swig_type_info         **type_initial;	/* Array of initially generated type structures */
+  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
+  void                    *clientdata;		/* Language specific module data */
+} swig_module_info;
+
+/* 
+  Compare two type names skipping the space characters, therefore
+  "char*" == "char *" and "Class<int>" == "Class<int >", etc.
+
+  Return 0 when the two name types are equivalent, as in
+  strncmp, but skipping ' '.
+*/
+SWIGRUNTIME int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+		  const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return (int)(*f1 - *f2);
+  }
+  return (l1 - f1) - (l2 - f2);
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if not equal, 1 if equal
+*/
+SWIGRUNTIME int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
+*/
+SWIGRUNTIME int
+SWIG_TypeCompare(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+
+/* think of this as a c++ template<> or a scheme macro */
+#define SWIG_TypeCheck_Template(comparison, ty)         \
+  if (ty) {                                             \
+    swig_cast_info *iter = ty->cast;                    \
+    while (iter) {                                      \
+      if (comparison) {                                 \
+        if (iter == ty->cast) return iter;              \
+        /* Move iter to the top of the linked list */   \
+        iter->prev->next = iter->next;                  \
+        if (iter->next)                                 \
+          iter->next->prev = iter->prev;                \
+        iter->next = ty->cast;                          \
+        iter->prev = 0;                                 \
+        if (ty->cast) ty->cast->prev = iter;            \
+        ty->cast = iter;                                \
+        return iter;                                    \
+      }                                                 \
+      iter = iter->next;                                \
+    }                                                   \
+  }                                                     \
+  return 0
+
+/*
+  Check the typename
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheck(const char *c, swig_type_info *ty) {
+  SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);
+}
+
+/* Same as previous function, except strcmp is replaced with a pointer comparison */
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {
+  SWIG_TypeCheck_Template(iter->type == from, into);
+}
+
+/*
+  Cast a pointer up an inheritance hierarchy
+*/
+SWIGRUNTIMEINLINE void *
+SWIG_TypeCast(swig_cast_info *ty, void *ptr) {
+  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr);
+}
+
+/* 
+   Dynamic pointer casting. Down an inheritance hierarchy
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
+  swig_type_info *lastty = ty;
+  if (!ty || !ty->dcast) return ty;
+  while (ty && (ty->dcast)) {
+    ty = (*ty->dcast)(ptr);
+    if (ty) lastty = ty;
+  }
+  return lastty;
+}
+
+/*
+  Return the name associated with this type
+*/
+SWIGRUNTIMEINLINE const char *
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
+
+/*
+  Return the pretty name associated with this type,
+  that is an unmangled type name in a form presentable to the user.
+*/
+SWIGRUNTIME const char *
+SWIG_TypePrettyName(const swig_type_info *type) {
+  /* The "str" field contains the equivalent pretty names of the
+     type, separated by vertical-bar characters.  We choose
+     to print the last name, as it is often (?) the most
+     specific. */
+  if (!type) return NULL;
+  if (type->str != NULL) {
+    const char *last_name = type->str;
+    const char *s;
+    for (s = type->str; *s; s++)
+      if (*s == '|') last_name = s+1;
+    return last_name;
+  }
+  else
+    return type->name;
+}
+
+/* 
+   Set the clientdata field for a type
+*/
+SWIGRUNTIME void
+SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
+  swig_cast_info *cast = ti->cast;
+  /* if (ti->clientdata == clientdata) return; */
+  ti->clientdata = clientdata;
+  
+  while (cast) {
+    if (!cast->converter) {
+      swig_type_info *tc = cast->type;
+      if (!tc->clientdata) {
+	SWIG_TypeClientData(tc, clientdata);
+      }
+    }    
+    cast = cast->next;
+  }
+}
+SWIGRUNTIME void
+SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
+  SWIG_TypeClientData(ti, clientdata);
+  ti->owndata = 1;
+}
+  
+/*
+  Search for a swig_type_info structure only by mangled name
+  Search is a O(log #types)
+  
+  We start searching at module start, and finish searching when start == end.  
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_MangledTypeQueryModule(swig_module_info *start, 
+                            swig_module_info *end, 
+		            const char *name) {
+  swig_module_info *iter = start;
+  do {
+    if (iter->size) {
+      register size_t l = 0;
+      register size_t r = iter->size - 1;
+      do {
+	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
+	register size_t i = (l + r) >> 1; 
+	const char *iname = iter->types[i]->name;
+	if (iname) {
+	  register int compare = strcmp(name, iname);
+	  if (compare == 0) {	    
+	    return iter->types[i];
+	  } else if (compare < 0) {
+	    if (i) {
+	      r = i - 1;
+	    } else {
+	      break;
+	    }
+	  } else if (compare > 0) {
+	    l = i + 1;
+	  }
+	} else {
+	  break; /* should never happen */
+	}
+      } while (l <= r);
+    }
+    iter = iter->next;
+  } while (iter != end);
+  return 0;
+}
+
+/*
+  Search for a swig_type_info structure for either a mangled name or a human readable name.
+  It first searches the mangled names of the types, which is a O(log #types)
+  If a type is not found it then searches the human readable names, which is O(#types).
+  
+  We start searching at module start, and finish searching when start == end.  
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeQueryModule(swig_module_info *start, 
+                     swig_module_info *end, 
+		     const char *name) {
+  /* STEP 1: Search the name field using binary search */
+  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
+  if (ret) {
+    return ret;
+  } else {
+    /* STEP 2: If the type hasn't been found, do a complete search
+       of the str field (the human readable name) */
+    swig_module_info *iter = start;
+    do {
+      register size_t i = 0;
+      for (; i < iter->size; ++i) {
+	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
+	  return iter->types[i];
+      }
+      iter = iter->next;
+    } while (iter != end);
+  }
+  
+  /* neither found a match */
+  return 0;
+}
+
+/* 
+   Pack binary data into a string
+*/
+SWIGRUNTIME char *
+SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static const char hex[17] = "0123456789abcdef";
+  register const unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    register unsigned char uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+
+/* 
+   Unpack binary data from a string
+*/
+SWIGRUNTIME const char *
+SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  register unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu = u + sz;
+  for (; u != eu; ++u) {
+    register char d = *(c++);
+    register unsigned char uu;
+    if ((d >= '0') && (d <= '9'))
+      uu = ((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = ((d - ('a'-10)) << 4);
+    else 
+      return (char *) 0;
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (d - ('a'-10));
+    else 
+      return (char *) 0;
+    *u = uu;
+  }
+  return c;
+}
+
+/* 
+   Pack 'void *' into a string buffer.
+*/
+SWIGRUNTIME char *
+SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+  char *r = buff;
+  if ((2*sizeof(void *) + 2) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,&ptr,sizeof(void *));
+  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
+  strcpy(r,name);
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      *ptr = (void *) 0;
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sizeof(void *));
+}
+
+SWIGRUNTIME char *
+SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+  char *r = buff;
+  size_t lname = (name ? strlen(name) : 0);
+  if ((2*sz + 2 + lname) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  if (lname) {
+    strncpy(r,name,lname+1);
+  } else {
+    *r = 0;
+  }
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      memset(ptr,0,sz);
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sz);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/***********************************************************************
+ * pyrun.swg
+ *
+ *     This file contains the runtime support for Python modules
+ *     and includes code for managing global variables and pointer
+ *     type checking.
+ *
+ * Author : David Beazley (beazley@cs.uchicago.edu)
+ ************************************************************************/
+
+/* Common SWIG API */
+
+/* for raw pointers */
+#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(ptr, type, flags)
+#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) 
+#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)
+#define swig_owntype                                    int
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)
+
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(ptr, type, 0)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule()
+#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)
+#define SWIG_NewClientData(obj)                         PySwigClientData_New(obj)
+
+/* A functor is a function object with one single object argument */
+#if PY_VERSION_HEX >= 0x02020000
+#define SWIG_Python_CallFunctor(functor, obj)	        PyObject_CallFunctionObjArgs(functor, obj, NULL);
+#else
+#define SWIG_Python_CallFunctor(functor, obj)	        PyObject_CallFunction(functor, "O", obj);
+#endif
+
+/* Error manipulation */
+#define SWIG_SetErrorObj(type, obj)            		{SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(type, obj); SWIG_PYTHON_THREAD_END_BLOCK; }
+#define SWIG_SetErrorMsg(type, msg)            		{SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(type, msg); SWIG_PYTHON_THREAD_END_BLOCK; }
+#define SWIG_ErrorType(code)                            SWIG_Python_ErrorType(code)                       
+#define SWIG_Error(code, msg)            		SWIG_SetErrorMsg(SWIG_Python_ErrorType(code), msg)
+#define SWIG_fail                        		goto fail					   
+
+
+/*
+  Helper for static pointer initialization for both C and C++ code, for example
+  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);
+*/
+#ifdef __cplusplus
+#define SWIG_STATIC_POINTER(var)  var
+#else
+#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Pointer declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)
+#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)
+
+#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)
+
+/* For backward compatibility only */
+#define SWIG_POINTER_EXCEPTION  0
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* cc-mode */
+#endif
+#endif
+
+/*  Safe Py_None and Py_Void accessors */
+
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+# ifndef SWIG_PYTHON_NO_SAFE_NONE
+#  ifndef SWIG_PYTHON_SAFE_NONE
+#   define SWIG_PYTHON_SAFE_NONE
+#  endif
+# endif
+#endif
+
+#ifdef SWIG_PYTHON_SAFE_NONE
+SWIGRUNTIMEINLINE PyObject * 
+_SWIG_Py_None(void)
+{
+  PyObject *none = Py_BuildValue("");
+  Py_DECREF(none);
+  return none;
+}
+SWIGRUNTIME PyObject * 
+SWIG_Py_None(void)
+{
+  static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None();
+  return none;
+}
+#  ifdef Py_None
+#    undef Py_None
+#    define Py_None SWIG_Py_None()
+#  endif
+#endif
+
+SWIGRUNTIMEINLINE PyObject * 
+SWIG_Py_Void(void)
+{
+  PyObject *none = Py_None;
+  Py_INCREF(none);
+  return none;
+}
+
+/* Append a value to the result obj */
+
+SWIGINTERN PyObject*
+SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) {
+  if (!result) {
+    result = obj;
+  } else if (result == Py_None) {
+    Py_DECREF(result);
+    result = obj;
+  } else {
+    if (!PyList_Check(result)) {
+      PyObject *o2 = result;
+      result = PyList_New(1);
+      PyList_SetItem(result, 0, o2);
+    }
+    PyList_Append(result,obj);
+    Py_DECREF(obj);
+  }
+  return result;
+}
+
+SWIGINTERN int
+SWIG_Python_UnpackTuple(PyObject *args, const char *name, int min, int max, PyObject **objs)
+{    
+  if (!PyTuple_Check(args)) {
+    PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple");
+    return 0;
+  } else {
+    register int l = PyTuple_GET_SIZE(args);
+    if (l < min) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+		   name, (min == max ? "" : "at least "), min, l);
+      return 0;
+    } else if (l > max) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+		   name, (min == max ? "" : "at most "), max, l);
+      return 0;
+    } else {
+      register int i;
+      for (i = 0; i < l; ++i) {
+	objs[i] = PyTuple_GET_ITEM(args, i);
+      }
+      for (; l < max; ++l) {
+	objs[l] = 0;
+      }
+      return i + 1;
+    }    
+  }
+}
+
+/* PySwigClientData */
+
+typedef struct {
+  PyObject *klass;
+  PyObject *newraw;
+  PyObject *newargs;
+  PyObject *destroy;
+  int delargs;
+  int implicitconv;
+} PySwigClientData;
+
+SWIGRUNTIMEINLINE int 
+SWIG_Python_CheckImplicit(swig_type_info *ty)
+{
+  PySwigClientData *data = (PySwigClientData *)ty->clientdata;
+  return data ? data->implicitconv : 0;
+}
+
+
+SWIGRUNTIME PySwigClientData * 
+PySwigClientData_New(PyObject* obj)
+{
+  if (!obj) {
+    return 0;
+  } else {
+    PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData));
+    /* the klass element */
+    data->klass = obj;
+    Py_INCREF(obj);
+    /* the newraw method and newargs arguments used to create a new raw instance */
+    if (PyClass_Check(obj)) {
+      data->newraw = 0;
+      data->newargs = obj;
+      Py_INCREF(obj);
+    } else {
+#if (PY_VERSION_HEX < 0x02020000)
+      data->newraw = 0;
+      data->newargs = obj;
+      Py_INCREF(obj);
+#else
+      data->newraw = PyObject_GetAttrString((PyObject*)&PyBaseObject_Type, "__new__");
+      Py_INCREF(data->newraw);
+      data->newargs = PyTuple_New(1);
+      PyTuple_SetItem(data->newargs, 0, obj);
+      Py_INCREF(data->newargs);
+#endif
+    }
+    /* the destroy method, aka as the C++ delete method */
+    data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__");
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      data->destroy = 0;
+    }
+    if (data->destroy) {
+      Py_INCREF(data->destroy);
+      int flags = PyCFunction_GET_FLAGS(data->destroy);
+#ifdef METH_O
+      data->delargs = !(flags & (METH_O));
+#else
+      data->delargs = 0;
+#endif
+    } else {
+      data->delargs = 0;
+    }
+    data->implicitconv = 0;
+    return data;
+  }
+}
+
+SWIGRUNTIME void 
+PySwigClientData_Del(PySwigClientData* data)
+{
+  Py_XDECREF(data->klass);
+  Py_XDECREF(data->newraw);
+  Py_XDECREF(data->newargs);
+  Py_XDECREF(data->destroy);
+  free(data);
+}
+
+/* =============== PySwigObject =====================*/
+
+typedef struct {
+  PyObject_HEAD
+  void *ptr;
+  swig_type_info *ty;
+  int own;
+  PyObject *next;
+} PySwigObject;
+
+SWIGRUNTIME PyObject *
+PySwigObject_long(PySwigObject *v)
+{
+  return PyLong_FromVoidPtr(v->ptr);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_format(const char* fmt, PySwigObject *v)
+{
+  PyObject *res = NULL;
+  PyObject *args = PyTuple_New(1);
+  if (args) {
+    if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) {
+      PyObject *ofmt = PyString_FromString(fmt);
+      if (ofmt) {
+	res = PyString_Format(ofmt,args);
+	Py_DECREF(ofmt);
+      }
+      Py_DECREF(args);
+    }
+  }
+  return res;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_oct(PySwigObject *v)
+{
+  return PySwigObject_format("%o",v);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_hex(PySwigObject *v)
+{
+  return PySwigObject_format("%x",v);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_repr(PySwigObject *v)
+{
+  const char *name = SWIG_TypePrettyName(v->ty);
+  PyObject *hex = PySwigObject_hex(v);    
+  PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex));
+  Py_DECREF(hex);
+  if (v->next) {
+    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next);
+    PyString_ConcatAndDel(&repr,nrep);
+  }
+  return repr;  
+}
+
+SWIGRUNTIME int
+PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags))
+{
+  PyObject *repr = PySwigObject_repr(v);
+  if (repr) {
+    fputs(PyString_AsString(repr), fp);
+    Py_DECREF(repr);
+    return 0; 
+  } else {
+    return 1; 
+  }
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_str(PySwigObject *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ?
+    PyString_FromString(result) : 0;
+}
+
+SWIGRUNTIME int
+PySwigObject_compare(PySwigObject *v, PySwigObject *w)
+{
+  void *i = v->ptr;
+  void *j = w->ptr;
+  return (i < j) ? -1 : ((i > j) ? 1 : 0);
+}
+
+SWIGRUNTIME PyTypeObject* _PySwigObject_type(void);
+
+SWIGRUNTIME PyTypeObject*
+PySwigObject_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigObject_Check(PyObject *op) {
+  return ((op)->ob_type == PySwigObject_type()) 
+    || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0);
+}
+
+
+SWIGRUNTIME PyObject *
+PySwigObject_New(void *ptr, swig_type_info *ty, int own);
+
+SWIGRUNTIME void
+PySwigObject_dealloc(PyObject *v)
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+  PyObject *next = sobj->next;
+  if (sobj->own) {
+    swig_type_info *ty = sobj->ty;
+    PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;
+    PyObject *destroy = data ? data->destroy : 0;
+    if (destroy) {
+      /* destroy is always a VARARGS method */
+      PyObject *res;
+      if (data->delargs) {
+	/* we need to create a temporal object to carry the destroy operation */
+	PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0);
+	res = SWIG_Python_CallFunctor(destroy, tmp);
+	Py_DECREF(tmp);
+      } else {
+	PyCFunction meth = PyCFunction_GET_FUNCTION(destroy);
+	PyObject *mself = PyCFunction_GET_SELF(destroy);
+	res = ((*meth)(mself, v));
+      }
+      Py_XDECREF(res);
+    } else {
+      const char *name = SWIG_TypePrettyName(ty);
+#if (PY_VERSION_HEX >= 0x02020000)
+      PyObject *wrn = PyString_FromFormat("swig/python detected a memory leak of type '%s'.", name);
+      PyErr_Warn(PyExc_RuntimeWarning, PyString_AsString(wrn));
+      Py_DECREF(wrn);
+#else
+      printf("swig/python detected a memory leak of type '%s'.", name);
+#endif
+    }
+  } 
+  Py_XDECREF(next);
+  PyObject_DEL(v);
+}
+
+SWIGRUNTIME PyObject* 
+PySwigObject_append(PyObject* v, PyObject* next)
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+#ifndef METH_O
+  PyObject *tmp = 0;
+  if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL;
+  next = tmp;
+#endif
+  if (!PySwigObject_Check(next)) {
+    return NULL;
+  }
+  sobj->next = next;
+  Py_INCREF(next);
+  return SWIG_Py_Void();
+}
+
+SWIGRUNTIME PyObject* 
+#ifdef METH_NOARGS
+PySwigObject_next(PyObject* v)
+#else
+PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+  if (sobj->next) {    
+    Py_INCREF(sobj->next);
+    return sobj->next;
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+
+SWIGINTERN PyObject*
+#ifdef METH_NOARGS
+PySwigObject_disown(PyObject *v)
+#else
+PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *)v;
+  sobj->own = 0;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+#ifdef METH_NOARGS
+PySwigObject_acquire(PyObject *v)
+#else
+PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *)v;
+  sobj->own = SWIG_POINTER_OWN;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+PySwigObject_own(PyObject *v, PyObject *args)
+{
+  PyObject *val = 0;
+#if (PY_VERSION_HEX < 0x02020000)
+  if (!PyArg_ParseTuple(args,(char *)"O:own",&val))
+#else
+  if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) 
+#endif
+    {
+      return NULL;
+    } 
+  else
+    {
+      PySwigObject *sobj = (PySwigObject *)v;
+      PyObject *obj = sobj->own ? Py_True : Py_False;
+      if (val) {
+#ifdef METH_NOARGS
+	if (PyObject_IsTrue(val)) {
+	  PySwigObject_acquire(v);
+	} else {
+	  PySwigObject_disown(v);
+	}
+#else
+	if (PyObject_IsTrue(val)) {
+	  PySwigObject_acquire(v,args);
+	} else {
+	  PySwigObject_disown(v,args);
+	}
+#endif
+      } 
+      Py_INCREF(obj);
+      return obj;
+    }
+}
+
+SWIGRUNTIME PyTypeObject*
+_PySwigObject_type(void) {
+  static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer";
+  static PyMethodDef
+#ifdef METH_O
+    swigobject_methods[] = {
+      {"disown",  (PyCFunction)PySwigObject_disown,  METH_NOARGS,  "releases ownership of the pointer"},
+      {"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS,  "aquires ownership of the pointer"},
+      {"own",     (PyCFunction)PySwigObject_own,     METH_VARARGS, "returns/sets ownership of the pointer"},
+      {"append",  (PyCFunction)PySwigObject_append,  METH_O,       "appends another 'this' object"},
+      {"next",    (PyCFunction)PySwigObject_next,    METH_NOARGS,  "returns the next 'this' object"},
+      {0, 0, 0, 0}  
+    };
+#else
+    swigobject_methods[] = {
+      {"disown",  (PyCFunction)PySwigObject_disown,  METH_VARARGS,  "releases ownership of the pointer"},
+      {"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS,  "aquires ownership of the pointer"},
+      {"own",     (PyCFunction)PySwigObject_own,     METH_VARARGS, "returns/sets ownership of the pointer"},
+      {"append",  (PyCFunction)PySwigObject_append,  METH_VARARGS,       "appends another 'this' object"},
+      {"next",    (PyCFunction)PySwigObject_next,    METH_VARARGS,  "returns the next 'this' object"},
+      {0, 0, 0, 0}  
+    };
+#endif
+  
+  static PyNumberMethods PySwigObject_as_number = {
+    (binaryfunc)0, /*nb_add*/
+    (binaryfunc)0, /*nb_subtract*/
+    (binaryfunc)0, /*nb_multiply*/
+    (binaryfunc)0, /*nb_divide*/
+    (binaryfunc)0, /*nb_remainder*/
+    (binaryfunc)0, /*nb_divmod*/
+    (ternaryfunc)0,/*nb_power*/
+    (unaryfunc)0,  /*nb_negative*/
+    (unaryfunc)0,  /*nb_positive*/
+    (unaryfunc)0,  /*nb_absolute*/
+    (inquiry)0,    /*nb_nonzero*/
+    0,		   /*nb_invert*/
+    0,		   /*nb_lshift*/
+    0,		   /*nb_rshift*/
+    0,		   /*nb_and*/
+    0,		   /*nb_xor*/
+    0,		   /*nb_or*/
+    (coercion)0,   /*nb_coerce*/
+    (unaryfunc)PySwigObject_long, /*nb_int*/
+    (unaryfunc)PySwigObject_long, /*nb_long*/
+    (unaryfunc)0,                 /*nb_float*/
+    (unaryfunc)PySwigObject_oct,  /*nb_oct*/
+    (unaryfunc)PySwigObject_hex,  /*nb_hex*/
+#if PY_VERSION_HEX >= 0x02020000
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ 
+#elif PY_VERSION_HEX >= 0x02000000
+    0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */
+#endif
+  };
+
+  static PyTypeObject pyswigobject_type;  
+  static int type_init = 0;
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+	PyObject_HEAD_INIT(NULL)
+	0,				    /* ob_size */
+	(char *)"PySwigObject",		    /* tp_name */
+	sizeof(PySwigObject),		    /* tp_basicsize */
+	0,			            /* tp_itemsize */
+	(destructor)PySwigObject_dealloc,   /* tp_dealloc */
+	(printfunc)PySwigObject_print,	    /* tp_print */   
+	(getattrfunc)0,			    /* tp_getattr */ 
+	(setattrfunc)0,			    /* tp_setattr */ 
+	(cmpfunc)PySwigObject_compare,	    /* tp_compare */ 
+	(reprfunc)PySwigObject_repr,	    /* tp_repr */    
+	&PySwigObject_as_number,	    /* tp_as_number */
+	0,				    /* tp_as_sequence */
+	0,				    /* tp_as_mapping */
+	(hashfunc)0,			    /* tp_hash */
+	(ternaryfunc)0,			    /* tp_call */
+	(reprfunc)PySwigObject_str,	    /* tp_str */
+	PyObject_GenericGetAttr,	    /* tp_getattro */
+	0,				    /* tp_setattro */
+	0,		                    /* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,	            /* tp_flags */
+	swigobject_doc, 	            /* tp_doc */        
+	0,                                  /* tp_traverse */
+	0,                                  /* tp_clear */
+	0,                                  /* tp_richcompare */
+	0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+	0,                                  /* tp_iter */
+	0,                                  /* tp_iternext */
+	swigobject_methods,		    /* tp_methods */ 
+	0,			            /* tp_members */
+	0,				    /* tp_getset */	    	
+	0,			            /* tp_base */	        
+	0,				    /* tp_dict */	    	
+	0,				    /* tp_descr_get */  	
+	0,				    /* tp_descr_set */  	
+	0,				    /* tp_dictoffset */ 	
+	0,				    /* tp_init */	    	
+	0,				    /* tp_alloc */	    	
+	0,			            /* tp_new */	    	
+	PyObject_Del,	                    /* tp_free */	   
+        0,                                  /* tp_is_gc */  
+	0,				    /* tp_bases */   
+	0,				    /* tp_mro */
+	0,				    /* tp_cache */   
+ 	0,				    /* tp_subclasses */
+	0,				    /* tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+	0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+	0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+    pyswigobject_type = tmp;
+    pyswigobject_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &pyswigobject_type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_New(void *ptr, swig_type_info *ty, int own)
+{
+  PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type());
+  if (sobj) {
+    sobj->ptr  = ptr;
+    sobj->ty   = ty;
+    sobj->own  = own;
+    sobj->next = 0;
+  }
+  return (PyObject *)sobj;
+}
+
+/* -----------------------------------------------------------------------------
+ * Implements a simple Swig Packed type, and use it instead of string
+ * ----------------------------------------------------------------------------- */
+
+typedef struct {
+  PyObject_HEAD
+  void *pack;
+  swig_type_info *ty;
+  size_t size;
+} PySwigPacked;
+
+SWIGRUNTIME int
+PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags))
+{
+  char result[SWIG_BUFFER_SIZE];
+  fputs("<Swig Packed ", fp); 
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    fputs("at ", fp); 
+    fputs(result, fp); 
+  }
+  fputs(v->ty->name,fp); 
+  fputs(">", fp);
+  return 0; 
+}
+  
+SWIGRUNTIME PyObject *
+PySwigPacked_repr(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name);
+  } else {
+    return PyString_FromFormat("<Swig Packed %s>", v->ty->name);
+  }  
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_str(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
+    return PyString_FromFormat("%s%s", result, v->ty->name);
+  } else {
+    return PyString_FromString(v->ty->name);
+  }  
+}
+
+SWIGRUNTIME int
+PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)
+{
+  size_t i = v->size;
+  size_t j = w->size;
+  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
+  return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);
+}
+
+SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void);
+
+SWIGRUNTIME PyTypeObject*
+PySwigPacked_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigPacked_Check(PyObject *op) {
+  return ((op)->ob_type == _PySwigPacked_type()) 
+    || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0);
+}
+
+SWIGRUNTIME void
+PySwigPacked_dealloc(PyObject *v)
+{
+  if (PySwigPacked_Check(v)) {
+    PySwigPacked *sobj = (PySwigPacked *) v;
+    free(sobj->pack);
+  }
+  PyObject_DEL(v);
+}
+
+SWIGRUNTIME PyTypeObject*
+_PySwigPacked_type(void) {
+  static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer";
+  static PyTypeObject pyswigpacked_type;
+  static int type_init = 0;  
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+	PyObject_HEAD_INIT(NULL)
+	0,				    /* ob_size */	
+	(char *)"PySwigPacked",		    /* tp_name */	
+	sizeof(PySwigPacked),		    /* tp_basicsize */	
+	0,				    /* tp_itemsize */	
+	(destructor)PySwigPacked_dealloc,   /* tp_dealloc */	
+	(printfunc)PySwigPacked_print,	    /* tp_print */   	
+	(getattrfunc)0,			    /* tp_getattr */ 	
+	(setattrfunc)0,			    /* tp_setattr */ 	
+	(cmpfunc)PySwigPacked_compare,	    /* tp_compare */ 	
+	(reprfunc)PySwigPacked_repr,	    /* tp_repr */    	
+	0,	                            /* tp_as_number */	
+	0,				    /* tp_as_sequence */
+	0,				    /* tp_as_mapping */	
+	(hashfunc)0,			    /* tp_hash */	
+	(ternaryfunc)0,			    /* tp_call */	
+	(reprfunc)PySwigPacked_str,	    /* tp_str */	
+	PyObject_GenericGetAttr,            /* tp_getattro */
+	0,				    /* tp_setattro */
+	0,		                    /* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,	            /* tp_flags */
+	swigpacked_doc, 	            /* tp_doc */
+	0,                                  /* tp_traverse */
+	0,                                  /* tp_clear */
+	0,                                  /* tp_richcompare */
+	0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+	0,                                  /* tp_iter */
+	0,                                  /* tp_iternext */
+	0,		                    /* tp_methods */ 
+	0,			            /* tp_members */
+	0,				    /* tp_getset */	    	
+	0,			            /* tp_base */	        
+	0,				    /* tp_dict */	    	
+	0,				    /* tp_descr_get */  	
+	0,				    /* tp_descr_set */  	
+	0,				    /* tp_dictoffset */ 	
+	0,				    /* tp_init */	    	
+	0,				    /* tp_alloc */	    	
+	0,			            /* tp_new */	    	
+	PyObject_Del, 	                    /* tp_free */	   
+        0,                                  /* tp_is_gc */  
+	0,				    /* tp_bases */   
+	0,				    /* tp_mro */
+	0,				    /* tp_cache */   
+ 	0,				    /* tp_subclasses */
+	0,				    /* tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+	0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+	0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+    pyswigpacked_type = tmp;
+    pyswigpacked_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &pyswigpacked_type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty)
+{
+  PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type());
+  if (sobj) {
+    void *pack = malloc(size);
+    if (pack) {
+      memcpy(pack, ptr, size);
+      sobj->pack = pack;
+      sobj->ty   = ty;
+      sobj->size = size;
+    } else {
+      PyObject_DEL((PyObject *) sobj);
+      sobj = 0;
+    }
+  }
+  return (PyObject *) sobj;
+}
+
+SWIGRUNTIME swig_type_info *
+PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
+{
+  if (PySwigPacked_Check(obj)) {
+    PySwigPacked *sobj = (PySwigPacked *)obj;
+    if (sobj->size != size) return 0;
+    memcpy(ptr, sobj->pack, size);
+    return sobj->ty;
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIME PyObject *
+_SWIG_This(void)
+{
+  static PyObject *_this = 0;
+  if (!_this) {
+    _this = PyString_FromString("this");
+  }
+  return _this;
+}
+
+SWIGRUNTIME PyObject *
+SWIG_This(void)
+{
+  static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This();
+  return swig_this;
+}
+
+/* #define SWIG_PYTHON_SLOW_GETSET_THIS */
+
+SWIGRUNTIME PySwigObject *
+SWIG_Python_GetSwigThis(PyObject *pyobj) 
+{
+  if (PySwigObject_Check(pyobj)) {
+    return (PySwigObject *) pyobj;
+  } else {
+    PyObject *obj = 0;
+#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && !(PY_VERSION_HEX < 0x02020000))
+    if (PyInstance_Check(pyobj)) {
+      obj = _PyInstance_Lookup(pyobj, SWIG_This());
+    } else {
+      PyObject **dictptr = _PyObject_GetDictPtr(pyobj);
+      if (dictptr != NULL) {
+	PyObject *dict = *dictptr;
+	obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0;
+      }      
+#ifdef PyWeakref_CheckProxy
+      else if (PyWeakref_CheckProxy(pyobj)) {
+	PyObject *wobj = PyWeakref_GET_OBJECT(pyobj);
+	return wobj ? SWIG_Python_GetSwigThis(wobj) : 0;
+      }
+#endif
+      if (!obj) {
+	obj = PyObject_GetAttr(pyobj,SWIG_This());
+	if (obj) {
+	  Py_DECREF(obj);
+	} else {
+	  if (PyErr_Occurred()) PyErr_Clear();
+	  return 0;
+	}
+      }
+    }
+#else
+    obj = PyObject_GetAttr(pyobj,SWIG_This());
+    if (obj) {
+      Py_DECREF(obj);
+    } else {
+      if (PyErr_Occurred()) PyErr_Clear();
+      return 0;
+    }
+#endif
+    return (PySwigObject *)obj;
+  }
+}
+
+
+/* Acquire a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_AcquirePtr(PyObject *obj, int own) {
+  if (own) {
+    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);
+    if (sobj) {
+      int oldown = sobj->own;
+      sobj->own = own;
+      return oldown;
+    }
+  }
+  return 0;
+}
+
+/* Convert a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {
+  if (!obj) return SWIG_ERROR;
+  if (obj == Py_None) {
+    if (ptr) *ptr = 0;
+    return SWIG_OK;
+  } else {
+    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);
+    while (sobj) {
+      void *vptr = sobj->ptr;
+      if (ty) {
+	swig_type_info *to = sobj->ty;
+	if (to == ty) {
+	  /* no type cast needed */
+	  if (ptr) *ptr = vptr;
+	  break;
+	} else {
+	  swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+	  if (!tc) {
+	    sobj = (PySwigObject *)sobj->next;
+	  } else {
+	    if (ptr) *ptr = SWIG_TypeCast(tc,vptr);
+	    break;
+	  }
+	}
+      } else {
+	if (ptr) *ptr = vptr;
+	break;
+      }
+    }
+    if (sobj) {
+      if (own) *own = sobj->own;
+      if (flags & SWIG_POINTER_DISOWN) {
+	sobj->own = 0;
+      }
+      return SWIG_OK;
+    } else {
+      int res = SWIG_ERROR;
+      if (flags & SWIG_POINTER_IMPLICIT_CONV) {
+	PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;
+	if (data && !data->implicitconv) {
+	  PyObject *klass = data->klass;
+	  if (klass) {
+	    PyObject *impconv;
+	    data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/
+	    impconv = SWIG_Python_CallFunctor(klass, obj);
+	    data->implicitconv = 0;
+	    if (PyErr_Occurred()) {
+	      PyErr_Clear();
+	      impconv = 0;
+	    }
+	    if (impconv) {
+	      PySwigObject *sobj = SWIG_Python_GetSwigThis(impconv);
+	      if (sobj) {
+		void *vptr;
+		res = SWIG_Python_ConvertPtrAndOwn((PyObject*)sobj, &vptr, ty, 0, 0);
+		if (SWIG_IsOK(res)) {
+		  if (ptr) {
+		    *ptr = vptr;
+		    /* transfer the ownership to 'ptr' */
+		    sobj->own = 0;
+		    res = SWIG_AddNewMask(SWIG_AddCast(res));		    
+		  } else {
+		    res = SWIG_AddCast(res);		    
+		  }
+		}
+	      }
+	      Py_DECREF(impconv);
+	    }
+	  }
+	}
+      }
+      return res;
+    }
+  }
+}
+
+/* Convert a function ptr value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {
+  if (!PyCFunction_Check(obj)) {
+    return SWIG_ConvertPtr(obj, ptr, ty, 0);
+  } else {
+    void *vptr = 0;
+    
+    /* here we get the method pointer for callbacks */
+    char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
+    const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0;
+    if (desc) {
+      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;
+      if (!desc) return SWIG_ERROR;
+    }
+    if (ty) {
+      swig_cast_info *tc = SWIG_TypeCheck(desc,ty);
+      if (!tc) return SWIG_ERROR;
+      *ptr = SWIG_TypeCast(tc,vptr);
+    } else {
+      *ptr = vptr;
+    }
+    return SWIG_OK;
+  }
+}
+
+/* Convert a packed value value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {
+  swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz);
+  if (!to) return SWIG_ERROR;
+  if (ty) {
+    if (to != ty) {
+      /* check type cast? */
+      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+      if (!tc) return SWIG_ERROR;
+    }
+  }
+  return SWIG_OK;
+}  
+
+/* -----------------------------------------------------------------------------
+ * Create a new pointer object
+ * ----------------------------------------------------------------------------- */
+
+/*
+  Create a new instance object, whitout calling __init__, and set the
+  'this' attribute.
+*/
+
+SWIGRUNTIME PyObject* 
+SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this)
+{
+#if (PY_VERSION_HEX >= 0x02020000)
+  PyObject *inst = 0;
+  PyObject *newraw = data->newraw;
+  if (newraw) {
+    inst = PyObject_Call(newraw, data->newargs, NULL);
+    if (inst) {
+#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+      PyObject **dictptr = _PyObject_GetDictPtr(inst);
+      if (dictptr != NULL) {
+	PyObject *dict = *dictptr;
+	if (dict == NULL) {
+	  dict = PyDict_New();
+	  *dictptr = dict;
+	  PyDict_SetItem(dict, SWIG_This(), swig_this);
+	}
+      }
+#else
+      PyObject *key = SWIG_This();
+      PyObject_SetAttr(inst, key, swig_this);
+#endif
+    }
+  } else {
+    PyObject *dict = PyDict_New();
+    PyDict_SetItem(dict, SWIG_This(), swig_this);
+    inst = PyInstance_NewRaw(data->newargs, dict);
+    Py_DECREF(dict);
+  }
+  return inst;
+#else
+  PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);
+  if (inst == NULL) {
+    return NULL;
+  }
+  inst->in_class = (PyClassObject *)data->newargs;
+  Py_INCREF(inst->in_class);
+  inst->in_dict = PyDict_New();
+  if (inst->in_dict == NULL) {
+    Py_DECREF(inst);
+    return NULL;
+  }
+  PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this);
+  return (PyObject *) inst;
+#endif
+}
+
+/* Create a new pointer object */
+
+SWIGRUNTIME PyObject *
+SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) {
+  if (!ptr) {
+    return SWIG_Py_Void();
+  } else {
+    int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;
+    PyObject *robj = PySwigObject_New(ptr, type, own);
+    PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0;
+    if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {
+      PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);
+      if (inst) {
+	Py_DECREF(robj);
+	robj = inst;
+      }
+    }
+    return robj;
+  }
+}
+
+/* Create a new packed object */
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Get type list 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_LINK_RUNTIME
+void *SWIG_ReturnGlobalTypeList(void *);
+#endif
+
+SWIGRUNTIME swig_module_info *
+SWIG_Python_GetModule(void) {
+  static void *type_pointer = (void *)0;
+  /* first check if module already created */
+  if (!type_pointer) {
+#ifdef SWIG_LINK_RUNTIME
+    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
+#else
+    type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+				    (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      type_pointer = (void *)0;
+    }
+#endif
+  }
+  return (swig_module_info *) type_pointer;
+}
+
+#if PY_MAJOR_VERSION < 2
+/* PyModule_AddObject function was introduced in Python 2.0.  The following function
+   is copied out of Python/modsupport.c in python version 2.3.4 */
+SWIGINTERN int
+PyModule_AddObject(PyObject *m, char *name, PyObject *o)
+{
+  PyObject *dict;
+  if (!PyModule_Check(m)) {
+    PyErr_SetString(PyExc_TypeError,
+		    "PyModule_AddObject() needs module as first arg");
+    return SWIG_ERROR;
+  }
+  if (!o) {
+    PyErr_SetString(PyExc_TypeError,
+		    "PyModule_AddObject() needs non-NULL value");
+    return SWIG_ERROR;
+  }
+  
+  dict = PyModule_GetDict(m);
+  if (dict == NULL) {
+    /* Internal error -- modules must have a dict! */
+    PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
+		 PyModule_GetName(m));
+    return SWIG_ERROR;
+  }
+  if (PyDict_SetItemString(dict, name, o))
+    return SWIG_ERROR;
+  Py_DECREF(o);
+  return SWIG_OK;
+}
+#endif
+
+SWIGRUNTIME void
+SWIG_Python_DestroyModule(void *vptr)
+{
+  swig_module_info *swig_module = (swig_module_info *) vptr;
+  swig_type_info **types = swig_module->types;
+  size_t i;
+  for (i =0; i < swig_module->size; ++i) {
+    swig_type_info *ty = types[i];
+    if (ty->owndata) {
+      PySwigClientData *data = (PySwigClientData *) ty->clientdata;
+      if (data) PySwigClientData_Del(data);
+      ty->clientdata = 0;
+    }
+  }
+  Py_DECREF(SWIG_This());
+}
+
+SWIGRUNTIME void
+SWIG_Python_SetModule(swig_module_info *swig_module) {
+  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */
+
+  PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+				   swig_empty_runtime_method_table);
+  PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule);
+  if (pointer && module) {
+    PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
+  } else {
+    Py_XDECREF(pointer);
+  }
+}
+
+#ifdef __cplusplus
+#if 0
+{ /* cc-mode */
+#endif
+}
+#endif
+
+/* -----------------------------------------------------------------------------*
+   Standard SWIG API for use inside user code.
+ 
+   Don't include this file directly, run the command
+   swig -python -external-runtime
+   Also, read the Modules chapter of the SWIG Manual.
+ 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_MODULE_CLIENTDATA_TYPE
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_TypeQuery(SWIG_MODULE_CLIENTDATA_TYPE clientdata, const char *name) {
+  swig_module_info *module = SWIG_GetModule(clientdata);
+  return SWIG_TypeQueryModule(module, module, name);
+}
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_MangledTypeQuery(SWIG_MODULE_CLIENTDATA_TYPE clientdata, const char *name) {
+  swig_module_info *module = SWIG_GetModule(clientdata);
+  return SWIG_MangledTypeQueryModule(module, module, name);
+}
+
+#else
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_TypeQuery(const char *name) {
+  swig_module_info *module = SWIG_GetModule(NULL);
+  return SWIG_TypeQueryModule(module, module, name);
+}
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_MangledTypeQuery(const char *name) {
+  swig_module_info *module = SWIG_GetModule(NULL);
+  return SWIG_MangledTypeQueryModule(module, module, name);
+}
+
+#endif
+
+"""
diff --git a/trunk/Examples/r/check.list b/trunk/Examples/r/check.list
new file mode 100644
index 0000000..69d56a4
--- /dev/null
+++ b/trunk/Examples/r/check.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+class
+simple
diff --git a/trunk/Examples/r/class/Makefile b/trunk/Examples/r/class/Makefile
new file mode 100644
index 0000000..6bed3ce
--- /dev/null
+++ b/trunk/Examples/r/class/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+ARGS = SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)'
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile $(ARGS) r_clean
+
+check: all
+	R CMD BATCH runme.R
diff --git a/trunk/Examples/r/class/example.cxx b/trunk/Examples/r/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/r/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/r/class/example.dsp b/trunk/Examples/r/class/example.dsp
new file mode 100644
index 0000000..682b156
--- /dev/null
+++ b/trunk/Examples/r/class/example.dsp
@@ -0,0 +1,152 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(R_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(R_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(R_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(R_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cpp

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cpp" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo R_INCLUDE: %R_INCLUDE% 

+	echo R_LIB: %R_LIB% 

+	echo on 

+	..\..\..\swig -c++ -r -o example_wrap.cpp $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cpp" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo R_INCLUDE: %R_INCLUDE% 

+	echo R_LIB: %R_LIB% 

+	echo on 

+	..\..\..\swig -c++ -r -o example_wrap.cpp $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/r/class/example.h b/trunk/Examples/r/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/r/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/r/class/example.i b/trunk/Examples/r/class/example.i
new file mode 100644
index 0000000..4654d26
--- /dev/null
+++ b/trunk/Examples/r/class/example.i
@@ -0,0 +1,9 @@
+/* File : example.i */
+%module example
+
+%inline %{
+#include "example.h"
+%}
+%include "example.h"
+
+
diff --git a/trunk/Examples/r/class/runme.R b/trunk/Examples/r/class/runme.R
new file mode 100644
index 0000000..4a20285
--- /dev/null
+++ b/trunk/Examples/r/class/runme.R
@@ -0,0 +1,49 @@
+# This file illustrates the proxy class C++ interface generated
+# by SWIG.
+
+dyn.load(paste("example", .Platform$dynlib.ext, sep=""))
+source("example.R")
+cacheMetaData(1)
+
+# ----- Object creation -----
+
+print("Creating some objects:")
+circle <- Circle(10)
+print ("    Created circle")
+square <- Square(10)
+print ("    Created square")
+
+# ----- Access a static member -----
+
+sprintf("A total of %d shapes were created", Shape_nshapes())
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+circle$x <- 20
+circle$y <- 30
+
+square$x <- -10
+square$y <- 5
+
+print("Here is their current position:")
+sprintf("    Circle = (%f, %f)", circle$x,circle$y)
+sprintf("    Square = (%f, %f)", square$x,square$y)
+
+# ----- Call some methods -----
+
+print ("Here are some properties of the shapes:")
+
+sapply(c(circle, square), 
+		 function(o) {
+sprintf("       area = %f perimeter = %f", o$area(),  o$perimeter())
+})
+
+print("Guess I'll clean up now")
+delete(circle)
+delete(square)
+
+sprintf("%d shapes remain", Shape_nshapes())
+print ("Goodbye");
+
diff --git a/trunk/Examples/r/simple/Makefile b/trunk/Examples/r/simple/Makefile
new file mode 100644
index 0000000..e01d359
--- /dev/null
+++ b/trunk/Examples/r/simple/Makefile
@@ -0,0 +1,16 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+ARGS = SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)'
+
+all::
+	$(MAKE) -f $(TOP)/Makefile $(ARGS) r
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile $(ARGS) r_clean
+
+check: all
+	R CMD BATCH runme.R
diff --git a/trunk/Examples/r/simple/example.c b/trunk/Examples/r/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/r/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/r/simple/example.dsp b/trunk/Examples/r/simple/example.dsp
new file mode 100644
index 0000000..aaa5ef8
--- /dev/null
+++ b/trunk/Examples/r/simple/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(R_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(R_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(R_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(R_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo R_INCLUDE: %R_INCLUDE% 

+	echo R_LIB: %R_LIB% 

+	echo on 

+	..\..\..\swig -r $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo R_INCLUDE: %R_INCLUDE% 

+	echo R_LIB: %R_LIB% 

+	echo on 

+	..\..\..\swig -r $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/r/simple/example.i b/trunk/Examples/r/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/r/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/r/simple/runme.R b/trunk/Examples/r/simple/runme.R
new file mode 100644
index 0000000..7830937
--- /dev/null
+++ b/trunk/Examples/r/simple/runme.R
@@ -0,0 +1,24 @@
+# file: runme.R
+
+dyn.load(paste("example", .Platform$dynlib.ext, sep=""))
+source("example.R")
+cacheMetaData(1)
+
+# Call our gcd() function
+
+x <- 42
+y <- 105
+g <- gcd(x,y)
+sprintf("The gcd of %d and %d is %d", x, y, g)
+
+# Manipulate the Foo global variable
+
+# Output its current value
+Foo()
+
+# Change its value
+Foo(3.1415926)
+
+# See if the change took effect
+Foo()
+
diff --git a/trunk/Examples/ruby/check.list b/trunk/Examples/ruby/check.list
new file mode 100644
index 0000000..131dcbb
--- /dev/null
+++ b/trunk/Examples/ruby/check.list
@@ -0,0 +1,23 @@
+# see top-level Makefile.in
+class
+constants
+enum
+free_function
+funcptr
+funcptr2
+functor
+hashargs
+import
+import_template
+java
+mark_function
+multimap
+operator
+overloading
+pointer
+reference
+simple
+std_vector
+template
+value
+variables
diff --git a/trunk/Examples/ruby/class/Makefile b/trunk/Examples/ruby/class/Makefile
new file mode 100644
index 0000000..56c84c6
--- /dev/null
+++ b/trunk/Examples/ruby/class/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/class/example.cxx b/trunk/Examples/ruby/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/ruby/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/ruby/class/example.dsp b/trunk/Examples/ruby/class/example.dsp
new file mode 100644
index 0000000..9a26322
--- /dev/null
+++ b/trunk/Examples/ruby/class/example.dsp
@@ -0,0 +1,154 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/class/example.h b/trunk/Examples/ruby/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/ruby/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/ruby/class/example.i b/trunk/Examples/ruby/class/example.i
new file mode 100644
index 0000000..75700b3
--- /dev/null
+++ b/trunk/Examples/ruby/class/example.i
@@ -0,0 +1,10 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/ruby/class/index.html b/trunk/Examples/ruby/class/index.html
new file mode 100644
index 0000000..67eeac9
--- /dev/null
+++ b/trunk/Examples/ruby/class/index.html
@@ -0,0 +1,199 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:class</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/ruby/class/</tt>
+<hr>
+
+<H2>Wrapping a simple C++ class</H2>
+
+<p>
+This example illustrates C++ class wrapping performed by SWIG.
+C++ classes are simply transformed into Ruby classes that provide methods to
+access class members.
+
+<h2>The C++ Code</h2>
+
+Suppose you have some C++ classes described by the following (and admittedly lame) 
+header file:
+
+<blockquote>
+<pre>
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+A simple SWIG interface for this can be built by simply grabbing the header file
+like this:
+
+<blockquote>
+<pre>
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+</pre>
+</blockquote>
+
+Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> option like this:
+<blockquote>
+<pre>
+% swig -c++ -ruby example.i
+</pre>
+</blockquote>
+
+<h2>A sample Ruby script</h2>
+
+Click <a href="runme.rb">here</a> to see a script that calls the C++ functions from Ruby.
+
+<h2>Key points</h2>
+
+<ul>
+<li>To create a new object, you call a constructor like this:
+
+<blockquote>
+<pre>
+c = Example::Circle.new(10)
+</pre>
+</blockquote>
+
+<p>
+<li>To access member data, a pair of accessor methods are used.
+For example:
+
+<blockquote>
+<pre>
+c.x = 15    # Set member data
+x = c.x     # Get member data
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a member function, you simply do this
+
+<blockquote>
+<pre>
+print "The area is ", c.area, "\n"
+</pre>
+</blockquote>
+
+<p>
+<li>When a instance of Ruby level wrapper class is garbage collected by
+Ruby interpreter, the corresponding C++ destructor is automatically invoked.
+(Note: destructors are currently not inherited. This might change later.
+Until then, use <tt>-make_default</tt>).
+
+<p>
+<li>Static member variables are wrapped as Ruby class accessor methods.
+For example:
+
+<blockquote>
+<pre>
+n = Shape.nshapes     # Get a static data member
+Shapes.nshapes = 13   # Set a static data member
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>General Comments</h2>
+
+<ul>
+<li>Ruby module of SWIG differs from other language modules in wrapping C++
+interfaces.  They provides lower-level interfaces and optional higher-level
+interfaces know as proxy classes.  Ruby module needs no such redundancy
+due to Ruby's sophisticated extension API.
+
+<p>
+<li>SWIG *does* know how to properly perform upcasting of objects in
+an inheritance hierarchy except for multiple inheritance.
+
+<p>
+<li>A wide variety of C++ features are not currently supported by SWIG.  Here is the
+short and incomplete list:
+
+<p>
+<ul>
+<li>Overloaded methods and functions.  SWIG wrappers don't know how to resolve name
+conflicts so you must give an alternative name to any overloaded method name using the
+%name directive like this:
+
+<blockquote>
+<pre>
+void foo(int a);  
+%name(foo2) void foo(double a, double b);
+</pre>
+</blockquote>
+
+<p>
+<li>Overloaded operators.  Not supported at all. The only workaround for this is
+to write a helper function. For example:
+
+<blockquote>
+<pre>
+%inline %{
+    Vector *vector_add(Vector *a, Vector *b) {
+          ... whatever ...
+    }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>Namespaces.  Not supported at all. Won't be supported until SWIG2.0 (if at all).
+
+</ul>
+<p>
+
+<li>Dave's snide remark: Like a large bottle of strong Tequilla, it's better to
+use C++	in moderation.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ruby/class/runme.rb b/trunk/Examples/ruby/class/runme.rb
new file mode 100644
index 0000000..de73bcd
--- /dev/null
+++ b/trunk/Examples/ruby/class/runme.rb
@@ -0,0 +1,49 @@
+# file: runme.rb
+
+# This file illustrates the C++ interface created by SWIG.
+# All of our C++ classes get converted into Ruby classes.
+
+require 'example'
+
+# ----- Object creation -----
+
+print "Creating some objects:\n"
+c = Example::Circle.new(10)
+print "    Created circle #{c}\n"
+s = Example::Square.new(10)
+print "    Created square #{s}\n"
+
+# ----- Access a static member -----
+
+print "\nA total of #{Example::Shape.nshapes} shapes were created\n"
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+# Notice how we can do this using functions specific to
+# the 'Circle' class.
+c.x = 20
+c.y = 30
+
+# Now use the same functions in the base class
+s.x = -10
+s.y = 5
+
+print "\nHere is their current position:\n"
+print "    Circle = (", c.x, ",", c.y, ")\n"
+print "    Square = (", s.x, ",", s.y, ")\n"
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n"
+for o in [c, s]
+  print "    #{o}\n"
+  print "        area      = ", o.area, "\n"
+  print "        perimeter = ", o.perimeter, "\n"
+end
+# Notice how the Shape#area() and Shape#perimeter() functions really
+# invoke the appropriate virtual method on each object.
+
+print "\n", Example::Shape.nshapes," shapes remain\n"
+print "Goodbye\n"
diff --git a/trunk/Examples/ruby/constants/Makefile b/trunk/Examples/ruby/constants/Makefile
new file mode 100644
index 0000000..7dce3be
--- /dev/null
+++ b/trunk/Examples/ruby/constants/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/constants/example.i b/trunk/Examples/ruby/constants/example.i
new file mode 100644
index 0000000..14eb23c
--- /dev/null
+++ b/trunk/Examples/ruby/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int Iconst = 37;
+%constant double Fconst = 3.14;
+
+
diff --git a/trunk/Examples/ruby/constants/index.html b/trunk/Examples/ruby/constants/index.html
new file mode 100644
index 0000000..3b63f3d
--- /dev/null
+++ b/trunk/Examples/ruby/constants/index.html
@@ -0,0 +1,64 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:constants</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/ruby/constants/</tt>
+<hr>
+
+<H2>Wrapping C Constants</H2>
+
+<p>
+When SWIG encounters C preprocessor macros and C declarations that look like constants,
+it creates Ruby constants with an identical value.  Click <a href="example.i">here</a>
+to see a SWIG interface with some constant declarations in it.
+
+<h2>Accessing Constants from Ruby</h2>
+
+Click <a href="run.rb">here</a> to see a script that prints out the values
+of the constants contained in the above file.
+
+<h2>Key points</h2>
+
+<ul>
+<li>The values of preprocessor macros are converted into Ruby constants.
+<li>Types are inferred by syntax (e.g., "3" is an integer and "3.5" is a float).
+<li>Character constants such as 'x' are converted into Ruby strings.
+<li>C string literals such as "Hello World" are converted into Ruby strings.
+<li>Macros that are not fully defined are simply ignored.  For example:
+<blockquote>
+<pre>
+#define EXTERN extern
+</pre>
+</blockquote>
+is ignored because SWIG has no idea what type of variable this would be.
+
+<p>
+<li>Expressions are allowed provided that all of their components are defined. Otherwise, the constant is ignored.
+
+<li>Certain C declarations involving 'const' are also turned into Ruby constants.
+
+<li>Constants that begin with lower case character are automatically capitalized.
+For example:
+<blockquote>
+<pre>
+const int     iconst = 37;
+</pre>
+</blockquote>
+is capitalized as <tt>Example::Iconst</tt> because Ruby constants name must begin
+with upper case character.
+
+<li>The constants that appear in a SWIG interface file do not have to appear in any sort
+of matching C source file since the creation of a constant does not require linkage
+to a stored value (i.e., a value held in a C global variable or memory location).
+
+
+</ul>
+
+<hr>
+
+
+</body>
+</html>
diff --git a/trunk/Examples/ruby/constants/runme.rb b/trunk/Examples/ruby/constants/runme.rb
new file mode 100755
index 0000000..2a6b5f5
--- /dev/null
+++ b/trunk/Examples/ruby/constants/runme.rb
@@ -0,0 +1,25 @@
+# file: runme.rb
+
+require 'example'
+
+print "ICONST  = ", Example::ICONST,  " (should be 42)\n"
+print "FCONST  = ", Example::FCONST,  " (should be 2.1828)\n"
+print "CCONST  = ", Example::CCONST,  " (should be 'x')\n"
+print "CCONST2 = ", Example::CCONST2, " (this should be on a new line)\n"
+print "SCONST  = ", Example::SCONST,  " (should be 'Hello World')\n"
+print "SCONST2 = ", Example::SCONST2, " (should be '\"Hello World\"')\n"
+print "EXPR    = ", Example::EXPR,    " (should be 48.5484)\n"
+print "iconst  = ", Example::Iconst,  " (should be 37)\n"
+print "fconst  = ", Example::Fconst,  " (should be 3.14)\n"
+
+begin
+  print "EXTERN = ", Example::EXTERN, " (Arg! This shouldn't print anything)\n"
+rescue NameError
+  print "EXTERN isn't defined (good)\n"
+end
+
+begin
+  print "FOO    = ", Example::FOO, " (Arg! This shouldn't print anything)\n"
+rescue NameError
+  print "FOO isn't defined (good)\n"
+end
diff --git a/trunk/Examples/ruby/enum/Makefile b/trunk/Examples/ruby/enum/Makefile
new file mode 100644
index 0000000..56c84c6
--- /dev/null
+++ b/trunk/Examples/ruby/enum/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/enum/example.cxx b/trunk/Examples/ruby/enum/example.cxx
new file mode 100644
index 0000000..6785e57
--- /dev/null
+++ b/trunk/Examples/ruby/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.c */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/ruby/enum/example.h b/trunk/Examples/ruby/enum/example.h
new file mode 100644
index 0000000..525d62a
--- /dev/null
+++ b/trunk/Examples/ruby/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/ruby/enum/example.i b/trunk/Examples/ruby/enum/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/ruby/enum/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/ruby/enum/index.html b/trunk/Examples/ruby/enum/index.html
new file mode 100644
index 0000000..d773d9c
--- /dev/null
+++ b/trunk/Examples/ruby/enum/index.html
@@ -0,0 +1,35 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:enum</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/ruby/enum/</tt>
+<hr>
+
+<H2>Wrapping enumerations</H2>
+
+<p>
+This example tests SWIG's ability to wrap enumerations.  By default, SWIG
+converts enumeration specifications into integer constants.  Further use
+of enumerated types are handled as integers.
+
+<ul>
+<li><a href="example.h">example.h</a>.  Header file containing some enums.
+<li><a href="example.i">example.i</a>.  Interface file.
+<li><a href="runme.rb">runme.rb</a>. Sample Ruby script.
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>SWIG allows arbitrary integers to be passed as enum values.  However,
+the result of passing an integer not corresponding to any of the values
+specified in the <tt>enum</tt> specification is undefined.
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ruby/enum/runme.rb b/trunk/Examples/ruby/enum/runme.rb
new file mode 100644
index 0000000..cd6a76f
--- /dev/null
+++ b/trunk/Examples/ruby/enum/runme.rb
@@ -0,0 +1,30 @@
+# file: runme.rb
+
+require 'example'
+
+# ----- Object creation -----
+
+# Print out the value of some enums
+print "*** color ***\n"
+print "    RED    = #{Example::RED}\n"
+print "    BLUE   = #{Example::BLUE}\n"
+print "    GREEN  = #{Example::GREEN}\n"
+
+print "\n*** Foo::speed ***\n"
+print "    Foo::IMPULSE   = #{Example::Foo::IMPULSE}\n"
+print "    Foo::WARP      = #{Example::Foo::WARP}\n"
+print "    Foo::LUDICROUS = #{Example::Foo::LUDICROUS}\n"
+
+print "\nTesting use of enums with functions\n\n"
+
+Example::enum_test(Example::RED, Example::Foo::IMPULSE)
+Example::enum_test(Example::BLUE,  Example::Foo::WARP)
+Example::enum_test(Example::GREEN, Example::Foo::LUDICROUS)
+Example::enum_test(1234, 5678)
+
+print "\nTesting use of enum with class method\n"
+f = Example::Foo.new()
+
+f.enum_test(Example::Foo::IMPULSE)
+f.enum_test(Example::Foo::WARP)
+f.enum_test(Example::Foo::LUDICROUS)
diff --git a/trunk/Examples/ruby/exception_class/Makefile b/trunk/Examples/ruby/exception_class/Makefile
new file mode 100644
index 0000000..016a5ad
--- /dev/null
+++ b/trunk/Examples/ruby/exception_class/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/exception_class/example.h b/trunk/Examples/ruby/exception_class/example.h
new file mode 100644
index 0000000..9facde4
--- /dev/null
+++ b/trunk/Examples/ruby/exception_class/example.h
@@ -0,0 +1,51 @@
+/* File : example.h */
+
+// A simple exception
+class EmptyError { };
+class FullError { 
+ public:
+  int maxsize;
+  FullError(int m) : maxsize(m) { }
+};
+
+template<typename T> class Queue {
+  int maxsize;
+  T   *items;
+  int nitems;
+  int last;
+ public: 
+  Queue(int size) {
+    maxsize = size;
+    items = new T[size];
+    nitems = 0;
+    last = 0;
+  }
+  ~Queue() {
+    delete [] items;
+  }
+  void enqueue(T x) throw(FullError) {
+    if (nitems == maxsize) {
+      throw FullError(maxsize);
+    }
+    items[last] = x;
+    last = (last + 1) % maxsize;
+    nitems++;
+  }
+  T dequeue()  {
+    T x;
+    if (nitems == 0) throw EmptyError();
+    x = items[(last + maxsize - nitems) % maxsize];
+    nitems--;
+    return x;
+  }
+  int length() {
+    return nitems;
+  }
+};
+
+
+
+
+
+
+  
diff --git a/trunk/Examples/ruby/exception_class/example.i b/trunk/Examples/ruby/exception_class/example.i
new file mode 100644
index 0000000..5094b7a
--- /dev/null
+++ b/trunk/Examples/ruby/exception_class/example.i
@@ -0,0 +1,46 @@
+/* This example illustrates the use of the %exceptionclass feature.  By
+   default, if a method has a throws specification then SWIG will generate
+   code to catch the exception and pass it on the scripting language.
+   
+   If a method does not have a throws specification, but does throw 
+   an exception, then the %exceptionclass feature can be used to tell
+   SWIG about the exception class so it can be properly added to Ruby.
+   This is done by making the exception class inherit from rb_eRuntimeError.*/
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+
+/* The EmpytError doesn't appear in a throw declaration, and hence
+  we need to tell SWIG that the dequeue method throws it.  This can
+  now be done via the %catchs feature. */
+%catches(EmptyError) *::dequeue();
+
+
+/* What the catches clause is doing under the covers is this:
+
+%exceptionclass EmptyError;
+
+%exception *::dequeue {
+   try {
+      $action
+   } catch(EmptyError& e) {
+     // Create a new instance of the EmptyError, wrap it as a Ruby object that Ruby owns,
+     // and return it as the exception.  For this to work EmtpyError must inherit from
+     // a standard Ruby exception class such as rb_eRuntimeError.  SWIG automatically does
+     // this when the class is marked as %exceptionclass or is a throws specification.
+     %raise(SWIG_NewPointerObj(new EmptyError(e),SWIGTYPE_p_EmptyError, SWIG_POINTER_OWN), 
+            "EmptyError", SWIGTYPE_p_EmptyError);
+   }
+}
+*/
+
+/* Grab the original header file */
+%include "example.h"
+
+/* Instantiate a few templates */
+%template(IntQueue) Queue<int>;
+%template(DoubleQueue) Queue<double>;
diff --git a/trunk/Examples/ruby/exception_class/runme.rb b/trunk/Examples/ruby/exception_class/runme.rb
new file mode 100644
index 0000000..c198c14
--- /dev/null
+++ b/trunk/Examples/ruby/exception_class/runme.rb
@@ -0,0 +1,45 @@
+require 'example'
+
+q = Example::IntQueue.new(10)
+
+puts "Inserting items into intQueue"
+
+begin
+    0.upto(100) do |i|
+    q.enqueue(i)
+  end
+rescue Example::FullError => e
+  puts "Maxsize is: #{e.maxsize}"
+end
+
+puts "Removing items"
+
+begin
+  loop do
+    q.dequeue()
+  end
+rescue Example::EmptyError => e
+  ## do nothing
+end
+
+q = Example::DoubleQueue.new(1000)
+
+puts "Inserting items into doubleQueue"
+
+begin
+  0.upto(100) do |i|
+    q.enqueue(i*1.5)
+  end
+rescue Example::FullError => e
+  puts "Maxsize is: #{e.maxsize}"
+end
+
+puts "Removing items"
+
+begin
+  loop do
+    q.dequeue()
+  end
+rescue Example::EmptyError => e
+  # do nothing
+end
diff --git a/trunk/Examples/ruby/free_function/Makefile b/trunk/Examples/ruby/free_function/Makefile
new file mode 100644
index 0000000..56c84c6
--- /dev/null
+++ b/trunk/Examples/ruby/free_function/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/free_function/example.cxx b/trunk/Examples/ruby/free_function/example.cxx
new file mode 100644
index 0000000..402a947
--- /dev/null
+++ b/trunk/Examples/ruby/free_function/example.cxx
@@ -0,0 +1,67 @@
+#include "example.h"
+
+Animal::Animal(const char* name) : name_(name)
+{
+}
+
+Animal::~Animal()
+{
+}
+
+/* Return the animal's name */
+const char* Animal::get_name() const
+{
+	return name_.c_str();
+}
+	
+Zoo::Zoo()
+{
+}
+
+Zoo::~Zoo()
+{
+	IterType iter = this->animals.begin();
+	IterType end = this->animals.end();
+
+	for(; iter != end; ++iter)
+	{
+		Animal* animal = *iter;
+		delete animal;
+	}
+}
+
+/* Create a new animal. */
+Animal* Zoo::create_animal(const char* name)
+{
+	return new Animal(name);
+}
+
+/* Add a new animal to the zoo. */
+void Zoo::add_animal(Animal* animal)
+{
+	animals.push_back(animal);
+}
+
+Animal* Zoo::remove_animal(size_t i)
+{
+	/* Note a production implementation should check
+	   for out of range errors. */
+	Animal* result = this->animals[i];
+	IterType iter = this->animals.begin();
+	std::advance(iter, i);
+	this->animals.erase(iter);
+
+	return result;
+}
+
+/* Return the number of animals in the zoo. */
+size_t Zoo::get_num_animals() const
+{
+	return animals.size();
+}
+
+/* Return a pointer to the ith animal */
+Animal* Zoo::get_animal(size_t i) const
+{
+	return animals[i];
+}
diff --git a/trunk/Examples/ruby/free_function/example.dsp b/trunk/Examples/ruby/free_function/example.dsp
new file mode 100644
index 0000000..9a26322
--- /dev/null
+++ b/trunk/Examples/ruby/free_function/example.dsp
@@ -0,0 +1,154 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/free_function/example.h b/trunk/Examples/ruby/free_function/example.h
new file mode 100644
index 0000000..933bb36
--- /dev/null
+++ b/trunk/Examples/ruby/free_function/example.h
@@ -0,0 +1,49 @@
+#ifndef _EXAMPLE_H_
+#define _EXAMPLE_H_
+
+#include <vector>
+#include <string>
+
+class Animal
+{
+protected:
+	std::string name_;
+public:
+	// Construct an animal with a name
+	Animal(const char* name);
+
+	// Destruct an animal
+	~Animal();
+
+	// Return the animal's name
+	const char* get_name() const;
+};
+	
+class Zoo
+{
+private:
+	typedef std::vector<Animal*> AnimalsType;
+	typedef AnimalsType::iterator IterType;
+protected:
+	AnimalsType animals;
+public:
+	Zoo();
+	~Zoo();	
+
+	/* Create a new animal */
+	static Animal* create_animal(const char* name);
+
+	/* Add a new animal to the zoo */
+	void add_animal(Animal* animal);
+	
+	/* Remove an animal from the zoo */
+	Animal* remove_animal(size_t i);
+
+	/* Return the number of animals in the zoo */
+	size_t get_num_animals() const;
+	
+	/* Return a pointer to the ith animal */
+	Animal* get_animal(size_t i) const;
+};
+
+#endif /*_EXAMPLE_H_*/
diff --git a/trunk/Examples/ruby/free_function/example.i b/trunk/Examples/ruby/free_function/example.i
new file mode 100644
index 0000000..5ab29bd
--- /dev/null
+++ b/trunk/Examples/ruby/free_function/example.i
@@ -0,0 +1,41 @@
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Specify that ownership is transferred to the zoo
+	when calling add_animal */
+%apply SWIGTYPE *DISOWN { Animal* animal };
+
+/* Track objects */
+%trackobjects;
+
+/* Specify the mark function */
+%freefunc Zoo "free_Zoo";
+
+%include "example.h"
+
+%header %{
+	static void free_Zoo(void* ptr) {
+		Zoo* zoo = (Zoo*) ptr;
+
+		/* Loop over each object and call SWIG_RemoveMapping */
+		int count = zoo->get_num_animals();
+
+		for(int i = 0; i < count; ++i) {
+			/* Get an animal */
+			Animal* animal = zoo->get_animal(i);
+			/* Unlink the Ruby object from the C++ object */
+			SWIG_RubyUnlinkObjects(animal);
+			/* Now remove the tracking for this animal */
+			SWIG_RubyRemoveTracking(animal);
+		}
+
+	   /* Now call SWIG_RemoveMapping for the zoo */
+		SWIG_RubyRemoveTracking(ptr);
+
+		/* Now free the zoo which will free the animals it contains */
+		delete zoo;
+	}
+%}
diff --git a/trunk/Examples/ruby/free_function/runme.rb b/trunk/Examples/ruby/free_function/runme.rb
new file mode 100644
index 0000000..1d88b6f
--- /dev/null
+++ b/trunk/Examples/ruby/free_function/runme.rb
@@ -0,0 +1,46 @@
+require 'example'
+
+begin
+  begin
+    # Create an animal and zoo
+    tiger1 = Example::Animal.new("tiger1")
+    zoo = Example::Zoo.new
+  
+    # At the animal to the zoo - this will transfer ownership
+    # of the underlying C++ object to the C++ zoo object
+    zoo.add_animal(tiger1)
+
+    # get the id of the tiger
+    id1 = tiger1.object_id
+
+    # Unset the tiger
+    tiger1 = nil
+  end
+
+  # Force a gc
+  GC.start
+
+  # Get the tiger and its id
+  tiger2 = zoo.get_animal(0)
+  id2 = tiger2.object_id
+
+  # The ids should not be the same
+  if id1==id2
+    raise RuntimeError, "Id's should not be the same"
+  end
+
+  zoo = nil
+end
+
+GC.start
+
+# This method is no longer valid since the zoo freed the underlying
+# C++ object
+ok = false
+begin
+  puts tiger2.get_name
+rescue ObjectPreviouslyDeleted => error
+  ok = true
+end
+
+raise(RuntimeError, "Incorrect exception raised - should be ObjectPreviouslyDeleted") unless ok
diff --git a/trunk/Examples/ruby/funcptr/Makefile b/trunk/Examples/ruby/funcptr/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/funcptr/example.c b/trunk/Examples/ruby/funcptr/example.c
new file mode 100644
index 0000000..99583b7
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr/example.c
@@ -0,0 +1,17 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
diff --git a/trunk/Examples/ruby/funcptr/example.h b/trunk/Examples/ruby/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/ruby/funcptr/example.i b/trunk/Examples/ruby/funcptr/example.i
new file mode 100644
index 0000000..39390da
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr/example.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+
diff --git a/trunk/Examples/ruby/funcptr/index.html b/trunk/Examples/ruby/funcptr/index.html
new file mode 100644
index 0000000..980106c
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr/index.html
@@ -0,0 +1,90 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:funcptr</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/ruby/funcptr/</tt>
+<hr>
+
+<H2>Pointers to Functions</H2>
+
+<p>
+Okay, just what in the heck does SWIG do with a declaration like this?
+
+<blockquote>
+<pre>
+int do_op(int a, int b, int (*op)(int, int));
+</pre>
+</blockquote>
+
+Well, it creates a wrapper as usual.  Of course, that does raise some
+questions about the third argument (the pointer to a function). 
+
+<p>
+In this case, SWIG will wrap the function pointer as it does for all other
+pointers.  However, in order to actually call this function from a script,
+you will need to pass some kind of C function pointer object.  In C,
+this is easy, you just supply a function name as an argument like this:
+
+<blockquote>
+<pre>
+/* Some callback function */
+int add(int a, int b) {
+   return a+b;
+} 
+...
+int r = do_op(x,y,add);
+</pre>
+</blockquote>
+
+To make this work with SWIG, you will need to do a little extra work.  Specifically,
+you need to create some function pointer objects using the %constant directive like this:
+
+<blockquote>
+<pre>
+%constant(int (*)(int,int)) ADD = add;
+</pre>
+</blockquote>
+
+Now, in a script, you would do this:
+
+<blockquote>
+<pre>
+r = do_op(x,y, ADD)
+</pre>
+</blockquote>
+
+<h2>An Example</h2>
+
+Here are some files that illustrate this with a simple example:
+
+<ul>
+<li><a href="example.c">example.c</a>
+<li><a href="example.h">example.h</a>
+<li><a href="example.i">example.i</a> (SWIG interface)
+<li><a href="runme.rb">runme.rb</a> (Sample script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>The value of a function pointer must correspond to a function written in C or C++.
+It is not possible to pass an arbitrary Ruby proc object in as a substitute for a C 
+function pointer.
+
+<p>
+<li>A ruby proc can be used as a C/C++ callback if you write some
+clever typemaps and are very careful about how you create your extension.
+This is an advanced topic not covered here.
+</ul>
+
+<hr>
+</body>
+</html>
+
+
+
+
diff --git a/trunk/Examples/ruby/funcptr/runme.rb b/trunk/Examples/ruby/funcptr/runme.rb
new file mode 100644
index 0000000..4a5b014
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr/runme.rb
@@ -0,0 +1,21 @@
+# file: runme.rb
+
+require 'example'
+
+a = 37
+b = 42
+
+# Now call our C function with a bunch of callbacks
+
+print "Trying some C callback functions\n"
+print "    a        = #{a}\n"
+print "    b        = #{b}\n"
+print "    ADD(a,b) = ", Example::do_op(a,b,Example::ADD),"\n"
+print "    SUB(a,b) = ", Example::do_op(a,b,Example::SUB),"\n"
+print "    MUL(a,b) = ", Example::do_op(a,b,Example::MUL),"\n"
+
+print "Here is what the C callback function objects look like in Ruby\n"
+print "    ADD      = #{Example::ADD}\n"
+print "    SUB      = #{Example::SUB}\n"
+print "    MUL      = #{Example::MUL}\n"
+
diff --git a/trunk/Examples/ruby/funcptr2/Makefile b/trunk/Examples/ruby/funcptr2/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr2/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/funcptr2/example.c b/trunk/Examples/ruby/funcptr2/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr2/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/ruby/funcptr2/example.h b/trunk/Examples/ruby/funcptr2/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr2/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/ruby/funcptr2/example.i b/trunk/Examples/ruby/funcptr2/example.i
new file mode 100644
index 0000000..681775a
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr2/example.i
@@ -0,0 +1,18 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%callback("%(upper)s");
+int add(int, int);
+int sub(int, int);
+int mul(int, int);
+%nocallback;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/ruby/funcptr2/runme.rb b/trunk/Examples/ruby/funcptr2/runme.rb
new file mode 100644
index 0000000..99b9842
--- /dev/null
+++ b/trunk/Examples/ruby/funcptr2/runme.rb
@@ -0,0 +1,22 @@
+require 'example'
+
+a = 37
+b = 42
+
+# Now call our C function with a bunch of callbacks
+
+puts "Trying some C callback functions"
+puts "    a        = #{a}"
+puts "    b        = #{b}"
+puts "    ADD(a,b) = #{Example.do_op(a,b,Example::ADD)}"
+puts "    SUB(a,b) = #{Example.do_op(a,b,Example::SUB)}"
+puts "    MUL(a,b) = #{Example.do_op(a,b,Example::MUL)}"
+
+puts "Here is what the C callback function objects look like in Ruby"
+puts "    ADD      = #{Example::ADD}"
+puts "    SUB      = #{Example::SUB}"
+puts "    MUL      = #{Example::MUL}"
+
+puts "Call the functions directly..."
+puts "    add(a,b) = #{Example.add(a,b)}"
+puts "    sub(a,b) = #{Example.sub(a,b)}"
diff --git a/trunk/Examples/ruby/functor/Makefile b/trunk/Examples/ruby/functor/Makefile
new file mode 100644
index 0000000..730698d
--- /dev/null
+++ b/trunk/Examples/ruby/functor/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/functor/example.i b/trunk/Examples/ruby/functor/example.i
new file mode 100644
index 0000000..903c978
--- /dev/null
+++ b/trunk/Examples/ruby/functor/example.i
@@ -0,0 +1,26 @@
+/* File : example.i */
+%module example
+
+%inline %{
+// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514
+template<class T> class Sum {
+   T res;
+public:
+   Sum(T i = 0) : res(i) { }
+   void operator() (T x) { res += x; }
+   T result() const { return res; }
+};
+
+%}
+
+/**
+ * Rename the application operator to call() for Ruby.
+ * Note: this is normally automatic, but if you had to do it yourself
+ * you would use this directive:
+ *
+ *      %rename(call) *::operator();
+ */
+
+// Instantiate a few versions
+%template(IntSum) Sum<int>;
+%template(DoubleSum) Sum<double>;
diff --git a/trunk/Examples/ruby/functor/runme.rb b/trunk/Examples/ruby/functor/runme.rb
new file mode 100644
index 0000000..3f78dce
--- /dev/null
+++ b/trunk/Examples/ruby/functor/runme.rb
@@ -0,0 +1,17 @@
+# Operator overloading example
+require 'example'
+
+a = Example::IntSum.new(0)
+b = Example::DoubleSum.new(100.0)
+
+# Use the objects.  They should be callable just like a normal
+# Ruby function.
+
+(0..100).each do |i|
+  a.call(i)              # note: function call
+  b.call(Math.sqrt(i))   # note: function call
+end
+
+puts a.result
+puts b.result
+
diff --git a/trunk/Examples/ruby/hashargs/Makefile b/trunk/Examples/ruby/hashargs/Makefile
new file mode 100755
index 0000000..a2fbbd3
--- /dev/null
+++ b/trunk/Examples/ruby/hashargs/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/hashargs/example.i b/trunk/Examples/ruby/hashargs/example.i
new file mode 100755
index 0000000..159bbd3
--- /dev/null
+++ b/trunk/Examples/ruby/hashargs/example.i
@@ -0,0 +1,36 @@
+%module example
+
+%typemap(in) (int nattributes, const char **names, const int *values) (VALUE keys_ary, int i, VALUE key, VALUE val) {
+  Check_Type($input, T_HASH);
+  $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
+  $2 = NULL;
+  $3 = NULL;
+  if ($1 > 0) {
+    $2 = (char **) malloc($1*sizeof(char *));
+    $3 = (int *) malloc($1*sizeof(int));
+    keys_ary = rb_funcall($input, rb_intern("keys"), 0, NULL);
+    for (i = 0; i < $1; i++) {
+      key = rb_ary_entry(keys_ary, i);
+      val = rb_hash_aref($input, key);
+      Check_Type(key, T_STRING);
+      Check_Type(val, T_FIXNUM);
+      $2[i] = STR2CSTR(key);
+      $3[i] = NUM2INT(val);
+    }
+  }
+}
+
+%typemap(freearg) (int nattributes, const char **names, const int *values) {
+  free((void *) $2);
+  free((void *) $3);
+}
+
+%inline %{
+void setVitalStats(const char *person, int nattributes, const char **names, const int *values) {
+  int i;
+  printf("Name: %s\n", person);
+  for (i = 0; i < nattributes; i++) {
+    printf("  %s => %d\n", names[i], values[i]);
+  }
+}
+%}
diff --git a/trunk/Examples/ruby/hashargs/runme.rb b/trunk/Examples/ruby/hashargs/runme.rb
new file mode 100755
index 0000000..0b06f69
--- /dev/null
+++ b/trunk/Examples/ruby/hashargs/runme.rb
@@ -0,0 +1,26 @@
+require 'example'
+
+include Example
+
+# Pass arguments in as one or more key-value pairs
+setVitalStats("Fred",
+              'age'    => 42,
+              'weight' => 270
+              )
+
+# The order doesn't matter
+setVitalStats("Sally",
+              'age'    => 29,
+              'weight' => 115,
+	      'height' => 72
+              )
+
+# Can also pass a hash directly
+params = {
+    'ears' => 2,
+    'eyes' => 2
+}
+setVitalStats("Bob", params)
+
+# An empty hash is fine too
+setVitalStats("Joe", {})
diff --git a/trunk/Examples/ruby/import/Makefile b/trunk/Examples/ruby/import/Makefile
new file mode 100644
index 0000000..acae6e6
--- /dev/null
+++ b/trunk/Examples/ruby/import/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+ 
+all::
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/import/README b/trunk/Examples/ruby/import/README
new file mode 100644
index 0000000..c529cd9
--- /dev/null
+++ b/trunk/Examples/ruby/import/README
@@ -0,0 +1,39 @@
+This example tests the %import directive and working with multiple modules.
+
+Use 'ruby runme.rb' to run a test.
+
+Overview:
+---------
+
+The example defines 4 different extension modules--each wrapping
+a separate C++ class.
+
+     base.i     -  Base class
+     foo.i      -  Foo class derived from Base
+     bar.i      -  Bar class derived from Base
+     spam.i     -  Spam class derived from Bar
+
+Each module uses %import to refer to another module.  For
+example, the 'foo.i' module uses '%import base.i' to get
+definitions for its base class.
+
+If everything is okay, all of the modules will load properly and
+type checking will work correctly. Caveat: Some compilers, for example
+gcc-3.2.x, generate broken vtables with the inline methods in this test.
+This is not a SWIG problem and can usually be solved with non-inlined
+destructors compiled into separate shared objects/DLLs.
+
+Unix:
+-----
+- Run make
+- Run the test as described above
+
+Windows:
+--------
+- Use the Visual C++ 6 workspace file (example.dsw). Build the runtime
+  project DLL first followed by the other 4 DLLs as they all have a
+  dependency on the runtime DLL. The Batch build option in the Build menu
+  is usually the easiest way to do this. Only use the Release builds not
+  the Debug builds.
+- Run the test as described above
+
diff --git a/trunk/Examples/ruby/import/bar.dsp b/trunk/Examples/ruby/import/bar.dsp
new file mode 100644
index 0000000..dd09ca0
--- /dev/null
+++ b/trunk/Examples/ruby/import/bar.dsp
@@ -0,0 +1,146 @@
+# Microsoft Developer Studio Project File - Name="bar" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=bar - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak" CFG="bar - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "bar - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "bar - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"bar.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"bar.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "bar - Win32 Debug"

+# Name "bar - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\bar_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\bar.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\bar.i

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/import/bar.h b/trunk/Examples/ruby/import/bar.h
new file mode 100644
index 0000000..1c99f28
--- /dev/null
+++ b/trunk/Examples/ruby/import/bar.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Bar : public Base {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual const char * A() const { 
+    return "Bar::A";
+  }
+  const char * B() const {
+    return "Bar::B";
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Bar *fromBase(Base *b) {
+    return dynamic_cast<Bar *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/ruby/import/bar.i b/trunk/Examples/ruby/import/bar.i
new file mode 100644
index 0000000..5816cbe
--- /dev/null
+++ b/trunk/Examples/ruby/import/bar.i
@@ -0,0 +1,9 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+
diff --git a/trunk/Examples/ruby/import/base.dsp b/trunk/Examples/ruby/import/base.dsp
new file mode 100644
index 0000000..2bd4fa2
--- /dev/null
+++ b/trunk/Examples/ruby/import/base.dsp
@@ -0,0 +1,146 @@
+# Microsoft Developer Studio Project File - Name="base" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=base - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak" CFG="base - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "base - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "base - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"base.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"base.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "base - Win32 Debug"

+# Name "base - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\base_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\base.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\base.i

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/import/base.h b/trunk/Examples/ruby/import/base.h
new file mode 100644
index 0000000..fec0f32
--- /dev/null
+++ b/trunk/Examples/ruby/import/base.h
@@ -0,0 +1,16 @@
+class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual const char * A() const {
+         return "Base::A";
+     }
+     const char * B() const {
+       return "Base::B";
+     }
+     virtual Base *toBase() {
+       return static_cast<Base *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/ruby/import/base.i b/trunk/Examples/ruby/import/base.i
new file mode 100644
index 0000000..f6e19ef
--- /dev/null
+++ b/trunk/Examples/ruby/import/base.i
@@ -0,0 +1,6 @@
+%module base
+%{
+#include "base.h"
+%}
+
+%include base.h
diff --git a/trunk/Examples/ruby/import/example.dsw b/trunk/Examples/ruby/import/example.dsw
new file mode 100644
index 0000000..d395d46
--- /dev/null
+++ b/trunk/Examples/ruby/import/example.dsw
@@ -0,0 +1,65 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00

+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!

+

+###############################################################################

+

+Project: "bar"=.\bar.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "base"=.\base.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "foo"=.\foo.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "spam"=.\spam.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Global:

+

+Package=<5>

+{{{

+}}}

+

+Package=<3>

+{{{

+}}}

+

+###############################################################################

+

diff --git a/trunk/Examples/ruby/import/foo.dsp b/trunk/Examples/ruby/import/foo.dsp
new file mode 100644
index 0000000..2a764bb
--- /dev/null
+++ b/trunk/Examples/ruby/import/foo.dsp
@@ -0,0 +1,146 @@
+# Microsoft Developer Studio Project File - Name="foo" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=foo - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak" CFG="foo - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "foo - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "foo - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"foo.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"foo.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "foo - Win32 Debug"

+# Name "foo - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\foo_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\foo.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\foo.i

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/import/foo.h b/trunk/Examples/ruby/import/foo.h
new file mode 100644
index 0000000..1abe2c0
--- /dev/null
+++ b/trunk/Examples/ruby/import/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Foo : public Base {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual const char * A() const { 
+    return "Foo::A";
+  }
+  const char * B() const {
+    return "Foo::B";
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Foo *fromBase(Base *b) {
+    return dynamic_cast<Foo *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/ruby/import/foo.i b/trunk/Examples/ruby/import/foo.i
new file mode 100644
index 0000000..27feb2e
--- /dev/null
+++ b/trunk/Examples/ruby/import/foo.i
@@ -0,0 +1,8 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
diff --git a/trunk/Examples/ruby/import/runme.rb b/trunk/Examples/ruby/import/runme.rb
new file mode 100644
index 0000000..32ca482
--- /dev/null
+++ b/trunk/Examples/ruby/import/runme.rb
@@ -0,0 +1,90 @@
+# file: runme.rb
+# Test various properties of classes defined in separate modules
+
+puts "Testing the %import directive"
+
+require 'base'
+require 'foo'
+require 'bar'
+require 'spam'
+
+# Create some objects
+
+puts "Creating some objects"
+
+a = Base::Base.new
+b = Foo::Foo.new
+c = Bar::Bar.new
+d = Spam::Spam.new
+
+# Try calling some methods
+puts "Testing some methods"
+puts "Should see 'Base::A' ---> #{a.A}"
+puts "Should see 'Base::B' ---> #{a.B}"
+
+puts  "Should see 'Foo::A' ---> #{b.A}"
+puts  "Should see 'Foo::B' ---> #{b.B}"
+
+puts  "Should see 'Bar::A' ---> #{c.A}"
+puts  "Should see 'Bar::B' ---> #{c.B}"
+
+puts  "Should see 'Spam::A' ---> #{d.A}"
+puts  "Should see 'Spam::B' ---> #{d.B}"
+
+# Try some casts
+
+puts "\nTesting some casts\n"
+
+x = a.toBase
+puts "Should see 'Base::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = b.toBase
+puts "Should see 'Foo::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = c.toBase
+puts "Should see 'Bar::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = d.toBase
+puts "Should see 'Spam::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = d.toBar
+puts "Should see 'Bar::B' ---> #{x.B}"
+
+puts "\nTesting some dynamic casts\n"
+x = d.toBase
+
+puts " Spam -> Base -> Foo : "
+y = Foo::Foo.fromBase(x)
+if y != nil
+  puts "bad swig"
+else
+  puts "good swig"
+end
+
+puts " Spam -> Base -> Bar : "
+y = Bar::Bar.fromBase(x)
+if y != nil
+  puts "good swig"
+else
+  puts "bad swig"
+end
+      
+puts " Spam -> Base -> Spam : "
+y = Spam::Spam.fromBase(x)
+if y != nil
+  puts "good swig"
+else
+  puts "bad swig"
+end
+
+puts " Foo -> Spam : "
+y = Spam::Spam.fromBase(b)
+if y != nil
+  puts "bad swig"
+else
+  puts "good swig"
+end
diff --git a/trunk/Examples/ruby/import/spam.dsp b/trunk/Examples/ruby/import/spam.dsp
new file mode 100644
index 0000000..d2d7158
--- /dev/null
+++ b/trunk/Examples/ruby/import/spam.dsp
@@ -0,0 +1,146 @@
+# Microsoft Developer Studio Project File - Name="spam" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=spam - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak" CFG="spam - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "spam - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "spam - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"spam.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"spam.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "spam - Win32 Debug"

+# Name "spam - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\spam_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\spam.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\spam.i

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/import/spam.h b/trunk/Examples/ruby/import/spam.h
new file mode 100644
index 0000000..57db845
--- /dev/null
+++ b/trunk/Examples/ruby/import/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+class Spam : public Bar {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual const char * A() const { 
+    return "Spam::A";
+  }
+  const char * B() const {
+    return "Spam::B";
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  virtual Bar *toBar() {
+    return static_cast<Bar *>(this);
+  }
+  static Spam *fromBase(Base *b) {
+    return dynamic_cast<Spam *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/ruby/import/spam.i b/trunk/Examples/ruby/import/spam.i
new file mode 100644
index 0000000..d3d9121
--- /dev/null
+++ b/trunk/Examples/ruby/import/spam.i
@@ -0,0 +1,9 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+
diff --git a/trunk/Examples/ruby/import_template/Makefile b/trunk/Examples/ruby/import_template/Makefile
new file mode 100644
index 0000000..acae6e6
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+ 
+all::
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/import_template/README b/trunk/Examples/ruby/import_template/README
new file mode 100644
index 0000000..9170a7a
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/README
@@ -0,0 +1,30 @@
+This example tests the %import directive and working with multiple modules.
+
+Use 'ruby runme.rb' to run a test.
+
+Overview:
+---------
+
+The example defines 4 different extension modules--each wrapping
+a separate C++ class.
+
+     base.i     -  Base class
+     foo.i      -  Foo class derived from Base
+     bar.i      -  Bar class derived from Base
+     spam.i     -  Spam class derived from Bar
+
+Each module uses %import to refer to another module.  For
+example, the 'foo.i' module uses '%import base.i' to get
+definitions for its base class.
+
+If everything is okay, all of the modules will load properly and
+type checking will work correctly. Caveat: Some compilers, for example
+gcc-3.2.x, generate broken vtables with the inline methods in this test.
+This is not a SWIG problem and can usually be solved with non-inlined
+destructors compiled into separate shared objects/DLLs.
+
+Unix:
+-----
+- Run make
+- Run the test as described above
+
diff --git a/trunk/Examples/ruby/import_template/bar.h b/trunk/Examples/ruby/import_template/bar.h
new file mode 100644
index 0000000..1aa907d
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/bar.h
@@ -0,0 +1,22 @@
+#include "base.h"
+
+template<class T> class Bar : public Base<T> {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual const char * A() const { 
+    return "Bar::A";
+  }
+  const char * B() const {
+    return "Bar::B";
+  }
+  virtual Base<T> *toBase() {
+    return static_cast<Base<T> *>(this);
+  }
+  static Bar<T> *fromBase(Base<T> *b) {
+    return dynamic_cast<Bar<T> *>(b);
+  }
+
+};
+
+
diff --git a/trunk/Examples/ruby/import_template/bar.i b/trunk/Examples/ruby/import_template/bar.i
new file mode 100644
index 0000000..357de0d
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/bar.i
@@ -0,0 +1,11 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+%template(IntBar) Bar<int>;
+
+
diff --git a/trunk/Examples/ruby/import_template/base.h b/trunk/Examples/ruby/import_template/base.h
new file mode 100644
index 0000000..e88c440
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/base.h
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+template<class T> class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual const char * A() const {
+         return "Base::A";
+     }
+     const char * B() const {
+       return "Base::B";
+     }
+     virtual Base<T> *toBase() {
+       return static_cast<Base<T> *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/ruby/import_template/base.i b/trunk/Examples/ruby/import_template/base.i
new file mode 100644
index 0000000..bcf1a5f
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/base.i
@@ -0,0 +1,7 @@
+%module base
+%{
+#include "base.h"
+%}
+
+%include base.h
+%template(IntBase) Base<int>;
diff --git a/trunk/Examples/ruby/import_template/foo.h b/trunk/Examples/ruby/import_template/foo.h
new file mode 100644
index 0000000..6262574
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+template<class T> class Foo : public Base<T> {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual const char * A() const { 
+    return "Foo::A";
+  }
+  const char * B() const {
+    return "Foo::B";
+  }
+  virtual Base<T> *toBase() {
+    return static_cast<Base<T> *>(this);
+  }
+  static Foo<T> *fromBase(Base<T> *b) {
+    return dynamic_cast<Foo<T> *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/ruby/import_template/foo.i b/trunk/Examples/ruby/import_template/foo.i
new file mode 100644
index 0000000..37e655e
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/foo.i
@@ -0,0 +1,10 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
+%template(IntFoo) Foo<int>;
+
diff --git a/trunk/Examples/ruby/import_template/runme.rb b/trunk/Examples/ruby/import_template/runme.rb
new file mode 100644
index 0000000..b9ca19f
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/runme.rb
@@ -0,0 +1,92 @@
+# file: runme.rb
+# Test various properties of classes defined in separate modules
+
+puts "Testing the %import directive with templates"
+
+require 'base'
+require 'foo'
+require 'bar'
+require 'spam'
+
+# Create some objects
+
+puts "Creating some objects"
+
+a = Base::IntBase.new
+b = Foo::IntFoo.new
+c = Bar::IntBar.new
+d = Spam::IntSpam.new
+
+# Try calling some methods
+puts "Testing some methods"
+puts ""
+puts "Should see 'Base::A' ---> #{a.A}"
+puts "Should see 'Base::B' ---> #{a.B}"
+
+puts "Should see 'Foo::A' ---> #{b.A}"
+puts "Should see 'Foo::B' ---> #{b.B}"
+
+puts "Should see 'Bar::A' ---> #{c.A}"
+puts "Should see 'Bar::B' ---> #{c.B}"
+
+puts "Should see 'Spam::A' ---> #{d.A}"
+puts "Should see 'Spam::B' ---> #{d.B}"
+
+# Try some casts
+
+puts "\nTesting some casts\n"
+puts ""
+
+x = a.toBase
+puts "Should see 'Base::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = b.toBase
+puts "Should see 'Foo::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = c.toBase
+puts "Should see 'Bar::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = d.toBase
+puts "Should see 'Spam::A' ---> #{x.A}"
+puts "Should see 'Base::B' ---> #{x.B}"
+
+x = d.toBar
+puts "Should see 'Bar::B' ---> #{x.B}"
+
+puts "\nTesting some dynamic casts\n"
+x = d.toBase
+
+puts " Spam -> Base -> Foo : "
+y = Foo::IntFoo.fromBase(x)
+if y != nil
+      puts "bad swig"
+else
+      puts "good swig"
+end
+
+puts " Spam -> Base -> Bar : "
+y = Bar::IntBar.fromBase(x)
+if y != nil
+      puts "good swig"
+else
+      puts "bad swig"
+end
+      
+puts " Spam -> Base -> Spam : "
+y = Spam::IntSpam.fromBase(x)
+if y != nil
+      puts "good swig"
+else
+      puts "bad swig"
+end
+
+puts " Foo -> Spam : "
+y = Spam::IntSpam.fromBase(b)
+if y != nil
+      puts "bad swig"
+else
+      puts "good swig"
+end
diff --git a/trunk/Examples/ruby/import_template/spam.h b/trunk/Examples/ruby/import_template/spam.h
new file mode 100644
index 0000000..a27b088
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+template<class T> class Spam : public Bar<T> {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual const char * A() const { 
+    return "Spam::A";
+  }
+  const char * B() const {
+    return "Spam::B";
+  }
+  virtual Base<T> *toBase() {
+    return static_cast<Base<T> *>(this);
+  }
+  virtual Bar<T> *toBar() {
+    return static_cast<Bar<T> *>(this);
+  }
+  static Spam<T> *fromBase(Base<T> *b) {
+    return dynamic_cast<Spam<T> *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/ruby/import_template/spam.i b/trunk/Examples/ruby/import_template/spam.i
new file mode 100644
index 0000000..ff0ca11
--- /dev/null
+++ b/trunk/Examples/ruby/import_template/spam.i
@@ -0,0 +1,10 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+%template(IntSpam) Spam<int>;
+
diff --git a/trunk/Examples/ruby/index.html b/trunk/Examples/ruby/index.html
new file mode 100644
index 0000000..f04146e
--- /dev/null
+++ b/trunk/Examples/ruby/index.html
@@ -0,0 +1,94 @@
+
+<head>
+<title>SWIG:Examples:ruby</title>
+</head>
+
+<body bgcolor="#ffffff">
+<H1>SWIG Ruby Examples</H1>
+
+<p>
+The following examples illustrate the use of SWIG with Ruby.
+
+<ul>
+<li><a href="simple/index.html">simple</a>.  A minimal example showing how SWIG can
+be used to wrap a C function, a global variable, and a constant.
+<li><a href="constants/index.html">constants</a>.  This shows how preprocessor macros and
+certain C declarations are turned into constants.
+<li><a href="variables/index.html">variables</a>. An example showing how to access C global variables from Ruby.
+<li><a href="value/index.html">value</a>. How to pass and return structures by value.
+<li><a href="class/index.html">class</a>. Wrapping a simple C++ class.
+<li><a href="reference/index.html">reference</a>. C++ references.
+<li><a href="pointer/index.html">pointer</a>. Simple pointer handling.
+<li><a href="funcptr/index.html">funcptr</a>. Pointers to functions.
+<li><a href="enum/index.html">enum</a>. Enumeration.
+</ul>
+
+<h2>Compilation Issues</h2>
+
+<ul>
+<li>To create a Ruby extension, SWIG is run with the following options:
+
+<blockquote>
+<pre>
+% swig -ruby interface.i
+</pre>
+</blockquote>
+
+<li>
+Please see the <a href="../../Doc/Manual/Windows.html">Windows</a> page in the main manual for information on using the examples on Windows. <p>
+</li>
+
+<li>On Unix the compilation of examples is done using the file <tt>Example/Makefile</tt>.  This
+makefile performs a manual module compilation which is platform specific.  Typically,
+the steps look like this (Linux):
+
+<blockquote>
+<pre>
+% swig -ruby interface.i
+% gcc -fpic -c interface_wrap.c -I/usr/local/lib/ruby/1.4/i686-linux
+% gcc -shared interface_wrap.o $(OBJS) -o interface.so 
+% ruby
+require 'interface'
+Interface.blah(...)
+...
+</pre>
+</blockquote>
+
+<li>The politically "correct" way to compile a Ruby extension is to follow the steps
+described <tt>README.EXT</tt> in Ruby distribution:
+
+<p>
+<ol>
+<li>Create a file called <tt>extconf.rb</tt> that looks like the following:
+
+<blockquote>
+<pre>
+require 'mkmf'
+create_makefile('interface')
+</pre>
+</blockquote>
+<li>Type the following to build the extension:
+
+<blockquote>
+<pre>
+% ruby extconf.rb
+% make
+</pre>
+</blockquote>
+</ol>
+</ul>
+
+<h2>Compatibility</h2>
+
+The examples have been extensively tested on the following platforms:
+
+<ul>
+<li>Linux
+</ul>
+
+Your mileage may vary.  If you experience a problem, please let us know by 
+contacting us on the <a href="http://www.swig.org/mail.html">mailing lists</a>.
+</body>
+</html>
+
+
diff --git a/trunk/Examples/ruby/java/Example.java b/trunk/Examples/ruby/java/Example.java
new file mode 100644
index 0000000..91ddb1a
--- /dev/null
+++ b/trunk/Examples/ruby/java/Example.java
@@ -0,0 +1,29 @@
+public class Example {
+    public   int      mPublicInt;
+    
+    public Example() {
+	mPublicInt = 0;
+    }
+    
+    public Example(int IntVal) {
+	mPublicInt = IntVal;
+    }
+    
+    
+    public int Add(int a, int b) {
+	return (a+b);
+    }
+    
+    public float Add(float a, float b) {
+	return (a+b);
+    }
+    
+    public String Add(String a, String b) {
+	return (a+b);
+    }
+    
+    public Example Add(Example a, Example b) {
+	return new Example(a.mPublicInt + b.mPublicInt);
+    }
+}
+
diff --git a/trunk/Examples/ruby/java/Makefile b/trunk/Examples/ruby/java/Makefile
new file mode 100644
index 0000000..e525d88
--- /dev/null
+++ b/trunk/Examples/ruby/java/Makefile
@@ -0,0 +1,26 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all:: Example.class
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj" \
+	CXXSHARED="gcj -fpic -shared Example.class" LIBS="-lstdc++" DEFS='' ruby_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile python_clean
+	rm -f *.class Example.h
+
+check: all
+
+run:
+	ruby runme.rb
+
+Example.class: Example.java
+	gcj -fPIC -C -c -g Example.java
+	gcjh  Example
+
diff --git a/trunk/Examples/ruby/java/example.i b/trunk/Examples/ruby/java/example.i
new file mode 100644
index 0000000..13d5b5e
--- /dev/null
+++ b/trunk/Examples/ruby/java/example.i
@@ -0,0 +1,9 @@
+%module example
+%include <cni.i>
+
+%{
+#include "Example.h"
+%}
+
+
+%include Example.h
diff --git a/trunk/Examples/ruby/java/runme.rb b/trunk/Examples/ruby/java/runme.rb
new file mode 100644
index 0000000..fc018b7
--- /dev/null
+++ b/trunk/Examples/ruby/java/runme.rb
@@ -0,0 +1,18 @@
+require 'example'
+
+Example.JvCreateJavaVM(nil)
+Example.JvAttachCurrentThread(nil, nil)
+
+e1 = Example::Example.new(1)
+e2 = Example::Example.new(2)
+
+print e1.Add(1,2),"\n"
+print e1.Add(1.0,2.0),"\n"
+e3 = e1.Add(e1,e2)
+print e3.mPublicInt,"\n"
+
+
+print e1.Add("1","2"),"\n"
+
+Example.JvDetachCurrentThread()
+
diff --git a/trunk/Examples/ruby/mark_function/Makefile b/trunk/Examples/ruby/mark_function/Makefile
new file mode 100644
index 0000000..56c84c6
--- /dev/null
+++ b/trunk/Examples/ruby/mark_function/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/mark_function/example.cxx b/trunk/Examples/ruby/mark_function/example.cxx
new file mode 100644
index 0000000..504e8fc
--- /dev/null
+++ b/trunk/Examples/ruby/mark_function/example.cxx
@@ -0,0 +1,61 @@
+#include "example.h"
+
+Animal::Animal(const char* name) : name_(name)
+{
+}
+
+Animal::~Animal()
+{
+	name_ = "Destroyed";
+}
+
+/* Return the animal's name */
+const char* Animal::get_name() const
+{
+	return name_.c_str();
+}
+	
+Zoo::Zoo()
+{
+}
+
+Zoo::~Zoo()
+{
+	return;
+}
+
+/* Create a new animal. */
+Animal* Zoo::create_animal(const char* name)
+{
+	return new Animal(name);
+}
+
+/* Add a new animal to the zoo. */
+void Zoo::add_animal(Animal* animal)
+{
+	animals.push_back(animal);
+}
+
+Animal* Zoo::remove_animal(size_t i)
+{
+	/* Note a production implementation should check
+	   for out of range errors. */
+	Animal* result = this->animals[i];
+	IterType iter = this->animals.begin();
+	std::advance(iter, i);
+	this->animals.erase(iter);
+
+	return result;
+}
+
+/* Return the number of animals in the zoo. */
+size_t Zoo::get_num_animals() const
+{
+	return animals.size();
+}
+
+/* Return a pointer to the ith animal */
+Animal* Zoo::get_animal(size_t i) const
+{
+	return animals[i];
+}
diff --git a/trunk/Examples/ruby/mark_function/example.dsp b/trunk/Examples/ruby/mark_function/example.dsp
new file mode 100644
index 0000000..9a26322
--- /dev/null
+++ b/trunk/Examples/ruby/mark_function/example.dsp
@@ -0,0 +1,154 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -c++ -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/mark_function/example.h b/trunk/Examples/ruby/mark_function/example.h
new file mode 100644
index 0000000..933bb36
--- /dev/null
+++ b/trunk/Examples/ruby/mark_function/example.h
@@ -0,0 +1,49 @@
+#ifndef _EXAMPLE_H_
+#define _EXAMPLE_H_
+
+#include <vector>
+#include <string>
+
+class Animal
+{
+protected:
+	std::string name_;
+public:
+	// Construct an animal with a name
+	Animal(const char* name);
+
+	// Destruct an animal
+	~Animal();
+
+	// Return the animal's name
+	const char* get_name() const;
+};
+	
+class Zoo
+{
+private:
+	typedef std::vector<Animal*> AnimalsType;
+	typedef AnimalsType::iterator IterType;
+protected:
+	AnimalsType animals;
+public:
+	Zoo();
+	~Zoo();	
+
+	/* Create a new animal */
+	static Animal* create_animal(const char* name);
+
+	/* Add a new animal to the zoo */
+	void add_animal(Animal* animal);
+	
+	/* Remove an animal from the zoo */
+	Animal* remove_animal(size_t i);
+
+	/* Return the number of animals in the zoo */
+	size_t get_num_animals() const;
+	
+	/* Return a pointer to the ith animal */
+	Animal* get_animal(size_t i) const;
+};
+
+#endif /*_EXAMPLE_H_*/
diff --git a/trunk/Examples/ruby/mark_function/example.i b/trunk/Examples/ruby/mark_function/example.i
new file mode 100644
index 0000000..6380fa0
--- /dev/null
+++ b/trunk/Examples/ruby/mark_function/example.i
@@ -0,0 +1,37 @@
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Tell SWIG that create_animal creates a new object */
+%newobject Zoo::create_animal;
+
+/* Keep track of mappings between C/C++ structs/classes
+   and Ruby objects so we can implement a mark function. */
+%trackobjects;
+
+
+/* Specify the mark function */
+%markfunc Zoo "mark_Zoo";
+
+%include "example.h"
+
+%header %{
+	static void mark_Zoo(void* ptr) {
+		Zoo* zoo = (Zoo*) ptr;
+
+		/* Loop over each object and tell the garbage collector
+		   that we are holding a reference to them. */
+		int count = zoo->get_num_animals();
+
+		for(int i = 0; i < count; ++i) {
+			Animal* animal = zoo->get_animal(i);
+			VALUE object = SWIG_RubyInstanceFor(animal);
+
+			if (object != Qnil) {
+				rb_gc_mark(object);
+			}
+		}
+	}
+%}
diff --git a/trunk/Examples/ruby/mark_function/runme.rb b/trunk/Examples/ruby/mark_function/runme.rb
new file mode 100644
index 0000000..6d84ee8
--- /dev/null
+++ b/trunk/Examples/ruby/mark_function/runme.rb
@@ -0,0 +1,23 @@
+require 'example'
+
+# create a zoo
+zoo = Example::Zoo.new
+
+begin
+  # Add in an couple of animals
+  tiger1 = Example::Animal.new("tiger1")
+  zoo.add_animal(tiger1)
+  
+  # unset variables to force gc
+  tiger = nil
+end
+
+GC.start
+
+#  Now get the tiger again
+tiger2 = zoo.get_animal(0)
+
+# Call a method to verify the animal is still valid and not gc'ed
+if tiger2.get_name != "tiger1"
+    raise RuntimeError, "Wrong animal name"
+end	  
diff --git a/trunk/Examples/ruby/multimap/Makefile b/trunk/Examples/ruby/multimap/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/multimap/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/multimap/example.c b/trunk/Examples/ruby/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/ruby/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/ruby/multimap/example.dsp b/trunk/Examples/ruby/multimap/example.dsp
new file mode 100644
index 0000000..ccb99d4
--- /dev/null
+++ b/trunk/Examples/ruby/multimap/example.dsp
@@ -0,0 +1,150 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/multimap/example.i b/trunk/Examples/ruby/multimap/example.i
new file mode 100644
index 0000000..56952ec
--- /dev/null
+++ b/trunk/Examples/ruby/multimap/example.i
@@ -0,0 +1,92 @@
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+%include typemaps.i
+
+extern int    gcd(int x, int y);
+
+%typemap(in) (int argc, char *argv[]) {
+  int i;
+  
+  if (TYPE($input) != T_ARRAY) {
+    SWIG_exception(SWIG_ValueError, "Expected an array");
+  }
+  $1 = RARRAY($input)->len;
+  if ($1 == 0) {
+    SWIG_exception(SWIG_ValueError, "List must contain at least 1 element");
+  }
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i < $1; i++) {
+    VALUE   s = rb_ary_entry($input,i);
+    if (TYPE(s) != T_STRING) {
+      free($2);
+      SWIG_exception(SWIG_ValueError, "List items must be strings");
+    }
+    $2[i] = STR2CSTR(s);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) (int argc, char *argv[]) {
+  free($2);
+}
+
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  if (TYPE($input) != T_STRING) {
+    SWIG_exception(SWIG_ValueError, "Expected a string");
+  }
+  $1 = STR2CSTR($input);
+  $2 = RSTRING($input)->len;
+}
+
+extern int count(char *bytes, int len, char c);
+
+
+/* This example shows how to wrap a function that mutates a string */
+
+%typemap(in) (char *str, int len) {
+  char *temp;
+  if (TYPE($input) != T_STRING) {
+    SWIG_exception(SWIG_ValueError,"Expected a string");
+  }
+  temp = STR2CSTR($input);
+  $2 = RSTRING($input)->len;
+  $1 = (char *) malloc($2+1);
+  memmove($1,temp,$2);
+}
+
+/* Return the mutated string as a new object.  */
+
+%typemap(argout, fragment="output_helper") (char *str, int len) {
+   VALUE o;
+   o = rb_str_new($1,$2);
+   $result = output_helper($result,o);
+   free($1);
+}   
+
+extern void capitalize(char *str, int len);
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
+   }
+}
+
+extern void circle(double cx, double cy);
+
+
diff --git a/trunk/Examples/ruby/multimap/runme.rb b/trunk/Examples/ruby/multimap/runme.rb
new file mode 100755
index 0000000..dde8351
--- /dev/null
+++ b/trunk/Examples/ruby/multimap/runme.rb
@@ -0,0 +1,22 @@
+# file: runme.rb
+
+require 'example'
+
+# Call our gcd() function
+
+x = 42
+y = 105
+g = Example.gcd(x,y)
+printf "The gcd of %d and %d is %d\n",x,y,g
+
+# Call the gcdmain() function
+Example.gcdmain(["gcdmain","42","105"])
+
+# Call the count function
+
+printf "%d\n",Example.count("Hello World","l")
+
+# Call the capitalize function
+
+printf "%s\n",Example.capitalize("hello world")
+
diff --git a/trunk/Examples/ruby/operator/Makefile b/trunk/Examples/ruby/operator/Makefile
new file mode 100644
index 0000000..4c16edb
--- /dev/null
+++ b/trunk/Examples/ruby/operator/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/operator/example.h b/trunk/Examples/ruby/operator/example.h
new file mode 100644
index 0000000..4da6a23
--- /dev/null
+++ b/trunk/Examples/ruby/operator/example.h
@@ -0,0 +1,36 @@
+/* File : example.h */
+#include <math.h>
+
+class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &operator=(const Complex &c) {
+    rpart = c.rpart;
+    ipart = c.ipart;
+    return *this;
+  }
+  Complex operator+(const Complex &c) const {
+    return Complex(rpart+c.rpart, ipart+c.ipart);
+  }
+  Complex operator-(const Complex &c) const {
+    return Complex(rpart-c.rpart, ipart-c.ipart);
+  }
+  Complex operator*(const Complex &c) const {
+    return Complex(rpart*c.rpart - ipart*c.ipart,
+		   rpart*c.ipart + c.rpart*ipart);
+  }
+  Complex operator-() const {
+    return Complex(-rpart, -ipart);
+  }
+  
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+
+
+
+
+  
diff --git a/trunk/Examples/ruby/operator/example.i b/trunk/Examples/ruby/operator/example.i
new file mode 100644
index 0000000..b7e013f
--- /dev/null
+++ b/trunk/Examples/ruby/operator/example.i
@@ -0,0 +1,26 @@
+/* File : example.i */
+%module example
+
+%warnfilter(SWIGWARN_IGNORE_OPERATOR_EQ);
+
+
+%{
+#include "example.h"
+%}
+
+/* This header file is a little tough to handle because it has overloaded
+   operators and constructors.  We're going to try and deal with that here */
+
+/* Grab the original header file */
+%include "example.h"
+
+/* An output method that turns a complex into a short string */
+%extend Complex {
+   char *__str__() {
+       static char temp[512];
+       sprintf(temp,"(%g,%g)", $self->re(), $self->im());
+       return temp;
+   }
+};
+
+
diff --git a/trunk/Examples/ruby/operator/runme.rb b/trunk/Examples/ruby/operator/runme.rb
new file mode 100644
index 0000000..518d91e
--- /dev/null
+++ b/trunk/Examples/ruby/operator/runme.rb
@@ -0,0 +1,25 @@
+# Operator overloading example
+require 'example'
+
+include Example
+
+a = Complex.new(2, 3)
+b = Complex.new(-5, 10)
+
+puts "a   = #{a}"
+puts "b   = #{b}"
+
+c = a + b
+puts "c   = #{c}"
+puts "a*b = #{a*b}"
+puts "a-c = #{a-c}"
+
+# This should invoke Complex's copy constructor
+e = Complex.new(a-c)
+e = a - c
+puts "e   = #{e}"
+
+# Big expression
+f = ((a+b)*(c+b*e)) + (-a)
+puts "f   = #{f}"
+
diff --git a/trunk/Examples/ruby/overloading/Makefile b/trunk/Examples/ruby/overloading/Makefile
new file mode 100644
index 0000000..56c84c6
--- /dev/null
+++ b/trunk/Examples/ruby/overloading/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/overloading/example.cxx b/trunk/Examples/ruby/overloading/example.cxx
new file mode 100644
index 0000000..49d998d
--- /dev/null
+++ b/trunk/Examples/ruby/overloading/example.cxx
@@ -0,0 +1,125 @@
+#include <iostream>
+
+#include "example.h"
+
+// Overloaded constructors for class Bar
+Bar::Bar() {
+    std::cout << "Called Bar::Bar()" << std::endl;
+}
+
+Bar::Bar(const Bar&) {
+    std::cout << "Called Bar::Bar(const Bar&)" << std::endl;
+}
+
+Bar::Bar(double x) {
+    std::cout << "Called Bar::Bar(double) with x = " << x << std::endl;
+}
+
+Bar::Bar(double x, char *y) {
+    std::cout << "Called Bar::Bar(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl;
+}
+
+Bar::Bar(int x, int y) {
+    std::cout << "Called Bar::Bar(int, int) with x, y = " << x << ", " << y << std::endl;
+}
+
+Bar::Bar(char *x) {
+    std::cout << "Called Bar::Bar(char *) with x = \"" << x << "\"" << std::endl;
+}
+
+Bar::Bar(int x) {
+    std::cout << "Called Bar::Bar(int) with x = " << x << std::endl;
+}
+
+Bar::Bar(long x) {
+    std::cout << "Called Bar::Bar(long) with x = " << x << std::endl;
+}
+
+Bar::Bar(Bar *x) {
+    std::cout << "Called Bar::Bar(Bar *) with x = " << x << std::endl;
+}
+
+// Overloaded member functions
+void Bar::foo(const Bar& x) {
+    std::cout << "Called Bar::foo(const Bar&) with &x = " << &x << std::endl;
+}
+
+void Bar::foo(double x) {
+    std::cout << "Called Bar::foo(double) with x = " << x << std::endl;
+}
+
+void Bar::foo(double x, char *y) {
+    std::cout << "Called Bar::foo(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl;
+}
+
+void Bar::foo(int x, int y) {
+    std::cout << "Called Bar::foo(int, int) with x, y = " << x << ", " << y << std::endl;
+}
+
+void Bar::foo(char *x) {
+    std::cout << "Called Bar::foo(char *) with x = \"" << x << "\"" << std::endl;
+}
+
+void Bar::foo(int x) {
+    std::cout << "Called Bar::foo(int) with x = " << x << std::endl;
+}
+
+void Bar::foo(long x) {
+    std::cout << "Called Bar::foo(long) with x = " << x << std::endl;
+}
+
+void Bar::foo(Bar *x) {
+    std::cout << "Called Bar::foo(Bar *) with x = " << x << std::endl;
+}
+
+void Bar::spam(int x, int y, int z) {
+    std::cout << "Called Bar::spam(int, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl;
+}
+
+void Bar::spam(double x, int y, int z) {
+    std::cout << "Called Bar::spam(double, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl;
+}
+
+// Overloaded global methods
+void foo(const Bar& x) {
+    std::cout << "Called foo(const Bar& x) with &x = " << &x << std::endl;
+}
+
+void foo(double x) {
+    std::cout << "Called foo(double) with x = " << x << std::endl;
+}
+
+void foo(double x, char *y) {
+    std::cout << "Called foo(double, char *) with x, y = " << x << ", \"" << y << "\"" << std::endl;
+}
+
+void foo(int x, int y) {
+    std::cout << "Called foo(int, int) with x, y = " << x << ", " << y << std::endl;
+}
+
+void foo(char *x) {
+    std::cout << "Called foo(char *) with x = \"" << x << "\"" << std::endl;
+}
+
+void foo(int x) {
+    std::cout << "Called foo(int) with x = " << x << std::endl;
+}
+
+void foo(long x) {
+    std::cout << "Called foo(long) with x = " << x << std::endl;
+}
+
+void foo(Bar *x) {
+    std::cout << "Called foo(Bar *) with x = " << x << std::endl;
+}
+
+// Overloaded global spam() functions
+void spam(int x, int y, int z) {
+    std::cout << "Called spam(int, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl;
+}
+
+void spam(double x, int y, int z) {
+    std::cout << "Called spam(double, int, int) with x, y, z = " << x << ", " << y << ", " << z << std::endl;
+}
+
+
diff --git a/trunk/Examples/ruby/overloading/example.h b/trunk/Examples/ruby/overloading/example.h
new file mode 100644
index 0000000..e47a122
--- /dev/null
+++ b/trunk/Examples/ruby/overloading/example.h
@@ -0,0 +1,41 @@
+#ifndef EXAMPLE_H
+#define EXAMPLE_H
+
+class Bar {
+public:
+    Bar();
+    Bar(const Bar&);
+    Bar(double);
+    Bar(double, char *);
+    Bar(int, int);
+    Bar(char *);
+    Bar(long);
+    Bar(int);
+    Bar(Bar *);
+
+    void foo(const Bar&);
+    void foo(double);
+    void foo(double, char *);
+    void foo(int, int);
+    void foo(char *);
+    void foo(long);
+    void foo(int);
+    void foo(Bar *);
+    
+    void spam(int x, int y=2, int z=3);
+    void spam(double x, int y=2, int z=3);
+};
+
+void foo(const Bar&);
+void foo(double);
+void foo(double, char *);
+void foo(int, int);
+void foo(char *);
+void foo(int);
+void foo(long);
+void foo(Bar *);
+
+void spam(int x, int y=2, int z=3);
+void spam(double x, int y=2, int z=3);
+
+#endif
diff --git a/trunk/Examples/ruby/overloading/example.i b/trunk/Examples/ruby/overloading/example.i
new file mode 100644
index 0000000..17ad669
--- /dev/null
+++ b/trunk/Examples/ruby/overloading/example.i
@@ -0,0 +1,24 @@
+%module example
+
+%{
+#include "example.h"
+%}
+
+/**
+ * These overloaded declarations conflict with other overloads (as far as
+ * SWIG's Ruby module's implementation for overloaded methods is concerned).
+ * One option is use the %rename directive to rename the conflicting methods;
+ * here, we're just using %ignore to avoid wrapping some of the overloaded
+ * functions altogether.
+ */
+
+%ignore Bar::Bar(Bar *);
+%ignore Bar::Bar(long);
+
+%ignore Bar::foo(const Bar&);
+%ignore Bar::foo(long);
+
+%ignore ::foo(const Bar&);
+%ignore ::foo(int);
+
+%include example.h
diff --git a/trunk/Examples/ruby/overloading/runme.rb b/trunk/Examples/ruby/overloading/runme.rb
new file mode 100644
index 0000000..9f12333
--- /dev/null
+++ b/trunk/Examples/ruby/overloading/runme.rb
@@ -0,0 +1,88 @@
+require 'example'
+
+# This should invoke foo(double)
+Example.foo(3.14159)
+
+# This should invoke foo(double, char *)
+Example.foo(3.14159, "Pi")
+
+# This should invoke foo(int, int)
+Example.foo(3, 4)
+
+# This should invoke foo(char *)
+Example.foo("This is a test")
+
+# This should invoke foo(long)
+Example.foo(42)
+
+# This should invoke Bar::Bar() followed by foo(Bar *)
+Example.foo(Example::Bar.new)
+
+# Skip a line
+puts ""
+
+# Each of the following three calls should invoke spam(int, int, int)
+Example.spam(3)
+Example.spam(3, 4)
+Example.spam(3, 4, 5)
+
+# Skip a line
+puts ""
+
+# Each of the following three calls should invoke spam(double, int, int)
+Example.spam(3.0)
+Example.spam(3.0, 4)
+Example.spam(3.0, 4, 5)
+
+# Skip a line
+puts ""
+
+# This should invoke Bar::Bar(double)
+Example::Bar.new(3.14159)
+
+# This should invoke Bar::Bar(double, char *)
+Example::Bar.new(3.14159, "Pi")
+
+# This should invoke Bar::Bar(int, int)
+Example::Bar.new(3, 4)
+
+# This should invoke Bar::Bar(char *)
+Example::Bar.new("This is a test")
+
+# This should invoke Bar::Bar(int)
+Example::Bar.new(42)
+
+# This should invoke Bar::Bar() for the input argument,
+# followed by Bar::Bar(const Bar&).
+Example::Bar.new(Example::Bar.new)
+
+# Skip a line
+puts ""
+
+# Construct a new Bar instance (invokes Bar::Bar())
+bar = Example::Bar.new
+
+# This should invoke Bar::foo(double)
+bar.foo(3.14159)
+
+# This should invoke Bar::foo(double, char *)
+bar.foo(3.14159, "Pi")
+
+# This should invoke Bar::foo(int, int)
+bar.foo(3, 4)
+
+# This should invoke Bar::foo(char *)
+bar.foo("This is a test")
+
+# This should invoke Bar::foo(int)
+bar.foo(42)
+
+# This should invoke Bar::Bar() to construct the input
+# argument, followed by Bar::foo(Bar *).
+bar.foo(Example::Bar.new)
+
+# This should invoke Bar::spam(int x, int y, int z)
+bar.spam(1)
+
+# This should invoke Bar::spam(double x, int y, int z)
+bar.spam(3.14159)
diff --git a/trunk/Examples/ruby/pointer/Makefile b/trunk/Examples/ruby/pointer/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/pointer/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/pointer/example.c b/trunk/Examples/ruby/pointer/example.c
new file mode 100644
index 0000000..b877d9a
--- /dev/null
+++ b/trunk/Examples/ruby/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/ruby/pointer/example.i b/trunk/Examples/ruby/pointer/example.i
new file mode 100644
index 0000000..a8ac794
--- /dev/null
+++ b/trunk/Examples/ruby/pointer/example.i
@@ -0,0 +1,30 @@
+/* File : example.i */
+%module example
+
+%{
+extern void add(int *, int *, int *);
+extern void sub(int *, int *, int *);
+extern int divide(int, int, int *);
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/ruby/pointer/index.html b/trunk/Examples/ruby/pointer/index.html
new file mode 100644
index 0000000..2b9c40b
--- /dev/null
+++ b/trunk/Examples/ruby/pointer/index.html
@@ -0,0 +1,171 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:pointer</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/ruby/pointer/</tt>
+<hr>
+
+<H2>Simple Pointer Handling</H2>
+
+<p>
+This example illustrates a couple of techniques for handling
+simple pointers in SWIG.  The prototypical example is a C function
+that operates on pointers such as this:
+
+<blockquote>
+<pre>
+void add(int *x, int *y, int *r) { 
+    *r = *x + *y;
+}
+</pre>
+</blockquote>
+
+By default, SWIG wraps this function exactly as specified and creates
+an interface that expects pointer objects for arguments.  The only
+problem is how does one go about creating these objects from a script?
+
+<h2>Possible Solutions</h2>
+
+<ul>
+<li>Write some helper functions to explicitly create objects.  For
+example:
+
+<blockquote>
+<pre>
+int *new_int(int ivalue) {
+  int *i = (int *) malloc(sizeof(ivalue));
+  *i = ivalue;
+  return i;
+}
+int get_int(int *i) {
+  return *i;
+}
+
+void delete_int(int *i) {
+  free(i);
+}
+</pre>
+</blockquote>
+
+Now, in a script you would do this:
+
+<blockquote>
+<pre>
+a = new_int(37)
+b = new_int(42)
+c = new_int(0)
+add(a,b,c)
+r = get_int(c)
+print "Result = #{r}\n"
+delete_int(a)
+delete_int(b)
+delete_int(c)
+</pre>
+</blockquote>
+
+<p>
+<li>Use the SWIG pointer library.  For example, in the interface file 
+you would do this:
+
+<blockquote>
+<pre>
+%include "pointer.i"
+</pre>
+</blockquote>
+
+and in a script you would do this:
+
+<blockquote>
+<pre>
+a = ptrcreate("int",37)
+b = ptrcreate("int",42)
+c = ptrcreate("int")
+add(a,b,c)
+r = ptrvalue(c)
+print "Result = #{r}\n"
+ptrfree(a)
+ptrfree(b)
+ptrfree(c)
+</pre>
+</blockquote>
+
+The advantage to using the pointer library is that it unifies some of the helper
+functions behind a common set of names.  For example, the same set of functions work
+with int, double, float, and other fundamental types.
+
+<p>
+<li>Use the SWIG typemap library.  This library allows you to completely
+change the way arguments are processed by SWIG.  For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+void add(int *INPUT, int *INPUT, int *OUTPUT);
+</pre>
+</blockquote>
+
+And in a script:
+
+<blockquote>
+<pre>
+r = add(37,42)
+print "Result = #{r}\n"
+</pre>
+</blockquote>
+Needless to say, this is substantially easier.
+
+<p>
+<li>A final alternative is to use the typemaps library in combination
+with the %apply directive.  This allows you to change the names of parameters
+that behave as input or output parameters. For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+%apply int *INPUT {int *x, int *y};
+%apply int *OUTPUT {int *r};
+
+void add(int *x, int *y, int *r);
+void sub(int *x, int *y, int *r);
+void mul(int *x, int *y, int *r);
+... etc ...
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>Example</h2>
+
+The following example illustrates the use of these features for pointer
+extraction.
+
+<ul>
+<li> <a href="example.c">example.c</a>  (C Source)
+<li> <a href="example.i">example.i</a>  (Swig interface)
+<li> <a href="runme.rb">runme.rb</a> (Ruby Script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>Since pointers are used for so many different things (arrays, output values,
+etc...) the complexity of pointer handling can be as complicated as you want to
+make it.
+
+<p>
+<li>More documentation on the typemaps.i and pointer.i library files can be
+found in the SWIG user manual.  The files also contain documentation.
+
+<p>
+<li>The pointer.i library is designed primarily for convenience.  If you
+are concerned about performance, you probably want to use a different
+approach.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ruby/pointer/runme.rb b/trunk/Examples/ruby/pointer/runme.rb
new file mode 100644
index 0000000..d696b02
--- /dev/null
+++ b/trunk/Examples/ruby/pointer/runme.rb
@@ -0,0 +1,45 @@
+# file: runme.rb
+
+require 'example'
+
+# First create some objects using the pointer library.
+print "Testing the pointer library\n"
+a = Example::new_intp()
+b = Example::new_intp()
+c = Example::new_intp()
+
+Example::intp_assign(a,37)
+Example::intp_assign(b,42)
+
+print "     a = #{a}\n"
+print "     b = #{b}\n"
+print "     c = #{c}\n"
+
+# Call the add() function with some pointers
+Example::add(a, b, c)
+
+# Now get the result
+r = Example::intp_value(c)
+print "     37 + 42 = #{r}\n"
+
+# Clean up the pointers
+Example::delete_intp(a)
+Example::delete_intp(b)
+Example::delete_intp(c)
+
+# Now try the typemap library
+# This should be much easier. Now how it is no longer
+# necessary to manufacture pointers.
+
+print "Trying the typemap library\n"
+r = Example::sub(37, 42)
+print "     37 - 42 = #{r}\n"
+
+# Now try the version with multiple return values
+
+print "Testing multiple return values\n"
+q, r = Example::divide(42, 37)
+print "     42/37 = #{q} remainder #{r}\n"
+
+
+
diff --git a/trunk/Examples/ruby/reference/Makefile b/trunk/Examples/ruby/reference/Makefile
new file mode 100644
index 0000000..56c84c6
--- /dev/null
+++ b/trunk/Examples/ruby/reference/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/reference/example.cxx b/trunk/Examples/ruby/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/ruby/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/ruby/reference/example.h b/trunk/Examples/ruby/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/ruby/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/ruby/reference/example.i b/trunk/Examples/ruby/reference/example.i
new file mode 100644
index 0000000..6daa3b1
--- /dev/null
+++ b/trunk/Examples/ruby/reference/example.i
@@ -0,0 +1,46 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/ruby/reference/index.html b/trunk/Examples/ruby/reference/index.html
new file mode 100644
index 0000000..d45dbe3
--- /dev/null
+++ b/trunk/Examples/ruby/reference/index.html
@@ -0,0 +1,147 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:reference</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/ruby/reference/</tt>
+<hr>
+
+<H2>C++ Reference Handling</H2>
+
+<p>
+This example tests SWIG's handling of C++ references.  Since C++
+references are closely related to pointers (as both refer to a
+location in memory), SWIG simply collapses all references into
+pointers when creating wrappers.
+
+<h2>Some examples</h2>
+
+References are most commonly used as function parameter.  For example,
+you might have an operator like this:
+
+<blockquote>
+<pre>
+Vector operator+(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+or a function:
+
+<blockquote>
+<pre>
+Vector addv(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+In these cases, SWIG transforms everything into a pointer and creates a wrapper
+that looks like this:
+
+<blockquote>
+<pre>
+Vector wrap_addv(Vector *a, Vector *b) {
+    return addv(*a,*b);
+}
+</pre>
+</blockquote>
+
+Occasionally, a reference is used as a return value of a function
+when the return result is to be used as an lvalue in an expression.
+The prototypical example is an operator like this:
+
+<blockquote>
+<pre>
+Vector &amp;operator[](int index);
+</pre>
+</blockquote>
+
+or a method:
+
+<blockquote>
+<pre>
+Vector &amp;get(int index);
+</pre>
+</blockquote>
+
+For functions returning references, a wrapper like this is created:
+
+<blockquote>
+<pre>
+Vector *wrap_Object_get(Object *self, int index) {
+    Vector &amp;result = self-&gt;get(index);
+    return &amp;result;
+}
+</pre>
+</blockquote>
+
+The following <a href="example.h">header file</a> contains some class
+definitions with some operators and use of references.
+
+<h2>SWIG Interface</h2>
+
+SWIG does NOT support overloaded operators so it can not directly build
+an interface to the classes in the above file.   However, a number of workarounds
+can be made.  For example, an overloaded operator can be stuck behind a function
+call such as the <tt>addv()</tt> function above.  Array access can be handled
+with a pair of set/get functions like this:
+
+<blockquote>
+<pre>
+class VectorArray {
+public:
+ ...
+   %addmethods {
+    Vector &amp;get(int index) {
+      return (*self)[index];
+    }
+    void set(int index, Vector &amp;a) {
+      (*self)[index] = a;
+    }
+   }
+   ...
+}
+</pre>
+</blockquote>
+
+Click <a href="example.i">here</a> to see a SWIG interface file with these additions.
+
+<h2>Sample Ruby script</h2>
+
+Click <a href="runme.rb">here</a> to see a script that manipulates some C++ references.
+
+<h2>Notes:</h2>
+
+<ul>
+<li>C++ references primarily provide notational convenience for C++
+source code.  However, Ruby only supports the 'x.a' 
+notation so it doesn't much matter.
+
+<p>
+<li>When a program returns a reference, a pointer is returned.
+Unlike return by value, memory is not allocated to hold the
+return result.
+
+<p>
+<li>SWIG has particular trouble handling various combinations of references
+and pointers.  This is side effect of an old parsing scheme and
+type representation that will be replaced in future versions.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ruby/reference/runme.rb b/trunk/Examples/ruby/reference/runme.rb
new file mode 100644
index 0000000..67b76fc
--- /dev/null
+++ b/trunk/Examples/ruby/reference/runme.rb
@@ -0,0 +1,60 @@
+# file: runme.rb
+
+# This file illustrates the manipulation of C++ references in Ruby.
+
+require 'example'
+
+# ----- Object creation -----
+
+print "Creating some objects:\n"
+a = Example::Vector.new(3,4,5)
+b = Example::Vector.new(10,11,12)
+
+print "    Created ", a.print, "\n"
+print "    Created ", b.print, "\n"
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+print "Adding a+b\n"
+c = Example::addv(a, b)
+print "    a+b = ", c.print, "\n"
+
+# ----- Create a vector array -----
+
+print "Creating an array of vectors\n"
+va = Example::VectorArray.new(10)
+print "    va = #{va}\n"
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of a and b to the vector array
+va.set(0, a)
+va.set(1, b)
+
+va.set(2, Example::addv(a,b))
+
+c = Example::addv(a,b)
+va.set(3, c)
+
+=begin commented out due to GC issue
+
+# Get some values from the array
+
+print "Getting some array values\n"
+for i in 0...5
+  print "    va(#{i}) = ", va.get(i).print, "\n"
+end
+
+# Watch under resource meter to check on this
+print "Making sure we don't leak memory.\n"
+for i in 0...1000000
+  c = va.get(i % 10)
+end
+
+=end
diff --git a/trunk/Examples/ruby/simple/Makefile b/trunk/Examples/ruby/simple/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/simple/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/simple/example.c b/trunk/Examples/ruby/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/ruby/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/ruby/simple/example.dsp b/trunk/Examples/ruby/simple/example.dsp
new file mode 100644
index 0000000..ccb99d4
--- /dev/null
+++ b/trunk/Examples/ruby/simple/example.dsp
@@ -0,0 +1,150 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(RUBY_INCLUDE)" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+# SUBTRACT LINK32 /pdb:none

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(RUBY_INCLUDE)" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /D NT=1 /D "IMPORT" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(RUBY_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+# SUBTRACT LINK32 /pdb:none

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo RUBY_INCLUDE: %RUBY_INCLUDE% 

+	echo RUBY_LIB: %RUBY_LIB% 

+	echo on 

+	..\..\..\swig -ruby $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/ruby/simple/example.i b/trunk/Examples/ruby/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/ruby/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/ruby/simple/index.html b/trunk/Examples/ruby/simple/index.html
new file mode 100644
index 0000000..b2ab14e
--- /dev/null
+++ b/trunk/Examples/ruby/simple/index.html
@@ -0,0 +1,97 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:simple</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/ruby/simple/</tt>
+<hr>
+
+<H2>Simple Ruby Example</H2>
+
+<p>
+This example illustrates how you can hook Ruby to a very simple C program containing
+a function and a global variable.
+
+<h2>The C Code</h2>
+
+Suppose you have the following C code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x &gt; 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+Here is a simple SWIG interface file:
+
+<blockquote>
+<pre>
+/* File: example.i */
+%module example
+
+extern int gcd(int x, int y);
+extern double Foo;
+</pre>
+</blockquote>
+
+<h2>Compilation</h2>
+
+<ol>
+<li><tt>swig -ruby <a href="example.i">example.i</a></tt>
+<p>
+<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
+to create the extension <tt>example.so</tt>. 
+</ol>
+
+<h2>Using the extension</h2>
+
+Click <a href="run.rb">here</a> to see a script that calls our C functions from Ruby.
+
+<h2>Key points</h2>
+
+<ul>
+<li>Use the <tt>require</tt> function to load your extension library from Ruby. For example:
+<blockquote>
+<pre>
+require 'example'
+</pre>
+</blockquote>
+
+<li>C functions work just like Ruby functions. For example:
+<blockquote>
+<pre>
+g = Example.gcd(42,105)
+</pre>
+</blockquote>
+
+<li>C global variables are accessed through module method. For example:
+<blockquote>
+<pre>
+a = Example.Foo
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ruby/simple/runme.rb b/trunk/Examples/ruby/simple/runme.rb
new file mode 100755
index 0000000..9cc47b2
--- /dev/null
+++ b/trunk/Examples/ruby/simple/runme.rb
@@ -0,0 +1,21 @@
+# file: runme.rb
+
+require 'example'
+
+# Call our gcd() function
+
+x = 42
+y = 105
+g = Example.gcd(x,y)
+printf "The gcd of %d and %d is %d\n",x,y,g
+
+# Manipulate the Foo global variable
+
+# Output its current value
+print "Foo = ", Example.Foo, "\n"
+
+# Change its value
+Example.Foo = 3.1415926
+
+# See if the change took effect
+print "Foo = ", Example.Foo, "\n"
diff --git a/trunk/Examples/ruby/std_vector/Makefile b/trunk/Examples/ruby/std_vector/Makefile
new file mode 100644
index 0000000..15c9d70
--- /dev/null
+++ b/trunk/Examples/ruby/std_vector/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/std_vector/example.h b/trunk/Examples/ruby/std_vector/example.h
new file mode 100644
index 0000000..4f0dac7
--- /dev/null
+++ b/trunk/Examples/ruby/std_vector/example.h
@@ -0,0 +1,25 @@
+/* File : example.h */
+
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<double> half(const std::vector<double>& v) {
+    std::vector<double> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    // would you believe this is the same as the above?
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+
diff --git a/trunk/Examples/ruby/std_vector/example.i b/trunk/Examples/ruby/std_vector/example.i
new file mode 100644
index 0000000..aa58b66
--- /dev/null
+++ b/trunk/Examples/ruby/std_vector/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+/* instantiate the required template specializations */
+namespace std {
+    %template(IntVector)    vector<int>;
+    %template(DoubleVector) vector<double>;
+}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/ruby/std_vector/runme.rb b/trunk/Examples/ruby/std_vector/runme.rb
new file mode 100644
index 0000000..1529d38
--- /dev/null
+++ b/trunk/Examples/ruby/std_vector/runme.rb
@@ -0,0 +1,36 @@
+# file: runme.rb
+
+require 'example'
+
+# Call average with a Ruby array...
+
+puts Example::average([1,2,3,4])
+
+# ... or a wrapped std::vector<int>
+
+v = Example::IntVector.new(4)
+0.upto(v.length-1) { |i| v[i] = i+1 }
+puts Example::average(v)
+
+
+# half will return a Ruby array.
+# Call it with a Ruby array...
+
+w = Example::half([1.0, 1.5, 2.0, 2.5, 3.0])
+0.upto(w.length-1) { |i| print w[i],"; " }
+puts
+
+# ... or a wrapped std::vector<double>
+
+v = Example::DoubleVector.new
+[1,2,3,4].each { |i| v.push(i) }
+w = Example::half(v)
+0.upto(w.length-1) { |i| print w[i],"; " }
+puts
+
+# now halve a wrapped std::vector<double> in place
+
+Example::halve_in_place(v)
+0.upto(v.length-1) { |i| print v[i],"; " }
+puts
+
diff --git a/trunk/Examples/ruby/template/Makefile b/trunk/Examples/ruby/template/Makefile
new file mode 100644
index 0000000..15c9d70
--- /dev/null
+++ b/trunk/Examples/ruby/template/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+SWIGOPT    = 
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	SWIGOPT='$(SWIGOPT)' TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/template/example.h b/trunk/Examples/ruby/template/example.h
new file mode 100644
index 0000000..7401df6
--- /dev/null
+++ b/trunk/Examples/ruby/template/example.h
@@ -0,0 +1,32 @@
+/* File : example.h */
+
+// Some template definitions
+
+template<class T> T max(T a, T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+#ifdef SWIG
+  %extend {
+    T getitem(int index) {
+      return $self->get(index);
+    }
+    void setitem(int index, T val) {
+      $self->set(index,val);
+    }
+  }
+#endif
+};
+
diff --git a/trunk/Examples/ruby/template/example.i b/trunk/Examples/ruby/template/example.i
new file mode 100644
index 0000000..d5ddf7a
--- /dev/null
+++ b/trunk/Examples/ruby/template/example.i
@@ -0,0 +1,21 @@
+/* File : example.i */
+%module example
+
+%{
+#ifdef max
+#undef max
+#endif
+
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(Vecint) vector<int>;
+%template(Vecdouble) vector<double>;
+
diff --git a/trunk/Examples/ruby/template/runme.rb b/trunk/Examples/ruby/template/runme.rb
new file mode 100644
index 0000000..6c9c4eb
--- /dev/null
+++ b/trunk/Examples/ruby/template/runme.rb
@@ -0,0 +1,25 @@
+# file: runme.rb
+
+require 'example'
+
+# Call some templated functions
+puts Example::maxint(3, 7)
+puts Example::maxdouble(3.14, 2.18)
+
+# Create some class
+
+iv = Example::Vecint.new(100)
+dv = Example::Vecdouble.new(1000)
+
+100.times { |i| iv.setitem(i, 2*i) }
+
+1000.times { |i| dv.setitem(i, 1.0/(i+1)) }
+
+sum = 0
+100.times { |i| sum = sum + iv.getitem(i) }
+
+puts sum
+
+sum = 0.0
+1000.times { |i| sum = sum + dv.getitem(i) }
+puts sum
diff --git a/trunk/Examples/ruby/value/Makefile b/trunk/Examples/ruby/value/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/value/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/value/example.c b/trunk/Examples/ruby/value/example.c
new file mode 100644
index 0000000..4ed2fe1
--- /dev/null
+++ b/trunk/Examples/ruby/value/example.c
@@ -0,0 +1,15 @@
+/* File : example.c */
+
+#include "example.h"
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+Vector vector_add(Vector a, Vector b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
diff --git a/trunk/Examples/ruby/value/example.h b/trunk/Examples/ruby/value/example.h
new file mode 100644
index 0000000..212cf4b
--- /dev/null
+++ b/trunk/Examples/ruby/value/example.h
@@ -0,0 +1,5 @@
+/* File : example.h */
+
+typedef struct {
+     double x, y, z;
+} Vector;
diff --git a/trunk/Examples/ruby/value/example.i b/trunk/Examples/ruby/value/example.i
new file mode 100644
index 0000000..98fd60e
--- /dev/null
+++ b/trunk/Examples/ruby/value/example.i
@@ -0,0 +1,32 @@
+// Tests SWIG's handling of pass-by-value for complex datatypes
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Some functions that manipulate Vectors by value */
+%inline %{
+extern double dot_product(Vector a, Vector b);
+extern Vector vector_add(Vector a, Vector b);
+%}
+
+/* Include this because the vector_add() function will leak memory */
+void   free(void *);
+
+/* Some helper functions for our interface */
+%inline %{
+
+Vector *new_Vector(double x, double y, double z) {
+   Vector *v = (Vector *) malloc(sizeof(Vector));
+   v->x = x;
+   v->y = y;
+   v->z = z;
+   return v;
+}
+
+void vector_print(Vector *v) {
+  printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}
+%}
+
diff --git a/trunk/Examples/ruby/value/index.html b/trunk/Examples/ruby/value/index.html
new file mode 100644
index 0000000..cd99ba1
--- /dev/null
+++ b/trunk/Examples/ruby/value/index.html
@@ -0,0 +1,114 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:value</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/ruby/value/</tt>
+<hr>
+
+<H2>Passing and Returning Structures by Value</H2>
+
+<p>
+Occasionally, a C program will manipulate structures by value such as shown in the
+following code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+typedef struct Vector {
+   double x, y, z;
+} Vector;
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+Vector vector_add(Vector a, Vector b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+</pre>
+</blockquote>
+
+Since SWIG only knows how to manage pointers to structures (not their internal
+representation), the following translations are made when wrappers are
+created:
+
+<blockquote>
+<pre>
+double wrap_dot_product(Vector *a, Vector *b) {
+    return dot_product(*a,*b);
+}
+
+Vector *wrap_vector_add(Vector *a, Vector *b) {
+    Vector *r = (Vector *) malloc(sizeof(Vector));
+    *r = vector_add(*a,*b);
+    return r;
+}
+</pre>
+</blockquote>
+
+The functions are then called using pointers from the scripting language interface.
+It should also be noted that any function that returns a structure by value results
+in an implicit memory allocation. This will be a memory leak unless you take steps
+to free the result (see below).
+
+<h2>The SWIG interface</h2>
+
+Click <a href="example.i">here</a> to see a SWIG interface file that
+wraps these two functions.  In this file, there are a few essential features:
+
+<ul>
+<li>A wrapper for the <tt>free()</tt> function is created so that we
+can clean up the return result created by <tt>vector_add()</tt>
+function.
+
+<p>
+<li>The %inline directive is used to create a few helper functions for creating new Vector
+objects and to print out the value (for debugging purposes).
+</ul>
+
+<h2>A Ruby Script</h2>
+
+Click <a href="runme.rb">here</a> to see a script that uses these functions from Ruby.
+
+<h2>Notes</h2>
+
+<ul>
+<li>When the '<tt>-c++</tt>' option is used, the resulting wrapper code for the return value
+changes to the following:
+
+<blockquote>
+<pre>
+Vector *wrap_vector_add(Vector *a, Vector *b) {
+    Vector *r = new Vector(vector_add(*a,*b));
+    return r;
+}
+</pre>
+</blockquote>
+
+<p>
+<li>If you define C structure (or C++ class with '<tt>-c++</tt>' option)
+in the interface file, the SWIG generated wrappers can automaticallyclean
+up the result of return-by-reference by GC.
+
+<p>
+<li>Passing parameters by value like this really isn't the best C programming style.
+If possible, you might change your application to use pointers.
+
+<p>
+<li>Similar translations are made when C++ references are used.
+
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/ruby/value/runme.rb b/trunk/Examples/ruby/value/runme.rb
new file mode 100644
index 0000000..9372c03
--- /dev/null
+++ b/trunk/Examples/ruby/value/runme.rb
@@ -0,0 +1,32 @@
+# file: runme.rb
+
+require 'example'
+
+# Create a couple of a vectors
+
+v = Example::new_Vector(1, 2, 3)
+w = Example::new_Vector(10, 11, 12)
+
+print "I just created the following vectors\n"
+Example::vector_print(v)
+Example::vector_print(w)
+
+# Now call some of our functions
+
+print "\nNow I'm going to compute the dot product\n"
+d = Example::dot_product(v,w)
+print "dot product = #{d} (should be 68)\n"
+
+# Add the vectors together
+
+print "\nNow I'm going to add the vectors together\n"
+r = Example::vector_add(v,w)
+Example::vector_print(r)
+print "The value should be (11, 13, 15)\n"
+
+# Now I'd better clean up the return result r
+
+print "\nNow I'm going to clean up the return result\n"
+Example::free(r)
+
+print "Good\n"
diff --git a/trunk/Examples/ruby/variables/Makefile b/trunk/Examples/ruby/variables/Makefile
new file mode 100644
index 0000000..8c4fe10
--- /dev/null
+++ b/trunk/Examples/ruby/variables/Makefile
@@ -0,0 +1,18 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile ruby_clean
+
+check: all
diff --git a/trunk/Examples/ruby/variables/example.c b/trunk/Examples/ruby/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/ruby/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/ruby/variables/example.h b/trunk/Examples/ruby/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/ruby/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/ruby/variables/example.i b/trunk/Examples/ruby/variables/example.i
new file mode 100644
index 0000000..84a1509
--- /dev/null
+++ b/trunk/Examples/ruby/variables/example.i
@@ -0,0 +1,50 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_SWIGTYPELEAK
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/ruby/variables/index.html b/trunk/Examples/ruby/variables/index.html
new file mode 100644
index 0000000..d83a87c
--- /dev/null
+++ b/trunk/Examples/ruby/variables/index.html
@@ -0,0 +1,94 @@
+<html>
+<head>
+<title>SWIG:Examples:ruby:variables</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/ruby/variables/</tt>
+<hr>
+
+<H2>Wrapping C Global Variables</H2>
+
+<p>
+When a C global variable appears in an interface file, SWIG tries to
+wrap it using a technique known as "variable linking."  The idea is
+pretty simple---we try to create a Ruby variable (actually module method) that
+magically retrieves or updates the value of the underlying C variable when it is
+accessed.  Click <a href="example.i">here</a> to see a SWIG interface with some variable
+declarations in it.
+
+<h2>Manipulating Variables from Ruby</h2>
+
+Before going any further, it is important to understand some important
+differences between C and Ruby variables.  In C, a variable is
+simply a name that refers to a specific location in memory.  For
+example, when you declare a global variable '<tt>double a</tt>' you
+know that somewhere in memory, 8 bytes have been set aside to hold a
+<tt>double</tt> and that <tt>a</tt> is bound to this location for the
+life of the program.  In Ruby, variable creation is nothing more
+than a naming operation.  For example, when you say '<tt>a = 3</tt>',
+'a' becomes a name that refers to some object '3'.  Later on, if you say
+'<tt>a = 7.5</tt>, the name 'a' is bound to an entirely different object
+containing the value '7.5' (the contents of the original object are not
+changed).  The end result of this is that a variable in Ruby can refer
+to a virtually unlimited number of different objects (memory locations)
+over the lifetime of a program.
+
+<p>
+Because of Ruby's somewhat unusual variable assignment semantics, it is not
+possible to directly link a C global variable into an equivalent Ruby variable.
+Instead, all C global variables are accessed as attributes of the module.
+For example, if you had a global variable
+
+<blockquote>
+<pre>
+double foo;
+</pre>
+</blockquote>
+
+it will be accessed in the Ruby module as <tt>Example.foo</tt>. Click
+<a href="runme.rb">here</a> to see a script that updates and prints
+out the values of the variables using this technique.
+
+<h2>Key points</h2>
+
+<ul>
+<li>When a global variable has the type "<tt>char *</tt>", SWIG manages it as a character
+string.   However, whenever the value of such a variable is set from Ruby, the old
+value is destroyed using <tt>free()</tt>.
+<li><tt>signed char</tt> and <tt>unsigned char</tt> are handled as small 8-bit integers.
+<li>String array variables such as '<tt>char name[256]</tt>' are managed as Ruby strings, but
+when setting the value, the result is truncated to the maximum length of the array.  Furthermore, the string is assumed to be null-terminated.
+<li>When structures and classes are used as global variables, they are mapped into pointers.
+Getting the "value" returns a pointer to the global variable.  Setting the value of a structure results in a memory copy from a pointer to the global.
+</ul>
+
+<h2>Creating read-only variables</h2>
+
+The <tt>%immutable</tt> and <tt>%mutable</tt> directives can be used to
+specify a collection of read-only variables.  For example:
+
+<blockquote>
+<pre>
+%immutable;
+int    status;
+double blah;
+...
+%mutable;
+</pre>
+</blockquote>
+
+The <tt>%immutable</tt> directive remains in effect until it is explicitly disabled
+using the <tt>%mutable</tt> directive.
+
+<h2>Comments</h2>
+<ul>
+<li>Management of global variables is one of the most problematic aspects 
+of C/C++ wrapping because the scripting interface and resulting memory management
+is much trickier than simply creating a wrapper function.
+</ul>
+
+</body>
+</html>
+<hr>
diff --git a/trunk/Examples/ruby/variables/runme.rb b/trunk/Examples/ruby/variables/runme.rb
new file mode 100644
index 0000000..38531c8
--- /dev/null
+++ b/trunk/Examples/ruby/variables/runme.rb
@@ -0,0 +1,77 @@
+# file: runme.rb
+
+require 'example'
+
+# Try to set the values of some global variables
+
+Example.ivar   =  42
+Example.svar   = -31000
+Example.lvar   =  65537
+Example.uivar  =  123456
+Example.usvar  =  61000
+Example.ulvar  =  654321
+Example.scvar  =  -13
+Example.ucvar  =  251
+Example.cvar   =  "S"
+Example.fvar   =  3.14159
+Example.dvar   =  2.1828
+Example.strvar =  "Hello World"
+Example.iptrvar= Example.new_int(37)
+Example.ptptr  = Example.new_Point(37,42)
+Example.name   = "Bill"
+
+# Now print out the values of the variables
+
+puts "Variables (values printed from Ruby)"
+
+puts "ivar      = #{Example.ivar}"
+puts "svar      = #{Example.svar}"
+puts "lvar      = #{Example.lvar}"
+puts "uivar     = #{Example.uivar}"
+puts "usvar     = #{Example.usvar}"
+puts "ulvar     = #{Example.ulvar}"
+puts "scvar     = #{Example.scvar}"
+puts "ucvar     = #{Example.ucvar}"
+puts "fvar      = #{Example.fvar}"
+puts "dvar      = #{Example.dvar}"
+puts "cvar      = #{Example.cvar}"
+puts "strvar    = #{Example.strvar}"
+puts "cstrvar   = #{Example.cstrvar}"
+puts "iptrvar   = #{Example.iptrvar}"
+puts "name      = #{Example.name}"
+puts "ptptr     = #{Example.ptptr} (#{Example.Point_print(Example.ptptr)})"
+puts "pt        = #{Example.pt} (#{Example.Point_print(Example.pt)})"
+
+puts "\nVariables (values printed from C)"
+
+Example.print_vars()
+
+puts "\nNow I'm going to try and modify some read only variables";
+
+puts "     Tring to set 'path'";
+begin
+  Example.path = "Whoa!"
+  puts "Hey, what's going on?!?! This shouldn't work"
+rescue NameError
+  puts "Good."
+end
+
+puts "     Trying to set 'status'";
+begin
+  Example.status = 0
+  puts "Hey, what's going on?!?! This shouldn't work"
+rescue NameError
+  puts "Good."
+end
+
+
+puts "\nI'm going to try and update a structure variable.\n"
+
+Example.pt = Example.ptptr
+
+puts "The new value is"
+Example.pt_print()
+puts "You should see the value #{Example.Point_print(Example.ptptr)}"
+
+
+
diff --git a/trunk/Examples/s-exp/uffi.lisp b/trunk/Examples/s-exp/uffi.lisp
new file mode 100644
index 0000000..5ddb4c2
--- /dev/null
+++ b/trunk/Examples/s-exp/uffi.lisp
@@ -0,0 +1,450 @@
+;;; This is experimental code that uses the s-expression
+;;; representation of a C/C++ library interface to generate Foreign
+;;; Function Interface definitions for use with Kevin Rosenberg's
+;;; UFFI.
+;;;
+;;; Written by Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>
+
+(eval-when (:compile-toplevel :load-toplevel :execute)
+  (require 'port)				; from CLOCC
+  (require 'uffi))
+
+(in-package :cl-user)
+
+;; Interaction with the SWIG binary
+
+(defvar *swig-source-directory* #p"/home/mkoeppe/s/swig1.3/")
+
+(defvar *swig-program* (merge-pathnames "preinst-swig" *swig-source-directory*))
+
+(defun run-swig (swig-interface-file-name &key directory-search-list module
+		 ignore-errors c++)
+  (let ((temp-file-name "/tmp/swig.lsp"))
+    (let ((process
+	   (port:run-prog (namestring *swig-program*)
+			  :output t
+			  :args `(,@(and c++ '("-c++"))
+				  "-sexp"
+				  ,@(mapcar (lambda (dir)
+				       (concatenate 'string
+						    "-I" (namestring dir)))
+					    directory-search-list)
+				  ,@(and module
+					 `("-module" ,module))
+				  "-o" ,temp-file-name
+				  ,(namestring swig-interface-file-name)))))
+      #+cmu (unless (or (zerop (ext:process-exit-code process))
+			ignore-errors)
+	      (error "Process swig exited abnormally"))
+      (with-open-file (s temp-file-name)
+	(read s)))))
+
+;; Type system
+
+(defun parse-swigtype (type-string &key start end junk-ok)
+  "Parse TYPE-STRING as SWIG's internal representation of C/C++
+types. Return two values: The type description (an improper list) and
+the terminating index into TYPE-STRING."
+  ;; SWIG's internal representation is described in Source/Swig/stype.c
+  (unless start
+    (setq start 0))
+  (unless end
+    (setq end (length type-string)))
+  (flet ((prefix-match (prefix)
+	   (let ((position (mismatch prefix type-string :start2 start :end2 end)))
+	     (or (not position)
+		 (= position (length prefix)))))
+	 (bad-type-error (reason)
+	   (error "Bad SWIG type (~A): ~A" reason
+		  (subseq type-string start end)))
+	 (type-char (index)
+	   (and (< index (length type-string))
+		(char type-string index)))	       
+	 (cons-and-recurse (prefix start end)
+	   (multiple-value-bind (type-description index)
+	       (parse-swigtype type-string :start start :end end
+				:junk-ok junk-ok)
+	     (values (cons prefix type-description)
+		     index))))
+    (cond
+      ((prefix-match "p.")		; pointer
+       (cons-and-recurse '* (+ start 2) end))
+      ((prefix-match "r.")		; C++ reference
+       (cons-and-recurse '& (+ start 2) end))
+      ((prefix-match "a(")		; array
+       (let ((closing-paren (position #\) type-string
+				  :start (+ start 2)
+				  :end end)))
+	 (unless closing-paren
+	   (bad-type-error "missing right paren"))
+	 (unless (eql (type-char (+ closing-paren 1)) #\.)
+	   (bad-type-error "missing dot"))
+	 (cons-and-recurse (list 'ARRAY (subseq type-string (+ start 2) closing-paren))
+			   (+ closing-paren 2) end)))
+      ((prefix-match "q(")		; qualifier (const, volatile)
+       (let ((closing-paren (position #\) type-string
+				  :start (+ start 2)
+				  :end end)))
+	 (unless closing-paren
+	   (bad-type-error "missing right paren"))
+	 (unless (eql (type-char (+ closing-paren 1)) #\.)
+	   (bad-type-error "missing dot"))
+	 (cons-and-recurse (list 'QUALIFIER (subseq type-string (+ start 2) closing-paren))
+			   (+ closing-paren 2) end)))
+      ((prefix-match "m(")		; C++ member pointer
+       (multiple-value-bind (class-type class-end-index)
+	   (parse-swigtype type-string :junk-ok t
+			    :start (+ start 2) :end end)
+	 (unless (eql (type-char class-end-index) #\))
+	   (bad-type-error "missing right paren"))
+	 (unless (eql (type-char (+ class-end-index 1)) #\.)
+	   (bad-type-error "missing dot"))
+	 (cons-and-recurse (list 'MEMBER-POINTER class-type)
+			   (+ class-end-index 2) end)))	 
+      ((prefix-match "f(")		; function
+       (loop with index = (+ start 2) 
+	     until (eql (type-char index) #\))
+	     collect (multiple-value-bind (arg-type arg-end-index)
+			 (parse-swigtype type-string :junk-ok t
+					  :start index :end end)
+		       (case (type-char arg-end-index)
+			 (#\, (setq index (+ arg-end-index 1)))
+			 (#\) (setq index arg-end-index))
+			 (otherwise (bad-type-error "comma or right paren expected"))) 
+		       arg-type)
+	     into arg-types
+	     finally (unless (eql (type-char (+ index 1)) #\.)
+		       (bad-type-error "missing dot"))
+	     (return (cons-and-recurse (cons 'FUNCTION arg-types)
+				       (+ index 2) end))))
+      ((prefix-match "v(")		;varargs
+       (let ((closing-paren (position #\) type-string
+				  :start (+ start 2)
+				  :end end)))
+	 (unless closing-paren
+	   (bad-type-error "missing right paren"))
+	 (values (list 'VARARGS (subseq type-string (+ start 2) closing-paren))
+		 (+ closing-paren 1))))
+      (t (let ((junk-position (position-if (lambda (char)
+					     (member char '(#\, #\( #\) #\.)))
+					   type-string
+					   :start start :end end)))
+	   (cond (junk-position		; found junk
+		  (unless junk-ok
+		    (bad-type-error "trailing junk"))
+		  (values (subseq type-string start junk-position)
+			  junk-position))
+		 (t
+		  (values (subseq type-string start end)
+			  end))))))))
+
+(defun swigtype-function-p (swigtype)
+  "Check whether SWIGTYPE designates a function.  If so, the second
+value is the list of argument types, and the third value is the return
+type."
+  (if (and (consp swigtype)
+	   (consp (first swigtype))
+	   (eql (first (first swigtype)) 'FUNCTION))
+      (values t (rest (first swigtype)) (rest swigtype))
+      (values nil nil nil)))
+	      
+
+;; UFFI
+
+(defvar *uffi-definitions* '())
+
+(defconstant *uffi-default-primitive-type-alist*
+  '(("char" . :char)
+    ("unsigned char" . :unsigned-byte)
+    ("signed char" . :byte)
+    ("short" . :short)
+    ("signed short" . :short)
+    ("unsigned short" . :unsigned-short)
+    ("int" . :int)
+    ("signed int" . :int)
+    ("unsigned int" . :unsigned-int)
+    ("long" . :long)
+    ("signed long" . :long)
+    ("unsigned long" . :unsigned-long)
+    ("float" . :float)
+    ("double" . :double)
+    ((* . "char") . :cstring)
+    ((* . "void") . :pointer-void)
+    ("void" . :void)))
+
+(defvar *uffi-primitive-type-alist* *uffi-default-primitive-type-alist*)
+
+(defun uffi-type-spec (type-list)
+  "Return the UFFI type spec equivalent to TYPE-LIST, or NIL if there
+is no representation."
+  (let ((primitive-type-pair
+	 (assoc type-list *uffi-primitive-type-alist* :test 'equal)))
+    (cond
+      (primitive-type-pair
+       (cdr primitive-type-pair))
+      ((and (consp type-list)
+	    (eql (first type-list) '*))
+       (let ((base-type-spec (uffi-type-spec (rest type-list))))
+	 (cond
+	   ((not base-type-spec)
+	    :pointer-void)
+	   (t
+	    (list '* base-type-spec)))))
+      (t nil))))
+
+;; Parse tree
+
+(defvar *uffi-output* nil)
+
+(defun emit-uffi-definition (uffi-definition)
+  (format *uffi-output* "~&~S~%" uffi-definition)
+  (push uffi-definition *uffi-definitions*))
+
+(defun make-cl-symbol (c-identifier &key uninterned)
+  (let ((name (substitute #\- #\_ (string-upcase c-identifier))))
+    (if uninterned
+	(make-symbol name)
+	(intern name))))
+
+(defvar *class-scope* '() "A stack of names of nested C++ classes.")
+
+(defvar *struct-fields* '())
+
+(defvar *linkage* :C "NIL or :C")
+
+(defgeneric handle-node (node-type &key &allow-other-keys)
+  (:documentation "Handle a node of SWIG's parse tree of a C/C++ program"))
+
+(defmethod handle-node ((node-type t) &key &allow-other-keys)
+  ;; do nothing for unknown node types
+  nil)
+
+(defmethod handle-node ((node-type (eql 'cdecl)) &key name decl storage parms type &allow-other-keys)
+  (let ((swigtype (parse-swigtype (concatenate 'string decl type))))
+    (let ((*print-pretty* nil) ; or FUNCTION would be printed as #' by cmucl
+	  (*print-circle* t))
+      (format *uffi-output* "~&;; C Declaration: ~A ~A ~A ~A~%;;  with-parms ~W~%;;   of-type ~W~%"
+	      storage type name decl parms swigtype))
+    (multiple-value-bind (function-p arg-swigtype-list return-swigtype)
+	(swigtype-function-p swigtype)
+      (declare (ignore arg-swigtype-list))
+      (cond
+	((and (null *class-scope*) function-p
+	      (or (eql *linkage* :c)
+		  (string= storage "externc")))
+	 ;; ordinary top-level function with C linkage
+	 (let ((argnum 0)
+	       (argname-list '()))
+	   (flet ((unique-argname (name)
+		    ;; Sometimes the functions in SWIG interfaces
+		    ;; do not have unique names.  Make them unique
+		    ;; by adding a suffix.  Also avoid symbols
+		    ;; that are specially bound.
+		    (unless name
+		      (setq name (format nil "arg~D" argnum)))
+		    (let ((argname (make-cl-symbol name)))
+		      (when (boundp argname) ;specially bound
+			(setq argname (make-cl-symbol name :uninterned t)))
+		      (push argname argname-list)
+		      argname)))
+	     (let ((uffi-arg-list
+		    (mapcan (lambda (param)
+			      (incf argnum)
+			      (destructuring-bind (&key name type &allow-other-keys) param
+				(let ((uffi-type (uffi-type-spec (parse-swigtype type))))
+				  (cond
+				    ((not uffi-type)
+				     (format *uffi-output* "~&;; Warning: Cannot handle type ~S of argument `~A'~%"
+					     type name)
+				     (return-from handle-node))
+				    ((eq uffi-type :void)
+				     '())
+				    (t
+				     (let ((symbol (unique-argname name)))
+				       (list `(,symbol ,uffi-type))))))))
+			    parms))
+		   (uffi-return-type
+		    (uffi-type-spec return-swigtype)))
+	       (unless uffi-return-type
+		 (format *uffi-output* "~&;; Warning: Cannot handle return type `~S'~%"
+			 return-swigtype)
+		 (return-from handle-node))
+	       (emit-uffi-definition `(UFFI:DEF-FUNCTION ,name ,uffi-arg-list :RETURNING ,uffi-return-type))))))
+	((and (not (null *class-scope*)) (null (rest *class-scope*))
+	      (not function-p))	; class/struct member (no nested structs)
+	 (let ((uffi-type (uffi-type-spec swigtype)))
+	   (unless  uffi-type
+	     (format *uffi-output* "~&;; Warning: Cannot handle type ~S of struct field `~A'~%"
+		     type name)
+	     (return-from handle-node))
+	   (push `(,(make-cl-symbol name) ,uffi-type) *struct-fields*)))))))
+
+(defmethod handle-node ((node-type (eql 'class)) &key name children kind &allow-other-keys)
+  (format *uffi-output* "~&;; Class ~A~%" name)
+  (let ((*class-scope* (cons name *class-scope*))
+	(*struct-fields* '()))
+    (dolist (child children)
+      (apply 'handle-node child))
+    (emit-uffi-definition `(,(if (string= kind "union")
+				 'UFFI:DEF-UNION
+				 'UFFI:DEF-STRUCT)
+			    ,(make-cl-symbol name) ,@(nreverse *struct-fields*)))))
+
+(defmethod handle-node ((node-type (eql 'top)) &key children &allow-other-keys)
+  (dolist (child children)
+    (apply 'handle-node child)))
+  
+(defmethod handle-node ((node-type (eql 'include)) &key name children &allow-other-keys)
+  (format *uffi-output* ";; INCLUDE ~A~%" name)
+  (dolist (child children)
+    (apply 'handle-node child)))
+
+(defmethod handle-node ((node-type (eql 'extern)) &key name children &allow-other-keys)
+  (format *uffi-output* ";; EXTERN \"C\" ~A~%" name)
+  (let ((*linkage* :c))
+    (dolist (child children)
+      (apply 'handle-node child))))
+
+;;(defun compute-uffi-definitions (swig-interface)
+;;  (let ((*uffi-definitions* '()))
+;;    (handle-node swig-interface)
+;;    *uffi-definitions*))
+
+;; Test instances
+
+#||
+
+#+ignore
+(defvar *gifplot-interface*
+  (run-swig (merge-pathnames "Examples/GIFPlot/Interface/gifplot.i"
+			     *swig-source-directory*)
+	    :directory-search-list (list (merge-pathnames "Examples/GIFPlot/Interface/" *swig-source-directory*))))
+
+(defvar *simple-gifplot-interface*
+  (run-swig (merge-pathnames "Examples/GIFPlot/Include/gifplot.h"
+			     *swig-source-directory*)
+	    :directory-search-list (list (merge-pathnames "Examples/GIFPlot/Interface/" *swig-source-directory*))
+	    :module "gifplot"))
+
+(defvar *cplex-glue-directory* #p"/home/mkoeppe/cvs/cplex-glue/")
+
+(defvar *cplex-glue-interface*
+  (run-swig (merge-pathnames "cplex.i" *cplex-glue-directory*)
+	    :directory-search-list (list (merge-pathnames "Lib/guile"
+							  *swig-source-directory*)
+					 *cplex-glue-directory*)
+	    :ignore-errors t))
+	    
+  
+
+(require 'uffi)
+
+;;(let ((*uffi-primitive-type-alist* (cons '("Pixel" . :unsigned-int) *uffi-default-primitive-type-alist*)))
+;;  (eval (cons 'progn (compute-uffi-definitions *simple-gifplot-interface*))))
+
+
+(with-open-file (f "/tmp/swig-uffi.lisp" :direction :output
+		   :if-exists :supersede)
+  (let ((*uffi-definitions* '())
+	(*uffi-output* f)
+	(*uffi-primitive-type-alist*
+	 (cons '("Pixel" . :unsigned-int) *uffi-default-primitive-type-alist*)))
+    (apply 'handle-node *simple-gifplot-interface*)))
+
+#+cplex
+(with-open-file (f "/tmp/swig-uffi.lisp" :direction :output)
+  (let ((*uffi-definitions* '())
+	(*uffi-output* f)
+	(*uffi-primitive-type-alist*
+	 (cons '("Pixel" . :unsigned-int) *uffi-default-primitive-type-alist*)))
+    (apply 'handle-node *cplex-glue-interface*)))
+
+(compile-file "/tmp/swig-uffi.lisp")
+
+(uffi:load-foreign-library (merge-pathnames "Examples/GIFPlot/libgifplot.a"
+					    *swig-source-directory*))
+
+(load "/tmp/swig-uffi.lisp")
+
+(load (merge-pathnames "Examples/GIFPlot/Common-Lisp/full/runme.lisp" *swig-source-directory*))
+
+(action (namestring (merge-pathnames "Examples/GIFPlot/Common-Lisp/full/cmap"
+				     *swig-source-directory*)))
+
+||#
+
+;;; Link to SWIG itself
+
+#||
+
+(defparameter *c++-compiler* "g++")
+
+(defun stdc++-library (&key env)
+  (let ((error-output (make-string-output-stream)))
+    (let ((name-output (make-string-output-stream)))
+      (let ((proc (ext:run-program
+		   *c++-compiler*
+		   '("-print-file-name=libstdc++.so")
+		   :env env
+		   :input nil
+		   :output name-output
+		   :error error-output)))
+	(unless proc
+	  (error "Could not run ~A" *c++-compiler*))
+	(unless (zerop (ext:process-exit-code proc))
+	  (system:serve-all-events 0)
+	  (error "~A failed:~%~A" *c++-compiler*
+		 (get-output-stream-string error-output))))
+      (string-right-trim '(#\Newline) (get-output-stream-string name-output)))))
+
+(defvar *swig-interface* nil)
+
+(defvar *swig-uffi-pathname* #p"/tmp/swig-uffi.lisp")
+
+(defun link-swig ()
+  (setq *swig-interface*
+	(run-swig (merge-pathnames "Source/swig.i" *swig-source-directory*)
+		  :directory-search-list
+		  (list (merge-pathnames "Source/" *swig-source-directory*))
+		  :module "swig"
+		  :ignore-errors t
+		  :c++ t))
+  (with-open-file (f *swig-uffi-pathname* :direction :output)
+    (let ((*linkage* :c++)
+	  (*uffi-definitions* '())
+	  (*uffi-output* f)
+	  (*uffi-primitive-type-alist* *uffi-default-primitive-type-alist*))
+      (apply 'handle-node *swig-interface*)))
+  (compile-file *swig-uffi-pathname*)
+  (alien:load-foreign (merge-pathnames "Source/libswig.a"
+				       *swig-source-directory*)
+		      :libraries (list (stdc++-library)))
+  ;; FIXME: UFFI stuffes a "-l" in front of the passed library names
+  ;;  (uffi:load-foreign-library (merge-pathnames "Source/libswig.a"
+  ;;                                              *swig-source-directory*)
+  ;;                             :supporting-libraries
+  ;;                             (list (stdc++-library)))
+  (load (compile-file-pathname *swig-uffi-pathname*)))
+
+||#
+
+;;;; TODO:
+
+;; * How to do type lookups?  Is everything important that SWIG knows
+;;   about the types written out?  What to make of typemaps?
+;;
+;; * Wrapped functions should probably automatically COERCE their
+;;   arguments (as of type DOUBLE-FLOAT), to make the functions more
+;;   flexible?
+;;
+;; * Why are the functions created by FFI interpreted?
+;;
+;; * We can't deal with more complicated structs and C++ classes
+;; directly with the FFI; we have to emit SWIG wrappers that access
+;; those classes.
+;;
+;; * A CLOS layer where structure fields are mapped as slots.  It
+;; looks like we need MOP functions to implement this.
+;;
+;; * Maybe modify SWIG so that key-value hashes are distinguished from
+;; value-value hashes.
diff --git a/trunk/Examples/tcl/check.list b/trunk/Examples/tcl/check.list
new file mode 100644
index 0000000..8e7a8a9
--- /dev/null
+++ b/trunk/Examples/tcl/check.list
@@ -0,0 +1,16 @@
+# see top-level Makefile.in
+class
+constants
+contract
+enum
+funcptr
+import
+java
+multimap
+operator
+pointer
+reference
+simple
+std_vector
+value
+variables
diff --git a/trunk/Examples/tcl/class/Makefile b/trunk/Examples/tcl/class/Makefile
new file mode 100644
index 0000000..c01283c
--- /dev/null
+++ b/trunk/Examples/tcl/class/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/class/example.cxx b/trunk/Examples/tcl/class/example.cxx
new file mode 100644
index 0000000..1e8e203
--- /dev/null
+++ b/trunk/Examples/tcl/class/example.cxx
@@ -0,0 +1,28 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
diff --git a/trunk/Examples/tcl/class/example.dsp b/trunk/Examples/tcl/class/example.dsp
new file mode 100644
index 0000000..bf61494
--- /dev/null
+++ b/trunk/Examples/tcl/class/example.dsp
@@ -0,0 +1,152 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.cxx

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\example.h

+# End Source File

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/class/example.h b/trunk/Examples/tcl/class/example.h
new file mode 100644
index 0000000..46d9013
--- /dev/null
+++ b/trunk/Examples/tcl/class/example.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+
+
+
+  
diff --git a/trunk/Examples/tcl/class/example.i b/trunk/Examples/tcl/class/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/tcl/class/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/tcl/class/index.html b/trunk/Examples/tcl/class/index.html
new file mode 100644
index 0000000..fd8cfe5
--- /dev/null
+++ b/trunk/Examples/tcl/class/index.html
@@ -0,0 +1,274 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:class</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/tcl/class/</tt>
+<hr>
+
+<H2>Wrapping a simple C++ class</H2>
+
+<p>
+This example illustrates the most primitive form of C++ class wrapping performed
+by SWIG.  In this case, C++ classes are simply transformed into a collection of
+C-style functions that provide access to class members.
+
+<h2>The C++ Code</h2>
+
+Suppose you have some C++ classes described by the following (and admittedly lame) 
+header file:
+
+<blockquote>
+<pre>
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+A simple SWIG interface for this can be built by simply grabbing the header file
+like this:
+
+<blockquote>
+<pre>
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+</pre>
+</blockquote>
+
+Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> option like this:
+<blockquote>
+<pre>
+% swig -c++ -tcl example.i
+</pre>
+</blockquote>
+
+<h2>Some sample Tcl scripts</h2>
+
+SWIG performs two forms of C++ wrapping-- a low level interface and a high level widget-like interface.
+<ul>
+<li>
+Click <a href="example1.tcl">here</a> to see a script that calls the C++ functions using the
+low-level interface.
+<li>
+Click <a href="example2.tcl">here</a> to see a the same script written with the high-level
+interface.
+</ul>
+
+<h2>Key points</h2>
+
+<ul>
+<li>The low-level C++ interface works like this:
+<p>
+<ul>
+<li>To create a new object, you call a constructor like this:
+
+<blockquote>
+<pre>
+set c [new_Circle 10.0]
+</pre>
+</blockquote>
+
+<p>
+<li>To access member data, a pair of accessor functions are used.
+For example:
+
+<blockquote>
+<pre>
+Shape_x_set $c 15        ;# Set member data
+set x [Shape_x_get $c]   ;# Get member data
+</pre>
+</blockquote>
+
+Note: when accessing member data, the name of the base class must
+be used such as <tt>Shape_x_get</tt>
+
+<p>
+<li>To invoke a member function, you simply do this
+
+<blockquote>
+<pre>
+puts "The area is [Shape_area $c]"
+</pre>
+</blockquote>
+
+<p>
+<li>Type checking knows about the inheritance structure of C++. For example:
+
+<blockquote>
+<pre>
+Shape_area $c       # Works (c is a Shape)
+Circle_area $c      # Works (c is a Circle)
+Square_area $c      # Fails (c is definitely not a Square)
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a destructor, simply do this
+
+<blockquote>
+<pre>
+delete_Shape $c     # Deletes a shape
+</pre>
+</blockquote>
+
+<p>
+<li>Static member variables are wrapped as C global variables.  For example:
+
+<blockquote>
+<pre>
+set n $Shape_nshapes    # Get a static data member
+set Shapes_nshapes 13   # Set a static data member
+</pre>
+</blockquote>
+
+</ul>
+
+<p>
+<li>The high-level interface works like a Tk widget
+
+<p>
+<ul>
+<li>To create a new object, you call a constructor like this:
+
+<blockquote>
+<pre>
+Circle c 10      # c becomes a name for the Circle object
+</pre>
+</blockquote>
+
+<p>
+<li>To access member data, use cget and configure methods.
+For example:
+
+<blockquote>
+<pre>
+c configure -x 15        ;# Set member data
+set x [c cget -x]        ;# Get member data
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a member function, you simply do this
+
+<blockquote>
+<pre>
+puts "The area is [c area]"
+</pre>
+</blockquote>
+
+<p>
+<li>To invoke a destructor, simply destroy the object name like this:
+
+<blockquote>
+<pre>
+rename c ""         # c goes away
+</pre>
+</blockquote>
+
+<p>
+<li>Static member variables are wrapped as C global variables.  For example:
+
+<blockquote>
+<pre>
+set n $Shape_nshapes    # Get a static data member
+set Shapes_nshapes 13   # Set a static data member
+</pre>
+</blockquote>
+
+</ul>
+</ul>
+
+<h2>General Comments</h2>
+
+<ul>
+<li>The low-level function interface is much faster than the high-level interface.
+In fact, all the higher level interface does is call functions in the low-level interface.
+
+<p>
+<li>SWIG *does* know how to properly perform upcasting of objects in an inheritance
+hierarchy (including multiple inheritance).  Therefore it is perfectly safe to pass
+an object of a derived class to any function involving a base class.
+
+<p>
+<li>A wide variety of C++ features are not currently supported by SWIG.  Here is the
+short and incomplete list:
+
+<p>
+<ul>
+<li>Overloaded methods and functions.  SWIG wrappers don't know how to resolve name
+conflicts so you must give an alternative name to any overloaded method name using the
+%name directive like this:
+
+<blockquote>
+<pre>
+void foo(int a);  
+%name(foo2) void foo(double a, double b);
+</pre>
+</blockquote>
+
+<p>
+<li>Overloaded operators.  Not supported at all. The only workaround for this is
+to write a helper function. For example:
+
+<blockquote>
+<pre>
+%inline %{
+    Vector *vector_add(Vector *a, Vector *b) {
+          ... whatever ...
+    }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>Namespaces.  Not supported at all. Won't be supported until SWIG2.0 (if at all).
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/tcl/class/runme.tcl b/trunk/Examples/tcl/class/runme.tcl
new file mode 100644
index 0000000..c7f4725
--- /dev/null
+++ b/trunk/Examples/tcl/class/runme.tcl
@@ -0,0 +1,50 @@
+# file: runme.tcl
+
+# This file illustrates the high level C++ interface.
+# In this case C++ classes work kind of like Tk widgets
+
+catch { load ./example[info sharedlibextension] example}
+
+# ----- Object creation -----
+
+puts "Creating some objects:"
+Circle c 10
+puts "    Created circle [c cget -this]"
+Square s 10
+puts "    Created square [s cget -this]"
+
+# ----- Access a static member -----
+
+puts "\nA total of $Shape_nshapes shapes were created"
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c configure -x 20 -y 30
+s configure -x -10 -y 5
+
+puts "\nHere is their current position:"
+puts "    Circle = ([c cget -x], [c cget -y])"
+puts "    Square = ([s cget -x], [s cget -y])"
+
+# ----- Call some methods -----
+
+puts "\nHere are some properties of the shapes:"
+foreach o "c s" {
+      puts "    [$o cget -this]"
+      puts "        area      = [$o area]"
+      puts "        perimeter = [$o perimeter]"
+}
+
+# ----- Delete everything -----
+
+puts "\nGuess I'll clean up now"
+
+# Note: this invokes the virtual destructor
+rename c ""
+rename s ""
+
+puts "$Shape_nshapes shapes remain"
+puts "Goodbye"
+
diff --git a/trunk/Examples/tcl/class/runme2.tcl b/trunk/Examples/tcl/class/runme2.tcl
new file mode 100644
index 0000000..88ec2f6
--- /dev/null
+++ b/trunk/Examples/tcl/class/runme2.tcl
@@ -0,0 +1,70 @@
+# file: runme2.tcl
+
+# This file illustrates the low-level C++ interface
+# created by SWIG.  In this case, all of our C++ classes
+# get converted into function calls.
+
+catch { load ./example[info sharedlibextension] example}
+
+# ----- Object creation -----
+
+puts "Creating some objects:"
+set c [new_Circle 10]
+puts "    Created circle $c"
+set s [new_Square 10]
+puts "    Created square $s"
+
+# ----- Access a static member -----
+
+puts "\nA total of $Shape_nshapes shapes were created"
+
+# ----- Member data access -----
+
+# Set the location of the object
+# Note: the base class must be used since that's where x and y
+# were declared.
+
+Shape_x_set $c 20
+Shape_y_set $c 30
+Shape_x_set $s -10
+Shape_y_set $s 5
+
+puts "\nHere is their current position:"
+puts "    Circle = ([Shape_x_get $c], [Shape_y_get $c])"
+puts "    Square = ([Shape_x_get $s], [Shape_y_get $s])"
+
+# ----- Call some methods -----
+
+puts "\nHere are some properties of the shapes:"
+foreach o "$c $s" {
+      puts "    $o"
+      puts "        area      = [Shape_area $o]"
+      puts "        perimeter = [Shape_perimeter $o]"
+}
+# Notice how the Shape_area() and Shape_perimeter() functions really
+# invoke the appropriate virtual method on each object.
+
+# ----- Try to cause a type error -----
+
+puts "\nI'm going to try and break the type system"
+
+if { [catch {
+    # Bad script!
+    Square_area $c         # Try to invoke Square method on a Circle
+    puts "    Bad bad SWIG!"
+
+}]} {
+    puts "    Well, it didn't work. Good SWIG."
+}
+
+# ----- Delete everything -----
+
+puts "\nGuess I'll clean up now"
+
+# Note: this invokes the virtual destructor
+delete_Shape $c
+delete_Shape $s
+
+puts "$Shape_nshapes shapes remain"
+puts "Goodbye"
+
diff --git a/trunk/Examples/tcl/constants/Makefile b/trunk/Examples/tcl/constants/Makefile
new file mode 100644
index 0000000..ba28f47
--- /dev/null
+++ b/trunk/Examples/tcl/constants/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       =
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/constants/example.i b/trunk/Examples/tcl/constants/example.i
new file mode 100644
index 0000000..4f7b1a4
--- /dev/null
+++ b/trunk/Examples/tcl/constants/example.i
@@ -0,0 +1,27 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following directives also produce constants */
+
+%constant int iconst = 37;
+%constant double fconst = 3.14;
+
+
diff --git a/trunk/Examples/tcl/constants/index.html b/trunk/Examples/tcl/constants/index.html
new file mode 100644
index 0000000..fa332c6
--- /dev/null
+++ b/trunk/Examples/tcl/constants/index.html
@@ -0,0 +1,61 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:constants</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/tcl/constants/</tt>
+<hr>
+
+<H2>Wrapping C Constants</H2>
+
+<p>
+When SWIG encounters C preprocessor macros and C declarations that look like constants,
+it creates Tcl variables with an identical value.  Click <a href="example.i">here</a>
+to see a SWIG interface with some constant declarations in it.
+
+<h2>Accessing Constants from Tcl</h2>
+
+Click <a href="runme.tcl">here</a> to see a script that prints out the values
+of the constants contained in the above file.
+
+<h2>Key points</h2>
+
+<ul>
+<li>The values of preprocessor macros are converted into Tcl read-only variables.
+<li>Types are inferred by syntax (e.g., "3" is an integer and "3.5" is a float).
+<li>Character constants such as 'x' are converted into strings.
+<li>C string literals such as "Hello World" are converted into strings.
+<li>Macros that are not fully defined are simply ignored.  For example:
+<blockquote>
+<pre>
+#define EXTERN extern
+</pre>
+</blockquote>
+is ignored because SWIG has no idea what type of variable this would be.
+
+<p>
+<li>Expressions are allowed provided that all of their components are defined. Otherwise, the constant is ignored.
+
+<li>Certain C declarations involving 'const' are also turned into Tcl constants. 
+<li>The constants that appear in a SWIG interface file do not have to appear in any sort
+of matching C source file since the creation of a constant does not require linkage
+to a stored value (i.e., a value held in a C global variable or memory location).
+<li>Since constants are turned into Tcl variables, you have to use the global
+statement when accessing from a procedure. For example:
+
+<blockquote>
+<pre>
+proc foo {} {
+    global ICONST          # Some C constant
+    puts $ICONST
+}
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+
+</body>
+</html>
diff --git a/trunk/Examples/tcl/constants/runme.tcl b/trunk/Examples/tcl/constants/runme.tcl
new file mode 100644
index 0000000..b504ba8
--- /dev/null
+++ b/trunk/Examples/tcl/constants/runme.tcl
@@ -0,0 +1,26 @@
+# file: runme.tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+puts "ICONST  = $ICONST (should be 42)"
+puts "FCONST  = $FCONST (should be 2.1828)"
+puts "CCONS T = $CCONST (should be 'x')"
+puts "CCONST2 = $CCONST2 (this should be on a separate line)"
+puts "SCONST  = $SCONST (should be 'Hello World')"
+puts "SCONST2 = $SCONST2 (should be '\"Hello World\"')" 
+puts "EXPR    = $EXPR (should be 48.5484)"
+puts "iconst  = $iconst (should be 37)"
+puts "fconst  = $fconst (should be 3.14)"
+
+if { [catch {
+    puts "EXTERN = $EXTERN (Arg! This shouldn't print anything)"
+}]} {
+    puts "EXTERN isn't defined (good)"
+}
+
+if { [catch {
+    puts "FOO    = $FOO (Arg! This shouldn't print anything)"
+}]} {
+    puts "FOO isn't defined (good)"
+}
+
diff --git a/trunk/Examples/tcl/contract/Makefile b/trunk/Examples/tcl/contract/Makefile
new file mode 100644
index 0000000..91a139a
--- /dev/null
+++ b/trunk/Examples/tcl/contract/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+SWIGOPT    =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/contract/example.c b/trunk/Examples/tcl/contract/example.c
new file mode 100644
index 0000000..1a64454
--- /dev/null
+++ b/trunk/Examples/tcl/contract/example.c
@@ -0,0 +1,23 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int fact(int n) {
+  if (n <= 0) return 1;
+  return n*fact(n-1);
+}
+
+
diff --git a/trunk/Examples/tcl/contract/example.dsp b/trunk/Examples/tcl/contract/example.dsp
new file mode 100644
index 0000000..296cb31
--- /dev/null
+++ b/trunk/Examples/tcl/contract/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/contract/example.i b/trunk/Examples/tcl/contract/example.i
new file mode 100644
index 0000000..8fd1a80
--- /dev/null
+++ b/trunk/Examples/tcl/contract/example.i
@@ -0,0 +1,21 @@
+/* File : example.i */
+%module example
+
+%contract gcd(int x, int y) {
+require:
+	x >= 0;
+	y >= 0;
+}
+
+%contract fact(int n) {
+require:
+	n >= 0;
+ensure:
+	fact >= 1;
+}
+
+%inline %{
+extern int    gcd(int x, int y);
+extern int    fact(int n);
+extern double Foo;
+%}
diff --git a/trunk/Examples/tcl/contract/runme.tcl b/trunk/Examples/tcl/contract/runme.tcl
new file mode 100644
index 0000000..3a6ce10
--- /dev/null
+++ b/trunk/Examples/tcl/contract/runme.tcl
@@ -0,0 +1,22 @@
+# file: runme.tcl
+# Try to load as a dynamic module.
+
+catch { load ./example[info sharedlibextension] example}
+
+# Call our gcd() function
+set x 42
+set y 105
+set g [gcd $x $y]
+puts "The gcd of $x and $y is $g"
+
+# Manipulate the Foo global variable
+
+# Output its current value
+puts "Foo = $Foo"
+
+# Change its value
+set Foo 3.1415926
+
+# See if the change took effect
+puts "Foo = $Foo"
+
diff --git a/trunk/Examples/tcl/enum/Makefile b/trunk/Examples/tcl/enum/Makefile
new file mode 100644
index 0000000..c01283c
--- /dev/null
+++ b/trunk/Examples/tcl/enum/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/enum/example.cxx b/trunk/Examples/tcl/enum/example.cxx
new file mode 100644
index 0000000..6785e57
--- /dev/null
+++ b/trunk/Examples/tcl/enum/example.cxx
@@ -0,0 +1,37 @@
+/* File : example.c */
+
+#include "example.h"
+#include <stdio.h>
+
+void Foo::enum_test(speed s) {
+  if (s == IMPULSE) {
+    printf("IMPULSE speed\n");
+  } else if (s == WARP) {
+    printf("WARP speed\n");
+  } else if (s == LUDICROUS) {
+    printf("LUDICROUS speed\n");
+  } else {
+    printf("Unknown speed\n");
+  }
+}
+
+void enum_test(color c, Foo::speed s) {
+  if (c == RED) {
+    printf("color = RED, ");
+  } else if (c == BLUE) {
+    printf("color = BLUE, ");
+  } else if (c == GREEN) {
+    printf("color = GREEN, ");
+  } else {
+    printf("color = Unknown color!, ");
+  }
+  if (s == Foo::IMPULSE) {
+    printf("speed = IMPULSE speed\n");
+  } else if (s == Foo::WARP) {
+    printf("speed = WARP speed\n");
+  } else if (s == Foo::LUDICROUS) {
+    printf("speed = LUDICROUS speed\n");
+  } else {
+    printf("speed = Unknown speed!\n");
+  }
+}
diff --git a/trunk/Examples/tcl/enum/example.h b/trunk/Examples/tcl/enum/example.h
new file mode 100644
index 0000000..525d62a
--- /dev/null
+++ b/trunk/Examples/tcl/enum/example.h
@@ -0,0 +1,13 @@
+/* File : example.h */
+
+enum color { RED, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
diff --git a/trunk/Examples/tcl/enum/example.i b/trunk/Examples/tcl/enum/example.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/tcl/enum/example.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/tcl/enum/index.html b/trunk/Examples/tcl/enum/index.html
new file mode 100644
index 0000000..559f6a8
--- /dev/null
+++ b/trunk/Examples/tcl/enum/index.html
@@ -0,0 +1,35 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:enum</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/tcl/enum/</tt>
+<hr>
+
+<H2>Wrapping enumerations</H2>
+
+<p>
+This example tests SWIG's ability to wrap enumerations.  By default, SWIG
+converts enumeration specifications into integer constants.  Further use
+of enumerated types are handled as integers.
+
+<ul>
+<li><a href="example.h">example.h</a>.  Header file containing some enums.
+<li><a href="example.i">example.i</a>.  Interface file.
+<li><a href="runme.tcl">runme.tcl</a>. Sample Tcl script.
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>SWIG allows arbitrary integers to be passed as enum values.  However,
+the result of passing an integer not corresponding to any of the values
+specified in the <tt>enum</tt> specification is undefined.
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/tcl/enum/runme.tcl b/trunk/Examples/tcl/enum/runme.tcl
new file mode 100644
index 0000000..3d4e52a
--- /dev/null
+++ b/trunk/Examples/tcl/enum/runme.tcl
@@ -0,0 +1,32 @@
+# file: runme.tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+# ----- Object creation -----
+
+# Print out the value of some enums
+puts "*** color ***"
+puts "    RED    = $RED"
+puts "    BLUE   = $BLUE"
+puts "    GREEN  = $GREEN"
+
+puts "\n*** Foo::speed ***"
+puts "    Foo_IMPULSE   = $Foo_IMPULSE"
+puts "    Foo_WARP      = $Foo_WARP"
+puts "    Foo_LUDICROUS = $Foo_LUDICROUS"
+
+
+puts "\nTesting use of enums with functions\n"
+
+enum_test $RED   $Foo_IMPULSE
+enum_test $BLUE  $Foo_WARP
+enum_test $GREEN $Foo_LUDICROUS
+enum_test 1234   5678
+
+puts "\nTesting use of enum with class method"
+Foo f
+
+f enum_test $Foo_IMPULSE
+f enum_test $Foo_WARP
+f enum_test $Foo_LUDICROUS
+
diff --git a/trunk/Examples/tcl/funcptr/Makefile b/trunk/Examples/tcl/funcptr/Makefile
new file mode 100644
index 0000000..bed049a
--- /dev/null
+++ b/trunk/Examples/tcl/funcptr/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/funcptr/example.c b/trunk/Examples/tcl/funcptr/example.c
new file mode 100644
index 0000000..5c4a3da
--- /dev/null
+++ b/trunk/Examples/tcl/funcptr/example.c
@@ -0,0 +1,19 @@
+/* File : example.c */
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int sub(int a, int b) {
+  return a-b;
+}
+
+int mul(int a, int b) {
+  return a*b;
+}
+
+int (*funcvar)(int,int) = add;
diff --git a/trunk/Examples/tcl/funcptr/example.h b/trunk/Examples/tcl/funcptr/example.h
new file mode 100644
index 0000000..9936e24
--- /dev/null
+++ b/trunk/Examples/tcl/funcptr/example.h
@@ -0,0 +1,9 @@
+/* file: example.h */
+
+extern int do_op(int,int, int (*op)(int,int));
+extern int add(int,int);
+extern int sub(int,int);
+extern int mul(int,int);
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/tcl/funcptr/example.i b/trunk/Examples/tcl/funcptr/example.i
new file mode 100644
index 0000000..8b3bef6
--- /dev/null
+++ b/trunk/Examples/tcl/funcptr/example.i
@@ -0,0 +1,16 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+/* Wrap a function taking a pointer to a function */
+extern int  do_op(int a, int b, int (*op)(int, int));
+
+/* Now install a bunch of "ops" as constants */
+%constant int (*ADD)(int,int) = add;
+%constant int (*SUB)(int,int) = sub;
+%constant int (*MUL)(int,int) = mul;
+
+extern int (*funcvar)(int,int);
+
diff --git a/trunk/Examples/tcl/funcptr/index.html b/trunk/Examples/tcl/funcptr/index.html
new file mode 100644
index 0000000..b822962
--- /dev/null
+++ b/trunk/Examples/tcl/funcptr/index.html
@@ -0,0 +1,90 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:funcptr</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/tcl/funcptr/</tt>
+<hr>
+
+<H2>Pointers to Functions</H2>
+
+<p>
+Okay, just what in the heck does SWIG do with a declaration like this?
+
+<blockquote>
+<pre>
+int do_op(int a, int b, int (*op)(int, int));
+</pre>
+</blockquote>
+
+Well, it creates a wrapper as usual.  Of course, that does raise some
+questions about the third argument (the pointer to a function). 
+
+<p>
+In this case, SWIG will wrap the function pointer as it does for all other
+pointers.  However, in order to actually call this function from a script,
+you will need to pass some kind of C function pointer object.  In C,
+this is easy, you just supply a function name as an argument like this:
+
+<blockquote>
+<pre>
+/* Some callback function */
+int add(int a, int b) {
+   return a+b;
+} 
+...
+int r = do_op(x,y,add);
+</pre>
+</blockquote>
+
+To make this work with SWIG, you will need to do a little extra work.  Specifically,
+you need to create some function pointer objects using the %constant directive like this:
+
+<blockquote>
+<pre>
+%constant(int (*)(int,int)) ADD = add;
+</pre>
+</blockquote>
+
+Now, in a script, you would do this:
+
+<blockquote>
+<pre>
+set r [do_op $x $y $ADD]
+</pre>
+</blockquote>
+
+<h2>An Example</h2>
+
+Here are some files that illustrate this with a simple example:
+
+<ul>
+<li><a href="example.c">example.c</a>
+<li><a href="example.h">example.h</a>
+<li><a href="example.i">example.i</a> (SWIG interface)
+<li><a href="runme.tcl">runme.tcl</a> (Sample script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>The value of a function pointer must correspond to a function written in C or C++.
+It is not possible to pass an arbitrary Tcl function object in as a substitute for a C 
+function pointer.
+
+<p>
+<li>A Tcl function can be used as a C/C++ callback if you write some
+clever typemaps and are very careful about how you create your extension.
+This is an advanced topic not covered here.
+</ul>
+
+<hr>
+</body>
+</html>
+
+
+
+
diff --git a/trunk/Examples/tcl/funcptr/runme.tcl b/trunk/Examples/tcl/funcptr/runme.tcl
new file mode 100644
index 0000000..7e676c2
--- /dev/null
+++ b/trunk/Examples/tcl/funcptr/runme.tcl
@@ -0,0 +1,21 @@
+# file: runme.tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+set a 37
+set b 42
+
+# Now call our C function with a bunch of callbacks
+
+puts "Trying some C callback functions"
+puts "    a        = $a"
+puts "    b        = $b"
+puts "    ADD(a,b) = [do_op $a $b $ADD]"
+puts "    SUB(a,b) = [do_op $a $b $SUB]"
+puts "    MUL(a,b) = [do_op $a $b $MUL]"
+
+puts "Here is what the C callback function objects look like in Tcl"
+puts "    ADD      = $ADD"
+puts "    SUB      = $SUB"
+puts "    MUL      = $MUL"
+
diff --git a/trunk/Examples/tcl/import/Makefile b/trunk/Examples/tcl/import/Makefile
new file mode 100644
index 0000000..6b257aa
--- /dev/null
+++ b/trunk/Examples/tcl/import/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SWIGOPT    =
+LIBS       =
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' tcl_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' tcl_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' tcl_cpp
+	$(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \
+	LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' tcl_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/import/README b/trunk/Examples/tcl/import/README
new file mode 100644
index 0000000..b2a65f5
--- /dev/null
+++ b/trunk/Examples/tcl/import/README
@@ -0,0 +1,37 @@
+This example tests the %import directive and working with multiple modules.
+
+Use 'tclsh runme.tcl' to run a test.
+
+Overview:
+---------
+
+The example defines 4 different extension modules--each wrapping
+a separate C++ class.
+
+     base.i     -  Base class
+     foo.i      -  Foo class derived from Base
+     bar.i      -  Bar class derived from Base
+     spam.i     -  Spam class derived from Bar
+
+Each module used %import to refer to another module.  For
+example, the 'foo.i' module uses '%import base.i' to get
+definitions for its base class.
+
+If everything is okay, all of the modules will load properly and
+type checking will work correctly. Caveat: Some compilers, for example
+gcc-3.2.x, generate broken vtables with the inline methods in this test.
+This is not a SWIG problem and can usually be solved with non-inlined
+destructors compiled into separate shared objects/DLLs.
+
+Unix:
+-----
+- Run make
+- Run the test as described above
+
+Windows:
+--------
+- Use the Visual C++ 6 workspace file (example.dsw). The Batch build option
+  in the Build menu is usually the easiest way to do this. Only use the Release
+  builds not the Debug builds.
+- Run the test as described above
+
diff --git a/trunk/Examples/tcl/import/bar.dsp b/trunk/Examples/tcl/import/bar.dsp
new file mode 100644
index 0000000..35b4e60
--- /dev/null
+++ b/trunk/Examples/tcl/import/bar.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="bar" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=bar - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "bar.mak" CFG="bar - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "bar - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "bar - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"bar.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BAR_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"bar.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "bar - Win32 Debug"

+# Name "bar - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\bar_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\bar.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\bar.i

+

+!IF  "$(CFG)" == "bar - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "bar - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\bar.i

+InputName=bar

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/import/bar.h b/trunk/Examples/tcl/import/bar.h
new file mode 100644
index 0000000..fa4185f
--- /dev/null
+++ b/trunk/Examples/tcl/import/bar.h
@@ -0,0 +1,22 @@
+#include "base.h"
+
+class Bar : public Base {
+ public:
+  Bar() { }
+  ~Bar() { }
+  virtual void A() { 
+    printf("I'm Bar::A\n");
+  }
+  void B() {
+    printf("I'm Bar::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Bar *fromBase(Base *b) {
+    return dynamic_cast<Bar *>(b);
+  }
+
+};
+
+
diff --git a/trunk/Examples/tcl/import/bar.i b/trunk/Examples/tcl/import/bar.i
new file mode 100644
index 0000000..5816cbe
--- /dev/null
+++ b/trunk/Examples/tcl/import/bar.i
@@ -0,0 +1,9 @@
+%module bar
+%{
+#include "bar.h"
+%}
+
+%import base.i
+%include "bar.h"
+
+
diff --git a/trunk/Examples/tcl/import/base.dsp b/trunk/Examples/tcl/import/base.dsp
new file mode 100644
index 0000000..74870cc
--- /dev/null
+++ b/trunk/Examples/tcl/import/base.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="base" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=base - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "base.mak" CFG="base - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "base - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "base - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"base.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "BASE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"base.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "base - Win32 Debug"

+# Name "base - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\base_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\base.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\base.i

+

+!IF  "$(CFG)" == "base - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "base - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\base.i

+InputName=base

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/import/base.h b/trunk/Examples/tcl/import/base.h
new file mode 100644
index 0000000..5a266f6
--- /dev/null
+++ b/trunk/Examples/tcl/import/base.h
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+class Base {
+ public:
+     Base() { };
+     virtual ~Base() { };
+     virtual void A() {
+         printf("I'm Base::A\n");
+     }
+     void B() {
+       printf("I'm Base::B\n");
+     }
+     virtual Base *toBase() {
+       return static_cast<Base *>(this);
+     }
+};
+ 
+        
diff --git a/trunk/Examples/tcl/import/base.i b/trunk/Examples/tcl/import/base.i
new file mode 100644
index 0000000..f6e19ef
--- /dev/null
+++ b/trunk/Examples/tcl/import/base.i
@@ -0,0 +1,6 @@
+%module base
+%{
+#include "base.h"
+%}
+
+%include base.h
diff --git a/trunk/Examples/tcl/import/example.dsw b/trunk/Examples/tcl/import/example.dsw
new file mode 100644
index 0000000..d395d46
--- /dev/null
+++ b/trunk/Examples/tcl/import/example.dsw
@@ -0,0 +1,65 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00

+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!

+

+###############################################################################

+

+Project: "bar"=.\bar.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "base"=.\base.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "foo"=.\foo.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Project: "spam"=.\spam.dsp - Package Owner=<4>

+

+Package=<5>

+{{{

+}}}

+

+Package=<4>

+{{{

+}}}

+

+###############################################################################

+

+Global:

+

+Package=<5>

+{{{

+}}}

+

+Package=<3>

+{{{

+}}}

+

+###############################################################################

+

diff --git a/trunk/Examples/tcl/import/foo.dsp b/trunk/Examples/tcl/import/foo.dsp
new file mode 100644
index 0000000..ac7f09f
--- /dev/null
+++ b/trunk/Examples/tcl/import/foo.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="foo" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=foo - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "foo.mak" CFG="foo - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "foo - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "foo - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"foo.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FOO_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"foo.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "foo - Win32 Debug"

+# Name "foo - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\foo_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\foo.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\foo.i

+

+!IF  "$(CFG)" == "foo - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "foo - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\foo.i

+InputName=foo

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/import/foo.h b/trunk/Examples/tcl/import/foo.h
new file mode 100644
index 0000000..dd51840
--- /dev/null
+++ b/trunk/Examples/tcl/import/foo.h
@@ -0,0 +1,21 @@
+#include "base.h"
+
+class Foo : public Base {
+ public:
+  Foo() { }
+  ~Foo() { }
+  virtual void A() { 
+    printf("I'm Foo::A\n");
+  }
+  void B() {
+    printf("I'm Foo::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  static Foo *fromBase(Base *b) {
+    return dynamic_cast<Foo *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/tcl/import/foo.i b/trunk/Examples/tcl/import/foo.i
new file mode 100644
index 0000000..27feb2e
--- /dev/null
+++ b/trunk/Examples/tcl/import/foo.i
@@ -0,0 +1,8 @@
+%module foo
+%{
+#include "foo.h"
+%}
+
+%import base.i
+%include "foo.h"
+
diff --git a/trunk/Examples/tcl/import/runme.tcl b/trunk/Examples/tcl/import/runme.tcl
new file mode 100644
index 0000000..1227d7b
--- /dev/null
+++ b/trunk/Examples/tcl/import/runme.tcl
@@ -0,0 +1,114 @@
+# file: runme.tcl
+# Test various properties of classes defined in separate modules
+
+puts "Testing the %import directive"
+catch { load ./base[info sharedlibextension] base}
+catch { load ./foo[info sharedlibextension] foo}
+catch { load ./bar[info sharedlibextension] bar}
+catch { load ./spam[info sharedlibextension] spam}
+
+# Create some objects
+
+puts "Creating some objects"
+
+set a [Base]
+set b [Foo]
+set c [Bar]
+set d [Spam]
+
+# Try calling some methods
+puts "Testing some methods"
+puts "Should see 'Base::A' ---> "
+$a A
+puts "Should see 'Base::B' ---> "
+$a B
+
+puts  "Should see 'Foo::A' ---> "
+$b A
+puts  "Should see 'Foo::B' ---> "
+$b B
+
+puts  "Should see 'Bar::A' ---> "
+$c A
+puts  "Should see 'Bar::B' ---> "
+$c B
+
+puts  "Should see 'Spam::A' ---> "
+$d A
+puts  "Should see 'Spam::B' ---> "
+$d B
+
+# Try some casts
+
+puts "\nTesting some casts\n"
+
+Base x -this [$a toBase]
+puts "Should see 'Base::A' ---> "
+x A
+puts "Should see 'Base::B' ---> "
+x B
+rename x ""
+
+Base x -this [$b toBase]
+puts "Should see 'Foo::A' ---> "
+x A
+puts  "Should see 'Base::B' ---> "
+x B
+rename x ""
+
+Base x -this [$c toBase]
+puts  "Should see 'Bar::A' ---> "
+x A
+puts  "Should see 'Base::B' ---> "
+x B
+rename x ""
+
+Base x -this [$d toBase]
+puts  "Should see 'Spam::A' ---> "
+x A
+puts  "Should see 'Base::B' ---> "
+x B
+rename x ""
+
+Bar x -this [$d toBar]
+puts  "Should see 'Bar::B' ---> "
+x B
+rename x ""
+
+puts "\nTesting some dynamic casts\n"
+Base x -this [$d toBase]
+
+puts  "Spam -> Base -> Foo : "
+set y [Foo_fromBase [x cget -this]]
+if {$y != "NULL"} {
+      puts "bad swig"
+} {
+      puts "good swig"
+}
+
+puts  "Spam -> Base -> Bar : "
+set y [Bar_fromBase [x cget -this]]
+if {$y != "NULL"} {
+      puts "good swig"
+} {
+      puts "bad swig"
+}
+      
+puts  "Spam -> Base -> Spam : "
+set y [Spam_fromBase [x cget -this]]
+if {$y != "NULL"} {
+      puts "good swig"
+} {
+      puts "bad swig"
+}
+
+puts  "Foo -> Spam : "
+set y [Spam_fromBase $b]
+if {$y != "NULL"} {
+      puts "bad swig"
+} {
+      puts "good swig"
+}
+
+
+
diff --git a/trunk/Examples/tcl/import/spam.dsp b/trunk/Examples/tcl/import/spam.dsp
new file mode 100644
index 0000000..db9ade0
--- /dev/null
+++ b/trunk/Examples/tcl/import/spam.dsp
@@ -0,0 +1,144 @@
+# Microsoft Developer Studio Project File - Name="spam" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=spam - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For spam:

+!MESSAGE 

+!MESSAGE NMAKE /f "spam.mak" CFG="spam - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "spam - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "spam - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GR /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"spam.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GR /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SPAM_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"spam.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "spam - Win32 Debug"

+# Name "spam - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\spam_wrap.cxx

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# Begin Source File

+

+SOURCE=.\spam.h

+# End Source File

+# End Group

+# Begin Source File

+

+SOURCE=.\spam.i

+

+!IF  "$(CFG)" == "spam - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "spam - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\spam.i

+InputName=spam

+

+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -c++ -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/import/spam.h b/trunk/Examples/tcl/import/spam.h
new file mode 100644
index 0000000..b4e7a26
--- /dev/null
+++ b/trunk/Examples/tcl/import/spam.h
@@ -0,0 +1,24 @@
+#include "bar.h"
+
+class Spam : public Bar {
+ public:
+  Spam() { }
+  ~Spam() { }
+  virtual void A() { 
+    printf("I'm Spam::A\n");
+  }
+  void B() {
+    printf("I'm Spam::B\n");
+  }
+  virtual Base *toBase() {
+    return static_cast<Base *>(this);
+  }
+  virtual Bar *toBar() {
+    return static_cast<Bar *>(this);
+  }
+  static Spam *fromBase(Base *b) {
+    return dynamic_cast<Spam *>(b);
+  }
+};
+
+
diff --git a/trunk/Examples/tcl/import/spam.i b/trunk/Examples/tcl/import/spam.i
new file mode 100644
index 0000000..d3d9121
--- /dev/null
+++ b/trunk/Examples/tcl/import/spam.i
@@ -0,0 +1,9 @@
+%module spam
+%{
+#include "spam.h"
+%}
+
+%import bar.i
+%include "spam.h"
+
+
diff --git a/trunk/Examples/tcl/index.html b/trunk/Examples/tcl/index.html
new file mode 100644
index 0000000..b327260
--- /dev/null
+++ b/trunk/Examples/tcl/index.html
@@ -0,0 +1,70 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl</title>
+</head>
+
+<body bgcolor="#ffffff">
+<H1>SWIG Tcl Examples</H1>
+
+<p>
+The following examples illustrate the use of SWIG with Tcl.
+
+<ul>
+<li><a href="simple/index.html">simple</a>.  A minimal example showing how SWIG can
+be used to wrap a C function and a global variable.
+<li><a href="constants/index.html">constants</a>.  This shows how preprocessor macros and
+certain C declarations are turned into constants.
+<li><a href="variables/index.html">variables</a>.  How SWIG can be used to wrap C global variables.
+<li><a href="value/index.html">value</a>. How to pass and return structures by value.
+<li><a href="class/index.html">class</a>. How wrap a simple C++ class.
+<li><a href="reference/index.html">reference</a>. C++ references.
+<li><a href="pointer/index.html">pointer</a>. Simple pointer handling.
+<li><a href="funcptr/index.html">funcptr</a>. Pointers to functions.
+</ul>
+
+<h2>Compilation Issues</h2>
+
+<ul>
+<li>To create a Tcl extension, SWIG is run with the following options:
+
+<blockquote>
+<pre>
+% swig -tcl interface.i
+</pre>
+</blockquote>
+
+<li>
+Please see the <a href="../../Doc/Manual/Windows.html">Windows</a> page in the main manual for information on using the examples on Windows. <p>
+</li>
+
+<li>The compilation of examples is done using the file <tt>Example/Makefile</tt>.  This
+makefile performs a manual module compilation which is platform specific.  Typically,
+the steps look like this (Linux):
+
+<blockquote>
+<pre>
+unix % swig -tcl interface.i
+unix % gcc -fpic -c interface_wrap.c -I/usr/local/include
+unix % gcc -shared interface_wrap.o $(OBJS) -o interface.so
+unix % tclsh8.3
+% load ./interface.so
+% blah ...
+</pre>
+</blockquote>
+</ul>
+
+<h2>Compatibility</h2>
+
+The examples have been extensively tested on the following platforms:
+
+<ul>
+<li>Linux
+<li>Solaris
+</ul>
+
+Your mileage may vary.  If you experience a problem, please let us know by 
+contacting us on the <a href="http://www.swig.org/mail.html">mailing lists</a>.
+</body>
+</html>
+
+
diff --git a/trunk/Examples/tcl/java/Example.java b/trunk/Examples/tcl/java/Example.java
new file mode 100644
index 0000000..91ddb1a
--- /dev/null
+++ b/trunk/Examples/tcl/java/Example.java
@@ -0,0 +1,29 @@
+public class Example {
+    public   int      mPublicInt;
+    
+    public Example() {
+	mPublicInt = 0;
+    }
+    
+    public Example(int IntVal) {
+	mPublicInt = IntVal;
+    }
+    
+    
+    public int Add(int a, int b) {
+	return (a+b);
+    }
+    
+    public float Add(float a, float b) {
+	return (a+b);
+    }
+    
+    public String Add(String a, String b) {
+	return (a+b);
+    }
+    
+    public Example Add(Example a, Example b) {
+	return new Example(a.mPublicInt + b.mPublicInt);
+    }
+}
+
diff --git a/trunk/Examples/tcl/java/Makefile b/trunk/Examples/tcl/java/Makefile
new file mode 100644
index 0000000..1c6d4d0
--- /dev/null
+++ b/trunk/Examples/tcl/java/Makefile
@@ -0,0 +1,26 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all:: Example.class
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' CXX="gcj"  \
+	TCL_CXXSHARED="gcj -fpic -shared Example.class " LIBS="-lstdc++" DEFS='' tcl_cpp
+
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+	rm -f *.class Example.h
+
+check: all
+
+run:
+	tclsh runme.tcl
+
+Example.class: Example.java
+	gcj -fPIC -C -c -g Example.java
+	gcjh  Example
+
diff --git a/trunk/Examples/tcl/java/example.i b/trunk/Examples/tcl/java/example.i
new file mode 100644
index 0000000..b69d83f
--- /dev/null
+++ b/trunk/Examples/tcl/java/example.i
@@ -0,0 +1,8 @@
+%module example
+%include <cni.i>
+
+%{
+#include "Example.h"
+%}
+
+%include Example.h
diff --git a/trunk/Examples/tcl/java/runme.tcl b/trunk/Examples/tcl/java/runme.tcl
new file mode 100644
index 0000000..6caf007
--- /dev/null
+++ b/trunk/Examples/tcl/java/runme.tcl
@@ -0,0 +1,15 @@
+catch { load ./example[info sharedlibextension] example}
+
+JvCreateJavaVM  NULL
+JvAttachCurrentThread NULL NULL
+Example e1 1
+Example e2 2
+
+puts "[e1 cget -mPublicInt]"
+puts "[e2 cget -mPublicInt]"
+
+puts "[e2 Add 1 2]"
+puts "[e2 Add 1.0 2.0]"
+puts "[e2 Add '1' '2']"
+
+JvDetachCurrentThread
diff --git a/trunk/Examples/tcl/multimap/Makefile b/trunk/Examples/tcl/multimap/Makefile
new file mode 100644
index 0000000..bed049a
--- /dev/null
+++ b/trunk/Examples/tcl/multimap/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/multimap/example.c b/trunk/Examples/tcl/multimap/example.c
new file mode 100644
index 0000000..b8360fa
--- /dev/null
+++ b/trunk/Examples/tcl/multimap/example.c
@@ -0,0 +1,53 @@
+/* File : example.c */
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+int gcdmain(int argc, char *argv[]) {
+  int x,y;
+  if (argc != 3) {
+    printf("usage: gcd x y\n");
+    return -1;
+  }
+  x = atoi(argv[1]);
+  y = atoi(argv[2]);
+  printf("gcd(%d,%d) = %d\n", x,y,gcd(x,y));
+  return 0;
+}
+
+int count(char *bytes, int len, char c) {
+  int i;
+  int count = 0;
+  for (i = 0; i < len; i++) {
+    if (bytes[i] == c) count++;
+  }
+  return count;
+}
+
+void capitalize(char *str, int len) {
+  int i;
+  for (i = 0; i < len; i++) {
+    str[i] = (char)toupper(str[i]);
+  }
+}
+
+void circle(double x, double y) {
+  double a = x*x + y*y;
+  if (a > 1.0) {
+    printf("Bad points %g, %g\n", x,y);
+  } else {
+    printf("Good points %g, %g\n", x,y);
+  }
+}
diff --git a/trunk/Examples/tcl/multimap/example.dsp b/trunk/Examples/tcl/multimap/example.dsp
new file mode 100644
index 0000000..296cb31
--- /dev/null
+++ b/trunk/Examples/tcl/multimap/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/multimap/example.i b/trunk/Examples/tcl/multimap/example.i
new file mode 100644
index 0000000..9a141b6
--- /dev/null
+++ b/trunk/Examples/tcl/multimap/example.i
@@ -0,0 +1,80 @@
+/* File : example.i */
+%module example
+
+%{
+extern int gcd(int x, int y);
+extern int gcdmain(int argc, char *argv[]);
+extern int count(char *bytes, int len, char c);
+extern void capitalize (char *str, int len);
+extern void circle (double cx, double cy);
+extern int squareCubed (int n, int *OUTPUT);
+%}
+
+%include exception.i
+
+extern int    gcd(int x, int y);
+
+%typemap(arginit) (int argc, char *argv[]) "$2 = 0;";
+
+%typemap(in) (int argc, char *argv[]) {
+  Tcl_Obj **listobjv = 0;
+  int i;
+  if (Tcl_ListObjGetElements(interp,$input, &$1, &listobjv) == TCL_ERROR) {
+    SWIG_exception(SWIG_ValueError,"Expected a list");
+    return TCL_ERROR;
+  }
+  $2 = (char **) malloc(($1+1)*sizeof(char *));
+  for (i = 0; i < $1; i++) {
+    $2[i] = Tcl_GetStringFromObj(listobjv[i],0);
+  }
+  $2[i] = 0;
+}
+
+%typemap(freearg) char *argv[] {
+  if ($1) {
+    free($1);
+  }
+}
+
+extern int gcdmain(int argc, char *argv[]);
+
+%typemap(in) (char *bytes, int len) {
+  $1 = Tcl_GetStringFromObj($input,&$2);
+}
+
+extern int count(char *bytes, int len, char c);
+
+
+/* This example shows how to wrap a function that mutates a string */
+
+%typemap(in) (char *str, int len) {
+  char *temp;
+  temp = Tcl_GetStringFromObj($input,&$2);
+  $1 = (char *) malloc($2+1);
+  memmove($1,temp,$2);
+}
+
+/* Return the mutated string as a new object.   */
+
+%typemap(argout) (char *str, int len) {
+ Tcl_Obj *o;
+ o = Tcl_NewStringObj($1,$2);
+ Tcl_ListObjAppendElement(interp,$result,o);
+ free($1);
+}   
+
+extern void capitalize(char *str, int len);
+
+
+/* A multi-valued constraint.  Force two arguments to lie
+   inside the unit circle */
+
+%typemap(check) (double cx, double cy) {
+   double a = $1*$1 + $2*$2;
+   if (a > 1.0) {
+	SWIG_exception(SWIG_ValueError,"$1_name and $2_name must be in unit circle");
+        return TCL_ERROR;
+   }
+}
+
+extern void circle(double cx, double cy);
diff --git a/trunk/Examples/tcl/multimap/runme.tcl b/trunk/Examples/tcl/multimap/runme.tcl
new file mode 100644
index 0000000..bafa281
--- /dev/null
+++ b/trunk/Examples/tcl/multimap/runme.tcl
@@ -0,0 +1,24 @@
+# file: runme.tcl
+# Try to load as a dynamic module.
+
+catch { load ./example[info sharedlibextension] example}
+
+# Call our gcd() function
+set x 42
+set y 105
+set g [gcd $x $y]
+puts "The gcd of $x and $y is $g"
+
+# call the gcdmain
+gcdmain "gcdmain 42 105"
+
+
+# call count
+set c [count "Hello World" l]
+puts $c
+
+# call capitalize
+
+set c [capitalize "helloworld"]
+puts $c
+
diff --git a/trunk/Examples/tcl/operator/Makefile b/trunk/Examples/tcl/operator/Makefile
new file mode 100644
index 0000000..caf2f79
--- /dev/null
+++ b/trunk/Examples/tcl/operator/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/operator/example.h b/trunk/Examples/tcl/operator/example.h
new file mode 100644
index 0000000..4da6a23
--- /dev/null
+++ b/trunk/Examples/tcl/operator/example.h
@@ -0,0 +1,36 @@
+/* File : example.h */
+#include <math.h>
+
+class Complex {
+private:
+  double rpart, ipart;
+public:
+  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
+  Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
+  Complex &operator=(const Complex &c) {
+    rpart = c.rpart;
+    ipart = c.ipart;
+    return *this;
+  }
+  Complex operator+(const Complex &c) const {
+    return Complex(rpart+c.rpart, ipart+c.ipart);
+  }
+  Complex operator-(const Complex &c) const {
+    return Complex(rpart-c.rpart, ipart-c.ipart);
+  }
+  Complex operator*(const Complex &c) const {
+    return Complex(rpart*c.rpart - ipart*c.ipart,
+		   rpart*c.ipart + c.rpart*ipart);
+  }
+  Complex operator-() const {
+    return Complex(-rpart, -ipart);
+  }
+  
+  double re() const { return rpart; }
+  double im() const { return ipart; }
+};
+
+
+
+
+  
diff --git a/trunk/Examples/tcl/operator/example.i b/trunk/Examples/tcl/operator/example.i
new file mode 100644
index 0000000..fa5bccd
--- /dev/null
+++ b/trunk/Examples/tcl/operator/example.i
@@ -0,0 +1,28 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* This header file is a little tough to handle because it has overloaded
+   operators and constructors.  We're going to try and deal with that here */
+
+/* This turns the copy constructor in a function ComplexCopy() that can
+   be called */
+
+%rename(ComplexCopy) Complex::Complex(Complex const &);
+
+/* Now grab the original header file */
+%include "example.h"
+
+/* An output method that turns a complex into a short string */
+%extend Complex {
+   char *str() {
+       static char temp[512];
+       sprintf(temp,"(%g,%g)", $self->re(), $self->im());
+       return temp;
+   }
+};
+
+
diff --git a/trunk/Examples/tcl/operator/runme.tcl b/trunk/Examples/tcl/operator/runme.tcl
new file mode 100644
index 0000000..3b7c068
--- /dev/null
+++ b/trunk/Examples/tcl/operator/runme.tcl
@@ -0,0 +1,30 @@
+# Operator overloading example
+
+catch { load ./example[info sharedlibextension] example}
+
+set a [Complex -args 2 3]
+set b [Complex -args -5 10]
+
+puts "a   = $a [$a str]"
+puts "b   = $b [$b str]"
+
+set c [$a + $b]
+Complex -this $c
+puts "c   = $c [$c str]"
+
+set d [$a * $b]
+Complex -this $d
+puts "a*b  = [$d str]"
+
+# Alternative calling convention
+set e [Complex_- $a $c]
+puts "a-c  = [Complex_str $e]"
+
+set f [new_ComplexCopy $e]
+Complex -this $f
+puts "f    = [$f str]"
+
+# Call assignment operator
+$c = $f
+puts "c    = [$c str]"
+
diff --git a/trunk/Examples/tcl/pointer/Makefile b/trunk/Examples/tcl/pointer/Makefile
new file mode 100644
index 0000000..bed049a
--- /dev/null
+++ b/trunk/Examples/tcl/pointer/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/pointer/example.c b/trunk/Examples/tcl/pointer/example.c
new file mode 100644
index 0000000..b877d9a
--- /dev/null
+++ b/trunk/Examples/tcl/pointer/example.c
@@ -0,0 +1,16 @@
+/* File : example.c */
+
+void add(int *x, int *y, int *result) {
+  *result = *x + *y;
+}
+
+void sub(int *x, int *y, int *result) {
+  *result = *x - *y;
+}
+
+int divide(int n, int d, int *r) {
+   int q;
+   q = n/d;
+   *r = n - q*d;
+   return q;
+}
diff --git a/trunk/Examples/tcl/pointer/example.i b/trunk/Examples/tcl/pointer/example.i
new file mode 100644
index 0000000..4d5b523
--- /dev/null
+++ b/trunk/Examples/tcl/pointer/example.i
@@ -0,0 +1,31 @@
+/* File : example.i */
+%module example
+
+%{
+extern void add(int *, int *, int *);
+extern void sub(int *, int *, int *);
+extern int divide(int, int, int *);
+%}
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+
+%include cpointer.i
+%pointer_functions(int, intp);
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/tcl/pointer/index.html b/trunk/Examples/tcl/pointer/index.html
new file mode 100644
index 0000000..874088a
--- /dev/null
+++ b/trunk/Examples/tcl/pointer/index.html
@@ -0,0 +1,171 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:pointer</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/tcl/pointer/</tt>
+<hr>
+
+<H2>Simple Pointer Handling</H2>
+
+<p>
+This example illustrates a couple of techniques for handling
+simple pointers in SWIG.  The prototypical example is a C function
+that operates on pointers such as this:
+
+<blockquote>
+<pre>
+void add(int *x, int *y, int *r) { 
+    *r = *x + *y;
+}
+</pre>
+</blockquote>
+
+By default, SWIG wraps this function exactly as specified and creates
+an interface that expects pointer objects for arguments.  The only
+problem is how does one go about creating these objects from a script?
+
+<h2>Possible Solutions</h2>
+
+<ul>
+<li>Write some helper functions to explicitly create objects.  For
+example:
+
+<blockquote>
+<pre>
+int *new_int(int ivalue) {
+  int *i = (int *) malloc(sizeof(ivalue));
+  *i = ivalue;
+  return i;
+}
+int get_int(int *i) {
+  return *i;
+}
+
+void delete_int(int *i) {
+  free(i);
+}
+</pre>
+</blockquote>
+
+Now, in a script you would do this:
+
+<blockquote>
+<pre>
+set a [new_int 37]
+set b [new_int 42]
+set c [new_int 0]
+add $a $b $c
+set r [get_int $c]
+puts "Result = $r"
+delete_int $a
+delete_int $b
+delete_int $c
+</pre>
+</blockquote>
+
+<p>
+<li>Use the SWIG pointer library.  For example, in the interface file 
+you would do this:
+
+<blockquote>
+<pre>
+%include "pointer.i"
+</pre>
+</blockquote?
+
+and in a script you would do this:
+
+<blockquote>
+<pre>
+set a [ptrcreate int 37]
+set b [ptrcreate int 42]
+set c [ptrcreate int]
+add $a $b $c
+set r [ptrvalue $c]
+puts "Result = $r"
+ptrfree $a
+ptrfree $b
+ptrfree $c
+</pre>
+</blockquote>
+
+The advantage to using the pointer library is that it unifies some of the helper
+functions behind a common set of names.  For example, the same set of functions work
+with int, double, float, and other fundamental types.
+
+<p>
+<li>Use the SWIG typemap library.  This library allows you to completely
+change the way arguments are processed by SWIG.  For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+void add(int *INPUT, int *INPUT, int *OUTPUT);
+</pre>
+</blockquote>
+
+And in a script:
+
+<blockquote>
+<pre>
+set r [add 37 42]
+puts "Result = $r"
+</pre>
+</blockquote>
+Needless to say, this is substantially easier.
+
+<p>
+<li>A final alternative is to use the typemaps library in combination
+with the %apply directive.  This allows you to change the names of parameters
+that behave as input or output parameters. For example:
+
+<blockquote>
+<pre>
+%include "typemaps.i"
+%apply int *INPUT {int *x, int *y};
+%apply int *OUTPUT {int *r};
+
+void add(int *x, int *y, int *r);
+void sub(int *x, int *y, int *r);
+void mul(int *x, int *y, int *r);
+... etc ...
+</pre>
+</blockquote>
+
+</ul>
+
+<h2>Example</h2>
+
+The following example illustrates the use of these features for pointer
+extraction.
+
+<ul>
+<li> <a href="example.c">example.c</a>  (C Source)
+<li> <a href="example.i">example.i</a>  (Swig interface)
+<li> <a href="runme.tcl">runme.tcl</a> (Tcl Script)
+</ul>
+
+<h2>Notes</h2>
+
+<ul>
+<li>Since pointers are used for so many different things (arrays, output values,
+etc...) the complexity of pointer handling can be as complicated as you want to
+make it.
+
+<p>
+<li>More documentation on the typemaps.i and pointer.i library files can be
+found in the SWIG user manual.  The files also contain documentation.
+
+<p>
+<li>The pointer.i library is designed primarily for convenience.  If you
+are concerned about performance, you probably want to use a different
+approach.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/tcl/pointer/runme.tcl b/trunk/Examples/tcl/pointer/runme.tcl
new file mode 100644
index 0000000..efe9bb4
--- /dev/null
+++ b/trunk/Examples/tcl/pointer/runme.tcl
@@ -0,0 +1,47 @@
+# file: runme.tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+# First create some objects using the pointer library.
+puts "Testing the pointer library"
+set a [new_intp]
+set b [new_intp]
+set c [new_intp]       ;# Memory for result
+
+intp_assign $a 37
+intp_assign $b 42
+
+puts "     a = $a"
+puts "     b = $b"
+puts "     c = $c"
+
+# Call the add() function with some pointers
+add $a $b $c
+
+# Now get the result
+set r [intp_value $c]
+puts "     37 + 42 = $r"
+
+# Clean up the pointers
+delete_intp $a
+delete_intp $b
+delete_intp $c
+
+# Now try the typemap library
+# This should be much easier. Now how it is no longer
+# necessary to manufacture pointers.
+
+puts "Trying the typemap library"
+set r [sub 37 42]
+puts "     37 - 42 = $r"
+
+# Now try the version with multiple return values
+
+puts "Testing multiple return values"
+set qr [divide 42 37]
+set q [lindex $qr 0]
+set r [lindex $qr 1]
+puts "     42/37 = $q remainder $r"
+
+
+
diff --git a/trunk/Examples/tcl/reference/Makefile b/trunk/Examples/tcl/reference/Makefile
new file mode 100644
index 0000000..c01283c
--- /dev/null
+++ b/trunk/Examples/tcl/reference/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = example.cxx
+TARGET     = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/reference/example.cxx b/trunk/Examples/tcl/reference/example.cxx
new file mode 100644
index 0000000..8a513bf
--- /dev/null
+++ b/trunk/Examples/tcl/reference/example.cxx
@@ -0,0 +1,46 @@
+/* File : example.cxx */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include "example.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Vector operator+(const Vector &a, const Vector &b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+
+char *Vector::print() {
+  static char temp[512];
+  sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z);
+  return temp;
+}
+
+VectorArray::VectorArray(int size) {
+  items = new Vector[size];
+  maxsize = size;
+}
+
+VectorArray::~VectorArray() {
+  delete [] items;
+}
+
+Vector &VectorArray::operator[](int index) {
+  if ((index < 0) || (index >= maxsize)) {
+    printf("Panic! Array index out of bounds.\n");
+    exit(1);
+  }
+  return items[index];
+}
+
+int VectorArray::size() {
+  return maxsize;
+}
+
diff --git a/trunk/Examples/tcl/reference/example.h b/trunk/Examples/tcl/reference/example.h
new file mode 100644
index 0000000..4915adb
--- /dev/null
+++ b/trunk/Examples/tcl/reference/example.h
@@ -0,0 +1,26 @@
+/* File : example.h */
+
+class Vector {
+private:
+  double x,y,z;
+public:
+  Vector() : x(0), y(0), z(0) { };
+  Vector(double x, double y, double z) : x(x), y(y), z(z) { };
+  friend Vector operator+(const Vector &a, const Vector &b);
+  char *print();
+};
+
+class VectorArray {
+private:
+  Vector *items;
+  int     maxsize;
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  Vector &operator[](int);
+  int size();
+};
+
+
+
+  
diff --git a/trunk/Examples/tcl/reference/example.i b/trunk/Examples/tcl/reference/example.i
new file mode 100644
index 0000000..6daa3b1
--- /dev/null
+++ b/trunk/Examples/tcl/reference/example.i
@@ -0,0 +1,46 @@
+/* File : example.i */
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %extend {
+    Vector &get(int index) {
+      return (*$self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*$self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/tcl/reference/index.html b/trunk/Examples/tcl/reference/index.html
new file mode 100644
index 0000000..ef799fa
--- /dev/null
+++ b/trunk/Examples/tcl/reference/index.html
@@ -0,0 +1,147 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:reference</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/tcl/reference/</tt>
+<hr>
+
+<H2>C++ Reference Handling</H2>
+
+<p>
+This example tests SWIG's handling of C++ references.  Since C++
+references are closely related to pointers (as both refer to a
+location in memory), SWIG simply collapses all references into
+pointers when creating wrappers.
+
+<h2>Some examples</h2>
+
+References are most commonly used as function parameter.  For example,
+you might have an operator like this:
+
+<blockquote>
+<pre>
+Vector operator+(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+or a function:
+
+<blockquote>
+<pre>
+Vector addv(const Vector &amp;a, const Vector &amp;b) {
+   Vector result;
+   result.x = a.x + b.x;
+   result.y = a.y + b.y;
+   result.z = a.z + b.z;
+   return result;
+}
+</pre>
+</blockquote>
+
+In these cases, SWIG transforms everything into a pointer and creates a wrapper
+that looks like this:
+
+<blockquote>
+<pre>
+Vector wrap_addv(Vector *a, Vector *b) {
+    return addv(*a,*b);
+}
+</pre>
+</blockquote>
+
+Occasionally, a reference is used as a return value of a function
+when the return result is to be used as an lvalue in an expression.
+The prototypical example is an operator like this:
+
+<blockquote>
+<pre>
+Vector &amp;operator[](int index);
+</pre>
+</blockquote>
+
+or a method:
+
+<blockquote>
+<pre>
+Vector &amp;get(int index);
+</pre>
+</blockquote>
+
+For functions returning references, a wrapper like this is created:
+
+<blockquote>
+<pre>
+Vector *wrap_Object_get(Object *self, int index) {
+    Vector &amp;result = self-&gt;get(index);
+    return &amp;result;
+}
+</pre>
+</blockquote>
+
+The following <a href="example.h">header file</a> contains some class
+definitions with some operators and use of references.
+
+<h2>SWIG Interface</h2>
+
+SWIG does NOT support overloaded operators so it can not directly build
+an interface to the classes in the above file.   However, a number of workarounds
+can be made.  For example, an overloaded operator can be stuck behind a function
+call such as the <tt>addv()</tt> function above.  Array access can be handled
+with a pair of set/get functions like this:
+
+<blockquote>
+<pre>
+class VectorArray {
+public:
+ ...
+   %addmethods {
+    Vector &amp;get(int index) {
+      return (*self)[index];
+    }
+    void set(int index, Vector &amp;a) {
+      (*self)[index] = a;
+    }
+   }
+   ...
+}
+</pre>
+</blockquote>
+
+Click <a href="example.i">here</a> to see a SWIG interface file with these additions.
+
+<h2>Sample Tcl scripts</h2>
+
+Click <a href="runme.tcl">here</a> to see a script that manipulates some C++ references.
+
+<h2>Notes:</h2>
+
+<ul>
+<li>C++ references primarily provide notational convenience for C++
+source code.  However, Tcl has neither the 'x.a' or 'x-&gt;a'
+notation so it doesn't much matter.
+
+<p>
+<li>When a program returns a reference, a pointer is returned.
+Unlike return by value, memory is not allocated to hold the
+return result.
+
+<p>
+<li>SWIG has particular trouble handling various combinations of references
+and pointers.  This is side effect of an old parsing scheme and
+type representation that will be replaced in future versions.
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/tcl/reference/runme.tcl b/trunk/Examples/tcl/reference/runme.tcl
new file mode 100644
index 0000000..6560cf4
--- /dev/null
+++ b/trunk/Examples/tcl/reference/runme.tcl
@@ -0,0 +1,76 @@
+# file: runme.tcl
+
+# This file illustrates the manipulation of C++ references in Tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+# ----- Object creation -----
+
+puts "Creating some objects:"
+set  a [new_Vector 3 4 5]
+set  b [new_Vector 10 11 12]
+
+puts "    Created [Vector_print $a]"
+puts "    Created [Vector_print $b]"
+
+# ----- Call an overloaded operator -----
+
+# This calls the wrapper we placed around
+#
+#      operator+(const Vector &a, const Vector &) 
+#
+# It returns a new allocated object.
+
+puts "Adding a+b"
+set c [addv $a $b]
+puts "    a+b = [Vector_print $c]"
+
+# Note: Unless we free the result, a memory leak will occur
+delete_Vector $c
+
+# ----- Create a vector array -----
+
+# Note: Using the high-level interface here
+puts "Creating an array of vectors"
+VectorArray va 10
+puts "    va = [va cget -this]"
+
+
+# ----- Set some values in the array -----
+
+# These operators copy the value of $a and $b to the vector array
+va set 0 $a
+va set 1 $b
+
+# This will work, but it will cause a memory leak!
+
+va set 2 [addv $a $b]
+
+# The non-leaky way to do it
+
+set c [addv $a $b]
+va set 3 $c
+delete_Vector $c
+
+# Get some values from the array
+
+puts "Getting some array values"
+for {set i 0} {$i < 5} {incr i 1} {
+    puts "    va($i) = [Vector_print [va get $i]]"
+}
+
+# Watch under resource meter to check on this
+puts "Making sure we don't leak memory."
+for {set i 0} {$i < 1000000} {incr i 1} {
+    set c [va get [expr {$i % 10}]]
+}
+
+# ----- Clean up -----
+puts "Cleaning up"
+
+rename va ""
+
+delete_Vector $a
+delete_Vector $b
+
+
diff --git a/trunk/Examples/tcl/simple/Makefile b/trunk/Examples/tcl/simple/Makefile
new file mode 100644
index 0000000..bed049a
--- /dev/null
+++ b/trunk/Examples/tcl/simple/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/simple/example.c b/trunk/Examples/tcl/simple/example.c
new file mode 100644
index 0000000..1c2af78
--- /dev/null
+++ b/trunk/Examples/tcl/simple/example.c
@@ -0,0 +1,18 @@
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x > 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+
+
diff --git a/trunk/Examples/tcl/simple/example.dsp b/trunk/Examples/tcl/simple/example.dsp
new file mode 100644
index 0000000..296cb31
--- /dev/null
+++ b/trunk/Examples/tcl/simple/example.dsp
@@ -0,0 +1,148 @@
+# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>

+# Microsoft Developer Studio Generated Build File, Format Version 6.00

+# ** DO NOT EDIT **

+

+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102

+

+CFG=example - Win32 Release

+!MESSAGE This is not a valid makefile. To build this project using NMAKE,

+!MESSAGE use the Export Makefile command and run

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak".

+!MESSAGE 

+!MESSAGE You can specify a configuration when running NMAKE

+!MESSAGE by defining the macro CFG on the command line. For example:

+!MESSAGE 

+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"

+!MESSAGE 

+!MESSAGE Possible choices for configuration are:

+!MESSAGE 

+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")

+!MESSAGE 

+

+# Begin Project

+# PROP AllowPerConfigDependencies 0

+# PROP Scc_ProjName ""

+# PROP Scc_LocalPath ""

+CPP=cl.exe

+MTL=midl.exe

+RSC=rc.exe

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 1

+# PROP BASE Output_Dir "Debug"

+# PROP BASE Intermediate_Dir "Debug"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 1

+# PROP Output_Dir "Debug"

+# PROP Intermediate_Dir "Debug"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(TCL_INCLUDE)" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c

+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "_DEBUG"

+# ADD RSC /l 0x809 /d "_DEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /debug /machine:I386 /out:"example.dll" /pdbtype:sept

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# PROP BASE Use_MFC 0

+# PROP BASE Use_Debug_Libraries 0

+# PROP BASE Output_Dir "Release"

+# PROP BASE Intermediate_Dir "Release"

+# PROP BASE Target_Dir ""

+# PROP Use_MFC 0

+# PROP Use_Debug_Libraries 0

+# PROP Output_Dir "Release"

+# PROP Intermediate_Dir "Release"

+# PROP Ignore_Export_Lib 0

+# PROP Target_Dir ""

+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(TCL_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c

+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32

+# ADD BASE RSC /l 0x809 /d "NDEBUG"

+# ADD RSC /l 0x809 /d "NDEBUG"

+BSC32=bscmake.exe

+# ADD BASE BSC32 /nologo

+# ADD BSC32 /nologo

+LINK32=link.exe

+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386

+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(TCL_LIB)" /nologo /dll /machine:I386 /out:"example.dll"

+

+!ENDIF 

+

+# Begin Target

+

+# Name "example - Win32 Debug"

+# Name "example - Win32 Release"

+# Begin Group "Source Files"

+

+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"

+# Begin Source File

+

+SOURCE=.\example.c

+# End Source File

+# Begin Source File

+

+SOURCE=.\example_wrap.c

+# End Source File

+# End Group

+# Begin Group "Header Files"

+

+# PROP Default_Filter "h;hpp;hxx;hm;inl"

+# End Group

+# Begin Group "Resource Files"

+

+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"

+# End Group

+# Begin Source File

+

+SOURCE=.\example.i

+

+!IF  "$(CFG)" == "example - Win32 Debug"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ELSEIF  "$(CFG)" == "example - Win32 Release"

+

+# Begin Custom Build

+InputPath=.\example.i

+InputName=example

+

+"$(InputName)_wrap.c" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"

+	echo In order to function correctly, please ensure the following environment variables are correctly set: 

+	echo TCL_INCLUDE: %TCL_INCLUDE% 

+	echo TCL_LIB: %TCL_LIB% 

+	echo on 

+	..\..\..\swig -tcl8 $(InputPath) 

+	

+# End Custom Build

+

+!ENDIF 

+

+# End Source File

+# End Target

+# End Project

diff --git a/trunk/Examples/tcl/simple/example.i b/trunk/Examples/tcl/simple/example.i
new file mode 100644
index 0000000..24093b9
--- /dev/null
+++ b/trunk/Examples/tcl/simple/example.i
@@ -0,0 +1,7 @@
+/* File : example.i */
+%module example
+
+%inline %{
+extern int    gcd(int x, int y);
+extern double Foo;
+%}
diff --git a/trunk/Examples/tcl/simple/index.html b/trunk/Examples/tcl/simple/index.html
new file mode 100644
index 0000000..333d905
--- /dev/null
+++ b/trunk/Examples/tcl/simple/index.html
@@ -0,0 +1,97 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:simple</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/tcl/simple/</tt>
+<hr>
+
+<H2>Simple Tcl Example</H2>
+
+<p>
+This example illustrates how you can hook Tcl to a very simple C program containing
+a function and a global variable.
+
+<h2>The C Code</h2>
+
+Suppose you have the following C code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+/* A global variable */
+double Foo = 3.0;
+
+/* Compute the greatest common divisor of positive integers */
+int gcd(int x, int y) {
+  int g;
+  g = y;
+  while (x &gt; 0) {
+    g = x;
+    x = y % x;
+    y = g;
+  }
+  return g;
+}
+</pre>
+</blockquote>
+
+<h2>The SWIG interface</h2>
+
+Here is a simple SWIG interface file:
+
+<blockquote>
+<pre>
+/* File: example.i */
+%module example
+
+extern int gcd(int x, int y);
+extern double Foo;
+</pre>
+</blockquote>
+
+<h2>Compilation</h2>
+
+<ol>
+<li><tt>swig -tcl <a href="example.i">example.i</a></tt>
+<p>
+<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
+to create the extension <tt>example.so</tt>. 
+</ol>
+
+<h2>Using the extension</h2>
+
+Click <a href="runme.tcl">here</a> to see a script that calls our C functions from Tcl.
+
+<h2>Key points</h2>
+
+<ul>
+<li>Use the <tt>load</tt> statement to load your extension module into Tcl. For example:
+<blockquote>
+<pre>
+load ./example.so
+</pre>
+</blockquote>
+
+<li>C functions work just like Tcl functions. For example:
+<blockquote>
+<pre>
+set g [gcd 42 105]
+</pre>
+</blockquote>
+
+<li>C global variables are accessed as Tcl variables. For example:
+<blockquote>
+<pre>
+set a $Foo
+set Foo $newvalue
+</pre>
+</blockquote>
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/tcl/simple/runme.tcl b/trunk/Examples/tcl/simple/runme.tcl
new file mode 100644
index 0000000..3a6ce10
--- /dev/null
+++ b/trunk/Examples/tcl/simple/runme.tcl
@@ -0,0 +1,22 @@
+# file: runme.tcl
+# Try to load as a dynamic module.
+
+catch { load ./example[info sharedlibextension] example}
+
+# Call our gcd() function
+set x 42
+set y 105
+set g [gcd $x $y]
+puts "The gcd of $x and $y is $g"
+
+# Manipulate the Foo global variable
+
+# Output its current value
+puts "Foo = $Foo"
+
+# Change its value
+set Foo 3.1415926
+
+# See if the change took effect
+puts "Foo = $Foo"
+
diff --git a/trunk/Examples/tcl/std_vector/Makefile b/trunk/Examples/tcl/std_vector/Makefile
new file mode 100644
index 0000000..ce6a3c7
--- /dev/null
+++ b/trunk/Examples/tcl/std_vector/Makefile
@@ -0,0 +1,20 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+CXXSRCS    = 
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+LIBS       = -lm
+
+all::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl_cpp
+
+static::
+	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh_cpp_static
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/std_vector/example.h b/trunk/Examples/tcl/std_vector/example.h
new file mode 100644
index 0000000..4f0dac7
--- /dev/null
+++ b/trunk/Examples/tcl/std_vector/example.h
@@ -0,0 +1,25 @@
+/* File : example.h */
+
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <numeric>
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<double> half(const std::vector<double>& v) {
+    std::vector<double> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    // would you believe this is the same as the above?
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+
diff --git a/trunk/Examples/tcl/std_vector/example.i b/trunk/Examples/tcl/std_vector/example.i
new file mode 100644
index 0000000..aa58b66
--- /dev/null
+++ b/trunk/Examples/tcl/std_vector/example.i
@@ -0,0 +1,17 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+%include stl.i
+/* instantiate the required template specializations */
+namespace std {
+    %template(IntVector)    vector<int>;
+    %template(DoubleVector) vector<double>;
+}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
diff --git a/trunk/Examples/tcl/std_vector/runme.tcl b/trunk/Examples/tcl/std_vector/runme.tcl
new file mode 100644
index 0000000..2cece96
--- /dev/null
+++ b/trunk/Examples/tcl/std_vector/runme.tcl
@@ -0,0 +1,40 @@
+# file: runme.tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+# Exercise IntVector
+
+set iv [IntVector]
+$iv push 1
+$iv push 3
+$iv push 5
+
+puts "IntVector size:      [$iv size]   (should be 3)"
+puts "IntVector average:   [average $iv] (should be 3.0)"
+puts "IntVector pop:       [$iv pop]   (should be 5)"
+puts "IntVector pop:       [$iv pop]   (should be 3)"
+puts "IntVector get 0:     [$iv get 0]   (should be 1)"
+puts ""
+
+# Exercise DoubleVector
+
+set dv [DoubleVector]
+$dv push 2 
+$dv push 4
+$dv push 6
+ 
+puts "DoubleVector size:   [$dv size]           (should be 3)"
+puts "DoubleVector data:   [$dv get 0] [$dv get 1] [$dv get 2] (should be 2.0 4.0 6.0)"
+halve_in_place $dv
+puts "DoubleVector halved: [$dv get 0] [$dv get 1] [$dv get 2] (should be 1.0 2.0 3.0)"
+puts ""
+
+# Complain if unknown is called
+rename unknown unknown_orig
+proc unknown {args} {
+  puts "ERROR: unknown called with: $args"
+  uplevel 1 unknown_orig $args
+}
+
+puts "average \"1 2 3\": [average [list 1 2 3]]"
+
diff --git a/trunk/Examples/tcl/value/Makefile b/trunk/Examples/tcl/value/Makefile
new file mode 100644
index 0000000..bed049a
--- /dev/null
+++ b/trunk/Examples/tcl/value/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/value/example.c b/trunk/Examples/tcl/value/example.c
new file mode 100644
index 0000000..4ed2fe1
--- /dev/null
+++ b/trunk/Examples/tcl/value/example.c
@@ -0,0 +1,15 @@
+/* File : example.c */
+
+#include "example.h"
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+Vector vector_add(Vector a, Vector b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
diff --git a/trunk/Examples/tcl/value/example.h b/trunk/Examples/tcl/value/example.h
new file mode 100644
index 0000000..212cf4b
--- /dev/null
+++ b/trunk/Examples/tcl/value/example.h
@@ -0,0 +1,5 @@
+/* File : example.h */
+
+typedef struct {
+     double x, y, z;
+} Vector;
diff --git a/trunk/Examples/tcl/value/example.i b/trunk/Examples/tcl/value/example.i
new file mode 100644
index 0000000..98fd60e
--- /dev/null
+++ b/trunk/Examples/tcl/value/example.i
@@ -0,0 +1,32 @@
+// Tests SWIG's handling of pass-by-value for complex datatypes
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Some functions that manipulate Vectors by value */
+%inline %{
+extern double dot_product(Vector a, Vector b);
+extern Vector vector_add(Vector a, Vector b);
+%}
+
+/* Include this because the vector_add() function will leak memory */
+void   free(void *);
+
+/* Some helper functions for our interface */
+%inline %{
+
+Vector *new_Vector(double x, double y, double z) {
+   Vector *v = (Vector *) malloc(sizeof(Vector));
+   v->x = x;
+   v->y = y;
+   v->z = z;
+   return v;
+}
+
+void vector_print(Vector *v) {
+  printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}
+%}
+
diff --git a/trunk/Examples/tcl/value/index.html b/trunk/Examples/tcl/value/index.html
new file mode 100644
index 0000000..17a991e
--- /dev/null
+++ b/trunk/Examples/tcl/value/index.html
@@ -0,0 +1,122 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:value</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+
+<tt>SWIG/Examples/tcl/value/</tt>
+<hr>
+
+<H2>Passing and Returning Structures by Value</H2>
+
+<p>
+Occasionally, a C program will manipulate structures by value such as shown in the
+following code:
+
+<blockquote>
+<pre>
+/* File : example.c */
+
+typedef struct Vector {
+   double x, y, z;
+} Vector;
+
+double dot_product(Vector a, Vector b) {
+  return (a.x*b.x + a.y*b.y + a.z*b.z);
+}
+
+Vector vector_add(Vector a, Vector b) {
+  Vector r;
+  r.x = a.x + b.x;
+  r.y = a.y + b.y;
+  r.z = a.z + b.z;
+  return r;
+}
+</pre>
+</blockquote>
+
+Since SWIG only knows how to manage pointers to structures (not their internal
+representation), the following translations are made when wrappers are
+created:
+
+<blockquote>
+<pre>
+double wrap_dot_product(Vector *a, Vector *b) {
+    return dot_product(*a,*b);
+}
+
+Vector *wrap_vector_add(Vector *a, Vector *b) {
+    Vector *r = (Vector *) malloc(sizeof(Vector));
+    *r = vector_add(*a,*b);
+    return r;
+}
+</pre>
+</blockquote>
+
+The functions are then called using pointers from the scripting language interface.
+It should also be noted that any function that returns a structure by value results
+in an implicit memory allocation. This will be a memory leak unless you take steps
+to free the result (see below).
+
+<h2>The SWIG interface</h2>
+
+Click <a href="example.i">here</a> to see a SWIG interface file that
+wraps these two functions.  In this file, there are a few essential features:
+
+<ul>
+<li>A wrapper for the <tt>free()</tt> function is created so that we
+can clean up the return result created by <tt>vector_add()</tt>
+function.
+
+<p>
+<li>The %inline directive is used to create a few helper functions for creating new Vector
+objects and to print out the value (for debugging purposes).
+</ul>
+
+<h2>A Tcl Script</h2>
+
+Click <a href="runme.tcl">here</a> to see a script that uses these functions from Tcl.
+
+<h2>Notes</h2>
+
+<ul>
+<li>When the '<tt>-c++</tt>' option is used, the resulting wrapper code for the return value
+changes to the following:
+
+<blockquote>
+<pre>
+Vector *wrap_vector_add(Vector *a, Vector *b) {
+    Vector *r = new Vector(vector_add(*a,*b));
+    return r;
+}
+</pre>
+</blockquote>
+
+Similarly, it would be a mistake to use the <tt>free()</tt> function from C++.  A safer 
+approach would be to write a helper function like this:
+
+<blockquote>
+<pre>
+%inline %{
+   void delete_Vector(Vector *v) {
+       delete v;
+   }
+%}
+</pre>
+</blockquote>
+
+<p>
+<li>Passing parameters by value like this really isn't the best C programming style.
+If possible, you might change your application to use pointers.
+
+<p>
+<li>Similar translations are made when C++ references are used.
+
+
+</ul>
+
+<hr>
+</body>
+</html>
diff --git a/trunk/Examples/tcl/value/runme.tcl b/trunk/Examples/tcl/value/runme.tcl
new file mode 100644
index 0000000..1f6f4af
--- /dev/null
+++ b/trunk/Examples/tcl/value/runme.tcl
@@ -0,0 +1,39 @@
+# file: runme.tcl
+# Try to load as a dynamic module.
+
+catch { load ./example[info sharedlibextension] example}
+
+# Create a couple of a vectors
+
+set v [new_Vector 1 2 3]
+set w [new_Vector 10 11 12]
+
+puts "I just created the following vectors"
+vector_print $v
+vector_print $w
+
+# Now call some of our functions
+
+puts "\nNow I'm going to compute the dot product"
+set d [dot_product $v $w]
+puts "dot product = $d (should be 68)"
+
+# Add the vectors together
+
+puts "\nNow I'm going to add the vectors together"
+set r [vector_add $v $w]
+vector_print $r
+puts "The value should be (11,13,15)"
+
+# Now I'd better clean up the return result r
+
+puts "\nNow I'm going to clean up the return result"
+free $r
+
+puts "Good"
+
+
+
+
+
+
diff --git a/trunk/Examples/tcl/variables/Makefile b/trunk/Examples/tcl/variables/Makefile
new file mode 100644
index 0000000..bed049a
--- /dev/null
+++ b/trunk/Examples/tcl/variables/Makefile
@@ -0,0 +1,19 @@
+TOP        = ../..
+SWIG       = $(TOP)/../preinst-swig
+SRCS       = example.c
+TARGET     = my_tclsh
+DLTARGET   = example
+INTERFACE  = example.i
+
+all::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl
+
+static::
+	$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
+	TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh
+
+clean::
+	$(MAKE) -f $(TOP)/Makefile tcl_clean
+
+check: all
diff --git a/trunk/Examples/tcl/variables/example.c b/trunk/Examples/tcl/variables/example.c
new file mode 100644
index 0000000..aa4ffe9
--- /dev/null
+++ b/trunk/Examples/tcl/variables/example.c
@@ -0,0 +1,91 @@
+/* File : example.c */
+
+/* I'm a file containing some C global variables */
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "example.h"
+
+int              ivar = 0;                    
+short            svar = 0;
+long             lvar = 0;
+unsigned int     uivar = 0;
+unsigned short   usvar = 0;
+unsigned long    ulvar = 0;
+signed char      scvar = 0;
+unsigned char    ucvar = 0;
+char             cvar = 0;
+float            fvar = 0;
+double           dvar = 0;
+char            *strvar = 0;
+const char       cstrvar[] = "Goodbye";
+int             *iptrvar = 0;
+char             name[256] = "Dave";
+char             path[256] = "/home/beazley";
+
+
+/* Global variables involving a structure */
+Point           *ptptr = 0;
+Point            pt = { 10, 20 };
+
+/* A variable that we will make read-only in the interface */
+int              status = 1;
+
+/* A debugging function to print out their values */
+
+void print_vars() {
+  printf("ivar      = %d\n", ivar);
+  printf("svar      = %d\n", svar);
+  printf("lvar      = %ld\n", lvar);
+  printf("uivar     = %u\n", uivar);
+  printf("usvar     = %u\n", usvar);
+  printf("ulvar     = %lu\n", ulvar);
+  printf("scvar     = %d\n", scvar);
+  printf("ucvar     = %u\n", ucvar);
+  printf("fvar      = %g\n", fvar);
+  printf("dvar      = %g\n", dvar);
+  printf("cvar      = %c\n", cvar);
+  printf("strvar    = %s\n", strvar ? strvar : "(null)");
+  printf("cstrvar   = %s\n", cstrvar ? cstrvar : "(null)");
+  printf("iptrvar   = %p\n", iptrvar);
+  printf("name      = %s\n", name);
+  printf("ptptr     = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
+  printf("pt        = (%d, %d)\n", pt.x, pt.y);
+  printf("status    = %d\n", status);
+}
+
+/* A function to create an integer (to test iptrvar) */
+
+int *new_int(int value) {
+  int *ip = (int *) malloc(sizeof(int));
+  *ip = value;
+  return ip;
+}
+
+/* A function to create a point */
+
+Point *new_Point(int x, int y) {
+  Point *p = (Point *) malloc(sizeof(Point));
+  p->x = x;
+  p->y = y;
+  return p;
+}
+
+char * Point_print(Point *p) {
+  static char buffer[256];
+  if (p) {
+    sprintf(buffer,"(%d,%d)", p->x,p->y);
+  } else {
+    sprintf(buffer,"null");
+  }
+  return buffer;
+}
+
+void pt_print() {
+  printf("(%d, %d)\n", pt.x, pt.y);
+}
diff --git a/trunk/Examples/tcl/variables/example.h b/trunk/Examples/tcl/variables/example.h
new file mode 100644
index 0000000..0f7e895
--- /dev/null
+++ b/trunk/Examples/tcl/variables/example.h
@@ -0,0 +1,6 @@
+/* File: example.h */
+
+typedef struct {
+  int x,y;
+} Point;
+
diff --git a/trunk/Examples/tcl/variables/example.i b/trunk/Examples/tcl/variables/example.i
new file mode 100644
index 0000000..9d0101c
--- /dev/null
+++ b/trunk/Examples/tcl/variables/example.i
@@ -0,0 +1,51 @@
+/* File : example.i */
+%module example
+%{
+#include "example.h"
+%}
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_SWIGTYPELEAK
+
+/* Some global variable declarations */
+%inline %{
+extern int              ivar;
+extern short            svar;
+extern long             lvar;
+extern unsigned int     uivar;
+extern unsigned short   usvar;
+extern unsigned long    ulvar;
+extern signed char      scvar;
+extern unsigned char    ucvar;
+extern char             cvar;
+extern float            fvar;
+extern double           dvar;
+extern char            *strvar;
+extern const char       cstrvar[];
+extern int             *iptrvar;
+extern char             name[256];
+
+extern Point           *ptptr;
+extern Point            pt;
+%}
+
+
+/* Some read-only variables */
+
+%immutable;
+
+%inline %{
+extern int  status;
+extern char path[256];
+%}
+
+%mutable;
+
+/* Some helper functions to make it easier to test */
+%inline %{
+extern void  print_vars();
+extern int  *new_int(int value);
+extern Point *new_Point(int x, int y);
+extern char  *Point_print(Point *p);
+extern void  pt_print();
+%}
+
diff --git a/trunk/Examples/tcl/variables/index.html b/trunk/Examples/tcl/variables/index.html
new file mode 100644
index 0000000..245a445
--- /dev/null
+++ b/trunk/Examples/tcl/variables/index.html
@@ -0,0 +1,76 @@
+<html>
+<head>
+<title>SWIG:Examples:tcl:variables</title>
+</head>
+
+<body bgcolor="#ffffff">
+
+<tt>SWIG/Examples/tcl/variables/</tt>
+<hr>
+
+<H2>Wrapping C Global Variables</H2>
+
+<p>
+When a C global variable appears in an interface file, SWIG tries to wrap it using a technique
+known as "variable linking."  The idea is pretty simple---we try to create a Tcl
+variable that works exactly like you would expect in a Tcl script, but which magically 
+retrieves or updates the value of the underlying C variable.  
+Click <a href="example.i">here</a> to see a SWIG interface with some variable declarations in it.
+
+<h2>Manipulating Variables from Tcl</h2>
+
+Click <a href="runme.tcl">here</a> to see a script that updates and prints out the values of
+the variables defined in the above file.  Notice how the C global variables work just
+like normal Tcl variables.
+
+<h2>Key points</h2>
+
+<ul>
+<li>The <tt>set</tt> statement changes the value of the corresponding C global variable.
+<li>Whenever you access the value of a variable such as <tt>$ivar</tt>, the value
+of the C global variable is read. 
+<li>If a C program changes a global variable independently of Tcl, this change is
+automatically reflected in the Tcl variable (i.e., reads will always return the
+most up to date value of the variable).
+<li>When a global variable has the type "<tt>char *</tt>", SWIG manages it as a character
+string.   However, whenever the value of such a variable is set from Tcl, the old
+value is destroyed using <tt>free()</tt> or <tt>delete</tt> (the choice of which depends
+on whether or not SWIG was run with the -c++ option).
+<li><tt>signed char</tt> and <tt>unsigned char</tt> are handled as small 8-bit integers.
+<li>String array variables such as '<tt>char name[256]</tt>' are managed as Tcl strings, but
+when setting the value, the result is truncated to the maximum length of the array.  Furthermore, the string is assumed to be null-terminated.
+<li>When structures and classes are used as global variables, they are mapped into pointers.
+Getting the "value" returns a pointer to the global variable.  Setting the value of a structure results in a memory copy from a pointer to the global.
+</ul>
+
+<h2>Creating read-only variables</h2>
+
+The <tt>%immutable</tt> and <tt>%mutable</tt> directives can be used to
+specify a collection of read-only variables.  For example:
+
+<blockquote>
+<pre>
+%immutable;
+int    status;
+double blah;
+...
+%mutable;
+</pre>
+</blockquote>
+
+The <tt>%immutable</tt> directive remains in effect until it is explicitly disabled
+using the <tt>%mutable</tt> directive.
+
+<h2>Comments</h2>
+<ul>
+<li>Management of global variables is one of the most problematic aspects 
+of C/C++ wrapping because the scripting interface and resulting memory management
+is much trickier than simply creating a wrapper function.
+<p>
+<li>You may be better off hiding global variables behind a function based
+interface.
+</ul>
+
+</body>
+</html>
+<hr>
diff --git a/trunk/Examples/tcl/variables/runme.tcl b/trunk/Examples/tcl/variables/runme.tcl
new file mode 100644
index 0000000..b9e2fd4
--- /dev/null
+++ b/trunk/Examples/tcl/variables/runme.tcl
@@ -0,0 +1,76 @@
+# file: runme.tcl
+
+catch { load ./example[info sharedlibextension] example}
+
+# Try to set the values of some global variables
+
+set ivar    42
+set svar   -31000
+set lvar    65537
+set uivar   123456
+set usvar   61000
+set ulvar   654321
+set scvar   -13
+set ucvar   251
+set cvar    "S"
+set fvar    3.14159
+set dvar    2.1828
+set strvar  "Hello World"
+set iptrvar [new_int 37]
+set ptptr [new_Point 37 42]
+set name    "Bill"
+
+# Now print out the values of the variables
+
+puts "Variables (values printed from Tcl)"
+
+puts "ivar      = $ivar"
+puts "svar      = $svar"
+puts "lvar      = $lvar"
+puts "uivar     = $uivar"
+puts "usvar     = $usvar"
+puts "ulvar     = $ulvar"
+puts "scvar     = $scvar"
+puts "ucvar     = $ucvar"
+puts "fvar      = $fvar"
+puts "dvar      = $dvar"
+puts "cvar      = $cvar"
+puts "strvar    = $strvar"
+puts "cstrvar   = $cstrvar"
+puts "iptrvar   = $iptrvar"
+puts "name      = $name"
+puts "ptptr     = $ptptr [Point_print $ptptr]"
+puts "pt        = $pt [Point_print $pt]"
+
+puts "\nVariables (values printed from C)"
+
+print_vars
+
+puts "\nNow I'm going to try and modify some read only variables";
+
+puts "     Tring to set 'path'";
+if { [catch {
+    set path "Whoa!"
+    puts "Hey, what's going on?!?! This shouldn't work"
+}]} {
+    puts "Good."
+}
+
+puts "     Trying to set 'status'";
+if { [catch {
+    set status 0
+    puts "Hey, what's going on?!?! This shouldn't work"
+}]} {
+    puts "Good."
+}
+
+puts "\nI'm going to try and update a structure variable.\n"
+
+set pt $ptptr
+
+puts "The new value is"
+pt_print
+puts "You should see the value [Point_print $ptptr]"
+
+
+
diff --git a/trunk/Examples/test-suite/README b/trunk/Examples/test-suite/README
new file mode 100644
index 0000000..96dea94
--- /dev/null
+++ b/trunk/Examples/test-suite/README
@@ -0,0 +1,42 @@
+SWIG testsuite README file
+--------------------------
+
+This testsuite is here to ensure SWIG can handle a wide range of c/c++
+syntax. The testsuite comprises many testcases in this directory. Each
+test case is tested under each of the language modules thereby
+thoroughly testing all of SWIG. It ensures that each of the language
+modules are at a similar standard.
+
+Those modules that support shadow classes run the tests producing
+shadow classes to test the full language module functionality.
+
+Some test cases need a runtime test. These need implementing in each
+of the language modules. The language modules look for a file in the
+language specific test-suite directory which has _runme appended after
+the testcase name. If one is found it will be run as part of the test.
+
+Some language modules add to this common set of test cases for
+language specific tests. These can be found in the appropriate
+language test-suite directory. There is also a README in each of the
+language module directories.
+
+For each testcase a message showing which testcase is being tested is
+displayed. Nothing else is printed unless the test fails.
+
+
+Some Developer Guidelines
+-------------------------
+
+Note that the whole test suite need not be run each time a testcase is
+modified. An individual testcase may be run by going to the language
+module test-suite directory and using make testcasename.xxx where xxx
+is the type of test (eg cpptest). See common.mk. make -s doesn't print
+any junk on the screen and is useful for emulating the way make check
+works from the SWIG root directory.
+
+If there are runtime tests needed, don't print anything unless there
+is an error in which case stderr is suggested.
+
+Please set the name of the module to the same name as the testcase,
+otherwise modules will not be found.
+
diff --git a/trunk/Examples/test-suite/abstract_access.i b/trunk/Examples/test-suite/abstract_access.i
new file mode 100644
index 0000000..557f231
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_access.i
@@ -0,0 +1,36 @@
+%module abstract_access
+
+%warnfilter(SWIGWARN_LANG_DIRECTOR_ABSTRACT) A;
+
+%inline %{
+class A {
+public:
+  virtual ~A()
+  {
+  }
+
+private:
+	virtual int x() = 0;
+protected:
+	virtual int y() = 0;
+public:
+	virtual int z() = 0;
+	int do_x() { return x(); }
+};
+
+class B : public A {
+private:
+	virtual int x() { return y(); }
+};
+
+class C : public B {
+protected:
+	virtual int y() { return z(); }
+};
+
+class D : public C {
+private:
+	virtual int z() { return 1; }
+};
+
+%}
diff --git a/trunk/Examples/test-suite/abstract_inherit.i b/trunk/Examples/test-suite/abstract_inherit.i
new file mode 100644
index 0000000..3fe1f67
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_inherit.i
@@ -0,0 +1,62 @@
+%module abstract_inherit
+
+%warnfilter(SWIGWARN_TYPE_ABSTRACT) Spam;
+%warnfilter(SWIGWARN_TYPE_ABSTRACT) Bar;
+
+%inline %{
+
+class Foo {
+public:
+  virtual ~Foo()
+  {
+  }
+  
+  virtual int blah() = 0;
+};
+
+class Bar : public Foo { };
+
+class Spam: public Foo {
+public:
+   Spam() { }
+};
+
+
+template <class Type>
+class NRFilter {
+public:
+  virtual ~NRFilter()
+  {
+  }
+  
+protected:
+  virtual void do_filter() = 0;
+};
+
+template <class Type>
+class NRRCFilter : public NRFilter<Type>
+{
+};
+ 
+
+template <class Type>
+class NRRCFilterpro : protected NRFilter<Type>
+{
+};
+
+
+template <class Type>
+class NRRCFilterpri : private NRFilter<Type>
+{
+};
+
+%}
+
+%template(NRFilter_i) NRFilter<int>;
+
+%template(NRRCFilter_i) NRRCFilter<int>;
+
+%template(NRRCFilterpro_i) NRRCFilterpro<int>;
+
+%template(NRRCFilterpri_i) NRRCFilterpri<int>;
+
diff --git a/trunk/Examples/test-suite/abstract_inherit_ok.i b/trunk/Examples/test-suite/abstract_inherit_ok.i
new file mode 100644
index 0000000..cb40fa4
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_inherit_ok.i
@@ -0,0 +1,22 @@
+%module abstract_inherit_ok
+
+%feature("notabstract") Spam;
+%warnfilter(SWIGWARN_TYPE_ABSTRACT) Spam;
+
+%inline %{
+
+class Foo {
+public:
+    virtual ~Foo() { }
+    virtual int blah() = 0;
+};
+
+class Spam: public Foo {
+public:
+   Spam() { }
+#ifndef SWIG
+   int blah() { return 0; }
+#endif
+};
+
+%}
diff --git a/trunk/Examples/test-suite/abstract_signature.i b/trunk/Examples/test-suite/abstract_signature.i
new file mode 100644
index 0000000..5d68fd0
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_signature.i
@@ -0,0 +1,26 @@
+%module abstract_signature
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) abstract_foo;	// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) abstract_bar;	// Ruby, wrong class name
+
+%inline %{ 
+class abstract_foo 
+{ 
+public: 
+  abstract_foo() { }; 
+  virtual ~abstract_foo() { }; 
+  virtual int   meth(int meth_param) = 0; 
+}; 
+ 
+ 
+class abstract_bar : public abstract_foo 
+{ 
+public: 
+  abstract_bar() { }; 
+ 
+  virtual ~abstract_bar() { }; 
+  virtual int   meth(int meth_param) = 0; 
+  int           meth(int meth_param_1, int meth_param_2) { return 0; }
+}; 
+
+%}
diff --git a/trunk/Examples/test-suite/abstract_typedef.i b/trunk/Examples/test-suite/abstract_typedef.i
new file mode 100644
index 0000000..456cfc2
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_typedef.i
@@ -0,0 +1,56 @@
+%module abstract_typedef
+
+
+%inline %{
+    struct Engine
+    {
+    };
+
+    struct AbstractBaseClass
+    {
+      virtual ~AbstractBaseClass()
+      {
+      }
+      
+      virtual bool write(Engine& archive) const = 0;
+    };    
+
+    typedef Engine PersEngine;
+    typedef AbstractBaseClass PersClassBase;      
+
+    
+    class A : public PersClassBase
+    {
+      // This works always
+      // bool write(Engine& archive) const;
+
+      // This doesn't with Swig 1.3.17.
+      // But it works fine with 1.3.16
+      bool write(PersEngine& archive) const
+      {
+	return true;
+      }
+      
+    
+    };
+      
+%}
+
+
+/*
+
+Problem related to the direct comparison of strings
+in the file allocate.cxx (line 55)
+
+          ......
+	  String *local_decl = Getattr(dn,"decl");
+	  if (local_decl && !Strcmp(local_decl, base_decl)) {
+          ......
+
+with the direct string comparison, no equivalent types
+are checked and the two 'write' functions appear to be
+different because
+
+  "q(const).f(r.bss::PersEngine)." != "q(const).f(r.bss::Engine)."
+
+*/
diff --git a/trunk/Examples/test-suite/abstract_typedef2.i b/trunk/Examples/test-suite/abstract_typedef2.i
new file mode 100644
index 0000000..450af39
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_typedef2.i
@@ -0,0 +1,60 @@
+%module abstract_typedef2
+
+ /*
+   After the fix for abstract_typedef, this simpler
+   example got broken.
+ */
+
+%inline %{
+
+  enum FieldDim {
+    UnaryField,
+    BinaryField
+  };
+  
+  template <FieldDim Dim>
+    struct Facet;
+  
+
+  template <FieldDim Dim>
+    struct Base 
+    {
+      virtual ~Base() {}
+      
+      typedef unsigned int size_type;
+      typedef Facet<Dim>* facet_ptr;
+
+      // This works 
+      // virtual Facet<Dim>* set(size_type) = 0;
+      
+      // This doesn't
+      virtual facet_ptr set(size_type) = 0;
+    };
+  
+
+  template <FieldDim Dim>
+    struct Facet
+    {
+    };
+  
+
+  template <FieldDim Dim>
+    struct A : Base<Dim>
+    {
+      typedef Base<Dim> base;
+      typedef typename base::size_type size_type;
+
+      A(int a = 0)
+      {
+      }
+      
+      Facet<Dim>* set(size_type) 
+      {
+	return 0;
+      }      
+    };
+%}
+
+
+%template(Base_UF) Base<UnaryField>;
+%template(A_UF) A<UnaryField>;
diff --git a/trunk/Examples/test-suite/abstract_virtual.i b/trunk/Examples/test-suite/abstract_virtual.i
new file mode 100644
index 0000000..e2d8054
--- /dev/null
+++ b/trunk/Examples/test-suite/abstract_virtual.i
@@ -0,0 +1,67 @@
+%module(ruby_minherit="1") abstract_virtual
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) D; /* C#, Java, Php4 multiple inheritance */
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) E; /* C#, Java, Php4 multiple inheritance */
+
+%inline %{
+#if defined(_MSC_VER)
+  #pragma warning( disable : 4250) // warning C4250: 'D' : inherits 'B::B::foo' via dominance
+#endif
+  struct A 
+  {
+    virtual ~A()
+    {
+    }
+    
+    virtual int foo() = 0;
+  };
+ 
+  struct B : virtual A
+  {
+    int foo() 
+    {
+      return 0;
+    }
+  };
+  
+  struct C: virtual A
+  {
+  protected:
+    C()
+    {
+    }
+  };
+
+  //
+  // This case works
+  //
+  struct D : B, C
+  {
+    D()
+    {
+    }
+  };
+
+  //
+  // This case doesn't work.
+  // It seems the is_abstract function doesn't
+  // navigate the entire set of base classes,
+  // and therefore, it doesn't detect B::foo()
+  //
+#ifdef SWIG
+  // Uncommenting this line, of course, make it works
+  // %feature("notabstract") E;
+#endif
+  //
+  struct E : C, B
+  {
+    E()
+    {
+    }    
+  };
+%}
+
diff --git a/trunk/Examples/test-suite/access_change.i b/trunk/Examples/test-suite/access_change.i
new file mode 100644
index 0000000..aca5af3
--- /dev/null
+++ b/trunk/Examples/test-suite/access_change.i
@@ -0,0 +1,51 @@
+%module access_change
+
+// test access changing from protected to public
+
+%inline %{
+
+template<typename T> class Base {
+public:
+  virtual ~Base() {}
+  virtual int *PublicProtectedPublic1() { return 0; }
+  int *PublicProtectedPublic2() { return 0; }
+  virtual int *PublicProtectedPublic3() { return 0; }
+  int *PublicProtectedPublic4() { return 0; }
+protected:
+  virtual int * WasProtected1() { return 0; }
+  int * WasProtected2() { return 0; }
+  virtual int * WasProtected3() { return 0; }
+  int * WasProtected4() { return 0; }
+};
+
+template<typename T> class Derived : public Base<T> {
+public:
+  int * WasProtected1() { return 0; }
+  int * WasProtected2() { return 0; }
+  using Base<T>::WasProtected3;
+  using Base<T>::WasProtected4;
+protected:
+  virtual int *PublicProtectedPublic1() { return 0; }
+  int *PublicProtectedPublic2() { return 0; }
+  using Base<T>::PublicProtectedPublic3;
+  using Base<T>::PublicProtectedPublic4;
+};
+
+template<typename T> class Bottom : public Derived<T> {
+public:
+  int * WasProtected1() { return 0; }
+  int * WasProtected2() { return 0; }
+  using Base<T>::WasProtected3;
+  using Base<T>::WasProtected4;
+  int *PublicProtectedPublic1() { return 0; }
+  int *PublicProtectedPublic2() { return 0; }
+  int *PublicProtectedPublic3() { return 0; }
+  int *PublicProtectedPublic4() { return 0; }
+};
+%}
+
+%template(BaseInt) Base<int>;
+%template(DerivedInt) Derived<int>;
+%template(BottomInt) Bottom<int>;
+
+
diff --git a/trunk/Examples/test-suite/add_link.i b/trunk/Examples/test-suite/add_link.i
new file mode 100644
index 0000000..dfd4b37
--- /dev/null
+++ b/trunk/Examples/test-suite/add_link.i
@@ -0,0 +1,20 @@
+%module add_link
+
+%extend Foo {
+Foo *blah() {
+   return new Foo();
+}
+};
+
+
+%inline %{
+class Foo {
+public:
+  Foo() { };
+};
+
+%}
+
+
+
+
diff --git a/trunk/Examples/test-suite/aggregate.i b/trunk/Examples/test-suite/aggregate.i
new file mode 100644
index 0000000..dc00f06
--- /dev/null
+++ b/trunk/Examples/test-suite/aggregate.i
@@ -0,0 +1,37 @@
+/* This file tests a few new contract features.
+   First it checks to make sure the constant aggregation macro
+   %aggregate_check() works.  This is defined in swig.swg.
+
+   Next, it checks to make sure a simple contract works.
+   To support contracts, you need to add a macro to the runtime.
+   For Python, it looks like this:
+
+#define SWIG_contract_assert(expr, msg)  if (!(expr)) { PyErr_SetString(PyExc_RuntimeError, (char *) msg #expr ); goto fail; } else
+
+   Note: It is used like this:
+   SWIG_contract_assert(x == 1, "Some kind of error message");
+
+   Note: Contracts are still experimental.  The runtime interface may
+   change in future versions.   
+   */
+
+%module aggregate
+
+%include <exception.i>
+%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT)
+
+%contract move(int x) {
+require:
+   check_direction(x);
+}
+
+%inline %{
+#define UP    1
+#define DOWN  2
+#define LEFT  3
+#define RIGHT 4
+
+int move(int direction) {
+    return direction;
+}
+%}
diff --git a/trunk/Examples/test-suite/allegrocl/Makefile.in b/trunk/Examples/test-suite/allegrocl/Makefile.in
new file mode 100644
index 0000000..394d2d5
--- /dev/null
+++ b/trunk/Examples/test-suite/allegrocl/Makefile.in
@@ -0,0 +1,166 @@
+#######################################################################
+# Makefile for allegrocl test-suite
+#######################################################################
+
+LANGUAGE     = allegrocl
+ALLEGROCL    = @ALLEGROCLBIN@
+SCRIPTSUFFIX = _runme.lisp
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+# these cpp tests aren't working. Fix 'em
+# need to further separate these into tests requiring
+# std libraries, or the $ldestructor problem.
+CPP_TEST_BROKEN_ACL = \
+	array_member \
+	char_strings \
+	class_ignore \
+	constant_pointers \
+	contract \
+	cplusplus_throw \
+	cpp_basic \
+	cpp_enum \
+	cpp_typedef \
+	default_constructor \
+	default_args \
+	dynamic_cast \
+	enum_thorough \
+	extend_variable \
+	global_vars \
+	import_nomodule \
+	kind \
+	li_carrays \
+	li_cdata \
+	li_windows \
+	namespace_class \
+	namespace_spaces \
+	naturalvar \
+	operator_overload \
+	overload_simple \
+	register_par \
+	sizet \
+	smart_pointer_extend \
+	smart_pointer_namespace \
+	template \
+	template_classes \
+	template_default \
+	template_default_inherit \
+	template_enum \
+	template_explicit \
+	template_extend_overload \
+	template_ns \
+	template_ns4 \
+	template_ns_enum \
+	template_rename \
+	template_retvalue \
+	template_static \
+	template_tbase_template \
+	template_typedef \
+	template_typedef_cplx \
+	template_typedef_cplx2 \
+	template_typedef_cplx3 \
+	template_typedef_cplx4 \
+	template_typedef_cplx5 \
+	template_typedef_ns \
+	template_typedef_rec \
+	threads \
+	typedef_array_member \
+	typedef_sizet \
+	typemap_namespace \
+	union_scope \
+	using_pointers \
+	valuewrapper_opaque \
+	varargs \
+	virtual_poly \
+	voidtest \
+	wrapmacro
+
+# these aren't working due to longlong support. (low hanging fruit)
+CPP_TEST_BROKEN_LONGLONG = \
+	arrays_dimensionless \
+	arrays_global \
+	arrays_global_twodim \
+	li_stdint \
+	li_typemaps \
+	long_long_apply \
+	mixed_types \
+	primitive_ref \
+	reference_global_vars \
+	template_default_arg
+
+# These are currently unsupported.
+CPP_TEST_CASES_ACL_UNSUPPORTED = \
+	aggregate \
+	contract \
+	director_abstract \
+	director_basic \
+	director_constructor \
+	director_detect \
+	director_default \
+	director_enum \
+	director_exception \
+	director_frob \
+	director_finalizer \
+	director_nested \
+	director_protected \
+	director_redefined \
+	director_unroll \
+	director_using \
+	director_wombat \
+	exception_order \
+	extern_throws \
+	throw_exception
+		
+C_TEST_CASES_ACL_BROKEN = \
+	arrays \
+	enums \
+	extern_declaration \
+	immutable \
+	integers \
+	li_cdata \
+	typemap_subst
+
+C_TEST_BROKEN_LONGLONG = \
+	long_long
+
+
+# std lib support hasn't been done yet.
+SKIP_CPP_STD_CASES = Yes
+
+C_TEST_CASES =
+
+CPP_TEST_CASES =
+
+include $(srcdir)/../common.mk
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.lisp appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(ALLEGROCLBIN) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: (does nothing, we dont generate extra allegrocl code)
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile allegrocl_clean
+
diff --git a/trunk/Examples/test-suite/allowexcept.i b/trunk/Examples/test-suite/allowexcept.i
new file mode 100644
index 0000000..14b19b3
--- /dev/null
+++ b/trunk/Examples/test-suite/allowexcept.i
@@ -0,0 +1,61 @@
+// Test allowexcept feature
+
+%module allowexcept
+
+// First make sure %exception is not used by default for variable wrappers
+
+%nodefaultctor;
+%nodefaultdtor;
+%exception {
+   This will not compile
+}
+
+%inline %{
+struct UVW {};
+UVW uvw_global_variable;
+struct Bar {
+  UVW member_variable;
+  static UVW static_member_variable;
+};
+UVW Bar::static_member_variable;
+%}
+
+
+// Now test the allowexcept feature by making the usual $action uncompileable and ensuring the %exception is picked up
+
+struct XYZ {
+};
+
+%{
+struct XYZ {
+  void foo() {}
+private:
+  XYZ& operator=(const XYZ& other); // prevent assignment used in normally generated set method
+  XYZ* operator&(); // prevent dereferencing used in normally generated  get method
+};
+%}
+#if defined(SWIGUTL)
+%exception {
+  /* 
+   $action
+  */
+  SWIG_fail;
+}
+#else
+%exception {
+  /* 
+   $action
+  */
+}
+#endif
+%allowexception;
+
+%inline %{
+XYZ global_variable;
+struct Foo {
+  XYZ member_variable;
+  static XYZ static_member_variable;
+};
+XYZ Foo::static_member_variable;
+%}
+
diff --git a/trunk/Examples/test-suite/allprotected.i b/trunk/Examples/test-suite/allprotected.i
new file mode 100644
index 0000000..bd4dfe5
--- /dev/null
+++ b/trunk/Examples/test-suite/allprotected.i
@@ -0,0 +1,78 @@
+// Tests for the allprotected option
+
+%module(directors="1", allprotected="1") allprotected
+
+%{
+#include <string>
+%}
+
+%include "std_string.i"
+
+%feature("director") PublicBase;
+%feature("director") ProtectedBase;
+
+// protected types not supported (ProtectedEnum, IntegerType). Make sure they can be ignored.
+%ignore ProtectedBase::protectedenum;
+%ignore ProtectedBase::typedefs;
+
+%inline %{
+class Klass {
+  std::string name;
+public:
+  Klass(const std::string& n) : name(n) {}
+  std::string getName() { return name; }
+};
+
+class PublicBase {
+  std::string str;
+public:
+  enum AnEnum { EnumVal1, EnumVal2 };
+public:
+  PublicBase(const char* s): str(s), instanceMemberVariable(0), anEnum(EnumVal1), stringMember(0) {}
+  virtual ~PublicBase() { }
+  virtual std::string virtualMethod() const { return "PublicBase"; }
+  Klass instanceMethod(Klass k) const { return k; }
+  Klass *instanceOverloaded(Klass *k) const { return k; }
+  Klass *instanceOverloaded(Klass *k, std::string name) const { return new Klass(name); }
+  static Klass staticMethod(Klass k) { return k; }
+  static Klass *staticOverloaded(Klass *k) { return k; }
+  static Klass *staticOverloaded(Klass *k, std::string name) { return new Klass(name); }
+  int instanceMemberVariable;
+  static int staticMemberVariable;
+  static const int staticConstMemberVariable = 20;
+  AnEnum anEnum;
+  char *stringMember;
+};
+int PublicBase::staticMemberVariable = 10;
+
+class ProtectedBase {
+  std::string str;
+public:
+  enum AnEnum { EnumVal1, EnumVal2 };
+  std::string getName() { return str; }
+protected:
+  ProtectedBase(const char* s): str(s), instanceMemberVariable(0), anEnum(EnumVal1), stringMember(0), protectedenum(ProtEnumVal1) {}
+  virtual ~ProtectedBase() { }
+  virtual std::string virtualMethod() const { return "ProtectedBase"; }
+  Klass instanceMethod(Klass k) const { return k; }
+  Klass *instanceOverloaded(Klass *k) const { return k; }
+  Klass *instanceOverloaded(Klass *k, std::string name) const { return new Klass(name); }
+  static Klass staticMethod(Klass k) { return k; }
+  static Klass *staticOverloaded(Klass *k) { return k; }
+  static Klass *staticOverloaded(Klass *k, std::string name) { return new Klass(name); }
+  int instanceMemberVariable;
+  static int staticMemberVariable;
+  static const int staticConstMemberVariable = 20;
+  AnEnum anEnum;
+  char *stringMember;
+
+// unsupported: types defined with protected access and thus methods/variables which use them
+  enum ProtectedEnum { ProtEnumVal1, ProtEnumVal2 };
+  typedef int IntegerType;
+  ProtectedEnum protectedenum;
+  IntegerType typedefs(IntegerType it) { return it; }
+};
+int ProtectedBase::staticMemberVariable = 10;
+
+%}
+
diff --git a/trunk/Examples/test-suite/anonymous_bitfield.i b/trunk/Examples/test-suite/anonymous_bitfield.i
new file mode 100644
index 0000000..309f82c
--- /dev/null
+++ b/trunk/Examples/test-suite/anonymous_bitfield.i
@@ -0,0 +1,17 @@
+%module anonymous_bitfield 
+
+%inline %{
+
+struct Foo {
+   int x : 4;
+   int y : 4;
+   int   : 2;
+   unsigned int f : 1;
+   unsigned int : 5;
+   int z : 15;
+   unsigned int : 8+6; 
+   unsigned seq : (sizeof(unsigned)*8 - 6); 
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/apply_signed_char.i b/trunk/Examples/test-suite/apply_signed_char.i
new file mode 100644
index 0000000..c0fa00c
--- /dev/null
+++ b/trunk/Examples/test-suite/apply_signed_char.i
@@ -0,0 +1,37 @@
+/* Test %apply for char */
+
+%module(directors="1") apply_signed_char
+
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) DirectorTest;
+
+%apply signed char {char, const char};
+%apply const signed char & {const char &};
+
+%inline %{
+  char CharValFunction(char number) { return number; }
+  const char CCharValFunction(const char number) { return number; }
+  const char & CCharRefFunction(const char & number) { return number; }
+  char globalchar = -109;
+  const char globalconstchar = -110;
+%}
+
+// Director test
+%feature("director");
+
+%inline %{
+  struct DirectorTest {
+
+    DirectorTest() : memberchar(-111), memberconstchar(-112) {}
+
+    virtual char CharValFunction(char number) { return number; }
+    virtual const char CCharValFunction(const char number) { return number; }
+    virtual const char & CCharRefFunction(const char & number) { return number; }
+
+    char memberchar;
+    const char memberconstchar;
+
+    virtual ~DirectorTest() {}
+  private:
+    DirectorTest& operator=(const DirectorTest &);
+  };
+%}
diff --git a/trunk/Examples/test-suite/apply_strings.i b/trunk/Examples/test-suite/apply_strings.i
new file mode 100644
index 0000000..54a91f8
--- /dev/null
+++ b/trunk/Examples/test-suite/apply_strings.i
@@ -0,0 +1,78 @@
+/* Test %apply for char *, signed char *, unsigned char * 
+   This won't work in all situations, so does not necessarily have to be implemented. See 
+   http://groups.google.com.ai/group/comp.lang.c++.moderated/browse_thread/thread/ad5873ce25d49324/0ae94552452366be?lnk=raot */
+%module(directors="1") apply_strings
+
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) DirectorTest;
+%warnfilter(SWIGWARN_TYPEMAP_VARIN_UNDEF) DigitsGlobalB;
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK) DigitsGlobalC;
+
+%apply char * {UCharPtr};
+%apply char * {SCharPtr};
+%apply const char * {CUCharPtr};
+%apply const char * {CSCharPtr};
+
+%inline %{
+  typedef unsigned char* UCharPtr;
+  typedef signed char* SCharPtr;
+  typedef const unsigned char* CUCharPtr;
+  typedef const signed char* CSCharPtr;
+
+  UCharPtr UCharFunction(UCharPtr str) { return str; }
+  SCharPtr SCharFunction(SCharPtr str) { return str; }
+  CUCharPtr CUCharFunction(CUCharPtr str) { return str; }
+  CSCharPtr CSCharFunction(CSCharPtr str) { return str; }
+%}
+
+%typemap(freearg) SWIGTYPE * ""
+%apply SWIGTYPE* {CharPtr};
+%apply SWIGTYPE* {CCharPtr};
+
+%inline %{
+  typedef char* CharPtr;
+  typedef const char* CCharPtr;
+
+  CharPtr CharFunction(CharPtr buffer) { return buffer; }
+  CCharPtr CCharFunction(CCharPtr buffer) { return buffer; }
+%}
+
+// unsigned char* as strings
+#if defined(SWIGJAVA) || defined(SWIGCSHARP)
+
+/* Note: Chicken does not allow unsigned char * in strings */
+
+%apply char [ANY] {TAscii[ANY]}
+%apply char [] {TAscii []}
+%apply char * {TAscii *}
+
+#endif
+
+%inline %{
+typedef unsigned char TAscii;
+typedef struct {
+   TAscii DigitsMemberA[20];
+   TAscii *DigitsMemberB;
+} TNumber;
+ 
+TAscii DigitsGlobalA[20];
+TAscii DigitsGlobalB[] = {(unsigned char)'A', (unsigned char)'B', 0};
+TAscii *DigitsGlobalC;
+
+%} 
+
+// Director test
+%feature("director");
+
+%inline %{
+  struct DirectorTest {
+    virtual UCharPtr UCharFunction(UCharPtr str) { return str; }
+    virtual SCharPtr SCharFunction(SCharPtr str) { return str; }
+    virtual CUCharPtr CUCharFunction(CUCharPtr str) { return str; }
+    virtual CSCharPtr CSCharFunction(CSCharPtr str) { return str; }
+    virtual CharPtr CharFunction(CharPtr buffer) { return buffer; }
+    virtual CCharPtr CCharFunction(CCharPtr buffer) { return buffer; }
+    virtual ~DirectorTest() {}
+  };
+%}
+
+
diff --git a/trunk/Examples/test-suite/argout.i b/trunk/Examples/test-suite/argout.i
new file mode 100644
index 0000000..8f849a6
--- /dev/null
+++ b/trunk/Examples/test-suite/argout.i
@@ -0,0 +1,37 @@
+/* This interface file checks how well SWIG handles passing data back
+   through arguments WITHOUT returning it separately; for the cases where
+   maybe multiple values are passed by reference and all want changing */
+
+%module argout
+
+%include cpointer.i
+%pointer_functions(int,intp);
+
+%inline %{
+// returns old value
+int incp(int *value) {
+  return (*value)++;
+}
+
+// returns old value
+int incr(int &value) {
+  return value++;
+}
+
+typedef int & IntRef;
+// returns old value
+int inctr(IntRef value) {
+  return value++;
+}
+
+// example of the old DB login type routines where you keep
+// a void* which it points to its opaque struct when you login
+// So login function takes a void**
+void voidhandle(void** handle) {
+  *handle=(void*)"Here it is";
+}
+char * handle(void* handle) {
+  return (char *)handle;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/array_member.i b/trunk/Examples/test-suite/array_member.i
new file mode 100644
index 0000000..d8e2f87
--- /dev/null
+++ b/trunk/Examples/test-suite/array_member.i
@@ -0,0 +1,74 @@
+%module array_member
+
+%inline %{
+
+typedef struct Foo {
+    char   text[8]; 
+    int    data[8];
+} Foo;
+
+int global_data[8] = { 0,1,2,3,4,5,6,7 };
+
+void set_value(int *x, int i, int v) {
+    x[i] = v;
+}
+
+int get_value(int *x, int i) {
+    return x[i];
+}
+%}
+
+
+
+
+
+
+#ifdef __cplusplus
+%inline 
+{
+
+  struct Material
+  {
+  };
+
+  class RayPacketData {
+  public:
+    enum {
+      Size = 32
+    };
+    
+    const Material * chitMat[Size];
+    Material hitMat_val[Size];
+    Material *hitMat[Size];
+
+    const Material * chitMat2[Size][Size];
+    Material hitMat_val2[Size][Size];
+    Material *hitMat2[Size][Size];
+  };
+}
+
+#endif
+
+
+
+%inline %{
+#define BUFF_LEN 12
+
+typedef unsigned char BUFF[BUFF_LEN]; 
+
+typedef BUFF MY_BUFF;
+
+typedef struct _m {
+  int i;
+  MY_BUFF x;
+} MyBuff;
+
+
+typedef char SBUFF[BUFF_LEN];
+typedef SBUFF MY_SBUFF;
+typedef struct _sm {
+  int i;
+  MY_SBUFF x;
+} MySBuff;
+
+%}
diff --git a/trunk/Examples/test-suite/array_typedef_memberin.i b/trunk/Examples/test-suite/array_typedef_memberin.i
new file mode 100644
index 0000000..3a0cf25
--- /dev/null
+++ b/trunk/Examples/test-suite/array_typedef_memberin.i
@@ -0,0 +1,12 @@
+%module array_typedef_memberin
+%inline %{ 
+typedef short arr_short8[8]; 
+namespace ArrayExample 
+{ 
+    class ExampleDetail 
+    { 
+    public: 
+        arr_short8 node_list; 
+     }; 
+} 
+%} 
diff --git a/trunk/Examples/test-suite/arrayref.i b/trunk/Examples/test-suite/arrayref.i
new file mode 100644
index 0000000..f9c4df7
--- /dev/null
+++ b/trunk/Examples/test-suite/arrayref.i
@@ -0,0 +1,14 @@
+// A function that passes arrays by reference 
+
+%module arrayref
+
+%inline %{
+
+void foo(const int (&x)[10]) {
+}
+
+void bar(int (&x)[10]) {
+}
+%}
+
+
diff --git a/trunk/Examples/test-suite/arrays.i b/trunk/Examples/test-suite/arrays.i
new file mode 100644
index 0000000..decce74
--- /dev/null
+++ b/trunk/Examples/test-suite/arrays.i
@@ -0,0 +1,72 @@
+/*
+This test case tests that various types of arrays are working.
+*/
+
+%module arrays
+%{
+#include <stdlib.h>
+%}
+
+%inline %{
+#define ARRAY_LEN 2
+
+typedef enum {One, Two, Three, Four, Five} finger;
+
+typedef struct {
+	double         double_field;
+} SimpleStruct;
+
+typedef struct {
+	char           array_c [ARRAY_LEN];
+	signed char    array_sc[ARRAY_LEN];
+	unsigned char  array_uc[ARRAY_LEN];
+	short          array_s [ARRAY_LEN];
+	unsigned short array_us[ARRAY_LEN];
+	int            array_i [ARRAY_LEN];
+	unsigned int   array_ui[ARRAY_LEN];
+	long           array_l [ARRAY_LEN];
+	unsigned long  array_ul[ARRAY_LEN];
+	long long      array_ll[ARRAY_LEN];
+	float          array_f [ARRAY_LEN];
+        double         array_d [ARRAY_LEN];
+        SimpleStruct   array_struct[ARRAY_LEN];
+        SimpleStruct*  array_structpointers[ARRAY_LEN];
+        int*           array_ipointers [ARRAY_LEN];
+	finger         array_enum[ARRAY_LEN];
+	finger*        array_enumpointers[ARRAY_LEN];
+	const int      array_const_i[ARRAY_LEN];
+} ArrayStruct;
+
+void fn_taking_arrays(SimpleStruct array_struct[ARRAY_LEN]) {}
+
+/* Pointer helper functions used in the Java run test */
+int* newintpointer() {
+    return (int*)malloc(sizeof(int));
+}
+void setintfrompointer(int* intptr, int value) {
+    *intptr = value;
+}
+int getintfrompointer(int* intptr) {
+    return *intptr;
+}
+
+%}
+
+// This tests wrapping of function that involves pointer to array
+
+
+%inline %{
+void array_pointer_func(int (*x)[10]) {}
+%}
+
+
+%inline %{
+typedef float FLOAT;
+
+typedef FLOAT cartPosition_t[3]; 
+
+typedef struct {
+cartPosition_t p;
+} CartPoseData_t;
+
+%}
diff --git a/trunk/Examples/test-suite/arrays_dimensionless.i b/trunk/Examples/test-suite/arrays_dimensionless.i
new file mode 100644
index 0000000..11dc022
--- /dev/null
+++ b/trunk/Examples/test-suite/arrays_dimensionless.i
@@ -0,0 +1,69 @@
+
+%module arrays_dimensionless
+
+%warnfilter(SWIGWARN_TYPEMAP_VARIN_UNDEF) globalints;    /* Unable to set variable of type int [] */
+%warnfilter(SWIGWARN_TYPEMAP_VARIN_UNDEF) ints;          /* Unable to set variable of type int [] */
+
+%inline %{
+
+int globalints[] = {100, 200, 300};
+const int constglobalints[] = {400, 500, 600};
+
+struct Bar {
+    static int ints[];
+};
+int Bar::ints[] = {700, 800, 900};
+
+double arr_bool(bool array[], int length)                { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]=!array[i]; } return sum; }
+double arr_char(char array[], int length)                { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_schar(signed char array[], int length)        { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_uchar(unsigned char array[], int length)      { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_short(short array[], int length)              { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_ushort(unsigned short array[], int length)    { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_int(int array[], int length)                  { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_uint(unsigned int array[], int length)        { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_long(long array[], int length)                { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_ulong(unsigned long array[], int length)      { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_ll(long long array[], int length)             { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_ull(unsigned long long array[], int length)   { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_float(float array[], int length)              { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+double arr_double(double array[], int length)            { double sum=0.0; int i=0; for(; i<length; i++) { sum += array[i]; array[i]*=2; } return sum; }
+
+%}
+
+%apply SWIGTYPE[] {
+ bool *, 
+ char *, 
+ signed char *, 
+ unsigned char *, 
+ short *, 
+ unsigned short *, 
+ int *, 
+ unsigned int *, 
+ long *, 
+ unsigned long *, 
+ long *, 
+ unsigned long long *, 
+ float *, 
+ double *
+}
+
+%inline %{
+
+double ptr_bool(bool *array, int length)                { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_char(char *array, int length)                { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_schar(signed char *array, int length)        { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_uchar(unsigned char *array, int length)      { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_short(short *array, int length)              { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_ushort(unsigned short *array, int length)    { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_int(int *array, int length)                  { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_uint(unsigned int *array, int length)        { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_long(long *array, int length)                { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_ulong(unsigned long *array, int length)      { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_ll(long long *array, int length)             { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_ull(unsigned long long *array, int length)   { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_float(float *array, int length)              { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+double ptr_double(double *array, int length)            { double sum=0.0; int i=0; for(; i<length; i++) sum += array[i]; return sum; }
+
+%}
+
diff --git a/trunk/Examples/test-suite/arrays_global.i b/trunk/Examples/test-suite/arrays_global.i
new file mode 100644
index 0000000..10d29b6
--- /dev/null
+++ b/trunk/Examples/test-suite/arrays_global.i
@@ -0,0 +1,95 @@
+/*
+This test case tests that various types of arrays are working.
+*/
+
+%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK,SWIGWARN_TYPEMAP_VARIN_UNDEF);
+
+%module arrays_global
+
+%inline %{
+#define ARRAY_LEN 2
+
+typedef enum {One, Two, Three, Four, Five} finger;
+
+typedef struct {
+	double         double_field;
+} SimpleStruct;
+
+char           array_c [ARRAY_LEN];
+signed char    array_sc[ARRAY_LEN];
+unsigned char  array_uc[ARRAY_LEN];
+short          array_s [ARRAY_LEN];
+unsigned short array_us[ARRAY_LEN];
+int            array_i [ARRAY_LEN];
+unsigned int   array_ui[ARRAY_LEN];
+long           array_l [ARRAY_LEN];
+unsigned long  array_ul[ARRAY_LEN];
+long long      array_ll[ARRAY_LEN];
+float          array_f [ARRAY_LEN];
+double         array_d [ARRAY_LEN];
+SimpleStruct   array_struct[ARRAY_LEN];
+SimpleStruct*  array_structpointers[ARRAY_LEN];
+int*           array_ipointers [ARRAY_LEN];
+finger         array_enum[ARRAY_LEN];
+finger*        array_enumpointers[ARRAY_LEN];
+const int      array_const_i[ARRAY_LEN] = {10, 20};
+
+%}
+
+%inline %{
+  
+const char BeginString_FIX44a[8] = "FIX.a.a"; 
+char BeginString_FIX44b[8] = "FIX.b.b"; 
+
+const char BeginString_FIX44c[] = "FIX.c.c"; 
+char BeginString_FIX44d[] = "FIX.d.d"; 
+
+const char* BeginString_FIX44e = "FIX.e.e"; 
+const char* const BeginString_FIX44f = "FIX.f.f"; 
+
+typedef char name[8];
+typedef char namea[];
+
+char* test_a(char hello[8],
+	     char hi[],
+	     const char chello[8],
+	     const char chi[]) {
+  return hi;
+}
+
+char* test_b(name a, const namea b)  {
+  return a;
+}
+
+#if 0
+int test_a(int a)  {
+  return a;
+}
+
+int test_b(int a)  {
+  return a;
+}
+ 
+#endif
+%}
+
+
+
+#ifdef __cplusplus
+%inline 
+{
+
+  struct Material
+  {
+  };
+
+  enum {
+    Size = 32
+  };
+  
+  const Material * chitMat[Size];
+  Material hitMat_val[Size];
+  Material *hitMat[Size];
+}
+
+#endif
diff --git a/trunk/Examples/test-suite/arrays_global_twodim.i b/trunk/Examples/test-suite/arrays_global_twodim.i
new file mode 100644
index 0000000..f6404b9
--- /dev/null
+++ b/trunk/Examples/test-suite/arrays_global_twodim.i
@@ -0,0 +1,61 @@
+/*
+Two dimension arrays
+*/
+
+%module arrays_global_twodim
+
+%inline %{
+#define ARRAY_LEN_X 2
+#define ARRAY_LEN_Y 4
+
+typedef enum {One, Two, Three, Four, Five} finger;
+
+typedef struct {
+    double         double_field;
+} SimpleStruct;
+
+char           array_c [ARRAY_LEN_X][ARRAY_LEN_Y];
+signed char    array_sc[ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned char  array_uc[ARRAY_LEN_X][ARRAY_LEN_Y];
+short          array_s [ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned short array_us[ARRAY_LEN_X][ARRAY_LEN_Y];
+int            array_i [ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned int   array_ui[ARRAY_LEN_X][ARRAY_LEN_Y];
+long           array_l [ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned long  array_ul[ARRAY_LEN_X][ARRAY_LEN_Y];
+long long      array_ll[ARRAY_LEN_X][ARRAY_LEN_Y];
+float          array_f [ARRAY_LEN_X][ARRAY_LEN_Y];
+double         array_d [ARRAY_LEN_X][ARRAY_LEN_Y];
+SimpleStruct   array_struct[ARRAY_LEN_X][ARRAY_LEN_Y];
+SimpleStruct*  array_structpointers[ARRAY_LEN_X][ARRAY_LEN_Y];
+int*           array_ipointers [ARRAY_LEN_X][ARRAY_LEN_Y];
+finger         array_enum[ARRAY_LEN_X][ARRAY_LEN_Y];
+finger*        array_enumpointers[ARRAY_LEN_X][ARRAY_LEN_Y];
+const int      array_const_i[ARRAY_LEN_X][ARRAY_LEN_Y] = { {10, 11, 12, 13}, {14, 15, 16, 17} };
+
+void fn_taking_arrays(SimpleStruct array_struct[ARRAY_LEN_X][ARRAY_LEN_Y]) {}
+
+int get_2d_array(int (*array)[ARRAY_LEN_Y], int x, int y){
+    return array[x][y];
+}
+%}
+
+#ifdef __cplusplus
+%inline 
+{
+
+  struct Material
+  {
+  };
+
+  enum {
+    Size = 32
+  };
+  
+  const Material * chitMat[Size][Size];
+  Material hitMat_val[Size][Size];
+  Material *hitMat[Size][Size];
+}
+
+#endif
+
diff --git a/trunk/Examples/test-suite/arrays_scope.i b/trunk/Examples/test-suite/arrays_scope.i
new file mode 100644
index 0000000..efde11e
--- /dev/null
+++ b/trunk/Examples/test-suite/arrays_scope.i
@@ -0,0 +1,19 @@
+%module arrays_scope
+
+%inline %{
+
+enum { ASIZE = 256 };
+namespace foo {
+   enum { BBSIZE = 512 };
+   class Bar {
+   public:
+      enum { CCSIZE = 768 };
+      int  adata[ASIZE];
+      int  bdata[BBSIZE];
+      int  cdata[CCSIZE];
+      void blah(int x[ASIZE], int y[BBSIZE], int z[CCSIZE]) { };
+   };
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/bloody_hell.i b/trunk/Examples/test-suite/bloody_hell.i
new file mode 100644
index 0000000..e580f0d
--- /dev/null
+++ b/trunk/Examples/test-suite/bloody_hell.i
@@ -0,0 +1,18 @@
+%module bloody_hell
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) kMaxIOCTLSpaceParmsSize;
+
+#define kMaxIOCTLSpaceParmsSize 128 
+
+%{
+#define kMaxIOCTLSpaceParmsSize 128 
+  %}
+
+%inline %{
+typedef struct sm_channel_ix_dump_parms { 
+     unsigned        data[(kMaxIOCTLSpaceParmsSize - ((4*sizeof(int)) + (2*sizeof(unsigned))))/sizeof(unsigned)]; 
+} SM_CHANNEL_IX_DUMP_PARMS; 
+ %}
+
+
+
diff --git a/trunk/Examples/test-suite/bools.i b/trunk/Examples/test-suite/bools.i
new file mode 100644
index 0000000..7b94fcf
--- /dev/null
+++ b/trunk/Examples/test-suite/bools.i
@@ -0,0 +1,64 @@
+// bool typemaps check
+%module bools
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);                   /* memory leak when setting a ptr/ref variable */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) constbool;         /* Ruby, wrong class name */
+
+// bool constant
+%constant bool constbool=false;
+
+%inline %{
+
+// bool variables
+bool bool1 = true;
+bool bool2 = false;
+bool* pbool = &bool1;
+bool& rbool = bool2;
+const bool* const_pbool = pbool;
+const bool& const_rbool = rbool;
+
+static int eax()
+{
+  return 1024;  // NOTE: any number > 255 should do
+}
+
+// bool functions
+bool bo(bool b) {
+  return b;
+}
+bool& rbo(bool& b) {
+    return b;
+}
+bool* pbo(bool* b) {
+    return b;
+}
+const bool& const_rbo(const bool& b) {
+    return b;
+}
+const bool* const_pbo(const bool* b) {
+    return b;
+}
+
+// helper function
+bool value(bool* b) {
+    return *b;
+}
+
+struct BoolStructure {
+  bool m_bool1;
+  bool m_bool2;
+  bool* m_pbool;
+  bool& m_rbool;
+  const bool* m_const_pbool;
+  const bool& m_const_rbool;
+  BoolStructure() :
+    m_bool1(true),
+    m_bool2(false),
+    m_pbool(&m_bool1),
+    m_rbool(m_bool2),
+    m_const_pbool(m_pbool),
+    m_const_rbool(m_rbool) {}
+private:
+  BoolStructure& operator=(const BoolStructure &);
+};
+%}
+
diff --git a/trunk/Examples/test-suite/cast_operator.i b/trunk/Examples/test-suite/cast_operator.i
new file mode 100644
index 0000000..88964e3
--- /dev/null
+++ b/trunk/Examples/test-suite/cast_operator.i
@@ -0,0 +1,20 @@
+%module cast_operator
+
+%rename(tochar) A::operator char*() const;
+%inline %{
+#include <string.h>
+struct A 
+{ 
+operator char*() const; 
+}; 
+
+inline 
+A::operator char*() const 
+{
+  static char hi[16];
+  strcpy(hi, "hi");
+  return hi;
+} 
+
+%}
+
diff --git a/trunk/Examples/test-suite/casts.i b/trunk/Examples/test-suite/casts.i
new file mode 100644
index 0000000..4893756
--- /dev/null
+++ b/trunk/Examples/test-suite/casts.i
@@ -0,0 +1,21 @@
+%module casts
+
+%inline %{
+
+class A { 
+ public: 
+  A() {} 
+  
+  void hello() 
+    { 
+    } 
+}; 
+
+class B : public A 
+{ 
+ public: 
+  B() {} 
+  
+};
+
+%}
diff --git a/trunk/Examples/test-suite/cffi/Makefile.in b/trunk/Examples/test-suite/cffi/Makefile.in
new file mode 100644
index 0000000..c345196
--- /dev/null
+++ b/trunk/Examples/test-suite/cffi/Makefile.in
@@ -0,0 +1,47 @@
+#######################################################################
+# Makefile for cffi test-suite
+#######################################################################
+
+LANGUAGE     = cffi
+CFFI         = @CFFIBIN@
+SCRIPTSUFFIX = _runme.lisp
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+include $(srcdir)/../common.mk
+
+# no C++ tests for now
+CPP_TEST_CASES =
+#C_TEST_CASES += 
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.lisp appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CFFIBIN) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: (does nothing, we dont generate extra cffi code)
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile cffi_clean
+
diff --git a/trunk/Examples/test-suite/char_constant.i b/trunk/Examples/test-suite/char_constant.i
new file mode 100644
index 0000000..5235b05
--- /dev/null
+++ b/trunk/Examples/test-suite/char_constant.i
@@ -0,0 +1,20 @@
+/* This interface file tests whether character constants are correctly
+   wrapped as procedures returning Scheme characters (rather than
+   Scheme strings). 
+*/
+
+%module char_constant
+
+#define CHAR_CONSTANT 'x'
+
+#define STRING_CONSTANT "xyzzy"
+
+#define ESC_CONST  '\1'
+#define NULL_CONST '\0'
+#define SPECIALCHAR 'á'
+
+%inline 
+{
+  const int ia = (int)'a';
+  const int ib = 'b';
+}
diff --git a/trunk/Examples/test-suite/char_strings.i b/trunk/Examples/test-suite/char_strings.i
new file mode 100644
index 0000000..b06eba7
--- /dev/null
+++ b/trunk/Examples/test-suite/char_strings.i
@@ -0,0 +1,159 @@
+/*
+A test case for testing char based strings. Useful for runtime testing,
+there were some runtime crashes and leaks in the C# module in some of the scenarios
+below.
+*/
+
+%module char_strings
+
+%warnfilter(SWIGWARN_TYPEMAP_VARIN_UNDEF) global_char_array1;  // Unable to set variable of type char[]
+%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) global_const_char;  // Setting a const char * variable may leak memory.
+
+%{
+#define OTHERLAND_MSG "Little message from the safe world."
+#define CPLUSPLUS_MSG "A message from the deep dark world of C++, where anything is possible."
+static char *global_str = NULL;
+const int UINT_DIGITS = 10; // max unsigned int is 4294967295
+
+bool check(const char *str, unsigned int number) {
+  static char expected[256];
+  sprintf(expected, "%s%d", OTHERLAND_MSG, number);
+  bool matches = (strcmp(str, expected) == 0);
+  if (!matches) printf("Failed: [%s][%s]\n", str, expected);
+  return matches;
+}
+
+%}
+
+%immutable global_const_char;
+
+%inline %{
+// get functions
+char *GetCharHeapString() {
+  global_str = new char[sizeof(CPLUSPLUS_MSG)+1];
+  strcpy(global_str, CPLUSPLUS_MSG);
+  return global_str;
+}
+
+const char *GetConstCharProgramCodeString() {
+  return CPLUSPLUS_MSG;
+}
+
+void DeleteCharHeapString() {
+  delete[] global_str;
+  global_str = NULL;
+}
+
+char *GetCharStaticString() {
+  static char str[sizeof(CPLUSPLUS_MSG)+1];
+  strcpy(str, CPLUSPLUS_MSG);
+  return str;
+}
+
+char *GetCharStaticStringFixed() {
+  static char str[] = CPLUSPLUS_MSG;
+  return str;
+}
+
+const char *GetConstCharStaticStringFixed() {
+  static const char str[] = CPLUSPLUS_MSG;
+  return str;
+}
+
+// set functions
+bool SetCharHeapString(char *str, unsigned int number) {
+  delete[] global_str;
+  global_str = new char[strlen(str)+UINT_DIGITS+1];
+  strcpy(global_str, str);
+  return check(global_str, number);
+}
+
+bool SetCharStaticString(char *str, unsigned int number) {
+  static char static_str[] = CPLUSPLUS_MSG;
+  strcpy(static_str, str);
+  return check(static_str, number);
+}
+
+bool SetCharArrayStaticString(char str[], unsigned int number) {
+  static char static_str[] = CPLUSPLUS_MSG;
+  strcpy(static_str, str);
+  return check(static_str, number);
+}
+
+bool SetConstCharHeapString(const char *str, unsigned int number) {
+  delete[] global_str;
+  global_str = new char[strlen(str)+UINT_DIGITS+1];
+  strcpy(global_str, str);
+  return check(global_str, number);
+}
+
+bool SetConstCharStaticString(const char *str, unsigned int number) {
+  static char static_str[] = CPLUSPLUS_MSG;
+  strcpy(static_str, str);
+  return check(static_str, number);
+}
+
+bool SetConstCharArrayStaticString(const char str[], unsigned int number) {
+  static char static_str[] = CPLUSPLUS_MSG;
+  strcpy(static_str, str);
+  return check(static_str, number);
+}
+
+// get set function
+char *CharPingPong(char *str) {
+  return str;
+}
+
+// variables
+char *global_char = NULL;
+char global_char_array1[] = CPLUSPLUS_MSG;
+char global_char_array2[sizeof(CPLUSPLUS_MSG)+1] = CPLUSPLUS_MSG;
+
+const char *global_const_char = CPLUSPLUS_MSG;
+const char global_const_char_array1[] = CPLUSPLUS_MSG;
+const char global_const_char_array2[sizeof(CPLUSPLUS_MSG)+1] = CPLUSPLUS_MSG;
+
+%}
+
+
+%typemap(newfree) char *GetNewCharString() { /* hello */ delete[] $1; }
+%newobject GetNewCharString();
+
+%inline {
+  char *GetNewCharString() {
+    char *nstr = new char[sizeof(CPLUSPLUS_MSG)+1];
+    strcpy(nstr, CPLUSPLUS_MSG);
+    return nstr;
+  }
+}
+
+%inline {
+  struct Formatpos;
+  struct OBFormat;
+  
+  static int GetNextFormat(Formatpos& itr, const  char*& str,OBFormat*& pFormat) {
+    return 0;
+  }
+  
+
+
+}
+
+
+%inline %{
+
+// char *& tests
+const char *&GetConstCharPointerRef() {
+  static const char str[] = CPLUSPLUS_MSG;
+  static const char *ptr = str;
+  return ptr;
+}
+
+bool SetConstCharPointerRef(const char *&str, unsigned int number) {
+  static char static_str[] = CPLUSPLUS_MSG;
+  strcpy(static_str, str);
+  return check(static_str, number);
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/chicken/Makefile.in b/trunk/Examples/test-suite/chicken/Makefile.in
new file mode 100644
index 0000000..ef6d705
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/Makefile.in
@@ -0,0 +1,96 @@
+#######################################################################
+# Makefile for chicken test-suite
+#######################################################################
+
+LANGUAGE     = chicken
+VARIANT      = 
+SCRIPTSUFFIX = _runme.ss
+PROXYSUFFIX  = _runme_proxy.ss
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+CHICKEN_CSI  = @CHICKEN_CSI@ -quiet -batch -no-init
+SO           = @SO@
+
+#C_TEST_CASES = long_long list_vector pointer_in_out multivalue
+
+# Skip the STD cases for now, except for li_std_string.i
+SKIP_CPP_STD_CASES = Yes
+
+CPP_TEST_CASES += li_std_string 
+
+EXTRA_TEST_CASES += ext_test.externaltest
+
+include $(srcdir)/../common.mk
+
+
+# Overridden variables here
+SWIGOPT += -nounit
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then ( \
+	  $(MAKE) $*.cppproxy; ) \
+	fi;
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then ( \
+	  $(MAKE) $*.cproxy; ) \
+	fi;
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then ( \
+	  $(MAKE) $*.multiproxy; ) \
+	fi;
+
+%.externaltest:
+	$(setup)
+	+$(swig_and_compile_external)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.scm appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CHICKEN_CSI) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# If there exists a PROXYSUFFIX runme file, we also generate the wrapper
+# with the -proxy argument
+%.cppproxy: SWIGOPT += -proxy
+%.cppproxy: SCRIPTSUFFIX = $(PROXYSUFFIX)
+%.cppproxy:
+	echo "$(ACTION)ing testcase $* (with run test) under chicken with -proxy"
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.cproxy: SWIGOPT += -proxy
+%.cproxy: SCRIPTSUFFIX = $(PROXYSUFFIX)
+%.cproxy:
+	echo "$(ACTION)ing testcase $* (with run test) under chicken with -proxy"
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multiproxy: SWIGOPT += -proxy -noclosuses
+%.multiproxy: SCRIPTSUFFIX = $(PROXYSUFFIX)
+%.multiproxy:
+	echo "$(ACTION)ing testcase $* (with run test) under chicken with -proxy"
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Clean
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile chicken_clean
+	rm -f *.scm
diff --git a/trunk/Examples/test-suite/chicken/README b/trunk/Examples/test-suite/chicken/README
new file mode 100644
index 0000000..ba32bb4
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/README
@@ -0,0 +1,11 @@
+See ../README for common README file.
+
+Any testcases which have _runme.ss appended after the testcase name will be detected and run.
+NOTE: I had to use _runme.ss becuase otherwise it would be hard to implement make clean
+Since when SWIG runs it generates an example.scm file for every test, to clean those files
+I needed to add a rm -f *.scm to make clean.  But we don't want the runme scripts to
+dissappear as well!
+
+Any testcases which have _runme_proxy.ss appended after the testcase name will be detected
+and run with the -proxy argument passed to SWIG.  SWIG will not be run with the -unhide-primitive
+option, so the _runme_proxy.ss file must use only the tinyclos exported interface.
diff --git a/trunk/Examples/test-suite/chicken/casts_runme.ss b/trunk/Examples/test-suite/chicken/casts_runme.ss
new file mode 100644
index 0000000..2eca461
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/casts_runme.ss
@@ -0,0 +1,2 @@
+(load "casts.so")
+(include "../schemerunme/casts.scm")
diff --git a/trunk/Examples/test-suite/chicken/char_constant_runme.ss b/trunk/Examples/test-suite/chicken/char_constant_runme.ss
new file mode 100644
index 0000000..50dff30
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/char_constant_runme.ss
@@ -0,0 +1,2 @@
+(load "char_constant.so")
+(include "../schemerunme/char_constant.scm")
diff --git a/trunk/Examples/test-suite/chicken/class_ignore_runme.ss b/trunk/Examples/test-suite/chicken/class_ignore_runme.ss
new file mode 100644
index 0000000..ba84810
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/class_ignore_runme.ss
@@ -0,0 +1,2 @@
+(load "class_ignore.so")
+(include "../schemerunme/class_ignore.scm")
diff --git a/trunk/Examples/test-suite/chicken/clientdata_prop_runme_proxy.ss b/trunk/Examples/test-suite/chicken/clientdata_prop_runme_proxy.ss
new file mode 100644
index 0000000..62f2c20
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/clientdata_prop_runme_proxy.ss
@@ -0,0 +1,95 @@
+(require 'clientdata_prop_a)
+(require 'clientdata_prop_b)
+
+(define a (make <A>))
+(test-A a)
+(test-tA a)
+(test-t2A a)
+(test-t3A a)
+(fA a)
+
+(define b (make <B>))
+(test-A b)
+(test-tA b)
+(test-t2A b)
+(test-t3A b)
+(test-B b)
+(fA b)
+(fB b)
+
+(define c (make <C>))
+(test-A c)
+(test-tA c)
+(test-t2A c)
+(test-t3A c)
+(test-C c)
+(fA c)
+(fC c)
+
+(define d (make <D>))
+(test-A d)
+(test-tA d)
+(test-t2A d)
+(test-t3A d)
+(test-D d)
+(test-tD d)
+(test-t2D d)
+(fA d)
+(fD d)
+
+;; here are the real tests... if the clientdata is correctly
+;; propegated, new-tA, new-t2A, should all return wrapped proxy's
+;; of class <A>
+
+(define a2 (new-tA))
+(if (not (eq? (class-of a2) <A>))
+  (error "Error 1"))
+(test-A a2)
+(test-tA a2)
+(test-t2A a2)
+(test-t3A a2)
+(fA a2)
+
+(define a3 (new-t2A))
+(if (not (eq? (class-of a3) <A>))
+  (error "Error 2"))
+(test-A a3)
+(test-tA a3)
+(test-t2A a3)
+(test-t3A a3)
+(fA a3)
+
+(define a4 (new-t3A))
+(if (not (eq? (class-of a4) <A>))
+  (error "Error 3"))
+(test-A a4)
+(test-tA a4)
+(test-t2A a4)
+(test-t3A a4)
+(fA a4)
+
+(define d2 (new-tD))
+(if (not (eq? (class-of d2) <D>))
+  (error "Error 4"))
+(test-A d2)
+(test-tA d2)
+(test-t2A d2)
+(test-t3A d2)
+(test-D d2)
+(test-tD d2)
+(fA d2)
+(fD d2)
+
+(define d3 (new-t2D))
+(if (not (eq? (class-of d3) <D>))
+  (error "Error 5"))
+(test-A d3)
+(test-tA d3)
+(test-t2A d3)
+(test-t3A d3)
+(test-D d3)
+(test-tD d3)
+(fA d3)
+(fD d3)
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/constover_runme.ss b/trunk/Examples/test-suite/chicken/constover_runme.ss
new file mode 100644
index 0000000..eb39c7f
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/constover_runme.ss
@@ -0,0 +1,2 @@
+(load "constover.so")
+(include "../schemerunme/constover.scm")
diff --git a/trunk/Examples/test-suite/chicken/contract_runme.ss b/trunk/Examples/test-suite/chicken/contract_runme.ss
new file mode 100644
index 0000000..006bcfd
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/contract_runme.ss
@@ -0,0 +1,3 @@
+(load "contract.so")
+(include "testsuite.ss")
+(include "../schemerunme/contract.scm")
diff --git a/trunk/Examples/test-suite/chicken/cpp_basic_runme_proxy.ss b/trunk/Examples/test-suite/chicken/cpp_basic_runme_proxy.ss
new file mode 100644
index 0000000..7b0b6d7
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/cpp_basic_runme_proxy.ss
@@ -0,0 +1,64 @@
+(require 'cpp_basic)
+
+(define-macro (check test)
+  `(if (not ,test) (error "Error in test " ',test)))
+
+(define f (make <Foo> 4))
+(check (= (slot-ref f 'num) 4))
+(slot-set! f 'num -17)
+(check (= (slot-ref f 'num) -17))
+
+(define b (make <Bar>))
+
+(slot-set! b 'fptr f)
+(check (= (slot-ref (slot-ref b 'fptr) 'num) -17))
+(check (= (test b -3 (slot-ref b 'fptr)) -5))
+(slot-set! f 'num 12)
+(check (= (slot-ref (slot-ref b 'fptr) 'num) 12))
+
+(check (= (slot-ref (slot-ref b 'fref) 'num) -4))
+(check (= (test b 12 (slot-ref b 'fref)) 23))
+;; references don't take ownership, so if we didn't define this here it might get garbage collected
+(define f2 (make <Foo> 23))
+(slot-set! b 'fref f2)
+(check (= (slot-ref (slot-ref b 'fref) 'num) 23))
+(check (= (test b -3 (slot-ref b 'fref)) 35))
+
+(check (= (slot-ref (slot-ref b 'fval) 'num) 15))
+(check (= (test b 3 (slot-ref b 'fval)) 33))
+(slot-set! b 'fval (make <Foo> -15))
+(check (= (slot-ref (slot-ref b 'fval) 'num) -15))
+(check (= (test b 3 (slot-ref b 'fval)) -27))
+
+(define f3 (testFoo b 12 (slot-ref b 'fref)))
+(check (= (slot-ref f3 'num) 32))
+
+;; now test global
+(define f4 (make <Foo> 6))
+(Bar-global-fptr f4)
+(check (= (slot-ref (Bar-global-fptr) 'num) 6))
+(slot-set! f4 'num 8)
+(check (= (slot-ref (Bar-global-fptr) 'num) 8))
+
+(check (= (slot-ref (Bar-global-fref) 'num) 23))
+(Bar-global-fref (make <Foo> -7))
+(check (= (slot-ref (Bar-global-fref) 'num) -7))
+
+(check (= (slot-ref (Bar-global-fval) 'num) 3))
+(Bar-global-fval (make <Foo> -34))
+(check (= (slot-ref (Bar-global-fval) 'num) -34))
+
+;; Now test function pointers
+(define func1ptr (get-func1-ptr))
+(define func2ptr (get-func2-ptr))
+
+(slot-set! f 'num 4)
+(check (= (func1 f 2) 16))
+(check (= (func2 f 2) -8))
+
+(slot-set! f 'func-ptr func1ptr)
+(check (= (test-func-ptr f 2) 16))
+(slot-set! f 'func-ptr func2ptr)
+(check (= (test-func-ptr f 2) -8))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/cpp_enum_runme.ss b/trunk/Examples/test-suite/chicken/cpp_enum_runme.ss
new file mode 100644
index 0000000..4d4ec76
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/cpp_enum_runme.ss
@@ -0,0 +1,2 @@
+(load "cpp_enum.so")
+(include "../schemerunme/cpp_enum.scm")
diff --git a/trunk/Examples/test-suite/chicken/cpp_namespace_runme.ss b/trunk/Examples/test-suite/chicken/cpp_namespace_runme.ss
new file mode 100644
index 0000000..800172e
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/cpp_namespace_runme.ss
@@ -0,0 +1,2 @@
+(load "cpp_namespace.so")
+(include "../schemerunme/cpp_namespace.scm")
diff --git a/trunk/Examples/test-suite/chicken/dynamic_cast_runme.ss b/trunk/Examples/test-suite/chicken/dynamic_cast_runme.ss
new file mode 100644
index 0000000..1e81d55
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/dynamic_cast_runme.ss
@@ -0,0 +1,2 @@
+(load "dynamic_cast.so")
+(include "../schemerunme/dynamic_cast.scm")
diff --git a/trunk/Examples/test-suite/chicken/ext_test.i b/trunk/Examples/test-suite/chicken/ext_test.i
new file mode 100644
index 0000000..e8f5930
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/ext_test.i
@@ -0,0 +1,21 @@
+%module ext_test
+
+/* just use the imports_a.h header... for this test we only need a class */
+%{
+#include "imports_a.h"
+%}
+
+%include "imports_a.h"
+
+%{
+void test_create(C_word,C_word,C_word) C_noret;
+%}
+
+%init %{
+ {
+    C_word *space = C_alloc(2 + C_SIZEOF_INTERNED_SYMBOL(11));
+    sym = C_intern (&space, 11, "test-create");
+    C_mutate ((C_word*)sym+1, (*space=C_CLOSURE_TYPE|1, space[1]=(C_word)test_create, tmp=(C_word)space, space+=2, tmp));
+ }
+%}
+
diff --git a/trunk/Examples/test-suite/chicken/ext_test_external.cxx b/trunk/Examples/test-suite/chicken/ext_test_external.cxx
new file mode 100644
index 0000000..338151e
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/ext_test_external.cxx
@@ -0,0 +1,22 @@
+#include <ext_test_wrap_hdr.h>
+#include <imports_a.h>
+
+void test_create(C_word,C_word,C_word) C_noret;
+void test_create(C_word argc, C_word closure, C_word continuation) {
+  C_word resultobj;
+  swig_type_info *type;
+  A *newobj;
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  
+  C_trace("test-create");
+  if (argc!=2) C_bad_argc(argc,2);
+
+
+  newobj = new A();
+  
+  type = SWIG_TypeQuery("A *");
+  resultobj = SWIG_NewPointerObj(newobj, type, 1);
+
+  C_kontinue(continuation, resultobj);
+}
+
diff --git a/trunk/Examples/test-suite/chicken/ext_test_runme.ss b/trunk/Examples/test-suite/chicken/ext_test_runme.ss
new file mode 100644
index 0000000..ea3eaa4
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/ext_test_runme.ss
@@ -0,0 +1,5 @@
+(load "ext_test.so")
+
+(define a (test-create))
+
+(A-hello a)
diff --git a/trunk/Examples/test-suite/chicken/global_vars_runme.ss b/trunk/Examples/test-suite/chicken/global_vars_runme.ss
new file mode 100644
index 0000000..802205b
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/global_vars_runme.ss
@@ -0,0 +1,2 @@
+(require 'global_vars)
+(load "../schemerunme/global_vars.scm")
diff --git a/trunk/Examples/test-suite/chicken/global_vars_runme_proxy.ss b/trunk/Examples/test-suite/chicken/global_vars_runme_proxy.ss
new file mode 100644
index 0000000..3c4500d
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/global_vars_runme_proxy.ss
@@ -0,0 +1,2 @@
+(require 'global_vars)
+(load "../schemerunme/global_vars_proxy.scm")
diff --git a/trunk/Examples/test-suite/chicken/import_nomodule_runme.ss b/trunk/Examples/test-suite/chicken/import_nomodule_runme.ss
new file mode 100644
index 0000000..7e64053
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/import_nomodule_runme.ss
@@ -0,0 +1,2 @@
+(load "import_nomodule.so")
+(include "../schemerunme/import_nomodule.scm")
diff --git a/trunk/Examples/test-suite/chicken/imports_runme.ss b/trunk/Examples/test-suite/chicken/imports_runme.ss
new file mode 100644
index 0000000..ac5fb98
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/imports_runme.ss
@@ -0,0 +1,3 @@
+(load "imports_a.so")
+(load "imports_b.so")
+(include "../schemerunme/imports.scm")
diff --git a/trunk/Examples/test-suite/chicken/inherit_missing_runme.ss b/trunk/Examples/test-suite/chicken/inherit_missing_runme.ss
new file mode 100644
index 0000000..50a084a
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/inherit_missing_runme.ss
@@ -0,0 +1,2 @@
+(load "inherit_missing.so")
+(include "../schemerunme/inherit_missing.scm")
diff --git a/trunk/Examples/test-suite/chicken/li_std_string_runme.ss b/trunk/Examples/test-suite/chicken/li_std_string_runme.ss
new file mode 100644
index 0000000..cc64287
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/li_std_string_runme.ss
@@ -0,0 +1,2 @@
+(load "li_std_string.so")
+(include "../schemerunme/li_std_string.scm")
diff --git a/trunk/Examples/test-suite/chicken/li_std_string_runme_proxy.ss b/trunk/Examples/test-suite/chicken/li_std_string_runme_proxy.ss
new file mode 100644
index 0000000..e1e2409
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/li_std_string_runme_proxy.ss
@@ -0,0 +1,47 @@
+(load "li_std_string.so")
+
+(define x "hello")
+
+(if (not (string=? (test-value x) x))
+  (begin (error "Error 1") (exit 1)))
+
+(if (not (string=? (test-const-reference x) x))
+  (begin (error "Error 2") (exit 1)))
+
+(define y (test-pointer-out))
+(test-pointer y)
+(define z (test-const-pointer-out))
+(test-const-pointer z)
+
+(define a (test-reference-out))
+(test-reference a)
+
+;; test global variables
+(GlobalString "whee")
+(if (not (string=? (GlobalString) "whee"))
+  (error "Error 3"))
+(if (not (string=? (GlobalString2) "global string 2"))
+  (error "Error 4"))
+
+(define struct (make <Structure>))
+
+;; MemberString should be a wrapped class
+(if (not (string=? (slot-ref struct 'MemberString) ""))
+  (error "Error 4.5"))
+;(slot-set! (slot-ref struct 'MemberString) "and how")
+;;(if (not (string=? (slot-ref struct 'MemberString) "and how"))
+;;  (error "Error 5"))
+(if (not (string=? (slot-ref struct 'MemberString2) "member string 2"))
+  (error "Error 6"))
+(Structure-StaticMemberString "static str")
+(if (not (string=? (Structure-StaticMemberString) "static str"))
+  (error "Error 7"))
+(if (not (string=? (Structure-StaticMemberString2) "static member string 2"))
+  (error "Error 8"))
+
+;(if (not (string=? (Structure-ConstMemberString-get struct) "const member string"))
+;  (error "Error 9"))
+(if (not (string=? (Structure-ConstStaticMemberString) "const static member string"))
+  (error "Error 10"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/li_typemaps_runme.ss b/trunk/Examples/test-suite/chicken/li_typemaps_runme.ss
new file mode 100644
index 0000000..1ad6e92
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/li_typemaps_runme.ss
@@ -0,0 +1,12 @@
+(require 'li_typemaps)
+(load "../schemerunme/li_typemaps.scm")
+
+(call-with-values (lambda () (inoutr-int2 3 -2))
+		  (lambda (a b)
+		    (if (not (and (= a 3) (= b -2)))
+		      (error "Error in inoutr-int2"))))
+(call-with-values (lambda () (out-foo 4))
+		  (lambda (a b)
+		    (if (not (and (= (Foo-a-get a) 4) (= b 8)))
+		      (error "Error in out-foo"))))
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/li_typemaps_runme_proxy.ss b/trunk/Examples/test-suite/chicken/li_typemaps_runme_proxy.ss
new file mode 100644
index 0000000..52997c6
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/li_typemaps_runme_proxy.ss
@@ -0,0 +1,13 @@
+(require 'li_typemaps)
+(load "../schemerunme/li_typemaps_proxy.scm")
+
+(call-with-values (lambda () (inoutr-int2 3 -2))
+		  (lambda (a b)
+		    (if (not (and (= a 3) (= b -2)))
+		      (error "Error in inoutr-int2"))))
+(call-with-values (lambda () (out-foo 4))
+		  (lambda (a b)
+		    (if (not (and (= (slot-ref a 'a) 4) (= b 8)))
+		      (error "Error in out-foo"))))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/list_vector_runme.ss b/trunk/Examples/test-suite/chicken/list_vector_runme.ss
new file mode 100644
index 0000000..67d52f6
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/list_vector_runme.ss
@@ -0,0 +1,2 @@
+(load "list_vector.so")
+(include "../schemerunme/list_vector.scm")
diff --git a/trunk/Examples/test-suite/chicken/member_pointer_runme.ss b/trunk/Examples/test-suite/chicken/member_pointer_runme.ss
new file mode 100644
index 0000000..f2226b2
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/member_pointer_runme.ss
@@ -0,0 +1,28 @@
+(require 'member_pointer)
+
+(define (check-eq? msg expected actual)
+  (if (not (= expected actual))
+    (error "Error " msg ": expected " expected " got " actual)))
+
+(define area-pt (areapt))
+(define perim-pt (perimeterpt))
+
+(define s (new-Square 10))
+
+(check-eq? "Square area" 100.0 (do-op s area-pt))
+(check-eq? "Square perim" 40.0 (do-op s perim-pt))
+
+(check-eq? "Square area" 100.0 (do-op s (areavar)))
+(check-eq? "Square perim" 40.0 (do-op s (perimetervar)))
+
+;; Set areavar to return value of function
+(areavar perim-pt)
+(check-eq? "Square perim" 40 (do-op s (areavar)))
+
+(check-eq? "Square area" 100.0 (do-op s (AREAPT)))
+(check-eq? "Square perim" 40.0 (do-op s (PERIMPT)))
+
+(define test (NULLPT))
+
+(perimetervar (AREAPT))
+(check-eq? "Square area" 100.0 (do-op s (perimetervar)))
diff --git a/trunk/Examples/test-suite/chicken/multiple_inheritance_runme_proxy.ss b/trunk/Examples/test-suite/chicken/multiple_inheritance_runme_proxy.ss
new file mode 100644
index 0000000..313157c
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/multiple_inheritance_runme_proxy.ss
@@ -0,0 +1,2 @@
+(require 'multiple_inheritance)
+(load "../schemerunme/multiple_inheritance_proxy.scm")
diff --git a/trunk/Examples/test-suite/chicken/multivalue_runme.ss b/trunk/Examples/test-suite/chicken/multivalue_runme.ss
new file mode 100644
index 0000000..f5aafcb
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/multivalue_runme.ss
@@ -0,0 +1,4 @@
+;; this doesn't work yet :(
+(load "multivalue.so")
+(include "../schemerunme/multivalue.scm")
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/name_runme.ss b/trunk/Examples/test-suite/chicken/name_runme.ss
new file mode 100644
index 0000000..938915d
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/name_runme.ss
@@ -0,0 +1,2 @@
+(load "name.so")
+(include "../schemerunme/name.scm")
diff --git a/trunk/Examples/test-suite/chicken/newobject1_runme_proxy.ss b/trunk/Examples/test-suite/chicken/newobject1_runme_proxy.ss
new file mode 100644
index 0000000..7bc5a24
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/newobject1_runme_proxy.ss
@@ -0,0 +1,30 @@
+(require 'newobject1)
+
+(define-macro (check-count val)
+  `(if (not (= (Foo-fooCount) ,val)) (error "Error checking val " ,val " != " ,(Foo-fooCount))))
+
+(define f (Foo-makeFoo))
+
+(check-count 1)
+
+(define f2 (makeMore f))
+
+(check-count 2)
+
+(set! f #f)
+(gc #t)
+
+(check-count 1)
+
+(define f3 (makeMore f2))
+
+(check-count 2)
+
+(set! f3 #f)
+(set! f2 #f)
+
+(gc #t)
+
+(check-count 0)
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/newobject2_runme.ss b/trunk/Examples/test-suite/chicken/newobject2_runme.ss
new file mode 100644
index 0000000..cc445f4
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/newobject2_runme.ss
@@ -0,0 +1,29 @@
+(load "newobject2.so")
+
+(define f (new-Foo))
+
+(Foo-dummy-set f 14)
+(if (not (= (Foo-dummy-get f) 14))
+  (error "Bad dummy value"))
+
+(if (not (= (fooCount) 0))
+  (error "Bad foo count 1"))
+
+(define f2 (makeFoo))
+
+(if (not (= (fooCount) 1))
+  (error "Bad foo count 2"))
+
+(Foo-dummy-set f2 16)
+(if (not (= (Foo-dummy-get f2) 16))
+  (error "Bad dummy value for f2"))
+
+(set! f #f)
+(set! f2 #f)
+
+(gc #t)
+
+(if (not (= (fooCount) -1))
+  (error "Bad foo count 3"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/newobject2_runme_proxy.ss b/trunk/Examples/test-suite/chicken/newobject2_runme_proxy.ss
new file mode 100644
index 0000000..36b8cda
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/newobject2_runme_proxy.ss
@@ -0,0 +1,29 @@
+(load "newobject2.so")
+
+(define f (make <Foo>))
+
+(slot-set! f 'dummy 14)
+(if (not (= (slot-ref f 'dummy) 14))
+  (error "Bad dummy value"))
+
+(if (not (= (fooCount) 0))
+  (error "Bad foo count 1"))
+
+(define f2 (makeFoo))
+
+(if (not (= (fooCount) 1))
+  (error "Bad foo count 2"))
+
+(slot-set! f2 'dummy 16)
+(if (not (= (slot-ref f2 'dummy) 16))
+  (error "Bad dummy value for f2"))
+
+(set! f #f)
+(set! f2 #f)
+
+(gc #t)
+
+(if (not (= (fooCount) -1))
+  (error "Bad foo count 3"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/overload_complicated_runme.ss b/trunk/Examples/test-suite/chicken/overload_complicated_runme.ss
new file mode 100644
index 0000000..f89f70b
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_complicated_runme.ss
@@ -0,0 +1,2 @@
+(load "overload_complicated.so")
+(include "../schemerunme/overload_complicated.scm")
diff --git a/trunk/Examples/test-suite/chicken/overload_copy_runme.ss b/trunk/Examples/test-suite/chicken/overload_copy_runme.ss
new file mode 100644
index 0000000..4ec5422
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_copy_runme.ss
@@ -0,0 +1,2 @@
+(load "overload_copy.so")
+(include "../schemerunme/overload_copy.scm")
diff --git a/trunk/Examples/test-suite/chicken/overload_copy_runme_proxy.ss b/trunk/Examples/test-suite/chicken/overload_copy_runme_proxy.ss
new file mode 100644
index 0000000..5f48080
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_copy_runme_proxy.ss
@@ -0,0 +1,6 @@
+(load "./overload_copy.so")
+
+(define f (make <Foo>))
+(define g (make <Foo> f))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/overload_extend_runme.ss b/trunk/Examples/test-suite/chicken/overload_extend_runme.ss
new file mode 100644
index 0000000..a19cb29
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_extend_runme.ss
@@ -0,0 +1,2 @@
+(load "overload_extend.so")
+(include "../schemerunme/overload_extend.scm")
diff --git a/trunk/Examples/test-suite/chicken/overload_extend_runme_proxy.ss b/trunk/Examples/test-suite/chicken/overload_extend_runme_proxy.ss
new file mode 100644
index 0000000..2a6867e
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_extend_runme_proxy.ss
@@ -0,0 +1,14 @@
+(load "./overload_extend.so")
+
+(define f (make <Foo>))
+
+(if (not (= (test f 3) 1))
+  (error "test integer bad"))
+
+(if (not (= (test f "hello") 2))
+  (error "test string bad"))
+
+(if (not (= (test f 3.5 2.5) 6.0))
+  (error "test reals bad"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/overload_simple_runme.ss b/trunk/Examples/test-suite/chicken/overload_simple_runme.ss
new file mode 100644
index 0000000..24fa67a
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_simple_runme.ss
@@ -0,0 +1,2 @@
+(load "overload_simple.so")
+(include "../schemerunme/overload_simple.scm")
diff --git a/trunk/Examples/test-suite/chicken/overload_simple_runme_proxy.ss b/trunk/Examples/test-suite/chicken/overload_simple_runme_proxy.ss
new file mode 100644
index 0000000..0ae3e62
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_simple_runme_proxy.ss
@@ -0,0 +1,56 @@
+(load "overload_simple.so")
+
+(define-macro (check test)
+  `(if (not ,test) (error ',test)))
+
+(check (string=? (foo) "foo:"))
+(check (string=? (foo 3) "foo:int"))
+(check (string=? (foo 3.01) "foo:double"))
+(check (string=? (foo "hey") "foo:char *"))
+
+(define f (make <Foo>))
+(define b (make <Bar>))
+(define b2 (make <Bar> 3))
+
+(check (= (slot-ref b 'num) 0))
+(check (= (slot-ref b2 'num) 3))
+
+(check (string=? (foo f) "foo:Foo *"))
+(check (string=? (foo b) "foo:Bar *"))
+(check (string=? (foo f 3) "foo:Foo *,int"))
+(check (string=? (foo 3.2 b) "foo:double,Bar *"))
+
+;; now check blah
+(check (string=? (blah 2.01) "blah:double"))
+(check (string=? (blah "hey") "blah:char *"))
+
+;; now check spam member functions
+(define s (make <Spam>))
+(define s2 (make <Spam> 3))
+(define s3 (make <Spam> 3.2))
+(define s4 (make <Spam> "whee"))
+(define s5 (make <Spam> f))
+(define s6 (make <Spam> b))
+
+(check (string=? (slot-ref s 'type) "none"))
+(check (string=? (slot-ref s2 'type) "int"))
+(check (string=? (slot-ref s3 'type) "double"))
+(check (string=? (slot-ref s4 'type) "char *"))
+(check (string=? (slot-ref s5 'type) "Foo *"))
+(check (string=? (slot-ref s6 'type) "Bar *"))
+
+;; now check Spam member functions
+(check (string=? (foo s 2) "foo:int"))
+(check (string=? (foo s 2.1) "foo:double"))
+(check (string=? (foo s "hey") "foo:char *"))
+(check (string=? (foo s f) "foo:Foo *"))
+(check (string=? (foo s b) "foo:Bar *"))
+
+;; check static member funcs
+(check (string=? (Spam-bar 3) "bar:int"))
+(check (string=? (Spam-bar 3.2) "bar:double"))
+(check (string=? (Spam-bar "hey") "bar:char *"))
+(check (string=? (Spam-bar f) "bar:Foo *"))
+(check (string=? (Spam-bar b) "bar:Bar *"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/overload_subtype_runme.ss b/trunk/Examples/test-suite/chicken/overload_subtype_runme.ss
new file mode 100644
index 0000000..b3663b7
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_subtype_runme.ss
@@ -0,0 +1,2 @@
+(load "overload_subtype.so")
+(include "../schemerunme/overload_subtype.scm")
diff --git a/trunk/Examples/test-suite/chicken/overload_subtype_runme_proxy.ss b/trunk/Examples/test-suite/chicken/overload_subtype_runme_proxy.ss
new file mode 100644
index 0000000..d83d59a
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/overload_subtype_runme_proxy.ss
@@ -0,0 +1,12 @@
+(load "./overload_subtype.so")
+
+(define f (make <Foo>))
+(define b (make <Bar>))
+
+(if (not (= (spam f) 1))
+  (error "Error in foo"))
+
+(if (not (= (spam b) 2))
+  (error "Error in bar"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/pointer_in_out_runme.ss b/trunk/Examples/test-suite/chicken/pointer_in_out_runme.ss
new file mode 100644
index 0000000..807c4eb
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/pointer_in_out_runme.ss
@@ -0,0 +1,2 @@
+(load "pointer_in_out.so")
+(include "../schemerunme/pointer_in_out.scm")
diff --git a/trunk/Examples/test-suite/chicken/reference_global_vars_runme.ss b/trunk/Examples/test-suite/chicken/reference_global_vars_runme.ss
new file mode 100644
index 0000000..1e1914b
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/reference_global_vars_runme.ss
@@ -0,0 +1,2 @@
+(load "reference_global_vars.so")
+(include "../schemerunme/reference_global_vars.scm")
diff --git a/trunk/Examples/test-suite/chicken/testsuite.ss b/trunk/Examples/test-suite/chicken/testsuite.ss
new file mode 100644
index 0000000..e1152a6
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/testsuite.ss
@@ -0,0 +1,12 @@
+(define (lookup-ext-tag tag)
+  (cond
+    ((equal? tag '(quote swig-contract-assertion-failed))
+      '( ((exn type) #f)) )
+    (#t '())))
+
+(define-macro (expect-throw tag-form form)
+  `(if (condition-case (begin ,form #t)
+         ,@(lookup-ext-tag tag-form)
+         ((exn) (print "The form threw a different error than expected: " ',form) (exit 1))
+         (var () (print "The form did not error as expected: " ',form) (exit 1)))
+   (begin (print "The form returned normally when it was expected to throw an error: " ',form) (exit 1))))
diff --git a/trunk/Examples/test-suite/chicken/throw_exception_runme.ss b/trunk/Examples/test-suite/chicken/throw_exception_runme.ss
new file mode 100644
index 0000000..62bc7be
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/throw_exception_runme.ss
@@ -0,0 +1,29 @@
+(load "throw_exception.so")
+
+(define-macro (check-throw expr check)
+ `(if (handle-exceptions exvar (if ,check #f (begin (print "Error executing: " ',expr " " exvar) (exit 1))) ,expr #t)
+    (print "Expression did not throw an error: " ',expr)))
+
+(define f (new-Foo))
+
+(check-throw (Foo-test-int f) (= exvar 37))
+(check-throw (Foo-test-msg f) (string=? exvar "Dead"))
+(check-throw (Foo-test-cls f) (test-is-Error exvar))
+(check-throw (Foo-test-cls-ptr f) (test-is-Error exvar))
+(check-throw (Foo-test-cls-ref f) (test-is-Error exvar))
+(check-throw (Foo-test-cls-td f) (test-is-Error exvar))
+(check-throw (Foo-test-cls-ptr-td f) (test-is-Error exvar))
+(check-throw (Foo-test-cls-ref-td f) (test-is-Error exvar))
+(check-throw (Foo-test-enum f) (= exvar (enum2)))
+
+; don't know how to test this... it is returning a SWIG wrapped int *
+;(check-throw (Foo-test-array f) (equal? exvar '(0 1 2 3 4 5 6 7 8 9)))
+
+(check-throw (Foo-test-multi f 1) (= exvar 37))
+(check-throw (Foo-test-multi f 2) (string=? exvar "Dead"))
+(check-throw (Foo-test-multi f 3) (test-is-Error exvar))
+
+(set! f #f)
+(gc #t)
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/chicken/typedef_inherit_runme.ss b/trunk/Examples/test-suite/chicken/typedef_inherit_runme.ss
new file mode 100644
index 0000000..111296d
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/typedef_inherit_runme.ss
@@ -0,0 +1,2 @@
+(load "typedef_inherit.so")
+(include "../schemerunme/typedef_inherit.scm")
diff --git a/trunk/Examples/test-suite/chicken/typename_runme.ss b/trunk/Examples/test-suite/chicken/typename_runme.ss
new file mode 100644
index 0000000..60fc320
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/typename_runme.ss
@@ -0,0 +1,2 @@
+(load "typename.so")
+(include "../schemerunme/typename.scm")
diff --git a/trunk/Examples/test-suite/chicken/unions_runme.ss b/trunk/Examples/test-suite/chicken/unions_runme.ss
new file mode 100644
index 0000000..465784a
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/unions_runme.ss
@@ -0,0 +1,2 @@
+(load "unions.so")
+(include "../schemerunme/unions.scm")
diff --git a/trunk/Examples/test-suite/chicken/unions_runme_proxy.ss b/trunk/Examples/test-suite/chicken/unions_runme_proxy.ss
new file mode 100644
index 0000000..4dd1414
--- /dev/null
+++ b/trunk/Examples/test-suite/chicken/unions_runme_proxy.ss
@@ -0,0 +1,2 @@
+(load "unions.so")
+(include "../schemerunme/unions_proxy.scm")
diff --git a/trunk/Examples/test-suite/class_ignore.i b/trunk/Examples/test-suite/class_ignore.i
new file mode 100644
index 0000000..c0b954c
--- /dev/null
+++ b/trunk/Examples/test-suite/class_ignore.i
@@ -0,0 +1,47 @@
+%module class_ignore
+
+%ignore Foo;
+%ignore *::Bar::foo;
+%ignore Far::away() const;
+
+%inline %{
+  class Foo {
+  public:
+    virtual ~Foo() { }
+    virtual char *blah() = 0;
+  };
+  
+  namespace hi 
+  {
+    namespace hello
+    {
+      class Bar : public Foo {
+      public:
+	void foo(void) {};
+	
+	virtual char *blah() { return (char *) "Bar::blah"; }
+      };
+
+    }
+  }
+
+  struct Boo {
+    virtual ~Boo() {}
+    virtual void away() const {}
+  };
+  struct Far : Boo {
+    virtual void away() const {}
+  };
+  struct Hoo : Far {
+    virtual void away() const {}
+  };
+
+  char *do_blah(Foo *f) {
+    return f->blah();
+  }
+
+  class ForwardClass;  
+  template <class C> class ForwardClassT;  
+  template<typename T1, typename T2> class PatchList;
+%}
+
diff --git a/trunk/Examples/test-suite/class_scope_weird.i b/trunk/Examples/test-suite/class_scope_weird.i
new file mode 100644
index 0000000..cc55dc8
--- /dev/null
+++ b/trunk/Examples/test-suite/class_scope_weird.i
@@ -0,0 +1,50 @@
+%module class_scope_weird
+
+// Use this version with extra qualifiers to test SWIG as some compilers accept this
+class Foo {
+public:
+  Foo::Foo(void) {}
+  Foo::Foo(int) {}
+  int Foo::bar(int x) {
+    return x;
+  }
+};
+
+// Remove extra qualifiers for the compiler as some compilers won't compile the extra qaulification (eg gcc-4.1 onwards) 
+%{
+class Foo {
+public:
+  Foo(void) {}
+  Foo(int) {}
+  int bar(int x) {
+    return x;
+  }
+};
+%}
+
+%inline %{
+class Quat;
+class matrix4;
+class tacka3;
+%}
+
+// Use this version with extra qualifiers to test SWIG as some compilers accept this
+class Quat {
+public:
+  Quat::Quat(void){}  
+  Quat::Quat(float in_w, float x, float y, float z){}
+  Quat::Quat(const tacka3& axis, float angle){}
+  Quat::Quat(const matrix4& m){}
+};
+
+// Remove extra qualifiers for the compiler as some compilers won't compile the extra qaulification (eg gcc-4.1 onwards) 
+%{
+class Quat {
+public:
+  Quat(void){}  
+  Quat(float in_w, float x, float y, float z){}
+  Quat(const tacka3& axis, float angle){}
+  Quat(const matrix4& m){}
+};
+%}
+
diff --git a/trunk/Examples/test-suite/clientdata_prop.list b/trunk/Examples/test-suite/clientdata_prop.list
new file mode 100644
index 0000000..5e41f6d
--- /dev/null
+++ b/trunk/Examples/test-suite/clientdata_prop.list
@@ -0,0 +1,2 @@
+clientdata_prop_a
+clientdata_prop_b
diff --git a/trunk/Examples/test-suite/clientdata_prop_a.h b/trunk/Examples/test-suite/clientdata_prop_a.h
new file mode 100644
index 0000000..5f82e98
--- /dev/null
+++ b/trunk/Examples/test-suite/clientdata_prop_a.h
@@ -0,0 +1,12 @@
+
+class A {
+  public:
+    void fA() {}
+};
+
+typedef A tA;
+
+void test_A(A *a) {}
+void test_tA(tA *a) {}
+
+tA *new_tA() { return new tA(); }
diff --git a/trunk/Examples/test-suite/clientdata_prop_a.i b/trunk/Examples/test-suite/clientdata_prop_a.i
new file mode 100644
index 0000000..626f2a1
--- /dev/null
+++ b/trunk/Examples/test-suite/clientdata_prop_a.i
@@ -0,0 +1,12 @@
+/* This file tests the clientdata propagation at swig wrapper
+   generation.  It tests a bug in the TCL module where the
+   clientdata was not propagated correctly to all classes */
+
+%module clientdata_prop_a
+%{
+  #include "clientdata_prop_a.h"
+%}
+
+%include "clientdata_prop_a.h"
+
+%newobject new_tA;
diff --git a/trunk/Examples/test-suite/clientdata_prop_b.h b/trunk/Examples/test-suite/clientdata_prop_b.h
new file mode 100644
index 0000000..f8a709e
--- /dev/null
+++ b/trunk/Examples/test-suite/clientdata_prop_b.h
@@ -0,0 +1,38 @@
+#include "clientdata_prop_a.h"
+
+typedef tA t2A;
+typedef A t3A;
+
+class B : public A
+{
+  public:
+    void fB() {}
+};
+
+class C : public tA
+{
+  public:
+    void fC() {}
+};
+
+class D : public t2A
+{
+  public:
+    void fD() {}
+};
+
+typedef D tD;
+typedef tD t2D;
+
+void test_t2A(t2A *a) {}
+void test_t3A(t3A *a) {}
+void test_B(B *b) {}
+void test_C(C *c) {}
+void test_D(D *d) {}
+void test_tD(tD *d) {}
+void test_t2D(t2D *d) {}
+
+t2A *new_t2A() { return new t2A(); }
+t3A *new_t3A() { return new t3A(); }
+tD * new_tD () { return new tD (); }
+t2D *new_t2D() { return new t2D(); }
diff --git a/trunk/Examples/test-suite/clientdata_prop_b.i b/trunk/Examples/test-suite/clientdata_prop_b.i
new file mode 100644
index 0000000..709c1a2
--- /dev/null
+++ b/trunk/Examples/test-suite/clientdata_prop_b.i
@@ -0,0 +1,20 @@
+/* This file tests the clientdata propagation at swig wrapper
+   generation.  It tests a bug in the TCL module where the
+   clientdata was not propagated correctly to all classes */
+
+%module clientdata_prop_b
+
+%{
+#include "clientdata_prop_b.h"
+%}
+
+%import "clientdata_prop_a.i"
+
+%include "clientdata_prop_b.h"
+
+%types(tA *);
+
+%newobject new_t2A;
+%newobject new_t3A;
+%newobject new_tD;
+%newobject new_t2D;
diff --git a/trunk/Examples/test-suite/clisp/Makefile.in b/trunk/Examples/test-suite/clisp/Makefile.in
new file mode 100644
index 0000000..279ab97
--- /dev/null
+++ b/trunk/Examples/test-suite/clisp/Makefile.in
@@ -0,0 +1,47 @@
+#######################################################################
+# Makefile for clisp test-suite
+#######################################################################
+
+LANGUAGE     = clisp
+CLISP        = @CLISPBIN@
+SCRIPTSUFFIX = _runme.lisp
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+include $(srcdir)/../common.mk
+
+# no C++ tests for now
+CPP_TEST_CASES =
+#C_TEST_CASES += 
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.lisp appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CLISPBIN) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: (does nothing, we dont generate extra clisp code)
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile clisp_clean
+
diff --git a/trunk/Examples/test-suite/common.mk b/trunk/Examples/test-suite/common.mk
new file mode 100644
index 0000000..0a3a085
--- /dev/null
+++ b/trunk/Examples/test-suite/common.mk
@@ -0,0 +1,542 @@
+#######################################################################
+# SWIG test suite makefile.
+# The test suite comprises many different test cases, which have
+# typically produced bugs in the past. The aim is to have the test 
+# cases compiling for every language modules. Some testcase have
+# a runtime test which is written in each of the module's language.
+#
+# This makefile runs SWIG on the testcases, compiles the c/c++ code
+# then builds the object code for use by the language.
+# To complete a test in a language follow these guidelines: 
+# 1) Add testcases to CPP_TEST_CASES (c++) or C_TEST_CASES (c) or
+#    MULTI_CPP_TEST_CASES (multi-module c++ tests)
+# 2) If not already done, create a makefile which:
+#    a) Defines LANGUAGE matching a language rule in Examples/Makefile, 
+#       for example LANGUAGE = java
+#    b) Define rules for %.ctest, %.cpptest, %.multicpptest and %.clean.
+#    c) Define srcdir, top_srcdir and top_builddir (these are the
+#       equivalent to configure's variables of the same name).
+# 3) One off special commandline options can be achieved by adding a
+#    test case to CUSTOM_TEST_CASES and defining rules to run and test.
+#
+# The 'check' target runs the testcases including SWIG invocation,
+# C/C++ compilation, target language compilation (if any) and runtime
+# test (if there is an associated 'runme' test).
+# The 'partialcheck' target only invokes SWIG.
+# The 'all' target is the same as the 'check' target but also includes
+# known broken testcases.
+# The 'clean' target cleans up.
+#
+# Note that the RUNTOOL, COMPILETOOL and SWIGTOOL variables can be used
+# for # invoking tools for the runtime tests and target language 
+# compiler (eg javac) respectively. For example, valgrind can be used 
+# for memory checking of the runtime tests using:
+#   make RUNTOOL="valgrind --leak-check-full"
+# and valgrind can be used when invoking SWIG using:
+#   make SWIGTOOL="valgrind --tool=memcheck"
+#
+# The variables below can be overridden after including this makefile
+#######################################################################
+
+#######################################################################
+# Variables
+#######################################################################
+
+ifneq (,$(USE_VALGRIND))
+VALGRIND_OPT = --leak-check=full
+RUNTOOL    = valgrind $(VALGRIND_OPT)
+else
+RUNTOOL    =
+endif
+COMPILETOOL=
+SWIGTOOL   =
+
+SWIG       = $(SWIGTOOL) $(top_builddir)/preinst-swig
+SWIG_LIB   = $(top_srcdir)/Lib
+TEST_SUITE = test-suite
+EXAMPLES   = Examples
+CXXSRCS    = 
+CSRCS      = 
+TARGETPREFIX = 
+TARGETSUFFIX = 
+SWIGOPT    = -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$(LANGUAGE) -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE) -DSWIG_NOEXTRA_QUALIFICATION
+INCLUDES   = -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$(LANGUAGE) -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)
+LIBS       = -L.
+LIBPREFIX  = lib
+ACTION     = check
+
+#
+# Please keep test cases in alphabetical order.
+# Note that any whitespace after the last entry in each list will break make
+#
+
+# Broken C++ test cases. (Can be run individually using make testcase.cpptest.)
+CPP_TEST_BROKEN += \
+	constants \
+	cpp_broken \
+	exception_partial_info \
+	extend_variable \
+	namespace_union \
+	nested_comment \
+	overload_complicated \
+	template_default_pointer \
+	template_expr
+
+
+# Broken C test cases. (Can be run individually using make testcase.ctest.)
+C_TEST_BROKEN += \
+	tag_no_clash_with_variable
+
+
+# C++ test cases. (Can be run individually using make testcase.cpptest.)
+CPP_TEST_CASES += \
+	abstract_access \
+	abstract_inherit \
+	abstract_inherit_ok \
+	abstract_signature \
+	abstract_typedef \
+	abstract_typedef2 \
+	abstract_virtual \
+	access_change \
+	add_link \
+	aggregate \
+	allowexcept \
+	allprotected \
+	anonymous_bitfield \
+	apply_signed_char \
+	apply_strings \
+	argout \
+	array_member \
+	array_typedef_memberin \
+	arrayref \
+	arrays_dimensionless \
+	arrays_global \
+	arrays_global_twodim \
+	arrays_scope \
+	bloody_hell \
+	bools \
+	cast_operator \
+	casts \
+	char_strings \
+	class_ignore \
+	class_scope_weird \
+	compactdefaultargs \
+	const_const_2 \
+	constant_pointers \
+	constover \
+	constructor_copy \
+	constructor_exception \
+	constructor_explicit \
+	constructor_ignore \
+	constructor_value \
+	contract \
+	conversion \
+	conversion_namespace \
+	conversion_ns_template \
+	cplusplus_throw \
+	cpp_basic \
+	cpp_enum \
+	cpp_namespace \
+	cpp_nodefault \
+	cpp_static \
+	cpp_typedef \
+	default_args \
+	default_constructor \
+	defvalue_constructor \
+	derived_byvalue \
+	derived_nested \
+	destructor_reprotected \
+	director_abstract \
+	director_basic \
+	director_classes \
+	director_classic \
+	director_constructor \
+	director_default \
+	director_detect \
+	director_enum \
+	director_exception \
+	director_extend \
+	director_finalizer \
+	director_frob \
+	director_ignore \
+	director_namespace_clash \
+	director_nested \
+	director_overload \
+	director_primitives \
+	director_protected \
+	director_redefined \
+	director_thread \
+	director_unroll \
+	director_using \
+	director_wombat \
+	disown \
+	dynamic_cast \
+	empty \
+	enum_scope_template \
+	enum_template \
+	enum_thorough \
+	enum_var \
+	evil_diamond \
+	evil_diamond_ns \
+	evil_diamond_prop \
+	exception_order \
+	extend \
+	extend_default \
+	extend_placement \
+	extend_template \
+	extend_template_ns \
+	extern_namespace \
+	extern_throws \
+	features \
+	fragments \
+	friends \
+	fvirtual \
+	global_ns_arg \
+	global_vars \
+	grouping \
+	ignore_parameter \
+	import_nomodule \
+	inherit \
+	inherit_missing \
+	inherit_same_name \
+	inherit_target_language \
+	inherit_void_arg \
+	inline_initializer \
+        keyword_rename \
+	kind \
+	langobj \
+	li_attribute \
+	li_boost_shared_ptr \
+	li_boost_shared_ptr_bits \
+	li_carrays \
+	li_cdata \
+	li_cpointer \
+	li_stdint \
+	li_typemaps \
+	li_windows \
+	long_long_apply \
+	member_pointer \
+	member_template \
+	minherit \
+	minherit2 \
+	mixed_types \
+	multiple_inheritance \
+	name_cxx \
+	name_warnings \
+	namespace_class \
+	namespace_enum \
+	namespace_extend \
+	namespace_nested \
+	namespace_spaces \
+	namespace_template \
+	namespace_typedef_class \
+	namespace_typemap \
+	namespace_virtual_method \
+	naturalvar \
+	newobject1 \
+	null_pointer \
+	operator_overload \
+	operator_overload_break \
+	ordering \
+	overload_copy \
+	overload_extend \
+	overload_rename \
+	overload_simple \
+	overload_subtype \
+	overload_template \
+	overload_template_fast \
+	pointer_reference \
+	primitive_ref \
+	private_assign \
+	protected_rename \
+	pure_virtual \
+	redefined \
+	refcount \
+	reference_global_vars \
+	register_par \
+	rename1 \
+	rename2 \
+	rename3 \
+	rename4 \
+	rename_scope \
+	restrict_cplusplus \
+	return_const_value \
+	return_value_scope \
+	rname \
+	samename \
+	sizet \
+	smart_pointer_const \
+	smart_pointer_const2 \
+	smart_pointer_extend \
+	smart_pointer_member \
+	smart_pointer_multi \
+	smart_pointer_multi_typedef \
+	smart_pointer_namespace \
+	smart_pointer_namespace2 \
+	smart_pointer_not \
+	smart_pointer_overload \
+	smart_pointer_protected \
+	smart_pointer_rename \
+	smart_pointer_simple \
+	smart_pointer_static \
+	smart_pointer_templatemethods \
+	smart_pointer_templatevariables \
+	smart_pointer_typedef \
+	special_variables \
+	static_array_member \
+	static_const_member \
+	static_const_member_2 \
+	struct_value \
+	template \
+	template_arg_replace \
+	template_arg_scope \
+	template_arg_typename \
+	template_array_numeric \
+	template_base_template \
+	template_classes \
+	template_const_ref \
+	template_construct \
+	template_default \
+	template_default2 \
+	template_default_arg \
+	template_default_class_parms \
+	template_default_inherit \
+	template_default_qualify \
+	template_default_vw \
+	template_enum \
+	template_enum_ns_inherit \
+	template_enum_typedef \
+	template_explicit \
+	template_extend1 \
+	template_extend2 \
+	template_extend_overload \
+	template_extend_overload_2 \
+	template_forward \
+	template_inherit \
+	template_inherit_abstract \
+	template_int_const \
+	template_methods \
+	template_ns \
+	template_ns2 \
+	template_ns3 \
+	template_ns4 \
+	template_ns_enum \
+	template_ns_enum2 \
+	template_ns_inherit \
+	template_ns_scope \
+	template_partial_arg \
+	template_qualifier \
+	template_qualifier \
+	template_ref_type \
+	template_rename \
+	template_retvalue \
+	template_specialization \
+	template_specialization_defarg \
+	template_specialization_enum \
+	template_static \
+	template_tbase_template \
+	template_template_parameters \
+	template_typedef \
+	template_typedef_cplx \
+	template_typedef_cplx2 \
+	template_typedef_cplx3 \
+	template_typedef_cplx4 \
+	template_typedef_cplx5 \
+	template_typedef_funcptr \
+	template_typedef_ns \
+	template_typedef_ptr \
+	template_typedef_rec \
+	template_using \
+	template_virtual \
+	template_whitespace \
+	threads \
+	throw_exception \
+	typedef_array_member \
+	typedef_class \
+	typedef_funcptr \
+	typedef_inherit \
+	typedef_mptr \
+	typedef_reference \
+	typedef_scope \
+	typedef_sizet \
+	typedef_struct \
+	typemap_namespace \
+	typemap_ns_using \
+	typemap_numinputs \
+	typemap_variables \
+	typemap_various \
+	typename \
+	types_directive \
+	union_scope \
+	using1 \
+	using2 \
+	using_composition \
+	using_extend \
+	using_inherit \
+	using_namespace \
+	using_pointers \
+	using_private \
+	using_protected \
+	valuewrapper \
+	valuewrapper_base \
+	valuewrapper_const \
+	valuewrapper_opaque \
+	varargs \
+	virtual_destructor \
+	virtual_poly \
+	voidtest \
+	wrapmacro
+
+#
+# Put all the heavy STD/STL cases here, where they can be skipped if needed
+#
+CPP_STD_TEST_CASES += \
+	director_string \
+	ignore_template_constructor \
+	li_std_deque \
+	li_std_except \
+        li_std_pair \
+	li_std_string \
+	li_std_vector \
+	naturalvar \
+	smart_pointer_inherit \
+	template_typedef_fnc \
+	template_type_namespace \
+	template_opaque
+
+
+ifndef SKIP_CPP_STD_CASES
+CPP_TEST_CASES += ${CPP_STD_TEST_CASES}
+endif
+
+
+# C test cases. (Can be run individually using make testcase.ctest.)
+C_TEST_CASES += \
+	arrays \
+	char_constant \
+	const_const \
+	empty \
+	enums \
+	extern_declaration \
+	funcptr \
+	function_typedef \
+	immutable \
+	inctest \
+	integers \
+        keyword_rename \
+	lextype \
+	li_carrays \
+	li_cdata \
+	li_cmalloc \
+	li_constraints \
+	li_cpointer \
+	li_math \
+	long_long \
+	name \
+	nested \
+	newobject2 \
+	overload_extend \
+	overload_extendc \
+	preproc \
+	ret_by_value \
+	sizeof_pointer \
+	sneaky1 \
+	struct_rename \
+	typedef_struct \
+	typemap_subst \
+	unions
+
+
+# Multi-module C++ test cases . (Can be run individually using make testcase.multicpptest.)
+MULTI_CPP_TEST_CASES += \
+	clientdata_prop \
+	imports \
+	packageoption \
+	mod \
+	template_typedef_import \
+	multi_import
+
+NOT_BROKEN_TEST_CASES =	$(CPP_TEST_CASES:=.cpptest) \
+			$(C_TEST_CASES:=.ctest) \
+			$(MULTI_CPP_TEST_CASES:=.multicpptest) \
+			$(CUSTOM_TEST_CASES:=.customtest) \
+			$(EXTRA_TEST_CASES)
+
+BROKEN_TEST_CASES = 	$(CPP_TEST_BROKEN:=.cpptest) \
+			$(C_TEST_BROKEN:=.ctest)
+
+ALL_CLEAN = 		$(CPP_TEST_CASES:=.clean) \
+			$(C_TEST_CASES:=.clean) \
+			$(MULTI_CPP_TEST_CASES:=.clean) \
+			$(CUSTOM_TEST_CASES:=.clean) \
+			$(CPP_TEST_BROKEN:=.clean) \
+			$(C_TEST_BROKEN:=.clean)
+
+#######################################################################
+# The following applies for all module languages
+#######################################################################
+all:	$(BROKEN_TEST_CASES) $(NOT_BROKEN_TEST_CASES)
+
+check: 	$(NOT_BROKEN_TEST_CASES)
+
+# partialcheck target runs SWIG only, ie no compilation or running of tests (for a subset of languages)
+partialcheck:
+	$(MAKE) check CC=true CXX=true LDSHARED=true CXXSHARED=true RUNTOOL=true COMPILETOOL=true
+
+broken: $(BROKEN_TEST_CASES)
+
+swig_and_compile_cpp =  \
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \
+	SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \
+	INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \
+	TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACE="$*.i" \
+	$(LANGUAGE)$(VARIANT)_cpp
+
+swig_and_compile_c =  \
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CSRCS="$(CSRCS)" \
+	SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \
+	INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \
+	TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACE="$*.i" \
+	$(LANGUAGE)$(VARIANT)
+
+swig_and_compile_multi_cpp = \
+	for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \
+	  $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \
+	  SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \
+	  INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \
+	  TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACE="$$f.i" \
+	  $(LANGUAGE)$(VARIANT)_cpp; \
+	done
+
+swig_and_compile_external =  \
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile \
+	SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \
+	TARGET="$*_wrap_hdr.h" \
+	$(LANGUAGE)$(VARIANT)_externalhdr; \
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS) $*_external.cxx" \
+	SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \
+	INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \
+	TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACE="$*.i" \
+	$(LANGUAGE)$(VARIANT)_cpp
+
+swig_and_compile_runtime = \
+
+setup = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then	  \
+	  echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \
+	else								  \
+	  echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ;		  \
+	fi;
+
+
+
+#######################################################################
+# Clean
+#######################################################################
+clean: $(ALL_CLEAN)
+
+distclean: clean
+	@rm -f Makefile
+
+.PHONY: all check partialcheck broken clean distclean 
+
diff --git a/trunk/Examples/test-suite/compactdefaultargs.i b/trunk/Examples/test-suite/compactdefaultargs.i
new file mode 100644
index 0000000..b2b07c5
--- /dev/null
+++ b/trunk/Examples/test-suite/compactdefaultargs.i
@@ -0,0 +1,38 @@
+%module compactdefaultargs
+
+// compactdefaultargs off by default
+
+// The following should compile with compactdefaultargs off
+%inline %{
+class Defaults1 {
+  static const int PRIVATE_DEFAULT = -1;
+public:
+  static const double PUBLIC_DEFAULT;
+  Defaults1(int a = PRIVATE_DEFAULT) {}
+  double ret(double d = PUBLIC_DEFAULT) { return d; }
+};
+%}
+
+%{
+const double Defaults1::PUBLIC_DEFAULT = -1.0;
+%}
+
+// compactdefaultargs now on by default
+%feature("compactdefaultargs");
+
+// Turn compactdefaultargs off for the constructor which can't work with this feature
+%feature("compactdefaultargs", "0") Defaults2(int a = PRIVATE_DEFAULT);
+
+%inline %{
+class Defaults2 {
+  static const int PRIVATE_DEFAULT = -1;
+public:
+  static const double PUBLIC_DEFAULT;
+  Defaults2(int a = PRIVATE_DEFAULT) {}
+  double ret(double d = PUBLIC_DEFAULT) { return d; }
+};
+%}
+
+%{
+const double Defaults2::PUBLIC_DEFAULT = -1.0;
+%}
diff --git a/trunk/Examples/test-suite/const_const.i b/trunk/Examples/test-suite/const_const.i
new file mode 100644
index 0000000..7c1c92d
--- /dev/null
+++ b/trunk/Examples/test-suite/const_const.i
@@ -0,0 +1,13 @@
+/* This interface file tests whether SWIG handles types like
+   "const int *const" right.
+
+   SWIG 1.3a5 signals a syntax error.
+*/
+
+%module const_const
+
+%typemap(in) const int *const { $1 = NULL; }
+
+%inline %{
+void foo(const int *const i) {}
+%}
diff --git a/trunk/Examples/test-suite/const_const_2.i b/trunk/Examples/test-suite/const_const_2.i
new file mode 100644
index 0000000..9094262
--- /dev/null
+++ b/trunk/Examples/test-suite/const_const_2.i
@@ -0,0 +1,21 @@
+/* This interface file tests whether SWIG handles doubly constant
+   methods right. SF Bug #216057 against Swig 1.3a5, reported by
+   Mike Romberg <romberg@users.sf.net>
+*/
+
+%module const_const_2
+
+%inline %{
+class Spam { 
+public: 
+  Spam() {} 
+}; 
+
+class Eggs { 
+ public: 
+ Eggs() {} 
+
+ const Spam *spam(void) const { return new Spam(); } 
+}; 
+
+ %}
diff --git a/trunk/Examples/test-suite/constant_pointers.i b/trunk/Examples/test-suite/constant_pointers.i
new file mode 100644
index 0000000..5bd2fd5
--- /dev/null
+++ b/trunk/Examples/test-suite/constant_pointers.i
@@ -0,0 +1,154 @@
+/*
+This testcase primarily test constant pointers, eg int* const.  Only a getter is expected to be produced when wrapping constant pointer variables. A number of other const issues are also tested.
+*/
+
+%module constant_pointers
+
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);                   /* memory leak when setting a ptr/ref variable */
+
+%inline %{
+
+int        GlobalInt;
+const int  ConstInt=2;
+int*       GlobalIntPtr=&GlobalInt;
+int* const GlobalConstIntPtr=&GlobalInt;
+#define ARRAY_SIZE 2
+
+class ParametersTest {
+public:
+    void param1(int* a) {}
+    void param2(const int* a) {}
+    void param3(int* const a) {}
+    void param4(int const a) {}
+    void param5(const int a) {}
+    void param6(int& a) {}
+    void param7(const int& a) {}
+    void param8(int const& a) {}
+    void param9(int*& a) {}
+    void param10(int* const& a) {}
+    void param11(const int* const a) {}
+
+    void param_array1(int* a[ARRAY_SIZE]) {}
+    void param_array2(const int* a[ARRAY_SIZE]) {}
+    void param_array3(int* const a[ARRAY_SIZE]) {}
+    void param_array4(int const a[ARRAY_SIZE]) {}
+    void param_array5(const int a[ARRAY_SIZE]) {}
+    void param_array6(const int* const a[ARRAY_SIZE]) {}
+};
+
+class MemberVariablesTest {
+public:
+    int* member1;
+    ParametersTest* member2;
+    int* const member3;
+    ParametersTest* const member4;
+
+    int* array_member1[ARRAY_SIZE];
+    ParametersTest* array_member2[ARRAY_SIZE];
+    MemberVariablesTest() : member3(NULL), member4(NULL) {}
+private:
+  MemberVariablesTest& operator=(const MemberVariablesTest&);
+};
+void foo(const int *const i) {}
+
+typedef int *typedef1, typedef2, *const typedef3;
+int int1, int2=2, *int3, *const int4 = &GlobalInt;
+
+int* const global_const_int_ptr_array[ARRAY_SIZE] = { &int1, &int2 };
+ParametersTest* const array_member4[ARRAY_SIZE] = { new ParametersTest(), new ParametersTest() };
+
+class ReturnValuesTest {
+public:
+    typedef1 td1;
+    typedef2 td2;
+    int int1, int2, *const int3, *int4, array1[ARRAY_SIZE];
+    int ret1() {return 5;}
+    const int ret2() {return 5;}
+    int ret3() {return 5;}
+    const int* ret4() {return &ConstInt;}
+    int* const ret5() {return &GlobalInt;}
+
+    void ret6(int*& a) {}
+    int*& ret7() {return GlobalIntPtr;}
+    ReturnValuesTest() : int3(NULL) {}
+private:
+  ReturnValuesTest& operator=(const ReturnValuesTest&);
+};
+
+const int* globalRet1() {return &GlobalInt;}
+int* const globalRet2() {return &GlobalInt;}
+
+%}
+
+
+%{
+  struct A
+  {
+  };
+%}
+
+
+%inline 
+{
+  typedef const A* Acptr;
+
+  Acptr opaque(Acptr aptr) {
+    return aptr;
+  }
+
+  struct B
+  {
+    B() : ca() {}
+    const A ca;
+    A a;
+    A* ap;
+    const A* cap;
+    Acptr acptr;  
+  private:
+    B& operator=(const B&);
+  };
+
+  const B* bar(const B* b) {
+    return b;
+  }
+
+  B const*& cbar(B const*& b) {
+    return b;
+  }
+}
+
+
+
+%{
+static int wxEVT_COMMAND_BUTTON_CLICKEDv;
+static int **wxEVT_COMMAND_BUTTON_CLICKEDp;
+#if defined(SWIGR)
+#undef lang1 /* conflicts with symbol in R internals */
+#endif
+
+char lang1[16] = "Hello";
+char *langs[] ={ lang1 };
+ 
+     
+%}
+
+
+%inline {
+#define EWXWEXPORT_VAR 
+
+  const int* wxEVENT_COMMAND_BUTTON_CLICKEDr = (int*) &wxEVT_COMMAND_BUTTON_CLICKEDv;
+  const int* wxEVENT_COMMAND_BUTTON_CLICKEDp = (int*) *wxEVT_COMMAND_BUTTON_CLICKEDp;
+  char **languages1 = &langs[0];
+  char **languages2 = (char **)&langs[0];
+}
+
+%inline %{
+struct Foo {
+  const int *icap;
+};
+const int* icap;
+const Foo *cap;
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/constants.i b/trunk/Examples/test-suite/constants.i
new file mode 100644
index 0000000..1ca1dc6
--- /dev/null
+++ b/trunk/Examples/test-suite/constants.i
@@ -0,0 +1,16 @@
+%module constants
+
+
+%inline %{
+  
+  struct A {
+    A(double) { }
+
+  };
+
+  const A b123(3.0);
+
+%}
+
+  
+
diff --git a/trunk/Examples/test-suite/constover.i b/trunk/Examples/test-suite/constover.i
new file mode 100644
index 0000000..06f9ac7
--- /dev/null
+++ b/trunk/Examples/test-suite/constover.i
@@ -0,0 +1,38 @@
+// This test checks SWIG's code generation for C++ functions
+// and methods that differ only in constness.  
+
+%module constover
+
+%rename(test_pconst) test(const char *);
+%rename(test_constm) test(char *) const;
+%rename(test_pconstm) test(const char *) const;
+
+%inline %{
+
+char *test(char *x) {
+  return (char *) "test";
+}
+
+char *test(const char *x) {
+  return (char *) "test_pconst";
+}
+
+ class Foo {
+ public:
+   Foo() { }
+   char *test(char *x) {
+     return (char *) "test";
+   }
+   char *test(const char *x) {
+     return (char *) "test_pconst";
+   }
+   char *test(char *x) const {
+     return (char *) "test_constmethod";
+   }
+   char *test(const char *x) const {
+     return (char *) "test_pconstmethod";
+   }
+ };
+
+%}
+
diff --git a/trunk/Examples/test-suite/constructor_copy.i b/trunk/Examples/test-suite/constructor_copy.i
new file mode 100644
index 0000000..c74268a
--- /dev/null
+++ b/trunk/Examples/test-suite/constructor_copy.i
@@ -0,0 +1,162 @@
+%module constructor_copy
+
+%copyctor;
+%nocopyctor Foo8;
+%nocopyctor Bar<double>;
+
+%inline %{
+  
+struct Foo1 {
+  int x;
+
+  Foo1(int _x = 2) : x(_x)
+  {
+  }  
+};
+
+struct Foo2 {
+  Foo2() { }
+};
+
+struct Foo3 {
+  Foo3() { }
+  Foo3(const Foo3& ) { }
+};
+
+struct Foo4 {
+  Foo4() { }
+  
+protected:
+  Foo4(const Foo4& ) { }
+};
+
+
+struct Foo4a {
+  Foo4a() { }
+  
+private:
+  Foo4a(const Foo4a& ) { }
+};
+
+
+struct Foo5 : Foo4 {
+};
+
+struct Foo6 : Foo4 {
+  Foo6(const Foo6& f) : Foo4(f) { }
+};
+
+struct Foo7 : Foo5 {
+};
+
+struct Foo8 {
+};
+
+template <class T>
+class Bar 
+{
+public:
+  int x;
+
+  Bar(int _x = 0) : x(_x)
+  {
+  }
+};
+%}
+
+%template(Bari) Bar<int>;
+%template(Bard) Bar<double>;
+
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGUTL)
+
+
+%include "std_vector.i"
+
+#if defined(SWIGCSHARP)
+SWIG_STD_VECTOR_SPECIALIZE_MINIMUM(Flow, Space::Flow)
+#endif
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGR) || defined(SWIGOCTAVE) || defined(SWIGRUBY)
+#define SWIG_GOOD_VECTOR
+%ignore std::vector<Space::Flow>::vector(size_type);
+%ignore std::vector<Space::Flow>::resize(size_type);
+#endif
+
+#if defined(SWIGTCL) || defined(SWIGPERL)
+#define SWIG_GOOD_VECTOR
+/* here, for languages with bad declaration */
+%ignore std::vector<Space::Flow>::vector(unsigned int);
+%ignore std::vector<Space::Flow>::resize(unsigned int);
+#endif
+
+%copyctor;
+
+%ignore FlowFlow::FlowFlow;
+
+%inline %{
+
+namespace Space {
+class Flow {
+public:
+  Flow(int i) {}
+};
+
+
+class FlowFlow {
+public:
+  FlowFlow(int i) {}
+};
+
+}
+
+%}
+
+%template (VectFlow) std::vector<Space::Flow>;
+
+#endif
+
+
+%rename(ABC_Libor_ModelUtils) ABC_Nam::ABC_Libor::ModelUtils;
+
+%copyctor;
+%inline %{
+  namespace ABC_Nam {
+    namespace ABC_Libor {
+      struct ModelUtils {};
+
+      template <class T>
+      struct ModelUtils_T {};
+
+    }    
+  }
+%}
+
+%template(ModelUtils_i) ABC_Nam::ABC_Libor::ModelUtils_T<int>;
+
+
+%rename(Space1Space2_TotalReturnSwap) Space1::Space2::TotalReturnSwap;
+
+%copyctor;
+
+%inline %{
+namespace Space1 {
+  namespace Space2 {
+
+    class TotalReturnSwap {
+    public:
+      TotalReturnSwap() {}
+    };    
+
+    template <class T>
+    class TotalReturnSwap_T {
+    public:
+      TotalReturnSwap_T() {}
+    };    
+
+  }
+}
+%}
+
+%template(Total_i) Space1::Space2::TotalReturnSwap_T<int>;
+
diff --git a/trunk/Examples/test-suite/constructor_exception.i b/trunk/Examples/test-suite/constructor_exception.i
new file mode 100644
index 0000000..4c867c1
--- /dev/null
+++ b/trunk/Examples/test-suite/constructor_exception.i
@@ -0,0 +1,27 @@
+%module constructor_exception
+
+%inline %{
+class Error {
+};
+
+class SomeClass {
+public:
+   SomeClass(int x) {
+       if (x < 0) {
+           throw Error();
+       }
+   }
+};
+
+class Test {
+  SomeClass o;
+public:
+  Test(int x) try : o(x) { }
+  catch (Error &) {
+  } 
+  catch (int) {
+  }
+  catch (...) {
+  }
+};
+%}
diff --git a/trunk/Examples/test-suite/constructor_explicit.i b/trunk/Examples/test-suite/constructor_explicit.i
new file mode 100644
index 0000000..5f4c83c
--- /dev/null
+++ b/trunk/Examples/test-suite/constructor_explicit.i
@@ -0,0 +1,19 @@
+/* Swig 1.3.6 fails to understand the "explicit" keyword.
+   SF Bug #445233, reported by Krzysztof Kozminski
+   <kozminski@users.sf.net>. 
+*/
+
+%module constructor_explicit
+%inline %{
+
+class Foo {
+public:
+   explicit Foo() { }
+   explicit Foo(int) {};
+};
+
+Foo test(Foo x) {
+   return x;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/constructor_ignore.i b/trunk/Examples/test-suite/constructor_ignore.i
new file mode 100644
index 0000000..9af126b
--- /dev/null
+++ b/trunk/Examples/test-suite/constructor_ignore.i
@@ -0,0 +1,36 @@
+%module constructor_ignore
+
+%ignore Space::Delta1::Delta1();
+%ignore Space::Delta2::Delta2(int i);
+%ignore Space::Delta3::Delta3;
+%ignore Space::Delta4::Delta4;
+
+%inline %{
+namespace Space {
+  struct Delta1 {
+  };
+  struct Delta2 {
+    Delta2(int i) {}
+  };
+  struct Delta3 {
+    Delta3(const Delta3&) {}
+    Delta3() {}
+    Delta3(int i) {}
+  };
+  struct Delta4 {
+  };
+}
+%}
+
+%copyctor;
+%ignore Space::Delta5::Delta5;
+%ignore Space::Delta6::Delta6(const Space::Delta6&);
+
+%inline %{
+namespace Space {
+  struct Delta5 {
+  };
+  struct Delta6 {
+  };
+}
+%}
diff --git a/trunk/Examples/test-suite/constructor_value.i b/trunk/Examples/test-suite/constructor_value.i
new file mode 100644
index 0000000..b5c56d0
--- /dev/null
+++ b/trunk/Examples/test-suite/constructor_value.i
@@ -0,0 +1,15 @@
+%module constructor_value
+%inline %{
+
+class Foo { 
+public: 
+Foo(int a) {}; 
+}; 
+
+class Bar { 
+public: 
+Bar(Foo ci) {} 
+}; 
+
+%}
+
diff --git a/trunk/Examples/test-suite/contract.i b/trunk/Examples/test-suite/contract.i
new file mode 100644
index 0000000..6ee0a35
--- /dev/null
+++ b/trunk/Examples/test-suite/contract.i
@@ -0,0 +1,203 @@
+%module contract
+
+%warnfilter(SWIGWARN_RUBY_MULTIPLE_INHERITANCE,
+	    SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) C; /* Ruby, C#, Java, Php4 multiple inheritance */
+
+#ifdef SWIGCSHARP
+%ignore B::bar; // otherwise get a warning: `C.bar' no suitable methods found to override
+#endif
+
+%contract test_preassert(int a, int b) {
+require:
+	a > 0;
+	b > 0;
+}
+
+%contract test_postassert(int a) {
+ensure:
+	test_postassert > 0;
+}
+
+%contract test_prepost(int a, int b) {
+require:
+	a > 0;
+ensure:
+	test_prepost > 0;
+}
+
+%inline %{
+
+int test_preassert(int x, int y) {
+   if ((x > 0) && (y > 0)) return 1;
+   return 0;
+}
+
+int test_postassert(int x) {
+    return x;
+}
+
+int test_prepost(int x, int y) {
+    return x+y;    
+}
+%}
+
+/* Class tests */
+
+%contract Foo::test_preassert(int x, int y) {
+ require:
+  x > 0;
+  y > 0;
+}
+
+%contract Foo::test_postassert(int a) {
+ ensure:
+  test_postassert > 0;
+}
+
+%contract Foo::test_prepost(int a, int b) {
+ require:
+  a > 0;
+ ensure:
+  test_prepost > 0;
+}
+
+%contract Foo::stest_prepost(int a, int b) {
+ require:
+  a > 0;
+ ensure:
+  stest_prepost > 0;
+}
+
+%contract Bar::test_prepost(int c, int d) {
+ require:
+  d > 0;
+}
+
+%inline %{
+class Foo {
+public:
+        virtual ~Foo() { }
+  
+	virtual int test_preassert(int x, int y) {
+            if ((x > 0) && (y > 0)) return 1;
+            return 0;
+	}   
+	virtual int test_postassert(int x) {
+	  return x;
+	}
+	virtual int test_prepost(int x, int y) {
+	  return x+y;
+	}
+	static int stest_prepost(int x, int y) {
+	  return x+y;
+	}
+ };
+
+class Bar : public Foo {
+public:
+	virtual int test_prepost(int x, int y) {
+	  return x+y;
+	}
+};
+
+%}
+
+/* Multiple inheritance test */
+
+%contract A::foo(int i, int j, int k, int l, int m) {
+ require:
+  i > 0;
+  j > 0;
+ ensure:
+  foo > 0;
+}
+
+%contract B::bar(int x, int y, int z, int w, int v) {
+ require:
+  w > 0;
+  v > 0;
+ ensure:
+  bar > 0;
+}
+
+%contract C::foo(int a, int b, int c, int d, int e) {
+ require:
+  c > 0;
+  d > 0;
+ ensure:
+  foo > 0;
+}
+
+%contract D::foo(int, int, int, int, int x) {
+ require:
+  x > 0;
+}
+
+%contract D::bar(int a, int b, int c, int, int) {
+ require:
+  a > 0;
+  b > 0;
+  c > 0;
+}
+
+%inline %{
+  class A {
+   public:
+    virtual ~A() {}
+    virtual int foo(int a, int b, int c, int d, int e) {
+      if ((a > 0) && (b > 0) && (c > 0) && (d > 0) && (e > 0)) {
+	return 1;
+      }
+      return 0;
+    }
+  };
+
+  class B {
+   public:
+    virtual ~B() {}
+    virtual int bar(int a, int b, int c, int d, int e) {
+      if ((a > 0) && (b > 0) && (c > 0) && (d > 0) && (e > 0)) {
+	return 1;
+      }
+      return 0;
+    }
+  };
+
+  class C : public A, public B {
+   public:
+    virtual int foo(int a, int b, int c, int d, int e) {
+      return A::foo(a,b,c,d,e);
+    }
+    virtual int bar(int a, int b, int c, int d, int e) {
+      return B::bar(a,b,c,d,e);
+    }
+  };
+  
+  class D : public C {
+   public:
+    virtual int foo(int a, int b, int c, int d, int e) {
+      return C::foo(a,b,c,d,e);
+    }
+    virtual int bar(int a, int b, int c, int d, int e) {
+      return C::bar(a,b,c,d,e);
+    }
+  };
+  %}
+
+%extend E {
+  %contract manipulate_i(int i) {
+  require:
+  i <= $self->m_i;
+  }
+}
+
+%inline %{
+struct E {
+  int m_i;
+  void manipulate_i(int i) {
+  }
+};
+%}
+
diff --git a/trunk/Examples/test-suite/conversion.i b/trunk/Examples/test-suite/conversion.i
new file mode 100644
index 0000000..bad6c14
--- /dev/null
+++ b/trunk/Examples/test-suite/conversion.i
@@ -0,0 +1,11 @@
+%module conversion
+%rename(toFoo) Bar::operator Foo();
+
+%inline %{ 
+   struct Foo {
+   };
+   struct Bar {
+      operator Foo () { return Foo(); }
+   };
+%} 
+
diff --git a/trunk/Examples/test-suite/conversion_namespace.i b/trunk/Examples/test-suite/conversion_namespace.i
new file mode 100644
index 0000000..e090025
--- /dev/null
+++ b/trunk/Examples/test-suite/conversion_namespace.i
@@ -0,0 +1,14 @@
+%module conversion_namespace
+%rename(toFoo) oss::Bar::operator Foo();
+
+%inline %{ 
+ namespace oss 
+ { 
+   struct Foo {
+   };
+   struct Bar {
+      operator Foo () { return Foo(); }
+   };
+  } 
+%} 
+
diff --git a/trunk/Examples/test-suite/conversion_ns_template.i b/trunk/Examples/test-suite/conversion_ns_template.i
new file mode 100644
index 0000000..0814f2a
--- /dev/null
+++ b/trunk/Examples/test-suite/conversion_ns_template.i
@@ -0,0 +1,76 @@
+%module conversion_ns_template
+%{ 
+ namespace oss 
+ { 
+   struct Hi
+   {
+     Hi(){}     
+     Hi(int){}     
+   };
+
+   enum Test {One, Two}; 
+
+   template <Test> 
+   struct Foo { 
+     Foo(){}
+   }; 
+
+   template <Test T>   
+   struct Bar { 
+     Bar(){ }
+     Bar(int){ }
+     
+     operator int() { return 0; }
+     operator int&() { static int num = 0; return num; }
+     operator Foo<T>() { return Foo<T>(); }
+     operator Foo<T>&() { return *(new Foo<T>()); }
+   }; 
+  } 
+%} 
+
+ namespace oss 
+ { 
+   enum Test {One, Two}; 
+ 
+   // these works 
+   %ignore Hi::Hi(); 
+   %rename(create) Hi::Hi(int); 
+
+   struct Hi 
+   {
+     Hi();
+     Hi(int);
+   };
+
+   template <Test> 
+   struct Foo { 
+     Foo();
+   }; 
+ 
+   // these works 
+   %rename(hello1) Bar<One>::operator int&(); 
+   %ignore Bar<One>::operator int(); 
+   %rename(hello2) Bar<One>::operator Foo<oss::One>&(); 
+   %ignore Bar<One>::operator Foo<oss::One>();
+    
+   // these don't
+   %ignore Bar<One>::Bar(); 
+   %rename(Bar_create) Bar<One>::Bar(int); 
+ 
+   template <Test T>   
+   struct Bar { 
+     Bar();
+     Bar(int);
+     operator int(); 
+     operator int&(); 
+     operator Foo<T>(); 
+     operator Foo<T>&(); 
+   }; 
+  } 
+
+  
+namespace oss 
+{ 
+  %template(Foo_One) Foo<One>; 
+  %template(Bar_One) Bar<One>; 
+} 
diff --git a/trunk/Examples/test-suite/cplusplus_throw.i b/trunk/Examples/test-suite/cplusplus_throw.i
new file mode 100644
index 0000000..3b11c48
--- /dev/null
+++ b/trunk/Examples/test-suite/cplusplus_throw.i
@@ -0,0 +1,28 @@
+/* This interface file checks whether the SWIG parses the throw
+   directive in combination with the const directive.  Bug reported by
+   Scott B. Drummonds, 08 June 2001.  
+*/
+
+%module cplusplus_throw
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%nodefaultctor;
+
+%inline %{
+
+class Foo { };
+
+class Bar {
+public:
+  void baz() const { };
+  void foo() throw (Foo) { };
+  void bazfoo() const throw (int) { };
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/cpp_basic.i b/trunk/Examples/test-suite/cpp_basic.i
new file mode 100644
index 0000000..a247dd2
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_basic.i
@@ -0,0 +1,107 @@
+/* This is a basic test of proxy classes, used by chicken */
+
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);                   /* memory leak when setting a ptr/ref variable */
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) global_cint;       /* Ruby, wrong constant name */
+
+%module cpp_basic
+
+%newobject Bar::testFoo;
+
+%inline %{
+
+class Foo {
+  public:
+    Foo(int a) : num(a) {}
+    int num;
+
+    int func1(int a) {
+      return 2*a*num;
+    }
+    
+    int func2(int a) {
+      return -a*num;
+    }
+    
+    int (Foo::*func_ptr)(int);
+};
+
+%}
+
+%{
+static Foo init_ref = Foo(-4);
+%}
+
+%inline %{
+class Bar {
+  public:
+    Bar() : fptr(0), fref(init_ref), fval(15) , cint(3) {}
+  
+    Foo *fptr;
+    Foo &fref;
+    Foo fval;
+
+    const int cint;
+    static const int global_cint = -4;
+
+    static Foo *global_fptr;
+    static Foo &global_fref;
+    static Foo global_fval;
+
+    int test(int a, Foo *f) {
+      return a + (f ? f->num : 0) + fval.num;
+    }
+
+    Foo *testFoo(int a, Foo *f) {
+      return new Foo(2 * a + (f ? f->num : 0) + fval.num);
+    }
+private:
+    Bar& operator=(const Bar&);
+};
+
+%}
+
+%{
+Foo *Bar::global_fptr = NULL;
+Foo &Bar::global_fref = init_ref;
+Foo Bar::global_fval = Foo(3);
+%}
+
+/* member function tests */
+%inline %{
+int (Foo::*get_func1_ptr())(int) {
+  return &Foo::func1;
+}
+
+int (Foo::*get_func2_ptr())(int) {
+  return &Foo::func2;
+}
+
+int test_func_ptr(Foo *f, int a) {
+  return (f->*(f->func_ptr))(a);
+}
+
+%}
+
+
+#ifdef __cplusplus
+%define MACRO_WINDOW_SHOW
+void show(void *count = 0, void *data = 0)
+{
+  return;
+}
+%enddef
+
+%inline %{
+  class Fl_Window {
+  public:
+    Fl_Window() {};
+    ~Fl_Window() {};
+  };
+%}
+
+%extend Fl_Window {
+  MACRO_WINDOW_SHOW
+}
+
+#endif
diff --git a/trunk/Examples/test-suite/cpp_broken.i b/trunk/Examples/test-suite/cpp_broken.i
new file mode 100644
index 0000000..fe109ea
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_broken.i
@@ -0,0 +1,75 @@
+%module cpp_broken
+
+
+// bug #1060789
+%inline %{
+#define MASK(shift, size) (((1 << (size)) - 1) << (shift))
+#define SOME_MASK_DEF (80*MASK(8, 10))
+%}
+
+// bug #1060079
+%inline %{
+#define FIELD(name, width) unsigned int name:width
+#define SOME_CONST 2
+#define NEXT_CONST (2 * SOME_CONST)
+
+typedef struct {
+FIELD(a, SOME_CONST);
+FIELD(b, NEXT_CONST);
+} MyStruct_t;
+%}
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+// bug #994301
+%inline %{
+#define max(a,b) ((a) > (b) ? (a) : (b))
+%}
+
+
+// bug #940318
+%inline %{
+typedef enum {
+eZero = 0
+#define ONE 1
+} EFoo;
+%}
+
+
+// bug #754443
+
+%inline %{
+#define MAG_STYLE_BORDER_OFFS 0
+#define MAG_STYLE_BORDER_BITS 3
+#define MAG_STYLE_BORDER_MASK (((1UL<<MAG_STYLE_BORDER_BITS)-1)<<MAG_STYLE_BORDER_OFFS)
+
+/* these CANNOT be combined */
+#define MAG_STYLE_BORDER_NONE       (1 << MAG_STYLE_BORDER_OFFS)
+#define MAG_STYLE_BORDER_STATIC     (2 << MAG_STYLE_BORDER_OFFS)
+#define MAG_STYLE_BORDER_SIMPLE     (3 << MAG_STYLE_BORDER_OFFS)
+#define MAG_STYLE_BORDER_RAISED     (4 << MAG_STYLE_BORDER_OFFS)
+#define MAG_STYLE_BORDER_DOUBLE     (5 << MAG_STYLE_BORDER_OFFS)
+#define MAG_STYLE_BORDER_DEFAULT    MAG_STYLE_BORDER_SIMPLE
+
+
+#define MAG_STYLE_CAPTION_OFFS ( MAG_STYLE_BORDER_OFFS + MAG_STYLE_BORDER_BITS )
+#define MAG_STYLE_CAPTION_BITS 8
+#define MAG_STYLE_CAPTION_MASK (((1UL<<MAG_STYLE_CAPTION_BITS)-1)<<MAG_STYLE_CAPTION_OFFS)
+
+/* these CAN be combined */
+#define MAG_STYLE_CAPTION_NONE      ( 1 << ( 0 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_PRESENT   ( 1 << ( 1 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_SYSMENU   ( 1 << ( 2 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_MINIMIZE  ( 1 << ( 3 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_MAXIMIZE  ( 1 << ( 4 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_RESIZE    ( 1 << ( 5 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_TINYHOR   ( 1 << ( 6 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_TINYVER   ( 1 << ( 7 + MAG_STYLE_CAPTION_OFFS ))
+#define MAG_STYLE_CAPTION_DEFAULT   ( MAG_STYLE_CAPTION_RESIZE + MAG_STYLE_CAPTION_MAXIMIZE + MAG_STYLE_CAPTION_MINIMIZE + MAG_STYLE_CAPTION_SYSMENU + MAG_STYLE_CAPTION_PRESENT )
+
+
+%}
diff --git a/trunk/Examples/test-suite/cpp_enum.i b/trunk/Examples/test-suite/cpp_enum.i
new file mode 100644
index 0000000..e6eef6d
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_enum.i
@@ -0,0 +1,43 @@
+/*
+The primary purpose of this testcase is to ensure that enums used along with the 'enum' keyword compile under c++.
+*/
+
+%module cpp_enum
+
+%inline %{
+
+enum SOME_ENUM {ENUM_ONE, ENUM_TWO};
+
+struct StructWithEnums {
+    StructWithEnums() : some_enum(ENUM_ONE) {};
+    enum SOME_ENUM some_enum;
+    void enum_test1(enum SOME_ENUM param1, enum SOME_ENUM* param2, enum SOME_ENUM& param3) {};
+    void enum_test2(SOME_ENUM param1, SOME_ENUM* param2, SOME_ENUM& param3) {};
+
+    SOME_ENUM enum_test3() { return ENUM_ONE; };
+    enum SOME_ENUM enum_test4() { return ENUM_TWO; };
+
+    SOME_ENUM* enum_test5() { return &some_enum; };
+    enum SOME_ENUM* enum_test6() { return &some_enum; };
+
+    SOME_ENUM& enum_test7() { return some_enum; };
+    enum SOME_ENUM& enum_test8() { return some_enum; };
+};
+
+
+ struct Foo
+ {   
+   enum {Hi, Hello } hola;
+   
+   Foo() 
+     : hola(Hello)
+   {
+   }
+ };
+
+extern "C"
+{
+ enum {Hi, Hello } hi;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/cpp_namespace.i b/trunk/Examples/test-suite/cpp_namespace.i
new file mode 100644
index 0000000..d7bf95e
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_namespace.i
@@ -0,0 +1,105 @@
+// C++ namespace tests
+
+%module cpp_namespace
+
+%inline %{
+  typedef int Bad;
+
+  /* A very basic namespace */
+  namespace example {
+    typedef char *Bad;
+
+    int fact(int n) {
+      if (n <= 0) return 1;
+      else return n*fact(n-1);
+    }
+    int Foo = 42;
+
+    class Test {
+    public:
+      Test() { }
+      ~Test() { }
+      char *method() {
+	return (char *) "Test::method";
+      }
+    };
+    typedef Test *TestPtr;
+    void weird(Bad x, ::Bad y) { }
+  }
+
+  char *do_method(example::TestPtr t) {
+    return t->method();
+  }
+
+  namespace ex = example;
+
+  char *do_method2(ex::TestPtr t) {
+     return t->method();
+  }
+
+%}
+
+// Some more complicated namespace examples
+
+%inline %{
+namespace Foo {
+   typedef int Integer;
+   class Test2 { 
+   public:
+       virtual ~Test2() { }
+       virtual char *method() {	
+	 return (char *) "Test2::method";
+       }
+   };
+  typedef Test2 *Test2Ptr;
+}
+
+namespace Foo2 {
+  using Foo::Integer;
+  using Foo::Test2;
+  class Test3 : public Test2 {
+  public:
+    virtual char *method() {	
+      return (char *) "Test3::method";
+    }
+  };
+  typedef Test3 *Test3Ptr;
+  typedef Test3 Test3Alt;
+}
+
+namespace Foo3 {
+  using namespace Foo2;
+  class Test4 : public Test3 {
+  public:
+    virtual char *method() {	
+      return (char *) "Test4::method";
+    }
+  };
+  Integer foo3(Integer x) { return x; }
+  typedef Test4 *Test4Ptr;
+  
+}
+   
+using Foo2::Test3Alt;
+using Foo3::Integer;
+
+class Test5 : public Test3Alt { 
+public:
+  virtual char *method() {	
+    return (char *) "Test5::method";
+  }
+};
+
+char *do_method3(Foo::Test2 *t, Integer x) {
+  return t->method();
+}
+
+%}
+
+
+
+   
+
+
+      	
+
diff --git a/trunk/Examples/test-suite/cpp_nodefault.i b/trunk/Examples/test-suite/cpp_nodefault.i
new file mode 100644
index 0000000..30629ec
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_nodefault.i
@@ -0,0 +1,40 @@
+// This file tests SWIG pass/return by value for
+// a class with no default constructor
+
+%module cpp_nodefault
+
+%inline %{
+
+class Foo {
+public:
+   int a;
+   Foo(int x, int y) { }
+  ~Foo() {}
+};
+
+Foo create(int x, int y) {
+    return Foo(x,y);
+}
+
+typedef Foo Foo_t;
+
+void consume(Foo f, Foo_t g) {}
+
+class Bar {
+public:
+    void consume(Foo f, Foo_t g) {}
+    Foo create(int x, int y) {
+        return Foo(x,y);
+    }
+};
+
+
+%}
+
+%{
+Foo gvar = Foo(3,4);
+%}
+
+Foo gvar;
+
+
diff --git a/trunk/Examples/test-suite/cpp_static.i b/trunk/Examples/test-suite/cpp_static.i
new file mode 100644
index 0000000..c68e986
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_static.i
@@ -0,0 +1,26 @@
+/*
+Testcase to test c++ static member variables and static functions.
+Tests Sourceforge bug #444748.
+*/
+
+%module cpp_static
+
+%inline %{
+
+class StaticMemberTest {
+public:
+  static int static_int;
+};
+
+class StaticFunctionTest {
+public:
+  static void static_func() {};
+  static void static_func_2(int param_1) {};
+  static void static_func_3(int param_1, int param_2) {};
+};
+
+%}
+
+%{
+int StaticMemberTest::static_int;
+%}
diff --git a/trunk/Examples/test-suite/cpp_typedef.i b/trunk/Examples/test-suite/cpp_typedef.i
new file mode 100644
index 0000000..f869f4d
--- /dev/null
+++ b/trunk/Examples/test-suite/cpp_typedef.i
@@ -0,0 +1,46 @@
+// This file tests SWIG's tracking of C++ typedef declarations
+
+%module cpp_typedef
+
+%{
+
+class Bar {
+public:
+};
+%}
+
+%inline %{
+class Foo {
+public:
+    typedef Bar SomeBar;
+    typedef SomeBar SomeOtherBar;
+    SomeOtherBar bar() {
+        SomeOtherBar b;
+        return b;
+    }
+    static SomeOtherBar sbar() {
+        SomeOtherBar b;
+        return b;
+    }
+};
+
+// Test that the correct types are used for typedef struct declarations
+typedef struct {
+} UnnamedStruct;
+
+typedef struct NamedStruct {
+} TypedefNamedStruct;
+
+typedef TypedefNamedStruct DoubleTypedef;
+
+class Test {
+public:
+    UnnamedStruct test1(UnnamedStruct a) {return a;};
+    struct NamedStruct test2(struct NamedStruct a) {return a;};
+    TypedefNamedStruct test3(TypedefNamedStruct a) {return a;};
+    DoubleTypedef test4(DoubleTypedef a) {return a;};
+};
+
+%}
+        
+
diff --git a/trunk/Examples/test-suite/csharp/Makefile.in b/trunk/Examples/test-suite/csharp/Makefile.in
new file mode 100644
index 0000000..5fd576e
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/Makefile.in
@@ -0,0 +1,86 @@
+#######################################################################
+# Makefile for C# test-suite
+#######################################################################
+
+LANGUAGE     = csharp
+SCRIPTSUFFIX = _runme.cs
+INTERPRETER  = @CSHARPCILINTERPRETER@
+CSHARPPATHSEPARATOR = "@CSHARPPATHSEPARATOR@"
+CSHARPCYGPATH_W     = @CSHARPCYGPATH_W@
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@/..
+top_builddir = @top_builddir@/..
+
+CPP_TEST_CASES = \
+	csharp_attributes \
+	csharp_exceptions \
+	csharp_features \
+	csharp_prepost \
+	csharp_typemaps \
+	enum_thorough_simple \
+	enum_thorough_typesafe \
+	exception_partial_info
+
+CUSTOM_TEST_CASES = intermediary_classname
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+SWIGOPT += -namespace $*Namespace $(SWIGOPTSPECIAL)
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+(cd $* && $(swig_and_compile_cpp))
+	+$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+(cd $* && $(swig_and_compile_c))
+	+$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+(cd $* && $(swig_and_compile_multi_cpp))
+	+$(run_testcase)
+
+# Rules for custom tests
+intermediary_classname.customtest: 
+	$(MAKE) intermediary_classname.cpptest SWIGOPTSPECIAL="-dllimport intermediary_classname"
+
+# Makes a directory for the testcase if it does not exist
+setup = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then	  \
+	  echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \
+	else								  \
+	  echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ;		  \
+	fi;								  \
+	if [ ! -d $* ]; then						  \
+		mkdir $*;						  \
+	fi;
+
+# Compiles C# files then runs the testcase. A testcase is only run if
+# a file is found which has _runme.cs appended after the testcase name.
+# Note C# uses LD_LIBRARY_PATH under Unix, PATH under Cygwin/Windows and SHLIB_PATH on HPUX.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  $(MAKE) -f $*/$(top_builddir)/$(EXAMPLES)/Makefile \
+	  CSHARPFLAGS='-nologo -out:$*_runme.exe' \
+	  CSHARPSRCS='`$(CSHARPCYGPATH_W) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX)` \
+	  $*$(CSHARPPATHSEPARATOR)*.cs' csharp_compile && \
+	  env LD_LIBRARY_PATH="$*:$$LD_LIBRARY_PATH" PATH="$*:$$PATH" SHLIB_PATH="$*:$$SHLIB_PATH" $(RUNTOOL) $(INTERPRETER) $*_runme.exe; ) \
+	else ( \
+	  cd $* && \
+	  $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile \
+	  CSHARPFLAGS='-nologo -t:module -out:$*.netmodule' \
+	  CSHARPSRCS='*.cs' csharp_compile; ); \
+	fi;
+
+# Clean: remove testcase directories
+%.clean:
+	@if [ -d $* ]; then \
+		rm -rf $*; \
+	fi;
+
+clean:
+	@rm -f *.exe *.exe.mdb
diff --git a/trunk/Examples/test-suite/csharp/README b/trunk/Examples/test-suite/csharp/README
new file mode 100644
index 0000000..96dea94
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/README
@@ -0,0 +1,42 @@
+SWIG testsuite README file
+--------------------------
+
+This testsuite is here to ensure SWIG can handle a wide range of c/c++
+syntax. The testsuite comprises many testcases in this directory. Each
+test case is tested under each of the language modules thereby
+thoroughly testing all of SWIG. It ensures that each of the language
+modules are at a similar standard.
+
+Those modules that support shadow classes run the tests producing
+shadow classes to test the full language module functionality.
+
+Some test cases need a runtime test. These need implementing in each
+of the language modules. The language modules look for a file in the
+language specific test-suite directory which has _runme appended after
+the testcase name. If one is found it will be run as part of the test.
+
+Some language modules add to this common set of test cases for
+language specific tests. These can be found in the appropriate
+language test-suite directory. There is also a README in each of the
+language module directories.
+
+For each testcase a message showing which testcase is being tested is
+displayed. Nothing else is printed unless the test fails.
+
+
+Some Developer Guidelines
+-------------------------
+
+Note that the whole test suite need not be run each time a testcase is
+modified. An individual testcase may be run by going to the language
+module test-suite directory and using make testcasename.xxx where xxx
+is the type of test (eg cpptest). See common.mk. make -s doesn't print
+any junk on the screen and is useful for emulating the way make check
+works from the SWIG root directory.
+
+If there are runtime tests needed, don't print anything unless there
+is an error in which case stderr is suggested.
+
+Please set the name of the module to the same name as the testcase,
+otherwise modules will not be found.
+
diff --git a/trunk/Examples/test-suite/csharp/aggregate_runme.cs b/trunk/Examples/test-suite/csharp/aggregate_runme.cs
new file mode 100644
index 0000000..ee6394b
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/aggregate_runme.cs
@@ -0,0 +1,28 @@
+using System;
+using aggregateNamespace;
+
+public class runme {
+    static void Main() {
+
+      // Confirm that move() returns correct results under normal use
+      int result = aggregate.move(aggregate.UP);
+      if (result != aggregate.UP) throw new Exception("UP failed");
+
+      result = aggregate.move(aggregate.DOWN);
+      if (result != aggregate.DOWN) throw new Exception("DOWN failed");
+
+      result = aggregate.move(aggregate.LEFT);
+      if (result != aggregate.LEFT) throw new Exception("LEFT failed");
+
+      result = aggregate.move(aggregate.RIGHT);
+      if (result != aggregate.RIGHT) throw new Exception("RIGHT failed");
+
+      // Confirm that move() raises an exception when the contract is violated
+      try {
+        aggregate.move(0);
+        throw new Exception("0 test failed");
+      }
+      catch (ArgumentOutOfRangeException) {
+      }
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/allprotected_runme.cs b/trunk/Examples/test-suite/csharp/allprotected_runme.cs
new file mode 100644
index 0000000..99a791d
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/allprotected_runme.cs
@@ -0,0 +1,71 @@
+using System;
+using allprotectedNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    runme r = new runme();
+    r.run();
+  }
+
+  void run()
+  {
+    MyProtectedBase mpb = new MyProtectedBase("MyProtectedBase");
+    mpb.accessProtected();
+  }
+}
+
+class MyProtectedBase : ProtectedBase
+{
+  public MyProtectedBase(string name) : base(name) {
+  }
+  public void accessProtected() {
+    string s = virtualMethod();
+    if (s != "ProtectedBase")
+      throw new Exception("Failed");
+
+    Klass k = instanceMethod(new Klass("xyz"));
+    if (k.getName() != "xyz") 
+      throw new Exception("Failed");
+
+    k = instanceOverloaded(new Klass("xyz"));
+    if (k.getName() != "xyz") 
+      throw new Exception("Failed");
+
+    k = instanceOverloaded(new Klass("xyz"), "abc");
+    if (k.getName() != "abc") 
+      throw new Exception("Failed");
+
+    k = ProtectedBase.staticMethod(new Klass("abc"));
+    if (k.getName() != "abc") 
+      throw new Exception("Failed");
+
+    k = ProtectedBase.staticOverloaded(new Klass("xyz"));
+    if (k.getName() != "xyz") 
+      throw new Exception("Failed");
+
+    k = ProtectedBase.staticOverloaded(new Klass("xyz"), "abc");
+    if (k.getName() != "abc") 
+      throw new Exception("Failed");
+
+    instanceMemberVariable = 30;
+    int i = instanceMemberVariable;
+    if (i != 30)
+      throw new Exception("Failed");
+
+    staticMemberVariable = 40;
+    i = staticMemberVariable;
+    if (i != 40)
+      throw new Exception("Failed");
+
+    i = staticConstMemberVariable;
+    if (i != 20)
+      throw new Exception("Failed");
+
+    anEnum = ProtectedBase.AnEnum.EnumVal1;
+    ProtectedBase.AnEnum ae = anEnum;
+    if (ae != ProtectedBase.AnEnum.EnumVal1)
+      throw new Exception("Failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/csharp/apply_strings_runme.cs b/trunk/Examples/test-suite/csharp/apply_strings_runme.cs
new file mode 100644
index 0000000..deaa521
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/apply_strings_runme.cs
@@ -0,0 +1,16 @@
+
+using System;
+using apply_stringsNamespace;
+
+public class apply_strings_runme {
+
+  private static string TEST_MESSAGE = "A message from target language to the C++ world and back again.";
+
+  public static void Main() {
+    if (apply_strings.UCharFunction(TEST_MESSAGE) != TEST_MESSAGE) throw new Exception("UCharFunction failed");
+    if (apply_strings.SCharFunction(TEST_MESSAGE) != TEST_MESSAGE) throw new Exception("SCharFunction failed");
+    SWIGTYPE_p_char pChar = apply_strings.CharFunction(null);
+    if (pChar != null) throw new Exception("CharFunction failed");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/bools_runme.cs b/trunk/Examples/test-suite/csharp/bools_runme.cs
new file mode 100755
index 0000000..70620fc
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/bools_runme.cs
@@ -0,0 +1,29 @@
+
+// This is the bool runtime testcase. It checks that the C++ bool type works.
+
+using System;
+using boolsNamespace;
+
+public class bools_runme {
+
+  public static void Main() {
+
+		bool t = true;
+		bool f = false;
+		
+		check_bo(f);
+		check_bo(t);
+  }
+
+  public static void check_bo(bool input) {
+
+		for( int i=0; i<1000; i++ ) {
+			if( bools.bo(input) != input ) {
+				string ErrorMessage = "Runtime test check_bo failed.";
+				throw new Exception(ErrorMessage);
+			}
+		}
+
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/char_strings_runme.cs b/trunk/Examples/test-suite/csharp/char_strings_runme.cs
new file mode 100644
index 0000000..a8907fb
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/char_strings_runme.cs
@@ -0,0 +1,134 @@
+
+using System;
+using char_stringsNamespace;
+
+public class char_strings_runme {
+
+  private static string CPLUSPLUS_MSG = "A message from the deep dark world of C++, where anything is possible.";
+  private static string OTHERLAND_MSG = "Little message from the safe world.";
+
+  public static void Main() {
+
+    uint count = 10000;
+    uint i = 0;
+
+    // get functions
+    for (i=0; i<count; i++) {
+      string str = char_strings.GetCharHeapString();
+      if (str != CPLUSPLUS_MSG)
+        throw new Exception("Test char get 1 failed, iteration " + i);
+      char_strings.DeleteCharHeapString();
+    }
+
+    for (i=0; i<count; i++) {
+      string str = char_strings.GetConstCharProgramCodeString();
+      if (str != CPLUSPLUS_MSG)
+        throw new Exception("Test char get 2 failed, iteration " + i);
+      char_strings.DeleteCharHeapString();
+    }
+
+    for (i=0; i<count; i++) {
+      string str = char_strings.GetCharStaticString();
+      if (str != CPLUSPLUS_MSG)
+        throw new Exception("Test char get 3 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      string str = char_strings.GetCharStaticStringFixed();
+      if (str != CPLUSPLUS_MSG)
+        throw new Exception("Test char get 4 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      string str = char_strings.GetConstCharStaticStringFixed();
+      if (str != CPLUSPLUS_MSG)
+        throw new Exception("Test char get 5 failed, iteration " + i);
+    }
+
+    // set functions
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetCharHeapString(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char set 1 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetCharStaticString(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char set 2 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetCharArrayStaticString(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char set 3 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharHeapString(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char set 4 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharStaticString(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char set 5 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharArrayStaticString(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char set 6 failed, iteration " + i);
+    }
+
+    // get set function
+    for (i=0; i<count*10; i++) {
+      string ping = OTHERLAND_MSG + i;
+      string pong = char_strings.CharPingPong(ping);
+      if (ping != pong)
+        throw new Exception("Test PingPong 1 failed.\nExpected:" + ping + "\nReceived:" + pong);
+    }
+
+    // variables
+    for (i=0; i<count; i++) {
+      char_strings.global_char = OTHERLAND_MSG + i;
+      if (char_strings.global_char != OTHERLAND_MSG + i)
+        throw new Exception("Test variables 1 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      char_strings.global_char_array1 = OTHERLAND_MSG + i;
+      if (char_strings.global_char_array1 != OTHERLAND_MSG + i)
+        throw new Exception("Test variables 2 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      char_strings.global_char_array2 = OTHERLAND_MSG + i;
+      if (char_strings.global_char_array2 != OTHERLAND_MSG + i)
+        throw new Exception("Test variables 3 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (char_strings.global_const_char != CPLUSPLUS_MSG)
+        throw new Exception("Test variables 4 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (char_strings.global_const_char_array1 != CPLUSPLUS_MSG)
+        throw new Exception("Test variables 5 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (char_strings.global_const_char_array2 != CPLUSPLUS_MSG)
+        throw new Exception("Test variables 6 failed, iteration " + i);
+    }
+
+    // char *& tests
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetConstCharPointerRef();
+      if (str != CPLUSPLUS_MSG)
+        throw new Exception("Test char pointer ref get failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharPointerRef(OTHERLAND_MSG + i, i))
+        throw new Exception("Test char pointer ref set failed, iteration " + i);
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/constover_runme.cs b/trunk/Examples/test-suite/csharp/constover_runme.cs
new file mode 100644
index 0000000..bae7b38
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/constover_runme.cs
@@ -0,0 +1,34 @@
+using System;
+using constoverNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+        string p = constover.test("test");
+        if ( p != "test" )
+            throw new Exception( "test failed!" );
+
+        p = constover.test_pconst("test");
+        if ( p != "test_pconst" )
+            throw new Exception( "test_pconst failed!" );
+
+        Foo f = new Foo();
+        p = f.test("test");
+        if ( p != "test" )
+            throw new Exception( "member-test failed!" );
+
+        p = f.test_pconst("test");
+        if ( p != "test_pconst" )
+            throw new Exception( "member-test_pconst failed!" );
+
+        p = f.test_constm("test");
+        if ( p != "test_constmethod" )
+            throw new Exception( "member-test_constm failed!" );
+
+        p = f.test_pconstm("test");
+        if ( p != "test_pconstmethod" )
+            throw new Exception( "member-test_pconstm failed!" );
+    }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/csharp_attributes_runme.cs b/trunk/Examples/test-suite/csharp/csharp_attributes_runme.cs
new file mode 100644
index 0000000..7dc9d7c
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/csharp_attributes_runme.cs
@@ -0,0 +1,239 @@
+using System;
+using System.Reflection;
+using csharp_attributesNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    // Custom attributes typemap tests
+    //
+    // cstype typemap attributechecks
+    //
+    // Global function cstype typemap attributes check
+    Type globaltype = typeof(csharp_attributes);
+    {
+      MethodInfo member = (MethodInfo)globaltype.GetMember("GlobalFunction")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
+        throw new Exception("No IntOut attribute for " + member.Name);
+      ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
+      if (parameter.Name != "myInt")
+        throw new Exception("Incorrect parameter name");
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntInAttribute))
+        throw new Exception("Expecting IntIn attribute");
+    }
+    // Constant - cstype typemap attributes check
+    {
+      MemberInfo member = (MemberInfo)globaltype.GetMember("TESTMACRO")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
+        throw new Exception("No IntOut attribute for " + member.Name);
+    }
+
+    // Non-static method cstype typemap attributes check
+    Type type = typeof(Stations);
+    {
+      MethodInfo member = (MethodInfo)type.GetMember("Reading")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
+        throw new Exception("No IntOut attribute for " + member.Name);
+      ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
+      if (parameter.Name != "myInt")
+        throw new Exception("Incorrect parameter name");
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntInAttribute))
+        throw new Exception("Expecting IntIn attribute");
+    }
+    // Static method cstype typemap attributes check
+    {
+      MethodInfo member = (MethodInfo)type.GetMember("Swindon")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
+        throw new Exception("No IntOut attribute for " + member.Name);
+      ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
+      if (parameter.Name != "myInt")
+        throw new Exception("Incorrect parameter name");
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntInAttribute))
+        throw new Exception("Expecting IntIn attribute");
+    }
+    // Constructor cstype typemap attributes check
+    {
+      ConstructorInfo member = (ConstructorInfo)type.GetConstructors()[0];
+      ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
+      if (parameter.Name != "myInt")
+        throw new Exception("Incorrect parameter name");
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntInAttribute))
+        throw new Exception("Expecting IntIn attribute");
+    }
+
+    //
+    // imtype typemap attributechecks
+    //
+    // Global function imtype typemap attributes check
+    Type imclasstype = typeof(csharp_attributesPINVOKE);
+    {
+      MethodInfo member = (MethodInfo)imclasstype.GetMember("GlobalFunction")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
+        throw new Exception("No IntegerOut attribute for " + member.Name);
+      ParameterInfo parameter = member.GetParameters()[0]; // checking 1st parameter
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntegerInAttribute))
+        throw new Exception("Expecting IntegerIn attribute");
+    }
+    // Constant - imtype typemap attributes check
+    {
+      MethodInfo member = (MethodInfo)imclasstype.GetMember("TESTMACRO_get")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
+        throw new Exception("No IntegerOut attribute for " + member.Name);
+    }
+    // Non-static method imtype typemap attributes check
+    {
+      MethodInfo member = (MethodInfo)imclasstype.GetMember("Stations_Reading")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
+        throw new Exception("No IntegerOut attribute for " + member.Name);
+      ParameterInfo parameter = member.GetParameters()[1]; // checking 2nd parameter
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntegerInAttribute))
+        throw new Exception("Expecting IntegerIn attribute");
+    }
+    // Static method imtype typemap attributes check
+    {
+      MethodInfo member = (MethodInfo)imclasstype.GetMember("Stations_Swindon")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
+        throw new Exception("No IntegerOut attribute for " + member.Name);
+      ParameterInfo parameter = member.GetParameters()[0]; // checking 1st parameter
+      Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+      if (attribute.GetType() != typeof(IntegerInAttribute))
+        throw new Exception("Expecting IntegerIn attribute");
+    }
+
+    //
+    // attributes feature
+    //
+    Type moretype = typeof(MoreStations);
+
+    // Constructor attributes feature check
+    {
+      ConstructorInfo member = (ConstructorInfo)moretype.GetConstructors()[0];
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity1Attribute)) == null)
+        throw new Exception("MoreStations::MoreStations attribute failed");
+    }
+    // Non-static method attributes feature check
+    {
+      MethodInfo member = (MethodInfo)moretype.GetMember("Chippenham")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity2Attribute)) == null)
+        throw new Exception("MoreStations::Chippenham attribute failed");
+    }
+    // Static method attributes feature check
+    {
+      MethodInfo member = (MethodInfo)moretype.GetMember("Bath")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity3Attribute)) == null)
+        throw new Exception("MoreStations::Bath attribute failed");
+    }
+    // Non-static member variable attributes feature check
+    {
+      PropertyInfo member = (PropertyInfo)moretype.GetProperty("Bristol");
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity4Attribute)) == null)
+        throw new Exception("MoreStations::Bristol attribute failed");
+    }
+    // Static member variable attributes feature check
+    {
+      PropertyInfo member = (PropertyInfo)moretype.GetProperty("WestonSuperMare");
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity5Attribute)) == null)
+        throw new Exception("MoreStations::Bristol attribute failed");
+    }
+    // Global function attributes feature check
+    {
+      MethodInfo member = (MethodInfo)globaltype.GetMember("Paddington")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity7Attribute)) == null)
+        throw new Exception("MoreStations::Paddington attribute failed");
+    }
+    // Global variables attributes feature check
+    {
+      PropertyInfo member = (PropertyInfo)globaltype.GetProperty("DidcotParkway");
+      if (Attribute.GetCustomAttribute(member, typeof(InterCity8Attribute)) == null)
+        throw new Exception("MoreStations::Paddington attribute failed");
+    }
+
+    //
+    // csattribute typemaps
+    //
+    // Class csattribute typemap
+    {
+      Object[] attribs = moretype.GetCustomAttributes(true);
+      Eurostar1Attribute tgv = (Eurostar1Attribute)attribs[0];
+      if (tgv == null)
+        throw new Exception("No attribute for MoreStations");
+    }
+    // Nested enum csattribute typemap
+    {
+      MemberInfo member = (MemberInfo)moretype.GetMember("Wales")[0];
+      if (Attribute.GetCustomAttribute(member, typeof(Eurostar2Attribute)) == null)
+        throw new Exception("No attribute for " + member.Name);
+    }
+    // Enum csattribute typemap
+    {
+      Type cymrutype = typeof(Cymru);
+      Object[] attribs = cymrutype.GetCustomAttributes(true);
+      Eurostar3Attribute tgv = (Eurostar3Attribute)attribs[0];
+      if (tgv == null)
+        throw new Exception("No attribute for Cymru");
+    }
+  }
+}
+
+// Custom attribute classes
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class IntInAttribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class IntOutAttribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class IntegerInAttribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class IntegerOutAttribute : Attribute {}
+
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity1Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity2Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity3Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity4Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity5Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity6Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity7Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class InterCity8Attribute : Attribute {}
+
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class Eurostar1Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class Eurostar2Attribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class Eurostar3Attribute : Attribute {}
+
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class ThreadSafeAttribute : Attribute {
+  public ThreadSafeAttribute(bool safe) {}
+  public ThreadSafeAttribute() {}
+}
+
diff --git a/trunk/Examples/test-suite/csharp/csharp_exceptions_runme.cs b/trunk/Examples/test-suite/csharp/csharp_exceptions_runme.cs
new file mode 100644
index 0000000..43585b1
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/csharp_exceptions_runme.cs
@@ -0,0 +1,342 @@
+using System;
+using System.Threading;
+using csharp_exceptionsNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      // %exception tests
+      try {
+        csharp_exceptions.ThrowByValue();
+        throw new Exception("ThrowByValue not working");
+      } catch (DivideByZeroException) {
+      }
+      try {
+        csharp_exceptions.ThrowByReference();
+        throw new Exception("ThrowByReference not working");
+      } catch (DivideByZeroException) {
+      }
+
+      // %csnothrowexception
+      csharp_exceptions.NoThrowException();
+      csharp_exceptions.NullReference(new Ex("should not throw"));
+
+      // exception specifications
+      bool testFailed = false;
+      try {
+        csharp_exceptions.ExceptionSpecificationValue();
+        testFailed = true;
+      } catch (ApplicationException) {
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationValue not working");
+      try {
+        csharp_exceptions.ExceptionSpecificationReference();
+        testFailed = true;
+      } catch (ApplicationException) {
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationReference not working");
+      try {
+        csharp_exceptions.ExceptionSpecificationString();
+        testFailed = true;
+      } catch (ApplicationException e) {
+        if (e.Message != "ExceptionSpecificationString") throw new Exception("ExceptionSpecificationString unexpected message: " + e.Message);
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationString not working");
+      try {
+        csharp_exceptions.ExceptionSpecificationInteger();
+        testFailed = true;
+      } catch (ApplicationException) {
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationInteger not working");
+
+      // null reference exceptions
+      try {
+        csharp_exceptions.NullReference(null);
+        throw new Exception("NullReference not working");
+      } catch (ArgumentNullException) {
+      }
+      try {
+        csharp_exceptions.NullValue(null);
+        throw new Exception("NullValue not working");
+      } catch (ArgumentNullException) {
+      }
+
+      // enums
+      try {
+        csharp_exceptions.ExceptionSpecificationEnumValue();
+        testFailed = true;
+      } catch (ApplicationException) {
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationEnumValue not working");
+      try {
+        csharp_exceptions.ExceptionSpecificationEnumReference();
+        testFailed = true;
+      } catch (ApplicationException) {
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationEnumReference not working");
+
+      // std::string
+      try {
+        csharp_exceptions.NullStdStringValue(null);
+        throw new Exception("NullStdStringValue not working");
+      } catch (ArgumentNullException) {
+      }
+      try {
+        csharp_exceptions.NullStdStringReference(null);
+        throw new Exception("NullStdStringReference not working");
+      } catch (ArgumentNullException) {
+      }
+      try {
+        csharp_exceptions.ExceptionSpecificationStdStringValue();
+        testFailed = true;
+      } catch (ApplicationException e) {
+        if (e.Message != "ExceptionSpecificationStdStringValue") throw new Exception("ExceptionSpecificationStdStringValue unexpected message: " + e.Message);
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationStdStringValue not working");
+      try {
+        csharp_exceptions.ExceptionSpecificationStdStringReference();
+        testFailed = true;
+      } catch (ApplicationException e) {
+        if (e.Message != "ExceptionSpecificationStdStringReference") throw new Exception("ExceptionSpecificationStdStringReference unexpected message: " + e.Message);
+      }
+      if (testFailed) throw new Exception("ExceptionSpecificationStdStringReference not working");
+      
+      // Memory leak check (The C++ exception stack was never unwound in the original approach to throwing exceptions from unmanaged code)
+      try {
+        csharp_exceptions.MemoryLeakCheck();
+        throw new Exception("MemoryLeakCheck not working");
+      } catch (DivideByZeroException) {
+      }
+      if (Counter.count != 0) throw new Exception("Memory leaks when throwing exception. count: " + Counter.count);
+
+      // test exception pending in the csconstruct typemap
+      try {
+        new constructor(null);
+        throw new Exception("constructor 1 not working");
+      } catch (ArgumentNullException) {
+      }
+      try {
+        new constructor();
+        throw new Exception("constructor 2 not working");
+      } catch (ApplicationException) {
+      }
+
+      // test exception pending in the csout typemaps
+      try {
+        csharp_exceptions.ushorttest();
+        throw new Exception("csout not working");
+      } catch (IndexOutOfRangeException) {
+      }
+
+      // test exception pending in the csvarout/csvarin typemaps and canthrow attribute in unmanaged code typemaps (1) global variables
+      // 1) global variables
+      int numberout = 0;
+      try {
+        csharp_exceptions.numberin = -1;
+        throw new Exception("global csvarin not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      csharp_exceptions.numberin = 5;
+      if (csharp_exceptions.numberin != 5)
+        throw new Exception("global numberin not 5");
+      csharp_exceptions.numberout = 20;
+      try {
+        numberout += csharp_exceptions.numberout;
+        throw new Exception("global csvarout not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      // 2) static member variables
+      try {
+        InOutStruct.staticnumberin = -1;
+        throw new Exception("static csvarin not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      InOutStruct.staticnumberin = 5;
+      if (InOutStruct.staticnumberin != 5)
+        throw new Exception("static staticnumberin not 5");
+      InOutStruct.staticnumberout = 20;
+      try {
+        numberout += InOutStruct.staticnumberout;
+        throw new Exception("static csvarout not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      // 3) member variables
+      InOutStruct io = new InOutStruct();
+      try {
+        io.numberin = -1;
+        throw new Exception("member csvarin not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      io.numberin = 5;
+      if (io.numberin != 5)
+        throw new Exception("member numberin not 5");
+      io.numberout = 20;
+      try {
+        numberout += io.numberout;
+        throw new Exception("member csvarout not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      // test SWIG_exception macro - it must return from unmanaged code without executing any further unmanaged code
+      try {
+        csharp_exceptions.exceptionmacrotest(-1);
+        throw new Exception("exception macro not working");
+      } catch (IndexOutOfRangeException) {
+      }
+      if (csharp_exceptions.exception_macro_run_flag)
+        throw new Exception("exceptionmacrotest was executed");
+
+      // test all the types of exceptions
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedApplicationException);
+        throw new Exception("ApplicationException not caught");
+      } catch (ApplicationException e) {
+        if (e.Message != "msg") throw new Exception("ApplicationException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArithmeticException);
+        throw new Exception("ArithmeticException not caught");
+      } catch (ArithmeticException e) {
+        if (e.Message != "msg") throw new Exception("ArithmeticException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedDivideByZeroException);
+        throw new Exception("DivideByZeroException not caught");
+      } catch (DivideByZeroException e) {
+        if (e.Message != "msg") throw new Exception("DivideByZeroException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIndexOutOfRangeException);
+        throw new Exception("IndexOutOfRangeException not caught");
+      } catch (IndexOutOfRangeException e) {
+        if (e.Message != "msg") throw new Exception("IndexOutOfRangeException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedInvalidOperationException);
+        throw new Exception("InvalidOperationException not caught");
+      } catch (InvalidOperationException e) {
+        if (e.Message != "msg") throw new Exception("InvalidOperationException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIOException);
+        throw new Exception("IOException not caught");
+      } catch (System.IO.IOException e) {
+        if (e.Message != "msg") throw new Exception("IOException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedNullReferenceException);
+        throw new Exception("NullReferenceException not caught");
+      } catch (NullReferenceException e) {
+        if (e.Message != "msg") throw new Exception("NullReferenceException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOutOfMemoryException);
+        throw new Exception("OutOfMemoryException not caught");
+      } catch (OutOfMemoryException e) {
+        if (e.Message != "msg") throw new Exception("OutOfMemoryException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOverflowException);
+        throw new Exception("OverflowException not caught");
+      } catch (OverflowException e) {
+        if (e.Message != "msg") throw new Exception("OverflowException msg incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedSystemException);
+        throw new Exception("SystemException not caught");
+      } catch (SystemException e) {
+        if (e.Message != "msg") throw new Exception("SystemException msg incorrect");
+      }
+
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentException);
+        throw new Exception("ArgumentException not caught");
+      } catch (ArgumentException e) {
+        if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentException msg incorrect");
+        if (e.ParamName != "parm") throw new Exception("ArgumentException parm incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentNullException);
+        throw new Exception("ArgumentNullException not caught");
+      } catch (ArgumentNullException e) {
+        if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentNullException msg incorrect");
+        if (e.ParamName != "parm") throw new Exception("ArgumentNullException parm incorrect");
+      }
+      try {
+        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentOutOfRangeException);
+        throw new Exception("ArgumentOutOfRangeException not caught");
+      } catch (ArgumentOutOfRangeException e) {
+        if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentOutOfRangeException msg incorrect");
+        if (e.ParamName != "parm") throw new Exception("ArgumentOutOfRangeException parm incorrect");
+      }
+
+
+      // exceptions in multiple threads test
+      {
+        ThrowsClass throwsClass = new ThrowsClass(1234.5678);
+        const int NUM_THREADS = 8;
+        Thread[] threads = new Thread[NUM_THREADS];
+        TestThread[] testThreads = new TestThread[NUM_THREADS];
+        // invoke the threads
+        for (int i=0; i<NUM_THREADS; i++) {
+            testThreads[i] = new TestThread(throwsClass, i);
+            threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
+            threads[i].Start();
+        }
+        // wait for the threads to finish
+        for (int i=0; i<NUM_THREADS; i++) {
+            threads[i].Join();
+        }
+        for (int i=0; i<NUM_THREADS; i++) {
+            if (testThreads[i].Failed) throw new Exception("Test Failed");
+        }
+      }
+
+
+      // test inner exceptions
+      try {
+        csharp_exceptions.InnerExceptionTest();
+        throw new Exception("InnerExceptionTest exception not caught");
+      } catch (InvalidOperationException e) {
+        if (e.Message != "My OuterException message") throw new Exception("OuterException msg incorrect");
+        if (e.InnerException.Message != "My InnerException message") throw new Exception("InnerException msg incorrect");
+      }
+    }
+    public static string CRLF = "\r\n"; // Some CLR implementations use a CRLF instead of just CR
+}
+
+public class TestThread {
+   private int threadId;
+   private ThrowsClass throwsClass;
+   public bool Failed;
+   public TestThread(ThrowsClass t, int id) {
+       throwsClass = t;
+       threadId = id;
+   }
+   public void Run() {
+     Failed = false;
+     try {
+       for (int i=0; i<6000; i++) { // run test for about 10 seconds on a 1GHz machine (Mono)
+         try {
+           throwsClass.ThrowException(i);
+           throw new Exception("No exception thrown");
+         } catch (ArgumentOutOfRangeException e) {
+           String expectedMessage = "caught:" + i + "\n" + "Parameter name: input";
+           if (e.Message.Replace(runme.CRLF,"\n") != expectedMessage)
+             throw new Exception("Exception message incorrect. Expected:\n[" + expectedMessage + "]\n" + "Received:\n[" + e.Message + "]");
+           if (e.ParamName != "input")
+             throw new Exception("Exception ParamName incorrect. Expected:\n[input]\n" + "Received:\n[" + e.ParamName + "]");
+           if (e.InnerException != null)
+             throw new Exception("Unexpected inner exception");
+         }
+         if (throwsClass.dub != 1234.5678) // simple check which attempts to catch memory corruption
+           throw new Exception("throwsException.dub = " + throwsClass.dub + " expected: 1234.5678");
+       }
+     } catch (Exception e) {
+       Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message);
+       Failed = true;
+     }
+   }
+}
+
+
diff --git a/trunk/Examples/test-suite/csharp/csharp_prepost_runme.cs b/trunk/Examples/test-suite/csharp/csharp_prepost_runme.cs
new file mode 100644
index 0000000..d0bacda
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/csharp_prepost_runme.cs
@@ -0,0 +1,70 @@
+
+using System;
+using System.Reflection;
+using csharp_prepostNamespace;
+
+public class csharp_prepost_runme {
+
+  public static void Main() {
+    {
+      double[] v;
+      csharp_prepost.globalfunction(out v);
+      Assert(v.Length, 3);
+      Assert(v[0], 0.0);
+      Assert(v[1], 1.1);
+      Assert(v[2], 2.2);
+    }
+    {
+      double[] v;
+      new PrePostTest(out v);
+      Assert(v.Length, 2);
+      Assert(v[0], 3.3);
+      Assert(v[1], 4.4);
+    }
+    {
+      double[] v;
+      PrePostTest p = new PrePostTest();
+      p.method(out v);
+      Assert(v.Length, 2);
+      Assert(v[0], 5.5);
+      Assert(v[1], 6.6);
+    }
+    {
+      double[] v;
+      PrePostTest.staticmethod(out v);
+      Assert(v.Length, 2);
+      Assert(v[0], 7.7);
+      Assert(v[1], 8.8);
+    }
+
+    // Check attributes are generated for the constructor helper function
+    {
+      CsinAttributes c = new CsinAttributes(5);
+      Assert(c.getVal(), 500);
+
+      Type type = typeof(CsinAttributes);
+      {
+        MethodInfo member = (MethodInfo)type.GetMember("SwigConstructCsinAttributes", BindingFlags.NonPublic | BindingFlags.Static)[0];
+        if (Attribute.GetCustomAttribute(member, typeof(CustomIntPtrAttribute)) == null)
+          throw new Exception("No CustomIntPtr attribute for " + member.Name);
+        ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
+        if (parameter.Name != "val")
+          throw new Exception("Incorrect parameter name");
+        Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
+        if (attribute.GetType() != typeof(CustomIntAttribute))
+          throw new Exception("Expecting CustomInt attribute");
+      }
+    }
+  }
+  private static void Assert(double d1, double d2) {
+    if (d1 != d2)
+      throw new Exception("assertion failure. " + d1 + " != " + d2);
+  }
+}
+
+// Custom attribute classes
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class CustomIntAttribute : Attribute {}
+
+[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
+public class CustomIntPtrAttribute : Attribute {}
diff --git a/trunk/Examples/test-suite/csharp/csharp_typemaps_runme.cs b/trunk/Examples/test-suite/csharp/csharp_typemaps_runme.cs
new file mode 100644
index 0000000..846644f
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/csharp_typemaps_runme.cs
@@ -0,0 +1,113 @@
+using System;
+using System.Threading;
+using csharp_typemapsNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    // Test the C# types customisation by modifying the default char * typemaps to return a single char
+    Things things = new Things();
+    System.Text.StringBuilder initialLetters = new System.Text.StringBuilder();
+    char myChar = things.start("boo");
+    initialLetters.Append(myChar);
+    myChar = Things.stop("hiss");
+    initialLetters.Append(myChar);
+    myChar = csharp_typemaps.partyon("off");
+    initialLetters.Append(myChar);
+    if (initialLetters.ToString() != "bho")
+      throw new Exception("initial letters failed");
+
+    // $csinput expansion
+    csharp_typemaps.myInt = 1;
+    try {
+      csharp_typemaps.myInt = -1;
+      throw new Exception("oops");
+    } catch (ApplicationException) {
+    }
+
+    // Eager garbage collector test
+    {
+      const int NUM_THREADS = 8;
+      Thread[] threads = new Thread[NUM_THREADS];
+      TestThread[] testThreads = new TestThread[NUM_THREADS];
+      // invoke the threads
+      for (int i=0; i<NUM_THREADS; i++) {
+        testThreads[i] = new TestThread(i);
+        threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
+        threads[i].Start();
+      }
+      // wait for the threads to finish
+      for (int i=0; i<NUM_THREADS; i++) {
+        threads[i].Join();
+      }
+      for (int i=0; i<NUM_THREADS; i++) {
+        if (testThreads[i].Failed) throw new Exception("Test Failed");
+      }
+    }
+
+  }
+}
+
+
+public class TestThread {
+   private int threadId;
+   public bool Failed;
+   public TestThread(int id) {
+       threadId = id;
+   }
+   public void Run() {
+     Failed = false;
+     try {
+       // Older versions of SWIG used IntPtr instead of HandleRef to hold the underlying
+       // C++ pointer, so this test would (usually) fail as the garbage collector would
+       // sometimes collect the Number class while it was being used in unmanaged code
+       for (int i=0; i<5000; i++) { // run test for a few seconds
+         {
+           Obj obj = new Obj();
+           Number n = new Number(i);
+           Number triple = obj.triple(n);
+           if (triple.Value != i*3)
+             throw new ApplicationException("triple failed: " + triple.Value);
+         }
+         {
+           Obj obj = new Obj();
+           Number n = new Number(i);
+           Number times6 = obj.times6(n);
+           if (times6.Value != i*6)
+             throw new ApplicationException("times6 failed: " + times6.Value);
+         }
+         {
+           Obj obj = new Obj();
+           Number n = new Number(i);
+           Number times9 = obj.times9(n);
+           if (times9.Value != i*9)
+             throw new ApplicationException("times9 failed: " + times9.Value);
+         }
+         {
+           Number n = new Number(i);
+           Number quadruple = csharp_typemaps.quadruple(n);
+           if (quadruple.Value != i*4)
+             throw new ApplicationException("quadruple failed: " + quadruple.Value);
+         }
+         {
+           Number n = new Number(i);
+           Number times8 = csharp_typemaps.times8(n);
+           if (times8.Value != i*8)
+             throw new ApplicationException("times8 failed: " + times8.Value);
+         }
+         {
+           Number n = new Number(i);
+           Number times12 = csharp_typemaps.times12(n);
+           if (times12.Value != i*12)
+             throw new ApplicationException("times12 failed: " + times12.Value);
+         }
+       }
+     } catch (Exception e) {
+       Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message);
+       Failed = true;
+     }
+   }
+}
+
+
diff --git a/trunk/Examples/test-suite/csharp/default_args_runme.cs b/trunk/Examples/test-suite/csharp/default_args_runme.cs
new file mode 100644
index 0000000..68ea0e8
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/default_args_runme.cs
@@ -0,0 +1,143 @@
+using System;
+using default_argsNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      if (default_args.anonymous() != 7771)
+        throw new Exception("anonymous (1) failed");
+      if (default_args.anonymous(1234) != 1234)
+        throw new Exception("anonymous (2) failed");
+
+      if (default_args.booltest() != true)
+        throw new Exception("booltest (1) failed");
+      if (default_args.booltest(true) != true)
+        throw new Exception("booltest (2) failed");
+      if (default_args.booltest(false) != false)
+        throw new Exception("booltest (3) failed");
+
+      EnumClass ec = new EnumClass();
+      if (ec.blah() != true)
+        throw new Exception("EnumClass failed");
+
+      if (default_args.casts1() != null)
+        throw new Exception("casts1 failed");
+
+      if (default_args.casts2() != "Hello")
+        throw new Exception("casts2 failed");
+
+      if (default_args.casts1("Ciao") != "Ciao")
+        throw new Exception("casts1 not default failed");
+
+      if (default_args.chartest1() != 'x')
+        throw new Exception("chartest1 failed");
+
+      if (default_args.chartest2() != '\0')
+        throw new Exception("chartest2 failed");
+
+      if (default_args.chartest1('y') != 'y')
+        throw new Exception("chartest1 not default failed");
+
+      if (default_args.chartest1('y') != 'y')
+        throw new Exception("chartest1 not default failed");
+
+      if (default_args.reftest1() != 42)
+        throw new Exception("reftest1 failed");
+
+      if (default_args.reftest1(400) != 400)
+        throw new Exception("reftest1 not default failed");
+
+      if (default_args.reftest2() != "hello")
+        throw new Exception("reftest2 failed");
+
+      // rename
+      Foo foo = new Foo();
+      foo.newname(); 
+      foo.newname(10); 
+      foo.renamed3arg(10, 10.0); 
+      foo.renamed2arg(10); 
+      foo.renamed1arg(); 
+
+      // exception specifications
+      try {
+        default_args.exceptionspec();
+        throw new Exception("exceptionspec 1 failed");
+      } catch (Exception) {
+      }
+      try {
+        default_args.exceptionspec(-1);
+        throw new Exception("exceptionspec 2 failed");
+      } catch (Exception) {
+      }
+      try {
+        default_args.exceptionspec(100);
+        throw new Exception("exceptionspec 3 failed");
+      } catch (Exception) {
+      }
+      Except ex = new Except(false);
+      try {
+        ex.exspec();
+        throw new Exception("exspec 1 failed");
+      } catch (Exception) {
+      }
+      try {
+        ex.exspec(-1);
+        throw new Exception("exspec 2 failed");
+      } catch (Exception) {
+      }
+      try {
+        ex.exspec(100);
+        throw new Exception("exspec 3 failed");
+      } catch (Exception) {
+      }
+      try {
+        ex = new Except(true);
+        throw new Exception("Except constructor 1 failed");
+      } catch (Exception) {
+      }
+      try {
+        ex = new Except(true, -2);
+        throw new Exception("Except constructor 2 failed");
+      } catch (Exception) {
+      }
+
+      // Default parameters in static class methods
+      if (Statics.staticmethod() != 10+20+30)
+        throw new Exception("staticmethod 1 failed");
+      if (Statics.staticmethod(100) != 100+20+30)
+        throw new Exception("staticmethod 2 failed");
+      if (Statics.staticmethod(100,200,300) != 100+200+300)
+        throw new Exception("staticmethod 3 failed");
+
+
+      Tricky tricky = new Tricky();
+      if (tricky.privatedefault() != 200)
+        throw new Exception("privatedefault failed");
+      if (tricky.protectedint() != 2000)
+        throw new Exception("protectedint failed");
+      if (tricky.protecteddouble() != 987.654)
+        throw new Exception("protecteddouble failed");
+      if (tricky.functiondefault() != 500)
+        throw new Exception("functiondefault failed");
+      if (tricky.contrived() != 'X')
+        throw new Exception("contrived failed");
+
+      if (default_args.constructorcall().val != -1)
+        throw new Exception("constructorcall test 1 failed");
+
+      if (default_args.constructorcall(new Klass(2222)).val != 2222)
+        throw new Exception("constructorcall test 2 failed");
+
+      if (default_args.constructorcall(new Klass()).val != -1)
+        throw new Exception("constructorcall test 3 failed");
+
+      // const methods 
+      ConstMethods cm = new ConstMethods();
+      if (cm.coo() != 20)
+        throw new Exception("coo test 1 failed");
+      if (cm.coo(1.0) != 20)
+        throw new Exception("coo test 2 failed");
+    }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/default_constructor_runme.cs b/trunk/Examples/test-suite/csharp/default_constructor_runme.cs
new file mode 100644
index 0000000..acd62dc
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/default_constructor_runme.cs
@@ -0,0 +1,24 @@
+using System;
+using default_constructorNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+        // calling protected destructor test
+        try {
+            using (G g = new G()) {
+            }
+            throw new Exception("Protected destructor exception should have been thrown");
+        } catch (MethodAccessException) {
+        }
+
+        // calling private destructor test
+        try {
+            using (FFF f = new FFF()) {
+            }
+            throw new Exception("Private destructor exception should have been thrown");
+        } catch (MethodAccessException) {
+        }
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/director_classes_runme.cs b/trunk/Examples/test-suite/csharp/director_classes_runme.cs
new file mode 100644
index 0000000..1125614
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/director_classes_runme.cs
@@ -0,0 +1,180 @@
+/*
+This test demonstrates director classes when the types are classes.
+Shown are virtual function calls which use classes passed by:
+  - Value
+  - Reference
+  - Pointer
+as both parameters and return values.
+The test also demonstrates directors used with:
+  - method overloading
+  - default parameters
+Note: Methods with default parameters that call up from C++ cannot call
+the overloaded C# methods, see DefaultParms method.
+
+Expected output if PrintDebug enabled:
+------------ Start ------------
+Base - Val(444.555)
+Base - Ref(444.555)
+Base - Ptr(444.555)
+Base - FullyOverloaded(int 10)
+Base - FullyOverloaded(bool 1)
+Base - SemiOverloaded(int -678)
+Base - SemiOverloaded(bool 1)
+Base - DefaultParms(10, 2.2)
+Base - DefaultParms(10, 1.1)
+--------------------------------
+Derived - Val(444.555)
+Derived - Ref(444.555)
+Derived - Ptr(444.555)
+Derived - FullyOverloaded(int 10)
+Derived - FullyOverloaded(bool 1)
+Derived - SemiOverloaded(int -678)
+Base - SemiOverloaded(bool 1)
+Derived - DefaultParms(10, 2.2)
+Derived - DefaultParms(10, 1.1)
+--------------------------------
+CSharpDerived - Val(444.555)
+CSharpDerived - Ref(444.555)
+CSharpDerived - Ptr(444.555)
+CSharpDerived - FullyOverloaded(int 10)
+CSharpDerived - FullyOverloaded(bool True)
+CSharpDerived - SemiOverloaded(-678)
+Base - SemiOverloaded(bool 1)
+CSharpDerived - DefaultParms(10, 2.2)
+CSharpDerived - DefaultParms(10, 1.1)
+------------ Finish ------------
+*/
+
+using System;
+
+namespace director_classesNamespace {
+
+public class runme
+{
+  static void Main() 
+  {
+    runme r = new runme();
+    r.run();
+  }
+
+  void run()
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("------------ Start ------------ ");
+
+    Caller myCaller = new Caller();
+
+    // test C++ base class
+    using (Base myBase = new Base(100.0))
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    if (director_classes.PrintDebug) Console.WriteLine("--------------------------------");
+
+    // test vanilla C++ wrapped derived class
+    using (Base myBase = new Derived(200.0))
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    if (director_classes.PrintDebug) Console.WriteLine("--------------------------------");
+
+    // test director / C# derived class
+    using (Base myBase = new CSharpDerived(300.0))
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    if (director_classes.PrintDebug) Console.WriteLine("------------ Finish ------------ ");
+  }
+
+  void makeCalls(Caller myCaller, Base myBase)
+  {
+    string NAMESPACE = "director_classesNamespace.";
+    myCaller.set(myBase);
+
+    DoubleHolder dh = new DoubleHolder(444.555);
+
+    // Class pointer, reference and pass by value tests
+    if (myCaller.ValCall(dh).val != dh.val) throw new Exception("failed");
+    if (myCaller.RefCall(dh).val != dh.val) throw new Exception("failed");
+    if (myCaller.PtrCall(dh).val != dh.val) throw new Exception("failed");
+
+    // Fully overloaded method test (all methods in base class are overloaded)
+    if (NAMESPACE + myCaller.FullyOverloadedCall(10) != myBase.GetType() + "::FullyOverloaded(int)") throw new Exception("failed");
+    if (NAMESPACE + myCaller.FullyOverloadedCall(true) != myBase.GetType() + "::FullyOverloaded(bool)") throw new Exception("failed");
+
+    // Semi overloaded method test (some methods in base class are overloaded)
+    if (NAMESPACE + myCaller.SemiOverloadedCall(-678) != myBase.GetType() + "::SemiOverloaded(int)") throw new Exception("failed");
+    if (myCaller.SemiOverloadedCall(true) != "Base" + "::SemiOverloaded(bool)") throw new Exception("failed");
+
+    // Default parameters methods test
+    if (NAMESPACE + myCaller.DefaultParmsCall(10, 2.2) != myBase.GetType() + "::DefaultParms(int, double)") throw new Exception("failed");
+    if (myBase.GetType() == typeof(CSharpDerived)) { // special handling for C# derived classes, there is no way to do this any other way
+      if (NAMESPACE + myCaller.DefaultParmsCall(10) != myBase.GetType() + "::DefaultParms(int, double)") throw new Exception("failed");
+    } else {
+      if (NAMESPACE + myCaller.DefaultParmsCall(10) != myBase.GetType() + "::DefaultParms(int)") throw new Exception("failed");
+    }
+
+    myCaller.reset();
+  }
+}
+
+public class CSharpDerived : Base
+{
+  public CSharpDerived(double dd)
+    : base(dd)
+  {
+  }
+
+  public override DoubleHolder Val(DoubleHolder x)
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - Val({0})", x.val);
+    return x;
+  }
+  public override DoubleHolder Ref(DoubleHolder x)
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - Ref({0})", x.val);
+    return x;
+  }
+  public override DoubleHolder Ptr(DoubleHolder x)
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - Ptr({0})", x.val);
+    return x;
+  }
+  public override String FullyOverloaded(int x)
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - FullyOverloaded(int {0})", x);
+    return "CSharpDerived::FullyOverloaded(int)";
+  }
+  public override String FullyOverloaded(bool x)
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - FullyOverloaded(bool {0})", x);
+    return "CSharpDerived::FullyOverloaded(bool)";
+  }
+  // Note no SemiOverloaded(bool x) method
+  public override String SemiOverloaded(int x)
+  {
+    String ret = "CSharpDerived::SemiOverloaded(int)";
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - SemiOverloaded({0})", x);
+    return ret;
+  }
+  public override String DefaultParms(int x, double y)
+  {
+    String ret = "CSharpDerived::DefaultParms(int, double)";
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - DefaultParms({0}, {1})", x, y);
+    return ret;
+  }
+  // Note the following method can never be called from unmanaged code.
+  // It is here only for code that calls it directly from managed code.
+  // But should always be defined to ensure behaviour is consistent
+  // independent of where DefaultParsms is called from (managed or unmanaged code).
+  // Note this method can never be called from unmanaged code
+  public override String DefaultParms(int x)
+  {
+    if (director_classes.PrintDebug) Console.WriteLine("CSharpDerived - DefaultParms({0})", x);
+    return DefaultParms(x, 1.1/*use C++ default here*/);
+  }
+}
+
+}
diff --git a/trunk/Examples/test-suite/csharp/director_classic_runme.cs b/trunk/Examples/test-suite/csharp/director_classic_runme.cs
new file mode 100755
index 0000000..7220437
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/director_classic_runme.cs
@@ -0,0 +1,314 @@
+using System;
+
+namespace director_classicNamespace {
+
+public class runme
+{
+  static void Main() 
+  {
+    { 
+      Person person = new Person();
+      check(person, "Person");
+      person.Dispose();
+    }
+    { 
+      Person person = new Child();
+      check(person, "Child");
+      person.Dispose();
+    }
+    { 
+      Person person = new GrandChild();
+      check(person, "GrandChild"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangPerson();
+      check(person, "TargetLangPerson"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangChild();
+      check(person, "TargetLangChild"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangGrandChild();
+      check(person, "TargetLangGrandChild"); 
+      person.Dispose();
+    }
+
+    // Semis - don't override id() in target language
+    { 
+      Person person = new TargetLangSemiPerson();
+      check(person, "Person"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangSemiChild();
+      check(person, "Child"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangSemiGrandChild();
+      check(person, "GrandChild"); 
+      person.Dispose();
+    }
+
+    // Orphans - don't override id() in C++
+    { 
+      Person person = new OrphanPerson();
+      check(person, "Person"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new OrphanChild();
+      check(person, "Child"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangOrphanPerson();
+      check(person, "TargetLangOrphanPerson"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangOrphanChild();
+      check(person, "TargetLangOrphanChild"); 
+      person.Dispose();
+    }
+
+    // Duals - id() makes an upcall to the base id()
+    { 
+      Person person = new TargetLangDualPerson();
+      check(person, "TargetLangDualPerson + Person"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangDualChild();
+      check(person, "TargetLangDualChild + Child"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangDualGrandChild();
+      check(person, "TargetLangDualGrandChild + GrandChild"); 
+      person.Dispose();
+    }
+
+    // Mix Orphans and Duals
+    { 
+      Person person = new TargetLangDualOrphanPerson();
+      check(person, "TargetLangDualOrphanPerson + Person"); 
+      person.Dispose();
+    }
+    { 
+      Person person = new TargetLangDualOrphanChild();
+      check(person, "TargetLangDualOrphanChild + Child"); 
+      person.Dispose();
+    }
+  }
+
+  static void check(Person person, String expected) {
+    String ret;
+    // Normal target language polymorphic call
+    ret = person.id();
+    if (debug) 
+      Console.WriteLine(ret);
+    if (ret != expected)
+      throw new Exception("Failed. Received: " + ret + " Expected: " + expected);
+
+    // Polymorphic call from C++
+    Caller caller = new Caller();
+    caller.setCallback(person);
+    ret = caller.call();
+    if (debug) 
+      Console.WriteLine(ret);
+    if (ret != expected)
+      throw new Exception("Failed. Received: " + ret + " Expected: " + expected);
+
+    // Polymorphic call of object created in target language and passed to C++ and back again
+    Person baseclass = caller.baseClass();
+    ret = baseclass.id();
+    if (debug) 
+      Console.WriteLine(ret);
+    if (ret != expected)
+      throw new Exception("Failed. Received: " + ret + " Expected: " + expected);
+
+    caller.resetCallback();
+    if (debug) 
+      Console.WriteLine("----------------------------------------");
+  }
+  static bool debug = false;
+}
+
+public class TargetLangPerson : Person
+{
+  public TargetLangPerson()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangPerson";
+    return identifier;
+  }
+}
+
+public class TargetLangChild : Child
+{
+  public TargetLangChild()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangChild";
+    return identifier;
+  }
+}
+
+public class TargetLangGrandChild : GrandChild
+{
+  public TargetLangGrandChild()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangGrandChild";
+    return identifier;
+  }
+}
+
+// Semis - don't override id() in target language
+public class TargetLangSemiPerson : Person
+{
+  public TargetLangSemiPerson()
+    : base()
+  {
+  }
+  // No id() override
+}
+
+public class TargetLangSemiChild : Child
+{
+  public TargetLangSemiChild()
+    : base()
+  {
+  }
+  // No id() override
+}
+
+public class TargetLangSemiGrandChild : GrandChild
+{
+  public TargetLangSemiGrandChild()
+    : base()
+  {
+  }
+  // No id() override
+}
+
+// Orphans - don't override id() in C++
+class TargetLangOrphanPerson : OrphanPerson
+{
+  public TargetLangOrphanPerson()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangOrphanPerson";
+    return identifier;
+  }
+}
+
+class TargetLangOrphanChild : OrphanChild
+{
+  public TargetLangOrphanChild()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangOrphanChild";
+    return identifier;
+  }
+}
+
+
+// Duals - id() makes an upcall to the base id()
+class TargetLangDualPerson : Person
+{
+  public TargetLangDualPerson()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangDualPerson + " + base.id();
+    return identifier;
+  }
+}
+
+class TargetLangDualChild : Child
+{
+  public TargetLangDualChild()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangDualChild + " + base.id();
+    return identifier;
+  }
+}
+
+class TargetLangDualGrandChild : GrandChild
+{
+  public TargetLangDualGrandChild()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangDualGrandChild + " + base.id();
+    return identifier;
+  }
+}
+
+// Mix Orphans and Duals
+class TargetLangDualOrphanPerson : OrphanPerson
+{
+  public TargetLangDualOrphanPerson()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangDualOrphanPerson + " + base.id();
+    return identifier;
+  }
+}
+
+class TargetLangDualOrphanChild : OrphanChild
+{
+  public TargetLangDualOrphanChild()
+    : base()
+  {
+  }
+
+  public override String id()
+  {
+    String identifier = "TargetLangDualOrphanChild + " + base.id();
+    return identifier;
+  }
+}
+
+}
diff --git a/trunk/Examples/test-suite/csharp/director_ignore_runme.cs b/trunk/Examples/test-suite/csharp/director_ignore_runme.cs
new file mode 100644
index 0000000..481b1f4
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/director_ignore_runme.cs
@@ -0,0 +1,57 @@
+using System;
+
+namespace director_ignoreNamespace {
+
+public class runme
+{
+  static void Main() 
+  {
+    runme r = new runme();
+    r.run();
+  }
+
+  void run()
+  {
+    // Just check the classes can be instantiated and other methods work as expected
+    DIgnoresDerived a = new DIgnoresDerived();
+    if (a.Triple(5) != 15)
+      throw new Exception("Triple failed");
+    DAbstractIgnoresDerived b = new DAbstractIgnoresDerived();
+    if (b.Quadruple(5) != 20)
+      throw new Exception("Quadruple failed");
+  }
+}
+
+class DIgnoresDerived : DIgnores
+{
+  public DIgnoresDerived() : base()
+  {
+  }
+
+  // These will give a warning if the %ignore is not working
+  public virtual int OverloadedMethod(int n, int xoffset, int yoffset) { return 0; }
+  public virtual int OverloadedMethod(int n, int xoffset) { return 0; }
+  public virtual int OverloadedMethod(int n) { return 0; }
+
+  public virtual int OverloadedProtectedMethod(int n, int xoffset, int yoffset) { return 0; }
+  public virtual int OverloadedProtectedMethod(int n, int xoffset) { return 0; }
+  public virtual int OverloadedProtectedMethod(int n) { return 0; }
+}
+
+class DAbstractIgnoresDerived : DAbstractIgnores
+{
+  public DAbstractIgnoresDerived() : base()
+  {
+  }
+
+  // These will give a warning if the %ignore is not working
+  public virtual int OverloadedMethod(int n, int xoffset, int yoffset) { return 0; }
+  public virtual int OverloadedMethod(int n, int xoffset) { return 0; }
+  public virtual int OverloadedMethod(int n) { return 0; }
+
+  public virtual int OverloadedProtectedMethod(int n, int xoffset, int yoffset) { return 0; }
+  public virtual int OverloadedProtectedMethod(int n, int xoffset) { return 0; }
+  public virtual int OverloadedProtectedMethod(int n) { return 0; }
+}
+
+}
diff --git a/trunk/Examples/test-suite/csharp/director_primitives_runme.cs b/trunk/Examples/test-suite/csharp/director_primitives_runme.cs
new file mode 100644
index 0000000..0a8f705
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/director_primitives_runme.cs
@@ -0,0 +1,127 @@
+/*
+  This test program shows a C# class CSharpDerived inheriting from Base. Three types of classes are created
+  and the virtual methods called to demonstrate:
+  1) Wide variety of primitive types
+  2) Calling methods with zero, one or more parameters
+  3) Director methods that are not overridden in C#
+  4) Director classes that are not overridden at all in C#, ie non-director behaviour is as expected for director classes
+  5) Inheritance hierarchy using director methods
+  6) Return types working as well as parameters
+
+  The Caller class is a tester class, which calls the virtual functions from C++.
+*/
+
+using System;
+using director_primitivesNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    runme r = new runme();
+    r.run();
+  }
+
+  void run()
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("------------ Start ------------ ");
+
+    Caller myCaller = new Caller();
+
+    // test C++ base class
+    using (Base myBase = new Base(100.0))
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    if (director_primitives.PrintDebug) Console.WriteLine("--------------------------------");
+
+    // test vanilla C++ wrapped derived class
+    using (Base myBase = new Derived(200.0))
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    if (director_primitives.PrintDebug) Console.WriteLine("--------------------------------");
+
+    // test director / C# derived class
+    using (Base myBase = new CSharpDerived(300.0))
+    {
+      makeCalls(myCaller, myBase);
+    }
+
+    if (director_primitives.PrintDebug) Console.WriteLine("------------ Finish ------------ ");
+  }
+
+  void makeCalls(Caller myCaller, Base myBase)
+  {
+    myCaller.set(myBase);
+
+    myCaller.NoParmsMethodCall();
+    if (myCaller.BoolMethodCall(true) != true) throw new Exception("failed");
+    if (myCaller.BoolMethodCall(false) != false) throw new Exception("failed");
+    if (myCaller.IntMethodCall(-123) != -123) throw new Exception("failed");
+    if (myCaller.UIntMethodCall(123) != 123) throw new Exception("failed");
+    if (myCaller.FloatMethodCall((float)-123.456) != (float)-123.456) throw new Exception("failed");
+    if (myCaller.CharPtrMethodCall("test string") != "test string") throw new Exception("failed");
+    if (myCaller.ConstCharPtrMethodCall("another string") != "another string") throw new Exception("failed");
+    if (myCaller.EnumMethodCall(HShadowMode.HShadowHard) != HShadowMode.HShadowHard) throw new Exception("failed");
+    myCaller.ManyParmsMethodCall(true, -123, 123, (float)123.456, "test string", "another string", HShadowMode.HShadowHard);
+    myCaller.NotOverriddenMethodCall();
+
+    myCaller.reset();
+  }
+}
+
+public class CSharpDerived : Base
+{
+  public CSharpDerived(double dd)
+    : base(dd)
+  {
+  }
+
+  public override void NoParmsMethod()
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - NoParmsMethod()");
+  }
+  public override bool BoolMethod(bool x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - BoolMethod({0})", x);
+    return x;
+  }
+  public override int IntMethod(int x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - IntMethod({0})", x);
+    return x;
+  }
+  public override uint UIntMethod(uint x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
+    return x;
+  }
+  public override float FloatMethod(float x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - FloatMethod({0})", x);
+    return x;
+  }
+  public override string CharPtrMethod(string x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - CharPtrMethod({0})", x);
+    return x;
+  }
+  public override string ConstCharPtrMethod(string x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - ConstCharPtrMethod({0})", x);
+    return x;
+  }
+  public override HShadowMode EnumMethod(HShadowMode x)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - EnumMethod({0})", x);
+    return x;
+  }
+  public override void ManyParmsMethod(bool b, int i, uint u, float f, string c, string cc, HShadowMode h)
+  {
+    if (director_primitives.PrintDebug) Console.WriteLine("CSharpDerived - ManyParmsMethod({0}, {1}, {2}, {3}, {4}, {5}, {6})", b, i, u, f, c, cc, h);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/director_protected_runme.cs b/trunk/Examples/test-suite/csharp/director_protected_runme.cs
new file mode 100644
index 0000000..ee4697b
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/director_protected_runme.cs
@@ -0,0 +1,72 @@
+using System;
+
+namespace director_protectedNamespace {
+
+public class runme
+{
+  static void Main() 
+  {
+    runme r = new runme();
+    r.run();
+  }
+
+  void run()
+  {
+    Bar b  = new Bar();
+    Foo f = b.create();
+    FooBar fb = new FooBar();
+    FooBar2 fb2 = new FooBar2();
+
+    String s;
+    s = fb.used();
+    if ( s != ("Foo::pang();Bar::pong();Foo::pong();FooBar::ping();"))
+      throw new Exception("bad FooBar::used" + " - " + s);
+
+    s = fb2.used();
+    if ( s != ("FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();"))
+      throw new Exception("bad FooBar2::used");
+
+    s = b.pong();
+    if ( s != ("Bar::pong();Foo::pong();Bar::ping();"))
+      throw new Exception("bad Bar::pong");
+
+    s = f.pong();
+    if ( s != ("Bar::pong();Foo::pong();Bar::ping();"))
+      throw new Exception("bad Foo::pong");
+
+    s = fb.pong();
+    if ( s != ("Bar::pong();Foo::pong();FooBar::ping();"))
+      throw new Exception("bad FooBar::pong");
+  }
+}
+
+class FooBar : Bar
+{
+  public FooBar() : base()
+  {
+  }
+
+  protected override String ping()
+  {
+    return "FooBar::ping();";
+  }
+}
+
+class FooBar2 : Bar
+{
+  public FooBar2() : base()
+  {
+  }
+
+  protected override String ping()
+  {
+    return "FooBar2::ping();";
+  }
+
+  protected override String pang()
+  {
+    return "FooBar2::pang();";
+  }
+}
+
+}
diff --git a/trunk/Examples/test-suite/csharp/director_string_runme.cs b/trunk/Examples/test-suite/csharp/director_string_runme.cs
new file mode 100644
index 0000000..0b1b04f
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/director_string_runme.cs
@@ -0,0 +1,53 @@
+using System;
+using director_stringNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    runme r = new runme();
+    r.run();
+  }
+
+  void run()
+  {
+    String s;
+
+    director_string_A c = new director_string_A("hi");
+    for (int i=0; i<3; i++) {
+      s = c.call_get(i);
+      Object ii = i;
+      if (s != ii.ToString()) throw new Exception("director_string_A.get(" + i + ") failed. Got:" + s);
+    }
+
+    director_string_B b = new director_string_B("hello");
+
+    s = b.call_get_first();
+    if (s != "director_string_B.get_first") throw new Exception("call_get_first() failed");
+
+    s = b.call_get(0);
+    if (s != "director_string_B.get: hello") throw new Exception("get(0) failed");
+  }
+}
+
+class director_string_B : A {
+    public director_string_B(String first) : base(first) {
+    }
+    public override String get_first() {
+      return "director_string_B.get_first";
+    }
+  
+    public override String get(int n) {
+      return "director_string_B.get: " + base.get(n);
+    }
+}
+
+class director_string_A : A {
+    public director_string_A(String first) : base(first) {
+    }
+    public override String get(int n) {
+      Object nn = n;
+      return nn.ToString();
+    }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/enum_thorough_runme.cs b/trunk/Examples/test-suite/csharp/enum_thorough_runme.cs
new file mode 100755
index 0000000..765347e
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/enum_thorough_runme.cs
@@ -0,0 +1,371 @@
+using System;
+using enum_thoroughNamespace;
+
+public class runme {
+  static void Main() {
+    {
+      // Anonymous enums
+      int i = enum_thorough.AnonEnum1;
+      if (enum_thorough.ReallyAnInteger != 200) throw new Exception("Test Anon 1 failed");
+      i += enum_thorough.AnonSpaceEnum1;
+      i += AnonStruct.AnonStructEnum1;
+    }
+    {
+      colour red = colour.red;
+      enum_thorough.colourTest1(red);
+      enum_thorough.colourTest2(red);
+      enum_thorough.colourTest3(red);
+      enum_thorough.colourTest4(red);
+      enum_thorough.myColour = red;
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed speed = SpeedClass.speed.slow;
+      if (s.speedTest1(speed) != speed) throw new Exception("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new Exception("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new Exception("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new Exception("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new Exception("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new Exception("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new Exception("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new Exception("speedTest 8 failed");
+
+      if (enum_thorough.speedTest1(speed) != speed) throw new Exception("speedTest Global 1 failed");
+      if (enum_thorough.speedTest2(speed) != speed) throw new Exception("speedTest Global 2 failed");
+      if (enum_thorough.speedTest3(speed) != speed) throw new Exception("speedTest Global 3 failed");
+      if (enum_thorough.speedTest4(speed) != speed) throw new Exception("speedTest Global 4 failed");
+      if (enum_thorough.speedTest5(speed) != speed) throw new Exception("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed slow = SpeedClass.speed.slow;
+      SpeedClass.speed lightning = SpeedClass.speed.lightning;
+
+      if (s.mySpeedtd1 != slow) throw new Exception("mySpeedtd1 1 failed");
+      if ((int)s.mySpeedtd1 != 10) throw new Exception("mySpeedtd1 2 failed");
+
+      s.mySpeedtd1 = lightning;
+      if (s.mySpeedtd1 != lightning) throw new Exception("mySpeedtd1 3 failed");
+      if ((int)s.mySpeedtd1 != 31) throw new Exception("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest 1 failed");
+    }
+    {
+      twonames val = twonames.TwoNames2;
+      if (enum_thorough.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
+      if (enum_thorough.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
+      if (enum_thorough.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      TwoNamesStruct.twonames val = TwoNamesStruct.twonames.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
+    }
+    {
+      namedanonspace val = namedanonspace.NamedAnonSpace2;
+      if (enum_thorough.namedanonspaceTest1(val) != val) throw new Exception("namedanonspaceTest 1 failed");
+      if (enum_thorough.namedanonspaceTest2(val) != val) throw new Exception("namedanonspaceTest 2 failed");
+      if (enum_thorough.namedanonspaceTest3(val) != val) throw new Exception("namedanonspaceTest 3 failed");
+      if (enum_thorough.namedanonspaceTest4(val) != val) throw new Exception("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new Exception("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new Exception("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new Exception("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new Exception("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new Exception("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new Exception("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new Exception("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new Exception("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new Exception("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new Exception("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new Exception("scientistsTest J failed");
+
+      if (enum_thorough.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest Global 1 failed");
+      if (enum_thorough.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest Global 2 failed");
+      if (enum_thorough.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest Global 3 failed");
+      if (enum_thorough.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest Global 4 failed");
+      if (enum_thorough.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest Global 5 failed");
+      if (enum_thorough.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest Global 6 failed");
+      if (enum_thorough.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest Global 7 failed");
+      if (enum_thorough.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      TClassInt.scientists bell = TClassInt.scientists.bell;
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new Exception("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new Exception("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new Exception("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new Exception("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new Exception("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new Exception("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new Exception("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new Exception("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new Exception("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new Exception("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new Exception("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new Exception("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new Exception("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new Exception("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new Exception("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new Exception("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new Exception("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new Exception("scientistsOtherTest 7 failed");
+
+      if (enum_thorough.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest Global 1 failed");
+      if (enum_thorough.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest Global 2 failed");
+      if (enum_thorough.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest Global 3 failed");
+      if (enum_thorough.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest Global 4 failed");
+      if (enum_thorough.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest Global 5 failed");
+      if (enum_thorough.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest Global 6 failed");
+      if (enum_thorough.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough.scientistsNameSpaceTest8(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough.scientistsNameSpaceTest9(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough.scientistsNameSpaceTestA(bell) != bell) throw new Exception("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough.scientistsNameSpaceTestB(bell) != bell) throw new Exception("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough.scientistsNameSpaceTestC(bell) != bell) throw new Exception("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough.scientistsNameSpaceTestD(bell) != bell) throw new Exception("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough.scientistsNameSpaceTestE(bell) != bell) throw new Exception("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough.scientistsNameSpaceTestF(bell) != bell) throw new Exception("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough.scientistsNameSpaceTestG(bell) != bell) throw new Exception("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough.scientistsNameSpaceTestH(bell) != bell) throw new Exception("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough.scientistsNameSpaceTestI(bell) != bell) throw new Exception("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough.scientistsNameSpaceTestJ(bell) != bell) throw new Exception("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough.scientistsNameSpaceTestK(bell) != bell) throw new Exception("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough.scientistsNameSpaceTestL(bell) != bell) throw new Exception("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      newname val = newname.argh;
+      if (enum_thorough.renameTest1(val) != val) throw new Exception("renameTest Global 1 failed");
+      if (enum_thorough.renameTest2(val) != val) throw new Exception("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest Global 3 failed");
+      if (enum_thorough.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest Global 4 failed");
+      if (enum_thorough.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 5 failed");
+      if (enum_thorough.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 6 failed");
+      if (enum_thorough.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      TreesClass.trees pine = TreesClass.trees.pine;
+
+      if (t.treesTest1(pine) != pine) throw new Exception("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new Exception("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new Exception("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new Exception("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new Exception("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new Exception("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new Exception("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new Exception("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new Exception("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new Exception("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new Exception("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new Exception("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new Exception("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new Exception("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new Exception("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new Exception("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new Exception("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new Exception("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new Exception("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new Exception("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new Exception("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new Exception("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new Exception("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new Exception("treesTest O failed");
+
+      if (enum_thorough.treesTest1(pine) != pine) throw new Exception("treesTest Global 1 failed");
+      if (enum_thorough.treesTest2(pine) != pine) throw new Exception("treesTest Global 2 failed");
+      if (enum_thorough.treesTest3(pine) != pine) throw new Exception("treesTest Global 3 failed");
+      if (enum_thorough.treesTest4(pine) != pine) throw new Exception("treesTest Global 4 failed");
+      if (enum_thorough.treesTest5(pine) != pine) throw new Exception("treesTest Global 5 failed");
+      if (enum_thorough.treesTest6(pine) != pine) throw new Exception("treesTest Global 6 failed");
+      if (enum_thorough.treesTest7(pine) != pine) throw new Exception("treesTest Global 7 failed");
+      if (enum_thorough.treesTest8(pine) != pine) throw new Exception("treesTest Global 8 failed");
+      if (enum_thorough.treesTest9(pine) != pine) throw new Exception("treesTest Global 9 failed");
+      if (enum_thorough.treesTestA(pine) != pine) throw new Exception("treesTest Global A failed");
+      if (enum_thorough.treesTestB(pine) != pine) throw new Exception("treesTest Global B failed");
+      if (enum_thorough.treesTestC(pine) != pine) throw new Exception("treesTest Global C failed");
+      if (enum_thorough.treesTestD(pine) != pine) throw new Exception("treesTest Global D failed");
+      if (enum_thorough.treesTestE(pine) != pine) throw new Exception("treesTest Global E failed");
+      if (enum_thorough.treesTestF(pine) != pine) throw new Exception("treesTest Global F failed");
+      if (enum_thorough.treesTestG(pine) != pine) throw new Exception("treesTest Global G failed");
+      if (enum_thorough.treesTestH(pine) != pine) throw new Exception("treesTest Global H failed");
+      if (enum_thorough.treesTestI(pine) != pine) throw new Exception("treesTest Global I failed");
+      if (enum_thorough.treesTestJ(pine) != pine) throw new Exception("treesTest Global J failed");
+      if (enum_thorough.treesTestK(pine) != pine) throw new Exception("treesTest Global K failed");
+      if (enum_thorough.treesTestL(pine) != pine) throw new Exception("treesTest Global L failed");
+      if (enum_thorough.treesTestM(pine) != pine) throw new Exception("treesTest Global M failed");
+//      if (enum_thorough.treesTestN(pine) != pine) throw new Exception("treesTest Global N failed");
+      if (enum_thorough.treesTestO(pine) != pine) throw new Exception("treesTest Global O failed");
+      if (enum_thorough.treesTestP(pine) != pine) throw new Exception("treesTest Global P failed");
+      if (enum_thorough.treesTestQ(pine) != pine) throw new Exception("treesTest Global Q failed");
+      if (enum_thorough.treesTestR(pine) != pine) throw new Exception("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      HairStruct.hair ginger = HairStruct.hair.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new Exception("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new Exception("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new Exception("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new Exception("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new Exception("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new Exception("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new Exception("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new Exception("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new Exception("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new Exception("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new Exception("hairTest B failed");
+
+      colour red = colour.red;
+      if (h.colourTest1(red) != red) throw new Exception("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new Exception("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new Exception("namedanonspaceTest HairStruct 1 failed");
+
+      TreesClass.trees fir = TreesClass.trees.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+      if (enum_thorough.hairTest1(blonde) != blonde) throw new Exception("hairTest Global 1 failed");
+      if (enum_thorough.hairTest2(blonde) != blonde) throw new Exception("hairTest Global 2 failed");
+      if (enum_thorough.hairTest3(blonde) != blonde) throw new Exception("hairTest Global 3 failed");
+      if (enum_thorough.hairTest4(blonde) != blonde) throw new Exception("hairTest Global 4 failed");
+      if (enum_thorough.hairTest5(blonde) != blonde) throw new Exception("hairTest Global 5 failed");
+      if (enum_thorough.hairTest6(blonde) != blonde) throw new Exception("hairTest Global 6 failed");
+      if (enum_thorough.hairTest7(blonde) != blonde) throw new Exception("hairTest Global 7 failed");
+      if (enum_thorough.hairTest8(blonde) != blonde) throw new Exception("hairTest Global 8 failed");
+      if (enum_thorough.hairTest9(blonde) != blonde) throw new Exception("hairTest Global 9 failed");
+      if (enum_thorough.hairTestA(blonde) != blonde) throw new Exception("hairTest Global A failed");
+      if (enum_thorough.hairTestB(blonde) != blonde) throw new Exception("hairTest Global B failed");
+      if (enum_thorough.hairTestC(blonde) != blonde) throw new Exception("hairTest Global C failed");
+
+      if (enum_thorough.hairTestA1(blonde) != blonde) throw new Exception("hairTest Global A1 failed");
+      if (enum_thorough.hairTestA2(blonde) != blonde) throw new Exception("hairTest Global A2 failed");
+      if (enum_thorough.hairTestA3(blonde) != blonde) throw new Exception("hairTest Global A3 failed");
+      if (enum_thorough.hairTestA4(blonde) != blonde) throw new Exception("hairTest Global A4 failed");
+      if (enum_thorough.hairTestA5(blonde) != blonde) throw new Exception("hairTest Global A5 failed");
+      if (enum_thorough.hairTestA6(blonde) != blonde) throw new Exception("hairTest Global A6 failed");
+      if (enum_thorough.hairTestA7(blonde) != blonde) throw new Exception("hairTest Global A7 failed");
+      if (enum_thorough.hairTestA8(blonde) != blonde) throw new Exception("hairTest Global A8 failed");
+      if (enum_thorough.hairTestA9(blonde) != blonde) throw new Exception("hairTest Global A9 failed");
+      if (enum_thorough.hairTestAA(blonde) != blonde) throw new Exception("hairTest Global AA failed");
+      if (enum_thorough.hairTestAB(blonde) != blonde) throw new Exception("hairTest Global AB failed");
+      if (enum_thorough.hairTestAC(blonde) != blonde) throw new Exception("hairTest Global AC failed");
+
+      if (enum_thorough.hairTestB1(blonde) != blonde) throw new Exception("hairTest Global B1 failed");
+      if (enum_thorough.hairTestB2(blonde) != blonde) throw new Exception("hairTest Global B2 failed");
+      if (enum_thorough.hairTestB3(blonde) != blonde) throw new Exception("hairTest Global B3 failed");
+      if (enum_thorough.hairTestB4(blonde) != blonde) throw new Exception("hairTest Global B4 failed");
+      if (enum_thorough.hairTestB5(blonde) != blonde) throw new Exception("hairTest Global B5 failed");
+      if (enum_thorough.hairTestB6(blonde) != blonde) throw new Exception("hairTest Global B6 failed");
+      if (enum_thorough.hairTestB7(blonde) != blonde) throw new Exception("hairTest Global B7 failed");
+      if (enum_thorough.hairTestB8(blonde) != blonde) throw new Exception("hairTest Global B8 failed");
+      if (enum_thorough.hairTestB9(blonde) != blonde) throw new Exception("hairTest Global B9 failed");
+      if (enum_thorough.hairTestBA(blonde) != blonde) throw new Exception("hairTest Global BA failed");
+      if (enum_thorough.hairTestBB(blonde) != blonde) throw new Exception("hairTest Global BB failed");
+      if (enum_thorough.hairTestBC(blonde) != blonde) throw new Exception("hairTest Global BC failed");
+
+      if (enum_thorough.hairTestC1(blonde) != blonde) throw new Exception("hairTest Global C1 failed");
+      if (enum_thorough.hairTestC2(blonde) != blonde) throw new Exception("hairTest Global C2 failed");
+      if (enum_thorough.hairTestC3(blonde) != blonde) throw new Exception("hairTest Global C3 failed");
+      if (enum_thorough.hairTestC4(blonde) != blonde) throw new Exception("hairTest Global C4 failed");
+      if (enum_thorough.hairTestC5(blonde) != blonde) throw new Exception("hairTest Global C5 failed");
+      if (enum_thorough.hairTestC6(blonde) != blonde) throw new Exception("hairTest Global C6 failed");
+      if (enum_thorough.hairTestC7(blonde) != blonde) throw new Exception("hairTest Global C7 failed");
+      if (enum_thorough.hairTestC8(blonde) != blonde) throw new Exception("hairTest Global C8 failed");
+      if (enum_thorough.hairTestC9(blonde) != blonde) throw new Exception("hairTest Global C9 failed");
+      if (enum_thorough.hairTestCA(blonde) != blonde) throw new Exception("hairTest Global CA failed");
+      if (enum_thorough.hairTestCB(blonde) != blonde) throw new Exception("hairTest Global CB failed");
+      if (enum_thorough.hairTestCC(blonde) != blonde) throw new Exception("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new Exception("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new Exception("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new Exception("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new Exception("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new Exception("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new Exception("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new Exception("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new Exception("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new Exception("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new Exception("hairTestFir A failed");
+    }
+    {
+      enum_thorough.GlobalInstance = enum_thorough.globalinstance2;
+      if (enum_thorough.GlobalInstance != enum_thorough.globalinstance2) throw new Exception("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.MemberInstance = Instances.memberinstance3;
+      if (i.MemberInstance != Instances.memberinstance3) throw new Exception("MemberInstance 1 failed");
+    }
+    {
+      if ((int)enum_thorough.repeatTest(repeat.one) != 1) throw new Exception("repeatTest 1 failed");
+      if ((int)enum_thorough.repeatTest(repeat.initial) != 1) throw new Exception("repeatTest 2 failed");
+      if ((int)enum_thorough.repeatTest(repeat.two) != 2) throw new Exception("repeatTest 3 failed");
+      if ((int)enum_thorough.repeatTest(repeat.three) != 3) throw new Exception("repeatTest 4 failed");
+      if ((int)enum_thorough.repeatTest(repeat.last) != 3) throw new Exception("repeatTest 5 failed");
+      if ((int)enum_thorough.repeatTest(repeat.end) != 3) throw new Exception("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/enum_thorough_simple_runme.cs b/trunk/Examples/test-suite/csharp/enum_thorough_simple_runme.cs
new file mode 100644
index 0000000..f8556ff
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/enum_thorough_simple_runme.cs
@@ -0,0 +1,371 @@
+using System;
+using enum_thorough_simpleNamespace;
+
+public class runme {
+  static void Main() {
+    {
+      // Anonymous enums
+      int i = enum_thorough_simple.AnonEnum1;
+      if (enum_thorough_simple.ReallyAnInteger != 200) throw new Exception("Test Anon 1 failed");
+      i += enum_thorough_simple.AnonSpaceEnum1;
+      i += AnonStruct.AnonStructEnum1;
+    }
+    {
+      int red = enum_thorough_simple.red;
+      enum_thorough_simple.colourTest1(red);
+      enum_thorough_simple.colourTest2(red);
+      enum_thorough_simple.colourTest3(red);
+      enum_thorough_simple.colourTest4(red);
+      enum_thorough_simple.myColour = red;
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      int speed = SpeedClass.slow;
+      if (s.speedTest1(speed) != speed) throw new Exception("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new Exception("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new Exception("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new Exception("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new Exception("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new Exception("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new Exception("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new Exception("speedTest 8 failed");
+
+      if (enum_thorough_simple.speedTest1(speed) != speed) throw new Exception("speedTest Global 1 failed");
+      if (enum_thorough_simple.speedTest2(speed) != speed) throw new Exception("speedTest Global 2 failed");
+      if (enum_thorough_simple.speedTest3(speed) != speed) throw new Exception("speedTest Global 3 failed");
+      if (enum_thorough_simple.speedTest4(speed) != speed) throw new Exception("speedTest Global 4 failed");
+      if (enum_thorough_simple.speedTest5(speed) != speed) throw new Exception("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      int slow = SpeedClass.slow;
+      int lightning = SpeedClass.lightning;
+
+      if (s.mySpeedtd1 != slow) throw new Exception("mySpeedtd1 1 failed");
+      if (s.mySpeedtd1 != 10) throw new Exception("mySpeedtd1 2 failed");
+
+      s.mySpeedtd1 = lightning;
+      if (s.mySpeedtd1 != lightning) throw new Exception("mySpeedtd1 3 failed");
+      if (s.mySpeedtd1 != 31) throw new Exception("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough_simple.namedanonTest1(enum_thorough_simple.NamedAnon2) != enum_thorough_simple.NamedAnon2) throw new Exception("namedanonTest 1 failed");
+    }
+    {
+      int val = enum_thorough_simple.TwoNames2;
+      if (enum_thorough_simple.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
+      if (enum_thorough_simple.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
+      if (enum_thorough_simple.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      int val = TwoNamesStruct.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
+    }
+    {
+      int val = enum_thorough_simple.NamedAnonSpace2;
+      if (enum_thorough_simple.namedanonspaceTest1(val) != val) throw new Exception("namedanonspaceTest 1 failed");
+      if (enum_thorough_simple.namedanonspaceTest2(val) != val) throw new Exception("namedanonspaceTest 2 failed");
+      if (enum_thorough_simple.namedanonspaceTest3(val) != val) throw new Exception("namedanonspaceTest 3 failed");
+      if (enum_thorough_simple.namedanonspaceTest4(val) != val) throw new Exception("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      int galileo = TemplateClassInt.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new Exception("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new Exception("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new Exception("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new Exception("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new Exception("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new Exception("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new Exception("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new Exception("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new Exception("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new Exception("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new Exception("scientistsTest J failed");
+
+      if (enum_thorough_simple.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest Global 1 failed");
+      if (enum_thorough_simple.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest Global 2 failed");
+      if (enum_thorough_simple.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest Global 3 failed");
+      if (enum_thorough_simple.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest Global 4 failed");
+      if (enum_thorough_simple.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest Global 5 failed");
+      if (enum_thorough_simple.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest Global 6 failed");
+      if (enum_thorough_simple.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest Global 7 failed");
+      if (enum_thorough_simple.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      int bell = TClassInt.bell;
+      int galileo = TemplateClassInt.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new Exception("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new Exception("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new Exception("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new Exception("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new Exception("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new Exception("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new Exception("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new Exception("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new Exception("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new Exception("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new Exception("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new Exception("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new Exception("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new Exception("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new Exception("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new Exception("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new Exception("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new Exception("scientistsOtherTest 7 failed");
+
+      if (enum_thorough_simple.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest Global 1 failed");
+      if (enum_thorough_simple.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest Global 2 failed");
+      if (enum_thorough_simple.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest Global 3 failed");
+      if (enum_thorough_simple.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest Global 4 failed");
+      if (enum_thorough_simple.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest Global 5 failed");
+      if (enum_thorough_simple.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest Global 6 failed");
+      if (enum_thorough_simple.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough_simple.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough_simple.scientistsNameSpaceTest8(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest9(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestA(bell) != bell) throw new Exception("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestB(bell) != bell) throw new Exception("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestC(bell) != bell) throw new Exception("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestD(bell) != bell) throw new Exception("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestE(bell) != bell) throw new Exception("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough_simple.scientistsNameSpaceTestF(bell) != bell) throw new Exception("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestG(bell) != bell) throw new Exception("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestH(bell) != bell) throw new Exception("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestI(bell) != bell) throw new Exception("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestJ(bell) != bell) throw new Exception("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestK(bell) != bell) throw new Exception("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestL(bell) != bell) throw new Exception("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      int val = enum_thorough_simple.argh;
+      if (enum_thorough_simple.renameTest1(val) != val) throw new Exception("renameTest Global 1 failed");
+      if (enum_thorough_simple.renameTest2(val) != val) throw new Exception("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.bang) != NewNameStruct.bang) throw new Exception("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.bang) != NewNameStruct.bang) throw new Exception("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simple1) != NewNameStruct.simple1) throw new Exception("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlename1) != NewNameStruct.singlename1) throw new Exception("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough_simple.renameTest3(NewNameStruct.bang) != NewNameStruct.bang) throw new Exception("renameTest Global 3 failed");
+      if (enum_thorough_simple.renameTest4(NewNameStruct.simple1) != NewNameStruct.simple1) throw new Exception("renameTest Global 4 failed");
+      if (enum_thorough_simple.renameTest5(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest Global 5 failed");
+      if (enum_thorough_simple.renameTest6(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new Exception("renameTest Global 6 failed");
+      if (enum_thorough_simple.renameTest7(NewNameStruct.singlename1) != NewNameStruct.singlename1) throw new Exception("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      int pine = TreesClass.pine;
+
+      if (t.treesTest1(pine) != pine) throw new Exception("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new Exception("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new Exception("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new Exception("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new Exception("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new Exception("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new Exception("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new Exception("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new Exception("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new Exception("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new Exception("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new Exception("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new Exception("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new Exception("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new Exception("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new Exception("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new Exception("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new Exception("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new Exception("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new Exception("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new Exception("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new Exception("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new Exception("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new Exception("treesTest O failed");
+
+      if (enum_thorough_simple.treesTest1(pine) != pine) throw new Exception("treesTest Global 1 failed");
+      if (enum_thorough_simple.treesTest2(pine) != pine) throw new Exception("treesTest Global 2 failed");
+      if (enum_thorough_simple.treesTest3(pine) != pine) throw new Exception("treesTest Global 3 failed");
+      if (enum_thorough_simple.treesTest4(pine) != pine) throw new Exception("treesTest Global 4 failed");
+      if (enum_thorough_simple.treesTest5(pine) != pine) throw new Exception("treesTest Global 5 failed");
+      if (enum_thorough_simple.treesTest6(pine) != pine) throw new Exception("treesTest Global 6 failed");
+      if (enum_thorough_simple.treesTest7(pine) != pine) throw new Exception("treesTest Global 7 failed");
+      if (enum_thorough_simple.treesTest8(pine) != pine) throw new Exception("treesTest Global 8 failed");
+      if (enum_thorough_simple.treesTest9(pine) != pine) throw new Exception("treesTest Global 9 failed");
+      if (enum_thorough_simple.treesTestA(pine) != pine) throw new Exception("treesTest Global A failed");
+      if (enum_thorough_simple.treesTestB(pine) != pine) throw new Exception("treesTest Global B failed");
+      if (enum_thorough_simple.treesTestC(pine) != pine) throw new Exception("treesTest Global C failed");
+      if (enum_thorough_simple.treesTestD(pine) != pine) throw new Exception("treesTest Global D failed");
+      if (enum_thorough_simple.treesTestE(pine) != pine) throw new Exception("treesTest Global E failed");
+      if (enum_thorough_simple.treesTestF(pine) != pine) throw new Exception("treesTest Global F failed");
+      if (enum_thorough_simple.treesTestG(pine) != pine) throw new Exception("treesTest Global G failed");
+      if (enum_thorough_simple.treesTestH(pine) != pine) throw new Exception("treesTest Global H failed");
+      if (enum_thorough_simple.treesTestI(pine) != pine) throw new Exception("treesTest Global I failed");
+      if (enum_thorough_simple.treesTestJ(pine) != pine) throw new Exception("treesTest Global J failed");
+      if (enum_thorough_simple.treesTestK(pine) != pine) throw new Exception("treesTest Global K failed");
+      if (enum_thorough_simple.treesTestL(pine) != pine) throw new Exception("treesTest Global L failed");
+      if (enum_thorough_simple.treesTestM(pine) != pine) throw new Exception("treesTest Global M failed");
+//      if (enum_thorough_simple.treesTestN(pine) != pine) throw new Exception("treesTest Global N failed");
+      if (enum_thorough_simple.treesTestO(pine) != pine) throw new Exception("treesTest Global O failed");
+      if (enum_thorough_simple.treesTestP(pine) != pine) throw new Exception("treesTest Global P failed");
+      if (enum_thorough_simple.treesTestQ(pine) != pine) throw new Exception("treesTest Global Q failed");
+      if (enum_thorough_simple.treesTestR(pine) != pine) throw new Exception("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      int ginger = HairStruct.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new Exception("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new Exception("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new Exception("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new Exception("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new Exception("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new Exception("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new Exception("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new Exception("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new Exception("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new Exception("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new Exception("hairTest B failed");
+
+      int red = enum_thorough_simple.red;
+      if (h.colourTest1(red) != red) throw new Exception("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new Exception("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(enum_thorough_simple.NamedAnon2) != enum_thorough_simple.NamedAnon2) throw new Exception("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(enum_thorough_simple.NamedAnonSpace2) != enum_thorough_simple.NamedAnonSpace2) throw new Exception("namedanonspaceTest HairStruct 1 failed");
+
+      int fir = TreesClass.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      int blonde = HairStruct.blonde;
+      if (enum_thorough_simple.hairTest1(blonde) != blonde) throw new Exception("hairTest Global 1 failed");
+      if (enum_thorough_simple.hairTest2(blonde) != blonde) throw new Exception("hairTest Global 2 failed");
+      if (enum_thorough_simple.hairTest3(blonde) != blonde) throw new Exception("hairTest Global 3 failed");
+      if (enum_thorough_simple.hairTest4(blonde) != blonde) throw new Exception("hairTest Global 4 failed");
+      if (enum_thorough_simple.hairTest5(blonde) != blonde) throw new Exception("hairTest Global 5 failed");
+      if (enum_thorough_simple.hairTest6(blonde) != blonde) throw new Exception("hairTest Global 6 failed");
+      if (enum_thorough_simple.hairTest7(blonde) != blonde) throw new Exception("hairTest Global 7 failed");
+      if (enum_thorough_simple.hairTest8(blonde) != blonde) throw new Exception("hairTest Global 8 failed");
+      if (enum_thorough_simple.hairTest9(blonde) != blonde) throw new Exception("hairTest Global 9 failed");
+      if (enum_thorough_simple.hairTestA(blonde) != blonde) throw new Exception("hairTest Global A failed");
+      if (enum_thorough_simple.hairTestB(blonde) != blonde) throw new Exception("hairTest Global B failed");
+      if (enum_thorough_simple.hairTestC(blonde) != blonde) throw new Exception("hairTest Global C failed");
+
+      if (enum_thorough_simple.hairTestA1(blonde) != blonde) throw new Exception("hairTest Global A1 failed");
+      if (enum_thorough_simple.hairTestA2(blonde) != blonde) throw new Exception("hairTest Global A2 failed");
+      if (enum_thorough_simple.hairTestA3(blonde) != blonde) throw new Exception("hairTest Global A3 failed");
+      if (enum_thorough_simple.hairTestA4(blonde) != blonde) throw new Exception("hairTest Global A4 failed");
+      if (enum_thorough_simple.hairTestA5(blonde) != blonde) throw new Exception("hairTest Global A5 failed");
+      if (enum_thorough_simple.hairTestA6(blonde) != blonde) throw new Exception("hairTest Global A6 failed");
+      if (enum_thorough_simple.hairTestA7(blonde) != blonde) throw new Exception("hairTest Global A7 failed");
+      if (enum_thorough_simple.hairTestA8(blonde) != blonde) throw new Exception("hairTest Global A8 failed");
+      if (enum_thorough_simple.hairTestA9(blonde) != blonde) throw new Exception("hairTest Global A9 failed");
+      if (enum_thorough_simple.hairTestAA(blonde) != blonde) throw new Exception("hairTest Global AA failed");
+      if (enum_thorough_simple.hairTestAB(blonde) != blonde) throw new Exception("hairTest Global AB failed");
+      if (enum_thorough_simple.hairTestAC(blonde) != blonde) throw new Exception("hairTest Global AC failed");
+
+      if (enum_thorough_simple.hairTestB1(blonde) != blonde) throw new Exception("hairTest Global B1 failed");
+      if (enum_thorough_simple.hairTestB2(blonde) != blonde) throw new Exception("hairTest Global B2 failed");
+      if (enum_thorough_simple.hairTestB3(blonde) != blonde) throw new Exception("hairTest Global B3 failed");
+      if (enum_thorough_simple.hairTestB4(blonde) != blonde) throw new Exception("hairTest Global B4 failed");
+      if (enum_thorough_simple.hairTestB5(blonde) != blonde) throw new Exception("hairTest Global B5 failed");
+      if (enum_thorough_simple.hairTestB6(blonde) != blonde) throw new Exception("hairTest Global B6 failed");
+      if (enum_thorough_simple.hairTestB7(blonde) != blonde) throw new Exception("hairTest Global B7 failed");
+      if (enum_thorough_simple.hairTestB8(blonde) != blonde) throw new Exception("hairTest Global B8 failed");
+      if (enum_thorough_simple.hairTestB9(blonde) != blonde) throw new Exception("hairTest Global B9 failed");
+      if (enum_thorough_simple.hairTestBA(blonde) != blonde) throw new Exception("hairTest Global BA failed");
+      if (enum_thorough_simple.hairTestBB(blonde) != blonde) throw new Exception("hairTest Global BB failed");
+      if (enum_thorough_simple.hairTestBC(blonde) != blonde) throw new Exception("hairTest Global BC failed");
+
+      if (enum_thorough_simple.hairTestC1(blonde) != blonde) throw new Exception("hairTest Global C1 failed");
+      if (enum_thorough_simple.hairTestC2(blonde) != blonde) throw new Exception("hairTest Global C2 failed");
+      if (enum_thorough_simple.hairTestC3(blonde) != blonde) throw new Exception("hairTest Global C3 failed");
+      if (enum_thorough_simple.hairTestC4(blonde) != blonde) throw new Exception("hairTest Global C4 failed");
+      if (enum_thorough_simple.hairTestC5(blonde) != blonde) throw new Exception("hairTest Global C5 failed");
+      if (enum_thorough_simple.hairTestC6(blonde) != blonde) throw new Exception("hairTest Global C6 failed");
+      if (enum_thorough_simple.hairTestC7(blonde) != blonde) throw new Exception("hairTest Global C7 failed");
+      if (enum_thorough_simple.hairTestC8(blonde) != blonde) throw new Exception("hairTest Global C8 failed");
+      if (enum_thorough_simple.hairTestC9(blonde) != blonde) throw new Exception("hairTest Global C9 failed");
+      if (enum_thorough_simple.hairTestCA(blonde) != blonde) throw new Exception("hairTest Global CA failed");
+      if (enum_thorough_simple.hairTestCB(blonde) != blonde) throw new Exception("hairTest Global CB failed");
+      if (enum_thorough_simple.hairTestCC(blonde) != blonde) throw new Exception("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      int blonde = HairStruct.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new Exception("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new Exception("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new Exception("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new Exception("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new Exception("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new Exception("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new Exception("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new Exception("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new Exception("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new Exception("hairTestFir A failed");
+    }
+    {
+      enum_thorough_simple.GlobalInstance = enum_thorough_simple.globalinstance2;
+      if (enum_thorough_simple.GlobalInstance != enum_thorough_simple.globalinstance2) throw new Exception("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.MemberInstance = Instances.memberinstance3;
+      if (i.MemberInstance != Instances.memberinstance3) throw new Exception("MemberInstance 1 failed");
+    }
+    {
+      if (enum_thorough_simple.repeatTest(enum_thorough_simple.one) != 1) throw new Exception("repeatTest 1 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simple.initial) != 1) throw new Exception("repeatTest 2 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simple.two) != 2) throw new Exception("repeatTest 3 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simple.three) != 3) throw new Exception("repeatTest 4 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simple.last) != 3) throw new Exception("repeatTest 5 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simple.end) != 3) throw new Exception("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/enum_thorough_typesafe_runme.cs b/trunk/Examples/test-suite/csharp/enum_thorough_typesafe_runme.cs
new file mode 100644
index 0000000..dc2a981
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/enum_thorough_typesafe_runme.cs
@@ -0,0 +1,371 @@
+using System;
+using enum_thorough_typesafeNamespace;
+
+public class runme {
+  static void Main() {
+    {
+      // Anonymous enums
+      int i = enum_thorough_typesafe.AnonEnum1;
+      if (enum_thorough_typesafe.ReallyAnInteger != 200) throw new Exception("Test Anon 1 failed");
+      i += enum_thorough_typesafe.AnonSpaceEnum1;
+      i += AnonStruct.AnonStructEnum1;
+    }
+    {
+      colour red = colour.red;
+      enum_thorough_typesafe.colourTest1(red);
+      enum_thorough_typesafe.colourTest2(red);
+      enum_thorough_typesafe.colourTest3(red);
+      enum_thorough_typesafe.colourTest4(red);
+      enum_thorough_typesafe.myColour = red;
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed speed = SpeedClass.speed.slow;
+      if (s.speedTest1(speed) != speed) throw new Exception("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new Exception("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new Exception("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new Exception("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new Exception("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new Exception("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new Exception("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new Exception("speedTest 8 failed");
+
+      if (enum_thorough_typesafe.speedTest1(speed) != speed) throw new Exception("speedTest Global 1 failed");
+      if (enum_thorough_typesafe.speedTest2(speed) != speed) throw new Exception("speedTest Global 2 failed");
+      if (enum_thorough_typesafe.speedTest3(speed) != speed) throw new Exception("speedTest Global 3 failed");
+      if (enum_thorough_typesafe.speedTest4(speed) != speed) throw new Exception("speedTest Global 4 failed");
+      if (enum_thorough_typesafe.speedTest5(speed) != speed) throw new Exception("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed slow = SpeedClass.speed.slow;
+      SpeedClass.speed lightning = SpeedClass.speed.lightning;
+
+      if (s.mySpeedtd1 != slow) throw new Exception("mySpeedtd1 1 failed");
+      if (s.mySpeedtd1.swigValue != 10) throw new Exception("mySpeedtd1 2 failed");
+
+      s.mySpeedtd1 = lightning;
+      if (s.mySpeedtd1 != lightning) throw new Exception("mySpeedtd1 3 failed");
+      if (s.mySpeedtd1.swigValue != 31) throw new Exception("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough_typesafe.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest 1 failed");
+    }
+    {
+      twonames val = twonames.TwoNames2;
+      if (enum_thorough_typesafe.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
+      if (enum_thorough_typesafe.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
+      if (enum_thorough_typesafe.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      TwoNamesStruct.twonames val = TwoNamesStruct.twonames.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new Exception("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new Exception("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new Exception("twonamesTest 3 failed");
+    }
+    {
+      namedanonspace val = namedanonspace.NamedAnonSpace2;
+      if (enum_thorough_typesafe.namedanonspaceTest1(val) != val) throw new Exception("namedanonspaceTest 1 failed");
+      if (enum_thorough_typesafe.namedanonspaceTest2(val) != val) throw new Exception("namedanonspaceTest 2 failed");
+      if (enum_thorough_typesafe.namedanonspaceTest3(val) != val) throw new Exception("namedanonspaceTest 3 failed");
+      if (enum_thorough_typesafe.namedanonspaceTest4(val) != val) throw new Exception("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new Exception("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new Exception("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new Exception("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new Exception("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new Exception("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new Exception("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new Exception("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new Exception("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new Exception("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new Exception("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new Exception("scientistsTest J failed");
+
+      if (enum_thorough_typesafe.scientistsTest1(galileo) != galileo) throw new Exception("scientistsTest Global 1 failed");
+      if (enum_thorough_typesafe.scientistsTest2(galileo) != galileo) throw new Exception("scientistsTest Global 2 failed");
+      if (enum_thorough_typesafe.scientistsTest3(galileo) != galileo) throw new Exception("scientistsTest Global 3 failed");
+      if (enum_thorough_typesafe.scientistsTest4(galileo) != galileo) throw new Exception("scientistsTest Global 4 failed");
+      if (enum_thorough_typesafe.scientistsTest5(galileo) != galileo) throw new Exception("scientistsTest Global 5 failed");
+      if (enum_thorough_typesafe.scientistsTest6(galileo) != galileo) throw new Exception("scientistsTest Global 6 failed");
+      if (enum_thorough_typesafe.scientistsTest7(galileo) != galileo) throw new Exception("scientistsTest Global 7 failed");
+      if (enum_thorough_typesafe.scientistsTest8(galileo) != galileo) throw new Exception("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      TClassInt.scientists bell = TClassInt.scientists.bell;
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new Exception("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new Exception("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new Exception("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new Exception("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new Exception("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new Exception("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new Exception("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new Exception("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new Exception("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new Exception("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new Exception("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new Exception("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new Exception("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new Exception("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new Exception("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new Exception("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new Exception("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new Exception("scientistsOtherTest 7 failed");
+
+      if (enum_thorough_typesafe.scientistsNameTest1(bell) != bell) throw new Exception("scientistsNameTest Global 1 failed");
+      if (enum_thorough_typesafe.scientistsNameTest2(bell) != bell) throw new Exception("scientistsNameTest Global 2 failed");
+      if (enum_thorough_typesafe.scientistsNameTest3(bell) != bell) throw new Exception("scientistsNameTest Global 3 failed");
+      if (enum_thorough_typesafe.scientistsNameTest4(bell) != bell) throw new Exception("scientistsNameTest Global 4 failed");
+      if (enum_thorough_typesafe.scientistsNameTest5(bell) != bell) throw new Exception("scientistsNameTest Global 5 failed");
+      if (enum_thorough_typesafe.scientistsNameTest6(bell) != bell) throw new Exception("scientistsNameTest Global 6 failed");
+      if (enum_thorough_typesafe.scientistsNameTest7(bell) != bell) throw new Exception("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough_typesafe.scientistsNameSpaceTest1(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest2(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest3(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest4(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest5(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest6(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest7(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough_typesafe.scientistsNameSpaceTest8(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTest9(bell) != bell) throw new Exception("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestA(bell) != bell) throw new Exception("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestB(bell) != bell) throw new Exception("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestC(bell) != bell) throw new Exception("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestD(bell) != bell) throw new Exception("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestE(bell) != bell) throw new Exception("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough_typesafe.scientistsNameSpaceTestF(bell) != bell) throw new Exception("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestG(bell) != bell) throw new Exception("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestH(bell) != bell) throw new Exception("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestI(bell) != bell) throw new Exception("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestJ(bell) != bell) throw new Exception("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestK(bell) != bell) throw new Exception("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough_typesafe.scientistsNameSpaceTestL(bell) != bell) throw new Exception("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      newname val = newname.argh;
+      if (enum_thorough_typesafe.renameTest1(val) != val) throw new Exception("renameTest Global 1 failed");
+      if (enum_thorough_typesafe.renameTest2(val) != val) throw new Exception("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough_typesafe.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new Exception("renameTest Global 3 failed");
+      if (enum_thorough_typesafe.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new Exception("renameTest Global 4 failed");
+      if (enum_thorough_typesafe.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 5 failed");
+      if (enum_thorough_typesafe.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new Exception("renameTest Global 6 failed");
+      if (enum_thorough_typesafe.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new Exception("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      TreesClass.trees pine = TreesClass.trees.pine;
+
+      if (t.treesTest1(pine) != pine) throw new Exception("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new Exception("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new Exception("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new Exception("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new Exception("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new Exception("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new Exception("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new Exception("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new Exception("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new Exception("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new Exception("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new Exception("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new Exception("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new Exception("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new Exception("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new Exception("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new Exception("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new Exception("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new Exception("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new Exception("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new Exception("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new Exception("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new Exception("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new Exception("treesTest O failed");
+
+      if (enum_thorough_typesafe.treesTest1(pine) != pine) throw new Exception("treesTest Global 1 failed");
+      if (enum_thorough_typesafe.treesTest2(pine) != pine) throw new Exception("treesTest Global 2 failed");
+      if (enum_thorough_typesafe.treesTest3(pine) != pine) throw new Exception("treesTest Global 3 failed");
+      if (enum_thorough_typesafe.treesTest4(pine) != pine) throw new Exception("treesTest Global 4 failed");
+      if (enum_thorough_typesafe.treesTest5(pine) != pine) throw new Exception("treesTest Global 5 failed");
+      if (enum_thorough_typesafe.treesTest6(pine) != pine) throw new Exception("treesTest Global 6 failed");
+      if (enum_thorough_typesafe.treesTest7(pine) != pine) throw new Exception("treesTest Global 7 failed");
+      if (enum_thorough_typesafe.treesTest8(pine) != pine) throw new Exception("treesTest Global 8 failed");
+      if (enum_thorough_typesafe.treesTest9(pine) != pine) throw new Exception("treesTest Global 9 failed");
+      if (enum_thorough_typesafe.treesTestA(pine) != pine) throw new Exception("treesTest Global A failed");
+      if (enum_thorough_typesafe.treesTestB(pine) != pine) throw new Exception("treesTest Global B failed");
+      if (enum_thorough_typesafe.treesTestC(pine) != pine) throw new Exception("treesTest Global C failed");
+      if (enum_thorough_typesafe.treesTestD(pine) != pine) throw new Exception("treesTest Global D failed");
+      if (enum_thorough_typesafe.treesTestE(pine) != pine) throw new Exception("treesTest Global E failed");
+      if (enum_thorough_typesafe.treesTestF(pine) != pine) throw new Exception("treesTest Global F failed");
+      if (enum_thorough_typesafe.treesTestG(pine) != pine) throw new Exception("treesTest Global G failed");
+      if (enum_thorough_typesafe.treesTestH(pine) != pine) throw new Exception("treesTest Global H failed");
+      if (enum_thorough_typesafe.treesTestI(pine) != pine) throw new Exception("treesTest Global I failed");
+      if (enum_thorough_typesafe.treesTestJ(pine) != pine) throw new Exception("treesTest Global J failed");
+      if (enum_thorough_typesafe.treesTestK(pine) != pine) throw new Exception("treesTest Global K failed");
+      if (enum_thorough_typesafe.treesTestL(pine) != pine) throw new Exception("treesTest Global L failed");
+      if (enum_thorough_typesafe.treesTestM(pine) != pine) throw new Exception("treesTest Global M failed");
+//      if (enum_thorough_typesafe.treesTestN(pine) != pine) throw new Exception("treesTest Global N failed");
+      if (enum_thorough_typesafe.treesTestO(pine) != pine) throw new Exception("treesTest Global O failed");
+      if (enum_thorough_typesafe.treesTestP(pine) != pine) throw new Exception("treesTest Global P failed");
+      if (enum_thorough_typesafe.treesTestQ(pine) != pine) throw new Exception("treesTest Global Q failed");
+      if (enum_thorough_typesafe.treesTestR(pine) != pine) throw new Exception("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      HairStruct.hair ginger = HairStruct.hair.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new Exception("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new Exception("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new Exception("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new Exception("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new Exception("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new Exception("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new Exception("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new Exception("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new Exception("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new Exception("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new Exception("hairTest B failed");
+
+      colour red = colour.red;
+      if (h.colourTest1(red) != red) throw new Exception("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new Exception("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new Exception("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new Exception("namedanonspaceTest HairStruct 1 failed");
+
+      TreesClass.trees fir = TreesClass.trees.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new Exception("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+      if (enum_thorough_typesafe.hairTest1(blonde) != blonde) throw new Exception("hairTest Global 1 failed");
+      if (enum_thorough_typesafe.hairTest2(blonde) != blonde) throw new Exception("hairTest Global 2 failed");
+      if (enum_thorough_typesafe.hairTest3(blonde) != blonde) throw new Exception("hairTest Global 3 failed");
+      if (enum_thorough_typesafe.hairTest4(blonde) != blonde) throw new Exception("hairTest Global 4 failed");
+      if (enum_thorough_typesafe.hairTest5(blonde) != blonde) throw new Exception("hairTest Global 5 failed");
+      if (enum_thorough_typesafe.hairTest6(blonde) != blonde) throw new Exception("hairTest Global 6 failed");
+      if (enum_thorough_typesafe.hairTest7(blonde) != blonde) throw new Exception("hairTest Global 7 failed");
+      if (enum_thorough_typesafe.hairTest8(blonde) != blonde) throw new Exception("hairTest Global 8 failed");
+      if (enum_thorough_typesafe.hairTest9(blonde) != blonde) throw new Exception("hairTest Global 9 failed");
+      if (enum_thorough_typesafe.hairTestA(blonde) != blonde) throw new Exception("hairTest Global A failed");
+      if (enum_thorough_typesafe.hairTestB(blonde) != blonde) throw new Exception("hairTest Global B failed");
+      if (enum_thorough_typesafe.hairTestC(blonde) != blonde) throw new Exception("hairTest Global C failed");
+
+      if (enum_thorough_typesafe.hairTestA1(blonde) != blonde) throw new Exception("hairTest Global A1 failed");
+      if (enum_thorough_typesafe.hairTestA2(blonde) != blonde) throw new Exception("hairTest Global A2 failed");
+      if (enum_thorough_typesafe.hairTestA3(blonde) != blonde) throw new Exception("hairTest Global A3 failed");
+      if (enum_thorough_typesafe.hairTestA4(blonde) != blonde) throw new Exception("hairTest Global A4 failed");
+      if (enum_thorough_typesafe.hairTestA5(blonde) != blonde) throw new Exception("hairTest Global A5 failed");
+      if (enum_thorough_typesafe.hairTestA6(blonde) != blonde) throw new Exception("hairTest Global A6 failed");
+      if (enum_thorough_typesafe.hairTestA7(blonde) != blonde) throw new Exception("hairTest Global A7 failed");
+      if (enum_thorough_typesafe.hairTestA8(blonde) != blonde) throw new Exception("hairTest Global A8 failed");
+      if (enum_thorough_typesafe.hairTestA9(blonde) != blonde) throw new Exception("hairTest Global A9 failed");
+      if (enum_thorough_typesafe.hairTestAA(blonde) != blonde) throw new Exception("hairTest Global AA failed");
+      if (enum_thorough_typesafe.hairTestAB(blonde) != blonde) throw new Exception("hairTest Global AB failed");
+      if (enum_thorough_typesafe.hairTestAC(blonde) != blonde) throw new Exception("hairTest Global AC failed");
+
+      if (enum_thorough_typesafe.hairTestB1(blonde) != blonde) throw new Exception("hairTest Global B1 failed");
+      if (enum_thorough_typesafe.hairTestB2(blonde) != blonde) throw new Exception("hairTest Global B2 failed");
+      if (enum_thorough_typesafe.hairTestB3(blonde) != blonde) throw new Exception("hairTest Global B3 failed");
+      if (enum_thorough_typesafe.hairTestB4(blonde) != blonde) throw new Exception("hairTest Global B4 failed");
+      if (enum_thorough_typesafe.hairTestB5(blonde) != blonde) throw new Exception("hairTest Global B5 failed");
+      if (enum_thorough_typesafe.hairTestB6(blonde) != blonde) throw new Exception("hairTest Global B6 failed");
+      if (enum_thorough_typesafe.hairTestB7(blonde) != blonde) throw new Exception("hairTest Global B7 failed");
+      if (enum_thorough_typesafe.hairTestB8(blonde) != blonde) throw new Exception("hairTest Global B8 failed");
+      if (enum_thorough_typesafe.hairTestB9(blonde) != blonde) throw new Exception("hairTest Global B9 failed");
+      if (enum_thorough_typesafe.hairTestBA(blonde) != blonde) throw new Exception("hairTest Global BA failed");
+      if (enum_thorough_typesafe.hairTestBB(blonde) != blonde) throw new Exception("hairTest Global BB failed");
+      if (enum_thorough_typesafe.hairTestBC(blonde) != blonde) throw new Exception("hairTest Global BC failed");
+
+      if (enum_thorough_typesafe.hairTestC1(blonde) != blonde) throw new Exception("hairTest Global C1 failed");
+      if (enum_thorough_typesafe.hairTestC2(blonde) != blonde) throw new Exception("hairTest Global C2 failed");
+      if (enum_thorough_typesafe.hairTestC3(blonde) != blonde) throw new Exception("hairTest Global C3 failed");
+      if (enum_thorough_typesafe.hairTestC4(blonde) != blonde) throw new Exception("hairTest Global C4 failed");
+      if (enum_thorough_typesafe.hairTestC5(blonde) != blonde) throw new Exception("hairTest Global C5 failed");
+      if (enum_thorough_typesafe.hairTestC6(blonde) != blonde) throw new Exception("hairTest Global C6 failed");
+      if (enum_thorough_typesafe.hairTestC7(blonde) != blonde) throw new Exception("hairTest Global C7 failed");
+      if (enum_thorough_typesafe.hairTestC8(blonde) != blonde) throw new Exception("hairTest Global C8 failed");
+      if (enum_thorough_typesafe.hairTestC9(blonde) != blonde) throw new Exception("hairTest Global C9 failed");
+      if (enum_thorough_typesafe.hairTestCA(blonde) != blonde) throw new Exception("hairTest Global CA failed");
+      if (enum_thorough_typesafe.hairTestCB(blonde) != blonde) throw new Exception("hairTest Global CB failed");
+      if (enum_thorough_typesafe.hairTestCC(blonde) != blonde) throw new Exception("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new Exception("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new Exception("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new Exception("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new Exception("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new Exception("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new Exception("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new Exception("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new Exception("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new Exception("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new Exception("hairTestFir A failed");
+    }
+    {
+      enum_thorough_typesafe.GlobalInstance = enum_thorough_typesafe.globalinstance2;
+      if (enum_thorough_typesafe.GlobalInstance != enum_thorough_typesafe.globalinstance2) throw new Exception("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.MemberInstance = Instances.memberinstance3;
+      if (i.MemberInstance != Instances.memberinstance3) throw new Exception("MemberInstance 1 failed");
+    }
+    {
+      if (enum_thorough_typesafe.repeatTest(repeat.one).swigValue != 1) throw new Exception("repeatTest 1 failed");
+      if (enum_thorough_typesafe.repeatTest(repeat.initial).swigValue != 1) throw new Exception("repeatTest 2 failed");
+      if (enum_thorough_typesafe.repeatTest(repeat.two).swigValue != 2) throw new Exception("repeatTest 3 failed");
+      if (enum_thorough_typesafe.repeatTest(repeat.three).swigValue != 3) throw new Exception("repeatTest 4 failed");
+      if (enum_thorough_typesafe.repeatTest(repeat.last).swigValue != 3) throw new Exception("repeatTest 5 failed");
+      if (enum_thorough_typesafe.repeatTest(repeat.end).swigValue != 3) throw new Exception("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/imports_runme.cs b/trunk/Examples/test-suite/csharp/imports_runme.cs
new file mode 100644
index 0000000..579dc8a
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/imports_runme.cs
@@ -0,0 +1,18 @@
+using System;
+using importsNamespace;
+
+public class runme
+{
+    static void Main() {
+        B b = new B();
+        b.hello(); //call member function in A which is in a different SWIG generated library.
+        b.bye();
+
+        if (b.member_virtual_test(A.MemberEnum.memberenum1) != A.MemberEnum.memberenum2)
+          throw new Exception("Test 1 failed");
+        if (b.global_virtual_test(GlobalEnum.globalenum1) != GlobalEnum.globalenum2)
+          throw new Exception("Test 2 failed");
+
+        imports_b.global_test(A.MemberEnum.memberenum1);
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/intermediary_classname_runme.cs b/trunk/Examples/test-suite/csharp/intermediary_classname_runme.cs
new file mode 100644
index 0000000..0ae8fba
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/intermediary_classname_runme.cs
@@ -0,0 +1,21 @@
+
+/***********************************************************************************************
+   NOTE: This is a custom testcase and should be run using make intermediary_classname.customtest
+ ***********************************************************************************************/
+
+using System;
+using intermediary_classnameNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      // test the renamed module class is correctly named
+      double d = intermediary_classnameModule.maxdouble(10.0, 20.0);
+      if (d!=20.0) throw new Exception("Test failed");
+
+      // test the renamed intermediary class is correctly named
+      IntPtr ptr = intermediary_classname.new_vecdouble(10);
+      intermediary_classname.delete_vecdouble(new System.Runtime.InteropServices.HandleRef(null,ptr));
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs b/trunk/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs
new file mode 100644
index 0000000..27bc462
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs
@@ -0,0 +1,579 @@
+using System;
+using li_boost_shared_ptrNamespace;
+
+public class runme
+{
+  // Debugging flag
+  public static bool debug = false;
+
+  static void Main() 
+  {
+    if (debug)
+      Console.WriteLine("Started");
+
+    li_boost_shared_ptr.debug_shared=debug;
+
+    // Change loop count to run for a long time to monitor memory
+    const int loopCount = 1; //50000;
+    for (int i=0; i<loopCount; i++) {
+      new runme().runtest();
+      System.GC.Collect(); 
+      System.GC.WaitForPendingFinalizers();
+      if (i%100 == 0) {
+        System.Threading.Thread.Sleep(1); // give some time to the lower priority finalizer thread
+      }
+    }
+
+    if (debug)
+      Console.WriteLine("Nearly finished");
+
+    int countdown = 100;
+    while (true) {
+      System.GC.Collect(); 
+      System.GC.WaitForPendingFinalizers();
+      System.Threading.Thread.Sleep(10);
+      if (--countdown == 0)
+        break;
+      if (Klass.getTotal_count() == 1) // Expect 1 instance - the one global variable (GlobalValue)
+        break;
+    };
+    if (Klass.getTotal_count() != 1)
+      throw new ApplicationException("Klass.total_count=" + Klass.getTotal_count());
+
+    int wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count(); 
+    if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING)
+      if (wrapper_count != 1) // Expect 1 instance - the one global variable (GlobalSmartValue)
+        throw new ApplicationException("shared_ptr wrapper count=" + wrapper_count);
+
+    if (debug)
+      Console.WriteLine("Finished");
+  }
+
+  private void runtest() {
+    // simple shared_ptr usage - created in C++
+    {
+      Klass k = new Klass("me oh my");
+      String val = k.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(1, k);
+    }
+
+    // simple shared_ptr usage - not created in C++
+    {
+      Klass k = li_boost_shared_ptr.factorycreate();
+      String val = k.getValue();
+      verifyValue("factorycreate", val);
+      verifyCount(1, k);
+    }
+
+    // pass by shared_ptr
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointertest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by shared_ptr pointer
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointertest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by shared_ptr reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerreftest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by shared_ptr pointer reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointerreftest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // const pass by shared_ptr
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.constsmartpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // const pass by shared_ptr pointer
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.constsmartpointerpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // const pass by shared_ptr reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.constsmartpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by value
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.valuetest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my valuetest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // pass by pointer
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.pointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my pointertest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // pass by reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.reftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my reftest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // pass by pointer reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.pointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my pointerreftest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // null tests
+    {
+      Klass k = null;
+
+      // TODO: add in const versions too
+      if (li_boost_shared_ptr.smartpointertest(k) != null)
+        throw new ApplicationException("return was not null");
+
+      if (li_boost_shared_ptr.smartpointerpointertest(k) != null)
+        throw new ApplicationException("return was not null");
+
+      if (li_boost_shared_ptr.smartpointerreftest(k) != null)
+        throw new ApplicationException("return was not null");
+
+      if (li_boost_shared_ptr.smartpointerpointerreftest(k) != null)
+        throw new ApplicationException("return was not null");
+
+      if (li_boost_shared_ptr.nullsmartpointerpointertest(null) != "null pointer")
+        throw new ApplicationException("not null smartpointer pointer");
+
+      try { li_boost_shared_ptr.valuetest(k); throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
+
+      if (li_boost_shared_ptr.pointertest(k) != null)
+        throw new ApplicationException("return was not null");
+
+      try { li_boost_shared_ptr.reftest(k); throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
+    }
+
+    // $owner
+    {
+      Klass k = li_boost_shared_ptr.pointerownertest();
+      String val = k.getValue();
+      verifyValue("pointerownertest", val);
+      verifyCount(1, k);
+    }
+    {
+      Klass k = li_boost_shared_ptr.smartpointerpointerownertest();
+      String val = k.getValue();
+      verifyValue("smartpointerpointerownertest", val);
+      verifyCount(1, k);
+    }
+
+    ////////////////////////////////// Derived classes ////////////////////////////////////////
+    // derived pass by shared_ptr
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrtest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrtest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by shared_ptr pointer
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrpointertest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by shared_ptr ref
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrreftest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by shared_ptr pointer ref
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by pointer
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedpointertest-Derived", val);
+      verifyCount(2, k); // includes an extra reference for the upcast in the proxy class
+      verifyCount(2, kret);
+    }
+    // derived pass by ref
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedreftest-Derived", val);
+      verifyCount(2, k); // includes an extra reference for the upcast in the proxy class
+      verifyCount(2, kret);
+    }
+
+    ////////////////////////////////// Derived and base class mixed ////////////////////////////////////////
+    // pass by shared_ptr (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointertest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by shared_ptr pointer (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointertest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by shared_ptr reference (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerreftest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by shared_ptr pointer reference (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointerreftest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by value (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.valuetest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my valuetest", val); // note slicing
+      verifyCount(2, k); // an extra reference for the upcast in the proxy class
+      verifyCount(1, kret);
+    }
+
+    // pass by pointer (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.pointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my pointertest-Derived", val);
+      verifyCount(2, k); // an extra reference for the upcast in the proxy class
+      verifyCount(1, kret);
+    }
+
+    // pass by ref (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.reftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my reftest-Derived", val);
+      verifyCount(2, k); // an extra reference for the upcast in the proxy class
+      verifyCount(1, kret);
+    }
+
+
+    ////////////////////////////////// Member variables ////////////////////////////////////////
+    // smart pointer by value
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("smart member value");
+      m.SmartMemberValue = k;
+      String val = k.getValue();
+      verifyValue("smart member value", val);
+      verifyCount(2, k);
+
+      Klass kmember = m.SmartMemberValue;
+      val = kmember.getValue();
+      verifyValue("smart member value", val);
+      verifyCount(3, kmember);
+      verifyCount(3, k);
+
+      m.Dispose();
+      verifyCount(2, kmember);
+      verifyCount(2, k);
+    }
+    // smart pointer by pointer
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("smart member pointer");
+      m.SmartMemberPointer = k;
+      String val = k.getValue();
+      verifyValue("smart member pointer", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.SmartMemberPointer;
+      val = kmember.getValue();
+      verifyValue("smart member pointer", val);
+      verifyCount(2, kmember);
+      verifyCount(2, k);
+
+      m.Dispose();
+      verifyCount(2, kmember);
+      verifyCount(2, k);
+    }
+    // smart pointer by reference
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("smart member reference");
+      m.SmartMemberReference = k;
+      String val = k.getValue();
+      verifyValue("smart member reference", val);
+      verifyCount(2, k);
+
+      Klass kmember = m.SmartMemberReference;
+      val = kmember.getValue();
+      verifyValue("smart member reference", val);
+      verifyCount(3, kmember);
+      verifyCount(3, k);
+
+      // The C++ reference refers to SmartMemberValue...
+      Klass kmemberVal = m.SmartMemberValue;
+      val = kmember.getValue();
+      verifyValue("smart member reference", val);
+      verifyCount(4, kmemberVal);
+      verifyCount(4, kmember);
+      verifyCount(4, k);
+
+      m.Dispose();
+      verifyCount(3, kmember);
+      verifyCount(3, k);
+    }
+    // plain by value
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("plain member value");
+      m.MemberValue = k;
+      String val = k.getValue();
+      verifyValue("plain member value", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.MemberValue;
+      val = kmember.getValue();
+      verifyValue("plain member value", val);
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+
+      m.Dispose();
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+    }
+    // plain by pointer
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("plain member pointer");
+      m.MemberPointer = k;
+      String val = k.getValue();
+      verifyValue("plain member pointer", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.MemberPointer;
+      val = kmember.getValue();
+      verifyValue("plain member pointer", val);
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+
+      m.Dispose();
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+    }
+    // plain by reference
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("plain member reference");
+      m.MemberReference = k;
+      String val = k.getValue();
+      verifyValue("plain member reference", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.MemberReference;
+      val = kmember.getValue();
+      verifyValue("plain member reference", val);
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+
+      m.Dispose();
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+    }
+
+    // null member variables
+    {
+      MemberVariables m = new MemberVariables();
+
+      // shared_ptr by value
+      Klass k = m.SmartMemberValue;
+      if (k != null)
+        throw new ApplicationException("expected null");
+      m.SmartMemberValue = null;
+      k = m.SmartMemberValue;
+      if (k != null)
+        throw new ApplicationException("expected null");
+      verifyCount(0, k);
+
+      // plain by value
+      try { m.MemberValue = null; throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
+    }
+
+    ////////////////////////////////// Global variables ////////////////////////////////////////
+    // smart pointer
+    {
+      Klass kglobal = li_boost_shared_ptr.GlobalSmartValue;
+      if (kglobal != null)
+        throw new ApplicationException("expected null");
+
+      Klass k = new Klass("smart global value");
+      li_boost_shared_ptr.GlobalSmartValue = k;
+      verifyCount(2, k);
+
+      kglobal = li_boost_shared_ptr.GlobalSmartValue;
+      String val = kglobal.getValue();
+      verifyValue("smart global value", val);
+      verifyCount(3, kglobal);
+      verifyCount(3, k);
+      verifyValue("smart global value", li_boost_shared_ptr.GlobalSmartValue.getValue());
+      li_boost_shared_ptr.GlobalSmartValue = null;
+    }
+    // plain value
+    {
+      Klass kglobal;
+
+      Klass k = new Klass("global value");
+      li_boost_shared_ptr.GlobalValue = k;
+      verifyCount(1, k);
+
+      kglobal = li_boost_shared_ptr.GlobalValue;
+      String val = kglobal.getValue();
+      verifyValue("global value", val);
+      verifyCount(1, kglobal);
+      verifyCount(1, k);
+      verifyValue("global value", li_boost_shared_ptr.GlobalValue.getValue());
+
+      try { li_boost_shared_ptr.GlobalValue = null; throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
+    }
+    // plain pointer
+    {
+      Klass kglobal = li_boost_shared_ptr.GlobalPointer;
+      if (kglobal != null)
+        throw new ApplicationException("expected null");
+
+      Klass k = new Klass("global pointer");
+      li_boost_shared_ptr.GlobalPointer = k;
+      verifyCount(1, k);
+
+      kglobal = li_boost_shared_ptr.GlobalPointer;
+      String val = kglobal.getValue();
+      verifyValue("global pointer", val);
+      verifyCount(1, kglobal);
+      verifyCount(1, k);
+      li_boost_shared_ptr.GlobalPointer = null;
+    }
+    // plain reference
+    {
+      Klass kglobal;
+
+      Klass k = new Klass("global reference");
+      li_boost_shared_ptr.GlobalReference = k;
+      verifyCount(1, k);
+
+      kglobal = li_boost_shared_ptr.GlobalReference;
+      String val = kglobal.getValue();
+      verifyValue("global reference", val);
+      verifyCount(1, kglobal);
+      verifyCount(1, k);
+
+      try { li_boost_shared_ptr.GlobalReference = null; throw new ApplicationException("Failed to catch null pointer"); } catch (ArgumentNullException) {}
+    }
+
+    ////////////////////////////////// Templates ////////////////////////////////////////
+    {
+      PairIntDouble pid = new PairIntDouble(10, 20.2);
+      if (pid.baseVal1 != 20 || pid.baseVal2 != 40.4)
+        throw new ApplicationException("Base values wrong");
+      if (pid.val1 != 10 || pid.val2 != 20.2)
+        throw new ApplicationException("Derived Values wrong");
+    }
+  }
+  private void verifyValue(String expected, String got) {
+    if (expected != got)
+      throw new Exception("verify value failed. Expected: " + expected + " Got: " + got);
+  }
+  private void verifyCount(int expected, Klass k) {
+    int got = li_boost_shared_ptr.use_count(k); 
+    if (expected != got)
+      throw new Exception("verify use_count failed. Expected: " + expected + " Got: " + got);
+  }
+}
diff --git a/trunk/Examples/test-suite/csharp/li_std_except_runme.cs b/trunk/Examples/test-suite/csharp/li_std_except_runme.cs
new file mode 100644
index 0000000..86ab448
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/li_std_except_runme.cs
@@ -0,0 +1,24 @@
+// This test tests all the methods in the C# collection wrapper
+
+using System;
+using li_std_exceptNamespace;
+
+public class li_std_except_runme {
+
+  public static void Main() {
+    Test test = new Test();
+    try { test.throw_bad_exception(); throw new Exception("throw_bad_exception failed"); } catch (ApplicationException) {}
+    try { test.throw_domain_error(); throw new Exception("throw_domain_error failed"); } catch (ApplicationException) {}
+    try { test.throw_exception(); throw new Exception("throw_exception failed"); } catch (ApplicationException) {}
+    try { test.throw_invalid_argument(); throw new Exception("throw_invalid_argument failed"); } catch (ArgumentException) {}
+    try { test.throw_length_error(); throw new Exception("throw_length_error failed"); } catch (IndexOutOfRangeException) {}
+    try { test.throw_logic_error(); throw new Exception("throw_logic_error failed"); } catch (ApplicationException) {}
+    try { test.throw_out_of_range(); throw new Exception("throw_out_of_range failed"); } catch (ArgumentOutOfRangeException) {}
+    try { test.throw_overflow_error(); throw new Exception("throw_overflow_error failed"); } catch (OverflowException) {}
+    try { test.throw_range_error(); throw new Exception("throw_range_error failed"); } catch (IndexOutOfRangeException) {}
+    try { test.throw_runtime_error(); throw new Exception("throw_runtime_error failed"); } catch (ApplicationException) {}
+    try { test.throw_underflow_error(); throw new Exception("throw_underflow_error failed"); } catch (OverflowException) {}
+  }
+
+}
+
diff --git a/trunk/Examples/test-suite/csharp/li_std_string_runme.cs b/trunk/Examples/test-suite/csharp/li_std_string_runme.cs
new file mode 100644
index 0000000..4c9d713
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/li_std_string_runme.cs
@@ -0,0 +1,100 @@
+using System;
+using li_std_stringNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+        // Checking expected use of %typemap(in) std::string {}
+        li_std_string.test_value("Fee");
+
+        // Checking expected result of %typemap(out) std::string {}
+        if (li_std_string.test_value("Fi") != "Fi")
+            throw new Exception("Test 1 failed");
+
+        // Verify type-checking for %typemap(in) std::string {}
+        try {
+            li_std_string.test_value(null);
+            throw new Exception("Test 2 failed");
+        } catch (ArgumentNullException) {
+        }
+
+        // Checking expected use of %typemap(in) const std::string & {}
+        li_std_string.test_const_reference("Fo");
+
+        // Checking expected result of %typemap(out) const std::string& {}
+        if (li_std_string.test_const_reference("Fum") != "Fum")
+            throw new Exception("Test 3 failed");
+
+        // Verify type-checking for %typemap(in) const std::string & {}
+        try {
+            li_std_string.test_const_reference(null);
+            throw new Exception("Test 4 failed");
+        } catch (ArgumentNullException) {
+        }
+
+        //
+        // Input and output typemaps for pointers and non-const references to
+        // std::string are *not* supported; the following tests confirm
+        // that none of these cases are slipping through.
+        //
+        
+        SWIGTYPE_p_std__string stringPtr = null;
+        
+        stringPtr = li_std_string.test_pointer_out();
+
+        li_std_string.test_pointer(stringPtr);
+
+        stringPtr = li_std_string.test_const_pointer_out();
+
+        li_std_string.test_const_pointer(stringPtr);
+
+        stringPtr = li_std_string.test_reference_out();
+
+        li_std_string.test_reference(stringPtr);
+
+        // Check throw exception specification
+        try {
+            li_std_string.test_throw();
+            throw new Exception("Test 5 failed");
+        } catch (ApplicationException e) {
+          if (e.Message != "test_throw message")
+            throw new Exception("Test 5 string check: " + e.Message);
+        }
+        try {
+            li_std_string.test_const_reference_throw();
+            throw new Exception("Test 6 failed");
+        } catch (ApplicationException e) {
+          if (e.Message != "test_const_reference_throw message")
+            throw new Exception("Test 6 string check: " + e.Message);
+        }
+
+        // Global variables
+        const string s = "initial string";
+        if (li_std_string.GlobalString2 != "global string 2")
+          throw new Exception("GlobalString2 test 1");
+        li_std_string.GlobalString2 = s;
+        if (li_std_string.GlobalString2 != s)
+          throw new Exception("GlobalString2 test 2");
+        if (li_std_string.ConstGlobalString != "const global string")
+          throw new Exception("ConstGlobalString test");
+
+        // Member variables
+        Structure myStructure = new Structure();
+        if (myStructure.MemberString2 != "member string 2")
+          throw new Exception("MemberString2 test 1");
+        myStructure.MemberString2 = s;
+        if (myStructure.MemberString2 != s)
+          throw new Exception("MemberString2 test 2");
+        if (myStructure.ConstMemberString != "const member string")
+          throw new Exception("ConstMemberString test");
+
+        if (Structure.StaticMemberString2 != "static member string 2")
+          throw new Exception("StaticMemberString2 test 1");
+        Structure.StaticMemberString2 = s;
+        if (Structure.StaticMemberString2 != s)
+          throw new Exception("StaticMemberString2 test 2");
+      if (Structure.ConstStaticMemberString != "const static member string")
+        throw new Exception("ConstStaticMemberString test");
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/li_std_vector_runme.cs b/trunk/Examples/test-suite/csharp/li_std_vector_runme.cs
new file mode 100644
index 0000000..7180873
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/li_std_vector_runme.cs
@@ -0,0 +1,606 @@
+// This test tests all the methods in the C# collection wrapper
+
+using System;
+using li_std_vectorNamespace;
+
+public class li_std_vector_runme {
+
+  private static readonly int collectionSize = 20;
+  private static readonly int midCollection = collectionSize/2;
+
+  public static DoubleVector myDoubleVector;
+  public static RealVector myRealVector;
+
+  public static void Main() {
+    // Setup collection
+    DoubleVector vect = new DoubleVector();
+    for (int i=0; i<collectionSize; i++) {
+      double num = i*10.1;
+      vect.Add(num);
+    }
+
+    // Count property test
+    if (vect.Count != collectionSize)
+      throw new Exception("Count test failed");
+
+    // IsFixedSize property test
+    if (vect.IsFixedSize)
+      throw new Exception("IsFixedSize test failed");
+
+    // IsReadOnly property test
+    if (vect.IsReadOnly)
+      throw new Exception("IsReadOnly test failed");
+
+    // Item indexing
+    vect[0] = 200.1;
+    if (vect[0] != 200.1)
+      throw new Exception("Item property test failed");
+    vect[0] = 0*10.1;
+    try {
+      vect[-1] = 777.1;
+      throw new Exception("Item out of range (1) test failed");
+    } catch (ArgumentOutOfRangeException) {
+    }
+    try {
+      vect[vect.Count] = 777.1;
+      throw new Exception("Item out of range (2) test failed");
+    } catch (ArgumentOutOfRangeException) {
+    }
+
+    // CopyTo() test
+    {
+      double[] outputarray = new double[collectionSize];
+      vect.CopyTo(outputarray);
+      int index = 0;
+      foreach(double val in outputarray) {
+        if (vect[index] != val)
+          throw new Exception("CopyTo (1) test failed, index:" + index);
+        index++;
+      }
+    }
+    {
+      double[] outputarray = new double[midCollection+collectionSize];
+      vect.CopyTo(outputarray, midCollection);
+      int index = midCollection;
+      foreach(double val in vect) {
+        if (outputarray[index] != val)
+          throw new Exception("CopyTo (2) test failed, index:" + index);
+        index++;
+      }
+    }
+    {
+      double[] outputarray = new double[3];
+      vect.CopyTo(10, outputarray, 1, 2);
+        if (outputarray[0] != 0.0 || outputarray[1] != vect[10] || outputarray[2] != vect[11])
+          throw new Exception("CopyTo (3) test failed");
+    }
+    {
+      double[] outputarray = new double[collectionSize-1];
+      try {
+        vect.CopyTo(outputarray);
+        throw new Exception("CopyTo (4) test failed");
+      } catch (ArgumentException) {
+      }
+    }
+    {
+      double[,] outputarray = new double[collectionSize,collectionSize];
+      try {
+        vect.CopyTo(outputarray);
+        throw new Exception("CopyTo (5) test failed");
+      } catch (ArgumentException) {
+      }
+    }
+    {
+      StructVector inputvector = new StructVector();
+      int arrayLen = 10;
+      for (int i=0; i<arrayLen; i++) {
+        inputvector.Add(new Struct(i/10.0));
+      }
+      Struct[] outputarray = new Struct[arrayLen];
+      inputvector.CopyTo(outputarray);
+      for(int i=0; i<arrayLen; i++) {
+        if (outputarray[i].num != inputvector[i].num)
+          throw new Exception("CopyTo (6) test failed, i:" + i);
+      }
+      foreach (Struct s in inputvector) {
+        s.num += 20.0;
+      }
+      for(int i=0; i<arrayLen; i++) {
+        if (outputarray[i].num + 20.0 != inputvector[i].num )
+          throw new Exception("CopyTo (7) test failed (only a shallow copy was made), i:" + i);
+      }
+    }
+    {
+      try {
+        vect.CopyTo(null);
+        throw new Exception("CopyTo (8) test failed");
+      } catch (ArgumentNullException) {
+      }
+    }
+
+    // Contains() test
+    if (!vect.Contains(0*10.1))
+      throw new Exception("Contains test 1 failed");
+    if (!vect.Contains(10*10.1))
+      throw new Exception("Contains test 2 failed");
+    if (!vect.Contains(19*10.1))
+      throw new Exception("Contains test 3 failed");
+    if (vect.Contains(20*10.1))
+      throw new Exception("Contains test 4 failed");
+
+    {
+      // ICollection constructor
+      double[] doubleArray = new double[] { 0.0, 11.1, 22.2, 33.3, 44.4, 55.5, 33.3 };
+      DoubleVector dv = new DoubleVector(doubleArray);
+      if (doubleArray.Length != dv.Count)
+        throw new Exception("ICollection constructor length check failed: " + doubleArray.Length + "-" + dv.Count);
+      for (int i=0; i<doubleArray.Length; i++) {
+        if (doubleArray[i] != dv[i])
+          throw new Exception("ICollection constructor failed, index:" + i);
+      }
+      {
+        Struct[] structArray = new Struct[] { new Struct(0.0), new Struct(11.1), new Struct(22.2), new Struct(33.3) };
+        StructVector sv = new StructVector(structArray);
+        for (int i=0; i<structArray.Length; i++) {
+          structArray[i].num += 200.0;
+        }
+        for (int i=0; i<structArray.Length; i++) {
+          if (structArray[i].num != sv[i].num + 200.0)
+            throw new Exception("ICollection constructor not a deep copy, index:" + i);
+        }
+      }
+      try {
+        new DoubleVector(null);
+        throw new Exception("ICollection constructor null test failed");
+      } catch (ArgumentNullException) {
+      }
+
+      // IndexOf() test
+      for (int i=0; i<collectionSize; i++) {
+        if (vect.IndexOf(i*10.1) != i)
+          throw new Exception("IndexOf test " + i + " failed");
+      }
+      if (vect.IndexOf(200.1) != -1)
+        throw new Exception("IndexOf non-existent test failed");
+      if (dv.IndexOf(33.3) != 3)
+        throw new Exception("IndexOf position test failed");
+
+      // LastIndexOf() test
+      for (int i=0; i<collectionSize; i++) {
+        if (vect.LastIndexOf(i*10.1) != i)
+          throw new Exception("LastIndexOf test " + i + " failed");
+      }
+      if (vect.LastIndexOf(200.1) != -1)
+        throw new Exception("LastIndexOf non-existent test failed");
+      if (dv.LastIndexOf(33.3) != 6)
+        throw new Exception("LastIndexOf position test failed");
+    }
+    {
+      // Repeat() test
+      try {
+        myDoubleVector = DoubleVector.Repeat(77.7, -1);
+        throw new Exception("Repeat negative count test failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      DoubleVector dv = DoubleVector.Repeat(77.7, 5);
+      if (dv.Count != 5)
+        throw new Exception("Repeat count test failed");
+      
+      // Also tests enumerator
+      System.Collections.IEnumerator myEnumerator = dv.GetEnumerator();
+      while ( myEnumerator.MoveNext() ) {
+         if ((double)myEnumerator.Current != 77.7)
+           throw new Exception("Repeat test failed");
+      }
+    }
+
+    {
+      // InsertRange() test
+      DoubleVector dvect = new DoubleVector();
+      for (int i=0; i<5; i++) {
+        dvect.Add(1000.0*i);
+      }
+      vect.InsertRange(midCollection, dvect);
+      if (vect.Count != collectionSize+dvect.Count)
+        throw new Exception("InsertRange test size failed");
+
+      for (int i=0; i<midCollection; i++) {
+        if (vect.IndexOf(i*10.1) != i)
+          throw new Exception("InsertRange (1) test " + i + " failed");
+      }
+      for (int i=0; i<dvect.Count; i++) {
+        if (vect[i+midCollection] != dvect[i])
+          throw new Exception("InsertRange (2) test " + i + " failed");
+      }
+      for (int i=midCollection; i<collectionSize; i++) {
+        if (vect.IndexOf(i*10.1) != i+dvect.Count)
+          throw new Exception("InsertRange (3) test " + i + " failed");
+      }
+      try {
+        vect.InsertRange(0, null);
+        throw new Exception("InsertRange (4) test failed");
+      } catch (ArgumentNullException) {
+      }
+
+      // RemoveRange() test
+      vect.RemoveRange(0, 0);
+      vect.RemoveRange(midCollection, dvect.Count);
+      if (vect.Count != collectionSize)
+        throw new Exception("RemoveRange test size failed");
+      for (int i=0; i<collectionSize; i++) {
+        if (vect.IndexOf(i*10.1) != i)
+          throw new Exception("RemoveRange test " + i + " failed");
+      }
+      try {
+        vect.RemoveRange(-1, 0);
+        throw new Exception("RemoveRange index out of range (1) test failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        vect.RemoveRange(0, -1);
+        throw new Exception("RemoveRange count out of range (2) test failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        vect.RemoveRange(collectionSize+1, 0);
+        throw new Exception("RemoveRange index and count out of range (1) test failed");
+      } catch (ArgumentException) {
+      }
+      try {
+        vect.RemoveRange(0, collectionSize+1);
+        throw new Exception("RemoveRange index and count out of range (2) test failed");
+      } catch (ArgumentException) {
+      }
+
+      // AddRange() test
+      vect.AddRange(dvect);
+      if (vect.Count != collectionSize+dvect.Count)
+        throw new Exception("AddRange test size failed");
+      for (int i=0; i<collectionSize; i++) {
+        if (vect.IndexOf(i*10.1) != i)
+          throw new Exception("AddRange (1) test " + i + " failed");
+      }
+      for (int i=0; i<dvect.Count; i++) {
+        if (vect[i+collectionSize] != dvect[i])
+          throw new Exception("AddRange (2) test " + i + " failed");
+      }
+      try {
+        vect.AddRange(null);
+        throw new Exception("AddRange (3) test failed");
+      } catch (ArgumentNullException) {
+      }
+      vect.RemoveRange(collectionSize, dvect.Count);
+
+      // GetRange() test
+      int rangeSize = 5;
+      DoubleVector returnedVec = vect.GetRange(0, 0);
+      returnedVec = vect.GetRange(midCollection, rangeSize);
+      if (returnedVec.Count != rangeSize)
+        throw new Exception("GetRange test size failed");
+      for (int i=0; i<rangeSize; i++) {
+        if (returnedVec.IndexOf((i+midCollection)*10.1) != i)
+          throw new Exception("GetRange test " + i + " failed");
+      }
+      try {
+        vect.GetRange(-1, 0);
+        throw new Exception("GetRange index out of range (1) test failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        vect.GetRange(0, -1);
+        throw new Exception("GetRange count out of range (2) test failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        vect.GetRange(collectionSize+1, 0);
+        throw new Exception("GetRange index and count out of range (1) test failed");
+      } catch (ArgumentException) {
+      }
+      try {
+        vect.GetRange(0, collectionSize+1);
+        throw new Exception("GetRange index and count out of range (2) test failed");
+      } catch (ArgumentException) {
+      }
+      {
+        StructVector inputvector = new StructVector();
+        int arrayLen = 10;
+        for (int i=0; i<arrayLen; i++) {
+          inputvector.Add(new Struct(i/10.0));
+        }
+        StructVector outputvector = inputvector.GetRange(0,arrayLen);
+        for(int i=0; i<arrayLen; i++) {
+          if (outputvector[i].num != inputvector[i].num)
+            throw new Exception("GetRange (1) test failed, i:" + i);
+        }
+        foreach (Struct s in inputvector) {
+          s.num += 20.0;
+        }
+        for(int i=0; i<arrayLen; i++) {
+          if (outputvector[i].num + 20.0 != inputvector[i].num )
+            throw new Exception("GetRange (2) test failed (only a shallow copy was made), i:" + i);
+        }
+      }
+    }
+
+    // Insert() test
+    int pos = 0;
+    int count = vect.Count;
+    vect.Insert(pos, -5.1);
+    count++;
+    if (vect.Count != count || vect[pos] != -5.1)
+      throw new Exception("Insert at beginning test failed");
+
+    pos = midCollection;
+    vect.Insert(pos, 85.1);
+    count++;
+    if (vect.Count != count || vect[pos] != 85.1)
+      throw new Exception("Insert at " + pos + " test failed");
+
+    pos = vect.Count;
+    vect.Insert(pos, 195.1);
+    count++;
+    if (vect.Count != count || vect[pos] != 195.1)
+      throw new Exception("Insert at end test failed");
+
+    pos = vect.Count+1;
+    try {
+      vect.Insert(pos, 222.1); // should throw
+      throw new Exception("Insert after end (1) test failed");
+    } catch (ArgumentOutOfRangeException) {
+    }
+    if (vect.Count != count)
+      throw new Exception("Insert after end (2) test failed");
+
+    pos = -1;
+    try {
+      vect.Insert(pos, 333.1); // should throw
+      throw new Exception("Insert before start (1) test failed");
+    } catch (ArgumentOutOfRangeException) {
+    }
+    if (vect.Count != count)
+      throw new Exception("Insert before start (2) test failed");
+
+    // Remove() test
+    vect.Remove(195.1);
+    count--;
+    vect.Remove(-5.1);
+    count--;
+    vect.Remove(85.1);
+    count--;
+    vect.Remove(9999.1); // element does not exist, should quietly do nothing
+    if (vect.Count != count)
+      throw new Exception("Remove count check test failed");
+    for (int i=0; i<collectionSize; i++) {
+      if (vect[i] != i*10.1)
+        throw new Exception("Remove test failed, index:" + i);
+    }
+
+    // RemoveAt() test
+    vect.Insert(0, -4.1);
+    vect.Insert(midCollection, 84.1);
+    vect.Insert(vect.Count, 194.1);
+    vect.RemoveAt(vect.Count-1);
+    vect.RemoveAt(midCollection);
+    vect.RemoveAt(0);
+    try {
+      vect.RemoveAt(-1);
+      throw new Exception("RemoveAt test (1) failed");
+    } catch (ArgumentOutOfRangeException) {
+    }
+    try {
+      vect.RemoveAt(vect.Count);
+      throw new Exception("RemoveAt test (2) failed");
+    } catch (ArgumentOutOfRangeException) {
+    }
+    for (int i=0; i<collectionSize; i++) {
+      if (vect[i] != i*10.1)
+        throw new Exception("RemoveAt test (3) failed, index:" + i);
+    }
+
+    {
+      // Capacity test
+      try {
+        myDoubleVector = new DoubleVector(-1);
+        throw new Exception("constructor setting capacity (1) test failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+
+      DoubleVector dv = new DoubleVector(10);
+      if (dv.Capacity != 10 || dv.Count != 0)
+        throw new Exception("constructor setting capacity (2) test failed");
+      dv.Capacity = 20;
+      if (dv.Capacity != 20)
+        throw new Exception("capacity test (1) failed");
+      dv.Add(1.11);
+      try {
+        dv.Capacity = dv.Count-1;
+        throw new Exception("capacity test (2) failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+
+      // SetRange() test
+      for (int i=dv.Count; i<collectionSize; i++) {
+        dv.Add(0.0);
+      }
+      dv.SetRange(0, vect);
+      if (dv.Count != collectionSize)
+        throw new Exception("SetRange count check test failed");
+      for (int i=0; i<collectionSize; i++) {
+        if (vect[i] != dv[i])
+          throw new Exception("SetRange test (1) failed, index:" + i);
+      }
+      try {
+        dv.SetRange(-1, vect);
+        throw new Exception("SetRange test (2) failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        dv.SetRange(1, vect);
+        throw new Exception("SetRange test (3) failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        vect.SetRange(0, null);
+        throw new Exception("SetRange (4) test failed");
+      } catch (ArgumentNullException) {
+      }
+
+      // Reverse() test
+      dv.Reverse();
+      for (int i=0; i<collectionSize; i++) {
+        if (vect[i] != dv[collectionSize-i-1])
+          throw new Exception("Reverse test (1) failed, index:" + i);
+      }
+      dv.Reverse(0, collectionSize);
+      for (int i=0; i<collectionSize; i++) {
+        if (vect[i] != dv[i])
+          throw new Exception("Reverse test (2) failed, index:" + i);
+      }
+      dv.Reverse(0, 0); // should do nothing!
+      for (int i=0; i<collectionSize; i++) {
+        if (vect[i] != dv[i])
+          throw new Exception("Reverse test (3) failed, index:" + i);
+      }
+      try {
+        dv.Reverse(-1, 0);
+        throw new Exception("Reverse test (4) failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        dv.Reverse(0, -1);
+        throw new Exception("Reverse test (5) failed");
+      } catch (ArgumentOutOfRangeException) {
+      }
+      try {
+        dv.Reverse(collectionSize+1, 0);
+        throw new Exception("Reverse test (6) failed");
+      } catch (ArgumentException) {
+      }
+      try {
+        dv.Reverse(0, collectionSize+1);
+        throw new Exception("Reverse test (7) failed");
+      } catch (ArgumentException) {
+      }
+    }
+
+    // foreach test
+    {
+      int index=0;
+      foreach (double s in vect) {
+        if (s != index*10.1)
+          throw new Exception("foreach test failed, index:" + index);
+        index++;
+      }
+    }
+
+    // Clear() test
+    vect.Clear();
+    if (vect.Count != 0)
+      throw new Exception("Clear failed");
+
+    // Finally test the methods being wrapped
+    {
+      IntVector iv = new IntVector();
+      for (int i=0; i<4; i++) {
+        iv.Add(i);
+      }
+
+      double x = li_std_vector.average(iv);
+      x += li_std_vector.average( new IntVector( new int[] {1, 2, 3, 4} ) );
+      myRealVector = li_std_vector.half( new RealVector( new float[] {10F, 10.5F, 11F, 11.5F} ) );
+
+      DoubleVector dvec = new DoubleVector();
+      for (int i=0; i<10; i++) {
+        dvec.Add(i/2.0);
+      }
+      li_std_vector.halve_in_place(dvec);
+    }
+
+    // More wrapped methods
+    {
+      RealVector v0 = li_std_vector.vecreal(new RealVector());
+      float flo = 123.456f;
+      v0.Add(flo);
+      flo = v0[0];
+
+      IntVector v1 = li_std_vector.vecintptr(new IntVector());
+      IntPtrVector v2 = li_std_vector.vecintptr(new IntPtrVector());
+      IntConstPtrVector v3 = li_std_vector.vecintconstptr(new IntConstPtrVector());
+
+      v1.Add(123);
+      v2.Clear();
+      v3.Clear();
+
+      StructVector v4 = li_std_vector.vecstruct(new StructVector());
+      StructPtrVector v5 = li_std_vector.vecstructptr(new StructPtrVector());
+      StructConstPtrVector v6 = li_std_vector.vecstructconstptr(new StructConstPtrVector());
+
+      v4.Add(new Struct(123));
+      v5.Add(new Struct(123));
+      v6.Add(new Struct(123));
+    }
+
+    // Test vectors of pointers
+    {
+      StructPtrVector inputvector = new StructPtrVector();
+      int arrayLen = 10;
+      for (int i=0; i<arrayLen; i++) {
+        inputvector.Add(new Struct(i/10.0));
+      }
+      Struct[] outputarray = new Struct[arrayLen];
+      inputvector.CopyTo(outputarray);
+      for(int i=0; i<arrayLen; i++) {
+        if (outputarray[i].num != inputvector[i].num)
+          throw new Exception("StructPtrVector test (1) failed, i:" + i);
+      }
+      foreach (Struct s in inputvector) {
+        s.num += 20.0;
+      }
+      for(int i=0; i<arrayLen; i++) {
+        if (outputarray[i].num != 20.0 + i/10.0)
+          throw new Exception("StructPtrVector test (2) failed (a deep copy was incorrectly made), i:" + i);
+      }
+
+      int rangeSize = 5;
+      int mid = arrayLen/2;
+      StructPtrVector returnedVec = inputvector.GetRange(mid, rangeSize);
+      for (int i=0; i<rangeSize; i++) {
+        if (inputvector[i+mid].num != returnedVec[i].num)
+          throw new Exception("StructPtrVector test (3) failed, i:" + i);
+      }
+    }
+
+    // Test vectors of const pointers
+    {
+      StructConstPtrVector inputvector = new StructConstPtrVector();
+      int arrayLen = 10;
+      for (int i=0; i<arrayLen; i++) {
+        inputvector.Add(new Struct(i/10.0));
+      }
+      Struct[] outputarray = new Struct[arrayLen];
+      inputvector.CopyTo(outputarray);
+      for(int i=0; i<arrayLen; i++) {
+        if (outputarray[i].num != inputvector[i].num)
+          throw new Exception("StructConstPtrVector test (1) failed, i:" + i);
+      }
+      foreach (Struct s in inputvector) {
+        s.num += 20.0;
+      }
+      for(int i=0; i<arrayLen; i++) {
+        if (outputarray[i].num != 20.0 + i/10.0)
+          throw new Exception("StructConstPtrVector test (2) failed (a deep copy was incorrectly made), i:" + i);
+      }
+
+      int rangeSize = 5;
+      int mid = arrayLen/2;
+      StructConstPtrVector returnedVec = inputvector.GetRange(mid, rangeSize);
+      for (int i=0; i<rangeSize; i++) {
+        if (inputvector[i+mid].num != returnedVec[i].num)
+          throw new Exception("StructConstPtrVector test (3) failed, i:" + i);
+      }
+    }
+
+  }
+
+}
+
diff --git a/trunk/Examples/test-suite/csharp/li_std_wstring_runme.cs b/trunk/Examples/test-suite/csharp/li_std_wstring_runme.cs
new file mode 100755
index 0000000..fe663a3
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/li_std_wstring_runme.cs
@@ -0,0 +1,76 @@
+using System;
+using li_std_wstringNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      char y='h';
+
+      if (li_std_wstring.test_wcvalue(y) != y)
+        throw new Exception("bad string mapping:" + li_std_wstring.test_wcvalue(y));
+
+      if (li_std_wstring.test_wcvalue_w() != 'W')
+        throw new Exception("bad string mapping:" + li_std_wstring.test_wcvalue_w());
+
+      string x="hello";
+
+      if (li_std_wstring.test_ccvalue(x) != x)
+        throw new Exception("bad string mapping");
+
+      if (li_std_wstring.test_cvalue(x) != x)
+        throw new Exception("bad string mapping");
+
+
+      if (li_std_wstring.test_value(x) != x)
+        throw new Exception("bad string mapping: " + x + li_std_wstring.test_value(x));
+
+      if (li_std_wstring.test_const_reference(x) != x)
+        throw new Exception("bad string mapping");
+
+
+      string s = "he";
+      s = s + "llo";
+
+      if (s != x)
+        throw new Exception("bad string mapping: " + s + x);
+
+      if (li_std_wstring.test_value(s) != x)
+        throw new Exception("bad string mapping");
+
+      if (li_std_wstring.test_const_reference(s) != x)
+        throw new Exception("bad string mapping");
+
+      string a = s;
+
+      if (li_std_wstring.test_value(a) != x)
+        throw new Exception("bad string mapping");
+
+      if (li_std_wstring.test_const_reference(a) != x)
+        throw new Exception("bad string mapping");
+
+      string b = " world";
+
+      if (a + b != "hello world")
+        throw new Exception("bad string mapping");
+
+      if (a + " world" != "hello world")
+        throw new Exception("bad string mapping");
+
+      if ("hello" + b != "hello world")
+        throw new Exception("bad string mapping");
+
+      s = "hello world";
+
+      B myB = new B("hi");
+
+      myB.name = "hello";
+      if (myB.name != "hello")
+        throw new Exception("bad string mapping");
+
+      myB.a = "hello";
+      if (myB.a != "hello")
+        throw new Exception("bad string mapping");
+    }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/li_typemaps_runme.cs b/trunk/Examples/test-suite/csharp/li_typemaps_runme.cs
new file mode 100644
index 0000000..fde6e8b
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/li_typemaps_runme.cs
@@ -0,0 +1,101 @@
+
+// Check a few of the INPUT, OUTPUT and INOUT typemaps.
+
+using System;
+using li_typemapsNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    // Check double INPUT typemaps
+    if (li_typemaps.in_double(22.22) != 22.22) exit_test("in_double");
+    if (li_typemaps.inr_double(22.22) != 22.22) exit_test("inr_double");
+
+    // Check double OUTPUT typemaps
+    {
+      double var = 44.44;
+      li_typemaps.out_double(22.22, out var);
+      if (var != 22.22) exit_test("out_double");
+    }
+    {
+      double var = 44.44;
+      li_typemaps.outr_double(22.22, out var);
+      if (var != 22.22) exit_test("outr_double");
+    }
+
+    // Check double INOUT typemaps
+    {
+      double var = 44.44;
+      li_typemaps.inout_double(ref var);
+      if (var != 44.44) exit_test("inout_double");
+    }
+    {
+      double var = 44.44;
+      li_typemaps.inoutr_double(ref var);
+      if (var != 44.44) exit_test("inoutr_double");
+    }
+
+    // Check unsigned long long INPUT typemaps
+    if (li_typemaps.in_ulonglong(20) != 20) exit_test("in_ulonglong");
+    if (li_typemaps.inr_ulonglong(20) != 20) exit_test("inr_ulonglong");
+
+    // Check unsigned long long OUTPUT typemaps
+    {
+      ulong var = 40;
+      li_typemaps.out_ulonglong(20, out var);
+      if (var != 20) exit_test("out_ulonglong");
+    }
+    {
+      ulong var = 40;
+      li_typemaps.outr_ulonglong(20, out var);
+      if (var != 20) exit_test("outr_ulonglong");
+    }
+
+    // Check unsigned long long INOUT typemaps
+    {
+      ulong var = 40;
+      li_typemaps.inout_ulonglong(ref var);
+      if (var != 40) exit_test("inout_ulonglong");
+    }
+    {
+      ulong var = 40;
+      li_typemaps.inoutr_ulonglong(ref var);
+      if (var != 40) exit_test("inoutr_ulonglong");
+    }
+
+    // Check unsigned bool INPUT typemaps
+    if (li_typemaps.in_bool(false) != false) exit_test("in_bool");
+    if (li_typemaps.inr_bool(false) != false) exit_test("inr_bool");
+
+    // Check unsigned bool OUTPUT typemaps
+    {
+      bool var = false;
+      li_typemaps.out_bool(true, out var);
+      if (var != true) exit_test("out_bool");
+    }
+    {
+      bool var = false;
+      li_typemaps.outr_bool(true, out var);
+      if (var != true) exit_test("outr_bool");
+    }
+
+    // Check unsigned bool INOUT typemaps
+    {
+      bool var = false;
+      li_typemaps.inout_bool(ref var);
+      if (var != false) exit_test("inout_bool");
+    }
+    {
+      bool var = false;
+      li_typemaps.inoutr_bool(ref var);
+      if (var != false) exit_test("inoutr_bool");
+    }
+  }
+
+  private static void exit_test(String funcName) {
+    throw new Exception("Test FAILED in function " + funcName);
+  }
+
+}
+
diff --git a/trunk/Examples/test-suite/csharp/long_long_runme.cs b/trunk/Examples/test-suite/csharp/long_long_runme.cs
new file mode 100644
index 0000000..51d91e2
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/long_long_runme.cs
@@ -0,0 +1,41 @@
+
+// This is the long_long runtime testcase. It checks that the long long and
+// unsigned long long types work.
+
+using System;
+using long_longNamespace;
+
+public class long_long_runme {
+
+  public static void Main() {
+
+    check_ll(0L);
+    check_ll(0x7FFFFFFFFFFFFFFFL);
+    check_ll(-10);
+
+    check_ull(0);
+    check_ull(127);
+    check_ull(128);
+    check_ull(9223372036854775807); //0x7FFFFFFFFFFFFFFFL
+    check_ull(18446744073709551615); //0xFFFFFFFFFFFFFFFFL
+  }
+
+  public static void check_ll(long ll) {
+    long_long.ll = ll;
+    long ll_check = long_long.ll;
+    if (ll != ll_check) {
+      string ErrorMessage = "Runtime test using long long failed. ll=" + ll + " ll_check=" + ll_check;
+      throw new Exception(ErrorMessage);
+    }
+  }
+
+  public static void check_ull(ulong ull) {
+    long_long.ull = ull;
+    ulong ull_check = long_long.ull;
+    if (ull != ull_check) {
+      string ErrorMessage = "Runtime test using unsigned long long failed. ull=" + ull + " ull_check=" + ull_check;
+      throw new Exception(ErrorMessage);
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/member_pointer_runme.cs b/trunk/Examples/test-suite/csharp/member_pointer_runme.cs
new file mode 100644
index 0000000..ad324d4
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/member_pointer_runme.cs
@@ -0,0 +1,47 @@
+using System;
+using member_pointerNamespace;
+
+public class runme {
+  public static SWIGTYPE_m_Shape__f_void__double memberPtr = null;
+  static void Main() {
+    // Get the pointers
+
+    SWIGTYPE_m_Shape__f_void__double area_pt = member_pointer.areapt();
+    SWIGTYPE_m_Shape__f_void__double perim_pt = member_pointer.perimeterpt();
+
+    // Create some objects
+
+    Square s = new Square(10);
+
+    // Do some calculations
+
+    check( "Square area ", 100.0, member_pointer.do_op(s,area_pt) );
+    check( "Square perim", 40.0, member_pointer.do_op(s,perim_pt) );
+
+    memberPtr = member_pointer.areavar;
+    memberPtr = member_pointer.perimetervar;
+
+    // Try the variables
+    check( "Square area ", 100.0, member_pointer.do_op(s,member_pointer.areavar) );
+    check( "Square perim", 40.0, member_pointer.do_op(s,member_pointer.perimetervar) );
+
+    // Modify one of the variables
+    member_pointer.areavar = perim_pt;
+
+    check( "Square perimeter", 40.0, member_pointer.do_op(s,member_pointer.areavar) );
+
+    // Try the constants
+
+    memberPtr = member_pointer.AREAPT;
+    memberPtr = member_pointer.PERIMPT;
+    memberPtr = member_pointer.NULLPT;
+
+    check( "Square area ", 100.0, member_pointer.do_op(s,member_pointer.AREAPT) );
+    check( "Square perim", 40.0, member_pointer.do_op(s,member_pointer.PERIMPT) );
+
+  }
+  private static void check(string what, double expected, double actual) {
+    if (expected != actual)
+      throw new ApplicationException("Failed: " + what + " Expected: " + expected + " Actual: " + actual);
+  }
+}
diff --git a/trunk/Examples/test-suite/csharp/operator_overload_runme.cs b/trunk/Examples/test-suite/csharp/operator_overload_runme.cs
new file mode 100644
index 0000000..294bb7e
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/operator_overload_runme.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Threading;
+using operator_overloadNamespace;
+
+public class runme
+{
+  static void Main() 
+  {
+    Op.sanity_check();
+    {
+      Op op = new Op(100);
+      Op opNew = op++;
+      if (op.i != 101) throw new Exception("operator++ postfix failed (op)");
+      if (opNew.i != 100) throw new Exception("operator++ postfix failed (opNew)");
+    }
+    {
+      Op op = new Op(100);
+      Op opNew = op--;
+      if (op.i != 99) throw new Exception("operator-- postfix failed (op)");
+      if (opNew.i != 100) throw new Exception("operator-- postfix failed (opNew)");
+    }
+    {
+      Op op = new Op(100);
+      Op opNew = ++op;
+      if (op.i != 101) throw new Exception("operator++ prefix failed (op)");
+      if (opNew.i != 101) throw new Exception("operator++ prefix failed (opNew)");
+    }
+    {
+      Op op = new Op(100);
+      Op opNew = --op;
+      if (op.i != 99) throw new Exception("operator-- prefix failed (op)");
+      if (opNew.i != 99) throw new Exception("operator-- prefix failed (opNew)");
+    }
+
+    // overloaded operator class
+    Op k = new OpDerived(3);
+    int check_k = k.IntCast();
+    Assert(check_k == 6);
+  }
+
+  public static void Assert(bool b) {
+    if (!b)
+      throw new Exception("Assertion failed");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/overload_complicated_runme.cs b/trunk/Examples/test-suite/csharp/overload_complicated_runme.cs
new file mode 100755
index 0000000..1374182
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/overload_complicated_runme.cs
@@ -0,0 +1,55 @@
+using System;
+using overload_complicatedNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      SWIGTYPE_p_int pInt = null;
+
+      // Check the correct constructors are available
+      Pop p = new Pop(pInt);
+
+      p = new Pop(pInt, false);
+
+      // Check overloaded in const only and pointers/references which target languages cannot disambiguate
+      if (p.hip(false) != 701)
+        throw new Exception("Test 1 failed");
+
+      if (p.hip(pInt) != 702)
+        throw new Exception("Test 2 failed");
+
+      // Reverse the order for the above
+      if (p.hop(pInt) != 805)
+        throw new Exception("Test 3 failed");
+
+      if (p.hop(false) != 801)
+        throw new Exception("Test 4 failed");
+
+      // Few more variations and order shuffled
+      if (p.pop(false) != 901)
+        throw new Exception("Test 5 failed");
+
+      if (p.pop(pInt) != 902)
+        throw new Exception("Test 6 failed");
+
+      if (p.pop() != 905)
+        throw new Exception("Test 7 failed");
+
+      // Overload on const only
+      if (p.bop(pInt) != 1001)
+        throw new Exception("Test 8 failed");
+
+      if (p.bip(pInt) != 2001)
+        throw new Exception("Test 9 failed");
+
+      // Globals
+      if (overload_complicated.muzak(false) != 3001)
+        throw new Exception("Test 10 failed");
+
+      if (overload_complicated.muzak(pInt) != 3002)
+        throw new Exception("Test 11 failed");
+    }
+}
+
+
diff --git a/trunk/Examples/test-suite/csharp/overload_template_runme.cs b/trunk/Examples/test-suite/csharp/overload_template_runme.cs
new file mode 100644
index 0000000..e491016
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/overload_template_runme.cs
@@ -0,0 +1,152 @@
+using System;
+using overload_templateNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      int f = overload_template.foo();
+
+      f += overload_template.max(3,4);
+      double b = overload_template.max(3.4,5.2);
+      b++; // warning suppression
+
+      // mix 1
+      if (overload_template.mix1("hi") != 101)
+        throw new Exception ("mix1(const char*)");
+
+      if (overload_template.mix1(1.0, 1.0) != 102)
+        throw new Exception ("mix1(double, const double &)");
+
+      if (overload_template.mix1(1.0) != 103)
+        throw new Exception ("mix1(double)");
+
+      // mix 2
+      if (overload_template.mix2("hi") != 101)
+        throw new Exception ("mix2(const char*)");
+
+      if (overload_template.mix2(1.0, 1.0) != 102)
+        throw new Exception ("mix2(double, const double &)");
+
+      if (overload_template.mix2(1.0) != 103)
+        throw new Exception ("mix2(double)");
+
+      // mix 3
+      if (overload_template.mix3("hi") != 101)
+        throw new Exception ("mix3(const char*)");
+
+      if (overload_template.mix3(1.0, 1.0) != 102)
+        throw new Exception ("mix3(double, const double &)");
+
+      if (overload_template.mix3(1.0) != 103)
+        throw new Exception ("mix3(double)");
+
+      // Combination 1
+      if (overload_template.overtparams1(100) != 10)
+        throw new Exception ("overtparams1(int)");
+
+      if (overload_template.overtparams1(100.0, 100) != 20)
+        throw new Exception ("overtparams1(double, int)");
+
+      // Combination 2
+      if (overload_template.overtparams2(100.0, 100) != 40)
+        throw new Exception ("overtparams2(double, int)");
+
+      // Combination 3
+      if (overload_template.overloaded() != 60)
+        throw new Exception ("overloaded()");
+
+      if (overload_template.overloaded(100.0, 100) != 70)
+        throw new Exception ("overloaded(double, int)");
+
+      // Combination 4
+      if (overload_template.overloadedagain("hello") != 80)
+        throw new Exception ("overloadedagain(const char *)");
+
+      if (overload_template.overloadedagain() != 90)
+        throw new Exception ("overloadedagain(double)");
+
+      // specializations
+      if (overload_template.specialization(10) != 202)
+        throw new Exception ("specialization(int)");
+
+      if (overload_template.specialization(10.0) != 203)
+        throw new Exception ("specialization(double)");
+
+      if (overload_template.specialization(10, 10) != 204)
+        throw new Exception ("specialization(int, int)");
+
+      if (overload_template.specialization(10.0, 10.0) != 205)
+        throw new Exception ("specialization(double, double)");
+
+      if (overload_template.specialization("hi", "hi") != 201)
+        throw new Exception ("specialization(const char *, const char *)");
+
+
+      // simple specialization
+      overload_template.xyz();
+      overload_template.xyz_int();
+      overload_template.xyz_double();
+
+
+      // a bit of everything
+      if (overload_template.overload("hi") != 0)
+        throw new Exception ("overload()");
+
+      if (overload_template.overload(1) != 10)
+        throw new Exception ("overload(int t)");
+
+      if (overload_template.overload(1, 1) != 20)
+        throw new Exception ("overload(int t, const int &)");
+
+      if (overload_template.overload(1, "hello") != 30)
+        throw new Exception ("overload(int t, const char *)");
+
+      Klass k = new Klass();
+      if (overload_template.overload(k) != 10)
+        throw new Exception ("overload(Klass t)");
+
+      if (overload_template.overload(k, k) != 20)
+        throw new Exception ("overload(Klass t, const Klass &)");
+
+      if (overload_template.overload(k, "hello") != 30)
+        throw new Exception ("overload(Klass t, const char *)");
+
+      if (overload_template.overload(10.0, "hi") != 40)
+        throw new Exception ("overload(double t, const char *)");
+
+      if (overload_template.overload() != 50)
+        throw new Exception ("overload(const char *)");
+
+
+      // everything put in a namespace
+      if (overload_template.nsoverload("hi") != 1000)
+        throw new Exception ("nsoverload()");
+
+      if (overload_template.nsoverload(1) != 1010)
+        throw new Exception ("nsoverload(int t)");
+
+      if (overload_template.nsoverload(1, 1) != 1020)
+        throw new Exception ("nsoverload(int t, const int &)");
+
+      if (overload_template.nsoverload(1, "hello") != 1030)
+        throw new Exception ("nsoverload(int t, const char *)");
+
+      if (overload_template.nsoverload(k) != 1010)
+        throw new Exception ("nsoverload(Klass t)");
+
+      if (overload_template.nsoverload(k, k) != 1020)
+        throw new Exception ("nsoverload(Klass t, const Klass &)");
+
+      if (overload_template.nsoverload(k, "hello") != 1030)
+        throw new Exception ("nsoverload(Klass t, const char *)");
+
+      if (overload_template.nsoverload(10.0, "hi") != 1040)
+        throw new Exception ("nsoverload(double t, const char *)");
+
+      if (overload_template.nsoverload() != 1050)
+        throw new Exception ("nsoverload(const char *)");
+
+    }
+}
+
diff --git a/trunk/Examples/test-suite/csharp/pointer_reference_runme.cs b/trunk/Examples/test-suite/csharp/pointer_reference_runme.cs
new file mode 100644
index 0000000..d005551
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/pointer_reference_runme.cs
@@ -0,0 +1,18 @@
+// This test tests all the methods in the C# collection wrapper
+
+using System;
+using pointer_referenceNamespace;
+
+public class pointer_reference_runme {
+
+  public static void Main() {
+    Struct s  = pointer_reference.get();
+    if (s.value != 10) throw new Exception("get test failed");
+
+    Struct ss = new Struct(20);
+    pointer_reference.set(ss);
+    if (Struct.instance.value != 20) throw new Exception("set test failed");
+  }
+
+}
+
diff --git a/trunk/Examples/test-suite/csharp/sizet_runme.cs b/trunk/Examples/test-suite/csharp/sizet_runme.cs
new file mode 100644
index 0000000..4852441
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/sizet_runme.cs
@@ -0,0 +1,18 @@
+
+using System;
+using sizetNamespace;
+
+public class sizet_runme {
+
+  public static void Main() {
+    uint s = 2000;
+    s = sizet.test1(s+1);
+    s = sizet.test2(s+1);
+    s = sizet.test3(s+1);
+    s = sizet.test4(s+1);
+    if (s != 2004)
+      throw new Exception("failed");
+  }
+
+}
+
diff --git a/trunk/Examples/test-suite/csharp/sneaky1_runme.cs b/trunk/Examples/test-suite/csharp/sneaky1_runme.cs
new file mode 100644
index 0000000..07e2570
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/sneaky1_runme.cs
@@ -0,0 +1,20 @@
+using System;
+using sneaky1Namespace;
+
+public class runme
+{
+    static void Main() 
+    {
+        if (sneaky1.add(30, 2) != 32)
+            throw new Exception("add test failed");
+
+        if (sneaky1.subtract(20, 2) != 18)
+            throw new Exception("subtract test failed");
+
+        if (sneaky1.mul(20, 2) != 40)
+            throw new Exception("mul test failed");
+
+        if (sneaky1.divide(20, 2) != 10)
+            throw new Exception("div test failed");
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/threads_runme.cs b/trunk/Examples/test-suite/csharp/threads_runme.cs
new file mode 100644
index 0000000..fa90199
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/threads_runme.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Threading;
+using threadsNamespace;
+
+public class runme
+{
+    static void Main() 
+    {
+      Kerfuffle kerf = new Kerfuffle();
+      const int NUM_THREADS = 8;
+      Thread[] threads = new Thread[NUM_THREADS];
+      TestThread[] testThreads = new TestThread[NUM_THREADS];
+      // invoke the threads
+      for (int i=0; i<NUM_THREADS; i++) {
+        testThreads[i] = new TestThread(kerf, i);
+        threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
+        threads[i].Start();
+      }
+      // wait for the threads to finish
+      for (int i=0; i<NUM_THREADS; i++) {
+        threads[i].Join();
+      }
+      for (int i=0; i<NUM_THREADS; i++) {
+        if (testThreads[i].Failed) throw new Exception("Test Failed");
+      }
+    }
+}
+
+public class TestThread {
+   private int threadId;
+   private Kerfuffle kerf;
+   public bool Failed;
+   public TestThread(Kerfuffle t, int id) {
+       kerf = t;
+       threadId = id;
+   }
+   public void Run() {
+     Failed = false;
+     try {
+       for (int i=0; i<30000; i++) { // run test for a few seconds on a 1GHz machine
+         string given = "This is the test string that should come back. A number: " + i;
+         string received = kerf.StdString(given);
+         if (received != given) {
+           throw new ApplicationException("StdString string does not match. Received:\n[" + received + "].\nExpected:\n{" + given + "}");
+         }
+       }
+       for (int i=0; i<30000; i++) { // run test for a few seconds on a 1GHz machine
+         string given = "This is the test string that should come back. A number: " + i;
+         string received = kerf.CharString(given);
+         if (received != given) {
+           throw new ApplicationException("StdString string does not match. Received:\n[" + received + "].\nExpected:\n{" + given + "}");
+         }
+       }
+     } catch (Exception e) {
+       Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message);
+       Failed = true;
+     }
+   }
+}
+
+
diff --git a/trunk/Examples/test-suite/csharp/throw_exception_runme.cs b/trunk/Examples/test-suite/csharp/throw_exception_runme.cs
new file mode 100644
index 0000000..e2e5200
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/throw_exception_runme.cs
@@ -0,0 +1,24 @@
+using System;
+using throw_exceptionNamespace;
+
+public class runme
+{
+    static void Main() {
+        Foo f = new Foo();
+        try {
+            f.test_int();
+            throw new Exception("Integer exception should have been thrown");
+        } catch (System.Exception) {
+        }
+        try {
+            f.test_msg();
+            throw new Exception("String exception should have been thrown");
+        } catch (System.Exception) {
+        }
+        try {
+            f.test_cls();
+            throw new Exception("Class exception should have been thrown");
+        } catch (System.Exception) {
+        }
+    }
+}
diff --git a/trunk/Examples/test-suite/csharp/typemap_namespace_runme.cs b/trunk/Examples/test-suite/csharp/typemap_namespace_runme.cs
new file mode 100644
index 0000000..39f1c65
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/typemap_namespace_runme.cs
@@ -0,0 +1,16 @@
+// This test tests all the methods in the C# collection wrapper
+
+using System;
+using typemap_namespaceNamespace;
+
+public class typemap_namespace_runme {
+
+  public static void Main() {
+    if (typemap_namespace.test1("hello") != "hello")
+      throw new Exception("test1 failed");
+    if (typemap_namespace.test2("hello") != "hello")
+      throw new Exception("test2 failed");
+  }
+
+}
+
diff --git a/trunk/Examples/test-suite/csharp/varargs_runme.cs b/trunk/Examples/test-suite/csharp/varargs_runme.cs
new file mode 100644
index 0000000..b9fca32
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/varargs_runme.cs
@@ -0,0 +1,20 @@
+// varargs test
+
+using System;
+using varargsNamespace;
+
+public class varargs_runme {
+
+  public static void Main() {
+
+    if (varargs.test("Hello") != "Hello")
+      throw new Exception("Failed");
+
+    Foo f = new Foo("Greetings");
+    if (f.str != "Greetings")
+      throw new Exception("Failed");
+        
+    if (f.test("Hello") != "Hello")
+      throw new Exception("Failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/csharp/virtual_poly_runme.cs b/trunk/Examples/test-suite/csharp/virtual_poly_runme.cs
new file mode 100644
index 0000000..9c1f796
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp/virtual_poly_runme.cs
@@ -0,0 +1,51 @@
+using System;
+using virtual_polyNamespace;
+
+public class runme {
+    static void Main() {
+
+        NDouble d = new NDouble(3.5);
+        NInt i = new NInt(2);
+
+        //
+        // These two natural 'copy' forms fail because no covariant (polymorphic) return types 
+        // are supported in C#. 
+        //
+        // NDouble dc = d.copy();
+        // NInt ic = i.copy();
+
+        //
+        // Unlike C++, we have to downcast instead.
+        //
+        NDouble dc = (NDouble)d.copy();
+        NInt ic = (NInt)i.copy();
+
+        NDouble ddc = NDouble.narrow(dc);
+        NInt dic = NInt.narrow(ic);
+        dc = ddc; ic = dic; // warning suppression
+
+        virtual_poly.incr(ic);
+        if ( (i.get() + 1) != ic.get() )
+            throw new Exception("incr test failed");
+
+        //
+        // Checking a pure user downcast
+        //
+        NNumber n1 = d.copy();
+        NNumber n2 = d.nnumber();
+        NDouble dn1 = NDouble.narrow(n1);
+        NDouble dn2 = NDouble.narrow(n2);
+
+        if ( (dn1.get()) != dn2.get() )
+          throw new Exception("copy/narrow test failed");
+
+        //
+        // Checking the ref polymorphic case
+        //
+        NNumber nr = d.ref_this();
+        NDouble dr1 = NDouble.narrow(nr);
+        NDouble dr2 = (NDouble)d.ref_this();
+        if ( dr1.get() != dr2.get() )
+          throw new Exception("copy/narrow test failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/csharp_attributes.i b/trunk/Examples/test-suite/csharp_attributes.i
new file mode 100644
index 0000000..101e897
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp_attributes.i
@@ -0,0 +1,48 @@
+%module csharp_attributes
+
+// Test the inattributes and outattributes typemaps
+%typemap(cstype, outattributes="[IntOut]", inattributes="[IntIn]") int "int"
+%typemap(imtype, outattributes="[IntegerOut]", inattributes="[IntegerIn]") int "int"
+
+%inline %{
+class Stations {
+public:
+  Stations(int myInt) { }
+  int Reading(int myInt) { return myInt; }
+  static int Swindon(int myInt) { return myInt; }
+};
+#define TESTMACRO 10
+int GlobalFunction(int myInt) { return myInt; }
+%}
+
+
+// Test the attributes feature
+%csattributes MoreStations::MoreStations()      "[InterCity1]"
+%csattributes MoreStations::Chippenham()        "[InterCity2]"
+%csattributes MoreStations::Bath()              "[InterCity3]"
+%csattributes Bristol                           "[InterCity4]"
+%csattributes WestonSuperMare                   "[InterCity5]"
+%csattributes Wales                             "[InterCity6]"
+%csattributes Paddington()                      "[InterCity7]"
+%csattributes DidcotParkway                     "[InterCity8]"
+
+%typemap(csattributes) MoreStations "[Eurostar1]"
+%typemap(csattributes) MoreStations::Wales "[Eurostar2]"
+%typemap(csattributes) Cymru "[Eurostar3]"
+
+%inline %{
+struct MoreStations {
+  MoreStations() : Bristol(0) {}
+  void Chippenham() {}
+  static void Bath() {}
+  int Bristol;
+  static double WestonSuperMare;
+  enum Wales { Cardiff = 1, Swansea };
+};
+void Paddington() {}
+float DidcotParkway;
+enum Cymru { Llanelli };
+
+double MoreStations::WestonSuperMare = 0.0;
+%}
+
diff --git a/trunk/Examples/test-suite/csharp_exceptions.i b/trunk/Examples/test-suite/csharp_exceptions.i
new file mode 100644
index 0000000..0f11e7d
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp_exceptions.i
@@ -0,0 +1,241 @@
+%module csharp_exceptions
+
+%include <exception.i>
+
+%inline %{
+  class Ex {
+    const char *message;
+  public:
+    Ex(const char *msg) : message(msg) {}
+    const char *what() { return message; }
+  };
+%}
+
+%exception ThrowByValue() {
+  try {
+    $action
+  } catch(Ex e) {
+    SWIG_exception(SWIG_DivisionByZero, e.what());
+  }
+}
+
+%exception ThrowByReference() {
+  try {
+    $action
+  } catch(Ex &e) {
+    SWIG_exception(SWIG_DivisionByZero, e.what());
+  }
+}
+
+%csnothrowexception NoThrowException() {
+  try {
+    $action
+  } catch(Ex) {
+    // swallowed
+  }
+}
+
+%inline %{
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+// %exception tests
+void ThrowByValue()                                     { throw Ex("ThrowByValue"); }
+void ThrowByReference()                                 { throw Ex("ThrowByReference"); }
+// %csnothrowexception
+void NoThrowException()                                 { throw Ex("NoThrowException"); }
+// exception specifications
+void ExceptionSpecificationValue() throw(Ex)            { throw Ex("ExceptionSpecificationValue"); }
+void ExceptionSpecificationReference() throw(Ex&)       { throw Ex("ExceptionSpecificationReference"); }
+void ExceptionSpecificationString() throw(const char *) { throw "ExceptionSpecificationString"; }
+void ExceptionSpecificationInteger() throw(int)         { throw 20; }
+%}
+
+// test exceptions in the default typemaps
+
+// null reference exceptions
+%inline %{
+void NullReference(Ex& e) {}
+void NullValue(Ex e) {}
+%}
+
+// enums
+%inline %{
+enum TestEnum {TestEnumItem};
+void ExceptionSpecificationEnumValue() throw(TestEnum) { throw TestEnumItem; }
+void ExceptionSpecificationEnumReference() throw(TestEnum&) { throw TestEnumItem; }
+%}
+
+// std::string
+%include <std_string.i>
+%inline %{
+void ExceptionSpecificationStdStringValue() throw(std::string) { throw std::string("ExceptionSpecificationStdStringValue"); }
+void ExceptionSpecificationStdStringReference() throw(const std::string&) { throw std::string("ExceptionSpecificationStdStringReference"); }
+void NullStdStringValue(std::string s) {}
+void NullStdStringReference(std::string &s) {}
+%}
+
+// Memory leak check (The C++ exception stack was never unwound in the original approach to throwing exceptions from unmanaged code)
+%exception MemoryLeakCheck() {
+  Counter destructor_should_be_called;
+  try {
+    $action
+  } catch(Ex e) {
+    SWIG_exception(SWIG_DivisionByZero, e.what());
+  }
+}
+
+%inline %{
+struct Counter {
+  static int count;
+  Counter() { count++; }
+  ~Counter() { count--; }
+};
+int Counter::count = 0;
+
+void MemoryLeakCheck() {
+  throw Ex("testing memory leaks when throwing exceptions");
+}
+%}
+
+// test exception pending in the csconstruct typemap
+%inline %{
+struct constructor {
+  constructor(std::string s) {}
+  constructor() throw(int) { throw 10; }
+};
+
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+// test exception pending in the csout typemaps
+%typemap(out, canthrow=1) unsigned short ushorttest %{
+  $result = $1;
+  if ($result == 100) {
+    SWIG_CSharpSetPendingException(SWIG_CSharpIndexOutOfRangeException, "don't like 100");
+    return $null;
+  }
+%}
+%inline %{
+unsigned short ushorttest() { return 100; }
+%}
+
+// test exception pending in the csvarout/csvarin typemaps and canthrow attribute in unmanaged code typemaps
+%typemap(check, canthrow=1) int numberin, int InOutStruct::staticnumberin %{
+  if ($1 < 0) {
+    SWIG_CSharpSetPendingException(SWIG_CSharpIndexOutOfRangeException, "too small");
+    return $null;
+  }
+%}
+%typemap(out, canthrow=1) int numberout, int InOutStruct::staticnumberout %{
+  $result = $1;
+  if ($result > 10) {
+    SWIG_CSharpSetPendingException(SWIG_CSharpIndexOutOfRangeException, "too big");
+    return $null;
+  }
+%}
+%inline %{
+  int numberin;
+  int numberout;
+  struct InOutStruct {
+    int numberin;
+    int numberout;
+    static int staticnumberin;
+    static int staticnumberout;
+  };
+  int InOutStruct::staticnumberin;
+  int InOutStruct::staticnumberout;
+%}
+
+// test SWIG_exception macro - it must return from unmanaged code without executing any further unmanaged code
+%typemap(check, canthrow=1) int macrotest {
+  if ($1 < 0) {
+    SWIG_exception(SWIG_IndexError, "testing SWIG_exception macro");
+  }
+}
+%inline %{
+  bool exception_macro_run_flag = false;
+  void exceptionmacrotest(int macrotest) {
+    exception_macro_run_flag = true;
+  }
+%}
+
+// test all the types of exceptions
+%typemap(check, canthrow=1) UnmanagedExceptions {
+  switch($1) {
+    case UnmanagedApplicationException:          SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException,        "msg"); return $null; break;
+    case UnmanagedArithmeticException:           SWIG_CSharpSetPendingException(SWIG_CSharpArithmeticException,         "msg"); return $null; break;
+    case UnmanagedDivideByZeroException:         SWIG_CSharpSetPendingException(SWIG_CSharpDivideByZeroException,       "msg"); return $null; break;
+    case UnmanagedIndexOutOfRangeException:      SWIG_CSharpSetPendingException(SWIG_CSharpIndexOutOfRangeException,    "msg"); return $null; break;
+    case UnmanagedInvalidCastException:          SWIG_CSharpSetPendingException(SWIG_CSharpInvalidCastException,        "msg"); return $null; break;
+    case UnmanagedInvalidOperationException:     SWIG_CSharpSetPendingException(SWIG_CSharpInvalidOperationException,   "msg"); return $null; break;
+    case UnmanagedIOException:                   SWIG_CSharpSetPendingException(SWIG_CSharpIOException,                 "msg"); return $null; break;
+    case UnmanagedNullReferenceException:        SWIG_CSharpSetPendingException(SWIG_CSharpNullReferenceException,      "msg"); return $null; break;
+    case UnmanagedOutOfMemoryException:          SWIG_CSharpSetPendingException(SWIG_CSharpOutOfMemoryException,        "msg"); return $null; break;
+    case UnmanagedOverflowException:             SWIG_CSharpSetPendingException(SWIG_CSharpOverflowException,           "msg"); return $null; break;
+    case UnmanagedSystemException:               SWIG_CSharpSetPendingException(SWIG_CSharpSystemException,             "msg"); return $null; break;
+    case UnmanagedArgumentException:             SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException,           "msg", "parm"); return $null; break;
+    case UnmanagedArgumentNullException:         SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException,       "msg", "parm"); return $null; break;
+    case UnmanagedArgumentOutOfRangeException:   SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, "msg", "parm"); return $null; break;
+  }
+}
+%inline %{
+enum UnmanagedExceptions {
+  UnmanagedApplicationException,
+  UnmanagedArithmeticException,
+  UnmanagedDivideByZeroException,
+  UnmanagedIndexOutOfRangeException,
+  UnmanagedInvalidCastException,
+  UnmanagedInvalidOperationException,
+  UnmanagedIOException,
+  UnmanagedNullReferenceException,
+  UnmanagedOutOfMemoryException,
+  UnmanagedOverflowException,
+  UnmanagedSystemException,
+  UnmanagedArgumentException,
+  UnmanagedArgumentNullException,
+  UnmanagedArgumentOutOfRangeException,
+};
+
+void check_exception(UnmanagedExceptions e) {
+}
+%}
+
+// exceptions in multiple threads test
+%exception ThrowsClass::ThrowException(long long input) {
+  try {
+    $action
+  } catch (long long d) {
+    char message[64];
+    sprintf(message, "caught:%lld", d);
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, message, "input");
+  }
+}
+%inline %{
+struct ThrowsClass {
+  double dub;
+  ThrowsClass(double d) : dub(d) {}
+  long long ThrowException(long long input) {
+    throw input;
+    return input;
+  }
+};
+%}
+
+// test inner exceptions
+%exception InnerExceptionTest() {
+  try {
+    $action
+  } catch(Ex &e) {
+    SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
+    SWIG_CSharpSetPendingException(SWIG_CSharpInvalidOperationException, "My OuterException message");
+  }
+}
+
+%inline %{
+void InnerExceptionTest() { throw Ex("My InnerException message"); }
+%}
diff --git a/trunk/Examples/test-suite/csharp_features.i b/trunk/Examples/test-suite/csharp_features.i
new file mode 100644
index 0000000..578a56a
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp_features.i
@@ -0,0 +1,24 @@
+%module csharp_features
+
+// SWIG gets the method modifiers wrong occasionally, like with private inheritance, %csmethodmodifiers can fix this
+%csmethodmodifiers Derived::VirtualMethod() "public virtual"
+%csmethodmodifiers MoreDerived::variable "public new"
+
+%inline %{
+class Base {
+public:
+  virtual ~Base() {}
+  virtual void VirtualMethod() {}
+};
+class Derived : private Base {
+public:
+  virtual ~Derived() {}
+  virtual void VirtualMethod() {}
+  int variable;
+};
+class MoreDerived : public Derived {
+public:
+  int variable;
+};
+%}
+
diff --git a/trunk/Examples/test-suite/csharp_prepost.i b/trunk/Examples/test-suite/csharp_prepost.i
new file mode 100644
index 0000000..9c2cedc
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp_prepost.i
@@ -0,0 +1,90 @@
+%module csharp_prepost
+
+// Test the pre, post and cshin attributes for csin typemaps
+
+%include "std_vector.i"
+
+%define VECTOR_DOUBLE_CSIN_POST
+"      int count$csinput = d$csinput.Count;
+      $csinput = new double[count$csinput];
+      for (int i=0; i<count$csinput; ++i) {
+        $csinput[i] = d$csinput[i];
+      }"
+%enddef
+
+// pre and post in csin typemaps
+%typemap(cstype) std::vector<double> &v "out double[]"
+%typemap(csin, pre="    DoubleVector d$csinput = new DoubleVector();", post=VECTOR_DOUBLE_CSIN_POST, cshin="out $csinput") std::vector<double> &v
+  "$csclassname.getCPtr(d$csinput)"
+
+%apply std::vector<double> & v { std::vector<double> & v2 }
+
+// pre only in csin typemap
+%typemap(cstype) std::vector<double> &vpre "ref double[]"
+%typemap(csin, pre="    DoubleVector d$csinput = new DoubleVector();\n    foreach (double d in $csinput) {\n      d$csinput.Add(d);\n    }", cshin="ref $csinput") std::vector<double> &vpre
+  "$csclassname.getCPtr(d$csinput)"
+
+// post only in csin typemap
+%typemap(csin, post="      int size = $csinput.Count;\n      for (int i=0; i<size; ++i) {\n        $csinput[i] /= 100;\n      }") std::vector<double> &vpost
+  "$csclassname.getCPtr($csinput)"
+
+%inline %{
+bool globalfunction(std::vector<double> & v) {
+  v.push_back(0.0);
+  v.push_back(1.1);
+  v.push_back(2.2);
+  return true;
+}
+struct PrePostTest {
+  PrePostTest() {
+  }
+  PrePostTest(std::vector<double> & v) {
+    v.push_back(3.3);
+    v.push_back(4.4);
+  }
+  bool method(std::vector<double> & v) {
+    v.push_back(5.5);
+    v.push_back(6.6);
+    return true;
+  }
+  static bool staticmethod(std::vector<double> & v) {
+    v.push_back(7.7);
+    v.push_back(8.8);
+    return true;
+  }
+};
+
+// Check pre and post only typemaps and that they coexist okay and that the generated code line spacing looks okay
+bool globalfunction2(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+  return true;
+}
+struct PrePost2 {
+  PrePost2() {
+  }
+  PrePost2(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+  }
+  bool method(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+    return true;
+  }
+  static bool staticmethod(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+    return true;
+  }
+};
+%}
+
+%template(DoubleVector) std::vector<double>;
+
+// Check attributes in the typemaps
+%typemap(cstype, inattributes="[CustomInt]") int val "int"
+%typemap(csin, pre="    int tmp_$csinput = $csinput * 100;") int "tmp_$csinput"
+%typemap(imtype, out="IntPtr/*overridden*/", outattributes="[CustomIntPtr]") CsinAttributes * "HandleRef/*overridden*/"
+
+%inline %{
+class CsinAttributes {
+  int m_val;
+public:
+  CsinAttributes(int val) : m_val(val) {}
+  int getVal() { return m_val; }
+};
+%}
+
diff --git a/trunk/Examples/test-suite/csharp_typemaps.i b/trunk/Examples/test-suite/csharp_typemaps.i
new file mode 100644
index 0000000..dcef278
--- /dev/null
+++ b/trunk/Examples/test-suite/csharp_typemaps.i
@@ -0,0 +1,103 @@
+%module csharp_typemaps
+
+// Test the C# types customisation by modifying the default char * typemaps to return a single char
+
+%typemap(ctype, out="char /*ctype out override*/") char * "char *"
+%typemap(imtype, out="char /*imtype out override*/") char * "string"
+%typemap(cstype, out="char /*cstype out override*/") char * "string"
+
+%typemap(out) char * %{
+  // return the 0th element rather than the whole string
+  $result = SWIG_csharp_string_callback($1)[0];
+%}
+
+%typemap(csout, excode=SWIGEXCODE) char * {
+    char ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) char * %{
+    get {
+      char ret = $imcall;$excode
+      return ret;
+    } %}
+
+%inline %{
+namespace Space {
+    class Things {
+    public:
+        char* start(char *val) { return val; }
+        static char* stop(char *val) { return val; }
+    };
+    char* partyon(char *val) { return val; }
+}
+%}
+
+
+// Test variables when ref is used in the cstype typemap - the variable name should come from the out attribute if specified
+%typemap(cstype) MKVector, const MKVector& "MKVector"
+%typemap(cstype, out="MKVector") MKVector &, MKVector * "ref MKVector"
+
+%inline %{
+struct MKVector {
+};
+struct MKRenderGameVector {
+  MKVector memberValue;
+  static MKVector staticValue;
+};
+MKVector MKRenderGameVector::staticValue;
+MKVector globalValue;
+%}
+
+
+// Number and Obj are for the eager garbage collector runtime test
+%inline %{
+struct Number {
+  Number(double value) : Value(value) {}
+  double Value;
+};
+
+class Obj {
+public:
+  Number triple(Number n) {
+    n.Value *= 3;
+    return n;
+  }
+  Number times6(const Number& num) {
+    Number n(num);
+    n.Value *= 6;
+    return n;
+  }
+  Number times9(const Number* num) {
+    Number n(*num);
+    n.Value *= 9;
+    return n;
+  }
+};
+Number quadruple(Number n) {
+    n.Value *= 4;
+    return n;
+};
+Number times8(const Number& num) {
+    Number n(num);
+    n.Value *= 8;
+    return n;
+};
+Number times12(const Number* num) {
+    Number n(*num);
+    n.Value *= 12;
+    return n;
+};
+%}
+
+// Test $csinput expansion
+%typemap(csvarin, excode=SWIGEXCODE2) int %{
+    set {
+      if ($csinput < 0)
+        throw new ApplicationException("number too small!");
+      $imcall;$excode
+    } %}
+
+%inline %{
+int myInt = 0;
+%}
diff --git a/trunk/Examples/test-suite/default_args.i b/trunk/Examples/test-suite/default_args.i
new file mode 100644
index 0000000..69c90e2
--- /dev/null
+++ b/trunk/Examples/test-suite/default_args.i
@@ -0,0 +1,241 @@
+// Lots of tests for methods with default parameters / default arguments
+
+%module default_args
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%include <std_string.i>
+
+%inline %{
+  #include <string>
+
+  // Anonymous arguments
+  int anonymous(int = 7771);
+  int anonymous(int x) { return x; }
+
+  // Bug [548272] Default arguments
+  bool booltest(bool x = true) { return x; }
+
+  // scoped enums
+  enum flavor { BITTER, SWEET };
+  class EnumClass {
+    public:
+      enum speed { FAST, SLOW };
+      // Note: default values should be EnumClass::FAST and SWEET 
+      bool blah(speed s = FAST, flavor f = SWEET) { return (s == FAST && f == SWEET); };
+  };
+
+  // casts
+  const char * casts1(const char *m = (const char *) NULL) {
+    char *ret = NULL; 
+    if (m) { 
+      ret = new char[strlen(m)+1];
+      strcpy(ret, m);
+    }
+    return ret;
+  }
+  const char * casts2(const char *m = (const char *) "Hello") {
+    char *ret = NULL; 
+    if (m) { 
+      ret = new char[strlen(m)+1];
+      strcpy(ret, m);
+    }
+    return ret;
+  }
+
+  // char
+  char chartest1(char c = 'x') { return c; }
+  char chartest2(char c = '\0') { return c; }
+
+  // namespaces
+  namespace AType { 
+    enum AType { NoType }; 
+  } 
+  void dummy(AType::AType aType = AType::NoType) {}
+  namespace A { 
+    namespace B { 
+      int CONST_NUM = 10; 
+    } 
+    int afunction(int i = B::CONST_NUM) { return i; }
+  } 
+
+  // references
+  int reftest1(const int &x = 42) { return x; }
+  std::string reftest2(const std::string &x = "hello") { return x; }
+
+  // enum scope
+  class Tree {
+    public:
+      enum types {Oak, Fir, Cedar};
+      void chops(enum types type) {}
+      void test(int x = Oak + Fir + Cedar) {}
+  };
+  enum Tree::types chops(enum Tree::types type) { return type; }
+ 
+%}
+
+// Rename a class member
+%rename(bar2) Foo::bar;
+%rename(newname) Foo::oldname(int x = 1234);
+%ignore Foo::Foo(int x, int y = 0, int z = 0);
+%ignore Foo::meth(int x, int y = 0, int z = 0);
+%rename(renamed3arg) Foo::renameme(int x, double d) const;
+%rename(renamed2arg) Foo::renameme(int x) const;
+%rename(renamed1arg) Foo::renameme() const;
+
+%inline %{
+
+  // Define a class
+  class Foo {
+    public:
+      static int bar;
+      static int spam;
+
+      Foo(){}
+     
+      Foo(int x, int y = 0, int z = 0){}
+
+      void meth(int x, int y = 0, int z = 0){}
+    
+      // Use a renamed member as a default argument.  SWIG has to resolve
+      // bar to Foo::bar and not Foo::spam.  SWIG-1.3.11 got this wrong.
+      // (Different default parameter wrapping in SWIG-1.3.23 ensures SWIG doesn't have to resolve these symbols).
+      void method1(int x = bar) {}
+
+      // Use unrenamed member as default
+      void method2(int x = spam) {}
+
+      // test the method itself being renamed
+      void oldname(int x = 1234) {}
+      void renameme(int x = 1234, double d=123.4) const {}
+  };
+  int Foo::bar = 1;
+  int Foo::spam = 2;
+%}
+
+
+// tests valuewrapper
+%inline %{
+  enum MyType { Val1, Val2 }; 
+
+  class MyClass1 
+  { 
+    public: 
+      MyClass1(MyType myType) {}
+  }; 
+
+  class MyClass2 
+  { 
+    public : 
+      void set(MyClass1 cl1 = Val1) {}
+      // This could have been written : set(MyClass1 cl1 = MyClass1(Val1)) 
+      // But it works in C++ since there is a "conversion" constructor in  MyClass1. 
+  };
+%}
+
+
+// Default parameters with exception specifications
+%inline %{
+void exceptionspec(int a = -1) throw (int, const char*) {
+  if (a == -1)
+    throw "ciao";
+  else
+    throw a;
+}
+struct Except {
+  Except(bool throwException, int a = -1) throw (int) {
+    if (throwException)
+      throw a;
+  }
+  void exspec(int a = 0) throw (int, const char*) {
+    ::exceptionspec(a);
+  }
+};
+%}
+
+// Default parameters in static class methods
+#ifdef SWIGPYTHON
+%rename(staticMethod) staticmethod;
+#endif
+
+%inline %{
+namespace SpaceName {
+  struct Statics {
+    static int staticmethod(int a=10, int b=20, int c=30) { return a+b+c; }
+  };
+}
+%}
+
+
+// Tests which could never be wrapped prior to changes in default argument wrapping implemented in SWIG-1.3.23:
+%inline %{
+class Tricky {
+  static int getDefault() { return 500; }
+  enum { privatevalue = 200 };
+  static const char charvalue;
+public:
+  int privatedefault(int val = privatevalue) { return val; }
+  int protectedint(int val = intvalue) { return val; }
+  double protecteddouble(double val = doublevalue) { return val; }
+  int functiondefault(int val = Tricky::getDefault()) { return val; }
+  char contrived(const char *c = &charvalue) { return *c; }
+protected:
+  static const int intvalue = 2000;
+  static const double doublevalue;
+};
+const char Tricky::charvalue = 'X';
+const double Tricky::doublevalue = 987.654;
+
+
+// tests default argument which is a constructor call within namespace
+// also tests default constructor (from defaulted parameter)
+namespace Space {
+struct Klass {
+  int val;
+  Klass(int val = -1) : val(val) {}
+};
+Klass constructorcall(const Klass& k = Klass()) { return k; }
+
+}
+%}
+
+%{
+struct ConstMethods {
+  int coo(double d = 0.0) { return 10; }
+  int coo(double d = 0.0) const { return 20; }
+};
+%}
+
+// const methods 
+// runtime test needed to check that the const method is called
+struct ConstMethods {
+  int coo(double d = 0.0) const;
+};
+
+
+
+// Default args with C linkage
+%inline
+%{
+  extern "C" double cfunc1(double x,double p = 1) {
+    return(x+p);
+  }
+
+  extern "C" {
+    double cfunc2(double x,double p = 2) {
+      return(x+p);
+    }
+
+    double cfunc3(double x,double p = 3) {
+      return(x+p);
+    }
+
+    typedef struct Pointf { 
+      double		x,y; 
+    } Pointf;
+  }
+%}
diff --git a/trunk/Examples/test-suite/default_constructor.i b/trunk/Examples/test-suite/default_constructor.i
new file mode 100644
index 0000000..71600e5
--- /dev/null
+++ b/trunk/Examples/test-suite/default_constructor.i
@@ -0,0 +1,170 @@
+// This module tests default constructor generation under a
+// number of different conditions
+
+%module(ruby_minherit="1") default_constructor
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) EB; /* C#, Java, Php4 multiple inheritance */
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) AD; /* C#, Java, Php4 multiple inheritance */
+
+%warnfilter(SWIGWARN_LANG_FRIEND_IGNORE) F; /* friend function */
+
+%delobject F::destroy;
+%delobject G::destroy;
+
+%inline %{
+
+/* A class with a public default constructor */
+class A {
+public:
+   A() { };
+};
+
+/* This class should get default constructor/destructors */
+class AA : public A {
+};
+
+/* A class with a public constructor, but not default */
+
+class B {
+private:
+   B() { }
+public:
+   B(int x, int y) { }
+};
+
+/* This class should get no default constructor, but a destructor */
+class BB : public B {
+};
+
+/* A class with a protected constructor */
+class C {
+protected:
+    C() { };
+public:
+};
+
+/* This class does get a default constructor/destructor */
+class CC : public C {
+};
+
+
+/* A class with a private constructor */
+class D {
+private:
+   D() { };
+public:
+   void foo() { };
+};
+
+/* This class does not get a default constructor */
+class DD: public D {
+	
+};
+
+/* No default constructor.  A is okay, but D is not */
+class AD: public A, public D {
+
+};
+
+/* This class has a default constructor because of optional arguments */
+class E {
+public:
+   E(int x = 0, int y = 0) { }
+};
+
+/* This should get a default constructor */
+class EE : public E {
+};
+
+/* This class should not get a default constructor. B doesn't have one */
+
+class EB : public E, public B {
+
+};
+
+/* A class with a private destructor */
+
+class F {
+private:
+   ~F() { }
+public:
+   void foo(int, int) { }
+   friend void bar(F *);
+   void destroy() { delete this; }
+    
+};
+
+void bar(F *) { }
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4624) // : destructor could not be generated because a base class destructor is inaccessible
+#endif
+class FFF : public F { 
+};
+#if defined(_MSC_VER)
+  #pragma warning(default: 4624) // : destructor could not be generated because a base class destructor is inaccessible
+#endif
+
+/* A class with a protected destructor */
+class G {
+protected:
+   ~G() { }
+
+public:
+  static void destroy(G *g) { delete g; }
+};
+
+class GG : public G { 
+};
+
+template <class T>
+class HH_T 
+{
+
+
+public:
+
+  HH_T(int i,int j)
+  {
+  }
+  
+
+protected:
+  HH_T();
+  
+};
+ 
+ 
+%}
+ 
+
+%template(HH) HH_T<int>;
+
+
+%{
+  class OSRSpatialReferenceShadow {
+  private:
+    OSRSpatialReferenceShadow();
+  public:
+  };
+%}
+
+typedef void OSRSpatialReferenceShadow; 
+
+class OSRSpatialReferenceShadow {
+private:
+public:
+  %extend {
+    OSRSpatialReferenceShadow( char const * wkt = "" ) {
+      return 0;
+    }
+  } 
+};
+
+
+  
diff --git a/trunk/Examples/test-suite/defvalue_constructor.i b/trunk/Examples/test-suite/defvalue_constructor.i
new file mode 100644
index 0000000..e4aabaf
--- /dev/null
+++ b/trunk/Examples/test-suite/defvalue_constructor.i
@@ -0,0 +1,14 @@
+%module defvalue_constructor
+%inline %{
+
+namespace Foo { 
+ 
+    class Bar {}; 
+ 
+    class Baz { 
+      public: 
+        Baz(Bar b = Bar()) {}
+    }; 
+} 
+
+%}
diff --git a/trunk/Examples/test-suite/derived_byvalue.i b/trunk/Examples/test-suite/derived_byvalue.i
new file mode 100644
index 0000000..a251a8f
--- /dev/null
+++ b/trunk/Examples/test-suite/derived_byvalue.i
@@ -0,0 +1,91 @@
+%module derived_byvalue
+
+%inline %{
+
+struct Foo {
+  int x;
+
+  // this works
+  int rmethod(const Foo& f) { return f.x; }
+
+  // this doesn't when DerFoo (below) is introduced
+  int method(Foo f) { return f.x; }
+};
+
+struct Bar {
+   Foo   a;
+   struct Foo b;
+};
+
+/*
+  When the next derived class is declared, the 
+  following bad method is generated
+
+  static void *_DerFooTo_Foo(void *x) {   // **** bad ****
+    return (void *)((Foo)  ((DerFoo) x));
+  }
+
+  static void *_p_DerFooTo_p_Foo(void *x) {   // *** good ***
+    return (void *)((Foo *)  ((DerFoo *) x));
+  }
+  
+  if the derived class is deleted, it works again 
+
+  if the previous Foo::method is deleted, it works again
+
+ */
+struct DerFoo : Foo {
+};
+
+/*
+  The problem is caused by accidentally remembering a object value type
+  instead of an object pointer type.
+  During the course of SWIGing a file, several calls to SwigType_remember()
+  or SwigType_remember_clientdata() will be made.
+  When the SwigType_emit_type_table() function is called it emits all the
+  type conversion functions.
+  
+  If a object type exists in the SwigType table, you get this error.
+
+  You can view the SwigType table, with a #define DEBUG at the top of
+  Source/Swig/typesys.c
+
+  When run you get an output like this:
+
+---r_mangled---
+Hash {
+    '_p_Bar' : Hash {
+        'p.Bar' : _p_Bar, 
+    }
+, 
+    '_p_DerFoo' : Hash {
+        'p.DerFoo' : _p_DerFoo, 
+    }
+, 
+    '_p_Foo' : Hash {
+        'r.Foo' : _p_Foo, 
+        'p.Foo' : _p_Foo, 
+    }
+, 
+    '_Foo' : Hash {
+        'Foo' : _Foo, 
+    }
+, 
+}
+....
+
+  The last field ('_Foo') is an object type and caused the error.
+  It can be fixed either by checking all the calls to SwigType_remember()
+  and by checking the typemaps.
+  The typemap code also calls SwigType_remember(), if your typemaps
+  defined an object type, it will be added into the SwigType table.
+  its normally a 
+    SWIG_ConvertPtr(....$descriptor...)
+  when it should have been a $&descriptor or $*descriptor
+    
+  Commenting out all your object typemaps (and typecheck fns) may help
+  isolate it.
+
+*/
+#
+%}
diff --git a/trunk/Examples/test-suite/derived_nested.i b/trunk/Examples/test-suite/derived_nested.i
new file mode 100644
index 0000000..2e9ace3
--- /dev/null
+++ b/trunk/Examples/test-suite/derived_nested.i
@@ -0,0 +1,15 @@
+/* This testcase tests nested derived classes.
+This was reported in bug #909389 */
+
+%module derived_nested
+
+%inline %{
+
+class A { int x; };
+class B {
+  class C { int y; }; //generates a warning
+  class D : public A { int z; }; //ok
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/destructor_reprotected.i b/trunk/Examples/test-suite/destructor_reprotected.i
new file mode 100644
index 0000000..67328f3
--- /dev/null
+++ b/trunk/Examples/test-suite/destructor_reprotected.i
@@ -0,0 +1,41 @@
+%module destructor_reprotected
+
+
+%inline {
+
+  struct A
+  {
+    A()
+    {
+    }
+    
+    virtual ~A()
+    {
+    }
+    
+  };
+  
+  struct B : A
+  {
+  protected:
+    B()
+    {
+    }
+    
+    ~B()
+    {
+    }
+    
+  };
+
+  struct C : B
+  {
+    C()
+    {
+    }
+    
+    ~C()
+    {
+    }    
+  };
+}
diff --git a/trunk/Examples/test-suite/director_abstract.i b/trunk/Examples/test-suite/director_abstract.i
new file mode 100644
index 0000000..cc9dca5
--- /dev/null
+++ b/trunk/Examples/test-suite/director_abstract.i
@@ -0,0 +1,200 @@
+%module(directors="1") director_abstract
+%{
+#include <string>
+
+class Foo {
+public:
+	virtual ~Foo() {}
+	virtual std::string ping() = 0;
+	virtual std::string pong() { return "Foo::pong();" + ping(); }
+};
+
+%}
+
+%include <std_string.i>
+
+%feature("director") Foo;
+
+class Foo {
+public:
+  virtual ~Foo() {}
+  virtual std::string ping() = 0;
+  virtual std::string pong() { return "Foo::pong();" + ping(); }
+};
+
+
+
+%feature("director");
+
+%inline %{
+class Example0
+{
+protected:
+  int xsize, ysize;
+  
+public:
+  
+  Example0(int x, int y)
+    : xsize(x), ysize(y) { }
+
+  Example0() { }
+
+public:
+  virtual ~Example0() {}
+  
+  int  GetXSize() const { return xsize; }
+  
+  // pure virtual methods that must be overridden
+  virtual int Color(unsigned char r, unsigned char g, unsigned char b)  
+  {
+    return 0;
+  }
+  
+
+  static int get_color(Example0 *ptr, unsigned char r, 
+		       unsigned char g, unsigned char b) {
+    return ptr->Color(r, g, b);
+  }
+};
+
+class Example1
+{
+protected:
+  int xsize, ysize;
+  
+protected:
+  /* this shouldn't be emitted, unless 'dirprot' is used, since they
+   is already a public constructor */
+  
+  Example1(int x, int y)
+    : xsize(x), ysize(y) { }
+
+public:
+  Example1() { }
+
+public:
+  virtual ~Example1() {}
+  
+  int  GetXSize() const { return xsize; }
+  
+  // pure virtual methods that must be overridden
+  virtual int Color(unsigned char r, unsigned char g, unsigned char b)  = 0;
+
+  static int get_color(Example1 *ptr, unsigned char r, 
+		       unsigned char g, unsigned char b) {
+    return ptr->Color(r, g, b);
+  }
+  
+
+};
+
+
+class Example2
+{
+protected:
+ int xsize, ysize;
+
+protected:
+  /* there is no default constructor, hence, all protected constructors
+     should be emitted */
+
+  Example2(int x)
+  {
+  }
+
+  Example2(int x, int y)
+    : xsize(x), ysize(y) { }
+
+public:
+
+  virtual ~Example2() {}
+
+  int  GetXSize() const { return xsize; }
+
+  // pure virtual methods that must be overridden
+  virtual int Color(unsigned char r, unsigned char g, unsigned char b) = 0;
+
+  static int get_color(Example2 *ptr, unsigned char r, 
+		       unsigned char g, unsigned char b) {
+    return ptr->Color(r, g, b);
+  }
+};
+
+class Example4
+{
+protected:
+ int xsize, ysize;
+
+protected:
+
+  Example4()
+  {
+  }
+
+  /* this is not emitted, unless dirprot is used */
+  Example4(int x, int y)
+    : xsize(x), ysize(y) { }
+
+public:
+
+  virtual ~Example4() {}
+
+  int  GetXSize() const { return xsize; }
+
+  // pure virtual methods that must be overridden
+  virtual int Color(unsigned char r, unsigned char g, unsigned char b) = 0;
+
+  static int get_color(Example4 *ptr, unsigned char r, 
+		       unsigned char g, unsigned char b) {
+    return ptr->Color(r, g, b);
+  }
+};
+
+namespace ns 
+{
+  template <class T>
+  class Example3
+  {
+  protected:
+    /* the default constructor is always emitter, even when protected,
+        having another public constructor, and 'dirprot' is not used.
+        This is just for Java compatibility */
+    Example3()
+    {
+    }
+
+    /* this is no emitted, unless dirprot mode is used */
+    Example3(int x) { }
+
+  public:
+    
+    Example3(int x, int y) { }
+
+    virtual ~Example3() {}
+    
+    // pure virtual methods that must be overridden
+    virtual int Color(unsigned char r, unsigned char g, unsigned char b) = 0;    
+
+    static int get_color(Example3 *ptr, unsigned char r, 
+			 unsigned char g, unsigned char b) {
+      return ptr->Color(r, g, b);
+    }
+  };
+}    
+%}
+
+%template(Example3_i) ns::Example3<int>;
+
+
+%inline %{
+  struct A{
+    virtual ~A() {}
+    friend  int g(A* obj);    
+  protected:
+    A(const A&){}
+    virtual int f() = 0;
+  };
+  
+  int g(A* obj) {return 1;}
+
+%}
diff --git a/trunk/Examples/test-suite/director_basic.i b/trunk/Examples/test-suite/director_basic.i
new file mode 100644
index 0000000..986a170
--- /dev/null
+++ b/trunk/Examples/test-suite/director_basic.i
@@ -0,0 +1,142 @@
+ %module(directors="1") director_basic
+ #pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+ %{
+ #include <string>
+
+ class Foo {
+ public:
+   virtual ~Foo() {}
+   virtual std::string ping() { return "Foo::ping()"; }
+   virtual std::string pong() { return "Foo::pong();" + ping(); }
+
+   static Foo* get_self(Foo *self) {return self;}
+   
+ };
+
+ %}
+
+ %include <std_string.i>
+
+ %feature("director") Foo;
+
+
+ class Foo {
+ public:
+   virtual ~Foo();
+   virtual std::string ping();
+   virtual std::string pong();
+   
+   static Foo* get_self(Foo *self);
+   
+ };
+
+ %{
+ #include <complex> 
+ %}
+ %feature("director") A;
+
+ // basic renaming
+ %rename(rg) A::gg;
+ %feature("nodirector") hi::A1::gg;
+
+ %inline %{
+
+ struct A{
+     A(std::complex<int> i, double d=0.0) {}
+     A(int i, bool j=false) {}
+     virtual ~A() {}
+
+     virtual int f(int i=0) {return i;}
+     virtual int gg(int i=0) {return i;}
+ };
+
+ namespace hi  {
+
+   struct A1 : public A {
+     A1(std::complex<int> i, double d=0.0) : A(i, d) {}
+     A1(int i, bool j=false) : A(i, j) {}
+
+     virtual int ff(int i = 0) {return i;}  
+   };
+ }
+
+
+ %}
+
+
+ %feature("director") MyClass;
+
+ %inline %{
+
+ typedef void VoidType;
+
+  struct Bar
+  {
+    int x;
+    Bar(int _x = 0) : x(_x)
+    {
+    }
+ };
+ 
+ 
+
+class MyClass {
+public:
+  MyClass(int a = 0) 
+  {
+  }
+  
+  virtual void method(VoidType *)
+  {
+  }
+  
+  virtual ~MyClass()
+  {
+  }
+
+  virtual Bar vmethod(Bar b)
+  {
+    b.x += 13;
+    return b;
+  }  
+
+  virtual Bar* pmethod(Bar *b)
+  {
+    b->x += 12;
+    return b;
+  }  
+
+  Bar cmethod(const Bar &b)
+  {
+    return vmethod(b);
+  }  
+
+
+  static MyClass *get_self(MyClass *c) 
+  {
+    return c;
+  }
+  
+};
+
+template<class T>
+class MyClassT {
+public:
+  MyClassT(int a = 0) 
+  {
+  }
+  
+  virtual void method(VoidType *)
+  {
+  }
+  
+  virtual ~MyClassT()
+  {
+  }
+  
+};
+
+%}
+
+%template(MyClassT_i) MyClassT<int>;
diff --git a/trunk/Examples/test-suite/director_classes.i b/trunk/Examples/test-suite/director_classes.i
new file mode 100644
index 0000000..5d0a67d
--- /dev/null
+++ b/trunk/Examples/test-suite/director_classes.i
@@ -0,0 +1,104 @@
+// Tests classes passed by value, pointer and reference
+// Note: C# module has a large runtime test
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%module(directors="1") director_classes
+
+%feature("director") Base;
+%feature("director") Derived;
+
+%include "std_string.i"
+
+%inline %{
+#include <cstdio>
+#include <iostream>
+
+
+// Use for debugging
+bool PrintDebug = false;
+
+
+struct DoubleHolder
+{
+  DoubleHolder(double v = 0.0) : val(v) {}
+  double val;
+};
+
+class Base {
+protected:
+  double m_dd;
+public:
+
+  Base(double dd) : m_dd(dd) {}
+  virtual ~Base() {}
+
+  virtual DoubleHolder Val(DoubleHolder x) { if (PrintDebug) std::cout << "Base - Val(" << x.val << ")" << std::endl; return x; }
+  virtual DoubleHolder& Ref(DoubleHolder& x) { if (PrintDebug) std::cout << "Base - Ref(" << x.val << ")" << std::endl; return x; }
+  virtual DoubleHolder* Ptr(DoubleHolder* x) { if (PrintDebug) std::cout << "Base - Ptr(" << x->val << ")" << std::endl; return x; }
+
+  virtual std::string FullyOverloaded(int x) { if (PrintDebug) std::cout << "Base - FullyOverloaded(int " << x << ")" << std::endl; return "Base::FullyOverloaded(int)"; }
+  virtual std::string FullyOverloaded(bool x) { if (PrintDebug) std::cout << "Base - FullyOverloaded(bool " << x << ")" << std::endl; return "Base::FullyOverloaded(bool)"; }
+
+  virtual std::string SemiOverloaded(int x) { if (PrintDebug) std::cout << "Base - SemiOverloaded(int " << x << ")" << std::endl; return "Base::SemiOverloaded(int)"; }
+  virtual std::string SemiOverloaded(bool x) { if (PrintDebug) std::cout << "Base - SemiOverloaded(bool " << x << ")" << std::endl; return "Base::SemiOverloaded(bool)"; }
+
+  virtual std::string DefaultParms(int x, double y = 1.1) {
+    if (PrintDebug) std::cout << "Base - DefaultParms(" << x << ", " << y << ")" << std::endl;
+    std::string ret("Base::DefaultParms(int");
+    if (y!=1.1)
+      ret = ret + std::string(", double");
+    ret = ret + std::string(")");
+    return ret;
+  }
+};
+
+class Derived : public Base {
+public:
+  Derived(double dd) : Base(dd) {}
+  virtual ~Derived() {}
+
+  virtual DoubleHolder Val(DoubleHolder x) { if (PrintDebug) std::cout << "Derived - Val(" << x.val << ")" << std::endl; return x; }
+  virtual DoubleHolder& Ref(DoubleHolder& x) { if (PrintDebug) std::cout << "Derived - Ref(" << x.val << ")" << std::endl; return x; }
+  virtual DoubleHolder* Ptr(DoubleHolder* x) { if (PrintDebug) std::cout << "Derived - Ptr(" << x->val << ")" << std::endl; return x; }
+
+  virtual std::string FullyOverloaded(int x) { if (PrintDebug) std::cout << "Derived - FullyOverloaded(int " << x << ")" << std::endl; return "Derived::FullyOverloaded(int)"; }
+  virtual std::string FullyOverloaded(bool x) { if (PrintDebug) std::cout << "Derived - FullyOverloaded(bool " << x << ")" << std::endl; return "Derived::FullyOverloaded(bool)"; }
+
+  virtual std::string SemiOverloaded(int x) { if (PrintDebug) std::cout << "Derived - SemiOverloaded(int " << x << ")" << std::endl; return "Derived::SemiOverloaded(int)"; }
+  // No SemiOverloaded(bool x)
+
+  virtual std::string DefaultParms(int x, double y = 1.1) { 
+    if (PrintDebug) std::cout << "Derived - DefaultParms(" << x << ", " << y << ")" << std::endl;
+    std::string ret("Derived::DefaultParms(int");
+    if (y!=1.1)
+      ret = ret + std::string(", double");
+    ret = ret + std::string(")");
+    return ret;
+  }
+};
+
+
+class Caller {
+private:
+  Base *m_base;
+  void delBase() { delete m_base; m_base = 0; }
+public:
+  Caller(): m_base(0) {}
+  ~Caller() { delBase(); }
+  void set(Base *b) { delBase(); m_base = b; }
+  void reset() { m_base = 0; }
+
+  DoubleHolder ValCall(DoubleHolder x) { return m_base->Val(x); }
+  DoubleHolder& RefCall(DoubleHolder& x) { return m_base->Ref(x); }
+  DoubleHolder* PtrCall(DoubleHolder* x) { return m_base->Ptr(x); }
+  std::string FullyOverloadedCall(int x) { return m_base->FullyOverloaded(x); }
+  std::string FullyOverloadedCall(bool x) { return m_base->FullyOverloaded(x); }
+  std::string SemiOverloadedCall(int x) { return m_base->SemiOverloaded(x); }
+  std::string SemiOverloadedCall(bool x) { return m_base->SemiOverloaded(x); }
+  std::string DefaultParmsCall(int x) { return m_base->DefaultParms(x); }
+  std::string DefaultParmsCall(int x, double y) { return m_base->DefaultParms(x, y); }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/director_classic.i b/trunk/Examples/test-suite/director_classic.i
new file mode 100755
index 0000000..f22de4c
--- /dev/null
+++ b/trunk/Examples/test-suite/director_classic.i
@@ -0,0 +1,53 @@
+%module(directors="1") director_classic
+
+%include "std_string.i"
+
+%feature("director");
+
+%inline %{
+
+#include <cstdio>
+#include <iostream>
+#include <string>
+
+struct Being {
+  virtual std::string id() { return "Being"; }
+  virtual ~Being() {}
+};
+
+struct Person : Being {
+  virtual std::string id() { return "Person"; }
+};
+
+struct Child : Person {
+  virtual std::string id() { return "Child"; }
+};
+
+struct GrandChild : Child {
+  virtual std::string id() { return "GrandChild"; }
+};
+
+// Orphans - don't override id() in C++
+struct OrphanPerson : Person {
+  // no overridden id()
+};
+
+struct OrphanChild : Child {
+  // no overridden id()
+};
+
+class Caller {
+private:
+  Person *_callback;
+public:
+  Caller(): _callback(0) {}
+  ~Caller() { delCallback(); }
+  void delCallback() { delete _callback; _callback = 0; }
+  void setCallback(Person *cb) { delCallback(); _callback = cb; }
+  void resetCallback() { _callback = 0; }
+  std::string call() { if (_callback) return _callback->id(); else return "oops";  }
+  Person* baseClass() { return _callback; }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/director_constructor.i b/trunk/Examples/test-suite/director_constructor.i
new file mode 100644
index 0000000..b3505f9
--- /dev/null
+++ b/trunk/Examples/test-suite/director_constructor.i
@@ -0,0 +1,37 @@
+%module(directors="1") director_constructor
+
+%feature("director") Foo;
+
+%inline %{
+class Foo
+{
+public:
+  int a;
+  
+  Foo(int i)
+  {
+    a=i;
+  }
+  
+  virtual ~Foo() { }
+  
+  int do_test() {
+    return test();
+  }
+  
+  virtual int getit()
+  {
+    return a;
+  }
+  
+  virtual void doubleit()
+  {
+    a = a * 2;
+  }
+  
+  virtual int test() = 0; 
+};
+%}  
+  
+
+
diff --git a/trunk/Examples/test-suite/director_default.i b/trunk/Examples/test-suite/director_default.i
new file mode 100644
index 0000000..8eb2ce3
--- /dev/null
+++ b/trunk/Examples/test-suite/director_default.i
@@ -0,0 +1,66 @@
+%module(directors="1") director_default
+
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) DefaultsBase;
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) DefaultsDerived;
+
+%{
+#include <string>
+
+class Foo {
+public:
+        Foo(int i = -1) {}
+	virtual ~Foo() {}
+	virtual std::string Msg(std::string msg = "default") { return "Foo-" + msg; }
+
+	std::string GetMsg() { return Msg(); }
+	std::string GetMsg(std::string msg) { return Msg(msg); }
+};
+
+%}
+
+%include <std_string.i>
+
+%feature("director") Foo;
+
+class Foo {
+public:
+        Foo(int i = -1) {}
+	virtual ~Foo() {}
+	virtual std::string Msg(std::string msg = "default") { return msg; }
+
+	std::string GetMsg() { return Msg(); }
+	std::string GetMsg(std::string msg) { return Msg(msg); }
+};
+
+
+%inline %{
+class Bar {
+public:
+        Bar() {}
+        Bar(int i) {}
+	virtual ~Bar() {}
+	virtual std::string Msg(std::string msg = "default") { return "Bar-" + msg; }
+
+	std::string GetMsg() { return Msg(); }
+	std::string GetMsg(std::string msg) { return Msg(msg); }
+};
+
+%}
+
+%feature("director") DefaultsBase;
+%feature("director") DefaultsDerived;
+
+%inline %{
+typedef int* IntegerPtr;
+typedef double Double;
+
+struct DefaultsBase {
+	virtual IntegerPtr defaultargs(double d, int * a = 0) = 0;
+        virtual ~DefaultsBase() {}
+};
+
+struct DefaultsDerived : DefaultsBase {
+	int * defaultargs(Double d, IntegerPtr a = 0) { return 0; }
+};
+%}
+
diff --git a/trunk/Examples/test-suite/director_detect.i b/trunk/Examples/test-suite/director_detect.i
new file mode 100644
index 0000000..355e5ee
--- /dev/null
+++ b/trunk/Examples/test-suite/director_detect.i
@@ -0,0 +1,70 @@
+%module(directors="1") director_detect
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET,
+	    SWIGWARN_CSHARP_COVARIANT_RET) cloner; /* Java, C# covariant return types */
+
+%{
+#include <string>
+#include <iostream>
+%}
+
+%include <std_string.i>
+
+%feature("director") Bar;
+%feature("director") Foo;
+
+%newobject Foo::cloner();
+%newobject Bar::cloner();
+
+
+%inline {
+  namespace foo { typedef int Int; }
+  
+  struct A
+  {
+  };
+  
+  typedef A B;
+  
+  struct Foo {
+    virtual ~Foo() {}
+    virtual Foo* cloner() = 0;
+    virtual int get_value() = 0;
+    virtual A* get_class() = 0;
+
+    virtual void just_do_it() = 0;
+  };
+  
+  class Bar : public Foo
+  {
+  public:    
+    Foo* baseclass() 
+    {
+      return this;
+    }    
+    
+    Bar* cloner()
+    {
+      return new Bar();
+    }
+    
+    
+    foo::Int get_value() 
+    {
+      return 1;
+    }
+
+    B* get_class() 
+    {
+      return new B();
+    }
+
+    void just_do_it() 
+    {
+    }
+  };  
+}
+
+
+
diff --git a/trunk/Examples/test-suite/director_enum.i b/trunk/Examples/test-suite/director_enum.i
new file mode 100644
index 0000000..c7932d1
--- /dev/null
+++ b/trunk/Examples/test-suite/director_enum.i
@@ -0,0 +1,86 @@
+%module(directors="1") director_enum
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::hi; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::hello; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::yo; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::awright; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::Foo::ciao; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::Foo::aufwiedersehen; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) EnumDirector::Foo::adios; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,
+	    SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) EnumDirector::Foo; /* Thread/reentrant unsafe wrapping, consider returning by value instead. */
+
+
+
+%feature("director") Foo;
+
+%rename(Hallo) EnumDirector::Hello;
+
+%inline %{
+namespace EnumDirector {
+  struct A;
+
+  enum Hello {
+    hi, hello, yo, awright = 10
+  };
+
+  class Foo {
+  public:
+    enum Bye {
+      ciao, aufwiedersehen = 100, adios
+    };
+    virtual ~Foo() {}
+    virtual Hello say_hi(Hello h){ return h;}
+    virtual Hello say_hello(Hello){ return hello;}
+    virtual Hello say_hi(A *a){ return hi;}
+    virtual Bye say_bye(Bye b){ return b;}
+    virtual const Hello & say_hi_ref(const Hello & h){ return h;}
+
+    Hello ping(Hello h){ return say_hi(h);}
+    const Hello & ping_ref(const Hello &h){ return say_hi_ref(h);}
+    Bye ping_member_enum(Bye b){ return say_bye(b);}
+
+  };
+}
+%}
+
+%feature("director");
+
+%inline %{
+namespace EnumDirector {
+enum FType{ SA = -1, NA=0, EA=1};
+
+struct A{
+    A(const double a, const double b, const FType c)
+    {}    
+
+    virtual ~A() {}
+    
+    virtual int f(int i=0) {return i;}
+};
+
+struct B : public A{
+    B(const double a, const double b, const FType c)
+        : A(a, b, c) 
+    {}    
+};
+}
+%}
+
+
+%inline %{
+namespace EnumDirector {
+struct A2{
+    A2(const FType c = NA) {}    
+
+    virtual ~A2() {}
+    
+    virtual int f(int i=0) {return i;}
+};
+
+struct B2 : public A2{
+    B2(const FType c) : A2(c) {}
+};
+}
+ 
+%}
diff --git a/trunk/Examples/test-suite/director_exception.i b/trunk/Examples/test-suite/director_exception.i
new file mode 100644
index 0000000..de0ef33
--- /dev/null
+++ b/trunk/Examples/test-suite/director_exception.i
@@ -0,0 +1,112 @@
+%module(directors="1") director_exception
+
+%{
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+#include <string>
+
+
+// define dummy director exception classes to prevent spurious errors 
+// in target languages that do not support directors.
+
+#ifndef SWIG_DIRECTORS
+namespace Swig {
+class DirectorException {};
+class DirectorMethodException: public Swig::DirectorException {};
+}
+  #ifndef SWIG_fail
+    #define SWIG_fail
+  #endif
+#endif /* !SWIG_DIRECTORS */
+
+%}
+
+%include "std_string.i"
+
+#ifdef SWIGPYTHON
+
+%feature("director:except") {
+	if ($error != NULL) {
+		throw Swig::DirectorMethodException();
+	}
+}
+
+%exception {
+	try { $action }
+	catch (Swig::DirectorException &) { SWIG_fail; }
+}
+
+#endif
+
+#ifdef SWIGRUBY
+
+%feature("director:except") {
+    throw Swig::DirectorMethodException($error);
+}
+
+%exception {
+  try { $action }
+  catch (Swig::DirectorException &e) { rb_exc_raise(e.getError()); }
+}
+
+#endif
+
+%feature("director") Foo;
+
+%inline {
+
+class Foo {
+public:
+  virtual ~Foo() {}
+  virtual std::string ping() { return "Foo::ping()"; }
+  virtual std::string pong(int val=3) { return "Foo::pong();" + ping(); }
+};
+
+Foo *launder(Foo *f) {
+  return f;
+}
+
+}
+
+
+%{
+  struct Unknown1
+  {
+  };
+
+  struct Unknown2
+  {
+  };
+%}
+
+%feature("director") Bar;
+
+
+%inline %{
+  struct Exception1
+  {
+  };
+
+  struct Exception2
+  {
+  };
+
+  class Base 
+  {
+  public:
+    virtual ~Base() throw () {}
+  };
+  
+
+  class Bar : public Base
+  {
+  public:
+    virtual std::string ping() throw (Exception1, Exception2&) { return "Bar::ping()"; }
+    virtual std::string pong() throw (Unknown1, int, Unknown2&) { return "Bar::pong();" + ping(); }
+    virtual std::string pang() throw () { return "Bar::pang()"; }
+  };
+  
+%}
diff --git a/trunk/Examples/test-suite/director_extend.i b/trunk/Examples/test-suite/director_extend.i
new file mode 100644
index 0000000..515866a
--- /dev/null
+++ b/trunk/Examples/test-suite/director_extend.i
@@ -0,0 +1,54 @@
+
+%module(directors="1") director_extend
+
+%extend SpObject 
+{
+   virtual int dummy()          // Had to remove virtual to work
+   {
+      return $self->getFooBar();
+   }
+};
+
+%inline %{
+#ifndef SWIG_DIRECTORS
+// dummy definition for non-director languages
+namespace Swig {
+  typedef int Director;
+}
+#endif
+%}
+
+%extend SpObject
+{
+  size_t ExceptionMethod()
+  {
+// Check positioning of director code in wrapper file
+// Below is what we really want to test, but director exceptions vary too much across across all languages
+//    throw Swig::DirectorException("DirectorException was not in scope!!");
+// Instead check definition of Director class as that is defined in the same place as DirectorException (director.swg)
+    size_t size = sizeof(Swig::Director);
+    return size;
+  }
+};
+
+
+%inline %{
+class SpObject
+{
+public:
+   SpObject() {}
+   virtual ~SpObject() {}
+
+   int getFooBar() const {
+      return 666;
+   }
+
+private:
+   // Do NOT define the assignment operator
+   SpObject& operator=(const SpObject& rhs);
+
+   // This class can not be copied.  Do NOT define the copy Constructor.
+   SpObject (const SpObject& rhs);
+};
+%}
+
diff --git a/trunk/Examples/test-suite/director_finalizer.i b/trunk/Examples/test-suite/director_finalizer.i
new file mode 100644
index 0000000..52cdb1f
--- /dev/null
+++ b/trunk/Examples/test-suite/director_finalizer.i
@@ -0,0 +1,42 @@
+%module(directors="1") director_finalizer
+%{
+
+int status = 0;
+
+class Foo {
+public:
+	virtual ~Foo() { orStatus(1); }
+	virtual void orStatus(int x) { status |= x; }
+};
+
+void deleteFoo(Foo *f) {
+	delete f;
+}
+
+Foo *launder(Foo *f) {
+	return f;
+}
+
+int getStatus() {
+	return status;
+}
+
+void resetStatus() {
+	status = 0;
+}
+
+%}
+
+%feature("director") Foo;
+
+class Foo {
+public:
+	virtual ~Foo();
+	virtual void orStatus(int x);
+};
+
+void deleteFoo(Foo *f);
+int getStatus();
+Foo *launder(Foo *f);
+void resetStatus();
+
diff --git a/trunk/Examples/test-suite/director_frob.i b/trunk/Examples/test-suite/director_frob.i
new file mode 100644
index 0000000..cf555eb
--- /dev/null
+++ b/trunk/Examples/test-suite/director_frob.i
@@ -0,0 +1,106 @@
+%module(directors="1") director_frob;
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%header %{
+#include <iostream>
+%}
+
+%feature("director");
+%feature("nodirector") Bravo::abs_method();   // ok
+%feature("director")   Charlie::abs_method(); // ok
+%feature("nodirector") Delta::abs_method();   // ok
+
+%inline %{
+
+  struct Alpha
+  {
+    virtual ~Alpha() { };
+    virtual const char* abs_method() = 0;
+  };
+  
+  struct Bravo : Alpha
+  {
+    const char* abs_method()
+    {
+      return "Bravo::abs_method()";
+    }
+  };
+
+  struct Charlie : Bravo 
+  {
+    const char* abs_method()
+    {
+      return "Charlie::abs_method()";
+    }
+  };
+  
+  struct Delta : Charlie
+  {
+  };
+%}
+
+%rename(OpInt) operator int();
+%rename(OpIntStarStarConst) operator int **() const;
+%rename(OpIntAmp) operator int &();
+%rename(OpIntStar) operator void *();
+%rename(OpConstIntIntStar) operator const int *();
+
+%inline %{
+  class Ops {
+  public:
+    Ops() : num(0) {}
+    virtual ~Ops() {}
+    virtual operator int() { return 0; }
+    virtual operator int **() const {
+      return (int **) 0;
+    }
+    virtual operator int &() {
+      return num;
+    }
+    virtual operator void *() {
+      return (void *) this;
+    }
+    virtual operator const int *() {
+      return &num;
+    }
+  private:
+    int num;
+  };
+
+  struct Prims {
+    virtual ~Prims() {}
+    virtual unsigned long long ull(unsigned long long i, unsigned long long j) { return i + j; }
+    unsigned long long callull(int i, int j) { return ull(i, j); }
+  };
+%}
+
+
+// The similarity of the director class name and other symbol names were causing a problem in the code generation
+%feature("director") coreCallbacks;
+
+%inline %{
+class corePoint3d {};
+
+struct coreCallbacks_On3dEngineRedrawnData
+{
+	corePoint3d _eye;
+	corePoint3d _at;
+};
+
+struct coreCallbacksOn3dEngineRedrawnData
+{
+	corePoint3d _eye;
+	corePoint3d _at;
+};
+
+class coreCallbacks
+{
+public:
+	coreCallbacks(void) {}
+	virtual ~coreCallbacks(void) {}
+
+	virtual void On3dEngineRedrawn(const coreCallbacks_On3dEngineRedrawnData& data){}
+	virtual void On3dEngineRedrawn2(const coreCallbacksOn3dEngineRedrawnData& data){}
+};
+%}
+
diff --git a/trunk/Examples/test-suite/director_ignore.i b/trunk/Examples/test-suite/director_ignore.i
new file mode 100755
index 0000000..51317fb
--- /dev/null
+++ b/trunk/Examples/test-suite/director_ignore.i
@@ -0,0 +1,96 @@
+%module(directors="1") director_ignore
+
+%warnfilter(SWIGWARN_LANG_DIRECTOR_ABSTRACT) DIgnoreOnlyConstructor;
+
+%include "std_string.i"
+
+%feature("director");
+
+%ignore OverloadedMethod(int n, int xoffset = 0, int yoffset = 0);
+%ignore OverloadedProtectedMethod(int n, int xoffset = 0, int yoffset = 0);
+%ignore DIgnoreConstructor(bool b);
+%ignore DIgnoreOnlyConstructor(bool b);
+%ignore Pointers;
+%ignore References;
+%ignore PublicMethod1;
+%ignore PublicMethod2;
+%ignore PublicPureVirtualMethod1;
+%ignore PublicPureVirtualMethod2;
+%ignore ProtectedMethod1;
+%ignore ProtectedMethod2;
+%ignore ProtectedPureVirtualMethod1;
+%ignore ProtectedPureVirtualMethod2;
+
+%inline %{
+
+#include <string>
+class DIgnores
+{
+  public:
+    virtual ~DIgnores() {}
+    virtual void OverloadedMethod(int n, int xoffset = 0, int yoffset = 0) {}
+    virtual void OverloadedMethod(bool b) {}
+    virtual int Triple(int n) { return n*3; }
+    virtual int& References(int& n) { static int nn; nn=n; return nn; }
+    virtual int* Pointers(int* n) { static int nn; nn=*n; return &nn; }
+    virtual double PublicMethod1() { return 0.0; }
+    virtual double PublicPureVirtualMethod1() = 0;
+    virtual void PublicMethod2() {}
+    virtual void PublicPureVirtualMethod2() = 0;
+    virtual void TempMethod() = 0;
+  protected:
+    virtual void OverloadedProtectedMethod(int n, int xoffset = 0, int yoffset = 0) {}
+    virtual void OverloadedProtectedMethod() {}
+    virtual double ProtectedMethod1() { return 0.0; }
+    virtual double ProtectedPureVirtualMethod1() = 0;
+    virtual void ProtectedMethod2() {}
+    virtual void ProtectedPureVirtualMethod2() = 0;
+};
+
+class DAbstractIgnores
+{
+  public:
+    virtual ~DAbstractIgnores() {}
+    virtual double OverloadedMethod(int n, int xoffset = 0, int yoffset = 0) = 0;
+    virtual double OverloadedMethod(bool b) = 0;
+    virtual int Quadruple(int n) { return n*4; }
+    virtual int& References(int& n) { static int nn; nn=n; return nn; }
+    virtual int* Pointers(int* n) { static int nn; nn=*n; return &nn; }
+  protected:
+    virtual double OverloadedProtectedMethod(int n, int xoffset = 0, int yoffset = 0) = 0;
+    virtual double OverloadedProtectedMethod() = 0;
+};
+
+class DIgnoreConstructor
+{
+  public:
+    virtual ~DIgnoreConstructor() {}
+    DIgnoreConstructor(std::string s, int i) {}
+    DIgnoreConstructor(bool b) {}
+};
+
+class DIgnoreOnlyConstructor
+{
+  public:
+    virtual ~DIgnoreOnlyConstructor() {}
+    DIgnoreOnlyConstructor(bool b) {}
+};
+
+template <typename T> class DTemplateAbstractIgnores
+{
+  T t;
+  public:
+    virtual ~DTemplateAbstractIgnores() {}
+    virtual double OverloadedMethod(int n, int xoffset = 0, int yoffset = 0) = 0;
+    virtual double OverloadedMethod(bool b) = 0;
+    virtual int Quadruple(int n) { return n*4; }
+    virtual int& References(int& n) { static int nn; nn=n; return nn; }
+    virtual int* Pointers(int* n) { static int nn; nn=*n; return &nn; }
+  protected:
+    virtual double OverloadedProtectedMethod(int n, int xoffset = 0, int yoffset = 0) = 0;
+    virtual double OverloadedProtectedMethod() = 0;
+};
+%}
+
+%template(DTemplateAbstractIgnoresInt) DTemplateAbstractIgnores<int>;
+
diff --git a/trunk/Examples/test-suite/director_namespace_clash.i b/trunk/Examples/test-suite/director_namespace_clash.i
new file mode 100644
index 0000000..5525159
--- /dev/null
+++ b/trunk/Examples/test-suite/director_namespace_clash.i
@@ -0,0 +1,21 @@
+%module(directors="1") director_namespace_clash
+
+%rename(GreatOne) One::Great;
+
+%feature("director");
+
+%inline %{
+namespace One {
+  struct Great {
+    virtual void superb(int a) {}
+    virtual ~Great() {}
+  };
+}
+namespace Two {
+  struct Great {
+    virtual void excellent() {}
+    virtual ~Great() {}
+  };
+}
+%}
+
diff --git a/trunk/Examples/test-suite/director_nested.i b/trunk/Examples/test-suite/director_nested.i
new file mode 100644
index 0000000..c1b4d29
--- /dev/null
+++ b/trunk/Examples/test-suite/director_nested.i
@@ -0,0 +1,86 @@
+%module(directors="1",dirprot="1") director_nested
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%{
+#include <string>
+#include <iostream>
+%}
+
+%include "std_string.i"
+
+%feature("director") Bar;
+%feature("director") Foo<int>;
+%feature("director") FooBar<int>;
+
+%newobject *::create();
+
+%inline {
+  template <class C>
+    class Foo {
+    public:
+      virtual ~Foo() {}
+      
+      std::string advance() 
+      {
+	return "Foo::advance;" + do_advance();
+      }  
+
+    protected:
+      virtual std::string do_advance() = 0;
+    };
+}
+
+%template(Foo_int) Foo<int>;
+
+%inline {
+
+  class Bar : public Foo<int>
+  {
+  public:
+    
+    std::string step() 
+    {
+      return "Bar::step;" + advance();    
+    }
+    
+  protected:
+    std::string do_advance() 
+    {
+      return "Bar::do_advance;" + do_step();
+    }
+    
+
+#if defined(SWIGPYTHON) || defined(SWIGRUBY) || \
+  defined(SWIGJAVA) || defined(SWIGOCAML) || defined(SWIGCSHARP)
+    virtual std::string do_step() const = 0;
+#else
+    virtual std::string do_step() const {return "";};
+#endif
+  };  
+  
+  template <class C>
+    class FooBar : public Bar
+    {
+    public:
+      virtual C get_value() const = 0;
+
+      virtual const char * get_name() 
+      {
+	return "FooBar::get_name";
+      }
+
+      const char *name() 
+      {
+	return get_name();
+      }
+      
+      static FooBar *get_self(FooBar *a)
+      {
+	return a;
+      }
+      
+    };
+}
+
+%template(FooBar_int) FooBar<int>;
+
diff --git a/trunk/Examples/test-suite/director_overload.i b/trunk/Examples/test-suite/director_overload.i
new file mode 100644
index 0000000..55bdf2c
--- /dev/null
+++ b/trunk/Examples/test-suite/director_overload.i
@@ -0,0 +1,47 @@
+%module(directors="1") director_overload
+
+%feature("director");
+
+#ifdef SWIGPYTHON
+%feature("director:except") {
+  if ($error != NULL) {
+    throw Swig::DirectorMethodException();
+  }
+}
+#endif
+
+#ifdef SWIGRUBY
+// Catch ruby exceptions in directors
+%feature("director:except") {
+ throw Swig::DirectorMethodException($error);
+}
+#endif
+
+%inline %{
+
+class OverloadedClass
+{
+public:
+  virtual ~OverloadedClass() {}
+  virtual void method1() const {}
+  virtual void method2() const {}
+  virtual void method3() const {}
+  // test overloaded method, but not directly after the first method
+  virtual void method2(bool b) const {}
+};
+
+class OverloadedPointers
+{
+public:
+  virtual ~OverloadedPointers() {}
+  virtual void method(int *p) const {}
+  virtual void method(double *p) const {}
+  virtual void method(bool &r) const {}
+  virtual void method(short &r) const {}
+  virtual void method(OverloadedClass *p) const {}
+  virtual void method(OverloadedPointers *p) const {}
+  virtual void notover(int *p) const {}
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/director_primitives.i b/trunk/Examples/test-suite/director_primitives.i
new file mode 100644
index 0000000..0842bd2
--- /dev/null
+++ b/trunk/Examples/test-suite/director_primitives.i
@@ -0,0 +1,88 @@
+// Tests primitives
+// Note: C# module has a large runtime test
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%module(directors="1") director_primitives
+
+%feature("director") Base;
+%feature("director") Derived;
+
+%include "std_string.i"
+
+%inline %{
+#include <cstdio>
+#include <iostream>
+
+
+// Use for debugging
+bool PrintDebug = false;
+
+enum HShadowMode
+{
+  HShadowNone = 1,
+  HShadowSoft = 2,
+  HShadowHard = 3
+};
+
+class Base {
+protected:
+  double m_dd;
+public:
+
+  Base(double dd) : m_dd(dd) {}
+  virtual ~Base() {}
+
+  virtual void NoParmsMethod() { if (PrintDebug) std::cout << "Base - NoParmsMethod()" << std::endl; }
+  virtual bool BoolMethod(bool x) { if (PrintDebug) std::cout << "Base - BoolMethod(" << x << ")" << std::endl; return x; }
+  virtual int IntMethod(int x) { if (PrintDebug) std::cout << "Base - IntMethod(" << x << ")" << std::endl; return x; }
+  virtual unsigned int UIntMethod(unsigned int x) { if (PrintDebug) std::cout << "Base - UIntMethod(" << x << ")" << std::endl; return x; }
+  virtual float FloatMethod(float x) { if (PrintDebug) std::cout << "Base - FloatMethod(" << x << ")" << std::endl; return x; }
+  virtual char * CharPtrMethod(char * x) { if (PrintDebug) std::cout << "Base - CharPtrMethod(" << x << ")" << std::endl; return x; }
+  virtual const char * ConstCharPtrMethod(const char * x) { if (PrintDebug) std::cout << "Base - ConstCharPtrMethod(" << x << ")" << std::endl; return x; }
+  virtual HShadowMode EnumMethod(HShadowMode x) { if (PrintDebug) std::cout << "Base - EnumMethod(" << x << ")" << std::endl; return x; }
+  virtual void ManyParmsMethod(bool b, int i, unsigned int u, float f, char * c, const char * cc, HShadowMode h) { if (PrintDebug) std::cout << "Base - ManyParmsMethod(" << b << ", " << i << ", " << u << ", " << f << ", " << c << ", " << cc << ", " << h << ")" << std::endl; }
+  virtual void NotOverriddenMethod() { if (PrintDebug) std::cout << "Base - NotOverriddenMethod()" << std::endl; }
+};
+
+class Derived : public Base {
+public:
+  Derived(double dd) : Base(dd) {}
+  virtual ~Derived() {}
+
+  virtual void NoParmsMethod() { if (PrintDebug) std::cout << "Derived - NoParmsMethod()" << std::endl; }
+  virtual bool BoolMethod(bool x) { if (PrintDebug) std::cout << "Derived - BoolMethod(" << x << ")" << std::endl; return x; }
+  virtual int IntMethod(int x) { if (PrintDebug) std::cout << "Derived - IntMethod(" << x << ")" << std::endl; return x; }
+  virtual unsigned int UIntMethod(unsigned int x) { if (PrintDebug) std::cout << "Derived - UIntMethod(" << x << ")" << std::endl; return x; }
+  virtual float FloatMethod(float x) { if (PrintDebug) std::cout << "Derived - FloatMethod(" << x << ")" << std::endl; return x; }
+  virtual char * CharPtrMethod(char * x) { if (PrintDebug) std::cout << "Derived - CharPtrMethod(" << x << ")" << std::endl; return x; }
+  virtual const char * ConstCharPtrMethod(const char * x) { if (PrintDebug) std::cout << "Derived - ConstCharPtrMethod(" << x << ")" << std::endl; return x; }
+  virtual HShadowMode EnumMethod(HShadowMode x) { if (PrintDebug) std::cout << "Derived - EnumMethod(" << x << ")" << std::endl; return x; }
+  virtual void ManyParmsMethod(bool b, int i, unsigned int u, float f, char * c, const char * cc, HShadowMode h) { if (PrintDebug) std::cout << "Derived - ManyParmsMethod(" << b << ", " << i << ", " << u << ", " << f << ", " << c << ", " << cc << ", " << h << ")" << std::endl; }
+};
+
+
+class Caller {
+private:
+  Base *m_base;
+  void delBase() { delete m_base; m_base = 0; }
+public:
+  Caller(): m_base(0) {}
+  virtual ~Caller() { delBase(); }
+  void set(Base *b) { delBase(); m_base = b; }
+  void reset() { m_base = 0; }
+
+  void NoParmsMethodCall() { m_base->NoParmsMethod(); }
+  bool BoolMethodCall(bool x) { return m_base->BoolMethod(x); }
+  int IntMethodCall(int x) { return m_base->IntMethod(x); }
+  unsigned int UIntMethodCall(unsigned int x) { return m_base->UIntMethod(x); }
+  float FloatMethodCall(float x) { return m_base->FloatMethod(x); }
+  char * CharPtrMethodCall(char * x) { return m_base->CharPtrMethod(x); }
+  const char * ConstCharPtrMethodCall(const char * x) { return m_base->ConstCharPtrMethod(x); }
+  HShadowMode EnumMethodCall(HShadowMode x) { return m_base->EnumMethod(x); }
+  virtual void ManyParmsMethodCall(bool b, int i, unsigned int u, float f, char * c, const char * cc, HShadowMode h) { return m_base->ManyParmsMethod(b, i, u, f, c, cc, h); }
+  virtual void NotOverriddenMethodCall() { m_base->NotOverriddenMethod(); }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/director_protected.i b/trunk/Examples/test-suite/director_protected.i
new file mode 100644
index 0000000..df34185
--- /dev/null
+++ b/trunk/Examples/test-suite/director_protected.i
@@ -0,0 +1,141 @@
+%module(directors="1",dirprot="1") director_protected
+%{
+#include <string>
+#include <iostream>
+%}
+
+%include "std_string.i"
+
+%feature("director") Foo;
+%feature("director") Bar;
+
+%newobject *::create();
+
+%rename(a) Bar::hello;
+%rename(s) Foo::p;
+%rename(q) Foo::r;
+
+%inline {
+class Foo {
+public:
+  virtual ~Foo() {}
+  virtual std::string pong() {
+    return "Foo::pong();" + ping();
+  }
+
+  int p(){ return 1;}
+  int r(){ return 1;}
+    
+  
+protected:
+  
+  typedef int q(); 
+  static int s(); 
+  
+  Foo() {}  
+
+  virtual std::string ping() = 0;
+
+  virtual std::string pang() 
+  {
+    return "Foo::pang();"; 
+  }
+
+  void hellom() {}
+
+  virtual std::string used() {
+    return pang() + pong();
+  }
+};
+
+class Bar : public Foo 
+{
+public:
+  Foo* create() 
+  {
+    return new Bar();
+  }
+
+  std::string pong() {
+    return "Bar::pong();" + Foo::pong();
+  }
+
+  int hello;
+
+  using Foo::used;
+  
+protected:
+  std::string ping() { 
+    return "Bar::ping();"; 
+  };
+
+  enum Hello {hola, chao};
+
+  static int a;
+  static const int b;
+  
+  int hi;
+  void him() {}
+
+private:
+  int c;
+
+};
+ 
+
+class PrivateFoo : private Foo 
+{
+};
+
+}
+
+
+%director A;
+%director B;
+
+%inline %{
+  class A {
+  public:
+    A() {};
+    virtual ~A() {};
+  protected:
+    virtual void draw() {};
+  };
+
+  class B : public A {
+  public:
+    B() {};
+    virtual ~B() {};
+  protected:
+    void draw() {};
+    void draw(int arg1) {};
+  };
+
+%}
+
+
+%cleardirector;
+
+%inline %{
+  class AA {
+  public:
+    AA() {};
+    virtual ~AA() {};
+  protected:
+    virtual void draw() {};
+    virtual void plot() {};
+  };
+
+  class BB : public AA {
+  public:
+    BB() {};
+    virtual ~BB() {};
+  protected:
+    void draw() {};
+    void draw(int arg1) {};
+
+    void plot(int arg1) {};
+    void plot() {};
+  };
+%}
+
diff --git a/trunk/Examples/test-suite/director_redefined.i b/trunk/Examples/test-suite/director_redefined.i
new file mode 100644
index 0000000..60da4a1
--- /dev/null
+++ b/trunk/Examples/test-suite/director_redefined.i
@@ -0,0 +1,50 @@
+%module(directors="1") director_redefined
+
+ /*
+   This example generates two 'get_val' virtual members in the
+   director, and since they are equivalent, the compilation fails.
+ */
+
+%feature("director")  B;
+
+%inline 
+{
+  typedef int Int;
+
+  struct A
+  {
+    virtual ~A()
+    {
+    }
+
+    virtual int get_val(Int a)
+    {
+      return 0;
+    }
+
+    virtual int get_rval(const Int& a)
+    {
+      return 0;
+    }
+    
+  };
+  
+  struct B : A
+  {
+    int get_val(int a)
+    {
+      return 1;
+    }    
+
+    int get_rval(const int& a)
+    {
+      return 1;
+    }    
+
+    const int& get_rrval(const int& a)
+    {
+      return a;
+    }    
+  };  
+}
+
diff --git a/trunk/Examples/test-suite/director_string.i b/trunk/Examples/test-suite/director_string.i
new file mode 100644
index 0000000..8dfbe03
--- /dev/null
+++ b/trunk/Examples/test-suite/director_string.i
@@ -0,0 +1,58 @@
+%module(directors="1") director_string;
+%include <stl.i>
+
+#ifndef SWIG_STL_UNIMPL
+
+%include std_vector.i
+%include std_string.i
+
+// Using thread unsafe wrapping
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) A;
+
+%{
+#include <vector>
+#include <string>
+%}
+
+%feature("director") A;
+%inline %{
+
+struct A
+{
+  A(const std::string& first)
+    : m_strings(1, first)
+  {}
+  
+  virtual ~A() {}
+  
+  virtual const std::string& get_first() const
+  { return get(0); }
+  
+  virtual const std::string& get(int n) const
+  { return m_strings[n]; }
+
+  virtual const std::string& call_get_first() const
+  { return get_first(); }
+
+  virtual const std::string& call_get(int n) const
+  { return get(n); }
+
+  virtual int string_length(const std::string & s) const
+  { return (int)s.size(); }
+
+  std::vector<std::string> m_strings;
+
+
+  virtual void process_text(const char *text) 
+  {
+  }
+
+  void call_process_func() { process_text("hello"); }
+ };
+ 
+ %}
+
+%template(StringVector) std::vector<std::string>;
+
+
+#endif
diff --git a/trunk/Examples/test-suite/director_thread.i b/trunk/Examples/test-suite/director_thread.i
new file mode 100644
index 0000000..4f4e55c
--- /dev/null
+++ b/trunk/Examples/test-suite/director_thread.i
@@ -0,0 +1,85 @@
+// This testcase was in the python subdirectory
+
+#if defined(SWIGPYTHON)
+// Is "threads" really needed for Python? It seems to work without it.
+%module(directors="1",threads="1") director_thread
+#else
+%module(directors="1") director_thread
+#endif
+
+%{
+#ifdef _WIN32
+#include <windows.h>
+#include <process.h>
+#else
+#include <pthread.h>
+#include <unistd.h>
+#endif
+
+#include <iostream>
+
+class Foo;  
+extern "C" {
+#ifdef _WIN32
+  unsigned int __stdcall working(void* t);
+  unsigned int thread_id(0);
+#else
+  void* working(void* t);
+  pthread_t thread;
+#endif
+}
+%}
+
+%director Foo;
+
+%inline {
+  static void MilliSecondSleep(int milliseconds) {
+  %#ifdef _WIN32
+    Sleep(milliseconds);
+  %#else
+    usleep(milliseconds*1000);
+  %#endif
+  }
+
+  class Foo {
+  public:
+    int val;
+    
+    Foo() : val(0) {
+    }
+    
+    virtual ~Foo()  {
+    }
+
+    void run() {
+%#ifdef _WIN32
+      _beginthreadex(NULL,0,working,this,0,&thread_id);
+%#else
+      pthread_create(&thread,NULL,working,this);
+%#endif
+      MilliSecondSleep(500);
+    }
+    
+    virtual void do_foo() {
+      val += 1;
+    }
+  };
+}
+
+%{
+extern "C" {
+#ifdef _WIN32
+  unsigned int __stdcall working(void* t)
+#else
+  void* working(void* t)
+#endif
+  {
+    Foo* f = static_cast<Foo*>(t);
+    while (1) {
+      MilliSecondSleep(50);
+      f->do_foo();
+    }
+    return 0;
+  }
+}
+%}
diff --git a/trunk/Examples/test-suite/director_unroll.i b/trunk/Examples/test-suite/director_unroll.i
new file mode 100644
index 0000000..6a11c3a
--- /dev/null
+++ b/trunk/Examples/test-suite/director_unroll.i
@@ -0,0 +1,40 @@
+%module(directors="1") director_unroll
+%{
+#include <string>
+
+class Foo {
+public:
+	virtual ~Foo() {}
+	virtual std::string ping() { return "Foo::ping()"; }
+	virtual std::string pong() { return "Foo::pong();" + ping(); }
+};
+
+class Bar {
+private:
+	Foo *foo;
+public:
+	void set(Foo *x) { foo = x; }
+	Foo *get() { return foo; }
+};
+
+%}
+
+%include "std_string.i"
+
+%feature("director") Foo;
+
+class Foo {
+public:
+	virtual ~Foo() {}
+	virtual std::string ping() { return "Foo::ping()"; }
+	virtual std::string pong() { return "Foo::pong();" + ping(); }
+};
+
+class Bar {
+private:
+	Foo *foo;
+public:
+	void set(Foo *x) { foo = x; }
+	Foo *get() { return foo; }
+};
+
diff --git a/trunk/Examples/test-suite/director_using.i b/trunk/Examples/test-suite/director_using.i
new file mode 100644
index 0000000..104528c
--- /dev/null
+++ b/trunk/Examples/test-suite/director_using.i
@@ -0,0 +1,65 @@
+%module(directors="1",dirprot="1") director_using
+
+%{
+#include <string>
+#include <iostream>
+%}
+
+%include "std_string.i"
+
+%feature("director");
+
+%newobject *::create();
+
+%inline {
+  template <class C>
+    class Foo {
+    public:
+      virtual ~Foo() {}
+      
+      std::string advance() 
+      {
+	return "Foo::advance;" + do_advance();
+      }  
+
+    protected:
+      virtual std::string do_advance() = 0;
+      virtual std::string do_step() const = 0;
+    };
+}
+
+%template(Foo_int) Foo<int>;
+
+%inline {
+
+  class Bar : public Foo<int>
+  {
+  public:
+    
+    std::string step() 
+    {
+      return "Bar::step;" + advance();    
+    }
+
+    
+    using Foo<int>::do_step;
+  protected:
+    std::string do_advance() 
+    {
+      return "Bar::do_advance;" + do_step();
+    }
+    
+  };  
+  
+  template <class C>
+    class FooBar : public Bar
+    {
+    public:
+      virtual C get_value() const = 0;
+      using Bar::do_advance;
+      
+    };
+}
+
+%template(FooBar_int) FooBar<int>;
+
diff --git a/trunk/Examples/test-suite/director_wombat.i b/trunk/Examples/test-suite/director_wombat.i
new file mode 100644
index 0000000..ab798ba
--- /dev/null
+++ b/trunk/Examples/test-suite/director_wombat.i
@@ -0,0 +1,49 @@
+%module(directors="1") director_wombat
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%feature(director) Bar;
+%feature(director) Foo<int>;
+
+%inline %{
+template<typename T> class Foo
+{
+public:
+                        Foo()
+                        { /* NOP */ }
+  virtual              ~Foo()
+                        { /* NOP */ }
+  virtual int           meth(T param)
+                        { return param; }
+};
+
+typedef Foo<int>        Foo_int;
+
+class Bar
+{
+public:
+  virtual              ~Bar();
+  virtual Foo_int      *meth();
+  virtual void          foo_meth_ref(Foo_int &, int);
+  virtual void          foo_meth_ptr(Foo_int *, int);
+  virtual void          foo_meth_val(Foo_int, int);
+  virtual void          foo_meth_cref(const Foo_int &, int);
+  virtual void          foo_meth_cptr(const Foo_int *, int);
+};
+
+Bar::~Bar()
+{ /* NOP */ }
+
+Foo_int *
+Bar::meth()
+{
+  return new Foo_int();
+}
+
+void Bar::foo_meth_ref(Foo_int &arg, int param) { }
+void Bar::foo_meth_ptr(Foo_int *arg, int param) { }
+void Bar::foo_meth_val(Foo_int arg, int param) { }
+void Bar::foo_meth_cref(const Foo_int &arg, int param) { }
+void Bar::foo_meth_cptr(const Foo_int *arg, int param) { }
+%}
+
+%template(Foo_integers) Foo<int>;
diff --git a/trunk/Examples/test-suite/director_wstring.i b/trunk/Examples/test-suite/director_wstring.i
new file mode 100644
index 0000000..17761ea
--- /dev/null
+++ b/trunk/Examples/test-suite/director_wstring.i
@@ -0,0 +1,60 @@
+%module(directors="1") director_wstring;
+%include <stl.i>
+
+#ifndef SWIG_STL_UNIMPL
+
+%include std_vector.i
+%include std_wstring.i
+
+// Using thread unsafe wrapping
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR) A;
+
+%{
+#include <vector>
+#include <string>
+%}
+
+%feature("director") A;
+%inline %{
+
+struct A
+{
+  A(const std::wstring& first)
+    : m_strings(1, first)
+  {}
+  
+  virtual ~A() {}
+  
+  virtual const std::wstring& get_first() const
+  { return get(0); }
+  
+  virtual const std::wstring& get(int n) const
+  { return m_strings[n]; }
+
+  virtual const std::wstring& call_get_first() const
+  { return get_first(); }
+
+  virtual const std::wstring& call_get(int n) const
+  { return get(n); }
+
+  std::vector<std::wstring> m_strings;
+
+
+  virtual void process_text(const wchar_t *text) 
+  {
+  }
+
+  virtual std::wstring multiple_params_val(const std::wstring& p1, const std::wstring& p2, std::wstring p3, std::wstring p4) const
+  { return get_first(); }
+  
+  virtual const std::wstring& multiple_params_ref(const std::wstring& p1, const std::wstring& p2, std::wstring p3, std::wstring p4) const
+  { return get_first(); }
+  
+  void call_process_func() { process_text(L"hello"); }
+ };
+ 
+ %}
+
+%template(StringVector) std::vector<std::wstring>;
+
+#endif
diff --git a/trunk/Examples/test-suite/disown.i b/trunk/Examples/test-suite/disown.i
new file mode 100644
index 0000000..8b3aeb0
--- /dev/null
+++ b/trunk/Examples/test-suite/disown.i
@@ -0,0 +1,47 @@
+%module disown
+
+%{
+#include <iostream>
+%}
+
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_APPLY_UNDEF
+
+%apply SWIGTYPE *DISOWN { A *disown };
+
+%inline {
+  struct A
+  {
+    ~A()
+    {
+      // std::cout <<"delete A" << std::endl;
+    }
+    
+    
+  };
+  
+  class B
+  {
+    A *_a;
+  public:
+    B() : _a(0)
+    {
+    }
+    
+    ~B()
+    {
+      if (_a) {
+	// std::cout <<"delete A from B" << std::endl;	
+	delete _a;
+      }
+      // std::cout <<"delete B" << std::endl;      
+    }
+
+    int acquire(A *disown) 
+    {
+      // std::cout <<"acquire A" << std::endl;      
+      _a = disown;    
+      return 5;      
+    }
+    
+  };
+}
diff --git a/trunk/Examples/test-suite/dynamic_cast.i b/trunk/Examples/test-suite/dynamic_cast.i
new file mode 100644
index 0000000..5d4fbb0
--- /dev/null
+++ b/trunk/Examples/test-suite/dynamic_cast.i
@@ -0,0 +1,76 @@
+/* File : example.i */
+%module dynamic_cast
+
+#if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
+%apply SWIGTYPE *DYNAMIC { Foo * };
+#endif
+
+%inline %{
+
+class Foo {
+public:
+  virtual ~Foo() { }
+  
+  virtual Foo *blah() {
+    return this;
+  }
+};
+%}
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP)
+%typemap(out) Foo *blah {
+    Bar *downcast = dynamic_cast<Bar *>($1);
+    *(Bar **)&$result = downcast;
+}
+#endif
+
+#if defined(SWIGJAVA)
+%typemap(javaout) Foo * {
+    return new Bar($jnicall, $owner);
+  }
+#endif
+
+#if defined(SWIGCSHARP)
+%typemap(csout, excode=SWIGEXCODE) Foo * {
+    Bar ret = new Bar($imcall, $owner);$excode
+    return ret;
+  }
+#endif
+
+%inline %{
+
+class Bar : public Foo {
+public:
+   virtual Foo *blah() {
+       return (Foo *) this;
+   }
+   virtual char * test() {
+       return (char *) "Bar::test";
+   }
+};
+
+char *do_test(Bar *b) {
+   return b->test();
+}
+%}
+
+#if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
+// A general purpose function for dynamic casting of a Foo *
+%{
+static swig_type_info *
+Foo_dynamic(void **ptr) {
+   Bar *b;
+   b = dynamic_cast<Bar *>((Foo *) *ptr);
+   if (b) {
+      *ptr = (void *) b;
+      return SWIGTYPE_p_Bar;
+   }
+   return 0;
+}
+%}
+
+// Register the above casting function
+DYNAMIC_CAST(SWIGTYPE_p_Foo, Foo_dynamic);
+
+#endif
+
diff --git a/trunk/Examples/test-suite/empty.i b/trunk/Examples/test-suite/empty.i
new file mode 100644
index 0000000..a504098
--- /dev/null
+++ b/trunk/Examples/test-suite/empty.i
@@ -0,0 +1 @@
+%module empty
diff --git a/trunk/Examples/test-suite/enum_plus.i b/trunk/Examples/test-suite/enum_plus.i
new file mode 100644
index 0000000..74cc7fa
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_plus.i
@@ -0,0 +1,12 @@
+%module enum_plus
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) iFoo; /* Ruby, wrong constant name */
+
+%inline %{
+struct iFoo 
+{ 
+    enum { 
+       Phoo = +50 
+    }; 
+}; 
+%}
diff --git a/trunk/Examples/test-suite/enum_scope_template.i b/trunk/Examples/test-suite/enum_scope_template.i
new file mode 100644
index 0000000..b6b156b
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_scope_template.i
@@ -0,0 +1,20 @@
+%module enum_scope_template
+
+#ifdef SWIGPHP
+// php internal naming conflict
+%rename (chops) chop;
+#endif
+
+%inline %{
+
+template<class T> class Tree {
+public:
+   enum types {Oak, Fir, Cedar};
+   void chop(enum types type) {}
+};
+enum Tree<int>::types chop(enum Tree<int>::types type) { return type; }
+ 
+%}                                                      
+
+%template(TreeInt) Tree<int>;
+
diff --git a/trunk/Examples/test-suite/enum_template.i b/trunk/Examples/test-suite/enum_template.i
new file mode 100644
index 0000000..953a425
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_template.i
@@ -0,0 +1,43 @@
+%module enum_template
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) eTest0;        /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) eTest1;        /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) eTest2;        /* Ruby, wrong class name */
+
+/*
+From bug report 992329:
+
+In Python I see
+
+>>> import enum_template
+>>> enum_template.MakeETest()
+'_60561408_p_ETest'
+>>> enum_template.TakeETest(0)
+Traceback (most recent call last):
+File "<stdin>", line 1, in ?
+TypeError: Expected a pointer
+
+Without the %template, things work fine: the first
+function call returns an integer, and the second
+succeeds.
+*/
+
+%inline %{
+
+enum ETest
+{
+eTest0,
+eTest1,
+eTest2
+};
+
+void TakeETest(ETest test) {}
+ETest MakeETest(void) {return eTest1;}
+
+template<class T> class CTempl
+{
+};
+
+%}
+
+%template(CTempl_ETest) CTempl<ETest>;
diff --git a/trunk/Examples/test-suite/enum_thorough.i b/trunk/Examples/test-suite/enum_thorough.i
new file mode 100644
index 0000000..31e3e21
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_thorough.i
@@ -0,0 +1,532 @@
+%module "enum_thorough"
+
+// Suppress warning messages from the Ruby module for all of the
+// following...
+
+#pragma SWIG nowarn=SWIGWARN_PARSE_KEYWORD
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME);
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) red;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) blue;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) green;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) SpeedClass::slow;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) SpeedClass::medium;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) SpeedClass::fast;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) SpeedClass::lightning;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) TemplateClass::einstein;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) TemplateClass::galileo;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Name::TClass::faraday;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Name::TClass::bell;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) argh;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) eek;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) OldNameStruct::whizz;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) OldNameStruct::kerboom;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) OldNameStruct::pop;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) OldNameStruct::simple1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) OldNameStruct::singlename1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) OldNameStruct::doublename1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) TreesClass::oak;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) TreesClass::fir;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) TreesClass::pine;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) curly::greasy::HairStruct::blonde;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) curly::greasy::HairStruct::ginger;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Obscure::one;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Obscure::onetrail;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Obscure::two;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Obscure::twoagain;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Obscure::twotrail;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Obscure::twotrailagain;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) globalinstance1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) globalinstance2;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) globalinstance3;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Instances::memberinstance1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Instances::memberinstance2;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Instances::memberinstance3;
+
+%inline %{
+
+enum { AnonEnum1, AnonEnum2 = 100 };
+enum { ReallyAnInteger = 200 };
+//enum { AnonEnum3, AnonEnum4 } instance;
+namespace AnonSpace {
+  enum { AnonSpaceEnum1, AnonSpaceEnum2 = 300 };
+  struct AnonStruct {
+    enum { AnonStructEnum1, AnonStructEnum2 = 400 };
+  };
+}
+
+
+enum colour { red=-1, blue, green = 10 };
+colour colourTest1(colour e) { return e; }
+enum colour colourTest2(enum colour e) { return e; }
+const colour colourTest3(const colour e) { return e; }
+const enum colour colourTest4(const enum colour e) { return e; }
+
+colour myColour;
+
+struct SpeedClass {
+  enum speed { slow=10, medium=20, fast=30, lightning };
+  typedef enum speed speedtd1;
+
+  int                           speedTest0(int s) { return s; }
+  speed                         speedTest1(speed s) { return s; }
+  enum speed                    speedTest2(enum speed s) { return s; }
+  const speed                   speedTest3(const speed s) { return s; }
+  const enum speed              speedTest4(const enum speed s) { return s; }
+  speedtd1                      speedTest5(speedtd1 s) { return s; }
+  const speedtd1                speedTest6(const speedtd1 s) { return s; }
+  const speed &                 speedTest7(const speed &s) { return s; }
+  const enum speed &            speedTest8(const enum speed &s) { return s; }
+
+  const colour myColour2;
+  speedtd1 mySpeedtd1;
+  SpeedClass() : myColour2(red), mySpeedtd1(slow) { }
+private:
+  SpeedClass& operator=(const SpeedClass&);
+};
+
+int                            speedTest0(int s) { return s; }
+SpeedClass::speed              speedTest1(SpeedClass::speed s) { return s; }
+enum SpeedClass::speed         speedTest2(enum SpeedClass::speed s) { return s; }
+const SpeedClass::speed        speedTest3(const SpeedClass::speed s) { return s; }
+const enum SpeedClass::speed   speedTest4(const enum SpeedClass::speed s) { return s; }
+const SpeedClass::speed &      speedTest5(const SpeedClass::speed &s) { return s; }
+
+
+typedef enum { NamedAnon1, NamedAnon2 } namedanon;
+
+namedanon                       namedanonTest1(namedanon e) { return e; } 
+
+typedef enum twonamestag { TwoNames1, TwoNames2, TwoNames3 = 33 } twonames;
+
+twonames                        twonamesTest1(twonames e) { return e; } 
+twonamestag                     twonamesTest2(twonamestag e) { return e; } 
+enum twonamestag                twonamesTest3(enum twonamestag e) { return e; } 
+
+struct TwoNamesStruct {
+  typedef enum twonamestag { TwoNamesStruct1, TwoNamesStruct2 } twonames;
+  twonames                      twonamesTest1(twonames e) { return e; } 
+  twonamestag                   twonamesTest2(twonamestag e) { return e; } 
+  enum twonamestag              twonamesTest3(enum twonamestag e) { return e; } 
+};
+
+namespace AnonSpace{
+  typedef enum { NamedAnonSpace1, NamedAnonSpace2 } namedanonspace;
+  namedanonspace                namedanonspaceTest1(namedanonspace e) { return e; } 
+  AnonSpace::namedanonspace     namedanonspaceTest2(AnonSpace::namedanonspace e) { return e; } 
+}
+AnonSpace::namedanonspace       namedanonspaceTest3(AnonSpace::namedanonspace e) { return e; } 
+using namespace AnonSpace;
+namedanonspace                  namedanonspaceTest4(namedanonspace e) { return e; } 
+
+
+template<typename T> struct TemplateClass {
+  enum scientists { einstein, galileo = 10 }; 
+  typedef enum scientists scientiststd1;
+  typedef scientists scientiststd2;
+  typedef scientiststd1 scientiststd3;
+  scientists                                scientistsTest1(scientists e) { return e; }
+  enum scientists                           scientistsTest2(enum scientists e) { return e; }
+  const scientists                          scientistsTest3(const scientists e) { return e; }
+  const enum scientists                     scientistsTest4(const enum scientists e) { return e; }
+  typename TemplateClass<T>::scientists     scientistsTest5(typename TemplateClass<T>::scientists e) { return e; }
+  const typename TemplateClass<T>::scientists        scientistsTest6(const typename TemplateClass<T>::scientists e) { return e; }
+  enum TemplateClass<T>::scientists         scientistsTest7(enum TemplateClass<T>::scientists e) { return e; }
+  const enum TemplateClass<T>::scientists   scientistsTest8(const enum TemplateClass<T>::scientists e) { return e; }
+  typename TemplateClass::scientists        scientistsTest9(typename TemplateClass::scientists e) { return e; }
+//  enum TemplateClass::scientists            scientistsTestA(enum TemplateClass::scientists e) { return e; }
+  const typename TemplateClass::scientists  scientistsTestB(const typename TemplateClass::scientists e) { return e; }
+//  const enum TemplateClass::scientists      scientistsTestC(const enum TemplateClass::scientists e) { return e; }
+  scientiststd1                             scientistsTestD(scientiststd1 e) { return e; }
+  scientiststd2                             scientistsTestE(scientiststd2 e) { return e; }
+  scientiststd3                             scientistsTestF(scientiststd3 e) { return e; }
+  typename TemplateClass<T>::scientiststd1  scientistsTestG(typename TemplateClass<T>::scientiststd1 e) { return e; }
+  typename TemplateClass<T>::scientiststd2  scientistsTestH(typename TemplateClass<T>::scientiststd2 e) { return e; }
+  typename TemplateClass<T>::scientiststd3  scientistsTestI(typename TemplateClass<T>::scientiststd3 e) { return e; }
+  const scientists &                        scientistsTestJ(const scientists &e) { return e; }
+};
+
+TemplateClass<int>::scientists              scientistsTest1(TemplateClass<int>::scientists e) { return e; }
+const TemplateClass<int>::scientists        scientistsTest2(const TemplateClass<int>::scientists e) { return e; }
+enum TemplateClass<int>::scientists         scientistsTest3(enum TemplateClass<int>::scientists e) { return e; }
+const enum TemplateClass<int>::scientists   scientistsTest4(const enum TemplateClass<int>::scientists e) { return e; }
+TemplateClass<int>::scientiststd1           scientistsTest5(TemplateClass<int>::scientiststd1 e) { return e; }
+TemplateClass<int>::scientiststd2           scientistsTest6(TemplateClass<int>::scientiststd2 e) { return e; }
+TemplateClass<int>::scientiststd3           scientistsTest7(TemplateClass<int>::scientiststd3 e) { return e; }
+const TemplateClass<int>::scientiststd3 &   scientistsTest8(const TemplateClass<int>::scientiststd3 &e) { return e; }
+
+
+namespace Name {
+template<typename T> struct TClass {
+  enum scientists { faraday, bell = 20 }; 
+  typedef enum scientists scientiststd1;
+  typedef scientists scientiststd2;
+  typedef scientiststd1 scientiststd3;
+  scientists                                scientistsNameTest1(scientists e) { return e; }
+  enum scientists                           scientistsNameTest2(enum scientists e) { return e; }
+  const scientists                          scientistsNameTest3(const scientists e) { return e; }
+  const enum scientists                     scientistsNameTest4(const enum scientists e) { return e; }
+  typename TClass<T>::scientists            scientistsNameTest5(typename TClass<T>::scientists e) { return e; }
+  const typename TClass<T>::scientists      scientistsNameTest6(const typename TClass<T>::scientists e) { return e; }
+  enum TClass<T>::scientists                scientistsNameTest7(enum TClass<T>::scientists e) { return e; }
+  const enum TClass<T>::scientists          scientistsNameTest8(const enum TClass<T>::scientists e) { return e; }
+  typename TClass::scientists               scientistsNameTest9(typename TClass::scientists e) { return e; }
+//  enum TClass::scientists                   scientistsNameTestA(enum TClass::scientists e) { return e; }
+  const typename TClass::scientists         scientistsNameTestB(const typename TClass::scientists e) { return e; }
+//  const enum TClass::scientists             scientistsNameTestC(const enum TClass::scientists e) { return e; }
+  scientiststd1                             scientistsNameTestD(scientiststd1 e) { return e; }
+  scientiststd2                             scientistsNameTestE(scientiststd2 e) { return e; }
+  scientiststd3                             scientistsNameTestF(scientiststd3 e) { return e; }
+  typename TClass<T>::scientiststd1         scientistsNameTestG(typename TClass<T>::scientiststd1 e) { return e; }
+  typename TClass<T>::scientiststd2         scientistsNameTestH(typename TClass<T>::scientiststd2 e) { return e; }
+  typename TClass<T>::scientiststd3         scientistsNameTestI(typename TClass<T>::scientiststd3 e) { return e; }
+
+  typename Name::TClass<T>::scientists      scientistsNameSpaceTest1(typename Name::TClass<T>::scientists e) { return e; }
+  const typename Name::TClass<T>::scientists         scientistsNameSpaceTest2(const typename Name::TClass<T>::scientists e) { return e; }
+  enum Name::TClass<T>::scientists          scientistsNameSpaceTest3(enum Name::TClass<T>::scientists e) { return e; }
+  const enum Name::TClass<T>::scientists    scientistsNameSpaceTest4(const enum Name::TClass<T>::scientists e) { return e; }
+  typename Name::TClass<T>::scientiststd1   scientistsNameSpaceTest5(typename Name::TClass<T>::scientiststd1 e) { return e; }
+  typename Name::TClass<T>::scientiststd2   scientistsNameSpaceTest6(typename Name::TClass<T>::scientiststd2 e) { return e; }
+  typename Name::TClass<T>::scientiststd3   scientistsNameSpaceTest7(typename Name::TClass<T>::scientiststd3 e) { return e; }
+
+  // Test TemplateClass::scientists rather then TClass::scientists
+  ::TemplateClass<int>::scientists              scientistsOtherTest1(::TemplateClass<int>::scientists e) { return e; }
+  const ::TemplateClass<int>::scientists        scientistsOtherTest2(const ::TemplateClass<int>::scientists e) { return e; }
+  enum ::TemplateClass<int>::scientists         scientistsOtherTest3(enum ::TemplateClass<int>::scientists e) { return e; }
+  const enum ::TemplateClass<int>::scientists   scientistsOtherTest4(const enum ::TemplateClass<int>::scientists e) { return e; }
+  ::TemplateClass<int>::scientiststd1           scientistsOtherTest5(::TemplateClass<int>::scientiststd1 e) { return e; }
+  ::TemplateClass<int>::scientiststd2           scientistsOtherTest6(::TemplateClass<int>::scientiststd2 e) { return e; }
+  ::TemplateClass<int>::scientiststd3           scientistsOtherTest7(::TemplateClass<int>::scientiststd3 e) { return e; }
+};
+
+TClass<int>::scientists                     scientistsNameTest1(TClass<int>::scientists e) { return e; }
+const TClass<int>::scientists               scientistsNameTest2(const TClass<int>::scientists e) { return e; }
+enum TClass<int>::scientists                scientistsNameTest3(enum TClass<int>::scientists e) { return e; }
+const enum TClass<int>::scientists          scientistsNameTest4(const enum TClass<int>::scientists e) { return e; }
+TClass<int>::scientiststd1                  scientistsNameTest5(TClass<int>::scientiststd1 e) { return e; }
+TClass<int>::scientiststd2                  scientistsNameTest6(TClass<int>::scientiststd2 e) { return e; }
+TClass<int>::scientiststd3                  scientistsNameTest7(TClass<int>::scientiststd3 e) { return e; }
+
+Name::TClass<int>::scientists               scientistsNameSpaceTest1(Name::TClass<int>::scientists e) { return e; }
+const Name::TClass<int>::scientists         scientistsNameSpaceTest2(const Name::TClass<int>::scientists e) { return e; }
+enum Name::TClass<int>::scientists          scientistsNameSpaceTest3(enum Name::TClass<int>::scientists e) { return e; }
+const enum Name::TClass<int>::scientists    scientistsNameSpaceTest4(const enum Name::TClass<int>::scientists e) { return e; }
+Name::TClass<int>::scientiststd1            scientistsNameSpaceTest5(Name::TClass<int>::scientiststd1 e) { return e; }
+Name::TClass<int>::scientiststd2            scientistsNameSpaceTest6(Name::TClass<int>::scientiststd2 e) { return e; }
+Name::TClass<int>::scientiststd3            scientistsNameSpaceTest7(Name::TClass<int>::scientiststd3 e) { return e; }
+}
+
+Name::TClass<int>::scientists               scientistsNameSpaceTest8(Name::TClass<int>::scientists e) { return e; }
+const Name::TClass<int>::scientists         scientistsNameSpaceTest9(const Name::TClass<int>::scientists e) { return e; }
+enum Name::TClass<int>::scientists          scientistsNameSpaceTestA(enum Name::TClass<int>::scientists e) { return e; }
+const enum Name::TClass<int>::scientists    scientistsNameSpaceTestB(const enum Name::TClass<int>::scientists e) { return e; }
+Name::TClass<int>::scientiststd1            scientistsNameSpaceTestC(Name::TClass<int>::scientiststd1 e) { return e; }
+Name::TClass<int>::scientiststd2            scientistsNameSpaceTestD(Name::TClass<int>::scientiststd2 e) { return e; }
+Name::TClass<int>::scientiststd3            scientistsNameSpaceTestE(Name::TClass<int>::scientiststd3 e) { return e; }
+
+using namespace Name;
+TClass<int>::scientists                     scientistsNameSpaceTestF(TClass<int>::scientists e) { return e; }
+const TClass<int>::scientists               scientistsNameSpaceTestG(const TClass<int>::scientists e) { return e; }
+enum TClass<int>::scientists                scientistsNameSpaceTestH(enum TClass<int>::scientists e) { return e; }
+const enum TClass<int>::scientists          scientistsNameSpaceTestI(const enum TClass<int>::scientists e) { return e; }
+TClass<int>::scientiststd1                  scientistsNameSpaceTestJ(TClass<int>::scientiststd1 e) { return e; }
+TClass<int>::scientiststd2                  scientistsNameSpaceTestK(TClass<int>::scientiststd2 e) { return e; }
+TClass<int>::scientiststd3                  scientistsNameSpaceTestL(TClass<int>::scientiststd3 e) { return e; }
+
+%}
+
+%template(TemplateClassInt) TemplateClass<int>;
+%template(TClassInt) Name::TClass<int>;
+
+
+// %rename tests
+%rename(NewNameStruct) OldNameStruct;
+%rename(newname) old_name;
+%rename(doublenamerenamed) doublename;
+%rename(simplerenamed) simple;
+%rename(singlenamerenamed) singlename;
+%rename(bang) OldNameStruct::kerboom;
+
+%inline %{
+enum old_name { argh, eek = -1 };
+typedef old_name old_nametd;
+old_name                            renameTest1(old_name e) { return e; }
+old_nametd                          renameTest2(old_nametd e) { return e; }
+
+struct OldNameStruct {
+  enum enumeration {whizz, kerboom, pop};
+  enumeration                       renameTest1(enumeration e) { return e; }
+  OldNameStruct::enumeration        renameTest2(OldNameStruct::enumeration e) { return e; }
+
+  enum simple {simple1};
+  typedef enum doublenametag {doublename1} doublename;
+  typedef enum {singlename1} singlename;
+
+  simple                            renameTest3(simple e) { return e; }
+  doublename                        renameTest4(doublename e) { return e; }
+  doublenametag                     renameTest5(doublenametag e) { return e; }
+  singlename                        renameTest6(singlename e) { return e; }
+};
+
+OldNameStruct::enumeration          renameTest3(OldNameStruct::enumeration e) { return e; }
+OldNameStruct::simple               renameTest4(OldNameStruct::simple e) { return e; }
+OldNameStruct::doublename           renameTest5(OldNameStruct::doublename e) { return e; }
+OldNameStruct::doublenametag        renameTest6(OldNameStruct::doublenametag e) { return e; }
+OldNameStruct::singlename           renameTest7(OldNameStruct::singlename e) { return e; }
+%}
+
+%inline %{
+struct TreesClass {
+  enum trees {oak, fir, pine };
+  typedef enum trees treestd1;
+  typedef trees treestd2;
+  typedef treestd1 treestd3;
+  typedef TreesClass::trees treestd4;
+  typedef treestd1 treestd5;
+
+  trees                             treesTest1(trees e) { return e; }
+  treestd1                          treesTest2(treestd1 e) { return e; }
+  treestd2                          treesTest3(treestd2 e) { return e; }
+  treestd3                          treesTest4(treestd3 e) { return e; }
+  treestd4                          treesTest5(treestd4 e) { return e; }
+  treestd5                          treesTest6(treestd5 e) { return e; }
+  const trees                       treesTest7(const trees e) { return e; }
+  const treestd1                    treesTest8(const treestd1 e) { return e; }
+  const treestd2                    treesTest9(const treestd2 e) { return e; }
+  const treestd3                    treesTestA(const treestd3 e) { return e; }
+  const treestd4                    treesTestB(const treestd4 e) { return e; }
+  const treestd5                    treesTestC(const treestd5 e) { return e; }
+  TreesClass::trees                 treesTestD(TreesClass::trees e) { return e; }
+  TreesClass::treestd1              treesTestE(TreesClass::treestd1 e) { return e; }
+  TreesClass::treestd2              treesTestF(TreesClass::treestd2 e) { return e; }
+  TreesClass::treestd3              treesTestG(TreesClass::treestd3 e) { return e; }
+  TreesClass::treestd4              treesTestH(TreesClass::treestd4 e) { return e; }
+  TreesClass::treestd5              treesTestI(TreesClass::treestd5 e) { return e; }
+  const TreesClass::trees           treesTestJ(const TreesClass::trees e) { return e; }
+  const TreesClass::treestd1        treesTestK(const TreesClass::treestd1 e) { return e; }
+  const TreesClass::treestd2        treesTestL(const TreesClass::treestd2 e) { return e; }
+  const TreesClass::treestd3        treesTestM(const TreesClass::treestd3 e) { return e; }
+  const TreesClass::treestd4        treesTestN(const TreesClass::treestd4 e) { return e; }
+  const TreesClass::treestd5        treesTestO(const TreesClass::treestd5 e) { return e; }
+};
+
+TreesClass::trees                   treesTest1(TreesClass::trees e) { return e; }
+TreesClass::treestd1                treesTest2(TreesClass::treestd1 e) { return e; }
+TreesClass::treestd2                treesTest3(TreesClass::treestd2 e) { return e; }
+TreesClass::treestd3                treesTest4(TreesClass::treestd3 e) { return e; }
+TreesClass::treestd4                treesTest5(TreesClass::treestd4 e) { return e; }
+TreesClass::treestd5                treesTest6(TreesClass::treestd5 e) { return e; }
+const TreesClass::trees             treesTest7(const TreesClass::trees e) { return e; }
+const TreesClass::treestd1          treesTest8(const TreesClass::treestd1 e) { return e; }
+const TreesClass::treestd2          treesTest9(const TreesClass::treestd2 e) { return e; }
+const TreesClass::treestd3          treesTestA(const TreesClass::treestd3 e) { return e; }
+const TreesClass::treestd4          treesTestB(const TreesClass::treestd4 e) { return e; }
+const TreesClass::treestd5          treesTestC(const TreesClass::treestd5 e) { return e; }
+
+typedef enum TreesClass::trees treesglobaltd1;
+typedef TreesClass::trees treesglobaltd2;
+typedef TreesClass::treestd1 treesglobaltd3;
+typedef TreesClass::treestd2 treesglobaltd4;
+typedef treesglobaltd4 treesglobaltd5;
+
+treesglobaltd1                      treesTestD(treesglobaltd1 e) { return e; }
+treesglobaltd2                      treesTestE(treesglobaltd2 e) { return e; }
+treesglobaltd3                      treesTestF(treesglobaltd3 e) { return e; }
+treesglobaltd4                      treesTestG(treesglobaltd4 e) { return e; }
+treesglobaltd5                      treesTestH(treesglobaltd5 e) { return e; }
+const treesglobaltd1                treesTestI(const treesglobaltd1 e) { return e; }
+const treesglobaltd2                treesTestJ(const treesglobaltd2 e) { return e; }
+const treesglobaltd3                treesTestK(const treesglobaltd3 e) { return e; }
+const treesglobaltd4                treesTestL(const treesglobaltd4 e) { return e; }
+const treesglobaltd5                treesTestM(const treesglobaltd5 e) { return e; }
+
+typedef const enum TreesClass::trees treesglobaltd6;
+typedef const TreesClass::trees treesglobaltd7;
+typedef const TreesClass::treestd1 treesglobaltd8;
+typedef const TreesClass::treestd2 treesglobaltd9;
+typedef const treesglobaltd4 treesglobaltdA;
+
+//treesglobaltd6                      treesTestN(treesglobaltd6 e) { return e; } // casting using an int instead of treesglobaltd6
+treesglobaltd7                      treesTestO(treesglobaltd7 e) { return e; }
+treesglobaltd8                      treesTestP(treesglobaltd8 e) { return e; }
+treesglobaltd9                      treesTestQ(treesglobaltd9 e) { return e; }
+treesglobaltdA                      treesTestR(treesglobaltdA e) { return e; }
+
+namespace curly {
+  namespace greasy {
+    struct HairStruct {
+      enum hair { blonde=0xFF0, ginger };
+      typedef hair hairtd1;
+      typedef HairStruct::hair hairtd2;
+      typedef greasy::HairStruct::hair hairtd3;
+      typedef curly::greasy::HairStruct::hair hairtd4;
+      typedef ::curly::greasy::HairStruct::hair hairtd5;
+      typedef hairtd1 hairtd6;
+      typedef HairStruct::hairtd1 hairtd7;
+      typedef greasy::HairStruct::hairtd1 hairtd8;
+      typedef curly::greasy::HairStruct::hairtd1 hairtd9;
+      typedef ::curly::greasy::HairStruct::hairtd1 hairtdA;
+      hair                          hairTest1(hair e) { return e; }
+      hairtd1                       hairTest2(hairtd1 e) { return e; }
+      hairtd2                       hairTest3(hairtd2 e) { return e; }
+      hairtd3                       hairTest4(hairtd3 e) { return e; }
+      hairtd4                       hairTest5(hairtd4 e) { return e; }
+      hairtd5                       hairTest6(hairtd5 e) { return e; }
+      hairtd6                       hairTest7(hairtd6 e) { return e; }
+      hairtd7                       hairTest8(hairtd7 e) { return e; }
+      hairtd8                       hairTest9(hairtd8 e) { return e; }
+      hairtd9                       hairTestA(hairtd9 e) { return e; }
+      hairtdA                       hairTestB(hairtdA e) { return e; }
+
+      ::colour                      colourTest1(::colour e) { return e; }
+      enum colour                   colourTest2(enum colour e) { return e; }
+      namedanon                     namedanonTest1(namedanon e) { return e; }
+      AnonSpace::namedanonspace      namedanonspaceTest1(AnonSpace::namedanonspace e) { return e; }
+
+      treesglobaltd1                treesGlobalTest1(treesglobaltd1 e) { return e; }
+      treesglobaltd2                treesGlobalTest2(treesglobaltd2 e) { return e; }
+      treesglobaltd3                treesGlobalTest3(treesglobaltd3 e) { return e; }
+      treesglobaltd4                treesGlobalTest4(treesglobaltd4 e) { return e; }
+      treesglobaltd5                treesGlobalTest5(treesglobaltd5 e) { return e; }
+
+    };
+    HairStruct::hair                hairTest1(HairStruct::hair e) { return e; }
+    HairStruct::hairtd1             hairTest2(HairStruct::hairtd1 e) { return e; }
+    HairStruct::hairtd2             hairTest3(HairStruct::hairtd2 e) { return e; }
+    HairStruct::hairtd3             hairTest4(HairStruct::hairtd3 e) { return e; }
+    HairStruct::hairtd4             hairTest5(HairStruct::hairtd4 e) { return e; }
+    HairStruct::hairtd5             hairTest6(HairStruct::hairtd5 e) { return e; }
+    HairStruct::hairtd6             hairTest7(HairStruct::hairtd6 e) { return e; }
+    HairStruct::hairtd7             hairTest8(HairStruct::hairtd7 e) { return e; }
+    HairStruct::hairtd8             hairTest9(HairStruct::hairtd8 e) { return e; }
+    HairStruct::hairtd9             hairTestA(HairStruct::hairtd9 e) { return e; }
+    HairStruct::hairtdA             hairTestB(HairStruct::hairtdA e) { return e; }
+    const HairStruct::hair &        hairTestC(const HairStruct::hair &e) { return e; }
+  }
+  greasy::HairStruct::hair          hairTestA1(greasy::HairStruct::hair e) { return e; }
+  greasy::HairStruct::hairtd1       hairTestA2(greasy::HairStruct::hairtd1 e) { return e; }
+  greasy::HairStruct::hairtd2       hairTestA3(greasy::HairStruct::hairtd2 e) { return e; }
+  greasy::HairStruct::hairtd3       hairTestA4(greasy::HairStruct::hairtd3 e) { return e; }
+  greasy::HairStruct::hairtd4       hairTestA5(greasy::HairStruct::hairtd4 e) { return e; }
+  greasy::HairStruct::hairtd5       hairTestA6(greasy::HairStruct::hairtd5 e) { return e; }
+  greasy::HairStruct::hairtd6       hairTestA7(greasy::HairStruct::hairtd6 e) { return e; }
+  greasy::HairStruct::hairtd7       hairTestA8(greasy::HairStruct::hairtd7 e) { return e; }
+  greasy::HairStruct::hairtd8       hairTestA9(greasy::HairStruct::hairtd8 e) { return e; }
+  greasy::HairStruct::hairtd9       hairTestAA(greasy::HairStruct::hairtd9 e) { return e; }
+  greasy::HairStruct::hairtdA       hairTestAB(greasy::HairStruct::hairtdA e) { return e; }
+  const greasy::HairStruct::hairtdA &     hairTestAC(const greasy::HairStruct::hairtdA &e) { return e; }
+}
+curly::greasy::HairStruct::hair     hairTestB1(curly::greasy::HairStruct::hair e) { return e; }
+curly::greasy::HairStruct::hairtd1  hairTestB2(curly::greasy::HairStruct::hairtd1 e) { return e; }
+curly::greasy::HairStruct::hairtd2  hairTestB3(curly::greasy::HairStruct::hairtd2 e) { return e; }
+curly::greasy::HairStruct::hairtd3  hairTestB4(curly::greasy::HairStruct::hairtd3 e) { return e; }
+curly::greasy::HairStruct::hairtd4  hairTestB5(curly::greasy::HairStruct::hairtd4 e) { return e; }
+curly::greasy::HairStruct::hairtd5  hairTestB6(curly::greasy::HairStruct::hairtd5 e) { return e; }
+curly::greasy::HairStruct::hairtd6  hairTestB7(curly::greasy::HairStruct::hairtd6 e) { return e; }
+curly::greasy::HairStruct::hairtd7  hairTestB8(curly::greasy::HairStruct::hairtd7 e) { return e; }
+curly::greasy::HairStruct::hairtd8  hairTestB9(curly::greasy::HairStruct::hairtd8 e) { return e; }
+curly::greasy::HairStruct::hairtd9  hairTestBA(curly::greasy::HairStruct::hairtd9 e) { return e; }
+curly::greasy::HairStruct::hairtdA  hairTestBB(curly::greasy::HairStruct::hairtdA e) { return e; }
+const curly::greasy::HairStruct::hairtdA & hairTestBC(const curly::greasy::HairStruct::hairtdA &e) { return e; }
+
+using curly::greasy::HairStruct;
+HairStruct::hair                    hairTestC1(HairStruct::hair e) { return e; }
+HairStruct::hairtd1                 hairTestC2(HairStruct::hairtd1 e) { return e; }
+HairStruct::hairtd2                 hairTestC3(HairStruct::hairtd2 e) { return e; }
+HairStruct::hairtd3                 hairTestC4(HairStruct::hairtd3 e) { return e; }
+HairStruct::hairtd4                 hairTestC5(HairStruct::hairtd4 e) { return e; }
+HairStruct::hairtd5                 hairTestC6(HairStruct::hairtd5 e) { return e; }
+HairStruct::hairtd6                 hairTestC7(HairStruct::hairtd6 e) { return e; }
+HairStruct::hairtd7                 hairTestC8(HairStruct::hairtd7 e) { return e; }
+HairStruct::hairtd8                 hairTestC9(HairStruct::hairtd8 e) { return e; }
+HairStruct::hairtd9                 hairTestCA(HairStruct::hairtd9 e) { return e; }
+HairStruct::hairtdA                 hairTestCB(HairStruct::hairtdA e) { return e; }
+const HairStruct::hairtdA &         hairTestCC(const HairStruct::hairtdA &e) { return e; }
+
+namespace curly {
+  namespace greasy {
+    struct FirStruct : HairStruct {
+      hair                          hairTestFir1(hair e) { return e; }
+      hairtd1                       hairTestFir2(hairtd1 e) { return e; }
+      hairtd2                       hairTestFir3(hairtd2 e) { return e; }
+      hairtd3                       hairTestFir4(hairtd3 e) { return e; }
+      hairtd4                       hairTestFir5(hairtd4 e) { return e; }
+      hairtd5                       hairTestFir6(hairtd5 e) { return e; }
+      hairtd6                       hairTestFir7(hairtd6 e) { return e; }
+      hairtd7                       hairTestFir8(hairtd7 e) { return e; }
+      hairtd8                       hairTestFir9(hairtd8 e) { return e; }
+      hairtd9                       hairTestFirA(hairtd9 e) { return e; }
+      hairtdA                       hairTestFirB(hairtdA e) { return e; }
+    };
+  }
+}
+
+struct Obscure {
+  enum Zero {};
+  enum One {one};
+  enum Two {two, twoagain};
+#if defined(SWIG)
+  // g++-4.3 warns about this
+  typedef enum Empty {};
+#endif
+  typedef enum {} AlsoEmpty;
+};
+
+// Unnamed enum instance
+extern "C" {
+enum { globalinstance1, globalinstance2, globalinstance3 = 30 } GlobalInstance;
+}
+
+struct Instances {
+  enum { memberinstance1, memberinstance2, memberinstance3 = 300 } MemberInstance;
+  Instances() : MemberInstance(memberinstance3) {}
+};
+
+%}
+
+// Repeated values
+#if defined(SWIGJAVA)
+%javaconst(1);
+#elif defined(SWIGCSHARP)
+%csconst(1);
+#endif
+
+#if defined(SWIGPERL)
+%inline %{
+
+namespace RepeatSpace {
+typedef enum
+{
+   one = 1,
+   initial = one,
+   two,
+   three,
+   llast = three,
+   end = llast
+} repeat;
+repeat repeatTest(repeat e) { return e; }
+}
+
+%}
+
+#else
+%inline %{
+
+namespace RepeatSpace {
+typedef enum
+{
+   one = 1,
+   initial = one,
+   two,
+   three,
+   last = three,
+   end = last
+} repeat;
+repeat repeatTest(repeat e) { return e; }
+}
+
+%}
+
+
+#endif
+
diff --git a/trunk/Examples/test-suite/enum_thorough_proper.i b/trunk/Examples/test-suite/enum_thorough_proper.i
new file mode 100644
index 0000000..dcddd25
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_thorough_proper.i
@@ -0,0 +1,7 @@
+%module "enum_thorough_proper"
+
+// Test enum wrapping using the proper enums in the target language
+%include "enums.swg"
+
+%include "enum_thorough.i"
+
diff --git a/trunk/Examples/test-suite/enum_thorough_simple.i b/trunk/Examples/test-suite/enum_thorough_simple.i
new file mode 100644
index 0000000..2e1f84c
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_thorough_simple.i
@@ -0,0 +1,7 @@
+%module "enum_thorough_simple"
+
+// Test enum wrapping using simple constants (SWIG-1.3.21 and earlier default enum wrapping for C# and Java)
+%include "enumsimple.swg"
+
+%include "enum_thorough.i"
+
diff --git a/trunk/Examples/test-suite/enum_thorough_typesafe.i b/trunk/Examples/test-suite/enum_thorough_typesafe.i
new file mode 100644
index 0000000..8bae5b0
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_thorough_typesafe.i
@@ -0,0 +1,7 @@
+%module "enum_thorough_typesafe"
+
+// Test enum wrapping using the typesafe enum pattern in the target language
+%include "enumtypesafe.swg"
+
+%include "enum_thorough.i"
+
diff --git a/trunk/Examples/test-suite/enum_thorough_typeunsafe.i b/trunk/Examples/test-suite/enum_thorough_typeunsafe.i
new file mode 100644
index 0000000..1e41250
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_thorough_typeunsafe.i
@@ -0,0 +1,7 @@
+%module "enum_thorough_typeunsafe"
+
+// Test enum wrapping using a type unsafe enum pattern (constant integers in a class for the enum type)
+%include "enumtypeunsafe.swg"
+
+%include "enum_thorough.i"
+
diff --git a/trunk/Examples/test-suite/enum_var.i b/trunk/Examples/test-suite/enum_var.i
new file mode 100644
index 0000000..c8626d8
--- /dev/null
+++ b/trunk/Examples/test-suite/enum_var.i
@@ -0,0 +1,8 @@
+%module enum_var
+
+%inline %{
+
+enum Fruit { APPLE, PEAR };
+Fruit test;
+
+%}
diff --git a/trunk/Examples/test-suite/enums.i b/trunk/Examples/test-suite/enums.i
new file mode 100644
index 0000000..3ea48b9
--- /dev/null
+++ b/trunk/Examples/test-suite/enums.i
@@ -0,0 +1,75 @@
+/* Test whether varios enums in C. */
+
+%module "enums"
+
+/* Suppress warning messages from the Ruby module for all of the following.. */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) boo;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hoo;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) globalinstance1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) globalinstance2;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) globalinstance3;
+
+%inline %{
+
+typedef enum { 
+    CSP_ITERATION_FWD,
+    CSP_ITERATION_BWD = 11
+} foo1;
+
+typedef enum foo2 {
+    ABCDE = 0,
+    FGHJI = 1
+} foo3;
+
+void
+bar1(foo1 x) {}
+
+void
+bar2(enum foo2 x) {}
+
+void 
+bar3(foo3 x) {}
+
+enum sad { boo, hoo = 5 };
+
+/* Unnamed enum instance */
+enum { globalinstance1, globalinstance2, globalinstance3 = 30 } GlobalInstance;
+
+/* Anonymous enum */
+enum { AnonEnum1, AnonEnum2 = 100 };
+
+%}
+
+%inline %{
+
+typedef struct _Foo {
+  enum { BAR1, BAR2 } e;
+} Foo;
+
+%}
+
+  
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) _iFoo;
+
+#ifndef __cplusplus
+%inline %{
+typedef struct _iFoo 
+{ 
+    enum { 
+      Phoo = +50,
+      Char = 'a'
+    } e; 
+} iFoo; 
+%}
+#else
+%inline %{
+struct iFoo 
+{ 
+    enum { 
+      Phoo = +50,
+      Char = 'a'
+    }; 
+}; 
+%}
+
+#endif
diff --git a/trunk/Examples/test-suite/errors/c_bad_name.i b/trunk/Examples/test-suite/errors/c_bad_name.i
new file mode 100644
index 0000000..43ccb4d
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_bad_name.i
@@ -0,0 +1,4 @@
+%module xxx
+
+%name() int foo;
+
diff --git a/trunk/Examples/test-suite/errors/c_bad_native.i b/trunk/Examples/test-suite/errors/c_bad_native.i
new file mode 100644
index 0000000..4d09e04
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_bad_native.i
@@ -0,0 +1,5 @@
+%module xxx
+
+%native(foo) int foo;
+
+
diff --git a/trunk/Examples/test-suite/errors/c_class.i b/trunk/Examples/test-suite/errors/c_class.i
new file mode 100644
index 0000000..cd168f6
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_class.i
@@ -0,0 +1,8 @@
+%module xxx
+
+int class(int x);
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/c_default_error.i b/trunk/Examples/test-suite/errors/c_default_error.i
new file mode 100644
index 0000000..f6220e1
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_default_error.i
@@ -0,0 +1,4 @@
+%module xxx
+
+int foo(int x = 42 || 3);
+
diff --git a/trunk/Examples/test-suite/errors/c_deprecated.i b/trunk/Examples/test-suite/errors/c_deprecated.i
new file mode 100644
index 0000000..27e7439
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_deprecated.i
@@ -0,0 +1,8 @@
+%module xxx
+
+int foo(%val int *x, %out int *y);
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/c_empty_char.i b/trunk/Examples/test-suite/errors/c_empty_char.i
new file mode 100644
index 0000000..0a669af
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_empty_char.i
@@ -0,0 +1,4 @@
+%module xxx
+
+int foo(int x = '');
+
diff --git a/trunk/Examples/test-suite/errors/c_enum_badvalue.i b/trunk/Examples/test-suite/errors/c_enum_badvalue.i
new file mode 100644
index 0000000..8649c03
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_enum_badvalue.i
@@ -0,0 +1,7 @@
+%module xxx
+
+enum stuff {
+   FOO = 'x',
+   BAR = 3.14159
+};
+
diff --git a/trunk/Examples/test-suite/errors/c_extra_rblock.i b/trunk/Examples/test-suite/errors/c_extra_rblock.i
new file mode 100644
index 0000000..3e8e86a
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_extra_rblock.i
@@ -0,0 +1,8 @@
+%module xxx
+
+int foo(int x);
+
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/errors/c_extra_rbrace.i b/trunk/Examples/test-suite/errors/c_extra_rbrace.i
new file mode 100644
index 0000000..0228f9b
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_extra_rbrace.i
@@ -0,0 +1,7 @@
+%module xxx
+
+int foo(int);
+
+}
+
+
diff --git a/trunk/Examples/test-suite/errors/c_extra_unsigned.i b/trunk/Examples/test-suite/errors/c_extra_unsigned.i
new file mode 100644
index 0000000..f5728cf
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_extra_unsigned.i
@@ -0,0 +1,6 @@
+%module xxx
+
+int foo(unsigned unsigned int x);
+int bar(signed signed y);
+int spam(unsigned signed int x);
+
diff --git a/trunk/Examples/test-suite/errors/c_insert_missing.i b/trunk/Examples/test-suite/errors/c_insert_missing.i
new file mode 100644
index 0000000..35755cc
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_insert_missing.i
@@ -0,0 +1,3 @@
+%module xxx
+
+%insert("header") "missing_file.i";
diff --git a/trunk/Examples/test-suite/errors/c_long_short.i b/trunk/Examples/test-suite/errors/c_long_short.i
new file mode 100644
index 0000000..f05831a
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_long_short.i
@@ -0,0 +1,6 @@
+%module xxx
+
+int foo(long short x);
+int bar(short long y);
+int spam(long long long x);
+int grok(short short int x);
diff --git a/trunk/Examples/test-suite/errors/c_missing_rbrace.i b/trunk/Examples/test-suite/errors/c_missing_rbrace.i
new file mode 100644
index 0000000..381d500
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_missing_rbrace.i
@@ -0,0 +1,10 @@
+%module xxx
+
+int foo(int x) {
+   int y;
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/c_missing_semi.i b/trunk/Examples/test-suite/errors/c_missing_semi.i
new file mode 100644
index 0000000..fc20e1d
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_missing_semi.i
@@ -0,0 +1,4 @@
+%module xxx
+int foo(int)
+int bar(int,int);
+
diff --git a/trunk/Examples/test-suite/errors/c_redefine.i b/trunk/Examples/test-suite/errors/c_redefine.i
new file mode 100644
index 0000000..818d707
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_redefine.i
@@ -0,0 +1,20 @@
+%module xxx
+
+int foo(int x, int y);
+int foo;
+
+int bar(int x);
+
+struct bar {
+  int y;
+};
+
+%rename(bar) spam;
+
+int spam(int);
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/c_varargs.i b/trunk/Examples/test-suite/errors/c_varargs.i
new file mode 100644
index 0000000..88f9c2e
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_varargs.i
@@ -0,0 +1,3 @@
+%module xxx
+
+int foo(int x, ...);
diff --git a/trunk/Examples/test-suite/errors/c_varargs_neg.i b/trunk/Examples/test-suite/errors/c_varargs_neg.i
new file mode 100644
index 0000000..a88d8b7
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/c_varargs_neg.i
@@ -0,0 +1,7 @@
+%module xxx
+
+%varargs(0,int x = 0) foo;
+int foo(int x, ...);
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_bad_extern.i b/trunk/Examples/test-suite/errors/cpp_bad_extern.i
new file mode 100644
index 0000000..b6895a5
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_bad_extern.i
@@ -0,0 +1,7 @@
+%module xxx
+
+extern "INTERCAL" {
+   int foo(int);
+};
+
+extern "INTERCAL" int blah(int);
diff --git a/trunk/Examples/test-suite/errors/cpp_extend_redefine.i b/trunk/Examples/test-suite/errors/cpp_extend_redefine.i
new file mode 100644
index 0000000..dfe8fe4
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_extend_redefine.i
@@ -0,0 +1,23 @@
+%module xxx
+
+%extend foo {
+    int bar() {
+    }
+};
+
+struct foo {
+    int bar();
+    int spam();
+};
+
+%extend foo {
+    int spam();
+};
+
+
+   
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_extend_undefined.i b/trunk/Examples/test-suite/errors/cpp_extend_undefined.i
new file mode 100644
index 0000000..808a748
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_extend_undefined.i
@@ -0,0 +1,6 @@
+%module xxx
+
+%extend foo {
+    int bar() {
+    }
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_inline_namespace.i b/trunk/Examples/test-suite/errors/cpp_inline_namespace.i
new file mode 100644
index 0000000..d92746a
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_inline_namespace.i
@@ -0,0 +1,7 @@
+%module xxx
+
+namespace foo {
+%inline %{
+int bar(int x) { }
+%}
+}
diff --git a/trunk/Examples/test-suite/errors/cpp_missing_rtemplate.i b/trunk/Examples/test-suite/errors/cpp_missing_rtemplate.i
new file mode 100644
index 0000000..2d87eec
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_missing_rtemplate.i
@@ -0,0 +1,11 @@
+%module xxx
+
+
+int foo(vector<int);
+
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_namespace_alias.i b/trunk/Examples/test-suite/errors/cpp_namespace_alias.i
new file mode 100644
index 0000000..1e45972
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_namespace_alias.i
@@ -0,0 +1,14 @@
+%module xxx
+
+namespace blah {
+}
+
+namespace B = blah;
+
+namespace B {
+}
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_namespace_aliasnot.i b/trunk/Examples/test-suite/errors/cpp_namespace_aliasnot.i
new file mode 100644
index 0000000..c52f8c1
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_namespace_aliasnot.i
@@ -0,0 +1,4 @@
+%module xxx
+
+int blah;
+namespace B = blah;
diff --git a/trunk/Examples/test-suite/errors/cpp_namespace_aliasundef.i b/trunk/Examples/test-suite/errors/cpp_namespace_aliasundef.i
new file mode 100644
index 0000000..25b5b7f
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_namespace_aliasundef.i
@@ -0,0 +1,3 @@
+%module xxx
+
+namespace B = blah;
diff --git a/trunk/Examples/test-suite/errors/cpp_nested.i b/trunk/Examples/test-suite/errors/cpp_nested.i
new file mode 100644
index 0000000..625812e
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_nested.i
@@ -0,0 +1,13 @@
+%module xxx
+
+class Foo {
+public:
+    class Bar {
+    };
+};
+
+class Spam {
+public:
+    class Grok {
+    } x;
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_no_access.i b/trunk/Examples/test-suite/errors/cpp_no_access.i
new file mode 100644
index 0000000..e04ad9d
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_no_access.i
@@ -0,0 +1,4 @@
+%module xxx
+
+class Bar : foo {
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_nobase.i b/trunk/Examples/test-suite/errors/cpp_nobase.i
new file mode 100644
index 0000000..70e6d68
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_nobase.i
@@ -0,0 +1,7 @@
+%module xxx
+
+class Foo : public Bar {
+};
+
+class Spam : public Bar<int> {
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_overload.i b/trunk/Examples/test-suite/errors/cpp_overload.i
new file mode 100644
index 0000000..34fa3cc
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_overload.i
@@ -0,0 +1,15 @@
+%module xxx
+int foo(int x);
+int foo(double x);
+
+class Foo {
+public:
+    int bar(int);
+    int bar(double);
+};
+
+class Spam {
+public:
+    Spam();
+    Spam(int);
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_private_defvalue.i b/trunk/Examples/test-suite/errors/cpp_private_defvalue.i
new file mode 100644
index 0000000..15542c7
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_private_defvalue.i
@@ -0,0 +1,7 @@
+%module xxx
+
+class foo {
+static const int BAR = 42;
+public:
+   int blah(int x = BAR);
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_private_inherit.i b/trunk/Examples/test-suite/errors/cpp_private_inherit.i
new file mode 100644
index 0000000..e8267e9
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_private_inherit.i
@@ -0,0 +1,11 @@
+%module xxx
+
+class Foo {
+};
+
+class Bar : private Foo {
+};
+
+class Spam : protected Foo {
+};
+
diff --git a/trunk/Examples/test-suite/errors/cpp_template_argname.i b/trunk/Examples/test-suite/errors/cpp_template_argname.i
new file mode 100644
index 0000000..b87c115
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_template_argname.i
@@ -0,0 +1,8 @@
+%module xxx
+
+template<T> T blah(T x);
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_template_nargs.i b/trunk/Examples/test-suite/errors/cpp_template_nargs.i
new file mode 100644
index 0000000..1a4fbdc
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_template_nargs.i
@@ -0,0 +1,10 @@
+%module xxx
+
+template<typename T> T blah(T x) { };
+
+%template(blahi) blah<int,double>;
+%template(blahf) blah<>;
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_template_not.i b/trunk/Examples/test-suite/errors/cpp_template_not.i
new file mode 100644
index 0000000..c8df700
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_template_not.i
@@ -0,0 +1,9 @@
+%module xxx
+
+int blah;
+
+%template(blahi) blah<int>;
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_template_partial.i b/trunk/Examples/test-suite/errors/cpp_template_partial.i
new file mode 100644
index 0000000..04ae905
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_template_partial.i
@@ -0,0 +1,4 @@
+%module xxx
+
+template<class T> class vector<T *> {
+};
diff --git a/trunk/Examples/test-suite/errors/cpp_template_repeat.i b/trunk/Examples/test-suite/errors/cpp_template_repeat.i
new file mode 100644
index 0000000..e63ffe8
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_template_repeat.i
@@ -0,0 +1,7 @@
+%module xxx
+
+template<class T> T blah(T x) { };
+
+%template(iblah) blah<int>;
+%template(iiblah) blah<int>;
+
diff --git a/trunk/Examples/test-suite/errors/cpp_template_undef.i b/trunk/Examples/test-suite/errors/cpp_template_undef.i
new file mode 100644
index 0000000..2c0afbe
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_template_undef.i
@@ -0,0 +1,7 @@
+%module xxx
+
+%template(blahi) blah<int>;
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_using_not.i b/trunk/Examples/test-suite/errors/cpp_using_not.i
new file mode 100644
index 0000000..2d5b6bf
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_using_not.i
@@ -0,0 +1,9 @@
+%module xxx
+
+int blah;
+using namespace blah;
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/cpp_using_undef.i b/trunk/Examples/test-suite/errors/cpp_using_undef.i
new file mode 100644
index 0000000..bc0c8c7
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/cpp_using_undef.i
@@ -0,0 +1,9 @@
+%module xxx
+
+using foo::bar;
+using namespace foo;
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/make.sh b/trunk/Examples/test-suite/errors/make.sh
new file mode 100755
index 0000000..ae38ca8
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/make.sh
@@ -0,0 +1,103 @@
+#!/bin/sh
+echo "---------------------------------------"
+echo "Testing SWIG error and warning messages"
+echo "---------------------------------------"
+
+SWIG='../../../preinst-swig'
+
+# Files run in C mode
+CFILES='
+c_bad_name
+c_bad_native
+c_class
+c_default_error
+c_deprecated
+c_empty_char
+c_enum_badvalue
+c_extra_rblock
+c_extra_rbrace
+c_extra_unsigned
+c_insert_missing
+c_long_short
+c_missing_rbrace
+c_missing_semi
+c_redefine
+c_varargs
+c_varargs_neg
+nomodule 
+pp_badeval
+pp_defined
+pp_macro_args
+pp_macro_badchar
+pp_macro_nargs
+pp_macro_redef
+pp_macro_rparen
+pp_macro_unterminated
+pp_misplaced_elif
+pp_misplaced_else
+pp_missing_enddef
+pp_missing_endif
+pp_missing_file
+pp_missing_rblock
+pp_unterm_char
+pp_unterm_comment
+pp_unterm_string
+swig_apply_nargs
+swig_identifier
+swig_insert_bad
+swig_typemap_copy
+swig_typemap_old
+'
+
+# Files run in C++ mode
+CPPFILES='
+cpp_bad_extern
+cpp_extend_redefine
+cpp_extend_undefined
+cpp_inline_namespace
+cpp_missing_rtemplate
+cpp_namespace_alias
+cpp_namespace_aliasnot
+cpp_namespace_aliasundef
+cpp_nested
+cpp_no_access
+cpp_nobase
+cpp_overload
+cpp_private_defvalue
+cpp_private_inherit
+cpp_template_argname
+cpp_template_nargs
+cpp_template_not
+cpp_template_partial
+cpp_template_repeat
+cpp_template_undef
+cpp_using_not
+cpp_using_undef
+'
+
+LOGFILE='test.log'
+SWIGOPT=$*
+
+rm -f ${LOGFILE}
+
+echo "SWIG error and warning test. opts=${SWIGOPT}" >> ${LOGFILE}
+echo "-----------------------------------------------------------" >> ${LOGFILE}
+
+for i in ${CFILES}; do 
+   echo "    Testing : ${i}.i"; 
+   echo "" >> ${LOGFILE};
+   echo ":::::::::::::::::::::::::::::::: ${i}.i :::::::::::::::::::::::::::::::::::" >> ${LOGFILE};
+   ${SWIG} -Wall ${SWIGOPT} ${i}.i >>${LOGFILE} 2>&1
+done
+
+for i in ${CPPFILES}; do 
+   echo "    Testing : ${i}.i"; 
+   echo "" >> ${LOGFILE}
+   echo ":::::::::::::::::::::::::::::::: ${i}.i :::::::::::::::::::::::::::::::::::" >> ${LOGFILE};
+   ${SWIG} -Wall -c++ ${SWIGOPT} ${i}.i >>${LOGFILE} 2>&1
+done
+
+echo ""
+echo "Results written to '${LOGFILE}'"
+
+
diff --git a/trunk/Examples/test-suite/errors/nomodule.i b/trunk/Examples/test-suite/errors/nomodule.i
new file mode 100644
index 0000000..6341be3
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/nomodule.i
@@ -0,0 +1,2 @@
+/* No module name */
+int foo(int);
diff --git a/trunk/Examples/test-suite/errors/pp_badeval.i b/trunk/Examples/test-suite/errors/pp_badeval.i
new file mode 100644
index 0000000..aca397c
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_badeval.i
@@ -0,0 +1,11 @@
+%module xxx
+
+#if FOO==4
+#elif FOO==4+
+#endif
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_defined.i b/trunk/Examples/test-suite/errors/pp_defined.i
new file mode 100644
index 0000000..e2f3430
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_defined.i
@@ -0,0 +1,7 @@
+%module xxx
+
+#if defined()
+#endif
+
+#if defined
+#endif
diff --git a/trunk/Examples/test-suite/errors/pp_macro_args.i b/trunk/Examples/test-suite/errors/pp_macro_args.i
new file mode 100644
index 0000000..8bbbfb1
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_macro_args.i
@@ -0,0 +1,7 @@
+%module xxx
+
+#define foo(a,x) a x
+
+#if foo
+#endif
+
diff --git a/trunk/Examples/test-suite/errors/pp_macro_badchar.i b/trunk/Examples/test-suite/errors/pp_macro_badchar.i
new file mode 100644
index 0000000..2760115
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_macro_badchar.i
@@ -0,0 +1,5 @@
+%module xxx
+
+#define f@oo(a,x)   a + x
+#define foo(a@,x)   a + x
+
diff --git a/trunk/Examples/test-suite/errors/pp_macro_nargs.i b/trunk/Examples/test-suite/errors/pp_macro_nargs.i
new file mode 100644
index 0000000..15e4348
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_macro_nargs.i
@@ -0,0 +1,16 @@
+%module xxx
+
+#define foo(a,x)      a x
+#define bar(x)        x
+#define spam()        /**/
+
+foo(3)
+foo(3,4,5)
+bar()
+bar(2,3)
+spam(1)
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_macro_redef.i b/trunk/Examples/test-suite/errors/pp_macro_redef.i
new file mode 100644
index 0000000..e0910e6
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_macro_redef.i
@@ -0,0 +1,8 @@
+%module xxx
+
+#define foo(a,x)      a+x
+#define foo           4
+
+/* Should not generate an error */
+#define foo           4
+
diff --git a/trunk/Examples/test-suite/errors/pp_macro_rparen.i b/trunk/Examples/test-suite/errors/pp_macro_rparen.i
new file mode 100644
index 0000000..cbb04fb
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_macro_rparen.i
@@ -0,0 +1,3 @@
+%module xxx
+
+#define foo(a,x       3
diff --git a/trunk/Examples/test-suite/errors/pp_macro_unterminated.i b/trunk/Examples/test-suite/errors/pp_macro_unterminated.i
new file mode 100644
index 0000000..d0e32d7
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_macro_unterminated.i
@@ -0,0 +1,7 @@
+%module xxx
+
+#define foo(a,x)      a+x
+
+foo(3,
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_misplaced_elif.i b/trunk/Examples/test-suite/errors/pp_misplaced_elif.i
new file mode 100644
index 0000000..5e656f0
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_misplaced_elif.i
@@ -0,0 +1,7 @@
+%module xxx
+
+
+#elif foo == 3
+int x;
+#endif
+
diff --git a/trunk/Examples/test-suite/errors/pp_misplaced_else.i b/trunk/Examples/test-suite/errors/pp_misplaced_else.i
new file mode 100644
index 0000000..ad29946
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_misplaced_else.i
@@ -0,0 +1,7 @@
+%module xxx
+
+
+#else
+int x;
+#endif
+
diff --git a/trunk/Examples/test-suite/errors/pp_missing_enddef.i b/trunk/Examples/test-suite/errors/pp_missing_enddef.i
new file mode 100644
index 0000000..e13deef
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_missing_enddef.i
@@ -0,0 +1,7 @@
+%module xxx
+
+%define FOO
+int x;
+
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_missing_endif.i b/trunk/Examples/test-suite/errors/pp_missing_endif.i
new file mode 100644
index 0000000..e83496f
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_missing_endif.i
@@ -0,0 +1,6 @@
+%module xxx
+
+#ifdef FOO
+int x;
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_missing_file.i b/trunk/Examples/test-suite/errors/pp_missing_file.i
new file mode 100644
index 0000000..5e3f0ea
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_missing_file.i
@@ -0,0 +1,3 @@
+%module test
+
+%include "missing_filename.i"
diff --git a/trunk/Examples/test-suite/errors/pp_missing_rblock.i b/trunk/Examples/test-suite/errors/pp_missing_rblock.i
new file mode 100644
index 0000000..55c3cc8
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_missing_rblock.i
@@ -0,0 +1,7 @@
+%module xxx
+
+%{
+int x;
+
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_unterm_char.i b/trunk/Examples/test-suite/errors/pp_unterm_char.i
new file mode 100644
index 0000000..9b028fd
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_unterm_char.i
@@ -0,0 +1,7 @@
+%module xxx
+
+
+const char x = 'H
+
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_unterm_comment.i b/trunk/Examples/test-suite/errors/pp_unterm_comment.i
new file mode 100644
index 0000000..f9cdb82
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_unterm_comment.i
@@ -0,0 +1,6 @@
+%module xxx
+
+/* Hello
+
+
+
diff --git a/trunk/Examples/test-suite/errors/pp_unterm_string.i b/trunk/Examples/test-suite/errors/pp_unterm_string.i
new file mode 100644
index 0000000..31ed8d4
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/pp_unterm_string.i
@@ -0,0 +1,6 @@
+%module xxx
+
+
+const char *x = "Hello
+
+
diff --git a/trunk/Examples/test-suite/errors/swig_apply_nargs.i b/trunk/Examples/test-suite/errors/swig_apply_nargs.i
new file mode 100644
index 0000000..bb1519c
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/swig_apply_nargs.i
@@ -0,0 +1,6 @@
+%module xxx
+
+%typemap(in) (char *str, int len) {
+}
+
+%apply (char *str, int len) { int x };
diff --git a/trunk/Examples/test-suite/errors/swig_identifier.i b/trunk/Examples/test-suite/errors/swig_identifier.i
new file mode 100644
index 0000000..3ad0736
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/swig_identifier.i
@@ -0,0 +1,6 @@
+%module xxx
+
+%rename("foo bar") foobar;
+
+int foobar(int);
+
diff --git a/trunk/Examples/test-suite/errors/swig_insert_bad.i b/trunk/Examples/test-suite/errors/swig_insert_bad.i
new file mode 100644
index 0000000..e2dd8a9
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/swig_insert_bad.i
@@ -0,0 +1,5 @@
+%module xxx
+
+%insert("foobar") %{
+some code
+%}
diff --git a/trunk/Examples/test-suite/errors/swig_typemap_copy.i b/trunk/Examples/test-suite/errors/swig_typemap_copy.i
new file mode 100644
index 0000000..17607f2
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/swig_typemap_copy.i
@@ -0,0 +1,3 @@
+%module xxx
+
+%typemap(in) int = blah;
diff --git a/trunk/Examples/test-suite/errors/swig_typemap_old.i b/trunk/Examples/test-suite/errors/swig_typemap_old.i
new file mode 100644
index 0000000..c27ff55
--- /dev/null
+++ b/trunk/Examples/test-suite/errors/swig_typemap_old.i
@@ -0,0 +1,6 @@
+%module xxx
+
+%typemap(in) int x {
+   $source;
+   $target;
+}
diff --git a/trunk/Examples/test-suite/evil_diamond.i b/trunk/Examples/test-suite/evil_diamond.i
new file mode 100644
index 0000000..33353e3
--- /dev/null
+++ b/trunk/Examples/test-suite/evil_diamond.i
@@ -0,0 +1,26 @@
+%module(ruby_minherit="1") evil_diamond
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) bar;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) baz;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME,
+	    SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) spam;	// Ruby, wrong class name - C# & Java, Php4 multiple inheritance
+
+%inline %{
+
+class foo { };
+
+class bar : public foo {
+};
+
+class baz : public foo {
+};
+
+class spam : public bar, public baz {
+};
+
+foo *test(foo *f) { return f; }
+%}
+
diff --git a/trunk/Examples/test-suite/evil_diamond_ns.i b/trunk/Examples/test-suite/evil_diamond_ns.i
new file mode 100644
index 0000000..78a764c
--- /dev/null
+++ b/trunk/Examples/test-suite/evil_diamond_ns.i
@@ -0,0 +1,27 @@
+%module(ruby_minherit="1") evil_diamond_ns
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Blah::foo;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Blah::bar;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Blah::baz;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME,
+	    SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) Blah::spam;	// Ruby, wrong class name - C# & Java, Php4 multiple inheritance
+
+%inline %{
+namespace Blah {
+class foo { };
+
+class bar : public foo {
+};
+
+class baz : public foo {
+};
+
+class spam : public bar, public baz {
+};
+
+foo *test(foo *f) { return f; }
+}
+%}
+
diff --git a/trunk/Examples/test-suite/evil_diamond_prop.i b/trunk/Examples/test-suite/evil_diamond_prop.i
new file mode 100644
index 0000000..e9fc24f
--- /dev/null
+++ b/trunk/Examples/test-suite/evil_diamond_prop.i
@@ -0,0 +1,39 @@
+%module(ruby_minherit="1") evil_diamond_prop
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) bar;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) baz;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME,
+	    SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) spam;	// Ruby, wrong class name - C# & Java, Php4 multiple inheritance
+
+%inline %{
+
+class foo { 
+  public:
+    int _foo;
+    foo() : _foo(1) {}
+};
+
+class bar : public foo {
+  public:
+    int _bar;
+    bar() : _bar(2) {}
+};
+
+class baz : public foo {
+  public:
+    int _baz;
+    baz() : _baz(3) {}
+};
+
+class spam : public bar, public baz {
+  public:
+    int _spam;
+    spam() : _spam(4) {}
+};
+
+foo *test(foo *f) { return f; }
+%}
+
diff --git a/trunk/Examples/test-suite/exception_order.i b/trunk/Examples/test-suite/exception_order.i
new file mode 100644
index 0000000..45a87e0
--- /dev/null
+++ b/trunk/Examples/test-suite/exception_order.i
@@ -0,0 +1,111 @@
+%module exception_order
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME);
+
+%include "exception.i"
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+/* 
+   last resource, catch everything but don't override 
+   user's throw declarations.
+*/
+
+#if defined(SWIGUTL)
+%exception {
+  try {
+    $action
+  } catch(...) {
+    SWIG_exception_fail(SWIG_RuntimeError,"postcatch unknown");
+  }
+}
+#else
+%exception {
+  try {
+    $action
+  } catch(...) {
+    SWIG_exception(SWIG_RuntimeError,"postcatch unknown");
+  }
+}
+#endif
+
+%catches(E1,E2*,ET<int>,ET<double>,...) A::barfoo(int i);
+
+
+%allowexception efoovar;
+%allowexception A::efoovar;
+
+%inline %{
+  int efoovar;
+  int foovar;
+  const int cfoovar = 1;
+  
+  struct E1
+  {
+  };
+
+  struct E2 
+  {
+  };
+
+  struct E3 
+  {
+  };
+
+  template <class T>
+  struct ET 
+  {
+  };
+
+  struct A 
+  {
+    static int sfoovar;
+    static const int CSFOOVAR = 1;
+    int foovar;
+    int efoovar;
+
+    /* caught by the user's throw definition */
+    int foo() throw(E1) 
+    {
+      throw E1();
+      return 0;     
+    }
+    
+    int bar() throw(E2)
+    {
+      throw E2();
+      return 0;     
+    }
+    
+    /* caught by %postexception */
+    int foobar()
+    {
+      throw E3();
+      return 0;
+    }
+
+
+    int barfoo(int i)
+    {
+      if (i == 1) {
+	throw E1();
+      } else if (i == 2) {
+	static E2 *ep = new E2();
+	throw ep;
+      } else if (i == 3) {
+	throw ET<int>();
+      } else  {
+	throw ET<double>();
+      }
+      return 0;
+    }
+  };
+  int A::sfoovar = 1;
+%}
+
+%template(ET_i) ET<int>;
+%template(ET_d) ET<double>;
diff --git a/trunk/Examples/test-suite/exception_partial_info.i b/trunk/Examples/test-suite/exception_partial_info.i
new file mode 100644
index 0000000..37b87ef
--- /dev/null
+++ b/trunk/Examples/test-suite/exception_partial_info.i
@@ -0,0 +1,51 @@
+%module exception_partial_info
+
+// This produced compileable code for Tcl, Python in 1.3.27, fails in 1.3.29
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%{
+class myException
+{
+   public:
+      virtual const char *name() = 0;
+};
+
+class ex1 : public myException
+{
+   public:
+      virtual const char *name() { return "ex1"; }
+};
+
+class ex2 : public myException
+{
+   public:
+      virtual const char *name()  { return "ex2"; }
+};
+%}
+
+#if !defined(SWIGUTL)
+
+#if !defined(SWIGCHICKEN)
+
+%inline %{
+class Impl
+{
+   public:
+      void f1() throw (myException) { ex1 e; throw e; }
+      void f2() throw (myException) { ex2 e; throw e; }
+};
+%}
+
+#else
+#warning "Chicken needs fixing for partial exception information"
+#endif
+
+#else
+#warning "UTL needs fixing for partial exception information"
+#endif
+
diff --git a/trunk/Examples/test-suite/extend.i b/trunk/Examples/test-suite/extend.i
new file mode 100644
index 0000000..2a2a472
--- /dev/null
+++ b/trunk/Examples/test-suite/extend.i
@@ -0,0 +1,53 @@
+%module extend
+
+%extend Base {
+  ~Base() {
+    delete $self; 
+  }
+  static int zeroVal() {
+    return 0;
+  }
+  virtual int currentValue() {
+    return $self->value;
+  }
+  int extendmethod(int v) {
+    int ret = $self->method(v);
+    return ret * 2;
+  }
+};
+
+%inline %{
+struct Base {
+  Base(int v = 0) : value(v) {}
+  int value;
+  virtual int method(int v) {
+    return v;
+  }
+};
+struct Derived : Base {
+  double actualval;
+};
+%}
+
+%{
+  double extendval = 0;
+  double Derived_extendval_get(Derived *self) {
+    return self->actualval * 100;
+  }
+  void Derived_extendval_set(Derived *self, double d) {
+    self->actualval = d/100;
+  }
+%}
+
+%extend Derived {
+  Derived(int v) {
+    Derived *$self = new Derived();
+    $self->value = v*2;
+    return $self;
+  }
+  virtual int method(int v) {
+    int ret = $self->Base::method(v);
+    return ret * 2;
+  }
+  double extendval;
+}
diff --git a/trunk/Examples/test-suite/extend_default.i b/trunk/Examples/test-suite/extend_default.i
new file mode 100644
index 0000000..097b533
--- /dev/null
+++ b/trunk/Examples/test-suite/extend_default.i
@@ -0,0 +1,133 @@
+// Tests %extend with default arguments as well as %extend with default arguments with overloading
+
+%module extend_default
+
+%warnfilter(SWIGWARN_PARSE_REDEFINED) Override::over; 
+%warnfilter(SWIGWARN_PARSE_REDEFINED) Override::overload; 
+%warnfilter(SWIGWARN_PARSE_REDEFINED) Override::ride; 
+
+// %extend before the class definition
+%extend Before {
+  Before(int i = -1, double d = -1.0) { 
+    Before *self = new Before();
+    self->i = i;
+    self->d = d;
+    return self;
+  }
+  static double AddedStaticMethod(int i = -1, double d = -1) { return i+d; }
+  double AddedMethod(int i = -1, double d = -1.0) { return i+d; }
+}
+
+%inline %{
+struct Before {
+  double d;
+  int i;
+};
+%}
+
+// %extend after the class definition
+%inline %{
+struct After {
+  double d;
+  int i;
+};
+%}
+
+%extend After {
+  After(int i = -1, double d = -1.0) { 
+    After *self = new After();
+    self->i = i;
+    self->d = d;
+    return self;
+  }
+  static double AddedStaticMethod(int i = -1, double d = -1) { return i+d; }
+  double AddedMethod(int i = -1, double d = -1.0) { return i+d; }
+}
+
+
+// %extend before the class definition - with overloading and default args
+%extend OverBefore {
+  OverBefore(int i = -1, double d = -1.0) { 
+    OverBefore *self = new OverBefore("boo");
+    self->i = i;
+    self->d = d;
+    return self;
+  }
+  static double AddedStaticMethod(int i = -1, double d = -1) { return i+d; }
+  double AddedMethod(int i = -1, double d = -1.0) { return i+d; }
+}
+
+%inline %{
+struct OverBefore {
+  OverBefore(const char *str, int ii = -2, double dd = -2.0) : d(dd), i(ii) { str=0; }
+  static double AddedStaticMethod(const char*, int ii = -1, double dd = -1) { return ii+dd; }
+  double AddedMethod(const char*, int ii = -1, double dd = -1.0) { return ii+dd; }
+  double d;
+  int i;
+};
+%}
+
+// %extend after the class definition - with overloading and default args
+%extend OverAfter {
+  OverAfter(int i = -1, double d = -1.0) { 
+    OverAfter *self = new OverAfter("boo");
+    self->i = i;
+    self->d = d;
+    return self;
+  }
+  static double AddedStaticMethod(int i = -1, double d = -1) { return i+d; }
+  double AddedMethod(int i = -1, double d = -1.0) { return i+d; }
+}
+
+%inline %{
+struct OverAfter {
+  OverAfter(const char *str, int ii = -2, double dd = -2.0) : d(dd), i(ii) { str=0; }
+  static double AddedStaticMethod(const char*, int ii = -1, double dd = -1) { return ii+dd; }
+  double AddedMethod(const char*, int ii = -1, double dd = -1.0) { return ii+dd; }
+  double d;
+  int i;
+};
+%}
+
+
+// %extend overrides the class definition
+%extend Override {
+  int over(int a) { return a*a; } // SWIG should give a warning then choose this one over the real one
+  int overload(int a) { return a*a; } // Similarly, but this one generated uncompileable code in SWIG-1.3.22
+}
+%inline %{
+struct Override {
+  int over(int a = -1) { return a; }
+  int ride(int a = -1) { return a; }
+  int overload(int a) { return a; }
+  int overload() { return -10; }
+};
+%}
+%extend Override {
+  int ride(int a) { return a+a; } // SWIG should give a warning then ignore this one
+}
+
+
+// %extend in class hierarchy
+%extend Base {
+virtual int * virtualmethod(int a = 0) { return 0; }
+int * nonvirtual(int a = 0) { return 0; }
+static int * static_method(int a = 0) { return 0; }
+}
+%extend Derived {
+int * virtualmethod(int a = 0) { return 0; }
+int * nonvirtual(int a = 0) { return 0; }
+static int * static_method(int a = 0) { return 0; }
+int * realvirtual(int a = 0) { return 0; }
+}
+
+
+%inline %{
+struct Base {
+  virtual ~Base() {}
+  virtual int * realvirtual(int a = 0) { return 0; }
+};
+struct Derived : Base {
+};
+%}
+
diff --git a/trunk/Examples/test-suite/extend_placement.i b/trunk/Examples/test-suite/extend_placement.i
new file mode 100644
index 0000000..b95e821
--- /dev/null
+++ b/trunk/Examples/test-suite/extend_placement.i
@@ -0,0 +1,107 @@
+%module extend_placement
+
+// Tests placement of %extend directives
+
+// Before the class
+
+%extend Foo {
+  Foo(int a) { return new Foo(); }
+  ~Foo() { delete $self;}
+  int spam(int x) { return x; }
+  int spam(int x, int y) { return x + y ; }
+  int spam(int x, int y,int z) { return x + y ; }
+  int spam(Foo f, double d = 10.0) { return 0; }
+};
+
+%inline %{
+class Foo {
+public:
+  Foo(){}
+
+#ifdef SWIG
+%extend { Foo(int a, int b) { return new Foo(); } }  
+#endif
+
+  int spam() { return 1; }
+  int spam(const char* c) { return 2; }
+};
+%}
+
+// After the class
+
+%inline %{
+class Bar {
+public:
+  Bar() { }
+  int spam() { return 1; }
+  int spam(const char* c) { return 2; }
+};
+%}
+
+
+%extend Bar {
+  Bar(int a) { return new Bar(); }
+  ~Bar() { delete $self;}
+  int spam() { return 1}
+  int spam(int x) { return x; }
+  int spam(int x, int y) { return x + y ; }
+  int spam(int x, int y,int z) { return x + y ; }
+  int spam(Bar b, double d = 10.0) { return 0; }
+};
+
+
+// testing templates
+
+// Before the class
+
+%extend FooT {
+  FooT(int a) { return new FooT<T>(); }
+  ~FooT() { delete $self;}
+  int spam(int x) { return x; }
+  int spam(int x, int y) { return x + y ; }
+  int spam(int x, int y,int z) { return x + y ; }
+  int spam(Foo f, double d = 10.0) { return 0; }
+};
+
+%inline %{
+template<class T>
+class FooT {
+public:
+  FooT(){}
+
+#ifdef SWIG
+%extend { FooT(int a, int b) { return new FooT<T>(); } }  
+#endif
+
+  int spam() { return 1; }
+  int spam(const char* c) { return 2; }
+};
+%}
+
+%template(FooTi) FooT<int>;
+
+
+// After the class
+
+%inline %{
+template<class T>
+class BarT {
+public:
+  BarT() { }
+  int spam() { return 1; }
+  int spam(const char* c) { return 2; }
+};
+%}
+
+
+%extend BarT {
+  BarT(int a) { return new BarT<T>(); }
+  ~BarT() { delete $self;}
+  int spam() { return 1}
+  int spam(int x) { return x; }
+  int spam(int x, int y) { return x + y ; }
+  int spam(int x, int y,int z) { return x + y ; }
+  int spam(Bar b, double d = 10.0) { return 0; }
+};
+
+%template(BarTi) BarT<int>;
diff --git a/trunk/Examples/test-suite/extend_template.i b/trunk/Examples/test-suite/extend_template.i
new file mode 100644
index 0000000..a39ac54
--- /dev/null
+++ b/trunk/Examples/test-suite/extend_template.i
@@ -0,0 +1,26 @@
+%module extend_template
+%module xxx
+namespace oss { // this doesn't 
+ %extend Foo<0> { 
+    int test1(int x) { return x; }
+ } 
+} 
+ 
+%extend oss::Foo<0> { // this doesn't 
+ int test2(int x) { return x; }
+};
+
+ 
+%inline %{ 
+ namespace oss 
+ { 
+   template <int> 
+   struct Foo { 
+   }; 
+  } 
+%} 
+ 
+namespace oss 
+{ 
+ %template(Foo_0) Foo<0>; 
+} 
diff --git a/trunk/Examples/test-suite/extend_template_ns.i b/trunk/Examples/test-suite/extend_template_ns.i
new file mode 100644
index 0000000..3712f2c
--- /dev/null
+++ b/trunk/Examples/test-suite/extend_template_ns.i
@@ -0,0 +1,32 @@
+%module extend_template_ns
+%inline %{ 
+namespace oss 
+{ 
+  enum Test {One, Two}; 
+} 
+%} 
+ 
+namespace oss { 
+   %extend Foo<One> {           //************ this doesn't  work 
+     int test1(int x) { return x; } 
+   };
+} 
+ 
+%extend oss::Foo<oss::One> {  //******** this works 
+int test2(int x) { return x; } 
+}; 
+ 
+%inline %{ 
+namespace oss 
+{ 
+  template <Test> 
+  struct Foo { 
+  }; 
+ } 
+%} 
+ 
+namespace oss 
+{ 
+%template(Foo_One) Foo<One>; 
+} 
+ 
diff --git a/trunk/Examples/test-suite/extend_variable.i b/trunk/Examples/test-suite/extend_variable.i
new file mode 100644
index 0000000..7cb6e86
--- /dev/null
+++ b/trunk/Examples/test-suite/extend_variable.i
@@ -0,0 +1,103 @@
+%module extend_variable
+
+// Tests %extend for variables
+
+%inline %{
+class ExtendMe {
+  double var;
+public:
+  ExtendMe() : var(0.0) {}
+  bool get(double &d) {
+    d = var;
+    return true;
+  }
+  bool set(const double &d) {
+    var = d;
+    return true;
+  }
+};
+%}
+
+%extend ExtendMe {
+  double ExtendVar;
+};
+
+%{
+// If possible, all language modules should use this naming format for consistency
+void ExtendMe_ExtendVar_set(ExtendMe *thisptr, double value) {
+  thisptr->set(value);
+}
+double ExtendMe_ExtendVar_get(ExtendMe *thisptr) {
+  double value = 0;
+  thisptr->get(value);
+  return value;
+}
+%}
+
+
+%{
+  class Foo 
+  {
+  };
+%}
+
+#if SWIGJAVA
+%javaconst(1) AllBarOne;
+#elif SWIGCSHARP
+%csconst(1) AllBarOne;
+#endif
+
+
+class Foo {
+  public:
+    %extend {
+        static const int Bar = 42;
+        static const int AllBarOne = 4422;
+        static const int StaticConstInt;
+        static int StaticInt;
+    }
+}; 
+  
+%{
+  int globalVariable = 1111;
+
+  void Foo_StaticInt_set(int value) {
+    globalVariable = value;
+  }
+
+  int Foo_StaticInt_get() {
+    return globalVariable;
+  }
+
+  int Foo_StaticConstInt_get() {
+    static int var = 2222;
+    return var;
+  }
+%}
+
+%inline {
+  namespace ns1 
+  {
+    struct Bar
+    {
+    }
+    ;
+  }
+}
+
+%{
+  int ns1_Bar_x_get(ns1::Bar *self) {
+    return 1;
+  }
+
+  void ns1_Bar_x_set(ns1::Bar *self, int x) {
+  }
+%}
+  
+%extend ns1::Bar 
+{
+  int x;
+}
+
+
+  
diff --git a/trunk/Examples/test-suite/extern_declaration.i b/trunk/Examples/test-suite/extern_declaration.i
new file mode 100644
index 0000000..eca97b5
--- /dev/null
+++ b/trunk/Examples/test-suite/extern_declaration.i
@@ -0,0 +1,31 @@
+%module extern_declaration 
+
+// Test different calling conventions on Windows. Old versions of SWIG generated
+// an incorrect extern declaration that wouldn't compile with Windows compilers.
+#define SWIGEXPORT
+#define SWIGSTDCALL
+#define MYDLLIMPORT
+
+%{
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#  define MYDLLIMPORT __declspec(dllimport)
+#else
+#  define MYDLLIMPORT
+#endif
+%}
+
+MYDLLIMPORT extern int externimport(int i);
+SWIGEXPORT extern int externexport(int);
+extern int SWIGSTDCALL externstdcall(int);
+
+%{
+/*
+  externimport ought to be using MYDLLIMPORT and compiled into another dll, but that is 
+  a bit tricky to do in the test framework
+*/
+SWIGEXPORT extern int externimport(int i) { return i; }
+SWIGEXPORT extern int externexport(int i) { return i; }
+extern int SWIGSTDCALL externstdcall(int i) { return i; }
+%}
+
+
diff --git a/trunk/Examples/test-suite/extern_namespace.i b/trunk/Examples/test-suite/extern_namespace.i
new file mode 100644
index 0000000..e7f952f
--- /dev/null
+++ b/trunk/Examples/test-suite/extern_namespace.i
@@ -0,0 +1,23 @@
+%module extern_namespace
+%inline %{
+
+  namespace foo {
+    
+    extern int bar(int blah = 1);
+    
+  }
+
+  extern "C" int foobar(int i) {
+    return i;
+  }
+  
+%}
+
+
+
+%{
+  int foo::bar(int blah) {
+    return blah;
+  }
+%}
+  
diff --git a/trunk/Examples/test-suite/extern_throws.i b/trunk/Examples/test-suite/extern_throws.i
new file mode 100644
index 0000000..eab2624
--- /dev/null
+++ b/trunk/Examples/test-suite/extern_throws.i
@@ -0,0 +1,18 @@
+%module extern_throws 
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%inline %{
+#include <exception>
+extern int get() throw(std::exception);
+
+%}
+
+%{
+int get() throw(std::exception) { return 0; }
+%}
+
diff --git a/trunk/Examples/test-suite/features.i b/trunk/Examples/test-suite/features.i
new file mode 100644
index 0000000..2db51ae
--- /dev/null
+++ b/trunk/Examples/test-suite/features.i
@@ -0,0 +1,164 @@
+%module features
+
+%warnfilter(SWIGWARN_LANG_IDENTIFIER,SWIGWARN_IGNORE_OPERATOR_PLUSEQ);
+
+// This testcase checks that %feature is working for templates and non user supplied constructors/destructors and is just generally working
+
+// If the default %exception is used it will not compile. It shouldn't get used.
+%exception "this_will_not_compile";
+
+// Test 1: Test for no user supplied constructors and destructor
+%exception Simple::Simple(const Simple&) "$action /*Simple::Simple*/";
+%exception Simple::Simple() "$action /*Simple::Simple*/";
+%exception Simple::~Simple() "$action /*Simple::~Simple*/";
+
+%inline %{
+class Simple {};
+%}
+
+
+%exception NS::SimpleNS::SimpleNS(const NS::SimpleNS&) "$action /*NS::SimpleNS::SimpleNS*/";
+%exception NS::SimpleNS::SimpleNS() "$action /*NS::SimpleNS::SimpleNS*/";
+%exception NS::SimpleNS::~SimpleNS() "$action /*NS::SimpleNS::~SimpleNS*/";
+// method tests
+%exception NS::SimpleNS::method()       "_failed_ /*NS::Simple::method() const*/";
+%exception NS::SimpleNS::method() const "$action /*NS::Simple::method() const*/";
+%exception NS::SimpleNS::afunction() "$action /*NS::Simple::afunction()*/";
+
+%inline %{
+  namespace NS 
+  {
+    
+    class SimpleNS {
+    public:
+      void method() const {}
+      void afunction() {}
+    };
+  }
+  
+%}
+
+// Test 2: Test templated functions
+%exception foobar "caca";
+%exception foobar<int>(int) "$action /*foobar<int>*/";
+
+%inline %{
+template<class T> void foobar(T t) {}
+%}
+
+%template(FooBarInt) foobar<int>;
+
+// Test 3: Test templates with no user supplied constructors and destructor
+%exception SimpleTemplate<int>::SimpleTemplate(const SimpleTemplate<int>&) "$action /*SimpleTemplate<int>::SimpleTemplate<int>*/";
+%exception SimpleTemplate<int>::SimpleTemplate() "$action /*SimpleTemplate<int>::SimpleTemplate<int>*/";
+%exception SimpleTemplate<int>::~SimpleTemplate() "$action /*SimpleTemplate<int>::~SimpleTemplate*/";
+
+%inline %{
+template<class T> class SimpleTemplate {
+ public:
+};
+ 
+%}
+
+%template(SimpleInt) SimpleTemplate<int>;
+
+// Test 4: Test templates with user supplied constructors and destructor
+%exception Template<int>::Template() "$action /*Template<int>::Template<int>*/";
+%exception Template<int>::Template(const Template&) "$action /*Template<int>::Template<int>(const Template&)*/";
+%exception Template<int>::~Template() "$action /*Template<int>::~Template*/";
+// method tests
+%exception Template<int>::foo "$action /*Template<int>::foo*/";
+%exception Template::get "$action /*Template<int>::get*/";
+%exception Template<int>::set(const int &t) "$action /*Template<int>::set(const int &t)*/";
+%exception Template<int>::bar(const int &t)       "_failed_ /*Template<int>::bar(const int &t) const*/";
+%exception Template<int>::bar(const int &t) const "$action /*Template<int>::bar(const int &t) const*/";
+
+%inline %{
+template<class T> class Template {
+public:
+  Template(){}
+
+  Template(const Template&){}
+  ~Template(){}
+  void foo(){}
+  void bar(const int &t) const {}
+#ifdef SWIG
+    %extend {
+      T& get(int i) const {
+        throw 1;
+      }
+      void set(const T &t) {}
+    }
+#endif
+};
+%}
+
+%template(TemplateInt) Template<int>; 
+
+// Test 5: wildcards
+%exception Space::WildCards::WildCards(const Space::WildCards&) "$action /* Space::WildCards::WildCards() */";
+%exception Space::WildCards::WildCards() "$action /* Space::WildCards::WildCards() */";
+%exception Space::WildCards::~WildCards() "$action /* Space::WildCards::WildCards() */";
+%exception *::incy              "_failure_ /* *::incy */";
+%exception *::incy(int a)       "_failure_ /* *::incy(int a) */";
+%exception *::incy(int a) const "$action /* *::incy(int a) const */";
+%exception *::wincy(int a) "$action /* *::wincy(int a) */";
+%exception *::spider "$action /* *::spider */";
+%exception *::spider(int a) "_failure_ /* *::spider(int a)  */";
+
+%inline %{
+namespace Space {
+  struct WildCards {
+    virtual ~WildCards() {}
+    virtual WildCards* incy(int a) const { return 0; }
+    virtual WildCards* wincy(int a) { return 0; }
+    virtual WildCards* spider(int a) const { return 0; }
+  };
+}
+%}
+
+// Test 6: default arguments
+%exception Space::Animals::Animals(const Space::Animals&) "$action /* Space::Animals::Animals(int a = 0, double d = 0.0) */";
+%exception Space::Animals::Animals(int a = 0, double d = 0.0) "$action /* Space::Animals::Animals(int a = 0, double d = 0.0) */";
+%exception Space::Animals::~Animals() "$action /* Space::Animals::~Animals() */";
+%exception Space::Animals::lions(int a = 0, double d = 0.0) const "$action /* Space::Animals::lions(int a = 0, double d = 0.0) const */";
+%exception Space::Animals::leopards(int a = 0, double d = 0.0) "$action /* Space::Animals::leopards(int a = 0, double d = 0.0) */";
+%exception *::cheetahs(int a = 0, double d = 0.0) const "$action /* *::cheetahs(int a = 0, double d = 0.0) const */";
+%exception *::jackal(int a = 0, double d = 0.0) "$action /* *::jackal(int a = 0, double d = 0.0) */";
+%inline %{
+namespace Space {
+  struct Animals {
+    Animals(int a = 0, double d = 0.0) {}
+    void* lions(int a = 0, double d = 0.0) const { return 0; }
+    void* leopards(int a = 0, double d = 0.0) { return 0; }
+    int cheetahs(int a = 0, double d = 0.0) const { return 0; }
+    int jackal(int a = 0, double d = 0.0) { return 0; }
+  };
+}
+%}
+
+// Test 7: inheritance
+%exception Space::Base::Base(const Space::Base&) "$action /* Space::Base::Base() */";
+%exception Space::Base::Base() "$action /* Space::Base::Base() */";
+%exception Space::Base::~Base() "$action /* Space::Base::~Base() */";
+%exception Space::Derived::Derived(const Space::Derived&) "$action /* Space::Derived::Derived() */";
+%exception Space::Derived::Derived() "$action /* Space::Derived::Derived() */";
+%exception Space::Derived::~Derived() "$action /* Space::Derived::~Derived() */";
+// The following should apply to both Base and Derived
+%exception Space::Base::virtualmethod(int a) const "$action /* Space::Base::virtualmethod(int a) const */";
+
+%exception Space::Base::operator+=(int) "$action /* Space::Base::Base() */";
+
+%inline %{
+namespace Space {
+  struct Base {
+    int operator+=(int) { return 0; }    
+    virtual const char** virtualmethod(int a) const { return 0; }
+    virtual ~Base() {}
+  };
+  struct Derived : Base {
+    virtual const char** virtualmethod(int a) const { return 0; }
+  };
+}
+%}
+
diff --git a/trunk/Examples/test-suite/file_test.i b/trunk/Examples/test-suite/file_test.i
new file mode 100644
index 0000000..f4d98a8
--- /dev/null
+++ b/trunk/Examples/test-suite/file_test.i
@@ -0,0 +1,21 @@
+%module file_test
+
+%include file.i
+
+
+%inline 
+%{
+  int nfile(FILE *file) {
+    return 0;
+  }
+
+  int nfile_name(const char *filename) {
+    return 0;
+  }
+
+  FILE* GetStdOut() {
+    return stdout;
+  }
+  
+%}
+
diff --git a/trunk/Examples/test-suite/fragments.i b/trunk/Examples/test-suite/fragments.i
new file mode 100644
index 0000000..4bf399a
--- /dev/null
+++ b/trunk/Examples/test-suite/fragments.i
@@ -0,0 +1,36 @@
+%module fragments
+
+
+%fragment("Hello","header") %{
+/* hello!!! */
+int foobar(int a)
+{
+  return a;
+}  
+%}
+
+/*
+ this fragment include the previous fragment if needed.
+*/
+
+%fragment("Hi","header",fragment="Hello") %{
+/* hi!!! */
+int bar(int a)
+{
+  return foobar(a);
+}  
+%}
+
+%typemap(in,fragment="Hi") int hola "$1 = 123;";
+
+
+%inline %{
+
+int bar(int a);
+
+int foo(int hola) 
+{
+  return bar(hola);
+}
+
+%}
diff --git a/trunk/Examples/test-suite/friends.i b/trunk/Examples/test-suite/friends.i
new file mode 100644
index 0000000..2dfee6f
--- /dev/null
+++ b/trunk/Examples/test-suite/friends.i
@@ -0,0 +1,178 @@
+%module friends
+%{
+#include <iostream>
+%}
+
+%warnfilter(SWIGWARN_LANG_IDENTIFIER);
+
+  
+%inline 
+{
+
+  void globalscope(); // forward declaration needed for some compilers
+
+  struct A;
+  struct B
+  {
+    B(int i) : v(i) 
+    {
+    }
+    
+    friend void ::globalscope();
+    friend int mix(A* a, B *b);
+    virtual ~B()
+    {
+    }
+    
+  private:
+    int v;
+    
+  };
+  
+  void globalscope() { B b(0); b.v=10; }
+  
+  struct A
+  {
+    A(int v) : val(v)
+    {
+    }
+
+    friend int get_val1(const A& a)
+    {
+      return a.val;
+    }
+
+    /* simple overloading */
+    friend int get_val1(const A& a, int o)
+    {
+      return a.val + o;
+    }
+
+    /*
+      note that operators << and >> are ignored, as they
+      should, since no rename is performed.
+    */
+    friend std::istream& operator>>(std::istream& in, A& a);
+
+    /* already declare at B */
+    friend int mix(A* a, B *b);
+
+  protected:
+    friend int get_val2(const A& a)
+    {
+      return a.val*2;
+    }
+    
+  private:
+    friend int get_val3(const A& a);
+
+    /* this should be ignored */
+    friend std::ostream& operator<<(std::ostream& out, const A& a)
+    {
+      out << a.val;
+      return out;
+    }
+
+    int val;    
+  };
+
+  /* 
+     'mix' is an interesting case, this is the third declaration
+     swig is getting (two friends + one inline).
+   */
+  inline int mix(A* a, B *b) {
+    return a->val + b->v;
+  }
+
+  /* this should be ignored */
+  inline std::istream& operator>>(std::istream& in, A& a) {
+    int v;
+    in >> v;
+    a = A(v);
+    return in;
+  }
+
+  inline int get_val3(const A& a) {
+    return a.val*3;
+  }
+  
+  /* another overloading */
+  inline int get_val1(int i, int a, int b) {
+    return i;
+  }
+
+
+  /*
+    sit and watch how well this case works, is just incredible!!,
+
+    also note that there is no special code added to manage friends
+    and templates (or overloading), this is just old swig magic
+    working at its best.
+  */
+
+  template <class C>
+    struct D
+    {
+      D(C v) : val(v) {}
+
+      /* note that here we are overloading the already super
+	 overloaded 'get_val1' */
+      friend C get_val1(D& b)
+      {
+	return b.val;
+      }
+
+      /* here set will be 'auto' overloaded, depending of the
+	 %template instantiations. */
+      friend void set(D& b, C v)
+      {
+	b.val = v;
+      }
+
+    private:
+      C val;
+    };
+
+  namespace ns1 {
+
+    void bas() {}
+
+    void baz() {}
+  }
+}
+
+// Use this version with extra qualifiers to test SWIG as some compilers accept this
+  namespace ns1 {
+    namespace ns2 {
+      class Foo {
+      public:
+	Foo::Foo() {};
+	friend void bar();
+	friend void ns1::baz();	
+	void Foo::member() { }
+	
+      };
+      void bar() {}    
+    }
+  }
+
+// Remove extra qualifiers for the compiler as some compilers won't compile the extra qaulification (eg gcc-4.1 onwards) 
+%{
+  namespace ns1 {
+    namespace ns2 {
+      class Foo {
+      public:
+	Foo() {};
+	friend void bar();
+	friend void ns1::baz();	
+	void member() { }
+	
+      };
+      void bar() {}    
+    }
+  }
+%}
+    
+
+%template(D_i) D<int>;
+%template(D_d) D<double>;
diff --git a/trunk/Examples/test-suite/funcptr.i b/trunk/Examples/test-suite/funcptr.i
new file mode 100644
index 0000000..dae1ec5
--- /dev/null
+++ b/trunk/Examples/test-suite/funcptr.i
@@ -0,0 +1,60 @@
+%module funcptr
+
+/*
+ Complicated one that should defeat just reading , to find
+ the number of arguments expected in the function pointer.
+extern void do(int (*op)(int (*i)(double, double), int j)); 
+*/
+
+%inline %{
+typedef double (*DistFun)(double* data, int r, int c, int i, int j, void *xdata);
+
+void distance(double *data, int *dim, DistFun fun,  double *output) {
+}
+
+typedef int (*Operator)(int i,int j);
+
+int do_op(int a, int b, int (*op)(int,int)) {
+  return (*op)(a,b);
+}
+
+int add(int a, int b) {
+  return a+b;
+}
+
+int subtract(int a, int b) {
+  return a-b;
+}
+
+int multiply(int a, int b) {
+  return a*b;
+}
+
+int *nowt() { 
+  return 0;
+}
+
+int *nowt2(void) { 
+  return 0;
+}
+
+struct MyStruct { int i; };
+typedef struct MyStruct * MyStructPtr;
+
+MyStructPtr mystructptr() { 
+  return 0;
+}
+
+typedef int * Integer;
+
+int (*funcvar)(int,int) = add;
+int * (*funcvar2)() = nowt;
+int * (*funcvar3)(void) = nowt2;
+Integer (*funcvar4)() = nowt;
+MyStructPtr (*funcvar5)() = mystructptr;
+
+void (*pfunc0)();
+int (*pfuncA)();
+void (*pfunc1)(int);
+void (*pfunc2)(int, double);
+%}
diff --git a/trunk/Examples/test-suite/function_typedef.i b/trunk/Examples/test-suite/function_typedef.i
new file mode 100644
index 0000000..718af9c
--- /dev/null
+++ b/trunk/Examples/test-suite/function_typedef.i
@@ -0,0 +1,20 @@
+%module function_typedef
+
+%inline %{
+
+typedef int binop_t(int, int);
+
+int do_binop1(binop_t f, int x, int y) {
+   return f(x,y);
+}
+
+int do_binop2(binop_t *f, int x, int y) {
+   return (*f)(x,y);
+}
+
+int do_binop3(int f(int,int), int x, int y) {
+   return f(x,y);
+}
+%}
+
+
diff --git a/trunk/Examples/test-suite/fvirtual.i b/trunk/Examples/test-suite/fvirtual.i
new file mode 100644
index 0000000..af189ed
--- /dev/null
+++ b/trunk/Examples/test-suite/fvirtual.i
@@ -0,0 +1,21 @@
+// This testcase tests corner cases for the -fvirtual optimisation flag.
+// Note that the test-suite does not actually run with -fvirtual at any point, but this can be tested using the SWIG_FEATURES=-fvirtual env variable.
+%module fvirtual
+
+// Test overloaded methods #1508327 (requires a scripting language runtime test)
+%inline %{
+  class Node {
+    public:
+      virtual int addChild( Node *child ) { return 1; }
+      virtual ~Node() {}
+  };
+
+  class NodeSwitch : public Node {
+    public :
+      virtual int addChild( Node *child ) { return 2; } // This was hidden with -fvirtual
+      virtual int addChild( Node *child, bool value ) { return 3; }
+      virtual ~NodeSwitch() {}
+  };
+%}
+
+
diff --git a/trunk/Examples/test-suite/global_ns_arg.i b/trunk/Examples/test-suite/global_ns_arg.i
new file mode 100644
index 0000000..3554fd8
--- /dev/null
+++ b/trunk/Examples/test-suite/global_ns_arg.i
@@ -0,0 +1,15 @@
+%module global_ns_arg
+
+%inline %{
+
+typedef int Integer;
+
+::Integer foo(::Integer x) {
+   return x;
+}
+
+::Integer bar() {
+   return 1;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/global_vars.i b/trunk/Examples/test-suite/global_vars.i
new file mode 100644
index 0000000..8c18bbd
--- /dev/null
+++ b/trunk/Examples/test-suite/global_vars.i
@@ -0,0 +1,31 @@
+%module global_vars
+
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);                   /* memory leak when setting a ptr/ref variable */
+
+%include std_string.i
+
+%inline %{
+
+  struct A 
+  {
+    int x;
+  };  
+
+  std::string b;
+  A a;
+  A *ap;
+  const A *cap;
+  A &ar = a;
+
+  int x;
+  int *xp;
+  int& c_member = x;
+
+  void *vp;
+
+  enum Hello { Hi, Hola };
+
+  Hello h;
+  Hello *hp;
+  Hello &hr = h;
+%}
diff --git a/trunk/Examples/test-suite/grouping.i b/trunk/Examples/test-suite/grouping.i
new file mode 100644
index 0000000..5632231
--- /dev/null
+++ b/trunk/Examples/test-suite/grouping.i
@@ -0,0 +1,31 @@
+%module grouping
+
+%inline %{
+
+typedef int Integer;
+
+int (test1)(int x) {
+   return x;
+}
+
+int *(test2)(int x) {
+    static int y;
+    y = x;
+    return &y;
+}
+
+int (test3) = 37;
+
+typedef Integer (UnaryOp)(Integer);
+
+Integer do_unary(Integer x, UnaryOp *f) {
+   return (*f)(x);
+}
+
+int negate(int x) {
+   return -x;
+}
+
+%}
+
+%constant UnaryOp *NEGATE = negate;
diff --git a/trunk/Examples/test-suite/guile/Makefile.in b/trunk/Examples/test-suite/guile/Makefile.in
new file mode 100644
index 0000000..97f30e3
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/Makefile.in
@@ -0,0 +1,61 @@
+#######################################################################
+# Makefile for guile test-suite
+#######################################################################
+
+LANGUAGE     = guile
+VARIANT      = _gh
+SCRIPTSUFFIX = _runme.scm
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+GUILE        = @GUILE@
+
+C_TEST_CASES = long_long list_vector pointer_in_out multivalue
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+# none!
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+# override the default in common.mk by adding SWIGOPT +=
+swig_and_compile_multi_cpp = \
+	for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \
+	  SWIGOPT=" -runtime "; \
+	  export SWIGOPT; \
+	  $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \
+	  SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \
+	  INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT) $$SWIGOPT" NOLINK=true \
+	  TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACE="$$f.i" \
+	  $(LANGUAGE)$(VARIANT)_cpp; \
+	  SWIGOPT=" -noruntime "; \
+	done
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.scm appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(GUILE) -l $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean
+%.clean:
+	@rm -f $*-guile
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile guile_clean
diff --git a/trunk/Examples/test-suite/guile/README b/trunk/Examples/test-suite/guile/README
new file mode 100644
index 0000000..37432ea
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/README
@@ -0,0 +1,4 @@
+See ../README for common README file.
+
+Any testcases which have _runme.scm appended after the testcase name will be detected and run.
+
diff --git a/trunk/Examples/test-suite/guile/casts_runme.scm b/trunk/Examples/test-suite/guile/casts_runme.scm
new file mode 100644
index 0000000..7a0a042
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/casts_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_casts_module" (dynamic-link "./libcasts.so"))
+(load "../schemerunme/casts.scm")
diff --git a/trunk/Examples/test-suite/guile/char_constant_runme.scm b/trunk/Examples/test-suite/guile/char_constant_runme.scm
new file mode 100644
index 0000000..d183b35
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/char_constant_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_char_constant_module" (dynamic-link "./libchar_constant.so"))
+(load "../schemerunme/char_constant.scm")
diff --git a/trunk/Examples/test-suite/guile/class_ignore_runme.scm b/trunk/Examples/test-suite/guile/class_ignore_runme.scm
new file mode 100644
index 0000000..b3229f8
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/class_ignore_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_class_ignore_module" (dynamic-link "./libclass_ignore.so"))
+(load "../schemerunme/class_ignore.scm")
diff --git a/trunk/Examples/test-suite/guile/constover_runme.scm b/trunk/Examples/test-suite/guile/constover_runme.scm
new file mode 100644
index 0000000..1ab42d3
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/constover_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_constover_module" (dynamic-link "./libconstover.so"))
+(load "../schemerunme/constover.scm")
diff --git a/trunk/Examples/test-suite/guile/contract_runme.scm b/trunk/Examples/test-suite/guile/contract_runme.scm
new file mode 100644
index 0000000..ea80e32
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/contract_runme.scm
@@ -0,0 +1,6 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_contract_module" (dynamic-link "./libcontract.so"))
+(load "testsuite.scm")
+(load "../schemerunme/contract.scm")
diff --git a/trunk/Examples/test-suite/guile/cpp_enum_runme.scm b/trunk/Examples/test-suite/guile/cpp_enum_runme.scm
new file mode 100644
index 0000000..5a2d9f0
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/cpp_enum_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_cpp_enum_module" (dynamic-link "./libcpp_enum.so"))
+(load "../schemerunme/cpp_enum.scm")
diff --git a/trunk/Examples/test-suite/guile/cpp_namespace_runme.scm b/trunk/Examples/test-suite/guile/cpp_namespace_runme.scm
new file mode 100644
index 0000000..2a871de
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/cpp_namespace_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_cpp_namespace_module" (dynamic-link "./libcpp_namespace.so"))
+(load "../schemerunme/cpp_namespace.scm")
diff --git a/trunk/Examples/test-suite/guile/dynamic_cast_runme.scm b/trunk/Examples/test-suite/guile/dynamic_cast_runme.scm
new file mode 100644
index 0000000..7b70001
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/dynamic_cast_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_dynamic_cast_module" (dynamic-link "./libdynamic_cast.so"))
+(load "../schemerunme/dynamic_cast.scm")
diff --git a/trunk/Examples/test-suite/guile/import_nomodule_runme.scm b/trunk/Examples/test-suite/guile/import_nomodule_runme.scm
new file mode 100644
index 0000000..ffb2474
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/import_nomodule_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_import_nomodule_module" (dynamic-link "./libimport_nomodule.so"))
+(load "../schemerunme/import_nomodule.scm")
diff --git a/trunk/Examples/test-suite/guile/imports_runme.scm b/trunk/Examples/test-suite/guile/imports_runme.scm
new file mode 100644
index 0000000..2fda017
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/imports_runme.scm
@@ -0,0 +1,11 @@
+;;; This file is part of a test for SF bug #231619. 
+;;; It shows that the %import directive does not work properly in SWIG
+;;; 1.3a5:  Type information is not properly generated if a base class
+;;; comes from an %import-ed file. 
+
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_imports_a_module" (dynamic-link "./libimports_a.so"))
+(dynamic-call "scm_init_imports_b_module" (dynamic-link "./libimports_b.so"))
+(load "../schemerunme/imports.scm")
diff --git a/trunk/Examples/test-suite/guile/inherit_missing_runme.scm b/trunk/Examples/test-suite/guile/inherit_missing_runme.scm
new file mode 100644
index 0000000..97e950c
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/inherit_missing_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_inherit_missing_module" (dynamic-link "./libinherit_missing.so"))
+(load "../schemerunme/inherit_missing.scm")
diff --git a/trunk/Examples/test-suite/guile/integers_runme.scm b/trunk/Examples/test-suite/guile/integers_runme.scm
new file mode 100644
index 0000000..14ec8b0
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/integers_runme.scm
@@ -0,0 +1,11 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_integers_module" (dynamic-link "./libintegers.so"))
+
+(define-macro (throws-exception? form)
+  `(catch #t
+     (lambda () ,form #f)
+     (lambda args #t)))
+
+(load "../schemerunme/integers.scm")
diff --git a/trunk/Examples/test-suite/guile/li_std_string_runme.scm b/trunk/Examples/test-suite/guile/li_std_string_runme.scm
new file mode 100644
index 0000000..05b74cd
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/li_std_string_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_li_std_string_module" (dynamic-link "./libli_std_string.so"))
+(load "../schemerunme/li_std_string.scm")
diff --git a/trunk/Examples/test-suite/guile/li_typemaps_runme.scm b/trunk/Examples/test-suite/guile/li_typemaps_runme.scm
new file mode 100644
index 0000000..9824fc9
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/li_typemaps_runme.scm
@@ -0,0 +1,18 @@
+;;; This is the union runtime testcase. It ensures that values within a
+;;; union embedded within a struct can be set and read correctly.
+
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_li_typemaps_module" (dynamic-link "./libli_typemaps.so"))
+(load "../schemerunme/li_typemaps.scm")
+
+(let ((lst (inoutr-int2 3 -2)))
+  (if (not (and (= (car lst) 3) (= (cadr lst) -2)))
+    (error "Error in inoutr-int2")))
+
+(let ((lst (out-foo 4)))
+  (if (not (and (= (Foo-a-get (car lst)) 4) (= (cadr lst) 8)))
+    (error "Error in out-foo")))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/guile/list_vector_runme.scm b/trunk/Examples/test-suite/guile/list_vector_runme.scm
new file mode 100644
index 0000000..546d8a1
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/list_vector_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_list_vector_module" (dynamic-link "./liblist_vector.so"))
+(load "../schemerunme/list_vector.scm")
diff --git a/trunk/Examples/test-suite/guile/multivalue_runme.scm b/trunk/Examples/test-suite/guile/multivalue_runme.scm
new file mode 100644
index 0000000..d1d7fbf
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/multivalue_runme.scm
@@ -0,0 +1,7 @@
+;;;; Automatic test of multiple return values
+
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_multivalue_module" (dynamic-link "./libmultivalue.so"))
+(load "../schemerunme/multivalue.scm")
diff --git a/trunk/Examples/test-suite/guile/name_runme.scm b/trunk/Examples/test-suite/guile/name_runme.scm
new file mode 100644
index 0000000..831c206
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/name_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_name_module" (dynamic-link "./libname.so"))
+(load "../schemerunme/name.scm")
diff --git a/trunk/Examples/test-suite/guile/overload_complicated_runme.scm b/trunk/Examples/test-suite/guile/overload_complicated_runme.scm
new file mode 100644
index 0000000..3c2b80d
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/overload_complicated_runme.scm
@@ -0,0 +1,21 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_overload_complicated_module" (dynamic-link "./liboverload_complicated.so"))
+
+(define-macro (check form)
+  `(if (not ,form)
+       (error "Check failed: " ',form)))
+
+(define (=~ a b)
+  (< (abs (- a b)) 1e-8))
+
+;; Check first method
+(check (=~ (foo 1 2 "bar" 4) 15))
+
+;; Check second method
+(check (=~ (foo 1 2) 4811.4))
+(check (=~ (foo 1 2 3.2) 4797.2))
+(check (=~ (foo 1 2 3.2 #\Q) 4798.2))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/guile/overload_copy_runme.scm b/trunk/Examples/test-suite/guile/overload_copy_runme.scm
new file mode 100644
index 0000000..9b93aeb
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/overload_copy_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_overload_copy_module" (dynamic-link "./liboverload_copy.so"))
+(load "../schemerunme/overload_copy.scm")
diff --git a/trunk/Examples/test-suite/guile/overload_extend_runme.scm b/trunk/Examples/test-suite/guile/overload_extend_runme.scm
new file mode 100644
index 0000000..cb0223d
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/overload_extend_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_overload_extend_module" (dynamic-link "./liboverload_extend.so"))
+(load "../schemerunme/overload_extend.scm")
diff --git a/trunk/Examples/test-suite/guile/overload_simple_runme.scm b/trunk/Examples/test-suite/guile/overload_simple_runme.scm
new file mode 100644
index 0000000..993a5f3
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/overload_simple_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_overload_simple_module" (dynamic-link "./liboverload_simple.so"))
+(load "../schemerunme/overload_simple.scm")
diff --git a/trunk/Examples/test-suite/guile/overload_subtype_runme.scm b/trunk/Examples/test-suite/guile/overload_subtype_runme.scm
new file mode 100644
index 0000000..7dfa2c1
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/overload_subtype_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_overload_subtype_module" (dynamic-link "./liboverload_subtype.so"))
+(load "../schemerunme/overload_subtype.scm")
diff --git a/trunk/Examples/test-suite/guile/pointer_in_out_runme.scm b/trunk/Examples/test-suite/guile/pointer_in_out_runme.scm
new file mode 100644
index 0000000..de35227
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/pointer_in_out_runme.scm
@@ -0,0 +1,5 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_pointer_in_out_module" (dynamic-link "./libpointer_in_out.so"))
+(load "../schemerunme/pointer_in_out.scm")
diff --git a/trunk/Examples/test-suite/guile/reference_global_vars_runme.scm b/trunk/Examples/test-suite/guile/reference_global_vars_runme.scm
new file mode 100644
index 0000000..8cd31c3
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/reference_global_vars_runme.scm
@@ -0,0 +1,3 @@
+; copied from python runme_.py
+(dynamic-call "scm_init_reference_global_vars_module" (dynamic-link "./libreference_global_vars.so"))
+(load "../schemerunme/reference_global_vars.scm")
diff --git a/trunk/Examples/test-suite/guile/testsuite.scm b/trunk/Examples/test-suite/guile/testsuite.scm
new file mode 100644
index 0000000..7f5fd71
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/testsuite.scm
@@ -0,0 +1,37 @@
+;; Little helper functions and macros for the run tests
+
+(use-modules (ice-9 format))
+
+(define (test-error error-format . args)
+  (display "Runtime check failed. ")
+  (apply format #t error-format args)
+  (newline)
+  (exit 1))
+
+(define-macro (expect-true form)
+  `(if (not ,form)
+       (test-error "Expected true value of ~A" ',form)))
+
+(define-macro (expect-false form)
+  `(if ,form
+       (test-error "Expected false value of ~A" ',form)))
+
+(define-macro (expect-result expected-result-form equal? form)
+  `(let ((expected-result ,expected-result-form)
+	 (result ,form))
+     (if (not (,equal? result expected-result))
+	 (test-error "The result of ~A was ~A, expected ~A, which is not ~A"
+		     ',form result expected-result ',equal?))))
+
+(define-macro (expect-throw tag-form form)
+  `(let ((tag ,tag-form))
+     (if (catch #t
+		(lambda ()
+		  ,form
+		  #t)
+		(lambda (key . args)
+		  (if (eq? key ,tag-form)
+		      #f
+		      (test-error "The form ~A threw to ~A (expected a throw to ~A)"
+				  ',form key tag))))
+	 (test-error "The form ~A returned normally (expected a throw to ~A)"))))
diff --git a/trunk/Examples/test-suite/guile/throw_exception_runme.scm b/trunk/Examples/test-suite/guile/throw_exception_runme.scm
new file mode 100644
index 0000000..3775062
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/throw_exception_runme.scm
@@ -0,0 +1,45 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_throw_exception_module" (dynamic-link "./libthrow_exception.so"))
+
+(define-macro (check-throw form)
+  `(catch 'swig-exception
+     (lambda ()
+       ,form
+       (error "Check failed (returned normally): " ',form))
+     (lambda (key result)
+       result)))
+
+(define-macro (check-throw-error form)
+  `(let ((result (check-throw ,form)))
+     (test-is-Error result)))
+
+(let ((foo (new-Foo)))
+  (let ((result (check-throw (Foo-test-int foo))))
+    (if (not (eqv? result 37))
+	(error "Foo-test-int failed, returned " result)))
+  (let ((result (check-throw (Foo-test-multi foo 1))))
+    (if (not (eqv? result 37))
+	(error "Foo-test-multi 1 failed, returned " result)))
+  (let ((result (check-throw (Foo-test-msg foo))))
+    (if (not (and (string? result)
+		  (string=? result "Dead")))
+	(error "Foo-test-msg failed, returned " result)))
+  (let ((result (check-throw (Foo-test-multi foo 2))))
+    (if (not (and (string? result)
+		  (string=? result "Dead")))
+	(error "Foo-test-multi 2 failed, returned " result)))
+  (check-throw-error (Foo-test-cls foo))
+  (check-throw-error (Foo-test-multi foo 3))
+  (check-throw-error (Foo-test-cls-ptr foo))
+  (check-throw-error (Foo-test-cls-ref foo))
+  ;; Namespace stuff
+  (let ((result (check-throw (Foo-test-enum foo))))
+    (if (not (eqv? result (enum2)))
+	(error "Foo-test-enum failed, returned " result)))
+  (check-throw-error (Foo-test-cls-td foo))
+  (check-throw-error (Foo-test-cls-ptr-td foo))
+  (check-throw-error (Foo-test-cls-ref-td foo)))
+  			      
+(exit 0)
diff --git a/trunk/Examples/test-suite/guile/typedef_inherit_runme.scm b/trunk/Examples/test-suite/guile/typedef_inherit_runme.scm
new file mode 100644
index 0000000..d75d421
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/typedef_inherit_runme.scm
@@ -0,0 +1,2 @@
+(dynamic-call "scm_init_typedef_inherit_module" (dynamic-link "./libtypedef_inherit.so"))
+(load "../schemerunme/typedef_inherit.scm")
diff --git a/trunk/Examples/test-suite/guile/typename_runme.scm b/trunk/Examples/test-suite/guile/typename_runme.scm
new file mode 100644
index 0000000..4243f69
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/typename_runme.scm
@@ -0,0 +1,3 @@
+(dynamic-call "scm_init_typename_module" (dynamic-link "./libtypename.so"))
+;;(dynamic-call "scm_init_types_module" (dynamic-link "./libtypes.so"))
+(load "../schemerunme/typename.scm")
diff --git a/trunk/Examples/test-suite/guile/unions_runme.scm b/trunk/Examples/test-suite/guile/unions_runme.scm
new file mode 100644
index 0000000..867e8a3
--- /dev/null
+++ b/trunk/Examples/test-suite/guile/unions_runme.scm
@@ -0,0 +1,8 @@
+;;; This is the union runtime testcase. It ensures that values within a
+;;; union embedded within a struct can be set and read correctly.
+
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(dynamic-call "scm_init_unions_module" (dynamic-link "./libunions.so"))
+(load "../schemerunme/unions.scm")
diff --git a/trunk/Examples/test-suite/guilescm/Makefile.in b/trunk/Examples/test-suite/guilescm/Makefile.in
new file mode 100644
index 0000000..04de236
--- /dev/null
+++ b/trunk/Examples/test-suite/guilescm/Makefile.in
@@ -0,0 +1,54 @@
+#######################################################################
+# Makefile for guile test-suite (with SCM API)
+#######################################################################
+
+EXTRA_TEST_CASES += ext_test.externaltest
+
+include ../guile/Makefile
+
+INCLUDES += -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/guilescm
+
+VARIANT      =
+# Refer to the guile directory for the run scripts
+SCRIPTPREFIX = ../guile/
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.scm appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(GUILE) -l $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+setup = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then	  \
+	  echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE) (with SCM API)" ; \
+	else								  \
+	  echo "$(ACTION)ing testcase $* under $(LANGUAGE) (with SCM API)" ;		  \
+	fi;
+
+swig_and_compile_multi_cpp = \
+	for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \
+	  $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \
+	  SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \
+	  INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT) $$SWIGOPT" NOLINK=true \
+	  TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACE="$$f.i" \
+	  $(LANGUAGE)$(VARIANT)_cpp; \
+	done
+
+%.externaltest:
+	$(local_setup)
+	+$(swig_and_compile_external)
+	$(local_run_testcase)
+	
+# Same as setup and run_testcase, but without the SCRIPTPREFIX (so the runme comes from the guilescm directory)
+local_setup = \
+	if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then	  \
+	  echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE) (with SCM API)" ; \
+	else								  \
+	  echo "$(ACTION)ing testcase $* under $(LANGUAGE) (with SCM API)" ;		  \
+	fi;
+
+local_run_testcase = \
+	if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(GUILE) -l $(srcdir)/$*$(SCRIPTSUFFIX);) \
+	fi;
diff --git a/trunk/Examples/test-suite/guilescm/ext_test.i b/trunk/Examples/test-suite/guilescm/ext_test.i
new file mode 100644
index 0000000..8b117bb
--- /dev/null
+++ b/trunk/Examples/test-suite/guilescm/ext_test.i
@@ -0,0 +1,19 @@
+%module ext_test
+
+/* just use the imports_a.h header... for this test we only need a class */
+%{
+#include "imports_a.h"
+%}
+
+%include "imports_a.h"
+
+%{
+SCM test_create();
+SCM test_is_pointer(SCM val);
+%}
+
+%init %{
+  scm_c_define_gsubr("test-create", 0, 0, 0, (swig_guile_proc) test_create);
+  scm_c_define_gsubr("test-is-pointer", 1, 0, 0, (swig_guile_proc) test_is_pointer);
+%}
+
diff --git a/trunk/Examples/test-suite/guilescm/ext_test_external.cxx b/trunk/Examples/test-suite/guilescm/ext_test_external.cxx
new file mode 100644
index 0000000..4b65f49
--- /dev/null
+++ b/trunk/Examples/test-suite/guilescm/ext_test_external.cxx
@@ -0,0 +1,24 @@
+#include <ext_test_wrap_hdr.h>
+#include <imports_a.h>
+
+SCM test_create()
+{
+#define FUNC_NAME "test-create"
+  SCM result;
+  A *newobj;
+  swig_type_info *type;
+  
+  newobj = new A();
+  type = SWIG_TypeQuery("A *");
+  result = SWIG_NewPointerObj(result, type, 1);
+  
+  return result;
+#undef FUNC_NAME
+}
+
+SCM test_is_pointer(SCM val)
+{
+#define FUNC_NAME "test-is-pointer"
+  return SCM_BOOL(SWIG_IsPointer(val));
+#undef FUNC_NAME
+}
diff --git a/trunk/Examples/test-suite/guilescm/ext_test_runme.scm b/trunk/Examples/test-suite/guilescm/ext_test_runme.scm
new file mode 100644
index 0000000..67add84
--- /dev/null
+++ b/trunk/Examples/test-suite/guilescm/ext_test_runme.scm
@@ -0,0 +1,19 @@
+(dynamic-call "scm_init_ext_test_module" (dynamic-link "./libext_test.so"))
+
+; This is a test for SF Bug 1573892
+; If IsPointer is called before TypeQuery, the test-is-pointer will fail
+; (i.e if the bottom two lines were moved to the top, the old code would succeed)
+; only a problem when is-pointer is called first
+
+(define a (new-A))
+
+(if (not (test-is-pointer a))
+  (error "test-is-pointer failed!"))
+
+(if (test-is-pointer 5)
+  (error "test-is-pointer thinks 5 is a pointer!"))
+
+(define b (test-create))
+(A-hello b)
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/ignore_parameter.i b/trunk/Examples/test-suite/ignore_parameter.i
new file mode 100644
index 0000000..bc0892c
--- /dev/null
+++ b/trunk/Examples/test-suite/ignore_parameter.i
@@ -0,0 +1,42 @@
+// Test for %typemap(ignore)
+
+%module ignore_parameter
+
+%typemap(in,numinputs=0) char* a "static const char* hi = \"hello\"; $1 = const_cast<char *>(hi);";
+%typemap(in,numinputs=0) int bb "$1 = 101;";
+%typemap(in,numinputs=0) double ccc "$1 = 8.8;";
+
+%typemap(freearg) char* a ""; // ensure freearg is not generated (needed for Java at least)
+
+%inline %{
+// global function tests
+char* jaguar(char* a, int b, double c) { return a; }
+int lotus(char* aa, int bb, double cc) { return bb; }
+double tvr(char* aaa, int bbb, double ccc) { return ccc; }
+int ferrari(int bb) { return bb; }
+
+// member function tests
+struct SportsCars {
+  char* daimler(char* a, int b, double c) { return a; }
+  int astonmartin(char* aa, int bb, double cc) { return bb; }
+  double bugatti(char* aaa, int bbb, double ccc) { return ccc; }
+  int lamborghini(int bb) { return bb; }
+};
+
+// constructor tests
+struct MiniCooper {
+    MiniCooper(char* a, int b, double c) {}
+};
+struct MorrisMinor {
+    MorrisMinor(char* aa, int bb, double cc) {}
+};
+struct FordAnglia {
+    FordAnglia(char* aaa, int bbb, double ccc) {}
+};
+struct AustinAllegro {
+    AustinAllegro(int bb) {}
+};
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/ignore_template_constructor.i b/trunk/Examples/test-suite/ignore_template_constructor.i
new file mode 100644
index 0000000..5225d51
--- /dev/null
+++ b/trunk/Examples/test-suite/ignore_template_constructor.i
@@ -0,0 +1,39 @@
+%module ignore_template_constructor
+%include std_vector.i
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGPERL) || defined(SWIGRUBY) 
+#define SWIG_GOOD_VECTOR
+%ignore std::vector<Flow>::vector(size_type);
+%ignore std::vector<Flow>::resize(size_type);
+#endif
+
+#if defined(SWIGTCL) || defined(SWIGPERL)
+#define SWIG_GOOD_VECTOR
+/* here, for languages with bad declaration */
+%ignore std::vector<Flow>::vector(unsigned int);
+%ignore std::vector<Flow>::resize(unsigned int);
+#endif
+
+#if defined(SWIG_GOOD_VECTOR)
+%inline %{
+class Flow {
+  Flow() {}
+public:
+  Flow(double d) {}
+};
+%}
+
+#else
+/* here, for languages with bad typemaps */
+
+%inline %{
+class Flow {
+public:
+  Flow() {}
+  Flow(double d) {}
+};
+%}
+
+#endif
+
+%template(VectFlow) std::vector<Flow>;
diff --git a/trunk/Examples/test-suite/immutable.i b/trunk/Examples/test-suite/immutable.i
new file mode 100644
index 0000000..ff5081e
--- /dev/null
+++ b/trunk/Examples/test-suite/immutable.i
@@ -0,0 +1,20 @@
+// test to make sure setters are not generated for constants
+
+%module immutable
+
+
+%immutable;
+%mutable;
+
+%inline %{
+#define ABC -11
+enum count {Zero, One, Two}; %}
+
+
+%clearimmutable;
+
+%inline %{
+#define XYZ -22
+enum backwards {Tre=3, Duo=2, Uno=1};
+%}
+
diff --git a/trunk/Examples/test-suite/import_nomodule.h b/trunk/Examples/test-suite/import_nomodule.h
new file mode 100644
index 0000000..2e80e72
--- /dev/null
+++ b/trunk/Examples/test-suite/import_nomodule.h
@@ -0,0 +1,2 @@
+class Foo { };
+typedef int Integer;
diff --git a/trunk/Examples/test-suite/import_nomodule.i b/trunk/Examples/test-suite/import_nomodule.i
new file mode 100644
index 0000000..5d51153
--- /dev/null
+++ b/trunk/Examples/test-suite/import_nomodule.i
@@ -0,0 +1,39 @@
+%module import_nomodule
+%{
+#include "import_nomodule.h"
+%}
+
+%import "import_nomodule.h"
+
+#if !defined(SWIGJAVA) && !defined(SWIGRUBY) && !defined(SWIGCSHARP)
+
+/**
+ * The proxy class does not have Bar derived from Foo, yet an instance of Bar
+ * can successfully be passed to a proxy function taking a Foo pointer (for some
+ * language modules).
+ * 
+ * This violation of the type system is not possible in Java and C# due to static
+ * type checking. It's also not (currently) possible in Ruby, but this may be
+ * fixable (needs more investigation).
+ */
+
+%newobject create_Foo;
+%delobject delete_Foo;
+
+%inline %{
+Foo *create_Foo() {
+   return new Foo();
+}
+
+void delete_Foo(Foo *f) {
+   delete f;
+}
+
+void test1(Foo *f, Integer x) { }
+
+class Bar : public Foo { };
+
+%}
+
+#endif
+
diff --git a/trunk/Examples/test-suite/imports.list b/trunk/Examples/test-suite/imports.list
new file mode 100644
index 0000000..36c0802
--- /dev/null
+++ b/trunk/Examples/test-suite/imports.list
@@ -0,0 +1,2 @@
+imports_a
+imports_b
diff --git a/trunk/Examples/test-suite/imports_a.h b/trunk/Examples/test-suite/imports_a.h
new file mode 100644
index 0000000..f761ea3
--- /dev/null
+++ b/trunk/Examples/test-suite/imports_a.h
@@ -0,0 +1,21 @@
+#ifndef a_h
+#define a_h
+enum GlobalEnum { globalenum1=1, globalenum2 };
+
+/* This function should be static as it will be emitted into the code for
+ * every module.  All _static targets would fail here with a multiple 
+ * definition if this is not static. */
+static GlobalEnum global_test(GlobalEnum e) { return e; }
+
+class A { 
+ public: 
+  A() {}
+  virtual ~A() {}
+  
+  void hello() {}
+
+  enum MemberEnum { memberenum1=10, memberenum2 };
+  virtual MemberEnum member_virtual_test(MemberEnum e) { return e; }
+  virtual GlobalEnum global_virtual_test(GlobalEnum e) { return global_test(e); }
+};
+#endif
diff --git a/trunk/Examples/test-suite/imports_a.i b/trunk/Examples/test-suite/imports_a.i
new file mode 100644
index 0000000..562a148
--- /dev/null
+++ b/trunk/Examples/test-suite/imports_a.i
@@ -0,0 +1,15 @@
+/* This file is part of a test for SF bug #231619. 
+   It shows that the %import directive does not work properly in SWIG
+   1.3a5:  Type information is not properly generated if a base class
+   comes from an %import-ed file. */
+
+%module imports_a
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) A::MemberEnum; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) GlobalEnum; /* Ruby, wrong constant name */
+
+%{ 
+  #include "imports_a.h" 
+%} 
+
+%include "imports_a.h"
diff --git a/trunk/Examples/test-suite/imports_b.h b/trunk/Examples/test-suite/imports_b.h
new file mode 100644
index 0000000..f50cee5
--- /dev/null
+++ b/trunk/Examples/test-suite/imports_b.h
@@ -0,0 +1,31 @@
+#include "imports_a.h"
+
+class B : public A 
+{ 
+ public: 
+  B() {};
+  
+  void bye() {} ;
+
+  virtual MemberEnum member_virtual_test(MemberEnum e) { return memberenum2; }
+  virtual GlobalEnum global_virtual_test(GlobalEnum e) { return globalenum2; }
+};
+
+A::MemberEnum global_test(A::MemberEnum e) { return e; }
+
+struct C : A
+{
+  typedef A a_type;
+
+  A* get_a(A* a)
+  {
+    return a;
+  }
+  
+  a_type* get_a_type(a_type* a)
+  {
+    return a;
+  }
+  
+};
+
diff --git a/trunk/Examples/test-suite/imports_b.i b/trunk/Examples/test-suite/imports_b.i
new file mode 100644
index 0000000..afc573a
--- /dev/null
+++ b/trunk/Examples/test-suite/imports_b.i
@@ -0,0 +1,42 @@
+/* This file is part of a test for SF bug #231619. 
+   It shows that the %import directive does not work properly in SWIG
+   1.3a5:  Type information is not properly generated if a base class
+   comes from an %import-ed file. 
+
+   Extra tests added for enums to test languages that have enum types.
+*/
+
+%module imports_b
+
+%{ 
+#include "imports_b.h" 
+%} 
+
+
+/* 
+   To import, you can use either
+   
+     %import "imports_a.i"
+
+   or
+
+     %import(module="imports_a") "imports_a.h" 
+
+
+   In the first case, imports_a.i should declare the module name using
+   the %module directive.
+
+   In the second case, the file could be either a .h file, where no
+   %module directive will be found, or a swig interface file, where
+   the module option will take priority over any %module directive
+   inside the imported file.
+
+*/
+
+#if 0
+%import "imports_a.i"
+#else
+%import(module="imports_a") "imports_a.h" 
+#endif
+
+%include "imports_b.h"  
diff --git a/trunk/Examples/test-suite/inctest.h b/trunk/Examples/test-suite/inctest.h
new file mode 100644
index 0000000..e63d833
--- /dev/null
+++ b/trunk/Examples/test-suite/inctest.h
@@ -0,0 +1,2 @@
+int IntegerMember;
+double DoubleMember;
diff --git a/trunk/Examples/test-suite/inctest.i b/trunk/Examples/test-suite/inctest.i
new file mode 100644
index 0000000..f333042
--- /dev/null
+++ b/trunk/Examples/test-suite/inctest.i
@@ -0,0 +1,35 @@
+%module inctest
+
+ //
+ // This test fails if swig is not able to include
+ // the following two files:
+ //
+ //   'testdir/subdir1/hello.i'
+ //   'testdir/subdir2/hello.i'
+ //
+ // since they have the same basename 'hello', swig is only
+ // including one. This is not right, it must include both,
+ // as the well known compilers do.
+ //
+ // Also repeats the test for the import directive in subdirectories
+
+%include "testdir/test.i"
+
+
+// Bug #1162194
+%inline %{
+typedef struct {
+#include "inctest.h"
+} MY_TYPES;
+
+%}
+
+%{
+typedef struct {
+#include "inctest.h"
+} MY_THINGS;
+%}
+
+typedef struct {
+%include "inctest.h"
+} MY_THINGS;
diff --git a/trunk/Examples/test-suite/inherit.i b/trunk/Examples/test-suite/inherit.i
new file mode 100644
index 0000000..e4eee23
--- /dev/null
+++ b/trunk/Examples/test-suite/inherit.i
@@ -0,0 +1,19 @@
+// Test that was failing for Perl - the non-member Foo was being called when the member version was intended
+%module inherit
+
+%inline %{
+
+const char* Foo(void) {
+  return "Non-member Foo";
+}
+
+class CBase {
+public:
+  const char* Foo(void) {
+    return "CBase::Foo";
+  }
+};
+
+class CDerived : public CBase {};
+
+%}
diff --git a/trunk/Examples/test-suite/inherit_missing.i b/trunk/Examples/test-suite/inherit_missing.i
new file mode 100644
index 0000000..5ef50c5
--- /dev/null
+++ b/trunk/Examples/test-suite/inherit_missing.i
@@ -0,0 +1,51 @@
+// Tests handling of inheritance when a base class isn't provided to SWIG
+%module inherit_missing
+
+%warnfilter(402);
+
+%{
+/* Define the class internally, but don't tell SWIG about it */
+class Foo {
+public:
+     virtual ~Foo() {}
+     virtual char *blah() {
+	return (char *) "Foo::blah";
+     }
+};
+%}
+
+/* Forward declaration.  Says that Foo is a class, but doesn't provide a definition */
+
+class Foo;
+
+%newobject new_Foo;
+%delobject delete_Foo;
+%inline %{
+
+class Bar : public Foo {
+ public:
+  virtual ~Bar() {}
+  virtual char *blah() {
+    return (char *) "Bar::blah";
+  };
+};
+
+class Spam : public Bar {
+  public:
+  virtual char *blah() {
+    return (char *) "Spam::blah";
+  };
+};
+
+Foo *new_Foo() {
+   return new Foo();
+}
+
+void delete_Foo(Foo *f) {
+   delete f;
+}
+
+char *do_blah(Foo *f) {
+  return f->blah();
+}
+%}
diff --git a/trunk/Examples/test-suite/inherit_same_name.i b/trunk/Examples/test-suite/inherit_same_name.i
new file mode 100644
index 0000000..e50d064
--- /dev/null
+++ b/trunk/Examples/test-suite/inherit_same_name.i
@@ -0,0 +1,16 @@
+%module inherit_same_name
+
+%inline %{
+  struct Base {
+    Base() : MethodOrVariable(0) {}
+    virtual ~Base() {}
+  protected:
+    int MethodOrVariable;
+  };
+  struct Derived : Base {
+    virtual void MethodOrVariable() { Base::MethodOrVariable = 10; }
+  };
+  struct Bottom : Derived {
+    void MethodOrVariable() {}
+  };
+%}
diff --git a/trunk/Examples/test-suite/inherit_target_language.i b/trunk/Examples/test-suite/inherit_target_language.i
new file mode 100644
index 0000000..770e11d
--- /dev/null
+++ b/trunk/Examples/test-suite/inherit_target_language.i
@@ -0,0 +1,63 @@
+// Test using a target language specified base class, primarily for Java/C# and possibly other single inheritance languages
+
+// Note the multiple inheritance warnings don't appear because of the two techniques used in here: typemaps and %ignore
+
+%module inherit_target_language
+
+#if defined(SWIGJAVA)
+# define csbase javabase
+#endif
+
+%pragma(csharp) moduleimports=%{
+using System;
+using System.Runtime.InteropServices;
+public class TargetLanguageBase { public virtual void targetLanguageBaseMethod() {} };
+%}
+
+%pragma(java) moduleimports=%{
+class TargetLanguageBase { public void targetLanguageBaseMethod() {} };
+%}
+
+
+%typemap(csbase) SWIGTYPE "TargetLanguageBase"
+
+// Two ways to replace a C++ base with a completely different target language base
+%ignore Base1; // another way to use the target language base
+%typemap(csbase, replace="1") Derived2 "TargetLanguageBase"
+
+%inline %{
+struct Base1 { virtual ~Base1() {} };
+struct Base2 { virtual ~Base2() {} };
+struct Derived1 : Base1 {};
+struct Derived2 : Base2 {};
+%}
+
+// Multiple inheritance
+%ignore MBase1a;
+%ignore MBase1b;
+%typemap(csbase, replace="1") MultipleDerived2 "TargetLanguageBase"
+
+%inline %{
+struct MBase1a { virtual ~MBase1a() {} virtual void a() {} };
+struct MBase1b { virtual ~MBase1b() {} virtual void b() {} };
+struct MBase2a { virtual ~MBase2a() {} virtual void c() {} };
+struct MBase2b { virtual ~MBase2b() {} virtual void d() {} };
+struct MultipleDerived1 : MBase1a, MBase1b {};
+struct MultipleDerived2 : MBase1a, MBase2b {};
+%}
+
+
+%ignore MBase3a;
+%ignore MBase4b;
+%typemap(csbase) MultipleDerived3 ""
+%typemap(csbase) MultipleDerived4 ""
+
+%inline %{
+struct MBase3a { virtual ~MBase3a() {} virtual void e() {} };
+struct MBase3b { virtual ~MBase3b() {} virtual void f() {} };
+struct MBase4a { virtual ~MBase4a() {} virtual void g() {} };
+struct MBase4b { virtual ~MBase4b() {} virtual void h() {} };
+struct MultipleDerived3 : MBase3a, MBase3b {};
+struct MultipleDerived4 : MBase4a, MBase4b {};
+%}
+
diff --git a/trunk/Examples/test-suite/inherit_void_arg.i b/trunk/Examples/test-suite/inherit_void_arg.i
new file mode 100644
index 0000000..9b04038
--- /dev/null
+++ b/trunk/Examples/test-suite/inherit_void_arg.i
@@ -0,0 +1,18 @@
+%module inherit_void_arg
+
+%inline %{
+
+class A {
+public:
+        virtual ~A() { }
+  
+	virtual void f(void) = 0;
+};
+
+class B : public A {
+public:
+        void f() { }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/inline_initializer.i b/trunk/Examples/test-suite/inline_initializer.i
new file mode 100644
index 0000000..35da6da
--- /dev/null
+++ b/trunk/Examples/test-suite/inline_initializer.i
@@ -0,0 +1,12 @@
+%module inline_initializer
+
+%inline %{
+class Foo {
+   int x;
+public:
+   Foo(int a);
+};
+
+Foo::Foo(int a) : x(a) { }
+
+%}
diff --git a/trunk/Examples/test-suite/integers.i b/trunk/Examples/test-suite/integers.i
new file mode 100644
index 0000000..7f78a2a
--- /dev/null
+++ b/trunk/Examples/test-suite/integers.i
@@ -0,0 +1,20 @@
+/* This test case is meant to be used with run tests that check that
+   -- the whole range of the integer types is supported;
+   -- errors are signalled when out-of-range values are passed.
+*/
+
+%module integers;
+
+%inline %{
+  signed char signed_char_identity(signed char x) { return x; }
+  unsigned char unsigned_char_identity(unsigned char x) { return x; }
+  signed short signed_short_identity(signed short x) { return x; }
+  unsigned short unsigned_short_identity(unsigned short x) { return x; }
+  signed int signed_int_identity(signed int x) { return x; }
+  unsigned int unsigned_int_identity(unsigned int x) { return x; }
+  signed long signed_long_identity(signed long x) { return x; }
+  unsigned long unsigned_long_identity(unsigned long x) { return x; }
+  signed long long signed_long_long_identity(signed long long x) { return x; }
+  unsigned long long unsigned_long_long_identity(unsigned long long x) { return x; }
+%}
+
diff --git a/trunk/Examples/test-suite/intermediary_classname.i b/trunk/Examples/test-suite/intermediary_classname.i
new file mode 100644
index 0000000..0f90f9c
--- /dev/null
+++ b/trunk/Examples/test-suite/intermediary_classname.i
@@ -0,0 +1,81 @@
+
+// This test is to check the intermediary class name can be changed (C# and Java only use intermediary classes at time of writing)
+%module(directors="1", jniclassname="intermediary_classname", imclassname="intermediary_classname") "intermediary_classname"
+
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR);
+
+// change the access to the intermediary class for testing purposes
+%pragma(java) jniclassclassmodifiers="public class";
+%pragma(csharp) imclassclassmodifiers="public class";
+
+%feature("director") Base;
+%feature("director") Derived;
+
+// Test the throws attribute in these typemaps
+%typemap(javadirectorout, throws="InstantiationException/*javadirectorout Base&*/") Base& 
+  "$javaclassname.getCPtr($javacall)/* XYZ& typemap directorout*/"
+%typemap(javadirectorin, throws="ClassNotFoundException/*javadirectorin Base&*/") Base&
+  "new $javaclassname($jniinput, false)/*javadirectorin*/"
+%typemap(out, throws="IllegalAccessException/*out Base&*/") Base& {
+  // XYZ& typemap out
+}
+%inline %{
+
+template<class T> T maximum(const T a, const T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+  void testconst(const T x) { }
+};
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+class Base {
+public:
+  Base() : mVectInt(0) {}
+  Base(Base *b) : mVectInt(0) {}
+  virtual ~Base() {}
+  virtual Base& m1(Base &b) { return b; }
+  virtual Base& m1out() { static Base b; return b; }
+  virtual Base* m2(Base *b) { return b; }
+//  virtual Base m3(Base b) { return b; }
+  vector<int> mVectInt;
+  int mInt;
+  enum en { en1, en2 };
+  en enummethod(en e) { return e; }
+};
+class Derived : public Base {
+public:
+  Derived(Base *b) : Base(b) {}
+  virtual Base& m1(Base &b) { return b; }
+  virtual Base* m2(Base *b) { return b; }
+//  virtual Base m3(Base b) { return b; }
+  void throwspec() throw (int, Base) {}
+};
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%template(maxint) maximum<int>;
+%template(maxdouble) maximum<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+%template(maxintp) maximum<int (*)[10]>;
+%template(vecintp) vector<int (*)[10]>;
+
+
diff --git a/trunk/Examples/test-suite/java/Makefile.in b/trunk/Examples/test-suite/java/Makefile.in
new file mode 100644
index 0000000..ace8dee
--- /dev/null
+++ b/trunk/Examples/test-suite/java/Makefile.in
@@ -0,0 +1,85 @@
+#######################################################################
+# Makefile for java test-suite
+#######################################################################
+
+LANGUAGE     = java
+JAVA         = java
+JAVAC        = javac
+SCRIPTSUFFIX = _runme.java
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@/..
+top_builddir = @top_builddir@/..
+
+C_TEST_CASES = \
+	java_lib_arrays \
+	java_lib_various
+
+CPP_TEST_CASES = \
+	enum_thorough_proper \
+	enum_thorough_simple \
+	enum_thorough_typeunsafe \
+	exception_partial_info \
+	intermediary_classname \
+	java_constants \
+	java_director \
+	java_enums \
+	java_lib_arrays_dimensionless \
+	java_lib_various \
+	java_jnitypes \
+	java_pgcpp \
+	java_pragmas \
+	java_prepost \
+	java_throws \
+	java_typemaps_proxy \
+	java_typemaps_typewrapper
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+SWIGOPT += -package $*
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+(cd $* && $(swig_and_compile_cpp))
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+(cd $* && $(swig_and_compile_c))
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+(cd $* && $(swig_and_compile_multi_cpp))
+	$(run_testcase)
+
+# Makes a directory for the testcase if it does not exist
+setup = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then	  \
+	  echo "$(ACTION)ing testcase $* (with run test) under $(LANGUAGE)" ; \
+	else								  \
+	  echo "$(ACTION)ing testcase $* under $(LANGUAGE)" ;		  \
+	fi;								  \
+	if [ ! -d $* ]; then						  \
+		mkdir $*;						  \
+	fi;
+
+# Compiles java files then runs the testcase. A testcase is only run if
+# a file is found which has _runme.java appended after the testcase name.
+# Note Java uses LD_LIBRARY_PATH under Unix, PATH under Cygwin/Windows, SHLIB_PATH on HPUX and DYLD_LIBRARY_PATH on Mac OS X.
+run_testcase = \
+	(cd $* && $(COMPILETOOL) $(JAVAC) -classpath . *.java) && \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  $(COMPILETOOL) $(JAVAC) -classpath . -d . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && 	  \
+	  env LD_LIBRARY_PATH="$*:$$LD_LIBRARY_PATH" PATH="$*:$$PATH" SHLIB_PATH="$*:$$SHLIB_PATH" DYLD_LIBRARY_PATH="$*:$$DYLD_LIBRARY_PATH" $(RUNTOOL) $(JAVA) -classpath . $*\_runme;) \
+	fi;
+
+# Clean: remove testcase directories
+%.clean:
+	@if [ -d $* ]; then \
+		rm -rf $*; \
+	fi;
+
+clean:
+	@rm -f *.class hs_err*.log
diff --git a/trunk/Examples/test-suite/java/README b/trunk/Examples/test-suite/java/README
new file mode 100644
index 0000000..b8b7416
--- /dev/null
+++ b/trunk/Examples/test-suite/java/README
@@ -0,0 +1,6 @@
+See ../README for common README file.
+
+The Java implementation of the test-suite is a little different to the other languages in that all of SWIGs output goes into a subdirectory named after the individual test case. This is so that all the shadow classes can be compiled as Java classes have to go into separate files. Otherwise the Makefile wouldn't know which .java files would be relevant to the testcase. For this to work the testcase must go into a Java package.
+
+Any testcases which have _runme.java appended after the testcase name will be detected and run.
+
diff --git a/trunk/Examples/test-suite/java/aggregate_runme.java b/trunk/Examples/test-suite/java/aggregate_runme.java
new file mode 100644
index 0000000..f25728b
--- /dev/null
+++ b/trunk/Examples/test-suite/java/aggregate_runme.java
@@ -0,0 +1,39 @@
+
+import aggregate.*;
+
+public class aggregate_runme {
+
+  static {
+    try {
+	System.loadLibrary("aggregate");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+      // Confirm that move() returns correct results under normal use
+      int result = aggregate.move(aggregate.UP);
+      if (result != aggregate.UP) throw new RuntimeException("UP failed");
+
+      result = aggregate.move(aggregate.DOWN);
+      if (result != aggregate.DOWN) throw new RuntimeException("DOWN failed");
+
+      result = aggregate.move(aggregate.LEFT);
+      if (result != aggregate.LEFT) throw new RuntimeException("LEFT failed");
+
+      result = aggregate.move(aggregate.RIGHT);
+      if (result != aggregate.RIGHT) throw new RuntimeException("RIGHT failed");
+
+      // Confirm that move() raises an exception when the contract is violated
+      try {
+        aggregate.move(0);
+        throw new RuntimeException("0 test failed");
+      }
+      catch (IllegalArgumentException e) {
+      }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/allprotected_runme.java b/trunk/Examples/test-suite/java/allprotected_runme.java
new file mode 100755
index 0000000..aa5413a
--- /dev/null
+++ b/trunk/Examples/test-suite/java/allprotected_runme.java
@@ -0,0 +1,74 @@
+import allprotected.*;
+
+public class allprotected_runme {
+  static {
+    try {
+      System.loadLibrary("allprotected");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    MyProtectedBase mpb = new MyProtectedBase("MyProtectedBase");
+    mpb.accessProtected();
+  }
+}
+
+class MyProtectedBase extends ProtectedBase
+{
+  MyProtectedBase(String name) {
+    super(name);
+  }
+  void accessProtected() {
+    String s = virtualMethod();
+    if (!s.equals("ProtectedBase"))
+      throw new RuntimeException("Failed");
+
+    Klass k = instanceMethod(new Klass("xyz"));
+    if (!k.getName().equals("xyz")) 
+      throw new RuntimeException("Failed");
+
+    k = instanceOverloaded(new Klass("xyz"));
+    if (!k.getName().equals("xyz")) 
+      throw new RuntimeException("Failed");
+
+    k = instanceOverloaded(new Klass("xyz"), "abc");
+    if (!k.getName().equals("abc")) 
+      throw new RuntimeException("Failed");
+
+    k = ProtectedBase.staticMethod(new Klass("abc"));
+    if (!k.getName().equals("abc")) 
+      throw new RuntimeException("Failed");
+
+    k = ProtectedBase.staticOverloaded(new Klass("xyz"));
+    if (!k.getName().equals("xyz")) 
+      throw new RuntimeException("Failed");
+
+    k = ProtectedBase.staticOverloaded(new Klass("xyz"), "abc");
+    if (!k.getName().equals("abc")) 
+      throw new RuntimeException("Failed");
+
+    setInstanceMemberVariable(30);
+    int i = getInstanceMemberVariable();
+    if (i != 30)
+      throw new RuntimeException("Failed");
+
+    setStaticMemberVariable(40);
+    i = getStaticMemberVariable();
+    if (i != 40)
+      throw new RuntimeException("Failed");
+
+    i = staticConstMemberVariable;
+    if (i != 20)
+      throw new RuntimeException("Failed");
+
+    setAnEnum(ProtectedBase.AnEnum.EnumVal1);
+    ProtectedBase.AnEnum ae = getAnEnum();
+    if (ae != ProtectedBase.AnEnum.EnumVal1)
+      throw new RuntimeException("Failed");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/apply_signed_char_runme.java b/trunk/Examples/test-suite/java/apply_signed_char_runme.java
new file mode 100644
index 0000000..531558e
--- /dev/null
+++ b/trunk/Examples/test-suite/java/apply_signed_char_runme.java
@@ -0,0 +1,36 @@
+import apply_signed_char.*;
+
+public class apply_signed_char_runme {
+
+  static {
+    try {
+	System.loadLibrary("apply_signed_char");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    byte smallnum = -127;
+    if (apply_signed_char.CharValFunction(smallnum) != smallnum) throw new RuntimeException("failed");
+    if (apply_signed_char.CCharValFunction(smallnum) != smallnum) throw new RuntimeException("failed");
+    if (apply_signed_char.CCharRefFunction(smallnum) != smallnum) throw new RuntimeException("failed");
+
+    apply_signed_char.setGlobalchar(smallnum);
+    if (apply_signed_char.getGlobalchar() != smallnum) throw new RuntimeException("failed");
+    if (apply_signed_char.getGlobalconstchar() != -110) throw new RuntimeException("failed");
+
+    DirectorTest d = new DirectorTest();
+    if (d.CharValFunction(smallnum) != smallnum) throw new RuntimeException("failed");
+    if (d.CCharValFunction(smallnum) != smallnum) throw new RuntimeException("failed");
+    if (d.CCharRefFunction(smallnum) != smallnum) throw new RuntimeException("failed");
+
+    d.setMemberchar(smallnum);
+    if (d.getMemberchar() != smallnum) throw new RuntimeException("failed");
+    if (d.getMemberconstchar() != -112) throw new RuntimeException("failed");
+
+  }
+}
+
+
diff --git a/trunk/Examples/test-suite/java/apply_strings_runme.java b/trunk/Examples/test-suite/java/apply_strings_runme.java
new file mode 100644
index 0000000..0b9f780
--- /dev/null
+++ b/trunk/Examples/test-suite/java/apply_strings_runme.java
@@ -0,0 +1,24 @@
+import apply_strings.*;
+
+public class apply_strings_runme {
+
+  static {
+    try {
+	System.loadLibrary("apply_strings");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  private static String TEST_MESSAGE = "A message from target language to the C++ world and back again.";
+
+  public static void main(String argv[]) {
+    if (!apply_strings.UCharFunction(TEST_MESSAGE).equals(TEST_MESSAGE)) throw new RuntimeException("UCharFunction failed");
+    if (!apply_strings.SCharFunction(TEST_MESSAGE).equals(TEST_MESSAGE)) throw new RuntimeException("SCharFunction failed");
+    SWIGTYPE_p_char pChar = apply_strings.CharFunction(null);
+    if (pChar != null) throw new RuntimeException("CharFunction failed");
+  }
+}
+
+
diff --git a/trunk/Examples/test-suite/java/array_member_runme.java b/trunk/Examples/test-suite/java/array_member_runme.java
new file mode 100644
index 0000000..2f17bb0
--- /dev/null
+++ b/trunk/Examples/test-suite/java/array_member_runme.java
@@ -0,0 +1,35 @@
+import array_member.*;
+
+public class array_member_runme {
+  static {
+    try {
+        System.loadLibrary("array_member");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      Foo f = new Foo();
+      f.setData(array_member.getGlobal_data());
+
+      for (int i=0; i<8; i++) {
+          if (array_member.get_value(f.getData(),i) != array_member.get_value(array_member.getGlobal_data(),i))
+              throw new RuntimeException("Bad array assignment");
+      }
+
+      for (int i=0; i<8; i++) {
+          array_member.set_value(f.getData(),i,-i);
+      }
+
+      array_member.setGlobal_data(f.getData());
+
+      for (int i=0; i<8; i++) {
+          if (array_member.get_value(f.getData(),i) != array_member.get_value(array_member.getGlobal_data(),i))
+              throw new RuntimeException("Bad array assignment");
+      }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/arrays_global_twodim_runme.java b/trunk/Examples/test-suite/java/arrays_global_twodim_runme.java
new file mode 100644
index 0000000..2cbc013
--- /dev/null
+++ b/trunk/Examples/test-suite/java/arrays_global_twodim_runme.java
@@ -0,0 +1,33 @@
+// Two dimension arrays test
+
+import arrays_global_twodim.*;
+
+public class arrays_global_twodim_runme {
+  static {
+    try {
+        System.loadLibrary("arrays_global_twodim");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      SWIGTYPE_p_a_4__int constintarray2d = arrays_global_twodim.getArray_const_i();
+      SWIGTYPE_p_a_4__int intarray2d = arrays_global_twodim.getArray_i();
+
+      // Set all the non const int array members from the const int array members and check
+      arrays_global_twodim.setArray_i(constintarray2d);
+
+      int count = 10;
+      for (int x=0; x<arrays_global_twodim.ARRAY_LEN_X; x++) {
+        for (int y=0; y<arrays_global_twodim.ARRAY_LEN_Y; y++) {
+          if ( arrays_global_twodim.get_2d_array(intarray2d, x, y) != count++) {
+            System.out.println("Value incorrect array_i[" + x + "][" + y + "]");
+            System.exit(1);
+          }
+        }
+      }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/char_strings_runme.java b/trunk/Examples/test-suite/java/char_strings_runme.java
new file mode 100644
index 0000000..2c71d3e
--- /dev/null
+++ b/trunk/Examples/test-suite/java/char_strings_runme.java
@@ -0,0 +1,142 @@
+import char_strings.*;
+
+public class char_strings_runme {
+
+  static {
+    try {
+	System.loadLibrary("char_strings");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  private static String CPLUSPLUS_MSG = "A message from the deep dark world of C++, where anything is possible.";
+  private static String OTHERLAND_MSG = "Little message from the safe world.";
+
+  public static void main(String argv[]) {
+
+    long count = 10000;
+    long i = 0;
+
+    // get functions
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetCharHeapString();
+      if (!str.equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test char get 1 failed, iteration " + i);
+      char_strings.DeleteCharHeapString();
+    }
+
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetConstCharProgramCodeString();
+      if (!str.equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test char get 2 failed, iteration " + i);
+      char_strings.DeleteCharHeapString();
+    }
+
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetCharStaticString();
+      if (!str.equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test char get 3 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetCharStaticStringFixed();
+      if (!str.equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test char get 4 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetConstCharStaticStringFixed();
+      if (!str.equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test char get 5 failed, iteration " + i);
+    }
+
+    // set functions
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetCharHeapString(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char set 1 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetCharStaticString(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char set 2 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetCharArrayStaticString(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char set 3 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharHeapString(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char set 4 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharStaticString(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char set 5 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharArrayStaticString(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char set 6 failed, iteration " + i);
+    }
+
+    // get set function
+    for (i=0; i<count; i++) {
+      String ping = OTHERLAND_MSG + i;
+      String pong = char_strings.CharPingPong(ping);
+      if (!ping.equals(pong))
+        throw new RuntimeException("Test PingPong 1 failed.\nExpected:" + ping + "\nReceived:" + pong);
+    }
+
+    // variables
+    for (i=0; i<count; i++) {
+      char_strings.setGlobal_char(OTHERLAND_MSG + i);
+      if (!char_strings.getGlobal_char().equals(OTHERLAND_MSG + i))
+        throw new RuntimeException("Test variables 1 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      char_strings.setGlobal_char_array1(OTHERLAND_MSG + i);
+      if (!char_strings.getGlobal_char_array1().equals(OTHERLAND_MSG + i))
+        throw new RuntimeException("Test variables 2 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      char_strings.setGlobal_char_array2(OTHERLAND_MSG + i);
+      if (!char_strings.getGlobal_char_array2().equals(OTHERLAND_MSG + i))
+        throw new RuntimeException("Test variables 3 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.getGlobal_const_char().equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test variables 4 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.getGlobal_const_char_array1().equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test variables 5 failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.getGlobal_const_char_array2().equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test variables 6 failed, iteration " + i);
+    }
+
+    // char *& tests
+    for (i=0; i<count; i++) {
+      String str = char_strings.GetConstCharPointerRef();
+      if (!str.equals(CPLUSPLUS_MSG))
+        throw new RuntimeException("Test char pointer ref get failed, iteration " + i);
+    }
+
+    for (i=0; i<count; i++) {
+      if (!char_strings.SetConstCharPointerRef(OTHERLAND_MSG + i, i))
+        throw new RuntimeException("Test char pointer ref set failed, iteration " + i);
+    }
+  }
+}
+
+
diff --git a/trunk/Examples/test-suite/java/cpp_typedef_runme.java b/trunk/Examples/test-suite/java/cpp_typedef_runme.java
new file mode 100644
index 0000000..75bb474
--- /dev/null
+++ b/trunk/Examples/test-suite/java/cpp_typedef_runme.java
@@ -0,0 +1,34 @@
+
+// This is the cpp_typedef runtime testcase. It checks that proxy classes are
+// generated for typedef'd types.
+
+import cpp_typedef.*;
+
+public class cpp_typedef_runme {
+
+  static {
+    try {
+	System.loadLibrary("cpp_typedef");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    Foo f = new Foo();
+    SWIGTYPE_p_Bar pbar = f.bar();
+    pbar = Foo.sbar();
+
+    Test test = new Test();
+    UnnamedStruct unnamed = new UnnamedStruct();
+    TypedefNamedStruct named = new TypedefNamedStruct();
+
+    UnnamedStruct unnamed2 = test.test1(unnamed);
+    TypedefNamedStruct named2 = test.test2(named);
+    TypedefNamedStruct named3 = test.test3(named);
+    TypedefNamedStruct named4 = test.test4(named);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/default_args_runme.java b/trunk/Examples/test-suite/java/default_args_runme.java
new file mode 100644
index 0000000..20a7949
--- /dev/null
+++ b/trunk/Examples/test-suite/java/default_args_runme.java
@@ -0,0 +1,150 @@
+
+import default_args.*;
+
+public class default_args_runme {
+  static {
+    try {
+        System.loadLibrary("default_args");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    if (default_args.anonymous() != 7771)
+      throw new RuntimeException("anonymous (1) failed");
+    if (default_args.anonymous(1234) != 1234)
+      throw new RuntimeException("anonymous (2) failed");
+
+    if (default_args.booltest() != true)
+      throw new RuntimeException("booltest (1) failed");
+    if (default_args.booltest(true) != true)
+      throw new RuntimeException("booltest (2) failed");
+    if (default_args.booltest(false) != false)
+      throw new RuntimeException("booltest (3) failed");
+
+    EnumClass ec = new EnumClass();
+    if (ec.blah() != true)
+      throw new RuntimeException("EnumClass failed");
+
+    if (default_args.casts1() != null)
+      throw new RuntimeException("casts1 failed");
+
+    if (!default_args.casts2().equals("Hello"))
+      throw new RuntimeException("casts2 failed");
+
+    if (!default_args.casts1("Ciao").equals("Ciao"))
+      throw new RuntimeException("casts1 not default failed");
+
+    if (default_args.chartest1() != 'x')
+      throw new RuntimeException("chartest1 failed");
+
+    if (default_args.chartest2() != '\0')
+      throw new RuntimeException("chartest2 failed");
+
+    if (default_args.chartest1('y') != 'y')
+      throw new RuntimeException("chartest1 not default failed");
+
+    if (default_args.chartest1('y') != 'y')
+      throw new RuntimeException("chartest1 not default failed");
+
+    if (default_args.reftest1() != 42)
+      throw new RuntimeException("reftest1 failed");
+
+    if (default_args.reftest1(400) != 400)
+      throw new RuntimeException("reftest1 not default failed");
+
+    if (!default_args.reftest2().equals("hello"))
+      throw new RuntimeException("reftest2 failed");
+
+    // rename
+    Foo foo = new Foo();
+    foo.newname(); 
+    foo.newname(10); 
+    foo.renamed3arg(10, 10.0); 
+    foo.renamed2arg(10); 
+    foo.renamed1arg(); 
+     
+    // exception specifications
+    try {
+      default_args.exceptionspec();
+      throw new RuntimeException("exceptionspec 1 failed");
+    } catch (RuntimeException e) {
+    }
+    try {
+      default_args.exceptionspec(-1);
+      throw new RuntimeException("exceptionspec 2 failed");
+    } catch (RuntimeException e) {
+    }
+    try {
+      default_args.exceptionspec(100);
+      throw new RuntimeException("exceptionspec 3 failed");
+    } catch (RuntimeException e) {
+    }
+    Except ex = new Except(false);
+    try {
+      ex.exspec();
+      throw new RuntimeException("exspec 1 failed");
+    } catch (RuntimeException e) {
+    }
+    try {
+      ex.exspec(-1);
+      throw new RuntimeException("exspec 2 failed");
+    } catch (RuntimeException e) {
+    }
+    try {
+      ex.exspec(100);
+      throw new RuntimeException("exspec 3 failed");
+    } catch (RuntimeException e) {
+    }
+    try {
+      ex = new Except(true);
+      throw new RuntimeException("Except constructor 1 failed");
+    } catch (RuntimeException e) {
+    }
+    try {
+      ex = new Except(true, -2);
+      throw new RuntimeException("Except constructor 2 failed");
+    } catch (RuntimeException e) {
+    }
+
+    // Default parameters in static class methods
+    if (Statics.staticmethod() != 10+20+30)
+      throw new RuntimeException("staticmethod 1 failed");
+    if (Statics.staticmethod(100) != 100+20+30)
+      throw new RuntimeException("staticmethod 2 failed");
+    if (Statics.staticmethod(100,200,300) != 100+200+300)
+      throw new RuntimeException("staticmethod 3 failed");
+
+
+    Tricky tricky = new Tricky();
+    if (tricky.privatedefault() != 200)
+      throw new RuntimeException("privatedefault failed");
+    if (tricky.protectedint() != 2000)
+      throw new RuntimeException("protectedint failed");
+    if (tricky.protecteddouble() != 987.654)
+      throw new RuntimeException("protecteddouble failed");
+    if (tricky.functiondefault() != 500)
+      throw new RuntimeException("functiondefault failed");
+    if (tricky.contrived() != 'X')
+      throw new RuntimeException("contrived failed");
+
+    if (default_args.constructorcall().getVal() != -1)
+      throw new RuntimeException("constructorcall test 1 failed");
+
+    if (default_args.constructorcall(new Klass(2222)).getVal() != 2222)
+      throw new RuntimeException("constructorcall test 2 failed");
+
+    if (default_args.constructorcall(new Klass()).getVal() != -1)
+      throw new RuntimeException("constructorcall test 3 failed");
+
+    // const methods 
+    ConstMethods cm = new ConstMethods();
+    if (cm.coo() != 20)
+      throw new RuntimeException("coo test 1 failed");
+    if (cm.coo(1.0) != 20)
+      throw new RuntimeException("coo test 2 failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/default_constructor_runme.java b/trunk/Examples/test-suite/java/default_constructor_runme.java
new file mode 100644
index 0000000..6473c40
--- /dev/null
+++ b/trunk/Examples/test-suite/java/default_constructor_runme.java
@@ -0,0 +1,32 @@
+
+import default_constructor.*;
+
+public class default_constructor_runme {
+  static {
+    try {
+        System.loadLibrary("default_constructor");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      // calling protected destructor test
+      try {
+          G g = new G();
+          g.delete();
+          throw new RuntimeException("Protected destructor exception should have been thrown");
+      } catch (UnsupportedOperationException e) {
+      }
+
+      // calling private destructor test
+      try {
+          FFF f = new FFF();
+          f.delete();
+          throw new RuntimeException("Private destructor exception should have been thrown");
+      } catch (UnsupportedOperationException e) {
+      }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/director_abstract_runme.java b/trunk/Examples/test-suite/java/director_abstract_runme.java
new file mode 100644
index 0000000..0453fb7
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_abstract_runme.java
@@ -0,0 +1,46 @@
+
+import director_abstract.*;
+
+public class director_abstract_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_abstract");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+      director_abstract_MyFoo a = new director_abstract_MyFoo();
+
+      if (!a.ping().equals("director_abstract_MyFoo::ping()")) {
+          throw new RuntimeException ( "a.ping()" );
+      }
+
+      if (!a.pong().equals("Foo::pong();director_abstract_MyFoo::ping()")) {
+          throw new RuntimeException ( "a.pong()" );
+      }
+
+      director_abstract_BadFoo b = new director_abstract_BadFoo();
+      try {
+        b.ping();
+        System.out.println( "Test failed. An attempt to call a pure virtual method should throw an exception" );
+        System.exit(1);
+      }
+      catch (RuntimeException e) {
+      }
+  }
+}
+
+class director_abstract_MyFoo extends Foo {
+    public String ping() {
+        return "director_abstract_MyFoo::ping()";
+    }
+}
+
+class director_abstract_BadFoo extends Foo {
+}
+
diff --git a/trunk/Examples/test-suite/java/director_basic_runme.java b/trunk/Examples/test-suite/java/director_basic_runme.java
new file mode 100644
index 0000000..eafe20b
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_basic_runme.java
@@ -0,0 +1,47 @@
+
+import director_basic.*;
+
+public class director_basic_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_basic");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+      director_basic_MyFoo a = new director_basic_MyFoo();
+
+      if (!a.ping().equals("director_basic_MyFoo::ping()")) {
+          throw new RuntimeException ( "a.ping()" );
+      }
+
+      if (!a.pong().equals("Foo::pong();director_basic_MyFoo::ping()")) {
+          throw new RuntimeException ( "a.pong()" );
+      }
+
+      Foo b = new Foo();
+
+      if (!b.ping().equals("Foo::ping()")) {
+          throw new RuntimeException ( "b.ping()" );
+      }
+
+      if (!b.pong().equals("Foo::pong();Foo::ping()")) {
+          throw new RuntimeException ( "b.pong()" );
+      }
+
+      A1 a1 = new A1(1, false);
+      a1.delete();
+  }
+}
+
+class director_basic_MyFoo extends Foo {
+    public String ping() {
+        return "director_basic_MyFoo::ping()";
+    }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_classes_runme.java b/trunk/Examples/test-suite/java/director_classes_runme.java
new file mode 100644
index 0000000..013bdc7
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_classes_runme.java
@@ -0,0 +1,207 @@
+/*
+This test demonstrates director classes when the types are classes.
+Shown are virtual function calls which use classes passed by:
+  - Value
+  - Reference
+  - Pointer
+as both parameters and return values.
+The test also demonstrates directors used with:
+  - method overloading
+  - default parameters
+Note: Methods with default parameters that call up from C++ cannot call
+the overloaded Java methods, see DefaultParms method.
+
+Expected output if PrintDebug enabled:
+------------ Start ------------
+Base - Val(444.555)
+Base - Ref(444.555)
+Base - Ptr(444.555)
+Base - FullyOverloaded(int 10)
+Base - FullyOverloaded(bool 1)
+Base - SemiOverloaded(int -678)
+Base - SemiOverloaded(bool 1)
+Base - DefaultParms(10, 2.2)
+Base - DefaultParms(10, 1.1)
+--------------------------------
+Derived - Val(444.555)
+Derived - Ref(444.555)
+Derived - Ptr(444.555)
+Derived - FullyOverloaded(int 10)
+Derived - FullyOverloaded(bool 1)
+Derived - SemiOverloaded(int -678)
+Base - SemiOverloaded(bool 1)
+Derived - DefaultParms(10, 2.2)
+Derived - DefaultParms(10, 1.1)
+--------------------------------
+JavaDerived - Val(444.555)
+JavaDerived - Ref(444.555)
+JavaDerived - Ptr(444.555)
+JavaDerived - FullyOverloaded(int 10)
+JavaDerived - FullyOverloaded(bool True)
+JavaDerived - SemiOverloaded(-678)
+Base - SemiOverloaded(bool 1)
+JavaDerived - DefaultParms(10, 2.2)
+JavaDerived - DefaultParms(10, 1.1)
+------------ Finish ------------
+*/
+
+
+import director_classes.*;
+
+public class director_classes_runme {
+
+  static {
+    try {
+        System.loadLibrary("director_classes");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    director_classes_runme r = new director_classes_runme();
+    r.run();
+  }
+
+  void run()
+  {
+    if (director_classes.getPrintDebug()) System.out.println("------------ Start ------------ ");
+
+    Caller myCaller = new Caller();
+
+    // test C++ base class
+    {
+      Base myBase = new Base(100.0);
+      makeCalls(myCaller, myBase);
+      myBase.delete();
+    }
+
+    if (director_classes.getPrintDebug()) System.out.println("--------------------------------");
+
+    // test vanilla C++ wrapped derived class
+    {
+      Base myBase = new Derived(200.0);
+      makeCalls(myCaller, myBase);
+      myBase.delete();
+    }
+
+    if (director_classes.getPrintDebug()) System.out.println("--------------------------------");
+
+    // test director / Java derived class
+    {
+      Base myBase = new JavaDerived(300.0);
+      makeCalls(myCaller, myBase);
+      myBase.delete();
+    }
+
+    if (director_classes.getPrintDebug()) System.out.println("------------ Finish ------------ ");
+  }
+
+  void makeCalls(Caller myCaller, Base myBase)
+  {
+    String baseSimpleName = getSimpleName(myBase.getClass());
+
+    myCaller.set(myBase);
+
+    DoubleHolder dh = new DoubleHolder(444.555);
+
+    // Class pointer, reference and pass by value tests
+    if (myCaller.ValCall(dh).getVal() != dh.getVal()) throw new RuntimeException("failed");
+    if (myCaller.RefCall(dh).getVal() != dh.getVal()) throw new RuntimeException("failed");
+    if (myCaller.PtrCall(dh).getVal() != dh.getVal()) throw new RuntimeException("failed");
+
+    // Fully overloaded method test (all methods in base class are overloaded)
+    if (!myCaller.FullyOverloadedCall(10).equals(baseSimpleName + "::FullyOverloaded(int)")) {
+      System.out.println(myCaller.FullyOverloadedCall(10) + "----" + (baseSimpleName + "::FullyOverloaded(int)"));
+      throw new RuntimeException("failed");
+    }
+    if (!myCaller.FullyOverloadedCall(true).equals(baseSimpleName + "::FullyOverloaded(bool)")) throw new RuntimeException("failed");
+
+    // Semi overloaded method test (some methods in base class are overloaded)
+    if (!myCaller.SemiOverloadedCall(-678).equals(baseSimpleName + "::SemiOverloaded(int)")) throw new RuntimeException("failed");
+    if (!myCaller.SemiOverloadedCall(true).equals("Base" + "::SemiOverloaded(bool)")) throw new RuntimeException("failed");
+
+    // Default parameters methods test
+    if (!(myCaller.DefaultParmsCall(10, 2.2)).equals(baseSimpleName + "::DefaultParms(int, double)")) throw new RuntimeException("failed");
+    if (myBase instanceof JavaDerived) { // special handling for Java derived classes, there is no way to do this any other way
+      if (!myCaller.DefaultParmsCall(10).equals(baseSimpleName + "::DefaultParms(int, double)")) throw new RuntimeException("failed");
+    } else {
+      if (!myCaller.DefaultParmsCall(10).equals(baseSimpleName + "::DefaultParms(int)")) throw new RuntimeException("failed");
+    }
+
+    myCaller.reset();
+  }
+
+  // Same as Class.getSimpleName() which is not present in all jdks
+  static String getSimpleName(Class klass) {
+    String fullName = klass.getName();
+    Package packag = klass.getPackage();
+    String simpleName = null;
+    if (packag != null)
+        simpleName = fullName.replaceAll(packag.getName() + ".", "");
+    else
+        simpleName = fullName;
+    return simpleName;
+  }
+}
+
+
+class JavaDerived extends Base
+{
+  public JavaDerived(double dd)
+  {
+    super(dd);
+  }
+
+  public DoubleHolder Val(DoubleHolder x)
+  {
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - Val(" + x.getVal() + ")");
+    return x;
+  }
+  public DoubleHolder Ref(DoubleHolder x)
+  {
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - Ref(" + x.getVal() + ")");
+    return x;
+  }
+  public DoubleHolder Ptr(DoubleHolder x)
+  {
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - Ptr(" + x.getVal() + ")");
+    return x;
+  }
+  public String FullyOverloaded(int x)
+  {
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - FullyOverloaded(int " + x + ")");
+    return "JavaDerived::FullyOverloaded(int)";
+  }
+  public String FullyOverloaded(boolean x)
+  {
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - FullyOverloaded(bool " + x + ")");
+    return "JavaDerived::FullyOverloaded(bool)";
+  }
+  // Note no SemiOverloaded(bool x) method
+  public String SemiOverloaded(int x)
+  {
+    String ret = "JavaDerived::SemiOverloaded(int)";
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - SemiOverloaded(" + x + ")");
+    return ret;
+  }
+  public String DefaultParms(int x, double y)
+  {
+    String ret = "JavaDerived::DefaultParms(int, double)";
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - DefaultParms(" + x + ", " + y + ")");
+    return ret;
+  }
+  // Note the following method can never be called from unmanaged code.
+  // It is here only for code that calls it directly from managed code.
+  // But should always be defined to ensure behaviour is consistent
+  // independent of where DefaultParsms is called from (managed or unmanaged code).
+  // Note this method can never be called from unmanaged code
+  public String DefaultParms(int x)
+  {
+    if (director_classes.getPrintDebug()) System.out.println("JavaDerived - DefaultParms(" + x + ")");
+    return DefaultParms(x, 1.1/*use C++ default here*/);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_classic_runme.java b/trunk/Examples/test-suite/java/director_classic_runme.java
new file mode 100755
index 0000000..50ea2b8
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_classic_runme.java
@@ -0,0 +1,318 @@
+import director_classic.*;
+
+public class director_classic_runme {
+  static {
+    try {
+        System.loadLibrary("director_classic");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    { 
+      Person person = new Person();
+      check(person, "Person");
+      person.delete();
+    }
+    { 
+      Person person = new Child();
+      check(person, "Child");
+      person.delete();
+    }
+    { 
+      Person person = new GrandChild();
+      check(person, "GrandChild"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangPerson();
+      check(person, "TargetLangPerson"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangChild();
+      check(person, "TargetLangChild"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangGrandChild();
+      check(person, "TargetLangGrandChild"); 
+      person.delete();
+    }
+
+    // Semis - don't override id() in target language
+    { 
+      Person person = new TargetLangSemiPerson();
+      check(person, "Person"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangSemiChild();
+      check(person, "Child"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangSemiGrandChild();
+      check(person, "GrandChild"); 
+      person.delete();
+    }
+
+    // Orphans - don't override id() in C++
+    { 
+      Person person = new OrphanPerson();
+      check(person, "Person"); 
+      person.delete();
+    }
+    { 
+      Person person = new OrphanChild();
+      check(person, "Child"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangOrphanPerson();
+      check(person, "TargetLangOrphanPerson"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangOrphanChild();
+      check(person, "TargetLangOrphanChild"); 
+      person.delete();
+    }
+
+    // Duals - id() makes an upcall to the base id()
+    { 
+      Person person = new TargetLangDualPerson();
+      check(person, "TargetLangDualPerson + Person"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangDualChild();
+      check(person, "TargetLangDualChild + Child"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangDualGrandChild();
+      check(person, "TargetLangDualGrandChild + GrandChild"); 
+      person.delete();
+    }
+
+    // Mix Orphans and Duals
+    { 
+      Person person = new TargetLangDualOrphanPerson();
+      check(person, "TargetLangDualOrphanPerson + Person"); 
+      person.delete();
+    }
+    { 
+      Person person = new TargetLangDualOrphanChild();
+      check(person, "TargetLangDualOrphanChild + Child"); 
+      person.delete();
+    }
+  }
+
+  static void check(Person person, String expected) {
+    String ret;
+    // Normal target language polymorphic call
+    ret = person.id();
+    if (debug) 
+      System.out.println(ret);
+    if (!ret.equals(expected))
+      throw new RuntimeException("Failed. Received: " + ret + " Expected: " + expected);
+
+    // Polymorphic call from C++
+    Caller caller = new Caller();
+    caller.setCallback(person);
+    ret = caller.call();
+    if (debug) 
+      System.out.println(ret);
+    if (!ret.equals(expected))
+      throw new RuntimeException("Failed. Received: " + ret + " Expected: " + expected);
+
+    // Polymorphic call of object created in target language and passed to C++ and back again
+    Person baseclass = caller.baseClass();
+    ret = baseclass.id();
+    if (debug) 
+      System.out.println(ret);
+    if (!ret.equals(expected))
+      throw new RuntimeException("Failed. Received: " + ret + " Expected: " + expected);
+
+    caller.resetCallback();
+    if (debug) 
+      System.out.println("----------------------------------------");
+  }
+  static boolean debug = false;
+}
+
+class TargetLangPerson extends Person
+{
+  public TargetLangPerson()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangPerson";
+    return identifier;
+  }
+}
+
+class TargetLangChild extends Child
+{
+  public TargetLangChild()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangChild";
+    return identifier;
+  }
+}
+
+class TargetLangGrandChild extends GrandChild
+{
+  public TargetLangGrandChild()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangGrandChild";
+    return identifier;
+  }
+}
+
+// Semis - don't override id() in target language
+class TargetLangSemiPerson extends Person
+{
+  public TargetLangSemiPerson()
+  {
+    super();
+  }
+  // No id() override
+}
+
+class TargetLangSemiChild extends Child
+{
+  public TargetLangSemiChild()
+  {
+    super();
+  }
+  // No id() override
+}
+
+class TargetLangSemiGrandChild extends GrandChild
+{
+  public TargetLangSemiGrandChild()
+  {
+    super();
+  }
+  // No id() override
+}
+
+// Orphans - don't override id() in C++
+class TargetLangOrphanPerson extends OrphanPerson
+{
+  public TargetLangOrphanPerson()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangOrphanPerson";
+    return identifier;
+  }
+}
+
+class TargetLangOrphanChild extends OrphanChild
+{
+  public TargetLangOrphanChild()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangOrphanChild";
+    return identifier;
+  }
+}
+
+// Duals - id() makes an upcall to the base id()
+class TargetLangDualPerson extends Person
+{
+  public TargetLangDualPerson()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangDualPerson + " + super.id();
+    return identifier;
+  }
+}
+
+class TargetLangDualChild extends Child
+{
+  public TargetLangDualChild()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangDualChild + " + super.id();
+    return identifier;
+  }
+}
+
+class TargetLangDualGrandChild extends GrandChild
+{
+  public TargetLangDualGrandChild()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangDualGrandChild + " + super.id();
+    return identifier;
+  }
+}
+
+// Mix Orphans and Duals
+class TargetLangDualOrphanPerson extends OrphanPerson
+{
+  public TargetLangDualOrphanPerson()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangDualOrphanPerson + " + super.id();
+    return identifier;
+  }
+}
+
+class TargetLangDualOrphanChild extends OrphanChild
+{
+  public TargetLangDualOrphanChild()
+  {
+    super();
+  }
+
+  public String id()
+  {
+    String identifier = "TargetLangDualOrphanChild + " + super.id();
+    return identifier;
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_default_runme.java b/trunk/Examples/test-suite/java/director_default_runme.java
new file mode 100644
index 0000000..b71e45e
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_default_runme.java
@@ -0,0 +1,51 @@
+
+import director_default.*;
+
+public class director_default_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_default");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    {
+      director_default_MyFoo a = new director_default_MyFoo();
+      a = new director_default_MyFoo(10);
+    }
+
+    director_default_MyFoo a = new director_default_MyFoo();
+    if (!a.GetMsg().equals("director_default_MyFoo-default")) {
+      throw new RuntimeException ( "Test 1 failed" );
+    }
+    if (!a.GetMsg("boo").equals("director_default_MyFoo-boo")) {
+      throw new RuntimeException ( "Test 2 failed" );
+    }
+
+    Foo b = new Foo();
+    if (!b.GetMsg().equals("Foo-default")) {
+      throw new RuntimeException ( "Test 1 failed" );
+    }
+    if (!b.GetMsg("boo").equals("Foo-boo")) {
+      throw new RuntimeException ( "Test 2 failed" );
+    }
+
+  }
+}
+
+class director_default_MyFoo extends Foo {
+    public director_default_MyFoo() {
+      super();
+    }
+    public director_default_MyFoo(int i) {
+      super(i);
+    }
+    public String Msg(String msg) { 
+      return "director_default_MyFoo-" + msg; 
+    }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_enum_runme.java b/trunk/Examples/test-suite/java/director_enum_runme.java
new file mode 100644
index 0000000..9abfa31
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_enum_runme.java
@@ -0,0 +1,54 @@
+
+import director_enum.*;
+
+public class director_enum_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_enum");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+      director_enum_MyFoo a = new director_enum_MyFoo();
+
+      if (a.ping(Hallo.awright) != Hallo.yo) {
+          throw new RuntimeException ( "a.ping()" );
+      }
+      if (a.ping_ref(Hallo.awright) != Hallo.hello) {
+          throw new RuntimeException ( "a.ping_ref()" );
+      }
+      if (a.ping_member_enum(Foo.Bye.adios) != Foo.Bye.aufwiedersehen) {
+          throw new RuntimeException ( "a.ping_member_enum()" );
+      }
+
+      Foo b = new Foo();
+
+      if (b.ping(Hallo.awright) != Hallo.awright) {
+          throw new RuntimeException ( "b.ping()" );
+      }
+      if (b.ping_ref(Hallo.awright) != Hallo.awright) {
+          throw new RuntimeException ( "b.ping_ref()" );
+      }
+      if (b.ping_member_enum(Foo.Bye.adios) != Foo.Bye.adios) {
+          throw new RuntimeException ( "b.ping_member_enum()" );
+      }
+  }
+}
+
+class director_enum_MyFoo extends Foo {
+    public Hallo say_hi(Hallo h) {
+        return Hallo.yo;
+    }
+    public Hallo say_hi_ref(Hallo h) {
+        return Hallo.hello;
+    }
+    public Foo.Bye say_bye(Foo.Bye b) {
+        return Foo.Bye.aufwiedersehen;
+    }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_exception_runme.java b/trunk/Examples/test-suite/java/director_exception_runme.java
new file mode 100644
index 0000000..3d2958a
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_exception_runme.java
@@ -0,0 +1,34 @@
+
+import director_exception.*;
+
+public class director_exception_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_exception");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+      director_exception_MyFoo a = new director_exception_MyFoo();
+      Foo b = director_exception.launder(a);
+
+      try {
+          a.pong();
+          throw new RuntimeException ( "Failed to catch exception" );
+      }
+      catch (UnsupportedOperationException e) {
+      }
+  }
+}
+
+class director_exception_MyFoo extends Foo {
+    public String ping() {
+        throw new UnsupportedOperationException("Foo::ping not implemented");
+    }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_frob_runme.java b/trunk/Examples/test-suite/java/director_frob_runme.java
new file mode 100644
index 0000000..ac1c4eb
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_frob_runme.java
@@ -0,0 +1,39 @@
+
+import director_frob.*;
+import java.lang.reflect.*;
+
+public class director_frob_runme
+{
+  static {
+    try {
+      System.loadLibrary("director_frob");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String args[])
+  {
+    Bravo foo = new Bravo();
+
+    String s = foo.abs_method();
+    if (!s.equals("Bravo::abs_method()"))
+      throw new RuntimeException( "error" );
+
+    Prims prims = new PrimsDerived();
+    java.math.BigInteger bi = prims.callull(200, 50);
+    java.math.BigInteger biCheck = new java.math.BigInteger("150");
+    if (bi.compareTo(biCheck) != 0)
+      throw new RuntimeException( "failed got:" + bi);
+  }
+}
+
+class PrimsDerived extends Prims {
+  PrimsDerived() {
+    super();
+  }
+  public java.math.BigInteger ull(java.math.BigInteger i, java.math.BigInteger j) {
+    return i.subtract(j);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/director_ignore_runme.java b/trunk/Examples/test-suite/java/director_ignore_runme.java
new file mode 100755
index 0000000..9b98ee4
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_ignore_runme.java
@@ -0,0 +1,40 @@
+import director_ignore.*;
+
+public class director_ignore_runme {
+  static {
+    try {
+        System.loadLibrary("director_ignore");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    // Just check the classes can be instantiated and other methods work as expected
+    DIgnoresDerived a = new DIgnoresDerived();
+    if (a.Triple(5) != 15)
+      throw new RuntimeException("Triple failed");
+    DAbstractIgnoresDerived b = new DAbstractIgnoresDerived();
+    if (b.Quadruple(5) != 20)
+      throw new RuntimeException("Quadruple failed");
+  }
+}
+
+class DIgnoresDerived extends DIgnores
+{
+  public DIgnoresDerived()
+  {
+    super();
+  }
+}
+
+class DAbstractIgnoresDerived extends DAbstractIgnores
+{
+  public DAbstractIgnoresDerived()
+  {
+    super();
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_primitives_runme.java b/trunk/Examples/test-suite/java/director_primitives_runme.java
new file mode 100644
index 0000000..8dedfff
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_primitives_runme.java
@@ -0,0 +1,138 @@
+/*
+  This test program shows a C# class JavaDerived inheriting from Base. Three types of classes are created
+  and the virtual methods called to demonstrate:
+  1) Wide variety of primitive types
+  2) Calling methods with zero, one or more parameters
+  3) Director methods that are not overridden in C#
+  4) Director classes that are not overridden at all in C#, ie non-director behaviour is as expected for director classes
+  5) Inheritance hierarchy using director methods
+  6) Return types working as well as parameters
+
+  The Caller class is a tester class, which calls the virtual functions from C++.
+*/
+
+import director_primitives.*;
+
+public class director_primitives_runme {
+
+  static {
+    try {
+        System.loadLibrary("director_primitives");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    director_primitives_runme r = new director_primitives_runme();
+    r.run();
+  }
+
+  void run()
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("------------ Start ------------ ");
+
+    Caller myCaller = new Caller();
+
+    // test C++ base class
+    {
+      Base myBase = new Base(100.0);
+      makeCalls(myCaller, myBase);
+      myBase.delete();
+    }
+
+    if (director_primitives.getPrintDebug()) System.out.println("--------------------------------");
+
+    // test vanilla C++ wrapped derived class
+    {
+      Base myBase = new Derived(200.0);
+      makeCalls(myCaller, myBase);
+      myBase.delete();
+    }
+
+    if (director_primitives.getPrintDebug()) System.out.println("--------------------------------");
+
+    // test director / C# derived class
+    {
+      Base myBase = new JavaDerived(300.0);
+      makeCalls(myCaller, myBase);
+      myBase.delete();
+    }
+
+    if (director_primitives.getPrintDebug()) System.out.println("------------ Finish ------------ ");
+  }
+
+  void makeCalls(Caller myCaller, Base myBase)
+  {
+    myCaller.set(myBase);
+
+    myCaller.NoParmsMethodCall();
+    if (myCaller.BoolMethodCall(true) != true) throw new RuntimeException("failed");
+    if (myCaller.BoolMethodCall(false) != false) throw new RuntimeException("failed");
+    if (myCaller.IntMethodCall(-123) != -123) throw new RuntimeException("failed");
+    if (myCaller.UIntMethodCall(123) != 123) throw new RuntimeException("failed");
+    if (myCaller.FloatMethodCall((float)-123.456) != (float)-123.456) throw new RuntimeException("failed");
+    if (!myCaller.CharPtrMethodCall("test string").equals("test string")) throw new RuntimeException("failed");
+    if (!myCaller.ConstCharPtrMethodCall("another string").equals("another string")) throw new RuntimeException("failed");
+    if (myCaller.EnumMethodCall(HShadowMode.HShadowHard) != HShadowMode.HShadowHard) throw new RuntimeException("failed");
+    myCaller.ManyParmsMethodCall(true, -123, 123, (float)123.456, "test string", "another string", HShadowMode.HShadowHard);
+    myCaller.NotOverriddenMethodCall();
+
+    myCaller.reset();
+  }
+}
+
+class JavaDerived extends Base
+{
+  public JavaDerived(double dd)
+  {
+    super(dd);
+  }
+
+  public void NoParmsMethod()
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - NoParmsMethod()");
+  }
+  public boolean BoolMethod(boolean x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - BoolMethod(" + x + ")");
+    return x;
+  }
+  public int IntMethod(int x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - IntMethod(" + x + ")");
+    return x;
+  }
+  public long UIntMethod(long x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - UIntMethod(" + x + ")");
+    return x;
+  }
+  public float FloatMethod(float x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - FloatMethod(" + x + ")");
+    return x;
+  }
+  public String CharPtrMethod(String x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - CharPtrMethod(" + x + ")");
+    return x;
+  }
+  public String ConstCharPtrMethod(String x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - ConstCharPtrMethod(" + x + ")");
+    return x;
+  }
+  public HShadowMode EnumMethod(HShadowMode x)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - EnumMethod(" + x + ")");
+    return x;
+  }
+  public void ManyParmsMethod(boolean b, int i, long u, float f, String c, String cc, HShadowMode h)
+  {
+    if (director_primitives.getPrintDebug()) System.out.println("JavaDerived - ManyParmsMethod(" + b + ", " + i + ", " + u + ", " + f + ", " + c + ", " + cc + ", " + h);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_protected_runme.java b/trunk/Examples/test-suite/java/director_protected_runme.java
new file mode 100644
index 0000000..464b4d4
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_protected_runme.java
@@ -0,0 +1,85 @@
+
+import director_protected.*;
+import java.lang.reflect.*;
+
+public class director_protected_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_protected");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    Bar b = new Bar();
+    Foo f = b.create();
+    director_protected_FooBar fb = new director_protected_FooBar();
+    director_protected_FooBar2 fb2 = new director_protected_FooBar2();
+
+    {
+      String s = fb.used();
+      if (!s.equals("Foo::pang();Bar::pong();Foo::pong();director_protected_FooBar::ping();"))
+        throw new RuntimeException( "bad director_protected_FooBar::used" );
+    }
+
+    {
+      String s = fb2.used();
+      if (!s.equals("director_protected_FooBar2::pang();Bar::pong();Foo::pong();director_protected_FooBar2::ping();"))
+        throw new RuntimeException( "bad director_protected_FooBar2::used" );
+    }
+
+    {
+      String s = b.pong();
+      if (!s.equals("Bar::pong();Foo::pong();Bar::ping();"))
+        throw new RuntimeException( "bad Bar::pong" );
+    }
+
+    {
+      String s = f.pong();
+      if (!s.equals("Bar::pong();Foo::pong();Bar::ping();"))
+        throw new RuntimeException(" bad Foo::pong" );
+    }
+
+    {
+      String s3 = fb.pong();
+      if (!s3.equals("Bar::pong();Foo::pong();director_protected_FooBar::ping();"))
+        throw new RuntimeException(" bad director_protected_FooBar::pong" );
+    }
+
+    try {
+
+      Method method = b.getClass().getDeclaredMethod("ping", (java.lang.Class[])null);
+      if ( !Modifier.isProtected(method.getModifiers()) )
+        throw new RuntimeException("Bar::ping should be protected" );
+
+      method = f.getClass().getDeclaredMethod("ping", (java.lang.Class[])null);
+      if ( !Modifier.isProtected(method.getModifiers()) )
+        throw new RuntimeException("Foo::ping should be protected" );
+
+    } catch (NoSuchMethodException n) {
+      throw new RuntimeException("NoSuchmethodException caught. Test failed.");
+    } catch (SecurityException s) {
+      throw new RuntimeException("SecurityException caught. Test failed.");
+    }
+  }
+}
+
+class director_protected_FooBar extends Bar {
+  public String ping() {
+    return "director_protected_FooBar::ping();";
+  }
+}
+
+class director_protected_FooBar2 extends Bar {
+  public String ping() {
+    return "director_protected_FooBar2::ping();";
+  }
+  public String pang() {
+    return "director_protected_FooBar2::pang();";
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_string_runme.java b/trunk/Examples/test-suite/java/director_string_runme.java
new file mode 100644
index 0000000..a6ed671
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_string_runme.java
@@ -0,0 +1,56 @@
+
+import director_string.*;
+
+public class director_string_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_string");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    String s;
+
+    director_string_A c = new director_string_A("hi");
+    for (int i=0; i<3; i++) {
+      s = c.call_get(i);
+      if (!s.equals(new Integer(i).toString())) throw new RuntimeException("director_string_A.get(" + i + ") failed. Got:" + s);
+    }
+
+    director_string_B b = new director_string_B("hello");
+
+    s = b.call_get_first();
+    if (!s.equals("director_string_B.get_first")) throw new RuntimeException("call_get_first() failed");
+
+    s = b.call_get(0);
+    if (!s.equals("director_string_B.get: hello")) throw new RuntimeException("get(0) failed");
+  }
+}
+
+class director_string_B extends A {
+    public director_string_B(String first) {
+      super(first);
+    }
+    public String get_first() {
+      return "director_string_B.get_first";
+    }
+  
+    public String get(int n) {
+      return "director_string_B.get: " + super.get(n);
+    }
+}
+
+class director_string_A extends A {
+    public director_string_A(String first) {
+      super(first);
+    }
+    public String get(int n) {
+      return new Integer(n).toString();
+    }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_thread_runme.java b/trunk/Examples/test-suite/java/director_thread_runme.java
new file mode 100644
index 0000000..c67d410
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_thread_runme.java
@@ -0,0 +1,36 @@
+
+import director_thread.*;
+import java.lang.reflect.*;
+
+public class director_thread_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_thread");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    // This test used to hang the process. The solution is to call DetachCurrentThread in ~JNIEnvWrapper, however it causes seg faults in other JNI calls on older JDKs on Solaris. See SWIG_JAVA_NO_DETACH_CURRENT_THREAD in director.swg.
+    director_thread_Derived d = new director_thread_Derived();
+    d.run();
+
+    if (d.getVal() >= 0) {
+        throw new RuntimeException("Failed. Val: " + d.getVal());
+    }
+  }
+}
+
+class director_thread_Derived extends Foo {
+  director_thread_Derived() {
+    super();
+  }
+
+  public void do_foo() {
+    setVal(getVal() - 1);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_unroll_runme.java b/trunk/Examples/test-suite/java/director_unroll_runme.java
new file mode 100644
index 0000000..9ae7edd
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_unroll_runme.java
@@ -0,0 +1,34 @@
+
+import director_unroll.*;
+
+public class director_unroll_runme {
+
+  static {
+    try {
+      System.loadLibrary("director_unroll");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+      director_unroll_MyFoo a = new director_unroll_MyFoo();
+
+      Bar b = new Bar();
+
+      b.set(a);
+      Foo c = b.get();
+
+      if (!c.ping().equals("director_unroll_MyFoo::ping()"))
+          throw new RuntimeException ( "c.ping()" );
+  }
+}
+
+class director_unroll_MyFoo extends Foo {
+    public String ping() {
+        return "director_unroll_MyFoo::ping()";
+    }
+}
+
diff --git a/trunk/Examples/test-suite/java/director_wombat_runme.java b/trunk/Examples/test-suite/java/director_wombat_runme.java
new file mode 100644
index 0000000..575d8d7
--- /dev/null
+++ b/trunk/Examples/test-suite/java/director_wombat_runme.java
@@ -0,0 +1,94 @@
+import director_wombat.*;
+
+public class director_wombat_runme
+{
+  static {
+    try {
+        System.loadLibrary("director_wombat");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String[] args)
+  {
+    Bar                 b = new Bar();
+    Foo_integers        a;
+    int                 retval;
+
+    a = b.meth();
+    if ((retval = a.meth(49)) != 49) {
+      throw new RuntimeException ("Test failed: retval = " + retval + ", expected 49");
+    }
+
+    a.delete();
+
+    a = new director_wombat_Foo_integers_derived();
+    if ((retval = a.meth(62)) != 62 + 2) {
+      throw new RuntimeException ("Test failed: retval = " + retval + ", expected 62 + 2");
+    }
+
+    a.delete();
+
+    a = new director_wombat_Foo_integers_derived_2();
+    if ((retval = a.meth(37)) != 37) {
+      throw new RuntimeException ("Test failed: retval = " + retval + ", expected 37");
+    }
+
+    b.delete();
+
+    b = new director_wombat_Bar_derived_1();
+    b.foo_meth_ref(a, 0);
+    b.foo_meth_ptr(a, 1);
+    b.foo_meth_val(a, 2);
+  }
+}
+
+class director_wombat_Foo_integers_derived extends Foo_integers
+{
+  public director_wombat_Foo_integers_derived()
+  {
+    super();
+  }
+
+  public int meth(int param)
+  {
+    return param + 2;
+  }
+}
+
+class director_wombat_Foo_integers_derived_2 extends Foo_integers
+{
+  public director_wombat_Foo_integers_derived_2()
+  {
+    super();
+  }
+}
+
+class director_wombat_Bar_derived_1 extends Bar
+{
+  public director_wombat_Bar_derived_1()
+  {
+    super();
+  }
+
+  public void foo_meth_ref(Foo_integers foo_obj, int param)
+  {
+    if (!(foo_obj instanceof director_wombat_Foo_integers_derived_2)) {
+      throw new RuntimeException ("Test failed: foo_obj in foo_meth_ref is not director_wombat_Foo_integers_derived_2, got " + foo_obj);
+    }
+  }
+  public void foo_meth_ptr(Foo_integers foo_obj, int param)
+  {
+    if (!(foo_obj instanceof director_wombat_Foo_integers_derived_2)) {
+      throw new RuntimeException ("Test failed: foo_obj in foo_meth_ptr is not director_wombat_Foo_integers_derived_2, got " + foo_obj);
+    }
+  }
+  public void foo_meth_val(Foo_integers foo_obj, int param)
+  {
+    if (!(foo_obj instanceof director_wombat_Foo_integers_derived_2)) {
+      throw new RuntimeException ("Test failed: foo_obj in foo_meth_val is not director_wombat_Foo_integers_derived_2, got " + foo_obj);
+    }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/dynamic_cast_runme.java b/trunk/Examples/test-suite/java/dynamic_cast_runme.java
new file mode 100644
index 0000000..be1f97b
--- /dev/null
+++ b/trunk/Examples/test-suite/java/dynamic_cast_runme.java
@@ -0,0 +1,29 @@
+
+import dynamic_cast.*;
+
+public class dynamic_cast_runme {
+  static {
+    try {
+        System.loadLibrary("dynamic_cast");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    Foo f = new Foo();
+    Bar b = new Bar();
+
+    Foo x = f.blah();
+    Foo y = b.blah();
+
+    // Note it is possible to downcast y with a Java cast.
+    String a = dynamic_cast.do_test((Bar)y);
+    if (!a.equals("Bar::test")) {
+        System.err.println("Failed!");
+        System.exit(1);
+    }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/enum_thorough_proper_runme.java b/trunk/Examples/test-suite/java/enum_thorough_proper_runme.java
new file mode 100644
index 0000000..243d3bd
--- /dev/null
+++ b/trunk/Examples/test-suite/java/enum_thorough_proper_runme.java
@@ -0,0 +1,382 @@
+
+import enum_thorough_proper.*;
+
+public class enum_thorough_proper_runme {
+
+  static {
+    try {
+        System.loadLibrary("enum_thorough_proper");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    {
+      // Anonymous enums
+      int i = enum_thorough_proper.AnonEnum1;
+      if (enum_thorough_proper.ReallyAnInteger != 200) throw new RuntimeException("Test Anon 1 failed");
+      int j = enum_thorough_proper.AnonSpaceEnum1;
+      int k = AnonStruct.AnonStructEnum1;
+    }
+    {
+      colour red = colour.red;
+      enum_thorough_proper.colourTest1(red);
+      enum_thorough_proper.colourTest2(red);
+      enum_thorough_proper.colourTest3(red);
+      enum_thorough_proper.colourTest4(red);
+      enum_thorough_proper.setMyColour(red);
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed speed = SpeedClass.speed.slow;
+      if (s.speedTest1(speed) != speed) throw new RuntimeException("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new RuntimeException("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new RuntimeException("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new RuntimeException("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new RuntimeException("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new RuntimeException("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new RuntimeException("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new RuntimeException("speedTest 8 failed");
+
+      if (enum_thorough_proper.speedTest1(speed) != speed) throw new RuntimeException("speedTest Global 1 failed");
+      if (enum_thorough_proper.speedTest2(speed) != speed) throw new RuntimeException("speedTest Global 2 failed");
+      if (enum_thorough_proper.speedTest3(speed) != speed) throw new RuntimeException("speedTest Global 3 failed");
+      if (enum_thorough_proper.speedTest4(speed) != speed) throw new RuntimeException("speedTest Global 4 failed");
+      if (enum_thorough_proper.speedTest5(speed) != speed) throw new RuntimeException("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed slow = SpeedClass.speed.slow;
+      SpeedClass.speed lightning = SpeedClass.speed.lightning;
+
+      if (s.getMySpeedtd1() != slow) throw new RuntimeException("mySpeedtd1 1 failed");
+      if (s.getMySpeedtd1().swigValue() != 10) throw new RuntimeException("mySpeedtd1 2 failed");
+
+      s.setMySpeedtd1(lightning);
+      if (s.getMySpeedtd1() != lightning) throw new RuntimeException("mySpeedtd1 3 failed");
+      if (s.getMySpeedtd1().swigValue() != 31) throw new RuntimeException("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough_proper.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new RuntimeException("namedanonTest 1 failed");
+    }
+    {
+      twonames val = twonames.TwoNames2;
+      if (enum_thorough_proper.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (enum_thorough_proper.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (enum_thorough_proper.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      TwoNamesStruct.twonames val = TwoNamesStruct.twonames.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      namedanonspace val = namedanonspace.NamedAnonSpace2;
+      if (enum_thorough_proper.namedanonspaceTest1(val) != val) throw new RuntimeException("namedanonspaceTest 1 failed");
+      if (enum_thorough_proper.namedanonspaceTest2(val) != val) throw new RuntimeException("namedanonspaceTest 2 failed");
+      if (enum_thorough_proper.namedanonspaceTest3(val) != val) throw new RuntimeException("namedanonspaceTest 3 failed");
+      if (enum_thorough_proper.namedanonspaceTest4(val) != val) throw new RuntimeException("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new RuntimeException("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new RuntimeException("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new RuntimeException("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new RuntimeException("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new RuntimeException("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new RuntimeException("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new RuntimeException("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new RuntimeException("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new RuntimeException("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new RuntimeException("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new RuntimeException("scientistsTest J failed");
+
+      if (enum_thorough_proper.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest Global 1 failed");
+      if (enum_thorough_proper.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest Global 2 failed");
+      if (enum_thorough_proper.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest Global 3 failed");
+      if (enum_thorough_proper.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest Global 4 failed");
+      if (enum_thorough_proper.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest Global 5 failed");
+      if (enum_thorough_proper.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest Global 6 failed");
+      if (enum_thorough_proper.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest Global 7 failed");
+      if (enum_thorough_proper.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      TClassInt.scientists bell = TClassInt.scientists.bell;
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new RuntimeException("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new RuntimeException("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new RuntimeException("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new RuntimeException("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new RuntimeException("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new RuntimeException("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new RuntimeException("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new RuntimeException("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new RuntimeException("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new RuntimeException("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new RuntimeException("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 7 failed");
+
+      if (enum_thorough_proper.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest Global 1 failed");
+      if (enum_thorough_proper.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest Global 2 failed");
+      if (enum_thorough_proper.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest Global 3 failed");
+      if (enum_thorough_proper.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest Global 4 failed");
+      if (enum_thorough_proper.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest Global 5 failed");
+      if (enum_thorough_proper.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest Global 6 failed");
+      if (enum_thorough_proper.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough_proper.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough_proper.scientistsNameSpaceTest8(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTest9(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestA(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestB(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestC(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestD(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestE(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough_proper.scientistsNameSpaceTestF(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestG(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestH(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestI(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestJ(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestK(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough_proper.scientistsNameSpaceTestL(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      newname val = newname.argh;
+      if (enum_thorough_proper.renameTest1(val) != val) throw new RuntimeException("renameTest Global 1 failed");
+      if (enum_thorough_proper.renameTest2(val) != val) throw new RuntimeException("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new RuntimeException("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new RuntimeException("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough_proper.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest Global 3 failed");
+      if (enum_thorough_proper.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new RuntimeException("renameTest Global 4 failed");
+      if (enum_thorough_proper.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest Global 5 failed");
+      if (enum_thorough_proper.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest Global 6 failed");
+      if (enum_thorough_proper.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new RuntimeException("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      TreesClass.trees pine = TreesClass.trees.pine;
+
+      if (t.treesTest1(pine) != pine) throw new RuntimeException("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new RuntimeException("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new RuntimeException("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new RuntimeException("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new RuntimeException("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new RuntimeException("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new RuntimeException("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new RuntimeException("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new RuntimeException("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new RuntimeException("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new RuntimeException("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new RuntimeException("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new RuntimeException("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new RuntimeException("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new RuntimeException("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new RuntimeException("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new RuntimeException("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new RuntimeException("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new RuntimeException("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new RuntimeException("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new RuntimeException("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new RuntimeException("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new RuntimeException("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new RuntimeException("treesTest O failed");
+
+      if (enum_thorough_proper.treesTest1(pine) != pine) throw new RuntimeException("treesTest Global 1 failed");
+      if (enum_thorough_proper.treesTest2(pine) != pine) throw new RuntimeException("treesTest Global 2 failed");
+      if (enum_thorough_proper.treesTest3(pine) != pine) throw new RuntimeException("treesTest Global 3 failed");
+      if (enum_thorough_proper.treesTest4(pine) != pine) throw new RuntimeException("treesTest Global 4 failed");
+      if (enum_thorough_proper.treesTest5(pine) != pine) throw new RuntimeException("treesTest Global 5 failed");
+      if (enum_thorough_proper.treesTest6(pine) != pine) throw new RuntimeException("treesTest Global 6 failed");
+      if (enum_thorough_proper.treesTest7(pine) != pine) throw new RuntimeException("treesTest Global 7 failed");
+      if (enum_thorough_proper.treesTest8(pine) != pine) throw new RuntimeException("treesTest Global 8 failed");
+      if (enum_thorough_proper.treesTest9(pine) != pine) throw new RuntimeException("treesTest Global 9 failed");
+      if (enum_thorough_proper.treesTestA(pine) != pine) throw new RuntimeException("treesTest Global A failed");
+      if (enum_thorough_proper.treesTestB(pine) != pine) throw new RuntimeException("treesTest Global B failed");
+      if (enum_thorough_proper.treesTestC(pine) != pine) throw new RuntimeException("treesTest Global C failed");
+      if (enum_thorough_proper.treesTestD(pine) != pine) throw new RuntimeException("treesTest Global D failed");
+      if (enum_thorough_proper.treesTestE(pine) != pine) throw new RuntimeException("treesTest Global E failed");
+      if (enum_thorough_proper.treesTestF(pine) != pine) throw new RuntimeException("treesTest Global F failed");
+      if (enum_thorough_proper.treesTestG(pine) != pine) throw new RuntimeException("treesTest Global G failed");
+      if (enum_thorough_proper.treesTestH(pine) != pine) throw new RuntimeException("treesTest Global H failed");
+      if (enum_thorough_proper.treesTestI(pine) != pine) throw new RuntimeException("treesTest Global I failed");
+      if (enum_thorough_proper.treesTestJ(pine) != pine) throw new RuntimeException("treesTest Global J failed");
+      if (enum_thorough_proper.treesTestK(pine) != pine) throw new RuntimeException("treesTest Global K failed");
+      if (enum_thorough_proper.treesTestL(pine) != pine) throw new RuntimeException("treesTest Global L failed");
+      if (enum_thorough_proper.treesTestM(pine) != pine) throw new RuntimeException("treesTest Global M failed");
+//      if (enum_thorough_proper.treesTestN(pine) != pine) throw new RuntimeException("treesTest Global N failed");
+      if (enum_thorough_proper.treesTestO(pine) != pine) throw new RuntimeException("treesTest Global O failed");
+      if (enum_thorough_proper.treesTestP(pine) != pine) throw new RuntimeException("treesTest Global P failed");
+      if (enum_thorough_proper.treesTestQ(pine) != pine) throw new RuntimeException("treesTest Global Q failed");
+      if (enum_thorough_proper.treesTestR(pine) != pine) throw new RuntimeException("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      HairStruct.hair ginger = HairStruct.hair.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new RuntimeException("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new RuntimeException("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new RuntimeException("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new RuntimeException("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new RuntimeException("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new RuntimeException("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new RuntimeException("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new RuntimeException("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new RuntimeException("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new RuntimeException("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new RuntimeException("hairTest B failed");
+
+      colour red = colour.red;
+      if (h.colourTest1(red) != red) throw new RuntimeException("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new RuntimeException("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new RuntimeException("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new RuntimeException("namedanonspaceTest HairStruct 1 failed");
+
+      TreesClass.trees fir = TreesClass.trees.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+      if (enum_thorough_proper.hairTest1(blonde) != blonde) throw new RuntimeException("hairTest Global 1 failed");
+      if (enum_thorough_proper.hairTest2(blonde) != blonde) throw new RuntimeException("hairTest Global 2 failed");
+      if (enum_thorough_proper.hairTest3(blonde) != blonde) throw new RuntimeException("hairTest Global 3 failed");
+      if (enum_thorough_proper.hairTest4(blonde) != blonde) throw new RuntimeException("hairTest Global 4 failed");
+      if (enum_thorough_proper.hairTest5(blonde) != blonde) throw new RuntimeException("hairTest Global 5 failed");
+      if (enum_thorough_proper.hairTest6(blonde) != blonde) throw new RuntimeException("hairTest Global 6 failed");
+      if (enum_thorough_proper.hairTest7(blonde) != blonde) throw new RuntimeException("hairTest Global 7 failed");
+      if (enum_thorough_proper.hairTest8(blonde) != blonde) throw new RuntimeException("hairTest Global 8 failed");
+      if (enum_thorough_proper.hairTest9(blonde) != blonde) throw new RuntimeException("hairTest Global 9 failed");
+      if (enum_thorough_proper.hairTestA(blonde) != blonde) throw new RuntimeException("hairTest Global A failed");
+      if (enum_thorough_proper.hairTestB(blonde) != blonde) throw new RuntimeException("hairTest Global B failed");
+      if (enum_thorough_proper.hairTestC(blonde) != blonde) throw new RuntimeException("hairTest Global C failed");
+
+      if (enum_thorough_proper.hairTestA1(blonde) != blonde) throw new RuntimeException("hairTest Global A1 failed");
+      if (enum_thorough_proper.hairTestA2(blonde) != blonde) throw new RuntimeException("hairTest Global A2 failed");
+      if (enum_thorough_proper.hairTestA3(blonde) != blonde) throw new RuntimeException("hairTest Global A3 failed");
+      if (enum_thorough_proper.hairTestA4(blonde) != blonde) throw new RuntimeException("hairTest Global A4 failed");
+      if (enum_thorough_proper.hairTestA5(blonde) != blonde) throw new RuntimeException("hairTest Global A5 failed");
+      if (enum_thorough_proper.hairTestA6(blonde) != blonde) throw new RuntimeException("hairTest Global A6 failed");
+      if (enum_thorough_proper.hairTestA7(blonde) != blonde) throw new RuntimeException("hairTest Global A7 failed");
+      if (enum_thorough_proper.hairTestA8(blonde) != blonde) throw new RuntimeException("hairTest Global A8 failed");
+      if (enum_thorough_proper.hairTestA9(blonde) != blonde) throw new RuntimeException("hairTest Global A9 failed");
+      if (enum_thorough_proper.hairTestAA(blonde) != blonde) throw new RuntimeException("hairTest Global AA failed");
+      if (enum_thorough_proper.hairTestAB(blonde) != blonde) throw new RuntimeException("hairTest Global AB failed");
+      if (enum_thorough_proper.hairTestAC(blonde) != blonde) throw new RuntimeException("hairTest Global AC failed");
+
+      if (enum_thorough_proper.hairTestB1(blonde) != blonde) throw new RuntimeException("hairTest Global B1 failed");
+      if (enum_thorough_proper.hairTestB2(blonde) != blonde) throw new RuntimeException("hairTest Global B2 failed");
+      if (enum_thorough_proper.hairTestB3(blonde) != blonde) throw new RuntimeException("hairTest Global B3 failed");
+      if (enum_thorough_proper.hairTestB4(blonde) != blonde) throw new RuntimeException("hairTest Global B4 failed");
+      if (enum_thorough_proper.hairTestB5(blonde) != blonde) throw new RuntimeException("hairTest Global B5 failed");
+      if (enum_thorough_proper.hairTestB6(blonde) != blonde) throw new RuntimeException("hairTest Global B6 failed");
+      if (enum_thorough_proper.hairTestB7(blonde) != blonde) throw new RuntimeException("hairTest Global B7 failed");
+      if (enum_thorough_proper.hairTestB8(blonde) != blonde) throw new RuntimeException("hairTest Global B8 failed");
+      if (enum_thorough_proper.hairTestB9(blonde) != blonde) throw new RuntimeException("hairTest Global B9 failed");
+      if (enum_thorough_proper.hairTestBA(blonde) != blonde) throw new RuntimeException("hairTest Global BA failed");
+      if (enum_thorough_proper.hairTestBB(blonde) != blonde) throw new RuntimeException("hairTest Global BB failed");
+      if (enum_thorough_proper.hairTestBC(blonde) != blonde) throw new RuntimeException("hairTest Global BC failed");
+
+      if (enum_thorough_proper.hairTestC1(blonde) != blonde) throw new RuntimeException("hairTest Global C1 failed");
+      if (enum_thorough_proper.hairTestC2(blonde) != blonde) throw new RuntimeException("hairTest Global C2 failed");
+      if (enum_thorough_proper.hairTestC3(blonde) != blonde) throw new RuntimeException("hairTest Global C3 failed");
+      if (enum_thorough_proper.hairTestC4(blonde) != blonde) throw new RuntimeException("hairTest Global C4 failed");
+      if (enum_thorough_proper.hairTestC5(blonde) != blonde) throw new RuntimeException("hairTest Global C5 failed");
+      if (enum_thorough_proper.hairTestC6(blonde) != blonde) throw new RuntimeException("hairTest Global C6 failed");
+      if (enum_thorough_proper.hairTestC7(blonde) != blonde) throw new RuntimeException("hairTest Global C7 failed");
+      if (enum_thorough_proper.hairTestC8(blonde) != blonde) throw new RuntimeException("hairTest Global C8 failed");
+      if (enum_thorough_proper.hairTestC9(blonde) != blonde) throw new RuntimeException("hairTest Global C9 failed");
+      if (enum_thorough_proper.hairTestCA(blonde) != blonde) throw new RuntimeException("hairTest Global CA failed");
+      if (enum_thorough_proper.hairTestCB(blonde) != blonde) throw new RuntimeException("hairTest Global CB failed");
+      if (enum_thorough_proper.hairTestCC(blonde) != blonde) throw new RuntimeException("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new RuntimeException("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new RuntimeException("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new RuntimeException("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new RuntimeException("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new RuntimeException("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new RuntimeException("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new RuntimeException("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new RuntimeException("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new RuntimeException("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new RuntimeException("hairTestFir A failed");
+    }
+    {
+      enum_thorough_proper.setGlobalInstance(enum_thorough_proper.globalinstance2);
+      if (enum_thorough_proper.getGlobalInstance() != enum_thorough_proper.globalinstance2) throw new RuntimeException("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.setMemberInstance(Instances.memberinstance3);
+      if (i.getMemberInstance() != Instances.memberinstance3) throw new RuntimeException("MemberInstance 1 failed");
+    }
+    {
+      if (enum_thorough_proper.repeatTest(repeat.one).swigValue() != 1) throw new RuntimeException("repeatTest 1 failed");
+      if (enum_thorough_proper.repeatTest(repeat.initial).swigValue() != 1) throw new RuntimeException("repeatTest 2 failed");
+      if (enum_thorough_proper.repeatTest(repeat.two).swigValue() != 2) throw new RuntimeException("repeatTest 3 failed");
+      if (enum_thorough_proper.repeatTest(repeat.three).swigValue() != 3) throw new RuntimeException("repeatTest 4 failed");
+      if (enum_thorough_proper.repeatTest(repeat.last).swigValue() != 3) throw new RuntimeException("repeatTest 5 failed");
+      if (enum_thorough_proper.repeatTest(repeat.end).swigValue() != 3) throw new RuntimeException("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/enum_thorough_runme.java b/trunk/Examples/test-suite/java/enum_thorough_runme.java
new file mode 100644
index 0000000..1cd02d3
--- /dev/null
+++ b/trunk/Examples/test-suite/java/enum_thorough_runme.java
@@ -0,0 +1,382 @@
+
+import enum_thorough.*;
+
+public class enum_thorough_runme {
+
+  static {
+    try {
+        System.loadLibrary("enum_thorough");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    {
+      // Anonymous enums
+      int i = enum_thorough.AnonEnum1;
+      if (enum_thorough.ReallyAnInteger != 200) throw new RuntimeException("Test Anon 1 failed");
+      int j = enum_thorough.AnonSpaceEnum1;
+      int k = AnonStruct.AnonStructEnum1;
+    }
+    {
+      colour red = colour.red;
+      enum_thorough.colourTest1(red);
+      enum_thorough.colourTest2(red);
+      enum_thorough.colourTest3(red);
+      enum_thorough.colourTest4(red);
+      enum_thorough.setMyColour(red);
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed speed = SpeedClass.speed.slow;
+      if (s.speedTest1(speed) != speed) throw new RuntimeException("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new RuntimeException("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new RuntimeException("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new RuntimeException("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new RuntimeException("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new RuntimeException("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new RuntimeException("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new RuntimeException("speedTest 8 failed");
+
+      if (enum_thorough.speedTest1(speed) != speed) throw new RuntimeException("speedTest Global 1 failed");
+      if (enum_thorough.speedTest2(speed) != speed) throw new RuntimeException("speedTest Global 2 failed");
+      if (enum_thorough.speedTest3(speed) != speed) throw new RuntimeException("speedTest Global 3 failed");
+      if (enum_thorough.speedTest4(speed) != speed) throw new RuntimeException("speedTest Global 4 failed");
+      if (enum_thorough.speedTest5(speed) != speed) throw new RuntimeException("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      SpeedClass.speed slow = SpeedClass.speed.slow;
+      SpeedClass.speed lightning = SpeedClass.speed.lightning;
+
+      if (s.getMySpeedtd1() != slow) throw new RuntimeException("mySpeedtd1 1 failed");
+      if (s.getMySpeedtd1().swigValue() != 10) throw new RuntimeException("mySpeedtd1 2 failed");
+
+      s.setMySpeedtd1(lightning);
+      if (s.getMySpeedtd1() != lightning) throw new RuntimeException("mySpeedtd1 3 failed");
+      if (s.getMySpeedtd1().swigValue() != 31) throw new RuntimeException("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new RuntimeException("namedanonTest 1 failed");
+    }
+    {
+      twonames val = twonames.TwoNames2;
+      if (enum_thorough.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (enum_thorough.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (enum_thorough.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      TwoNamesStruct.twonames val = TwoNamesStruct.twonames.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      namedanonspace val = namedanonspace.NamedAnonSpace2;
+      if (enum_thorough.namedanonspaceTest1(val) != val) throw new RuntimeException("namedanonspaceTest 1 failed");
+      if (enum_thorough.namedanonspaceTest2(val) != val) throw new RuntimeException("namedanonspaceTest 2 failed");
+      if (enum_thorough.namedanonspaceTest3(val) != val) throw new RuntimeException("namedanonspaceTest 3 failed");
+      if (enum_thorough.namedanonspaceTest4(val) != val) throw new RuntimeException("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new RuntimeException("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new RuntimeException("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new RuntimeException("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new RuntimeException("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new RuntimeException("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new RuntimeException("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new RuntimeException("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new RuntimeException("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new RuntimeException("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new RuntimeException("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new RuntimeException("scientistsTest J failed");
+
+      if (enum_thorough.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest Global 1 failed");
+      if (enum_thorough.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest Global 2 failed");
+      if (enum_thorough.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest Global 3 failed");
+      if (enum_thorough.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest Global 4 failed");
+      if (enum_thorough.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest Global 5 failed");
+      if (enum_thorough.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest Global 6 failed");
+      if (enum_thorough.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest Global 7 failed");
+      if (enum_thorough.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      TClassInt.scientists bell = TClassInt.scientists.bell;
+      TemplateClassInt.scientists galileo = TemplateClassInt.scientists.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new RuntimeException("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new RuntimeException("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new RuntimeException("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new RuntimeException("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new RuntimeException("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new RuntimeException("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new RuntimeException("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new RuntimeException("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new RuntimeException("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new RuntimeException("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new RuntimeException("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 7 failed");
+
+      if (enum_thorough.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest Global 1 failed");
+      if (enum_thorough.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest Global 2 failed");
+      if (enum_thorough.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest Global 3 failed");
+      if (enum_thorough.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest Global 4 failed");
+      if (enum_thorough.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest Global 5 failed");
+      if (enum_thorough.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest Global 6 failed");
+      if (enum_thorough.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough.scientistsNameSpaceTest8(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough.scientistsNameSpaceTest9(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough.scientistsNameSpaceTestA(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough.scientistsNameSpaceTestB(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough.scientistsNameSpaceTestC(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough.scientistsNameSpaceTestD(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough.scientistsNameSpaceTestE(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough.scientistsNameSpaceTestF(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough.scientistsNameSpaceTestG(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough.scientistsNameSpaceTestH(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough.scientistsNameSpaceTestI(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough.scientistsNameSpaceTestJ(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough.scientistsNameSpaceTestK(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough.scientistsNameSpaceTestL(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      newname val = newname.argh;
+      if (enum_thorough.renameTest1(val) != val) throw new RuntimeException("renameTest Global 1 failed");
+      if (enum_thorough.renameTest2(val) != val) throw new RuntimeException("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new RuntimeException("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new RuntimeException("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest Global 3 failed");
+      if (enum_thorough.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new RuntimeException("renameTest Global 4 failed");
+      if (enum_thorough.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest Global 5 failed");
+      if (enum_thorough.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest Global 6 failed");
+      if (enum_thorough.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new RuntimeException("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      TreesClass.trees pine = TreesClass.trees.pine;
+
+      if (t.treesTest1(pine) != pine) throw new RuntimeException("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new RuntimeException("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new RuntimeException("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new RuntimeException("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new RuntimeException("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new RuntimeException("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new RuntimeException("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new RuntimeException("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new RuntimeException("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new RuntimeException("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new RuntimeException("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new RuntimeException("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new RuntimeException("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new RuntimeException("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new RuntimeException("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new RuntimeException("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new RuntimeException("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new RuntimeException("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new RuntimeException("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new RuntimeException("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new RuntimeException("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new RuntimeException("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new RuntimeException("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new RuntimeException("treesTest O failed");
+
+      if (enum_thorough.treesTest1(pine) != pine) throw new RuntimeException("treesTest Global 1 failed");
+      if (enum_thorough.treesTest2(pine) != pine) throw new RuntimeException("treesTest Global 2 failed");
+      if (enum_thorough.treesTest3(pine) != pine) throw new RuntimeException("treesTest Global 3 failed");
+      if (enum_thorough.treesTest4(pine) != pine) throw new RuntimeException("treesTest Global 4 failed");
+      if (enum_thorough.treesTest5(pine) != pine) throw new RuntimeException("treesTest Global 5 failed");
+      if (enum_thorough.treesTest6(pine) != pine) throw new RuntimeException("treesTest Global 6 failed");
+      if (enum_thorough.treesTest7(pine) != pine) throw new RuntimeException("treesTest Global 7 failed");
+      if (enum_thorough.treesTest8(pine) != pine) throw new RuntimeException("treesTest Global 8 failed");
+      if (enum_thorough.treesTest9(pine) != pine) throw new RuntimeException("treesTest Global 9 failed");
+      if (enum_thorough.treesTestA(pine) != pine) throw new RuntimeException("treesTest Global A failed");
+      if (enum_thorough.treesTestB(pine) != pine) throw new RuntimeException("treesTest Global B failed");
+      if (enum_thorough.treesTestC(pine) != pine) throw new RuntimeException("treesTest Global C failed");
+      if (enum_thorough.treesTestD(pine) != pine) throw new RuntimeException("treesTest Global D failed");
+      if (enum_thorough.treesTestE(pine) != pine) throw new RuntimeException("treesTest Global E failed");
+      if (enum_thorough.treesTestF(pine) != pine) throw new RuntimeException("treesTest Global F failed");
+      if (enum_thorough.treesTestG(pine) != pine) throw new RuntimeException("treesTest Global G failed");
+      if (enum_thorough.treesTestH(pine) != pine) throw new RuntimeException("treesTest Global H failed");
+      if (enum_thorough.treesTestI(pine) != pine) throw new RuntimeException("treesTest Global I failed");
+      if (enum_thorough.treesTestJ(pine) != pine) throw new RuntimeException("treesTest Global J failed");
+      if (enum_thorough.treesTestK(pine) != pine) throw new RuntimeException("treesTest Global K failed");
+      if (enum_thorough.treesTestL(pine) != pine) throw new RuntimeException("treesTest Global L failed");
+      if (enum_thorough.treesTestM(pine) != pine) throw new RuntimeException("treesTest Global M failed");
+//      if (enum_thorough.treesTestN(pine) != pine) throw new RuntimeException("treesTest Global N failed");
+      if (enum_thorough.treesTestO(pine) != pine) throw new RuntimeException("treesTest Global O failed");
+      if (enum_thorough.treesTestP(pine) != pine) throw new RuntimeException("treesTest Global P failed");
+      if (enum_thorough.treesTestQ(pine) != pine) throw new RuntimeException("treesTest Global Q failed");
+      if (enum_thorough.treesTestR(pine) != pine) throw new RuntimeException("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      HairStruct.hair ginger = HairStruct.hair.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new RuntimeException("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new RuntimeException("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new RuntimeException("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new RuntimeException("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new RuntimeException("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new RuntimeException("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new RuntimeException("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new RuntimeException("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new RuntimeException("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new RuntimeException("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new RuntimeException("hairTest B failed");
+
+      colour red = colour.red;
+      if (h.colourTest1(red) != red) throw new RuntimeException("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new RuntimeException("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new RuntimeException("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new RuntimeException("namedanonspaceTest HairStruct 1 failed");
+
+      TreesClass.trees fir = TreesClass.trees.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+      if (enum_thorough.hairTest1(blonde) != blonde) throw new RuntimeException("hairTest Global 1 failed");
+      if (enum_thorough.hairTest2(blonde) != blonde) throw new RuntimeException("hairTest Global 2 failed");
+      if (enum_thorough.hairTest3(blonde) != blonde) throw new RuntimeException("hairTest Global 3 failed");
+      if (enum_thorough.hairTest4(blonde) != blonde) throw new RuntimeException("hairTest Global 4 failed");
+      if (enum_thorough.hairTest5(blonde) != blonde) throw new RuntimeException("hairTest Global 5 failed");
+      if (enum_thorough.hairTest6(blonde) != blonde) throw new RuntimeException("hairTest Global 6 failed");
+      if (enum_thorough.hairTest7(blonde) != blonde) throw new RuntimeException("hairTest Global 7 failed");
+      if (enum_thorough.hairTest8(blonde) != blonde) throw new RuntimeException("hairTest Global 8 failed");
+      if (enum_thorough.hairTest9(blonde) != blonde) throw new RuntimeException("hairTest Global 9 failed");
+      if (enum_thorough.hairTestA(blonde) != blonde) throw new RuntimeException("hairTest Global A failed");
+      if (enum_thorough.hairTestB(blonde) != blonde) throw new RuntimeException("hairTest Global B failed");
+      if (enum_thorough.hairTestC(blonde) != blonde) throw new RuntimeException("hairTest Global C failed");
+
+      if (enum_thorough.hairTestA1(blonde) != blonde) throw new RuntimeException("hairTest Global A1 failed");
+      if (enum_thorough.hairTestA2(blonde) != blonde) throw new RuntimeException("hairTest Global A2 failed");
+      if (enum_thorough.hairTestA3(blonde) != blonde) throw new RuntimeException("hairTest Global A3 failed");
+      if (enum_thorough.hairTestA4(blonde) != blonde) throw new RuntimeException("hairTest Global A4 failed");
+      if (enum_thorough.hairTestA5(blonde) != blonde) throw new RuntimeException("hairTest Global A5 failed");
+      if (enum_thorough.hairTestA6(blonde) != blonde) throw new RuntimeException("hairTest Global A6 failed");
+      if (enum_thorough.hairTestA7(blonde) != blonde) throw new RuntimeException("hairTest Global A7 failed");
+      if (enum_thorough.hairTestA8(blonde) != blonde) throw new RuntimeException("hairTest Global A8 failed");
+      if (enum_thorough.hairTestA9(blonde) != blonde) throw new RuntimeException("hairTest Global A9 failed");
+      if (enum_thorough.hairTestAA(blonde) != blonde) throw new RuntimeException("hairTest Global AA failed");
+      if (enum_thorough.hairTestAB(blonde) != blonde) throw new RuntimeException("hairTest Global AB failed");
+      if (enum_thorough.hairTestAC(blonde) != blonde) throw new RuntimeException("hairTest Global AC failed");
+
+      if (enum_thorough.hairTestB1(blonde) != blonde) throw new RuntimeException("hairTest Global B1 failed");
+      if (enum_thorough.hairTestB2(blonde) != blonde) throw new RuntimeException("hairTest Global B2 failed");
+      if (enum_thorough.hairTestB3(blonde) != blonde) throw new RuntimeException("hairTest Global B3 failed");
+      if (enum_thorough.hairTestB4(blonde) != blonde) throw new RuntimeException("hairTest Global B4 failed");
+      if (enum_thorough.hairTestB5(blonde) != blonde) throw new RuntimeException("hairTest Global B5 failed");
+      if (enum_thorough.hairTestB6(blonde) != blonde) throw new RuntimeException("hairTest Global B6 failed");
+      if (enum_thorough.hairTestB7(blonde) != blonde) throw new RuntimeException("hairTest Global B7 failed");
+      if (enum_thorough.hairTestB8(blonde) != blonde) throw new RuntimeException("hairTest Global B8 failed");
+      if (enum_thorough.hairTestB9(blonde) != blonde) throw new RuntimeException("hairTest Global B9 failed");
+      if (enum_thorough.hairTestBA(blonde) != blonde) throw new RuntimeException("hairTest Global BA failed");
+      if (enum_thorough.hairTestBB(blonde) != blonde) throw new RuntimeException("hairTest Global BB failed");
+      if (enum_thorough.hairTestBC(blonde) != blonde) throw new RuntimeException("hairTest Global BC failed");
+
+      if (enum_thorough.hairTestC1(blonde) != blonde) throw new RuntimeException("hairTest Global C1 failed");
+      if (enum_thorough.hairTestC2(blonde) != blonde) throw new RuntimeException("hairTest Global C2 failed");
+      if (enum_thorough.hairTestC3(blonde) != blonde) throw new RuntimeException("hairTest Global C3 failed");
+      if (enum_thorough.hairTestC4(blonde) != blonde) throw new RuntimeException("hairTest Global C4 failed");
+      if (enum_thorough.hairTestC5(blonde) != blonde) throw new RuntimeException("hairTest Global C5 failed");
+      if (enum_thorough.hairTestC6(blonde) != blonde) throw new RuntimeException("hairTest Global C6 failed");
+      if (enum_thorough.hairTestC7(blonde) != blonde) throw new RuntimeException("hairTest Global C7 failed");
+      if (enum_thorough.hairTestC8(blonde) != blonde) throw new RuntimeException("hairTest Global C8 failed");
+      if (enum_thorough.hairTestC9(blonde) != blonde) throw new RuntimeException("hairTest Global C9 failed");
+      if (enum_thorough.hairTestCA(blonde) != blonde) throw new RuntimeException("hairTest Global CA failed");
+      if (enum_thorough.hairTestCB(blonde) != blonde) throw new RuntimeException("hairTest Global CB failed");
+      if (enum_thorough.hairTestCC(blonde) != blonde) throw new RuntimeException("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      HairStruct.hair blonde = HairStruct.hair.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new RuntimeException("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new RuntimeException("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new RuntimeException("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new RuntimeException("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new RuntimeException("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new RuntimeException("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new RuntimeException("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new RuntimeException("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new RuntimeException("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new RuntimeException("hairTestFir A failed");
+    }
+    {
+      enum_thorough.setGlobalInstance(enum_thorough.globalinstance2);
+      if (enum_thorough.getGlobalInstance() != enum_thorough.globalinstance2) throw new RuntimeException("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.setMemberInstance(Instances.memberinstance3);
+      if (i.getMemberInstance() != Instances.memberinstance3) throw new RuntimeException("MemberInstance 1 failed");
+    }
+    {
+      if (enum_thorough.repeatTest(repeat.one).swigValue() != 1) throw new RuntimeException("repeatTest 1 failed");
+      if (enum_thorough.repeatTest(repeat.initial).swigValue() != 1) throw new RuntimeException("repeatTest 2 failed");
+      if (enum_thorough.repeatTest(repeat.two).swigValue() != 2) throw new RuntimeException("repeatTest 3 failed");
+      if (enum_thorough.repeatTest(repeat.three).swigValue() != 3) throw new RuntimeException("repeatTest 4 failed");
+      if (enum_thorough.repeatTest(repeat.last).swigValue() != 3) throw new RuntimeException("repeatTest 5 failed");
+      if (enum_thorough.repeatTest(repeat.end).swigValue() != 3) throw new RuntimeException("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/enum_thorough_simple_runme.java b/trunk/Examples/test-suite/java/enum_thorough_simple_runme.java
new file mode 100644
index 0000000..9bd5627
--- /dev/null
+++ b/trunk/Examples/test-suite/java/enum_thorough_simple_runme.java
@@ -0,0 +1,382 @@
+
+import enum_thorough_simple.*;
+
+public class enum_thorough_simple_runme {
+
+  static {
+    try {
+        System.loadLibrary("enum_thorough_simple");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    {
+      // Anonymous enums
+      int i = enum_thorough_simple.AnonEnum1;
+      if (enum_thorough_simple.ReallyAnInteger != 200) throw new RuntimeException("Test Anon 1 failed");
+      int j = enum_thorough_simple.AnonSpaceEnum1;
+      int k = AnonStruct.AnonStructEnum1;
+    }
+    {
+      int red = enum_thorough_simple.red;
+      enum_thorough_simple.colourTest1(red);
+      enum_thorough_simple.colourTest2(red);
+      enum_thorough_simple.colourTest3(red);
+      enum_thorough_simple.colourTest4(red);
+      enum_thorough_simple.setMyColour(red);
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      int speed = SpeedClass.slow;
+      if (s.speedTest1(speed) != speed) throw new RuntimeException("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new RuntimeException("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new RuntimeException("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new RuntimeException("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new RuntimeException("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new RuntimeException("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new RuntimeException("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new RuntimeException("speedTest 8 failed");
+
+      if (enum_thorough_simple.speedTest1(speed) != speed) throw new RuntimeException("speedTest Global 1 failed");
+      if (enum_thorough_simple.speedTest2(speed) != speed) throw new RuntimeException("speedTest Global 2 failed");
+      if (enum_thorough_simple.speedTest3(speed) != speed) throw new RuntimeException("speedTest Global 3 failed");
+      if (enum_thorough_simple.speedTest4(speed) != speed) throw new RuntimeException("speedTest Global 4 failed");
+      if (enum_thorough_simple.speedTest5(speed) != speed) throw new RuntimeException("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      int slow = SpeedClass.slow;
+      int lightning = SpeedClass.lightning;
+
+      if (s.getMySpeedtd1() != slow) throw new RuntimeException("mySpeedtd1 1 failed");
+      if (s.getMySpeedtd1() != 10) throw new RuntimeException("mySpeedtd1 2 failed");
+
+      s.setMySpeedtd1(lightning);
+      if (s.getMySpeedtd1() != lightning) throw new RuntimeException("mySpeedtd1 3 failed");
+      if (s.getMySpeedtd1() != 31) throw new RuntimeException("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough_simple.namedanonTest1(enum_thorough_simple.NamedAnon2) != enum_thorough_simple.NamedAnon2) throw new RuntimeException("namedanonTest 1 failed");
+    }
+    {
+      int val = enum_thorough_simple.TwoNames2;
+      if (enum_thorough_simple.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (enum_thorough_simple.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (enum_thorough_simple.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      int val = TwoNamesStruct.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      int val = enum_thorough_simple.NamedAnonSpace2;
+      if (enum_thorough_simple.namedanonspaceTest1(val) != val) throw new RuntimeException("namedanonspaceTest 1 failed");
+      if (enum_thorough_simple.namedanonspaceTest2(val) != val) throw new RuntimeException("namedanonspaceTest 2 failed");
+      if (enum_thorough_simple.namedanonspaceTest3(val) != val) throw new RuntimeException("namedanonspaceTest 3 failed");
+      if (enum_thorough_simple.namedanonspaceTest4(val) != val) throw new RuntimeException("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      int galileo = TemplateClassInt.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new RuntimeException("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new RuntimeException("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new RuntimeException("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new RuntimeException("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new RuntimeException("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new RuntimeException("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new RuntimeException("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new RuntimeException("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new RuntimeException("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new RuntimeException("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new RuntimeException("scientistsTest J failed");
+
+      if (enum_thorough_simple.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest Global 1 failed");
+      if (enum_thorough_simple.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest Global 2 failed");
+      if (enum_thorough_simple.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest Global 3 failed");
+      if (enum_thorough_simple.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest Global 4 failed");
+      if (enum_thorough_simple.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest Global 5 failed");
+      if (enum_thorough_simple.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest Global 6 failed");
+      if (enum_thorough_simple.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest Global 7 failed");
+      if (enum_thorough_simple.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      int bell = TClassInt.bell;
+      int galileo = TemplateClassInt.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new RuntimeException("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new RuntimeException("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new RuntimeException("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new RuntimeException("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new RuntimeException("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new RuntimeException("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new RuntimeException("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new RuntimeException("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new RuntimeException("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new RuntimeException("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new RuntimeException("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 7 failed");
+
+      if (enum_thorough_simple.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest Global 1 failed");
+      if (enum_thorough_simple.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest Global 2 failed");
+      if (enum_thorough_simple.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest Global 3 failed");
+      if (enum_thorough_simple.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest Global 4 failed");
+      if (enum_thorough_simple.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest Global 5 failed");
+      if (enum_thorough_simple.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest Global 6 failed");
+      if (enum_thorough_simple.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough_simple.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough_simple.scientistsNameSpaceTest8(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTest9(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestA(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestB(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestC(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestD(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestE(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough_simple.scientistsNameSpaceTestF(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestG(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestH(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestI(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestJ(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestK(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough_simple.scientistsNameSpaceTestL(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      int val = enum_thorough_simple.argh;
+      if (enum_thorough_simple.renameTest1(val) != val) throw new RuntimeException("renameTest Global 1 failed");
+      if (enum_thorough_simple.renameTest2(val) != val) throw new RuntimeException("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.bang) != NewNameStruct.bang) throw new RuntimeException("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.bang) != NewNameStruct.bang) throw new RuntimeException("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simple1) != NewNameStruct.simple1) throw new RuntimeException("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new RuntimeException("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new RuntimeException("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlename1) != NewNameStruct.singlename1) throw new RuntimeException("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough_simple.renameTest3(NewNameStruct.bang) != NewNameStruct.bang) throw new RuntimeException("renameTest Global 3 failed");
+      if (enum_thorough_simple.renameTest4(NewNameStruct.simple1) != NewNameStruct.simple1) throw new RuntimeException("renameTest Global 4 failed");
+      if (enum_thorough_simple.renameTest5(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new RuntimeException("renameTest Global 5 failed");
+      if (enum_thorough_simple.renameTest6(NewNameStruct.doublename1) != NewNameStruct.doublename1) throw new RuntimeException("renameTest Global 6 failed");
+      if (enum_thorough_simple.renameTest7(NewNameStruct.singlename1) != NewNameStruct.singlename1) throw new RuntimeException("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      int pine = TreesClass.pine;
+
+      if (t.treesTest1(pine) != pine) throw new RuntimeException("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new RuntimeException("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new RuntimeException("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new RuntimeException("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new RuntimeException("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new RuntimeException("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new RuntimeException("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new RuntimeException("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new RuntimeException("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new RuntimeException("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new RuntimeException("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new RuntimeException("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new RuntimeException("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new RuntimeException("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new RuntimeException("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new RuntimeException("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new RuntimeException("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new RuntimeException("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new RuntimeException("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new RuntimeException("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new RuntimeException("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new RuntimeException("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new RuntimeException("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new RuntimeException("treesTest O failed");
+
+      if (enum_thorough_simple.treesTest1(pine) != pine) throw new RuntimeException("treesTest Global 1 failed");
+      if (enum_thorough_simple.treesTest2(pine) != pine) throw new RuntimeException("treesTest Global 2 failed");
+      if (enum_thorough_simple.treesTest3(pine) != pine) throw new RuntimeException("treesTest Global 3 failed");
+      if (enum_thorough_simple.treesTest4(pine) != pine) throw new RuntimeException("treesTest Global 4 failed");
+      if (enum_thorough_simple.treesTest5(pine) != pine) throw new RuntimeException("treesTest Global 5 failed");
+      if (enum_thorough_simple.treesTest6(pine) != pine) throw new RuntimeException("treesTest Global 6 failed");
+      if (enum_thorough_simple.treesTest7(pine) != pine) throw new RuntimeException("treesTest Global 7 failed");
+      if (enum_thorough_simple.treesTest8(pine) != pine) throw new RuntimeException("treesTest Global 8 failed");
+      if (enum_thorough_simple.treesTest9(pine) != pine) throw new RuntimeException("treesTest Global 9 failed");
+      if (enum_thorough_simple.treesTestA(pine) != pine) throw new RuntimeException("treesTest Global A failed");
+      if (enum_thorough_simple.treesTestB(pine) != pine) throw new RuntimeException("treesTest Global B failed");
+      if (enum_thorough_simple.treesTestC(pine) != pine) throw new RuntimeException("treesTest Global C failed");
+      if (enum_thorough_simple.treesTestD(pine) != pine) throw new RuntimeException("treesTest Global D failed");
+      if (enum_thorough_simple.treesTestE(pine) != pine) throw new RuntimeException("treesTest Global E failed");
+      if (enum_thorough_simple.treesTestF(pine) != pine) throw new RuntimeException("treesTest Global F failed");
+      if (enum_thorough_simple.treesTestG(pine) != pine) throw new RuntimeException("treesTest Global G failed");
+      if (enum_thorough_simple.treesTestH(pine) != pine) throw new RuntimeException("treesTest Global H failed");
+      if (enum_thorough_simple.treesTestI(pine) != pine) throw new RuntimeException("treesTest Global I failed");
+      if (enum_thorough_simple.treesTestJ(pine) != pine) throw new RuntimeException("treesTest Global J failed");
+      if (enum_thorough_simple.treesTestK(pine) != pine) throw new RuntimeException("treesTest Global K failed");
+      if (enum_thorough_simple.treesTestL(pine) != pine) throw new RuntimeException("treesTest Global L failed");
+      if (enum_thorough_simple.treesTestM(pine) != pine) throw new RuntimeException("treesTest Global M failed");
+//      if (enum_thorough_simple.treesTestN(pine) != pine) throw new RuntimeException("treesTest Global N failed");
+      if (enum_thorough_simple.treesTestO(pine) != pine) throw new RuntimeException("treesTest Global O failed");
+      if (enum_thorough_simple.treesTestP(pine) != pine) throw new RuntimeException("treesTest Global P failed");
+      if (enum_thorough_simple.treesTestQ(pine) != pine) throw new RuntimeException("treesTest Global Q failed");
+      if (enum_thorough_simple.treesTestR(pine) != pine) throw new RuntimeException("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      int ginger = HairStruct.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new RuntimeException("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new RuntimeException("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new RuntimeException("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new RuntimeException("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new RuntimeException("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new RuntimeException("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new RuntimeException("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new RuntimeException("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new RuntimeException("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new RuntimeException("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new RuntimeException("hairTest B failed");
+
+      int red = enum_thorough_simple.red;
+      if (h.colourTest1(red) != red) throw new RuntimeException("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new RuntimeException("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(enum_thorough_simple.NamedAnon2) != enum_thorough_simple.NamedAnon2) throw new RuntimeException("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(enum_thorough_simple.NamedAnonSpace2) != enum_thorough_simple.NamedAnonSpace2) throw new RuntimeException("namedanonspaceTest HairStruct 1 failed");
+
+      int fir = TreesClass.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      int blonde = HairStruct.blonde;
+      if (enum_thorough_simple.hairTest1(blonde) != blonde) throw new RuntimeException("hairTest Global 1 failed");
+      if (enum_thorough_simple.hairTest2(blonde) != blonde) throw new RuntimeException("hairTest Global 2 failed");
+      if (enum_thorough_simple.hairTest3(blonde) != blonde) throw new RuntimeException("hairTest Global 3 failed");
+      if (enum_thorough_simple.hairTest4(blonde) != blonde) throw new RuntimeException("hairTest Global 4 failed");
+      if (enum_thorough_simple.hairTest5(blonde) != blonde) throw new RuntimeException("hairTest Global 5 failed");
+      if (enum_thorough_simple.hairTest6(blonde) != blonde) throw new RuntimeException("hairTest Global 6 failed");
+      if (enum_thorough_simple.hairTest7(blonde) != blonde) throw new RuntimeException("hairTest Global 7 failed");
+      if (enum_thorough_simple.hairTest8(blonde) != blonde) throw new RuntimeException("hairTest Global 8 failed");
+      if (enum_thorough_simple.hairTest9(blonde) != blonde) throw new RuntimeException("hairTest Global 9 failed");
+      if (enum_thorough_simple.hairTestA(blonde) != blonde) throw new RuntimeException("hairTest Global A failed");
+      if (enum_thorough_simple.hairTestB(blonde) != blonde) throw new RuntimeException("hairTest Global B failed");
+      if (enum_thorough_simple.hairTestC(blonde) != blonde) throw new RuntimeException("hairTest Global C failed");
+
+      if (enum_thorough_simple.hairTestA1(blonde) != blonde) throw new RuntimeException("hairTest Global A1 failed");
+      if (enum_thorough_simple.hairTestA2(blonde) != blonde) throw new RuntimeException("hairTest Global A2 failed");
+      if (enum_thorough_simple.hairTestA3(blonde) != blonde) throw new RuntimeException("hairTest Global A3 failed");
+      if (enum_thorough_simple.hairTestA4(blonde) != blonde) throw new RuntimeException("hairTest Global A4 failed");
+      if (enum_thorough_simple.hairTestA5(blonde) != blonde) throw new RuntimeException("hairTest Global A5 failed");
+      if (enum_thorough_simple.hairTestA6(blonde) != blonde) throw new RuntimeException("hairTest Global A6 failed");
+      if (enum_thorough_simple.hairTestA7(blonde) != blonde) throw new RuntimeException("hairTest Global A7 failed");
+      if (enum_thorough_simple.hairTestA8(blonde) != blonde) throw new RuntimeException("hairTest Global A8 failed");
+      if (enum_thorough_simple.hairTestA9(blonde) != blonde) throw new RuntimeException("hairTest Global A9 failed");
+      if (enum_thorough_simple.hairTestAA(blonde) != blonde) throw new RuntimeException("hairTest Global AA failed");
+      if (enum_thorough_simple.hairTestAB(blonde) != blonde) throw new RuntimeException("hairTest Global AB failed");
+      if (enum_thorough_simple.hairTestAC(blonde) != blonde) throw new RuntimeException("hairTest Global AC failed");
+
+      if (enum_thorough_simple.hairTestB1(blonde) != blonde) throw new RuntimeException("hairTest Global B1 failed");
+      if (enum_thorough_simple.hairTestB2(blonde) != blonde) throw new RuntimeException("hairTest Global B2 failed");
+      if (enum_thorough_simple.hairTestB3(blonde) != blonde) throw new RuntimeException("hairTest Global B3 failed");
+      if (enum_thorough_simple.hairTestB4(blonde) != blonde) throw new RuntimeException("hairTest Global B4 failed");
+      if (enum_thorough_simple.hairTestB5(blonde) != blonde) throw new RuntimeException("hairTest Global B5 failed");
+      if (enum_thorough_simple.hairTestB6(blonde) != blonde) throw new RuntimeException("hairTest Global B6 failed");
+      if (enum_thorough_simple.hairTestB7(blonde) != blonde) throw new RuntimeException("hairTest Global B7 failed");
+      if (enum_thorough_simple.hairTestB8(blonde) != blonde) throw new RuntimeException("hairTest Global B8 failed");
+      if (enum_thorough_simple.hairTestB9(blonde) != blonde) throw new RuntimeException("hairTest Global B9 failed");
+      if (enum_thorough_simple.hairTestBA(blonde) != blonde) throw new RuntimeException("hairTest Global BA failed");
+      if (enum_thorough_simple.hairTestBB(blonde) != blonde) throw new RuntimeException("hairTest Global BB failed");
+      if (enum_thorough_simple.hairTestBC(blonde) != blonde) throw new RuntimeException("hairTest Global BC failed");
+
+      if (enum_thorough_simple.hairTestC1(blonde) != blonde) throw new RuntimeException("hairTest Global C1 failed");
+      if (enum_thorough_simple.hairTestC2(blonde) != blonde) throw new RuntimeException("hairTest Global C2 failed");
+      if (enum_thorough_simple.hairTestC3(blonde) != blonde) throw new RuntimeException("hairTest Global C3 failed");
+      if (enum_thorough_simple.hairTestC4(blonde) != blonde) throw new RuntimeException("hairTest Global C4 failed");
+      if (enum_thorough_simple.hairTestC5(blonde) != blonde) throw new RuntimeException("hairTest Global C5 failed");
+      if (enum_thorough_simple.hairTestC6(blonde) != blonde) throw new RuntimeException("hairTest Global C6 failed");
+      if (enum_thorough_simple.hairTestC7(blonde) != blonde) throw new RuntimeException("hairTest Global C7 failed");
+      if (enum_thorough_simple.hairTestC8(blonde) != blonde) throw new RuntimeException("hairTest Global C8 failed");
+      if (enum_thorough_simple.hairTestC9(blonde) != blonde) throw new RuntimeException("hairTest Global C9 failed");
+      if (enum_thorough_simple.hairTestCA(blonde) != blonde) throw new RuntimeException("hairTest Global CA failed");
+      if (enum_thorough_simple.hairTestCB(blonde) != blonde) throw new RuntimeException("hairTest Global CB failed");
+      if (enum_thorough_simple.hairTestCC(blonde) != blonde) throw new RuntimeException("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      int blonde = HairStruct.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new RuntimeException("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new RuntimeException("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new RuntimeException("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new RuntimeException("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new RuntimeException("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new RuntimeException("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new RuntimeException("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new RuntimeException("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new RuntimeException("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new RuntimeException("hairTestFir A failed");
+    }
+    {
+      enum_thorough_simple.setGlobalInstance(enum_thorough_simple.globalinstance2);
+      if (enum_thorough_simple.getGlobalInstance() != enum_thorough_simple.globalinstance2) throw new RuntimeException("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.setMemberInstance(Instances.memberinstance3);
+      if (i.getMemberInstance() != Instances.memberinstance3) throw new RuntimeException("MemberInstance 1 failed");
+    }
+    {
+      if (enum_thorough_simple.repeatTest(enum_thorough_simpleConstants.one) != 1) throw new RuntimeException("repeatTest 1 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simpleConstants.initial) != 1) throw new RuntimeException("repeatTest 2 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simpleConstants.two) != 2) throw new RuntimeException("repeatTest 3 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simpleConstants.three) != 3) throw new RuntimeException("repeatTest 4 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simpleConstants.last) != 3) throw new RuntimeException("repeatTest 5 failed");
+      if (enum_thorough_simple.repeatTest(enum_thorough_simpleConstants.end) != 3) throw new RuntimeException("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/enum_thorough_typeunsafe_runme.java b/trunk/Examples/test-suite/java/enum_thorough_typeunsafe_runme.java
new file mode 100644
index 0000000..35d1a19
--- /dev/null
+++ b/trunk/Examples/test-suite/java/enum_thorough_typeunsafe_runme.java
@@ -0,0 +1,382 @@
+
+import enum_thorough_typeunsafe.*;
+
+public class enum_thorough_typeunsafe_runme {
+
+  static {
+    try {
+        System.loadLibrary("enum_thorough_typeunsafe");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    {
+      // Anonymous enums
+      int i = enum_thorough_typeunsafe.AnonEnum1;
+      if (enum_thorough_typeunsafe.ReallyAnInteger != 200) throw new RuntimeException("Test Anon 1 failed");
+      int j = enum_thorough_typeunsafe.AnonSpaceEnum1;
+      int k = AnonStruct.AnonStructEnum1;
+    }
+    {
+      int red = colour.red;
+      enum_thorough_typeunsafe.colourTest1(red);
+      enum_thorough_typeunsafe.colourTest2(red);
+      enum_thorough_typeunsafe.colourTest3(red);
+      enum_thorough_typeunsafe.colourTest4(red);
+      enum_thorough_typeunsafe.setMyColour(red);
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      int speed = SpeedClass.speed.slow;
+      if (s.speedTest1(speed) != speed) throw new RuntimeException("speedTest 1 failed");
+      if (s.speedTest2(speed) != speed) throw new RuntimeException("speedTest 2 failed");
+      if (s.speedTest3(speed) != speed) throw new RuntimeException("speedTest 3 failed");
+      if (s.speedTest4(speed) != speed) throw new RuntimeException("speedTest 4 failed");
+      if (s.speedTest5(speed) != speed) throw new RuntimeException("speedTest 5 failed");
+      if (s.speedTest6(speed) != speed) throw new RuntimeException("speedTest 6 failed");
+      if (s.speedTest7(speed) != speed) throw new RuntimeException("speedTest 7 failed");
+      if (s.speedTest8(speed) != speed) throw new RuntimeException("speedTest 8 failed");
+
+      if (enum_thorough_typeunsafe.speedTest1(speed) != speed) throw new RuntimeException("speedTest Global 1 failed");
+      if (enum_thorough_typeunsafe.speedTest2(speed) != speed) throw new RuntimeException("speedTest Global 2 failed");
+      if (enum_thorough_typeunsafe.speedTest3(speed) != speed) throw new RuntimeException("speedTest Global 3 failed");
+      if (enum_thorough_typeunsafe.speedTest4(speed) != speed) throw new RuntimeException("speedTest Global 4 failed");
+      if (enum_thorough_typeunsafe.speedTest5(speed) != speed) throw new RuntimeException("speedTest Global 5 failed");
+    }
+    {
+      SpeedClass s = new SpeedClass();
+      int slow = SpeedClass.speed.slow;
+      int lightning = SpeedClass.speed.lightning;
+
+      if (s.getMySpeedtd1() != slow) throw new RuntimeException("mySpeedtd1 1 failed");
+      if (s.getMySpeedtd1() != 10) throw new RuntimeException("mySpeedtd1 2 failed");
+
+      s.setMySpeedtd1(lightning);
+      if (s.getMySpeedtd1() != lightning) throw new RuntimeException("mySpeedtd1 3 failed");
+      if (s.getMySpeedtd1() != 31) throw new RuntimeException("mySpeedtd1 4 failed");
+    }
+    {
+      if (enum_thorough_typeunsafe.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new RuntimeException("namedanonTest 1 failed");
+    }
+    {
+      int val = twonames.TwoNames2;
+      if (enum_thorough_typeunsafe.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (enum_thorough_typeunsafe.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (enum_thorough_typeunsafe.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      TwoNamesStruct t = new TwoNamesStruct();
+      int val = TwoNamesStruct.twonames.TwoNamesStruct1;
+      if (t.twonamesTest1(val) != val) throw new RuntimeException("twonamesTest 1 failed");
+      if (t.twonamesTest2(val) != val) throw new RuntimeException("twonamesTest 2 failed");
+      if (t.twonamesTest3(val) != val) throw new RuntimeException("twonamesTest 3 failed");
+    }
+    {
+      int val = namedanonspace.NamedAnonSpace2;
+      if (enum_thorough_typeunsafe.namedanonspaceTest1(val) != val) throw new RuntimeException("namedanonspaceTest 1 failed");
+      if (enum_thorough_typeunsafe.namedanonspaceTest2(val) != val) throw new RuntimeException("namedanonspaceTest 2 failed");
+      if (enum_thorough_typeunsafe.namedanonspaceTest3(val) != val) throw new RuntimeException("namedanonspaceTest 3 failed");
+      if (enum_thorough_typeunsafe.namedanonspaceTest4(val) != val) throw new RuntimeException("namedanonspaceTest 4 failed");
+    }
+    {
+      TemplateClassInt t = new TemplateClassInt();
+      int galileo = TemplateClassInt.scientists.galileo;
+
+      if (t.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest 1 failed");
+      if (t.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest 2 failed");
+      if (t.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest 3 failed");
+      if (t.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest 4 failed");
+      if (t.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest 5 failed");
+      if (t.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest 6 failed");
+      if (t.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest 7 failed");
+      if (t.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest 8 failed");
+      if (t.scientistsTest9(galileo) != galileo) throw new RuntimeException("scientistsTest 9 failed");
+//      if (t.scientistsTestA(galileo) != galileo) throw new RuntimeException("scientistsTest A failed");
+      if (t.scientistsTestB(galileo) != galileo) throw new RuntimeException("scientistsTest B failed");
+//      if (t.scientistsTestC(galileo) != galileo) throw new RuntimeException("scientistsTest C failed");
+      if (t.scientistsTestD(galileo) != galileo) throw new RuntimeException("scientistsTest D failed");
+      if (t.scientistsTestE(galileo) != galileo) throw new RuntimeException("scientistsTest E failed");
+      if (t.scientistsTestF(galileo) != galileo) throw new RuntimeException("scientistsTest F failed");
+      if (t.scientistsTestG(galileo) != galileo) throw new RuntimeException("scientistsTest G failed");
+      if (t.scientistsTestH(galileo) != galileo) throw new RuntimeException("scientistsTest H failed");
+      if (t.scientistsTestI(galileo) != galileo) throw new RuntimeException("scientistsTest I failed");
+      if (t.scientistsTestJ(galileo) != galileo) throw new RuntimeException("scientistsTest J failed");
+
+      if (enum_thorough_typeunsafe.scientistsTest1(galileo) != galileo) throw new RuntimeException("scientistsTest Global 1 failed");
+      if (enum_thorough_typeunsafe.scientistsTest2(galileo) != galileo) throw new RuntimeException("scientistsTest Global 2 failed");
+      if (enum_thorough_typeunsafe.scientistsTest3(galileo) != galileo) throw new RuntimeException("scientistsTest Global 3 failed");
+      if (enum_thorough_typeunsafe.scientistsTest4(galileo) != galileo) throw new RuntimeException("scientistsTest Global 4 failed");
+      if (enum_thorough_typeunsafe.scientistsTest5(galileo) != galileo) throw new RuntimeException("scientistsTest Global 5 failed");
+      if (enum_thorough_typeunsafe.scientistsTest6(galileo) != galileo) throw new RuntimeException("scientistsTest Global 6 failed");
+      if (enum_thorough_typeunsafe.scientistsTest7(galileo) != galileo) throw new RuntimeException("scientistsTest Global 7 failed");
+      if (enum_thorough_typeunsafe.scientistsTest8(galileo) != galileo) throw new RuntimeException("scientistsTest Global 8 failed");
+    }
+    {
+      TClassInt t = new TClassInt();
+      int bell = TClassInt.scientists.bell;
+      int galileo = TemplateClassInt.scientists.galileo;
+      if (t.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest 1 failed");
+      if (t.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest 2 failed");
+      if (t.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest 3 failed");
+      if (t.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest 4 failed");
+      if (t.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest 5 failed");
+      if (t.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest 6 failed");
+      if (t.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest 7 failed");
+      if (t.scientistsNameTest8(bell) != bell) throw new RuntimeException("scientistsNameTest 8 failed");
+      if (t.scientistsNameTest9(bell) != bell) throw new RuntimeException("scientistsNameTest 9 failed");
+//      if (t.scientistsNameTestA(bell) != bell) throw new RuntimeException("scientistsNameTest A failed");
+      if (t.scientistsNameTestB(bell) != bell) throw new RuntimeException("scientistsNameTest B failed");
+//      if (t.scientistsNameTestC(bell) != bell) throw new RuntimeException("scientistsNameTest C failed");
+      if (t.scientistsNameTestD(bell) != bell) throw new RuntimeException("scientistsNameTest D failed");
+      if (t.scientistsNameTestE(bell) != bell) throw new RuntimeException("scientistsNameTest E failed");
+      if (t.scientistsNameTestF(bell) != bell) throw new RuntimeException("scientistsNameTest F failed");
+      if (t.scientistsNameTestG(bell) != bell) throw new RuntimeException("scientistsNameTest G failed");
+      if (t.scientistsNameTestH(bell) != bell) throw new RuntimeException("scientistsNameTest H failed");
+      if (t.scientistsNameTestI(bell) != bell) throw new RuntimeException("scientistsNameTest I failed");
+
+      if (t.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 1 failed");
+      if (t.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 2 failed");
+      if (t.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 3 failed");
+      if (t.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 4 failed");
+      if (t.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 5 failed");
+      if (t.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 6 failed");
+      if (t.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest 7 failed");
+
+      if (t.scientistsOtherTest1(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 1 failed");
+      if (t.scientistsOtherTest2(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 2 failed");
+      if (t.scientistsOtherTest3(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 3 failed");
+      if (t.scientistsOtherTest4(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 4 failed");
+      if (t.scientistsOtherTest5(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 5 failed");
+      if (t.scientistsOtherTest6(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 6 failed");
+      if (t.scientistsOtherTest7(galileo) != galileo) throw new RuntimeException("scientistsOtherTest 7 failed");
+
+      if (enum_thorough_typeunsafe.scientistsNameTest1(bell) != bell) throw new RuntimeException("scientistsNameTest Global 1 failed");
+      if (enum_thorough_typeunsafe.scientistsNameTest2(bell) != bell) throw new RuntimeException("scientistsNameTest Global 2 failed");
+      if (enum_thorough_typeunsafe.scientistsNameTest3(bell) != bell) throw new RuntimeException("scientistsNameTest Global 3 failed");
+      if (enum_thorough_typeunsafe.scientistsNameTest4(bell) != bell) throw new RuntimeException("scientistsNameTest Global 4 failed");
+      if (enum_thorough_typeunsafe.scientistsNameTest5(bell) != bell) throw new RuntimeException("scientistsNameTest Global 5 failed");
+      if (enum_thorough_typeunsafe.scientistsNameTest6(bell) != bell) throw new RuntimeException("scientistsNameTest Global 6 failed");
+      if (enum_thorough_typeunsafe.scientistsNameTest7(bell) != bell) throw new RuntimeException("scientistsNameTest Global 7 failed");
+
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest1(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 1 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest2(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 2 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest3(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 3 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest4(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 4 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest5(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 5 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest6(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 6 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest7(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 7 failed");
+
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest8(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 8 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTest9(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global 9 failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestA(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global A failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestB(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global B failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestC(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global C failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestD(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global D failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestE(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global E failed");
+
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestF(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global F failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestG(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global G failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestH(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global H failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestI(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global I failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestJ(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global J failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestK(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global K failed");
+      if (enum_thorough_typeunsafe.scientistsNameSpaceTestL(bell) != bell) throw new RuntimeException("scientistsNameSpaceTest Global L failed");
+    }
+    {
+      int val = newname.argh;
+      if (enum_thorough_typeunsafe.renameTest1(val) != val) throw new RuntimeException("renameTest Global 1 failed");
+      if (enum_thorough_typeunsafe.renameTest2(val) != val) throw new RuntimeException("renameTest Global 2 failed");
+    }
+    {
+      NewNameStruct n = new NewNameStruct();
+      if (n.renameTest1(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest 1 failed");
+      if (n.renameTest2(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest 2 failed");
+      if (n.renameTest3(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new RuntimeException("renameTest 3 failed");
+      if (n.renameTest4(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest 4 failed");
+      if (n.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest 5 failed");
+      if (n.renameTest6(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new RuntimeException("renameTest 6 failed");
+    }
+    {
+      if (enum_thorough_typeunsafe.renameTest3(NewNameStruct.enumeration.bang) != NewNameStruct.enumeration.bang) throw new RuntimeException("renameTest Global 3 failed");
+      if (enum_thorough_typeunsafe.renameTest4(NewNameStruct.simplerenamed.simple1) != NewNameStruct.simplerenamed.simple1) throw new RuntimeException("renameTest Global 4 failed");
+      if (enum_thorough_typeunsafe.renameTest5(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest Global 5 failed");
+      if (enum_thorough_typeunsafe.renameTest6(NewNameStruct.doublenamerenamed.doublename1) != NewNameStruct.doublenamerenamed.doublename1) throw new RuntimeException("renameTest Global 6 failed");
+      if (enum_thorough_typeunsafe.renameTest7(NewNameStruct.singlenamerenamed.singlename1) != NewNameStruct.singlenamerenamed.singlename1) throw new RuntimeException("renameTest Global 7 failed");
+    }
+    {
+      TreesClass t = new TreesClass();
+      int pine = TreesClass.trees.pine;
+
+      if (t.treesTest1(pine) != pine) throw new RuntimeException("treesTest 1 failed");
+      if (t.treesTest2(pine) != pine) throw new RuntimeException("treesTest 2 failed");
+      if (t.treesTest3(pine) != pine) throw new RuntimeException("treesTest 3 failed");
+      if (t.treesTest4(pine) != pine) throw new RuntimeException("treesTest 4 failed");
+      if (t.treesTest5(pine) != pine) throw new RuntimeException("treesTest 5 failed");
+      if (t.treesTest6(pine) != pine) throw new RuntimeException("treesTest 6 failed");
+      if (t.treesTest7(pine) != pine) throw new RuntimeException("treesTest 7 failed");
+      if (t.treesTest8(pine) != pine) throw new RuntimeException("treesTest 8 failed");
+      if (t.treesTest9(pine) != pine) throw new RuntimeException("treesTest 9 failed");
+      if (t.treesTestA(pine) != pine) throw new RuntimeException("treesTest A failed");
+      if (t.treesTestB(pine) != pine) throw new RuntimeException("treesTest B failed");
+      if (t.treesTestC(pine) != pine) throw new RuntimeException("treesTest C failed");
+      if (t.treesTestD(pine) != pine) throw new RuntimeException("treesTest D failed");
+      if (t.treesTestE(pine) != pine) throw new RuntimeException("treesTest E failed");
+      if (t.treesTestF(pine) != pine) throw new RuntimeException("treesTest F failed");
+      if (t.treesTestG(pine) != pine) throw new RuntimeException("treesTest G failed");
+      if (t.treesTestH(pine) != pine) throw new RuntimeException("treesTest H failed");
+      if (t.treesTestI(pine) != pine) throw new RuntimeException("treesTest I failed");
+      if (t.treesTestJ(pine) != pine) throw new RuntimeException("treesTest J failed");
+      if (t.treesTestK(pine) != pine) throw new RuntimeException("treesTest K failed");
+      if (t.treesTestL(pine) != pine) throw new RuntimeException("treesTest L failed");
+      if (t.treesTestM(pine) != pine) throw new RuntimeException("treesTest M failed");
+      if (t.treesTestN(pine) != pine) throw new RuntimeException("treesTest N failed");
+      if (t.treesTestO(pine) != pine) throw new RuntimeException("treesTest O failed");
+
+      if (enum_thorough_typeunsafe.treesTest1(pine) != pine) throw new RuntimeException("treesTest Global 1 failed");
+      if (enum_thorough_typeunsafe.treesTest2(pine) != pine) throw new RuntimeException("treesTest Global 2 failed");
+      if (enum_thorough_typeunsafe.treesTest3(pine) != pine) throw new RuntimeException("treesTest Global 3 failed");
+      if (enum_thorough_typeunsafe.treesTest4(pine) != pine) throw new RuntimeException("treesTest Global 4 failed");
+      if (enum_thorough_typeunsafe.treesTest5(pine) != pine) throw new RuntimeException("treesTest Global 5 failed");
+      if (enum_thorough_typeunsafe.treesTest6(pine) != pine) throw new RuntimeException("treesTest Global 6 failed");
+      if (enum_thorough_typeunsafe.treesTest7(pine) != pine) throw new RuntimeException("treesTest Global 7 failed");
+      if (enum_thorough_typeunsafe.treesTest8(pine) != pine) throw new RuntimeException("treesTest Global 8 failed");
+      if (enum_thorough_typeunsafe.treesTest9(pine) != pine) throw new RuntimeException("treesTest Global 9 failed");
+      if (enum_thorough_typeunsafe.treesTestA(pine) != pine) throw new RuntimeException("treesTest Global A failed");
+      if (enum_thorough_typeunsafe.treesTestB(pine) != pine) throw new RuntimeException("treesTest Global B failed");
+      if (enum_thorough_typeunsafe.treesTestC(pine) != pine) throw new RuntimeException("treesTest Global C failed");
+      if (enum_thorough_typeunsafe.treesTestD(pine) != pine) throw new RuntimeException("treesTest Global D failed");
+      if (enum_thorough_typeunsafe.treesTestE(pine) != pine) throw new RuntimeException("treesTest Global E failed");
+      if (enum_thorough_typeunsafe.treesTestF(pine) != pine) throw new RuntimeException("treesTest Global F failed");
+      if (enum_thorough_typeunsafe.treesTestG(pine) != pine) throw new RuntimeException("treesTest Global G failed");
+      if (enum_thorough_typeunsafe.treesTestH(pine) != pine) throw new RuntimeException("treesTest Global H failed");
+      if (enum_thorough_typeunsafe.treesTestI(pine) != pine) throw new RuntimeException("treesTest Global I failed");
+      if (enum_thorough_typeunsafe.treesTestJ(pine) != pine) throw new RuntimeException("treesTest Global J failed");
+      if (enum_thorough_typeunsafe.treesTestK(pine) != pine) throw new RuntimeException("treesTest Global K failed");
+      if (enum_thorough_typeunsafe.treesTestL(pine) != pine) throw new RuntimeException("treesTest Global L failed");
+      if (enum_thorough_typeunsafe.treesTestM(pine) != pine) throw new RuntimeException("treesTest Global M failed");
+//      if (enum_thorough_typeunsafe.treesTestN(pine) != pine) throw new RuntimeException("treesTest Global N failed");
+      if (enum_thorough_typeunsafe.treesTestO(pine) != pine) throw new RuntimeException("treesTest Global O failed");
+      if (enum_thorough_typeunsafe.treesTestP(pine) != pine) throw new RuntimeException("treesTest Global P failed");
+      if (enum_thorough_typeunsafe.treesTestQ(pine) != pine) throw new RuntimeException("treesTest Global Q failed");
+      if (enum_thorough_typeunsafe.treesTestR(pine) != pine) throw new RuntimeException("treesTest Global R failed");
+    }
+    {
+      HairStruct h = new HairStruct();
+      int ginger = HairStruct.hair.ginger;
+
+      if (h.hairTest1(ginger) != ginger) throw new RuntimeException("hairTest 1 failed");
+      if (h.hairTest2(ginger) != ginger) throw new RuntimeException("hairTest 2 failed");
+      if (h.hairTest3(ginger) != ginger) throw new RuntimeException("hairTest 3 failed");
+      if (h.hairTest4(ginger) != ginger) throw new RuntimeException("hairTest 4 failed");
+      if (h.hairTest5(ginger) != ginger) throw new RuntimeException("hairTest 5 failed");
+      if (h.hairTest6(ginger) != ginger) throw new RuntimeException("hairTest 6 failed");
+      if (h.hairTest7(ginger) != ginger) throw new RuntimeException("hairTest 7 failed");
+      if (h.hairTest8(ginger) != ginger) throw new RuntimeException("hairTest 8 failed");
+      if (h.hairTest9(ginger) != ginger) throw new RuntimeException("hairTest 9 failed");
+      if (h.hairTestA(ginger) != ginger) throw new RuntimeException("hairTest A failed");
+      if (h.hairTestB(ginger) != ginger) throw new RuntimeException("hairTest B failed");
+
+      int red = colour.red;
+      if (h.colourTest1(red) != red) throw new RuntimeException("colourTest HairStruct 1 failed");
+      if (h.colourTest2(red) != red) throw new RuntimeException("colourTest HairStruct 2 failed");
+      if (h.namedanonTest1(namedanon.NamedAnon2) != namedanon.NamedAnon2) throw new RuntimeException("namedanonTest HairStruct 1 failed");
+      if (h.namedanonspaceTest1(namedanonspace.NamedAnonSpace2) != namedanonspace.NamedAnonSpace2) throw new RuntimeException("namedanonspaceTest HairStruct 1 failed");
+
+      int fir = TreesClass.trees.fir;
+      if (h.treesGlobalTest1(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 1 failed");
+      if (h.treesGlobalTest2(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 2 failed");
+      if (h.treesGlobalTest3(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 3 failed");
+      if (h.treesGlobalTest4(fir) != fir) throw new RuntimeException("treesGlobalTest1 HairStruct 4 failed");
+    }
+    {
+      int blonde = HairStruct.hair.blonde;
+      if (enum_thorough_typeunsafe.hairTest1(blonde) != blonde) throw new RuntimeException("hairTest Global 1 failed");
+      if (enum_thorough_typeunsafe.hairTest2(blonde) != blonde) throw new RuntimeException("hairTest Global 2 failed");
+      if (enum_thorough_typeunsafe.hairTest3(blonde) != blonde) throw new RuntimeException("hairTest Global 3 failed");
+      if (enum_thorough_typeunsafe.hairTest4(blonde) != blonde) throw new RuntimeException("hairTest Global 4 failed");
+      if (enum_thorough_typeunsafe.hairTest5(blonde) != blonde) throw new RuntimeException("hairTest Global 5 failed");
+      if (enum_thorough_typeunsafe.hairTest6(blonde) != blonde) throw new RuntimeException("hairTest Global 6 failed");
+      if (enum_thorough_typeunsafe.hairTest7(blonde) != blonde) throw new RuntimeException("hairTest Global 7 failed");
+      if (enum_thorough_typeunsafe.hairTest8(blonde) != blonde) throw new RuntimeException("hairTest Global 8 failed");
+      if (enum_thorough_typeunsafe.hairTest9(blonde) != blonde) throw new RuntimeException("hairTest Global 9 failed");
+      if (enum_thorough_typeunsafe.hairTestA(blonde) != blonde) throw new RuntimeException("hairTest Global A failed");
+      if (enum_thorough_typeunsafe.hairTestB(blonde) != blonde) throw new RuntimeException("hairTest Global B failed");
+      if (enum_thorough_typeunsafe.hairTestC(blonde) != blonde) throw new RuntimeException("hairTest Global C failed");
+
+      if (enum_thorough_typeunsafe.hairTestA1(blonde) != blonde) throw new RuntimeException("hairTest Global A1 failed");
+      if (enum_thorough_typeunsafe.hairTestA2(blonde) != blonde) throw new RuntimeException("hairTest Global A2 failed");
+      if (enum_thorough_typeunsafe.hairTestA3(blonde) != blonde) throw new RuntimeException("hairTest Global A3 failed");
+      if (enum_thorough_typeunsafe.hairTestA4(blonde) != blonde) throw new RuntimeException("hairTest Global A4 failed");
+      if (enum_thorough_typeunsafe.hairTestA5(blonde) != blonde) throw new RuntimeException("hairTest Global A5 failed");
+      if (enum_thorough_typeunsafe.hairTestA6(blonde) != blonde) throw new RuntimeException("hairTest Global A6 failed");
+      if (enum_thorough_typeunsafe.hairTestA7(blonde) != blonde) throw new RuntimeException("hairTest Global A7 failed");
+      if (enum_thorough_typeunsafe.hairTestA8(blonde) != blonde) throw new RuntimeException("hairTest Global A8 failed");
+      if (enum_thorough_typeunsafe.hairTestA9(blonde) != blonde) throw new RuntimeException("hairTest Global A9 failed");
+      if (enum_thorough_typeunsafe.hairTestAA(blonde) != blonde) throw new RuntimeException("hairTest Global AA failed");
+      if (enum_thorough_typeunsafe.hairTestAB(blonde) != blonde) throw new RuntimeException("hairTest Global AB failed");
+      if (enum_thorough_typeunsafe.hairTestAC(blonde) != blonde) throw new RuntimeException("hairTest Global AC failed");
+
+      if (enum_thorough_typeunsafe.hairTestB1(blonde) != blonde) throw new RuntimeException("hairTest Global B1 failed");
+      if (enum_thorough_typeunsafe.hairTestB2(blonde) != blonde) throw new RuntimeException("hairTest Global B2 failed");
+      if (enum_thorough_typeunsafe.hairTestB3(blonde) != blonde) throw new RuntimeException("hairTest Global B3 failed");
+      if (enum_thorough_typeunsafe.hairTestB4(blonde) != blonde) throw new RuntimeException("hairTest Global B4 failed");
+      if (enum_thorough_typeunsafe.hairTestB5(blonde) != blonde) throw new RuntimeException("hairTest Global B5 failed");
+      if (enum_thorough_typeunsafe.hairTestB6(blonde) != blonde) throw new RuntimeException("hairTest Global B6 failed");
+      if (enum_thorough_typeunsafe.hairTestB7(blonde) != blonde) throw new RuntimeException("hairTest Global B7 failed");
+      if (enum_thorough_typeunsafe.hairTestB8(blonde) != blonde) throw new RuntimeException("hairTest Global B8 failed");
+      if (enum_thorough_typeunsafe.hairTestB9(blonde) != blonde) throw new RuntimeException("hairTest Global B9 failed");
+      if (enum_thorough_typeunsafe.hairTestBA(blonde) != blonde) throw new RuntimeException("hairTest Global BA failed");
+      if (enum_thorough_typeunsafe.hairTestBB(blonde) != blonde) throw new RuntimeException("hairTest Global BB failed");
+      if (enum_thorough_typeunsafe.hairTestBC(blonde) != blonde) throw new RuntimeException("hairTest Global BC failed");
+
+      if (enum_thorough_typeunsafe.hairTestC1(blonde) != blonde) throw new RuntimeException("hairTest Global C1 failed");
+      if (enum_thorough_typeunsafe.hairTestC2(blonde) != blonde) throw new RuntimeException("hairTest Global C2 failed");
+      if (enum_thorough_typeunsafe.hairTestC3(blonde) != blonde) throw new RuntimeException("hairTest Global C3 failed");
+      if (enum_thorough_typeunsafe.hairTestC4(blonde) != blonde) throw new RuntimeException("hairTest Global C4 failed");
+      if (enum_thorough_typeunsafe.hairTestC5(blonde) != blonde) throw new RuntimeException("hairTest Global C5 failed");
+      if (enum_thorough_typeunsafe.hairTestC6(blonde) != blonde) throw new RuntimeException("hairTest Global C6 failed");
+      if (enum_thorough_typeunsafe.hairTestC7(blonde) != blonde) throw new RuntimeException("hairTest Global C7 failed");
+      if (enum_thorough_typeunsafe.hairTestC8(blonde) != blonde) throw new RuntimeException("hairTest Global C8 failed");
+      if (enum_thorough_typeunsafe.hairTestC9(blonde) != blonde) throw new RuntimeException("hairTest Global C9 failed");
+      if (enum_thorough_typeunsafe.hairTestCA(blonde) != blonde) throw new RuntimeException("hairTest Global CA failed");
+      if (enum_thorough_typeunsafe.hairTestCB(blonde) != blonde) throw new RuntimeException("hairTest Global CB failed");
+      if (enum_thorough_typeunsafe.hairTestCC(blonde) != blonde) throw new RuntimeException("hairTest Global CC failed");
+    }
+    {
+      FirStruct f = new FirStruct();
+      int blonde = HairStruct.hair.blonde;
+
+      if (f.hairTestFir1(blonde) != blonde) throw new RuntimeException("hairTestFir 1 failed");
+      if (f.hairTestFir2(blonde) != blonde) throw new RuntimeException("hairTestFir 2 failed");
+      if (f.hairTestFir3(blonde) != blonde) throw new RuntimeException("hairTestFir 3 failed");
+      if (f.hairTestFir4(blonde) != blonde) throw new RuntimeException("hairTestFir 4 failed");
+      if (f.hairTestFir5(blonde) != blonde) throw new RuntimeException("hairTestFir 5 failed");
+      if (f.hairTestFir6(blonde) != blonde) throw new RuntimeException("hairTestFir 6 failed");
+      if (f.hairTestFir7(blonde) != blonde) throw new RuntimeException("hairTestFir 7 failed");
+      if (f.hairTestFir8(blonde) != blonde) throw new RuntimeException("hairTestFir 8 failed");
+      if (f.hairTestFir9(blonde) != blonde) throw new RuntimeException("hairTestFir 9 failed");
+      if (f.hairTestFirA(blonde) != blonde) throw new RuntimeException("hairTestFir A failed");
+    }
+    {
+      enum_thorough_typeunsafe.setGlobalInstance(enum_thorough_typeunsafe.globalinstance2);
+      if (enum_thorough_typeunsafe.getGlobalInstance() != enum_thorough_typeunsafe.globalinstance2) throw new RuntimeException("GlobalInstance 1 failed");
+
+      Instances i = new Instances();
+      i.setMemberInstance(Instances.memberinstance3);
+      if (i.getMemberInstance() != Instances.memberinstance3) throw new RuntimeException("MemberInstance 1 failed");
+    }
+    {
+      if (enum_thorough_typeunsafe.repeatTest(repeat.one) != 1) throw new RuntimeException("repeatTest 1 failed");
+      if (enum_thorough_typeunsafe.repeatTest(repeat.initial) != 1) throw new RuntimeException("repeatTest 2 failed");
+      if (enum_thorough_typeunsafe.repeatTest(repeat.two) != 2) throw new RuntimeException("repeatTest 3 failed");
+      if (enum_thorough_typeunsafe.repeatTest(repeat.three) != 3) throw new RuntimeException("repeatTest 4 failed");
+      if (enum_thorough_typeunsafe.repeatTest(repeat.last) != 3) throw new RuntimeException("repeatTest 5 failed");
+      if (enum_thorough_typeunsafe.repeatTest(repeat.end) != 3) throw new RuntimeException("repeatTest 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/extend_default_runme.java b/trunk/Examples/test-suite/java/extend_default_runme.java
new file mode 100644
index 0000000..49c52f4
--- /dev/null
+++ b/trunk/Examples/test-suite/java/extend_default_runme.java
@@ -0,0 +1,226 @@
+
+import extend_default.Override;
+import extend_default.*;
+
+public class extend_default_runme {
+  static {
+    try {
+        System.loadLibrary("extend_default");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    // %extend before the class definition
+    {
+      Before ex = new Before();
+      if (ex.getI() != -1.0 && ex.getD() != -1.0)
+        throw new RuntimeException("Before constructor 1 failed");
+
+      ex = new Before(10);
+      if (ex.getI() != 10.0 && ex.getD() != -1.0)
+        throw new RuntimeException("Before constructor 2 failed");
+
+      ex = new Before(20, 30.0);
+      if (ex.getI() != 20 && ex.getD() != 30.0)
+        throw new RuntimeException("Before constructor 3 failed");
+    }
+    {
+      Before ex = new Before();
+      if (ex.AddedMethod() != -2.0)
+        throw new RuntimeException("Before AddedMethod 1 failed");
+      if (ex.AddedMethod(-2) != -3.0)
+        throw new RuntimeException("Before AddedMethod 2 failed");
+      if (ex.AddedMethod(-10, -10.0) != -20)
+        throw new RuntimeException("Before AddedMethod 3 failed");
+    }
+    {
+      if (Before.AddedStaticMethod() != -2.0)
+        throw new RuntimeException("Before AddedStaticMethod 1 failed");
+      if (Before.AddedStaticMethod(-2) != -3.0)
+        throw new RuntimeException("Before AddedStaticMethod 2 failed");
+      if (Before.AddedStaticMethod(-10, -10.0) != -20)
+        throw new RuntimeException("Before AddedStaticMethod 3 failed");
+    }
+
+    // %extend after the class definition
+    {
+      After ex = new After();
+      if (ex.getI() != -1.0 && ex.getD() != -1.0)
+        throw new RuntimeException("After constructor 1 failed");
+
+      ex = new After(10);
+      if (ex.getI() != 10.0 && ex.getD() != -1.0)
+        throw new RuntimeException("After constructor 2 failed");
+
+      ex = new After(20, 30.0);
+      if (ex.getI() != 20 && ex.getD() != 30.0)
+        throw new RuntimeException("After constructor 3 failed");
+    }
+    {
+      After ex = new After();
+      if (ex.AddedMethod() != -2.0)
+        throw new RuntimeException("After AddedMethod 1 failed");
+      if (ex.AddedMethod(-2) != -3.0)
+        throw new RuntimeException("After AddedMethod 2 failed");
+      if (ex.AddedMethod(-10, -10.0) != -20)
+        throw new RuntimeException("After AddedMethod 3 failed");
+    }
+    {
+      if (After.AddedStaticMethod() != -2.0)
+        throw new RuntimeException("After AddedStaticMethod 1 failed");
+      if (After.AddedStaticMethod(-2) != -3.0)
+        throw new RuntimeException("After AddedStaticMethod 2 failed");
+      if (After.AddedStaticMethod(-10, -10.0) != -20)
+        throw new RuntimeException("After AddedStaticMethod 3 failed");
+    }
+
+    // %extend before the class definition - with overloading and default args
+    {
+      OverBefore ex = new OverBefore();
+      if (ex.getI() != -1.0 && ex.getD() != -1.0)
+        throw new RuntimeException("OverBefore constructor 1 failed");
+
+      ex = new OverBefore(10);
+      if (ex.getI() != 10.0 && ex.getD() != -1.0)
+        throw new RuntimeException("OverBefore constructor 2 failed");
+
+      ex = new OverBefore(20, 30.0);
+      if (ex.getI() != 20 && ex.getD() != 30.0)
+        throw new RuntimeException("OverBefore constructor 3 failed");
+    }
+    {
+      OverBefore ex = new OverBefore();
+      if (ex.AddedMethod() != -2.0)
+        throw new RuntimeException("OverBefore AddedMethod 1 failed");
+      if (ex.AddedMethod(-2) != -3.0)
+        throw new RuntimeException("OverBefore AddedMethod 2 failed");
+      if (ex.AddedMethod(-10, -10.0) != -20)
+        throw new RuntimeException("OverBefore AddedMethod 3 failed");
+    }
+    {
+      if (OverBefore.AddedStaticMethod() != -2.0)
+        throw new RuntimeException("OverBefore AddedStaticMethod 1 failed");
+      if (OverBefore.AddedStaticMethod(-2) != -3.0)
+        throw new RuntimeException("OverBefore AddedStaticMethod 2 failed");
+      if (OverBefore.AddedStaticMethod(-10, -10.0) != -20)
+        throw new RuntimeException("OverBefore AddedStaticMethod 3 failed");
+    }
+    {
+      OverBefore ex = new OverBefore("hello");
+      if (ex.getI() != -2.0 && ex.getD() != -2.0)
+        throw new RuntimeException("OverBefore overload constructor 1 failed");
+
+      ex = new OverBefore("hello", 10);
+      if (ex.getI() != 10.0 && ex.getD() != -1.0)
+        throw new RuntimeException("OverBefore overload constructor 2 failed");
+
+      ex = new OverBefore("hello", 20, 30.0);
+      if (ex.getI() != 20 && ex.getD() != 30.0)
+        throw new RuntimeException("OverBefore overload constructor 3 failed");
+    }
+    {
+      OverBefore ex = new OverBefore("hello");
+      if (ex.AddedMethod("hello") != -2.0)
+        throw new RuntimeException("OverBefore overload AddedMethod 1 failed");
+      if (ex.AddedMethod("hello", -2) != -3.0)
+        throw new RuntimeException("OverBefore overload AddedMethod 2 failed");
+      if (ex.AddedMethod("hello", -10, -10.0) != -20)
+        throw new RuntimeException("OverBefore overload AddedMethod 3 failed");
+    }
+    {
+      if (OverBefore.AddedStaticMethod("hello") != -2.0)
+        throw new RuntimeException("OverBefore overload AddedStaticMethod 1 failed");
+      if (OverBefore.AddedStaticMethod("hello", -2) != -3.0)
+        throw new RuntimeException("OverBefore overload AddedStaticMethod 2 failed");
+      if (OverBefore.AddedStaticMethod("hello", -10, -10.0) != -20)
+        throw new RuntimeException("OverBefore overload AddedStaticMethod 3 failed");
+    }
+
+    // %extend after the class definition - with overloading and default args
+    {
+      OverAfter ex = new OverAfter();
+      if (ex.getI() != -1.0 && ex.getD() != -1.0)
+        throw new RuntimeException("OverAfter constructor 1 failed");
+
+      ex = new OverAfter(10);
+      if (ex.getI() != 10.0 && ex.getD() != -1.0)
+        throw new RuntimeException("OverAfter constructor 2 failed");
+
+      ex = new OverAfter(20, 30.0);
+      if (ex.getI() != 20 && ex.getD() != 30.0)
+        throw new RuntimeException("OverAfter constructor 3 failed");
+    }
+    {
+      OverAfter ex = new OverAfter();
+      if (ex.AddedMethod() != -2.0)
+        throw new RuntimeException("OverAfter AddedMethod 1 failed");
+      if (ex.AddedMethod(-2) != -3.0)
+        throw new RuntimeException("OverAfter AddedMethod 2 failed");
+      if (ex.AddedMethod(-10, -10.0) != -20)
+        throw new RuntimeException("OverAfter AddedMethod 3 failed");
+    }
+    {
+      if (OverAfter.AddedStaticMethod() != -2.0)
+        throw new RuntimeException("OverAfter AddedStaticMethod 1 failed");
+      if (OverAfter.AddedStaticMethod(-2) != -3.0)
+        throw new RuntimeException("OverAfter AddedStaticMethod 2 failed");
+      if (OverAfter.AddedStaticMethod(-10, -10.0) != -20)
+        throw new RuntimeException("OverAfter AddedStaticMethod 3 failed");
+    }
+    {
+      OverAfter ex = new OverAfter("hello");
+      if (ex.getI() != -2.0 && ex.getD() != -2.0)
+        throw new RuntimeException("OverAfter overload constructor 1 failed");
+
+      ex = new OverAfter("hello", 10);
+      if (ex.getI() != 10.0 && ex.getD() != -1.0)
+        throw new RuntimeException("OverAfter overload constructor 2 failed");
+
+      ex = new OverAfter("hello", 20, 30.0);
+      if (ex.getI() != 20 && ex.getD() != 30.0)
+        throw new RuntimeException("OverAfter overload constructor 3 failed");
+    }
+    {
+      OverAfter ex = new OverAfter("hello");
+      if (ex.AddedMethod("hello") != -2.0)
+        throw new RuntimeException("OverAfter overload AddedMethod 1 failed");
+      if (ex.AddedMethod("hello", -2) != -3.0)
+        throw new RuntimeException("OverAfter overload AddedMethod 2 failed");
+      if (ex.AddedMethod("hello", -10, -10.0) != -20)
+        throw new RuntimeException("OverAfter overload AddedMethod 3 failed");
+    }
+    {
+      if (OverAfter.AddedStaticMethod("hello") != -2.0)
+        throw new RuntimeException("OverAfter overload AddedStaticMethod 1 failed");
+      if (OverAfter.AddedStaticMethod("hello", -2) != -3.0)
+        throw new RuntimeException("OverAfter overload AddedStaticMethod 2 failed");
+      if (OverAfter.AddedStaticMethod("hello", -10, -10.0) != -20)
+        throw new RuntimeException("OverAfter overload AddedStaticMethod 3 failed");
+    }
+
+    // Override
+    {
+      Override o = new Override();
+
+      if (o.over() != -1)
+        throw new RuntimeException("override test 1 failed");
+      if (o.over(10) != 10*10)
+        throw new RuntimeException("override test 2 failed");
+
+      if (o.ride() != -1)
+        throw new RuntimeException("override test 3 failed");
+      if (o.ride(10) != 10)
+        throw new RuntimeException("override test 4 failed");
+
+      if (o.overload() != -10)
+        throw new RuntimeException("override test 5 failed");
+      if (o.overload(10) != 10*10)
+        throw new RuntimeException("override test 6 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/extern_declaration_runme.java b/trunk/Examples/test-suite/java/extern_declaration_runme.java
new file mode 100644
index 0000000..e1d7eb1
--- /dev/null
+++ b/trunk/Examples/test-suite/java/extern_declaration_runme.java
@@ -0,0 +1,21 @@
+
+import extern_declaration.*;
+
+public class extern_declaration_runme {
+  static {
+    try {
+        System.loadLibrary("extern_declaration");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    if (extern_declaration.externimport(100) != 100) throw new RuntimeException("externimport failed");
+    if (extern_declaration.externexport(200) != 200) throw new RuntimeException("externexport failed");
+    if (extern_declaration.externstdcall(300) != 300) throw new RuntimeException("externstdcall failed");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/ignore_parameter_runme.java b/trunk/Examples/test-suite/java/ignore_parameter_runme.java
new file mode 100644
index 0000000..7dbcb06
--- /dev/null
+++ b/trunk/Examples/test-suite/java/ignore_parameter_runme.java
@@ -0,0 +1,36 @@
+// Runtime test checking the %typemap(ignore) macro
+
+import ignore_parameter.*;
+
+public class ignore_parameter_runme {
+  static {
+    try {
+        System.loadLibrary("ignore_parameter");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      // Compilation will ensure the number of arguments and type are correct.
+      // Then check the return value is the same as the value given to the ignored parameter.
+      if (!ignore_parameter.jaguar(200, 0.0).equals("hello")) { System.err.println("Runtime Error in jaguar()");}
+      if (ignore_parameter.lotus("fast", 0.0) != 101) { System.err.println("Runtime Error in lotus()");}
+      if (ignore_parameter.tvr("fast", 200) != 8.8) { System.err.println("Runtime Error in tvr()");}
+      if (ignore_parameter.ferrari() != 101) { System.err.println("Runtime Error in ferrari()");}
+
+      SportsCars sc = new SportsCars();
+      if (!sc.daimler(200, 0.0).equals("hello")) { System.err.println("Runtime Error in daimler()");}
+      if (sc.astonmartin("fast", 0.0) != 101) { System.err.println("Runtime Error in astonmartin()");}
+      if (sc.bugatti("fast", 200) != 8.8) { System.err.println("Runtime Error in bugatti()");}
+      if (sc.lamborghini() != 101) { System.err.println("Runtime Error in lamborghini()");}
+
+      // Check constructors are also generated correctly
+      MiniCooper mc = new MiniCooper(200, 0.0);
+      MorrisMinor mm = new MorrisMinor("slow", 0.0);
+      FordAnglia fa = new FordAnglia("slow", 200);
+      AustinAllegro aa = new AustinAllegro();
+  }
+}
diff --git a/trunk/Examples/test-suite/java/imports_runme.java b/trunk/Examples/test-suite/java/imports_runme.java
new file mode 100644
index 0000000..b82862b
--- /dev/null
+++ b/trunk/Examples/test-suite/java/imports_runme.java
@@ -0,0 +1,24 @@
+
+// This is the imports runtime testcase. It shows that the %import directive
+// is working correctly
+
+import imports.*;
+
+public class imports_runme {
+
+  static {
+    try {
+	System.loadLibrary("imports_a");
+	System.loadLibrary("imports_b");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    B b = new B();
+    b.hello(); //call member function in A which is in a different SWIG generated library.
+ }
+}
diff --git a/trunk/Examples/test-suite/java/inctest_runme.java b/trunk/Examples/test-suite/java/inctest_runme.java
new file mode 100644
index 0000000..4c298ad
--- /dev/null
+++ b/trunk/Examples/test-suite/java/inctest_runme.java
@@ -0,0 +1,21 @@
+
+import inctest.*;
+
+public class inctest_runme {
+  static {
+    try {
+        System.loadLibrary("inctest");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    MY_THINGS things = new MY_THINGS();
+    int i=0;
+    things.setIntegerMember(i);
+    double d = things.getDoubleMember();
+  }
+}
diff --git a/trunk/Examples/test-suite/java/inherit_target_language_runme.java b/trunk/Examples/test-suite/java/inherit_target_language_runme.java
new file mode 100644
index 0000000..6c7c1bf
--- /dev/null
+++ b/trunk/Examples/test-suite/java/inherit_target_language_runme.java
@@ -0,0 +1,26 @@
+
+import inherit_target_language.*;
+
+
+public class inherit_target_language_runme {
+
+  static {
+    try {
+	System.loadLibrary("inherit_target_language");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    new Derived1().targetLanguageBaseMethod();
+    new Derived2().targetLanguageBaseMethod();
+
+    new MultipleDerived1().targetLanguageBaseMethod();
+    new MultipleDerived2().targetLanguageBaseMethod();
+    new MultipleDerived3().f();
+    new MultipleDerived4().g();
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/intermediary_classname_runme.java b/trunk/Examples/test-suite/java/intermediary_classname_runme.java
new file mode 100644
index 0000000..03efc03
--- /dev/null
+++ b/trunk/Examples/test-suite/java/intermediary_classname_runme.java
@@ -0,0 +1,24 @@
+
+import intermediary_classname.*;
+
+public class intermediary_classname_runme {
+  static {
+    try {
+        System.loadLibrary("intermediary_classname");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      // test the renamed module class is correctly named
+      double d = intermediary_classnameModule.maxdouble(10.0, 20.0);
+      if (d!=20.0) throw new RuntimeException("Test failed");
+
+      // test the renamed intermediary class is correctly named
+      long ptr = intermediary_classname.new_vecdouble(10);
+      intermediary_classname.delete_vecdouble(ptr);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_constants_runme.java b/trunk/Examples/test-suite/java/java_constants_runme.java
new file mode 100644
index 0000000..be2ece0
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_constants_runme.java
@@ -0,0 +1,29 @@
+
+import java_constants.*;
+
+public class java_constants_runme {
+  static {
+    try {
+        System.loadLibrary("java_constants");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      int number = 200;
+
+      // Switch statement will only compile if these constants are initialised 
+      // from a constant Java value, that is not from a function call
+      switch(number) {
+          case java_constants.CHINA:
+              break;
+          case java_constants.BRISTOLS:
+              break;
+          default:
+              break;
+      }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_director_runme.java b/trunk/Examples/test-suite/java/java_director_runme.java
new file mode 100644
index 0000000..dffba0e
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_director_runme.java
@@ -0,0 +1,75 @@
+// Mainly tests that directors are finalized correctly
+
+import java_director.*;
+
+public class java_director_runme {
+
+  static {
+    try {
+      System.loadLibrary("java_director");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    QuuxContainer qc = createContainer();
+
+    int instances = Quux.instances();
+    if (instances != 4)
+      throw new RuntimeException("Quux instances should be 4, actually " + instances);
+
+    for (int i = 0; i < qc.size(); ++i) {
+      Quux q = qc.get(i);
+
+      if (!q.director_method().equals(qc.invoke(i))) {
+        throw new RuntimeException ( "q.director_method()/qv.invoke(" + i + ")");
+      }
+    }
+
+    qc = null;
+    /* Watch qc get reaped, which causes the C++ object to delete
+       objects from the internal vector */
+    System.gc();
+    System.runFinalization();
+
+    /* Watch the Quux objects formerly in the QuuxContainer object
+       get reaped */
+    System.gc();
+    System.runFinalization();
+
+    instances = Quux.instances();
+    if (instances != 0)
+      throw new RuntimeException("Quux instances should be 0, actually " + instances);
+
+    /* Test Quux1's director disconnect method rename */
+    Quux1 quux1 = new Quux1("quux1");
+    if (quux1.disconnectMethodCalled)
+      throw new RuntimeException("Oops");
+    quux1.delete();
+    if (!quux1.disconnectMethodCalled)
+      throw new RuntimeException("disconnect method not called");
+  }
+
+  public static QuuxContainer createContainer() {
+    QuuxContainer qc = new QuuxContainer();
+
+    qc.push(new Quux("element 1"));
+    qc.push(new java_director_MyQuux("element 2"));
+    qc.push(new java_director_MyQuux("element 3"));
+    qc.push(new Quux("element 4"));
+
+    return qc;
+  }
+}
+
+class java_director_MyQuux extends Quux {
+  public java_director_MyQuux(String arg) {
+    super(arg);
+  }
+
+  public String director_method() {
+    return "java_director_MyQuux:" + member();
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_enums_runme.java b/trunk/Examples/test-suite/java/java_enums_runme.java
new file mode 100644
index 0000000..bc7d416
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_enums_runme.java
@@ -0,0 +1,54 @@
+
+import java_enums.*;
+
+public class java_enums_runme implements stuff {
+  static {
+    try {
+        System.loadLibrary("java_enums");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      int number = 200;
+
+      // Switch statement will only compile if these enums are initialised 
+      // from a constant Java value, that is not from a function call
+      switch(number) {
+          case stuff.FIDDLE:
+              break;
+          case stuff.STICKS:
+              break;
+          case stuff.BONGO:
+              break;
+          case stuff.DRUMS:
+              break;
+          default:
+              break;
+      }
+      if (stuff.DRUMS != 15)
+          throw new RuntimeException("Incorrect value for DRUMS");
+
+      // check typemaps use short for this enum
+      short poppycock = nonsense.POPPYCOCK;
+      short tst1 = java_enums.test1(poppycock);
+      short tst2 = java_enums.test2(poppycock);
+
+      // Check that stuff is an interface and not a class - we can drop the stuff keyword as this class implements the stuff interface
+      switch(number) {
+          case FIDDLE:
+              break;
+          case STICKS:
+              break;
+          case BONGO:
+              break;
+          case DRUMS:
+              break;
+          default:
+              break;
+      }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_jnitypes_runme.java b/trunk/Examples/test-suite/java/java_jnitypes_runme.java
new file mode 100644
index 0000000..40395ce
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_jnitypes_runme.java
@@ -0,0 +1,57 @@
+
+import java_jnitypes.*;
+
+public class java_jnitypes_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_jnitypes");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static class Test {
+  }
+
+  public static void main(String argv[]) {
+
+    Test test = new Test();
+    boolean booleanArray[] = new boolean[] {true, false};
+    char charArray[] = new char[] {'A', 'B'};
+    byte byteArray[] = new byte[] {10, 20};
+    short shortArray[] = new short[] {10, 20};
+    int intArray[] = new int[] {10, 20};
+    long longArray[] = new long[] {10, 20};
+    float floatArray[] = new float[] {(float)10.0, (float)20.0};
+    double doubleArray[] = new double[] {10.0, 20.0};
+    Test objectArray[] = new Test[] {new Test(), test};
+
+    if (java_jnitypes.jnifunc(true) != true)                testFailed("jboolean");
+    if (java_jnitypes.jnifunc('A') != 'A')                  testFailed("jchar");
+    if (java_jnitypes.jnifunc((byte)100) != (byte)100)      testFailed("jbyte");
+    if (java_jnitypes.jnifunc((short)100) != (short)100)    testFailed("jshort");
+    if (java_jnitypes.jnifunc(100) != 100)                  testFailed("jint");
+    if (java_jnitypes.jnifunc((long)100) != (long)100)      testFailed("jlong");
+    if (java_jnitypes.jnifunc((float)100) != (float)100)    testFailed("jfloat");
+    if (java_jnitypes.jnifunc(100.0) != 100.0)              testFailed("jdouble");
+    if (java_jnitypes.jnifunc("100") != "100")              testFailed("jstring");
+    if (java_jnitypes.jnifunc(test) != test)                testFailed("jobject");
+    if (java_jnitypes.jnifunc(booleanArray)[1] != false)    testFailed("jbooleanArray");
+    if (java_jnitypes.jnifunc(charArray)[1] != 'B')         testFailed("jcharArray");
+    if (java_jnitypes.jnifunc(byteArray)[1] != 20)          testFailed("jbyteArray");
+    if (java_jnitypes.jnifunc(shortArray)[1] != 20)         testFailed("jshortArray");
+    if (java_jnitypes.jnifunc(intArray)[1] != 20)           testFailed("jintArray");
+    if (java_jnitypes.jnifunc(longArray)[1] != 20)          testFailed("jlongArray");
+    if (java_jnitypes.jnifunc(floatArray)[1] != 20.0)       testFailed("jfloatArray");
+    if (java_jnitypes.jnifunc(doubleArray)[1] != 20.0)      testFailed("jdoubleArray");
+    if (java_jnitypes.jnifunc(objectArray)[1] != test)      testFailed("jobjectArray");
+
+  }
+
+  public static void testFailed(String str) {
+      System.err.println(str + " test failed");
+      System.exit(1);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_lib_arrays_dimensionless_runme.java b/trunk/Examples/test-suite/java/java_lib_arrays_dimensionless_runme.java
new file mode 100644
index 0000000..cd9f7da
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_lib_arrays_dimensionless_runme.java
@@ -0,0 +1,62 @@
+
+import java_lib_arrays_dimensionless.*;
+
+public class java_lib_arrays_dimensionless_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_lib_arrays_dimensionless");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    boolean bools[] = {true, false, true, false, true};
+    byte schars[] = {5, 10, 15, 20, 25};
+    short uchars[] = {5, 10, 15, 20, 25};
+    short shorts[] = {5, 10, 15, 20, 25};
+    int ushorts[] = {5, 10, 15, 20, 25};
+    int ints[] = {5, 10, 15, 20, 25};
+    long uints[] = {5, 10, 15, 20, 25};
+    int longs[] = {5, 10, 15, 20, 25};
+    long ulongs[] = {5, 10, 15, 20, 25};
+    long lls[] = {5, 10, 15, 20, 25};
+    //java.math.BigInteger ulls[] = {5, 10, 15, 20, 25};
+    float floats[] = {5, 10, 15, 20, 25};
+    double doubles[] = {5, 10, 15, 20, 25};
+
+    if (java_lib_arrays_dimensionless.arr_bool(bools, bools.length) != 3) throw new RuntimeException("test bools 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_bool(bools, bools.length) != 2) throw new RuntimeException("test bools 2 failed");
+//    if (java_lib_arrays_dimensionless.arr_char(chars, chars.length) != 75) throw new RuntimeException("test chars 1 failed");
+//    if (java_lib_arrays_dimensionless.ptr_char(chars, chars.length) != 150) throw new RuntimeException("test chars 2 failed");
+    if (java_lib_arrays_dimensionless.arr_schar(schars, schars.length) != 75) throw new RuntimeException("test schars 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_schar(schars, schars.length) != 150) throw new RuntimeException("test schars 2 failed");
+    if (java_lib_arrays_dimensionless.arr_uchar(uchars, uchars.length) != 75) throw new RuntimeException("test uchars 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_uchar(uchars, uchars.length) != 150) throw new RuntimeException("test uchars 2 failed");
+    if (java_lib_arrays_dimensionless.arr_short(shorts, shorts.length) != 75) throw new RuntimeException("test shorts 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_short(shorts, shorts.length) != 150) throw new RuntimeException("test shorts 2 failed");
+    if (java_lib_arrays_dimensionless.arr_ushort(ushorts, ushorts.length) != 75) throw new RuntimeException("test ushorts 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_ushort(ushorts, ushorts.length) != 150) throw new RuntimeException("test ushorts 2 failed");
+    if (java_lib_arrays_dimensionless.arr_int(ints, ints.length) != 75) throw new RuntimeException("test ints 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_int(ints, ints.length) != 150) throw new RuntimeException("test ints 2 failed");
+    if (java_lib_arrays_dimensionless.arr_uint(uints, uints.length) != 75) throw new RuntimeException("test uints 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_uint(uints, uints.length) != 150) throw new RuntimeException("test uints 2 failed");
+    if (java_lib_arrays_dimensionless.arr_long(longs, longs.length) != 75) throw new RuntimeException("test longs 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_long(longs, longs.length) != 150) throw new RuntimeException("test longs 2 failed");
+    if (java_lib_arrays_dimensionless.arr_ulong(ulongs, ulongs.length) != 75) throw new RuntimeException("test ulongs 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_ulong(ulongs, ulongs.length) != 150) throw new RuntimeException("test ulongs 2 failed");
+//    if (java_lib_arrays_dimensionless.arr_ll(lls, lls.length) != 75) throw new RuntimeException("test lls 1 failed");
+//    if (java_lib_arrays_dimensionless.ptr_ll(lls, lls.length) != 150) throw new RuntimeException("test lls 2 failed");
+//    if (java_lib_arrays_dimensionless.arr_ull(ulls, ulls.length) != 75) throw new RuntimeException("test ulls 1 failed");
+//    if (java_lib_arrays_dimensionless.ptr_ull(ulls, ulls.length) != 150) throw new RuntimeException("test ulls 2 failed");
+    if (java_lib_arrays_dimensionless.arr_float(floats, floats.length) != 75) throw new RuntimeException("test floats 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_float(floats, floats.length) != 150) throw new RuntimeException("test floats 2 failed");
+    if (java_lib_arrays_dimensionless.arr_double(doubles, doubles.length) != 75) throw new RuntimeException("test doubles 1 failed");
+    if (java_lib_arrays_dimensionless.ptr_double(doubles, doubles.length) != 150) throw new RuntimeException("test doubles 2 failed");
+
+  }
+
+}
diff --git a/trunk/Examples/test-suite/java/java_lib_arrays_runme.java b/trunk/Examples/test-suite/java/java_lib_arrays_runme.java
new file mode 100644
index 0000000..9ee3621
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_lib_arrays_runme.java
@@ -0,0 +1,165 @@
+
+// This is the java_lib_arrays runtime testcase. It ensures that a getter and a setter has 
+// been produced for array members and that they function as expected. It is a
+// pretty comprehensive test for all the Java array library typemaps.
+
+import java_lib_arrays.*;
+
+public class java_lib_arrays_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_lib_arrays");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // Check array member variables
+    ArrayStruct as = new ArrayStruct();
+
+    // Create arrays for all the array types that ArrayStruct can handle
+    String array_c = "X";
+    byte[] array_sc = {10, 20};
+    short[] array_uc = {101, 201};
+    short[] array_s = {1002, 2002};
+    int[] array_us = {1003, 2003};
+    int[] array_i = {1004, 2004};
+    long[] array_ui = {1005, 2005};
+    int[] array_l = {1006, 2006};
+    long[] array_ul = {1007, 2007};
+    long[] array_ll = {1008, 2008};
+    float[] array_f = {1009.1f, 2009.1f};
+    double[] array_d = {1010.2f, 2010.2f};
+    int[] array_finger = {finger.Three, finger.Four};
+    int[] array_toe = {toe.Big, toe.Little};
+
+    SimpleStruct[] array_struct={new SimpleStruct(), new SimpleStruct()};
+    array_struct[0].setDouble_field(222.333);
+    array_struct[1].setDouble_field(444.555);
+
+    AnotherStruct[] array_another_struct={new AnotherStruct(), new AnotherStruct()};
+    array_another_struct[0].setSimple(array_struct[0]);
+    array_another_struct[1].setSimple(array_struct[1]);
+
+    YetAnotherStruct[] array_yet_another_struct={new YetAnotherStruct(), new YetAnotherStruct()};
+    array_yet_another_struct[0].setSimple(array_struct[0]);
+    array_yet_another_struct[1].setSimple(array_struct[1]);
+
+    if (array_another_struct[0].getSimple().getDouble_field() != 222.333) throw new RuntimeException("AnotherStruct[0] failed");
+    if (array_another_struct[1].getSimple().getDouble_field() != 444.555) throw new RuntimeException("AnotherStruct[1] failed");
+
+    if (java_lib_arrays.extract_ptr(array_yet_another_struct, 0) != 222.333) throw new RuntimeException("extract_ptr 0 failed");
+    if (java_lib_arrays.extract_ptr(array_yet_another_struct, 1) != 444.555) throw new RuntimeException("extract_ptr 1 failed");
+
+    java_lib_arrays.modifyYAS(array_yet_another_struct, array_yet_another_struct.length);
+    for (int i=0; i<2; ++i) {
+      if (array_yet_another_struct[i].getSimple().getDouble_field() != array_struct[i].getDouble_field() * 10.0)
+        throw new RuntimeException("modifyYAS failed ");
+    }
+
+    java_lib_arrays.toestest(array_toe, array_toe, array_toe);
+
+    // Now set the array members and check that they have been set correctly
+    as.setArray_c(array_c);
+    check_string(array_c, as.getArray_c());
+
+    as.setArray_sc(array_sc);
+    check_byte_array(array_sc, as.getArray_sc());
+
+    as.setArray_uc(array_uc);
+    check_short_array(array_uc, as.getArray_uc());
+
+    as.setArray_s(array_s);
+    check_short_array(array_s, as.getArray_s());
+
+    as.setArray_us(array_us);
+    check_int_array(array_us, as.getArray_us());
+
+    as.setArray_i(array_i);
+    check_int_array(array_i, as.getArray_i());
+
+    as.setArray_ui(array_ui);
+    check_long_array(array_ui, as.getArray_ui());
+
+    as.setArray_l(array_l);
+    check_int_array(array_l, as.getArray_l());
+
+    as.setArray_ul(array_ul);
+    check_long_array(array_ul, as.getArray_ul());
+
+    as.setArray_ll(array_ll);
+    check_long_array(array_ll, as.getArray_ll());
+
+    as.setArray_f(array_f);
+    check_float_array(array_f, as.getArray_f());
+
+    as.setArray_d(array_d);
+    check_double_array(array_d, as.getArray_d());
+
+    as.setArray_enum(array_finger);
+    check_int_array(array_finger, as.getArray_enum());
+
+    as.setArray_struct(array_struct);
+    check_struct_array(array_struct, as.getArray_struct());
+ }
+
+  // Functions to check that the array values were set correctly
+  public static void check_string(String original, String checking) {
+    if (!checking.equals(original)) {
+      throw new RuntimeException("Runtime test failed. checking = [" + checking + "]");
+    }
+  }
+  public static void check_byte_array(byte[] original, byte[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i] != original[i]) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
+      }
+    }
+  }
+  public static void check_short_array(short[] original, short[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i] != original[i]) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
+      }
+    }
+  }
+  public static void check_int_array(int[] original, int[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i] != original[i]) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
+      }
+    }
+  }
+  public static void check_long_array(long[] original, long[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i] != original[i]) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
+      }
+    }
+  }
+  public static void check_float_array(float[] original, float[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i] != original[i]) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
+      }
+    }
+  }
+  public static void check_double_array(double[] original, double[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i] != original[i]) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
+      }
+    }
+  }
+  public static void check_struct_array(SimpleStruct[] original, SimpleStruct[] checking) {
+    for (int i=0; i<original.length; i++) {
+      if (checking[i].getDouble_field() != original[i].getDouble_field()) {
+        throw new RuntimeException("Runtime test failed. checking[" + i + "].double_field=" + checking[i].getDouble_field());
+      }
+    }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_lib_various_runme.java b/trunk/Examples/test-suite/java/java_lib_various_runme.java
new file mode 100644
index 0000000..ab54ace
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_lib_various_runme.java
@@ -0,0 +1,83 @@
+
+// Test case to check typemaps in various.i
+
+import java_lib_various.*;
+
+public class java_lib_various_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_lib_various");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // STRING_ARRAY typemap parameter
+    String animals[] = {"Cat","Dog","Cow","Goat"};
+    if (java_lib_various.check_animals(animals) != 1)
+      throw new RuntimeException("check_animals failed");
+
+    // STRING_ARRAY typemap return value
+    String expected[] = { "Dave", "Mike", "Susan", "John", "Michelle" };
+    String got[] = java_lib_various.get_names();
+    for (int i=0; i<got.length; i++)
+      if ( !got[i].equals(expected[i]) )
+        throw new RuntimeException("Name failed " + i + " " + got[i] + "|" + expected[i]);
+
+    // STRING_ARRAY variable getter
+    String langscheck[] = { "Hungarian", "Afrikaans", "Norwegian" };
+    String langs[] = java_lib_various.getLanguages();
+    for (int i=0; i<langs.length; i++)
+      if ( !langs[i].equals(langscheck[i]) )
+        throw new RuntimeException("Languages read failed " + i + " " + langs[i] + "|" + langscheck[i]);
+
+    // STRING_ARRAY variable setter
+    String newLangs[] = { "French", "Italian", "Spanish" };
+    java_lib_various.setLanguages(newLangs);
+
+    // STRING_ARRAY variable getter
+    langs = java_lib_various.getLanguages();
+    for (int i=0; i<langs.length; i++)
+      if ( !langs[i].equals(newLangs[i]) )
+        throw new RuntimeException("Languages verify failed " + i + " " + langs[i] + "|" + newLangs[i]);
+
+    // STRING_RET test
+    {
+      String stringOutArray[] = { "" };
+      java_lib_various.char_ptr_ptr_out(stringOutArray);
+      if (!stringOutArray[0].equals("returned string"))
+        throw new RuntimeException("Test failed: expected: returned string. got: " + stringOutArray[0]);
+    }
+
+    // STRING_RET null array test. Check that exception is thrown.
+    try {
+      String stringOutArray[] = null;
+      java_lib_various.char_ptr_ptr_out(stringOutArray);
+      throw new RuntimeException("Test failed: null array");
+    } catch (NullPointerException e) {
+    }
+
+    // STRING_RET empty array test. Check that exception is thrown.
+    try {
+      String stringOutArray[] = {};
+      java_lib_various.char_ptr_ptr_out(stringOutArray);
+      throw new RuntimeException("Test failed: empty array");
+    } catch (IndexOutOfBoundsException e) {
+    }
+
+    // BYTE typemap check
+    byte b[] = new byte[20];
+    java_lib_various.charout(b);
+    String byjovestring = new String("by jove");
+    byte byjove[] = byjovestring.getBytes();
+    for (int i=0; i<byjovestring.length(); i++) {
+      if (byjove[i] != b[i])
+        throw new RuntimeException("By jove, it failed: [" + new String(b) + "]");
+    }
+  }
+
+}
diff --git a/trunk/Examples/test-suite/java/java_pgcpp_runme.java b/trunk/Examples/test-suite/java/java_pgcpp_runme.java
new file mode 100644
index 0000000..624100c
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_pgcpp_runme.java
@@ -0,0 +1,32 @@
+
+import java_pgcpp.*;
+
+
+public class java_pgcpp_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_pgcpp");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    Classic object = new Classic();
+    long ptr = object.getCPtrValue();
+
+    java_pgcppJNI.new_Classic__SWIG_1(ptr, object, ptr, object, ptr, object, ptr, object, ptr, object);
+    java_pgcppJNI.new_Classic__SWIG_2(ptr, object, ptr, object, ptr, object, ptr, object, ptr, object, false);
+
+    java_pgcppJNI.Classic_method(ptr, object, ptr, object, ptr, object, ptr, object, ptr, object, ptr, object);
+    java_pgcppJNI.Classic_methodconst(ptr, object, ptr, object, ptr, object, ptr, object, ptr, object, ptr, object);
+
+    java_pgcppJNI.function(ptr, object, ptr, object, ptr, object, ptr, object, ptr, object);
+    java_pgcppJNI.functionconst(ptr, object, ptr, object, ptr, object, ptr, object, ptr, object);
+
+    java_pgcppJNI.comment_in_typemaps(ptr, object, ptr, object, ptr, object);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/java_pragmas_runme.java b/trunk/Examples/test-suite/java/java_pragmas_runme.java
new file mode 100644
index 0000000..3111411
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_pragmas_runme.java
@@ -0,0 +1,15 @@
+
+import java_pragmas.*;
+
+public class java_pragmas_runme {
+
+  // No system.loadLibrary() as the JNI class will do this
+
+  public static void main(String argv[]) 
+  {
+    // Call a JNI class function. Normally this is not possible as the class is protected, however, the jniclassmodifiers pragma has changed this.
+    long int_pointer = java_pragmasJNI.get_int_pointer(); 
+
+    java_pragmas.added_function("hello");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_prepost_runme.java b/trunk/Examples/test-suite/java/java_prepost_runme.java
new file mode 100644
index 0000000..6eeb603
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_prepost_runme.java
@@ -0,0 +1,28 @@
+
+import java_prepost.*;
+
+public class java_prepost_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_prepost");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    // ensure checked exception is generated
+    try {
+      PrePostThrows ppt = new PrePostThrows(null);
+    } catch (InstantiationException e) {
+    }
+  }
+
+  private static void Assert(double d1, double d2) {
+    if (d1 != d2)
+      throw new RuntimeException("assertion failure. " + d1 + " != " + d2);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_throws_runme.java b/trunk/Examples/test-suite/java/java_throws_runme.java
new file mode 100644
index 0000000..3538aa6
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_throws_runme.java
@@ -0,0 +1,98 @@
+
+import java_throws.*;
+
+public class java_throws_runme {
+
+  static {
+    try {
+        System.loadLibrary("java_throws");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      // Check the exception classes in the main typemaps
+      boolean pass = false;
+
+      // This won't compile unless all of these exceptions are in the throw clause
+      try {
+        short s = java_throws.full_of_exceptions(10);
+      }
+      catch (ClassNotFoundException e) {}
+      catch (NoSuchFieldException e) { pass = true; }
+      catch (InstantiationException e) {}
+      catch (CloneNotSupportedException e) {}
+      catch (IllegalAccessException e) {}
+
+      if (!pass)
+        throw new RuntimeException("Test 1 failed");
+
+      // Check the exception class in the throw typemap
+      pass = false;
+      try {
+        java_throws.throw_spec_function(100);
+      }
+      catch (IllegalAccessException e) { pass = true; }
+
+      if (!pass)
+        throw new RuntimeException("Test 2 failed");
+
+      // Check newfree typemap throws attribute
+      try {
+        TestClass tc = java_throws.makeTestClass();
+      }
+      catch (NoSuchMethodException e) {}
+
+      // Check javaout typemap throws attribute
+      pass = false;
+      try {
+        int myInt = java_throws.ioTest();
+      }
+      catch (java.io.IOException e) { pass = true; }
+
+      if (!pass)
+        throw new RuntimeException("Test 4 failed");
+
+      // Check except feature throws attribute...
+      // Static method
+      pass = false;
+      try {
+        FeatureTest.staticMethod();
+      }
+      catch (MyException e) { pass = true; }
+      
+      if (!pass)
+        throw new RuntimeException("Test 5 failed");
+
+      FeatureTest f = null;
+      try {
+        f = new FeatureTest();
+      }
+      catch (MyException e) {}
+
+      // Instance method
+      pass = false;
+      try {
+        f.method();
+      }
+      catch (MyException e) { pass = true; }
+
+      if (!pass)
+        throw new RuntimeException("Test 6 failed");
+
+      // Global function
+      pass = false;
+      try {
+        java_throws.globalFunction(10);
+      }
+      catch (MyException e) { pass = true; }
+      catch (ClassNotFoundException e) {}
+      catch (NoSuchFieldException e) {}
+
+      if (!pass)
+        throw new RuntimeException("Test 7 failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/java_typemaps_proxy_runme.java b/trunk/Examples/test-suite/java/java_typemaps_proxy_runme.java
new file mode 100644
index 0000000..67a0831
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_typemaps_proxy_runme.java
@@ -0,0 +1,81 @@
+
+// This is the java_typemaps_proxy runtime testcase. Contrived example checks that the pure Java code from the Java typemaps compiles.
+
+import java_typemaps_proxy.*;
+import java.lang.reflect.*;
+
+public class java_typemaps_proxy_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_typemaps_proxy");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    Greeting greet = new Greeting();
+    Farewell bye = new Farewell();
+
+    // Check that pure Java methods have been added
+    greet.sayhello();
+    bye.saybye(new java.math.BigDecimal(java.math.BigInteger.ONE));
+
+    // No finalize method so may as well delete manually
+    bye.delete();
+
+    // Check that Greeting is derived from Exception
+    try {
+      throw new Greeting();
+    } catch (Greeting g) {
+        String msg = g.getMessage(); 
+    }
+
+    // Check that Greeting has implemented the EventListener interface
+    Greeting.cheerio(greet); 
+
+    // The default getCPtr() call in each method will through an exception if null is passed.
+    // Make sure the modified version works with and without null objects.
+    Greeting.ciao(null);
+    Greeting.ciao(greet);
+
+    // Create a NULL pointer for Farewell using the constructor with changed modifiers
+    Farewell nullFarewell = new Farewell(0, false);
+
+    // Test typemaps are being found for templated classes
+    AdieuIntPtrPtr.adieu();
+
+    // Check the %javamethodmodifiers feature
+    try {
+      Method methodmodifiertest = nullFarewell.getClass().getDeclaredMethod("methodmodifiertest", (java.lang.Class[])null);
+      if ( !Modifier.isPrivate(methodmodifiertest.getModifiers()) )
+        throw new RuntimeException("NS::Farewell::methodmodifiertest not private" );
+
+    } catch (NoSuchMethodException n) {
+      throw new RuntimeException("NoSuchmethodException caught. Test failed.");
+    } catch (SecurityException s) {
+      throw new RuntimeException("SecurityException caught. Test failed.");
+    }
+
+    // Check the premature garbage collection prevention parameter
+    // Check it is normally present
+    long nullPtr = 0;
+    With with = new With(null);
+    java_typemaps_proxyJNI.new_With(nullPtr, with);
+    java_typemaps_proxyJNI.With_static_method(nullPtr, with);
+    java_typemaps_proxyJNI.With_member_method(nullPtr, with, nullPtr, with);
+    java_typemaps_proxyJNI.delete_With(nullPtr);
+    java_typemaps_proxyJNI.global_method_with(nullPtr, with);
+
+    // Check that it can be turned off
+    java_typemaps_proxyJNI.new_Without(nullPtr);
+    java_typemaps_proxyJNI.Without_static_method(nullPtr);
+    java_typemaps_proxyJNI.Without_member_method(nullPtr, nullPtr);
+    java_typemaps_proxyJNI.delete_Without(nullPtr);
+    java_typemaps_proxyJNI.global_method_without(nullPtr);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/java_typemaps_typewrapper_runme.java b/trunk/Examples/test-suite/java/java_typemaps_typewrapper_runme.java
new file mode 100644
index 0000000..f6769fe
--- /dev/null
+++ b/trunk/Examples/test-suite/java/java_typemaps_typewrapper_runme.java
@@ -0,0 +1,45 @@
+
+// This is the java_typemaps_typewrapper runtime testcase. Contrived example checks that the pure Java code generated from the Java typemaps compiles.
+
+import java_typemaps_typewrapper.*;
+
+public class java_typemaps_typewrapper_runme {
+
+  static {
+    try {
+	System.loadLibrary("java_typemaps_typewrapper");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    SWIGTYPE_p_Greeting greet = SWIGTYPE_p_Greeting.CreateNullPointer();
+    SWIGTYPE_p_Farewell bye = SWIGTYPE_p_Farewell.CreateNullPointer();
+
+    // Check that pure Java methods have been added
+    greet.sayhello();
+    bye.saybye(new java.math.BigDecimal(java.math.BigInteger.ONE));
+
+    // Check that SWIGTYPE_p_Greeting is derived from Exception
+    try {
+      throw SWIGTYPE_p_Greeting.CreateNullPointer();
+    } catch (SWIGTYPE_p_Greeting g) {
+        String msg = g.getMessage(); 
+    }
+
+    // Check that SWIGTYPE_p_Greeting has implemented the EventListener interface
+    SWIGTYPE_p_Greeting.cheerio(greet); 
+
+    // The default getCPtr() call in each method will through an exception if null is passed.
+    // Make sure the modified version works with and without null objects.
+    java_typemaps_typewrapper.solong(null);
+    java_typemaps_typewrapper.solong(bye);
+
+    // Create a NULL pointer for Farewell using the constructor with changed modifiers
+    SWIGTYPE_p_Farewell nullFarewell = new SWIGTYPE_p_Farewell(0, false);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/li_boost_shared_ptr_runme.java b/trunk/Examples/test-suite/java/li_boost_shared_ptr_runme.java
new file mode 100644
index 0000000..a699222
--- /dev/null
+++ b/trunk/Examples/test-suite/java/li_boost_shared_ptr_runme.java
@@ -0,0 +1,593 @@
+import li_boost_shared_ptr.*;
+
+public class li_boost_shared_ptr_runme {
+  static {
+    try {
+        System.loadLibrary("li_boost_shared_ptr");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  // Debugging flag
+  public final static boolean debug = false;
+
+  public static void main(String argv[]) 
+  {
+    if (debug)
+      System.out.println("Started");
+
+    li_boost_shared_ptr.setDebug_shared(debug);
+
+    // Change loop count to run for a long time to monitor memory
+    final int loopCount = 1; //5000;
+    for (int i=0; i<loopCount; i++) {
+      new li_boost_shared_ptr_runme().runtest();
+      System.gc();
+      System.runFinalization();
+      try {
+        if (i%100 == 0) {
+          java.lang.Thread.sleep(1); // give some time to the lower priority finalizer thread
+        }
+      } catch (java.lang.InterruptedException e) {
+      }
+    }
+
+    if (debug)
+      System.out.println("Nearly finished");
+
+    int countdown = 100;
+    while (true) {
+      System.gc();
+      System.runFinalization();
+      try {
+        java.lang.Thread.sleep(10);
+      } catch (java.lang.InterruptedException e) {
+      }
+      if (--countdown == 0)
+        break;
+      if (Klass.getTotal_count() == 1) // Expect 1 instance - the one global variable (GlobalValue)
+        break;
+    };
+    if (Klass.getTotal_count() != 1)
+      throw new RuntimeException("Klass.total_count=" + Klass.getTotal_count());
+
+    int wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count(); 
+    if (wrapper_count != li_boost_shared_ptr.getNOT_COUNTING())
+      if (wrapper_count != 1) // Expect 1 instance - the one global variable (GlobalSmartValue)
+        throw new RuntimeException("shared_ptr wrapper count=" + wrapper_count);
+
+    if (debug)
+      System.out.println("Finished");
+  }
+
+  private void runtest() {
+    // simple shared_ptr usage - created in C++
+    {
+      Klass k = new Klass("me oh my");
+      String val = k.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(1, k);
+    }
+
+    // simple shared_ptr usage - not created in C++
+    {
+      Klass k = li_boost_shared_ptr.factorycreate();
+      String val = k.getValue();
+      verifyValue("factorycreate", val);
+      verifyCount(1, k);
+    }
+
+    // pass by shared_ptr
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointertest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by shared_ptr pointer
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointertest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by shared_ptr reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerreftest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by shared_ptr pointer reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointerreftest", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // const pass by shared_ptr
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.constsmartpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // const pass by shared_ptr pointer
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.constsmartpointerpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // const pass by shared_ptr reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.constsmartpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my", val);
+      verifyCount(2, k);
+      verifyCount(2, kret);
+    }
+
+    // pass by value
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.valuetest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my valuetest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // pass by pointer
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.pointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my pointertest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // pass by reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.reftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my reftest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // pass by pointer reference
+    {
+      Klass k = new Klass("me oh my");
+      Klass kret = li_boost_shared_ptr.pointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my pointerreftest", val);
+      verifyCount(1, k);
+      verifyCount(1, kret);
+    }
+
+    // null tests
+    {
+      Klass k = null;
+
+      if (li_boost_shared_ptr.smartpointertest(k) != null)
+        throw new RuntimeException("return was not null");
+
+      if (li_boost_shared_ptr.smartpointerpointertest(k) != null)
+        throw new RuntimeException("return was not null");
+
+      if (li_boost_shared_ptr.smartpointerreftest(k) != null)
+        throw new RuntimeException("return was not null");
+
+      if (li_boost_shared_ptr.smartpointerpointerreftest(k) != null)
+        throw new RuntimeException("return was not null");
+
+      if (!li_boost_shared_ptr.nullsmartpointerpointertest(null).equals("null pointer"))
+        throw new RuntimeException("not null smartpointer pointer");
+
+      try { li_boost_shared_ptr.valuetest(k); throw new RuntimeException("Failed to catch null pointer"); } catch (NullPointerException e) {}
+
+      if (li_boost_shared_ptr.pointertest(k) != null)
+        throw new RuntimeException("return was not null");
+
+      try { li_boost_shared_ptr.reftest(k); throw new RuntimeException("Failed to catch null pointer"); } catch (NullPointerException e) {}
+    }
+
+    // $owner
+    {
+      Klass k = li_boost_shared_ptr.pointerownertest();
+      String val = k.getValue();
+      verifyValue("pointerownertest", val);
+      verifyCount(1, k);
+    }
+    {
+      Klass k = li_boost_shared_ptr.smartpointerpointerownertest();
+      String val = k.getValue();
+      verifyValue("smartpointerpointerownertest", val);
+      verifyCount(1, k);
+    }
+
+    ////////////////////////////////// Derived classes ////////////////////////////////////////
+    // derived pass by shared_ptr
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrtest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrtest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts
+      verifyCount(4, kret);
+    }
+    // derived pass by shared_ptr pointer
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrpointertest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by shared_ptr ref
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrreftest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by shared_ptr pointer ref
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val);
+      verifyCount(4, k); // includes two extra references for upcasts in the proxy classes
+      verifyCount(4, kret);
+    }
+    // derived pass by pointer
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedpointertest-Derived", val);
+      verifyCount(2, k); // includes an extra reference for the upcast in the proxy class
+      verifyCount(2, kret);
+    }
+    // derived pass by ref
+    {
+      KlassDerived k = new KlassDerived("me oh my");
+      KlassDerived kret = li_boost_shared_ptr.derivedreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my derivedreftest-Derived", val);
+      verifyCount(2, k); // includes an extra reference for the upcast in the proxy class
+      verifyCount(2, kret);
+    }
+
+    ////////////////////////////////// Derived and base class mixed ////////////////////////////////////////
+    // pass by shared_ptr (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointertest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by shared_ptr pointer (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointertest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by shared_ptr reference (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerreftest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by shared_ptr pointer reference (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my smartpointerpointerreftest-Derived", val);
+      verifyCount(3, k); // an extra reference for the upcast in the proxy class
+      verifyCount(3, kret);
+    }
+
+    // pass by value (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.valuetest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my valuetest", val); // note slicing
+      verifyCount(2, k); // an extra reference for the upcast in the proxy class
+      verifyCount(1, kret);
+    }
+
+    // pass by pointer (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.pointertest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my pointertest-Derived", val);
+      verifyCount(2, k); // an extra reference for the upcast in the proxy class
+      verifyCount(1, kret);
+    }
+
+    // pass by ref (mixed)
+    {
+      Klass k = new KlassDerived("me oh my");
+      Klass kret = li_boost_shared_ptr.reftest(k);
+      String val = kret.getValue();
+      verifyValue("me oh my reftest-Derived", val);
+      verifyCount(2, k); // an extra reference for the upcast in the proxy class
+      verifyCount(1, kret);
+    }
+
+
+    ////////////////////////////////// Member variables ////////////////////////////////////////
+    // smart pointer by value
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("smart member value");
+      m.setSmartMemberValue(k);
+      String val = k.getValue();
+      verifyValue("smart member value", val);
+      verifyCount(2, k);
+
+      Klass kmember = m.getSmartMemberValue();
+      val = kmember.getValue();
+      verifyValue("smart member value", val);
+      verifyCount(3, kmember);
+      verifyCount(3, k);
+
+      m.delete();
+      verifyCount(2, kmember);
+      verifyCount(2, k);
+    }
+    // smart pointer by pointer
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("smart member pointer");
+      m.setSmartMemberPointer(k);
+      String val = k.getValue();
+      verifyValue("smart member pointer", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.getSmartMemberPointer();
+      val = kmember.getValue();
+      verifyValue("smart member pointer", val);
+      verifyCount(2, kmember);
+      verifyCount(2, k);
+
+      m.delete();
+      verifyCount(2, kmember);
+      verifyCount(2, k);
+    }
+    // smart pointer by reference
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("smart member reference");
+      m.setSmartMemberReference(k);
+      String val = k.getValue();
+      verifyValue("smart member reference", val);
+      verifyCount(2, k);
+
+      Klass kmember = m.getSmartMemberReference();
+      val = kmember.getValue();
+      verifyValue("smart member reference", val);
+      verifyCount(3, kmember);
+      verifyCount(3, k);
+
+      // The C++ reference refers to SmartMemberValue...
+      Klass kmemberVal = m.getSmartMemberValue();
+      val = kmember.getValue();
+      verifyValue("smart member reference", val);
+      verifyCount(4, kmemberVal);
+      verifyCount(4, kmember);
+      verifyCount(4, k);
+
+      m.delete();
+      verifyCount(3, kmemberVal);
+      verifyCount(3, kmember);
+      verifyCount(3, k);
+    }
+    // plain by value
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("plain member value");
+      m.setMemberValue(k);
+      String val = k.getValue();
+      verifyValue("plain member value", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.getMemberValue();
+      val = kmember.getValue();
+      verifyValue("plain member value", val);
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+
+      m.delete();
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+    }
+    // plain by pointer
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("plain member pointer");
+      m.setMemberPointer(k);
+      String val = k.getValue();
+      verifyValue("plain member pointer", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.getMemberPointer();
+      val = kmember.getValue();
+      verifyValue("plain member pointer", val);
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+
+      m.delete();
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+    }
+    // plain by reference
+    {
+      MemberVariables m = new MemberVariables();
+      Klass k = new Klass("plain member reference");
+      m.setMemberReference(k);
+      String val = k.getValue();
+      verifyValue("plain member reference", val);
+      verifyCount(1, k);
+
+      Klass kmember = m.getMemberReference();
+      val = kmember.getValue();
+      verifyValue("plain member reference", val);
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+
+      m.delete();
+      verifyCount(1, kmember);
+      verifyCount(1, k);
+    }
+
+    // null member variables
+    {
+      MemberVariables m = new MemberVariables();
+
+      // shared_ptr by value
+      Klass k = m.getSmartMemberValue();
+      if (k != null)
+        throw new RuntimeException("expected null");
+      m.setSmartMemberValue(null);
+      k = m.getSmartMemberValue();
+      if (k != null)
+        throw new RuntimeException("expected null");
+      verifyCount(0, k);
+
+      // plain by value
+      try { m.setMemberValue(null); throw new RuntimeException("Failed to catch null pointer"); } catch (NullPointerException e) {}
+    }
+
+    ////////////////////////////////// Global variables ////////////////////////////////////////
+    // smart pointer
+    {
+      Klass kglobal = li_boost_shared_ptr.getGlobalSmartValue();
+      if (kglobal != null)
+        throw new RuntimeException("expected null");
+
+      Klass k = new Klass("smart global value");
+      li_boost_shared_ptr.setGlobalSmartValue(k);
+      verifyCount(2, k);
+
+      kglobal = li_boost_shared_ptr.getGlobalSmartValue();
+      String val = kglobal.getValue();
+      verifyValue("smart global value", val);
+      verifyCount(3, kglobal);
+      verifyCount(3, k);
+      verifyValue("smart global value", li_boost_shared_ptr.getGlobalSmartValue().getValue());
+      li_boost_shared_ptr.setGlobalSmartValue(null);
+    }
+    // plain value
+    {
+      Klass kglobal;
+
+      Klass k = new Klass("global value");
+      li_boost_shared_ptr.setGlobalValue(k);
+      verifyCount(1, k);
+
+      kglobal = li_boost_shared_ptr.getGlobalValue();
+      String val = kglobal.getValue();
+      verifyValue("global value", val);
+      verifyCount(1, kglobal);
+      verifyCount(1, k);
+      verifyValue("global value", li_boost_shared_ptr.getGlobalValue().getValue());
+
+      try { li_boost_shared_ptr.setGlobalValue(null); throw new RuntimeException("Failed to catch null pointer"); } catch (NullPointerException e) {}
+    }
+    // plain pointer
+    {
+      Klass kglobal = li_boost_shared_ptr.getGlobalPointer();
+      if (kglobal != null)
+        throw new RuntimeException("expected null");
+
+      Klass k = new Klass("global pointer");
+      li_boost_shared_ptr.setGlobalPointer(k);
+      verifyCount(1, k);
+
+      kglobal = li_boost_shared_ptr.getGlobalPointer();
+      String val = kglobal.getValue();
+      verifyValue("global pointer", val);
+      verifyCount(1, kglobal);
+      verifyCount(1, k);
+      li_boost_shared_ptr.setGlobalPointer(null);
+    }
+
+    // plain reference
+    {
+      Klass kglobal;
+
+      Klass k = new Klass("global reference");
+      li_boost_shared_ptr.setGlobalReference(k);
+      verifyCount(1, k);
+
+      kglobal = li_boost_shared_ptr.getGlobalReference();
+      String val = kglobal.getValue();
+      verifyValue("global reference", val);
+      verifyCount(1, kglobal);
+      verifyCount(1, k);
+
+      try { li_boost_shared_ptr.setGlobalReference(null); throw new RuntimeException("Failed to catch null pointer"); } catch (NullPointerException e) {}
+    }
+
+    ////////////////////////////////// Templates ////////////////////////////////////////
+    {
+      PairIntDouble pid = new PairIntDouble(10, 20.2);
+      if (pid.getBaseVal1() != 20 || pid.getBaseVal2() != 40.4)
+        throw new RuntimeException("Base values wrong");
+      if (pid.getVal1() != 10 || pid.getVal2() != 20.2)
+        throw new RuntimeException("Derived Values wrong");
+    }
+  }
+  private void verifyValue(String expected, String got) {
+    if (!expected.equals(got))
+      throw new RuntimeException("verify value failed. Expected: " + expected + " Got: " + got);
+  }
+  private void verifyCount(int expected, Klass k) {
+    int got = li_boost_shared_ptr.use_count(k); 
+    if (expected != got)
+      throw new RuntimeException("verify use_count failed. Expected: " + expected + " Got: " + got);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/li_carrays_runme.java b/trunk/Examples/test-suite/java/li_carrays_runme.java
new file mode 100644
index 0000000..f576eab
--- /dev/null
+++ b/trunk/Examples/test-suite/java/li_carrays_runme.java
@@ -0,0 +1,88 @@
+import li_carrays.*;
+
+public class li_carrays_runme {
+
+  static {
+    try {
+        System.loadLibrary("li_carrays");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    // array_class
+    {
+      int length = 5;
+      XYArray xyArray = new XYArray(length);
+      for (int i=0; i<length; i++) {
+        XY xy = xyArray.getitem(i);
+        xy.setX(i*10);
+        xy.setY(i*100);
+        xyArray.setitem(i, xy);
+      }
+      for (int i=0; i<length; i++) {
+        Assert(xyArray.getitem(i).getX(), i*10);
+        Assert(xyArray.getitem(i).getY(), i*100);
+      }
+    }
+
+    {
+      // global array variable
+      int length = 5;
+      XY xyArrayPointer = li_carrays.getGlobalXYArray();
+      XYArray xyArray = XYArray.frompointer(xyArrayPointer);
+      for (int i=0; i<length; i++) {
+        XY xy = xyArray.getitem(i);
+        xy.setX(i*10);
+        xy.setY(i*100);
+        xyArray.setitem(i, xy);
+      }
+      for (int i=0; i<length; i++) {
+        Assert(xyArray.getitem(i).getX(), i*10);
+        Assert(xyArray.getitem(i).getY(), i*100);
+      }
+    }
+
+    // array_functions
+    {
+      int length = 5;
+      AB abArray = li_carrays.new_ABArray(length);
+      for (int i=0; i<length; i++) {
+        AB ab = li_carrays.ABArray_getitem(abArray, i);
+        ab.setA(i*10);
+        ab.setB(i*100);
+        li_carrays.ABArray_setitem(abArray, i, ab);
+      }
+      for (int i=0; i<length; i++) {
+        Assert(li_carrays.ABArray_getitem(abArray, i).getA(), i*10);
+        Assert(li_carrays.ABArray_getitem(abArray, i).getB(), i*100);
+      }
+      li_carrays.delete_ABArray(abArray);
+    }
+
+    {
+      // global array variable
+      int length = 3;
+      AB abArray = li_carrays.getGlobalABArray();
+      for (int i=0; i<length; i++) {
+        AB ab = li_carrays.ABArray_getitem(abArray, i);
+        ab.setA(i*10);
+        ab.setB(i*100);
+        li_carrays.ABArray_setitem(abArray, i, ab);
+      }
+      for (int i=0; i<length; i++) {
+        Assert(li_carrays.ABArray_getitem(abArray, i).getA(), i*10);
+        Assert(li_carrays.ABArray_getitem(abArray, i).getB(), i*100);
+      }
+    }
+  }
+
+  private static void Assert(int val1, int val2) {
+//      System.out.println("val1=" + val1 + " val2=" + val2);
+    if (val1 != val2)
+      throw new RuntimeException("Mismatch. val1=" + val1 + " val2=" + val2);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/li_std_except_runme.java b/trunk/Examples/test-suite/java/li_std_except_runme.java
new file mode 100644
index 0000000..6fe6ba5
--- /dev/null
+++ b/trunk/Examples/test-suite/java/li_std_except_runme.java
@@ -0,0 +1,29 @@
+import li_std_except.*;
+
+public class li_std_except_runme {
+
+  static {
+    try {
+        System.loadLibrary("li_std_except");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    Test test = new Test();
+    try { test.throw_bad_exception(); throw new RuntimeException("throw_bad_exception failed"); } catch (RuntimeException e) {}
+    try { test.throw_domain_error(); throw new RuntimeException("throw_domain_error failed"); } catch (RuntimeException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_exception(); throw new RuntimeException("throw_exception failed"); } catch (RuntimeException e) {}
+    try { test.throw_invalid_argument(); throw new RuntimeException("throw_invalid_argument failed"); } catch (IllegalArgumentException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_length_error(); throw new RuntimeException("throw_length_error failed"); } catch (IndexOutOfBoundsException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_logic_error(); throw new RuntimeException("throw_logic_error failed"); } catch (RuntimeException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_out_of_range(); throw new RuntimeException("throw_out_of_range failed"); } catch (IndexOutOfBoundsException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_overflow_error(); throw new RuntimeException("throw_overflow_error failed"); } catch (ArithmeticException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_range_error(); throw new RuntimeException("throw_range_error failed"); } catch (IndexOutOfBoundsException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_runtime_error(); throw new RuntimeException("throw_runtime_error failed"); } catch (RuntimeException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+    try { test.throw_underflow_error(); throw new RuntimeException("throw_underflow_error failed"); } catch (ArithmeticException e) { if (!e.getMessage().equals("oops")) throw new RuntimeException("wrong message returned"); }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/li_std_string_runme.java b/trunk/Examples/test-suite/java/li_std_string_runme.java
new file mode 100644
index 0000000..1ee2a23
--- /dev/null
+++ b/trunk/Examples/test-suite/java/li_std_string_runme.java
@@ -0,0 +1,108 @@
+import li_std_string.*;
+
+public class li_std_string_runme {
+
+  static {
+    try {
+        System.loadLibrary("li_std_string");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+      // Checking expected use of %typemap(in) std::string {}
+      li_std_string.test_value("Fee");
+
+      // Checking expected result of %typemap(out) std::string {}
+      if (!li_std_string.test_value("Fi").equals("Fi"))
+          throw new RuntimeException("Test 1 failed");
+
+      // Verify type-checking for %typemap(in) std::string {}
+      try {
+          li_std_string.test_value(null);
+          throw new RuntimeException("Test 2 failed");
+      } catch (NullPointerException e) {
+      }
+
+      // Checking expected use of %typemap(in) const std::string & {}
+      li_std_string.test_const_reference("Fo");
+
+      // Checking expected result of %typemap(out) const std::string& {}
+      if (!li_std_string.test_const_reference("Fum").equals("Fum"))
+          throw new RuntimeException("Test 3 failed");
+
+      // Verify type-checking for %typemap(in) const std::string & {}
+      try {
+          li_std_string.test_const_reference(null);
+          throw new RuntimeException("Test 4 failed");
+      } catch (NullPointerException e) {
+      }
+
+      //
+      // Input and output typemaps for pointers and non-const references to
+      // std::string are *not* supported; the following tests confirm
+      // that none of these cases are slipping through.
+      //
+
+      SWIGTYPE_p_std__string stringPtr = null;
+
+      stringPtr = li_std_string.test_pointer_out();
+
+      li_std_string.test_pointer(stringPtr);
+
+      stringPtr = li_std_string.test_const_pointer_out();
+
+      li_std_string.test_const_pointer(stringPtr);
+
+      stringPtr = li_std_string.test_reference_out();
+
+      li_std_string.test_reference(stringPtr);
+
+      // Check throw exception specification
+      try {
+          li_std_string.test_throw();
+          throw new Throwable("Test 5 failed");
+      } catch (RuntimeException e) {
+        if (!e.getMessage().equals("test_throw message"))
+          throw new Exception("Test 5 string check: " + e.getMessage());
+      }
+      try {
+          li_std_string.test_const_reference_throw();
+          throw new Throwable("Test 6 failed");
+      } catch (RuntimeException e) {
+        if (!e.getMessage().equals("test_const_reference_throw message"))
+          throw new Exception("Test 6 string check: " + e.getMessage());
+      }
+
+      // Global variables
+      String s = "initial string";
+      if (!li_std_string.getGlobalString2().equals("global string 2"))
+        throw new Exception("GlobalString2 test 1");
+      li_std_string.setGlobalString2(s);
+      if (!li_std_string.getGlobalString2().equals(s))
+        throw new Exception("GlobalString2 test 2");
+      if (!li_std_string.getConstGlobalString().equals("const global string"))
+        throw new Exception("ConstGlobalString test");
+
+      // Member variables
+      Structure myStructure = new Structure();
+      if (!myStructure.getMemberString2().equals("member string 2"))
+        throw new Exception("MemberString2 test 1");
+      myStructure.setMemberString2(s);
+      if (!myStructure.getMemberString2().equals(s))
+        throw new Exception("MemberString2 test 2");
+      if (!myStructure.getConstMemberString().equals("const member string"))
+        throw new Exception("ConstMemberString test");
+
+      if (!Structure.getStaticMemberString2().equals("static member string 2"))
+        throw new Exception("StaticMemberString2 test 1");
+      Structure.setStaticMemberString2(s);
+      if (!Structure.getStaticMemberString2().equals(s))
+        throw new Exception("StaticMemberString2 test 2");
+      if (!Structure.getConstStaticMemberString().equals("const static member string"))
+        throw new Exception("ConstStaticMemberString test");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/li_std_vector_runme.java b/trunk/Examples/test-suite/java/li_std_vector_runme.java
new file mode 100644
index 0000000..b422655
--- /dev/null
+++ b/trunk/Examples/test-suite/java/li_std_vector_runme.java
@@ -0,0 +1,36 @@
+import li_std_vector.*;
+
+public class li_std_vector_runme {
+
+  static {
+    try {
+        System.loadLibrary("li_std_vector");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    IntVector v1 = li_std_vector.vecintptr(new IntVector());
+    IntPtrVector v2 = li_std_vector.vecintptr(new IntPtrVector());
+    IntConstPtrVector v3 = li_std_vector.vecintconstptr(new IntConstPtrVector());
+
+    v1.add(123);
+    if (v1.get(0) != 123) throw new RuntimeException("v1 test failed");
+
+    StructVector v4 = li_std_vector.vecstruct(new StructVector());
+    StructPtrVector v5 = li_std_vector.vecstructptr(new StructPtrVector());
+    StructConstPtrVector v6 = li_std_vector.vecstructconstptr(new StructConstPtrVector());
+
+    v4.add(new Struct(12));
+    v5.add(new Struct(34));
+    v6.add(new Struct(56));
+
+    Struct s = null;
+    if (v4.get(0).getNum() != 12) throw new RuntimeException("v4 test failed");
+    if (v5.get(0).getNum() != 34) throw new RuntimeException("v5 test failed");
+    if (v6.get(0).getNum() != 56) throw new RuntimeException("v6 test failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/li_typemaps_runme.java b/trunk/Examples/test-suite/java/li_typemaps_runme.java
new file mode 100644
index 0000000..327b188
--- /dev/null
+++ b/trunk/Examples/test-suite/java/li_typemaps_runme.java
@@ -0,0 +1,125 @@
+
+// Check a few of the INPUT, OUTPUT and INOUT typemaps.
+
+import li_typemaps.*;
+import java.math.*;
+
+public class li_typemaps_runme {
+
+  static {
+    try {
+	System.loadLibrary("li_typemaps");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // Check double INPUT typemaps
+    if (li_typemaps.in_double(22.22) != 22.22) exit_test("in_double");
+    if (li_typemaps.inr_double(22.22) != 22.22) exit_test("inr_double");
+
+    // Check double OUTPUT typemaps
+    {
+        double[] var = {44.44};
+        li_typemaps.out_double(22.22, var);
+        if (var[0] != 22.22) exit_test("out_double");
+    }
+    {
+        double[] var = {44.44};
+        li_typemaps.outr_double(22.22, var);
+        if (var[0] != 22.22) exit_test("outr_double");
+    }
+    try {
+        double[] var = null;
+        li_typemaps.out_double(22.22, var);
+        exit_test("null out_double");
+    } catch (NullPointerException e) {
+    }
+
+    // Check double INOUT typemaps
+    {
+        double[] var = {44.44};
+        li_typemaps.inout_double(var);
+        if (var[0] != 44.44) exit_test("inout_double");
+    }
+    {
+        double[] var = {44.44};
+        li_typemaps.inoutr_double(var);
+        if (var[0] != 44.44) exit_test("inoutr_double");
+    }
+    try {
+        double[] var = null;
+        li_typemaps.inout_double(var);
+        exit_test("null inout_double");
+    } catch (NullPointerException e) {
+    }
+
+    // Check unsigned long long INPUT typemaps
+    BigInteger forty = new BigInteger("40");
+    BigInteger twenty = new BigInteger("20");
+    if (!li_typemaps.in_ulonglong(twenty).equals(twenty)) exit_test("in_ulonglong");
+    if (!li_typemaps.inr_ulonglong(twenty).equals(twenty)) exit_test("inr_ulonglong");
+
+    try {
+        li_typemaps.in_ulonglong(null);
+        exit_test("null in_ulonglong");
+    } catch (NullPointerException e) {
+    }
+
+    // Check unsigned long long OUTPUT typemaps
+    {
+        BigInteger[] var = {new BigInteger("40")};
+        li_typemaps.out_ulonglong(twenty, var);
+        if (!var[0].equals(twenty)) exit_test("out_ulonglong");
+    }
+    {
+        BigInteger[] var = {new BigInteger("40")};
+        li_typemaps.outr_ulonglong(twenty, var);
+        if (!var[0].equals(twenty)) exit_test("outr_ulonglong");
+    }
+    try {
+        BigInteger[] var = null;
+        li_typemaps.out_ulonglong(twenty, var);
+        exit_test("null out_ulonglong");
+    } catch (NullPointerException e) {
+    }
+    {
+        BigInteger[] var = { null };
+        li_typemaps.out_ulonglong(twenty, var);
+        if (!var[0].equals(twenty)) exit_test("null element out_ulonglong");
+    }
+
+    // Check unsigned long long INOUT typemaps
+    {
+        BigInteger[] var = {new BigInteger("40")};
+        li_typemaps.inout_ulonglong(var);
+        if (!var[0].equals(forty)) exit_test("inout_ulonglong");
+    }
+    {
+        BigInteger[] var = {new BigInteger("40")};
+        li_typemaps.inoutr_ulonglong(var);
+        if (!var[0].equals(forty)) exit_test("inoutr_ulonglong");
+    }
+    try {
+        BigInteger[] var = null;
+        li_typemaps.inout_ulonglong(var);
+        exit_test("null inout_ulonglong");
+    } catch (NullPointerException e) {
+    }
+    try {
+        BigInteger[] var = { null };
+        li_typemaps.inout_ulonglong(var);
+        exit_test("null element inout_ulonglong");
+    } catch (NullPointerException e) {
+    }
+
+  }
+
+  private static void exit_test(String funcName) {
+      throw new RuntimeException("Test FAILED in function " + funcName);
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/long_long_runme.java b/trunk/Examples/test-suite/java/long_long_runme.java
new file mode 100644
index 0000000..d3092b3
--- /dev/null
+++ b/trunk/Examples/test-suite/java/long_long_runme.java
@@ -0,0 +1,83 @@
+
+// This is the long_long runtime testcase. It checks that the long long and
+// unsigned long long types map correctly to long and BigInteger respectively.
+
+import long_long.*;
+import java.math.*;
+
+public class long_long_runme {
+
+  static {
+    try {
+	System.loadLibrary("long_long");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    check_ll(0L);
+    check_ll(0x7FFFFFFFFFFFFFFFL);
+    check_ll(-10);
+
+    BigInteger testNumber = new BigInteger("0");
+    final int COUNT = 1025;
+
+    for (long i=0; i<COUNT; i++) {
+      check_ull(testNumber);
+      testNumber = testNumber.add(BigInteger.ONE);
+    }
+
+    testNumber = new BigInteger(Long.toString(256*256/2-COUNT));
+    for (long i=0; i<COUNT*2; i++) {
+      check_ull(testNumber);
+      testNumber = testNumber.add(BigInteger.ONE);
+    }
+
+    testNumber = new BigInteger(Long.toString(256*256-COUNT));
+    for (long i=0; i<COUNT*2; i++) {
+      check_ull(testNumber);
+      testNumber = testNumber.add(BigInteger.ONE);
+    }
+
+    testNumber = new BigInteger(Long.toString(0x7FFFFFFFFFFFFFFFL-COUNT));
+    for (long i=0; i<COUNT*2; i++) {
+      check_ull(testNumber);
+      testNumber = testNumber.add(BigInteger.ONE);
+    }
+
+    testNumber = new BigInteger("18446744073709551615"); //0xFFFFFFFFFFFFFFFFL
+    testNumber = testNumber.add(BigInteger.valueOf(1-COUNT));
+    for (long i=0; i<COUNT; i++) {
+      check_ull(testNumber);
+      testNumber = testNumber.add(BigInteger.ONE);
+    }
+    
+    try {
+      long_long.setUll(null);
+      throw new RuntimeException("null check failed");
+    } catch (NullPointerException e) {
+    }
+  }
+
+  public static void check_ll(long ll) {
+    long_long.setLl(ll);
+    long ll_check = long_long.getLl();
+    if (ll != ll_check) {
+      System.err.println("Runtime test using long long failed. ll=" + ll + " ll_check=" + ll_check);
+      System.exit(1);
+    }
+  }
+
+  public static void check_ull(BigInteger ull) {
+    long_long.setUll(ull);
+    BigInteger ull_check = long_long.getUll();
+    if (ull.compareTo(ull_check) != 0) {
+      System.err.println("Runtime test using unsigned long long failed. ull=" + ull.toString() + " ull_check=" + ull_check.toString());
+      System.exit(1);
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/member_pointer_runme.java b/trunk/Examples/test-suite/java/member_pointer_runme.java
new file mode 100644
index 0000000..f8dcfbc
--- /dev/null
+++ b/trunk/Examples/test-suite/java/member_pointer_runme.java
@@ -0,0 +1,58 @@
+import member_pointer.*;
+
+public class member_pointer_runme {
+
+  static {
+    try {
+        System.loadLibrary("member_pointer");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static SWIGTYPE_m_Shape__f_void__double memberPtr = null;
+
+  public static void main(String argv[]) {
+    // Get the pointers
+
+    SWIGTYPE_m_Shape__f_void__double area_pt = member_pointer.areapt();
+    SWIGTYPE_m_Shape__f_void__double perim_pt = member_pointer.perimeterpt();
+
+    // Create some objects
+
+    Square s = new Square(10);
+
+    // Do some calculations
+
+    check( "Square area ", 100.0, member_pointer.do_op(s,area_pt) );
+    check( "Square perim", 40.0, member_pointer.do_op(s,perim_pt) );
+
+    memberPtr = member_pointer.getAreavar();
+    memberPtr = member_pointer.getPerimetervar();
+
+    // Try the variables
+    check( "Square area ", 100.0, member_pointer.do_op(s,member_pointer.getAreavar()) );
+    check( "Square perim", 40.0, member_pointer.do_op(s,member_pointer.getPerimetervar()) );
+
+    // Modify one of the variables
+    member_pointer.setAreavar(perim_pt);
+
+    check( "Square perimeter", 40.0, member_pointer.do_op(s,member_pointer.getAreavar()) );
+
+    // Try the constants
+
+    memberPtr = member_pointer.AREAPT;
+    memberPtr = member_pointer.PERIMPT;
+    memberPtr = member_pointer.NULLPT;
+
+    check( "Square area ", 100.0, member_pointer.do_op(s,member_pointer.AREAPT) );
+    check( "Square perim", 40.0, member_pointer.do_op(s,member_pointer.PERIMPT) );
+
+  }
+
+  private static void check(String what, double expected, double actual) {
+    if (expected != actual)
+      throw new RuntimeException("Failed: " + what + " Expected: " + expected + " Actual: " + actual);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/minherit2_runme.java b/trunk/Examples/test-suite/java/minherit2_runme.java
new file mode 100644
index 0000000..ea8102a
--- /dev/null
+++ b/trunk/Examples/test-suite/java/minherit2_runme.java
@@ -0,0 +1,32 @@
+
+import minherit2.*;
+import java.lang.reflect.*;
+
+public class minherit2_runme {
+
+  static {
+    try {
+        System.loadLibrary("minherit2");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    try {
+
+      Method method = IRemoteAsyncIO.class.getDeclaredMethod("asyncmethod", (java.lang.Class[])null);
+      if ( !Modifier.isAbstract(method.getModifiers()) )
+        throw new RuntimeException("asyncmethod should be abstract" );
+
+      method = IRemoteSyncIO.class.getDeclaredMethod("syncmethod", (java.lang.Class[])null);
+      if ( !Modifier.isAbstract(method.getModifiers()) )
+        throw new RuntimeException("syncmethod should be abstract" );
+
+    } catch (NoSuchMethodException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/multiple_inheritance_runme.java b/trunk/Examples/test-suite/java/multiple_inheritance_runme.java
new file mode 100644
index 0000000..dbfd798
--- /dev/null
+++ b/trunk/Examples/test-suite/java/multiple_inheritance_runme.java
@@ -0,0 +1,32 @@
+
+import multiple_inheritance.*;
+
+public class multiple_inheritance_runme {
+
+  static {
+    try {
+	System.loadLibrary("multiple_inheritance");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    FooBar fooBar = new FooBar();
+    fooBar.foo();
+
+    IgnoreDerived1 ignoreDerived1 = new IgnoreDerived1();
+    ignoreDerived1.bar();
+
+    IgnoreDerived2 ignoreDerived2 = new IgnoreDerived2();
+    ignoreDerived2.bar();
+
+    IgnoreDerived3 ignoreDerived3 = new IgnoreDerived3();
+    ignoreDerived3.bar();
+
+    IgnoreDerived4 ignoreDerived4 = new IgnoreDerived4();
+    ignoreDerived4.bar();
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/operator_overload_runme.java b/trunk/Examples/test-suite/java/operator_overload_runme.java
new file mode 100644
index 0000000..8a9dddf
--- /dev/null
+++ b/trunk/Examples/test-suite/java/operator_overload_runme.java
@@ -0,0 +1,113 @@
+import operator_overload.*;
+
+public class operator_overload_runme {
+
+  static {
+    System.loadLibrary("operator_overload");
+  }
+
+  public static void main(String argv[]) {
+
+    // Java does not support operators, so we just check that these can be called as methods.
+
+    Op.sanity_check();
+
+    //test routine:
+    Op a = new Op();
+    Op b = new Op(5);
+    Op c = new Op(b); // copy constructor
+    Op d = new Op(2);
+    Op dd = d.Equal(d); // assignment operator
+
+    // test equality
+    Assert(a.NotEqual(b));
+    Assert(b.EqualEqual(c));
+    Assert(a.NotEqual(d));
+    Assert(d.EqualEqual(dd));
+
+    // test <
+    Assert(a.LessThan(b));
+    Assert(a.LessThanEqual(b));
+    Assert(b.LessThanEqual(c));
+    Assert(b.GreaterThanEqual(c));
+    Assert(b.GreaterThan(d));
+    Assert(b.GreaterThanEqual(d));
+
+    // test +=
+    Op e = new Op(3);
+    e.PlusEqual(d);
+    Assert(e.EqualEqual(b));
+    e.MinusEqual(c);
+    Assert(e.EqualEqual(a));
+    e = new Op(1);
+    e.MultiplyEqual(b);
+    Assert(e.EqualEqual(c));
+    e.DivideEqual(d);
+    Assert(e.EqualEqual(d));
+    e.PercentEqual(c);
+    Assert(e.EqualEqual(d));
+
+    // test +
+    Op f = new Op(1);
+    Op g = new Op(1);
+    Assert(f.Plus(g).EqualEqual(new Op(2)));
+    Assert(f.Minus(g).EqualEqual(new Op(0)));
+    Assert(f.Multiply(g).EqualEqual(new Op(1)));
+    Assert(f.Divide(g).EqualEqual(new Op(1)));
+    Assert(f.Percent(g).EqualEqual(new Op(0)));
+
+    // test unary operators
+    Assert((a.Not() == true));
+    Assert((b.Not() == false));
+    Assert(a.Minus().EqualEqual(a));
+    Assert(b.Minus().EqualEqual( new Op(-5)));
+
+    // test []
+    Op h = new Op(3);
+    Assert(h.__getitem__(0) == 3);
+    Assert(h.__getitem__(1) == 0);
+    h.__setitem__(0,2);	// set
+    Assert(h.__getitem__(0) == 2);
+    h.__setitem__(1,2);	// ignored
+    Assert(h.IndexIntoConst(0) == 2);
+    Assert(h.IndexIntoConst(1) == 0);
+
+    // test ()
+    Op i = new Op(3);
+    Assert(i.Functor()==3);
+    Assert(i.Functor(1)==4);
+    Assert(i.Functor(1,2)==6);
+
+    // test ++ --
+    Op j = new Op(10);
+    j.PlusPlusPrefix();
+    j.PlusPlusPostfix(0);
+    Assert(j.getI() == 12);
+    j.MinusMinusPrefix();
+    j.MinusMinusPostfix(0);
+    Assert(j.getI() == 10);
+    {
+      Op op = j.PlusPlusPostfix(0);
+      Assert(j.getI() == op.getI()+1);
+    }
+    {
+      Op op = j.MinusMinusPostfix(0);
+      Assert(j.getI() == op.getI()-1);
+    }
+
+    // cast operators
+    Op k = new Op(3);
+    int check_k = k.IntCast();
+    Assert(check_k == 3);
+
+    Op l = new Op(4);
+    double check_l = l.DoubleCast();
+    Assert(check_l == 4);
+
+  }
+
+  public static void Assert(boolean b) {
+    if (!b)
+      throw new RuntimeException("Assertion failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/overload_complicated_runme.java b/trunk/Examples/test-suite/java/overload_complicated_runme.java
new file mode 100755
index 0000000..ac8523d
--- /dev/null
+++ b/trunk/Examples/test-suite/java/overload_complicated_runme.java
@@ -0,0 +1,63 @@
+
+import overload_complicated.*;
+
+public class overload_complicated_runme {
+
+  static {
+    try {
+        System.loadLibrary("overload_complicated");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+      SWIGTYPE_p_int pInt = null;
+
+      // Check the correct constructors are available
+      Pop p = new Pop(pInt);
+
+      p = new Pop(pInt, false);
+
+      // Check overloaded in const only and pointers/references which target languages cannot disambiguate
+      if (p.hip(false) != 701)
+        throw new RuntimeException("Test 1 failed");
+
+      if (p.hip(pInt) != 702)
+        throw new RuntimeException("Test 2 failed");
+
+      // Reverse the order for the above
+      if (p.hop(pInt) != 805)
+        throw new RuntimeException("Test 3 failed");
+
+      if (p.hop(false) != 801)
+        throw new RuntimeException("Test 4 failed");
+
+      // Few more variations and order shuffled
+      if (p.pop(false) != 901)
+        throw new RuntimeException("Test 5 failed");
+
+      if (p.pop(pInt) != 902)
+        throw new RuntimeException("Test 6 failed");
+
+      if (p.pop() != 905)
+        throw new RuntimeException("Test 7 failed");
+
+      // Overload on const only
+      if (p.bop(pInt) != 1001)
+        throw new RuntimeException("Test 8 failed");
+
+      if (p.bip(pInt) != 2001)
+        throw new RuntimeException("Test 9 failed");
+
+      // Globals
+      if (overload_complicated.muzak(false) != 3001)
+        throw new RuntimeException("Test 10 failed");
+
+      if (overload_complicated.muzak(pInt) != 3002)
+        throw new RuntimeException("Test 11 failed");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/overload_template_runme.java b/trunk/Examples/test-suite/java/overload_template_runme.java
new file mode 100644
index 0000000..e76bf63
--- /dev/null
+++ b/trunk/Examples/test-suite/java/overload_template_runme.java
@@ -0,0 +1,160 @@
+
+
+import overload_template.*;
+
+public class overload_template_runme {
+
+  static {
+    try {
+	System.loadLibrary("overload_template");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    int f = overload_template.foo();
+
+    int a = overload_template.max(3,4);
+    double b = overload_template.max(3.4,5.2);
+
+    // mix 1
+    if (overload_template.mix1("hi") != 101)
+      throw new RuntimeException ("mix1(const char*)");
+
+    if (overload_template.mix1(1.0, 1.0) != 102)
+      throw new RuntimeException ("mix1(double, const double &)");
+
+    if (overload_template.mix1(1.0) != 103)
+      throw new RuntimeException ("mix1(double)");
+
+    // mix 2
+    if (overload_template.mix2("hi") != 101)
+      throw new RuntimeException ("mix2(const char*)");
+
+    if (overload_template.mix2(1.0, 1.0) != 102)
+      throw new RuntimeException ("mix2(double, const double &)");
+
+    if (overload_template.mix2(1.0) != 103)
+      throw new RuntimeException ("mix2(double)");
+
+    // mix 3
+    if (overload_template.mix3("hi") != 101)
+      throw new RuntimeException ("mix3(const char*)");
+
+    if (overload_template.mix3(1.0, 1.0) != 102)
+      throw new RuntimeException ("mix3(double, const double &)");
+
+    if (overload_template.mix3(1.0) != 103)
+      throw new RuntimeException ("mix3(double)");
+
+    // Combination 1
+    if (overload_template.overtparams1(100) != 10)
+      throw new RuntimeException ("overtparams1(int)");
+
+    if (overload_template.overtparams1(100.0, 100) != 20)
+      throw new RuntimeException ("overtparams1(double, int)");
+
+    // Combination 2
+    if (overload_template.overtparams2(100.0, 100) != 40)
+      throw new RuntimeException ("overtparams2(double, int)");
+
+    // Combination 3
+    if (overload_template.overloaded() != 60)
+      throw new RuntimeException ("overloaded()");
+
+    if (overload_template.overloaded(100.0, 100) != 70)
+      throw new RuntimeException ("overloaded(double, int)");
+
+    // Combination 4
+    if (overload_template.overloadedagain("hello") != 80)
+      throw new RuntimeException ("overloadedagain(const char *)");
+
+    if (overload_template.overloadedagain() != 90)
+      throw new RuntimeException ("overloadedagain(double)");
+
+    // specializations
+    if (overload_template.specialization(10) != 202)
+      throw new RuntimeException ("specialization(int)");
+
+    if (overload_template.specialization(10.0) != 203)
+      throw new RuntimeException ("specialization(double)");
+
+    if (overload_template.specialization(10, 10) != 204)
+      throw new RuntimeException ("specialization(int, int)");
+
+    if (overload_template.specialization(10.0, 10.0) != 205)
+      throw new RuntimeException ("specialization(double, double)");
+
+    if (overload_template.specialization("hi", "hi") != 201)
+      throw new RuntimeException ("specialization(const char *, const char *)");
+
+
+    // simple specialization
+    overload_template.xyz();
+    overload_template.xyz_int();
+    overload_template.xyz_double();
+
+
+    // a bit of everything
+    if (overload_template.overload("hi") != 0)
+      throw new RuntimeException ("overload()");
+
+    if (overload_template.overload(1) != 10)
+      throw new RuntimeException ("overload(int t)");
+
+    if (overload_template.overload(1, 1) != 20)
+      throw new RuntimeException ("overload(int t, const int &)");
+
+    if (overload_template.overload(1, "hello") != 30)
+      throw new RuntimeException ("overload(int t, const char *)");
+
+    Klass k = new Klass();
+    if (overload_template.overload(k) != 10)
+      throw new RuntimeException ("overload(Klass t)");
+
+    if (overload_template.overload(k, k) != 20)
+      throw new RuntimeException ("overload(Klass t, const Klass &)");
+
+    if (overload_template.overload(k, "hello") != 30)
+      throw new RuntimeException ("overload(Klass t, const char *)");
+
+    if (overload_template.overload(10.0, "hi") != 40)
+      throw new RuntimeException ("overload(double t, const char *)");
+
+    if (overload_template.overload() != 50)
+      throw new RuntimeException ("overload(const char *)");
+
+
+    // everything put in a namespace
+    if (overload_template.nsoverload("hi") != 1000)
+      throw new RuntimeException ("nsoverload()");
+
+    if (overload_template.nsoverload(1) != 1010)
+      throw new RuntimeException ("nsoverload(int t)");
+
+    if (overload_template.nsoverload(1, 1) != 1020)
+      throw new RuntimeException ("nsoverload(int t, const int &)");
+
+    if (overload_template.nsoverload(1, "hello") != 1030)
+      throw new RuntimeException ("nsoverload(int t, const char *)");
+
+    if (overload_template.nsoverload(k) != 1010)
+      throw new RuntimeException ("nsoverload(Klass t)");
+
+    if (overload_template.nsoverload(k, k) != 1020)
+      throw new RuntimeException ("nsoverload(Klass t, const Klass &)");
+
+    if (overload_template.nsoverload(k, "hello") != 1030)
+      throw new RuntimeException ("nsoverload(Klass t, const char *)");
+
+    if (overload_template.nsoverload(10.0, "hi") != 1040)
+      throw new RuntimeException ("nsoverload(double t, const char *)");
+
+    if (overload_template.nsoverload() != 1050)
+      throw new RuntimeException ("nsoverload(const char *)");
+
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/pointer_reference_runme.java b/trunk/Examples/test-suite/java/pointer_reference_runme.java
new file mode 100644
index 0000000..e8bd680
--- /dev/null
+++ b/trunk/Examples/test-suite/java/pointer_reference_runme.java
@@ -0,0 +1,23 @@
+import pointer_reference.*;
+
+public class pointer_reference_runme {
+
+  static {
+    try {
+        System.loadLibrary("pointer_reference");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    Struct s  = pointer_reference.get();
+    if (s.getValue() != 10) throw new RuntimeException("get test failed");
+
+    Struct ss = new Struct(20);
+    pointer_reference.set(ss);
+    if (Struct.getInstance().getValue() != 20) throw new RuntimeException("set test failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/primitive_ref_runme.java b/trunk/Examples/test-suite/java/primitive_ref_runme.java
new file mode 100644
index 0000000..2955004
--- /dev/null
+++ b/trunk/Examples/test-suite/java/primitive_ref_runme.java
@@ -0,0 +1,64 @@
+// Check that C++ primitive types that are passed by const reference work when
+// passed by value from Java
+
+import primitive_ref.*;
+import java.math.*;
+
+public class primitive_ref_runme {
+
+  static {
+    try {
+	System.loadLibrary("primitive_ref");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    if (primitive_ref.ref_int(3) != 3) {
+        System.err.println( "ref_int failed!" );
+    }
+    if (primitive_ref.ref_uint(3) != 3) {
+        System.err.println( "ref_uint failed!" );
+    }
+    if (primitive_ref.ref_short((short)3) != 3) {
+        System.err.println( "ref_short failed!" );
+    }
+    if (primitive_ref.ref_ushort(3) != 3) {
+        System.err.println( "ref_ushort failed!" );
+    }
+    if (primitive_ref.ref_long(3) != 3) {
+        System.err.println( "ref_long failed!" );
+    }
+    if (primitive_ref.ref_ulong(3) != 3) {
+        System.err.println( "ref_ulong failed!" );
+    }
+    if (primitive_ref.ref_schar((byte)3) != 3) {
+        System.err.println( "ref_schar failed!" );
+    }
+    if (primitive_ref.ref_uchar((short)3) != 3) {
+        System.err.println( "ref_uchar failed!" );
+    }
+    if (primitive_ref.ref_bool(true) != true) {
+        System.err.println( "ref_bool failed!" );
+    }
+    if (primitive_ref.ref_float((float)3.5) != 3.5) {
+        System.err.println( "ref_float failed!" );
+    }
+    if (primitive_ref.ref_double(3.5) != 3.5) {
+        System.err.println( "ref_double failed!" );
+    }
+    if (primitive_ref.ref_char('x') != 'x') {
+        System.err.println( "ref_char failed!" );
+    }
+    if (primitive_ref.ref_longlong(0x123456789ABCDEF0L) != 0x123456789ABCDEF0L) {
+        System.err.println( "ref_longlong failed!" );
+    }
+    BigInteger bi = new BigInteger("18446744073709551615"); //0xFFFFFFFFFFFFFFFFL
+    if (bi.compareTo(primitive_ref.ref_ulonglong(bi)) != 0) {
+        System.err.println( "ref_ulonglong failed!" );
+    }
+  }
+}
diff --git a/trunk/Examples/test-suite/java/profiletest_runme.java b/trunk/Examples/test-suite/java/profiletest_runme.java
new file mode 100644
index 0000000..f550013
--- /dev/null
+++ b/trunk/Examples/test-suite/java/profiletest_runme.java
@@ -0,0 +1,15 @@
+import profiletest.*;
+
+public class profiletest_runme {
+
+    System.loadLibrary("profiletest");
+
+    public static void main(String argv[]) {
+	
+	long a = profiletest.new_A();
+	long b = profiletest.new_B();
+	for (int i=0; i<1000000; i++) {
+	    a = profiletest.B_fn(b, a);
+	}
+    }
+}
diff --git a/trunk/Examples/test-suite/java/rename1_runme.java b/trunk/Examples/test-suite/java/rename1_runme.java
new file mode 100644
index 0000000..058de41
--- /dev/null
+++ b/trunk/Examples/test-suite/java/rename1_runme.java
@@ -0,0 +1,75 @@
+
+import rename1.*;
+
+public class rename1_runme {
+
+  static {
+    try {
+	System.loadLibrary("rename1");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  // The code in main is the same for rename1_runme, rename2_runme, rename3_runme and renam4_runme
+  public static void main(String argv[]) {
+    {
+      XYZInt xyz = new XYZInt();
+      NotXYZInt notxyz = new NotXYZInt();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother2();
+      xyz.opT2();
+      xyz.tMethod2(0);
+      xyz.tMethodNotXYZ2(notxyz);
+      xyz.opNotXYZ2();
+      xyz.opXYZ2();
+    }
+    {
+      XYZDouble xyz = new XYZDouble();
+      NotXYZDouble notxyz = new NotXYZDouble();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother1();
+      xyz.opT1();
+      xyz.tMethod1(0);
+      xyz.tMethodNotXYZ1(notxyz);
+      xyz.opNotXYZ1();
+      xyz.opXYZ1();
+    }
+    {
+      XYZKlass xyz = new XYZKlass();
+      NotXYZKlass notxyz = new NotXYZKlass();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother3();
+      xyz.opT3();
+      xyz.tMethod3(new Klass());
+      xyz.tMethodNotXYZ3(notxyz);
+      xyz.opNotXYZ3();
+      xyz.opXYZ3();
+    }
+    {
+      XYZEnu xyz = new XYZEnu();
+      NotXYZEnu notxyz = new NotXYZEnu();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother4();
+      xyz.opT4();
+      xyz.tMethod4(Enu.En1);
+      xyz.tMethodNotXYZ4(notxyz);
+      xyz.opNotXYZ4();
+      xyz.opXYZ4();
+    }
+    {
+      ABC abc = new ABC();
+      abc.methodABC(abc);
+      Klass k = new Klass();
+      abc.methodKlass(k);
+      ABC a = abc.opABC();
+      k = abc.opKlass();
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/rename2_runme.java b/trunk/Examples/test-suite/java/rename2_runme.java
new file mode 100644
index 0000000..b6a62dd
--- /dev/null
+++ b/trunk/Examples/test-suite/java/rename2_runme.java
@@ -0,0 +1,75 @@
+
+import rename2.*;
+
+public class rename2_runme {
+
+  static {
+    try {
+	System.loadLibrary("rename2");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  // The code in main is the same for rename1_runme, rename2_runme, rename3_runme and renam4_runme
+  public static void main(String argv[]) {
+    {
+      XYZInt xyz = new XYZInt();
+      NotXYZInt notxyz = new NotXYZInt();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother2();
+      xyz.opT2();
+      xyz.tMethod2(0);
+      xyz.tMethodNotXYZ2(notxyz);
+      xyz.opNotXYZ2();
+      xyz.opXYZ2();
+    }
+    {
+      XYZDouble xyz = new XYZDouble();
+      NotXYZDouble notxyz = new NotXYZDouble();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother1();
+      xyz.opT1();
+      xyz.tMethod1(0);
+      xyz.tMethodNotXYZ1(notxyz);
+      xyz.opNotXYZ1();
+      xyz.opXYZ1();
+    }
+    {
+      XYZKlass xyz = new XYZKlass();
+      NotXYZKlass notxyz = new NotXYZKlass();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother3();
+      xyz.opT3();
+      xyz.tMethod3(new Klass());
+      xyz.tMethodNotXYZ3(notxyz);
+      xyz.opNotXYZ3();
+      xyz.opXYZ3();
+    }
+    {
+      XYZEnu xyz = new XYZEnu();
+      NotXYZEnu notxyz = new NotXYZEnu();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother4();
+      xyz.opT4();
+      xyz.tMethod4(Enu.En1);
+      xyz.tMethodNotXYZ4(notxyz);
+      xyz.opNotXYZ4();
+      xyz.opXYZ4();
+    }
+    {
+      ABC abc = new ABC();
+      abc.methodABC(abc);
+      Klass k = new Klass();
+      abc.methodKlass(k);
+      ABC a = abc.opABC();
+      k = abc.opKlass();
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/rename3_runme.java b/trunk/Examples/test-suite/java/rename3_runme.java
new file mode 100644
index 0000000..e1b090a
--- /dev/null
+++ b/trunk/Examples/test-suite/java/rename3_runme.java
@@ -0,0 +1,75 @@
+
+import rename3.*;
+
+public class rename3_runme {
+
+  static {
+    try {
+	System.loadLibrary("rename3");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  // The code in main is the same for rename1_runme, rename2_runme, rename3_runme and renam4_runme
+  public static void main(String argv[]) {
+    {
+      XYZInt xyz = new XYZInt();
+      NotXYZInt notxyz = new NotXYZInt();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother2();
+      xyz.opT2();
+      xyz.tMethod2(0);
+      xyz.tMethodNotXYZ2(notxyz);
+      xyz.opNotXYZ2();
+      xyz.opXYZ2();
+    }
+    {
+      XYZDouble xyz = new XYZDouble();
+      NotXYZDouble notxyz = new NotXYZDouble();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother1();
+      xyz.opT1();
+      xyz.tMethod1(0);
+      xyz.tMethodNotXYZ1(notxyz);
+      xyz.opNotXYZ1();
+      xyz.opXYZ1();
+    }
+    {
+      XYZKlass xyz = new XYZKlass();
+      NotXYZKlass notxyz = new NotXYZKlass();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother3();
+      xyz.opT3();
+      xyz.tMethod3(new Klass());
+      xyz.tMethodNotXYZ3(notxyz);
+      xyz.opNotXYZ3();
+      xyz.opXYZ3();
+    }
+    {
+      XYZEnu xyz = new XYZEnu();
+      NotXYZEnu notxyz = new NotXYZEnu();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother4();
+      xyz.opT4();
+      xyz.tMethod4(Enu.En1);
+      xyz.tMethodNotXYZ4(notxyz);
+      xyz.opNotXYZ4();
+      xyz.opXYZ4();
+    }
+    {
+      ABC abc = new ABC();
+      abc.methodABC(abc);
+      Klass k = new Klass();
+      abc.methodKlass(k);
+      ABC a = abc.opABC();
+      k = abc.opKlass();
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/rename4_runme.java b/trunk/Examples/test-suite/java/rename4_runme.java
new file mode 100644
index 0000000..69f909e
--- /dev/null
+++ b/trunk/Examples/test-suite/java/rename4_runme.java
@@ -0,0 +1,75 @@
+
+import rename4.*;
+
+public class rename4_runme {
+
+  static {
+    try {
+	System.loadLibrary("rename4");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  // The code in main is the same for rename1_runme, rename2_runme, rename3_runme and renam4_runme
+  public static void main(String argv[]) {
+    {
+      XYZInt xyz = new XYZInt();
+      NotXYZInt notxyz = new NotXYZInt();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother2();
+      xyz.opT2();
+      xyz.tMethod2(0);
+      xyz.tMethodNotXYZ2(notxyz);
+      xyz.opNotXYZ2();
+      xyz.opXYZ2();
+    }
+    {
+      XYZDouble xyz = new XYZDouble();
+      NotXYZDouble notxyz = new NotXYZDouble();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother1();
+      xyz.opT1();
+      xyz.tMethod1(0);
+      xyz.tMethodNotXYZ1(notxyz);
+      xyz.opNotXYZ1();
+      xyz.opXYZ1();
+    }
+    {
+      XYZKlass xyz = new XYZKlass();
+      NotXYZKlass notxyz = new NotXYZKlass();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother3();
+      xyz.opT3();
+      xyz.tMethod3(new Klass());
+      xyz.tMethodNotXYZ3(notxyz);
+      xyz.opNotXYZ3();
+      xyz.opXYZ3();
+    }
+    {
+      XYZEnu xyz = new XYZEnu();
+      NotXYZEnu notxyz = new NotXYZEnu();
+      xyz.opIntPtrA();
+      xyz.opIntPtrB();
+      xyz.opAnother4();
+      xyz.opT4();
+      xyz.tMethod4(Enu.En1);
+      xyz.tMethodNotXYZ4(notxyz);
+      xyz.opNotXYZ4();
+      xyz.opXYZ4();
+    }
+    {
+      ABC abc = new ABC();
+      abc.methodABC(abc);
+      Klass k = new Klass();
+      abc.methodKlass(k);
+      ABC a = abc.opABC();
+      k = abc.opKlass();
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/ret_by_value_runme.java b/trunk/Examples/test-suite/java/ret_by_value_runme.java
new file mode 100644
index 0000000..44bb697
--- /dev/null
+++ b/trunk/Examples/test-suite/java/ret_by_value_runme.java
@@ -0,0 +1,33 @@
+
+// This is the ret_by_value runtime testcase. It checks that SWIG handles
+// return by value okay.
+
+import ret_by_value.*;
+
+public class ret_by_value_runme {
+
+  static {
+    try {
+	System.loadLibrary("ret_by_value");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // Get the test class. Note that this constructor will ensure that the memory created 
+    // in the wrapper is owned by the test class.
+    test tst = ret_by_value.get_test();
+
+    if (tst.getMyInt() != 100 || tst.getMyShort() != 200) {
+      System.err.println("Runtime test failed. myInt=" + tst.getMyInt() + " myShort=" + tst.getMyShort());
+      System.exit(1);
+    }
+
+    // Delete memory manually, it should not be deleted again by the test class finalizer
+    tst.delete();
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/rname_runme.java b/trunk/Examples/test-suite/java/rname_runme.java
new file mode 100644
index 0000000..7f2ab2f
--- /dev/null
+++ b/trunk/Examples/test-suite/java/rname_runme.java
@@ -0,0 +1,38 @@
+
+import rname.*;
+
+public class rname_runme {
+
+  static {
+    try {
+	System.loadLibrary("rname");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    rname.foo_i(10);
+    rname.foo_d(10.0);
+    rname.foo_s((short)10);
+    rname.foo((long)10);
+
+    Bar bar = new Bar();
+    bar.foo_i(10);
+    bar.foo_d(10.0);
+    bar.foo((short)10);
+    bar.foo_u((long)10);
+
+    RenamedBase base = new RenamedBase();
+    base.fn(base, base, base);
+    if (!base.newname(10.0).equals("Base"))
+      throw new RuntimeException("base.newname");
+
+    RenamedDerived derived = new RenamedDerived();
+    derived.func(base, base, base);
+    if (!derived.newname(10.0).equals("Derived"))
+      throw new RuntimeException("derived.newname");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/sizet_runme.java b/trunk/Examples/test-suite/java/sizet_runme.java
new file mode 100644
index 0000000..20ab047
--- /dev/null
+++ b/trunk/Examples/test-suite/java/sizet_runme.java
@@ -0,0 +1,24 @@
+import sizet.*;
+
+public class sizet_runme {
+
+  static {
+    try {
+        System.loadLibrary("sizet");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    long s = 2000;
+    s = sizet.test1(s+1);
+    s = sizet.test2(s+1);
+    s = sizet.test3(s+1);
+    s = sizet.test4(s+1);
+    if (s != 2004)
+      throw new RuntimeException("failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/special_variables_runme.java b/trunk/Examples/test-suite/java/special_variables_runme.java
new file mode 100644
index 0000000..eb9f093
--- /dev/null
+++ b/trunk/Examples/test-suite/java/special_variables_runme.java
@@ -0,0 +1,53 @@
+
+import special_variables.*;
+
+public class special_variables_runme {
+
+  static {
+    try {
+        System.loadLibrary("special_variables");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    verify(special_variables.ExceptionVars(1.0, 2.0),
+           "result = Space::exceptionvars(arg1,arg2);  Space::exceptionvars  ExceptionVars   Java_special_1variables_special_1variablesJNI_ExceptionVars");
+
+    verify(special_variables.overloadedmethod(),
+           "result = Space::overloadedmethod();  Space::overloadedmethod  overloadedmethod  __SWIG_1 Java_special_1variables_special_1variablesJNI_overloadedmethod_1_1SWIG_11");
+
+    verify(special_variables.overloadedmethod(10.0),
+          "result = Space::overloadedmethod(arg1);  Space::overloadedmethod  overloadedmethod  __SWIG_0 Java_special_1variables_special_1variablesJNI_overloadedmethod_1_1SWIG_10");
+
+    ABC a = new ABC(0, 0.0);
+    verify(special_variables.getDeclaration(), "SpaceNamespace::ABC::ABC(int,double) SpaceNamespace::ABC::ABC(int,double)");
+    a = new ABC();
+    verify(special_variables.getDeclaration(), "SpaceNamespace::ABC::ABC() SpaceNamespace::ABC::ABC()");
+    a.instancemethod(1);
+    verify(special_variables.getDeclaration(), "short * SpaceNamespace::ABC::instancemethod(int) SpaceNamespace::ABC::instancemethod(int)");
+    a.instancemethod(1, false);
+    verify(special_variables.getDeclaration(), "short * SpaceNamespace::ABC::instancemethod(int,bool) SpaceNamespace::ABC::instancemethod(int,bool)");
+    a.constmethod(1);
+    verify(special_variables.getDeclaration(), "short * SpaceNamespace::ABC::constmethod(int) const SpaceNamespace::ABC::constmethod(int) const");
+    ABC.staticmethod(0, false);
+    verify(special_variables.getDeclaration(), "short * SpaceNamespace::ABC::staticmethod(int,bool) SpaceNamespace::ABC::staticmethod(int,bool)");
+    a.delete();
+    verify(special_variables.getDeclaration(), "SpaceNamespace::ABC::~ABC() SpaceNamespace::ABC::~ABC()");
+    TemplateABC abc = new TemplateABC();
+    verify(special_variables.getDeclaration(), "SpaceNamespace::Template< SpaceNamespace::ABC >::Template() SpaceNamespace::Template< SpaceNamespace::ABC >::Template()");
+    abc.tmethod(new ABC());
+    verify(special_variables.getDeclaration(), "std::string SpaceNamespace::Template< SpaceNamespace::ABC >::tmethod(SpaceNamespace::ABC) SpaceNamespace::Template< SpaceNamespace::ABC >::tmethod(SpaceNamespace::ABC)");
+    abc.delete();
+    verify(special_variables.getDeclaration(), "SpaceNamespace::Template< SpaceNamespace::ABC >::~Template() SpaceNamespace::Template< SpaceNamespace::ABC >::~Template()");
+    special_variables.globtemplate(new TemplateABC());
+    verify(special_variables.getDeclaration(), "void SpaceNamespace::globtemplate(SpaceNamespace::Template< SpaceNamespace::ABC >) SpaceNamespace::globtemplate(SpaceNamespace::Template< SpaceNamespace::ABC >)");
+  }
+  static void verify(String received, String expected) {
+    if (!received.equals(expected))
+      throw new RuntimeException("Incorrect, received: " + received);
+  }
+}
diff --git a/trunk/Examples/test-suite/java/template_classes_runme.java b/trunk/Examples/test-suite/java/template_classes_runme.java
new file mode 100644
index 0000000..48f12cb
--- /dev/null
+++ b/trunk/Examples/test-suite/java/template_classes_runme.java
@@ -0,0 +1,25 @@
+
+// This is the template_classes runtime testcase. It checks that SWIG handles a templated 
+// class used by another templated class, in particular that the proxy classes can be used.
+
+import template_classes.*;
+
+public class template_classes_runme {
+
+  static {
+    try {
+	System.loadLibrary("template_classes");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    RectangleInt rectint = new RectangleInt();
+    PointInt pi = rectint.getPoint();
+    int x = pi.getX();
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/template_default_arg_runme.java b/trunk/Examples/test-suite/java/template_default_arg_runme.java
new file mode 100644
index 0000000..b274935
--- /dev/null
+++ b/trunk/Examples/test-suite/java/template_default_arg_runme.java
@@ -0,0 +1,156 @@
+
+
+import template_default_arg.*;
+
+public class template_default_arg_runme {
+
+  static {
+    try {
+	System.loadLibrary("template_default_arg");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    {
+      Hello_int helloInt = new Hello_int();
+      helloInt.foo(Hello_int.Hi.hi);
+    }
+    {
+      X_int x = new X_int();
+      if (x.meth(20.0, 200) != 200)
+        throw new RuntimeException("X_int test 1 failed");
+      if (x.meth(20) != 20)
+        throw new RuntimeException("X_int test 2 failed");
+      if (x.meth() != 0)
+        throw new RuntimeException("X_int test 3 failed");
+    }
+
+    {
+      Y_unsigned y = new Y_unsigned();
+      if (y.meth(20.0, 200) != 200)
+        throw new RuntimeException("Y_unsigned test 1 failed");
+      if (y.meth(20) != 20)
+        throw new RuntimeException("Y_unsigned test 2 failed");
+      if (y.meth() != 0)
+        throw new RuntimeException("Y_unsigned test 3 failed");
+    }
+
+    {
+      X_longlong x = new X_longlong();
+      x = new X_longlong(20.0);
+      x = new X_longlong(20.0, 200L);
+    }
+    {
+      X_int x = new X_int();
+      x = new X_int(20.0);
+      x = new X_int(20.0, 200);
+    }
+    {
+      X_hello_unsigned x = new X_hello_unsigned();
+      x = new X_hello_unsigned(20.0);
+      x = new X_hello_unsigned(20.0, new Hello_int());
+    }
+    {
+      Y_hello_unsigned y = new Y_hello_unsigned();
+      y.meth(20.0, new Hello_int());
+      y.meth(new Hello_int());
+      y.meth();
+    }
+
+    {
+      Foo_Z_8 fz = new Foo_Z_8();
+      X_Foo_Z_8 x = new X_Foo_Z_8();
+      Foo_Z_8 fzc = x.meth(fz);
+    }
+
+    // Templated functions
+    {
+      // plain function: int ott(Foo<int>)
+      if (template_default_arg.ott(new Foo_int()) != 30)
+        throw new RuntimeException("ott test 1 failed");
+
+      // %template(ott) ott<int, int>;
+      if (template_default_arg.ott() != 10)
+        throw new RuntimeException("ott test 2 failed");
+      if (template_default_arg.ott(1) != 10)
+        throw new RuntimeException("ott test 3 failed");
+      if (template_default_arg.ott(1, 1) != 10)
+        throw new RuntimeException("ott test 4 failed");
+
+      if (template_default_arg.ott("hi") != 20)
+        throw new RuntimeException("ott test 5 failed");
+      if (template_default_arg.ott("hi", 1) != 20)
+        throw new RuntimeException("ott test 6 failed");
+      if (template_default_arg.ott("hi", 1, 1) != 20)
+        throw new RuntimeException("ott test 7 failed");
+
+      // %template(ott) ott<const char *>;
+      if (template_default_arg.ottstring(new Hello_int(), "hi") != 40)
+        throw new RuntimeException("ott test 8 failed");
+
+      if (template_default_arg.ottstring(new Hello_int()) != 40)
+        throw new RuntimeException("ott test 9 failed");
+
+      // %template(ott) ott<int>;
+      if (template_default_arg.ottint(new Hello_int(), 1) != 50)
+        throw new RuntimeException("ott test 10 failed");
+
+      if (template_default_arg.ottint(new Hello_int()) != 50)
+        throw new RuntimeException("ott test 11 failed");
+
+      // %template(ott) ott<double>;
+      if (template_default_arg.ott(new Hello_int(), 1.0) != 60)
+        throw new RuntimeException("ott test 12 failed");
+
+      if (template_default_arg.ott(new Hello_int()) != 60)
+        throw new RuntimeException("ott test 13 failed");
+    }
+
+    // Above test in namespaces
+    {
+      // plain function: int nsott(Foo<int>)
+      if (template_default_arg.nsott(new Foo_int()) != 130)
+        throw new RuntimeException("nsott test 1 failed");
+
+      // %template(nsott) nsott<int, int>;
+      if (template_default_arg.nsott() != 110)
+        throw new RuntimeException("nsott test 2 failed");
+      if (template_default_arg.nsott(1) != 110)
+        throw new RuntimeException("nsott test 3 failed");
+      if (template_default_arg.nsott(1, 1) != 110)
+        throw new RuntimeException("nsott test 4 failed");
+
+      if (template_default_arg.nsott("hi") != 120)
+        throw new RuntimeException("nsott test 5 failed");
+      if (template_default_arg.nsott("hi", 1) != 120)
+        throw new RuntimeException("nsott test 6 failed");
+      if (template_default_arg.nsott("hi", 1, 1) != 120)
+        throw new RuntimeException("nsott test 7 failed");
+
+      // %template(nsott) nsott<const char *>;
+      if (template_default_arg.nsottstring(new Hello_int(), "hi") != 140)
+        throw new RuntimeException("nsott test 8 failed");
+
+      if (template_default_arg.nsottstring(new Hello_int()) != 140)
+        throw new RuntimeException("nsott test 9 failed");
+
+      // %template(nsott) nsott<int>;
+      if (template_default_arg.nsottint(new Hello_int(), 1) != 150)
+        throw new RuntimeException("nsott test 10 failed");
+
+      if (template_default_arg.nsottint(new Hello_int()) != 150)
+        throw new RuntimeException("nsott test 11 failed");
+
+      // %template(nsott) nsott<double>;
+      if (template_default_arg.nsott(new Hello_int(), 1.0) != 160)
+        throw new RuntimeException("nsott test 12 failed");
+
+      if (template_default_arg.nsott(new Hello_int()) != 160)
+        throw new RuntimeException("nsott test 13 failed");
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/template_default_class_parms_runme.java b/trunk/Examples/test-suite/java/template_default_class_parms_runme.java
new file mode 100644
index 0000000..4c80107
--- /dev/null
+++ b/trunk/Examples/test-suite/java/template_default_class_parms_runme.java
@@ -0,0 +1,43 @@
+
+
+import template_default_class_parms.*;
+
+public class template_default_class_parms_runme {
+
+  static {
+    try {
+	System.loadLibrary("template_default_class_parms");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    {
+      DefaultBar bar = new DefaultBar(20.0, new SomeType(), 10);
+      double d = bar.getCType();
+      SomeType s = bar.getDType();
+      int i = bar.getEType();
+      d = bar.method(d, s, i);
+    }
+    {
+      DefaultFoo foo = new DefaultFoo(new SomeType());
+      SomeType s = foo.getTType();
+      s = foo.method(s);
+    }
+    {
+      BarAnotherTypeBool bar = new BarAnotherTypeBool(new AnotherType(), true, 10);
+      AnotherType a = bar.getCType();
+      boolean b = bar.getDType();
+      int i = bar.getEType();
+      a = bar.method(a, b, i);
+    }
+    {
+      FooAnotherType foo = new FooAnotherType(new AnotherType());
+      AnotherType a = foo.getTType();
+      a = foo.method(a);
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/template_methods_runme.java b/trunk/Examples/test-suite/java/template_methods_runme.java
new file mode 100644
index 0000000..cc179aa
--- /dev/null
+++ b/trunk/Examples/test-suite/java/template_methods_runme.java
@@ -0,0 +1,37 @@
+
+import template_methods.*;
+
+public class template_methods_runme {
+
+  static {
+    try {
+	System.loadLibrary("template_methods");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    float num = (float)1.1;
+
+    // Global templated functions
+    int i = template_methods.convolve1Bool();
+    template_methods.convolve1Bool(true);
+    i = template_methods.convolve2Float();
+    template_methods.convolve3FloatRenamed(num);
+    i = template_methods.convolve4Float();
+    template_methods.convolve4FloatRenamed(num);
+    i = template_methods.convolve5FloatRenamed();
+    template_methods.convolve5FloatRenamed(num);
+
+
+    // Static templated methods
+    Klass k = new Klass();
+    boolean b = k.KlassTMethodBoolRenamed(true);
+    k.KlassTMethodBool();
+    b = Klass.KlassStaticTMethodBoolRenamed(true);
+    Klass.KlassStaticTMethodBool();
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/template_template_parameters_runme.java b/trunk/Examples/test-suite/java/template_template_parameters_runme.java
new file mode 100644
index 0000000..42135b9
--- /dev/null
+++ b/trunk/Examples/test-suite/java/template_template_parameters_runme.java
@@ -0,0 +1,28 @@
+
+
+import template_template_parameters.*;
+
+public class template_template_parameters_runme {
+
+  static {
+    try {
+	System.loadLibrary("template_template_parameters");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+    ListFastBool listBool = new ListFastBool();
+    listBool.setItem(true);
+    if (listBool.getItem() != true)
+      throw new RuntimeException("Failed");
+
+    ListDefaultDouble listDouble = new ListDefaultDouble();
+    listDouble.setItem(10.2);
+    if (listDouble.getItem() != 10.2)
+      throw new RuntimeException("Failed");
+  }
+}
+
diff --git a/trunk/Examples/test-suite/java/typemap_namespace_runme.java b/trunk/Examples/test-suite/java/typemap_namespace_runme.java
new file mode 100644
index 0000000..eddb896
--- /dev/null
+++ b/trunk/Examples/test-suite/java/typemap_namespace_runme.java
@@ -0,0 +1,21 @@
+import typemap_namespace.*;
+
+public class typemap_namespace_runme {
+
+  static {
+    try {
+        System.loadLibrary("typemap_namespace");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) throws Throwable
+  {
+    if (!typemap_namespace.test1("hello").equals("hello"))
+      throw new RuntimeException("test1 failed");
+    if (!typemap_namespace.test2("hello").equals("hello"))
+      throw new RuntimeException("test2 failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/unions_runme.java b/trunk/Examples/test-suite/java/unions_runme.java
new file mode 100644
index 0000000..16a5b3b
--- /dev/null
+++ b/trunk/Examples/test-suite/java/unions_runme.java
@@ -0,0 +1,68 @@
+
+// This is the union runtime testcase. It ensures that values within a 
+// union embedded within a struct can be set and read correctly.
+
+import unions.*;
+
+public class unions_runme {
+
+  static {
+    try {
+	System.loadLibrary("unions");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    // Create new instances of SmallStruct and BigStruct for later use
+    SmallStruct small = new SmallStruct();
+    small.setJill((short)200);
+
+    BigStruct big = new BigStruct();
+    big.setSmallstruct(small);
+    big.setJack(300);
+
+    // Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+    // Ensure values in EmbeddedUnionTest are set correctly for each.
+    EmbeddedUnionTest eut = new EmbeddedUnionTest();
+
+    // First check the SmallStruct in EmbeddedUnionTest
+    eut.setNumber(1);
+    eut.getUni().setSmall(small);
+    short Jill1 = eut.getUni().getSmall().getJill();
+    if (Jill1 != 200) {
+        System.err.println("Runtime test1 failed. eut.uni.small.jill=" + Jill1);
+        System.exit(1);
+    }
+
+    int Num1 = eut.getNumber();
+    if (Num1 != 1) {
+        System.err.println("Runtime test2 failed. eut.number=" + Num1);
+        System.exit(1);
+    }
+
+    // Secondly check the BigStruct in EmbeddedUnionTest
+    eut.setNumber(2);
+    eut.getUni().setBig(big);
+    int Jack1 = eut.getUni().getBig().getJack();
+    if (Jack1 != 300) {
+        System.err.println("Runtime test3 failed. eut.uni.big.jack=" + Jack1);
+        System.exit(1);
+    }
+
+    short Jill2 = eut.getUni().getBig().getSmallstruct().getJill();
+    if (Jill2 != 200) {
+        System.err.println("Runtime test4 failed. eut.uni.big.smallstruct.jill=" + Jill2);
+        System.exit(1);
+    }
+
+    int Num2 = eut.getNumber();
+    if (Num2 != 2) {
+        System.err.println("Runtime test5 failed. eut.number=" + Num2);
+        System.exit(1);
+    }
+}
+}
diff --git a/trunk/Examples/test-suite/java/using_pointers_runme.java b/trunk/Examples/test-suite/java/using_pointers_runme.java
new file mode 100644
index 0000000..deab4e6
--- /dev/null
+++ b/trunk/Examples/test-suite/java/using_pointers_runme.java
@@ -0,0 +1,32 @@
+
+import using_pointers.*;
+
+public class using_pointers_runme {
+
+  static {
+    try {
+        System.loadLibrary("using_pointers");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) 
+  {
+    FooBar f = new FooBar();
+    boolean pass = true;
+    try {
+      f.exception_spec(1);
+      pass = false;
+    } catch (RuntimeException e) {
+    }
+    if (!pass) throw new RuntimeException("Missed exception 1");
+    try {
+      f.exception_spec(2);
+      pass = false;
+    } catch (RuntimeException e) {
+    }
+    if (!pass) throw new RuntimeException("Missed exception 2");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/varargs_runme.java b/trunk/Examples/test-suite/java/varargs_runme.java
new file mode 100644
index 0000000..e8b485d
--- /dev/null
+++ b/trunk/Examples/test-suite/java/varargs_runme.java
@@ -0,0 +1,35 @@
+// varargs test
+
+import varargs.*;
+
+public class varargs_runme {
+
+  static {
+    try {
+	System.loadLibrary("varargs");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    if (!varargs.test("Hello").equals("Hello"))
+      throw new RuntimeException("Failed");
+
+    Foo f = new Foo("BuonGiorno", 1);
+    if (!f.getStr().equals("BuonGiorno"))
+      throw new RuntimeException("Failed");
+
+    f = new Foo("Greetings");
+    if (!f.getStr().equals("Greetings"))
+      throw new RuntimeException("Failed");
+        
+    if (!f.test("Hello").equals("Hello"))
+      throw new RuntimeException("Failed");
+
+    if (!Foo.statictest("Grussen", 1).equals("Grussen"))
+      throw new RuntimeException("Failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java/virtual_poly_runme.java b/trunk/Examples/test-suite/java/virtual_poly_runme.java
new file mode 100644
index 0000000..81e2f39
--- /dev/null
+++ b/trunk/Examples/test-suite/java/virtual_poly_runme.java
@@ -0,0 +1,61 @@
+// virtual_poly test
+
+import virtual_poly.*;
+
+public class virtual_poly_runme {
+
+  static {
+    try {
+	System.loadLibrary("virtual_poly");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+
+  public static void main(String argv[]) {
+
+    NDouble d = new NDouble(3.5);
+    NInt i = new NInt(2);
+
+    //
+    // These two natural 'copy' forms fail because no covariant (polymorphic) return types 
+    // are supported in Java. 
+    //
+    // NDouble dc = d.copy();
+    // NInt ic = i.copy();
+
+    //
+    // Unlike C++, we have to downcast instead.
+    //
+    NDouble dc = (NDouble)d.copy();
+    NInt ic = (NInt)i.copy();
+
+    NDouble ddc = NDouble.narrow(dc);
+    NInt dic = NInt.narrow(ic);
+
+    virtual_poly.incr(ic);
+    if ( (i.get() + 1) != ic.get() )
+      throw new RuntimeException("incr test failed");
+
+    //
+    // Checking a pure user downcast
+    //
+    NNumber n1 = d.copy();
+    NNumber n2 = d.nnumber();
+    NDouble dn1 = NDouble.narrow(n1);
+    NDouble dn2 = NDouble.narrow(n2);
+
+    if ( (dn1.get()) != dn2.get() )
+      throw new RuntimeException("copy/narrow test failed");
+
+    //
+    // Checking the ref polymorphic case
+    //
+    NNumber nr = d.ref_this();
+    NDouble dr1 = NDouble.narrow(nr);
+    NDouble dr2 = (NDouble)d.ref_this();
+    if ( dr1.get() != dr2.get() )
+      throw new RuntimeException("copy/narrow test failed");
+  }
+}
diff --git a/trunk/Examples/test-suite/java_constants.i b/trunk/Examples/test-suite/java_constants.i
new file mode 100644
index 0000000..2204853
--- /dev/null
+++ b/trunk/Examples/test-suite/java_constants.i
@@ -0,0 +1,35 @@
+
+// This testcase uses the %javaconst directive to control how constants are initialised
+
+%module java_constants
+
+
+%constant short DIPSTICK=100;
+
+// Set default Java const code generation
+%javaconst(1);
+
+// Modify the code generation to use JNI function call initialisation for some difficult cases
+%javaconst(0) TOM;
+%javaconst(0) ORCHESTRA_STALLS;
+%javaconst(0) PORKY;
+
+%inline %{
+#define CHINA 2*100
+#define TOM 300ULL
+#define ORCHESTRA_STALLS 400LL
+#define JAM_JAR "500"
+#define OXO '6'
+#define PORKY !7
+%}
+
+%constant int BRISTOLS=800;
+
+%javaconstvalue(100L) APPLES;
+%inline %{
+#define APPLES 100LL
+%}
+
+%javaconst(0);
+%constant long long ROSY=900LL;
+
diff --git a/trunk/Examples/test-suite/java_director.i b/trunk/Examples/test-suite/java_director.i
new file mode 100644
index 0000000..04d55e1
--- /dev/null
+++ b/trunk/Examples/test-suite/java_director.i
@@ -0,0 +1,124 @@
+/*
+ * Test Java director typemaps and features
+ */
+
+%warnfilter(SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR); /* Thread/reentrant unsafe wrapping, consider returning by value instead. */
+
+%module(directors="1") java_director
+
+%typemap(javafinalize) SWIGTYPE %{
+  protected void finalize() {
+//    System.out.println("Finalizing " + this);
+    delete();
+  }
+%}
+
+
+%{
+#include <string>
+#include <vector>
+
+class Quux {
+public:
+	Quux() : memb_("default Quux ctor arg") {instances_++; }
+	Quux(const std::string &arg) : memb_(arg) {instances_++;}
+	Quux(const Quux &src) : memb_(src.memb_) {instances_++;}
+	virtual ~Quux() {instances_--;}
+	virtual const std::string &director_method() { return memb_; }
+	const std::string &member() { return memb_; }
+        static int instances() { return instances_; }
+private:
+        static int instances_;
+	std::string memb_;
+};
+
+int Quux::instances_ = 0;
+
+class QuuxContainer {
+protected:
+	typedef std::vector<Quux *> quuxvec_t;
+public:
+	QuuxContainer() : quuxen_()
+	{ }
+	~QuuxContainer() {
+	  for (quuxvec_t::iterator iter = quuxen_.begin(); iter != quuxen_.end(); ++iter) {
+	    delete *iter;
+          }
+	  quuxen_.clear();
+	}
+	void push(Quux *elem) {
+	  quuxen_.push_back(elem);
+	}
+	Quux *get(int idx) {
+	  return quuxen_[idx];
+        }
+	const std::string &invoke(int idx) {
+	  return quuxen_[idx]->director_method();
+        }
+	size_t size() {
+	  return quuxen_.size();
+        }
+private:
+	quuxvec_t quuxen_;
+};
+%}
+
+%include "std_string.i"
+
+%feature("director") Quux;
+SWIG_DIRECTOR_OWNED(Quux)
+
+class Quux {
+public:
+	Quux();
+	Quux(const std::string &arg);
+	Quux(const Quux &src);
+	virtual ~Quux();
+	virtual const std::string &director_method();
+	const std::string &member();
+        static int instances();
+};
+
+class QuuxContainer {
+public:
+	QuuxContainer();
+	~QuuxContainer();
+	void push(Quux *elem);
+	Quux *get(int idx);
+	const std::string &invoke(int idx);
+	size_t size();
+};
+
+
+%feature("director");
+
+%typemap(javacode) hi::Quux1 %{
+  public boolean disconnectMethodCalled = false;
+%}
+
+%typemap(directordisconnect, methodname="disconnect_director") hi::Quux1 %{
+  public void $methodname() {
+    swigCMemOwn = false;
+    $jnicall;
+    // add in a flag to check this method is really called
+    disconnectMethodCalled = true;
+  }
+%}
+
+%inline %{
+
+namespace hi  {
+  struct Quux1 : public Quux {
+    Quux1(const std::string& arg) : Quux(arg) {}
+    virtual int ff(int i = 0) {return i;}  
+  };
+}
+ 
+struct JObjectTest {
+  virtual ~JObjectTest() {}
+  // Test special Java JNI type jobject
+  virtual jobject foo(jobject x) { return x; }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/java_enums.i b/trunk/Examples/test-suite/java_enums.i
new file mode 100644
index 0000000..4d2fe92
--- /dev/null
+++ b/trunk/Examples/test-suite/java_enums.i
@@ -0,0 +1,60 @@
+
+// This testcase uses the %javaconst directive to control how enums are initialised
+
+%module java_enums
+
+%include "enumtypeunsafe.swg"
+
+// Some pragmas to add in an interface to the module class
+%pragma(java) moduleinterfaces="Serializable"
+%pragma(java) moduleimports=%{
+import java.io.*; // For Serializable
+%}
+%pragma(java) modulecode=%{
+  public static final long serialVersionUID = 0x52151001; // Suppress ecj warning
+%}
+
+
+// Set default Java const code generation
+%javaconst(1);
+
+// Change the default generation so that these enums are generated into an interface instead of a class
+%typemap(javaclassmodifiers) enum stuff "public interface"
+
+%inline %{
+enum stuff { FIDDLE = 2*100,  STICKS = 5+8, BONGO, DRUMS };
+%}
+
+// Check that the enum typemaps are working by using a short for the enums instead of int
+%javaconst(0); // will create compile errors in runme file if short typemaps not used 
+
+namespace Space {
+%typemap(jtype) enum nonsense "short"
+%typemap(jstype) enum nonsense "short"
+%typemap(javain) enum nonsense "$javainput"
+%typemap(in) enum nonsense %{ $1 = (enum Space::nonsense)$input; %}
+%typemap(out) enum nonsense %{ $result = (jshort)$1; %}
+%typemap(jni) enum nonsense "jshort"
+%typemap(javaout) enum nonsense {
+    return $jnicall;
+  }
+}
+
+%inline %{
+namespace Space {
+enum nonsense { POPPYCOCK, JUNK };
+nonsense test1(nonsense n) { return n; }
+enum nonsense test2(enum nonsense n) { return n; }
+}
+%}
+
+// Test the %javaconstvalue directive for enums
+%{
+static const int FOUR = 4;
+%}
+
+%javaconst(1);
+%javaconstvalue(4) Quattro;
+%inline %{
+enum Numero { Quattro = FOUR };
+%}
diff --git a/trunk/Examples/test-suite/java_jnitypes.i b/trunk/Examples/test-suite/java_jnitypes.i
new file mode 100644
index 0000000..bc40579
--- /dev/null
+++ b/trunk/Examples/test-suite/java_jnitypes.i
@@ -0,0 +1,29 @@
+
+// This testcase tests the JNI types
+
+%module java_jnitypes
+
+%inline %{
+
+jboolean      jnifunc(jboolean in) { return in; }
+jchar         jnifunc(jchar in) { return in; }
+jbyte         jnifunc(jbyte in) { return in; }
+jshort        jnifunc(jshort in) { return in; }
+jint          jnifunc(jint in) { return in; }
+jlong         jnifunc(jlong in) { return in; }
+jfloat        jnifunc(jfloat in) { return in; }
+jdouble       jnifunc(jdouble in) { return in; }
+jstring       jnifunc(jstring in) { return in; }
+jobject       jnifunc(jobject in) { return in; }
+jbooleanArray jnifunc(jbooleanArray in) { return in; }
+jcharArray    jnifunc(jcharArray in) { return in; }
+jbyteArray    jnifunc(jbyteArray in) { return in; }
+jshortArray   jnifunc(jshortArray in) { return in; }
+jintArray     jnifunc(jintArray in) { return in; }
+jlongArray    jnifunc(jlongArray in) { return in; }
+jfloatArray   jnifunc(jfloatArray in) { return in; }
+jdoubleArray  jnifunc(jdoubleArray in) { return in; }
+jobjectArray  jnifunc(jobjectArray in) { return in; }
+
+%}
+
diff --git a/trunk/Examples/test-suite/java_lib_arrays.i b/trunk/Examples/test-suite/java_lib_arrays.i
new file mode 100644
index 0000000..0551cd1
--- /dev/null
+++ b/trunk/Examples/test-suite/java_lib_arrays.i
@@ -0,0 +1,56 @@
+/* Testcase for the Java array typemaps which are not used by default. */
+%module java_lib_arrays
+
+%include "enumtypeunsafe.swg"
+
+/* Use the Java library typemaps */
+%include "arrays_java.i"
+
+JAVA_ARRAYSOFCLASSES(SimpleStruct)
+%apply ARRAYSOFENUMS[ANY] { finger[ANY] }
+
+%include "arrays.i"
+
+// This will test the %typemap(javacode) in the JAVA_ARRAYSOFCLASSES works with C structs amongst other things
+JAVA_ARRAYSOFCLASSES(struct AnotherStruct)
+%inline %{
+struct AnotherStruct {
+	SimpleStruct  simple;
+};
+double extract(struct AnotherStruct as[], int index) {
+  return as[index].simple.double_field;
+}
+double extract2(struct AnotherStruct as[5], int index) {
+  return as[index].simple.double_field;
+}
+%}
+
+// Test %apply to pointers
+JAVA_ARRAYSOFCLASSES(struct YetAnotherStruct)
+%apply struct YetAnotherStruct[] { struct YetAnotherStruct *yas }
+//%apply struct YetAnotherStruct[] { struct YetAnotherStruct * } // Note: Does not work unless this is put after the YetAnotherStruct definition
+%inline %{
+struct YetAnotherStruct {
+	SimpleStruct  simple;
+};
+double extract_ptr(struct YetAnotherStruct *yas, int index) {
+  return yas[index].simple.double_field;
+}
+void modifyYAS(struct YetAnotherStruct yas[], int size) {
+  int i;
+  for (i=0; i<size; ++i) {
+    SimpleStruct ss;
+    ss.double_field = yas[i].simple.double_field * 10.0;
+    yas[i].simple = ss;
+  }
+}
+%}
+
+%apply ARRAYSOFENUMS[ANY] { toe[ANY] }
+%apply ARRAYSOFENUMS[] { toe[] }
+%apply ARRAYSOFENUMS[] { toe* }
+%inline %{
+typedef enum { Big, Little } toe;
+void toestest(toe *t, toe tt[], toe ttt[2]) {}
+%}
+
diff --git a/trunk/Examples/test-suite/java_lib_arrays_dimensionless.i b/trunk/Examples/test-suite/java_lib_arrays_dimensionless.i
new file mode 100644
index 0000000..ec2676f
--- /dev/null
+++ b/trunk/Examples/test-suite/java_lib_arrays_dimensionless.i
@@ -0,0 +1,26 @@
+%module java_lib_arrays_dimensionless
+
+%include "arrays_java.i"
+
+// Can't wrap dimensionless arrays, so we use the old pointer approach
+%apply SWIGTYPE* { int globalints[], int constglobalints[], int Bar::ints[] }
+
+// Test %apply for arrays in arrays_java.i library file
+%apply bool []                  { bool *array }
+%apply char []                  { char *array }
+%apply signed char []           { signed char *array }
+%apply unsigned char []         { unsigned char *array }
+%apply short []                 { short *array }
+%apply unsigned short []        { unsigned short *array }
+%apply int []                   { int *array }
+%apply unsigned int []          { unsigned int *array }
+%apply long []                  { long *array }
+%apply unsigned long []         { unsigned long *array }
+%apply long []                  { long *array }
+%apply unsigned long long []    { unsigned long long *array }
+%apply float []                 { float *array }
+%apply double []                { double *array }
+
+%include "arrays_dimensionless.i"
+
+
diff --git a/trunk/Examples/test-suite/java_lib_various.i b/trunk/Examples/test-suite/java_lib_various.i
new file mode 100644
index 0000000..716ae91
--- /dev/null
+++ b/trunk/Examples/test-suite/java_lib_various.i
@@ -0,0 +1,51 @@
+/* Java various.i library tests */
+%module java_lib_various
+
+%include "various.i"
+
+%apply char **STRING_ARRAY { char **received };
+%apply char **STRING_ARRAY { char **get_names };
+%apply char **STRING_ARRAY { char **languages };
+%apply char *BYTE { char *chars };
+%apply char **STRING_OUT { char **string_ptr };
+%typemap(freearg) char **languages "" // don't delete memory when setting global variable
+
+%{
+char *langs[] = { (char *)"Hungarian", (char *)"Afrikaans", (char *)"Norwegian", NULL };
+%}
+
+%inline %{
+char **languages = &langs[0];
+%}
+
+%inline %{
+
+int check_animals(char **received) {
+    const char *expected[] = {"Cat","Dog","Cow","Goat", 0};
+    int strings_match = 1;
+    int i=0;
+    while (expected[i]) {
+        if (strcmp(received[i], expected[i]) != 0)
+            strings_match = 0;
+        i++;
+    }
+    return strings_match;
+}
+
+char **get_names() {
+    static char *values[] = { (char *)"Dave", (char *)"Mike", (char *)"Susan", (char *)"John", (char *)"Michelle", NULL};
+    return &values[0];
+}
+
+void charout(char *chars) {
+    if(chars != NULL)
+        sprintf(chars, "by jove");
+}
+
+void char_ptr_ptr_out(char **string_ptr) {
+    static char ret[] = "returned string";
+    *string_ptr = ret;
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/java_pgcpp.i b/trunk/Examples/test-suite/java_pgcpp.i
new file mode 100644
index 0000000..6a50ffe
--- /dev/null
+++ b/trunk/Examples/test-suite/java_pgcpp.i
@@ -0,0 +1,56 @@
+// Test the premature garbage collection prevention parameter (pgcpp) for the different ways of passing objects
+
+%module java_pgcpp
+
+%pragma(java) jniclassclassmodifiers="public class"
+
+%typemap(javacode) Space::Classic %{
+  public long getCPtrValue() {
+    return this.swigCPtr;
+  }
+%}
+
+// Default pointer to pointer typemaps do not use proxy class, so make sure that the pgcpp is generated for these typemaps
+%typemap(jni) Space::Classic ** "jlong"
+%typemap(jtype) Space::Classic ** "long"
+%typemap(jstype) Space::Classic ** " Classic "
+%typemap(javain) Space::Classic ** "Classic.getCPtr($javainput)"
+
+// Default typemaps for pass by value, ref, pointer and pointer reference should use pgcpp
+
+%inline %{
+namespace Space {
+  struct Classic {
+    Classic() {}
+    Classic(Classic c1, Classic& c2, Classic* c3, Classic*& c4, Classic** c5) {}
+    Classic(const Classic c1, const Classic& c2, const Classic* c3, const Classic*& c4, const Classic** c5, bool b) {}
+
+    void method(Classic c1, Classic& c2, Classic* c3, Classic*& c4, Classic** c5) {}
+    void methodconst(const Classic c1, const Classic& c2, const Classic* c3, const Classic*& c4, const Classic** c5) {}
+  };
+
+  void function(Classic c1, Classic& c2, Classic* c3, Classic*& c4, Classic** c5) {}
+  void functionconst(const Classic c1, const Classic& c2, const Classic* c3, const Classic*& c4, const Classic** c5) {}
+}
+%}
+
+
+%typemap(jtype)  Klassic *k1 "/*a*/ long   /*b*/ /*c*/"
+%typemap(jstype) Klassic *k1 "/*a*/ Classic/*b*/ /*c*/"
+
+%typemap(jtype)  Klassic *k2 "/*d*/ long"
+%typemap(jstype) Klassic *k2 "/*d*/ Classic"
+
+%typemap(jtype)  Klassic *k3 "long/*e*/ "
+%typemap(jstype) Klassic *k3 "Classic/*e*/ "
+
+%typemap(javain) Klassic * "Classic.getCPtr($javainput)"
+
+%{
+typedef Space::Classic Klassic;
+%}
+
+%inline %{
+  void comment_in_typemaps(Klassic *k1, Klassic *k2, Klassic *k3) {}
+%}
+
diff --git a/trunk/Examples/test-suite/java_pragmas.i b/trunk/Examples/test-suite/java_pragmas.i
new file mode 100644
index 0000000..b1fab27
--- /dev/null
+++ b/trunk/Examples/test-suite/java_pragmas.i
@@ -0,0 +1,50 @@
+
+// Test case uses all the Java pragmas which are for tailoring the generated JNI class and Java module class.
+
+%module java_pragmas
+
+%pragma(java) jniclassimports=%{
+import java.lang.*; // For Exception
+%}
+
+%pragma(java) jniclassclassmodifiers="public class"
+%pragma(java) jniclassbase="Exception"
+%pragma(java) jniclassinterfaces="Cloneable"
+
+%pragma(java) jniclasscode=%{
+  // jniclasscode pragma code: Static block so that the JNI class loads the C++ DLL/shared object when the class is loaded
+  static {
+    try {
+	  System.loadLibrary("java_pragmas");
+    } catch (UnsatisfiedLinkError e) {
+      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
+      System.exit(1);
+    }
+  }
+  public static final long serialVersionUID = 0x52151000; // Suppress ecj warning
+%}
+
+
+%pragma(java) moduleimports=%{
+import java.io.*; // For Serializable
+%}
+
+%pragma(java) moduleclassmodifiers="public final class"
+%pragma(java) modulebase="Object"
+%pragma(java) moduleinterfaces="Serializable"
+
+%pragma(java) modulecode=%{
+  public static final long serialVersionUID = 0x52151001; // Suppress ecj warning
+  public static void added_function(String s) {
+    // Added function
+  }
+%}
+
+
+%inline %{
+int *get_int_pointer() {
+    static int number = 10;
+    return &number;
+}
+%}
+
diff --git a/trunk/Examples/test-suite/java_prepost.i b/trunk/Examples/test-suite/java_prepost.i
new file mode 100644
index 0000000..3e38392
--- /dev/null
+++ b/trunk/Examples/test-suite/java_prepost.i
@@ -0,0 +1,91 @@
+%module java_prepost
+
+// Test the pre, post attributes for javain typemaps
+
+%include "std_vector.i"
+
+%define VECTOR_DOUBLE_JAVAIN_POST
+"      int count$javainput = (int)d$javainput.size();
+      $javainput = new double[count$javainput];
+      for (int i=0; i<count$javainput; ++i) {
+        $javainput[i] = d$javainput.get(i);
+      }"
+%enddef
+
+// pre and post in javain typemaps
+//%typemap(jtype, nopgcpp=1) std::vector<double> &v "long" // could suppress pgcpp instead of using pgcppname, but not recommended
+%typemap(jstype) std::vector<double> &v "double[]"
+%typemap(javain, pre="    DoubleVector d$javainput = new DoubleVector();", post=VECTOR_DOUBLE_JAVAIN_POST, pgcppname="d$javainput") std::vector<double> &v
+  "$javaclassname.getCPtr(d$javainput)"
+
+%apply std::vector<double> & v { std::vector<double> & v2 }
+
+// pre only in javain typemap
+//%typemap(jtype, nopgcpp=1) std::vector<double> &vpre "long" // could suppress pgcpp instead of using pgcppname, but not recommended
+%typemap(jstype) std::vector<double> &vpre "double[]"
+%typemap(javain, pre="    DoubleVector d$javainput = new DoubleVector();\n    for (int i=0; i<$javainput.length; ++i) {\n      double d = $javainput[i];\n      d$javainput.add(d);\n    }", pgcppname="d$javainput") std::vector<double> &vpre
+  "$javaclassname.getCPtr(d$javainput)"
+
+// post only in javain typemap
+%typemap(javain, post="      int size = (int)$javainput.size();\n      for (int i=0; i<size; ++i) {\n        $javainput.set(i, $javainput.get(i)/100);\n      }") std::vector<double> &vpost
+  "$javaclassname.getCPtr($javainput)"
+
+%inline %{
+bool globalfunction(std::vector<double> & v) {
+  v.push_back(0.0);
+  v.push_back(1.1);
+  v.push_back(2.2);
+  return true;
+}
+struct PrePostTest {
+  PrePostTest() {
+  }
+  PrePostTest(std::vector<double> & v) {
+    v.push_back(3.3);
+    v.push_back(4.4);
+  }
+  bool method(std::vector<double> & v) {
+    v.push_back(5.5);
+    v.push_back(6.6);
+    return true;
+  }
+  static bool staticmethod(std::vector<double> & v) {
+    v.push_back(7.7);
+    v.push_back(8.8);
+    return true;
+  }
+};
+
+// Check pre and post only typemaps and that they coexist okay and that the generated code line spacing looks okay
+bool globalfunction2(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+  return true;
+}
+struct PrePost2 {
+  PrePost2() {
+  }
+  PrePost2(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+  }
+  bool method(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+    return true;
+  }
+  static bool staticmethod(std::vector<double> & v, std::vector<double> &v2, std::vector<double> & vpre, std::vector<double> & vpost) {
+    return true;
+  }
+};
+%}
+
+%template(DoubleVector) std::vector<double>;
+
+
+// Check pre post constructor helper deals with checked exceptions, InstantiationException is just a random checked exception
+%typemap(javain, pre="    if ($javainput == null)\n      throw new InstantiationException(\"empty value!!\");", throws="InstantiationException") PrePostTest *
+  "$javaclassname.getCPtr($javainput)"
+
+%inline %{
+struct PrePostThrows {
+  PrePostThrows(PrePostTest *ppt) {
+  }
+};
+%}
+
+
diff --git a/trunk/Examples/test-suite/java_throws.i b/trunk/Examples/test-suite/java_throws.i
new file mode 100644
index 0000000..3aa11de
--- /dev/null
+++ b/trunk/Examples/test-suite/java_throws.i
@@ -0,0 +1,145 @@
+// Test to check the exception classes in the throws attribute of the typemaps and except feature is working
+
+%module java_throws
+
+// Exceptions are chosen at random but are ones which have to have a try catch block to compile
+%typemap(in, throws="	 ClassNotFoundException") int num { 
+    $1 = (int)$input;
+}
+%typemap(freearg, throws="InstantiationException  ") int num "/*not written*/"
+%typemap(argout, throws="CloneNotSupportedException		") int num "/*not written*/"
+%typemap(check, throws="NoSuchFieldException") int num {
+    if ($input == 10) {
+        jenv->ExceptionClear();
+        jclass excep = jenv->FindClass("java/lang/NoSuchFieldException");
+        if (excep)
+            jenv->ThrowNew(excep, "Value of 10 not acceptable");
+        return $null;
+    }
+}
+
+// Duplicate exceptions should be removed from the generated throws clause
+%typemap(out, throws="IllegalAccessException, NoSuchFieldException,   CloneNotSupportedException    ") short { 
+    $result = (jshort)$1; 
+}
+
+%inline %{
+short full_of_exceptions(int num) {
+    return 0;
+}
+%}
+
+
+%typemap(throws, throws="IllegalAccessException") int {
+    (void)$1;
+    jclass excep = jenv->FindClass("java/lang/IllegalAccessException");
+    if (excep) {
+        jenv->ThrowNew(excep, "Test exception");
+    }
+    return $null;
+}
+%inline %{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+void throw_spec_function(int value) throw (int) { throw (int)0; }
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+
+// Check newfree typemap throws attribute
+%newobject makeTestClass;
+%typemap(newfree, throws="NoSuchMethodException") TestClass* "/*not written*/"
+%inline %{
+class TestClass {
+    int x;
+public:
+    TestClass(int xx) : x(xx) {}
+};
+TestClass* makeTestClass() { return new TestClass(1000); }
+%}
+
+
+// javain typemap throws attribute
+// Will only compile if the fileFunction has a java.io.IOException throws clause as getCanonicalPath() throws this exception
+%typemap(jstype) char* someFileArgument "java.io.File"
+%typemap(javain, throws="java.io.IOException") char* someFileArgument "$javainput.getCanonicalPath()"
+
+%inline %{
+void fileFunction(char* someFileArgument) {}
+%}
+
+
+// javout typemap throws attribute
+%typemap(javaout, throws="java.io.IOException") int {
+    int returnValue=$jnicall;
+    if (returnValue==0) throw new java.io.IOException("some IOException");
+    return returnValue;
+  }
+
+%inline %{
+int ioTest() { return 0; }
+%}
+
+// except feature (%javaexception) specifying a checked exception class for the throws clause
+%typemap(javabase) MyException "Throwable";
+%typemap(javacode) MyException %{
+  public static final long serialVersionUID = 0x52151000; // Suppress ecj warning
+%}
+%inline %{
+    struct MyException {
+        MyException(const char *msg) {}
+    };
+%}
+
+%define JAVAEXCEPTION(METHOD)
+%javaexception("MyException") METHOD %{
+try {
+    $action
+} catch (MyException) {
+    jclass excep = jenv->FindClass("java_throws/MyException");
+    if (excep)
+        jenv->ThrowNew(excep, "exception message");
+    return $null;
+}
+%}
+%enddef
+
+JAVAEXCEPTION(FeatureTest::FeatureTest)
+JAVAEXCEPTION(FeatureTest::method)
+JAVAEXCEPTION(FeatureTest::staticMethod)
+
+%inline %{
+    struct FeatureTest {
+        static void staticMethod() {
+            throw MyException("no message");
+        }
+        void method() {
+            throw MyException("no message");
+        }
+    };
+%}
+
+// Mixing except feature and typemaps when both generate a class for the throws clause
+%typemap(in, throws="ClassNotFoundException") int both { 
+    $1 = (int)$input;
+}
+%javaexception("MyException , NoSuchFieldException") globalFunction %{
+try {
+    $action
+} catch (MyException) {
+    jclass excep = jenv->FindClass("java_throws/MyException");
+    if (excep)
+        jenv->ThrowNew(excep, "exception message");
+    return $null;
+}
+%}
+
+%inline %{
+    void globalFunction(int both) {
+        throw MyException("no message");
+    }
+%}
+
diff --git a/trunk/Examples/test-suite/java_typemaps_proxy.i b/trunk/Examples/test-suite/java_typemaps_proxy.i
new file mode 100644
index 0000000..e315a36
--- /dev/null
+++ b/trunk/Examples/test-suite/java_typemaps_proxy.i
@@ -0,0 +1,129 @@
+/* Tests the Java specific directives */
+
+%module java_typemaps_proxy
+
+
+%typemap(javaimports) SWIGTYPE "import java.math.*;";
+%typemap(javacode) NS::Farewell %{
+  public void saybye(BigDecimal num_times) {
+    // BigDecimal requires the java.math library
+  }
+%}
+%typemap(javaclassmodifiers) NS::Farewell "public final class";
+
+%typemap(javaimports) NS::Greeting %{
+import java.util.*; // for EventListener
+import java.lang.*; // for Exception
+%};
+
+%typemap(javabase) NS::Greeting "Exception";
+%typemap(javainterfaces) NS::Greeting "EventListener";
+%typemap(javacode) NS::Greeting %{
+  public static final long serialVersionUID = 0x52151000; // Suppress ecj warning
+  // Pure Java code generated using %typemap(javacode) 
+  public void sayhello() {
+    hello();
+  }
+
+  public static void cheerio(EventListener e) {
+  }
+%}
+
+// Create a new getCPtr() function which takes Java null and is public
+%typemap(javabody) NS::Greeting %{
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  protected $javaclassname(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  public static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+// Make the pointer constructor public
+%typemap(javabody) NS::Farewell %{
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  public $javaclassname(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+// get rid of the finalize method for NS::Farewell
+%typemap(javafinalize) NS::Farewell "";
+
+// Test typemaps are being found for templated classes
+%typemap(javacode) NS::Adieu<int**> %{
+  public static void adieu() {
+  }
+%}
+
+// Check the %javamethodmodifiers feature
+%javamethodmodifiers NS::Farewell::methodmodifiertest() "private";
+
+%inline %{
+namespace NS {
+    class Greeting {
+    public:
+        void hello() {}
+        static void ciao(Greeting* g) {}
+    };
+    class Farewell {
+    public:
+        void methodmodifiertest() {}
+    };
+    template<class T> class Adieu {};
+}
+%}
+
+%template(AdieuIntPtrPtr) NS::Adieu<int**>;
+
+// Check the premature garbage collection prevention parameter can be turned off
+%typemap(jtype, nopgcpp="1") Without * "long";
+%pragma(java) jniclassclassmodifiers="public class"
+
+%inline %{
+struct Without {
+  Without(Without *p) : var(0) {}
+  static void static_method(Without *p) {}
+  void member_method(Without *p) {}
+  Without *var;
+};
+Without *global_without = 0;
+void global_method_without(Without *p) {}
+struct With {
+  With(With *p) {}
+  static void static_method(With *p) {}
+  void member_method(With *p) {}
+};
+void global_method_with(With *p) {}
+%}
+
+%typemap(jtype, nopgcpp="1") const ConstWithout * "long";
+%inline %{
+class ConstWithout {
+public:
+  ConstWithout(const ConstWithout *p) : const_var(0), var_const(0) {}
+  static void static_method(const ConstWithout *p) {}
+  void member_method(const ConstWithout *p) {}
+  void const_member_method(const ConstWithout *p) const {}
+  const ConstWithout * const_var;
+  const ConstWithout * const var_const;
+private:
+  ConstWithout& operator=(const ConstWithout &);
+};
+const ConstWithout * global_constwithout = 0;
+void global_method_constwithout(const ConstWithout *p) {}
+%}
+
+
diff --git a/trunk/Examples/test-suite/java_typemaps_typewrapper.i b/trunk/Examples/test-suite/java_typemaps_typewrapper.i
new file mode 100644
index 0000000..8c772ae
--- /dev/null
+++ b/trunk/Examples/test-suite/java_typemaps_typewrapper.i
@@ -0,0 +1,65 @@
+/* Contrived example to test the Java specific directives on the type wrapper classes */
+
+%module java_typemaps_typewrapper
+
+
+%typemap(javaimports) SWIGTYPE * "import java.math.*;";
+%typemap(javacode) Farewell * %{
+  public static $javaclassname CreateNullPointer() {
+    return new $javaclassname();
+  }
+  public void saybye(BigDecimal num_times) {
+    // BigDecimal requires the java.math library
+  }
+%}
+%typemap(javaclassmodifiers) Farewell * "public final class";
+
+%typemap(javaimports) Greeting * %{
+import java.util.*; // for EventListener
+import java.lang.*; // for Exception
+%};
+
+%typemap(javabase) Greeting * "Exception";
+%typemap(javainterfaces) Greeting * "EventListener";
+%typemap(javacode) Greeting * %{
+  public static final long serialVersionUID = 0x52151000; // Suppress ecj warning
+  // Pure Java code generated using %typemap(javacode) 
+  public static $javaclassname CreateNullPointer() {
+    return new $javaclassname();
+  }
+
+  public void sayhello() {
+    $javaclassname.cheerio(new $javaclassname());
+  }
+
+  public static void cheerio(EventListener e) {
+  }
+%}
+
+// Create a new getCPtr() function which takes Java null and is public
+// Make the pointer constructor public
+%typemap(javabody) Farewell * %{
+  private long swigCPtr;
+
+  public $javaclassname(long cPtr, boolean bFutureUse) {
+    swigCPtr = cPtr;
+  }
+
+  protected $javaclassname() {
+    swigCPtr = 0;
+  }
+
+  public static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+%{
+class Greeting {};
+class Farewell {};
+%}
+
+%inline %{
+    Greeting* solong(Farewell* f) { return NULL; }
+%}
+
diff --git a/trunk/Examples/test-suite/keyword_rename.i b/trunk/Examples/test-suite/keyword_rename.i
new file mode 100644
index 0000000..da93288
--- /dev/null
+++ b/trunk/Examples/test-suite/keyword_rename.i
@@ -0,0 +1,32 @@
+/*
+ * Test reserved keyword renaming
+ */
+
+%module keyword_rename
+
+#pragma SWIG nowarn=SWIGWARN_PARSE_KEYWORD
+
+%inline %{
+
+#define KW(x, y) int x (int y) { return y; }
+
+/* Python keywords */
+KW(in, except)
+KW(except, in)
+KW(pass, in)
+
+/* Perl keywords */
+KW(tie, die)
+KW(use, next)
+
+/* Java keywords */
+KW(implements, native)
+KW(synchronized, final)
+
+/* C# Keywords */
+KW(string, out)
+struct sealed {int i;};
+
+%}
+
+
diff --git a/trunk/Examples/test-suite/kind.i b/trunk/Examples/test-suite/kind.i
new file mode 100644
index 0000000..15727fd
--- /dev/null
+++ b/trunk/Examples/test-suite/kind.i
@@ -0,0 +1,34 @@
+/* 
+ * This interface file tests whether the language modules handle the kind when declared 
+ * with the function/member name, especially when used with proxy classes.
+*/
+
+%module kind
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo;  /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) bar;  /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) uni;  /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) test; /* Ruby, wrong class name */
+
+%inline %{
+
+class foo {};
+struct bar {};
+union uni {};
+
+struct test {
+  void foofn(class foo myfoo1, foo myfoo2, class foo* myfoo3, foo* myfoo4, class foo& myfoo5, foo& myfoo6) {}
+  void barfn(struct bar mybar1, bar mybar2, struct bar* mybar3, bar* mybar4, struct bar& mybar5, bar& mybar6) {}
+  void unifn(union uni myuni1, uni myuni2, union uni* myuni3, uni* myuni4, union myuni& myuni5, myuni& myuni6) {}
+
+  class foo myFooMember;
+  struct bar myBarMember;
+  union uni myUniMember;
+
+  class foo* mypFooMember;
+  struct bar* mypBarMember;
+  union uni* mypUniMember;
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/langobj.i b/trunk/Examples/test-suite/langobj.i
new file mode 100644
index 0000000..9afd2d4
--- /dev/null
+++ b/trunk/Examples/test-suite/langobj.i
@@ -0,0 +1,41 @@
+%module langobj
+
+
+#ifndef SWIG_Object
+#define SWIG_Object void *
+#endif
+
+
+%inline %{
+
+#ifdef SWIGTCL
+#define SWIG_Object Tcl_Obj *
+#endif
+
+#ifdef SWIGPYTHON
+#define SWIG_Object PyObject *
+#endif
+
+#ifdef SWIGRUBY
+#define SWIG_Object VALUE
+#endif
+
+#ifndef SWIG_Object
+#define SWIG_Object void *
+#endif
+
+%}
+
+
+%inline {
+
+  SWIG_Object identity(SWIG_Object x) {
+#ifdef SWIGPYTHON
+    Py_XINCREF(x);
+#endif
+    return x;    
+  }
+
+}
+
+  
diff --git a/trunk/Examples/test-suite/lextype.i b/trunk/Examples/test-suite/lextype.i
new file mode 100644
index 0000000..0c0ef66
--- /dev/null
+++ b/trunk/Examples/test-suite/lextype.i
@@ -0,0 +1,54 @@
+/*
+This module tests whether SWIG sets the '$lextype' variable
+correctly.  This variable maintains the literal base name of the
+type in the wrapper code - it's therefore usually the same
+as '$basetype', but NOT ALWAYS.
+
+In the example below, the typemap definitions are written
+for any type of 'Animal', but are parameterized through
+preprocessor definitions.  So when wrapping functions which
+explicitly reference Giraffes,  the wrapper code can 
+behave appropriately for that particular species.
+
+For this to work correctly however, it is critical that
+there is a variable which strictly preserves the name
+of the type.  '$basetype' doesn't currently do this - 
+it sometimes contains 'Giraffe' and sometimes (specifically
+the case of arrays) contains 'Animal'.  Since existing
+code may rely on that behaviour, we create a new variable
+'$lextype' which does what we need.
+
+There is no need for any runtime test here, since if the
+code is not functioning properly it will fail to compile.
+*/
+
+%module lextype
+%{
+#include <stdlib.h>
+%}
+
+%typemap(in) Animal ()
+{
+    void *space_needed = malloc(HEIGHT_$1_lextype * WIDTH_$1_lextype);
+    $1 = space_needed;
+}
+
+%typemap(in) Animal[2] ()
+{
+    void *space_needed = malloc(2 * HEIGHT_$1_lextype * WIDTH_$1_lextype);
+    $1 = space_needed;
+}
+
+%inline %{
+
+#define HEIGHT_Giraffe 100
+#define WIDTH_Giraffe 5
+
+typedef void * Animal;
+typedef Animal Giraffe;
+
+void eat(Giraffe g) {}
+void drink(Giraffe *g) {}
+Giraffe mate(Giraffe g[2]) { return g[0]; }
+
+%}
diff --git a/trunk/Examples/test-suite/li_attribute.i b/trunk/Examples/test-suite/li_attribute.i
new file mode 100644
index 0000000..5b4379e
--- /dev/null
+++ b/trunk/Examples/test-suite/li_attribute.i
@@ -0,0 +1,108 @@
+%module li_attribute
+
+%include <exception.i>
+
+//#define SWIG_ATTRIBUTE_TEMPLATE
+%include <attribute.i>
+
+%{
+// forward reference needed if using SWIG_ATTRIBUTE_TEMPLATE
+struct A;
+struct MyFoo; // %attribute2 does not work with templates
+%}
+
+%attribute(A, int, a, get_a, set_a);
+%attributeref(A, int, b);
+
+%attributeref(Param<int>, int, value);
+
+
+%attribute(A, int, c, get_c);  /* read-only */
+%attributeref(A, int, d, b);   /* renames accessor method 'b' to attribute name 'd' */
+
+%attributeref(B, A*, a)
+
+%inline
+{
+  struct A
+  {
+    A(int a, int b, int c) : _a(a), _b(b), _c(c)
+    {
+    }
+    
+    int get_a() const 
+    {
+      return _a;
+    }
+    
+    void set_a(int aa) 
+    {
+      _a = aa;
+    }
+
+    /* only one ref method */
+    int& b() 
+    {
+      return _b;
+    }    
+
+    int get_c() const 
+    {
+      return _c;
+    }
+  private:
+    int _a;
+    int _b;
+    int _c;
+  };
+
+  template <class C>
+  struct Param 
+  {
+    Param(C v) : _v(v)
+    {
+    }
+
+    const int& value() const 
+    {
+      return _v;
+    }
+    
+    int& value() 
+    {
+      return _v;
+    }    
+  private:
+    C _v;
+  }; 
+  
+  
+  struct B {
+    B(A *a) : mA(a)
+    {
+    }
+    
+    A*& a() { return mA; }
+    
+  protected:
+    A*  mA;
+  };
+ 
+}
+
+%template(Param_i) Param<int>;
+
+
+%attribute2(MyClass, MyFoo, Foo, GetFoo, SetFoo);
+%inline %{
+  struct MyFoo { 
+    int x;
+  };
+  class MyClass {
+    MyFoo foo;
+  public:
+    MyFoo& GetFoo() { return foo; }
+    void SetFoo(const MyFoo& other) { foo = other; }
+  };
+%} 
+
diff --git a/trunk/Examples/test-suite/li_boost_shared_ptr.i b/trunk/Examples/test-suite/li_boost_shared_ptr.i
new file mode 100644
index 0000000..a622541
--- /dev/null
+++ b/trunk/Examples/test-suite/li_boost_shared_ptr.i
@@ -0,0 +1,384 @@
+// This tests shared_ptr is working okay. It also checks that there are no memory leaks in the
+// class that shared_ptr is pointing via a counting mechanism in the constructors and destructor of Klass.
+// In order to test that there are no leaks of the shared_ptr class itself (as it is created on the heap)
+// the runtime tests can be run for a long time to monitor memory leaks using memory monitor tools 
+// like 'top'. There is a wrapper for shared_ptr in shared_ptr_wrapper.h which enables one to
+// count the instances of shared_ptr. Uncomment the SHARED_PTR_WRAPPER macro to turn this on.
+//
+// Also note the debug_shared flag  which can be set from the target language.
+
+%module li_boost_shared_ptr
+
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);
+
+%inline %{
+#include "boost/shared_ptr.hpp"
+#include "swig_examples_lock.h"
+
+// Uncomment macro below to turn on shared_ptr memory leak checking as described above
+//#define SHARED_PTR_WRAPPER
+
+#ifdef SHARED_PTR_WRAPPER
+# include "shared_ptr_wrapper.h"
+#endif
+%}
+
+%{
+#ifndef SHARED_PTR_WRAPPER
+# define SwigBoost boost
+#endif
+%}
+
+%include "std_string.i"
+#ifndef SHARED_PTR_WRAPPER
+# define SWIG_SHARED_PTR_NAMESPACE SwigBoost
+#endif
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON)
+#define SHARED_PTR_WRAPPERS_IMPLEMENTED
+#endif
+
+#if defined(SHARED_PTR_WRAPPERS_IMPLEMENTED)
+
+%include <boost_shared_ptr.i>
+SWIG_SHARED_PTR(Klass, Space::Klass)
+SWIG_SHARED_PTR_DERIVED(KlassDerived, Space::Klass, Space::KlassDerived)
+
+#endif
+
+// TODO:
+// const shared_ptr
+// std::vector
+// Add in generic %extend for the Upcast function for derived classes
+// Remove proxy upcast method - implement %feature("shadow") ??? which replaces the proxy method
+
+%exception {
+  if (debug_shared) {
+    cout << "++++++" << endl;
+    cout << "calling $name" << endl;
+  }
+  $action
+  if (debug_shared) {
+    cout << "------" << endl;
+  }
+}
+
+%ignore IgnoredMultipleInheritBase;
+%ignore Space::Klass::operator=;
+%newobject pointerownertest();
+%newobject smartpointerpointerownertest();
+
+%inline %{
+#include <iostream>
+using namespace std;
+
+static bool debug_shared = false;
+
+namespace Space {
+
+struct Klass {
+  Klass() : value("EMPTY") { if (debug_shared) cout << "Klass() [" << value << "]" << endl; increment(); }
+
+  Klass(const std::string &val) : value(val) { if (debug_shared) cout << "Klass(string) [" << value << "]" << endl; increment(); }
+
+  virtual ~Klass() { if (debug_shared) cout << "~Klass() [" << value << "]" << endl; decrement(); }
+  virtual std::string getValue() const { return value; }
+  void append(const std::string &s) { value += s; }
+  Klass(const Klass &other) : value(other.value) { if (debug_shared) cout << "Klass(const Klass&) [" << value << "]" << endl; increment(); }
+
+  Klass &operator=(const Klass &other) { value = other.value; return *this; }
+  static int getTotal_count() { return total_count; }
+
+private:
+  // lock increment and decrement as a destructor could be called at the same time as a 
+  // new object is being created - C# / Java, at least, have finalizers run in a separate thread
+  static SwigExamples::CriticalSection critical_section;
+  static void increment() { SwigExamples::Lock lock(critical_section); total_count++; if (debug_shared) cout << "      ++xxxxx Klass::increment tot: " << total_count << endl;}
+  static void decrement() { SwigExamples::Lock lock(critical_section); total_count--; if (debug_shared) cout << "      --xxxxx Klass::decrement tot: " << total_count << endl;}
+  static int total_count;
+  std::string value;
+  int array[1024];
+};
+SwigExamples::CriticalSection Space::Klass::critical_section;
+
+struct IgnoredMultipleInheritBase { virtual ~IgnoredMultipleInheritBase() {} double d; double e;};
+
+// For most compilers, this use of multiple inheritance results in different derived and base class 
+// pointer values ... for some more challenging tests :)
+struct KlassDerived : IgnoredMultipleInheritBase, Klass {
+  KlassDerived() : Klass() {}
+  KlassDerived(const std::string &val) : Klass(val) {}
+  KlassDerived(const KlassDerived &other) : Klass(other) {}
+  virtual ~KlassDerived() {}
+  virtual std::string getValue() const { return Klass::getValue() + "-Derived"; }
+};
+KlassDerived* derivedpointertest(KlassDerived* kd) {
+  if (kd)
+    kd->append(" derivedpointertest");
+  return kd;
+}
+KlassDerived& derivedreftest(KlassDerived& kd) {
+  kd.append(" derivedreftest");
+  return kd;
+}
+SwigBoost::shared_ptr<KlassDerived> derivedsmartptrtest(SwigBoost::shared_ptr<KlassDerived> kd) {
+  if (kd)
+    kd->append(" derivedsmartptrtest");
+  return kd;
+}
+SwigBoost::shared_ptr<KlassDerived>* derivedsmartptrpointertest(SwigBoost::shared_ptr<KlassDerived>* kd) {
+  if (kd && *kd)
+    (*kd)->append(" derivedsmartptrpointertest");
+  return kd;
+}
+SwigBoost::shared_ptr<KlassDerived>* derivedsmartptrreftest(SwigBoost::shared_ptr<KlassDerived>* kd) {
+  if (kd && *kd)
+    (*kd)->append(" derivedsmartptrreftest");
+  return kd;
+}
+SwigBoost::shared_ptr<KlassDerived>*& derivedsmartptrpointerreftest(SwigBoost::shared_ptr<KlassDerived>*& kd) {
+  if (kd && *kd)
+    (*kd)->append(" derivedsmartptrpointerreftest");
+  return kd;
+}
+
+
+
+
+
+SwigBoost::shared_ptr<Klass> factorycreate() {
+  return SwigBoost::shared_ptr<Klass>(new Klass("factorycreate"));
+}
+// smart pointer
+SwigBoost::shared_ptr<Klass> smartpointertest(SwigBoost::shared_ptr<Klass> k) {
+  if (k)
+    k->append(" smartpointertest");
+  return SwigBoost::shared_ptr<Klass>(k);
+}
+SwigBoost::shared_ptr<Klass>* smartpointerpointertest(SwigBoost::shared_ptr<Klass>* k) {
+  if (k && *k)
+    (*k)->append(" smartpointerpointertest");
+  return k;
+}
+SwigBoost::shared_ptr<Klass>& smartpointerreftest(SwigBoost::shared_ptr<Klass>& k) {
+  if (k)
+    k->append(" smartpointerreftest");
+  return k;
+}
+SwigBoost::shared_ptr<Klass>*& smartpointerpointerreftest(SwigBoost::shared_ptr<Klass>*& k) {
+  if (k && *k)
+    (*k)->append(" smartpointerpointerreftest");
+  return k;
+}
+// const
+SwigBoost::shared_ptr<const Klass> constsmartpointertest(SwigBoost::shared_ptr<const Klass> k) {
+  return SwigBoost::shared_ptr<const Klass>(k);
+}
+SwigBoost::shared_ptr<const Klass>* constsmartpointerpointertest(SwigBoost::shared_ptr<const Klass>* k) {
+  return k;
+}
+SwigBoost::shared_ptr<const Klass>& constsmartpointerreftest(SwigBoost::shared_ptr<const Klass>& k) {
+  return k;
+}
+// plain pointer
+Klass valuetest(Klass k) {
+  k.append(" valuetest");
+  return k;
+}
+Klass *pointertest(Klass *k) {
+  if (k)
+    k->append(" pointertest");
+  return k;
+}
+Klass& reftest(Klass& k) {
+  k.append(" reftest");
+  return k;
+}
+Klass*& pointerreftest(Klass*& k) {
+  k->append(" pointerreftest");
+  return k;
+}
+// null
+std::string nullsmartpointerpointertest(SwigBoost::shared_ptr<Klass>* k) {
+  if (k && *k)
+    return "not null";
+  else if (!k)
+    return "null smartpointer pointer";
+  else if (!*k)
+    return "null pointer";
+  else
+    return "also not null";
+}
+// $owner
+Klass *pointerownertest() {
+  return new Klass("pointerownertest");
+}
+SwigBoost::shared_ptr<Klass>* smartpointerpointerownertest() {
+  return new SwigBoost::shared_ptr<Klass>(new Klass("smartpointerpointerownertest"));
+}
+
+// Provide overloads for Klass and KlassDerived as some language modules, eg Python, create an extra reference in
+// the marshalling if an upcast to a base class is required.
+long use_count(const SwigBoost::shared_ptr<KlassDerived>& sptr) {
+  return sptr.use_count();
+}
+long use_count(const SwigBoost::shared_ptr<Klass>& sptr) {
+  return sptr.use_count();
+}
+const SwigBoost::shared_ptr<Klass>& ref_1() { 
+  static SwigBoost::shared_ptr<Klass> sptr;
+  return sptr;
+}
+
+// overloading tests
+std::string overload_rawbyval(int i) { return "int"; }
+std::string overload_rawbyval(Klass k) { return "rawbyval"; }
+
+std::string overload_rawbyref(int i) { return "int"; }
+std::string overload_rawbyref(Klass &k) { return "rawbyref"; }
+
+std::string overload_rawbyptr(int i) { return "int"; }
+std::string overload_rawbyptr(Klass *k) { return "rawbyptr"; }
+
+std::string overload_rawbyptrref(int i) { return "int"; }
+std::string overload_rawbyptrref(Klass *&k) { return "rawbyptrref"; }
+
+
+
+std::string overload_smartbyval(int i) { return "int"; }
+std::string overload_smartbyval(SwigBoost::shared_ptr<Klass> k) { return "smartbyval"; }
+
+std::string overload_smartbyref(int i) { return "int"; }
+std::string overload_smartbyref(SwigBoost::shared_ptr<Klass> &k) { return "smartbyref"; }
+
+std::string overload_smartbyptr(int i) { return "int"; }
+std::string overload_smartbyptr(SwigBoost::shared_ptr<Klass> *k) { return "smartbyptr"; }
+
+std::string overload_smartbyptrref(int i) { return "int"; }
+std::string overload_smartbyptrref(SwigBoost::shared_ptr<Klass> *&k) { return "smartbyptrref"; }
+
+} // namespace Space
+
+%}
+%{
+  int Space::Klass::total_count = 0;
+%}
+
+
+// Member variables
+
+%inline %{
+struct MemberVariables {
+  MemberVariables() : SmartMemberPointer(&SmartMemberValue), SmartMemberReference(SmartMemberValue), MemberPointer(0), MemberReference(MemberValue) {}
+  SwigBoost::shared_ptr<Space::Klass> SmartMemberValue;
+  SwigBoost::shared_ptr<Space::Klass> * SmartMemberPointer;
+  SwigBoost::shared_ptr<Space::Klass> & SmartMemberReference;
+  Space::Klass MemberValue;
+  Space::Klass * MemberPointer;
+  Space::Klass & MemberReference;
+};
+
+// Global variables
+SwigBoost::shared_ptr<Space::Klass> GlobalSmartValue;
+Space::Klass GlobalValue;
+Space::Klass * GlobalPointer = 0;
+Space::Klass & GlobalReference = GlobalValue;
+
+%}
+
+#if defined(SHARED_PTR_WRAPPERS_IMPLEMENTED)
+
+// Note: %template after the shared_ptr typemaps
+SWIG_SHARED_PTR(BaseIntDouble, Base<int, double>)
+// Note: cannot use Base<int, double> in the macro below because of the comma in the type, 
+// so we use a typedef instead. Alternatively use %arg(Base<int, double>). %arg is defined in swigmacros.swg.
+SWIG_SHARED_PTR_DERIVED(PairIntDouble, BaseIntDouble_t, Pair<int, double>)
+
+#endif
+
+// Templates
+%inline %{
+template <class T1, class T2> struct Base {
+  Space::Klass klassBase;
+  T1 baseVal1;
+  T2 baseVal2;
+  Base(T1 t1, T2 t2) : baseVal1(t1*2), baseVal2(t2*2) {}
+  virtual std::string getValue() const { return "Base<>"; };
+};
+typedef Base<int, double> BaseIntDouble_t;
+%}
+
+%template(BaseIntDouble) Base<int, double>;
+
+%inline %{
+template <class T1, class T2> struct Pair : Base<T1, T2> {
+  Space::Klass klassPair;
+  T1 val1;
+  T2 val2;
+  Pair(T1 t1, T2 t2) : Base<T1, T2>(t1, t2), val1(t1), val2(t2) {}
+  virtual std::string getValue() const { return "Pair<>"; };
+};
+Pair<int, double> pair_id2(Pair<int, double> p) { return p; }
+SwigBoost::shared_ptr< Pair<int, double> > pair_id1(SwigBoost::shared_ptr< Pair<int, double> > p) { return p; }
+%}
+
+%template(PairIntDouble) Pair<int, double>;
+
+
+// For counting the instances of shared_ptr (all of which are created on the heap)
+// shared_ptr_wrapper_count() gives overall count
+%inline %{
+namespace SwigBoost {
+  const int NOT_COUNTING = -123456;
+  int shared_ptr_wrapper_count() { 
+  #ifdef SHARED_PTR_WRAPPER
+    return SwigBoost::SharedPtrWrapper::getTotalCount(); 
+  #else
+    return NOT_COUNTING;
+  #endif
+  }
+  #ifdef SHARED_PTR_WRAPPER
+  template<> std::string show_message(boost::shared_ptr<Space::Klass >*t) {
+    if (!t)
+      return "null shared_ptr!!!";
+    if (boost::get_deleter<SWIG_null_deleter>(*t))
+      return "Klass NULL DELETER"; // pointer may be dangling so cannot use it
+    if (*t)
+      return "Klass: " + (*t)->getValue();
+    else
+      return "Klass: NULL";
+  }
+  template<> std::string show_message(boost::shared_ptr<const Space::Klass >*t) {
+    if (!t)
+      return "null shared_ptr!!!";
+    if (boost::get_deleter<SWIG_null_deleter>(*t))
+      return "Klass NULL DELETER"; // pointer may be dangling so cannot use it
+    if (*t)
+      return "Klass: " + (*t)->getValue();
+    else
+      return "Klass: NULL";
+  }
+  template<> std::string show_message(boost::shared_ptr<Space::KlassDerived >*t) {
+    if (!t)
+      return "null shared_ptr!!!";
+    if (boost::get_deleter<SWIG_null_deleter>(*t))
+      return "KlassDerived NULL DELETER"; // pointer may be dangling so cannot use it
+    if (*t)
+      return "KlassDerived: " + (*t)->getValue();
+    else
+      return "KlassDerived: NULL";
+  }
+  template<> std::string show_message(boost::shared_ptr<const Space::KlassDerived >*t) {
+    if (!t)
+      return "null shared_ptr!!!";
+    if (boost::get_deleter<SWIG_null_deleter>(*t))
+      return "KlassDerived NULL DELETER"; // pointer may be dangling so cannot use it
+    if (*t)
+      return "KlassDerived: " + (*t)->getValue();
+    else
+      return "KlassDerived: NULL";
+  }
+  #endif
+}
+%}
+
diff --git a/trunk/Examples/test-suite/li_boost_shared_ptr_bits.i b/trunk/Examples/test-suite/li_boost_shared_ptr_bits.i
new file mode 100644
index 0000000..85ce1d6
--- /dev/null
+++ b/trunk/Examples/test-suite/li_boost_shared_ptr_bits.i
@@ -0,0 +1,25 @@
+%module li_boost_shared_ptr_bits
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON)
+#define SHARED_PTR_WRAPPERS_IMPLEMENTED
+#endif
+
+#if defined(SHARED_PTR_WRAPPERS_IMPLEMENTED)
+
+%include <boost_shared_ptr.i>
+SWIG_SHARED_PTR(NonDynamic, NonDynamic)
+
+#endif
+
+#if defined(SWIGPYTHON)
+%pythonnondynamic NonDynamic;
+#endif
+
+%inline %{
+#include <boost/shared_ptr.hpp>
+struct NonDynamic {
+  int i;
+};
+boost::shared_ptr<NonDynamic> boing(boost::shared_ptr<NonDynamic> b) { return b; }
+%}
+
diff --git a/trunk/Examples/test-suite/li_carrays.i b/trunk/Examples/test-suite/li_carrays.i
new file mode 100644
index 0000000..45c6537
--- /dev/null
+++ b/trunk/Examples/test-suite/li_carrays.i
@@ -0,0 +1,28 @@
+%module li_carrays
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) doubleArray; /* Ruby, wrong class name */
+
+%include <carrays.i>
+
+%array_functions(int,intArray);
+%array_class(double, doubleArray);
+
+%inline %{
+typedef struct {
+  int x;
+  int y;
+} XY;
+XY globalXYArray[3];
+
+typedef struct {
+  int a;
+  int b;
+} AB;
+
+AB globalABArray[3];
+%}
+
+// Note that struct XY { ... }; gives compiler error for C when using %array_class or %array_functions, but is okay in C++
+%array_class(XY, XYArray)
+%array_functions(AB, ABArray)
+
diff --git a/trunk/Examples/test-suite/li_cdata.i b/trunk/Examples/test-suite/li_cdata.i
new file mode 100644
index 0000000..6ce006d
--- /dev/null
+++ b/trunk/Examples/test-suite/li_cdata.i
@@ -0,0 +1,8 @@
+%module li_cdata
+
+%include <cdata.i>
+
+%cdata(int);
+%cdata(double);
+
+
diff --git a/trunk/Examples/test-suite/li_cdata_carrays.i b/trunk/Examples/test-suite/li_cdata_carrays.i
new file mode 100644
index 0000000..7b000c1
--- /dev/null
+++ b/trunk/Examples/test-suite/li_cdata_carrays.i
@@ -0,0 +1,8 @@
+%module li_cdata_carrays
+
+%include <carrays.i>
+%array_class(int, intArray);
+
+%include <cdata.i>
+
+%cdata(int);
diff --git a/trunk/Examples/test-suite/li_cmalloc.i b/trunk/Examples/test-suite/li_cmalloc.i
new file mode 100644
index 0000000..364351d
--- /dev/null
+++ b/trunk/Examples/test-suite/li_cmalloc.i
@@ -0,0 +1,12 @@
+%module li_cmalloc
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) sizeof_int;    /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) sizeof_double; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) sizeof_intp;   /* Ruby, wrong constant name */
+
+%include <cmalloc.i>
+
+%allocators(int);
+%allocators(double);
+%allocators(void);
+%allocators(int *, intp);
diff --git a/trunk/Examples/test-suite/li_constraints.i b/trunk/Examples/test-suite/li_constraints.i
new file mode 100644
index 0000000..1bbecf1
--- /dev/null
+++ b/trunk/Examples/test-suite/li_constraints.i
@@ -0,0 +1,35 @@
+%module li_constraints
+%include <constraints.i>
+
+%inline %{
+void test_nonnegative(double NONNEGATIVE) {
+}
+
+void test_nonpositive(double NONPOSITIVE) {
+}
+
+void test_positive(double POSITIVE) {
+}
+
+void test_negative(double POSITIVE) {
+}
+
+void test_nonzero(double NONZERO) {
+}
+
+void test_nonnull(void *NONNULL) {
+}
+
+/* These generated non-portable code and there isn't an obvious fix
+
+void test_align8(void *ALIGN8) {
+}
+
+void test_align4(void *ALIGN4) {
+}
+
+void test_align2(void *ALIGN2) {
+}
+*/
+%}
+
diff --git a/trunk/Examples/test-suite/li_cpointer.i b/trunk/Examples/test-suite/li_cpointer.i
new file mode 100644
index 0000000..c5584ce
--- /dev/null
+++ b/trunk/Examples/test-suite/li_cpointer.i
@@ -0,0 +1,10 @@
+%module li_cpointer
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) doublep; /* Ruby, wrong class name */
+
+%include "cpointer.i"
+
+%pointer_functions(int,intp);
+%pointer_class(double,doublep);
+%pointer_cast(int, unsigned int, int_to_uint);
+
diff --git a/trunk/Examples/test-suite/li_cstring.i b/trunk/Examples/test-suite/li_cstring.i
new file mode 100644
index 0000000..fd92ac7
--- /dev/null
+++ b/trunk/Examples/test-suite/li_cstring.i
@@ -0,0 +1,98 @@
+%module li_cstring
+
+%include "cstring.i"
+
+#ifndef SWIG_CSTRING_UNIMPL
+
+%cstring_input_binary(char *in, int n);
+%cstring_bounded_output(char *out1, 512);
+%cstring_chunk_output(char *out2, 64);
+%cstring_bounded_mutable(char *out3, 512);
+%cstring_mutable(char *out4, 32);
+%cstring_output_maxsize(char *out5, int max);
+%cstring_output_withsize(char *out6, int *size);
+
+#ifdef __cplusplus
+%cstring_output_allocate(char **out7, delete [] *$1);
+%cstring_output_allocate_size(char **out8, int *size, delete [] *$1);
+#else
+%cstring_output_allocate(char **out7, free(*$1));
+%cstring_output_allocate_size(char **out8, int *size, free(*$1));
+#endif
+
+%inline %{
+
+int count(char *in, int n, char c) {
+   int r = 0;
+   while (n > 0) {
+     if (*in == c) {
+	r++;
+     }
+     in++;
+     --n;
+   }
+   return r;
+}
+
+void test1(char *out1) {
+   strcpy(out1,"Hello World");
+}
+
+void test2(char *out2) {
+   int i;
+   for (i = 0; i < 64; i++) {
+       *out2 = (char) i + 32;
+       out2++;
+   }
+}
+
+void test3(char *out3) {
+   strcat(out3,"-suffix");
+}
+
+void test4(char *out4) {
+   strcat(out4,"-suffix");
+}
+
+void test5(char *out5, int max) {
+   int i;
+   for (i = 0; i < max; i++) {
+       out5[i] = 'x';
+   }
+   out5[max]='\0';
+}
+
+void test6(char *out6, int *size) {
+   int i;
+   for (i = 0; i < (*size/2); i++) {
+       out6[i] = 'x';
+   }
+   *size = (*size/2);
+}
+
+void test7(char **out7) {
+#ifdef __cplusplus
+   *out7 = new char[64];
+#else
+   *out7 = malloc(64);
+#endif
+   (*out7)[0] = 0;
+   strcat(*out7,"Hello world!");
+}
+
+void test8(char **out8, int *size) {
+   int i;
+#ifdef __cplusplus
+   *out8 = new char[64];
+#else
+   *out8 = malloc(64);
+#endif
+   for (i = 0; i < 64; i++) {
+      (*out8)[i] = (char) i+32;
+   }
+   *size = 64;
+}
+
+%}
+
+#endif
diff --git a/trunk/Examples/test-suite/li_cwstring.i b/trunk/Examples/test-suite/li_cwstring.i
new file mode 100644
index 0000000..dc9a1c4
--- /dev/null
+++ b/trunk/Examples/test-suite/li_cwstring.i
@@ -0,0 +1,98 @@
+%module li_cwstring
+
+%include "cwstring.i"
+
+#ifndef SWIG_CWSTRING_UNIMPL
+
+%cwstring_input_binary(wchar_t *in, int n);
+%cwstring_bounded_output(wchar_t *out1, 512);
+%cwstring_chunk_output(wchar_t *out2, 64);
+%cwstring_bounded_mutable(wchar_t *out3, 512);
+%cwstring_mutable(wchar_t *out4, 32);
+%cwstring_output_maxsize(wchar_t *out5, int max);
+%cwstring_output_withsize(wchar_t *out6, int *size);
+
+#ifdef __cplusplus
+%cwstring_output_allocate(wchar_t **out7, delete [] *$1);
+%cwstring_output_allocate_size(wchar_t **out8, int *size, delete [] *$1);
+#else
+%cwstring_output_allocate(wchar_t **out7, free(*$1));
+%cwstring_output_allocate_size(wchar_t **out8, int *size, free(*$1));
+#endif
+
+%inline %{
+
+int count(wchar_t *in, int n, wchar_t c) {
+   int r = 0;
+   while (n > 0) {
+     if (*in == c) {
+	r++;
+     }
+     in++;
+     --n;
+   }
+   return r;
+}
+
+void test1(wchar_t *out1) {
+   wcscpy(out1,L"Hello World");
+}
+
+void test2(wchar_t *out2) {
+   int i;
+   for (i = 0; i < 64; i++) {
+       *out2 = (wchar_t) i + 32;
+       out2++;
+   }
+}
+
+void test3(wchar_t *out3) {
+   wcscat(out3,L"-suffix");
+}
+
+void test4(wchar_t *out4) {
+   wcscat(out4,L"-suffix");
+}
+
+void test5(wchar_t *out5, int max) {
+   int i;
+   for (i = 0; i < max; i++) {
+       out5[i] = 'x';
+   }
+   out5[max]='\0';
+}
+
+void test6(wchar_t *out6, int *size) {
+   int i;
+   for (i = 0; i < (*size/2); i++) {
+       out6[i] = 'x';
+   }
+   *size = (*size/2);
+}
+
+void test7(wchar_t **out7) {
+#ifdef __cplusplus
+   *out7 = new wchar_t[64];
+#else
+   *out7 = malloc(64*sizeof(wchar_t));
+#endif
+   (*out7)[0] = 0;
+   wcscat(*out7,L"Hello world!");
+}
+
+void test8(wchar_t **out8, int *size) {
+   int i;
+#ifdef __cplusplus
+   *out8 = new wchar_t[64];
+#else
+   *out8 = malloc(64*sizeof(wchar_t));
+#endif
+   for (i = 0; i < 64; i++) {
+      (*out8)[i] = (wchar_t) i + 32;
+   }
+   *size = 64;
+}
+
+%}
+
+#endif
diff --git a/trunk/Examples/test-suite/li_factory.i b/trunk/Examples/test-suite/li_factory.i
new file mode 100644
index 0000000..dcd8b30
--- /dev/null
+++ b/trunk/Examples/test-suite/li_factory.i
@@ -0,0 +1,46 @@
+%module li_factory
+%include factory.i
+
+%newobject Geometry::create;
+
+%newobject Geometry::clone;
+%factory(Geometry *Geometry::create, Point, Circle);
+%factory(Geometry *Geometry::clone, Point, Circle);
+%factory(Geometry *Point::clone, Point, Circle);
+%factory(Geometry *Circle::clone, Point, Circle);
+
+%inline {
+  struct Geometry {
+    enum GeomType{
+      POINT,
+      CIRCLE
+    };
+    
+    virtual ~Geometry() {}    
+    virtual int draw() = 0;
+    static Geometry *create(GeomType i);
+		virtual Geometry *clone() = 0;
+  };
+
+  struct Point : Geometry  {
+    int draw() { return 1; }
+    double width() { return 1.0; }    
+		Geometry *clone() { return new Point(); }
+  };
+
+  struct Circle : Geometry  {
+    int draw() { return 2; }
+    double radius() { return 1.5; }      
+		Geometry *clone() { return new Circle(); }
+  }; 
+
+  Geometry *Geometry::create(GeomType type) {
+    switch (type) {
+    case POINT: return new Point();
+    case CIRCLE: return new Circle(); 
+    default: return 0;
+    }
+  }
+}
+
+
diff --git a/trunk/Examples/test-suite/li_implicit.i b/trunk/Examples/test-suite/li_implicit.i
new file mode 100644
index 0000000..0ce10dd
--- /dev/null
+++ b/trunk/Examples/test-suite/li_implicit.i
@@ -0,0 +1,23 @@
+%module("nocastmode") li_implicit
+#pragma SWIG nowarn=SWIGWARN_PP_CPP_WARNING
+%include implicit.i
+
+%inline 
+{
+  struct B { };  
+}
+
+%implicit(A, int, double, B);
+
+%inline 
+{
+  struct A
+  {
+    int ii;
+    A(int i) { ii = 1; }
+    A(double d) { ii = 2; }
+    A(const B& b) { ii = 3; }
+  };
+
+  int get(const A& a) { return a.ii; }
+}
diff --git a/trunk/Examples/test-suite/li_math.i b/trunk/Examples/test-suite/li_math.i
new file mode 100644
index 0000000..db39cd3
--- /dev/null
+++ b/trunk/Examples/test-suite/li_math.i
@@ -0,0 +1,2 @@
+%module li_math
+%include math.i
diff --git a/trunk/Examples/test-suite/li_std_deque.i b/trunk/Examples/test-suite/li_std_deque.i
new file mode 100644
index 0000000..152bc86
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_deque.i
@@ -0,0 +1,47 @@
+%module li_std_deque
+
+%include "std_deque.i"
+
+%{
+#include <algorithm>
+#include <functional>
+#include <numeric>
+%}
+
+namespace std {
+    %template(IntDeque) deque<int>;
+}
+
+%template(DoubleDeque) std::deque<double>;
+
+%inline %{
+typedef float Real;
+%}
+
+namespace std {
+    %template(RealDeque) deque<Real>;
+}
+
+%inline %{
+
+double average(std::deque<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::deque<float> half(const std::deque<float>& v) {
+    std::deque<float> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::deque<double>& v) {
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+%}
+
+
+
+
diff --git a/trunk/Examples/test-suite/li_std_except.i b/trunk/Examples/test-suite/li_std_except.i
new file mode 100644
index 0000000..fc886dc
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_except.i
@@ -0,0 +1,39 @@
+%module li_std_except
+
+%include <std_except.i>
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+
+%inline %{
+  struct E1 : public std::exception
+  {
+  };
+
+  struct E2 
+  {
+  };
+
+  struct Test {
+    int foo1() throw(std::bad_exception) { return 0; }
+    int foo2() throw(std::logic_error) { return 0; }
+    int foo3() throw(E1) { return 0; }
+    int foo4() throw(E2) { return 0; }
+    // all the STL exceptions...
+    void throw_bad_exception()    throw(std::bad_exception)     { throw std::bad_exception(); }
+    void throw_domain_error()     throw(std::domain_error)      { throw std::domain_error("oops"); }
+    void throw_exception()        throw(std::exception)         { throw std::exception(); }
+    void throw_invalid_argument() throw(std::invalid_argument)  { throw std::invalid_argument("oops"); }
+    void throw_length_error()     throw(std::length_error)      { throw std::length_error("oops"); }
+    void throw_logic_error()      throw(std::logic_error)       { throw std::logic_error("oops"); }
+    void throw_out_of_range()     throw(std::out_of_range)      { throw std::out_of_range("oops"); }
+    void throw_overflow_error()   throw(std::overflow_error)    { throw std::overflow_error("oops"); }
+    void throw_range_error()      throw(std::range_error)       { throw std::range_error("oops"); }
+    void throw_runtime_error()    throw(std::runtime_error)     { throw std::runtime_error("oops"); }
+    void throw_underflow_error()  throw(std::underflow_error)   { throw std::underflow_error("oops"); }
+  };
+%}
diff --git a/trunk/Examples/test-suite/li_std_map.i b/trunk/Examples/test-suite/li_std_map.i
new file mode 100644
index 0000000..edcb056
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_map.i
@@ -0,0 +1,76 @@
+/**
+ * @file   li_std_map.i
+ * @author gga
+ * @date   Mon Apr 30 15:03:58 2007
+ * 
+ * @brief  a test of map containers. 
+ *         Languages should define swig::LANGUAGE_OBJ to be
+ *         an entity of their native pointer type which can be
+ *         included in a STL container.
+ *
+ *         For example:
+ *                swig::LANGUAGE_OBJ  is  GC_VALUE in Ruby
+ *                swig::LANGUAGE_OBJ  is  PyObject_ptr in python
+ * 
+ * 
+ */
+
+%module("templatereduce") li_std_map
+%feature("trackobjects");
+
+%include std_pair.i
+%include std_map.i
+%include std_multimap.i
+
+%inline %{
+struct A{
+    int val;
+    
+    A(int v = 0): val(v)
+    {
+    }
+
+};
+%}
+
+namespace std
+{
+  %template(pairii) pair<int, int>;
+  %template(pairAA) pair<int, A>;
+  %template(pairA) pair<int, A*>;
+  %template(mapA) map<int, A*>;
+  %template(mmapA) multimap<int, A*>;
+
+  %template(paircA1) pair<const int, A*>;
+  %template(paircA2) pair<const int, const A*>;
+  %template(pairiiA) pair<int,pair<int, A*> >;
+  %template(pairiiAc) pair<int,const pair<int, A*> >;
+
+
+  %template() pair< swig::LANGUAGE_OBJ, swig::LANGUAGE_OBJ >;
+  %template(LanguageMap) map< swig::LANGUAGE_OBJ, swig::LANGUAGE_OBJ >;
+  
+}
+
+
+
+%inline 
+{
+std::pair<int, A*> 
+p_identa(std::pair<int, A*> p) {
+  return p;
+}
+
+std::map<int,A*> m_identa(const std::map<int,A*>& v)
+{
+  return v;
+}
+
+}
+
+
+
+namespace std
+{
+%template(mapii) map<int,int>;
+}
diff --git a/trunk/Examples/test-suite/li_std_pair.i b/trunk/Examples/test-suite/li_std_pair.i
new file mode 100644
index 0000000..9dea1d8
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_pair.i
@@ -0,0 +1,62 @@
+%module li_std_pair
+
+%include "std_pair.i"
+
+namespace std {
+  %template(IntPair)   pair<int, int>;
+}
+
+%inline %{
+
+/* Test the "out" typemap for pair<T, U> */
+std::pair<int, int> makeIntPair(int a, int b) {
+    return std::make_pair(a, b);
+}
+
+/**
+ * There is no "out" typemap for a pointer to a pair, so
+ * this should return a wrapped instance of a std::pair
+ * instead of the native "array" type for the target language.
+ */
+std::pair<int, int> * makeIntPairPtr(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return &p;
+}
+
+/**
+ * There is no "out" typemap for a non-const reference to a pair, so
+ * this should return a wrapped instance of a std::pair instead of
+ * the native "array" type for the target language.
+ */
+std::pair<int, int>& makeIntPairRef(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return p;
+}
+
+/**
+ * There is no "out" typemap for a const reference to a pair, so
+ * this should return a wrapped instance of a std::pair
+ * instead of the native "array" type for the target language.
+ */
+const std::pair<int, int> & makeIntPairConstRef(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return p;
+}
+
+/* Test the "in" typemap for pair<T, U> */
+int product1(std::pair<int, int> p) {
+    return p.first*p.second;
+}
+
+/* Test the "in" typemap for const pair<T, U>& */
+int product2(const std::pair<int, int>& p) {
+    return p.first*p.second;
+}
+
+/* Test the "in" typemap for const pair<T, U>* */
+int product3(const std::pair<int, int> *p) {
+    return p->first*p->second;
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/li_std_set.i b/trunk/Examples/test-suite/li_std_set.i
new file mode 100644
index 0000000..c2cdc2e
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_set.i
@@ -0,0 +1,34 @@
+/**
+ * @file   li_std_set.i
+ * @author gga
+ * @date   Tue May  1 02:52:47 2007
+ * 
+ * @brief  a test of set containers. 
+ *         Languages should define swig::LANGUAGE_OBJ to be
+ *         an entity of their native pointer type which can be
+ *         included in a STL container.
+ *
+ *         For example:
+ *                swig::LANGUAGE_OBJ  is  GC_VALUE in Ruby
+ *                swig::LANGUAGE_OBJ  is  PyObject_ptr in python
+ * 
+ * 
+ */
+
+%module li_std_set
+
+%include <std_string.i>
+%include <std_set.i>
+%include <std_multiset.i>
+%include <std_vector.i>
+
+%template(set_string) std::set<std::string>;
+%template(set_int) std::multiset<int>;
+
+
+%template(v_int) std::vector<int>;
+
+
+
+
+%template(LanguageSet) std::set<swig::LANGUAGE_OBJ>; 
diff --git a/trunk/Examples/test-suite/li_std_stream.i b/trunk/Examples/test-suite/li_std_stream.i
new file mode 100644
index 0000000..0a999dd
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_stream.i
@@ -0,0 +1,59 @@
+%module li_std_stream
+
+%inline %{
+  struct A;  
+%}
+
+%include <std_iostream.i>
+%include <std_sstream.i>
+
+
+
+%callback(1) A::bar;
+
+%inline %{
+
+  struct B {
+    virtual ~B()
+    {
+    }
+    
+  };
+  
+  struct A : B
+  {
+    void __add__(int a)
+    {
+    }
+
+    void __add__(double a)
+    {
+    }
+
+    static int bar(int a){
+      return a;
+    }
+
+    static int foo(int a, int (*pf)(int a))
+    {
+      return pf(a);
+    }
+
+
+    std::ostream& __rlshift__(std::ostream& out)
+    {
+      out << "A class";
+      return out;
+    }    
+  };
+%}
+
+%extend std::basic_ostream<char>{
+  std::basic_ostream<char>& 
+    operator<<(const A& a)
+    {
+      *self << "A class";
+      return *self;
+    }
+}
+
diff --git a/trunk/Examples/test-suite/li_std_string.i b/trunk/Examples/test-suite/li_std_string.i
new file mode 100644
index 0000000..2d0b750
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_string.i
@@ -0,0 +1,149 @@
+%module li_std_string
+%include <std_string.i>
+
+#if defined(SWIGUTL)
+%apply std::string& INPUT { std::string &input }
+%apply std::string& INOUT { std::string &inout }
+#endif
+
+
+%inline %{
+
+std::string test_value(std::string x) {
+   return x;
+}
+
+const std::string& test_const_reference(const std::string &x) {
+   return x;
+}
+
+void test_pointer(std::string *x) {
+}
+
+std::string *test_pointer_out() {
+   static std::string x = "x";
+   return &x;
+}
+
+void test_const_pointer(const std::string *x) {
+}
+
+const std::string *test_const_pointer_out() {
+   static std::string x = "x";
+   return &x;
+}
+
+void test_reference(std::string &x) {
+}
+
+std::string& test_reference_out() {
+   static std::string x = "test_reference_out message";
+   return x;
+}
+
+std::string test_reference_input(std::string &input) {
+  return input;
+}
+
+void test_reference_inout(std::string &inout) {
+  inout += inout;
+}
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+void test_throw() throw(std::string){
+  static std::string x = "test_throw message";
+  throw x;
+}
+
+void test_const_reference_throw() throw(const std::string &){
+  static std::string x = "test_const_reference_throw message";
+  throw x;
+}
+
+void test_pointer_throw() throw(std::string *) {
+  throw new std::string("foo");
+}
+
+void test_const_pointer_throw() throw(const std::string *) {
+  throw new std::string("foo");
+}
+
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+%}
+
+/* Old way, now std::string is a %naturalvar by default
+%apply const std::string& { std::string *GlobalString2, 
+                            std::string *MemberString2, 
+                            std::string *Structure::StaticMemberString2 };
+*/
+
+%inline %{
+std::string GlobalString;
+std::string GlobalString2 = "global string 2";
+const std::string ConstGlobalString = "const global string";
+
+struct Structure {
+  std::string MemberString;
+  std::string MemberString2;
+  static std::string StaticMemberString;
+  static std::string StaticMemberString2;
+
+  const std::string ConstMemberString;
+  static const std::string ConstStaticMemberString;
+
+  Structure() : MemberString2("member string 2"), ConstMemberString("const member string") {}
+};
+%}
+
+%{
+  std::string Structure::StaticMemberString = "static member string";
+  std::string Structure::StaticMemberString2 = "static member string 2";
+  const std::string Structure::ConstStaticMemberString = "const static member string";
+%}
+
+
+%inline %{
+class Foo {
+public:
+   unsigned long long  test(unsigned long long l)
+   {
+       return l + 1;
+   }
+   std::string test(std::string l)
+   {
+       return l + "1";
+   }
+
+   unsigned long long  testl(unsigned long long l)
+   {
+       return l + 1;
+   }
+
+}; 
+%}
+
+%inline %{
+  std::string stdstring_empty() {
+    return std::string();
+  }
+
+  char *c_empty() {
+    return (char *)"";
+  }
+
+  char *c_null() {
+    return 0;
+  }
+
+  const char *get_null(const char *a) {
+    return a == 0 ? a : "non-null";
+  }
+
+
+%}
diff --git a/trunk/Examples/test-suite/li_std_vector.i b/trunk/Examples/test-suite/li_std_vector.i
new file mode 100644
index 0000000..587ea22
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_vector.i
@@ -0,0 +1,124 @@
+%module li_std_vector
+
+%include "std_vector.i"
+%include "std_string.i"
+
+%{
+#include <algorithm>
+#include <functional>
+#include <numeric>
+%}
+
+namespace std {
+    %template(IntVector) vector<int>;
+}
+
+%template(BoolVector) std::vector<bool>;
+%template(CharVector) std::vector<char>;
+%template(ShortVector) std::vector<short>;
+%template(LongVector) std::vector<long>;
+%template(UCharVector) std::vector<unsigned char>;
+%template(UIntVector) std::vector<unsigned int>;
+%template(UShortVector) std::vector<unsigned short>;
+%template(ULongVector) std::vector<unsigned long>;
+%template(DoubleVector) std::vector<double>;
+%template(StringVector) std::vector<std::string>;
+
+
+%inline %{
+typedef float Real;
+%}
+
+namespace std {
+    %template(RealVector) vector<Real>;
+}
+
+%inline %{
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<Real> half(const std::vector<Real>& v) {
+    std::vector<Real> w(v);
+    for (std::vector<Real>::size_type i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+struct Struct {
+  double num;
+  Struct() : num(0.0) {}
+  Struct(double d) : num(d) {}
+};
+
+struct Structure {
+  double num;
+  Structure() : num(0.0) {}
+  Structure(double d) : num(d) {}
+};
+
+const std::vector<Real> & vecreal(const std::vector<Real> & vec) { return vec; }
+
+const std::vector<int> & vecintptr(const std::vector<int> & vec) { return vec; }
+const std::vector<int *> & vecintptr(const std::vector<int *> & vec) { return vec; }
+const std::vector<const int *> & vecintconstptr(const std::vector<const int *> & vec) { return vec; }
+
+const std::vector<Struct> & vecstruct(const std::vector<Struct> & vec) { return vec; }
+const std::vector<Struct *> & vecstructptr(const std::vector<Struct *> & vec) { return vec; }
+const std::vector<const Struct *> & vecstructconstptr(const std::vector<const Struct *> & vec) { return vec; }
+%}
+
+#if defined(SWIGCSHARP)
+SWIG_STD_VECTOR_SPECIALIZE(Struct, Struct *)
+SWIG_STD_VECTOR_SPECIALIZE(Struct, const Struct *)
+SWIG_STD_VECTOR_SPECIALIZE(SWIGTYPE_p_int, int *)
+SWIG_STD_VECTOR_SPECIALIZE(SWIGTYPE_p_int, const int *)
+
+// Also test non-specialized versions
+%template(StructurePtrVector) std::vector<Structure *>;
+%template(StructureConstPtrVector) std::vector<const Structure *>;
+#endif
+
+%template(IntPtrVector) std::vector<int *>;
+%template(IntConstPtrVector) std::vector<const int *>;
+%template(StructVector) std::vector<Struct>;
+%template(StructPtrVector) std::vector<Struct *>;
+%template(StructConstPtrVector) std::vector<const Struct *>;
+
+#if defined(SWIGCSHARP)
+SWIG_STD_VECTOR_SPECIALIZE(MyClass, MyClass *)
+#endif
+
+#if !defined(SWIGTCL)
+%inline {
+  struct MyClass {};
+  typedef MyClass *MyClassPtr;
+  typedef std::vector<MyClassPtr> MyClassVector;
+}
+%template(MyClassPtrVector) std::vector<MyClassPtr>;
+
+%inline {
+  class RetsMetadata
+  {
+  public:
+    MyClassVector GetAllResources(size_t n) const
+    {
+      return MyClassVector(n, 0);
+    }
+  };
+}
+#endif
+
+#if defined(SWIGRUBY)
+%template(LanguageVector) std::vector< swig::LANGUAGE_OBJ >;
+
+%inline {
+  std::vector< swig::LANGUAGE_OBJ > LanguageVector; 
+}
+#endif
diff --git a/trunk/Examples/test-suite/li_std_wstring.i b/trunk/Examples/test-suite/li_std_wstring.i
new file mode 100644
index 0000000..c809e11
--- /dev/null
+++ b/trunk/Examples/test-suite/li_std_wstring.i
@@ -0,0 +1,89 @@
+%module li_std_wstring
+%include <std_basic_string.i>
+%include <std_wstring.i>
+
+
+%inline %{
+
+struct A : std::wstring 
+{
+  A(const std::wstring& s) : std::wstring(s)
+  {
+  }
+};
+
+struct B 
+{
+  B(const std::wstring& s) : cname(0), name(s), a(s)
+  {
+  }
+  
+  char *cname;
+  std::wstring name;
+  A a;
+
+};
+ 
+
+wchar_t test_wcvalue(wchar_t x) {
+   return x;
+}
+
+const wchar_t* test_ccvalue(const wchar_t* x) {
+   return x;
+}
+
+wchar_t* test_cvalue(wchar_t* x) {
+   return x;
+}
+  
+
+std::wstring test_value(std::wstring x) {
+   return x;
+}
+
+const std::wstring& test_const_reference(const std::wstring &x) {
+   return x;
+}
+
+void test_pointer(std::wstring *x) {
+}
+
+std::wstring *test_pointer_out() {
+   static std::wstring x = L"x";
+   return &x;
+}
+
+void test_const_pointer(const std::wstring *x) {
+}
+
+const std::wstring *test_const_pointer_out() {
+   static std::wstring x = L"x";
+   return &x;
+}
+
+void test_reference(std::wstring &x) {
+}
+
+std::wstring& test_reference_out() {
+   static std::wstring x = L"x";
+   return x;
+}
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+void test_throw() throw(std::wstring){
+  static std::wstring x = L"x";
+  
+  throw x;
+}
+
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+%}
+
+
diff --git a/trunk/Examples/test-suite/li_stdint.i b/trunk/Examples/test-suite/li_stdint.i
new file mode 100644
index 0000000..5186799
--- /dev/null
+++ b/trunk/Examples/test-suite/li_stdint.i
@@ -0,0 +1,67 @@
+%module li_stdint
+
+%include <stdint.i>
+
+%inline %{
+  struct StdInts {
+    int8_t   int8_member;
+    int16_t  int16_member;
+    int32_t  int32_member;
+    int64_t  int64_member;
+    uint8_t  uint8_member;
+    uint16_t uint16_member;
+    uint32_t uint32_member;
+    uint64_t uint64_member;
+  };
+
+  int8_t   int8_td (int8_t  i) { return i; }
+  int16_t  int16_td(int16_t i) { return i; }
+  int32_t  int32_td(int32_t i) { return i; }
+  int64_t  int64_td(int64_t i) { return i; }
+  uint8_t  uint8_td (int8_t  i) { return i; }
+  uint16_t uint16_td(int16_t i) { return i; }
+  uint32_t uint32_td(int32_t i) { return i; }
+  uint64_t uint64_td(int64_t i) { return i; }
+
+  struct StdIntFasts {
+    int_fast8_t   int_fast8_member;
+    int_fast16_t  int_fast16_member;
+    int_fast32_t  int_fast32_member;
+    int_fast64_t  int_fast64_member;
+    uint_fast8_t  uint_fast8_member;
+    uint_fast16_t uint_fast16_member;
+    uint_fast32_t uint_fast32_member;
+    uint_fast64_t uint_fast64_member;
+  };
+
+  int_fast8_t   int_fast8_td (int_fast8_t  i) { return i; }
+  int_fast16_t  int_fast16_td(int_fast16_t i) { return i; }
+  int_fast32_t  int_fast32_td(int_fast32_t i) { return i; }
+  int_fast64_t  int_fast64_td(int_fast64_t i) { return i; }
+  uint_fast8_t  uint_fast8_td (int_fast8_t  i) { return i; }
+  uint_fast16_t uint_fast16_td(int_fast16_t i) { return i; }
+  uint_fast32_t uint_fast32_td(int_fast32_t i) { return i; }
+  uint_fast64_t uint_fast64_td(int_fast64_t i) { return i; }
+
+  struct StdIntLeasts {
+    int_least8_t   int_least8_member;
+    int_least16_t  int_least16_member;
+    int_least32_t  int_least32_member;
+    int_least64_t  int_least64_member;
+    uint_least8_t  uint_least8_member;
+    uint_least16_t uint_least16_member;
+    uint_least32_t uint_least32_member;
+    uint_least64_t uint_least64_member;
+  };
+
+  int_least8_t   int_least8_td (int_least8_t  i) { return i; }
+  int_least16_t  int_least16_td(int_least16_t i) { return i; }
+  int_least32_t  int_least32_td(int_least32_t i) { return i; }
+  int_least64_t  int_least64_td(int_least64_t i) { return i; }
+  uint_least8_t  uint_least8_td (int_least8_t  i) { return i; }
+  uint_least16_t uint_least16_td(int_least16_t i) { return i; }
+  uint_least32_t uint_least32_td(int_least32_t i) { return i; }
+  uint_least64_t uint_least64_td(int_least64_t i) { return i; }
+
+%}
+
diff --git a/trunk/Examples/test-suite/li_typemaps.i b/trunk/Examples/test-suite/li_typemaps.i
new file mode 100644
index 0000000..a53c1c7
--- /dev/null
+++ b/trunk/Examples/test-suite/li_typemaps.i
@@ -0,0 +1,109 @@
+%module li_typemaps
+
+%include "typemaps.i"
+
+%apply int &INOUT { int &INOUT2 };
+%newobject out_foo;
+%inline %{
+
+struct Foo { int a; };
+
+bool in_bool(bool *INPUT) { return *INPUT; }
+int in_int(int *INPUT) { return *INPUT; }
+long in_long(long *INPUT) { return *INPUT; }
+short in_short(short *INPUT) { return *INPUT; }
+unsigned int in_uint(unsigned int *INPUT) { return *INPUT; }
+unsigned short in_ushort(unsigned short *INPUT) { return *INPUT; }
+unsigned long in_ulong(unsigned long *INPUT) { return *INPUT; }
+unsigned char in_uchar(unsigned char *INPUT) { return *INPUT; }
+signed char in_schar(signed char *INPUT) { return *INPUT; }
+float in_float(float *INPUT) { return *INPUT; }
+double in_double(double *INPUT) { return *INPUT; }
+long long in_longlong(long long *INPUT) { return *INPUT; }
+unsigned long long in_ulonglong(unsigned long long *INPUT) { return *INPUT; }
+
+bool inr_bool(bool &INPUT) { return INPUT; }
+int inr_int(int &INPUT) { return INPUT; }
+long inr_long(long &INPUT) { return INPUT; }
+short inr_short(short &INPUT) { return INPUT; }
+unsigned int inr_uint(unsigned int &INPUT) { return INPUT; }
+unsigned short inr_ushort(unsigned short &INPUT) { return INPUT; }
+unsigned long inr_ulong(unsigned long &INPUT) { return INPUT; }
+unsigned char inr_uchar(unsigned char &INPUT) { return INPUT; }
+signed char inr_schar(signed char &INPUT) { return INPUT; }
+float inr_float(float &INPUT) { return INPUT; }
+double inr_double(double &INPUT) { return INPUT; }
+long long inr_longlong(long long &INPUT) { return INPUT; }
+unsigned long long inr_ulonglong(unsigned long long &INPUT) { return INPUT; }
+
+void out_bool(bool x, bool *OUTPUT) {  *OUTPUT = x; }
+void out_int(int x, int *OUTPUT) {  *OUTPUT = x; }
+void out_short(short x, short *OUTPUT) {  *OUTPUT = x; }
+void out_long(long x, long *OUTPUT) {  *OUTPUT = x; }
+void out_uint(unsigned int x, unsigned int *OUTPUT) {  *OUTPUT = x; }
+void out_ushort(unsigned short x, unsigned short *OUTPUT) {  *OUTPUT = x; }
+void out_ulong(unsigned long x, unsigned long *OUTPUT) {  *OUTPUT = x; }
+void out_uchar(unsigned char x, unsigned char *OUTPUT) {  *OUTPUT = x; }
+void out_schar(signed char x, signed char *OUTPUT) {  *OUTPUT = x; }
+void out_float(float x, float *OUTPUT) {  *OUTPUT = x; }
+void out_double(double x, double *OUTPUT) {  *OUTPUT = x; }
+void out_longlong(long long x, long long *OUTPUT) {  *OUTPUT = x; }
+void out_ulonglong(unsigned long long x, unsigned long long *OUTPUT) {  *OUTPUT = x; }
+
+/* Tests a returning a wrapped pointer and an output argument */
+struct Foo *out_foo(int a, int *OUTPUT) {
+  struct Foo *f = new struct Foo();
+  f->a = a;
+  *OUTPUT = a * 2;
+  return f;
+}
+
+void outr_bool(bool x, bool &OUTPUT) {  OUTPUT = x; }
+void outr_int(int x, int &OUTPUT) {  OUTPUT = x; }
+void outr_short(short x, short &OUTPUT) {  OUTPUT = x; }
+void outr_long(long x, long &OUTPUT) {  OUTPUT = x; }
+void outr_uint(unsigned int x, unsigned int &OUTPUT) {  OUTPUT = x; }
+void outr_ushort(unsigned short x, unsigned short &OUTPUT) {  OUTPUT = x; }
+void outr_ulong(unsigned long x, unsigned long &OUTPUT) {  OUTPUT = x; }
+void outr_uchar(unsigned char x, unsigned char &OUTPUT) {  OUTPUT = x; }
+void outr_schar(signed char x, signed char &OUTPUT) {  OUTPUT = x; }
+void outr_float(float x, float &OUTPUT) {  OUTPUT = x; }
+void outr_double(double x, double &OUTPUT) {  OUTPUT = x; }
+void outr_longlong(long long x, long long &OUTPUT) {  OUTPUT = x; }
+void outr_ulonglong(unsigned long long x, unsigned long long &OUTPUT) {  OUTPUT = x; }
+
+void inout_bool(bool *INOUT) {  *INOUT = *INOUT; }
+void inout_int(int *INOUT) {  *INOUT = *INOUT; }
+void inout_short(short *INOUT) {  *INOUT = *INOUT; }
+void inout_long(long *INOUT) {  *INOUT = *INOUT; }
+void inout_uint(unsigned int *INOUT) {  *INOUT = *INOUT; }
+void inout_ushort(unsigned short *INOUT) {  *INOUT = *INOUT; }
+void inout_ulong(unsigned long *INOUT) {  *INOUT = *INOUT; }
+void inout_uchar(unsigned char *INOUT) {  *INOUT = *INOUT; }
+void inout_schar(signed char *INOUT) {  *INOUT = *INOUT; }
+void inout_float(float *INOUT) {  *INOUT = *INOUT; }
+void inout_double(double *INOUT) {  *INOUT = *INOUT; }
+void inout_longlong(long long *INOUT) {  *INOUT = *INOUT; }
+void inout_ulonglong(unsigned long long *INOUT) {  *INOUT = *INOUT; }
+
+void inoutr_bool(bool &INOUT) {  INOUT = INOUT; }
+void inoutr_int(int &INOUT) {  INOUT = INOUT; }
+void inoutr_short(short &INOUT) {  INOUT = INOUT; }
+void inoutr_long(long &INOUT) {  INOUT = INOUT; }
+void inoutr_uint(unsigned int &INOUT) {  INOUT = INOUT; }
+void inoutr_ushort(unsigned short &INOUT) {  INOUT = INOUT; }
+void inoutr_ulong(unsigned long &INOUT) {  INOUT = INOUT; }
+void inoutr_uchar(unsigned char &INOUT) {  INOUT = INOUT; }
+void inoutr_schar(signed char &INOUT) {  INOUT = INOUT; }
+void inoutr_float(float &INOUT) {  INOUT = INOUT; }
+void inoutr_double(double &INOUT) {  INOUT = INOUT; }
+void inoutr_longlong(long long &INOUT) {  INOUT = INOUT; }
+void inoutr_ulonglong(unsigned long long &INOUT) {  INOUT = INOUT; }
+
+void inoutr_int2(int &INOUT, int &INOUT2) {  INOUT = INOUT; INOUT2 = INOUT2;}
+
+%}
+
+
+
+
diff --git a/trunk/Examples/test-suite/li_windows.i b/trunk/Examples/test-suite/li_windows.i
new file mode 100644
index 0000000..26f96cc
--- /dev/null
+++ b/trunk/Examples/test-suite/li_windows.i
@@ -0,0 +1,97 @@
+%module li_windows
+
+%include "windows.i"
+
+%{
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+  #include <windows.h>
+#else
+  // Use equivalent types for non-windows systems
+  #define __int8   char
+  #define __int16  short
+  #define __int32  int
+  #define __int64  long long
+#endif
+%}
+
+%inline %{
+// Non ISO integral types
+         __int8   int8_val (         __int8  i) { return i; }
+         __int16  int16_val(         __int16 i) { return i; }
+         __int32  int32_val(         __int32 i) { return i; }
+         __int64  int64_val(         __int64 i) { return i; }
+unsigned __int8  uint8_val (unsigned __int8  i) { return i; }
+unsigned __int16 uint16_val(unsigned __int16 i) { return i; }
+unsigned __int32 uint32_val(unsigned __int32 i) { return i; }
+unsigned __int64 uint64_val(unsigned __int64 i) { return i; }
+
+const          __int8&   int8_ref (const          __int8&  i) { return i; }
+const          __int16&  int16_ref(const          __int16& i) { return i; }
+const          __int32&  int32_ref(const          __int32& i) { return i; }
+const          __int64&  int64_ref(const          __int64& i) { return i; }
+const unsigned __int8&  uint8_ref (const unsigned __int8&  i) { return i; }
+const unsigned __int16& uint16_ref(const unsigned __int16& i) { return i; }
+const unsigned __int32& uint32_ref(const unsigned __int32& i) { return i; }
+const unsigned __int64& uint64_ref(const unsigned __int64& i) { return i; }
+
+         __int8   int8_global;
+         __int16  int16_global;
+         __int32  int32_global;
+         __int64  int64_global;
+unsigned __int8  uint8_global;
+unsigned __int16 uint16_global;
+unsigned __int32 uint32_global;
+unsigned __int64 uint64_global;
+
+struct WindowsInts {
+           __int8   int8_member;
+           __int16  int16_member;
+           __int32  int32_member;
+           __int64  int64_member;
+  unsigned __int8  uint8_member;
+  unsigned __int16 uint16_member;
+  unsigned __int32 uint32_member;
+  unsigned __int64 uint64_member;
+};
+
+// Typedef for non ISO integral types
+typedef __int8 int8;
+typedef __int16 int16;
+typedef __int32 int32;
+typedef __int64 int64;
+
+typedef unsigned __int8 uint8;
+typedef unsigned __int16 uint16;
+typedef unsigned __int32 uint32;
+typedef unsigned __int64 uint64;
+
+ int8   int8_td (int8  i) { return i; }
+ int16  int16_td(int16 i) { return i; }
+ int32  int32_td(int32 i) { return i; }
+ int64  int64_td(int64 i) { return i; }
+uint8  uint8_td (int8  i) { return i; }
+uint16 uint16_td(int16 i) { return i; }
+uint32 uint32_td(int32 i) { return i; }
+uint64 uint64_td(int64 i) { return i; }
+
+%}
+
+// Windows calling conventions and some types in windows.h
+%inline %{
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#else
+
+#define __stdcall
+#define __declspec(WINDOWS_EXTENDED_ATTRIBUTE)
+#define DWORD unsigned int
+#define PSZ char *
+
+#endif
+
+// Windows calling conventions
+__declspec(dllexport) int __stdcall declspecstdcall(int i) { return i; }
+
+DWORD mefod(DWORD d) { return d; }
+PSZ funktion(PSZ d) { return d; }
+%}
+
diff --git a/trunk/Examples/test-suite/list_vector.i b/trunk/Examples/test-suite/list_vector.i
new file mode 100644
index 0000000..7f907d4
--- /dev/null
+++ b/trunk/Examples/test-suite/list_vector.i
@@ -0,0 +1,153 @@
+/* -*- c -*- */
+
+%module list_vector
+
+%include "list-vector.i"
+
+%multiple_values
+
+/* The ordinary, well behaved multi-typemap. */
+double sum_list(int LISTLENINPUT, double *LISTINPUT);
+double sum_vector(int VECTORLENINPUT, double *VECTORINPUT);
+void one_to_seven_list(int *LISTLENOUTPUT, int **LISTOUTPUT);
+void one_to_seven_vector(int *VECTORLENOUTPUT, int **VECTOROUTPUT);
+
+/* Variants with `size_t' instead of `int' length.  */
+double sum_list2(size_t LISTLENINPUT, double *LISTINPUT);
+double sum_vector2(size_t VECTORLENINPUT, double *VECTORINPUT);
+void one_to_seven_list2(size_t *LISTLENOUTPUT, int **LISTOUTPUT);
+void one_to_seven_vector2(size_t *VECTORLENOUTPUT, int **VECTOROUTPUT);
+
+/* Parallel variants */
+
+double sum_lists(int PARALLEL_LISTLENINPUT,
+		 double *PARALLEL_LISTINPUT,
+		 int *PARALLEL_LISTINPUT,
+		 int *PARALLEL_LISTINPUT);
+double sum_lists2(size_t PARALLEL_LISTLENINPUT,
+		 double *PARALLEL_LISTINPUT,
+		 int *PARALLEL_LISTINPUT,
+		 int *PARALLEL_LISTINPUT);
+void produce_lists(int *PARALLEL_VECTORLENOUTPUT,
+		   int **PARALLEL_VECTOROUTPUT,
+		   int **PARALLEL_VECTOROUTPUT,
+		   double **PARALLEL_VECTOROUTPUT);
+
+%{
+  double sum_list(int length, double *item)
+  {
+    int i;
+    double res = 0.0;
+    for (i = 0; i<length; i++)
+      res += item[i];
+    return res;
+  }
+
+  double sum_list2(size_t length, double *item)
+  {
+    size_t i;
+    double res = 0.0;
+    for (i = 0; i<length; i++)
+      res += item[i];
+    return res;
+  }
+
+
+  double sum_vector(int length, double *item)
+  {
+    int i;
+    double res = 0.0;
+    for (i = 0; i<length; i++)
+      res += item[i];
+    return res;
+  }
+
+  double sum_vector2(size_t length, double *item)
+  {
+    size_t i;
+    double res = 0.0;
+    for (i = 0; i<length; i++)
+      res += item[i];
+    return res;
+  }
+
+
+  void one_to_seven_list(int *length_p, int **list_p)
+  {
+    int i;
+    *length_p = 7;
+    *list_p = malloc(7 * sizeof(int));
+    for (i = 0; i<7; i++)
+      (*list_p)[i] = i+1;
+  }
+
+   void one_to_seven_list2(size_t *length_p, int **list_p)
+  {
+    size_t i;
+    *length_p = 7;
+    *list_p = malloc(7 * sizeof(int));
+    for (i = 0; i<7; i++)
+      (*list_p)[i] = i+1;
+  }
+
+   void one_to_seven_vector(int *length_p, int **list_p)
+  {
+    int i;
+    *length_p = 7;
+    *list_p = malloc(7 * sizeof(int));
+    for (i = 0; i<7; i++)
+      (*list_p)[i] = i+1;
+  }
+
+  void one_to_seven_vector2(size_t *length_p, int **list_p)
+  {
+    size_t i;
+    *length_p = 7;
+    *list_p = malloc(7 * sizeof(int));
+    for (i = 0; i<7; i++)
+      (*list_p)[i] = i+1;
+  }
+
+double sum_lists(int len,
+		 double *list1,
+		 int *list2,
+		 int *list3)
+{
+  int i;
+  double sum = 0.0;
+  for (i = 0; i<len; i++)
+    sum += (list1[i] + list2[i] + list3[i]);
+  return sum;
+}
+
+double sum_lists2(size_t len,
+		  double *list1,
+		  int *list2,
+		  int *list3)
+{
+  size_t i;
+  double sum = 0.0;
+  for (i = 0; i<len; i++)
+    sum += (list1[i] + list2[i] + list3[i]);
+  return sum;
+}
+
+void produce_lists(int *len_p,
+		   int **list1_p,
+		   int **list2_p,
+		   double **list3_p)
+{
+  int i;
+  *len_p = 5;
+  *list1_p = malloc(sizeof(int) * 5);
+  *list2_p = malloc(sizeof(int) * 5);
+  *list3_p = malloc(sizeof(double) * 5);
+  for (i = 0; i<5; i++) {
+    (*list1_p)[i] = i;
+    (*list2_p)[i] = i*i;
+    (*list3_p)[i] = 1.5*i;
+  }
+}
+
+  
+%}
diff --git a/trunk/Examples/test-suite/long_long.i b/trunk/Examples/test-suite/long_long.i
new file mode 100644
index 0000000..74dd87a
--- /dev/null
+++ b/trunk/Examples/test-suite/long_long.i
@@ -0,0 +1,40 @@
+/* This interface file tests whether SWIG handles the new ISO C
+   long long types.
+*/
+
+%module long_long
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) lconst1; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) lconst2; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) lconst3; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) lconst4; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) lconst5; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) lconst6; /* Ruby, wrong constant name */
+
+%inline %{
+void foo1(long long x) {}
+void foo2(long long int x) {}
+void foo3(signed long long int x) {}
+void foo4(unsigned long long int x) {}
+void foo5(signed long long x) {}
+void foo6(unsigned long long x) {}
+
+long long bar1() {return 0;}
+long long int bar2() {return 0;}
+signed long long int bar3() {return 0;}
+unsigned long long int bar4() {return 0;}
+signed long long bar5() {return 0;}
+unsigned long long bar6() {return 0;}
+
+long long ll;
+unsigned long long ull;
+%}
+
+%constant long long  lconst1 = 1234567890LL;
+%constant unsigned long long lconst2 = 1234567890ULL;
+
+%constant lconst3 = 1234567LL;
+%constant lconst4 = 1234567ULL;
+
+#define lconst5 987654321LL
+#define lconst6 987654321ULL
diff --git a/trunk/Examples/test-suite/long_long_apply.i b/trunk/Examples/test-suite/long_long_apply.i
new file mode 100644
index 0000000..0280994
--- /dev/null
+++ b/trunk/Examples/test-suite/long_long_apply.i
@@ -0,0 +1,77 @@
+/* This interface file tests whether SWIG handles the Microsoft __int64 type through the use of 
+applying the long long typemaps. The generated code should not have any instances of long long. */
+
+%module long_long_apply
+
+%{
+#ifdef _MSC_VER /* Visual C++ */
+    typedef __int64 LongLong;
+    typedef unsigned __int64 UnsignedLongLong;
+#else
+    typedef long long LongLong;
+    typedef unsigned long long UnsignedLongLong;
+#endif
+%}
+
+%apply long long { LongLong };
+%apply unsigned long long { UnsignedLongLong };
+
+%apply const long long & { const LongLong & };
+%apply const unsigned long long & { const UnsignedLongLong & };
+
+%inline %{
+// pass by value
+LongLong value1(LongLong x) { return x; }
+UnsignedLongLong value2(UnsignedLongLong x) { return x; }
+
+// pass by reference
+const LongLong &ref1(const LongLong &x) { return x; }
+const UnsignedLongLong &ref2(const UnsignedLongLong &x) { return x; }
+
+// global variables
+LongLong global1;
+UnsignedLongLong global2;
+
+// global reference variables
+const LongLong& global_ref1 = global1;
+const UnsignedLongLong& global_ref2 = global2;
+%}
+
+
+// typemaps library
+%include "typemaps.i"
+%apply long long *INPUT { LongLong *INPUT };
+%apply unsigned long long *INPUT { UnsignedLongLong *INPUT };
+
+%apply long long *OUTPUT { LongLong *OUTPUT };
+%apply unsigned long long *OUTPUT { UnsignedLongLong *OUTPUT };
+
+%apply long long *INOUT { LongLong *INOUT };
+%apply unsigned long long *INOUT { UnsignedLongLong *INOUT };
+
+%apply long long &INPUT { LongLong &INPUT };
+%apply unsigned long long &INPUT { UnsignedLongLong &INPUT };
+
+%apply long long &OUTPUT { LongLong &OUTPUT };
+%apply unsigned long long &OUTPUT { UnsignedLongLong &OUTPUT };
+
+%apply long long &INOUT { LongLong &INOUT };
+%apply unsigned long long &INOUT { UnsignedLongLong &INOUT };
+
+%inline %{
+LongLong in_longlong(LongLong *INPUT) { return *INPUT; }
+UnsignedLongLong in_ulonglong(UnsignedLongLong *INPUT) { return *INPUT; }
+LongLong inr_longlong(LongLong &INPUT) { return INPUT; }
+UnsignedLongLong inr_ulonglong(UnsignedLongLong &INPUT) { return INPUT; }
+
+void out_longlong(LongLong x, LongLong *OUTPUT) {  *OUTPUT = x; }
+void out_ulonglong(UnsignedLongLong x, UnsignedLongLong *OUTPUT) {  *OUTPUT = x; }
+void outr_longlong(LongLong x, LongLong &OUTPUT) {  OUTPUT = x; }
+void outr_ulonglong(UnsignedLongLong x, UnsignedLongLong &OUTPUT) {  OUTPUT = x; }
+
+void inout_longlong(LongLong *INOUT) {  *INOUT = *INOUT; }
+void inout_ulonglong(UnsignedLongLong *INOUT) {  *INOUT = *INOUT; }
+void inoutr_longlong(LongLong &INOUT) {  INOUT = INOUT; }
+void inoutr_ulonglong(UnsignedLongLong &INOUT) {  INOUT = INOUT; }
+%}
+
diff --git a/trunk/Examples/test-suite/lua/Makefile.in b/trunk/Examples/test-suite/lua/Makefile.in
new file mode 100644
index 0000000..b370ae1
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/Makefile.in
@@ -0,0 +1,61 @@
+#######################################################################
+# Makefile for lua test-suite
+#######################################################################
+
+LANGUAGE     = lua
+LUA          = @LUABIN@
+SCRIPTSUFFIX = _runme.lua
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+# sorry, currently very few test cases work/have been written
+
+#CPP_TEST_CASES += \
+#	cnum 
+
+#C_TEST_CASES += \
+#	file_test \
+#	nondynamic
+
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+LIBS       = -L.
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.lua appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(LUA) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: (does nothing, we dont generate extra lua code)
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile lua_clean
+
+cvsignore:
+	@echo '*wrap* *.so *.dll *.exp *.lib'
+	@echo Makefile
+	@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do echo $$i.lua; done 
+	@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do if grep -q $${i}_runme.lua CVS/Entries ; then echo $${i}_runme.lua; fi; done 
diff --git a/trunk/Examples/test-suite/lua/abstract_access_runme.lua b/trunk/Examples/test-suite/lua/abstract_access_runme.lua
new file mode 100644
index 0000000..b9f44cf
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/abstract_access_runme.lua
@@ -0,0 +1,17 @@
+require("import")	-- the import fn
+import("abstract_access")	-- import code
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+-- trying to instantiate pure virual classes
+-- should fail
+assert(pcall(abstract_access.A)==false)
+assert(pcall(abstract_access.B)==false)
+assert(pcall(abstract_access.C)==false)
+
+-- instantiate object
+d=abstract_access.D()
+
+--call fn
+assert(d:do_x()==1)
diff --git a/trunk/Examples/test-suite/lua/cpp_basic_runme.lua b/trunk/Examples/test-suite/lua/cpp_basic_runme.lua
new file mode 100644
index 0000000..b63b89c
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/cpp_basic_runme.lua
@@ -0,0 +1,64 @@
+require("import")	-- the import fn
+import("cpp_basic")	-- import code
+cb=cpp_basic    -- renaming import
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+f=cb.Foo(4)
+assert(f.num==4)
+f.num=-17
+assert(f.num==-17)
+
+b=cb.Bar()
+
+b.fptr=f
+assert(b.fptr.num==-17)
+assert(b:test(-3,b.fptr)==-5)
+f.num=12
+assert(b.fptr.num==12)
+
+assert(b.fref.num==-4)
+assert(b:test(12,b.fref)==23)
+
+-- references don't take ownership, so if we didn't define this here it might get garbage collected
+f2=cb.Foo(23)
+b.fref=f2
+assert(b.fref.num==23)
+assert(b:test(-3,b.fref)==35)
+
+assert(b.fval.num==15)
+assert(b:test(3,b.fval)==33)
+b.fval=cb.Foo(-15)  -- this is safe as it is copied into the C++
+assert(b.fval.num==-15)
+assert(b:test(3,b.fval)==-27)
+
+f3=b:testFoo(12,b.fref)
+assert(f3.num==32)
+
+-- now test global
+f4=cb.Foo(6)
+cb.Bar_global_fptr=f4
+assert(cb.Bar_global_fptr.num==6)
+f4.num=8
+assert(cb.Bar_global_fptr.num==8)
+
+assert(cb.Bar_global_fref.num==23)
+cb.Bar_global_fref=cb.Foo(-7) -- this will set the value
+assert(cb.Bar_global_fref.num==-7)
+
+assert(cb.Bar_global_fval.num==3)
+cb.Bar_global_fval=cb.Foo(-34)
+assert(cb.Bar_global_fval.num==-34)
+
+-- Now test member function pointers
+func1_ptr=cb.get_func1_ptr()
+func2_ptr=cb.get_func2_ptr()
+f.num=4
+assert(f:func1(2)==16)
+assert(f:func2(2)==-8)
+
+f.func_ptr=func1_ptr
+assert(cb.test_func_ptr(f,2)==16)
+f.func_ptr=func2_ptr
+assert(cb.test_func_ptr(f,2)==-8)
diff --git a/trunk/Examples/test-suite/lua/disown_runme.lua b/trunk/Examples/test-suite/lua/disown_runme.lua
new file mode 100644
index 0000000..2707589
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/disown_runme.lua
@@ -0,0 +1,12 @@
+require("import")	-- the import fn
+import("disown")	-- import code
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+for x=0,100 do
+    a=disown.A()
+    b=disown.B()
+    b:acquire(a)
+end
+collectgarbage() -- this will double delete unless the memory is managed properly
diff --git a/trunk/Examples/test-suite/lua/dynamic_cast_runme.lua b/trunk/Examples/test-suite/lua/dynamic_cast_runme.lua
new file mode 100644
index 0000000..6e0a1d2
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/dynamic_cast_runme.lua
@@ -0,0 +1,15 @@
+require("import")	-- the import fn
+import("dynamic_cast")	-- import code
+
+f = dynamic_cast.Foo()
+b = dynamic_cast.Bar()
+
+x = f:blah()
+y = b:blah()
+
+-- swig_type is a swiglua specific function which gets the swig_type_info's name
+assert(swig_type(f)==swig_type(x))
+assert(swig_type(b)==swig_type(y))
+
+-- the real test: is y a Foo* or a Bar*?
+assert(dynamic_cast.do_test(y)=="Bar::test")
diff --git a/trunk/Examples/test-suite/lua/enums_runme.lua b/trunk/Examples/test-suite/lua/enums_runme.lua
new file mode 100644
index 0000000..f96331c
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/enums_runme.lua
@@ -0,0 +1,20 @@
+require("import")	-- the import fn
+import("enums")	-- import lib
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+-- check values
+assert(enums.CSP_ITERATION_FWD==0)
+assert(enums.CSP_ITERATION_BWD==11)
+assert(enums.ABCDE==0)
+assert(enums.FGHJI==1)
+assert(enums.boo==0)
+assert(enums.hoo==5)
+assert(enums.globalinstance1==0)
+assert(enums.globalinstance2==1)
+assert(enums.globalinstance3==30)
+assert(enums.AnonEnum1==0)
+assert(enums.AnonEnum2==100)
+
+-- no point in checking fns, C will allow any value
diff --git a/trunk/Examples/test-suite/lua/exception_order_runme.lua b/trunk/Examples/test-suite/lua/exception_order_runme.lua
new file mode 100644
index 0000000..e5caa83
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/exception_order_runme.lua
@@ -0,0 +1,45 @@
+-- demo of lua swig capacilities (operator overloading)
+require("import")	-- the import fn
+import("exception_order")	-- import lib into global
+eo=exception_order --alias
+
+-- catching undefined variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+a = eo.A()
+
+function try1()
+	a:foo()
+end
+
+function try2()
+	a:bar()
+end
+
+function try3()
+	a:foobar()
+end
+
+-- the following code used to work
+-- but now no longer works, as the lua bindings don't throw objects any more
+-- all objects are converted to string & thrown
+-- it could be made to work, if E1 & E2 were thrown by value (see lua.swg)
+--[[
+ok,ex=pcall(try1)
+print(ok,ex)
+assert(ok==false and swig_type(ex)==swig_type(eo.E1()))
+
+ok,ex=pcall(try2)
+assert(ok==false and swig_type(ex)==swig_type(eo.E2()))
+]]
+-- this new code does work, but has to look at the string
+ok,ex=pcall(try1)
+assert(ok==false and ex=="object exception:E1")
+
+ok,ex=pcall(try2)
+assert(ok==false and ex=="object exception:E2")
+
+-- the SWIG_exception is just an error string
+ok,ex=pcall(try3)
+assert(ok==false and type(ex)=="string")
+
diff --git a/trunk/Examples/test-suite/lua/exception_partial_info_runme.lua b/trunk/Examples/test-suite/lua/exception_partial_info_runme.lua
new file mode 100644
index 0000000..fb0e514
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/exception_partial_info_runme.lua
@@ -0,0 +1,12 @@
+require("import")	-- the import fn
+import("exception_partial_info")	-- import code
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+imp=exception_partial_info.Impl()
+
+-- trying to call throwing methods
+-- should fail
+assert(pcall(function() imp:f1() end)==false)
+assert(pcall(function() imp:f2() end)==false)
diff --git a/trunk/Examples/test-suite/lua/import.lua b/trunk/Examples/test-suite/lua/import.lua
new file mode 100644
index 0000000..eaab3b4
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/import.lua
@@ -0,0 +1,28 @@
+-- import
+-- the lua 5.0 loading mechanism is rather poor & relies upon the loadlib() fn
+-- the lua 5.1 loading mechanism is simplicity itself
+-- for now we need a bridge which will use the correct verion
+
+function import_5_0(name)
+	-- imports the file into the program
+	-- for a module 'example'
+	-- this must load 'example.dll' or 'example.so'
+	-- and look for the fn 'luaopen_example()'
+	if rawget(_G,name)~=nil then return end -- module appears to be loaded
+		
+	local lib=loadlib(name..'.dll','luaopen_'..name) or loadlib(name..'.so','luaopen_'..name)
+	assert(lib,"error loading module:"..name)
+	
+	lib() -- execute the function: initalising the lib
+	assert(rawget(_G,name)~=nil,"no module table found")
+end
+
+function import_5_1(name)
+	require(name)
+end
+
+if string.sub(_VERSION,1,7)=='Lua 5.0' then
+	import=import_5_0
+else
+	import=import_5_1
+end
\ No newline at end of file
diff --git a/trunk/Examples/test-suite/lua/import_nomodule_runme.lua b/trunk/Examples/test-suite/lua/import_nomodule_runme.lua
new file mode 100644
index 0000000..947aceb
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/import_nomodule_runme.lua
@@ -0,0 +1,14 @@
+require("import")	-- the import fn
+import("import_nomodule")	-- import code
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+f = import_nomodule.create_Foo()
+import_nomodule.test1(f,42)
+import_nomodule.delete_Foo(f)
+
+b = import_nomodule.Bar()
+import_nomodule.test1(b,37)
+
+collectgarbage()
\ No newline at end of file
diff --git a/trunk/Examples/test-suite/lua/imports_runme.lua b/trunk/Examples/test-suite/lua/imports_runme.lua
new file mode 100644
index 0000000..1509e17
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/imports_runme.lua
@@ -0,0 +1,28 @@
+require("import")	-- the import fn
+-- need to load two modules
+import("imports_a")	-- import code
+import("imports_b")	-- import code
+
+b=imports_b.B()
+b:hello() -- call member function in A which is in a different SWIG generated library.
+b:bye()
+
+assert (b:member_virtual_test(imports_a.A_memberenum1) == imports_a.A_memberenum2)
+assert (b:global_virtual_test(imports_a.globalenum1) == imports_a.globalenum2)
+
+imports_b.global_test(imports_a.A_memberenum1)
+
+--[[    B b = new B();
+    b.hello(); //call member function in A which is in a different SWIG generated library.
+
+            B b = new B();
+        b.hello(); //call member function in A which is in a different SWIG generated library.
+        b.bye();
+
+        if (b.member_virtual_test(A.MemberEnum.memberenum1) != A.MemberEnum.memberenum2)
+          throw new Exception("Test 1 failed");
+        if (b.global_virtual_test(GlobalEnum.globalenum1) != GlobalEnum.globalenum2)
+          throw new Exception("Test 2 failed");
+
+        imports_b.global_test(A.MemberEnum.memberenum1);
+]]
diff --git a/trunk/Examples/test-suite/lua/li_carrays_runme.lua b/trunk/Examples/test-suite/lua/li_carrays_runme.lua
new file mode 100644
index 0000000..c54e36a
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/li_carrays_runme.lua
@@ -0,0 +1,29 @@
+require("import")	-- the import fn
+import("li_carrays")	-- import code
+
+-- moving to global
+for k,v in pairs(li_carrays) do _G[k]=v end
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+-- Testing for %array_functions(int,intArray)
+ary = new_intArray(2)
+intArray_setitem(ary, 0, 0)
+intArray_setitem(ary, 1, 1)
+assert(intArray_getitem(ary, 0)==0)
+assert(intArray_getitem(ary, 1)==1)
+delete_intArray(ary)
+
+-- Testing for %array_class(double, doubleArray)
+d = doubleArray(10)
+d[0] = 7
+d[5] = d[0] + 3
+assert(d[5] + d[0] == 17)
+--print(d[5] + d[0])
+
+ptr = d:cast()	-- to ptr
+d2 = doubleArray_frompointer(ptr) -- and back to array
+assert(d2[5] + d2[0] == 17)
+--print(d2[5] + d2[0])
+
diff --git a/trunk/Examples/test-suite/lua/li_std_except_runme.lua b/trunk/Examples/test-suite/lua/li_std_except_runme.lua
new file mode 100644
index 0000000..014368f
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/li_std_except_runme.lua
@@ -0,0 +1,16 @@
+require("import")	-- the import fn
+import("li_std_except")	-- import code
+
+test = li_std_except.Test()
+-- under lua, all the std::exceptions are just turned to strings, so we are only checking that is fails
+assert(pcall(function() test:throw_bad_exception() end)==false)
+assert(pcall(function() test:throw_domain_error() end)==false)
+assert(pcall(function() test:throw_exception() end)==false)
+assert(pcall(function() test:throw_invalid_argument() end)==false)
+assert(pcall(function() test:throw_length_error() end)==false)
+assert(pcall(function() test:throw_logic_error() end)==false)
+assert(pcall(function() test:throw_out_of_range() end)==false)
+assert(pcall(function() test:throw_overflow_error() end)==false)
+assert(pcall(function() test:throw_range_error() end)==false)
+assert(pcall(function() test:throw_runtime_error() end)==false)
+assert(pcall(function() test:throw_underflow_error() end)==false)
diff --git a/trunk/Examples/test-suite/lua/li_std_pair_runme.lua b/trunk/Examples/test-suite/lua/li_std_pair_runme.lua
new file mode 100644
index 0000000..793eaa8
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/li_std_pair_runme.lua
@@ -0,0 +1,34 @@
+require("import")	-- the import fn
+import("li_std_pair")	-- import code
+
+for k,v in pairs(li_std_pair) do _G[k]=v end -- move to global
+
+intPair = makeIntPair(7, 6)
+assert(intPair.first==7 and intPair.second==6)
+
+intPairPtr = makeIntPairPtr(7, 6)
+assert(intPairPtr.first==7 and intPairPtr.second==6)
+
+intPairRef = makeIntPairRef(7, 6)
+assert(intPairRef.first == 7 and intPairRef.second == 6)
+
+intPairConstRef = makeIntPairConstRef(7, 6)
+assert(intPairConstRef.first == 7 and intPairConstRef.second == 6)
+
+-- call fns
+assert(product1(intPair) == 42)
+assert(product2(intPair) == 42)
+assert(product3(intPair) == 42)
+
+-- also use the pointer version
+assert(product1(intPairPtr) == 42)
+assert(product2(intPairPtr) == 42)
+assert(product3(intPairPtr) == 42)
+
+-- or the other types
+assert(product1(intPairRef) == 42)
+assert(product2(intPairRef) == 42)
+assert(product3(intPairRef) == 42)
+assert(product1(intPairConstRef) == 42)
+assert(product2(intPairConstRef) == 42)
+assert(product3(intPairConstRef) == 42)
diff --git a/trunk/Examples/test-suite/lua/li_std_string_runme.lua b/trunk/Examples/test-suite/lua/li_std_string_runme.lua
new file mode 100644
index 0000000..70461f7
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/li_std_string_runme.lua
@@ -0,0 +1,113 @@
+require("import")	-- the import fn
+import("li_std_string")	-- import lib
+
+for k,v in pairs(li_std_string) do _G[k]=v end -- move to global
+
+-- catch "undefined" global variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+-- helper to check type
+function is_std_string(s) 
+	return type(s)=='userdata' and swig_type(s)=='std::string *'
+end
+
+-- std::string by value is just a Lua string
+s=test_value("foo")
+assert(type(s)=="string" and s=="foo")
+
+-- std::string by const ref is also just a Lua string
+s=test_const_reference("foo")
+assert(type(s)=="string" and s=="foo")
+
+-- std:string* is an object
+obj=test_pointer_out()
+assert(is_std_string(obj) and obj:c_str()=="x")	-- check type & value
+
+test_pointer(obj)	-- this wants an object
+
+cobj=test_const_pointer_out()
+assert(is_std_string(cobj) and cobj:c_str()=="x")	-- check type & value
+
+test_const_pointer(cobj)
+
+-- this shouldnt work, but it does
+-- swig doesnt appear to diff between const object ptrs & object ptrs very well
+test_pointer(cobj)	-- this wants an non const object (give it a const one!)
+
+-- refs are also wrappered as ptrs (unless the correct typemaps are applied)
+robj=test_reference_out()
+assert(is_std_string(robj) and robj:c_str()=="test_reference_out message")	-- check type & value
+
+test_reference(robj)
+test_reference(obj)	-- object ptr is ok
+test_reference(cobj)	-- obj const ptr is also ok
+
+-- throwing string
+ok,ex=pcall(test_throw)
+assert(ok==false and type(ex)=="string")	-- failed & threw string
+
+ok,ex=pcall(test_const_reference_throw)
+assert(ok==false and type(ex)=="string")	-- failed & threw string
+
+-- const ptrs are now converted to lua strings
+-- they used to be std::string*
+ok,ex=pcall(test_const_pointer_throw)
+assert(ok==false and type(ex)=="string")	-- failed & threw object
+
+-- ditto non const ptrs 
+ok,ex=pcall(test_pointer_throw)
+assert(ok==false and type(ex)=="string")	-- failed & threw object
+
+-- testing std::string variables
+-- Global variables
+s = "initial string"
+assert (li_std_string.GlobalString2 == "global string 2")
+li_std_string.GlobalString2 = s
+assert (li_std_string.GlobalString2 == s)
+assert (li_std_string.ConstGlobalString == "const global string")
+
+-- Member variables
+myStructure = Structure()
+assert(myStructure.MemberString2 == "member string 2")
+myStructure.MemberString2 = s
+assert (myStructure.MemberString2 == s)
+assert (myStructure.ConstMemberString == "const member string")
+
+assert (li_std_string.Structure_StaticMemberString2 == "static member string 2")
+li_std_string.Structure_StaticMemberString2 = s
+assert (li_std_string.Structure_StaticMemberString2 == s)
+assert (li_std_string.Structure_ConstStaticMemberString == "const static member string")
+
+
+-- testing the structure (these are some old tests which predated the std::string variable tests above)
+struc=Structure()
+
+assert(type(struc.MemberString2)=="string") -- typemaps make this a string
+assert(type(struc.ConstMemberString)=="string")
+
+-- set a const (should fail with error)
+assert(pcall(function () struc.ConstMemberString="c" end)==false)
+--print(struc.MemberString:data(),struc.MemberString2,struc.ConstMemberString:data())
+
+--check type again
+assert(type(struc.MemberString2)=="string") -- typemaps make this a string
+assert(type(struc.ConstMemberString)=="string")
+
+-- for static types: they are really variables, 
+-- so we must still use the module name
+
+-- check static type
+assert(type(li_std_string.Structure_StaticMemberString2)=="string")
+assert(type(li_std_string.Structure_ConstStaticMemberString)=="string")
+
+-- try setting (should fail with error)
+--li_std_string.Structure_StaticMemberString2='e'
+assert(pcall(function () li_std_string.Structure_ConstStaticMemberString='f' end)==false)
+--[[print(li_std_string.Structure_StaticMemberString:data(),
+		li_std_string.Structure_StaticMemberString2,
+		li_std_string.Structure_ConstStaticMemberString:data())]]
+
+-- check static type again
+assert(type(li_std_string.Structure_StaticMemberString)=="string")
+assert(type(li_std_string.Structure_StaticMemberString2)=="string")
+assert(type(li_std_string.Structure_ConstStaticMemberString)=="string")
diff --git a/trunk/Examples/test-suite/lua/li_std_vector_runme.lua b/trunk/Examples/test-suite/lua/li_std_vector_runme.lua
new file mode 100644
index 0000000..81994b9
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/li_std_vector_runme.lua
@@ -0,0 +1,66 @@
+require("import")	-- the import fn
+import("li_std_vector")	-- import code
+
+for k,v in pairs(li_std_vector) do _G[k]=v end -- move to global
+
+iv = IntVector(4)
+for i=0,3 do
+    iv[i] = i
+end
+
+for i=0,3 do assert(iv[i]==i) end
+
+x = average(iv)
+
+function near(x,y) return math.abs(x-y)<0.001 end
+
+assert(near(x,1.5))
+
+rv = RealVector()
+rv:push_back(10)
+rv:push_back(10.5)
+rv:push_back(11)
+rv:push_back(11.5)
+
+a=half(rv)
+for i=0,rv:size()-1 do
+	assert(near(a[i],rv[i]/2))
+end
+
+dv = DoubleVector(10)
+for i=0,9 do dv[i] = i/2.0 end
+
+halve_in_place(dv)
+
+for i=0,9 do 
+	assert(near(dv[i],i/4))
+end
+
+sv=StructVector(4)
+
+for i=0,3 do
+	sv[i]=Struct(i)
+end
+
+for i=0,3 do
+	assert( swig_type(sv[i]) =='Struct *' and sv[i].num==i)
+end
+
+-- range checking
+idx=0
+function test_set() iv[idx]=0 end
+function test_get() iv[idx]=0 end
+
+idx=0 --ok
+assert(pcall(test_get)==true)
+assert(pcall(test_set)==true)
+idx=-1 --should error
+assert(pcall(test_get)==false)
+assert(pcall(test_set)==false)
+idx=3 --ok
+assert(pcall(test_get)==true)
+assert(pcall(test_set)==true)
+idx=4 --should error
+assert(pcall(test_get)==false)
+assert(pcall(test_set)==false)
+
diff --git a/trunk/Examples/test-suite/lua/li_typemaps_runme.lua b/trunk/Examples/test-suite/lua/li_typemaps_runme.lua
new file mode 100644
index 0000000..77aeb54
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/li_typemaps_runme.lua
@@ -0,0 +1,40 @@
+require("import")	-- the import fn

+import("li_typemaps")	-- import code

+

+-- catch "undefined" global variables

+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})

+

+-- Check double INPUT typemaps

+assert(li_typemaps.in_double(22.22) == 22.22)

+assert(li_typemaps.inr_double(22.22) == 22.22)

+

+-- Check double OUTPUT typemaps

+assert(li_typemaps.out_double(22.22) == 22.22)

+assert(li_typemaps.outr_double(22.22) == 22.22)

+

+-- Check double INOUT typemaps

+assert(li_typemaps.inout_double(22.22) == 22.22)

+assert(li_typemaps.inoutr_double(22.22) == 22.22)

+

+-- check long long

+assert(li_typemaps.in_ulonglong(20)==20)

+assert(li_typemaps.inr_ulonglong(20)==20)

+assert(li_typemaps.out_ulonglong(20)==20)

+assert(li_typemaps.outr_ulonglong(20)==20)

+assert(li_typemaps.inout_ulonglong(20)==20)

+assert(li_typemaps.inoutr_ulonglong(20)==20)

+

+-- check bools

+assert(li_typemaps.in_bool(true)==true)

+assert(li_typemaps.inr_bool(false)==false)

+assert(li_typemaps.out_bool(true)==true)

+assert(li_typemaps.outr_bool(false)==false)

+assert(li_typemaps.inout_bool(true)==true)

+assert(li_typemaps.inoutr_bool(false)==false)

+

+-- the others

+a,b=li_typemaps.inoutr_int2(1,2)

+assert(a==1 and b==2)

+

+f,i=li_typemaps.out_foo(10)

+assert(f.a==10 and i==20)

diff --git a/trunk/Examples/test-suite/lua/member_pointer_runme.lua b/trunk/Examples/test-suite/lua/member_pointer_runme.lua
new file mode 100644
index 0000000..8dddab2
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/member_pointer_runme.lua
@@ -0,0 +1,43 @@
+--Example using pointers to member functions
+
+require("import")	-- the import fn
+import("member_pointer")	-- import code
+
+for k,v in pairs(member_pointer) do _G[k]=v end
+
+function check(what, expected, actual)
+	assert(expected == actual,"Failed: "..what.." Expected: "..expected.." Actual: "..actual)
+end
+
+-- Get the pointers
+area_pt = areapt()
+perim_pt = perimeterpt()
+
+-- Create some objects
+s = Square(10)
+
+-- Do some calculations
+check ("Square area ", 100.0, do_op(s,area_pt))
+check ("Square perim", 40.0, do_op(s,perim_pt))
+
+-- Try the variables
+-- these have to still be part of the 'member_pointer' table
+memberPtr = member_pointer.areavar
+memberPtr = member_pointer.perimetervar
+
+check ("Square area ", 100.0, do_op(s,member_pointer.areavar))
+check ("Square perim", 40.0, do_op(s,member_pointer.perimetervar))
+
+-- Modify one of the variables
+member_pointer.areavar = perim_pt
+
+check ("Square perimeter", 40.0, do_op(s,member_pointer.areavar))
+
+-- Try the constants
+memberPtr = AREAPT
+memberPtr = PERIMPT
+memberPtr = NULLPT
+
+check ("Square area ", 100.0, do_op(s,AREAPT))
+check ("Square perim", 40.0, do_op(s,PERIMPT))
+
diff --git a/trunk/Examples/test-suite/lua/multi_import_runme.lua b/trunk/Examples/test-suite/lua/multi_import_runme.lua
new file mode 100644
index 0000000..5d4c136
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/multi_import_runme.lua
@@ -0,0 +1,16 @@
+require("import")	-- the import fn
+-- note: need to import the base class module before the derived class
+-- this is because if the derived class is imported first it doesn't get the base class methods
+import("multi_import_b")	-- import code
+import("multi_import_a")	-- import code
+
+x = multi_import_b.XXX()
+assert(x:testx() == 0)
+
+y = multi_import_b.YYY()
+assert(y:testx() == 0)
+assert(y:testy() == 1)
+
+z = multi_import_a.ZZZ()
+assert(z:testx() == 0)
+assert(z:testz() == 2)
diff --git a/trunk/Examples/test-suite/lua/newobject1_runme.lua b/trunk/Examples/test-suite/lua/newobject1_runme.lua
new file mode 100644
index 0000000..5de8276
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/newobject1_runme.lua
@@ -0,0 +1,16 @@
+require("import")	-- the import fn
+import("newobject1")	-- import code
+
+foo1 = newobject1.Foo_makeFoo()	-- lua doesnt yet support static fns properly
+assert(newobject1.Foo_fooCount() == 1)	-- lua doesnt yet support static fns properly
+
+foo2 = foo1:makeMore()
+assert(newobject1.Foo_fooCount() == 2)
+
+foo1 = nil 
+collectgarbage()
+assert(newobject1.Foo_fooCount() == 1)
+
+foo2 = nil 
+collectgarbage()
+assert(newobject1.Foo_fooCount() == 0)
diff --git a/trunk/Examples/test-suite/lua/newobject2_runme.lua b/trunk/Examples/test-suite/lua/newobject2_runme.lua
new file mode 100644
index 0000000..cf6c87a
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/newobject2_runme.lua
@@ -0,0 +1,16 @@
+require("import")	-- the import fn
+import("newobject2",true)	-- import code
+
+foo1 = newobject2.makeFoo()	-- lua doesnt yet support static fns properly
+assert(newobject2.fooCount() == 1)	-- lua doesnt yet support static fns properly
+
+foo2 = newobject2.makeFoo()
+assert(newobject2.fooCount() == 2)
+
+foo1 = nil 
+collectgarbage()
+assert(newobject2.fooCount() == 1)
+
+foo2 = nil 
+collectgarbage()
+assert(newobject2.fooCount() == 0)
diff --git a/trunk/Examples/test-suite/lua/operator_overload_runme.lua b/trunk/Examples/test-suite/lua/operator_overload_runme.lua
new file mode 100644
index 0000000..1610c17
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/operator_overload_runme.lua
@@ -0,0 +1,157 @@
+-- demo of lua swig capacilities (operator overloading)
+require("import")	-- the import fn
+import("operator_overload")	-- import lib
+
+for k,v in pairs(operator_overload) do _G[k]=v end -- move to global
+
+-- first check all the operators are implemented correctly from pure C++ code
+Op_sanity_check()
+
+-- catching undefined variables
+setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
+
+-- test routine:
+a=Op()
+b=Op(5)
+c=Op(b) -- copy construct
+d=Op(2)
+dd=d; -- assignment operator
+
+-- test equality
+assert(a~=b)
+assert(b==c)
+assert(a~=d)
+assert(d==dd)
+
+-- test <
+assert(a<b)
+assert(a<=b)
+assert(b<=c)
+assert(b>=c)
+assert(b>d)
+assert(b>=d)
+
+-- lua does not support += operators: skiping
+
+-- test +
+f=Op(1)
+g=Op(1)
+assert(f+g==Op(2))
+assert(f-g==Op(0))
+assert(f*g==Op(1))
+assert(f/g==Op(1))
+--assert(f%g==Op(0))	-- lua does not support %
+
+-- test unary operators
+--assert((not a)==true) -- lua does not allow overloading for not operator
+--assert((not b)==false) -- lua does not allow overloading for not operator
+
+--lua 5.0.2 defines that unary - is __unm(self,nil)
+--lua 5.1.2 defines that unary - is __unm(self,self)
+--C++ expectes unary - as operator-()
+--however the latest version of SWIG strictly checks the number of args
+--and will complain if too many args are provided
+--therefore disabling these tests for now
+-- (solution will to be not to check args for this test case)
+assert(-a==a)
+assert(-b==Op(-5))
+
+-- test []
+h=Op(3)
+assert(h[0]==3)
+assert(h[1]==0)
+h[0]=2	-- set
+assert(h[0]==2)
+h[1]=2	-- ignored
+assert(h[0]==2)
+assert(h[1]==0)
+
+-- test ()
+i=Op(3)
+assert(i()==3)
+assert(i(1)==4)
+assert(i(1,2)==6)
+
+-- plus add some code to check the __str__ fn
+assert(tostring(Op(1))=="Op(1)")
+assert(tostring(Op(-3))=="Op(-3)")
+
+--[[
+/* Sample test code in C++
+
+#include <assert.h>
+#include <stdio.h>
+
+int main(int argc,char** argv)
+{
+	// test routine:
+	Op a;
+	Op b=5;
+	Op c=b;	// copy construct
+	Op d=2;
+
+	// test equality
+	assert(a!=b);
+	assert(b==c);
+	assert(a!=d);
+
+	// test <
+	assert(a<b);
+	assert(a<=b);
+	assert(b<=c);
+	assert(b>=c);
+	assert(b>d);
+	assert(b>=d);
+
+	// test +=
+	Op e=3;
+	e+=d;
+	assert(e==b);
+	e-=c;
+	assert(e==a);
+	e=Op(1);
+	e*=b;
+	assert(e==c);
+	e/=d;
+	assert(e==d);
+	e%=c;
+	assert(e==d);
+
+	// test +
+	Op f(1),g(1);
+	assert(f+g==Op(2));
+	assert(f-g==Op(0));
+	assert(f*g==Op(1));
+	assert(f/g==Op(1));
+	assert(f%g==Op(0));
+
+	// test unary operators
+	assert(!a==true);
+	assert(!b==false);
+	assert(-a==a);
+	assert(-b==Op(-5));
+
+	// test []
+	Op h=3;
+	assert(h[0]==3);
+	assert(h[1]==0);
+	h[0]=2;	// set
+	assert(h[0]==2);
+	h[1]=2;	// ignored
+	assert(h[0]==2);
+	assert(h[1]==0);
+
+	// test ()
+	Op i=3;
+	assert(i()==3);
+	assert(i(1)==4);
+	assert(i(1,2)==6);
+
+	// plus add some code to check the __str__ fn
+	//assert(str(Op(1))=="Op(1)");
+	//assert(str(Op(-3))=="Op(-3)");
+
+	printf("ok\n");
+}
+*/
+]]
diff --git a/trunk/Examples/test-suite/lua/overload_simple_runme.lua b/trunk/Examples/test-suite/lua/overload_simple_runme.lua
new file mode 100644
index 0000000..97b1876
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/overload_simple_runme.lua
@@ -0,0 +1,55 @@
+require("import")	-- the import fn
+import("overload_simple")	-- import code
+for k,v in pairs(overload_simple) do _G[k]=v end -- move to global
+
+-- lua has only one numeric type, foo(int) and foo(double) are the same
+-- whichever one was wrapper first will be used
+
+assert(foo(3)=="foo:int" or foo(3)=="foo:double") -- could be either
+assert(foo("hello")=="foo:char *")
+
+f=Foo()
+b=Bar()
+
+assert(foo(f)=="foo:Foo *")
+assert(foo(b)=="foo:Bar *")
+
+v = malloc_void(32)
+
+assert(foo(v) == "foo:void *")
+
+s = Spam()
+
+assert(s:foo(3) == "foo:int" or s:foo(3.0) == "foo:double") -- could be either
+assert(s:foo("hello") == "foo:char *")
+assert(s:foo(f) == "foo:Foo *")
+assert(s:foo(b) == "foo:Bar *")
+assert(s:foo(v) == "foo:void *")
+
+assert(Spam_bar(3) == "bar:int" or Spam_bar(3.0) == "bar:double")
+assert(Spam_bar("hello") == "bar:char *")
+assert(Spam_bar(f) == "bar:Foo *")
+assert(Spam_bar(b) == "bar:Bar *")
+assert(Spam_bar(v) == "bar:void *")
+
+-- Test constructors
+
+s = Spam()
+assert(s.type == "none")
+
+s = Spam(3)
+assert(s.type == "int" or s.type == "double")
+
+s = Spam("hello")
+assert(s.type == "char *")
+
+s = Spam(f)
+assert(s.type == "Foo *")
+
+s = Spam(b)
+assert(s.type == "Bar *")
+
+s = Spam(v)
+assert(s.type == "void *")
+
+free_void(v)
diff --git a/trunk/Examples/test-suite/lua/overload_template_fast_runme.lua b/trunk/Examples/test-suite/lua/overload_template_fast_runme.lua
new file mode 100644
index 0000000..97078f3
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/overload_template_fast_runme.lua
@@ -0,0 +1,81 @@
+require("import")	-- the import fn
+import("overload_template_fast")	-- import code
+for k,v in pairs(overload_template_fast) do _G[k]=v end -- move to global
+
+-- lua has only one numeric type, so max(int,int) and max(double,double) are the same
+-- whichever one was wrapper first will be used (which is int)
+
+f = foo()
+
+a = max(3,4)
+
+-- mix 1
+assert(mix1("hi") == 101)
+assert(mix1(1.0, 1.0) == 102)
+assert(mix1(1.0) == 103)
+
+-- mix 2
+assert(mix2("hi") == 101)
+assert(mix2(1.0, 1.0) == 102)
+assert(mix2(1.0) == 103)
+
+-- mix 3
+assert(mix3("hi") == 101)
+assert(mix3(1.0, 1.0) == 102)
+assert(mix3(1.0) == 103)
+
+-- Combination 1
+assert(overtparams1(100) == 10)
+assert(overtparams1(100.0, 100) == 20)
+
+-- Combination 2
+assert(overtparams2(100.0, 100) == 40)
+
+-- Combination 3
+assert(overloaded() == 60)
+assert(overloaded(100.0, 100) == 70)
+
+-- Combination 4
+assert(overloadedagain("hello") == 80)
+assert(overloadedagain() == 90)
+
+-- specializations
+assert(specialization(10) == 202 or specialization(10.0) == 203) -- only one works
+assert(specialization(10, 10) == 204 or specialization(10.0, 10.0) == 205) -- ditto
+assert(specialization("hi", "hi") == 201)
+
+-- simple specialization
+xyz()
+xyz_int()
+xyz_double()
+
+-- a bit of everything
+assert(overload("hi") == 0)
+assert(overload(1) == 10)
+assert(overload(1, 1) == 20)
+assert(overload(1, "hello") == 30)
+
+k = Klass()
+assert(overload(k) == 10)
+assert(overload(k, k) == 20)
+assert(overload(k, "hello") == 30)
+-- this one is incorrect: it mactches overload(10.0, "hi") with int overload(T t, const char *c)
+--print(overload(10.0, "hi"))
+--assert(overload(10.0, "hi") == 40)
+assert(overload() == 50)
+
+-- everything put in a namespace
+assert(nsoverload("hi") == 1000,"nsoverload()")
+assert(nsoverload(1) == 1010,"nsoverload(int t)")
+assert(nsoverload(1, 1) == 1020,"nsoverload(int t, const int &)")
+assert(nsoverload(1, "hello") == 1030,"nsoverload(int t, const char *)")
+assert(nsoverload(k) == 1010,"nsoverload(Klass t)")
+assert(nsoverload(k, k) == 1020,"nsoverload(Klass t, const Klass &)")
+assert(nsoverload(k, "hello") == 1030,"nsoverload(Klass t, const char *)")
+-- again this one fails
+--assert(nsoverload(10.0, "hi") == 1040,"nsoverload(double t, const char *)")
+assert(nsoverload() == 1050,"nsoverload(const char *)")
+
+A_foo(1)
+b = B()
+b:foo(1)
diff --git a/trunk/Examples/test-suite/lua/overload_template_runme.lua b/trunk/Examples/test-suite/lua/overload_template_runme.lua
new file mode 100644
index 0000000..c62a42c
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/overload_template_runme.lua
@@ -0,0 +1,81 @@
+require("import")	-- the import fn
+import("overload_template")	-- import code
+for k,v in pairs(overload_template) do _G[k]=v end -- move to global
+
+-- lua has only one numeric type, so max(int,int) and max(double,double) are the same
+-- whichever one was wrapper first will be used (which is int)
+
+f = foo()
+
+a = max(3,4)
+
+-- mix 1
+assert(mix1("hi") == 101)
+assert(mix1(1.0, 1.0) == 102)
+assert(mix1(1.0) == 103)
+
+-- mix 2
+assert(mix2("hi") == 101)
+assert(mix2(1.0, 1.0) == 102)
+assert(mix2(1.0) == 103)
+
+-- mix 3
+assert(mix3("hi") == 101)
+assert(mix3(1.0, 1.0) == 102)
+assert(mix3(1.0) == 103)
+
+-- Combination 1
+assert(overtparams1(100) == 10)
+assert(overtparams1(100.0, 100) == 20)
+
+-- Combination 2
+assert(overtparams2(100.0, 100) == 40)
+
+-- Combination 3
+assert(overloaded() == 60)
+assert(overloaded(100.0, 100) == 70)
+
+-- Combination 4
+assert(overloadedagain("hello") == 80)
+assert(overloadedagain() == 90)
+
+-- specializations
+assert(specialization(10) == 202 or specialization(10.0) == 203) -- only one works
+assert(specialization(10, 10) == 204 or specialization(10.0, 10.0) == 205) -- ditto
+assert(specialization("hi", "hi") == 201)
+
+-- simple specialization
+xyz()
+xyz_int()
+xyz_double()
+
+-- a bit of everything
+assert(overload("hi") == 0)
+assert(overload(1) == 10)
+assert(overload(1, 1) == 20)
+assert(overload(1, "hello") == 30)
+
+k = Klass()
+assert(overload(k) == 10)
+assert(overload(k, k) == 20)
+assert(overload(k, "hello") == 30)
+-- this one is incorrect: it mactches overload(10.0, "hi") with int overload(T t, const char *c)
+--print(overload(10.0, "hi"))
+--assert(overload(10.0, "hi") == 40)
+assert(overload() == 50)
+
+-- everything put in a namespace
+assert(nsoverload("hi") == 1000,"nsoverload()")
+assert(nsoverload(1) == 1010,"nsoverload(int t)")
+assert(nsoverload(1, 1) == 1020,"nsoverload(int t, const int &)")
+assert(nsoverload(1, "hello") == 1030,"nsoverload(int t, const char *)")
+assert(nsoverload(k) == 1010,"nsoverload(Klass t)")
+assert(nsoverload(k, k) == 1020,"nsoverload(Klass t, const Klass &)")
+assert(nsoverload(k, "hello") == 1030,"nsoverload(Klass t, const char *)")
+-- again this one fails
+--assert(nsoverload(10.0, "hi") == 1040,"nsoverload(double t, const char *)")
+assert(nsoverload() == 1050,"nsoverload(const char *)")
+
+A_foo(1)
+b = B()
+b:foo(1)
diff --git a/trunk/Examples/test-suite/lua/pointer_reference_runme.lua b/trunk/Examples/test-suite/lua/pointer_reference_runme.lua
new file mode 100644
index 0000000..959d5a2
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/pointer_reference_runme.lua
@@ -0,0 +1,11 @@
+require("import")	-- the import fn
+import("pointer_reference",true)	-- import code
+
+
+s=pointer_reference.get()
+assert(s.value == 10)
+
+ss = pointer_reference.Struct(20);
+pointer_reference.set(ss);
+assert(pointer_reference.Struct_instance.value == 20)
+
diff --git a/trunk/Examples/test-suite/lua/primitive_ref_runme.lua b/trunk/Examples/test-suite/lua/primitive_ref_runme.lua
new file mode 100644
index 0000000..d3da5dc
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/primitive_ref_runme.lua
@@ -0,0 +1,32 @@
+require("import")	-- the import fn
+import("primitive_ref")	-- import code
+pr=primitive_ref --alias
+
+assert(pr.ref_int(3)==3)
+
+assert(pr.ref_uint(3) == 3)
+
+assert(pr.ref_short(3) == 3)
+
+assert(pr.ref_ushort(3) == 3)
+
+assert(pr.ref_long(3) == 3)
+
+assert(pr.ref_ulong(3) == 3)
+
+assert(pr.ref_schar(3) == 3)
+
+assert(pr.ref_uchar(3) == 3)
+
+assert(pr.ref_float(3.5) == 3.5)
+
+assert(pr.ref_double(3.5) == 3.5)
+
+assert(pr.ref_bool(true) == true)
+
+assert(pr.ref_char('x') == 'x')
+
+assert(pr.ref_over(0) == 0)
+
+a=pr.A(12)
+assert(pr.ref_over(a)==12)
diff --git a/trunk/Examples/test-suite/lua/ret_by_value_runme.lua b/trunk/Examples/test-suite/lua/ret_by_value_runme.lua
new file mode 100644
index 0000000..f1f5c6c
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/ret_by_value_runme.lua
@@ -0,0 +1,6 @@
+require("import")	-- the import fn
+import("ret_by_value")	-- import code
+
+a = ret_by_value.get_test()
+assert(a.myInt == 100)
+assert(a.myShort == 200)
diff --git a/trunk/Examples/test-suite/lua/sizet_runme.lua b/trunk/Examples/test-suite/lua/sizet_runme.lua
new file mode 100644
index 0000000..fbaea6a
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/sizet_runme.lua
@@ -0,0 +1,9 @@
+require("import")	-- the import fn
+import("sizet")	-- import code
+
+s = 2000
+s = sizet.test1(s+1)
+s = sizet.test2(s+1)
+s = sizet.test3(s+1)
+s = sizet.test4(s+1)
+assert(s == 2004)
diff --git a/trunk/Examples/test-suite/lua/smart_pointer_overload_runme.lua b/trunk/Examples/test-suite/lua/smart_pointer_overload_runme.lua
new file mode 100644
index 0000000..b83bede
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/smart_pointer_overload_runme.lua
@@ -0,0 +1,14 @@
+require("import")	-- the import fn
+import("smart_pointer_overload")	-- import code
+for k,v in pairs(smart_pointer_overload) do _G[k]=v end -- move to global
+
+f = Foo()
+b = Bar(f)
+
+assert(f:test(3) == 1)
+--assert(f:test(3.5) == 2)	-- won't work due to being unable to overloads
+assert(f:test("hello") == 3)
+
+assert(b:test(3) == 1)
+--assert(b:test(3.5) == 2)	-- won't work due to being unable to overloads
+assert(b:test("hello") == 3)
diff --git a/trunk/Examples/test-suite/lua/template_default_arg_runme.lua b/trunk/Examples/test-suite/lua/template_default_arg_runme.lua
new file mode 100644
index 0000000..ebb22ed
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/template_default_arg_runme.lua
@@ -0,0 +1,63 @@
+require("import")	-- the import fn
+import("template_default_arg")	-- import code
+--for k,v in pairs(template_default_arg) do _G[k]=v end -- move to global
+
+helloInt = template_default_arg.Hello_int()
+helloInt:foo(template_default_arg.Hello_int_hi)
+
+x = template_default_arg.X_int()
+assert(x:meth(20.0, 200) == 200,"X_int test 1 failed")
+assert(x:meth(20) == 20,"X_int test 2 failed")
+assert(x:meth() == 0,"X_int test 3 failed")
+
+y = template_default_arg.Y_unsigned()
+assert(y:meth(20.0, 200) == 200,"Y_unsigned test 1 failed")
+assert(y:meth(20) == 20,"Y_unsigned test 2 failed")
+assert(y:meth() == 0,"Y_unsigned test 3 failed")
+
+x = template_default_arg.X_longlong()
+x = template_default_arg.X_longlong(20.0)
+x = template_default_arg.X_longlong(20.0, 200) -- note: long longs just treated as another number
+
+x = template_default_arg.X_int()
+x = template_default_arg.X_int(20.0)
+x = template_default_arg.X_int(20.0, 200)
+
+x = template_default_arg.X_hello_unsigned()
+x = template_default_arg.X_hello_unsigned(20.0)
+x = template_default_arg.X_hello_unsigned(20.0, template_default_arg.Hello_int())
+
+y = template_default_arg.Y_hello_unsigned()
+y:meth(20.0, template_default_arg.Hello_int())
+y:meth(template_default_arg.Hello_int())
+y:meth()
+
+fz = template_default_arg.Foo_Z_8()
+x = template_default_arg.X_Foo_Z_8()
+fzc = x:meth(fz)
+
+-- Templated functions
+
+-- plain function: int ott(Foo<int>)
+assert(template_default_arg.ott(template_default_arg.Foo_int()) == 30,"ott test 1 failed")
+
+-- %template(ott) ott<int, int>
+assert(template_default_arg.ott() == 10,"ott test 2 failed")
+assert(template_default_arg.ott(1) == 10,"ott test 3 failed")
+assert(template_default_arg.ott(1, 1) == 10,"ott test 4 failed")
+
+assert(template_default_arg.ott("hi") == 20,"ott test 5 failed")
+assert(template_default_arg.ott("hi", 1) == 20,"ott test 6 failed")
+assert(template_default_arg.ott("hi", 1, 1) == 20,"ott test 7 failed")
+ 
+-- %template(ott) ott<const char *>
+assert(template_default_arg.ottstring(template_default_arg.Hello_int(), "hi") == 40,"ott test 8 failed")
+assert(template_default_arg.ottstring(template_default_arg.Hello_int()) == 40,"ott test 9 failed")
+
+-- %template(ott) ott<int>
+assert(template_default_arg.ottint(template_default_arg.Hello_int(), 1) == 50,"ott test 10 failed")
+assert(template_default_arg.ottint(template_default_arg.Hello_int()) == 50,"ott test 11 failed")
+
+-- %template(ott) ott<double>
+assert(template_default_arg.ott(template_default_arg.Hello_int(), 1.0) == 60,"ott test 12 failed")
+assert(template_default_arg.ott(template_default_arg.Hello_int()) == 60,"ott test 13 failed")
diff --git a/trunk/Examples/test-suite/lua/voidtest_runme.lua b/trunk/Examples/test-suite/lua/voidtest_runme.lua
new file mode 100644
index 0000000..e185dbd
--- /dev/null
+++ b/trunk/Examples/test-suite/lua/voidtest_runme.lua
@@ -0,0 +1,37 @@
+-- demo of lua swig
+require("import")	-- the import fn
+import("voidtest")	-- import lib
+
+-- test calling functions
+voidtest.globalfunc()
+f = voidtest.Foo()
+f:memberfunc()  -- member fns must have : not a .
+
+voidtest.Foo_staticmemberfunc() -- static member fns are still a little messy
+
+v1 = voidtest.vfunc1(f)
+v2 = voidtest.vfunc2(f)
+
+assert(swig_equals(v1,v2)) -- a raw equals will not work, we look at the raw pointers
+
+v3 = voidtest.vfunc3(v1)
+assert(swig_equals(v3,f))
+
+v4 = voidtest.vfunc1(f)
+assert(swig_equals(v4,v1))
+
+v3:memberfunc()
+
+-- also testing nil's support
+-- nil, are acceptable anywhere a pointer is
+n1 = voidtest.vfunc1(nil)
+n2 = voidtest.vfunc2(nil)
+
+assert(n1==nil)
+assert(n2==nil)
+
+n3 = voidtest.vfunc3(n1)
+n4 = voidtest.vfunc1(nil)
+
+assert(n3==nil)
+assert(n4==nil)
diff --git a/trunk/Examples/test-suite/member_pointer.i b/trunk/Examples/test-suite/member_pointer.i
new file mode 100644
index 0000000..f03528c
--- /dev/null
+++ b/trunk/Examples/test-suite/member_pointer.i
@@ -0,0 +1,101 @@
+%module member_pointer
+
+%inline %{
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  double  *z;
+
+  void    move(double dx, double dy);
+  virtual double area(void) = 0;
+  virtual double perimeter(void) = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+  
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area(void);
+  virtual double perimeter(void);
+};
+
+extern double do_op(Shape *s, double (Shape::*m)(void));
+
+/* Functions that return member pointers */
+
+extern double (Shape::*areapt())(void);
+extern double (Shape::*perimeterpt())(void);
+
+/* Global variables that are member pointers */
+extern double (Shape::*areavar)(void);
+extern double (Shape::*perimetervar)(void);
+
+%}
+
+%{
+#  define SWIG_M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy) {
+  x += dx;
+  y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void) {
+  return SWIG_M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+  return 2*SWIG_M_PI*radius;
+}
+
+double Square::area(void) {
+  return width*width;
+}
+
+double Square::perimeter(void) {
+  return 4*width;
+}
+
+double do_op(Shape *s, double (Shape::*m)(void)) {
+  return (s->*m)();
+}
+
+double (Shape::*areapt())(void) {
+  return &Shape::area;
+}
+
+double (Shape::*perimeterpt())(void) {
+  return &Shape::perimeter;
+}
+
+/* Member pointer variables */
+double (Shape::*areavar)(void) = &Shape::area;
+double (Shape::*perimetervar)(void) = &Shape::perimeter;
+%}
+
+
+/* Some constants */
+%constant double (Shape::*AREAPT)(void) = &Shape::area;
+%constant double (Shape::*PERIMPT)(void) = &Shape::perimeter;
+%constant double (Shape::*NULLPT)(void) = 0;
+
diff --git a/trunk/Examples/test-suite/member_template.i b/trunk/Examples/test-suite/member_template.i
new file mode 100644
index 0000000..6a1cb33
--- /dev/null
+++ b/trunk/Examples/test-suite/member_template.i
@@ -0,0 +1,28 @@
+%module member_template
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+  
+
+%inline %{
+template<class T> T max(T x, T y, T z) { return (x > y) ? x : y; }
+
+template<class T> class Foo {
+ public:
+  template<class S> S max(S x, S y) { return (x > y) ? x : y; }
+};
+
+%}
+
+%extend Foo {
+  %template(maxi)   max<int>;
+  %template(maxd)   max<double>;
+};
+
+%template(Fooint)    Foo<int>;
+%template(Foodouble) Foo<double>;
+
diff --git a/trunk/Examples/test-suite/memberin1.i b/trunk/Examples/test-suite/memberin1.i
new file mode 100644
index 0000000..9203230
--- /dev/null
+++ b/trunk/Examples/test-suite/memberin1.i
@@ -0,0 +1,63 @@
+%module memberin1
+
+%{
+class String {
+private:
+  char *str;
+public:
+  // Constructor
+  String(const char *s = 0) : str(0) {
+    if (s != 0) {
+      str = new char[strlen(s) + 1];
+      strcpy(str, s);
+    }
+  }
+
+  // Copy constructor
+  String(const String& other) {
+    delete [] str;
+    str = 0;
+    if (other.str != 0) {
+      str = new char[strlen(other.str) + 1];
+      strcpy(str, other.str);
+    }
+  }
+
+  // Assignment operator
+  String& operator=(const String& other) {
+    if (&other != this) {
+      delete [] str;
+      str = 0;
+      if (other.str != 0) {
+        str = new char[strlen(other.str) + 1];
+        strcpy(str, other.str);
+      }
+    }
+    return *this;
+  }
+
+  // String contents
+  const char *c_str() const { return str; }
+
+  // Destructor
+  ~String() { delete [] str; }
+};
+%}
+
+#ifdef SWIGRUBY
+%typemap(in) String {
+  Check_Type($input, T_STRING);
+  $1 = String(STR2CSTR($input));
+}
+#endif
+
+%typemap(memberin) String {
+  $1 = $input;
+}
+
+%inline %{
+struct Person {
+  String name;
+};
+%}
+
diff --git a/trunk/Examples/test-suite/minherit.i b/trunk/Examples/test-suite/minherit.i
new file mode 100644
index 0000000..24092b6
--- /dev/null
+++ b/trunk/Examples/test-suite/minherit.i
@@ -0,0 +1,77 @@
+// This module tests multiple inheritance, typedef handling, and some
+// truly horrible parts of the SWIG type system.   This is only tested
+// for Python since not all language modules support multiple-inheritance.
+// However, if it works for Python, things should be working for other
+// modules.
+
+%module(ruby_minherit="1") minherit
+
+#if defined(SWIGPYTHON) || defined(SWIGRUBY) || defined(SWIGOCAML) || defined(SWIGOCTAVE) || defined(SWIGPERL)
+
+%inline %{
+
+class Foo {
+private:
+    int x;
+public:
+    Foo() { x = 1; }
+    virtual ~Foo() {}
+    virtual int  xget() {  return x; };
+};
+typedef Foo *FooPtr;
+
+FooPtr toFooPtr(Foo *f) { return f; }
+
+class Bar {
+private:
+    int y;
+public:
+    Bar() { y = 2; }
+    virtual ~Bar() {}
+    virtual int yget() { return y; }
+};
+
+typedef Bar *BarPtr;
+BarPtr toBarPtr(Bar *f) { return f; }
+
+class FooBar : public Foo, public Bar {
+private:
+    int z;
+public:
+    FooBar() { z = 3; }
+    virtual int zget() { return z; }
+};
+
+typedef FooBar *FooBarPtr;
+FooBarPtr toFooBarPtr(FooBar *f) { return f; }
+
+class Spam: public FooBar {
+private:
+    int w;
+public:
+    Spam() { w = 4; }
+    virtual int wget() { return w; }
+};
+
+typedef Spam *SpamPtr;
+SpamPtr toSpamPtr(Spam *f) { return f; }
+
+int xget(FooPtr f) {
+   return f->xget();
+}
+
+int yget(BarPtr f) {
+   return f->yget();
+}
+
+int zget(FooBarPtr f) {
+   return f->zget();
+}
+
+int wget(SpamPtr f) {
+   return f->wget();
+}
+%}
+
+#endif
+
diff --git a/trunk/Examples/test-suite/minherit2.i b/trunk/Examples/test-suite/minherit2.i
new file mode 100644
index 0000000..f55131f
--- /dev/null
+++ b/trunk/Examples/test-suite/minherit2.i
@@ -0,0 +1,94 @@
+%module minherit2
+
+// A multiple inheritance example, mainly for Java and C#.
+// The example shows how it is possible to turn C++ abstract base classes into Java/C# interface.
+// In the future, all this trouble might be more automated.
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_RUBY_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) RemoteMpe;
+
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP)
+
+#if defined(SWIGCSHARP)
+#define javaclassmodifiers   csclassmodifiers
+#define javabody             csbody
+#define javafinalize         csfinalize
+#define javadestruct         csdestruct
+#define javaout              csout
+#define javainterfaces       csinterfaces
+#define javabase             csbase
+#endif
+
+// Modify multiple inherited base classes into inheriting interfaces
+%typemap(javainterfaces) RemoteMpe "IRemoteSyncIO, IRemoteAsyncIO";
+%typemap(javabase, replace="1") RemoteMpe "";
+
+// Turn the proxy class into an interface
+%typemap(javaclassmodifiers) IRemoteSyncIO "public interface";
+%typemap(javaclassmodifiers) IRemoteAsyncIO "public interface";
+%typemap(javabody) IRemoteSyncIO "";
+%typemap(javabody) IRemoteAsyncIO "";
+%typemap(javafinalize) IRemoteSyncIO "";
+%typemap(javafinalize) IRemoteAsyncIO "";
+%typemap(javadestruct) IRemoteSyncIO "";
+%typemap(javadestruct) IRemoteAsyncIO "";
+
+// Turn the methods into abstract methods
+%typemap(javaout) void IRemoteSyncIO::syncmethod ";"
+%typemap(javaout) void IRemoteAsyncIO::asyncmethod ";"
+#if defined(SWIGJAVA)
+%javamethodmodifiers IRemoteSyncIO::syncmethod "abstract public";
+%javamethodmodifiers IRemoteAsyncIO::asyncmethod "abstract public";
+// Features are inherited by derived classes, so override this
+%javamethodmodifiers RemoteMpe::syncmethod "public"
+%javamethodmodifiers RemoteMpe::asyncmethod "public"
+#elif defined(SWIGCSHARP)
+%csmethodmodifiers IRemoteSyncIO::syncmethod "";
+%csmethodmodifiers IRemoteAsyncIO::asyncmethod "";
+// Features are inherited by derived classes, so override this
+%csmethodmodifiers RemoteMpe::syncmethod "public"
+%csmethodmodifiers RemoteMpe::asyncmethod "public"
+#endif
+
+#endif
+
+
+%inline %{
+class IRemoteSyncIO
+{
+public:
+  virtual ~IRemoteSyncIO () {}
+  virtual void syncmethod() = 0;
+protected:
+  IRemoteSyncIO () {}
+  
+private:
+  IRemoteSyncIO (const IRemoteSyncIO&);
+  IRemoteSyncIO& operator= (const IRemoteSyncIO&);
+};
+
+class IRemoteAsyncIO
+{
+public:
+  virtual ~IRemoteAsyncIO () {}
+  virtual void asyncmethod() = 0;
+protected:
+  IRemoteAsyncIO () {}
+  
+private:
+  IRemoteAsyncIO (const IRemoteAsyncIO&);
+  IRemoteAsyncIO& operator= (const IRemoteAsyncIO&);
+};
+
+class RemoteMpe : public IRemoteSyncIO, public IRemoteAsyncIO
+{
+public:
+  virtual void syncmethod() {}
+  virtual void asyncmethod() {}
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/mixed_types.i b/trunk/Examples/test-suite/mixed_types.i
new file mode 100644
index 0000000..274cfcf
--- /dev/null
+++ b/trunk/Examples/test-suite/mixed_types.i
@@ -0,0 +1,164 @@
+%module mixed_types
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hi; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hello; /* Ruby, wrong constant name */
+
+%inline 
+{
+  const void* ref_pointer(const void*& a) {
+    return a;
+  }
+
+  struct A
+  {
+  };
+  
+  const A* ref_pointer(A* const& a) {
+    return a;
+  }
+
+  const A** ref_pointer_1(const A**& a) {
+    return a;
+  }
+
+  A* pointer_1(A* a) {
+    return a;
+  }
+
+  const A& ref_const(const A& a) {
+    return a;
+  }
+
+  enum Hello { hi,hello };
+
+  int sint(int a) {
+    return a;
+  }
+
+  const int& ref_int(const int& a) {
+    return a;
+  }
+
+  Hello senum(Hello a) {
+    return a;
+  }
+  
+  const Hello& ref_enum(const Hello& a) {
+    return a;
+  }  
+
+  typedef A *Aptr;
+  const Aptr& rptr_const(const Aptr& a) {
+    return a;
+  }
+
+  const Aptr& rptr_const2(const Aptr& a) {
+    return a;
+  }
+
+  const void*& rptr_void(const void*& a) {
+    return a;
+  }
+
+  const A& cref_a(const A& a) {
+    return a;
+  }
+
+  A& ref_a(A& a) {
+    return a;
+  }
+
+
+  template <class T> struct NameT {
+  };
+  
+  
+  typedef char name[8];
+  typedef char namea[];
+
+  typedef NameT<char> name_t[8];
+  
+  char* test_a(char hello[8],
+	       char hi[],
+	       const char chello[8],
+	       const char chi[]) {
+    return hi;
+  }
+
+  int test_b(name n2) {
+    return 1;
+  }
+
+/* gcc doesn't like this one. Removing until reason resolved.*/
+  int test_c(const name& n1) {
+    return 1;
+  }
+
+  int test_d(name* n1) {
+    return 1;
+  }
+
+  int test_e(const name_t& n1) {
+    return 1;
+  }
+
+  int test_f(name_t n1) {
+    return 1;
+  }
+
+  int test_g(name_t* n1) {
+    return 1;
+  }
+
+  struct Foo 
+  {
+    int foo(const Aptr&a);
+    int foon(const char (&a)[8]);
+  };
+
+  inline int Foo::foo(A* const& a) { return 1; }
+
+}
+
+%{
+  inline int Foo::foon(const name& a) { return a[0]; }
+%}
+
+
+
+%inline %{
+#define ARRAY_LEN_X 2
+#define ARRAY_LEN_Y 4
+
+typedef enum {One, Two, Three, Four, Five} finger;
+
+typedef struct {
+    double         double_field;
+} SimpleStruct;
+
+char           array_c [ARRAY_LEN_X][ARRAY_LEN_Y];
+signed char    array_sc[ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned char  array_uc[ARRAY_LEN_X][ARRAY_LEN_Y];
+short          array_s [ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned short array_us[ARRAY_LEN_X][ARRAY_LEN_Y];
+int            array_i [ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned int   array_ui[ARRAY_LEN_X][ARRAY_LEN_Y];
+long           array_l [ARRAY_LEN_X][ARRAY_LEN_Y];
+unsigned long  array_ul[ARRAY_LEN_X][ARRAY_LEN_Y];
+long long      array_ll[ARRAY_LEN_X][ARRAY_LEN_Y];
+float          array_f [ARRAY_LEN_X][ARRAY_LEN_Y];
+double         array_d [ARRAY_LEN_X][ARRAY_LEN_Y];
+SimpleStruct   array_struct[ARRAY_LEN_X][ARRAY_LEN_Y];
+SimpleStruct*  array_structpointers[ARRAY_LEN_X][ARRAY_LEN_Y];
+int*           array_ipointers [ARRAY_LEN_X][ARRAY_LEN_Y];
+finger         array_enum[ARRAY_LEN_X][ARRAY_LEN_Y];
+finger*        array_enumpointers[ARRAY_LEN_X][ARRAY_LEN_Y];
+const int      array_const_i[ARRAY_LEN_X][ARRAY_LEN_Y] = { {10, 11, 12, 13}, {14, 15, 16, 17} };
+
+void fn_taking_arrays(SimpleStruct array_struct[ARRAY_LEN_X][ARRAY_LEN_Y]) {}
+
+int get_2d_array(int (*array)[ARRAY_LEN_Y], int x, int y){
+    return array[x][y];
+}
+%}
+
diff --git a/trunk/Examples/test-suite/mod.h b/trunk/Examples/test-suite/mod.h
new file mode 100644
index 0000000..aae6298
--- /dev/null
+++ b/trunk/Examples/test-suite/mod.h
@@ -0,0 +1,34 @@
+
+
+class C;
+
+class A
+{
+public:
+    A() {}
+    C* GetC() { return NULL; }
+
+    void DoSomething(A* a) {}
+};
+
+
+class B : public A
+{
+public:
+  B() {}
+  
+};
+
+
+class C : public B
+{
+public:
+    C() {}
+};
+
+
+class D : public C
+{
+public:
+    D() {}
+};
diff --git a/trunk/Examples/test-suite/mod.list b/trunk/Examples/test-suite/mod.list
new file mode 100644
index 0000000..41350ae
--- /dev/null
+++ b/trunk/Examples/test-suite/mod.list
@@ -0,0 +1,2 @@
+mod_a
+mod_b
diff --git a/trunk/Examples/test-suite/mod_a.i b/trunk/Examples/test-suite/mod_a.i
new file mode 100644
index 0000000..bc8c163
--- /dev/null
+++ b/trunk/Examples/test-suite/mod_a.i
@@ -0,0 +1,24 @@
+%module mod_a
+
+%{
+#include "mod.h"
+%}
+
+
+class C;
+
+class A
+{
+public:
+    A() {}
+    C* GetC() { return NULL; }
+
+    void DoSomething(A* a) {}
+};
+
+
+class B : public A
+{
+public:
+    B();
+};
diff --git a/trunk/Examples/test-suite/mod_b.i b/trunk/Examples/test-suite/mod_b.i
new file mode 100644
index 0000000..3bb8c8b
--- /dev/null
+++ b/trunk/Examples/test-suite/mod_b.i
@@ -0,0 +1,22 @@
+%module mod_b
+
+%{
+#include "mod.h"
+%}
+
+
+%import mod_a.i
+
+
+class C : public B
+{
+public:
+    C() {}
+};
+
+
+class D : public C
+{
+public:
+    D() {}
+};
diff --git a/trunk/Examples/test-suite/multi_import.h b/trunk/Examples/test-suite/multi_import.h
new file mode 100644
index 0000000..fa7a460
--- /dev/null
+++ b/trunk/Examples/test-suite/multi_import.h
@@ -0,0 +1,17 @@
+class XXX
+{
+	public:
+		int testx() { return 0;}
+};
+
+class YYY : public XXX
+{
+	public:
+		int testy() { return 1;}
+};
+
+class ZZZ : public XXX
+{
+	public:
+		int testz() { return 2;}
+};
diff --git a/trunk/Examples/test-suite/multi_import.list b/trunk/Examples/test-suite/multi_import.list
new file mode 100644
index 0000000..6f7f98c
--- /dev/null
+++ b/trunk/Examples/test-suite/multi_import.list
@@ -0,0 +1,2 @@
+multi_import_a
+multi_import_b
diff --git a/trunk/Examples/test-suite/multi_import_a.i b/trunk/Examples/test-suite/multi_import_a.i
new file mode 100644
index 0000000..62d7cc0
--- /dev/null
+++ b/trunk/Examples/test-suite/multi_import_a.i
@@ -0,0 +1,15 @@
+/* This was reported in Bug #1735931 */
+
+%module multi_import_a
+
+%import multi_import_b.i
+
+%{
+#include "multi_import.h"
+%}
+
+class ZZZ : public XXX
+{
+public:
+   int testz();
+};
diff --git a/trunk/Examples/test-suite/multi_import_b.i b/trunk/Examples/test-suite/multi_import_b.i
new file mode 100644
index 0000000..a2be270
--- /dev/null
+++ b/trunk/Examples/test-suite/multi_import_b.i
@@ -0,0 +1,13 @@
+%module multi_import_b
+
+%include multi_import_c.i
+
+%{
+#include "multi_import.h"
+%}
+
+class YYY : public XXX
+{
+public:
+        int testy();
+};
diff --git a/trunk/Examples/test-suite/multi_import_c.i b/trunk/Examples/test-suite/multi_import_c.i
new file mode 100644
index 0000000..854e6b1
--- /dev/null
+++ b/trunk/Examples/test-suite/multi_import_c.i
@@ -0,0 +1,5 @@
+class XXX
+{
+public:
+  int testx();
+};
diff --git a/trunk/Examples/test-suite/multiple_inheritance.i b/trunk/Examples/test-suite/multiple_inheritance.i
new file mode 100644
index 0000000..1c44581
--- /dev/null
+++ b/trunk/Examples/test-suite/multiple_inheritance.i
@@ -0,0 +1,92 @@
+/* This was broken in the perl module.  See bug 962115 
+It tests basic multiple inheritance */
+
+%module(ruby_minherit="1") multiple_inheritance
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) FooBar;	/* C#, Java, Php4 multiple inheritance */
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) FooBarSpam;	/* C#, Java, Php4 multiple inheritance */
+
+
+%inline %{
+
+class Bar {
+public:
+  virtual ~Bar()
+  {
+  }
+  
+  virtual int bar() { return 1; }
+};
+
+class Foo {
+public:
+  virtual ~Foo()
+  {
+  }
+
+  virtual int foo() { return 2; }
+};
+
+template<class T> class Spam {
+public:
+  virtual ~Spam()
+  {
+  }
+  
+  virtual int spam(const T& t) { return 100; }
+};
+%}
+
+%template(SpamInt) Spam<int>;
+
+%inline %{
+class FooBar : public Foo, public Bar {
+public:
+  virtual int fooBar() { return 3; }
+};
+
+class FooBarSpam : public Foo, public Bar, public Spam<int> {
+public:
+  virtual int fooBarSpam() { return 4; }
+};
+
+%}
+
+// Languages that don't support multiple inheritance should inherit from one of the non-ignored classes
+%ignore IgnoreMe;
+%ignore IgnoreMeToo;
+
+%inline %{
+class IgnoreMe {
+public:
+  virtual int ignoreme() { return 5; }
+  virtual ~IgnoreMe() {}
+};
+class IgnoreMeToo {
+public:
+  virtual int ignoremetoo() { return 6; }
+  virtual ~IgnoreMeToo() {}
+};
+class IgnoreDerived1 : public IgnoreMe, public Bar {
+public:
+  virtual int ignorederived1() { return 7; }
+};
+class IgnoreDerived2 : public IgnoreMe, public IgnoreMeToo, public Bar {
+public:
+  virtual int ignorederived2() { return 8; }
+};
+class IgnoreDerived3 : public IgnoreMe, public Bar, public IgnoreMeToo {
+public:
+  virtual int ignorederived3() { return 9; }
+};
+class IgnoreDerived4 : public Bar, public IgnoreMe, public IgnoreMeToo {
+public:
+  virtual int ignorederived4() { return 10; }
+};
+%}
+
diff --git a/trunk/Examples/test-suite/multivalue.i b/trunk/Examples/test-suite/multivalue.i
new file mode 100644
index 0000000..59f3d76
--- /dev/null
+++ b/trunk/Examples/test-suite/multivalue.i
@@ -0,0 +1,52 @@
+/* -*- c -*- */
+
+%module multivalue
+
+#ifdef SWIGGUILE
+
+/* Multiple values as lists. By default, if more than one value is to
+be returned, a list of the values is created and returned; to switch
+back to this behavior, use: */
+%values_as_list; 
+
+void divide_l(int a, int b, int *OUTPUT, int *OUTPUT);
+
+/* Multiple values as vectors. By issueing: */
+%values_as_vector;
+/* vectors instead of lists will be used. */
+
+void divide_v(int a, int b, int *OUTPUT, int *OUTPUT);
+
+/* Multiple values for multiple-value continuations.
+   (This is the most elegant way.)  By issueing: */
+%multiple_values;
+/* multiple values are passed to the multiple-value
+   continuation, as created by `call-with-values' or the
+   convenience macro `receive'. (See the Scheme file.) */
+
+void divide_mv(int a, int b, int *OUTPUT, int *OUTPUT);
+
+#endif
+
+%{
+
+void divide_l(int a, int b, int *quotient_p, int *remainder_p)
+{
+  *quotient_p = a/b;
+  *remainder_p = a%b;
+}
+
+void divide_v(int a, int b, int *quotient_p, int *remainder_p)
+{
+  *quotient_p = a/b;
+  *remainder_p = a%b;
+}
+
+void divide_mv(int a, int b, int *quotient_p, int *remainder_p)
+{
+  *quotient_p = a/b;
+  *remainder_p = a%b;
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/mzscheme/Makefile.in b/trunk/Examples/test-suite/mzscheme/Makefile.in
new file mode 100644
index 0000000..753b01f
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/Makefile.in
@@ -0,0 +1,45 @@
+#######################################################################
+# Makefile for mzscheme test-suite
+#######################################################################
+
+LANGUAGE     = mzscheme
+MZSCHEME     = mzscheme
+SCRIPTSUFFIX = _runme.scm
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+# none!
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.scm appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(MZSCHEME) -r $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile mzscheme_clean
diff --git a/trunk/Examples/test-suite/mzscheme/README b/trunk/Examples/test-suite/mzscheme/README
new file mode 100644
index 0000000..37432ea
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/README
@@ -0,0 +1,4 @@
+See ../README for common README file.
+
+Any testcases which have _runme.scm appended after the testcase name will be detected and run.
+
diff --git a/trunk/Examples/test-suite/mzscheme/casts_runme.scm b/trunk/Examples/test-suite/mzscheme/casts_runme.scm
new file mode 100644
index 0000000..3aaa62d
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/casts_runme.scm
@@ -0,0 +1,7 @@
+(load-extension "casts.so")
+
+(define x (new-B))
+
+(A-hello x)				
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/mzscheme/char_constant_runme.scm b/trunk/Examples/test-suite/mzscheme/char_constant_runme.scm
new file mode 100644
index 0000000..4e3ed47
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/char_constant_runme.scm
@@ -0,0 +1,6 @@
+(load-extension "char_constant.so")
+
+(if (and (char? (CHAR-CONSTANT))
+	 (string? (STRING-CONSTANT)))
+    (exit 0)
+    (exit 1))
diff --git a/trunk/Examples/test-suite/mzscheme/imports_runme.scm b/trunk/Examples/test-suite/mzscheme/imports_runme.scm
new file mode 100644
index 0000000..ae636aa
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/imports_runme.scm
@@ -0,0 +1,16 @@
+;;; This file is part of a test for SF bug #231619. 
+;;; It shows that the %import directive does not work properly in SWIG
+;;; 1.3a5:  Type information is not properly generated if a base class
+;;; comes from an %import-ed file. 
+
+(load-extension "imports_a.so")
+(load-extension "imports_b.so")
+
+(define x (new-B))
+
+;; This fails in 1.3a5 because the SWIG runtime code does not know
+;; that x (an instance of class B) can be passed to methods of class A. 
+
+(A-hello x)				
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/mzscheme/integers_runme.scm b/trunk/Examples/test-suite/mzscheme/integers_runme.scm
new file mode 100644
index 0000000..03c8021
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/integers_runme.scm
@@ -0,0 +1,9 @@
+(load-extension "integers.so")
+(require (lib "defmacro.ss"))
+
+(define-macro (throws-exception? form)
+  `(with-handlers ((not-break-exn? (lambda (exn) #t)))
+     ,form
+     #f))
+
+(load "../schemerunme/integers.scm")
diff --git a/trunk/Examples/test-suite/mzscheme/name_runme.scm b/trunk/Examples/test-suite/mzscheme/name_runme.scm
new file mode 100644
index 0000000..1782c64
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/name_runme.scm
@@ -0,0 +1,10 @@
+;; The SWIG modules have "passive" Linkage, i.e., they don't generate
+;; Guile modules (namespaces) but simply put all the bindings into the
+;; current module.  That's enough for such a simple test.
+(load-extension "./name.so")
+
+(foo-2)
+bar-2
+Baz-2
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/mzscheme/unions_runme.scm b/trunk/Examples/test-suite/mzscheme/unions_runme.scm
new file mode 100644
index 0000000..c44847c
--- /dev/null
+++ b/trunk/Examples/test-suite/mzscheme/unions_runme.scm
@@ -0,0 +1,38 @@
+;;; This is the union runtime testcase. It ensures that values within a
+;;; union embedded within a struct can be set and read correctly.
+
+(load-extension "unions.so")
+
+;; Create new instances of SmallStruct and BigStruct for later use
+(define small (new-SmallStruct))
+(SmallStruct-jill-set small 200)
+
+(define big (new-BigStruct))
+(BigStruct-smallstruct-set big small)
+(BigStruct-jack-set big 300)
+
+;; Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+;; Ensure values in EmbeddedUnionTest are set correctly for each.
+(define eut (new-EmbeddedUnionTest))
+
+;; First check the SmallStruct in EmbeddedUnionTest
+(EmbeddedUnionTest-number-set eut 1)
+(EmbeddedUnionTest-uni-small-set (EmbeddedUnionTest-uni-get eut)
+				 small)
+(let ((Jill1 (SmallStruct-jill-get
+	      (EmbeddedUnionTest-uni-small-get
+	       (EmbeddedUnionTest-uni-get eut)))))
+  (if (not (= Jill1 200))
+      (begin
+	(display "Runtime test 1 failed.")
+	(exit 1))))
+
+(let ((Num1 (EmbeddedUnionTest-number-get eut)))
+  (if (not (= Num1 1))
+      (begin
+	(display "Runtime test 2 failed.")
+	(exit 1))))
+
+;; that should do
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/name.i b/trunk/Examples/test-suite/name.i
new file mode 100644
index 0000000..70e80dc
--- /dev/null
+++ b/trunk/Examples/test-suite/name.i
@@ -0,0 +1,28 @@
+/* This interface file tests whether SWIG/Guile handle the %rename and
+   %name directives, which was not the case in 1.3a5.
+*/
+
+%module name
+
+#pragma SWIG nowarn=SWIGWARN_DEPRECATED_NAME // %name is deprecated. Use %rename instead.
+
+#ifdef SWIGGUILE
+%rename foo_1 "foo-2";
+#else
+%rename foo_1 "foo_2";
+#endif
+%inline %{
+void foo_1() {}
+%}
+
+#ifdef SWIGGUILE
+%name("bar-2")
+#else
+%name("bar_2")
+#endif
+%inline %{
+int bar_1 = 17;
+%}
+
+%name("Baz_2")
+%constant int Baz_1 = 47;
diff --git a/trunk/Examples/test-suite/name_cxx.i b/trunk/Examples/test-suite/name_cxx.i
new file mode 100644
index 0000000..64d79c3
--- /dev/null
+++ b/trunk/Examples/test-suite/name_cxx.i
@@ -0,0 +1,31 @@
+/* This interface files tests whether SWIG handles overloaded
+   renamed functions. 
+*/
+
+%module name_cxx
+
+#pragma SWIG nowarn=SWIGWARN_DEPRECATED_NAME // %name is deprecated. Use %rename instead.
+
+%name("bar_int")
+%inline %{
+void bar(int i) {}
+%}
+
+%name("bar_double")
+%inline %{
+void bar(double i) {}
+%}
+
+// %name inheritance test
+%{
+class A {
+};
+
+class B : public A {
+};
+
+%}
+
+%name(AA) class A { };
+class B : public A { };
+
diff --git a/trunk/Examples/test-suite/name_warnings.i b/trunk/Examples/test-suite/name_warnings.i
new file mode 100644
index 0000000..a9cb356
--- /dev/null
+++ b/trunk/Examples/test-suite/name_warnings.i
@@ -0,0 +1,70 @@
+%module name_warnings
+/*
+  This test should produce no warnings at all.
+
+  It just show the cases where swig was showing unintended warnings
+  before.
+
+  Right now the test includes some cases for python, java and csharp.
+
+*/
+
+/* activate all the name warnings */
+%warnfilter(+SWIGWARN_PARSE_KEYWORD,+SWIGWARN_PARSE_BUILTIN_NAME,-SWIGWARN_TYPE_ABSTRACT);
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+class string; // csharp keyword
+namespace std 
+{
+  template <class T>
+    class complex;
+}
+
+%inline 
+{
+  class complex; // python built-in
+
+  typedef complex None;  // python built-in
+  
+  struct A 
+  {
+    typedef complex None;
+    
+    A* clone(int) { return NULL; }
+    
+    virtual ~A() {}
+    virtual int func() = 0;
+  private:
+     typedef complex False;
+  };
+
+  template <class T>
+    T max (T a, T b) { // python 'max' built-in
+    return a > b ? a : b;
+  }  
+
+  struct B : A
+  {
+    B() {}
+  };
+  
+  
+}
+
+%template(max_i) max<int>;
+
+
+%inline {
+  /* silently rename the parameter names in csharp/java */
+#ifdef SWIGR
+  double foo(double inparam, double out) { return 1.0; }
+#else
+  double foo(double in, double out) { return 1.0; }
+#endif
+  double bar(double native, bool boolean) { return 1.0; }
+}
diff --git a/trunk/Examples/test-suite/namespace_class.i b/trunk/Examples/test-suite/namespace_class.i
new file mode 100644
index 0000000..5e9545c
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_class.i
@@ -0,0 +1,302 @@
+%module namespace_class
+
+%inline %{
+  template<class T> void foobar(T t) {}
+  namespace test {
+    template<class T> void barfoo(T t) {}
+  }  
+%}
+
+%template(FooBarInt) ::foobar<int>;
+%template(BarFooInt) test::barfoo<int>;
+
+
+%inline %{
+  template <class C>
+  struct Bar_T
+  {
+  };
+  
+  
+
+  namespace test {
+    enum Hello {
+      Hi
+    };    
+    
+    struct Test;
+
+    struct Bar  {
+      Hello foo(Hello h) {
+	return h;
+      }
+    };
+
+    namespace hola {
+      struct Bor;
+      struct Foo;
+      struct Foobar;
+      template <class T> struct BarT {
+      };
+
+      template <class T> class FooT;
+    }
+
+    template <class T>
+    class hola::FooT {
+    public:
+      Hello foo(Hello h) {
+	return h;
+      }
+      
+      T bar(T h) {
+	return h;
+      }
+    };
+
+    namespace hola {
+      template <> class FooT<double>;
+      template <> class FooT<int>;
+    }
+    
+    template <>
+    class hola::FooT<double> {
+    public:
+      double moo(double h) {
+	return h;
+      }
+    };
+
+    int a;
+
+    struct hola::Foo : Bar {
+      Hello bar(Hello h) {
+	return h;
+      }    
+    };
+  }
+  
+  struct test::Test {
+    Hello foo(Hello h) {
+      return h;
+    }
+  };
+
+  struct test::hola::Bor {
+    Hello foo(Hello h) {
+      return h;
+    }    
+  };
+
+  namespace test {
+    struct hola::Foobar : Bar {
+      Hello bar(Hello h) {
+	return h;
+      }    
+    };
+  }
+
+  template <>
+  class test::hola::FooT<int> {
+  public:
+    int quack(int h) {
+      return h;
+    }
+  };
+
+%}
+
+
+namespace test
+{
+  namespace hola {
+    %template(FooT_i) FooT<int>;
+  }
+
+  %template(FooT_H) hola::FooT<Hello>;
+}
+
+%template(FooT_d) ::test::hola::FooT<double>;
+%template(BarT_H) test::hola::BarT<test::Hello>;
+
+%inline %{
+
+  namespace hi {
+    namespace hello {
+      template <class T> struct PooT;
+    }
+
+    namespace hello {
+      template <class T> struct PooT
+      {
+      }; 
+    }
+  }
+%}
+
+%template(Poo_i) hi::hello::PooT<int>;
+
+%inline %{
+
+  template <class T> struct BooT {
+  };
+
+  namespace test {
+    
+    typedef ::BooT<Hello> BooT_H;
+  }
+
+%}
+
+namespace test {
+  
+  %template(BooT_H) ::BooT<Hello>;
+}
+%template(BooT_i) ::BooT<int>;
+
+
+%inline %{
+
+namespace jafar {
+  namespace jmath {
+    class EulerT3D {
+    public:
+      static void hello(){}
+      
+      template<class VecFrame, class Vec, class VecRes>
+      static void toFrame(const VecFrame& frame_, const Vec&v_,const VecRes& vRes){}
+      
+      template<class T>
+      void operator ()(T& x){}
+
+      template<class T>
+      void operator < (T& x){}
+      
+      template<class T>
+      operator Bar_T<T> () {}
+
+    };
+  }
+}
+%}
+
+%template(toFrame) jafar::jmath::EulerT3D::toFrame<int,int,int>;
+%template(callint) jafar::jmath::EulerT3D::operator()<int>;
+%template(lessint) jafar::jmath::EulerT3D::operator < <int>;
+%template(callfooi) jafar::jmath::EulerT3D::operator() <test::hola::FooT<int> >;
+%template(lessfooi) jafar::jmath::EulerT3D::operator < < test::hola::FooT<int> >;
+
+
+%inline %{
+
+namespace {
+  /* the unnamed namespace is 'private', so, the following
+     declarations shouldn't be wrapped */
+  class Private1
+  {
+  };
+
+}
+
+namespace a
+{
+  namespace 
+  {
+    class Private2
+    {
+    };
+  }
+}
+ 
+%}
+
+#pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
+// %copyctor doesn't work with nested class workaround
+%nocopyctor;
+
+%inline %{
+  class Ala {
+  public : 
+    Ala() {}
+    class Ola {
+    public:
+      Ola() {}
+      void eek() {}
+    };
+    
+    template <class T>
+    static void hi() 
+    {
+    }
+  };
+%}
+
+%rename(Ala__Ola) Ala::Ola;
+class Ala::Ola {
+public:
+  Ola() {}
+  void eek() {}
+};
+
+%template(hi) Ala::hi<int>;
+
+%extend jafar::jmath::EulerT3D 
+{
+  
+}
+
+%rename(FLACFile) TagLib::FLAC::File;
+
+%inline {
+namespace TagLib
+{
+  class File {
+  public:
+    File() {}
+  };
+
+  class AudioProperties {
+  };
+
+  class AudioPropertiesFile {
+  public:
+    typedef TagLib::File File;
+  };
+  
+  namespace FLAC
+  {
+    class File;
+    class Properties : public AudioProperties  {
+    public:
+      Properties(File *) {}
+    };
+
+    class PropertiesFile : public AudioPropertiesFile  {
+    public:
+      PropertiesFile(File * = 0) {}
+    };
+
+    namespace bar {
+      class PropertiesFree  : public AudioProperties  {
+      public:
+	PropertiesFree(File *) {}
+      };
+    }
+
+    class FooFilePrivate : private PropertiesFile  {
+    public:
+      FooFilePrivate(File *) {}
+    };
+
+    class FooFile : public PropertiesFile  {
+    public:
+      FooFile(File *) {}
+    };
+
+    class File {
+    public:
+      File() {}
+    };
+  }
+}
+}
diff --git a/trunk/Examples/test-suite/namespace_enum.i b/trunk/Examples/test-suite/namespace_enum.i
new file mode 100644
index 0000000..82a97c6
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_enum.i
@@ -0,0 +1,24 @@
+%module namespace_enum
+
+%inline %{
+
+namespace Foo {
+   enum Swig {
+       LAGER,
+       STOUT,
+       ALE
+    };
+
+   class Bar {
+   public:
+        enum Speed {
+            SLOW,
+            FAST
+        };
+   };
+}
+
+%}
+
+       
+   
\ No newline at end of file
diff --git a/trunk/Examples/test-suite/namespace_extend.i b/trunk/Examples/test-suite/namespace_extend.i
new file mode 100644
index 0000000..3c414d1
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_extend.i
@@ -0,0 +1,34 @@
+%module namespace_extend
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) bar; /* Ruby, wrong class name */
+
+%{
+namespace foo {
+   class bar {
+   public:
+   };
+}
+foo::bar *new_foo_bar() {
+   return new foo::bar;
+}
+void     delete_foo_bar(foo::bar *self) {
+   delete self;
+}
+int foo_bar_blah(foo::bar *self, int x) {
+   return x;
+}
+%}
+
+namespace foo {
+    class bar {
+    public:
+    %extend {
+        bar();
+       ~bar();
+        int blah(int x);
+    };
+  };
+}
+
+
+
diff --git a/trunk/Examples/test-suite/namespace_nested.i b/trunk/Examples/test-suite/namespace_nested.i
new file mode 100644
index 0000000..63d871f
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_nested.i
@@ -0,0 +1,101 @@
+%module namespace_nested
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hello::hi::hi0;	/* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::hi1<hello::Hi0 >;	/* Ruby, wrong class name */
+
+%inline %{
+  namespace hello
+  {  
+    namespace hi
+    {      
+      struct hi0
+      {
+      };      
+    }
+
+    template < class T1 >
+    struct Hi : T1
+    {
+    };
+  }
+
+%}
+
+namespace hello 
+{
+  %template(Hi_hi0) Hi<hi::hi0>;
+}
+
+
+
+%inline %{
+
+  namespace hello
+  {
+    //
+    // This works 
+    //
+    // typedef Hi<hello::hi::hi0> Hi0;
+    
+    //
+    // This doesn't work
+    //
+    typedef Hi<hi::hi0> Hi0;
+  }
+  
+  
+  namespace oss
+  {
+    template <class T1>
+    struct hi1 : T1
+    {
+    };
+
+    typedef hello::Hi<hello::hi::hi0> h0;
+  }
+  
+%}
+
+namespace oss
+{
+  %template(hi1_hi0) hi1<hello::Hi0 >;
+}
+
+
+%rename(MyFoo) geos::algorithm::Foo;
+
+%inline 
+{
+  namespace geos {
+    namespace algorithm {
+      class Foo 
+      {
+      };
+    }
+    
+    namespace planargraph { // geos.planargraph
+      namespace algorithm { // geos.planargraph.algorithm
+	class Bar {
+	};
+      }
+      namespace algorithm { // geos.planargraph.algorithm
+
+	class Foo {
+	public:
+	  typedef int size_type;
+	};
+      }
+      namespace algorithm { // geos.planargraph.algorithm
+
+	class ConnectedSubgraphFinder : public Foo {
+	public:
+	  ConnectedSubgraphFinder(size_type)
+	  {
+	  }
+	  
+	};
+      }
+    }
+  }
+}
+
diff --git a/trunk/Examples/test-suite/namespace_spaces.i b/trunk/Examples/test-suite/namespace_spaces.i
new file mode 100644
index 0000000..9819161
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_spaces.i
@@ -0,0 +1,26 @@
+%module namespace_spaces 
+%inline %{ 
+ 
+class Foo { 
+public: 
+    Foo(); 
+    ~Foo(); 
+    typedef int Integer; 
+    int blah(int x); 
+    int spam(int x); 
+    Integer bar(Integer x); 
+    void (Foo:: *func_ptr) (int);
+}; 
+ 
+inline Foo :: Foo () {}
+ 
+inline Foo :: ~Foo () {}
+     
+inline int Foo  
+::blah(int x) { return 2*x; } 
+ 
+inline int Foo :: spam(int x) { return -x; } 
+ 
+inline Foo :: Integer Foo :: bar(Foo :: Integer x) { return x; } 
+ 
+%} 
diff --git a/trunk/Examples/test-suite/namespace_template.i b/trunk/Examples/test-suite/namespace_template.i
new file mode 100644
index 0000000..a36abb1
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_template.i
@@ -0,0 +1,84 @@
+/* Tests the use of %template with namespaces */
+
+%module namespace_template
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<int>;            /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) test2::vector<short>;   /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) test3::vector<long>;    /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<test4::Integer>; /* Ruby, wrong class name */
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+%{
+namespace test {
+   template<typename T> T max(T a, T b) { return (a > b) ? a : b; }
+   template<typename T> class vector { 
+	public:
+	   vector() { }
+          ~vector() { }
+           char * blah(T x) {
+              return (char *) "vector::blah";
+           }
+   }; 
+}
+
+namespace test2 {
+   using namespace test;
+}
+
+namespace test3 {
+   using test::max;
+   using test::vector;
+}
+
+using namespace test2;
+namespace T4 = test;
+%}
+
+namespace test {
+   template<typename T> T max(T a, T b) { return (a > b) ? a : b; }
+   template<typename T> class vector { 
+	public:
+	   vector() { }
+          ~vector() { }
+           char * blah(T x) {
+              return (char *) "vector::blah";
+           }
+   }; 
+}
+
+using namespace test;
+%template(maxint) max<int>;
+%template(vectorint) vector<int>;
+
+namespace test2 {
+   using namespace test;
+   %template(maxshort) max<short>;
+   %template(vectorshort) vector<short>;
+}
+
+namespace test3 {
+   using test::max;
+   using test::vector;
+   %template(maxlong) max<long>;
+   %template(vectorlong) vector<long>;
+}
+
+%inline %{
+
+namespace test4 {
+   using namespace test;
+   typedef int Integer;
+}
+
+%}
+
+namespace test4 {
+   %template(maxInteger) max<Integer>;
+   %template(vectorInteger) vector<Integer>;
+}
+
diff --git a/trunk/Examples/test-suite/namespace_typedef_class.i b/trunk/Examples/test-suite/namespace_typedef_class.i
new file mode 100644
index 0000000..6e3729a
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_typedef_class.i
@@ -0,0 +1,18 @@
+%module namespace_typedef_class
+
+%inline %{
+namespace ns {
+  
+  struct S1
+  {
+    int n;
+  };
+
+  typedef struct
+  {
+    int n;
+  } S2;
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/namespace_typemap.i b/trunk/Examples/test-suite/namespace_typemap.i
new file mode 100644
index 0000000..e4e0af9
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_typemap.i
@@ -0,0 +1,258 @@
+// This tests SWIG's handling of typemaps and namespaces
+%module namespace_typemap
+
+%{
+namespace test {
+   /* A minimalistic string class */
+   class string_class {
+      char *data;
+   public:
+      string_class() {
+	data = 0;
+      }
+      string_class(const char *s) {
+        data = new char[strlen(s)+1];
+	strcpy(data,s);
+      }
+     ~string_class() {
+        if (data) delete [] data;
+      }
+      char *c_str() {
+        return data;
+      }
+   };
+
+   /* A minimalistic test_complex class */
+   class test_complex {
+      double re;
+      double im;
+   public:
+      test_complex(double r = 0, double i = 0) {
+	re = r;
+	im = i;
+      }
+      double real() {
+        return re;
+      }
+      double imag() {
+        return im;
+      }
+   };
+}
+ %}
+
+/* SWIG interface tests */
+
+#ifdef SWIGPYTHON
+%typemap(in) test::test_complex * {
+    if (PyComplex_Check($input)) {
+	$1 = new test_complex(PyComplex_RealAsDouble($input),
+			 PyComplex_ImagAsDouble($input));
+    } else {
+	PyErr_SetString(PyExc_TypeError,"Expected test_complex.\n");
+	return NULL;
+    }
+}
+%typemap(freearg) test::test_complex * {
+    delete $1;
+}
+#endif
+#ifdef SWIGOCTAVE
+%typemap(in) test::test_complex * {
+    if ($input.is_complex_scalar()) {
+	$1 = new test_complex($input.complex_value().real(),
+			      $input.complex_value().imag());
+    } else {
+	error("Expected test_complex.");
+    }
+}
+%typemap(freearg) test::test_complex * {
+    delete $1;
+}
+#endif
+
+namespace test {
+    class string_class;
+#ifdef SWIGPYTHON
+	%typemap(in) string_class * {
+	    $1 = new string_class(PyString_AsString($input));
+	}
+	%typemap(freearg) string_class * {
+	    delete $1;
+	}
+#endif
+#ifdef SWIGOCTAVE
+	%typemap(in) string_class * {
+	    $1 = new string_class($input.string_value().c_str());
+	}
+	%typemap(freearg) string_class * {
+	    delete $1;
+	}
+#endif
+#ifdef SWIGRUBY
+	%typemap(in) string_class * {
+	    $1 = new string_class(STR2CSTR($input));
+	}
+	%typemap(freearg) string_class * {
+	    delete $1;
+	}
+#endif
+}
+
+%inline %{
+    namespace test {
+	class string_class;
+	class test_complex;
+
+	/* Functions in the namespace itself */
+	char *stest1(string_class *s) {
+	    return s->c_str();
+	}
+	double ctest1(test_complex *c) {
+	    return c->real();
+	}
+    }
+
+    namespace test2 {
+	using test::string_class;
+	using test::test_complex;
+
+	/* Functions in another namespace */
+	char *stest2(string_class *s) {
+	    return s->c_str();
+	}
+	double ctest2(test_complex *c) {
+	    return c->real();
+	}
+    }
+
+    namespace test3 {
+	using namespace test;
+
+	char *stest3(string_class *s) {
+	    return s->c_str();
+	}
+	double ctest3(test_complex *c) {
+	    return c->real();
+	}
+    }
+    
+    namespace test4 {
+	using namespace test2;
+
+	char *stest4(string_class *s) {
+	    return s->c_str();
+	}
+	double ctest4(test_complex *c) {
+	    return c->real();
+	}
+    }
+
+    namespace test5 {
+	using namespace test3;
+
+	char *stest5(string_class *s) {
+	    return s->c_str();
+	}
+	double ctest5(test_complex *c) {
+	    return c->real();
+	}
+    }
+
+    char *stest6(test::string_class *s) {
+	return s->c_str();
+    }
+    double ctest6(test::test_complex *c) {
+	return c->real();
+    }
+
+    char *stest7(test2::string_class *s) {
+	return s->c_str();
+    }
+    double ctest7(test2::test_complex *c) {
+	return c->real();
+    }
+
+    char *stest8(test3::string_class *s) {
+	return s->c_str();
+    }
+    double ctest8(test3::test_complex *c) {
+	return c->real();
+    }
+
+    char *stest9(test4::string_class *s) {
+	return s->c_str();
+    }
+    double ctest9(test4::test_complex *c) {
+	return c->real();
+    }
+
+    char *stest10(test5::string_class *s) {
+	return s->c_str();
+    }
+    double ctest10(test5::test_complex *c) {
+	return c->real();
+    }
+
+    namespace test11 = test;
+    
+    char *stest11(test11::string_class *s) {
+	return s->c_str();
+    }
+    double ctest11(test11::test_complex *c) {
+	return c->real();
+    }
+
+    using namespace test2;
+    using test::test_complex;
+
+    char *stest12(string_class *s) {
+	return s->c_str();
+    }
+    double ctest12(test_complex *c) {
+	return c->real();
+    }
+%}
+
+namespace Split {
+#ifdef SWIGPYTHON
+    %typemap(in) PosInteger {
+	$1 = PyInt_AsLong($input);
+	if ($1 < 0) {
+	    PyErr_SetString(PyExc_ValueError,"domain error\n");
+	    return NULL;
+	}
+    }	
+#endif
+#ifdef SWIGOCTAVE
+    %typemap(in) PosInteger {
+	$1 = $input.long_value();
+	if ($1 < 0) {
+	  error("domain error");
+	}
+    }	
+#endif
+#ifdef SWIGRUBY
+    %typemap(in) PosInteger {
+	$1 = NUM2INT($input);
+	if ($1 < 0) {
+	    rb_raise(rb_eRangeError, "domain error");
+	}
+    }	
+#endif
+}
+    
+%inline %{
+    namespace Split {
+	typedef int PosInteger;
+	PosInteger ttest1(PosInteger x) {
+	    return x;
+	}
+    }
+%}
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/namespace_union.i b/trunk/Examples/test-suite/namespace_union.i
new file mode 100644
index 0000000..edade96
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_union.i
@@ -0,0 +1,28 @@
+%module namespace_union
+%inline %{
+namespace SpatialIndex 
+{ 
+        class Variant 
+        { 
+        public: 
+                Variant() { }; 
+                int varType; 
+                union 
+                { 
+                        long           lVal;         // VT_LONG 
+                        short          iVal;         // VT_SHORT 
+                        float          fltVal;       // VT_FLOAT 
+                        double         dblVal;       // VT_DOUBLE 
+                        char           cVal;         // VT_CHAR 
+                        unsigned short uiVal;        // VT_USHORT 
+                        unsigned long  ulVal;        // VT_ULONG 
+                        int            intVal;       // VT_INT 
+                        unsigned int   uintVal;      // VT_UINT 
+                        bool           blVal;        // VT_BOOL 
+                        char*          pcVal;        // VT_PCHAR 
+                        void*          pvVal;        // VT_PVOID 
+                } val; 
+        }; // Variant 
+} 
+%}
+ 
diff --git a/trunk/Examples/test-suite/namespace_virtual_method.i b/trunk/Examples/test-suite/namespace_virtual_method.i
new file mode 100644
index 0000000..05c8f97
--- /dev/null
+++ b/trunk/Examples/test-suite/namespace_virtual_method.i
@@ -0,0 +1,41 @@
+%module namespace_virtual_method
+
+%warnfilter(515);
+
+
+%inline %{
+
+namespace A {
+   namespace B {
+       class Foo;
+   }
+   namespace C {
+       class Foo {
+	public:
+           Foo() { };
+           virtual ~Foo() { };
+           virtual int bar(const A::B::Foo &x) = 0;
+       };
+   }
+}
+
+namespace A {
+   namespace C {
+        class Spam : public Foo {
+	public:
+            Spam() { }
+            virtual ~Spam() { }
+            virtual int bar(const B::Foo &x) { return 1; }
+        };
+   }
+}
+
+%}
+
+%{
+namespace A {
+   namespace B {
+         class Foo { };
+   }
+}
+%}
diff --git a/trunk/Examples/test-suite/naturalvar.i b/trunk/Examples/test-suite/naturalvar.i
new file mode 100644
index 0000000..af13620
--- /dev/null
+++ b/trunk/Examples/test-suite/naturalvar.i
@@ -0,0 +1,40 @@
+%module(naturalvar) naturalvar
+
+#ifdef __cplusplus
+%include std_string.i
+%inline 
+{
+  struct Foo
+  {
+  };
+  
+
+  Foo f;
+  std::string s;
+  struct Bar
+  {
+    int i;
+    Foo f;
+    std::string s;
+  };
+}
+#else
+%inline 
+{
+  typedef struct _foo
+  {
+  }Foo;
+  
+
+  Foo f;
+  char *s;
+  typedef struct _bar
+  {
+    int i;
+    Foo f;
+    char *s;
+  }  Bar;
+}
+#endif
+
+    
diff --git a/trunk/Examples/test-suite/nested.i b/trunk/Examples/test-suite/nested.i
new file mode 100644
index 0000000..0b93be4
--- /dev/null
+++ b/trunk/Examples/test-suite/nested.i
@@ -0,0 +1,33 @@
+/* 
+This testcase tests that nested structs/unions work. Named structs/unions declared within
+a struct produced redefinition errors in SWIG 1.3.6 as reported by SF bug #447488.
+Also tests reported error when a #define placed in a deeply embedded struct/union.
+*/
+
+%module nested
+
+%inline %{
+
+struct TestStruct {
+  int a;
+};
+
+typedef struct OuterStruct {
+  union {
+
+    struct outer_nested_struct {
+      union inner_nested_union {
+#define BAD_STYLE 1
+        int red;
+        struct TestStruct green;
+      } InnerNestedUnion;
+
+      struct inner_nested_struct {
+        int blue;
+      } InnerNestedStruct;
+    } OuterNestedStruct;
+
+  } EmbeddedUnion;
+} OuterStruct;
+
+%}
diff --git a/trunk/Examples/test-suite/nested_comment.i b/trunk/Examples/test-suite/nested_comment.i
new file mode 100644
index 0000000..16f1b7a
--- /dev/null
+++ b/trunk/Examples/test-suite/nested_comment.i
@@ -0,0 +1,41 @@
+%module nested_comment
+
+// this example shows a problem with 'dump_nested' (parser.y).
+
+// bug #949654
+%inline %{
+typedef struct s1 {
+union {
+int fsc; /* genie structure hiding - Conductor
+*/
+int fso; /* genie structure hiding - FSOptions
+*/
+struct {
+double *vals;
+int size;
+} vector_val; /* matrix values are mainly used
+in rlgc models */
+char *name;
+} n ;
+} s2; 
+
+%}
+
+// bug #491476
+%inline %{
+struct {
+struct {
+int a;
+} a, b;
+} a;
+
+%}
+
+// bug #909387
+%inline %{
+struct foo {
+  struct happy; // no warning
+  struct sad { int x; }; // warning
+  happy *good(); // produces good code
+  sad *bad(); // produces bad code
+};
diff --git a/trunk/Examples/test-suite/newobject1.i b/trunk/Examples/test-suite/newobject1.i
new file mode 100644
index 0000000..b5b018b
--- /dev/null
+++ b/trunk/Examples/test-suite/newobject1.i
@@ -0,0 +1,51 @@
+/**
+ * The purpose of this test is to confirm that a language module
+ * correctly handles the case when C++ class member functions (of both
+ * the static and non-static persuasion) have been tagged with the
+ * %newobject directive.
+ */
+
+%module newobject1
+
+%newobject Foo::makeFoo();
+%newobject Foo::makeMore();
+
+%inline %{
+class Foo
+{
+private:
+    Foo(const Foo&);
+    Foo& operator=(const Foo&);
+private:
+    static int m_fooCount;
+protected:
+    Foo() {
+        m_fooCount++;
+    }
+public:
+    // Factory function (static)
+    static Foo *makeFoo() {
+        return new Foo;
+    }
+    
+    // Factory function (regular)
+    Foo *makeMore() {
+        return new Foo;
+    }
+    
+    // Return the number of instances
+    static int fooCount() {
+        return m_fooCount;
+    }
+    
+    // Destructor
+    ~Foo() {
+        m_fooCount--;
+    }
+};
+%}
+
+%{
+// Static member initialization (not wrapped)
+int Foo::m_fooCount = 0;
+%}
diff --git a/trunk/Examples/test-suite/newobject2.i b/trunk/Examples/test-suite/newobject2.i
new file mode 100644
index 0000000..bc7394d
--- /dev/null
+++ b/trunk/Examples/test-suite/newobject2.i
@@ -0,0 +1,47 @@
+/**
+ * The purpose of this test is to confirm that a language module
+ * correctly handles the case when a C function has been tagged with the
+ * %newobject directive.
+ */
+
+%module newobject2
+
+%{
+#include <stdlib.h>
+%}
+
+%{
+/* Global initialization (not wrapped) */
+int g_fooCount = 0;
+%}
+
+%newobject makeFoo();
+
+%inline %{
+/* Struct definition */
+typedef struct {
+  int dummy;
+} Foo;
+
+/* Make one */
+Foo *makeFoo() {
+    Foo *foo = (Foo *) malloc(sizeof(Foo));
+    g_fooCount++;
+    return foo;
+}
+
+/* Return the number of instances */
+int fooCount() {
+    return g_fooCount;
+}
+
+void do_stuff(Foo *f) {
+}
+%}
+
+%extend Foo {
+    ~Foo() {
+        free((void *) $self);
+	g_fooCount--;
+    }
+}
diff --git a/trunk/Examples/test-suite/null_pointer.i b/trunk/Examples/test-suite/null_pointer.i
new file mode 100644
index 0000000..59d554c
--- /dev/null
+++ b/trunk/Examples/test-suite/null_pointer.i
@@ -0,0 +1,10 @@
+%module null_pointer
+
+%inline {
+  struct A {};
+  
+  bool func(A* a) {
+    return !a;
+  }
+}
+
diff --git a/trunk/Examples/test-suite/ocaml/Makefile.in b/trunk/Examples/test-suite/ocaml/Makefile.in
new file mode 100644
index 0000000..6f0b654
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/Makefile.in
@@ -0,0 +1,80 @@
+#######################################################################
+# Makefile for ocaml test-suite
+#######################################################################
+
+LANGUAGE     = ocaml
+OCAMLC       = ocamlc
+VARIANT      = _static
+SCRIPTSUFFIX = _runme.ml
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+C_TEST_CASES = 
+
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) -a \
+	     -f $(top_srcdir)/Examples/test-suite/$*.list ] ; then ( \
+		$(COMPILETOOL) $(OCAMLC) -c $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \
+		$(COMPILETOOL) $(OCAMLC) swig.cmo -custom -g -cc '$(CXX)' -o runme `cat $(top_srcdir)/Examples/test-suite/$(*).list | sed -e 's/\(.*\)/\1_wrap.o \1.cmo/g'`&& ./runme) ; \
+	elif [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+		$(COMPILETOOL) $(OCAMLC) -c $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \
+		$(COMPILETOOL) $(OCAMLC) swig.cmo -custom -g -cc '$(CXX)' -o runme $(srcdir)/$(*).cmo $(srcdir)/$(*)_runme.cmo $(srcdir)/$(*)_wrap.o && \
+		$(RUNTOOL) ./runme) ; \
+	fi ; 
+
+check_quant:
+	cat /dev/null > testing
+	cat /dev/null > success
+	cat /dev/null > results
+	$(MAKE) check
+	echo "Failed:" >> results
+	for element in `cat testing` ; do \
+		if grep $$element success >/dev/null 2>/dev/null ; then \
+			: ; \
+		else \
+			echo $$element >> results ; \
+		fi ; \
+	done
+	echo "Success:" >> results
+	cat success >> results
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+# none!
+
+# Rules for the different types of tests
+%.cpptest:
+	echo $@ >> testing
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+	if [ -f $(@:%.cpptest=%_wrap.o) ] ; then \
+		echo $@ >> success ; \
+	fi
+
+%.ctest:
+	echo $@ >> testing
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+	if [ -f $(@:%.ctest=%_wrap.o) ] ; then \
+		echo $@ >> success ; \
+	fi
+
+%.multicpptest:
+	echo $@ >> testing
+	+$(swig_and_compile_multi_cpp)
+	$(setup)
+	$(run_testcase)
+	if [ -f $(@:%.multicpptest=%_runtime_wrap.o) ] ; then \
+		echo $@ >> success ; \
+	fi
+
+# Clean
+%.clean:
+	@rm -f $*.ml $*.mli;
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile ocaml_clean
diff --git a/trunk/Examples/test-suite/ocaml/README b/trunk/Examples/test-suite/ocaml/README
new file mode 100644
index 0000000..3fdea62
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/README
@@ -0,0 +1,2 @@
+I stole most of these runme's from the ruby runme scripts, since the current
+ocaml interface mirrors the ruby interface in many ways.
diff --git a/trunk/Examples/test-suite/ocaml/class_ignore_runme.ml b/trunk/Examples/test-suite/ocaml/class_ignore_runme.ml
new file mode 100644
index 0000000..5189305
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/class_ignore_runme.ml
@@ -0,0 +1,7 @@
+open Swig
+open Class_ignore
+
+let a = new_Bar C_void
+let _ = (if _do_blah a <> C_string "Bar::blah" then
+  raise (Failure "We didn't really get a bar object."))
+
diff --git a/trunk/Examples/test-suite/ocaml/imports_runme.ml b/trunk/Examples/test-suite/ocaml/imports_runme.ml
new file mode 100644
index 0000000..33d6314
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/imports_runme.ml
@@ -0,0 +1,10 @@
+(* purpose: to receive the hello A method from Imports_a exposed through
+ * a B object derived from A *)
+
+open Swig
+open Imports_a
+open Imports_b
+let x = new_B C_void
+(* Tests conversion of x to a generic value *)
+let a = swig_val `unknown x
+let _ = (invoke x) "hello" C_void
diff --git a/trunk/Examples/test-suite/ocaml/makedebugtop b/trunk/Examples/test-suite/ocaml/makedebugtop
new file mode 100755
index 0000000..d51439a
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/makedebugtop
@@ -0,0 +1,21 @@
+#!/bin/sh
+#
+# Usage: makedebugtop test_name.c[pp]test
+#
+# Creates an ocaml toplevel for debugging based on a .cpptest or .ctest
+# file.
+#
+
+OCAMLINC=/usr/local/lib/ocaml
+swigtest=$1
+thetest=`echo $1 | sed -e 's/\.c[p]*test//g'`
+cppopt=""
+if echo $swigtest | grep -s cpptest ; then
+	cppopt=-xc++
+fi
+
+echo "Making the test"
+make $swigtest
+echo "Building ${thetest}_top"
+gcc -c -g $cppopt -I$OCAMLINC ${thetest}_wrap.c
+ocamlmktop -cclib -g -custom swig.cmo ${thetest}_wrap.o ${thetest}.cmo -o ${thetest}_top -cclib -lstdc++
diff --git a/trunk/Examples/test-suite/ocaml/minherit_runme.ml b/trunk/Examples/test-suite/ocaml/minherit_runme.ml
new file mode 100644
index 0000000..29a37f4
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/minherit_runme.ml
@@ -0,0 +1,131 @@
+(* Stolen from the python tests *)
+open Swig
+open Minherit
+
+let a = new_Foo C_void
+let b = new_Bar C_void 
+let c = new_FooBar C_void
+let d = new_Spam C_void
+
+let soci x = (string_of_int (get_int x))
+
+let _ =
+  if (invoke a) "xget" C_void <> (C_int 1) then
+    raise (Failure "Bad attribute value (a.xget)")
+
+let _ =
+  if (invoke b) "yget" C_void <> (C_int 2) then
+    raise (Failure "Bad attribute value (b.yget)")
+
+let _ =
+  if   (invoke c) "xget" C_void <> (C_int 1)
+    || (invoke c) "yget" C_void <> (C_int 2)
+    || (invoke c) "zget" C_void <> (C_int 3) then
+      raise (Failure "Bad attribute value c")
+	
+let _ =
+  if   (invoke d) "xget" C_void <> (C_int 1)
+    || (invoke d) "yget" C_void <> (C_int 2)
+    || (invoke d) "zget" C_void <> (C_int 3)
+    || (invoke d) "wget" C_void <> (C_int 4) then
+      raise (Failure "Bad attribute value d")
+
+let xga = _xget a
+let _ =
+  if xga <> (C_int 1) then
+    raise (Failure ("Bad attribute value (xget a): " ^ (soci xga)))
+
+let ygb = _yget b
+let _ =
+  if ygb <> (C_int 2) then
+    raise (Failure ("Bad attribute value (yget b): " ^
+		    (string_of_int (get_int ygb))))
+
+let xgc = _xget c and ygc = _yget c and zgc = _zget c
+let _ =
+  if xgc <> (C_int 1) || ygc <> (C_int 2) || zgc <> (C_int 3) then
+    raise (Failure ("Bad attribute value (xgc=" ^ (soci xgc) ^
+		    " (sb 1) ygc=" ^ (soci ygc) ^
+		    " (sb 2) zgc=" ^ (soci zgc) ^
+		    " (sb 3))"))
+
+let xgd = _xget d and ygd = _yget d and zgd = _zget d and wgd = _wget d
+let _ =
+  if   xgd <> (C_int 1) || ygd <> (C_int 2) 
+    || zgd <> (C_int 3) || wgd <> (C_int 4) then
+      raise (Failure ("Bad attribute value (xgd=" ^ (soci xgd) ^
+		      " (sb 1) ygd=" ^ (soci ygd) ^
+		      " (sb 2) zgd=" ^ (soci zgd) ^
+		      " (sb 3)"))
+
+(* Cleanse all of the pointers and see what happens *)
+
+let aa = _toFooPtr a
+let bb = _toBarPtr b
+let cc = _toFooBarPtr c
+let dd = _toSpamPtr d
+
+let xgaa = (invoke aa) "xget" C_void
+let _ =
+  if xgaa <> (C_int 1) then
+    raise (Failure ("Bad attribute value xgaa " ^ (soci xgaa)))
+      
+let ygbb = (invoke bb) "yget" C_void
+let _ =
+  if ygbb <> (C_int 2) then
+    raise (Failure ("Bad attribute value ygbb " ^ (soci ygbb)))
+      
+let xgcc = (invoke cc) "xget" C_void
+and ygcc = (invoke cc) "yget" C_void
+and zgcc = (invoke cc) "zget" C_void
+	     
+let _ =
+  if xgcc <> (C_int 1) || ygcc <> (C_int 2) || zgcc <> (C_int 3) then
+    raise (Failure ("Bad attribute value (" ^
+		    (soci xgcc) ^ " (sb 1) " ^
+		    (soci ygcc) ^ " (sb 2) " ^
+		    (soci zgcc) ^ " (sb 3))"))
+
+let xgdd = (invoke dd) "xget" C_void
+and ygdd = (invoke dd) "yget" C_void
+and zgdd = (invoke dd) "zget" C_void
+and wgdd = (invoke dd) "wget" C_void
+
+let _ =
+  if   xgdd <> (C_int 1) || ygdd <> (C_int 2)
+    || zgdd <> (C_int 3) || wgdd <> (C_int 4) then
+      raise (Failure ("Bad value: " ^
+		      "xgdd=" ^ (soci xgdd) ^
+		      "ygdd=" ^ (soci ygdd) ^
+		      "zgdd=" ^ (soci zgdd) ^
+		      "wgdd=" ^ (soci wgdd)))
+
+let xgaa = _xget aa
+and ygbb = _yget bb
+and xgcc = _xget cc
+and ygcc = _yget cc
+and zgcc = _zget cc
+and xgdd = _xget dd
+and ygdd = _yget dd
+and zgdd = _zget dd
+and wgdd = _wget dd
+
+let _ = 
+  if xgaa <> (C_int 1) then
+    raise (Failure ("Fn xget: xgaa=" ^ (soci xgaa)))
+
+let _ =
+  if ygbb <> (C_int 2) then
+    raise (Failure ("Fn yget: ygbb=" ^ (soci ygbb)))
+
+let _ =
+  if   xgcc <> (C_int 1) || ygcc <> (C_int 2) || zgcc <> (C_int 3) then
+    raise (Failure ("CC with fns: (" ^ 
+		    (soci xgcc) ^ " " ^ (soci ygcc) ^ " " ^ (soci zgcc)))
+
+let _ =
+  if   xgdd <> (C_int 1) || ygdd <> (C_int 2) 
+    || zgdd <> (C_int 3) || wgdd <> (C_int 4) then
+    raise (Failure ("CC with fns: (" ^ 
+		    (soci xgdd) ^ " " ^ (soci ygdd) ^ " " ^ 
+		    (soci zgdd) ^ " " ^ (soci wgdd) ^ ")"))
diff --git a/trunk/Examples/test-suite/ocaml/name_runme.ml b/trunk/Examples/test-suite/ocaml/name_runme.ml
new file mode 100644
index 0000000..1e4e62c
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/name_runme.ml
@@ -0,0 +1,9 @@
+open Swig
+open Name 
+
+let _ = if (get_int (_Baz_2 C_void)) - (get_int (_bar_2 C_void)) == 30 
+then 
+  exit 0 
+else 
+  exit 1
+  
diff --git a/trunk/Examples/test-suite/ocaml/newobject1_runme.ml b/trunk/Examples/test-suite/ocaml/newobject1_runme.ml
new file mode 100644
index 0000000..c7d66c1
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/newobject1_runme.ml
@@ -0,0 +1,26 @@
+open Swig
+open Newobject1
+
+exception RuntimeError of string * int
+
+let foo1 = ref (_Foo_makeFoo C_void)
+let _ = if get_int (_Foo_fooCount C_void) != 1 then
+   raise (RuntimeError ("(1) Foo.fooCount != 1",
+			get_int (_Foo_fooCount C_void)))
+
+let foo2 = ref ((invoke !foo1) "makeMore" C_void) 
+let _ = if get_int (_Foo_fooCount C_void) != 2 then
+   raise (RuntimeError ("(2) Foo.fooCount != 2",
+			get_int (_Foo_fooCount C_void)))
+
+let _ = begin
+  foo1 := C_void ; Gc.full_major () ;
+  (if get_int (_Foo_fooCount C_void) != 1 then
+	raise (RuntimeError ("(3) Foo.fooCount != 1",
+			     get_int (_Foo_fooCount C_void)))) ;
+
+  foo2 := C_void ; Gc.full_major () ;
+  (if get_int (_Foo_fooCount C_void) != 0 then
+	raise (RuntimeError ("(4) Foo.fooCount != 0",
+			     get_int (_Foo_fooCount C_void)))) ;
+end
diff --git a/trunk/Examples/test-suite/ocaml/overload_copy_runme.ml b/trunk/Examples/test-suite/ocaml/overload_copy_runme.ml
new file mode 100644
index 0000000..c7839aee
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/overload_copy_runme.ml
@@ -0,0 +1,5 @@
+open Swig
+open Overload_copy
+
+let f = new_Foo C_void 
+let g = new_Foo f 
diff --git a/trunk/Examples/test-suite/ocaml/sneaky1_runme.ml b/trunk/Examples/test-suite/ocaml/sneaky1_runme.ml
new file mode 100644
index 0000000..81b69f3
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/sneaky1_runme.ml
@@ -0,0 +1,9 @@
+(* Stolen from ruby test cases *)
+
+open Swig
+open Sneaky1
+
+let x = Sneaky1._add (C_list [ C_int 3; C_int 4 ])
+let y = Sneaky1._subtract (C_list [ C_int 3; C_int 4 ])
+let z = Sneaky1._mul (C_list [ C_int 3; C_int 4 ])
+let w = Sneaky1._divide (C_list [ C_int 3; C_int 4 ])
diff --git a/trunk/Examples/test-suite/ocaml/throw_exception_runme.ml b/trunk/Examples/test-suite/ocaml/throw_exception_runme.ml
new file mode 100644
index 0000000..8781926
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/throw_exception_runme.ml
@@ -0,0 +1,28 @@
+(* Throw exception test *)
+
+open Swig
+open Throw_exception
+
+let x = new_Foo C_void ;;
+let _ =
+  try
+    (invoke x) "test_int" C_void 
+  with (Failure "Exception(37): Thrown exception from C++ (int)\n") ->
+  try 
+    (invoke x) "test_msg" C_void
+  with (Failure "Exception(0): Dead\n") ->
+  try
+    (invoke x) "test_cls" C_void 
+  with (Failure "Exception(0): Thrown exception from C++ (unknown)\n") ->
+  try
+    (invoke x) "test_multi" (C_int 1)
+  with (Failure "Exception(37): Thrown exception from C++ (int)\n") ->
+  try
+    (invoke x) "test_multi" (C_int 2)
+  with (Failure "Exception(0): Dead\n") ->
+  try
+    (invoke x) "test_multi" (C_int 3)
+  with (Failure "Exception(0): Thrown exception from C++ (unknown)\n") ->
+    exit 0
+
+let _ = exit 1
diff --git a/trunk/Examples/test-suite/ocaml/typedef_mptr_runme.ml b/trunk/Examples/test-suite/ocaml/typedef_mptr_runme.ml
new file mode 100644
index 0000000..3bdaac4
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/typedef_mptr_runme.ml
@@ -0,0 +1,16 @@
+open Swig
+open Typedef_mptr
+
+let soci x = (string_of_int (get_int x))
+
+let x = new_Foo C_void 
+let add_res = _do_op (C_list [ x ; C_int 2 ; C_int 1 ; _add ])
+and sub_res = _do_op (C_list [ x ; C_int 2 ; C_int 1 ; _sub ])
+let _ =
+  if add_res <> (C_int 3) || sub_res <> (C_int 1) then
+    raise (Failure ("Bad result:" ^
+		    " (add " ^ (soci add_res) ^ ") " ^
+		    " (sub " ^ (soci sub_res) ^ ")"))
+let _ = Printf.printf "2 + 1 = %d, 2 - 1 = %d\n" 
+	  (get_int add_res)
+	  (get_int sub_res)
diff --git a/trunk/Examples/test-suite/ocaml/typename_runme.ml b/trunk/Examples/test-suite/ocaml/typename_runme.ml
new file mode 100644
index 0000000..01f49de
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/typename_runme.ml
@@ -0,0 +1,12 @@
+(* Fun with type names -- stolen from the ruby runme *)
+
+open Swig
+open Typename
+
+let f = new_Foo C_void 
+let b = new_Bar C_void
+
+let x = _twoFoo f 
+let _ = match x with C_double f -> () | _ -> raise (Failure "not a float")
+let y = _twoBar b
+let _ = match y with C_int i -> () | _ -> raise (Failure "not an int")
diff --git a/trunk/Examples/test-suite/ocaml/unions_runme.ml b/trunk/Examples/test-suite/ocaml/unions_runme.ml
new file mode 100644
index 0000000..cbf1628
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/unions_runme.ml
@@ -0,0 +1,28 @@
+(* Test the unions example... *)
+
+open Swig
+open Unions 
+
+let a = new_SmallStruct C_void
+let b = new_BigStruct C_void
+let c = new_UnionTest C_void
+let d = new_EmbeddedUnionTest C_void 
+
+let _ = (invoke a) "jill" (C_short 3)
+let _ = (invoke b) "jack" (C_char 'a')  (* Int conversion *)
+let _ = (invoke b) "smallstruct" a      (* Put a in b *)
+let _ = (invoke c) "bs" b
+
+let _ = if get_int ((invoke a) "jill" C_void) != 3 then
+	raise (Failure "jill value is not preserved")
+let _ = if get_int ((invoke b) "jack" C_void) != (int_of_char 'a') then
+	raise (Failure "jack value is not preserved")
+let _ = if get_int ((invoke ((invoke b) "smallstruct" C_void))
+	"jill" C_void) != 3 then
+	raise (Failure "jill value is not embedded in bigstruct")
+let _ = if get_int ((invoke ((invoke c) "bs" C_void))
+	"jack" C_void) != (int_of_char 'a') then
+	raise (Failure "union set of bigstruct did not take")
+let _ = if get_int ((invoke ((invoke c) "ss" C_void))
+	"jill" C_void) != (int_of_char 'a') then
+	raise (Failure "corresponding union values are not the same")
diff --git a/trunk/Examples/test-suite/ocaml/using_protected_runme.ml b/trunk/Examples/test-suite/ocaml/using_protected_runme.ml
new file mode 100644
index 0000000..4dc4fe1
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/using_protected_runme.ml
@@ -0,0 +1,8 @@
+open Swig
+open Using_protected
+
+let f = new_FooBar C_void
+let _ = (invoke f) "x" (C_int 3)
+
+let _ = if (invoke f) "blah" (C_int 4) <> (C_int 4) then
+    raise (Failure "blah(int)")
diff --git a/trunk/Examples/test-suite/ocaml/varargs_runme.ml b/trunk/Examples/test-suite/ocaml/varargs_runme.ml
new file mode 100644
index 0000000..52962d9
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/varargs_runme.ml
@@ -0,0 +1,11 @@
+(* Test case stolen from the python directory *)
+
+open Swig
+open Varargs
+
+let _ = if _test (C_string "Hello") <> (C_string "Hello") then
+    raise (Failure "1")
+
+let f = new_Foo C_void
+let _ = if (invoke f) "test" (C_string "Hello") <> (C_string "Hello") then
+    raise (Failure "2")
diff --git a/trunk/Examples/test-suite/ocaml/voidtest_runme.ml b/trunk/Examples/test-suite/ocaml/voidtest_runme.ml
new file mode 100644
index 0000000..542ec35
--- /dev/null
+++ b/trunk/Examples/test-suite/ocaml/voidtest_runme.ml
@@ -0,0 +1,8 @@
+open Swig
+open Voidtest
+
+let _ = _globalfunc C_void 
+let f = new_Foo C_void
+let _ = (invoke f) "memberfunc" C_void
+
+let _ = _Foo_staticmemberfunc C_void
diff --git a/trunk/Examples/test-suite/octave/Makefile.in b/trunk/Examples/test-suite/octave/Makefile.in
new file mode 100644
index 0000000..534da55
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/Makefile.in
@@ -0,0 +1,85 @@
+#######################################################################
+# Makefile for octave test-suite
+#######################################################################
+
+LANGUAGE     = octave
+OCTAVE       = @OCTAVE@ -q
+SCRIPTSUFFIX = _runme.m
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+CPP_TEST_CASES += \
+	cell_deref
+
+CPP_TEST_BROKEN += \
+	implicittest \
+	li_implicit \
+	li_std_map \
+	li_std_set \
+	li_std_stream
+
+#C_TEST_CASES += 
+
+#
+# This test only works with modern C compilers
+#
+#C_TEST_CASES += \
+#	complextest
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+LIBS       = -L.
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.m appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH OCTAVEPATH=$(srcdir):OCTAVEPATH $(RUNTOOL) $(OCTAVE) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: remove the generated .m file
+%.clean:
+	@rm -f hugemod.h hugemod_a.i hugemod_b.i hugemod_a.m hugemod_b.m hugemod_runme.m
+	@rm -f $*.m;
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile octave_clean
+
+cvsignore:
+	@echo '*wrap* *.mc *.so *.dll *.exp *.lib'
+	@echo Makefile
+	@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do echo $$i.m; done 
+	@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do if grep -q $${i}_runme.m CVS/Entries ; then echo $${i}_runme.m; fi; done 
+	@echo clientdata_prop_a.m 
+	@echo clientdata_prop_b.m 
+	@echo imports_a.m 
+	@echo imports_b.m 
+	@echo mod_a.m mod_b.m 
+	@echo hugemod.h hugemod_a.i hugemod_b.i hugemod_a.m hugemod_b.m hugemod_runme.m
+	@echo template_typedef_import.m
+
+
+hugemod:
+	perl hugemod.pl
+	$(MAKE) hugemod_a.cpptest
+	$(MAKE) hugemod_b.cpptest
+	time $(OCTAVE) hugemod_runme.m
+	time $(OCTAVE) hugemod_runme.m
diff --git a/trunk/Examples/test-suite/octave/abstract_access_runme.m b/trunk/Examples/test-suite/octave/abstract_access_runme.m
new file mode 100644
index 0000000..e49343a
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/abstract_access_runme.m
@@ -0,0 +1,7 @@
+abstract_access
+
+d = abstract_access.D();
+if (d.do_x() != 1)
+   error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/abstract_typedef2_runme.m b/trunk/Examples/test-suite/octave/abstract_typedef2_runme.m
new file mode 100644
index 0000000..7f364db
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/abstract_typedef2_runme.m
@@ -0,0 +1,8 @@
+abstract_typedef2
+
+a = A_UF();
+  
+
+
+
+
diff --git a/trunk/Examples/test-suite/octave/abstract_typedef_runme.m b/trunk/Examples/test-suite/octave/abstract_typedef_runme.m
new file mode 100644
index 0000000..f28cf3c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/abstract_typedef_runme.m
@@ -0,0 +1,12 @@
+abstract_typedef
+e = Engine();
+
+a = A();
+  
+
+if (a.write(e) != 1)
+  error
+endif
+
+
+
diff --git a/trunk/Examples/test-suite/octave/abstract_virtual_runme.m b/trunk/Examples/test-suite/octave/abstract_virtual_runme.m
new file mode 100644
index 0000000..9845a58
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/abstract_virtual_runme.m
@@ -0,0 +1,7 @@
+abstract_virtual
+
+
+d = D();
+
+e = E();
+
diff --git a/trunk/Examples/test-suite/octave/argcargvtest_runme.m b/trunk/Examples/test-suite/octave/argcargvtest_runme.m
new file mode 100644
index 0000000..f246dd9
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/argcargvtest_runme.m
@@ -0,0 +1,29 @@
+argcargvtest
+
+largs={'hi','hola','hello'};
+if (mainc(largs) != 3)
+  error("bad main typemap");
+endif
+
+targs={'hi','hola'};
+if (mainv(targs,1) != 'hola')
+  error("bad main typemap");
+endif
+
+targs={'hi', 'hola'};
+if (mainv(targs,1) != 'hola')
+  error("bad main typemap");
+endif
+
+try
+  error_flag = 0;
+  mainv('hello',1);
+  error_flag = 1;
+catch
+end_try_catch
+if (error_flag)
+  error("bad main typemap")
+endif
+
+
+initializeApp(largs);
diff --git a/trunk/Examples/test-suite/octave/array_member_runme.m b/trunk/Examples/test-suite/octave/array_member_runme.m
new file mode 100644
index 0000000..56b7968
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/array_member_runme.m
@@ -0,0 +1,25 @@
+array_member
+
+f = Foo();
+f.data = cvar.global_data;
+
+for i=0:7,
+    if (get_value(f.data,i) != get_value(cvar.global_data,i))
+      error("Bad array assignment");
+    endif
+endfor
+
+for i=0:7,
+    set_value(f.data,i,-i);
+endfor
+
+cvar.global_data = f.data;
+
+for i=0:7,
+  if (get_value(f.data,i) != get_value(cvar.global_data,i))
+    error("Bad array assignment")
+  endif
+endfor
+
+
+
diff --git a/trunk/Examples/test-suite/octave/arrays_global_runme.m b/trunk/Examples/test-suite/octave/arrays_global_runme.m
new file mode 100644
index 0000000..619d381
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/arrays_global_runme.m
@@ -0,0 +1,19 @@
+arrays_global
+
+arrays_global.cvar.array_i = arrays_global.cvar.array_const_i;
+
+cvar.BeginString_FIX44a;
+cvar.BeginString_FIX44b;
+cvar.BeginString_FIX44c;
+cvar.BeginString_FIX44d;
+cvar.BeginString_FIX44d;
+cvar.BeginString_FIX44b = strcat("12","\0","45");
+cvar.BeginString_FIX44b;
+cvar.BeginString_FIX44d;
+cvar.BeginString_FIX44e;
+cvar.BeginString_FIX44f;
+
+test_a("hello","hi","chello","chi");
+
+test_b("1234567","hi");
+
diff --git a/trunk/Examples/test-suite/octave/callback_runme.m b/trunk/Examples/test-suite/octave/callback_runme.m
new file mode 100644
index 0000000..db9f788
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/callback_runme.m
@@ -0,0 +1,40 @@
+_callback
+callback
+
+if (foo(2) != 2)
+  error
+endif
+
+if (A_bar(2) != 4)
+  error
+endif
+
+if (foobar(3, _callback.foo) != foo(3))
+  error  
+endif
+
+if (foobar(3, foo) != foo(3))
+  error  
+endif
+
+if (foobar(3, A_bar) != A_bar(3))
+  error
+endif
+
+if (foobar(3, foof) != foof(3))
+  error
+endif
+
+if (foobar_i(3, foo_i) != foo_i(3))
+  error
+endif
+
+
+if (foobar_d(3.5, foo_d) != foo_d(3.5))
+  error
+endif
+
+a = A();
+if (foobarm(3, a, A.foom_cb_ptr) != a.foom(3))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/cell_deref.i b/trunk/Examples/test-suite/octave/cell_deref.i
new file mode 100644
index 0000000..fddcd80
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/cell_deref.i
@@ -0,0 +1,15 @@
+%module cell_deref
+
+%inline {
+  bool func(const char* s) {
+    return !strcmp("hello",s);
+  }
+
+ Cell func2() {
+   Cell c(1,2);
+   c(0) = "hello";
+   c(1) = 4;
+   return c;
+ } 
+}
+
diff --git a/trunk/Examples/test-suite/octave/cell_deref_runme.m b/trunk/Examples/test-suite/octave/cell_deref_runme.m
new file mode 100644
index 0000000..1c370fe
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/cell_deref_runme.m
@@ -0,0 +1,8 @@
+cell_deref;
+
+assert(func("hello"));
+assert(func({"hello"}));
+
+c = func2();
+assert(strcmp(c{1}, "hello"));
+assert(c{2} == 4);
diff --git a/trunk/Examples/test-suite/octave/class_ignore_runme.m b/trunk/Examples/test-suite/octave/class_ignore_runme.m
new file mode 100644
index 0000000..76bbcd3
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/class_ignore_runme.m
@@ -0,0 +1,7 @@
+class_ignore
+
+a = class_ignore.Bar();
+
+if (!strcmp(class_ignore.do_blah(a),"Bar::blah"))
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/class_scope_weird_runme.m b/trunk/Examples/test-suite/octave/class_scope_weird_runme.m
new file mode 100644
index 0000000..2fc8578
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/class_scope_weird_runme.m
@@ -0,0 +1,7 @@
+class_scope_weird
+
+f = class_scope_weird.Foo();
+g = class_scope_weird.Foo(3);
+if (f.bar(3) != 3)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/compactdefaultargs_runme.m b/trunk/Examples/test-suite/octave/compactdefaultargs_runme.m
new file mode 100644
index 0000000..08e8727
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/compactdefaultargs_runme.m
@@ -0,0 +1,24 @@
+compactdefaultargs
+
+defaults1 = Defaults1(1000);
+defaults1 = Defaults1();
+
+if (defaults1.ret(10.0) != 10.0)
+  error
+endif
+
+if (defaults1.ret() != -1.0)
+  error
+endif
+
+defaults2 = Defaults2(1000);
+defaults2 = Defaults2();
+
+if (defaults2.ret(10.0) != 10.0)
+  error
+endif
+
+if (defaults2.ret() != -1.0)
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/complextest_runme.m b/trunk/Examples/test-suite/octave/complextest_runme.m
new file mode 100644
index 0000000..cd0f9f4
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/complextest_runme.m
@@ -0,0 +1,19 @@
+complextest
+
+a = complex(-1,2);
+
+if (complextest.Conj(a) != a.conjugate())
+  error("bad complex mapping")
+endif
+
+if (complextest.Conjf(a) != a.conjugate())
+  error("bad complex mapping")
+endif
+
+
+v = (complex(1,2), complex(2,3), complex(4,3), 1);
+
+try
+  complextest.Copy_h(v);
+catch
+end_try_catch
diff --git a/trunk/Examples/test-suite/octave/constover_runme.m b/trunk/Examples/test-suite/octave/constover_runme.m
new file mode 100644
index 0000000..febcdae
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/constover_runme.m
@@ -0,0 +1,34 @@
+constover
+
+p = constover.test("test");
+if (!strcmp(p,"test"))
+    error("test failed!")
+endif
+
+p = constover.test_pconst("test");
+if (!strcmp(p,"test_pconst"))
+    error("test_pconst failed!")
+endif
+    
+f = constover.Foo();
+p = f.test("test");
+if (!strcmp(p,"test"))
+    error("member-test failed!")
+endif
+
+p = f.test_pconst("test");
+if (!strcmp(p,"test_pconst"))
+    error("member-test_pconst failed!")
+endif
+
+p = f.test_constm("test");
+if (!strcmp(p,"test_constmethod"))
+    error("member-test_constm failed!")
+endif
+
+p = f.test_pconstm("test");
+if (!strcmp(p,"test_pconstmethod"))
+    error("member-test_pconstm failed!")
+endif
+
+
diff --git a/trunk/Examples/test-suite/octave/constructor_copy_runme.m b/trunk/Examples/test-suite/octave/constructor_copy_runme.m
new file mode 100644
index 0000000..5d52ab5
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/constructor_copy_runme.m
@@ -0,0 +1,44 @@
+constructor_copy
+
+f1 = Foo1(3);
+f11 = Foo1(f1);
+
+
+if (f1.x != f11.x)
+    error
+endif
+
+
+f8 = Foo8();
+try
+    f81 = Foo8(f8);
+    good = 0;
+catch
+    good = 1;
+end_try_catch
+
+if (!good)
+    error
+endif
+
+
+bi = Bari(5);
+bc = Bari(bi);
+
+if (bi.x != bc.x)
+    error
+endif
+    
+
+bd = Bard(5);
+try
+    bc = Bard(bd);
+    good = 0;
+catch
+    good = 1;
+end_try_catch
+
+if (!good)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/contract_runme.m b/trunk/Examples/test-suite/octave/contract_runme.m
new file mode 100644
index 0000000..9170e77
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/contract_runme.m
@@ -0,0 +1,135 @@
+contract
+
+contract.test_preassert(1,2);
+try
+	contract.test_preassert(-1,0)
+	error("Failed! Preassertions are broken")
+catch
+end_try_catch
+
+contract.test_postassert(3);
+try
+	contract.test_postassert(-3);
+	error("Failed! Postassertions are broken")
+catch
+end_try_catch
+
+contract.test_prepost(2,3);
+contract.test_prepost(5,-4);
+try
+	contract.test_prepost(-3,4);
+	error("Failed! Preassertions are broken")
+catch
+end_try_catch
+
+try
+	contract.test_prepost(4,-10);
+	error("Failed! Postassertions are broken")
+
+catch
+end_try_catch
+
+f = contract.Foo();
+f.test_preassert(4,5);
+try
+	f.test_preassert(-2,3);
+	error("Failed! Method preassertion.")
+catch
+end_try_catch
+
+f.test_postassert(4);
+try
+	f.test_postassert(-4);
+	error("Failed! Method postassertion")
+catch
+end_try_catch
+
+f.test_prepost(3,4);
+f.test_prepost(4,-3);
+try
+	f.test_prepost(-4,2);
+	error("Failed! Method preassertion.")
+catch
+end_try_catch
+
+try
+	f.test_prepost(4,-10);
+	error("Failed! Method postassertion.")
+catch
+end_try_catch
+
+contract.Foo_stest_prepost(4,0);
+try
+	contract.Foo_stest_prepost(-4,2);
+	error("Failed! Static method preassertion")
+catch
+end_try_catch
+
+try
+	contract.Foo_stest_prepost(4,-10);
+	error("Failed! Static method posteassertion")
+catch
+end_try_catch
+	
+b = contract.Bar();
+try
+	b.test_prepost(2,-4);
+	error("Failed! Inherited preassertion.")
+catch
+end_try_catch
+
+
+d = contract.D();
+try
+	d.foo(-1,1,1,1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.foo(1,-1,1,1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.foo(1,1,-1,1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.foo(1,1,1,-1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.foo(1,1,1,1,-1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+
+
+try
+	d.bar(-1,1,1,1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.bar(1,-1,1,1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.bar(1,1,-1,1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.bar(1,1,1,-1,1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+try
+	d.bar(1,1,1,1,-1);
+	error("Failed! Inherited preassertion (D).")
+catch
+end_try_catch
+
diff --git a/trunk/Examples/test-suite/octave/cpp_enum_runme.m b/trunk/Examples/test-suite/octave/cpp_enum_runme.m
new file mode 100644
index 0000000..fe5f3b1
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/cpp_enum_runme.m
@@ -0,0 +1,27 @@
+cpp_enum
+
+f = cpp_enum.Foo();
+
+if (f.hola != cpp_enum.Foo_Hello)
+     error(f.hola);
+     error;
+endif
+
+f.hola = cpp_enum.Foo_Hi;
+if (f.hola != cpp_enum.Foo_Hi)
+     error(f.hola);
+     error;
+endif
+
+f.hola = cpp_enum.Foo_Hello;
+
+if (f.hola != cpp_enum.Foo_Hello)
+     error(f.hola);
+     error;
+endif
+
+cpp_enum.hi = cpp_enum.Hello;
+if (cpp_enum.hi != cpp_enum.Hello)
+     error(cpp_enum.hi);
+     error;
+endif
diff --git a/trunk/Examples/test-suite/octave/cpp_namespace_runme.m b/trunk/Examples/test-suite/octave/cpp_namespace_runme.m
new file mode 100644
index 0000000..ac6c663
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/cpp_namespace_runme.m
@@ -0,0 +1,55 @@
+# Note: This example assumes that namespaces are flattened
+cpp_namespace
+
+n = cpp_namespace.fact(4);
+if (n != 24)
+    error("Bad return value!")
+endif
+
+if (cpp_namespace.cvar.Foo != 42)
+    error("Bad variable value!")
+endif
+
+t = cpp_namespace.Test();
+if (!strcmp(t.method(),"Test::method"))
+    error("Bad method return value!")
+endif
+
+if (!strcmp(cpp_namespace.do_method(t),"Test::method"))
+    error("Bad return value!")
+endif
+
+if (!strcmp(cpp_namespace.do_method2(t),"Test::method"))
+    error("Bad return value!")
+endif
+    
+cpp_namespace.weird("hello", 4);
+
+clear t;
+
+t2 = cpp_namespace.Test2();
+t3 = cpp_namespace.Test3();
+t4 = cpp_namespace.Test4();
+t5 = cpp_namespace.Test5();
+
+if (cpp_namespace.foo3(42) != 42)
+    error("Bad return value!")
+endif
+
+if (!strcmp(cpp_namespace.do_method3(t2,40),"Test2::method"))
+    error("Bad return value!")
+endif
+
+if (!strcmp(cpp_namespace.do_method3(t3,40),"Test3::method"))
+    error("Bad return value!")
+endif
+
+if (!strcmp(cpp_namespace.do_method3(t4,40),"Test4::method"))
+    error("Bad return value!")
+endif
+
+if (!strcmp(cpp_namespace.do_method3(t5,40),"Test5::method"))
+    error("Bad return value!")
+endif
+
+    
diff --git a/trunk/Examples/test-suite/octave/default_args_runme.m b/trunk/Examples/test-suite/octave/default_args_runme.m
new file mode 100644
index 0000000..f8a6560
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/default_args_runme.m
@@ -0,0 +1,86 @@
+default_args
+
+
+if (default_args.Statics.staticmethod() != 60)
+  error
+endif
+
+if (default_args.cfunc1(1) != 2)
+  error
+endif
+
+if (default_args.cfunc2(1) != 3)
+  error
+endif
+
+if (default_args.cfunc3(1) != 4)
+  error
+endif
+
+
+f = default_args.Foo();
+
+f.newname();
+f.newname(1);
+
+
+try
+  f = default_args.Foo(1);
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+if (ok)
+  error("Foo::Foo ignore is not working")
+endif
+
+try
+  f = default_args.Foo(1,2);
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+if (ok)
+  error("Foo::Foo ignore is not working")
+endif
+
+try
+  f = default_args.Foo(1,2,3);
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+if (ok)
+  error("Foo::Foo ignore is not working")
+endif
+
+try
+  m = f.meth(1);
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+if (ok)
+  error("Foo::meth ignore is not working")
+endif
+
+try
+  m = f.meth(1,2);
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+if (ok)
+  error("Foo::meth ignore is not working")
+endif
+
+try
+  m = f.meth(1,2,3);
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+if (ok)
+  error("Foo::meth ignore is not working")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/default_constructor_runme.m b/trunk/Examples/test-suite/octave/default_constructor_runme.m
new file mode 100644
index 0000000..41d0f3f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/default_constructor_runme.m
@@ -0,0 +1,111 @@
+default_constructor
+
+dc = default_constructor;
+
+a = dc.new_A();
+dc.delete_A(a);
+
+aa = dc.new_AA();
+dc.delete_AA(aa);
+
+try
+    b = dc.new_B();
+    error("Whoa. new_BB created.")
+catch
+end_try_catch
+
+del_b = dc.delete_B;
+
+try
+    bb = dc.new_BB();
+    error("Whoa. new_BB created.")
+catch
+end_try_catch
+
+del_bb = dc.delete_BB;
+
+try
+    c = dc.new_C();
+    error("Whoa. new_C created.")
+catch
+end_try_catch
+
+del_c = dc.delete_C;
+
+cc = dc.new_CC();
+dc.delete_CC(cc);
+
+try
+    d = dc.new_D();
+    error("Whoa. new_D created")
+catch
+end_try_catch
+
+del_d = dc.delete_D;
+
+try
+    dd = dc.new_DD();
+    error("Whoa. new_DD created")
+catch
+end_try_catch
+
+dd = dc.delete_DD;
+
+try
+    ad = dc.new_AD();
+    error("Whoa. new_AD created")
+catch
+end_try_catch
+
+del_ad = dc.delete_AD;
+
+e = dc.new_E();
+dc.delete_E(e);
+
+ee = dc.new_EE();
+dc.delete_EE(ee);
+
+try
+    eb = dc.new_EB();
+    error("Whoa. new_EB created")
+catch
+end_try_catch
+
+del_eb = dc.delete_EB;
+
+f = dc.new_F();
+
+try
+    del_f = dc.delete_F;
+    error("Whoa. delete_F created")
+catch
+end_try_catch
+
+dc.F_destroy(f);
+
+ff = dc.new_FFF();
+try
+    del_ff = dc.delete_FFF;
+    error("Whoa. delete_FFF created")
+catch
+end_try_catch
+
+dc.F_destroy(ff);
+
+g = dc.new_G();
+
+try
+    del_g = dc.delete_G;
+    error("Whoa. delete_G created")
+catch
+end_try_catch
+
+dc.G_destroy(g);
+
+gg = dc.new_GG();
+dc.delete_GG(gg);
+
+
+hh = default_constructor.HH(1,1);
+
+
diff --git a/trunk/Examples/test-suite/octave/director_abstract_runme.m b/trunk/Examples/test-suite/octave/director_abstract_runme.m
new file mode 100644
index 0000000..00fb676
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_abstract_runme.m
@@ -0,0 +1,44 @@
+director_abstract
+
+MyFoo=@() subclass(director_abstract.Foo(),@ping);
+function out=ping(self)
+  out="MyFoo::ping()";
+end
+
+
+a = MyFoo();
+
+if (!strcmp(a.ping(),"MyFoo::ping()"))
+  error(a.ping())
+endif
+
+if (!strcmp(a.pong(),"Foo::pong();MyFoo::ping()"))
+  error(a.pong())
+endif
+
+
+MyExample1=@() subclass(director_abstract.Example1(),'Color',@(self,r,g,b) r);
+MyExample2=@(a,b) subclass(director_abstract.Example2(a,b),'Color',@(self,r,g,b) g);
+MyExample3=@() subclass(director_abstract.Example3_i(),'Color',@(self,r,g,b) b);
+
+me1 = MyExample1();
+if (director_abstract.Example1.get_color(me1, 1,2,3) != 1)
+  error
+endif
+
+me2 = MyExample2(1,2);
+if (me2.get_color(me2, 1,2,3) != 2)
+  error
+endif
+
+me3 = MyExample3();
+if (me3.get_color(me3, 1,2,3) != 3)
+  error
+endif
+
+
+# don't check that we cannot construct abstract bases, since we have no
+# way of disambiguating that with the normal construction case using
+# subclass. furthermore, calling a pure virtual method will still generate
+# an error.
+
diff --git a/trunk/Examples/test-suite/octave/director_basic_runme.m b/trunk/Examples/test-suite/octave/director_basic_runme.m
new file mode 100644
index 0000000..9de54a3
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_basic_runme.m
@@ -0,0 +1,110 @@
+director_basic
+
+
+function self=OctFoo()
+  global director_basic;
+  self=subclass(director_basic.Foo());
+  self.ping=@OctFoo_ping;
+end
+function string=OctFoo_ping(self)
+  string="OctFoo::ping()";
+end
+
+a = OctFoo();
+
+if (!strcmp(a.ping(),"OctFoo::ping()"))
+  error(a.ping())
+endif
+
+if (!strcmp(a.pong(),"Foo::pong();OctFoo::ping()"))
+  error(a.pong())
+endif
+
+b = director_basic.Foo();
+
+if (!strcmp(b.ping(),"Foo::ping()"))
+  error(b.ping())
+endif
+
+if (!strcmp(b.pong(),"Foo::pong();Foo::ping()"))
+  error(b.pong())
+endif
+
+a = director_basic.A1(1);
+
+if (a.rg(2) != 2)
+  error
+endif
+
+function self=OctClass()
+  global director_basic;
+  self=subclass(director_basic.MyClass());
+  self.method=@OctClass_method;
+  self.vmethod=@OctClass_vmethod;
+end
+function OctClass_method(self,vptr)
+  self.cmethod = 7;
+end
+function out=OctClass_vmethod(self,b)
+  b.x = b.x + 31;
+  out=b;
+end
+
+b = director_basic.Bar(3);
+d = director_basic.MyClass();
+c = OctClass();
+
+cc = director_basic.MyClass_get_self(c);
+dd = director_basic.MyClass_get_self(d);
+
+bc = cc.cmethod(b);
+bd = dd.cmethod(b);
+
+cc.method(b);
+if (c.cmethod != 7)
+  error
+endif
+
+if (bc.x != 34)
+  error
+endif
+
+
+if (bd.x != 16)
+  error
+endif
+
+
+function self=OctMulti()
+  global director_basic;
+  self=subclass(director_basic.Foo(),director_basic.MyClass());
+  self.vmethod=@OctMulti_vmethod;
+  self.ping=@OctMulti_ping;
+end
+function out=OctMulti_vmethod(self,b)
+  b.x = b.x + 31;
+  out=b;
+end
+function out=OctMulti_ping(self)
+  out="OctFoo::ping()";
+end
+
+a = 0;
+for i=0:100,
+    octmult = OctMulti();
+    octmult.pong();
+    clear octmult 
+endfor
+
+
+octmult = OctMulti();
+
+
+p1 = director_basic.Foo_get_self(octmult);
+p2 = director_basic.MyClass_get_self(octmult);
+
+p1.ping();
+p2.vmethod(bc);
+
+
+
diff --git a/trunk/Examples/test-suite/octave/director_classic_runme.m b/trunk/Examples/test-suite/octave/director_classic_runme.m
new file mode 100644
index 0000000..c1f8e95
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_classic_runme.m
@@ -0,0 +1,98 @@
+director_classic
+
+TargetLangPerson=@() subclass(Person(),'id',@(self) "TargetLangPerson");
+TargetLangChild=@() subclass(Child(),'id',@(self) "TargetLangChild");
+TargetLangGrandChild=@() subclass(GrandChild(),'id',@(self) "TargetLangGrandChild");
+
+# Semis - don't override id() in target language
+TargetLangSemiPerson=@() subclass(Person());
+TargetLangSemiChild=@() subclass(Child());
+TargetLangSemiGrandChild=@() subclass(GrandChild());
+
+# Orphans - don't override id() in C++
+TargetLangOrphanPerson=@() subclass(OrphanPerson(),'id',@(self) "TargetLangOrphanPerson");
+TargetLangOrphanChild=@() subclass(OrphanChild(),'id',@(self) "TargetLangOrphanChild");
+
+
+function check(person,expected)
+  global Caller;
+
+  # Normal target language polymorphic call
+  ret = person.id();
+  if (ret != expected)
+    raise ("Failed. Received: " + ret + " Expected: " + expected);
+  endif
+
+  # Polymorphic call from C++
+  caller = Caller();
+  caller.setCallback(person);
+  ret = caller.call();
+  if (ret != expected)
+    error ("Failed. Received: " + ret + " Expected: " + expected);
+  endif
+
+  # Polymorphic call of object created in target language and passed to C++ and back again
+  baseclass = caller.baseClass();
+  ret = baseclass.id();
+  if (ret != expected)
+    error ("Failed. Received: " + ret + " Expected: " + expected);
+  endif
+
+  caller.resetCallback();
+end
+
+
+person = Person();
+check(person, "Person");
+clear person;
+
+person = Child();
+check(person, "Child");
+clear person;
+
+person = GrandChild();
+check(person, "GrandChild"); 
+clear person;
+
+person = TargetLangPerson();
+check(person, "TargetLangPerson"); 
+clear person;
+
+person = TargetLangChild();
+check(person, "TargetLangChild"); 
+clear person;
+
+person = TargetLangGrandChild();
+check(person, "TargetLangGrandChild"); 
+clear person;
+
+# Semis - don't override id() in target language
+person = TargetLangSemiPerson();
+check(person, "Person"); 
+clear person;
+
+person = TargetLangSemiChild();
+check(person, "Child"); 
+clear person;
+
+person = TargetLangSemiGrandChild();
+check(person, "GrandChild"); 
+clear person;
+
+# Orphans - don't override id() in C++
+person = OrphanPerson();
+check(person, "Person");
+clear person;
+
+person = OrphanChild();
+check(person, "Child");
+clear person;
+
+person = TargetLangOrphanPerson();
+check(person, "TargetLangOrphanPerson"); 
+clear person;
+
+person = TargetLangOrphanChild();
+check(person, "TargetLangOrphanChild"); 
+clear person;
+
diff --git a/trunk/Examples/test-suite/octave/director_default_runme.m b/trunk/Examples/test-suite/octave/director_default_runme.m
new file mode 100644
index 0000000..c0b479d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_default_runme.m
@@ -0,0 +1,10 @@
+director_default
+
+
+f = Foo();
+f = Foo(1);
+
+
+f = Bar();
+f = Bar(1);
+
diff --git a/trunk/Examples/test-suite/octave/director_detect_runme.m b/trunk/Examples/test-suite/octave/director_detect_runme.m
new file mode 100644
index 0000000..f2d8c8d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_detect_runme.m
@@ -0,0 +1,36 @@
+director_detect 
+
+global MyBar=@(val=2) \
+    subclass(director_detect.Bar(),'val',val,@get_value,@get_class,@just_do_it,@clone);
+function val=get_value(self)
+    self.val = self.val + 1;
+    val = self.val;
+end
+function ptr=get_class(self)
+  global director_detect;
+  self.val = self.val + 1;
+  ptr=director_detect.A();
+end
+function just_do_it(self)
+  self.val = self.val + 1;
+end
+function ptr=clone(self)
+  global MyBar;
+  ptr=MyBar(self.val);
+end
+
+b = MyBar();
+
+f = b.baseclass();
+
+v = f.get_value();
+a = f.get_class();
+f.just_do_it();
+
+c = b.clone();
+vc = c.get_value();
+
+if ((v != 3) || (b.val != 5) || (vc != 6))
+  error("Bad virtual detection")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/director_enum_runme.m b/trunk/Examples/test-suite/octave/director_enum_runme.m
new file mode 100644
index 0000000..96f158d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_enum_runme.m
@@ -0,0 +1,10 @@
+director_enum
+
+MyFoo=@() subclass(director_enum.Foo(),'say_hi',@(self,val) val);
+
+b = director_enum.Foo();
+a = MyFoo();
+
+if (a.say_hi(director_enum.hello) != b.say_hello(director_enum.hi))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/director_exception_runme.m b/trunk/Examples/test-suite/octave/director_exception_runme.m
new file mode 100644
index 0000000..3e0b230
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_exception_runme.m
@@ -0,0 +1,57 @@
+director_exception
+
+MyFoo=@() subclass(Foo(),
+		   'ping',@(self) raise(NotImplementedError("MyFoo::ping() EXCEPTION")));
+
+MyFoo2=@() subclass(Foo(),
+		    'ping',@(self) true);
+		   
+ok = 0;
+
+a = MyFoo();
+b = launder(a);
+
+try
+  b.pong();
+catch
+  [etype,e]=raised();
+  if (etype=="NotImplementedError")
+    ok=1;
+  endif
+end_try_catch
+
+if (!ok)
+  error
+endif
+
+ok = 0;
+
+a = MyFoo2();
+b = launder(a);
+
+try
+  b.pong();
+catch
+  ok = 1;
+end_try_catch
+
+if (!ok)
+  error
+endif
+
+
+try
+  raise(Exception2());
+catch
+  if (!strcmp(raised,"Exception2"))
+    rethrow(lasterr);
+  endif
+end_try_catch
+
+try
+  raise(Exception1());
+catch
+  if (!strcmp(raised,"Exception1"))
+    rethrow(lasterr);
+  endif
+end_try_catch
diff --git a/trunk/Examples/test-suite/octave/director_extend_runme.m b/trunk/Examples/test-suite/octave/director_extend_runme.m
new file mode 100644
index 0000000..1cbeac8
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_extend_runme.m
@@ -0,0 +1,12 @@
+director_extend
+
+MyObject=@() subclass(SpObject(),'getFoo',@(self) 123);
+    
+m = MyObject();
+if (m.dummy() != 666)
+  error("1st call")
+endif
+if (m.dummy() != 666)
+  error("2nd call")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/director_finalizer_runme.m b/trunk/Examples/test-suite/octave/director_finalizer_runme.m
new file mode 100644
index 0000000..3781a0f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_finalizer_runme.m
@@ -0,0 +1,56 @@
+director_finalizer
+
+MyFoo=@() subclass(Foo(),'__del__',@delete_MyFoo);
+function delete_MyFoo(self)
+  self.orStatus(2);
+  try
+    Foo.__del__(self);
+  catch
+  end_try_catch
+endfunction
+
+resetStatus();
+
+a = MyFoo();
+clear a;
+
+if (getStatus() != 3)
+  error
+endif
+
+resetStatus();
+
+a = MyFoo();
+launder(a);
+
+if (getStatus() != 0)
+  error
+endif
+
+clear a;
+
+if (getStatus() != 3)
+  error
+endif
+
+resetStatus();
+
+a = MyFoo().__disown__();
+deleteFoo(a);
+
+if (getStatus() != 3)
+  error
+endif
+
+resetStatus();
+
+a = MyFoo().__disown__();
+deleteFoo(launder(a));
+
+if (getStatus() != 3)
+  error
+endif
+
+resetStatus();
+
+
diff --git a/trunk/Examples/test-suite/octave/director_frob_runme.m b/trunk/Examples/test-suite/octave/director_frob_runme.m
new file mode 100644
index 0000000..16585cc
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_frob_runme.m
@@ -0,0 +1,9 @@
+director_frob
+
+foo = Bravo();
+s = foo.abs_method();
+
+if (!strcmp(s,"Bravo::abs_method()"))
+  error(s)
+endif
+
diff --git a/trunk/Examples/test-suite/octave/director_nested_runme.m b/trunk/Examples/test-suite/octave/director_nested_runme.m
new file mode 100644
index 0000000..6e1d0de
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_nested_runme.m
@@ -0,0 +1,39 @@
+director_nested
+
+A=@() subclass(FooBar_int(),
+	       'do_step',@(self) "A::do_step;",
+	       'get_value',@(self) "A::get_value");
+
+a = A();
+if (!strcmp(a.step(),"Bar::step;Foo::advance;Bar::do_advance;A::do_step;"))
+  error("Bad A virtual resolution")
+endif
+
+B=@() subclass(FooBar_int(),
+	       'do_advance',@(self) strcat("B::do_advance;",self.do_step()),
+	       'do_step',@(self) "B::do_step;",
+	       'get_value',@(self) 1);
+
+b = B();
+
+if (!strcmp(b.step(),"Bar::step;Foo::advance;B::do_advance;B::do_step;"))
+  error("Bad B virtual resolution")
+endif
+
+C=@() subclass(FooBar_int(),
+	       'do_advance',@(self) strcat("C::do_advance;",self.FooBar_int.do_advance()),
+	       'do_step',@(self) "C::do_step;",
+	       'get_value',@(self) 2,
+	       'get_name',@(self) strcat(self.FooBar_int.get_name()," hello"));
+
+cc = C();
+c = FooBar_int_get_self(cc);
+c.advance();
+
+if (!strcmp(c.get_name(),"FooBar::get_name hello"))
+  error
+endif
+
+if (!strcmp(c.name(),"FooBar::get_name hello"))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/director_stl_runme.m b/trunk/Examples/test-suite/octave/director_stl_runme.m
new file mode 100644
index 0000000..e8f4c5e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_stl_runme.m
@@ -0,0 +1,31 @@
+director_stl
+
+MyFoo=@() subclass(director_stl.Foo(),\
+  'ping',@(self,s) "MyFoo::ping():" + s,\
+  'pident',@(self,arg) arg,\
+  'vident',@(self,v) v,\
+  'vidents',@(self,v) v,\
+  'vsecond',@(self,v1,v2) v2,\
+);
+
+a = MyFoo();
+
+a.tping("hello");
+a.tpong("hello");
+
+p = {1,2}
+a.pident(p);
+v = {3,4}
+a.vident(v);
+
+a.tpident(p);
+a.tvident(v);
+
+v1 = {3,4};
+v2 = {5,6};
+a.tvsecond(v1,v2);
+
+vs=("hi", "hello");
+vs;
+a.tvidents(vs);
+
diff --git a/trunk/Examples/test-suite/octave/director_string_runme.m b/trunk/Examples/test-suite/octave/director_string_runme.m
new file mode 100644
index 0000000..c2d4e9c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_string_runme.m
@@ -0,0 +1,27 @@
+director_string
+
+
+function out=get_first(self)
+  out = strcat(self.A.get_first()," world!");
+end
+function process_text(self,string)
+  self.A.process_text(string);
+  self.smem = "hello";
+end
+B=@(string) subclass(A(string),'get_first',@get_first,'process_text',@process_text);
+
+
+b = B("hello");
+
+b.get(0);
+if (!strcmp(b.get_first(),"hello world!"))
+  error(b.get_first())
+endif
+
+b.call_process_func();
+
+if (!strcmp(b.smem,"hello"))
+  error(b.smem)
+endif
+
+  
diff --git a/trunk/Examples/test-suite/octave/director_unroll_runme.m b/trunk/Examples/test-suite/octave/director_unroll_runme.m
new file mode 100644
index 0000000..6ca213c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_unroll_runme.m
@@ -0,0 +1,16 @@
+director_unroll
+
+MyFoo=@() subclass(director_unroll.Foo(),'ping',@(self) "MyFoo::ping()");
+
+a = MyFoo();
+
+b = director_unroll.Bar();
+
+b.set(a);
+c = b.get();
+
+if (swig_this(a) != swig_this(c))
+  a,c
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/director_wstring_runme.m b/trunk/Examples/test-suite/octave/director_wstring_runme.m
new file mode 100644
index 0000000..b59ff6e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/director_wstring_runme.m
@@ -0,0 +1,21 @@
+director_wstring
+
+
+B=@(string) subclass(A(string),\
+		     'get_first',A.get_first(self) + " world!",\
+		     'process_text',@(self) self.smem = u"hello"\
+		     );
+
+b = B("hello");
+
+b.get(0);
+if (!strcmp(b.get_first(),"hello world!"))
+  error(b.get_first())
+endif
+
+b.call_process_func();
+
+if (!strcmp(b.smem,"hello"))
+  error(smem)
+endif
+  
diff --git a/trunk/Examples/test-suite/octave/dynamic_cast_runme.m b/trunk/Examples/test-suite/octave/dynamic_cast_runme.m
new file mode 100644
index 0000000..dad0ba2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/dynamic_cast_runme.m
@@ -0,0 +1,14 @@
+dynamic_cast
+
+f = dynamic_cast.Foo();
+b = dynamic_cast.Bar();
+
+x = f.blah();
+y = b.blah();
+
+a = dynamic_cast.do_test(y);
+if (!strcmp(a,"Bar::test"))
+  error("Failed!!")
+endif
+
+    
diff --git a/trunk/Examples/test-suite/octave/empty_runme.m b/trunk/Examples/test-suite/octave/empty_runme.m
new file mode 100644
index 0000000..c6cac69
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/empty_runme.m
@@ -0,0 +1 @@
+empty
diff --git a/trunk/Examples/test-suite/octave/enum_template_runme.m b/trunk/Examples/test-suite/octave/enum_template_runme.m
new file mode 100644
index 0000000..ca10f1f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/enum_template_runme.m
@@ -0,0 +1,13 @@
+enum_template
+
+if (enum_template.MakeETest() != 1)
+  error
+endif
+
+enum_template.TakeETest(0);
+try
+  a=enum_template.TakeETest(0);
+  error
+catch
+end_try_catch
+  
diff --git a/trunk/Examples/test-suite/octave/enums_runme.m b/trunk/Examples/test-suite/octave/enums_runme.m
new file mode 100644
index 0000000..91f2ce2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/enums_runme.m
@@ -0,0 +1,7 @@
+
+enums
+
+enums.bar2(1)
+enums.bar3(1)
+enums.bar1(1)
+
diff --git a/trunk/Examples/test-suite/octave/exception_order_runme.m b/trunk/Examples/test-suite/octave/exception_order_runme.m
new file mode 100644
index 0000000..a5914f8
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/exception_order_runme.m
@@ -0,0 +1,45 @@
+exception_order
+
+
+a = A();
+
+try
+  a.foo()
+catch
+  if (!strcmp(raised(),"E1"))
+    error, "bad exception order"
+  endif
+end_try_catch
+
+try
+  a.bar()
+catch
+  if (!strcmp(raised(),"E2"))
+    error, "bad exception order"
+  endif
+end_try_catch
+
+try
+  a.foobar()
+catch
+  [t,e]=raised();
+  if (!strcmp(e.args(0),"postcatch unknown"))
+    error
+  endif
+end_try_catch
+
+try
+  a.barfoo(1)
+catch
+  if (!strcmp(raised(),"E1"))
+    error, "bad exception order"
+  endif
+end_try_catch
+
+try
+  a.barfoo(2)
+catch
+  if (!strcmp(raised(),"E2"))
+    error, "bad exception order"
+  endif
+end_try_catch
diff --git a/trunk/Examples/test-suite/octave/extend_placement_runme.m b/trunk/Examples/test-suite/octave/extend_placement_runme.m
new file mode 100644
index 0000000..b7a8e78
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/extend_placement_runme.m
@@ -0,0 +1,46 @@
+extend_placement
+
+foo = extend_placement.Foo();
+foo = extend_placement.Foo(1);
+foo = extend_placement.Foo(1,1);
+foo.spam();
+foo.spam("hello");
+foo.spam(1);
+foo.spam(1,1);
+foo.spam(1,1,1);
+foo.spam(extend_placement.Foo());
+foo.spam(extend_placement.Foo(), 1.0);
+
+
+bar = extend_placement.Bar();
+bar = extend_placement.Bar(1);
+bar.spam();
+bar.spam("hello");
+bar.spam(1);
+bar.spam(1,1);
+bar.spam(1,1,1);
+bar.spam(extend_placement.Bar());
+bar.spam(extend_placement.Bar(), 1.0);
+
+
+foo = extend_placement.FooTi();
+foo = extend_placement.FooTi(1);
+foo = extend_placement.FooTi(1,1);
+foo.spam();
+foo.spam("hello");
+foo.spam(1);
+foo.spam(1,1);
+foo.spam(1,1,1);
+foo.spam(extend_placement.Foo());
+foo.spam(extend_placement.Foo(), 1.0);
+
+
+bar = extend_placement.BarTi();
+bar = extend_placement.BarTi(1);
+bar.spam();
+bar.spam("hello");
+bar.spam(1);
+bar.spam(1,1);
+bar.spam(1,1,1);
+bar.spam(extend_placement.Bar());
+bar.spam(extend_placement.Bar(), 1.0);
diff --git a/trunk/Examples/test-suite/octave/extend_template_ns_runme.m b/trunk/Examples/test-suite/octave/extend_template_ns_runme.m
new file mode 100644
index 0000000..401ea63
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/extend_template_ns_runme.m
@@ -0,0 +1,10 @@
+extend_template_ns
+
+f = Foo_One();
+if (f.test1(37) != 37)
+    error
+endif
+
+if (f.test2(42) != 42)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/extend_template_runme.m b/trunk/Examples/test-suite/octave/extend_template_runme.m
new file mode 100644
index 0000000..1cad7bf
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/extend_template_runme.m
@@ -0,0 +1,10 @@
+extend_template
+
+f = extend_template.Foo_0();
+if (f.test1(37) != 37)
+    error
+endif
+
+if (f.test2(42) != 42)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/extend_variable_runme.m b/trunk/Examples/test-suite/octave/extend_variable_runme.m
new file mode 100644
index 0000000..c55b6c5
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/extend_variable_runme.m
@@ -0,0 +1,6 @@
+extend_variable
+
+if (Foo.Bar != 42)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/file_test_runme.m b/trunk/Examples/test-suite/octave/file_test_runme.m
new file mode 100644
index 0000000..4c22a30
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/file_test_runme.m
@@ -0,0 +1,9 @@
+file_test
+
+file_test.nfile("stdout");
+
+cstdout = file_test.GetStdOut();
+
+file_test.nfile(cstdout);
+file_test.nfile_name("test.dat");
+
diff --git a/trunk/Examples/test-suite/octave/friends_runme.m b/trunk/Examples/test-suite/octave/friends_runme.m
new file mode 100644
index 0000000..e18f47a
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/friends_runme.m
@@ -0,0 +1,46 @@
+friends
+
+a = friends.A(2);
+
+if (friends.get_val1(a) != 2)
+  error
+endif
+if (friends.get_val2(a) != 4)
+  error
+endif
+if (friends.get_val3(a) != 6)
+  error
+endif
+
+				# nice overload working fine
+if (friends.get_val1(1,2,3) != 1)
+  error
+endif
+
+b = friends.B(3);
+
+				# David's case
+if (friends.mix(a,b) != 5)
+  error
+endif
+
+di = friends.D_d(2);
+dd = friends.D_d(3.3);
+
+				# incredible template overloading working just fine
+if (friends.get_val1(di) != 2)
+  error
+endif
+if (friends.get_val1(dd) != 3.3)
+  error
+endif
+
+friends.set(di, 4);
+friends.set(dd, 1.3);
+
+if (friends.get_val1(di) != 4)
+  error
+endif
+if (friends.get_val1(dd) != 1.3)
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/fvirtual_runme.m b/trunk/Examples/test-suite/octave/fvirtual_runme.m
new file mode 100644
index 0000000..e755a55
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/fvirtual_runme.m
@@ -0,0 +1,10 @@
+fvirtual
+
+sw = NodeSwitch();
+n = Node();
+i = sw.addChild(n);
+
+if (i != 2)
+  error("addChild")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/global_ns_arg_runme.m b/trunk/Examples/test-suite/octave/global_ns_arg_runme.m
new file mode 100644
index 0000000..fa3625e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/global_ns_arg_runme.m
@@ -0,0 +1,5 @@
+global_ns_arg
+
+a = foo(1);
+b = bar();
+
diff --git a/trunk/Examples/test-suite/octave/grouping_runme.m b/trunk/Examples/test-suite/octave/grouping_runme.m
new file mode 100644
index 0000000..26b896c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/grouping_runme.m
@@ -0,0 +1,15 @@
+grouping
+
+x = grouping.test1(42);
+if (x != 42)
+    error
+endif
+
+grouping.test2(42);
+
+x = (grouping.do_unary(37, grouping.NEGATE));
+if (x != -37)
+    error
+endif
+
+grouping.cvar.test3 = 42;
diff --git a/trunk/Examples/test-suite/octave/iadd_runme.m b/trunk/Examples/test-suite/octave/iadd_runme.m
new file mode 100755
index 0000000..c386c66
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/iadd_runme.m
@@ -0,0 +1,10 @@
+iadd
+
+f = iadd.Foo();
+
+f.AsA.x = 3;
+f.AsA += f.AsA;
+
+if (f.AsA.x != 6)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/implicittest.i b/trunk/Examples/test-suite/octave/implicittest.i
new file mode 100644
index 0000000..91205aa
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/implicittest.i
@@ -0,0 +1,68 @@
+%module(naturalvar="1") implicittest
+
+%implicitconv;
+
+%inline 
+{
+  struct B { };  
+}
+
+%inline 
+{
+  struct A
+  {
+    int ii;
+    A(int i) { ii = 1; }
+    A(double d) { ii = 2; }
+    A(const B& b) { ii = 3; }
+    explicit A(char *s) { ii = 4; }
+
+    int get() const { return ii; }
+    
+  };
+
+  int get(const A& a) { return a.ii; }
+
+  template <class T>
+  struct A_T
+  {
+    int ii;
+    A_T(int i) { ii = 1; }
+    A_T(double d) { ii = 2; }
+    A_T(const B& b) { ii = 3; }
+    explicit A_T(char *s) { ii = 4; }
+
+    int get() const { return ii; }
+    
+  };
+}
+
+%inline 
+{
+  struct Foo 
+  {
+    int ii;
+    Foo(){ ii = 0;}
+    Foo(int){ ii = 1;}
+    Foo(double){ ii = 2;}
+    explicit Foo(char *s){ii = 3;}
+    Foo(const Foo& f){ ii = f.ii;}
+    
+  };
+
+  struct Bar 
+  {
+    int ii;
+    Foo f;
+    Bar() {ii = -1;}
+    Bar(const Foo& ff){ ii = ff.ii;}
+  };
+
+
+  int get_b(const Bar&b) { return b.ii; }
+  
+  Foo foo;
+  
+}
+
+%template(A_int) A_T<int>;
diff --git a/trunk/Examples/test-suite/octave/import_nomodule_runme.m b/trunk/Examples/test-suite/octave/import_nomodule_runme.m
new file mode 100644
index 0000000..a70b468
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/import_nomodule_runme.m
@@ -0,0 +1,8 @@
+import_nomodule
+
+f = create_Foo();
+test1(f,42);
+delete_Foo(f);
+
+b = Bar();
+test1(b,37);
diff --git a/trunk/Examples/test-suite/octave/imports_runme.m b/trunk/Examples/test-suite/octave/imports_runme.m
new file mode 100644
index 0000000..3964552
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/imports_runme.m
@@ -0,0 +1,19 @@
+# This is the import runtime testcase.
+
+imports_b
+imports_a
+
+x = imports_b.B();
+x.hello();
+
+a = imports_a.A();
+
+c = imports_b.C();
+a1 = c.get_a(c);
+a2 = c.get_a_type(c);
+
+a1.hello();
+a2.hello();
+assert(swig_this(a1)==swig_this(a2));
+assert(strcmp(swig_type(a1),swig_type(a2)));
+
diff --git a/trunk/Examples/test-suite/octave/inctest_runme.m b/trunk/Examples/test-suite/octave/inctest_runme.m
new file mode 100644
index 0000000..ab0cb64
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/inctest_runme.m
@@ -0,0 +1,24 @@
+inctest
+
+try
+  a = inctest.A();
+catch
+  error("didn't find A\ntherefore, I didn't include \
+      'testdir/subdir1/hello.i'")
+end_try_catch
+
+try
+  b = inctest.B();
+catch
+  error("didn't find B\ntherefore, I didn't include 'testdir/subdir2/hello.i'")
+end_try_catch
+
+# Check the import in subdirectory worked
+if (inctest.importtest1(5) != 15)
+  error("import test 1 failed")
+endif
+
+if (!strcmp(inctest.importtest2("black"),"white"))
+  error("import test 2 failed")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/inherit_missing_runme.m b/trunk/Examples/test-suite/octave/inherit_missing_runme.m
new file mode 100644
index 0000000..8517e2d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/inherit_missing_runme.m
@@ -0,0 +1,22 @@
+inherit_missing
+
+a = inherit_missing.new_Foo();
+b = inherit_missing.Bar();
+c = inherit_missing.Spam();
+
+x = inherit_missing.do_blah(a);
+if (!strcmp(x, "Foo::blah"))
+    error("Whoa! Bad return %s", x)
+endif
+
+x = inherit_missing.do_blah(b);
+if (!strcmp(x, "Bar::blah"))
+    error("Whoa! Bad return %s", x)
+endif
+
+x = inherit_missing.do_blah(c);
+if (!strcmp(x, "Spam::blah"))
+    error("Whoa! Bad return %s", x)
+endif
+
+inherit_missing.delete_Foo(a);
diff --git a/trunk/Examples/test-suite/octave/inout_runme.m b/trunk/Examples/test-suite/octave/inout_runme.m
new file mode 100644
index 0000000..74caaff
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/inout_runme.m
@@ -0,0 +1,27 @@
+inout
+
+a = inout.AddOne1(1);
+if (a != 2)
+  error
+endif
+
+a = inout.AddOne3(1,1,1);
+if (a != [2,2,2])
+  error
+endif
+
+a = inout.AddOne1p((1,1));
+if (a != (2,2))
+  error
+endif
+
+a = inout.AddOne2p((1,1),1);
+if (a != [(2,2),2])
+  error
+endif
+
+a = inout.AddOne3p(1,(1,1),1);
+if (a != [2,(2,2),2])
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/inplaceadd_runme.m b/trunk/Examples/test-suite/octave/inplaceadd_runme.m
new file mode 100644
index 0000000..2bc1937
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/inplaceadd_runme.m
@@ -0,0 +1,24 @@
+inplaceadd
+a = inplaceadd.A(7);
+
+a += 5;
+if (a.val != 12)
+  error
+endif
+
+a -= 5;
+if a.val != 7:
+  error
+endif
+
+a *= 2;
+
+if (a.val != 14)
+  error
+endif
+
+a += a;
+if (a.val != 28)
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/input_runme.m b/trunk/Examples/test-suite/octave/input_runme.m
new file mode 100644
index 0000000..7578621
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/input_runme.m
@@ -0,0 +1,22 @@
+input
+
+f = Foo();
+if (f.foo(2) != 4)
+  error
+endif
+
+try
+  a=f.foo();
+  error
+catch
+end_try_catch
+
+if (!strcmp(sfoo("Hello"),"Hello world"))
+  error
+endif
+
+try
+  a=sfoo();
+  error
+catch
+end_try_catch
diff --git a/trunk/Examples/test-suite/octave/li_attribute_runme.m b/trunk/Examples/test-suite/octave/li_attribute_runme.m
new file mode 100644
index 0000000..c66e27c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_attribute_runme.m
@@ -0,0 +1,57 @@
+li_attribute
+
+aa = li_attribute.A(1,2,3);
+
+if (aa.a != 1)
+  error
+endif
+aa.a = 3;
+if (aa.a != 3)
+  error("aa.a = %i",aa.a)
+endif
+
+
+if (aa.b != 2)
+  error(aa.b)
+endif
+aa.b = 5;
+if (aa.b != 5)
+  error
+endif
+
+
+
+if (aa.d != aa.b)
+  error
+endif
+
+if (aa.c != 3)
+  error
+endif
+
+pi = li_attribute.Param_i(7);
+if (pi.value != 7)
+ error
+endif
+
+pi.value=3;
+if (pi.value != 3)
+ error
+endif
+
+
+b = li_attribute.B(aa);
+
+if (b.a.c != 3)
+ error
+endif
+  
+
+myFoo = li_attribute.MyFoo();
+myFoo.x = 8;
+myClass = li_attribute.MyClass();
+myClass.Foo = myFoo;
+if (myClass.Foo.x != 8)
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_boost_shared_ptr_runme.m b/trunk/Examples/test-suite/octave/li_boost_shared_ptr_runme.m
new file mode 100644
index 0000000..ca09316
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_boost_shared_ptr_runme.m
@@ -0,0 +1,478 @@
+li_boost_shared_ptr
+
+debug = false;
+
+function main()
+    if (debug)
+      printf("Started\n")
+    endif
+
+    li_boost_shared_ptr.cvar.debug_shared = debug;
+
+    # Change loop count to run for a long time to monitor memory
+    loopCount = 1; #5000
+    for i=0:loopCount,
+      self.runtest();
+    endfor
+
+    if (li_boost_shared_ptr.Klass.getTotal_count() != 0)
+      error("Klass.total_count=", li_boost_shared_ptr.Klass.getTotal_count())
+    endif
+
+    wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count();
+    if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING)
+      if (wrapper_count != 0)
+        error("shared_ptr wrapper count not zero: %i", wrapper_count)
+      endif
+    endif
+
+    if (debug)
+      error("Finished")
+    endif
+endfunction
+
+function runtest()
+    # simple shared_ptr usage - created in C++
+    k = li_boost_shared_ptr.Klass("me oh my");
+    val = k.getValue();
+    self.verifyValue("me oh my", val);
+    self.verifyCount(1, k);
+
+    # simple shared_ptr usage - not created in C++
+    k = li_boost_shared_ptr.factorycreate();
+    val = k.getValue();
+    self.verifyValue("factorycreate", val);
+    self.verifyCount(1, k);
+
+    # pass by shared_ptr
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.smartpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointertest", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by shared_ptr pointer
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.smartpointerpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointerpointertest", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by shared_ptr reference
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.smartpointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointerreftest", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by shared_ptr pointer reference
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointerpointerreftest", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # const pass by shared_ptr
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.constsmartpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # const pass by shared_ptr pointer
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.constsmartpointerpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # const pass by shared_ptr reference
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.constsmartpointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by value
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.valuetest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my valuetest", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # pass by pointer
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.pointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my pointertest", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # pass by reference
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.reftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my reftest", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # pass by pointer reference
+    k = li_boost_shared_ptr.Klass("me oh my");
+    kret = li_boost_shared_ptr.pointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my pointerreftest", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # null tests
+    k = None;
+
+    if (li_boost_shared_ptr.smartpointertest(k) != None)
+      error("return was not null")
+    endif
+
+    if (li_boost_shared_ptr.smartpointerpointertest(k) != None)
+      error("return was not null")
+    endif
+
+    if (li_boost_shared_ptr.smartpointerreftest(k) != None)
+      error("return was not null")
+    endif
+
+    if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None)
+      error("return was not null")
+    endif
+
+    if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer")
+      error("not null smartpointer pointer")
+    endif
+
+    try
+      li_boost_shared_ptr.valuetest(k)
+      error("Failed to catch null pointer")
+    catch
+    end_try_catch
+
+    if (li_boost_shared_ptr.pointertest(k) != None)
+      error("return was not null")
+    endif
+
+    try
+      li_boost_shared_ptr.reftest(k)
+      error("Failed to catch null pointer")
+    catch
+    end_try_catch
+
+    # $owner
+    k = li_boost_shared_ptr.pointerownertest();
+    val = k.getValue();
+    self.verifyValue("pointerownertest", val);
+    self.verifyCount(1, k);
+    k = li_boost_shared_ptr.smartpointerpointerownertest();
+    val = k.getValue();
+    self.verifyValue("smartpointerpointerownertest", val);
+    self.verifyCount(1, k);
+
+    # //////////////////////////////// Derived class ////////////////////////////////////////
+    # derived pass by shared_ptr
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.derivedsmartptrtest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my derivedsmartptrtest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # derived pass by shared_ptr pointer
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.derivedsmartptrpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # derived pass by shared_ptr ref
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.derivedsmartptrreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my derivedsmartptrreftest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # derived pass by shared_ptr pointer ref
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # derived pass by pointer
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.derivedpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my derivedpointertest-Derived", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # derived pass by ref
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.derivedreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my derivedreftest-Derived", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # //////////////////////////////// Derived and base class mixed ////////////////////////////////////////
+    # pass by shared_ptr (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.smartpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointertest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by shared_ptr pointer (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.smartpointerpointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointerpointertest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by shared_ptr reference (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.smartpointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointerreftest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by shared_ptr pointer reference (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.smartpointerpointerreftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my smartpointerpointerreftest-Derived", val);
+    self.verifyCount(2, k);
+    self.verifyCount(2, kret);
+
+    # pass by value (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.valuetest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my valuetest", val); # note slicing
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # pass by pointer (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.pointertest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my pointertest-Derived", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # pass by ref (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    kret = li_boost_shared_ptr.reftest(k);
+    val = kret.getValue();
+    self.verifyValue("me oh my reftest-Derived", val);
+    self.verifyCount(1, k);
+    self.verifyCount(1, kret);
+
+    # //////////////////////////////// Overloading tests ////////////////////////////////////////
+    # Base class
+    k = li_boost_shared_ptr.Klass("me oh my");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref");
+
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval");
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref");
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr");
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref");
+
+    # Derived class
+    k = li_boost_shared_ptr.KlassDerived("me oh my");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr");
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref");
+
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval");
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref");
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr");
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref");
+
+    # //////////////////////////////// Member variables ////////////////////////////////////////
+    # smart pointer by value
+    m = li_boost_shared_ptr.MemberVariables();
+    k = li_boost_shared_ptr.Klass("smart member value");
+    m.SmartMemberValue = k;
+    val = k.getValue();
+    self.verifyValue("smart member value", val);
+    self.verifyCount(2, k);
+
+    kmember = m.SmartMemberValue;
+    val = kmember.getValue();
+    self.verifyValue("smart member value", val);
+    self.verifyCount(3, kmember);
+    self.verifyCount(3, k);
+
+    clear m;
+    self.verifyCount(2, kmember);
+    self.verifyCount(2, k);
+
+    # smart pointer by pointer
+    m = li_boost_shared_ptr.MemberVariables();
+    k = li_boost_shared_ptr.Klass("smart member pointer");
+    m.SmartMemberPointer = k;
+    val = k.getValue();
+    self.verifyValue("smart member pointer", val);
+    self.verifyCount(1, k);
+
+    kmember = m.SmartMemberPointer;
+    val = kmember.getValue();
+    self.verifyValue("smart member pointer", val);
+    self.verifyCount(2, kmember);
+    self.verifyCount(2, k);
+
+    clear m;
+    self.verifyCount(2, kmember);
+    self.verifyCount(2, k);
+
+    # smart pointer by reference
+    m = li_boost_shared_ptr.MemberVariables();
+    k = li_boost_shared_ptr.Klass("smart member reference");
+    m.SmartMemberReference = k;
+    val = k.getValue();
+    self.verifyValue("smart member reference", val);
+    self.verifyCount(2, k);
+
+    kmember = m.SmartMemberReference;
+    val = kmember.getValue();
+    self.verifyValue("smart member reference", val);
+    self.verifyCount(3, kmember);
+    self.verifyCount(3, k);
+
+    # The C++ reference refers to SmartMemberValue...
+    kmemberVal = m.SmartMemberValue;
+    val = kmember.getValue();
+    self.verifyValue("smart member reference", val);
+    self.verifyCount(4, kmemberVal);
+    self.verifyCount(4, kmember);
+    self.verifyCount(4, k);
+
+    clear m;
+    self.verifyCount(3, kmemberVal);
+    self.verifyCount(3, kmember);
+    self.verifyCount(3, k);
+
+    # plain by value
+    m = li_boost_shared_ptr.MemberVariables();
+    k = li_boost_shared_ptr.Klass("plain member value");
+    m.MemberValue = k;
+    val = k.getValue();
+    self.verifyValue("plain member value", val);
+    self.verifyCount(1, k);
+
+    kmember = m.MemberValue;
+    val = kmember.getValue();
+    self.verifyValue("plain member value", val);
+    self.verifyCount(1, kmember);
+    self.verifyCount(1, k);
+
+    clear m;
+    self.verifyCount(1, kmember);
+    self.verifyCount(1, k);
+
+    # plain by pointer
+    m = li_boost_shared_ptr.MemberVariables();
+    k = li_boost_shared_ptr.Klass("plain member pointer");
+    m.MemberPointer = k;
+    val = k.getValue();
+    self.verifyValue("plain member pointer", val);
+    self.verifyCount(1, k);
+
+    kmember = m.MemberPointer;
+    val = kmember.getValue();
+    self.verifyValue("plain member pointer", val);
+    self.verifyCount(1, kmember);
+    self.verifyCount(1, k);
+
+    clear m;
+    self.verifyCount(1, kmember);
+    self.verifyCount(1, k);
+
+    # plain by reference
+    m = li_boost_shared_ptr.MemberVariables();
+    k = li_boost_shared_ptr.Klass("plain member reference");
+    m.MemberReference = k;
+    val = k.getValue();
+    self.verifyValue("plain member reference", val);
+    self.verifyCount(1, k);
+
+    kmember = m.MemberReference;
+    val = kmember.getValue();
+    self.verifyValue("plain member reference", val);
+    self.verifyCount(1, kmember);
+    self.verifyCount(1, k);
+
+    clear m;
+    self.verifyCount(1, kmember);
+    self.verifyCount(1, k);
+
+    # null member variables
+    m = li_boost_shared_ptr.MemberVariables();
+
+    # shared_ptr by value
+    k = m.SmartMemberValue;
+    if (k != None)
+      error("expected null")
+    endif
+    m.SmartMemberValue = None;
+    k = m.SmartMemberValue;
+    if (k != None)
+      error("expected null")
+    endif
+    self.verifyCount(0, k);
+
+    # plain by value
+    try
+      m.MemberValue = None;
+      error("Failed to catch null pointer");
+    catch
+    end_try_catch
+
+    # templates
+    pid = li_boost_shared_ptr.PairIntDouble(10, 20.2)
+    if (pid.baseVal1 != 20 || pid.baseVal2 != 40.4)
+      error("Base values wrong")
+    endif
+    if (pid.val1 != 10 || pid.val2 != 20.2)
+      error("Derived Values wrong")
+    endif
+endfunction
+
+function verifyValue(expected,got)
+  if (expected != got)
+    error("verify value failed. Expected: %i, Got %i\n",expected,got)
+  endif
+endfunction
+
+function verifyCount(expected,k)
+  got = li_boost_shared_ptr.use_count(k);
+  if (expected != got)
+    error("verify value failed. Expected: %i, Got %i\n",expected,got)
+  endif
+endfunction
+
+
diff --git a/trunk/Examples/test-suite/octave/li_carrays_runme.m b/trunk/Examples/test-suite/octave/li_carrays_runme.m
new file mode 100644
index 0000000..8ec7e59
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_carrays_runme.m
@@ -0,0 +1,10 @@
+li_carrays
+
+d = doubleArray(10);
+
+d(0) = 7;
+d(5) = d(0) + 3;
+
+if (d(5) + d(0) != 17)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/li_cmalloc_runme.m b/trunk/Examples/test-suite/octave/li_cmalloc_runme.m
new file mode 100644
index 0000000..45faf73
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_cmalloc_runme.m
@@ -0,0 +1,17 @@
+li_cmalloc
+
+p = malloc_int();
+free_int(p);
+
+ok = 0;
+try
+    p = calloc_int(-1);
+    free_int(p);
+catch
+    ok = 1;
+end_try_catch
+
+if (ok != 1)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_cpointer_runme.m b/trunk/Examples/test-suite/octave/li_cpointer_runme.m
new file mode 100644
index 0000000..bf660a6
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_cpointer_runme.m
@@ -0,0 +1,12 @@
+li_cpointer
+
+
+p = new_intp();
+intp_assign(p,3);
+
+if (intp_value(p) != 3)
+    error
+endif
+
+delete_intp(p);
+
diff --git a/trunk/Examples/test-suite/octave/li_cstring_runme.m b/trunk/Examples/test-suite/octave/li_cstring_runme.m
new file mode 100644
index 0000000..0d2bdb7
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_cstring_runme.m
@@ -0,0 +1,39 @@
+li_cstring
+
+
+if (count("ab\0ab\0ab\0", 0) != 3)
+    error    
+endif
+
+if (!strcmp(test1(),"Hello World"))
+    error
+endif
+
+if (!strcmp(test2()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_"))
+    error
+endif
+
+if (!strcmp(test3("hello"),"hello-suffix"))
+    error(test3("hello"))
+endif
+
+if (!strcmp(test4("hello"),"hello-suffix"))
+    error(test4("hello"))
+endif
+    
+if (!strcmp(test5(4),'xxxx'))
+    error
+endif
+
+if (!strcmp(test6(10),'xxxxx'))
+    error
+endif
+    
+if (!strcmp(test7(),"Hello world!"))
+    error
+endif
+
+if (!strcmp(test8()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_"))
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_cwstring_runme.m b/trunk/Examples/test-suite/octave/li_cwstring_runme.m
new file mode 100644
index 0000000..4cfef7f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_cwstring_runme.m
@@ -0,0 +1,38 @@
+li_cwstring
+
+if (count("ab\0ab\0ab\0", 0) != 3)
+    error    
+endif
+
+if (!strcmp(test1(),"Hello World"))
+    error
+endif
+
+if (!strcmp(test2()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_"))
+    error
+endif
+
+if (!strcmp(test3("hello"),"hello-suffix"))
+    error
+endif
+
+if (!strcmp(test4("hello"),"hello-suffix"))
+    error
+endif
+    
+if (!strcmp(test5(4),'xxxx'))
+    error
+endif
+
+if (!strcmp(test6(10),'xxxxx'))
+    error
+endif
+    
+if (!strcmp(test7(),"Hello world!"))
+    error
+endif
+
+if (!strcmp(test8()," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_"))
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_factory_runme.m b/trunk/Examples/test-suite/octave/li_factory_runme.m
new file mode 100644
index 0000000..d87920d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_factory_runme.m
@@ -0,0 +1,13 @@
+li_factory
+
+circle = Geometry_create(Geometry.CIRCLE);
+r = circle.radius();
+if (r != 1.5)
+  error
+endif
+
+point = Geometry_create(Geometry.POINT);
+w = point.width();
+if (w != 1.0)
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/li_implicit_runme.m b/trunk/Examples/test-suite/octave/li_implicit_runme.m
new file mode 100644
index 0000000..2ca8b59
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_implicit_runme.m
@@ -0,0 +1,20 @@
+li_implicit
+b = B();
+ai = A(1);
+ad = A(2.0);
+ab = A(b);
+
+ai, get(ai);
+ad, get(ad);
+ab, get(ab);
+
+if (get(ai) != get(1))
+  error("bad implicit type")
+endif
+if (get(ad) != get(2.0))
+  error("bad implicit type")
+endif
+if (get(ab) != get(b))
+  error("bad implicit type")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_std_carray_runme.m b/trunk/Examples/test-suite/octave/li_std_carray_runme.m
new file mode 100644
index 0000000..4943fa8
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_carray_runme.m
@@ -0,0 +1,52 @@
+li_std_carray
+
+
+v3 = Vector3();
+for i=0:len(v3),
+    v3(i) = i;
+endfor
+
+i = 0;
+for d in v3,
+  if (d != i)
+    error
+  endif
+  i = i + 1;
+endfor
+
+
+m3 = Matrix3();
+
+for i=0:len(m3),
+  v3 = m3(i);
+  for j=0:len(v3),
+    v3(j) = i + j;
+  endfor
+endfor
+
+i = 0;
+for v3 in m3,
+  j = 0;
+  for d in v3,
+    if (d != i + j)
+      error
+    endif
+    j = j + 1;
+  endfor
+  i = i + 1
+endfor
+
+for i=0:len(m3),
+  for j=0:len(m3),
+    if (m3(i,j) != i + j)
+      error
+    endif
+  endfor
+endfor
+
+da = Vector3([1,2,3]);
+ma = Matrix3({[1,2,3],[4,5,6],[7,8,9]});
+
+
+
+
diff --git a/trunk/Examples/test-suite/octave/li_std_map_runme.m b/trunk/Examples/test-suite/octave/li_std_map_runme.m
new file mode 100644
index 0000000..e74fc79
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_map_runme.m
@@ -0,0 +1,61 @@
+li_std_map
+
+a1 = li_std_map.A(3);
+a2 = li_std_map.A(7);
+
+
+p0 = li_std_map.pairii(1,2);
+p1 = li_std_map.pairA(1,a1.this);
+m = {};
+m{1} = a1;
+m{2} = a2;
+
+pp1 = li_std_map.p_identa(p1);
+mm = li_std_map.m_identa(m);
+
+
+
+m = li_std_map.mapA();
+m{1} = a1;
+m{2} = a2;
+
+
+pm ={};
+for k in m,
+  pm{k} = m{k};
+endfor
+
+for k in m,
+  if (swig_this(pm{k}) != swig_this(m{k}))
+    error
+  endif
+endfor
+
+  
+
+m = {};
+m{1} = [1,2];
+m["foo"] = "hello";
+
+pm = li_std_map.pymap();
+
+for k in m,
+  pm{k} = m{k};
+endfor
+
+for k in pm,
+  if (pm{k} != m{k})
+    error
+  endif
+endfor
+
+mii = li_std_map.mapii();
+
+mii{1} = 1;
+mii{1} = 2;
+
+if (mii[1] != 2)
+  error
+endif
+
+  
diff --git a/trunk/Examples/test-suite/octave/li_std_pair.i b/trunk/Examples/test-suite/octave/li_std_pair.i
new file mode 100644
index 0000000..886bf1a
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_pair.i
@@ -0,0 +1,210 @@
+%module li_std_pair
+
+//
+// activate the automatic comparison methods generation (==,!=,...) 
+//
+
+%{
+#include <algorithm>                   // for std::swap
+%}
+
+
+%include std_pair.i
+%include std_string.i
+%include std_complex.i
+
+%inline
+%{
+  struct A 
+  {
+    int val;
+    
+    A(int v = 0): val(v)
+    {
+    }
+    
+  };
+  struct B
+  {
+  };
+%}
+
+%std_comp_methods(std::pair<std::string, int>);
+
+namespace std {
+  %template(CIntPair) pair<const int, const int>;
+  %template() pair<double, double>;
+  %template(ShortPair) pair<short, short>;
+
+  %template(IntPair) pair<int, int>;
+  %extend pair<int, int>
+  {
+    %template(pair) pair<short,short>;
+  }
+  
+  
+
+  %template(SIPair) pair<std::string, int>;
+  %template(CIPair) pair<std::complex<double>, int>;
+  %template(SIIPair) pair<std::pair<std::string, int>, int>;
+  %template(AIntPair) pair<A, int>;
+
+  %template(CCIntPair) pair<const A, const pair<int, int> >;
+
+  %template(ABPair) pair<A, B>;
+  %template(IntAPair) pair<int, A>;
+
+  %template(pairP1) pair<int, A*>;
+  %template(pairP2) pair<A*, int>;
+  %template(pairP3) pair<A*, A*>;
+  %template(pairP4) pair<int, int*>;
+  %template(pairP5) pair<int*, int>;
+  %template(pairP6) pair<int*, int*>;
+  
+}
+%std_comp_methods(std::pair<std::pair<std::string, int>, int>);
+
+%apply std::pair<int,int> *INOUT {std::pair<int,int> *INOUT2};
+
+%inline %{
+
+/* Test the "out" typemap for pair<T, U> */
+std::pair<int, int> makeIntPair(int a, int b) {
+    return std::make_pair(a, b);
+}
+
+/**
+ * There is no "out" typemap for a pointer to a pair, so
+ * this should return a wrapped instance of a std::pair
+ * instead of the native "array" type for the target language.
+ */
+std::pair<int, int> * makeIntPairPtr(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return &p;
+}
+
+/**
+ * There is no "out" typemap for a non-const reference to a pair, so
+ * this should return a wrapped instance of a std::pair instead of
+ * the native "array" type for the target language.
+ */
+std::pair<int, int>& makeIntPairRef(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return p;
+}
+
+/**
+ * There is no "out" typemap for a const reference to a pair, so
+ * this should return a wrapped instance of a std::pair
+ * instead of the native "array" type for the target language.
+ */
+const std::pair<int, int> & makeIntPairConstRef(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return p;
+}
+
+/* Test the "in" typemap for pair<T, U> */
+int product1(std::pair<int, int> p) {
+    return p.first*p.second;
+}
+
+/* Test the "in" typemap for const pair<T, U>& */
+int product2(const std::pair<int, int>& p) {
+    return p.first*p.second;
+}
+
+std::pair<int, int> 
+  p_ident(std::pair<int, int> p, const std::pair<int, int>& q) {
+  return p;
+}
+
+
+std::pair<int, A*> 
+p_identa(const std::pair<int, A*>& p) {
+  return p;
+}
+
+void
+d_inout(double *INOUT) {
+  *INOUT += *INOUT;
+}
+
+void
+d_inout(int *INOUT) {
+  *INOUT += *INOUT;
+}
+
+int
+d_inout2(double *INOUT) {
+  *INOUT += *INOUT;
+  return 1;
+}
+
+void
+p_inout(std::pair<int, int> *INOUT) {
+  std::swap(INOUT->first, INOUT->second);
+}
+
+int
+p_inout2(std::pair<int, int> *INOUT) {
+  std::swap(INOUT->first, INOUT->second);
+  return 1;
+}
+
+void
+  p_inout3(std::pair<int,int> *INOUT, std::pair<int,int> *INOUT2) {
+  std::swap(*INOUT, *INOUT2);
+} 
+
+void
+p_inoutd(std::pair<double, double> *INOUT) {
+  std::swap(INOUT->first, INOUT->second);
+}
+
+std::string
+  s_ident(const std::string& s) {
+  return s;
+}
+
+#if 0
+std::pair<char, char> 
+  p_ident(std::pair<char, char> p, const std::pair<char, char>& q) {
+  return p;
+}
+
+/* Test the "in" typemap for const pair<T, U>* */
+std::pair<A, B> 
+  p_ident(std::pair<A, B> p, const std::pair<A, B>& q) {
+  return q;
+}
+
+/* Test the "in" typemap for const pair<T, U>* */
+std::pair<int, A> 
+  p_ident(std::pair<int, A> p, const std::pair<int, A>& q) {
+  return p;
+}
+
+
+std::pair<int, int> 
+  p_ident(std::pair<int, int> p, const std::pair<A, int>& q) {
+  return p;
+}
+
+std::pair<int, int> 
+  p_ident(std::pair<int, int> p, const std::pair<A, B>& q) {
+  return p;
+}
+
+
+
+#endif
+%}
+
+
+namespace std
+{
+  %template(paircA1) pair<const int, A*>;
+  %template(paircA2) pair<const int, const A*>;
+  %template(pairiiA) pair<int,pair<int, A*> >;
+}
+
diff --git a/trunk/Examples/test-suite/octave/li_std_pair_runme.m b/trunk/Examples/test-suite/octave/li_std_pair_runme.m
new file mode 100644
index 0000000..83e9fe5
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_pair_runme.m
@@ -0,0 +1,69 @@
+li_std_pair
+
+p = {1,2};
+p1 = li_std_pair.p_inout(p);
+assert(all(cell2mat(p1)==[2,1]));
+p2 = li_std_pair.p_inoutd(p1);
+assert(all(cell2mat(p2)==[1,2]));
+
+d1 = li_std_pair.d_inout(2);
+assert(d1==4);
+
+[i,d2] = li_std_pair.d_inout2(2);
+assert(all([i,d2]==[1,4]));
+
+[i,p] = li_std_pair.p_inout2(p);
+assert(i==1&&all([cell2mat(p)]==[2,1]));
+[p3,p4] = li_std_pair.p_inout3(p1,p1);
+assert(all(cell2mat(p3)==[2,1]));
+assert(all(cell2mat(p4)==[2,1]));
+
+psi = li_std_pair.SIPair("hello",1);
+assert(psi=={"hello",1});
+pci = li_std_pair.CIPair(complex(1,2),1);
+assert(pci.first==complex(1,2)&&pci.second==1);
+
+
+psi = li_std_pair.SIPair("hi",1);
+assert(psi.first=="hi"&&psi.second==1);
+
+psii = li_std_pair.SIIPair(psi,1);
+assert(psii.first.first=="hi");
+assert(psii.first.second==1);
+assert(psii.second==1);
+
+a = li_std_pair.A();
+b = li_std_pair.B();
+
+pab = li_std_pair.ABPair(a,b);
+
+pab.first = a;
+pab.first.val = 2;
+
+assert(pab.first.val == 2);
+
+pci = li_std_pair.CIntPair(1,0);
+assert(pci.first==1&&pci.second==0);
+
+a = li_std_pair.A(5);
+p1 = li_std_pair.pairP1(1,a);
+p2 = li_std_pair.pairP2(a,1);
+p3 = li_std_pair.pairP3(a,a);
+
+assert(a.val == li_std_pair.p_identa(p1){2}.val);
+  
+p = li_std_pair.IntPair(1,10);
+assert(p.first==1&&p.second==10);
+p.first = 1;
+assert(p.first==1);
+
+p = li_std_pair.paircA1(1,a);
+assert(p.first==1);
+assert(swig_this(p.second)==swig_this(a));
+
+p = li_std_pair.paircA2(1,a);
+assert(p.first==1);
+assert(swig_this(p.second)==swig_this(a));
+#pp = li_std_pair.pairiiA(1,p); # conversion pb re const of pairA1/A2
+pp = li_std_pair.pairiiA(1,{1,A()});
+
diff --git a/trunk/Examples/test-suite/octave/li_std_set_runme.m b/trunk/Examples/test-suite/octave/li_std_set_runme.m
new file mode 100644
index 0000000..9bd4f15
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_set_runme.m
@@ -0,0 +1,96 @@
+li_std_set
+
+s = set_string()
+
+s.append("a")
+s.append("b")
+s.append("c")
+
+sum = ""
+for i in s:
+    sum = sum + i
+
+if (sum != "abc")
+    error
+
+i = s.__iter__()
+if i.next() != "a":
+    error
+if i.next() != "b":
+    error
+if i.next() != "c":
+    error
+
+
+b = s.begin()
+e = s.end()
+sum = ""
+while (b != e):    
+    sum = sum + b.next()
+if sum != "abc":
+    error
+
+b = s.rbegin()
+e = s.rend()
+sum = ""
+while (b != e):    
+    sum = sum  + b.next()
+
+if sum != "cba":
+    error
+
+
+
+si = set_int()
+
+si.append(1)
+si.append(2)
+si.append(3)
+i = si.__iter__()
+
+if i.next() != 1:
+    error
+if i.next() != 2:
+    error
+if i.next() != 3:
+    error
+
+
+
+
+i = s.begin()
+i.next()
+s.erase(i)
+
+b = s.begin()
+e = s.end()
+sum = ""
+while (b != e):    
+    sum = sum + b.next()
+if sum != "ac":
+    error
+
+
+b = s.begin()
+e = s.end()
+if e - b != 2:
+    error
+    
+m = b + 1
+if m.value() != "c":
+    error
+
+
+
+s = pyset()
+s.insert((1,2))
+s.insert(1)
+s.insert("hello")
+
+
+sum = ()
+for i in s:
+    sum = sum  + (i,)
+
+if sum != (1, 'hello', (1, 2)):
+    error
diff --git a/trunk/Examples/test-suite/octave/li_std_stream_runme.m b/trunk/Examples/test-suite/octave/li_std_stream_runme.m
new file mode 100644
index 0000000..bf9402e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_stream_runme.m
@@ -0,0 +1,13 @@
+li_std_stream
+
+a = A();
+
+o = ostringstream();
+
+o << a << " " << 2345 << " " << 1.435;
+
+
+if (o.str() !=  "A class 2345 1.435")
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_std_string.i b/trunk/Examples/test-suite/octave/li_std_string.i
new file mode 100644
index 0000000..822d713
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_string.i
@@ -0,0 +1,55 @@
+%module li_std_string
+
+%naturalvar A;
+
+
+%include <std_basic_string.i>
+%include <std_string.i>
+
+
+%inline %{
+
+struct A : std::string 
+{
+  A(const std::string& s) : std::string(s)
+  {
+  }
+};
+
+struct B 
+{
+  B(const std::string& s) : cname(0), name(s), a(s)
+  {
+  }
+  
+  char *cname;
+  std::string name;
+  A a;
+
+};
+ 
+
+const char* test_ccvalue(const char* x) {
+   return x;
+}
+
+char* test_cvalue(char* x) {
+   return x;
+}
+
+std::basic_string<char> test_value_basic1(std::basic_string<char> x) {
+   return x;
+}
+
+std::basic_string<char,std::char_traits<char> > test_value_basic2(std::basic_string<char,std::char_traits<char> > x) {
+   return x;
+}
+
+std::basic_string<char,std::char_traits<char>,std::allocator<char> > test_value_basic3(std::basic_string<char,std::char_traits<char>,std::allocator<char> > x) {
+   return x;
+}
+
+%}
+
+%include ../li_std_string.i
+
diff --git a/trunk/Examples/test-suite/octave/li_std_string_runme.m b/trunk/Examples/test-suite/octave/li_std_string_runme.m
new file mode 100644
index 0000000..fa0e260
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_string_runme.m
@@ -0,0 +1,162 @@
+li_std_string
+
+x="hello";
+
+
+
+if (li_std_string.test_ccvalue(x) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_string.test_cvalue(x) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_string.test_value(x) != x)
+  error("bad string mapping: %s, %s", x, li_std_string.test_value(x))
+endif
+
+if (li_std_string.test_const_reference(x) != x)
+  error("bad string mapping")
+endif
+
+
+s = li_std_string.string("he");
+#s += "ll"
+#s.append('o')
+s = s + "llo";
+
+if (s != x)
+  error("bad string mapping: %s, %s", s, x);
+endif
+
+if (s[1:4] != x[1:4])
+  error("bad string mapping")
+endif
+
+if (li_std_string.test_value(s) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_string.test_const_reference(s) != x)
+  error("bad string mapping")
+endif
+
+a = li_std_string.A(s);
+
+if (li_std_string.test_value(a) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_string.test_const_reference(a) != x)
+  error("bad string mapping")
+endif
+
+b = li_std_string.string(" world");
+
+s = a + b;
+if (a + b != "hello world")
+  error("bad string mapping: %s", a + b)
+endif
+  
+if (a + " world" != "hello world")
+  error("bad string mapping")
+endif
+
+if ("hello" + b != "hello world")
+  error("bad string mapping")
+endif
+
+c = ("hello" + b)
+if (c.find_last_of("l") != 9)
+  error("bad string mapping")
+endif
+  
+s = "hello world";
+
+b = li_std_string.B("hi");
+
+b.name = li_std_string.string("hello");
+if (b.name != "hello")
+  error("bad string mapping")
+endif
+
+
+b.a = li_std_string.A("hello");
+if (b.a != "hello")
+  error("bad string mapping")
+endif
+
+
+if (li_std_string.test_value_basic1(x) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_string.test_value_basic2(x) != x)
+  error("bad string mapping")
+endif
+
+
+if (li_std_string.test_value_basic3(x) != x)
+  error("bad string mapping")
+endif
+
+# Global variables
+s = "initial string";
+if (li_std_string.cvar.GlobalString2 != "global string 2")
+  error("GlobalString2 test 1")
+endif
+li_std_string.cvar.GlobalString2 = s;
+if (li_std_string.cvar.GlobalString2 != s)
+  error("GlobalString2 test 2")
+endif
+if (li_std_string.cvar.ConstGlobalString != "const global string")
+  error("ConstGlobalString test")
+endif
+
+# Member variables
+myStructure = li_std_string.Structure();
+if (myStructure.MemberString2 != "member string 2")
+  error("MemberString2 test 1")
+endif
+myStructure.MemberString2 = s;
+if (myStructure.MemberString2 != s)
+  error("MemberString2 test 2")
+endif
+if (myStructure.ConstMemberString != "const member string")
+  error("ConstMemberString test")
+endif
+
+if (li_std_string.cvar.Structure_StaticMemberString2 != "static member string 2")
+  error("StaticMemberString2 test 1")
+endif
+li_std_string.cvar.Structure_StaticMemberString2 = s;
+if (li_std_string.cvar.Structure_StaticMemberString2 != s)
+  error("StaticMemberString2 test 2")
+endif
+if (li_std_string.cvar.Structure_ConstStaticMemberString != "const static member string")
+  error("ConstStaticMemberString test")
+endif
+
+
+if (li_std_string.test_reference_input("hello") != "hello")
+  error
+endif
+s = li_std_string.test_reference_inout("hello");
+if (s != "hellohello")
+  error
+endif
+
+
+if (li_std_string.stdstring_empty() != "")
+  error
+endif
+
+
+if (li_std_string.c_empty() != "")
+  error
+endif
+
+if (li_std_string.c_null() != None)
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/li_std_vector_runme.m b/trunk/Examples/test-suite/octave/li_std_vector_runme.m
new file mode 100644
index 0000000..b9f33ee
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_vector_runme.m
@@ -0,0 +1,160 @@
+li_std_vector
+
+iv = IntVector(4);
+for i=0:4,
+    iv(i) = i;
+endfor
+
+x = average(iv);
+y = average([1,2,3,4]);
+
+a = half([10,10.5,11,11.5]);
+
+dv = DoubleVector(10);
+for i=0:10,
+    dv(i) = i/2.0;
+endfor
+
+halve_in_place(dv);
+
+
+bv = BoolVector(4);
+bv(0)= 1;
+bv(1)= 0;
+bv(2)= 4;
+bv(3)= 0;
+
+if (bv(0) != bv(2))
+    error("bad std::vector<bool> mapping")
+endif
+
+b = B(5);
+va = VecA([b,None,b,b]);
+
+if (va(0).f(1) != 6)
+    error("bad std::vector<A*> mapping")
+endif
+
+if (vecAptr(va) != 6)
+    error("bad std::vector<A*> mapping")
+endif
+
+b.val = 7;
+if (va(3).f(1) != 8)
+    error("bad std::vector<A*> mapping")
+endif
+
+
+ip = PtrInt();
+ap = new_ArrInt(10);
+
+ArrInt_setitem(ip,0,123);
+ArrInt_setitem(ap,2,123);
+
+vi = IntPtrVector((ip,ap,None));
+if (ArrInt_getitem(vi[0],0) != ArrInt_getitem(vi[1],2))
+    error("bad std::vector<int*> mapping")
+endif
+
+delete_ArrInt(ap);
+
+
+a = halfs([10,8,4,3]);
+
+v = IntVector();
+v(0:2) = [1,2];
+if (v(0) != 1 || v[1] != 2)
+    error("bad setslice")
+endif
+
+if (v(0:-1)(0) != 1)
+    error("bad getslice")
+endif
+
+if (v(0:-2).size() != 0)
+    error("bad getslice")
+
+v(0:1) = [2];
+if (v(0) != 2)
+    error("bad setslice")
+endif
+
+v(1:) = [3];
+if (v(1) != 3)
+    error("bad setslice")
+endif
+
+v(2:) = [3]
+if (v(2) != 3)
+    error("bad setslice")
+endif
+
+if (v(0:)(0) != v(0))
+    error("bad getslice")
+endif
+
+
+v.erase(:)
+if (v.size() != 0)
+    error("bad getslice")
+endif
+
+v.erase(:)
+if (v.size() != 0)
+    error("bad getslice")
+endif
+
+
+
+v = vecStr({"hello ", "world"});
+if (v(0) != 'hello world')
+    error,"bad std::string+std::vector"
+endif
+
+
+pv = pyvector({1, "hello", (1,2)});
+
+if (pv(1) != "hello")
+    error
+endif
+
+
+iv = IntVector(5);
+for i=0:5,
+    iv(i) = i
+endif
+
+iv(1:3) = [];
+if (iv(1) != 3)
+    error
+endif
+
+# Overloading checks
+if (overloaded1(iv) != "vector<int>")
+  error
+endif
+
+if (overloaded1(dv) != "vector<double>")
+  error
+endif
+
+if (overloaded2(iv) != "vector<int>")
+  error
+endif
+
+if (overloaded2(dv) != "vector<double>")
+  error
+endif
+
+if (overloaded3(iv) != "vector<int> *")
+  error
+endif
+
+if (overloaded3(None) != "vector<int> *")
+  error
+endif
+
+if (overloaded3(100) != "int")
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_std_wstream_runme.m b/trunk/Examples/test-suite/octave/li_std_wstream_runme.m
new file mode 100644
index 0000000..a017e8a
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_wstream_runme.m
@@ -0,0 +1,14 @@
+li_std_wstream
+
+
+
+a = A();
+
+o = wostringstream();
+
+o << a << u" " << 2345 << u" " << 1.435 << wends;
+
+if (o.str() !=  "A class 2345 1.435\0")
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/li_std_wstring_runme.m b/trunk/Examples/test-suite/octave/li_std_wstring_runme.m
new file mode 100644
index 0000000..e46c1f2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/li_std_wstring_runme.m
@@ -0,0 +1,90 @@
+li_std_wstring
+
+x="h";
+
+if (li_std_wstring.test_wcvalue(x) != x)
+  error("bad string mapping")
+endif
+
+x="hello";
+if (li_std_wstring.test_ccvalue(x) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_wstring.test_cvalue(x) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_wstring.test_value(x) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_wstring.test_const_reference(x) != x)
+  error("bad string mapping")
+endif
+
+
+s = li_std_wstring.wstring("he");
+s = s + "llo";
+
+if (s != x)
+  error("bad string mapping")
+endif
+
+if (s(1:4) != x(1:4))
+  error("bad string mapping")
+endif
+
+if (li_std_wstring.test_value(s) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_wstring.test_const_reference(s) != x)
+  error("bad string mapping")
+endif
+
+a = li_std_wstring.A(s);
+
+if (li_std_wstring.test_value(a) != x)
+  error("bad string mapping")
+endif
+
+if (li_std_wstring.test_const_reference(a) != x)
+  error("bad string mapping")
+endif
+
+b = li_std_wstring.wstring(" world");
+
+if (a + b != "hello world")
+  error("bad string mapping")
+endif
+  
+if (a + " world" != "hello world")
+  error("bad string mapping")
+endif
+
+if ("hello" + b != "hello world")
+  error("bad string mapping")
+endif
+
+c = "hello" + b;
+if (c.find_last_of("l") != 9)
+  error("bad string mapping")
+endif
+  
+s = "hello world";
+
+b = li_std_wstring.B("hi");
+
+b.name = li_std_wstring.wstring("hello");
+if (b.name != "hello")
+  error("bad string mapping")
+endif
+
+
+b.a = li_std_wstring.A("hello");
+if (b.a != "hello")
+  error("bad string mapping")
+endif
+
+
diff --git a/trunk/Examples/test-suite/octave/member_pointer_runme.m b/trunk/Examples/test-suite/octave/member_pointer_runme.m
new file mode 100644
index 0000000..c13350b
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/member_pointer_runme.m
@@ -0,0 +1,45 @@
+# Example using pointers to member functions
+
+member_pointer
+
+function check(what,expected,actual)
+  if (expected != actual)
+    error ("Failed: %s, Expected: %f, Actual: %f",what,expected,actual);
+  endif
+end
+
+# Get the pointers
+
+area_pt = areapt;
+perim_pt = perimeterpt;
+
+# Create some objects
+
+s = Square(10);
+
+# Do some calculations
+
+check ("Square area ", 100.0, do_op(s,area_pt));
+check ("Square perim", 40.0, do_op(s,perim_pt));
+
+memberPtr = cvar.areavar;
+memberPtr = cvar.perimetervar;
+
+# Try the variables
+check ("Square area ", 100.0, do_op(s,cvar.areavar));
+check ("Square perim", 40.0, do_op(s,cvar.perimetervar));
+
+# Modify one of the variables
+cvar.areavar = perim_pt;
+
+check ("Square perimeter", 40.0, do_op(s,cvar.areavar));
+
+# Try the constants
+
+memberPtr = AREAPT;
+memberPtr = PERIMPT;
+memberPtr = NULLPT;
+
+check ("Square area ", 100.0, do_op(s,AREAPT));
+check ("Square perim", 40.0, do_op(s,PERIMPT));
+
diff --git a/trunk/Examples/test-suite/octave/minherit_runme.m b/trunk/Examples/test-suite/octave/minherit_runme.m
new file mode 100644
index 0000000..24d2091
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/minherit_runme.m
@@ -0,0 +1,86 @@
+minherit
+
+a = minherit.Foo();
+b = minherit.Bar();
+c = minherit.FooBar();
+d = minherit.Spam();
+
+if (a.xget() != 1)
+    error("Bad attribute value")
+endif
+
+if (b.yget() != 2)
+    error("Bad attribute value")
+endif
+
+if (c.xget() != 1 || c.yget() != 2 || c.zget() != 3)
+    error("Bad attribute value")
+endif
+
+if (d.xget() != 1 || d.yget() != 2 || d.zget() != 3 || d.wget() != 4)
+    error("Bad attribute value")
+endif
+
+
+if (minherit.xget(a) != 1)
+    error("Bad attribute value %d",minherit.xget(a))
+endif
+
+if (minherit.yget(b) != 2)
+    error("Bad attribute value %d",minherit.yget(b))
+endif
+
+if (minherit.xget(c) != 1 || minherit.yget(c) != 2 || minherit.zget(c) != 3)
+    error("Bad attribute value %d %d %d",minherit.xget(c),minherit.yget(c),minherit.zget(c))
+endif
+
+if (minherit.xget(d) != 1 || minherit.yget(d) != 2 || minherit.zget(d) != 3 || minherit.wget(d) != 4)
+    error("Bad attribute value %d %d %d %d",minherit.xget(d),minherit.yget(d),minherit.zget(d),minherit.wget(d))
+endif
+
+# Cleanse all of the pointers and see what happens
+
+aa = minherit.toFooPtr(a);
+bb = minherit.toBarPtr(b);
+cc = minherit.toFooBarPtr(c);
+dd = minherit.toSpamPtr(d);
+
+if (aa.xget() != 1)
+    error("Bad attribute value");
+endif
+
+if (bb.yget() != 2)
+    error("Bad attribute value");
+endif
+
+if (cc.xget() != 1 || cc.yget() != 2 || cc.zget() != 3)
+    error("Bad attribute value")
+endif
+
+if (dd.xget() != 1 || dd.yget() != 2 || dd.zget() != 3 || dd.wget() != 4)
+    error("Bad attribute value")
+endif
+
+if (minherit.xget(aa) != 1)
+    error("Bad attribute value %d",minherit.xget(aa));
+endif
+
+if (minherit.yget(bb) != 2)
+    error("Bad attribute value %d",minherit.yget(bb));
+endif
+
+if (minherit.xget(cc) != 1 || minherit.yget(cc) != 2 || minherit.zget(cc) != 3)
+    error("Bad attribute value %d %d %d",minherit.xget(cc),minherit.yget(cc),minherit.zget(cc));
+endif
+
+if (minherit.xget(dd) != 1 || minherit.yget(dd) != 2 || minherit.zget(dd) != 3 || minherit.wget(dd) != 4)
+    error("Bad attribute value %d %d %d %d",minherit.xget(dd),minherit.yget(dd),minherit.zget(dd),minherit.wget(dd))
+endif
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/octave/mod_runme.m b/trunk/Examples/test-suite/octave/mod_runme.m
new file mode 100644
index 0000000..faebf70
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/mod_runme.m
@@ -0,0 +1,7 @@
+mod_a
+mod_b
+
+c = mod_b.C();
+d = mod_b.D();
+d.DoSomething(c);
+
diff --git a/trunk/Examples/test-suite/octave/multi_import_runme.m b/trunk/Examples/test-suite/octave/multi_import_runme.m
new file mode 100644
index 0000000..a613873
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/multi_import_runme.m
@@ -0,0 +1,24 @@
+multi_import_a
+multi_import_b
+
+x = multi_import_b.XXX();
+if (x.testx() != 0)
+  error
+endif
+
+y = multi_import_b.YYY();
+if (y.testx() != 0)
+  error
+endif
+if (y.testy() != 1)
+  error
+endif
+
+z = multi_import_a.ZZZ();
+if (z.testx() != 0)
+  error
+endif
+if (z.testz() != 2)
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/namespace_class_runme.m b/trunk/Examples/test-suite/octave/namespace_class_runme.m
new file mode 100644
index 0000000..564cf87
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/namespace_class_runme.m
@@ -0,0 +1,39 @@
+namespace_class
+
+try
+  p = Private1();
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+
+if (ok)
+  error("Private1 is private")
+endif
+
+try
+  p = Private2();
+  ok = 1;
+catch
+  ok = 0;
+end_try_catch
+
+if (ok)
+  error("Private2 is private")
+endif
+
+EulerT3D.toFrame(1,1,1);
+
+b = BooT_i();
+b = BooT_H();
+
+
+f = FooT_i();
+f.quack(1);
+
+f = FooT_d();
+f.moo(1);
+
+f = FooT_H();
+f.foo(Hi);
+
diff --git a/trunk/Examples/test-suite/octave/namespace_typemap_runme.m b/trunk/Examples/test-suite/octave/namespace_typemap_runme.m
new file mode 100644
index 0000000..ca37307
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/namespace_typemap_runme.m
@@ -0,0 +1,106 @@
+namespace_typemap
+
+if (!strcmp(stest1("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest2("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest3("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest4("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest5("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest6("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest7("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest8("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest9("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest10("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest11("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(stest12("hello"),"hello"))
+    error
+endif
+
+c = complex(2,3);
+r = real(c);
+
+if (ctest1(c) != r)
+    error
+endif
+
+if (ctest2(c) != r)
+    error
+endif
+
+if (ctest3(c) != r)
+    error
+endif
+
+if (ctest4(c) != r)
+    error
+endif
+
+if (ctest5(c) != r)
+    error
+endif
+
+if (ctest6(c) != r)
+    error
+endif
+
+if (ctest7(c) != r)
+    error
+endif
+
+if (ctest8(c) != r)
+    error
+endif
+
+if (ctest9(c) != r)
+    error
+endif
+
+if (ctest10(c) != r)
+    error
+endif
+
+if (ctest11(c) != r)
+    error
+endif
+
+if (ctest12(c) != r)
+    error
+endif
+
+try
+    ttest1(-14)
+    error
+catch
+end_try_catch
diff --git a/trunk/Examples/test-suite/octave/namespace_virtual_method_runme.m b/trunk/Examples/test-suite/octave/namespace_virtual_method_runme.m
new file mode 100644
index 0000000..b78e912
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/namespace_virtual_method_runme.m
@@ -0,0 +1,4 @@
+namespace_virtual_method
+
+x = namespace_virtual_method.Spam();
+
diff --git a/trunk/Examples/test-suite/octave/naturalvar_runme.m b/trunk/Examples/test-suite/octave/naturalvar_runme.m
new file mode 100644
index 0000000..889563f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/naturalvar_runme.m
@@ -0,0 +1,14 @@
+naturalvar
+
+f = Foo();
+b = Bar();
+
+b.f = f;
+
+cvar.s = "hello";
+b.s = "hello";
+
+if (b.s != cvar.s)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/nondynamic_runme.m b/trunk/Examples/test-suite/octave/nondynamic_runme.m
new file mode 100644
index 0000000..7b3b441
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/nondynamic_runme.m
@@ -0,0 +1,36 @@
+nondynamic
+
+aa = nondynamic.A();
+
+aa.a = 1;
+aa.b = 2;
+try
+  aa.c = 2;
+  err = 0;
+catch
+  err = 1;
+end_try_catch
+
+if (!err)
+  error("A is not static")
+endif
+
+
+B=@() subclass(nondynamic.A(),'c',4);
+
+bb = B();
+bb.c = 3;
+try
+  bb.d = 2
+  err = 0
+catch
+  err = 1
+end_try_catch
+
+if (!err)
+  error("B is not static")
+endif
+    
+cc = nondynamic.C();
+cc.d = 3;
+
diff --git a/trunk/Examples/test-suite/octave/null_pointer_runme.m b/trunk/Examples/test-suite/octave/null_pointer_runme.m
new file mode 100644
index 0000000..51b6eaf
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/null_pointer_runme.m
@@ -0,0 +1,3 @@
+null_pointer;
+
+assert(func([]));
diff --git a/trunk/Examples/test-suite/octave/overload_complicated_runme.m b/trunk/Examples/test-suite/octave/overload_complicated_runme.m
new file mode 100755
index 0000000..0313be9
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_complicated_runme.m
@@ -0,0 +1,58 @@
+overload_complicated
+
+pInt = None;
+
+# Check the correct constructors are available
+p = Pop(pInt);
+
+p = Pop(pInt, 0);
+
+# Check overloaded in const only and pointers/references which target languages cannot disambiguate
+if (p.hip(0) != 701)
+  error("Test 1 failed")
+endif
+
+if (p.hip(pInt) != 702)
+  error("Test 2 failed")
+endif
+
+# Reverse the order for the above
+if (p.hop(pInt) != 805)
+  error("Test 3 failed")
+endif
+
+if (p.hop(0) != 801)
+  error("Test 4 failed")
+endif
+
+# Few more variations and order shuffled
+if (p.pop(0) != 901)
+  error("Test 5 failed")
+endif
+
+if (p.pop(pInt) != 902)
+  error("Test 6 failed")
+endif
+
+if (p.pop() != 905)
+  error("Test 7 failed")
+endif
+
+# Overload on const only
+if (p.bop(pInt) != 1001)
+  error("Test 8 failed")
+endif
+
+if (p.bip(pInt) != 2001)
+  error("Test 9 failed")
+endif
+
+# Globals
+if (muzak(0) != 3001)
+  error("Test 10 failed")
+endif
+
+if (muzak(pInt) != 3002)
+  error("Test 11 failed")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/overload_copy_runme.m b/trunk/Examples/test-suite/octave/overload_copy_runme.m
new file mode 100644
index 0000000..b303ba6
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_copy_runme.m
@@ -0,0 +1,3 @@
+overload_copy
+f = Foo();
+g = Foo(f);
diff --git a/trunk/Examples/test-suite/octave/overload_extend_runme.m b/trunk/Examples/test-suite/octave/overload_extend_runme.m
new file mode 100644
index 0000000..42c7938
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_extend_runme.m
@@ -0,0 +1,19 @@
+overload_extend
+
+f = overload_extend.Foo();
+if (f.test() != 0)
+    error
+endif
+if (f.test(3) != 1)
+    error
+endif
+if (f.test("hello") != 2)
+    error
+endif
+if (f.test(3,2) != 5)
+    error
+endif
+if (f.test(3.1)-.1 != 1003) # :)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/overload_extendc_runme.m b/trunk/Examples/test-suite/octave/overload_extendc_runme.m
new file mode 100644
index 0000000..fec586d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_extendc_runme.m
@@ -0,0 +1,30 @@
+overload_extendc
+
+f = overload_extendc.Foo();
+if (f.test(3) != 1)
+    error
+endif
+if (f.test("hello") != 2)
+    error
+endif
+if (f.test(3.5,2.5) != 3)
+    error
+endif
+if (f.test("hello",20) != 1020)
+    error
+endif
+if (f.test("hello",20,100) != 120)
+    error
+endif
+
+# C default args
+if (f.test(f) != 30)
+    error
+endif
+if (f.test(f,100) != 120)
+    error
+endif
+if (f.test(f,100,200) != 300)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/overload_rename_runme.m b/trunk/Examples/test-suite/octave/overload_rename_runme.m
new file mode 100644
index 0000000..4a416cf
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_rename_runme.m
@@ -0,0 +1,8 @@
+overload_rename
+
+
+f = overload_rename.Foo(1);
+f = overload_rename.Foo(1,1);
+f = overload_rename.new_Foo_int(1,1);
+f = overload_rename.new_Foo_int(1,1,1);
+
diff --git a/trunk/Examples/test-suite/octave/overload_simple_cast_runme.m b/trunk/Examples/test-suite/octave/overload_simple_cast_runme.m
new file mode 100644
index 0000000..65bc422
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_simple_cast_runme.m
@@ -0,0 +1,229 @@
+overload_simple_cast
+
+Ai=@(x) subclass('x',x,'__int',@(self) self.x);
+Ad=@(x) subclass('x',x,'__float',@(self) self.x);
+
+ai = Ai(4);
+
+ad = Ad(5.0);
+add = Ad(5.5);
+
+try
+    fint(add);
+    good = 0;
+catch
+    good = 1;
+end_try_catch
+
+if (!good)
+    error("fint(int)")
+endif
+
+
+if (!strcmp(fint(ad),"fint:int"))
+    error("fint(int)")
+endif
+
+if (!strcmp(fdouble(ad),"fdouble:double"))
+    error("fdouble(double)")
+endif
+
+if (!strcmp(fint(ai),"fint:int"))
+    error("fint(int)")
+endif
+
+if (!strcmp(fint(5.0),"fint:int"))
+    error("fint(int)")
+endif
+    
+if (!strcmp(fint(3),"fint:int"))
+    error("fint(int)")
+endif
+if (!strcmp(fint(3.0),"fint:int"))
+    error("fint(int)")
+endif
+
+if (!strcmp(fdouble(ad),"fdouble:double"))
+    error("fdouble(double)")
+endif
+if (!strcmp(fdouble(3),f"fdouble:double"))
+    error("fdouble(double)")
+endif
+if (!strcmp(fdouble(3.0),"fdouble:double"))
+    error("fdouble(double)")
+endif
+
+if (!strcmp(fid(3,3.0),"fid:intdouble"))
+    error("fid:intdouble")
+endif
+
+if (!strcmp(fid(3.0,3),"fid:doubleint"))
+    error("fid:doubleint")
+endif
+
+if (!strcmp(fid(ad,ai),"fid:doubleint"))
+    error("fid:doubleint")
+endif
+
+if (!strcmp(fid(ai,ad),"fid:intdouble"))
+    error("fid:intdouble")
+endif
+
+
+
+if (!strcmp(foo(3),"foo:int"))
+    error("foo(int)")
+endif
+
+if (!strcmp(foo(3.0),"foo:double"))
+    error("foo(double)")
+endif
+
+if (!strcmp(foo("hello"),"foo:char *"))
+    error("foo(char *)")
+endif
+
+f = Foo();
+b = Bar();
+
+if (!strcmp(foo(f),"foo:Foo *"))
+    error("foo(Foo *)")
+endif
+
+if (!strcmp(foo(b),"foo:Bar *"))
+    error("foo(Bar *)")
+endif
+
+v = malloc_void(32);
+
+if (!strcmp(foo(v),"foo:void *"))
+    error("foo(void *)")
+endif
+
+s = Spam();
+
+if (!strcmp(s.foo(3),"foo:int"))
+    error("Spam::foo(int)")
+endif
+
+if (!strcmp(s.foo(3.0),"foo:double"))
+    error("Spam::foo(double)")
+endif
+
+if (!strcmp(s.foo("hello"),"foo:char *"))
+    error("Spam::foo(char *)")
+endif
+
+if (!strcmp(s.foo(f),"foo:Foo *"))
+    error("Spam::foo(Foo *)")
+endif
+
+if (!strcmp(s.foo(b),"foo:Bar *"))
+    error("Spam::foo(Bar *)")
+endif
+
+if (!strcmp(s.foo(v),"foo:void *"))
+    error("Spam::foo(void *)")
+endif
+
+if (!strcmp(Spam_bar(3),"bar:int"))
+    error("Spam::bar(int)")
+endif
+
+if (!strcmp(Spam_bar(3.0),"bar:double"))
+    error("Spam::bar(double)")
+endif
+
+if (!strcmp(Spam_bar("hello"),"bar:char *"))
+    error("Spam::bar(char *)")
+endif
+
+if (!strcmp(Spam_bar(f),"bar:Foo *"))
+    error("Spam::bar(Foo *)")
+endif
+
+if (!strcmp(Spam_bar(b),"bar:Bar *"))
+    error("Spam::bar(Bar *)")
+endif
+
+if (!strcmp(Spam_bar(v),"bar:void *"))
+    error("Spam::bar(void *)")
+endif
+
+# Test constructors
+
+s = Spam();
+if (!strcmp(s.type,"none"))
+    error("Spam()")
+endif
+
+s = Spam(3);
+if (!strcmp(s.type,"int"))
+    error("Spam(int)")
+endif
+    
+s = Spam(3.4);
+if (!strcmp(s.type,"double"))
+    error("Spam(double)")
+endif
+
+s = Spam("hello");
+if (!strcmp(s.type,"char *"))
+    error("Spam(char *)")
+endif
+
+s = Spam(f);
+if (!strcmp(s.type,"Foo *"))
+    error("Spam(Foo *)")
+endif
+
+s = Spam(b);
+if (!strcmp(s.type,"Bar *"))
+    error("Spam(Bar *)")
+endif
+
+s = Spam(v);
+if (!strcmp(s.type,"void *"))
+    error("Spam(void *)")
+endif
+
+
+# unsigned long long
+ullmax = 9223372036854775807; #0xffffffffffffffff
+ullmaxd = 9007199254740992.0;
+ullmin = 0;
+ullmind = 0.0;
+if (ull(ullmin) != ullmin)
+    error("ull(ullmin)")
+endif
+if (ull(ullmax) != ullmax)
+    error("ull(ullmax)")
+endif
+if (ull(ullmind) != ullmind)
+    error("ull(ullmind)")
+endif
+if (ull(ullmaxd) != ullmaxd)
+    error("ull(ullmaxd)")
+endif
+
+# long long
+llmax = 9223372036854775807; #0x7fffffffffffffff
+llmin = -9223372036854775808;
+# these are near the largest  floats we can still convert into long long
+llmaxd = 9007199254740992.0;
+llmind = -9007199254740992.0;
+if (ll(llmin) != llmin)
+    error("ll(llmin)")
+endif
+if (ll(llmax) != llmax)
+    error("ll(llmax)")
+endif
+if (ll(llmind) != llmind)
+    error("ll(llmind)")
+endif
+if (ll(llmaxd) != llmaxd)
+    error("ll(llmaxd)")
+endif
+
+free_void(v);
+
diff --git a/trunk/Examples/test-suite/octave/overload_simple_runme.m b/trunk/Examples/test-suite/octave/overload_simple_runme.m
new file mode 100644
index 0000000..e980610
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_simple_runme.m
@@ -0,0 +1,125 @@
+overload_simple
+
+# unless explicitly casted via {{u}int{8,16,32,64},double,single},
+# octave will take numeric literals as doubles.
+
+if (!strcmp(foo(3),"foo:int"))
+    error("foo(int)")
+endif
+
+if (!strcmp(foo(3.1),"foo:double"))
+    error("foo(double)")
+endif
+
+if (!strcmp(foo("hello"),"foo:char *"))
+    error("foo(char *)")
+endif
+
+f = Foo();
+b = Bar();
+
+if (!strcmp(foo(f),"foo:Foo *"))
+    error("foo(Foo *)")
+endif
+
+if (!strcmp(foo(b),"foo:Bar *"))
+    error("foo(Bar *)")
+endif
+
+v = malloc_void(32);
+
+if (!strcmp(foo(v),"foo:void *"))
+    error("foo(void *)")
+endif
+
+s = Spam();
+
+if (!strcmp(s.foo(3),"foo:int"))
+    error("Spam::foo(int)")
+endif
+
+if (!strcmp(s.foo(3.1),"foo:double"))
+    error("Spam::foo(double)")
+endif
+
+if (!strcmp(s.foo("hello"),"foo:char *"))
+    error("Spam::foo(char *)")
+endif
+
+if (!strcmp(s.foo(f),"foo:Foo *"))
+    error("Spam::foo(Foo *)")
+endif
+
+if (!strcmp(s.foo(b),"foo:Bar *"))
+    error("Spam::foo(Bar *)")
+endif
+
+if (!strcmp(s.foo(v),"foo:void *"))
+    error("Spam::foo(void *)")
+endif
+
+if (!strcmp(Spam_bar(3),"bar:int"))
+    error("Spam::bar(int)")
+endif
+
+if (!strcmp(Spam_bar(3.1),"bar:double"))
+    error("Spam::bar(double)")
+endif
+
+if (!strcmp(Spam_bar("hello"),"bar:char *"))
+    error("Spam::bar(char *)")
+endif
+
+if (!strcmp(Spam_bar(f),"bar:Foo *"))
+    error("Spam::bar(Foo *)")
+endif
+
+if (!strcmp(Spam_bar(b),"bar:Bar *"))
+    error("Spam::bar(Bar *)")
+endif
+
+if (!strcmp(Spam_bar(v),"bar:void *"))
+    error("Spam::bar(void *)")
+endif
+
+# Test constructors
+
+s = Spam();
+if (!strcmp(s.type,"none"))
+    error("Spam()")
+endif
+
+s = Spam(3);
+if (!strcmp(s.type,"int"))
+    error("Spam(int)")
+endif
+    
+s = Spam(3.4);
+if (!strcmp(s.type,"double"))
+    error("Spam(double)")
+endif
+
+s = Spam("hello");
+if (!strcmp(s.type,"char *"))
+    error("Spam(char *)")
+endif
+
+s = Spam(f);
+if (!strcmp(s.type,"Foo *"))
+    error("Spam(Foo *)")
+endif
+
+s = Spam(b);
+if (!strcmp(s.type,"Bar *"))
+    error("Spam(Bar *)")
+endif
+
+s = Spam(v);
+if (!strcmp(s.type,"void *"))
+    error("Spam(void *)")
+endif
+
+free_void(v);
+
+a = ClassA();
+b = a.method1(1);
diff --git a/trunk/Examples/test-suite/octave/overload_subtype_runme.m b/trunk/Examples/test-suite/octave/overload_subtype_runme.m
new file mode 100644
index 0000000..b34be97
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_subtype_runme.m
@@ -0,0 +1,13 @@
+overload_subtype
+
+f = Foo();
+b = Bar();
+
+if (spam(f) != 1)
+    error("foo")
+endif
+
+if (spam(b) != 2)
+    error("bar")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/overload_template_fast_runme.m b/trunk/Examples/test-suite/octave/overload_template_fast_runme.m
new file mode 100644
index 0000000..346af72
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_template_fast_runme.m
@@ -0,0 +1,188 @@
+overload_template_fast
+
+# unless explicitly casted via {{u}int{8,16,32,64},double,single},
+# octave will take numeric literals as doubles.
+
+f = foo();
+
+a = max(3,4);
+b = max(3.4,5.2);
+
+# mix 1
+if (mix1("hi") != 101)
+  error("mix1(const char*)")
+endif
+
+if (mix1(1.1, 1.1) != 102)
+  error("mix1(double, const double &)")
+endif
+
+if (mix1(1.1) != 103)
+  error("mix1(double)")
+endif
+
+# mix 2
+if (mix2("hi") != 101)
+  error("mix2(const char*)")
+endif
+
+if (mix2(1.1, 1.1) != 102)
+  error("mix2(double, const double &)")
+endif
+
+if (mix2(1.1) != 103)
+  error("mix2(double)")
+endif
+
+# mix 3
+if (mix3("hi") != 101)
+  error("mix3(const char*)")
+endif
+
+if (mix3(1.1, 1.1) != 102)
+  error("mix3(double, const double &)")
+endif
+
+if (mix3(1.1) != 103)
+  error("mix3(double)")
+endif
+
+# Combination 1
+if (overtparams1(100) != 10)
+  error("overtparams1(int)")
+endif
+
+if (overtparams1(100.1, 100) != 20)
+  error("overtparams1(double, int)")
+endif
+
+# Combination 2
+if (overtparams2(100.1, 100) != 40)
+  error("overtparams2(double, int)")
+endif
+
+# Combination 3
+if (overloaded() != 60)
+  error("overloaded()")
+endif
+
+if (overloaded(100.1, 100) != 70)
+  error("overloaded(double, int)")
+endif
+
+# Combination 4
+if (overloadedagain("hello") != 80)
+  error("overloadedagain(const char *)")
+endif
+
+if (overloadedagain() != 90)
+  error("overloadedagain(double)")
+endif
+
+# specializations
+if (specialization(10) != 202)
+  error("specialization(int)")
+endif
+
+if (specialization(10.1) != 203)
+  error("specialization(double)")
+endif
+
+if (specialization(10, 10) != 204)
+  error("specialization(int, int)")
+endif
+
+if (specialization(10.1, 10.1) != 205)
+  error("specialization(double, double)")
+endif
+
+if (specialization("hi", "hi") != 201)
+  error("specialization(const char *, const char *)")
+endif
+
+
+# simple specialization
+xyz();
+xyz_int();
+xyz_double();
+
+# a bit of everything
+if (overload("hi") != 0)
+  error("overload()")
+endif
+
+if (overload(1) != 10)
+  error("overload(int t)")
+endif
+
+if (overload(1, 1) != 20)
+  error("overload(int t, const int &)")
+endif
+
+if (overload(1, "hello") != 30)
+  error("overload(int t, const char *)")
+endif
+
+k = Klass();
+if (overload(k) != 10)
+  error("overload(Klass t)")
+endif
+
+if (overload(k, k) != 20)
+  error("overload(Klass t, const Klass &)")
+endif
+
+if (overload(k, "hello") != 30)
+  error("overload(Klass t, const char *)")
+endif
+
+if (overload(10.1, "hi") != 40)
+  error("overload(double t, const char *)")
+endif
+
+if (overload() != 50)
+  error("overload(const char *)")
+endif
+
+
+# everything put in a namespace
+if (nsoverload("hi") != 1000)
+  error("nsoverload()")
+endif
+
+if (nsoverload(1) != 1010)
+  error("nsoverload(int t)")
+endif
+
+if (nsoverload(1, 1) != 1020)
+  error("nsoverload(int t, const int &)")
+endif
+
+if (nsoverload(1, "hello") != 1030)
+  error("nsoverload(int t, const char *)")
+endif
+
+if (nsoverload(k) != 1010)
+  error("nsoverload(Klass t)")
+endif
+
+if (nsoverload(k, k) != 1020)
+  error("nsoverload(Klass t, const Klass &)")
+endif
+
+if (nsoverload(k, "hello") != 1030)
+  error("nsoverload(Klass t, const char *)")
+endif
+
+if (nsoverload(10.1, "hi") != 1040)
+  error("nsoverload(double t, const char *)")
+endif
+
+if (nsoverload() != 1050)
+  error("nsoverload(const char *)")
+endif
+
+
+A.foo(1);
+b = B();
+b.foo(1);
diff --git a/trunk/Examples/test-suite/octave/overload_template_runme.m b/trunk/Examples/test-suite/octave/overload_template_runme.m
new file mode 100644
index 0000000..b38dc73
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/overload_template_runme.m
@@ -0,0 +1,184 @@
+overload_template
+f = foo();
+
+a = max(3,4);
+b = max(3.4,5.2);
+
+# mix 1
+if (mix1("hi") != 101)
+  error("mix1(const char*)")
+endif
+
+if (mix1(1.0, 1.0) != 102)
+  error("mix1(double, const double &)")
+endif
+
+if (mix1(1.0) != 103)
+  error("mix1(double)")
+endif
+
+# mix 2
+if (mix2("hi") != 101)
+  error("mix2(const char*)")
+endif
+
+if (mix2(1.0, 1.0) != 102)
+  error("mix2(double, const double &)")
+endif
+
+if (mix2(1.0) != 103)
+  error("mix2(double)")
+endif
+
+# mix 3
+if (mix3("hi") != 101)
+  error("mix3(const char*)")
+endif
+
+if (mix3(1.0, 1.0) != 102)
+  error("mix3(double, const double &)")
+endif
+
+if (mix3(1.0) != 103)
+  error("mix3(double)")
+endif
+
+# Combination 1
+if (overtparams1(100) != 10)
+  error("overtparams1(int)")
+endif
+
+if (overtparams1(100.0, 100) != 20)
+  error("overtparams1(double, int)")
+endif
+
+# Combination 2
+if (overtparams2(100.0, 100) != 40)
+  error("overtparams2(double, int)")
+endif
+
+# Combination 3
+if (overloaded() != 60)
+  error("overloaded()")
+endif
+
+if (overloaded(100.0, 100) != 70)
+  error("overloaded(double, int)")
+endif
+
+# Combination 4
+if (overloadedagain("hello") != 80)
+  error("overloadedagain(const char *)")
+endif
+
+if (overloadedagain() != 90)
+  error("overloadedagain(double)")
+endif
+
+# specializations
+if (specialization(10) != 202)
+  error("specialization(int)")
+endif
+
+if (specialization(10.1) != 203)
+  error("specialization(double)")
+endif
+
+if (specialization(10, 10) != 204)
+  error("specialization(int, int)")
+endif
+
+if (specialization(10.0, 10.1) != 205)
+  error("specialization(double, double)")
+endif
+
+if (specialization("hi", "hi") != 201)
+  error("specialization(const char *, const char *)")
+endif
+
+
+# simple specialization
+xyz();
+xyz_int();
+xyz_double();
+
+# a bit of everything
+if (overload("hi") != 0)
+  error("overload()")
+endif
+
+if (overload(1) != 10)
+  error("overload(int t)")
+endif
+
+if (overload(1, 1) != 20)
+  error("overload(int t, const int &)")
+endif
+
+if (overload(1, "hello") != 30)
+  error("overload(int t, const char *)")
+endif
+
+k = Klass();
+if (overload(k) != 10)
+  error("overload(Klass t)")
+endif
+
+if (overload(k, k) != 20)
+  error("overload(Klass t, const Klass &)")
+endif
+
+if (overload(k, "hello") != 30)
+  error("overload(Klass t, const char *)")
+endif
+
+if (overload(10.1, "hi") != 40)
+  error("overload(double t, const char *)")
+endif
+
+if (overload() != 50)
+  error("overload(const char *)")
+endif
+
+
+# everything put in a namespace
+if (nsoverload("hi") != 1000)
+  error("nsoverload()")
+endif
+
+if (nsoverload(1) != 1010)
+  error("nsoverload(int t)")
+endif
+
+if (nsoverload(1, 1) != 1020)
+  error("nsoverload(int t, const int &)")
+endif
+
+if (nsoverload(1, "hello") != 1030)
+  error("nsoverload(int t, const char *)")
+endif
+
+if (nsoverload(k) != 1010)
+  error("nsoverload(Klass t)")
+endif
+
+if (nsoverload(k, k) != 1020)
+  error("nsoverload(Klass t, const Klass &)")
+endif
+
+if (nsoverload(k, "hello") != 1030)
+  error("nsoverload(Klass t, const char *)")
+endif
+
+if (nsoverload(10.1, "hi") != 1040)
+  error("nsoverload(double t, const char *)")
+endif
+
+if (nsoverload() != 1050)
+  error("nsoverload(const char *)")
+endif
+
+
+A_foo(1);
+b = B();
+b.foo(1);
diff --git a/trunk/Examples/test-suite/octave/preproc_runme.m b/trunk/Examples/test-suite/octave/preproc_runme.m
new file mode 100644
index 0000000..791b38b
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/preproc_runme.m
@@ -0,0 +1,18 @@
+preproc
+
+if (preproc.cvar.endif != 1)
+  error
+endif
+
+if (preproc.cvar.define != 1)
+  error
+endif
+
+if (preproc.cvar.defined != 1)
+  error
+endif
+
+if (2*preproc.one != preproc.two)
+  error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/primitive_ref_runme.m b/trunk/Examples/test-suite/octave/primitive_ref_runme.m
new file mode 100644
index 0000000..68a5750
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/primitive_ref_runme.m
@@ -0,0 +1,53 @@
+primitive_ref
+
+if (ref_int(3) != 3)
+    error
+endif
+
+if (ref_uint(3) != 3)
+    error
+endif
+
+if (ref_short(3) != 3)
+    error
+endif
+
+if (ref_ushort(3) != 3)
+    error
+endif
+
+if (ref_long(3) != 3)
+    error
+endif
+
+if (ref_ulong(3) != 3)
+    error
+endif
+
+if (ref_schar(3) != 3)
+    error
+endif
+
+if (ref_uchar(3) != 3)
+    error
+endif
+
+if (ref_float(3.5) != 3.5)
+    error
+endif
+
+if (ref_double(3.5) != 3.5)
+    error
+endif
+
+if (ref_bool(true) != true)
+    error
+endif
+
+if (!strcmp(ref_char('x'),'x'))
+    error
+endif
+
+if (ref_over(0) != 0)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/primitive_types_runme.m b/trunk/Examples/test-suite/octave/primitive_types_runme.m
new file mode 100644
index 0000000..568e351
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/primitive_types_runme.m
@@ -0,0 +1,402 @@
+primitive_types
+
+var_init();
+
+# assigning globals calls
+cvar.var_bool = sct_bool;
+cvar.var_schar = sct_schar;
+cvar.var_uchar = sct_uchar;
+cvar.var_int = sct_int;
+cvar.var_uint = sct_uint;
+cvar.var_short = sct_short;
+cvar.var_ushort = sct_ushort;
+cvar.var_long = sct_long;
+cvar.var_ulong = sct_ulong;
+cvar.var_llong = sct_llong;
+cvar.var_ullong = sct_ullong;
+cvar.var_char = sct_char;
+cvar.var_pchar = sct_pchar;
+cvar.var_pcharc = sct_pcharc;
+cvar.var_pint = sct_pint;
+cvar.var_sizet = sct_sizet;
+cvar.var_hello = sct_hello;
+cvar.var_myint = sct_myint;
+cvar.var_namet = def_namet;
+cvar.var_parami = sct_parami;
+cvar.var_paramd = sct_paramd;
+cvar.var_paramc = sct_paramc;
+
+v_check();
+
+function octerror(name, val, cte)
+  name, val, cte
+  error
+endfunction
+
+if cvar.var_bool != cct_bool:
+octerror("bool", cvar.var_bool, cct_bool)
+endif
+if cvar.var_schar != cct_schar:
+octerror("schar", cvar.var_schar, cct_schar)
+endif
+if cvar.var_uchar != cct_uchar:
+ octerror("uchar", cvar.var_uchar, cct_uchar)
+endif
+if cvar.var_int != cct_int:
+ octerror("int", cvar.var_int, cct_int)
+endif
+if cvar.var_uint != cct_uint:
+ octerror("uint", cvar.var_uint, cct_uint)
+endif
+if cvar.var_short != cct_short:
+ octerror("short", cvar.var_short, cct_short)
+endif
+if cvar.var_ushort != cct_ushort:
+ octerror("ushort", cvar.var_ushort, cct_ushort)
+endif
+if cvar.var_long != cct_long:
+ octerror("long", cvar.var_long, cct_long)
+endif
+if cvar.var_ulong != cct_ulong:
+ octerror("ulong", cvar.var_ulong, cct_ulong)
+endif
+if cvar.var_llong != cct_llong:
+ octerror("llong", cvar.var_llong, cct_llong)
+endif
+if cvar.var_ullong != cct_ullong:
+ octerror("ullong", cvar.var_ullong, cct_ullong)
+endif
+if cvar.var_char != cct_char:
+ octerror("char", cvar.var_char, cct_char)
+endif
+if cvar.var_pchar != cct_pchar:
+ octerror("pchar", cvar.var_pchar, cct_pchar)
+endif
+if cvar.var_pcharc != cct_pcharc:
+ octerror("pchar", cvar.var_pcharc, cct_pcharc)
+endif
+if cvar.var_pint != cct_pint:
+ octerror("pint", cvar.var_pint, cct_pint)
+endif
+if cvar.var_sizet != cct_sizet:
+ octerror("sizet", cvar.var_sizet, cct_sizet)
+endif
+if cvar.var_hello != cct_hello:
+ octerror("hello", cvar.var_hello, cct_hello)
+endif
+if cvar.var_myint != cct_myint:
+ octerror("myint", cvar.var_myint, cct_myint)
+endif
+if cvar.var_namet != def_namet:
+ octerror("name", cvar.var_namet, def_namet)
+endif
+
+
+function OctTest()
+  self=subclass(TestDirector);
+  self.ident=@(self,x) x;
+  
+  self.vval_bool=@(self, x) self.ident(x);
+  self.vval_schar=@(self, x) self.ident(x);
+  self.vval_uchar=@(self, x) self.ident(x);
+  self.vval_int=@(self, x) self.ident(x);
+  self.vval_uint=@(self, x) self.ident(x);
+  self.vval_short=@(self, x) self.ident(x);
+  self.vval_ushort=@(self, x) self.ident(x);
+  self.vval_long=@(self, x) self.ident(x);
+  self.vval_ulong=@(self, x) self.ident(x);
+  self.vval_llong=@(self, x) self.ident(x);
+  self.vval_ullong=@(self, x) self.ident(x);
+  self.vval_float=@(self, x) self.ident(x);
+  self.vval_double=@(self, x) self.ident(x);
+  self.vval_char=@(self, x) self.ident(x);
+  self.vval_pchar=@(self, x) self.ident(x);
+  self.vval_pcharc=@(self, x) self.ident(x);
+  self.vval_pint=@(self, x) self.ident(x);
+  self.vval_sizet=@(self, x) self.ident(x);
+  self.vval_hello=@(self, x) self.ident(x);
+  self.vval_myint=@(self, x) self.ident(x);
+
+  self.vref_bool=@(self, x) self.ident(x);
+  self.vref_schar=@(self, x) self.ident(x);
+  self.vref_uchar=@(self, x) self.ident(x);
+  self.vref_int=@(self, x) self.ident(x);
+  self.vref_uint=@(self, x) self.ident(x);
+  self.vref_short=@(self, x) self.ident(x);
+  self.vref_ushort=@(self, x) self.ident(x);
+  self.vref_long=@(self, x) self.ident(x);
+  self.vref_ulong=@(self, x) self.ident(x);
+  self.vref_llong=@(self, x) self.ident(x);
+  self.vref_ullong=@(self, x) self.ident(x);
+  self.vref_float=@(self, x) self.ident(x);
+  self.vref_double=@(self, x) self.ident(x);
+  self.vref_char=@(self, x) self.ident(x);
+  self.vref_pchar=@(self, x) self.ident(x);
+  self.vref_pcharc=@(self, x) self.ident(x);
+  self.vref_pint=@(self, x) self.ident(x);
+  self.vref_sizet=@(self, x) self.ident(x);
+  self.vref_hello=@(self, x) self.ident(x);
+  self.vref_myint=@(self, x) self.ident(x);
+endfunction
+
+
+t = Test();
+p = OctTest();
+
+
+# internal call check
+if (t.c_check() != p.c_check())
+  error, "bad director"
+endif
+
+p.var_bool = p.stc_bool;
+p.var_schar = p.stc_schar;
+p.var_uchar = p.stc_uchar;
+p.var_int = p.stc_int;
+p.var_uint = p.stc_uint;
+p.var_short = p.stc_short;
+p.var_ushort = p.stc_ushort;
+p.var_long = p.stc_long;
+p.var_ulong = p.stc_ulong;
+p.var_llong = p.stc_llong;
+p.var_ullong = p.stc_ullong;
+p.var_char = p.stc_char;
+p.var_pchar = sct_pchar;
+p.var_pcharc = sct_pcharc;
+p.var_pint = sct_pint;
+p.var_sizet = sct_sizet;
+p.var_hello = sct_hello;
+p.var_myint = sct_myint;
+p.var_namet = def_namet;
+p.var_parami = sct_parami;
+p.var_paramd = sct_paramd;
+p.var_paramc = sct_paramc;
+
+p.v_check();
+
+t.var_bool = t.stc_bool;
+t.var_schar = t.stc_schar;
+t.var_uchar = t.stc_uchar;
+t.var_int = t.stc_int;
+t.var_uint = t.stc_uint;
+t.var_short = t.stc_short;
+t.var_ushort = t.stc_ushort;
+t.var_long = t.stc_long;
+t.var_ulong = t.stc_ulong;
+t.var_llong = t.stc_llong;
+t.var_ullong = t.stc_ullong;
+t.var_char = t.stc_char;
+t.var_pchar = sct_pchar;
+t.var_pcharc = sct_pcharc;
+t.var_pint = sct_pint;
+t.var_sizet = sct_sizet;
+t.var_hello = sct_hello;
+t.var_myint = sct_myint;
+t.var_namet = def_namet;
+t.var_parami = sct_parami;
+t.var_paramd = sct_paramd;
+t.var_paramc = sct_paramc;
+
+t.v_check();
+
+# this value contains a '0' char!
+if (def_namet != 'ho\0la')
+  error
+endif
+
+t.var_namet = def_namet;
+if (t.var_namet != def_namet)
+  error
+endif
+
+t.var_namet = 'holac';
+
+if (t.var_namet != 'holac')
+  error
+endif
+
+t.var_namet = 'hol';
+
+if (t.var_namet != 'hol')
+  error
+endif
+
+if (t.strlen('hile') != 4)
+  error
+endif
+
+if (t.strlen('hil\0') != 4)
+  error
+endif
+
+cvar.var_char = '\0';
+if (cvar.var_char != '\0')
+  error
+endif
+  
+cvar.var_char = 0;
+if (cvar.var_char != '\0')
+  error
+endif
+
+cvar.var_namet = '\0';
+if (cvar.var_namet != '')
+  error
+endif
+
+cvar.var_namet = '';
+if (cvar.var_namet != '')
+  error, "bad char empty case"
+endif
+
+cvar.var_pchar = None;
+if (cvar.var_pchar != None)
+  error, "bad None case"
+endif
+
+cvar.var_pchar = '';
+if (cvar.var_pchar != '')
+  error
+endif
+
+cvar.var_pcharc = None;
+if (cvar.var_pcharc != None)
+  error
+endif
+
+cvar.var_pcharc = '';
+if (cvar.var_pcharc != '')
+  error
+endif
+
+#
+# creating a raw char*
+#
+pc = new_pchar(5);
+pchar_setitem(pc, 0, 'h');
+pchar_setitem(pc, 1, 'o');
+pchar_setitem(pc, 2, 'l');
+pchar_setitem(pc, 3, 'a');
+pchar_setitem(pc, 4, 0);
+
+
+if (t.strlen(pc) != 4)
+  error
+endif
+
+cvar.var_pchar = pc;
+if (cvar.var_pchar != "hola")
+  error
+endif
+
+cvar.var_namet = pc;
+if (cvar.var_namet != "hola")
+  error
+endif
+
+delete_pchar(pc);
+
+#
+# Now when things should fail
+#
+
+try
+  error = 0;
+  a = t.var_uchar;
+  t.var_uchar = 10000;
+  err = 1;
+catch
+  if (a != t.var_uchar)
+    err = 1;
+  endif
+end_try_catch
+
+if (err)
+  error
+endif
+
+try
+  err = 0;
+  a = t.var_char;
+  t.var_char = '23';
+  err = 1;
+catch
+  if (a != t.var_char)
+    error = 1
+  endif
+end_try_catch
+if (err)
+  error
+endif
+
+try
+  err = 0
+  a = t.var_uint
+  t.var_uint = -1
+  err = 1;
+catch
+  if a != t.var_uint:
+    err = 1;
+  endif
+end_try_catch
+if (err)
+  error
+endif
+
+#
+#
+try
+  err = 0;
+  a = t.var_namet;
+  t.var_namet = '123456';
+  err = 1;
+catch
+  if (a != t.var_namet)
+    err = 1;
+  endif
+end_try_catch
+if (err)
+  error
+endif
+
+#
+#
+#
+t2 = p.vtest(t);
+if (t.var_namet !=  t2.var_namet)
+  error
+endif
+  
+
+if (cvar.fixsize != 'ho\0la\0\0\0')
+  error
+endif
+
+cvar.fixsize = 'ho';
+if (cvar.fixsize != 'ho\0\0\0\0\0\0')
+  error
+endif
+
+
+f = Foo(3);
+f1 = fptr_val(f);
+f2 = fptr_ref(f);
+if (f1._a != f2._a)
+  error
+endif
+
+v = char_foo(1,3);
+if (v !=3)
+  error
+endif
+
+s = char_foo(1,"hello");
+if (s !="hello")
+  error
+endif
+  
+
+v = SetPos(1,3);
+if (v !=4)
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/profiletest_runme.m b/trunk/Examples/test-suite/octave/profiletest_runme.m
new file mode 100644
index 0000000..d4f07dc
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/profiletest_runme.m
@@ -0,0 +1,32 @@
+import _profiletest       
+import profiletest       
+
+a = profiletest.A()
+print a
+print a.this
+
+b = profiletest.B()
+fn = b.fn
+i = 50000
+while i:
+  a = fn(a) #1
+  a = fn(a) #2
+  a = fn(a) #3
+  a = fn(a) #4
+  a = fn(a) #5
+  a = fn(a) #6
+  a = fn(a) #7
+  a = fn(a) #8
+  a = fn(a) #9
+  a = fn(a) #10
+  a = fn(a) #1
+  a = fn(a) #2
+  a = fn(a) #3
+  a = fn(a) #4
+  a = fn(a) #5
+  a = fn(a) #6
+  a = fn(a) #7
+  a = fn(a) #8
+  a = fn(a) #9
+  a = fn(a) #20
+  i -= 1
diff --git a/trunk/Examples/test-suite/octave/refcount_runme.m b/trunk/Examples/test-suite/octave/refcount_runme.m
new file mode 100644
index 0000000..3ce5bcd
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/refcount_runme.m
@@ -0,0 +1,15 @@
+refcount
+#
+# very innocent example
+#
+
+a = A3();
+b1 = B(a);
+b2 = B.create(a);
+
+
+if (a.ref_count() != 3)
+  error("This program will crash... now")
+endif
+
+
diff --git a/trunk/Examples/test-suite/octave/reference_global_vars_runme.m b/trunk/Examples/test-suite/octave/reference_global_vars_runme.m
new file mode 100644
index 0000000..67ad9c5
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/reference_global_vars_runme.m
@@ -0,0 +1,91 @@
+reference_global_vars
+
+# const class reference variable
+if (getconstTC().num != 33)
+    error
+endif
+
+# primitive reference variables
+cvar.var_bool = createref_bool(false);
+if (value_bool(cvar.var_bool) != 0)
+    error
+endif
+
+cvar.var_bool = createref_bool(true);
+if (value_bool(cvar.var_bool) != 1)
+    error
+endif
+
+cvar.var_char = createref_char('w');
+if (!strcmp(value_char(cvar.var_char),'w'))
+    error
+endif
+
+cvar.var_unsigned_char = createref_unsigned_char(10);
+if (value_unsigned_char(cvar.var_unsigned_char) != 10)
+    error
+endif
+
+cvar.var_signed_char = createref_signed_char(10);
+if (value_signed_char(cvar.var_signed_char) != 10)
+    error
+endif
+
+cvar.var_short = createref_short(10);
+if (value_short(cvar.var_short) != 10)
+    error
+endif
+
+cvar.var_unsigned_short = createref_unsigned_short(10);
+if (value_unsigned_short(cvar.var_unsigned_short) != 10)
+    error
+endif
+
+cvar.var_int = createref_int(10);
+if (value_int(cvar.var_int) != 10)
+    error
+endif
+
+cvar.var_unsigned_int = createref_unsigned_int(10);
+if (value_unsigned_int(cvar.var_unsigned_int) != 10)
+    error
+endif
+
+cvar.var_long = createref_long(10);
+if (value_long(cvar.var_long) != 10)
+    error
+endif
+
+cvar.var_unsigned_long = createref_unsigned_long(10);
+if (value_unsigned_long(cvar.var_unsigned_long) != 10)
+    error
+endif
+
+cvar.var_long_long = createref_long_long(int64(0x6FFFFFFFFFFFFFF8));
+if (value_long_long(cvar.var_long_long) != int64(0x6FFFFFFFFFFFFFF8))
+    error
+endif
+
+#ull = abs(0xFFFFFFF2FFFFFFF0)
+ull = uint64(55834574864);
+cvar.var_unsigned_long_long = createref_unsigned_long_long(ull);
+if (value_unsigned_long_long(cvar.var_unsigned_long_long) != ull)
+    error
+endif
+
+cvar.var_float = createref_float(10.5);
+if (value_float(cvar.var_float) != 10.5)
+    error
+endif
+
+cvar.var_double = createref_double(10.5);
+if (value_double(cvar.var_double) != 10.5)
+    error
+endif
+
+# class reference variable
+cvar.var_TestClass = createref_TestClass(TestClass(20));
+if (value_TestClass(cvar.var_TestClass).num != 20)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/rename_scope_runme.m b/trunk/Examples/test-suite/octave/rename_scope_runme.m
new file mode 100644
index 0000000..154f99d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/rename_scope_runme.m
@@ -0,0 +1,15 @@
+rename_scope
+
+a = Natural_UP();
+b = Natural_BP();
+
+if (a.rtest() != 1)
+    error
+endif
+
+if (b.rtest() != 1)
+    error
+endif
+
+f = @equals;
+
diff --git a/trunk/Examples/test-suite/octave/ret_by_value_runme.m b/trunk/Examples/test-suite/octave/ret_by_value_runme.m
new file mode 100644
index 0000000..d17c9f2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/ret_by_value_runme.m
@@ -0,0 +1,10 @@
+ret_by_value
+
+a = ret_by_value.get_test();
+if (a.myInt != 100)
+    error
+endif
+
+if (a.myShort != 200)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/return_const_value_runme.m b/trunk/Examples/test-suite/octave/return_const_value_runme.m
new file mode 100644
index 0000000..1219c92
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/return_const_value_runme.m
@@ -0,0 +1,11 @@
+return_const_value
+
+p = return_const_value.Foo_ptr.getPtr();
+if (p.getVal() != 17)
+  error("Runtime test1 faild. p.getVal()=", p.getVal())
+endif
+
+p = return_const_value.Foo_ptr.getConstPtr();
+if (p.getVal() != 17)
+  error("Runtime test2 faild. p.getVal()=", p.getVal())
+endif
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_extend_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_extend_runme.m
new file mode 100644
index 0000000..c30cd9f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_extend_runme.m
@@ -0,0 +1,41 @@
+smart_pointer_extend
+
+f = Foo();
+b = Bar(f);
+
+if (b.extension() != f.extension())
+  error
+endif
+
+
+b = CBase();
+d = CDerived();
+p = CPtr();
+
+if (b.bar() != p.bar())
+  error
+endif
+
+if (d.foo() != p.foo())
+  error
+endif
+
+if (b.hello() != p.hello())
+  error
+endif
+
+
+
+d = DFoo();
+
+dp = DPtrFoo(d);
+
+if (d.SExt(1) != dp.SExt(1))
+  error
+endif
+
+if (d.Ext(1) != dp.Ext(1))
+  error
+endif
+
+  
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_member_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_member_runme.m
new file mode 100644
index 0000000..30251c3
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_member_runme.m
@@ -0,0 +1,39 @@
+smart_pointer_member
+
+f = Foo();
+f.y = 1;
+
+if (f.y != 1)
+  error
+endif
+
+b = Bar(f);
+b.y = 2;
+
+if (f.y != 2)
+  error("f.y = %i, b.y = %i",f.y,b.y)
+endif
+
+if (swig_this(b.x) != swig_this(f.x))
+  error
+endif
+
+if (b.z != f.z)
+  error
+endif
+
+try
+  if (Foo.z == Bar.z)
+    error
+  endif
+    error
+catch
+end_try_catch
+
+  
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_multi_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_multi_runme.m
new file mode 100644
index 0000000..71ef910
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_multi_runme.m
@@ -0,0 +1,17 @@
+smart_pointer_multi
+
+f = Foo();
+b = Bar(f);
+s = Spam(b);
+g = Grok(b);
+
+s.x = 3;
+if (s.getx() != 3)
+    error
+endif
+
+g.x = 4;
+if (g.getx() != 4)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m
new file mode 100644
index 0000000..4b77e0e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_multi_typedef_runme.m
@@ -0,0 +1,18 @@
+smart_pointer_multi_typedef
+
+f = Foo();
+b = Bar(f);
+s = Spam(b);
+g = Grok(b);
+
+s.x = 3;
+if (s.getx() != 3)
+    error
+endif
+
+g.x = 4;
+if (g.getx() != 4)
+    error
+endif
+
+
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_not_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_not_runme.m
new file mode 100644
index 0000000..8b3fea8
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_not_runme.m
@@ -0,0 +1,42 @@
+smart_pointer_not
+
+f = Foo();
+b = Bar(f);
+s = Spam(f);
+g = Grok(f);
+
+try
+    x = b.x;
+    error("Error! b.x")
+catch
+end_try_catch
+
+try
+    x = s.x;
+    error("Error! s.x")
+catch
+end_try_catch
+
+try
+    x = g.x;
+    error("Error! g.x")
+catch
+end_try_catch
+
+try
+    x = b.getx();
+    error("Error! b.getx()")
+catch
+end_try_catch
+
+try
+    x = s.getx();
+    error("Error! s.getx()")
+catch
+end_try_catch
+
+try
+    x = g.getx();
+    error("Error! g.getx()")
+catch
+end_try_catch
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_overload_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_overload_runme.m
new file mode 100644
index 0000000..214437d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_overload_runme.m
@@ -0,0 +1,27 @@
+smart_pointer_overload
+
+f = Foo();
+b = Bar(f);
+
+
+if (f.test(3) != 1)
+    error
+endif
+if (f.test(3.5) != 2)
+    error
+endif
+if (f.test("hello") != 3)
+    error
+endif
+
+if (b.test(3) != 1)
+    error
+endif
+if (b.test(3.5) != 2)
+    error
+endif
+if (b.test("hello") != 3)
+    error
+endif
+
+
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_rename_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_rename_runme.m
new file mode 100644
index 0000000..260ee3e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_rename_runme.m
@@ -0,0 +1,17 @@
+smart_pointer_rename
+
+f = Foo();
+b = Bar(f);
+
+if (b.test() != 3)
+    error
+endif
+
+if (b.ftest1(1) != 1)
+    error
+endif
+
+if (b.ftest2(2,3) != 2)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_simple_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_simple_runme.m
new file mode 100644
index 0000000..26f32e0
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_simple_runme.m
@@ -0,0 +1,15 @@
+smart_pointer_simple
+
+f = Foo();
+b = Bar(f);
+
+b.x = 3;
+if (b.getx() != 3)
+    error
+endif
+
+fp = b.__deref__();
+fp.x = 4;
+if (fp.getx() != 4)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m
new file mode 100644
index 0000000..4884fa2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_templatevariables_runme.m
@@ -0,0 +1,19 @@
+smart_pointer_templatevariables
+
+d = DiffImContainerPtr_D(create(1234, 5678));
+
+if (d.id != 1234)
+  error
+endif
+#if (d.xyz != 5678):
+#  error
+
+d.id = 4321;
+#d.xyz = 8765
+
+if (d.id != 4321)
+  error
+endif
+#if (d.xyz != 8765):
+#  error
+
diff --git a/trunk/Examples/test-suite/octave/smart_pointer_typedef_runme.m b/trunk/Examples/test-suite/octave/smart_pointer_typedef_runme.m
new file mode 100644
index 0000000..8fa6ca2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/smart_pointer_typedef_runme.m
@@ -0,0 +1,15 @@
+smart_pointer_typedef
+
+f = Foo();
+b = Bar(f);
+
+b.x = 3;
+if (b.getx() != 3)
+    error
+endif
+
+fp = b.__deref__();
+fp.x = 4;
+if (fp.getx() != 4)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/sneaky1_runme.m b/trunk/Examples/test-suite/octave/sneaky1_runme.m
new file mode 100644
index 0000000..e044370
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/sneaky1_runme.m
@@ -0,0 +1,5 @@
+sneaky1
+x = sneaky1.add(3,4);
+y = sneaky1.subtract(3,4);
+z = sneaky1.mul(3,4);
+w = sneaky1.divide(3,4);
diff --git a/trunk/Examples/test-suite/octave/static_const_member_2_runme.m b/trunk/Examples/test-suite/octave/static_const_member_2_runme.m
new file mode 100644
index 0000000..b242bfc
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/static_const_member_2_runme.m
@@ -0,0 +1,18 @@
+static_const_member_2
+
+c = Test_int();
+try
+    a = c.forward_field;
+    a = c.current_profile;
+    a = c.RightIndex;
+    a = Test_int.backward_field;
+    a = Test_int.LeftIndex;
+    a = Test_int.cavity_flags;
+catch
+end_try_catch
+
+
+if (Foo.BAZ.val != 2*Foo.BAR.val)
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/std_containers_runme.m b/trunk/Examples/test-suite/octave/std_containers_runme.m
new file mode 100644
index 0000000..074f0fd
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/std_containers_runme.m
@@ -0,0 +1,135 @@
+std_containers
+
+
+cube = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
+
+icube = std_containers.cident(cube);
+for i=len(cube),
+  if (cube{i} != icube{i})
+    error("bad cident")
+  endif
+endfor
+
+
+p = {1,2};
+if (p != std_containers.pident(p))
+  error("bad pident")
+endif
+
+v = {1,2,3,4,5,6};
+iv = std_containers.vident(v);
+for i=0:len(v),
+  if (v{i} != iv{i})
+    error("bad vident")
+  endif
+endfor
+
+
+iv = std_containers.videntu(v);
+for i=0:len(v),
+  if (v{i} != iv{i})
+    error("bad videntu")
+  endif
+endfor
+
+
+vu = std_containers.vector_ui(v);
+if (vu{2} != std_containers.videntu(vu){2})
+  error("bad videntu")
+endif
+  
+
+if (v(0:3)(1) != vu(0:3)(1))
+  error("bad getslice")
+endif
+  
+
+m = {[1,2,3],[2,3],[3,4]};
+im = std_containers.midenti(m);
+
+for i=0:len(m),
+  for j=0:len(m(i)),
+    if (m(i)(j) != im(i)(j))
+      error("bad getslice")
+    endif
+  endfor
+endfor
+
+m = {[1,0,1],[1,1],[1,1]};
+im = std_containers.midentb(m);
+for i=0:len(m),
+  for j in range(0,len(m[i])):
+    if (m(i)(j) != im(i)(j))
+      error("bad getslice")
+    endif
+  endfor
+endfor
+
+
+mi = std_containers.imatrix(m);
+mc = std_containers.cmatrix(m);
+if (mi(0)(1) != mc(0)(1))
+  error("bad matrix")
+endif
+
+
+map ={};
+map{'hello'} = 1;
+map{'hi'} = 2;
+map{'3'} = 2;
+
+imap = std_containers.mapident(map);
+for k in map,
+  if (map(k) != imap(k))
+    error("bad map")
+  endif
+endfor
+
+
+mapc ={};
+c1 = std_containers.C();
+c2 = std_containers.C();
+mapc(1) = swig_this(c1);
+mapc(2) = c2;
+
+std_containers.mapidentc(mapc);
+
+
+vi = std_containers.vector_i([2,2,3,4]);
+
+
+v = [1,2];
+v1 = std_containers.v_inout(vi);
+vi(1), v1(1);
+
+[v1,v2] = std_containers.v_inout2(v1,v2);
+
+a1 = std_containers.A(1);
+a2 = std_containers.A(2);
+
+p1 = {1,a1};
+p2 = {2,a2};
+v = (p1,p2);
+v2= std_containers.pia_vident(v);
+
+v2(0)(1).a;
+v2(1)(1).a;
+
+v3 = std_containers.vector_piA(v2);
+
+v3(0)(1).a;
+v3(1)(1).a;
+
+s = std_containers.set_i();
+s.append(1);
+s.append(2);
+s.append(3);
+j=1;
+for i in s,
+  if (i != j)
+    error
+  endif
+  j = j + 1;
+endfor
+
+
diff --git a/trunk/Examples/test-suite/octave/struct_rename_runme.m b/trunk/Examples/test-suite/octave/struct_rename_runme.m
new file mode 100644
index 0000000..1b57d8f
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/struct_rename_runme.m
@@ -0,0 +1,4 @@
+struct_rename
+
+b = struct_rename.Bar();
+
diff --git a/trunk/Examples/test-suite/octave/struct_value_runme.m b/trunk/Examples/test-suite/octave/struct_value_runme.m
new file mode 100644
index 0000000..7340a36
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/struct_value_runme.m
@@ -0,0 +1,13 @@
+struct_value
+
+b = struct_value.Bar();
+
+b.a.x = 3;
+if (b.a.x != 3)
+  error
+endif
+
+b.b.x = 3;
+if (b.b.x != 3)
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/swigobject_runme.m b/trunk/Examples/test-suite/octave/swigobject_runme.m
new file mode 100644
index 0000000..614e2a4
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/swigobject_runme.m
@@ -0,0 +1,28 @@
+swigobject
+
+a = A();
+
+a1 = a_ptr(a);
+a2 = a_ptr(a);
+
+if (swig_this(a1) != swig_this(a2))
+  error
+endif
+  
+
+lthis = uint64(swig_this(a.this));
+xstr1 = printf("0x%x",lthis);
+xstr2 = pointer_str(a);
+
+if (xstr1 != xstr2)
+  error
+endif
+
+s = str(a.this);
+r = repr(a.this);
+
+v1 = v_ptr(a);
+v2 = v_ptr(a);
+if (uint64(v1) != uint64(v2))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/template_construct_runme.m b/trunk/Examples/test-suite/octave/template_construct_runme.m
new file mode 100644
index 0000000..2ed0664
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_construct_runme.m
@@ -0,0 +1 @@
+template_construct
diff --git a/trunk/Examples/test-suite/octave/template_default_arg_runme.m b/trunk/Examples/test-suite/octave/template_default_arg_runme.m
new file mode 100644
index 0000000..e500662
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_default_arg_runme.m
@@ -0,0 +1,117 @@
+template_default_arg
+
+
+helloInt = template_default_arg.Hello_int();
+helloInt.foo(template_default_arg.Hello_int_hi);
+
+
+x = template_default_arg.X_int();
+if (x.meth(20.0, 200) != 200)
+  error("X_int test 1 failed")
+endif
+if (x.meth(20) != 20)
+  error("X_int test 2 failed")
+endif
+if (x.meth() != 0)
+  error("X_int test 3 failed")
+endif
+
+
+
+y = template_default_arg.Y_unsigned();
+if (y.meth(20.0, 200) != 200)
+  error("Y_unsigned test 1 failed")
+endif
+if (y.meth(20) != 20)
+  error("Y_unsigned test 2 failed")
+endif
+if (y.meth() != 0)
+  error("Y_unsigned test 3 failed")
+endif
+
+
+
+x = template_default_arg.X_longlong();
+x = template_default_arg.X_longlong(20.0);
+x = template_default_arg.X_longlong(20.0, 200);
+
+
+x = template_default_arg.X_int();
+x = template_default_arg.X_int(20.0);
+x = template_default_arg.X_int(20.0, 200);
+
+
+x = template_default_arg.X_hello_unsigned();
+x = template_default_arg.X_hello_unsigned(20.0);
+x = template_default_arg.X_hello_unsigned(20.0, template_default_arg.Hello_int());
+
+
+y = template_default_arg.Y_hello_unsigned();
+y.meth(20.0, template_default_arg.Hello_int());
+y.meth(template_default_arg.Hello_int());
+y.meth();
+
+
+
+fz = template_default_arg.Foo_Z_8();
+x = template_default_arg.X_Foo_Z_8();
+fzc = x.meth(fz);
+
+
+# Templated functions
+
+# plain function: int ott(Foo<int>)
+if (template_default_arg.ott(template_default_arg.Foo_int()) != 30)
+  error("ott test 1 failed")
+endif
+
+# %template(ott) ott<int, int>
+if (template_default_arg.ott() != 10)
+  error("ott test 2 failed")
+endif
+if (template_default_arg.ott(1) != 10)
+  error("ott test 3 failed")
+endif
+if (template_default_arg.ott(1, 1) != 10)
+  error("ott test 4 failed")
+endif
+
+if (template_default_arg.ott("hi") != 20)
+  error("ott test 5 failed")
+endif
+if (template_default_arg.ott("hi", 1) != 20)
+  error("ott test 6 failed")
+endif
+if (template_default_arg.ott("hi", 1, 1) != 20)
+  error("ott test 7 failed")
+endif
+
+# %template(ott) ott<const char *>
+if (template_default_arg.ottstring(template_default_arg.Hello_int(), "hi") != 40)
+  error("ott test 8 failed")
+endif
+
+if (template_default_arg.ottstring(template_default_arg.Hello_int()) != 40)
+  error("ott test 9 failed")
+endif
+
+# %template(ott) ott<int>
+if (template_default_arg.ottint(template_default_arg.Hello_int(), 1) != 50)
+  error("ott test 10 failed")
+endif
+
+if (template_default_arg.ottint(template_default_arg.Hello_int()) != 50)
+  error("ott test 11 failed")
+endif
+
+# %template(ott) ott<double>
+if (template_default_arg.ott(template_default_arg.Hello_int(), 1.0) != 60)
+  error("ott test 12 failed")
+endif
+
+if (template_default_arg.ott(template_default_arg.Hello_int()) != 60)
+  error("ott test 13 failed")
+endif
+
+
+
diff --git a/trunk/Examples/test-suite/octave/template_extend1_runme.m b/trunk/Examples/test-suite/octave/template_extend1_runme.m
new file mode 100644
index 0000000..e672da7
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_extend1_runme.m
@@ -0,0 +1,12 @@
+template_extend1
+
+a = template_extend1.lBaz();
+b = template_extend1.dBaz();
+
+if (!strcmp(a.foo(),"lBaz::foo"))
+    error
+endif
+
+if (!strcmp(b.foo(),"dBaz::foo"))
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/template_extend2_runme.m b/trunk/Examples/test-suite/octave/template_extend2_runme.m
new file mode 100644
index 0000000..93c44d7
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_extend2_runme.m
@@ -0,0 +1,12 @@
+template_extend2
+
+a = template_extend2.lBaz();
+b = template_extend2.dBaz();
+
+if (!strcmp(a.foo(),"lBaz::foo"))
+    error
+endif
+
+if (!strcmp(b.foo(),"dBaz::foo"))
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/template_inherit_runme.m b/trunk/Examples/test-suite/octave/template_inherit_runme.m
new file mode 100644
index 0000000..ce7931e
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_inherit_runme.m
@@ -0,0 +1,68 @@
+template_inherit
+a = FooInt();
+b = FooDouble();
+c = BarInt();
+d = BarDouble();
+e = FooUInt();
+f = BarUInt();
+
+if (!strcmp(a.blah(),"Foo"))
+    error
+endif
+
+if (!strcmp(b.blah(),"Foo"))
+    error
+endif
+
+if (!strcmp(e.blah(),"Foo"))
+    error
+endif
+
+if (!strcmp(c.blah(),"Bar"))
+    error
+endif
+
+if (!strcmp(d.blah(),"Bar"))
+    error
+endif
+
+if (!strcmp(f.blah(),"Bar"))
+    error
+endif
+
+if (!strcmp(c.foomethod(),"foomethod"))
+    error
+endif
+
+if (!strcmp(d.foomethod(),"foomethod"))
+    error
+endif
+
+if (!strcmp(f.foomethod(),"foomethod"))
+    error
+endif
+
+if (!strcmp(invoke_blah_int(a),"Foo"))
+    error
+endif
+
+if (!strcmp(invoke_blah_int(c),"Bar"))
+    error
+endif
+
+if (!strcmp(invoke_blah_double(b),"Foo"))
+    error
+endif
+
+if (!strcmp(invoke_blah_double(d),"Bar"))
+    error
+endif
+
+if (!strcmp(invoke_blah_uint(e),"Foo"))
+    error
+endif
+
+if (!strcmp(invoke_blah_uint(f),"Bar"))
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/template_matrix_runme.m b/trunk/Examples/test-suite/octave/template_matrix_runme.m
new file mode 100644
index 0000000..b8fb3d3
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_matrix_runme.m
@@ -0,0 +1,6 @@
+template_matrix
+passVector([1,2,3]);
+passMatrix({[1,2],[1,2,3]});
+passCube({{[1,2],[1,2,3]},{[1,2],[1,2,3]}});
+
+
diff --git a/trunk/Examples/test-suite/octave/template_ns4_runme.m b/trunk/Examples/test-suite/octave/template_ns4_runme.m
new file mode 100644
index 0000000..58ced7c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_ns4_runme.m
@@ -0,0 +1,6 @@
+template_ns4
+
+d = make_Class_DD();
+if (!strcmp(d.test(),"test"))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/template_ns_runme.m b/trunk/Examples/test-suite/octave/template_ns_runme.m
new file mode 100644
index 0000000..29a2f53
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_ns_runme.m
@@ -0,0 +1,21 @@
+template_ns
+p1 = pairii(2,3);
+p2 = pairii(p1);
+
+if (p2.first != 2)
+    error
+endif
+if (p2.second != 3)
+    error
+endif
+
+p3 = pairdd(3.5,2.5);
+p4 = pairdd(p3);
+
+if (p4.first != 3.5)
+    error
+endif
+
+if (p4.second != 2.5)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/template_opaque_runme.m b/trunk/Examples/test-suite/octave/template_opaque_runme.m
new file mode 100644
index 0000000..1c123b3
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_opaque_runme.m
@@ -0,0 +1,7 @@
+template_opaque
+
+v = template_opaque.OpaqueVectorType(10);
+
+template_opaque.FillVector(v);
+
+
diff --git a/trunk/Examples/test-suite/octave/template_ref_type_runme.m b/trunk/Examples/test-suite/octave/template_ref_type_runme.m
new file mode 100644
index 0000000..ef77e06
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_ref_type_runme.m
@@ -0,0 +1,5 @@
+template_ref_type
+
+xr = template_ref_type.XC();
+y  = template_ref_type.Y();
+y.find(xr);
diff --git a/trunk/Examples/test-suite/octave/template_rename_runme.m b/trunk/Examples/test-suite/octave/template_rename_runme.m
new file mode 100644
index 0000000..7cb5493
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_rename_runme.m
@@ -0,0 +1,12 @@
+template_rename
+
+i = template_rename.iFoo();
+d = template_rename.dFoo();
+
+a = i.blah_test(4);
+b = i.spam_test(5);
+c = i.groki_test(6);
+
+x = d.blah_test(7);
+y = d.spam(8);
+z = d.grok_test(9);
diff --git a/trunk/Examples/test-suite/octave/template_static_runme.m b/trunk/Examples/test-suite/octave/template_static_runme.m
new file mode 100644
index 0000000..c54139a
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_static_runme.m
@@ -0,0 +1,3 @@
+template_static
+
+Foo_bar_double(1);
diff --git a/trunk/Examples/test-suite/octave/template_tbase_template_runme.m b/trunk/Examples/test-suite/octave/template_tbase_template_runme.m
new file mode 100644
index 0000000..da8ec4c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_tbase_template_runme.m
@@ -0,0 +1,6 @@
+template_tbase_template
+
+a = make_Class_dd();
+if (!strcmp(a.test(),"test"))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/template_type_namespace_runme.m b/trunk/Examples/test-suite/octave/template_type_namespace_runme.m
new file mode 100644
index 0000000..bbdcdef
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_type_namespace_runme.m
@@ -0,0 +1,5 @@
+template_type_namespace
+
+assert(strcmp(foo()(1),"foo"));
+
+                                  
diff --git a/trunk/Examples/test-suite/octave/template_typedef_cplx2_runme.m b/trunk/Examples/test-suite/octave/template_typedef_cplx2_runme.m
new file mode 100644
index 0000000..94d3beb
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_typedef_cplx2_runme.m
@@ -0,0 +1,103 @@
+template_typedef_cplx2
+
+#
+# double case
+#
+
+try
+  d = make_Identity_double();
+  a = swig_this(d);
+catch
+  d
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(d)) != 1)
+  d
+  error("is not an ArithUnaryFunction")
+  error
+endif
+
+try
+  e = make_Multiplies_double_double_double_double(d, d);
+  a = swig_this(e);
+catch
+  e
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(e)) != 1)
+  e
+  error("is not an ArithUnaryFunction")
+endif
+
+
+#
+# complex case
+#
+
+try
+  c = make_Identity_complex();
+  a = swig_this(c);
+catch
+  c
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(c)) != 1)
+  c
+  error("is not an ArithUnaryFunction")
+endif
+
+try
+  f = make_Multiplies_complex_complex_complex_complex(c, c);
+  a = swig_this(f);
+catch
+  f
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(f)) != 1)
+  f
+  error("is not an ArithUnaryFunction")
+endif
+
+#
+# Mix case
+#
+
+try
+  g = make_Multiplies_double_double_complex_complex(d, c);
+  a = swig_this(g);
+catch
+  g
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(g)) != 1)
+  g
+  error("is not an ArithUnaryFunction")
+  error
+endif
+
+
+try
+  h = make_Multiplies_complex_complex_double_double(c, d);
+  a = swig_this(h);
+catch
+  h
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(h)) == -1)
+  h
+  error("is not an ArithUnaryFunction")
+endif
+
+try
+  a = g.get_value();
+catch
+  error(g, "has not get_value() method")
+  error
+end_try_catch
+
diff --git a/trunk/Examples/test-suite/octave/template_typedef_cplx3_runme.m b/trunk/Examples/test-suite/octave/template_typedef_cplx3_runme.m
new file mode 100644
index 0000000..d21f279
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_typedef_cplx3_runme.m
@@ -0,0 +1,34 @@
+template_typedef_cplx3
+
+#
+# this is OK
+#
+
+
+s = Sin();
+s.get_base_value();
+s.get_value();
+s.get_arith_value();
+my_func_r(s);
+make_Multiplies_double_double_double_double(s,s);
+
+z = CSin();
+z.get_base_value();
+z.get_value();
+z.get_arith_value();
+my_func_c(z);
+make_Multiplies_complex_complex_complex_complex(z,z);
+
+#
+# Here we fail
+#
+d = make_Identity_double();
+my_func_r(d);
+
+c = make_Identity_complex();
+my_func_c(c);
+
+  
+
+
+
diff --git a/trunk/Examples/test-suite/octave/template_typedef_cplx4_runme.m b/trunk/Examples/test-suite/octave/template_typedef_cplx4_runme.m
new file mode 100644
index 0000000..4db276d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_typedef_cplx4_runme.m
@@ -0,0 +1,33 @@
+template_typedef_cplx4
+
+#
+# this is OK
+#
+
+
+s = Sin();
+s.get_base_value();
+s.get_value();
+s.get_arith_value();
+my_func_r(s);
+make_Multiplies_double_double_double_double(s,s);
+
+z = CSin();
+z.get_base_value();
+z.get_value();
+z.get_arith_value();
+my_func_c(z);
+make_Multiplies_complex_complex_complex_complex(z,z);
+
+#
+# Here we fail
+#
+d = make_Identity_double();
+my_func_r(d);
+
+c = make_Identity_complex();
+my_func_c(c);
+  
+
+
+
diff --git a/trunk/Examples/test-suite/octave/template_typedef_cplx_runme.m b/trunk/Examples/test-suite/octave/template_typedef_cplx_runme.m
new file mode 100644
index 0000000..d00981c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_typedef_cplx_runme.m
@@ -0,0 +1,92 @@
+template_typedef_cplx
+
+#
+# double case
+#
+
+try
+  d = make_Identity_double();
+  a = swig_this(d);
+catch
+  d
+  error("is not an instance")
+end_try_catch
+
+if (findstr("ArithUnaryFunction",swig_type(d)) != 1)
+  d
+  error("is not an ArithUnaryFunction")
+endif
+
+try
+  e = make_Multiplies_double_double_double_double(d, d);
+  a = swig_this(e);
+catch
+  error(e, "is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(e)) != 1);
+  c
+  error("is not an ArithUnaryFunction")
+endif
+
+
+#
+# complex case
+#
+
+try
+  c = make_Identity_complex();
+  a = swig_this(c);
+catch
+  c
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(c)) != 1)
+  c
+  error("is not an ArithUnaryFunction")
+endif
+
+try
+  f = make_Multiplies_complex_complex_complex_complex(c, c);
+  a = swig_this(f);
+catch
+  f
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(f)) != 1)
+  f
+  error("is not an ArithUnaryFunction")
+endif
+
+#
+# Mix case
+#
+
+try
+  g = make_Multiplies_double_double_complex_complex(d, c);
+  a = swig_this(g);
+catch
+  g
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(g)) != 1)
+  g
+  error("is not an ArithUnaryFunction")
+endif
+
+
+try
+  h = make_Multiplies_complex_complex_double_double(c, d);
+  a = swig_this(h);
+catch
+  h
+  error("is not an instance")
+end_try_catch
+
+if (findstr('ArithUnaryFunction',swig_type(h)) != 1)
+  h
+  error("is not an ArithUnaryFunction")
+endif
diff --git a/trunk/Examples/test-suite/octave/template_typedef_import_runme.m b/trunk/Examples/test-suite/octave/template_typedef_import_runme.m
new file mode 100644
index 0000000..0574ab1
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_typedef_import_runme.m
@@ -0,0 +1,34 @@
+template_typedef_cplx2
+template_typedef_import
+
+#
+# this is OK
+#
+
+
+s = Sin();
+s.get_base_value();
+s.get_value();
+s.get_arith_value();
+my_func_r(s);
+make_Multiplies_double_double_double_double(s,s);
+
+z = CSin();
+z.get_base_value();
+z.get_value();
+z.get_arith_value();
+my_func_c(z);
+make_Multiplies_complex_complex_complex_complex(z,z);
+
+#
+# Here we fail
+#
+d = make_Identity_double();
+my_func_r(d);
+
+c = make_Identity_complex();
+my_func_c(c);
+
+
+
+
diff --git a/trunk/Examples/test-suite/octave/template_typedef_runme.m b/trunk/Examples/test-suite/octave/template_typedef_runme.m
new file mode 100644
index 0000000..8d8af79
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/template_typedef_runme.m
@@ -0,0 +1,51 @@
+template_typedef
+
+d = make_Identity_float();
+c = make_Identity_reald();
+
+
+try
+  a = swig_this(d);
+  a = swig_this(c);
+catch
+  error
+end_try_catch
+
+try
+  e = make_Multiplies_float_float_float_float(d, d);
+  a = swig_this(e);
+catch
+  e
+  error("is not an instance")
+end_try_catch
+
+try
+  f = make_Multiplies_reald_reald_reald_reald(c, c);
+  a = swig_this(f);
+catch
+  f
+  error("is not an instance");
+end_try_catch
+
+try
+  g = make_Multiplies_float_float_reald_reald(d, c);
+  a = swig_this(g);
+catch
+  error(g, "is not an instance")
+end_try_catch
+
+
+# the old large format
+if (strcmp("<unknown>",swig_typequery("vfncs::ArithUnaryFunction<vfncs::arith_traits<float,double>::argument_type,vfncs::arith_traits<float,double >::result_type > *")))
+  error
+endif
+
+# the reduced format
+if (strcmp("<unknown>",swig_typequery("vfncs::ArithUnaryFunction<double,double> *")))
+  error
+endif
+
+# this is a bad name
+if (!strcmp("<unknown>",swig_typequery("vfncs::ArithUnaryFunction<double,doublex> *")))
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/typedef_class_runme.m b/trunk/Examples/test-suite/octave/typedef_class_runme.m
new file mode 100644
index 0000000..97d2aed
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/typedef_class_runme.m
@@ -0,0 +1,7 @@
+typedef_class
+
+a = typedef_class.RealA();
+a.a = 3;
+ 
+b = typedef_class.B();
+b.testA(a);
diff --git a/trunk/Examples/test-suite/octave/typedef_inherit_runme.m b/trunk/Examples/test-suite/octave/typedef_inherit_runme.m
new file mode 100644
index 0000000..6c4c47a
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/typedef_inherit_runme.m
@@ -0,0 +1,27 @@
+typedef_inherit
+
+a = typedef_inherit.Foo();
+b = typedef_inherit.Bar();
+
+x = typedef_inherit.do_blah(a);
+if (!strcmp(x,"Foo::blah"))
+    error("Whoa! Bad return", x)
+endif
+
+x = typedef_inherit.do_blah(b);
+if (!strcmp(x,"Bar::blah"))
+    error("Whoa! Bad return", x)
+endif
+
+c = typedef_inherit.Spam();
+d = typedef_inherit.Grok();
+
+x = typedef_inherit.do_blah2(c);
+if (!strcmp(x,"Spam::blah"))
+    error("Whoa! Bad return", x)
+endif
+
+x = typedef_inherit.do_blah2(d);
+if (!strcmp(x,"Grok::blah"))
+    error("Whoa! Bad return", x)
+endif
diff --git a/trunk/Examples/test-suite/octave/typedef_scope_runme.m b/trunk/Examples/test-suite/octave/typedef_scope_runme.m
new file mode 100644
index 0000000..9e6d101
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/typedef_scope_runme.m
@@ -0,0 +1,14 @@
+typedef_scope
+
+b = typedef_scope.Bar();
+x = b.test1(42,"hello");
+if (x != 42)
+    error("Failed!!")
+endif
+
+x = b.test2(42,"hello");
+if (!strcmp(x,"hello"))
+    error("Failed!!")
+endif
+    
+    
diff --git a/trunk/Examples/test-suite/octave/typemap_namespace_runme.m b/trunk/Examples/test-suite/octave/typemap_namespace_runme.m
new file mode 100644
index 0000000..ec62a39
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/typemap_namespace_runme.m
@@ -0,0 +1,10 @@
+typemap_namespace
+
+if (!strcmp(test1("hello"),"hello"))
+    error
+endif
+
+if (!strcmp(test2("hello"),"hello"))
+    error
+endif
+
diff --git a/trunk/Examples/test-suite/octave/typemap_ns_using_runme.m b/trunk/Examples/test-suite/octave/typemap_ns_using_runme.m
new file mode 100644
index 0000000..dd3f657
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/typemap_ns_using_runme.m
@@ -0,0 +1,5 @@
+typemap_ns_using
+
+if (typemap_ns_using.spam(37) != 37)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/typename_runme.m b/trunk/Examples/test-suite/octave/typename_runme.m
new file mode 100644
index 0000000..c47f817
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/typename_runme.m
@@ -0,0 +1,13 @@
+typename
+f = typename.Foo();
+b = typename.Bar();
+
+x = typename.twoFoo(f);
+if (x == floor(x))
+    error("Wrong return type!")
+endif
+y = typename.twoBar(b);
+if (y != floor(y))
+    error("Wrong return type!")
+endif
+    
diff --git a/trunk/Examples/test-suite/octave/types_directive_runme.m b/trunk/Examples/test-suite/octave/types_directive_runme.m
new file mode 100644
index 0000000..0757c6c
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/types_directive_runme.m
@@ -0,0 +1,15 @@
+types_directive
+
+d1 = Time1(2001, 2, 3, 60);
+newDate = add(d1, 7); # check that a Time1 instance is accepted where Date is expected
+if (newDate.day != 10)
+  error
+endif
+
+d2 = Time2(1999, 8, 7, 60);
+newDate = add(d2, 7); # check that a Time2 instance is accepted where Date is expected
+if (newDate.day != 14)
+  error
+endif
+
+
diff --git a/trunk/Examples/test-suite/octave/unions_runme.m b/trunk/Examples/test-suite/octave/unions_runme.m
new file mode 100644
index 0000000..05ac252
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/unions_runme.m
@@ -0,0 +1,49 @@
+
+# This is the union runtime testcase. It ensures that values within a 
+# union embedded within a struct can be set and read correctly.
+
+unions
+
+# Create new instances of SmallStruct and BigStruct for later use
+small = unions.SmallStruct();
+small.jill = 200;
+
+big = unions.BigStruct();
+big.smallstruct = small;
+big.jack = 300;
+
+# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+# Ensure values in EmbeddedUnionTest are set correctly for each.
+eut = unions.EmbeddedUnionTest();
+
+# First check the SmallStruct in EmbeddedUnionTest
+eut.number = 1;
+eut.uni.small = small;
+Jill1 = eut.uni.small.jill;
+if (Jill1 != 200)
+    error("Runtime test1 failed. eut.uni.small.jill=%i" , Jill1)
+endif
+
+Num1 = eut.number;
+if (Num1 != 1)
+    error("Runtime test2 failed. eut.number=%i" , Num1)
+endif
+
+# Secondly check the BigStruct in EmbeddedUnionTest
+eut.number = 2;
+eut.uni.big = big;
+Jack1 = eut.uni.big.jack;
+if (Jack1 != 300)
+    error("Runtime test3 failed. eut.uni.big.jack=%i" , Jack1)
+endif
+
+Jill2 = eut.uni.big.smallstruct.jill;
+if (Jill2 != 200)
+    error("Runtime test4 failed. eut.uni.big.smallstruct.jill=%i" , Jill2)
+endif
+
+Num2 = eut.number;
+if (Num2 != 2)
+    error("Runtime test5 failed. eut.number=%i" , Num2)
+endif
+
diff --git a/trunk/Examples/test-suite/octave/using1_runme.m b/trunk/Examples/test-suite/octave/using1_runme.m
new file mode 100644
index 0000000..0c37daf
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using1_runme.m
@@ -0,0 +1,5 @@
+using1
+
+if (using1.spam(37) != 37)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/using2_runme.m b/trunk/Examples/test-suite/octave/using2_runme.m
new file mode 100644
index 0000000..205c6d7
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using2_runme.m
@@ -0,0 +1,5 @@
+using2
+
+if (using2.spam(37) != 37)
+    error
+endif
diff --git a/trunk/Examples/test-suite/octave/using_composition_runme.m b/trunk/Examples/test-suite/octave/using_composition_runme.m
new file mode 100644
index 0000000..9b58d6d
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using_composition_runme.m
@@ -0,0 +1,43 @@
+using_composition
+
+f = FooBar();
+if (f.blah(3) != 3)
+  error("FooBar::blah(int)")
+endif
+
+if (f.blah(3.5) != 3.5)
+  error("FooBar::blah(double)")
+endif
+
+if (!strcmp(f.blah("hello"),"hello"))
+  error("FooBar::blah(char *)")
+endif
+
+
+f = FooBar2();
+if (f.blah(3) != 3)
+  error("FooBar2::blah(int)")
+endif
+
+if (f.blah(3.5) != 3.5)
+  error("FooBar2::blah(double)")
+endif
+
+if (!strcmp(f.blah("hello"),"hello"))
+  error("FooBar2::blah(char *)")
+endif
+
+
+f = FooBar3();
+if (f.blah(3) != 3)
+  error("FooBar3::blah(int)")
+endif
+
+if (f.blah(3.5) != 3.5)
+  error("FooBar3::blah(double)")
+endif
+
+if (!strcmp(f.blah("hello"),"hello"))
+  error("FooBar3::blah(char *)")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/using_extend_runme.m b/trunk/Examples/test-suite/octave/using_extend_runme.m
new file mode 100644
index 0000000..b9c13fa
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using_extend_runme.m
@@ -0,0 +1,27 @@
+using_extend
+
+f = FooBar();
+if (f.blah(3) != 3)
+    error("blah(int)")
+endif
+
+if (f.blah(3.5) != 3.5)
+    error("blah(double)")
+endif
+
+if (!strcmp(f.blah("hello"),"hello"))
+    error("blah(char *)")
+endif
+
+if (f.blah(3,4) != 7)
+    error("blah(int,int)")
+endif
+
+if (f.blah(3.5,7.5) != (3.5+7.5))
+    error("blah(double,double)")
+endif
+
+
+if (f.duh(3) != 3)
+    error("duh(int)")
+endif
diff --git a/trunk/Examples/test-suite/octave/using_inherit_runme.m b/trunk/Examples/test-suite/octave/using_inherit_runme.m
new file mode 100644
index 0000000..effd0e2
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using_inherit_runme.m
@@ -0,0 +1,61 @@
+using_inherit
+
+b = Bar();
+if (b.test(3) != 3)
+  error("Bar::test(int)")
+endif
+
+if (b.test(3.5) != 3.5)
+  error("Bar::test(double)")
+endif
+
+
+b = Bar2();
+if (b.test(3) != 6)
+  error("Bar2::test(int)")
+endif
+
+if (b.test(3.5) != 7.0)
+  error("Bar2::test(double)")
+endif
+
+
+b = Bar3();
+if (b.test(3) != 6)
+  error("Bar3::test(int)")
+endif
+
+if (b.test(3.5) != 7.0)
+  error("Bar3::test(double)")
+endif
+
+
+b = Bar4();
+if (b.test(3) != 6)
+  error("Bar4::test(int)")
+endif
+
+if (b.test(3.5) != 7.0)
+  error("Bar4::test(double)")
+endif
+
+
+b = Fred1();
+if (b.test(3) != 3)
+  error("Fred1::test(int)")
+endif
+
+if (b.test(3.5) != 7.0)
+  error("Fred1::test(double)")
+endif
+
+
+b = Fred2();
+if (b.test(3) != 3)
+  error("Fred2::test(int)")
+endif
+
+if (b.test(3.5) != 7.0)
+  error("Fred2::test(double)")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/using_private_runme.m b/trunk/Examples/test-suite/octave/using_private_runme.m
new file mode 100644
index 0000000..3ac71db
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using_private_runme.m
@@ -0,0 +1,16 @@
+using_private
+
+f = FooBar();
+f.x = 3;
+
+if (f.blah(4) != 4)
+    error, "blah(int)"
+endif
+
+if (f.defaulted() != -1)
+    error, "defaulted()"
+endif
+
+if (f.defaulted(222) != 222)
+    error, "defaulted(222)"
+endif
diff --git a/trunk/Examples/test-suite/octave/using_protected_runme.m b/trunk/Examples/test-suite/octave/using_protected_runme.m
new file mode 100644
index 0000000..ed4b1c3
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/using_protected_runme.m
@@ -0,0 +1,8 @@
+using_protected
+
+f = FooBar();
+f.x = 3;
+
+if (f.blah(4) != 4)
+    error("blah(int)")
+endif
diff --git a/trunk/Examples/test-suite/octave/varargs_runme.m b/trunk/Examples/test-suite/octave/varargs_runme.m
new file mode 100644
index 0000000..dcdcb24
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/varargs_runme.m
@@ -0,0 +1,23 @@
+varargs
+
+if (!strcmp(varargs.test("Hello"),"Hello"))
+    error("Failed")
+endif
+
+f = varargs.Foo("Greetings");
+if (!strcmp(f.str,"Greetings"))
+    error("Failed")
+endif
+
+if (!strcmp(f.test("Hello"),"Hello"))
+    error("Failed")
+endif
+
+
+if (!strcmp(varargs.test_def("Hello",1),"Hello"))
+    error("Failed")
+endif
+
+if (!strcmp(varargs.test_def("Hello"),"Hello"))
+    error("Failed")
+endif
diff --git a/trunk/Examples/test-suite/octave/virtual_derivation_runme.m b/trunk/Examples/test-suite/octave/virtual_derivation_runme.m
new file mode 100644
index 0000000..8ce8503
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/virtual_derivation_runme.m
@@ -0,0 +1,9 @@
+virtual_derivation
+#
+# very innocent example
+#
+b = B(3);
+if (b.get_a() != b.get_b())
+  error("something is really wrong")
+endif
+
diff --git a/trunk/Examples/test-suite/octave/virtual_poly_runme.m b/trunk/Examples/test-suite/octave/virtual_poly_runme.m
new file mode 100644
index 0000000..0c7c951
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/virtual_poly_runme.m
@@ -0,0 +1,44 @@
+virtual_poly
+
+d = virtual_poly.NDouble(3.5);
+i = virtual_poly.NInt(2);
+
+#
+# the copy methods return the right polymorphic types
+# 
+dc = d.copy();
+ic = i.copy();
+
+if (d.get() != dc.get())
+  error
+endif
+
+if (i.get() != ic.get())
+  error
+endif
+
+virtual_poly.incr(ic);
+
+if ((i.get() + 1) != ic.get())
+  error
+endif
+
+
+dr = d.ref_this();
+if (d.get() != dr.get())
+  error
+endif
+
+
+#
+# 'narrowing' also works
+#
+ddc = virtual_poly.NDouble_narrow(d.nnumber());
+if (d.get() != ddc.get())
+  error
+endif
+
+dic = virtual_poly.NInt_narrow(i.nnumber());
+if (i.get() != dic.get())
+  error
+endif
diff --git a/trunk/Examples/test-suite/octave/voidtest_runme.m b/trunk/Examples/test-suite/octave/voidtest_runme.m
new file mode 100644
index 0000000..e62f8a5
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/voidtest_runme.m
@@ -0,0 +1,38 @@
+voidtest
+
+voidtest.globalfunc();
+f = voidtest.Foo();
+f.memberfunc();
+
+voidtest.Foo_staticmemberfunc();
+
+function fvoid()
+end
+
+try
+  a = f.memberfunc();
+catch
+end_try_catch
+try
+  a = fvoid();
+catch
+end_try_catch
+
+
+v1 = voidtest.vfunc1(f);
+v2 = voidtest.vfunc2(f);
+if (swig_this(v1) != swig_this(v2))
+    error
+endif
+
+v3 = voidtest.vfunc3(v1);
+if (swig_this(v3) != swig_this(f))
+    error
+endif
+v4 = voidtest.vfunc1(f);
+if (swig_this(v4) != swig_this(v1))
+    error
+endif
+
+
+v3.memberfunc();
diff --git a/trunk/Examples/test-suite/octave/wrapmacro_runme.m b/trunk/Examples/test-suite/octave/wrapmacro_runme.m
new file mode 100644
index 0000000..4f42883
--- /dev/null
+++ b/trunk/Examples/test-suite/octave/wrapmacro_runme.m
@@ -0,0 +1,8 @@
+wrapmacro
+
+a = 2;
+b = -1;
+wrapmacro.max(a,b);
+wrapmacro.max(a/7.0, -b*256);
+wrapmacro.GUINT16_SWAP_LE_BE_CONSTANT(1);
+
diff --git a/trunk/Examples/test-suite/operator_overload.i b/trunk/Examples/test-suite/operator_overload.i
new file mode 100644
index 0000000..b2748f9
--- /dev/null
+++ b/trunk/Examples/test-suite/operator_overload.i
@@ -0,0 +1,352 @@
+/* File : operator_overload.i */
+/*
+This is a test of all the possible operator overloads
+
+see bottom for a set of possible tests
+*/
+%module operator_overload
+
+#if defined(SWIGPYTHON)
+%warnfilter(SWIGWARN_IGNORE_OPERATOR_EQ,
+	    SWIGWARN_IGNORE_OPERATOR_INDEX,
+	    SWIGWARN_IGNORE_OPERATOR_PLUSPLUS,
+	    SWIGWARN_IGNORE_OPERATOR_MINUSMINUS,
+	    SWIGWARN_IGNORE_OPERATOR_LAND,
+	    SWIGWARN_IGNORE_OPERATOR_LOR);
+#endif
+
+#if !defined(SWIGLUA) && !defined(SWIGR)
+%rename(Equal) operator =;
+%rename(PlusEqual) operator +=;
+%rename(MinusEqual) operator -=;
+%rename(MultiplyEqual) operator *=;
+%rename(DivideEqual) operator /=;
+%rename(PercentEqual) operator %=;
+%rename(Plus) operator +;
+%rename(Minus) operator -;
+%rename(Multiply) operator *;
+%rename(Divide) operator /;
+%rename(Percent) operator %;
+%rename(Not) operator !;
+%rename(IndexIntoConst) operator[](unsigned idx) const;
+%rename(IndexInto) operator[](unsigned idx);
+%rename(Functor) operator ();
+%rename(EqualEqual) operator ==;
+%rename(NotEqual) operator !=;
+%rename(LessThan) operator <;
+%rename(LessThanEqual) operator <=;
+%rename(GreaterThan) operator >;
+%rename(GreaterThanEqual) operator >=;
+%rename(And) operator &&;
+%rename(Or) operator ||;
+%rename(PlusPlusPrefix) operator++();
+%rename(PlusPlusPostfix) operator++(int);
+%rename(MinusMinusPrefix) operator--();
+%rename(MinusMinusPostfix) operator--(int);
+#endif
+
+#ifdef SWIGCSHARP
+%csmethodmodifiers operator++() "protected";
+%csmethodmodifiers operator++(int) "private";
+%csmethodmodifiers operator--() "private";
+%csmethodmodifiers operator--(int) "protected";
+%typemap(cscode) Op %{
+  public static Op operator++(Op op) {
+    // Unlike C++, operator++ must not modify the parameter and both prefix and postfix operations call this method
+    Op newOp = new Op(op.i);
+    newOp.PlusPlusPostfix(0);
+    return newOp;
+  }
+  public static Op operator--(Op op) {
+    // Unlike C++, operator-- must not modify the parameter and both prefix and postfix operations call this method
+    Op newOp = new Op(op.i);
+    newOp.MinusMinusPrefix();
+    return newOp;
+  }
+%}
+#endif
+
+#ifdef SWIGPHP
+%rename(AndOperator) operator &&;
+%rename(OrOperator) operator ||;
+#endif
+
+%rename(IntCast) operator int();
+%rename(DoubleCast) operator double();
+
+%inline %{
+
+#if defined(_MSC_VER)
+  #include <iso646.h> /* for named logical operator, eg 'operator or' */
+#endif
+
+#include <assert.h>
+
+class Op {
+public:
+  int i;
+  Op(int a=0) : i(a)
+  {}
+  Op(const Op& o) : i(o.i)
+  {}
+  virtual ~Op()
+  {}
+
+  friend Op operator &&(const Op& a,const Op& b){return Op(a.i&&b.i);}
+  friend Op operator or(const Op& a,const Op& b){return Op(a.i||b.i);}
+
+  Op &operator=(const Op& o) {
+    i=o.i;
+    return *this;
+  }
+  // +=,-=... are member fns
+  void operator+=(const Op& o){ i+=o.i;}
+  void operator-=(const Op& o){ i-=o.i;}
+  void operator*=(const Op& o){ i*=o.i;}
+  void operator/=(const Op& o){ i/=o.i;}
+  void operator%=(const Op& o){ i%=o.i;}
+  // the +,-,*,... are friends
+  // (just to make life harder)
+  friend Op operator+(const Op& a,const Op& b){return Op(a.i+b.i);}
+  friend Op operator-(const Op& a,const Op& b);
+  friend Op operator*(const Op& a,const Op& b){return Op(a.i*b.i);}
+  friend Op operator/(const Op& a,const Op& b){return Op(a.i/b.i);}
+  friend Op operator%(const Op& a,const Op& b){return Op(a.i%b.i);}
+
+  // unary operators
+  Op operator-() const {return Op(-i);}
+  bool operator !() const {return !(i);}
+
+  // overloading the [] operator
+  // need 2 versions: get & set
+  // note: C++ can be a little mixed up upon which version it calls
+  // most of the time it calls the second version
+  int operator[](unsigned idx)const
+  {	  if (idx==0) return i; return 0;}
+  int& operator[](unsigned idx)
+  {	  if (idx==0) return i; static int j;j=0; return j;}
+
+  // overloading the () operator
+  // this can have many parameters so we will test this
+  int operator()(int a=0){return i+a;}
+  int operator()(int a,int b){return i+a+b;}
+
+  // increment/decrement operators
+  Op& operator++() {++i; return *this;} // prefix ++
+  Op operator++(int) {Op o = *this; ++(*this); return o;} // postfix ++
+  Op& operator--() {--i; return *this;} // prefix --
+  Op operator--(int) {Op o = *this; --(*this); return o;} // postfix --
+
+  // TODO: <<,<<=
+
+  // cast operators
+  operator double() { return i; }
+  virtual operator int() { return i; }
+
+  // This method just checks that the operators are implemented correctly
+  static void sanity_check();
+};
+
+// just to complicate matters
+// we have a couple of non class operators
+inline bool operator==(const Op& a,const Op& b){return a.i==b.i;}
+inline bool operator!=(const Op& a,const Op& b){return a.i!=b.i;}
+inline bool operator< (const Op& a,const Op& b){return a.i<b.i;}
+inline bool operator<=(const Op& a,const Op& b){return a.i<=b.i;}
+inline bool operator> (const Op& a,const Op& b){return a.i>b.i;}
+inline bool operator>=(const Op& a,const Op& b){return a.i>=b.i;}
+
+%}
+
+%{
+  // This one is not declared inline as VC++7.1 gets mixed up with the unary operator-
+  Op operator-(const Op& a,const Op& b){return Op(a.i-b.i);}
+%}
+
+// in order to wrapper this correctly
+// we need to extend the class
+// to make the friends & non members part of the class
+%extend Op{
+        Op operator &&(const Op& b){return Op($self->i&&b.i);}
+        Op operator or(const Op& b){return Op($self->i||b.i);}
+
+	Op operator+(const Op& b){return Op($self->i+b.i);}
+	Op operator-(const Op& b){return Op($self->i-b.i);}
+	Op operator*(const Op& b){return Op($self->i*b.i);}
+	Op operator/(const Op& b){return Op($self->i/b.i);}
+	Op operator%(const Op& b){return Op($self->i%b.i);}
+
+	bool operator==(const Op& b){return $self->i==b.i;}
+	bool operator!=(const Op& b){return $self->i!=b.i;}
+	bool operator< (const Op& b){return $self->i<b.i;}
+	bool operator<=(const Op& b){return $self->i<=b.i;}
+	bool operator> (const Op& b){return $self->i>b.i;}
+	bool operator>=(const Op& b){return $self->i>=b.i;}
+
+	// subtraction with reversed arguments
+	Op __rsub__(const int b){return Op(b - $self->i);}
+
+	// we also add the __str__() fn to the class
+	// this allows it to be converted to a string (so it can be printed)
+	const char* __str__()
+	{
+		static char buffer[255];
+		sprintf(buffer,"Op(%d)",$self->i);
+		return buffer;
+	}
+	// to get the [] operator working correctly we need to extend with two function
+	// __getitem__ & __setitem__
+	int __getitem__(unsigned i)
+	{	return (*$self)[i];	}
+	void __setitem__(unsigned i,int v)
+	{	(*$self)[i]=v;	}
+}
+
+/*
+Suggested list of operator overloads (mainly from python)
+
+Operators overloaded with their C++ equivalent
+__add__,__sub__,__mul__,__div__,__mod__	+,-,*,/,%
+__iadd__,__isub__,__imul__,__idiv__,__imod__	+=,-=,*=,/=,%=
+
+__eq__,__ne__,__lt__,__le__,__gt__,__ge__ ==,!=,<,<=,>,>=
+__not__,__neg__	unary !, unary -
+__and__,__or__,__xor__	logical and,logical or,logical xor
+__rshift__,__lshift__ >>,<<
+
+__getitem__,__setitem__ for operator[]
+
+Operators overloaded without C++ equivilents
+__pow__ for power operator
+__str__ converts object to a string (should return a const char*)
+__concat__ for contatenation (if language supports)
+
+*/
+
+%inline %{
+class OpDerived : public Op {
+public:
+  OpDerived(int a=0) : Op(a)
+  {}
+
+  // overloaded
+  virtual operator int() { return i*2; }
+};
+%}
+
+
+%{
+
+#include <assert.h>
+
+void Op::sanity_check()
+{
+	// test routine:
+	Op a;
+	Op b=5;
+	Op c=b;	// copy construct
+	Op d=2;
+        Op dd=d; // assignment operator
+
+	// test equality
+	assert(a!=b);
+	assert(b==c);
+	assert(a!=d);
+        assert(d==dd);
+
+	// test <
+	assert(a<b);
+	assert(a<=b);
+	assert(b<=c);
+	assert(b>=c);
+	assert(b>d);
+	assert(b>=d);
+
+	// test +=
+	Op e=3;
+	e+=d;
+	assert(e==b);
+	e-=c;
+	assert(e==a);
+	e=Op(1);
+	e*=b;
+	assert(e==c);
+	e/=d;
+	assert(e==d);
+	e%=c;
+	assert(e==d);
+
+	// test +
+	Op f(1),g(1);
+	assert(f+g==Op(2));
+	assert(f-g==Op(0));
+	assert(f*g==Op(1));
+	assert(f/g==Op(1));
+	assert(f%g==Op(0));
+
+	// test unary operators
+	assert(!a==true);
+	assert(!b==false);
+	assert(-a==a);
+	assert(-b==Op(-5));
+
+	// test []
+	Op h=3;
+	assert(h[0]==3);
+	assert(h[1]==0);
+	h[0]=2;	// set
+	assert(h[0]==2);
+	h[1]=2;	// ignored
+	assert(h[0]==2);
+	assert(h[1]==0);
+
+	// test ()
+	Op i=3;
+	assert(i()==3);
+	assert(i(1)==4);
+	assert(i(1,2)==6);
+
+	// plus add some code to check the __str__ fn
+	//assert(str(Op(1))=="Op(1)");
+	//assert(str(Op(-3))=="Op(-3)");
+
+        // test ++ and --
+        Op j(100);
+        int original = j.i;
+        {
+          Op newOp = j++;
+          int newInt = original++;
+          assert(j.i == original);
+          assert(newOp.i == newInt);
+        }
+        {
+          Op newOp = j--;
+          int newInt = original--;
+          assert(j.i == original);
+          assert(newOp.i == newInt);
+        }
+        {
+          Op newOp = ++j;
+          int newInt = ++original;
+          assert(j.i == original);
+          assert(newOp.i == newInt);
+        }
+        {
+          Op newOp = --j;
+          int newInt = --original;
+          assert(j.i == original);
+          assert(newOp.i == newInt);
+        }
+
+        // cast operators
+        Op k=3;
+        int check_k = k;
+        assert (check_k == 3);
+
+        Op l=4;
+        double check_l = l;
+        assert (check_l == 4);
+}
+
+%}
+
diff --git a/trunk/Examples/test-suite/operator_overload_break.i b/trunk/Examples/test-suite/operator_overload_break.i
new file mode 100644
index 0000000..0893da7
--- /dev/null
+++ b/trunk/Examples/test-suite/operator_overload_break.i
@@ -0,0 +1,64 @@
+%module operator_overload_break
+
+#if defined(SWIGPYTHON)
+%warnfilter(SWIGWARN_IGNORE_OPERATOR_PLUSPLUS);
+#endif
+
+#if !defined(SWIGLUA) && !defined(SWIGR) && !defined(SWIGPERL)
+%rename(Plus) operator +;
+%rename(Minus) operator -;
+%rename(EqualEqual) operator ==;
+%rename(PlusPlusPrefix) operator++();
+%rename(PlusPlusPostfix) operator++(int);
+#endif
+
+
+%{
+#include <iostream>
+using namespace std;
+%}
+
+%inline %{
+
+class Op
+{
+public:
+    Op(int n) {k = n;}
+    Op(const Op& other) {
+      std::cerr << "COPY: "<< other.k << std::endl;
+      k = other.k;
+    }
+
+    bool operator==(const Op& rhs) {
+       std::cerr << "Op: " << k << std::endl;
+       std::cerr << "obj: " << rhs.k << std::endl;
+       return (k == rhs.k);
+    }
+    bool operator==(int i) {
+       std::cerr << "Op: " << k << std::endl;
+       std::cerr << "other: " << i << std::endl;
+       return (k == i);
+    }
+
+    Op operator+(const Op& rhs) {return Op(k + rhs.k);}
+    Op operator+(int rhs) {return Op(k + rhs);}
+
+    Op operator-(const Op& rhs) {return Op(k - rhs.k);}
+    Op operator-(int rhs) {
+      std::cerr << "sub: " << rhs << std::endl;
+      return Op(k - rhs);
+    }
+
+    Op __rsub__(int lhs) {
+      std::cerr << "sub: " << lhs << std::endl;
+      return Op(lhs - k);
+    }
+
+    Op& operator++() {k++; return *this;}
+
+    void Print() {std::cerr << k << std::endl;}
+
+    int k;
+};
+
+%}
diff --git a/trunk/Examples/test-suite/ordering.i b/trunk/Examples/test-suite/ordering.i
new file mode 100644
index 0000000..258e7b1
--- /dev/null
+++ b/trunk/Examples/test-suite/ordering.i
@@ -0,0 +1,30 @@
+%module ordering
+
+// Ruby used to fail on the ordering of the two Class declarations below
+
+struct Klass {
+  int variable;
+};
+
+%{
+struct Klass {
+  int variable;
+};
+%}
+
+
+// Testing the order of various code block sections
+
+%runtime %{
+   class RuntimeSection {};
+%}
+
+%header %{
+   class HeaderSection {};
+   void HeaderMethod(RuntimeSection rs) {}
+%}
+
+%wrapper %{
+   void WrapperMethod(HeaderSection hs, RuntimeSection rs) {}
+%}
+
diff --git a/trunk/Examples/test-suite/overload_complicated.i b/trunk/Examples/test-suite/overload_complicated.i
new file mode 100644
index 0000000..63ed32b
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_complicated.i
@@ -0,0 +1,72 @@
+// A complicated test of overloaded functions
+%module overload_complicated
+
+#ifndef SWIG_NO_OVERLOAD
+
+// Different warning filters needed for scripting languages (eg Python) and for statically typed languages (eg C#).
+%warnfilter(509, 516) Pop::Pop;      // Overloaded xxxx is shadowed by xxxx at xxx:y. | Overloaded method xxxx ignored. Method at xxx:y used.
+%warnfilter(509, 516) Pop::hip;      // Overloaded xxxx is shadowed by xxxx at xxx:y. | Overloaded method xxxx ignored. Method at xxx:y used.
+%warnfilter(509, 516) Pop::hop;      // Overloaded xxxx is shadowed by xxxx at xxx:y. | Overloaded method xxxx ignored. Method at xxx:y used.
+%warnfilter(509, 516) Pop::pop;      // Overloaded xxxx is shadowed by xxxx at xxx:y. | Overloaded method xxxx ignored. Method at xxx:y used.
+%warnfilter(516) Pop::bop;           // Overloaded method xxxx ignored. Method at xxx:y used.
+%warnfilter(516) Pop::bip;           // Overloaded method xxxx ignored. Method at xxx:y used.
+%warnfilter(509, 516) ::muzak;       // Overloaded xxxx is shadowed by xxxx at xxx:y. | Overloaded method xxxx ignored. Method at xxx:y used.
+
+%typemap(in, numinputs=0) int l { $1 = 4711; }
+
+%inline %{
+
+double foo(int, int, char *, int) {
+    return 15;
+}
+
+double foo(int i, int j, double k = 17.4, int l = 18, char m = 'P') {
+    return i + j + k + l + (int) m;
+}
+
+struct Pop {
+    Pop(int* i) {}
+    Pop(int& i) {}
+    Pop(const int* i, bool b) {}
+    Pop(const int* i) {}
+
+    // Check overloaded in const only and pointers/references which target languages cannot disambiguate
+    int hip(bool b)                 { return 701; }
+    int hip(int* i)                 { return 702; }
+    int hip(int& i)                 { return 703; }
+    int hip(int* i) const           { return 704; }
+    int hip(const int* i)           { return 705; }
+
+    // Reverse the order for the above
+    int hop(const int* i)           { return 805; }
+    int hop(int* i) const           { return 804; }
+    int hop(int& i)                 { return 803; }
+    int hop(int* i)                 { return 802; }
+    int hop(bool b)                 { return 801; }
+
+    // Few more variations and order shuffled
+    int pop(bool b)                 { return 901; }
+    int pop(int* i) const           { return 902; }
+    int pop(int& i)                 { return 903; }
+    int pop(int* i)                 { return 904; }
+    int pop()                       { return 905; }
+    int pop(const int* i)           { return 906; }
+
+    // Overload on const only
+    int bop(int* i)                 { return 1001; }
+    int bop(int* i) const           { return 1002; }
+
+    int bip(int* i) const           { return 2001; }
+    int bip(int* i)                 { return 2002; }
+};
+
+// Globals
+int muzak(bool b)                 { return 3001; }
+int muzak(int* i)                 { return 3002; }
+int muzak(int& i)                 { return 3003; }
+int muzak(const int* i)           { return 3004; }
+
+%}
+
+#endif
+
diff --git a/trunk/Examples/test-suite/overload_copy.i b/trunk/Examples/test-suite/overload_copy.i
new file mode 100644
index 0000000..a685f76
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_copy.i
@@ -0,0 +1,16 @@
+// Tests copy constructor
+%module overload_copy
+
+#ifndef SWIG_NO_OVERLOAD
+%inline %{
+
+class Foo {
+public:
+    Foo() { }
+    Foo(const Foo &) { }
+};
+
+%}
+
+#endif
+
diff --git a/trunk/Examples/test-suite/overload_extend.i b/trunk/Examples/test-suite/overload_extend.i
new file mode 100644
index 0000000..c32a07f
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_extend.i
@@ -0,0 +1,65 @@
+%module overload_extend
+
+#ifndef __cplusplus
+%{
+#include <stdlib.h>
+%}
+
+%typemap(default) double y "$1=1000;";
+#endif
+
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) test;
+#endif
+
+%warnfilter(SWIGWARN_PARSE_REDEFINED) Foo::test; 
+
+
+
+%extend Foo {
+    int test() { return 0; }
+    int test(int x) { x = 0; return 1; }
+    int test(char *s) { s = 0; return 2; }
+#ifdef __cplusplus
+    double test(double x, double y = 1000) { return x + y; }
+#else
+    double test(double x, double y) { return x + y; }
+#endif
+};
+
+
+%inline %{
+struct Foo {
+  int variable;
+#ifdef __cplusplus
+    int test() { return -1; }
+#endif
+};
+%}
+
+
+%extend Bar {
+#ifdef __cplusplus
+  Bar() {
+    return new Bar();
+  }
+  ~Bar() {
+    delete $self;
+  }
+#else
+  Bar() {
+    return (Bar *) malloc(sizeof(Bar));
+  }
+  ~Bar() {
+    free($self);
+  }
+#endif
+}
+
+%inline %{
+typedef struct {
+  int variable;
+} Bar;
+%}
+       
+
diff --git a/trunk/Examples/test-suite/overload_extendc.i b/trunk/Examples/test-suite/overload_extendc.i
new file mode 100644
index 0000000..1c1dd00
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_extendc.i
@@ -0,0 +1,21 @@
+%module overload_extendc
+
+%typemap(default) int int2 "$1=1000;";
+
+%inline %{
+typedef struct Foo {
+  int dummy;
+} Foo;
+%}
+
+%extend Foo {
+    int test(int x) { x = 0; return 1; }
+    int test(char *s) { s = 0; return 2; }
+    int test(double x, double y) { x = 0; y = 0; return 3; }
+    int test(char *s, int int1, int int2) { s = 0; return int1+int2; }
+
+    /* C default arguments */
+    int test(Foo* f, int i=10, int j=20) { return i+j; }
+};
+
+
diff --git a/trunk/Examples/test-suite/overload_rename.i b/trunk/Examples/test-suite/overload_rename.i
new file mode 100644
index 0000000..cdb6451
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_rename.i
@@ -0,0 +1,28 @@
+%module overload_rename
+
+
+%{
+
+class Foo {
+public:
+  Foo(float a, float b=1.0)
+  {
+  }
+  
+  Foo(float a, int c, float b=1.0)
+  {
+  }
+  
+};
+
+%}
+
+%rename(Foo_int) Foo::Foo(float a, int c, float b=1.0);
+
+class Foo {
+public:
+  Foo(float a, float b=1.0);
+  Foo(float a, int c, float b=1.0);
+};
+
+
diff --git a/trunk/Examples/test-suite/overload_simple.i b/trunk/Examples/test-suite/overload_simple.i
new file mode 100644
index 0000000..be76020
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_simple.i
@@ -0,0 +1,205 @@
+// Simple tests of overloaded functions
+%module overload_simple
+
+#ifdef SWIGCHICKEN
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) fbool;
+#endif
+
+#ifdef SWIGLUA
+// lua only has one numeric type, so most of the overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) foo;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) bar;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) Spam;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) num;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) fid;
+#endif
+
+#ifndef SWIG_NO_OVERLOAD
+%immutable Spam::type;
+
+%inline %{
+
+struct Foo {
+};
+
+class Bar {
+public:
+  Bar(int i = 0) { num = i; }
+
+  static int foo(int a=0, int b=0) {return 0;}
+
+  int num;
+};
+
+char *foo() {
+   return (char *) "foo:";
+}
+char *foo(int) {
+   return (char*) "foo:int";
+}
+
+char *foo(double) {
+   return (char*) "foo:double";
+}
+
+char *foo(char *) {
+   return (char*) "foo:char *";
+}
+
+char *foo(Foo *) {
+   return (char*) "foo:Foo *";
+}
+char *foo(Bar *) {
+   return (char *) "foo:Bar *";
+}
+char *foo(void *) {
+   return (char *) "foo:void *";
+}
+char *foo(Foo *, int) {
+   return (char *) "foo:Foo *,int";
+}
+char *foo(double, Bar *) {
+   return (char *) "foo:double,Bar *";
+}
+
+char *blah(double) {
+   return (char *) "blah:double";
+}
+
+char *blah(char *) {
+   return (char *) "blah:char *";
+}
+
+class Spam {
+public:
+    Spam() { type = "none"; }
+    Spam(int) { type = "int"; }
+    Spam(double) { type = "double"; }
+    Spam(char *) { type = "char *"; }
+    Spam(Foo *) { type = "Foo *"; }
+    Spam(Bar *) { type = "Bar *"; }
+    Spam(void *) { type = "void *"; }
+    const char *type;
+
+char *foo(int) {
+   return (char*) "foo:int";
+}
+char *foo(double) {
+   return (char*) "foo:double";
+}
+char *foo(char *) {
+   return (char*) "foo:char *";
+}
+char *foo(Foo *) {
+   return (char*) "foo:Foo *";
+}
+char *foo(Bar *) {
+   return (char *) "foo:Bar *";
+}
+char *foo(void *) {
+   return (char *) "foo:void *";
+}
+
+static char *bar(int) {
+   return (char*) "bar:int";
+}
+static char *bar(double) {
+   return (char*) "bar:double";
+}
+static char *bar(char *) {
+   return (char*) "bar:char *";
+}
+static char *bar(Foo *) {
+   return (char*) "bar:Foo *";
+}
+static char *bar(Bar *) {
+   return (char *) "bar:Bar *";
+}
+static char *bar(void *) {
+   return (char *) "bar:void *";
+}
+};
+
+
+bool fbool(bool b) {
+   return b;
+}
+
+int fbool(int b) {
+   return b;
+}
+
+char *fint(int) {
+   return (char*) "fint:int";
+}
+
+char *fdouble(double) {
+   return (char*) "fdouble:double";
+}
+
+char *num(int) {
+   return (char*) "num:int";
+}
+char *num(double) {
+   return (char*) "num:double";
+}
+
+char *fid(int, int) {
+   return (char*) "fid:intint";
+}
+char *fid(int, double) {
+   return (char*) "fid:intdouble";
+}
+
+char *fid(double, int) {
+   return (char*) "fid:doubleint";
+}
+
+char *fid(double, double) {
+   return (char*) "fid:doubledouble";
+}
+
+%}
+
+%inline %{
+unsigned long long ull() { return 0ULL; }
+unsigned long long ull(unsigned long long ull) { return ull; }
+long long ll() { return 0LL; }
+long long ll(long long ull) { return ull; }
+%}
+
+%include cmalloc.i
+%malloc(void);
+%free(void);
+
+#endif
+
+
+%inline {  
+  class ClassA
+  {
+  public:
+    ClassA() {}  
+    int method1( ) {return 0;}
+    int method1( int arg1 ) {return arg1;}
+  protected:
+    int method1( int arg1, int arg2 ) {return arg1 + arg2;}
+    
+  };
+}
+
+#ifdef SWIGPYTHON
+%inline 
+{
+  class Graph {
+  public:
+    int val;
+    Graph(int i) : val(i) {};
+  };
+}
+
+%extend Graph {
+  Graph(PyObject* p) { return new Graph(123);}
+} 
+
+#endif
diff --git a/trunk/Examples/test-suite/overload_subtype.i b/trunk/Examples/test-suite/overload_subtype.i
new file mode 100644
index 0000000..3d9645d
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_subtype.i
@@ -0,0 +1,17 @@
+%module overload_subtype
+
+%inline %{
+
+class Foo {};
+class Bar : public Foo {};
+
+
+int  spam(Foo *f) {
+    return 1;
+}
+
+int spam(Bar *b) {
+    return 2;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/overload_template.i b/trunk/Examples/test-suite/overload_template.i
new file mode 100644
index 0000000..a889dbf
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_template.i
@@ -0,0 +1,216 @@
+%module overload_template
+
+#ifdef SWIGLUA
+// lua only has one numeric type, so most of the overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) foo;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) max;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) specialization;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) overload;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) space::nsoverload;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) fooT;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) barT;
+#endif
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+%inline %{
+
+int foo() {
+  return 3;
+}
+
+template <class T>
+  int foo(T x) {
+     return (int)x;
+  }
+
+template<class T>
+  T max(T a, T b) { return  (a > b) ? a : b; }
+%}                                     
+
+
+%template(foo) foo<int>;
+%template(foo) foo<double>;
+
+%template(max) max<int>;
+%template(max) max<double>;
+
+// Mix template overloading with plain function overload
+// Mix 1
+%inline %{
+  int mix1(const char* msg) { return 101; }
+  template<typename T> int mix1(T t, const T& tt) { return 102; }
+  template<typename T> int mix1(T t) { return 103; }
+%}
+%template(mix1) mix1<double>;
+
+// Mix 2
+%inline %{
+  template<typename T> int mix2(T t, const T& tt) { return 102; }
+  int mix2(const char* msg) { return 101; }
+  template<typename T> int mix2(T t) { return 103; }
+%}
+%template(mix2) mix2<double>;
+
+// Mix 3
+%inline %{
+  template<typename T> int mix3(T t, const T& tt) { return 102; }
+  template<typename T> int mix3(T t) { return 103; }
+  int mix3(const char* msg) { return 101; }
+%}
+%template(mix3) mix3<double>;
+
+
+// overloaded by number of templated parameters
+// Combination 1
+%inline %{
+template<typename T> int overtparams1(T t) { return 10; }
+template<typename T, typename U> int overtparams1(T t, U u) { return 20; }
+%}
+
+%template(overtparams1) overtparams1<int>;
+%template(overtparams1) overtparams1<double, int>;
+
+
+// Combination 2
+%inline %{
+template<typename T> int overtparams2(T t) { return 30; }
+template<typename T, typename U> int overtparams2(T t, U u) { return 40; }
+%}
+
+%template(overtparams2) overtparams2<double, int>;
+
+
+// Combination 3
+%inline %{
+template<typename T> int overloaded(T t) { return 50; }
+int overloaded() { return 60; }
+template<typename T, typename U> int overloaded(T t, U u) { return 70; }
+%}
+
+%template(overloaded) overloaded<double, int>;
+
+// Combination 4
+%inline %{
+int overloadedagain(const char* msg) { return 80; }
+template<typename T> int overloadedagain() { return 90; }
+template<typename T, typename U> int overloadedagain(T t, U u) { return 100; }
+%}
+
+%template(overloadedagain) overloadedagain<double>;
+
+// simple specialization
+%inline %{
+template<typename T> void xyz() {}
+template<> void xyz<double>() {}
+void xyz() {}
+%}
+
+// We can have xyz(); xyz<double>(); xyz<int>(); in C++, but can't have this type of overloading in target language, so we need to do some renaming
+%template(xyz_double) xyz<double>;
+%template(xyz_int) xyz<int>;
+
+
+// specializations
+%inline %{
+template<typename T> int specialization(T t) { return 200; }
+template<typename T, typename U> int specialization(T t, U u) { return 201; }
+template<> int specialization(int t) { return 202; }
+template<> int specialization<double>(double t) { return 203; }
+template<> int specialization(int t, int u) { return 204; }
+template<> int specialization<double,double>(double t, double u) { return 205; }
+%}
+
+%template(specialization) specialization<int>;
+%template(specialization) specialization<double>;
+%template(specialization) specialization<int, int>;
+%template(specialization) specialization<double, double>;
+%template(specialization) specialization<const char *, const char *>;
+
+
+// a bit of everything
+%inline %{
+int overload(const char *c) { return 0; }
+template<typename T> int overload(T t) { return 10; }
+template<typename T> int overload(T t, const T &tref) { return 20; }
+template<typename T> int overload(T t, const char *c) { return 30; }
+template<> int overload<double>(double t, const char *c) { return 40; }
+int overload() { return 50; }
+
+class Klass {};
+%}
+
+%template(overload) overload<int>;
+%template(overload) overload<Klass>;
+%template(overload) overload<double>;
+
+
+// everything put in a namespace
+%inline %{
+namespace space {
+  int nsoverload(const char *c) { return 1000; }
+  template<typename T> int nsoverload(T t) { return 1010; }
+  template<typename T> int nsoverload(T t, const T &tref) { return 1020; }
+  template<typename T> int nsoverload(T t, const char *c) { return 1030; }
+  template<> int nsoverload<double>(double t, const char *c) { return 1040; }
+  int nsoverload() { return 1050; }
+}
+%}
+
+%template(nsoverload) space::nsoverload<int>;
+%template(nsoverload) space::nsoverload<Klass>;
+%template(nsoverload) space::nsoverload<double>;
+
+
+%inline %{
+  namespace space 
+  {
+    template <class T>
+    struct Foo 
+    {
+      void bar(T t1) { }
+      void bar(T t1, T t2) { }
+      void bar(int a, int b, int c) { }
+    };
+    struct A
+    {
+      template <class Y>
+      static void fooT(Y y) { }
+
+    };
+
+  }
+  template <class T>
+    struct Bar
+    {
+      void foo(T t1) { }
+      void foo(T t1, T t2) { }
+      void foo(int a, int b, int c) { }
+      template <class Y>
+      void fooT(Y y) { }
+    };
+
+
+  struct B
+  {
+    template <class Y>
+    void barT(Y y) { }
+    
+  };
+  
+%}
+
+
+%template(Bar_d) Bar<double>;
+%template(Foo_d) space::Foo<double>;
+%template(foo) space::A::fooT<double>;
+%template(foo) space::A::fooT<int>;
+%template(foo) space::A::fooT<char>;
+
+%template(foo) B::barT<double>;
+%template(foo) B::barT<int>;
+%template(foo) B::barT<char>;
diff --git a/trunk/Examples/test-suite/overload_template_fast.i b/trunk/Examples/test-suite/overload_template_fast.i
new file mode 100644
index 0000000..83d5acc
--- /dev/null
+++ b/trunk/Examples/test-suite/overload_template_fast.i
@@ -0,0 +1,5 @@
+%module overload_template_fast
+
+%fastdispatch;
+
+%include overload_template.i
diff --git a/trunk/Examples/test-suite/packageoption.h b/trunk/Examples/test-suite/packageoption.h
new file mode 100644
index 0000000..a7ef499
--- /dev/null
+++ b/trunk/Examples/test-suite/packageoption.h
@@ -0,0 +1,5 @@
+class A
+{
+ public:
+  int testInt() { return 2;}
+};
diff --git a/trunk/Examples/test-suite/packageoption.list b/trunk/Examples/test-suite/packageoption.list
new file mode 100644
index 0000000..4bdabec
--- /dev/null
+++ b/trunk/Examples/test-suite/packageoption.list
@@ -0,0 +1,2 @@
+packageoption_a
+packageoption_b
diff --git a/trunk/Examples/test-suite/packageoption_a.i b/trunk/Examples/test-suite/packageoption_a.i
new file mode 100644
index 0000000..e95091b
--- /dev/null
+++ b/trunk/Examples/test-suite/packageoption_a.i
@@ -0,0 +1,10 @@
+%module(package="C") "packageoption_a";
+
+%inline %{
+class A
+{
+ public:
+  int testInt() { return 2;}
+};
+
+%}
diff --git a/trunk/Examples/test-suite/packageoption_b.i b/trunk/Examples/test-suite/packageoption_b.i
new file mode 100644
index 0000000..466853c
--- /dev/null
+++ b/trunk/Examples/test-suite/packageoption_b.i
@@ -0,0 +1,10 @@
+%module(package="C") "packageoption_b";
+
+%inline %{
+class B
+{
+ public:
+  int testInt() { return 4; }
+};
+
+%}
diff --git a/trunk/Examples/test-suite/perl5/Makefile.in b/trunk/Examples/test-suite/perl5/Makefile.in
new file mode 100644
index 0000000..3fee35b
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/Makefile.in
@@ -0,0 +1,58 @@
+#######################################################################
+# Makefile for perl5 test-suite
+#######################################################################
+
+LANGUAGE     = perl5
+PERL         = @PERL@
+SCRIPTSUFFIX = _runme.pl
+TEST_RUNNER  = run-perl-test.pl
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+CPP_TEST_CASES += \
+	primitive_types \
+	li_cdata \
+	li_cstring \
+	li_cdata_carrays \
+
+C_TEST_CASES += \
+	li_cdata \
+	li_cstring \
+	li_cdata_carrays \
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+# none!
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.pl appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PERL) $(TEST_RUNNER) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ; ) \
+	fi; \
+
+
+# Clean: remove the generated .pm file
+%.clean:
+	@rm -f $*.pm;
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile perl5_clean
diff --git a/trunk/Examples/test-suite/perl5/README b/trunk/Examples/test-suite/perl5/README
new file mode 100644
index 0000000..14eb527
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/README
@@ -0,0 +1,32 @@
+See ../README for common README file.
+
+Any testcases which have _runme.pl appended after the testcase name will be detected and run.
+
+Test::More Support
+==
+
+Test::More and Test::Harness are two of the standard perl test harness
+tools. Support has been added for these modules as of 1.3.28. If
+adding a new test to this suite, please use Test::More. 
+
+Currently converted test cases include:
+
+* operator_overload
+* operator_overload_break
+* package
+* overload_simple
+* apply_strings
+* char_strings
+* default_args
+* enum_thorough
+* global_vars
+* import_nomodule
+* inherit
+* li_cdata_carrays
+* li_std_string
+* member_pointer
+* multiple_inheritance
+* primitive_ref
+* template_default_arg
+* unions
+* voidtest
diff --git a/trunk/Examples/test-suite/perl5/Test/Builder.pm b/trunk/Examples/test-suite/perl5/Test/Builder.pm
new file mode 100644
index 0000000..9f6a3a4
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/Test/Builder.pm
@@ -0,0 +1,1591 @@
+package Test::Builder;
+
+use 5.004;
+
+# $^C was only introduced in 5.005-ish.  We do this to prevent
+# use of uninitialized value warnings in older perls.
+$^C ||= 0;
+
+use strict;
+use vars qw($VERSION);
+$VERSION = '0.22';
+$VERSION = eval $VERSION;    # make the alpha version come out as a number
+
+# Make Test::Builder thread-safe for ithreads.
+BEGIN {
+    use Config;
+    # Load threads::shared when threads are turned on
+    if( $] >= 5.008 && $Config{useithreads} && $INC{'threads.pm'}) {
+        require threads::shared;
+
+        # Hack around YET ANOTHER threads::shared bug.  It would 
+        # occassionally forget the contents of the variable when sharing it.
+        # So we first copy the data, then share, then put our copy back.
+        *share = sub (\[$@%]) {
+            my $type = ref $_[0];
+            my $data;
+
+            if( $type eq 'HASH' ) {
+                %$data = %{$_[0]};
+            }
+            elsif( $type eq 'ARRAY' ) {
+                @$data = @{$_[0]};
+            }
+            elsif( $type eq 'SCALAR' ) {
+                $$data = ${$_[0]};
+            }
+            else {
+                die "Unknown type: ".$type;
+            }
+
+            $_[0] = &threads::shared::share($_[0]);
+
+            if( $type eq 'HASH' ) {
+                %{$_[0]} = %$data;
+            }
+            elsif( $type eq 'ARRAY' ) {
+                @{$_[0]} = @$data;
+            }
+            elsif( $type eq 'SCALAR' ) {
+                ${$_[0]} = $$data;
+            }
+            else {
+                die "Unknown type: ".$type;
+            }
+
+            return $_[0];
+        };
+    }
+    # 5.8.0's threads::shared is busted when threads are off.
+    # We emulate it here.
+    else {
+        *share = sub { return $_[0] };
+        *lock  = sub { 0 };
+    }
+}
+
+
+=head1 NAME
+
+Test::Builder - Backend for building test libraries
+
+=head1 SYNOPSIS
+
+  package My::Test::Module;
+  use Test::Builder;
+  require Exporter;
+  @ISA = qw(Exporter);
+  @EXPORT = qw(ok);
+
+  my $Test = Test::Builder->new;
+  $Test->output('my_logfile');
+
+  sub import {
+      my($self) = shift;
+      my $pack = caller;
+
+      $Test->exported_to($pack);
+      $Test->plan(@_);
+
+      $self->export_to_level(1, $self, 'ok');
+  }
+
+  sub ok {
+      my($test, $name) = @_;
+
+      $Test->ok($test, $name);
+  }
+
+
+=head1 DESCRIPTION
+
+Test::Simple and Test::More have proven to be popular testing modules,
+but they're not always flexible enough.  Test::Builder provides the a
+building block upon which to write your own test libraries I<which can
+work together>.
+
+=head2 Construction
+
+=over 4
+
+=item B<new>
+
+  my $Test = Test::Builder->new;
+
+Returns a Test::Builder object representing the current state of the
+test.
+
+Since you only run one test per program, there is B<one and only one>
+Test::Builder object.  No matter how many times you call new(), you're
+getting the same object.  (This is called a singleton).
+
+=cut
+
+my $Test = Test::Builder->new;
+sub new {
+    my($class) = shift;
+    $Test ||= bless ['Move along, nothing to see here'], $class;
+    return $Test;
+}
+
+=item B<reset>
+
+  $Test->reset;
+
+Reinitializes the Test::Builder singleton to its original state.
+Mostly useful for tests run in persistent environments where the same
+test might be run multiple times in the same process.
+
+=cut
+
+my $Test_Died;
+my $Have_Plan;
+my $No_Plan;
+my $Curr_Test;     share($Curr_Test);
+use vars qw($Level);
+my $Original_Pid;
+my @Test_Results;  share(@Test_Results);
+
+my $Exported_To;
+my $Expected_Tests;
+
+my $Skip_All;
+
+my $Use_Nums;
+
+my($No_Header, $No_Ending);
+
+$Test->reset;
+
+sub reset {
+    my ($self) = @_;
+
+    $Test_Died = 0;
+    $Have_Plan = 0;
+    $No_Plan   = 0;
+    $Curr_Test = 0;
+    $Level     = 1;
+    $Original_Pid = $$;
+    @Test_Results = ();
+
+    $Exported_To    = undef;
+    $Expected_Tests = 0;
+
+    $Skip_All = 0;
+
+    $Use_Nums = 1;
+
+    ($No_Header, $No_Ending) = (0,0);
+
+    $self->_dup_stdhandles unless $^C;
+
+    return undef;
+}
+
+=back
+
+=head2 Setting up tests
+
+These methods are for setting up tests and declaring how many there
+are.  You usually only want to call one of these methods.
+
+=over 4
+
+=item B<exported_to>
+
+  my $pack = $Test->exported_to;
+  $Test->exported_to($pack);
+
+Tells Test::Builder what package you exported your functions to.
+This is important for getting TODO tests right.
+
+=cut
+
+sub exported_to {
+    my($self, $pack) = @_;
+
+    if( defined $pack ) {
+        $Exported_To = $pack;
+    }
+    return $Exported_To;
+}
+
+=item B<plan>
+
+  $Test->plan('no_plan');
+  $Test->plan( skip_all => $reason );
+  $Test->plan( tests => $num_tests );
+
+A convenient way to set up your tests.  Call this and Test::Builder
+will print the appropriate headers and take the appropriate actions.
+
+If you call plan(), don't call any of the other methods below.
+
+=cut
+
+sub plan {
+    my($self, $cmd, $arg) = @_;
+
+    return unless $cmd;
+
+    if( $Have_Plan ) {
+        die sprintf "You tried to plan twice!  Second plan at %s line %d\n",
+          ($self->caller)[1,2];
+    }
+
+    if( $cmd eq 'no_plan' ) {
+        $self->no_plan;
+    }
+    elsif( $cmd eq 'skip_all' ) {
+        return $self->skip_all($arg);
+    }
+    elsif( $cmd eq 'tests' ) {
+        if( $arg ) {
+            return $self->expected_tests($arg);
+        }
+        elsif( !defined $arg ) {
+            die "Got an undefined number of tests.  Looks like you tried to ".
+                "say how many tests you plan to run but made a mistake.\n";
+        }
+        elsif( !$arg ) {
+            die "You said to run 0 tests!  You've got to run something.\n";
+        }
+    }
+    else {
+        require Carp;
+        my @args = grep { defined } ($cmd, $arg);
+        Carp::croak("plan() doesn't understand @args");
+    }
+
+    return 1;
+}
+
+=item B<expected_tests>
+
+    my $max = $Test->expected_tests;
+    $Test->expected_tests($max);
+
+Gets/sets the # of tests we expect this test to run and prints out
+the appropriate headers.
+
+=cut
+
+sub expected_tests {
+    my $self = shift;
+    my($max) = @_;
+
+    if( @_ ) {
+        die "Number of tests must be a postive integer.  You gave it '$max'.\n"
+          unless $max =~ /^\+?\d+$/ and $max > 0;
+
+        $Expected_Tests = $max;
+        $Have_Plan      = 1;
+
+        $self->_print("1..$max\n") unless $self->no_header;
+    }
+    return $Expected_Tests;
+}
+
+
+=item B<no_plan>
+
+  $Test->no_plan;
+
+Declares that this test will run an indeterminate # of tests.
+
+=cut
+
+sub no_plan {
+    $No_Plan    = 1;
+    $Have_Plan  = 1;
+}
+
+=item B<has_plan>
+
+  $plan = $Test->has_plan
+  
+Find out whether a plan has been defined. $plan is either C<undef> (no plan has been set), C<no_plan> (indeterminate # of tests) or an integer (the number of expected tests).
+
+=cut
+
+sub has_plan {
+	return($Expected_Tests) if $Expected_Tests;
+	return('no_plan') if $No_Plan;
+	return(undef);
+};
+
+
+=item B<skip_all>
+
+  $Test->skip_all;
+  $Test->skip_all($reason);
+
+Skips all the tests, using the given $reason.  Exits immediately with 0.
+
+=cut
+
+sub skip_all {
+    my($self, $reason) = @_;
+
+    my $out = "1..0";
+    $out .= " # Skip $reason" if $reason;
+    $out .= "\n";
+
+    $Skip_All = 1;
+
+    $self->_print($out) unless $self->no_header;
+    exit(0);
+}
+
+=back
+
+=head2 Running tests
+
+These actually run the tests, analogous to the functions in
+Test::More.
+
+$name is always optional.
+
+=over 4
+
+=item B<ok>
+
+  $Test->ok($test, $name);
+
+Your basic test.  Pass if $test is true, fail if $test is false.  Just
+like Test::Simple's ok().
+
+=cut
+
+sub ok {
+    my($self, $test, $name) = @_;
+
+    # $test might contain an object which we don't want to accidentally
+    # store, so we turn it into a boolean.
+    $test = $test ? 1 : 0;
+
+    unless( $Have_Plan ) {
+        require Carp;
+        Carp::croak("You tried to run a test without a plan!  Gotta have a plan.");
+    }
+
+    lock $Curr_Test;
+    $Curr_Test++;
+
+    # In case $name is a string overloaded object, force it to stringify.
+    $self->_unoverload(\$name);
+
+    $self->diag(<<ERR) if defined $name and $name =~ /^[\d\s]+$/;
+    You named your test '$name'.  You shouldn't use numbers for your test names.
+    Very confusing.
+ERR
+
+    my($pack, $file, $line) = $self->caller;
+
+    my $todo = $self->todo($pack);
+    $self->_unoverload(\$todo);
+
+    my $out;
+    my $result = &share({});
+
+    unless( $test ) {
+        $out .= "not ";
+        @$result{ 'ok', 'actual_ok' } = ( ( $todo ? 1 : 0 ), 0 );
+    }
+    else {
+        @$result{ 'ok', 'actual_ok' } = ( 1, $test );
+    }
+
+    $out .= "ok";
+    $out .= " $Curr_Test" if $self->use_numbers;
+
+    if( defined $name ) {
+        $name =~ s|#|\\#|g;     # # in a name can confuse Test::Harness.
+        $out   .= " - $name";
+        $result->{name} = $name;
+    }
+    else {
+        $result->{name} = '';
+    }
+
+    if( $todo ) {
+        $out   .= " # TODO $todo";
+        $result->{reason} = $todo;
+        $result->{type}   = 'todo';
+    }
+    else {
+        $result->{reason} = '';
+        $result->{type}   = '';
+    }
+
+    $Test_Results[$Curr_Test-1] = $result;
+    $out .= "\n";
+
+    $self->_print($out);
+
+    unless( $test ) {
+        my $msg = $todo ? "Failed (TODO)" : "Failed";
+        $self->_print_diag("\n") if $ENV{HARNESS_ACTIVE};
+        $self->diag("    $msg test ($file at line $line)\n");
+    } 
+
+    return $test ? 1 : 0;
+}
+
+
+sub _unoverload {
+    my $self  = shift;
+
+    local($@,$!);
+
+    eval { require overload } || return;
+
+    foreach my $thing (@_) {
+        eval { 
+            if( defined $$thing ) {
+                if( my $string_meth = overload::Method($$thing, '""') ) {
+                    $$thing = $$thing->$string_meth();
+                }
+            }
+        };
+    }
+}
+
+
+=item B<is_eq>
+
+  $Test->is_eq($got, $expected, $name);
+
+Like Test::More's is().  Checks if $got eq $expected.  This is the
+string version.
+
+=item B<is_num>
+
+  $Test->is_num($got, $expected, $name);
+
+Like Test::More's is().  Checks if $got == $expected.  This is the
+numeric version.
+
+=cut
+
+sub is_eq {
+    my($self, $got, $expect, $name) = @_;
+    local $Level = $Level + 1;
+
+    if( !defined $got || !defined $expect ) {
+        # undef only matches undef and nothing else
+        my $test = !defined $got && !defined $expect;
+
+        $self->ok($test, $name);
+        $self->_is_diag($got, 'eq', $expect) unless $test;
+        return $test;
+    }
+
+    return $self->cmp_ok($got, 'eq', $expect, $name);
+}
+
+sub is_num {
+    my($self, $got, $expect, $name) = @_;
+    local $Level = $Level + 1;
+
+    if( !defined $got || !defined $expect ) {
+        # undef only matches undef and nothing else
+        my $test = !defined $got && !defined $expect;
+
+        $self->ok($test, $name);
+        $self->_is_diag($got, '==', $expect) unless $test;
+        return $test;
+    }
+
+    return $self->cmp_ok($got, '==', $expect, $name);
+}
+
+sub _is_diag {
+    my($self, $got, $type, $expect) = @_;
+
+    foreach my $val (\$got, \$expect) {
+        if( defined $$val ) {
+            if( $type eq 'eq' ) {
+                # quote and force string context
+                $$val = "'$$val'"
+            }
+            else {
+                # force numeric context
+                $$val = $$val+0;
+            }
+        }
+        else {
+            $$val = 'undef';
+        }
+    }
+
+    return $self->diag(sprintf <<DIAGNOSTIC, $got, $expect);
+         got: %s
+    expected: %s
+DIAGNOSTIC
+
+}    
+
+=item B<isnt_eq>
+
+  $Test->isnt_eq($got, $dont_expect, $name);
+
+Like Test::More's isnt().  Checks if $got ne $dont_expect.  This is
+the string version.
+
+=item B<isnt_num>
+
+  $Test->is_num($got, $dont_expect, $name);
+
+Like Test::More's isnt().  Checks if $got ne $dont_expect.  This is
+the numeric version.
+
+=cut
+
+sub isnt_eq {
+    my($self, $got, $dont_expect, $name) = @_;
+    local $Level = $Level + 1;
+
+    if( !defined $got || !defined $dont_expect ) {
+        # undef only matches undef and nothing else
+        my $test = defined $got || defined $dont_expect;
+
+        $self->ok($test, $name);
+        $self->_cmp_diag($got, 'ne', $dont_expect) unless $test;
+        return $test;
+    }
+
+    return $self->cmp_ok($got, 'ne', $dont_expect, $name);
+}
+
+sub isnt_num {
+    my($self, $got, $dont_expect, $name) = @_;
+    local $Level = $Level + 1;
+
+    if( !defined $got || !defined $dont_expect ) {
+        # undef only matches undef and nothing else
+        my $test = defined $got || defined $dont_expect;
+
+        $self->ok($test, $name);
+        $self->_cmp_diag($got, '!=', $dont_expect) unless $test;
+        return $test;
+    }
+
+    return $self->cmp_ok($got, '!=', $dont_expect, $name);
+}
+
+
+=item B<like>
+
+  $Test->like($this, qr/$regex/, $name);
+  $Test->like($this, '/$regex/', $name);
+
+Like Test::More's like().  Checks if $this matches the given $regex.
+
+You'll want to avoid qr// if you want your tests to work before 5.005.
+
+=item B<unlike>
+
+  $Test->unlike($this, qr/$regex/, $name);
+  $Test->unlike($this, '/$regex/', $name);
+
+Like Test::More's unlike().  Checks if $this B<does not match> the
+given $regex.
+
+=cut
+
+sub like {
+    my($self, $this, $regex, $name) = @_;
+
+    local $Level = $Level + 1;
+    $self->_regex_ok($this, $regex, '=~', $name);
+}
+
+sub unlike {
+    my($self, $this, $regex, $name) = @_;
+
+    local $Level = $Level + 1;
+    $self->_regex_ok($this, $regex, '!~', $name);
+}
+
+=item B<maybe_regex>
+
+  $Test->maybe_regex(qr/$regex/);
+  $Test->maybe_regex('/$regex/');
+
+Convenience method for building testing functions that take regular
+expressions as arguments, but need to work before perl 5.005.
+
+Takes a quoted regular expression produced by qr//, or a string
+representing a regular expression.
+
+Returns a Perl value which may be used instead of the corresponding
+regular expression, or undef if it's argument is not recognised.
+
+For example, a version of like(), sans the useful diagnostic messages,
+could be written as:
+
+  sub laconic_like {
+      my ($self, $this, $regex, $name) = @_;
+      my $usable_regex = $self->maybe_regex($regex);
+      die "expecting regex, found '$regex'\n"
+          unless $usable_regex;
+      $self->ok($this =~ m/$usable_regex/, $name);
+  }
+
+=cut
+
+
+sub maybe_regex {
+    my ($self, $regex) = @_;
+    my $usable_regex = undef;
+
+    return $usable_regex unless defined $regex;
+
+    my($re, $opts);
+
+    # Check for qr/foo/
+    if( ref $regex eq 'Regexp' ) {
+        $usable_regex = $regex;
+    }
+    # Check for '/foo/' or 'm,foo,'
+    elsif( ($re, $opts)        = $regex =~ m{^ /(.*)/ (\w*) $ }sx           or
+           (undef, $re, $opts) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
+         )
+    {
+        $usable_regex = length $opts ? "(?$opts)$re" : $re;
+    }
+
+    return $usable_regex;
+};
+
+sub _regex_ok {
+    my($self, $this, $regex, $cmp, $name) = @_;
+
+    local $Level = $Level + 1;
+
+    my $ok = 0;
+    my $usable_regex = $self->maybe_regex($regex);
+    unless (defined $usable_regex) {
+        $ok = $self->ok( 0, $name );
+        $self->diag("    '$regex' doesn't look much like a regex to me.");
+        return $ok;
+    }
+
+    {
+        local $^W = 0;
+        my $test = $this =~ /$usable_regex/ ? 1 : 0;
+        $test = !$test if $cmp eq '!~';
+        $ok = $self->ok( $test, $name );
+    }
+
+    unless( $ok ) {
+        $this = defined $this ? "'$this'" : 'undef';
+        my $match = $cmp eq '=~' ? "doesn't match" : "matches";
+        $self->diag(sprintf <<DIAGNOSTIC, $this, $match, $regex);
+                  %s
+    %13s '%s'
+DIAGNOSTIC
+
+    }
+
+    return $ok;
+}
+
+=item B<cmp_ok>
+
+  $Test->cmp_ok($this, $type, $that, $name);
+
+Works just like Test::More's cmp_ok().
+
+    $Test->cmp_ok($big_num, '!=', $other_big_num);
+
+=cut
+
+sub cmp_ok {
+    my($self, $got, $type, $expect, $name) = @_;
+
+    my $test;
+    {
+        local $^W = 0;
+        local($@,$!);   # don't interfere with $@
+                        # eval() sometimes resets $!
+        $test = eval "\$got $type \$expect";
+    }
+    local $Level = $Level + 1;
+    my $ok = $self->ok($test, $name);
+
+    unless( $ok ) {
+        if( $type =~ /^(eq|==)$/ ) {
+            $self->_is_diag($got, $type, $expect);
+        }
+        else {
+            $self->_cmp_diag($got, $type, $expect);
+        }
+    }
+    return $ok;
+}
+
+sub _cmp_diag {
+    my($self, $got, $type, $expect) = @_;
+    
+    $got    = defined $got    ? "'$got'"    : 'undef';
+    $expect = defined $expect ? "'$expect'" : 'undef';
+    return $self->diag(sprintf <<DIAGNOSTIC, $got, $type, $expect);
+    %s
+        %s
+    %s
+DIAGNOSTIC
+}
+
+=item B<BAILOUT>
+
+    $Test->BAILOUT($reason);
+
+Indicates to the Test::Harness that things are going so badly all
+testing should terminate.  This includes running any additional test
+scripts.
+
+It will exit with 255.
+
+=cut
+
+sub BAILOUT {
+    my($self, $reason) = @_;
+
+    $self->_print("Bail out!  $reason");
+    exit 255;
+}
+
+=item B<skip>
+
+    $Test->skip;
+    $Test->skip($why);
+
+Skips the current test, reporting $why.
+
+=cut
+
+sub skip {
+    my($self, $why) = @_;
+    $why ||= '';
+    $self->_unoverload(\$why);
+
+    unless( $Have_Plan ) {
+        require Carp;
+        Carp::croak("You tried to run tests without a plan!  Gotta have a plan.");
+    }
+
+    lock($Curr_Test);
+    $Curr_Test++;
+
+    $Test_Results[$Curr_Test-1] = &share({
+        'ok'      => 1,
+        actual_ok => 1,
+        name      => '',
+        type      => 'skip',
+        reason    => $why,
+    });
+
+    my $out = "ok";
+    $out   .= " $Curr_Test" if $self->use_numbers;
+    $out   .= " # skip";
+    $out   .= " $why"       if length $why;
+    $out   .= "\n";
+
+    $Test->_print($out);
+
+    return 1;
+}
+
+
+=item B<todo_skip>
+
+  $Test->todo_skip;
+  $Test->todo_skip($why);
+
+Like skip(), only it will declare the test as failing and TODO.  Similar
+to
+
+    print "not ok $tnum # TODO $why\n";
+
+=cut
+
+sub todo_skip {
+    my($self, $why) = @_;
+    $why ||= '';
+
+    unless( $Have_Plan ) {
+        require Carp;
+        Carp::croak("You tried to run tests without a plan!  Gotta have a plan.");
+    }
+
+    lock($Curr_Test);
+    $Curr_Test++;
+
+    $Test_Results[$Curr_Test-1] = &share({
+        'ok'      => 1,
+        actual_ok => 0,
+        name      => '',
+        type      => 'todo_skip',
+        reason    => $why,
+    });
+
+    my $out = "not ok";
+    $out   .= " $Curr_Test" if $self->use_numbers;
+    $out   .= " # TODO & SKIP $why\n";
+
+    $Test->_print($out);
+
+    return 1;
+}
+
+
+=begin _unimplemented
+
+=item B<skip_rest>
+
+  $Test->skip_rest;
+  $Test->skip_rest($reason);
+
+Like skip(), only it skips all the rest of the tests you plan to run
+and terminates the test.
+
+If you're running under no_plan, it skips once and terminates the
+test.
+
+=end _unimplemented
+
+=back
+
+
+=head2 Test style
+
+=over 4
+
+=item B<level>
+
+    $Test->level($how_high);
+
+How far up the call stack should $Test look when reporting where the
+test failed.
+
+Defaults to 1.
+
+Setting $Test::Builder::Level overrides.  This is typically useful
+localized:
+
+    {
+        local $Test::Builder::Level = 2;
+        $Test->ok($test);
+    }
+
+=cut
+
+sub level {
+    my($self, $level) = @_;
+
+    if( defined $level ) {
+        $Level = $level;
+    }
+    return $Level;
+}
+
+
+=item B<use_numbers>
+
+    $Test->use_numbers($on_or_off);
+
+Whether or not the test should output numbers.  That is, this if true:
+
+  ok 1
+  ok 2
+  ok 3
+
+or this if false
+
+  ok
+  ok
+  ok
+
+Most useful when you can't depend on the test output order, such as
+when threads or forking is involved.
+
+Test::Harness will accept either, but avoid mixing the two styles.
+
+Defaults to on.
+
+=cut
+
+sub use_numbers {
+    my($self, $use_nums) = @_;
+
+    if( defined $use_nums ) {
+        $Use_Nums = $use_nums;
+    }
+    return $Use_Nums;
+}
+
+=item B<no_header>
+
+    $Test->no_header($no_header);
+
+If set to true, no "1..N" header will be printed.
+
+=item B<no_ending>
+
+    $Test->no_ending($no_ending);
+
+Normally, Test::Builder does some extra diagnostics when the test
+ends.  It also changes the exit code as described below.
+
+If this is true, none of that will be done.
+
+=cut
+
+sub no_header {
+    my($self, $no_header) = @_;
+
+    if( defined $no_header ) {
+        $No_Header = $no_header;
+    }
+    return $No_Header;
+}
+
+sub no_ending {
+    my($self, $no_ending) = @_;
+
+    if( defined $no_ending ) {
+        $No_Ending = $no_ending;
+    }
+    return $No_Ending;
+}
+
+
+=back
+
+=head2 Output
+
+Controlling where the test output goes.
+
+It's ok for your test to change where STDOUT and STDERR point to,
+Test::Builder's default output settings will not be affected.
+
+=over 4
+
+=item B<diag>
+
+    $Test->diag(@msgs);
+
+Prints out the given @msgs.  Like C<print>, arguments are simply
+appended together.
+
+Normally, it uses the failure_output() handle, but if this is for a
+TODO test, the todo_output() handle is used.
+
+Output will be indented and marked with a # so as not to interfere
+with test output.  A newline will be put on the end if there isn't one
+already.
+
+We encourage using this rather than calling print directly.
+
+Returns false.  Why?  Because diag() is often used in conjunction with
+a failing test (C<ok() || diag()>) it "passes through" the failure.
+
+    return ok(...) || diag(...);
+
+=for blame transfer
+Mark Fowler <mark@twoshortplanks.com>
+
+=cut
+
+sub diag {
+    my($self, @msgs) = @_;
+    return unless @msgs;
+
+    # Prevent printing headers when compiling (i.e. -c)
+    return if $^C;
+
+    # Smash args together like print does.
+    # Convert undef to 'undef' so its readable.
+    my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
+
+    # Escape each line with a #.
+    $msg =~ s/^/# /gm;
+
+    # Stick a newline on the end if it needs it.
+    $msg .= "\n" unless $msg =~ /\n\Z/;
+
+    local $Level = $Level + 1;
+    $self->_print_diag($msg);
+
+    return 0;
+}
+
+=begin _private
+
+=item B<_print>
+
+    $Test->_print(@msgs);
+
+Prints to the output() filehandle.
+
+=end _private
+
+=cut
+
+sub _print {
+    my($self, @msgs) = @_;
+
+    # Prevent printing headers when only compiling.  Mostly for when
+    # tests are deparsed with B::Deparse
+    return if $^C;
+
+    my $msg = join '', @msgs;
+
+    local($\, $", $,) = (undef, ' ', '');
+    my $fh = $self->output;
+
+    # Escape each line after the first with a # so we don't
+    # confuse Test::Harness.
+    $msg =~ s/\n(.)/\n# $1/sg;
+
+    # Stick a newline on the end if it needs it.
+    $msg .= "\n" unless $msg =~ /\n\Z/;
+
+    print $fh $msg;
+}
+
+
+=item B<_print_diag>
+
+    $Test->_print_diag(@msg);
+
+Like _print, but prints to the current diagnostic filehandle.
+
+=cut
+
+sub _print_diag {
+    my $self = shift;
+
+    local($\, $", $,) = (undef, ' ', '');
+    my $fh = $self->todo ? $self->todo_output : $self->failure_output;
+    print $fh @_;
+}    
+
+=item B<output>
+
+    $Test->output($fh);
+    $Test->output($file);
+
+Where normal "ok/not ok" test output should go.
+
+Defaults to STDOUT.
+
+=item B<failure_output>
+
+    $Test->failure_output($fh);
+    $Test->failure_output($file);
+
+Where diagnostic output on test failures and diag() should go.
+
+Defaults to STDERR.
+
+=item B<todo_output>
+
+    $Test->todo_output($fh);
+    $Test->todo_output($file);
+
+Where diagnostics about todo test failures and diag() should go.
+
+Defaults to STDOUT.
+
+=cut
+
+my($Out_FH, $Fail_FH, $Todo_FH);
+sub output {
+    my($self, $fh) = @_;
+
+    if( defined $fh ) {
+        $Out_FH = _new_fh($fh);
+    }
+    return $Out_FH;
+}
+
+sub failure_output {
+    my($self, $fh) = @_;
+
+    if( defined $fh ) {
+        $Fail_FH = _new_fh($fh);
+    }
+    return $Fail_FH;
+}
+
+sub todo_output {
+    my($self, $fh) = @_;
+
+    if( defined $fh ) {
+        $Todo_FH = _new_fh($fh);
+    }
+    return $Todo_FH;
+}
+
+
+sub _new_fh {
+    my($file_or_fh) = shift;
+
+    my $fh;
+    if( _is_fh($file_or_fh) ) {
+        $fh = $file_or_fh;
+    }
+    else {
+        $fh = do { local *FH };
+        open $fh, ">$file_or_fh" or 
+            die "Can't open test output log $file_or_fh: $!";
+    }
+
+    return $fh;
+}
+
+
+sub _is_fh {
+    my $maybe_fh = shift;
+
+    return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
+
+    return UNIVERSAL::isa($maybe_fh,               'GLOB')       ||
+           UNIVERSAL::isa($maybe_fh,               'IO::Handle') ||
+
+           # 5.5.4's tied() and can() doesn't like getting undef
+           UNIVERSAL::can((tied($maybe_fh) || ''), 'TIEHANDLE');
+}
+
+
+sub _autoflush {
+    my($fh) = shift;
+    my $old_fh = select $fh;
+    $| = 1;
+    select $old_fh;
+}
+
+
+my $Opened_Testhandles = 0;
+sub _dup_stdhandles {
+    my $self = shift;
+
+    $self->_open_testhandles unless $Opened_Testhandles;
+
+    # Set everything to unbuffered else plain prints to STDOUT will
+    # come out in the wrong order from our own prints.
+    _autoflush(\*TESTOUT);
+    _autoflush(\*STDOUT);
+    _autoflush(\*TESTERR);
+    _autoflush(\*STDERR);
+
+    $Test->output(\*TESTOUT);
+    $Test->failure_output(\*TESTERR);
+    $Test->todo_output(\*TESTOUT);
+}
+
+sub _open_testhandles {
+    # We dup STDOUT and STDERR so people can change them in their
+    # test suites while still getting normal test output.
+    open(TESTOUT, ">&STDOUT") or die "Can't dup STDOUT:  $!";
+    open(TESTERR, ">&STDERR") or die "Can't dup STDERR:  $!";
+    $Opened_Testhandles = 1;
+}
+
+
+=back
+
+
+=head2 Test Status and Info
+
+=over 4
+
+=item B<current_test>
+
+    my $curr_test = $Test->current_test;
+    $Test->current_test($num);
+
+Gets/sets the current test number we're on.  You usually shouldn't
+have to set this.
+
+If set forward, the details of the missing tests are filled in as 'unknown'.
+if set backward, the details of the intervening tests are deleted.  You
+can erase history if you really want to.
+
+=cut
+
+sub current_test {
+    my($self, $num) = @_;
+
+    lock($Curr_Test);
+    if( defined $num ) {
+        unless( $Have_Plan ) {
+            require Carp;
+            Carp::croak("Can't change the current test number without a plan!");
+        }
+
+        $Curr_Test = $num;
+
+        # If the test counter is being pushed forward fill in the details.
+        if( $num > @Test_Results ) {
+            my $start = @Test_Results ? $#Test_Results + 1 : 0;
+            for ($start..$num-1) {
+                $Test_Results[$_] = &share({
+                    'ok'      => 1, 
+                    actual_ok => undef, 
+                    reason    => 'incrementing test number', 
+                    type      => 'unknown', 
+                    name      => undef 
+                });
+            }
+        }
+        # If backward, wipe history.  Its their funeral.
+        elsif( $num < @Test_Results ) {
+            $#Test_Results = $num - 1;
+        }
+    }
+    return $Curr_Test;
+}
+
+
+=item B<summary>
+
+    my @tests = $Test->summary;
+
+A simple summary of the tests so far.  True for pass, false for fail.
+This is a logical pass/fail, so todos are passes.
+
+Of course, test #1 is $tests[0], etc...
+
+=cut
+
+sub summary {
+    my($self) = shift;
+
+    return map { $_->{'ok'} } @Test_Results;
+}
+
+=item B<details>
+
+    my @tests = $Test->details;
+
+Like summary(), but with a lot more detail.
+
+    $tests[$test_num - 1] = 
+            { 'ok'       => is the test considered a pass?
+              actual_ok  => did it literally say 'ok'?
+              name       => name of the test (if any)
+              type       => type of test (if any, see below).
+              reason     => reason for the above (if any)
+            };
+
+'ok' is true if Test::Harness will consider the test to be a pass.
+
+'actual_ok' is a reflection of whether or not the test literally
+printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
+tests.  
+
+'name' is the name of the test.
+
+'type' indicates if it was a special test.  Normal tests have a type
+of ''.  Type can be one of the following:
+
+    skip        see skip()
+    todo        see todo()
+    todo_skip   see todo_skip()
+    unknown     see below
+
+Sometimes the Test::Builder test counter is incremented without it
+printing any test output, for example, when current_test() is changed.
+In these cases, Test::Builder doesn't know the result of the test, so
+it's type is 'unkown'.  These details for these tests are filled in.
+They are considered ok, but the name and actual_ok is left undef.
+
+For example "not ok 23 - hole count # TODO insufficient donuts" would
+result in this structure:
+
+    $tests[22] =    # 23 - 1, since arrays start from 0.
+      { ok        => 1,   # logically, the test passed since it's todo
+        actual_ok => 0,   # in absolute terms, it failed
+        name      => 'hole count',
+        type      => 'todo',
+        reason    => 'insufficient donuts'
+      };
+
+=cut
+
+sub details {
+    return @Test_Results;
+}
+
+=item B<todo>
+
+    my $todo_reason = $Test->todo;
+    my $todo_reason = $Test->todo($pack);
+
+todo() looks for a $TODO variable in your tests.  If set, all tests
+will be considered 'todo' (see Test::More and Test::Harness for
+details).  Returns the reason (ie. the value of $TODO) if running as
+todo tests, false otherwise.
+
+todo() is pretty part about finding the right package to look for
+$TODO in.  It uses the exported_to() package to find it.  If that's
+not set, it's pretty good at guessing the right package to look at.
+
+Sometimes there is some confusion about where todo() should be looking
+for the $TODO variable.  If you want to be sure, tell it explicitly
+what $pack to use.
+
+=cut
+
+sub todo {
+    my($self, $pack) = @_;
+
+    $pack = $pack || $self->exported_to || $self->caller(1);
+
+    no strict 'refs';
+    return defined ${$pack.'::TODO'} ? ${$pack.'::TODO'}
+                                     : 0;
+}
+
+=item B<caller>
+
+    my $package = $Test->caller;
+    my($pack, $file, $line) = $Test->caller;
+    my($pack, $file, $line) = $Test->caller($height);
+
+Like the normal caller(), except it reports according to your level().
+
+=cut
+
+sub caller {
+    my($self, $height) = @_;
+    $height ||= 0;
+
+    my @caller = CORE::caller($self->level + $height + 1);
+    return wantarray ? @caller : $caller[0];
+}
+
+=back
+
+=cut
+
+=begin _private
+
+=over 4
+
+=item B<_sanity_check>
+
+  _sanity_check();
+
+Runs a bunch of end of test sanity checks to make sure reality came
+through ok.  If anything is wrong it will die with a fairly friendly
+error message.
+
+=cut
+
+#'#
+sub _sanity_check {
+    _whoa($Curr_Test < 0,  'Says here you ran a negative number of tests!');
+    _whoa(!$Have_Plan and $Curr_Test, 
+          'Somehow your tests ran without a plan!');
+    _whoa($Curr_Test != @Test_Results,
+          'Somehow you got a different number of results than tests ran!');
+}
+
+=item B<_whoa>
+
+  _whoa($check, $description);
+
+A sanity check, similar to assert().  If the $check is true, something
+has gone horribly wrong.  It will die with the given $description and
+a note to contact the author.
+
+=cut
+
+sub _whoa {
+    my($check, $desc) = @_;
+    if( $check ) {
+        die <<WHOA;
+WHOA!  $desc
+This should never happen!  Please contact the author immediately!
+WHOA
+    }
+}
+
+=item B<_my_exit>
+
+  _my_exit($exit_num);
+
+Perl seems to have some trouble with exiting inside an END block.  5.005_03
+and 5.6.1 both seem to do odd things.  Instead, this function edits $?
+directly.  It should ONLY be called from inside an END block.  It
+doesn't actually exit, that's your job.
+
+=cut
+
+sub _my_exit {
+    $? = $_[0];
+
+    return 1;
+}
+
+
+=back
+
+=end _private
+
+=cut
+
+$SIG{__DIE__} = sub {
+    # We don't want to muck with death in an eval, but $^S isn't
+    # totally reliable.  5.005_03 and 5.6.1 both do the wrong thing
+    # with it.  Instead, we use caller.  This also means it runs under
+    # 5.004!
+    my $in_eval = 0;
+    for( my $stack = 1;  my $sub = (CORE::caller($stack))[3];  $stack++ ) {
+        $in_eval = 1 if $sub =~ /^\(eval\)/;
+    }
+    $Test_Died = 1 unless $in_eval;
+};
+
+sub _ending {
+    my $self = shift;
+
+    _sanity_check();
+
+    # Don't bother with an ending if this is a forked copy.  Only the parent
+    # should do the ending.
+    do{ _my_exit($?) && return } if $Original_Pid != $$;
+
+    # Bailout if plan() was never called.  This is so
+    # "require Test::Simple" doesn't puke.
+    do{ _my_exit(0) && return } if !$Have_Plan && !$Test_Died;
+
+    # Figure out if we passed or failed and print helpful messages.
+    if( @Test_Results ) {
+        # The plan?  We have no plan.
+        if( $No_Plan ) {
+            $self->_print("1..$Curr_Test\n") unless $self->no_header;
+            $Expected_Tests = $Curr_Test;
+        }
+
+        # Auto-extended arrays and elements which aren't explicitly
+        # filled in with a shared reference will puke under 5.8.0
+        # ithreads.  So we have to fill them in by hand. :(
+        my $empty_result = &share({});
+        for my $idx ( 0..$Expected_Tests-1 ) {
+            $Test_Results[$idx] = $empty_result
+              unless defined $Test_Results[$idx];
+        }
+
+        my $num_failed = grep !$_->{'ok'}, @Test_Results[0..$Expected_Tests-1];
+        $num_failed += abs($Expected_Tests - @Test_Results);
+
+        if( $Curr_Test < $Expected_Tests ) {
+            my $s = $Expected_Tests == 1 ? '' : 's';
+            $self->diag(<<"FAIL");
+Looks like you planned $Expected_Tests test$s but only ran $Curr_Test.
+FAIL
+        }
+        elsif( $Curr_Test > $Expected_Tests ) {
+            my $num_extra = $Curr_Test - $Expected_Tests;
+            my $s = $Expected_Tests == 1 ? '' : 's';
+            $self->diag(<<"FAIL");
+Looks like you planned $Expected_Tests test$s but ran $num_extra extra.
+FAIL
+        }
+        elsif ( $num_failed ) {
+            my $s = $num_failed == 1 ? '' : 's';
+            $self->diag(<<"FAIL");
+Looks like you failed $num_failed test$s of $Expected_Tests.
+FAIL
+        }
+
+        if( $Test_Died ) {
+            $self->diag(<<"FAIL");
+Looks like your test died just after $Curr_Test.
+FAIL
+
+            _my_exit( 255 ) && return;
+        }
+
+        _my_exit( $num_failed <= 254 ? $num_failed : 254  ) && return;
+    }
+    elsif ( $Skip_All ) {
+        _my_exit( 0 ) && return;
+    }
+    elsif ( $Test_Died ) {
+        $self->diag(<<'FAIL');
+Looks like your test died before it could output anything.
+FAIL
+        _my_exit( 255 ) && return;
+    }
+    else {
+        $self->diag("No tests run!\n");
+        _my_exit( 255 ) && return;
+    }
+}
+
+END {
+    $Test->_ending if defined $Test and !$Test->no_ending;
+}
+
+=head1 EXIT CODES
+
+If all your tests passed, Test::Builder will exit with zero (which is
+normal).  If anything failed it will exit with how many failed.  If
+you run less (or more) tests than you planned, the missing (or extras)
+will be considered failures.  If no tests were ever run Test::Builder
+will throw a warning and exit with 255.  If the test died, even after
+having successfully completed all its tests, it will still be
+considered a failure and will exit with 255.
+
+So the exit codes are...
+
+    0                   all tests successful
+    255                 test died
+    any other number    how many failed (including missing or extras)
+
+If you fail more than 254 tests, it will be reported as 254.
+
+
+=head1 THREADS
+
+In perl 5.8.0 and later, Test::Builder is thread-safe.  The test
+number is shared amongst all threads.  This means if one thread sets
+the test number using current_test() they will all be effected.
+
+Test::Builder is only thread-aware if threads.pm is loaded I<before>
+Test::Builder.
+
+=head1 EXAMPLES
+
+CPAN can provide the best examples.  Test::Simple, Test::More,
+Test::Exception and Test::Differences all use Test::Builder.
+
+=head1 SEE ALSO
+
+Test::Simple, Test::More, Test::Harness
+
+=head1 AUTHORS
+
+Original code by chromatic, maintained by Michael G Schwern
+E<lt>schwern@pobox.comE<gt>
+
+=head1 COPYRIGHT
+
+Copyright 2002, 2004 by chromatic E<lt>chromatic@wgz.orgE<gt> and
+                        Michael G Schwern E<lt>schwern@pobox.comE<gt>.
+
+This program is free software; you can redistribute it and/or 
+modify it under the same terms as Perl itself.
+
+See F<http://www.perl.com/perl/misc/Artistic.html>
+
+=cut
+
+1;
diff --git a/trunk/Examples/test-suite/perl5/Test/More.pm b/trunk/Examples/test-suite/perl5/Test/More.pm
new file mode 100644
index 0000000..aa02808
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/Test/More.pm
@@ -0,0 +1,1448 @@
+package Test::More;
+
+use 5.004;
+
+use strict;
+use Test::Builder;
+
+
+# Can't use Carp because it might cause use_ok() to accidentally succeed
+# even though the module being used forgot to use Carp.  Yes, this
+# actually happened.
+sub _carp {
+    my($file, $line) = (caller(1))[1,2];
+    warn @_, " at $file line $line\n";
+}
+
+
+
+require Exporter;
+use vars qw($VERSION @ISA @EXPORT %EXPORT_TAGS $TODO);
+$VERSION = '0.54';
+$VERSION = eval $VERSION;    # make the alpha version come out as a number
+
+@ISA    = qw(Exporter);
+@EXPORT = qw(ok use_ok require_ok
+             is isnt like unlike is_deeply
+             cmp_ok
+             skip todo todo_skip
+             pass fail
+             eq_array eq_hash eq_set
+             $TODO
+             plan
+             can_ok  isa_ok
+             diag
+            );
+
+my $Test = Test::Builder->new;
+my $Show_Diag = 1;
+
+
+# 5.004's Exporter doesn't have export_to_level.
+sub _export_to_level
+{
+      my $pkg = shift;
+      my $level = shift;
+      (undef) = shift;                  # redundant arg
+      my $callpkg = caller($level);
+      $pkg->export($callpkg, @_);
+}
+
+
+=head1 NAME
+
+Test::More - yet another framework for writing test scripts
+
+=head1 SYNOPSIS
+
+  use Test::More tests => $Num_Tests;
+  # or
+  use Test::More qw(no_plan);
+  # or
+  use Test::More skip_all => $reason;
+
+  BEGIN { use_ok( 'Some::Module' ); }
+  require_ok( 'Some::Module' );
+
+  # Various ways to say "ok"
+  ok($this eq $that, $test_name);
+
+  is  ($this, $that,    $test_name);
+  isnt($this, $that,    $test_name);
+
+  # Rather than print STDERR "# here's what went wrong\n"
+  diag("here's what went wrong");
+
+  like  ($this, qr/that/, $test_name);
+  unlike($this, qr/that/, $test_name);
+
+  cmp_ok($this, '==', $that, $test_name);
+
+  is_deeply($complex_structure1, $complex_structure2, $test_name);
+
+  SKIP: {
+      skip $why, $how_many unless $have_some_feature;
+
+      ok( foo(),       $test_name );
+      is( foo(42), 23, $test_name );
+  };
+
+  TODO: {
+      local $TODO = $why;
+
+      ok( foo(),       $test_name );
+      is( foo(42), 23, $test_name );
+  };
+
+  can_ok($module, @methods);
+  isa_ok($object, $class);
+
+  pass($test_name);
+  fail($test_name);
+
+  # Utility comparison functions.
+  eq_array(\@this, \@that);
+  eq_hash(\%this, \%that);
+  eq_set(\@this, \@that);
+
+  # UNIMPLEMENTED!!!
+  my @status = Test::More::status;
+
+  # UNIMPLEMENTED!!!
+  BAIL_OUT($why);
+
+
+=head1 DESCRIPTION
+
+B<STOP!> If you're just getting started writing tests, have a look at
+Test::Simple first.  This is a drop in replacement for Test::Simple
+which you can switch to once you get the hang of basic testing.
+
+The purpose of this module is to provide a wide range of testing
+utilities.  Various ways to say "ok" with better diagnostics,
+facilities to skip tests, test future features and compare complicated
+data structures.  While you can do almost anything with a simple
+C<ok()> function, it doesn't provide good diagnostic output.
+
+
+=head2 I love it when a plan comes together
+
+Before anything else, you need a testing plan.  This basically declares
+how many tests your script is going to run to protect against premature
+failure.
+
+The preferred way to do this is to declare a plan when you C<use Test::More>.
+
+  use Test::More tests => $Num_Tests;
+
+There are rare cases when you will not know beforehand how many tests
+your script is going to run.  In this case, you can declare that you
+have no plan.  (Try to avoid using this as it weakens your test.)
+
+  use Test::More qw(no_plan);
+
+B<NOTE>: using no_plan requires a Test::Harness upgrade else it will
+think everything has failed.  See L<BUGS and CAVEATS>)
+
+In some cases, you'll want to completely skip an entire testing script.
+
+  use Test::More skip_all => $skip_reason;
+
+Your script will declare a skip with the reason why you skipped and
+exit immediately with a zero (success).  See L<Test::Harness> for
+details.
+
+If you want to control what functions Test::More will export, you
+have to use the 'import' option.  For example, to import everything
+but 'fail', you'd do:
+
+  use Test::More tests => 23, import => ['!fail'];
+
+Alternatively, you can use the plan() function.  Useful for when you
+have to calculate the number of tests.
+
+  use Test::More;
+  plan tests => keys %Stuff * 3;
+
+or for deciding between running the tests at all:
+
+  use Test::More;
+  if( $^O eq 'MacOS' ) {
+      plan skip_all => 'Test irrelevant on MacOS';
+  }
+  else {
+      plan tests => 42;
+  }
+
+=cut
+
+sub plan {
+    my(@plan) = @_;
+
+    my $idx = 0;
+    my @cleaned_plan;
+    while( $idx <= $#plan ) {
+        my $item = $plan[$idx];
+
+        if( $item eq 'no_diag' ) {
+            $Show_Diag = 0;
+        }
+        else {
+            push @cleaned_plan, $item;
+        }
+
+        $idx++;
+    }
+
+    $Test->plan(@cleaned_plan);
+}
+
+sub import {
+    my($class) = shift;
+
+    my $caller = caller;
+
+    $Test->exported_to($caller);
+
+    my $idx = 0;
+    my @plan;
+    my @imports;
+    while( $idx <= $#_ ) {
+        my $item = $_[$idx];
+
+        if( $item eq 'import' ) {
+            push @imports, @{$_[$idx+1]};
+            $idx++;
+        }
+        else {
+            push @plan, $item;
+        }
+
+        $idx++;
+    }
+
+    plan(@plan);
+
+    __PACKAGE__->_export_to_level(1, __PACKAGE__, @imports);
+}
+
+
+=head2 Test names
+
+By convention, each test is assigned a number in order.  This is
+largely done automatically for you.  However, it's often very useful to
+assign a name to each test.  Which would you rather see:
+
+  ok 4
+  not ok 5
+  ok 6
+
+or
+
+  ok 4 - basic multi-variable
+  not ok 5 - simple exponential
+  ok 6 - force == mass * acceleration
+
+The later gives you some idea of what failed.  It also makes it easier
+to find the test in your script, simply search for "simple
+exponential".
+
+All test functions take a name argument.  It's optional, but highly
+suggested that you use it.
+
+
+=head2 I'm ok, you're not ok.
+
+The basic purpose of this module is to print out either "ok #" or "not
+ok #" depending on if a given test succeeded or failed.  Everything
+else is just gravy.
+
+All of the following print "ok" or "not ok" depending on if the test
+succeeded or failed.  They all also return true or false,
+respectively.
+
+=over 4
+
+=item B<ok>
+
+  ok($this eq $that, $test_name);
+
+This simply evaluates any expression (C<$this eq $that> is just a
+simple example) and uses that to determine if the test succeeded or
+failed.  A true expression passes, a false one fails.  Very simple.
+
+For example:
+
+    ok( $exp{9} == 81,                   'simple exponential' );
+    ok( Film->can('db_Main'),            'set_db()' );
+    ok( $p->tests == 4,                  'saw tests' );
+    ok( !grep !defined $_, @items,       'items populated' );
+
+(Mnemonic:  "This is ok.")
+
+$test_name is a very short description of the test that will be printed
+out.  It makes it very easy to find a test in your script when it fails
+and gives others an idea of your intentions.  $test_name is optional,
+but we B<very> strongly encourage its use.
+
+Should an ok() fail, it will produce some diagnostics:
+
+    not ok 18 - sufficient mucus
+    #     Failed test 18 (foo.t at line 42)
+
+This is actually Test::Simple's ok() routine.
+
+=cut
+
+sub ok ($;$) {
+    my($test, $name) = @_;
+    $Test->ok($test, $name);
+}
+
+=item B<is>
+
+=item B<isnt>
+
+  is  ( $this, $that, $test_name );
+  isnt( $this, $that, $test_name );
+
+Similar to ok(), is() and isnt() compare their two arguments
+with C<eq> and C<ne> respectively and use the result of that to
+determine if the test succeeded or failed.  So these:
+
+    # Is the ultimate answer 42?
+    is( ultimate_answer(), 42,          "Meaning of Life" );
+
+    # $foo isn't empty
+    isnt( $foo, '',     "Got some foo" );
+
+are similar to these:
+
+    ok( ultimate_answer() eq 42,        "Meaning of Life" );
+    ok( $foo ne '',     "Got some foo" );
+
+(Mnemonic:  "This is that."  "This isn't that.")
+
+So why use these?  They produce better diagnostics on failure.  ok()
+cannot know what you are testing for (beyond the name), but is() and
+isnt() know what the test was and why it failed.  For example this
+test:
+
+    my $foo = 'waffle';  my $bar = 'yarblokos';
+    is( $foo, $bar,   'Is foo the same as bar?' );
+
+Will produce something like this:
+
+    not ok 17 - Is foo the same as bar?
+    #     Failed test (foo.t at line 139)
+    #          got: 'waffle'
+    #     expected: 'yarblokos'
+
+So you can figure out what went wrong without rerunning the test.
+
+You are encouraged to use is() and isnt() over ok() where possible,
+however do not be tempted to use them to find out if something is
+true or false!
+
+  # XXX BAD!
+  is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
+
+This does not check if C<exists $brooklyn{tree}> is true, it checks if
+it returns 1.  Very different.  Similar caveats exist for false and 0.
+In these cases, use ok().
+
+  ok( exists $brooklyn{tree},    'A tree grows in Brooklyn' );
+
+For those grammatical pedants out there, there's an C<isn't()>
+function which is an alias of isnt().
+
+=cut
+
+sub is ($$;$) {
+    $Test->is_eq(@_);
+}
+
+sub isnt ($$;$) {
+    $Test->isnt_eq(@_);
+}
+
+*isn't = \&isnt;
+
+
+=item B<like>
+
+  like( $this, qr/that/, $test_name );
+
+Similar to ok(), like() matches $this against the regex C<qr/that/>.
+
+So this:
+
+    like($this, qr/that/, 'this is like that');
+
+is similar to:
+
+    ok( $this =~ /that/, 'this is like that');
+
+(Mnemonic "This is like that".)
+
+The second argument is a regular expression.  It may be given as a
+regex reference (i.e. C<qr//>) or (for better compatibility with older
+perls) as a string that looks like a regex (alternative delimiters are
+currently not supported):
+
+    like( $this, '/that/', 'this is like that' );
+
+Regex options may be placed on the end (C<'/that/i'>).
+
+Its advantages over ok() are similar to that of is() and isnt().  Better
+diagnostics on failure.
+
+=cut
+
+sub like ($$;$) {
+    $Test->like(@_);
+}
+
+
+=item B<unlike>
+
+  unlike( $this, qr/that/, $test_name );
+
+Works exactly as like(), only it checks if $this B<does not> match the
+given pattern.
+
+=cut
+
+sub unlike ($$;$) {
+    $Test->unlike(@_);
+}
+
+
+=item B<cmp_ok>
+
+  cmp_ok( $this, $op, $that, $test_name );
+
+Halfway between ok() and is() lies cmp_ok().  This allows you to
+compare two arguments using any binary perl operator.
+
+    # ok( $this eq $that );
+    cmp_ok( $this, 'eq', $that, 'this eq that' );
+
+    # ok( $this == $that );
+    cmp_ok( $this, '==', $that, 'this == that' );
+
+    # ok( $this && $that );
+    cmp_ok( $this, '&&', $that, 'this && that' );
+    ...etc...
+
+Its advantage over ok() is when the test fails you'll know what $this
+and $that were:
+
+    not ok 1
+    #     Failed test (foo.t at line 12)
+    #     '23'
+    #         &&
+    #     undef
+
+It's also useful in those cases where you are comparing numbers and
+is()'s use of C<eq> will interfere:
+
+    cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
+
+=cut
+
+sub cmp_ok($$$;$) {
+    $Test->cmp_ok(@_);
+}
+
+
+=item B<can_ok>
+
+  can_ok($module, @methods);
+  can_ok($object, @methods);
+
+Checks to make sure the $module or $object can do these @methods
+(works with functions, too).
+
+    can_ok('Foo', qw(this that whatever));
+
+is almost exactly like saying:
+
+    ok( Foo->can('this') && 
+        Foo->can('that') && 
+        Foo->can('whatever') 
+      );
+
+only without all the typing and with a better interface.  Handy for
+quickly testing an interface.
+
+No matter how many @methods you check, a single can_ok() call counts
+as one test.  If you desire otherwise, use:
+
+    foreach my $meth (@methods) {
+        can_ok('Foo', $meth);
+    }
+
+=cut
+
+sub can_ok ($@) {
+    my($proto, @methods) = @_;
+    my $class = ref $proto || $proto;
+
+    unless( @methods ) {
+        my $ok = $Test->ok( 0, "$class->can(...)" );
+        $Test->diag('    can_ok() called with no methods');
+        return $ok;
+    }
+
+    my @nok = ();
+    foreach my $method (@methods) {
+        local($!, $@);  # don't interfere with caller's $@
+                        # eval sometimes resets $!
+        eval { $proto->can($method) } || push @nok, $method;
+    }
+
+    my $name;
+    $name = @methods == 1 ? "$class->can('$methods[0]')" 
+                          : "$class->can(...)";
+    
+    my $ok = $Test->ok( !@nok, $name );
+
+    $Test->diag(map "    $class->can('$_') failed\n", @nok);
+
+    return $ok;
+}
+
+=item B<isa_ok>
+
+  isa_ok($object, $class, $object_name);
+  isa_ok($ref,    $type,  $ref_name);
+
+Checks to see if the given C<< $object->isa($class) >>.  Also checks to make
+sure the object was defined in the first place.  Handy for this sort
+of thing:
+
+    my $obj = Some::Module->new;
+    isa_ok( $obj, 'Some::Module' );
+
+where you'd otherwise have to write
+
+    my $obj = Some::Module->new;
+    ok( defined $obj && $obj->isa('Some::Module') );
+
+to safeguard against your test script blowing up.
+
+It works on references, too:
+
+    isa_ok( $array_ref, 'ARRAY' );
+
+The diagnostics of this test normally just refer to 'the object'.  If
+you'd like them to be more specific, you can supply an $object_name
+(for example 'Test customer').
+
+=cut
+
+sub isa_ok ($$;$) {
+    my($object, $class, $obj_name) = @_;
+
+    my $diag;
+    $obj_name = 'The object' unless defined $obj_name;
+    my $name = "$obj_name isa $class";
+    if( !defined $object ) {
+        $diag = "$obj_name isn't defined";
+    }
+    elsif( !ref $object ) {
+        $diag = "$obj_name isn't a reference";
+    }
+    else {
+        # We can't use UNIVERSAL::isa because we want to honor isa() overrides
+        local($@, $!);  # eval sometimes resets $!
+        my $rslt = eval { $object->isa($class) };
+        if( $@ ) {
+            if( $@ =~ /^Can't call method "isa" on unblessed reference/ ) {
+                if( !UNIVERSAL::isa($object, $class) ) {
+                    my $ref = ref $object;
+                    $diag = "$obj_name isn't a '$class' it's a '$ref'";
+                }
+            } else {
+                die <<WHOA;
+WHOA! I tried to call ->isa on your object and got some weird error.
+This should never happen.  Please contact the author immediately.
+Here's the error.
+$@
+WHOA
+            }
+        }
+        elsif( !$rslt ) {
+            my $ref = ref $object;
+            $diag = "$obj_name isn't a '$class' it's a '$ref'";
+        }
+    }
+            
+      
+
+    my $ok;
+    if( $diag ) {
+        $ok = $Test->ok( 0, $name );
+        $Test->diag("    $diag\n");
+    }
+    else {
+        $ok = $Test->ok( 1, $name );
+    }
+
+    return $ok;
+}
+
+
+=item B<pass>
+
+=item B<fail>
+
+  pass($test_name);
+  fail($test_name);
+
+Sometimes you just want to say that the tests have passed.  Usually
+the case is you've got some complicated condition that is difficult to
+wedge into an ok().  In this case, you can simply use pass() (to
+declare the test ok) or fail (for not ok).  They are synonyms for
+ok(1) and ok(0).
+
+Use these very, very, very sparingly.
+
+=cut
+
+sub pass (;$) {
+    $Test->ok(1, @_);
+}
+
+sub fail (;$) {
+    $Test->ok(0, @_);
+}
+
+=back
+
+=head2 Diagnostics
+
+If you pick the right test function, you'll usually get a good idea of
+what went wrong when it failed.  But sometimes it doesn't work out
+that way.  So here we have ways for you to write your own diagnostic
+messages which are safer than just C<print STDERR>.
+
+=over 4
+
+=item B<diag>
+
+  diag(@diagnostic_message);
+
+Prints a diagnostic message which is guaranteed not to interfere with
+test output.  Like C<print> @diagnostic_message is simply concatinated
+together.
+
+Handy for this sort of thing:
+
+    ok( grep(/foo/, @users), "There's a foo user" ) or
+        diag("Since there's no foo, check that /etc/bar is set up right");
+
+which would produce:
+
+    not ok 42 - There's a foo user
+    #     Failed test (foo.t at line 52)
+    # Since there's no foo, check that /etc/bar is set up right.
+
+You might remember C<ok() or diag()> with the mnemonic C<open() or
+die()>.
+
+All diag()s can be made silent by passing the "no_diag" option to
+Test::More.  C<use Test::More tests => 1, 'no_diag'>.  This is useful
+if you have diagnostics for personal testing but then wish to make
+them silent for release without commenting out each individual
+statement.
+
+B<NOTE> The exact formatting of the diagnostic output is still
+changing, but it is guaranteed that whatever you throw at it it won't
+interfere with the test.
+
+=cut
+
+sub diag {
+    return unless $Show_Diag;
+    $Test->diag(@_);
+}
+
+
+=back
+
+=head2 Module tests
+
+You usually want to test if the module you're testing loads ok, rather
+than just vomiting if its load fails.  For such purposes we have
+C<use_ok> and C<require_ok>.
+
+=over 4
+
+=item B<use_ok>
+
+   BEGIN { use_ok($module); }
+   BEGIN { use_ok($module, @imports); }
+
+These simply use the given $module and test to make sure the load
+happened ok.  It's recommended that you run use_ok() inside a BEGIN
+block so its functions are exported at compile-time and prototypes are
+properly honored.
+
+If @imports are given, they are passed through to the use.  So this:
+
+   BEGIN { use_ok('Some::Module', qw(foo bar)) }
+
+is like doing this:
+
+   use Some::Module qw(foo bar);
+
+Version numbers can be checked like so:
+
+   # Just like "use Some::Module 1.02"
+   BEGIN { use_ok('Some::Module', 1.02) }
+
+Don't try to do this:
+
+   BEGIN {
+       use_ok('Some::Module');
+
+       ...some code that depends on the use...
+       ...happening at compile time...
+   }
+
+because the notion of "compile-time" is relative.  Instead, you want:
+
+  BEGIN { use_ok('Some::Module') }
+  BEGIN { ...some code that depends on the use... }
+
+
+=cut
+
+sub use_ok ($;@) {
+    my($module, @imports) = @_;
+    @imports = () unless @imports;
+
+    my($pack,$filename,$line) = caller;
+
+    local($@,$!);   # eval sometimes interferes with $!
+
+    if( @imports == 1 and $imports[0] =~ /^\d+(?:\.\d+)?$/ ) {
+        # probably a version check.  Perl needs to see the bare number
+        # for it to work with non-Exporter based modules.
+        eval <<USE;
+package $pack;
+use $module $imports[0];
+USE
+    }
+    else {
+        eval <<USE;
+package $pack;
+use $module \@imports;
+USE
+    }
+
+    my $ok = $Test->ok( !$@, "use $module;" );
+
+    unless( $ok ) {
+        chomp $@;
+        $@ =~ s{^BEGIN failed--compilation aborted at .*$}
+                {BEGIN failed--compilation aborted at $filename line $line.}m;
+        $Test->diag(<<DIAGNOSTIC);
+    Tried to use '$module'.
+    Error:  $@
+DIAGNOSTIC
+
+    }
+
+    return $ok;
+}
+
+=item B<require_ok>
+
+   require_ok($module);
+   require_ok($file);
+
+Like use_ok(), except it requires the $module or $file.
+
+=cut
+
+sub require_ok ($) {
+    my($module) = shift;
+
+    my $pack = caller;
+
+    # Try to deterine if we've been given a module name or file.
+    # Module names must be barewords, files not.
+    $module = qq['$module'] unless _is_module_name($module);
+
+    local($!, $@); # eval sometimes interferes with $!
+    eval <<REQUIRE;
+package $pack;
+require $module;
+REQUIRE
+
+    my $ok = $Test->ok( !$@, "require $module;" );
+
+    unless( $ok ) {
+        chomp $@;
+        $Test->diag(<<DIAGNOSTIC);
+    Tried to require '$module'.
+    Error:  $@
+DIAGNOSTIC
+
+    }
+
+    return $ok;
+}
+
+
+sub _is_module_name {
+    my $module = shift;
+
+    # Module names start with a letter.
+    # End with an alphanumeric.
+    # The rest is an alphanumeric or ::
+    $module =~ s/\b::\b//g;
+    $module =~ /^[a-zA-Z]\w+$/;
+}
+
+=back
+
+=head2 Conditional tests
+
+Sometimes running a test under certain conditions will cause the
+test script to die.  A certain function or method isn't implemented
+(such as fork() on MacOS), some resource isn't available (like a 
+net connection) or a module isn't available.  In these cases it's
+necessary to skip tests, or declare that they are supposed to fail
+but will work in the future (a todo test).
+
+For more details on the mechanics of skip and todo tests see
+L<Test::Harness>.
+
+The way Test::More handles this is with a named block.  Basically, a
+block of tests which can be skipped over or made todo.  It's best if I
+just show you...
+
+=over 4
+
+=item B<SKIP: BLOCK>
+
+  SKIP: {
+      skip $why, $how_many if $condition;
+
+      ...normal testing code goes here...
+  }
+
+This declares a block of tests that might be skipped, $how_many tests
+there are, $why and under what $condition to skip them.  An example is
+the easiest way to illustrate:
+
+    SKIP: {
+        eval { require HTML::Lint };
+
+        skip "HTML::Lint not installed", 2 if $@;
+
+        my $lint = new HTML::Lint;
+        isa_ok( $lint, "HTML::Lint" );
+
+        $lint->parse( $html );
+        is( $lint->errors, 0, "No errors found in HTML" );
+    }
+
+If the user does not have HTML::Lint installed, the whole block of
+code I<won't be run at all>.  Test::More will output special ok's
+which Test::Harness interprets as skipped, but passing, tests.
+
+It's important that $how_many accurately reflects the number of tests
+in the SKIP block so the # of tests run will match up with your plan.
+If your plan is C<no_plan> $how_many is optional and will default to 1.
+
+It's perfectly safe to nest SKIP blocks.  Each SKIP block must have
+the label C<SKIP>, or Test::More can't work its magic.
+
+You don't skip tests which are failing because there's a bug in your
+program, or for which you don't yet have code written.  For that you
+use TODO.  Read on.
+
+=cut
+
+#'#
+sub skip {
+    my($why, $how_many) = @_;
+
+    unless( defined $how_many ) {
+        # $how_many can only be avoided when no_plan is in use.
+        _carp "skip() needs to know \$how_many tests are in the block"
+          unless $Test->has_plan eq 'no_plan';
+        $how_many = 1;
+    }
+
+    for( 1..$how_many ) {
+        $Test->skip($why);
+    }
+
+    local $^W = 0;
+    last SKIP;
+}
+
+
+=item B<TODO: BLOCK>
+
+    TODO: {
+        local $TODO = $why if $condition;
+
+        ...normal testing code goes here...
+    }
+
+Declares a block of tests you expect to fail and $why.  Perhaps it's
+because you haven't fixed a bug or haven't finished a new feature:
+
+    TODO: {
+        local $TODO = "URI::Geller not finished";
+
+        my $card = "Eight of clubs";
+        is( URI::Geller->your_card, $card, 'Is THIS your card?' );
+
+        my $spoon;
+        URI::Geller->bend_spoon;
+        is( $spoon, 'bent',    "Spoon bending, that's original" );
+    }
+
+With a todo block, the tests inside are expected to fail.  Test::More
+will run the tests normally, but print out special flags indicating
+they are "todo".  Test::Harness will interpret failures as being ok.
+Should anything succeed, it will report it as an unexpected success.
+You then know the thing you had todo is done and can remove the
+TODO flag.
+
+The nice part about todo tests, as opposed to simply commenting out a
+block of tests, is it's like having a programmatic todo list.  You know
+how much work is left to be done, you're aware of what bugs there are,
+and you'll know immediately when they're fixed.
+
+Once a todo test starts succeeding, simply move it outside the block.
+When the block is empty, delete it.
+
+B<NOTE>: TODO tests require a Test::Harness upgrade else it will
+treat it as a normal failure.  See L<BUGS and CAVEATS>)
+
+
+=item B<todo_skip>
+
+    TODO: {
+        todo_skip $why, $how_many if $condition;
+
+        ...normal testing code...
+    }
+
+With todo tests, it's best to have the tests actually run.  That way
+you'll know when they start passing.  Sometimes this isn't possible.
+Often a failing test will cause the whole program to die or hang, even
+inside an C<eval BLOCK> with and using C<alarm>.  In these extreme
+cases you have no choice but to skip over the broken tests entirely.
+
+The syntax and behavior is similar to a C<SKIP: BLOCK> except the
+tests will be marked as failing but todo.  Test::Harness will
+interpret them as passing.
+
+=cut
+
+sub todo_skip {
+    my($why, $how_many) = @_;
+
+    unless( defined $how_many ) {
+        # $how_many can only be avoided when no_plan is in use.
+        _carp "todo_skip() needs to know \$how_many tests are in the block"
+          unless $Test->has_plan eq 'no_plan';
+        $how_many = 1;
+    }
+
+    for( 1..$how_many ) {
+        $Test->todo_skip($why);
+    }
+
+    local $^W = 0;
+    last TODO;
+}
+
+=item When do I use SKIP vs. TODO?
+
+B<If it's something the user might not be able to do>, use SKIP.
+This includes optional modules that aren't installed, running under
+an OS that doesn't have some feature (like fork() or symlinks), or maybe
+you need an Internet connection and one isn't available.
+
+B<If it's something the programmer hasn't done yet>, use TODO.  This
+is for any code you haven't written yet, or bugs you have yet to fix,
+but want to put tests in your testing script (always a good idea).
+
+
+=back
+
+=head2 Comparison functions
+
+Not everything is a simple eq check or regex.  There are times you
+need to see if two arrays are equivalent, for instance.  For these
+instances, Test::More provides a handful of useful functions.
+
+B<NOTE> I'm not quite sure what will happen with filehandles.
+
+=over 4
+
+=item B<is_deeply>
+
+  is_deeply( $this, $that, $test_name );
+
+Similar to is(), except that if $this and $that are hash or array
+references, it does a deep comparison walking each data structure to
+see if they are equivalent.  If the two structures are different, it
+will display the place where they start differing.
+
+Test::Differences and Test::Deep provide more in-depth functionality
+along these lines.
+
+=cut
+
+use vars qw(@Data_Stack %Refs_Seen);
+my $DNE = bless [], 'Does::Not::Exist';
+sub is_deeply {
+    unless( @_ == 2 or @_ == 3 ) {
+        my $msg = <<WARNING;
+is_deeply() takes two or three args, you gave %d.
+This usually means you passed an array or hash instead 
+of a reference to it
+WARNING
+        chop $msg;   # clip off newline so carp() will put in line/file
+
+        _carp sprintf $msg, scalar @_;
+    }
+
+    my($this, $that, $name) = @_;
+
+    my $ok;
+    if( !ref $this xor !ref $that ) {  # one's a reference, one isn't
+        $ok = 0;
+    }
+    if( !ref $this and !ref $that ) {
+        $ok = $Test->is_eq($this, $that, $name);
+    }
+    else {
+        local @Data_Stack = ();
+        local %Refs_Seen  = ();
+        if( _deep_check($this, $that) ) {
+            $ok = $Test->ok(1, $name);
+        }
+        else {
+            $ok = $Test->ok(0, $name);
+            $ok = $Test->diag(_format_stack(@Data_Stack));
+        }
+    }
+
+    return $ok;
+}
+
+sub _format_stack {
+    my(@Stack) = @_;
+
+    my $var = '$FOO';
+    my $did_arrow = 0;
+    foreach my $entry (@Stack) {
+        my $type = $entry->{type} || '';
+        my $idx  = $entry->{'idx'};
+        if( $type eq 'HASH' ) {
+            $var .= "->" unless $did_arrow++;
+            $var .= "{$idx}";
+        }
+        elsif( $type eq 'ARRAY' ) {
+            $var .= "->" unless $did_arrow++;
+            $var .= "[$idx]";
+        }
+        elsif( $type eq 'REF' ) {
+            $var = "\${$var}";
+        }
+    }
+
+    my @vals = @{$Stack[-1]{vals}}[0,1];
+    my @vars = ();
+    ($vars[0] = $var) =~ s/\$FOO/     \$got/;
+    ($vars[1] = $var) =~ s/\$FOO/\$expected/;
+
+    my $out = "Structures begin differing at:\n";
+    foreach my $idx (0..$#vals) {
+        my $val = $vals[$idx];
+        $vals[$idx] = !defined $val ? 'undef' : 
+                      $val eq $DNE  ? "Does not exist"
+                                    : "'$val'";
+    }
+
+    $out .= "$vars[0] = $vals[0]\n";
+    $out .= "$vars[1] = $vals[1]\n";
+
+    $out =~ s/^/    /msg;
+    return $out;
+}
+
+
+sub _type {
+    my $thing = shift;
+
+    return '' if !ref $thing;
+
+    for my $type (qw(ARRAY HASH REF SCALAR GLOB Regexp)) {
+        return $type if UNIVERSAL::isa($thing, $type);
+    }
+
+    return '';
+}
+
+
+=item B<eq_array>
+
+  eq_array(\@this, \@that);
+
+Checks if two arrays are equivalent.  This is a deep check, so
+multi-level structures are handled correctly.
+
+=cut
+
+#'#
+sub eq_array {
+    local @Data_Stack;
+    local %Refs_Seen;
+    _eq_array(@_);
+}
+
+sub _eq_array  {
+    my($a1, $a2) = @_;
+
+    if( grep !_type($_) eq 'ARRAY', $a1, $a2 ) {
+        warn "eq_array passed a non-array ref";
+        return 0;
+    }
+
+    return 1 if $a1 eq $a2;
+
+    if($Refs_Seen{$a1}) {
+        return $Refs_Seen{$a1} eq $a2;
+    }
+    else {
+        $Refs_Seen{$a1} = "$a2";
+    }
+
+    my $ok = 1;
+    my $max = $#$a1 > $#$a2 ? $#$a1 : $#$a2;
+    for (0..$max) {
+        my $e1 = $_ > $#$a1 ? $DNE : $a1->[$_];
+        my $e2 = $_ > $#$a2 ? $DNE : $a2->[$_];
+
+        push @Data_Stack, { type => 'ARRAY', idx => $_, vals => [$e1, $e2] };
+        $ok = _deep_check($e1,$e2);
+        pop @Data_Stack if $ok;
+
+        last unless $ok;
+    }
+
+    return $ok;
+}
+
+sub _deep_check {
+    my($e1, $e2) = @_;
+    my $ok = 0;
+
+    {
+        # Quiet uninitialized value warnings when comparing undefs.
+        local $^W = 0; 
+
+        $Test->_unoverload(\$e1, \$e2);
+
+        # Either they're both references or both not.
+        my $same_ref = !(!ref $e1 xor !ref $e2);
+
+        if( defined $e1 xor defined $e2 ) {
+            $ok = 0;
+        }
+        elsif ( $e1 == $DNE xor $e2 == $DNE ) {
+            $ok = 0;
+        }
+        elsif ( $same_ref and ($e1 eq $e2) ) {
+            $ok = 1;
+        }
+        else {
+            my $type = _type($e1);
+            $type = '' unless _type($e2) eq $type;
+
+            if( !$type ) {
+                push @Data_Stack, { vals => [$e1, $e2] };
+                $ok = 0;
+            }
+            elsif( $type eq 'ARRAY' ) {
+                $ok = _eq_array($e1, $e2);
+            }
+            elsif( $type eq 'HASH' ) {
+                $ok = _eq_hash($e1, $e2);
+            }
+            elsif( $type eq 'REF' ) {
+                push @Data_Stack, { type => 'REF', vals => [$e1, $e2] };
+                $ok = _deep_check($$e1, $$e2);
+                pop @Data_Stack if $ok;
+            }
+            elsif( $type eq 'SCALAR' ) {
+                push @Data_Stack, { type => 'REF', vals => [$e1, $e2] };
+                $ok = _deep_check($$e1, $$e2);
+                pop @Data_Stack if $ok;
+            }
+        }
+    }
+
+    return $ok;
+}
+
+
+=item B<eq_hash>
+
+  eq_hash(\%this, \%that);
+
+Determines if the two hashes contain the same keys and values.  This
+is a deep check.
+
+=cut
+
+sub eq_hash {
+    local @Data_Stack;
+    local %Refs_Seen;
+    return _eq_hash(@_);
+}
+
+sub _eq_hash {
+    my($a1, $a2) = @_;
+
+    if( grep !_type($_) eq 'HASH', $a1, $a2 ) {
+        warn "eq_hash passed a non-hash ref";
+        return 0;
+    }
+
+    return 1 if $a1 eq $a2;
+
+    if( $Refs_Seen{$a1} ) {
+        return $Refs_Seen{$a1} eq $a2;
+    }
+    else {
+        $Refs_Seen{$a1} = "$a2";
+    }
+
+    my $ok = 1;
+    my $bigger = keys %$a1 > keys %$a2 ? $a1 : $a2;
+    foreach my $k (keys %$bigger) {
+        my $e1 = exists $a1->{$k} ? $a1->{$k} : $DNE;
+        my $e2 = exists $a2->{$k} ? $a2->{$k} : $DNE;
+
+        push @Data_Stack, { type => 'HASH', idx => $k, vals => [$e1, $e2] };
+        $ok = _deep_check($e1, $e2);
+        pop @Data_Stack if $ok;
+
+        last unless $ok;
+    }
+
+    return $ok;
+}
+
+=item B<eq_set>
+
+  eq_set(\@this, \@that);
+
+Similar to eq_array(), except the order of the elements is B<not>
+important.  This is a deep check, but the irrelevancy of order only
+applies to the top level.
+
+B<NOTE> By historical accident, this is not a true set comparision.
+While the order of elements does not matter, duplicate elements do.
+
+=cut
+
+sub eq_set  {
+    my($a1, $a2) = @_;
+    return 0 unless @$a1 == @$a2;
+
+    # There's faster ways to do this, but this is easiest.
+    local $^W = 0;
+
+    # We must make sure that references are treated neutrally.  It really
+    # doesn't matter how we sort them, as long as both arrays are sorted
+    # with the same algorithm.
+    # Have to inline the sort routine due to a threading/sort bug.
+    # See [rt.cpan.org 6782]
+    return eq_array(
+           [sort { ref $a ? -1 : ref $b ? 1 : $a cmp $b } @$a1],
+           [sort { ref $a ? -1 : ref $b ? 1 : $a cmp $b } @$a2]
+    );
+}
+
+=back
+
+
+=head2 Extending and Embedding Test::More
+
+Sometimes the Test::More interface isn't quite enough.  Fortunately,
+Test::More is built on top of Test::Builder which provides a single,
+unified backend for any test library to use.  This means two test
+libraries which both use Test::Builder B<can be used together in the
+same program>.
+
+If you simply want to do a little tweaking of how the tests behave,
+you can access the underlying Test::Builder object like so:
+
+=over 4
+
+=item B<builder>
+
+    my $test_builder = Test::More->builder;
+
+Returns the Test::Builder object underlying Test::More for you to play
+with.
+
+=cut
+
+sub builder {
+    return Test::Builder->new;
+}
+
+=back
+
+
+=head1 EXIT CODES
+
+If all your tests passed, Test::Builder will exit with zero (which is
+normal).  If anything failed it will exit with how many failed.  If
+you run less (or more) tests than you planned, the missing (or extras)
+will be considered failures.  If no tests were ever run Test::Builder
+will throw a warning and exit with 255.  If the test died, even after
+having successfully completed all its tests, it will still be
+considered a failure and will exit with 255.
+
+So the exit codes are...
+
+    0                   all tests successful
+    255                 test died
+    any other number    how many failed (including missing or extras)
+
+If you fail more than 254 tests, it will be reported as 254.
+
+
+=head1 CAVEATS and NOTES
+
+=over 4
+
+=item Backwards compatibility
+
+Test::More works with Perls as old as 5.004_05.
+
+
+=item Overloaded objects
+
+String overloaded objects are compared B<as strings>.  This prevents
+Test::More from piercing an object's interface allowing better blackbox
+testing.  So if a function starts returning overloaded objects instead of
+bare strings your tests won't notice the difference.  This is good.
+
+However, it does mean that functions like is_deeply() cannot be used to
+test the internals of string overloaded objects.  In this case I would
+suggest Test::Deep which contains more flexible testing functions for
+complex data structures.
+
+
+=item Threads
+
+Test::More will only be aware of threads if "use threads" has been done
+I<before> Test::More is loaded.  This is ok:
+
+    use threads;
+    use Test::More;
+
+This may cause problems:
+
+    use Test::More
+    use threads;
+
+
+=item Test::Harness upgrade
+
+no_plan and todo depend on new Test::Harness features and fixes.  If
+you're going to distribute tests that use no_plan or todo your
+end-users will have to upgrade Test::Harness to the latest one on
+CPAN.  If you avoid no_plan and TODO tests, the stock Test::Harness
+will work fine.
+
+Installing Test::More should also upgrade Test::Harness.
+
+=back
+
+
+=head1 HISTORY
+
+This is a case of convergent evolution with Joshua Pritikin's Test
+module.  I was largely unaware of its existence when I'd first
+written my own ok() routines.  This module exists because I can't
+figure out how to easily wedge test names into Test's interface (along
+with a few other problems).
+
+The goal here is to have a testing utility that's simple to learn,
+quick to use and difficult to trip yourself up with while still
+providing more flexibility than the existing Test.pm.  As such, the
+names of the most common routines are kept tiny, special cases and
+magic side-effects are kept to a minimum.  WYSIWYG.
+
+
+=head1 SEE ALSO
+
+L<Test::Simple> if all this confuses you and you just want to write
+some tests.  You can upgrade to Test::More later (it's forward
+compatible).
+
+L<Test> is the old testing module.  Its main benefit is that it has
+been distributed with Perl since 5.004_05.
+
+L<Test::Harness> for details on how your test results are interpreted
+by Perl.
+
+L<Test::Differences> for more ways to test complex data structures.
+And it plays well with Test::More.
+
+L<Test::Class> is like XUnit but more perlish.
+
+L<Test::Deep> gives you more powerful complex data structure testing.
+
+L<Test::Unit> is XUnit style testing.
+
+L<Test::Inline> shows the idea of embedded testing.
+
+L<Bundle::Test> installs a whole bunch of useful test modules.
+
+
+=head1 AUTHORS
+
+Michael G Schwern E<lt>schwern@pobox.comE<gt> with much inspiration
+from Joshua Pritikin's Test module and lots of help from Barrie
+Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and
+the perl-qa gang.
+
+
+=head1 BUGS
+
+See F<http://rt.cpan.org> to report and view bugs.
+
+
+=head1 COPYRIGHT
+
+Copyright 2001, 2002, 2004 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
+
+This program is free software; you can redistribute it and/or 
+modify it under the same terms as Perl itself.
+
+See F<http://www.perl.com/perl/misc/Artistic.html>
+
+=cut
+
+1;
diff --git a/trunk/Examples/test-suite/perl5/aggregate_runme.pl b/trunk/Examples/test-suite/perl5/aggregate_runme.pl
new file mode 100644
index 0000000..148ec94
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/aggregate_runme.pl
@@ -0,0 +1,22 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 7;
+BEGIN { use_ok('aggregate') }
+require_ok('aggregate');
+
+# adapted from ../java/aggregate_runme.java
+
+# Confirm that move() returns correct results under normal use
+is(aggregate::move($aggregate::UP), $aggregate::UP, "UP");
+
+is(aggregate::move($aggregate::DOWN), $aggregate::DOWN, "DOWN");
+
+is(aggregate::move($aggregate::LEFT), $aggregate::LEFT, "LEFT");
+
+is(aggregate::move($aggregate::RIGHT), $aggregate::RIGHT, "RIGHT");
+
+# Confirm that move() raises an exception when the contract is violated
+eval { aggregate::move(0) };
+like($@, qr/\bRuntimeError\b/);
+
diff --git a/trunk/Examples/test-suite/perl5/apply_signed_char_runme.pl b/trunk/Examples/test-suite/perl5/apply_signed_char_runme.pl
new file mode 100644
index 0000000..d39e4c3
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/apply_signed_char_runme.pl
@@ -0,0 +1,26 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 12;
+BEGIN { use_ok('apply_signed_char') }
+require_ok('apply_signed_char');
+
+# adapted from ../java/apply_signed_char_runme.java
+
+my $smallnum = -127;
+is(apply_signed_char::CharValFunction($smallnum), $smallnum);
+is(apply_signed_char::CCharValFunction($smallnum), $smallnum);
+is(apply_signed_char::CCharRefFunction($smallnum), $smallnum);
+
+$apply_signed_char::globalchar = $smallnum;
+is($apply_signed_char::globalchar, $smallnum);
+is($apply_signed_char::globalconstchar, -110);
+
+my $d = new apply_signed_char::DirectorTest();
+is($d->CharValFunction($smallnum), $smallnum);
+is($d->CCharValFunction($smallnum), $smallnum);
+is($d->CCharRefFunction($smallnum), $smallnum);
+
+$d->{memberchar} = $smallnum;
+is($d->{memberchar}, $smallnum);
+is($d->{memberconstchar}, -112);
diff --git a/trunk/Examples/test-suite/perl5/apply_strings_runme.pl b/trunk/Examples/test-suite/perl5/apply_strings_runme.pl
new file mode 100644
index 0000000..2cb54d1
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/apply_strings_runme.pl
@@ -0,0 +1,11 @@
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('apply_strings') }
+require_ok('apply_strings');
+
+my $TEST_MESSAGE = "A message from target language to the C++ world and back again.";
+
+is(apply_strings::UCharFunction($TEST_MESSAGE), $TEST_MESSAGE, "UCharFunction"); 
+
+is(apply_strings::SCharFunction($TEST_MESSAGE), $TEST_MESSAGE, "SCharFunction");
diff --git a/trunk/Examples/test-suite/perl5/array_member_runme.pl b/trunk/Examples/test-suite/perl5/array_member_runme.pl
new file mode 100644
index 0000000..77d28fe
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/array_member_runme.pl
@@ -0,0 +1,28 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 18;
+BEGIN { use_ok('array_member') }
+require_ok('array_member');
+
+my $f = array_member::Foo->new();
+$f->{data} = $array_member::global_data;
+
+for(my $i=0; $i<8; $i++) {
+	is( array_member::get_value($f->{data},$i),
+		array_member::get_value($array_member::global_data,$i),
+		"array assignment");
+}
+
+for(my $i=0; $i<8; $i++) {
+	array_member::set_value($f->{data},$i,-$i);
+}
+
+$array_member::global_data = $f->{data};
+
+for(my $i=0; $i<8; $i++) {
+	is(array_member::get_value($f->{data},$i),
+		array_member::get_value($array_member::global_data,$i),
+		"array assignment");
+}
+
diff --git a/trunk/Examples/test-suite/perl5/char_strings_runme.pl b/trunk/Examples/test-suite/perl5/char_strings_runme.pl
new file mode 100644
index 0000000..51c227b
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/char_strings_runme.pl
@@ -0,0 +1,12 @@
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('char_strings') }
+require_ok('char_strings');
+
+my $val1 = "100";
+is(char_strings::CharPingPong($val1), "100", 'cstr1');
+
+my $val2 = "greetings";
+is(char_strings::CharPingPong($val2), "greetings", 'cstr2');
+
diff --git a/trunk/Examples/test-suite/perl5/class_ignore_runme.pl b/trunk/Examples/test-suite/perl5/class_ignore_runme.pl
new file mode 100755
index 0000000..989150c
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/class_ignore_runme.pl
@@ -0,0 +1,12 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 3;
+BEGIN { use_ok('class_ignore') }
+require_ok('class_ignore');
+
+# adapted from ../python/class_ignore_runme.py
+
+my $a = class_ignore::Bar->new();
+
+is(class_ignore::do_blah($a), "Bar::blah");
diff --git a/trunk/Examples/test-suite/perl5/contract_runme.pl b/trunk/Examples/test-suite/perl5/contract_runme.pl
new file mode 100755
index 0000000..fb162e6
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/contract_runme.pl
@@ -0,0 +1,78 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 32;
+BEGIN { use_ok('contract') }
+require_ok('contract');
+
+# adapted from ../python/contract_runme.py
+{
+	ok(contract::test_preassert(1,2), "good preassertion");
+	eval { contract::test_preassert(-1) };
+	like($@, qr/\bRuntimeError\b/, "bad preassertion");
+
+	ok(contract::test_postassert(3), "good postassertion");
+	eval { contract::test_postassert(-3) };
+	like($@, qr/\bRuntimeError\b/, "bad postassertion");
+
+	ok(contract::test_prepost(2,3), "good prepost");
+	ok(contract::test_prepost(5,-4), "good prepost");
+	eval { contract::test_prepost(-3,4); };
+	like($@, qr/\bRuntimeError\b/, "bad preassertion");
+	eval { contract::test_prepost(4,-10) };
+	like($@, qr/\bRuntimeError\b/, "bad postassertion");
+}
+{
+	my $f = contract::Foo->new();
+	ok($f->test_preassert(4,5), "method pre");
+	eval { $f->test_preassert(-2,3) };
+	like($@, qr/\bRuntimeError\b/, "method pre bad");
+
+	ok($f->test_postassert(4), "method post");
+	eval { $f->test_postassert(-4) };
+	like($@, qr/\bRuntimeError\b/, "method post bad");
+
+	ok($f->test_prepost(3,4), "method prepost");
+	ok($f->test_prepost(4,-3), "method prepost");
+	eval { $f->test_prepost(-4,2) };
+	like($@, qr/\bRuntimeError\b/, "method pre bad");
+	eval { $f->test_prepost(4,-10) };
+	like($@, qr/\bRuntimeError\b/, "method post bad");
+}
+{
+	ok(contract::Foo::stest_prepost(4,0), "static method prepost");
+	eval { contract::Foo::stest_prepost(-4,2) };
+	like($@, qr/\bRuntimeError\b/, "static method pre bad");
+	eval { contract::Foo::stest_prepost(4,-10) };
+	like($@, qr/\bRuntimeError\b/, "static method post bad");
+}
+{
+	my $b = contract::Bar->new();
+	eval { $b->test_prepost(2,-4) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre bad");
+}
+{
+	my $d = contract::D->new();
+	eval { $d->foo(-1,1,1,1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->foo(1,-1,1,1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->foo(1,1,-1,1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->foo(1,1,1,-1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->foo(1,1,1,1,-1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+
+	eval { $d->bar(-1,1,1,1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->bar(1,-1,1,1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->bar(1,1,-1,1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->bar(1,1,1,-1,1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+	eval { $d->bar(1,1,1,1,-1) };
+	like($@, qr/\bRuntimeError\b/, "inherit pre D");
+}
+
diff --git a/trunk/Examples/test-suite/perl5/default_args_runme.pl b/trunk/Examples/test-suite/perl5/default_args_runme.pl
new file mode 100644
index 0000000..8d0d268
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/default_args_runme.pl
@@ -0,0 +1,85 @@
+use strict;
+use warnings;
+use Test::More tests => 40;
+BEGIN { use_ok('default_args') }
+require_ok('default_args');
+
+my $true = 1;
+my $false = '';
+
+is(default_args::anonymous(), 7771, "anonymous (1)");
+is(default_args::anonymous(1234), 1234, "anonymous (2)");
+
+is(default_args::booltest(), $true, "booltest (1)");
+is(default_args::booltest($true), $true, "booltest (2)");
+is(default_args::booltest($false), $false, "booltest (3)");
+
+my $ec = new default_args::EnumClass();
+is($ec->blah(), $true, "EnumClass");
+
+is(default_args::casts1(), undef, "casts1");
+is(default_args::casts2(), "Hello", "casts2");
+is(default_args::casts1("Ciao"), "Ciao", "casts1 not default");
+is(default_args::chartest1(), 'x', "chartest1");
+is(default_args::chartest2(), "\0", "chartest2");
+is(default_args::chartest1('y'), 'y', "chartest1 not default");
+is(default_args::reftest1(), 42, "reftest1");
+is(default_args::reftest1(400), 400, "reftest1 not default");
+is(default_args::reftest2(), "hello", "reftest2");
+
+# rename
+my $foo = new default_args::Foo();
+can_ok($foo, qw(newname renamed3arg renamed2arg renamed1arg));
+eval {
+	$foo->newname(); 
+	$foo->newname(10); 
+	$foo->renamed3arg(10, 10.0); 
+	$foo->renamed2arg(10); 
+	$foo->renamed1arg();
+};
+ok(not($@), '%rename handling');
+ 
+# exception specifications
+eval { default_args::exceptionspec() };
+is($@, "ciao", "exceptionspec 1");
+eval { default_args::exceptionspec(-1) };
+is($@, "ciao", "exceptionspec 2");
+eval { default_args::exceptionspec(100) };
+is($@, '100', "exceptionspec 3");
+
+my $ex = new default_args::Except($false);
+
+my $hit = 0;
+eval { $ex->exspec(); $hit = 1; };
+# a zero was thrown, an exception occured, but $@ is false
+is($hit, 0, "exspec 1");
+eval { $ex->exspec(-1) };
+is($@, "ciao", "exspec 2");
+eval { $ex->exspec(100) };
+is($@, 100, "exspec 3");
+eval { $ex = default_args::Except->new($true) };
+is($@, -1, "Except constructor 1");
+eval { $ex = default_args::Except->new($true, -2) };
+is($@, -2, "Except constructor 2");
+
+#Default parameters in static class methods
+is(default_args::Statics::staticmethod(), 60, "staticmethod 1");
+is(default_args::Statics::staticmethod(100), 150, "staticmethod 2");
+is(default_args::Statics::staticmethod(100,200,300), 600, "staticmethod 3");
+
+my $tricky = new default_args::Tricky();
+is($tricky->privatedefault(), 200, "privatedefault");
+is($tricky->protectedint(), 2000, "protectedint");
+is($tricky->protecteddouble(), 987.654, "protecteddouble");
+is($tricky->functiondefault(), 500, "functiondefault");
+is($tricky->contrived(), 'X', "contrived");
+is(default_args::constructorcall()->{val}, -1, "constructorcall test 1");
+is(default_args::constructorcall(new default_args::Klass(2222))->{val},
+   2222, "constructorcall test 2");
+is(default_args::constructorcall(new default_args::Klass())->{val},
+   -1, "constructorcall test 3");
+
+# const methods 
+my $cm = new default_args::ConstMethods();
+is($cm->coo(), 20, "coo test 1");
+is($cm->coo(1.0), 20, "coo test 2");
diff --git a/trunk/Examples/test-suite/perl5/default_constructor_runme.pl b/trunk/Examples/test-suite/perl5/default_constructor_runme.pl
new file mode 100644
index 0000000..b43df9e
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/default_constructor_runme.pl
@@ -0,0 +1,51 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 20;
+BEGIN { use_ok('default_constructor') }
+require_ok('default_constructor');
+
+isa_ok(eval { default_constructor::A->new() }, "default_constructor::A");
+isa_ok(eval { default_constructor::AA->new() }, "default_constructor::AA");
+is(    eval { default_constructor::B->new() }, undef, "private default constructor");
+isa_ok(eval { default_constructor::B->new(0, 0) }, "default_constructor::B");
+is(    eval { default_constructor::BB->new() }, undef, "inherited private default constructor");
+is(    eval { default_constructor::C->new() }, undef, "protected default constructor");
+isa_ok(eval { default_constructor::CC->new() }, "default_constructor::CC");
+is(    eval { default_constructor::D->new() }, undef, "private constructor");
+is(    eval { default_constructor::DD->new() }, undef, "inherited private constructor");
+{ local $TODO = "default_constructor.i disagrees with our result";
+is(    eval { default_constructor::AD->new() }, undef, "MI on A, D");
+}
+isa_ok(eval { default_constructor::E->new() }, "default_constructor::E");
+isa_ok(eval { default_constructor::EE->new() }, "default_constructor::EE");
+{ local $TODO = "default_constructor.i disagrees with our result";
+is(    eval { default_constructor::EB->new() }, undef, "MI on E, B");
+}
+{ local $TODO = "destructor hiding seems off";
+my $hit = 0;
+eval {
+	my $F = default_constructor::F->new();
+	undef $F;
+	$hit = 1;
+};
+ok(not($hit), "private destructor");
+$hit = 0;
+eval {
+	my $G = default_constructor::G->new();
+	undef $G;
+	$hit = 1;
+};
+ok(not($hit), "protected destructor");
+$hit = 0;
+eval {
+	my $G = default_constructor::GG->new();
+	undef $G;
+	$hit = 1;
+};
+ok(not($hit), "inherited protected destructor");
+}
+isa_ok(eval { default_constructor::HH->new(0, 0) }, "default_constructor::HH");
+is(    eval { default_constructor::HH->new() }, undef, "templated protected constructor");
+
+# TODO: sort out what needs to be tested from OSRSpatialReferenceShadow
diff --git a/trunk/Examples/test-suite/perl5/disown_runme.pl b/trunk/Examples/test-suite/perl5/disown_runme.pl
new file mode 100644
index 0000000..0e8f8cb
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/disown_runme.pl
@@ -0,0 +1,10 @@
+use disown;
+
+if (1) {
+    $a = new disown::A();
+    $b = new disown::B();    
+    $c = $b->acquire($a);   
+}
+
+
+
diff --git a/trunk/Examples/test-suite/perl5/dynamic_cast_runme.pl b/trunk/Examples/test-suite/perl5/dynamic_cast_runme.pl
new file mode 100644
index 0000000..3940669
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/dynamic_cast_runme.pl
@@ -0,0 +1,13 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 3;
+BEGIN { use_ok('dynamic_cast') }
+require_ok('dynamic_cast');
+
+my $f = dynamic_cast::Foo->new();
+my $b = dynamic_cast::Bar->new();
+my $x = $f->blah();
+my $y = $b->blah();
+my $a = dynamic_cast::do_test($y);
+is($a, "Bar::test");
diff --git a/trunk/Examples/test-suite/perl5/enum_template_runme.pl b/trunk/Examples/test-suite/perl5/enum_template_runme.pl
new file mode 100755
index 0000000..bdaaa85
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/enum_template_runme.pl
@@ -0,0 +1,12 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('enum_template') }
+require_ok('enum_template');
+
+# adapted from ../python/enum_template_runme.py
+
+is(enum_template::MakeETest(), 1);
+
+is(enum_template::TakeETest(0), undef);
diff --git a/trunk/Examples/test-suite/perl5/enum_thorough_runme.pl b/trunk/Examples/test-suite/perl5/enum_thorough_runme.pl
new file mode 100644
index 0000000..80a2cca
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/enum_thorough_runme.pl
@@ -0,0 +1,375 @@
+# an adaptation of ../java/enum_thorough_runme.java
+use strict;
+use warnings;
+use Test::More tests => 272;
+BEGIN { use_ok('enum_thorough') }
+require_ok('enum_thorough');
+
+is($enum_thorough::ReallyAnInteger, 200, "Test Anon 1");
+
+{
+	my $red = $enum_thorough::red;
+	is(enum_thorough::colourTest1($red), $red, "colourTest1");
+	is(enum_thorough::colourTest2($red), $red, "colourTest2");
+	is(enum_thorough::colourTest3($red), $red, "colourTest3");
+	is(enum_thorough::colourTest4($red), $red, "colourTest4");
+	isnt($enum_thorough::myColour, $red, "colour global get");
+	$enum_thorough::myColour = $red;
+	is($enum_thorough::myColour, $red, "colour global set");
+}
+{
+	my $s = enum_thorough::SpeedClass->new();
+	my $speed = $enum_thorough::SpeedClass::slow;
+	ok(defined($speed), "SpeedClass.slow");
+	is($s->speedTest1($speed), $speed, "speedTest 1");
+	is($s->speedTest2($speed), $speed, "speedTest 2");
+	is($s->speedTest3($speed), $speed, "speedTest 3");
+	is($s->speedTest4($speed), $speed, "speedTest 4");
+	is($s->speedTest5($speed), $speed, "speedTest 5");
+	is($s->speedTest6($speed), $speed, "speedTest 6");
+	is($s->speedTest7($speed), $speed, "speedTest 7");
+	is($s->speedTest8($speed), $speed, "speedTest 8");
+	is(enum_thorough::speedTest1($speed), $speed, "speedTest Global 1");
+	is(enum_thorough::speedTest2($speed), $speed, "speedTest Global 2");
+	is(enum_thorough::speedTest3($speed), $speed, "speedTest Global 3");
+	is(enum_thorough::speedTest4($speed), $speed, "speedTest Global 4");
+	is(enum_thorough::speedTest5($speed), $speed, "speedTest Global 5");
+}
+{
+	my $s = enum_thorough::SpeedClass->new();
+	my $slow = $enum_thorough::SpeedClass::slow;
+	my $lightning = $enum_thorough::SpeedClass::lightning;
+	is($s->{mySpeedtd1}, $slow, "mySpeedtd1 1");
+	is($s->{mySpeedtd1}, 10, "mySpeedtd1 2");
+	$s->{mySpeedtd1} = $lightning;
+	is($s->{mySpeedtd1}, $lightning, "mySpeedtd1 3");
+	is($s->{mySpeedtd1}, 31, "mySpeedtd1 4");
+}
+is(enum_thorough::namedanonTest1($enum_thorough::NamedAnon2),
+	$enum_thorough::NamedAnon2, "namedanonTest1");
+{
+	my $val = $enum_thorough::TwoNames2;
+	is(enum_thorough::twonamesTest1($val), $val, "twonamesTest 1");
+	is(enum_thorough::twonamesTest2($val), $val, "twonamesTest 2");
+	is(enum_thorough::twonamesTest3($val), $val, "twonamesTest 3");
+}
+{ local $TODO = "shouldn't namespaces drop into a package?";
+	my $val = $enum_thorough::AnonSpace::NamedAnonSpace2;
+	ok(defined($val), "found enum value");
+SKIP: {
+	skip "enum value not in expected package", 3 unless defined $val;
+	is(enum_thorough::namedanonspaceTest1($val), $val, "namedanonspaceTest 1");
+	is(enum_thorough::namedanonspaceTest2($val), $val, "namedanonspaceTest 2");
+	is(enum_thorough::namedanonspaceTest3($val), $val, "namedanonspaceTest 3");
+}}
+{
+	my $t = enum_thorough::TemplateClassInt->new();
+	my $galileo = $enum_thorough::TemplateClassInt::galileo;
+	is($t->scientistsTest1($galileo), $galileo, "scientistsTest 1");
+	is($t->scientistsTest2($galileo), $galileo, "scientistsTest 2");
+	is($t->scientistsTest3($galileo), $galileo, "scientistsTest 3");
+	is($t->scientistsTest4($galileo), $galileo, "scientistsTest 4");
+	is($t->scientistsTest5($galileo), $galileo, "scientistsTest 5");
+	is($t->scientistsTest6($galileo), $galileo, "scientistsTest 6");
+	is($t->scientistsTest7($galileo), $galileo, "scientistsTest 7");
+	is($t->scientistsTest8($galileo), $galileo, "scientistsTest 8");
+	is($t->scientistsTest9($galileo), $galileo, "scientistsTest 9");
+	is($t->scientistsTestB($galileo), $galileo, "scientistsTest B");
+	is($t->scientistsTestD($galileo), $galileo, "scientistsTest D");
+	is($t->scientistsTestE($galileo), $galileo, "scientistsTest E");
+	is($t->scientistsTestF($galileo), $galileo, "scientistsTest F");
+	is($t->scientistsTestG($galileo), $galileo, "scientistsTest G");
+	is($t->scientistsTestH($galileo), $galileo, "scientistsTest H");
+	is($t->scientistsTestI($galileo), $galileo, "scientistsTest I");
+	is($t->scientistsTestJ($galileo), $galileo, "scientistsTest J");
+
+	is(enum_thorough::scientistsTest1($galileo), $galileo, "scientistsTest Global 1");
+	is(enum_thorough::scientistsTest2($galileo), $galileo, "scientistsTest Global 2");
+	is(enum_thorough::scientistsTest3($galileo), $galileo, "scientistsTest Global 3");
+	is(enum_thorough::scientistsTest4($galileo), $galileo, "scientistsTest Global 4");
+	is(enum_thorough::scientistsTest5($galileo), $galileo, "scientistsTest Global 5");
+	is(enum_thorough::scientistsTest6($galileo), $galileo, "scientistsTest Global 6");
+	is(enum_thorough::scientistsTest7($galileo), $galileo, "scientistsTest Global 7");
+	is(enum_thorough::scientistsTest8($galileo), $galileo, "scientistsTest Global 8");
+}
+{
+	my $t = enum_thorough::TClassInt->new();
+	my $bell = $enum_thorough::TClassInt::bell;
+	my $galileo = $enum_thorough::TemplateClassInt::galileo;
+	is($t->scientistsNameTest1($bell), $bell, "scientistsNameTest 1");
+	is($t->scientistsNameTest2($bell), $bell, "scientistsNameTest 2");
+	is($t->scientistsNameTest3($bell), $bell, "scientistsNameTest 3");
+	is($t->scientistsNameTest4($bell), $bell, "scientistsNameTest 4");
+	is($t->scientistsNameTest5($bell), $bell, "scientistsNameTest 5");
+	is($t->scientistsNameTest6($bell), $bell, "scientistsNameTest 6");
+	is($t->scientistsNameTest7($bell), $bell, "scientistsNameTest 7");
+	is($t->scientistsNameTest8($bell), $bell, "scientistsNameTest 8");
+	is($t->scientistsNameTest9($bell), $bell, "scientistsNameTest 9");
+	is($t->scientistsNameTestB($bell), $bell, "scientistsNameTest B");
+	is($t->scientistsNameTestD($bell), $bell, "scientistsNameTest D");
+	is($t->scientistsNameTestE($bell), $bell, "scientistsNameTest E");
+	is($t->scientistsNameTestF($bell), $bell, "scientistsNameTest F");
+	is($t->scientistsNameTestG($bell), $bell, "scientistsNameTest G");
+	is($t->scientistsNameTestH($bell), $bell, "scientistsNameTest H");
+	is($t->scientistsNameTestI($bell), $bell, "scientistsNameTest I");
+
+	is($t->scientistsNameSpaceTest1($bell), $bell, "scientistsNameSpaceTest 1");
+	is($t->scientistsNameSpaceTest2($bell), $bell, "scientistsNameSpaceTest 2");
+	is($t->scientistsNameSpaceTest3($bell), $bell, "scientistsNameSpaceTest 3");
+	is($t->scientistsNameSpaceTest4($bell), $bell, "scientistsNameSpaceTest 4");
+	is($t->scientistsNameSpaceTest5($bell), $bell, "scientistsNameSpaceTest 5");
+	is($t->scientistsNameSpaceTest6($bell), $bell, "scientistsNameSpaceTest 6");
+	is($t->scientistsNameSpaceTest7($bell), $bell, "scientistsNameSpaceTest 7");
+
+	is($t->scientistsOtherTest1($galileo), $galileo, "scientistsOtherTest 1");
+	is($t->scientistsOtherTest2($galileo), $galileo, "scientistsOtherTest 2");
+	is($t->scientistsOtherTest3($galileo), $galileo, "scientistsOtherTest 3");
+	is($t->scientistsOtherTest4($galileo), $galileo, "scientistsOtherTest 4");
+	is($t->scientistsOtherTest5($galileo), $galileo, "scientistsOtherTest 5");
+	is($t->scientistsOtherTest6($galileo), $galileo, "scientistsOtherTest 6");
+	is($t->scientistsOtherTest7($galileo), $galileo, "scientistsOtherTest 7");
+
+	is(enum_thorough::scientistsNameTest1($bell), $bell, "scientistsNameTest Global 1");
+	is(enum_thorough::scientistsNameTest2($bell), $bell, "scientistsNameTest Global 2");
+	is(enum_thorough::scientistsNameTest3($bell), $bell, "scientistsNameTest Global 3");
+	is(enum_thorough::scientistsNameTest4($bell), $bell, "scientistsNameTest Global 4");
+	is(enum_thorough::scientistsNameTest5($bell), $bell, "scientistsNameTest Global 5");
+	is(enum_thorough::scientistsNameTest6($bell), $bell, "scientistsNameTest Global 6");
+	is(enum_thorough::scientistsNameTest7($bell), $bell, "scientistsNameTest Global 7");
+
+	is(enum_thorough::scientistsNameSpaceTest1($bell), $bell, "scientistsNameSpaceTest Global 1");
+	is(enum_thorough::scientistsNameSpaceTest2($bell), $bell, "scientistsNameSpaceTest Global 2");
+	is(enum_thorough::scientistsNameSpaceTest3($bell), $bell, "scientistsNameSpaceTest Global 3");
+	is(enum_thorough::scientistsNameSpaceTest4($bell), $bell, "scientistsNameSpaceTest Global 4");
+	is(enum_thorough::scientistsNameSpaceTest5($bell), $bell, "scientistsNameSpaceTest Global 5");
+	is(enum_thorough::scientistsNameSpaceTest6($bell), $bell, "scientistsNameSpaceTest Global 6");
+	is(enum_thorough::scientistsNameSpaceTest7($bell), $bell, "scientistsNameSpaceTest Global 7");
+
+	is(enum_thorough::scientistsNameSpaceTest8($bell), $bell, "scientistsNameSpaceTest Global 8");
+	is(enum_thorough::scientistsNameSpaceTest9($bell), $bell, "scientistsNameSpaceTest Global 9");
+	is(enum_thorough::scientistsNameSpaceTestA($bell), $bell, "scientistsNameSpaceTest Global A");
+	is(enum_thorough::scientistsNameSpaceTestB($bell), $bell, "scientistsNameSpaceTest Global B");
+	is(enum_thorough::scientistsNameSpaceTestC($bell), $bell, "scientistsNameSpaceTest Global C");
+	is(enum_thorough::scientistsNameSpaceTestD($bell), $bell, "scientistsNameSpaceTest Global D");
+	is(enum_thorough::scientistsNameSpaceTestE($bell), $bell, "scientistsNameSpaceTest Global E");
+
+	is(enum_thorough::scientistsNameSpaceTestF($bell), $bell, "scientistsNameSpaceTest Global F");
+	is(enum_thorough::scientistsNameSpaceTestG($bell), $bell, "scientistsNameSpaceTest Global G");
+	is(enum_thorough::scientistsNameSpaceTestH($bell), $bell, "scientistsNameSpaceTest Global H");
+	is(enum_thorough::scientistsNameSpaceTestI($bell), $bell, "scientistsNameSpaceTest Global I");
+	is(enum_thorough::scientistsNameSpaceTestJ($bell), $bell, "scientistsNameSpaceTest Global J");
+	is(enum_thorough::scientistsNameSpaceTestK($bell), $bell, "scientistsNameSpaceTest Global K");
+	is(enum_thorough::scientistsNameSpaceTestL($bell), $bell, "scientistsNameSpaceTest Global L");
+}
+{
+	my $val = $enum_thorough::argh;
+	is(enum_thorough::renameTest1($val), $val, "renameTest Global 1");
+	is(enum_thorough::renameTest2($val), $val, "renameTest Global 2");
+}
+{
+	my $n = enum_thorough::NewNameStruct->new();
+	is($n->renameTest1($enum_thorough::NewNameStruct::bang), $enum_thorough::NewNameStruct::bang, "renameTest 1");
+	is($n->renameTest2($enum_thorough::NewNameStruct::bang), $enum_thorough::NewNameStruct::bang, "renameTest 2");
+	is($n->renameTest3($enum_thorough::NewNameStruct::simple1), $enum_thorough::NewNameStruct::simple1, "renameTest 3");
+	is($n->renameTest4($enum_thorough::NewNameStruct::doublename1), $enum_thorough::NewNameStruct::doublename1, "renameTest 4");
+	is($n->renameTest5($enum_thorough::NewNameStruct::doublename1), $enum_thorough::NewNameStruct::doublename1, "renameTest 5");
+	is($n->renameTest6($enum_thorough::NewNameStruct::singlename1), $enum_thorough::NewNameStruct::singlename1, "renameTest 6");
+}
+{
+	is(enum_thorough::renameTest3($enum_thorough::NewNameStruct::bang), $enum_thorough::NewNameStruct::bang, "renameTest Global 3");
+	is(enum_thorough::renameTest4($enum_thorough::NewNameStruct::simple1), $enum_thorough::NewNameStruct::simple1, "renameTest Global 4");
+	is(enum_thorough::renameTest5($enum_thorough::NewNameStruct::doublename1), $enum_thorough::NewNameStruct::doublename1, "renameTest Global 5");
+	is(enum_thorough::renameTest6($enum_thorough::NewNameStruct::doublename1), $enum_thorough::NewNameStruct::doublename1, "renameTest Global 6");
+	is(enum_thorough::renameTest7($enum_thorough::NewNameStruct::singlename1), $enum_thorough::NewNameStruct::singlename1, "renameTest Global 7");
+}
+{
+	my $t = enum_thorough::TreesClass->new();
+	my $pine = $enum_thorough::TreesClass::pine;
+	is($t->treesTest1($pine), $pine, "treesTest 1");
+	is($t->treesTest2($pine), $pine, "treesTest 2");
+	is($t->treesTest3($pine), $pine, "treesTest 3");
+	is($t->treesTest4($pine), $pine, "treesTest 4");
+	is($t->treesTest5($pine), $pine, "treesTest 5");
+	is($t->treesTest6($pine), $pine, "treesTest 6");
+	is($t->treesTest7($pine), $pine, "treesTest 7");
+	is($t->treesTest8($pine), $pine, "treesTest 8");
+	is($t->treesTest9($pine), $pine, "treesTest 9");
+	is($t->treesTestA($pine), $pine, "treesTest A");
+	is($t->treesTestB($pine), $pine, "treesTest B");
+	is($t->treesTestC($pine), $pine, "treesTest C");
+	is($t->treesTestD($pine), $pine, "treesTest D");
+	is($t->treesTestE($pine), $pine, "treesTest E");
+	is($t->treesTestF($pine), $pine, "treesTest F");
+	is($t->treesTestG($pine), $pine, "treesTest G");
+	is($t->treesTestH($pine), $pine, "treesTest H");
+	is($t->treesTestI($pine), $pine, "treesTest I");
+	is($t->treesTestJ($pine), $pine, "treesTest J");
+	is($t->treesTestK($pine), $pine, "treesTest K");
+	is($t->treesTestL($pine), $pine, "treesTest L");
+	is($t->treesTestM($pine), $pine, "treesTest M");
+	is($t->treesTestN($pine), $pine, "treesTest N");
+	is($t->treesTestO($pine), $pine, "treesTest O");
+
+	is(enum_thorough::treesTest1($pine), $pine, "treesTest Global 1");
+	is(enum_thorough::treesTest2($pine), $pine, "treesTest Global 2");
+	is(enum_thorough::treesTest3($pine), $pine, "treesTest Global 3");
+	is(enum_thorough::treesTest4($pine), $pine, "treesTest Global 4");
+	is(enum_thorough::treesTest5($pine), $pine, "treesTest Global 5");
+	is(enum_thorough::treesTest6($pine), $pine, "treesTest Global 6");
+	is(enum_thorough::treesTest7($pine), $pine, "treesTest Global 7");
+	is(enum_thorough::treesTest8($pine), $pine, "treesTest Global 8");
+	is(enum_thorough::treesTest9($pine), $pine, "treesTest Global 9");
+	is(enum_thorough::treesTestA($pine), $pine, "treesTest Global A");
+	is(enum_thorough::treesTestB($pine), $pine, "treesTest Global B");
+	is(enum_thorough::treesTestC($pine), $pine, "treesTest Global C");
+	is(enum_thorough::treesTestD($pine), $pine, "treesTest Global D");
+	is(enum_thorough::treesTestE($pine), $pine, "treesTest Global E");
+	is(enum_thorough::treesTestF($pine), $pine, "treesTest Global F");
+	is(enum_thorough::treesTestG($pine), $pine, "treesTest Global G");
+	is(enum_thorough::treesTestH($pine), $pine, "treesTest Global H");
+	is(enum_thorough::treesTestI($pine), $pine, "treesTest Global I");
+	is(enum_thorough::treesTestJ($pine), $pine, "treesTest Global J");
+	is(enum_thorough::treesTestK($pine), $pine, "treesTest Global K");
+	is(enum_thorough::treesTestL($pine), $pine, "treesTest Global L");
+	is(enum_thorough::treesTestM($pine), $pine, "treesTest Global M");
+	is(enum_thorough::treesTestO($pine), $pine, "treesTest Global O");
+	is(enum_thorough::treesTestP($pine), $pine, "treesTest Global P");
+	is(enum_thorough::treesTestQ($pine), $pine, "treesTest Global Q");
+	is(enum_thorough::treesTestR($pine), $pine, "treesTest Global R");
+}
+{
+	my $h = enum_thorough::HairStruct->new();
+	my $ginger = $enum_thorough::HairStruct::ginger;
+
+	is($h->hairTest1($ginger), $ginger, "hairTest 1");
+	is($h->hairTest2($ginger), $ginger, "hairTest 2");
+	is($h->hairTest3($ginger), $ginger, "hairTest 3");
+	is($h->hairTest4($ginger), $ginger, "hairTest 4");
+	is($h->hairTest5($ginger), $ginger, "hairTest 5");
+	is($h->hairTest6($ginger), $ginger, "hairTest 6");
+	is($h->hairTest7($ginger), $ginger, "hairTest 7");
+	is($h->hairTest8($ginger), $ginger, "hairTest 8");
+	is($h->hairTest9($ginger), $ginger, "hairTest 9");
+	is($h->hairTestA($ginger), $ginger, "hairTest A");
+	is($h->hairTestB($ginger), $ginger, "hairTest B");
+
+	my $red = $enum_thorough::red;
+	is($h->colourTest1($red), $red, "colourTest HairStruct 1");
+	is($h->colourTest2($red), $red, "colourTest HairStruct 2");
+	is($h->namedanonTest1($enum_thorough::NamedAnon2), $enum_thorough::NamedAnon2, "namedanonTest HairStruct 1");
+{ local $TODO = "shouldn't namespaces drop into a package?";
+	ok(defined($enum_thorough::AnonSpace::NamedAnonSpace2), "found enum value");
+SKIP: {
+	skip "enum value not in expected package", 1 unless defined $enum_thorough::AnonSpace::NamedAnonSpace2;
+	is($h->namedanonspaceTest1($enum_thorough::AnonSpace::NamedAnonSpace2), $enum_thorough::AnonSpace::NamedAnonSpace2, "namedanonspaceTest HairStruct 1");
+}}
+	
+
+	my $fir = $enum_thorough::TreesClass::fir;
+	is($h->treesGlobalTest1($fir), $fir, "treesGlobalTest1 HairStruct 1");
+	is($h->treesGlobalTest2($fir), $fir, "treesGlobalTest1 HairStruct 2");
+	is($h->treesGlobalTest3($fir), $fir, "treesGlobalTest1 HairStruct 3");
+	is($h->treesGlobalTest4($fir), $fir, "treesGlobalTest1 HairStruct 4");
+}
+{
+	my $blonde = $enum_thorough::HairStruct::blonde;
+	is(enum_thorough::hairTest1($blonde), $blonde, "hairTest Global 1");
+	is(enum_thorough::hairTest2($blonde), $blonde, "hairTest Global 2");
+	is(enum_thorough::hairTest3($blonde), $blonde, "hairTest Global 3");
+	is(enum_thorough::hairTest4($blonde), $blonde, "hairTest Global 4");
+	is(enum_thorough::hairTest5($blonde), $blonde, "hairTest Global 5");
+	is(enum_thorough::hairTest6($blonde), $blonde, "hairTest Global 6");
+	is(enum_thorough::hairTest7($blonde), $blonde, "hairTest Global 7");
+	is(enum_thorough::hairTest8($blonde), $blonde, "hairTest Global 8");
+	is(enum_thorough::hairTest9($blonde), $blonde, "hairTest Global 9");
+	is(enum_thorough::hairTestA($blonde), $blonde, "hairTest Global A");
+	is(enum_thorough::hairTestB($blonde), $blonde, "hairTest Global B");
+	is(enum_thorough::hairTestC($blonde), $blonde, "hairTest Global C");
+
+	is(enum_thorough::hairTestA1($blonde), $blonde, "hairTest Global A1");
+	is(enum_thorough::hairTestA2($blonde), $blonde, "hairTest Global A2");
+	is(enum_thorough::hairTestA3($blonde), $blonde, "hairTest Global A3");
+	is(enum_thorough::hairTestA4($blonde), $blonde, "hairTest Global A4");
+	is(enum_thorough::hairTestA5($blonde), $blonde, "hairTest Global A5");
+	is(enum_thorough::hairTestA6($blonde), $blonde, "hairTest Global A6");
+	is(enum_thorough::hairTestA7($blonde), $blonde, "hairTest Global A7");
+	is(enum_thorough::hairTestA8($blonde), $blonde, "hairTest Global A8");
+	is(enum_thorough::hairTestA9($blonde), $blonde, "hairTest Global A9");
+	is(enum_thorough::hairTestAA($blonde), $blonde, "hairTest Global AA");
+	is(enum_thorough::hairTestAB($blonde), $blonde, "hairTest Global AB");
+	is(enum_thorough::hairTestAC($blonde), $blonde, "hairTest Global AC");
+
+	is(enum_thorough::hairTestB1($blonde), $blonde, "hairTest Global B1");
+	is(enum_thorough::hairTestB2($blonde), $blonde, "hairTest Global B2");
+	is(enum_thorough::hairTestB3($blonde), $blonde, "hairTest Global B3");
+	is(enum_thorough::hairTestB4($blonde), $blonde, "hairTest Global B4");
+	is(enum_thorough::hairTestB5($blonde), $blonde, "hairTest Global B5");
+	is(enum_thorough::hairTestB6($blonde), $blonde, "hairTest Global B6");
+	is(enum_thorough::hairTestB7($blonde), $blonde, "hairTest Global B7");
+	is(enum_thorough::hairTestB8($blonde), $blonde, "hairTest Global B8");
+	is(enum_thorough::hairTestB9($blonde), $blonde, "hairTest Global B9");
+	is(enum_thorough::hairTestBA($blonde), $blonde, "hairTest Global BA");
+	is(enum_thorough::hairTestBB($blonde), $blonde, "hairTest Global BB");
+	is(enum_thorough::hairTestBC($blonde), $blonde, "hairTest Global BC");
+
+	is(enum_thorough::hairTestC1($blonde), $blonde, "hairTest Global C1");
+	is(enum_thorough::hairTestC2($blonde), $blonde, "hairTest Global C2");
+	is(enum_thorough::hairTestC3($blonde), $blonde, "hairTest Global C3");
+	is(enum_thorough::hairTestC4($blonde), $blonde, "hairTest Global C4");
+	is(enum_thorough::hairTestC5($blonde), $blonde, "hairTest Global C5");
+	is(enum_thorough::hairTestC6($blonde), $blonde, "hairTest Global C6");
+	is(enum_thorough::hairTestC7($blonde), $blonde, "hairTest Global C7");
+	is(enum_thorough::hairTestC8($blonde), $blonde, "hairTest Global C8");
+	is(enum_thorough::hairTestC9($blonde), $blonde, "hairTest Global C9");
+	is(enum_thorough::hairTestCA($blonde), $blonde, "hairTest Global CA");
+	is(enum_thorough::hairTestCB($blonde), $blonde, "hairTest Global CB");
+	is(enum_thorough::hairTestCC($blonde), $blonde, "hairTest Global CC");
+}
+{
+	my $f = enum_thorough::FirStruct->new();
+	my $blonde = $enum_thorough::HairStruct::blonde;
+
+	is($f->hairTestFir1($blonde), $blonde, "hairTestFir 1");
+	is($f->hairTestFir2($blonde), $blonde, "hairTestFir 2");
+	is($f->hairTestFir3($blonde), $blonde, "hairTestFir 3");
+	is($f->hairTestFir4($blonde), $blonde, "hairTestFir 4");
+	is($f->hairTestFir5($blonde), $blonde, "hairTestFir 5");
+	is($f->hairTestFir6($blonde), $blonde, "hairTestFir 6");
+	is($f->hairTestFir7($blonde), $blonde, "hairTestFir 7");
+	is($f->hairTestFir8($blonde), $blonde, "hairTestFir 8");
+	is($f->hairTestFir9($blonde), $blonde, "hairTestFir 9");
+	is($f->hairTestFirA($blonde), $blonde, "hairTestFir A");
+}
+{
+	$enum_thorough::GlobalInstance = $enum_thorough::globalinstance2;
+	is($enum_thorough::GlobalInstance, $enum_thorough::globalinstance2, "GlobalInstance 1");
+
+	my $i = enum_thorough::Instances->new();
+	$i->{MemberInstance} = $enum_thorough::Instances::memberinstance3;
+	is($i->{MemberInstance}, $enum_thorough::Instances::memberinstance3, "MemberInstance 1");
+}
+{
+	is(enum_thorough::repeatTest($enum_thorough::one), 1, "repeatTest 1");
+	is(enum_thorough::repeatTest($enum_thorough::initial), 1, "repeatTest 2");
+	is(enum_thorough::repeatTest($enum_thorough::two), 2, "repeatTest 3");
+	is(enum_thorough::repeatTest($enum_thorough::three), 3, "repeatTest 4");
+{ local $TODO = "overzealous keyword guarding";
+	ok(defined($enum_thorough::last), "found enum value");
+SKIP: {
+	skip "enum value not in expected package", 1 unless defined $enum_thorough::last;
+	is(enum_thorough::repeatTest($enum_thorough::last), 3, "repeatTest 5");
+}}
+	is(enum_thorough::repeatTest($enum_thorough::end), 3, "repeatTest 6");
+}
+
+# these were the preexisting Perl testcases before the port.
+
+# Just test an in and out typemap for enum SWIGTYPE and const enum SWIGTYPE & typemaps
+is(enum_thorough::speedTest4($enum_thorough::SpeedClass::slow),
+	$enum_thorough::SpeedClass::slow, "speedTest Global 4");
+is(enum_thorough::speedTest5($enum_thorough::SpeedClass::slow),
+	$enum_thorough::SpeedClass::slow, "speedTest Global 5 failed");
+is(enum_thorough::speedTest4($enum_thorough::SpeedClass::fast),
+	$enum_thorough::SpeedClass::fast, "speedTest Global 4 failed");
+is(enum_thorough::speedTest5($enum_thorough::SpeedClass::fast),
+	$enum_thorough::SpeedClass::fast, "speedTest Global 5 failed");
diff --git a/trunk/Examples/test-suite/perl5/exception_order_runme.pl b/trunk/Examples/test-suite/perl5/exception_order_runme.pl
new file mode 100644
index 0000000..79b1b9d
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/exception_order_runme.pl
@@ -0,0 +1,25 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 7;
+BEGIN { use_ok('exception_order') }
+require_ok('exception_order');
+
+# adapted from ../python/exception_order_runme.py
+
+my $a = exception_order::A->new();
+
+eval { $a->foo() };
+isa_ok($@, "exception_order::E1");
+
+eval { $a->bar() };
+isa_ok($@, "exception_order::E2");
+
+eval { $a->foobar() };
+like($@, qr/\bpostcatch unknown\b/);
+
+eval { $a->barfoo(1) };
+isa_ok($@, "exception_order::E1");
+
+eval { $a->barfoo(2) };
+isa_ok($@, "exception_order::E2");
diff --git a/trunk/Examples/test-suite/perl5/global_vars_runme.pl b/trunk/Examples/test-suite/perl5/global_vars_runme.pl
new file mode 100644
index 0000000..b645f7b
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/global_vars_runme.pl
@@ -0,0 +1,11 @@
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('global_vars') }
+require_ok('global_vars');
+
+my $an = new global_vars::A();
+isa_ok($an, 'global_vars::A');
+$global_vars::ap = $an;
+is($global_vars::ap, $an, "global var assignment");
+
diff --git a/trunk/Examples/test-suite/perl5/grouping_runme.pl b/trunk/Examples/test-suite/perl5/grouping_runme.pl
new file mode 100755
index 0000000..2009cce
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/grouping_runme.pl
@@ -0,0 +1,17 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 6;
+BEGIN { use_ok('grouping') }
+require_ok('grouping');
+
+# adapted from ../python/grouping_runme.py
+
+is(grouping::test1(42), 42);
+
+isnt(eval { grouping::test2(42) }, undef);
+
+is(grouping::do_unary(37, $grouping::NEGATE), -37);
+
+$grouping::test3 = 42;
+is($grouping::test3, 42);
diff --git a/trunk/Examples/test-suite/perl5/ignore_parameter_runme.pl b/trunk/Examples/test-suite/perl5/ignore_parameter_runme.pl
new file mode 100755
index 0000000..8e75e0b
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/ignore_parameter_runme.pl
@@ -0,0 +1,33 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 14;
+BEGIN { use_ok('ignore_parameter') }
+require_ok('ignore_parameter');
+
+# adapted from ../java/ignore_parameter_runme.java
+
+# Runtime test checking the %typemap(ignore) macro
+
+# Compilation will ensure the number of arguments and type are correct.
+# Then check the return value is the same as the value given to the ignored parameter.
+is(ignore_parameter::jaguar(200, 0.0), "hello", "jaguar()");
+is(ignore_parameter::lotus("fast", 0.0), 101, "lotus()");
+is(ignore_parameter::tvr("fast", 200), 8.8, "tvr()");
+is(ignore_parameter::ferrari(), 101, "ferrari()");
+
+my $sc = new ignore_parameter::SportsCars();
+is($sc->daimler(200, 0.0), "hello", "daimler()");
+is($sc->astonmartin("fast", 0.0), 101, "astonmartin()");
+is($sc->bugatti("fast", 200), 8.8, "bugatti()");
+is($sc->lamborghini(), 101, "lamborghini()");
+
+# Check constructors are also generated correctly
+my $mc = eval { new ignore_parameter::MiniCooper(200, 0.0) };
+isa_ok($mc, 'ignore_parameter::MiniCooper');
+my $mm = eval { new ignore_parameter::MorrisMinor("slow", 0.0) };
+isa_ok($mm, 'ignore_parameter::MorrisMinor');
+my $fa = eval { new ignore_parameter::FordAnglia("slow", 200) };
+isa_ok($fa, 'ignore_parameter::FordAnglia');
+my $aa = eval { new ignore_parameter::AustinAllegro() };
+isa_ok($aa, 'ignore_parameter::AustinAllegro');
diff --git a/trunk/Examples/test-suite/perl5/import_nomodule_runme.pl b/trunk/Examples/test-suite/perl5/import_nomodule_runme.pl
new file mode 100644
index 0000000..f2136c1
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/import_nomodule_runme.pl
@@ -0,0 +1,13 @@
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('import_nomodule') }
+require_ok('import_nomodule');
+
+my $f = import_nomodule::create_Foo();
+import_nomodule::test1($f,42);
+ok(1, "basecase");
+
+my $b = new import_nomodule::Bar();
+import_nomodule::test1($b,37);
+ok(1, "testcase");
diff --git a/trunk/Examples/test-suite/perl5/imports_runme.pl b/trunk/Examples/test-suite/perl5/imports_runme.pl
new file mode 100644
index 0000000..fd730fe
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/imports_runme.pl
@@ -0,0 +1,5 @@
+use imports_b;
+use imports_a;
+
+$x = imports_bc::new_B();
+imports_ac::A_hello($x);
diff --git a/trunk/Examples/test-suite/perl5/inctest_runme.pl b/trunk/Examples/test-suite/perl5/inctest_runme.pl
new file mode 100644
index 0000000..db78c66
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/inctest_runme.pl
@@ -0,0 +1,12 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 3;
+BEGIN { use_ok('inctest') }
+require_ok('inctest');
+
+my $things = inctest::MY_THINGS->new();
+my $i = 0;
+$things->{IntegerMember} = $i;
+my $d = $things->{DoubleMember};
+ok(1);
diff --git a/trunk/Examples/test-suite/perl5/inherit_missing_runme.pl b/trunk/Examples/test-suite/perl5/inherit_missing_runme.pl
new file mode 100755
index 0000000..bc22602
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/inherit_missing_runme.pl
@@ -0,0 +1,20 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 5;
+BEGIN { use_ok('inherit_missing') }
+require_ok('inherit_missing');
+
+# adapted from ../python/inherit_missing_runme.py
+
+my $a = inherit_missing::new_Foo();
+my $b = inherit_missing::Bar->new();
+my $c = inherit_missing::Spam->new();
+
+is(inherit_missing::do_blah($a), "Foo::blah");
+
+is(inherit_missing::do_blah($b), "Bar::blah");
+
+is(inherit_missing::do_blah($c), "Spam::blah");
+
+inherit_missing::delete_Foo($a);
diff --git a/trunk/Examples/test-suite/perl5/inherit_runme.pl b/trunk/Examples/test-suite/perl5/inherit_runme.pl
new file mode 100644
index 0000000..3add80d
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/inherit_runme.pl
@@ -0,0 +1,9 @@
+use strict;
+use warnings;
+use Test::More tests => 3;
+BEGIN { use_ok('inherit') }
+require_ok('inherit');
+
+my $der = new inherit::CDerived();
+is($der->Foo(), "CBase::Foo", "inherit test");
+
diff --git a/trunk/Examples/test-suite/perl5/li_carrays_runme.pl b/trunk/Examples/test-suite/perl5/li_carrays_runme.pl
new file mode 100644
index 0000000..00d12cd
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/li_carrays_runme.pl
@@ -0,0 +1,72 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 38;
+BEGIN { use_ok('li_carrays') }
+require_ok('li_carrays');
+
+# array_class
+{
+  my $length = 5;
+  my $xyArray = new li_carrays::XYArray($length);
+  for (my $i=0; $i<$length; $i++) {
+    my $xy = $xyArray->getitem($i);
+    $xy->{x} = $i*10;
+    $xy->{y} = $i*100;
+    $xyArray->setitem($i, $xy);
+  }
+  for (my $i=0; $i<$length; $i++) {
+    is($xyArray->getitem($i)->{x}, $i*10);
+    is($xyArray->getitem($i)->{y}, $i*100);
+  }
+}
+
+{
+  # global array variable
+  my $length = 5;
+  my $xyArrayPointer = $li_carrays::globalXYArray;
+  my $xyArray = li_carrays::XYArray::frompointer($xyArrayPointer);
+  for (my $i=0; $i<$length; $i++) {
+    my $xy = $xyArray->getitem($i);
+    $xy->{x} = $i*10;
+    $xy->{y} = $i*100;
+    $xyArray->setitem($i, $xy);
+  }
+  for (my $i=0; $i<$length; $i++) {
+    is($xyArray->getitem($i)->{x}, $i*10);
+    is($xyArray->getitem($i)->{y}, $i*100);
+  }
+}
+
+# array_functions
+{
+  my $length = 5;
+  my $abArray = li_carrays::new_ABArray($length);
+  for (my $i=0; $i<$length; $i++) {
+    my $ab = li_carrays::ABArray_getitem($abArray, $i);
+    $ab->{a} = $i*10;
+    $ab->{b} = $i*100;
+	li_carrays::ABArray_setitem($abArray, $i, $ab);
+  }
+  for (my $i=0; $i<$length; $i++) {
+    is(li_carrays::ABArray_getitem($abArray, $i)->{a}, $i*10);
+    is(li_carrays::ABArray_getitem($abArray, $i)->{b}, $i*100);
+  }
+  li_carrays::delete_ABArray($abArray);
+}
+
+{
+  # global array variable
+  my $length = 3;
+  my $abArray = $li_carrays::globalABArray;
+  for (my $i=0; $i<$length; $i++) {
+    my $ab = li_carrays::ABArray_getitem($abArray, $i);
+    $ab->{a} = $i*10;
+    $ab->{b} = $i*100;
+	li_carrays::ABArray_setitem($abArray, $i, $ab);
+  }
+  for (my $i=0; $i<$length; $i++) {
+    is(li_carrays::ABArray_getitem($abArray, $i)->{a}, $i*10);
+    is(li_carrays::ABArray_getitem($abArray, $i)->{b}, $i*100);
+  }
+}
diff --git a/trunk/Examples/test-suite/perl5/li_cdata_carrays_runme.pl b/trunk/Examples/test-suite/perl5/li_cdata_carrays_runme.pl
new file mode 100644
index 0000000..133006e
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/li_cdata_carrays_runme.pl
@@ -0,0 +1,14 @@
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('li_cdata_carrays') }
+require_ok('li_cdata_carrays');
+
+my $ia = li_cdata_carrays::intArray->new(5);
+for (0..4) {
+  $ia->setitem($_, $_**2);
+}
+ok(1, "setitems");
+my $x = pack q{I5}, map $_**2, (0..4);
+my $y = li_cdata_carrays::cdata_int($ia->cast, 5);
+is($x, $y, "carrays");
diff --git a/trunk/Examples/test-suite/perl5/li_std_except_runme.pl b/trunk/Examples/test-suite/perl5/li_std_except_runme.pl
new file mode 100755
index 0000000..59d3126
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/li_std_except_runme.pl
@@ -0,0 +1,46 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 22;
+BEGIN { use_ok('li_std_except') }
+require_ok('li_std_except');
+
+# adapted from ../java/li_std_except_runme.java
+
+# these are not prescriptive tests, they just match the error classes I
+# found are currently being issued, we may want to provide a more
+# granular error api later, so don't let these tests stop code
+# improvements.
+
+my $test = new li_std_except::Test();
+eval { $test->throw_bad_exception() };
+like($@, qr/\bSystemError\b/, "throw_bad_exception");
+eval { $test->throw_domain_error() };
+like($@, qr/\bValueError\b/, "throw_domain_error");
+like($@, qr/\boops\b/, "throw_domain_error message");
+eval { $test->throw_exception() };
+like($@, qr/\bSystemError\b/, "throw_exception");
+eval { $test->throw_invalid_argument() };
+like($@, qr/\bValueError\b/, "throw_invalid_argument");
+like($@, qr/\boops\b/, "throw_invalid_argument message");
+eval { $test->throw_length_error() };
+like($@, qr/\bIndexError\b/, "throw_length_error");
+like($@, qr/\boops\b/, "throw_length_error message");
+eval { $test->throw_logic_error() };
+like($@, qr/\bRuntimeError\b/, "throw_logic_error");
+like($@, qr/\boops\b/, "throw_logic_error message");
+eval { $test->throw_out_of_range() };
+like($@, qr/\bIndexError\b/, "throw_out_of_range");
+like($@, qr/\boops\b/, "throw_out_of_range message");
+eval { $test->throw_overflow_error() };
+like($@, qr/\bOverflowError\b/, "throw_overflow_error");
+like($@, qr/\boops\b/, "throw_overflow_error message");
+eval { $test->throw_range_error() };
+like($@, qr/\bOverflowError\b/, "throw_range_error");
+like($@, qr/\boops\b/, "throw_range_error message");
+eval { $test->throw_runtime_error() };
+like($@, qr/\bRuntimeError\b/, "throw_runtime_error");
+like($@, qr/\boops\b/, "throw_runtime_error message");
+eval { $test->throw_underflow_error() };
+like($@, qr/\bOverflowError\b/, "throw_underflow_error");
+like($@, qr/\boops\b/, "throw_underflow_error message");
diff --git a/trunk/Examples/test-suite/perl5/li_std_list.i b/trunk/Examples/test-suite/perl5/li_std_list.i
new file mode 100644
index 0000000..bae475e
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/li_std_list.i
@@ -0,0 +1,46 @@
+%module li_std_list
+
+%include "std_list.i"
+
+%{
+#include <algorithm>
+#include <functional>
+#include <numeric>
+%}
+
+namespace std {
+    %template(IntList) list<int>;
+}
+
+%template(DoubleList) std::list<double>;
+
+%inline %{
+typedef float Real;
+%}
+
+namespace std {
+    %template(RealList) list<Real>;
+}
+
+%inline %{
+
+double average(std::list<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+
+void halve_in_place(std::list<double>& v) {
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+struct Struct {
+  double num;
+  Struct() : num(0.0) {}
+  Struct(double d) : num(d) {}
+//  bool operator==(const Struct &other) { return (num == other.num); }
+};
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/perl5/li_std_string_runme.pl b/trunk/Examples/test-suite/perl5/li_std_string_runme.pl
new file mode 100644
index 0000000..9ec7dd0
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/li_std_string_runme.pl
@@ -0,0 +1,113 @@
+use strict;
+use warnings;
+use Test::More tests => 30;
+BEGIN { use_ok('li_std_string') }
+require_ok('li_std_string');
+
+use Devel::Peek;
+# Checking expected use of %typemap(in) std::string {}
+li_std_string::test_value("Fee");
+
+# Checking expected result of %typemap(out) std::string {}
+is(li_std_string::test_value("Fi"), "Fi", "Test 1");
+
+
+# Verify type-checking for %typemap(in) std::string {}
+eval { li_std_string::test_value(undef) };
+like($@, qr/\bTypeError\b/, "Test 2");
+
+# Checking expected use of %typemap(in) const std::string & {}
+li_std_string::test_const_reference("Fo");
+
+# Checking expected result of %typemap(out) const std::string& {}
+is(li_std_string::test_const_reference("Fum"), "Fum", "Test 3");
+
+# Verify type-checking for %typemap(in) const std::string & {}
+eval { li_std_string::test_const_reference(undef) };
+like($@, qr/\bValueError\b/, "Test 4");
+
+#
+# Input and output typemaps for pointers and non-const references to
+# std::string are *not* supported; the following tests confirm
+# that none of these cases are slipping through.
+#
+
+my $stringPtr = undef;
+
+$stringPtr = li_std_string::test_pointer_out();
+
+li_std_string::test_pointer($stringPtr);
+
+$stringPtr = li_std_string::test_const_pointer_out();
+
+li_std_string::test_const_pointer($stringPtr);
+
+$stringPtr = li_std_string::test_reference_out();
+
+li_std_string::test_reference($stringPtr);
+
+# Check throw exception specification
+eval { li_std_string::test_throw() };
+is($@, "test_throw message", "Test 5");
+{ local $TODO = "why is the error not a Perl string?";
+eval { li_std_string::test_const_reference_throw() };
+is($@, "<some kind of string>", "Test 6");
+}
+
+# Global variables
+my $s = "initial string";
+is($li_std_string::GlobalString2, "global string 2", "GlobalString2 test 1");
+$li_std_string::GlobalString2 = $s;
+is($li_std_string::GlobalString2, $s, "GlobalString2 test 2");
+is($li_std_string::ConstGlobalString, "const global string", "ConstGlobalString test");
+
+# Member variables
+my $myStructure = new li_std_string::Structure();
+is($myStructure->{MemberString2}, "member string 2", "MemberString2 test 1");
+$myStructure->{MemberString2} = $s;
+is($myStructure->{MemberString2}, $s, "MemberString2 test 2");
+is($myStructure->{ConstMemberString}, "const member string", "ConstMemberString test");
+
+is($li_std_string::Structure::StaticMemberString2, "static member string 2", "StaticMemberString2 test 1");
+$li_std_string::Structure::StaticMemberString2 = $s;
+is($li_std_string::Structure::StaticMemberString2, $s, "StaticMemberString2 test 2");
+is($li_std_string::Structure::ConstStaticMemberString, "const static member string", "ConstStaticMemberString test");
+
+is(li_std_string::test_reference_input("hello"), "hello", "reference_input");
+
+is(li_std_string::test_reference_inout("hello"), "hellohello", "reference_inout");
+
+
+no strict;
+my $gen1 = new li_std_string::Foo();
+is($gen1->test(1), 2, "ulonglong");
+is($gen1->test("1"), "11", "ulonglong");
+is($gen1->testl(12345), 12346, "ulonglong small number");
+# Note: 32 bit builds of perl will fail this test as the number is stored internally in scientific notation 
+# (USE_64_BIT_ALL probably needs defining when building Perl in order to avoid this)
+SKIP: {
+	skip "this Perl does not seem to do 64 bit ints", 1
+		if 9234567890121111114 - 9234567890121111113 != 1;
+	local $TODO;
+	use Config;
+	$TODO = "if we're lucky this might work" unless $Config{use64bitall};
+	is(eval { $gen1->testl(9234567890121111113) }, 9234567890121111114, "ulonglong big number");
+	# TODO: I suspect we can get by with "use64bitint", but I'll have to
+	# work that out later. -talby
+}
+is($gen1->testl("9234567890121111113"), "9234567890121111114", "ulonglong big number");
+
+
+is(li_std_string::stdstring_empty(), "", "stdstring_empty");
+
+is(li_std_string::c_empty(),  "", "c_empty");
+
+
+is(li_std_string::c_null(), undef, "c_empty");
+
+
+is(li_std_string::get_null(li_std_string::c_null()), undef, "c_empty");
+
+is(li_std_string::get_null(li_std_string::c_empty()), "non-null", "c_empty");
+
+is(li_std_string::get_null(li_std_string::stdstring_empty()), "non-null", "stdstring_empty");
diff --git a/trunk/Examples/test-suite/perl5/li_typemaps_runme.pl b/trunk/Examples/test-suite/perl5/li_typemaps_runme.pl
new file mode 100644
index 0000000..c149284
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/li_typemaps_runme.pl
@@ -0,0 +1,77 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 415;
+BEGIN { use_ok('li_typemaps') }
+require_ok('li_typemaps');
+
+sub batch { my($type, @values) = @_;
+  # this is a little ugly because I'm trying to be clever and save my
+  # wrists from hammering out all these tests.
+  for my $val (@values) {
+    for my $tst (qw(
+      in inr
+      out outr
+      inout inoutr
+    )) {
+      my $func = $tst . '_' . $type;
+      is(eval { li_typemaps->can($func)->($val) }, $val, "$func $val");
+      if($@) {
+        my $err = $@;
+        $err =~ s/^/#\$\@# /mg;
+        print $err;
+      }
+    }
+  }
+}
+
+batch('bool', '', 1);
+# let's assume we're at least on a 32 bit machine
+batch('int', -0x80000000, -1, 0, 1, 12, 0x7fffffff);
+# long could be bigger, but it's at least this big
+batch('long', -0x80000000, -1, 0, 1, 12, 0x7fffffff);
+batch('short', -0x8000, -1, 0, 1, 12, 0x7fff);
+batch('uint', 0, 1, 12, 0xffffffff);
+batch('ushort', 0, 1, 12, 0xffff);
+batch('ulong', 0, 1, 12, 0xffffffff);
+batch('uchar', 0, 1, 12, 0xff);
+batch('schar', -0x80, 0, 1, 12, 0x7f);
+
+# IEEE 754 machine, please!
+batch('float',
+  -(2 - 2 ** -23) * 2 ** 127,
+  -1, -2 ** -149, 0, 2 ** -149, 1,
+  (2 - 2 ** -23) * 2 ** 127,
+  'nan');
+{ local $TODO = "shouldn't some Inf <=> float work?";
+  # I'm going to guess that it could work reasonably as
+  # NV Inf => float Inf
+  # float Inf => NV NaN
+  # but this needs some thought.
+  batch('float', 'inf');
+}
+batch('double',
+  -(2 - 2 ** -53) ** 1023,
+  -1, -2 ** -1074, 0, 2 ** 1074,
+  (2 - 2 ** -53) ** 1023,
+  'nan', 'inf');
+batch('longlong', -1, 0, 1, 12);
+batch('ulonglong', 0, 1, 12);
+SKIP: {
+  my $a = "8000000000000000";
+  my $b = "7fffffffffffffff";
+  my $c = "ffffffffffffffff";
+  skip "not a 64bit Perl", 18 unless eval { pack 'q', 1 };
+  batch('longlong', -hex($a), hex($b));
+  batch('ulonglong', hex($c));
+}
+
+my($foo, $int) = li_typemaps::out_foo(10);
+isa_ok($foo, 'li_typemaps::Foo');
+is($foo->{a}, 10);
+is($int, 20);
+
+my($a, $b) = li_typemaps::inoutr_int2(13, 31);
+is($a, 13);
+is($b, 31);
+
diff --git a/trunk/Examples/test-suite/perl5/member_pointer_runme.pl b/trunk/Examples/test-suite/perl5/member_pointer_runme.pl
new file mode 100644
index 0000000..ff2cee7
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/member_pointer_runme.pl
@@ -0,0 +1,51 @@
+use strict;
+use warnings;
+use Test::More tests => 9;
+# member_pointer using pointers to member functions
+
+BEGIN { use_ok('member_pointer') }
+require_ok('member_pointer');
+
+sub check($;$;$) {
+  my($what, $expected, $actual) = @_;
+  if ($expected != $actual) {
+    die ("Failed: $what Expected: $expected Actual: $actual");
+  }
+}
+
+# Get the pointers
+
+my $area_pt = member_pointer::areapt();
+my $perim_pt = member_pointer::perimeterpt();
+
+# Create some objects
+
+my $s = new member_pointer::Square(10);
+
+# Do some calculations
+
+is(100.0, member_pointer::do_op($s,$area_pt), "Square area");
+is(40.0, member_pointer::do_op($s,$perim_pt), "Square perim");
+no strict;
+
+my $memberPtr = $member_pointer::areavar;
+$memberPtr = $member_pointer::perimetervar;
+
+# Try the variables
+is(100.0, member_pointer::do_op($s,$member_pointer::areavar), "Square area");
+is(40.0, member_pointer::do_op($s,$member_pointer::perimetervar), "Square perim");
+
+# Modify one of the variables
+$member_pointer::areavar = $perim_pt;
+
+is(40.0, member_pointer::do_op($s,$member_pointer::areavar), "Square perimeter");
+
+# Try the constants
+
+$memberPtr = $member_pointer::AREAPT;
+$memberPtr = $member_pointer::PERIMPT;
+$memberPtr = $member_pointer::NULLPT;
+
+is(100.0, member_pointer::do_op($s,$member_pointer::AREAPT), "Square area");
+is(40.0, member_pointer::do_op($s,$member_pointer::PERIMPT), "Square perim");
+
diff --git a/trunk/Examples/test-suite/perl5/minherit_runme.pl b/trunk/Examples/test-suite/perl5/minherit_runme.pl
new file mode 100755
index 0000000..1f3afad
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/minherit_runme.pl
@@ -0,0 +1,72 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 38;
+BEGIN { use_ok('minherit') }
+require_ok('minherit');
+
+# adapted from ../python/minherit_runme.py
+
+my $a = minherit::Foo->new();
+my $b = minherit::Bar->new();
+my $c = minherit::FooBar->new();
+my $d = minherit::Spam->new();
+
+is($a->xget(), 1);
+
+is($b->yget(), 2);
+
+is($c->xget(), 1);
+is($c->yget(), 2);
+is($c->zget(), 3);
+
+is($d->xget(), 1);
+is($d->yget(), 2);
+is($d->zget(), 3);
+is($d->wget(), 4);
+
+is(minherit::xget($a), 1);
+
+is(minherit::yget($b), 2);
+
+is(minherit::xget($c), 1);
+is(minherit::yget($c), 2);
+is(minherit::zget($c), 3);
+
+is(minherit::xget($d), 1);
+is(minherit::yget($d), 2);
+is(minherit::zget($d), 3);
+is(minherit::wget($d), 4);
+
+# Cleanse all of the pointers and see what happens
+
+my $aa = minherit::toFooPtr($a);
+my $bb = minherit::toBarPtr($b);
+my $cc = minherit::toFooBarPtr($c);
+my $dd = minherit::toSpamPtr($d);
+
+is($aa->xget, 1);
+
+is($bb->yget(), 2);
+
+is($cc->xget(), 1);
+is($cc->yget(), 2);
+is($cc->zget(), 3);
+
+is($dd->xget(), 1);
+is($dd->yget(), 2);
+is($dd->zget(), 3);
+is($dd->wget(), 4);
+
+is(minherit::xget($aa), 1);
+
+is(minherit::yget($bb), 2);
+
+is(minherit::xget($cc), 1);
+is(minherit::yget($cc), 2);
+is(minherit::zget($cc), 3);
+
+is(minherit::xget($dd), 1);
+is(minherit::yget($dd), 2);
+is(minherit::zget($dd), 3);
+is(minherit::wget($dd), 4);
diff --git a/trunk/Examples/test-suite/perl5/multiple_inheritance_runme.pl b/trunk/Examples/test-suite/perl5/multiple_inheritance_runme.pl
new file mode 100644
index 0000000..1d913ff
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/multiple_inheritance_runme.pl
@@ -0,0 +1,12 @@
+use strict;
+use warnings;
+use Test::More tests => 5;
+BEGIN { use_ok('multiple_inheritance') }
+require_ok('multiple_inheritance');
+
+my $fooBar = new multiple_inheritance::FooBar();
+is($fooBar->foo(), 2, "Runtime test1");
+
+is($fooBar->bar(), 1, "Runtime test2");
+
+is($fooBar->fooBar(), 3, "Runtime test3 ");
diff --git a/trunk/Examples/test-suite/perl5/naturalvar_runme.pl b/trunk/Examples/test-suite/perl5/naturalvar_runme.pl
new file mode 100755
index 0000000..c0f972d
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/naturalvar_runme.pl
@@ -0,0 +1,22 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 5;
+BEGIN { use_ok('naturalvar') }
+require_ok('naturalvar');
+
+# adapted from ../python/naturalvar_runme.py
+
+my $f = naturalvar::Foo->new();
+isa_ok($f, 'naturalvar::Foo');
+my $b = naturalvar::Bar->new();
+isa_ok($b, 'naturalvar::Bar');
+
+$b->{f} = $f;
+
+$naturalvar::s = "hello";
+
+$b->{s} = "hello";
+
+is($naturalvar::s, $b->{s});
+
diff --git a/trunk/Examples/test-suite/perl5/operator_overload_break_runme.pl b/trunk/Examples/test-suite/perl5/operator_overload_break_runme.pl
new file mode 100644
index 0000000..fd3fe33
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/operator_overload_break_runme.pl
@@ -0,0 +1,55 @@
+#!/usr/bin/perl -w
+use strict;
+use Test::More tests => 9;
+
+use operator_overload_break;
+
+# Workaround for 
+#   ok( not (expression) , "test description" );
+# does not working in older versions of Perl, eg 5.004_04
+sub ok_not ($;$) {
+    my($test, $name) = @_;
+    $test = not $test;
+    ok($test, $name);
+}
+
+pass("loaded");
+
+my $op = operator_overload_break::Op->new(5);
+
+isa_ok($op, "operator_overload_break::Op");
+
+ok((2 == $op - 3),
+   "subtraction");
+
+$op->{k} = 37;
+
+ok((40 == $op + 3),
+   "addition");
+
+$op->{k} = 22;
+
+ok((10 == (32 - $op)),
+   "reversed subtraction");
+
+ok_not((3 == $op),
+       'not equal');
+
+$op->{k} = 3;
+
+++$op;
+
+ok(($op == 4),
+   "pre-increment operator");
+
+$op++;
+
+ok(($op == 5),
+   "post-increment operator");
+
+my $op2 = ++$op;
+
+$op2 = $op++;
+
+ok(($op == 7) and ($op2 == 7),
+   "multiple post-increments");
diff --git a/trunk/Examples/test-suite/perl5/operator_overload_runme.pl b/trunk/Examples/test-suite/perl5/operator_overload_runme.pl
new file mode 100644
index 0000000..ba3f33a
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/operator_overload_runme.pl
@@ -0,0 +1,175 @@
+#!/usr/bin/perl -w
+use strict;
+use Test::More tests => 39;
+
+use operator_overload;
+
+# Workaround for 
+#   ok( not (expression) , "test description" );
+# does not working in older versions of Perl, eg 5.004_04
+sub ok_not ($;$) {
+    my($test, $name) = @_;
+    $test = not $test;
+    ok($test, $name);
+}
+
+pass("loaded");
+
+# first check all the operators are implemented correctly from pure C++ code
+operator_overloadc::Op_sanity_check();
+
+my $op = operator_overload::Op->new();
+
+isa_ok($op, "operator_overload::Op");
+
+my $op2 = operator_overload::Op->new();
+
+isa_ok($op2, "operator_overload::Op");
+
+# operator equal
+$op->{i} = 5;
+$op2->{i} = 3;
+
+ok_not(($op == $op2), "operator equal: not equal");
+
+$op->{i} = 3;
+ok(($op == $op2), "operator equal: equal");
+
+# operator not equal
+$op->{i} = 5;
+$op2->{i} = 3;
+
+ok(($op != $op2), "operator not equal: not equal");
+
+$op->{i} = 3;
+ok_not(($op != $op2), "operator not equal: equal");
+
+# stringify operator
+$op->{i} = 3;
+is("Op(3)", "$op", "operator stringify");
+
+# addition operator
+$op->{i} = 3;
+$op2->{i} = 3;
+my $op3 = $op + $op2;
+is($op3->{i}, 6, "operator addition");
+
+# addition assignment operator
+$op->{i} = 3;
+$op2->{i} = 3;
+$op += $op2;
+is($op->{i}, 6, "operator additive assignment");
+
+# subtraction operator
+$op3->{i} = 6;
+$op2->{i} = 3;
+$op = $op3 - $op2;
+is($op->{i}, 3, "operator subtraction");
+
+# reversed subtraction operator (with int)
+$op3->{i} = 3;
+$op = 6 - $op3;
+is($op->{i}, 3, "reversed operator subtraction (with int)");
+
+# subtractive assignment operator
+$op->{i} = 6;
+$op2->{i} = 3;
+$op -= $op2;
+is($op->{i}, 3, "operator subtractive assignment");
+
+# multiplication operator
+$op->{i} = 3;
+$op2->{i} = 3;
+$op3 = $op * $op2;
+is($op3->{i}, 9, "operator multiplication");
+
+# division operator
+$op->{i} = 9;
+$op2->{i} = 3;
+$op3 = $op / $op2;
+is($op3->{i}, 3, "operator division");
+
+# modulus operator
+$op->{i} = 8;
+$op2->{i} = 3;
+$op3 = $op % $op2;
+is($op3->{i}, 2, "operator modulus");
+
+# greater than operator
+$op->{i} = 8;
+$op2->{i} = 3;
+ok($op > $op2, "operator greater than");
+ok_not(($op2 > $op), "operator greater than");
+$op->{i} = 3;
+ok_not(($op2 > $op), "operator greater than");
+ok_not(($op > $op2), "operator greater than");
+
+# greater than or equal operator
+$op->{i} = 8;
+$op2->{i} = 3;
+ok($op >= $op2, "operator greater than or equal");
+ok_not(($op2 >= $op), "operator greater than or equal");
+$op->{i} = 3;
+ok(($op2 >= $op), "operator greater than or equal");
+ok(($op >= $op2), "operator greater than or equal");
+
+# lesser than operator
+$op2->{i} = 8;
+$op->{i} = 3;
+ok($op < $op2, "operator lesser than");
+ok_not(($op2 < $op), "operator lesser than");
+$op2->{i} = 3;
+ok_not(($op2 < $op), "operator lesser than");
+ok_not(($op < $op2), "operator lesser than");
+
+# less than or equal operator
+$op2->{i} = 8;
+$op->{i} = 3;
+ok($op <= $op2, "operator lesser than or equal");
+ok_not(($op2 <= $op), "operator lesser than or equal");
+$op2->{i} = 3;
+ok(($op2 <= $op), "operator less than or equal");
+ok(($op <= $op2), "operator less than or equal");
+
+# post-increment operator
+$op->{i} = 7;
+$op++;
+is($op->{i}, 8, "operator post-increment");
+
+# pre-increment operator
+$op->{i} = 7;
+++$op;
+is($op->{i}, 8, "operator pre-increment");
+
+# post-decrement operator
+$op->{i} = 7;
+$op--;
+is($op->{i}, 6, "operator post-decrement");
+
+# pre-decrement operator
+$op->{i} = 7;
+--$op;
+is($op->{i}, 6, "operator pre-decrement");
+
+# neg operator
+$op->{i} = 3;
+$op2 = -$op;
+is($op2->{i}, -3, "operator neg");
+
+# not operator
+$op->{i} = 0;
+is(!$op, !0, "operator not");
+
+$op->{i} = 1;
+is(!$op, !1, "operator not");
+
+### # and operator
+### $op->{i} = 4;
+### $op2->{i} = 2;
+### 
+### is($op & $op2, 4 & 2, "operator and");
+### 
+### isnt(($op & $op2), (10 & 2), "operator and - false");
+
+# fail("testing failed condition");
+
diff --git a/trunk/Examples/test-suite/perl5/overload_copy_runme.pl b/trunk/Examples/test-suite/perl5/overload_copy_runme.pl
new file mode 100644
index 0000000..06d03f5
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/overload_copy_runme.pl
@@ -0,0 +1,5 @@
+
+use overload_copy;
+
+$f = new overload_copy::Foo();
+$g = new overload_copy::Foo($f);
diff --git a/trunk/Examples/test-suite/perl5/overload_simple_runme.pl b/trunk/Examples/test-suite/perl5/overload_simple_runme.pl
new file mode 100644
index 0000000..27719aa
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/overload_simple_runme.pl
@@ -0,0 +1,191 @@
+#!/usr/bin/perl -w
+use overload_simple;
+use vars qw/$DOWARN/;
+use strict;
+use Test::More tests => 71;
+
+pass("loaded");
+
+my $f = new overload_simple::Foo();
+isa_ok($f, "overload_simple::Foo");
+my $b = new overload_simple::Bar();
+isa_ok($b, "overload_simple::Bar");
+my $v = overload_simple::malloc_void(32);
+isa_ok($v, "_p_void");
+
+
+#
+# Silence warnings about bad types
+#
+BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } }
+#
+#these tests should 'fail'
+#
+eval { overload_simple::fint("l") };
+ok($@, "fint(int) - int");
+
+eval { overload_simple::fint("3.5") };
+ok($@, "fint(int) - double");
+
+eval { overload_simple::fdouble("l") };
+ok($@, "fint(double) - int");
+
+eval { overload_simple::fdouble("1.5/2.0") };
+ok($@, "fint(double) - double");
+
+#
+#enable the warnings again
+#
+$DOWARN =1;
+
+#
+# 'simple' dispatch (no overload) of int and double arguments
+#
+
+is(overload_simple::fint(3), "fint:int", "fint(int) - int");
+
+is(overload_simple::fint("1"), "fint:int", "fint(int) - string int");
+
+is(overload_simple::fint(3.0), "fint:int", "fint(int) - double");
+
+is(overload_simple::fint("3.0"), "fint:int", "fint(int) - string double");
+
+# old bad case that now works
+my $n = 3;
+$n = $n + 1;
+is(overload_simple::fint($n), "fint:int", "fint(int) - int var");
+
+is(overload_simple::fint(4/2), "fint:int", "fint(int) - divide int denom");
+
+is(overload_simple::fint(4/2.0), "fint:int", "fint(int) - divide double denom");
+
+is(overload_simple::fdouble(3), "fdouble:double", "fdouble(double) - int");
+
+is(overload_simple::fdouble("3"), "fdouble:double", "fdouble(double) - string int");
+
+is(overload_simple::fdouble(3.0), "fdouble:double", "fdouble(double) - double");
+
+is(overload_simple::fdouble("3.0"), "fdouble:double", "fdouble(double) - string doubl");
+
+#
+# Overload between int and double
+#
+is(overload_simple::num(3), "num:int", "num(int) - int");
+
+is(overload_simple::num("3"), "num:int", "num(int) - string int");
+
+is(overload_simple::num(3.0), "num:double", "num(int) - double");
+
+is(overload_simple::num("3.0"), "num:double", "num(int) - string double");
+
+#
+# Overload between int, double, char * and many types.
+#
+is(overload_simple::foo(3), "foo:int", "foo:int - int");
+
+is(overload_simple::foo(3.0), "foo:double", "foo:double - double");
+
+is(overload_simple::foo("3"), "foo:char *", "foo:char * - string int");
+
+is(overload_simple::foo("3.0"), "foo:char *", "foo:char * - string double");
+
+is(overload_simple::foo("hello"), "foo:char *", "foo:char * string");
+
+is(overload_simple::foo($f), "foo:Foo *", "foo:Foo *");
+
+is(overload_simple::foo($b), "foo:Bar *", "foo:Bar *");
+
+is(overload_simple::foo($v), "foo:void *", "foo:void *");
+
+is(overload_simple::blah(3), "blah:double", "blah:double");
+
+is(overload_simple::blah("hello"), "blah:char *", "blah:char *");
+
+my $s = new overload_simple::Spam();
+
+is($s->foo(3), "foo:int", "Spam::foo:int");
+
+is($s->foo(3.0), "foo:double", "Spam::foo(double)");
+
+is($s->foo("hello"), "foo:char *", "Spam::foo:char *");
+
+is($s->foo($f), "foo:Foo *", "Spam::foo(Foo *)");
+
+is($s->foo($b), "foo:Bar *", "Spam::foo(Bar *)");
+
+is($s->foo($v), "foo:void *", "Spam::foo(void *)");
+
+is(overload_simple::Spam::bar(3), "bar:int", "Spam::bar(int)");
+
+is(overload_simple::Spam::bar(3.0), "bar:double", "Spam::bar(double)");
+
+is(overload_simple::Spam::bar("hello"), "bar:char *", "Spam::bar(char *)");
+
+is(overload_simple::Spam::bar($f), "bar:Foo *", "Spam::bar(Foo *)");
+
+is(overload_simple::Spam::bar($b), "bar:Bar *", "Spam::bar(Bar *)");
+
+is(overload_simple::Spam::bar($v), "bar:void *", "Spam::bar(void *)");
+
+# Test constructors
+
+$s = new overload_simple::Spam();
+isa_ok($s, "overload_simple::Spam");
+
+is($s->{type}, "none", "Spam()");
+
+$s = new overload_simple::Spam(3);
+isa_ok($s, "overload_simple::Spam");
+
+is($s->{type}, "int", "Spam(int)");
+
+$s = new overload_simple::Spam(3.0);
+isa_ok($s, "overload_simple::Spam");
+is($s->{type}, "double", "Spam(double)");
+
+$s = new overload_simple::Spam("hello");
+isa_ok($s, "overload_simple::Spam");
+is($s->{type}, "char *", "Spam(char *)");
+
+$s = new overload_simple::Spam($f);
+isa_ok($s, "overload_simple::Spam");
+is($s->{type}, "Foo *", "Spam(Foo *)");
+
+$s = new overload_simple::Spam($b);
+isa_ok($s, "overload_simple::Spam");
+is($s->{type}, "Bar *", "Spam(Bar *)");
+
+$s = new overload_simple::Spam($v);
+isa_ok($s, "overload_simple::Spam");
+is($s->{type}, "void *", "Spam(void *)");
+
+#
+# Combine dispatch
+#
+
+
+is(overload_simple::fid(3, 3.0), "fid:intdouble", "fid(int,double)");
+
+is(overload_simple::fid(3.0, 3), "fid:doubleint", "fid(double,int)");
+
+is(overload_simple::fid(3.0, 3.0), "fid:doubledouble", "fid(double,double)");
+
+is(overload_simple::fid(3, 3), "fid:intint", "fid(int,int)");
+
+# with strings now
+
+is(overload_simple::fid(3, "3.0"), "fid:intdouble", "fid(int,double)");
+
+is(overload_simple::fid("3", 3.0), "fid:intdouble", "fid(int,double)");
+
+is(overload_simple::fid("3", "3.0"), "fid:intdouble", "fid(int,double)");
+
+is(overload_simple::fid(3.0, "3"), "fid:doubleint", "fid(double,int)");
+
+is(overload_simple::fid("3.0", "3.0"), "fid:doubledouble", "fid:doubledouble");
+
+is(overload_simple::fid("3", 3), "fid:intint", "fid:fid(int,int)");
+
+isnt(overload_simple::fbool(0), overload_simple::fbool(1), "fbool(bool)");
+
+is(2, overload_simple::fbool(2), "fbool(int)");
diff --git a/trunk/Examples/test-suite/perl5/packageoption_runme.pl b/trunk/Examples/test-suite/perl5/packageoption_runme.pl
new file mode 100644
index 0000000..debea78
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/packageoption_runme.pl
@@ -0,0 +1,24 @@
+#!/usr/bin/perl -w
+use strict;
+use Test::More tests => 4;
+
+BEGIN { use_ok('packageoption_a'); }
+BEGIN { use_ok('packageoption_b'); }
+
+# Workaround for 
+#   ok( not (expression) , "test description" );
+# does not working in older versions of Perl, eg 5.004_04
+sub ok_not ($;$) {
+    my($test, $name) = @_;
+    $test = not $test;
+    ok($test, $name);
+}
+
+my $a = C::A->new();
+
+isa_ok($a, 'C::A');
+
+my $b = C::B->new();
+
+isa_ok($b, 'C::B');
+       
diff --git a/trunk/Examples/test-suite/perl5/preproc_runme.pl b/trunk/Examples/test-suite/perl5/preproc_runme.pl
new file mode 100755
index 0000000..89e25f8
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/preproc_runme.pl
@@ -0,0 +1,14 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 6;
+BEGIN { use_ok('preproc') }
+require_ok('preproc');
+
+# adapted from ../python/preproc_runme.py
+
+is($preproc::endif, 1);
+is($preproc::define, 1);
+is($preproc::defined, 1);
+is($preproc::one * 2, $preproc::two);
+
diff --git a/trunk/Examples/test-suite/perl5/primitive_ref_runme.pl b/trunk/Examples/test-suite/perl5/primitive_ref_runme.pl
new file mode 100644
index 0000000..20d37a7
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/primitive_ref_runme.pl
@@ -0,0 +1,18 @@
+use strict;
+use warnings;
+use Test::More tests => 14;
+BEGIN { use_ok('primitive_ref') }
+require_ok('primitive_ref');
+
+is(primitive_ref::ref_int(3), 3, "ref_int");
+is(primitive_ref::ref_uint(3), 3, "ref_uint");
+is(primitive_ref::ref_short(3), 3, "ref_short");
+is(primitive_ref::ref_ushort(3), 3, "ref_ushort");
+is(primitive_ref::ref_long(3), 3, "ref_long");
+is(primitive_ref::ref_ulong(3), 3, "ref_ulong");
+is(primitive_ref::ref_schar(3), 3, "ref_schar");
+is(primitive_ref::ref_uchar(3), 3, "ref_uchar");
+is(primitive_ref::ref_bool(1), 1, "ref_bool");
+is(primitive_ref::ref_float(3.5), 3.5, "ref_float");
+is(primitive_ref::ref_double(3.5), 3.5, "ref_double");
+is(primitive_ref::ref_char('x'), 'x', "ref_char");
diff --git a/trunk/Examples/test-suite/perl5/primitive_types_runme.pl b/trunk/Examples/test-suite/perl5/primitive_types_runme.pl
new file mode 100755
index 0000000..6d7b05d
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/primitive_types_runme.pl
@@ -0,0 +1,282 @@
+use strict;
+use warnings;
+use Test::More tests => 54;
+BEGIN { use_ok('primitive_types') }
+require_ok('primitive_types');
+
+primitive_types::var_init();
+
+# assigning globals calls
+$primitive_types::var_bool = $primitive_types::sct_bool;
+$primitive_types::var_schar = $primitive_types::sct_schar;
+$primitive_types::var_uchar = $primitive_types::sct_uchar;
+$primitive_types::var_int = $primitive_types::sct_int;
+$primitive_types::var_uint = $primitive_types::sct_uint;
+$primitive_types::var_short = $primitive_types::sct_short;
+$primitive_types::var_ushort = $primitive_types::sct_ushort;
+$primitive_types::var_long = $primitive_types::sct_long;
+$primitive_types::var_ulong = $primitive_types::sct_ulong;
+$primitive_types::var_llong = $primitive_types::sct_llong;
+$primitive_types::var_ullong = $primitive_types::sct_ullong;
+$primitive_types::var_char = $primitive_types::sct_char;
+$primitive_types::var_pchar = $primitive_types::sct_pchar;
+$primitive_types::var_pcharc = $primitive_types::sct_pcharc;
+$primitive_types::var_pint = $primitive_types::sct_pint;
+$primitive_types::var_sizet = $primitive_types::sct_sizet;
+$primitive_types::var_hello = $primitive_types::sct_hello;
+$primitive_types::var_myint = $primitive_types::sct_myint;
+$primitive_types::var_namet = $primitive_types::def_namet;
+$primitive_types::var_parami = $primitive_types::sct_parami;
+$primitive_types::var_paramd = $primitive_types::sct_paramd;
+$primitive_types::var_paramc = $primitive_types::sct_paramc;
+
+ok(primitive_types::v_check(), "v_check");
+
+#def pyerror(name, val, cte):
+#  print "bad val/cte", name, val, cte
+#  raise RuntimeError
+#  pass
+
+is($primitive_types::var_bool, $primitive_types::cct_bool, "bool");
+is($primitive_types::var_schar, $primitive_types::cct_schar, "schar");
+is($primitive_types::var_uchar, $primitive_types::cct_uchar, "uchar");
+is($primitive_types::var_int, $primitive_types::cct_int, "int");
+is($primitive_types::var_uint, $primitive_types::cct_uint, "uint");
+is($primitive_types::var_short, $primitive_types::cct_short, "short");
+is($primitive_types::var_ushort, $primitive_types::cct_ushort, "ushort");
+is($primitive_types::var_long, $primitive_types::cct_long, "long");
+is($primitive_types::var_ulong, $primitive_types::cct_ulong, "ulong");
+is($primitive_types::var_llong, $primitive_types::cct_llong, "llong");
+is($primitive_types::var_ullong, $primitive_types::cct_ullong, "ullong");
+is($primitive_types::var_char, $primitive_types::cct_char, "char");
+is($primitive_types::var_pchar, $primitive_types::cct_pchar, "pchar");
+is($primitive_types::var_pcharc, $primitive_types::cct_pcharc, "pchar");
+is($primitive_types::var_pint, $primitive_types::cct_pint, "pint");
+is($primitive_types::var_sizet, $primitive_types::cct_sizet, "sizet");
+is($primitive_types::var_hello, $primitive_types::cct_hello, "hello");
+is($primitive_types::var_myint, $primitive_types::cct_myint, "myint");
+is($primitive_types::var_namet, $primitive_types::def_namet, "name");
+
+#class PyTest (TestDirector):
+#  def __init__(self):
+#    TestDirector.__init__(self)
+#    pass
+#  def ident(self, x):
+#    return x
+#  
+#  def vval_bool(self, x): return self.ident(x)
+#  def vval_schar(self, x): return self.ident(x)
+#  def vval_uchar(self, x): return self.ident(x)
+#  def vval_int(self, x): return self.ident(x)
+#  def vval_uint(self, x): return self.ident(x)
+#  def vval_short(self, x): return self.ident(x)
+#  def vval_ushort(self, x): return self.ident(x)
+#  def vval_long(self, x): return self.ident(x)
+#  def vval_ulong(self, x): return self.ident(x)
+#  def vval_llong(self, x): return self.ident(x)
+#  def vval_ullong(self, x): return self.ident(x)
+#  def vval_float(self, x): return self.ident(x)
+#  def vval_double(self, x): return self.ident(x)
+#  def vval_char(self, x): return self.ident(x)
+#  def vval_pchar(self, x): return self.ident(x)
+#  def vval_pcharc(self, x): return self.ident(x)
+#  def vval_pint(self, x): return self.ident(x)
+#  def vval_sizet(self, x): return self.ident(x)
+#  def vval_hello(self, x): return self.ident(x)
+#  def vval_myint(self, x): return self.ident(x)
+#
+#  def vref_bool(self, x): return self.ident(x)
+#  def vref_schar(self, x): return self.ident(x)
+#  def vref_uchar(self, x): return self.ident(x)
+#  def vref_int(self, x): return self.ident(x)
+#  def vref_uint(self, x): return self.ident(x)
+#  def vref_short(self, x): return self.ident(x)
+#  def vref_ushort(self, x): return self.ident(x)
+#  def vref_long(self, x): return self.ident(x)
+#  def vref_ulong(self, x): return self.ident(x)
+#  def vref_llong(self, x): return self.ident(x)
+#  def vref_ullong(self, x): return self.ident(x)
+#  def vref_float(self, x): return self.ident(x)
+#  def vref_double(self, x): return self.ident(x)
+#  def vref_char(self, x): return self.ident(x)
+#  def vref_pchar(self, x): return self.ident(x)
+#  def vref_pcharc(self, x): return self.ident(x)
+#  def vref_pint(self, x): return self.ident(x)
+#  def vref_sizet(self, x): return self.ident(x)
+#  def vref_hello(self, x): return self.ident(x)
+#  def vref_myint(self, x): return self.ident(x)
+#
+#  pass
+
+
+my $t = primitive_types::Test->new();
+#p = PyTest()
+#
+#
+# internal call check
+#if t.c_check() != p.c_check():
+#  raise RuntimeError, "bad director"
+#
+#p.var_bool = p.stc_bool
+#p.var_schar = p.stc_schar
+#p.var_uchar = p.stc_uchar
+#p.var_int = p.stc_int
+#p.var_uint = p.stc_uint
+#p.var_short = p.stc_short
+#p.var_ushort = p.stc_ushort
+#p.var_long = p.stc_long
+#p.var_ulong = p.stc_ulong
+#p.var_llong = p.stc_llong
+#p.var_ullong = p.stc_ullong
+#p.var_char = p.stc_char
+#p.var_pchar = sct_pchar
+#p.var_pcharc = sct_pcharc
+#p.var_pint = sct_pint
+#p.var_sizet = sct_sizet
+#p.var_hello = sct_hello
+#p.var_myint = sct_myint
+#p.var_namet = def_namet
+#p.var_parami = sct_parami
+#p.var_paramd = sct_paramd
+#p.var_paramc = sct_paramc
+#
+#p.v_check()
+
+$t->{var_bool} = $primitive_types::Test::stc_bool;
+$t->{var_schar} = $primitive_types::Test::stc_schar;
+$t->{var_uchar} = $primitive_types::Test::stc_uchar;
+$t->{var_int} = $primitive_types::Test::stc_int;
+$t->{var_uint} = $primitive_types::Test::stc_uint;
+$t->{var_short} = $primitive_types::Test::stc_short;
+$t->{var_ushort} = $primitive_types::Test::stc_ushort;
+$t->{var_long} = $primitive_types::Test::stc_long;
+$t->{var_ulong} = $primitive_types::Test::stc_ulong;
+$t->{var_llong} = $primitive_types::Test::stc_llong;
+$t->{var_ullong} = $primitive_types::Test::stc_ullong;
+$t->{var_char} = $primitive_types::Test::stc_char;
+$t->{var_pchar} = $primitive_types::sct_pchar;
+$t->{var_pcharc} = $primitive_types::sct_pcharc;
+$t->{var_pint} = $primitive_types::sct_pint;
+$t->{var_sizet} = $primitive_types::sct_sizet;
+$t->{var_hello} = $primitive_types::sct_hello;
+$t->{var_myint} = $primitive_types::sct_myint;
+$t->{var_namet} = $primitive_types::def_namet;
+$t->{var_parami} = $primitive_types::sct_parami;
+$t->{var_paramd} = $primitive_types::sct_paramd;
+$t->{var_paramc} = $primitive_types::sct_paramc;
+ok($t->v_check(), 'v_check');
+
+is($primitive_types::def_namet, "ho\0la", "namet");
+$t->{var_namet} = $primitive_types::def_namet;
+is($t->{var_namet}, $primitive_types::def_namet, "namet");
+
+$t->{var_namet} = 'holac';
+
+is($t->{var_namet}, 'holac', "namet");
+
+$t->{var_namet} = 'hol';
+
+is($t->{var_namet}, 'hol', "namet");
+
+
+is($t->strlen('hile'), 4, "string typemap");
+
+is($t->strlen("hil\0"), 4, "string typemap");
+
+
+$primitive_types::var_char = "\0";
+is($primitive_types::var_char, "\0", "char '0' case");
+  
+$primitive_types::var_char = 0;
+is($primitive_types::var_char, "\0", "char '0' case");
+
+$primitive_types::var_namet = "\0";
+is($primitive_types::var_namet, '', "char '\\0' case");
+
+$primitive_types::var_namet = '';
+is($primitive_types::var_namet, '', "char empty case");
+
+$primitive_types::var_pchar = undef;
+is($primitive_types::var_pchar, undef, "undef case");
+
+$primitive_types::var_pchar = '';
+is($primitive_types::var_pchar, '', "char empty case");
+
+$primitive_types::var_pcharc = undef;
+is($primitive_types::var_pcharc, undef, "undef case");
+
+$primitive_types::var_pcharc = '';
+is($primitive_types::var_pcharc, '', "char empty case");
+
+
+#
+# creating a raw char*
+#
+my $pc = primitive_types::new_pchar(5);
+primitive_types::pchar_setitem($pc, 0, 'h');
+primitive_types::pchar_setitem($pc, 1, 'o');
+primitive_types::pchar_setitem($pc, 2, 'l');
+primitive_types::pchar_setitem($pc, 3, 'a');
+primitive_types::pchar_setitem($pc, 4, 0);
+
+
+is($t->strlen($pc), 4, "string typemap");
+
+$primitive_types::var_pchar = $pc;
+is($primitive_types::var_pchar, "hola", "pointer case");
+
+$primitive_types::var_namet = $pc;
+is($primitive_types::var_namet, "hola", "pointer case");
+
+primitive_types::delete_pchar($pc);
+
+#
+# Now when things should fail
+#
+
+{
+	my $orig = $t->{var_uchar};
+	eval { $t->{var_uchar} = 10000 };
+	like($@, qr/\bOverflowError\b/, "uchar typemap");
+	is($orig, $t->{var_uchar}, "uchar typemap");
+}
+{
+	my $orig = $t->{var_char};
+	#eval { $t->{var_char} = "23" }; Perl will gladly make a number out of that
+	eval { $t->{var_char} = "twenty-three" };
+	like($@, qr/\bTypeError\b/, "char typemap");
+	is($orig, $t->{var_char}, "char typemap");
+}
+{
+	my $orig = $t->{var_uint};
+	eval { $t->{var_uint} = -1 };
+	like($@, qr/\bOverflowError\b/, "uint typemap");
+	is($orig, $t->{var_uint}, "uint typemap");
+}
+{
+	my $orig = $t->{var_namet};
+	eval { $t->{var_namet} = '123456' };
+	like($@, qr/\bTypeError\b/, "namet typemap");
+	is($orig, $t->{var_namet}, "namet typemap");
+}
+#t2 = p.vtest(t)
+#if t.var_namet !=  t2.var_namet:
+#  raise RuntimeError, "bad SWIGTYPE* typemap"
+
+is($primitive_types::fixsize, "ho\0la\0\0\0", "FIXSIZE typemap");
+
+$primitive_types::fixsize = 'ho';
+is($primitive_types::fixsize, "ho\0\0\0\0\0\0", "FIXSIZE typemap");
+
+
+my $f = primitive_types::Foo->new(3);
+my $f1 = primitive_types::fptr_val($f);
+my $f2 = primitive_types::fptr_ref($f);
+is($f1->{_a}, $f2->{_a}, "const ptr& typemap");
+  
+
+is(primitive_types::char_foo(1,3), 3, "int typemap");
+
+is(primitive_types::char_foo(1,"hello"), "hello", "char* typemap");
+  
+is(primitive_types::SetPos(1,3), 4, "int typemap");
diff --git a/trunk/Examples/test-suite/perl5/profiletest_runme.pl b/trunk/Examples/test-suite/perl5/profiletest_runme.pl
new file mode 100644
index 0000000..fcf5c6a
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/profiletest_runme.pl
@@ -0,0 +1,8 @@
+use profiletest;
+$a = profiletestc::new_A();
+$b = profiletestc::new_B();
+
+for ($i = 0; $i < 100000; $i++) {
+    $a = profiletestc::B_fn($b, $a);
+}
+
diff --git a/trunk/Examples/test-suite/perl5/reference_global_vars_runme.pl b/trunk/Examples/test-suite/perl5/reference_global_vars_runme.pl
new file mode 100755
index 0000000..dfbcf15
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/reference_global_vars_runme.pl
@@ -0,0 +1,80 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 19;
+BEGIN { use_ok('reference_global_vars') }
+require_ok('reference_global_vars');
+
+# adapted from ../python/reference_global_vars_runme.py
+
+my $cvar;
+{
+	# don't try this at home kids... sneaking an import of all symbols
+	# from reference_global_vars to main because my fingers are getting
+	# sore from qualifying all these names. ;)
+	my $cvar = *reference_global_vars::;
+	map { ${*::}{$_} = ${$cvar}{$_} } keys %{$cvar};
+}
+
+is(getconstTC()->{num}, 33);
+
+# primitive reference variables
+$cvar->{var_bool} = createref_bool(0);
+is(value_bool($cvar->{var_bool}), '');
+
+$cvar->{var_bool} = createref_bool(1);
+is(value_bool($cvar->{var_bool}), 1);
+
+$cvar->{var_char} = createref_char('w');
+is(value_char($cvar->{var_char}), 'w');
+
+$cvar->{var_unsigned_char} = createref_unsigned_char(10);
+is(value_unsigned_char($cvar->{var_unsigned_char}), 10);
+
+$cvar->{var_signed_char} = createref_signed_char(10);
+is(value_signed_char($cvar->{var_signed_char}), 10);
+
+$cvar->{var_short} = createref_short(10);
+is(value_short($cvar->{var_short}), 10);
+
+$cvar->{var_unsigned_short} = createref_unsigned_short(10);
+is(value_unsigned_short($cvar->{var_unsigned_short}), 10);
+
+$cvar->{var_int} = createref_int(10);
+is(value_int($cvar->{var_int}), 10);
+
+$cvar->{var_unsigned_int} = createref_unsigned_int(10);
+is(value_unsigned_int($cvar->{var_unsigned_int}), 10);
+
+$cvar->{var_long} = createref_long(10);
+is(value_long($cvar->{var_long}), 10);
+
+$cvar->{var_unsigned_long} = createref_unsigned_long(10);
+is(value_unsigned_long($cvar->{var_unsigned_long}), 10);
+
+SKIP: {
+	my $a = "6FFFFFFFFFFFFFF8";
+	skip "64 bit int support", 1 unless eval { pack 'q', 1 };
+	# using hex() here instead of a literal because non 64bit Perls will
+	# be noisy about big constants.
+	$cvar->{var_long_long} = createref_long_long(hex $a);
+	is(value_long_long($cvar->{var_long_long}), hex $a);
+}
+
+#ull = abs(0xFFFFFFF2FFFFFFF0)
+my $ull = 55834574864;
+$cvar->{var_unsigned_long_long} = createref_unsigned_long_long($ull);
+is(value_unsigned_long_long($cvar->{var_unsigned_long_long}), $ull);
+
+$cvar->{var_float} = createref_float(10.5);
+is(value_float($cvar->{var_float}), 10.5);
+
+$cvar->{var_double} = createref_double(10.5);
+is(value_double($cvar->{var_double}), 10.5);
+
+# class reference variable
+$cvar->{var_TestClass} = createref_TestClass(
+	TestClass->new(20)
+);
+is(value_TestClass($cvar->{var_TestClass})->{num}, 20);
+
diff --git a/trunk/Examples/test-suite/perl5/rename_scope_runme.pl b/trunk/Examples/test-suite/perl5/rename_scope_runme.pl
new file mode 100755
index 0000000..71c0cfc
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/rename_scope_runme.pl
@@ -0,0 +1,15 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 5;
+BEGIN { use_ok('rename_scope') }
+require_ok('rename_scope');
+
+# adapted from ../python/rename_scope_runme.py
+
+my $a = rename_scope::Natural_UP->new();
+is($a->rtest(), 1);
+my $b = rename_scope::Natural_BP->new();
+is($b->rtest(), 1);
+
+isa_ok(rename_scope->can('equals'), 'CODE');
diff --git a/trunk/Examples/test-suite/perl5/ret_by_value_runme.pl b/trunk/Examples/test-suite/perl5/ret_by_value_runme.pl
new file mode 100644
index 0000000..6126627
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/ret_by_value_runme.pl
@@ -0,0 +1,12 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 5;
+BEGIN { use_ok('ret_by_value') }
+require_ok('ret_by_value');
+
+my $tst = ret_by_value::get_test();
+isa_ok($tst, 'ret_by_value::test');
+is($tst->{myInt}, 100);
+is($tst->{myShort}, 200);
+
diff --git a/trunk/Examples/test-suite/perl5/return_const_value_runme.pl b/trunk/Examples/test-suite/perl5/return_const_value_runme.pl
new file mode 100755
index 0000000..4b31c0b
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/return_const_value_runme.pl
@@ -0,0 +1,13 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('return_const_value') }
+require_ok('return_const_value');
+
+# adapted from ../python/return_const_value_runme.py
+
+is(return_const_value::Foo_ptr::getPtr()->getVal(), 17);
+
+is(return_const_value::Foo_ptr::getConstPtr()->getVal(), 17);
+
diff --git a/trunk/Examples/test-suite/perl5/run-perl-test.pl b/trunk/Examples/test-suite/perl5/run-perl-test.pl
new file mode 100755
index 0000000..106bf00
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/run-perl-test.pl
@@ -0,0 +1,15 @@
+#!/usr/bin/perl
+    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
+	if $running_under_some_shell;
+#!/usr/bin/perl -w
+
+use strict;
+
+my $command = shift @ARGV;
+
+my $output = `$^X $command 2>&1`;
+
+die "SWIG Perl test failed: \n\n$output\n"
+  if $?;
+
+exit(0);
diff --git a/trunk/Examples/test-suite/perl5/sizet_runme.pl b/trunk/Examples/test-suite/perl5/sizet_runme.pl
new file mode 100755
index 0000000..5f29773
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/sizet_runme.pl
@@ -0,0 +1,18 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 6;
+BEGIN { use_ok('sizet') }
+require_ok('sizet');
+
+# adapted from ../java/sizet_runme.java
+
+my $s = 2000;
+$s = sizet::test1($s + 1);
+is($s, 2001, 'test1');
+$s = sizet::test1($s + 1);
+is($s, 2002, 'test2');
+$s = sizet::test1($s + 1);
+is($s, 2003, 'test3');
+$s = sizet::test1($s + 1);
+is($s, 2004, 'test4');
diff --git a/trunk/Examples/test-suite/perl5/sneaky1_runme.pl b/trunk/Examples/test-suite/perl5/sneaky1_runme.pl
new file mode 100755
index 0000000..097d446
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/sneaky1_runme.pl
@@ -0,0 +1,13 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More 'no_plan';
+BEGIN { use_ok('sneaky1') }
+require_ok('sneaky1');
+
+# adapted from ../python/sneaky1_runme.py
+
+is(sneaky1::add(3,4), 7);
+is(sneaky1::subtract(3,4), -1);
+is(sneaky1::mul(3,4), 12);
+is(sneaky1::divide(3,4), 0);
diff --git a/trunk/Examples/test-suite/perl5/template_default_arg_runme.pl b/trunk/Examples/test-suite/perl5/template_default_arg_runme.pl
new file mode 100644
index 0000000..791f508
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/template_default_arg_runme.pl
@@ -0,0 +1,111 @@
+use strict;
+use warnings;
+use Test::More tests => 34;
+BEGIN { use_ok('template_default_arg') }
+require_ok('template_default_arg');
+
+{
+  my $helloInt = new template_default_arg::Hello_int();
+  $helloInt->foo(0);
+}
+{
+  my $x = new template_default_arg::X_int();
+  is($x->meth(20.0, 200), 200, "X_int test 1");
+  is($x->meth(20), 20, "X_int test 2");
+  is($x->meth(), 0, "X_int test 3");
+}
+
+{
+  my $y = new template_default_arg::Y_unsigned();
+  is($y->meth(20.0, 200), 200, "Y_unsigned test 1");
+  is($y->meth(20), 20, "Y_unsigned test 2");
+  is($y->meth(), 0, "Y_unsigned test 3");
+}
+
+{
+  my $x = new template_default_arg::X_longlong();
+  $x = new template_default_arg::X_longlong(20.0);
+  $x = new template_default_arg::X_longlong(20.0, 200);
+}
+{
+  my $x = new template_default_arg::X_int();
+  $x = new template_default_arg::X_int(20.0);
+  $x = new template_default_arg::X_int(20.0, 200);
+}
+{
+  my $x = new template_default_arg::X_hello_unsigned();
+  $x = new template_default_arg::X_hello_unsigned(20.0);
+  $x = new template_default_arg::X_hello_unsigned(20.0, new template_default_arg::Hello_int());
+}
+{
+  my $y = new template_default_arg::Y_hello_unsigned();
+  $y->meth(20.0, new template_default_arg::Hello_int());
+  $y->meth(new template_default_arg::Hello_int());
+  $y->meth();
+}
+
+{
+  my $fz = new template_default_arg::Foo_Z_8();
+  my $x = new template_default_arg::X_Foo_Z_8();
+  my $fzc = $x->meth($fz);
+}
+
+# Templated functions
+{
+  # plain function: int ott(Foo<int>)
+  is(template_default_arg::ott(new template_default_arg::Foo_int()), 30, "ott test 1");
+
+  # %template(ott) ott<int, int>;
+  is(template_default_arg::ott(), 10, "ott test 2");
+  is(template_default_arg::ott(1), 10, "ott test 3");
+  is(template_default_arg::ott(1, 1), 10, "ott test 4");
+
+  is(template_default_arg::ott("hi"), 20, "ott test 5");
+  is(template_default_arg::ott("hi", 1), 20, "ott test 6");
+  is(template_default_arg::ott("hi", 1, 1), 20,"ott test 7");
+
+  # %template(ott) ott<const char *>;
+  is(template_default_arg::ottstring(new template_default_arg::Hello_int(), "hi"), 40, "ott test 8");
+
+  is(template_default_arg::ottstring(new template_default_arg::Hello_int()), 40, "ott test 9");
+
+  # %template(ott) ott<int>;
+  is(template_default_arg::ottint(new template_default_arg::Hello_int(), 1), 50, "ott test 10");
+
+  is(template_default_arg::ottint(new template_default_arg::Hello_int()), 50, "ott test 11");
+
+  # %template(ott) ott<double>;
+  is(template_default_arg::ott(new template_default_arg::Hello_int(), 1.0), 60, "ott test 12");
+
+  is(template_default_arg::ott(new template_default_arg::Hello_int()), 60, "ott test 13");
+}
+
+# Above test in namespaces
+{
+  # plain function: int nsott(Foo<int>)
+  is(template_default_arg::nsott(new template_default_arg::Foo_int()), 130, "nsott test 1");
+
+  # %template(nsott) nsott<int, int>;
+  is(template_default_arg::nsott(), 110, "nsott test 2");
+  is(template_default_arg::nsott(1), 110, "nsott test 3");
+  is(template_default_arg::nsott(1, 1), 110,  "nsott test 4");
+
+  is(template_default_arg::nsott("hi"), 120, "nsott test 5");
+  is(template_default_arg::nsott("hi", 1), 120, "nsott test 6");
+  is(template_default_arg::nsott("hi", 1, 1), 120, "nsott test 7");
+
+  # %template(nsott) nsott<const char *>;
+  is(template_default_arg::nsottstring(new template_default_arg::Hello_int(), "hi"), 140, "nsott test 8");
+
+  is(template_default_arg::nsottstring(new template_default_arg::Hello_int()), 140, "nsott test 9");
+
+  # %template(nsott) nsott<int>;
+  is(template_default_arg::nsottint(new template_default_arg::Hello_int(), 1), 150, "nsott test 10");
+
+  is(template_default_arg::nsottint(new template_default_arg::Hello_int()), 150, "nsott test 11");
+
+  # %template(nsott) nsott<double>;
+  is(template_default_arg::nsott(new template_default_arg::Hello_int(), 1.0), 160, "nsott test 12");
+
+  is(template_default_arg::nsott(new template_default_arg::Hello_int()), 160, "nsott test 13");
+}
diff --git a/trunk/Examples/test-suite/perl5/template_ref_type_runme.pl b/trunk/Examples/test-suite/perl5/template_ref_type_runme.pl
new file mode 100644
index 0000000..ba6e2b9
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/template_ref_type_runme.pl
@@ -0,0 +1,6 @@
+use template_ref_type;
+
+my $xr = template_ref_type::XC->new();
+my $y = template_ref_type::Y->new();
+
+$y->find($xr);
diff --git a/trunk/Examples/test-suite/perl5/template_typedef_cplx2_runme.pl b/trunk/Examples/test-suite/perl5/template_typedef_cplx2_runme.pl
new file mode 100755
index 0000000..e0a3003
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/template_typedef_cplx2_runme.pl
@@ -0,0 +1,53 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 16;
+BEGIN { use_ok('template_typedef_cplx2') }
+require_ok('template_typedef_cplx2');
+
+# adapted from ../python/template_typedef_cplx2_runme.py
+
+{	# kids, don't try this at home (glob hijinks)
+	my $cvar = *template_typedef_cplx2::;
+	map { ${*::}{$_} = ${$cvar}{$_} } keys %{$cvar};
+}
+
+#
+# double case
+#
+
+my $d = eval { make_Identity_double() };
+ok(ref($d), 'is an object');
+like(ref($d), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+my $e = eval { make_Multiplies_double_double_double_double($d, $d) };
+ok(ref($e), 'is an object');
+like(ref($e), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+#
+# complex case
+#
+
+my $c = eval { make_Identity_complex() };
+ok(ref($c), 'is an object');
+like(ref($c), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+my $f = eval { make_Multiplies_complex_complex_complex_complex($c, $c) };
+ok(ref($f), 'is an object');
+like(ref($f), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+#
+# Mix case
+#
+
+my $g = eval { make_Multiplies_double_double_complex_complex($d, $c) };
+ok(ref($g), 'is an object');
+like(ref($g), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+my $h = eval { make_Multiplies_complex_complex_double_double($c, $d) };
+ok(ref($h), 'is an object');
+like(ref($h), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+can_ok($g, 'get_value');
+ok(eval { $g->get_value() }, 'get_value');
+
diff --git a/trunk/Examples/test-suite/perl5/template_typedef_cplx3_runme.pl b/trunk/Examples/test-suite/perl5/template_typedef_cplx3_runme.pl
new file mode 100644
index 0000000..fe411f6
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/template_typedef_cplx3_runme.pl
@@ -0,0 +1,41 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 16;
+BEGIN { use_ok('template_typedef_cplx3') }
+require_ok('template_typedef_cplx3');
+
+# adapted from ../python/template_typedef_cplx3_runme.py
+
+{       # kids, don't try this at home (glob hijinks)
+        my $cvar = *template_typedef_cplx3::;
+        map { ${*::}{$_} = ${$cvar}{$_} } keys %{$cvar};
+}
+
+my $s = Sin->new();
+is($s->get_base_value(), 0);
+is($s->get_value(), 1);
+is($s->get_arith_value(), 2);
+is(my_func_r($s), 0);
+isa_ok(make_Multiplies_double_double_double_double($s,$s),
+  "template_typedef_cplx3::ArithUnaryFunction_double_double");
+
+my $z = CSin->new();
+is($z->get_base_value(), 0);
+is($z->get_value(), 1);
+is($z->get_arith_value(), 2);
+is(my_func_c($z), 1);
+isa_ok(make_Multiplies_complex_complex_complex_complex($z,$z),
+  "template_typedef_cplx3::ArithUnaryFunction_complex_complex");
+
+my $d = eval { make_Identity_double() };
+isa_ok($d, "template_typedef_cplx3::ArithUnaryFunction_double_double");
+is(my_func_r($d), 0);
+
+my $c = eval { make_Identity_complex() };
+isa_ok($d, "template_typedef_cplx3::ArithUnaryFunction_double_double");
+is(my_func_c($c), 1);
+  
+
+
+
diff --git a/trunk/Examples/test-suite/perl5/template_typedef_cplx_runme.pl b/trunk/Examples/test-suite/perl5/template_typedef_cplx_runme.pl
new file mode 100644
index 0000000..47cc672
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/template_typedef_cplx_runme.pl
@@ -0,0 +1,49 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 14;
+BEGIN { use_ok('template_typedef_cplx') }
+require_ok('template_typedef_cplx');
+
+# adapted from ../python/template_typedef_cplx_runme.py
+
+{	# kids, don't try this at home (glob hijinks)
+	my $cvar = *template_typedef_cplx::;
+	map { ${*::}{$_} = ${$cvar}{$_} } keys %{$cvar};
+}
+
+#
+# double case
+#
+
+my $d = eval { make_Identity_double() };
+ok(ref($d), 'is an object');
+like(ref($d), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+my $e = eval { make_Multiplies_double_double_double_double($d, $d) };
+ok(ref($e), 'is an object');
+like(ref($e), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+#
+# complex case
+#
+
+my $c = eval { make_Identity_complex() };
+ok(ref($c), 'is an object');
+like(ref($c), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+my $f = eval { make_Multiplies_complex_complex_complex_complex($c, $c) };
+ok(ref($f), 'is an object');
+like(ref($f), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+#
+# Mix case
+#
+
+my $g = eval { make_Multiplies_double_double_complex_complex($d, $c) };
+ok(ref($f), 'is an object');
+like(ref($f), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
+
+my $h = eval { make_Multiplies_complex_complex_double_double($c, $d) };
+ok(ref($h), 'is an object');
+like(ref($h), qr/ArithUnaryFunction/, "is an ArithUnaryFunction");
diff --git a/trunk/Examples/test-suite/perl5/typedef_class_runme.pl b/trunk/Examples/test-suite/perl5/typedef_class_runme.pl
new file mode 100755
index 0000000..a7b88a7
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/typedef_class_runme.pl
@@ -0,0 +1,16 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 6;
+BEGIN { use_ok('typedef_class') }
+require_ok('typedef_class');
+
+# adapted from ../python/typedef_class_runme.py
+
+my $a = typedef_class::RealA->new();
+isa_ok($a, 'typedef_class::RealA');
+$a->{a} = 3;
+is($a->{a}, 3);
+my $b = typedef_class::B->new();
+isa_ok($b, 'typedef_class::B');
+is($b->testA($a), 3);
diff --git a/trunk/Examples/test-suite/perl5/typemap_namespace_runme.pl b/trunk/Examples/test-suite/perl5/typemap_namespace_runme.pl
new file mode 100644
index 0000000..f2fdd6f
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/typemap_namespace_runme.pl
@@ -0,0 +1,9 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('typemap_namespace') }
+require_ok('typemap_namespace');
+
+is(typemap_namespace::test1("hello"), "hello", "test 1");
+is(typemap_namespace::test2("hello"), "hello", "test 1");
diff --git a/trunk/Examples/test-suite/perl5/typename_runme.pl b/trunk/Examples/test-suite/perl5/typename_runme.pl
new file mode 100755
index 0000000..543080d
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/typename_runme.pl
@@ -0,0 +1,17 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 4;
+BEGIN { use_ok('typename') }
+require_ok('typename');
+
+# adapted from ../python/typename_runme.py
+
+my $f = typename::Foo->new();
+my $b = typename::Bar->new();
+my $x = typename::twoFoo($f);
+is($x, 4.3656);
+my $y = typename::twoBar($b);
+is($y, 84);
+# I would like this test better if I could pass in a float to the
+# integer test and see it lose precision.
diff --git a/trunk/Examples/test-suite/perl5/unions_runme.pl b/trunk/Examples/test-suite/perl5/unions_runme.pl
new file mode 100644
index 0000000..7a62295
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/unions_runme.pl
@@ -0,0 +1,42 @@
+use strict;
+use warnings;
+use Test::More tests => 7;
+# This is the union runtime testcase. It ensures that values within a 
+# union embedded within a struct can be set and read correctly.
+
+BEGIN { use_ok('unions') }
+require_ok('unions');
+
+# Create new instances of SmallStruct and BigStruct for later use
+my $small = new unions::SmallStruct();
+$small->{jill} = 200;
+
+my $big = new unions::BigStruct();
+$big->{smallstruct} = $small;
+$big->{jack} = 300;
+
+# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+# Ensure values in EmbeddedUnionTest are set correctly for each.
+my $eut = new unions::EmbeddedUnionTest();
+
+# First check the SmallStruct in EmbeddedUnionTest
+$eut->{number} = 1;
+$eut->{uni}->{small} = $small;
+my $Jill1 = $eut->{uni}->{small}->{jill};
+is($Jill1, 200, "eut.uni.small.jill");
+
+my $Num1 = $eut->{number};
+is($Num1, 1, "test2 eut.number");
+
+# Secondly check the BigStruct in EmbeddedUnionTest
+$eut->{number} = 2;
+$eut->{uni}->{big} = $big;
+my $Jack1 = $eut->{uni}->{big}->{jack};
+is($Jack1, 300, "test3 eut.uni.big.jack");
+
+my $Jill2 = $eut->{uni}->{big}->{smallstruct}->{jill};
+is($Jill2, 200, "test4 eut.uni.big.smallstruct.jill");
+
+my $Num2 = $eut->{number};
+is($Num2,  2, "test5 eut.number");
+
diff --git a/trunk/Examples/test-suite/perl5/using1_runme.pl b/trunk/Examples/test-suite/perl5/using1_runme.pl
new file mode 100755
index 0000000..8551b6f
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/using1_runme.pl
@@ -0,0 +1,10 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 3;
+BEGIN { use_ok('using1') }
+require_ok('using1');
+
+# adapted from ../python/using1_runme.py
+
+is(using1::spam(37), 37);
diff --git a/trunk/Examples/test-suite/perl5/using2_runme.pl b/trunk/Examples/test-suite/perl5/using2_runme.pl
new file mode 100755
index 0000000..3a31bb3
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/using2_runme.pl
@@ -0,0 +1,10 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 3;
+BEGIN { use_ok('using2') }
+require_ok('using2');
+
+# adapted from ../python/using2_runme.py
+
+is(using2::spam(37), 37);
diff --git a/trunk/Examples/test-suite/perl5/varargs_runme.pl b/trunk/Examples/test-suite/perl5/varargs_runme.pl
new file mode 100644
index 0000000..4d8a831
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/varargs_runme.pl
@@ -0,0 +1,18 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 7;
+BEGIN { use_ok('varargs') }
+require_ok('varargs');
+
+is(varargs::test("Hello"), "Hello");
+
+my $f = new varargs::Foo("BuonGiorno", 1);
+is($f->{str}, "BuonGiorno");
+
+$f = new varargs::Foo("Greetings");
+is($f->{str}, "Greetings");
+        
+is($f->test("Hello"), "Hello");
+
+is(varargs::Foo::statictest("Grussen", 1), "Grussen");
diff --git a/trunk/Examples/test-suite/perl5/virtual_poly_runme.pl b/trunk/Examples/test-suite/perl5/virtual_poly_runme.pl
new file mode 100644
index 0000000..a56a64e
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/virtual_poly_runme.pl
@@ -0,0 +1,36 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 8;
+BEGIN { use_ok('virtual_poly') }
+require_ok('virtual_poly');
+
+my $d = virtual_poly::NDouble->new(3.5);
+my $i = virtual_poly::NInt->new(2);
+
+#
+# the copy methods return the right polymorphic types
+# 
+my $dc = $d->copy();
+my $ic = $i->copy();
+
+is($d->get(), $dc->get());
+
+is($i->get(), $ic->get());
+
+virtual_poly::incr($ic);
+
+is($i->get() + 1, $ic->get());
+
+my $dr = $d->ref_this();
+is($d->get(), $dr->get());
+
+
+#
+# 'narrowing' also works
+#
+my $ddc = virtual_poly::NDouble::narrow($d->nnumber());
+is($d->get, $ddc->get());
+
+my $dic = virtual_poly::NInt::narrow($i->nnumber());
+is($i->get(), $dic->get());
diff --git a/trunk/Examples/test-suite/perl5/voidtest_runme.pl b/trunk/Examples/test-suite/perl5/voidtest_runme.pl
new file mode 100644
index 0000000..405f8fd
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/voidtest_runme.pl
@@ -0,0 +1,20 @@
+use strict;
+use warnings;
+use Test::More tests => 7;
+BEGIN { use_ok('voidtest') }
+require_ok('voidtest');
+
+# adapted from ../python/voidtest_runme.py
+voidtest::globalfunc();
+my $f = voidtest::Foo->new();
+is($f->memberfunc(), undef);
+{ local $TODO = "opaque pointers hidden behind layer of indirection";
+my $v1 = voidtest::vfunc1($f);
+my $v2 = voidtest::vfunc2($f);
+is($v1, $v2);
+my $v3 = voidtest::vfunc3($v1);
+is($v3->this, $f->this);
+my $v4 = voidtest::vfunc4($f);
+is($v1, $v4);
+}
+ok(1, "done");
diff --git a/trunk/Examples/test-suite/perl5/wrapmacro_runme.pl b/trunk/Examples/test-suite/perl5/wrapmacro_runme.pl
new file mode 100755
index 0000000..f0345e4
--- /dev/null
+++ b/trunk/Examples/test-suite/perl5/wrapmacro_runme.pl
@@ -0,0 +1,14 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use Test::More tests => 5;
+BEGIN { use_ok('wrapmacro') }
+require_ok('wrapmacro');
+
+# adapted from ../python/wrapmacro_runme.py
+
+my $a = 2;
+my $b = -1;
+is(wrapmacro::max($a,$b), 2);
+is(wrapmacro::max($a/7.0, -$b*256), 256);
+is(wrapmacro::GUINT16_SWAP_LE_BE_CONSTANT(1), 256);
diff --git a/trunk/Examples/test-suite/php4/Makefile.in b/trunk/Examples/test-suite/php4/Makefile.in
new file mode 100644
index 0000000..2e14ef9
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/Makefile.in
@@ -0,0 +1,69 @@
+#######################################################################
+# Makefile for php4 test-suite
+#######################################################################
+
+LANGUAGE     = php4
+SCRIPTSUFFIX = _runme.php4
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+TARGETPREFIX =# Should be php_ for Windows, empty otherwise
+
+makecpptests:
+	@bash -ec 'for test in $(CPP_TEST_CASES) ; do $(MAKE) clean && $(MAKE) $${test}.cpptest; done'
+
+maketests: makecpptests makectests
+
+makectests:
+	@bash -ec 'for test in $(C_TEST_CASES) ; do $($(MAKE)) clean && $(MAKE) $${test}.cpptest; done'
+
+runcpptests:
+	@bash -ec 'for test in $(CPP_TEST_CASES) ; do if [ -f $${test}_runme.php4 ] ; then $(MAKE) clean && $(MAKE) $${test}.cpptest; fi ; done'
+
+runctests:
+	@bash -ec 'for test in $(C_TEST_CASES) ; do if [ -f $${test}_runme.php4 ] ; then $(MAKE) clean && $(MAKE) $${test}.cpptest; fi; done'
+
+runtests: runcpptests runctests
+
+# write out tests without a _runme.php4
+missingcpptests:
+	@bash -ec 'for test in $(CPP_TEST_CASES) ; do test -f $${test}_runme.php4 || echo $${test}; done'
+
+missingctests:
+	@bash -ec 'for test in $(C_TEST_CASES) ; do test -f $${test}_runme.php4 || echo $${test}; done'
+
+missingtests: missingcpptests missingctests
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	+$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	+$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	+$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.php4 appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SCRIPT=$(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL=$(RUNTOOL) php4_run;) \
+	fi;
+
+# Clean: remove the generated .php file
+%.clean:
+	@rm -f $*.php;
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile php4_clean
diff --git a/trunk/Examples/test-suite/php4/abstract_inherit_ok_runme.php4 b/trunk/Examples/test-suite/php4/abstract_inherit_ok_runme.php4
new file mode 100644
index 0000000..1182e4c
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/abstract_inherit_ok_runme.php4
@@ -0,0 +1,12 @@
+<?php
+
+require "tests.php4";
+require "abstract_inherit_ok.php";
+
+check::classes(array(Foo,Spam));
+$spam=new Spam();
+
+check::equal(0,$spam->blah(),"spam object method");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/abstract_inherit_runme.php4 b/trunk/Examples/test-suite/php4/abstract_inherit_runme.php4
new file mode 100644
index 0000000..fbc9717
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/abstract_inherit_runme.php4
@@ -0,0 +1,14 @@
+<?php
+
+require "tests.php4";
+require "abstract_inherit.php";
+
+check::classes(array(Foo,Bar,Spam,NRFilter_i,NRRCFilter_i,NRRCFilterpro_i,NRRCFilterpri_i));
+// This constructor attempt should fail as there isn't one
+//$spam=new Spam();
+
+//check::equal(0,$spam->blah(),"spam object method");
+//check::equal(0,Spam::blah($spam),"spam class method");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/add_link_runme.php4 b/trunk/Examples/test-suite/php4/add_link_runme.php4
new file mode 100644
index 0000000..b9d5334
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/add_link_runme.php4
@@ -0,0 +1,23 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "add_link.php";
+
+// No new functions, except the flat functions
+check::functions(array(new_foo,foo_blah));
+
+check::classes(array(Foo));
+
+$foo=new foo();
+check::is_a($foo,foo);
+
+$foo_blah=$foo->blah();
+check::is_a($foo_blah,foo);
+
+//fails, can't be called as a class method, should allow and make it nil?
+//$class_foo_blah=foo::blah();
+//check::is_a($class_foo_blah,foo);
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/argout_runme.php4 b/trunk/Examples/test-suite/php4/argout_runme.php4
new file mode 100644
index 0000000..1328b09
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/argout_runme.php4
@@ -0,0 +1,37 @@
+<?php
+
+require "tests.php4";
+require "argout.php";
+
+check::functions(array(incp,incr,inctr,new_intp,copy_intp,delete_intp,intp_assign,intp_value,voidhandle,handle));
+
+$ip=copy_intp(42);
+check::equal(42,incp($ip),"42==incp($ip)");
+check::equal(43,intp_value($ip),"43=$ip");
+
+$p=copy_intp(2);
+check::equal(2,incp($p),"2==incp($p)");
+check::equal(3,intp_value($p),"3==$p");
+
+$r=copy_intp(7);
+check::equal(7,incr($r),"7==incr($r)");
+check::equal(8,intp_value($r),"8==$r");
+
+$tr=copy_intp(4);
+check::equal(4,inctr($tr),"4==incr($tr)");
+check::equal(5,intp_value($tr),"5==$tr");
+
+# Check the voidhandle call, first with null
+unset($handle);
+voidhandle(&$handle);
+check::resource($handle,"_p_void",'$handle is not _p_void');
+$handledata=handle($handle);
+check::equal($handledata,"Here it is","\$handledata != \"Here it is\"");
+
+unset($handle);
+// without reference, should fatal error so can't test here
+//voidhandle($handle);
+//check::isnull($handle,'$handle not null');
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/arrayptr_runme.php4 b/trunk/Examples/test-suite/php4/arrayptr_runme.php4
new file mode 100644
index 0000000..c057a67
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/arrayptr_runme.php4
@@ -0,0 +1,15 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "arrayptr.php";
+
+// No new functions
+check::functions(array(foo));
+// No new classes
+check::classes(array());
+// now new vars
+check::globals(array());
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/arrays_global_runme.php4 b/trunk/Examples/test-suite/php4/arrays_global_runme.php4
new file mode 100644
index 0000000..d6a3955
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/arrays_global_runme.php4
@@ -0,0 +1,14 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "arrays_global.php";
+
+check::functions(array(test_a,test_b,new_simplestruct,new_material));
+check::classes(array(arrays_global,SimpleStruct,Material));
+check::globals(array(array_c,array_sc,array_uc,array_s,array_us,array_i,array_ui,array_l,array_ul,array_ll,array_f,array_d,array_struct,array_structpointers,array_ipointers,array_enum,array_enumpointers,array_const_i,beginstring_fix44a,beginstring_fix44b,beginstring_fix44c,beginstring_fix44d,beginstring_fix44e,beginstring_fix44f,chitmat,hitmat_val,hitmat));
+check::set(array_c,"hac");
+check::equal("ha",check::get(array_c,"ha"),"set array_c");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/arrays_global_twodim_runme.php4 b/trunk/Examples/test-suite/php4/arrays_global_twodim_runme.php4
new file mode 100644
index 0000000..352ad25
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/arrays_global_twodim_runme.php4
@@ -0,0 +1,23 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "arrays_global_twodim.php";
+
+check::functions(array(fn_taking_arrays,get_2d_array,new_simplestruct,new_material));
+check::classes(array(arrays_global_twodim,SimpleStruct,Material));
+check::globals(array(array_c,array_sc,array_uc,array_s,array_us,array_i,array_ui,array_l,array_ul,array_ll,array_f,array_d,array_struct,array_structpointers,array_ipointers,array_enum,array_enumpointers,array_const_i,chitmat,hitmat_val,hitmat));
+$a1=array(10,11,12,13);
+$a2=array(14,15,16,17);
+$a=array($a1,$a2);
+
+$_a=check::get(array_const_i);
+
+for($x=0;$x<count($a1);$x++) {
+  for($y=0;$y<2;$y++) {
+    check::equal($a[$y][$x],get_2d_array($_a,$y,$x),"check array $x,$y");
+  }
+}
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/arrays_runme.php4 b/trunk/Examples/test-suite/php4/arrays_runme.php4
new file mode 100644
index 0000000..407c32c
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/arrays_runme.php4
@@ -0,0 +1,19 @@
+<?php
+// Sample test file
+require "tests.php4";
+require "arrays.php";
+
+check::functions(array(fn_taking_arrays,newintpointer,setintfrompointer,getintfrompointer,array_pointer_func));
+check::classes(array(arrays,SimpleStruct,ArrayStruct,CartPoseData_t));
+// No new vars
+check::globals(array());
+
+$ss=new simplestruct();
+check::classname(simplestruct,$ss);
+
+$as=new arraystruct();
+$as->array_c="abc";
+check::equal($as->array_c,"ab",'$as->array_c=="ab"');
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/arrays_scope_runme.php4 b/trunk/Examples/test-suite/php4/arrays_scope_runme.php4
new file mode 100644
index 0000000..75c7ccf
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/arrays_scope_runme.php4
@@ -0,0 +1,17 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "arrays_scope.php";
+
+// No new functions
+check::functions(array(new_bar,bar_blah));
+// No new classes
+check::classes(array(arrays_scope,Bar));
+// now new vars
+check::globals(array());
+
+$bar=new bar();
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/casts_runme.php4 b/trunk/Examples/test-suite/php4/casts_runme.php4
new file mode 100644
index 0000000..c3d19e2
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/casts_runme.php4
@@ -0,0 +1,19 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "casts.php";
+
+// No new functions
+check::functions(array(new_a,a_hello,new_b));
+// No new classes
+check::classes(array(A,B));
+// now new vars
+check::globals(array());
+
+# Make sure $b inherites hello() from class A
+$b=new B();
+$b->hello();
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/class_ignore_runme.php4 b/trunk/Examples/test-suite/php4/class_ignore_runme.php4
new file mode 100644
index 0000000..5da23e5
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/class_ignore_runme.php4
@@ -0,0 +1,17 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "class_ignore.php";
+
+check::functions(array(do_blah,new_bar,bar_blah,new_boo,boo_away,new_far,new_hoo));
+check::classes(array(class_ignore,Bar,Boo,Far,Hoo));
+// No new vars
+check::globals(array());
+
+$bar=new bar();
+do_blah($bar);
+check::classparent($bar,"");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/conversion_namespace_runme.php4 b/trunk/Examples/test-suite/php4/conversion_namespace_runme.php4
new file mode 100644
index 0000000..ae49d20
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/conversion_namespace_runme.php4
@@ -0,0 +1,14 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "conversion_namespace.php";
+
+check::classes(array("Foo","Bar"));
+$bar=new Bar;
+check::classname("bar",$bar);
+$foo=$bar->toFoo();
+check::classname("foo",$foo);
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/conversion_ns_template_runme.php4 b/trunk/Examples/test-suite/php4/conversion_ns_template_runme.php4
new file mode 100644
index 0000000..e799cdd
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/conversion_ns_template_runme.php4
@@ -0,0 +1,10 @@
+<?php
+
+require "tests.php4";
+require "conversion_ns_template.php";
+
+check::classes(array("conversion_ns_template","Foo_One","Bar_One","Hi"));
+// this is too hard, I'm not sure what to test for,
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/conversion_runme.php4 b/trunk/Examples/test-suite/php4/conversion_runme.php4
new file mode 100644
index 0000000..7941a7b
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/conversion_runme.php4
@@ -0,0 +1,14 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "conversion.php";
+
+check::classes(array("Foo","Bar"));
+$bar=new Bar;
+check::classname("bar",$bar);
+$foo=$bar->toFoo();
+check::classname("foo",$foo);
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/cpp_static_runme.php4 b/trunk/Examples/test-suite/php4/cpp_static_runme.php4
new file mode 100644
index 0000000..b7f9875
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/cpp_static_runme.php4
@@ -0,0 +1,15 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "cpp_static.php";
+
+// No new functions
+check::functions(array());
+// No new classes
+check::classes(array(StaticMemberTest,StaticFunctionTest));
+// now new vars
+check::globals(array());
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/enum_scope_template_runme.php4 b/trunk/Examples/test-suite/php4/enum_scope_template_runme.php4
new file mode 100644
index 0000000..40efc57
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/enum_scope_template_runme.php4
@@ -0,0 +1,17 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "enum_scope_template.php";
+
+check::classes(array("enum_scope_template", "TreeInt"));
+check::functions("chops");
+check::equal(0,TreeInt_Oak,"0==TreeInt_Oak");
+check::equal(1,TreeInt_Fir,"0==TreeInt_Fir");
+check::equal(2,TreeInt_Cedar,"0==TreeInt_Cedar");
+check::equal(TreeInt_Oak,chops(TreeInt_Oak),"TreeInt_Oak==chops(TreeInt_Oak)");
+check::equal(TreeInt_Fir,chops(TreeInt_Fir),"TreeInt_Fir==chops(TreeInt_Fir)");
+check::equal(TreeInt_Cedar,chops(TreeInt_Cedar),"TreeInt_Cedar==chops(TreeInt_Cedar)");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/evil_diamond_ns_runme.php4 b/trunk/Examples/test-suite/php4/evil_diamond_ns_runme.php4
new file mode 100644
index 0000000..29e8cd5
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/evil_diamond_ns_runme.php4
@@ -0,0 +1,19 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "evil_diamond_ns.php";
+
+check::classes(array("evil_diamond_ns","foo","bar","baz","spam"));
+check::functions("test");
+check::is_a("bar","foo");
+check::is_a("baz","foo");
+check::is_a("spam","foo");
+check::is_a("spam","bar");
+//No multiple inheritance
+//check::is_a("spam","baz");
+$spam=new spam();
+$_spam=test($spam);
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/evil_diamond_prop_runme.php4 b/trunk/Examples/test-suite/php4/evil_diamond_prop_runme.php4
new file mode 100644
index 0000000..c0b157f
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/evil_diamond_prop_runme.php4
@@ -0,0 +1,38 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "evil_diamond_prop.php";
+
+check::classes(array("evil_diamond_prop","foo","bar","baz","spam"));
+check::functions("test");
+check::is_a("bar","foo");
+check::is_a("baz","foo");
+check::is_a("spam","foo");
+check::is_a("spam","bar");
+//No multiple inheritance introspection yet
+//check::is_a("spam","baz");
+
+$foo=new foo();
+check::is_a($foo,"foo");
+check::equal(1,$foo->_foo,"1==foo->_foo");
+
+$bar=new bar();
+check::is_a($bar,"bar");
+check::equal(1,$bar->_foo,"1==bar->_foo");
+check::equal(2,$bar->_bar,"2==bar->_bar");
+
+$baz=new baz();
+check::is_a($baz,"baz");
+check::equal(1,$baz->_foo,"1==baz->_foo");
+check::equal(3,$baz->_baz,"3==baz->_baz");
+
+$spam=new spam();
+check::is_a($spam,"spam");
+check::equal(1,$spam->_foo,"1==spam->_foo");
+check::equal(2,$spam->_bar,"2==spam->_bar");
+check::equal(3,$spam->_baz,"3==spam->_baz");
+check::equal(4,$spam->_spam,"4==spam->_spam");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/evil_diamond_runme.php4 b/trunk/Examples/test-suite/php4/evil_diamond_runme.php4
new file mode 100644
index 0000000..677813b
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/evil_diamond_runme.php4
@@ -0,0 +1,17 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "evil_diamond.php";
+
+check::classes(array("evil_diamond","foo","bar","baz","spam"));
+check::functions("test");
+check::is_a("bar","foo");
+check::is_a("baz","foo");
+check::is_a("spam","foo");
+check::is_a("spam","bar");
+//No multiple inheritance
+//check::is_a("spam","baz");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/extend_template_ns_runme.php4 b/trunk/Examples/test-suite/php4/extend_template_ns_runme.php4
new file mode 100644
index 0000000..16a6434
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/extend_template_ns_runme.php4
@@ -0,0 +1,13 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "extend_template_ns.php";
+
+check::classes(array("extend_template_ns","Foo_One"));
+$foo=new Foo_One();
+check::equal(2,$foo->test1(2),"test1");
+check::equal(3,$foo->test2(3),"test2");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/extend_template_runme.php4 b/trunk/Examples/test-suite/php4/extend_template_runme.php4
new file mode 100644
index 0000000..c12f330
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/extend_template_runme.php4
@@ -0,0 +1,13 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "extend_template.php";
+
+check::classes(array("Foo_0"));
+$foo=new Foo_0();
+check::equal(2,$foo->test1(2),"test1");
+check::equal(3,$foo->test2(3),"test2");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/grouping_runme.php4 b/trunk/Examples/test-suite/php4/grouping_runme.php4
new file mode 100644
index 0000000..45e321f
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/grouping_runme.php4
@@ -0,0 +1,23 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "grouping.php";
+
+check::functions(array("test1","test2","do_unary","negate"));
+check::equal(5,test1(5),"5==test1(5)");
+check::resource(test2(7),"_p_int","_p_int==test2(7)");
+check::globals(array(test3));
+
+//check::equal(37,test3_get(),'37==test3_get()');
+check::equal(37,check::get("test3"),'37==get(test3)');
+//test3_set(38);
+check::set(test3,38); 
+//check::equal(38,test3_get(),'38==test3_get() after test3_set(37)');
+check::equal(38,check::get(test3),'38==get(test3) after set(test)');
+
+check::equal(-5,negate(5),"-5==negate(5)");
+check::equal(7,do_unary(-7,NEGATE),"7=do_unary(-7,NEGATE)");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/ignore_parameter_runme.php4 b/trunk/Examples/test-suite/php4/ignore_parameter_runme.php4
new file mode 100644
index 0000000..8a2bf89
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/ignore_parameter_runme.php4
@@ -0,0 +1,39 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "ignore_parameter.php";
+
+// No new functions
+check::functions(array(jaguar,lotus,tvr,ferrari));
+// No new classes
+check::classes(array(sportscars,minicooper,morrisminor,fordanglia,austinallegro));
+// now new vars
+check::globals(array());
+
+check::equal(jaguar(2,3.4),"hello",'jaguar(2,3.4)=="hello"');
+check::equal(lotus("eek",3.4),101,'lotus("eek",3.4)==101');
+check::equal(tvr("eek",2),8.8,'tvr("eek",2)==8.8');
+check::equal(ferrari(),101,'ferrari(2)==101');
+
+$sc=new sportscars();
+check::classname("sportscars",$sc);
+check::equal($sc->daimler(2,3.4),"hello",'$sc->daimler(2,3.4)=="hello"');
+check::equal($sc->astonmartin("eek",3.4),101,'$sc->mastonmartin("eek",3.4)==101');
+check::equal($sc->bugatti("eek",2),8.8,'$sc->bugatti("eek",2)==8.8');
+check::equal($sc->lamborghini(),101,'$sc->lamborghini(2)==101');
+
+$mc=new minicooper(2,3.4);
+check::classname("minicooper",$mc);
+
+$mm=new morrisminor("eek",3.4);
+check::classname("morrisminor",$mm);
+
+$fa=new fordanglia("eek",2);
+check::classname("fordanglia",$fa);
+
+$aa=new austinallegro();
+check::classname("austinallegro",$aa);
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/li_carrays_runme.php4 b/trunk/Examples/test-suite/php4/li_carrays_runme.php4
new file mode 100644
index 0000000..b0b93da
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/li_carrays_runme.php4
@@ -0,0 +1,15 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "li_carrays.php";
+
+// No new functions
+check::functions(array(new_intarray,delete_intarray,intarray_getitem,intarray_setitem));
+// No new classes
+check::classes(array(doubleArray));
+// now new vars
+check::globals(array());
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/li_std_string_runme.php4 b/trunk/Examples/test-suite/php4/li_std_string_runme.php4
new file mode 100644
index 0000000..fb3da35
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/li_std_string_runme.php4
@@ -0,0 +1,32 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "li_std_string.php";
+
+// Global variables
+//$s="initial string";
+//check::equal(GlobalString2_get() ,"global string 2", "GlobalString2 test 1");
+
+// Global variables
+$s = "initial string";
+check::equal(GlobalString2_get(), "global string 2", "GlobalString2 test 1");
+GlobalString2_set($s);
+check::equal(GlobalString2_get(), $s, "GlobalString2 test 2");
+check::equal(ConstGlobalString_get(), "const global string", "ConstGlobalString test");
+
+// Member variables
+$myStructure = new Structure();
+check::equal($myStructure->MemberString2, "member string 2", "MemberString2 test 1");
+$myStructure->MemberString2 = $s;
+check::equal($myStructure->MemberString2, $s, "MemberString2 test 2");
+check::equal($myStructure->ConstMemberString, "const member string", "ConstMemberString test");
+
+check::equal(Structure::StaticMemberString2(), "static member string 2", "StaticMemberString2 test 1");
+Structure::StaticMemberString2($s);
+check::equal(Structure::StaticMemberString2(), $s, "StaticMemberString2 test 2");
+// below broken ?
+//check::equal(Structure::ConstStaticMemberString(), "const static member string", "ConstStaticMemberString test");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/namewarn_rename.i b/trunk/Examples/test-suite/php4/namewarn_rename.i
new file mode 100644
index 0000000..98de311
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/namewarn_rename.i
@@ -0,0 +1,20 @@
+%module namewarn_rename
+
+
+%inline %{
+
+  void Empty() {};
+  
+
+  class stdClass 
+  {
+  };
+
+  struct Hello 
+  {
+    void empty() {}    
+  };
+  
+  
+
+%}
diff --git a/trunk/Examples/test-suite/php4/rename_scope_runme.php4 b/trunk/Examples/test-suite/php4/rename_scope_runme.php4
new file mode 100644
index 0000000..ad86321
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/rename_scope_runme.php4
@@ -0,0 +1,17 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "rename_scope.php";
+
+check::classes(array("rename_scope","Interface_UP","Interface_BP","Natural_UP","Natural_BP","Bucket"));
+
+check::classmethods("Interface_UP",array("interface_up"));
+check::classmethods("Interface_BP",array("interface_bp"));
+check::classmethods("Natural_UP",array("interface_up","natural_up","rtest"));
+check::classmethods("Natural_BP",array("interface_bp","natural_bp","rtest"));
+check::classparent("Natural_UP","interface_up");
+check::classparent("Natural_BP","interface_bp");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/skel.php4 b/trunk/Examples/test-suite/php4/skel.php4
new file mode 100644
index 0000000..d6f3375
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/skel.php4
@@ -0,0 +1,15 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "____.php";
+
+// No new functions
+check::functions(array());
+// No new classes
+check::classes(array());
+// now new vars
+check::globals(array());
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/smart_pointer_rename_runme.php4 b/trunk/Examples/test-suite/php4/smart_pointer_rename_runme.php4
new file mode 100644
index 0000000..5f21b6d
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/smart_pointer_rename_runme.php4
@@ -0,0 +1,28 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "smart_pointer_rename.php";
+
+check::classes(array("Foo","Bar"));
+check::classmethods("foo",array("foo","ftest1","ftest2"));
+check::classmethods("bar",array("__deref__","bar","test","ftest1","ftest2"));
+$foo=new foo();
+check::classname("foo",$foo);
+$bar=new bar($foo);
+check::classname("bar",$bar);
+
+# check foo's ftest1, ftest2
+check::equal(1,$foo->ftest1(1),"foo->ftest1");
+check::equal(2,$foo->ftest2(1,2),"foo->ftest2");
+
+# check bar's ftest1, ftest2, ftest
+check::equal(1,$bar->ftest1(1),"bar->ftest1");
+check::equal(2,$bar->ftest2(1,2),"bar->ftest2");
+check::equal(3,$bar->test(),"bar->test");
+
+# check deref returns foo
+check::classname("foo",$bar->__deref__());
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/sym_runme.php4 b/trunk/Examples/test-suite/php4/sym_runme.php4
new file mode 100644
index 0000000..ce89ea4
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/sym_runme.php4
@@ -0,0 +1,23 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "sym.php";
+
+// No new functions
+check::functions(array());
+// No new classes
+check::classes(array(flim,flam));
+// now new vars
+check::globals(array());
+
+$flim=new flim();
+$flam=new flam();
+
+check::equal($flim->hulahoops(),"flim-jam","flim()->hulahoops==flim-jam");
+check::equal($flim->jar(),"flim-jar","flim()->jar==flim-jar");
+check::equal($flam->jam(),"flam-jam","flam()->jam==flam-jam");
+check::equal($flam->jar(),"flam-jar","flam()->jar==flam-jar");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/template_arg_typename_runme.php4 b/trunk/Examples/test-suite/php4/template_arg_typename_runme.php4
new file mode 100644
index 0000000..7062c67
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/template_arg_typename_runme.php4
@@ -0,0 +1,19 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "template_arg_typename.php";
+
+// No new functions
+check::functions(array());
+// No new classes
+check::classes(array(UnaryFunction_bool_bool,BoolUnaryFunction_bool));
+$ufbb=new unaryfunction_bool_bool();
+check::is_a($ufbb,"unaryfunction_bool_bool");
+
+unset($whatisthis);
+$bufb=new boolunaryfunction_bool(&$whatisthis);
+check::is_a($bufb,"boolunaryfunction_bool");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/template_construct_runme.php4 b/trunk/Examples/test-suite/php4/template_construct_runme.php4
new file mode 100644
index 0000000..d0fbc9b
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/template_construct_runme.php4
@@ -0,0 +1,11 @@
+<?php
+
+require "tests.php4";
+require "template_construct.php";
+
+check::classes(array(Foo_int));
+$foo_int=new foo_int(3);
+check::is_a($foo_int,"foo_int","Made a foo_int");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/tests.php4 b/trunk/Examples/test-suite/php4/tests.php4
new file mode 100644
index 0000000..ae43398
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/tests.php4
@@ -0,0 +1,227 @@
+<?php
+
+// do we have true global vars or just GETSET functions?
+// Used to filter out get/set global functions to fake vars...
+define(GETSET,1);
+
+$_original_functions=get_defined_functions();
+$_original_globals=1;
+$_original_classes=get_declared_classes();
+$_original_globals=array_keys($GLOBALS);
+
+class check {
+  function get_extra_classes($ref=FALSE) {
+    static $extra;
+    global $_original_classes;
+    if ($ref===FALSE) $f=$_original_classes;
+    if (! is_array($extra)) {
+      $df=array_flip(get_declared_classes());
+      foreach($_original_classes as $class) unset($df[$class]);
+      $extra=array_keys($df);
+    }
+    return $extra;
+  }
+
+  function get_extra_functions($ref=FALSE,$gs=false) {
+    static $extra;
+    static $extrags; // for get/setters
+    global $_original_functions;
+    if ($ref===FALSE) $f=$_original_functions;
+    if (! is_array($extra) || $gs) {
+      $extra=array();
+      $extrags=array();
+      $df=get_defined_functions();
+      $df=array_flip($df[internal]);
+      foreach($_original_functions[internal] as $func) unset($df[$func]);
+      // Now chop out any get/set accessors
+      foreach(array_keys($df) as $func) if (GETSET && ereg('_[gs]et$',$func)) $extrags[]=$func;
+      else $extra[]=$func;
+//      $extra=array_keys($df);
+    }
+    if ($gs) return $extrags;
+    return $extra;
+  }
+
+  function get_extra_globals($ref=FALSE) {
+    static $extra;
+    global $_original_globals;
+    if (! is_array($extra)) {
+      if (GETSET) {
+        $_extra=array();
+        foreach(check::get_extra_functions(false,1) as $global) {
+          if (ereg('^(.*)_[sg]et$',$global,$match)) $_extra[$match[1]]=1;
+        }
+        $extra=array_keys($_extra);
+      } else {
+        if ($ref===FALSE) $ref=$_original_globals;
+        if (! is_array($extra)) {
+          $df=array_flip(array_keys($GLOBALS));
+          foreach($_original_globals as $func) unset($df[$func]);
+          // MASK xxxx_LOADED__ variables
+          foreach(array_keys($df) as $func) if (ereg('_LOADED__$',$func)) unset($df[$func]);
+          $extra=array_keys($df);
+        }
+      }
+    }
+    return $extra;
+  }
+
+  function classname($string,$object) {
+    if ($string!=($classname=get_class($object))) return check::fail("Object: $object is of class %s not class %s",$classname,$string);
+    return TRUE;
+  }
+
+  function classmethods($classname,$methods) {
+    if (is_object($classname)) $classname=get_class($classname);
+    $classmethods=array_flip(get_class_methods($classname));
+    $missing=array();
+    $extra=array();
+    foreach($methods as $method) {
+      if (! isset($classmethods[$method])) $missing[]=$method;
+      else unset($classmethods[$method]);
+    }
+    $extra=array_keys($classmethods);
+    if ($missing) $message[]="does not have these methods:\n  ".join(",",$missing);
+    if ($message) {
+      return check::fail("Class %s %s\nFull class list:\n  %s\n",$classname,join("\nbut ",$message),join("\n  ",get_class_methods($classname)));
+    }
+    if ($extra) $message[]="Class ".$classname." has these extra methods:\n  ".join(",",$extra);
+    if ($message) return check::warn(join("\n  ",$message));
+    return TRUE;
+  }
+
+  function set($var,$value) {
+    $func=$var."_set";
+    if (GETSET) $func($value);
+    else $_GLOBALS[$var]=$value;
+  }
+
+  function &get($var) {
+    $func=$var."_get";
+    if (GETSET) return $func();
+    else return $_GLOBALS[$var];
+  }
+
+  function is_a($a,$b) {
+    if (is_object($a)) $a=strtolower(get_class($a));
+    if (is_object($b)) $a=strtolower(get_class($b));
+    $parents=array();
+    $c=$a;
+    while($c!=$b && $c) {
+      $parents[]=$c;
+      $c=strtolower(get_parent_class($c));
+    }
+    if ($c!=$b) return check::fail("Class $a does not inherit from class $b\nHierachy:\n  %s\n",join("\n  ",$parents));
+    return TRUE;
+  }
+
+  function classparent($a,$b) {
+    if (is_object($a)) $a=get_class($a);
+    if (is_object($b)) $a=get_class($b);
+    $parent=get_parent_class($a);
+
+    if ($parent!=$b) return check::fail("Class $a parent not actually $b but $parent");
+    return TRUE;
+  }
+
+  function classes($classes) {
+    if (! is_array($classes)) $classes=array($classes);
+    $message=array();
+    $missing=array();
+    $extra=array_flip(check::get_extra_classes());
+    foreach($classes as $class) {
+      if (! class_exists($class)) $missing[]=$class;
+      else unset($extra[$class]);
+    }
+    if ($missing) $message[]=sprintf("Classes missing: %s",join(",",$missing));
+    if ($message) return check::fail(join("\n  ",$message));
+    if ($extra) $message[]=sprintf("These extra classes are defined: %s",join(",",array_keys($extra)));
+    if ($message) return check::warn(join("\n  ",$message));
+    return TRUE;    
+  }
+
+  function functions($functions) {
+    if (! is_array($functions)) $functions=array($functions);
+    $message=array();
+    $missing=array();
+    $extra=array_flip(check::get_extra_functions());
+
+    foreach ($functions as $func) {
+      if (! function_exists($func)) $missing[]=$func;
+      else unset($extra[$func]);
+    }
+    if ($missing) $message[]=sprintf("Functions missing: %s",join(",",$missing));
+    if ($message) return check::fail(join("\n  ",$message));
+    if ($extra) $message[]=sprintf("These extra functions are defined: %s",join(",",array_keys($extra)));
+    if ($message) return check::warn(join("\n  ",$message));
+    return TRUE;    
+  }
+
+  function globals($globals) {
+    if (! is_array($globals)) $globals=array($globals);
+    $message=array();
+    $missing=array();
+    $extra=array_flip(check::get_extra_globals());
+    foreach ($globals as $glob) {
+      if (GETSET) {
+        if (! isset($extra[$glob])) $missing[]=$glob;
+        else unset($extra[$glob]);
+      } else {
+        if (! isset($GLOBALS[$glob])) $missing[]=$glob;
+        else unset($extra[$glob]);
+      }
+    }
+    if ($missing) $message[]=sprintf("Globals missing: %s",join(",",$missing));
+    if ($message) return check::fail(join("\n  ",$message));
+    if ($extra) $message[]=sprintf("These extra globals are defined: %s",join(",",array_keys($extra)));
+    if ($message) return check::warn(join("\n  ",$message));
+    return TRUE;    
+
+  }
+
+  function functionref($a,$type,$message) {
+    if (! eregi("^_[a-f0-9]+$type$",$a)) return check::fail($message);
+    return TRUE;
+  }
+
+  function equal($a,$b,$message) {
+    if (! ($a===$b)) return check::fail($message);
+    return TRUE;
+  }
+
+  function resource($a,$b,$message) {
+    $resource=trim(check::var_dump($a));
+    if (! eregi("^resource\([0-9]+\) of type \($b\)",$resource)) return check::fail($message);
+    return TRUE;
+  }
+
+  function isnull($a,$message) {
+    $value=trim(check::var_dump($a));
+    return check::equal($value,"NULL",$message);
+  }
+
+  function var_dump($arg) {
+    ob_start();
+    var_dump($arg);
+    $result=ob_get_contents();
+    ob_end_clean();
+    return $result;
+  }
+
+  function fail($pattern) {
+    $args=func_get_args();
+    print("Failed on: ".call_user_func_array("sprintf",$args)."\n");
+    exit(1);
+  }
+
+  function warn($pattern) {
+    $args=func_get_args();
+    print("Warning on: ".call_user_func_array("sprintf",$args)."\n");
+    return FALSE;
+  }
+
+  function done() {
+#    print $_SERVER[argv][0]." ok\n";
+  }
+}
+?>
diff --git a/trunk/Examples/test-suite/php4/typedef_reference_runme.php4 b/trunk/Examples/test-suite/php4/typedef_reference_runme.php4
new file mode 100644
index 0000000..2c64efc
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/typedef_reference_runme.php4
@@ -0,0 +1,13 @@
+<?php
+
+require "tests.php4";
+require "typedef_reference.php";
+
+check::functions(array(somefunc,otherfunc,new_intp,copy_intp,delete_intp,intp_assign,intp_value));
+$int2=copy_intp(2);
+check::equal(2,somefunc($int2)," test passing intp to somefunc");
+$int3=copy_intp(3);
+check::equal(3,otherfunc($int3)," test passing intp to otherfunc");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/typemap_ns_using_runme.php4 b/trunk/Examples/test-suite/php4/typemap_ns_using_runme.php4
new file mode 100644
index 0000000..44403d1
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/typemap_ns_using_runme.php4
@@ -0,0 +1,9 @@
+<?php
+
+require "tests.php4";
+require "typemap_ns_using.php";
+if (! class_exists("_fooimpl")) die("_fooimpl class not found\n");
+if (! 3==spam(3)) die("spam function not working right\n");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/using1_runme.php4 b/trunk/Examples/test-suite/php4/using1_runme.php4
new file mode 100644
index 0000000..ed7e32b
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/using1_runme.php4
@@ -0,0 +1,9 @@
+<?php
+
+require "tests.php4";
+require "using1.php";
+if (! class_exists("_fooimpl")) die("_fooimpl class not found\n");
+if (! 3==spam(3)) die("spam function not working right\n");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/using2_runme.php4 b/trunk/Examples/test-suite/php4/using2_runme.php4
new file mode 100644
index 0000000..e57f0ce
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/using2_runme.php4
@@ -0,0 +1,9 @@
+<?php
+
+require "tests.php4";
+require "using2.php";
+if (! class_exists("_fooimpl")) die("_fooimpl class not found\n");
+if (! 3==spam(3)) die("spam function not working right\n");
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/php4/valuewrapper_base_runme.php4 b/trunk/Examples/test-suite/php4/valuewrapper_base_runme.php4
new file mode 100644
index 0000000..355bb41
--- /dev/null
+++ b/trunk/Examples/test-suite/php4/valuewrapper_base_runme.php4
@@ -0,0 +1,14 @@
+<?php
+// Sample test file
+
+require "tests.php4";
+require "valuewrapper_base.php";
+
+check::classes(array("valuewrapper_base","Base","Interface_BP"));
+check::functions("make_interface_bp");
+
+$ibp=make_interface_bp();
+check::classname("interface_bp",$ibp);
+
+check::done();
+?>
diff --git a/trunk/Examples/test-suite/pike/Makefile.in b/trunk/Examples/test-suite/pike/Makefile.in
new file mode 100644
index 0000000..a753019
--- /dev/null
+++ b/trunk/Examples/test-suite/pike/Makefile.in
@@ -0,0 +1,46 @@
+#######################################################################
+# Makefile for Pike test-suite
+#######################################################################
+
+LANGUAGE     = pike
+PIKE         = pike
+SCRIPTSUFFIX = _runme.pike
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+# none!
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.pike appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PIKE) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: remove the generated .pike file
+%.clean:
+	@rm -f $*.pike;
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile pike_clean
+
diff --git a/trunk/Examples/test-suite/pointer_in_out.i b/trunk/Examples/test-suite/pointer_in_out.i
new file mode 100644
index 0000000..f4b1ed4
--- /dev/null
+++ b/trunk/Examples/test-suite/pointer_in_out.i
@@ -0,0 +1,35 @@
+/* This file tests the pointer-in-out typemap library,
+   currently only available for Guile. */
+
+%module pointer_in_out
+
+%include "pointer-in-out.i"
+
+TYPEMAP_POINTER_INPUT_OUTPUT(int *, int-pointer);
+
+int consume_int_pointer(int **INPUT);
+void produce_int_pointer(int **OUTPUT, int value1, int value2);
+void frobnicate_int_pointer(int **INOUT);
+
+%{
+
+int consume_int_pointer(int **INPUT)
+{
+  return **INPUT;
+}
+
+void produce_int_pointer(int **OUTPUT, int value1, int value2)
+{
+  int *foo = malloc(2 * sizeof(int));
+  foo[0] = value1;
+  foo[1] = value2;
+  *OUTPUT = foo;
+}
+
+void frobnicate_int_pointer(int **INOUT)
+{
+  /* advance the pointer */
+  (*INOUT)++;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/pointer_reference.i b/trunk/Examples/test-suite/pointer_reference.i
new file mode 100644
index 0000000..b7c6054
--- /dev/null
+++ b/trunk/Examples/test-suite/pointer_reference.i
@@ -0,0 +1,44 @@
+/* This interface file tests whether SWIG handles pointer-reference
+   (*&) arguments.
+
+   SWIG 1.3a5 signals a syntax error.
+*/
+
+%module pointer_reference
+
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);                   /* memory leak when setting a ptr/ref variable */
+
+#ifdef SWIGGUILE
+/* A silly testing typemap for feeding a doubly indirect integer */
+%typemap(in) int *&XYZZY (int temp1, int *temp2) {
+   temp1 = gh_scm2int($input); temp2 = &temp1; $1 = &temp2;
+};
+#endif
+
+%inline %{
+void foo(int *&XYZZY) {}
+%}
+
+
+// Test pointer reference typemaps shipped with SWIG (add in SWIG 1.3.28 for many languages)
+%inline %{
+struct Struct {
+  int value;
+  Struct(int v) : value(v) {}
+  static Struct instance;
+  static Struct *pInstance;
+};
+
+void set(Struct *& s) {
+  Struct::instance = *s;
+}
+Struct *& get() {
+  return Struct::pInstance;
+}
+%}
+
+%{
+Struct Struct::instance = Struct(10);
+Struct *Struct::pInstance = &Struct::instance;
+%}
+
diff --git a/trunk/Examples/test-suite/preproc.i b/trunk/Examples/test-suite/preproc.i
new file mode 100644
index 0000000..9491fc1
--- /dev/null
+++ b/trunk/Examples/test-suite/preproc.i
@@ -0,0 +1,339 @@
+%module preproc
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) one; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) two; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) three; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) __GMP_HAVE_CONST; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) __GMP_HAVE_PROTOTYPES; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) __GMP_HAVE_TOKEN_PASTE; /* Ruby, wrong constant name */
+
+/* check __cplusplus case */
+%header
+%{
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+  /* C code */
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+%}
+
+
+/* This interface file tests whether SWIG's extended C
+   preprocessor is working right. 
+
+   In this example, SWIG 1.3.6 chokes on "//" in a #define with a
+   syntax error.
+*/
+
+#define SLASHSLASH "//"
+
+/* This SWIG -*- c -*- interface is to test for some strange
+   preprocessor bug.
+
+   I get syntax errors unless I remove the apostrophe in the comment
+   or the sharp-sign substitution.  (The apostrophe seems to disable
+   sharp-sign substitution.)
+*/
+
+
+%define TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(SCM_TYPE)
+
+     /* Don't check for NULL pointers (override checks). */
+
+     %typemap(argout, doc="($arg <vector of <" #SCM_TYPE ">>)") 
+          int *VECTORLENOUTPUT
+     {
+     }
+
+%enddef
+
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(boolean)
+
+// preproc_3
+
+#define Sum( A, B, \
+             C)    \
+        A + B + C 
+
+
+// preproc_4
+%{
+  int hello0()
+  {
+    return 0;
+  }
+
+  int hello1()
+  {
+    return 1;
+  }
+
+  int hello2()
+  {
+    return 2;
+  }  
+  int f(int min) { return min; }
+%}
+
+#define ARITH_RTYPE(A1, A2) A2
+
+#define HELLO_TYPE(A, B) ARITH_RTYPE(A, ARITH_RTYPE(A,B))
+
+//
+// These two work fine
+//
+int hello0();
+ARITH_RTYPE(double,int) hello1();
+
+
+//
+// This doesn't work with 1.3.17+ ( but it was ok in 1.3.16 )
+// it gets expanded as (using -E)
+// 
+//   ARITH_RTYPE(double,int) hello2();
+//
+HELLO_TYPE(double,int) hello2();
+
+#define min(x,y) ((x) < (y)) ? (x) : (y) 
+int f(int min);
+
+// preproc_5
+
+%warnfilter(SWIGWARN_PARSE_REDEFINED) A5;	// Ruby, wrong constant name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) a5;	// Ruby, wrong constant name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) b5;	// Ruby, wrong constant name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) c5;	// Ruby, wrong constant name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) d5;	// Ruby, wrong constant name
+
+// Various preprocessor bits of nastiness.
+
+
+/* Test argument name substitution */
+#define foo(x,xx) #x #xx
+#define bar(x,xx) x + xx
+
+%constant char *a5 = foo(hello,world);
+%constant int   b5 = bar(3,4);
+
+// Wrap your brain around this one ;-)
+
+%{
+#define cat(x,y) x ## y
+%}
+
+#define cat(x,y) x ## y
+
+/* This should expand to cat(1,2);  
+   See K&R, p. 231 */
+
+%constant int c5 = cat(cat(1,2),;)
+
+#define xcat(x,y) cat(x,y)
+
+/* This expands to 123.  See K&R, p. 231 */
+%constant int d5 = xcat(xcat(1,2),3);
+
+
+#define C1\
+"hello"
+
+#define C2
+#define C3 C2
+
+#define ALONG_\
+NAME 42
+
+#define C4"Hello"
+
+// preproc_6
+
+%warnfilter(SWIGWARN_PARSE_REDEFINED) A6; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) a6; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) b6; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) c6; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) d6; /* Ruby, wrong constant name */
+
+#define add(a, b) (a + b)
+#define times(a, b) (a * b)
+#define op(x) x(1, 5)
+ 
+/* expand to (1 + 5) */
+%constant int a6 = op(add);
+/* expand to (1 * 5) */
+%constant int b6 = op(times);
+/* expand to ((1 + 5) * 5) */
+%constant int c6 = times(add(1, 5), 5);
+/* expand to ((1 + 5) * 5) */
+%constant int d6 = times(op(add), 5);                 
+
+/* This interface file tests whether SWIG's extended C
+   preprocessor is working right. 
+
+   In this example, SWIG 1.3a5 reports missing macro arguments, which
+   is bogus.
+*/
+
+%define MACRO1(C_TYPE, GETLENGTH)
+     /* nothing */
+%enddef
+
+%define MACRO2(XYZZY)
+  MACRO1(XYZZY, 1)
+%enddef
+
+MACRO2(int)
+
+// cpp_macro_noarg.  Tests to make sure macros with no arguments work right.
+#define MACROWITHARG(x) something(x) 
+
+typedef int MACROWITHARG; 
+
+/* 
+This testcase tests for embedded defines and embedded %constants
+*/
+
+%inline %{
+
+typedef struct EmbeddedDefines {
+  int dummy;
+#define  EMBEDDED_DEFINE 44
+#ifdef SWIG
+%constant EMBEDDED_SWIG_CONSTANT = 55;
+#endif
+} EmbeddedDefines;
+
+%}
+
+/* 
+This testcase tests operators for defines
+*/
+
+#define A1   1 + 2
+#define A2   3 - 4
+#define A3   5 * 6
+#define A4   7 / 8
+#define A5   9 >> 10
+#define A6   11 << 12
+#define A7   13 & 14
+#define A8   15 | 16
+#define A9   17 ^ 18
+#define A10  19 && 20
+#define A11  21 || 21
+#define A12  ~22
+#define A13  !23
+
+
+
+#ifdef __cplusplus
+		   
+#define %mangle_macro(...) #@__VA_ARGS__
+#define %mangle_macro_str(...) ##@__VA_ARGS__
+
+%define my_func(...)
+inline const char* mangle_macro ## #@__VA_ARGS__ () {
+  return %mangle_macro_str(__VA_ARGS__);
+}
+%enddef
+
+%inline {
+  my_func(class Int) ;
+  my_func(std::pair<double, std::complex< double > >*) ;
+}
+
+#endif
+
+
+#if defined (__cplusplus) \
+|| defined (_AIX) \
+|| defined (__DECC) \
+|| (defined (__mips) && defined (_SYSTYPE_SVR4)) \
+|| defined (_MSC_VER) \
+|| defined (_WIN32)
+#define __GMP_HAVE_CONST 1
+#define __GMP_HAVE_PROTOTYPES 1
+#define __GMP_HAVE_TOKEN_PASTE 1
+#else
+#define __GMP_HAVE_CONST 0
+#define __GMP_HAVE_PROTOTYPES 0
+#define __GMP_HAVE_TOKEN_PASTE 0
+#endif
+
+
+/* empty TWO() macro is broken */
+#define ONE 1
+#define TWO() 2
+#define THREE(FOO) 3
+
+#define one ONE
+#define two TWO()
+#define three THREE(42)
+
+
+#if defined(one)
+/* hello */
+#else
+/* chiao */
+#endif;
+
+#ifdef SWIGCHICKEN
+/* define is a scheme keyword (and thus an invalid variable name), so SWIG warns about it */
+%warnfilter(SWIGWARN_PARSE_KEYWORD) define; 
+#endif
+
+#ifdef SWIGRUBY
+%rename(ddefined) defined;
+#endif
+#ifdef SWIGPHP
+%rename(endif_) endif;
+#endif
+%inline %{
+const int endif = 1;
+const int define = 1;
+const int defined = 1; 
+int test(int defined)
+{
+  return defined;
+}
+ 
+%}
+
+#pragma SWIG nowarn=SWIGWARN_PP_CPP_WARNING
+#warning "Some warning"
+
+/* check that #error can be turned into a warning, but suppress the warning message for the test-suite! */
+#pragma SWIG nowarn=SWIGWARN_PP_CPP_ERROR
+#pragma SWIG cpperraswarn=1
+#error "Some error"
+
+
+#define MASK(shift, size) (((1 << (size)) - 1) <<(shift))
+#define SOME_MASK_DEF (80*MASK(8, 10))
+
+
+%{
+#define TEUCHOS_TYPE_NAME_TRAITS_BUILTIN_TYPE_SPECIALIZATION(TYPE) \
+struct TypeNameTraits { \
+  int val; \
+} \
+
+%}
+
+
+#define TEUCHOS_TYPE_NAME_TRAITS_BUILTIN_TYPE_SPECIALIZATION(TYPE) \
+struct TypeNameTraits { \
+  int val; \
+} \
+
+%inline %{
+TEUCHOS_TYPE_NAME_TRAITS_BUILTIN_TYPE_SPECIALIZATION(int);
+%}
+
+%inline %{
+int method(struct TypeNameTraits tnt) {
+  return tnt.val;
+}
+%}
diff --git a/trunk/Examples/test-suite/primitive_ref.i b/trunk/Examples/test-suite/primitive_ref.i
new file mode 100644
index 0000000..1e228f2
--- /dev/null
+++ b/trunk/Examples/test-suite/primitive_ref.i
@@ -0,0 +1,47 @@
+// Tests passing of references to primitive datatypes
+%module primitive_ref
+
+%define ref(type,name)
+%inline %{
+const type &ref_##name(const type &x) {
+   static type y = x;
+   return y;
+}
+%}
+%enddef
+
+ref(int,int);
+ref(unsigned int, uint);
+ref(short, short);
+ref(unsigned short, ushort);
+ref(long,long);
+ref(unsigned long, ulong);
+ref(signed char, schar);
+ref(unsigned char, uchar);
+ref(char, char);
+ref(float, float);
+ref(double, double);
+ref(bool, bool);
+ref(long long, longlong);
+ref(unsigned long long, ulonglong);
+
+
+%inline %{
+
+int ref_over(int a)
+{
+  return a;
+}
+
+ struct A 
+ {
+   int v;
+   A(int V) :v(V) {}
+ };
+ 
+int ref_over(const A& a)
+{
+  return a.v;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/primitive_types.i b/trunk/Examples/test-suite/primitive_types.i
new file mode 100644
index 0000000..e00108b
--- /dev/null
+++ b/trunk/Examples/test-suite/primitive_types.i
@@ -0,0 +1,617 @@
+// Massive primitive datatype test.
+%module(directors="1") primitive_types
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+// Ruby constant names
+#pragma SWIG nowarn=SWIGWARN_RUBY_WRONG_NAME
+
+// Using thread unsafe wrapping
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+ /*
+
+ if your language has problems with MyInt* and/or Hello*,
+ you need to change the constant reference typemaps from something
+ like:
+
+ %typemap(in) const char & (char temp), 
+             const signed char & (signed char temp), 
+             const unsigned char & (unsigned char temp), 
+             const short & (short temp), 
+             const unsigned short & (unsigned short temp), 
+             const int & (int temp), 
+             const unsigned int & (unsigned int temp), 
+             const long & (long temp), 
+             const unsigned long & (unsigned long temp), 
+             const long long & ($*1_ltype temp), 
+             const float & (float temp), 
+             const double & (double temp)
+  %{ temp = ($*1_ltype)$input;  $1 = &temp; %}
+
+  to the following:
+
+  %typemap(in) const char & ($basetype temp), 
+             const signed char & ($basetype temp), 
+             const unsigned char & ($basetype temp), 
+             const short & ($basetype temp), 
+             const unsigned short & ($basetype temp), 
+             const int & ($basetype temp), 
+             const unsigned int & ($basetype temp), 
+             const long & ($basetype temp), 
+             const unsigned long & ($basetype temp), 
+             const long long & ($basetype temp), 
+             const float & ($basetype temp), 
+             const double & ($basetype temp)
+  %{ temp = ($basetype)$input;  $1 = &temp; %}
+
+  the other tipical change is to add the enum SWIGTYPE to the
+  integer throws typemaps:
+
+  %typemap(throws) int, 
+                  long, 
+                  short, 
+                  unsigned int, 
+                  unsigned long, 
+                  unsigned short,
+                  enum SWIGTYPE {
+    Tcl_SetObjResult(interp, Tcl_NewIntObj((long) $1));
+    SWIG_fail;
+  }
+
+  or just add the %apply directive after all the typemaps declaration
+
+  %apply int { enum SWIGTYPE };
+
+
+  Also note that this test should not only compile, if you run the
+  program
+
+     grep 'resultobj = SWIG_NewPointerObj' primitive_types_wrap.cxx 
+ 
+  you should get only two calls:
+
+    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Test, 1);
+    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_TestDirector, 1);
+
+  if you get a lot more, some typemap could be not defined.
+
+  The same with
+
+     grep SWIG_ConvertPtr primitive_types_wrap.cxx| egrep -v 'Test'
+
+  you should only get
+
+    #define SWIG_ConvertPtr(obj, pp, type, flags)
+
+ */
+
+//
+// Try your language module with and without 
+// these nowarn flags.
+//
+%warnfilter(SWIGWARN_TYPEMAP_CHARLEAK);
+
+%{
+#include <stddef.h>
+#include <iostream>
+#include <sstream>
+%}
+
+%feature("director") TestDirector;
+
+%{
+  // Integer class, only visible in C++
+  struct MyInt
+  {
+    char name[5];
+    int val;
+
+    MyInt(int v = 0): val(v) {
+    }
+    
+    operator int() const { return val; }
+  };
+
+  // Template primitive type, only visible in C++
+  template <class T>
+  struct Param
+  {
+    char name[5];
+    T val;
+
+    Param(T v = 0): val(v) {
+      name[0] = 0;
+      name[1] = 0;
+      name[2] = 0;
+      name[3] = 0;
+      name[4] = 0;
+    }
+    
+    operator T() const { return val; }
+  };
+
+  typedef char namet[5];
+  extern namet gbl_namet;
+  namet gbl_namet;
+
+%}
+
+
+//
+// adding applies for incomplete swig type MyInt
+//
+%apply int { MyInt };
+%apply const int& {  const MyInt& };
+%apply int { Param<int> };
+%apply char { Param<char> };
+%apply float { Param<float> };
+%apply double { Param<double> };
+%apply const int&  { const Param<int>& };
+%apply const char&  { const Param<char>& };
+%apply const float&  { const Param<float>& };
+%apply const double&  { const Param<double>& };
+
+
+
+//
+// These applies shouldn't be needed ....!!
+//
+//%apply const int& { const Hello&  };
+
+%apply void* { pint };
+%apply void* const& { const pint& };
+  
+
+//
+// Some simple types
+%apply char FIXSIZE[ANY] {char fixsize[8]};
+
+  
+		    
+%inline %{
+  enum Hello {
+    Hi, Hola
+  };
+
+  typedef char namet[5];
+  typedef char* pchar;
+  typedef const char* pcharc;
+  typedef char* pint;
+
+  char* const def_pchar = (char *const)"hello";
+  const char* const def_pcharc = "hija";
+
+  const namet def_namet = {'h','o',0, 'l','a'};
+
+  extern namet gbl_namet;
+
+  char fixsize[8] =  {'h','o',0, 'l','a', 0, 0, 0};
+%}
+
+
+/* all the primitive types */
+#define def_bool 1
+#define def_schar 1
+#define def_uchar 1
+#define def_int 1
+#define def_uint 1
+#define def_short 1
+#define def_ushort 1
+#define def_long 1
+#define def_ulong 1
+#define def_llong 1
+#define def_ullong 1
+#define def_float 1
+#define def_double 1
+#define def_char 'H'
+#define def_pint  0
+#define def_sizet 1
+#define def_hello Hola
+#define def_myint 1
+#define def_parami 1
+#define def_paramd 1
+#define def_paramc 'c'
+
+/* types that can be declared as static const class members */
+%define %test_prim_types_stc(macro, pfx)
+macro(bool,               pfx, bool)
+macro(signed char,        pfx, schar)
+macro(unsigned char,      pfx, uchar)
+macro(int,                pfx, int)
+macro(unsigned int,       pfx, uint)
+macro(short,              pfx, short)
+macro(unsigned short,     pfx, ushort)
+macro(long,               pfx, long)
+macro(unsigned long,      pfx, ulong)
+macro(long long,          pfx, llong)
+macro(unsigned long long, pfx, ullong)
+macro(char,               pfx, char)
+%enddef
+
+
+/* types that can be used to test overloading */
+%define %test_prim_types_ovr(macro, pfx)
+%test_prim_types_stc(macro, pfx)
+macro(pchar,              pfx, pchar)
+%enddef
+
+/* all the types */
+%define %test_prim_types(macro, pfx)
+%test_prim_types_ovr(macro, pfx)
+macro(pcharc,             pfx, pcharc)
+macro(pint,               pfx, pint)
+/* these ones should behave like primitive types too */
+macro(Hello,              pfx, hello)
+macro(MyInt,              pfx, myint)
+macro(Param<int>,         pfx, parami)
+macro(Param<double>,      pfx, paramd)
+macro(Param<char>,        pfx, paramc)
+macro(size_t,             pfx, sizet)
+%enddef
+
+
+/* function passing by value */
+%define val_decl(type, pfx, name)
+  type pfx##_##name(type x) throw (type) { return x; }
+%enddef
+/* function passing by ref */
+%define ref_decl(type, pfx, name)
+  const type& pfx##_##name(const type& x) throw (type) { return x; }
+%enddef
+
+/* C++ constant declaration */
+%define cct_decl(type, pfx, name)
+  const type pfx##_##name = def##_##name;
+%enddef
+
+/* C++ static constant declaration */
+%define stc_decl(type, pfx, name)
+  static const type pfx##_##name = def##_##name;
+%enddef
+
+/* Swig constant declaration */
+%define sct_decl(type, pfx, name)
+  %constant type pfx##_##name = def##_##name;
+%enddef
+
+/* variable delaration */
+%define var_decl(type, pfx, name)
+  type pfx##_##name;
+%enddef
+
+/* virtual function passing by value */
+%define vval_decl(type, pfx, name)
+  virtual val_decl(type, pfx, name)
+%enddef
+/* virtual function passing by ref */
+%define vref_decl(type, pfx, name)
+  virtual ref_decl(type, pfx, name)
+%enddef
+
+
+%test_prim_types(sct_decl, sct)
+
+%inline {
+  %test_prim_types(val_decl, val)
+  %test_prim_types(ref_decl, ref)
+  %test_prim_types(cct_decl, cct)
+  %test_prim_types(var_decl, var)
+
+  var_decl(namet, var, namet)
+
+  void var_init() 
+  {
+    var_pchar = 0;
+    var_pcharc = 0;
+    var_pint = 0;
+    var_namet[0] = 'h';
+  }
+  
+}
+
+/* check variables */
+%define var_check(type, pfx, name)
+  if (pfx##_##name != def_##name) {
+    std::ostringstream a; std::ostringstream b;
+    a << pfx##_##name;
+    b << def_##name;
+    if (a.str() != b.str()) {
+      std::cout << "failing in pfx""_""name : "
+		<< a.str() << " : " << b.str() << std::endl;
+      //      return 0;
+    }
+  }
+%enddef
+
+/* check a function call */
+%define call_check(type, pfx, name)
+  type pfx##_##tmp##name = def_##name;
+  if (pfx##_##name(pfx##_##tmp##name) != def_##name) {
+    std::ostringstream a; std::ostringstream b;
+    a << pfx##_##name(pfx##_##tmp##name);
+    b << def_##name;
+    if (a.str() != b.str()) {
+      std::cout << "failing in pfx""_""name : "
+		<< a.str() << " : " << b.str() << std::endl;
+      // return 0;
+    }
+  }
+%enddef
+
+%define wrp_decl(type, pfx, name)
+  type wrp##_##pfx##_##name(type x) { 
+    return pfx##_##name(x); 
+  }
+%enddef
+
+/* function passing by value */
+%define ovr_decl(type, pfx, name)
+  virtual int pfx##_##val(type x) { return 1; }
+  virtual int pfx##_##ref(const type& x) { return 1; }
+%enddef
+
+
+%apply (char *STRING, int LENGTH) { (const char *str, size_t len) }
+
+%inline {
+  struct Foo
+  {
+    int _a;
+    
+    Foo (int a) : _a(a)
+    {
+    }
+    
+    Foo(const Foo&)
+    {
+    }
+
+    Foo copy(Foo x) 
+    {
+      return x;
+    }
+
+    const Foo copy_c(const Foo x) 
+    {
+      return x;
+    }
+
+    const Foo& copy_r(const Foo& x) 
+    {
+      return x;
+    }
+
+    Foo* this_p() 
+    {
+      return this;
+    }
+
+    Foo& this_r() 
+    {
+      return *this;
+    }
+    
+  };
+  
+  typedef Foo* foo_ptr;
+  
+  foo_ptr fptr_val(foo_ptr a) {
+    return a;
+  }
+
+  const foo_ptr& fptr_ref(const foo_ptr& a) {
+    return a;
+  }
+  
+  
+ struct Test 
+ {
+   Test()
+     : var_pchar(0), var_pcharc(0), var_pint(0)
+   {
+   }
+
+   virtual ~Test()
+   {
+   }
+   
+   %test_prim_types_stc(stc_decl, stc)
+   %test_prim_types(var_decl, var)
+   var_decl(namet, var, namet)
+
+
+   const char* val_namet(namet x) throw(namet)
+   {
+     return x;
+   }
+
+   const char* val_cnamet(const namet x) throw(namet)
+   {
+     return x;
+   }
+
+#if 0
+   /* I have no idea how to define a typemap for 
+      const namet&, where namet is a char[ANY]  array */
+   const namet& ref_namet(const namet& x) throw(namet)
+   {
+     return x;
+   }
+#endif
+
+   
+   %test_prim_types(val_decl, val)
+   %test_prim_types(ref_decl, ref)
+
+   int c_check() 
+   {
+     %test_prim_types(call_check, val)
+     %test_prim_types(call_check, ref)
+     return 1;
+   }
+
+   int v_check() 
+   {
+     %test_prim_types_stc(var_check, stc)
+     %test_prim_types(var_check, var)
+     var_check(namet, var, namet);
+     return 1;
+   }
+
+   %test_prim_types_ovr(ovr_decl, ovr)
+
+   size_t strlen(const char *str, size_t len)
+   {
+     return len;
+   }
+
+   static const double stc_double;
+   static const double stc_float;
+
+   
+ };
+
+ struct TestDirector
+ {
+   TestDirector()
+     : var_pchar(0), var_pcharc(0), var_pint(0)
+   {
+   }
+
+   
+   virtual ~TestDirector()
+   {
+     var_namet[0]='h';
+   }
+
+   virtual const char* vval_namet(namet x) throw(namet)
+   {
+     return x;
+   }
+
+   virtual const char* vval_cnamet(const namet x) throw(namet)
+   {
+     return x;
+   }
+
+#if 0
+   /* I have no idea how to define a typemap for 
+      const namet&, where namet is a char[ANY]  array */
+   virtual const namet& vref_namet(const namet& x) throw(namet)
+   {
+     return x;
+   }
+#endif
+
+
+   %test_prim_types_stc(stc_decl, stc)
+   %test_prim_types(var_decl, var)
+   var_decl(namet, var, namet)
+
+   %test_prim_types(val_decl, val)
+   %test_prim_types(ref_decl, ref)
+
+   %test_prim_types(vval_decl, vval)
+   %test_prim_types(vref_decl, vref)
+
+   %test_prim_types(wrp_decl, vref)
+   %test_prim_types(wrp_decl, vval)
+
+   int c_check() 
+   {
+     %test_prim_types(call_check, vval)
+     %test_prim_types(call_check, vref)
+     return 1;
+   }
+
+   int v_check() 
+   {
+     %test_prim_types_stc(var_check, stc)
+     %test_prim_types(var_check, var)
+     return 1;
+   }
+
+   %test_prim_types_ovr(ovr_decl, ovr)
+   
+
+   virtual Test* vtest(Test* t) const throw (Test)
+   {
+     return t;
+   }
+   
+ }; 
+
+ int v_check() 
+ {
+   %test_prim_types(var_check, cct)
+   %test_prim_types(var_check, var)
+   var_check(namet, var, namet);
+   return 1;
+ }
+
+}
+
+%inline %{
+
+  const char* char_foo(float f, const char *s) {
+    return s;
+  }
+  
+  int char_foo(double d, int i) {
+    return i;
+  }
+  
+%}
+
+%{
+  const double Test::stc_double = 1;
+  const double Test::stc_float = 1;
+%}
+
+
+%inline
+%{
+    namespace DCTypes
+    {
+        typedef const unsigned int cuint;
+    }
+
+    namespace DCSystem
+    {
+        using namespace DCTypes;
+        unsigned int SetPos(cuint& x, cuint& y) {return x + y;}
+    }
+
+    double val_double_2(double x, const double& y = 3.0) {
+      return x + y;
+    } 
+
+    double val_double(double x) {
+      return x;
+    } 
+
+    float val_float_2(float x, const float& y = 3.0) {
+      return x + y;
+    } 
+
+    // Regression test for bug1699646 - we weren't handling
+    // + or - after e for float constants.
+    float regression_test_for_bug1699646(float f = 1e-02f) {
+      return f;
+    } 
+
+    float val_float(float x) {
+      return x;
+    } 
+%}
+
+
+%apply SWIGTYPE* { char *};
+  
+%include "carrays.i"
+%array_functions(char,pchar);
+
diff --git a/trunk/Examples/test-suite/private_assign.i b/trunk/Examples/test-suite/private_assign.i
new file mode 100644
index 0000000..acc4d0b
--- /dev/null
+++ b/trunk/Examples/test-suite/private_assign.i
@@ -0,0 +1,71 @@
+// A class with a private assignment operator.
+// This is rare, but sometimes used with singletons and
+// objects that have complicated state.
+
+%module private_assign
+%{
+#include <stdlib.h>
+%}
+
+%inline %{
+   class Foo {
+   private:
+       Foo &operator=(const Foo &f) {
+           return *this;
+       }
+   public:
+       void bar() { }
+   };
+
+   Foo blah() {
+      return Foo();
+   }
+
+  class Bar : protected Foo
+  {
+  };
+
+%}
+
+#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_NEW // operator new
+
+%inline %{
+  class TROOT {
+  protected:
+     void *operator new(size_t l) { return malloc(sizeof(TROOT)); }
+   
+    int prot_meth() 
+    {
+      return 1;
+    }
+    
+  public:
+    TROOT()
+    {
+    }
+
+    TROOT(const char *name, const char *title, void *initfunc = 0)
+    {
+    }
+  };
+
+  class A : protected TROOT
+  {
+  };
+  
+%}
+
+#ifdef SWIGPYTHON
+
+// This case only works in python
+%inline %{
+   struct FooBar : Foo 
+   {
+   };
+   
+   FooBar bar;
+   
+%}
+
+
+#endif
diff --git a/trunk/Examples/test-suite/profiletest.i b/trunk/Examples/test-suite/profiletest.i
new file mode 100644
index 0000000..e75f8fc
--- /dev/null
+++ b/trunk/Examples/test-suite/profiletest.i
@@ -0,0 +1,65 @@
+%module profiletest
+
+%inline %{
+
+  class A  {
+  public:
+    A() {}
+  };
+
+  class B
+  { 
+    A aa;
+  public: 
+    B() {} 
+    A fn(const A* a) {
+      return *a;
+    }
+
+    int fi(int a) {
+      return a;
+    }
+
+    int fj(const A* a) {
+      return 10;
+    }
+
+    B* fk(int i) {
+      return this;
+    }
+
+    const char* fl(int i) {
+      return "hello";
+    }
+
+    const char* fs(const char *s) {
+      return s;
+    }
+
+    int fi(int a, int) {
+      return a;
+    }
+
+    int fi(char *) {
+      return 1;
+    }
+
+    int fi(double) {
+      return 2;
+    }
+
+    int fi(A *a) {
+      return 3;
+    }
+
+    int fi(int a, int, int) {
+      return a;
+    }
+
+    int fi(int a, int, int, int) {
+      return a;
+    }
+
+  };
+
+%}
diff --git a/trunk/Examples/test-suite/protected_rename.i b/trunk/Examples/test-suite/protected_rename.i
new file mode 100644
index 0000000..41f7ac4
--- /dev/null
+++ b/trunk/Examples/test-suite/protected_rename.i
@@ -0,0 +1,19 @@
+%module protected_rename
+
+/**
+ * We should be able to rename Foo::y() to 'x' since the protected
+ * member variable of the same name is not wrapped. Thus this test
+ * case shouldn't generate any warnings.
+ */
+
+%rename(x) Foo::y();
+
+%inline %{
+class Foo {
+protected:
+    int x;
+public:
+    void y() {}
+};
+
+%}
diff --git a/trunk/Examples/test-suite/pure_virtual.i b/trunk/Examples/test-suite/pure_virtual.i
new file mode 100644
index 0000000..b41e48a
--- /dev/null
+++ b/trunk/Examples/test-suite/pure_virtual.i
@@ -0,0 +1,80 @@
+/* SF Bug #445219, submitted by Krzysztof Kozminski
+   <kozminski@users.sf.net>. 
+
+   Swig 1.3.6 gets confused by pure virtual destructors,
+   as in this file:
+*/
+
+%module(ruby_minherit="1") pure_virtual
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) E; /* C#, Java, Php4 multiple inheritance */
+
+%nodefaultctor C;
+%nodefaultdtor C;
+%nodefaultctor E;
+%nodefaultdtor E;
+
+%inline %{
+
+class A {
+ public:
+  A() { };
+  virtual ~A() = 0;
+  virtual void something() = 0;
+  virtual void method() = 0;
+};
+
+class B : public A {
+public:
+  B() {};
+  virtual ~B() { };
+  virtual void something() { };
+  virtual void method() { };
+};
+
+/* class C is abstract because it doesn't define all methods in A */
+class C : public A {
+ public:
+  virtual ~C() { };
+  virtual void method() { };
+}
+;
+
+/* class D is not abstract, it defines everything */
+class D : public C {
+ public:
+  virtual ~D() { };
+  virtual void something() { };
+}
+;
+
+/* Another abstract class */
+class AA {
+  public:
+     virtual ~AA() { }
+     virtual void method2() = 0;
+};
+
+/* Multiple inheritance between two abstract classes */
+class E : public C, public AA {
+public:
+   virtual void something() { };
+};
+
+/* Fill in method from AA.  This class should be constructable */
+#ifdef SWIGCSHARP
+%ignore F::method2(); // Work around for lack of multiple inheritance support - base AA is ignored.
+#endif
+class F : public E {
+   public:
+     virtual void method2() { }
+};
+
+%}
+
+%{
+A::~A() {}
+%}
+
diff --git a/trunk/Examples/test-suite/python/Makefile.in b/trunk/Examples/test-suite/python/Makefile.in
new file mode 100644
index 0000000..7f11cd4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/Makefile.in
@@ -0,0 +1,114 @@
+#######################################################################
+# Makefile for python test-suite
+#######################################################################
+
+LANGUAGE     = python
+PYTHON       = @PYTHON@
+SCRIPTSUFFIX = _runme.py
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+CPP_TEST_CASES += \
+	argcargvtest \
+	autodoc \
+	callback \
+	complextest \
+	director_stl \
+	director_wstring \
+	file_test \
+	iadd \
+	inout \
+	input \
+	inplaceadd \
+	implicittest \
+	kwargs \
+	li_cstring \
+	li_cwstring \
+	li_factory \
+	li_implicit \
+	li_std_vectora \
+	li_std_map \
+	li_std_set \
+	li_std_stream \
+	li_std_wstream \
+	li_std_wstring \
+	nondynamic \
+	overload_simple_cast \
+	primitive_types \
+	std_containers \
+	swigobject \
+	template_matrix \
+	simutry \
+	vector
+
+
+C_TEST_CASES += \
+	file_test \
+	li_cstring \
+	li_cwstring \
+	nondynamic
+
+#
+# This test only works with modern C compilers
+#
+#C_TEST_CASES += \
+#	complextest
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+LIBS       = -L.
+VALGRIND_OPT += --suppressions=pythonswig.supp
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.py appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=$(srcdir):$$PYTHONPATH $(RUNTOOL) $(PYTHON) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: remove the generated .py file
+%.clean:
+	@rm -f hugemod.h hugemod_a.i hugemod_b.i hugemod_a.py hugemod_b.py hugemod_runme.py
+	@rm -f $*.py;
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile python_clean
+
+cvsignore:
+	@echo '*wrap* *.pyc *.so *.dll *.exp *.lib'
+	@echo Makefile
+	@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do echo $$i.py; done 
+	@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do if grep -q $${i}_runme.py CVS/Entries ; then echo $${i}_runme.py; fi; done 
+	@echo clientdata_prop_a.py 
+	@echo clientdata_prop_b.py 
+	@echo imports_a.py 
+	@echo imports_b.py 
+	@echo mod_a.py mod_b.py 
+	@echo hugemod.h hugemod_a.i hugemod_b.i hugemod_a.py hugemod_b.py hugemod_runme.py
+	@echo template_typedef_import.py
+
+
+hugemod:
+	perl hugemod.pl
+	$(MAKE) hugemod_a.cpptest
+	$(MAKE) hugemod_b.cpptest
+	time $(PYTHON) hugemod_runme.py
+	time $(PYTHON) hugemod_runme.py
diff --git a/trunk/Examples/test-suite/python/README b/trunk/Examples/test-suite/python/README
new file mode 100644
index 0000000..b86ec52
--- /dev/null
+++ b/trunk/Examples/test-suite/python/README
@@ -0,0 +1,4 @@
+See ../README for common README file.
+
+Any testcases which have _runme.py appended after the testcase name will be detected and run.
+
diff --git a/trunk/Examples/test-suite/python/abstract_access_runme.py b/trunk/Examples/test-suite/python/abstract_access_runme.py
new file mode 100644
index 0000000..55638e4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/abstract_access_runme.py
@@ -0,0 +1,6 @@
+import abstract_access
+
+d = abstract_access.D()
+if d.do_x() != 1:
+   raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/abstract_typedef2_runme.py b/trunk/Examples/test-suite/python/abstract_typedef2_runme.py
new file mode 100644
index 0000000..2a11d19
--- /dev/null
+++ b/trunk/Examples/test-suite/python/abstract_typedef2_runme.py
@@ -0,0 +1,8 @@
+from  abstract_typedef2 import *
+
+a = A_UF()
+  
+
+
+
+
diff --git a/trunk/Examples/test-suite/python/abstract_typedef_runme.py b/trunk/Examples/test-suite/python/abstract_typedef_runme.py
new file mode 100644
index 0000000..15d70aa
--- /dev/null
+++ b/trunk/Examples/test-suite/python/abstract_typedef_runme.py
@@ -0,0 +1,11 @@
+from  abstract_typedef import *
+e = Engine()
+
+a = A()
+  
+
+if a.write(e) != 1:
+  raise RuntimeError
+
+
+
diff --git a/trunk/Examples/test-suite/python/abstract_virtual_runme.py b/trunk/Examples/test-suite/python/abstract_virtual_runme.py
new file mode 100644
index 0000000..9cd0b7c
--- /dev/null
+++ b/trunk/Examples/test-suite/python/abstract_virtual_runme.py
@@ -0,0 +1,6 @@
+from abstract_virtual import *
+
+
+d = D()
+
+e = E()
diff --git a/trunk/Examples/test-suite/python/argcargvtest.i b/trunk/Examples/test-suite/python/argcargvtest.i
new file mode 100644
index 0000000..ed5aa09
--- /dev/null
+++ b/trunk/Examples/test-suite/python/argcargvtest.i
@@ -0,0 +1,23 @@
+%module argcargvtest
+
+%include <argcargv.i>
+
+%apply (int ARGC, char **ARGV) { (size_t argc, const char **argv) }
+
+%inline %{
+
+int mainc(size_t argc, const char **argv) 
+{
+  return (int)argc;
+}
+
+const char* mainv(size_t argc, const char **argv, int idx) 
+{
+  return argv[idx];
+}   
+
+void initializeApp(size_t argc, const char **argv, bool setPGid = true, bool isMakeline = false)
+{
+}
+
+%}
diff --git a/trunk/Examples/test-suite/python/argcargvtest_runme.py b/trunk/Examples/test-suite/python/argcargvtest_runme.py
new file mode 100644
index 0000000..584a19f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/argcargvtest_runme.py
@@ -0,0 +1,27 @@
+from argcargvtest import *
+
+largs=['hi','hola','hello']
+if mainc(largs) != 3:
+  raise RuntimeError, "bad main typemap"
+
+targs=('hi','hola')
+if mainv(targs,1) != 'hola':
+  print mainv(targs,1)
+  raise RuntimeError, "bad main typemap"
+
+targs=('hi', 'hola')
+if mainv(targs,1) != 'hola':
+  raise RuntimeError, "bad main typemap"
+
+try:
+  error = 0
+  mainv('hello',1)
+  error = 1
+except TypeError:
+  pass
+if error:
+  raise RuntimeError, "bad main typemap"
+
+
+
+initializeApp(largs)
diff --git a/trunk/Examples/test-suite/python/array_member_runme.py b/trunk/Examples/test-suite/python/array_member_runme.py
new file mode 100644
index 0000000..95cf03b
--- /dev/null
+++ b/trunk/Examples/test-suite/python/array_member_runme.py
@@ -0,0 +1,21 @@
+from array_member import *
+
+f = Foo()
+f.data = cvar.global_data
+
+for i in range(0,8):
+    if get_value(f.data,i) != get_value(cvar.global_data,i):
+        raise RuntimeError, "Bad array assignment"
+
+
+for i in range(0,8):
+    set_value(f.data,i,-i)
+
+cvar.global_data = f.data
+
+for i in range(0,8):
+    if get_value(f.data,i) != get_value(cvar.global_data,i):
+        raise RuntimeError, "Bad array assignment"
+    
+
+
diff --git a/trunk/Examples/test-suite/python/arrays_global_runme.py b/trunk/Examples/test-suite/python/arrays_global_runme.py
new file mode 100644
index 0000000..ab7fd6a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/arrays_global_runme.py
@@ -0,0 +1,20 @@
+import arrays_global
+
+arrays_global.cvar.array_i = arrays_global.cvar.array_const_i
+
+from  arrays_global import *
+
+BeginString_FIX44a
+cvar.BeginString_FIX44b
+BeginString_FIX44c
+cvar.BeginString_FIX44d
+cvar.BeginString_FIX44d
+cvar.BeginString_FIX44b ="12"'\0'"45"
+cvar.BeginString_FIX44b
+cvar.BeginString_FIX44d
+cvar.BeginString_FIX44e
+BeginString_FIX44f
+
+test_a("hello","hi","chello","chi")
+
+test_b("1234567","hi")
diff --git a/trunk/Examples/test-suite/python/autodoc.i b/trunk/Examples/test-suite/python/autodoc.i
new file mode 100644
index 0000000..c22cc02
--- /dev/null
+++ b/trunk/Examples/test-suite/python/autodoc.i
@@ -0,0 +1,95 @@
+%module(docstring="hello") autodoc
+
+%feature("autodoc");
+
+// especial typemap and its docs
+%typemap(in) (int c, int d) "$1 =0; $2 = 0;";
+%typemap(doc,name="hello",type="Tuple") (int c, int d) "hello: int tuple[2]";
+
+// testing for different documentation levels
+%feature("autodoc","0") A::func0; // names
+%feature("autodoc","1") A::func1; // names + types
+%feature("autodoc","2") A::func2; // extended 
+%feature("autodoc","3") A::func3; // extended + types
+
+%feature("autodoc","just a string") A::func; // names
+
+%inline {
+
+  enum Hola {
+    hi, hello
+  };
+  
+  struct A
+  {
+    A(int a, short b, Hola h)
+    {
+    }
+
+    int func(int a)
+    {
+      return a;
+    }
+
+    int func0(int c, int d)
+    {
+      return c;
+    }
+    
+    int func1(int c, int d)
+    {
+      return c;
+    }    
+
+    int func2(A* c, double d = 2)
+    {
+      return 2;
+    }
+
+    int func3(A* c, double d = 2)
+    {
+      return 2;
+    }
+  }; 
+}
+
+
+// deleting typemaps and docs
+%typemap(in) (int c, int d) ;
+%typemap(doc) (int c, int d);
+
+// docs for some parameters
+%typemap(doc) int a "a: special comment for parameter a";
+%typemap(doc) int b "b: another special comment for parameter b";
+
+%callback(1) func_cb;
+
+%inline {
+  
+  struct B
+  {
+    B(int a, int b, Hola h)
+    {
+    }
+    
+    
+    int func(int c, int d)
+    {
+      return c;
+    }
+    
+  }; 
+
+  int func(int c, int d) {
+    return c;
+  }
+
+  int funcio(int *INOUT) {
+    return 1;
+  }
+
+  int func_cb(int c, int d) {
+    return c;
+  }
+  
+}
diff --git a/trunk/Examples/test-suite/python/callback.i b/trunk/Examples/test-suite/python/callback.i
new file mode 100644
index 0000000..c4d50d3
--- /dev/null
+++ b/trunk/Examples/test-suite/python/callback.i
@@ -0,0 +1,72 @@
+%module callback
+
+%callback(1) foo;
+%callback(1) foof;
+%callback(1) A::bar;
+%callback(1) A::foom;
+%callback("%s_Cb_Ptr") foo_T;  // old style, still works.
+
+%inline %{
+
+  int foo(int a) {
+    return a;
+  }
+  
+  int foof(int a) {
+    return 3*a;
+  }  
+  
+  struct A 
+  {
+    static int bar(int a) {
+      return 2*a;
+    }
+
+    int foom(int a) 
+    {
+      return -a;
+    }
+
+    //friend int foof(int a);
+  };
+
+
+  extern "C" int foobar(int a, int (*pf)(int a)) {
+    return pf(a);
+  }
+
+  extern "C" int foobarm(int a, A ap, int (A::*pf)(int a)) {
+    return (ap.*pf)(a);
+  }
+
+  template <class T>
+    T foo_T(T a) 
+    {
+      return a;
+    }
+
+  template <class T>
+    T foo_T(T a, T b) 
+    {
+      return a + b;
+    }
+
+
+  template <class T>
+  T foobar_T(T a, T (*pf)(T a)) {
+    return pf(a);
+  }
+
+  template <class T>
+  const T& ident(const T& x) {
+    return x;
+  }
+%}
+
+%template(foo_i) foo_T<int>;
+%template(foobar_i) foobar_T<int>;
+
+%template(foo_d) foo_T<double>;
+%template(foobar_d) foobar_T<double>;
+
+%template(ident_d) ident<double>;
diff --git a/trunk/Examples/test-suite/python/callback_runme.py b/trunk/Examples/test-suite/python/callback_runme.py
new file mode 100644
index 0000000..b2bbb2d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/callback_runme.py
@@ -0,0 +1,31 @@
+import _callback
+from callback import *
+
+if foo(2) != 2:
+  raise RuntimeError
+
+if A_bar(2) != 4:
+  raise RuntimeError
+
+if foobar(3, _callback.foo) != foo(3):
+  raise RuntimeError  
+
+if foobar(3, foo) != foo(3):
+  raise RuntimeError  
+
+if foobar(3, A_bar) != A_bar(3):
+  raise RuntimeError
+
+if foobar(3, foof) != foof(3):
+  raise RuntimeError
+
+if foobar_i(3, foo_i) != foo_i(3):
+  raise RuntimeError
+
+
+if foobar_d(3.5, foo_d) != foo_d(3.5):
+  raise RuntimeError
+
+a = A()
+if foobarm(3, a, A.foom_cb_ptr) != a.foom(3):
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/class_ignore_runme.py b/trunk/Examples/test-suite/python/class_ignore_runme.py
new file mode 100644
index 0000000..782fc07
--- /dev/null
+++ b/trunk/Examples/test-suite/python/class_ignore_runme.py
@@ -0,0 +1,6 @@
+import class_ignore
+
+a = class_ignore.Bar()
+
+if class_ignore.do_blah(a) != "Bar::blah":
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/class_scope_weird_runme.py b/trunk/Examples/test-suite/python/class_scope_weird_runme.py
new file mode 100644
index 0000000..5c91d44
--- /dev/null
+++ b/trunk/Examples/test-suite/python/class_scope_weird_runme.py
@@ -0,0 +1,6 @@
+import class_scope_weird
+
+f = class_scope_weird.Foo()
+g = class_scope_weird.Foo(3)
+if f.bar(3) != 3:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/compactdefaultargs_runme.py b/trunk/Examples/test-suite/python/compactdefaultargs_runme.py
new file mode 100644
index 0000000..ff86571
--- /dev/null
+++ b/trunk/Examples/test-suite/python/compactdefaultargs_runme.py
@@ -0,0 +1,20 @@
+from compactdefaultargs import *
+
+defaults1 = Defaults1(1000)
+defaults1 = Defaults1()
+
+if defaults1.ret(10.0) != 10.0:
+  raise RuntimeError
+
+if defaults1.ret() != -1.0:
+  raise RuntimeError
+
+defaults2 = Defaults2(1000)
+defaults2 = Defaults2()
+
+if defaults2.ret(10.0) != 10.0:
+  raise RuntimeError
+
+if defaults2.ret() != -1.0:
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/complextest.i b/trunk/Examples/test-suite/python/complextest.i
new file mode 100644
index 0000000..64c751a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/complextest.i
@@ -0,0 +1,61 @@
+%module complextest
+
+%include <complex.i>
+
+#ifdef __cplusplus
+%{
+#include <algorithm>
+#include <functional>
+#include <numeric>
+%}
+%include <std_vector.i>
+
+#if 1
+%template(VectorStdCplx) std::vector<std::complex<double> >;
+#endif
+
+%inline 
+{
+  std::complex<double> Conj(const std::complex<double>&  a) 
+  {
+    return std::conj(a);
+  }  
+
+  std::complex<float> Conjf(const std::complex<float>&  a) 
+  {
+    return std::conj(a);
+  }  
+
+#if 1
+  std::vector<std::complex<double> > Copy_h(const std::vector<std::complex<double> >&  a) 
+  {
+    std::vector<std::complex<double> > b(a.size()/2);
+    std::copy(a.begin(), a.begin()+a.size()/2, b.begin());
+    return b;
+  }  
+#endif
+}
+
+
+#else
+
+
+%{
+%}
+
+%inline 
+{
+  complex Conj(complex a)
+  {
+    return conj(a);
+  }
+
+
+  complex float Conjf(float complex a)
+  {
+    return conj(a);
+  }
+}
+
+
+#endif
diff --git a/trunk/Examples/test-suite/python/complextest_runme.py b/trunk/Examples/test-suite/python/complextest_runme.py
new file mode 100644
index 0000000..cc2463a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/complextest_runme.py
@@ -0,0 +1,17 @@
+import complextest
+
+a = complex(-1,2)
+
+if complextest.Conj(a) != a.conjugate():
+  raise RuntimeError, "bad complex mapping"
+
+if complextest.Conjf(a) != a.conjugate():
+  raise RuntimeError, "bad complex mapping"
+
+
+v = (complex(1,2), complex(2,3), complex(4,3), 1)
+
+try:
+  complextest.Copy_h(v)
+except:
+  pass
diff --git a/trunk/Examples/test-suite/python/constover_runme.py b/trunk/Examples/test-suite/python/constover_runme.py
new file mode 100644
index 0000000..5c54197
--- /dev/null
+++ b/trunk/Examples/test-suite/python/constover_runme.py
@@ -0,0 +1,38 @@
+import constover
+import sys
+error = 0
+
+p = constover.test("test")
+if p != "test":
+    print "test failed!"
+    error = 1
+
+p = constover.test_pconst("test")
+if p != "test_pconst":
+    print "test_pconst failed!"
+    error = 1
+    
+f = constover.Foo()
+p = f.test("test")
+if p != "test":
+    print "member-test failed!"
+    error = 1
+
+p = f.test_pconst("test")
+if p != "test_pconst":
+    print "member-test_pconst failed!"
+    error = 1
+
+p = f.test_constm("test")
+if p != "test_constmethod":
+    print "member-test_constm failed!"
+    error = 1
+
+p = f.test_pconstm("test")
+if p != "test_pconstmethod":
+    print "member-test_pconstm failed!"
+    error = 1
+    
+sys.exit(error)
+
+
diff --git a/trunk/Examples/test-suite/python/constructor_copy_runme.py b/trunk/Examples/test-suite/python/constructor_copy_runme.py
new file mode 100644
index 0000000..431d323
--- /dev/null
+++ b/trunk/Examples/test-suite/python/constructor_copy_runme.py
@@ -0,0 +1,38 @@
+from constructor_copy import *
+
+f1 = Foo1(3);
+f11 = Foo1(f1);
+
+
+if f1.x != f11.x:
+    raise RuntimeError
+
+
+f8 = Foo8()
+try:
+    f81 = Foo8(f8)
+    good = 0
+except:
+    good = 1
+
+if not good:
+    raise RuntimeError
+
+
+bi = Bari(5)
+bc = Bari(bi)
+
+if (bi.x != bc.x):
+    raise RuntimeError
+    
+
+bd = Bard(5)
+try:
+    bc = Bard(bd)
+    good = 0
+except:
+    good = 1
+
+if not good:
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/contract_runme.py b/trunk/Examples/test-suite/python/contract_runme.py
new file mode 100644
index 0000000..9ded5bb
--- /dev/null
+++ b/trunk/Examples/test-suite/python/contract_runme.py
@@ -0,0 +1,135 @@
+import contract
+
+contract.test_preassert(1,2)
+try:
+	contract.test_preassert(-1)
+	print "Failed! Preassertions are broken"
+except:
+	pass
+
+contract.test_postassert(3)
+try:
+	contract.test_postassert(-3)
+	print "Failed! Postassertions are broken"
+except:
+	pass
+
+contract.test_prepost(2,3)
+contract.test_prepost(5,-4)
+try:
+	contract.test_prepost(-3,4)
+	print "Failed! Preassertions are broken"
+except:
+	pass
+
+try:
+	contract.test_prepost(4,-10)
+	print "Failed! Postassertions are broken"
+
+except:
+	pass
+
+f = contract.Foo()
+f.test_preassert(4,5)
+try:
+	f.test_preassert(-2,3)
+	print "Failed! Method preassertion."
+except:
+	pass
+
+f.test_postassert(4)
+try:
+	f.test_postassert(-4)
+	print "Failed! Method postassertion"
+except:
+	pass
+
+f.test_prepost(3,4)
+f.test_prepost(4,-3)
+try:
+	f.test_prepost(-4,2)
+	print "Failed! Method preassertion."
+except:
+	pass
+
+try:
+	f.test_prepost(4,-10)
+	print "Failed! Method postassertion."
+except:
+	pass
+
+contract.Foo_stest_prepost(4,0)
+try:
+	contract.Foo_stest_prepost(-4,2)
+	print "Failed! Static method preassertion"
+except:
+	pass
+
+try:
+	contract.Foo_stest_prepost(4,-10)
+	print "Failed! Static method posteassertion"
+except:
+	pass
+	
+b = contract.Bar()
+try:
+	b.test_prepost(2,-4)
+	print "Failed! Inherited preassertion."
+except:
+	pass
+
+
+d = contract.D()
+try:
+	d.foo(-1,1,1,1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.foo(1,-1,1,1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.foo(1,1,-1,1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.foo(1,1,1,-1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.foo(1,1,1,1,-1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+
+
+try:
+	d.bar(-1,1,1,1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.bar(1,-1,1,1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.bar(1,1,-1,1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.bar(1,1,1,-1,1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+try:
+	d.bar(1,1,1,1,-1)
+	print "Failed! Inherited preassertion (D)."
+except:
+	pass
+
diff --git a/trunk/Examples/test-suite/python/cpp_enum_runme.py b/trunk/Examples/test-suite/python/cpp_enum_runme.py
new file mode 100644
index 0000000..0054ae2
--- /dev/null
+++ b/trunk/Examples/test-suite/python/cpp_enum_runme.py
@@ -0,0 +1,23 @@
+import cpp_enum
+
+f = cpp_enum.Foo()
+
+if f.hola != f.Hello:
+  print f.hola
+  raise RuntimeError
+
+f.hola = f.Hi
+if f.hola != f.Hi:
+  print f.hola
+  raise RuntimeError
+
+f.hola = f.Hello
+
+if f.hola != f.Hello:
+  print f.hola
+  raise RuntimeError
+
+cpp_enum.cvar.hi = cpp_enum.Hello
+if cpp_enum.cvar.hi != cpp_enum.Hello:
+  print cpp_enum.cvar.hi
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/cpp_namespace_runme.py b/trunk/Examples/test-suite/python/cpp_namespace_runme.py
new file mode 100644
index 0000000..3108b4f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/cpp_namespace_runme.py
@@ -0,0 +1,45 @@
+# Note: This example assumes that namespaces are flattened
+import cpp_namespace
+
+n = cpp_namespace.fact(4)
+if n != 24:
+    raise "Bad return value!"
+
+if cpp_namespace.cvar.Foo != 42:
+    raise "Bad variable value!"
+
+t = cpp_namespace.Test()
+if t.method() != "Test::method":
+    raise "Bad method return value!"
+
+if cpp_namespace.do_method(t) != "Test::method":
+    raise "Bad return value!"
+
+if cpp_namespace.do_method2(t) != "Test::method":
+    raise "Bad return value!"
+    
+cpp_namespace.weird("hello", 4)
+
+del t
+
+t2 = cpp_namespace.Test2()
+t3 = cpp_namespace.Test3()
+t4 = cpp_namespace.Test4()
+t5 = cpp_namespace.Test5()
+
+if cpp_namespace.foo3(42) != 42:
+    raise "Bad return value!"
+
+if cpp_namespace.do_method3(t2,40) != "Test2::method":
+    raise "Bad return value!"
+
+if cpp_namespace.do_method3(t3,40) != "Test3::method":
+    raise "Bad return value!"
+
+if cpp_namespace.do_method3(t4,40) != "Test4::method":
+    raise "Bad return value!"
+
+if cpp_namespace.do_method3(t5,40) != "Test5::method":
+    raise "Bad return value!"
+
+    
diff --git a/trunk/Examples/test-suite/python/default_args_runme.py b/trunk/Examples/test-suite/python/default_args_runme.py
new file mode 100644
index 0000000..091a923
--- /dev/null
+++ b/trunk/Examples/test-suite/python/default_args_runme.py
@@ -0,0 +1,64 @@
+import default_args 
+
+
+if default_args.Statics_staticMethod() != 60:
+  raise RuntimeError
+  
+if default_args.cfunc1(1) != 2:
+  raise RuntimeError
+
+if default_args.cfunc2(1) != 3:
+  raise RuntimeError
+
+if default_args.cfunc3(1) != 4:
+  raise RuntimeError
+
+
+f = default_args.Foo()
+
+f.newname()
+f.newname(1)
+
+
+try:
+  f = default_args.Foo(1)
+  error = 1
+except:
+  error = 0
+if error:  raise RuntimeError,"Foo::Foo ignore is not working"
+
+try:
+  f = default_args.Foo(1,2)
+  error = 1
+except:
+  error = 0
+if error:  raise RuntimeError,"Foo::Foo ignore is not working"
+
+try:
+  f = default_args.Foo(1,2,3)
+  error = 1
+except:
+  error = 0
+if error:  raise RuntimeError,"Foo::Foo ignore is not working"
+
+try:
+  m = f.meth(1)
+  error = 1
+except:
+  error = 0
+if error:  raise RuntimeError,"Foo::meth ignore is not working"
+
+try:
+  m = f.meth(1,2)
+  error = 1
+except:
+  error = 0
+if error:  raise RuntimeError,"Foo::meth ignore is not working"
+
+try:
+  m = f.meth(1,2,3)
+  error = 1
+except:
+  error = 0
+if error:  raise RuntimeError,"Foo::meth ignore is not working"
+
diff --git a/trunk/Examples/test-suite/python/default_constructor_runme.py b/trunk/Examples/test-suite/python/default_constructor_runme.py
new file mode 100644
index 0000000..334eaa8
--- /dev/null
+++ b/trunk/Examples/test-suite/python/default_constructor_runme.py
@@ -0,0 +1,111 @@
+import _default_constructor
+
+dc = _default_constructor
+
+a = dc.new_A()
+dc.delete_A(a)
+
+aa = dc.new_AA()
+dc.delete_AA(aa)
+
+try:
+    b = dc.new_B()
+    print "Whoa. new_BB created."
+except:
+    pass
+
+del_b = dc.delete_B
+
+try:
+    bb = dc.new_BB();
+    print "Whoa. new_BB created."
+except:
+    pass
+
+del_bb = dc.delete_BB
+
+try:
+    c = dc.new_C()
+    print "Whoa. new_C created."
+except:
+    pass
+
+del_c = dc.delete_C
+
+cc = dc.new_CC()
+dc.delete_CC(cc)
+
+try:
+    d = dc.new_D();
+    print "Whoa. new_D created"
+except:
+    pass
+
+del_d = dc.delete_D
+
+try:
+    dd = dc.new_DD()
+    print "Whoa. new_DD created"
+except:
+    pass
+
+dd = dc.delete_DD
+
+try:
+    ad = dc.new_AD()
+    print "Whoa. new_AD created"
+except:
+    pass
+
+del_ad = dc.delete_AD
+
+e = dc.new_E()
+dc.delete_E(e)
+
+ee = dc.new_EE()
+dc.delete_EE(ee)
+
+try:
+    eb = dc.new_EB()
+    print "Whoa. new_EB created"
+except:
+    pass
+
+del_eb = dc.delete_EB
+
+f = dc.new_F()
+
+try:
+    del_f = dc.delete_F
+    print "Whoa. delete_F created"
+except AttributeError:
+    pass
+
+dc.F_destroy(f)
+
+ff = dc.new_FFF()
+try:
+    del_ff = dc.delete_FFF
+    print "Whoa. delete_FFF created"
+except AttributeError:
+    pass
+
+dc.F_destroy(ff)
+
+g = dc.new_G()
+
+try:
+    del_g = dc.delete_G
+    print "Whoa. delete_G created"
+except AttributeError:
+    pass
+
+dc.G_destroy(g)
+
+gg = dc.new_GG()
+dc.delete_GG(gg)
+
+
+import default_constructor
+hh = default_constructor.HH(1,1)
+
diff --git a/trunk/Examples/test-suite/python/director_abstract_runme.py b/trunk/Examples/test-suite/python/director_abstract_runme.py
new file mode 100644
index 0000000..7d92d10
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_abstract_runme.py
@@ -0,0 +1,68 @@
+import director_abstract
+
+class MyFoo(director_abstract.Foo):
+	def __init__(self):
+		director_abstract.Foo.__init__(self)
+	def ping(self):
+		return "MyFoo::ping()"
+
+
+a = MyFoo()
+
+if a.ping() != "MyFoo::ping()":
+	raise RuntimeError, a.ping()
+
+if a.pong() != "Foo::pong();MyFoo::ping()":
+	raise RuntimeError, a.pong()
+
+
+class MyExample1(director_abstract.Example1):
+	def Color(self, r, g, b):
+		return r
+
+class MyExample2(director_abstract.Example2):
+	def Color(self, r, g, b):
+		return g
+
+class MyExample3(director_abstract.Example3_i):
+	def Color(self, r, g, b):
+		return b
+
+me1 = MyExample1()
+if director_abstract.Example1_get_color(me1, 1,2,3) != 1:
+	raise RuntimeError
+
+me2 = MyExample2(1,2)
+if MyExample2.get_color(me2, 1,2,3) != 2:
+	raise RuntimeError
+
+me3 = MyExample3()
+if MyExample3.get_color(me3, 1,2,3) != 3:
+	raise RuntimeError
+
+error = 1
+try:
+	me1 = director_abstract.Example1()
+except:
+	error = 0
+if (error): raise RuntimeError
+
+error = 1
+try:
+	me2 = director_abstract.Example2()
+except:
+	error = 0
+if (error): raise RuntimeError
+
+error = 1
+try:
+	me3 = director_abstract.Example3_i()
+except:
+	error = 0
+if (error): raise RuntimeError
+
+
+try:
+	f = director_abstract.A.f
+except:
+	raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/director_basic_runme.py b/trunk/Examples/test-suite/python/director_basic_runme.py
new file mode 100644
index 0000000..5411398
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_basic_runme.py
@@ -0,0 +1,98 @@
+import director_basic
+
+class PyFoo(director_basic.Foo):
+	def ping(self):
+		return "PyFoo::ping()"
+
+
+a = PyFoo()
+
+if a.ping() != "PyFoo::ping()":
+	raise RuntimeError, a.ping()
+
+if a.pong() != "Foo::pong();PyFoo::ping()":
+	raise RuntimeError, a.pong()
+
+b = director_basic.Foo()
+
+if b.ping() != "Foo::ping()":
+	raise RuntimeError, b.ping()
+
+if b.pong() != "Foo::pong();Foo::ping()":
+	raise RuntimeError, b.pong()
+
+a = director_basic.A1(1)
+
+if a.rg(2) != 2:
+	raise RuntimeError
+
+
+
+class PyClass(director_basic.MyClass):
+	def method(self, vptr):
+		self.cmethod = 7
+		pass
+	
+	def vmethod(self, b):
+		b.x = b.x + 31
+		return b
+
+
+b = director_basic.Bar(3)
+d = director_basic.MyClass()
+c = PyClass()
+
+cc = director_basic.MyClass_get_self(c)
+dd = director_basic.MyClass_get_self(d)
+
+bc = cc.cmethod(b)
+bd = dd.cmethod(b)
+
+cc.method(b)
+if c.cmethod != 7:
+	raise RuntimeError
+
+if bc.x != 34:
+	raise RuntimeError
+
+
+if bd.x != 16:
+	raise RuntimeError
+
+
+
+class PyMulti(director_basic.Foo, director_basic.MyClass):
+	def __init__(self):
+		director_basic.Foo.__init__(self)
+		director_basic.MyClass.__init__(self)		
+		pass
+
+		
+	def vmethod(self, b):
+		b.x = b.x  + 31
+		return b
+
+	
+	def ping(self):
+		return "PyFoo::ping()"
+
+a = 0
+for i in range(0,100):
+    pymult = PyMulti()
+    pymult.pong()
+    del pymult 
+
+
+
+pymult = PyMulti()
+
+
+
+
+p1 = director_basic.Foo_get_self(pymult)
+p2 = director_basic.MyClass_get_self(pymult)
+
+p1.ping()
+p2.vmethod(bc)
+
+
diff --git a/trunk/Examples/test-suite/python/director_classic_runme.py b/trunk/Examples/test-suite/python/director_classic_runme.py
new file mode 100644
index 0000000..8789056
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_classic_runme.py
@@ -0,0 +1,142 @@
+from director_classic import *
+
+class TargetLangPerson(Person):
+	def __init__(self):
+		Person.__init__(self)
+	def id(self):
+		identifier = "TargetLangPerson"
+                return identifier
+
+class TargetLangChild(Child):
+	def __init__(self):
+		Child.__init__(self)
+	def id(self):
+		identifier = "TargetLangChild"
+                return identifier
+
+class TargetLangGrandChild(GrandChild):
+	def __init__(self):
+		GrandChild.__init__(self)
+	def id(self):
+		identifier = "TargetLangGrandChild"
+                return identifier
+
+# Semis - don't override id() in target language
+class TargetLangSemiPerson(Person):
+	def __init__(self):
+		Person.__init__(self)
+        # No id() override
+
+class TargetLangSemiChild(Child):
+	def __init__(self):
+		Child.__init__(self)
+        # No id() override
+
+class TargetLangSemiGrandChild(GrandChild):
+	def __init__(self):
+		GrandChild.__init__(self)
+        # No id() override
+
+# Orphans - don't override id() in C++
+class TargetLangOrphanPerson(OrphanPerson):
+	def __init__(self):
+		OrphanPerson.__init__(self)
+	def id(self):
+		identifier = "TargetLangOrphanPerson"
+                return identifier
+
+class TargetLangOrphanChild(OrphanChild):
+	def __init__(self):
+		Child.__init__(self)
+	def id(self):
+		identifier = "TargetLangOrphanChild"
+                return identifier
+
+
+def check(person, expected):
+
+  debug = 0
+  # Normal target language polymorphic call
+  ret = person.id()
+  if (debug):
+    print(ret)
+  if (ret != expected):
+    raise ("Failed. Received: " + ret + " Expected: " + expected)
+
+  # Polymorphic call from C++
+  caller = Caller()
+  caller.setCallback(person)
+  ret = caller.call()
+  if (debug):
+    print(ret)
+  if (ret != expected):
+    raise ("Failed. Received: " + ret + " Expected: " + expected)
+
+  # Polymorphic call of object created in target language and passed to C++ and back again
+  baseclass = caller.baseClass()
+  ret = baseclass.id()
+  if (debug):
+    print(ret)
+  if (ret != expected):
+    raise ("Failed. Received: " + ret + " Expected: " + expected)
+
+  caller.resetCallback()
+  if (debug):
+    print("----------------------------------------")
+
+
+
+person = Person();
+check(person, "Person");
+del person
+
+person = Child();
+check(person, "Child");
+del person
+
+person = GrandChild();
+check(person, "GrandChild"); 
+del person
+
+person = TargetLangPerson();
+check(person, "TargetLangPerson"); 
+del person
+
+person = TargetLangChild();
+check(person, "TargetLangChild"); 
+del person
+
+person = TargetLangGrandChild();
+check(person, "TargetLangGrandChild"); 
+del person
+
+# Semis - don't override id() in target language
+person = TargetLangSemiPerson();
+check(person, "Person"); 
+del person
+
+person = TargetLangSemiChild();
+check(person, "Child"); 
+del person
+
+person = TargetLangSemiGrandChild();
+check(person, "GrandChild"); 
+del person
+
+# Orphans - don't override id() in C++
+person = OrphanPerson();
+check(person, "Person");
+del person
+
+person = OrphanChild();
+check(person, "Child");
+del person
+
+person = TargetLangOrphanPerson();
+check(person, "TargetLangOrphanPerson"); 
+del person
+
+person = TargetLangOrphanChild();
+check(person, "TargetLangOrphanChild"); 
+del person
+
diff --git a/trunk/Examples/test-suite/python/director_default_runme.py b/trunk/Examples/test-suite/python/director_default_runme.py
new file mode 100644
index 0000000..f3ac149
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_default_runme.py
@@ -0,0 +1,9 @@
+from director_default import *
+
+
+f = Foo()
+f = Foo(1)
+
+
+f = Bar()
+f = Bar(1)
diff --git a/trunk/Examples/test-suite/python/director_detect_runme.py b/trunk/Examples/test-suite/python/director_detect_runme.py
new file mode 100644
index 0000000..a90cfe8
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_detect_runme.py
@@ -0,0 +1,36 @@
+import director_detect 
+
+class MyBar(director_detect.Bar):
+  def __init__(self, val = 2):
+    director_detect.Bar.__init__(self)
+    self.val = val
+
+  def get_value(self):
+    self.val = self.val + 1
+    return self.val
+  
+  def get_class(self):
+    self.val = self.val + 1
+    return director_detect.A()
+
+  def just_do_it(self):
+    self.val = self.val + 1
+
+  def clone(self):
+    return MyBar(self.val)
+  pass
+
+
+b = MyBar()
+
+f = b.baseclass()
+
+v = f.get_value()
+a = f.get_class()
+f.just_do_it()
+
+c = b.clone()
+vc = c.get_value()
+
+if (v != 3) or (b.val != 5) or (vc != 6):
+  raise RuntimeError,"Bad virtual detection"
diff --git a/trunk/Examples/test-suite/python/director_enum_runme.py b/trunk/Examples/test-suite/python/director_enum_runme.py
new file mode 100644
index 0000000..5692c88
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_enum_runme.py
@@ -0,0 +1,12 @@
+import director_enum
+
+class MyFoo(director_enum.Foo):
+  def say_hi(self, val):
+    return val
+
+
+b = director_enum.Foo()
+a = MyFoo()
+
+if a.say_hi(director_enum.hello) != b.say_hello(director_enum.hi):
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/director_exception_runme.py b/trunk/Examples/test-suite/python/director_exception_runme.py
new file mode 100644
index 0000000..7c9e692
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_exception_runme.py
@@ -0,0 +1,51 @@
+from director_exception import *
+from exceptions import *
+
+class MyFoo(Foo):
+	def ping(self):
+		raise NotImplementedError, "MyFoo::ping() EXCEPTION"
+
+class MyFoo2(Foo):
+	def ping(self):
+		return true
+		pass # error: should return a string
+
+ok = 0
+
+a = MyFoo()
+b = launder(a)
+
+try:
+	b.pong()
+except NotImplementedError, e:
+	ok = 1
+except:
+	pass
+
+if not ok:
+	raise RuntimeError
+
+ok = 0
+
+a = MyFoo2()
+b = launder(a)
+
+try:
+	b.pong()
+except:
+	ok = 1
+
+
+if not ok:
+	raise RuntimeError
+
+
+try:
+	raise Exception2()
+except Exception2:
+	pass
+
+try:
+	raise Exception1()
+except Exception1:
+	pass
diff --git a/trunk/Examples/test-suite/python/director_extend_runme.py b/trunk/Examples/test-suite/python/director_extend_runme.py
new file mode 100644
index 0000000..1ab5867
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_extend_runme.py
@@ -0,0 +1,20 @@
+# Test case from bug #1506850
+#"When threading is enabled, the interpreter will infinitely wait on a mutex the second
+#time this type of extended method is called. Attached is an example
+#program that waits on the mutex to be unlocked."
+
+from director_extend import *
+
+class MyObject(SpObject):
+    def __init__(self):
+        SpObject.__init__(self)
+        return
+
+    def getFoo(self):
+        return 123
+    
+m = MyObject()
+if m.dummy() != 666:
+  raise RuntimeError, "1st call"
+if m.dummy() != 666:                        # Locked system
+  raise RuntimeError, "2nd call"
diff --git a/trunk/Examples/test-suite/python/director_finalizer_runme.py b/trunk/Examples/test-suite/python/director_finalizer_runme.py
new file mode 100644
index 0000000..4cd1f57
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_finalizer_runme.py
@@ -0,0 +1,48 @@
+from director_finalizer import *
+
+class MyFoo(Foo):
+	def __del__(self):
+		self.orStatus(2)
+		try: Foo.__del__(self)
+		except: pass
+
+
+resetStatus()
+
+a = MyFoo()
+del a
+
+if getStatus() != 3:
+	raise RuntimeError
+
+resetStatus()
+
+a = MyFoo()
+launder(a)
+
+if getStatus() != 0:
+	raise RuntimeError
+
+del a
+
+if getStatus() != 3:
+	raise RuntimeError
+
+resetStatus()
+
+a = MyFoo().__disown__()
+deleteFoo(a)
+
+if getStatus() != 3:
+	raise RuntimeError
+	
+resetStatus()
+
+a = MyFoo().__disown__()
+deleteFoo(launder(a))
+
+if getStatus() != 3:
+	raise RuntimeError
+	
+resetStatus()
+
diff --git a/trunk/Examples/test-suite/python/director_frob_runme.py b/trunk/Examples/test-suite/python/director_frob_runme.py
new file mode 100644
index 0000000..c2dd734
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_frob_runme.py
@@ -0,0 +1,7 @@
+from director_frob import *
+
+foo = Bravo();
+s = foo.abs_method();
+
+if s != "Bravo::abs_method()":
+  raise RuntimeError, s
diff --git a/trunk/Examples/test-suite/python/director_nested_runme.py b/trunk/Examples/test-suite/python/director_nested_runme.py
new file mode 100644
index 0000000..cff82f5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_nested_runme.py
@@ -0,0 +1,63 @@
+from director_nested import *
+
+
+class A(FooBar_int):
+  def do_step(self):
+    return "A::do_step;"
+  
+  def get_value(self):
+    return "A::get_value"
+
+  pass
+
+
+a = A()
+if a.step() != "Bar::step;Foo::advance;Bar::do_advance;A::do_step;":
+  raise RuntimeError,"Bad A virtual resolution"
+
+
+class B(FooBar_int):
+  def do_advance(self):
+    return "B::do_advance;" + self.do_step()
+
+  def do_step(self):
+    return "B::do_step;"
+  
+  def get_value(self):
+    return 1
+
+  pass
+
+
+b = B()
+
+if b.step() != "Bar::step;Foo::advance;B::do_advance;B::do_step;":
+  raise RuntimeError,"Bad B virtual resolution"
+
+
+
+class C(FooBar_int):
+  def do_advance(self):
+    return "C::do_advance;" + FooBar_int.do_advance(self)
+
+  def do_step(self):
+    return "C::do_step;"
+  
+  def get_value(self):
+    return 2
+
+  def get_name(self):
+    return FooBar_int.get_name(self) + " hello"
+
+  
+  pass
+
+cc = C()
+c = FooBar_int_get_self(cc)
+c.advance()
+
+if c.get_name() != "FooBar::get_name hello":
+  raise RuntimeError
+
+if c.name() != "FooBar::get_name hello":
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/director_profile.i b/trunk/Examples/test-suite/python/director_profile.i
new file mode 100644
index 0000000..25ed895
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_profile.i
@@ -0,0 +1,64 @@
+%module(directors="1") director_profile
+
+%include std_string.i
+
+%feature("director") B;
+
+
+%inline %{
+
+  class A  {
+  public:
+    A() {}
+  };
+
+  class B
+  { 
+    A aa;
+  public: 
+    B() {}
+
+    virtual A fn(const A* a) {
+      return *a;
+    }
+
+    virtual int vfi(int a) {
+      return a + 1;
+    }
+
+    int fi(int a) {
+      return vfi(a);
+    }
+
+    int fj(const A* a) {
+      return 10;
+    }
+
+    B* fk(int i) {
+      return this;
+    }
+
+    const char* fl(int i) {
+      return "hello";
+    }
+
+    virtual ~B()
+    {
+    }
+
+    static B* get_self(B *b) 
+    {
+      return b;
+    }
+
+    virtual std::string vfs(const std::string& a) {
+      return a;
+    }
+    
+    std::string fs(const std::string& a) {
+      return vfs(a);
+    }
+    
+  };
+
+%}
diff --git a/trunk/Examples/test-suite/python/director_profile_runme.py b/trunk/Examples/test-suite/python/director_profile_runme.py
new file mode 100644
index 0000000..2f67481
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_profile_runme.py
@@ -0,0 +1,41 @@
+import director_profile
+
+class MyB(director_profile.B):
+    def vfi(self, a):
+        return a+3
+
+
+
+a = director_profile.A()
+myb = MyB()
+b = director_profile.B.get_self(myb)
+
+
+fi = b.fi
+i = 50000
+a = 1
+while i:
+  a = fi(a) #1
+  a = fi(a) #2
+  a = fi(a) #3
+  a = fi(a) #4
+  a = fi(a) #5
+  a = fi(a) #6
+  a = fi(a) #7
+  a = fi(a) #8
+  a = fi(a) #9
+  a = fi(a) #10
+  a = fi(a) #1
+  a = fi(a) #2
+  a = fi(a) #3
+  a = fi(a) #4
+  a = fi(a) #5
+  a = fi(a) #6
+  a = fi(a) #7
+  a = fi(a) #8
+  a = fi(a) #9
+  a = fi(a) #20
+  i -= 1
+
+print a
+
diff --git a/trunk/Examples/test-suite/python/director_protected_runme.py b/trunk/Examples/test-suite/python/director_protected_runme.py
new file mode 100644
index 0000000..9d565a1
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_protected_runme.py
@@ -0,0 +1,88 @@
+from director_protected import *
+
+
+
+class FooBar(Bar):
+  def ping(self):
+    return "FooBar::ping();"
+
+class FooBar2(Bar):
+  def ping(self):
+    return "FooBar2::ping();"
+  def pang(self):
+    return "FooBar2::pang();"
+
+
+b  = Bar()
+f  = b.create()
+fb = FooBar()
+fb2 = FooBar2()
+
+
+try:
+  s = fb.used()
+  if s != "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();":
+    raise RuntimeError
+  pass
+except:
+  raise RuntimeError, "bad FooBar::used"
+
+try:
+  s = fb2.used()
+  if s != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();":
+    raise RuntimeError
+  pass
+except:
+  raise RuntimeError, "bad FooBar2::used"
+
+try:
+  s = b.pong()
+  if s != "Bar::pong();Foo::pong();Bar::ping();":
+    raise RuntimeError
+  pass
+except:
+  raise RuntimeError, "bad Bar::pong"
+
+try:
+  s = f.pong()
+  if s != "Bar::pong();Foo::pong();Bar::ping();":
+    raise RuntimeError
+  pass
+except:
+  raise RuntimeError," bad Foo::pong"
+  
+try:
+  s = fb.pong()
+  if s != "Bar::pong();Foo::pong();FooBar::ping();":
+    raise RuntimeError
+  pass
+except:
+  raise RuntimeError," bad FooBar::pong"
+
+protected=1  
+try:
+  b.ping()
+  protected=0
+except:
+  pass
+if not protected:
+  raise  RuntimeError,"Boo::ping is protected"
+  
+protected=1  
+try:
+  f.ping()
+  protected=0
+except:
+  pass
+if not protected:
+  raise  RuntimeError,"Foo::ping is protected"
+
+
+protected=1  
+try:
+  f.pang()
+  protected=0
+except:
+  pass
+if not protected:
+  raise  RuntimeError,"FooBar::pang is protected"
diff --git a/trunk/Examples/test-suite/python/director_stl.i b/trunk/Examples/test-suite/python/director_stl.i
new file mode 100644
index 0000000..cbcb4ba
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_stl.i
@@ -0,0 +1,76 @@
+%module(directors="1") director_stl
+#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
+
+%include "std_string.i"
+%include "std_pair.i"
+%include "std_vector.i"
+
+#ifndef SWIG_STD_DEFAULT_INSTANTIATION
+%template() std::vector<double>;
+%template() std::vector<int>;
+%template() std::vector<std::string>;
+%template() std::pair<std::string, int>;
+%template() std::pair<int,double>;
+%template() std::pair<double,int>;
+#endif
+
+%feature("director") Foo;
+
+%feature("director:except") {
+  if ($error != NULL) {
+    throw Swig::DirectorMethodException();
+  }
+}
+
+%exception {
+  try { $action }
+  catch (...) { SWIG_fail; }
+}
+
+%inline 
+{
+class Foo {
+public:
+  virtual ~Foo() {}
+
+  virtual std::string& bar(std::string& s) 
+  {
+    return s;
+  }
+  
+
+  virtual std::string ping(std::string s) = 0;
+  virtual std::string pong(const std::string& s) 
+  { return std::string("Foo::pong:") + s + ":" + ping(s); }
+
+  std::string tping(std::string s) { return ping(s); }
+  std::string tpong(const std::string& s) { return pong(s); }
+  
+  virtual std::pair<double, int>
+  pident(const std::pair<double, int>& p) { return p; }
+
+  virtual std::vector<int>
+  vident(const std::vector<int>& p) { return p; }
+
+  virtual std::vector<int>
+  vsecond(const std::vector<int>& p, const std::vector<int>& s) { return s; }    
+
+  std::pair<double, int>
+  tpident(const std::pair<double, int>& p) { return pident(p); }
+
+  std::vector<int>
+  tvident(const std::vector<int>& p) { return vident(p); }
+
+  virtual std::vector<int>
+  tvsecond(const std::vector<int>& p, const std::vector<int>& s) { return vsecond(p,s); }
+
+
+  virtual std::vector<std::string>
+  vidents(const std::vector<std::string>& p) { return p; }
+
+  std::vector<std::string>
+  tvidents(const std::vector<std::string>& p) { return vidents(p); }
+  
+};
+
+}
diff --git a/trunk/Examples/test-suite/python/director_stl_runme.py b/trunk/Examples/test-suite/python/director_stl_runme.py
new file mode 100644
index 0000000..aaea036
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_stl_runme.py
@@ -0,0 +1,39 @@
+import director_stl
+
+class MyFoo(director_stl.Foo):
+  def ping(self, s):
+    return "MyFoo::ping():" + s
+
+  def pident(self, arg):
+    return arg
+    
+  def vident(self,v):
+    return v
+
+  def vidents(self,v):
+    return v
+
+  def vsecond(self,v1,v2):
+    return v2
+
+
+a = MyFoo()
+
+a.tping("hello")
+a.tpong("hello")
+
+p = (1,2)
+a.pident(p)
+v = (3,4)
+a.vident(v)
+
+a.tpident(p)
+a.tvident(v)
+
+v1 = (3,4)
+v2 = (5,6)
+a.tvsecond(v1,v2)
+
+vs=("hi", "hello")
+vs
+a.tvidents(vs)
diff --git a/trunk/Examples/test-suite/python/director_string_runme.py b/trunk/Examples/test-suite/python/director_string_runme.py
new file mode 100644
index 0000000..f2db416
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_string_runme.py
@@ -0,0 +1,29 @@
+from director_string import *
+
+class B(A):
+  def __init__(self,string):
+    A.__init__(self,string)
+
+  def get_first(self):
+    return A.get_first(self) + " world!"
+
+  def process_text(self, string):
+    A.process_text(self, string)
+    self.smem = "hello"
+    
+
+
+b = B("hello")
+
+b.get(0)
+if b.get_first() != "hello world!":
+  print b.get_first() 
+  raise RuntimeError
+
+
+b.call_process_func()
+
+if b.smem != "hello":
+  print smem
+  raise RuntimeError
+  
diff --git a/trunk/Examples/test-suite/python/director_thread_runme.py b/trunk/Examples/test-suite/python/director_thread_runme.py
new file mode 100644
index 0000000..e66817e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_thread_runme.py
@@ -0,0 +1,16 @@
+from director_thread import Foo
+
+class Derived(Foo) :
+    def __init__(self):
+        Foo.__init__(self)
+
+    def do_foo(self):
+        self.val = self.val - 1
+
+
+d = Derived()
+d.run()
+
+if d.val >= 0:
+    print d.val
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/director_unroll_runme.py b/trunk/Examples/test-suite/python/director_unroll_runme.py
new file mode 100644
index 0000000..e2bc937
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_unroll_runme.py
@@ -0,0 +1,19 @@
+import director_unroll
+
+class MyFoo(director_unroll.Foo):
+	def ping(self):
+		return "MyFoo::ping()"
+
+
+a = MyFoo()
+
+b = director_unroll.Bar()
+
+b.set(a)
+c = b.get()
+
+
+if not (a.this == c.this):
+	print a, c
+	raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/director_wstring_runme.py b/trunk/Examples/test-suite/python/director_wstring_runme.py
new file mode 100644
index 0000000..f3f29de
--- /dev/null
+++ b/trunk/Examples/test-suite/python/director_wstring_runme.py
@@ -0,0 +1,28 @@
+from director_wstring import *
+
+class B(A):
+  def __init__(self,string):
+    A.__init__(self,string)
+
+  def get_first(self):
+    return A.get_first(self) + u" world!"
+
+  def process_text(self, string):
+    self.smem = u"hello"
+    
+
+
+b = B(u"hello")
+
+b.get(0)
+if b.get_first() != u"hello world!":
+  print b.get_first() 
+  raise RuntimeError
+
+
+b.call_process_func()
+
+if b.smem != u"hello":
+  print smem
+  raise RuntimeError
+  
diff --git a/trunk/Examples/test-suite/python/disown_runme.py b/trunk/Examples/test-suite/python/disown_runme.py
new file mode 100644
index 0000000..b8cae07
--- /dev/null
+++ b/trunk/Examples/test-suite/python/disown_runme.py
@@ -0,0 +1,25 @@
+from disown import *
+
+a = A()
+
+tmp = a.thisown
+
+a.thisown = 0
+if a.thisown:
+    raise RuntimeError
+
+a.thisown = 1
+if (not a.thisown):
+    raise RuntimeError
+
+a.thisown = tmp
+if (a.thisown != tmp):
+    raise RuntimeError    
+
+
+b = B()
+
+b.acquire(a)
+
+if a.thisown:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/dynamic_cast_runme.py b/trunk/Examples/test-suite/python/dynamic_cast_runme.py
new file mode 100644
index 0000000..68b06db
--- /dev/null
+++ b/trunk/Examples/test-suite/python/dynamic_cast_runme.py
@@ -0,0 +1,12 @@
+import dynamic_cast
+
+f = dynamic_cast.Foo()
+b = dynamic_cast.Bar()
+
+x = f.blah()
+y = b.blah()
+
+a = dynamic_cast.do_test(y)
+if a != "Bar::test":
+    print "Failed!!"
+    
diff --git a/trunk/Examples/test-suite/python/empty_runme.py b/trunk/Examples/test-suite/python/empty_runme.py
new file mode 100644
index 0000000..7de5d15
--- /dev/null
+++ b/trunk/Examples/test-suite/python/empty_runme.py
@@ -0,0 +1 @@
+import empty
diff --git a/trunk/Examples/test-suite/python/enum_template_runme.py b/trunk/Examples/test-suite/python/enum_template_runme.py
new file mode 100644
index 0000000..6ad0a80
--- /dev/null
+++ b/trunk/Examples/test-suite/python/enum_template_runme.py
@@ -0,0 +1,7 @@
+import enum_template
+if enum_template.MakeETest() != 1:
+  raise RuntimeError
+
+if enum_template.TakeETest(0) != None:
+  raise RuntimeError
+  
diff --git a/trunk/Examples/test-suite/python/enums_runme.py b/trunk/Examples/test-suite/python/enums_runme.py
new file mode 100644
index 0000000..59a9829
--- /dev/null
+++ b/trunk/Examples/test-suite/python/enums_runme.py
@@ -0,0 +1,7 @@
+
+import _enums
+
+_enums.bar2(1)
+_enums.bar3(1)
+_enums.bar1(1)
+
diff --git a/trunk/Examples/test-suite/python/exception_order_runme.py b/trunk/Examples/test-suite/python/exception_order_runme.py
new file mode 100644
index 0000000..0b0b1c0
--- /dev/null
+++ b/trunk/Examples/test-suite/python/exception_order_runme.py
@@ -0,0 +1,41 @@
+from exception_order import *
+
+
+a = A()
+
+try:
+  a.foo()
+except E1,e:
+  pass
+except:
+  raise RuntimeError, "bad exception order"
+
+try:
+  a.bar()
+except E2,e:
+  pass
+except:
+  raise RuntimeError, "bad exception order"
+
+try:
+  a.foobar()
+except RuntimeError,e:
+  if e.args[0] != "postcatch unknown":
+    print "bad exception order", 
+    raise RuntimeError, e.args
+
+
+
+try:
+  a.barfoo(1)
+except E1,e:
+  pass
+except:
+  raise RuntimeError, "bad exception order"
+
+try:
+  a.barfoo(2)
+except E2,e:
+  pass
+except:
+  raise RuntimeError, "bad exception order"
diff --git a/trunk/Examples/test-suite/python/extend_placement_runme.py b/trunk/Examples/test-suite/python/extend_placement_runme.py
new file mode 100644
index 0000000..97b7b16
--- /dev/null
+++ b/trunk/Examples/test-suite/python/extend_placement_runme.py
@@ -0,0 +1,46 @@
+import extend_placement
+
+foo = extend_placement.Foo()
+foo = extend_placement.Foo(1)
+foo = extend_placement.Foo(1,1)
+foo.spam()
+foo.spam("hello")
+foo.spam(1)
+foo.spam(1,1)
+foo.spam(1,1,1)
+foo.spam(extend_placement.Foo())
+foo.spam(extend_placement.Foo(), 1.0)
+
+
+bar = extend_placement.Bar()
+bar = extend_placement.Bar(1)
+bar.spam()
+bar.spam("hello")
+bar.spam(1)
+bar.spam(1,1)
+bar.spam(1,1,1)
+bar.spam(extend_placement.Bar())
+bar.spam(extend_placement.Bar(), 1.0)
+
+
+foo = extend_placement.FooTi()
+foo = extend_placement.FooTi(1)
+foo = extend_placement.FooTi(1,1)
+foo.spam()
+foo.spam("hello")
+foo.spam(1)
+foo.spam(1,1)
+foo.spam(1,1,1)
+foo.spam(extend_placement.Foo())
+foo.spam(extend_placement.Foo(), 1.0)
+
+
+bar = extend_placement.BarTi()
+bar = extend_placement.BarTi(1)
+bar.spam()
+bar.spam("hello")
+bar.spam(1)
+bar.spam(1,1)
+bar.spam(1,1,1)
+bar.spam(extend_placement.Bar())
+bar.spam(extend_placement.Bar(), 1.0)
diff --git a/trunk/Examples/test-suite/python/extend_template_ns_runme.py b/trunk/Examples/test-suite/python/extend_template_ns_runme.py
new file mode 100644
index 0000000..5c5feac
--- /dev/null
+++ b/trunk/Examples/test-suite/python/extend_template_ns_runme.py
@@ -0,0 +1,7 @@
+from extend_template_ns import *
+f = Foo_One()
+if f.test1(37) != 37:
+    raise RuntimeError
+
+if f.test2(42) != 42:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/extend_template_runme.py b/trunk/Examples/test-suite/python/extend_template_runme.py
new file mode 100644
index 0000000..be6e2fc
--- /dev/null
+++ b/trunk/Examples/test-suite/python/extend_template_runme.py
@@ -0,0 +1,8 @@
+import extend_template
+
+f = extend_template.Foo_0()
+if f.test1(37) != 37:
+    raise RuntimeError
+
+if f.test2(42) != 42:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/extend_variable_runme.py b/trunk/Examples/test-suite/python/extend_variable_runme.py
new file mode 100644
index 0000000..6a6628c
--- /dev/null
+++ b/trunk/Examples/test-suite/python/extend_variable_runme.py
@@ -0,0 +1,4 @@
+from extend_variable import *
+
+if Foo.Bar != 42:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/file_test_runme.py b/trunk/Examples/test-suite/python/file_test_runme.py
new file mode 100644
index 0000000..64154c6
--- /dev/null
+++ b/trunk/Examples/test-suite/python/file_test_runme.py
@@ -0,0 +1,9 @@
+import sys
+import file_test
+
+file_test.nfile(sys.stdout)
+
+cstdout = file_test.GetStdOut()
+
+file_test.nfile(cstdout)
+file_test.nfile_name("test.dat")
diff --git a/trunk/Examples/test-suite/python/friends_runme.py b/trunk/Examples/test-suite/python/friends_runme.py
new file mode 100644
index 0000000..0489765
--- /dev/null
+++ b/trunk/Examples/test-suite/python/friends_runme.py
@@ -0,0 +1,28 @@
+import friends
+
+a = friends.A(2)
+
+if friends.get_val1(a) != 2: raise RuntimeError
+if friends.get_val2(a) != 4: raise RuntimeError
+if friends.get_val3(a) != 6: raise RuntimeError
+
+# nice overload working fine
+if friends.get_val1(1,2,3) != 1: raise RuntimeError
+
+b = friends.B(3)
+
+# David's case
+if friends.mix(a,b) != 5: raise RuntimeError
+
+di = friends.D_d(2)
+dd = friends.D_d(3.3)
+
+# incredible template overloading working just fine
+if friends.get_val1(di) != 2: raise RuntimeError
+if friends.get_val1(dd) != 3.3: raise RuntimeError
+
+friends.set(di, 4)
+friends.set(dd, 1.3)
+
+if friends.get_val1(di) != 4: raise RuntimeError
+if friends.get_val1(dd) != 1.3: raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/fvirtual_runme.py b/trunk/Examples/test-suite/python/fvirtual_runme.py
new file mode 100644
index 0000000..ada3313
--- /dev/null
+++ b/trunk/Examples/test-suite/python/fvirtual_runme.py
@@ -0,0 +1,9 @@
+from fvirtual import *
+
+sw = NodeSwitch()
+n = Node()
+i = sw.addChild(n);
+
+if i != 2:
+  raise RuntimeError, "addChild"
+
diff --git a/trunk/Examples/test-suite/python/global_ns_arg_runme.py b/trunk/Examples/test-suite/python/global_ns_arg_runme.py
new file mode 100644
index 0000000..e597db5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/global_ns_arg_runme.py
@@ -0,0 +1,5 @@
+from global_ns_arg import *
+
+a = foo(1)
+b = bar()
+
diff --git a/trunk/Examples/test-suite/python/grouping_runme.py b/trunk/Examples/test-suite/python/grouping_runme.py
new file mode 100644
index 0000000..13f8c8c
--- /dev/null
+++ b/trunk/Examples/test-suite/python/grouping_runme.py
@@ -0,0 +1,13 @@
+import grouping
+
+x = grouping.test1(42)
+if x != 42:
+    raise RuntimeError
+
+grouping.test2(42)
+
+x = grouping.do_unary(37, grouping.NEGATE)
+if x != -37:
+    raise RuntimeError
+
+grouping.cvar.test3 = 42
diff --git a/trunk/Examples/test-suite/python/hugemod.pl b/trunk/Examples/test-suite/python/hugemod.pl
new file mode 100644
index 0000000..15c4ce4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/hugemod.pl
@@ -0,0 +1,51 @@
+#!/usr/bin/perl
+
+use strict;
+
+open HEADER, ">hugemod.h" or die "error";
+open TEST, ">hugemod_runme.py" or die "error";
+open I1, ">hugemod_a.i" or die "error";
+open I2, ">hugemod_b.i" or die "error";
+
+print TEST "import hugemod_a\n";
+print TEST "import hugemod_b\n";
+
+print I1 "\%module hugemod_a;\n";
+print I1 "\%include \"hugemod.h\";\n";
+print I1 "\%{ #include \"hugemod.h\" \%}\n";
+
+print I2 "\%module hugemod_b;\n";
+print I2 "\%import \"hugemod.h\";\n";
+print I2 "\%{ #include \"hugemod.h\" \%}\n";
+print I2 "\%inline \%{\n";
+
+my $i;
+
+for ($i = 0; $i < 6000; $i++) {
+  my $t = $i * 4;
+  print HEADER "class type$i { public: int a; };\n";
+  print I2 "class dtype$i : public type$i { public: int b; };\n";
+  
+  print TEST "c = hugemod_a.type$i()\n";
+  print TEST "c.a = $t\n";
+  print TEST "if c.a != $t:\n";
+  print TEST "    raise RuntimeError\n";
+
+  print TEST "c = hugemod_b.dtype$i()\n";
+  print TEST "c.a = $t\n";
+  print TEST "if c.a != $t:\n";
+  print TEST "    raise RuntimeError\n";
+  
+  $t = -$t;
+  
+  print TEST "c.b = $t\n";
+  print TEST "if c.b != $t:\n";
+  print TEST "    raise RuntimeError\n\n";
+}
+
+print I2 "\%}\n";
+
+close HEADER;
+close TEST;
+close I1;
+close I2;
diff --git a/trunk/Examples/test-suite/python/iadd.h b/trunk/Examples/test-suite/python/iadd.h
new file mode 100644
index 0000000..367eda2
--- /dev/null
+++ b/trunk/Examples/test-suite/python/iadd.h
@@ -0,0 +1,47 @@
+struct B {
+	int x;
+	B(const int x) : x(x) {}
+	
+        B& get_me() 
+        {
+		return *this;
+        }
+  
+	B& operator+=(const B& a) {
+		x += a.x;
+		return *this;
+	}
+};
+
+
+
+namespace test { 
+
+struct A {
+	int x;
+	A(const int x) : x(x) {}
+	
+        A& get_me() 
+        {
+		return *this;
+        }
+  
+	A operator+=(const A& a) {
+		x += a.x;
+		return *this;
+	}
+};
+
+
+class Foo {
+public: 
+	Foo(): _a(new A(5)), _n(new long) {}
+	~Foo() { delete _a; delete _n; _a = NULL; _n = NULL; }
+
+	A & AsA() const { return *_a; }
+	long& AsLong() const { return *_n; }
+private: 
+	A *_a;
+	long *_n;
+};
+}
diff --git a/trunk/Examples/test-suite/python/iadd.i b/trunk/Examples/test-suite/python/iadd.i
new file mode 100644
index 0000000..76604c0
--- /dev/null
+++ b/trunk/Examples/test-suite/python/iadd.i
@@ -0,0 +1,12 @@
+%module iadd
+
+%include attribute.i
+%{
+#include "iadd.h"
+%} 
+class Foo; 
+%attribute_ref(test::Foo, test::A& , AsA);
+%attribute_ref(test::Foo, long, AsLong);
+
+
+%include "iadd.h"
diff --git a/trunk/Examples/test-suite/python/iadd_runme.py b/trunk/Examples/test-suite/python/iadd_runme.py
new file mode 100755
index 0000000..fbeb0ec
--- /dev/null
+++ b/trunk/Examples/test-suite/python/iadd_runme.py
@@ -0,0 +1,9 @@
+import iadd
+
+f = iadd.Foo()
+
+f.AsA.x = 3
+f.AsA += f.AsA 
+
+if f.AsA.x != 6:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/implicittest.i b/trunk/Examples/test-suite/python/implicittest.i
new file mode 100644
index 0000000..91205aa
--- /dev/null
+++ b/trunk/Examples/test-suite/python/implicittest.i
@@ -0,0 +1,68 @@
+%module(naturalvar="1") implicittest
+
+%implicitconv;
+
+%inline 
+{
+  struct B { };  
+}
+
+%inline 
+{
+  struct A
+  {
+    int ii;
+    A(int i) { ii = 1; }
+    A(double d) { ii = 2; }
+    A(const B& b) { ii = 3; }
+    explicit A(char *s) { ii = 4; }
+
+    int get() const { return ii; }
+    
+  };
+
+  int get(const A& a) { return a.ii; }
+
+  template <class T>
+  struct A_T
+  {
+    int ii;
+    A_T(int i) { ii = 1; }
+    A_T(double d) { ii = 2; }
+    A_T(const B& b) { ii = 3; }
+    explicit A_T(char *s) { ii = 4; }
+
+    int get() const { return ii; }
+    
+  };
+}
+
+%inline 
+{
+  struct Foo 
+  {
+    int ii;
+    Foo(){ ii = 0;}
+    Foo(int){ ii = 1;}
+    Foo(double){ ii = 2;}
+    explicit Foo(char *s){ii = 3;}
+    Foo(const Foo& f){ ii = f.ii;}
+    
+  };
+
+  struct Bar 
+  {
+    int ii;
+    Foo f;
+    Bar() {ii = -1;}
+    Bar(const Foo& ff){ ii = ff.ii;}
+  };
+
+
+  int get_b(const Bar&b) { return b.ii; }
+  
+  Foo foo;
+  
+}
+
+%template(A_int) A_T<int>;
diff --git a/trunk/Examples/test-suite/python/import_nomodule_runme.py b/trunk/Examples/test-suite/python/import_nomodule_runme.py
new file mode 100644
index 0000000..ba0abfd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/import_nomodule_runme.py
@@ -0,0 +1,8 @@
+from import_nomodule import *
+
+f = create_Foo()
+test1(f,42)
+delete_Foo(f)
+
+b = Bar()
+test1(b,37)
diff --git a/trunk/Examples/test-suite/python/imports_runme.py b/trunk/Examples/test-suite/python/imports_runme.py
new file mode 100644
index 0000000..50a3ab5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/imports_runme.py
@@ -0,0 +1,17 @@
+# This is the import runtime testcase.
+
+import imports_b
+import imports_a
+import sys
+
+x = imports_b.B()
+imports_a.A.hello(x)
+
+a = imports_a.A()
+
+c = imports_b.C()
+a1 = c.get_a(c)
+a2 = c.get_a_type(c)
+
+if a1.hello() != a2.hello():
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/inctest_runme.py b/trunk/Examples/test-suite/python/inctest_runme.py
new file mode 100644
index 0000000..e10f454
--- /dev/null
+++ b/trunk/Examples/test-suite/python/inctest_runme.py
@@ -0,0 +1,32 @@
+import inctest
+
+error = 0
+try:
+  a = inctest.A()
+except:
+  print "didn't find A"
+  print "therefore, I didn't include 'testdir/subdir1/hello.i'"
+  error = 1
+pass
+
+
+try:
+  b = inctest.B()
+except:
+  print "didn't find B"
+  print "therefore, I didn't include 'testdir/subdir2/hello.i'"
+  error = 1
+pass
+
+if error == 1:
+  raise RuntimeError
+
+# Check the import in subdirectory worked
+if inctest.importtest1(5) != 15:
+  print "import test 1 failed"
+  raise RuntimeError
+
+if inctest.importtest2("black") != "white":
+  print "import test 2 failed"
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/inherit_missing_runme.py b/trunk/Examples/test-suite/python/inherit_missing_runme.py
new file mode 100644
index 0000000..044c166
--- /dev/null
+++ b/trunk/Examples/test-suite/python/inherit_missing_runme.py
@@ -0,0 +1,19 @@
+import inherit_missing
+
+a = inherit_missing.new_Foo()
+b = inherit_missing.Bar()
+c = inherit_missing.Spam()
+
+x = inherit_missing.do_blah(a)
+if x != "Foo::blah":
+    print "Whoa! Bad return", x
+
+x = inherit_missing.do_blah(b)
+if x != "Bar::blah":
+    print "Whoa! Bad return", x
+
+x = inherit_missing.do_blah(c)
+if x != "Spam::blah":
+    print "Whoa! Bad return", x
+
+inherit_missing.delete_Foo(a)
diff --git a/trunk/Examples/test-suite/python/inout.i b/trunk/Examples/test-suite/python/inout.i
new file mode 100644
index 0000000..dc6db0e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/inout.i
@@ -0,0 +1,48 @@
+%module inout
+
+%include "typemaps.i"
+%include "std_pair.i"
+
+%{
+  inline void AddOne3(double* a, double* b, double* c) {
+    *a += 1;
+    *b += 1;
+    *c += 1;
+  }
+
+  inline void AddOne1(double* a) {
+    *a += 1;
+  } 
+
+  inline void AddOne1p(std::pair<double, double>* p) {
+    p->first += 1;
+    p->second += 1;
+  } 
+
+  inline void AddOne2p(std::pair<double, double>* p,double* a) {
+    *a += 1;
+    p->first += 1;
+    p->second += 1;
+  } 
+
+  inline void AddOne3p(double* a, std::pair<double, double>* p,double* b) {
+    *a += 1;
+    *b += 1;
+    p->first += 1;
+    p->second += 1;
+  } 
+
+  inline void AddOne1r(double& a) {
+    a += 1;
+  } 
+
+%}
+
+%template() std::pair<double, double>;
+
+void AddOne1(double* INOUT);
+void AddOne3(double* INOUT, double* INOUT, double* INOUT);
+void AddOne1p(std::pair<double, double>* INOUT);
+void AddOne2p(std::pair<double, double>* INOUT, double* INOUT);
+void AddOne3p(double* INOUT, std::pair<double, double>* INOUT, double* INOUT);
+void AddOne1r(double& INOUT);
diff --git a/trunk/Examples/test-suite/python/inout_runme.py b/trunk/Examples/test-suite/python/inout_runme.py
new file mode 100644
index 0000000..fb290f6
--- /dev/null
+++ b/trunk/Examples/test-suite/python/inout_runme.py
@@ -0,0 +1,22 @@
+import inout
+
+a = inout.AddOne1(1)
+if a != 2:
+  raise RuntimeError
+
+a = inout.AddOne3(1,1,1)
+if a != [2,2,2]:
+  raise RuntimeError
+
+a = inout.AddOne1p((1,1))
+if a != (2,2):
+  raise RuntimeError
+
+a = inout.AddOne2p((1,1),1)
+if a != [(2,2),2]:
+  raise RuntimeError
+
+a = inout.AddOne3p(1,(1,1),1)
+if a != [2,(2,2),2]:
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/inplaceadd.i b/trunk/Examples/test-suite/python/inplaceadd.i
new file mode 100644
index 0000000..91ef84b
--- /dev/null
+++ b/trunk/Examples/test-suite/python/inplaceadd.i
@@ -0,0 +1,40 @@
+%module inplaceadd
+%{
+#include <iostream>
+%}
+
+
+%inline %{
+  struct A 
+  {
+    int val;
+    
+    A(int v): val(v)
+    {
+    }
+    
+    A& operator+=(int v) 
+    {
+      val += v;
+      return *this;
+    }
+
+    A& operator+=(const A& a) 
+    {
+      val += a.val;
+      return *this;
+    }
+
+    A& operator-=(int v) 
+    {
+      val -= v;
+      return *this;
+    }
+
+    A& operator*=(int v) 
+    {
+      val *= v;
+      return *this;
+    }
+  };
+%}
diff --git a/trunk/Examples/test-suite/python/inplaceadd_runme.py b/trunk/Examples/test-suite/python/inplaceadd_runme.py
new file mode 100644
index 0000000..b703c56
--- /dev/null
+++ b/trunk/Examples/test-suite/python/inplaceadd_runme.py
@@ -0,0 +1,20 @@
+import inplaceadd
+a = inplaceadd.A(7)
+
+a += 5
+if a.val != 12:
+  print a.val
+  raise RuntimeError
+
+a -= 5
+if a.val != 7:
+  raise RuntimeError
+
+a *= 2
+
+if a.val != 14:
+  raise RuntimeError
+
+a += a
+if a.val != 28:
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/input.i b/trunk/Examples/test-suite/python/input.i
new file mode 100644
index 0000000..6cef3f9
--- /dev/null
+++ b/trunk/Examples/test-suite/python/input.i
@@ -0,0 +1,41 @@
+%module input
+
+%apply int *INPUT {int *bar};
+
+%typemap(out, fragment=SWIG_From_frag(int)) int *foo {
+  if ($1) {
+    $result = SWIG_From(int)(*$1);
+  } else {
+    $result = SWIG_Py_Void();
+  }
+}
+
+%inline 
+{
+  struct Foo {
+    int *foo(int *bar = 0) {
+      if (bar) {
+	*bar *= 2;
+      }
+      return (bar) ? bar : 0;
+    }
+  };
+}
+
+%include std_string.i
+%apply std::string *INPUT {std::string *bar};
+
+%typemap(out, fragment=SWIG_From_frag(std::string)) std::string *sfoo {
+  if ($1) {
+    $result = SWIG_From(std::string)(*$1);
+  } else {
+    $result = SWIG_Py_Void();
+  }
+}
+
+%inline %{
+  std::string *sfoo(std::string *bar = 0) {
+    if (bar) *bar += " world";
+    return (bar) ? bar : 0;
+  }
+%}
diff --git a/trunk/Examples/test-suite/python/input_runme.py b/trunk/Examples/test-suite/python/input_runme.py
new file mode 100644
index 0000000..f5ef6dc
--- /dev/null
+++ b/trunk/Examples/test-suite/python/input_runme.py
@@ -0,0 +1,20 @@
+from input import *
+
+f = Foo()
+if f.foo(2) != 4:
+  raise RuntimeError
+  
+if f.foo(None)!= None:
+  raise RuntimeError
+
+if f.foo()!= None:
+  raise RuntimeError
+
+if sfoo("Hello") != "Hello world":
+  raise RuntimeError
+
+if sfoo(None) != None:
+  raise RuntimeError
+
+if sfoo() != None:
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/keyword_rename_runme.py b/trunk/Examples/test-suite/python/keyword_rename_runme.py
new file mode 100644
index 0000000..5646ce7
--- /dev/null
+++ b/trunk/Examples/test-suite/python/keyword_rename_runme.py
@@ -0,0 +1,4 @@
+#!/usr/bin/env python
+import keyword_rename
+keyword_rename._in(1)
+keyword_rename._except(1)
diff --git a/trunk/Examples/test-suite/python/kwargs.i b/trunk/Examples/test-suite/python/kwargs.i
new file mode 100644
index 0000000..83713d8
--- /dev/null
+++ b/trunk/Examples/test-suite/python/kwargs.i
@@ -0,0 +1,112 @@
+%module kwargs
+
+%nocopyctor;
+%kwargs;
+
+%rename(myDel) del;
+%inline 
+{
+  struct s { int del; };
+}
+
+
+// Simple class
+%extend Foo 
+{
+  int efoo(int a = 1, int b = 0) {return a + b; }
+  static int sfoo(int a = 1, int b = 0) { return a + b; }
+}
+
+%newobject Foo::create;
+
+%inline %{
+
+  struct Foo 
+  {
+    Foo(int a, int b = 0) {}
+
+    virtual int foo(int a = 1, int b = 0) {return a + b; }
+    static int statfoo(int a = 1, int b = 0) {return a + b; }
+
+    static Foo *create(int a = 1, int b = 0) 
+    {
+      return new Foo(a, b);
+    }
+
+    virtual ~Foo() {
+    }
+    
+  };
+
+%}
+
+
+// Templated class
+%extend Bar 
+{
+  T ebar(T a = 1, T b = 0) {return a + b; }
+  static T sbar(T a = 1, T b = 0) { return a + b; }
+}
+
+%inline %{
+  template <typename T> struct Bar 
+  {
+    Bar(T a, T b = 0){}
+
+    T bar(T a = 1, T b = 0) {return a + b; }
+    static T statbar(T a = 1, T b = 0) {return a + b; }
+  };
+
+%}
+
+%template(BarInt) Bar<int>;
+
+
+// Functions
+%inline %{
+  int foo(int a = 1, int b = 0) {return a + b; }
+
+  
+  template<typename T> T templatedfunction(T a = 1, T b = 0) { return a + b; }
+%}
+
+%template(templatedfunction) templatedfunction<int>;
+
+
+// Deafult args with references
+%inline
+%{
+
+  typedef int size_type;
+  
+  struct Hello 
+  {
+    static const size_type hello = 3;
+  };
+  
+  
+  
+  int rfoo( const size_type& x = Hello::hello, const Hello& y = Hello() )
+  {
+    return x;
+  }
+  
+%}
+%{
+  const int Hello::hello;
+%}
+  
+
+// Functions with keywords
+%warnfilter(SWIGWARN_PARSE_KEYWORD);
+%inline %{
+  /* silently rename the parameter names in python */
+
+  int foo_kw(int from = 1, int except = 2) {return from + except; }
+
+
+  int foo_nu(int from = 1, int = 0) {return from; }
+
+  int foo_mm(int min = 1, int max = 2) {return min + max; }
+
+%}
diff --git a/trunk/Examples/test-suite/python/kwargs_runme.py b/trunk/Examples/test-suite/python/kwargs_runme.py
new file mode 100644
index 0000000..9181292
--- /dev/null
+++ b/trunk/Examples/test-suite/python/kwargs_runme.py
@@ -0,0 +1,67 @@
+from kwargs import *
+
+class MyFoo(Foo):
+  def __init__(self, a , b = 0):
+    Foo.__init__(self, a, b)
+
+    
+
+# Simple class
+f1 = MyFoo(2)
+
+f = Foo(b=2,a=1)
+
+if f.foo(b=1,a=2) != 3:
+  raise RuntimeError
+
+if Foo_statfoo(b=2) != 3:
+  raise RuntimeError
+
+if f.efoo(b=2) != 3:
+  raise RuntimeError
+
+if Foo_sfoo(b=2) != 3:
+  raise RuntimeError
+
+
+# Templated class
+b = BarInt(b=2,a=1)
+
+if b.bar(b=1,a=2) != 3:
+  raise RuntimeError
+
+if BarInt_statbar(b=2) != 3:
+  raise RuntimeError
+
+if b.ebar(b=2) != 3:
+  raise RuntimeError
+
+if BarInt_sbar(b=2) != 3:
+  raise RuntimeError
+
+
+# Functions
+if templatedfunction(b=2) != 3:
+  raise RuntimeError
+
+if foo(a=1,b=2) != 3:
+  raise RuntimeError
+
+if foo(b=2) != 3:
+  raise RuntimeError
+
+
+#Funtions with keywords
+
+if foo_kw(_from=2) != 4:
+  raise RuntimeError
+
+if foo_nu(_from=2, arg2=3) != 2:
+  raise RuntimeError
+
+if foo_mm(min=2) != 4:
+  raise RuntimeError
+
+if foo_mm(max=3) != 4:
+  raise RuntimeError
+  
diff --git a/trunk/Examples/test-suite/python/langobj_runme.py b/trunk/Examples/test-suite/python/langobj_runme.py
new file mode 100644
index 0000000..c10e193
--- /dev/null
+++ b/trunk/Examples/test-suite/python/langobj_runme.py
@@ -0,0 +1,13 @@
+import sys
+from langobj import *
+
+
+x ="hello"
+rx = sys.getrefcount(x)
+v = identity(x)
+rv = sys.getrefcount(v)
+if v != x:
+    raise RuntimeError
+
+if rv - rx != 1:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_attribute_runme.py b/trunk/Examples/test-suite/python/li_attribute_runme.py
new file mode 100644
index 0000000..5eeec29
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_attribute_runme.py
@@ -0,0 +1,52 @@
+import li_attribute
+
+aa = li_attribute.A(1,2,3)
+
+if aa.a != 1:
+  raise RuntimeError
+aa.a = 3
+if aa.a != 3:
+  print aa.a
+  raise RuntimeError
+
+
+if aa.b != 2:
+  print aa.b
+  raise RuntimeError
+aa.b = 5
+if aa.b != 5:
+  raise RuntimeError
+
+
+
+if aa.d != aa.b:
+  raise RuntimeError
+
+if aa.c != 3:
+  raise RuntimeError
+#aa.c = 5
+#if aa.c != 3:
+#  raise RuntimeError
+
+pi = li_attribute.Param_i(7)
+if pi.value != 7:
+ raise RuntimeError
+
+pi.value=3
+if pi.value != 3:
+ raise RuntimeError
+
+
+b = li_attribute.B(aa)
+
+if b.a.c != 3:
+ raise RuntimeError
+  
+
+myFoo = li_attribute.MyFoo
+myFoo.x = 8
+myClass = li_attribute.MyClass
+myClass.Foo = myFoo
+if myClass.Foo.x != 8:
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py b/trunk/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py
new file mode 100644
index 0000000..c6bd2f9
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py
@@ -0,0 +1,20 @@
+from li_boost_shared_ptr_bits import *
+
+def check(nd):
+  nd.i = 200
+  i = nd.i
+
+  try:
+    nd.notexist = 100
+    passed = 0
+  except:
+    passed = 1
+
+  if not passed:
+    raise "Test failed"
+
+nd = NonDynamic()
+check(nd)
+b = boing(nd)
+check(b)
+
diff --git a/trunk/Examples/test-suite/python/li_boost_shared_ptr_runme.py b/trunk/Examples/test-suite/python/li_boost_shared_ptr_runme.py
new file mode 100644
index 0000000..5f6cbd2
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_boost_shared_ptr_runme.py
@@ -0,0 +1,535 @@
+import li_boost_shared_ptr
+import gc
+
+debug = False
+
+# simple shared_ptr usage - created in C++
+class li_boost_shared_ptr_runme:
+  def main(self):
+    if (debug):
+      print "Started"
+
+    li_boost_shared_ptr.cvar.debug_shared = debug
+
+    # Change loop count to run for a long time to monitor memory
+    loopCount = 1 #5000
+    for i in range (0,loopCount):
+      self.runtest()
+
+    # Expect 1 instance - the one global variable (GlobalValue)
+    if (li_boost_shared_ptr.Klass.getTotal_count() != 1):
+      raise RuntimeError("Klass.total_count=%s" % li_boost_shared_ptr.Klass.getTotal_count())
+
+    wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count() 
+    if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING):
+      # Expect 1 instance - the one global variable (GlobalSmartValue)
+      if (wrapper_count != 1):
+        raise RuntimeError("shared_ptr wrapper count=%s" % wrapper_count)
+
+    if (debug):
+      print "Finished"
+
+  def runtest(self):
+    # simple shared_ptr usage - created in C++
+    k = li_boost_shared_ptr.Klass("me oh my")
+    val = k.getValue()
+    self.verifyValue("me oh my", val)
+    self.verifyCount(1, k)
+
+    # simple shared_ptr usage - not created in C++
+    k = li_boost_shared_ptr.factorycreate()
+    val = k.getValue()
+    self.verifyValue("factorycreate", val)
+    self.verifyCount(1, k)
+
+    # pass by shared_ptr
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.smartpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointertest", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by shared_ptr pointer
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.smartpointerpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointerpointertest", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by shared_ptr reference
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.smartpointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointerreftest", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by shared_ptr pointer reference
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.smartpointerpointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointerpointerreftest", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # const pass by shared_ptr
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.constsmartpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # const pass by shared_ptr pointer
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.constsmartpointerpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # const pass by shared_ptr reference
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.constsmartpointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by value
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.valuetest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my valuetest", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # pass by pointer
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.pointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my pointertest", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # pass by reference
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.reftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my reftest", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # pass by pointer reference
+    k = li_boost_shared_ptr.Klass("me oh my")
+    kret = li_boost_shared_ptr.pointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my pointerreftest", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # null tests
+    k = None
+
+    if (li_boost_shared_ptr.smartpointertest(k) != None):
+      raise RuntimeError("return was not null")
+
+    if (li_boost_shared_ptr.smartpointerpointertest(k) != None):
+      raise RuntimeError("return was not null")
+
+    if (li_boost_shared_ptr.smartpointerreftest(k) != None):
+      raise RuntimeError("return was not null")
+
+    if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None):
+      raise RuntimeError("return was not null")
+
+    if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer"):
+      raise RuntimeError("not null smartpointer pointer")
+
+    try:
+      li_boost_shared_ptr.valuetest(k)
+      raise RuntimeError("Failed to catch null pointer")
+    except ValueError:
+      pass
+
+    if (li_boost_shared_ptr.pointertest(k) != None):
+      raise RuntimeError("return was not null")
+
+    try:
+      li_boost_shared_ptr.reftest(k)
+      raise RuntimeError("Failed to catch null pointer")
+    except ValueError:
+      pass
+
+    # $owner
+    k = li_boost_shared_ptr.pointerownertest()
+    val = k.getValue()
+    self.verifyValue("pointerownertest", val)
+    self.verifyCount(1, k)
+    k = li_boost_shared_ptr.smartpointerpointerownertest()
+    val = k.getValue()
+    self.verifyValue("smartpointerpointerownertest", val)
+    self.verifyCount(1, k)
+
+    # //////////////////////////////// Derived class ////////////////////////////////////////
+    # derived pass by shared_ptr
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.derivedsmartptrtest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my derivedsmartptrtest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # derived pass by shared_ptr pointer
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.derivedsmartptrpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # derived pass by shared_ptr ref
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.derivedsmartptrreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my derivedsmartptrreftest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # derived pass by shared_ptr pointer ref
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # derived pass by pointer
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.derivedpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my derivedpointertest-Derived", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # derived pass by ref
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.derivedreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my derivedreftest-Derived", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # //////////////////////////////// Derived and base class mixed ////////////////////////////////////////
+    # pass by shared_ptr (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.smartpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointertest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by shared_ptr pointer (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.smartpointerpointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointerpointertest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by shared_ptr reference (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.smartpointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointerreftest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by shared_ptr pointer reference (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.smartpointerpointerreftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my smartpointerpointerreftest-Derived", val)
+    self.verifyCount(2, k)
+    self.verifyCount(2, kret)
+
+    # pass by value (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.valuetest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my valuetest", val) # note slicing
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # pass by pointer (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.pointertest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my pointertest-Derived", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # pass by ref (mixed)
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    kret = li_boost_shared_ptr.reftest(k)
+    val = kret.getValue()
+    self.verifyValue("me oh my reftest-Derived", val)
+    self.verifyCount(1, k)
+    self.verifyCount(1, kret)
+
+    # //////////////////////////////// Overloading tests ////////////////////////////////////////
+    # Base class
+    k = li_boost_shared_ptr.Klass("me oh my")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref")
+
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval")
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref")
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr")
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref")
+
+    # Derived class
+    k = li_boost_shared_ptr.KlassDerived("me oh my")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr")
+    self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref")
+
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval")
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref")
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr")
+    self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref")
+
+    # //////////////////////////////// Member variables ////////////////////////////////////////
+    # smart pointer by value
+    m = li_boost_shared_ptr.MemberVariables()
+    k = li_boost_shared_ptr.Klass("smart member value")
+    m.SmartMemberValue = k
+    val = k.getValue()
+    self.verifyValue("smart member value", val)
+    self.verifyCount(2, k)
+
+    kmember = m.SmartMemberValue
+    val = kmember.getValue()
+    self.verifyValue("smart member value", val)
+    self.verifyCount(3, kmember)
+    self.verifyCount(3, k)
+
+    del m
+    self.verifyCount(2, kmember)
+    self.verifyCount(2, k)
+
+    # smart pointer by pointer
+    m = li_boost_shared_ptr.MemberVariables()
+    k = li_boost_shared_ptr.Klass("smart member pointer")
+    m.SmartMemberPointer = k
+    val = k.getValue()
+    self.verifyValue("smart member pointer", val)
+    self.verifyCount(1, k)
+
+    kmember = m.SmartMemberPointer
+    val = kmember.getValue()
+    self.verifyValue("smart member pointer", val)
+    self.verifyCount(2, kmember)
+    self.verifyCount(2, k)
+
+    del m
+    self.verifyCount(2, kmember)
+    self.verifyCount(2, k)
+
+    # smart pointer by reference
+    m = li_boost_shared_ptr.MemberVariables()
+    k = li_boost_shared_ptr.Klass("smart member reference")
+    m.SmartMemberReference = k
+    val = k.getValue()
+    self.verifyValue("smart member reference", val)
+    self.verifyCount(2, k)
+
+    kmember = m.SmartMemberReference
+    val = kmember.getValue()
+    self.verifyValue("smart member reference", val)
+    self.verifyCount(3, kmember)
+    self.verifyCount(3, k)
+
+    # The C++ reference refers to SmartMemberValue...
+    kmemberVal = m.SmartMemberValue
+    val = kmember.getValue()
+    self.verifyValue("smart member reference", val)
+    self.verifyCount(4, kmemberVal)
+    self.verifyCount(4, kmember)
+    self.verifyCount(4, k)
+
+    del m
+    self.verifyCount(3, kmemberVal)
+    self.verifyCount(3, kmember)
+    self.verifyCount(3, k)
+
+    # plain by value
+    m = li_boost_shared_ptr.MemberVariables()
+    k = li_boost_shared_ptr.Klass("plain member value")
+    m.MemberValue = k
+    val = k.getValue()
+    self.verifyValue("plain member value", val)
+    self.verifyCount(1, k)
+
+    kmember = m.MemberValue
+    val = kmember.getValue()
+    self.verifyValue("plain member value", val)
+    self.verifyCount(1, kmember)
+    self.verifyCount(1, k)
+
+    del m
+    self.verifyCount(1, kmember)
+    self.verifyCount(1, k)
+
+    # plain by pointer
+    m = li_boost_shared_ptr.MemberVariables()
+    k = li_boost_shared_ptr.Klass("plain member pointer")
+    m.MemberPointer = k
+    val = k.getValue()
+    self.verifyValue("plain member pointer", val)
+    self.verifyCount(1, k)
+
+    kmember = m.MemberPointer
+    val = kmember.getValue()
+    self.verifyValue("plain member pointer", val)
+    self.verifyCount(1, kmember)
+    self.verifyCount(1, k)
+
+    del m
+    self.verifyCount(1, kmember)
+    self.verifyCount(1, k)
+
+    # plain by reference
+    m = li_boost_shared_ptr.MemberVariables()
+    k = li_boost_shared_ptr.Klass("plain member reference")
+    m.MemberReference = k
+    val = k.getValue()
+    self.verifyValue("plain member reference", val)
+    self.verifyCount(1, k)
+
+    kmember = m.MemberReference
+    val = kmember.getValue()
+    self.verifyValue("plain member reference", val)
+    self.verifyCount(1, kmember)
+    self.verifyCount(1, k)
+
+    del m
+    self.verifyCount(1, kmember)
+    self.verifyCount(1, k)
+
+    # null member variables
+    m = li_boost_shared_ptr.MemberVariables()
+
+    # shared_ptr by value
+    k = m.SmartMemberValue
+    if (k != None):
+      raise RuntimeError("expected null")
+    m.SmartMemberValue = None
+    k = m.SmartMemberValue
+    if (k != None):
+      raise RuntimeError("expected null")
+    self.verifyCount(0, k)
+
+    # plain by value
+    try:
+      m.MemberValue = None
+      raise RuntimeError("Failed to catch null pointer")
+    except ValueError:
+      pass
+
+    # ////////////////////////////////// Global variables ////////////////////////////////////////
+    # smart pointer
+    kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue
+    if (kglobal != None):
+      raise RuntimeError("expected null")
+
+    k = li_boost_shared_ptr.Klass("smart global value")
+    li_boost_shared_ptr.cvar.GlobalSmartValue = k
+    self.verifyCount(2, k)
+
+    kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue
+    val = kglobal.getValue()
+    self.verifyValue("smart global value", val)
+    self.verifyCount(3, kglobal)
+    self.verifyCount(3, k)
+    self.verifyValue("smart global value", li_boost_shared_ptr.cvar.GlobalSmartValue.getValue())
+    li_boost_shared_ptr.cvar.GlobalSmartValue = None
+
+    # plain value
+    k = li_boost_shared_ptr.Klass("global value")
+    li_boost_shared_ptr.cvar.GlobalValue = k
+    self.verifyCount(1, k)
+
+    kglobal = li_boost_shared_ptr.cvar.GlobalValue
+    val = kglobal.getValue()
+    self.verifyValue("global value", val)
+    self.verifyCount(1, kglobal)
+    self.verifyCount(1, k)
+    self.verifyValue("global value", li_boost_shared_ptr.cvar.GlobalValue.getValue())
+
+    try:
+      li_boost_shared_ptr.cvar.GlobalValue = None
+      raise RuntimeError("Failed to catch null pointer")
+    except ValueError:
+      pass
+
+    # plain pointer
+    kglobal = li_boost_shared_ptr.cvar.GlobalPointer
+    if (kglobal != None):
+      raise RuntimeError("expected null")
+
+    k = li_boost_shared_ptr.Klass("global pointer")
+    li_boost_shared_ptr.cvar.GlobalPointer = k
+    self.verifyCount(1, k)
+
+    kglobal = li_boost_shared_ptr.cvar.GlobalPointer
+    val = kglobal.getValue()
+    self.verifyValue("global pointer", val)
+    self.verifyCount(1, kglobal)
+    self.verifyCount(1, k)
+    li_boost_shared_ptr.cvar.GlobalPointer = None
+
+    # plain reference
+    kglobal
+
+    k = li_boost_shared_ptr.Klass("global reference")
+    li_boost_shared_ptr.cvar.GlobalReference = k
+    self.verifyCount(1, k)
+
+    kglobal = li_boost_shared_ptr.cvar.GlobalReference
+    val = kglobal.getValue()
+    self.verifyValue("global reference", val)
+    self.verifyCount(1, kglobal)
+    self.verifyCount(1, k)
+
+    try:
+      li_boost_shared_ptr.cvar.GlobalReference = None 
+      raise RuntimeError("Failed to catch null pointer")
+    except ValueError:
+      pass
+
+    # ////////////////////////////////// Templates ////////////////////////////////////////
+    pid = li_boost_shared_ptr.PairIntDouble(10, 20.2)
+    if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4):
+      raise RuntimeError("Base values wrong")
+    if (pid.val1 != 10 or pid.val2 != 20.2):
+      raise RuntimeError("Derived Values wrong")
+
+  def verifyValue(self, expected, got):
+    if (expected != got):
+      raise RuntimeError("verify value failed. Expected: ", expected, " Got: ", got)
+
+  def verifyCount(self, expected, k):
+    got = li_boost_shared_ptr.use_count(k)
+    if (expected != got):
+      raise RuntimeError("verify use_count failed. Expected: ", expected, " Got: ", got)
+
+
+runme = li_boost_shared_ptr_runme()
+runme.main()
+
diff --git a/trunk/Examples/test-suite/python/li_carrays_runme.py b/trunk/Examples/test-suite/python/li_carrays_runme.py
new file mode 100644
index 0000000..ad48eab
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_carrays_runme.py
@@ -0,0 +1,9 @@
+from li_carrays import *
+
+d = doubleArray(10)
+
+d[0] = 7
+d[5] = d[0] + 3
+
+if d[5] + d[0] != 17:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_cmalloc_runme.py b/trunk/Examples/test-suite/python/li_cmalloc_runme.py
new file mode 100644
index 0000000..9e698ae
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_cmalloc_runme.py
@@ -0,0 +1,14 @@
+from li_cmalloc import *
+
+p = malloc_int()
+free_int(p)
+
+ok = 0
+try:
+    p = calloc_int(-1)
+    free_int(p)
+except:
+    ok = 1
+
+if ok != 1:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_cpointer_runme.py b/trunk/Examples/test-suite/python/li_cpointer_runme.py
new file mode 100644
index 0000000..ac95ff4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_cpointer_runme.py
@@ -0,0 +1,10 @@
+from li_cpointer import *
+
+
+p = new_intp()
+intp_assign(p,3)
+
+if intp_value(p) != 3:
+    raise RuntimeError
+
+delete_intp(p)
diff --git a/trunk/Examples/test-suite/python/li_cstring_runme.py b/trunk/Examples/test-suite/python/li_cstring_runme.py
new file mode 100644
index 0000000..6503744
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_cstring_runme.py
@@ -0,0 +1,32 @@
+from li_cstring import *
+
+
+if count("ab\0ab\0ab\0", 0) != 3:
+    raise RuntimeError    
+
+if test1() != "Hello World":
+    raise RuntimeError
+
+if test2() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_":
+    raise RuntimeError
+
+if test3("hello") != "hello-suffix":
+    print test3("hello")
+    raise RuntimeError
+
+if test4("hello") != "hello-suffix":
+    print test4("hello")
+    raise RuntimeError
+    
+if test5(4) != 'xxxx':
+    raise RuntimeError
+
+if test6(10) != 'xxxxx':
+    raise RuntimeError
+    
+if test7() !="Hello world!":
+    raise RuntimeError
+
+if test8() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_":
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/li_cwstring_runme.py b/trunk/Examples/test-suite/python/li_cwstring_runme.py
new file mode 100644
index 0000000..4ab5908
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_cwstring_runme.py
@@ -0,0 +1,29 @@
+from li_cwstring import *
+
+if count(u"ab\0ab\0ab\0", 0) != 3:
+    raise RuntimeError    
+
+if test1() != u"Hello World":
+    raise RuntimeError
+
+if test2() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_":
+    raise RuntimeError
+
+if test3("hello") != u"hello-suffix":
+    raise RuntimeError
+
+if test4("hello") != u"hello-suffix":
+    raise RuntimeError
+    
+if test5(4) != u'xxxx':
+    raise RuntimeError
+
+if test6(10) != u'xxxxx':
+    raise RuntimeError
+    
+if test7() != u"Hello world!":
+    raise RuntimeError
+
+if test8() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_":
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/li_factory_runme.py b/trunk/Examples/test-suite/python/li_factory_runme.py
new file mode 100644
index 0000000..fb2c81e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_factory_runme.py
@@ -0,0 +1,11 @@
+from li_factory import *
+
+circle = Geometry_create(Geometry.CIRCLE)
+r = circle.radius()
+if (r != 1.5):
+    raise RuntimeError
+
+point = Geometry_create(Geometry.POINT)
+w = point.width()
+if (w != 1.0):
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_implicit_runme.py b/trunk/Examples/test-suite/python/li_implicit_runme.py
new file mode 100644
index 0000000..a0672e0
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_implicit_runme.py
@@ -0,0 +1,17 @@
+from li_implicit import *
+b = B()
+ai = A(1)
+ad = A(2.0)
+ab = A(b)
+
+ai, get(ai)
+ad, get(ad)
+ab, get(ab)
+
+if get(ai) != get(1):
+  raise RuntimeError,"bad implicit type"
+if get(ad) != get(2.0):
+  raise RuntimeError,"bad implicit type"
+if get(ab) != get(b):
+  raise RuntimeError,"bad implicit type"
+
diff --git a/trunk/Examples/test-suite/python/li_std_carray.i b/trunk/Examples/test-suite/python/li_std_carray.i
new file mode 100644
index 0000000..b38e0e4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_carray.i
@@ -0,0 +1,8 @@
+%module li_std_carray
+
+%include <std_carray.i>
+
+%template(Vector3) std::carray<double, 3>;
+
+%template(Matrix3) std::carray<std::carray<double, 3>, 3>;
+
diff --git a/trunk/Examples/test-suite/python/li_std_carray_runme.py b/trunk/Examples/test-suite/python/li_std_carray_runme.py
new file mode 100644
index 0000000..803bc96
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_carray_runme.py
@@ -0,0 +1,41 @@
+from li_std_carray import *
+
+
+v3 = Vector3()
+for i in range(0,len(v3)):
+    v3[i] = i
+
+i = 0
+for d in v3:
+    if d != i:
+        raise RuntimeError
+    i = i + 1
+
+
+m3 = Matrix3()
+
+for i in range(0,len(m3)):
+    v3 = m3[i]
+    for j in range(0,len(v3)):
+        v3[j] = i + j
+
+i = 0
+for v3 in m3:
+    j = 0
+    for d in v3:
+        if d != i + j:
+            raise RuntimeError
+        j = j + 1
+        pass
+    i = i + 1
+    pass
+
+for i in range(0,len(m3)):
+    for j in range(0,len(m3)):
+        if m3[i][j] != i + j:
+            raise RuntimeError
+
+da = Vector3((1,2,3))
+ma = Matrix3(((1,2,3),(4,5,6),(7,8,9)))
+
+
diff --git a/trunk/Examples/test-suite/python/li_std_map.i b/trunk/Examples/test-suite/python/li_std_map.i
new file mode 100644
index 0000000..a8ba4f2
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_map.i
@@ -0,0 +1,58 @@
+%module("templatereduce") li_std_map
+
+%include std_pair.i
+%include std_map.i
+%include std_multimap.i
+
+%inline %{
+struct A{
+    int val;
+    
+    A(int v = 0): val(v)
+    {
+    }
+
+};
+%}
+
+namespace std
+{
+  %template(pairii) pair<int, int>;
+  %template(pairAA) pair<int, A>;
+  %template(pairA) pair<int, A*>;
+  %template(mapA) map<int, A*>;
+  %template(mmapA) multimap<int, A*>;
+
+  %template(paircA1) pair<const int, A*>;
+  %template(paircA2) pair<const int, const A*>;
+  %template(pairiiA) pair<int,pair<int, A*> >;
+  %template(pairiiAc) pair<int,const pair<int, A*> >;
+
+
+  %template() pair<swig::PyObject_ptr, swig::PyObject_ptr>;
+  %template(pymap) map<swig::PyObject_ptr, swig::PyObject_ptr>;
+  
+}
+
+
+
+%inline 
+{
+std::pair<int, A*> 
+p_identa(std::pair<int, A*> p) {
+  return p;
+}
+
+std::map<int,A*> m_identa(const std::map<int,A*>& v)
+{
+  return v;
+}
+
+}
+
+
+
+namespace std
+{
+%template(mapii) map<int,int>;
+}
diff --git a/trunk/Examples/test-suite/python/li_std_map_runme.py b/trunk/Examples/test-suite/python/li_std_map_runme.py
new file mode 100644
index 0000000..461421a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_map_runme.py
@@ -0,0 +1,58 @@
+import li_std_map
+
+a1 = li_std_map.A(3)
+a2 = li_std_map.A(7)
+
+
+p0 = li_std_map.pairii(1,2)
+p1 = li_std_map.pairA(1,a1.this)
+m = {}
+m[1] = a1
+m[2] = a2
+
+pp1 = li_std_map.p_identa(p1)
+mm = li_std_map.m_identa(m)
+
+
+
+m = li_std_map.mapA()
+m[1] = a1
+m[2] = a2
+
+
+pm ={}
+for k in m:
+  pm[k] = m[k]
+
+for k in m:  
+  if pm[k].this != m[k].this:
+    print pm[k], m[k]
+    raise RuntimeError
+
+  
+
+
+
+m = {}
+m[1] = (1,2)
+m["foo"] = "hello"
+
+pm = li_std_map.pymap()
+
+for k in m:  
+  pm[k] = m[k]
+
+for k in pm:  
+  if (pm[k] != m[k]):
+    raise RuntimeError
+
+
+
+mii = li_std_map.mapii()
+
+mii[1] = 1
+mii[1] = 2
+
+if mii[1] != 2:
+  raise RuntimeError
+  
diff --git a/trunk/Examples/test-suite/python/li_std_pair.i b/trunk/Examples/test-suite/python/li_std_pair.i
new file mode 100644
index 0000000..886bf1a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_pair.i
@@ -0,0 +1,210 @@
+%module li_std_pair
+
+//
+// activate the automatic comparison methods generation (==,!=,...) 
+//
+
+%{
+#include <algorithm>                   // for std::swap
+%}
+
+
+%include std_pair.i
+%include std_string.i
+%include std_complex.i
+
+%inline
+%{
+  struct A 
+  {
+    int val;
+    
+    A(int v = 0): val(v)
+    {
+    }
+    
+  };
+  struct B
+  {
+  };
+%}
+
+%std_comp_methods(std::pair<std::string, int>);
+
+namespace std {
+  %template(CIntPair) pair<const int, const int>;
+  %template() pair<double, double>;
+  %template(ShortPair) pair<short, short>;
+
+  %template(IntPair) pair<int, int>;
+  %extend pair<int, int>
+  {
+    %template(pair) pair<short,short>;
+  }
+  
+  
+
+  %template(SIPair) pair<std::string, int>;
+  %template(CIPair) pair<std::complex<double>, int>;
+  %template(SIIPair) pair<std::pair<std::string, int>, int>;
+  %template(AIntPair) pair<A, int>;
+
+  %template(CCIntPair) pair<const A, const pair<int, int> >;
+
+  %template(ABPair) pair<A, B>;
+  %template(IntAPair) pair<int, A>;
+
+  %template(pairP1) pair<int, A*>;
+  %template(pairP2) pair<A*, int>;
+  %template(pairP3) pair<A*, A*>;
+  %template(pairP4) pair<int, int*>;
+  %template(pairP5) pair<int*, int>;
+  %template(pairP6) pair<int*, int*>;
+  
+}
+%std_comp_methods(std::pair<std::pair<std::string, int>, int>);
+
+%apply std::pair<int,int> *INOUT {std::pair<int,int> *INOUT2};
+
+%inline %{
+
+/* Test the "out" typemap for pair<T, U> */
+std::pair<int, int> makeIntPair(int a, int b) {
+    return std::make_pair(a, b);
+}
+
+/**
+ * There is no "out" typemap for a pointer to a pair, so
+ * this should return a wrapped instance of a std::pair
+ * instead of the native "array" type for the target language.
+ */
+std::pair<int, int> * makeIntPairPtr(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return &p;
+}
+
+/**
+ * There is no "out" typemap for a non-const reference to a pair, so
+ * this should return a wrapped instance of a std::pair instead of
+ * the native "array" type for the target language.
+ */
+std::pair<int, int>& makeIntPairRef(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return p;
+}
+
+/**
+ * There is no "out" typemap for a const reference to a pair, so
+ * this should return a wrapped instance of a std::pair
+ * instead of the native "array" type for the target language.
+ */
+const std::pair<int, int> & makeIntPairConstRef(int a, int b) {
+    static std::pair<int, int> p = std::make_pair(a, b);
+    return p;
+}
+
+/* Test the "in" typemap for pair<T, U> */
+int product1(std::pair<int, int> p) {
+    return p.first*p.second;
+}
+
+/* Test the "in" typemap for const pair<T, U>& */
+int product2(const std::pair<int, int>& p) {
+    return p.first*p.second;
+}
+
+std::pair<int, int> 
+  p_ident(std::pair<int, int> p, const std::pair<int, int>& q) {
+  return p;
+}
+
+
+std::pair<int, A*> 
+p_identa(const std::pair<int, A*>& p) {
+  return p;
+}
+
+void
+d_inout(double *INOUT) {
+  *INOUT += *INOUT;
+}
+
+void
+d_inout(int *INOUT) {
+  *INOUT += *INOUT;
+}
+
+int
+d_inout2(double *INOUT) {
+  *INOUT += *INOUT;
+  return 1;
+}
+
+void
+p_inout(std::pair<int, int> *INOUT) {
+  std::swap(INOUT->first, INOUT->second);
+}
+
+int
+p_inout2(std::pair<int, int> *INOUT) {
+  std::swap(INOUT->first, INOUT->second);
+  return 1;
+}
+
+void
+  p_inout3(std::pair<int,int> *INOUT, std::pair<int,int> *INOUT2) {
+  std::swap(*INOUT, *INOUT2);
+} 
+
+void
+p_inoutd(std::pair<double, double> *INOUT) {
+  std::swap(INOUT->first, INOUT->second);
+}
+
+std::string
+  s_ident(const std::string& s) {
+  return s;
+}
+
+#if 0
+std::pair<char, char> 
+  p_ident(std::pair<char, char> p, const std::pair<char, char>& q) {
+  return p;
+}
+
+/* Test the "in" typemap for const pair<T, U>* */
+std::pair<A, B> 
+  p_ident(std::pair<A, B> p, const std::pair<A, B>& q) {
+  return q;
+}
+
+/* Test the "in" typemap for const pair<T, U>* */
+std::pair<int, A> 
+  p_ident(std::pair<int, A> p, const std::pair<int, A>& q) {
+  return p;
+}
+
+
+std::pair<int, int> 
+  p_ident(std::pair<int, int> p, const std::pair<A, int>& q) {
+  return p;
+}
+
+std::pair<int, int> 
+  p_ident(std::pair<int, int> p, const std::pair<A, B>& q) {
+  return p;
+}
+
+
+
+#endif
+%}
+
+
+namespace std
+{
+  %template(paircA1) pair<const int, A*>;
+  %template(paircA2) pair<const int, const A*>;
+  %template(pairiiA) pair<int,pair<int, A*> >;
+}
+
diff --git a/trunk/Examples/test-suite/python/li_std_pair_runme.py b/trunk/Examples/test-suite/python/li_std_pair_runme.py
new file mode 100644
index 0000000..b301f0d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_pair_runme.py
@@ -0,0 +1,59 @@
+import li_std_pair
+
+p = (1,2)
+p1 = li_std_pair.p_inout(p)
+p2 = li_std_pair.p_inoutd(p1)
+
+d1 = li_std_pair.d_inout(2)
+
+i,d2 = li_std_pair.d_inout2(2)
+
+i,p = li_std_pair.p_inout2(p)
+p3,p4 = li_std_pair.p_inout3(p1,p1)
+
+psi = li_std_pair.SIPair("hello",1)
+pci = li_std_pair.CIPair(1,1)
+
+
+#psi.first = "hi"
+
+
+psi = li_std_pair.SIPair("hi",1)
+if psi != ("hi",1):
+  raise RuntimeError
+
+psii = li_std_pair.SIIPair(psi,1)
+
+a = li_std_pair.A()
+b = li_std_pair.B()
+
+pab = li_std_pair.ABPair(a,b);
+
+pab.first = a
+pab.first.val = 2
+
+if pab.first.val != 2:
+  raise RuntimeError
+  
+
+pci = li_std_pair.CIntPair(1,0)
+
+a = li_std_pair.A(5)
+p1 = li_std_pair.pairP1(1,a.this)
+p2 = li_std_pair.pairP2(a,1)
+p3 = li_std_pair.pairP3(a,a)
+
+
+if a.val != li_std_pair.p_identa(p1.this)[1].val:
+  raise RuntimeError
+  
+p = li_std_pair.IntPair(1,10)
+p.first = 1
+
+p = li_std_pair.paircA1(1,a)
+p.first
+p.second
+
+p = li_std_pair.paircA2(1,a)
+pp = li_std_pair.pairiiA(1,p)
+
diff --git a/trunk/Examples/test-suite/python/li_std_set.i b/trunk/Examples/test-suite/python/li_std_set.i
new file mode 100644
index 0000000..f0fddb0
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_set.i
@@ -0,0 +1,17 @@
+%module li_std_set
+
+%include <std_string.i>
+%include <std_set.i>
+%include <std_multiset.i>
+%include <std_vector.i>
+
+%template(set_string) std::set<std::string>;
+%template(set_int) std::multiset<int>;
+
+
+%template(v_int) std::vector<int>;
+
+
+
+
+%template(pyset) std::set<swig::PyObject_ptr>; 
diff --git a/trunk/Examples/test-suite/python/li_std_set_runme.py b/trunk/Examples/test-suite/python/li_std_set_runme.py
new file mode 100644
index 0000000..6d89631
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_set_runme.py
@@ -0,0 +1,96 @@
+from li_std_set import *
+
+s = set_string()
+
+s.append("a")
+s.append("b")
+s.append("c")
+
+sum = ""
+for i in s:
+    sum = sum + i
+
+if sum != "abc":
+    raise RuntimeError
+
+i = s.__iter__()
+if i.next() != "a":
+    raise RuntimeError
+if i.next() != "b":
+    raise RuntimeError
+if i.next() != "c":
+    raise RuntimeError
+
+
+b = s.begin()
+e = s.end()
+sum = ""
+while (b != e):    
+    sum = sum + b.next()
+if sum != "abc":
+    raise RuntimeError
+
+b = s.rbegin()
+e = s.rend()
+sum = ""
+while (b != e):    
+    sum = sum  + b.next()
+
+if sum != "cba":
+    raise RuntimeError
+
+
+
+si = set_int()
+
+si.append(1)
+si.append(2)
+si.append(3)
+i = si.__iter__()
+
+if i.next() != 1:
+    raise RuntimeError
+if i.next() != 2:
+    raise RuntimeError
+if i.next() != 3:
+    raise RuntimeError
+
+
+
+
+i = s.begin()
+i.next()
+s.erase(i)
+
+b = s.begin()
+e = s.end()
+sum = ""
+while (b != e):    
+    sum = sum + b.next()
+if sum != "ac":
+    raise RuntimeError
+
+
+b = s.begin()
+e = s.end()
+if e - b != 2:
+    raise RuntimeError
+    
+m = b + 1
+if m.value() != "c":
+    raise RuntimeError
+
+
+
+s = pyset()
+s.insert((1,2))
+s.insert(1)
+s.insert("hello")
+
+
+sum = ()
+for i in s:
+    sum = sum  + (i,)
+
+if sum != (1, 'hello', (1, 2)):
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_std_stream.i b/trunk/Examples/test-suite/python/li_std_stream.i
new file mode 100644
index 0000000..0a999dd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_stream.i
@@ -0,0 +1,59 @@
+%module li_std_stream
+
+%inline %{
+  struct A;  
+%}
+
+%include <std_iostream.i>
+%include <std_sstream.i>
+
+
+
+%callback(1) A::bar;
+
+%inline %{
+
+  struct B {
+    virtual ~B()
+    {
+    }
+    
+  };
+  
+  struct A : B
+  {
+    void __add__(int a)
+    {
+    }
+
+    void __add__(double a)
+    {
+    }
+
+    static int bar(int a){
+      return a;
+    }
+
+    static int foo(int a, int (*pf)(int a))
+    {
+      return pf(a);
+    }
+
+
+    std::ostream& __rlshift__(std::ostream& out)
+    {
+      out << "A class";
+      return out;
+    }    
+  };
+%}
+
+%extend std::basic_ostream<char>{
+  std::basic_ostream<char>& 
+    operator<<(const A& a)
+    {
+      *self << "A class";
+      return *self;
+    }
+}
+
diff --git a/trunk/Examples/test-suite/python/li_std_stream_runme.py b/trunk/Examples/test-suite/python/li_std_stream_runme.py
new file mode 100644
index 0000000..d41e41f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_stream_runme.py
@@ -0,0 +1,14 @@
+from li_std_stream import *
+
+
+
+a = A()
+
+o = ostringstream()
+
+o << a << " " << 2345 << " " << 1.435
+
+
+if o.str() !=  "A class 2345 1.435":
+  print "\"%s\"" % (o.str(),)
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_std_string.i b/trunk/Examples/test-suite/python/li_std_string.i
new file mode 100644
index 0000000..822d713
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_string.i
@@ -0,0 +1,55 @@
+%module li_std_string
+
+%naturalvar A;
+
+
+%include <std_basic_string.i>
+%include <std_string.i>
+
+
+%inline %{
+
+struct A : std::string 
+{
+  A(const std::string& s) : std::string(s)
+  {
+  }
+};
+
+struct B 
+{
+  B(const std::string& s) : cname(0), name(s), a(s)
+  {
+  }
+  
+  char *cname;
+  std::string name;
+  A a;
+
+};
+ 
+
+const char* test_ccvalue(const char* x) {
+   return x;
+}
+
+char* test_cvalue(char* x) {
+   return x;
+}
+
+std::basic_string<char> test_value_basic1(std::basic_string<char> x) {
+   return x;
+}
+
+std::basic_string<char,std::char_traits<char> > test_value_basic2(std::basic_string<char,std::char_traits<char> > x) {
+   return x;
+}
+
+std::basic_string<char,std::char_traits<char>,std::allocator<char> > test_value_basic3(std::basic_string<char,std::char_traits<char>,std::allocator<char> > x) {
+   return x;
+}
+
+%}
+
+%include ../li_std_string.i
+
diff --git a/trunk/Examples/test-suite/python/li_std_string_runme.py b/trunk/Examples/test-suite/python/li_std_string_runme.py
new file mode 100644
index 0000000..c0dae1e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_string_runme.py
@@ -0,0 +1,132 @@
+import li_std_string
+
+x="hello"
+
+
+
+if li_std_string.test_ccvalue(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_cvalue(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_value(x) != x:
+  print x, li_std_string.test_value(x)
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_const_reference(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+
+s = li_std_string.string("he")
+#s += "ll"
+#s.append('o')
+s = s + "llo"
+
+if s != x:
+  print s, x
+  raise RuntimeError, "bad string mapping"
+
+if s[1:4] != x[1:4]:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_value(s) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_const_reference(s) != x:
+  raise RuntimeError, "bad string mapping"
+
+a = li_std_string.A(s)
+
+if li_std_string.test_value(a) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_const_reference(a) != x:
+  raise RuntimeError, "bad string mapping"
+
+b = li_std_string.string(" world")
+
+s = a + b
+if a + b != "hello world":
+  print a + b
+  raise RuntimeError, "bad string mapping"
+  
+if a + " world" != "hello world":
+  raise RuntimeError, "bad string mapping"
+
+if "hello" + b != "hello world":
+  raise RuntimeError, "bad string mapping"
+
+c = "hello" + b
+if c.find_last_of("l") != 9:
+  raise RuntimeError, "bad string mapping"
+  
+s = "hello world"
+
+b = li_std_string.B("hi")
+
+b.name = li_std_string.string("hello")
+if b.name != "hello":
+  raise RuntimeError, "bad string mapping"
+
+
+b.a = li_std_string.A("hello")
+if b.a != "hello":
+  raise RuntimeError, "bad string mapping"
+
+
+if li_std_string.test_value_basic1(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_string.test_value_basic2(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+
+if li_std_string.test_value_basic3(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+# Global variables
+s = "initial string"
+if li_std_string.cvar.GlobalString2 != "global string 2":
+  raise RuntimeError, "GlobalString2 test 1"
+li_std_string.cvar.GlobalString2 = s
+if li_std_string.cvar.GlobalString2 != s:
+  raise RuntimeError, "GlobalString2 test 2"
+if li_std_string.cvar.ConstGlobalString != "const global string":
+  raise RuntimeError, "ConstGlobalString test"
+
+# Member variables
+myStructure = li_std_string.Structure()
+if myStructure.MemberString2 != "member string 2":
+  raise RuntimeError, "MemberString2 test 1"
+myStructure.MemberString2 = s
+if myStructure.MemberString2 != s:
+  raise RuntimeError, "MemberString2 test 2"
+if myStructure.ConstMemberString != "const member string":
+  raise RuntimeError, "ConstMemberString test"
+
+if li_std_string.cvar.Structure_StaticMemberString2 != "static member string 2":
+  raise RuntimeError, "StaticMemberString2 test 1"
+li_std_string.cvar.Structure_StaticMemberString2 = s
+if li_std_string.cvar.Structure_StaticMemberString2 != s:
+  raise RuntimeError, "StaticMemberString2 test 2"
+if li_std_string.cvar.Structure_ConstStaticMemberString != "const static member string":
+  raise RuntimeError, "ConstStaticMemberString test"
+
+
+if li_std_string.test_reference_input("hello") != "hello":
+  raise RuntimeError
+s = li_std_string.test_reference_inout("hello")
+if s != "hellohello":
+  raise RuntimeError
+
+
+if li_std_string.stdstring_empty() != "":
+  raise RuntimeError
+  
+
+if li_std_string.c_empty() != "":
+  raise RuntimeError
+
+if li_std_string.c_null() != None:
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_std_vector.i b/trunk/Examples/test-suite/python/li_std_vector.i
new file mode 100644
index 0000000..06dafce
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_vector.i
@@ -0,0 +1,141 @@
+%module li_std_vector
+
+%warnfilter(509) overloaded1;
+%warnfilter(509) overloaded2;
+
+%include "std_string.i"
+%include "std_vector.i"
+%include "cpointer.i"
+%include "carrays.i"
+
+%{
+#include <algorithm>
+#include <functional>
+#include <numeric>
+%}
+
+namespace std {
+    %template() vector<short>;
+    %template(IntVector) vector<int>;
+    %template(BoolVector) vector<bool>;
+    %template() vector<string>;
+}
+
+%template(DoubleVector) std::vector<double>;
+
+
+%template(sizeVector) std::vector<size_t>;
+%{
+  template <class T>
+  struct Param
+  {
+    T val;
+
+    Param(T v = 0): val(v) {
+    }
+    
+    operator T() const { return val; }
+  };
+%}
+specialize_std_vector(Param<int>,PyInt_Check,PyInt_AsLong,PyInt_FromLong);
+%template(PIntVector) std::vector<Param<int> >;
+
+%inline %{
+typedef float Real;
+%}
+
+namespace std {
+    %template(RealVector) vector<Real>;
+}
+
+%inline %{
+
+double average(std::vector<int> v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<Real> half(const std::vector<Real>& v) {
+    std::vector<Real> w(v);
+    for (std::vector<Real>::size_type i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+void halve_in_place(std::vector<double>& v) {
+    std::transform(v.begin(),v.end(),v.begin(),
+                   std::bind2nd(std::divides<double>(),2.0));
+}
+
+%}
+
+%template(IntPtrVector) std::vector<int *>;
+
+
+
+//
+//
+%{
+#include <iostream>
+%}
+
+%inline %{
+  
+namespace Test {
+struct A {
+    virtual ~A() {}    
+    virtual int f(const int i) const = 0;
+};
+
+struct B : public A {
+  int val;
+  
+  B(int i = 0) : val(i)
+  {
+  }
+  
+  int f(const int i) const { return i + val; }
+};
+
+
+int vecAptr(const std::vector<A*>& v) {
+    return v[0]->f(1);
+}
+
+} 
+
+std::vector<short> halfs(const std::vector<short>& v) {
+    std::vector<short> w(v);
+    for (std::vector<short>::size_type i=0; i<w.size(); i++)
+        w[i] /= 2;
+    return w;
+}
+
+
+std::vector<std::string>  vecStr(std::vector<std::string> v) {
+  v[0] += v[1];
+  return v;
+}
+
+%}
+%template(VecB) std::vector<Test::B>; 
+%template(VecA) std::vector<Test::A*>; 
+
+%pointer_class(int,PtrInt)
+%array_functions(int,ArrInt)
+
+
+%template(pyvector) std::vector<swig::PyObject_ptr>; 
+
+namespace std {
+   %template(ConstIntVector) vector<const int *>;
+}
+
+%inline %{
+std::string overloaded1(std::vector<double> vi) { return "vector<double>"; }
+std::string overloaded1(std::vector<int> vi) { return "vector<int>"; }
+std::string overloaded2(std::vector<int> vi) { return "vector<int>"; }
+std::string overloaded2(std::vector<double> vi) { return "vector<double>"; }
+std::string overloaded3(std::vector<int> *vi) { return "vector<int> *"; }
+std::string overloaded3(int i) { return "int"; }
+%}
+
diff --git a/trunk/Examples/test-suite/python/li_std_vector_runme.py b/trunk/Examples/test-suite/python/li_std_vector_runme.py
new file mode 100644
index 0000000..a0d96d4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_vector_runme.py
@@ -0,0 +1,135 @@
+from li_std_vector import *
+
+iv = IntVector(4)
+for i in range(0,4):
+    iv[i] = i
+
+x = average(iv)
+y = average([1,2,3,4])
+
+a = half([10,10.5,11,11.5])
+
+dv = DoubleVector(10)
+for i in range(0,10):
+    dv[i] = i/2.0
+
+halve_in_place(dv)
+
+
+bv = BoolVector(4)
+bv[0]= 1
+bv[1]= 0
+bv[2]= 4
+bv[3]= 0
+
+if bv[0] != bv[2]:
+    raise RuntimeError,"bad std::vector<bool> mapping"
+
+b = B(5)
+va = VecA([b,None,b,b])
+
+if va[0].f(1) != 6:
+    raise RuntimeError,"bad std::vector<A*> mapping"
+
+if vecAptr(va) != 6:
+    raise RuntimeError,"bad std::vector<A*> mapping"
+
+b.val = 7
+if va[3].f(1) != 8:
+    raise RuntimeError,"bad std::vector<A*> mapping"
+
+
+ip = PtrInt()
+ap = new_ArrInt(10)
+
+ArrInt_setitem(ip,0,123)
+ArrInt_setitem(ap,2,123)
+
+vi = IntPtrVector((ip,ap,None))
+if ArrInt_getitem(vi[0],0) != ArrInt_getitem(vi[1],2):
+    raise RuntimeError,"bad std::vector<int*> mapping"
+
+delete_ArrInt(ap)    
+
+
+a = halfs([10,8,4,3])
+
+v = IntVector()
+v[0:2] = [1,2]
+if v[0] != 1 or v[1] != 2:
+    raise RuntimeError,"bad setslice"
+
+if v[0:-1][0] != 1:
+    raise RuntimeError,"bad getslice"
+
+if v[0:-2].size() != 0:
+    raise RuntimeError,"bad getslice"
+
+v[0:1] = [2]
+if v[0] != 2:
+    raise RuntimeError,"bad setslice"
+
+v[1:] = [3]
+if v[1] != 3:
+    raise RuntimeError,"bad setslice"
+
+v[2:] = [3]
+if v[2] != 3:
+    raise RuntimeError,"bad setslice"
+
+if v[0:][0] != v[0]:
+    raise RuntimeError,"bad getslice"
+
+
+del v[:]
+if v.size() != 0:
+    raise RuntimeError,"bad getslice"    
+
+del v[:]
+if v.size() != 0:
+    raise RuntimeError,"bad getslice"    
+
+
+
+v = vecStr(["hello ", "world"])
+if v[0] != 'hello world':
+    raise RuntimeError,"bad std::string+std::vector"
+    
+
+
+pv = pyvector([1, "hello", (1,2)])
+
+if pv[1] != "hello":
+    raise RuntimeError
+
+
+iv = IntVector(5)
+for i in range(0,5):
+    iv[i] = i
+
+iv[1:3] = []
+if iv[1] != 3:
+    raise RuntimeError
+
+# Overloading checks
+if overloaded1(iv) != "vector<int>":
+  raise RuntimeError
+
+if overloaded1(dv) != "vector<double>":
+  raise RuntimeError
+
+if overloaded2(iv) != "vector<int>":
+  raise RuntimeError
+
+if overloaded2(dv) != "vector<double>":
+  raise RuntimeError
+
+if overloaded3(iv) != "vector<int> *":
+  raise RuntimeError
+
+if overloaded3(None) != "vector<int> *":
+  raise RuntimeError
+
+if overloaded3(100) != "int":
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/li_std_vectora.i b/trunk/Examples/test-suite/python/li_std_vectora.i
new file mode 100644
index 0000000..d95fdf6
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_vectora.i
@@ -0,0 +1,65 @@
+%module li_std_vectora
+
+%include std_vectora.i
+
+
+%{
+#include <algorithm>
+#include <functional>
+#include <numeric>
+%}
+
+
+%template(vector_i) std::vector<int, std::allocator<int> >;
+
+%template(matrix_i) std::vector<std::vector<int,std::allocator<int> >,std::allocator<std::vector<int,std::allocator<int> > > >;
+
+%inline 
+{
+  typedef 
+    std::vector<std::vector<int,std::allocator<int> >,
+                std::allocator<std::vector<int,std::allocator<int> > > >
+    imatrix;
+
+  std::vector<int> vident(const std::vector<int,std::allocator<int> >& v)
+  {
+    return v;
+  }
+
+  imatrix mident(const imatrix& v)
+  {
+    return v;
+  }
+}
+
+
+%template(DoubleVector) std::vector<double, std::allocator<double> >;
+
+%inline %{
+typedef float Real;
+%}
+
+namespace std {
+  %template(RealVector) vector<Real, std::allocator<Real> >;
+}
+
+%inline %{
+
+double average(std::vector<int, std::allocator<int> > v) {
+    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+}
+
+std::vector<Real,std::allocator<Real> >
+half(const std::vector<Real,std::allocator<Real> >& v) {
+    std::vector<Real> w(v);
+    for (unsigned int i=0; i<w.size(); i++)
+        w[i] /= 2.0;
+    return w;
+}
+
+%}
+
+%template(IntPtrVector) std::vector<int *,std::allocator<int *> >;
+
+
+
diff --git a/trunk/Examples/test-suite/python/li_std_wstream.i b/trunk/Examples/test-suite/python/li_std_wstream.i
new file mode 100644
index 0000000..e4d725f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_wstream.i
@@ -0,0 +1,59 @@
+%module li_std_wstream
+
+%inline %{
+  struct A;  
+%}
+
+%include <std_wiostream.i>
+%include <std_wsstream.i>
+
+
+
+%callback(1) A::bar;
+
+%inline %{
+
+  struct B {
+    virtual ~B()
+    {
+    }
+    
+  };
+  
+  struct A : B
+  {
+    void __add__(int a)
+    {
+    }
+
+    void __add__(double a)
+    {
+    }
+
+    static int bar(int a){
+      return a;
+    }
+
+    static int foo(int a, int (*pf)(int a))
+    {
+      return pf(a);
+    }
+
+
+    std::wostream& __rlshift__(std::wostream& out)
+    {
+      out << "A class";
+      return out;
+    }    
+  };
+%}
+
+%extend std::basic_ostream<wchar_t>{
+  std::basic_ostream<wchar_t>& 
+    operator<<(const A& a)
+    {
+      *self << "A class";
+      return *self;
+    }
+}
+
diff --git a/trunk/Examples/test-suite/python/li_std_wstream_runme.py b/trunk/Examples/test-suite/python/li_std_wstream_runme.py
new file mode 100644
index 0000000..f7379bd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_wstream_runme.py
@@ -0,0 +1,13 @@
+from li_std_wstream import *
+
+
+
+a = A()
+
+o = wostringstream()
+
+o << a << u" " << 2345 << u" " << 1.435 << wends
+
+if o.str() !=  "A class 2345 1.435\0":
+  print "\"%s\"" % (o.str(),)
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/li_std_wstring.i b/trunk/Examples/test-suite/python/li_std_wstring.i
new file mode 100644
index 0000000..c809e11
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_wstring.i
@@ -0,0 +1,89 @@
+%module li_std_wstring
+%include <std_basic_string.i>
+%include <std_wstring.i>
+
+
+%inline %{
+
+struct A : std::wstring 
+{
+  A(const std::wstring& s) : std::wstring(s)
+  {
+  }
+};
+
+struct B 
+{
+  B(const std::wstring& s) : cname(0), name(s), a(s)
+  {
+  }
+  
+  char *cname;
+  std::wstring name;
+  A a;
+
+};
+ 
+
+wchar_t test_wcvalue(wchar_t x) {
+   return x;
+}
+
+const wchar_t* test_ccvalue(const wchar_t* x) {
+   return x;
+}
+
+wchar_t* test_cvalue(wchar_t* x) {
+   return x;
+}
+  
+
+std::wstring test_value(std::wstring x) {
+   return x;
+}
+
+const std::wstring& test_const_reference(const std::wstring &x) {
+   return x;
+}
+
+void test_pointer(std::wstring *x) {
+}
+
+std::wstring *test_pointer_out() {
+   static std::wstring x = L"x";
+   return &x;
+}
+
+void test_const_pointer(const std::wstring *x) {
+}
+
+const std::wstring *test_const_pointer_out() {
+   static std::wstring x = L"x";
+   return &x;
+}
+
+void test_reference(std::wstring &x) {
+}
+
+std::wstring& test_reference_out() {
+   static std::wstring x = L"x";
+   return x;
+}
+
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+void test_throw() throw(std::wstring){
+  static std::wstring x = L"x";
+  
+  throw x;
+}
+
+#if defined(_MSC_VER)
+  #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+
+%}
+
+
diff --git a/trunk/Examples/test-suite/python/li_std_wstring_runme.py b/trunk/Examples/test-suite/python/li_std_wstring_runme.py
new file mode 100644
index 0000000..a4b9d3e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/li_std_wstring_runme.py
@@ -0,0 +1,76 @@
+import li_std_wstring
+
+x=u"h"
+
+if li_std_wstring.test_wcvalue(x) != x:
+  print li_std_wstring.test_wcvalue(x)
+  raise RuntimeError, "bad string mapping"
+
+x=u"hello"
+if li_std_wstring.test_ccvalue(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_wstring.test_cvalue(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_wstring.test_value(x) != x:
+  print x, li_std_wstring.test_value(x)
+  raise RuntimeError, "bad string mapping"
+
+if li_std_wstring.test_const_reference(x) != x:
+  raise RuntimeError, "bad string mapping"
+
+
+s = li_std_wstring.wstring(u"he")
+s = s + u"llo"
+
+if s != x:
+  print s, x
+  raise RuntimeError, "bad string mapping"
+
+if s[1:4] != x[1:4]:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_wstring.test_value(s) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_wstring.test_const_reference(s) != x:
+  raise RuntimeError, "bad string mapping"
+
+a = li_std_wstring.A(s)
+
+if li_std_wstring.test_value(a) != x:
+  raise RuntimeError, "bad string mapping"
+
+if li_std_wstring.test_const_reference(a) != x:
+  raise RuntimeError, "bad string mapping"
+
+b = li_std_wstring.wstring(" world")
+
+if a + b != "hello world":
+  raise RuntimeError, "bad string mapping"
+  
+if a + " world" != "hello world":
+  raise RuntimeError, "bad string mapping"
+
+if "hello" + b != "hello world":
+  raise RuntimeError, "bad string mapping"
+
+c = "hello" + b
+if c.find_last_of("l") != 9:
+  raise RuntimeError, "bad string mapping"
+  
+s = "hello world"
+
+b = li_std_wstring.B("hi")
+
+b.name = li_std_wstring.wstring(u"hello")
+if b.name != "hello":
+  raise RuntimeError, "bad string mapping"
+
+
+b.a = li_std_wstring.A("hello")
+if b.a != u"hello":
+  raise RuntimeError, "bad string mapping"
+
+
diff --git a/trunk/Examples/test-suite/python/member_pointer_runme.py b/trunk/Examples/test-suite/python/member_pointer_runme.py
new file mode 100644
index 0000000..27e7a48
--- /dev/null
+++ b/trunk/Examples/test-suite/python/member_pointer_runme.py
@@ -0,0 +1,43 @@
+# Example using pointers to member functions
+
+from member_pointer import *
+
+def check(what, expected, actual):
+  if expected != actual:
+    raise RuntimeError ("Failed: " , what , " Expected: " , expected , " Actual: " , actual)
+
+# Get the pointers
+
+area_pt = areapt()
+perim_pt = perimeterpt()
+
+# Create some objects
+
+s = Square(10)
+
+# Do some calculations
+
+check ("Square area ", 100.0, do_op(s,area_pt))
+check ("Square perim", 40.0, do_op(s,perim_pt))
+
+memberPtr = cvar.areavar
+memberPtr = cvar.perimetervar
+
+# Try the variables
+check ("Square area ", 100.0, do_op(s,cvar.areavar))
+check ("Square perim", 40.0, do_op(s,cvar.perimetervar))
+
+# Modify one of the variables
+cvar.areavar = perim_pt
+
+check ("Square perimeter", 40.0, do_op(s,cvar.areavar))
+
+# Try the constants
+
+memberPtr = AREAPT
+memberPtr = PERIMPT
+memberPtr = NULLPT
+
+check ("Square area ", 100.0, do_op(s,AREAPT))
+check ("Square perim", 40.0, do_op(s,PERIMPT))
+
diff --git a/trunk/Examples/test-suite/python/minherit_runme.py b/trunk/Examples/test-suite/python/minherit_runme.py
new file mode 100644
index 0000000..d7ad0b3
--- /dev/null
+++ b/trunk/Examples/test-suite/python/minherit_runme.py
@@ -0,0 +1,71 @@
+
+import minherit
+
+a = minherit.Foo()
+b = minherit.Bar()
+c = minherit.FooBar()
+d = minherit.Spam()
+
+if a.xget() != 1:
+    raise RuntimeError, "Bad attribute value"
+
+if b.yget() != 2:
+    raise RuntimeError, "Bad attribute value"    
+
+if c.xget() != 1 or c.yget() != 2 or c.zget() != 3:
+    raise RuntimeError, "Bad attribute value"    
+
+if d.xget() != 1 or d.yget() != 2 or d.zget() != 3 or d.wget() != 4:
+    raise RuntimeError, "Bad attribute value"        
+
+
+if minherit.xget(a) != 1:
+    raise RuntimeError, "Bad attribute value %d" % (minherit.xget(a))     
+
+if minherit.yget(b) != 2:
+    raise RuntimeError, "Bad attribute value %d" % (minherit.yget(b)) 
+
+if minherit.xget(c) != 1 or minherit.yget(c) != 2 or minherit.zget(c) != 3:
+    raise RuntimeError, "Bad attribute value %d %d %d" % (minherit.xget(c), minherit.yget(c), minherit.zget(c))    
+
+if minherit.xget(d) != 1 or minherit.yget(d) != 2 or minherit.zget(d) != 3 or minherit.wget(d) != 4:
+    raise RuntimeError, "Bad attribute value %d %d %d %d" % (minherit.xget(d), minherit.yget(d), minherit.zget(d), minherit.wget(d))
+
+# Cleanse all of the pointers and see what happens
+
+aa = minherit.toFooPtr(a)
+bb = minherit.toBarPtr(b)
+cc = minherit.toFooBarPtr(c)
+dd = minherit.toSpamPtr(d)
+
+if aa.xget() != 1:
+    raise RuntimeError, "Bad attribute value"
+
+if bb.yget() != 2:
+    raise RuntimeError, "Bad attribute value"    
+
+if cc.xget() != 1 or cc.yget() != 2 or cc.zget() != 3:
+    raise RuntimeError, "Bad attribute value"    
+
+if dd.xget() != 1 or dd.yget() != 2 or dd.zget() != 3 or dd.wget() != 4:
+    raise RuntimeError, "Bad attribute value"        
+
+if minherit.xget(aa) != 1:
+    raise RuntimeError, "Bad attribute value %d" % (minherit.xget(aa))     
+
+if minherit.yget(bb) != 2:
+    raise RuntimeError, "Bad attribute value %d" % (minherit.yget(bb)) 
+
+if minherit.xget(cc) != 1 or minherit.yget(cc) != 2 or minherit.zget(cc) != 3:
+    raise RuntimeError, "Bad attribute value %d %d %d" % (minherit.xget(cc), minherit.yget(cc), minherit.zget(cc))    
+
+if minherit.xget(dd) != 1 or minherit.yget(dd) != 2 or minherit.zget(dd) != 3 or minherit.wget(dd) != 4:
+    raise RuntimeError, "Bad attribute value %d %d %d %d" % (minherit.xget(dd), minherit.yget(dd), minherit.zget(dd), minherit.wget(dd))
+
+
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/python/mod_runme.py b/trunk/Examples/test-suite/python/mod_runme.py
new file mode 100644
index 0000000..d926119
--- /dev/null
+++ b/trunk/Examples/test-suite/python/mod_runme.py
@@ -0,0 +1,6 @@
+import mod_a
+import mod_b
+
+c = mod_b.C()
+d = mod_b.D()
+d.DoSomething(c)
diff --git a/trunk/Examples/test-suite/python/multi_import_runme.py b/trunk/Examples/test-suite/python/multi_import_runme.py
new file mode 100644
index 0000000..f8a2f19
--- /dev/null
+++ b/trunk/Examples/test-suite/python/multi_import_runme.py
@@ -0,0 +1,18 @@
+import multi_import_a
+import multi_import_b
+
+x = multi_import_b.XXX()
+if x.testx() != 0:
+	raise RuntimeError
+
+y = multi_import_b.YYY()
+if y.testx() != 0:
+	raise RuntimeError
+if y.testy() != 1:
+	raise RuntimeError
+
+z = multi_import_a.ZZZ()
+if z.testx() != 0:
+	raise RuntimeError
+if z.testz() != 2:
+	raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/namespace_class_runme.py b/trunk/Examples/test-suite/python/namespace_class_runme.py
new file mode 100644
index 0000000..84d3b00
--- /dev/null
+++ b/trunk/Examples/test-suite/python/namespace_class_runme.py
@@ -0,0 +1,34 @@
+from namespace_class import *
+
+try:
+  p = Private1()
+  error = 1
+except:
+  error = 0
+
+if (error):
+  raise RuntimeError, "Private1 is private"
+
+try:
+  p = Private2()
+  error = 1
+except:
+  error = 0
+
+if (error):
+  raise RuntimeError, "Private2 is private"
+
+EulerT3D.toFrame(1,1,1)
+
+b = BooT_i()
+b = BooT_H()
+
+
+f = FooT_i()
+f.quack(1)
+
+f = FooT_d()
+f.moo(1)
+
+f = FooT_H()
+f.foo(Hi)
diff --git a/trunk/Examples/test-suite/python/namespace_typemap_runme.py b/trunk/Examples/test-suite/python/namespace_typemap_runme.py
new file mode 100644
index 0000000..682ad3b
--- /dev/null
+++ b/trunk/Examples/test-suite/python/namespace_typemap_runme.py
@@ -0,0 +1,82 @@
+from namespace_typemap import *
+
+if stest1("hello") != "hello":
+    raise RuntimeError
+
+if stest2("hello") != "hello":
+    raise RuntimeError
+
+if stest3("hello") != "hello":
+    raise RuntimeError
+
+if stest4("hello") != "hello":
+    raise RuntimeError
+
+if stest5("hello") != "hello":
+    raise RuntimeError
+
+if stest6("hello") != "hello":
+    raise RuntimeError
+
+if stest7("hello") != "hello":
+    raise RuntimeError
+
+if stest8("hello") != "hello":
+    raise RuntimeError
+
+if stest9("hello") != "hello":
+    raise RuntimeError
+
+if stest10("hello") != "hello":
+    raise RuntimeError
+
+if stest11("hello") != "hello":
+    raise RuntimeError
+
+if stest12("hello") != "hello":
+    raise RuntimeError
+
+c = complex(2,3)
+r = c.real
+
+if ctest1(c) != r:
+    raise RuntimeError
+
+if ctest2(c) != r:
+    raise RuntimeError
+
+if ctest3(c) != r:
+    raise RuntimeError
+
+if ctest4(c) != r:
+    raise RuntimeError
+
+if ctest5(c) != r:
+    raise RuntimeError
+
+if ctest6(c) != r:
+    raise RuntimeError
+
+if ctest7(c) != r:
+    raise RuntimeError
+
+if ctest8(c) != r:
+    raise RuntimeError
+
+if ctest9(c) != r:
+    raise RuntimeError
+
+if ctest10(c) != r:
+    raise RuntimeError
+
+if ctest11(c) != r:
+    raise RuntimeError
+
+if ctest12(c) != r:
+    raise RuntimeError
+
+try:
+    ttest1(-14)
+    raise RuntimeError
+except ValueError:
+    pass
diff --git a/trunk/Examples/test-suite/python/namespace_virtual_method_runme.py b/trunk/Examples/test-suite/python/namespace_virtual_method_runme.py
new file mode 100644
index 0000000..c3580fb
--- /dev/null
+++ b/trunk/Examples/test-suite/python/namespace_virtual_method_runme.py
@@ -0,0 +1,3 @@
+import namespace_virtual_method
+
+x = namespace_virtual_method.Spam()
diff --git a/trunk/Examples/test-suite/python/naturalvar_runme.py b/trunk/Examples/test-suite/python/naturalvar_runme.py
new file mode 100644
index 0000000..a0481ec
--- /dev/null
+++ b/trunk/Examples/test-suite/python/naturalvar_runme.py
@@ -0,0 +1,12 @@
+from naturalvar import *
+
+f = Foo()
+b = Bar()
+
+b.f = f
+
+cvar.s = "hello"
+b.s = "hello"
+
+if b.s != cvar.s:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/nondynamic.i b/trunk/Examples/test-suite/python/nondynamic.i
new file mode 100644
index 0000000..2acc9bf
--- /dev/null
+++ b/trunk/Examples/test-suite/python/nondynamic.i
@@ -0,0 +1,58 @@
+%module nondynamic
+
+/*
+ Use the %pythonnondynamic directuve to make the wrapped class a
+ nondynamic one, ie, a python class that doesn't dynamically add new
+ attributes.  Hence, for the class
+
+  %pythonnondynamic A;
+  struct A 
+  {
+    int a;
+    int b;
+  };
+
+ you will get:
+
+  aa = A()
+  aa.a = 1  # Ok
+  aa.b = 1  # Ok
+  aa.c = 3  # error
+
+ Since "nondynamic" is a feature, if you use
+
+  %pythonnondynamic;
+
+ it will make all the wrapped class nondynamic ones.
+
+ The implementation is based on the recipe:
+
+   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
+
+ and works for modern (-modern) and plain python.
+
+*/
+
+
+
+%pythonnondynamic A;
+%pythondynamic C;
+
+
+%inline %{
+
+  struct A 
+  {
+    int a;
+    int b;
+  };
+
+
+  struct C
+  {
+    int a;
+    int b;
+  };
+
+%}
+
diff --git a/trunk/Examples/test-suite/python/nondynamic_runme.py b/trunk/Examples/test-suite/python/nondynamic_runme.py
new file mode 100644
index 0000000..1823061
--- /dev/null
+++ b/trunk/Examples/test-suite/python/nondynamic_runme.py
@@ -0,0 +1,39 @@
+import nondynamic
+
+aa = nondynamic.A()
+
+aa.a = 1
+aa.b = 2
+try:
+  aa.c = 2
+  err = 0
+except:
+  err = 1
+
+if not err:  
+  raise RuntimeError, "A is not static"  
+
+
+class B(nondynamic.A):
+  c = 4
+  def __init__(self):
+    nondynamic.A.__init__(self)
+    pass
+  pass
+
+
+
+bb = B()
+bb.c = 3
+try:
+  bb.d = 2
+  err = 0
+except:
+  err = 1
+
+if not err:  
+  raise RuntimeError, "B is not static"  
+    
+      
+cc = nondynamic.C()
+cc.d = 3
diff --git a/trunk/Examples/test-suite/python/overload_complicated_runme.py b/trunk/Examples/test-suite/python/overload_complicated_runme.py
new file mode 100755
index 0000000..2b7467d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_complicated_runme.py
@@ -0,0 +1,47 @@
+from overload_complicated import *
+
+pInt = None
+
+# Check the correct constructors are available
+p = Pop(pInt)
+
+p = Pop(pInt, 0)
+
+# Check overloaded in const only and pointers/references which target languages cannot disambiguate
+if p.hip(0) != 701:
+  raise RuntimeError,"Test 1 failed"
+
+if p.hip(pInt) != 702:
+  raise RuntimeError,"Test 2 failed"
+
+# Reverse the order for the above
+if p.hop(pInt) != 805:
+  raise RuntimeError,"Test 3 failed"
+
+if p.hop(0) != 801:
+  raise RuntimeError,"Test 4 failed"
+
+# Few more variations and order shuffled
+if p.pop(0) != 901:
+  raise RuntimeError,"Test 5 failed"
+
+if p.pop(pInt) != 902:
+  raise RuntimeError,"Test 6 failed"
+
+if p.pop() != 905:
+  raise RuntimeError,"Test 7 failed"
+
+# Overload on const only
+if p.bop(pInt) != 1001:
+  raise RuntimeError,"Test 8 failed"
+
+if p.bip(pInt) != 2001:
+  raise RuntimeError,"Test 9 failed"
+
+# Globals
+if muzak(0) != 3001:
+  raise RuntimeError,"Test 10 failed"
+
+if muzak(pInt) != 3002:
+  raise RuntimeError,"Test 11 failed"
+
diff --git a/trunk/Examples/test-suite/python/overload_copy_runme.py b/trunk/Examples/test-suite/python/overload_copy_runme.py
new file mode 100644
index 0000000..6ccf401
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_copy_runme.py
@@ -0,0 +1,3 @@
+from overload_copy import *
+f = Foo()
+g = Foo(f)
diff --git a/trunk/Examples/test-suite/python/overload_extend_runme.py b/trunk/Examples/test-suite/python/overload_extend_runme.py
new file mode 100644
index 0000000..7d08d48
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_extend_runme.py
@@ -0,0 +1,14 @@
+import overload_extend
+
+f = overload_extend.Foo()
+if f.test() != 0:
+    raise RuntimeError
+if f.test(3) != 1:
+    raise RuntimeError
+if f.test("hello") != 2:
+    raise RuntimeError
+if f.test(3,2) != 5:
+    raise RuntimeError
+if f.test(3.0) != 1003:
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/overload_extendc_runme.py b/trunk/Examples/test-suite/python/overload_extendc_runme.py
new file mode 100644
index 0000000..cea3ea6
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_extendc_runme.py
@@ -0,0 +1,22 @@
+import overload_extendc
+
+f = overload_extendc.Foo()
+if f.test(3) != 1:
+    raise RuntimeError
+if f.test("hello") != 2:
+    raise RuntimeError
+if f.test(3.5,2.5) != 3:
+    raise RuntimeError
+if f.test("hello",20) != 1020:
+    raise RuntimeError
+if f.test("hello",20,100) != 120:
+    raise RuntimeError
+
+# C default args
+if f.test(f) != 30:
+    raise RuntimeError
+if f.test(f,100) != 120:
+    raise RuntimeError
+if f.test(f,100,200) != 300:
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/overload_rename_runme.py b/trunk/Examples/test-suite/python/overload_rename_runme.py
new file mode 100644
index 0000000..b192f7d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_rename_runme.py
@@ -0,0 +1,8 @@
+import overload_rename
+
+
+f = overload_rename.Foo(1)
+f = overload_rename.Foo(1,1)
+f = overload_rename.Foo_int(1,1)
+f = overload_rename.Foo_int(1,1,1)
+
diff --git a/trunk/Examples/test-suite/python/overload_simple_cast.i b/trunk/Examples/test-suite/python/overload_simple_cast.i
new file mode 100644
index 0000000..d274722
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_simple_cast.i
@@ -0,0 +1,4 @@
+// Simple tests of overloaded functions
+%module("castmode") overload_simple_cast
+
+%include overload_simple.i
diff --git a/trunk/Examples/test-suite/python/overload_simple_cast_runme.py b/trunk/Examples/test-suite/python/overload_simple_cast_runme.py
new file mode 100644
index 0000000..87e6e5d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_simple_cast_runme.py
@@ -0,0 +1,192 @@
+from overload_simple_cast import *
+
+class Ai:
+    def __init__(self,x):
+        self.x = x
+        
+    def __int__(self):
+        return self.x
+
+class Ad:
+    def __init__(self,x):
+        self.x = x
+        
+    def __float__(self):
+        return self.x
+
+ai = Ai(4)
+
+ad = Ad(5.0)
+add = Ad(5.5)
+
+try:
+    fint(add)
+    good = 0
+except:
+    good = 1
+
+if not good:
+    raise RuntimeError, "fint(int)"    
+
+
+if fint(ad) != "fint:int":
+    raise RuntimeError, "fint(int)"
+
+if fdouble(ad) != "fdouble:double":
+    raise RuntimeError, "fdouble(double)"
+
+if fint(ai) != "fint:int":
+    raise RuntimeError, "fint(int)"
+
+if fint(5.0) != "fint:int":
+    raise RuntimeError, "fint(int)"
+    
+if fint(3) != "fint:int":
+    raise RuntimeError, "fint(int)"
+if fint(3.0) != "fint:int":
+    raise RuntimeError, "fint(int)"
+
+if fdouble(ad) != "fdouble:double":
+    raise RuntimeError, "fdouble(double)"
+if fdouble(3) != "fdouble:double":
+    raise RuntimeError, "fdouble(double)"
+if fdouble(3.0) != "fdouble:double":
+    raise RuntimeError, "fdouble(double)"
+
+if fid(3,3.0) != "fid:intdouble":
+    raise RuntimeError, "fid:intdouble"
+
+if fid(3.0,3) != "fid:doubleint":
+    raise RuntimeError, "fid:doubleint"
+
+if fid(ad,ai) != "fid:doubleint":
+    raise RuntimeError, "fid:doubleint"
+
+if fid(ai,ad) != "fid:intdouble":
+    raise RuntimeError, "fid:intdouble"
+
+
+
+if foo(3) != "foo:int":
+    raise RuntimeError, "foo(int)"
+
+if foo(3.0) != "foo:double":
+    raise RuntimeError, "foo(double)"
+
+if foo("hello") != "foo:char *":
+    raise RuntimeError, "foo(char *)"
+
+f = Foo()
+b = Bar()
+
+if foo(f) != "foo:Foo *":
+    raise RuntimeError, "foo(Foo *)"
+
+if foo(b) != "foo:Bar *":
+    raise RuntimeError, "foo(Bar *)"
+
+v = malloc_void(32)
+
+if foo(v) != "foo:void *":
+    raise RuntimeError, "foo(void *)"
+
+s = Spam()
+
+if s.foo(3) != "foo:int":
+    raise RuntimeError, "Spam::foo(int)"
+
+if s.foo(3.0) != "foo:double":
+    raise RuntimeError, "Spam::foo(double)"
+
+if s.foo("hello") != "foo:char *":
+    raise RuntimeError, "Spam::foo(char *)"
+
+if s.foo(f) != "foo:Foo *":
+    raise RuntimeError, "Spam::foo(Foo *)"
+
+if s.foo(b) != "foo:Bar *":
+    raise RuntimeError, "Spam::foo(Bar *)"
+
+if s.foo(v) != "foo:void *":
+    raise RuntimeError, "Spam::foo(void *)"
+
+if Spam_bar(3) != "bar:int":
+    raise RuntimeError, "Spam::bar(int)"
+
+if Spam_bar(3.0) != "bar:double":
+    raise RuntimeError, "Spam::bar(double)"
+
+if Spam_bar("hello") != "bar:char *":
+    raise RuntimeError, "Spam::bar(char *)"
+
+if Spam_bar(f) != "bar:Foo *":
+    raise RuntimeError, "Spam::bar(Foo *)"
+
+if Spam_bar(b) != "bar:Bar *":
+    raise RuntimeError, "Spam::bar(Bar *)"
+
+if Spam_bar(v) != "bar:void *":
+    raise RuntimeError, "Spam::bar(void *)"
+
+# Test constructors
+
+s = Spam()
+if s.type != "none":
+    raise RuntimeError, "Spam()"
+
+s = Spam(3)
+if s.type != "int":
+    raise RuntimeError, "Spam(int)"
+    
+s = Spam(3.4)
+if s.type != "double":
+    raise RuntimeError, "Spam(double)"
+
+s = Spam("hello")
+if s.type != "char *":
+    raise RuntimeError, "Spam(char *)"
+
+s = Spam(f)
+if s.type != "Foo *":
+    raise RuntimeError, "Spam(Foo *)"
+
+s = Spam(b)
+if s.type != "Bar *":
+    raise RuntimeError, "Spam(Bar *)"
+
+s = Spam(v)
+if s.type != "void *":
+    raise RuntimeError, "Spam(void *)"
+
+
+# unsigned long long
+ullmax = 9223372036854775807 #0xffffffffffffffff
+ullmaxd = 9007199254740992.0
+ullmin = 0
+ullmind = 0.0
+if ull(ullmin) != ullmin:
+    raise runtimeerror, "ull(ullmin)"
+if ull(ullmax) != ullmax:
+    raise runtimeerror, "ull(ullmax)"
+if ull(ullmind) != ullmind:
+    raise RuntimeError, "ull(ullmind)"
+if ull(ullmaxd) != ullmaxd:
+    raise RuntimeError, "ull(ullmaxd)"
+
+# long long
+llmax = 9223372036854775807 #0x7fffffffffffffff
+llmin = -9223372036854775808
+# these are near the largest  floats we can still convert into long long
+llmaxd = 9007199254740992.0
+llmind = -9007199254740992.0
+if ll(llmin) != llmin:
+    raise runtimeerror, "ll(llmin)"
+if ll(llmax) != llmax:
+    raise runtimeerror, "ll(llmax)"
+if ll(llmind) != llmind:
+    raise RuntimeError, "ll(llmind)"
+if ll(llmaxd) != llmaxd:
+    raise RuntimeError, "ll(llmaxd)"
+
+
+free_void(v)
diff --git a/trunk/Examples/test-suite/python/overload_simple_runme.py b/trunk/Examples/test-suite/python/overload_simple_runme.py
new file mode 100644
index 0000000..a78f372
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_simple_runme.py
@@ -0,0 +1,102 @@
+from overload_simple import *
+
+if foo(3) != "foo:int":
+    raise RuntimeError, "foo(int)"
+
+if foo(3.0) != "foo:double":
+    raise RuntimeError, "foo(double)"
+
+if foo("hello") != "foo:char *":
+    raise RuntimeError, "foo(char *)"
+
+f = Foo()
+b = Bar()
+
+if foo(f) != "foo:Foo *":
+    raise RuntimeError, "foo(Foo *)"
+
+if foo(b) != "foo:Bar *":
+    raise RuntimeError, "foo(Bar *)"
+
+v = malloc_void(32)
+
+if foo(v) != "foo:void *":
+    raise RuntimeError, "foo(void *)"
+
+s = Spam()
+
+if s.foo(3) != "foo:int":
+    raise RuntimeError, "Spam::foo(int)"
+
+if s.foo(3.0) != "foo:double":
+    raise RuntimeError, "Spam::foo(double)"
+
+if s.foo("hello") != "foo:char *":
+    raise RuntimeError, "Spam::foo(char *)"
+
+if s.foo(f) != "foo:Foo *":
+    raise RuntimeError, "Spam::foo(Foo *)"
+
+if s.foo(b) != "foo:Bar *":
+    raise RuntimeError, "Spam::foo(Bar *)"
+
+if s.foo(v) != "foo:void *":
+    raise RuntimeError, "Spam::foo(void *)"
+
+if Spam_bar(3) != "bar:int":
+    raise RuntimeError, "Spam::bar(int)"
+
+if Spam_bar(3.0) != "bar:double":
+    raise RuntimeError, "Spam::bar(double)"
+
+if Spam_bar("hello") != "bar:char *":
+    raise RuntimeError, "Spam::bar(char *)"
+
+if Spam_bar(f) != "bar:Foo *":
+    raise RuntimeError, "Spam::bar(Foo *)"
+
+if Spam_bar(b) != "bar:Bar *":
+    raise RuntimeError, "Spam::bar(Bar *)"
+
+if Spam_bar(v) != "bar:void *":
+    raise RuntimeError, "Spam::bar(void *)"
+
+# Test constructors
+
+s = Spam()
+if s.type != "none":
+    raise RuntimeError, "Spam()"
+
+s = Spam(3)
+if s.type != "int":
+    raise RuntimeError, "Spam(int)"
+    
+s = Spam(3.4)
+if s.type != "double":
+    raise RuntimeError, "Spam(double)"
+
+s = Spam("hello")
+if s.type != "char *":
+    raise RuntimeError, "Spam(char *)"
+
+s = Spam(f)
+if s.type != "Foo *":
+    raise RuntimeError, "Spam(Foo *)"
+
+s = Spam(b)
+if s.type != "Bar *":
+    raise RuntimeError, "Spam(Bar *)"
+
+s = Spam(v)
+if s.type != "void *":
+    raise RuntimeError, "Spam(void *)"
+
+
+
+
+
+free_void(v)
+
+
+a = ClassA()
+b = a.method1(1)
diff --git a/trunk/Examples/test-suite/python/overload_subtype_runme.py b/trunk/Examples/test-suite/python/overload_subtype_runme.py
new file mode 100644
index 0000000..6bf77dc
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_subtype_runme.py
@@ -0,0 +1,11 @@
+from overload_subtype import *
+
+f = Foo()
+b = Bar()
+
+if spam(f) != 1:
+    raise RuntimeError, "foo"
+
+if spam(b) != 2:
+    raise RuntimeError, "bar"
+
diff --git a/trunk/Examples/test-suite/python/overload_template_fast_runme.py b/trunk/Examples/test-suite/python/overload_template_fast_runme.py
new file mode 100644
index 0000000..a8d271d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_template_fast_runme.py
@@ -0,0 +1,145 @@
+from overload_template_fast import *
+f = foo()
+
+a = max(3,4)
+b = max(3.4,5.2)
+
+# mix 1
+if (mix1("hi") != 101):
+  raise RuntimeError, ("mix1(const char*)")
+
+if (mix1(1.0, 1.0) != 102):
+  raise RuntimeError, ("mix1(double, const double &)")
+
+if (mix1(1.0) != 103):
+  raise RuntimeError, ("mix1(double)")
+
+# mix 2
+if (mix2("hi") != 101):
+  raise RuntimeError, ("mix2(const char*)")
+
+if (mix2(1.0, 1.0) != 102):
+  raise RuntimeError, ("mix2(double, const double &)")
+
+if (mix2(1.0) != 103):
+  raise RuntimeError, ("mix2(double)")
+
+# mix 3
+if (mix3("hi") != 101):
+  raise RuntimeError, ("mix3(const char*)")
+
+if (mix3(1.0, 1.0) != 102):
+  raise RuntimeError, ("mix3(double, const double &)")
+
+if (mix3(1.0) != 103):
+  raise RuntimeError, ("mix3(double)")
+
+# Combination 1
+if (overtparams1(100) != 10):
+  raise RuntimeError, ("overtparams1(int)")
+
+if (overtparams1(100.0, 100) != 20):
+  raise RuntimeError, ("overtparams1(double, int)")
+
+# Combination 2
+if (overtparams2(100.0, 100) != 40):
+  raise RuntimeError, ("overtparams2(double, int)")
+
+# Combination 3
+if (overloaded() != 60):
+  raise RuntimeError, ("overloaded()")
+
+if (overloaded(100.0, 100) != 70):
+  raise RuntimeError, ("overloaded(double, int)")
+
+# Combination 4
+if (overloadedagain("hello") != 80):
+  raise RuntimeError, ("overloadedagain(const char *)")
+
+if (overloadedagain() != 90):
+  raise RuntimeError, ("overloadedagain(double)")
+
+# specializations
+if (specialization(10) != 202):
+  raise RuntimeError, ("specialization(int)")
+
+if (specialization(10.0) != 203):
+  raise RuntimeError, ("specialization(double)")
+
+if (specialization(10, 10) != 204):
+  raise RuntimeError, ("specialization(int, int)")
+
+if (specialization(10.0, 10.0) != 205):
+  raise RuntimeError, ("specialization(double, double)")
+
+if (specialization("hi", "hi") != 201):
+  raise RuntimeError, ("specialization(const char *, const char *)")
+
+
+# simple specialization
+xyz()
+xyz_int()
+xyz_double()
+
+# a bit of everything
+if (overload("hi") != 0):
+  raise RuntimeError, ("overload()")
+
+if (overload(1) != 10):
+  raise RuntimeError, ("overload(int t)")
+
+if (overload(1, 1) != 20):
+  raise RuntimeError, ("overload(int t, const int &)")
+
+if (overload(1, "hello") != 30):
+  raise RuntimeError, ("overload(int t, const char *)")
+
+k = Klass()
+if (overload(k) != 10):
+  raise RuntimeError, ("overload(Klass t)")
+
+if (overload(k, k) != 20):
+  raise RuntimeError, ("overload(Klass t, const Klass &)")
+
+if (overload(k, "hello") != 30):
+  raise RuntimeError, ("overload(Klass t, const char *)")
+
+if (overload(10.0, "hi") != 40):
+  raise RuntimeError, ("overload(double t, const char *)")
+
+if (overload() != 50):
+  raise RuntimeError, ("overload(const char *)")
+
+
+# everything put in a namespace
+if (nsoverload("hi") != 1000):
+  raise RuntimeError, ("nsoverload()")
+
+if (nsoverload(1) != 1010):
+  raise RuntimeError, ("nsoverload(int t)")
+
+if (nsoverload(1, 1) != 1020):
+  raise RuntimeError, ("nsoverload(int t, const int &)")
+
+if (nsoverload(1, "hello") != 1030):
+  raise RuntimeError, ("nsoverload(int t, const char *)")
+
+if (nsoverload(k) != 1010):
+  raise RuntimeError, ("nsoverload(Klass t)")
+
+if (nsoverload(k, k) != 1020):
+  raise RuntimeError, ("nsoverload(Klass t, const Klass &)")
+
+if (nsoverload(k, "hello") != 1030):
+  raise RuntimeError, ("nsoverload(Klass t, const char *)")
+
+if (nsoverload(10.0, "hi") != 1040):
+  raise RuntimeError, ("nsoverload(double t, const char *)")
+
+if (nsoverload() != 1050):
+  raise RuntimeError, ("nsoverload(const char *)")
+
+
+A.foo(1)
+b = B()
+b.foo(1)
diff --git a/trunk/Examples/test-suite/python/overload_template_runme.py b/trunk/Examples/test-suite/python/overload_template_runme.py
new file mode 100644
index 0000000..3fd77f3
--- /dev/null
+++ b/trunk/Examples/test-suite/python/overload_template_runme.py
@@ -0,0 +1,145 @@
+from overload_template import *
+f = foo()
+
+a = max(3,4)
+b = max(3.4,5.2)
+
+# mix 1
+if (mix1("hi") != 101):
+  raise RuntimeError, ("mix1(const char*)")
+
+if (mix1(1.0, 1.0) != 102):
+  raise RuntimeError, ("mix1(double, const double &)")
+
+if (mix1(1.0) != 103):
+  raise RuntimeError, ("mix1(double)")
+
+# mix 2
+if (mix2("hi") != 101):
+  raise RuntimeError, ("mix2(const char*)")
+
+if (mix2(1.0, 1.0) != 102):
+  raise RuntimeError, ("mix2(double, const double &)")
+
+if (mix2(1.0) != 103):
+  raise RuntimeError, ("mix2(double)")
+
+# mix 3
+if (mix3("hi") != 101):
+  raise RuntimeError, ("mix3(const char*)")
+
+if (mix3(1.0, 1.0) != 102):
+  raise RuntimeError, ("mix3(double, const double &)")
+
+if (mix3(1.0) != 103):
+  raise RuntimeError, ("mix3(double)")
+
+# Combination 1
+if (overtparams1(100) != 10):
+  raise RuntimeError, ("overtparams1(int)")
+
+if (overtparams1(100.0, 100) != 20):
+  raise RuntimeError, ("overtparams1(double, int)")
+
+# Combination 2
+if (overtparams2(100.0, 100) != 40):
+  raise RuntimeError, ("overtparams2(double, int)")
+
+# Combination 3
+if (overloaded() != 60):
+  raise RuntimeError, ("overloaded()")
+
+if (overloaded(100.0, 100) != 70):
+  raise RuntimeError, ("overloaded(double, int)")
+
+# Combination 4
+if (overloadedagain("hello") != 80):
+  raise RuntimeError, ("overloadedagain(const char *)")
+
+if (overloadedagain() != 90):
+  raise RuntimeError, ("overloadedagain(double)")
+
+# specializations
+if (specialization(10) != 202):
+  raise RuntimeError, ("specialization(int)")
+
+if (specialization(10.0) != 203):
+  raise RuntimeError, ("specialization(double)")
+
+if (specialization(10, 10) != 204):
+  raise RuntimeError, ("specialization(int, int)")
+
+if (specialization(10.0, 10.0) != 205):
+  raise RuntimeError, ("specialization(double, double)")
+
+if (specialization("hi", "hi") != 201):
+  raise RuntimeError, ("specialization(const char *, const char *)")
+
+
+# simple specialization
+xyz()
+xyz_int()
+xyz_double()
+
+# a bit of everything
+if (overload("hi") != 0):
+  raise RuntimeError, ("overload()")
+
+if (overload(1) != 10):
+  raise RuntimeError, ("overload(int t)")
+
+if (overload(1, 1) != 20):
+  raise RuntimeError, ("overload(int t, const int &)")
+
+if (overload(1, "hello") != 30):
+  raise RuntimeError, ("overload(int t, const char *)")
+
+k = Klass()
+if (overload(k) != 10):
+  raise RuntimeError, ("overload(Klass t)")
+
+if (overload(k, k) != 20):
+  raise RuntimeError, ("overload(Klass t, const Klass &)")
+
+if (overload(k, "hello") != 30):
+  raise RuntimeError, ("overload(Klass t, const char *)")
+
+if (overload(10.0, "hi") != 40):
+  raise RuntimeError, ("overload(double t, const char *)")
+
+if (overload() != 50):
+  raise RuntimeError, ("overload(const char *)")
+
+
+# everything put in a namespace
+if (nsoverload("hi") != 1000):
+  raise RuntimeError, ("nsoverload()")
+
+if (nsoverload(1) != 1010):
+  raise RuntimeError, ("nsoverload(int t)")
+
+if (nsoverload(1, 1) != 1020):
+  raise RuntimeError, ("nsoverload(int t, const int &)")
+
+if (nsoverload(1, "hello") != 1030):
+  raise RuntimeError, ("nsoverload(int t, const char *)")
+
+if (nsoverload(k) != 1010):
+  raise RuntimeError, ("nsoverload(Klass t)")
+
+if (nsoverload(k, k) != 1020):
+  raise RuntimeError, ("nsoverload(Klass t, const Klass &)")
+
+if (nsoverload(k, "hello") != 1030):
+  raise RuntimeError, ("nsoverload(Klass t, const char *)")
+
+if (nsoverload(10.0, "hi") != 1040):
+  raise RuntimeError, ("nsoverload(double t, const char *)")
+
+if (nsoverload() != 1050):
+  raise RuntimeError, ("nsoverload(const char *)")
+
+
+A_foo(1)
+b = B()
+b.foo(1)
diff --git a/trunk/Examples/test-suite/python/preproc_runme.py b/trunk/Examples/test-suite/python/preproc_runme.py
new file mode 100644
index 0000000..c989294
--- /dev/null
+++ b/trunk/Examples/test-suite/python/preproc_runme.py
@@ -0,0 +1,14 @@
+import preproc
+
+if preproc.endif != 1:
+  raise RuntimeError
+
+if preproc.define != 1:
+  raise RuntimeError
+
+if preproc.defined != 1:
+  raise RuntimeError
+
+if 2*preproc.one != preproc.two:
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/primitive_ref_runme.py b/trunk/Examples/test-suite/python/primitive_ref_runme.py
new file mode 100644
index 0000000..7ce872a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/primitive_ref_runme.py
@@ -0,0 +1,40 @@
+from primitive_ref import *
+
+if ref_int(3) != 3:
+    raise RuntimeError
+
+if ref_uint(3) != 3:
+    raise RuntimeError
+
+if ref_short(3) != 3:
+    raise RuntimeError
+
+if ref_ushort(3) != 3:
+    raise RuntimeError
+
+if ref_long(3) != 3:
+    raise RuntimeError
+
+if ref_ulong(3) != 3:
+    raise RuntimeError
+
+if ref_schar(3) != 3:
+    raise RuntimeError
+
+if ref_uchar(3) != 3:
+    raise RuntimeError
+
+if ref_float(3.5) != 3.5:
+    raise RuntimeError
+
+if ref_double(3.5) != 3.5:
+    raise RuntimeError
+
+if ref_bool(1) != 1:
+    raise RuntimeError
+
+if ref_char('x') != 'x':
+    raise RuntimeError
+
+if ref_over(0) != 0:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/primitive_types_runme.py b/trunk/Examples/test-suite/python/primitive_types_runme.py
new file mode 100644
index 0000000..02cc217
--- /dev/null
+++ b/trunk/Examples/test-suite/python/primitive_types_runme.py
@@ -0,0 +1,353 @@
+from primitive_types import *
+
+var_init()
+
+# assigning globals calls
+cvar.var_bool = sct_bool
+cvar.var_schar = sct_schar
+cvar.var_uchar = sct_uchar
+cvar.var_int = sct_int
+cvar.var_uint = sct_uint
+cvar.var_short = sct_short
+cvar.var_ushort = sct_ushort
+cvar.var_long = sct_long
+cvar.var_ulong = sct_ulong
+cvar.var_llong = sct_llong
+cvar.var_ullong = sct_ullong
+cvar.var_char = sct_char
+cvar.var_pchar = sct_pchar
+cvar.var_pcharc = sct_pcharc
+cvar.var_pint = sct_pint
+cvar.var_sizet = sct_sizet
+cvar.var_hello = sct_hello
+cvar.var_myint = sct_myint
+cvar.var_namet = def_namet
+cvar.var_parami = sct_parami
+cvar.var_paramd = sct_paramd
+cvar.var_paramc = sct_paramc
+
+v_check()
+
+def pyerror(name, val, cte):
+  print "bad val/cte", name, val, cte
+  raise RuntimeError
+  pass
+
+if cvar.var_bool != cct_bool: pyerror("bool", cvar.var_bool, cct_bool)
+if cvar.var_schar != cct_schar: pyerror("schar", cvar.var_schar, cct_schar)
+if cvar.var_uchar != cct_uchar: pyerror("uchar", cvar.var_uchar, cct_uchar)
+if cvar.var_int != cct_int: pyerror("int", cvar.var_int, cct_int)
+if cvar.var_uint != cct_uint: pyerror("uint", cvar.var_uint, cct_uint)
+if cvar.var_short != cct_short: pyerror("short", cvar.var_short, cct_short)
+if cvar.var_ushort != cct_ushort: pyerror("ushort", cvar.var_ushort, cct_ushort)
+if cvar.var_long != cct_long: pyerror("long", cvar.var_long, cct_long)
+if cvar.var_ulong != cct_ulong: pyerror("ulong", cvar.var_ulong, cct_ulong)
+if cvar.var_llong != cct_llong: pyerror("llong", cvar.var_llong, cct_llong)
+if cvar.var_ullong != cct_ullong: pyerror("ullong", cvar.var_ullong, cct_ullong)
+if cvar.var_char != cct_char: pyerror("char", cvar.var_char, cct_char)
+if cvar.var_pchar != cct_pchar: pyerror("pchar", cvar.var_pchar, cct_pchar)
+if cvar.var_pcharc != cct_pcharc: pyerror("pchar", cvar.var_pcharc, cct_pcharc)
+if cvar.var_pint != cct_pint: pyerror("pint", cvar.var_pint, cct_pint)
+if cvar.var_sizet != cct_sizet: pyerror("sizet", cvar.var_sizet, cct_sizet)
+if cvar.var_hello != cct_hello: pyerror("hello", cvar.var_hello, cct_hello)
+if cvar.var_myint != cct_myint: pyerror("myint", cvar.var_myint, cct_myint)
+if cvar.var_namet != def_namet: pyerror("name", cvar.var_namet, def_namet)
+
+class PyTest (TestDirector):
+  def __init__(self):
+    TestDirector.__init__(self)
+    pass
+  def ident(self, x):
+    return x
+  
+  def vval_bool(self, x): return self.ident(x)
+  def vval_schar(self, x): return self.ident(x)
+  def vval_uchar(self, x): return self.ident(x)
+  def vval_int(self, x): return self.ident(x)
+  def vval_uint(self, x): return self.ident(x)
+  def vval_short(self, x): return self.ident(x)
+  def vval_ushort(self, x): return self.ident(x)
+  def vval_long(self, x): return self.ident(x)
+  def vval_ulong(self, x): return self.ident(x)
+  def vval_llong(self, x): return self.ident(x)
+  def vval_ullong(self, x): return self.ident(x)
+  def vval_float(self, x): return self.ident(x)
+  def vval_double(self, x): return self.ident(x)
+  def vval_char(self, x): return self.ident(x)
+  def vval_pchar(self, x): return self.ident(x)
+  def vval_pcharc(self, x): return self.ident(x)
+  def vval_pint(self, x): return self.ident(x)
+  def vval_sizet(self, x): return self.ident(x)
+  def vval_hello(self, x): return self.ident(x)
+  def vval_myint(self, x): return self.ident(x)
+
+  def vref_bool(self, x): return self.ident(x)
+  def vref_schar(self, x): return self.ident(x)
+  def vref_uchar(self, x): return self.ident(x)
+  def vref_int(self, x): return self.ident(x)
+  def vref_uint(self, x): return self.ident(x)
+  def vref_short(self, x): return self.ident(x)
+  def vref_ushort(self, x): return self.ident(x)
+  def vref_long(self, x): return self.ident(x)
+  def vref_ulong(self, x): return self.ident(x)
+  def vref_llong(self, x): return self.ident(x)
+  def vref_ullong(self, x): return self.ident(x)
+  def vref_float(self, x): return self.ident(x)
+  def vref_double(self, x): return self.ident(x)
+  def vref_char(self, x): return self.ident(x)
+  def vref_pchar(self, x): return self.ident(x)
+  def vref_pcharc(self, x): return self.ident(x)
+  def vref_pint(self, x): return self.ident(x)
+  def vref_sizet(self, x): return self.ident(x)
+  def vref_hello(self, x): return self.ident(x)
+  def vref_myint(self, x): return self.ident(x)
+
+  pass
+
+
+t = Test()
+p = PyTest()
+
+
+# internal call check
+if t.c_check() != p.c_check():
+  raise RuntimeError, "bad director"
+
+p.var_bool = p.stc_bool
+p.var_schar = p.stc_schar
+p.var_uchar = p.stc_uchar
+p.var_int = p.stc_int
+p.var_uint = p.stc_uint
+p.var_short = p.stc_short
+p.var_ushort = p.stc_ushort
+p.var_long = p.stc_long
+p.var_ulong = p.stc_ulong
+p.var_llong = p.stc_llong
+p.var_ullong = p.stc_ullong
+p.var_char = p.stc_char
+p.var_pchar = sct_pchar
+p.var_pcharc = sct_pcharc
+p.var_pint = sct_pint
+p.var_sizet = sct_sizet
+p.var_hello = sct_hello
+p.var_myint = sct_myint
+p.var_namet = def_namet
+p.var_parami = sct_parami
+p.var_paramd = sct_paramd
+p.var_paramc = sct_paramc
+
+p.v_check()
+
+
+t.var_bool = t.stc_bool
+t.var_schar = t.stc_schar
+t.var_uchar = t.stc_uchar
+t.var_int = t.stc_int
+t.var_uint = t.stc_uint
+t.var_short = t.stc_short
+t.var_ushort = t.stc_ushort
+t.var_long = t.stc_long
+t.var_ulong = t.stc_ulong
+t.var_llong = t.stc_llong
+t.var_ullong = t.stc_ullong
+t.var_char = t.stc_char
+t.var_pchar = sct_pchar
+t.var_pcharc = sct_pcharc
+t.var_pint = sct_pint
+t.var_sizet = sct_sizet
+t.var_hello = sct_hello
+t.var_myint = sct_myint
+t.var_namet = def_namet
+t.var_parami = sct_parami
+t.var_paramd = sct_paramd
+t.var_paramc = sct_paramc
+
+t.v_check()
+
+# this value contains a '0' char!
+if def_namet != 'ho\0la':
+  print "bad namet", def_namet
+  raise RuntimeError
+
+t.var_namet = def_namet
+if t.var_namet != def_namet:
+  print "bad namet", t.var_namet, def_namet
+  raise RuntimeError
+
+t.var_namet = 'holac'
+
+if t.var_namet != 'holac':
+  print "bad namet", t.var_namet
+  raise RuntimeError
+
+t.var_namet = 'hol'
+
+if t.var_namet != 'hol':
+#if t.var_namet != 'hol\0\0':
+  print "bad namet", t.var_namet
+  raise RuntimeError
+
+
+if t.strlen('hile') != 4:
+  print t.strlen('hile')
+  raise RuntimeError, "bad string typemap"
+
+if t.strlen('hil\0') != 4:
+  raise RuntimeError, "bad string typemap"
+
+
+cvar.var_char = '\0'
+if cvar.var_char != '\0':
+  raise RuntimeError, "bad char '0' case"
+  
+cvar.var_char = 0
+if cvar.var_char != '\0':
+  raise RuntimeError, "bad char '0' case"
+
+cvar.var_namet = '\0'
+#if cvar.var_namet != '\0\0\0\0\0':
+if cvar.var_namet != '':
+  print 'hola', '', cvar.var_namet
+  raise RuntimeError, "bad char '\0' case"
+
+cvar.var_namet = ''
+#if cvar.var_namet != '\0\0\0\0\0':
+if cvar.var_namet != '':
+  raise RuntimeError, "bad char empty case"
+
+cvar.var_pchar = None
+if cvar.var_pchar != None:
+  raise RuntimeError, "bad None case"
+
+cvar.var_pchar = ''
+if cvar.var_pchar != '':
+  print '%c' % (cvar.var_pchar[0],)
+  raise RuntimeError, "bad char empty case"
+
+cvar.var_pcharc = None
+if cvar.var_pcharc != None:
+  raise RuntimeError, "bad None case"
+
+cvar.var_pcharc = ''
+if cvar.var_pcharc != '':
+  raise RuntimeError, "bad char empty case"
+
+
+#
+# creating a raw char*
+#
+pc = new_pchar(5)
+pchar_setitem(pc, 0, 'h')
+pchar_setitem(pc, 1, 'o')
+pchar_setitem(pc, 2, 'l')
+pchar_setitem(pc, 3, 'a')
+pchar_setitem(pc, 4, 0)
+
+
+if t.strlen(pc) != 4:
+  raise RuntimeError, "bad string typemap"
+
+cvar.var_pchar = pc
+if cvar.var_pchar != "hola":
+  print cvar.var_pchar
+  raise RuntimeError, "bad pointer case"
+
+cvar.var_namet = pc
+#if cvar.var_namet != "hola\0":
+if cvar.var_namet != "hola":
+  raise RuntimeError, "bad pointer case"
+
+delete_pchar(pc)
+
+#
+# Now when things should fail
+#
+
+
+try:
+  error = 0
+  a = t.var_uchar
+  t.var_uchar = 10000
+  error = 1
+except OverflowError:
+  if a != t.var_uchar:
+    error = 1
+  pass
+if error:
+  raise RuntimeError, "bad uchar typemap"
+
+
+
+try:
+  error = 0
+  a = t.var_char
+  t.var_char = '23'
+  error = 1
+except TypeError:
+  if a != t.var_char:
+    error = 1
+  pass 
+if error:
+  raise RuntimeError, "bad char typemap"
+
+try:
+  error = 0
+  a = t.var_uint
+  t.var_uint = -1
+  error = 1
+except OverflowError:
+  if a != t.var_uint:
+    error = 1
+  pass 
+if error:
+  raise RuntimeError, "bad uint typemap"
+
+#
+#
+try:
+  error = 0
+  a = t.var_namet
+  t.var_namet = '123456'
+  error = 1
+except TypeError:
+  if a != t.var_namet:
+    error = 1
+  pass 
+if error:
+  raise RuntimeError, "bad namet typemap"
+
+#
+#
+#
+t2 = p.vtest(t)
+if t.var_namet !=  t2.var_namet:
+  raise RuntimeError, "bad SWIGTYPE* typemap"
+  
+
+if cvar.fixsize != 'ho\0la\0\0\0':
+  raise RuntimeError, "bad FIXSIZE typemap"
+
+cvar.fixsize = 'ho'
+if cvar.fixsize != 'ho\0\0\0\0\0\0':
+  raise RuntimeError, "bad FIXSIZE typemap"
+
+
+f = Foo(3)
+f1 = fptr_val(f)
+f2 = fptr_ref(f)
+if f1._a != f2._a:
+  raise RuntimeError, "bad const ptr& typemap"
+  
+
+v = char_foo(1,3)
+if v !=3:
+  raise RuntimeError, "bad int typemap"
+
+s = char_foo(1,"hello")
+if s !="hello":
+  raise RuntimeError, "bad char* typemap"
+  
+
+v = SetPos(1,3)
+if v !=4:
+  raise RuntimeError, "bad int typemap"
diff --git a/trunk/Examples/test-suite/python/profiletest_runme.py b/trunk/Examples/test-suite/python/profiletest_runme.py
new file mode 100644
index 0000000..d4f07dc
--- /dev/null
+++ b/trunk/Examples/test-suite/python/profiletest_runme.py
@@ -0,0 +1,32 @@
+import _profiletest       
+import profiletest       
+
+a = profiletest.A()
+print a
+print a.this
+
+b = profiletest.B()
+fn = b.fn
+i = 50000
+while i:
+  a = fn(a) #1
+  a = fn(a) #2
+  a = fn(a) #3
+  a = fn(a) #4
+  a = fn(a) #5
+  a = fn(a) #6
+  a = fn(a) #7
+  a = fn(a) #8
+  a = fn(a) #9
+  a = fn(a) #10
+  a = fn(a) #1
+  a = fn(a) #2
+  a = fn(a) #3
+  a = fn(a) #4
+  a = fn(a) #5
+  a = fn(a) #6
+  a = fn(a) #7
+  a = fn(a) #8
+  a = fn(a) #9
+  a = fn(a) #20
+  i -= 1
diff --git a/trunk/Examples/test-suite/python/profiletestc_runme.py b/trunk/Examples/test-suite/python/profiletestc_runme.py
new file mode 100644
index 0000000..33461e4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/profiletestc_runme.py
@@ -0,0 +1,54 @@
+import _profiletest       
+#import profiletest       
+
+pa = _profiletest.new_A()
+pb  = _profiletest.new_B()
+fn = _profiletest.B_fn
+destroy = _profiletest.delete_A
+i = 50000
+a = pa
+while i:
+  a = fn(pb,a) #1
+  destroy(a)
+  a = fn(pb,a) #2
+  destroy(a)
+  a = fn(pb,a) #3
+  destroy(a)
+  a = fn(pb,a) #4
+  destroy(a)
+  a = fn(pb,a) #5
+  destroy(a)
+  a = fn(pb,a) #6
+  destroy(a)
+  a = fn(pb,a) #7
+  destroy(a)
+  a = fn(pb,a) #8
+  destroy(a)
+  a = fn(pb,a) #9
+  destroy(a)
+  a = fn(pb,a) #10
+  destroy(a)
+  a = fn(pb,a) #1
+  destroy(a)
+  a = fn(pb,a) #2
+  destroy(a)
+  a = fn(pb,a) #3
+  destroy(a)
+  a = fn(pb,a) #4
+  destroy(a)
+  a = fn(pb,a) #5
+  destroy(a)
+  a = fn(pb,a) #6
+  destroy(a)
+  a = fn(pb,a) #7
+  destroy(a)
+  a = fn(pb,a) #8
+  destroy(a)
+  a = fn(pb,a) #9
+  destroy(a)
+  a = fn(pb,a) #20
+  destroy(a)
+  i -= 1
+
+_profiletest.delete_A(pa)
+_profiletest.delete_B(pb)
diff --git a/trunk/Examples/test-suite/python/pythonswig.supp b/trunk/Examples/test-suite/python/pythonswig.supp
new file mode 100644
index 0000000..a9b03af
--- /dev/null
+++ b/trunk/Examples/test-suite/python/pythonswig.supp
@@ -0,0 +1,463 @@
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:_Z21SWIG_AsCharPtrAndSizeP7_objectPPcPmPi
+   fun:var_pcharc_set
+   fun:swig_varlink_setattr
+   fun:PyObject_SetAttr
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:var_pchar_set
+   fun:swig_varlink_setattr
+   fun:PyObject_SetAttr
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:_wrap_Test_var_pcharc_set
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:function_call
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+   fun:instance_setattr
+   fun:PyObject_SetAttr
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:_wrap_TestDirector_var_pcharc_set
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:function_call
+   fun:PyObject_Call
+   fun:instancemethod_call
+   fun:PyObject_Call
+   fun:call_method
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:_Z21SWIG_AsCharPtrAndSizeP7_objectPPcPmPi
+   fun:var_pcharc_set
+   fun:swig_varlink_setattr
+   fun:PyObject_SetAttr
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:_wrap_Test_var_pchar_set
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:function_call
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+   fun:instance_setattr
+   fun:PyObject_SetAttr
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znam
+   fun:_wrap_TestDirector_var_pchar_set
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:function_call
+   fun:PyObject_Call
+   fun:instancemethod_call
+   fun:PyObject_Call
+   fun:call_method
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:SWIG_Python_newvarlink
+   fun:SWIG_globals
+   fun:init_primitive_types
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:SWIG_Python_addvarlink
+   fun:init_primitive_types
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:PyFloat_FromDouble
+   fun:init_primitive_types
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:SWIG_Python_addvarlink
+   fun:init_primitive_types
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:realloc
+   fun:_PyString_Resize
+   fun:jcompile
+   fun:com_funcdef
+   fun:com_node
+   fun:com_node
+   fun:compile_node
+   fun:jcompile
+   fun:com_classdef
+   fun:com_node
+   fun:compile_node
+   fun:jcompile
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:_PyObject_GC_New
+   fun:PyDict_New
+   fun:PyModule_New
+   fun:PyImport_AddModule
+   fun:Py_InitModule4
+   fun:_PyExc_Init
+   fun:Py_InitializeEx
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z21createref_signed_chara
+   fun:_wrap_createref_signed_char
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z23createref_unsigned_charh
+   fun:_wrap_createref_unsigned_char
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z14createref_charc
+   fun:_wrap_createref_char
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z24createref_unsigned_shortt
+   fun:_wrap_createref_unsigned_short
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z15createref_shorts
+   fun:_wrap_createref_short
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z14createref_boolb
+   fun:_wrap_createref_bool
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z19createref_TestClass9TestClass
+   fun:_wrap_createref_TestClass
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z15createref_floatf
+   fun:_wrap_createref_float
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z22createref_unsigned_intj
+   fun:_wrap_createref_unsigned_int
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z13createref_inti
+   fun:_wrap_createref_int
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z16createref_doubled
+   fun:_wrap_createref_double
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z28createref_unsigned_long_longy
+   fun:_wrap_createref_unsigned_long_long
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z19createref_long_longx
+   fun:_wrap_createref_long_long
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z23createref_unsigned_longm
+   fun:_wrap_createref_unsigned_long
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_Z14createref_longl
+   fun:_wrap_createref_long
+   fun:PyEval_EvalFrame
+   fun:PyEval_EvalCodeEx
+   fun:PyEval_EvalCode
+   fun:PyRun_FileExFlags
+   fun:PyRun_SimpleFileExFlags
+   fun:Py_Main
+   fun:__libc_start_main
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:SWIG_Python_newvarlink
+   fun:SWIG_globals
+   fun:init_reference_global_vars
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:SWIG_Python_addvarlink
+   fun:init_reference_global_vars
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+}
+{
+   <insert a suppression name here>
+   Memcheck:Leak
+   fun:malloc
+   fun:SWIG_Python_addvarlink
+   fun:init_reference_global_vars
+   fun:_PyImport_LoadDynamicModule
+   fun:load_module
+   fun:import_submodule
+   fun:load_next
+   fun:import_module_ex
+   fun:PyImport_ImportModuleEx
+   fun:builtin___import__
+   fun:PyObject_Call
+   fun:PyEval_CallObjectWithKeywords
+}
diff --git a/trunk/Examples/test-suite/python/refcount_runme.py b/trunk/Examples/test-suite/python/refcount_runme.py
new file mode 100644
index 0000000..b429404
--- /dev/null
+++ b/trunk/Examples/test-suite/python/refcount_runme.py
@@ -0,0 +1,32 @@
+from refcount import *
+#
+# very innocent example
+#
+
+a = A3()
+b1 = B(a)
+b2 = B.create(a)
+
+
+
+if a.ref_count() != 3:
+  print "This program will crash... now"
+
+
+rca = b2.get_rca()
+b3 = B.create(rca)
+
+if a.ref_count() != 5:
+  print "This program will crash... now"
+
+
+v = vector_A(2)
+v[0] = a
+v[1] = a
+
+x = v[0]
+del v
+
+
+
+
diff --git a/trunk/Examples/test-suite/python/reference_global_vars_runme.py b/trunk/Examples/test-suite/python/reference_global_vars_runme.py
new file mode 100644
index 0000000..aa42ff5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/reference_global_vars_runme.py
@@ -0,0 +1,74 @@
+from reference_global_vars import *
+
+# const class reference variable
+if getconstTC().num != 33:
+    raise RuntimeError
+
+# primitive reference variables
+cvar.var_bool = createref_bool(0)
+if value_bool(cvar.var_bool) != 0:
+    raise RuntimeError
+
+cvar.var_bool = createref_bool(1)
+if value_bool(cvar.var_bool) != 1:
+    raise RuntimeError
+
+cvar.var_char = createref_char('w')
+if value_char(cvar.var_char) != 'w':
+    raise RuntimeError
+
+cvar.var_unsigned_char = createref_unsigned_char(10)
+if value_unsigned_char(cvar.var_unsigned_char) != 10:
+    raise RuntimeError
+
+cvar.var_signed_char = createref_signed_char(10)
+if value_signed_char(cvar.var_signed_char) != 10:
+    raise RuntimeError
+
+cvar.var_short = createref_short(10)
+if value_short(cvar.var_short) != 10:
+    raise RuntimeError
+
+cvar.var_unsigned_short = createref_unsigned_short(10)
+if value_unsigned_short(cvar.var_unsigned_short) != 10:
+    raise RuntimeError
+
+cvar.var_int = createref_int(10)
+if value_int(cvar.var_int) != 10:
+    raise RuntimeError
+
+cvar.var_unsigned_int = createref_unsigned_int(10)
+if value_unsigned_int(cvar.var_unsigned_int) != 10:
+    raise RuntimeError
+
+cvar.var_long = createref_long(10)
+if value_long(cvar.var_long) != 10:
+    raise RuntimeError
+
+cvar.var_unsigned_long = createref_unsigned_long(10)
+if value_unsigned_long(cvar.var_unsigned_long) != 10:
+    raise RuntimeError
+
+cvar.var_long_long = createref_long_long(0x6FFFFFFFFFFFFFF8)
+if value_long_long(cvar.var_long_long) != 0x6FFFFFFFFFFFFFF8:
+    raise RuntimeError
+
+#ull = abs(0xFFFFFFF2FFFFFFF0)
+ull = 55834574864
+cvar.var_unsigned_long_long = createref_unsigned_long_long(ull)
+if value_unsigned_long_long(cvar.var_unsigned_long_long) != ull:
+    raise RuntimeError
+
+cvar.var_float = createref_float(10.5)
+if value_float(cvar.var_float) != 10.5:
+    raise RuntimeError
+
+cvar.var_double = createref_double(10.5)
+if value_double(cvar.var_double) != 10.5:
+    raise RuntimeError
+
+# class reference variable
+cvar.var_TestClass = createref_TestClass(TestClass(20))
+if value_TestClass(cvar.var_TestClass).num != 20:
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/rename_scope_runme.py b/trunk/Examples/test-suite/python/rename_scope_runme.py
new file mode 100644
index 0000000..faea6a8
--- /dev/null
+++ b/trunk/Examples/test-suite/python/rename_scope_runme.py
@@ -0,0 +1,12 @@
+from rename_scope import *
+
+a = Natural_UP()
+b = Natural_BP()
+
+if a.rtest() != 1:
+    raise RuntimeError
+
+if b.rtest() != 1:
+    raise RuntimeError
+
+f = equals
diff --git a/trunk/Examples/test-suite/python/ret_by_value_runme.py b/trunk/Examples/test-suite/python/ret_by_value_runme.py
new file mode 100644
index 0000000..0b2d7fd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/ret_by_value_runme.py
@@ -0,0 +1,8 @@
+import ret_by_value
+
+a = ret_by_value.get_test()
+if a.myInt != 100:
+    raise RuntimeError
+
+if a.myShort != 200:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/return_const_value_runme.py b/trunk/Examples/test-suite/python/return_const_value_runme.py
new file mode 100644
index 0000000..516e9f5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/return_const_value_runme.py
@@ -0,0 +1,12 @@
+import return_const_value
+import sys
+
+p = return_const_value.Foo_ptr.getPtr()
+if (p.getVal() != 17):
+	print "Runtime test1 faild. p.getVal()=", p.getVal()
+	sys.exit(1)
+
+p = return_const_value.Foo_ptr.getConstPtr()
+if (p.getVal() != 17):
+	print "Runtime test2 faild. p.getVal()=", p.getVal()
+	sys.exit(1)
diff --git a/trunk/Examples/test-suite/python/simutry.i b/trunk/Examples/test-suite/python/simutry.i
new file mode 100644
index 0000000..addea14
--- /dev/null
+++ b/trunk/Examples/test-suite/python/simutry.i
@@ -0,0 +1,98 @@
+%module simutry
+
+%include "std_vector.i"
+
+%inline {
+
+namespace simuPOP
+{
+  // some simple pop class
+  template <class Type>
+  struct Population {
+    int m_a;
+    Population(int a):m_a(a){}
+  };
+
+  // base operator, output pop.m_a
+  template<class Pop>
+  struct Operator
+  {
+    Pop m_pop;
+    Operator(int a):m_pop(a){}
+    virtual ~Operator()
+    {
+    }
+    
+    virtual int func() const 
+    { return m_pop.m_a; }
+  };
+
+  // derived operator, output double of pop.m_a
+  template<class Pop>
+  struct DerivedOperator: public Operator<Pop>
+  {
+    DerivedOperator(int a):Operator<Pop>(a){}
+    virtual int func() const 
+    { return 2*this->m_pop.m_a; }
+  };
+
+}
+
+}
+
+#if 1
+namespace simuPOP
+{
+  %template(population)   Population< std::pair<unsigned long,unsigned long> >;
+}      
+
+%inline 
+{
+  namespace simuPOP
+  {
+    typedef Population< std::pair<unsigned long,unsigned long> > pop;
+  }
+}
+#else
+%inline 
+{
+  namespace simuPOP
+  {
+    //  %template(population)          Population< std::pair<unsigned long,unsigned long> >;
+    
+    struct pop {
+      int m_a;
+      pop(int a):m_a(a){}
+    };
+  }
+}
+#endif
+
+
+namespace simuPOP
+{
+ %template(baseOperator)        Operator< pop >;
+ %template(derivedOperator)     DerivedOperator< pop >;
+}
+
+
+
+namespace std
+{
+  %template(vectorop)   vector< simuPOP::Operator<simuPOP::pop> * >;
+}
+
+%inline
+{
+namespace simuPOP
+{
+  // test function, use of a vector of Operator*
+  void test( const std::vector< Operator<pop>*>& para)
+  {
+    for( size_t i =0; i < para.size(); ++i)
+    para[i]->func();
+  }
+}
+}
+
+
diff --git a/trunk/Examples/test-suite/python/smart_pointer_extend_runme.py b/trunk/Examples/test-suite/python/smart_pointer_extend_runme.py
new file mode 100644
index 0000000..969757b
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_extend_runme.py
@@ -0,0 +1,34 @@
+from smart_pointer_extend import *
+
+f = Foo()
+b = Bar(f)
+
+if b.extension() != f.extension():
+  raise RuntimeError
+
+
+b = CBase()
+d = CDerived()
+p = CPtr()
+
+if b.bar() != p.bar():
+  raise RuntimeError
+
+if d.foo() != p.foo():
+  raise RuntimeError
+
+if b.hello() != p.hello():
+  raise RuntimeError
+
+
+
+d = DFoo()
+
+dp = DPtrFoo(d)
+
+if d.SExt(1) != dp.SExt(1):
+  raise RuntimeError
+
+if d.Ext(1) != dp.Ext(1):
+  raise RuntimeError
+  
diff --git a/trunk/Examples/test-suite/python/smart_pointer_member_runme.py b/trunk/Examples/test-suite/python/smart_pointer_member_runme.py
new file mode 100644
index 0000000..70e6556
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_member_runme.py
@@ -0,0 +1,30 @@
+from smart_pointer_member import *
+
+f = Foo()
+f.y = 1
+
+if f.y != 1:
+  raise RuntimeError
+
+b = Bar(f)
+b.y = 2
+
+if f.y != 2:
+  print f.y
+  print b.y
+  raise RuntimeError
+
+if b.x != f.x:
+  raise RuntimeError
+
+if b.z != f.z:
+  raise RuntimeError
+
+if Foo.z == Bar.z:
+  raise RuntimeError
+
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/python/smart_pointer_multi_runme.py b/trunk/Examples/test-suite/python/smart_pointer_multi_runme.py
new file mode 100644
index 0000000..c170530
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_multi_runme.py
@@ -0,0 +1,15 @@
+from smart_pointer_multi import *
+
+f = Foo()
+b = Bar(f)
+s = Spam(b)
+g = Grok(b)
+
+s.x = 3
+if s.getx() != 3:
+    raise RuntimeError
+
+g.x = 4
+if g.getx() != 4:
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py b/trunk/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py
new file mode 100644
index 0000000..ebf4c9b
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py
@@ -0,0 +1,15 @@
+from smart_pointer_multi_typedef import *
+
+f = Foo()
+b = Bar(f)
+s = Spam(b)
+g = Grok(b)
+
+s.x = 3
+if s.getx() != 3:
+    raise RuntimeError
+
+g.x = 4
+if g.getx() != 4:
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/smart_pointer_not_runme.py b/trunk/Examples/test-suite/python/smart_pointer_not_runme.py
new file mode 100644
index 0000000..4c90b37
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_not_runme.py
@@ -0,0 +1,42 @@
+from smart_pointer_not import *
+
+f = Foo()
+b = Bar(f)
+s = Spam(f)
+g = Grok(f)
+
+try:
+    x = b.x
+    print "Error! b.x"
+except:
+    pass
+
+try:
+    x = s.x
+    print "Error! s.x"    
+except:
+    pass
+
+try:
+    x = g.x
+    print "Error! g.x"
+except:
+    pass
+
+try:
+    x = b.getx()
+    print "Error! b.getx()"    
+except:
+    pass
+
+try:
+    x = s.getx()
+    print "Error! s.getx()"        
+except:
+    pass
+
+try:
+    x = g.getx()
+    print "Error! g.getx()"
+except:
+    pass
diff --git a/trunk/Examples/test-suite/python/smart_pointer_overload_runme.py b/trunk/Examples/test-suite/python/smart_pointer_overload_runme.py
new file mode 100644
index 0000000..c9fd3a5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_overload_runme.py
@@ -0,0 +1,21 @@
+from smart_pointer_overload import *
+
+f = Foo()
+b = Bar(f)
+
+
+if f.test(3) != 1:
+    raise RuntimeError
+if f.test(3.5) != 2:
+    raise RuntimeError
+if f.test("hello") != 3:
+    raise RuntimeError
+
+if b.test(3) != 1:
+    raise RuntimeError
+if b.test(3.5) != 2:
+    raise RuntimeError
+if b.test("hello") != 3:
+    raise RuntimeError
+
+
diff --git a/trunk/Examples/test-suite/python/smart_pointer_rename_runme.py b/trunk/Examples/test-suite/python/smart_pointer_rename_runme.py
new file mode 100644
index 0000000..c6d2227
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_rename_runme.py
@@ -0,0 +1,13 @@
+from smart_pointer_rename import *
+
+f = Foo()
+b = Bar(f)
+
+if b.test() != 3:
+    raise RuntimeError
+
+if b.ftest1(1) != 1:
+    raise RuntimeError
+
+if b.ftest2(2,3) != 2:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/smart_pointer_simple_runme.py b/trunk/Examples/test-suite/python/smart_pointer_simple_runme.py
new file mode 100644
index 0000000..95b678a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_simple_runme.py
@@ -0,0 +1,13 @@
+from smart_pointer_simple import *
+
+f = Foo()
+b = Bar(f)
+
+b.x = 3
+if b.getx() != 3:
+    raise RuntimeError
+
+fp = b.__deref__()
+fp.x = 4
+if fp.getx() != 4:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/smart_pointer_templatevariables_runme.py b/trunk/Examples/test-suite/python/smart_pointer_templatevariables_runme.py
new file mode 100644
index 0000000..367dcf3
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_templatevariables_runme.py
@@ -0,0 +1,17 @@
+from smart_pointer_templatevariables import *
+
+d = DiffImContainerPtr_D(create(1234, 5678))
+
+if (d.id != 1234):
+  raise RuntimeError
+#if (d.xyz != 5678):
+#  raise RuntimeError
+
+d.id = 4321
+#d.xyz = 8765
+
+if (d.id != 4321):
+  raise RuntimeError
+#if (d.xyz != 8765):
+#  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/smart_pointer_typedef_runme.py b/trunk/Examples/test-suite/python/smart_pointer_typedef_runme.py
new file mode 100644
index 0000000..eee0537
--- /dev/null
+++ b/trunk/Examples/test-suite/python/smart_pointer_typedef_runme.py
@@ -0,0 +1,13 @@
+from smart_pointer_typedef import *
+
+f = Foo()
+b = Bar(f)
+
+b.x = 3
+if b.getx() != 3:
+    raise RuntimeError
+
+fp = b.__deref__()
+fp.x = 4
+if fp.getx() != 4:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/sneaky1_runme.py b/trunk/Examples/test-suite/python/sneaky1_runme.py
new file mode 100644
index 0000000..9c2c32f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/sneaky1_runme.py
@@ -0,0 +1,5 @@
+import sneaky1
+x = sneaky1.add(3,4)
+y = sneaky1.subtract(3,4)
+z = sneaky1.mul(3,4)
+w = sneaky1.divide(3,4)
diff --git a/trunk/Examples/test-suite/python/static_const_member_2_runme.py b/trunk/Examples/test-suite/python/static_const_member_2_runme.py
new file mode 100644
index 0000000..0817263
--- /dev/null
+++ b/trunk/Examples/test-suite/python/static_const_member_2_runme.py
@@ -0,0 +1,16 @@
+from static_const_member_2 import *
+
+c = Test_int()
+try:
+    a = c.forward_field
+    a = c.current_profile
+    a = c.RightIndex
+    a = Test_int.backward_field
+    a = Test_int.LeftIndex
+    a = Test_int.cavity_flags
+except:
+    raise RuntimeError
+
+
+if Foo.BAZ.val != 2*Foo.BAR.val:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/std_containers.i b/trunk/Examples/test-suite/python/std_containers.i
new file mode 100644
index 0000000..a1d39e7
--- /dev/null
+++ b/trunk/Examples/test-suite/python/std_containers.i
@@ -0,0 +1,199 @@
+%module std_containers
+
+%{
+#include <set>
+%}
+%include std_vector.i
+%include std_string.i
+%include std_deque.i
+%include std_list.i
+%include std_set.i
+%include std_multiset.i
+%include std_pair.i
+%include std_map.i
+%include std_multimap.i
+%include std_complex.i
+
+%template() std::vector<double>;
+%template() std::pair<std::string, int>;
+%template() std::pair<int,double>;
+
+%template() std::vector< std::vector<double > > ;
+%template(ccube) std::vector< std::vector< std::vector<double > > >;
+
+%inline 
+{ 
+  typedef
+    std::vector<std::vector<std::vector<double > > >
+    ccube;
+ 
+  ccube cident(const ccube& c)
+  {
+    return c;
+  }
+
+  struct C
+  {
+  };
+}
+
+
+%template(map_si)  std::map<std::string, int>;
+%template(pair_iC)  std::pair<int, C*>;
+%template(map_iC)  std::map<int, C*>;
+%template(mmap_si)  std::multimap<std::string, int>;
+%template(set_i) std::set<int>;
+%template(multiset_i) std::multiset<int>;
+%template(list_i) std::list<int>;
+%template(deque_i) std::deque<int>;
+
+%template(vector_b) std::vector<bool>;
+%template(vector_i) std::vector<int>;
+%template(vector_c) std::vector<std::complex<double> >;
+%template(vector_ui) std::vector<unsigned int>;
+
+%template(bmatrix) std::vector<std::vector<bool> >;
+%template(imatrix) std::vector<std::vector<int> >;
+%template(cmatrix) std::vector<std::vector<std::complex<double> > >;
+
+%apply std::vector<int> *INOUT {std::vector<int> *INOUT2};
+
+%inline 
+{
+  typedef std::vector<std::vector<int> >  imatrix;
+  imatrix midenti(const imatrix& v)
+  {
+    return v;
+  }
+
+  typedef std::vector<std::vector<bool> >  bmatrix;
+  bmatrix midentb(const bmatrix& v)
+  {
+    return v;
+  }
+
+  std::map<int,C*> mapidentc(const std::map<int,C*>& v)
+  {
+    return v;
+  }
+
+  std::map<int,int> mapidenti(const std::map<int,int>& v)
+  {
+    return v;
+  }
+
+  std::map<std::string,int> mapident(const std::map<std::string,int>& v)
+  {
+    return v;
+  }
+
+  std::multimap<std::string,int> mapident(const std::multimap<std::string,int>& v)
+  {
+    return v;
+  }
+
+  std::vector<int> vident(const std::vector<int>& v)
+  {
+    return v;
+  }
+
+  std::set<int> sident(const std::set<int>& v)
+  {
+    return v;
+  }
+
+  std::vector<unsigned int> videntu(const std::vector<unsigned int>& v)
+  {
+    return v;
+  }
+
+
+  int get_elem(const std::vector<int>& v, int index)
+  {
+    return v[index];
+  }
+
+  std::pair<int,double> pident(const std::pair<int,double>& p) 
+  {
+    return p;
+  }
+
+  void
+  v_inout(std::vector<int> *INOUT) {
+    *INOUT = *INOUT;
+  }  
+
+  void
+  v_inout2(std::vector<int> *INOUT, std::vector<int> *INOUT2) {
+    std::swap(*INOUT, *INOUT2);
+  } 
+
+}
+
+
+%{
+  
+  template <class C> struct Param 
+  {
+  };	    
+%}
+
+
+template <class C> struct Param 
+{
+};
+
+
+%template(Param_c) Param<std::complex<double> >;
+%inline 
+{
+  int hello(Param<std::complex<double> > c)
+  {
+    return 0;
+  }
+}
+
+%inline 
+{
+  struct A 
+  {
+    A(int aa = 0) : a(aa)
+    {
+    }
+    int a;
+  };  
+}
+
+%template() std::pair<A,int>;
+%template(pair_iA) std::pair<int,A>;
+%template(vector_piA) std::vector<std::pair<int,A> >;
+
+
+%inline {
+  std::pair<A,int> ident(std::pair<int,A> a, const std::pair<int,int>& b)
+  {
+    return std::pair<A,int>();
+  }  
+
+
+  std::vector<std::pair<int,A> > pia_vident(std::vector<std::pair<int,A> > a )
+  {
+    return a;
+  }  
+
+  struct Foo
+  {
+    Foo(int i) {
+    }
+  };
+  
+}
+
+
+%std_nodefconst_type(Foo);
+
+%template(vector_Foo) std::vector<Foo>;
+%template(deque_Foo) std::deque<Foo>;
+%template(list_Foo) std::list<Foo>;
+
+
diff --git a/trunk/Examples/test-suite/python/std_containers_runme.py b/trunk/Examples/test-suite/python/std_containers_runme.py
new file mode 100644
index 0000000..bed59bb
--- /dev/null
+++ b/trunk/Examples/test-suite/python/std_containers_runme.py
@@ -0,0 +1,119 @@
+import sys
+import std_containers
+
+
+cube = (((1, 2), (3, 4)), ((5, 6), (7, 8)))
+
+icube = std_containers.cident(cube)
+for i in range(0,len(cube)):
+  if cube[i] != icube[i]:
+    raise RuntimeError, "bad cident"
+
+
+p = (1,2)
+if p != std_containers.pident(p):
+  raise RuntimeError, "bad pident"
+
+v = (1,2,3,4,5,6)
+iv = std_containers.vident(v)
+for i in range(0,len(v)):
+  if v[i] != iv[i]:
+    raise RuntimeError, "bad vident"
+
+
+
+iv = std_containers.videntu(v)
+for i in range(0,len(v)):
+  if v[i] != iv[i]:
+    raise RuntimeError, "bad videntu"
+
+
+vu = std_containers.vector_ui(v)
+if vu[2] != std_containers.videntu(vu)[2]:
+  raise RuntimeError, "bad videntu"
+  
+
+if v[0:3][1] != vu[0:3][1]:
+  print v[0:3][1], vu[0:3][1]
+  raise RuntimeError, "bad getslice"
+  
+
+m = ((1,2,3),(2,3),(3,4))
+im = std_containers.midenti(m)
+
+for i in range(0,len(m)):
+  for j in range(0,len(m[i])):
+    if m[i][j] != im[i][j]:
+      raise RuntimeError, "bad getslice"
+
+m = ((1,0,1),(1,1),(1,1))
+im = std_containers.midentb(m)
+for i in range(0,len(m)):
+  for j in range(0,len(m[i])):
+    if m[i][j] != im[i][j]:
+      raise RuntimeError, "bad getslice"
+
+
+mi = std_containers.imatrix(m)
+mc = std_containers.cmatrix(m)
+if mi[0][1] != mc[0][1]:
+  raise RuntimeError, "bad matrix"
+
+
+map ={}
+map['hello'] = 1
+map['hi'] = 2
+map['3'] = 2
+
+imap = std_containers.mapident(map)
+for k in map:
+  if map[k] != imap[k]:
+    raise RuntimeError, "bad map"
+
+
+mapc ={}
+c1 = std_containers.C()
+c2 = std_containers.C()
+mapc[1] = c1.this
+mapc[2] = c2
+
+std_containers.mapidentc(mapc)
+
+
+vi = std_containers.vector_i((2,2,3,4))
+
+
+v = (1,2)
+v1 = std_containers.v_inout(vi)
+vi[1], v1[1]
+
+v1,v2 = ((1,2),(3,4))
+v1,v2 = std_containers.v_inout2(v1,v2)
+
+a1 = std_containers.A(1)
+a2 = std_containers.A(2)
+
+p1 = (1,a1)
+p2 = (2,a2)
+v = (p1,p2)
+v2= std_containers.pia_vident(v)
+
+v2[0][1].a
+v2[1][1].a
+
+v3 = std_containers.vector_piA(v2)
+
+v3[0][1].a
+v3[1][1].a
+
+s = std_containers.set_i()
+s.append(1)
+s.append(2)
+s.append(3)
+j=1
+for i in s:
+  if i != j:
+    raise RuntimeError
+  j = j + 1
+
+
diff --git a/trunk/Examples/test-suite/python/struct_rename_runme.py b/trunk/Examples/test-suite/python/struct_rename_runme.py
new file mode 100644
index 0000000..880c416
--- /dev/null
+++ b/trunk/Examples/test-suite/python/struct_rename_runme.py
@@ -0,0 +1,3 @@
+import struct_rename
+
+b = struct_rename.Bar()
diff --git a/trunk/Examples/test-suite/python/struct_value_runme.py b/trunk/Examples/test-suite/python/struct_value_runme.py
new file mode 100644
index 0000000..727996f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/struct_value_runme.py
@@ -0,0 +1,9 @@
+import struct_value
+
+b = struct_value.Bar()
+
+b.a.x = 3
+if b.a.x != 3: raise RuntimeError
+
+b.b.x = 3
+if b.b.x != 3: raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/swigobject.i b/trunk/Examples/test-suite/python/swigobject.i
new file mode 100644
index 0000000..2e77969
--- /dev/null
+++ b/trunk/Examples/test-suite/python/swigobject.i
@@ -0,0 +1,25 @@
+%module swigobject
+
+
+
+%inline
+{
+  struct A {
+    char name[4];
+  };
+
+  const char* pointer_str(A *a){
+    static char result[1024];
+    sprintf(result,"0x%lx", (unsigned long)(void *)a);
+    return result;
+  }
+
+  A *a_ptr(A *a){
+    return a;
+  }
+
+
+  void *v_ptr(void *a){
+    return a;
+  }
+}
diff --git a/trunk/Examples/test-suite/python/swigobject_runme.py b/trunk/Examples/test-suite/python/swigobject_runme.py
new file mode 100644
index 0000000..7f629e1
--- /dev/null
+++ b/trunk/Examples/test-suite/python/swigobject_runme.py
@@ -0,0 +1,28 @@
+
+from swigobject import  *
+
+a = A()
+
+
+a1 = a_ptr(a)
+a2 = a_ptr(a)
+
+if a1.this != a2.this:
+  raise RuntimeError
+  
+
+lthis = long(a.this)
+xstr1 = "0x%x" % (lthis,)
+xstr2 = pointer_str(a)
+
+if xstr1 != xstr2:
+  print  xstr1, xstr2
+  raise RuntimeError
+
+s = str(a.this)
+r = repr(a.this)
+
+v1 = v_ptr(a)
+v2 = v_ptr(a)
+if long(v1) != long(v2):
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/tag_no_clash_with_variable_runme.i b/trunk/Examples/test-suite/python/tag_no_clash_with_variable_runme.i
new file mode 100644
index 0000000..0f8fdaf
--- /dev/null
+++ b/trunk/Examples/test-suite/python/tag_no_clash_with_variable_runme.i
@@ -0,0 +1,3 @@
+import enum_tag_no_clash_with_variable
+
+error_action = error_action
diff --git a/trunk/Examples/test-suite/python/template_construct_runme.py b/trunk/Examples/test-suite/python/template_construct_runme.py
new file mode 100644
index 0000000..3409fdd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_construct_runme.py
@@ -0,0 +1 @@
+import template_construct
diff --git a/trunk/Examples/test-suite/python/template_default_arg_runme.py b/trunk/Examples/test-suite/python/template_default_arg_runme.py
new file mode 100644
index 0000000..235a231
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_default_arg_runme.py
@@ -0,0 +1,98 @@
+import template_default_arg
+
+
+helloInt = template_default_arg.Hello_int()
+helloInt.foo(template_default_arg.Hello_int.hi)
+
+
+x = template_default_arg.X_int()
+if (x.meth(20.0, 200) != 200):
+  raise RuntimeError, ("X_int test 1 failed")
+if (x.meth(20) != 20):
+  raise RuntimeError, ("X_int test 2 failed")
+if (x.meth() != 0):
+  raise RuntimeError, ("X_int test 3 failed")
+
+
+
+y = template_default_arg.Y_unsigned()
+if (y.meth(20.0, 200) != 200):
+  raise RuntimeError, ("Y_unsigned test 1 failed")
+if (y.meth(20) != 20):
+  raise RuntimeError, ("Y_unsigned test 2 failed")
+if (y.meth() != 0):
+  raise RuntimeError, ("Y_unsigned test 3 failed")
+
+
+
+x = template_default_arg.X_longlong()
+x = template_default_arg.X_longlong(20.0)
+x = template_default_arg.X_longlong(20.0, 200L)
+
+
+x = template_default_arg.X_int()
+x = template_default_arg.X_int(20.0)
+x = template_default_arg.X_int(20.0, 200)
+
+
+x = template_default_arg.X_hello_unsigned()
+x = template_default_arg.X_hello_unsigned(20.0)
+x = template_default_arg.X_hello_unsigned(20.0, template_default_arg.Hello_int())
+
+
+y = template_default_arg.Y_hello_unsigned()
+y.meth(20.0, template_default_arg.Hello_int())
+y.meth(template_default_arg.Hello_int())
+y.meth()
+
+
+
+fz = template_default_arg.Foo_Z_8()
+x = template_default_arg.X_Foo_Z_8()
+fzc = x.meth(fz)
+
+
+# Templated functions
+
+# plain function: int ott(Foo<int>)
+if (template_default_arg.ott(template_default_arg.Foo_int()) != 30):
+  raise RuntimeError, ("ott test 1 failed")
+
+# %template(ott) ott<int, int>
+if (template_default_arg.ott() != 10):
+  raise RuntimeError, ("ott test 2 failed")
+if (template_default_arg.ott(1) != 10):
+  raise RuntimeError, ("ott test 3 failed")
+if (template_default_arg.ott(1, 1) != 10):
+  raise RuntimeError, ("ott test 4 failed")
+
+if (template_default_arg.ott("hi") != 20):
+  raise RuntimeError, ("ott test 5 failed")
+if (template_default_arg.ott("hi", 1) != 20):
+  raise RuntimeError, ("ott test 6 failed")
+if (template_default_arg.ott("hi", 1, 1) != 20):
+  raise RuntimeError, ("ott test 7 failed")
+
+# %template(ott) ott<const char *>
+if (template_default_arg.ottstring(template_default_arg.Hello_int(), "hi") != 40):
+  raise RuntimeError, ("ott test 8 failed")
+
+if (template_default_arg.ottstring(template_default_arg.Hello_int()) != 40):
+  raise RuntimeError, ("ott test 9 failed")
+
+# %template(ott) ott<int>
+if (template_default_arg.ottint(template_default_arg.Hello_int(), 1) != 50):
+  raise RuntimeError, ("ott test 10 failed")
+
+if (template_default_arg.ottint(template_default_arg.Hello_int()) != 50):
+  raise RuntimeError, ("ott test 11 failed")
+
+# %template(ott) ott<double>
+if (template_default_arg.ott(template_default_arg.Hello_int(), 1.0) != 60):
+  raise RuntimeError, ("ott test 12 failed")
+
+if (template_default_arg.ott(template_default_arg.Hello_int()) != 60):
+  raise RuntimeError, ("ott test 13 failed")
+
+
+
diff --git a/trunk/Examples/test-suite/python/template_extend1_runme.py b/trunk/Examples/test-suite/python/template_extend1_runme.py
new file mode 100644
index 0000000..b467951
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_extend1_runme.py
@@ -0,0 +1,10 @@
+import template_extend1
+
+a = template_extend1.lBaz()
+b = template_extend1.dBaz()
+
+if a.foo() != "lBaz::foo":
+    raise RuntimeError
+
+if b.foo() != "dBaz::foo":
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/template_extend2_runme.py b/trunk/Examples/test-suite/python/template_extend2_runme.py
new file mode 100644
index 0000000..a5f222f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_extend2_runme.py
@@ -0,0 +1,10 @@
+import template_extend2
+
+a = template_extend2.lBaz()
+b = template_extend2.dBaz()
+
+if a.foo() != "lBaz::foo":
+    raise RuntimeError
+
+if b.foo() != "dBaz::foo":
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/template_inherit_runme.py b/trunk/Examples/test-suite/python/template_inherit_runme.py
new file mode 100644
index 0000000..bb1465a
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_inherit_runme.py
@@ -0,0 +1,53 @@
+from template_inherit import *
+a = FooInt()
+b = FooDouble()
+c = BarInt()
+d = BarDouble()
+e = FooUInt()
+f = BarUInt()
+
+if a.blah() != "Foo":
+    raise ValueError
+
+if b.blah() != "Foo":
+    raise ValueError
+
+if e.blah() != "Foo":
+    raise ValueError
+
+if c.blah() != "Bar":
+    raise ValueError
+
+if d.blah() != "Bar":
+    raise ValueError
+
+if f.blah() != "Bar":
+    raise ValueError
+
+if c.foomethod() != "foomethod":
+    raise ValueError
+
+if d.foomethod() != "foomethod":
+    raise ValueError
+
+if f.foomethod() != "foomethod":
+    raise ValueError
+
+if invoke_blah_int(a) != "Foo":
+    raise ValueError
+
+if invoke_blah_int(c) != "Bar":
+    raise ValueError
+
+if invoke_blah_double(b) != "Foo":
+    raise ValueError
+
+if invoke_blah_double(d) != "Bar":
+    raise ValueError
+
+if invoke_blah_uint(e) != "Foo":
+    raise ValueError
+
+if invoke_blah_uint(f) != "Bar":
+    raise ValueError
+
diff --git a/trunk/Examples/test-suite/python/template_matrix.i b/trunk/Examples/test-suite/python/template_matrix.i
new file mode 100644
index 0000000..2769654
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_matrix.i
@@ -0,0 +1,71 @@
+%module template_matrix
+%{
+#include <vector>
+
+  struct pop 
+  {
+  };  
+
+%}
+
+%include "std_vector.i"
+
+
+%inline {
+namespace simuPOP
+{
+  struct POP
+  {
+  };  
+
+  template<class _POP1, class _POP2 = POP>
+  class Operator
+  {
+  };
+}
+
+}
+
+%template(vectorop) std::vector< simuPOP::Operator<pop> >;
+
+
+
+namespace simuPOP
+{
+  %template(baseOperator)        Operator<pop>;
+}
+
+
+#if 1
+
+namespace std
+{
+%template(vectori)     vector<int>;
+%template(matrixi)     vector< vector<int> >;
+%template(cubei)       vector< vector< vector<int> > >;
+}
+
+
+
+%inline %{
+std::vector<int>
+passVector(const std::vector<int>& a)
+{
+  return a;
+}
+
+std::vector< std::vector<int> >
+passMatrix(const  std::vector< std::vector<int> >& a)
+{
+  return a;
+}
+
+std::vector< std::vector< std::vector<int> > >
+passCube(const  std::vector< std::vector< std::vector<int> > >& a)
+{
+  return a;
+}
+
+%}
+
+#endif
diff --git a/trunk/Examples/test-suite/python/template_matrix_runme.py b/trunk/Examples/test-suite/python/template_matrix_runme.py
new file mode 100644
index 0000000..95815a0
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_matrix_runme.py
@@ -0,0 +1,6 @@
+from template_matrix import  *
+passVector([1,2,3])
+passMatrix([[1,2],[1,2,3]])
+passCube([[[1,2],[1,2,3]],[[1,2],[1,2,3]]])
+
+
diff --git a/trunk/Examples/test-suite/python/template_ns4_runme.py b/trunk/Examples/test-suite/python/template_ns4_runme.py
new file mode 100644
index 0000000..81107b4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_ns4_runme.py
@@ -0,0 +1,5 @@
+from template_ns4 import *
+
+d = make_Class_DD();
+if d.test() != "test":
+	raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/template_ns_runme.py b/trunk/Examples/test-suite/python/template_ns_runme.py
new file mode 100644
index 0000000..20cc9b9
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_ns_runme.py
@@ -0,0 +1,17 @@
+from template_ns import *
+p1 = pairii(2,3)
+p2 = pairii(p1)
+
+if p2.first != 2:
+    raise RuntimeError
+if p2.second != 3:
+    raise RuntimeError
+
+p3 = pairdd(3.5,2.5)
+p4 = pairdd(p3)
+
+if p4.first != 3.5:
+    raise RuntimeError
+
+if p4.second != 2.5:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/template_opaque_runme.py b/trunk/Examples/test-suite/python/template_opaque_runme.py
new file mode 100644
index 0000000..f3aeb39
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_opaque_runme.py
@@ -0,0 +1,6 @@
+import template_opaque
+
+v = template_opaque.OpaqueVectorType(10)
+
+template_opaque.FillVector(v)
+
diff --git a/trunk/Examples/test-suite/python/template_ref_type_runme.py b/trunk/Examples/test-suite/python/template_ref_type_runme.py
new file mode 100644
index 0000000..0b3e4dd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_ref_type_runme.py
@@ -0,0 +1,5 @@
+import template_ref_type
+
+xr = template_ref_type.XC()
+y  = template_ref_type.Y()
+y.find(xr)
diff --git a/trunk/Examples/test-suite/python/template_rename_runme.py b/trunk/Examples/test-suite/python/template_rename_runme.py
new file mode 100644
index 0000000..4f0e7e8
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_rename_runme.py
@@ -0,0 +1,12 @@
+import template_rename
+
+i = template_rename.iFoo()
+d = template_rename.dFoo()
+
+a = i.blah_test(4)
+b = i.spam_test(5)
+c = i.groki_test(6)
+
+x = d.blah_test(7)
+y = d.spam(8)
+z = d.grok_test(9)
diff --git a/trunk/Examples/test-suite/python/template_static_runme.py b/trunk/Examples/test-suite/python/template_static_runme.py
new file mode 100644
index 0000000..9171d93
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_static_runme.py
@@ -0,0 +1,3 @@
+from template_static import  *
+
+Foo_bar_double(1)
diff --git a/trunk/Examples/test-suite/python/template_tbase_template_runme.py b/trunk/Examples/test-suite/python/template_tbase_template_runme.py
new file mode 100644
index 0000000..d13c5f2
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_tbase_template_runme.py
@@ -0,0 +1,5 @@
+from template_tbase_template import *
+
+a = make_Class_dd()
+if a.test() != "test":
+	raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/template_type_namespace_runme.py b/trunk/Examples/test-suite/python/template_type_namespace_runme.py
new file mode 100644
index 0000000..19ea5f5
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_type_namespace_runme.py
@@ -0,0 +1,5 @@
+from template_type_namespace import *
+
+if type(foo()[0]) != type(""):
+     raise RuntimeError
+                                  
diff --git a/trunk/Examples/test-suite/python/template_typedef_cplx2_runme.py b/trunk/Examples/test-suite/python/template_typedef_cplx2_runme.py
new file mode 100644
index 0000000..030fe02
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_typedef_cplx2_runme.py
@@ -0,0 +1,95 @@
+import string
+from template_typedef_cplx2 import *
+
+#
+# double case
+#
+
+try:
+  d = make_Identity_double()
+  a = d.this
+except:
+  print d, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % d
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print d, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+try:
+  e = make_Multiplies_double_double_double_double(d, d)
+  a = e.this
+except:
+  print e, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % e
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print e, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+
+#
+# complex case
+#
+
+try:
+  c = make_Identity_complex()
+  a = c.this
+except:
+  print c, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % c
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print c, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+try:
+  f = make_Multiplies_complex_complex_complex_complex(c, c)
+  a = f.this
+except:
+  print f, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % f
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print f, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+#
+# Mix case
+#
+
+try:
+  g = make_Multiplies_double_double_complex_complex(d, c)
+  a = g.this
+except:
+  print g, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % g
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print g, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+
+try:
+  h = make_Multiplies_complex_complex_double_double(c, d)
+  a = h.this
+except:
+  print h, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % h
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print h, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+try:
+  a = g.get_value()
+except:
+  print g, "has not get_value() method"
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/template_typedef_cplx3_runme.py b/trunk/Examples/test-suite/python/template_typedef_cplx3_runme.py
new file mode 100644
index 0000000..b8ac1b6
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_typedef_cplx3_runme.py
@@ -0,0 +1,34 @@
+import string
+from template_typedef_cplx3 import *
+
+#
+# this is OK
+#
+
+
+s = Sin()
+s.get_base_value()
+s.get_value()
+s.get_arith_value()
+my_func_r(s)
+make_Multiplies_double_double_double_double(s,s)
+
+z = CSin()
+z.get_base_value()
+z.get_value()
+z.get_arith_value()
+my_func_c(z)
+make_Multiplies_complex_complex_complex_complex(z,z)
+
+#
+# Here we fail
+#
+d = make_Identity_double()
+my_func_r(d)
+
+c = make_Identity_complex()
+my_func_c(c)
+  
+
+
+
diff --git a/trunk/Examples/test-suite/python/template_typedef_cplx4_runme.py b/trunk/Examples/test-suite/python/template_typedef_cplx4_runme.py
new file mode 100644
index 0000000..faeca21
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_typedef_cplx4_runme.py
@@ -0,0 +1,34 @@
+import string
+from template_typedef_cplx4 import *
+
+#
+# this is OK
+#
+
+
+s = Sin()
+s.get_base_value()
+s.get_value()
+s.get_arith_value()
+my_func_r(s)
+make_Multiplies_double_double_double_double(s,s)
+
+z = CSin()
+z.get_base_value()
+z.get_value()
+z.get_arith_value()
+my_func_c(z)
+make_Multiplies_complex_complex_complex_complex(z,z)
+
+#
+# Here we fail
+#
+d = make_Identity_double()
+my_func_r(d)
+
+c = make_Identity_complex()
+my_func_c(c)
+  
+
+
+
diff --git a/trunk/Examples/test-suite/python/template_typedef_cplx_runme.py b/trunk/Examples/test-suite/python/template_typedef_cplx_runme.py
new file mode 100644
index 0000000..99ffcb9
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_typedef_cplx_runme.py
@@ -0,0 +1,88 @@
+import string
+from template_typedef_cplx import *
+
+#
+# double case
+#
+
+try:
+  d = make_Identity_double()
+  a = d.this
+except:
+  print d, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % d
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print d, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+try:
+  e = make_Multiplies_double_double_double_double(d, d)
+  a = e.this
+except:
+  print e, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % e
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print e, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+
+#
+# complex case
+#
+
+try:
+  c = make_Identity_complex()
+  a = c.this
+except:
+  print c, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % c
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print c, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+try:
+  f = make_Multiplies_complex_complex_complex_complex(c, c)
+  a = f.this
+except:
+  print f, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % f
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print f, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+#
+# Mix case
+#
+
+try:
+  g = make_Multiplies_double_double_complex_complex(d, c)
+  a = g.this
+except:
+  print g, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % g
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print g, "is not an ArithUnaryFunction"
+  raise RuntimeError
+
+
+try:
+  h = make_Multiplies_complex_complex_double_double(c, d)
+  a = h.this
+except:
+  print h, "is not an instance"
+  raise RuntimeError
+
+s = '%s' % h
+if string.find(s, 'ArithUnaryFunction') == -1:
+  print h, "is not an ArithUnaryFunction"
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/template_typedef_import_runme.py b/trunk/Examples/test-suite/python/template_typedef_import_runme.py
new file mode 100644
index 0000000..48d88ed
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_typedef_import_runme.py
@@ -0,0 +1,35 @@
+import string
+from template_typedef_cplx2 import *
+from template_typedef_import import *
+
+#
+# this is OK
+#
+
+
+s = Sin()
+s.get_base_value()
+s.get_value()
+s.get_arith_value()
+my_func_r(s)
+make_Multiplies_double_double_double_double(s,s)
+
+z = CSin()
+z.get_base_value()
+z.get_value()
+z.get_arith_value()
+my_func_c(z)
+make_Multiplies_complex_complex_complex_complex(z,z)
+
+#
+# Here we fail
+#
+d = make_Identity_double()
+my_func_r(d)
+
+c = make_Identity_complex()
+my_func_c(c)
+  
+
+
+
diff --git a/trunk/Examples/test-suite/python/template_typedef_runme.py b/trunk/Examples/test-suite/python/template_typedef_runme.py
new file mode 100644
index 0000000..4b39705
--- /dev/null
+++ b/trunk/Examples/test-suite/python/template_typedef_runme.py
@@ -0,0 +1,46 @@
+from template_typedef import *
+
+d = make_Identity_float()
+c = make_Identity_reald()
+
+
+try:
+  a = d.this
+  a = c.this
+except:
+  raise RuntimeError
+
+try:
+  e = make_Multiplies_float_float_float_float(d, d)
+  a = e.this
+except:
+  print e, "is not an instance"
+  raise RuntimeError
+
+try:
+  f = make_Multiplies_reald_reald_reald_reald(c, c)
+  a = f.this
+except:
+  print f, "is not an instance"
+  raise RuntimeError
+
+try:
+  g = make_Multiplies_float_float_reald_reald(d, c)
+  a = g.this
+except:
+  print g, "is not an instance"
+  raise RuntimeError
+
+
+# the old large format
+if not SWIG_TypeQuery("vfncs::ArithUnaryFunction<vfncs::arith_traits<float,double>::argument_type,vfncs::arith_traits<float,double >::result_type > *"):
+  raise RuntimeError
+
+
+# the reduced format
+if not SWIG_TypeQuery("vfncs::ArithUnaryFunction<double,double> *"):
+  raise RuntimeError
+
+# this is a bad name
+if SWIG_TypeQuery("vfncs::ArithUnaryFunction<double,doublex> *"):
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/typedef_class_runme.py b/trunk/Examples/test-suite/python/typedef_class_runme.py
new file mode 100644
index 0000000..71436b3
--- /dev/null
+++ b/trunk/Examples/test-suite/python/typedef_class_runme.py
@@ -0,0 +1,7 @@
+import typedef_class
+
+a = typedef_class.RealA() 
+a.a = 3 
+ 
+b = typedef_class.B() 
+b.testA(a) 
diff --git a/trunk/Examples/test-suite/python/typedef_inherit_runme.py b/trunk/Examples/test-suite/python/typedef_inherit_runme.py
new file mode 100644
index 0000000..6b7f2d8
--- /dev/null
+++ b/trunk/Examples/test-suite/python/typedef_inherit_runme.py
@@ -0,0 +1,23 @@
+import typedef_inherit
+
+a = typedef_inherit.Foo()
+b = typedef_inherit.Bar()
+
+x = typedef_inherit.do_blah(a)
+if x != "Foo::blah":
+    print "Whoa! Bad return", x
+
+x = typedef_inherit.do_blah(b)
+if x != "Bar::blah":
+    print "Whoa! Bad return", x
+
+c = typedef_inherit.Spam()
+d = typedef_inherit.Grok()
+
+x = typedef_inherit.do_blah2(c)
+if x != "Spam::blah":
+    print "Whoa! Bad return", x
+
+x = typedef_inherit.do_blah2(d)
+if x != "Grok::blah":
+    print "Whoa! Bad return", x
diff --git a/trunk/Examples/test-suite/python/typedef_scope_runme.py b/trunk/Examples/test-suite/python/typedef_scope_runme.py
new file mode 100644
index 0000000..37bfc97
--- /dev/null
+++ b/trunk/Examples/test-suite/python/typedef_scope_runme.py
@@ -0,0 +1,12 @@
+import typedef_scope
+
+b = typedef_scope.Bar()
+x = b.test1(42,"hello")
+if x != 42:
+    print "Failed!!"
+
+x = b.test2(42,"hello")
+if x != "hello":
+    print "Failed!!"
+    
+    
diff --git a/trunk/Examples/test-suite/python/typemap_namespace_runme.py b/trunk/Examples/test-suite/python/typemap_namespace_runme.py
new file mode 100644
index 0000000..581a0f4
--- /dev/null
+++ b/trunk/Examples/test-suite/python/typemap_namespace_runme.py
@@ -0,0 +1,8 @@
+from typemap_namespace import *
+
+if test1("hello") != "hello":
+    raise RuntimeError
+
+if test2("hello") != "hello":
+    raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/typemap_ns_using_runme.py b/trunk/Examples/test-suite/python/typemap_ns_using_runme.py
new file mode 100644
index 0000000..802ea7f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/typemap_ns_using_runme.py
@@ -0,0 +1,4 @@
+import typemap_ns_using
+
+if typemap_ns_using.spam(37) != 37:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/typename_runme.py b/trunk/Examples/test-suite/python/typename_runme.py
new file mode 100644
index 0000000..59a0f1f
--- /dev/null
+++ b/trunk/Examples/test-suite/python/typename_runme.py
@@ -0,0 +1,12 @@
+import typename
+import types
+f = typename.Foo()
+b = typename.Bar()
+
+x = typename.twoFoo(f)
+if not isinstance(x,types.FloatType):
+    print "Wrong return type!"
+y = typename.twoBar(b)
+if not isinstance(y,types.IntType):
+    print "Wrong return type!"
+    
diff --git a/trunk/Examples/test-suite/python/types_directive_runme.py b/trunk/Examples/test-suite/python/types_directive_runme.py
new file mode 100644
index 0000000..c28453e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/types_directive_runme.py
@@ -0,0 +1,12 @@
+from types_directive import *
+
+d1 = Time1(2001, 2, 3, 60)
+newDate = add(d1, 7) # check that a Time1 instance is accepted where Date is expected
+if newDate.day != 10:
+  raise RuntimeError
+
+d2 = Time2(1999, 8, 7, 60)
+newDate = add(d2, 7) # check that a Time2 instance is accepted where Date is expected
+if newDate.day != 14:
+  raise RuntimeError
+
diff --git a/trunk/Examples/test-suite/python/unions_runme.py b/trunk/Examples/test-suite/python/unions_runme.py
new file mode 100644
index 0000000..d59e242
--- /dev/null
+++ b/trunk/Examples/test-suite/python/unions_runme.py
@@ -0,0 +1,51 @@
+
+# This is the union runtime testcase. It ensures that values within a 
+# union embedded within a struct can be set and read correctly.
+
+import unions
+import sys
+import string
+
+# Create new instances of SmallStruct and BigStruct for later use
+small = unions.SmallStruct()
+small.jill = 200
+
+big = unions.BigStruct()
+big.smallstruct = small
+big.jack = 300
+
+# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+# Ensure values in EmbeddedUnionTest are set correctly for each.
+eut = unions.EmbeddedUnionTest()
+
+# First check the SmallStruct in EmbeddedUnionTest
+eut.number = 1
+eut.uni.small = small
+Jill1 = eut.uni.small.jill
+if (Jill1 != 200):
+    print "Runtime test1 failed. eut.uni.small.jill=" , Jill1
+    sys.exit(1)
+
+Num1 = eut.number
+if (Num1 != 1):
+    print "Runtime test2 failed. eut.number=" , Num1
+    sys.exit(1)
+
+# Secondly check the BigStruct in EmbeddedUnionTest
+eut.number = 2
+eut.uni.big = big
+Jack1 = eut.uni.big.jack
+if (Jack1 != 300):
+    print "Runtime test3 failed. eut.uni.big.jack=" , Jack1
+    sys.exit(1)
+
+Jill2 = eut.uni.big.smallstruct.jill
+if (Jill2 != 200):
+    print "Runtime test4 failed. eut.uni.big.smallstruct.jill=" , Jill2
+    sys.exit(1)
+
+Num2 = eut.number
+if (Num2 != 2):
+    print "Runtime test5 failed. eut.number=" , Num2
+    sys.exit(1)
+
diff --git a/trunk/Examples/test-suite/python/using1_runme.py b/trunk/Examples/test-suite/python/using1_runme.py
new file mode 100644
index 0000000..5556c1b
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using1_runme.py
@@ -0,0 +1,4 @@
+import using1
+
+if using1.spam(37) != 37:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/using2_runme.py b/trunk/Examples/test-suite/python/using2_runme.py
new file mode 100644
index 0000000..cf657d7
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using2_runme.py
@@ -0,0 +1,4 @@
+import using2
+
+if using2.spam(37) != 37:
+    raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/using_composition_runme.py b/trunk/Examples/test-suite/python/using_composition_runme.py
new file mode 100644
index 0000000..6baa16d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using_composition_runme.py
@@ -0,0 +1,34 @@
+from using_composition import *
+
+f = FooBar()
+if f.blah(3) != 3:
+  raise RuntimeError,"FooBar::blah(int)"
+
+if f.blah(3.5) != 3.5:
+  raise RuntimeError,"FooBar::blah(double)"
+
+if f.blah("hello") != "hello":
+  raise RuntimeError,"FooBar::blah(char *)"
+
+
+f = FooBar2()
+if f.blah(3) != 3:
+  raise RuntimeError,"FooBar2::blah(int)"
+
+if f.blah(3.5) != 3.5:
+  raise RuntimeError,"FooBar2::blah(double)"
+
+if f.blah("hello") != "hello":
+  raise RuntimeError,"FooBar2::blah(char *)"
+
+
+f = FooBar3()
+if f.blah(3) != 3:
+  raise RuntimeError,"FooBar3::blah(int)"
+
+if f.blah(3.5) != 3.5:
+  raise RuntimeError,"FooBar3::blah(double)"
+
+if f.blah("hello") != "hello":
+  raise RuntimeError,"FooBar3::blah(char *)"
+
diff --git a/trunk/Examples/test-suite/python/using_extend_runme.py b/trunk/Examples/test-suite/python/using_extend_runme.py
new file mode 100644
index 0000000..14615a0
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using_extend_runme.py
@@ -0,0 +1,21 @@
+from using_extend import *
+
+f = FooBar()
+if f.blah(3) != 3:
+    raise RuntimeError,"blah(int)"
+
+if f.blah(3.5) != 3.5:
+    raise RuntimeError,"blah(double)"
+
+if f.blah("hello") != "hello":
+    raise RuntimeError,"blah(char *)"
+
+if f.blah(3,4) != 7:
+    raise RuntimeError,"blah(int,int)"
+
+if f.blah(3.5,7.5) != (3.5+7.5):
+    raise RuntimeError,"blah(double,double)"
+
+
+if f.duh(3) != 3:
+    raise RuntimeError,"duh(int)"
diff --git a/trunk/Examples/test-suite/python/using_inherit_runme.py b/trunk/Examples/test-suite/python/using_inherit_runme.py
new file mode 100644
index 0000000..b00e66e
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using_inherit_runme.py
@@ -0,0 +1,49 @@
+from using_inherit import *
+
+b = Bar()
+if b.test(3) != 3:
+  raise RuntimeError,"Bar::test(int)"
+
+if b.test(3.5) != 3.5:
+  raise RuntimeError, "Bar::test(double)"
+
+
+b = Bar2()
+if b.test(3) != 6:
+  raise RuntimeError,"Bar2::test(int)"
+
+if b.test(3.5) != 7.0:
+  raise RuntimeError, "Bar2::test(double)"
+
+
+b = Bar3()
+if b.test(3) != 6:
+  raise RuntimeError,"Bar3::test(int)"
+
+if b.test(3.5) != 7.0:
+  raise RuntimeError, "Bar3::test(double)"
+
+
+b = Bar4()
+if b.test(3) != 6:
+  raise RuntimeError,"Bar4::test(int)"
+
+if b.test(3.5) != 7.0:
+  raise RuntimeError, "Bar4::test(double)"
+
+
+b = Fred1()
+if b.test(3) != 3:
+  raise RuntimeError,"Fred1::test(int)"
+
+if b.test(3.5) != 7.0:
+  raise RuntimeError, "Fred1::test(double)"
+
+
+b = Fred2()
+if b.test(3) != 3:
+  raise RuntimeError,"Fred2::test(int)"
+
+if b.test(3.5) != 7.0:
+  raise RuntimeError, "Fred2::test(double)"
+
diff --git a/trunk/Examples/test-suite/python/using_private_runme.py b/trunk/Examples/test-suite/python/using_private_runme.py
new file mode 100644
index 0000000..00c9a8d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using_private_runme.py
@@ -0,0 +1,13 @@
+from using_private import *
+
+f = FooBar()
+f.x = 3
+
+if f.blah(4) != 4:
+    raise RuntimeError, "blah(int)"
+
+if f.defaulted() != -1:
+    raise RuntimeError, "defaulted()"
+
+if f.defaulted(222) != 222:
+    raise RuntimeError, "defaulted(222)"
diff --git a/trunk/Examples/test-suite/python/using_protected_runme.py b/trunk/Examples/test-suite/python/using_protected_runme.py
new file mode 100644
index 0000000..525a1cd
--- /dev/null
+++ b/trunk/Examples/test-suite/python/using_protected_runme.py
@@ -0,0 +1,7 @@
+from using_protected import *
+
+f = FooBar()
+f.x = 3
+
+if f.blah(4) != 4:
+    raise RuntimeError, "blah(int)"
diff --git a/trunk/Examples/test-suite/python/varargs_runme.py b/trunk/Examples/test-suite/python/varargs_runme.py
new file mode 100644
index 0000000..301de78
--- /dev/null
+++ b/trunk/Examples/test-suite/python/varargs_runme.py
@@ -0,0 +1,18 @@
+import varargs
+
+if varargs.test("Hello") != "Hello":
+    raise RuntimeError, "Failed"
+
+f = varargs.Foo("Greetings")
+if f.str != "Greetings":
+    raise RuntimeError, "Failed"
+
+if f.test("Hello") != "Hello":
+    raise RuntimeError, "Failed"
+
+
+if varargs.test_def("Hello",1) != "Hello":
+    raise RuntimeError, "Failed"
+
+if varargs.test_def("Hello") != "Hello":
+    raise RuntimeError, "Failed"
diff --git a/trunk/Examples/test-suite/python/vector.i b/trunk/Examples/test-suite/python/vector.i
new file mode 100644
index 0000000..04c961c
--- /dev/null
+++ b/trunk/Examples/test-suite/python/vector.i
@@ -0,0 +1,51 @@
+%module vector
+%{
+#include <vector>
+%}
+
+%define SWIG_STD_VECTOR_MINIMUM(CSTYPE, CTYPE...)
+  public:
+    typedef size_t size_type;
+    typedef CTYPE value_type;
+    size_type size() const;
+    vector();
+    %extend {
+      static std::vector<CTYPE > *Repeat(const value_type& value, int count) /*throw (std::out_of_range)*/ {
+//        if (count < 0)
+//          throw std::out_of_range("count");
+        return new std::vector<CTYPE >(count, value);
+      }
+    }
+%enddef
+
+namespace std {
+  // primary (unspecialized) class template for std::vector
+  // does not require operator== to be defined
+  template<class T> class vector {
+    SWIG_STD_VECTOR_MINIMUM(T, T)
+  };
+}
+
+%define SWIG_STD_VECTOR_SPECIALIZE(CSTYPE, CTYPE...)
+namespace std {
+  template<> class vector<CTYPE > {
+    SWIG_STD_VECTOR_MINIMUM(CSTYPE, CTYPE)
+  };
+}
+%enddef
+
+SWIG_STD_VECTOR_SPECIALIZE(float, float)
+
+%inline %{
+typedef float Real;
+%}
+
+#if 1
+//fails
+namespace std {
+    %template(RealVector) vector<Real>;
+}
+#else
+//works
+%template(RealVector) std::vector<Real>;
+#endif 
diff --git a/trunk/Examples/test-suite/python/virtual_derivation_runme.py b/trunk/Examples/test-suite/python/virtual_derivation_runme.py
new file mode 100644
index 0000000..8a6e743
--- /dev/null
+++ b/trunk/Examples/test-suite/python/virtual_derivation_runme.py
@@ -0,0 +1,8 @@
+from virtual_derivation import *
+#
+# very innocent example
+#
+b = B(3)
+if b.get_a() != b.get_b():
+  raise RuntimeError, "something is really wrong"
+
diff --git a/trunk/Examples/test-suite/python/virtual_poly_runme.py b/trunk/Examples/test-suite/python/virtual_poly_runme.py
new file mode 100644
index 0000000..7e202f9
--- /dev/null
+++ b/trunk/Examples/test-suite/python/virtual_poly_runme.py
@@ -0,0 +1,38 @@
+import virtual_poly
+
+d = virtual_poly.NDouble(3.5)
+i = virtual_poly.NInt(2)
+
+#
+# the copy methods return the right polymorphic types
+# 
+dc = d.copy()
+ic = i.copy()
+
+if d.get() != dc.get():
+  raise RuntimeError
+
+if i.get() != ic.get():
+  raise RuntimeError
+
+virtual_poly.incr(ic)
+
+if (i.get() + 1) != ic.get():
+  raise RuntimeError
+
+
+dr = d.ref_this()
+if d.get() != dr.get():
+  raise RuntimeError
+
+
+#
+# 'narrowing' also works
+#
+ddc = virtual_poly.NDouble_narrow(d.nnumber())
+if d.get() != ddc.get():
+  raise RuntimeError
+
+dic = virtual_poly.NInt_narrow(i.nnumber())
+if i.get() != dic.get():
+  raise RuntimeError
diff --git a/trunk/Examples/test-suite/python/voidtest_runme.py b/trunk/Examples/test-suite/python/voidtest_runme.py
new file mode 100644
index 0000000..a7b421d
--- /dev/null
+++ b/trunk/Examples/test-suite/python/voidtest_runme.py
@@ -0,0 +1,29 @@
+import voidtest
+
+voidtest.globalfunc()
+f = voidtest.Foo()
+f.memberfunc()
+
+voidtest.Foo_staticmemberfunc()
+
+def fvoid():
+    pass
+
+if  f.memberfunc() != fvoid():
+    raise RuntimeError
+
+
+v1 = voidtest.vfunc1(f)
+v2 = voidtest.vfunc2(f)
+if v1 != v2:
+    raise RuntimeError
+
+v3 = voidtest.vfunc3(v1)
+if v3.this != f.this:
+    raise RuntimeError
+v4 = voidtest.vfunc1(f)
+if v4 != v1:
+    raise RuntimeError
+
+
+v3.memberfunc()
diff --git a/trunk/Examples/test-suite/python/wrapmacro_runme.py b/trunk/Examples/test-suite/python/wrapmacro_runme.py
new file mode 100644
index 0000000..e7a5a37
--- /dev/null
+++ b/trunk/Examples/test-suite/python/wrapmacro_runme.py
@@ -0,0 +1,7 @@
+import wrapmacro
+
+a = 2
+b = -1
+wrapmacro.max(a,b)
+wrapmacro.max(a/7.0, -b*256)
+wrapmacro.GUINT16_SWAP_LE_BE_CONSTANT(1)
diff --git a/trunk/Examples/test-suite/r/Makefile.in b/trunk/Examples/test-suite/r/Makefile.in
new file mode 100644
index 0000000..70dd62e
--- /dev/null
+++ b/trunk/Examples/test-suite/r/Makefile.in
@@ -0,0 +1,69 @@
+#######################################################################
+# Makefile for r test-suite
+#######################################################################
+
+LANGUAGE     = r
+SCRIPTSUFFIX = _runme.R
+WRAPSUFFIX   = .R
+RUNR         = R CMD BATCH --no-save --no-restore
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+C_TEST_CASES = copy_struct simple_array legacy
+CPP_TEST_CASES = double_delete
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_multitestcase)
+
+# Runs the testcase.
+# 
+# Run the runme if it exists.  If not just load the R wrapper to 
+# check for syntactic correctness
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then ( \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" \
+               $(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ;) \
+	else \
+	  ($(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$*$(WRAPSUFFIX);) \
+	fi;
+
+run_multitestcase = \
+	for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX) ]; then ( \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" \
+               $(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX) ;) \
+	else \
+	  ($(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX);) \
+	fi; \
+	done
+# Clean
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile r_clean
+
+%.clean:
+	@rm -f $*.R $*_wrap.so $*_wrap.cpp $*_wrap.c $*_wrap.o $*_runme.Rout $*.Rout
+	@if [ -f  $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list ]; then ( \
+	for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \
+	   rm -f $${f}.R $${f}.Rout ; \
+	done ) \
+	fi
+
+
diff --git a/trunk/Examples/test-suite/r/copy_struct.i b/trunk/Examples/test-suite/r/copy_struct.i
new file mode 100644
index 0000000..db62233
--- /dev/null
+++ b/trunk/Examples/test-suite/r/copy_struct.i
@@ -0,0 +1,93 @@
+%module copy_struct
+
+%feature("opaque", "yes")  B;
+%feature("opaque", "yes")  C;
+
+%inline %{
+struct A {
+  int i;
+  unsigned int ui;
+  double d;
+  char* str;
+  int **tmp;
+};
+
+struct A getA();
+struct A* getARef();
+
+typedef struct  {
+  int invisible;
+} B;
+
+struct C {
+ int invisible;
+ double blind;
+};
+
+typedef B C;
+
+B* getBRef();
+struct C* getCRef();
+
+C* getCCRef();
+
+typedef struct 
+{
+ int x;
+ double u;
+} D;
+
+struct A 
+getA()
+{
+  struct A a;
+
+  a.i = 10;
+  a.d = 3.1415;
+
+  return a;
+}
+
+static struct A fixed = {20, 3, 42.0};
+
+struct A *
+getARef()
+{
+  return(&fixed);
+}
+
+
+static B bb = {101};
+
+B*
+getBRef()
+{
+  return(&bb);
+}
+
+struct C cc = {201, 3.14159};
+struct C *
+getCRef()
+{
+  return(&cc);
+}
+
+
+C*
+getCCRef()
+{
+  return(&bb);
+}
+
+D
+bar()
+{ D a;
+ a.x = 1;
+ a.u = 0;
+ return(a);
+}
+
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/r/copy_struct_runme.R b/trunk/Examples/test-suite/r/copy_struct_runme.R
new file mode 100644
index 0000000..523f1d6
--- /dev/null
+++ b/trunk/Examples/test-suite/r/copy_struct_runme.R
@@ -0,0 +1,57 @@
+source("unittest.R")
+dyn.load(paste("copy_struct", .Platform$dynlib.ext, sep=""))
+source("copy_struct.R")
+cacheMetaData(1)
+
+a <- getA()
+
+r = getARef()
+
+unittest(A_d_get(r), 42)
+unittest(r$d, 42)
+unittest(r$i, 20)
+
+# An error in trying to access a field that doesn't exist.
+try(r$foo) 
+
+r$d <- pi
+unittesttol(r$d, 3.141593, 0.0001)
+r$i <- -100
+
+r$ui
+r$ui <- 10
+
+ # An error since i is unsigned and so must  be positive.
+try(r$ui <- -10)
+
+
+a = A()
+unittest(a$i,0)
+unittest(a$d,0)
+unittest(a$ui,0)
+a$ui <- 100
+unittest(a$ui,100)
+a$d = 1
+unittest(a$d,1)
+
+d <- bar()
+unittest(class(d), "_p_D")
+unittest(d$x, 1)
+unittest(d$u, 0)
+
+
+la <- new("A");
+la@ui <- 5
+# Removing the next line makes this fail in R 2.4
+la@str <- ""
+
+other = A()
+foo <- copyToC(la, other)
+
+aa = A()
+aa$i = 201
+aa$d = pi
+aa$str = "foo"
+copyToR(aa)
+
+
diff --git a/trunk/Examples/test-suite/r/double_delete.i b/trunk/Examples/test-suite/r/double_delete.i
new file mode 100644
index 0000000..4f2d1e0
--- /dev/null
+++ b/trunk/Examples/test-suite/r/double_delete.i
@@ -0,0 +1,15 @@
+/* File : example.i */
+%module double_delete
+
+%inline %{
+
+class Foo {
+private:
+  double r;
+public:
+  Foo(double rin) : r(rin) {}; 
+};
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/r/double_delete_runme.R b/trunk/Examples/test-suite/r/double_delete_runme.R
new file mode 100644
index 0000000..8ac6b43
--- /dev/null
+++ b/trunk/Examples/test-suite/r/double_delete_runme.R
@@ -0,0 +1,12 @@
+# This file illustrates the proxy class C++ interface generated
+# by SWIG.
+
+dyn.load(paste("double_delete", .Platform$dynlib.ext, sep=""))
+source("double_delete.R")
+cacheMetaData(1)
+
+# ----- Object creation -----
+
+f <- Foo(2.0)
+delete(f);
+delete(f);
diff --git a/trunk/Examples/test-suite/r/funcptr_runme.R b/trunk/Examples/test-suite/r/funcptr_runme.R
new file mode 100644
index 0000000..3d5281b
--- /dev/null
+++ b/trunk/Examples/test-suite/r/funcptr_runme.R
@@ -0,0 +1,7 @@
+source("unittest.R")
+dyn.load(paste("funcptr", .Platform$dynlib.ext, sep=""))
+source("funcptr.R")
+cacheMetaData(1)
+unittest(do_op(1, 3, add), 4)
+unittest(do_op(2, 3, multiply), 6)
+unittest(do_op(2, 3, funcvar()), 5)
diff --git a/trunk/Examples/test-suite/r/ignore_parameter_runme.R b/trunk/Examples/test-suite/r/ignore_parameter_runme.R
new file mode 100644
index 0000000..89e461d
--- /dev/null
+++ b/trunk/Examples/test-suite/r/ignore_parameter_runme.R
@@ -0,0 +1,10 @@
+source("unittest.R")
+dyn.load(paste("ignore_parameter", .Platform$dynlib.ext, sep=""))
+source("ignore_parameter.R")
+cacheMetaData(1)
+
+unittest(jaguar(1, 1.0), "hello")
+q(save="no")
+
+
+
diff --git a/trunk/Examples/test-suite/r/legacy.i b/trunk/Examples/test-suite/r/legacy.i
new file mode 100644
index 0000000..4e20802
--- /dev/null
+++ b/trunk/Examples/test-suite/r/legacy.i
@@ -0,0 +1,98 @@
+%module legacy
+%inline %{
+typedef char *String;
+
+typedef struct {
+  int i;
+  double d;
+  char *str;
+  String s;
+} Obj;
+
+Obj *getObject(int i, double d);
+
+#include <string.h>
+
+Obj *
+getObject(int i, double d)
+{
+
+  const char *test_string = "a test string";
+  Obj *obj;
+  obj = (Obj *) calloc(1, sizeof(Obj));
+
+  obj->i = i;
+  obj->d = d;
+  /* allocate one extra byte for the null */
+  obj->str = (char *)malloc(strlen(test_string) + 1);
+  strcpy(obj->str, test_string);
+
+  return(obj);
+}
+%}
+
+char *getString();
+int getInt();
+double getDouble();
+float getFloat();
+long getLong();
+unsigned long getUnsignedLong();
+char getChar();
+
+extern unsigned long MyULong;
+
+extern const double PiSquared;
+
+#if 0
+extern float *MyFloatRef;
+#endif
+
+%inline %{
+#define PI 3.14159265358979
+unsigned long MyULong = 20;
+
+static float MyFloat = 1.05f;
+float *MyFloatRef = &MyFloat;
+
+const double PiSquared = PI * PI;
+
+char *getString()
+{
+  return "This is a literal string";
+}
+
+int 
+getInt()
+{
+ return 42;
+}
+
+double 
+getDouble()
+{
+  return PI;
+}
+
+float 
+getFloat()
+{
+  return (float)PI/2;
+}
+
+long getLong()
+{
+  return -321313L;
+}
+
+unsigned long 
+getUnsignedLong()
+{
+  return 23123L;
+}
+
+char
+getChar()
+{
+  return('A');
+}
+%}
diff --git a/trunk/Examples/test-suite/r/legacy_runme.R b/trunk/Examples/test-suite/r/legacy_runme.R
new file mode 100644
index 0000000..a1466e4
--- /dev/null
+++ b/trunk/Examples/test-suite/r/legacy_runme.R
@@ -0,0 +1,30 @@
+source("unittest.R")
+dyn.load(paste("legacy", .Platform$dynlib.ext, sep=""))
+source("legacy.R")
+cacheMetaData(1)
+
+obj <- getObject(1,3)
+unittest(class(obj), "_p_Obj")
+unittest(obj$i, 1)
+unittesttol(obj$d, 3, 0.001)
+unittest(obj$str, "a test string")
+obj$i <- 2
+unittest(obj$i, 2)
+obj$d <- 4
+unittesttol(obj$d, 4, 0.001)
+obj$str <- "a new string"
+unittest(obj$str, "a new string")
+
+unittest(getInt(), 42)
+unittesttol(getDouble(),3.14159, 0.001)
+unittesttol(getFloat(),3.14159/2.0, 0.001)
+unittest(getLong(), -321313)  
+unittest(getUnsignedLong(), 23123)
+unittest(getChar(), "A")
+
+q(save="no")
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/r/simple_array.i b/trunk/Examples/test-suite/r/simple_array.i
new file mode 100644
index 0000000..6ddc436
--- /dev/null
+++ b/trunk/Examples/test-suite/r/simple_array.i
@@ -0,0 +1,42 @@
+%module simple_array
+
+extern int x[10];
+extern double y[7];
+
+
+%inline %{
+
+struct BarArray {
+  int i;
+  double d;
+};
+
+extern struct BarArray bars[2]; 
+
+int x[10];
+double y[7];
+struct BarArray bars[2]; 
+
+void
+initArray()
+{
+  int i, n;
+
+  n = sizeof(x)/sizeof(x[0]);
+  for(i = 0; i < n; i++) 
+    x[i] = i;
+
+  n = sizeof(y)/sizeof(y[0]);
+  for(i = 0; i < n; i++) 
+    y[i] = ((double) i)/ ((double) n);
+
+  n = sizeof(bars)/sizeof(bars[0]);
+  for(i = 0; i < n; i++)  {
+    bars[i].i = x[i+2];
+    bars[i].d = y[i+2];
+  }
+
+  return;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/r/simple_array_runme.R b/trunk/Examples/test-suite/r/simple_array_runme.R
new file mode 100644
index 0000000..a6758de
--- /dev/null
+++ b/trunk/Examples/test-suite/r/simple_array_runme.R
@@ -0,0 +1,9 @@
+source("unittest.R")
+dyn.load(paste("simple_array", .Platform$dynlib.ext, sep=""))
+source("simple_array.R")
+cacheMetaData(1)
+initArray()
+
+q(save="no")
+
+
diff --git a/trunk/Examples/test-suite/r/unions_runme.R b/trunk/Examples/test-suite/r/unions_runme.R
new file mode 100644
index 0000000..76870d1
--- /dev/null
+++ b/trunk/Examples/test-suite/r/unions_runme.R
@@ -0,0 +1,12 @@
+source("unittest.R")
+dyn.load(paste("unions", .Platform$dynlib.ext, sep=""))
+source("unions.R")
+cacheMetaData(1)
+
+ss <- SmallStruct()
+
+bstruct <- BigStruct()
+
+q(save="no")
+
+
diff --git a/trunk/Examples/test-suite/r/unittest.R b/trunk/Examples/test-suite/r/unittest.R
new file mode 100644
index 0000000..81c590a
--- /dev/null
+++ b/trunk/Examples/test-suite/r/unittest.R
@@ -0,0 +1,9 @@
+unittest <- function (x,y) {
+if (x==y) print("PASS") 
+else print("FAIL") 
+}
+
+unittesttol <- function(x,y,z) {
+if (abs(x-y) < z) print("PASS")
+else print("FAIL")
+}
\ No newline at end of file
diff --git a/trunk/Examples/test-suite/redefined.i b/trunk/Examples/test-suite/redefined.i
new file mode 100644
index 0000000..3022ee9
--- /dev/null
+++ b/trunk/Examples/test-suite/redefined.i
@@ -0,0 +1,107 @@
+%module redefined
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) agua;
+
+/* no redundant warnings */
+%warnfilter(SWIGWARN_PARSE_REDUNDANT);
+
+#if 1
+ //
+ // All these repeated declarations are not redefinitions,
+ // and they are valid C++ code, therefore, we skip 
+ // swig redefined warnings.
+ //
+%define uja
+  aju;
+%enddef
+
+%define uja
+  aju;
+%enddef
+
+%constant int agua = 0;
+%constant int agua = 0;
+
+%inline %{
+
+#define REDUNDANT 1
+#define REDUNDANT 1
+
+#define MACROREP(x) x
+#define MACROREP(x) x
+
+  class Hello;
+  class Hello;
+  
+  typedef int Int;
+  typedef int Int;
+
+  inline int hello(int);
+  int hello(int) { return 0; }
+  
+  struct B;
+  
+  struct A
+  {
+    typedef int Int;
+    friend int foo(A*, B*);    
+  };
+
+  struct B
+  {
+    typedef int Int;
+    friend int foo(A*, B*);
+  };
+
+  inline int foo(A*, B*) { return 0; }
+  
+%}
+
+
+#else
+
+//
+// the %extend and %rename directive ALWAYS emit redefined warnings,
+// since they are not C/C++/CPP standard.
+//
+%extend Hello {
+  int hi(int) { return 0; }
+}
+
+%rename(chao) hi(int);
+
+//
+// All these repeated declarations are really redefinitions,
+// therefore, swig must produce a redefined warning
+//
+
+%constant int agua = 0;
+%constant int agua = 1;
+
+
+%inline %{
+
+#define REDEFINED 1
+#define REDEFINED 2
+
+#define MACROREP(x) x
+#define MACROREP(x) x*2
+
+  typedef int Int;
+  typedef double Int;
+
+  int hi(int);
+  int chao(int);
+  int hello(int);
+  inline double hello(int) { return 0; }
+  
+  struct Hello 
+  {
+    typedef int Int;
+    typedef double Int;
+    friend short hello(int);
+    int hi(int) { return 0; }
+  };
+  
+%}
+#endif
diff --git a/trunk/Examples/test-suite/refcount.h b/trunk/Examples/test-suite/refcount.h
new file mode 100644
index 0000000..7d07e72
--- /dev/null
+++ b/trunk/Examples/test-suite/refcount.h
@@ -0,0 +1,198 @@
+#ifndef TEST_SUITE_REFCOUNT_H__
+#define TEST_SUITE_REFCOUNT_H__
+
+struct RCObjBase  {
+  /*!
+    Return  the numbers of active references.
+
+    \return The internal \c refCount value.
+  */
+  int ref_count() const
+  {
+    return refCount;
+  }
+
+  /*!
+    Add one reference.
+
+    \return The reference counter value.
+  */
+  int addref() const
+  {
+    return  add_ref();
+  }
+    
+  /*!
+    Delete one reference. If the refCount is zero, the
+    object is deleted. 
+
+    \return The reference counter value, which can be zero after
+    deletion.
+  */
+  int delref() const
+  {
+    if (ref_count() == 0 || del_ref() == 0 )
+      {
+	delete this;
+	return 0;
+      } 
+    return ref_count();
+  }
+    
+protected:
+  RCObjBase();
+  RCObjBase(const RCObjBase& );
+  virtual ~RCObjBase() = 0;
+
+private:
+
+  RCObjBase& operator=(const RCObjBase& );
+
+  friend struct RCObj;
+
+  int add_ref() const
+  {
+    return ++refCount;
+  }
+    
+  int del_ref() const
+  {
+    return --refCount;
+  }
+    
+  mutable int refCount;
+};
+
+struct RCObj : virtual RCObjBase {
+protected:
+  RCObj()
+  {
+  }
+};
+
+/*! Reference an RCObj object
+  \return The input pointer \a r
+*/
+template <class T>
+inline
+T* addref(T* r)
+{ 
+  return (r && r->addref() ) ? r : 0;
+}
+  
+/*! Unreference an RCObj object.
+  \return The input pointer \a r or nil if the object was deleted.
+*/
+template <class T>
+inline
+T* delref(T* r)
+{ 
+  return ( r && r->delref() ) ? r : 0;
+}
+
+
+
+RCObjBase::RCObjBase()
+  : refCount(0)
+{
+}
+
+
+RCObjBase::~RCObjBase()
+{
+}
+
+RCObjBase::RCObjBase(const RCObjBase&)
+  : refCount(0)
+{
+}
+
+
+RCObjBase& RCObjBase::operator=(const RCObjBase&)
+{
+  return *this;
+}
+
+
+template <class T>                     
+struct RCPtr  {
+  typedef T* pointer_type;
+  typedef T& refernce_type;
+  typedef T  value_type;  
+  
+  RCPtr();
+  RCPtr(T* realPtr);
+  RCPtr(const RCPtr& rhs);
+
+  ~RCPtr();
+
+  RCPtr& operator=(const RCPtr& rhs);
+
+  RCPtr& operator=(T* realPtr);
+  
+  T* operator->() { return pointee; }
+  T& operator*() { return *pointee; }
+
+  const T* operator->() const { return pointee; }
+  const T& operator*() const { return *pointee; }
+
+  operator T*() { return pointee; }
+  operator T&() { return *pointee; }  
+
+  operator const T*() const { return pointee; }
+  operator const T&() const { return *pointee; }  
+
+  T* get() { return pointee; }
+  T* get() const { return pointee; }
+
+    
+private:
+  T* pointee;
+};
+
+
+template <class T>
+inline
+RCPtr<T>::RCPtr()
+  : pointee(0)
+{
+}
+
+template <class T>
+inline
+RCPtr<T>::RCPtr(T* realPtr)
+  : pointee(realPtr)
+{
+  addref(pointee);
+}
+
+template <class T>
+inline
+RCPtr<T>::RCPtr(const RCPtr& rhs)
+  : pointee(rhs.pointee)
+{
+  addref(pointee);
+}
+
+template <class T>
+inline
+RCPtr<T>::~RCPtr()
+{
+  delref(pointee);
+}
+
+template <class T>
+inline
+RCPtr<T>& RCPtr<T>::operator=(const RCPtr& rhs)
+{
+  if (pointee != rhs.pointee) {
+    delref(pointee);
+    pointee = rhs.pointee;
+    addref(pointee);
+  }
+  return *this;
+}
+
+
+
+#endif //TEST_SUITE_REFCOUNT_H__
diff --git a/trunk/Examples/test-suite/refcount.i b/trunk/Examples/test-suite/refcount.i
new file mode 100644
index 0000000..8352b50
--- /dev/null
+++ b/trunk/Examples/test-suite/refcount.i
@@ -0,0 +1,104 @@
+%module refcount
+
+%warnfilter(SWIGWARN_IGNORE_OPERATOR_EQ,SWIGWARN_LANG_IDENTIFIER);
+
+%{ 
+#include <iostream> 
+#include "refcount.h"
+%}
+
+//
+// using the %refobject/%unrefobject directives you can active the
+// ref. counting for RCObj and all its descendents at once
+//
+
+%refobject   RCObj "$this->addref();"
+%unrefobject RCObj "$this->delref();"
+
+%include "refcount.h"
+
+%newobject B::create(A* a);
+%newobject B::cloner();
+
+
+ 
+%inline %{
+
+  struct A : RCObj
+  {
+    A() {}
+    
+    ~A() 
+    {
+      // std::cout << "deleting a" << std::endl;
+    }
+
+#ifdef SWIGRUBY 
+    // fix strange ruby + virtual derivation problem
+    using RCObjBase::ref_count;
+#endif
+  };
+
+  struct A1 : A 
+  {
+  protected:
+    A1() {}
+  };
+
+  struct A2 : A
+  {
+  };
+
+  struct A3 : A1, private A2
+  {    
+  };
+
+%}
+
+#if defined(SWIGPYTHON)
+%extend_smart_pointer(RCPtr<A>);
+%template(RCPtr_A) RCPtr<A>;
+#endif
+
+%inline %{
+  
+  struct B : RCObj
+  {
+    B(A* a) : _a(a) {}
+    
+    A* get_a() 
+    {
+      return _a;
+    }
+    
+    static B* create(A* a)
+    {
+      return new B(a);
+    }
+    
+    B* cloner() 
+    {
+      return new B(_a);
+    }
+
+    ~B() 
+    {
+      // std::cout << "deleting b" << std::endl;
+    }
+
+    RCPtr<A> get_rca() {
+      return _a;      
+    }
+
+  private:
+    RCPtr<A> _a;
+  };
+
+%}
+
+#if defined(SWIGPYTHON) || defined(SWIGOCTAVE)
+
+%include <std_vector.i>
+%template(vector_A) std::vector<RCPtr<A> >;
+
+#endif
diff --git a/trunk/Examples/test-suite/reference_global_vars.i b/trunk/Examples/test-suite/reference_global_vars.i
new file mode 100644
index 0000000..8c80659
--- /dev/null
+++ b/trunk/Examples/test-suite/reference_global_vars.i
@@ -0,0 +1,65 @@
+// Tests global reference variables:
+//  - all non const primitives
+//  - const and non const class
+
+%module reference_global_vars
+
+%warnfilter(SWIGWARN_TYPEMAP_SWIGTYPELEAK);      /* memory leak when setting a ptr/ref variable */
+
+%inline %{
+class TestClass {
+public:
+    int num;
+    TestClass(int n = 0) : num(n) {}
+};
+%}
+
+// const class reference variable
+%{
+const TestClass& global_constTestClass = TestClass(33);
+%}
+%inline %{
+TestClass getconstTC() {
+    return global_constTestClass;
+}
+%}
+
+// Macro to help define similar functions
+%define ref(type,name)
+%{
+static type initial_value_##name;
+%}
+%inline %{
+static type &var_##name = initial_value_##name;
+type setref_##name(type &x) {
+    var_##name = x;
+    return var_##name;
+}
+type& createref_##name(type x) {
+    return *new type(x);
+}
+type value_##name(type &x) {
+    return x;
+}
+%}
+%enddef
+
+// primitive reference variables
+ref(bool,               bool);
+ref(char,               char);
+ref(unsigned char,      unsigned_char);
+ref(signed char,        signed_char);
+ref(short,              short);
+ref(unsigned short,     unsigned_short);
+ref(int,                int);
+ref(unsigned int,       unsigned_int);
+ref(long,               long);
+ref(unsigned long,      unsigned_long);
+ref(float,              float);
+ref(double,             double);
+ref(long long,          long_long);
+ref(unsigned long long, unsigned_long_long);
+
+// class reference variable
+ref(TestClass,          TestClass);
+
diff --git a/trunk/Examples/test-suite/register_par.i b/trunk/Examples/test-suite/register_par.i
new file mode 100644
index 0000000..030be45
--- /dev/null
+++ b/trunk/Examples/test-suite/register_par.i
@@ -0,0 +1,6 @@
+%module register_par
+
+// bug # 924413
+%inline {
+  void clear_tree_flags(register struct tree *tp, register int i) {}
+}
diff --git a/trunk/Examples/test-suite/rename.h b/trunk/Examples/test-suite/rename.h
new file mode 100644
index 0000000..4750337
--- /dev/null
+++ b/trunk/Examples/test-suite/rename.h
@@ -0,0 +1,44 @@
+
+namespace Space {
+struct Klass {
+  Klass(int i) {}
+  Klass() {}
+};
+}
+
+namespace AnotherSpace {
+  class Another {};
+}
+
+namespace Space {
+  using namespace AnotherSpace;
+  enum Enu { En1, En2, En3 };
+  template<typename T> struct NotXYZ {};
+  template<typename T> class XYZ {
+    NotXYZ<int> *m_int;
+    T m_t;
+    NotXYZ<T> m_notxyz;
+  public:
+    operator NotXYZ<int>*() const { return m_int; }
+    operator XYZ<int>*() const { return 0; }
+    operator Another() const { Another an; return an; }
+    void templateT(T i) {}
+    void templateNotXYZ(NotXYZ<T> i) {}
+    void templateXYZ(XYZ<T> i) {}
+    operator T() { return m_t; }
+    operator NotXYZ<T>() const { return m_notxyz; }
+    operator XYZ<T>() const { XYZ<T> xyz = XYZ<T>(); return xyz; }
+  };
+}
+
+namespace Space {
+// non-templated class using itself in method and operator
+class ABC {
+  public:
+    void method(ABC a) const {}
+    void method(Klass k) const {}
+    operator ABC() const { ABC a; return a; }
+    operator Klass() const { Klass k; return k; }
+};
+}
+
diff --git a/trunk/Examples/test-suite/rename1.i b/trunk/Examples/test-suite/rename1.i
new file mode 100644
index 0000000..38af2b3
--- /dev/null
+++ b/trunk/Examples/test-suite/rename1.i
@@ -0,0 +1,63 @@
+// Test %rename directive in global namespace by fully qualifying types
+%module rename1
+
+// Note: Space:: qualifier
+%rename(opIntPtrA) Space::XYZ::operator NotXYZ<int>*() const;
+%rename(opIntPtrB) Space::XYZ::operator XYZ<int>*() const;
+
+%rename(opAnother1) Space::XYZ::operator Another() const;
+%rename(opAnother2) Space::XYZ<int>::operator Another() const;
+%rename(opAnother3) Space::XYZ<Space::Klass>::operator Another() const;
+%rename(opAnother4) Space::XYZ<Space::Enu>::operator Another() const;
+
+%rename(tMethod1) Space::XYZ::templateT(T i);
+%rename(tMethod2) Space::XYZ<int>::templateT(int i);
+%rename(tMethod3) Space::XYZ<Space::Klass>::templateT(Space::Klass i);
+%rename(tMethod4) Space::XYZ<Space::Enu>::templateT(Space::Enu i);
+
+%rename(tMethodNotXYZ1) Space::XYZ::templateNotXYZ(NotXYZ<T>);
+%rename(tMethodNotXYZ2) Space::XYZ<int>::templateNotXYZ(NotXYZ<int>);
+%rename(tMethodNotXYZ3) Space::XYZ<Space::Klass>::templateNotXYZ(NotXYZ<Space::Klass>);
+%rename(tMethodNotXYZ4) Space::XYZ<Space::Enu>::templateNotXYZ(NotXYZ<Space::Enu>);
+
+%rename(tMethodXYZ1) Space::XYZ::templateXYZ(XYZ<T>);
+%rename(tMethodXYZ2) Space::XYZ<int>::templateXYZ(XYZ<int>);
+%rename(tMethodXYZ3) Space::XYZ<Space::Klass>::templateXYZ(XYZ<Space::Klass>);
+%rename(tMethodXYZ4) Space::XYZ<Space::Enu>::templateXYZ(XYZ<Space::Enu>);
+
+%rename(opT1) Space::XYZ::operator T();
+%rename(opT2) Space::XYZ<int>::operator int();
+%rename(opT3) Space::XYZ<Space::Klass>::operator Space::Klass();
+%rename(opT4) Space::XYZ<Space::Enu>::operator Space::Enu();
+
+%rename(opNotXYZ1) Space::XYZ::operator NotXYZ<T>() const;
+%rename(opNotXYZ2) Space::XYZ<int>::operator NotXYZ<int>() const;
+%rename(opNotXYZ3) Space::XYZ<Space::Klass>::operator NotXYZ<Space::Klass>() const;
+%rename(opNotXYZ4) Space::XYZ<Space::Enu>::operator NotXYZ<Space::Enu>() const;
+
+%rename(opXYZ1) Space::XYZ::operator XYZ<T>() const;
+%rename(opXYZ2) Space::XYZ<int>::operator XYZ<int>() const;
+%rename(opXYZ3) Space::XYZ<Space::Klass>::operator XYZ<Space::Klass>() const;
+%rename(opXYZ4) Space::XYZ<Space::Enu>::operator XYZ<Space::Enu>() const;
+
+
+%rename(methodABC) Space::ABC::method(ABC a) const;
+%rename(opABC) Space::ABC::operator ABC() const;
+%rename(methodKlass) Space::ABC::method(Klass k) const;
+%rename(opKlass) Space::ABC::operator Klass() const;
+
+%{
+#include "rename.h"
+%}
+%include "rename.h"
+
+%template(XYZInt) Space::XYZ<int>;
+%template(XYZDouble) Space::XYZ<double>;
+%template(XYZKlass) Space::XYZ<Space::Klass>;
+%template(XYZEnu) Space::XYZ<Space::Enu>;
+
+%template(NotXYZInt) Space::NotXYZ<int>;
+%template(NotXYZDouble) Space::NotXYZ<double>;
+%template(NotXYZKlass) Space::NotXYZ<Space::Klass>;
+%template(NotXYZEnu) Space::NotXYZ<Space::Enu>;
+
diff --git a/trunk/Examples/test-suite/rename2.i b/trunk/Examples/test-suite/rename2.i
new file mode 100644
index 0000000..6a9c22e
--- /dev/null
+++ b/trunk/Examples/test-suite/rename2.i
@@ -0,0 +1,65 @@
+// Test %rename directive in the Space namespace
+%module rename2
+
+namespace Space {
+// Note: no Space:: qualifier
+%rename(opIntPtrA) XYZ::operator NotXYZ<int>*() const;
+%rename(opIntPtrB) XYZ::operator XYZ<int>*() const;
+
+%rename(opAnother1) XYZ::operator Another() const;
+%rename(opAnother2) XYZ<int>::operator Another() const;
+%rename(opAnother3) XYZ<Space::Klass>::operator Another() const;
+%rename(opAnother4) XYZ<Space::Enu>::operator Another() const;
+
+%rename(tMethod1) XYZ::templateT(T i);
+%rename(tMethod2) XYZ<int>::templateT(int i);
+%rename(tMethod3) XYZ<Space::Klass>::templateT(Space::Klass i);
+%rename(tMethod4) XYZ<Space::Enu>::templateT(Space::Enu i);
+
+%rename(tMethodNotXYZ1) XYZ::templateNotXYZ(NotXYZ<T>);
+%rename(tMethodNotXYZ2) XYZ<int>::templateNotXYZ(NotXYZ<int>);
+%rename(tMethodNotXYZ3) XYZ<Space::Klass>::templateNotXYZ(NotXYZ<Space::Klass>);
+%rename(tMethodNotXYZ4) XYZ<Space::Enu>::templateNotXYZ(NotXYZ<Space::Enu>);
+
+%rename(tMethodXYZ1) XYZ::templateXYZ(XYZ<T>);
+%rename(tMethodXYZ2) XYZ<int>::templateXYZ(XYZ<int>);
+%rename(tMethodXYZ3) XYZ<Space::Klass>::templateXYZ(XYZ<Space::Klass>);
+%rename(tMethodXYZ4) XYZ<Space::Enu>::templateXYZ(XYZ<Space::Enu>);
+
+%rename(opT1) XYZ::operator T();
+%rename(opT2) XYZ<int>::operator int();
+%rename(opT3) XYZ<Space::Klass>::operator Space::Klass();
+%rename(opT4) XYZ<Space::Enu>::operator Space::Enu();
+
+%rename(opNotXYZ1) XYZ::operator NotXYZ<T>() const;
+%rename(opNotXYZ2) XYZ<int>::operator NotXYZ<int>() const;
+%rename(opNotXYZ3) XYZ<Space::Klass>::operator NotXYZ<Space::Klass>() const;
+%rename(opNotXYZ4) XYZ<Space::Enu>::operator NotXYZ<Space::Enu>() const;
+
+%rename(opXYZ1) XYZ::operator XYZ<T>() const;
+%rename(opXYZ2) XYZ<int>::operator XYZ<int>() const;
+%rename(opXYZ3) XYZ<Space::Klass>::operator XYZ<Space::Klass>() const;
+%rename(opXYZ4) XYZ<Space::Enu>::operator XYZ<Space::Enu>() const;
+
+
+%rename(methodABC) ABC::method(ABC a) const;
+%rename(opABC) ABC::operator ABC() const;
+%rename(methodKlass) ABC::method(Klass k) const;
+%rename(opKlass) ABC::operator Klass() const;
+}
+
+%{
+#include "rename.h"
+%}
+%include "rename.h"
+
+%template(XYZInt) Space::XYZ<int>;
+%template(XYZDouble) Space::XYZ<double>;
+%template(XYZKlass) Space::XYZ<Space::Klass>;
+%template(XYZEnu) Space::XYZ<Space::Enu>;
+
+%template(NotXYZInt) Space::NotXYZ<int>;
+%template(NotXYZDouble) Space::NotXYZ<double>;
+%template(NotXYZKlass) Space::NotXYZ<Space::Klass>;
+%template(NotXYZEnu) Space::NotXYZ<Space::Enu>;
+
diff --git a/trunk/Examples/test-suite/rename3.i b/trunk/Examples/test-suite/rename3.i
new file mode 100644
index 0000000..b39979f
--- /dev/null
+++ b/trunk/Examples/test-suite/rename3.i
@@ -0,0 +1,75 @@
+// Test %rename directive within %extend
+%module rename3
+
+namespace Space {
+  // Note no namespace nor class qualification
+  %extend XYZ {
+    %rename(opIntPtrA) operator NotXYZ<int>*() const;
+    %rename(opIntPtrB) operator XYZ<int>*() const;
+  }
+
+  %extend XYZ {
+    // Note use of type T
+    %rename(opAnother1) operator Another() const;
+    %rename(tMethod1) templateT(T i);
+    %rename(tMethodNotXYZ1) templateNotXYZ(NotXYZ<T>);
+    %rename(tMethodXYZ1) templateXYZ(XYZ<T>);
+    %rename(opT1) operator T();
+    %rename(opNotXYZ1) operator NotXYZ<T>() const;
+    %rename(opXYZ1) operator XYZ<T>() const;
+  }
+
+  %extend XYZ<int> {
+    %rename(opAnother2) operator Another() const;
+    %rename(tMethod2) templateT(int i);
+    %rename(tMethodNotXYZ2) templateNotXYZ(NotXYZ<int>);
+    %rename(tMethodXYZ2) templateXYZ(XYZ<int>);
+    %rename(opT2) operator int();
+    %rename(opNotXYZ2) operator NotXYZ<int>() const;
+    %rename(opXYZ2) operator XYZ<int>() const;
+  }
+
+  %extend XYZ<Space::Klass> {
+    %rename(opAnother3) operator Another() const;
+    %rename(tMethod3) templateT(Space::Klass i);
+    %rename(tMethodNotXYZ3) templateNotXYZ(NotXYZ<Space::Klass>);
+    %rename(tMethodXYZ3) templateXYZ(XYZ<Space::Klass>);
+    %rename(opT3) operator Space::Klass();
+    %rename(opNotXYZ3) operator NotXYZ<Space::Klass>() const;
+    %rename(opXYZ3) operator XYZ<Space::Klass>() const;
+  }
+
+  %extend XYZ<Space::Enu> {
+    %rename(opAnother4 )operator Another() const;
+    %rename(tMethod4) templateT(Space::Enu i);
+    %rename(tMethodNotXYZ4) templateNotXYZ(NotXYZ<Space::Enu>);
+    %rename(tMethodXYZ4) templateXYZ(XYZ<Space::Enu>);
+    %rename(opT4) operator Space::Enu();
+    %rename(opNotXYZ4) operator NotXYZ<Space::Enu>() const;
+    %rename(opXYZ4) operator XYZ<Space::Enu>() const;
+  }
+
+
+  %extend ABC {
+    %rename(methodABC) method(ABC a) const;
+    %rename(opABC) operator ABC() const;
+    %rename(methodKlass) method(Klass k) const;
+    %rename(opKlass) operator Klass() const;
+  }
+}
+
+%{
+#include "rename.h"
+%}
+%include "rename.h"
+
+%template(XYZInt) Space::XYZ<int>;
+%template(XYZDouble) Space::XYZ<double>;
+%template(XYZKlass) Space::XYZ<Space::Klass>;
+%template(XYZEnu) Space::XYZ<Space::Enu>;
+
+%template(NotXYZInt) Space::NotXYZ<int>;
+%template(NotXYZDouble) Space::NotXYZ<double>;
+%template(NotXYZKlass) Space::NotXYZ<Space::Klass>;
+%template(NotXYZEnu) Space::NotXYZ<Space::Enu>;
+
diff --git a/trunk/Examples/test-suite/rename4.i b/trunk/Examples/test-suite/rename4.i
new file mode 100644
index 0000000..3f61e0c
--- /dev/null
+++ b/trunk/Examples/test-suite/rename4.i
@@ -0,0 +1,108 @@
+// Test %rename directive with the 'using' keyword and within the class definition
+%module rename4
+
+%{
+#include "rename.h"
+%}
+
+namespace Space {
+struct Klass {
+  Klass(int i) {}
+  Klass() {}
+};
+}
+
+namespace AnotherSpace {
+  class Another {};
+}
+
+namespace Space {
+  %rename(opAnother1) XYZ::operator Another() const;
+  %rename(opAnother2) XYZ<int>::operator Another() const;
+  %rename(opAnother3) XYZ<Space::Klass>::operator Another() const;
+  %rename(opAnother4) XYZ<Space::Enu>::operator Another() const;
+}
+
+// Test %rename - no namespace, but specific templated type in the parameter, is used over the generic type T
+%rename(tMethod2) templateT(int i);
+%rename(tMethodNotXYZ2) templateNotXYZ(NotXYZ<int>);
+%rename(tMethodXYZ2) templateXYZ(XYZ<int>);
+%rename(opT2) operator int();
+%rename(opNotXYZ2) operator NotXYZ<int>() const;
+%rename(opXYZ2) operator XYZ<int>() const;
+
+%rename(tMethod3) templateT(Space::Klass i);
+%rename(tMethodNotXYZ3) templateNotXYZ(NotXYZ<Space::Klass>);
+%rename(tMethodXYZ3) templateXYZ(XYZ<Space::Klass>);
+%rename(opT3) operator Space::Klass();
+%rename(opNotXYZ3) operator NotXYZ<Space::Klass>() const;
+%rename(opXYZ3) operator XYZ<Space::Klass>() const;
+
+%rename(tMethod4) templateT(Space::Enu i);
+%rename(tMethodNotXYZ4) templateNotXYZ(NotXYZ<Space::Enu>);
+%rename(tMethodXYZ4) templateXYZ(XYZ<Space::Enu>);
+%rename(opT4) operator Space::Enu();
+%rename(opNotXYZ4) operator NotXYZ<Space::Enu>() const;
+%rename(opXYZ4) operator XYZ<Space::Enu>() const;
+
+namespace Space {
+  using namespace AnotherSpace;
+  enum Enu { En1, En2, En3 };
+  template<typename T> struct NotXYZ {};
+  template<typename T> class XYZ {
+
+    // Test %rename within the class
+    %rename(opIntPtrA) operator NotXYZ<int>*() const;
+    %rename(opIntPtrB) operator XYZ<int>*() const;
+
+    %rename(tMethod1) templateT(T i);
+    %rename(tMethodNotXYZ1) templateNotXYZ(NotXYZ<T>);
+    %rename(tMethodXYZ1) templateXYZ(XYZ<T>);
+    %rename(opT1) operator T();
+    %rename(opNotXYZ1) operator NotXYZ<T>() const;
+    %rename(opXYZ1) operator XYZ<T>() const;
+
+    NotXYZ<int> *m_int;
+    T m_t;
+    NotXYZ<T> m_notxyz;
+  public:
+    operator NotXYZ<int>*() const { return m_int; }
+    operator XYZ<int>*() const { return 0; }
+    operator Another() const { Another an; return an; }
+    void templateT(T i) {}
+    void templateNotXYZ(NotXYZ<T> i) {}
+    void templateXYZ(XYZ<T> i) {}
+    operator T() { return m_t; }
+    operator NotXYZ<T>() const { return m_notxyz; }
+    operator XYZ<T>() const { XYZ<T> xyz; return xyz; }
+  };
+}
+
+namespace Space {
+// non-templated class using itself in method and operator
+class ABC {
+  public:
+
+    %rename(methodABC) method(ABC a) const;
+    %rename(opABC) operator ABC() const;
+    %rename(methodKlass) method(Klass k) const;
+    %rename(opKlass) operator Klass() const;
+
+    void method(ABC a) const {}
+    void method(Klass k) const {}
+    operator ABC() const { ABC a; return a; }
+    operator Klass() const { Klass k; return k; }
+};
+}
+
+
+%template(XYZInt) Space::XYZ<int>;
+%template(XYZDouble) Space::XYZ<double>;
+%template(XYZKlass) Space::XYZ<Space::Klass>;
+%template(XYZEnu) Space::XYZ<Space::Enu>;
+
+%template(NotXYZInt) Space::NotXYZ<int>;
+%template(NotXYZDouble) Space::NotXYZ<double>;
+%template(NotXYZKlass) Space::NotXYZ<Space::Klass>;
+%template(NotXYZEnu) Space::NotXYZ<Space::Enu>;
+
diff --git a/trunk/Examples/test-suite/rename_camel.i b/trunk/Examples/test-suite/rename_camel.i
new file mode 100644
index 0000000..54f06f9
--- /dev/null
+++ b/trunk/Examples/test-suite/rename_camel.i
@@ -0,0 +1,68 @@
+%module rename_camel
+
+%rename("%(utitle)s",%$isfunction,%$ismember) ""; 
+%rename("%(ctitle)s",%$isvariable,%$ismember) ""; 
+
+%inline {
+  struct GeometryFactory 
+  {
+    void createPointFromInternalCoord(int);
+    void BIG_METHOD(int);
+  };  
+
+  class ByteOrderValues {
+    
+  public:
+    void readHEX();
+    static int ENDIAN_BIG;
+  };
+  
+}
+
+
+%define SedCmd "%(command:sed -e 's/\([a-z]\)/\U\\1/' -e 's/\(_\)\([a-z]\)/\U\\2/g' <<<)s" %enddef
+
+%rename(CamelCase1) camel_case_1;
+%rename(SedCmd)     camel_case_2;
+%rename("%(ctitle)s") camel_case_3;
+
+
+%rename("%(utitle)s") CamelCase_5;
+
+%define awk_cmd "%(command:awk '/^i/{print toupper($1)}' <<<)s" %enddef
+
+%rename(awk_cmd) "";
+
+%rename("%(title)s",rxsmatch$parentNode$type="enum .*") "";
+
+%inline 
+{
+  int camel_case_1(int);
+  int camel_case_2(int);
+  int camel_case_3(int);
+  int camel_case_4(int);
+  int camel_case(int);
+  int CamelCase_5(int);
+  int also_works_here(int);
+
+  enum HelloEnum {
+    hello, hi_there
+  };
+  
+
+  enum ChaoEnum {
+    bye, see_you
+  };
+
+  int import(int);
+  int foo(int);
+  
+}
+
+%rename("%(lowercase)s",sourcefmt="%(rxspencer:[GSL_(.*)][@1])s",%$isfunction) "";
+%inline {
+  void GSL_Hello() {}
+}
+
+
+
diff --git a/trunk/Examples/test-suite/rename_scope.i b/trunk/Examples/test-suite/rename_scope.i
new file mode 100644
index 0000000..6bea35b
--- /dev/null
+++ b/trunk/Examples/test-suite/rename_scope.i
@@ -0,0 +1,68 @@
+%module rename_scope
+
+%inline 
+%{ 
+  namespace oss 
+  { 
+    enum Polarization { UnaryPolarization, BinaryPolarization }; 
+ 
+    template <Polarization P> 
+    struct Interface 
+    { 
+    };    
+  } 
+%} 
+ 
+namespace oss 
+{ 
+  // Interface 
+  %template(Interface_UP) Interface<UnaryPolarization>; 
+  %template(Interface_BP) Interface<BinaryPolarization>; 
+ 
+} 
+%inline 
+%{ 
+  namespace oss 
+  { 
+    namespace interfaces 
+    { 
+      template <Polarization P> 
+      struct Natural : Interface<P> 
+      { 
+           int test(void) { return 1; }
+      };      
+    } 
+  } 
+%} 
+ 
+namespace oss 
+{ 
+  namespace interfaces 
+  {    
+    %rename(rtest) Natural<UnaryPolarization>::test;
+    %rename(rtest) Natural<oss::BinaryPolarization>::test;
+    
+    // Natural 
+    %template(Natural_UP) Natural<UnaryPolarization>; 
+    %template(Natural_BP) Natural<BinaryPolarization>; 
+  } 
+} 
+
+%rename("equals") operator==;
+
+%inline %{
+
+  namespace Utilities {
+    class Bucket
+    {
+    public:
+      Bucket() : m_left(0) {}
+      friend bool operator==(const Bucket& lhs, const Bucket& rhs){
+	return ( rhs.m_left == lhs.m_left );
+      }
+    private:
+      int m_left;
+    };
+  }
+  
+%}
diff --git a/trunk/Examples/test-suite/restrict_cplusplus.i b/trunk/Examples/test-suite/restrict_cplusplus.i
new file mode 100644
index 0000000..4e4bfc2
--- /dev/null
+++ b/trunk/Examples/test-suite/restrict_cplusplus.i
@@ -0,0 +1,7 @@
+%module restrict_cplusplus
+
+%inline %{
+struct Foo {
+    int restrict;
+};
+%}
diff --git a/trunk/Examples/test-suite/ret_by_value.i b/trunk/Examples/test-suite/ret_by_value.i
new file mode 100644
index 0000000..c69ade3
--- /dev/null
+++ b/trunk/Examples/test-suite/ret_by_value.i
@@ -0,0 +1,19 @@
+/* Simple test to check SWIG's handling of return by value */
+
+%module ret_by_value
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) test; /* Ruby, wrong class name */
+
+%inline %{
+
+typedef struct {
+   int myInt;
+   short myShort;
+} test;
+
+test get_test() {
+    test myTest = {100, 200};
+    return myTest;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/return_const_value.i b/trunk/Examples/test-suite/return_const_value.i
new file mode 100644
index 0000000..1d688d1
--- /dev/null
+++ b/trunk/Examples/test-suite/return_const_value.i
@@ -0,0 +1,45 @@
+/* This test a return by value constant SWIGTYPE.
+It was reported in bug 899332 by Jermey Brown (jhbrown94) */
+
+%module return_const_value
+
+
+%inline %{
+
+class Foo {
+public:
+    int _val;
+    Foo(int x): _val(x) {}
+    int getVal() const {
+        return _val;
+    }
+};
+
+class Foo_ptr {
+    Foo *_ptr;
+    mutable bool _own;
+  
+public:
+  Foo_ptr(Foo *p, bool own = false): _ptr(p), _own(own) {}
+  static Foo_ptr getPtr() {
+    return Foo_ptr(new Foo(17), true);
+  }
+  static const Foo_ptr getConstPtr() {
+    return Foo_ptr(new Foo(17), true);
+  }
+  const Foo *operator->() {
+    return _ptr;
+  }
+
+  Foo_ptr(const Foo_ptr& f) : _ptr(f._ptr), _own(f._own) 
+  {
+    f._own = 0;
+  }
+  
+
+  ~Foo_ptr() {
+    if(_own) delete _ptr;
+  }  
+};
+
+%}
diff --git a/trunk/Examples/test-suite/return_value_scope.i b/trunk/Examples/test-suite/return_value_scope.i
new file mode 100644
index 0000000..d7d97a1
--- /dev/null
+++ b/trunk/Examples/test-suite/return_value_scope.i
@@ -0,0 +1,28 @@
+%module return_value_scope
+%inline %{
+
+namespace Hell {
+class Foo {
+public:
+    Foo(int) { };
+};
+
+class Bar {
+public:
+   typedef Foo fooref;
+};
+
+class Spam {
+public:
+   typedef Bar base;
+   typedef base::fooref rettype;
+   rettype test() {
+       return rettype(1);
+   }
+};
+}
+%}
+
+
+
+
diff --git a/trunk/Examples/test-suite/rname.i b/trunk/Examples/test-suite/rname.i
new file mode 100644
index 0000000..dde71f2
--- /dev/null
+++ b/trunk/Examples/test-suite/rname.i
@@ -0,0 +1,57 @@
+// This module tests various facets of the %rename directive
+
+%module rname
+
+/* Applied everywhere */
+%rename(foo_i) foo(int);
+%rename(foo_d) foo(double);
+
+/* Applied only to global scope */
+
+%rename(foo_s) ::foo(short);
+
+/* Applied only to class scope */
+
+%rename(foo_u) *::foo(unsigned);
+
+/* Rename classes in a class hierarchy */
+%rename (RenamedBase) Base;
+%rename (RenamedDerived) Derived;
+
+/* Rename base class method applies to derived classes too */#
+%rename (newname) Base::oldname(double d) const;
+
+/* Rename derived class method only */
+%rename (func) Derived::fn(Base baseValue, Base* basePtr, Base& baseRef);
+
+%inline %{
+class Bar {
+public:
+   char *foo(int)      { return (char *) "Bar::foo-int"; }
+   char *foo(double)   { return (char *) "Bar::foo-double"; }
+   char *foo(short)    { return (char *) "Bar::foo-short"; }
+   char *foo(unsigned) { return (char *) "Bar::foo-unsigned"; }
+};
+
+char *foo(int)      { return (char *) "foo-int"; }
+char *foo(double)   { return (char *) "foo-double"; }
+char *foo(short)    { return (char *) "foo-short"; }
+char *foo(unsigned) { return (char *) "foo-unsigned"; }
+
+class Base {
+public: 
+  Base(){}; 
+  virtual ~Base(){};
+  void fn(Base baseValue, Base* basePtr, Base& baseRef){}
+  virtual const char * oldname(double d) const { return (char*) "Base"; }
+};
+class Derived : public Base {
+public:
+  Derived(){}
+  ~Derived(){}
+  void fn(Base baseValue, Base* basePtr, Base& baseRef){}
+  virtual const char * oldname(double d) const { return (char*) "Derived"; }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/ruby/Makefile.in b/trunk/Examples/test-suite/ruby/Makefile.in
new file mode 100644
index 0000000..7339373
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/Makefile.in
@@ -0,0 +1,71 @@
+#######################################################################
+# Makefile for ruby test-suite
+#######################################################################
+
+LANGUAGE     = ruby
+RUBY         = @RUBY@
+SCRIPTSUFFIX = _runme.rb
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+CPP_TEST_CASES = \
+	keywords \
+	li_cdata \
+	li_cstring \
+	li_factory \
+	li_std_functors \
+	li_std_map \
+	li_std_pair_lang_object \
+	li_std_queue \
+	li_std_set \
+	li_std_stack \
+	naming \
+	primitive_types \
+	std_containers \
+	track_objects \
+	track_objects_directors
+
+C_TEST_CASES += \
+	li_cdata \
+	li_cstring
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+SWIGOPT += -w801 -noautorename -features autodoc=4
+
+
+# Rules for the different types of tests
+
+# make sure -autorename is true for the naming test
+naming.cpptest: SWIGOPT = -autorename
+
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.rb appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile ruby_clean
diff --git a/trunk/Examples/test-suite/ruby/README b/trunk/Examples/test-suite/ruby/README
new file mode 100644
index 0000000..c4ace93
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/README
@@ -0,0 +1,4 @@
+See ../README for common README file.
+
+Any testcases which have _runme.rb appended after the testcase name will be detected and run.
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_access_runme.rb b/trunk/Examples/test-suite/ruby/abstract_access_runme.rb
new file mode 100755
index 0000000..6f91702
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_access_runme.rb
@@ -0,0 +1,34 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'abstract_access'
+
+include Abstract_access
+
+begin
+  a = A.new
+rescue TypeError
+  swig_assert(true, binding, 'A.new')
+end
+
+begin
+  b = B.new
+rescue TypeError
+  swig_assert(true, binding, 'B.new')
+end
+
+begin
+  c = C.new
+rescue TypeError
+  swig_assert(true, binding, 'C.new')
+end
+
+swig_assert( 'D.new' )
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_inherit_ok_runme.rb b/trunk/Examples/test-suite/ruby/abstract_inherit_ok_runme.rb
new file mode 100644
index 0000000..1d68993
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_inherit_ok_runme.rb
@@ -0,0 +1,48 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'abstract_inherit_ok'
+
+include Abstract_inherit_ok
+
+#
+# Shouldn't be able to instantiate Foo, because it declares
+# a pure virtual function.
+#
+
+exceptionRaised = false
+begin
+  Foo.new
+rescue NameError
+  exceptionRaised = true
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Abstract_inherit_ok::Foo
+	exceptionRaised = true
+ensure
+  swig_assert( "exceptionRaised", binding )
+end
+
+#
+# This one's OK since we cleared it with a %feature("notabstract")
+# declaration in the interface file.
+#
+
+exceptionRaised = false
+begin
+  spam = Spam.new
+  raise RuntimeError unless spam.blah == 0 
+rescue NameError
+  exceptionRaised = true
+ensure
+  swig_assert( "!exceptionRaised", binding )
+end
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_inherit_runme.rb b/trunk/Examples/test-suite/ruby/abstract_inherit_runme.rb
new file mode 100644
index 0000000..c9cef7d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_inherit_runme.rb
@@ -0,0 +1,61 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'abstract_inherit'
+
+include Abstract_inherit
+
+#
+# Shouldn't be able to instantiate any of these classes
+# since none of them implements the pure virtual function
+# declared in the base class (Foo).
+#
+
+exceptionRaised = false
+begin
+  Foo.new
+rescue NameError
+  exceptionRaised = true
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Abstract_inherit::Foo
+	exceptionRaised = true
+ensure
+  swig_assert( "exceptionRaised", binding )
+end
+
+exceptionRaised = false
+begin
+  Bar.new
+rescue NameError
+  exceptionRaised = true
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Abstract_inherit::Bar
+	exceptionRaised = true
+ensure
+  swig_assert( "exceptionRaised", binding )
+end
+
+exceptionRaised = false
+begin
+  Spam.new
+rescue NameError
+  exceptionRaised = true
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Abstract_inherit::Spam
+	exceptionRaised = true
+ensure
+  swig_assert( "exceptionRaised", binding )
+end
+
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_signature_runme.rb b/trunk/Examples/test-suite/ruby/abstract_signature_runme.rb
new file mode 100644
index 0000000..8c090a7
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_signature_runme.rb
@@ -0,0 +1,62 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'abstract_signature'
+
+include Abstract_signature
+
+#
+# Shouldn't be able to instantiate Abstract_foo, because it declares
+# a pure virtual function.
+#
+
+exceptionRaised = false
+begin
+  foo = Abstract_foo.new
+  begin
+    foo.meth(1)
+  rescue RuntimeError 
+    # here we are using directors
+    exceptionRaised = true
+  end
+rescue NameError
+  exceptionRaised = true
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Abstract_signature::Abstract_foo
+	exceptionRaised = true
+ensure
+  swig_assert( "exceptionRaised", binding)
+end
+
+#
+# Shouldn't be able to instantiate an Abstract_bar either, because it doesn't
+# implement the pure virtual function with the correct signature.
+#
+
+exceptionRaised = false
+begin
+  bar = Abstract_bar.new
+  begin
+    bar.meth(1)
+  rescue RuntimeError 
+    # here we are using directors
+    exceptionRaised = true
+  end
+rescue NameError
+  exceptionRaised = true
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Abstract_signature::Abstract_bar
+	exceptionRaised = true
+ensure
+  swig_assert( "exceptionRaised", binding)
+end
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_typedef2_runme.rb b/trunk/Examples/test-suite/ruby/abstract_typedef2_runme.rb
new file mode 100644
index 0000000..8c7d43f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_typedef2_runme.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'abstract_typedef2'
+
+include Abstract_typedef2
+
+swig_assert( 'a = A_UF.new' )
+
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_typedef_runme.rb b/trunk/Examples/test-suite/ruby/abstract_typedef_runme.rb
new file mode 100644
index 0000000..100f089
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_typedef_runme.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'abstract_typedef'
+
+include Abstract_typedef
+
+swig_assert_each_line(<<'EOF', binding)
+
+e = Engine.new
+a = A.new
+a.write(e)
+
+EOF
+
diff --git a/trunk/Examples/test-suite/ruby/abstract_virtual_runme.rb b/trunk/Examples/test-suite/ruby/abstract_virtual_runme.rb
new file mode 100644
index 0000000..08fb43b
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/abstract_virtual_runme.rb
@@ -0,0 +1,16 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'abstract_virtual'
+
+include Abstract_virtual
+
+swig_assert('d = D.new')
+swig_assert('e = E.new')
diff --git a/trunk/Examples/test-suite/ruby/access_change_runme.rb b/trunk/Examples/test-suite/ruby/access_change_runme.rb
new file mode 100755
index 0000000..5b3e99c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/access_change_runme.rb
@@ -0,0 +1,46 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'access_change'
+
+
+#
+# this test will currently fail, as it exposes functions that were
+# made protected from public.  swig limitation for now.
+#
+exit(0)
+
+include Access_change
+
+klass = BaseInt.new
+public = ['PublicProtectedPublic1', 'PublicProtectedPublic2',
+              'PublicProtectedPublic3', 'PublicProtectedPublic4']
+methods = (klass.public_methods - Object.methods).sort
+pmethods = (klass.protected_methods - Object.methods).sort
+swig_assert( methods == public, 
+             " incorrect public methods for BaseInt\n" +
+             "#{methods.inspect} !=\n#{public.inspect}" )
+
+klass = DerivedInt.new
+public = ['PublicProtectedPublic3', 'PublicProtectedPublic4',
+         'WasProtected1', 'WasProtected2', 'WasProtected3', 'WasProtected4']
+methods = (klass.public_methods - Object.methods).sort
+swig_assert( methods == public, 
+             " incorrect public methods for DerivedInt\n" + 
+             "#{methods.inspect} !=\n#{public.inspect}" )
+
+klass = BottomInt.new
+public = ['PublicProtectedPublic1', 'PublicProtectedPublic2',
+          'PublicProtectedPublic3', 'PublicProtectedPublic4',
+          'WasProtected1', 'WasProtected2']
+methods = (klass.public_methods - Object.methods).sort
+swig_assert( methods == public, 
+             " incorrect public methods for BottomInt\n" +
+             "#{methods.inspect} !=\n#{public.inspect}" )
diff --git a/trunk/Examples/test-suite/ruby/add_link_runme.rb b/trunk/Examples/test-suite/ruby/add_link_runme.rb
new file mode 100755
index 0000000..8f726d2
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/add_link_runme.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'add_link'
+include Add_link
+
+#
+# This test currently fails due to swig
+#
+exit(0)
+
+swig_assert( 'Foo.new' )
+swig_assert( 'Foo.blah' )
diff --git a/trunk/Examples/test-suite/ruby/aggregate_runme.rb b/trunk/Examples/test-suite/ruby/aggregate_runme.rb
new file mode 100644
index 0000000..4849fd1
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/aggregate_runme.rb
@@ -0,0 +1,37 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'aggregate'
+
+include Aggregate
+
+# Confirm that move() returns correct results under normal use
+result = move(UP)
+raise RuntimeError unless (result == UP)
+
+result = move(DOWN)
+raise RuntimeError unless (result == DOWN)
+
+result = move(LEFT)
+raise RuntimeError unless (result == LEFT)
+
+result = move(RIGHT)
+raise RuntimeError unless (result == RIGHT)
+
+# Confirm that it raises an exception when the contract is violated
+failed = false
+begin
+  move(0)
+rescue RuntimeError
+  failed = true
+end
+raise RuntimeError unless failed
+
diff --git a/trunk/Examples/test-suite/ruby/anonymous_bitfield_runme.rb b/trunk/Examples/test-suite/ruby/anonymous_bitfield_runme.rb
new file mode 100755
index 0000000..6949a3f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/anonymous_bitfield_runme.rb
@@ -0,0 +1,35 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'anonymous_bitfield'
+
+include Anonymous_bitfield
+
+foo = Foo.new
+
+{'x' => 4,
+  'y' => 3,
+  'f' => 1,
+  'z' => 8,
+  'seq' => 3 }.each do |m, v|
+  foo.send("#{m}=", v)
+  val = foo.send(m)
+  swig_assert("val == v", binding)
+end
+
+{'x' => (1 << 4),
+  'y' => (1 << 4),
+  'f' => (1 << 1),
+  'z' => (1 << 16),
+  'seq' => (1 << (4*8-6)) }.each do |m, v|
+  foo.send("#{m}=", v)
+  val = foo.send(m)
+  swig_assert("val != v", binding)
+end
diff --git a/trunk/Examples/test-suite/ruby/apply_signed_char_runme.rb b/trunk/Examples/test-suite/ruby/apply_signed_char_runme.rb
new file mode 100755
index 0000000..3256e1f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/apply_signed_char_runme.rb
@@ -0,0 +1,45 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'apply_signed_char'
+
+include Apply_signed_char
+
+
+['CharValFunction', 'CCharValFunction', 'CCharRefFunction'].each do |m|
+  [ 3, -3 ].each do |v|
+    val = send( m, v )
+    swig_assert( "v == val", binding, "for #{m}")
+  end
+end
+
+{ 'globalchar' => -109,
+  'globalconstchar' => -110,
+}.each do |k,v|
+  val = Apply_signed_char.send( k )
+  swig_assert( "v == val", binding, "for #{k}")
+end
+
+
+a = DirectorTest.new
+
+['CharValFunction', 'CCharValFunction', 'CCharRefFunction'].each do |m|
+  [ 3, -3 ].each do |v|
+    val = a.send( m, v )
+    swig_assert( "v == val", binding, "for DirectorTest.#{m}")
+  end
+end
+
+{ 'memberchar' => -111,
+  'memberconstchar' => -112,
+}.each do |k,v|
+  val = a.send( k )
+  swig_assert( "v == val", binding, "for #{k}")
+end
diff --git a/trunk/Examples/test-suite/ruby/apply_strings_runme.rb b/trunk/Examples/test-suite/ruby/apply_strings_runme.rb
new file mode 100755
index 0000000..299b96b
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/apply_strings_runme.rb
@@ -0,0 +1,61 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'apply_strings'
+
+include Apply_strings
+
+begin
+  x = UcharPtr.new
+  swig_assert( fail, "UcharPtr should not be defined")
+rescue NameError
+end
+
+ptr = 'a'
+['UCharFunction', 'SCharFunction', 'CUCharFunction',
+ 'CSCharFunction'].each do |m|
+  val = Apply_strings.send(m, ptr)
+  swig_assert( "val == ptr", binding )
+end
+
+
+['CharFunction', 'CCharFunction'].each do |m|
+  begin
+    val = Apply_strings.send(m, ptr)
+    swig_assert( false, nil, "Apply_strings.#{m} should raise TypeError" )
+  rescue TypeError
+  end
+end
+
+ptr = 'a'
+foo = DirectorTest.new
+['UCharFunction', 'SCharFunction', 'CUCharFunction',
+ 'CSCharFunction'].each do |m|
+  val = foo.send(m, ptr)
+  swig_assert( "val == ptr", binding, "DirectorTest.#{m}" )
+end
+
+
+['CharFunction', 'CCharFunction'].each do |m|
+  begin
+    val = foo.send(m, ptr)
+    swig_assert( false, nil, "DirectorTest.#{m} should raise TypeError" )
+  rescue TypeError
+  end
+end
+
+
+# ary = Apply_strings.DigitsGlobalB
+# { 0 => 'A',
+#   1 => 'B',
+#   2 => 'B' }.each do |k,v|
+#   val = ary[k]
+#   swig_assert( val == v, "Apply_strings.DigitsGlobalB[#{k}] #{val} != #{v}")
+# end
diff --git a/trunk/Examples/test-suite/ruby/argout_runme.rb b/trunk/Examples/test-suite/ruby/argout_runme.rb
new file mode 100755
index 0000000..54cb8f3
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/argout_runme.rb
@@ -0,0 +1,42 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'argout'
+
+include Argout
+
+swig_assert_each_line(<<'EOF', binding)
+
+t = new_intp
+intp_assign(t, 5)
+v = incp(t)
+val = intp_value(t)
+val == 6
+
+t = new_intp
+intp_assign(t, 5)
+v = incr(t)
+v == 5
+val = intp_value(t)
+val == 6
+
+t = new_intp
+intp_assign(t, 5)
+v = inctr(t)
+v == 5
+val = intp_value(t)
+val == 6
+
+EOF
+
+#
+# @todo: how to use voidhandle and handle?
+#
+
diff --git a/trunk/Examples/test-suite/ruby/array_member_runme.rb b/trunk/Examples/test-suite/ruby/array_member_runme.rb
new file mode 100644
index 0000000..686f5a3
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/array_member_runme.rb
@@ -0,0 +1,36 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'array_member'
+
+include Array_member
+
+f = Foo.new
+f.data = Array_member.global_data
+
+0.upto(7) { |i|
+  unless get_value(f.data, i) == get_value(Array_member.global_data, i)
+    raise RuntimeError, "Bad array assignment"
+  end
+}
+
+0.upto(7) { |i|
+  set_value(f.data, i, -i)
+}
+
+Array_member.global_data = f.data
+
+0.upto(7) { |i|
+  unless get_value(f.data, i) == get_value(Array_member.global_data, i)
+    raise RuntimeError, "Bad array assignment"
+  end
+}
+
diff --git a/trunk/Examples/test-suite/ruby/arrays_global_runme.rb b/trunk/Examples/test-suite/ruby/arrays_global_runme.rb
new file mode 100644
index 0000000..9835f2a
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/arrays_global_runme.rb
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'arrays_global'
+
+Arrays_global.array_i = Arrays_global.array_const_i
+
diff --git a/trunk/Examples/test-suite/ruby/arrays_runme.rb b/trunk/Examples/test-suite/ruby/arrays_runme.rb
new file mode 100755
index 0000000..749d817
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/arrays_runme.rb
@@ -0,0 +1,25 @@
+#!/usr/bin/env ruby
+#
+# Test run of arrays.i
+#
+#
+
+require 'swig_assert'
+require 'arrays'
+
+include Arrays
+
+a = SimpleStruct.new
+a.double_field = 2.0
+
+b = SimpleStruct.new
+b.double_field = 1.0
+
+# @bug:  this is broken
+#
+# c = [a,b]
+# fn_taking_arrays(c)
+#
+# a = ArrayStruct.new
+# a.array_i[0] = 0
+#
diff --git a/trunk/Examples/test-suite/ruby/bools_runme.rb b/trunk/Examples/test-suite/ruby/bools_runme.rb
new file mode 100644
index 0000000..373477c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/bools_runme.rb
@@ -0,0 +1,82 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+
+require 'bools'
+
+# bool constant check
+if (Bools::Constbool != false)
+    print "Runtime test 1 failed\n"
+    exit 1
+end
+
+# bool variables check
+if (Bools.bool1 != true)
+    print "Runtime test 2 failed\n"
+    exit 1
+end
+
+if (Bools.bool2 != false)
+    print "Runtime test 3 failed\n"
+    exit 1
+end
+
+if (Bools.value(Bools.pbool) != Bools.bool1)
+    print "Runtime test 4 failed\n"
+    exit 1
+end
+
+if (Bools.value(Bools.rbool) != Bools.bool2)
+    print "Runtime test 5 failed\n"
+    exit 1
+end
+
+if (Bools.value(Bools.const_pbool) != Bools.bool1)
+    print "Runtime test 6 failed\n"
+    exit 1
+end
+
+if (Bools.const_rbool != Bools.bool2)
+    print "Runtime test 7 failed\n"
+    exit 1
+end
+
+# bool functions check
+if (Bools.bo(false) != false)
+    print "Runtime test 8 failed\n"
+    exit 1
+end
+
+if (Bools.bo(true) != true)
+    print "Runtime test 9 failed\n"
+    exit 1
+end
+
+if (Bools.value(Bools.rbo(Bools.rbool)) != Bools.value(Bools.rbool))
+    print "Runtime test 10 failed\n"
+    exit 1
+end
+
+if (Bools.value(Bools.pbo(Bools.pbool)) != Bools.value(Bools.pbool))
+    print "Runtime test 11 failed\n"
+    exit 1
+end
+
+if (Bools.const_rbo(Bools.const_rbool) != Bools.const_rbool)
+    print "Runtime test 12 failed\n"
+    exit 1
+end
+
+if (Bools.value(Bools.const_pbo(Bools.const_pbool)) != Bools.value(Bools.const_pbool))
+    print "Runtime test 13 failed\n"
+    exit 1
+end
+
diff --git a/trunk/Examples/test-suite/ruby/cast_operator_runme.rb b/trunk/Examples/test-suite/ruby/cast_operator_runme.rb
new file mode 100755
index 0000000..4879bef
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/cast_operator_runme.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'cast_operator'
+include Cast_operator
+
+a = A.new
+t = a.tochar
+
+swig_assert( t == 'hi' )
diff --git a/trunk/Examples/test-suite/ruby/casts_runme.rb b/trunk/Examples/test-suite/ruby/casts_runme.rb
new file mode 100755
index 0000000..d1f536d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/casts_runme.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'casts'
+
+include Casts
+
+swig_assert( B.ancestors.include?(A), 'B.ancestors.include? A' )
+
+a = A.new
+a.hello
+
+b = B.new
+b.hello
+
+swig_assert( b.kind_of?( A ), ' B.kind_of? A' )
diff --git a/trunk/Examples/test-suite/ruby/char_constant_runme.rb b/trunk/Examples/test-suite/ruby/char_constant_runme.rb
new file mode 100644
index 0000000..4e9d9d5
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/char_constant_runme.rb
@@ -0,0 +1,34 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'char_constant'
+
+
+if Char_constant::CHAR_CONSTANT != 'x'
+  raise RuntimeError, "Invalid value for CHAR_CONSTANT."
+end
+  
+if Char_constant::STRING_CONSTANT != 'xyzzy'
+  raise RuntimeError, "Invalid value for STRING_CONSTANT."
+end
+
+if Char_constant::ESC_CONST != "\001"
+  raise RuntimeError, "Invalid value for ESC_CONST."
+end
+
+if Char_constant::NULL_CONST != "\000"
+  raise RuntimeError, "Invalid value for NULL_CONST."
+end
+
+if Char_constant::SPECIALCHAR != "\341"  #'á'
+  raise RuntimeError, "Invalid value for SPECIALCHAR."
+end
+
diff --git a/trunk/Examples/test-suite/ruby/check_missing_tests.rb b/trunk/Examples/test-suite/ruby/check_missing_tests.rb
new file mode 100755
index 0000000..97e197e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/check_missing_tests.rb
@@ -0,0 +1,53 @@
+#!/usr/bin/env ruby
+#
+# This script allows you to compare the tests in the current directory
+# (Ruby) against the tests of other languages to see which ones are missing
+#
+# 
+# 
+# 
+#
+
+
+ignore = ['ruby','std','typemaps']
+
+curr = Dir.pwd.sub(/.*\//, '')
+
+langs = Dir.glob('../*').select { |x| File.directory?("../#{x}") }
+langs.map! { |x| x.sub(/^\.\.\/*/, '') }
+langs -= ignore
+
+# Add generic test directory, too
+langs << ''
+
+testsB = Dir.glob("*runme*").map { |x| x.sub(/\.\w+$/, '') }
+
+
+all_tests = []
+
+langs.each do |lang|
+  testsA = Dir.glob("../#{lang}/*runme*")
+  testsA.map! { |x| x.sub(/.*\/(\w+)\.\w+$/, '\1') }
+  testsA.delete_if { |x| x =~ /~$/ } # ignore emacs backups
+
+  diff = testsA - testsB
+
+  unless diff.empty?
+    puts '-'*70
+    title = !lang.empty? ? "#{lang[0,1].upcase}#{lang[1..-1]}" : 'Generic'
+    title = "Missing #{title} tests"
+    puts title
+    puts '='*title.size
+    puts diff.join(', ')
+    all_tests += diff 
+  end
+
+end
+
+
+all_tests.uniq!
+
+puts '-'*70
+puts 'All missing tests'
+puts '================='
+puts all_tests.join(', ')
diff --git a/trunk/Examples/test-suite/ruby/class_ignore_runme.rb b/trunk/Examples/test-suite/ruby/class_ignore_runme.rb
new file mode 100755
index 0000000..28e4324
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/class_ignore_runme.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'class_ignore'
+
+a = Class_ignore::Bar.new
+
+# Even though we didn't wrap the Foo class, this call
+# to do_blah() should succeed.
+
+if Class_ignore.do_blah(a) != "Bar::blah"
+  raise RuntimeError
+end
diff --git a/trunk/Examples/test-suite/ruby/const_const_runme.rb b/trunk/Examples/test-suite/ruby/const_const_runme.rb
new file mode 100755
index 0000000..cadc73a
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/const_const_runme.rb
@@ -0,0 +1,14 @@
+#!/usr/bin/env ruby
+#
+#
+
+require 'swig_assert'
+
+require 'const_const'
+include Const_const
+
+swig_assert_each_line <<EOF
+foo(1)  # 1 is unused
+EOF
+
+
diff --git a/trunk/Examples/test-suite/ruby/constover_runme.rb b/trunk/Examples/test-suite/ruby/constover_runme.rb
new file mode 100755
index 0000000..49c0c81
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/constover_runme.rb
@@ -0,0 +1,55 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'constover'
+
+error = 0
+
+p = Constover.test("test")
+if p != "test"
+  puts "test failed!"
+  error = 1
+end
+
+p = Constover.test_pconst("test")
+if p != "test_pconst"
+  puts "test_pconst failed!"
+  error = 1
+end
+    
+f = Constover::Foo.new
+p = f.test("test")
+if p != "test"
+  print "member-test failed!"
+  error = 1
+end
+
+p = f.test_pconst("test")
+if p != "test_pconst"
+  print "member-test_pconst failed!"
+  error = 1
+end
+
+p = f.test_constm("test")
+if p != "test_constmethod"
+  print "member-test_constm failed!"
+  error = 1
+end
+
+p = f.test_pconstm("test")
+if p != "test_pconstmethod"
+  print "member-test_pconstm failed!"
+  error = 1
+end
+    
+exit(error)
+
+
diff --git a/trunk/Examples/test-suite/ruby/cpp_namespace_runme.rb b/trunk/Examples/test-suite/ruby/cpp_namespace_runme.rb
new file mode 100755
index 0000000..53649fa
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/cpp_namespace_runme.rb
@@ -0,0 +1,62 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+# Note: This example assumes that namespaces are flattened
+require 'cpp_namespace'
+
+n = Cpp_namespace.fact(4)
+if n != 24
+  raise "Bad return value!"
+end
+
+if Cpp_namespace.Foo != 42
+  raise "Bad variable value!"
+end
+
+t = Cpp_namespace::Test.new
+if t.method() != "Test::method"
+  raise "Bad method return value!"
+end
+
+if Cpp_namespace.do_method(t) != "Test::method"
+  raise "Bad return value!"
+end
+
+if Cpp_namespace.do_method2(t) != "Test::method"
+  raise "Bad return value!"
+end
+    
+Cpp_namespace.weird("hello", 4)
+
+t2 = Cpp_namespace::Test2.new
+t3 = Cpp_namespace::Test3.new
+t4 = Cpp_namespace::Test4.new
+t5 = Cpp_namespace::Test5.new
+
+if Cpp_namespace.foo3(42) != 42
+  raise "Bad return value!"
+end
+
+if Cpp_namespace.do_method3(t2, 40) != "Test2::method"
+  raise "Bad return value!"
+end
+
+if Cpp_namespace.do_method3(t3, 40) != "Test3::method"
+  raise "Bad return value!"
+end
+
+if Cpp_namespace.do_method3(t4, 40) != "Test4::method"
+  raise "Bad return value!"
+end
+
+if Cpp_namespace.do_method3(t5, 40) != "Test5::method"
+  raise "Bad return value!"
+end
diff --git a/trunk/Examples/test-suite/ruby/default_constructor_runme.rb b/trunk/Examples/test-suite/ruby/default_constructor_runme.rb
new file mode 100755
index 0000000..2706f67
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/default_constructor_runme.rb
@@ -0,0 +1,153 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'default_constructor'
+
+include Default_constructor
+
+# Ruby 1.6 raises NameError if you try to call Class.new where no constructor
+# is defined; Ruby 1.7 changed this to NoMethodError
+
+NoConstructorError = Kernel.const_defined?("NoMethodError") ? NoMethodError : NameError
+
+# This should be no problem
+a = A.new
+
+# Nor should this
+aa = AA.new
+
+# The default constructor for B is private, so this should raise an exception
+begin
+  b = B.new
+rescue ArgumentError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::BB
+	exceptionRaised = true
+end
+
+# The two-argument constructor for B should work
+b = B.new(3, 4)
+
+# BB shouldn't inherit B's default constructor, so this should raise an exception
+begin
+  bb = BB.new
+  puts "Whoa. new BB created."
+rescue NoConstructorError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::BB
+	exceptionRaised = true
+end
+
+# C's constructor is protected, so this should raise an exception
+begin
+  c = C.new
+  print "Whoa. new C created."
+rescue NoConstructorError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::C
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::C
+  # pass
+end
+
+# CC gets a default constructor, so no problem here
+cc = CC.new
+
+# D's constructor is private, so this should fail
+begin
+  d = D.new
+  puts "Whoa. new D created"
+rescue NoConstructorError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::D
+  # pass
+end
+
+# DD shouldn't get a default constructor, so this should fail
+begin
+  dd = DD.new
+  puts "Whoa. new DD created"
+rescue NoConstructorError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::DD
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::D
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::DD
+  # pass
+end
+
+# AD shouldn't get a default constructor, so this should fail
+begin
+  ad = AD.new
+  puts "Whoa. new AD created"
+rescue NoConstructorError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::AD
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::AD
+  # pass
+end
+
+# Both of the arguments to E's constructor have default values,
+# so this should be fine.
+e = E.new
+
+# EE should get a default constructor
+ee = EE.new
+
+# EB should not get a default constructor (because B doesn't have one)
+begin
+  eb = EB.new
+  puts "Whoa. new EB created"
+rescue NoConstructorError
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::EB
+  # pass
+rescue TypeError
+  # In Ruby 1.8 the exception raised is:
+  # TypeError: allocator undefined for Default_constructor::EB
+  # pass
+end
+
+# This should work fine
+f = F.new
+
+# This should work fine
+ff = FFF.new
+
+# This should work fine
+g = G.new
+
+# This should work fine
+gg = GG.new
diff --git a/trunk/Examples/test-suite/ruby/director_abstract_runme.rb b/trunk/Examples/test-suite/ruby/director_abstract_runme.rb
new file mode 100644
index 0000000..685ede1
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_abstract_runme.rb
@@ -0,0 +1,42 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_abstract'
+
+class MyFoo < Director_abstract::Foo
+  def ping
+    "MyFoo::ping()"
+  end
+end
+
+
+a = MyFoo.new
+
+if a.ping != "MyFoo::ping()"
+  raise RuntimeError, a.ping
+end
+
+if a.pong != "Foo::pong();MyFoo::ping()"
+  raise RuntimeError, a.pong
+end
+
+
+class MyExample1 < Director_abstract::Example1
+  def color(r,g,b)
+    r
+  end
+end
+
+#m1 = MyExample1.new
+#
+#if m1.color(1,2,3) != 1
+#  raise RuntimeError, m1.color
+#end
diff --git a/trunk/Examples/test-suite/ruby/director_basic_runme.rb b/trunk/Examples/test-suite/ruby/director_basic_runme.rb
new file mode 100644
index 0000000..a9019b6
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_basic_runme.rb
@@ -0,0 +1,36 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_basic'
+
+class MyFoo < Director_basic::Foo
+  def ping
+    "MyFoo::ping()"
+  end
+end
+
+a = MyFoo.new
+
+raise RuntimeError if a.ping != "MyFoo::ping()"
+raise RuntimeError if a.pong != "Foo::pong();MyFoo::ping()"
+
+b = Director_basic::Foo.new
+
+raise RuntimeError if b.ping != "Foo::ping()"
+raise RuntimeError if b.pong != "Foo::pong();Foo::ping()"
+
+
+a = Director_basic::MyClass.new 
+a = Director_basic::MyClassT_i.new 
+
+
+a = Director_basic::MyClass.new 1
+a = Director_basic::MyClassT_i.new 1
diff --git a/trunk/Examples/test-suite/ruby/director_constructor_runme.rb b/trunk/Examples/test-suite/ruby/director_constructor_runme.rb
new file mode 100644
index 0000000..f83f23e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_constructor_runme.rb
@@ -0,0 +1,37 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_constructor'
+
+include Director_constructor
+
+class Test < Foo
+  def initialize(i)
+    super(i)
+  end
+
+  def doubleit()
+    self.a = (self.a * 2)
+  end
+
+  def test
+    3
+  end
+end
+
+a = Test.new(5) #dies here
+
+raise RuntimeError if a.getit != 5
+raise RuntimeError if a.do_test != 3
+
+a.doubleit
+raise RuntimeError if a.getit != 10
+
diff --git a/trunk/Examples/test-suite/ruby/director_default_runme.rb b/trunk/Examples/test-suite/ruby/director_default_runme.rb
new file mode 100644
index 0000000..355f3c7
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_default_runme.rb
@@ -0,0 +1,30 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_default'
+
+
+
+a = Director_default::Foo.new 1
+a = Director_default::Foo.new 
+
+a.Msg 
+a.Msg "hello"
+a.GetMsg
+a.GetMsg "hello"
+
+a = Director_default::Bar.new 1
+a = Director_default::Bar.new 
+
+a.Msg 
+a.Msg "hello"
+a.GetMsg
+a.GetMsg "hello"
diff --git a/trunk/Examples/test-suite/ruby/director_detect_runme.rb b/trunk/Examples/test-suite/ruby/director_detect_runme.rb
new file mode 100644
index 0000000..c1bd8ad
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_detect_runme.rb
@@ -0,0 +1,54 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_detect'
+
+class MyBar < Director_detect::Bar
+  def initialize(v)
+    @val = v
+  end
+
+  def get_value
+    @val = @val + 1
+  end
+  
+  def get_class
+    @val = @val + 1
+    Director_detect::A
+  end
+
+  def just_do_it
+    @val = @val + 1
+  end
+
+  def clone
+    MyBar.new(@val)
+  end
+
+  def val
+    @val
+  end
+end
+
+
+b = MyBar.new(2)
+
+f = b
+
+v = f.get_value
+a = f.get_class
+f.just_do_it
+
+c = b.clone
+vc = c.get_value
+
+raise RuntimeError if (v != 3) || (b.val != 5) || (vc != 6)
+
diff --git a/trunk/Examples/test-suite/ruby/director_exception_runme.rb b/trunk/Examples/test-suite/ruby/director_exception_runme.rb
new file mode 100644
index 0000000..d31cd71
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_exception_runme.rb
@@ -0,0 +1,70 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_exception'
+
+include Director_exception
+
+class MyFoo < Foo
+  def ping
+    raise NotImplementedError, "MyFoo::ping() EXCEPTION"
+  end
+end
+
+class MyFoo2 < Foo
+  def ping
+    nil # error: should return a string
+  end
+end
+
+class MyFoo3 < Foo
+  def ping
+    5 # error: should return a string
+  end
+end
+
+ok = false
+
+a = MyFoo.new
+b = launder(a)
+
+begin
+  b.pong
+rescue NotImplementedError
+  ok = true
+end
+
+raise RuntimeError unless ok
+
+ok = false
+
+a = MyFoo2.new
+b = launder(a)
+
+begin
+  b.pong
+rescue TypeError
+  ok = true
+end
+
+
+a = MyFoo3.new
+b = launder(a)
+
+begin
+  b.pong
+rescue TypeError
+  ok = true
+end
+
+
+raise RuntimeError unless ok
+
diff --git a/trunk/Examples/test-suite/ruby/director_frob_runme.rb b/trunk/Examples/test-suite/ruby/director_frob_runme.rb
new file mode 100644
index 0000000..edd861c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_frob_runme.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_frob'
+
+foo = Director_frob::Bravo.new;
+s = foo.abs_method;
+
+raise RuntimeError if s != "Bravo::abs_method()"
diff --git a/trunk/Examples/test-suite/ruby/director_nested_runme.rb b/trunk/Examples/test-suite/ruby/director_nested_runme.rb
new file mode 100644
index 0000000..a376b0d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_nested_runme.rb
@@ -0,0 +1,54 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_nested'
+
+NoProtectedError = Kernel.const_defined?("NoMethodError") ? NoMethodError : NameError
+
+class A < Director_nested::FooBar_int
+  protected
+    def do_step
+      "A::do_step;"
+    end
+  
+    def get_value
+      "A::get_value"
+    end
+end
+
+a = A.new
+
+begin 
+  a.do_advance
+rescue NoProtectedError
+end
+
+raise RuntimeError if a.step != "Bar::step;Foo::advance;Bar::do_advance;A::do_step;"
+
+
+class B < Director_nested::FooBar_int
+  protected
+    def do_advance
+      "B::do_advance;" + do_step
+    end
+
+    def do_step
+      "B::do_step;"
+    end
+  
+    def get_value
+      "B::get_value"
+    end
+end
+
+
+b = B.new
+raise RuntimeError if b.step != "Bar::step;Foo::advance;B::do_advance;B::do_step;"
diff --git a/trunk/Examples/test-suite/ruby/director_protected_runme.rb b/trunk/Examples/test-suite/ruby/director_protected_runme.rb
new file mode 100644
index 0000000..3bee9ac
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_protected_runme.rb
@@ -0,0 +1,45 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_protected'
+
+NoProtectedError = Kernel.const_defined?("NoMethodError") ? NoMethodError : NameError
+
+class FooBar < Director_protected::Bar
+  protected
+    def ping
+      "FooBar::ping();"
+    end
+end
+
+class Hello < FooBar
+  public
+    def pang
+      ping
+    end
+end
+
+b = Director_protected::Bar.new
+fb = FooBar.new
+
+p = 0
+begin 
+  b.ping
+  p = 1
+rescue NoProtectedError
+end
+
+h = Hello.new
+
+raise RuntimeError if p == 1
+raise RuntimeError if b.pong != "Bar::pong();Foo::pong();Bar::ping();"
+raise RuntimeError if fb.pong != "Bar::pong();Foo::pong();FooBar::ping();"
+raise RuntimeError if h.pang != "FooBar::ping();"
diff --git a/trunk/Examples/test-suite/ruby/director_string_runme.rb b/trunk/Examples/test-suite/ruby/director_string_runme.rb
new file mode 100644
index 0000000..a18feac
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_string_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_string'
+
+class B < Director_string::A
+
+ def initialize(some_string)
+  super(some_string)
+ end
+end
+
+
+b = B.new("hello")
+b.get_first
+b.get(0)
diff --git a/trunk/Examples/test-suite/ruby/director_unroll_runme.rb b/trunk/Examples/test-suite/ruby/director_unroll_runme.rb
new file mode 100644
index 0000000..0545671
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_unroll_runme.rb
@@ -0,0 +1,28 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_unroll'
+
+class MyFoo < Director_unroll::Foo
+  def ping
+    "MyFoo::ping()"
+  end
+end
+
+a = MyFoo.new
+
+b = Director_unroll::Bar.new
+
+b.set(a)
+c = b.get()
+
+raise RuntimeError if a != c
+
diff --git a/trunk/Examples/test-suite/ruby/director_wombat_runme.rb b/trunk/Examples/test-suite/ruby/director_wombat_runme.rb
new file mode 100644
index 0000000..39f4a9e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/director_wombat_runme.rb
@@ -0,0 +1,60 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'director_wombat'
+
+include Director_wombat
+
+# Test base class functionality
+barObj = Bar.new
+
+# Bar#meth should return a Foo_integers instance
+fooIntsObj = barObj.meth
+raise RuntimeError unless fooIntsObj.instance_of?(Foo_integers)
+
+# Foo_integers#meth(n) should return n
+raise RuntimeError if fooIntsObj.meth(42) != 42
+
+#
+# Now subclass Foo_integers, but override its virtual method
+# meth(n) so that it returns the number plus one.
+#
+class MyFooInts < Foo_integers
+  def meth(n)
+    n + 1
+  end
+end
+
+#
+# Subclass Bar and override its virtual method meth()
+# so that it returns a new MyFooInts instance instead of
+# a Foo_integers instance.
+#
+class MyBar < Bar
+  def meth
+    MyFooInts.new
+  end
+end
+
+#
+# Now repeat previous tests:
+#
+# Create a MyBar instance...
+#
+barObj = MyBar.new
+
+# MyBar#meth should return a MyFooInts instance
+fooIntsObj = barObj.meth
+raise RuntimeError unless fooIntsObj.instance_of?(MyFooInts)
+
+# MyFooInts#meth(n) should return n+1
+raise RuntimeError if fooIntsObj.meth(42) != 43
+
diff --git a/trunk/Examples/test-suite/ruby/disown_runme.rb b/trunk/Examples/test-suite/ruby/disown_runme.rb
new file mode 100644
index 0000000..60b7421
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/disown_runme.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'disown'
+
+include Disown
+
+
+a = A.new
+b = B.new
+b.acquire(a)
+
diff --git a/trunk/Examples/test-suite/ruby/dynamic_cast_runme.rb b/trunk/Examples/test-suite/ruby/dynamic_cast_runme.rb
new file mode 100755
index 0000000..8239051
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/dynamic_cast_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'dynamic_cast'
+
+f = Dynamic_cast::Foo.new
+b = Dynamic_cast::Bar.new
+
+x = f.blah
+y = b.blah
+
+a = Dynamic_cast.do_test(y)
+if a != "Bar::test"
+  puts "Failed!!"
+end
+    
diff --git a/trunk/Examples/test-suite/ruby/enum_thorough_runme.rb b/trunk/Examples/test-suite/ruby/enum_thorough_runme.rb
new file mode 100755
index 0000000..e4a1ec7
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/enum_thorough_runme.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'enum_thorough'
+
+include Enum_thorough
+
+# Just test an in and out typemap for enum SWIGTYPE and const enum SWIGTYPE & typemaps
+raise RuntimeError if speedTest4(SpeedClass::Slow) != SpeedClass::Slow
+raise RuntimeError if speedTest5(SpeedClass::Slow) != SpeedClass::Slow
+
diff --git a/trunk/Examples/test-suite/ruby/enums_runme.rb b/trunk/Examples/test-suite/ruby/enums_runme.rb
new file mode 100644
index 0000000..cafac25
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/enums_runme.rb
@@ -0,0 +1,34 @@
+#!/usr/bin/env ruby
+#
+# Runtime tests for enums.i
+#
+
+require 'swig_assert'
+require 'enums'
+
+swig_assert_each_line( <<EOF )
+Enums::CSP_ITERATION_FWD == 0
+Enums::CSP_ITERATION_BWD == 11
+Enums::ABCDE == 0
+Enums::FGHJI == 1
+Enums.bar1(1)
+Enums.bar2(1)
+Enums.bar3(1)
+Enums::Boo == 0
+Enums::Hoo == 5
+Enums::Globalinstance1 == 0
+Enums::Globalinstance2 == 1
+Enums::Globalinstance3 == 30
+Enums::AnonEnum1 == 0
+Enums::AnonEnum2 == 100
+Enums::BAR1 == 0
+Enums::BAR2 == 1
+EOF
+
+#
+# @bug: 
+#
+# swig_assert_each_line( <<EOF )
+# Enums::IFoo::Phoo == 50
+# Enums::IFoo::Char == 'a'[0]
+# EOF
diff --git a/trunk/Examples/test-suite/ruby/extend_template_ns_runme.rb b/trunk/Examples/test-suite/ruby/extend_template_ns_runme.rb
new file mode 100644
index 0000000..d0ccee3
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/extend_template_ns_runme.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'extend_template_ns'
+
+include Extend_template_ns
+
+f = Foo_One.new
+if f.test1(37) != 37
+  raise RuntimeError
+end
+
+if f.test2(42) != 42
+  raise RuntimeError
+end
diff --git a/trunk/Examples/test-suite/ruby/extend_template_runme.rb b/trunk/Examples/test-suite/ruby/extend_template_runme.rb
new file mode 100644
index 0000000..62f22bc
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/extend_template_runme.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'extend_template'
+
+f = Extend_template::Foo_0.new
+if f.test1(37) != 37
+  raise RuntimeError
+end
+
+if f.test2(42) != 42
+  raise RuntimeError
+end
diff --git a/trunk/Examples/test-suite/ruby/friends_runme.rb b/trunk/Examples/test-suite/ruby/friends_runme.rb
new file mode 100644
index 0000000..c5c1caa
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/friends_runme.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'friends'
+
+
+a = Friends::A.new(2)
+
+raise RuntimeError if Friends::get_val1(a) != 2
+raise RuntimeError if Friends::get_val2(a) != 4
+raise RuntimeError if Friends::get_val3(a) != 6
diff --git a/trunk/Examples/test-suite/ruby/function_typedef_runme.rb b/trunk/Examples/test-suite/ruby/function_typedef_runme.rb
new file mode 100755
index 0000000..c17f44d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/function_typedef_runme.rb
@@ -0,0 +1,11 @@
+#!/usr/bin/env ruby
+#
+# Tests for function_typedef.i
+#
+#
+
+require 'swig_assert'
+require 'function_typedef'
+include Function_typedef
+
+# Hmm... not sure how to test this.
diff --git a/trunk/Examples/test-suite/ruby/grouping_runme.rb b/trunk/Examples/test-suite/ruby/grouping_runme.rb
new file mode 100644
index 0000000..ad60eec
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/grouping_runme.rb
@@ -0,0 +1,26 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'grouping'
+
+x = Grouping.test1(42)
+if x != 42
+  raise RuntimeError
+end
+
+Grouping.test2(42)
+
+x = Grouping.do_unary(37, Grouping::NEGATE)
+if x != -37
+  raise RuntimeError
+end
+
+Grouping.test3 = 42
diff --git a/trunk/Examples/test-suite/ruby/ignore_parameter_runme.rb b/trunk/Examples/test-suite/ruby/ignore_parameter_runme.rb
new file mode 100644
index 0000000..c5466a2
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/ignore_parameter_runme.rb
@@ -0,0 +1,34 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'ignore_parameter'
+
+include Ignore_parameter
+
+# Global function tests
+raise RuntimeError unless jaguar(0, 1.0) == "hello"
+raise RuntimeError unless lotus("foo", 1.0) == 101
+raise RuntimeError unless tvr("foo", 0) == 8.8
+raise RuntimeError unless ferrari() == 101
+
+# Member function tests
+sc = SportsCars.new
+raise RuntimeError unless sc.daimler(0, 1.0) == "hello"
+raise RuntimeError unless sc.astonmartin("foo", 1.0) == 101
+raise RuntimeError unless sc.bugatti("foo", 0) == 8.8
+raise RuntimeError unless sc.lamborghini() == 101
+
+# Constructor tests
+MiniCooper.new(0, 1.0)
+MorrisMinor.new("foo", 1.0)
+FordAnglia.new("foo", 0)
+AustinAllegro.new()
+
diff --git a/trunk/Examples/test-suite/ruby/imports_runme.rb b/trunk/Examples/test-suite/ruby/imports_runme.rb
new file mode 100755
index 0000000..8bd242e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/imports_runme.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+# This is the import runtime testcase.
+
+require 'imports_a'
+require 'imports_b'
+
+x = Imports_b::B.new
+
+x.hello
+
diff --git a/trunk/Examples/test-suite/ruby/inherit_missing_runme.rb b/trunk/Examples/test-suite/ruby/inherit_missing_runme.rb
new file mode 100644
index 0000000..aeaec24
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/inherit_missing_runme.rb
@@ -0,0 +1,31 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'inherit_missing'
+
+a = Inherit_missing.new_Foo()
+b = Inherit_missing::Bar.new
+c = Inherit_missing::Spam.new
+
+x = Inherit_missing.do_blah(a)
+if x != "Foo::blah"
+  puts "Whoa! Bad return #{x}"
+end
+
+x = Inherit_missing.do_blah(b)
+if x != "Bar::blah"
+  puts "Whoa! Bad return #{x}"
+end
+
+x = Inherit_missing.do_blah(c)
+if x != "Spam::blah"
+  puts "Whoa! Bad return #{x}"
+end
diff --git a/trunk/Examples/test-suite/ruby/integers_runme.rb b/trunk/Examples/test-suite/ruby/integers_runme.rb
new file mode 100755
index 0000000..b6ca458
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/integers_runme.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+
+require 'swig_assert'
+require 'integers'
+include Integers
+
+swig_assert_each_line <<EOF
+signed_char_identity(-3)   == -3
+unsigned_char_identity(5)  == 5
+signed_short_identity(-3)  == -3
+unsigned_short_identity(5) == 5
+signed_int_identity(-3)  == -3
+unsigned_int_identity(5) == 5
+signed_long_identity(-3)  == -3
+unsigned_long_identity(5) == 5
+signed_long_long_identity(-3)  == -3
+unsigned_long_long_identity(5) == 5
+EOF
diff --git a/trunk/Examples/test-suite/ruby/keywords.i b/trunk/Examples/test-suite/ruby/keywords.i
new file mode 100644
index 0000000..eb91b4f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/keywords.i
@@ -0,0 +1,65 @@
+%module keywords
+
+// fix up conflicts with C++ keywords
+%rename("and") Keywords::and_;
+%rename("break") Keywords::break_;
+%rename("case") Keywords::case_;
+%rename("class") Keywords::class_;
+%rename("defined?") Keywords::defined_;
+%rename("do") Keywords::do_;
+%rename("else") Keywords::else_;
+%rename("false") Keywords::false_;
+%rename("for") Keywords::for_;
+%rename("if") Keywords::if_;
+%rename("not") Keywords::not_;
+%rename("return") Keywords::return_;
+%rename("or") Keywords::or_;
+%rename("true") Keywords::true_;
+%rename("while") Keywords::while_;
+
+
+%inline %{
+
+class Keywords {
+public:
+  Keywords() {}
+
+  const char* alias() { return "alias"; }
+  const char* and_() { return "and"; }
+  const char* begin() { return "begin"; }
+  const char* break_() { return "break"; }
+  const char* case_() { return "case"; }
+  const char* class_() { return "class"; }
+  const char* def() { return "def"; }
+  const char* defined_() { return "defined?"; }
+  const char* do_() { return "do"; }
+  const char* else_() { return "else"; }
+  const char* elsif() { return "elsif"; }
+  const char* end() { return "end"; }
+  const char* ensure() { return "ensure"; }
+  const char* false_() { return "false"; }
+  const char* for_() { return "for"; }
+  const char* if_() { return "if"; }
+  const char* in() { return "in"; }
+  const char* module() { return "module"; }
+  const char* next() { return "next"; }
+  const char* nil() { return "nil"; }
+  const char* not_() { return "not"; }
+  const char* or_() { return "or"; }
+  const char* redo() { return "redo"; }
+  const char* rescue() { return "rescue"; }
+  const char* retry() { return "retry"; }
+  const char* return_() { return "return"; }
+  const char* self() { return "self"; }
+  const char* super() { return "super"; }
+  const char* then() { return "then"; }
+  const char* true_() { return "true"; }
+  const char* undef() { return "undef"; }
+  const char* under() { return "under"; }
+  const char* unless() { return "unless"; }
+  const char* until() { return "until"; }
+  const char* when() { return "when"; }
+  const char* while_() { return "while"; }
+  const char* yield() { return "yield"; }
+};
+%}
diff --git a/trunk/Examples/test-suite/ruby/keywords_runme.rb b/trunk/Examples/test-suite/ruby/keywords_runme.rb
new file mode 100644
index 0000000..cb8bd38
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/keywords_runme.rb
@@ -0,0 +1,159 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'keywords'
+
+kw = Keywords::Keywords.new
+
+if kw.alias != 'alias' then
+ raise RuntimeError, 'Keyword method did not work: alias'
+end
+
+if kw.and != 'and' then
+ raise RuntimeError, 'Keyword method did not work: and'
+end
+
+if kw.begin != 'begin' then
+ raise RuntimeError, 'Keyword method did not work: begin'
+end
+
+if kw.break != 'break' then
+ raise RuntimeError, 'Keyword method did not work: break'
+end
+
+if kw.case != 'case' then
+ raise RuntimeError, 'Keyword method did not work: case'
+end
+
+if kw.class != 'class' then
+ raise RuntimeError, 'Keyword method did not work: class'
+end
+
+if kw.def != 'def' then
+ raise RuntimeError, 'Keyword method did not work: def'
+end
+
+if kw.defined? != 'defined?' then
+ raise RuntimeError, 'Keyword method did not work: defined?'
+end
+
+if kw.do != 'do' then
+ raise RuntimeError, 'Keyword method did not work: do'
+end
+
+if kw.else != 'else' then
+ raise RuntimeError, 'Keyword method did not work: else'
+end
+
+if kw.elsif != 'elsif' then
+ raise RuntimeError, 'Keyword method did not work: elsif'
+end
+
+if kw.end != 'end' then
+ raise RuntimeError, 'Keyword method did not work: end'
+end
+
+if kw.ensure != 'ensure' then
+ raise RuntimeError, 'Keyword method did not work: ensure'
+end
+
+if kw.false != 'false' then
+ raise RuntimeError, 'Keyword method did not work: false'
+end
+
+if kw.for != 'for' then
+ raise RuntimeError, 'Keyword method did not work: for'
+end
+
+if kw.if != 'if' then
+ raise RuntimeError, 'Keyword method did not work: if'
+end
+
+if kw.in != 'in' then
+ raise RuntimeError, 'Keyword method did not work: in'
+end
+
+if kw.module != 'module' then
+ raise RuntimeError, 'Keyword method did not work: module'
+end
+
+if kw.next != 'next' then
+ raise RuntimeError, 'Keyword method did not work: next'
+end
+
+if kw.nil != 'nil' then
+ raise RuntimeError, 'Keyword method did not work: nil'
+end
+
+if kw.not != 'not' then
+ raise RuntimeError, 'Keyword method did not work: not'
+end
+
+if kw.or != 'or' then
+ raise RuntimeError, 'Keyword method did not work: or'
+end
+
+if kw.redo != 'redo' then
+ raise RuntimeError, 'Keyword method did not work: redo'
+end
+
+if kw.rescue != 'rescue' then
+ raise RuntimeError, 'Keyword method did not work: rescue'
+end
+
+if kw.retry != 'retry' then
+ raise RuntimeError, 'Keyword method did not work: retry'
+end
+
+if kw.return != 'return' then
+ raise RuntimeError, 'Keyword method did not work: return'
+end
+
+if kw.self != 'self' then
+ raise RuntimeError, 'Keyword method did not work: self'
+end
+
+if kw.super != 'super' then
+ raise RuntimeError, 'Keyword method did not work: super'
+end
+
+if kw.then != 'then' then
+ raise RuntimeError, 'Keyword method did not work: then'
+end
+
+if kw.true != 'true' then
+ raise RuntimeError, 'Keyword method did not work: true'
+end
+
+if kw.under != 'under' then
+ raise RuntimeError, 'Keyword method did not work: under'
+end
+
+if kw.unless != 'unless' then
+ raise RuntimeError, 'Keyword method did not work: unless'
+end
+
+if kw.until != 'until' then
+ raise RuntimeError, 'Keyword method did not work: until'
+end
+
+if kw.when != 'when' then
+ raise RuntimeError, 'Keyword method did not work: when'
+end
+
+if kw.while != 'while' then
+ raise RuntimeError, 'Keyword method did not work: while'
+end
+
+if kw.yield != 'yield' then
+ raise RuntimeError, 'Keyword method did not work: yield'
+end
+
diff --git a/trunk/Examples/test-suite/ruby/li_carrays_runme.rb b/trunk/Examples/test-suite/ruby/li_carrays_runme.rb
new file mode 100644
index 0000000..97241a0
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_carrays_runme.rb
@@ -0,0 +1,36 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_carrays'
+
+include Li_carrays
+
+#
+# Testing for %array_functions(int,intArray)
+#
+ary = new_intArray(2)
+intArray_setitem(ary, 0, 0)
+intArray_setitem(ary, 1, 1)
+intArray_getitem(ary, 0)
+intArray_getitem(ary, 1)
+delete_intArray(ary)
+
+#
+# Testing for %array_class(double, doubleArray)
+#
+ary = DoubleArray.new(2)
+ary[0] = 0.0
+ary[1] = 1.0
+ary[0]
+ary[1]
+ptr = ary.cast
+ary2 = DoubleArray.frompointer(ptr)
+
diff --git a/trunk/Examples/test-suite/ruby/li_cstring_runme.rb b/trunk/Examples/test-suite/ruby/li_cstring_runme.rb
new file mode 100755
index 0000000..a4ffcad
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_cstring_runme.rb
@@ -0,0 +1,22 @@
+#!/usr/bin/env ruby
+#
+# Test for li_cstring.i
+#
+
+require 'swig_assert'
+require 'li_cstring'
+
+include Li_cstring
+
+swig_assert_each_line <<EOF
+count("hello", 'l'[0]) == 2
+test1 == 'Hello World'
+test2
+test3('hello') == 'hello-suffix'
+test4('hello') == 'hello-suffix'
+test5(5) == 'xxxxx'
+test6(6) == 'xxx'
+test7    == 'Hello world!'
+test8    == (32..32+63).map {|x| x.chr }.join
+EOF
+
diff --git a/trunk/Examples/test-suite/ruby/li_factory_runme.rb b/trunk/Examples/test-suite/ruby/li_factory_runme.rb
new file mode 100644
index 0000000..a638b6f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_factory_runme.rb
@@ -0,0 +1,38 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_factory'
+
+circle = Li_factory::Geometry.create(Li_factory::Geometry::CIRCLE)
+r = circle.radius()
+if (r != 1.5)
+	raise RuntimeError, "Invalid value for r"
+end
+
+new_circle = circle.clone()
+r = new_circle.radius()
+if (r != 1.5)
+	raise RuntimeError, "Invalid value for r"
+end
+
+point = Li_factory::Geometry.create(Li_factory::Geometry::POINT)
+w = point.width()
+
+if (w != 1.0)
+	raise RuntimeError, "Invalid value for w"
+end
+
+new_point = point.clone()
+w = new_point.width()
+
+if (w != 1.0)
+	raise RuntimeError, "Invalid value for w"
+end
diff --git a/trunk/Examples/test-suite/ruby/li_math_runme.rb b/trunk/Examples/test-suite/ruby/li_math_runme.rb
new file mode 100755
index 0000000..0382783
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_math_runme.rb
@@ -0,0 +1,13 @@
+#!/usr/bin/env ruby
+#
+# li_math.i tests
+#
+#
+
+require 'swig_assert'
+require 'li_math'
+
+swig_assert_each_line <<EOF
+Li_math.cos(-5) == Math.cos(-5)
+Li_math.sin(-5) == Math.sin(-5)
+EOF
diff --git a/trunk/Examples/test-suite/ruby/li_std_deque_runme.rb b/trunk/Examples/test-suite/ruby/li_std_deque_runme.rb
new file mode 100644
index 0000000..1c1c6a8
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_deque_runme.rb
@@ -0,0 +1,55 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_deque'
+
+include Li_std_deque
+
+# Test constructors for std::deque<int>
+intDeque  = IntDeque.new
+intDeque2 = IntDeque.new(3)
+intDeque3 = IntDeque.new(4, 42)
+intDeque4 = IntDeque.new(intDeque3)
+
+# Test constructors for std::deque<double>
+doubleDeque  = DoubleDeque.new
+doubleDeque2 = DoubleDeque.new(3)
+doubleDeque3 = DoubleDeque.new(4, 42.0)
+doubleDeque4 = DoubleDeque.new(doubleDeque3)
+
+# Test constructors for std::deque<Real>
+realDeque  = RealDeque.new
+realDeque2 = RealDeque.new(3)
+realDeque3 = RealDeque.new(4, 42.0)
+realDeque4 = RealDeque.new(realDeque3)
+
+# average() should return the average of all values in a std::deque<int>
+intDeque << 2
+intDeque << 4
+intDeque << 6
+avg = average(intDeque)
+raise RuntimeError if avg != 4.0
+
+#
+# half() should return a std::deque<float>, where each element is half
+# the value of the corresponding element in the input deque<float>.
+# The original deque's contents are unchanged.
+#
+realDeque.clear
+realDeque << 2.0
+halfDeque = half(realDeque)
+raise RuntimeError unless halfDeque[0] == 1.0
+
+#
+# halve_in_place() should...
+#
+halve_in_place(doubleDeque)
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_functors.i b/trunk/Examples/test-suite/ruby/li_std_functors.i
new file mode 100644
index 0000000..067bb10
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_functors.i
@@ -0,0 +1,18 @@
+%module li_std_functors
+
+%include <std_vector.i>
+%include <std_deque.i>
+%include <std_list.i>
+%include <std_set.i>
+%include <std_map.i>
+%include <std_functors.i>
+
+%template(Vector  ) std::vector  <swig::LANGUAGE_OBJ>;
+%template(Deque   ) std::deque   <swig::LANGUAGE_OBJ>;
+%template(List    ) std::list    <swig::LANGUAGE_OBJ>;
+
+%template(Set     ) std::set     <swig::LANGUAGE_OBJ,
+                                   swig::BinaryPredicate<> >;
+%template(Map     ) std::map     <swig::LANGUAGE_OBJ,swig::LANGUAGE_OBJ,
+                                   swig::BinaryPredicate<> >;
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_functors_runme.rb b/trunk/Examples/test-suite/ruby/li_std_functors_runme.rb
new file mode 100755
index 0000000..d31735c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_functors_runme.rb
@@ -0,0 +1,70 @@
+#!/usr/bin/env ruby
+#
+# This is a test of STL containers using proc
+# objects to change the sorting function used in them.  Same as a
+# std::binary_predicate in C++.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'li_std_functors'
+
+
+def _set(container)
+  swig_assert_each_line(<<EOF, binding)
+    cont = #{container}.new
+    [9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
+    i0 = cont.begin()
+    cont.to_a == [1,2,3,4,5,6,7,8,9]
+    cont = #{container}.new( proc { |a,b| b < a } )
+    [9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
+    cont.to_a == [9, 8, 7, 6, 5, 4, 3, 2, 1]
+    cont = #{container}.new( proc { |a,b| b > a } )
+    [9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
+    cont.to_a == [1, 2, 3, 4, 5, 6, 7, 8, 9]
+    cont = #{container}.new(proc { |a,b| b < a } )
+    cont.insert(1)
+    cont.to_a == [1]
+    i0 = cont.begin()
+    cont.erase(i0) # don't use i0 anymore, it is invalid now
+    cont.to_a == []
+EOF
+end
+    
+def _map(container)
+  swig_assert_each_line(<<EOF, binding)
+    cont = #{container}.new
+    cont['z'] = 9
+    cont['y'] = 1
+    cont['x'] = 8
+    cont['w'] = 2
+    cont.to_a == [['w',2],['x',8],['y',1],['z',9]]
+
+    cont = #{container}.new(proc { |a,b| b < a } )
+    cont['z'] = 9
+    cont['y'] = 1
+    cont['x'] = 8
+    cont['w'] = 2
+    cont.to_a == [['z',9],['y',1],['x',8],['w',2]]
+EOF
+end
+
+def test
+  yield method(:_set), Li_std_functors::Set
+  yield method(:_map), Li_std_functors::Map
+end
+
+# these should fail and not segfault
+begin
+  Li_std_functors::Set.new('sd')
+rescue
+end
+
+test do |proc, container|
+  proc.call(container)
+end
+
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_map_runme.rb b/trunk/Examples/test-suite/ruby/li_std_map_runme.rb
new file mode 100755
index 0000000..319fdec
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_map_runme.rb
@@ -0,0 +1,60 @@
+#!/usr/bin/env ruby
+#
+# Tests for std::map and std::multimap
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'li_std_map'
+
+swig_assert_each_line(<<'EOF', binding)
+
+a1 = Li_std_map::A.new(3)
+a2 = Li_std_map::A.new(7)
+
+p0 = Li_std_map::Pairii.new(1,2)
+p1 = Li_std_map::PairA.new(1,a1)
+m = {}
+m[1] = a1
+m[2] = a2
+
+pp1 = Li_std_map::p_identa(p1)
+mm = Li_std_map::m_identa(m)
+
+m = Li_std_map::MapA.new
+m[1] = a1
+m[2] = a2
+m.respond_to?(:each_key) == true
+m.respond_to?(:each_value) == true
+
+pm ={}
+m.each_key { |k| pm[k] = m[k] }
+m.each_key { |k| swig_assert_equal("pm[k].object_id", "m[k].object_id", binding, 'only true if %trackings is on') }
+
+m = {}
+m[1] = [1,2]
+m["foo"] = "hello"
+
+pm = Li_std_map::LanguageMap.new
+m.each_key { |k| pm[k] = m[k] }
+m.each_key { |k| swig_assert_equal("pm[#{k.inspect}]", "m[#{k.inspect}]", binding) }
+
+m = Li_std_map::MmapA.new
+m[0] = a1
+m[0] = a2
+m[0].size == 2
+m.respond_to?(:each) == true
+m.respond_to?(:each_key) == true
+m.respond_to?(:each_value) == true
+m.values_at(0)[0] == m[0]
+EOF
+
+mii = Li_std_map::Mapii.new
+
+mii[1] = 1
+mii[1] = 2
+
+swig_assert( "mii[1] == 2", binding )
diff --git a/trunk/Examples/test-suite/ruby/li_std_pair_lang_object.i b/trunk/Examples/test-suite/ruby/li_std_pair_lang_object.i
new file mode 100644
index 0000000..a830af7
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_pair_lang_object.i
@@ -0,0 +1,8 @@
+%module li_std_pair_lang_object
+
+%include <std_pair.i>
+
+namespace std {
+  %template(ValuePair) pair< swig::LANGUAGE_OBJ, swig::LANGUAGE_OBJ >;
+}
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_pair_lang_object_runme.rb b/trunk/Examples/test-suite/ruby/li_std_pair_lang_object_runme.rb
new file mode 100644
index 0000000..3ce2bd3
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_pair_lang_object_runme.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_pair_lang_object'
+include Li_std_pair_lang_object
+
+swig_assert_each_line(<<'EOF', binding)
+val = ValuePair.new
+val.first = 'sd'
+val.second = [5,4,3]
+EOF
diff --git a/trunk/Examples/test-suite/ruby/li_std_pair_runme.rb b/trunk/Examples/test-suite/ruby/li_std_pair_runme.rb
new file mode 100755
index 0000000..685046f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_pair_runme.rb
@@ -0,0 +1,57 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_pair'
+include Li_std_pair
+
+swig_assert_each_line(<<'EOF', binding)
+#
+# Because of template specializations for pair<int, int>, these should return
+# an Array of size 2, where both elements are Fixnums.
+#
+intPair = makeIntPair(7, 6)
+intPair.instance_of?(Array)
+intPair.size == 2
+intPair[0] == 7 && intPair[1] == 6
+
+intPairConstRef = makeIntPairConstRef(7, 6)
+intPairConstRef.instance_of?(Array)
+intPairConstRef[0] == 7 && intPairConstRef[1] == 6
+
+#
+# Each of these should return a reference to a wrapped
+# std::pair<int, int> object (i.e. an IntPair instance).
+#
+intPairPtr = makeIntPairPtr(7, 6)
+intPairPtr.instance_of?(IntPair)
+intPairPtr[0] == 7 && intPairPtr[1] == 6
+
+intPairRef = makeIntPairRef(7, 6)
+intPairRef.instance_of?(IntPair)
+intPairRef[0] == 7 && intPairRef[1] == 6
+#
+# Now test various input typemaps. Each of the wrapped C++ functions
+# (product1, product2 and product3) is expecting an argument of a
+# different type (see li_std_pair.i). Typemaps should be in place to
+# convert this Array into the expected argument type.
+#
+product1(intPair) == 42
+product2(intPair) == 42
+product3(intPair) == 42
+
+#
+# Similarly, each of the input typemaps should know what to do
+# with an IntPair instance.
+#
+product1(intPairPtr) == 42
+product2(intPairPtr) == 42
+product3(intPairPtr) == 42
+EOF
diff --git a/trunk/Examples/test-suite/ruby/li_std_queue.i b/trunk/Examples/test-suite/ruby/li_std_queue.i
new file mode 100644
index 0000000..2d322b4
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_queue.i
@@ -0,0 +1,16 @@
+/**
+ * @file   std_queue.i
+ * @author gga
+ * @date   Sun May  6 01:52:44 2007
+ * 
+ * @brief  test of std::queue
+ * 
+ * 
+ */
+
+%module li_std_queue
+
+%include std_queue.i
+
+
+%template( IntQueue ) std::queue< int >;
diff --git a/trunk/Examples/test-suite/ruby/li_std_queue_runme.rb b/trunk/Examples/test-suite/ruby/li_std_queue_runme.rb
new file mode 100755
index 0000000..63101ed
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_queue_runme.rb
@@ -0,0 +1,32 @@
+#!/usr/bin/env ruby
+#
+# A simple std::queue test
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_queue'
+include Li_std_queue
+
+swig_assert_each_line(<<'EOF', binding)
+a = IntQueue.new
+a << 1
+a << 2
+a << 3
+a.back  == 3
+a.front == 1
+a.pop
+a.back  == 3
+a.front == 2
+a.pop
+a.back  == 3
+a.front == 3
+a.pop
+a.size == 0
+a.empty? == true
+
+EOF
diff --git a/trunk/Examples/test-suite/ruby/li_std_set_runme.rb b/trunk/Examples/test-suite/ruby/li_std_set_runme.rb
new file mode 100755
index 0000000..65354be
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_set_runme.rb
@@ -0,0 +1,63 @@
+#!/usr/bin/env ruby
+#
+# Put script description here.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_set'
+include Li_std_set
+
+swig_assert_each_line(<<'EOF', binding)
+s = Set_string.new
+
+s.push("a")
+s.push("b")
+s << "c"
+
+sum = ''
+s.each { |x| sum << x }
+sum == 'abc'
+
+b = s.begin  # only if swig iterators are on
+e = s.end
+sum = ''
+while b != e; sum << b.value; b.next; end
+sum == 'abc'
+
+b = s.rbegin  # only if swig iterators are on
+e = s.rend
+sum = ''
+while b != e; sum << b.value; b.next; end
+sum == 'cba'
+
+
+si = Set_int.new
+si << 1
+si.push(2)
+si.push(3)
+
+i = s.begin()
+i.next()
+s.erase(i)
+s.to_s == 'ac'
+
+b = s.begin
+e = s.end
+e - b == 2
+
+m = b + 1
+m.value == 'c'
+
+s = LanguageSet.new
+s.insert([1,2])
+s.insert(1)
+s.insert("hello")
+s.to_a == [1,[1,2],'hello']  # sort order: s.sort {|a,b| a.hash <=> b.hash}
+
+EOF
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_speed.i b/trunk/Examples/test-suite/ruby/li_std_speed.i
new file mode 100644
index 0000000..0dad816
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_speed.i
@@ -0,0 +1,26 @@
+/**
+ * @file   li_std_speed.i
+ * @author gga
+ * @date   Fri May 18 18:03:15 2007
+ * 
+ * @brief  A speed test of the ruby stl
+ * 
+ * 
+ */
+
+%module li_std_speed
+
+%include <std_list.i>
+%include <std_vector.i>
+%include <std_deque.i>
+%include <std_set.i>
+
+%template(RbList)   std::list<swig::GC_VALUE>;
+%template(RbVector) std::vector<swig::GC_VALUE>;
+%template(RbDeque)  std::deque<swig::GC_VALUE>;
+%template(RbSet)    std::set<swig::GC_VALUE>; 
+
+%template(RbFloatList)   std::list<float>;
+%template(RbFloatVector) std::vector<float>;
+%template(RbFloatDeque)  std::deque<float>;
+%template(RbFloatSet)    std::set<float>; 
diff --git a/trunk/Examples/test-suite/ruby/li_std_speed2_runme.rb b/trunk/Examples/test-suite/ruby/li_std_speed2_runme.rb
new file mode 100755
index 0000000..1c4e15f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_speed2_runme.rb
@@ -0,0 +1,67 @@
+#!/usr/bin/env ruby
+
+require 'benchmark'
+require 'li_std_speed'
+include Li_std_speed
+
+def benchmark(f, phigh, sequences)
+  print f.class
+  puts '%10s ' % 'n' + sequences.inject('') { |a,s| a << '%10s' % s.class }
+  0.upto(phigh-1) do |p|
+    n = 2**p
+    print "%10d"%n
+    $stdout.flush
+    for s in sequences
+      cont = s.new((0..n).to_a)
+      Benchmark.benchmark { f.call(cont) }
+    end
+  end
+end
+
+def iterate(cont)
+   # expected: O(n)
+   # got: O(n**2) for set/list (vector/deque fine)
+   it = cont.begin
+   last = cont.end
+   while it != last 
+     it.next
+   end
+end
+
+
+def erase(cont)
+   # expected: O(n)
+   # got: O(n**2) for vector/deque and O(n**3) for set/list
+   it = cont.end
+   # can't reuse begin since it might get invalidated
+   while it != cont.begin
+     it.previous
+     # set returns None, so need to reobtain end
+     it = cont.erase(it) or cont.end
+   end
+end
+
+def insert(cont)
+   it = cont.end
+   size = cont.size
+   if cont.kind_of? RbSet
+       # swig stl missing hint version of insert for set
+       # expected would be O(n) with iterator hint version
+       # expected: O(n*log(n))
+       # got: O(n**3*log(n))
+     size.upto(size<<1) { |x| cont.insert(x) }
+   else
+     # expected: O(n)
+     # got: O(n**3) for list (vector/deque fine)
+     size.upto(size<<1) { |x| cont.push(x) }
+   end
+end
+
+if $0 == __FILE__
+  sequences = [RbVector,RbDeque,RbSet,RbList]
+  for f,phigh in [[method(:iterate),15], [method(:insert),15],
+                  [method(:erase),11]]
+    benchmark(f, phigh, sequences)
+  end
+end
+       
diff --git a/trunk/Examples/test-suite/ruby/li_std_speed_runme.rb b/trunk/Examples/test-suite/ruby/li_std_speed_runme.rb
new file mode 100755
index 0000000..a67e618
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_speed_runme.rb
@@ -0,0 +1,85 @@
+#!/usr/bin/env ruby
+#
+# This is a simple speed benchmark suite for std containers,
+# to verify their O(n) performance.
+# It is not part of the standard tests.
+#
+# License::   SWIG
+#
+
+
+require 'benchmark'
+require 'mathn'
+require 'li_std_speed'
+include Li_std_speed
+
+
+def benchmark(f, phigh, sequences)
+  puts f
+  print '%10s' % 'n'
+  maxlen = sequences.max { |a,b| a.to_s.size <=> b.to_s.size }
+  maxlen = maxlen.to_s.size - 12
+  sequences.each { |s| print "%#{maxlen}s" % "#{s.to_s.sub(/.*::/,'')}" }
+  puts
+  o_perf = Array.new(sequences.size, 0)
+  last_t = Array.new(sequences.size, nil)
+  1.upto(phigh) do |p|
+    n = 2**(p-1)
+    print "%10d" % n
+    sequences.each_with_index do |s, i|
+      cont = s.new((0..n).to_a)
+      Benchmark.benchmark('',0,"%#{maxlen-2}.6r") { |x|
+        t = x.report { f.call(cont) }
+        o_perf[i] += last_t[i] ? (t.real / last_t[i]) : t.real
+        last_t[i] = t.real
+      }
+    end
+    puts
+  end
+
+  print "  avg. O(n)"
+  base = 1.0 / Math.log(2.0)
+  sequences.each_with_index do |s, i|
+    o_perf[i] /= phigh
+    # o_perf[i] = 1 if o_perf[i] < 1
+    o_perf[i]  = Math.log(o_perf[i]) * base
+    print "%#{maxlen-1}.2f " % o_perf[i]
+  end
+  puts
+end
+
+def iterate(cont)
+   it = cont.begin
+   last = cont.end
+   while it != last 
+     it.next
+   end
+end
+
+
+def erase(cont)
+   it = cont.end
+   # can't reuse begin since it might get invalidated
+   while it != cont.begin
+     it.previous
+     # set returns None, so need to reobtain end
+     it = cont.erase(it) || cont.end
+   end
+end
+
+def insert(cont)
+  size = cont.size
+  size.upto((size<<1) - 1) { |x| cont.push(x) }
+end
+
+if $0 == __FILE__
+  GC.disable
+  sequences = [RbVector,RbDeque,RbSet,RbList,
+               RbFloatVector,RbFloatDeque,RbFloatSet,RbFloatList]
+  n = 17
+  for f,phigh in [[method(:iterate),n], [method(:insert),n],
+                  [method(:erase),n-4]]
+    benchmark(f, phigh, sequences)
+  end
+end
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_stack.i b/trunk/Examples/test-suite/ruby/li_std_stack.i
new file mode 100644
index 0000000..d292540
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_stack.i
@@ -0,0 +1,16 @@
+/**
+ * @file   std_stack.i
+ * @author gga
+ * @date   Sun May  6 01:52:44 2007
+ * 
+ * @brief  test of std::stack
+ * 
+ * 
+ */
+
+%module li_std_stack
+
+%include std_stack.i
+
+
+%template( IntStack ) std::stack< int >;
diff --git a/trunk/Examples/test-suite/ruby/li_std_stack_runme.rb b/trunk/Examples/test-suite/ruby/li_std_stack_runme.rb
new file mode 100755
index 0000000..806bba0
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_stack_runme.rb
@@ -0,0 +1,30 @@
+#!/usr/bin/env ruby
+#
+# A simple std::stack test
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_stack'
+include Li_std_stack
+
+swig_assert_each_line(<<'EOF', binding)
+a = IntStack.new
+a << 1
+a << 2
+a << 3
+a.top == 3
+a.pop
+a.top == 2
+a.pop
+a.top == 1
+a.pop
+a.size == 0
+a.empty? == true
+# a.top == Qnil
+
+EOF
diff --git a/trunk/Examples/test-suite/ruby/li_std_stream_runme.rb b/trunk/Examples/test-suite/ruby/li_std_stream_runme.rb
new file mode 100755
index 0000000..80c5166
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_stream_runme.rb
@@ -0,0 +1,22 @@
+#!/usr/bin/env ruby
+#
+# Simple test of std::ostringstream.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_stream'
+include Li_std_stream
+
+swig_assert_each_line(<<'EOF', binding)
+
+a = A.new
+o = Ostringstream.new
+o << a << " " << 2345 << " " << 1.435
+o.str == "A class 2345 1.435"
+
+EOF
diff --git a/trunk/Examples/test-suite/ruby/li_std_string_runme.rb b/trunk/Examples/test-suite/ruby/li_std_string_runme.rb
new file mode 100644
index 0000000..dc85b5d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_string_runme.rb
@@ -0,0 +1,144 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_string'
+
+include Li_std_string
+
+# Checking expected use of %typemap(in) std::string {}
+test_value("Fee")
+
+# Checking expected result of %typemap(out) std::string {}
+raise RuntimeError unless test_value("Fi") == "Fi"
+
+# Verify type-checking for %typemap(in) std::string {}
+exceptionRaised = false
+begin
+  test_value(0)
+rescue TypeError
+  exceptionRaised = true
+ensure
+  raise RuntimeError unless exceptionRaised
+end
+
+# Checking expected use of %typemap(in) const std::string & {}
+test_const_reference("Fo")
+
+# Checking expected result of %typemap(out) const std::string& {}
+raise RuntimeError unless test_const_reference("Fum") == "Fum"
+
+# Verify type-checking for %typemap(in) const std::string & {}
+exceptionRaised = false
+begin
+  test_const_reference(0)
+rescue TypeError
+  exceptionRaised = true
+ensure
+  raise RuntimeError unless exceptionRaised
+end
+
+#
+# Input and output typemaps for pointers and non-const references to
+# std::string are *not* supported; the following tests confirm
+# that none of these cases are slipping through.
+#
+
+exceptionRaised = false
+begin
+  test_pointer("foo")
+rescue TypeError
+  exceptionRaised = true
+ensure
+  raise RuntimeError unless exceptionRaised
+end
+
+result = test_pointer_out()
+raise RuntimeError if result.is_a? String
+
+exceptionRaised = false
+begin
+  test_const_pointer("bar")
+rescue TypeError
+  exceptionRaised = true
+ensure
+  raise RuntimeError unless exceptionRaised
+end
+
+result = test_const_pointer_out()
+raise RuntimeError if result.is_a? String
+
+exceptionRaised = false
+begin
+  test_reference("foo")
+rescue TypeError
+  exceptionRaised = true
+ensure
+  raise RuntimeError unless exceptionRaised
+end
+
+result = test_reference_out()
+raise RuntimeError if result.is_a? String
+
+
+# Member Strings
+myStructure = Structure.new
+if (myStructure.MemberString2 != "member string 2")
+  raise RuntimeError
+end
+s = "Hello"
+myStructure.MemberString2 = s
+if (myStructure.MemberString2 != s)
+  raise RuntimeError
+end
+if (myStructure.ConstMemberString != "const member string")
+  raise RuntimeError 
+end
+
+
+if (Structure.StaticMemberString2 != "static member string 2")
+  raise RuntimeError
+end
+Structure.StaticMemberString2 = s
+if (Structure.StaticMemberString2 != s)
+  raise RuntimeError
+end
+if (Structure.ConstStaticMemberString != "const static member string")
+  raise RuntimeError
+end
+
+
+if (test_reference_input("hello") != "hello")
+  raise RuntimeError
+end
+s = test_reference_inout("hello")
+if (s != "hellohello")
+  raise RuntimeError
+end
+
+
+if (stdstring_empty() != "")
+  raise RuntimeError
+end
+
+if (c_empty() != "") 
+  raise RuntimeError
+end
+
+
+if (c_null() != nil) 
+  raise RuntimeError
+end
+
+
+if (get_null(c_null()) != nil) 
+  raise RuntimeError
+end
+
diff --git a/trunk/Examples/test-suite/ruby/li_std_vector_runme.rb b/trunk/Examples/test-suite/ruby/li_std_vector_runme.rb
new file mode 100755
index 0000000..484f188
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/li_std_vector_runme.rb
@@ -0,0 +1,115 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'li_std_vector'
+
+include Li_std_vector
+
+iv = IntVector.new(4)
+
+swig_assert( "iv.respond_to? :each", binding )
+
+begin
+  iv.each
+  swig_assert( false, nil, "iv.each worked with no block!")
+rescue ArgumentError
+end
+
+swig_assert_each_line(<<'EOF', binding)
+iv.respond_to?(:each) == true
+iv.respond_to?(:each_with_index) == true
+EOF
+
+iv.each_with_index { |e,i| 
+  swig_assert("#{e} == 0", binding, "for iv[#{i}] == 0") 
+}
+
+0.upto(3) { |i| iv[i] = i }
+
+{ "iv[-1]" => 3,
+  "iv.slice(0,2).to_s" => "01", 
+  "iv.slice(1,2).to_s" => "12", 
+  "iv[0,-2]" => nil,
+  "iv[0,3].to_s" => "012",
+  "iv[0,10].to_s" => "012",
+  "iv[1..2].to_s" => '12',
+  "iv[1..3].to_s" => '123',
+  "iv[1..4].to_s" => '123',
+  "iv[1..-2].to_s" => '12',
+  "iv[2..-3]" => nil,
+}.each do |k,v|
+  swig_assert( "#{k} == #{v.inspect}", binding )
+end
+
+swig_assert_each_line(<<'EOF', binding)
+iv << 5
+iv.push 5
+iv.pop == 5
+iv.unshift(7)
+iv.shift == 7
+iv.unshift(7, 3)
+iv.insert(1,5)
+iv.insert(0, 3)
+iv.unshift(2,3,4)
+x = average(iv)
+y = average([1, 2, 3, 4])
+half([10, 10.5, 11, 11.5])
+EOF
+
+dv = DoubleVector.new(10)
+
+swig_assert( "dv.respond_to? :each_with_index", binding )
+
+dv.each_with_index { |e,i| swig_assert_equal("dv[#{i}]", 0.0, binding) }
+
+0.upto(9) { |i| dv[i] = i/2.0 }
+
+{ "dv[-1]" => 4.5,
+  "dv.slice(0,2).to_s" => "0.00.5",
+  "dv[0,-2]" => nil,
+  "dv[0,3].to_s" => "0.00.51.0",
+  "dv[3,3].to_s" => "1.52.02.5",
+}.each do |k,v|
+  swig_assert_equal( k, v.inspect, binding )
+end
+
+swig_assert_each_line(<<'EOF', binding)
+dv.delete_at(2)
+dv.delete_if { |x| x == 2.0 }
+dv.include? 3.0
+dv.find {|x| x == 3.0 }
+dv.kind_of? DoubleVector
+halved = []
+halved = dv.map { |x| x / 2 }
+halve_in_place(dv)
+halved.to_a == dv.to_a
+sv = StructVector.new
+sv << Li_std_vector::Struct.new
+sv[0].class == Li_std_vector::Struct
+sv[1] = Li_std_vector::Struct.new
+
+EOF
+
+
+swig_assert_each_line(<<'EOF', binding)
+lv = LanguageVector.new
+lv << 1
+lv << [1,2]
+lv << 'asd'
+lv[0], lv[1] = lv[1], lv[0]
+EOF
+
+
+# this should assert
+begin
+  lv = LanguageVector.new('crapola')
+rescue
+end
diff --git a/trunk/Examples/test-suite/ruby/member_pointer_runme.rb b/trunk/Examples/test-suite/ruby/member_pointer_runme.rb
new file mode 100644
index 0000000..eca6f0d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/member_pointer_runme.rb
@@ -0,0 +1,54 @@
+#!/usr/bin/env ruby
+#
+# Example using pointers to member functions
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'member_pointer'
+
+include Member_pointer
+
+def check(what, expected, actual)
+  if not expected == actual
+    raise RuntimeError, "Failed: #{what} Expected: #{expected} Actual: #{actual}"
+  end
+end
+
+# Get the pointers
+
+area_pt = Member_pointer::areapt
+perim_pt = Member_pointer::perimeterpt
+
+# Create some objects
+
+s = Member_pointer::Square.new(10)
+
+# Do some calculations
+
+check "Square area ", 100.0, Member_pointer::do_op(s, area_pt) 
+check "Square perim", 40.0, Member_pointer::do_op(s, perim_pt)
+
+memberPtr = Member_pointer::areavar
+memberPtr = Member_pointer::perimetervar
+
+# Try the variables
+check "Square area ", 100.0, Member_pointer::do_op(s, Member_pointer::areavar)
+check "Square perim", 40.0, Member_pointer::do_op(s, Member_pointer::perimetervar)
+
+# Modify one of the variables
+Member_pointer::areavar = perim_pt
+
+check "Square perimeter", 40.0, Member_pointer::do_op(s, Member_pointer::areavar)
+
+# Try the constants
+
+memberPtr = Member_pointer::AREAPT
+memberPtr = Member_pointer::PERIMPT
+memberPtr = Member_pointer::NULLPT
+
+check "Square area ", 100.0, Member_pointer::do_op(s, Member_pointer::AREAPT)
+check "Square perim", 40.0, Member_pointer::do_op(s, Member_pointer::PERIMPT)
+
diff --git a/trunk/Examples/test-suite/ruby/minherit_runme.rb b/trunk/Examples/test-suite/ruby/minherit_runme.rb
new file mode 100644
index 0000000..ba41ab6
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/minherit_runme.rb
@@ -0,0 +1,89 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'minherit'
+
+a = Minherit::Foo.new
+b = Minherit::Bar.new
+c = Minherit::FooBar.new
+d = Minherit::Spam.new
+
+if a.xget() != 1
+  raise RuntimeError, "Bad attribute value"
+end
+
+if b.yget() != 2
+  raise RuntimeError, "Bad attribute value"
+end    
+
+if c.xget() != 1 or c.yget() != 2 or c.zget() != 3
+  raise RuntimeError, "Bad attribute value"
+end
+
+if d.xget() != 1 or d.yget() != 2 or d.zget() != 3 or d.wget() != 4
+  raise RuntimeError, "Bad attribute value"
+end
+
+if Minherit.xget(a) != 1
+  raise RuntimeError, "Bad attribute value #{Minherit.xget(a)}"
+end     
+
+if Minherit.yget(b) != 2
+  raise RuntimeError, "Bad attribute value #{Minherit.yget(b)}"
+end
+
+if Minherit.xget(c) != 1 or Minherit.yget(c) != 2 or Minherit.zget(c) != 3
+  raise RuntimeError, "Bad attribute value #{Minherit.xget(c)} #{Minherit.yget(c)} #{Minherit.zget(c)}"
+end    
+
+if Minherit.xget(d) != 1 or Minherit.yget(d) != 2 or Minherit.zget(d) != 3 or Minherit.wget(d) != 4
+  raise RuntimeError, "Bad attribute value #{Minherit.xget(d)} #{Minherit.yget(d)} #{Minherit.zget(d)} #{Minherit.wget(d)}"
+end
+
+# Cleanse all of the pointers and see what happens
+
+aa = Minherit.toFooPtr(a)
+bb = Minherit.toBarPtr(b)
+cc = Minherit.toFooBarPtr(c)
+dd = Minherit.toSpamPtr(d)
+
+if aa.xget() != 1
+  raise RuntimeError, "Bad attribute value"
+end
+
+if bb.yget() != 2
+  raise RuntimeError, "Bad attribute value"
+end
+
+if cc.xget() != 1 or cc.yget() != 2 or cc.zget() != 3
+  raise RuntimeError, "Bad attribute value"
+end
+
+if dd.xget() != 1 or dd.yget() != 2 or dd.zget() != 3 or dd.wget() != 4
+  raise RuntimeError, "Bad attribute value"
+end
+
+if Minherit.xget(aa) != 1
+  raise RuntimeError, "Bad attribute value #{Minherit.xget(aa)}"
+end
+
+if Minherit.yget(bb) != 2
+  raise RuntimeError, "Bad attribute value #{Minherit.yget(bb)}"
+end
+
+if Minherit.xget(cc) != 1 or Minherit.yget(cc) != 2 or Minherit.zget(cc) != 3
+  raise RuntimeError, "Bad attribute value #{Minherit.xget(cc)} #{Minherit.yget(cc)} #{Minherit.zget(cc)}"
+end
+
+if Minherit.xget(dd) != 1 or Minherit.yget(dd) != 2 or Minherit.zget(dd) != 3 or Minherit.wget(dd) != 4
+  raise RuntimeError, "Bad attribute value #{Minherit.xget(dd)} #{Minherit.yget(dd)} #{Minherit.zget(dd)} #{Minherit.wget(dd)}"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/namespace_typemap_runme.rb b/trunk/Examples/test-suite/ruby/namespace_typemap_runme.rb
new file mode 100755
index 0000000..42a5e23
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/namespace_typemap_runme.rb
@@ -0,0 +1,44 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'namespace_typemap'
+
+include Namespace_typemap
+
+raise RuntimeError if stest1("hello") != "hello"
+
+raise RuntimeError if stest2("hello") != "hello"
+
+raise RuntimeError if stest3("hello") != "hello"
+
+raise RuntimeError if stest4("hello") != "hello"
+
+raise RuntimeError if stest5("hello") != "hello"
+
+raise RuntimeError if stest6("hello") != "hello"
+
+raise RuntimeError if stest7("hello") != "hello"
+
+raise RuntimeError if stest8("hello") != "hello"
+
+raise RuntimeError if stest9("hello") != "hello"
+
+raise RuntimeError if stest10("hello") != "hello"
+
+raise RuntimeError if stest11("hello") != "hello"
+
+raise RuntimeError if stest12("hello") != "hello"
+
+begin
+  ttest1(-14)
+  raise RuntimeError
+rescue RangeError
+end
diff --git a/trunk/Examples/test-suite/ruby/naming.i b/trunk/Examples/test-suite/ruby/naming.i
new file mode 100644
index 0000000..75500ae
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/naming.i
@@ -0,0 +1,107 @@
+%module naming
+
+%predicate predicateMethod();
+%bang bangMethod();
+
+/* This gets mapped to a constant */
+%constant int constant1 = 1;
+
+/* This gets mapped to a constant */
+#define constant2 2
+
+%immutable TestConstants::constant8;
+
+%inline %{
+
+/* ============  Test Constants Names ============== */
+
+/* This gets mapped to a constant */
+#define constant3 3
+
+/* These are all singleton methods */
+const int constant4[2] = {10, 20};
+const int constant5 = 5;
+static const int constant6 = 6;
+
+
+class TestConstants {
+public:
+  TestConstants() : constant7(7) {}
+  
+  /* This gets mapped to a method */
+  const int constant7;
+  
+  /* This gets mapped to a singleton method, but this is not legal C++ */
+  static const int constant8;
+  
+  /* This gets mapped to a method, but this it not legal C++ */
+  /*const int constant9 = 9;*/
+  
+  /* This gets mapped to a constant */
+  static const int constant10 = 10;
+};
+
+const int TestConstants::constant8 = 8;
+
+const TestConstants * constant11[5];
+
+
+/* ============  Test Enum ============== */
+typedef enum {Red, Green, Blue} Colors;
+
+
+/* ============  Test Method Names ============== */
+class my_class {
+public:
+	int methodOne()
+	{
+		return 1;
+	}
+	
+  int MethodTwo()
+	{
+		return 2;
+	}
+	
+  int Method_THREE()
+	{
+		return 3;
+	}
+
+  int Method44_4()
+	{
+		return 4;
+	}
+	
+  bool predicateMethod()
+	{
+		return true;
+	}
+	
+  bool bangMethod()
+	{
+		return true;
+	}
+  int begin() 
+  {
+    return 1;
+  }
+
+  int end() 
+  {
+    return 1;
+  }
+  
+};
+
+%}
+
+%inline 
+{
+  template <class _Type>
+  struct A 
+  {
+  };
+}
+
+%template(A_i) A<int>;
diff --git a/trunk/Examples/test-suite/ruby/naming_runme.rb b/trunk/Examples/test-suite/ruby/naming_runme.rb
new file mode 100644
index 0000000..dab3a50
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/naming_runme.rb
@@ -0,0 +1,115 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'naming'
+
+# Check class names
+if not Naming
+  raise RuntimeError, 'Invalid module name for Naming'
+end
+
+if not Naming::MyClass
+  raise RuntimeError, 'Invalid class name for MyClass'
+end
+
+
+# Check constant names / values
+if Naming::CONSTANT1 != 1
+  raise RuntimeError, "Incorrect value for CONSTANT1" 
+end
+
+if Naming::CONSTANT2 != 2
+  raise RuntimeError, "Incorrect value for CONSTANT2" 
+end
+
+# Check constant names / values
+if Naming::CONSTANT3 != 3
+  raise RuntimeError, "Incorrect value for CONSTANT3" 
+end
+
+if not Naming::methods.include?("constant4")
+  raise RuntimeError, "Incorrect mapping for constant4" 
+end
+
+if not Naming::methods.include?("constant5")
+  raise RuntimeError, "Incorrect mapping for constant5" 
+end
+
+if not Naming::methods.include?("constant6")
+  raise RuntimeError, "Incorrect mapping for constant6" 
+end
+
+if not Naming::TestConstants.instance_methods.include?("constant7")
+  raise RuntimeError, "Incorrect mapping for constant7" 
+end
+
+if not Naming::TestConstants.methods.include?("constant8")
+  raise RuntimeError, "Incorrect mapping for constant8" 
+end
+
+# There is no constant9 because it is illegal C++
+#if not Naming::TestConstants.instance_methods.include?("constant9")
+#  raise RuntimeError, "Incorrect mapping for constant9" 
+#end
+
+if Naming::TestConstants::CONSTANT10 != 10
+  raise RuntimeError, "Incorrect value for CONSTANT10" 
+end
+
+if not Naming::methods.include?("constant11")
+  raise RuntimeError, "Incorrect mapping for constant11" 
+end
+
+
+# Check enums
+if Naming::constants.include?("Color")
+  raise RuntimeError, "Color enum should not be exposed to Ruby" 
+end
+
+if Naming::Red != 0
+  raise RuntimeError, "Incorrect value for enum RED" 
+end
+
+if Naming::Green != 1
+  raise RuntimeError, "Incorrect value for enum GREEN" 
+end
+
+if Naming::Blue != 2
+  raise RuntimeError, "Incorrect value for enum BLUE" 
+end
+
+
+# Check method names
+my_class = Naming::MyClass.new()
+
+if my_class.method_one != 1 
+  raise RuntimeError, "Incorrect value for method_one" 
+end
+  
+if my_class.method_two != 2
+  raise RuntimeError, "Incorrect value for method_two" 
+end
+
+if my_class.method_three != 3
+  raise RuntimeError, "Incorrect value for method_three" 
+end
+
+if my_class.method_44_4 != 4
+  raise RuntimeError, "Incorrect value for method_44_4" 
+end
+
+if my_class.predicate_method? != true
+  raise RuntimeError, "Incorrect value for predicate_method?" 
+end
+
+if my_class.bang_method! != true
+  raise RuntimeError, "Incorrect value for bang_method!" 
+end
diff --git a/trunk/Examples/test-suite/ruby/newobject1_runme.rb b/trunk/Examples/test-suite/ruby/newobject1_runme.rb
new file mode 100644
index 0000000..f5dc12f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/newobject1_runme.rb
@@ -0,0 +1,33 @@
+#!/usr/bin/env ruby
+#
+# Simple test of %newobject
+#  * The purpose of this test is to confirm that a language module
+#  * correctly handles the case when C++ class member functions (of both
+#  * the static and non-static persuasion) have been tagged with the
+#  * %newobject directive.
+#
+# Ruby's GC is somewhat broken in that it will mark some more stack space
+# leading to the collection of local objects to be delayed.
+# Thus, upon invokation, it sometimes you can wait up to several
+# instructions to kick in.
+# See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/7449
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'swig_gc'
+require 'newobject1'
+
+include Newobject1
+
+GC.track_class = Foo
+GC.start
+100.times { foo1 = Foo.makeFoo; foo2 = foo1.makeMore }
+GC.stats if $VERBOSE
+swig_assert( 'Foo.fooCount == 200', binding, "but is #{Foo.fooCount}" )
+GC.start
+swig_assert( 'Foo.fooCount <= 2', binding, "but is #{Foo.fooCount}" )
+
diff --git a/trunk/Examples/test-suite/ruby/newobject2_runme.rb b/trunk/Examples/test-suite/ruby/newobject2_runme.rb
new file mode 100644
index 0000000..99bc243
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/newobject2_runme.rb
@@ -0,0 +1,27 @@
+#!/usr/bin/env ruby
+#
+# Ruby's GC is somewhat broken in that it will mark some more stack space
+# leading to the collection of local objects to be delayed.
+# Thus, upon invokation, it sometimes you can wait up to several
+# instructions to kick in.
+# See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/7449
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'swig_gc'
+require 'newobject2'
+
+include Newobject2
+
+GC.track_class = Foo
+GC.stats if $VERBOSE
+100.times { foo1 = makeFoo }
+GC.stats if $VERBOSE
+swig_assert( 'fooCount == 100', nil, "but is #{fooCount}" )
+GC.start
+swig_assert( 'fooCount <= 1', nil, "but is #{fooCount}" )
+
diff --git a/trunk/Examples/test-suite/ruby/overload_copy_runme.rb b/trunk/Examples/test-suite/ruby/overload_copy_runme.rb
new file mode 100755
index 0000000..eb184b8
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/overload_copy_runme.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'overload_copy'
+
+include Overload_copy
+
+f = Foo.new
+g = Foo.new(f)
diff --git a/trunk/Examples/test-suite/ruby/overload_extend_runme.rb b/trunk/Examples/test-suite/ruby/overload_extend_runme.rb
new file mode 100755
index 0000000..255793f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/overload_extend_runme.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'overload_extend'
+
+f = Overload_extend::Foo.new
+
+raise RuntimeError if f.test(3) != 1
+raise RuntimeError if f.test("hello") != 2
+raise RuntimeError if f.test(3.5,2.5) != 6
+
diff --git a/trunk/Examples/test-suite/ruby/overload_extendc_runme.rb b/trunk/Examples/test-suite/ruby/overload_extendc_runme.rb
new file mode 100755
index 0000000..a2682bf
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/overload_extendc_runme.rb
@@ -0,0 +1,18 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'overload_extend'
+
+f = Overload_extend::Foo.new
+
+raise RuntimeError if f.test(3) != 1
+raise RuntimeError if f.test("hello") != 2
+raise RuntimeError if f.test(3.5,2.5) != 6
diff --git a/trunk/Examples/test-suite/ruby/overload_simple_runme.rb b/trunk/Examples/test-suite/ruby/overload_simple_runme.rb
new file mode 100755
index 0000000..88cee44
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/overload_simple_runme.rb
@@ -0,0 +1,130 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'overload_simple'
+
+include Overload_simple
+
+if foo(3) != "foo:int"
+  raise RuntimeError, "foo(int)"
+end
+
+if foo(3.0) != "foo:double"
+  raise RuntimeError, "foo(double)"
+end
+
+if foo("hello") != "foo:char *"
+  raise RuntimeError, "foo(char *)"
+end
+
+f = Foo.new
+b = Bar.new
+
+if foo(f) != "foo:Foo *"
+  raise RuntimeError, "foo(Foo *)"
+end
+
+if foo(b) != "foo:Bar *"
+  raise RuntimeError, "foo(Bar *)"
+end
+
+v = malloc_void(32)
+
+if foo(v) != "foo:void *"
+  raise RuntimeError, "foo(void *)"
+end
+
+s = Spam.new
+
+if s.foo(3) != "foo:int"
+  raise RuntimeError, "Spam::foo(int)"
+end
+
+if s.foo(3.0) != "foo:double"
+  raise RuntimeError, "Spam::foo(double)"
+end
+
+if s.foo("hello") != "foo:char *"
+  raise RuntimeError, "Spam::foo(char *)"
+end
+
+if s.foo(f) != "foo:Foo *"
+  raise RuntimeError, "Spam::foo(Foo *)"
+end
+
+if s.foo(b) != "foo:Bar *"
+  raise RuntimeError, "Spam::foo(Bar *)"
+end
+
+if s.foo(v) != "foo:void *"
+  raise RuntimeError, "Spam::foo(void *)"
+end
+
+if Spam.bar(3) != "bar:int"
+  raise RuntimeError, "Spam::bar(int)"
+end
+
+if Spam.bar(3.0) != "bar:double"
+  raise RuntimeError, "Spam::bar(double)"
+end
+
+if Spam.bar("hello") != "bar:char *"
+  raise RuntimeError, "Spam::bar(char *)"
+end
+
+if Spam.bar(f) != "bar:Foo *"
+  raise RuntimeError, "Spam::bar(Foo *)"
+end
+
+if Spam.bar(b) != "bar:Bar *"
+  raise RuntimeError, "Spam::bar(Bar *)"
+end
+
+if Spam.bar(v) != "bar:void *"
+  raise RuntimeError, "Spam::bar(void *)"
+end
+
+# Test constructors
+
+s = Spam.new
+if s.type != "none"
+  raise RuntimeError, "Spam()"
+end
+
+s = Spam.new(3)
+if s.type != "int"
+  raise RuntimeError, "Spam(int)"
+end
+    
+s = Spam.new(3.4)
+if s.type != "double"
+  raise RuntimeError, "Spam(double)"
+end
+
+s = Spam.new("hello")
+if s.type != "char *"
+  raise RuntimeError, "Spam(char *)"
+end
+
+s = Spam.new(f)
+if s.type != "Foo *"
+  raise RuntimeError, "Spam(Foo *)"
+end
+
+s = Spam.new(b)
+if s.type != "Bar *"
+  raise RuntimeError, "Spam(Bar *)"
+end
+
+s = Spam.new(v)
+if s.type != "void *"
+  raise RuntimeError, "Spam(void *)"
+end
diff --git a/trunk/Examples/test-suite/ruby/overload_subtype_runme.rb b/trunk/Examples/test-suite/ruby/overload_subtype_runme.rb
new file mode 100644
index 0000000..991a2e4
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/overload_subtype_runme.rb
@@ -0,0 +1,26 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'overload_subtype'
+
+include Overload_subtype
+
+f = Foo.new
+b = Bar.new
+
+if spam(f) != 1
+  raise RuntimeError, "foo"
+end
+
+if spam(b) != 2
+  raise RuntimeError, "bar"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/overload_template_runme.rb b/trunk/Examples/test-suite/ruby/overload_template_runme.rb
new file mode 100755
index 0000000..bcbddf5
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/overload_template_runme.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'overload_template'
+
+f = Overload_template.foo()
+
+a = Overload_template.max(3,4)
+b = Overload_template.max(3.4,5.2)
diff --git a/trunk/Examples/test-suite/ruby/primitive_ref_runme.rb b/trunk/Examples/test-suite/ruby/primitive_ref_runme.rb
new file mode 100755
index 0000000..5e97c7a
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/primitive_ref_runme.rb
@@ -0,0 +1,38 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'primitive_ref'
+
+include Primitive_ref
+
+raise RuntimeError if ref_int(3) != 3
+
+raise RuntimeError if ref_uint(3) != 3
+
+raise RuntimeError if ref_short(3) != 3
+
+raise RuntimeError if ref_ushort(3) != 3
+
+raise RuntimeError if ref_long(3) != 3
+
+raise RuntimeError if ref_ulong(3) != 3
+
+raise RuntimeError if ref_schar(3) != 3
+
+raise RuntimeError if ref_uchar(3) != 3
+
+raise RuntimeError if ref_float(3.5) != 3.5
+
+raise RuntimeError if ref_double(3.5) != 3.5
+
+raise RuntimeError if ref_bool(true) != true
+
+raise RuntimeError if ref_char('x') != 'x'
diff --git a/trunk/Examples/test-suite/ruby/primitive_types_runme.rb b/trunk/Examples/test-suite/ruby/primitive_types_runme.rb
new file mode 100644
index 0000000..9fde5b3
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/primitive_types_runme.rb
@@ -0,0 +1,95 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'primitive_types'
+
+include Primitive_types
+
+
+raise RuntimeError if val_uchar(255) != 255
+
+fail = 0
+begin
+  val_uchar(-1)
+rescue RangeError
+  fail = 1
+end
+
+fail = 0
+begin
+  val_uchar(256)
+rescue RangeError
+  fail = 1
+end
+
+raise RuntimeError if fail != 1
+
+fail = 0
+begin
+  val_uchar(256.0)
+rescue TypeError
+  fail = 1
+end
+
+raise RuntimeError if fail != 1
+
+fail = 0
+begin
+  val_uchar("caca")
+rescue TypeError
+  fail = 1
+end
+
+raise RuntimeError if fail != 1
+
+
+raise RuntimeError if val_double_2(1.0) != 4.0
+raise RuntimeError if val_double_2(1) != 4
+raise RuntimeError if val_double_2(1,1) != 2
+
+fail = 0
+begin
+  val_double_2("1.0",1.0)
+rescue 
+  fail = 1
+end
+raise RuntimeError if fail != 1
+
+
+fail = 0
+begin
+  val_double_2(1.0,"1.0")
+rescue 
+  fail = 1
+end
+raise RuntimeError if fail != 1
+
+
+raise RuntimeError if val_float_2(1.0) != 4.0
+raise RuntimeError if val_float_2(1) != 4
+raise RuntimeError if val_float_2(1,1) != 2
+
+fail = 0
+begin
+  val_float_2("1.0",1.0)
+rescue 
+  fail = 1
+end
+raise RuntimeError if fail != 1
+
+
+fail = 0
+begin
+  val_float_2(1.0,"1.0")
+rescue 
+  fail = 1
+end
+raise RuntimeError if fail != 1
diff --git a/trunk/Examples/test-suite/ruby/profiletest_runme.rb b/trunk/Examples/test-suite/ruby/profiletest_runme.rb
new file mode 100644
index 0000000..0f6ddc7
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/profiletest_runme.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'profiletest'
+
+a = Profiletest::A.new()
+b = Profiletest::B.new()
+
+for i in 0...1000000
+  a = b.fn(a)
+end
+
diff --git a/trunk/Examples/test-suite/ruby/refcount_runme.rb b/trunk/Examples/test-suite/ruby/refcount_runme.rb
new file mode 100644
index 0000000..7ef3c84
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/refcount_runme.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'refcount'
+
+
+a = Refcount::A3.new;
+b1 = Refcount::B.new a;
+b2 = Refcount::B.new a;
+
+if a.ref_count() != 3 
+  print "This program will crash... now\n"
+end
diff --git a/trunk/Examples/test-suite/ruby/reference_global_vars_runme.rb b/trunk/Examples/test-suite/ruby/reference_global_vars_runme.rb
new file mode 100644
index 0000000..49fbf4d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/reference_global_vars_runme.rb
@@ -0,0 +1,104 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'reference_global_vars'
+
+# primitive reference variables
+Reference_global_vars.var_bool = Reference_global_vars.createref_bool(true)
+if (Reference_global_vars.value_bool(Reference_global_vars.var_bool) != true)
+    print "Runtime error test 1\n"
+    exit 1
+end
+
+Reference_global_vars.var_bool = Reference_global_vars.createref_bool(false)
+if (Reference_global_vars.value_bool(Reference_global_vars.var_bool) != false)
+    print "Runtime error test 2 \n"
+    exit 1
+end
+
+Reference_global_vars.var_char = Reference_global_vars.createref_char('w')
+if (Reference_global_vars.value_char(Reference_global_vars.var_char) != 'w')
+    print "Runtime error test 3 \n"
+    exit 1
+end
+
+Reference_global_vars.var_unsigned_char = Reference_global_vars.createref_unsigned_char(10)
+if (Reference_global_vars.value_unsigned_char(Reference_global_vars.var_unsigned_char) != 10)
+    print "Runtime error test 4 \n"
+    exit 1
+end
+
+Reference_global_vars.var_signed_char = Reference_global_vars.createref_signed_char(10)
+if (Reference_global_vars.value_signed_char(Reference_global_vars.var_signed_char) != 10)
+    print "Runtime error test 5 \n"
+    exit 1
+end
+
+Reference_global_vars.var_short = Reference_global_vars.createref_short(10)
+if (Reference_global_vars.value_short(Reference_global_vars.var_short) != 10)
+    print "Runtime error test 6 \n"
+    exit 1
+end
+
+Reference_global_vars.var_unsigned_short = Reference_global_vars.createref_unsigned_short(10)
+if (Reference_global_vars.value_unsigned_short(Reference_global_vars.var_unsigned_short) != 10)
+    print "Runtime error test 7 \n"
+    exit 1
+end
+
+Reference_global_vars.var_int = Reference_global_vars.createref_int(10)
+if (Reference_global_vars.value_int(Reference_global_vars.var_int) != 10)
+    print "Runtime error test 8 \n"
+    exit 1
+end
+
+Reference_global_vars.var_unsigned_int = Reference_global_vars.createref_unsigned_int(10)
+if (Reference_global_vars.value_unsigned_int(Reference_global_vars.var_unsigned_int) != 10)
+    print "Runtime error test 9 \n"
+    exit 1
+end
+
+Reference_global_vars.var_long = Reference_global_vars.createref_long(10)
+if (Reference_global_vars.value_long(Reference_global_vars.var_long) != 10)
+    print "Runtime error test 10 \n"
+    exit 1
+end
+
+Reference_global_vars.var_unsigned_long = Reference_global_vars.createref_unsigned_long(10)
+if (Reference_global_vars.value_unsigned_long(Reference_global_vars.var_unsigned_long) != 10)
+    print "Runtime error test 11 \n"
+    exit 1
+end
+
+Reference_global_vars.var_long_long = Reference_global_vars.createref_long_long(10)
+if (Reference_global_vars.value_long_long(Reference_global_vars.var_long_long) != 10)
+    print "Runtime error test 12 \n"
+    exit 1
+end
+
+Reference_global_vars.var_unsigned_long_long = Reference_global_vars.createref_unsigned_long_long(10)
+if (Reference_global_vars.value_unsigned_long_long(Reference_global_vars.var_unsigned_long_long) != 10)
+    print "Runtime error test 13 \n"
+    exit 1
+end
+
+Reference_global_vars.var_float = Reference_global_vars.createref_float(10.5)
+if (Reference_global_vars.value_float(Reference_global_vars.var_float) != 10.5)
+    print "Runtime error test 14 \n"
+    exit 1
+end
+
+Reference_global_vars.var_double = Reference_global_vars.createref_double(10.5)
+if (Reference_global_vars.value_double(Reference_global_vars.var_double) != 10.5)
+    print "Runtime error test 15 \n"
+    exit 1
+end
+
diff --git a/trunk/Examples/test-suite/ruby/rename_scope_runme.rb b/trunk/Examples/test-suite/ruby/rename_scope_runme.rb
new file mode 100644
index 0000000..76a1487
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/rename_scope_runme.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'rename_scope'
+
+include Rename_scope
+
+a = Natural_UP.new
+b = Natural_BP.new
+
+raise RuntimeError if a.rtest() != 1
+
+raise RuntimeError if b.rtest() != 1
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_const_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_const_runme.rb
new file mode 100644
index 0000000..b6565ad
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_const_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_const'
+
+include Smart_pointer_const
+
+f = Foo.new
+b = Bar.new(f)
+
+b.x = 3
+raise RuntimeError if b.getx() != 3
+
+fp = b.__deref__()
+fp.x = 4
+raise RuntimeError if fp.getx() != 4
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_multi_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_multi_runme.rb
new file mode 100644
index 0000000..a899ae7
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_multi_runme.rb
@@ -0,0 +1,26 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_multi'
+
+include Smart_pointer_multi
+
+f = Foo.new
+b = Bar.new(f)
+s = Spam.new(b)
+g = Grok.new(b)
+
+s.x = 3
+raise RuntimeError if s.getx() != 3
+
+g.x = 4
+raise RuntimeError if g.getx() != 4
+
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_multi_typedef_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_multi_typedef_runme.rb
new file mode 100644
index 0000000..d07da0d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_multi_typedef_runme.rb
@@ -0,0 +1,25 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_multi_typedef'
+
+include Smart_pointer_multi_typedef
+
+f = Foo.new
+b = Bar.new(f)
+s = Spam.new(b)
+g = Grok.new(b)
+
+s.x = 3
+raise RuntimeError if s.getx() != 3
+
+g.x = 4
+raise RuntimeError if g.getx() != 4
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_not_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_not_runme.rb
new file mode 100644
index 0000000..4324908
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_not_runme.rb
@@ -0,0 +1,55 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_not'
+
+include Smart_pointer_not
+
+f = Foo.new
+b = Bar.new(f)
+s = Spam.new(f)
+g = Grok.new(f)
+
+begin
+  x = b.x
+  puts "Error! b.x"
+rescue NameError
+end
+
+begin
+  x = s.x
+  puts "Error! s.x"    
+rescue NameError
+end
+
+begin
+  x = g.x
+  puts "Error! g.x"
+rescue NameError
+end
+
+begin
+  x = b.getx()
+  puts "Error! b.getx()"    
+rescue NameError
+end
+
+begin
+  x = s.getx()
+  puts "Error! s.getx()"        
+rescue NameError
+end
+
+begin
+  x = g.getx()
+  puts "Error! g.getx()"
+rescue NameError
+end
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_overload_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_overload_runme.rb
new file mode 100644
index 0000000..24c343a
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_overload_runme.rb
@@ -0,0 +1,27 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_overload'
+
+include Smart_pointer_overload
+
+f = Foo.new
+b = Bar.new(f)
+
+
+raise RuntimeError if f.test(3) != 1
+raise RuntimeError if f.test(3.5) != 2
+raise RuntimeError if f.test("hello") != 3
+
+raise RuntimeError if b.test(3) != 1
+raise RuntimeError if b.test(3.5) != 2
+raise RuntimeError if b.test("hello") != 3
+
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_rename_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_rename_runme.rb
new file mode 100644
index 0000000..167e554
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_rename_runme.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_rename'
+
+include Smart_pointer_rename
+
+f = Foo.new
+b = Bar.new(f)
+
+raise RuntimeError if b.test() != 3
+
+raise RuntimeError if b.ftest1(1) != 1
+
+raise RuntimeError if b.ftest2(2,3) != 2
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_simple_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_simple_runme.rb
new file mode 100644
index 0000000..bdfbf9c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_simple_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_simple'
+
+include Smart_pointer_simple
+
+f = Foo.new
+b = Bar.new(f)
+
+b.x = 3
+raise RuntimeError if b.getx() != 3
+
+fp = b.__deref__()
+fp.x = 4
+raise RuntimeError if fp.getx() != 4
diff --git a/trunk/Examples/test-suite/ruby/smart_pointer_typedef_runme.rb b/trunk/Examples/test-suite/ruby/smart_pointer_typedef_runme.rb
new file mode 100644
index 0000000..1684712
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/smart_pointer_typedef_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'smart_pointer_typedef'
+
+include Smart_pointer_typedef
+
+f = Foo.new
+b = Bar.new(f)
+
+b.x = 3
+raise RuntimeError if b.getx() != 3
+
+fp = b.__deref__()
+fp.x = 4
+raise RuntimeError if fp.getx() != 4
diff --git a/trunk/Examples/test-suite/ruby/sneaky1_runme.rb b/trunk/Examples/test-suite/ruby/sneaky1_runme.rb
new file mode 100755
index 0000000..c30fdaf
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/sneaky1_runme.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'sneaky1'
+
+x = Sneaky1.add(3, 4)
+y = Sneaky1.subtract(3, 4)
+z = Sneaky1.mul(3, 4)
+w = Sneaky1.divide(3, 4)
diff --git a/trunk/Examples/test-suite/ruby/static_const_member_2_runme.rb b/trunk/Examples/test-suite/ruby/static_const_member_2_runme.rb
new file mode 100644
index 0000000..0ba970e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/static_const_member_2_runme.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'static_const_member_2'
+
+include Static_const_member_2
+
+c = Test_int.new
+a = Test_int::Forward_field	# should be available as a class constant
+a = Test_int::Current_profile	# should be available as a class constant
+a = Test_int::RightIndex	# should be available as a class constant
+a = Test_int::Backward_field	# should be available as a class constant
+a = Test_int::LeftIndex		# should be available as a class constant
+a = Test_int.cavity_flags
+
diff --git a/trunk/Examples/test-suite/ruby/std_containers_runme.rb b/trunk/Examples/test-suite/ruby/std_containers_runme.rb
new file mode 100755
index 0000000..73d4432
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/std_containers_runme.rb
@@ -0,0 +1,119 @@
+#!/usr/bin/env ruby
+#
+# Standard containers test suite. Tests:
+# std::complex, std::vector, std::set and std::map,
+# and IN/OUT functions for them.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'std_containers'
+include Std_containers
+
+swig_assert_each_line(<<'EOF', binding)
+
+cube = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
+
+icube = cident(cube)
+icube.each_index { |i| swig_assert_equal("cube[#{i}]","icube[#{i}]", binding, 'cident') }
+
+
+p = [1,2]
+p == pident(p)
+
+v = [1,2,3,4,5,6]
+iv = vident(v)
+iv.each_index { |i| swig_assert_equal("iv[#{i}]","v[#{i}]", binding, 'vident') }
+
+
+
+iv = videntu(v)
+iv.each_index { |i| swig_assert_equal("iv[#{i}]","v[#{i}]", binding, 'videntu') }
+
+
+vu = Vector_ui.new(v)
+vu[2] == videntu(vu)[2]
+
+v[0,3][1] == vu[0,3][1]
+
+m = [[1,2,3],[2,3],[3,4]]
+im = midenti(m)
+
+0.upto(m.size-1){ |i| 0.upto(m[i].size-1) { |j| swig_assert_equal("m[#{i}][#{j}]","im[#{i}][#{j}]", binding, 'getslice') } }
+
+
+m = [[1,0,1],[1,1],[1,1]]
+im = midentb(m)
+
+0.upto(m.size-1){ |i| 0.upto(m[i].size-1) { |j| swig_assert_equal("(m[#{i}][#{j}]==1)","im[#{i}][#{j}]", binding, 'getslice') } }
+
+mi = Imatrix.new(m)
+mc = Cmatrix.new(m)
+mi[0][0] == mc[0][0] # or bad matrix
+
+map ={}
+map['hello'] = 1
+map['hi'] = 2
+map['3'] = 2
+
+imap = Std_containers.mapident(map)
+map.each_key { |k| swig_assert_equal("map['#{k}']", "imap['#{k}']", binding) }
+
+mapc ={}
+c1 = C.new
+c2 = C.new
+mapc[1] = c1
+mapc[2] = c2
+
+mapidentc(mapc)
+
+vi = Vector_i.new([2,2,3,4])
+v1 = vi.dup
+v1.class == vi.class
+v1 != vi
+v1.object_id != vi.object_id
+
+v = [1,2]
+v1 = v_inout(vi)
+vi[1] == v1[1]
+# vi.class == v1.class # only if SWIG_RUBY_EXTRA_NATIVE_CONTAINERS was set
+
+v1,v2 = [[1,2],[3,4]]
+v1,v2 = v_inout2(v1,v2)
+v2 == [1,2]
+v1 == [3,4]
+
+a1 = A.new(1)
+a2 = A.new(2)
+
+p1 = [1,a1]
+p2 = [2,a2]
+v  = [p1,p2]
+v2 = pia_vident(v)
+
+
+
+# v2[0][1].a
+# v2[1][1].a
+
+# v3 = Std_containers.vector_piA(v2)
+
+# v3[0][1].a
+# v3[1][1].a
+
+
+
+
+s = Set_i.new
+s.push(1)
+s.push(2)
+s.push(3)
+j = 1
+s.each { |i| swig_assert_equal("#{i}","#{j}", binding, "for s[#{i}]"); j += 1 }
+
+
+EOF
+
diff --git a/trunk/Examples/test-suite/ruby/stl_new.i b/trunk/Examples/test-suite/ruby/stl_new.i
new file mode 100644
index 0000000..690a167
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/stl_new.i
@@ -0,0 +1,29 @@
+%module stl_new
+
+%include <std_vector.i>
+%include <std_deque.i>
+%include <std_list.i>
+%include <std_set.i>
+%include <std_map.i>
+
+%template(Vector  ) std::vector  <swig::LANGUAGE_OBJ>;
+%template(Deque   ) std::deque   <swig::LANGUAGE_OBJ>;
+%template(List    ) std::list    <swig::LANGUAGE_OBJ>;
+
+%template(Set     ) std::set     <swig::LANGUAGE_OBJ,
+				  swig::BinaryPredicate<> >;
+%template(Map     ) std::map     <swig::LANGUAGE_OBJ,swig::LANGUAGE_OBJ,
+                                   swig::BinaryPredicate<> >;
+
+
+// %inline %{
+//     namespace swig {
+//         void nth_element(swig::Iterator_T< _Iter>& first,
+//                          swig::Iterator_T< _Iter>& nth,
+//                          swig::Iterator_T< _Iter>& last,
+//                          const swig::BinaryPredicate<>& comp = swig::BinaryPredicate<>())
+//         {
+// 	  std::nth_element( first, nth, last, comp);
+//         }
+//     }
+// %}
diff --git a/trunk/Examples/test-suite/ruby/stl_new_runme.rb b/trunk/Examples/test-suite/ruby/stl_new_runme.rb
new file mode 100755
index 0000000..80d4cea
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/stl_new_runme.rb
@@ -0,0 +1,117 @@
+#!/usr/bin/env ruby
+#
+# This is a test of STL containers, iterators and using proc
+# objects to change the sorting function used in them.  Same as a
+# std::binary_predicate in C++.
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+require 'stl_new'
+
+
+def _sequence(container)
+  swig_assert_each_line(<<'EOF', binding)
+cont = container.new([9,1,8,2,7,3,6,4,5])
+cont.to_a == [9,1,8,2,7,3,6,4,5]
+cont.size == 9
+i = cont.begin
+i.class == Stl_new::Iterator
+cont.end - cont.begin == cont.size
+cont.begin.value == 9
+(cont.end-1).value == 5
+cont[0],cont[1] = cont[1],cont[0]
+cont.to_a == [1,9,8,2,7,3,6,4,5]
+i0 = cont.begin
+i1 = i0+1
+tmp = i0.value   # tmp = 1
+tmp == 1
+i0.value = i1.value # elem[0] = 9
+i1.value = tmp      # elem[1] = 1
+cont.to_a == [9,1,8,2,7,3,6,4,5]
+i0 += 8
+prev = i0.value
+i0 -= 8
+cur = i0.value
+i0.value = prev
+prev = cur
+i0 += 8
+cur = i0.value
+i0.value = prev
+cont.to_a == [5,1,8,2,7,3,6,4,9]
+i0 == cont.end-1
+i0 != cont.end
+EOF
+end
+
+def _random_iterator(container)
+  swig_assert_each_line(<<EOF, binding)
+  cont = #{container}.new([9,1,8,2,7,3,6,4,5])
+  Stl_new.nth_element(cont.begin,cont.begin+cont.size/2,cont.end)
+  cont.to_a == [3, 1, 2, 4, 5, 6, 7, 8, 9]
+  Stl_new.nth_element(cont.begin,cont.begin+1,cont.end, proc { |a,b| b<a } )
+  cont.to_a == [9, 8, 7, 6, 5, 4, 2, 1, 3]
+EOF
+end
+
+def _set(container)
+  swig_assert_each_line(<<EOF, binding)
+    cont = #{container}.new
+    [9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
+    i0 = cont.begin()
+    cont.to_a == [1,2,3,4,5,6,7,8,9]
+    cont = #{container}.new( proc { |a,b| b < a } )
+    [9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
+    cont.to_a == [9, 8, 7, 6, 5, 4, 3, 2, 1]
+    cont = #{container}.new( proc { |a,b| b > a } )
+    [9,1,8,2,7,3,6,4,5].each { |x| cont.insert(x) }
+    cont.to_a == [1, 2, 3, 4, 5, 6, 7, 8, 9]
+    cont = #{container}.new(proc { |a,b| b < a } )
+    cont.insert(1)
+    cont.to_a == [1]
+    i0 = cont.begin()
+    cont.erase(i0) # don't use i0 anymore, it is invalid now
+    cont.to_a == []
+EOF
+end
+    
+def _map(container)
+  swig_assert_each_line(<<EOF, binding)
+    cont = #{container}.new
+    cont['z'] = 9
+    cont['y'] = 1
+    cont['x'] = 8
+    cont['w'] = 2
+    cont.to_a == [['w',2],['x',8],['y',1],['z',9]]
+
+    cont = #{container}.new(proc { |a,b| b < a } )
+    cont['z'] = 9
+    cont['y'] = 1
+    cont['x'] = 8
+    cont['w'] = 2
+    cont.to_a == [['z',9],['y',1],['x',8],['w',2]]
+
+    #cont.iterator.to_a == [['w',2],['x',8],['y',1],['z',9]]
+EOF
+end
+
+def test
+  for container in [Stl_new::Vector, Stl_new::Deque, Stl_new::List]
+    yield method(:_sequence), container
+  end
+  yield method(:_set), Stl_new::Set
+  yield method(:_map), Stl_new::Map
+#   for container in [Stl_new::Vector, Stl_new::Deque]
+#     yield method(:_random_iterator), container
+#   end
+end
+
+
+test do |proc, container|
+  proc.call(container)
+end
+
+
diff --git a/trunk/Examples/test-suite/ruby/struct_value_runme.rb b/trunk/Examples/test-suite/ruby/struct_value_runme.rb
new file mode 100644
index 0000000..afed418
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/struct_value_runme.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'struct_value'
+
+b = Struct_value::Bar.new
+
+b.a.x = 3
+raise RuntimeError if b.a.x != 3
+
+b.b.x = 3
+raise RuntimeError if b.b.x != 3
+
diff --git a/trunk/Examples/test-suite/ruby/swig_assert.rb b/trunk/Examples/test-suite/ruby/swig_assert.rb
new file mode 100755
index 0000000..200b083
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/swig_assert.rb
@@ -0,0 +1,141 @@
+#!/usr/bin/env ruby
+#
+# A simple function to create useful asserts
+#
+# 
+# 
+# 
+#
+
+
+#
+# Exception raised when some swig binding test fails
+#
+class SwigRubyError < RuntimeError
+end
+
+
+#
+# Asserts whether a and b are equal.
+#
+# scope - optional Binding where to run the code
+# msg   - optional additional message to print
+#
+def swig_assert_equal( a, b, scope = nil, msg = nil )
+  begin
+    check = "#{a} == #{b}"
+    if scope.kind_of? Binding
+      ok = eval(check.to_s, scope)
+    else
+      ok = eval(check.to_s)
+      if !msg
+        msg = scope
+        scope = nil
+      end
+    end
+  rescue => e
+    raise
+  end
+
+  unless ok
+    valA = eval(a, scope)
+    valB = eval(b, scope)
+    raise SwigRubyError.new("FAILED EQUALITY: #{check} was #{valA} not #{valB}")
+  end
+
+  if $VERBOSE
+    $stdout.puts "\tPASSED EQUALITY #{check} #{msg}"
+  end
+
+  return ok
+rescue => e
+  trace = e.backtrace[1..-1]
+  $stderr.puts "#{trace[0,1]}: #{e}"
+  if trace.size > 1
+    $stderr.puts "\tfrom #{trace[1..-1].join("\n\t     ")}"
+  end
+  exit(1)
+end
+
+
+#
+# Asserts whether an expression runs properly and is true
+#
+# scope - optional Binding where to run the code
+# msg   - optional additional message to print
+#
+def swig_assert( expr, scope = nil, msg = nil )
+  begin
+    if scope.kind_of? Binding
+      ok = eval(expr.to_s, scope)
+    else
+      ok = eval(expr.to_s)
+      msg = scope if !msg
+    end
+  rescue
+    raise
+  end
+
+  raise SwigRubyError.new("FAILED: #{expr.to_s} - #{msg}") unless ok
+
+  if $VERBOSE
+    $stdout.puts "\tPASSED #{expr} #{msg}"
+  end
+rescue => e
+  trace = e.backtrace[1..-1]
+  $stderr.puts "#{trace[0,1]}: #{e}"
+  if trace.size > 1
+    $stderr.puts "\tfrom #{trace[1..-1].join("\n\t     ")}"
+  end
+  exit(1)
+end
+
+#
+# Asserts whether an expression runs properly
+#
+# scope - optional Binding where to run the code
+# msg   - optional additional message to print
+#
+def swig_eval( expr, scope = nil, msg = nil )
+  begin
+    if scope.kind_of? Binding
+      eval(expr.to_s, scope)
+    else
+      eval(expr.to_s)
+      msg = scope if !msg
+    end
+  rescue => e
+    raise SwigRubyError.new("Wrong assert: #{expr.to_s} - #{e}")
+  end
+  if $VERBOSE
+    $stdout.puts "\tPASSED #{expr} #{msg}"
+  end
+rescue => e
+  trace = e.backtrace[1..-1]
+  $stderr.puts "#{trace[0,1]}: #{e}"
+  if trace.size > 1
+    $stderr.puts "\tfrom #{trace[1..-1].join("\n\t     ")}"
+  end
+  exit(1)
+end
+
+
+#
+# Given a set of lines as text, runs each of them, asserting them.
+# Lines that are of the form:
+#     a == b  are run with swig_assert_equal
+#             others are run with swig_eval.
+#
+# scope - optional Binding where to run the code
+# msg   - optional additional message to print
+#
+def swig_assert_each_line( lines, scope = nil, msg = nil )
+  lines.split("\n").each do |line|
+    next if line.empty? or line =~ /^\s*#.*/
+      if line =~ /^\s*([^\s]*)\s*==\s*(.*)\s*$/
+        swig_assert_equal($1, $2, scope, msg)
+      else
+        swig_eval(line, scope, msg)
+      end
+  end
+end
diff --git a/trunk/Examples/test-suite/ruby/swig_gc.rb b/trunk/Examples/test-suite/ruby/swig_gc.rb
new file mode 100755
index 0000000..30f6dfa
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/swig_gc.rb
@@ -0,0 +1,70 @@
+#!/usr/bin/env ruby
+#
+#
+# VERY nice function from Robert Klemme to check memory leaks
+# and check on what GC has collected since last call.
+#
+# Usage can be:
+#
+#     require 'swig_gc'
+#
+#     GC.stats
+#     # do some stuff..
+#     GC.start  # collect and report stats
+#     # do some more...
+#     GC.stats  # just report stats
+#
+# or:
+#
+#     require 'swig_gc'
+#
+#     GC.track_class = String  # track just String classes
+#     GC.stats
+#     # do some stuff..
+#     GC.start  # collect and report stats
+#     # do some more...
+#     GC.stats  # just report stats
+#
+# 
+# 
+# 
+#
+
+module GC
+
+  class << self
+      
+    attr          :last_stat
+    attr_accessor :track_class
+
+    alias :_start :start
+    
+    def start
+      _start
+      stats if $VERBOSE
+    end
+    
+    def stats
+      stats = Hash.new(0)
+      ObjectSpace.each_object {|o| stats[o.class] += 1}
+      
+      if track_class
+        v = stats[track_class]
+        printf "\t%-30s  %10d", track_class.to_s, v
+        if last_stat
+          printf " | delta %10d", (v - last_stat[track_class])
+        end
+        puts
+      else
+        stats.sort {|(k1,v1),(k2,v2)| v2 <=> v1}.each do |k,v|
+          printf "\t%-30s  %10d", k, v
+          printf " | delta %10d", (v - last_stat[k]) if last_stat
+          puts
+        end
+      end
+        
+      last_stat = stats
+    end
+  end
+  
+end
diff --git a/trunk/Examples/test-suite/ruby/template_construct_runme.rb b/trunk/Examples/test-suite/ruby/template_construct_runme.rb
new file mode 100644
index 0000000..4acebfe
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_construct_runme.rb
@@ -0,0 +1,13 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_construct'
+
diff --git a/trunk/Examples/test-suite/ruby/template_extend1_runme.rb b/trunk/Examples/test-suite/ruby/template_extend1_runme.rb
new file mode 100644
index 0000000..999b181
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_extend1_runme.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_extend1'
+
+a = Template_extend1::LBaz.new
+b = Template_extend1::DBaz.new
+
+raise RuntimeError unless a.foo() == "lBaz::foo"
+raise RuntimeError unless b.foo() == "dBaz::foo"
+
diff --git a/trunk/Examples/test-suite/ruby/template_extend2_runme.rb b/trunk/Examples/test-suite/ruby/template_extend2_runme.rb
new file mode 100644
index 0000000..89082b9
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_extend2_runme.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_extend2'
+
+a = Template_extend2::LBaz.new
+b = Template_extend2::DBaz.new
+
+raise RuntimeError unless a.foo() == "lBaz::foo"
+raise RuntimeError unless b.foo() == "dBaz::foo"
+
diff --git a/trunk/Examples/test-suite/ruby/template_inherit_runme.rb b/trunk/Examples/test-suite/ruby/template_inherit_runme.rb
new file mode 100755
index 0000000..6095088
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_inherit_runme.rb
@@ -0,0 +1,51 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_inherit'
+
+include Template_inherit
+
+a = FooInt.new
+b = FooDouble.new
+c = BarInt.new
+d = BarDouble.new
+e = FooUInt.new
+f = BarUInt.new
+
+raise ValueError if a.blah() != "Foo"
+
+raise ValueError if b.blah() != "Foo"
+
+raise ValueError if e.blah() != "Foo"
+
+raise ValueError if c.blah() != "Bar"
+
+raise ValueError if d.blah() != "Bar"
+
+raise ValueError if f.blah() != "Bar"
+
+raise ValueError if c.foomethod() != "foomethod"
+
+raise ValueError if d.foomethod() != "foomethod"
+
+raise ValueError if f.foomethod() != "foomethod"
+
+raise ValueError if invoke_blah_int(a) != "Foo"
+
+raise ValueError if invoke_blah_int(c) != "Bar"
+
+raise ValueError if invoke_blah_double(b) != "Foo"
+
+raise ValueError if invoke_blah_double(d) != "Bar"
+
+raise ValueError if invoke_blah_uint(e) != "Foo"
+
+raise ValueError if invoke_blah_uint(f) != "Bar"
diff --git a/trunk/Examples/test-suite/ruby/template_ns4_runme.rb b/trunk/Examples/test-suite/ruby/template_ns4_runme.rb
new file mode 100755
index 0000000..bf2c5f5
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_ns4_runme.rb
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_ns4'
+
+d = Template_ns4.make_Class_DD()
+raise RuntimeError if d.test() != "test"
diff --git a/trunk/Examples/test-suite/ruby/template_ns_runme.rb b/trunk/Examples/test-suite/ruby/template_ns_runme.rb
new file mode 100755
index 0000000..6446127
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_ns_runme.rb
@@ -0,0 +1,26 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_ns'
+
+include Template_ns
+
+p1 = Pairii.new(2, 3)
+p2 = Pairii.new(p1)
+
+raise RuntimeError if p2.first != 2
+raise RuntimeError if p2.second != 3
+
+p3 = Pairdd.new(3.5, 2.5)
+p4 = Pairdd.new(p3)
+
+raise RuntimeError if p4.first != 3.5
+raise RuntimeError if p4.second != 2.5
diff --git a/trunk/Examples/test-suite/ruby/template_rename_runme.rb b/trunk/Examples/test-suite/ruby/template_rename_runme.rb
new file mode 100755
index 0000000..18cfd4c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_rename_runme.rb
@@ -0,0 +1,23 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_rename'
+
+i = Template_rename::IFoo.new
+d = Template_rename::DFoo.new
+
+a = i.blah_test(4)
+b = i.spam_test(5)
+c = i.groki_test(6)
+
+x = d.blah_test(7)
+y = d.spam(8)
+z = d.grok_test(9)
diff --git a/trunk/Examples/test-suite/ruby/template_tbase_template_runme.rb b/trunk/Examples/test-suite/ruby/template_tbase_template_runme.rb
new file mode 100644
index 0000000..43f0555
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_tbase_template_runme.rb
@@ -0,0 +1,18 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_tbase_template'
+
+include Template_tbase_template
+
+a = make_Class_dd()
+raise RuntimeError unless a.test() == "test"
+
diff --git a/trunk/Examples/test-suite/ruby/template_type_namespace_runme.rb b/trunk/Examples/test-suite/ruby/template_type_namespace_runme.rb
new file mode 100644
index 0000000..6db2fc4
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_type_namespace_runme.rb
@@ -0,0 +1,18 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_type_namespace'
+
+include Template_type_namespace
+
+result = foo()
+raise RuntimeError unless result[0].is_a? String
+
diff --git a/trunk/Examples/test-suite/ruby/template_typedef_cplx2_runme.rb b/trunk/Examples/test-suite/ruby/template_typedef_cplx2_runme.rb
new file mode 100644
index 0000000..a6eb049
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_typedef_cplx2_runme.rb
@@ -0,0 +1,81 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_typedef_cplx2'
+
+include Template_typedef_cplx2
+
+#
+# double case
+#
+
+
+d = make_Identity_double()
+raise RuntimeError, "#{d} is not an instance" if d.is_a? SWIG::Pointer
+
+classname = d.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{d} is not an ArithUnaryFunction"
+end
+
+e = make_Multiplies_double_double_double_double(d, d)
+raise RuntimeError, "#{e} is not an instance" if e.is_a? SWIG::Pointer
+
+classname = e.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{e} is not an ArithUnaryFunction"
+end
+
+
+#
+# complex case
+#
+
+c = make_Identity_complex()
+raise RuntimeError, "#{c}is not an instance" if c.is_a? SWIG::Pointer
+
+classname = c.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{c} is not an ArithUnaryFunction"
+end
+
+f = make_Multiplies_complex_complex_complex_complex(c, c)
+raise RuntimeError, "{f} is not an instance" if f.is_a? SWIG::Pointer
+
+classname = f.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{f} is not an ArithUnaryFunction"
+end
+
+#
+# Mix case
+#
+
+g = make_Multiplies_double_double_complex_complex(d, c)
+raise RuntimeError, "#{g} is not an instance" if g.is_a? SWIG::Pointer
+
+classname = g.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{g} is not an ArithUnaryFunction"
+end
+
+# This should raise NoMethodError if it fails
+g.get_value()
+  
+h = make_Multiplies_complex_complex_double_double(c, d)
+raise RuntimeError, "#{h} is not an instance" if h.is_a? SWIG::Pointer
+
+classname = h.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{h} is not an ArithUnaryFunction"
+end
+
+
diff --git a/trunk/Examples/test-suite/ruby/template_typedef_cplx3_runme.rb b/trunk/Examples/test-suite/ruby/template_typedef_cplx3_runme.rb
new file mode 100644
index 0000000..98a8803
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_typedef_cplx3_runme.rb
@@ -0,0 +1,46 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_typedef_cplx3'
+
+include Template_typedef_cplx3
+
+#
+# this is OK
+#
+
+
+s = Sin.new
+s.get_base_value()
+s.get_value()
+s.get_arith_value()
+my_func_r(s)
+make_Multiplies_double_double_double_double(s,s)
+
+z = CSin.new
+z.get_base_value()
+z.get_value()
+z.get_arith_value()
+my_func_c(z)
+make_Multiplies_complex_complex_complex_complex(z,z)
+
+#
+# Here we fail
+#
+d = make_Identity_double()
+my_func_r(d)
+
+c = make_Identity_complex()
+my_func_c(c)
+  
+
+
+
diff --git a/trunk/Examples/test-suite/ruby/template_typedef_cplx4_runme.rb b/trunk/Examples/test-suite/ruby/template_typedef_cplx4_runme.rb
new file mode 100644
index 0000000..d67e3cd
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_typedef_cplx4_runme.rb
@@ -0,0 +1,46 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_typedef_cplx4'
+
+include Template_typedef_cplx4
+
+#
+# this is OK
+#
+
+
+s = Sin.new
+s.get_base_value()
+s.get_value()
+s.get_arith_value()
+my_func_r(s)
+make_Multiplies_double_double_double_double(s,s)
+
+z = CSin.new
+z.get_base_value()
+z.get_value()
+z.get_arith_value()
+my_func_c(z)
+make_Multiplies_complex_complex_complex_complex(z,z)
+
+#
+# Here we fail
+#
+d = make_Identity_double()
+my_func_r(d)
+
+c = make_Identity_complex()
+my_func_c(c)
+  
+
+
+
diff --git a/trunk/Examples/test-suite/ruby/template_typedef_cplx_runme.rb b/trunk/Examples/test-suite/ruby/template_typedef_cplx_runme.rb
new file mode 100644
index 0000000..eac337a
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/template_typedef_cplx_runme.rb
@@ -0,0 +1,77 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'template_typedef_cplx'
+
+include Template_typedef_cplx
+
+#
+# double case
+#
+
+
+d = make_Identity_double()
+raise RuntimeError, "#{d} is not an instance" if d.is_a? SWIG::Pointer
+
+classname = d.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{d} is not an ArithUnaryFunction"
+end
+
+e = make_Multiplies_double_double_double_double(d, d)
+raise RuntimeError, "#{e} is not an instance" if e.is_a? SWIG::Pointer
+
+classname = e.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{e} is not an ArithUnaryFunction"
+end
+
+
+#
+# complex case
+#
+
+c = make_Identity_complex()
+raise RuntimeError, "#{c}is not an instance" if c.is_a? SWIG::Pointer
+
+classname = c.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{c} is not an ArithUnaryFunction"
+end
+
+f = make_Multiplies_complex_complex_complex_complex(c, c)
+raise RuntimeError, "{f} is not an instance" if f.is_a? SWIG::Pointer
+
+classname = f.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{f} is not an ArithUnaryFunction"
+end
+
+#
+# Mix case
+#
+
+g = make_Multiplies_double_double_complex_complex(d, c)
+raise RuntimeError, "#{g} is not an instance" if g.is_a? SWIG::Pointer
+
+classname = g.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{g} is not an ArithUnaryFunction"
+end
+
+h = make_Multiplies_complex_complex_double_double(c, d)
+raise RuntimeError, "#{h} is not an instance" if h.is_a? SWIG::Pointer
+
+classname = h.class.name.split(/::/).last
+unless classname =~ /ArithUnaryFunction/
+  raise RuntimeError, "#{h} is not an ArithUnaryFunction"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/throw_exception_runme.rb b/trunk/Examples/test-suite/ruby/throw_exception_runme.rb
new file mode 100644
index 0000000..f21ff94
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/throw_exception_runme.rb
@@ -0,0 +1,41 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'throw_exception'
+
+include Throw_exception
+
+foo = Foo.new
+
+begin
+  foo.test_int
+rescue => ex
+  raise RuntimeError if ex.message != "37"
+end
+
+begin
+  foo.test_msg
+rescue => ex
+  raise RuntimeError if ex.message != "Dead"
+end
+
+begin
+  foo.test_multi(1)
+rescue => ex
+  raise RuntimeError if ex.message != "37"
+end
+
+begin
+  foo.test_multi(2)
+rescue => ex
+  raise RuntimeError if ex.message != "Dead"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/track_objects.i b/trunk/Examples/test-suite/ruby/track_objects.i
new file mode 100644
index 0000000..0a50e1f
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/track_objects.i
@@ -0,0 +1,125 @@
+%module track_objects
+
+%include typemaps.i
+
+%trackobjects Foo;
+
+%newobject Bar::get_new_foo;
+
+%typemap(in, numinputs=0) Foo** foo (Foo *temp) {
+	/* %typemap(in, numinputs=0) Foo** foo */
+	$1 = &temp;
+}
+
+%typemap(argout) Foo** foo {
+	/* %typemap(argout) Foo** foo */
+	$result = SWIG_NewPointerObj((void *) *$1, $*1_descriptor, 0);
+}	
+
+%apply SWIGTYPE *DISOWN {Foo* ownedFoo};
+
+
+%trackobjects ItemA;
+%trackobjects ItemB;
+
+%inline %{
+
+class Foo
+{
+public:
+	Foo() {}
+	~Foo() {}
+
+	/* Helper method that can be called from Ruby that checks
+	   that two Ruby objects are pointing to the same underlying
+		C++ object */
+	bool cpp_equal(const Foo* other)
+	{
+		return (this == other);
+	}
+
+	/* Just a simple method to call on Foo*/
+	const char* say_hello()
+	{
+		return "Hello";
+	}
+};
+
+
+class Bar
+{
+private:
+	Foo* owned_;
+	Foo* unowned_;
+public:
+	Bar(): owned_(new Foo), unowned_(0)
+	{
+	}
+
+	~Bar()
+	{
+		delete owned_;
+	}
+
+	/* Test that track objects works with %newobject */
+	static Foo* get_new_foo()
+	{
+		return new Foo;
+	}
+
+	/* Test the same foo Ruby object is created each time */
+	Foo* get_owned_foo()
+	{
+		return owned_;
+	}
+
+	/* Test that track objects works with argout parameters.*/
+	void get_owned_foo_by_argument(Foo** foo)
+	{
+		*foo = owned_;
+	}
+
+	/* Test that track objects works with the DISOWN typemap.*/
+	void set_owned_foo(Foo* ownedFoo)
+	{
+		delete owned_;
+		owned_ = ownedFoo;
+	}
+
+	Foo* get_unowned_foo()
+	{
+		return unowned_;
+	}
+
+	void set_unowned_foo(Foo* foo)
+	{
+		unowned_ = foo;
+	}
+};
+
+class ItemA
+{
+};
+
+class ItemB: public ItemA
+{
+public:
+};
+
+ItemB* downcast(ItemA* item)
+{
+	return static_cast<ItemB*>(item);
+}
+
+class Factory
+{
+public:
+	Factory() {}
+
+	ItemA* createItem()
+	{
+		return new ItemB;
+	}
+};
+
+%}
diff --git a/trunk/Examples/test-suite/ruby/track_objects_directors.i b/trunk/Examples/test-suite/ruby/track_objects_directors.i
new file mode 100644
index 0000000..adac8ae
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/track_objects_directors.i
@@ -0,0 +1,44 @@
+%module(directors="1") track_objects_directors
+
+%{
+#include <string>
+%}
+
+%include "std_string.i";
+%feature("director") Foo;
+
+%trackobjects;
+
+%inline %{
+
+class Foo {
+public:
+	Foo() {}
+	virtual ~Foo() {}
+	virtual std::string ping() 
+	{
+		return "Foo::ping()";
+	}
+
+	virtual std::string pong()
+	{
+		return "Foo::pong();" + ping();
+	}
+};
+
+
+class Container {
+	Foo* foo_;
+public:
+	Foo* get_foo() 
+	{
+		return foo_;
+	}
+
+	void set_foo(Foo *foo)
+	{
+		foo_ = foo;
+	}
+};
+
+%}
diff --git a/trunk/Examples/test-suite/ruby/track_objects_directors_runme.rb b/trunk/Examples/test-suite/ruby/track_objects_directors_runme.rb
new file mode 100644
index 0000000..247d3e9
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/track_objects_directors_runme.rb
@@ -0,0 +1,39 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'track_objects_directors'
+	
+class MyFoo < Track_objects_directors::Foo
+  def ping
+    "MyFoo::ping()"
+  end
+end
+
+a = MyFoo.new
+
+raise RuntimeError if a.ping != "MyFoo::ping()"
+raise RuntimeError if a.pong != "Foo::pong();MyFoo::ping()"
+
+b = Track_objects_directors::Foo.new
+
+raise RuntimeError if b.ping != "Foo::ping()"
+raise RuntimeError if b.pong != "Foo::pong();Foo::ping()"
+
+container = Track_objects_directors::Container.new
+foo = MyFoo.new
+container.set_foo(foo)
+    
+myFoo1 = container.get_foo
+myFoo2 = container.get_foo
+
+if not myFoo1.equal?(myFoo2)
+  raise RuntimeError, "MyFoo's should be the same"
+end
diff --git a/trunk/Examples/test-suite/ruby/track_objects_runme.rb b/trunk/Examples/test-suite/ruby/track_objects_runme.rb
new file mode 100644
index 0000000..27d8f6d
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/track_objects_runme.rb
@@ -0,0 +1,117 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'track_objects'
+
+def test_same_ruby_object(foo1, foo2)
+  if not foo1.equal?(foo2)
+    raise "Ruby objects should be the same."
+  end
+end
+
+def test_same_cpp_object(foo1, foo2)
+  if not foo1.cpp_equal(foo2)
+    raise "C++ objects should be the same"
+  end
+end
+
+bar = Track_objects::Bar.new
+foo1 = Track_objects::Foo.new()
+bar.set_unowned_foo(foo1)
+  
+# test_simple_identity
+foo2 = Track_objects::Foo.new()
+foo3 = foo2
+
+test_same_ruby_object(foo2, foo3)
+test_same_cpp_object(foo2, foo3)
+
+# test_unowned_foo_identity
+foo4 = bar.get_unowned_foo()
+
+test_same_ruby_object(foo1, foo4)
+test_same_cpp_object(foo1, foo4)
+
+# test_owned_foo_identity
+foo5 = bar.get_owned_foo()
+foo6 = bar.get_owned_foo()
+
+test_same_ruby_object(foo5, foo6)
+test_same_cpp_object(foo5, foo6)
+  
+# test_new_foo_identity
+foo7 = Track_objects::Bar.get_new_foo()
+foo8 = Track_objects::Bar.get_new_foo()
+
+if foo7.equal?(foo8)
+  raise "Ruby objects should be different."
+end
+
+if foo7.cpp_equal(foo8)
+  raise "C++ objects should be different."
+end
+    
+# test_set_owned_identity
+foo9 = Track_objects::Foo.new
+bar.set_owned_foo(foo9)
+foo10 = bar.get_owned_foo()
+    
+test_same_ruby_object(foo9, foo10)
+test_same_cpp_object(foo9, foo10)
+
+# test_set_owned_identity2
+begin
+  foo11 = Track_objects::Foo.new
+  bar.set_owned_foo(foo11)
+  foo11 = nil
+end
+   
+GC.start
+
+foo12 = bar.get_owned_foo()
+
+if not (foo12.say_hello == "Hello")
+  raise "Invalid C++ object returned."
+end
+
+# test_set_owned_identity3
+foo13 = bar.get_owned_foo_by_argument()
+foo14 = bar.get_owned_foo_by_argument()
+
+test_same_ruby_object(foo13, foo14)
+test_same_cpp_object(foo13, foo14)
+
+# Now create the factory
+factory = Track_objects::Factory.new
+
+# Create itemA which is really an itemB 
+itemA = factory.createItem
+
+# Check class
+if itemA.class != Track_objects::ItemA
+  raise RuntimeError, 'Item should have an ItemA class'
+end
+
+# Now downcast
+itemB = Track_objects.downcast(itemA)
+
+if itemB.class != Track_objects::ItemB
+  raise RuntimeError, 'Item should have an ItemB class'
+end
+
+if itemA.eql?(itemB)
+  raise RuntimeError, 'Items should be different'
+end
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/ruby/typedef_inherit_runme.rb b/trunk/Examples/test-suite/ruby/typedef_inherit_runme.rb
new file mode 100755
index 0000000..029b80c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/typedef_inherit_runme.rb
@@ -0,0 +1,38 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'typedef_inherit'
+
+a = Typedef_inherit::Foo.new
+b = Typedef_inherit::Bar.new
+
+x = Typedef_inherit.do_blah(a)
+if x != "Foo::blah"
+  puts "Whoa! Bad return #{x}"
+end
+
+x = Typedef_inherit.do_blah(b)
+if x != "Bar::blah"
+  puts "Whoa! Bad return #{x}"
+end
+
+c = Typedef_inherit::Spam.new
+d = Typedef_inherit::Grok.new
+
+x = Typedef_inherit.do_blah2(c)
+if x != "Spam::blah"
+  puts "Whoa! Bad return #{x}"
+end
+
+x = Typedef_inherit.do_blah2(d)
+if x != "Grok::blah"
+  puts "Whoa! Bad return #{x}"
+end
diff --git a/trunk/Examples/test-suite/ruby/typedef_scope_runme.rb b/trunk/Examples/test-suite/ruby/typedef_scope_runme.rb
new file mode 100755
index 0000000..4858a2e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/typedef_scope_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'typedef_scope'
+
+b = Typedef_scope::Bar.new
+
+x = b.test1(42, "hello")
+if x != 42
+  puts "Failed!!"
+end
+
+x = b.test2(42, "hello")
+if x != "hello"
+  puts "Failed!!"
+end
diff --git a/trunk/Examples/test-suite/ruby/typemap_namespace_runme.rb b/trunk/Examples/test-suite/ruby/typemap_namespace_runme.rb
new file mode 100755
index 0000000..09eb57e
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/typemap_namespace_runme.rb
@@ -0,0 +1,18 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'typemap_namespace'
+
+include Typemap_namespace
+
+raise RuntimeError if test1("hello") != "hello"
+
+raise RuntimeError if test2("hello") != "hello"
diff --git a/trunk/Examples/test-suite/ruby/typemap_ns_using_runme.rb b/trunk/Examples/test-suite/ruby/typemap_ns_using_runme.rb
new file mode 100644
index 0000000..80f38c3
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/typemap_ns_using_runme.rb
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'typemap_ns_using'
+
+raise RuntimeError unless Typemap_ns_using.spam(37) == 37
+
diff --git a/trunk/Examples/test-suite/ruby/typename_runme.rb b/trunk/Examples/test-suite/ruby/typename_runme.rb
new file mode 100755
index 0000000..65de733
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/typename_runme.rb
@@ -0,0 +1,25 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'typename'
+
+f = Typename::Foo.new
+b = Typename::Bar.new
+
+x = Typename.twoFoo(f)
+unless x.is_a? Float
+  puts "Wrong return type!"
+end
+
+y = Typename.twoBar(b)
+unless y.is_a? Integer
+  puts "Wrong return type!"
+end
diff --git a/trunk/Examples/test-suite/ruby/unions_runme.rb b/trunk/Examples/test-suite/ruby/unions_runme.rb
new file mode 100644
index 0000000..00a8703
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/unions_runme.rb
@@ -0,0 +1,65 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+
+# This is the union runtime testcase. It ensures that values within a 
+# union embedded within a struct can be set and read correctly.
+
+require 'unions'
+
+# Create new instances of SmallStruct and BigStruct for later use
+small = Unions::SmallStruct.new()
+small.jill = 200
+
+big = Unions::BigStruct.new()
+big.smallstruct = small
+big.jack = 300
+
+# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+# Ensure values in EmbeddedUnionTest are set correctly for each.
+eut = Unions::EmbeddedUnionTest.new()
+
+# First check the SmallStruct in EmbeddedUnionTest
+eut.number = 1
+eut.uni.small = small
+Jill1 = eut.uni.small.jill
+if (Jill1 != 200)
+    print "Runtime test1 failed. eut.uni.small.jill=" , Jill1 , "\n"
+    exit 1
+end
+
+Num1 = eut.number
+if (Num1 != 1)
+    print "Runtime test2 failed. eut.number=" , Num1 , "\n"
+    exit 1
+end
+
+# Secondly check the BigStruct in EmbeddedUnionTest
+eut.number = 2
+eut.uni.big = big
+Jack1 = eut.uni.big.jack
+if (Jack1 != 300)
+    print "Runtime test3 failed. eut.uni.big.jack=" , Jack1 , "\n"
+    exit 1
+end
+
+Jill2 = eut.uni.big.smallstruct.jill
+if (Jill2 != 200)
+    print "Runtime test4 failed. eut.uni.big.smallstruct.jill=" , Jill2 , "\n"
+    exit 1
+end
+
+Num2 = eut.number
+if (Num2 != 2)
+    print "Runtime test5 failed. eut.number=" , Num2 , "\n"
+    exit 1
+end
+
diff --git a/trunk/Examples/test-suite/ruby/using1_runme.rb b/trunk/Examples/test-suite/ruby/using1_runme.rb
new file mode 100644
index 0000000..44fcf12
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using1_runme.rb
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using1'
+
+raise RuntimeError unless Using1.spam(37) == 37
+
diff --git a/trunk/Examples/test-suite/ruby/using2_runme.rb b/trunk/Examples/test-suite/ruby/using2_runme.rb
new file mode 100644
index 0000000..1eb72c1
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using2_runme.rb
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using2'
+
+raise RuntimeError unless Using2.spam(37) == 37
+
diff --git a/trunk/Examples/test-suite/ruby/using_composition_runme.rb b/trunk/Examples/test-suite/ruby/using_composition_runme.rb
new file mode 100644
index 0000000..b9500cb
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using_composition_runme.rb
@@ -0,0 +1,56 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using_composition'
+
+include Using_composition
+
+f = FooBar.new
+if f.blah(3) != 3
+  raise RuntimeError,"FooBar::blah(int)"
+end
+
+if f.blah(3.5) != 3.5
+  raise RuntimeError,"FooBar::blah(double)"
+end
+
+if f.blah("hello") != "hello"
+  raise RuntimeError,"FooBar::blah(char *)"
+end
+
+
+f = FooBar2.new
+if f.blah(3) != 3
+  raise RuntimeError,"FooBar2::blah(int)"
+end
+
+if f.blah(3.5) != 3.5
+  raise RuntimeError,"FooBar2::blah(double)"
+end
+
+if f.blah("hello") != "hello"
+  raise RuntimeError,"FooBar2::blah(char *)"
+end
+
+
+f = FooBar3.new
+if f.blah(3) != 3
+  raise RuntimeError,"FooBar3::blah(int)"
+end
+
+if f.blah(3.5) != 3.5
+  raise RuntimeError,"FooBar3::blah(double)"
+end
+
+if f.blah("hello") != "hello"
+  raise RuntimeError,"FooBar3::blah(char *)"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/using_extend_runme.rb b/trunk/Examples/test-suite/ruby/using_extend_runme.rb
new file mode 100644
index 0000000..4caaa5b
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using_extend_runme.rb
@@ -0,0 +1,36 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using_extend'
+
+include Using_extend
+
+f = FooBar.new
+if f.blah(3) != 3
+  raise RuntimeError,"blah(int)"
+end
+
+if f.blah(3.5) != 3.5
+  raise RuntimeError,"blah(double)"
+end
+
+if f.blah("hello") != "hello"
+  raise RuntimeError,"blah(char *)"
+end
+
+if f.blah(3,4) != 7
+  raise RuntimeError,"blah(int,int)"
+end
+
+if f.blah(3.5,7.5) != (3.5+7.5)
+  raise RuntimeError,"blah(double,double)"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/using_inherit_runme.rb b/trunk/Examples/test-suite/ruby/using_inherit_runme.rb
new file mode 100644
index 0000000..1b7e404
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using_inherit_runme.rb
@@ -0,0 +1,74 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using_inherit'
+
+include Using_inherit
+
+b = Bar.new
+if b.test(3) != 3
+  raise RuntimeError,"Bar::test(int)"
+end
+
+if b.test(3.5) != 3.5
+  raise RuntimeError, "Bar::test(double)"
+end
+
+b = Bar2.new
+if b.test(3) != 6
+  raise RuntimeError,"Bar2::test(int)"
+end
+
+if b.test(3.5) != 7.0
+  raise RuntimeError, "Bar2::test(double)"
+end
+
+
+b = Bar3.new
+if b.test(3) != 6
+  raise RuntimeError,"Bar3::test(int)"
+end
+
+if b.test(3.5) != 7.0
+  raise RuntimeError, "Bar3::test(double)"
+end
+
+
+b = Bar4.new
+if b.test(3) != 6
+  raise RuntimeError,"Bar4::test(int)"
+end
+
+if b.test(3.5) != 7.0
+  raise RuntimeError, "Bar4::test(double)"
+end
+
+
+b = Fred1.new
+if b.test(3) != 3
+  raise RuntimeError,"Fred1::test(int)"
+end
+
+if b.test(3.5) != 7.0
+  raise RuntimeError, "Fred1::test(double)"
+end
+
+
+b = Fred2.new
+if b.test(3) != 3
+  raise RuntimeError,"Fred2::test(int)"
+end
+
+if b.test(3.5) != 7.0
+  raise RuntimeError, "Fred2::test(double)"
+end
+
+
diff --git a/trunk/Examples/test-suite/ruby/using_private_runme.rb b/trunk/Examples/test-suite/ruby/using_private_runme.rb
new file mode 100644
index 0000000..cf6928c
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using_private_runme.rb
@@ -0,0 +1,30 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using_private'
+
+include Using_private
+
+f = FooBar.new
+f.x = 3
+
+if f.blah(4) != 4
+  raise RuntimeError, "blah(int)"
+end
+
+if f.defaulted() != -1
+  raise RuntimeError, "defaulted()"
+end
+
+if f.defaulted(222) != 222
+  raise RuntimeError, "defaulted(hi)"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/using_protected_runme.rb b/trunk/Examples/test-suite/ruby/using_protected_runme.rb
new file mode 100644
index 0000000..3b4f88b
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/using_protected_runme.rb
@@ -0,0 +1,22 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'using_protected'
+
+include Using_protected
+
+f = FooBar.new
+f.x = 3
+
+if f.blah(4) != 4
+  raise RuntimeError, "blah(int)"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/varargs_runme.rb b/trunk/Examples/test-suite/ruby/varargs_runme.rb
new file mode 100644
index 0000000..9825c25
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/varargs_runme.rb
@@ -0,0 +1,26 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'varargs'
+
+if Varargs.test("Hello") != "Hello"
+  raise RuntimeError, "Failed"
+end
+
+f = Varargs::Foo.new("Greetings")
+if f.str != "Greetings"
+  raise RuntimeError, "Failed"
+end
+
+if f.test("Hello") != "Hello"
+  raise RuntimeError, "Failed"
+end
+
diff --git a/trunk/Examples/test-suite/ruby/virtual_derivation_runme.rb b/trunk/Examples/test-suite/ruby/virtual_derivation_runme.rb
new file mode 100644
index 0000000..a739ddf
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/virtual_derivation_runme.rb
@@ -0,0 +1,18 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'virtual_derivation'
+
+b = Virtual_derivation::B.new 3
+
+if b.get_a() != b.get_b() 
+  print "something is still wrong ", b.get_a(), b.get_b(), "\n"
+end
diff --git a/trunk/Examples/test-suite/ruby/virtual_poly_runme.rb b/trunk/Examples/test-suite/ruby/virtual_poly_runme.rb
new file mode 100644
index 0000000..38752cc
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/virtual_poly_runme.rb
@@ -0,0 +1,33 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'virtual_poly'
+
+d = Virtual_poly::NDouble.new(3.5)
+i = Virtual_poly::NInt.new(2)
+
+#
+# polymorphic return type working
+#
+dc = d.copy
+ic = i.copy
+
+raise RuntimeError if d.get != dc.get
+raise RuntimeError if i.get != ic.get
+
+#
+# 'narrowing' working ('nnumber' returns a NNumber)
+#
+ddc = Virtual_poly::NDouble.narrow(dc.nnumber)
+raise RuntimeError if d.get != ddc.get 
+
+dic = Virtual_poly::NInt.narrow(ic.nnumber)
+raise RuntimeError if i.get != dic.get
diff --git a/trunk/Examples/test-suite/ruby/voidtest_runme.rb b/trunk/Examples/test-suite/ruby/voidtest_runme.rb
new file mode 100644
index 0000000..33cffe6
--- /dev/null
+++ b/trunk/Examples/test-suite/ruby/voidtest_runme.rb
@@ -0,0 +1,24 @@
+#!/usr/bin/env ruby
+#
+# Put description here
+#
+# 
+# 
+# 
+#
+
+require 'swig_assert'
+
+require 'voidtest'
+
+Voidtest.globalfunc()
+f = Voidtest::Foo.new
+f.memberfunc()
+
+Voidtest::Foo.staticmemberfunc()
+
+v1 = Voidtest::vfunc1(f)
+v3 =  Voidtest::vfunc3(v1)
+
+v3.memberfunc()
+
diff --git a/trunk/Examples/test-suite/samename.i b/trunk/Examples/test-suite/samename.i
new file mode 100644
index 0000000..819cb4a
--- /dev/null
+++ b/trunk/Examples/test-suite/samename.i
@@ -0,0 +1,22 @@
+%module samename
+
+#if !(defined(SWIGCSHARP) || defined(SWIGJAVA))
+class samename {
+ public:
+  void do_something() {
+    // ...
+  }
+};
+#endif
+
+%{
+
+class samename {
+ public:
+  void do_something() {
+    // ...
+  }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/samename_runme.m b/trunk/Examples/test-suite/samename_runme.m
new file mode 100644
index 0000000..a3864cf
--- /dev/null
+++ b/trunk/Examples/test-suite/samename_runme.m
@@ -0,0 +1 @@
+samename
diff --git a/trunk/Examples/test-suite/schemerunme/casts.scm b/trunk/Examples/test-suite/schemerunme/casts.scm
new file mode 100644
index 0000000..8a566ec
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/casts.scm
@@ -0,0 +1,8 @@
+(define x (new-B))
+
+;; This fails in 1.3a5 because the SWIG/Guile runtime code gets the
+;; source and the target of a cast the wrong way around.
+
+(A-hello x)				
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/char_constant.scm b/trunk/Examples/test-suite/schemerunme/char_constant.scm
new file mode 100644
index 0000000..81ee7da
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/char_constant.scm
@@ -0,0 +1,4 @@
+(if (and (char? (CHAR-CONSTANT))
+	 (string? (STRING-CONSTANT)))
+    (exit 0)
+    (exit 1))
diff --git a/trunk/Examples/test-suite/schemerunme/class_ignore.scm b/trunk/Examples/test-suite/schemerunme/class_ignore.scm
new file mode 100644
index 0000000..2a62e7b
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/class_ignore.scm
@@ -0,0 +1,6 @@
+(define a (new-Bar))
+
+(if (not (string=? (Bar-blah a) "Bar::blah"))
+    (error "Wrong string"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/constover.scm b/trunk/Examples/test-suite/schemerunme/constover.scm
new file mode 100644
index 0000000..38c30cb
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/constover.scm
@@ -0,0 +1,26 @@
+(define p (test "test"))
+(if (not (string=? p "test"))
+    (error "test failed!"))
+
+(set! p (test-pconst "test"))
+(if (not (string=? p "test_pconst"))
+    (error "test_pconst failed!"))
+
+(define f (new-Foo))
+(set! p (Foo-test f "test"))
+(if (not (string=? p "test"))
+    (error "member-test failed!"))
+
+(set! p (Foo-test-pconst f "test"))
+(if (not (string=? p "test_pconst"))
+    (error "member-test_pconst failed!"))
+
+(set! p (Foo-test-constm f "test"))
+(if (not (string=? p "test_constmethod"))
+    (error "member-test_constm failed!"))
+
+(set! p (Foo-test-pconstm f "test"))
+(if (not (string=? p "test_pconstmethod"))
+    (error "member-test_pconstm failed!"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/contract.scm b/trunk/Examples/test-suite/schemerunme/contract.scm
new file mode 100644
index 0000000..16dd069
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/contract.scm
@@ -0,0 +1,14 @@
+(test-preassert 1 2)
+(expect-throw 'swig-contract-assertion-failed
+	      (test-preassert -1 2))
+(test-postassert 3)
+(expect-throw 'swig-contract-assertion-failed
+	      (test-postassert -3))
+(test-prepost 2 3)
+(test-prepost 5 -4)
+(expect-throw 'swig-contract-assertion-failed
+	      (test-prepost -3 4))
+(expect-throw 'swig-contract-assertion-failed
+	      (test-prepost 4 -10))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/cpp_enum.scm b/trunk/Examples/test-suite/schemerunme/cpp_enum.scm
new file mode 100644
index 0000000..101c0da
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/cpp_enum.scm
@@ -0,0 +1,21 @@
+(define f (new-Foo))
+
+(if (not (= (Foo-hola-get f) (Foo-Hello)))
+  (error "Error 1"))
+
+(Foo-hola-set f (Foo-Hi))
+
+(if (not (= (Foo-hola-get f) (Foo-Hi)))
+  (error "Error 2"))
+
+(Foo-hola-set f (Foo-Hello))
+
+(if (not (= (Foo-hola-get f) (Foo-Hello)))
+  (error "Error 3"))
+
+(hi (Hello))
+
+(if (not (= (hi) (Hello)))
+  (error "Error 4"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/cpp_namespace.scm b/trunk/Examples/test-suite/schemerunme/cpp_namespace.scm
new file mode 100644
index 0000000..ecfdab5
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/cpp_namespace.scm
@@ -0,0 +1,42 @@
+(define n (fact 4))
+(if (not (= n 24))
+    (error "Bad return value!"))
+
+(if (not (= (Foo) 42))
+    (error "bad variable value!"))
+
+(define t (new-Test))
+(if (not (string=? (Test-method t) "Test::method"))
+    (error "Bad method return value!"))
+
+(if (not (string=? (do-method t) "Test::method"))
+    (error "Bad return value!"))
+
+(if (not (string=? (do-method2 t) "Test::method"))
+    (error "Bad return value!"))
+
+(weird "hello" 4)
+
+;; (delete-Test t)
+
+(define t2 (new-Test2))
+(define t3 (new-Test3))
+(define t4 (new-Test4))
+(define t5 (new-Test5))
+
+(if (not (= (foo3 42) 42))
+    (error "Bad return value!"))
+
+(if (not (string=? (do-method3 t2 40) "Test2::method"))
+    (error "bad return value!"))
+
+(if (not (string=? (do-method3 t3 40) "Test3::method"))
+    (error "bad return value"))
+
+(if (not (string=? (do-method3 t4 40) "Test4::method"))
+    (error "bad return value"))
+
+(if (not (string=? (do-method3 t5 40) "Test5::method"))
+    (error "bad return value"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/dynamic_cast.scm b/trunk/Examples/test-suite/schemerunme/dynamic_cast.scm
new file mode 100644
index 0000000..ebb44de
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/dynamic_cast.scm
@@ -0,0 +1,11 @@
+(define f (new-Foo))
+(define b (new-Bar))
+
+(define x (Foo-blah f))
+(define y (Bar-blah b))
+
+(define a (do-test y))
+(if (not (string=? a "Bar::test"))
+    (error "Failed!"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/global_vars.scm b/trunk/Examples/test-suite/schemerunme/global_vars.scm
new file mode 100644
index 0000000..a3e0219
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/global_vars.scm
@@ -0,0 +1,31 @@
+(define-macro (check test)
+  `(if (not ,test) (error "Error in test" ',test)))
+
+(b "hello")
+(check (string=? (b) "hello"))
+
+(define sa (new-A))
+(A-x-set sa 5)
+(a sa)
+(check (= (A-x-get (a)) 5))
+
+(ap sa)
+(check (= (A-x-get (ap)) 5))
+(A-x-set sa 10)
+(check (= (A-x-get (ap)) 10))
+
+(define sa2 (new-A))
+(A-x-set sa2 -4)
+(cap sa2)
+(check (= (A-x-get (cap)) -4))
+(A-x-set sa2 -7)
+(check (= (A-x-get (cap)) -7))
+
+(check (= (A-x-get (ar)) 5))
+(ar sa2)
+(check (= (A-x-get (ar)) -7))
+
+(x 4)
+(check (= (x) 4))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/global_vars_proxy.scm b/trunk/Examples/test-suite/schemerunme/global_vars_proxy.scm
new file mode 100644
index 0000000..41d7337
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/global_vars_proxy.scm
@@ -0,0 +1,31 @@
+(define-macro (check test)
+  `(if (not ,test) (error "Error in test" ',test)))
+
+(b "hello")
+(check (string=? (b) "hello"))
+
+(define sa (make <A>))
+(slot-set! sa 'x 5)
+(a sa)
+(check (= (slot-ref (a) 'x) 5))
+
+(ap sa)
+(check (= (slot-ref (ap) 'x) 5))
+(slot-set! sa 'x 10)
+(check (= (slot-ref (ap) 'x) 10))
+
+(define sa2 (make <A>))
+(slot-set! sa2 'x -4)
+(cap sa2)
+(check (= (slot-ref (cap) 'x) -4))
+(slot-set! sa2 'x -7)
+(check (= (slot-ref (cap) 'x) -7))
+
+(check (= (slot-ref (ar) 'x) 5))
+(ar sa2)
+(check (= (slot-ref (ar) 'x) -7))
+
+(x 4)
+(check (= (x) 4))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/import_nomodule.scm b/trunk/Examples/test-suite/schemerunme/import_nomodule.scm
new file mode 100644
index 0000000..4598a8b
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/import_nomodule.scm
@@ -0,0 +1,7 @@
+(define f (create-Foo))
+(test1 f 42)
+
+(define b (new-Bar))
+(test1 b 37)
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/imports.scm b/trunk/Examples/test-suite/schemerunme/imports.scm
new file mode 100644
index 0000000..663cc8b
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/imports.scm
@@ -0,0 +1,13 @@
+;;; This file is part of a test for SF bug #231619. 
+;;; It shows that the %import directive does not work properly in SWIG
+;;; 1.3a5:  Type information is not properly generated if a base class
+;;; comes from an %import-ed file. 
+
+(define x (new-B))
+
+;; This fails in 1.3a5 because the SWIG runtime code does not know
+;; that x (an instance of class B) can be passed to methods of class A. 
+
+(A-hello x)				
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/inherit_missing.scm b/trunk/Examples/test-suite/schemerunme/inherit_missing.scm
new file mode 100644
index 0000000..1b9bd0e
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/inherit_missing.scm
@@ -0,0 +1,14 @@
+(define a (new-Foo))
+(define b (new-Bar))
+(define c (new-Spam))
+
+(if (not (string=? (do-blah a) "Foo::blah"))
+    (error "Bad return"))
+
+(if (not (string=? (do-blah b) "Bar::blah"))
+    (error "Bad return"))
+
+(if (not (string=? (do-blah c) "Spam::blah"))
+    (error "bad return"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/integers.scm b/trunk/Examples/test-suite/schemerunme/integers.scm
new file mode 100644
index 0000000..0bbf36e
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/integers.scm
@@ -0,0 +1,28 @@
+(define-macro (check-equality form1 form2)
+  `(let ((result1 ,form1)
+	 (result2 ,form2))
+     (if (not (equal? result1 result2))
+	 (error "Check failed:"
+		(list 'equal? ',form1 ',form2)
+		result1 result2))))
+
+(define-macro (check-range function from to)
+  `(begin (check-equality (,function ,from) ,from)
+	  (check-equality (,function ,to)   ,to)
+	  (check-equality (throws-exception? (,function (- ,from 1))) #t)
+	  (check-equality (throws-exception? (,function (+ ,to 1))) #t)))
+
+;;; signed char, unsigned char typemaps deal with characters, not integers.
+;; (check-range signed-char-identity (- (expt 2 7)) (- (expt 2 7) 1))
+;; (check-range unsigned-char-identity 0 (- (expt 2 8) 1))
+(check-range signed-short-identity (- (expt 2 15)) (- (expt 2 15) 1))
+(check-range unsigned-short-identity 0 (- (expt 2 16) 1))
+(check-range signed-int-identity (- (expt 2 31)) (- (expt 2 31) 1))
+(check-range unsigned-int-identity 0 (- (expt 2 32) 1))
+(check-range signed-long-identity (- (expt 2 31)) (- (expt 2 31) 1))
+(check-range unsigned-long-identity 0 (- (expt 2 32) 1))
+;;; long long not implemented in Guile and MzScheme.
+;; (check-range signed-long-long-identity (- (expt 2 63)) (- (expt 2 63) 1))
+;; (check-range unsigned-long-long-identity 0 (- (expt 2 64) 1))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/li_std_string.scm b/trunk/Examples/test-suite/schemerunme/li_std_string.scm
new file mode 100644
index 0000000..e77c328
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/li_std_string.scm
@@ -0,0 +1,46 @@
+(define x "hello")
+
+(if (not (string=? (test-value x) x))
+  (begin (error "Error 1") (exit 1)))
+
+(if (not (string=? (test-const-reference x) x))
+  (begin (error "Error 2") (exit 1)))
+
+(define y (test-pointer-out))
+(test-pointer y)
+(define z (test-const-pointer-out))
+(test-const-pointer z)
+
+(define a (test-reference-out))
+(test-reference a)
+
+;; test global variables
+(GlobalString "whee")
+(if (not (string=? (GlobalString) "whee"))
+  (error "Error 3"))
+(if (not (string=? (GlobalString2) "global string 2"))
+  (error "Error 4"))
+
+(define struct (new-Structure))
+
+;; MemberString should be a wrapped class
+(define scl (Structure-MemberString-get struct))
+(if (not (string=? scl ""))
+  (error "Error 4.5"))
+(Structure-MemberString-set struct "and how")
+(if (not (string=? (Structure-MemberString-get struct) "and how"))
+  (error "Error 5"))
+(if (not (string=? (Structure-MemberString2-get struct) "member string 2"))
+  (error "Error 6"))
+(Structure-StaticMemberString "static str")
+(if (not (string=? (Structure-StaticMemberString) "static str"))
+  (error "Error 7"))
+(if (not (string=? (Structure-StaticMemberString2) "static member string 2"))
+  (error "Error 8"))
+
+;(if (not (string=? (Structure-ConstMemberString-get struct) "const member string"))
+;  (error "Error 9"))
+(if (not (string=? (Structure-ConstStaticMemberString) "const static member string"))
+  (error "Error 10"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/li_typemaps.scm b/trunk/Examples/test-suite/schemerunme/li_typemaps.scm
new file mode 100644
index 0000000..161e803
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/li_typemaps.scm
@@ -0,0 +1,45 @@
+(define-macro (check func val test)
+  (cons 'begin
+    (map
+      (lambda (x) 
+        `(if (not (,test (,(string->symbol (string-append x func)) ,val) ,val))
+           (error ,(string-append "Error in test " x func))))
+      (list "in-" "inr-" "out-" "outr-" "inout-" "inoutr-"))))
+
+(define (=~ a b)
+  (< (abs (- a b)) 1e-5))
+                      
+(check "bool" #t and)
+(check "int" -2 =)
+(check "long" -32 =)
+(check "short" -15 =)
+(check "uint" 75 =)
+(check "ushort" 123 =)
+(check "ulong" 462 =)
+;(check "uchar" 16 =)
+;(check "schar" -53 =)
+(check "float" 4.3 =~)
+(check "double" -175.42 =~)
+;(check "longlong" 1634 =)
+;(check "ulonglong" 6432 =)
+
+;; The checking of inoutr-int2 and out-foo is done in the individual
+;; language runme scripts, since chicken returns multiple values
+;; and must be checked with call-with-values, while guile just returns a list
+
+;(call-with-values (lambda () (inoutr-int2 3 -2))
+;		  (lambda (a b)
+;		    (if (not (and (= a 3) (= b -2)))
+;		      (error "Error in inoutr-int2"))))
+;(call-with-values (lambda () (out-foo 4))
+;		  (lambda (a b)
+;		    (if (not (and (= (Foo-a-get a) 4) (= b 8)))
+;		      (error "Error in out-foo"))))
+		      
+;(let ((lst (inoutr-int2 3 -2)))
+;  (if (not (and (= (car lst) 3) (= (cadr lst) -2)))
+;    (error "Error in inoutr-int2")))
+
+;(let ((lst (out-foo 4)))
+;  (if (not (and (= (Foo-a-get (car lst)) 4) (= (cadr lst) 8)))
+;    (error "Error in out-foo")))
diff --git a/trunk/Examples/test-suite/schemerunme/li_typemaps_proxy.scm b/trunk/Examples/test-suite/schemerunme/li_typemaps_proxy.scm
new file mode 100644
index 0000000..f61d4fe
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/li_typemaps_proxy.scm
@@ -0,0 +1,45 @@
+(define-macro (check func val test)
+  (cons 'begin
+    (map
+      (lambda (x) 
+        `(if (not (,test (,(string->symbol (string-append x func)) ,val) ,val))
+           (error ,(string-append "Error in test " x func))))
+      (list "in-" "inr-" "out-" "outr-" "inout-" "inoutr-"))))
+
+(define (=~ a b)
+  (< (abs (- a b)) 1e-5))
+                      
+(check "bool" #t and)
+(check "int" -2 =)
+(check "long" -32 =)
+(check "short" -15 =)
+(check "uint" 75 =)
+(check "ushort" 123 =)
+(check "ulong" 462 =)
+;(check "uchar" 16 =)
+;(check "schar" -53 =)
+(check "float" 4.3 =~)
+(check "double" -175.42 =~)
+(check "longlong" 1634 =)
+(check "ulonglong" 6432 =)
+
+;; The checking of inoutr-int2 and out-foo is done in the individual
+;; language runme scripts, since chicken returns multiple values
+;; and must be checked with call-with-values, while guile just returns a list
+
+;(call-with-values (lambda () (inoutr-int2 3 -2))
+;		  (lambda (a b)
+;		    (if (not (and (= a 3) (= b -2)))
+;		      (error "Error in inoutr-int2"))))
+;(call-with-values (lambda () (out-foo 4))
+;		  (lambda (a b)
+;		    (if (not (and (= (slot-ref a 'a) 4) (= b 8)))
+;		      (error "Error in out-foo"))))
+
+;(let ((lst (inoutr-int2 3 -2)))
+;  (if (not (and (= (car lst) 3) (= (cadr lst) -2)))
+;    (error "Error in inoutr-int2")))
+
+;(let ((lst (out-foo 4)))
+;  (if (not (and (= (slot-ref (car lst) 'a) 4) (= (cadr lst) 8)))
+;    (error "Error in out-foo")))
diff --git a/trunk/Examples/test-suite/schemerunme/list_vector.scm b/trunk/Examples/test-suite/schemerunme/list_vector.scm
new file mode 100644
index 0000000..e3dfa6a
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/list_vector.scm
@@ -0,0 +1,26 @@
+(define-macro (check-equality form1 form2)
+  `(let ((result1 ,form1)
+	 (result2 ,form2))
+     (if (not (equal? result1 result2))
+	 (error "Check failed:"
+		(list 'equal? ',form1 ',form2)
+		result1 result2))))
+
+(check-equality (sum-list '(1 3 4 6 7)) 21.0)
+(check-equality (sum-vector #(2 4 6 7 9)) 28.0)
+(check-equality (one-to-seven-list) '(1 2 3 4 5 6 7))
+(check-equality (one-to-seven-vector) #(1 2 3 4 5 6 7))
+
+(check-equality (sum-list2 '(1 3 4 6 7)) 21.0)
+(check-equality (sum-vector2 #(2 4 6 7 9)) 28.0)
+(check-equality (one-to-seven-list2) '(1 2 3 4 5 6 7))
+(check-equality (one-to-seven-vector2) #(1 2 3 4 5 6 7))
+
+(check-equality (sum-lists '(1 2 3) '(4 5 6) '(7 8 9)) 45.0)
+(check-equality (sum-lists2 '(1 2 3) '(4 5 6) '(7 8 9)) 45.0)
+(check-equality (call-with-values produce-lists list)
+	       '(#(0 1 2 3 4)
+		 #(0 1 4 9 16)
+		 #(0.0 1.5 3.0 4.5 6.0)))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/multiple_inheritance_proxy.scm b/trunk/Examples/test-suite/schemerunme/multiple_inheritance_proxy.scm
new file mode 100644
index 0000000..ab48f8a
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/multiple_inheritance_proxy.scm
@@ -0,0 +1,31 @@
+(define-macro (check test)
+  `(if (not ,test) (error "Error in test" ',test)))
+
+(define b (make <Bar>))
+(check (= (bar b) 1))
+
+(define f (make <Foo>))
+(check (= (foo f) 2))
+
+(define fb (make <FooBar>))
+(check (= (bar fb) 1))
+(check (= (foo fb) 2))
+(check (= (fooBar fb) 3))
+
+(define id1 (make <IgnoreDerived1>))
+(check (= (bar id1) 1))
+(check (= (ignorederived1 id1) 7))
+
+(define id2 (make <IgnoreDerived2>))
+(check (= (bar id2) 1))
+(check (= (ignorederived2 id2) 8))
+
+(define id3 (make <IgnoreDerived3>))
+(check (= (bar id3) 1))
+(check (= (ignorederived3 id3) 9))
+
+(define id4 (make <IgnoreDerived4>))
+(check (= (bar id4) 1))
+(check (= (ignorederived4 id4) 10))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/multivalue.scm b/trunk/Examples/test-suite/schemerunme/multivalue.scm
new file mode 100644
index 0000000..780ba38
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/multivalue.scm
@@ -0,0 +1,19 @@
+;;;; Automatic test of multiple return values
+
+(let ((quotient/remainder (divide-l 37 5)))
+  (if (not (equal? quotient/remainder '(7 2)))
+      (exit 1)))
+
+(let ((quotient-remainder-vector (divide-v 41 7)))
+  (if (not (equal? quotient-remainder-vector #(5 6)))
+      (exit 1)))
+
+(call-with-values (lambda ()
+		    (divide-mv 91 13))
+		  (lambda (quotient remainder)
+		    (if (not (and (= quotient 7)
+				  (= remainder 0)))
+			(exit 1))))
+
+(exit 0)
+			     
diff --git a/trunk/Examples/test-suite/schemerunme/name.scm b/trunk/Examples/test-suite/schemerunme/name.scm
new file mode 100644
index 0000000..6fbaf7c
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/name.scm
@@ -0,0 +1,5 @@
+(foo-2)
+bar-2
+Baz-2
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/overload_complicated.scm b/trunk/Examples/test-suite/schemerunme/overload_complicated.scm
new file mode 100644
index 0000000..4320c82
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/overload_complicated.scm
@@ -0,0 +1,16 @@
+(define-macro (check form)
+  `(if (not ,form)
+       (error "Check failed: " ',form)))
+
+(define (=~ a b)
+  (< (abs (- a b)) 1e-8))
+
+;; Check first method
+(check (=~ (foo 1 2 "bar" 4) 15))
+
+;; Check second method
+(check (=~ (foo 1 2) 4811.4))
+(check (=~ (foo 1 2 3.2) 4797.2))
+(check (=~ (foo 1 2 3.2 #\Q) 4798.2))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/overload_copy.scm b/trunk/Examples/test-suite/schemerunme/overload_copy.scm
new file mode 100644
index 0000000..b6e89c7
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/overload_copy.scm
@@ -0,0 +1,4 @@
+(define f (new-Foo))
+(define g (new-Foo f))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/overload_extend.scm b/trunk/Examples/test-suite/schemerunme/overload_extend.scm
new file mode 100644
index 0000000..0b03b28
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/overload_extend.scm
@@ -0,0 +1,12 @@
+(define f (new-Foo))
+
+(if (not (= (Foo-test f 3) 1))
+    (error "test integer bad"))
+
+(if (not (= (Foo-test f "hello") 2))
+    (error "test string bad"))
+
+(if (not (= (Foo-test f 3.5 2.5) 6.0))
+    (error "test reals bad"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/overload_simple.scm b/trunk/Examples/test-suite/schemerunme/overload_simple.scm
new file mode 100644
index 0000000..fc60ff1
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/overload_simple.scm
@@ -0,0 +1,51 @@
+(if (not (string=? (foo 3) "foo:int"))
+    (error "foo(int)"))
+
+(if (not (string=? (foo 3.01) "foo:double"))
+    (error "foo(double)"))
+
+(if (not (string=? (foo "hello") "foo:char *"))
+    (error "foo(char *)"))
+
+(let ((f (new-Foo))
+      (b (new-Bar))
+      (s (new-Spam)))
+  (if (not (string=? (foo f) "foo:Foo *"))
+      (error "foo(Foo *)"))
+  (if (not (string=? (foo b) "foo:Bar *"))
+      (error "foo(Bar *)"))
+  ;; Test member functions
+  (if (not (string=? (Spam-foo s 3) "foo:int"))
+      (error "Spam::foo(int)"))
+  (if (not (string=? (Spam-foo s 3.01) "foo:double"))
+      (error "Spam::foo(double)"))
+  (if (not (string=? (Spam-foo s "hello") "foo:char *"))
+      (error "Spam::foo(char *)"))
+  (if (not (string=? (Spam-foo s f) "foo:Foo *"))
+      (error "Spam::foo(Foo *)"))
+  (if (not (string=? (Spam-foo s b) "foo:Bar *"))
+      (error "Spam::foo(Bar *)"))
+  ;; Test static member functions
+  (if (not (string=? (Spam-bar 3) "bar:int"))
+      (error "Spam::bar(int)"))
+  (if (not (string=? (Spam-bar 3.01) "bar:double"))
+      (error "Spam::bar(double)"))
+  (if (not (string=? (Spam-bar "hello") "bar:char *"))
+      (error "Spam::bar(char *)"))
+  (if (not (string=? (Spam-bar f) "bar:Foo *"))
+      (error "Spam::bar(Foo *)"))
+  (if (not (string=? (Spam-bar b) "bar:Bar *"))
+      (error "Spam::bar(Bar *)"))
+  ;; Test constructors
+  (if (not (string=? (Spam-type-get (new-Spam)) "none"))
+      (error "Spam()"))
+  (if (not (string=? (Spam-type-get (new-Spam 3)) "int"))
+      (error "Spam(int)"))
+  (if (not (string=? (Spam-type-get (new-Spam 3.4)) "double"))
+      (error "Spam(double)"))
+  (if (not (string=? (Spam-type-get (new-Spam "hello")) "char *"))
+      (error "Spam(char *)"))
+  (if (not (string=? (Spam-type-get (new-Spam b)) "Bar *"))
+      (error "Spam(Bar *)")))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/overload_subtype.scm b/trunk/Examples/test-suite/schemerunme/overload_subtype.scm
new file mode 100644
index 0000000..bcc9276
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/overload_subtype.scm
@@ -0,0 +1,7 @@
+(if (not (= (spam (new-Foo)) 1))
+    (error "foo"))
+
+(if (not (= (spam (new-Bar)) 2))
+    (error "bar"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/pointer_in_out.scm b/trunk/Examples/test-suite/schemerunme/pointer_in_out.scm
new file mode 100644
index 0000000..cabf6c1
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/pointer_in_out.scm
@@ -0,0 +1,13 @@
+(define-macro (check form)
+  `(if (not ,form)
+       (error "Check failed: " ',form)))
+
+(define p (produce-int-pointer 47 11))
+
+(check (= (consume-int-pointer p) 47))
+
+(define q (frobnicate-int-pointer p))
+
+(check (= (consume-int-pointer q) 11))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/reference_global_vars.scm b/trunk/Examples/test-suite/schemerunme/reference_global_vars.scm
new file mode 100644
index 0000000..4b3370c
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/reference_global_vars.scm
@@ -0,0 +1,59 @@
+(define (!= a b) (not (= a b)))
+
+; const class reference variable
+(if (!= (TestClass-num-get (getconstTC)) 33)
+  (begin (display "Runtime test 1 failed.\n") (exit 1)))
+
+; primitive reference variables
+(var-bool (createref-bool #f))
+(if (value-bool (var-bool))
+  (begin (display "Runtime test 2 failed.\n") (exit 1)))
+
+(var-char (createref-char #\w))
+(if (not (char=? (value-char (var-char)) #\w))
+  (begin (display "Runtime test 3 failed.\n") (exit 1)))
+
+(var-unsigned-char (createref-unsigned-char #\newline))
+(if (not (char=? (value-unsigned-char (var-unsigned-char)) #\newline))
+  (begin (display "Runtime test 4 failed.\n") (exit 1)))
+
+(var-signed-char (createref-signed-char #\newline))
+(if (not (char=? (value-signed-char (var-signed-char)) #\newline))
+  (begin (display "Runtime test 5 failed.\n") (exit 1)))
+
+(var-unsigned-short (createref-unsigned-short 10))
+(if (!= (value-unsigned-short (var-unsigned-short)) 10)
+  (begin (display "Runtime test 6 failed.\n") (exit 1)))
+
+(var-int (createref-int 10))
+(if (!= (value-int (var-int)) 10)
+  (begin (display "Runtime test 7 failed.\n") (exit 1)))
+
+(var-unsigned-int (createref-unsigned-int 10))
+(if (!= (value-unsigned-int (var-unsigned-int)) 10)
+  (begin (display "Runtime test 8 failed.\n") (exit 1)))
+
+(var-long (createref-long 10))
+(if (!= (value-long (var-long)) 10)
+  (begin (display "Runtime test 9 failed.\n") (exit 1)))
+
+(var-unsigned-long (createref-unsigned-long 10))
+(if (!= (value-unsigned-long (var-unsigned-long)) 10)
+  (begin (display "Runtime test 10 failed.\n") (exit 1)))
+
+;skip long long and unsigned long long
+
+(var-float (createref-float 10.5))
+(if (!= (value-float (var-float)) 10.5)
+  (begin (display "Runtime test 11 failed.\n") (exit 1)))
+
+(var-double (createref-double 10.55))
+(if (!= (value-double (var-double)) 10.55)
+  (begin (display "Runtime test 12 failed.\n") (exit 1)))
+
+;class reference
+(var-TestClass (createref-TestClass (new-TestClass 20)))
+(if (!= (TestClass-num-get (value-TestClass (var-TestClass))) 20)
+  (begin (display "Runtime test 13 failed.\n") (exit 1)))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/typedef_inherit.scm b/trunk/Examples/test-suite/schemerunme/typedef_inherit.scm
new file mode 100644
index 0000000..e1a8925
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/typedef_inherit.scm
@@ -0,0 +1,19 @@
+(define a (new-Foo))
+(define b (new-Bar))
+
+(if (not (string=? (do-blah a) "Foo::blah"))
+    (error "bad return"))
+
+(if (not (string=? (do-blah b) "Bar::blah"))
+    (error "bad return"))
+
+(define c (new-Spam))
+(define d (new-Grok))
+
+(if (not (string=? (do-blah2 c) "Spam::blah"))
+    (error "bad return"))
+
+(if (not (string=? (do-blah2 d) "Grok::blah"))
+    (error "bad return"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/typename.scm b/trunk/Examples/test-suite/schemerunme/typename.scm
new file mode 100644
index 0000000..1e897dd
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/typename.scm
@@ -0,0 +1,12 @@
+(define f (new-Foo))
+(define b (new-Bar))
+
+(define x (twoFoo f))
+;;(if (not (isinstance x (types-FloatType)))
+;;    (error "wrong return type"))
+
+(define y (twoBar b))
+;;(if (not (isinstance y (types-IntType)))
+;;    (error "wrong return type"))
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/unions.scm b/trunk/Examples/test-suite/schemerunme/unions.scm
new file mode 100644
index 0000000..0ab2cc7
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/unions.scm
@@ -0,0 +1,36 @@
+;;; This is the union runtime testcase. It ensures that values within a
+;;; union embedded within a struct can be set and read correctly.
+
+;; Create new instances of SmallStruct and BigStruct for later use
+(define small (new-SmallStruct))
+(SmallStruct-jill-set small 200)
+
+(define big (new-BigStruct))
+(BigStruct-smallstruct-set big small)
+(BigStruct-jack-set big 300)
+
+;; Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+;; Ensure values in EmbeddedUnionTest are set correctly for each.
+(define eut (new-EmbeddedUnionTest))
+
+;; First check the SmallStruct in EmbeddedUnionTest
+(EmbeddedUnionTest-number-set eut 1)
+(EmbeddedUnionTest-uni-small-set (EmbeddedUnionTest-uni-get eut)
+				 small)
+(let ((Jill1 (SmallStruct-jill-get
+	      (EmbeddedUnionTest-uni-small-get
+	       (EmbeddedUnionTest-uni-get eut)))))
+  (if (not (= Jill1 200))
+      (begin
+	(display "Runtime test 1 failed.")
+	(exit 1))))
+
+(let ((Num1 (EmbeddedUnionTest-number-get eut)))
+  (if (not (= Num1 1))
+      (begin
+	(display "Runtime test 2 failed.")
+	(exit 1))))
+
+;; that should do
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/schemerunme/unions_proxy.scm b/trunk/Examples/test-suite/schemerunme/unions_proxy.scm
new file mode 100644
index 0000000..43cb836
--- /dev/null
+++ b/trunk/Examples/test-suite/schemerunme/unions_proxy.scm
@@ -0,0 +1,37 @@
+;;; This is the union runtime testcase. It ensures that values within a
+;;; union embedded within a struct can be set and read correctly.
+
+;; Create new instances of SmallStruct and BigStruct for later use
+(define small (make <SmallStruct>))
+(slot-set! small 'jill 200)
+
+(define big (make <BigStruct>))
+(slot-set! big 'smallstruct small)
+(slot-set! big 'jack 300)
+
+;; Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+;; Ensure values in EmbeddedUnionTest are set correctly for each.
+(define eut (make <EmbeddedUnionTest>))
+
+;; First check the SmallStruct in EmbeddedUnionTest
+(slot-set! eut 'number 1)
+(slot-set! (slot-ref eut 'uni) 'small small)
+(let ((Jill1 (slot-ref
+	       (slot-ref 
+		  (slot-ref eut 'uni) 
+		  'small)
+	       'jill)))
+  (if (not (= Jill1 200))
+      (begin
+	(display "Runtime test 1 failed.")
+	(exit 1))))
+
+(let ((Num1 (slot-ref eut 'number)))
+  (if (not (= Num1 1))
+      (begin
+	(display "Runtime test 2 failed.")
+	(exit 1))))
+
+;; that should do
+
+(exit 0)
diff --git a/trunk/Examples/test-suite/shared_ptr_wrapper.h b/trunk/Examples/test-suite/shared_ptr_wrapper.h
new file mode 100644
index 0000000..ef7b261
--- /dev/null
+++ b/trunk/Examples/test-suite/shared_ptr_wrapper.h
@@ -0,0 +1,100 @@
+// defines SwigBoost::shared_ptr, a wrapper around boost::shared_ptr
+// Use this shared_ptr wrapper for testing memory leaks of shared_ptr.
+// getTotalCount() should return zero at end of test
+
+#include <iostream>
+
+struct SWIG_null_deleter; // forward reference, definition is in shared_ptr.i
+namespace SwigBoost {
+// This template can be specialized for better debugging information
+template <typename T> std::string show_message(boost::shared_ptr<T>*t) {
+  if (!t)
+    return "null shared_ptr!!!";
+  if (boost::get_deleter<SWIG_null_deleter>(*t))
+    return std::string(typeid(t).name()) + " NULL DELETER";
+  if (*t)
+    return std::string(typeid(t).name()) + " object";
+  else
+    return std::string(typeid(t).name()) + " NULL";
+}
+
+namespace SharedPtrWrapper {
+  static SwigExamples::CriticalSection critical_section;
+  static int total_count = 0;
+
+  template<typename T> void increment(boost::shared_ptr<T>* ptr) { 
+    SwigExamples::Lock lock(critical_section); 
+    std::cout << "====SharedPtrWrapper==== + " << ptr << " " << show_message(ptr) << " " <<  std::endl << std::flush;
+    total_count++;
+  }
+  template<typename T> void decrement(boost::shared_ptr<T>* ptr) {
+    SwigExamples::Lock lock(critical_section); 
+    std::cout << "====SharedPtrWrapper==== - " << ptr << " " << show_message(ptr) << " " <<  std::endl << std::flush;
+    total_count--;
+  }
+  static int getTotalCount() { return total_count; }
+}
+
+template<typename T> class shared_ptr {
+private:
+    typedef shared_ptr<T> this_type;
+public:
+    typedef typename boost::detail::shared_ptr_traits<T>::reference reference;
+
+  shared_ptr() : m_shared_ptr() {
+    SharedPtrWrapper::increment(&m_shared_ptr);
+  }
+  template<typename Y> explicit shared_ptr(Y* p) : m_shared_ptr(p) {
+    SharedPtrWrapper::increment(&m_shared_ptr);
+  }
+  template<typename Y, typename D> explicit shared_ptr(Y* p, D d) : m_shared_ptr(p, d) {
+    SharedPtrWrapper::increment(&m_shared_ptr);
+  }
+
+  shared_ptr(shared_ptr const & other)
+    : m_shared_ptr(other.m_shared_ptr)
+  {
+    SharedPtrWrapper::increment(&m_shared_ptr);
+  }
+
+  template<typename Y> shared_ptr(shared_ptr<Y> const & other)
+    : m_shared_ptr(other.m_shared_ptr)
+  {
+    SharedPtrWrapper::increment(&m_shared_ptr);
+  }
+
+  reference operator*() const {
+    return m_shared_ptr.operator*();
+  }
+  T* operator->() const {
+    return m_shared_ptr.operator->();
+  }
+  T* get() const { 
+    return m_shared_ptr.get();
+  }
+  operator bool() const {
+    return m_shared_ptr.get() == 0 ? false : true;
+  }
+  bool unique() const {
+    return m_shared_ptr.unique();
+  }
+  long use_count() const {
+    return m_shared_ptr.use_count();
+  }
+  void swap(shared_ptr<T>& other) {
+    std::swap(m_shared_ptr, other.m_shared_ptr);
+  }
+  template<class Y> bool _internal_less(shared_ptr<Y> const & rhs) const {
+    return m_shared_ptr < rhs.m_shared_ptr;
+  }
+  ~shared_ptr() {
+    SharedPtrWrapper::decrement(&m_shared_ptr);
+  }
+
+private:
+  template<class Y> friend class shared_ptr;
+
+  boost::shared_ptr<T> m_shared_ptr;
+};
+}
+
diff --git a/trunk/Examples/test-suite/sizeof_pointer.i b/trunk/Examples/test-suite/sizeof_pointer.i
new file mode 100644
index 0000000..993ba4d
--- /dev/null
+++ b/trunk/Examples/test-suite/sizeof_pointer.i
@@ -0,0 +1,19 @@
+/* 
+This testcase tests whether the sizeof operator on a pointer is working.
+*/
+
+%module sizeof_pointer
+
+%inline %{
+
+#define  NO_PROBLEM sizeof(char)
+#define  STAR_PROBLEM sizeof(char*)
+#define  STAR_STAR_PROBLEM sizeof(char**)
+
+typedef struct SizeofPointerTest {
+  unsigned char array1[NO_PROBLEM];
+  unsigned char array2[STAR_PROBLEM];
+  unsigned char array3[STAR_STAR_PROBLEM];
+} SizeofPointerTest;
+
+%}
diff --git a/trunk/Examples/test-suite/sizet.i b/trunk/Examples/test-suite/sizet.i
new file mode 100644
index 0000000..5379141
--- /dev/null
+++ b/trunk/Examples/test-suite/sizet.i
@@ -0,0 +1,52 @@
+%module sizet
+%{
+#include <vector>
+%}
+
+#ifndef SWIGCHICKEN
+%include "std_common.i"
+#endif
+
+%inline
+{
+  size_t test1(size_t s)
+  {
+    return s;
+  }
+
+  std::size_t test2(std::size_t s)
+  {
+    return s;
+  }
+
+  const std::size_t& test3(const std::size_t& s)
+  {
+    return s;
+  }
+
+  const size_t& test4(const size_t& s)
+  {
+    return s;
+  }
+
+}
+
+#ifdef SWIGPYTHON
+%include "std_vector.i"
+
+%template(vectors) std::vector<unsigned long>;
+  
+%inline 
+{
+  std::vector<std::size_t> testv1(std::vector<std::size_t> s)
+  {
+    return s;
+  }
+
+  const std::vector<std::size_t>& testv2(const std::vector<std::size_t>& s)
+  {
+    return s;
+  }
+
+}
+#endif
diff --git a/trunk/Examples/test-suite/smart_pointer_const.i b/trunk/Examples/test-suite/smart_pointer_const.i
new file mode 100644
index 0000000..3100a02
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_const.i
@@ -0,0 +1,19 @@
+%module smart_pointer_const
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() const { return x; }
+};
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   Foo *operator->() {
+      return f;
+   }
+};
+%}
+
+
diff --git a/trunk/Examples/test-suite/smart_pointer_const2.i b/trunk/Examples/test-suite/smart_pointer_const2.i
new file mode 100644
index 0000000..aa0d4ab
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_const2.i
@@ -0,0 +1,20 @@
+%module smart_pointer_const2
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() const { return x; }
+   int test() { return x; }
+};
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   const Foo *operator->() {
+      return f;
+   }
+};
+%}
+
+
diff --git a/trunk/Examples/test-suite/smart_pointer_extend.i b/trunk/Examples/test-suite/smart_pointer_extend.i
new file mode 100644
index 0000000..d972f67
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_extend.i
@@ -0,0 +1,132 @@
+%module smart_pointer_extend
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hi::CBase::z;	/* Ruby, wrong const name */
+
+%inline %{
+  namespace hi
+  {
+    struct CBase
+    {
+      static int hello() 
+      {
+	return 1;
+      }
+      int x;
+      static const int z = 1;
+    };
+
+    class CDerived : public CBase
+    {
+    };
+
+    class CPtr
+    {
+    public:
+      CDerived* operator->(void) {return 0;}
+    };
+
+    int get_hello(CPtr ptr)
+    {
+      return ptr->hello();
+    }
+
+    class CPtrConst
+    {
+    public:
+      const CDerived* operator->() const {return 0;};
+    };
+    
+  }
+  
+%}
+
+%extend hi::CBase {
+  int foo(void) {return 1;};
+  int bar(void) {return 2;};
+  int boo(int i) {return i;};
+}
+
+%extend hi::CDerived {
+  int foo(void) {return 1;};
+}
+
+
+
+%extend Foo
+{
+  int extension(int i, int j) { return i; }
+  int extension(int i) { return i; }
+  int extension() { return 1; }
+}
+
+%inline %{
+  struct Foo {
+  };
+  
+  class Bar {
+    Foo *f;
+  public:
+    Bar(Foo *f) : f(f) { }
+    Foo *operator->() {
+      return f;
+    }
+  };
+%}
+
+
+
+%extend CFoo
+{
+public:
+    static void StatFun() {};
+    static void StatFun(int i) {};
+
+    static void HoHoHo(int i, int j) {};
+}
+
+%inline %{
+
+class CFoo
+{
+};
+
+class CPtrFoo
+{
+public:
+    CFoo* operator->(void) {return 0;};
+};
+
+%}
+
+
+
+%inline %{
+  namespace foo {
+    
+    class DFoo;
+    
+    class DPtrFoo
+    {
+      DFoo *p;
+    public:
+      DPtrFoo(DFoo *ptr) : p(ptr)
+      {
+      }
+      
+      DFoo* operator->(void) {return p;};
+    };
+    
+    class DFoo
+    {
+    public:
+      void F(void) {};
+    };
+  }
+%}
+
+
+
+%extend foo::DFoo {
+  static int SExt(int i = 1) {return i;};
+  int Ext(int i = 2) {return i;};
+}
diff --git a/trunk/Examples/test-suite/smart_pointer_inherit.i b/trunk/Examples/test-suite/smart_pointer_inherit.i
new file mode 100644
index 0000000..a81d722
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_inherit.i
@@ -0,0 +1,76 @@
+%module smart_pointer_inherit
+
+#ifdef SWIGCSHARP
+// Test that the override is removed in the smart pointer for custom method modifiers
+%csmethodmodifiers hi::Derived::value3 "/*csmethodmodifiers*/ public override";
+#endif
+
+%inline %{
+
+  namespace hi
+  {    
+    struct Base 
+    {
+      Base(int i) : val(i) {}
+      virtual ~Base() { }
+      virtual int value() = 0;
+      virtual int value2() { return val; }
+      virtual int value3() { return val; }
+      int valuehide() { return val; }
+      int val;
+    };    
+    
+    struct Derived : Base 
+    {
+      Derived(int i) : Base(i) {}
+      virtual int value() { return val; }
+      virtual int value3() { return Base::value3(); }
+      int valuehide() { return -1; }
+    };
+
+    template <typename T> struct SmartPtr
+    {
+      SmartPtr(T *t) : ptr(t) {}
+      T * operator->() const { return ptr; }
+    private:
+      T *ptr;
+    };
+  }
+%}
+
+%template(SmartBase) hi::SmartPtr<hi::Base>;
+%template(SmartDerived) hi::SmartPtr<hi::Derived>;
+
+
+
+%include std_vector.i
+
+%inline %{
+class ItkLevelSetNodeUS2 {
+};
+%}
+
+#ifdef SWIGCSHARP
+// Get rid of C# compiler warnings.
+// Really the itkVectorContainerUILSNUS2_Pointer class should be manually modified to contain the same %extend methods that are in std_vector.i
+%csmethodmodifiers std::vector<ItkLevelSetNodeUS2>::getitemcopy "protected"
+%csmethodmodifiers std::vector<ItkLevelSetNodeUS2>::getitem "protected"
+%csmethodmodifiers std::vector<ItkLevelSetNodeUS2>::setitem "protected"
+%csmethodmodifiers std::vector<ItkLevelSetNodeUS2>::size "protected"
+%csmethodmodifiers std::vector<ItkLevelSetNodeUS2>::capacity "protected"
+%csmethodmodifiers std::vector<ItkLevelSetNodeUS2>::reserve "protected"
+#endif
+
+%template(VectorLevelSetNodeUS2) std::vector< ItkLevelSetNodeUS2 >;
+
+%inline %{
+class ItkVectorContainerUILSNUS2 : public std::vector< ItkLevelSetNodeUS2 > {
+};
+
+class ItkVectorContainerUILSNUS2_Pointer {
+  public:
+    ItkVectorContainerUILSNUS2 * operator->() const { return 0; }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/smart_pointer_member.i b/trunk/Examples/test-suite/smart_pointer_member.i
new file mode 100644
index 0000000..7a77626
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_member.i
@@ -0,0 +1,56 @@
+%module smart_pointer_member
+
+
+
+%inline %{
+
+  class Foo {
+  public:
+    int x[4];
+    int y;
+    static const int z;
+    static const int ZZ = 3;
+    static int zx;
+
+    static int boo() { return 0;}
+
+    friend int foo(Foo* foo) { return 0;}
+  };
+  
+  class Bar {
+    Foo *f;
+  public:
+    Bar(Foo *f) : f(f) { }
+    Foo *operator->() {
+      return f;
+    }
+
+    static int bua() { return 0;}
+  };
+
+  class CBar {
+    Foo *f;
+  public:
+    CBar(Foo *f) : f(f) { }
+    const Foo *operator->()  {
+      return f;
+    }
+  };
+
+  
+  int get_y(Bar *b) 
+  {
+    return (*b)->y;
+  }
+  
+  int get_z(Bar *b) 
+  {
+    return (*b)->z;
+  }
+%}
+
+
+%{
+  const int Foo::z = 3;
+  int Foo::zx;
+%}
diff --git a/trunk/Examples/test-suite/smart_pointer_multi.i b/trunk/Examples/test-suite/smart_pointer_multi.i
new file mode 100644
index 0000000..4b0aa0e
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_multi.i
@@ -0,0 +1,39 @@
+// Test cases for classes that do *NOT* result in smart-pointer wrapping
+%module smart_pointer_multi
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() { return x; }
+};
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   Foo *operator->() {
+      return f;
+   }
+};
+
+class Spam {
+   Bar *b;
+public:
+   Spam(Bar *b) : b(b) { }
+   Bar operator->() {
+      return *b;
+   }
+};
+
+class Grok {
+   Bar *b;
+public:
+   Grok(Bar *b) : b(b) { }
+   Bar &operator->() {
+      return *b;
+   }
+};
+   
+%}
+
+
diff --git a/trunk/Examples/test-suite/smart_pointer_multi_typedef.i b/trunk/Examples/test-suite/smart_pointer_multi_typedef.i
new file mode 100644
index 0000000..ed32b70
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_multi_typedef.i
@@ -0,0 +1,45 @@
+// Test cases for classes that do *NOT* result in smart-pointer wrapping
+%module smart_pointer_multi_typedef
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() { return x; }
+};
+
+typedef Foo FooObj;
+typedef FooObj *FooPtr;
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   FooPtr operator->() {
+      return f;
+   }
+};
+
+typedef Bar BarObj;
+typedef Bar &BarRef;
+
+class Spam {
+   Bar *b;
+public:
+   Spam(Bar *b) : b(b) { }
+   BarObj operator->() {
+      return *b;
+   }
+};
+
+class Grok {
+   Bar *b;
+public:
+   Grok(Bar *b) : b(b) { }
+   BarRef operator->() {
+      return *b;
+   }
+};
+   
+%}
+
+
diff --git a/trunk/Examples/test-suite/smart_pointer_namespace.i b/trunk/Examples/test-suite/smart_pointer_namespace.i
new file mode 100644
index 0000000..651da5c
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_namespace.i
@@ -0,0 +1,78 @@
+
+%module smart_pointer_namespace
+%{
+namespace one
+{
+    template <typename T>
+    class Ptr
+    {
+        T* p;
+    public:
+        Ptr(T *tp) : p(tp) {}
+        ~Ptr() { };
+        T* operator->() { return p; }
+    };
+}
+namespace one
+{
+    class Obj1
+    {
+    public:
+        Obj1() {}
+        void donothing() {}
+    };
+    typedef one::Ptr<Obj1> Obj1_ptr;
+}
+
+namespace two
+{
+    class Obj2
+    {
+    public:
+        Obj2() {}
+        void donothing() {}
+    };
+    typedef one::Ptr<Obj2> Obj2_ptr;
+}
+%}
+
+namespace one
+{
+    template <typename T>
+    class Ptr
+    {
+        T* p;
+    public:
+        Ptr(T *tp) : p(tp) {}
+        ~Ptr() { };
+        T* operator->() { return p; }
+    };
+}
+
+namespace one
+{
+    class Obj1
+    {
+    public:
+        Obj1() {}
+        void donothing() {}
+    };
+
+    typedef one::Ptr<Obj1> Obj1;
+}
+
+%template(Obj1_ptr) one::Ptr<one::Obj1>;
+
+namespace two
+{
+    class Obj2
+    {
+    public:
+        Obj2() {}
+        void donothing() {}
+    };
+    typedef one::Ptr<Obj2> Obj2;
+}
+
+%template(Obj2_ptr) one::Ptr<two::Obj2>;
+
diff --git a/trunk/Examples/test-suite/smart_pointer_namespace2.i b/trunk/Examples/test-suite/smart_pointer_namespace2.i
new file mode 100644
index 0000000..8827998
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_namespace2.i
@@ -0,0 +1,80 @@
+
+%module smart_pointer_namespace2
+%{
+namespace one
+{
+    template <typename T>
+    class Ptr
+    {
+        T* p;
+    public:
+        Ptr(T *tp) : p(tp) {}
+        ~Ptr() { };
+        T* operator->() { return p; }
+    };
+}
+namespace one
+{
+    class Obj1
+    {
+    public:
+        Obj1() {}
+        void donothing() {}
+    };
+    typedef one::Ptr<Obj1> Obj1_ptr;
+}
+
+namespace two
+{
+    class Obj2
+    {
+    public:
+        Obj2() {}
+        void donothing() {}
+    };
+    typedef one::Ptr<Obj2> Obj2_ptr;
+}
+%}
+
+namespace one
+{
+    template <typename T>
+    class Ptr
+    {
+        T* p;
+    public:
+        Ptr(T *tp) : p(tp) {}
+        ~Ptr() { };
+        T* operator->() { return p; }
+    };
+}
+
+%define PTR_DEF(o)
+typedef one::Ptr<o> o ## _ptr;
+%template(o ## _ptr) one::Ptr<o>;
+%enddef
+
+namespace one
+{
+    class Obj1
+    {
+    public:
+        Obj1() {}
+        void donothing() {}
+    };
+
+    PTR_DEF(Obj1)
+}
+
+namespace two
+{
+    class Obj2
+    {
+    public:
+        Obj2() {}
+        void donothing() {}
+    };
+
+    PTR_DEF(Obj2)
+}
+
diff --git a/trunk/Examples/test-suite/smart_pointer_not.i b/trunk/Examples/test-suite/smart_pointer_not.i
new file mode 100644
index 0000000..712aa48
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_not.i
@@ -0,0 +1,39 @@
+// Test cases for classes that do *NOT* result in smart-pointer wrapping
+%module smart_pointer_not
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() { return x; }
+};
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   Foo operator->() {
+      return *f;
+   }
+};
+
+class Spam {
+   Foo *f;
+public:
+   Spam(Foo *f) : f(f) { }
+   Foo &operator->() {
+      return *f;
+   }
+};
+
+class Grok {
+   Foo *f;
+public:
+   Grok(Foo *f) : f(f) { }
+   Foo **operator->() {
+      return &f;
+   }
+};
+   
+%}
+
+
diff --git a/trunk/Examples/test-suite/smart_pointer_overload.i b/trunk/Examples/test-suite/smart_pointer_overload.i
new file mode 100644
index 0000000..0d2cc59
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_overload.i
@@ -0,0 +1,28 @@
+%module smart_pointer_overload
+
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) test;
+#endif
+
+#ifndef SWIG_NO_OVERLOAD
+
+%inline %{
+struct Foo {
+   int x;
+   int test(int y) { y = 0; return 1; }
+   int test(double y) { y = 0; return 2; }
+   int test(char *s) { s = 0; return 3; }
+};
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   Foo *operator->() {
+      return f;
+   }
+};
+%}
+
+#endif
+
diff --git a/trunk/Examples/test-suite/smart_pointer_protected.i b/trunk/Examples/test-suite/smart_pointer_protected.i
new file mode 100644
index 0000000..c9b2a76
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_protected.i
@@ -0,0 +1,33 @@
+%module smart_pointer_protected
+
+%inline %{
+
+  namespace hi
+  {    
+    struct A 
+    {
+      virtual ~A() { }
+      virtual int value(A*) = 0;
+      int index;
+    };    
+    
+    struct B : A 
+    {
+    protected:
+      int value(A*)
+      {
+	return 1;
+      }
+    };
+
+    struct C
+    {
+      hi::B* operator->() const { return new hi::B(); }
+    private:
+      int index;
+    };
+  }
+  
+
+%}
+
diff --git a/trunk/Examples/test-suite/smart_pointer_rename.i b/trunk/Examples/test-suite/smart_pointer_rename.i
new file mode 100644
index 0000000..b137ffe
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_rename.i
@@ -0,0 +1,25 @@
+%module smart_pointer_rename
+
+%rename(ftest1) Foo::test(int);
+%rename(ftest2) Foo::test(int,int);
+
+%inline %{
+
+class Foo {
+public:
+    int   test(int) { return 1; }
+    int   test(int,int) { return 2; }
+};
+
+class Bar {
+    Foo *f;
+public:
+    Bar(Foo *_f) : f(_f) { }
+    Foo *operator->() { return f; }
+    int  test() { return 3; }
+};
+
+%}
+
+	
+
diff --git a/trunk/Examples/test-suite/smart_pointer_simple.i b/trunk/Examples/test-suite/smart_pointer_simple.i
new file mode 100644
index 0000000..ceb499c
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_simple.i
@@ -0,0 +1,19 @@
+%module smart_pointer_simple
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() { return x; }
+};
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   Foo *operator->() {
+      return f;
+   }
+};
+%}
+
+
diff --git a/trunk/Examples/test-suite/smart_pointer_static.i b/trunk/Examples/test-suite/smart_pointer_static.i
new file mode 100644
index 0000000..a9574f7
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_static.i
@@ -0,0 +1,24 @@
+%module smart_pointer_static
+%inline %{
+class Foo2;
+
+class  MyHandle_Foo2 { 
+ public: 
+  Foo2 * operator -> (); 
+}; 
+
+class Foo2 { 
+ public: 
+  virtual ~Foo2() {}
+  virtual int sum(int i, int j) { return i+j; }
+  static int sum(int i, int j, int k); 
+}; 
+
+%}
+
+%{
+int Foo2::sum(int i, int j, int k) {
+  return i+j+k;
+}
+Foo2 * MyHandle_Foo2::operator -> () { return new Foo2(); }
+%}
diff --git a/trunk/Examples/test-suite/smart_pointer_templatemethods.i b/trunk/Examples/test-suite/smart_pointer_templatemethods.i
new file mode 100644
index 0000000..7baa638
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_templatemethods.i
@@ -0,0 +1,52 @@
+
+%module smart_pointer_templatemethods
+
+%inline %{
+namespace ns {
+ 
+template <typename T>
+class Ptr
+{
+public:
+  Ptr () {}
+  T *operator -> () { return 0; }
+};
+ 
+typedef unsigned short uint16_t;
+class InterfaceId
+{
+public:
+  InterfaceId (uint16_t iid) {}
+  InterfaceId() {}
+};
+ 
+template <typename K> class Objekt
+{
+public:
+  Objekt () {}
+  virtual ~Objekt () {}
+  Ptr<K> QueryInterface (InterfaceId iid) const { return Ptr<K>(); }
+  void DisposeObjekt (void) {}
+};
+
+class Object
+{
+public:
+  Object () {}
+  virtual ~Object () {}
+  template <typename T> Ptr<T> QueryInterface (InterfaceId iid) const { return Ptr<T>(); }
+  void DisposeObject (void) {}
+};
+ 
+#ifdef SWIG
+%template(PtrObject) Ptr<Object>;
+%template(PtrInt) Ptr<int>;
+%template(ObjektInt) Objekt<int>;
+%template(PtrObjektInt) Ptr<Objekt<int> >;
+%template(QueryInterfaceObject) Object::QueryInterface<Object>;
+#endif
+
+}; // namespace
+ 
+%}
+
diff --git a/trunk/Examples/test-suite/smart_pointer_templatevariables.i b/trunk/Examples/test-suite/smart_pointer_templatevariables.i
new file mode 100644
index 0000000..fd705eb
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_templatevariables.i
@@ -0,0 +1,39 @@
+%module smart_pointer_templatevariables
+
+%inline %{
+template <class _CharT>
+struct basic_string {
+    int npos;
+};
+
+template<class T>
+struct Ptr {
+    Ptr(T *p = 0) : ptr(p) {}
+    ~Ptr() { delete ptr; }
+    T *operator->() const { return ptr; }
+private:
+    T *ptr;
+};
+
+template <typename KernelPixelT>
+struct DiffImContainer {
+    int id;
+// static members seem to be can of worms. Note that SWIG wraps them as non-static members. Why?
+// Note CHANGES entry 10/14/2003. Static const variables are not wrapped as constants but as a read only variable. Why?
+//    static short xyz;
+//    static const short constvar = 555;
+};
+//template<typename KernelPixelT> short DiffImContainer<KernelPixelT>::xyz = 0;
+
+DiffImContainer<double>* create(int id, short xyz) { 
+  DiffImContainer<double> *d = new DiffImContainer<double>();
+  d->id = id;
+//  DiffImContainer<double>::xyz = xyz;
+  return d;
+}
+%}
+
+%template(BasicString)                     basic_string<char>;
+%template(DiffImContainer_D)               DiffImContainer<double>;
+%template(DiffImContainerPtr_D)            Ptr<DiffImContainer<double> >;
+
diff --git a/trunk/Examples/test-suite/smart_pointer_typedef.i b/trunk/Examples/test-suite/smart_pointer_typedef.i
new file mode 100644
index 0000000..d4e874f
--- /dev/null
+++ b/trunk/Examples/test-suite/smart_pointer_typedef.i
@@ -0,0 +1,21 @@
+%module smart_pointer_typedef
+
+%inline %{
+struct Foo {
+   int x;
+   int getx() { return x; }
+};
+
+typedef Foo *FooPtr;
+
+class Bar {
+   Foo *f;
+public:
+   Bar(Foo *f) : f(f) { }
+   FooPtr operator->() {
+      return f;
+   }
+};
+%}
+
+
diff --git a/trunk/Examples/test-suite/sneaky1.i b/trunk/Examples/test-suite/sneaky1.i
new file mode 100644
index 0000000..2d915e1
--- /dev/null
+++ b/trunk/Examples/test-suite/sneaky1.i
@@ -0,0 +1,29 @@
+%module sneaky1
+
+%{
+int add(int x, int y) {
+   return x+y;
+}
+
+int subtract(int x, int y) {
+   return x-y;
+}
+int mul(int x, int y) {
+   return x*y;
+}
+
+int divide(int x, int y) {
+   return x/y;
+}
+%}
+
+%inline %{
+typedef int binop(int,int);
+%}
+
+binop add,subtract,mul,divide;
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/special_variables.i b/trunk/Examples/test-suite/special_variables.i
new file mode 100644
index 0000000..e8853ce
--- /dev/null
+++ b/trunk/Examples/test-suite/special_variables.i
@@ -0,0 +1,90 @@
+%module special_variables
+
+%include <std_string.i>
+
+// will fail to compile if $symname is not expanded
+%typemap(argout) int i {
+  $symname(99);
+}
+
+%{
+#define KKK_testmethod testmethod
+#define KKK_teststaticmethod KKK::teststaticmethod
+%}
+
+%inline %{
+void testmethod(int i) {}
+struct KKK {
+  void testmethod(int i) {}
+  static void teststaticmethod(int i) {}
+};
+%}
+
+%{
+std::string ExceptionVars(double i, double j) {
+  return "a1";
+}
+%}
+
+%rename(ExceptionVars) Space::exceptionvars;
+%exception Space::exceptionvars %{
+  $action
+  result = $symname(1.0,2.0); // Should expand to ExceptionVars
+  result = $name(3.0,4.0); // Should expand to Space::exceptionvars
+  // above will not compile if the variables are not expanded properly
+  result = "$action  $name  $symname  $overname $wrapname";
+%}
+%inline %{
+namespace Space {
+std::string exceptionvars(double i, double j) {
+  return "b2";
+}
+}
+%}
+
+
+%exception Space::overloadedmethod %{
+  $action
+  result = Space::$symname(1.0);
+  result = $name();
+  result = $name(2.0);
+  // above will not compile if the variables are not expanded properly
+  result = "$action  $name  $symname  $overname $wrapname";
+  // $decl
+%}
+
+%inline %{
+namespace Space {
+  std::string overloadedmethod(double j) {
+    return "c3";
+  }
+  std::string overloadedmethod() {
+    return "d4";
+  }
+}
+std::string declaration;
+%}
+
+%exception {
+  $action
+  declaration = "$fulldecl $decl";
+}
+
+%inline %{
+namespace SpaceNamespace {
+  struct ABC {
+    ABC(int a, double b) {}
+    ABC() {}
+    static short * staticmethod(int x, bool b) { return 0; }
+    short * instancemethod(int x, bool b = false) { return 0; }
+    short * constmethod(int x) const { return 0; }
+  };
+  template<typename T> struct Template {
+    std::string tmethod(T t) { return ""; }
+  };
+  void globtemplate(Template<ABC> t) {}
+}
+%}
+
+%template(TemplateABC) SpaceNamespace::Template<SpaceNamespace::ABC>;
+
diff --git a/trunk/Examples/test-suite/static_array_member.i b/trunk/Examples/test-suite/static_array_member.i
new file mode 100644
index 0000000..3bd8cf9
--- /dev/null
+++ b/trunk/Examples/test-suite/static_array_member.i
@@ -0,0 +1,12 @@
+/* This interface file checks whether the SWIG parser handles static
+   array members of classes.  Bug reported by Annalisa Terracina
+   <annalisa.terracina@datamat.it> on 2001-07-03. 
+*/
+
+%module static_array_member
+
+%inline %{
+class RB {
+  static char *rberror[];
+};
+%}
diff --git a/trunk/Examples/test-suite/static_const_member.i b/trunk/Examples/test-suite/static_const_member.i
new file mode 100644
index 0000000..99dc89b
--- /dev/null
+++ b/trunk/Examples/test-suite/static_const_member.i
@@ -0,0 +1,17 @@
+/* Swig 1.3.6 does not understand initialization of static class
+   constants like this.  SF Bug #445221, reported by Krzysztof
+   Kozminski <kozminski@users.sf.net>. 
+*/
+
+%module static_const_member
+
+%inline %{
+  
+class X {
+public:
+  static const int PN = 0;
+  static const int CN = 1;
+  static const int EN = 2;
+};
+
+%}
diff --git a/trunk/Examples/test-suite/static_const_member_2.i b/trunk/Examples/test-suite/static_const_member_2.i
new file mode 100644
index 0000000..0b6d38d
--- /dev/null
+++ b/trunk/Examples/test-suite/static_const_member_2.i
@@ -0,0 +1,76 @@
+%module static_const_member_2
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::modules::CavityPackFlags::forward_field;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::modules::CavityPackFlags::backward_field;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::modules::Test::current_profile;
+
+%inline %{ 
+ namespace oss 
+ {   
+   namespace modules
+   {
+     struct CavityPackFlags 
+     {
+       typedef unsigned int viewflags;
+       static const viewflags forward_field  = 1 << 0;
+       static const viewflags backward_field = 1 << 1;
+       static const viewflags cavity_flags;
+       static viewflags flags;
+       static const int &reftest;
+     };     
+
+     template <class T>
+     struct Test : CavityPackFlags
+     {
+       enum {LeftIndex, RightIndex};
+       static const viewflags current_profile  = 1 << 2;
+     };
+   }
+ }
+
+%} 
+
+%{
+
+int refvalue = 42;
+const int &oss::modules::CavityPackFlags::reftest = refvalue;
+
+%}
+
+%{
+  using oss::modules::CavityPackFlags;
+  
+  const CavityPackFlags::viewflags 
+    CavityPackFlags::cavity_flags = 
+    CavityPackFlags::forward_field | CavityPackFlags::backward_field;
+
+  CavityPackFlags::viewflags 
+    CavityPackFlags::flags = 0;
+
+%}
+
+%template(Test_int) oss::modules::Test<int>;
+
+
+
+
+%inline %{
+
+class Foo
+{
+public:
+  int val;
+  
+  Foo(int v) : val(v)
+  {
+  }
+  
+  static const Foo BAR;
+  static const Foo BAZ;
+};
+
+%}
+%{
+  const Foo Foo::BAR = Foo(1);
+  const Foo Foo::BAZ = Foo(2);
+%}
diff --git a/trunk/Examples/test-suite/std_containers.i b/trunk/Examples/test-suite/std_containers.i
new file mode 100644
index 0000000..0955226
--- /dev/null
+++ b/trunk/Examples/test-suite/std_containers.i
@@ -0,0 +1,207 @@
+%module std_containers
+
+//
+// STL containers test suite. 
+// Tests:
+//   std::complex, std::string, std::vector, std::set, std::deque,
+//   std::pair, std::map, std::multiset, std::multimap and IN/OUT functions
+//   for them, with C++ types.
+//
+
+%{
+#include <set>
+%}
+%include std_vector.i
+%include std_string.i
+%include std_deque.i
+%include std_list.i
+%include std_set.i
+%include std_multiset.i
+%include std_pair.i
+%include std_map.i
+%include std_multimap.i
+%include std_complex.i
+
+%template() std::vector<double>;
+%template() std::pair<std::string, int>;
+%template() std::pair<int,double>;
+
+%template() std::vector< std::vector<double > > ;
+%template(ccube) std::vector< std::vector< std::vector<double > > >;
+
+%inline 
+{ 
+  typedef
+    std::vector<std::vector<std::vector<double > > >
+    ccube;
+ 
+  ccube cident(const ccube& c)
+  {
+    return c;
+  }
+
+  struct C
+  {
+  };
+}
+
+
+%template(map_si)  std::map<std::string, int>;
+%template(pair_iC)  std::pair<int, C*>;
+%template(map_iC)  std::map<int, C*>;
+%template(mmap_si)  std::multimap<std::string, int>;
+%template(set_i) std::set<int>;
+%template(multiset_i) std::multiset<int>;
+%template(list_i) std::list<int>;
+%template(deque_i) std::deque<int>;
+
+%template(vector_b) std::vector<bool>;
+%template(vector_i) std::vector<int>;
+%template(vector_c) std::vector<std::complex<double> >;
+%template(vector_ui) std::vector<unsigned int>;
+
+%template(bmatrix) std::vector<std::vector<bool> >;
+%template(imatrix) std::vector<std::vector<int> >;
+%template(cmatrix) std::vector<std::vector<std::complex<double> > >;
+
+%apply std::vector<int> *INOUT {std::vector<int> *INOUT2};
+
+%inline 
+{
+  typedef std::vector<std::vector<int> >  imatrix;
+  imatrix midenti(const imatrix& v)
+  {
+    return v;
+  }
+
+  typedef std::vector<std::vector<bool> >  bmatrix;
+  bmatrix midentb(const bmatrix& v)
+  {
+    return v;
+  }
+
+  std::map<int,C*> mapidentc(const std::map<int,C*>& v)
+  {
+    return v;
+  }
+
+  std::map<int,int> mapidenti(const std::map<int,int>& v)
+  {
+    return v;
+  }
+
+  std::map<std::string,int> mapident(const std::map<std::string,int>& v)
+  {
+    return v;
+  }
+
+  std::multimap<std::string,int> mapident(const std::multimap<std::string,int>& v)
+  {
+    return v;
+  }
+
+  std::vector<int> vident(const std::vector<int>& v)
+  {
+    return v;
+  }
+
+  std::set<int> sident(const std::set<int>& v)
+  {
+    return v;
+  }
+
+  std::vector<unsigned int> videntu(const std::vector<unsigned int>& v)
+  {
+    return v;
+  }
+
+
+  int get_elem(const std::vector<int>& v, int index)
+  {
+    return v[index];
+  }
+
+  std::pair<int,double> pident(const std::pair<int,double>& p) 
+  {
+    return p;
+  }
+
+  void
+  v_inout(std::vector<int> *INOUT) {
+    *INOUT = *INOUT;
+  }  
+
+  void
+  v_inout2(std::vector<int> *INOUT, std::vector<int> *INOUT2) {
+    std::swap(*INOUT, *INOUT2);
+  } 
+
+}
+
+
+%{
+  
+  template <class C> struct Param 
+  {
+  };	    
+%}
+
+
+template <class C> struct Param 
+{
+};
+
+
+%template(Param_c) Param<std::complex<double> >;
+%inline 
+{
+  int hello(Param<std::complex<double> > c)
+  {
+    return 0;
+  }
+}
+
+%inline 
+{
+  struct A 
+  {
+    A(int aa = 0) : a(aa)
+    {
+    }
+    int a;
+  };  
+}
+
+%template() std::pair<A,int>;
+%template(pair_iA) std::pair<int,A>;
+%template(vector_piA) std::vector<std::pair<int,A> >;
+
+
+%inline {
+  std::pair<A,int> ident(std::pair<int,A> a, const std::pair<int,int>& b)
+  {
+    return std::pair<A,int>();
+  }  
+
+
+  std::vector<std::pair<int,A> > pia_vident(std::vector<std::pair<int,A> > a )
+  {
+    return a;
+  }  
+
+  struct Foo
+  {
+    Foo(int i) {
+    }
+  };
+  
+}
+
+
+%std_nodefconst_type(Foo);
+
+%template(vector_Foo) std::vector<Foo>;
+%template(deque_Foo) std::deque<Foo>;
+%template(list_Foo) std::list<Foo>;
+
+
diff --git a/trunk/Examples/test-suite/struct_rename.i b/trunk/Examples/test-suite/struct_rename.i
new file mode 100644
index 0000000..7acd706
--- /dev/null
+++ b/trunk/Examples/test-suite/struct_rename.i
@@ -0,0 +1,11 @@
+%module struct_rename
+
+%rename(Bar) Foo;
+
+%inline %{
+typedef struct {
+    int x;
+} Foo;
+
+%}
+
diff --git a/trunk/Examples/test-suite/struct_value.i b/trunk/Examples/test-suite/struct_value.i
new file mode 100644
index 0000000..bf944e2
--- /dev/null
+++ b/trunk/Examples/test-suite/struct_value.i
@@ -0,0 +1,14 @@
+%module struct_value
+
+%inline %{
+
+struct Foo {
+   int x;
+};
+
+struct Bar {
+   Foo   a;
+   struct Foo b;
+};
+
+%}
diff --git a/trunk/Examples/test-suite/swig_examples_lock.h b/trunk/Examples/test-suite/swig_examples_lock.h
new file mode 100644
index 0000000..7710f93
--- /dev/null
+++ b/trunk/Examples/test-suite/swig_examples_lock.h
@@ -0,0 +1,61 @@
+
+namespace SwigExamples {
+
+# if defined(_WIN32) || defined(__WIN32__)
+
+#include <windows.h>
+
+class CriticalSection {
+public:
+  CriticalSection() {
+    InitializeCriticalSection(&mutex_);
+  }
+  ~CriticalSection() {
+    DeleteCriticalSection(&mutex_);
+  }
+  CRITICAL_SECTION mutex_;
+};
+
+struct Lock {
+  Lock(CriticalSection &cs) : critical_section(cs) {
+    EnterCriticalSection(&critical_section.mutex_);
+  }
+  ~Lock() {
+    LeaveCriticalSection(&critical_section.mutex_);
+  }
+private:
+  CriticalSection &critical_section;
+};
+
+#else
+
+#include <pthread.h>
+class CriticalSection {
+public:
+  CriticalSection() {
+    pthread_mutexattr_t mutexattr;
+    pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
+    pthread_mutex_init(&mutex_, &mutexattr);
+    pthread_mutexattr_destroy(&mutexattr);
+  }
+  ~CriticalSection() {
+    pthread_mutex_destroy (&mutex_);
+  }
+  pthread_mutex_t mutex_;
+};
+
+struct Lock {
+  Lock(CriticalSection &cs) : critical_section(cs) {
+    pthread_mutex_lock (&critical_section.mutex_);
+  }
+  ~Lock() {
+    pthread_mutex_unlock (&critical_section.mutex_);
+  }
+private:
+  CriticalSection &critical_section;
+};
+
+#endif
+
+}
+
diff --git a/trunk/Examples/test-suite/sym.i b/trunk/Examples/test-suite/sym.i
new file mode 100644
index 0000000..83226cb
--- /dev/null
+++ b/trunk/Examples/test-suite/sym.i
@@ -0,0 +1,24 @@
+%module sym
+// make sure different classes are allowed to have methods of the same name 
+// that we properly qualify wrappers in the C namespace to avoid collisions
+
+%rename(hulahoops) Flim::Jam();
+
+%inline %{
+
+class Flim {
+public:
+   Flim() { }
+   const char * Jam() { return "flim-jam"; }
+   const char * Jar() { return "flim-jar"; }
+};
+
+class Flam {
+public:
+   Flam() { }
+   const char * Jam() { return "flam-jam"; }
+   const char * Jar() { return "flam-jar"; }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/tag_no_clash_with_variable.i b/trunk/Examples/test-suite/tag_no_clash_with_variable.i
new file mode 100644
index 0000000..5d63423
--- /dev/null
+++ b/trunk/Examples/test-suite/tag_no_clash_with_variable.i
@@ -0,0 +1,33 @@
+/* This is a test case for -*- C -*- mode. */
+%module tag_no_clash_with_variable
+
+%inline %{
+
+/* error_action is only a tag, not a type... */
+enum error_action {
+    ERRACT_ABORT,
+    ERRACT_EXIT, 
+    ERRACT_THROW
+};
+
+/* ... thus it does not clash with a variable of the same name. */ 
+enum error_action error_action;
+
+/* Likewise for structs: */
+
+struct buffalo { 
+  int foo;
+};
+
+struct buffalo buffalo; 
+
+/* And for union */
+
+union onion {
+  int cheese;
+};
+
+union onion onion;
+ 
+%}
+
diff --git a/trunk/Examples/test-suite/tcl/Makefile.in b/trunk/Examples/test-suite/tcl/Makefile.in
new file mode 100644
index 0000000..e26d775
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/Makefile.in
@@ -0,0 +1,57 @@
+#######################################################################
+# Makefile for tcl test-suite
+#######################################################################
+
+LANGUAGE     = tcl
+TCLSH        = tclsh
+SCRIPTSUFFIX = _runme.tcl 
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+CPP_TEST_CASES += \
+	primitive_types \
+	li_cdata \
+	li_cstring \
+	li_cwstring
+
+C_TEST_CASES += \
+	li_cdata \
+	li_cstring \
+	li_cwstring \
+	union
+
+include $(srcdir)/../common.mk
+
+# Overridden variables here
+# none!
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.tcl appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(TCLSH) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile tcl_clean
diff --git a/trunk/Examples/test-suite/tcl/README b/trunk/Examples/test-suite/tcl/README
new file mode 100644
index 0000000..c36c3aa
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/README
@@ -0,0 +1,4 @@
+See ../README for common README file.
+
+Any testcases which have _runme.tcl appended after the testcase name will be detected and run.
+
diff --git a/trunk/Examples/test-suite/tcl/bools_runme.tcl b/trunk/Examples/test-suite/tcl/bools_runme.tcl
new file mode 100644
index 0000000..582b812
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/bools_runme.tcl
@@ -0,0 +1,73 @@
+
+if [ catch { load ./bools[info sharedlibextension] bools} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+# bool constant check
+if {$constbool != 0} {
+    puts stderr "Runtime test 1 failed"
+    exit 1
+}
+
+# bool variables check
+if {$bool1 != 1} {
+    puts stderr "Runtime test 2 failed"
+    exit 1
+}
+
+if {$bool2 != 0} {
+    puts stderr "Runtime test 3 failed"
+    exit 1
+}
+
+if { [ value $pbool ] != $bool1} {
+    puts stderr "Runtime test 4 failed"
+    exit 1
+}
+
+if { [ value $rbool ] != $bool2} {
+    puts stderr "Runtime test 5 failed"
+    exit 1
+}
+
+if { [ value $const_pbool ] != $bool1} {
+    puts stderr "Runtime test 6 failed"
+    exit 1
+}
+
+if { $const_rbool != $bool2} {
+    puts stderr "Runtime test 7 failed"
+    exit 1
+}
+
+# bool functions check
+if { [ bo 0 ] != 0} {
+    puts stderr "Runtime test 8 failed"
+    exit 1
+}
+
+if { [ bo 1 ] != 1} {
+    puts stderr "Runtime test 9 failed"
+    exit 1
+}
+
+if { [ value  [ rbo $rbool ] ] !=  [ value $rbool ]} {
+    puts stderr "Runtime test 10 failed"
+    exit 1
+}
+
+if { [ value  [ pbo $pbool ] ] !=  [ value $pbool ]} {
+    puts stderr "Runtime test 11 failed"
+    exit 1
+}
+
+if { [ const_rbo $const_rbool ] !=   $const_rbool } {
+    puts stderr "Runtime test 12 failed"
+    exit 1
+}
+
+if { [ value  [ const_pbo $const_pbool ] ] !=  [ value $const_pbool ]} {
+    puts stderr "Runtime test 13 failed"
+    exit 1
+}
+
diff --git a/trunk/Examples/test-suite/tcl/clientdata_prop_runme.tcl b/trunk/Examples/test-suite/tcl/clientdata_prop_runme.tcl
new file mode 100644
index 0000000..2ac993f
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/clientdata_prop_runme.tcl
@@ -0,0 +1,88 @@
+
+if [ catch { load ./clientdata_prop_b[info sharedlibextension] clientdata_prop_b} err_msg ] {
+  puts stderr "Could not load shared object:\n$err_msg"
+  exit 1
+}
+if [ catch { load ./clientdata_prop_a[info sharedlibextension] clientdata_prop_a} err_msg ] {
+  puts stderr "Could not load shared object:\n$err_msg"
+  exit 1
+}
+
+A a
+test_A a
+test_tA a
+test_t2A a
+test_t3A a
+a fA
+
+B b
+test_A b
+test_tA b
+test_t2A b
+test_t3A b
+test_B b
+b fA
+b fB
+
+C c
+test_A c
+test_tA c
+test_t2A c
+test_t3A c
+test_C c
+c fA
+c fC
+
+D d
+test_A d
+test_tA d
+test_t2A d
+test_t3A d
+test_D d
+test_tD d
+test_t2D d
+d fA
+d fD
+
+set a2 [new_tA]
+test_A $a2
+test_tA $a2
+test_t2A $a2
+test_t3A $a2
+$a2 fA
+
+set a3 [new_t2A]
+test_A $a3
+test_tA $a3
+test_t2A $a3
+test_t3A $a3
+$a3 fA
+
+set a4 [new_t3A]
+test_A $a4
+test_tA $a4
+test_t2A $a4
+test_t3A $a4
+$a4 fA
+
+set d2 [new_tD]
+test_A $d2
+test_tA $d2
+test_t2A $d2
+test_t3A $d2
+test_D $d2
+test_tD $d2
+test_t2D $d2
+$d2 fA
+$d2 fD
+
+set d3 [new_t2D]
+test_A $d3
+test_tA $d3
+test_t2A $d3
+test_t3A $d3
+test_D $d3
+test_tD $d3
+test_t2D $d3
+$d3 fA
+$d3 fD
diff --git a/trunk/Examples/test-suite/tcl/disown_runme.tcl b/trunk/Examples/test-suite/tcl/disown_runme.tcl
new file mode 100644
index 0000000..d6647c0
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/disown_runme.tcl
@@ -0,0 +1,16 @@
+
+# This is the union runtime testcase. It ensures that values within a 
+# union embedded within a struct can be set and read correctly.
+
+if [ catch { load ./disown[info sharedlibextension] disown} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+set x 0
+while {$x<100} {
+  set a [new_A]
+  B b
+  b acquire $a
+  incr x
+}
+
diff --git a/trunk/Examples/test-suite/tcl/enum_thorough_runme.tcl b/trunk/Examples/test-suite/tcl/enum_thorough_runme.tcl
new file mode 100644
index 0000000..d4cc199
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/enum_thorough_runme.tcl
@@ -0,0 +1,9 @@
+
+if [ catch { load ./enum_thorough[info sharedlibextension] enum_thorough} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+if { [speedTest0 $SpeedClass_slow] != $SpeedClass_slow } { puts stderr "speedTest0 failed" }
+if { [speedTest4 $SpeedClass_slow] != $SpeedClass_slow } { puts stderr "speedTest4 failed" }
+if { [speedTest5 $SpeedClass_slow] != $SpeedClass_slow } { puts stderr "speedTest5 failed" }
+
diff --git a/trunk/Examples/test-suite/tcl/import_nomodule_runme.tcl b/trunk/Examples/test-suite/tcl/import_nomodule_runme.tcl
new file mode 100644
index 0000000..ead6c3f
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/import_nomodule_runme.tcl
@@ -0,0 +1,4 @@
+
+if [ catch { load ./import_nomodule[info sharedlibextension] import_nomodule} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
diff --git a/trunk/Examples/test-suite/tcl/imports_runme.tcl b/trunk/Examples/test-suite/tcl/imports_runme.tcl
new file mode 100644
index 0000000..85abe49
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/imports_runme.tcl
@@ -0,0 +1,19 @@
+
+# This is the imports runtime testcase. 
+
+if [ catch { load ./imports_b[info sharedlibextension] imports_b} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+	exit 1
+}
+if [ catch { load ./imports_a[info sharedlibextension] imports_a} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+exit 1
+}
+
+set x [new_B]
+A_hello $x
+if [ catch { $x nonexistant } ] {
+} else {
+  puts stderr "nonexistant method did not throw exception\n"
+  exit 1
+}
diff --git a/trunk/Examples/test-suite/tcl/li_std_string_runme.tcl b/trunk/Examples/test-suite/tcl/li_std_string_runme.tcl
new file mode 100644
index 0000000..333c1f1
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/li_std_string_runme.tcl
@@ -0,0 +1,21 @@
+
+if [ catch { load ./li_std_string[info sharedlibextension] li_std_string} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+
+Structure s 
+if {"[s cget -MemberString2]" != "member string 2"} { error "bad string map"}
+s configure -MemberString2 "hello"
+if {"[s cget -MemberString2]" != "hello"} { error "bad string map"}
+
+if {"[s cget -ConstMemberString]" != "const member string"} { error "bad string map"}
+
+if {"$GlobalString2" != "global string 2"} { error "bad string map"}
+if {"$Structure_StaticMemberString2" != "static member string 2"} { error "bad string map"}
+
+set GlobalString2 "hello"
+if {"$GlobalString2" != "hello"} { error "bad string map"}
+
+set Structure_StaticMemberString2 "hello"
+if {"$Structure_StaticMemberString2" != "hello"} { error "bad string map"}
diff --git a/trunk/Examples/test-suite/tcl/member_pointer_runme.tcl b/trunk/Examples/test-suite/tcl/member_pointer_runme.tcl
new file mode 100644
index 0000000..e4d0991
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/member_pointer_runme.tcl
@@ -0,0 +1,46 @@
+# Example using pointers to member functions
+
+if [ catch { load ./member_pointer[info sharedlibextension] member_pointer} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+proc check {what expected actual} {
+  if {$expected != $actual } {
+    error "Failed: $what , Expected: $expected , Actual: $actual"
+  }
+}
+# Get the pointers
+
+set area_pt [ areapt ]
+set perim_pt [ perimeterpt ]
+
+# Create some objects
+
+set s [Square -args 10]
+
+# Do some calculations
+
+check "Square area " 100.0 [do_op $s $area_pt]
+check "Square perim" 40.0 [do_op $s $perim_pt]
+
+set memberPtr $areavar
+set memberPtr $perimetervar
+
+# Try the variables
+check "Square area " 100.0 [do_op $s $areavar]
+check "Square perim" 40.0 [do_op $s $perimetervar]
+
+# Modify one of the variables
+set areavar $perim_pt
+
+check "Square perimeter" 40.0 [do_op $s $areavar]
+
+# Try the constants
+
+set memberPtr $AREAPT
+set memberPtr $PERIMPT
+set memberPtr $NULLPT
+
+check "Square area " 100.0 [do_op $s $AREAPT]
+check "Square perim" 40.0 [do_op $s $PERIMPT]
+
diff --git a/trunk/Examples/test-suite/tcl/newobject1_runme.tcl b/trunk/Examples/test-suite/tcl/newobject1_runme.tcl
new file mode 100644
index 0000000..da6ff66
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/newobject1_runme.tcl
@@ -0,0 +1,28 @@
+if [ catch { load ./newobject1[info sharedlibextension] newobject1} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+set foo1 [Foo_makeFoo]
+if {[Foo_fooCount] != 1} {
+    puts stderr "newobject1 test 1 failed"
+    exit 1
+}
+
+set foo2 [$foo1 makeMore]
+if {[Foo_fooCount] != 2} {
+    puts stderr "newobject1 test 2 failed"
+    exit 1
+}
+
+# Disable test while we solve the problem of premature object deletion
+#$foo1 -delete
+#if {[Foo_fooCount] != 1} {
+#    puts stderr "newobject1 test 3 failed"
+#    exit 1
+#}
+#
+#$foo2 -delete
+#if {[Foo_fooCount] != 0} {
+#    puts stderr "newobject1 test 4 failed"
+#    exit 1
+#}
diff --git a/trunk/Examples/test-suite/tcl/newobject2_runme.tcl b/trunk/Examples/test-suite/tcl/newobject2_runme.tcl
new file mode 100644
index 0000000..18d23af
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/newobject2_runme.tcl
@@ -0,0 +1,27 @@
+if [ catch { load ./newobject2[info sharedlibextension] newobject2} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+set foo1 [makeFoo]
+if {[fooCount] != 1} {
+    puts stderr "newobject2 test 1 failed"
+    exit 1
+}
+
+set foo2 [makeFoo]
+if {[fooCount] != 2} {
+    puts stderr "newobject2 test 2 failed"
+    exit 1
+}
+
+#$foo1 -delete
+#if {[fooCount] != 1} {
+#    puts stderr "newobject2 test 3 failed"
+#    exit 1
+#}
+
+#$foo2 -delete
+#if {[fooCount] != 0} {
+#    puts stderr "newobject2 test 4 failed"
+#    exit 1
+#}
diff --git a/trunk/Examples/test-suite/tcl/overload_copy_runme.tcl b/trunk/Examples/test-suite/tcl/overload_copy_runme.tcl
new file mode 100644
index 0000000..46d7058
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/overload_copy_runme.tcl
@@ -0,0 +1,12 @@
+
+if [ catch { load ./overload_copy[info sharedlibextension] overload_copy} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+Foo f
+Foo g [f cget -this]
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/tcl/overload_simple_runme.tcl b/trunk/Examples/test-suite/tcl/overload_simple_runme.tcl
new file mode 100644
index 0000000..6b65ccc
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/overload_simple_runme.tcl
@@ -0,0 +1,166 @@
+
+if [ catch { load ./overload_simple[info sharedlibextension] overload_simple} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+set f [new_Foo]
+set b [new_Bar]
+set v [malloc_void 32]
+
+set x [foo 3]
+if {$x != "foo:int"} {
+   puts stderr "foo(int) test failed $x"
+   exit 1
+}
+
+set x [foo 3.4]
+if {$x != "foo:double"} {
+   puts stderr "foo(double) test failed"
+   exit 1
+}
+
+set x [foo hello]
+if {$x != "foo:char *"} {
+   puts stderr "foo(char *) test failed"
+   exit 1
+}
+
+set x [foo $f]
+if {$x != "foo:Foo *"} {
+   puts stderr "foo(Foo *) test failed"
+   exit 1
+}
+
+set x [foo $b]
+if {$x != "foo:Bar *"} {
+   puts stderr "foo(Bar *) test failed"
+   exit 1
+}
+
+set x [foo $v]
+if {$x != "foo:void *"} {
+   puts stderr "foo(void *) test failed"
+   exit 1
+}
+
+Spam s
+
+set x [s foo 3]
+if {$x != "foo:int"} {
+   puts stderr "Spam::foo(int) test failed"
+   exit 1
+}
+
+set x [s foo 3.4]
+if {$x != "foo:double"} {
+   puts stderr "Spam::foo(double) test failed"
+   exit 1
+}
+
+set x [s foo hello]
+if {$x != "foo:char *"} {
+   puts stderr "Spam::foo(char *) test failed"
+   exit 1
+}
+
+set x [s foo $f]
+if {$x != "foo:Foo *"} {
+   puts stderr "Spam::foo(Foo *) test failed"
+   exit 1
+}
+
+set x [s foo $b]
+if {$x != "foo:Bar *"} {
+   puts stderr "Spam::foo(Bar *) test failed"
+   exit 1
+}
+
+set x [s foo $v]
+if {$x != "foo:void *"} {
+   puts stderr "Spam::foo(void *) test failed"
+   exit 1
+}
+
+
+set x [Spam_bar 3]
+if {$x != "bar:int"} {
+   puts stderr "Spam::bar(int) test failed"
+   exit 1
+}
+
+set x [Spam_bar 3.4]
+if {$x != "bar:double"} {
+   puts stderr "Spam::bar(double) test failed"
+   exit 1
+}
+
+set x [Spam_bar hello]
+if {$x != "bar:char *"} {
+   puts stderr "Spam::bar(char *) test failed"
+   exit 1
+}
+
+set x [Spam_bar $f]
+if {$x != "bar:Foo *"} {
+   puts stderr "Spam::bar(Foo *) test failed"
+   exit 1
+}
+
+set x [Spam_bar $b]
+if {$x != "bar:Bar *"} {
+   puts stderr "Spam::bar(Bar *) test failed"
+   exit 1
+}
+
+set x [Spam_bar $v]
+if {$x != "bar:void *"} {
+   puts stderr "Spam::bar(void *) test failed"
+   exit 1
+}
+
+Spam s
+set x [s cget -type]
+if {$x != "none"} {
+    puts stderr "Spam() test failed"
+}
+
+Spam s 3
+set x [s cget -type]
+if {$x != "int"} {
+    puts stderr "Spam(int) test failed"
+}
+
+Spam s 3.4
+set x [s cget -type]
+if {$x != "double"} {
+    puts stderr "Spam(double) test failed"
+}
+
+Spam s hello
+set x [s cget -type]
+if {$x != "char *"} {
+    puts stderr "Spam(char *) test failed"
+}
+
+Spam s $f
+set x [s cget -type]
+if {$x != "Foo *"} {
+    puts stderr "Spam(Foo *) test failed"
+}
+
+Spam s $b
+set x [s cget -type]
+if {$x != "Bar *"} {
+    puts stderr "Spam(Bar *) test failed"
+}
+
+Spam s $v
+set x [s cget -type]
+if {$x != "void *"} {
+    puts stderr "Spam(void *) test failed"
+}
+
+free_void $v
+
+
+
diff --git a/trunk/Examples/test-suite/tcl/primitive_ref_runme.tcl b/trunk/Examples/test-suite/tcl/primitive_ref_runme.tcl
new file mode 100644
index 0000000..ab4e444
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/primitive_ref_runme.tcl
@@ -0,0 +1,19 @@
+# Primitive ref testcase.  Tests to make sure references to 
+# primitive types are passed by value
+
+if [ catch { load ./primitive_ref[info sharedlibextension] primitive_ref} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+if { [ref_int 3] != 3 } { puts stderr "ref_int failed" }
+if { [ref_uint 3] != 3 } { puts stderr "ref_uint failed" }
+if { [ref_short 3] != 3 } { puts stderr "ref_short failed" }
+if { [ref_ushort 3] != 3 } { puts stderr "ref_ushort failed" }
+if { [ref_long 3] != 3 } { puts stderr "ref_long failed" }
+if { [ref_ulong 3] != 3 } { puts stderr "ref_ulong failed" }
+if { [ref_schar 3] != 3 } { puts stderr "ref_schar failed" }
+if { [ref_uchar 3] != 3 } { puts stderr "ref_uchar failed" }
+if { [ref_float 3.5] != 3.5 } { puts stderr "ref_float failed" }
+if { [ref_double 3.5] != 3.5 } { puts stderr "ref_double failed" }
+if { [ref_char x] != "x" } { puts stderr "ref_char failed" }
+
diff --git a/trunk/Examples/test-suite/tcl/primitive_types_runme.tcl b/trunk/Examples/test-suite/tcl/primitive_types_runme.tcl
new file mode 100644
index 0000000..fa4c46b
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/primitive_types_runme.tcl
@@ -0,0 +1,33 @@
+
+if [ catch { load ./primitive_types[info sharedlibextension] primitive_types} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+
+if {[val_int 10] != 10 }  { error "bad int map"  }
+if {[val_schar 10] != 10 } { error "bad char map" }
+if {[val_short 10] != 10 } { error "bad schar map" }
+
+
+if [catch { val_schar 10000 } ] {} else { error "bad schar map" }
+if [catch { val_uint  -100 } ]  {} else { error "bad uint map"  }
+if [catch { val_uchar -100 } ]  {} else { error "bad uchar map" }
+
+if {[val_uint 10] != 10 }  { error "bad uint map"  }
+if {[val_uchar 10] != 10 } { error "bad uchar map" }
+if {[val_ushort 10] != 10 } { error "bad ushort map" }
+
+
+if {[val_double 10] != 10 } { error "bad double map" }
+if {[val_float 10] != 10 } { error "bad double map" }
+
+
+
+if [catch { val_float hello } ] {} else { error "bad double map" }
+
+if {[val_char c] != "c" } { error "bad char map" }
+if {[val_char "c"] != "c" } { error "bad char map" }
+if {[val_char 101] != "e" } { error "bad char map" }
+
+
+
diff --git a/trunk/Examples/test-suite/tcl/profiletest_runme.tcl b/trunk/Examples/test-suite/tcl/profiletest_runme.tcl
new file mode 100644
index 0000000..087eea4
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/profiletest_runme.tcl
@@ -0,0 +1,8 @@
+catch { load ./profiletest[info sharedlibextension] profiletest}
+
+set  a [new_A]
+set  b [new_B]
+
+for {set i 0} {$i < 1000000} {incr i 1} {
+    set a [B_fn $b $a]
+}
diff --git a/trunk/Examples/test-suite/tcl/reference_global_vars_runme.tcl b/trunk/Examples/test-suite/tcl/reference_global_vars_runme.tcl
new file mode 100644
index 0000000..bfd31a9
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/reference_global_vars_runme.tcl
@@ -0,0 +1,108 @@
+if [ catch { load ./reference_global_vars[info sharedlibextension] reference_global_vars} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+# const class reference variable
+if {[ [getconstTC ] cget -num] != 33 } {
+   puts stderr "test 1 failed"
+   exit 1
+}
+
+# primitive reference variables
+set var_bool [createref_bool 0]
+if {[value_bool $var_bool] != 0} {
+   puts stderr "test 2 failed"
+   exit 1
+}
+
+set var_bool [createref_bool 1]
+if {[value_bool $var_bool] != 1} {
+   puts stderr "test 3 failed"
+   exit 1
+}
+
+set var_char [createref_char "w"]
+if {[value_char $var_char] != "w"} {
+   puts stderr "test 4 failed"
+   exit 1
+}
+
+set var_unsigned_char [createref_unsigned_char 10]
+if {[value_unsigned_char $var_unsigned_char] != 10} {
+   puts stderr "test 5 failed"
+   exit 1
+}
+
+set var_signed_char [createref_signed_char 10]
+if {[value_signed_char $var_signed_char] != 10} {
+   puts stderr "test 6 failed"
+   exit 1
+}
+
+set var_short [createref_short 10]
+if {[value_short $var_short] != 10} {
+   puts stderr "test 7 failed"
+   exit 1
+}
+
+set var_unsigned_short [createref_unsigned_short 10]
+if {[value_unsigned_short $var_unsigned_short] != 10} {
+   puts stderr "test 8 failed"
+   exit 1
+}
+
+set var_int [createref_int 10]
+if {[value_int $var_int] != 10} {
+   puts stderr "test 9 failed"
+   exit 1
+}
+
+set var_unsigned_int [createref_unsigned_int 10]
+if {[value_unsigned_int $var_unsigned_int] != 10} {
+   puts stderr "test 10 failed"
+   exit 1
+}
+
+set var_long [createref_long 10]
+if {[value_long $var_long] != 10} {
+   puts stderr "test 11 failed"
+   exit 1
+}
+
+set var_unsigned_long [createref_unsigned_long 10]
+if {[value_unsigned_long $var_unsigned_long] != 10} {
+   puts stderr "test 12 failed"
+   exit 1
+}
+
+set var_long_long [createref_long_long 10]
+if {[value_long_long $var_long_long] != 10} {
+   puts stderr "test 13 failed"
+   exit 1
+}
+
+set var_unsigned_long_long [createref_unsigned_long_long 10]
+if {[value_unsigned_long_long $var_unsigned_long_long] != 10} {
+   puts stderr "test 14 failed"
+   exit 1
+}
+
+set var_float [createref_float 10.5]
+if {[value_float $var_float] != 10.5} {
+   puts stderr "test 15 failed"
+   exit 1
+}
+
+set var_double [createref_double 10.5]
+if {[value_double $var_double] != 10.5} {
+   puts stderr "test 16 failed"
+   exit 1
+}
+
+# class reference variable
+set var_TestClass [createref_TestClass [TestClass tc 20] ]
+if {[ [value_TestClass $var_TestClass] cget -num] != 20} {
+   puts stderr "test 17 failed"
+   exit 1
+}
+
diff --git a/trunk/Examples/test-suite/tcl/union.i b/trunk/Examples/test-suite/tcl/union.i
new file mode 100644
index 0000000..d8ac62b
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/union.i
@@ -0,0 +1,41 @@
+%module unions
+
+%inline %{
+
+typedef unsigned char Uint8;
+
+typedef struct SDL_ActiveEvent {
+        Uint8 type;     /* SDL_ACTIVEEVENT */
+        Uint8 gain;     /* Whether given states were gained or lost (1/0) */
+        Uint8 state;    /* A mask of the focus states */
+} SDL_ActiveEvent;
+
+/* Keyboard event structure */
+typedef struct SDL_KeyboardEvent {
+        Uint8 type;     /* SDL_KEYDOWN or SDL_KEYUP */
+        int which;    /* The keyboard device index */
+        int state;    /* SDL_PRESSED or SDL_RELEASED */
+} SDL_KeyboardEvent;
+
+typedef union {
+        Uint8 type;
+        SDL_ActiveEvent active;
+        SDL_KeyboardEvent key;
+} SDL_Event;
+
+int SDL_PollEvent (SDL_Event *ev) {
+    static int toggle = 0;
+    if (toggle == 0) {
+        ev->type = 1;
+        ev->active.gain = 20;
+        ev->active.state = 30;
+    } else {
+        ev->type = 2;
+        ev->key.which = 2000;
+        ev->key.state = 3000;
+    }
+    toggle = 1 - toggle;
+    return 1;
+}
+
+%}
diff --git a/trunk/Examples/test-suite/tcl/union_runme.tcl b/trunk/Examples/test-suite/tcl/union_runme.tcl
new file mode 100755
index 0000000..2c47ece
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/union_runme.tcl
@@ -0,0 +1,36 @@
+if [ catch { load ./union[info sharedlibextension] unions} err_msg ] {
+        puts stderr "Could not load shared object:\n$err_msg"
+}
+
+set event [SDL_Event]
+
+for { set i 0 } { $i < 2 } { incr i } {
+#    puts -nonewline "Loop $i: "
+    set evAvailable [SDL_PollEvent $event]
+    set evType [$event cget -type]
+#    puts "evType = $evType"
+
+    if { $evType == 1 } {
+        set specEvent [$event cget -active]
+#        puts "specEvent = $specEvent"
+        set type [$specEvent cget -type]
+        if { $type != $evType } {
+            error "Type $type should be $evType"
+        }
+        set gain   [$specEvent cget -gain]
+        set state  [$specEvent cget -state]
+#        puts "gain=$gain state=$state"
+    }
+    if { $evType == 2 } {
+        set specEvent [$event cget -key]
+#        puts "specEvent = $specEvent"
+        set type [$specEvent cget -type]
+        if { $type != $evType } {
+            error "Type $type should be $evType"
+        }
+        set which  [$specEvent cget -which]
+        set state  [$specEvent cget -state]
+#        puts "which=$which state=$state"
+    }
+#    puts ""
+}
diff --git a/trunk/Examples/test-suite/tcl/unions_runme.tcl b/trunk/Examples/test-suite/tcl/unions_runme.tcl
new file mode 100644
index 0000000..8c31095
--- /dev/null
+++ b/trunk/Examples/test-suite/tcl/unions_runme.tcl
@@ -0,0 +1,63 @@
+
+# This is the union runtime testcase. It ensures that values within a 
+# union embedded within a struct can be set and read correctly.
+
+if [ catch { load ./unions[info sharedlibextension] unions} err_msg ] {
+	puts stderr "Could not load shared object:\n$err_msg"
+}
+
+# Create new instances of SmallStruct and BigStruct for later use
+SmallStruct small
+small configure -jill 200
+
+BigStruct big
+big configure -smallstruct [small cget -this]
+big configure -jack 300
+
+# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
+# Ensure values in EmbeddedUnionTest are set correctly for each.
+EmbeddedUnionTest eut
+
+# First check the SmallStruct in EmbeddedUnionTest
+eut configure -number 1
+
+#eut.uni.small = small
+EmbeddedUnionTest_uni_small_set [EmbeddedUnionTest_uni_get [eut cget -this] ] [small cget -this]
+
+#Jill1 = eut.uni.small.jill
+set Jill1 [SmallStruct_jill_get [EmbeddedUnionTest_uni_small_get [EmbeddedUnionTest_uni_get [eut cget -this] ] ] ]
+if {$Jill1 != 200} {
+    puts stderr "Runtime test1 failed. eut.uni.small.jill=$Jill1"
+    exit 1
+}
+
+set Num1 [eut cget -number]
+if {$Num1 != 1} {
+    puts stderr "Runtime test2 failed. eut.number=$Num1"
+    exit 1
+}
+
+# Secondly check the BigStruct in EmbeddedUnionTest
+eut configure -number 2
+#eut.uni.big = big
+EmbeddedUnionTest_uni_big_set [EmbeddedUnionTest_uni_get [eut cget -this] ] [big cget -this]
+#Jack1 = eut.uni.big.jack
+set Jack1 [BigStruct_jack_get [EmbeddedUnionTest_uni_big_get [EmbeddedUnionTest_uni_get [eut cget -this] ] ] ]
+if {$Jack1 != 300} {
+    puts stderr "Runtime test3 failed. eut.uni.big.jack=$Jack1"
+    exit 1
+}
+
+#Jill2 = eut.uni.big.smallstruct.jill
+set Jill2 [SmallStruct_jill_get [BigStruct_smallstruct_get [EmbeddedUnionTest_uni_big_get [EmbeddedUnionTest_uni_get [eut cget -this] ] ] ] ]
+if {$Jill2 != 200} {
+    puts stderr "Runtime test4 failed. eut.uni.big.smallstruct.jill=$Jill2"
+    exit 1
+}
+
+set Num2 [eut cget -number]
+if {$Num2 != 2} {
+    puts stderr "Runtime test5 failed. eut.number=$Num2"
+    exit 1
+}
+
diff --git a/trunk/Examples/test-suite/template.i b/trunk/Examples/test-suite/template.i
new file mode 100644
index 0000000..d2c7a91
--- /dev/null
+++ b/trunk/Examples/test-suite/template.i
@@ -0,0 +1,52 @@
+/* File : example.i */
+%module "template"
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<int>;         /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<double>;      /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<int (*)[10]>; /* Ruby, wrong class name */
+
+/* Let's just grab the original header file here */
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+%inline %{
+
+template<class T> T max(const T a, const T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+  // This really doesn't do anything except test const handling 
+  void testconst(const T x) { }
+};
+
+%}
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
+/* Now try to break constness */
+
+%template(maxintp) max<int (*)[10]>;
+%template(vecintp) vector<int (*)[10]>;
+
+
diff --git a/trunk/Examples/test-suite/template_arg_replace.i b/trunk/Examples/test-suite/template_arg_replace.i
new file mode 100644
index 0000000..25274c9
--- /dev/null
+++ b/trunk/Examples/test-suite/template_arg_replace.i
@@ -0,0 +1,14 @@
+%module template_arg_replace
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) test_Matrix<float, 3, 3>;	/* Ruby, wrong class name */
+
+%inline %{
+
+template <typename T, int r, int c> class test_Matrix { 
+public: 
+ void Func(const test_Matrix<T,r,c> &m) { }; 
+}; 
+%} 
+
+%template (matrix33f) test_Matrix<float,3, 3>; 
+
diff --git a/trunk/Examples/test-suite/template_arg_scope.i b/trunk/Examples/test-suite/template_arg_scope.i
new file mode 100644
index 0000000..36b593c
--- /dev/null
+++ b/trunk/Examples/test-suite/template_arg_scope.i
@@ -0,0 +1,16 @@
+%module template_arg_scope
+%inline %{
+
+template<class T> class Foo {
+};
+
+class Bar {
+public:
+   Bar();
+   void spam(Foo<Bar> *x);
+};
+Bar::Bar() {}
+void Bar::spam(Foo<Bar> *x) {}
+
+%}
+
diff --git a/trunk/Examples/test-suite/template_arg_typename.i b/trunk/Examples/test-suite/template_arg_typename.i
new file mode 100644
index 0000000..0f4c887
--- /dev/null
+++ b/trunk/Examples/test-suite/template_arg_typename.i
@@ -0,0 +1,26 @@
+%module template_arg_typename
+
+%inline %{
+
+
+  template <class ArgType, class ResType>
+  struct UnaryFunction 
+  {
+    typedef void* vptr_type;
+  };
+
+  template <class ArgType>
+  struct BoolUnaryFunction : UnaryFunction<ArgType, bool>
+			     
+  {
+    typedef UnaryFunction<ArgType, bool> base;
+    BoolUnaryFunction(const typename base::vptr_type* vptrf) {}
+
+  };
+
+
+%}
+
+
+%template(UnaryFunction_bool_bool) UnaryFunction<bool, bool>;
+%template(BoolUnaryFunction_bool) BoolUnaryFunction<bool>;
diff --git a/trunk/Examples/test-suite/template_array_numeric.i b/trunk/Examples/test-suite/template_array_numeric.i
new file mode 100644
index 0000000..463b04a
--- /dev/null
+++ b/trunk/Examples/test-suite/template_array_numeric.i
@@ -0,0 +1,26 @@
+%module template_array_numeric
+
+%inline %{
+
+template <int Len>
+class Arrayf
+{
+  float a[Len];
+ public:
+  Arrayf() {}
+  Arrayf(const float l[Len]) { };
+};
+
+template <int Len>
+Arrayf<Len> make_arrayf(const float l[Len])
+{
+  Arrayf<Len> a(l);
+  return a;
+}
+
+typedef Arrayf<4> Array4f;
+
+%}
+
+%template(Array4f) Arrayf<4>;
+%template(make_array4f) make_arrayf<4>;
diff --git a/trunk/Examples/test-suite/template_base_template.i b/trunk/Examples/test-suite/template_base_template.i
new file mode 100644
index 0000000..130dc39
--- /dev/null
+++ b/trunk/Examples/test-suite/template_base_template.i
@@ -0,0 +1,41 @@
+%module template_base_template
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) traits<double, double>; /* Ruby, wrong class name */
+
+%warnfilter(SWIGWARN_PARSE_EXPLICIT_TEMPLATE);
+
+%inline %{
+  template <class ArgType, class ResType>
+  struct traits
+  {
+    typedef ArgType arg_type;
+    typedef ResType res_type;
+  };
+ 
+  template <class ArgType, class ResType>
+  struct Funktion
+  {
+  };
+
+  // Egad!
+  template <class AF, class AG>
+  struct Klass
+    : Funktion<typename traits<AF, AG>::arg_type,
+                                typename traits<AF, AG>::res_type>
+  {
+  };
+%}
+
+%{
+ template struct Funktion <double, double>;
+ template struct Klass <double, double>;
+%}
+ 
+%template(traits_dd) traits <double, double>;
+%template(Funktion_dd) Funktion <double, double>;
+%template(Klass_dd) Klass <double, double>;
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/template_classes.i b/trunk/Examples/test-suite/template_classes.i
new file mode 100644
index 0000000..a05eb9b
--- /dev/null
+++ b/trunk/Examples/test-suite/template_classes.i
@@ -0,0 +1,52 @@
+/* File : template_classes.i */
+/* Tests the use of one templated class within another */
+
+%module template_classes
+
+
+#pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
+
+%{
+%}
+
+%inline %{
+
+template <class T>
+class Point {
+public:
+  T getX() {return x;}
+private:
+  T x;
+};
+
+template <class T>
+class RectangleTest {
+public:
+  Point<T>& getPoint() {return point;}
+  void setPoint(Point<T>& value) {point = value;}
+private:
+  Point<T> point;
+
+
+  template <class Data>
+  struct pair2nd_eq
+  {
+  };
+  
+  
+
+
+  struct Foo : Point<int>
+  {
+  };
+  
+  Foo foo;
+  
+};
+
+%}
+
+%template(PointInt) Point<int>;
+%template(RectangleInt) RectangleTest<int>;
+
+
diff --git a/trunk/Examples/test-suite/template_const_ref.i b/trunk/Examples/test-suite/template_const_ref.i
new file mode 100644
index 0000000..196ca90
--- /dev/null
+++ b/trunk/Examples/test-suite/template_const_ref.i
@@ -0,0 +1,14 @@
+%module template_const_ref
+%inline %{
+template <class T> class Foo {
+public:
+	char *bar(const T &obj) {
+	    return (char *) "Foo::bar";
+        }
+};
+class Bar { };
+%}
+
+%template(Foob) Foo<const Bar *>;
+%template(Fooi) Foo<const int *>;
+
diff --git a/trunk/Examples/test-suite/template_construct.i b/trunk/Examples/test-suite/template_construct.i
new file mode 100644
index 0000000..a6e8c3c
--- /dev/null
+++ b/trunk/Examples/test-suite/template_construct.i
@@ -0,0 +1,15 @@
+%module template_construct
+
+// Tests templates to make sure an extra <> in a constructor is ok.
+
+%inline %{
+template<class T> 
+class Foo {
+    T y;
+public:
+    Foo<T>(T x) : y(x) { }
+};
+
+%}
+
+%template(Foo_int) Foo<int>;
diff --git a/trunk/Examples/test-suite/template_default.i b/trunk/Examples/test-suite/template_default.i
new file mode 100644
index 0000000..2f6ffd5
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default.i
@@ -0,0 +1,217 @@
+%module template_default
+
+
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) ns1::Traits::c; /* Ruby, wrong constant name */
+namespace ns1 {
+  namespace ns2 {
+  
+    %feature("hello") A<int>;
+    %feature("hello") A<double,double>;
+    %feature("hi") A<int,int>;
+    %feature("hi") A<double>;
+    
+    %extend A<int> 
+    {
+      int foo() { return 1; }
+    }
+    
+    %extend A<double,double> 
+    {
+      int foo() { return 1; }
+    }
+    
+    %extend A<int,int> 
+    {
+      int bar() { return 1; }
+    }
+    
+    %extend A<double> 
+    {
+      int bar() { return 1; }
+    }
+
+    %extend N<double> 
+    {
+      int bar() { return 1; }
+    }
+  }
+}
+
+%inline %{
+  
+  namespace ns1 {
+    namespace ns2 {
+      
+      struct Parm
+      {
+      };
+      
+      template <class T1, class T2 = T1>
+      class A
+      {
+	
+#ifdef SWIG      
+	%typemap(in) A *  { /* in A */ }
+  #ifdef SWIGCSHARP
+	%typemap(out) A *  { /* out A */ $result=0; }
+  #else
+	%typemap(out) A *  { /* out A */ }
+  #endif
+#endif
+      };
+
+      typedef unsigned int category;
+      
+      const category one = 1;
+      const category two = 1;
+      
+      
+      template <class T1, category C = one, class T2 = Parm>
+      class N
+      {
+	
+#ifdef SWIG      
+	%typemap(in) N *  { /* in N */ }
+  #ifdef SWIGCSHARP
+	%typemap(out) N *  { /* out N */ $result=0; }
+  #else
+	%typemap(out) N *  { /* out N */ }
+  #endif
+#endif
+      };
+    }
+  }
+%}
+
+      
+
+
+%template(A_p) ns1::ns2::A<double,ns1::ns2::Parm>;
+%template(N_1p) ns1::ns2::N<int>;
+
+
+namespace ns1 {
+  namespace ns2 {
+    %template(A_ii) A<int, int>;       
+    %template(A_d) A<double>;
+    %template(N_d) N<double>;
+    
+  }
+}
+
+
+%inline %{
+  namespace ns1 {
+    namespace ns2 {    
+      namespace ns3 {  
+
+	struct B : A<int> 
+	{
+	};
+	
+	struct C : N<double,ns1::ns2::one> 
+	{	  
+	};
+	
+	
+	A<int> *get_a1(A<int> *a) {
+	  return a;
+	}
+	
+	A<int,int> *get_a2(A<int,int> *a) {
+	  return a;
+	}
+
+      }
+    }
+  }
+%}
+
+%inline %{
+  namespace ns1 {    
+    struct Traits
+    {
+      static const ns2::category c = ns2::one;
+    };
+    namespace ns4 {    
+      
+      template <class T>
+      struct D : ns2::N<double,T::c>
+      {
+	D()
+	{
+	}
+	
+      };
+
+      template <class T1, class T2 = D<T1> >
+      struct Base : T2
+      {
+      };
+    }
+  }
+%}
+
+
+%template(Do) ns1::ns4::D<ns1::Traits>;
+%template(Bo) ns1::ns4::Base<ns1::Traits, ns1::ns4::D<ns1::Traits> >;
+
+
+
+%inline %{
+  namespace ns1 {    
+    namespace ns5 {    
+      
+      struct Der : ns4::Base<Traits>
+      {
+      };
+    }
+  }
+  
+%}
+
+
+%inline %{
+
+  namespace hi 
+  {
+    class CFoo
+    {
+    };
+    
+    template<class T1, class T2 = T1> class CTemplate
+    {
+    };
+    
+    typedef CTemplate<CFoo> TBla;                  // OK
+    typedef void (*TFunc1)(CFoo arg);              // OK
+    typedef void (*TFunc2)(CTemplate<CFoo> arg);   // OK
+    typedef void (*TFunc3)(CTemplate<CFoo>* arg);  // OK
+
+    int foo(TFunc1 a, TFunc2 b, TFunc3 c) 
+    {
+      return 0;
+    }
+  }  
+%}
+
+
+#ifndef SWIGCHICKEN
+%include std_vector.i
+
+%{
+#include <vector>
+%}
+
+%inline %{
+void g(std::vector<double>* s = 0) {}
+void q(double = 0) {}
+%}
+
+
+%constant void (*Bf)(std::vector<double> *p = 0) = g; 
+%constant void (*Cf)(double = 0) = q; 
+
+
+#endif
diff --git a/trunk/Examples/test-suite/template_default2.i b/trunk/Examples/test-suite/template_default2.i
new file mode 100644
index 0000000..1e0b624
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default2.i
@@ -0,0 +1,44 @@
+%module template_default2
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::traits; // Ruby, wrong class name
+
+%inline %{
+  namespace oss
+  {
+    enum Polarization { UnaryPolarization, BinaryPolarization };
+ 
+    template <Polarization P>
+    struct Interface
+    {
+    };
+ 
+    struct traits
+    {
+      static const Polarization pmode = UnaryPolarization;
+    };
+ 
+    template <class C,
+          Polarization P = C::pmode,
+          class Base = Interface<P> >   // **** problem here *****
+    struct Module : Base
+    {
+    };
+ 
+  }
+%}                                
+
+namespace oss
+{
+  %template(Interface_UP) Interface<UnaryPolarization>;
+ 
+  // This works
+  %template(Module_UP1) Module<traits,
+                   UnaryPolarization,
+                   Interface<UnaryPolarization> >;
+ 
+   // These don't
+  %template(Module_UP2) Module<traits, UnaryPolarization>;
+  %template(Module_UP3) Module<traits>;
+}
+ 
+                                                       
diff --git a/trunk/Examples/test-suite/template_default_arg.i b/trunk/Examples/test-suite/template_default_arg.i
new file mode 100644
index 0000000..faa0f68
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default_arg.i
@@ -0,0 +1,126 @@
+%module template_default_arg
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Hello;	/* Ruby, wrong class name */
+#ifdef SWIGLUA
+// lua only has one numeric type, so most of the overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) X;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) Z;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) meth;
+#endif
+
+%inline %{
+  template <class T>
+    struct Foo 
+    {
+      typedef unsigned int size_type;
+      Foo(size_type n = size_type(0) ) { }
+    };
+  
+  int foob(Foo<int> h = Foo<int>()) {return 1; }
+
+  template <class T>
+    struct Hello
+    {
+      typedef unsigned int size_type;
+
+      // This works
+      // Hello(size_type n = Hello<T>::size_type(0) ) { }
+
+      // This doesn't
+      Hello(size_type n = size_type(0) ) { }
+
+      enum Hi { hi, hello };
+
+      void foo(Hi h = hi) { }
+    };
+
+  template <typename T> struct X {
+      X(const T& t = T()) {}
+      X(double a, const T& t = T(0)) {}
+      T meth(double a, const T& t = T(0)) { return t; }
+      const T& meth(const T& t = T(0)) { return t; }
+    };
+
+  template <typename TT> class Y : private X<TT> {
+  public:
+    // test using on templated class with default args in the method
+    using X<TT>::meth;
+  };
+
+  template <int V> struct Z 
+  {
+    Z(int t = V) {}    
+    // and also:
+    Z(double a, int t = V){}
+  };
+  
+  
+%}
+
+%template(Foo_int) Foo<int>;
+%template(Hello_int) Hello<int>;
+%template(X_int) X<int>;
+%template(X_longlong) X<long long>;
+%template(X_unsigned) X<unsigned>;
+%template(Y_unsigned) Y<unsigned>;
+
+%template(X_hello_unsigned) X<Hello<int> >;
+%template(Y_hello_unsigned) Y<Hello<int> >;
+%template(X_Foo_Foo_int) X<Foo<Foo<int> > >;
+%template(Z_8) Z<8>;
+%template(Foo_Z_8) Foo<Z<8> >;
+%template(X_Foo_Z_8) X<Foo<Z<8> > >;
+
+%inline %{
+
+  struct Bar : Hello<int>
+  {
+    Bar(size_type n) : Hello<int>(n)
+    {
+    }
+    
+  };
+%}
+
+
+// Templated functions
+%inline %{
+  // Templated methods which are overloaded and have default args, and %template which
+  // uses the same name as the C++ functions and overload on the template parameters and
+  // specialization thrown in too. Wow, SWIG can handle this insane stuff!
+  template<typename T, typename U> int ott(T t = 0, const U& u = U()) { return 10; }
+  template<typename T, typename U> int ott(const char *msg, T t = 0, const U& u = U()) { return 20; }
+  int ott(Foo<int>) { return 30; }
+  template<typename T> int ott(Hello<int> h, T t = 0) { return 40; }
+  template<> int ott<int>(Hello<int> h, int t) { return 50; }
+  template<> int ott(Hello<int> h, double t) { return 60; }
+%}
+
+%template(ott) ott<int, int>;
+%template(ott) ott<double>;
+%template(ottint) ott<int>; // default arg requires a rename
+%template(ottstring) ott<const char *>; // default arg requires a rename
+
+
+// Above test in namespaces
+%inline %{
+namespace OuterSpace {
+  namespace InnerSpace {
+    // Templated methods which are overloaded and have default args, and %template which
+    // uses the same name as the C++ functions and overload on the template parameters and
+    // specialization thrown in too. Wow, SWIG can handle this insane stuff!
+    template<typename T, typename U> int nsott(T t = 0, const U& u = U()) { return 110; }
+    template<typename T, typename U> int nsott(const char *msg, T t = 0, const U& u = U()) { return 120; }
+    int nsott(Foo<int>) { return 130; }
+    template<typename T> int nsott(Hello<int> h, T t = 0) { return 140; }
+    template<> int nsott<int>(Hello<int> h, int t) { return 150; }
+    template<> int nsott(Hello<int> h, double t) { return 160; }
+  }
+}
+%}
+
+%template(nsott) OuterSpace::InnerSpace::nsott<int, int>;
+%template(nsott) OuterSpace::InnerSpace::nsott<double>;
+%template(nsottint) OuterSpace::InnerSpace::nsott<int>; // default arg requires a rename
+%template(nsottstring) OuterSpace::InnerSpace::nsott<const char *>; // default arg requires a rename
+
diff --git a/trunk/Examples/test-suite/template_default_class_parms.i b/trunk/Examples/test-suite/template_default_class_parms.i
new file mode 100644
index 0000000..cd37269
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default_class_parms.i
@@ -0,0 +1,33 @@
+%module template_default_class_parms
+
+%inline %{
+namespace Space {
+  struct SomeType {};
+  struct AnotherType {};
+  template<typename C, typename D = SomeType, typename E = int> class Bar {
+  public:
+    C CType;
+    D DType;
+    E EType;
+    Bar(C c, D d, E e) {}
+    C method(C c, D d, E e) { return c; }
+  };
+  template<typename T = SomeType> class Foo {
+  public:
+    T TType;
+    Foo(T t) {}
+    T method(T t) { return t; }
+  };
+  template<typename T = int> class ATemplate {};
+}
+%}
+
+// Use defaults
+%template(DefaultBar) Space::Bar<double>;
+%template(DefaultFoo) Space::Foo<>;
+
+// Don't use all defaults
+%template(BarAnotherTypeBool) Space::Bar<Space::AnotherType, bool>;
+%template(FooAnotherType) Space::Foo<Space::AnotherType>;
+
+%template() Space::ATemplate<>;
diff --git a/trunk/Examples/test-suite/template_default_inherit.i b/trunk/Examples/test-suite/template_default_inherit.i
new file mode 100644
index 0000000..d8d34d8
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default_inherit.i
@@ -0,0 +1,25 @@
+%module template_default_inherit
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) A::nindex;	/* Ruby, wrong constant name */
+ 
+%inline %{
+  template <class C>
+    struct A
+    {
+      typedef unsigned int size_type;
+      static const size_type nindex = static_cast<size_type>(-1);
+ 
+    };
+ 
+    template <class C>
+    struct B : A<C>
+    {
+      typedef typename A<C>::size_type size_type;
+      void say_hi(size_type index = A<C>::nindex) {}
+    };
+ 
+%}
+ 
+%template(A_int) A<int>;
+%template(B_int) B<int>;                
+
diff --git a/trunk/Examples/test-suite/template_default_pointer.i b/trunk/Examples/test-suite/template_default_pointer.i
new file mode 100644
index 0000000..9582ef4
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default_pointer.i
@@ -0,0 +1,12 @@
+%module template_default_pointer
+
+%inline %{
+
+template <class T1, class T2 = T1*>
+class B
+{
+};
+
+%}
+
+%template(B_d) B<double>;
diff --git a/trunk/Examples/test-suite/template_default_qualify.i b/trunk/Examples/test-suite/template_default_qualify.i
new file mode 100644
index 0000000..bcba1a4
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default_qualify.i
@@ -0,0 +1,56 @@
+// Tests typename qualification and constant resolution in default
+// template arguments.  Another Marcelo special.. :-).
+
+%module template_default_qualify
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) etraits; /* Ruby, wrong class name */
+
+%inline %{
+  namespace oss
+  {
+ 
+    enum Polarization { UnaryPolarization, BinaryPolarization };
+ 
+    template <Polarization P>
+    struct Interface
+    {
+    };
+
+    namespace modules
+    {
+ 
+      template <class traits, class base = Interface<traits::pmode> >
+ // *** problem here ****
+      struct Module : base
+      {
+      };
+    }
+  }
+  struct etraits
+  {
+    static const oss::Polarization pmode = oss::UnaryPolarization;
+  };
+
+%}
+ 
+namespace oss
+{	
+  %template(Interface_UP) Interface<UnaryPolarization>;
+  namespace modules
+  {
+    %template(Module_etraits) Module<etraits>;
+  }
+}
+ 
+%inline %{
+  namespace oss
+  {
+    namespace modules
+    {
+      struct HModule1 : Module<etraits>
+      {
+      };
+    }
+  }
+%}
+                                        
diff --git a/trunk/Examples/test-suite/template_default_vw.i b/trunk/Examples/test-suite/template_default_vw.i
new file mode 100644
index 0000000..429ed30
--- /dev/null
+++ b/trunk/Examples/test-suite/template_default_vw.i
@@ -0,0 +1,24 @@
+%module template_default_vw
+
+%inline %{
+class SomeClass{ }; 
+ 
+template<class T>  
+class Handle { 
+public: 
+    Handle( T* t=0 ) { };   
+    // ... 
+}; 
+ 
+typedef Handle<SomeClass> hSomeClass; 
+class AnotherClass { 
+public: 
+  void someFunc( hSomeClass a = hSomeClass() ) { }; 
+}; 
+
+%}
+
+%template() Handle<SomeClass>;
+
+
+
diff --git a/trunk/Examples/test-suite/template_enum.i b/trunk/Examples/test-suite/template_enum.i
new file mode 100644
index 0000000..0d6fbf5
--- /dev/null
+++ b/trunk/Examples/test-suite/template_enum.i
@@ -0,0 +1,41 @@
+%module template_enum
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo<int>;    /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo<double>; /* Ruby, wrong class name */
+
+%inline %{
+template<class T> class foo {
+public:
+    enum { FOO, BAR };
+};
+%}
+
+%template(foo_i) foo<int>;
+%template(foo_d) foo<double>;
+
+
+%inline {
+  
+namespace Manta {
+  template<typename Traits> class ColorSpace {
+  public:
+    typedef typename Traits::ComponentType ComponentType;
+    enum { NumComponents = Traits::NumComponents};
+
+    ComponentType data[NumComponents];
+  };
+}
+
+namespace Manta {
+  class RGBTraits {
+  public:
+    typedef float ComponentType;
+    enum {NumComponents = 3};
+  };
+}
+}
+
+
+namespace Manta {
+  %template(Color) ColorSpace<RGBTraits>;
+}; 
diff --git a/trunk/Examples/test-suite/template_enum_ns_inherit.i b/trunk/Examples/test-suite/template_enum_ns_inherit.i
new file mode 100644
index 0000000..8992eef
--- /dev/null
+++ b/trunk/Examples/test-suite/template_enum_ns_inherit.i
@@ -0,0 +1,48 @@
+%module template_enum_ns_inherit
+%inline %{
+ 
+  namespace oss
+  {
+    enum Polarization { UnaryPolarization, BinaryPolarization };
+ 
+    template <Polarization P>
+    struct Interface
+    {
+    };
+
+    template <Polarization P, class C>
+    struct Module
+    {
+    };
+
+  }
+ 
+%}                                                 
+ 
+namespace oss
+{
+  %template(Interface_UP) Interface<UnaryPolarization>;
+  %template(Module_UPIUP) Module<UnaryPolarization,Interface<UnaryPolarization> >;
+}
+ 
+%inline %{
+  namespace oss
+  {
+    namespace hello
+    {
+      struct HInterface1 :
+           Interface<oss::UnaryPolarization>  // this works (with fullns qualification)
+      {
+      };
+ 
+      struct HInterface2 :
+          Interface<UnaryPolarization>       // this doesn't work
+      {
+      };
+ 
+     struct HModule1 : Module<UnaryPolarization, Interface<UnaryPolarization> > {
+ };
+
+    }
+  }
+%}                                   
\ No newline at end of file
diff --git a/trunk/Examples/test-suite/template_enum_typedef.i b/trunk/Examples/test-suite/template_enum_typedef.i
new file mode 100644
index 0000000..9752d08
--- /dev/null
+++ b/trunk/Examples/test-suite/template_enum_typedef.i
@@ -0,0 +1,39 @@
+%module template_enum_typedef
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::etraits; /* Ruby, wrong class name */
+
+%inline %{
+ 
+  namespace oss
+  {
+    enum Polarization { UnaryPolarization, BinaryPolarization };
+ 
+    template <Polarization P>
+    struct Interface
+    {
+    };
+ 
+    struct etraits
+    {
+      static const Polarization  pmode = UnaryPolarization;
+    };
+ 
+ 
+    template <class Traits>
+    struct Module
+    {
+      typedef Traits traits;
+      static const Polarization P = traits::pmode;
+ 
+      void get(Interface<P> arg) { };   // Here P is only replace by traits::pmode
+ 
+    };
+  }
+ 
+%}
+ 
+namespace oss
+{
+  %template(Interface_UP) Interface<UnaryPolarization>;
+  %template(Module_UP) Module<etraits>;
+}                                                                 
diff --git a/trunk/Examples/test-suite/template_explicit.i b/trunk/Examples/test-suite/template_explicit.i
new file mode 100644
index 0000000..ede854a
--- /dev/null
+++ b/trunk/Examples/test-suite/template_explicit.i
@@ -0,0 +1,60 @@
+/* File : example.i */
+%module "template_explicit"
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<int>;         /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<double>;      /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) vector<int (*)[10]>; /* Ruby, wrong class name */
+
+// #pragma is used for warnings that are not associated to
+// specific nodes.
+#pragma SWIG nowarn=-SWIGWARN_PARSE_EXPLICIT_TEMPLATE
+
+
+/* Let's just grab the original header file here */
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+%inline %{
+
+template<class T> T max(const T a, const T b) { return  a>b ? a : b; }
+
+template<class T> class vector {
+  T *v;
+  int sz;
+ public:
+  vector(int _sz) {
+    v = new T[_sz];
+    sz = _sz;
+  }
+  T &get(int index) {
+    return v[index];
+  }
+  void set(int index, T &val) {
+    v[index] = val;
+  }
+  // This really doesn't do anything except test const handling 
+  void testconst(const T x) { }
+};
+
+/* Explicit instantiation.  SWIG should ignore */
+template class vector<int>;
+template class vector<double>;
+template class vector<int *>;
+%}
+
+/* Now instantiate some specific template declarations */
+
+%template(maxint) max<int>;
+%template(maxdouble) max<double>;
+%template(vecint) vector<int>;
+%template(vecdouble) vector<double>;
+
+/* Now try to break constness */
+
+%template(maxintp) max<int (*)[10]>;
+%template(vecintp) vector<int (*)[10]>;
+
+
diff --git a/trunk/Examples/test-suite/template_expr.i b/trunk/Examples/test-suite/template_expr.i
new file mode 100644
index 0000000..a1bb7ef
--- /dev/null
+++ b/trunk/Examples/test-suite/template_expr.i
@@ -0,0 +1,57 @@
+%module template_expr
+
+// bug #925555
+%inline %{
+
+  template<int __stride, class __elementTypeSequence,
+    class __dataPtrType, class __elementType>
+    inline const ThisType & 
+    ConcatenationOf(const vctFixedLengthConstSequenceBase<_size - 1,
+		    __stride, __elementTypeSequence, __dataPtrType> & other,
+		    __elementType last);
+%}
+
+// bug #956282
+%inline %{
+
+  
+template<int q>
+class X {};
+
+
+%}
+
+%template(X_1) X<1>;
+%template(X_m1) X<-1>;
+%template(X_1plus2) X<1+2>;
+%template(X_1024div8) X<1024/8>;
+
+
+// bug #646275
+
+%inline %{
+    template<typename Type, short Rank>
+	typedef typename CondRetType< Rank!=1,
+		Test<Type,Rank-1>, Type>::TestRm1 TestRm1;
+%}
+
+
+// bug #994301
+
+
+%inline %{
+    template<int foo> class X994301 {};
+%}
+
+%template(X994301_ternary) X<(7 >= 4) ? 1 + 1 : 1>;
+%template(X994301_ternary2) X<(7 <= 4) ? 1 + 1 : 1>;
+
+
+// bug #1338527 (still broken)
+
+
+%inline %{
+
+  template<typename, typename> class PatchList;
+
+%}
diff --git a/trunk/Examples/test-suite/template_extend1.i b/trunk/Examples/test-suite/template_extend1.i
new file mode 100644
index 0000000..34e4f5c
--- /dev/null
+++ b/trunk/Examples/test-suite/template_extend1.i
@@ -0,0 +1,26 @@
+// One of Luigi's evil tests
+
+%module template_extend1
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Baz<long>;	// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Baz<double>;	// Ruby, wrong class name
+
+%{
+namespace Quux {
+  template <class T> class Baz {};
+}
+%}
+
+namespace Quux {  
+template <class T> class Baz {}; 
+ 
+%template (lBaz) Baz<long>; 
+%extend Baz<long> { 
+     char *foo(void) { return (char *) "lBaz::foo"; }
+} 
+ 
+%template (dBaz) Baz<double>; 
+%extend Baz<double> { 
+     char *foo(void) { return (char *) "dBaz::foo"; }
+} 
+} 
diff --git a/trunk/Examples/test-suite/template_extend2.i b/trunk/Examples/test-suite/template_extend2.i
new file mode 100644
index 0000000..b0ac6c9
--- /dev/null
+++ b/trunk/Examples/test-suite/template_extend2.i
@@ -0,0 +1,28 @@
+// Another evil Luigi test
+%module template_extend2
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Baz<long>;	// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Baz<double>;	// Ruby, wrong class name
+
+%{
+namespace Quux {  
+template <class T> class Baz {}; 
+}
+%}
+
+namespace Quux {  
+template <class T> class Baz {}; 
+
+%extend Baz<long> { 
+     char *foo(void) { return (char *) "lBaz::foo"; }
+} 
+%template (lBaz) Baz<long>; 
+
+%extend Baz<double> { 
+     char *foo(void) { return (char *) "dBaz::foo"; }
+} 
+ 
+%template (dBaz) Baz<double>; 
+} 
+
+
diff --git a/trunk/Examples/test-suite/template_extend_overload.i b/trunk/Examples/test-suite/template_extend_overload.i
new file mode 100644
index 0000000..343d7f7
--- /dev/null
+++ b/trunk/Examples/test-suite/template_extend_overload.i
@@ -0,0 +1,44 @@
+%module template_extend_overload
+
+
+%inline %{
+  template <class T>
+    struct A
+    {
+    };
+
+  template <class Arg, class Res>
+    struct B
+    {
+    };
+%}
+
+
+%define __compose_unary(Class, ArgType, ResType)
+  Class<ResType> compose(const B<ArgType, ResType>& f)
+  {
+    return Class<ResType>();
+  }
+%enddef
+
+%define __compose_unary_3(Class, Type)
+%extend Class<Type>
+{
+  __compose_unary(Class, Type, bool);
+  __compose_unary(Class, Type, double);
+  __compose_unary(Class, Type, int);
+}
+%enddef
+
+%define compose_unary(Class)
+  __compose_unary_3(Class, bool)
+  __compose_unary_3(Class, double)
+  __compose_unary_3(Class, int)
+%enddef
+
+compose_unary(A);
+  
+%template(A_double) A<double>;
+%template(A_int) A<int>;
+%template(A_bool) A<bool>;
+
diff --git a/trunk/Examples/test-suite/template_extend_overload_2.i b/trunk/Examples/test-suite/template_extend_overload_2.i
new file mode 100644
index 0000000..7121896
--- /dev/null
+++ b/trunk/Examples/test-suite/template_extend_overload_2.i
@@ -0,0 +1,121 @@
+%module template_extend_overload_2
+
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) A;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) AT;
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) BT;
+#endif
+
+%inline %{
+
+  struct A
+  {
+    A()
+    {
+    }
+    
+    A(int)
+    {
+    }
+
+    int hi()
+    {
+      return 0;
+    }
+  };
+
+  template <class T>
+  struct AT
+  {
+    AT()
+    {
+    }
+    
+    AT(int)
+    {
+    }
+
+    int hi()
+    {
+      return 0;
+    }
+  };
+
+  template <class T>
+  struct BT
+  {
+    BT()
+    {
+    }
+    
+    BT(int)
+    {
+    }
+
+    int hi()
+    {
+      return 0;
+    }
+  };
+  
+%}
+
+
+%extend A
+{
+  //
+  // this works
+  //
+
+  int hi(int)
+  {
+    return 0;
+  }
+
+  A(double i)
+  {
+    A* a = new A();
+    return a;
+  }
+}
+
+
+%template(AT_double) AT<double>;
+%extend AT<double>
+{
+  //
+  // this doesn't work
+  //
+
+  int hi(int)
+  {
+    return 1;
+  }
+  
+  AT<double>(double i)
+  {
+    AT<double>* a = new AT<double>();
+    return a;
+  }
+}
+
+
+%extend BT<double>
+{
+  //
+  // this doesn't work either
+  //
+
+  int hi(int)
+  {
+    return 1;
+  }
+  
+  BT<double>(double i)
+  {
+    BT<double>* a = new BT<double>();
+    return a;
+  }
+}
+%template(BT_double) BT<double>;
+
diff --git a/trunk/Examples/test-suite/template_forward.i b/trunk/Examples/test-suite/template_forward.i
new file mode 100644
index 0000000..5a7d44c
--- /dev/null
+++ b/trunk/Examples/test-suite/template_forward.i
@@ -0,0 +1,71 @@
+%module template_forward
+
+%{
+namespace foo {
+template<class T> class bar { };
+}
+%}
+
+namespace foo {
+   template<class T> class bar;
+};
+
+%inline %{
+namespace foo {
+   double test1(const bar<double> &x) { return 0; }
+   bar<double> test2() {
+	return bar<double>();
+   }
+}
+%}
+
+
+
+%inline {
+  // Forward declarations
+  template<class RangeScalar, class DomainScalar = RangeScalar> class LinearOpBase;
+  template<class Scalar>  class VectorBase;  
+}
+
+
+%inline {
+  // Class Describable
+  class Describable {
+  public:
+    void describe() {}
+  };
+  
+  // Class LinearOpBase
+  template<class RangeScalar, class DomainScalar> 
+    class LinearOpBase : virtual public Describable {
+    public:
+      
+    }; // end class LinearOpBase<RangeScalar,DomainScalar>
+  
+  // Class VectorBase
+  template<class Scalar>
+    class VectorBase : virtual public LinearOpBase<Scalar>
+    {
+    public:
+      using LinearOpBase<Scalar>::describe;
+    }; // end class VectorBase<Scalar>
+  
+}
+
+
+%template (LinearOpBase_double)    LinearOpBase<double>;
+%template (VectorBase_double)      VectorBase<double>;
+%template (LinearOpBase_int)    LinearOpBase<int,int>;
+%template (VectorBase_int)      VectorBase<int>;
+
+// Template forward class declarations mixing class and typename without always naming the templated parameter name
+%inline %{
+template <class> class TClass1;
+template <typename> class TClass2;
+template <class, typename> class TClass3;
+template <class, class, class> class TClass4;
+template <typename, typename> class TClass5;
+template <typename, class K = double> class TClass6;
+template<typename, class K, class C = K> class TClass7;
+%}
+
diff --git a/trunk/Examples/test-suite/template_inherit.i b/trunk/Examples/test-suite/template_inherit.i
new file mode 100644
index 0000000..9a5c948
--- /dev/null
+++ b/trunk/Examples/test-suite/template_inherit.i
@@ -0,0 +1,41 @@
+/* File : example.i */
+%module template_inherit
+
+/* This example tests template inheritance to see if it actually works */
+
+%inline %{
+
+template<class T> class Foo {
+public:
+  virtual ~Foo() { }
+  virtual char *blah() {
+       return (char *) "Foo";
+  }
+  virtual char *foomethod() {
+       return (char *) "foomethod";
+  }
+};
+
+template<class T> class Bar : public Foo<T> {
+public:
+   virtual char *blah() {
+        return (char *) "Bar";
+   }
+};
+
+template<class T> char *invoke_blah(Foo<T> *x) {
+   return x->blah();
+}
+%}
+
+%template(FooInt) Foo<int>;
+%template(FooDouble) Foo<double>;
+%template(FooUInt) Foo<unsigned int>;
+%template(BarInt) Bar<int>;
+%template(BarDouble) Bar<double>;
+%template(BarUInt) Bar<unsigned>;
+%template(invoke_blah_int) invoke_blah<int>;
+%template(invoke_blah_double) invoke_blah<double>;
+%template(invoke_blah_uint) invoke_blah<int unsigned>;
+
+
diff --git a/trunk/Examples/test-suite/template_inherit_abstract.i b/trunk/Examples/test-suite/template_inherit_abstract.i
new file mode 100644
index 0000000..f676b3b
--- /dev/null
+++ b/trunk/Examples/test-suite/template_inherit_abstract.i
@@ -0,0 +1,67 @@
+%module(ruby_minherit="1") template_inherit_abstract
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) oss::test;	/* Ruby, wrong class name */
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) oss::Module;	/* C#, Java, Php4 multiple inheritance */
+
+%inline %{ 
+ 
+  namespace oss 
+  { 
+      template <class C> 
+      struct Wrap 
+      { 
+      }; 
+ 
+      struct ModuleBase 
+      { 
+          virtual ~ModuleBase() {}
+          virtual int get() = 0; 
+      };      
+    
+      template <class C> 
+      struct Module : C, ModuleBase 
+      { 
+	virtual ~Module() {}
+
+        protected: 
+        Module() {}
+      }; 
+      
+      template <class  C> 
+      struct HModule : Module<Wrap<C> > 
+      { 
+       //  virtual int get();   // declaration here works 
+   
+      protected: 
+        HModule() {}
+      }; 
+  } 
+ 
+  struct B 
+  { 
+  }; 
+  
+%}                                                 
+  
+namespace oss 
+{ 
+  %template(Wrap_B) Wrap<B>; 
+  %template(Module_B) Module<Wrap<B> >; 
+  %template(HModule_B) HModule<B>; 
+} 
+  
+%inline %{ 
+  namespace oss 
+  { 
+#ifdef SWIGCSHARP
+%ignore HModule<B>::get(); // Work around for lack of multiple inheritance support - base ModuleBase is ignored.
+#endif
+    struct test : HModule<B> 
+    { 
+    virtual int get() {return 0;}   // declaration here breaks swig 
+    }; 
+  } 
+%}  
diff --git a/trunk/Examples/test-suite/template_int_const.i b/trunk/Examples/test-suite/template_int_const.i
new file mode 100644
index 0000000..e69a53c
--- /dev/null
+++ b/trunk/Examples/test-suite/template_int_const.i
@@ -0,0 +1,50 @@
+%module template_int_const
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) interface_traits;	/* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) module_traits;		/* Ruby, wrong class name */
+
+%inline %{ 
+  enum Polarization { UnaryPolarization, BinaryPolarization }; 
+  struct interface_traits 
+  { 
+    static const Polarization polarization = UnaryPolarization; 
+  }; 
+  template <Polarization P> 
+    struct Interface_
+    { 
+    }; 
+ 
+  typedef unsigned int Category; 
+  struct module_traits 
+  { 
+    static const Category category = 1; 
+  }; 
+  
+  template <Category C> 
+    struct Module 
+    { 
+    }; 
+%} 
+ 
+%template(Interface_UP) Interface_<UnaryPolarization>; 
+%template(Module_1) Module<1>; 
+ 
+%inline %{ 
+  struct ExtInterface1 :  
+    Interface_<UnaryPolarization> // works 
+  { 
+  }; 
+  struct ExtInterface2 : 
+    Interface_<interface_traits::polarization>  // doesn't work 
+  { 
+  }; 
+  struct ExtModule1 : 
+    Module<1>         // works 
+  { 
+  }; 
+  struct ExtModule2 : 
+    Module<module_traits::category>    // doesn't work 
+  { 
+  }; 
+%} 
+ 
diff --git a/trunk/Examples/test-suite/template_methods.i b/trunk/Examples/test-suite/template_methods.i
new file mode 100644
index 0000000..efd7e37
--- /dev/null
+++ b/trunk/Examples/test-suite/template_methods.i
@@ -0,0 +1,78 @@
+// Test %ignore and %rename for templated methods
+
+%module template_methods
+
+%warnfilter(SWIGWARN_LANG_TEMPLATE_METHOD_IGNORE) convolve1<float>();
+%warnfilter(SWIGWARN_LANG_TEMPLATE_METHOD_IGNORE) convolve3<float>();
+
+///////////////////
+%ignore convolve1<float>(float a);
+
+%inline %{
+template <typename ImageT> int convolve1() { return 0; }
+template <typename ImageT> void convolve1(ImageT a) { ImageT t = a; }
+%}
+
+%template() convolve1<float>;
+%template(convolve1Bool) convolve1<bool>;
+
+
+///////////////////
+%ignore convolve2<float>(float a);
+
+%inline %{
+template <typename ImageT> int convolve2() { return 0; }
+template <typename ImageT> void convolve2(ImageT a) { ImageT t = a; }
+%}
+
+%template(convolve2Float) convolve2<float>;
+
+///////////////////
+%rename(convolve3FloatRenamed) convolve3<float>(float a);
+
+%inline %{
+template <typename ImageT> int convolve3() { return 0; }
+template <typename ImageT> void convolve3(ImageT a) { ImageT t = a; }
+%}
+
+%template() convolve3<float>;
+
+///////////////////
+%rename(convolve4FloatRenamed) convolve4<float>(float a);
+
+%inline %{
+template <typename ImageT> int convolve4() { return 0; }
+template <typename ImageT> void convolve4(ImageT a) { ImageT t = a; }
+%}
+
+%template(convolve4Float) convolve4<float>;
+
+
+///////////////////
+%rename(convolve5FloatRenamed) convolve5<float>;
+%ignore convolve5<bool>;
+
+%inline %{
+template <typename ImageT> int convolve5() { return 0; }
+template <typename ImageT> void convolve5(ImageT a) { ImageT t = a; }
+%}
+
+%template() convolve5<float>;
+%template() convolve5<bool>;
+
+
+////////////////////////////////////////////////////////////////////////////
+%rename(KlassTMethodBoolRenamed) Klass::tmethod(bool);
+%rename(KlassStaticTMethodBoolRenamed) Klass::statictmethod(bool);
+
+%inline %{
+struct Klass {
+  template<typename X> X tmethod(X x) { return x; }
+  template<typename X> void tmethod() {}
+  template<typename X> static X statictmethod(X x) { return x; }
+  template<typename X> static void statictmethod() {}
+};
+%}
+%template(KlassTMethodBool) Klass::tmethod<bool>;
+%template(KlassStaticTMethodBool) Klass::statictmethod<bool>;
+
diff --git a/trunk/Examples/test-suite/template_ns.i b/trunk/Examples/test-suite/template_ns.i
new file mode 100644
index 0000000..77dfcd1
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns.i
@@ -0,0 +1,35 @@
+// Tests the use of the %template directive with fully
+// qualified scope names
+
+%module template_ns
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) std::my_pair<int, int>;       /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) std::my_pair<double, double>; /* Ruby, wrong class name */
+
+%ignore std::my_pair::my_pair();
+
+%inline %{
+namespace std
+{
+template <class _T1, class _T2>
+struct my_pair {
+  typedef _T1 first_type; 
+  typedef _T2 second_type;
+
+  _T1 first;              
+  _T2 second;             
+  my_pair() : first(_T1()), second(_T2()) {}
+  my_pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) {}
+  template <class _U1, class _U2>
+  my_pair(const my_pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) {}
+};
+}
+%}
+
+// Add copy constructor
+%extend std::my_pair {
+   %template(pair) my_pair<_T1,_T2>;
+};
+
+%template(pairii) std::my_pair<int,int>;
+%template(pairdd) std::my_pair<double,double>;
diff --git a/trunk/Examples/test-suite/template_ns2.i b/trunk/Examples/test-suite/template_ns2.i
new file mode 100644
index 0000000..f35d326
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns2.i
@@ -0,0 +1,16 @@
+// Tests compilation of uninstantiated templates in a namespace
+
+%module template_ns2
+
+%inline %{
+
+namespace foo {
+   template<class T> class bar {
+   };
+   bar<int> *test1(bar<int> *x) { return x; }
+   typedef int Integer;
+
+   bar<Integer *> *test2(bar<Integer *> *x) { return x; }
+}
+%}
+
diff --git a/trunk/Examples/test-suite/template_ns3.i b/trunk/Examples/test-suite/template_ns3.i
new file mode 100644
index 0000000..8df0280
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns3.i
@@ -0,0 +1,21 @@
+%module template_ns3
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo::bar<int>; /* Ruby, wrong class name */
+
+%inline %{
+namespace foo {
+   typedef int Integer;
+
+   template<class T> class bar {
+   public:
+       Integer test(Integer x) { return x; }
+   };
+
+}
+%}
+
+%template(bari) foo::bar<int>;
+
+   
+    
+
diff --git a/trunk/Examples/test-suite/template_ns4.i b/trunk/Examples/test-suite/template_ns4.i
new file mode 100644
index 0000000..34489c4
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns4.i
@@ -0,0 +1,77 @@
+%module template_ns4
+
+
+%inline %{
+    namespace hello {
+
+    class Double {
+    };
+   
+    template <class ArgType, class ResType>
+    struct Function
+    {     
+	char *test() { return (char *) "test"; }
+    };
+   
+    template <class AF, class RF>
+    struct ArithFunction : Function<AF, RF>
+    {
+    };
+   
+    template <class ArgType, class ResType>
+    struct traits
+    {
+    }; 
+
+    template <class ArgType>
+    struct traits<ArgType, double>
+    {
+      typedef ArgType arg_type;
+      typedef double res_type;
+      typedef ArithFunction<ArgType, double> base;
+    };   
+
+    template <class ArgType>
+    struct traits<ArgType, Double>
+    {
+      typedef ArgType arg_type;
+      typedef Double res_type;
+      typedef ArithFunction<ArgType, Double> base;
+    };   
+
+    template <class AF, class RF>
+    class Class : public ArithFunction< typename traits<AF, RF>::arg_type,
+                    typename traits<AF, RF>::res_type >
+    {
+    };
+ 
+    template <class AF, class RF>
+    typename traits<AF, RF>::base
+    make_Class()
+    {
+      return Class<AF, RF>();
+    }
+
+
+  }  
+%}
+
+%{  
+  namespace hello {
+    template struct Function <Double, Double>;
+    template struct ArithFunction <Double, Double>;
+    template class Class <Double, Double>;   
+  }  
+%}
+
+ namespace hello {
+  //
+  // This complains only when using a namespace
+  //
+  %template() traits<Double,Double>;
+  %template(Function_DD) Function <Double, Double>;
+  %template(ArithFunction_DD) ArithFunction <Double, Double>;
+  %template(Class_DD) Class <Double, Double>;
+  %template(make_Class_DD) make_Class <Double, Double>;
+ }
+
diff --git a/trunk/Examples/test-suite/template_ns_enum.i b/trunk/Examples/test-suite/template_ns_enum.i
new file mode 100644
index 0000000..4c73e50
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns_enum.i
@@ -0,0 +1,18 @@
+%module template_ns_enum
+%inline %{
+  namespace hello {
+    enum Hello { Hi, Hola };
+ 
+    template <Hello H>
+    struct traits
+    {
+      typedef double value_type;
+    };
+ 
+    traits<Hi>::value_type say_hi()
+    {
+      return traits<Hi>::value_type(1);
+    }
+ 
+  }
+%}                                             
diff --git a/trunk/Examples/test-suite/template_ns_enum2.i b/trunk/Examples/test-suite/template_ns_enum2.i
new file mode 100644
index 0000000..b646b3a
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns_enum2.i
@@ -0,0 +1,38 @@
+%module template_ns_enum2
+ 
+%inline %{ 
+  
+  namespace hi 
+  { 
+    enum Hello { Hi, Hola }; 
+    
+    template <Hello> 
+    struct traits 
+    { 
+    }; 
+ 
+    template <> 
+    struct traits<Hi> 
+    { 
+      typedef int value_type; 
+    }; 
+ 
+    template <> 
+    struct traits<Hola> 
+    { 
+      typedef double value_type; 
+    }; 
+    
+    struct B 
+    { 
+      const traits<Hola>::value_type& 
+          evaluate(const traits<Hola>::value_type& e) const; 
+    
+    }; 
+    const traits<Hola>::value_type&
+    B::evaluate(const traits<Hola>::value_type& e) const {
+      return e;
+    }
+  } 
+ 
+%} 
diff --git a/trunk/Examples/test-suite/template_ns_inherit.i b/trunk/Examples/test-suite/template_ns_inherit.i
new file mode 100644
index 0000000..fb33654
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns_inherit.i
@@ -0,0 +1,30 @@
+// Submitted by Marcelo Matus
+%module template_ns_inherit
+ 
+%inline %{
+  namespace hello  {
+      typedef double Double;
+  }
+  namespace hello
+  {
+    template <class ArgType, class ResType>
+    class VUnaryFunction
+    {};
+ 
+    template <class ArgType, class ResType>
+    class UnaryFunction  : public VUnaryFunction<ArgType, ResType>
+    {};
+  }
+ 
+%}
+ 
+namespace hello
+{
+  %template(VUnaryFunction_id) VUnaryFunction<int, Double>;
+  %template(UnaryFunction_id) UnaryFunction<int, Double>;
+}                                                                             
+
+
+
+
+
diff --git a/trunk/Examples/test-suite/template_ns_scope.i b/trunk/Examples/test-suite/template_ns_scope.i
new file mode 100644
index 0000000..928f628
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ns_scope.i
@@ -0,0 +1,38 @@
+%module template_ns_scope
+// Tests a scoping bug reported by Marcelo Matus.
+
+%inline %{
+  namespace hi {
+    enum Hello { Hi, Hola };
+ 
+    template <Hello h>
+    struct A
+    {
+    public:
+      A() {}    // *** Here, the const. breaks swig ***
+                // *** swig  works without it     ***
+    };
+ 
+    namespace hello
+    {
+      template <Hello H>
+      struct B : A<H>
+      {
+        int say_hi() { return 0; }
+      };
+    }
+  }
+ 
+%}
+namespace hi
+{
+  %template(A_Hi) A<Hi>;
+  namespace hello
+  {
+    %template(B_Hi) B<Hi>;
+  }
+}                                           
+
+
+
+
diff --git a/trunk/Examples/test-suite/template_opaque.i b/trunk/Examples/test-suite/template_opaque.i
new file mode 100644
index 0000000..5918fe0
--- /dev/null
+++ b/trunk/Examples/test-suite/template_opaque.i
@@ -0,0 +1,41 @@
+%module template_opaque
+%include "std_vector.i"
+
+%{
+  namespace A 
+  {
+    struct OpaqueStruct 
+    {
+    };
+  }
+
+  enum Hello { hi, hello };
+      
+%}
+
+
+%inline {
+namespace A {
+  struct OpaqueStruct;
+  typedef struct OpaqueStruct OpaqueType;
+  typedef enum Hello Hi;
+  typedef std::vector<OpaqueType> OpaqueVectorType;
+  typedef std::vector<Hi> OpaqueVectorEnum;
+  
+  void FillVector(OpaqueVectorType& v) 
+  {
+    for (size_t i = 0; i < v.size(); ++i) {
+      v[i] = OpaqueStruct();
+    }
+  }
+
+  void FillVector(const OpaqueVectorEnum& v) 
+  {
+  }
+}
+}
+
+#ifndef SWIGCSHARP
+// C# vector typemaps only ready for simple cases right now
+%template(OpaqueVectorType) std::vector<A::OpaqueType>; 
+#endif
diff --git a/trunk/Examples/test-suite/template_partial_arg.i b/trunk/Examples/test-suite/template_partial_arg.i
new file mode 100644
index 0000000..539f76f
--- /dev/null
+++ b/trunk/Examples/test-suite/template_partial_arg.i
@@ -0,0 +1,21 @@
+%module template_partial_arg
+
+%inline %{
+  template <class T> class Foo {
+  public: 
+    T bar() { return T(); }  
+    T* baz() { return 0; } 
+  };
+
+  template <class T> class Foo<T*> {
+  public: 
+    T bar() { return T(); }
+    T* baz() { return 0; }
+  };
+
+  class Bar {};
+%}
+
+%template(Foo1) Foo<Bar>;
+%template(Foo2) Foo<Bar*>;
+
diff --git a/trunk/Examples/test-suite/template_qualifier.i b/trunk/Examples/test-suite/template_qualifier.i
new file mode 100644
index 0000000..1c3b46f
--- /dev/null
+++ b/trunk/Examples/test-suite/template_qualifier.i
@@ -0,0 +1,15 @@
+%module template_qualifier
+
+/* Stroustruo, 3rd Ed, C.13.6 */
+%inline %{
+class X {
+public:
+    template<int> X *xalloc() { return new X(); }
+};
+
+%}
+
+%extend X {
+%template(xalloc_int) xalloc<200>;
+};
+
diff --git a/trunk/Examples/test-suite/template_ref_type.i b/trunk/Examples/test-suite/template_ref_type.i
new file mode 100644
index 0000000..a41d006
--- /dev/null
+++ b/trunk/Examples/test-suite/template_ref_type.i
@@ -0,0 +1,27 @@
+%module template_ref_type
+
+%inline %{
+class X {
+public:
+    unsigned _i;
+};
+
+template <class T> class Container {
+public:
+    Container () {}
+    bool reset () { return false ;}
+};
+
+typedef Container<X> XC;
+%}
+
+%template(XC) Container<X>;
+
+%inline %{
+class Y {
+public:
+    Y () {};
+    bool find (XC &) { return false; }
+};
+%}
+
diff --git a/trunk/Examples/test-suite/template_rename.i b/trunk/Examples/test-suite/template_rename.i
new file mode 100644
index 0000000..b34e260
--- /dev/null
+++ b/trunk/Examples/test-suite/template_rename.i
@@ -0,0 +1,49 @@
+%module template_rename
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Foo<int>;    /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Foo<double>; /* Ruby, wrong class name */
+
+%rename(blah_test) Foo::blah(int);
+%rename(spam_test) Foo<int>::spam(int);
+%rename(grok_test) Foo::grok(int);
+%rename(groki_test) Foo<int>::grok(int);
+
+%inline %{
+
+template<class T> class Foo {
+public:
+     int blah(int x) { return x; }
+     int spam(int x) { return x; }
+     int grok(int x) { return x; }
+};
+
+%}
+
+%template(iFoo) Foo<int>;
+%template(dFoo) Foo<double>;
+
+
+// Testing ignore
+
+%ignore std::tvector<Flow>::tvector(size_type);
+
+%inline %{
+
+namespace std {
+    
+    template<class T> class tvector {
+      public:
+        typedef size_t size_type;
+        tvector() {}
+        tvector(size_type n) { T t = T(); }
+    };
+}
+
+class Flow {
+  Flow() {}
+public:
+  Flow(double d) {}
+};
+%}
+
+%template(VectFlow) std::tvector<Flow>;
diff --git a/trunk/Examples/test-suite/template_retvalue.i b/trunk/Examples/test-suite/template_retvalue.i
new file mode 100644
index 0000000..9c15fea
--- /dev/null
+++ b/trunk/Examples/test-suite/template_retvalue.i
@@ -0,0 +1,32 @@
+%module template_retvalue
+%inline %{
+ 
+  enum Hello
+    {
+      Hi, Hola
+    };
+ 
+  struct C
+  {
+      C(int) {}
+  };
+ 
+  template <Hello>
+    class A
+    {
+    public:
+      A(int) {}
+    };
+ 
+ 
+  template <Hello h>
+    struct B
+    {
+      C get_c() { return C(0); }               // this works
+      A<h> get_a() { return A<h>(0); }         // this doesn't
+    };
+ 
+  %}
+ 
+%template(A_Hi) A<Hi>;
+%template(B_Hola) B<Hola>;                             
diff --git a/trunk/Examples/test-suite/template_specialization.i b/trunk/Examples/test-suite/template_specialization.i
new file mode 100644
index 0000000..00a0cf8
--- /dev/null
+++ b/trunk/Examples/test-suite/template_specialization.i
@@ -0,0 +1,37 @@
+%module template_specialization
+
+%rename(not1) *::operator!() const;
+%rename(negate) *::operator-() const;
+
+%inline %{
+  
+  namespace vfncs {
+    
+    template <class ArgType>
+    struct UnaryFunction 
+    {
+      UnaryFunction operator-() const { return *this; }
+    };
+
+    template <>
+    struct UnaryFunction<bool>
+    {
+      // This works
+      // UnaryFunction<bool> operator!() const;
+
+      // This doesn't
+      UnaryFunction operator!() const { return *this; }
+
+      // Does this?
+      void foo(UnaryFunction) { }
+      
+    };
+    
+  }
+%}
+
+namespace vfncs {  
+
+  %template(UnaryFunction_double) UnaryFunction<double>;  
+  %template(UnaryFunction_bool) UnaryFunction<bool>;  
+}
diff --git a/trunk/Examples/test-suite/template_specialization_defarg.i b/trunk/Examples/test-suite/template_specialization_defarg.i
new file mode 100644
index 0000000..2f664c6
--- /dev/null
+++ b/trunk/Examples/test-suite/template_specialization_defarg.i
@@ -0,0 +1,95 @@
+%module template_specialization_defarg
+
+%inline %{
+
+  template <class A, class B = double>
+    struct C
+    {
+    };
+  
+  
+  template <class BB>
+    struct C<int , BB> 
+    {
+      int hi()
+      {
+	return 0;
+      }
+
+      C(int a)
+      {
+      }
+      
+    };
+  
+
+  template <class BB>
+    struct C<double , BB> 
+    {
+      int hello()
+      {
+	return 0;
+      }
+      
+      C(double a)
+      {
+      }
+      
+    };
+
+  template <class T>
+    struct Alloc 
+    {
+    };
+  
+
+  template <class T, class A = double >
+    struct D
+    {
+      D(int){}
+    };
+
+
+  template <>
+    struct D<double>
+    {
+      D(){}
+      int foo() { return 0; }
+    };
+  
+      
+  
+  template <class T, class A = Alloc<T> >
+    struct Vector
+    {
+      Vector(int){}
+    };
+
+
+  template <>
+    struct Vector<double>
+    {
+      Vector(){}
+      int foo() { return 0; }
+    };
+  
+      
+%}
+
+
+//
+// This works fine
+//
+%template(C_i) C<int, double>;
+
+//
+// This one fails
+//
+%template(C_dd) C<double,double>;
+%template(C_d) C<double>;
+
+%template(D_i) D<int>;
+%template(D_d) D<double>;
+
+%template(Vector_i) Vector<int>;
+%template(Vector_d) Vector<double, Alloc<double> >;
diff --git a/trunk/Examples/test-suite/template_specialization_enum.i b/trunk/Examples/test-suite/template_specialization_enum.i
new file mode 100644
index 0000000..5fc51fb
--- /dev/null
+++ b/trunk/Examples/test-suite/template_specialization_enum.i
@@ -0,0 +1,63 @@
+%module template_specialization_enum
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Hello;	/* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Hi;	/* Ruby, wrong class name */
+
+
+%inline %{
+
+  enum Hello 
+  {
+    hi, hello
+  };
+  
+
+  template <Hello, class A>
+    struct C
+    {
+    };
+  
+
+  template <Hello, class BB>
+    struct Base
+    {
+    };  
+  
+  
+  template <class A>
+    struct C<hello , A>  : Base<hello, A>
+    {
+      int fhello()
+      {
+	return hello;
+      }
+      
+    protected:
+      C()
+      {
+      }
+    };
+  
+
+  template <class A>
+    struct C<hi , A> : Base<hi, A>
+    {
+      int fhi()
+      {
+	return hi;
+      }
+
+    protected:
+      C()
+      {
+      }
+    };
+  
+      
+%}
+
+%template(Base_dd) Base<hi, int>;
+%template(Base_ii) Base<hello, int>;
+
+%template(C_i) C<hi, int>;
+%template(C_d) C<hello, int>;
diff --git a/trunk/Examples/test-suite/template_static.i b/trunk/Examples/test-suite/template_static.i
new file mode 100644
index 0000000..bbca994
--- /dev/null
+++ b/trunk/Examples/test-suite/template_static.i
@@ -0,0 +1,33 @@
+%module template_static
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo<int>;    /* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) foo<double>; /* Ruby, wrong class name */
+
+%inline %{
+template<class T> class foo {
+public:
+    static int test;
+};
+template<class T> int foo<T>::test = 0;
+%}
+
+%template(foo_i) foo<int>;
+%template(foo_d) foo<double>;
+
+
+%inline %{
+namespace toto {
+  class Foo {
+  public:
+      template<class T>
+      static double bar(int i) {
+	return 1.0;
+      }
+
+    private:
+      int i;
+  };
+} 
+%}
+
+%template(bar_double) toto::Foo::bar<double>; 
diff --git a/trunk/Examples/test-suite/template_tbase_template.i b/trunk/Examples/test-suite/template_tbase_template.i
new file mode 100644
index 0000000..678a85d
--- /dev/null
+++ b/trunk/Examples/test-suite/template_tbase_template.i
@@ -0,0 +1,49 @@
+%module template_tbase_template
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) traits<Double, Double>;	/* Ruby, wrong class name */
+
+%warnfilter(SWIGWARN_PARSE_EXPLICIT_TEMPLATE);
+
+%inline %{
+  typedef double Double;
+
+ 
+  template <class ArgType, class ResType>
+  struct Funktion
+  {
+	char *test() { return (char *) "test"; }
+  };
+
+  template <class ArgType, class ResType>
+  struct traits
+  {
+    typedef ArgType arg_type;
+    typedef ResType res_type;
+    typedef Funktion<ArgType, double> base;	
+  };
+
+  // Egad!
+  template <class AF, class AG>
+  struct Class_
+    : Funktion<typename traits<AF, AG>::arg_type,
+                                typename traits<AF, AG>::res_type>
+  {
+  };
+ 
+  template <class AF, class RF>
+  typename traits<AF, RF>::base
+  make_Class()
+  {
+    return Class_<AF, RF>();
+  }
+
+%}
+%{
+  template struct Funktion <Double, Double>;
+  template struct Class_ <Double, Double>; 
+%}
+ 
+%template(traits_dd) traits <Double, Double>;
+%template(Funktion_dd) Funktion <Double, Double>;
+%template(Class_dd) Class_ <Double, Double>;
+%template(make_Class_dd) make_Class<Double,Double>;
diff --git a/trunk/Examples/test-suite/template_template_parameters.i b/trunk/Examples/test-suite/template_template_parameters.i
new file mode 100644
index 0000000..0c39896
--- /dev/null
+++ b/trunk/Examples/test-suite/template_template_parameters.i
@@ -0,0 +1,39 @@
+%module template_template_parameters
+
+
+%inline %{
+  namespace pfc {
+    template<typename t_item, template <typename> class t_alloc> class array_t {};
+    template<typename t_item> class alloc_fast {
+      public:
+        typedef t_item alloc_type;
+    };
+  }
+
+  template<typename t_item, typename t2> class list_impl_t {};
+
+  template<typename t_item, template<typename> class t_alloc = pfc::alloc_fast >
+    class list_t : public list_impl_t<t_item,pfc::array_t<t_item,t_alloc> > { 
+  public:
+    t_item item;
+//    typename t_alloc<t_item>::alloc_type allotype; // SWIG can't handle this yet
+    void xx() {
+      typename t_alloc<t_item>::alloc_type atype; // this type is the same as t_item type
+      atype = true;
+    }
+  };
+
+void TestInstantiations() {
+  pfc::array_t<int, pfc::alloc_fast> myArrayInt;
+  list_impl_t<int, pfc::array_t<int, pfc::alloc_fast> > myListImplInt;
+  (void) myArrayInt;
+  (void) myListImplInt;
+}
+%}
+
+%template(ListImplFastBool) list_impl_t<bool, pfc::array_t<bool, pfc::alloc_fast> >;
+%template(ListFastBool) list_t<bool, pfc::alloc_fast>;
+
+%template(ListImplFastDouble) list_impl_t<double, pfc::array_t<double, pfc::alloc_fast> >;
+%template(ListDefaultDouble) list_t<double>;
+
diff --git a/trunk/Examples/test-suite/template_type_namespace.i b/trunk/Examples/test-suite/template_type_namespace.i
new file mode 100644
index 0000000..ec94cd0
--- /dev/null
+++ b/trunk/Examples/test-suite/template_type_namespace.i
@@ -0,0 +1,14 @@
+%module template_type_namespace
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) std::vector<std::string>;	// Ruby, wrong class name
+
+%include std_string.i
+%include std_vector.i
+ 
+%template(string_vector) std::vector<std::string>;
+ 
+%inline %{
+     std::vector<std::string> foo() {
+         return std::vector<std::string>(1,"foo");
+     }
+%}                                                  
diff --git a/trunk/Examples/test-suite/template_typedef.i b/trunk/Examples/test-suite/template_typedef.i
new file mode 100644
index 0000000..b6128e1
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef.i
@@ -0,0 +1,179 @@
+#ifdef SWIGPYTHON
+%module("templatereduce") template_typedef
+#else
+%module template_typedef
+#endif
+//
+// Change this to #if 1 to test the 'test'
+//
+#if 0
+
+#define reald double
+%{
+#define reald double
+%}
+
+#else
+
+%inline %{
+  typedef double reald;
+%}
+
+#endif
+
+
+%inline %{
+
+  //  typedef double reald;
+
+  namespace vfncs {
+
+    struct UnaryFunctionBase
+    {
+    };    
+    
+    template <class ArgType, class ResType>
+    struct UnaryFunction;
+    
+    template <class ArgType, class ResType>
+    struct ArithUnaryFunction;  
+    
+    template <class ArgType, class ResType>
+    struct UnaryFunction : UnaryFunctionBase
+    {
+    };
+
+    template <class ArgType, class ResType>
+    struct ArithUnaryFunction : UnaryFunction<ArgType, ResType>
+    {
+    };      
+    
+    template <class ArgType, class ResType>         
+    struct unary_func_traits 
+    {
+      typedef ArithUnaryFunction<ArgType, ResType > base;
+    };
+  
+    template <class ArgType>
+    inline
+    typename unary_func_traits< ArgType, ArgType >::base
+    make_Identity()
+    {
+      return typename unary_func_traits< ArgType, ArgType >::base();
+    }
+
+    template <class Arg1, class Arg2>
+    struct arith_traits 
+    {
+    };
+
+    template<>
+    struct arith_traits< float, float >
+    {
+    
+      typedef float argument_type;
+      typedef float result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template<>
+    struct arith_traits< reald, reald >
+    {
+    
+      typedef reald argument_type;
+      typedef reald result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template<>
+    struct arith_traits< reald, float >
+    {
+      typedef float argument_type;
+      typedef reald result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template<>
+    struct arith_traits< float, reald >
+    {
+      typedef float argument_type;
+      typedef reald result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template <class AF, class RF, class AG, class RG>
+    inline
+    ArithUnaryFunction<typename arith_traits< AF, AG >::argument_type,
+		       typename arith_traits< RF, RG >::result_type >
+    make_Multiplies(const ArithUnaryFunction<AF, RF>& f,
+		    const ArithUnaryFunction<AG, RG >& g)
+    {
+      return 
+	ArithUnaryFunction<typename arith_traits< AF, AG >::argument_type,
+	                   typename arith_traits< RF, RG >::result_type>();
+    }
+
+#ifndef SWIG
+
+    // Initialize these static class members
+
+    const char* const arith_traits< float, float >::arg_type = "float";
+    const char* const arith_traits< float, float >::res_type = "float";
+
+    const char* const arith_traits< reald, reald >::arg_type = "reald";
+    const char* const arith_traits< reald, reald >::res_type = "reald";
+
+    const char* const arith_traits< reald, float >::arg_type = "float";
+    const char* const arith_traits< reald, float >::res_type = "reald";
+
+    const char* const arith_traits< float, reald >::arg_type = "float";
+    const char* const arith_traits< float, reald >::res_type = "reald";
+
+#endif
+
+  }
+%}
+
+namespace vfncs {  
+  %template(UnaryFunction_float_float) UnaryFunction<float, float >;  
+  %template(ArithUnaryFunction_float_float) ArithUnaryFunction<float, float >;  
+  %template() unary_func_traits<float, float >;
+  %template() arith_traits<float, float >;
+  %template(make_Identity_float) make_Identity<float >;
+
+  %template(UnaryFunction_reald_reald) UnaryFunction<reald, reald >;  
+  %template(ArithUnaryFunction_reald_reald) ArithUnaryFunction<reald, reald >;  
+
+  %template() unary_func_traits<reald, reald >;
+  %template() arith_traits<reald, reald >;
+  %template(make_Identity_reald) make_Identity<reald >;
+
+  /* [beazley] Added this part */
+  %template() unary_func_traits<float,reald>;
+  %template(UnaryFunction_float_reald) UnaryFunction<float,reald>;
+  %template(ArithUnaryFunction_float_reald) ArithUnaryFunction<float,reald>;
+
+  /* */
+
+  %template() arith_traits<reald, float >;
+  %template() arith_traits<float, reald >;
+  %template() arith_traits<float, float >;
+
+  %template(make_Multiplies_float_float_reald_reald)
+    make_Multiplies<float, float, reald, reald>;
+
+  %template(make_Multiplies_float_float_float_float)
+    make_Multiplies<float, float, float, float>;
+
+  %template(make_Multiplies_reald_reald_reald_reald)
+    make_Multiplies<reald, reald, reald, reald>;
+
+}
+
+#ifdef SWIGPYTHON
+swig_type_info *SWIG_TypeQuery(const char* name);
+#endif
diff --git a/trunk/Examples/test-suite/template_typedef_cplx.i b/trunk/Examples/test-suite/template_typedef_cplx.i
new file mode 100644
index 0000000..dcf311a
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_cplx.i
@@ -0,0 +1,178 @@
+%module template_typedef_cplx
+
+//
+// Change this to #if 1 to test the 'test'
+//
+#if 0
+
+%{
+#include <complex>
+typedef std::complex<double> cmplx;
+%}
+  
+%inline %{
+  typedef cmplx Complex;
+%}
+
+#else
+
+%inline %{
+#include <complex>
+  typedef std::complex<double> Complex;
+%}
+
+#endif
+
+
+%inline %{
+
+  namespace vfncs {
+
+    struct UnaryFunctionBase
+    {
+    };    
+    
+    template <class ArgType, class ResType>
+    struct UnaryFunction;
+    
+    template <class ArgType, class ResType>
+    struct ArithUnaryFunction;  
+    
+    template <class ArgType, class ResType>
+    struct UnaryFunction : UnaryFunctionBase
+    {
+    };
+
+    template <class ArgType, class ResType>
+    struct ArithUnaryFunction : UnaryFunction<ArgType, ResType>
+    {
+    };      
+    
+    template <class ArgType, class ResType>         
+    struct unary_func_traits 
+    {
+      typedef ArithUnaryFunction<ArgType, ResType > base;
+    };
+  
+    template <class ArgType>
+    inline
+    typename unary_func_traits< ArgType, ArgType >::base
+    make_Identity()
+    {
+      return typename unary_func_traits< ArgType, ArgType >::base();
+    }
+
+    template <class Arg1, class Arg2>
+    struct arith_traits 
+    {
+    };
+
+    template<>
+    struct arith_traits< double, double >
+    {
+    
+      typedef double argument_type;
+      typedef double result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template<>
+    struct arith_traits< Complex, Complex >
+    {
+    
+      typedef Complex argument_type;
+      typedef Complex result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template<>
+    struct arith_traits< Complex, double >
+    {
+      typedef double argument_type;
+      typedef Complex result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template<>
+    struct arith_traits< double, Complex >
+    {
+      typedef double argument_type;
+      typedef Complex result_type;
+      static const char* const arg_type;
+      static const char* const res_type;
+    };
+
+    template <class AF, class RF, class AG, class RG>
+    inline
+    ArithUnaryFunction<typename arith_traits< AF, AG >::argument_type,
+		       typename arith_traits< RF, RG >::result_type >
+    make_Multiplies(const ArithUnaryFunction<AF, RF>& f,
+		    const ArithUnaryFunction<AG, RG >& g)
+    {
+      return 
+	ArithUnaryFunction<typename arith_traits< AF, AG >::argument_type,
+	                   typename arith_traits< RF, RG >::result_type>();
+    }
+
+#ifndef SWIG
+
+    // Initialize these static class members
+
+    const char* const arith_traits< double, double >::arg_type = "double";
+    const char* const arith_traits< double, double >::res_type = "double";
+
+    const char* const arith_traits< Complex, Complex >::arg_type = "complex";
+    const char* const arith_traits< Complex, Complex >::res_type = "complex";
+
+    const char* const arith_traits< Complex, double>::arg_type = "double";
+    const char* const arith_traits< Complex, double >::res_type = "complex";
+
+    const char* const arith_traits< double, Complex >::arg_type = "double";
+    const char* const arith_traits< double, Complex >::res_type = "complex";
+
+#endif
+
+  }
+%}
+
+namespace vfncs {  
+  %template(UnaryFunction_double_double) UnaryFunction<double, double >;  
+  %template(ArithUnaryFunction_double_double) ArithUnaryFunction<double, double >;  
+  %template() unary_func_traits<double, double >;
+  %template() arith_traits<double, double >;
+  %template(make_Identity_double) make_Identity<double >;
+
+  %template(UnaryFunction_complex_complex) UnaryFunction<Complex, Complex >;  
+  %template(ArithUnaryFunction_complex_complex) ArithUnaryFunction<Complex, Complex >;  
+
+  %template() unary_func_traits<Complex, Complex >;
+  %template() arith_traits<Complex, Complex >;
+  %template(make_Identity_complex) make_Identity<Complex >;
+
+  /* [beazley] Added this part */
+  %template() unary_func_traits<double,Complex>;
+  %template(UnaryFunction_double_complex) UnaryFunction<double,Complex>;
+  %template(ArithUnaryFunction_double_complex) ArithUnaryFunction<double,Complex>;
+
+  /* */
+
+  %template() arith_traits<Complex, double >;
+  %template() arith_traits<double, Complex >;
+
+  %template(make_Multiplies_double_double_complex_complex)
+    make_Multiplies<double, double, Complex, Complex>;
+
+  %template(make_Multiplies_double_double_double_double)
+    make_Multiplies<double, double, double, double>;
+
+  %template(make_Multiplies_complex_complex_complex_complex)
+    make_Multiplies<Complex, Complex, Complex, Complex>;
+
+  %template(make_Multiplies_complex_complex_double_double)
+    make_Multiplies<Complex, Complex, double, double>;
+
+}
+
diff --git a/trunk/Examples/test-suite/template_typedef_cplx2.h b/trunk/Examples/test-suite/template_typedef_cplx2.h
new file mode 100644
index 0000000..17d0652
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_cplx2.h
@@ -0,0 +1,175 @@
+#ifndef ___typedef_import_h__
+#define ___typedef_import_h__
+
+#ifdef SWIG
+%module template_typedef_cplx2;
+#endif
+
+#include <complex>
+typedef std::complex<double> Complex;
+
+namespace vfncs {
+
+  struct UnaryFunctionBase
+  {
+    int get_base_value()
+    {
+      return 0;
+    }
+  };    
+    
+  template <class ArgType, class ResType>
+  struct UnaryFunction;
+    
+  template <class ArgType, class ResType>
+  struct ArithUnaryFunction;  
+    
+  template <class ArgType, class ResType>
+  struct UnaryFunction : UnaryFunctionBase
+  {
+    int get_value()
+    {
+      return 1;
+    }
+  };
+
+  template <class ArgType, class ResType>
+  struct ArithUnaryFunction : UnaryFunction<ArgType, ResType>
+  {
+    int get_arith_value()
+    {
+      return 2;
+    }
+  };      
+    
+  template <class ArgType, class ResType>         
+  struct unary_func_traits 
+  {
+    typedef ArithUnaryFunction<ArgType, ResType > base;
+  };
+  
+  template <class ArgType>
+  inline
+  typename unary_func_traits< ArgType, ArgType >::base
+  make_Identity()
+  {
+    return typename unary_func_traits< ArgType, ArgType >::base();
+  }
+
+  template <class Arg1, class Arg2>
+  struct arith_traits 
+  {
+  };
+
+  template<>
+  struct arith_traits< double, double >
+  {    
+    typedef double argument_type;
+    typedef double result_type;
+    static const char* const arg_type;
+    static const char* const res_type;
+  };
+
+  template<>
+  struct arith_traits< Complex, Complex >
+  {
+    
+    typedef Complex argument_type;
+    typedef Complex result_type;
+    static const char* const arg_type;
+    static const char* const res_type;
+  };
+
+  template<>
+  struct arith_traits< Complex, double >
+  {
+    typedef double argument_type;
+    typedef Complex result_type;
+    static const char* const arg_type;
+    static const char* const res_type;
+  };
+
+  template<>
+  struct arith_traits< double, Complex >
+  {
+    typedef double argument_type;
+    typedef Complex result_type;
+    static const char* const arg_type;
+    static const char* const res_type;
+  };
+
+  template <class AF, class RF, class AG, class RG>
+  inline
+  ArithUnaryFunction<typename arith_traits< AF, AG >::argument_type,
+		     typename arith_traits< RF, RG >::result_type >
+  make_Multiplies(const ArithUnaryFunction<AF, RF>& f,
+		  const ArithUnaryFunction<AG, RG >& g)
+  {
+    return 
+      ArithUnaryFunction<typename arith_traits< AF, AG >::argument_type,
+      typename arith_traits< RF, RG >::result_type>();
+  }
+
+#ifndef SWIG
+
+// Initialize these static class members
+
+const char* const arith_traits< double, double >::arg_type = "double";
+const char* const arith_traits< double, double >::res_type = "double";
+
+const char* const arith_traits< Complex, Complex >::arg_type = "complex";
+const char* const arith_traits< Complex, Complex >::res_type = "complex";
+
+const char* const arith_traits< Complex, double >::arg_type = "double";
+const char* const arith_traits< Complex, double >::res_type = "complex";
+
+const char* const arith_traits< double, Complex >::arg_type = "double";
+const char* const arith_traits< double, Complex >::res_type = "complex";
+
+#endif
+
+} // end namespace vfncs
+
+#ifdef SWIG
+
+namespace vfncs {
+  %template(UnaryFunction_double_double) UnaryFunction<double, double >;  
+  %template(ArithUnaryFunction_double_double) ArithUnaryFunction<double, double >;  
+  %template() unary_func_traits<double, double >;
+  %template() arith_traits<double, double >;
+  %template(make_Identity_double) make_Identity<double >;
+
+  %template(UnaryFunction_complex_complex) UnaryFunction<Complex, Complex >;  
+  %template(ArithUnaryFunction_complex_complex) ArithUnaryFunction<Complex, Complex >;  
+
+  %template() unary_func_traits<Complex, Complex >;
+  %template() arith_traits<Complex, Complex >;
+  %template(make_Identity_complex) make_Identity<Complex >;
+
+  /* [beazley] Added this part */
+  %template() unary_func_traits<double,Complex>;
+  %template(UnaryFunction_double_complex) UnaryFunction<double,Complex>;
+  %template(ArithUnaryFunction_double_complex) ArithUnaryFunction<double,Complex>;
+
+  /* */
+
+  %template() arith_traits<Complex, double >;
+  %template() arith_traits<double, Complex >;
+
+  %template(make_Multiplies_double_double_complex_complex)
+    make_Multiplies<double, double, Complex, Complex>;
+
+  %template(make_Multiplies_double_double_double_double)
+    make_Multiplies<double, double, double, double>;
+
+  %template(make_Multiplies_complex_complex_complex_complex)
+    make_Multiplies<Complex, Complex, Complex, Complex>;
+
+  %template(make_Multiplies_complex_complex_double_double)
+    make_Multiplies<Complex, Complex, double, double>;
+
+}
+
+#endif
+
+#endif //___template_typedef_h__
diff --git a/trunk/Examples/test-suite/template_typedef_cplx2.i b/trunk/Examples/test-suite/template_typedef_cplx2.i
new file mode 100644
index 0000000..6f99e89
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_cplx2.i
@@ -0,0 +1,7 @@
+%module template_typedef_cplx2
+
+%{
+#include "template_typedef_cplx2.h"
+%}
+
+%include "template_typedef_cplx2.h"
diff --git a/trunk/Examples/test-suite/template_typedef_cplx3.i b/trunk/Examples/test-suite/template_typedef_cplx3.i
new file mode 100644
index 0000000..71fcf5e
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_cplx3.i
@@ -0,0 +1,37 @@
+%module template_typedef_cplx3
+%{
+#include "template_typedef_cplx2.h"
+%}
+
+%include "template_typedef_cplx2.h"
+
+%inline %{
+
+  typedef vfncs::ArithUnaryFunction<double, double> RFunction;
+  typedef vfncs::ArithUnaryFunction<Complex, Complex> CFunction;
+  
+
+  int my_func_r(RFunction* hello)
+    {
+      return 0;
+    }
+  
+  int my_func_c(CFunction* hello)
+    {
+      return 1;
+    }  
+
+  struct Sin : RFunction
+  {
+  };  
+
+  struct CSin : CFunction
+  {
+  };  
+  
+%}
+
+  
+
+
+
diff --git a/trunk/Examples/test-suite/template_typedef_cplx4.i b/trunk/Examples/test-suite/template_typedef_cplx4.i
new file mode 100644
index 0000000..a2457ac
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_cplx4.i
@@ -0,0 +1,44 @@
+%module template_typedef_cplx4
+%{
+#include "template_typedef_cplx2.h"
+%}
+
+%include "template_typedef_cplx2.h"
+
+%inline %{
+
+  typedef vfncs::ArithUnaryFunction<double, double> RFunction;
+  // **** these two work ****
+  // typedef vfncs::ArithUnaryFunction<Complex, Complex > CFunction;
+  // typedef vfncs::ArithUnaryFunction<std::complex<double>, std::complex<double> > CFunction;
+  
+  // **** these ones don't ***
+  // typedef vfncs::ArithUnaryFunction<Complex, std::complex<double> > CFunction;
+  typedef vfncs::ArithUnaryFunction<std::complex<double>, Complex > CFunction;
+
+
+
+  int my_func_r(RFunction* hello)
+    {
+      return 0;
+    }
+  
+  int my_func_c(CFunction* hello)
+    {
+      return 1;
+    }  
+
+  struct Sin : RFunction
+  {
+  };  
+
+  struct CSin : CFunction
+  {
+  };  
+  
+%}
+
+  
+
+
+
diff --git a/trunk/Examples/test-suite/template_typedef_cplx5.i b/trunk/Examples/test-suite/template_typedef_cplx5.i
new file mode 100644
index 0000000..84b09fd
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_cplx5.i
@@ -0,0 +1,22 @@
+%module template_typedef_cplx5
+
+%{
+#include <complex>
+%}
+
+
+%inline %{
+
+  // This typedef triggers an inifinite recursion
+  // in the next test1() nd test2() function declarations
+
+  typedef std::complex<double> complex;  
+
+  struct A 
+  {
+    complex test1() { complex r; return r; }
+    std::complex<double> test2() { std::complex<double> r; return r; }
+  };
+  
+%}
+
diff --git a/trunk/Examples/test-suite/template_typedef_fnc.i b/trunk/Examples/test-suite/template_typedef_fnc.i
new file mode 100644
index 0000000..d0444d1
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_fnc.i
@@ -0,0 +1,14 @@
+%module template_typedef_fnc
+
+%include "std_vector.i"
+namespace std {
+   %template(IntVector) vector<int>;
+};
+
+%inline 
+{
+  typedef void (*RtMidiCallback)(std::vector<int> *message);
+
+  void setCallback( RtMidiCallback callback) {
+  }
+}
diff --git a/trunk/Examples/test-suite/template_typedef_funcptr.i b/trunk/Examples/test-suite/template_typedef_funcptr.i
new file mode 100644
index 0000000..0175c75
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_funcptr.i
@@ -0,0 +1,48 @@
+%module template_typedef_funcptr
+
+//Bug #1832613
+
+%include <std_string.i>
+
+%inline %{
+
+#include <string>
+
+template<typename T> class Ptr {};
+ 
+class MCContract {};
+typedef Ptr<MCContract> MCContractPtr;
+%}
+
+%template() Ptr<MCContract>;
+
+%inline %{
+template <class Contract, typename ContractID, typename CallbackType>
+class ContractFactory 
+{
+  public:
+    static ContractFactory<Contract,ContractID,CallbackType> &getInstance() {
+      static ContractFactory<Contract, ContractID, CallbackType> instance;
+      return instance;
+    }
+};
+/**
+ * CreateXXContractCallback is a pointer to a function taking no arguments and 
+ * returning a pointer to an XXContract. 
+ */
+typedef MCContractPtr (*CreateMCContractCallback)();
+%}
+
+
+//Get around it by changing this:
+%template(MCContractFactory) ContractFactory<MCContract, std::string, CreateMCContractCallback>;
+
+//to a form which expands the typedef:
+//%template(MCContractFactory) ContractFactory<MCContract, std::string, Ptr<MCContract>(*)()>;
+
+%inline %{
+typedef MCContractPtr* ContractPtrPtr;
+%}
+// Plain pointers were also causing problems...
+%template(MCContractFactory2) ContractFactory<MCContract, std::string, ContractPtrPtr>;
+
diff --git a/trunk/Examples/test-suite/template_typedef_import.i b/trunk/Examples/test-suite/template_typedef_import.i
new file mode 100644
index 0000000..10bc617
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_import.i
@@ -0,0 +1,37 @@
+%module template_typedef_import
+%{
+#include "template_typedef_cplx2.h"
+%}
+
+%import "template_typedef_cplx2.h"
+
+%inline %{
+
+  typedef vfncs::ArithUnaryFunction<double, double> RFunction;
+  typedef vfncs::ArithUnaryFunction<Complex, Complex> CFunction;
+  
+
+  int my_func_r(RFunction* hello)
+    {
+      return 0;
+    }
+  
+  int my_func_c(CFunction* hello)
+    {
+      return 1;
+    }  
+
+  struct Sin : RFunction
+  {
+  };  
+
+  struct CSin : CFunction
+  {
+  };  
+  
+%}
+
+  
+
+
+
diff --git a/trunk/Examples/test-suite/template_typedef_import.list b/trunk/Examples/test-suite/template_typedef_import.list
new file mode 100644
index 0000000..c7622b4
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_import.list
@@ -0,0 +1,2 @@
+template_typedef_cplx2
+template_typedef_import
diff --git a/trunk/Examples/test-suite/template_typedef_ns.i b/trunk/Examples/test-suite/template_typedef_ns.i
new file mode 100644
index 0000000..a386284
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_ns.i
@@ -0,0 +1,18 @@
+%module("templatereduce") template_typedef_ns
+
+%inline {
+  namespace Alpha {
+    typedef int Integer;
+  }
+  
+  namespace Beta {
+    template <typename Value>
+    struct Alpha {
+      Value x;
+    };
+  }
+}
+
+
+%template(AlphaInt) Beta::Alpha<Alpha::Integer>;
+
diff --git a/trunk/Examples/test-suite/template_typedef_ptr.i b/trunk/Examples/test-suite/template_typedef_ptr.i
new file mode 100644
index 0000000..9f9a29a
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_ptr.i
@@ -0,0 +1,38 @@
+%module("templatereduce") template_typedef_ptr
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Test<int, C*>; /* Ruby, wrong constant name */
+
+ /*
+   Use the "templatereduce" feature to force swig to reduce the template
+   typedef as much as possible.
+
+   This fixes cases like this one, but it can prevent some
+   typemaps from working.
+ */
+
+%inline %{
+ struct C{};
+ typedef C* pC;
+
+ template <class A, class B>
+   struct Test 
+   {
+     Test (A a, B b)
+     {
+     }
+     
+   };
+
+ 
+ template <class A, class B>
+   struct Test<A, B*> 
+   {
+     Test (B* a)
+     {
+     }
+     
+   };
+%}
+
+  
+%template(test_pC) Test<int, pC>;
diff --git a/trunk/Examples/test-suite/template_typedef_rec.i b/trunk/Examples/test-suite/template_typedef_rec.i
new file mode 100644
index 0000000..abdf113
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typedef_rec.i
@@ -0,0 +1,113 @@
+%module template_typedef_rec
+
+%inline %{
+// --- includes required to compile the wrapper code ---
+typedef size_t MY_sizeT;
+typedef long MY_intT;
+typedef double MY_floatT;
+
+class test_Array
+{
+public:
+  typedef MY_intT    intT;
+  typedef MY_sizeT   sizeT;
+};
+
+
+
+template <typename T>
+class ArrayIterator_
+{
+ public:
+  typedef test_Array::intT    intT;
+};
+
+
+template <typename T>
+class ArrayReverseIterator
+{
+ public:
+  typedef test_Array::intT    intT;
+};
+
+
+template <typename T>
+class ArrayPrimitiveT 
+  : public test_Array
+{
+public:
+  typedef T  ValueT;
+  typedef T  valueT;
+  typedef ArrayIterator_<T>       Iterator;
+  typedef ArrayIterator_<const T> ConstIterator;  
+  typedef ArrayReverseIterator<T>       ReverseIterator;
+  typedef ArrayReverseIterator<const T> ConstReverseIterator;
+};
+
+
+template <class T>
+class TreeNode
+{
+public:
+  typedef T  ValueT;
+  typedef T  valueT;
+  typedef MY_intT    intT;
+  typedef MY_sizeT   sizeT;
+};
+
+template <class T>
+struct ArrayPointerT
+{
+};
+
+template <class T>
+class TreeIterator
+{
+public:  
+  typedef MY_intT    intT;
+  typedef MY_sizeT   sizeT;
+  typedef ArrayPointerT< T* > NodeArrayT;
+  
+};
+
+
+template <class T>
+class Tree
+{
+public:
+  typedef T  ValueT;
+  typedef T  valueT;
+  typedef MY_intT    intT;
+  typedef MY_sizeT   sizeT;
+  typedef TreeNode<T> NodeT;
+  typedef ArrayPointerT< NodeT* > NodeArrayT;
+  typedef TreeIterator<NodeT> Iterator;
+  typedef TreeIterator<NodeT> ConstIterator;
+ 
+
+};
+
+
+class ModelNode
+{
+  typedef MY_intT    intT;
+  typedef MY_floatT  floatT;
+  typedef MY_sizeT   sizeT;
+  
+  
+};
+
+class Model
+{
+  typedef MY_intT    intT;
+  typedef MY_sizeT   sizeT;
+  typedef Tree<ModelNode> TreeT;
+  typedef TreeT::NodeT  TreeNodeT;
+  typedef TreeT::Iterator TreeIteratorT;
+  
+};
+%}
+
+
+// --- define ANSI C/C++ declarations to be interfaced ---
+%template(ModelTree)  Tree<ModelNode>;
diff --git a/trunk/Examples/test-suite/template_typemaps.i b/trunk/Examples/test-suite/template_typemaps.i
new file mode 100644
index 0000000..92968e5
--- /dev/null
+++ b/trunk/Examples/test-suite/template_typemaps.i
@@ -0,0 +1,62 @@
+%module template_typemap
+
+
+%typemap(in) Integer1 
+{
+  /* do nothing */
+}
+
+%typemap(out) Integer1 
+{
+  /* do nothing */
+}
+
+%typemap(in) Integer2 
+{
+  /* do nothing */
+}
+
+%typemap(out) Integer2 
+{
+  /* do nothing */
+}
+
+%{
+  typedef int Integer1;
+%}
+
+
+%inline %{
+  typedef int Integer2;
+
+  template <class T>
+    struct Foo 
+    {
+      T val;
+      
+      T get_val() const 
+      {
+	return val;
+      }
+
+      void set_val(T v) 
+      {
+	val = v;
+      }
+
+#ifdef SWIG
+       %typemap(in) Foo* "/* in typemap for Foo, with type T */" 
+#endif
+    };  
+%}
+
+%template(Foo_I1) Foo<Integer1>;
+%template(Foo_I2) Foo<Integer2>;
+
+%inline %{
+  int bar(Foo<Integer1> *foo) {
+    return 0;
+  }  
+%}
+
+  
diff --git a/trunk/Examples/test-suite/template_using.i b/trunk/Examples/test-suite/template_using.i
new file mode 100644
index 0000000..cb98dda
--- /dev/null
+++ b/trunk/Examples/test-suite/template_using.i
@@ -0,0 +1,17 @@
+%module template_using
+
+%inline 
+{
+  
+namespace foo {
+  template<typename T> class Foo { };
+  template<typename T> T maxk(T a, T b) { return a > b ? a : b; }
+}
+using foo::maxk;
+ 
+}
+
+%template(maxint)   foo::maxk<int>;   
+%template(Foofloat) foo::Foo<float>;
+%template(maxfloat) maxk<float>;    
+
diff --git a/trunk/Examples/test-suite/template_virtual.i b/trunk/Examples/test-suite/template_virtual.i
new file mode 100644
index 0000000..8c844f9
--- /dev/null
+++ b/trunk/Examples/test-suite/template_virtual.i
@@ -0,0 +1,34 @@
+%module template_virtual
+
+// Submitted by Marcelo Matus  
+// assertion emmitted with templates + derivation + pure virtual member
+// allocate.cxx:47: int Allocate::is_abstract_inherit(Node*, Node*):
+// Assertion `dn' failed.
+ 
+%inline %{
+ 
+    template <class T>
+    class A
+    {
+    public:
+      virtual ~A() { }
+
+      virtual void say_hi() = 0; // only fails with pure virtual methods
+ 
+      virtual void say_hello() {} // this works fine
+ 
+    protected:
+      A() { }  // defined protected as swig generates constructor by default
+    };
+ 
+    template <class T>
+    class B : public A<T>
+    {
+    protected:
+      B() { } // defined protected as swig generates constructor by default
+    };
+ 
+%}
+ 
+%template(A_int) A<int>;
+%template(B_int) B<int>;  // !!!! it crashes right here !!!!!                       
diff --git a/trunk/Examples/test-suite/template_whitespace.i b/trunk/Examples/test-suite/template_whitespace.i
new file mode 100644
index 0000000..f00b9e8
--- /dev/null
+++ b/trunk/Examples/test-suite/template_whitespace.i
@@ -0,0 +1,22 @@
+/* This interface file tests whether whitespace in angle brackets
+   affects the SWIG types. SF Bug #221917, reported by
+   burchanb@cs.tamu.edu. */
+
+%module template_whitespace
+
+%{
+template<class T> class vector {
+};
+template<class T, class U> class map {
+};
+%}
+
+//%typemap(in) vector<int> "$target = new vector<int>();";
+//%typemap(in) vector<unsigned int> "$target = new vector<unsigned int>();";
+//%typemap(in) map<int,int> "$target = new map<int, int>();";
+
+%inline %{
+void foo(vector<int > v) {}
+void bar(vector<unsigned  int> v) {}
+void baz(map < int , int > p) {}
+%}
diff --git a/trunk/Examples/test-suite/testdir/subdir1/hello.i b/trunk/Examples/test-suite/testdir/subdir1/hello.i
new file mode 100644
index 0000000..75d0ec4
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/subdir1/hello.i
@@ -0,0 +1,24 @@
+#ifndef subdir1_hello_i_
+#define subdir1_hello_i_
+
+%{
+typedef int Integer;
+%}
+
+%inline %{
+
+  struct A
+  {  
+    int aa;
+  };
+
+  Integer importtest1(Integer i) {
+    return i + 10;
+  }
+
+%}
+  
+
+
+
+#endif //subdir1_hello_i_
diff --git a/trunk/Examples/test-suite/testdir/subdir1/imports.i b/trunk/Examples/test-suite/testdir/subdir1/imports.i
new file mode 100644
index 0000000..4c35991
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/subdir1/imports.i
@@ -0,0 +1,6 @@
+#ifndef subdir1_imports_i_
+#define subdir1_imports_i_
+
+typedef int Integer;
+
+#endif //subdir1_imports_i_
diff --git a/trunk/Examples/test-suite/testdir/subdir1/subinc1.i b/trunk/Examples/test-suite/testdir/subdir1/subinc1.i
new file mode 100644
index 0000000..e023b4c
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/subdir1/subinc1.i
@@ -0,0 +1,5 @@
+// %include twice to check include header guards
+%include "hello.i"
+%include "hello.i"
+%import "imports.i"
+%import "imports.i"
diff --git a/trunk/Examples/test-suite/testdir/subdir2/hello.i b/trunk/Examples/test-suite/testdir/subdir2/hello.i
new file mode 100644
index 0000000..ed172b1
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/subdir2/hello.i
@@ -0,0 +1,24 @@
+#ifndef subdir2_hello_i_
+#define subdir2_hello_i_
+
+%{
+typedef char * TypedefString;
+%}
+
+
+%inline %{
+  
+  struct B
+  {
+    int bb;
+  };
+
+  TypedefString importtest2(TypedefString str) {
+    strcpy(str, "white");
+    return str;
+  }
+
+%}
+
+
+#endif //subdir2_hello_i_
diff --git a/trunk/Examples/test-suite/testdir/subdir2/imports.i b/trunk/Examples/test-suite/testdir/subdir2/imports.i
new file mode 100644
index 0000000..6a5a106
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/subdir2/imports.i
@@ -0,0 +1,6 @@
+#ifndef subdir2_imports_i_
+#define subdir2_imports_i_
+
+typedef char * TypedefString;
+
+#endif //subdir2_imports_i_
diff --git a/trunk/Examples/test-suite/testdir/subdir2/subinc2.i b/trunk/Examples/test-suite/testdir/subdir2/subinc2.i
new file mode 100644
index 0000000..1218f41
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/subdir2/subinc2.i
@@ -0,0 +1,3 @@
+%include "hello.i"
+%import "imports.i"
+
diff --git a/trunk/Examples/test-suite/testdir/test.i b/trunk/Examples/test-suite/testdir/test.i
new file mode 100644
index 0000000..96a949e
--- /dev/null
+++ b/trunk/Examples/test-suite/testdir/test.i
@@ -0,0 +1,4 @@
+
+%include "subdir1/subinc1.i"
+%include "subdir2/subinc2.i"
+
diff --git a/trunk/Examples/test-suite/threads.i b/trunk/Examples/test-suite/threads.i
new file mode 100644
index 0000000..7c6b09b
--- /dev/null
+++ b/trunk/Examples/test-suite/threads.i
@@ -0,0 +1,23 @@
+// This test is designed for testing wrappers in the target language in a multi-threaded environment.
+// The most common cause for this test failing is incorrect compiler settings for a multi-threaded environment.
+
+%module threads
+
+%include "std_string.i"
+
+%newobject Kerfuffle::CharString;
+
+%inline %{
+  #include <string>
+  struct Kerfuffle {
+    std::string StdString(std::string str) {
+      return str;
+    }
+    char * CharString(const char *str) {
+      char * retstr = new char[256];
+      strcpy(retstr, str);
+      return retstr;
+    }
+  };
+%}
+
diff --git a/trunk/Examples/test-suite/throw_exception.i b/trunk/Examples/test-suite/throw_exception.i
new file mode 100644
index 0000000..9a0ddab
--- /dev/null
+++ b/trunk/Examples/test-suite/throw_exception.i
@@ -0,0 +1,76 @@
+%module throw_exception
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Namespace::enum1;
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) Namespace::enum2;
+
+// Tests SWIG's automatic exception mechanism
+
+%inline %{
+
+class Error {
+};
+
+void test_is_Error(Error *r) {}
+
+namespace Namespace {
+  typedef Error ErrorTypedef;
+  typedef const Error& ErrorRef;
+  typedef const Error* ErrorPtr;
+  typedef int IntArray[10];
+  enum EnumTest { enum1, enum2 };
+}
+class Foo {
+public:
+    void test_int() throw(int) {
+      throw 37;
+    }
+    void test_msg() throw(const char *) {
+      throw "Dead";
+    }
+    void test_cls() throw(Error) {
+      throw Error();
+    }	
+    void test_cls_ptr() throw(Error *) {
+      static Error StaticError;
+      throw &StaticError;
+    }	
+    void test_cls_ref() throw(Error &) {
+      static Error StaticError;
+      throw StaticError;
+    }	
+    void test_cls_td() throw(Namespace::ErrorTypedef) {
+      throw Error();
+    }	
+    void test_cls_ptr_td() throw(Namespace::ErrorPtr) {
+      static Error StaticError;
+      throw &StaticError;
+    }	
+    void test_cls_ref_td() throw(Namespace::ErrorRef) {
+      static Error StaticError;
+      throw StaticError;
+    }	
+    void test_array() throw(Namespace::IntArray) {
+      static Namespace::IntArray array;
+      for (int i=0; i<10; i++) {
+        array[i] = i;
+      }
+      throw array;
+    }	
+    void test_enum() throw(Namespace::EnumTest) {
+      throw Namespace::enum2;
+    }	
+    void test_multi(int x) throw(int, const char *, Error) {
+      if (x == 1) throw 37;
+      if (x == 2) throw "Dead";
+      if (x == 3) throw Error();
+    }
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/traits.i b/trunk/Examples/test-suite/traits.i
new file mode 100644
index 0000000..0d25a60
--- /dev/null
+++ b/trunk/Examples/test-suite/traits.i
@@ -0,0 +1,6 @@
+%module traits
+
+%include typemaps/traits.swg
+
+
+%fragment("Traits");
diff --git a/trunk/Examples/test-suite/typedef_array_member.i b/trunk/Examples/test-suite/typedef_array_member.i
new file mode 100644
index 0000000..bb66efd
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_array_member.i
@@ -0,0 +1,25 @@
+%module typedef_array_member
+%inline %{
+
+typedef char amember[20];
+
+struct Foo {
+   amember x;
+};
+
+%}
+
+
+%ignore jbuf_tag;
+%inline %{
+
+  typedef struct jbuf_tag
+  {
+    int mask;
+  } jbuf[1];
+  
+  struct Ast_channel {
+    jbuf jmp[32];
+  };
+
+%}
diff --git a/trunk/Examples/test-suite/typedef_class.i b/trunk/Examples/test-suite/typedef_class.i
new file mode 100644
index 0000000..5a75305
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_class.i
@@ -0,0 +1,16 @@
+%module typedef_class
+
+%inline %{ 
+class RealA 
+{ 
+ public: 
+   int a; 
+}; 
+ 
+class B 
+{ 
+ public: 
+   typedef RealA A2; 
+   int testA (const A2& a) {return a.a;} 
+}; 
+%} 
diff --git a/trunk/Examples/test-suite/typedef_funcptr.i b/trunk/Examples/test-suite/typedef_funcptr.i
new file mode 100644
index 0000000..f8cdd14
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_funcptr.i
@@ -0,0 +1,27 @@
+// Tests typedef through function pointers
+
+%module typedef_funcptr
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) addf; /* Ruby, wrong constant name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) subf; /* Ruby, wrong constant name */
+
+%{
+int addf(int x, int y) {
+   return x+y;
+}
+int subf(int x, int y) {
+   return x-y;
+}
+%}
+
+%inline %{
+typedef int Integer;
+
+extern "C"
+Integer do_op(Integer x, Integer y, Integer (*op)(Integer, Integer)) {
+    return (*op)(x,y);
+}
+%}
+
+%constant int     addf(int x, int y);
+%constant Integer subf(Integer x, Integer y);
diff --git a/trunk/Examples/test-suite/typedef_inherit.i b/trunk/Examples/test-suite/typedef_inherit.i
new file mode 100644
index 0000000..48821a1
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_inherit.i
@@ -0,0 +1,49 @@
+// Inheritance through a typedef name
+%module typedef_inherit
+
+  
+%inline %{
+class Foo {
+public:
+     virtual ~Foo () { }
+  
+     virtual char *blah() {
+	return (char *) "Foo::blah";
+     }
+};
+
+typedef Foo FooObj;
+
+class Bar : public FooObj {
+ public:
+  virtual char *blah() {
+    return (char *) "Bar::blah";
+  };
+};
+
+char *do_blah(FooObj *f) {
+  return f->blah();
+}
+
+typedef struct spam {
+  virtual ~spam()
+  {
+  }
+  
+   virtual char *blah() {     
+       return (char *) "Spam::blah";
+   }
+} Spam;
+
+struct Grok : public Spam {
+   virtual ~Grok() { }
+   virtual char *blah() {
+       return (char *) "Grok::blah";
+   }
+};
+
+static char * do_blah2(Spam *s) {
+   return s->blah();
+}
+%}
+
diff --git a/trunk/Examples/test-suite/typedef_mptr.i b/trunk/Examples/test-suite/typedef_mptr.i
new file mode 100644
index 0000000..de0cde1
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_mptr.i
@@ -0,0 +1,34 @@
+// Tests typedef through member pointers
+
+%module typedef_mptr
+
+#if defined(SWIGPYTHON) || defined(SWIGOCAML)
+
+%inline %{
+
+class Foo {
+public:
+    int add(int x, int y) {
+        return x+y;
+    }
+    int sub(int x, int y) {
+        return x-y;
+    }
+    int do_op(int x, int y, int (Foo::*op)(int, int)) {
+	return (this->*op)(x,y);
+    }
+};
+
+typedef Foo FooObj;
+typedef int Integer;
+
+Integer do_op(Foo *f, Integer x, Integer y, Integer (FooObj::*op)(Integer, Integer)) {
+    return f->do_op(x,y,op);
+}
+%}
+#endif
+
+#if defined(SWIGPYTHON) || defined(SWIGOCAML)
+%constant int (Foo::*add)(int,int) = &Foo::add;
+%constant Integer (FooObj::*sub)(Integer,Integer) = &FooObj::sub;
+#endif
diff --git a/trunk/Examples/test-suite/typedef_reference.i b/trunk/Examples/test-suite/typedef_reference.i
new file mode 100644
index 0000000..5146317
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_reference.i
@@ -0,0 +1,10 @@
+%module typedef_reference
+
+%include cpointer.i
+%pointer_functions(int, intp);
+
+%inline %{
+  typedef int & IntRef;
+  int somefunc(IntRef i) { return i; }
+  int otherfunc(int &i) { return i; }
+%}
diff --git a/trunk/Examples/test-suite/typedef_scope.i b/trunk/Examples/test-suite/typedef_scope.i
new file mode 100644
index 0000000..5c04d6c
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_scope.i
@@ -0,0 +1,37 @@
+// Tests some subtle issues of typedef scoping in C++
+
+%module typedef_scope
+
+%inline %{
+
+typedef char * FooType;
+class Bar {
+public:
+     typedef int FooType;
+     FooType test1(FooType n, ::FooType data) {
+         return n;
+     }
+     ::FooType test2(FooType n, ::FooType data) {
+         return data;
+     }
+};
+
+
+
+class Foo
+{
+};
+
+typedef Foo FooBar;
+
+class CBaz
+{
+public:
+  typedef FooBar Foo;
+};
+
+
+%}
+
+
+
diff --git a/trunk/Examples/test-suite/typedef_sizet.i b/trunk/Examples/test-suite/typedef_sizet.i
new file mode 100644
index 0000000..0dc7d9e
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_sizet.i
@@ -0,0 +1,6 @@
+%module typedef_sizet
+
+typedef unsigned long long size_t;
+%inline %{
+size_t size(size_t x) {return x; } 
+%}
diff --git a/trunk/Examples/test-suite/typedef_struct.i b/trunk/Examples/test-suite/typedef_struct.i
new file mode 100644
index 0000000..800d93b
--- /dev/null
+++ b/trunk/Examples/test-suite/typedef_struct.i
@@ -0,0 +1,43 @@
+%module typedef_struct
+
+%inline %{
+  typedef struct {
+    int numpoints;
+  } LineObj;
+  
+  typedef LineObj MultipointObj;
+  
+  typedef struct {
+#ifdef SWIG
+    %immutable;
+#endif
+    char *filename; 
+    int numfonts;
+#ifdef SWIG
+    %mutable;
+#endif
+    int* fonts;
+#ifndef SWIG
+    void* map;
+#endif
+  } FontSetObj;
+
+#define MS_NOOVERRIDE -1111
+
+%}
+
+
+%inline %{
+typedef struct {
+    int a;
+    int b;
+} A_t, *B_t;
+
+A_t* make_a() {
+    return (A_t*)malloc(sizeof(A_t));
+} 
+
+B_t make_b() {
+    return make_a();
+}
+%} 
diff --git a/trunk/Examples/test-suite/typemap_namespace.i b/trunk/Examples/test-suite/typemap_namespace.i
new file mode 100644
index 0000000..5375c43
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_namespace.i
@@ -0,0 +1,49 @@
+%module typemap_namespace
+
+/* Secret typedefs */
+%{
+namespace Foo {
+   typedef char    Str1;
+   typedef char    Str2;
+}
+%}
+
+namespace Foo {
+    struct Str1;
+    struct Str2;
+
+#ifdef SWIGCSHARP
+    %typemap(ctype) Str1 * = char *;
+    %typemap(imtype) Str1 * = char *;
+    %typemap(cstype) Str1 * = char *;
+    %typemap(csin) Str1 * = char *;
+    %typemap(csout) Str1 * = char *;
+#endif
+#ifdef SWIGJAVA
+    %typemap(jni) Str1 * = char *;
+    %typemap(jtype) Str1 * = char *;
+    %typemap(jstype) Str1 * = char *;
+    %typemap(javain) Str1 * = char *;
+    %typemap(javaout) Str1 * = char *;
+#endif
+    %typemap(in) Str1 * = char *;
+#if !(defined(SWIGCSHARP) || defined(SWIGLUA) || defined(SWIGPHP))
+    %typemap(freearg) Str1 * = char *;
+#endif
+    %typemap(typecheck) Str1 * = char *;
+    %apply char * { Str2 * };
+}
+
+%inline %{
+namespace Foo {
+    char *test1(Str1 *s) {
+          return s;
+    }
+    char *test2(Str2 *s) {
+          return s;
+    }
+}
+%}
+
+    
+
diff --git a/trunk/Examples/test-suite/typemap_ns_using.i b/trunk/Examples/test-suite/typemap_ns_using.i
new file mode 100644
index 0000000..72f5c19
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_ns_using.i
@@ -0,0 +1,21 @@
+%module typemap_ns_using
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) X::_FooImpl;	/* Ruby, wrong class name */
+
+%inline %{
+namespace X {
+  typedef int Integer;
+
+  class _FooImpl {
+  public:
+      typedef Integer value_type;
+  };
+  typedef _FooImpl Foo;
+}
+
+using X::Foo;
+
+int spam(Foo::value_type x) { return x; }
+
+%}
+
diff --git a/trunk/Examples/test-suite/typemap_numinputs.i b/trunk/Examples/test-suite/typemap_numinputs.i
new file mode 100644
index 0000000..24e8f3a
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_numinputs.i
@@ -0,0 +1,37 @@
+%module typemap_numinputs
+
+
+%typemap(in, numinputs=1) (char *STR, int LEN)(int temp = 0)
+{
+  temp = 1;
+  $2 = 0;
+  $1 = 0;
+}
+
+%typemap(in) (int *OUTPUT)  (int temp = 0)
+{
+  temp = 2;
+  $1 = &temp;
+}
+
+%typemap(argout) (int *OUTPUT)
+{
+  ++temp$argnum;
+}
+
+%typemap(argout, numinputs=1) (char *STR, int LEN)
+{
+  ++temp$argnum;
+}
+
+%typemap(in) int hello
+{
+  $1 = 0;
+}
+
+%inline %{
+  int this_breaks(int hello, char *STR, int LEN, int *OUTPUT)
+  {
+    return LEN;
+  }
+%}
diff --git a/trunk/Examples/test-suite/typemap_self.i b/trunk/Examples/test-suite/typemap_self.i
new file mode 100644
index 0000000..3630688
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_self.i
@@ -0,0 +1,47 @@
+%module typemap_self
+
+// This typemap should be ignored for self?
+%typemap(in) A* (A* ptr) {
+  if (SWIG_ConvertPtr($input, (void**) &ptr, $1_descriptor, 0) != -1) {
+    $1 = ptr;
+  } else  {
+    $1 = new A();
+  }
+ }
+
+// Simple but unsecure current fix
+//%apply SWIGTYPE* {A* self}
+
+
+%inline %{
+  class A;
+  
+  int foo(A* self) 
+  {
+    return 0;
+  }
+  
+  struct A
+  {
+    static int bar(int, A* self)
+    {
+      return 1;
+    }
+    
+    int val;
+    
+    
+    int foo(A* self, A* b) 
+    {
+      return 1;
+    }
+  };
+  
+  struct B
+  {
+    B(A*) 
+    {
+    }
+  };
+  
+%}
diff --git a/trunk/Examples/test-suite/typemap_subst.i b/trunk/Examples/test-suite/typemap_subst.i
new file mode 100644
index 0000000..67d4124
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_subst.i
@@ -0,0 +1,65 @@
+/* This interface file tests for type-related typemap substitutions.
+ */
+
+%module typemap_subst
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) xyzzy; /* Ruby, wrong class name */
+
+%inline %{
+  struct xyzzy {
+    int member;
+  };
+%}
+
+%typemap(in) const struct xyzzy **TEST
+  ($type temp, $*type startemp, $&type amptemp, $basetype basetemp)
+{
+  { /* Test C type name substitutions */
+    $ltype a = (struct xyzzy **) NULL;
+    const struct xyzzy **b = ($type) NULL;
+    $&ltype c = (struct xyzzy ***) NULL;
+    const struct xyzzy ***d = ($&type) NULL;
+    $*ltype e = *a;
+    $basetype f;
+    f.member = 42;
+    (void)a;
+    (void)b;
+    (void)c;
+    (void)d;
+    (void)e;
+  }
+  { /* Test locals */
+    basetemp.member = 0;
+    startemp = &basetemp;
+    temp = &startemp;
+    amptemp = &temp;
+  }
+  { /* Test descriptors */
+    void *desc = $descriptor;
+    void *stardesc = $*descriptor;
+    void *ampdesc = $&descriptor;
+    (void)desc;
+    (void)stardesc;
+    (void)ampdesc;
+  }
+  { /* Test mangled names */
+    void *desc = SWIGTYPE$mangle;
+    void *stardesc = SWIGTYPE$*mangle;
+    void *ampdesc = SWIGTYPE$&mangle;
+    (void)desc;
+    (void)stardesc;
+    (void)ampdesc;
+  }
+  $1 = ($ltype) temp;  
+}
+
+/* Java and C# modules don't use SWIG's runtime type system */
+#if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
+%inline %{
+  void foo(const struct xyzzy **TEST) {}
+%}
+#endif
+
+
+
+
diff --git a/trunk/Examples/test-suite/typemap_variables.i b/trunk/Examples/test-suite/typemap_variables.i
new file mode 100644
index 0000000..142e350
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_variables.i
@@ -0,0 +1,69 @@
+%module typemap_variables
+
+// Check typemap name matching rules for variables
+// Some of these are using qualified names, which is not right... the test will be adjusted as these get fixed
+
+#if defined(SWIGUTL)
+%{
+#define TYPEMAP_VARIABLES_FAIL SWIG_fail;
+%}
+#else
+%{
+#define TYPEMAP_VARIABLES_FAIL
+%}
+#endif
+
+// Scripting languages use varin/varout for variables (except non-static member variables where in/out are used ???)
+%typemap(varin)  int                           "this_will_not_compile_varin "
+%typemap(varout) int                           "this_will_not_compile_varout"
+%typemap(varin)  int globul                    "/*int globul varin */ TYPEMAP_VARIABLES_FAIL"
+%typemap(varout) int globul                    "/*int globul varout*/ $result=0;"
+%typemap(varin)  int Space::nspace             "/*int nspace varin */ TYPEMAP_VARIABLES_FAIL"
+%typemap(varout) int Space::nspace             "/*int nspace varout*/ $result=0;"
+//%typemap(varin)  int member                    "/*int member varin */"
+//%typemap(varout) int member                    "/*int member varout*/ $result=0;"
+%typemap(varin)  int Space::Struct::smember    "/*int smember varin */ TYPEMAP_VARIABLES_FAIL"
+%typemap(varout) int Space::Struct::smember    "/*int smember varout*/ $result=0;"
+
+// Statically typed languages use in/out for variables
+%typemap(in)  int                           "this_will_not_compile_in "
+%typemap(out) int                           "this_will_not_compile_out"
+%typemap(in)  int globul                    "/*int globul in */ $1=0;"
+%typemap(out) int globul                    "/*int globul out*/ $result=0;"
+%typemap(in)  int Space::nspace             "/*int nspace in */ $1=0;"
+%typemap(out) int Space::nspace             "/*int nspace out*/ $result=0;"
+%typemap(in)  int member                    "/*int member in */ $1=0;"
+#ifdef SWIGTCL
+%typemap(out) int member                    "/*int member out*/"
+#else
+%typemap(out) int member                    "/*int member out*/ $result=0;"
+#endif
+%typemap(in)  int Space::Struct::smember    "/*int smember in */ $1=0;"
+%typemap(out) int Space::Struct::smember    "/*int smember out*/ $result=0;"
+
+%typemap(javain)  int                           "this_will_not_compile_javain "
+%typemap(javaout) int                           "this_will_not_compile_javaout"
+%typemap(javain)  int globul                    "/*int globul in */  $javainput"
+%typemap(javaout) int globul                    "/*int globul out*/  { return $jnicall; }"
+%typemap(javain)  int Space::nspace             "/*int nspace in */  $javainput"
+%typemap(javaout) int Space::nspace             "/*int nspace out*/  { return $jnicall; }"
+%typemap(javain)  int member                    "/*int member in */  $javainput"
+%typemap(javaout) int member                    "/*int member out*/  { return $jnicall; }"
+%typemap(javain)  int Space::Struct::smember    "/*int smember in */ $javainput"
+%typemap(javaout) int Space::Struct::smember    "/*int smember out*/ { return $jnicall; }"
+
+%inline %{
+
+int globul;
+
+namespace Space {
+  int nspace;
+  struct Struct {
+    int member;
+    static int smember;
+//    static short memberfunction() { return 0; } //javaout and jstype typemaps don't use fully qualified name, but other typemaps do
+  };
+  int Struct::smember = 0;
+}
+%}
+
diff --git a/trunk/Examples/test-suite/typemap_various.i b/trunk/Examples/test-suite/typemap_various.i
new file mode 100644
index 0000000..0b7035e
--- /dev/null
+++ b/trunk/Examples/test-suite/typemap_various.i
@@ -0,0 +1,57 @@
+%module typemap_various
+
+// %copyctor need to be disables since 'const SWIGTYPE &' is intended to generate errors
+%nocopyctor;
+
+%typemap(in) SWIGTYPE "_this_will_not_compile_SWIGTYPE_"
+%typemap(in) const SWIGTYPE & "_this_will_not_compile_const_SWIGTYPE_REF_"
+
+%inline %{
+template <class T> struct Foo {
+  Foo() {}
+#ifdef SWIG
+  // These typemaps should be used by foo1 and foo2
+  %typemap(in) Foo<T>      "/*in typemap for Foo<T> */"
+  %typemap(in) const Foo & "/*in typemap for const Foo&, with type T*/"
+#endif
+};
+%}
+
+%template(FooInt) Foo<int>;
+%template() Foo<short>; // previously Foo<short> typemaps were being picked up for Python only
+
+%inline %{
+void foo1(Foo<int> f, const Foo<int>& ff) {}
+void foo2(Foo<short> f, const Foo<short>& ff) {}
+%}
+
+#ifdef SWIGUTL
+%typemap(ret) int Bar1::foo() { /* hello1 */ };
+%typemap(ret) int Bar2::foo() { /* hello2 */ };
+%typemap(ret) int foo() {/* hello3 */ };
+#endif
+
+%inline %{
+  struct Bar1 {
+    int foo() { return 1;}    
+  };
+
+  struct Bar2 {
+    int foo() { return 1;}    
+  };
+%}
+
+
+
+%newobject FFoo::Bar(bool) const ;
+%typemap(newfree) char* Bar(bool)  {
+   /* hello */ delete[] result;
+}
+
+%inline {
+  class FFoo {
+  public:
+    char * Bar(bool b) const { return (char *)"x"; }
+  };
+}
+
diff --git a/trunk/Examples/test-suite/typename.i b/trunk/Examples/test-suite/typename.i
new file mode 100644
index 0000000..4253e08
--- /dev/null
+++ b/trunk/Examples/test-suite/typename.i
@@ -0,0 +1,34 @@
+%module "typename"
+
+// Tests the typename handling in templates.  
+
+%inline %{
+class Foo {
+public:
+    typedef double Number;
+    Number blah() {
+        return 2.1828;
+    }
+};
+
+class Bar {
+public:
+   typedef int Number;
+   Number blah() {
+       return 42;
+   }
+};
+
+template<typename T> typename T::Number twoblah(T &obj) {
+   return 2*(obj.blah());
+}
+
+Bar::Number spam() { return 3; }
+
+%}
+
+%template(twoFoo) twoblah<Foo>;
+%template(twoBar) twoblah<Bar>;
+
+
+       
\ No newline at end of file
diff --git a/trunk/Examples/test-suite/types_directive.i b/trunk/Examples/test-suite/types_directive.i
new file mode 100644
index 0000000..4431226
--- /dev/null
+++ b/trunk/Examples/test-suite/types_directive.i
@@ -0,0 +1,46 @@
+%module types_directive
+
+%ignore Time2::operator Date *;
+
+%inline %{
+struct Date {
+  Date(unsigned int year, unsigned int month, unsigned int day) : year(year), month(month), day(day) {}
+  unsigned int year;
+  unsigned int month;
+  unsigned int day;
+};
+
+struct Time1 {
+  Time1(unsigned int year, unsigned int month, unsigned int day, unsigned int seconds) : date(year, month, day), seconds(seconds) {}
+  Date &dateFromTime() {
+    return date;
+  }
+  Date date;
+  unsigned int seconds;
+};
+
+struct Time2 {
+  Time2(unsigned int year, unsigned int month, unsigned int day, unsigned int seconds) : date(year, month, day), seconds(seconds) {}
+  operator Date *() {
+    return &date;
+  }
+  Date date;
+  unsigned int seconds;
+};
+Date add(const Date &date, unsigned int days) {
+  Date newDate = date;
+  newDate.day += days;
+  return newDate;
+}
+%}
+
+// allow conversion from Date -> Time1 using the following code
+%types(Time1 = Date) %{
+  Time1 *t = (Time1 *)$from;
+  Date &d = t->dateFromTime();
+  return (void *) &d;
+%}
+
+// allow conversion from Date -> Time2 using conversion operator (cast) in Time2
+%types(Time2 = Date);
+
diff --git a/trunk/Examples/test-suite/uffi/Makefile.in b/trunk/Examples/test-suite/uffi/Makefile.in
new file mode 100644
index 0000000..c09153d
--- /dev/null
+++ b/trunk/Examples/test-suite/uffi/Makefile.in
@@ -0,0 +1,47 @@
+#######################################################################
+# Makefile for uffi test-suite
+#######################################################################
+
+LANGUAGE     = uffi
+UFFI         = @UFFIBIN@
+SCRIPTSUFFIX = _runme.lisp
+srcdir       = @srcdir@
+top_srcdir   = @top_srcdir@
+top_builddir = @top_builddir@
+
+include $(srcdir)/../common.mk
+
+# no C++ tests for now
+CPP_TEST_CASES =
+#C_TEST_CASES += 
+
+# Rules for the different types of tests
+%.cpptest: 
+	$(setup)
+	+$(swig_and_compile_cpp)
+	$(run_testcase)
+
+%.ctest:
+	$(setup)
+	+$(swig_and_compile_c)
+	$(run_testcase)
+
+%.multicpptest: 
+	$(setup)
+	+$(swig_and_compile_multi_cpp)
+	$(run_testcase)
+
+# Runs the testcase. A testcase is only run if
+# a file is found which has _runme.lisp appended after the testcase name.
+run_testcase = \
+	if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then (	  \
+	  env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(UFFIBIN) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
+	fi;
+
+# Clean: (does nothing, we dont generate extra uffi code)
+%.clean:
+	
+
+clean:
+	$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile uffi_clean
+
diff --git a/trunk/Examples/test-suite/union_scope.i b/trunk/Examples/test-suite/union_scope.i
new file mode 100644
index 0000000..67093ef
--- /dev/null
+++ b/trunk/Examples/test-suite/union_scope.i
@@ -0,0 +1,13 @@
+%module union_scope
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) nRState;		// Ruby, wrong class name
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) nRState_rstate;	// Ruby, wrong class name
+
+%inline %{
+class nRState { 
+public: 
+  union { 
+    int i; 
+  } rstate; 
+}; 
+%}
diff --git a/trunk/Examples/test-suite/unions.i b/trunk/Examples/test-suite/unions.i
new file mode 100644
index 0000000..49bb85d
--- /dev/null
+++ b/trunk/Examples/test-suite/unions.i
@@ -0,0 +1,42 @@
+/*
+This testcase checks that unions can be set and read.
+*/
+
+%module unions
+
+%{
+/* Must undefine small to work on Windows.  small is defined as a
+char in rpcndr.h */
+#ifdef small
+#undef small	
+#endif
+%}
+
+%inline %{
+
+typedef struct SmallStruct {
+  short         jill;
+} SmallStruct;
+
+typedef struct BigStruct {
+  int           jack;
+  SmallStruct   smallstruct;
+} BigStruct;
+
+/* This union is just to check the parser */
+typedef union {
+  BigStruct     bs;
+  SmallStruct   ss;
+} UnionTest;
+
+/* This union checks the parser and will be used in a runtime test */
+typedef struct {
+  union
+  {
+    BigStruct   big;
+    SmallStruct small;
+  } uni;
+  int           number;
+} EmbeddedUnionTest;
+
+%}
diff --git a/trunk/Examples/test-suite/using1.i b/trunk/Examples/test-suite/using1.i
new file mode 100644
index 0000000..2e336fa
--- /dev/null
+++ b/trunk/Examples/test-suite/using1.i
@@ -0,0 +1,22 @@
+%module using1
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) X::_FooImpl;	/* Ruby, wrong class name */
+
+%inline %{
+
+namespace X {
+  typedef int Integer;
+
+  class _FooImpl {
+  public:
+      typedef Integer value_type;
+  };
+  typedef _FooImpl Foo;
+}
+
+namespace Y = X;
+using namespace Y;
+
+int spam(Foo::value_type x) { return x; }
+
+%}
diff --git a/trunk/Examples/test-suite/using2.i b/trunk/Examples/test-suite/using2.i
new file mode 100644
index 0000000..1f3dc46
--- /dev/null
+++ b/trunk/Examples/test-suite/using2.i
@@ -0,0 +1,27 @@
+%module using2
+
+%warnfilter(SWIGWARN_PARSE_USING_UNDEF);
+
+using ::baz;
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) X::_FooImpl;	/* Ruby, wrong class name */
+
+%inline %{
+
+namespace X {
+  typedef int Integer;
+
+  class _FooImpl {
+  public:
+      typedef Integer value_type;
+  };
+  typedef _FooImpl Foo;
+}
+
+namespace Y = X;
+using Y::Foo;
+
+int spam(Foo::value_type x) { return x; }
+
+ 
+%}
diff --git a/trunk/Examples/test-suite/using_composition.i b/trunk/Examples/test-suite/using_composition.i
new file mode 100644
index 0000000..7bb6add
--- /dev/null
+++ b/trunk/Examples/test-suite/using_composition.i
@@ -0,0 +1,49 @@
+%module(ruby_minherit="1") using_composition
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) FooBar;   // C#, Java, Php4 multiple inheritance
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) FooBar2;   // C#, Java, Php4 multiple inheritance
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) FooBar3;   // C#, Java, Php4 multiple inheritance
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) blah;
+#endif
+
+%inline %{
+class Foo {
+public:
+     int blah(int x) { return x; }
+     char *blah(char *x) { return x; }
+};
+
+class Bar {
+public:
+     double blah(double x) { return x; }
+};
+
+class FooBar : public Foo, public Bar {
+public:
+     using Foo::blah;
+     using Bar::blah;
+     char *blah(char *x) { return x; }
+};
+
+class FooBar2 : public Foo, public Bar {
+public:
+     char *blah(char *x) { return x; }
+     using Foo::blah;
+     using Bar::blah;
+};
+
+class FooBar3 : public Foo, public Bar {
+public:
+     using Foo::blah;
+     char *blah(char *x) { return x; }
+     using Bar::blah;
+};
+
+%}
diff --git a/trunk/Examples/test-suite/using_extend.i b/trunk/Examples/test-suite/using_extend.i
new file mode 100644
index 0000000..414ceed
--- /dev/null
+++ b/trunk/Examples/test-suite/using_extend.i
@@ -0,0 +1,51 @@
+%module(ruby_minherit="1") using_extend
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) FooBar;   // C#, Java, Php4 multiple inheritance
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) blah;
+#endif
+
+%extend Foo {
+     int blah(int x, int y) {
+        return x+y;
+     }
+};
+
+%extend Bar {
+     double blah(double x, double y) {
+        return x+y;
+     }
+};
+
+%inline %{
+class Foo {
+public:
+     int blah(int x) { return x; }
+     char *blah(char *x) { return x; }
+};
+
+class Bar {
+public:
+     int duh1() { return 1; }
+     int duh(int x) { return x; }
+     double blah(double x) { return x; }
+};
+
+class FooBar : public Foo, public Bar {
+public:
+     using Foo::blah;
+     using Bar::blah;
+     char *blah(char *x) { return x; }
+};
+
+%}
+
+%extend FooBar 
+{
+  using Bar::duh1;
+  using Bar::duh;
+}
+
+
diff --git a/trunk/Examples/test-suite/using_inherit.i b/trunk/Examples/test-suite/using_inherit.i
new file mode 100644
index 0000000..b4fe966
--- /dev/null
+++ b/trunk/Examples/test-suite/using_inherit.i
@@ -0,0 +1,54 @@
+%module using_inherit
+
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) Foo::test;
+#endif
+
+%inline %{
+
+class Foo {
+public:
+     int test(int x) { return x; }
+     double test(double x) { return x; };
+};
+
+class Bar : public Foo {
+public:
+     using Foo::test;
+};
+
+class Bar2 : public Foo {
+public:
+     int test(int x) { return x*2; }
+     double test(double x) { return x*2; };
+     using Foo::test;
+};
+
+class Bar3 : public Foo {
+public:
+     int test(int x) { return x*2; }
+     double test(double x) { return x*2; };
+     using Foo::test;
+};
+
+class Bar4 : public Foo {
+public:
+     int test(int x) { return x*2; }
+     using Foo::test;
+     double test(double x) { return x*2; };
+};
+
+class Fred1 : public Foo {
+public:
+     using Foo::test;
+     double test(double x) { return x*2; };
+};
+
+class Fred2 : public Foo {
+public:
+     double test(double x) { return x*2; };
+     using Foo::test;
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/using_namespace.i b/trunk/Examples/test-suite/using_namespace.i
new file mode 100644
index 0000000..1989b6a
--- /dev/null
+++ b/trunk/Examples/test-suite/using_namespace.i
@@ -0,0 +1,76 @@
+%module(ruby_minherit="1") using_namespace
+
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hi::hi0;	/* Ruby, wrong class name */
+%warnfilter(SWIGWARN_RUBY_WRONG_NAME) hi::hi1;	/* Ruby, wrong class name */
+
+%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE,
+	    SWIGWARN_CSHARP_MULTIPLE_INHERITANCE,
+	    SWIGWARN_PHP4_MULTIPLE_INHERITANCE) Hi<hello::Hello, hi::hi0>; // C#, Java, Php4 multiple inheritance
+
+%inline %{
+  namespace hello
+  {  
+    struct Hello 
+    {
+    };
+
+    template <class _T1, class _T2>
+    struct Hi : _T1, _T2
+    {
+      int value1() const
+      {
+	return 1;
+      }      
+
+      int value2() const
+      {
+	return 2;
+      }      
+    };    
+  }
+
+  namespace hi
+  {
+
+    struct hi0
+    {
+    };
+    
+  }
+%}
+
+namespace hello
+{
+  %template(Hi_hi0) Hi<hello::Hello, hi::hi0>;
+}
+
+
+%inline %{
+  namespace hi
+  {
+    struct hi1 : private hello::Hi< hello::Hello, hi0 >
+    {
+      using hello::Hi< hello::Hello, hi::hi0 >::value1;
+      using hello::Hi< hello::Hello, hi0 >::value2;
+    };
+    
+  }
+  
+%}
+
+
+%inline {
+namespace foo {
+  typedef double mytype;
+}
+
+// global namespace
+typedef float mytype;
+
+using namespace foo;
+
+struct X {
+  ::mytype d;
+};
+
+}
diff --git a/trunk/Examples/test-suite/using_pointers.i b/trunk/Examples/test-suite/using_pointers.i
new file mode 100644
index 0000000..b2d6abe
--- /dev/null
+++ b/trunk/Examples/test-suite/using_pointers.i
@@ -0,0 +1,36 @@
+%module using_pointers
+
+#ifdef SWIGCSHARP
+%csmethodmodifiers x "public new"
+#endif
+
+%{
+#if defined(_MSC_VER)
+  #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#endif
+%}
+
+%inline %{
+  class Foo {
+  public:
+    int x;
+    virtual ~Foo() { }
+    virtual Foo* blah() { return this; }
+    virtual Foo* exception_spec(int what_to_throw) throw (int, const char *) {
+      int num = 10;
+      const char *str = "exception message";
+      if (what_to_throw == 1) throw num;
+      else if (what_to_throw == 2) throw str;
+      return 0;
+    }
+  };
+
+  class FooBar : public Foo {
+  public:
+    using Foo::blah;
+    using Foo::x;
+    using Foo::exception_spec;
+  };
+
+%}
+
diff --git a/trunk/Examples/test-suite/using_private.i b/trunk/Examples/test-suite/using_private.i
new file mode 100644
index 0000000..be57ef7
--- /dev/null
+++ b/trunk/Examples/test-suite/using_private.i
@@ -0,0 +1,25 @@
+%module using_private
+
+%inline %{
+class Foo {
+public:
+     virtual ~Foo() { }
+     int x;
+     int blah(int xx) { return xx; }
+     int defaulted(int i = -1) { return i; }
+     virtual void virtualmethod() {}
+     virtual void anothervirtual() {}
+};
+
+class FooBar : private Foo {
+public:
+     using Foo::blah;
+     using Foo::x;
+     using Foo::defaulted;
+     using Foo::virtualmethod;
+     virtual void anothervirtual() {}
+     virtual ~FooBar() {}
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/using_protected.i b/trunk/Examples/test-suite/using_protected.i
new file mode 100644
index 0000000..23adfdb
--- /dev/null
+++ b/trunk/Examples/test-suite/using_protected.i
@@ -0,0 +1,17 @@
+%module using_protected
+
+%inline %{
+class Foo {
+protected:
+     int x;
+     int blah(int xx) { return xx; }
+};
+
+class FooBar : public Foo {
+public:
+     using Foo::blah;
+     using Foo::x;
+};
+
+%}
+
diff --git a/trunk/Examples/test-suite/valuewrapper.i b/trunk/Examples/test-suite/valuewrapper.i
new file mode 100644
index 0000000..289f882
--- /dev/null
+++ b/trunk/Examples/test-suite/valuewrapper.i
@@ -0,0 +1,17 @@
+// valuewrapper.i
+%module valuewrapper
+
+%inline %{
+template <typename T> struct X {
+   X(int) {}
+};
+ 
+template <typename T> struct Y {
+   Y() {}
+   int spam(T t = T(0)) { return 0; }
+};
+%}
+ 
+%template(Xi) X<int>;
+%template(YXi) Y< X<int> >;
+
diff --git a/trunk/Examples/test-suite/valuewrapper_base.i b/trunk/Examples/test-suite/valuewrapper_base.i
new file mode 100644
index 0000000..1698c3e
--- /dev/null
+++ b/trunk/Examples/test-suite/valuewrapper_base.i
@@ -0,0 +1,28 @@
+%module valuewrapper_base
+%inline 
+%{ 
+  namespace oss 
+  { 
+    enum Polarization { UnaryPolarization, BinaryPolarization }; 
+ 
+    struct Base 
+    { 
+    };    
+ 
+    template <Polarization P> 
+    struct Interface : Base 
+    { 
+      Interface(const Base& b) { }; 
+    }; 
+    
+    template <class Result> 
+    Result make() { return Result(*new Base()); }
+  } 
+%} 
+ 
+namespace oss 
+{ 
+  // Interface 
+  %template(Interface_BP) Interface<BinaryPolarization>; 
+  %template(make_Interface_BP) make<Interface<BinaryPolarization> >; 
+} 
diff --git a/trunk/Examples/test-suite/valuewrapper_const.i b/trunk/Examples/test-suite/valuewrapper_const.i
new file mode 100644
index 0000000..db1c807
--- /dev/null
+++ b/trunk/Examples/test-suite/valuewrapper_const.i
@@ -0,0 +1,30 @@
+%module valuewrapper_const
+
+%inline %{
+// B requires swig to use the SwigValueWrapper 
+class B 
+{ 
+private: 
+  B() { } 
+public: 
+  B(const B&){ } 
+}; 
+ 
+// A returns a B and a const B 
+class A 
+{ 
+  B b;
+public: 
+  A(const B& b) : b(b) { }
+  // this one works    SwigValueWrapper< B > result; 
+  B GetB() {
+        return b;
+  } 
+  // this one is incorrect     B result; 
+  const B GetBconst() const {
+        return b;
+  }
+}; 
+
+%}
+ 
diff --git a/trunk/Examples/test-suite/valuewrapper_opaque.i b/trunk/Examples/test-suite/valuewrapper_opaque.i
new file mode 100644
index 0000000..52da893
--- /dev/null
+++ b/trunk/Examples/test-suite/valuewrapper_opaque.i
@@ -0,0 +1,253 @@
+%module valuewrapper_opaque
+
+/* 
+ *  Opaque types
+ */
+
+%feature("valuewrapper") C;
+class C;
+
+%{
+template<typename T> class TemplateClass {
+public:
+TemplateClass<T>(T a) {}
+};
+
+struct B
+{
+};
+
+class C
+{
+public:
+  C(int){}
+};
+%}
+
+
+/*
+ * Hint swig that the Opaque type B don't need the value wrapper.
+ * This hint is only necessary in very very special cases.
+ */
+%feature("novaluewrapper") B;
+class B;
+
+/*
+ * Force swig to use the value wrapper, even when the class
+ * has a default constructor, in case you want to save a
+ * instance construction.
+ * 
+ */
+%feature("valuewrapper") D;
+class D;
+
+
+%feature("valuewrapper") A;
+class A;
+
+%feature("valuewrapper") TemplateClass<A>;
+%feature("valuewrapper") TemplateClass<C>;
+template<class T> class TemplateClass;
+
+%feature("valuewrapper") BB;
+class BB;
+
+
+%inline %{
+
+struct A 
+{
+  A(int){}
+};
+
+class D {};
+
+class Klass {};
+
+
+TemplateClass<Klass> getKlass(Klass k) {
+  TemplateClass<Klass> t(k);
+  return t;
+}
+
+
+TemplateClass<A> getA(A a) {
+  TemplateClass<A> t(a);
+  return t;
+}
+
+
+TemplateClass<B> getA(B b) {
+  TemplateClass<B> t(b);
+  return t;
+}
+
+
+TemplateClass<C> getC(C a) {
+  TemplateClass<C> t(a);
+  return t;
+}
+
+
+TemplateClass<int> getInt(int a) {
+  TemplateClass<int> t(a);
+  return t;
+}
+
+A sgetA(A a) {
+  return a;
+}
+
+Klass sgetKlass(Klass a) {
+  return a;
+}
+
+template <class T> 
+struct auto_ptr
+{
+  auto_ptr(T a){}
+};
+
+auto_ptr<A> getPtrA(auto_ptr<A> a) {
+  return a;
+}
+
+B getB(B a) {
+  return a;
+}
+
+D getD(D a) {
+  return a;
+}
+ 
+%}
+
+%template() auto_ptr<A>;
+
+
+/***** Another strange case, member var + opaque, bug #901706 ******/
+%{
+class BB {
+friend class AA;
+
+protected:
+	BB(int aa) { this->a = aa; };
+	BB() {};
+	
+	int a;
+};
+%}
+  
+%inline %{
+
+class AA {
+public:	
+	AA(){}
+	
+	BB innerObj;
+};
+
+%}
+
+%{
+class Foobar
+{
+public:
+  Foobar()
+  {
+  }
+  
+  char *foo_method()
+  {
+    return 0;
+  }
+  
+};
+
+class Quux
+{
+public:
+  Quux()
+  {
+  }
+  
+  Foobar method()
+  {
+    return Foobar();
+  }
+  
+};
+%}
+
+%feature("novaluewrapper") Foobar;
+class Foobar;
+
+
+class Quux {
+public:
+  Quux();
+  
+  Foobar method();
+
+  
+};
+
+
+#if defined(SWIGPYTHON) 
+
+/*
+  This case can't be fixed by using the valuewrapper feature and the
+  old mechanismbut it works fine with the new mechanism 
+*/
+
+%{
+ 
+  // Template primitive type, only visible in C++
+  template <class T>
+  struct Param
+  {
+    T val;
+
+    // This case is disabled by now
+    // Param(T v): val(v) {}
+
+    Param(T v = T()): val(v) {}
+    
+    operator T() const { return val; }
+  };
+
+%}
+
+/*
+  Several languages have 'not 100% safe' typemaps, 
+  where the following %applies  don't work. 
+*/
+%apply int { Param<int> };
+%apply const int& { const Param<int>& };
+
+%apply double { Param<double> };
+%apply const double& { const Param<double>& };
+
+%inline %{
+
+  template <class T>
+  T getv(const Param<T>& p) 
+  {
+    return p.val;
+  }
+
+  template <class T>
+  Param<T> getp(const T& v)
+  {
+    return  Param<T>(v);
+  }
+  
+%}
+  
+%template(getv_i) getv<int>;
+%template(getp_i) getp<int>;
+
+%template(getv_d) getv<double>;
+%template(getp_d) getp<double>;
+
+#endif
diff --git a/trunk/Examples/test-suite/varargs.i b/trunk/Examples/test-suite/varargs.i
new file mode 100644
index 0000000..41e4903
--- /dev/null
+++ b/trunk/Examples/test-suite/varargs.i
@@ -0,0 +1,38 @@
+// Tests SWIG's *default* handling of varargs.  The default behavior is to simply ignore the varargs.
+%module varargs
+
+%varargs(int mode = 0) test_def;
+%varargs(int mode = 0) Foo::Foo;
+%varargs(int mode = 0) Foo::statictest(const char*fmt, ...);
+
+%inline %{
+char *test(const char *fmt, ...) {
+  return (char *) fmt;
+}
+
+const char *test_def(const char *fmt, ...) {
+  return fmt;
+}
+
+class Foo {
+public:
+    char *str;
+    Foo() {
+        str = NULL;
+    }
+    Foo(const char *fmt, ...) {
+        str = new char[strlen(fmt) + 1];
+        strcpy(str, fmt);
+    }
+    ~Foo() {
+        delete [] str;
+    }
+    char *test(const char *fmt, ...) {
+        return (char *) fmt;
+    }
+    static char *statictest(const char *fmt, ...) {
+        return (char *) fmt;
+    }
+};
+
+%}
diff --git a/trunk/Examples/test-suite/virtual_derivation.i b/trunk/Examples/test-suite/virtual_derivation.i
new file mode 100644
index 0000000..a199646
--- /dev/null
+++ b/trunk/Examples/test-suite/virtual_derivation.i
@@ -0,0 +1,67 @@
+%module virtual_derivation
+
+ /*
+
+ Try to add to your favorite language a runtime test like
+ this:
+ 
+ b = B(3)
+ if (b.get_a() != b.get_b()):
+     print "something is wrong"
+
+
+ The test runs fine with python, but not with ruby.
+ 
+ */
+
+%inline %{
+
+  struct A 
+  {
+    ~A()
+    {
+    }
+    
+    int m_a;
+    
+    A(int a) :m_a(a)
+    {
+    }
+    
+    int get_a()
+    {
+      return m_a;
+    }
+    
+  };
+  
+  struct B : virtual A
+  {
+    B(int a): A(a)
+    {
+    }
+    
+    int get_b()
+    {
+      return get_a();
+    }
+
+    // in ruby, get_a() returns trash if called from b, unless is
+    // wrapped with the previous get_b or using the 'using'
+    // declaration:
+    // using A::get_a;
+  };
+
+
+
+
+  class IndexReader{
+  public:
+    virtual void norms() = 0;
+  };
+
+  class MultiReader : public IndexReader {
+  protected:
+    MultiReader();
+  };
+%}
diff --git a/trunk/Examples/test-suite/virtual_destructor.i b/trunk/Examples/test-suite/virtual_destructor.i
new file mode 100644
index 0000000..f45fccc
--- /dev/null
+++ b/trunk/Examples/test-suite/virtual_destructor.i
@@ -0,0 +1,22 @@
+/*
+This testcase checks that a virtual destructor with void as a parameter is 
+correctly handled.
+Also tests a class with protected destructor derived from a class with a
+public destructor.
+*/
+
+%module virtual_destructor
+
+%inline %{
+
+class VirtualVoidDestructor {
+public:
+  VirtualVoidDestructor() {};
+  virtual ~VirtualVoidDestructor(void) { };
+};
+
+class Derived : public VirtualVoidDestructor {
+protected:
+  virtual ~Derived() {};
+};
+%}
diff --git a/trunk/Examples/test-suite/virtual_poly.i b/trunk/Examples/test-suite/virtual_poly.i
new file mode 100644
index 0000000..d8051ae
--- /dev/null
+++ b/trunk/Examples/test-suite/virtual_poly.i
@@ -0,0 +1,204 @@
+%module(directors="1") virtual_poly
+
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET, SWIGWARN_CSHARP_COVARIANT_RET) copy; /* Java, C# covariant return types */
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET, SWIGWARN_CSHARP_COVARIANT_RET) ref_this; /* Java, C# covariant return types */
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET, SWIGWARN_CSHARP_COVARIANT_RET) covariant; /* Java, C# covariant return types */
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET, SWIGWARN_CSHARP_COVARIANT_RET) covariant2; /* Java, C# covariant return types */
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET, SWIGWARN_CSHARP_COVARIANT_RET) covariant3; /* Java, C# covariant return types */
+%warnfilter(SWIGWARN_JAVA_COVARIANT_RET, SWIGWARN_CSHARP_COVARIANT_RET) covariant4; /* Java, C# covariant return types */
+
+//
+// Check this example with directors wherever possible.
+//
+//%feature("director");
+
+// This shouldn't get used.
+// %newobject *::copy();
+
+%newobject *::copy() const;
+
+
+%inline %{  
+  struct NNumber
+  {
+    virtual ~NNumber() {};
+    virtual NNumber* copy() const = 0;
+    virtual NNumber& ref_this() 
+    {
+      return *this;
+    }
+    
+    
+    NNumber* nnumber() 
+    {
+      return this;
+    }
+    
+
+  };
+  
+  /* 
+     NInt and NDouble are both NNumber derived classes, but they
+     have more different than common attributes.
+     
+     In particular the function 'get', that is type dependent, can't
+     be included in the NNumber abstract interface.
+
+     For this reason, the virtual 'copy' method has a polymorphic (covariant)
+     return type, since in most of the cases we don't want to lose the
+     original object type, which is very very important.
+
+     Using the polymorphic return type reduced greatly the need of
+     using 'dynamic_cast' at the C++ side, and at the target languages
+     that support it.
+   */
+  struct NInt : NNumber
+  {
+    NInt(int v) : val(v) 
+    {
+    }
+    
+    int get() const
+    {
+      return val;
+    }
+    
+    virtual NInt* copy() const
+    {
+      return new NInt(val);
+    }
+
+    virtual NInt& ref_this() 
+    {
+      return *this;
+    }
+
+    /* See below */
+    static NInt* narrow(NNumber* nn);
+
+    
+  private:
+    int val;
+  };
+
+  inline NInt& incr(NInt& i) {
+    i = i.get() + 1;
+    return i;
+  }
+
+  struct NDouble : NNumber
+  {
+    NDouble(double v) : val(v) 
+    {
+    }
+    
+    double get() const
+    {
+      return val;
+    }
+    
+    virtual NDouble* copy() const
+    {
+      return new NDouble(val);
+    }
+
+    virtual NDouble& ref_this() 
+    {
+      return *this;
+    }
+
+    /* See below */
+    static NDouble* narrow(NNumber* nn);
+    
+  private:
+    double val;
+  };
+
+  /*
+     Java and C# do not support the polymorphic (covariant) return types used
+     in the copy method. So, they just emit 'plain' copy functions as if this is
+     being wrapped instead:
+    
+      NNumber* NNumber::copy() const;
+      NNumber* NInt::copy() const;  
+      NNumber* NDouble::copy() const;
+    
+     However, since the objects provide their own downcasting
+     mechanism, the narrow methods similar to the CORBA mechanism,
+     could be used, otherwise use the Java/C# downcasts.
+  */
+  inline NInt* NInt::narrow(NNumber* n) {
+    // this is just a plain C++ dynamic_cast, but in theory the user
+    // could use whatever he wants.
+    return dynamic_cast<NInt*>(n);
+  }  
+  
+  inline NDouble* NDouble::narrow(NNumber* n) {
+    return dynamic_cast<NDouble*>(n);
+  }
+%}
+
+%inline %{
+
+// These three classes test covariant return types and whether swig accurately matches
+// polymorphic methods (mainly for C# override keyword). Also tests methods which hide
+// the base class' method (for C#, new keyword required on method declaration).
+
+typedef int* IntegerPtr;
+typedef double Double;
+
+template<typename T> struct Base {
+  T t;
+  virtual IntegerPtr method() const = 0;
+  virtual IntegerPtr foxy() const = 0;
+  virtual IntegerPtr foxy(int a) const = 0;
+  virtual int * foxy(int*& a) { return 0; }
+  virtual double afunction() = 0;
+  virtual IntegerPtr defaultargs(double d, int * a = 0) = 0;
+  static void StaticHidden() {}
+  void AmIAmINotVirtual() {}
+  IntegerPtr NotVirtual(IntegerPtr i) { return 0; }
+  virtual Base * covariant(int a = 0, int * i = 0) { return 0; }
+  typedef Base * BasePtr;
+  virtual BasePtr covariant2() { return 0; }
+  virtual BasePtr covariant3() { return 0; }
+  virtual ~Base() {}
+};
+
+template<typename T> struct Derived : Base<T> {
+  int * method() const { return 0; }
+  IntegerPtr foxy() const { return 0; }
+  int * foxy(int a) const { return 0; }
+  virtual int * foxy(int*& a) { return 0; }
+  Double afunction() { return 0; }
+  int * defaultargs(Double d, IntegerPtr a = 0) { return 0; }
+  void AmIAmINotVirtual() {}
+  int * NotVirtual(int *i) { return 0; }
+  typedef Derived * DerivedPtr;
+  DerivedPtr covariant(int a = 0, IntegerPtr i = 0) { return 0; }
+  DerivedPtr covariant2() { return 0; }
+  Derived<T> * covariant3() { return 0; }
+  virtual Derived<T> * covariant4(double d) { return 0; }
+  virtual int IsVirtual() { return 0; }
+};
+
+template<typename T> struct Bottom : Derived<T> {
+  int * method() const { return 0; }
+  static void StaticHidden() {}
+  void AmIAmINotVirtual() {}
+  IntegerPtr NotVirtual(IntegerPtr i) { return 0; }
+  void (*funcptr)(int a, bool b);
+  Bottom<T> * covariant(int a = 0, IntegerPtr i = 0) { return 0; }
+  Derived<T> * covariant2() { return 0; }
+  Bottom<T> * covariant3() { return 0; }
+  Bottom<T> * covariant4(double d) { return 0; }
+  int IsVirtual() { return 0; }
+};
+%}
+
+
+%template(BaseInt) Base<int>;
+%template(DerivedInt) Derived<int>;
+%template(BottomInt) Bottom<int>;
+
+
diff --git a/trunk/Examples/test-suite/voidtest.i b/trunk/Examples/test-suite/voidtest.i
new file mode 100644
index 0000000..90779e2
--- /dev/null
+++ b/trunk/Examples/test-suite/voidtest.i
@@ -0,0 +1,23 @@
+%module voidtest
+
+%inline %{
+
+void globalfunc(void) {
+}
+
+class Foo {
+public:
+   Foo(void) { }
+   void memberfunc(void) { }
+   static void staticmemberfunc(void) { }
+};
+
+
+void *vfunc1(void *f) { return f; }
+void *vfunc2(Foo *f) { return f; }
+Foo  *vfunc3(void *f) { return (Foo *) f; }
+Foo  *vfunc4(Foo *f) { return f; }
+ 
+
+%}
+   
diff --git a/trunk/Examples/test-suite/wrapmacro.i b/trunk/Examples/test-suite/wrapmacro.i
new file mode 100644
index 0000000..5353e77
--- /dev/null
+++ b/trunk/Examples/test-suite/wrapmacro.i
@@ -0,0 +1,61 @@
+%module wrapmacro
+
+#ifdef SWIGLUA	// lua only has one numeric type, so some overloads shadow each other creating warnings
+%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) SWIGMACRO_max;
+#endif
+
+/* Testing technique for wrapping macros */
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
+
+/* Here, some macros to wrap */
+%inline %{
+
+typedef unsigned short guint16;
+
+#define GUINT16_SWAP_LE_BE_CONSTANT(val) ((guint16) ( \
+    (guint16) ((guint16) (val) >> 8) |  \
+    (guint16) ((guint16) (val) << 8)))
+
+#define max(a,b) ((a) > (b) ? (a) : (b))
+  
+%}
+
+
+/* Here, the auxiliary macro to wrap a macro */
+%define %wrapmacro(type, name, lparams, lnames)
+%rename(name) SWIGMACRO_##name;
+%inline %{
+type SWIGMACRO_##name(lparams) {
+  return name(lnames);
+}
+%}
+%enddef
+#define PLIST(...) __VA_ARGS__
+
+
+
+/* Here, wrapping the macros */
+%wrapmacro(guint16, GUINT16_SWAP_LE_BE_CONSTANT, guint16 val, val);
+%wrapmacro(size_t, max, PLIST(size_t a, const size_t& b), PLIST(a, b));
+%wrapmacro(double, max, PLIST(double a, double b), PLIST(a, b));
+
+
+/* Maybe in the future, a swig directive will make this easier:
+
+#define max(a,b) ((a) > (b) ? (a) : (b))
+
+%wrapmacro double max(long a, double b); // target name is 'max'
+%wrapmacro(max_i) int max(int a, int b); // changes target name to 'max_i'.
+
+*/
+
+%{
+#ifdef max
+#undef max
+#endif
+%}
diff --git a/trunk/Examples/xml/Makefile.in b/trunk/Examples/xml/Makefile.in
new file mode 100644
index 0000000..dfda4a6
--- /dev/null
+++ b/trunk/Examples/xml/Makefile.in
@@ -0,0 +1,54 @@
+# Examples/xml/Makefile
+
+top_srcdir	= @top_srcdir@
+
+cleanup		= tail +2 \
+		  | sed -e 's/ident="ID[0-9A-F]*"//g' \
+			-e 's,name="/[^"]*/\([^/]*\.swg\)",name="\1",g'
+
+all-dot-i-files =				\
+	error.i					\
+	example.i				\
+	example_apply.i				\
+	example_const.i				\
+	example_gif.i				\
+	example_inl.i				\
+	example_p5.i				\
+	example_ro.i				\
+	example_title_add.i			\
+	example_xml.i				\
+	gnarly.i
+
+all: check
+
+chk-swiglib = $(top_srcdir)/Lib
+
+check:
+	for f in $(all-dot-i-files) ; do				\
+	  base=`basename $$f .i` ;					\
+	  xml=$$base.xml ;						\
+	  SWIG_LIB=$(chk-swiglib) $(top_srcdir)/swig -xml $$xml $$f ;	\
+	  cat $$xml | $(cleanup) | diff -c $$base.expected-xml - ;	\
+	done
+
+clean:
+	rm -f *.xml
+
+distclean: clean
+	rm -f Makefile
+
+# from here on, non-developers beware!
+
+%.expected-xml : %.i
+	SWIG_LIB=$(top_srcdir)/Lib $(top_srcdir)/swig -xml tmp-file $^
+	cat tmp-file | $(cleanup) > $@
+	rm -f tmp-file
+
+all-expected-xml:
+	for f in $(all-dot-i-files) ; do \
+	  make `basename $$f .i`.expected-xml ; done
+
+all-expected-xml-clean:
+	rm -f *.expected-xml
+
+# Examples/xml/Makefile ends here
diff --git a/trunk/Examples/xml/error.expected-xml b/trunk/Examples/xml/error.expected-xml
new file mode 100644
index 0000000..6b1a316
--- /dev/null
+++ b/trunk/Examples/xml/error.expected-xml
@@ -0,0 +1,24 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="error.i" >
+        <swigxml:child >
+          <swig:module name="error"  />
+          <c:enum >
+            <swigxml:child >
+              <c:enumvalue name="RED" >
+                <swigxml:value string="RED"  />
+              </c:enumvalue>
+              <c:enumvalue name="GREEN"  />
+              <c:enumvalue name="BLUE"  />
+            </swigxml:child>
+          </c:enum>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/error.i b/trunk/Examples/xml/error.i
new file mode 100644
index 0000000..7ea59a0
--- /dev/null
+++ b/trunk/Examples/xml/error.i
@@ -0,0 +1,2 @@
+%module error
+enum { RED=10, GREEN, BLUE };
\ No newline at end of file
diff --git a/trunk/Examples/xml/example.expected-xml b/trunk/Examples/xml/example.expected-xml
new file mode 100644
index 0000000..2823136
--- /dev/null
+++ b/trunk/Examples/xml/example.expected-xml
@@ -0,0 +1,23 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example.i" >
+        <swigxml:child >
+          <swig:module name="example"  />
+          <swig:apply name="OUTPUT" >
+            <swigxml:parms >
+              <swigxml:none name="r" >
+                <swigxml:type string="p.int"  />
+              </swigxml:none>
+            </swigxml:parms>
+            <swigxml:type string="p.int"  />
+          </swig:apply>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example.h b/trunk/Examples/xml/example.h
new file mode 100644
index 0000000..7f31fce
--- /dev/null
+++ b/trunk/Examples/xml/example.h
@@ -0,0 +1,3 @@
+// i add this file because it's referenced by other files.
+// someone should replace these comments w/ proper content.
+//   --ttn, 2001/01/16 17:44:19
diff --git a/trunk/Examples/xml/example.i b/trunk/Examples/xml/example.i
new file mode 100644
index 0000000..77d571e
--- /dev/null
+++ b/trunk/Examples/xml/example.i
@@ -0,0 +1,8 @@
+/* File : example.i */
+%module example
+
+%apply int *OUTPUT { int *r };
+
+
+
+
diff --git a/trunk/Examples/xml/example_apply.expected-xml b/trunk/Examples/xml/example_apply.expected-xml
new file mode 100644
index 0000000..50a6509
--- /dev/null
+++ b/trunk/Examples/xml/example_apply.expected-xml
@@ -0,0 +1,1486 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_apply.i" >
+        <swigxml:child >
+          <swig:module name="example"  />
+          <c:function name="add" >
+            <swigxml:parms >
+              <swigxml:parm name="x" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="result" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:file name="../../Lib/pointer.i" >
+            <swigxml:child >
+              <swig:module name="pointer"  />
+              <swig:insert >
+                <swigxml:code >
+
+%include pointer.i
+
+The pointer.i library provides run-time support for managing and 
+manipulating a variety of C/C++ pointer values.  In particular,
+you can create various kinds of objects and dereference common
+pointer types.  This is done through a common set of functions:
+
+    ptrvalue     - Dereferences a pointer 
+    ptrset       - Set the value of an object referenced by 
+                   a pointer.
+    ptrcreate    - Create a new object and return a pointer.
+    ptrfree      - Free the memory allocated by ptrcreate.
+    ptradd       - Increment/decrement a pointer value.
+
+When creating, dereferencing, or setting the value of pointer
+variable, only the common C datatypes of int, short, long, float,
+double, char, and char * are currently supported.   Other
+datatypes may generate an error.
+
+One of the more interesting aspects of this library is that
+it operates with a wide range of datatypes.  For example,
+the "ptrvalue" function can dereference "double *", "int *",
+"long *", "char *", and other datatypes. Since SWIG encodes
+pointers with type information, this can be done transparently
+and in most cases, you can dereference a pointer without
+ever knowing what type it actually is.
+
+This library is primarily designed for utility, not high 
+performance (the dynamic determination of pointer types takes
+more work than most normal wrapper functions).  As a result,
+you may achieve better performance by writing customized
+"helper" functions if you're making lots of calls to these
+functions in inner loops or other intensive operations.
+                </swigxml:code>
+                <swigxml:section string="doc"  />
+              </swig:insert>
+              <swig:types >
+                <swigxml:parms >
+                  <swigxml:parm >
+                    <swigxml:type string="p.int"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.short"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.long"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.float"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.double"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.char"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.p.char"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.void"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+              </swig:types>
+              <swig:file name="../../Lib/xml/ptrlang.i" >
+                <swigxml:child >
+                  <swig:insert >
+                    <swigxml:code >
+
+#include &amp;lt;ctype.h>
+
+/* Types used by the library */
+static swig_type_info *SWIG_POINTER_int_p = 0;
+static swig_type_info *SWIG_POINTER_short_p =0;
+static swig_type_info *SWIG_POINTER_long_p = 0;
+static swig_type_info *SWIG_POINTER_float_p = 0;
+static swig_type_info *SWIG_POINTER_double_p = 0;
+static swig_type_info *SWIG_POINTER_char_p = 0;
+static swig_type_info *SWIG_POINTER_char_pp = 0;
+static swig_type_info *SWIG_POINTER_void_p = 0;
+                    </swigxml:code>
+                  </swig:insert>
+                  <swig:insert >
+                    <swigxml:code >
+
+  SWIG_POINTER_int_p = SWIG_TypeQuery("int *");
+  SWIG_POINTER_short_p = SWIG_TypeQuery("short *");
+  SWIG_POINTER_long_p = SWIG_TypeQuery("long *");
+  SWIG_POINTER_float_p = SWIG_TypeQuery("float *");
+  SWIG_POINTER_double_p = SWIG_TypeQuery("double *");
+  SWIG_POINTER_char_p = SWIG_TypeQuery("char *");
+  SWIG_POINTER_char_pp = SWIG_TypeQuery("char **");
+  SWIG_POINTER_void_p = SWIG_TypeQuery("void *");
+                    </swigxml:code>
+                    <swigxml:section string="init"  />
+                  </swig:insert>
+                  <swig:insert >
+                    <swigxml:code >
+
+
+/* #ifdef WIN32
+#undef isspace
+#define isspace(c) (c == ' ')
+#endif
+*/
+
+/*------------------------------------------------------------------
+  ptrvalue(ptr,type = 0)
+
+  Attempts to dereference a pointer value.  If type is given, it
+  will try to use that type.  Otherwise, this function will attempt
+  to "guess" the proper datatype by checking against all of the
+  builtin C datatypes.
+  ------------------------------------------------------------------ */
+
+#ifdef PERL_OBJECT
+static SV *_ptrvalue(CPerlObj *pPerl,SV *_PTRVALUE, int index, char *type) {
+#define ptrvalue(a,b,c) _ptrvalue(pPerl,a,b,c)
+#else
+static SV *_ptrvalue(SV *_PTRVALUE, int index, char *type) {
+#define ptrvalue(a,b,c) _ptrvalue(a,b,c)
+#endif
+
+  void     *ptr;
+  SV       *obj = 0;
+
+  if (SWIG_ConvertPtr(_PTRVALUE, &amp;ptr, 0) &amp;lt; 0) {
+    croak("Type error it ptrvalue. Argument is not a valid pointer value.");
+  } else {
+    /* If no datatype was passed, try a few common datatypes first */
+    if (!type) {
+
+      /* No datatype was passed.   Type to figure out if it's a common one */
+
+      if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_int_p) >= 0) {
+	type = "int";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_double_p) >= 0) {
+	type = "double";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_short_p) >= 0) {
+	type = "short";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_long_p) >= 0) {
+	type = "long";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_float_p) >= 0) {
+	type = "float";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_p) >= 0) {
+	type = "char";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_pp) >= 0) {
+	type = "char *";
+      } else {
+	type = "unknown";
+      }
+    }
+
+    if (!ptr) {
+      croak("Unable to dereference NULL pointer.");
+      return 0;
+    }
+
+    /* Now we have a datatype.  Try to figure out what to do about it */
+    if (strcmp(type,"int") == 0) {
+      obj = sv_newmortal();
+      sv_setiv(obj,(IV) *(((int *) ptr) + index));
+    } else if (strcmp(type,"double") == 0) {
+      obj = sv_newmortal();
+      sv_setnv(obj,(double) *(((double *) ptr)+index));
+    } else if (strcmp(type,"short") == 0) {
+      obj = sv_newmortal();
+      sv_setiv(obj,(IV) *(((short *) ptr) + index));
+    } else if (strcmp(type,"long") == 0) {
+      obj = sv_newmortal();
+      sv_setiv(obj,(IV) *(((long *) ptr) + index));
+    } else if (strcmp(type,"float") == 0) {
+      obj = sv_newmortal();
+      sv_setnv(obj,(double) *(((float *) ptr)+index));
+    } else if (strcmp(type,"char") == 0) {
+      obj = sv_newmortal();
+      sv_setpv(obj,((char *) ptr)+index);
+    } else if (strcmp(type,"char *") == 0) {
+      char *c = *(((char **) ptr)+index);
+      obj = sv_newmortal();
+      if (c)
+	sv_setpv(obj,c);
+      else
+	sv_setpv(obj,"NULL");
+    } else {
+      croak("Unable to dereference unsupported datatype.");
+      obj = 0;
+    }
+  }
+  return obj;
+}
+
+/*------------------------------------------------------------------
+  ptrcreate(type,value = 0,numelements = 1)
+
+  Attempts to create a new object of given type.  Type must be
+  a basic C datatype.  Will not create complex objects.
+  ------------------------------------------------------------------ */
+#ifdef PERL_OBJECT
+static SV *_ptrcreate(CPerlObj *pPerl, char *type, SV *value, int numelements) {
+#define ptrcreate(a,b,c) _ptrcreate(pPerl,a,b,c)
+#else
+static SV *_ptrcreate(char *type, SV *value, int numelements) {
+#define ptrcreate(a,b,c) _ptrcreate(a,b,c)
+#endif
+
+  void     *ptr;
+  SV       *obj;
+  int       sz;
+  swig_type_info *cast = 0;
+
+  /* Check the type string against a variety of possibilities */
+
+  if (strcmp(type,"int") == 0) {
+    sz = sizeof(int)*numelements;
+    cast = SWIG_POINTER_int_p;
+  } else if (strcmp(type,"short") == 0) {
+    sz = sizeof(short)*numelements;
+    cast = SWIG_POINTER_short_p;
+  } else if (strcmp(type,"long") == 0) {
+    sz = sizeof(long)*numelements;
+    cast = SWIG_POINTER_long_p;
+  } else if (strcmp(type,"double") == 0) {
+    sz = sizeof(double)*numelements;
+    cast = SWIG_POINTER_double_p;
+  } else if (strcmp(type,"float") == 0) {
+    sz = sizeof(float)*numelements;
+    cast = SWIG_POINTER_float_p;
+  } else if (strcmp(type,"char") == 0) {
+    sz = sizeof(char)*numelements;
+    cast = SWIG_POINTER_char_p;
+  } else if (strcmp(type,"char *") == 0) {
+    sz = sizeof(char *)*(numelements+1);
+    cast = SWIG_POINTER_char_pp;
+  } else if (strcmp(type,"void") == 0) {
+    sz = numelements;
+    cast = SWIG_POINTER_void_p;
+  } else {
+    croak("Unable to create unknown datatype.");
+    return 0;
+  }
+
+  /* Create the new object */
+
+  ptr = (void *) malloc(sz);
+  if (!ptr) {
+    croak("Out of memory in ptrcreate.");
+    return 0;
+  }
+
+  /* Now try to set its default value */
+
+  if (value) {
+    if (strcmp(type,"int") == 0) {
+      int *ip,i,ivalue;
+      ivalue = (int) SvIV(value);
+      ip = (int *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"short") == 0) {
+      short *ip,ivalue;
+      int i;
+      ivalue = (short) SvIV(value);
+      ip = (short *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"long") == 0) {
+      long *ip,ivalue;
+      int i;
+      ivalue = (long) SvIV(value);
+      ip = (long *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"double") == 0) {
+      double *ip,ivalue;
+      int i;
+      ivalue = (double) SvNV(value);
+      ip = (double *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"float") == 0) {
+      float *ip,ivalue;
+      int i;
+      ivalue = (float) SvNV(value);
+      ip = (float *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"char") == 0) {
+      char *ip,*ivalue;
+      ivalue = (char *) SvPV(value,PL_na);
+      ip = (char *) ptr;
+      strncpy(ip,ivalue,numelements-1);
+    } else if (strcmp(type,"char *") == 0) {
+      char **ip, *ivalue;
+      int  i;
+      ivalue = (char *) SvPV(value,PL_na);
+      ip = (char **) ptr;
+      for (i = 0; i &amp;lt; numelements; i++) {
+	if (ivalue) {
+	  ip[i] = (char *) malloc(strlen(ivalue)+1);
+	  strcpy(ip[i],ivalue);
+	} else {
+	  ip[i] = 0;
+	}
+      }
+      ip[numelements] = 0;
+    }
+  }
+  /* Create the pointer value */
+
+
+  obj = sv_newmortal();
+  SWIG_MakePtr(obj,ptr,cast);
+  return obj;
+}
+
+/*------------------------------------------------------------------
+  ptrset(ptr,value,index = 0,type = 0)
+
+  Attempts to set the value of a pointer variable.  If type is
+  given, we will use that type.  Otherwise, we'll guess the datatype.
+  ------------------------------------------------------------------ */
+
+#ifdef PERL_OBJECT
+static void _ptrset(CPerlObj *pPerl,SV *_PTRVALUE, SV *value, int index, char *type) {
+#define ptrset(a,b,c,d) _ptrset(pPerl,a,b,c,d)
+#else
+static void _ptrset(SV *_PTRVALUE, SV *value, int index, char *type) {
+#define ptrset(a,b,c,d) _ptrset(a,b,c,d)
+#endif
+  void     *ptr;
+  SV       *obj;
+
+
+  if (SWIG_ConvertPtr(_PTRVALUE, &amp;ptr, 0) &amp;lt; 0) {
+    croak("Type error it ptrvalue. Argument is not a valid pointer value.");
+  } else {
+    /* If no datatype was passed, try a few common datatypes first */
+    if (!type) {
+      /* No datatype was passed.   Type to figure out if it's a common one */
+      if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_int_p) >= 0) {
+	type = "int";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_double_p) >= 0) {
+	type = "double";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_short_p) >= 0) {
+	type = "short";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_long_p) >= 0) {
+	type = "long";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_float_p) >= 0) {
+	type = "float";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_p) >= 0) {
+	type = "char";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_pp) >= 0) {
+	type = "char *";
+      } else {
+	type = "unknown";
+      }
+    }
+  }
+  if (!ptr) {
+    croak("Unable to set NULL pointer.");
+    return;
+  }
+
+  /* Now we have a datatype.  Try to figure out what to do about it */
+  if (strcmp(type,"int") == 0) {
+    *(((int *) ptr)+index) = (int) SvIV(value);
+  } else if (strcmp(type,"double") == 0) {
+    *(((double *) ptr)+index) = (double) SvNV(value);
+  } else if (strcmp(type,"short") == 0) {
+    *(((short *) ptr)+index) = (short) SvIV(value);
+  } else if (strcmp(type,"long") == 0) {
+    *(((long *) ptr)+index) = (long) SvIV(value);
+  } else if (strcmp(type,"float") == 0) {
+    *(((float *) ptr)+index) = (float) SvNV(value);
+  } else if (strcmp(type,"char") == 0) {
+    char *c = SvPV(value,PL_na);
+    strcpy(((char *) ptr)+index, c);
+  } else if (strcmp(type,"char *") == 0) {
+    char *c = SvPV(value,PL_na);
+    char **ca = (char **) ptr;
+    if (ca[index]) free(ca[index]);
+    if (strcmp(c,"NULL") == 0) {
+      ca[index] = 0;
+    } else {
+      ca[index] = (char *) malloc(strlen(c)+1);
+      strcpy(ca[index],c);
+    }
+  } else {
+    croak("Unable to set unsupported datatype.");
+    return;
+  }
+}
+
+/*------------------------------------------------------------------
+  ptradd(ptr,offset)
+
+  Adds a value to an existing pointer value.  Will do a type-dependent
+  add for basic datatypes.  For other datatypes, will do a byte-add.
+  ------------------------------------------------------------------ */
+
+#ifdef PERL_OBJECT
+static SV *_ptradd(CPerlObj *pPerl, SV *_PTRVALUE, int offset) {
+#define ptradd(a,b) _ptradd(pPerl,a,b)
+#else
+static SV *_ptradd(SV *_PTRVALUE, int offset) {
+#define ptradd(a,b) _ptradd(a,b)
+#endif
+
+  void *ptr,*junk;
+  SV   *obj;
+  swig_type_info *type;
+  char *tname;
+
+  /* Try to handle a few common datatypes first */
+
+  if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_int_p) >= 0) {
+    ptr = (void *) (((int *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_double_p) >= 0) {
+    ptr = (void *) (((double *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_short_p) >= 0) {
+    ptr = (void *) (((short *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_long_p) >= 0) {
+    ptr = (void *) (((long *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_float_p) >= 0) {
+    ptr = (void *) (((float *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_p) >= 0) {
+    ptr = (void *) (((char *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,0) >= 0) {
+    ptr = (void *) (((char *) ptr) + offset);
+  } else {
+    croak("Type error in ptradd. Argument is not a valid pointer value.");
+    return 0;
+  }
+  printf("ptradd = %x\n", ptr);
+  tname = HvNAME(SvSTASH(SvRV(_PTRVALUE)));
+  obj = sv_newmortal();
+  sv_setref_pv(obj,tname,ptr);
+  return obj;
+}
+
+/*------------------------------------------------------------------
+  ptrfree(ptr)
+
+  Destroys a pointer value
+  ------------------------------------------------------------------ */
+#ifdef PERL_OBJECT
+void _ptrfree(CPerlObj *pPerl, SV *_PTRVALUE) {
+#define ptrfree(a) _ptrfree(pPerl, a)
+#else
+void _ptrfree(SV *_PTRVALUE) {
+#define ptrfree(a) _ptrfree(a)
+#endif
+
+  void *ptr, *junk;
+
+  if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,0) &amp;lt; 0) {
+    croak("Type error in ptrfree. Argument is not a valid pointer value.");
+    return;
+  }
+
+  /* Check to see if this pointer is a char ** */
+  if (SWIG_ConvertPtr(_PTRVALUE,&amp;junk,SWIG_POINTER_char_pp) >= 0) {
+    char **c = (char **) ptr;
+    if (c) {
+      int i = 0;
+      while (c[i]) {
+	free(c[i]);
+	i++;
+      }
+    }
+  }
+  if (ptr)
+    free((char *) ptr);
+}
+
+                    </swigxml:code>
+                  </swig:insert>
+                  <swig:typemap name="ptr" >
+                    <swigxml:code >
+{
+  $target = $source;
+}                    </swigxml:code>
+                    <swigxml:method string="in"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="value" >
+                    <swigxml:code >
+{
+  $target = $source;
+}                    </swigxml:code>
+                    <swigxml:method string="in"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrcast" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrvalue" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrcreate" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptradd" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrset" >
+                    <swigxml:code >
+{
+  if ($source == -1) return NULL;
+}                    </swigxml:code>
+                    <swigxml:method string="ret"  />
+                    <swigxml:type string="int"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <c:function name="ptrvalue" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="index" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="type" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="p.char"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="p.SV"  />
+                  </c:function>
+                  <c:function name="ptrset" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="value" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="index" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="type" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="p.char"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="void"  />
+                  </c:function>
+                  <c:function name="ptrcreate" >
+                    <swigxml:parms >
+                      <swigxml:parm name="type" >
+                        <swigxml:type string="p.char"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="value" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="nitems" >
+                        <swigxml:value string="1"  />
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="p.SV"  />
+                  </c:function>
+                  <c:function name="ptrfree" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="void"  />
+                  </c:function>
+                  <c:function name="ptradd" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="offset" >
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="p.SV"  />
+                  </c:function>
+                </swigxml:child>
+                <swigxml:type string="include"  />
+              </swig:file>
+            </swigxml:child>
+            <swigxml:type string="include"  />
+          </swig:file>
+          <swig:file name="../../Lib/xml/typemaps.i" >
+            <swigxml:child >
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (double) SvNV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="float"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (float) SvNV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (int) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (short) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (long) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned int) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned short) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned long) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned char"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned char) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned char"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="float"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setnv($target,(double) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setnv($target,(double) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.int"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.short"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.long"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned short"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned long"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned char"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.float"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.double"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.int"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.short"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.long"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned short"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned long"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned char"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.float"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.double"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
+	printf("Received %d\n", SvTYPE(tempsv));
+	croak("Expected a double reference.");
+  }
+  dvalue = SvNV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="float"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
+    croak("expected a double reference");
+  }
+  dvalue = (float) SvNV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (short) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (long) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="unsigned int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (unsigned int) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="unsigned short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (unsigned short) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="unsigned long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (unsigned long) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setnv(tempsv, (double) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setnv(tempsv, (double) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+            </swigxml:child>
+            <swigxml:type string="include"  />
+          </swig:file>
+          <c:function name="sub" >
+            <swigxml:parms >
+              <swigxml:parm name="INPUT" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="INPUT" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="OUTPUT" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:apply name="OUTPUT" >
+            <swigxml:parms >
+              <swigxml:none name="r" >
+                <swigxml:type string="p.int"  />
+              </swigxml:none>
+            </swigxml:parms>
+            <swigxml:type string="p.int"  />
+          </swig:apply>
+          <c:function name="divide" >
+            <swigxml:parms >
+              <swigxml:parm name="n" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="d" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="r" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:function>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_apply.i b/trunk/Examples/xml/example_apply.i
new file mode 100644
index 0000000..2ed2b5b
--- /dev/null
+++ b/trunk/Examples/xml/example_apply.i
@@ -0,0 +1,23 @@
+/* File : example.i */
+%module example
+
+/* This example illustrates a couple of different techniques
+   for manipulating C pointers */
+
+/* First we'll use the pointer library */
+extern void add(int *x, int *y, int *result);
+%include pointer.i
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
+
+/* Next we'll use typemaps and the %apply directive */
+
+%apply int *OUTPUT { int *r };
+extern int divide(int n, int d, int *r);
+
+
+
+
diff --git a/trunk/Examples/xml/example_const.expected-xml b/trunk/Examples/xml/example_const.expected-xml
new file mode 100644
index 0000000..eee768c
--- /dev/null
+++ b/trunk/Examples/xml/example_const.expected-xml
@@ -0,0 +1,51 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_const.i" >
+        <swigxml:child >
+          <swig:module name="example"  />
+          <swig:constant name="ICONST" >
+            <swigxml:value string="42"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="FCONST" >
+            <swigxml:value string="2.1828"  />
+            <swigxml:type string="double"  />
+          </swig:constant>
+          <swig:constant name="CCONST" >
+            <swigxml:value string="x"  />
+            <swigxml:type string="char"  />
+          </swig:constant>
+          <swig:constant name="CCONST2" >
+            <swigxml:value string="\n"  />
+            <swigxml:type string="char"  />
+          </swig:constant>
+          <swig:constant name="SCONST" >
+            <swigxml:value string="Hello World"  />
+            <swigxml:type string="p.char"  />
+          </swig:constant>
+          <swig:constant name="SCONST2" >
+            <swigxml:value string="\&quot;Hello World\&quot;"  />
+            <swigxml:type string="p.char"  />
+          </swig:constant>
+          <swig:constant name="EXPR" >
+            <swigxml:value string="42+3*(2.1828)"  />
+            <swigxml:type string="double"  />
+          </swig:constant>
+          <c:variable name="iconst" >
+            <swigxml:value string="37"  />
+            <swigxml:type string="q(const).int"  />
+          </c:variable>
+          <c:variable name="fconst" >
+            <swigxml:value string="3.14"  />
+            <swigxml:type string="q(const).double"  />
+          </c:variable>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_const.i b/trunk/Examples/xml/example_const.i
new file mode 100644
index 0000000..29a1a7f
--- /dev/null
+++ b/trunk/Examples/xml/example_const.i
@@ -0,0 +1,26 @@
+/* File : example.i */
+%module example
+
+/* A few preprocessor macros */
+
+#define    ICONST      42
+#define    FCONST      2.1828
+#define    CCONST      'x'
+#define    CCONST2     '\n'
+#define    SCONST      "Hello World"
+#define    SCONST2     "\"Hello World\""
+
+/* This should work just fine */
+#define    EXPR        ICONST + 3*(FCONST)
+
+/* This shouldn't do anything */
+#define    EXTERN      extern
+
+/* Neither should this (BAR isn't defined) */
+#define    FOO         (ICONST + BAR)
+
+/* The following statements also produce constants */
+const int     iconst = 37;
+const double  fconst = 3.14;
+
+
diff --git a/trunk/Examples/xml/example_gif.expected-xml b/trunk/Examples/xml/example_gif.expected-xml
new file mode 100644
index 0000000..3b21b8e
--- /dev/null
+++ b/trunk/Examples/xml/example_gif.expected-xml
@@ -0,0 +1,2338 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_gif.i" >
+        <swigxml:child >
+          <c:typedef name="Pixel" >
+            <swigxml:type string="unsigned char"  />
+          </c:typedef>
+          <c:typedef name="Zvalue" >
+            <swigxml:type string="float"  />
+          </c:typedef>
+          <c:class name="ColorMap" >
+            <swigxml:child >
+              <c:variable name="cmap" >
+                <swigxml:type string="p.unsigned char"  />
+              </c:variable>
+              <c:variable name="name" >
+                <swigxml:type string="p.char"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="ColorMap"  />
+            <swigxml:altname string="ColorMap"  />
+          </c:class>
+          <c:typedef name="ColorMap" >
+            <swigxml:type string="ColorMap"  />
+          </c:typedef>
+          <c:function name="new_ColorMap" >
+            <swigxml:parms >
+              <swigxml:parm name="filename" >
+                <swigxml:type string="p.char"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.ColorMap"  />
+          </c:function>
+          <c:function name="delete_ColorMap" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="ColorMap_default" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="ColorMap_assign" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="index" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="r" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="g" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="b" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="ColorMap_getitem" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="index" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:function>
+          <c:function name="ColorMap_setitem" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="index" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="value" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="ColorMap_write" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="filename" >
+                <swigxml:type string="p.char"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:function>
+          <swig:constant name="BLACK" >
+            <swigxml:value string="0"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="WHITE" >
+            <swigxml:value string="1"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="RED" >
+            <swigxml:value string="2"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="GREEN" >
+            <swigxml:value string="3"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="BLUE" >
+            <swigxml:value string="4"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="YELLOW" >
+            <swigxml:value string="5"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="CYAN" >
+            <swigxml:value string="6"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="MAGENTA" >
+            <swigxml:value string="7"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <c:class name="FrameBuffer" >
+            <swigxml:child >
+              <c:variable name="pixels" >
+                <swigxml:type string="p.p.Pixel"  />
+              </c:variable>
+              <c:variable name="zbuffer" >
+                <swigxml:type string="p.p.Zvalue"  />
+              </c:variable>
+              <c:variable name="height" >
+                <swigxml:type string="unsigned int"  />
+              </c:variable>
+              <c:variable name="width" >
+                <swigxml:type string="unsigned int"  />
+              </c:variable>
+              <c:variable name="xmin" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="ymin" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="xmax" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="ymax" >
+                <swigxml:type string="int"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="FrameBuffer"  />
+            <swigxml:altname string="FrameBuffer"  />
+          </c:class>
+          <c:typedef name="FrameBuffer" >
+            <swigxml:type string="FrameBuffer"  />
+          </c:typedef>
+          <swig:constant name="ZMIN" >
+            <swigxml:value string="1e+36"  />
+            <swigxml:type string="double"  />
+          </swig:constant>
+          <c:function name="new_FrameBuffer" >
+            <swigxml:parms >
+              <swigxml:parm name="width" >
+                <swigxml:type string="unsigned int"  />
+              </swigxml:parm>
+              <swigxml:parm name="height" >
+                <swigxml:type string="unsigned int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.FrameBuffer"  />
+          </c:function>
+          <c:function name="delete_FrameBuffer" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_resize" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="width" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="height" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:function>
+          <c:function name="FrameBuffer_clear" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_plot" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_horizontal" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_horizontalinterp" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_vertical" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_box" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_solidbox" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_interpbox" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c3" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c4" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_circle" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="radius" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_solidcircle" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="radius" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_line" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_setclip" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_noclip" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_makeGIF" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="cmap" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="buffer" >
+                <swigxml:type string="p.void"  />
+              </swigxml:parm>
+              <swigxml:parm name="maxsize" >
+                <swigxml:type string="unsigned int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:function>
+          <c:function name="FrameBuffer_writeGIF" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="p.ColorMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="filename" >
+                <swigxml:type string="p.char"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:function>
+          <c:function name="FrameBuffer_zresize" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="width" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="height" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_zclear" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_solidtriangle" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_interptriangle" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="tx1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="ty1" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="tx2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="ty2" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="tx3" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="ty3" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c3" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:constant name="HORIZONTAL" >
+            <swigxml:value string="1"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="VERTICAL" >
+            <swigxml:value string="2"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <c:function name="FrameBuffer_drawchar" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="fgcolor" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="bgcolor" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="chr" >
+                <swigxml:type string="char"  />
+              </swigxml:parm>
+              <swigxml:parm name="orientation" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_drawstring" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="fgcolor" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="bgcolor" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="text" >
+                <swigxml:type string="p.char"  />
+              </swigxml:parm>
+              <swigxml:parm name="orientation" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:class name="PixMap" >
+            <swigxml:child >
+              <c:variable name="width" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="height" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="centerx" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="centery" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="map" >
+                <swigxml:type string="p.int"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="PixMap"  />
+            <swigxml:altname string="PixMap"  />
+          </c:class>
+          <c:typedef name="PixMap" >
+            <swigxml:type string="PixMap"  />
+          </c:typedef>
+          <c:function name="new_PixMap" >
+            <swigxml:parms >
+              <swigxml:parm name="width" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="height" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="centerx" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="centery" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.PixMap"  />
+          </c:function>
+          <c:function name="delete_PixMap" >
+            <swigxml:parms >
+              <swigxml:parm name="pm" >
+                <swigxml:type string="p.PixMap"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="PixMap_set" >
+            <swigxml:parms >
+              <swigxml:parm name="pm" >
+                <swigxml:type string="p.PixMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="pix" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="FrameBuffer_drawpixmap" >
+            <swigxml:parms >
+              <swigxml:parm name="f" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="pm" >
+                <swigxml:type string="p.PixMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="fgcolor" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="bgcolor" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:constant name="TRANSPARENT" >
+            <swigxml:value string="0"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="FOREGROUND" >
+            <swigxml:value string="1"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="BACKGROUND" >
+            <swigxml:value string="2"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <c:class name="Plot2D" >
+            <swigxml:child >
+              <c:variable name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </c:variable>
+              <c:variable name="view_xmin" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="view_ymin" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="view_xmax" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="view_ymax" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="xmin" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ymin" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="xmax" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ymax" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="xscale" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="yscale" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="dx" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="dy" >
+                <swigxml:type string="double"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="Plot2D"  />
+            <swigxml:altname string="Plot2D"  />
+          </c:class>
+          <c:typedef name="Plot2D" >
+            <swigxml:type string="Plot2D"  />
+          </c:typedef>
+          <c:function name="new_Plot2D" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.Plot2D"  />
+          </c:function>
+          <c:function name="delete_Plot2D" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_copy" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.Plot2D"  />
+          </c:function>
+          <c:function name="Plot2D_clear" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_setview" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="vxmin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="vymin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="vxmax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="vymax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_setrange" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_setscale" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="xscale" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="yscale" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_plot" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_box" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_solidbox" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_interpbox" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c3" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="c4" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_circle" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="radius" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_solidcircle" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="radius" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_line" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_start" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_drawpixmap" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="pm" >
+                <swigxml:type string="p.PixMap"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="bgcolor" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_xaxis" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="xtick" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ticklength" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_yaxis" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ytick" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ticklength" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_triangle" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_solidtriangle" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot2D_interptriangle" >
+            <swigxml:parms >
+              <swigxml:parm name="p2" >
+                <swigxml:type string="p.Plot2D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c3" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:constant name="LINEAR" >
+            <swigxml:value string="10"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <swig:constant name="LOG" >
+            <swigxml:value string="11"  />
+            <swigxml:type string="int"  />
+          </swig:constant>
+          <c:typedef name="Matrix" >
+            <swigxml:type string="p.double"  />
+          </c:typedef>
+          <c:class name="GL_Vector" >
+            <swigxml:child >
+              <c:variable name="x" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="y" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="z" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="w" >
+                <swigxml:type string="double"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="GL_Vector"  />
+            <swigxml:altname string="GL_Vector"  />
+          </c:class>
+          <c:typedef name="GL_Vector" >
+            <swigxml:type string="GL_Vector"  />
+          </c:typedef>
+          <c:function name="new_Matrix" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="Matrix"  />
+          </c:function>
+          <c:function name="delete_Matrix" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_copy" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="Matrix"  />
+          </c:function>
+          <c:function name="Matrix_multiply" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="b" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_identity" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_zero" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_transpose" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="result" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_invert" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="inva" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_transform" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="r" >
+                <swigxml:type string="p.GL_Vector"  />
+              </swigxml:parm>
+              <swigxml:parm name="t" >
+                <swigxml:type string="p.GL_Vector"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_transform4" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="rx" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ry" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="rz" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="rw" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="t" >
+                <swigxml:type string="p.GL_Vector"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_print" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_translate" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="tx" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ty" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="tz" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_rotatex" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_rotatey" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Matrix_rotatez" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Matrix"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:class name="Plot3D" >
+            <swigxml:child >
+              <c:variable name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </c:variable>
+              <c:variable name="view_xmin" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="view_ymin" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="view_xmax" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="view_ymax" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="xmin" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ymin" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="zmin" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="xmax" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ymax" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="zmax" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="xcenter" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ycenter" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="zcenter" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="fovy" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="aspect" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="znear" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="zfar" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="center_mat" >
+                <swigxml:type string="Matrix"  />
+              </c:variable>
+              <c:variable name="model_mat" >
+                <swigxml:type string="Matrix"  />
+              </c:variable>
+              <c:variable name="view_mat" >
+                <swigxml:type string="Matrix"  />
+              </c:variable>
+              <c:variable name="fullmodel_mat" >
+                <swigxml:type string="Matrix"  />
+              </c:variable>
+              <c:variable name="trans_mat" >
+                <swigxml:type string="Matrix"  />
+              </c:variable>
+              <c:variable name="lookatz" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="xshift" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="yshift" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="zoom" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="width" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="height" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="pers_mode" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="ortho_left" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ortho_right" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ortho_bottom" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="ortho_top" >
+                <swigxml:type string="double"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="Plot3D"  />
+            <swigxml:altname string="Plot3D"  />
+          </c:class>
+          <c:typedef name="Plot3D" >
+            <swigxml:type string="Plot3D"  />
+          </c:typedef>
+          <c:function name="new_Plot3D" >
+            <swigxml:parms >
+              <swigxml:parm name="frame" >
+                <swigxml:type string="p.FrameBuffer"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="zmin" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="xmax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="ymax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="zmax" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.Plot3D"  />
+          </c:function>
+          <c:function name="delete_Plot3D" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_copy" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.Plot3D"  />
+          </c:function>
+          <c:function name="Plot3D_clear" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="Color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_perspective" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="fovy" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="znear" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="zfar" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_ortho" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="left" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="right" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="top" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="bottom" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_lookat" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="z" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_autoperspective" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="fovy" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_autoortho" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotx" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_roty" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotz" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotl" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotr" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotd" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotu" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_rotc" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="deg" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_zoom" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="percent" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_left" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="percent" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_right" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="percent" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_down" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="percent" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_up" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="percent" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_center" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="cx" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="cy" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_plot" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="Color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_setview" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="vxmin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="vymin" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="vxmax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+              <swigxml:parm name="vymax" >
+                <swigxml:type string="int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_start" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_line" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_triangle" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_solidtriangle" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_interptriangle" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c3" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_quad" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_solidquad" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="x4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="color" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_interpquad" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z1" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c1" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z2" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c2" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z3" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c3" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="x4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z4" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c4" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_solidsphere" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="radius" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="Plot3D_outlinesphere" >
+            <swigxml:parms >
+              <swigxml:parm name="p3" >
+                <swigxml:type string="p.Plot3D"  />
+              </swigxml:parm>
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="radius" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="c" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+              <swigxml:parm name="bc" >
+                <swigxml:type string="Pixel"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:variable name="PixMap_SQUARE" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="PixMap"  />
+          </c:variable>
+          <c:variable name="PixMap_TRIANGLE" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="PixMap"  />
+          </c:variable>
+          <c:variable name="PixMap_CROSS" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="PixMap"  />
+          </c:variable>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_gif.i b/trunk/Examples/xml/example_gif.i
new file mode 100644
index 0000000..f0fb3b1
--- /dev/null
+++ b/trunk/Examples/xml/example_gif.i
@@ -0,0 +1,329 @@
+/* ----------------------------------------------------------------------------- 
+ * gifplot.h
+ *
+ *     Main header file for the GIFPlot library.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ * Copyright (C) 1995-1996
+ *
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <float.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#ifndef GIFPLOT_H
+
+/* Pixel is 8-bits */
+
+typedef unsigned char Pixel;
+typedef float Zvalue;
+
+/* ------------------------------------------------------------------------
+   ColorMap
+
+   Definition and methods for colormaps
+   ------------------------------------------------------------------------ */
+
+typedef struct ColorMap {
+  unsigned char          *cmap;
+  char                   *name;
+} ColorMap;
+
+extern ColorMap *new_ColorMap(char *filename);
+extern void      delete_ColorMap(ColorMap *c);
+extern void      ColorMap_default(ColorMap *c);
+extern void      ColorMap_assign(ColorMap *c, int index, int r, int g, int b);
+extern int       ColorMap_getitem(ColorMap *c, int index);
+extern void      ColorMap_setitem(ColorMap *c, int index, int value);
+extern int       ColorMap_write(ColorMap *c, char *filename);
+
+/* Some default colors */
+
+#define BLACK   0
+#define WHITE   1
+#define RED     2
+#define GREEN   3
+#define BLUE    4
+#define YELLOW  5
+#define CYAN    6
+#define MAGENTA 7
+
+/*-------------------------------------------------------------------------
+  FrameBuffer
+
+  This structure defines a simple 8 bit framebuffer.  
+  ------------------------------------------------------------------------- */
+
+typedef struct FrameBuffer {
+  Pixel         **pixels;
+  Zvalue        **zbuffer;
+  unsigned int    height;
+  unsigned int    width;
+  int             xmin;      /* These are used for clipping */
+  int             ymin;
+  int             xmax;
+  int             ymax;
+} FrameBuffer;
+
+#define ZMIN  1e+36
+
+/* FrameBuffer Methods */
+
+extern FrameBuffer *new_FrameBuffer(unsigned int width, unsigned int height);
+extern void         delete_FrameBuffer(FrameBuffer *frame);
+extern int          FrameBuffer_resize(FrameBuffer *frame, int width, int height);
+extern void         FrameBuffer_clear(FrameBuffer *frame, Pixel color);
+extern void         FrameBuffer_plot(FrameBuffer *frame, int x, int y, Pixel color);
+extern void         FrameBuffer_horizontal(FrameBuffer *frame, int xmin, int xmax, int y, Pixel color);
+extern void         FrameBuffer_horizontalinterp(FrameBuffer *f, int xmin, int xmax, int y,  Pixel c1, Pixel c2);
+extern void         FrameBuffer_vertical(FrameBuffer *frame, int ymin, int ymax, int x, Pixel color);
+extern void         FrameBuffer_box(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+extern void         FrameBuffer_solidbox(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+extern void         FrameBuffer_interpbox(FrameBuffer *f, int x1, int y1, int x2, int y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4);
+extern void         FrameBuffer_circle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+extern void         FrameBuffer_solidcircle(FrameBuffer *frame, int x1, int y1, int radius, Pixel color);
+extern void         FrameBuffer_line(FrameBuffer *frame, int x1, int y1, int x2, int y2, Pixel color);
+extern void         FrameBuffer_setclip(FrameBuffer *frame, int xmin, int ymin, int xmax, int ymax);
+extern void         FrameBuffer_noclip(FrameBuffer *frame);
+extern int          FrameBuffer_makeGIF(FrameBuffer *frame, ColorMap *cmap, void *buffer, unsigned int maxsize);
+extern int          FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename);
+extern void         FrameBuffer_zresize(FrameBuffer *f, int width, int height);
+extern void         FrameBuffer_zclear(FrameBuffer *f);
+extern void         FrameBuffer_solidtriangle(FrameBuffer *f, int x1, int y1, int x2, int y2, int x3, int y3, Pixel c);
+extern void         FrameBuffer_interptriangle(FrameBuffer *f, int tx1, int ty1, Pixel c1,
+                                               int tx2, int ty2, Pixel c2, int tx3, int ty3, Pixel c3);
+
+#define  HORIZONTAL  1
+#define  VERTICAL    2
+
+extern void         FrameBuffer_drawchar(FrameBuffer *frame, int x, int y, int fgcolor, int bgcolor, char chr, int orientation);
+extern void         FrameBuffer_drawstring(FrameBuffer *f, int x, int y, int fgcolor, int bgcolor, char *text, int orientation);
+
+/* ------------------------------------------------------------------------
+   PixMap
+
+   The equivalent of "bit-maps".
+   ------------------------------------------------------------------------ */
+
+typedef struct PixMap {
+  int    width;
+  int    height;
+  int    centerx;
+  int    centery;
+  int   *map;
+} PixMap;
+
+/* PIXMAP methods */
+
+extern PixMap   *new_PixMap(int width, int height, int centerx, int centery);
+extern void      delete_PixMap(PixMap *pm);
+extern void      PixMap_set(PixMap *pm, int x, int y, int pix);
+extern void      FrameBuffer_drawpixmap(FrameBuffer *f, PixMap *pm, int x, int y, int fgcolor, int bgcolor);
+
+#define   TRANSPARENT  0
+#define   FOREGROUND   1
+#define   BACKGROUND   2
+
+/* ------------------------------------------------------------------------
+   Plot2D
+
+   Definition and methods for 2D plots.
+   ------------------------------------------------------------------------ */
+
+typedef struct Plot2D {
+  FrameBuffer    *frame;        /* what frame buffer are we using     */
+  int             view_xmin;    /* Minimum coordinates of view region */
+  int             view_ymin;    
+  int             view_xmax;    /* Maximum coordinates of view region */
+  int             view_ymax;    
+  double          xmin;         /* Minimum coordinates of plot region */
+  double          ymin;
+  double          xmax;         /* Maximum coordinates of plot region */
+  double          ymax;
+  int             xscale;       /* Type of scaling (LINEAR, LOG, etc..) */
+  int             yscale;       
+  double          dx;           /* Private scaling parameters         */
+  double          dy;
+} Plot2D;
+
+/* 2D Plot methods */
+
+extern Plot2D  *new_Plot2D(FrameBuffer *frame,double xmin,double ymin, double xmax, double ymax);
+extern void     delete_Plot2D(Plot2D *p2);
+extern Plot2D  *Plot2D_copy(Plot2D *p2);
+extern void     Plot2D_clear(Plot2D *p2, Pixel c);
+extern void     Plot2D_setview(Plot2D *p2, int vxmin, int vymin, int vxmax, int vymax);
+extern void     Plot2D_setrange(Plot2D *p2, double xmin, double ymin, double xmax, double ymax);
+extern void     Plot2D_setscale(Plot2D *p2, int xscale, int yscale);
+extern void     Plot2D_plot(Plot2D *p2, double x, double y, Pixel color);
+extern void     Plot2D_box(Plot2D *p2, double x1, double y1,  double x2, double y2, Pixel color);
+extern void     Plot2D_solidbox(Plot2D *p2, double x1, double y1,double x2, double y2, Pixel color);
+extern void     Plot2D_interpbox(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel c1, Pixel c2, Pixel c3, Pixel c4);
+extern void     Plot2D_circle(Plot2D *p2, double x, double y, double radius, Pixel color);
+extern void     Plot2D_solidcircle(Plot2D *p2, double x, double y, double radius, Pixel color);
+extern void     Plot2D_line(Plot2D *p2, double x1, double y1, double x2, double y2, Pixel color);
+extern void     Plot2D_start(Plot2D *p2);
+extern void     Plot2D_drawpixmap(Plot2D *p2, PixMap *pm, double x, double y, Pixel color, Pixel bgcolor);
+extern void     Plot2D_xaxis(Plot2D *p2, double x, double y, double xtick, int ticklength, Pixel c);
+extern void     Plot2D_yaxis(Plot2D *p2, double x, double y, double ytick, int ticklength, Pixel c);
+extern void     Plot2D_triangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c);
+extern void     Plot2D_solidtriangle(Plot2D *p2, double x1, double y1, double x2, double y2, double x3, double y3, Pixel c);
+extern void     Plot2D_interptriangle(Plot2D *p2, double x1, double y1, Pixel c1,
+                                                  double x2, double y2, Pixel c2,
+                                                  double x3, double y3, Pixel c3);
+
+#define LINEAR     10
+#define LOG        11
+
+/* -----------------------------------------------------------------------
+   Matrix
+   
+   Operations on 4x4 transformation matrices and vectors.
+   Matrices are represented as a double array of 16 elements
+   ----------------------------------------------------------------------- */
+
+typedef  double *Matrix;
+typedef struct GL_Vector {
+  double x;
+  double y;
+  double z;
+  double w;
+} GL_Vector;
+
+extern Matrix new_Matrix();
+extern void   delete_Matrix(Matrix a);
+extern Matrix Matrix_copy(Matrix a);
+extern void   Matrix_multiply(Matrix a, Matrix b, Matrix c);
+extern void   Matrix_identity(Matrix a);
+extern void   Matrix_zero(Matrix a);
+extern void   Matrix_transpose(Matrix a, Matrix result);
+extern void   Matrix_invert(Matrix a, Matrix inva);
+extern void   Matrix_transform(Matrix a, GL_Vector *r, GL_Vector *t);
+extern void   Matrix_transform4(Matrix a, double rx, double ry, double rz,
+				double rw, GL_Vector *t);
+
+extern void   Matrix_print(Matrix a);
+extern void   Matrix_translate(Matrix a, double tx, double ty, double tz);
+extern void   Matrix_rotatex(Matrix a, double deg);
+extern void   Matrix_rotatey(Matrix a, double deg);
+extern void   Matrix_rotatez(Matrix a, double deg);
+
+/* -----------------------------------------------------------------------
+   Plot3D
+
+   Data Structure for 3-D plots
+   ------------------------------------------------------------------------ */
+
+typedef struct Plot3D {
+  FrameBuffer   *frame;      /* Frame buffer being used */
+  int            view_xmin;  /* Viewing region */
+  int            view_ymin;
+  int            view_xmax;
+  int            view_ymax;
+  double         xmin;       /* Bounding box */
+  double         ymin;
+  double         zmin;
+  double         xmax;
+  double         ymax;
+  double         zmax;
+  double         xcenter;    /* Center point */
+  double         ycenter;
+  double         zcenter;
+  double         fovy;       /* Field of view */
+  double         aspect;     /* Aspect ratio  */
+  double         znear;      /* near "clipping" plane */
+  double         zfar;       /* far "clipping" plane */
+  Matrix         center_mat; /* Matrix used for centering the model */
+  Matrix         model_mat;  /* Model rotation matrix */
+  Matrix         view_mat;   /* Viewing matrix */
+  Matrix         fullmodel_mat;  /* Full model matrix.  Used by sphere plot */
+  Matrix         trans_mat;  /* Total transformation matrix */
+  double         lookatz;    /* Where is the z-lookat point */
+  double         xshift;     /* Used for translation and stuff */
+  double         yshift;
+  double         zoom;
+  int            width;
+  int            height;
+  int            pers_mode;  /* Perspective mode (private) */
+  double         ortho_left,ortho_right,ortho_bottom,ortho_top;
+} Plot3D;
+
+extern Plot3D *new_Plot3D(FrameBuffer *frame, double xmin, double ymin, double zmin,
+			  double xmax, double ymax, double zmax);
+extern void   delete_Plot3D(Plot3D *p3);
+extern Plot3D *Plot3D_copy(Plot3D *p3);
+extern void   Plot3D_clear(Plot3D *p3, Pixel Color);
+extern void   Plot3D_perspective(Plot3D *p3, double fovy, double znear, double zfar);
+extern void   Plot3D_ortho(Plot3D *p3, double left, double right, double top, double bottom);
+extern void   Plot3D_lookat(Plot3D *p3, double z);
+extern void   Plot3D_autoperspective(Plot3D *p3, double fovy);
+extern void   Plot3D_autoortho(Plot3D *p3);
+extern void   Plot3D_rotx(Plot3D *p3, double deg);
+extern void   Plot3D_roty(Plot3D *p3, double deg);
+extern void   Plot3D_rotz(Plot3D *p3, double deg);
+extern void   Plot3D_rotl(Plot3D *p3, double deg);
+extern void   Plot3D_rotr(Plot3D *p3, double deg);
+extern void   Plot3D_rotd(Plot3D *p3, double deg);
+extern void   Plot3D_rotu(Plot3D *p3, double deg);
+extern void   Plot3D_rotc(Plot3D *p3, double deg);
+extern void   Plot3D_zoom(Plot3D *p3, double percent);
+extern void   Plot3D_left(Plot3D *p3, double percent);
+extern void   Plot3D_right(Plot3D *p3, double percent);
+extern void   Plot3D_down(Plot3D *p3, double percent);
+extern void   Plot3D_up(Plot3D *p3, double percent);
+extern void   Plot3D_center(Plot3D *p3, double cx, double cy);
+
+extern void   Plot3D_plot(Plot3D *p3, double x, double y, double z, Pixel Color);
+
+extern void   Plot3D_setview(Plot3D *p3, int vxmin, int vymin, int vxmax, int vymax);
+extern void   Plot3D_start(Plot3D *p3);
+extern void   Plot3D_line(Plot3D *p3, double x1, double y1, double z1,
+			 double x2, double y2, double z2, Pixel color);
+extern void   Plot3D_triangle(Plot3D *p3, double x1, double y1, double z1,
+		     double x2, double y2, double z2,
+		     double x3, double y3, double z3, Pixel color);
+extern void   Plot3D_solidtriangle(Plot3D *p3, double x1, double y1, double z1,
+		     double x2, double y2, double z2,
+		     double x3, double y3, double z3, Pixel color);
+
+extern void Plot3D_interptriangle(Plot3D *p3,
+			   double x1, double y1, double z1, Pixel c1,
+			   double x2, double y2, double z2, Pixel c2,
+			   double x3, double y3, double z3, Pixel c3);
+
+extern void   Plot3D_quad(Plot3D *p3, double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color);
+
+extern void   Plot3D_solidquad(Plot3D *p3, double x1, double y1, double z1,
+		 double x2, double y2, double z2,
+		 double x3, double y3, double z3,
+		 double x4, double y4, double z4,
+		 Pixel color);
+
+extern void   Plot3D_interpquad(Plot3D *p3, double x1, double y1, double z1, Pixel c1,
+		       double x2, double y2, double z2, Pixel c2,
+		       double x3, double y3, double z3, Pixel c3,
+		       double x4, double y4, double z4, Pixel c4);
+
+
+extern void   Plot3D_solidsphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c);
+
+extern void   Plot3D_outlinesphere(Plot3D *p3, double x, double y, double z, double radius,Pixel c, Pixel bc);
+
+extern PixMap  PixMap_SQUARE;
+extern PixMap  PixMap_TRIANGLE;
+extern PixMap  PixMap_CROSS;
+
+#endif
+#define GIFPLOT_H
+
+
+
diff --git a/trunk/Examples/xml/example_inl.expected-xml b/trunk/Examples/xml/example_inl.expected-xml
new file mode 100644
index 0000000..6f83cfd
--- /dev/null
+++ b/trunk/Examples/xml/example_inl.expected-xml
@@ -0,0 +1,104 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_inl.i" >
+        <swigxml:child >
+          <swig:module name="example"  />
+          <swig:insert >
+            <swigxml:code >
+
+#include "example.h"
+            </swigxml:code>
+          </swig:insert>
+          <c:function name="dot_product" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Vector"  />
+              </swigxml:parm>
+              <swigxml:parm name="b" >
+                <swigxml:type string="Vector"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="double"  />
+          </c:function>
+          <c:function name="vector_add" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="Vector"  />
+              </swigxml:parm>
+              <swigxml:parm name="b" >
+                <swigxml:type string="Vector"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="Vector"  />
+          </c:function>
+          <c:function name="free" >
+            <swigxml:parms >
+              <swigxml:parm >
+                <swigxml:type string="p.void"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:insert >
+            <swigxml:code >
+
+
+Vector *new_Vector(double x, double y, double z) {
+   Vector *v = (Vector *) malloc(sizeof(Vector));
+   v->x = x;
+   v->y = y;
+   v->z = z;
+   return v;
+}
+
+void vector_print(Vector *v) {
+  printf("Vector %x = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}
+            </swigxml:code>
+          </swig:insert>
+          <c:function name="new_Vector" >
+            <swigxml:parms >
+              <swigxml:parm name="x" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+              <swigxml:parm name="z" >
+                <swigxml:type string="double"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:code >
+{
+   Vector *v = (Vector *) malloc(sizeof(Vector));
+   v->x = x;
+   v->y = y;
+   v->z = z;
+   return v;
+}            </swigxml:code>
+            <swigxml:type string="p.Vector"  />
+          </c:function>
+          <c:function name="vector_print" >
+            <swigxml:parms >
+              <swigxml:parm name="v" >
+                <swigxml:type string="p.Vector"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:code >
+{
+  printf("Vector %x = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}            </swigxml:code>
+            <swigxml:type string="void"  />
+          </c:function>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_inl.h b/trunk/Examples/xml/example_inl.h
new file mode 100644
index 0000000..212cf4b
--- /dev/null
+++ b/trunk/Examples/xml/example_inl.h
@@ -0,0 +1,5 @@
+/* File : example.h */
+
+typedef struct {
+     double x, y, z;
+} Vector;
diff --git a/trunk/Examples/xml/example_inl.i b/trunk/Examples/xml/example_inl.i
new file mode 100644
index 0000000..39e4905
--- /dev/null
+++ b/trunk/Examples/xml/example_inl.i
@@ -0,0 +1,30 @@
+// Tests SWIG's handling of pass-by-value for complex datatypes
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Some functions that manipulate Vectors by value */
+extern double dot_product(Vector a, Vector b);
+extern Vector vector_add(Vector a, Vector b);
+
+/* Include this because the vector_add() function will leak memory */
+void   free(void *);
+
+/* Some helper functions for our interface */
+%inline %{
+
+Vector *new_Vector(double x, double y, double z) {
+   Vector *v = (Vector *) malloc(sizeof(Vector));
+   v->x = x;
+   v->y = y;
+   v->z = z;
+   return v;
+}
+
+void vector_print(Vector *v) {
+  printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z);
+}
+%}
+
diff --git a/trunk/Examples/xml/example_p5.expected-xml b/trunk/Examples/xml/example_p5.expected-xml
new file mode 100644
index 0000000..15dc205
--- /dev/null
+++ b/trunk/Examples/xml/example_p5.expected-xml
@@ -0,0 +1,24 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_p5.i" >
+        <swigxml:child >
+          <swig:module name="example"  />
+          <swig:insert >
+            <swigxml:code >
+
+#include "example.h"
+            </swigxml:code>
+          </swig:insert>
+          <swig:file name="example.h" >
+            <swigxml:type string="include"  />
+          </swig:file>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_p5.i b/trunk/Examples/xml/example_p5.i
new file mode 100644
index 0000000..23ee8a8
--- /dev/null
+++ b/trunk/Examples/xml/example_p5.i
@@ -0,0 +1,11 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+
+%include "example.h"
+
diff --git a/trunk/Examples/xml/example_ro.expected-xml b/trunk/Examples/xml/example_ro.expected-xml
new file mode 100644
index 0000000..d4a0661
--- /dev/null
+++ b/trunk/Examples/xml/example_ro.expected-xml
@@ -0,0 +1,23 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_ro.i" >
+        <swigxml:child >
+          <swig:pragma name="readonly"  />
+          <c:variable name="status" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="int"  />
+          </c:variable>
+          <c:variable name="path" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="a(256).char"  />
+          </c:variable>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_ro.i b/trunk/Examples/xml/example_ro.i
new file mode 100644
index 0000000..23bd1a8
--- /dev/null
+++ b/trunk/Examples/xml/example_ro.i
@@ -0,0 +1,6 @@
+/* File : example.i */
+%readonly 
+extern int  status;
+extern char path[256];
+
+
diff --git a/trunk/Examples/xml/example_title_add.expected-xml b/trunk/Examples/xml/example_title_add.expected-xml
new file mode 100644
index 0000000..5aed729
--- /dev/null
+++ b/trunk/Examples/xml/example_title_add.expected-xml
@@ -0,0 +1,119 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_title_add.i" >
+        <swigxml:child >
+          <swig:module name="example"  />
+          <swig:insert >
+            <swigxml:code >
+
+#include "example.h"
+            </swigxml:code>
+          </swig:insert>
+          <c:class name="Vector" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:function name="Vector" >
+                <swigxml:parms >
+                  <swigxml:parm name="x" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="y" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="z" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:destructor name="Vector"  />
+              <c:function name="print" >
+                <swigxml:type string="p.char"  />
+              </c:function>
+            </swigxml:child>
+            <swigxml:classtype string="class"  />
+            <swigxml:namespace string="Vector"  />
+          </c:class>
+          <swig:insert >
+            <swigxml:code >
+
+Vector addv(Vector &amp;a, Vector &amp;b) {
+  return a+b;
+}
+            </swigxml:code>
+          </swig:insert>
+          <c:function name="addv" >
+            <swigxml:parms >
+              <swigxml:parm name="a" >
+                <swigxml:type string="r.Vector"  />
+              </swigxml:parm>
+              <swigxml:parm name="b" >
+                <swigxml:type string="r.Vector"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:code >
+{
+  return a+b;
+}            </swigxml:code>
+            <swigxml:type string="Vector"  />
+          </c:function>
+          <c:class name="VectorArray" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:function name="VectorArray" >
+                <swigxml:parms >
+                  <swigxml:parm name="maxsize" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:destructor name="VectorArray"  />
+              <c:function name="size" >
+                <swigxml:type string="int"  />
+              </c:function>
+              <swig:addmethods >
+                <swigxml:child >
+                  <c:function name="get" >
+                    <swigxml:parms >
+                      <swigxml:parm name="index" >
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:code >
+{
+      return (*self)[index];
+    }                    </swigxml:code>
+                    <swigxml:type string="r.Vector"  />
+                  </c:function>
+                  <c:function name="set" >
+                    <swigxml:parms >
+                      <swigxml:parm name="index" >
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="a" >
+                        <swigxml:type string="r.Vector"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:code >
+{
+      (*self)[index] = a;
+    }                    </swigxml:code>
+                    <swigxml:type string="void"  />
+                  </c:function>
+                </swigxml:child>
+              </swig:addmethods>
+            </swigxml:child>
+            <swigxml:classtype string="class"  />
+            <swigxml:namespace string="VectorArray"  />
+          </c:class>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_title_add.i b/trunk/Examples/xml/example_title_add.i
new file mode 100644
index 0000000..3320919
--- /dev/null
+++ b/trunk/Examples/xml/example_title_add.i
@@ -0,0 +1,47 @@
+/* File : example.i */
+%title "Matrix and vector package"
+
+/* This file has a few "typical" uses of C++ references. */
+
+%module example
+
+%{
+#include "example.h"
+%}
+
+class Vector {
+public:
+    Vector(double x, double y, double z);
+   ~Vector();
+    char *print();
+};
+
+/* This helper function calls an overloaded operator */
+%inline %{
+Vector addv(Vector &a, Vector &b) {
+  return a+b;
+}
+%}
+
+/* Wrapper around an array of vectors class */
+
+class VectorArray {
+public:
+  VectorArray(int maxsize);
+  ~VectorArray();
+  int size();
+  
+  /* This wrapper provides an alternative to the [] operator */
+  %addmethods {
+    Vector &get(int index) {
+      return (*self)[index];
+    }
+    void set(int index, Vector &a) {
+      (*self)[index] = a;
+    }
+  }
+};
+
+
+
+
diff --git a/trunk/Examples/xml/example_xml.expected-xml b/trunk/Examples/xml/example_xml.expected-xml
new file mode 100644
index 0000000..584e468
--- /dev/null
+++ b/trunk/Examples/xml/example_xml.expected-xml
@@ -0,0 +1,1624 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="example_xml.i" >
+        <swigxml:child >
+          <swig:module name="my_example"  />
+          <c:enum name="color" >
+            <swigxml:child >
+              <c:enumvalue name="RED" >
+                <swigxml:value string="RED"  />
+              </c:enumvalue>
+              <c:enumvalue name="BLUE"  />
+              <c:enumvalue name="GREEN"  />
+            </swigxml:child>
+          </c:enum>
+          <c:class name="Foo" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:function name="Foo" >
+                <swigxml:code >
+{ }                </swigxml:code>
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:enum name="speed" >
+                <swigxml:child >
+                  <c:enumvalue name="IMPULSE"  />
+                  <c:enumvalue name="WARP"  />
+                  <c:enumvalue name="LUDICROUS"  />
+                </swigxml:child>
+              </c:enum>
+              <c:function name="enum_test" >
+                <swigxml:parms >
+                  <swigxml:parm name="s" >
+                    <swigxml:type string="speed"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:type string="void"  />
+              </c:function>
+            </swigxml:child>
+            <swigxml:classtype string="class"  />
+            <swigxml:namespace string="Foo"  />
+          </c:class>
+          <c:function name="enum_test" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="color"  />
+              </swigxml:parm>
+              <swigxml:parm name="s" >
+                <swigxml:type string="Foo::speed"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:file name="../../Lib/pointer.i" >
+            <swigxml:child >
+              <swig:module name="pointer"  />
+              <swig:insert >
+                <swigxml:code >
+
+%include pointer.i
+
+The pointer.i library provides run-time support for managing and 
+manipulating a variety of C/C++ pointer values.  In particular,
+you can create various kinds of objects and dereference common
+pointer types.  This is done through a common set of functions:
+
+    ptrvalue     - Dereferences a pointer 
+    ptrset       - Set the value of an object referenced by 
+                   a pointer.
+    ptrcreate    - Create a new object and return a pointer.
+    ptrfree      - Free the memory allocated by ptrcreate.
+    ptradd       - Increment/decrement a pointer value.
+
+When creating, dereferencing, or setting the value of pointer
+variable, only the common C datatypes of int, short, long, float,
+double, char, and char * are currently supported.   Other
+datatypes may generate an error.
+
+One of the more interesting aspects of this library is that
+it operates with a wide range of datatypes.  For example,
+the "ptrvalue" function can dereference "double *", "int *",
+"long *", "char *", and other datatypes. Since SWIG encodes
+pointers with type information, this can be done transparently
+and in most cases, you can dereference a pointer without
+ever knowing what type it actually is.
+
+This library is primarily designed for utility, not high 
+performance (the dynamic determination of pointer types takes
+more work than most normal wrapper functions).  As a result,
+you may achieve better performance by writing customized
+"helper" functions if you're making lots of calls to these
+functions in inner loops or other intensive operations.
+                </swigxml:code>
+                <swigxml:section string="doc"  />
+              </swig:insert>
+              <swig:types >
+                <swigxml:parms >
+                  <swigxml:parm >
+                    <swigxml:type string="p.int"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.short"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.long"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.float"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.double"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.char"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.p.char"  />
+                  </swigxml:parm>
+                  <swigxml:parm >
+                    <swigxml:type string="p.void"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+              </swig:types>
+              <swig:file name="../../Lib/xml/ptrlang.i" >
+                <swigxml:child >
+                  <swig:insert >
+                    <swigxml:code >
+
+#include &amp;lt;ctype.h>
+
+/* Types used by the library */
+static swig_type_info *SWIG_POINTER_int_p = 0;
+static swig_type_info *SWIG_POINTER_short_p =0;
+static swig_type_info *SWIG_POINTER_long_p = 0;
+static swig_type_info *SWIG_POINTER_float_p = 0;
+static swig_type_info *SWIG_POINTER_double_p = 0;
+static swig_type_info *SWIG_POINTER_char_p = 0;
+static swig_type_info *SWIG_POINTER_char_pp = 0;
+static swig_type_info *SWIG_POINTER_void_p = 0;
+                    </swigxml:code>
+                  </swig:insert>
+                  <swig:insert >
+                    <swigxml:code >
+
+  SWIG_POINTER_int_p = SWIG_TypeQuery("int *");
+  SWIG_POINTER_short_p = SWIG_TypeQuery("short *");
+  SWIG_POINTER_long_p = SWIG_TypeQuery("long *");
+  SWIG_POINTER_float_p = SWIG_TypeQuery("float *");
+  SWIG_POINTER_double_p = SWIG_TypeQuery("double *");
+  SWIG_POINTER_char_p = SWIG_TypeQuery("char *");
+  SWIG_POINTER_char_pp = SWIG_TypeQuery("char **");
+  SWIG_POINTER_void_p = SWIG_TypeQuery("void *");
+                    </swigxml:code>
+                    <swigxml:section string="init"  />
+                  </swig:insert>
+                  <swig:insert >
+                    <swigxml:code >
+
+
+/* #ifdef WIN32
+#undef isspace
+#define isspace(c) (c == ' ')
+#endif
+*/
+
+/*------------------------------------------------------------------
+  ptrvalue(ptr,type = 0)
+
+  Attempts to dereference a pointer value.  If type is given, it
+  will try to use that type.  Otherwise, this function will attempt
+  to "guess" the proper datatype by checking against all of the
+  builtin C datatypes.
+  ------------------------------------------------------------------ */
+
+#ifdef PERL_OBJECT
+static SV *_ptrvalue(CPerlObj *pPerl,SV *_PTRVALUE, int index, char *type) {
+#define ptrvalue(a,b,c) _ptrvalue(pPerl,a,b,c)
+#else
+static SV *_ptrvalue(SV *_PTRVALUE, int index, char *type) {
+#define ptrvalue(a,b,c) _ptrvalue(a,b,c)
+#endif
+
+  void     *ptr;
+  SV       *obj = 0;
+
+  if (SWIG_ConvertPtr(_PTRVALUE, &amp;ptr, 0) &amp;lt; 0) {
+    croak("Type error it ptrvalue. Argument is not a valid pointer value.");
+  } else {
+    /* If no datatype was passed, try a few common datatypes first */
+    if (!type) {
+
+      /* No datatype was passed.   Type to figure out if it's a common one */
+
+      if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_int_p) >= 0) {
+	type = "int";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_double_p) >= 0) {
+	type = "double";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_short_p) >= 0) {
+	type = "short";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_long_p) >= 0) {
+	type = "long";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_float_p) >= 0) {
+	type = "float";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_p) >= 0) {
+	type = "char";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_pp) >= 0) {
+	type = "char *";
+      } else {
+	type = "unknown";
+      }
+    }
+
+    if (!ptr) {
+      croak("Unable to dereference NULL pointer.");
+      return 0;
+    }
+
+    /* Now we have a datatype.  Try to figure out what to do about it */
+    if (strcmp(type,"int") == 0) {
+      obj = sv_newmortal();
+      sv_setiv(obj,(IV) *(((int *) ptr) + index));
+    } else if (strcmp(type,"double") == 0) {
+      obj = sv_newmortal();
+      sv_setnv(obj,(double) *(((double *) ptr)+index));
+    } else if (strcmp(type,"short") == 0) {
+      obj = sv_newmortal();
+      sv_setiv(obj,(IV) *(((short *) ptr) + index));
+    } else if (strcmp(type,"long") == 0) {
+      obj = sv_newmortal();
+      sv_setiv(obj,(IV) *(((long *) ptr) + index));
+    } else if (strcmp(type,"float") == 0) {
+      obj = sv_newmortal();
+      sv_setnv(obj,(double) *(((float *) ptr)+index));
+    } else if (strcmp(type,"char") == 0) {
+      obj = sv_newmortal();
+      sv_setpv(obj,((char *) ptr)+index);
+    } else if (strcmp(type,"char *") == 0) {
+      char *c = *(((char **) ptr)+index);
+      obj = sv_newmortal();
+      if (c)
+	sv_setpv(obj,c);
+      else
+	sv_setpv(obj,"NULL");
+    } else {
+      croak("Unable to dereference unsupported datatype.");
+      obj = 0;
+    }
+  }
+  return obj;
+}
+
+/*------------------------------------------------------------------
+  ptrcreate(type,value = 0,numelements = 1)
+
+  Attempts to create a new object of given type.  Type must be
+  a basic C datatype.  Will not create complex objects.
+  ------------------------------------------------------------------ */
+#ifdef PERL_OBJECT
+static SV *_ptrcreate(CPerlObj *pPerl, char *type, SV *value, int numelements) {
+#define ptrcreate(a,b,c) _ptrcreate(pPerl,a,b,c)
+#else
+static SV *_ptrcreate(char *type, SV *value, int numelements) {
+#define ptrcreate(a,b,c) _ptrcreate(a,b,c)
+#endif
+
+  void     *ptr;
+  SV       *obj;
+  int       sz;
+  swig_type_info *cast = 0;
+
+  /* Check the type string against a variety of possibilities */
+
+  if (strcmp(type,"int") == 0) {
+    sz = sizeof(int)*numelements;
+    cast = SWIG_POINTER_int_p;
+  } else if (strcmp(type,"short") == 0) {
+    sz = sizeof(short)*numelements;
+    cast = SWIG_POINTER_short_p;
+  } else if (strcmp(type,"long") == 0) {
+    sz = sizeof(long)*numelements;
+    cast = SWIG_POINTER_long_p;
+  } else if (strcmp(type,"double") == 0) {
+    sz = sizeof(double)*numelements;
+    cast = SWIG_POINTER_double_p;
+  } else if (strcmp(type,"float") == 0) {
+    sz = sizeof(float)*numelements;
+    cast = SWIG_POINTER_float_p;
+  } else if (strcmp(type,"char") == 0) {
+    sz = sizeof(char)*numelements;
+    cast = SWIG_POINTER_char_p;
+  } else if (strcmp(type,"char *") == 0) {
+    sz = sizeof(char *)*(numelements+1);
+    cast = SWIG_POINTER_char_pp;
+  } else if (strcmp(type,"void") == 0) {
+    sz = numelements;
+    cast = SWIG_POINTER_void_p;
+  } else {
+    croak("Unable to create unknown datatype.");
+    return 0;
+  }
+
+  /* Create the new object */
+
+  ptr = (void *) malloc(sz);
+  if (!ptr) {
+    croak("Out of memory in ptrcreate.");
+    return 0;
+  }
+
+  /* Now try to set its default value */
+
+  if (value) {
+    if (strcmp(type,"int") == 0) {
+      int *ip,i,ivalue;
+      ivalue = (int) SvIV(value);
+      ip = (int *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"short") == 0) {
+      short *ip,ivalue;
+      int i;
+      ivalue = (short) SvIV(value);
+      ip = (short *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"long") == 0) {
+      long *ip,ivalue;
+      int i;
+      ivalue = (long) SvIV(value);
+      ip = (long *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"double") == 0) {
+      double *ip,ivalue;
+      int i;
+      ivalue = (double) SvNV(value);
+      ip = (double *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"float") == 0) {
+      float *ip,ivalue;
+      int i;
+      ivalue = (float) SvNV(value);
+      ip = (float *) ptr;
+      for (i = 0; i &amp;lt; numelements; i++)
+	ip[i] = ivalue;
+    } else if (strcmp(type,"char") == 0) {
+      char *ip,*ivalue;
+      ivalue = (char *) SvPV(value,PL_na);
+      ip = (char *) ptr;
+      strncpy(ip,ivalue,numelements-1);
+    } else if (strcmp(type,"char *") == 0) {
+      char **ip, *ivalue;
+      int  i;
+      ivalue = (char *) SvPV(value,PL_na);
+      ip = (char **) ptr;
+      for (i = 0; i &amp;lt; numelements; i++) {
+	if (ivalue) {
+	  ip[i] = (char *) malloc(strlen(ivalue)+1);
+	  strcpy(ip[i],ivalue);
+	} else {
+	  ip[i] = 0;
+	}
+      }
+      ip[numelements] = 0;
+    }
+  }
+  /* Create the pointer value */
+
+
+  obj = sv_newmortal();
+  SWIG_MakePtr(obj,ptr,cast);
+  return obj;
+}
+
+/*------------------------------------------------------------------
+  ptrset(ptr,value,index = 0,type = 0)
+
+  Attempts to set the value of a pointer variable.  If type is
+  given, we will use that type.  Otherwise, we'll guess the datatype.
+  ------------------------------------------------------------------ */
+
+#ifdef PERL_OBJECT
+static void _ptrset(CPerlObj *pPerl,SV *_PTRVALUE, SV *value, int index, char *type) {
+#define ptrset(a,b,c,d) _ptrset(pPerl,a,b,c,d)
+#else
+static void _ptrset(SV *_PTRVALUE, SV *value, int index, char *type) {
+#define ptrset(a,b,c,d) _ptrset(a,b,c,d)
+#endif
+  void     *ptr;
+  SV       *obj;
+
+
+  if (SWIG_ConvertPtr(_PTRVALUE, &amp;ptr, 0) &amp;lt; 0) {
+    croak("Type error it ptrvalue. Argument is not a valid pointer value.");
+  } else {
+    /* If no datatype was passed, try a few common datatypes first */
+    if (!type) {
+      /* No datatype was passed.   Type to figure out if it's a common one */
+      if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_int_p) >= 0) {
+	type = "int";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_double_p) >= 0) {
+	type = "double";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_short_p) >= 0) {
+	type = "short";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_long_p) >= 0) {
+	type = "long";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_float_p) >= 0) {
+	type = "float";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_p) >= 0) {
+	type = "char";
+      } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_pp) >= 0) {
+	type = "char *";
+      } else {
+	type = "unknown";
+      }
+    }
+  }
+  if (!ptr) {
+    croak("Unable to set NULL pointer.");
+    return;
+  }
+
+  /* Now we have a datatype.  Try to figure out what to do about it */
+  if (strcmp(type,"int") == 0) {
+    *(((int *) ptr)+index) = (int) SvIV(value);
+  } else if (strcmp(type,"double") == 0) {
+    *(((double *) ptr)+index) = (double) SvNV(value);
+  } else if (strcmp(type,"short") == 0) {
+    *(((short *) ptr)+index) = (short) SvIV(value);
+  } else if (strcmp(type,"long") == 0) {
+    *(((long *) ptr)+index) = (long) SvIV(value);
+  } else if (strcmp(type,"float") == 0) {
+    *(((float *) ptr)+index) = (float) SvNV(value);
+  } else if (strcmp(type,"char") == 0) {
+    char *c = SvPV(value,PL_na);
+    strcpy(((char *) ptr)+index, c);
+  } else if (strcmp(type,"char *") == 0) {
+    char *c = SvPV(value,PL_na);
+    char **ca = (char **) ptr;
+    if (ca[index]) free(ca[index]);
+    if (strcmp(c,"NULL") == 0) {
+      ca[index] = 0;
+    } else {
+      ca[index] = (char *) malloc(strlen(c)+1);
+      strcpy(ca[index],c);
+    }
+  } else {
+    croak("Unable to set unsupported datatype.");
+    return;
+  }
+}
+
+/*------------------------------------------------------------------
+  ptradd(ptr,offset)
+
+  Adds a value to an existing pointer value.  Will do a type-dependent
+  add for basic datatypes.  For other datatypes, will do a byte-add.
+  ------------------------------------------------------------------ */
+
+#ifdef PERL_OBJECT
+static SV *_ptradd(CPerlObj *pPerl, SV *_PTRVALUE, int offset) {
+#define ptradd(a,b) _ptradd(pPerl,a,b)
+#else
+static SV *_ptradd(SV *_PTRVALUE, int offset) {
+#define ptradd(a,b) _ptradd(a,b)
+#endif
+
+  void *ptr,*junk;
+  SV   *obj;
+  swig_type_info *type;
+  char *tname;
+
+  /* Try to handle a few common datatypes first */
+
+  if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_int_p) >= 0) {
+    ptr = (void *) (((int *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_double_p) >= 0) {
+    ptr = (void *) (((double *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_short_p) >= 0) {
+    ptr = (void *) (((short *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_long_p) >= 0) {
+    ptr = (void *) (((long *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_float_p) >= 0) {
+    ptr = (void *) (((float *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,SWIG_POINTER_char_p) >= 0) {
+    ptr = (void *) (((char *) ptr) + offset);
+  } else if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,0) >= 0) {
+    ptr = (void *) (((char *) ptr) + offset);
+  } else {
+    croak("Type error in ptradd. Argument is not a valid pointer value.");
+    return 0;
+  }
+  printf("ptradd = %x\n", ptr);
+  tname = HvNAME(SvSTASH(SvRV(_PTRVALUE)));
+  obj = sv_newmortal();
+  sv_setref_pv(obj,tname,ptr);
+  return obj;
+}
+
+/*------------------------------------------------------------------
+  ptrfree(ptr)
+
+  Destroys a pointer value
+  ------------------------------------------------------------------ */
+#ifdef PERL_OBJECT
+void _ptrfree(CPerlObj *pPerl, SV *_PTRVALUE) {
+#define ptrfree(a) _ptrfree(pPerl, a)
+#else
+void _ptrfree(SV *_PTRVALUE) {
+#define ptrfree(a) _ptrfree(a)
+#endif
+
+  void *ptr, *junk;
+
+  if (SWIG_ConvertPtr(_PTRVALUE,&amp;ptr,0) &amp;lt; 0) {
+    croak("Type error in ptrfree. Argument is not a valid pointer value.");
+    return;
+  }
+
+  /* Check to see if this pointer is a char ** */
+  if (SWIG_ConvertPtr(_PTRVALUE,&amp;junk,SWIG_POINTER_char_pp) >= 0) {
+    char **c = (char **) ptr;
+    if (c) {
+      int i = 0;
+      while (c[i]) {
+	free(c[i]);
+	i++;
+      }
+    }
+  }
+  if (ptr)
+    free((char *) ptr);
+}
+
+                    </swigxml:code>
+                  </swig:insert>
+                  <swig:typemap name="ptr" >
+                    <swigxml:code >
+{
+  $target = $source;
+}                    </swigxml:code>
+                    <swigxml:method string="in"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="value" >
+                    <swigxml:code >
+{
+  $target = $source;
+}                    </swigxml:code>
+                    <swigxml:method string="in"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrcast" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrvalue" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrcreate" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptradd" >
+                    <swigxml:code >
+{
+  $target = $source;
+  argvi++;
+}                    </swigxml:code>
+                    <swigxml:method string="out"  />
+                    <swigxml:type string="p.SV"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <swig:typemap name="ptrset" >
+                    <swigxml:code >
+{
+  if ($source == -1) return NULL;
+}                    </swigxml:code>
+                    <swigxml:method string="ret"  />
+                    <swigxml:type string="int"  />
+                    <swigxml:lang string="perl5"  />
+                  </swig:typemap>
+                  <c:function name="ptrvalue" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="index" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="type" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="p.char"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="p.SV"  />
+                  </c:function>
+                  <c:function name="ptrset" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="value" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="index" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="type" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="p.char"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="void"  />
+                  </c:function>
+                  <c:function name="ptrcreate" >
+                    <swigxml:parms >
+                      <swigxml:parm name="type" >
+                        <swigxml:type string="p.char"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="value" >
+                        <swigxml:value string="0"  />
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="nitems" >
+                        <swigxml:value string="1"  />
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="p.SV"  />
+                  </c:function>
+                  <c:function name="ptrfree" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="void"  />
+                  </c:function>
+                  <c:function name="ptradd" >
+                    <swigxml:parms >
+                      <swigxml:parm name="ptr" >
+                        <swigxml:type string="p.SV"  />
+                      </swigxml:parm>
+                      <swigxml:parm name="offset" >
+                        <swigxml:type string="int"  />
+                      </swigxml:parm>
+                    </swigxml:parms>
+                    <swigxml:type string="p.SV"  />
+                  </c:function>
+                </swigxml:child>
+                <swigxml:type string="include"  />
+              </swig:file>
+            </swigxml:child>
+            <swigxml:type string="include"  />
+          </swig:file>
+          <swig:file name="../../Lib/xml/typemaps.i" >
+            <swigxml:child >
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (double) SvNV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="float"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (float) SvNV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (int) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (short) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (long) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned int) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned short) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned long) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="INPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned char"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  temp = (unsigned char) SvIV($source);
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="unsigned char"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="float"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:parms >
+                  <swigxml:parm name="temp" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  $target = &amp;amp;amp;amp;amp;amp;amp;amp;amp;temp;
+}                </swigxml:code>
+                <swigxml:method string="ignore"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setiv($target,(IV) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setnv($target,(double) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="OUTPUT" >
+                <swigxml:code >
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $target = sv_newmortal();
+  sv_setnv($target,(double) *($source));
+  argvi++;
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.int"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.short"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.long"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned short"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned long"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned char"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.float"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.double"  />
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="INPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.int"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.short"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.long"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned short"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned long"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.unsigned char"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned char"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.float"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="BOTH" >
+                <swigxml:srctype string="p.double"  />
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+                <swigxml:srcname string="OUTPUT"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="double"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
+	printf("Received %d\n", SvTYPE(tempsv));
+	croak("Expected a double reference.");
+  }
+  dvalue = SvNV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="float"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
+    croak("expected a double reference");
+  }
+  dvalue = (float) SvNV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (short) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (long) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="unsigned int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (unsigned int) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="unsigned short"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (unsigned short) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:parms >
+                  <swigxml:parm name="dvalue" >
+                    <swigxml:type string="unsigned long"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:code >
+{
+  SV *tempsv;
+  if (!SvROK($source)) {
+    croak("expected a reference");
+  }
+  tempsv = SvRV($source);
+  if (!SvIOK(tempsv)) {
+    croak("expected a integer reference");
+  }
+  dvalue = (unsigned long) SvIV(tempsv);
+  $target = &amp;dvalue;
+}                </swigxml:code>
+                <swigxml:method string="in"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setnv(tempsv, (double) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.double"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setnv(tempsv, (double) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.float"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned int"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned short"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+              <swig:typemap name="REFERENCE" >
+                <swigxml:code >
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  sv_setiv(tempsv, (int) *$source);
+}                </swigxml:code>
+                <swigxml:method string="argout"  />
+                <swigxml:type string="p.unsigned long"  />
+                <swigxml:lang string="perl5"  />
+              </swig:typemap>
+            </swigxml:child>
+            <swigxml:type string="include"  />
+          </swig:file>
+          <swig:typemap >
+            <swigxml:code >
+{
+    WHATEVER  MAKES YOU HAPPY AS RESULT
+}            </swigxml:code>
+            <swigxml:method string="out"  />
+            <swigxml:type string="p.int"  />
+          </swig:typemap>
+          <swig:typemap >
+            <swigxml:code >
+{
+    WHATEVER  MAKES YOU HAPPY AS PARAMETER
+}            </swigxml:code>
+            <swigxml:method string="in"  />
+            <swigxml:type string="p.int"  />
+          </swig:typemap>
+          <swig:pragma name="DEBUG" >
+            <swigxml:value string="false"  />
+            <swigxml:lang string="xml"  />
+          </swig:pragma>
+          <c:function name="my_gcd" >
+            <swigxml:parms >
+              <swigxml:parm name="x" >
+                <swigxml:type string="p.q(const).char"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="a().p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="r" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="op" >
+                <swigxml:type string="p.f(int,int).int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.int"  />
+          </c:function>
+          <c:variable name="my_foo" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="double"  />
+          </c:variable>
+          <c:function name="my_void" >
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="my_empty" >
+            <swigxml:type string="int"  />
+          </c:function>
+          <c:variable name="my_dutch" >
+            <swigxml:value string="1.0"  />
+            <swigxml:type string="q(const).double"  />
+          </c:variable>
+          <c:class name="my_union" >
+            <swigxml:child >
+              <c:variable name="my_iii" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="my_ccc" >
+                <swigxml:type string="char"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="union"  />
+            <swigxml:namespace string="my_union"  />
+          </c:class>
+          <c:class name="my_struct" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:destructor name="my_struct" >
+                <swigxml:storage string="virtual"  />
+              </c:destructor>
+              <c:function name="my_foo" >
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:access name="protected"  />
+              <c:variable name="my_bar" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="x" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="y" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:function name="area" >
+                <swigxml:abstract string="1"  />
+                <swigxml:storage string="virtual"  />
+                <swigxml:type string="double"  />
+              </c:function>
+              <c:variable name="nshapes" >
+                <swigxml:storage string="static"  />
+                <swigxml:type string="int"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="my_struct"  />
+          </c:class>
+          <c:class name="my_class" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:function name="my_class" >
+                <swigxml:parms >
+                  <swigxml:parm name="c" >
+                    <swigxml:type string="char"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:access name="private"  />
+              <c:destructor name="my_class"  />
+              <c:function name="my_func" >
+                <swigxml:parms >
+                  <swigxml:parm >
+                    <swigxml:type string="my_class"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="x" >
+                    <swigxml:type string="p.p.char"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="y" >
+                    <swigxml:type string="a().int"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="r" >
+                    <swigxml:type string="r.q(const).int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:storage string="virtual"  />
+                <swigxml:type string="p.q(const).int"  />
+              </c:function>
+              <c:variable name="my_foo" >
+                <swigxml:type string="a(128).double"  />
+              </c:variable>
+              <c:variable name="i" >
+                <swigxml:type string="q(const).my_int"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="class"  />
+            <swigxml:bases >
+                <swigxml:item name="my_struct"  />
+                <swigxml:item name="my_union"  />
+            </swigxml:bases>
+            <swigxml:namespace string="my_class"  />
+          </c:class>
+          <c:typedef name="my_int" >
+            <swigxml:type string="int"  />
+          </c:typedef>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/example_xml.h b/trunk/Examples/xml/example_xml.h
new file mode 100644
index 0000000..849071d
--- /dev/null
+++ b/trunk/Examples/xml/example_xml.h
@@ -0,0 +1,39 @@
+/* File : example.h */
+
+class Shape {
+public:
+  Shape() {
+    nshapes++;
+  }
+  virtual ~Shape() {
+    nshapes--;
+  };
+  double  x, y;   
+  void    move(double dx, double dy);
+  virtual double area() = 0;
+  virtual double perimeter() = 0;
+  static  int nshapes;
+};
+
+class Circle : public Shape {
+private:
+  double radius;
+public:
+  Circle(double r) : radius(r) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+class Square : public Shape {
+private:
+  double width;
+public:
+  Square(double w) : width(w) { };
+  virtual double area();
+  virtual double perimeter();
+};
+
+
+
+
+  
diff --git a/trunk/Examples/xml/example_xml.i b/trunk/Examples/xml/example_xml.i
new file mode 100644
index 0000000..a598b6a
--- /dev/null
+++ b/trunk/Examples/xml/example_xml.i
@@ -0,0 +1,69 @@
+/* File : example.i */
+%module my_example
+
+enum color { RED=10, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
+
+
+%include pointer.i
+
+/* Next we'll use some typemaps */
+
+%include typemaps.i
+
+%typemap(out) int * {
+    WHATEVER  MAKES YOU HAPPY AS RESULT
+}
+
+%typemap(in) int * {
+    WHATEVER  MAKES YOU HAPPY AS PARAMETER
+}
+
+%pragma(xml) DEBUG="false";
+
+extern  int *  my_gcd(const char * x, int * y[], int * r, int (*op)(int,int)) const;
+extern double my_foo;
+void my_void();
+my_empty();
+
+const double my_dutch = 1.0;
+
+union my_union
+{
+    int my_iii;
+    char my_ccc;
+};
+
+struct my_struct
+{
+public:
+    virtual ~my_struct();
+  int my_foo();
+protected:
+  int my_bar;
+  double  x, y;   
+  virtual double area() = 0;
+  static  int nshapes;
+};
+
+class my_class : public my_struct, public my_union
+{
+public:
+    my_class( char c );
+private:
+    ~my_class();
+    virtual const int *  my_func( my_class , char * * x, int y[], const int & r) const;
+    double my_foo[128];
+    const my_int i;
+};
+
+typedef int my_int;
diff --git a/trunk/Examples/xml/gnarly.expected-xml b/trunk/Examples/xml/gnarly.expected-xml
new file mode 100644
index 0000000..da87d8a
--- /dev/null
+++ b/trunk/Examples/xml/gnarly.expected-xml
@@ -0,0 +1,206 @@
+<swigxml:swig name="namespaces" xmlns:swigxml="http://jniplusplus.sourceforge.net" xmlns:swig="http://swig.sourceforge.net" xmlns:c="http://www.ansi.org" >
+  <swig:top >
+    <swigxml:child >
+      <swig:file name="../../Lib/swig.swg" >
+        <swigxml:type string="include"  />
+      </swig:file>
+      <swig:file name="gnarly.i" >
+        <swigxml:child >
+          <swig:module name="my_check"  />
+          <c:enum name="color" >
+            <swigxml:child >
+              <c:enumvalue name="RED" >
+                <swigxml:value string="RED"  />
+              </c:enumvalue>
+              <c:enumvalue name="BLUE"  />
+              <c:enumvalue name="GREEN"  />
+            </swigxml:child>
+          </c:enum>
+          <c:class name="Foo" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:function name="Foo" >
+                <swigxml:code >
+{ }                </swigxml:code>
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:enum name="speed" >
+                <swigxml:child >
+                  <c:enumvalue name="IMPULSE"  />
+                  <c:enumvalue name="WARP"  />
+                  <c:enumvalue name="LUDICROUS"  />
+                </swigxml:child>
+              </c:enum>
+              <c:function name="enum_test" >
+                <swigxml:parms >
+                  <swigxml:parm name="s" >
+                    <swigxml:type string="speed"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:type string="void"  />
+              </c:function>
+            </swigxml:child>
+            <swigxml:classtype string="class"  />
+            <swigxml:namespace string="Foo"  />
+          </c:class>
+          <c:function name="enum_test" >
+            <swigxml:parms >
+              <swigxml:parm name="c" >
+                <swigxml:type string="color"  />
+              </swigxml:parm>
+              <swigxml:parm name="s" >
+                <swigxml:type string="Foo::speed"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:type string="void"  />
+          </c:function>
+          <swig:typemap >
+            <swigxml:code >
+{
+    WHATEVER  MAKES YOU HAPPY AS RESULT
+}            </swigxml:code>
+            <swigxml:method string="out"  />
+            <swigxml:type string="p.int"  />
+          </swig:typemap>
+          <swig:typemap >
+            <swigxml:code >
+{
+    WHATEVER  MAKES YOU HAPPY AS PARAMETER
+}            </swigxml:code>
+            <swigxml:method string="in"  />
+            <swigxml:type string="p.int"  />
+          </swig:typemap>
+          <swig:pragma name="DEBUG" >
+            <swigxml:value string="false"  />
+            <swigxml:lang string="xml"  />
+          </swig:pragma>
+          <c:function name="my_gcd" >
+            <swigxml:parms >
+              <swigxml:parm name="x" >
+                <swigxml:type string="p.q(const).char"  />
+              </swigxml:parm>
+              <swigxml:parm name="y" >
+                <swigxml:type string="a().p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="r" >
+                <swigxml:type string="p.int"  />
+              </swigxml:parm>
+              <swigxml:parm name="op" >
+                <swigxml:type string="p.f(int,int).int"  />
+              </swigxml:parm>
+            </swigxml:parms>
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="p.int"  />
+          </c:function>
+          <c:variable name="my_foo" >
+            <swigxml:storage string="extern"  />
+            <swigxml:type string="double"  />
+          </c:variable>
+          <c:function name="my_void" >
+            <swigxml:type string="void"  />
+          </c:function>
+          <c:function name="my_empty" >
+            <swigxml:type string="int"  />
+          </c:function>
+          <c:variable name="my_dutch" >
+            <swigxml:value string="1.0"  />
+            <swigxml:type string="q(const).double"  />
+          </c:variable>
+          <c:class name="my_union" >
+            <swigxml:child >
+              <c:variable name="my_iii" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="my_ccc" >
+                <swigxml:type string="char"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="union"  />
+            <swigxml:namespace string="my_union"  />
+          </c:class>
+          <c:class name="my_struct" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:destructor name="my_struct" >
+                <swigxml:storage string="virtual"  />
+              </c:destructor>
+              <c:function name="my_foo" >
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:access name="protected"  />
+              <c:variable name="my_bar" >
+                <swigxml:type string="int"  />
+              </c:variable>
+              <c:variable name="x" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:variable name="y" >
+                <swigxml:type string="double"  />
+              </c:variable>
+              <c:function name="area" >
+                <swigxml:abstract string="1"  />
+                <swigxml:storage string="virtual"  />
+                <swigxml:type string="double"  />
+              </c:function>
+              <c:variable name="nshapes" >
+                <swigxml:storage string="static"  />
+                <swigxml:type string="int"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="struct"  />
+            <swigxml:namespace string="my_struct"  />
+          </c:class>
+          <c:class name="my_class" >
+            <swigxml:child >
+              <c:access name="public"  />
+              <c:function name="my_class" >
+                <swigxml:parms >
+                  <swigxml:parm name="c" >
+                    <swigxml:type string="char"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:type string="int"  />
+              </c:function>
+              <c:access name="private"  />
+              <c:destructor name="my_class"  />
+              <c:function name="my_func" >
+                <swigxml:parms >
+                  <swigxml:parm >
+                    <swigxml:type string="my_class"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="x" >
+                    <swigxml:type string="p.p.char"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="y" >
+                    <swigxml:type string="a().int"  />
+                  </swigxml:parm>
+                  <swigxml:parm name="r" >
+                    <swigxml:type string="r.q(const).int"  />
+                  </swigxml:parm>
+                </swigxml:parms>
+                <swigxml:storage string="virtual"  />
+                <swigxml:type string="p.q(const).int"  />
+              </c:function>
+              <c:variable name="my_foo" >
+                <swigxml:type string="a(128).double"  />
+              </c:variable>
+              <c:variable name="i" >
+                <swigxml:type string="q(const).my_int"  />
+              </c:variable>
+            </swigxml:child>
+            <swigxml:classtype string="class"  />
+            <swigxml:bases >
+                <swigxml:item name="my_struct"  />
+                <swigxml:item name="my_union"  />
+            </swigxml:bases>
+            <swigxml:namespace string="my_class"  />
+          </c:class>
+          <c:typedef name="my_int" >
+            <swigxml:type string="int"  />
+          </c:typedef>
+        </swigxml:child>
+        <swigxml:type string="include"  />
+      </swig:file>
+    </swigxml:child>
+  </swig:top>
+</swigxml:swig>
diff --git a/trunk/Examples/xml/gnarly.i b/trunk/Examples/xml/gnarly.i
new file mode 100644
index 0000000..47242f8
--- /dev/null
+++ b/trunk/Examples/xml/gnarly.i
@@ -0,0 +1,63 @@
+/* File : check.i */
+%module my_check
+
+enum color { RED=10, BLUE, GREEN };
+
+class Foo {
+ public:
+  Foo() { }
+  enum speed { IMPULSE, WARP, LUDICROUS };
+  void enum_test(speed s);
+};
+
+void enum_test(color c, Foo::speed s);
+
+
+
+%typemap(out) int * {
+    WHATEVER  MAKES YOU HAPPY AS RESULT
+}
+
+%typemap(in) int * {
+    WHATEVER  MAKES YOU HAPPY AS PARAMETER
+}
+
+%pragma(xml) DEBUG="false";
+
+extern  int *  my_gcd(const char * x, int * y[], int * r, int (*op)(int,int)) const;
+extern double my_foo;
+void my_void();
+my_empty();
+
+const double my_dutch = 1.0;
+
+union my_union
+{
+    int my_iii;
+    char my_ccc;
+};
+
+struct my_struct
+{
+public:
+    virtual ~my_struct();
+  int my_foo();
+protected:
+  int my_bar;
+  double  x, y;   
+  virtual double area() = 0;
+  static  int nshapes;
+};
+
+class my_class : public my_struct, public my_union
+{
+public:
+    my_class( char c );
+private:
+    ~my_class();
+    virtual const int *  my_func( my_class , char * * x, int y[], const int & r) const;
+    double my_foo[128];
+    const my_int i;
+};
+
+typedef int my_int;
diff --git a/trunk/FUTURE b/trunk/FUTURE
new file mode 100644
index 0000000..997de9b
--- /dev/null
+++ b/trunk/FUTURE
@@ -0,0 +1,335 @@
+SWIG-1.3.12, SWIG 2.0, and Beyond
+=================================
+
+With the release of SWIG-1.3.12, I thought I'd take a few moments of
+everyone's time to talk about the past, the present, and the future of
+SWIG development.  I'm really quite excited about the current release
+because I think it represents a huge turning point in SWIG's
+development.  Furthermore, it is only the beginning of bigger and
+better things to come.  However, we definitely need your help.
+
+To put a little perspective on the discussion, I'd start with a few
+development statistics.  In the last 12 months, there have been over
+300 entries added to the CHANGES log and over 4000 CVS commits.
+Although that may not sound like a lot compared to a huge software
+project, it is significant in the context of SWIG.  As a point of
+comparison, there has been more SWIG development this year than in any
+other year of the project and more than in the previous three years
+combined.  This even includes the first few years of development in
+which there was also a lot of activity.  Furthermore, many of the
+recent changes have been extremely non-trivial (e.g., templates,
+namespaces, type system, operators, etc.).  As a result, SWIG is more
+capable than I ever imagined possible.
+
+Regrettably, I must admit that I've been a little negligent in
+discussing the roadmap for where I thought this flurry of SWIG
+development was actually headed.  In part, this is because I've been
+buried in work.  However, the real reason is that I didn't really know
+where we were going---except that in a time far far far away in the
+future, we might arrive at some kind of "stable" release with a
+version number other than "1.3.x".  Needless to say, that's not a very
+compelling story.
+
+That said, I've spent a lot of time thinking about SWIG and trying to
+wrap my brain around it.  Specifically, just what is (or should be)
+the primary focus of this project and what are we really trying to do?
+That's what the rest of this message is about.
+
+SWIG Prehistory 
+---------------
+The first version of SWIG was written in 1995.  The original system
+was developed to help with some software wrapping problems I
+encountered while writing molecular dynamics software at Los
+Alamos. Later that year, I became interested in extending the wrapper
+generator to support other scripting languages so it was rewritten in
+C++ and modified with multiple backends (Tcl, Perl, and Guile).  This
+led to a first public release in February, 1996.  Feedback from this
+release led to a series of enhancements and the release of SWIG 1.0 in
+September 1996.  Throughout this process, my intent was to create a
+tool that I would want to use---I never viewed the project as an
+CS experiment in programming languages or software engineering.
+
+SWIG 1.1
+--------
+SWIG-1.1 (June, 1997) represented a series of enhancements that were
+added in response to feedback at conferences and from users.  Shadow
+classes, exception handling, typemaps, and a number of more useful
+features were added.  However, the overall structure of the system was
+relatively unchanged from the initial version.  Following the release
+of 1.1, a series of minor patch releases were made.  This resulted in
+the release of SWIG-1.1p5 in February, 1998.  Unfortunately, this
+release would remain the last "stable" release for quite a long
+time---in fact, it is still listed as the last "stable" release on the
+SWIG web page!
+
+SWIG Hell
+---------
+Even during the development of SWIG-1.1, it was clear that the whole
+design of the system was deeply flawed.  The implementation was a mess
+and the C/C++ support was full of holes and nasty corner cases.
+Furthermore, there was no unifying principle that tied all of the
+different SWIG directives together.  Not only that, fixing these
+problems appeared to be nothing short of impossible---requiring a
+total ground-up rewrite at best.  The only redeeming quality was that
+the system basically worked "well enough," it was extensively
+documented, and its flaws mostly known.  People could use it and there
+were work-arounds for most common problems.
+
+To deal with the design problem, there were at least four attempts to
+completely rewrite SWIG, some of which were attempted in parallel with
+the work on SWIG-1.1.  Unfortunately, none of these were ever
+completed. The primary problem was a strong "second system" effect and
+a desire to make SWIG do everything that one might conceivably want to
+do with a wrapper generator (somehow).  Clearly, this was a recipe for
+disaster. In fact, all such attempts to rewrite SWIG were eventually
+abandoned several years ago.  In hindsight, I think the real problem
+was that these rewrite efforts focused far too much attention on
+implementation technique rather than principles.  In short, the
+failure of these efforts was due to a lack of clarity in understanding
+how SWIG ought to work (regardless of how it was actually
+implemented).
+
+SWIG Restart (1.3a1-1.3a5)
+--------------------------
+Having languished for several years, the SWIG1.1p5 release had a
+growing pile of maintenance issues. It didn't work for newer versions
+of certain language modules and a lot of minor bug reports and feature
+requests had been building up.  With a lot of help from Loic Dachary and
+Thien-Thi Nguyen, we put together the 1.3a1 release (February,
+2000).  This was mostly a bug fix release to 1.1p5 except that the
+preprocessor module from SWIG1.2 was added and a lot of minor
+enhancements were added.
+
+For the next six months, a massive effort was made to rewrite all of
+SWIG's internal data structures (strings, lists, hashes, etc.).  This
+work was all going on underneath the covers while we tried to keep
+SWIG in an operational state. The primary focus of this work was
+really one of cleanup.  Having given up on a total rewrite, perhaps
+we could settle with making the implementation incrementally better 
+than before.  In addition this, Matthias Koppe jumped on board to 
+reimplement the Guile module and to make other improvements to the system.
+
+An important aspect of these releases was that many parts of the
+system not directly related to wrapper code generation were removed.
+This included the documentation system and Objective-C support.  These
+were not removed because they weren't useful.  Instead, the
+documentation system was removed because it accounted for nearly half
+of the special SWIG directives, yet had no direct bearing on what SWIG
+actually did.  Obective-C support was removed because it was tangled
+with C++ support in a way that was very difficult to understand and
+maintain.  The removal of these features was seen as a way to vastly
+simplify cleanup--and to buy some time where we could rethink their
+role in a future release.
+
+SWIG Redux (1.3.6-1.3.11)
+-------------------------
+This work, started in February 2001, is the beginning of the current
+SWIG implementation.  With the help of William Fulton, Matthias Koppe,
+Lyle Johnson, Luigi Ballabio, Jason Stewart, Richard Palmer, Sam
+Liddicot, and others, this work can best be described as the wholesale
+destruction of everything remaining from SWIG-1.1.  The language
+module API, type system, the parser, numerous SWIG directives, and
+SWIG library files---all destroyed or rewritten.  Not only that, we
+started introducing significant incompatibilities with
+SWIG-1.1---mostly in an effort to correct past wrongs and get
+ourselves out of the tangled mess of earlier versions.  A huge number
+of long-standing bugs and difficult feature requests have also been
+resolved.
+
+The general goal of this development could best be described as an
+attempt to reduce SWIG to an easily described set of general "ideas"
+about how it should operate.  Special SWIG directives have been
+eliminated or combined with others.  Different parts of the system have
+been better integrated.  Features not directly related to wrapper code
+generation have been removed and the system has become more
+focused. Changes in internal data structures and APIs have allowed
+SWIG to capture more information from interface files and to resolve
+hard corner cases.  More often than not, these are things that you
+never notice unless you are an old user and you suddenly realize that
+a problem you had several years back has disappeared.
+
+Along with the destruction of old code, this work has quietly
+introduced a new core--the most significant features of which are a
+new C++ type system and multi-pass compilation.  More importantly,
+this work has really tried to provide a more principled foundation for
+future SWIG development.  However, just what is this "more principled
+foundation?"
+
+Convergence (1.3.12)
+--------------------
+With the upcoming 1.3.12 release, SWIG is about to take a big leap
+forward. Almost all of this is due to one realization---that almost
+every hard problem in past SWIG releases has been directly related to
+errors and limitations in its type system.  Types are the key to
+understanding the structure of C and C++ code.  They are at the heart
+of understanding advanced language features like namespaces, nested
+classes, and templates.  They are directly related to the data
+marshalling that occurs in wrappers.  Not only that, they interact
+with nearly every SWIG directive.  A proper type system *is* the
+necessary foundation for moving SWIG forward.
+
+To be honest, I don't think that the emphasis on types is entirely
+obvious.  In fact, a great deal of work in past SWIG rewrites has
+focused on the problem of C++ parsing.  For instance, modifying the
+parser to handle more advanced C++ code or representing parse trees as
+XML.  Furthermore, if one looks at the SWIG mailing list, you can find
+a *lot* of messages related to issues of C++ parsing whereas almost no
+one ever talks about types (well, other than typemaps).  Even other
+wrapper generation tools seems to spend a lot of time dealing with the
+parsing issue. Although parsing is clearly important, I don't think it
+has ever been the real problem in SWIG.  This is because even though a
+parser can tell you what's in a header file, it doesn't tell you
+anything about how the different pieces of the system behave or how
+they might interact. To do that, you need to do a lot more than just
+parsing--and that's really the whole point.
+ 
+Although earlier 1.3 releases have made big improvements to the type
+system, SWIG-1.3.12 is the first release that really tries to tackle
+the type-system issue in a major way.  We have patched nearly all
+remaining holes in the type system and we have added full support for
+C++ namespaces. Not only that, we have completely reimplemented C++
+template support in a way that supports templates, member templates,
+and template specialization.  Luigi and I are currently using this to
+work on proper SWIG library support for parts of the C++ standard
+library and the Standard Template Library (STL).  Although some crusty
+C programmers (present company excepted), might balk at such apparent
+insanity, this work has impacted all parts of SWIG at all levels.
+Even a variety of subtle errors in C support have been fixed by this
+work.
+
+In addition to the type system work, SWIG-1.3.12 contains continued
+reduction in the implementation. Directives have been removed,
+refined, renamed, or consolidated.  We're still narrowing the focus of
+the system and working towards some kind of convergence.  "Convergence
+to what?!?", you ask.
+
+So, what is SWIG?
+-----------------
+In a nutshell, SWIG is a C/C++ declaration compiler that generates
+wrapper code (okay, so you knew that much).  However, to really
+understand what SWIG is doing and where SWIG-1.3.x is headed, it is
+useful to know that the whole system is essentially being built around
+three extensions to the C++ type system:
+
+   -  Typemaps.  Typemaps are rules that define the process by which
+      data is converted between languages.   They are fully integrated
+      with the C++ type system and they are applied using a type-based
+      pattern matching mechanism.  All data conversion SWIG is
+      defined by typemaps and is fully reconfigurable.
+
+   -  Declaration annotation. There are special directives that modify
+      the wrapping behavior of individual declarations. Declarations
+      can be selectively identified and decorated with arbitrary
+      attributes that affect wrapper generation.  Like typemaps, 
+      declaration matching is fully integrated with the C++ type system. 
+      Almost all SWIG customization directives are a form of declaration 
+      annotation.   
+
+   -  Class extension.  The ability to extend classes and structures
+      with new methods/attributes when building wrappers.  Classes
+      are part of the type system so class extension is naturally 
+      integrated with the C++ type system as well (big surprise).
+
+And that's it--this is the end-game of SWIG-1.3.x development.  When
+stabilized and documented it will become SWIG-2.0.
+
+The Bigger Picture
+------------------
+I really want to emphasize that all of this work is part of a much
+bigger picture.  SWIG is used by a surprising number of people in
+industry, government, and academia.  It's used to build systems used
+by millions of people every day.  It has even shown up in video games
+and other unlikely settings.  Although SWIG doesn't have the same
+visibility as many large software projects, over 12000 people have
+downloaded SWIG-1.3.11 in the last 4 months.  Clearly someone is using
+it for something!  Because of this, I think it is important for us to
+work on moving SWIG towards a more solid foundation.  Doing so will
+give the system more credibility and long term viability---and it will
+be a lot more fun to use!
+
+It's also worth noting that there are some rather interesting CS
+connections at work here.  Extensions to the type system and typemaps
+have some interesting relations to work in programming languages.  The
+SWIG declaration annotation system and class extension feature seem
+oddly similar to work in the emerging area of Aspect Oriented
+Programming (AOP).  There are undoubtedly connections to other areas
+of software engineering and architecture.
+
+The key point is that SWIG isn't going to connect to anything if
+no-one can quite describe what it is or how it works.
+
+SWIG-2.0 and the Future
+-----------------------
+SWIG-1.3.12 still represents work in progress. There are bugs, the
+documentation is still incomplete, and there are parts of the
+implementation that are rather ugly.  We are also still working out a
+few very hard problems like nested classes, callback functions, and
+overloading.  A few old features are still missing (Objective-C,
+documentation).  However, I believe the end of the 1.3.x series is
+near and achievable.
+
+Over the summer, a few more 1.3.x releases may appear but the current
+plan is to aim for a SWIG-2.0 release in September.  This release is
+really moving towards the design principles described above and will
+be a very major enhancement over SWIG-1.1.
+
+As for the future, a number of interesting ideas are on the table.  I
+want to add support for contracts/assertions in order to solve some
+reliability issues that arise when retrofitting legacy codes with a
+scripting interface.  Support for an extension language has been
+promoted by David Fletcher and was suggested by someone else on the
+mailing list rather recently.  I have a graduate student working on
+SWIG support for the Microsoft CLR and .NET languages.  Other work
+might include support for alternative parsers, dynamically loadable
+language modules, and so forth.  However, none of this is really going
+to materialize if we can't get the 2.0 release stablized.  In fact, I
+see SWIG-2.0 as a necessary step for moving forward with these ideas.
+
+We need your help! Yes, you.
+----------------------------
+Nobody gets paid to work on SWIG.  The developers are volunteers who
+work in their spare time.  Furthermore, SWIG is not supported by
+investors, a large corporation, or research grants.  I work on it
+because it's fun, challenging, and useful.  I presume that other
+developers do the same.  However, we only have limited resources and
+we need your help.
+
+-  If you like SWIG and find it useful, we need you to try new versions.
+   We want you to torture test the releases and to break them.  We need
+   bug reports. No bug is too obscure or unimportant---we *will* fix it
+   if we can.  We also need feedback about things that are annoying or
+   compatibility features that might help in going from 1.1 to 2.0.
+
+-  We need help with documentation, examples, testing, libraries, and all
+   sorts of other aspects of the release.  Even if you have never
+   written a SWIG language module or dived into its implementation,
+   there are many ways that you can help.  Consider writing a case study
+   about how you wrapped a big library.  Contribute tests that break the
+   implementation in horrible ways.  Help with the web page or FAQ.
+
+-  Most of the SWIG-1.3.x work has focused on the SWIG core.  However, as
+   the 2.0 release nears, we will be working on a variety of enhancements
+   to the language modules.  If there are things you would like to see
+   in any of the language modules, you need to let us know.
+
+-  There are SWIG language modules that have not made it into the
+   distribution.  Examples that I know about include ITCL, Swig-Eiffel,
+   and Swig-Lua.  We would gladly make these part of the standard SWIG
+   distribution.  However, we also need help to do it.  Porting from
+   SWIG-1.1 is no easy task, but we're more than willing to help.  It's
+   not as bad as one might imagine.
+
+-  We are always looking for developers.  Subscribe to
+   the swig-dev mailing list, details at http://www.swig.org/mail.html,
+   or send me email to get involved.
+
+Acknowledgements
+----------------
+I'd just like to thank everyone who has submitted feedback, bugs, made
+contributions, and put up with my occasional thrashing over the years. 
+I welcome any comments about this document and how we can make SWIG even
+better.
+
+Dave Beazley (beazley@cs.uchicago.edu)
+June 2, 2002
+
diff --git a/trunk/INSTALL b/trunk/INSTALL
new file mode 100644
index 0000000..666ffd9
--- /dev/null
+++ b/trunk/INSTALL
@@ -0,0 +1,226 @@
+Basic Installation
+==================
+
+   These are generic installation instructions.
+
+   The `configure' shell script attempts to guess correct values for
+various system-dependent variables used during compilation.  It uses
+those values to create a `Makefile' in each directory of the package.
+It may also create one or more `.h' files containing system-dependent
+definitions.  Finally, it creates a shell script `config.status' that
+you can run in the future to recreate the current configuration, and a
+file `config.log' containing compiler output (useful mainly for
+debugging `configure').
+
+   It can also use an optional file (typically called `config.cache'
+and enabled with `--cache-file=config.cache' or simply `-C') that saves
+the results of its tests to speed up reconfiguring.  (Caching is
+disabled by default to prevent problems with accidental use of stale
+cache files.)
+
+   If you need to do unusual things to compile the package, please try
+to figure out how `configure' could check whether to do them, and mail
+diffs or instructions to the address given in the `README' so they can
+be considered for the next release.  If you are using the cache, and at
+some point `config.cache' contains results you don't want to keep, you
+may remove or edit it.
+
+   The file `configure.ac' (or `configure.in') is used to create
+`configure' by a program called `autoconf'.  You only need
+`configure.ac' if you want to change it or regenerate `configure' using
+a newer version of `autoconf'.
+
+The simplest way to compile this package is:
+
+  1. `cd' to the directory containing the package's source code and type
+     `./configure' to configure the package for your system.  If you're
+     using `csh' on an old version of System V, you might need to type
+     `sh ./configure' instead to prevent `csh' from trying to execute
+     `configure' itself.
+
+     Running `configure' takes awhile.  While running, it prints some
+     messages telling which features it is checking for.
+
+  2. Type `make' to compile the package.
+
+  3. Optionally, type `make check' to run any self-tests that come with
+     the package.
+
+  4. Type `make install' to install the programs and any data files and
+     documentation.
+
+  5. You can remove the program binaries and object files from the
+     source code directory by typing `make clean'.  To also remove the
+     files that `configure' created (so you can compile the package for
+     a different kind of computer), type `make distclean'.  There is
+     also a `make maintainer-clean' target, but that is intended mainly
+     for the package's developers.  If you use it, you may have to get
+     all sorts of other programs in order to regenerate files that came
+     with the distribution.
+
+Compilers and Options
+=====================
+
+   Some systems require unusual options for compilation or linking that
+the `configure' script does not know about.  Run `./configure --help'
+for details on some of the pertinent environment variables.
+
+   You can give `configure' initial values for variables by setting
+them in the environment.  You can do that on the command line like this:
+
+     ./configure CC=c89 CFLAGS=-O2 LIBS=-lposix
+
+   *Note Environment Variables::, for more details.
+
+Compiling For Multiple Architectures
+====================================
+
+   You can compile the package for more than one kind of computer at the
+same time, by placing the object files for each architecture in their
+own directory.  To do this, you must use a version of `make' that
+supports the `VPATH' variable, such as GNU `make'.  `cd' to the
+directory where you want the object files and executables to go and run
+the `configure' script.  `configure' automatically checks for the
+source code in the directory that `configure' is in and in `..'.
+
+   If you have to use a `make' that does not support the `VPATH'
+variable, you have to compile the package for one architecture at a time
+in the source code directory.  After you have installed the package for
+one architecture, use `make distclean' before reconfiguring for another
+architecture.
+
+Installation Names
+==================
+
+   By default, `make install' will install the package's files in
+`/usr/local/bin', `/usr/local/man', etc.  You can specify an
+installation prefix other than `/usr/local' by giving `configure' the
+option `--prefix=PATH'.
+
+   You can specify separate installation prefixes for
+architecture-specific files and architecture-independent files.  If you
+give `configure' the option `--exec-prefix=PATH', the package will use
+PATH as the prefix for installing programs and libraries.
+Documentation and other data files will still use the regular prefix.
+
+   In addition, if you use an unusual directory layout you can give
+options like `--bindir=PATH' to specify different values for particular
+kinds of files.  Run `configure --help' for a list of the directories
+you can set and what kinds of files go in them.
+
+   If the package supports it, you can cause programs to be installed
+with an extra prefix or suffix on their names by giving `configure' the
+option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
+
+Optional Features
+=================
+
+   Some packages pay attention to `--enable-FEATURE' options to
+`configure', where FEATURE indicates an optional part of the package.
+They may also pay attention to `--with-PACKAGE' options, where PACKAGE
+is something like `gnu-as' or `x' (for the X Window System).  The
+`README' should mention any `--enable-' and `--with-' options that the
+package recognizes.
+
+   For packages that use the X Window System, `configure' can usually
+find the X include and library files automatically, but if it doesn't,
+you can use the `configure' options `--x-includes=DIR' and
+`--x-libraries=DIR' to specify their locations.
+
+Specifying the System Type
+==========================
+
+   There may be some features `configure' cannot figure out
+automatically, but needs to determine by the type of host the package
+will run on.  Usually `configure' can figure that out, but if it prints
+a message saying it cannot guess the host type, give it the
+`--build=TYPE' option.  TYPE can either be a short name for the system
+type, such as `sun4', or a canonical name which has the form:
+
+     CPU-COMPANY-SYSTEM
+
+where SYSTEM can have one of these forms:
+
+     OS
+     KERNEL-OS
+
+   See the file `config.sub' for the possible values of each field.  If
+`config.sub' isn't included in this package, then this package doesn't
+need to know the host type.
+
+   If you are _building_ compiler tools for cross-compiling, you should
+use the `--target=TYPE' option to select the type of system they will
+produce code for.
+
+   If you want to _use_ a cross compiler, that generates code for a
+platform different from the build platform, you should specify the host
+platform (i.e., that on which the generated programs will eventually be
+run) with `--host=TYPE'.  In this case, you should also specify the
+build platform with `--build=TYPE', because, in this case, it may not
+be possible to guess the build platform (it sometimes involves
+compiling and running simple test programs, and this can't be done if
+the compiler is a cross compiler).
+
+Sharing Defaults
+================
+
+   If you want to set default values for `configure' scripts to share,
+you can create a site shell script called `config.site' that gives
+default values for variables like `CC', `cache_file', and `prefix'.
+`configure' looks for `PREFIX/share/config.site' if it exists, then
+`PREFIX/etc/config.site' if it exists.  Or, you can set the
+`CONFIG_SITE' environment variable to the location of the site script.
+A warning: not all `configure' scripts look for a site script.
+
+Environment Variables
+=====================
+
+   Variables not defined in a site shell script can be set in the
+environment passed to configure.  However, some packages may run
+configure again during the build, and the customized values of these
+variables may be lost.  In order to avoid this problem, you should set
+them in the `configure' command line, using `VAR=value'.  For example:
+
+     ./configure CC=/usr/local2/bin/gcc
+
+will cause the specified gcc to be used as the C compiler (unless it is
+overridden in the site shell script).
+
+`configure' Invocation
+======================
+
+   `configure' recognizes the following options to control how it
+operates.
+
+`--help'
+`-h'
+     Print a summary of the options to `configure', and exit.
+
+`--version'
+`-V'
+     Print the version of Autoconf used to generate the `configure'
+     script, and exit.
+
+`--cache-file=FILE'
+     Enable the cache: use and save the results of the tests in FILE,
+     traditionally `config.cache'.  FILE defaults to `/dev/null' to
+     disable caching.
+
+`--config-cache'
+`-C'
+     Alias for `--cache-file=config.cache'.
+
+`--quiet'
+`--silent'
+`-q'
+     Do not print messages saying which checks are being made.  To
+     suppress all normal output, redirect it to `/dev/null' (any error
+     messages will still be shown).
+
+`--srcdir=DIR'
+     Look for the package's source code in directory DIR.  Usually
+     `configure' can determine that directory automatically.
+
+`configure' also accepts some other, not widely useful, options.  Run
+`configure --help' for more details.
+
diff --git a/trunk/LICENSE b/trunk/LICENSE
new file mode 100644
index 0000000..fdb73d9
--- /dev/null
+++ b/trunk/LICENSE
@@ -0,0 +1,95 @@
+SWIG is distributed under the following terms:
+
+I.  
+
+Copyright (c) 1995-1998
+The University of Utah and the Regents of the University of California
+All Rights Reserved
+
+Permission is hereby granted, without written agreement and without
+license or royalty fees, to use, copy, modify, and distribute this
+software and its documentation for any purpose, provided that 
+(1) The above copyright notice and the following two paragraphs
+appear in all copies of the source code and (2) redistributions
+including binaries reproduces these notices in the supporting
+documentation.   Substantial modifications to this software may be
+copyrighted by their authors and need not follow the licensing terms
+described here, provided that the new terms are clearly indicated in
+all files where they apply.
+
+IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE 
+UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
+PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
+EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGE.
+
+THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH
+SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, 
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND 
+THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE,
+SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+
+II. 
+
+This software includes contributions that are Copyright (c) 1998-2005
+University of Chicago.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer.  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.  Neither the name of
+the University of Chicago nor the names of its contributors may be
+used to endorse or promote products derived from this software without
+specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF CHICAGO AND CONTRIBUTORS
+"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 UNIVERSITY OF
+CHICAGO OR CONTRIBUTORS 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.
+
+
+III.  
+
+This software includes contributions that are Copyright (c) 2005-2006
+Arizona Board of Regents (University of Arizona).
+All Rights Reserved
+
+Permission is hereby granted, without written agreement and without
+license or royalty fees, to use, copy, modify, and distribute this
+software and its documentation for any purpose, provided that 
+(1) The above copyright notice and the following two paragraphs
+appear in all copies of the source code and (2) redistributions
+including binaries reproduces these notices in the supporting
+documentation.   Substantial modifications to this software may be
+copyrighted by their authors and need not follow the licensing terms
+described here, provided that the new terms are clearly indicated in
+all files where they apply.
+
+THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF ARIZONA AND CONTRIBUTORS
+"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 UNIVERSITY OF
+ARIZONA OR CONTRIBUTORS 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.
+
diff --git a/trunk/Lib/allegrocl/allegrocl.swg b/trunk/Lib/allegrocl/allegrocl.swg
new file mode 100644
index 0000000..0ae8ed7
--- /dev/null
+++ b/trunk/Lib/allegrocl/allegrocl.swg
@@ -0,0 +1,544 @@
+/* Define a C preprocessor symbol that can be used in interface files
+   to distinguish between the SWIG language modules. */ 
+
+#define SWIG_ALLEGRO_CL
+
+#define %ffargs(...) %feature("ffargs", "1", ##__VA_ARGS__)
+%ffargs(strings_convert="t");
+
+/* typemaps for argument and result type conversions. */
+%typemap(lin,numinputs=1)	SWIGTYPE 	"(cl::let (($out $in))\n  $body)";
+
+%typemap(lout) bool, char, unsigned char, signed char,
+               short, signed short, unsigned short,
+               int, signed int, unsigned int,
+               long, signed long, unsigned long,
+               float, double, long double, char *, void *,
+               enum SWIGTYPE    "(cl::setq ACL_ffresult $body)";
+%typemap(lout) void "$body";
+%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *,
+               SWIGTYPE &       
+%{ (cl:let* ((address $body)
+	  (new-inst (cl:make-instance '$lclass :foreign-address address)))
+     (cl:when (cl:and $owner (cl:not (cl:zerop address)))
+       (excl:schedule-finalization new-inst #'$ldestructor))
+     (cl:setq ACL_ffresult new-inst)) %}
+
+%typemap(lout) SWIGTYPE         "(cl::let* ((address $body)\n         (new-inst (cl::make-instance '$lclass :foreign-address address)))\n    (cl::unless (cl::zerop address)\n      (excl:schedule-finalization new-inst #'$ldestructor))\n    (cl::setq ACL_ffresult new-inst))";
+
+%typemap(lisptype) bool "cl:boolean";
+%typemap(lisptype) char "cl:character";
+%typemap(lisptype) unsigned char "cl:integer";
+%typemap(lisptype) signed char "cl:integer";
+
+%typemap(ffitype) bool ":int";
+%typemap(ffitype) char ":char";
+%typemap(ffitype) unsigned char ":unsigned-char";
+%typemap(ffitype) signed char ":char";
+%typemap(ffitype) short, signed short ":short";
+%typemap(ffitype) unsigned short ":unsigned-short";
+%typemap(ffitype) int, signed int ":int";
+%typemap(ffitype) unsigned int ":unsigned-int";
+%typemap(ffitype) long, signed long ":long";
+%typemap(ffitype) unsigned long ":unsigned-long";
+%typemap(ffitype) float ":float";
+%typemap(ffitype) double ":double";
+%typemap(ffitype) char * "(* :char)";
+%typemap(ffitype) void * "(* :void)";
+%typemap(ffitype) void ":void";
+%typemap(ffitype) enum SWIGTYPE ":int";
+%typemap(ffitype) SWIGTYPE & "(* :void)";
+
+%typemap(ctype) bool                       "int";
+%typemap(ctype) char, unsigned char, signed char,
+                short, signed short, unsigned short,
+                int, signed int, unsigned int,
+                long, signed long, unsigned long,
+                float, double, long double, char *, void *, void,
+                enum SWIGTYPE, SWIGTYPE *,
+                SWIGTYPE[ANY], SWIGTYPE &  "$1_ltype";
+%typemap(ctype) SWIGTYPE                   "$&1_type";
+
+%typemap(in) bool                          "$1 = (bool)$input;";
+%typemap(in) char, unsigned char, signed char,
+             short, signed short, unsigned short,
+             int, signed int, unsigned int,
+             long, signed long, unsigned long,
+             float, double, long double, char *, void *, void,
+             enum SWIGTYPE, SWIGTYPE *,
+             SWIGTYPE[ANY], SWIGTYPE &     "$1 = $input;";
+%typemap(in) SWIGTYPE                      "$1 = *$input;";
+
+/* We don't need to do any actual C-side typechecking, but need to
+   use the precedence values to choose which overloaded function
+   interfaces to generate when conflicts arise. */
+
+/* predefined precedence values
+
+Symbolic Name                   Precedence Value
+------------------------------  ------------------
+SWIG_TYPECHECK_POINTER           0  
+SWIG_TYPECHECK_VOIDPTR           10 
+SWIG_TYPECHECK_BOOL              15 
+SWIG_TYPECHECK_UINT8             20 
+SWIG_TYPECHECK_INT8              25 
+SWIG_TYPECHECK_UINT16            30 
+SWIG_TYPECHECK_INT16             35 
+SWIG_TYPECHECK_UINT32            40 
+SWIG_TYPECHECK_INT32             45 
+SWIG_TYPECHECK_UINT64            50 
+SWIG_TYPECHECK_INT64             55 
+SWIG_TYPECHECK_UINT128           60 
+SWIG_TYPECHECK_INT128            65 
+SWIG_TYPECHECK_INTEGER           70 
+SWIG_TYPECHECK_FLOAT             80 
+SWIG_TYPECHECK_DOUBLE            90 
+SWIG_TYPECHECK_COMPLEX           100 
+SWIG_TYPECHECK_UNICHAR           110 
+SWIG_TYPECHECK_UNISTRING         120 
+SWIG_TYPECHECK_CHAR              130 
+SWIG_TYPECHECK_STRING            140 
+SWIG_TYPECHECK_BOOL_ARRAY        1015 
+SWIG_TYPECHECK_INT8_ARRAY        1025 
+SWIG_TYPECHECK_INT16_ARRAY       1035 
+SWIG_TYPECHECK_INT32_ARRAY       1045 
+SWIG_TYPECHECK_INT64_ARRAY       1055 
+SWIG_TYPECHECK_INT128_ARRAY      1065 
+SWIG_TYPECHECK_FLOAT_ARRAY       1080 
+SWIG_TYPECHECK_DOUBLE_ARRAY      1090 
+SWIG_TYPECHECK_CHAR_ARRAY        1130 
+SWIG_TYPECHECK_STRING_ARRAY      1140
+*/
+
+%typecheck(SWIG_TYPECHECK_BOOL) bool { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_CHAR) char { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_FLOAT) float { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_DOUBLE) double { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_STRING) char * { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_INTEGER)
+                    unsigned char, signed char,
+                    short, signed short, unsigned short,
+                    int, signed int, unsigned int,
+                    long, signed long, unsigned long,
+                    enum SWIGTYPE { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &,
+                                   SWIGTYPE[ANY], SWIGTYPE { $1 = 1; };
+
+/* This maps C/C++ types to Lisp classes for overload dispatch */
+
+%typemap(lispclass) bool "t";
+%typemap(lispclass) char "cl:character";
+%typemap(lispclass) unsigned char, signed char,
+                    short, signed short, unsigned short,
+                    int, signed int, unsigned int,
+                    long, signed long, unsigned long,
+                    enum SWIGTYPE       "cl:integer";
+%typemap(lispclass) float "cl:single-float";
+%typemap(lispclass) double "cl:double-float";
+%typemap(lispclass) char * "cl:string";
+
+%typemap(out) void                          "";
+%typemap(out) bool                          "$result = (int)$1;";
+%typemap(out) char, unsigned char, signed char,
+              short, signed short, unsigned short,
+              int, signed int, unsigned int,
+              long, signed long, unsigned long,
+              float, double, long double, char *, void *,
+              enum SWIGTYPE, SWIGTYPE *,
+              SWIGTYPE[ANY], SWIGTYPE &    "$result = $1;";
+#ifdef __cplusplus
+%typemap(out) SWIGTYPE                     "$result = new $1_type($1);";
+#else
+%typemap(out) SWIGTYPE {
+  $result = ($&1_ltype) malloc(sizeof($1_type));
+  memmove($result, &$1, sizeof($1_type));
+}
+#endif
+
+//////////////////////////////////////////////////////////////
+// UCS-2 string conversion
+
+// should this be SWIG_TYPECHECK_CHAR?
+%typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; };
+
+%typemap(in)        wchar_t "$1 = $input;";
+%typemap(lin,numinputs=1)       wchar_t "(cl::let (($out (cl:char-code $in)))\n  $body)";
+%typemap(lin,numinputs=1)       wchar_t* "(excl:with-native-string ($out $in
+:external-format #+little-endian :fat-le #-little-endian :fat)\n
+$body)"
+
+%typemap(out)       wchar_t "$result = $1;";
+%typemap(lout)      wchar_t "(cl::setq ACL_ffresult (cl::code-char $body))";
+%typemap(lout)      wchar_t* "(cl::setq ACL_ffresult (excl:native-to-string $body
+:external-format #+little-endian :fat-le #-little-endian :fat))";
+
+%typemap(ffitype)   wchar_t ":unsigned-short";
+%typemap(lisptype)  wchar_t "";
+%typemap(ctype)     wchar_t "wchar_t";
+%typemap(lispclass) wchar_t "cl:character";
+%typemap(lispclass) wchar_t* "cl:string";
+//////////////////////////////////////////////////////////////
+
+/* name conversion for overloaded operators. */
+#ifdef __cplusplus
+%rename(__add__)	     *::operator+;
+%rename(__pos__)	     *::operator+();
+%rename(__pos__)	     *::operator+() const;
+
+%rename(__sub__)	     *::operator-;
+%rename(__neg__)	     *::operator-() const;
+%rename(__neg__)	     *::operator-();
+
+%rename(__mul__)	     *::operator*;
+%rename(__deref__)	     *::operator*();
+%rename(__deref__)	     *::operator*() const;
+
+%rename(__div__)	     *::operator/;
+%rename(__mod__)	     *::operator%;
+%rename(__logxor__)	     *::operator^;
+%rename(__logand__)	     *::operator&;
+%rename(__logior__)	     *::operator|;
+%rename(__lognot__)	     *::operator~();
+%rename(__lognot__)	     *::operator~() const;
+
+%rename(__not__)	     *::operator!();
+%rename(__not__)	     *::operator!() const;
+
+%rename(__assign__)	     *::operator=;
+
+%rename(__add_assign__)      *::operator+=;
+%rename(__sub_assign__)	     *::operator-=;
+%rename(__mul_assign__)	     *::operator*=;
+%rename(__div_assign__)	     *::operator/=;
+%rename(__mod_assign__)	     *::operator%=;
+%rename(__logxor_assign__)   *::operator^=;
+%rename(__logand_assign__)   *::operator&=;
+%rename(__logior_assign__)   *::operator|=;
+
+%rename(__lshift__)	     *::operator<<;
+%rename(__lshift_assign__)   *::operator<<=;
+%rename(__rshift__)	     *::operator>>;
+%rename(__rshift_assign__)   *::operator>>=;
+
+%rename(__eq__)		     *::operator==;
+%rename(__ne__)		     *::operator!=;
+%rename(__lt__)		     *::operator<;
+%rename(__gt__)		     *::operator>;
+%rename(__lte__)	     *::operator<=;
+%rename(__gte__)	     *::operator>=;
+
+%rename(__and__)	     *::operator&&;
+%rename(__or__)		     *::operator||;
+
+%rename(__preincr__)	     *::operator++();
+%rename(__postincr__)	     *::operator++(int);
+%rename(__predecr__)	     *::operator--();
+%rename(__postdecr__)	     *::operator--(int);
+
+%rename(__comma__)	     *::operator,();
+%rename(__comma__)	     *::operator,() const;
+
+%rename(__member_ref__)      *::operator->;
+%rename(__member_func_ref__) *::operator->*;
+
+%rename(__funcall__)	     *::operator();
+%rename(__aref__)	     *::operator[];
+#endif
+
+%insert("lisphead") %{
+;; $Id$
+
+(eval-when (compile load eval)
+
+  ;; avoid compiling ef-templates at runtime
+  (excl:find-external-format :fat)
+  (excl:find-external-format :fat-le)
+
+;;; You can define your own identifier converter if you want.
+;;; Use the -identifier-converter command line argument to
+;;; specify its name.
+
+(eval-when (:compile-toplevel :load-toplevel :execute)
+   (cl::defparameter *swig-export-list* nil))
+
+(cl::defconstant *void* :..void..)
+
+;; parsers to aid in finding SWIG definitions in files.
+(cl::defun scm-p1 (form)
+  (let* ((info (cl::second form))
+	 (id (car info))
+	 (id-args (if (eq (cl::car form) 'swig-dispatcher)
+		      (cl::cdr info)
+		      (cl::cddr info))))
+    (cl::apply *swig-identifier-converter* id 
+	   (cl::progn (cl::when (cl::eq (cl::car form) 'swig-dispatcher)
+		    (cl::remf id-args :arities))
+		  id-args))))
+
+(cl::defmacro defswig1 (name (&rest args) &body body)
+  `(cl::progn (cl::defmacro ,name ,args
+	    ,@body)
+	  (excl::define-simple-parser ,name scm-p1)) )
+
+(cl::defmacro defswig2 (name (&rest args) &body body)
+  `(cl::progn (cl::defmacro ,name ,args
+	    ,@body)
+	  (excl::define-simple-parser ,name second)))
+
+(defun read-symbol-from-string (string)
+  (cl::multiple-value-bind (result position)
+      (cl::read-from-string string nil "eof" :preserve-whitespace t)
+    (cl::if (cl::and (cl::symbolp result)
+    	             (cl::eql position (cl::length string)))
+        result
+	(cl::multiple-value-bind (sym)
+	    (cl::intern string)
+	  sym))))
+
+(cl::defun full-name (id type arity class)
+  (cl::case type
+    (:getter (cl::format nil "~@[~A_~]~A" class id))
+    (:constructor (cl::format nil "new_~A~@[~A~]" id arity))
+    (:destructor (cl::format nil "delete_~A" id))
+    (:type (cl::format nil "ff_~A" id))
+    (:slot id)
+    (:ff-operator (cl::format nil "ffi_~A" id))
+    (otherwise (cl::format nil "~@[~A_~]~A~@[~A~]"
+                       class id arity))))
+  
+(cl::defun identifier-convert-null (id &key type class arity)
+  (cl::if (cl::eq type :setter)
+      `(cl::setf ,(identifier-convert-null
+               id :type :getter :class class :arity arity))
+      (read-symbol-from-string (full-name id type arity class))))
+
+(cl::defun identifier-convert-lispify (cname &key type class arity)
+  (cl::assert (cl::stringp cname))
+  (cl::when (cl::eq type :setter)
+    (cl::return-from identifier-convert-lispify
+      `(cl::setf ,(identifier-convert-lispify
+               cname :type :getter :class class :arity arity))))
+  (cl::setq cname (full-name cname type arity class))
+  (cl::if (cl::eq type :constant)
+      (cl::setf cname (cl::format nil "*~A*" cname)))
+  (cl::setf cname (excl::replace-regexp cname "_" "-"))
+  (cl::let ((lastcase :other)
+       	    newcase char res)
+    (cl::dotimes (n (cl::length cname))
+      (cl::setf char (cl::schar cname n))
+      (excl::if* (cl::alpha-char-p char)
+         then
+              (cl::setf newcase (cl::if (cl::upper-case-p char) :upper :lower))
+
+              (cl::when (cl::or (cl::and (cl::eq lastcase :upper)
+	      				 (cl::eq newcase :lower))
+                                (cl::and (cl::eq lastcase :lower)
+					 (cl::eq newcase :upper)))
+                ;; case change... add a dash
+                (cl::push #\- res)
+                (cl::setf newcase :other))
+
+              (cl::push (cl::char-downcase char) res)
+
+              (cl::setf lastcase newcase)
+
+         else
+              (cl::push char res)
+              (cl::setf lastcase :other)))
+    (read-symbol-from-string (cl::coerce (cl::nreverse res) 'string))))
+
+(cl::defun id-convert-and-export (name &rest kwargs)
+  (cl::multiple-value-bind (symbol package)
+      (cl::apply *swig-identifier-converter* name kwargs)
+    (cl::let ((args (cl::list (cl::if (cl::consp symbol)
+    	     	    	         (cl::cadr symbol) symbol)
+                      (cl::or package cl::*package*))))
+      (cl::apply #'cl::export args)
+      (cl::pushnew args *swig-export-list*))
+    symbol))
+
+(cl::defmacro swig-insert-id (name namespace &key (type :type) class)
+  `(cl::let ((cl::*package* (cl::find-package ,(package-name-for-namespace namespace))))
+    (id-convert-and-export ,name :type ,type :class ,class)))
+
+(defswig2 swig-defconstant (string value)
+  (cl::let ((symbol (id-convert-and-export string :type :constant)))
+    `(cl::eval-when (compile load eval)
+       (cl::defconstant ,symbol ,value))))
+
+(cl::defun maybe-reorder-args (funcname arglist)
+  ;; in the foreign setter function the new value will be the last argument
+  ;; in Lisp it needs to be the first
+  (cl::if (cl::consp funcname)
+      (cl::append (cl::last arglist) (cl::butlast arglist))
+      arglist))
+
+(cl::defun maybe-return-value (funcname arglist)
+  ;; setf functions should return the new value
+  (cl::when (cl::consp funcname)
+    `(,(cl::if (cl::consp (cl::car arglist))
+           (cl::caar arglist)
+           (cl::car arglist)))))
+
+(cl::defun swig-anyvarargs-p (arglist)
+  (cl::member :SWIG__varargs_ arglist))
+
+(defswig1 swig-defun ((name &optional (mangled-name name)
+                            &key (type :operator) class arity)
+                      arglist kwargs
+		      &body body)
+  (cl::let* ((symbol (id-convert-and-export name :type type
+                          :arity arity :class class))
+             (mangle (excl::if* (cl::string-equal name mangled-name)
+                      then (id-convert-and-export 
+				    (cl::cond
+					  ((cl::eq type :setter) (cl::format nil "~A-set" name))
+					  ((cl::eq type :getter) (cl::format nil "~A-get" name))
+					  (t name))
+				    :type :ff-operator :arity arity :class class)
+                      else (cl::intern mangled-name)))
+         (defun-args (maybe-reorder-args
+                      symbol
+		      (cl::mapcar #'cl::car (cl::and (cl::not (cl::equal arglist '(:void)))
+					 (cl::loop as i in arglist
+					       when (cl::eq (cl::car i) :p+)
+					       collect (cl::cdr i))))))
+	 (ffargs (cl::if (cl::equal arglist '(:void))
+	 	      arglist
+		    (cl::mapcar #'cl::cdr arglist)))
+	 )
+    (cl::when (swig-anyvarargs-p ffargs)
+      (cl::setq ffargs '()))
+    `(cl::eval-when (compile load eval)
+       (excl::compiler-let ((*record-xref-info* nil))
+         (ff:def-foreign-call (,mangle ,mangled-name) ,ffargs ,@kwargs))
+       (cl::macrolet ((swig-ff-call (&rest args)
+                      (cl::cons ',mangle args)))
+         (cl::defun ,symbol ,defun-args
+           ,@body
+           ,@(maybe-return-value symbol defun-args))))))
+
+(defswig1 swig-defmethod ((name &optional (mangled-name name)
+	  	                &key (type :operator) class arity)
+                          ffargs kwargs
+                          &body body)
+  (cl::let* ((symbol (id-convert-and-export name :type type
+                          :arity arity :class class))
+         (mangle (cl::intern mangled-name))
+         (defmethod-args (maybe-reorder-args
+                          symbol
+                          (cl::unless (cl::equal ffargs '(:void))
+                            (cl::loop for (lisparg name dispatch) in ffargs
+			    	  when (eq lisparg :p+)
+                                  collect `(,name ,dispatch)))))
+         (ffargs (cl::if (cl::equal ffargs '(:void))
+                     ffargs
+                     (cl::loop for (nil name nil . ffi) in ffargs
+                           collect `(,name ,@ffi)))))
+    `(cl::eval-when (compile load eval)
+       (excl::compiler-let ((*record-xref-info* nil))
+         (ff:def-foreign-call (,mangle ,mangled-name) ,ffargs ,@kwargs))
+       (cl::macrolet ((swig-ff-call (&rest args)
+                      (cl::cons ',mangle args)))
+         (cl::defmethod ,symbol ,defmethod-args
+           ,@body
+           ,@(maybe-return-value symbol defmethod-args))))))
+
+(defswig1 swig-dispatcher ((name &key (type :operator) class arities))
+  (cl::let ((symbol (id-convert-and-export name
+                         :type type :class class)))
+    `(cl::eval-when (compile load eval)
+       (cl::defun ,symbol (&rest args)
+         (cl::case (cl::length args)
+           ,@(cl::loop for arity in arities
+                   for symbol-n = (id-convert-and-export name
+                                           :type type :class class :arity arity)
+                   collect `(,arity (cl::apply #',symbol-n args)))
+	   (t (cl::error "No applicable wrapper-methods for foreign call ~a with args ~a of classes ~a" ',symbol args (cl::mapcar #'(cl::lambda (x) (cl::class-name (cl::class-of x))) args)))
+	   )))))
+
+(defswig2 swig-def-foreign-stub (name)
+  (cl::let ((lsymbol (id-convert-and-export name :type :class))
+	    (symbol (id-convert-and-export name :type :type)))
+    `(cl::eval-when (compile load eval)
+	(ff:def-foreign-type ,symbol (:class ))
+	(cl::defclass ,lsymbol (ff:foreign-pointer) ()))))
+
+(defswig2 swig-def-foreign-class (name supers &rest rest)
+  (cl::let ((lsymbol (id-convert-and-export name :type :class))
+	    (symbol (id-convert-and-export name :type :type)))
+    `(cl::eval-when (compile load eval)
+       (ff:def-foreign-type ,symbol ,@rest)
+       (cl::defclass ,lsymbol ,supers
+	 ((foreign-type :initform ',symbol :initarg :foreign-type
+			:accessor foreign-pointer-type))))))
+
+(defswig2 swig-def-foreign-type (name &rest rest)
+  (cl::let ((symbol (id-convert-and-export name :type :type)))
+    `(cl::eval-when (compile load eval)
+       (ff:def-foreign-type ,symbol ,@rest))))
+
+(defswig2 swig-def-synonym-type (synonym of ff-synonym)
+  `(cl::eval-when (compile load eval)
+     (cl::setf (cl::find-class ',synonym) (cl::find-class ',of))
+     (ff:def-foreign-type ,ff-synonym (:struct ))))
+
+(cl::defun package-name-for-namespace (namespace)
+  (excl::list-to-delimited-string
+   (cl::cons *swig-module-name*
+         (cl::mapcar #'(cl::lambda (name)
+                     (cl::string
+                      (cl::funcall *swig-identifier-converter*
+                               name
+                               :type :namespace)))
+                 namespace))
+   "."))
+
+(cl::defmacro swig-defpackage (namespace)
+  (cl::let* ((parent-namespaces (cl::maplist #'cl::reverse (cl::cdr (cl::reverse namespace))))
+             (parent-strings (cl::mapcar #'package-name-for-namespace
+                                 parent-namespaces))
+             (string (package-name-for-namespace namespace)))
+    `(cl::eval-when (compile load eval)
+      (cl::defpackage ,string
+        (:use :swig :ff #+ignore '(:common-lisp :ff :excl)
+              ,@parent-strings ,*swig-module-name*)
+	(:import-from :cl :* :nil :t)))))
+
+(cl::defmacro swig-in-package (namespace)
+  `(cl::eval-when (compile load eval)
+    (cl::in-package ,(package-name-for-namespace namespace))))
+
+(defswig2 swig-defvar (name mangled-name &key type (ftype :unsigned-natural))
+  (cl::let ((symbol (id-convert-and-export name :type type)))
+    `(cl::eval-when (compile load eval)
+      (ff:def-foreign-variable (,symbol ,mangled-name) :type ,ftype))))
+
+) ;; eval-when
+
+(cl::eval-when (compile eval)
+  (cl::flet ((starts-with-p (str prefix)
+              (cl::and (cl::>= (cl::length str) (cl::length prefix))
+                (cl::string= str prefix :end1 (cl::length prefix)))))
+    (cl::export (cl::loop for sym being each present-symbol of cl::*package*
+                  when (cl::or (starts-with-p (cl::symbol-name sym) (cl::symbol-name :swig-))
+                           (starts-with-p (cl::symbol-name sym) (cl::symbol-name :identifier-convert-)))
+                  collect sym))))
+
+%}
+
+
+
+%{
+
+#ifdef __cplusplus
+#  define EXTERN   extern "C"
+#else
+#  define EXTERN   extern
+#endif
+
+#define EXPORT   EXTERN SWIGEXPORT
+
+#include <string.h>
+#include <stdlib.h>
+%}
diff --git a/trunk/Lib/allegrocl/inout_typemaps.i b/trunk/Lib/allegrocl/inout_typemaps.i
new file mode 100755
index 0000000..d8d61fe
--- /dev/null
+++ b/trunk/Lib/allegrocl/inout_typemaps.i
@@ -0,0 +1,111 @@
+/* inout_typemaps.i
+
+   Support for INPUT, OUTPUT, and INOUT typemaps. OUTPUT variables are returned
+   as multiple values.
+
+*/
+
+
+/* Note that this macro automatically adds a pointer to the type passed in.
+   As a result, INOUT typemaps for char are for 'char *'. The definition
+   of typemaps for 'char' takes advantage of this, believing that it's more
+   likely to see an INOUT argument for strings, than a single char. */
+%define INOUT_TYPEMAP(type_, OUTresult_, INbind_)
+// OUTPUT map.
+%typemap(lin,numinputs=0) type_ *OUTPUT, type_ &OUTPUT
+%{(cl::let (($out (ff:allocate-fobject '$*in_fftype :c)))
+     $body
+     OUTresult_
+     (ff:free-fobject $out)) %}
+
+// INPUT map.
+%typemap(in) type_ *INPUT, type_ &INPUT
+%{ $1 = &$input; %}
+
+%typemap(ctype) type_ *INPUT, type_ &INPUT "$*1_ltype";
+
+
+// INOUT map.
+// careful here. the input string is converted to a C string
+// with length equal to the input string. This should be large
+// enough to contain whatever OUTPUT value will be stored in it.
+%typemap(lin,numinputs=1) type_ *INOUT, type_ &INOUT
+%{(cl::let (($out (ff:allocate-fobject '$*in_fftype :c)))
+     INbind_
+     $body
+     OUTresult_
+     (ff:free-fobject $out)) %}
+
+%enddef
+
+// $in, $out, $lclass,
+// $in_fftype, $*in_fftype
+
+INOUT_TYPEMAP(int,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(short,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(long,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(unsigned int,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(unsigned short,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(unsigned long,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+// char * mapping for passing strings. didn't quite work
+// INOUT_TYPEMAP(char,
+//              (cl::push (excl:native-to-string $out) ACL_result),
+//	      (cl::setf (ff:fslot-value-typed (cl::quote $in_fftype) :c $out)
+//		    (excl:string-to-native $in)))
+INOUT_TYPEMAP(float,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(double,
+	      (cl::push (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
+INOUT_TYPEMAP(bool,
+	      (cl::push (not (zerop (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out)))
+		    ACL_result),
+	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) (if $in 1 0)));
+
+%typemap(lisptype) bool *INPUT, bool &INPUT "boolean";
+
+// long long support not yet complete
+// INOUT_TYPEMAP(long long);
+// INOUT_TYPEMAP(unsigned long long);
+
+// char *OUTPUT map.
+// for this to work, swig needs to know how large an array to allocate.
+// you can fake this by 
+// %typemap(ffitype) char *myarg	"(:array :char 30)";
+// %apply char *OUTPUT { char *myarg };
+%typemap(lin,numinputs=0) char *OUTPUT, char &OUTPUT
+%{(cl::let (($out (ff:allocate-fobject '$*in_fftype :c)))
+     $body
+     (cl::push (excl:native-to-string $out) ACL_result)
+     (ff:free-fobject $out)) %}
+
+// char *INPUT map.
+%typemap(in) char *INPUT, char &INPUT
+%{ $1 = &$input; %}
+%typemap(ctype) char *INPUT, char &INPUT "$*1_ltype";
+
+// char *INOUT map.
+%typemap(lin,numinputs=1) char *INOUT, char &INOUT
+%{(cl::let (($out (excl:string-to-native $in)))
+     $body
+     (cl::push (excl:native-to-string $out) ACL_result)
+     (ff:free-fobject $out)) %}
+
+// uncomment this if you want INOUT mappings for chars instead of strings.
+// INOUT_TYPEMAP(char,
+// 	      (cl::push (code-char (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out))
+//		    ACL_result),
+//	      (cl::setf (ff:fslot-value-typed (cl::quote $*in_fftype) :c $out) $in));
diff --git a/trunk/Lib/allegrocl/longlongs.i b/trunk/Lib/allegrocl/longlongs.i
new file mode 100755
index 0000000..b887a8a
--- /dev/null
+++ b/trunk/Lib/allegrocl/longlongs.i
@@ -0,0 +1,36 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * longlongs.i
+ *
+ * Typemap addition for support of 'long long' type and 'unsigned long long 
+ * Makes use of swig-def-foreign-class, so this header should be loaded
+ * after allegrocl.swg and after any custom user identifier-conversion
+ * functions have been defined.
+ * ----------------------------------------------------------------------------- */
+
+%typemap(in) long long, unsigned long long "$1 = $input;";
+%typemap(out) long long, unsigned long long "$result = &$1;";
+
+%typemap(ffitype) long long "(:struct (l1 :long) (l2 :long))";
+%typemap(ffitype) unsigned long long "(:struct (l1 :unsigned-long)
+         (l2 :unsigned-long))";
+
+%typemap(lout) long long 
+"  (make-instance #.(swig-insert-id \"longlong\" () :type :class)
+                  :foreign-address $body)";
+%typemap(lout) unsigned long long
+"  (make-instance #.(swig-insert-id \"ulonglong\" () :type :class)
+                  :foreign-address $body)";
+
+%insert("lisphead") %{
+
+(swig-def-foreign-class "longlong"
+ (ff:foreign-pointer)
+ (:struct (:struct (l1 :long) (l2 :long))))
+
+(swig-def-foreign-class "ulonglong"
+ (ff:foreign-pointer)
+ (:struct (:struct (l1 :unsigned-long) (l2 :unsigned-long))))
+%}
diff --git a/trunk/Lib/allegrocl/std_list.i b/trunk/Lib/allegrocl/std_list.i
new file mode 100755
index 0000000..c8ab456
--- /dev/null
+++ b/trunk/Lib/allegrocl/std_list.i
@@ -0,0 +1,233 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_list.i
+ *
+ * SWIG typemaps for std::list types
+ * 
+ * To use, add:
+ * 
+ * %include "std_list.i"
+ *
+ * to your interface file. You will also need to include a template directive
+ * for each instance of the list container you want to use in your application.
+ * e.g.
+ * 
+ * %template (intlist) std::list<int>;
+ * %template (floatlist) std::list<float>;
+ * ----------------------------------------------------------------------------- */
+
+%module std_list
+%warnfilter(468) std::list;
+
+%{
+#include <list>
+#include <stdexcept>
+%}
+
+
+namespace std{
+    template<class T> class list
+    {
+    public:
+	     
+	typedef T &reference;
+	typedef const T& const_reference;
+	typedef T &iterator;
+	typedef const T& const_iterator; 
+	    
+	list();
+	list(unsigned int size, const T& value = T());
+	list(const list<T> &);
+
+	~list();
+	void assign(unsigned int n, const T& value);
+	void swap(list<T> &x);
+
+	const_reference front();
+	const_reference back();
+	const_iterator begin();
+	const_iterator end();
+	     
+	void resize(unsigned int n, T c = T());
+	bool empty() const;
+
+	void push_front(const T& INPUT);
+	void push_back(const T& INPUT);
+
+
+	void pop_front();
+	void pop_back();
+	void clear();
+	unsigned int size() const;
+	unsigned int max_size() const;
+	void resize(unsigned int n, const T& INPUT);
+		
+	void remove(const T& INPUT);
+	void unique();
+	void reverse();
+	void sort();
+
+	%extend 
+	    {
+	        %typemap(lout) T &__getitem__ "(cl::setq ACL_ffresult (ff:fslot-value-typed '$*out_fftype :c $body))";
+		%typemap(lout) T *__getitem__ "(cl::setq ACL_ffresult (make-instance '$lclass :foreign-address $body))";
+
+		const_reference __getitem__(int i) throw (std::out_of_range) 
+		    {
+			std::list<T>::iterator first = self->begin(); 
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (i>=0 && i<size)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    return *first;
+			}
+			else throw std::out_of_range("list index out of range");
+		    }
+		void __setitem__(int i, const T& INPUT) throw (std::out_of_range)
+		    {
+			std::list<T>::iterator first = self->begin(); 
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (i>=0 && i<size)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    *first = INPUT;
+			}
+			else throw std::out_of_range("list index out of range");
+		    }
+		void __delitem__(int i) throw (std::out_of_range)
+		    {
+			std::list<T>::iterator first = self->begin(); 
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (i>=0 && i<size)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    self->erase(first);
+			}
+			else throw std::out_of_range("list index out of range");
+		    }	     
+		std::list<T> __getslice__(int i,int j) 
+		    {
+			std::list<T>::iterator first = self->begin();
+			std::list<T>::iterator end = self->end();
+
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (j<0) j += size;
+			if (i<0) i = 0;
+			if (j>size) j = size;
+			if (i>=j) i=j;
+			if (i>=0 && i<size && j>=0)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    for (int m=0;m<j;m++)
+			    {
+				end++;
+			    }
+			    std::list<T> tmp(j-i);
+			    if (j>i) std::copy(first,end,tmp.begin());
+			    return tmp;
+			}
+			else throw std::out_of_range("list index out of range");
+		    }
+		void __delslice__(int i,int j) 
+		    {
+			std::list<T>::iterator first = self->begin();
+			std::list<T>::iterator end = self->end();
+
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (j<0) j += size;
+			if (i<0) i = 0;
+			if (j>size) j = size;
+	
+			for (int k=0;k<i;k++)
+			{
+			    first++;
+			}
+			for (int m=0;m<=j;m++)
+			{
+			    end++;
+			}		   
+			self->erase(first,end);		
+		    }
+		void __setslice__(int i,int j, const std::list<T>& v) 
+		    {
+			std::list<T>::iterator first = self->begin();
+			std::list<T>::iterator end = self->end();
+
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (j<0) j += size;
+			if (i<0) i = 0;
+			if (j>size) j = size;
+		
+			for (int k=0;k<i;k++)
+			{
+			    first++;
+			}
+			for (int m=0;m<=j;m++)
+			{
+			    end++;
+			}
+			if (int(v.size()) == j-i) 
+			{
+			    std::copy(v.begin(),v.end(),first);
+			}
+			else {
+			    self->erase(first,end);
+			    if (i+1 <= int(self->size())) 
+			    {
+				first = self->begin();
+				for (int k=0;k<i;k++)
+				{
+				    first++;
+				}
+				self->insert(first,v.begin(),v.end());
+			    }
+			    else self->insert(self->end(),v.begin(),v.end());
+			}
+			   	
+		    }
+		unsigned int __len__() 
+		    {
+			return self->size();
+		    }	
+		bool __nonzero__()
+		    {
+			return !(self->empty());
+		    }
+		void append(const T& INPUT)
+		    {
+			self->push_back(INPUT);
+		    }
+		void pop()
+		    {
+			self->pop_back();
+		    }
+	      
+	    };   
+    };
+}
+
+
+
+
+
+
diff --git a/trunk/Lib/allegrocl/std_string.i b/trunk/Lib/allegrocl/std_string.i
new file mode 100755
index 0000000..4da0148
--- /dev/null
+++ b/trunk/Lib/allegrocl/std_string.i
@@ -0,0 +1,218 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string
+ * ----------------------------------------------------------------------------- */
+
+// ------------------------------------------------------------------------
+// std::string is typemapped by value
+// This can prevent exporting methods which return a string
+// in order for the user to modify it.
+// However, I think I'll wait until someone asks for it...
+// ------------------------------------------------------------------------
+
+// %include <exception.i>
+%warnfilter(404) std::string;
+%warnfilter(404) std::wstring;
+
+%{
+#include <string>
+// #include <vector>
+// using std::vector;
+
+using std::string;
+
+
+%}
+
+// %include <std_vector.i>
+
+// %naturalvar std::string;
+// %naturalvar std::wstring;
+
+namespace std {
+    typedef unsigned long size_t;
+    typedef signed long ptrdiff_t;
+
+    template <class charT> class basic_string {
+    public:
+	typedef charT *pointer;
+	typedef charT &reference;
+	typedef const charT &const_reference;
+	typedef size_t size_type;
+	typedef ptrdiff_t difference_type;
+	basic_string();
+	basic_string( charT *str );
+	size_type size();
+	charT operator []( int pos ) const;
+	charT *c_str() const;
+	basic_string<charT> &operator = ( const basic_string &ws );
+	basic_string<charT> &operator = ( const charT *str );
+	basic_string<charT> &append( const basic_string<charT> &other );
+	basic_string<charT> &append( const charT *str );
+	void push_back( charT c );
+	void clear();
+	void reserve( size_type t );
+	void resize( size_type n, charT c = charT() );
+	int compare( const basic_string<charT> &other ) const;
+	int compare( const charT *str ) const;
+	basic_string<charT> &insert( size_type pos, 
+				     const basic_string<charT> &str );
+	size_type find( const basic_string<charT> &other, int pos = 0 ) const;
+	size_type find( charT c, int pos = 0 ) const;
+	%extend {
+	    bool operator == ( const basic_string<charT> &other ) const {
+		return self->compare( other ) == 0;
+	    }
+	    bool operator != ( const basic_string<charT> &other ) const {
+		return self->compare( other ) != 0;
+	    }
+	    bool operator < ( const basic_string<charT> &other ) const {
+		return self->compare( other ) == -1;
+	    }
+	    bool operator > ( const basic_string<charT> &other ) const {
+		return self->compare( other ) == 1;
+	    }
+	    bool operator <= ( const basic_string<charT> &other ) const {
+		return self->compare( other ) != 1;
+	    }
+	    bool operator >= ( const basic_string<charT> &other ) const {
+		return self->compare( other ) != -1;
+	    }
+
+	}
+    };
+
+    %template(string) basic_string<char>;
+    %template(wstring) basic_string<wchar_t>;
+
+    %apply char * { string };
+    %apply wchar_t * { wstring };
+
+    typedef basic_string<char> string;
+    typedef basic_string<wchar_t> wstring;
+
+    // automatically convert constant std::strings to cl:strings
+    %typemap(ctype) string "char *";
+    %typemap(in) string "$1.assign($input);";
+    %typemap(out) string "$result = (char *)(&$1)->c_str();";
+    %typemap(lisptype) string "cl:string";
+    %typemap(lout) string "(cl::setq ACL_ffresult $body)";
+
+    %typemap(ctype) const string *"char *";
+    %typemap(in) const string * "$1.assign($input);";
+    %typemap(out) const string * "$result = (char *)($1)->c_str();";
+    %typemap(lisptype) const string * "cl:string";
+    %typemap(lout) const string * "(cl::setq ACL_ffresult $body)";
+
+    %typemap(ctype) wstring "wchar_t *";
+    %typemap(in) wstring "$1.assign($input);";
+    %typemap(out) wstring "$result = (wchar_t *)(&$1)->c_str();";
+    %typemap(lisptype) wstring "cl:string";
+    %typemap(lout) wstring "(cl::setq ACL_ffresult (excl:native-to-string $body
+:external-format #+little-endian :fat-le #-little-endian :fat))";
+
+    %typemap(ctype) const wstring *"char *";
+    %typemap(in) const wstring * "$1.assign($input);";
+    %typemap(out) const wstring * "$result = (char *)($1)->c_str();";
+    %typemap(lisptype) const wstring * "cl:string";
+    %typemap(lout) const wstring * "(cl::setq ACL_ffresult $body)";
+
+    /* Overloading check */
+//     %typemap(in) string {
+//         if (caml_ptr_check($input))
+//             $1.assign((char *)caml_ptr_val($input,0),
+// 			 caml_string_len($input));
+//         else
+//             SWIG_exception(SWIG_TypeError, "string expected");
+//     }
+
+//     %typemap(in) const string & (std::string temp) {
+//         if (caml_ptr_check($input)) {
+//             temp.assign((char *)caml_ptr_val($input,0),
+// 			   caml_string_len($input));
+//             $1 = &temp;
+//         } else {
+//             SWIG_exception(SWIG_TypeError, "string expected");
+//         }
+//     }
+
+//     %typemap(in) string & (std::string temp) {
+//         if (caml_ptr_check($input)) {
+//             temp.assign((char *)caml_ptr_val($input,0),
+// 			   caml_string_len($input));
+//             $1 = &temp;
+//         } else {
+//             SWIG_exception(SWIG_TypeError, "string expected");
+//         }
+//     }
+
+//     %typemap(in) string * (std::string *temp) {
+//         if (caml_ptr_check($input)) {
+//             temp = new std::string((char *)caml_ptr_val($input,0),
+// 				   caml_string_len($input));
+//             $1 = temp;
+//         } else {
+//             SWIG_exception(SWIG_TypeError, "string expected");
+//         }
+//     }
+
+//     %typemap(free) string * (std::string *temp) {
+// 	delete temp;
+//     }
+
+//    %typemap(argout) string & {
+//	caml_list_append(swig_result,caml_val_string_len((*$1).c_str(),
+//							 (*$1).size()));
+//    }
+
+//    %typemap(directorout) string {
+//	$result.assign((char *)caml_ptr_val($input,0),
+//		       caml_string_len($input));
+//    }
+
+//    %typemap(out) string {
+//        $result = caml_val_string_len($1.c_str(),$1.size());
+//    }
+
+//    %typemap(out) string * {
+//	$result = caml_val_string_len((*$1).c_str(),(*$1).size());
+//    }
+}
+
+// #ifdef ENABLE_CHARPTR_ARRAY
+// char **c_charptr_array( const std::vector <string > &str_v );
+
+// %{
+//   SWIGEXT char **c_charptr_array( const std::vector <string > &str_v ) {
+//     char **out = new char *[str_v.size() + 1];
+//     out[str_v.size()] = 0;
+//     for( int i = 0; i < str_v.size(); i++ ) {
+//       out[i] = (char *)str_v[i].c_str();
+//     }
+//     return out;
+//   }
+// %}
+// #endif
+
+// #ifdef ENABLE_STRING_VECTOR
+// %template (StringVector) std::vector<string >;
+
+// %insert(ml) %{
+//   (* Some STL convenience items *)
+
+//   let string_array_to_vector sa = 
+//     let nv = _new_StringVector C_void in
+//       array_to_vector nv (fun x -> C_string x) sa ; nv
+	
+//   let c_string_array ar = 
+//     _c_charptr_array (string_array_to_vector ar)
+// %}
+
+// %insert(mli) %{
+//   val c_string_array: string array -> c_obj
+// %}
+// #endif
diff --git a/trunk/Lib/allegrocl/typemaps.i b/trunk/Lib/allegrocl/typemaps.i
new file mode 100644
index 0000000..293d1cd
--- /dev/null
+++ b/trunk/Lib/allegrocl/typemaps.i
@@ -0,0 +1,4 @@
+/* Unused for Allegro CL module */
+
+%include "inout_typemaps.i"
+%include "longlongs.i"
diff --git a/trunk/Lib/allkw.swg b/trunk/Lib/allkw.swg
new file mode 100644
index 0000000..dec6c7c
--- /dev/null
+++ b/trunk/Lib/allkw.swg
@@ -0,0 +1,31 @@
+#ifndef __Lib_allkw_swg__
+#define __Lib_allkw_swg__
+
+
+/*  
+  Include all the known keyword warnings.  Very useful for adding test
+  files to the test-suite, or check if your own library is ok for all
+  the swig supported languages.
+
+  Use as 
+
+    swig -Wallkw ...
+
+  If you add a new language, remember to create a separete languagekw.swg
+  file, and add it here.
+  
+*/
+
+%include <chicken/chickenkw.swg>
+%include <csharp/csharpkw.swg>
+%include <java/javakw.swg>
+%include <php4/php4kw.swg>
+%include <pike/pikekw.swg>
+%include <python/pythonkw.swg>
+%include <ocaml/ocamlkw.swg>
+%include <ruby/rubykw.swg>
+%include <tcl/tclkw.swg>
+%include <perl5/perlkw.swg>
+
+
+#endif //__Lib_allkw_swg__
diff --git a/trunk/Lib/attribute.i b/trunk/Lib/attribute.i
new file mode 100644
index 0000000..45c3c5b
--- /dev/null
+++ b/trunk/Lib/attribute.i
@@ -0,0 +1,24 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * attribute.i
+ *
+ * SWIG library file for implementing attributes.
+ * ----------------------------------------------------------------------------- */
+
+/* we use a simple exception warning here */
+%{
+#include <stdio.h>
+%}
+#define %attribute_exception(code,msg) printf("%s\n",msg)
+
+#ifndef %arg
+#define %arg(x) x
+#endif
+
+#ifndef %mangle
+#define %mangle(Type...)  #@Type
+#endif
+
+%include <typemaps/attribute.swg>
diff --git a/trunk/Lib/carrays.i b/trunk/Lib/carrays.i
new file mode 100644
index 0000000..738b457
--- /dev/null
+++ b/trunk/Lib/carrays.i
@@ -0,0 +1,120 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * carrays.i
+ *
+ * SWIG library file containing macros that can be used to manipulate simple
+ * pointers as arrays.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * %array_functions(TYPE,NAME)
+ *
+ * Generates functions for creating and accessing elements of a C array
+ * (as pointers).  Creates the following functions:
+ *
+ *        TYPE *new_NAME(int nelements)
+ *        void delete_NAME(TYPE *);
+ *        TYPE NAME_getitem(TYPE *, int index);
+ *        void NAME_setitem(TYPE *, int index, TYPE value);
+ * 
+ * ----------------------------------------------------------------------------- */
+
+%define %array_functions(TYPE,NAME)
+%{
+static TYPE *new_##NAME(int nelements) { %}
+#ifdef __cplusplus
+%{  return new TYPE[nelements]; %}
+#else
+%{  return (TYPE *) calloc(nelements,sizeof(TYPE)); %}
+#endif
+%{}
+
+static void delete_##NAME(TYPE *ary) { %}
+#ifdef __cplusplus
+%{  delete [] ary; %}
+#else
+%{  free(ary); %}
+#endif
+%{}
+
+static TYPE NAME##_getitem(TYPE *ary, int index) {
+    return ary[index];
+}
+static void NAME##_setitem(TYPE *ary, int index, TYPE value) {
+    ary[index] = value;
+}
+%}
+
+TYPE *new_##NAME(int nelements);
+void delete_##NAME(TYPE *ary);
+TYPE NAME##_getitem(TYPE *ary, int index);
+void NAME##_setitem(TYPE *ary, int index, TYPE value);
+
+%enddef
+
+
+/* -----------------------------------------------------------------------------
+ * %array_class(TYPE,NAME)
+ *
+ * Generates a class wrapper around a C array.  The class has the following
+ * interface:
+ *
+ *          struct NAME {
+ *              NAME(int nelements);
+ *             ~NAME();
+ *              TYPE getitem(int index);
+ *              void setitem(int index, TYPE value);
+ *              TYPE * cast();
+ *              static NAME *frompointer(TYPE *t);
+  *         }
+ *
+ * ----------------------------------------------------------------------------- */
+
+%define %array_class(TYPE,NAME)
+%{
+typedef TYPE NAME;
+%}
+typedef struct NAME {
+  /* Put language specific enhancements here */
+
+} NAME;
+
+%extend NAME {
+
+#ifdef __cplusplus
+NAME(int nelements) {
+  return new TYPE[nelements];
+}
+~NAME() {
+  delete [] self;
+}
+#else
+NAME(int nelements) {
+  return (TYPE *) calloc(nelements,sizeof(TYPE));
+}
+~NAME() {
+  free(self);
+}
+#endif
+
+TYPE getitem(int index) {
+  return self[index];
+}
+void setitem(int index, TYPE value) {
+  self[index] = value;
+}
+TYPE * cast() {
+  return self;
+}
+static NAME *frompointer(TYPE *t) {
+  return (NAME *) t;
+}
+
+};
+
+%types(NAME = TYPE);
+
+%enddef
+
diff --git a/trunk/Lib/cdata.i b/trunk/Lib/cdata.i
new file mode 100644
index 0000000..a9e74ed
--- /dev/null
+++ b/trunk/Lib/cdata.i
@@ -0,0 +1,82 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cdata.i
+ *
+ * SWIG library file containing macros for manipulating raw C data as strings.
+ * ----------------------------------------------------------------------------- */
+
+%{
+typedef struct SWIGCDATA {
+    char *data;
+    int   len;
+} SWIGCDATA;
+%}
+
+/* -----------------------------------------------------------------------------
+ * Typemaps for returning binary data
+ * ----------------------------------------------------------------------------- */
+
+#if SWIGGUILE
+%typemap(out) SWIGCDATA {
+   $result = gh_str2scm($1.data,$1.len);
+}
+%typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH);
+#elif SWIGCHICKEN
+%typemap(out) SWIGCDATA {
+  C_word *string_space = C_alloc(C_SIZEOF_STRING($1.len));
+  $result = C_string(&string_space, $1.len, $1.data);
+}
+%typemap(in) (const void *indata, int inlen) = (char *STRING, int LENGTH);
+#else
+%echo "cdata.i module not supported."
+#endif
+
+
+/* -----------------------------------------------------------------------------
+ * %cdata(TYPE [, NAME]) 
+ *
+ * Convert raw C data to a binary string.
+ * ----------------------------------------------------------------------------- */
+
+%define %cdata(TYPE,NAME...)
+
+%insert("header") {
+#if #NAME == ""
+static SWIGCDATA cdata_##TYPE(TYPE *ptr, int nelements) {
+#else
+static SWIGCDATA cdata_##NAME(TYPE *ptr, int nelements) {
+#endif
+   SWIGCDATA d;
+   d.data = (char *) ptr;
+#if #TYPE != "void"
+   d.len  = nelements*sizeof(TYPE);
+#else
+   d.len  = nelements;
+#endif
+   return d;
+}
+}
+
+%typemap(default) int nelements "$1 = 1;"
+
+#if #NAME == ""
+SWIGCDATA cdata_##TYPE(TYPE *ptr, int nelements);
+#else
+SWIGCDATA cdata_##NAME(TYPE *ptr, int nelements);
+#endif
+%enddef
+
+%typemap(default) int nelements;
+
+%rename(cdata) ::cdata_void(void *ptr, int nelements);
+
+%cdata(void);
+
+/* Memory move function */
+void memmove(void *data, const void *indata, int inlen);
+
+
+
+
diff --git a/trunk/Lib/cffi/cffi.swg b/trunk/Lib/cffi/cffi.swg
new file mode 100644
index 0000000..c832e00
--- /dev/null
+++ b/trunk/Lib/cffi/cffi.swg
@@ -0,0 +1,286 @@
+/* Define a C preprocessor symbol that can be used in interface files
+   to distinguish between the SWIG language modules. */ 
+
+#define SWIG_CFFI
+
+/* Typespecs for basic types. */
+
+%typemap(cin) void ":void";
+
+%typemap(cin) char ":char";
+%typemap(cin) char * ":string";
+%typemap(cin) unsigned char ":unsigned-char";
+%typemap(cin) signed char ":char";
+
+%typemap(cin) short ":short";
+%typemap(cin) signed short ":short";
+%typemap(cin) unsigned short ":unsigned-short";
+
+%typemap(cin) int ":int";
+%typemap(cin) signed int ":int";
+%typemap(cin) unsigned int ":unsigned-int";
+
+%typemap(cin) long ":long";
+%typemap(cin) signed long ":long";
+%typemap(cin) unsigned long ":unsigned-long";
+
+%typemap(cin) long long ":long-long";
+%typemap(cin) signed long long ":long-long";
+%typemap(cin) unsigned long long ":unsigned-long-long";
+
+%typemap(cin) float ":float";
+%typemap(cin) double ":double";
+%typemap(cin) SWIGTYPE ":pointer";
+
+%typemap(cout) void ":void";
+
+%typemap(cout) char ":char";
+%typemap(cout) char * ":string";
+%typemap(cout) unsigned char ":unsigned-char";
+%typemap(cout) signed char ":char";
+
+%typemap(cout) short ":short";
+%typemap(cout) signed short ":short";
+%typemap(cout) unsigned short ":unsigned-short";
+
+%typemap(cout) int ":int";
+%typemap(cout) signed int ":int";
+%typemap(cout) unsigned int ":unsigned-int";
+
+%typemap(cout) long ":long";
+%typemap(cout) signed long ":long";
+%typemap(cout) unsigned long ":unsigned-long";
+
+%typemap(cout) long long ":long-long";
+%typemap(cout) signed long long ":long-long";
+%typemap(cout) unsigned long long ":unsigned-long-long";
+
+%typemap(cout) float ":float";
+%typemap(cout) double ":double";
+%typemap(cout) SWIGTYPE ":pointer";
+
+
+%typemap(ctype) bool                       "int";
+%typemap(ctype) char, unsigned char, signed char,
+                short, signed short, unsigned short,
+                int, signed int, unsigned int,
+                long, signed long, unsigned long,
+                float, double, long double, char *, void *, void,
+                enum SWIGTYPE, SWIGTYPE *,
+                SWIGTYPE[ANY], SWIGTYPE &  "$1_ltype";
+%typemap(ctype) SWIGTYPE                   "$&1_type";
+
+%typemap(in) bool                          "$1 = (bool)$input;";
+%typemap(in) char, unsigned char, signed char,
+             short, signed short, unsigned short,
+             int, signed int, unsigned int,
+             long, signed long, unsigned long,
+             float, double, long double, char *, void *, void,
+             enum SWIGTYPE, SWIGTYPE *,
+             SWIGTYPE[ANY], SWIGTYPE &     "$1 = $input;";
+%typemap(in) SWIGTYPE                      "$1 = *$input;";
+
+%typemap(out) void                         "";
+%typemap(out) bool                          "$result = (int)$1;";
+%typemap(out) char, unsigned char, signed char,
+              short, signed short, unsigned short,
+              int, signed int, unsigned int,
+              long, signed long, unsigned long,
+              float, double, long double, char *, void *,
+              enum SWIGTYPE, SWIGTYPE *,
+              SWIGTYPE[ANY], SWIGTYPE &    "$result = $1;";
+#ifdef __cplusplus
+%typemap(out) SWIGTYPE                     "$result = new $1_type($1);";
+#else
+%typemap(out) SWIGTYPE {
+  $result = ($&1_ltype) malloc(sizeof($1_type));
+  memmove($result, &$1, sizeof($1_type));
+}
+#endif
+
+%typecheck(SWIG_TYPECHECK_BOOL) bool { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_CHAR) char { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_FLOAT) float { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_DOUBLE) double { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_STRING) char * { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_INTEGER)
+                    unsigned char, signed char,
+                    short, signed short, unsigned short,
+                    int, signed int, unsigned int,
+                    long, signed long, unsigned long,
+                    enum SWIGTYPE { $1 = 1; };
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &,
+                                   SWIGTYPE[ANY], SWIGTYPE { $1 = 1; };
+/* This maps C/C++ types to Lisp classes for overload dispatch */
+
+%typemap(lisptype) bool "cl:boolean";
+%typemap(lisptype) char "cl:character";
+%typemap(lisptype) unsigned char "cl:integer";
+%typemap(lisptype) signed char "cl:integer";
+
+%typemap(lispclass) bool "t";
+%typemap(lispclass) char "cl:character";
+%typemap(lispclass) unsigned char, signed char,
+                    short, signed short, unsigned short,
+                    int, signed int, unsigned int,
+                    long, signed long, unsigned long,
+                    enum SWIGTYPE       "cl:integer";
+/* CLOS methods can't be specialized on single-float or double-float */
+%typemap(lispclass) float "cl:number";
+%typemap(lispclass) double "cl:number";
+%typemap(lispclass) char * "cl:string";
+
+
+%{
+
+#ifdef __cplusplus
+#  define EXTERN   extern "C"
+#else
+#  define EXTERN   extern
+#endif
+
+#define EXPORT   EXTERN SWIGEXPORT
+
+#include <string.h>
+%}
+
+%insert("swiglisp") %{
+;;;SWIG wrapper code starts here
+
+(cl:defmacro defanonenum (&body enums)
+   "Converts anonymous enums to defconstants."
+  `(cl:progn ,@(cl:loop for value in enums
+                        for index = 0 then (cl:1+ index)
+                        when (cl:listp value) do (cl:setf index (cl:second value)
+                                                          value (cl:first value))
+                        collect `(cl:defconstant ,value ,index))))
+
+(cl:eval-when (:compile-toplevel :load-toplevel)
+  (cl:unless (cl:fboundp 'swig-lispify)
+    (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*))
+      (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst)))
+                    (cl:cond
+                      ((cl:null lst)
+                       rest)
+                      ((cl:upper-case-p c)
+                       (helper (cl:cdr lst) 'upper
+                               (cl:case last
+                                 ((lower digit) (cl:list* c #\- rest))
+                                 (cl:t (cl:cons c rest)))))
+                      ((cl:lower-case-p c)
+                       (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest)))
+                      ((cl:digit-char-p c)
+                       (helper (cl:cdr lst) 'digit 
+                               (cl:case last
+                                 ((upper lower) (cl:list* c #\- rest))
+                                 (cl:t (cl:cons c rest)))))
+                      ((cl:char-equal c #\_)
+                       (helper (cl:cdr lst) '_ (cl:cons #\- rest)))
+                      (cl:t
+                       (cl:error "Invalid character: ~A" c)))))
+        (cl:let ((fix (cl:case flag
+                        ((constant enumvalue) "+")
+                        (variable "*")
+                        (cl:t ""))))
+          (cl:intern
+           (cl:concatenate
+            'cl:string
+            fix
+            (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
+            fix)
+           package))))))
+
+;;;SWIG wrapper code ends here
+%}
+
+#ifdef __cplusplus
+%typemap(out) SWIGTYPE                     "$result = new $1_type($1);";
+#else
+%typemap(out) SWIGTYPE {
+  $result = ($&1_ltype) malloc(sizeof($1_type));
+  memmove($result, &$1, sizeof($1_type));
+}
+#endif
+
+//////////////////////////////////////////////////////////////
+
+/* name conversion for overloaded operators. */
+#ifdef __cplusplus
+%rename(__add__)	     *::operator+;
+%rename(__pos__)	     *::operator+();
+%rename(__pos__)	     *::operator+() const;
+
+%rename(__sub__)	     *::operator-;
+%rename(__neg__)	     *::operator-() const;
+%rename(__neg__)	     *::operator-();
+
+%rename(__mul__)	     *::operator*;
+%rename(__deref__)	     *::operator*();
+%rename(__deref__)	     *::operator*() const;
+
+%rename(__div__)	     *::operator/;
+%rename(__mod__)	     *::operator%;
+%rename(__logxor__)	     *::operator^;
+%rename(__logand__)	     *::operator&;
+%rename(__logior__)	     *::operator|;
+%rename(__lognot__)	     *::operator~();
+%rename(__lognot__)	     *::operator~() const;
+
+%rename(__not__)	     *::operator!();
+%rename(__not__)	     *::operator!() const;
+
+%rename(__assign__)	     *::operator=;
+
+%rename(__add_assign__)      *::operator+=;
+%rename(__sub_assign__)	     *::operator-=;
+%rename(__mul_assign__)	     *::operator*=;
+%rename(__div_assign__)	     *::operator/=;
+%rename(__mod_assign__)	     *::operator%=;
+%rename(__logxor_assign__)   *::operator^=;
+%rename(__logand_assign__)   *::operator&=;
+%rename(__logior_assign__)   *::operator|=;
+
+%rename(__lshift__)	     *::operator<<;
+%rename(__lshift_assign__)   *::operator<<=;
+%rename(__rshift__)	     *::operator>>;
+%rename(__rshift_assign__)   *::operator>>=;
+
+%rename(__eq__)		     *::operator==;
+%rename(__ne__)		     *::operator!=;
+%rename(__lt__)		     *::operator<;
+%rename(__gt__)		     *::operator>;
+%rename(__lte__)	     *::operator<=;
+%rename(__gte__)	     *::operator>=;
+
+%rename(__and__)	     *::operator&&;
+%rename(__or__)		     *::operator||;
+
+%rename(__preincr__)	     *::operator++();
+%rename(__postincr__)	     *::operator++(int);
+%rename(__predecr__)	     *::operator--();
+%rename(__postdecr__)	     *::operator--(int);
+
+%rename(__comma__)	     *::operator,();
+%rename(__comma__)	     *::operator,() const;
+
+%rename(__member_ref__)      *::operator->;
+%rename(__member_func_ref__) *::operator->*;
+
+%rename(__funcall__)	     *::operator();
+%rename(__aref__)	     *::operator[];
+#endif
+
+
+%{
+
+#ifdef __cplusplus
+#  define EXTERN   extern "C"
+#else
+#  define EXTERN   extern
+#endif
+
+#define EXPORT   EXTERN SWIGEXPORT
+
+#include <string.h>
+#include <stdlib.h>
+%}
diff --git a/trunk/Lib/chicken/chicken.swg b/trunk/Lib/chicken/chicken.swg
new file mode 100644
index 0000000..d8b7187
--- /dev/null
+++ b/trunk/Lib/chicken/chicken.swg
@@ -0,0 +1,773 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * chicken.swg
+ *
+ * CHICKEN configuration module.
+ * ----------------------------------------------------------------------------- */
+
+/* chicken.h has to appear first. */
+
+%insert(runtime) %{
+#include <chicken.h>
+%}
+
+%insert(runtime) "swigrun.swg";            // Common C API type-checking code
+%insert(runtime) "chickenrun.swg";      // CHICKEN run-time code
+
+/* -----------------------------------------------------------------------------
+ *                          standard typemaps
+ * ----------------------------------------------------------------------------- */
+
+/*
+  CHICKEN: C
+  ----------
+
+  fixnum: int, short, unsigned int, unsigned short, unsigned char,
+  signed char
+
+  char: char
+
+  bool: bool
+
+  flonum: float, double, long, long long, unsigned long, unsigned long
+  long
+ */
+
+/* --- Primitive types --- */
+
+%define SIMPLE_TYPEMAP(type_, from_scheme, to_scheme, checker, convtype, storage_)
+
+%typemap(in) type_ 
+%{  if (!checker ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'type_'");
+  }
+  $1 = ($1_ltype) from_scheme ($input); %}
+
+/* Const primitive references.  Passed by value */
+
+%typemap(in) const type_ & ($*1_ltype temp)
+%{  if (!checker ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'type_'");
+  }
+  temp = ($*1_ltype) from_scheme ($input); 
+  $1 = &temp; %}
+
+/* --- Variable input --- */
+%typemap(varin) type_
+%{  if (!checker ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Cannot use '$1_ltype' for variable '$name' of type 'type_'");
+  }
+  $1 = ($1_ltype) from_scheme ($input); %}
+
+#if "storage_" == "0"
+
+%typemap(out) type_ 
+%{
+  $result = to_scheme (convtype ($1));
+%}
+
+/* References to primitive types.  Return by value */
+
+%typemap(out) const type_ &
+%{
+  $result = to_scheme (convtype (*$1));
+%}
+
+/* --- Variable output --- */
+%typemap(varout) type_ 
+%{
+  $result = to_scheme (convtype ($varname));
+%}
+
+%typemap(throws) type_
+%{
+  SWIG_Chicken_ThrowException(to_scheme ( convtype ($1)));
+%}
+
+#else
+
+%typemap(out) type_ 
+%{
+  {
+  C_word *space = C_alloc(storage_);
+  $result = to_scheme (&space, convtype ($1));
+  }
+%}
+
+/* References to primitive types.  Return by value */
+
+%typemap(out) const type_ &
+%{
+  {
+  C_word *space = C_alloc(storage_);
+  $result = to_scheme (&space, convtype (*$1));
+  }
+%}
+
+/* --- Variable output --- */
+%typemap(varout) type_ 
+%{
+  {
+  C_word *space = C_alloc(storage_);
+  $result = to_scheme (&space, convtype ($varname));
+  }
+%}
+
+%typemap(throws) type_
+%{
+  {
+  C_word *space = C_alloc(storage_);
+  SWIG_Chicken_ThrowException(to_scheme (&space, convtype ($1)));
+  }
+%}
+
+#endif
+
+/* --- Constants --- */
+
+%typemap(constcode) type_
+"static const $1_type $result = $value;"
+
+%enddef
+
+SIMPLE_TYPEMAP(int, C_num_to_int, C_fix, C_swig_is_number, (int), 0);
+//SIMPLE_TYPEMAP(enum SWIGTYPE, C_unfix, C_fix, C_swig_is_fixnum, (int), 0);
+SIMPLE_TYPEMAP(short, C_num_to_int, C_fix, C_swig_is_number, (int), 0);
+SIMPLE_TYPEMAP(long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM);
+SIMPLE_TYPEMAP(long long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM);
+SIMPLE_TYPEMAP(unsigned int, C_num_to_unsigned_int, C_unsigned_int_to_num, C_swig_is_number, (unsigned int), C_SIZEOF_FLONUM);
+SIMPLE_TYPEMAP(unsigned short, C_num_to_unsigned_int, C_fix, C_swig_is_number, (unsigned int), 0);
+SIMPLE_TYPEMAP(unsigned long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM);
+SIMPLE_TYPEMAP(unsigned long long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM);
+SIMPLE_TYPEMAP(unsigned char, C_character_code, C_make_character, C_swig_is_char, (unsigned int), 0);
+SIMPLE_TYPEMAP(signed char, C_character_code, C_make_character, C_swig_is_char, (int), 0);
+SIMPLE_TYPEMAP(char, C_character_code, C_make_character, C_swig_is_char, (char), 0);
+SIMPLE_TYPEMAP(bool, C_truep, C_mk_bool, C_swig_is_bool, (bool), 0);
+SIMPLE_TYPEMAP(float, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM);
+SIMPLE_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM);
+
+/* enum SWIGTYPE */
+%apply int { enum SWIGTYPE };
+%apply const int& { const enum SWIGTYPE& };
+
+%typemap(varin) enum SWIGTYPE
+{
+  if (!C_swig_is_fixnum($input) && sizeof(int) != sizeof($1)) {
+    swig_barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, "enum variable '$name' can not be set");
+  }
+  *((int *)(void *)&$1) = C_unfix($input);
+}
+
+
+/* --- Input arguments --- */
+
+/* Strings */
+
+%typemap(in) char * 
+{ if ($input == C_SCHEME_FALSE) {
+  $1 = NULL;
+ }
+ else { 
+   if (!C_swig_is_string ($input)) {
+     swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'char *'");
+   }
+   $1 = ($ltype) SWIG_MakeString ($input);
+ }
+}
+
+%typemap(freearg) char * "if ($1 != NULL) { free ($1); }"
+
+/* Pointers, references, and arrays */
+%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE *, SWIGTYPE [], SWIGTYPE &  {
+   $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, $disown);
+}
+
+%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE *DISOWN {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, SWIG_POINTER_DISOWN);
+}
+
+/* Void pointer.  Accepts any kind of pointer */
+%typemap(in) void * {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, NULL, $argnum, 0);
+}
+
+%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE * {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, SWIG_POINTER_DISOWN);
+}
+
+%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE & {
+  $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0));
+}
+
+%typemap(varin) SWIGTYPE [] {
+  SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, "Type error");
+}
+
+%typemap(varin) SWIGTYPE [ANY] {
+  void *temp;
+  int ii;
+  $1_basetype *b = 0;
+  temp = SWIG_MustGetPtr($input, $1_descriptor, 1, 0);
+  b = ($1_basetype *) $1;
+  for (ii = 0; ii < $1_size; ii++) b[ii] = *(($1_basetype *) temp + ii);
+}
+
+%typemap(varin) void * {
+  $1 = SWIG_MustGetPtr($input, NULL, 1, 0);
+}
+
+%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  $result = SWIG_NewPointerObj($1, $descriptor, $owner);
+}
+
+%typemap(out) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor,(void **) &$1);
+  $result = SWIG_NewPointerObj($1, ty, $owner);
+}
+    
+%typemap(varout) SWIGTYPE *, SWIGTYPE [] {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  $result = SWIG_NewPointerObj($varname, $descriptor, 0);
+}
+
+%typemap(varout) SWIGTYPE & {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  $result = SWIG_NewPointerObj((void *) &$varname, $1_descriptor, 0);
+}
+
+/* special typemaps for class pointers */
+%typemap(in) SWIGTYPE (CLASS::*) {
+  char err_msg[256];
+
+  if (C_swig_is_pair($input)) {
+    /* try and convert pointer object */
+    void *result;
+    if (!SWIG_ConvertPtr(C_block_item($input,1), &result, $descriptor, 0)) {
+      C_word ptr = C_block_item($input,0);
+      if (C_swig_is_string(ptr)) {
+        SWIG_UnpackData(C_c_string(ptr), (void *) &$1, sizeof($type));
+      } else {
+        snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", $argnum, ($descriptor->str ? $descriptor->str : $descriptor->name));
+        SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+      }
+    } else {
+      snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", $argnum, ($descriptor->str ? $descriptor->str : $descriptor->name));
+      SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+    }
+  } else {
+    snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", $argnum, ($descriptor->str ? $descriptor->str : $descriptor->name));
+    SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+  }
+}
+
+%typemap(out) SWIGTYPE (CLASS::*) {
+  size_t ptr_size = sizeof($type);
+  C_word *known_space = C_alloc(C_SIZEOF_PAIR + C_SIZEOF_STRING(2*ptr_size) + C_SIZEOF_SWIG_POINTER);
+  char *temp = (char *)malloc(2*ptr_size);
+  C_word ptr = SWIG_NewPointerObj((void *) known_space, $descriptor, 0);
+
+  SWIG_PackData(temp, (void *) &$1, ptr_size);
+  $result = C_pair(&known_space, C_string(&known_space, 2*ptr_size, temp), ptr);
+  free(temp);
+}
+
+%typemap(varin) SWIGTYPE (CLASS::*) {
+  char err_msg[256];
+
+  if (C_swig_is_pair($input)) {
+    /* try and convert pointer object */
+    void *result;
+    if (!SWIG_ConvertPtr(C_block_item($input,1), &result, $descriptor, 0)) {
+      C_word ptr = C_block_item($input,0);
+      if (C_swig_is_string(ptr)) {
+        SWIG_UnpackData(C_c_string(ptr), (void *) &$1, sizeof($type));
+      } else {
+        snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", 1, ($descriptor->str ? $descriptor->str : $descriptor->name));
+        SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+      }
+    } else {
+      snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", 1, ($descriptor->str ? $descriptor->str : $descriptor->name));
+      SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+    }
+  } else {
+    snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", 1, ($descriptor->str ? $descriptor->str : $descriptor->name));
+    SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+  }
+}
+
+%typemap(varout) SWIGTYPE (CLASS::*) {
+  size_t ptr_size = sizeof($type);
+  C_word *known_space = C_alloc(C_SIZEOF_PAIR + C_SIZEOF_STRING(2*ptr_size) + C_SIZEOF_SWIG_POINTER);
+  char *temp = (char *)malloc(2*ptr_size);
+  C_word ptr = SWIG_NewPointerObj((void *) known_space, $descriptor, 0);
+
+  SWIG_PackData(temp, (void *) &$varname, ptr_size);
+  $result = C_pair(&known_space, C_string(&known_space, 2*ptr_size, temp), ptr);
+  free(temp);
+}
+
+  
+
+/* Pass-by-value */
+
+%typemap(in,closcode="(slot-ref $input 'swig-this)") SWIGTYPE($&1_ltype argp) {
+  argp = ($&1_ltype)SWIG_MustGetPtr($input, $&1_descriptor, $argnum, 0);
+  $1 = *argp;
+}
+
+%typemap(varin,closcode="(slot-ref $input 'swig-this)") SWIGTYPE {
+  $&1_ltype argp;
+  argp = ($&1_ltype)SWIG_MustGetPtr($input, $&1_descriptor, 1, 0);
+  $1 = *argp;
+}
+
+%typemap(out) SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  resultptr = new $1_ltype((const $1_ltype &) $1);
+  $result =  SWIG_NewPointerObj(resultptr, $&1_descriptor, 1);
+} 
+#else
+{
+  $&1_ltype resultptr;
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 1);
+}
+#endif
+
+%typemap(varout) SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  resultptr = new $1_ltype((const $1_ltype&) $1);
+  $result =  SWIG_NewPointerObj(resultptr, $&1_descriptor, 0);
+} 
+#else
+{
+  $&1_ltype resultptr;
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 0);
+}
+#endif
+
+/* --- Output values --- */
+
+/* Strings */
+
+%typemap(out) 
+  char *
+{ char *s = (char*) $1;
+  if ($1 == NULL) {
+    $result = C_SCHEME_FALSE;
+  } 
+  else {
+    int string_len = strlen ((char *) ($1));
+    C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len));
+    $result = C_string (&string_space, string_len, s);
+  }
+}
+
+%typemap(varout) 
+  char *
+{ char *s = (char*) $varname;
+  if ($varname == NULL) {
+    $result = C_SCHEME_FALSE;
+  } 
+  else {
+    int string_len = strlen ($varname);
+    C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len));
+    $result = C_string (&string_space, string_len, s);
+  }
+}
+
+%typemap(throws) char *
+{ 
+  if ($1 == NULL) {
+    SWIG_Chicken_ThrowException(C_SCHEME_FALSE);
+  } else {
+    int string_len = strlen($1);
+    C_word *string_space = C_alloc(C_SIZEOF_STRING(string_len));
+    SWIG_Chicken_ThrowException(C_string(&string_space, string_len, (char *) $1));
+  }
+}
+
+/* Void */
+%typemap(out) void
+%{
+$result = C_SCHEME_UNDEFINED;
+%}
+
+/* Special typemap for character array return values */
+
+%typemap(out) 
+  char [ANY], const char [ANY] 
+%{ if ($1 == NULL) {
+  $result = C_SCHEME_FALSE;
+ }
+ else {
+   const int string_len = strlen ($1);
+   C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len));
+   $result = C_string (&string_space, string_len, $1);
+ } %}
+
+/* Primitive types--return by value */
+
+/* --- Variable input --- */
+
+/* A string */
+#ifdef __cplusplus
+%typemap(varin) char * {
+  if ($input == C_SCHEME_FALSE) {
+    $1 = NULL;
+  }
+  else if (!C_swig_is_string ($input)) {
+      swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'");
+  }
+  else {
+    char *temp = C_c_string ($input);
+    int  len   = C_header_size ($input);
+    if ($1) delete [] $1;
+    $1 = ($type) new char[len+1];
+    strncpy((char*)$1, temp, len);
+    ((char*)$1) [len] = 0;
+  }
+}
+%typemap(varin,warning="451:Setting const char * variable may leak memory") const char * {
+  if ($input == C_SCHEME_FALSE) {
+    $1 = NULL;
+  }
+  else if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'");
+  }
+  else {
+    char *temp = C_c_string ($input);
+    int  len   = C_header_size ($input);
+    $1 = ($type) new char[len+1];
+    strncpy((char*)$1,temp,len);
+    ((char*)$1) [len] = 0;
+  }
+}
+#else
+%typemap(varin) char * {
+  if ($input == C_SCHEME_FALSE) {
+    $1 = NULL;
+  }
+  else if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'");
+  }
+  else {
+    char *temp = C_c_string ($input);
+    int  len   = C_header_size ($input);
+    if ($1) free((char*) $1);
+    $1 = ($type) malloc(len+1);
+    strncpy((char*)$1,temp,len);
+    ((char*)$1) [len] = 0;
+  }
+}
+%typemap(varin,warning="451:Setting const char * variable may leak memory") const char * {
+  if ($input == C_SCHEME_FALSE) {
+    $1 = NULL;
+  }
+  else if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'");
+  }
+  else {
+    char *temp = C_c_string ($input);
+    int  len   = C_header_size ($input);
+    $1 = ($type) malloc(len+1);
+    strncpy((char*)$1,temp,len);
+    ((char*)$1) [len] = 0;
+  }
+}
+#endif
+
+%typemap(varin) char [] {
+  swig_barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, "C/C++ variable '$name' is read-only");
+}
+
+/* Special case for string array variables */
+%typemap(varin) char [ANY] {
+  if ($input == C_SCHEME_FALSE) {
+    memset($1,0,$1_dim0*sizeof(char));
+  }
+  else if (!C_swig_is_string ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "C variable '$name ($1_ltype)'");
+  }
+  else {
+    char *temp = C_c_string ($input);
+    strncpy($1,temp,$1_dim0*sizeof(char));
+  }
+}
+
+/* --- Variable output --- */
+
+/* Void */
+%typemap(varout) void "$result = C_SCHEME_UNDEFINED;";
+
+/* Special typemap for character array return values */
+%typemap(varout) char [ANY], const char [ANY] 
+%{  if ($varname == NULL) {
+    $result = C_SCHEME_FALSE;
+  }
+  else {
+   const int string_len = strlen ($varname);
+   C_word *string_space = C_alloc (C_SIZEOF_STRING (string_len));
+   $result = C_string (&string_space, string_len, (char *) $varname);
+  }
+%}
+
+
+/* --- Constants --- */
+
+%typemap(constcode) char *
+"static const char *$result = $value;"
+
+%typemap(constcode) SWIGTYPE *, SWIGTYPE &, SWIGTYPE []
+"static const void *$result = (void*) $value;"
+
+/* ------------------------------------------------------------
+ * String & length
+ * ------------------------------------------------------------ */
+
+%typemap(in) (char *STRING, int LENGTH) {
+  if ($input == C_SCHEME_FALSE) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Cannot use a null/#f string for a char*, int arguments");
+  }
+  else if (C_swig_is_string ($input)) {
+    $1 = ($1_ltype) C_c_string ($input);
+    $2 = ($2_ltype) C_header_size ($input);
+  }
+  else {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'string'");
+  }
+}
+
+/* ------------------------------------------------------------
+ * CHICKEN types
+ * ------------------------------------------------------------ */
+
+%typemap(in)   C_word "$1 = $input;";
+%typemap(out)  C_word "$result = $1;";
+
+/* ------------------------------------------------------------
+ * Typechecking rules
+ * ------------------------------------------------------------ */
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+         bool, const bool & 
+{
+  $1 = C_swig_is_bool ($input);
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 int, short, 
+ 	 unsigned int, unsigned short,
+	 signed char, unsigned char,
+	 const int &, const short &, 
+ 	 const unsigned int &, const unsigned short &,
+	 enum SWIGTYPE
+{
+  $1 = C_swig_is_fixnum ($input);
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 long,
+ 	 unsigned long,
+	 long long, unsigned long long,
+	 const long &,
+ 	 const unsigned long &,
+	 const long long &, const unsigned long long &
+{
+  $1 = (C_swig_is_bool ($input) || 
+    C_swig_is_fixnum ($input) || 
+    C_swig_is_flonum ($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE)
+	float, double,
+	const float &, const double &
+{
+  $1 = C_swig_is_flonum ($input);
+}
+
+%typecheck(SWIG_TYPECHECK_CHAR) char {
+  $1 = C_swig_is_string ($input);
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char * {
+  $1 = C_swig_is_string ($input);
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  void *ptr;
+  $1 = !SWIG_ConvertPtr($input, &ptr, $1_descriptor, 0);
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  $1 = !SWIG_ConvertPtr($input, &ptr, 0, 0);
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE &
+{
+  void *ptr = 0;
+  if (SWIG_ConvertPtr($input, &ptr, $descriptor, 0)) {
+    /* error */
+    $1 = 0;
+  } else {
+    $1 = (ptr != 0);
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE 
+{
+  void *ptr = 0;
+  if (SWIG_ConvertPtr($input, &ptr, $&descriptor, 0)) {
+    /* error */
+    $1 = 0;
+  } else {
+    $1 = (ptr != 0);
+  }
+}
+
+
+/* ------------------------------------------------------------
+ * Exception handling
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ * --- Exception handling ---
+ * ------------------------------------------------------------ */
+
+%typemap(throws) SWIGTYPE {
+  $&ltype temp = new $ltype($1);
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  C_word ptr = SWIG_NewPointerObj(temp, $&descriptor,1);
+  SWIG_Chicken_ThrowException(ptr);
+}
+
+%typemap(throws) SWIGTYPE * {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  C_word ptr = SWIG_NewPointerObj((void *) $1, $descriptor, 0);
+  SWIG_Chicken_ThrowException(ptr);
+}
+
+%typemap(throws) SWIGTYPE [ANY] {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  C_word ptr = SWIG_NewPointerObj((void *) $1, $descriptor, 0);
+  SWIG_Chicken_ThrowException(ptr);
+}
+
+%typemap(throws) SWIGTYPE & {
+  C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);
+  C_word ptr = SWIG_NewPointerObj((void *)&($1),$descriptor,0);
+  SWIG_Chicken_ThrowException(ptr);
+}
+
+/* ------------------------------------------------------------
+ * ANSI C typemaps
+ * ------------------------------------------------------------ */
+
+%apply unsigned long { size_t };
+
+/* ------------------------------------------------------------
+ * Overloaded operator support
+ * ------------------------------------------------------------ */
+
+#ifdef __cplusplus
+%rename(__add__)      *::operator+;
+%rename(__pos__)      *::operator+();
+%rename(__pos__)      *::operator+() const;
+%rename(__sub__)      *::operator-;
+%rename(__neg__)      *::operator-();
+%rename(__neg__)      *::operator-() const;
+%rename(__mul__)      *::operator*;
+%rename(__div__)      *::operator/;
+%rename(__mod__)      *::operator%;
+%rename(__lshift__)   *::operator<<;
+%rename(__rshift__)   *::operator>>;
+%rename(__and__)      *::operator&;
+%rename(__or__)       *::operator|;
+%rename(__xor__)      *::operator^;
+%rename(__invert__)   *::operator~;
+%rename(__iadd__)     *::operator+=;
+%rename(__isub__)     *::operator-=;
+%rename(__imul__)     *::operator*=;
+%rename(__idiv__)     *::operator/=;
+%rename(__imod__)     *::operator%=;
+%rename(__ilshift__)  *::operator<<=;
+%rename(__irshift__)  *::operator>>=;
+%rename(__iand__)     *::operator&=;
+%rename(__ior__)      *::operator|=;
+%rename(__ixor__)     *::operator^=;
+%rename(__lt__)       *::operator<;
+%rename(__le__)       *::operator<=;
+%rename(__gt__)       *::operator>;
+%rename(__ge__)       *::operator>=;
+%rename(__eq__)       *::operator==;
+%rename(__ne__)       *::operator!=;
+
+/* Special cases */
+%rename(__call__)     *::operator();
+
+#endif
+/* Warnings for certain CHICKEN keywords */
+%include <chickenkw.swg>
+
+/* TinyCLOS <--> Low-level CHICKEN */
+
+%typemap("clos_in") SIMPLE_CLOS_OBJECT * "(slot-ref $input (quote this))"
+%typemap("clos_out") SIMPLE_CLOS_OBJECT * "(make $class (quote this) $1)"
+
+%insert(header) %{
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* Chicken initialization function */
+SWIGEXPORT void SWIG_init(C_word, C_word, C_word) C_noret;
+#ifdef __cplusplus
+}
+#endif
+%}
+
+%insert(closprefix) "swigclosprefix.scm"
+
+%insert(init) "swiginit.swg"
+
+%insert(init) %{
+/* CHICKEN initialization function */
+#ifdef __cplusplus
+extern "C" {
+#endif
+SWIGEXPORT void SWIG_init(C_word argc, C_word closure, C_word continuation) {
+  int       i;
+  C_word sym;
+  C_word tmp;
+  C_word *a;
+  C_word ret;
+  C_word *return_vec;
+
+  SWIG_InitializeModule(0);
+  SWIG_PropagateClientData();
+  ret = C_SCHEME_TRUE;
+  
+#if $veclength
+  return_vec = C_alloc(C_SIZEOF_VECTOR($veclength));
+  ret = (C_word) return_vec;
+  *(return_vec++) = C_VECTOR_TYPE | $veclength;
+#endif
+
+  a = C_alloc(2*$nummethods$symsize);
+
+%}
diff --git a/trunk/Lib/chicken/chickenkw.swg b/trunk/Lib/chicken/chickenkw.swg
new file mode 100644
index 0000000..d2c26c7
--- /dev/null
+++ b/trunk/Lib/chicken/chickenkw.swg
@@ -0,0 +1,31 @@
+#ifndef CHICKEN_CHICKENKW_SWG_
+#define CHICKEN_CHICKENKW_SWG_
+
+/* Warnings for certain CHICKEN keywords. From Section 7.1.1 of
+   Revised^5 Report on the Algorithmic Language Scheme */
+#define CHICKENKW(x) %namewarn("314: '" #x "' is a R^5RS syntatic keyword")  #x
+
+CHICKENKW(else);
+CHICKENKW(=>);
+CHICKENKW(define);
+CHICKENKW(unquote);
+CHICKENKW(unquote-splicing);
+CHICKENKW(quote);
+CHICKENKW(lambda);
+CHICKENKW(if);
+CHICKENKW(set!);
+CHICKENKW(begin);
+CHICKENKW(cond);
+CHICKENKW(and);
+CHICKENKW(or);
+CHICKENKW(case);
+CHICKENKW(let);
+CHICKENKW(let*);
+CHICKENKW(letrec);
+CHICKENKW(do);
+CHICKENKW(delay);
+CHICKENKW(quasiquote);
+
+#undef CHICKENKW 
+
+#endif //CHICKEN_CHICKENKW_SWG_
diff --git a/trunk/Lib/chicken/chickenrun.swg b/trunk/Lib/chicken/chickenrun.swg
new file mode 100644
index 0000000..bd72424
--- /dev/null
+++ b/trunk/Lib/chicken/chickenrun.swg
@@ -0,0 +1,377 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * chickenrun.swg
+ *
+ * ----------------------------------------------------------------------------- */
+
+#include <chicken.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM)
+# ifndef snprintf
+#  define snprintf _snprintf
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define SWIG_malloc(size) \
+  malloc(size)
+#define SWIG_free(mem) \
+  free(mem)
+#define SWIG_MakeString(c) \
+  SWIG_Chicken_MakeString(c)
+#define SWIG_ConvertPtr(s, result, type, flags) \
+  SWIG_Chicken_ConvertPtr(s, result, type, flags)
+#define SWIG_MustGetPtr(s, type, argnum, flags) \
+  SWIG_Chicken_MustGetPtr(s, type, argnum, flags)
+#define SWIG_NewPointerObj(ptr, type, owner) \
+  SWIG_Chicken_NewPointerObj((void*)ptr, type, owner, &known_space)
+#define swig_barf SWIG_Chicken_Barf
+#define SWIG_ThrowException(val) SWIG_Chicken_ThrowException(val)
+
+#define SWIG_contract_assert(expr, message) if (!(expr)) { \
+                                              SWIG_Chicken_Barf(SWIG_BARF1_CONTRACT_ASSERT, C_text(message)); } else
+
+/* Runtime API */
+#define SWIG_GetModule(clientdata) SWIG_Chicken_GetModule()
+#define SWIG_SetModule(clientdata, pointer) SWIG_Chicken_SetModule(pointer)
+
+#define C_swig_is_bool(x) C_truep (C_booleanp (x))
+#define C_swig_is_char(x) C_truep (C_charp (x))
+#define C_swig_is_fixnum(x) C_truep (C_fixnump (x))
+#define C_swig_is_flonum(x) (C_truep (C_blockp (x)) && C_truep (C_flonump (x)))
+#define C_swig_is_string(x) (C_truep (C_blockp (x)) && C_truep (C_stringp (x)))
+#define C_swig_is_vector(x) (C_truep (C_blockp (x)) && C_truep (C_vectorp (x)))
+#define C_swig_is_list(x) (C_truep (C_i_listp (x)))
+#define C_swig_is_pair(x) (C_truep (C_blockp(x)) && C_truep (C_pairp(x)))
+#define C_swig_is_ptr(x) (C_truep (C_blockp (x)) && C_truep (C_pointerp (x)))
+#define C_swig_is_swigpointer(x) (C_truep (C_blockp(x)) && C_truep (C_swigpointerp(x)))
+#define C_swig_is_closurep(x) (C_truep (C_blockp(x)) && C_truep(C_closurep(x)))
+#define C_swig_is_number(x) (C_swig_is_fixnum(x) || C_swig_is_flonum(x))
+#define C_swig_is_long(x) C_swig_is_number(x)
+
+#define C_swig_sizeof_closure(num) (num+1)
+
+#define SWIG_Chicken_SetupArgout { \
+  C_word *a = C_alloc(C_swig_sizeof_closure(2)); \
+  C_word *closure = a; \
+  *(a++)=C_CLOSURE_TYPE|2; \
+  *(a++)=(C_word)SWIG_Chicken_ApplyResults; \
+  *(a++)=continuation; \
+  continuation=(C_word)closure; \
+}
+
+#define SWIG_APPEND_VALUE(obj) { \
+  C_word val = (C_word)(obj); \
+  if (val != C_SCHEME_UNDEFINED) { \
+    C_word *a = C_alloc(C_swig_sizeof_closure(3)); \
+    C_word *closure = a; \
+    *(a++)=C_CLOSURE_TYPE|3; \
+    *(a++)=(C_word)SWIG_Chicken_MultiResultBuild; \
+    *(a++)=(C_word)continuation; \
+    *(a++)=val; \
+    continuation=(C_word)closure; \
+  } }
+
+#define SWIG_Chicken_FindCreateProxy(func,obj) \
+  if (C_swig_is_swigpointer(obj)) { \
+    swig_type_info *t = (swig_type_info *) C_block_item(obj, 1); \
+    if (t && t->clientdata &&    ((swig_chicken_clientdata *)t->clientdata)->gc_proxy_create) { \
+      func = CHICKEN_gc_root_ref( ((swig_chicken_clientdata *)t->clientdata)->gc_proxy_create); \
+    } else { \
+      func = C_SCHEME_FALSE; \
+    } \
+  } else { \
+    func = C_SCHEME_FALSE; \
+  }
+
+
+enum {
+  SWIG_BARF1_BAD_ARGUMENT_TYPE /* 1 arg */,
+  SWIG_BARF1_ARGUMENT_NULL /* 1 arg */,
+  SWIG_BARF1_CONTRACT_ASSERT /* 1 arg */,
+};
+
+typedef C_word (*swig_chicken_destructor)(C_word,C_word,C_word,C_word);
+typedef struct swig_chicken_clientdata {
+  void *gc_proxy_create;
+  swig_chicken_destructor destroy;
+} swig_chicken_clientdata;
+  
+static char *
+SWIG_Chicken_MakeString(C_word str) {
+  char *ret;
+  size_t l;
+
+  l = C_header_size(str);
+  ret = (char *) SWIG_malloc( (l + 1) * sizeof(char));
+  if (!ret) return NULL;
+
+  memcpy(ret, C_c_string(str), l);
+  ret[l] = '\0';
+  return ret;
+}
+
+static C_word SWIG_Chicken_LookupSymbol(char *name, C_SYMBOL_TABLE *stable) {
+  C_word *a = C_alloc(C_SIZEOF_STRING (strlen (name)));
+  C_word n = C_string2(&a, name);
+  C_word sym = C_find_symbol(n, stable);
+  if (C_truep(sym)) {
+    return C_symbol_value(sym);
+  } else {
+    return C_SCHEME_FALSE;
+  }
+}
+
+/* Just a helper function.  Do not export it */
+static void SWIG_Chicken_Panic (C_char *) C_noret;
+static void SWIG_Chicken_Panic (C_char *msg)
+{
+  C_word *a = C_alloc (C_SIZEOF_STRING (strlen (msg)));
+  C_word scmmsg = C_string2 (&a, msg);
+  C_halt (scmmsg);
+  exit (5); /* should never get here */
+}
+
+static void
+SWIG_Chicken_Barf(int code, C_char *msg, ...) C_noret;
+static void
+SWIG_Chicken_Barf(int code, C_char *msg, ...)
+{
+  char *errorhook = C_text("\003syserror-hook");
+  C_word *a = C_alloc (C_SIZEOF_STRING (strlen (errorhook)));
+  C_word err = C_intern2 (&a, errorhook);
+  int c = -1;
+  int i, barfval;
+  va_list v;
+
+  
+  C_temporary_stack = C_temporary_stack_bottom;
+  err = C_block_item(err, 0);
+
+  if(C_immediatep (err))
+    SWIG_Chicken_Panic (C_text ("`##sys#error-hook' is not defined"));
+
+  switch (code) {
+  case SWIG_BARF1_BAD_ARGUMENT_TYPE:
+    barfval = C_BAD_ARGUMENT_TYPE_ERROR;
+    c = 1;
+    break;
+  case SWIG_BARF1_ARGUMENT_NULL:
+    barfval = C_BAD_ARGUMENT_TYPE_ERROR;
+    c = 1;
+    break;
+  case SWIG_BARF1_CONTRACT_ASSERT:
+    barfval = C_BAD_ARGUMENT_TYPE_ERROR;
+    c = 1;
+    break;
+  default:
+    SWIG_Chicken_Panic (C_text (msg));
+  };
+
+  if(c > 0 && !C_immediatep (err)) {
+    C_save (C_fix (barfval));
+
+    i = c;
+    if (i) {
+      C_word *b = C_alloc (C_SIZEOF_STRING (strlen (msg)));
+      C_word scmmsg = C_string2 (&b, msg);
+      C_save (scmmsg);
+      i--;
+    }
+
+    va_start (v, msg);
+
+    while(i--)
+      C_save (va_arg (v, C_word));
+
+    va_end (v);
+    C_do_apply (c + 1, err, 
+		C_SCHEME_UNDEFINED);  /* <- no continuation is passed:
+					 '##sys#error-hook' may not
+					 return! */
+  }
+  else if (msg) {
+    SWIG_Chicken_Panic (msg);
+  }
+  else {
+    SWIG_Chicken_Panic (C_text ("unspecified panic"));
+  }
+}
+
+static void SWIG_Chicken_ThrowException(C_word value) C_noret;
+static void SWIG_Chicken_ThrowException(C_word value)
+{
+  char *aborthook = C_text("\003sysabort");
+  C_word *a = C_alloc(C_SIZEOF_STRING(strlen(aborthook)));
+  C_word abort = C_intern2(&a, aborthook);
+
+  abort = C_block_item(abort, 0);
+  if (C_immediatep(abort))
+    SWIG_Chicken_Panic(C_text("`##sys#abort' is not defined"));
+
+  C_save(value);
+  C_do_apply(1, abort, C_SCHEME_UNDEFINED);
+}
+
+static void
+SWIG_Chicken_Finalizer(C_word argc, C_word closure, C_word continuation, C_word s)
+{
+  swig_type_info *type;
+  swig_chicken_clientdata *cdata;
+
+  if (argc == 3 && s != C_SCHEME_FALSE && C_swig_is_swigpointer(s)) {
+    type = (swig_type_info *) C_block_item(s, 1);
+    if (type) {
+      cdata = (swig_chicken_clientdata *) type->clientdata;
+      if (cdata && cdata->destroy) {
+	/* this will not return, but will continue correctly */
+        cdata->destroy(3,closure,continuation,s);
+      }
+    }
+  }
+  C_kontinue(continuation, C_SCHEME_UNDEFINED);
+}
+static C_word finalizer_obj[2] = {(C_word) (C_CLOSURE_TYPE|1), (C_word) SWIG_Chicken_Finalizer};
+
+static C_word
+SWIG_Chicken_NewPointerObj(void *ptr, swig_type_info *type, int owner, C_word **data)
+{
+  swig_chicken_clientdata *cdata = (swig_chicken_clientdata *) type->clientdata;
+
+  if (ptr == NULL)
+    return C_SCHEME_FALSE;
+  else {
+    C_word cptr = C_swigmpointer(data, ptr, type);
+    /* add finalizer to object */
+    #ifndef SWIG_CHICKEN_NO_COLLECTION
+    if (owner)
+      C_do_register_finalizer(cptr, (C_word) finalizer_obj);
+    #endif
+
+    return cptr;
+  }
+}
+
+/* Return 0 if successful. */
+static int
+SWIG_Chicken_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags)
+{
+  swig_cast_info *cast;
+  swig_type_info *from;
+
+  if (s == C_SCHEME_FALSE) {
+    *result = NULL;
+  } else if (C_swig_is_swigpointer(s)) {
+    /* try and convert type */
+    from = (swig_type_info *) C_block_item(s, 1);
+    if (!from) return 1;
+    if (type) {
+      cast = SWIG_TypeCheckStruct(from, type);
+      if (cast) {
+        int newmemory = 0;
+        *result = SWIG_TypeCast(cast, (void *) C_block_item(s, 0), &newmemory);
+        assert(!newmemory); /* newmemory handling not yet implemented */
+      } else {
+        return 1;
+      }
+    } else {
+      *result = (void *) C_block_item(s, 0);
+    }
+
+    /* check if we are disowning this object */
+    if (flags & SWIG_POINTER_DISOWN) {
+      C_do_unregister_finalizer(s);
+    }
+  } else {
+    return 1;
+  }
+
+  return 0;
+}
+
+static SWIGINLINE void *
+SWIG_Chicken_MustGetPtr (C_word s, swig_type_info *type, int argnum, int flags)
+{
+  void *result;
+  char err_msg[256];
+  if (SWIG_Chicken_ConvertPtr(s, &result, type, flags)) {
+    /* type mismatch */
+    snprintf(err_msg, sizeof(err_msg), "Type error in argument #%i: expected %s", argnum, (type->str ? type->str : type->name));
+    SWIG_Chicken_Barf(SWIG_BARF1_BAD_ARGUMENT_TYPE, err_msg);
+  }
+  return result;
+}
+
+static char *chicken_runtimevar_name = "type_pointer" SWIG_TYPE_TABLE_NAME;
+
+static swig_module_info *
+SWIG_Chicken_GetModule() {
+    swig_module_info *ret = 0;
+    C_word sym;
+
+    /* lookup the type pointer... it is stored in it's own symbol table */
+    C_SYMBOL_TABLE *stable = C_find_symbol_table("swig_runtime_data" SWIG_RUNTIME_VERSION);
+    if (stable != NULL) {
+      sym = SWIG_Chicken_LookupSymbol(chicken_runtimevar_name, stable);
+      if (C_truep(sym) && C_swig_is_ptr(sym)) {
+        ret = (swig_module_info *) C_block_item(sym, 0);
+      }
+    }
+
+    return ret;
+}
+
+static void
+SWIG_Chicken_SetModule(swig_module_info *module) {
+    C_word *a;
+    C_SYMBOL_TABLE *stable;
+    C_word sym;
+    C_word pointer;
+    static C_word *space = 0;
+    
+    /* type pointer is stored in it's own symbol table */
+    stable = C_find_symbol_table("swig_runtime_data" SWIG_RUNTIME_VERSION);
+    if (stable == NULL) {
+      stable = C_new_symbol_table("swig_runtime_data" SWIG_RUNTIME_VERSION, 16);
+    }
+
+    if (!space) {
+      space = (C_word *) C_malloc((C_SIZEOF_POINTER + C_SIZEOF_INTERNED_SYMBOL(C_strlen(chicken_runtimevar_name))) * sizeof(C_word));
+    }
+    a = space;
+    pointer = C_mpointer(&a, (void *) module);
+    sym = C_intern_in(&a, C_strlen(chicken_runtimevar_name), chicken_runtimevar_name, stable);
+    C_set_block_item(sym, 0, pointer);
+}
+
+static C_word SWIG_Chicken_MultiResultBuild(C_word num, C_word closure, C_word lst) {
+  C_word cont = C_block_item(closure,1);
+  C_word obj = C_block_item(closure,2);
+  C_word func;
+
+  SWIG_Chicken_FindCreateProxy(func,obj);
+
+  if (C_swig_is_closurep(func)) {
+    ((C_proc4)(void *)C_block_item(func, 0))(4,func,cont,obj,lst);
+  } else {
+    C_word *a = C_alloc(C_SIZEOF_PAIR);
+    C_kontinue(cont,C_pair(&a,obj,lst));
+  }
+  return C_SCHEME_UNDEFINED; /* never reached */
+}
+
+static C_word SWIG_Chicken_ApplyResults(C_word num, C_word closure, C_word result) {
+  C_apply_values(3,C_SCHEME_UNDEFINED,C_block_item(closure,1),result);
+  return C_SCHEME_UNDEFINED; /* never reached */
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/chicken/extra-install.list b/trunk/Lib/chicken/extra-install.list
new file mode 100644
index 0000000..48721ce
--- /dev/null
+++ b/trunk/Lib/chicken/extra-install.list
@@ -0,0 +1,3 @@
+swigclosprefix.scm
+multi-generic.scm
+tinyclos-multi-generic.patch
diff --git a/trunk/Lib/chicken/multi-generic.scm b/trunk/Lib/chicken/multi-generic.scm
new file mode 100644
index 0000000..ae822f3
--- /dev/null
+++ b/trunk/Lib/chicken/multi-generic.scm
@@ -0,0 +1,152 @@
+;; This file is no longer necessary with Chicken versions above 1.92
+;; 
+;; This file overrides two functions inside TinyCLOS to provide support
+;; for multi-argument generics.  There are many ways of linking this file
+;; into your code... all that needs to happen is this file must be
+;; executed after loading TinyCLOS but before any SWIG modules are loaded
+;;
+;; something like the following
+;; (require 'tinyclos)
+;; (load "multi-generic")
+;; (declare (uses swigmod))
+;;
+;; An alternative to loading this scheme code directly is to add a
+;; (declare (unit multi-generic)) to the top of this file, and then
+;; compile this into the final executable or something.  Or compile
+;; this into an extension.
+
+;; Lastly, to override TinyCLOS method creation, two functions are
+;; overridden: see the end of this file for which two are overridden.
+;; You might want to remove those two lines and then exert more control over
+;; which functions are used when.
+
+;; Comments, bugs, suggestions: send either to chicken-users@nongnu.org or to
+;; Author: John Lenz <lenz@cs.wisc.edu>, most code copied from TinyCLOS
+
+(define <multi-generic> (make <entity-class>
+			  'name "multi-generic"
+			  'direct-supers (list <generic>)
+			  'direct-slots '()))
+
+(letrec ([applicable?
+          (lambda (c arg)
+            (memq c (class-cpl (class-of arg))))]
+
+         [more-specific?
+          (lambda (c1 c2 arg)
+            (memq c2 (memq c1 (class-cpl (class-of arg)))))]
+
+         [filter-in
+           (lambda (f l)
+             (if (null? l)
+                 '()
+                 (let ([h (##sys#slot l 0)]
+	               [r (##sys#slot l 1)] )
+	           (if (f h)
+	               (cons h (filter-in f r))
+	               (filter-in f r) ) ) ) )])
+
+(add-method compute-apply-generic
+  (make-method (list <multi-generic>)
+    (lambda (call-next-method generic)
+      (lambda args
+		(let ([cam (let ([x (compute-apply-methods generic)]
+				 [y ((compute-methods generic) args)] )
+			     (lambda (args) (x y args)) ) ] )
+		  (cam args) ) ) ) ) )
+
+
+
+(add-method compute-methods
+  (make-method (list <multi-generic>)
+    (lambda (call-next-method generic)
+      (lambda (args)
+	(let ([applicable
+	       (filter-in (lambda (method)
+                            (let check-applicable ([list1 (method-specializers method)]
+                                                   [list2 args])
+                              (cond ((null? list1) #t)
+                                    ((null? list2) #f)
+                                    (else
+                                      (and (applicable? (##sys#slot list1 0) (##sys#slot list2 0))
+                                           (check-applicable (##sys#slot list1 1) (##sys#slot list2 1)))))))
+			  (generic-methods generic) ) ] )
+	  (if (or (null? applicable) (null? (##sys#slot applicable 1))) 
+	      applicable
+	      (let ([cmms (compute-method-more-specific? generic)])
+		(sort applicable (lambda (m1 m2) (cmms m1 m2 args))) ) ) ) ) ) ) )
+
+(add-method compute-method-more-specific?
+  (make-method (list <multi-generic>)
+    (lambda (call-next-method generic)
+      (lambda (m1 m2 args)
+	(let loop ((specls1 (method-specializers m1))
+		   (specls2 (method-specializers m2))
+		   (args args))
+	  (cond-expand
+	   [unsafe
+	    (let ((c1  (##sys#slot specls1 0))
+		  (c2  (##sys#slot specls2 0))
+		  (arg (##sys#slot args 0)))
+	      (if (eq? c1 c2)
+		  (loop (##sys#slot specls1 1)
+			(##sys#slot specls2 1)
+			(##sys#slot args 1))
+		  (more-specific? c1 c2 arg))) ] 
+	   [else
+	    (cond ((and (null? specls1) (null? specls2))
+		   (##sys#error "two methods are equally specific" generic))
+		  ;((or (null? specls1) (null? specls2))
+		  ; (##sys#error "two methods have different number of specializers" generic))
+                  ((null? specls1) #f)
+                  ((null? specls2) #t)
+		  ((null? args)
+		   (##sys#error "fewer arguments than specializers" generic))
+		  (else
+		   (let ((c1  (##sys#slot specls1 0))
+			 (c2  (##sys#slot specls2 0))
+			 (arg (##sys#slot args 0)))
+		     (if (eq? c1 c2)
+			 (loop (##sys#slot specls1 1)
+			       (##sys#slot specls2 1)
+			       (##sys#slot args 1))
+			 (more-specific? c1 c2 arg)))) ) ] ) ) ) ) ) )
+
+) ;; end of letrec
+
+(define multi-add-method
+  (lambda (generic method)
+    (slot-set!
+     generic
+     'methods
+       (let filter-in-method ([methods (slot-ref generic 'methods)])
+         (if (null? methods)
+           (list method)
+           (let ([l1 (length (method-specializers method))]
+		 [l2 (length (method-specializers (##sys#slot methods 0)))])
+             (cond ((> l1 l2)
+                    (cons (##sys#slot methods 0) (filter-in-method (##sys#slot methods 1))))
+                   ((< l1 l2)
+                    (cons method methods))
+                   (else
+                     (let check-method ([ms1 (method-specializers method)]
+                                        [ms2 (method-specializers (##sys#slot methods 0))])
+                       (cond ((and (null? ms1) (null? ms2))
+                              (cons method (##sys#slot methods 1))) ;; skip the method already in the generic
+                             ((eq? (##sys#slot ms1 0) (##sys#slot ms2 0))
+                              (check-method (##sys#slot ms1 1) (##sys#slot ms2 1)))
+                             (else
+                               (cons (##sys#slot methods 0) (filter-in-method (##sys#slot methods 1))))))))))))
+
+    (##sys#setslot (##sys#slot generic (- (##sys#size generic) 2)) 1 (compute-apply-generic generic)) ))
+
+(define (multi-add-global-method val sym specializers proc)
+  (let ((generic (if (procedure? val) val (make <multi-generic> 'name (##sys#symbol->string sym)))))
+    (multi-add-method generic (make-method specializers proc))
+    generic))
+
+;; Might want to remove these, or perhaps do something like
+;; (define old-add-method ##tinyclos#add-method)
+;; and then you can switch between creating multi-generics and TinyCLOS generics.
+(set! ##tinyclos#add-method multi-add-method)
+(set! ##tinyclos#add-global-method multi-add-global-method)
diff --git a/trunk/Lib/chicken/std_string.i b/trunk/Lib/chicken/std_string.i
new file mode 100644
index 0000000..2955d0e
--- /dev/null
+++ b/trunk/Lib/chicken/std_string.i
@@ -0,0 +1,100 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <string>
+%}
+
+namespace std {
+    %naturalvar string;
+  
+
+    %insert(closprefix) %{ (declare (hide <std-string>)) %}
+    %nodefault string;
+    %rename("std-string") string;
+    class string {
+      public:
+	~string() {}
+    };
+    %extend string {
+      char *str;
+    }
+    %{
+      #define std_string_str_get(s) ((char *)((s)->c_str()))
+      #define std_string_str_set(s,v) (s->assign((char *)(v)))
+    %}
+
+    %typemap(typecheck) string = char *;
+    %typemap(typecheck) const string & = char *;
+
+    %typemap(in) string (char* tempptr) {
+      if ($input == C_SCHEME_FALSE) {
+	$1.resize(0);
+      } else { 
+	if (!C_swig_is_string ($input)) {
+	  swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, 
+		     "Argument #$argnum is not a string");
+	}
+	tempptr = SWIG_MakeString($input);
+	$1.assign(tempptr);
+	if (tempptr) SWIG_free(tempptr);
+      }
+    }
+
+    %typemap(in) const string& (std::string temp,
+			 char* tempptr) {
+
+      if ($input == C_SCHEME_FALSE) {
+	temp.resize(0);
+	$1 = &temp;
+      } else { 
+	if (!C_swig_is_string ($input)) {
+	  swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, 
+		     "Argument #$argnum is not a string");
+	}
+	tempptr = SWIG_MakeString($input);
+	temp.assign(tempptr);
+	if (tempptr) SWIG_free(tempptr);
+	$1 = &temp;
+      }
+    }
+
+    %typemap(out) string { 
+      int size = $1.size();
+      C_word *space = C_alloc (C_SIZEOF_STRING (size));
+      $result = C_string (&space, size, (char *) $1.c_str());
+    }
+
+    %typemap(out) const string& { 
+      int size = $1->size();
+      C_word *space = C_alloc (C_SIZEOF_STRING (size));
+      $result = C_string (&space, size, (char *) $1->c_str());
+    }
+
+    %typemap(varin) string {
+      if ($input == C_SCHEME_FALSE) {
+	$1.resize(0);
+      } else { 
+        char *tempptr;
+	if (!C_swig_is_string ($input)) {
+	  swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, 
+		     "Argument #$argnum is not a string");
+   	}
+	tempptr = SWIG_MakeString($input);
+	$1.assign(tempptr);
+	if (tempptr) SWIG_free(tempptr);
+      }
+    }
+
+    %typemap(varout) string { 
+      int size = $1.size();
+      C_word *space = C_alloc (C_SIZEOF_STRING (size));
+      $result = C_string (&space, size, (char *) $1.c_str());
+    }
+}
diff --git a/trunk/Lib/chicken/swigclosprefix.scm b/trunk/Lib/chicken/swigclosprefix.scm
new file mode 100644
index 0000000..e4bd72b
--- /dev/null
+++ b/trunk/Lib/chicken/swigclosprefix.scm
@@ -0,0 +1,31 @@
+(declare (hide swig-initialize))
+
+(define (swig-initialize obj initargs create)
+     (slot-set! obj 'swig-this
+        (if (memq 'swig-this initargs)
+            (cadr initargs)
+            (let ((ret (apply create initargs)))
+              (if (instance? ret)
+                (slot-ref ret 'swig-this)
+                ret)))))
+
+(define-class <swig-metaclass-$module> (<class>) (void))
+
+(define-method (compute-getter-and-setter (class <swig-metaclass-$module>) slot allocator)
+  (if (not (memq ':swig-virtual slot))
+    (call-next-method)
+    (let ((getter (let search-get ((lst slot))
+                    (if (null? lst)
+                      #f
+                      (if (eq? (car lst) ':swig-get)
+                        (cadr lst)
+                        (search-get (cdr lst))))))
+          (setter (let search-set ((lst slot))
+                    (if (null? lst)
+                      #f
+                      (if (eq? (car lst) ':swig-set)
+                        (cadr lst)
+                        (search-set (cdr lst)))))))
+      (values
+        (lambda (o) (getter (slot-ref o 'swig-this)))
+	(lambda (o new) (setter (slot-ref o 'swig-this) new) new)))))
diff --git a/trunk/Lib/chicken/tinyclos-multi-generic.patch b/trunk/Lib/chicken/tinyclos-multi-generic.patch
new file mode 100644
index 0000000..2e58596
--- /dev/null
+++ b/trunk/Lib/chicken/tinyclos-multi-generic.patch
@@ -0,0 +1,150 @@
+# This patch is against chicken 1.92, but it should work just fine
+# with older versions of chicken.  It adds support for mulit-argument
+# generics, that is, generics now correctly handle adding methods
+# with different lengths of specializer lists
+
+# This patch has been committed into the CHICKEN darcs repository,
+# so chicken versions above 1.92 work fine.
+
+# Comments, bugs, suggestions send to chicken-users@nongnu.org
+
+# Patch written by John Lenz <lenz@cs.wisc.edu>
+
+--- tinyclos.scm.old	2005-04-05 01:13:56.000000000 -0500
++++ tinyclos.scm	2005-04-11 16:37:23.746181489 -0500
+@@ -37,8 +37,10 @@
+ 
+ (include "parameters")
+ 
++(cond-expand [(not chicken-compile-shared) (declare (unit tinyclos))]
++	     [else] )
++
+ (declare
+-  (unit tinyclos)
+   (uses extras)
+   (usual-integrations)
+   (fixnum) 
+@@ -234,7 +236,10 @@
+             y = C_block_item(y, 1);
+           }
+         }
+-        return(C_block_item(v, i + 1));
++        if (x == C_SCHEME_END_OF_LIST && y == C_SCHEME_END_OF_LIST)
++          return(C_block_item(v, i + 1));
++        else
++          goto mismatch;
+       }
+       else if(free_index == -1) free_index = i;
+     mismatch:
+@@ -438,7 +443,7 @@
+ (define hash-arg-list
+   (foreign-lambda* unsigned-int ((scheme-object args) (scheme-object svector)) "
+     C_word tag, h, x;
+-    int n, i, j;
++    int n, i, j, len = 0;
+     for(i = 0; args != C_SCHEME_END_OF_LIST; args = C_block_item(args, 1)) {
+       x = C_block_item(args, 0);
+       if(C_immediatep(x)) {
+@@ -481,8 +486,9 @@
+         default: i += 255;
+         }
+       }
++      ++len;
+     }
+-    return(i & (C_METHOD_CACHE_SIZE - 1));") )
++    return((i + len) & (C_METHOD_CACHE_SIZE - 1));") )
+ 
+ 
+ ;
+@@ -868,13 +874,27 @@
+     (##tinyclos#slot-set!
+      generic
+      'methods
+-     (cons method
+-	   (filter-in
+-	    (lambda (m) 
+-	      (let ([ms1 (method-specializers m)]
+-		    [ms2 (method-specializers method)] )
+-		(not (every2 (lambda (x y) (eq? x y)) ms1 ms2) ) ) )
+-	    (##tinyclos#slot-ref generic 'methods))))
++     (let* ([ms1 (method-specializers method)]
++	    [l1 (length ms1)] )
++       (let filter-in-method ([methods (##tinyclos#slot-ref generic 'methods)])
++	 (if (null? methods)
++	     (list method)
++	     (let* ([mm (##sys#slot methods 0)]
++		    [ms2 (method-specializers mm)]
++		    [l2 (length ms2)])
++	       (cond ((> l1 l2)
++		      (cons mm (filter-in-method (##sys#slot methods 1))))
++		     ((< l1 l2)
++		      (cons method methods))
++		     (else
++		      (let check-method ([ms1 ms1]
++					 [ms2 ms2])
++			(cond ((and (null? ms1) (null? ms2))
++			       (cons method (##sys#slot methods 1))) ;; skip the method already in the generic
++			      ((eq? (##sys#slot ms1 0) (##sys#slot ms2 0))
++			       (check-method (##sys#slot ms1 1) (##sys#slot ms2 1)))
++			      (else
++			       (cons mm (filter-in-method (##sys#slot methods 1)))))))))))))
+     (if (memq generic generic-invocation-generics)
+ 	(set! method-cache-tag (vector))
+ 	(%entity-cache-set! generic #f) )
+@@ -925,11 +945,13 @@
+ 				(memq (car args) generic-invocation-generics))
+ 			   (let ([proc 
+ 				  (method-procedure
++				    ; select the first method of one argument
+ 				   (let lp ([lis (generic-methods generic)])
+-				     (let ([tail (##sys#slot lis 1)])
+-				       (if (null? tail)
+-					   (##sys#slot lis 0)
+-					   (lp tail)) ) ) ) ] )
++				     (if (null? lis)
++				       (##sys#error "Unable to find original compute-apply-generic")
++				       (if (= (length (method-specializers (##sys#slot lis 0))) 1)
++					 (##sys#slot lis 0)
++					 (lp (##sys#slot lis 1)))))) ] )
+ 			     (lambda (args) (apply proc #f args)) )
+ 			   (let ([x (compute-apply-methods generic)]
+ 				 [y ((compute-methods generic) args)] )
+@@ -946,9 +968,13 @@
+       (lambda (args)
+ 	(let ([applicable
+ 	       (filter-in (lambda (method)
+-			    (every2 applicable?
+-				   (method-specializers method)
+-				   args))
++                            (let check-applicable ([list1 (method-specializers method)]
++                                                   [list2 args])
++                              (cond ((null? list1) #t)
++                                    ((null? list2) #f)
++                                    (else
++                                      (and (applicable? (##sys#slot list1 0) (##sys#slot list2 0))
++                                           (check-applicable (##sys#slot list1 1) (##sys#slot list2 1)))))))
+ 			  (generic-methods generic) ) ] )
+ 	  (if (or (null? applicable) (null? (##sys#slot applicable 1))) 
+ 	      applicable
+@@ -975,8 +1001,10 @@
+ 	   [else
+ 	    (cond ((and (null? specls1) (null? specls2))
+ 		   (##sys#error "two methods are equally specific" generic))
+-		  ((or (null? specls1) (null? specls2))
+-		   (##sys#error "two methods have different number of specializers" generic))
++		  ;((or (null? specls1) (null? specls2))
++		  ; (##sys#error "two methods have different number of specializers" generic))
++                  ((null? specls1) #f)
++                  ((null? specls2) #t)
+ 		  ((null? args)
+ 		   (##sys#error "fewer arguments than specializers" generic))
+ 		  (else
+@@ -1210,7 +1238,7 @@
+ (define <structure>      (make-primitive-class "structure"))
+ (define <procedure> (make-primitive-class "procedure" <procedure-class>))
+ (define <end-of-file> (make-primitive-class "end-of-file"))
+-(define <environment> (make-primitive-class "environment" <structure>))	; (Benedikt insisted on this)
++(define <environment> (make-primitive-class "environment" <structure>))
+ (define <hash-table> (make-primitive-class "hash-table" <structure>))
+ (define <promise> (make-primitive-class "promise" <structure>))
+ (define <queue> (make-primitive-class "queue" <structure>))
diff --git a/trunk/Lib/chicken/typemaps.i b/trunk/Lib/chicken/typemaps.i
new file mode 100644
index 0000000..d79e201
--- /dev/null
+++ b/trunk/Lib/chicken/typemaps.i
@@ -0,0 +1,318 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Pointer handling
+ *
+ * These mappings provide support for input/output arguments and
+ * common uses for C/C++ pointers.  INOUT mappings allow for C/C++
+ * pointer variables in addition to input/output arguments.
+ * ----------------------------------------------------------------------------- */
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+/* 
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+
+         int            *INPUT
+         short          *INPUT
+         long           *INPUT
+	 long long      *INPUT
+         unsigned int   *INPUT
+         unsigned short *INPUT
+         unsigned long  *INPUT
+         unsigned long long *INPUT
+         unsigned char  *INPUT
+         char           *INPUT
+         bool           *INPUT
+         float          *INPUT
+         double         *INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include <typemaps.i>
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a list element.
+
+/* 
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, they are returned in the form of a Scheme list.
+
+         int            *OUTPUT
+         short          *OUTPUT
+         long           *OUTPUT
+         long long      *OUTPUT
+         unsigned int   *OUTPUT
+         unsigned short *OUTPUT
+         unsigned long  *OUTPUT
+         unsigned long long *OUTPUT
+         unsigned char  *OUTPUT
+         char           *OUTPUT
+         bool           *OUTPUT
+         float          *OUTPUT
+         double         *OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters).K:
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+*/
+
+// These typemaps contributed by Robin Dunn
+//----------------------------------------------------------------------
+//
+// T_OUTPUT typemap (and helper function) to return multiple argouts as
+// a tuple instead of a list.
+//
+//----------------------------------------------------------------------
+
+// Simple types
+
+%define INOUT_TYPEMAP(type_, from_scheme, to_scheme, checker, convtype, storage_)
+
+%typemap(in) type_ *INPUT($*1_ltype temp), type_ &INPUT($*1_ltype temp)
+%{  if (!checker ($input)) {
+    swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, "Argument #$argnum is not of type 'type_'");
+  }
+  temp = ($*1_ltype) from_scheme ($input);
+  $1 = &temp; %}
+
+%typemap(typecheck) type_ *INPUT = type_;
+%typemap(typecheck) type_ &INPUT = type_;
+
+%typemap(in, numinputs=0) type_ *OUTPUT($*1_ltype temp), type_ &OUTPUT($*1_ltype temp)
+"  $1 = &temp;"
+
+#if "storage_" == "0"
+
+%typemap(argout) type_ *OUTPUT, type_ &OUTPUT 
+%{ 
+  if ($1 == NULL) {
+    swig_barf (SWIG_BARF1_ARGUMENT_NULL, "Argument #$argnum must be non-null");
+  }
+  SWIG_APPEND_VALUE(to_scheme (convtype (*$1)));
+%}
+
+#else
+
+%typemap(argout) type_ *OUTPUT, type_ &OUTPUT 
+%{
+  {
+    C_word *known_space = C_alloc(storage_);
+    if ($1 == NULL) {
+      swig_barf (SWIG_BARF1_ARGUMENT_NULL, "Variable '$1' must be non-null");
+    }
+    SWIG_APPEND_VALUE(to_scheme (&known_space, convtype (*$1)));
+  }
+%}
+
+#endif
+
+%enddef
+
+INOUT_TYPEMAP(int, C_num_to_int, C_fix, C_swig_is_number, (int), 0);
+INOUT_TYPEMAP(enum SWIGTYPE, C_num_to_int, C_fix, C_swig_is_number, (int), 0);
+INOUT_TYPEMAP(short, C_num_to_int, C_fix, C_swig_is_number, (int), 0);
+INOUT_TYPEMAP(long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM);
+INOUT_TYPEMAP(long long, C_num_to_long, C_long_to_num, C_swig_is_long, (long), C_SIZEOF_FLONUM);
+INOUT_TYPEMAP(unsigned int, C_num_to_unsigned_int, C_unsigned_int_to_num, C_swig_is_number, (int), C_SIZEOF_FLONUM);
+INOUT_TYPEMAP(unsigned short, C_num_to_unsigned_int, C_fix, C_swig_is_number, (unsigned int), 0);
+INOUT_TYPEMAP(unsigned long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM);
+INOUT_TYPEMAP(unsigned long long, C_num_to_unsigned_long, C_unsigned_long_to_num, C_swig_is_long, (unsigned long), C_SIZEOF_FLONUM);
+INOUT_TYPEMAP(unsigned char, C_character_code, C_make_character, C_swig_is_char, (unsigned int), 0);
+INOUT_TYPEMAP(signed char, C_character_code, C_make_character, C_swig_is_char, (int), 0);
+INOUT_TYPEMAP(char, C_character_code, C_make_character, C_swig_is_char, (char), 0);
+INOUT_TYPEMAP(bool, C_truep, C_mk_bool, C_swig_is_bool, (bool), 0);
+INOUT_TYPEMAP(float, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM);
+INOUT_TYPEMAP(double, C_c_double, C_flonum, C_swig_is_number, (double), C_SIZEOF_FLONUM);
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a CHICKEN tuple.  
+
+         int            *INOUT
+         short          *INOUT
+         long           *INOUT
+         long long      *INOUT
+         unsigned int   *INOUT
+         unsigned short *INOUT
+         unsigned long  *INOUT
+         unsigned long long *INOUT
+         unsigned char  *INOUT
+         char           *INOUT
+         bool           *INOUT
+         float          *INOUT
+         double         *INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+As well, you can wrap variables with :
+
+        %include <typemaps.i>
+        %apply double *INOUT { double *y };
+        extern double *y;
+
+Unlike C, this mapping does not directly modify the input value (since
+this makes no sense in CHICKEN).  Rather, the modified input value shows
+up as the return value of the function.  Thus, to apply this function
+to a CHICKEN variable you might do this :
+
+       x = neg(x)
+
+Note : previous versions of SWIG used the symbol 'BOTH' to mark
+input/output arguments.   This is still supported, but will be slowly
+phased out in future releases.
+
+*/
+
+%typemap(in) int *INOUT = int *INPUT;
+%typemap(in) enum SWIGTYPE *INOUT = enum SWIGTYPE *INPUT;
+%typemap(in) short *INOUT = short *INPUT;
+%typemap(in) long *INOUT = long *INPUT;
+%typemap(in) long long *INOUT = long long *INPUT;
+%typemap(in) unsigned *INOUT = unsigned *INPUT;
+%typemap(in) unsigned short *INOUT = unsigned short *INPUT;
+%typemap(in) unsigned long *INOUT = unsigned long *INPUT;
+%typemap(in) unsigned long long *INOUT = unsigned long long *INPUT;
+%typemap(in) unsigned char *INOUT = unsigned char *INPUT;
+%typemap(in) char *INOUT = char *INPUT;
+%typemap(in) bool *INOUT = bool *INPUT;
+%typemap(in) float *INOUT = float *INPUT;
+%typemap(in) double *INOUT = double *INPUT;
+
+%typemap(in) int &INOUT = int &INPUT;
+%typemap(in) enum SWIGTYPE &INOUT = enum SWIGTYPE &INPUT;
+%typemap(in) short &INOUT = short &INPUT;
+%typemap(in) long &INOUT = long &INPUT;
+%typemap(in) long long &INOUT = long long &INPUT;
+%typemap(in) unsigned &INOUT = unsigned &INPUT;
+%typemap(in) unsigned short &INOUT = unsigned short &INPUT;
+%typemap(in) unsigned long &INOUT = unsigned long &INPUT;
+%typemap(in) unsigned long long &INOUT = unsigned long long &INPUT;
+%typemap(in) unsigned char &INOUT = unsigned char &INPUT;
+%typemap(in) char &INOUT = char &INPUT;
+%typemap(in) bool &INOUT = bool &INPUT;
+%typemap(in) float &INOUT = float &INPUT;
+%typemap(in) double &INOUT = double &INPUT;
+
+%typemap(argout) int *INOUT = int *OUTPUT;
+%typemap(argout) enum SWIGTYPE *INOUT = enum SWIGTYPE *OUTPUT;
+%typemap(argout) short *INOUT = short *OUTPUT;
+%typemap(argout) long *INOUT = long *OUTPUT;
+%typemap(argout) long long *INOUT = long long *OUTPUT;
+%typemap(argout) unsigned *INOUT = unsigned *OUTPUT;
+%typemap(argout) unsigned short *INOUT = unsigned short *OUTPUT;
+%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT;
+%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT;
+%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT;
+%typemap(argout) bool *INOUT = bool *OUTPUT;
+%typemap(argout) float *INOUT = float *OUTPUT;
+%typemap(argout) double *INOUT = double *OUTPUT;
+
+%typemap(argout) int &INOUT = int &OUTPUT;
+%typemap(argout) enum SWIGTYPE &INOUT = enum SWIGTYPE &OUTPUT;
+%typemap(argout) short &INOUT = short &OUTPUT;
+%typemap(argout) long &INOUT = long &OUTPUT;
+%typemap(argout) long long &INOUT = long long &OUTPUT;
+%typemap(argout) unsigned &INOUT = unsigned &OUTPUT;
+%typemap(argout) unsigned short &INOUT = unsigned short &OUTPUT;
+%typemap(argout) unsigned long &INOUT = unsigned long &OUTPUT;
+%typemap(argout) unsigned long long &INOUT = unsigned long long &OUTPUT;
+%typemap(argout) unsigned char &INOUT = unsigned char &OUTPUT;
+%typemap(argout) char &INOUT = char &OUTPUT;
+%typemap(argout) bool &INOUT = bool &OUTPUT;
+%typemap(argout) float &INOUT = float &OUTPUT;
+%typemap(argout) double &INOUT = double &OUTPUT;
+
+/* Overloading information */
+
+%typemap(typecheck) double *INOUT = double;
+%typemap(typecheck) bool *INOUT = bool;
+%typemap(typecheck) char *INOUT = char;
+%typemap(typecheck) signed char *INOUT = signed char;
+%typemap(typecheck) unsigned char *INOUT = unsigned char;
+%typemap(typecheck) unsigned long *INOUT = unsigned long;
+%typemap(typecheck) unsigned long long *INOUT = unsigned long long;
+%typemap(typecheck) unsigned short *INOUT = unsigned short;
+%typemap(typecheck) unsigned int *INOUT = unsigned int;
+%typemap(typecheck) long *INOUT = long;
+%typemap(typecheck) long long *INOUT = long long;
+%typemap(typecheck) short *INOUT = short;
+%typemap(typecheck) int *INOUT = int;
+%typemap(typecheck) enum SWIGTYPE *INOUT = enum SWIGTYPE;
+%typemap(typecheck) float *INOUT = float;
+
+%typemap(typecheck) double &INOUT = double;
+%typemap(typecheck) bool &INOUT = bool;
+%typemap(typecheck) char &INOUT = char;
+%typemap(typecheck) signed char &INOUT = signed char;
+%typemap(typecheck) unsigned char &INOUT = unsigned char;
+%typemap(typecheck) unsigned long &INOUT = unsigned long;
+%typemap(typecheck) unsigned long long &INOUT = unsigned long long;
+%typemap(typecheck) unsigned short &INOUT = unsigned short;
+%typemap(typecheck) unsigned int &INOUT = unsigned int;
+%typemap(typecheck) long &INOUT = long;
+%typemap(typecheck) long long &INOUT = long long;
+%typemap(typecheck) short &INOUT = short;
+%typemap(typecheck) int &INOUT = int;
+%typemap(typecheck) enum SWIGTYPE &INOUT = enum SWIGTYPE;
+%typemap(typecheck) float &INOUT = float;
diff --git a/trunk/Lib/clisp/clisp.swg b/trunk/Lib/clisp/clisp.swg
new file mode 100644
index 0000000..fb6cdbf
--- /dev/null
+++ b/trunk/Lib/clisp/clisp.swg
@@ -0,0 +1,35 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * clisp.swg
+ * ----------------------------------------------------------------------------- */
+
+/* Define a C preprocessor symbol that can be used in interface files
+   to distinguish between the SWIG language modules. */ 
+
+#define SWIG_CLISP
+
+/* Typespecs for basic types. */
+
+%typemap(in) void "NIL";
+
+%typemap(in) char "character";
+%typemap(in) char * "ffi:c-string";
+%typemap(in) unsigned char "ffi:uchar";
+%typemap(in) signed char "ffi:char";
+
+%typemap(in) short "ffi:short";
+%typemap(in) signed short "ffi:short";
+%typemap(in) unsigned short "ffi:ushort";
+
+%typemap(in) int "ffi:int";
+%typemap(in) signed int "ffi:int";
+%typemap(in) unsigned int "ffi:uint";
+
+%typemap(in) long "ffi:long";
+%typemap(in) signed long "ffi:long";
+%typemap(in) unsigned long "ffi:ulong";
+
+%typemap(in) float "SINGLE-FLOAT";
+%typemap(in) double "DOUBLE-FLOAT";
diff --git a/trunk/Lib/cmalloc.i b/trunk/Lib/cmalloc.i
new file mode 100644
index 0000000..03a6135
--- /dev/null
+++ b/trunk/Lib/cmalloc.i
@@ -0,0 +1,113 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cmalloc.i
+ *
+ * SWIG library file containing macros that can be used to create objects using
+ * the C malloc function.
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <stdlib.h>
+%}
+
+/* %malloc(TYPE [, NAME = TYPE])
+   %calloc(TYPE [, NAME = TYPE])
+   %realloc(TYPE [, NAME = TYPE])
+   %free(TYPE [, NAME = TYPE])
+   %allocators(TYPE [,NAME = TYPE])
+
+   Creates functions for allocating/reallocating memory.
+
+   TYPE *malloc_NAME(int nbytes = sizeof(TYPE);
+   TYPE *calloc_NAME(int nobj=1, int size=sizeof(TYPE));
+   TYPE *realloc_NAME(TYPE *ptr, int nbytes);
+   void free_NAME(TYPE *ptr);
+
+*/
+
+%define %malloc(TYPE,NAME...)
+#if #NAME != ""
+%rename(malloc_##NAME) ::malloc(int nbytes);
+#else
+%rename(malloc_##TYPE) ::malloc(int nbytes);
+#endif
+
+#if #TYPE != "void"
+%typemap(default) int nbytes "$1 = (int) sizeof(TYPE);"
+#endif
+TYPE *malloc(int nbytes);
+%typemap(default) int nbytes;
+%enddef
+
+%define %calloc(TYPE,NAME...)
+#if #NAME != ""
+%rename(calloc_##NAME) ::calloc(int nobj, int sz);
+#else
+%rename(calloc_##TYPE) ::calloc(int nobj, int sz);
+#endif
+#if #TYPE != "void"
+%typemap(default) int sz "$1 = (int) sizeof(TYPE);"
+#else
+%typemap(default) int sz "$1 = 1;"
+#endif
+%typemap(default) int nobj "$1 = 1;"
+TYPE *calloc(int nobj, int sz);
+%typemap(default) int sz;
+%typemap(default) int nobj;
+%enddef
+
+%define %realloc(TYPE,NAME...)
+%insert("header") {
+#if #NAME != ""
+TYPE *realloc_##NAME(TYPE *ptr, int nitems)
+#else
+TYPE *realloc_##TYPE(TYPE *ptr, int nitems)
+#endif
+{
+#if #TYPE != "void"
+return (TYPE *) realloc(ptr, nitems*sizeof(TYPE));
+#else
+return (TYPE *) realloc(ptr, nitems);
+#endif
+}
+}
+#if #NAME != ""
+TYPE *realloc_##NAME(TYPE *ptr, int nitems);
+#else
+TYPE *realloc_##TYPE(TYPE *ptr, int nitems);
+#endif
+%enddef
+
+%define %free(TYPE,NAME...)
+#if #NAME != ""
+%rename(free_##NAME) ::free(TYPE *ptr);
+#else
+%rename(free_##TYPE) ::free(TYPE *ptr);
+#endif
+void free(TYPE *ptr);
+%enddef
+
+%define %sizeof(TYPE,NAME...)
+#if #NAME != ""
+%constant int sizeof_##NAME = sizeof(TYPE);
+#else
+%constant int sizeof_##TYPE = sizeof(TYPE);
+#endif
+%enddef
+
+%define %allocators(TYPE,NAME...)
+%malloc(TYPE,NAME)
+%calloc(TYPE,NAME)
+%realloc(TYPE,NAME)
+%free(TYPE,NAME)
+#if #TYPE != "void"
+%sizeof(TYPE,NAME)
+#endif
+%enddef
+
+
+
+
+
diff --git a/trunk/Lib/constraints.i b/trunk/Lib/constraints.i
new file mode 100644
index 0000000..2deb116
--- /dev/null
+++ b/trunk/Lib/constraints.i
@@ -0,0 +1,227 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * constraints.i
+ *
+ * SWIG constraints library.
+ *
+ * SWIG library file containing typemaps for implementing various kinds of 
+ * constraints.  Depends upon the SWIG exception library for generating
+ * errors in a language-independent manner.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef AUTODOC
+%text %{
+%include <constraints.i>
+
+This library provides support for applying constraints to function
+arguments.  Using a constraint, you can restrict arguments to be
+positive numbers, non-NULL pointers, and so on.   The following
+constraints are available :
+
+      Number  POSITIVE        - Positive number (not zero)
+      Number  NEGATIVE        - Negative number (not zero)
+      Number  NONZERO         - Nonzero number
+      Number  NONNEGATIVE     - Positive number (including zero)
+      Number  NONPOSITIVE     - Negative number (including zero)
+      Pointer NONNULL         - Non-NULL pointer
+      Pointer ALIGN8          - 8-byte aligned pointer
+      Pointer ALIGN4          - 4-byte aligned pointer
+      Pointer ALIGN2          - 2-byte aligned pointer
+
+To use the constraints, you need to "apply" them to specific
+function arguments in your code.  This is done using the %apply
+directive.   For example :
+
+  %apply Number NONNEGATIVE { double nonneg };
+  double sqrt(double nonneg);         // Name of argument must match
+  
+  %apply Pointer NONNULL { void *ptr };
+  void *malloc(int POSITIVE);       // May return a NULL pointer
+  void free(void *ptr);             // May not accept a NULL pointer
+
+Any function argument of the type you specify with the %apply directive
+will be checked with the appropriate constraint.   Multiple types may
+be specified as follows :
+
+  %apply Pointer NONNULL { void *, Vector *, List *, double *};
+
+In this case, all of the types listed would be checked for non-NULL 
+pointers.
+
+The common datatypes of int, short, long, unsigned int, unsigned long,
+unsigned short, unsigned char, signed char, float, and double can be
+checked without using the %apply directive by simply using the 
+constraint name as the parameter name. For example :
+
+  double sqrt(double NONNEGATIVE);
+  double log(double POSITIVE);
+
+If you have used typedef to change type-names, you can also do this :
+
+  %apply double { Real };       // Make everything defined for doubles
+                                // work for Reals.
+  Real sqrt(Real NONNEGATIVE);
+  Real log(Real POSITIVE);
+
+%}
+#endif
+
+%include <exception.i>
+
+#ifdef SWIGCSHARP
+// Required attribute for C# exception handling
+#define SWIGCSHARPCANTHROW , canthrow=1
+#else
+#define SWIGCSHARPCANTHROW
+#endif
+
+
+// Positive numbers
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                int               POSITIVE,
+                short             POSITIVE,
+                long              POSITIVE,
+                unsigned int      POSITIVE,
+                unsigned short    POSITIVE,
+                unsigned long     POSITIVE,
+                signed char       POSITIVE,
+                unsigned char     POSITIVE,
+                float             POSITIVE,
+                double            POSITIVE,
+                Number            POSITIVE
+{
+  if ($1 <= 0) {
+    SWIG_exception(SWIG_ValueError,"Expected a positive value.");
+  }
+}
+
+// Negative numbers
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                int               NEGATIVE,
+                short             NEGATIVE,
+                long              NEGATIVE,
+                unsigned int      NEGATIVE,
+                unsigned short    NEGATIVE,
+                unsigned long     NEGATIVE,
+                signed char       NEGATIVE,
+                unsigned char     NEGATIVE,
+                float             NEGATIVE,
+                double            NEGATIVE,
+                Number            NEGATIVE
+{
+  if ($1 >= 0) {
+    SWIG_exception(SWIG_ValueError,"Expected a negative value.");
+  }
+}
+
+// Nonzero numbers
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                int               NONZERO,
+                short             NONZERO,
+                long              NONZERO,
+                unsigned int      NONZERO,
+                unsigned short    NONZERO,
+                unsigned long     NONZERO,
+                signed char       NONZERO,
+                unsigned char     NONZERO,
+                float             NONZERO,
+                double            NONZERO,
+                Number            NONZERO
+{
+  if ($1 == 0) {
+    SWIG_exception(SWIG_ValueError,"Expected a nonzero value.");
+  }
+}
+
+// Nonnegative numbers
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                int               NONNEGATIVE,
+                short             NONNEGATIVE,
+                long              NONNEGATIVE,
+                unsigned int      NONNEGATIVE,
+                unsigned short    NONNEGATIVE,
+                unsigned long     NONNEGATIVE,
+                signed char       NONNEGATIVE,
+                unsigned char     NONNEGATIVE,
+                float             NONNEGATIVE,
+                double            NONNEGATIVE,
+                Number            NONNEGATIVE
+{
+  if ($1 < 0) {
+    SWIG_exception(SWIG_ValueError,"Expected a non-negative value.");
+  }
+}
+
+// Nonpositive numbers
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                int               NONPOSITIVE,
+                short             NONPOSITIVE,
+                long              NONPOSITIVE,
+                unsigned int      NONPOSITIVE,
+                unsigned short    NONPOSITIVE,
+                unsigned long     NONPOSITIVE,
+                signed char       NONPOSITIVE,
+                unsigned char     NONPOSITIVE,
+                float             NONPOSITIVE,
+                double            NONPOSITIVE,
+                Number            NONPOSITIVE
+{
+  if ($1 > 0) {
+    SWIG_exception(SWIG_ValueError,"Expected a non-positive value.");
+  }
+}
+                
+// Non-NULL pointer
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                void *            NONNULL,
+                Pointer           NONNULL
+{
+  if (!$1) {
+    SWIG_exception(SWIG_ValueError,"Received a NULL pointer.");
+  }
+}
+
+// Aligned pointers
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                void *            ALIGN8,
+                Pointer           ALIGN8
+{
+   unsigned long long tmp;
+   tmp = (unsigned long long) $1;
+   if (tmp & 7) {
+     SWIG_exception(SWIG_ValueError,"Pointer must be 8-byte aligned.");
+   }
+}
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                void *            ALIGN4,
+                Pointer           ALIGN4
+{
+   unsigned long long tmp;
+   tmp = (unsigned long long) $1;
+   if (tmp & 3) {
+     SWIG_exception(SWIG_ValueError,"Pointer must be 4-byte aligned.");
+   }
+}
+
+%typemap(check SWIGCSHARPCANTHROW) 
+                void *            ALIGN2,
+                Pointer           ALIGN2
+{
+   unsigned long long tmp;
+   tmp = (unsigned long long) $1;
+   if (tmp & 1) {
+     SWIG_exception(SWIG_ValueError,"Pointer must be 2-byte aligned.");
+   }
+}
+
+
diff --git a/trunk/Lib/cpointer.i b/trunk/Lib/cpointer.i
new file mode 100644
index 0000000..1a6e517
--- /dev/null
+++ b/trunk/Lib/cpointer.i
@@ -0,0 +1,183 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cpointer.i
+ *
+ * SWIG library file containing macros that can be used to manipulate simple
+ * pointer objects.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * %pointer_class(type,name)
+ *
+ * Places a simple proxy around a simple type like 'int', 'float', or whatever.
+ * The proxy provides this interface:
+ *
+ *       class type {
+ *       public:
+ *           type();
+ *          ~type();
+ *           type value();
+ *           void assign(type value);
+ *       };
+ *         
+ * Example:
+ *
+ *    %pointer_class(int, intp);
+ *
+ *    int add(int *x, int *y) { return *x + *y; }
+ *
+ * In python (with proxies)
+ *
+ *    >>> a = intp()
+ *    >>> a.assign(10)
+ *    >>> a.value()
+ *    10
+ *    >>> b = intp()
+ *    >>> b.assign(20)
+ *    >>> print add(a,b)
+ *    30
+ *
+ * As a general rule, this macro should not be used on class/structures that
+ * are already defined in the interface.
+ * ----------------------------------------------------------------------------- */
+
+
+%define %pointer_class(TYPE, NAME)
+%{
+typedef TYPE NAME;
+%}
+
+typedef struct {
+} NAME;
+
+%extend NAME {
+#ifdef __cplusplus
+NAME() {
+  return new TYPE();
+}
+~NAME() {
+  if (self) delete self;
+}
+#else
+NAME() {
+  return (TYPE *) calloc(1,sizeof(TYPE));
+}
+~NAME() {
+  if (self) free(self);
+}
+#endif
+}
+
+%extend NAME {
+
+void assign(TYPE value) {
+  *self = value;
+}
+TYPE value() {
+  return *self;
+}
+TYPE * cast() {
+  return self;
+}
+static NAME * frompointer(TYPE *t) {
+  return (NAME *) t;
+}
+
+}
+
+%types(NAME = TYPE);
+
+%enddef
+
+/* ----------------------------------------------------------------------------- 
+ * %pointer_functions(type,name)
+ *
+ * Create functions for allocating/deallocating pointers.   This can be used
+ * if you don't want to create a proxy class or if the pointer is complex.
+ *
+ *    %pointer_functions(int, intp)
+ *
+ *    int add(int *x, int *y) { return *x + *y; }
+ *
+ * In python (with proxies)
+ *
+ *    >>> a = copy_intp(10)
+ *    >>> intp_value(a)
+ *    10
+ *    >>> b = new_intp()
+ *    >>> intp_assign(b,20)
+ *    >>> print add(a,b)
+ *    30
+ *    >>> delete_intp(a)
+ *    >>> delete_intp(b)
+ * 
+ * ----------------------------------------------------------------------------- */
+
+%define %pointer_functions(TYPE,NAME)
+%{
+static TYPE *new_##NAME() { %}
+#ifdef __cplusplus
+%{  return new TYPE(); %}
+#else
+%{  return (TYPE *) calloc(1,sizeof(TYPE)); %}
+#endif
+%{}
+
+static TYPE *copy_##NAME(TYPE value) { %}
+#ifdef __cplusplus
+%{  return new TYPE(value); %}
+#else
+%{  TYPE *self = (TYPE *) calloc(1,sizeof(TYPE));
+  *self = value;
+  return self; %}
+#endif
+%{}
+
+static void delete_##NAME(TYPE *self) { %}
+#ifdef __cplusplus
+%{  if (self) delete self; %}
+#else
+%{  if (self) free(self); %}
+#endif
+%{}
+
+static void NAME ##_assign(TYPE *self, TYPE value) {
+  *self = value;
+}
+
+static TYPE NAME ##_value(TYPE *self) {
+  return *self;
+}
+%}
+
+TYPE *new_##NAME();
+TYPE *copy_##NAME(TYPE value);
+void  delete_##NAME(TYPE *self);
+void  NAME##_assign(TYPE *self, TYPE value);
+TYPE  NAME##_value(TYPE *self);
+
+%enddef
+
+/* -----------------------------------------------------------------------------
+ * %pointer_cast(type1,type2,name)
+ *
+ * Generates a pointer casting function.
+ * ----------------------------------------------------------------------------- */
+
+%define %pointer_cast(TYPE1,TYPE2,NAME)
+%inline %{
+TYPE2 NAME(TYPE1 x) {
+   return (TYPE2) x;
+}
+%}
+%enddef
+
+
+
+
+
+
+
+
diff --git a/trunk/Lib/csharp/boost_shared_ptr.i b/trunk/Lib/csharp/boost_shared_ptr.i
new file mode 100644
index 0000000..47fbaba
--- /dev/null
+++ b/trunk/Lib/csharp/boost_shared_ptr.i
@@ -0,0 +1,229 @@
+%include <shared_ptr.i>
+
+%define SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, CONST, TYPE...)
+
+%naturalvar TYPE;
+%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+
+// destructor mods
+%feature("unref") TYPE 
+//"if (debug_shared) { cout << \"deleting use_count: \" << (*smartarg1).use_count() << \" [\" << (boost::get_deleter<SWIG_null_deleter>(*smartarg1) ? std::string(\"CANNOT BE DETERMINED SAFELY\") : ( (*smartarg1).get() ? (*smartarg1)->getValue() : std::string(\"NULL PTR\") )) << \"]\" << endl << flush; }\n"
+                               "(void)arg1; delete smartarg1;"
+
+
+// plain value
+%typemap(in, canthrow=1) CONST TYPE ($&1_type argp = 0) %{
+  argp = ((SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input) ? ((SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input)->get() : 0;
+  if (!argp) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Attempt to dereference null $1_type", 0);
+    return $null;
+  }
+  $1 = *argp; %}
+%typemap(out) CONST TYPE 
+%{ $result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)); %}
+
+// plain pointer
+%typemap(in, canthrow=1) CONST TYPE * (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{
+  smartarg = (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input;
+  $1 = (TYPE *)(smartarg ? smartarg->get() : 0); %}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE * %{
+  $result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0;
+%}
+
+// plain reference
+%typemap(in, canthrow=1) CONST TYPE & %{
+  $1 = ($1_ltype)(((SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input) ? ((SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input)->get() : 0);
+  if(!$1) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type reference is null", 0);
+    return $null;
+  } %}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE &
+%{ $result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner); %}
+
+// plain pointer by reference
+%typemap(in) CONST TYPE *& ($*1_ltype temp = 0)
+%{ temp = (((SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input) ? ((SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)$input)->get() : 0);
+   $1 = &temp; %}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE *&
+%{ $result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner); %}
+
+// shared_ptr by value
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >
+%{ if ($input) $1 = *($&1_ltype)$input; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >
+%{ $result = $1 ? new $1_ltype($1) : 0; %}
+
+// shared_ptr by reference
+%typemap(in, canthrow=1) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & ($*1_ltype tempnull)
+%{ $1 = $input ? ($1_ltype)$input : &tempnull; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &
+%{ $result = *$1 ? new $*1_ltype(*$1) : 0; %} 
+
+// shared_ptr by pointer
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * ($*1_ltype tempnull)
+%{ $1 = $input ? ($1_ltype)$input : &tempnull; %}
+%typemap(out, fragment="SWIG_null_deleter") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *
+%{ $result = ($1 && *$1) ? new $*1_ltype(*($1_ltype)$1) : 0;
+   if ($owner) delete $1; %}
+
+// shared_ptr by pointer reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempnull, $*1_ltype temp = 0)
+%{ temp = $input ? *($1_ltype)&$input : &tempnull;
+   $1 = &temp; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *&
+%{ *($1_ltype)&$result = (*$1 && **$1) ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(**$1) : 0; %} 
+
+// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug
+%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+
+
+%typemap (ctype)  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "void *"
+%typemap (imtype, out="IntPtr") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                                SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                                SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                                SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "HandleRef"
+%typemap (cstype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "PROXYCLASS"
+
+%typemap(csin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+               SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+               SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+               SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "PROXYCLASS.getCPtr($csinput)"
+
+%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+    IntPtr cPtr = $imcall;
+    PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & {
+    IntPtr cPtr = $imcall;
+    PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * {
+    IntPtr cPtr = $imcall;
+    PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& {
+    IntPtr cPtr = $imcall;
+    PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+    return ret;
+  }
+
+
+%typemap(csout, excode=SWIGEXCODE) CONST TYPE {
+    PROXYCLASS ret = new PROXYCLASS($imcall, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) CONST TYPE & {
+    PROXYCLASS ret = new PROXYCLASS($imcall, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) CONST TYPE * {
+    IntPtr cPtr = $imcall;
+    PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) CONST TYPE *& {
+    IntPtr cPtr = $imcall;
+    PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) CONST TYPE & %{
+    get {
+      $csclassname ret = new $csclassname($imcall, true);$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) CONST TYPE * %{
+    get {
+      IntPtr cPtr = $imcall;
+      $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, true);$excode
+      return ret;
+    } %}
+
+%typemap(csvarout, excode=SWIGEXCODE2) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{
+    get {
+      IntPtr cPtr = $imcall;
+      PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{
+    get {
+      IntPtr cPtr = $imcall;
+      PROXYCLASS ret = (cPtr == IntPtr.Zero) ? null : new PROXYCLASS(cPtr, true);$excode
+      return ret;
+    } %}
+
+
+// Proxy classes (base classes, ie, not derived classes)
+%typemap(csbody) TYPE %{
+  private HandleRef swigCPtr;
+  private bool swigCMemOwnBase;
+
+  internal $csclassname(IntPtr cPtr, bool cMemoryOwn) {
+    swigCMemOwnBase = cMemoryOwn;
+    swigCPtr = new HandleRef(this, cPtr);
+  }
+
+  internal static HandleRef getCPtr($csclassname obj) {
+    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
+  }
+%}
+
+// Derived proxy classes
+%typemap(csbody_derived) TYPE %{
+  private HandleRef swigCPtr;
+  private bool swigCMemOwnDerived;
+
+  internal $csclassname(IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclassname_SWIGSharedPtrUpcast(cPtr), true) {
+    swigCMemOwnDerived = cMemoryOwn;
+    swigCPtr = new HandleRef(this, cPtr);
+  }
+
+  internal static HandleRef getCPtr($csclassname obj) {
+    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
+  }
+%}
+
+%typemap(csdestruct, methodname="Dispose", methodmodifiers="public") TYPE {
+    lock(this) {
+      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwnBase) {
+        swigCMemOwnBase = false;
+        $imcall;
+      }
+      swigCPtr = new HandleRef(null, IntPtr.Zero);
+      GC.SuppressFinalize(this);
+    }
+  }
+
+%typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") TYPE {
+    lock(this) {
+      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwnDerived) {
+        swigCMemOwnDerived = false;
+        $imcall;
+      }
+      swigCPtr = new HandleRef(null, IntPtr.Zero);
+      GC.SuppressFinalize(this);
+      base.Dispose();
+    }
+  }
+
+%typemap(imtype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "IntPtr"
+%typemap(csin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "PROXYCLASS.getCPtr($csinput).Handle"
+
+
+%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+%enddef
+
diff --git a/trunk/Lib/csharp/csharp.swg b/trunk/Lib/csharp/csharp.swg
new file mode 100644
index 0000000..35e5c26
--- /dev/null
+++ b/trunk/Lib/csharp/csharp.swg
@@ -0,0 +1,979 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * csharp.swg
+ *
+ * C# typemaps
+ * ----------------------------------------------------------------------------- */
+
+%include <csharphead.swg>
+
+/* The ctype, imtype and cstype typemaps work together and so there should be one of each. 
+ * The ctype typemap contains the PInvoke type used in the PInvoke (C/C++) code. 
+ * The imtype typemap contains the C# type used in the intermediary class. 
+ * The cstype typemap contains the C# type used in the C# proxy classes, type wrapper classes and module class. */
+
+
+/* Fragments */
+%fragment("SWIG_PackData", "header") {
+/* Pack binary data into a string */
+SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static const char hex[17] = "0123456789abcdef";
+  register const unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    register unsigned char uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+}
+
+%fragment("SWIG_UnPackData", "header") {
+/* Unpack binary data from a string */
+SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  register unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu = u + sz;
+  for (; u != eu; ++u) {
+    register char d = *(c++);
+    register unsigned char uu;
+    if ((d >= '0') && (d <= '9'))
+      uu = ((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = ((d - ('a'-10)) << 4);
+    else 
+      return (char *) 0;
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (d - ('a'-10));
+    else 
+      return (char *) 0;
+    *u = uu;
+  }
+  return c;
+}
+}
+
+/* Primitive types */
+%typemap(ctype) bool,               const bool &               "unsigned int"
+%typemap(ctype) char,               const char &               "char"
+%typemap(ctype) signed char,        const signed char &        "signed char"
+%typemap(ctype) unsigned char,      const unsigned char &      "unsigned char"
+%typemap(ctype) short,              const short &              "short"
+%typemap(ctype) unsigned short,     const unsigned short &     "unsigned short"
+%typemap(ctype) int,                const int &                "int"
+%typemap(ctype) unsigned int,       const unsigned int &       "unsigned int"
+%typemap(ctype) long,               const long &               "long"
+%typemap(ctype) unsigned long,      const unsigned long &      "unsigned long"
+%typemap(ctype) long long,          const long long &          "long long"
+%typemap(ctype) unsigned long long, const unsigned long long & "unsigned long long"
+%typemap(ctype) float,              const float &              "float"
+%typemap(ctype) double,             const double &             "double"
+%typemap(ctype) void                                           "void"
+
+%typemap(imtype) bool,               const bool &               "bool"
+%typemap(imtype) char,               const char &               "char"
+%typemap(imtype) signed char,        const signed char &        "sbyte"
+%typemap(imtype) unsigned char,      const unsigned char &      "byte"
+%typemap(imtype) short,              const short &              "short"
+%typemap(imtype) unsigned short,     const unsigned short &     "ushort"
+%typemap(imtype) int,                const int &                "int"
+%typemap(imtype) unsigned int,       const unsigned int &       "uint"
+%typemap(imtype) long,               const long &               "int"
+%typemap(imtype) unsigned long,      const unsigned long &      "uint"
+%typemap(imtype) long long,          const long long &          "long"
+%typemap(imtype) unsigned long long, const unsigned long long & "ulong"
+%typemap(imtype) float,              const float &              "float"
+%typemap(imtype) double,             const double &             "double"
+%typemap(imtype) void                                           "void"
+
+%typemap(cstype) bool,               const bool &               "bool"
+%typemap(cstype) char,               const char &               "char"
+%typemap(cstype) signed char,        const signed char &        "sbyte"
+%typemap(cstype) unsigned char,      const unsigned char &      "byte"
+%typemap(cstype) short,              const short &              "short"
+%typemap(cstype) unsigned short,     const unsigned short &     "ushort"
+%typemap(cstype) int,                const int &                "int"
+%typemap(cstype) unsigned int,       const unsigned int &       "uint"
+%typemap(cstype) long,               const long &               "int"
+%typemap(cstype) unsigned long,      const unsigned long &      "uint"
+%typemap(cstype) long long,          const long long &          "long"
+%typemap(cstype) unsigned long long, const unsigned long long & "ulong"
+%typemap(cstype) float,              const float &              "float"
+%typemap(cstype) double,             const double &             "double"
+%typemap(cstype) void                                           "void"
+
+%typemap(ctype) char *, char *&, char[ANY], char[]   "char *"
+%typemap(imtype) char *, char *&, char[ANY], char[]   "string"
+%typemap(cstype) char *, char *&, char[ANY], char[]   "string"
+
+/* Non primitive types */
+%typemap(ctype) SWIGTYPE "void *"
+%typemap(imtype, out="IntPtr") SWIGTYPE "HandleRef"
+%typemap(cstype) SWIGTYPE "$&csclassname"
+
+%typemap(ctype) SWIGTYPE [] "void *"
+%typemap(imtype, out="IntPtr") SWIGTYPE [] "HandleRef"
+%typemap(cstype) SWIGTYPE [] "$csclassname"
+
+%typemap(ctype) SWIGTYPE * "void *"
+%typemap(imtype, out="IntPtr") SWIGTYPE * "HandleRef"
+%typemap(cstype) SWIGTYPE * "$csclassname"
+
+%typemap(ctype) SWIGTYPE & "void *"
+%typemap(imtype, out="IntPtr") SWIGTYPE & "HandleRef"
+%typemap(cstype) SWIGTYPE & "$csclassname"
+
+/* pointer to a class member */
+%typemap(ctype) SWIGTYPE (CLASS::*) "char *"
+%typemap(imtype) SWIGTYPE (CLASS::*) "string"
+%typemap(cstype) SWIGTYPE (CLASS::*) "$csclassname"
+
+/* The following are the in and out typemaps. These are the PInvoke code generating typemaps for converting from C# to C and visa versa. */
+
+/* primitive types */
+%typemap(in) bool
+%{ $1 = $input ? true : false; %}
+
+%typemap(directorout) bool
+%{ $result = $input ? true : false; %}
+
+%typemap(csdirectorin) bool "$iminput"
+%typemap(csdirectorout) bool "$cscall"
+
+%typemap(in) char, 
+             signed char, 
+             unsigned char, 
+             short, 
+             unsigned short, 
+             int, 
+             unsigned int, 
+             long, 
+             unsigned long, 
+             long long, 
+             unsigned long long, 
+             float, 
+             double
+%{ $1 = ($1_ltype)$input; %}
+
+%typemap(directorout) char, 
+             signed char, 
+             unsigned char, 
+             short, 
+             unsigned short, 
+             int, 
+             unsigned int, 
+             long, 
+             unsigned long, 
+             long long, 
+             unsigned long long, 
+             float, 
+             double
+%{ $result = ($1_ltype)$input; %}
+
+%typemap(directorin) bool               "$input = $1;"
+%typemap(directorin) char               "$input = $1;"
+%typemap(directorin) signed char        "$input = $1;"
+%typemap(directorin) unsigned char      "$input = $1;"
+%typemap(directorin) short              "$input = $1;"
+%typemap(directorin) unsigned short     "$input = $1;"
+%typemap(directorin) int                "$input = $1;"
+%typemap(directorin) unsigned int       "$input = $1;"
+%typemap(directorin) long               "$input = $1;"
+%typemap(directorin) unsigned long      "$input = $1;"
+%typemap(directorin) long long          "$input = $1;"
+%typemap(directorin) unsigned long long "$input = $1;"
+%typemap(directorin) float              "$input = $1;"
+%typemap(directorin) double             "$input = $1;"
+
+%typemap(csdirectorin) char, 
+                       signed char, 
+                       unsigned char, 
+                       short, 
+                       unsigned short, 
+                       int, 
+                       unsigned int, 
+                       long, 
+                       unsigned long, 
+                       long long, 
+                       unsigned long long, 
+                       float, 
+                       double
+  "$iminput"
+
+%typemap(csdirectorout) char, 
+                        signed char, 
+                        unsigned char, 
+                        short, 
+                        unsigned short, 
+                        int, 
+                        unsigned int, 
+                        long, 
+                        unsigned long, 
+                        long long, 
+                        unsigned long long, 
+                        float, 
+                        double
+  "$cscall"
+
+%typemap(out) bool               %{ $result = $1; %}
+%typemap(out) char               %{ $result = $1; %}
+%typemap(out) signed char        %{ $result = $1; %}
+%typemap(out) unsigned char      %{ $result = $1; %}
+%typemap(out) short              %{ $result = $1; %}
+%typemap(out) unsigned short     %{ $result = $1; %}
+%typemap(out) int                %{ $result = $1; %}
+%typemap(out) unsigned int       %{ $result = $1; %}
+%typemap(out) long               %{ $result = $1; %}
+%typemap(out) unsigned long      %{ $result = (unsigned long)$1; %}
+%typemap(out) long long          %{ $result = $1; %}
+%typemap(out) unsigned long long %{ $result = $1; %}
+%typemap(out) float              %{ $result = $1; %}
+%typemap(out) double             %{ $result = $1; %}
+
+/* char * - treat as String */
+%typemap(in) char * %{ $1 = ($1_ltype)$input; %}
+%typemap(out) char * %{ $result = SWIG_csharp_string_callback((const char *)$1); %}
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) char * %{ $result = ($1_ltype)$input; %}
+%typemap(directorin) char * %{ $input = SWIG_csharp_string_callback((const char *)$1); %}
+%typemap(csdirectorin) char * "$iminput"
+%typemap(csdirectorout) char * "$cscall"
+
+/* char *& - treat as String */
+%typemap(in) char *& ($*1_ltype temp = 0) %{ 
+  temp = ($*1_ltype)$input;
+  $1 = &temp;
+%}
+%typemap(out) char *& %{ if ($1) $result = SWIG_csharp_string_callback((const char *)*$1); %}
+
+%typemap(out, null="") void ""
+%typemap(csdirectorin) void "$iminput"
+%typemap(csdirectorout) void "$cscall"
+%typemap(directorin) void ""
+
+/* primitive types by const reference */
+%typemap(in) const bool & ($*1_ltype temp)
+%{ temp = $input ? true : false; 
+   $1 = &temp; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const bool &
+%{ static $*1_ltype temp;
+   temp = $input ? true : false; 
+   $result = &temp; %}
+
+%typemap(csdirectorin) const bool & "$iminput"
+%typemap(csdirectorout) const bool & "$cscall"
+
+%typemap(in) const char & ($*1_ltype temp), 
+             const signed char & ($*1_ltype temp), 
+             const unsigned char & ($*1_ltype temp), 
+             const short & ($*1_ltype temp), 
+             const unsigned short & ($*1_ltype temp), 
+             const int & ($*1_ltype temp), 
+             const unsigned int & ($*1_ltype temp), 
+             const long & ($*1_ltype temp), 
+             const unsigned long & ($*1_ltype temp), 
+             const long long & ($*1_ltype temp), 
+             const unsigned long long & ($*1_ltype temp), 
+             const float & ($*1_ltype temp), 
+             const double & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const char &,
+             const signed char &,
+             const unsigned char &,
+             const short &,
+             const unsigned short &,
+             const int &,
+             const unsigned int &,
+             const long &,
+             const unsigned long &,
+             const long long &,
+             const float &,
+             const double &
+%{ static $*1_ltype temp;
+   temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+
+%typemap(directorin) const bool &           "$input = $1_name;"
+%typemap(directorin) const char &           "$input = $1_name;"
+%typemap(directorin) const signed char &    "$input = $1_name;"
+%typemap(directorin) const unsigned char &  "$input = $1_name;"
+%typemap(directorin) const short &          "$input = $1_name;"
+%typemap(directorin) const unsigned short & "$input = $1_name;"
+%typemap(directorin) const int &            "$input = $1_name;"
+%typemap(directorin) const unsigned int &   "$input = $1_name;"
+%typemap(directorin) const long &           "$input = $1_name;"
+%typemap(directorin) const unsigned long &  "$input = $1_name;"
+%typemap(directorin) const long long &      "$input = $1_name;"
+%typemap(directorin) const float &          "$input = $1_name;"
+%typemap(directorin) const double &         "$input = $1_name;"
+
+%typemap(csdirectorin) const char & ($*1_ltype temp), 
+                       const signed char & ($*1_ltype temp), 
+                       const unsigned char & ($*1_ltype temp), 
+                       const short & ($*1_ltype temp), 
+                       const unsigned short & ($*1_ltype temp), 
+                       const int & ($*1_ltype temp), 
+                       const unsigned int & ($*1_ltype temp), 
+                       const long & ($*1_ltype temp), 
+                       const unsigned long & ($*1_ltype temp), 
+                       const long long & ($*1_ltype temp), 
+                       const float & ($*1_ltype temp), 
+                       const double & ($*1_ltype temp)
+  "$iminput"
+
+%typemap(csdirectorout) const char & ($*1_ltype temp), 
+                        const signed char & ($*1_ltype temp), 
+                        const unsigned char & ($*1_ltype temp), 
+                        const short & ($*1_ltype temp), 
+                        const unsigned short & ($*1_ltype temp), 
+                        const int & ($*1_ltype temp), 
+                        const unsigned int & ($*1_ltype temp), 
+                        const long & ($*1_ltype temp), 
+                        const unsigned long & ($*1_ltype temp), 
+                        const long long & ($*1_ltype temp), 
+                        const float & ($*1_ltype temp), 
+                        const double & ($*1_ltype temp)
+  "$cscall"
+
+
+%typemap(out) const bool &               %{ $result = *$1; %}
+%typemap(out) const char &               %{ $result = *$1; %}
+%typemap(out) const signed char &        %{ $result = *$1; %}
+%typemap(out) const unsigned char &      %{ $result = *$1; %}
+%typemap(out) const short &              %{ $result = *$1; %}
+%typemap(out) const unsigned short &     %{ $result = *$1; %}
+%typemap(out) const int &                %{ $result = *$1; %}
+%typemap(out) const unsigned int &       %{ $result = *$1; %}
+%typemap(out) const long &               %{ $result = *$1; %}
+%typemap(out) const unsigned long &      %{ $result = (unsigned long)*$1; %}
+%typemap(out) const long long &          %{ $result = *$1; %}
+%typemap(out) const unsigned long long & %{ $result = *$1; %}
+%typemap(out) const float &              %{ $result = *$1; %}
+%typemap(out) const double &             %{ $result = *$1; %}
+
+/* Default handling. Object passed by value. Convert to a pointer */
+%typemap(in, canthrow=1) SWIGTYPE ($&1_type argp)
+%{ argp = ($&1_ltype)$input; 
+   if (!argp) {
+     SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Attempt to dereference null $1_type", 0);
+     return $null;
+   }
+   $1 = *argp; %}
+
+%typemap(directorout) SWIGTYPE
+%{ if (!$input) {
+     SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Unexpected null return for type $1_type", 0);
+     return $null;
+   }
+   $result = *($&1_ltype)$input; %}
+
+%typemap(out) SWIGTYPE 
+#ifdef __cplusplus
+%{ $result = new $1_ltype((const $1_ltype &)$1); %}
+#else
+{
+  $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype));
+  memmove($1ptr, &$1, sizeof($1_type));
+  $result = $1ptr;
+}
+#endif
+
+%typemap(directorin) SWIGTYPE 
+%{ $input = (void *)&$1; %}
+%typemap(csdirectorin) SWIGTYPE "new $&csclassname($iminput, false)"
+%typemap(csdirectorout) SWIGTYPE "$&csclassname.getCPtr($cscall).Handle"
+
+/* Generic pointers and references */
+%typemap(in) SWIGTYPE * %{ $1 = ($1_ltype)$input; %}
+%typemap(in, fragment="SWIG_UnPackData") SWIGTYPE (CLASS::*) %{ 
+  SWIG_UnpackData($input, (void *)&$1, sizeof($1));
+%}
+%typemap(in, canthrow=1) SWIGTYPE & %{ $1 = ($1_ltype)$input;
+  if(!$1) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "$1_type type is null", 0);
+    return $null;
+  } %}
+%typemap(out) SWIGTYPE * %{ $result = (void *)$1; %} 
+%typemap(out, fragment="SWIG_PackData") SWIGTYPE (CLASS::*) %{
+  char buf[128];
+  char *data = SWIG_PackData(buf, (void *)&$1, sizeof($1));
+  *data = '\0';
+  $result = SWIG_csharp_string_callback(buf);
+%}
+%typemap(out) SWIGTYPE & %{ $result = (void *)$1; %} 
+
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE *
+%{ $result = ($1_ltype)$input; %}
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE (CLASS::*)
+%{ $result = ($1_ltype)$input; %}
+
+%typemap(directorin) SWIGTYPE *
+%{ $input = (void *) $1; %}
+%typemap(directorin) SWIGTYPE (CLASS::*)
+%{ $input = (void *) $1; %}
+
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE &
+%{ if (!$input) {
+     SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "Unexpected null return for type $1_type", 0);
+     return $null;
+   }
+   $result = ($1_ltype)$input; %}
+%typemap(directorin) SWIGTYPE &
+%{ $input = ($1_ltype) &$1; %}
+
+%typemap(csdirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "new $csclassname($iminput, false)"
+%typemap(csdirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$csclassname.getCPtr($cscall).Handle"
+
+/* Default array handling */
+%typemap(in) SWIGTYPE [] %{ $1 = ($1_ltype)$input; %}
+%typemap(out) SWIGTYPE [] %{ $result = $1; %} 
+
+/* char arrays - treat as String */
+%typemap(in) char[ANY], char[] %{ $1 = ($1_ltype)$input; %}
+%typemap(out) char[ANY], char[] %{ $result = SWIG_csharp_string_callback((const char *)$1); %}
+
+%typemap(directorout) char[ANY], char[] %{ $result = ($1_ltype)$input; %}
+%typemap(directorin) char[ANY], char[] %{ $input = SWIG_csharp_string_callback((const char *)$1); %}
+
+%typemap(csdirectorin) char[ANY], char[] "$iminput"
+%typemap(csdirectorout) char[ANY], char[] "$cscall"
+
+
+/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions 
+ * that cannot be overloaded in C# as more than one C++ type maps to a single C# type */
+
+%typecheck(SWIG_TYPECHECK_BOOL)
+    bool,
+    const bool &
+    ""
+
+%typecheck(SWIG_TYPECHECK_CHAR)
+    char, 
+    const char &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT8)
+    signed char,
+    const signed char &
+    ""
+
+%typecheck(SWIG_TYPECHECK_UINT8)
+    unsigned char, 
+    const unsigned char & 
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT16)
+    short, 
+    const short &
+    ""
+
+%typecheck(SWIG_TYPECHECK_UINT16)
+    unsigned short, 
+    const unsigned short &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT32)
+    int, 
+    long, 
+    const int &, 
+    const long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_UINT32)
+    unsigned int, 
+    unsigned long, 
+    const unsigned int &, 
+    const unsigned long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT64)
+    long long, 
+    const long long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_UINT64)
+    unsigned long long,
+    const unsigned long long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT)
+    float,
+    const float &
+    ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE)
+    double,
+    const double &
+    ""
+
+%typecheck(SWIG_TYPECHECK_STRING)
+    char *,
+    char *&,
+    char[ANY],
+    char[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_POINTER)
+    SWIGTYPE, 
+    SWIGTYPE *, 
+    SWIGTYPE &, 
+    SWIGTYPE [],
+    SWIGTYPE (CLASS::*)
+    ""
+
+/* Exception handling */
+
+%typemap(throws, canthrow=1) int, 
+                 long, 
+                 short, 
+                 unsigned int, 
+                 unsigned long, 
+                 unsigned short
+%{ char error_msg[256];
+   sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1);
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, error_msg);
+   return $null; %}
+
+%typemap(throws, canthrow=1) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY]
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(throws, canthrow=1) char *
+%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1);
+   return $null; %}
+
+
+/* Typemaps for code generation in proxy classes and C# type wrapper classes */
+
+/* The csin typemap is used for converting function parameter types from the type 
+ * used in the proxy, module or type wrapper class to the type used in the PInvoke class. */
+%typemap(csin)   bool,               const bool &,
+                 char,               const char &,
+                 signed char,        const signed char &,
+                 unsigned char,      const unsigned char &,
+                 short,              const short &,
+                 unsigned short,     const unsigned short &,
+                 int,                const int &,
+                 unsigned int,       const unsigned int &,
+                 long,               const long &,
+                 unsigned long,      const unsigned long &,
+                 long long,          const long long &,
+                 unsigned long long, const unsigned long long &,
+                 float,              const float &,
+                 double,             const double &
+    "$csinput"
+%typemap(csin) char *, char *&, char[ANY], char[] "$csinput"
+%typemap(csin) SWIGTYPE "$&csclassname.getCPtr($csinput)"
+%typemap(csin) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$csclassname.getCPtr($csinput)"
+%typemap(csin) SWIGTYPE (CLASS::*) "$csclassname.getCMemberPtr($csinput)"
+
+/* The csout typemap is used for converting function return types from the return type
+ * used in the PInvoke class to the type returned by the proxy, module or type wrapper class.
+ * The $excode special variable is replaced by the excode typemap attribute code if the
+ * method can throw any exceptions from unmanaged code, otherwise replaced by nothing. */
+
+// Macro used by the $excode special variable
+%define SWIGEXCODE "\n    if ($imclassname.SWIGPendingException.Pending) throw $imclassname.SWIGPendingException.Retrieve();" %enddef
+%define SWIGEXCODE2 "\n      if ($imclassname.SWIGPendingException.Pending) throw $imclassname.SWIGPendingException.Retrieve();" %enddef
+
+%typemap(csout, excode=SWIGEXCODE) bool,               const bool &               {
+    bool ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) char,               const char &               {
+    char ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) signed char,        const signed char &        {
+    sbyte ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) unsigned char,      const unsigned char &      {
+    byte ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) short,              const short &              {
+    short ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) unsigned short,     const unsigned short &     {
+    ushort ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) int,                const int &                {
+    int ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) unsigned int,       const unsigned int &       {
+    uint ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) long,               const long &               {
+    int ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) unsigned long,      const unsigned long &      {
+    uint ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) long long,          const long long &          {
+    long ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) unsigned long long, const unsigned long long & {
+    ulong ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) float,              const float &              {
+    float ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) double,             const double &             {
+    double ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) char *, char *&, char[ANY], char[] {
+    string ret = $imcall;$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) void {
+    $imcall;$excode
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIGTYPE {
+    $&csclassname ret = new $&csclassname($imcall, true);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIGTYPE & {
+    $csclassname ret = new $csclassname($imcall, $owner);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIGTYPE *, SWIGTYPE [] {
+    IntPtr cPtr = $imcall;
+    $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode
+    return ret;
+  }
+%typemap(csout, excode=SWIGEXCODE) SWIGTYPE (CLASS::*) {
+    string cMemberPtr = $imcall;
+    $csclassname ret = (cMemberPtr == null) ? null : new $csclassname(cMemberPtr, $owner);$excode
+    return ret;
+  }
+
+
+/* Properties */
+%typemap(csvarin, excode=SWIGEXCODE2) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+    set {
+      $imcall;$excode
+    } %}
+
+%typemap(csvarin, excode=SWIGEXCODE2) char *, char *&, char[ANY], char[] %{
+    set {
+      $imcall;$excode
+    } %}
+
+%typemap(csvarout, excode=SWIGEXCODE2) bool,               const bool &               %{
+    get {
+      bool ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) char,               const char &               %{
+    get {
+      char ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) signed char,        const signed char &        %{
+    get {
+      sbyte ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) unsigned char,      const unsigned char &      %{
+    get {
+      byte ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) short,              const short &              %{
+    get {
+      short ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) unsigned short,     const unsigned short &     %{
+    get {
+      ushort ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) int,                const int &                %{
+    get {
+      int ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) unsigned int,       const unsigned int &       %{
+    get {
+      uint ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) long,               const long &               %{
+    get {
+      int ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) unsigned long,      const unsigned long &      %{
+    get {
+      uint ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) long long,          const long long &          %{
+    get {
+      long ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) unsigned long long, const unsigned long long & %{
+    get {
+      ulong ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) float,              const float &              %{
+    get {
+      float ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) double,             const double &             %{
+    get {
+      double ret = $imcall;$excode
+      return ret;
+    } %}
+
+
+%typemap(csvarout, excode=SWIGEXCODE2) char *, char *&, char[ANY], char[] %{
+    get {
+      string ret = $imcall;$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) void %{
+    get {
+      $imcall;$excode
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE %{
+    get {
+      $&csclassname ret = new $&csclassname($imcall, true);$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE & %{
+    get {
+      $csclassname ret = new $csclassname($imcall, $owner);$excode
+      return ret;
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE *, SWIGTYPE [] %{
+    get {
+      IntPtr cPtr = $imcall;
+      $csclassname ret = (cPtr == IntPtr.Zero) ? null : new $csclassname(cPtr, $owner);$excode
+      return ret;
+    } %}
+
+%typemap(csvarout, excode=SWIGEXCODE2) SWIGTYPE (CLASS::*) %{
+    get {
+      string cMemberPtr = $imcall;
+      $csclassname ret = (cMemberPtr == null) ? null : new $csclassname(cMemberPtr, $owner);$excode
+      return ret;
+    } %}
+
+/* Pointer reference typemaps */
+%typemap(ctype) SWIGTYPE *& "void *"
+%typemap(imtype, out="IntPtr") SWIGTYPE *& "HandleRef"
+%typemap(cstype) SWIGTYPE *& "$*csclassname"
+%typemap(csin) SWIGTYPE *& "$*csclassname.getCPtr($csinput)"
+%typemap(csout, excode=SWIGEXCODE) SWIGTYPE *& {
+    IntPtr cPtr = $imcall;
+    $*csclassname ret = (cPtr == IntPtr.Zero) ? null : new $*csclassname(cPtr, $owner);$excode
+    return ret;
+  }
+%typemap(in) SWIGTYPE *& ($*1_ltype temp = 0)
+%{ temp = ($*1_ltype)$input;
+   $1 = &temp; %}
+%typemap(out) SWIGTYPE *&
+%{ $result = (void *)*$1; %} 
+
+/* Array reference typemaps */
+%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) }
+
+/* Typemaps used for the generation of proxy and type wrapper class code */
+%typemap(csbase)                      SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(csclassmodifiers)            SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class"
+%typemap(cscode)                      SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(csimports)                   SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "\nusing System;\nusing System.Runtime.InteropServices;\n"
+%typemap(csinterfaces)                SWIGTYPE "IDisposable"
+%typemap(csinterfaces)                          SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(csinterfaces_derived)        SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+
+// Proxy classes (base classes, ie, not derived classes)
+%typemap(csbody) SWIGTYPE %{
+  private HandleRef swigCPtr;
+  protected bool swigCMemOwn;
+
+  internal $csclassname(IntPtr cPtr, bool cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = new HandleRef(this, cPtr);
+  }
+
+  internal static HandleRef getCPtr($csclassname obj) {
+    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
+  }
+%}
+
+// Derived proxy classes
+%typemap(csbody_derived) SWIGTYPE %{
+  private HandleRef swigCPtr;
+
+  internal $csclassname(IntPtr cPtr, bool cMemoryOwn) : base($imclassname.$csclassnameUpcast(cPtr), cMemoryOwn) {
+    swigCPtr = new HandleRef(this, cPtr);
+  }
+
+  internal static HandleRef getCPtr($csclassname obj) {
+    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
+  }
+%}
+
+// Typewrapper classes
+%typemap(csbody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] %{
+  private HandleRef swigCPtr;
+
+  internal $csclassname(IntPtr cPtr, bool futureUse) {
+    swigCPtr = new HandleRef(this, cPtr);
+  }
+
+  protected $csclassname() {
+    swigCPtr = new HandleRef(null, IntPtr.Zero);
+  }
+
+  internal static HandleRef getCPtr($csclassname obj) {
+    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
+  }
+%}
+
+%typemap(csbody) SWIGTYPE (CLASS::*) %{
+  private string swigCMemberPtr;
+
+  internal $csclassname(string cMemberPtr, bool futureUse) {
+    swigCMemberPtr = cMemberPtr;
+  }
+
+  protected $csclassname() {
+    swigCMemberPtr = null;
+  }
+
+  internal static string getCMemberPtr($csclassname obj) {
+    return obj.swigCMemberPtr;
+  }
+%}
+
+%typemap(csfinalize) SWIGTYPE %{
+  ~$csclassname() {
+    Dispose();
+  }
+%}
+
+%typemap(csconstruct, excode=SWIGEXCODE,directorconnect="\n    SwigDirectorConnect();") SWIGTYPE %{: this($imcall, true) {$excode$directorconnect
+  }
+%}
+
+%typemap(csdestruct, methodname="Dispose", methodmodifiers="public") SWIGTYPE {
+    lock(this) {
+      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
+        swigCMemOwn = false;
+        $imcall;
+      }
+      swigCPtr = new HandleRef(null, IntPtr.Zero);
+      GC.SuppressFinalize(this);
+    }
+  }
+
+%typemap(csdestruct_derived, methodname="Dispose", methodmodifiers="public") SWIGTYPE {
+    lock(this) {
+      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
+        swigCMemOwn = false;
+        $imcall;
+      }
+      swigCPtr = new HandleRef(null, IntPtr.Zero);
+      GC.SuppressFinalize(this);
+      base.Dispose();
+    }
+  }
+
+%typemap(directordisconnect, methodname="swigDirectorDisconnect") SWIGTYPE %{
+  protected void $methodname() {
+    swigCMemOwn = false;
+    $imcall;
+  }
+%}
+
+/* C# specific directives */
+#define %csconst(flag)              %feature("cs:const","flag")
+#define %csconstvalue(value)        %feature("cs:constvalue",value)
+#define %csenum(wrapapproach)       %feature("cs:enum","wrapapproach")
+#define %csmethodmodifiers          %feature("cs:methodmodifiers")
+#define %csnothrowexception         %feature("except")
+#define %csattributes               %feature("cs:attributes")
+
+%pragma(csharp) imclassclassmodifiers="class"
+%pragma(csharp) moduleclassmodifiers="public class"
+
+%pragma(csharp) moduleimports=%{
+using System;
+using System.Runtime.InteropServices;
+%}
+
+%pragma(csharp) imclassimports=%{
+using System;
+using System.Runtime.InteropServices;
+%}
+
+/* Some ANSI C typemaps */
+
+%apply unsigned long { size_t };
+%apply const unsigned long & { const size_t & };
+
+/* csharp keywords */
+%include <csharpkw.swg>
+
+// Default enum handling
+%include <enums.swg>
+
+/*
+// Alternative char * typemaps.
+%pragma(csharp) imclasscode=%{
+  public class SWIGStringMarshal : IDisposable {
+    public readonly HandleRef swigCPtr;
+    public SWIGStringMarshal(string str) {
+      swigCPtr = new HandleRef(this, System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(str));
+    }
+    public virtual void Dispose() {
+      System.Runtime.InteropServices.Marshal.FreeHGlobal(swigCPtr.Handle);
+      GC.SuppressFinalize(this);
+    }
+  }
+%}
+
+%typemap(imtype, out="IntPtr") char *, char[ANY], char[]   "HandleRef"
+%typemap(out) char *, char[ANY], char[] %{ $result = $1; %}
+%typemap(csin) char *, char[ANY], char[] "new $imclassname.SWIGStringMarshal($csinput).swigCPtr"
+%typemap(csout, excode=SWIGEXCODE) char *, char[ANY], char[] {
+    string ret = System.Runtime.InteropServices.Marshal.PtrToStringAnsi($imcall);$excode
+    return ret;
+  }
+%typemap(csvarin, excode=SWIGEXCODE2) char *, char[ANY], char[] %{
+    set {
+      $imcall;$excode
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) char *, char[ANY], char[] %{
+    get {
+      string ret = System.Runtime.InteropServices.Marshal.PtrToStringAnsi($imcall);$excode
+      return ret;
+    } %}
+*/
+
diff --git a/trunk/Lib/csharp/csharphead.swg b/trunk/Lib/csharp/csharphead.swg
new file mode 100644
index 0000000..ffff703
--- /dev/null
+++ b/trunk/Lib/csharp/csharphead.swg
@@ -0,0 +1,329 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * csharphead.swg
+ *
+ * Support code for exceptions if the SWIG_CSHARP_NO_EXCEPTION_HELPER is not defined
+ * Support code for strings if the SWIG_CSHARP_NO_STRING_HELPER is not defined
+ * ----------------------------------------------------------------------------- */
+
+%insert(runtime) %{
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+%}
+
+#if !defined(SWIG_CSHARP_NO_EXCEPTION_HELPER)
+%insert(runtime) %{
+/* Support for throwing C# exceptions from C/C++. There are two types: 
+ * Exceptions that take a message and ArgumentExceptions that take a message and a parameter name. */
+typedef enum {
+  SWIG_CSharpApplicationException,
+  SWIG_CSharpArithmeticException,
+  SWIG_CSharpDivideByZeroException,
+  SWIG_CSharpIndexOutOfRangeException,
+  SWIG_CSharpInvalidCastException,
+  SWIG_CSharpInvalidOperationException,
+  SWIG_CSharpIOException,
+  SWIG_CSharpNullReferenceException,
+  SWIG_CSharpOutOfMemoryException,
+  SWIG_CSharpOverflowException,
+  SWIG_CSharpSystemException
+} SWIG_CSharpExceptionCodes;
+
+typedef enum {
+  SWIG_CSharpArgumentException,
+  SWIG_CSharpArgumentNullException,
+  SWIG_CSharpArgumentOutOfRangeException
+} SWIG_CSharpExceptionArgumentCodes;
+
+typedef void (SWIGSTDCALL* SWIG_CSharpExceptionCallback_t)(const char *);
+typedef void (SWIGSTDCALL* SWIG_CSharpExceptionArgumentCallback_t)(const char *, const char *);
+
+typedef struct {
+  SWIG_CSharpExceptionCodes code;
+  SWIG_CSharpExceptionCallback_t callback;
+} SWIG_CSharpException_t;
+
+typedef struct {
+  SWIG_CSharpExceptionArgumentCodes code;
+  SWIG_CSharpExceptionArgumentCallback_t callback;
+} SWIG_CSharpExceptionArgument_t;
+
+static SWIG_CSharpException_t SWIG_csharp_exceptions[] = {
+  { SWIG_CSharpApplicationException, NULL },
+  { SWIG_CSharpArithmeticException, NULL },
+  { SWIG_CSharpDivideByZeroException, NULL },
+  { SWIG_CSharpIndexOutOfRangeException, NULL },
+  { SWIG_CSharpInvalidCastException, NULL },
+  { SWIG_CSharpInvalidOperationException, NULL },
+  { SWIG_CSharpIOException, NULL },
+  { SWIG_CSharpNullReferenceException, NULL },
+  { SWIG_CSharpOutOfMemoryException, NULL },
+  { SWIG_CSharpOverflowException, NULL },
+  { SWIG_CSharpSystemException, NULL }
+};
+
+static SWIG_CSharpExceptionArgument_t SWIG_csharp_exceptions_argument[] = {
+  { SWIG_CSharpArgumentException, NULL },
+  { SWIG_CSharpArgumentNullException, NULL },
+  { SWIG_CSharpArgumentOutOfRangeException, NULL },
+};
+
+static void SWIGUNUSED SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code, const char *msg) {
+  SWIG_CSharpExceptionCallback_t callback = SWIG_csharp_exceptions[SWIG_CSharpApplicationException].callback;
+  if ((size_t)code < sizeof(SWIG_csharp_exceptions)/sizeof(SWIG_CSharpException_t)) {
+    callback = SWIG_csharp_exceptions[code].callback;
+  }
+  callback(msg);
+}
+
+static void SWIGUNUSED SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code, const char *msg, const char *param_name) {
+  SWIG_CSharpExceptionArgumentCallback_t callback = SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentException].callback;
+  if ((size_t)code < sizeof(SWIG_csharp_exceptions_argument)/sizeof(SWIG_CSharpExceptionArgument_t)) {
+    callback = SWIG_csharp_exceptions_argument[code].callback;
+  }
+  callback(msg, param_name);
+}
+%}
+
+%insert(runtime) %{
+#ifdef __cplusplus
+extern "C" 
+#endif
+SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionCallbacks_$module(
+                                                SWIG_CSharpExceptionCallback_t applicationCallback,
+                                                SWIG_CSharpExceptionCallback_t arithmeticCallback,
+                                                SWIG_CSharpExceptionCallback_t divideByZeroCallback, 
+                                                SWIG_CSharpExceptionCallback_t indexOutOfRangeCallback, 
+                                                SWIG_CSharpExceptionCallback_t invalidCastCallback,
+                                                SWIG_CSharpExceptionCallback_t invalidOperationCallback,
+                                                SWIG_CSharpExceptionCallback_t ioCallback,
+                                                SWIG_CSharpExceptionCallback_t nullReferenceCallback,
+                                                SWIG_CSharpExceptionCallback_t outOfMemoryCallback, 
+                                                SWIG_CSharpExceptionCallback_t overflowCallback, 
+                                                SWIG_CSharpExceptionCallback_t systemCallback) {
+  SWIG_csharp_exceptions[SWIG_CSharpApplicationException].callback = applicationCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpArithmeticException].callback = arithmeticCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpDivideByZeroException].callback = divideByZeroCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpIndexOutOfRangeException].callback = indexOutOfRangeCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpInvalidCastException].callback = invalidCastCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpInvalidOperationException].callback = invalidOperationCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpIOException].callback = ioCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpNullReferenceException].callback = nullReferenceCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpOutOfMemoryException].callback = outOfMemoryCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpOverflowException].callback = overflowCallback;
+  SWIG_csharp_exceptions[SWIG_CSharpSystemException].callback = systemCallback;
+}
+
+#ifdef __cplusplus
+extern "C" 
+#endif
+SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_$module(
+                                                SWIG_CSharpExceptionArgumentCallback_t argumentCallback,
+                                                SWIG_CSharpExceptionArgumentCallback_t argumentNullCallback,
+                                                SWIG_CSharpExceptionArgumentCallback_t argumentOutOfRangeCallback) {
+  SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentException].callback = argumentCallback;
+  SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentNullException].callback = argumentNullCallback;
+  SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentOutOfRangeException].callback = argumentOutOfRangeCallback;
+}
+%}
+
+%pragma(csharp) imclasscode=%{
+  protected class SWIGExceptionHelper {
+
+    public delegate void ExceptionDelegate(string message);
+    public delegate void ExceptionArgumentDelegate(string message, string paramName);
+
+    static ExceptionDelegate applicationDelegate = new ExceptionDelegate(SetPendingApplicationException);
+    static ExceptionDelegate arithmeticDelegate = new ExceptionDelegate(SetPendingArithmeticException);
+    static ExceptionDelegate divideByZeroDelegate = new ExceptionDelegate(SetPendingDivideByZeroException);
+    static ExceptionDelegate indexOutOfRangeDelegate = new ExceptionDelegate(SetPendingIndexOutOfRangeException);
+    static ExceptionDelegate invalidCastDelegate = new ExceptionDelegate(SetPendingInvalidCastException);
+    static ExceptionDelegate invalidOperationDelegate = new ExceptionDelegate(SetPendingInvalidOperationException);
+    static ExceptionDelegate ioDelegate = new ExceptionDelegate(SetPendingIOException);
+    static ExceptionDelegate nullReferenceDelegate = new ExceptionDelegate(SetPendingNullReferenceException);
+    static ExceptionDelegate outOfMemoryDelegate = new ExceptionDelegate(SetPendingOutOfMemoryException);
+    static ExceptionDelegate overflowDelegate = new ExceptionDelegate(SetPendingOverflowException);
+    static ExceptionDelegate systemDelegate = new ExceptionDelegate(SetPendingSystemException);
+
+    static ExceptionArgumentDelegate argumentDelegate = new ExceptionArgumentDelegate(SetPendingArgumentException);
+    static ExceptionArgumentDelegate argumentNullDelegate = new ExceptionArgumentDelegate(SetPendingArgumentNullException);
+    static ExceptionArgumentDelegate argumentOutOfRangeDelegate = new ExceptionArgumentDelegate(SetPendingArgumentOutOfRangeException);
+
+    [DllImport("$dllimport", EntryPoint="SWIGRegisterExceptionCallbacks_$module")]
+    public static extern void SWIGRegisterExceptionCallbacks_$module(
+                                ExceptionDelegate applicationDelegate,
+                                ExceptionDelegate arithmeticDelegate,
+                                ExceptionDelegate divideByZeroDelegate, 
+                                ExceptionDelegate indexOutOfRangeDelegate, 
+                                ExceptionDelegate invalidCastDelegate,
+                                ExceptionDelegate invalidOperationDelegate,
+                                ExceptionDelegate ioDelegate,
+                                ExceptionDelegate nullReferenceDelegate,
+                                ExceptionDelegate outOfMemoryDelegate, 
+                                ExceptionDelegate overflowDelegate, 
+                                ExceptionDelegate systemExceptionDelegate);
+
+    [DllImport("$dllimport", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_$module")]
+    public static extern void SWIGRegisterExceptionCallbacksArgument_$module(
+                                ExceptionArgumentDelegate argumentDelegate,
+                                ExceptionArgumentDelegate argumentNullDelegate,
+                                ExceptionArgumentDelegate argumentOutOfRangeDelegate);
+
+    static void SetPendingApplicationException(string message) {
+      SWIGPendingException.Set(new System.ApplicationException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingArithmeticException(string message) {
+      SWIGPendingException.Set(new System.ArithmeticException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingDivideByZeroException(string message) {
+      SWIGPendingException.Set(new System.DivideByZeroException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingIndexOutOfRangeException(string message) {
+      SWIGPendingException.Set(new System.IndexOutOfRangeException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingInvalidCastException(string message) {
+      SWIGPendingException.Set(new System.InvalidCastException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingInvalidOperationException(string message) {
+      SWIGPendingException.Set(new System.InvalidOperationException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingIOException(string message) {
+      SWIGPendingException.Set(new System.IO.IOException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingNullReferenceException(string message) {
+      SWIGPendingException.Set(new System.NullReferenceException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingOutOfMemoryException(string message) {
+      SWIGPendingException.Set(new System.OutOfMemoryException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingOverflowException(string message) {
+      SWIGPendingException.Set(new System.OverflowException(message, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingSystemException(string message) {
+      SWIGPendingException.Set(new System.SystemException(message, SWIGPendingException.Retrieve()));
+    }
+
+    static void SetPendingArgumentException(string message, string paramName) {
+      SWIGPendingException.Set(new System.ArgumentException(message, paramName, SWIGPendingException.Retrieve()));
+    }
+    static void SetPendingArgumentNullException(string message, string paramName) {
+      Exception e = SWIGPendingException.Retrieve();
+      if (e != null) message = message + " Inner Exception: " + e.Message;
+      SWIGPendingException.Set(new System.ArgumentNullException(paramName, message));
+    }
+    static void SetPendingArgumentOutOfRangeException(string message, string paramName) {
+      Exception e = SWIGPendingException.Retrieve();
+      if (e != null) message = message + " Inner Exception: " + e.Message;
+      SWIGPendingException.Set(new System.ArgumentOutOfRangeException(paramName, message));
+    }
+
+    static SWIGExceptionHelper() {
+      SWIGRegisterExceptionCallbacks_$module(
+                                applicationDelegate,
+                                arithmeticDelegate,
+                                divideByZeroDelegate,
+                                indexOutOfRangeDelegate,
+                                invalidCastDelegate,
+                                invalidOperationDelegate,
+                                ioDelegate,
+                                nullReferenceDelegate,
+                                outOfMemoryDelegate,
+                                overflowDelegate,
+                                systemDelegate);
+
+      SWIGRegisterExceptionCallbacksArgument_$module(
+                                argumentDelegate,
+                                argumentNullDelegate,
+                                argumentOutOfRangeDelegate);
+    }
+  }
+
+  protected static SWIGExceptionHelper swigExceptionHelper = new SWIGExceptionHelper();
+
+  public class SWIGPendingException {
+    [ThreadStatic]
+    private static Exception pendingException = null;
+    private static int numExceptionsPending = 0;
+
+    public static bool Pending {
+      get {
+        bool pending = false;
+        if (numExceptionsPending > 0)
+          if (pendingException != null)
+            pending = true;
+        return pending;
+      } 
+    }
+
+    public static void Set(Exception e) {
+      if (pendingException != null)
+        throw new ApplicationException("FATAL: An earlier pending exception from unmanaged code was missed and thus not thrown (" + pendingException.ToString() + ")", e);
+      pendingException = e;
+      lock(typeof($imclassname)) {
+        numExceptionsPending++;
+      }
+    }
+
+    public static Exception Retrieve() {
+      Exception e = null;
+      if (numExceptionsPending > 0) {
+        if (pendingException != null) {
+          e = pendingException;
+          pendingException = null;
+          lock(typeof($imclassname)) {
+            numExceptionsPending--;
+          }
+        }
+      }
+      return e;
+    }
+  }
+%}
+#endif // SWIG_CSHARP_NO_EXCEPTION_HELPER
+
+#if !defined(SWIG_CSHARP_NO_STRING_HELPER)
+%insert(runtime) %{
+/* Callback for returning strings to C# without leaking memory */
+typedef char * (SWIGSTDCALL* SWIG_CSharpStringHelperCallback)(const char *);
+static SWIG_CSharpStringHelperCallback SWIG_csharp_string_callback = NULL;
+%}
+
+%pragma(csharp) imclasscode=%{
+  protected class SWIGStringHelper {
+
+    public delegate string SWIGStringDelegate(string message);
+    static SWIGStringDelegate stringDelegate = new SWIGStringDelegate(CreateString);
+
+    [DllImport("$dllimport", EntryPoint="SWIGRegisterStringCallback_$module")]
+    public static extern void SWIGRegisterStringCallback_$module(SWIGStringDelegate stringDelegate);
+
+    static string CreateString(string cString) {
+      return cString;
+    }
+
+    static SWIGStringHelper() {
+      SWIGRegisterStringCallback_$module(stringDelegate);
+    }
+  }
+
+  static protected SWIGStringHelper swigStringHelper = new SWIGStringHelper();
+%}
+
+%insert(runtime) %{
+#ifdef __cplusplus
+extern "C" 
+#endif
+SWIGEXPORT void SWIGSTDCALL SWIGRegisterStringCallback_$module(SWIG_CSharpStringHelperCallback callback) {
+  SWIG_csharp_string_callback = callback;
+}
+%}
+#endif // SWIG_CSHARP_NO_STRING_HELPER
+
+%insert(runtime) %{
+/* Contract support */
+
+#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, msg, ""); return nullreturn; } else
+%}
diff --git a/trunk/Lib/csharp/csharpkw.swg b/trunk/Lib/csharp/csharpkw.swg
new file mode 100644
index 0000000..9a6d979
--- /dev/null
+++ b/trunk/Lib/csharp/csharpkw.swg
@@ -0,0 +1,94 @@
+#ifndef CSHARP_CSHARPKW_SWG_
+#define CSHARP_CSHARPKW_SWG_
+
+/* Warnings for C# keywords */
+#define CSHARPKW(x) %keywordwarn("'" `x` "' is a C# keyword, renaming to '_" `x` "'",rename="_%s")  `x`
+
+/*
+   from
+   http://www.jaggersoft.com/csharp_grammar.html#1.7%20Keywords
+
+*/
+
+CSHARPKW(abstract);
+CSHARPKW(as);
+CSHARPKW(base);
+CSHARPKW(bool);
+CSHARPKW(break);
+CSHARPKW(byte);
+CSHARPKW(case);
+CSHARPKW(catch);
+CSHARPKW(char);
+CSHARPKW(checked);
+CSHARPKW(class);
+CSHARPKW(const);
+CSHARPKW(continue);
+CSHARPKW(decimal);
+CSHARPKW(default);
+CSHARPKW(delegate);
+CSHARPKW(do);
+CSHARPKW(double);
+CSHARPKW(else);
+CSHARPKW(enum);
+CSHARPKW(event);
+CSHARPKW(explicit);
+CSHARPKW(extern);
+CSHARPKW(false);
+CSHARPKW(finally);
+CSHARPKW(fixed);
+CSHARPKW(float);
+CSHARPKW(for);
+CSHARPKW(foreach);
+CSHARPKW(goto);
+CSHARPKW(if);
+CSHARPKW(implicit);
+CSHARPKW(in);
+CSHARPKW(int);
+CSHARPKW(interface);
+CSHARPKW(internal);
+CSHARPKW(is);
+CSHARPKW(lock);
+CSHARPKW(long);
+CSHARPKW(namespace);
+CSHARPKW(new);
+CSHARPKW(null);
+CSHARPKW(object);
+CSHARPKW(operator);
+CSHARPKW(out);
+CSHARPKW(override);
+CSHARPKW(params);
+CSHARPKW(private);
+CSHARPKW(protected);
+CSHARPKW(public);
+CSHARPKW(readonly);
+CSHARPKW(ref);
+CSHARPKW(return);
+CSHARPKW(sbyte);
+CSHARPKW(sealed);
+CSHARPKW(short);
+CSHARPKW(sizeof);
+CSHARPKW(stackalloc);
+CSHARPKW(static);
+CSHARPKW(struct);
+CSHARPKW(string);
+CSHARPKW(switch);
+CSHARPKW(this);
+CSHARPKW(throw);
+CSHARPKW(true);
+CSHARPKW(try);
+CSHARPKW(typeof);
+CSHARPKW(uint);
+CSHARPKW(ulong);
+CSHARPKW(unchecked);
+CSHARPKW(unsafe);
+CSHARPKW(ushort);
+CSHARPKW(using);
+CSHARPKW(virtual);
+CSHARPKW(void);
+CSHARPKW(volatile);
+CSHARPKW(while);
+
+
+#undef CSHARPKW
+
+#endif //CSHARP_CSHARPKW_SWG_
diff --git a/trunk/Lib/csharp/director.swg b/trunk/Lib/csharp/director.swg
new file mode 100644
index 0000000..8957ecf
--- /dev/null
+++ b/trunk/Lib/csharp/director.swg
@@ -0,0 +1,50 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * director.swg
+ *
+ * This file contains support for director classes so that C# proxy 
+ * methods can be called from C++.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+
+#if defined(DEBUG_DIRECTOR_OWNED)
+#include <iostream>
+#endif
+#include <string>
+
+namespace Swig {
+  /* Director base class - not currently used in C# directors */
+  class Director {
+  };
+
+  /* Base class for director exceptions */
+  class DirectorException {
+  protected:
+    std::string swig_msg;
+
+  public:
+    DirectorException(const char* msg) : swig_msg(msg) {
+    }
+    DirectorException(const std::string &msg) : swig_msg(msg) {
+    }
+    const std::string& what() const {
+      return swig_msg;
+    }
+    virtual ~DirectorException() {
+    }
+  };
+
+  /* Pure virtual method exception */
+  class DirectorPureVirtualException : public Swig::DirectorException {
+  public:
+    DirectorPureVirtualException(const char* msg) : DirectorException(std::string("Attempt to invoke pure virtual method ") + msg) {
+    }
+  };
+}
+
+#endif /* __cplusplus */
+
+
diff --git a/trunk/Lib/csharp/enums.swg b/trunk/Lib/csharp/enums.swg
new file mode 100644
index 0000000..be2a606
--- /dev/null
+++ b/trunk/Lib/csharp/enums.swg
@@ -0,0 +1,89 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enums.swg
+ *
+ * Include this file in order for C/C++ enums to be wrapped by proper C# enums.
+ * Note that the PINVOKE layer handles the enum as an int.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(ctype) const enum SWIGTYPE & "int"
+%typemap(imtype) const enum SWIGTYPE & "int"
+%typemap(cstype) const enum SWIGTYPE & "$*csclassname"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE & %{ $result = *$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin) const enum SWIGTYPE &    "$input = $1_name;"
+%typemap(csdirectorin) const enum SWIGTYPE & "($*csclassname)$iminput"
+%typemap(csdirectorout) const enum SWIGTYPE & "(int)$cscall"
+
+%typecheck(SWIG_TYPECHECK_POINTER) const enum SWIGTYPE & ""
+
+%typemap(throws, canthrow=1) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(csin) const enum SWIGTYPE & "(int)$csinput"
+%typemap(csout, excode=SWIGEXCODE) const enum SWIGTYPE & {
+    $*csclassname ret = ($*csclassname)$imcall;$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) const enum SWIGTYPE & %{
+    get {
+      $*csclassname ret = ($*csclassname)$imcall;$excode
+      return ret;
+    } %}
+
+
+// enum SWIGTYPE typemaps
+%typemap(ctype) enum SWIGTYPE "int"
+%typemap(imtype) enum SWIGTYPE "int"
+%typemap(cstype) enum SWIGTYPE "$csclassname"
+
+%typemap(in) enum SWIGTYPE %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE %{ $result = $1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin) enum SWIGTYPE    "$input = $1;"
+%typemap(csdirectorin) enum SWIGTYPE "($csclassname)$iminput"
+%typemap(csdirectorout) enum SWIGTYPE "(int)$cscall"
+
+%typecheck(SWIG_TYPECHECK_POINTER) enum SWIGTYPE ""
+
+%typemap(throws, canthrow=1) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(csin) enum SWIGTYPE "(int)$csinput"
+%typemap(csout, excode=SWIGEXCODE) enum SWIGTYPE {
+    $csclassname ret = ($csclassname)$imcall;$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) enum SWIGTYPE %{
+    get {
+      $csclassname ret = ($csclassname)$imcall;$excode
+      return ret;
+    } %}
+
+%typemap(csbase)           enum SWIGTYPE ""
+%typemap(csclassmodifiers) enum SWIGTYPE "public enum"
+%typemap(cscode)           enum SWIGTYPE ""
+%typemap(csimports)        enum SWIGTYPE ""
+%typemap(csinterfaces)     enum SWIGTYPE ""
+
+%typemap(csbody) enum SWIGTYPE ""
+
+%csenum(proper);
+
diff --git a/trunk/Lib/csharp/enumsimple.swg b/trunk/Lib/csharp/enumsimple.swg
new file mode 100644
index 0000000..f508498
--- /dev/null
+++ b/trunk/Lib/csharp/enumsimple.swg
@@ -0,0 +1,91 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enumsimple.swg
+ *
+ * This file provides backwards compatible enum wrapping. SWIG versions 1.3.21
+ * and earlier wrapped global enums with constant integers in the module
+ * class. Enums declared within a C++ class were wrapped by constant integers
+ * in the C# proxy class.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(ctype) const enum SWIGTYPE & "int"
+%typemap(imtype) const enum SWIGTYPE & "int"
+%typemap(cstype) const enum SWIGTYPE & "int"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE & %{ $result = *$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin) const enum SWIGTYPE &    "$input = $1_name;"
+%typemap(csdirectorin) const enum SWIGTYPE & "$iminput"
+%typemap(csdirectorout) const enum SWIGTYPE & "$cscall"
+
+%typecheck(SWIG_TYPECHECK_INT32) const enum SWIGTYPE & ""
+
+%typemap(throws, canthrow=1) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(csin) const enum SWIGTYPE & "$csinput"
+%typemap(csout, excode=SWIGEXCODE) const enum SWIGTYPE & {
+    int ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) const enum SWIGTYPE & %{
+    get {
+      int ret = $imcall;$excode
+      return ret;
+    } %}
+
+
+// enum SWIGTYPE typemaps
+%typemap(ctype) enum SWIGTYPE "int"
+%typemap(imtype) enum SWIGTYPE "int"
+%typemap(cstype) enum SWIGTYPE "int"
+
+%typemap(in) enum SWIGTYPE %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE %{ $result = $1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin) enum SWIGTYPE    "$input = $1;"
+%typemap(csdirectorin) enum SWIGTYPE "$iminput"
+%typemap(csdirectorout) enum SWIGTYPE "$cscall"
+
+%typecheck(SWIG_TYPECHECK_INT32) enum SWIGTYPE ""
+
+%typemap(throws, canthrow=1) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(csin) enum SWIGTYPE "$csinput"
+%typemap(csout, excode=SWIGEXCODE) enum SWIGTYPE {
+    int ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) enum SWIGTYPE %{
+    get {
+      int ret = $imcall;$excode
+      return ret;
+    } %}
+
+%typemap(csbase)           enum SWIGTYPE ""
+%typemap(csclassmodifiers) enum SWIGTYPE ""
+%typemap(cscode)           enum SWIGTYPE ""
+%typemap(csimports)        enum SWIGTYPE ""
+%typemap(csinterfaces)     enum SWIGTYPE ""
+
+%typemap(csbody) enum SWIGTYPE ""
+
+%csenum(simple);
+
diff --git a/trunk/Lib/csharp/enumtypesafe.swg b/trunk/Lib/csharp/enumtypesafe.swg
new file mode 100644
index 0000000..8ba7838
--- /dev/null
+++ b/trunk/Lib/csharp/enumtypesafe.swg
@@ -0,0 +1,133 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enumtypesafe.swg
+ *
+ * Include this file in order for C/C++ enums to be wrapped by the so called
+ * typesafe enum pattern. Each enum has an equivalent C# class named after the
+ * enum and each enum item is a static instance of this class.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(ctype) const enum SWIGTYPE & "int"
+%typemap(imtype) const enum SWIGTYPE & "int"
+%typemap(cstype) const enum SWIGTYPE & "$*csclassname"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE & %{ $result = *$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin) const enum SWIGTYPE &    "$input = $1_name;"
+%typemap(csdirectorin) const enum SWIGTYPE & "$*csclassname.swigToEnum($iminput)"
+%typemap(csdirectorout) const enum SWIGTYPE & "$cscall.swigValue"
+
+%typecheck(SWIG_TYPECHECK_POINTER) const enum SWIGTYPE & ""
+
+%typemap(throws, canthrow=1) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(csin) const enum SWIGTYPE & "$csinput.swigValue"
+%typemap(csout, excode=SWIGEXCODE) const enum SWIGTYPE & {
+    $*csclassname ret = $*csclassname.swigToEnum($imcall);$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) const enum SWIGTYPE & %{
+    get {
+      $*csclassname ret = $*csclassname.swigToEnum($imcall);$excode
+      return ret;
+    } %}
+
+
+// enum SWIGTYPE typemaps
+%typemap(ctype) enum SWIGTYPE "int"
+%typemap(imtype) enum SWIGTYPE "int"
+%typemap(cstype) enum SWIGTYPE "$csclassname"
+
+%typemap(in) enum SWIGTYPE %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE %{ $result = $1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin) enum SWIGTYPE    "$input = $1;"
+%typemap(csdirectorin) enum SWIGTYPE "$csclassname.swigToEnum($iminput)"
+%typemap(csdirectorout) enum SWIGTYPE "$cscall.swigValue"
+
+%typecheck(SWIG_TYPECHECK_POINTER) enum SWIGTYPE ""
+
+%typemap(throws, canthrow=1) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(csin) enum SWIGTYPE "$csinput.swigValue"
+%typemap(csout, excode=SWIGEXCODE) enum SWIGTYPE {
+    $csclassname ret = $csclassname.swigToEnum($imcall);$excode
+    return ret;
+  }
+
+%typemap(csvarout, excode=SWIGEXCODE2) enum SWIGTYPE %{
+    get {
+      $csclassname ret = $csclassname.swigToEnum($imcall);$excode
+      return ret;
+    } %}
+
+%typemap(csbase)           enum SWIGTYPE ""
+%typemap(csclassmodifiers) enum SWIGTYPE "public sealed class"
+%typemap(cscode)           enum SWIGTYPE ""
+%typemap(csimports)        enum SWIGTYPE ""
+%typemap(csinterfaces)     enum SWIGTYPE ""
+
+/*
+ * The swigToEnum method is used to find the C# enum from a C++ enum integer value. The default one here takes 
+ * advantage of the fact that most enums do not have initial values specified, so the lookup is fast. If initial
+ * values are specified then a lengthy linear search through all possible enums might occur. Specific typemaps could be
+ * written to possibly optimise this lookup by taking advantage of characteristics peculiar to the targeted enum.
+ * The special variable, $enumvalues, is replaced with a comma separated list of all the enum values.
+ */
+%typemap(csbody) enum SWIGTYPE %{
+  public readonly int swigValue;
+
+  public static $csclassname swigToEnum(int swigValue) {
+    if (swigValue < swigValues.Length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
+      return swigValues[swigValue];
+    for (int i = 0; i < swigValues.Length; i++)
+      if (swigValues[i].swigValue == swigValue)
+        return swigValues[i];
+    throw new System.ArgumentOutOfRangeException("No enum $csclassname with value " + swigValue);
+  }
+
+  public override string ToString() {
+    return swigName;
+  }
+
+  private $csclassname(string swigName) {
+    this.swigName = swigName;
+    this.swigValue = swigNext++;
+  }
+
+  private $csclassname(string swigName, int swigValue) {
+    this.swigName = swigName;
+    this.swigValue = swigValue;
+    swigNext = swigValue+1;
+  }
+
+  private $csclassname(string swigName, $csclassname swigEnum) {
+    this.swigName = swigName;
+    this.swigValue = swigEnum.swigValue;
+    swigNext = this.swigValue+1;
+  }
+
+  private static $csclassname[] swigValues = { $enumvalues };
+  private static int swigNext = 0;
+  private readonly string swigName;
+%}
+
+%csenum(typesafe);
+
diff --git a/trunk/Lib/csharp/std_common.i b/trunk/Lib/csharp/std_common.i
new file mode 100644
index 0000000..cee11e8
--- /dev/null
+++ b/trunk/Lib/csharp/std_common.i
@@ -0,0 +1,5 @@
+%include <std_except.i>
+
+%apply size_t { std::size_t };
+%apply const size_t& { const std::size_t& };
+
diff --git a/trunk/Lib/csharp/std_deque.i b/trunk/Lib/csharp/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/csharp/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/csharp/std_except.i b/trunk/Lib/csharp/std_except.i
new file mode 100644
index 0000000..c86e97a
--- /dev/null
+++ b/trunk/Lib/csharp/std_except.i
@@ -0,0 +1,33 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_except.i
+ *
+ * Typemaps used by the STL wrappers that throw exceptions. These typemaps are
+ * used when methods are declared with an STL exception specification, such as
+ *   size_t at() const throw (std::out_of_range);
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <stdexcept>
+%}
+
+namespace std 
+{
+  %ignore exception;
+  struct exception {};
+}
+
+%typemap(throws, canthrow=1) std::bad_exception     "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::domain_error      "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::exception         "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::invalid_argument  "SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), \"\");\n return $null;"
+%typemap(throws, canthrow=1) std::length_error      "SWIG_CSharpSetPendingException(SWIG_CSharpIndexOutOfRangeException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::logic_error       "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::out_of_range      "SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, 0, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::overflow_error    "SWIG_CSharpSetPendingException(SWIG_CSharpOverflowException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::range_error       "SWIG_CSharpSetPendingException(SWIG_CSharpIndexOutOfRangeException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::runtime_error     "SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.what());\n return $null;"
+%typemap(throws, canthrow=1) std::underflow_error   "SWIG_CSharpSetPendingException(SWIG_CSharpOverflowException, $1.what());\n return $null;"
+
diff --git a/trunk/Lib/csharp/std_map.i b/trunk/Lib/csharp/std_map.i
new file mode 100644
index 0000000..c35f21d
--- /dev/null
+++ b/trunk/Lib/csharp/std_map.i
@@ -0,0 +1,175 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, T x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    // add specializations here
+
+}
diff --git a/trunk/Lib/csharp/std_pair.i b/trunk/Lib/csharp/std_pair.i
new file mode 100644
index 0000000..78142ff
--- /dev/null
+++ b/trunk/Lib/csharp/std_pair.i
@@ -0,0 +1,37 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+namespace std {
+
+  template<class T, class U> struct pair {
+
+    pair();
+    pair(T t, U u);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+  };
+
+  // add specializations here
+
+}
diff --git a/trunk/Lib/csharp/std_string.i b/trunk/Lib/csharp/std_string.i
new file mode 100644
index 0000000..d296927
--- /dev/null
+++ b/trunk/Lib/csharp/std_string.i
@@ -0,0 +1,114 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * Typemaps for std::string and const std::string&
+ * These are mapped to a C# String and are passed around by value.
+ *
+ * To use non-const std::string references use the following %apply.  Note 
+ * that they are passed by value.
+ * %apply const std::string & {std::string &};
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+%naturalvar string;
+
+class string;
+
+// string
+%typemap(ctype) string "char *"
+%typemap(imtype) string "string"
+%typemap(cstype) string "string"
+
+%typemap(csdirectorin) string "$iminput"
+%typemap(csdirectorout) string "$cscall"
+
+%typemap(in, canthrow=1) string 
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0);
+    return $null;
+   }
+   $1.assign($input); %}
+%typemap(out) string %{ $result = SWIG_csharp_string_callback($1.c_str()); %}
+
+%typemap(directorout, canthrow=1) string 
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0);
+    return $null;
+   }
+   $result.assign($input); %}
+
+%typemap(directorin) string %{ $input = SWIG_csharp_string_callback($1.c_str()); %}
+
+%typemap(csin) string "$csinput"
+%typemap(csout, excode=SWIGEXCODE) string {
+    string ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(typecheck) string = char *;
+
+%typemap(throws, canthrow=1) string
+%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str());
+   return $null; %}
+
+// const string &
+%typemap(ctype) const string & "char *"
+%typemap(imtype) const string & "string"
+%typemap(cstype) const string & "string"
+
+%typemap(csdirectorin) const string & "$iminput"
+%typemap(csdirectorout) const string & "$cscall"
+
+%typemap(in, canthrow=1) const string &
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0);
+    return $null;
+   }
+   std::string $1_str($input);
+   $1 = &$1_str; %}
+%typemap(out) const string & %{ $result = SWIG_csharp_string_callback($1->c_str()); %}
+
+%typemap(csin) const string & "$csinput"
+%typemap(csout, excode=SWIGEXCODE) const string & {
+    string ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(directorout, canthrow=1, warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const string &
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null string", 0);
+    return $null;
+   }
+   /* possible thread/reentrant code problem */
+   static std::string $1_str;
+   $1_str = $input;
+   $result = &$1_str; %}
+
+%typemap(directorin) const string & %{ $input = SWIG_csharp_string_callback($1.c_str()); %}
+
+%typemap(csvarin, excode=SWIGEXCODE2) const string & %{
+    set {
+      $imcall;$excode
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) const string & %{
+    get {
+      string ret = $imcall;$excode
+      return ret;
+    } %}
+
+%typemap(typecheck) const string & = char *;
+
+%typemap(throws, canthrow=1) const string &
+%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str());
+   return $null; %}
+
+}
+
diff --git a/trunk/Lib/csharp/std_vector.i b/trunk/Lib/csharp/std_vector.i
new file mode 100755
index 0000000..a04831f
--- /dev/null
+++ b/trunk/Lib/csharp/std_vector.i
@@ -0,0 +1,384 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * SWIG typemaps for std::vector
+ * C# implementation
+ * The C# wrapper is made to look and feel like a typesafe C# System.Collections.ArrayList
+ * All the methods in IList are defined, but we don't derive from IList as this is a typesafe collection.
+ * Warning: heavy macro usage in this file. Use swig -E to get a sane view on the real file contents!
+ *
+ * Very often the C# generated code will not compile as the C++ template type is not the same as the C# 
+ * proxy type, so use the SWIG_STD_VECTOR_SPECIALIZE or SWIG_STD_VECTOR_SPECIALIZE_MINIMUM macro, eg
+ *
+ *   SWIG_STD_VECTOR_SPECIALIZE_MINIMUM(Klass, SomeNamespace::Klass)
+ *   %template(VectKlass) std::vector<SomeNamespace::Klass>;
+ * ----------------------------------------------------------------------------- */
+
+// Warning: Use the typemaps here in the expectation that the macros they are in will change name.
+
+
+%include <std_common.i>
+
+// MACRO for use within the std::vector class body
+// CSTYPE and CTYPE respectively correspond to the types in the cstype and ctype typemaps
+%define SWIG_STD_VECTOR_MINIMUM(CSTYPE, CTYPE...)
+%typemap(csinterfaces) std::vector<CTYPE > "IDisposable, System.Collections.IEnumerable";
+%typemap(cscode) std::vector<CTYPE > %{
+  public $csclassname(System.Collections.ICollection c) : this() {
+    if (c == null)
+      throw new ArgumentNullException("c");
+    foreach (CSTYPE element in c) {
+      this.Add(element);
+    }
+  }
+
+  public bool IsFixedSize {
+    get {
+      return false;
+    }
+  }
+
+  public bool IsReadOnly {
+    get {
+      return false;
+    }
+  }
+
+  public CSTYPE this[int index]  {
+    get {
+      return getitem(index);
+    }
+    set {
+      setitem(index, value);
+    }
+  }
+
+  public int Capacity {
+    get {
+      return (int)capacity();
+    }
+    set {
+      if (value < size())
+        throw new ArgumentOutOfRangeException("Capacity");
+      reserve((uint)value);
+    }
+  }
+
+  public int Count {
+    get {
+      return (int)size();
+    }
+  }
+
+  public bool IsSynchronized {
+    get {
+      return false;
+    }
+  }
+
+  public void CopyTo(System.Array array) {
+    CopyTo(0, array, 0, this.Count);
+  }
+
+  public void CopyTo(System.Array array, int arrayIndex) {
+    CopyTo(0, array, arrayIndex, this.Count);
+  }
+
+  public void CopyTo(int index, System.Array array, int arrayIndex, int count) {
+    if (array == null)
+      throw new ArgumentNullException("array");
+    if (index < 0)
+      throw new ArgumentOutOfRangeException("index", "Value is less than zero");
+    if (arrayIndex < 0)
+      throw new ArgumentOutOfRangeException("arrayIndex", "Value is less than zero");
+    if (count < 0)
+      throw new ArgumentOutOfRangeException("count", "Value is less than zero");
+    if (array.Rank > 1)
+      throw new ArgumentException("Multi dimensional array.");
+    if (index+count > this.Count || arrayIndex+count > array.Length)
+      throw new ArgumentException("Number of elements to copy is too large.");
+    for (int i=0; i<count; i++)
+      array.SetValue(getitemcopy(index+i), arrayIndex+i);
+  }
+
+  // Type-safe version of IEnumerable.GetEnumerator
+  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+    return new $csclassnameEnumerator(this);
+  }
+
+  public $csclassnameEnumerator GetEnumerator() {
+    return new $csclassnameEnumerator(this);
+  }
+
+  // Type-safe enumerator
+  /// Note that the IEnumerator documentation requires an InvalidOperationException to be thrown
+  /// whenever the collection is modified. This has been done for changes in the size of the
+  /// collection but not when one of the elements of the collection is modified as it is a bit
+  /// tricky to detect unmanaged code that modifies the collection under our feet.
+  public sealed class $csclassnameEnumerator : System.Collections.IEnumerator {
+    private $csclassname collectionRef;
+    private int currentIndex;
+    private object currentObject;
+    private int currentSize;
+
+    public $csclassnameEnumerator($csclassname collection) {
+      collectionRef = collection;
+      currentIndex = -1;
+      currentObject = null;
+      currentSize = collectionRef.Count;
+    }
+
+    // Type-safe iterator Current
+    public CSTYPE Current {
+      get {
+        if (currentIndex == -1)
+          throw new InvalidOperationException("Enumeration not started.");
+        if (currentIndex > currentSize - 1)
+          throw new InvalidOperationException("Enumeration finished.");
+        if (currentObject == null)
+          throw new InvalidOperationException("Collection modified.");
+        return (CSTYPE)currentObject;
+      }
+    }
+
+    // Type-unsafe IEnumerator.Current
+    object System.Collections.IEnumerator.Current {
+      get {
+        return Current;
+      }
+    }
+
+    public bool MoveNext() {
+      int size = collectionRef.Count;
+      bool moveOkay = (currentIndex+1 < size) && (size == currentSize);
+      if (moveOkay) {
+        currentIndex++;
+        currentObject = collectionRef[currentIndex];
+      } else {
+        currentObject = null;
+      }
+      return moveOkay;
+    }
+
+    public void Reset() {
+      currentIndex = -1;
+      currentObject = null;
+      if (collectionRef.Count != currentSize) {
+        throw new InvalidOperationException("Collection modified.");
+      }
+    }
+  }
+%}
+
+  public:
+    typedef size_t size_type;
+    typedef CTYPE value_type;
+    typedef const value_type& const_reference;
+    %rename(Clear) clear;
+    void clear();
+    %rename(Add) push_back;
+    void push_back(const value_type& x);
+    size_type size() const;
+    size_type capacity() const;
+    void reserve(size_type n);
+    %newobject GetRange(int index, int count);
+    %newobject Repeat(const value_type& value, int count);
+    vector();
+    %extend {
+      vector(int capacity) throw (std::out_of_range) {
+        std::vector<CTYPE >* pv = 0;
+        if (capacity >= 0) {
+          pv = new std::vector<CTYPE >();
+          pv->reserve(capacity);
+       } else {
+          throw std::out_of_range("capacity");
+       }
+       return pv;
+      }
+      CTYPE getitemcopy(int index) throw (std::out_of_range) {
+        if (index>=0 && index<(int)self->size())
+          return (*self)[index];
+        else
+          throw std::out_of_range("index");
+      }
+      const_reference getitem(int index) throw (std::out_of_range) {
+        if (index>=0 && index<(int)self->size())
+          return (*self)[index];
+        else
+          throw std::out_of_range("index");
+      }
+      void setitem(int index, const value_type& val) throw (std::out_of_range) {
+        if (index>=0 && index<(int)self->size())
+          (*self)[index] = val;
+        else
+          throw std::out_of_range("index");
+      }
+      // Takes a deep copy of the elements unlike ArrayList.AddRange
+      void AddRange(const std::vector<CTYPE >& values) {
+        self->insert(self->end(), values.begin(), values.end());
+      }
+      // Takes a deep copy of the elements unlike ArrayList.GetRange
+      std::vector<CTYPE > *GetRange(int index, int count) throw (std::out_of_range, std::invalid_argument) {
+        if (index < 0)
+          throw std::out_of_range("index");
+        if (count < 0)
+          throw std::out_of_range("count");
+        if (index >= (int)self->size()+1 || index+count > (int)self->size())
+          throw std::invalid_argument("invalid range");
+        return new std::vector<CTYPE >(self->begin()+index, self->begin()+index+count);
+      }
+      void Insert(int index, const value_type& x) throw (std::out_of_range) {
+        if (index>=0 && index<(int)self->size()+1)
+          self->insert(self->begin()+index, x);
+        else
+          throw std::out_of_range("index");
+      }
+      // Takes a deep copy of the elements unlike ArrayList.InsertRange
+      void InsertRange(int index, const std::vector<CTYPE >& values) throw (std::out_of_range) {
+        if (index>=0 && index<(int)self->size()+1)
+          self->insert(self->begin()+index, values.begin(), values.end());
+        else
+          throw std::out_of_range("index");
+      }
+      void RemoveAt(int index) throw (std::out_of_range) {
+        if (index>=0 && index<(int)self->size())
+          self->erase(self->begin() + index);
+        else
+          throw std::out_of_range("index");
+      }
+      void RemoveRange(int index, int count) throw (std::out_of_range, std::invalid_argument) {
+        if (index < 0)
+          throw std::out_of_range("index");
+        if (count < 0)
+          throw std::out_of_range("count");
+        if (index >= (int)self->size()+1 || index+count > (int)self->size())
+          throw std::invalid_argument("invalid range");
+        self->erase(self->begin()+index, self->begin()+index+count);
+      }
+      static std::vector<CTYPE > *Repeat(const value_type& value, int count) throw (std::out_of_range) {
+        if (count < 0)
+          throw std::out_of_range("count");
+        return new std::vector<CTYPE >(count, value);
+      }
+      void Reverse() {
+        std::reverse(self->begin(), self->end());
+      }
+      void Reverse(int index, int count) throw (std::out_of_range, std::invalid_argument) {
+        if (index < 0)
+          throw std::out_of_range("index");
+        if (count < 0)
+          throw std::out_of_range("count");
+        if (index >= (int)self->size()+1 || index+count > (int)self->size())
+          throw std::invalid_argument("invalid range");
+        std::reverse(self->begin()+index, self->begin()+index+count);
+      }
+      // Takes a deep copy of the elements unlike ArrayList.SetRange
+      void SetRange(int index, const std::vector<CTYPE >& values) throw (std::out_of_range) {
+        if (index < 0)
+          throw std::out_of_range("index");
+        if (index+values.size() > self->size())
+          throw std::out_of_range("index");
+        std::copy(values.begin(), values.end(), self->begin()+index);
+      }
+    }
+%enddef
+
+// Extra methods added to the collection class if operator== is defined for the class being wrapped
+// CSTYPE and CTYPE respectively correspond to the types in the cstype and ctype typemaps
+%define SWIG_STD_VECTOR_EXTRA_OP_EQUALS_EQUALS(CSTYPE, CTYPE...)
+    %extend {
+      bool Contains(const value_type& value) {
+        return std::find(self->begin(), self->end(), value) != self->end();
+      }
+      int IndexOf(const value_type& value) {
+        int index = -1;
+        std::vector<CTYPE >::iterator it = std::find(self->begin(), self->end(), value);
+        if (it != self->end())
+          index = (int)(it - self->begin());
+        return index;
+      }
+      int LastIndexOf(const value_type& value) {
+        int index = -1;
+        std::vector<CTYPE >::reverse_iterator rit = std::find(self->rbegin(), self->rend(), value);
+        if (rit != self->rend())
+          index = (int)(self->rend() - 1 - rit);
+        return index;
+      }
+      void Remove(const value_type& value) {
+        std::vector<CTYPE >::iterator it = std::find(self->begin(), self->end(), value);
+        if (it != self->end())
+          self->erase(it);
+      }
+    }
+%enddef
+
+// Macros for std::vector class specializations
+// CSTYPE and CTYPE respectively correspond to the types in the cstype and ctype typemaps
+%define SWIG_STD_VECTOR_SPECIALIZE(CSTYPE, CTYPE...)
+namespace std {
+  template<> class vector<CTYPE > {
+    SWIG_STD_VECTOR_MINIMUM(CSTYPE, CTYPE)
+    SWIG_STD_VECTOR_EXTRA_OP_EQUALS_EQUALS(CSTYPE, CTYPE)
+  };
+}
+%enddef
+
+%define SWIG_STD_VECTOR_SPECIALIZE_MINIMUM(CSTYPE, CTYPE...)
+namespace std {
+  template<> class vector<CTYPE > {
+    SWIG_STD_VECTOR_MINIMUM(CSTYPE, CTYPE)
+  };
+}
+%enddef
+
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+%csmethodmodifiers std::vector::getitemcopy "private"
+%csmethodmodifiers std::vector::getitem "private"
+%csmethodmodifiers std::vector::setitem "private"
+%csmethodmodifiers std::vector::size "private"
+%csmethodmodifiers std::vector::capacity "private"
+%csmethodmodifiers std::vector::reserve "private"
+
+namespace std {
+  // primary (unspecialized) class template for std::vector
+  // does not require operator== to be defined
+  template<class T> class vector {
+    SWIG_STD_VECTOR_MINIMUM(T, T)
+  };
+  // specializations for pointers
+  template<class T> class vector<T*> {
+    SWIG_STD_VECTOR_MINIMUM(T, T*)
+  };
+  template<class T> class vector<const T*> {
+    SWIG_STD_VECTOR_MINIMUM(T, const T*)
+  };
+}
+
+// template specializations for std::vector
+// these provide extra collections methods as operator== is defined
+SWIG_STD_VECTOR_SPECIALIZE(bool, bool)
+SWIG_STD_VECTOR_SPECIALIZE(char, char)
+SWIG_STD_VECTOR_SPECIALIZE(sbyte, signed char)
+SWIG_STD_VECTOR_SPECIALIZE(byte, unsigned char)
+SWIG_STD_VECTOR_SPECIALIZE(short, short)
+SWIG_STD_VECTOR_SPECIALIZE(ushort, unsigned short)
+SWIG_STD_VECTOR_SPECIALIZE(int, int)
+SWIG_STD_VECTOR_SPECIALIZE(uint, unsigned int)
+SWIG_STD_VECTOR_SPECIALIZE(int, long)
+SWIG_STD_VECTOR_SPECIALIZE(uint, unsigned long)
+SWIG_STD_VECTOR_SPECIALIZE(long, long long)
+SWIG_STD_VECTOR_SPECIALIZE(ulong, unsigned long long)
+SWIG_STD_VECTOR_SPECIALIZE(float, float)
+SWIG_STD_VECTOR_SPECIALIZE(double, double)
+SWIG_STD_VECTOR_SPECIALIZE(string, std::string) // also requires a %include <std_string.i>
+
+
diff --git a/trunk/Lib/csharp/std_wstring.i b/trunk/Lib/csharp/std_wstring.i
new file mode 100755
index 0000000..938070e
--- /dev/null
+++ b/trunk/Lib/csharp/std_wstring.i
@@ -0,0 +1,117 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_wstring.i
+ *
+ * Typemaps for std::wstring and const std::wstring&
+ * These are mapped to a C# String and are passed around by value.
+ *
+ * To use non-const std::wstring references use the following %apply.  Note 
+ * that they are passed by value.
+ * %apply const std::wstring & {std::wstring &};
+ * ----------------------------------------------------------------------------- */
+
+%include <wchar.i>
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+%naturalvar wstring;
+
+class wstring;
+
+// wstring
+%typemap(ctype, out="void *") wstring "wchar_t *"
+%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]") wstring "string"
+%typemap(cstype) wstring "string"
+%typemap(csdirectorin) wstring "$iminput"
+%typemap(csdirectorout) wstring "$cscall"
+
+%typemap(in, canthrow=1) wstring 
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null wstring", 0);
+    return $null;
+   }
+   $1.assign($input); %}
+%typemap(out) wstring %{ $result = SWIG_csharp_wstring_callback($1.c_str()); %}
+
+%typemap(directorout, canthrow=1) wstring 
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null wstring", 0);
+    return $null;
+   }
+   $result.assign($input); %}
+
+%typemap(directorin) wstring %{ $input = SWIG_csharp_wstring_callback($1.c_str()); %}
+
+%typemap(csin) wstring "$csinput"
+%typemap(csout, excode=SWIGEXCODE) wstring {
+    string ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(typecheck) wstring = wchar_t *;
+
+%typemap(throws, canthrow=1) wstring
+%{ std::string message($1.begin(), $1.end());
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, message.c_str());
+   return $null; %}
+
+// const wstring &
+%typemap(ctype, out="void *") const wstring & "wchar_t *"
+%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]") const wstring & "string"  
+%typemap(cstype) const wstring & "string"
+
+%typemap(csdirectorin) const wstring & "$iminput"
+%typemap(csdirectorout) const wstring & "$cscall"
+
+%typemap(in, canthrow=1) const wstring &
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null wstring", 0);
+    return $null;
+   }
+   std::wstring $1_str($input);
+   $1 = &$1_str; %}
+%typemap(out) const wstring & %{ $result = SWIG_csharp_wstring_callback($1->c_str()); %}
+
+%typemap(csin) const wstring & "$csinput"
+%typemap(csout, excode=SWIGEXCODE) const wstring & {
+    string ret = $imcall;$excode
+    return ret;
+  }
+
+%typemap(directorout, canthrow=1, warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const wstring &
+%{ if (!$input) {
+    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null wstring", 0);
+    return $null;
+   }
+   /* possible thread/reentrant code problem */
+   static std::wstring $1_str;
+   $1_str = $input;
+   $result = &$1_str; %}
+
+%typemap(directorin) const wstring & %{ $input = SWIG_csharp_wstring_callback($1.c_str()); %}
+
+%typemap(csvarin, excode=SWIGEXCODE2) const wstring & %{
+    set {
+      $imcall;$excode
+    } %}
+%typemap(csvarout, excode=SWIGEXCODE2) const wstring & %{
+    get {
+      string ret = $imcall;$excode
+      return ret;
+    } %}
+
+%typemap(typecheck) const wstring & = wchar_t *;
+
+%typemap(throws, canthrow=1) const wstring &
+%{ std::string message($1.begin(), $1.end());
+   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, message.c_str());
+   return $null; %}
+
+}
+
diff --git a/trunk/Lib/csharp/stl.i b/trunk/Lib/csharp/stl.i
new file mode 100644
index 0000000..66b72e0
--- /dev/null
+++ b/trunk/Lib/csharp/stl.i
@@ -0,0 +1,15 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/csharp/typemaps.i b/trunk/Lib/csharp/typemaps.i
new file mode 100644
index 0000000..ddfbd1b
--- /dev/null
+++ b/trunk/Lib/csharp/typemaps.i
@@ -0,0 +1,291 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Pointer and reference handling typemap library
+ *
+ * These mappings provide support for input/output arguments and common
+ * uses for C/C++ pointers and C++ references.
+ * ----------------------------------------------------------------------------- */
+
+/*
+INPUT typemaps
+--------------
+
+These typemaps are used for pointer/reference parameters that are input only
+and are mapped to a C# input parameter.
+
+The following typemaps can be applied to turn a pointer or reference into a simple
+input value.  That is, instead of passing a pointer or reference to an object,
+you would use a real value instead.
+
+        bool               *INPUT, bool               &INPUT
+        signed char        *INPUT, signed char        &INPUT
+        unsigned char      *INPUT, unsigned char      &INPUT
+        short              *INPUT, short              &INPUT
+        unsigned short     *INPUT, unsigned short     &INPUT
+        int                *INPUT, int                &INPUT
+        unsigned int       *INPUT, unsigned int       &INPUT
+        long               *INPUT, long               &INPUT
+        unsigned long      *INPUT, unsigned long      &INPUT
+        long long          *INPUT, long long          &INPUT
+        unsigned long long *INPUT, unsigned long long &INPUT
+        float              *INPUT, float              &INPUT
+        double             *INPUT, double             &INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include <typemaps.i>
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+In C# you could then use it like this:
+        double answer = modulename.fadd(10.0, 20.0);
+
+*/
+
+%define INPUT_TYPEMAP(TYPE, CTYPE, CSTYPE)
+%typemap(ctype) TYPE *INPUT, TYPE &INPUT "CTYPE"
+%typemap(imtype) TYPE *INPUT, TYPE &INPUT "CSTYPE"
+%typemap(cstype) TYPE *INPUT, TYPE &INPUT "CSTYPE"
+%typemap(csin) TYPE *INPUT, TYPE &INPUT "$csinput"
+%typemap(csdirectorin) TYPE *INPUT, TYPE &INPUT "$iminput"
+%typemap(csdirectorout) TYPE *INPUT, TYPE &INPUT "$cscall"
+
+%typemap(in) TYPE *INPUT, TYPE &INPUT
+%{ $1 = ($1_ltype)&$input; %}
+
+%typemap(directorout) TYPE *INPUT, TYPE &INPUT
+%{ $result = ($1_ltype)&$input; %}
+
+%typemap(directorin) TYPE &INPUT
+%{ $input = (CTYPE *)$1; %}
+
+%typemap(directorin) TYPE *INPUT
+%{ $input = (CTYPE *)$1; %}
+
+%typemap(typecheck) TYPE *INPUT = TYPE;
+%typemap(typecheck) TYPE &INPUT = TYPE;
+%enddef
+
+INPUT_TYPEMAP(bool,               unsigned int,         bool)
+//INPUT_TYPEMAP(char,               char,                 char)
+INPUT_TYPEMAP(signed char,        signed char,          sbyte)
+INPUT_TYPEMAP(unsigned char,      unsigned char,        byte)
+INPUT_TYPEMAP(short,              short,                short)
+INPUT_TYPEMAP(unsigned short,     unsigned short,       ushort)
+INPUT_TYPEMAP(int,                int,                  int)
+INPUT_TYPEMAP(unsigned int,       unsigned int,         uint)
+INPUT_TYPEMAP(long,               long,                 int)
+INPUT_TYPEMAP(unsigned long,      unsigned long,        uint)
+INPUT_TYPEMAP(long long,          long long,            long)
+INPUT_TYPEMAP(unsigned long long, unsigned long long,   ulong)
+INPUT_TYPEMAP(float,              float,                float)
+INPUT_TYPEMAP(double,             double,               double)
+
+#undef INPUT_TYPEMAP
+
+/*
+OUTPUT typemaps
+---------------
+
+These typemaps are used for pointer/reference parameters that are output only and
+are mapped to a C# output parameter.
+
+The following typemaps can be applied to turn a pointer or reference into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned. In C#, the 'out' keyword is
+used when passing the parameter to a function that takes an output parameter.
+
+        bool               *OUTPUT, bool               &OUTPUT
+        signed char        *OUTPUT, signed char        &OUTPUT
+        unsigned char      *OUTPUT, unsigned char      &OUTPUT
+        short              *OUTPUT, short              &OUTPUT
+        unsigned short     *OUTPUT, unsigned short     &OUTPUT
+        int                *OUTPUT, int                &OUTPUT
+        unsigned int       *OUTPUT, unsigned int       &OUTPUT
+        long               *OUTPUT, long               &OUTPUT
+        unsigned long      *OUTPUT, unsigned long      &OUTPUT
+        long long          *OUTPUT, long long          &OUTPUT
+        unsigned long long *OUTPUT, unsigned long long &OUTPUT
+        float              *OUTPUT, float              &OUTPUT
+        double             *OUTPUT, double             &OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters):
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The C# output of the function would be the function return value and the 
+value returned in the second output parameter. In C# you would use it like this:
+
+    double dptr;
+    double fraction = modulename.modf(5, out dptr);
+
+*/
+
+%define OUTPUT_TYPEMAP(TYPE, CTYPE, CSTYPE, TYPECHECKPRECEDENCE)
+%typemap(ctype) TYPE *OUTPUT, TYPE &OUTPUT "CTYPE *"
+%typemap(imtype) TYPE *OUTPUT, TYPE &OUTPUT "out CSTYPE"
+%typemap(cstype) TYPE *OUTPUT, TYPE &OUTPUT "out CSTYPE"
+%typemap(csin) TYPE *OUTPUT, TYPE &OUTPUT "out $csinput"
+%typemap(csdirectorin) TYPE *OUTPUT, TYPE &OUTPUT "$iminput"
+%typemap(csdirectorout) TYPE *OUTPUT, TYPE &OUTPUT "$cscall"
+
+
+%typemap(in) TYPE *OUTPUT, TYPE &OUTPUT
+%{ $1 = ($1_ltype)$input; %}
+
+%typemap(directorout,warning="Need to provide TYPE *OUTPUT directorout typemap") TYPE *OUTPUT, TYPE &OUTPUT {
+}
+
+%typemap(directorin) TYPE &OUTPUT
+%{ $input = &$1; %}
+
+%typemap(directorin,warning="Need to provide TYPE *OUTPUT directorin typemap, TYPE array length is unknown") TYPE *OUTPUT
+{
+}
+
+
+%typecheck(SWIG_TYPECHECK_##TYPECHECKPRECEDENCE) TYPE *OUTPUT, TYPE &OUTPUT ""
+%enddef
+
+OUTPUT_TYPEMAP(bool,               unsigned int,         bool,     BOOL_PTR)
+//OUTPUT_TYPEMAP(char,               char,                 char,     CHAR_PTR)
+OUTPUT_TYPEMAP(signed char,        signed char,          sbyte,    INT8_PTR)
+OUTPUT_TYPEMAP(unsigned char,      unsigned char,        byte,     UINT8_PTR)
+OUTPUT_TYPEMAP(short,              short,                short,    INT16_PTR)
+OUTPUT_TYPEMAP(unsigned short,     unsigned short,       ushort,   UINT16_PTR)
+OUTPUT_TYPEMAP(int,                int,                  int,      INT32_PTR)
+OUTPUT_TYPEMAP(unsigned int,       unsigned int,         uint,     UINT32_PTR)
+OUTPUT_TYPEMAP(long,               long,                 int,      INT32_PTR)
+OUTPUT_TYPEMAP(unsigned long,      unsigned long,        uint,     UINT32_PTR)
+OUTPUT_TYPEMAP(long long,          long long,            long,     INT64_PTR)
+OUTPUT_TYPEMAP(unsigned long long, unsigned long long,   ulong,    UINT64_PTR)
+OUTPUT_TYPEMAP(float,              float,                float,    FLOAT_PTR)
+OUTPUT_TYPEMAP(double,             double,               double,   DOUBLE_PTR)
+
+#undef OUTPUT_TYPEMAP
+
+
+/*
+INOUT typemaps
+--------------
+
+These typemaps are for pointer/reference parameters that are both input and
+output and are mapped to a C# reference parameter.
+
+The following typemaps can be applied to turn a pointer or reference into a
+reference parameters, that is the parameter is both an input and an output.
+In C#, the 'ref' keyword is used for reference parameters.
+
+        bool               *INOUT, bool               &INOUT
+        signed char        *INOUT, signed char        &INOUT
+        unsigned char      *INOUT, unsigned char      &INOUT
+        short              *INOUT, short              &INOUT
+        unsigned short     *INOUT, unsigned short     &INOUT
+        int                *INOUT, int                &INOUT
+        unsigned int       *INOUT, unsigned int       &INOUT
+        long               *INOUT, long               &INOUT
+        unsigned long      *INOUT, unsigned long      &INOUT
+        long long          *INOUT, long long          &INOUT
+        unsigned long long *INOUT, unsigned long long &INOUT
+        float              *INOUT, float              &INOUT
+        double             *INOUT, double             &INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+The C# output of the function would be the new value returned by the 
+reference parameter. In C# you would use it like this:
+
+
+       double x = 5.0;
+       neg(ref x);
+
+The implementation of the OUTPUT and INOUT typemaps is different to the scripting
+languages in that the scripting languages will return the output value as part 
+of the function return value.
+
+*/
+
+%define INOUT_TYPEMAP(TYPE, CTYPE, CSTYPE, TYPECHECKPRECEDENCE)
+%typemap(ctype) TYPE *INOUT, TYPE &INOUT "CTYPE *"
+%typemap(imtype) TYPE *INOUT, TYPE &INOUT "ref CSTYPE"
+%typemap(cstype) TYPE *INOUT, TYPE &INOUT "ref CSTYPE"
+%typemap(csin) TYPE *INOUT, TYPE &INOUT "ref $csinput"
+%typemap(csdirectorin) TYPE *INOUT, TYPE &INOUT "$iminput"
+%typemap(csdirectorout) TYPE *INOUT, TYPE &INOUT "$cscall"
+
+%typemap(in) TYPE *INOUT, TYPE &INOUT
+%{ $1 = ($1_ltype)$input; %}
+
+%typemap(directorout,warning="Need to provide TYPE *INOUT directorout typemap") TYPE *INOUT, TYPE &INOUT {
+}
+
+%typemap(directorin) TYPE &INOUT
+%{ $input = &$1; %}
+
+%typemap(directorin,warning="Need to provide TYPE *INOUT directorin typemap, TYPE array length is unknown") TYPE *INOUT, TYPE &INOUT
+{
+}
+
+%typecheck(SWIG_TYPECHECK_##TYPECHECKPRECEDENCE) TYPE *INOUT, TYPE &INOUT ""
+%enddef
+
+INOUT_TYPEMAP(bool,               unsigned int,         bool,     BOOL_PTR)
+//INOUT_TYPEMAP(char,               char,                 char,     CHAR_PTR)
+INOUT_TYPEMAP(signed char,        signed char,          sbyte,    INT8_PTR)
+INOUT_TYPEMAP(unsigned char,      unsigned char,        byte,     UINT8_PTR)
+INOUT_TYPEMAP(short,              short,                short,    INT16_PTR)
+INOUT_TYPEMAP(unsigned short,     unsigned short,       ushort,   UINT16_PTR)
+INOUT_TYPEMAP(int,                int,                  int,      INT32_PTR)
+INOUT_TYPEMAP(unsigned int,       unsigned int,         uint,     UINT32_PTR)
+INOUT_TYPEMAP(long,               long,                 int,      INT32_PTR)
+INOUT_TYPEMAP(unsigned long,      unsigned long,        uint,     UINT32_PTR)
+INOUT_TYPEMAP(long long,          long long,            long,     INT64_PTR)
+INOUT_TYPEMAP(unsigned long long, unsigned long long,   ulong,    UINT64_PTR)
+INOUT_TYPEMAP(float,              float,                float,    FLOAT_PTR)
+INOUT_TYPEMAP(double,             double,               double,   DOUBLE_PTR)
+
+#undef INOUT_TYPEMAP
+
diff --git a/trunk/Lib/csharp/wchar.i b/trunk/Lib/csharp/wchar.i
new file mode 100755
index 0000000..be87560
--- /dev/null
+++ b/trunk/Lib/csharp/wchar.i
@@ -0,0 +1,105 @@
+/* -----------------------------------------------------------------------------

+ * See the LICENSE file for information on copyright, usage and redistribution

+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.

+ *

+ * wchar.i

+ *

+ * Typemaps for the wchar_t type

+ * These are mapped to a C# String and are passed around by value.

+ *

+ * Support code for wide strings can be turned off by defining SWIG_CSHARP_NO_WSTRING_HELPER

+ *

+ * ----------------------------------------------------------------------------- */

+

+#if !defined(SWIG_CSHARP_NO_WSTRING_HELPER)

+#if !defined(SWIG_CSHARP_WSTRING_HELPER_)

+#define SWIG_CSHARP_WSTRING_HELPER_

+%insert(runtime) %{

+/* Callback for returning strings to C# without leaking memory */

+typedef void * (SWIGSTDCALL* SWIG_CSharpWStringHelperCallback)(const wchar_t *);

+static SWIG_CSharpWStringHelperCallback SWIG_csharp_wstring_callback = NULL;

+%}

+

+%pragma(csharp) imclasscode=%{

+  protected class SWIGWStringHelper {

+

+    public delegate string SWIGWStringDelegate(IntPtr message);

+    static SWIGWStringDelegate wstringDelegate = new SWIGWStringDelegate(CreateWString);

+

+    [DllImport("$dllimport", EntryPoint="SWIGRegisterWStringCallback_$module")]

+    public static extern void SWIGRegisterWStringCallback_$module(SWIGWStringDelegate wstringDelegate);

+

+    static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) {

+      return System.Runtime.InteropServices.Marshal.PtrToStringUni(cString);

+    }

+

+    static SWIGWStringHelper() {

+      SWIGRegisterWStringCallback_$module(wstringDelegate);

+    }

+  }

+

+  static protected SWIGWStringHelper swigWStringHelper = new SWIGWStringHelper();

+%}

+

+%insert(runtime) %{

+#ifdef __cplusplus

+extern "C"

+#endif

+SWIGEXPORT void SWIGSTDCALL SWIGRegisterWStringCallback_$module(SWIG_CSharpWStringHelperCallback callback) {

+  SWIG_csharp_wstring_callback = callback;

+}

+%}

+#endif // SWIG_CSHARP_WSTRING_HELPER_

+#endif // SWIG_CSHARP_NO_WSTRING_HELPER

+

+

+// wchar_t

+%typemap(ctype) wchar_t "wchar_t"

+%typemap(imtype) wchar_t "char"

+%typemap(cstype) wchar_t "char"

+

+%typemap(csin) wchar_t "$csinput"

+%typemap(csout, excode=SWIGEXCODE) wchar_t {

+    char ret = $imcall;$excode

+    return ret;

+  }

+%typemap(csvarin, excode=SWIGEXCODE2) wchar_t %{

+    set {

+      $imcall;$excode

+    } %}

+%typemap(csvarout, excode=SWIGEXCODE2) wchar_t %{

+    get {

+      char ret = $imcall;$excode

+      return ret;

+    } %}

+

+%typemap(in) wchar_t %{ $1 = ($1_ltype)$input; %}

+%typemap(out) wchar_t %{ $result = (wchar_t)$1; %}

+

+%typemap(typecheck) wchar_t = char;

+

+// wchar_t *

+%typemap(ctype) wchar_t * "wchar_t *"

+%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]", out="IntPtr" ) wchar_t * "string"

+%typemap(cstype) wchar_t * "string"

+

+%typemap(csin) wchar_t * "$csinput"

+%typemap(csout, excode=SWIGEXCODE) wchar_t * {

+    string ret = System.Runtime.InteropServices.Marshal.PtrToStringUni($imcall);$excode

+    return ret;

+  }

+%typemap(csvarin, excode=SWIGEXCODE2) wchar_t * %{

+    set {

+      $imcall;$excode

+    } %}

+%typemap(csvarout, excode=SWIGEXCODE2) wchar_t * %{

+    get {

+      string ret = $imcall;$excode

+      return ret;

+    } %}

+

+%typemap(in) wchar_t * %{ $1 = ($1_ltype)$input; %}

+%typemap(out) wchar_t * %{ $result = (wchar_t *)$1; %}

+

+%typemap(typecheck) wchar_t * = char *;

+

diff --git a/trunk/Lib/cstring.i b/trunk/Lib/cstring.i
new file mode 100644
index 0000000..4ebdf68
--- /dev/null
+++ b/trunk/Lib/cstring.i
@@ -0,0 +1,15 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cstring.i
+ * ----------------------------------------------------------------------------- */
+
+%echo "cstring.i not implemented for this target"
+#define SWIG_CSTRING_UNIMPL
+
+/* old name keep for compatibility */
+#define _CSTRING_UNIMPL 
+
+
+
diff --git a/trunk/Lib/cwstring.i b/trunk/Lib/cwstring.i
new file mode 100644
index 0000000..a6b08ae
--- /dev/null
+++ b/trunk/Lib/cwstring.i
@@ -0,0 +1,14 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cwstring.i
+ * ----------------------------------------------------------------------------- */
+
+%echo "cwstring.i not implemented for this target"
+#define SWIG_CWSTRING_UNIMPL
+
+
+
+
+
diff --git a/trunk/Lib/exception.i b/trunk/Lib/exception.i
new file mode 100644
index 0000000..e30ac1a
--- /dev/null
+++ b/trunk/Lib/exception.i
@@ -0,0 +1,271 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * exception.i
+ *
+ * SWIG library file providing language independent exception handling
+ * ----------------------------------------------------------------------------- */
+
+#if defined(SWIGUTL)
+#error "This version of exception.i should not be used"
+#endif
+
+
+%insert("runtime") "swigerrors.swg"
+
+
+#ifdef SWIGPHP
+%{
+#if PHP_MAJOR_VERSION < 5
+# define SWIG_exception(code, msg) { zend_error(E_ERROR, msg); }
+#else
+# include "zend_exceptions.h"
+# define SWIG_exception(code, msg) { zend_throw_exception(NULL, (char*)msg, code TSRMLS_CC); }
+#endif
+%}
+#endif
+
+#ifdef SWIGGUILE
+%{
+  SWIGINTERN void SWIG_exception_ (int code, const char *msg,
+                               const char *subr) {
+#define ERROR(scmerr)					\
+	scm_error(gh_symbol2scm((char *) (scmerr)),	\
+		  (char *) subr, (char *) msg,		\
+		  SCM_EOL, SCM_BOOL_F)
+#define MAP(swigerr, scmerr)			\
+	case swigerr:				\
+	  ERROR(scmerr);			\
+	  break
+    switch (code) {
+      MAP(SWIG_MemoryError,	"swig-memory-error");
+      MAP(SWIG_IOError,		"swig-io-error");
+      MAP(SWIG_RuntimeError,	"swig-runtime-error");
+      MAP(SWIG_IndexError,	"swig-index-error");
+      MAP(SWIG_TypeError,	"swig-type-error");
+      MAP(SWIG_DivisionByZero,	"swig-division-by-zero");
+      MAP(SWIG_OverflowError,	"swig-overflow-error");
+      MAP(SWIG_SyntaxError,	"swig-syntax-error");
+      MAP(SWIG_ValueError,	"swig-value-error");
+      MAP(SWIG_SystemError,	"swig-system-error");
+    default:
+      ERROR("swig-error");
+    }
+#undef ERROR
+#undef MAP
+  }
+
+#define SWIG_exception(a,b) SWIG_exception_(a, b, FUNC_NAME)
+%}
+#endif
+
+#ifdef SWIGMZSCHEME
+
+%{
+SWIGINTERN void SWIG_exception_ (int code, const char *msg) {
+#define ERROR(errname)				\
+	scheme_signal_error(errname " (%s)", msg);
+#define MAP(swigerr, errname)			\
+	case swigerr:				\
+	  ERROR(errname);			\
+	  break
+    switch (code) {
+      MAP(SWIG_MemoryError,	"swig-memory-error");
+      MAP(SWIG_IOError,		"swig-io-error");
+      MAP(SWIG_RuntimeError,	"swig-runtime-error");
+      MAP(SWIG_IndexError,	"swig-index-error");
+      MAP(SWIG_TypeError,	"swig-type-error");
+      MAP(SWIG_DivisionByZero,	"swig-division-by-zero");
+      MAP(SWIG_OverflowError,	"swig-overflow-error");
+      MAP(SWIG_SyntaxError,	"swig-syntax-error");
+      MAP(SWIG_ValueError,	"swig-value-error");
+      MAP(SWIG_SystemError,	"swig-system-error");
+    default:
+      ERROR("swig-error");
+    }
+#undef ERROR
+#undef MAP
+  }
+
+#define SWIG_exception(a,b) SWIG_exception_(a, b)
+%}
+#endif
+
+#ifdef SWIGJAVA
+%{
+SWIGINTERN void SWIG_JavaException(JNIEnv *jenv, int code, const char *msg) {
+  SWIG_JavaExceptionCodes exception_code = SWIG_JavaUnknownError;
+  switch(code) {
+  case SWIG_MemoryError:
+    exception_code = SWIG_JavaOutOfMemoryError;
+    break;
+  case SWIG_IOError:
+    exception_code = SWIG_JavaIOException;
+    break;
+  case SWIG_SystemError:
+  case SWIG_RuntimeError:
+    exception_code = SWIG_JavaRuntimeException;
+    break;
+  case SWIG_OverflowError:
+  case SWIG_IndexError:
+    exception_code = SWIG_JavaIndexOutOfBoundsException;
+    break;
+  case SWIG_DivisionByZero:
+    exception_code = SWIG_JavaArithmeticException;
+    break;
+  case SWIG_SyntaxError:
+  case SWIG_ValueError:
+  case SWIG_TypeError:
+    exception_code = SWIG_JavaIllegalArgumentException;
+    break;
+  case SWIG_UnknownError:
+  default:
+    exception_code = SWIG_JavaUnknownError;
+    break;
+  }
+  SWIG_JavaThrowException(jenv, exception_code, msg);
+}
+%}
+
+#define SWIG_exception(code, msg)\
+{ SWIG_JavaException(jenv, code, msg); return $null; }
+#endif // SWIGJAVA
+
+#ifdef SWIGOCAML
+%{
+#define OCAML_MSG_BUF_LEN 1024
+SWIGINTERN void SWIG_exception_(int code, const char *msg) {
+  char msg_buf[OCAML_MSG_BUF_LEN];
+  sprintf( msg_buf, "Exception(%d): %s\n", code, msg );
+  failwith( msg_buf );
+}
+#define SWIG_exception(a,b) SWIG_exception_((a),(b))
+%}
+#endif
+
+
+#ifdef SWIGCHICKEN
+%{
+SWIGINTERN void SWIG_exception_(int code, const char *msg) {
+  C_word *a;
+  C_word scmmsg;
+  C_word list;
+
+  a = C_alloc (C_SIZEOF_STRING (strlen (msg)) + C_SIZEOF_LIST(2));
+  scmmsg = C_string2 (&a, (char *) msg);
+  list = C_list(&a, 2, C_fix(code), scmmsg);
+  SWIG_ThrowException(list);
+}
+#define SWIG_exception(a,b) SWIG_exception_((a),(b))
+%}
+#endif
+
+#ifdef SWIGCSHARP
+%{
+SWIGINTERN void SWIG_CSharpException(int code, const char *msg) {
+  if (code == SWIG_ValueError) {
+    SWIG_CSharpExceptionArgumentCodes exception_code = SWIG_CSharpArgumentOutOfRangeException;
+    SWIG_CSharpSetPendingExceptionArgument(exception_code, msg, 0);
+  } else {
+    SWIG_CSharpExceptionCodes exception_code = SWIG_CSharpApplicationException;
+    switch(code) {
+    case SWIG_MemoryError:
+      exception_code = SWIG_CSharpOutOfMemoryException;
+      break;
+    case SWIG_IndexError:
+      exception_code = SWIG_CSharpIndexOutOfRangeException;
+      break;
+    case SWIG_DivisionByZero:
+      exception_code = SWIG_CSharpDivideByZeroException;
+      break;
+    case SWIG_IOError:
+      exception_code = SWIG_CSharpIOException;
+      break;
+    case SWIG_OverflowError:
+      exception_code = SWIG_CSharpOverflowException;
+      break;
+    case SWIG_RuntimeError:
+    case SWIG_TypeError:
+    case SWIG_SyntaxError:
+    case SWIG_SystemError:
+    case SWIG_UnknownError:
+    default:
+      exception_code = SWIG_CSharpApplicationException;
+      break;
+    }
+    SWIG_CSharpSetPendingException(exception_code, msg);
+  }
+}
+%}
+
+#define SWIG_exception(code, msg)\
+{ SWIG_CSharpException(code, msg); return $null; }
+#endif // SWIGCSHARP
+
+#ifdef SWIGLUA
+
+%{
+#define SWIG_exception(a,b)\
+{ lua_pushfstring(L,"%s:%s",#a,b);SWIG_fail; }
+%}
+
+#endif // SWIGLUA
+
+#ifdef __cplusplus
+/*
+  You can use the SWIG_CATCH_STDEXCEPT macro with the %exception
+  directive as follows:
+
+  %exception {
+    try {
+      $action
+    }
+    catch (my_except& e) {
+      ...
+    }
+    SWIG_CATCH_STDEXCEPT // catch std::exception
+    catch (...) {
+     SWIG_exception(SWIG_UnknownError, "Unknown exception");
+    }
+  }
+*/
+%{
+#include <stdexcept>
+%}
+%define SWIG_CATCH_STDEXCEPT
+  /* catching std::exception  */
+  catch (std::invalid_argument& e) {
+    SWIG_exception(SWIG_ValueError, e.what() );
+  } catch (std::domain_error& e) {
+    SWIG_exception(SWIG_ValueError, e.what() );
+  } catch (std::overflow_error& e) {
+    SWIG_exception(SWIG_OverflowError, e.what() );
+  } catch (std::out_of_range& e) {
+    SWIG_exception(SWIG_IndexError, e.what() );
+  } catch (std::length_error& e) {
+    SWIG_exception(SWIG_IndexError, e.what() );
+  } catch (std::runtime_error& e) {
+    SWIG_exception(SWIG_RuntimeError, e.what() );
+  } catch (std::exception& e) {
+    SWIG_exception(SWIG_SystemError, e.what() );
+  }
+%enddef
+%define SWIG_CATCH_UNKNOWN
+  catch (std::exception& e) {
+    SWIG_exception(SWIG_SystemError, e.what() );
+  }
+  catch (...) {
+    SWIG_exception(SWIG_UnknownError, "unknown exception");
+  }
+%enddef
+
+/* rethrow the unknown exception */
+
+%typemap(throws,noblock=1) (...) {
+  SWIG_exception(SWIG_RuntimeError,"unknown exception");
+}
+
+#endif /* __cplusplus */
+
+/* exception.i ends here */
diff --git a/trunk/Lib/gcj/cni.i b/trunk/Lib/gcj/cni.i
new file mode 100644
index 0000000..b12148e
--- /dev/null
+++ b/trunk/Lib/gcj/cni.i
@@ -0,0 +1,43 @@
+%{
+#include <gcj/cni.h>
+%}
+
+%include <gcj/javaprims.i>
+
+extern jobject JvAllocObject (jclass cls);
+
+extern jobject JvAllocObject (jclass cls, jsize sz);
+
+extern void JvInitClass (jclass cls);
+
+extern jstring JvAllocString (jsize sz);
+
+extern jstring JvNewString (const jchar *chars, jsize len);
+
+extern jstring JvNewStringLatin1 (const char *bytes, jsize len);
+
+extern jstring JvNewStringLatin1 (const char *bytes);
+
+extern jchar* JvGetStringChars (jstring str);
+
+extern jsize JvGetStringUTFLength (jstring string);
+
+extern jsize JvGetStringUTFRegion (jstring str, jsize start, jsize len, char *buf);
+
+extern jstring JvNewStringUTF (const char *bytes);
+
+extern void *JvMalloc (jsize size);
+
+extern void JvFree (void *ptr);
+
+extern jint JvCreateJavaVM (void* vm_args);
+
+extern java::lang::Thread* JvAttachCurrentThread (jstring name, java::lang::ThreadGroup* group);
+
+extern java::lang::Thread* JvAttachCurrentThreadAsDaemon (jstring name, java::lang::ThreadGroup* group);
+
+extern jint JvDetachCurrentThread (void);
+
+
+%include <gcj/cni.swg>
+
diff --git a/trunk/Lib/gcj/cni.swg b/trunk/Lib/gcj/cni.swg
new file mode 100644
index 0000000..247909a
--- /dev/null
+++ b/trunk/Lib/gcj/cni.swg
@@ -0,0 +1,17 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cni.swg
+ * ----------------------------------------------------------------------------- */
+
+#ifdef SWIG
+
+#define __attribute__(...)
+%ignore class$;
+#pragma SWIG nowarn=313,402
+
+%nodefaultdtor;
+
+#endif
+
diff --git a/trunk/Lib/gcj/javaprims.i b/trunk/Lib/gcj/javaprims.i
new file mode 100644
index 0000000..12c92a7
--- /dev/null
+++ b/trunk/Lib/gcj/javaprims.i
@@ -0,0 +1,422 @@
+%include <stdint.i>
+
+typedef int8_t jbyte;
+typedef int16_t jshort;
+typedef int32_t jint;
+typedef int64_t jlong;
+typedef float jfloat;
+typedef double jdouble;
+typedef jint jsize;
+typedef int8_t jboolean;
+
+extern "Java" 
+{
+  namespace java
+  {
+    namespace io
+    {
+      class BufferedInputStream;
+      class BufferedOutputStream;
+      class BufferedReader;
+      class BufferedWriter;
+      class ByteArrayInputStream;
+      class ByteArrayOutputStream;
+      class CharArrayReader;
+      class CharArrayWriter;
+      class CharConversionException;
+      class DataInput;
+      class DataInputStream;
+      class DataOutput;
+      class DataOutputStream;
+      class EOFException;
+      class Externalizable;
+      class File;
+      class FileDescriptor;
+      class FileFilter;
+      class FileInputStream;
+      class FileNotFoundException;
+      class FileOutputStream;
+      class FilePermission;
+      class FileReader;
+      class FileWriter;
+      class FilenameFilter;
+      class FilterInputStream;
+      class FilterOutputStream;
+      class FilterReader;
+      class FilterWriter;
+      class IOException;
+      class InputStream;
+      class InputStreamReader;
+      class InterfaceComparator;
+      class InterruptedIOException;
+      class InvalidClassException;
+      class InvalidObjectException;
+      class LineNumberInputStream;
+      class LineNumberReader;
+      class MemberComparator;
+      class NotActiveException;
+      class NotSerializableException;
+      class ObjectInput;
+      class ObjectInputStream;
+      class ObjectInputStream$GetField;
+      class ObjectInputValidation;
+      class ObjectOutput;
+      class ObjectOutputStream;
+      class ObjectOutputStream$PutField;
+      class ObjectStreamClass;
+      class ObjectStreamConstants;
+      class ObjectStreamException;
+      class ObjectStreamField;
+      class OptionalDataException;
+      class OutputStream;
+      class OutputStreamWriter;
+      class PipedInputStream;
+      class PipedOutputStream;
+      class PipedReader;
+      class PipedWriter;
+      class PrintStream;
+      class PrintWriter;
+      class PushbackInputStream;
+      class PushbackReader;
+      class RandomAccessFile;
+      class Reader;
+      class SequenceInputStream;
+      class Serializable;
+      class SerializablePermission;
+      class StreamCorruptedException;
+      class StreamTokenizer;
+      class StringBufferInputStream;
+      class StringReader;
+      class StringWriter;
+      class SyncFailedException;
+      class UTFDataFormatException;
+      class UnsupportedEncodingException;
+      class VMObjectStreamClass;
+      class ValidatorAndPriority;
+      class WriteAbortedException;
+      class Writer;
+    }
+
+    namespace lang
+    {
+      class AbstractMethodError;
+      class ArithmeticException;
+      class ArrayIndexOutOfBoundsException;
+      class ArrayStoreException;
+      class AssertionError;
+      class Boolean;
+      class Byte;
+      class CharSequence;
+      class Character;
+      class Character$Subset;
+      class Character$UnicodeBlock;
+      class Class;
+      class ClassCastException;
+      class ClassCircularityError;
+      class ClassFormatError;
+      class ClassLoader;
+      class ClassNotFoundException;
+      class CloneNotSupportedException;
+      class Cloneable;
+      class Comparable;
+      class Compiler;
+      class ConcreteProcess;
+      class Double;
+      class Error;
+      class Exception;
+      class ExceptionInInitializerError;
+      class Float;
+      class IllegalAccessError;
+      class IllegalAccessException;
+      class IllegalArgumentException;
+      class IllegalMonitorStateException;
+      class IllegalStateException;
+      class IllegalThreadStateException;
+      class IncompatibleClassChangeError;
+      class IndexOutOfBoundsException;
+      class InheritableThreadLocal;
+      class InstantiationError;
+      class InstantiationException;
+      class Integer;
+      class InternalError;
+      class InterruptedException;
+      class LinkageError;
+      class Long;
+      class Math;
+      class NegativeArraySizeException;
+      class NoClassDefFoundError;
+      class NoSuchFieldError;
+      class NoSuchFieldException;
+      class NoSuchMethodError;
+      class NoSuchMethodException;
+      class NullPointerException;
+      class Number;
+      class NumberFormatException;
+      class Object;
+      class OutOfMemoryError;
+      class Package;
+      class Process;
+      class Runnable;
+      class Runtime;
+      class RuntimeException;
+      class RuntimePermission;
+      class SecurityContext;
+      class SecurityException;
+      class SecurityManager;
+      class Short;
+      class StackOverflowError;
+      class StackTraceElement;
+      class StrictMath;
+      class String;
+      class String$CaseInsensitiveComparator;
+      class StringBuffer;
+      class StringIndexOutOfBoundsException;
+      class System;
+      class Thread;
+      class ThreadDeath;
+      class ThreadGroup;
+      class ThreadLocal;
+      class Throwable;
+      class UnknownError;
+      class UnsatisfiedLinkError;
+      class UnsupportedClassVersionError;
+      class UnsupportedOperationException;
+      class VMClassLoader;
+      class VMSecurityManager;
+      class VMThrowable;
+      class VerifyError;
+      class VirtualMachineError;
+      class Void;
+      namespace ref
+      {
+        class PhantomReference;
+        class Reference;
+        class ReferenceQueue;
+        class SoftReference;
+        class WeakReference;
+      }
+
+      namespace reflect
+      {
+        class AccessibleObject;
+        class Array;
+        class Constructor;
+        class Field;
+        class InvocationHandler;
+        class InvocationTargetException;
+        class Member;
+        class Method;
+        class Modifier;
+        class Proxy;
+        class Proxy$ClassFactory;
+        class Proxy$ProxyData;
+        class Proxy$ProxySignature;
+        class Proxy$ProxyType;
+        class ReflectPermission;
+        class UndeclaredThrowableException;
+      }
+    }
+
+    namespace util
+    {
+      class AbstractCollection;
+      class AbstractList;
+      class AbstractMap;
+      class AbstractMap$BasicMapEntry;
+      class AbstractSequentialList;
+      class AbstractSet;
+      class ArrayList;
+      class Arrays;
+      class Arrays$ArrayList;
+      class BitSet;
+      class Calendar;
+      class Collection;
+      class Collections;
+      class Collections$CopiesList;
+      class Collections$EmptyList;
+      class Collections$EmptyMap;
+      class Collections$EmptySet;
+      class Collections$ReverseComparator;
+      class Collections$SingletonList;
+      class Collections$SingletonMap;
+      class Collections$SingletonSet;
+      class Collections$SynchronizedCollection;
+      class Collections$SynchronizedIterator;
+      class Collections$SynchronizedList;
+      class Collections$SynchronizedListIterator;
+      class Collections$SynchronizedMap;
+      class Collections$SynchronizedMapEntry;
+      class Collections$SynchronizedRandomAccessList;
+      class Collections$SynchronizedSet;
+      class Collections$SynchronizedSortedMap;
+      class Collections$SynchronizedSortedSet;
+      class Collections$UnmodifiableCollection;
+      class Collections$UnmodifiableEntrySet;
+      class Collections$UnmodifiableIterator;
+      class Collections$UnmodifiableList;
+      class Collections$UnmodifiableListIterator;
+      class Collections$UnmodifiableMap;
+      class Collections$UnmodifiableRandomAccessList;
+      class Collections$UnmodifiableSet;
+      class Collections$UnmodifiableSortedMap;
+      class Collections$UnmodifiableSortedSet;
+      class Comparator;
+      class ConcurrentModificationException;
+      class Currency;
+      class Date;
+      class Dictionary;
+      class EmptyStackException;
+      class Enumeration;
+      class EventListener;
+      class EventListenerProxy;
+      class EventObject;
+      class GregorianCalendar;
+      class HashMap;
+      class HashMap$HashEntry;
+      class HashMap$HashIterator;
+      class HashSet;
+      class Hashtable;
+      class Hashtable$Enumerator;
+      class Hashtable$HashEntry;
+      class Hashtable$HashIterator;
+      class IdentityHashMap;
+      class IdentityHashMap$IdentityEntry;
+      class IdentityHashMap$IdentityIterator;
+      class Iterator;
+      class LinkedHashMap;
+      class LinkedHashMap$LinkedHashEntry;
+      class LinkedHashSet;
+      class LinkedList;
+      class LinkedList$Entry;
+      class LinkedList$LinkedListItr;
+      class List;
+      class ListIterator;
+      class ListResourceBundle;
+      class Locale;
+      class Map;
+      class Map$Entry;
+      class Map$Map;
+      class MissingResourceException;
+      class MyResources;
+      class NoSuchElementException;
+      class Observable;
+      class Observer;
+      class Properties;
+      class PropertyPermission;
+      class PropertyPermissionCollection;
+      class PropertyResourceBundle;
+      class Random;
+      class RandomAccess;
+      class RandomAccessSubList;
+      class ResourceBundle;
+      class Set;
+      class SimpleTimeZone;
+      class SortedMap;
+      class SortedSet;
+      class Stack;
+      class StringTokenizer;
+      class SubList;
+      class TimeZone;
+      class Timer;
+      class Timer$Scheduler;
+      class Timer$TaskQueue;
+      class TimerTask;
+      class TooManyListenersException;
+      class TreeMap;
+      class TreeMap$Node;
+      class TreeMap$SubMap;
+      class TreeMap$TreeIterator;
+      class TreeSet;
+      class Vector;
+      class WeakHashMap;
+      class WeakHashMap$WeakBucket;
+      class WeakHashMap$WeakEntry;
+      class WeakHashMap$WeakEntrySet;
+      namespace jar
+      {
+        class Attributes;
+        class Attributes$Name;
+        class JarEntry;
+        class JarException;
+        class JarFile;
+        class JarFile$JarEnumeration;
+        class JarInputStream;
+        class JarOutputStream;
+        class Manifest;
+      }
+
+      namespace logging
+      {
+        class ConsoleHandler;
+        class ErrorManager;
+        class FileHandler;
+        class Filter;
+        class Formatter;
+        class Handler;
+        class Level;
+        class LogManager;
+        class LogRecord;
+        class Logger;
+        class LoggingPermission;
+        class MemoryHandler;
+        class SimpleFormatter;
+        class SocketHandler;
+        class StreamHandler;
+        class XMLFormatter;
+      }
+
+      namespace prefs
+      {
+        class AbstractPreferences;
+        class BackingStoreException;
+        class InvalidPreferencesFormatException;
+        class NodeChangeEvent;
+        class NodeChangeListener;
+        class PreferenceChangeEvent;
+        class PreferenceChangeListener;
+        class Preferences;
+        class PreferencesFactory;
+      }
+
+      namespace regex
+      {
+        class Matcher;
+        class Pattern;
+        class PatternSyntaxException;
+      }
+
+      namespace zip
+      {
+        class Adler32;
+        class CRC32;
+        class CheckedInputStream;
+        class CheckedOutputStream;
+        class Checksum;
+        class DataFormatException;
+        class Deflater;
+        class DeflaterOutputStream;
+        class GZIPInputStream;
+        class GZIPOutputStream;
+        class Inflater;
+        class InflaterInputStream;
+        class ZipConstants;
+        class ZipEntry;
+        class ZipException;
+        class ZipFile;
+        class ZipFile$PartialInputStream;
+        class ZipFile$ZipEntryEnumeration;
+        class ZipInputStream;
+        class ZipOutputStream;
+      }
+    }
+  }
+}
+  
+typedef class java::lang::Object* jobject;
+typedef class java::lang::Class* jclass;
+typedef class java::lang::Throwable* jthrowable;
+typedef class java::lang::String* jstring;
+
+
+%include <gcj/cni.swg>
+
diff --git a/trunk/Lib/guile/Makefile b/trunk/Lib/guile/Makefile
new file mode 100644
index 0000000..ff66f9e
--- /dev/null
+++ b/trunk/Lib/guile/Makefile
@@ -0,0 +1,4 @@
+
+co::
+	co RCS/*.i* RCS/*.swg*
+
diff --git a/trunk/Lib/guile/common.scm b/trunk/Lib/guile/common.scm
new file mode 100644
index 0000000..a51d3a7
--- /dev/null
+++ b/trunk/Lib/guile/common.scm
@@ -0,0 +1,76 @@
+;;;************************************************************************
+;;;*common.scm
+;;;*
+;;;*     This file contains generic SWIG GOOPS classes for generated
+;;;*     GOOPS file support
+;;;*
+;;;* Copyright (C) 2003 John Lenz (jelenz@wisc.edu)
+;;;* Copyright (C) 2004 Matthias Koeppe (mkoeppe@mail.math.uni-magdeburg.de)
+;;;*
+;;;* This file may be freely redistributed without license or fee provided
+;;;* this copyright message remains intact.
+;;;************************************************************************
+
+(define-module (Swig swigrun))
+
+(define-module (Swig common)
+  #:use-module (oop goops)
+  #:use-module (Swig swigrun))
+
+(define-class <swig-metaclass> (<class>)
+  (new-function #:init-value #f))
+
+(define-method (initialize (class <swig-metaclass>) initargs)
+  (slot-set! class 'new-function (get-keyword #:new-function initargs #f))
+  (next-method))
+
+(define-class <swig> () 
+  (swig-smob #:init-value #f)
+  #:metaclass <swig-metaclass>
+)
+
+(define-method (initialize (obj <swig>) initargs)
+  (next-method)
+  (slot-set! obj 'swig-smob
+    (let ((arg (get-keyword #:init-smob initargs #f)))
+      (if arg
+        arg
+        (let ((ret (apply (slot-ref (class-of obj) 'new-function) (get-keyword #:args initargs '()))))
+          ;; if the class is registered with runtime environment,
+          ;; new-Function will return a <swig> goops class.  In that case, extract the smob
+          ;; from that goops class and set it as the current smob.
+          (if (slot-exists? ret 'swig-smob)
+            (slot-ref ret 'swig-smob)
+            ret))))))
+
+(define (display-address o file)
+  (display (number->string (object-address o) 16) file))
+
+(define (display-pointer-address o file)
+  ;; Don't fail if the function SWIG-PointerAddress is not present.
+  (let ((address (false-if-exception (SWIG-PointerAddress o))))
+    (if address
+	(begin
+	  (display " @ " file)
+	  (display (number->string address 16) file)))))
+
+(define-method (write (o <swig>) file)
+  ;; We display _two_ addresses to show the object's identity:
+  ;;  * first the address of the GOOPS proxy object,
+  ;;  * second the pointer address.
+  ;; The reason is that proxy objects are created and discarded on the
+  ;; fly, so different proxy objects for the same C object will appear.
+  (let ((class (class-of o)))
+    (if (slot-bound? class 'name)
+	(begin
+	  (display "#<" file)
+	  (display (class-name class) file)
+	  (display #\space file)
+	  (display-address o file)
+	  (display-pointer-address o file)
+	  (display ">" file))
+	(next-method))))
+                                              
+(export <swig-metaclass> <swig>)
+
+;;; common.scm ends here
diff --git a/trunk/Lib/guile/cplusplus.i b/trunk/Lib/guile/cplusplus.i
new file mode 100644
index 0000000..cb4cf74
--- /dev/null
+++ b/trunk/Lib/guile/cplusplus.i
@@ -0,0 +1,25 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cplusplus.i
+ *
+ * SWIG typemaps for C++
+ * ----------------------------------------------------------------------------- */
+
+%typemap(guile,out) string, std::string {
+  $result = gh_str02scm(const_cast<char*>($1.c_str()));
+}
+%typemap(guile,in) string, std::string {
+  $1 = SWIG_scm2str($input);
+}
+
+%typemap(guile,out) complex, complex<double>, std::complex<double> {
+  $result = scm_make_rectangular( gh_double2scm ($1.real ()),
+           gh_double2scm ($1.imag ()) );
+}
+%typemap(guile,in) complex, complex<double>, std::complex<double> {
+  $1 = std::complex<double>( gh_scm2double (scm_real_part ($input)),
+           gh_scm2double (scm_imag_part ($input)) );
+}
+
diff --git a/trunk/Lib/guile/extra-install.list b/trunk/Lib/guile/extra-install.list
new file mode 100644
index 0000000..05d2c0c
--- /dev/null
+++ b/trunk/Lib/guile/extra-install.list
@@ -0,0 +1,2 @@
+# see top-level Makefile.in
+common.scm
diff --git a/trunk/Lib/guile/ghinterface.i b/trunk/Lib/guile/ghinterface.i
new file mode 100644
index 0000000..c5fda62
--- /dev/null
+++ b/trunk/Lib/guile/ghinterface.i
@@ -0,0 +1,39 @@
+#define gh_append2(a, b) scm_append(scm_listify(a, b, SCM_UNDEFINED)) 
+#define gh_apply(a, b) scm_apply(a, b, SCM_EOL) 
+#define gh_bool2scm SCM_BOOL 
+#define gh_boolean_p SCM_BOOLP 
+#define gh_car SCM_CAR 
+#define gh_cdr SCM_CDR 
+#define gh_cons scm_cons 
+#define gh_double2scm scm_make_real 
+#define gh_int2scm scm_long2num 
+#define gh_length(lst) scm_num2ulong(scm_length(lst), SCM_ARG1, FUNC_NAME) 
+#define gh_list scm_listify 
+#define gh_list_to_vector scm_vector 
+#define gh_make_vector scm_make_vector 
+#define gh_null_p SCM_NULLP 
+#define gh_number_p SCM_NUMBERP 
+#define gh_pair_p SCM_CONSP 
+#define gh_scm2bool SCM_NFALSEP
+#define gh_scm2char SCM_CHAR 
+#define gh_scm2double(a) scm_num2dbl(a, FUNC_NAME) 
+#define gh_scm2int(a) scm_num2int(a, SCM_ARG1, FUNC_NAME) 
+#define gh_scm2long(a) scm_num2long(a, SCM_ARG1, FUNC_NAME) 
+#define gh_scm2short(a) scm_num2short(a, SCM_ARG1, FUNC_NAME)
+#define gh_scm2newstr SWIG_Guile_scm2newstr
+#define gh_scm2ulong(a) scm_num2ulong(a, SCM_ARG1, FUNC_NAME)
+#define gh_scm2ushort(a) scm_num2ushort(a, SCM_ARG1, FUNC_NAME)
+#define gh_scm2uint(a) scm_num2uint(a, SCM_ARG1, FUNC_NAME)
+#define gh_ulong2scm scm_ulong2num
+#define gh_long2scm scm_long2num
+#define gh_str02scm scm_makfrom0str 
+#define gh_long_long2scm scm_long_long2num
+#define gh_scm2long_long(a) scm_num2long_long(a, SCM_ARG1, FUNC_NAME)
+#define gh_ulong_long2scm scm_ulong_long2num
+#define gh_scm2ulong_long(a) scm_num2ulong_long(a, SCM_ARG1, FUNC_NAME)
+#define gh_string_p SCM_STRINGP 
+#define gh_vector_length SCM_VECTOR_LENGTH 
+#define gh_vector_p SCM_VECTORP 
+#define gh_vector_ref scm_vector_ref 
+#define gh_vector_set_x scm_vector_set_x 
+#define gh_char2scm SCM_MAKE_CHAR
diff --git a/trunk/Lib/guile/guile.i b/trunk/Lib/guile/guile.i
new file mode 100644
index 0000000..1bf28d6
--- /dev/null
+++ b/trunk/Lib/guile/guile.i
@@ -0,0 +1,36 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guile.i
+ *
+ * SWIG Configuration File for Guile.
+ * ----------------------------------------------------------------------------- */
+
+/* Macro for inserting Scheme code into the stub */
+#define %scheme	    %insert("scheme")
+#define %goops      %insert("goops")
+
+/* Return-styles */
+%pragma(guile) return_nothing_doc = "Returns unspecified."
+%pragma(guile) return_one_doc = "Returns $values."
+
+%define %values_as_list
+  %pragma(guile) beforereturn = ""
+  %pragma(guile) return_multi_doc = "Returns a list of $num_values values: $values."
+%enddef
+%values_as_list /* the default style */
+
+%define %values_as_vector
+  %pragma(guile) beforereturn = "GUILE_MAYBE_VECTOR"
+  %pragma(guile) return_multi_doc = "Returns a vector of $num_values values: $values."
+%enddef
+
+%define %multiple_values
+  %pragma(guile) beforereturn = "GUILE_MAYBE_VALUES"
+  %pragma(guile) return_multi_doc = "Returns $num_values values: $values."
+%enddef
+
+#define GUILE_APPEND_RESULT SWIG_APPEND_VALUE
+
+%include <typemaps.i>
diff --git a/trunk/Lib/guile/guile_gh.swg b/trunk/Lib/guile/guile_gh.swg
new file mode 100644
index 0000000..6412a4c
--- /dev/null
+++ b/trunk/Lib/guile/guile_gh.swg
@@ -0,0 +1,74 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guile_gh.swg
+ *
+ * This SWIG interface file is processed if the Guile module is run
+ * with gh_ flavor.
+ * ----------------------------------------------------------------------------- */
+
+#define SWIGGUILE_GH
+
+%runtime "swigrun.swg"
+%runtime "guile_gh_run.swg"
+
+#define SWIG_convert_short(o)					\
+  SWIG_convert_integer(o, - (1 << (8 * sizeof(short) - 1)),	\
+		       (1 << (8 * sizeof(short) - 1)) - 1,	\
+		       FUNC_NAME, $argnum)
+#define SWIG_convert_unsigned_short(o)			\
+  SWIG_convert_unsigned_integer(o, 0,				\
+		       (1 << (8 * sizeof(short))) - 1,	\
+		       FUNC_NAME, $argnum)
+#define SWIG_convert_unsigned_int(o)		\
+  SWIG_convert_unsigned_integer(o, 0, UINT_MAX,	\
+		       FUNC_NAME, $argnum)
+
+#define gh_scm2short(a) SWIG_convert_short(a)
+#define gh_scm2ushort(a) SWIG_convert_unsigned_short(a)
+#define gh_scm2uint(a)   SWIG_convert_unsigned_int(a)
+
+%include <guile.i>
+
+%runtime %{
+
+/* scm_values was implemented on C level in 1.4.1, and the prototype
+   is not included in libguile.h, so play safe and lookup `values'... */
+#define GUILE_MAYBE_VALUES						\
+    if (gswig_list_p)							\
+        gswig_result = gh_apply(gh_lookup("values"), gswig_result);
+    
+#define GUILE_MAYBE_VECTOR				\
+    if (gswig_list_p)					\
+        gswig_result = gh_list_to_vector(gswig_result);
+
+#define SWIG_APPEND_VALUE(object)						\
+    if (gswig_result == SCM_UNSPECIFIED) {		\
+        gswig_result = object;							\
+    } else {									\
+        if (!gswig_list_p) {							\
+	    gswig_list_p = 1;							\
+	    gswig_result = gh_list(gswig_result, object, SCM_UNDEFINED);	\
+        }									\
+        else									\
+            gswig_result = gh_append2(gswig_result,				\
+                                      gh_list(object, SCM_UNDEFINED));		\
+    }
+
+%}
+
+%init "swiginit.swg"
+
+%init %{
+static int _swig_module_smob_tag;
+
+SWIG_GUILE_INIT_STATIC void
+SWIG_init(void)
+{
+
+  SWIG_InitializeModule(0);
+  swig_module.clientdata = (void *) &_swig_module_smob_tag;
+
+  SWIG_Guile_Init(&swig_module);
+%}
diff --git a/trunk/Lib/guile/guile_gh_run.swg b/trunk/Lib/guile/guile_gh_run.swg
new file mode 100644
index 0000000..5b1fca0
--- /dev/null
+++ b/trunk/Lib/guile/guile_gh_run.swg
@@ -0,0 +1,261 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guile_gh_run.swg
+ *
+ * Guile GH runtime file
+ * ----------------------------------------------------------------------------- */
+
+#define SWIGGUILE
+#include "guile/gh.h"
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef SCM (*swig_guile_proc)();
+
+#define SWIG_malloc(size) \
+  SCM_MUST_MALLOC(size)
+#define SWIG_free(mem) \
+  scm_must_free(mem)
+#define SWIG_ConvertPtr(s, result, type, flags) \
+  SWIG_Guile_ConvertPtr(&swig_module, s, result, type, flags)
+#define SWIG_MustGetPtr(s, type, argnum, flags) \
+  SWIG_Guile_MustGetPtr(&swig_module, s, type, argnum, flags, FUNC_NAME)
+#define SWIG_NewPointerObj(ptr, type, owner) \
+  SWIG_Guile_NewPointerObj(&swig_module, (void*)ptr, type, owner)
+#define SWIG_GetModule(clientdata) SWIG_Guile_GetModule()
+#define SWIG_SetModule(clientdata, pointer) SWIG_Guile_SetModule(pointer)
+
+/* Ignore object-ownership changes in gh mode */
+#define SWIG_Guile_MarkPointerNoncollectable(s) (s)
+#define SWIG_Guile_MarkPointerDestroyed(s) (s)
+  
+#define SWIG_contract_assert(expr, msg)				\
+  if (!(expr))							\
+    scm_error(gh_symbol2scm("swig-contract-assertion-failed"),	\
+	      (char *) FUNC_NAME, (char *) msg,			\
+	      SCM_EOL, SCM_BOOL_F); else
+
+/* SCM_CHAR and SCM_CHARP were introduced in Guile 1.4; the following is for
+   1.3.4 compatibility. */
+#ifndef SCM_CHAR
+#  define SCM_CHAR SCM_ICHR
+#endif
+#ifndef SCM_CHARP
+#  define SCM_CHARP SCM_ICHRP
+#endif
+
+/* This function replaces gh_scm2char, which is broken in Guile 1.4 */
+SWIGINTERN char
+GSWIG_scm2char (SCM s)
+{
+  if (SCM_CHARP(s)) return SCM_CHAR(s);
+  scm_wrong_type_arg(NULL, 0, s);
+}
+#define gh_scm2char GSWIG_scm2char
+
+/* Interface function */
+#define SWIG_scm2str(x) gh_scm2newstr(x, NULL)
+
+/* More 1.3.4 compatibility */
+#ifndef SCM_INPUT_PORT_P
+#  define SCM_INPUT_PORT_P SCM_INPORTP
+#  define SCM_OUTPUT_PORT_P SCM_OUTPORTP
+#endif
+
+SWIGINTERN long
+SWIG_convert_integer(SCM o,
+		     long lower_bound, long upper_bound, 
+		     const char *func_name, int argnum)
+{
+  long value = gh_scm2long(o);
+  if (value < lower_bound || value > upper_bound)
+    scm_wrong_type_arg((char *) func_name, argnum, o);
+  return value;
+}
+  
+SWIGINTERN unsigned long
+SWIG_convert_unsigned_integer(SCM o,
+			      unsigned long lower_bound,
+			      unsigned long upper_bound, 
+			      const char *func_name, int argnum)
+{
+  unsigned long value = gh_scm2ulong(o);
+  if (value < lower_bound || value > upper_bound)
+    scm_wrong_type_arg((char *) func_name, argnum, o);
+  return value;
+}
+
+SWIGINTERN swig_type_info *
+SWIG_Guile_LookupType(swig_module_info *module, SCM s, int normal) 
+{
+  swig_module_info *iter;
+  if (!module) return 0;
+  iter = module;
+  do {
+    if ((normal && (unsigned long) SCM_TYP16(s) == *((int *)iter->clientdata))) {
+        
+      return iter->types[(long) SCM_CAR(s) >> 16];
+    }
+    iter = iter->next;
+  } while (iter != module);
+  return 0;
+}
+
+#ifdef SWIG_GLOBAL
+#define SWIG_GUILE_MODULE_STATIC
+#elif !defined(SWIG_NOINCLUDE)
+#define SWIG_GUILE_MODULE_STATIC static
+#endif
+
+#ifdef SWIG_GUILE_MODULE_STATIC
+static swig_module_info *swig_guile_module = 0;
+SWIG_GUILE_MODULE_STATIC swig_module_info *SWIG_Guile_GetModule(void) {
+  return swig_guile_module;
+}
+SWIG_GUILE_MODULE_STATIC void SWIG_Guile_SetModule(swig_module_info *pointer) {
+  swig_guile_module = pointer;
+}
+#else
+SWIGEXPORT swig_module_info * SWIG_Guile_GetModule(void);
+SWIGEXPORT void SWIG_Guile_SetModule(swig_module_info *pointer);
+#endif
+
+SWIGINTERN SCM
+SWIG_Guile_NewPointerObj(swig_module_info *module, void *ptr, 
+			 swig_type_info *type, int owner)
+{
+  unsigned long tag;
+  if (ptr==NULL) return SCM_EOL;
+  if (!module) return SCM_EOL;
+  for (tag = 0; tag < module->size; ++tag) {
+    if (module->types[tag] == type)
+      break;
+  }
+  if (tag >= module->size)
+    return SCM_EOL;
+    
+
+  SCM_RETURN_NEWSMOB( ((tag << 16) | *((int *)module->clientdata)), ptr);
+}
+
+/* Return 0 if successful. */
+SWIGINTERN int
+SWIG_Guile_ConvertPtr(swig_module_info *module, SCM s, void **result, 
+		      swig_type_info *type, int flags)
+{
+  swig_cast_info *cast;
+  swig_type_info *from;
+  if (SCM_NULLP(s)) {
+    *result = NULL;
+    return SWIG_OK;
+  } else if (SCM_NIMP(s)) {
+    from = SWIG_Guile_LookupType(module, s, 1);
+    if (!from) return SWIG_ERROR;
+    if (type) {
+      cast = SWIG_TypeCheckStruct(from, type);
+      if (cast) {
+        int newmemory = 0;
+        *result = SWIG_TypeCast(cast, (void *) SCM_CDR(s), &newmemory);
+        assert(!newmemory); /* newmemory handling not yet implemented */
+        return SWIG_OK;
+      } else {
+        return SWIG_ERROR;
+      }
+    } else {
+      *result = (void *) SCM_CDR(s);
+      return SWIG_OK;
+    }
+  }
+  return SWIG_ERROR;
+}
+
+SWIGINTERN void *
+SWIG_Guile_MustGetPtr (swig_module_info *module, SCM s, swig_type_info *type,
+                       int argnum, int flags, const char *func_name)
+{
+  void *result;
+  int res = SWIG_Guile_ConvertPtr(module, s, &result, type, flags);
+  if (!SWIG_IsOK(res)) {
+    /* type mismatch */
+    scm_wrong_type_arg((char *) func_name, argnum, s);
+  }
+  return result;
+}
+
+/* Init */
+
+SWIGINTERN int
+print_swig (SCM swig_smob, SCM port, scm_print_state *pstate)
+{
+  swig_type_info *type = SWIG_Guile_LookupType(0, swig_smob, 1);
+  if (type) {
+    scm_puts((char *) "#<swig ", port);
+    if (type->str != NULL)
+      scm_puts((char *) type->str, port);
+    else 
+      scm_puts((char *) type->name, port);
+    scm_puts((char *) " ", port);
+    scm_intprint((long) SCM_CDR(swig_smob), 16, port);
+    scm_puts((char *) ">", port);
+    /* non-zero means success */
+    return 1;
+  } else {
+    return 0;
+  }
+}
+
+SWIGINTERN SCM
+equalp_swig (SCM A, SCM B)
+{
+  if (SCM_CAR(A) == SCM_CAR(B)
+      && SCM_CDR(A) == SCM_CDR(B))
+    return SCM_BOOL_T;
+  else return SCM_BOOL_F;
+}
+
+SWIGINTERN void
+SWIG_Guile_Init (swig_module_info *module)
+{
+    *((int *)module->clientdata) = 
+         scm_make_smob_type_mfpe((char *) "swig", 0, NULL, NULL, print_swig, equalp_swig);
+}
+
+SWIGINTERN int
+SWIG_Guile_GetArgs (SCM *dest, SCM rest,
+		    int reqargs, int optargs,
+		    const char *procname)
+{
+  int i;
+  int num_args_passed = 0;
+  for (i = 0; i<reqargs; i++) {
+    if (!SCM_CONSP(rest))
+      scm_wrong_num_args(gh_str02scm((char *) procname));
+    *dest++ = SCM_CAR(rest);
+    rest = SCM_CDR(rest);
+    num_args_passed++;
+  }
+  for (i = 0; i<optargs && SCM_CONSP(rest); i++) {
+    *dest++ = SCM_CAR(rest);
+    rest = SCM_CDR(rest);
+    num_args_passed++;
+  }
+  for (; i<optargs; i++)
+    *dest++ = SCM_UNDEFINED;
+  if (!SCM_NULLP(rest))
+    scm_wrong_num_args(gh_str02scm((char *) procname));
+  return num_args_passed;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/* guile.swg ends here */
diff --git a/trunk/Lib/guile/guile_scm.swg b/trunk/Lib/guile/guile_scm.swg
new file mode 100644
index 0000000..caded72
--- /dev/null
+++ b/trunk/Lib/guile/guile_scm.swg
@@ -0,0 +1,53 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guile_scm.swg
+ *
+ * This SWIG interface file is processed if the Guile module is run
+ * with SCM_ flavor.
+ * ----------------------------------------------------------------------------- */
+
+#define SWIGGUILE_SCM
+
+%runtime "swigrun.swg"       // Common C API type-checking code
+
+%runtime "guile_scm_run.swg"
+%include <ghinterface.i>
+%include <guile.i>
+
+%runtime %{
+
+#define GUILE_MAYBE_VALUES \
+      if (gswig_list_p) gswig_result = scm_values(gswig_result);
+
+#define GUILE_MAYBE_VECTOR \
+      if (gswig_list_p) gswig_result = scm_vector(gswig_result);
+
+#define SWIG_APPEND_VALUE(object)						\
+    if (gswig_result == SCM_UNSPECIFIED)						\
+        gswig_result = object;							\
+    else {									\
+      if (!gswig_list_p) {							\
+	      gswig_list_p = 1;							\
+	      gswig_result = scm_listify(gswig_result, object, SCM_UNDEFINED);	\
+      }									\
+      else									\
+            gswig_result = scm_append(scm_listify(gswig_result, scm_listify(object, SCM_UNDEFINED), SCM_UNDEFINED));		\
+    }
+    /* used by Lib/exception.i */
+    #define gh_symbol2scm scm_str2symbol
+    /* useb by Lib/cdata.i */
+    #define gh_str2scm scm_mem2string
+
+%}
+
+%insert(init) "swiginit.swg"
+
+%init %{
+SWIG_GUILE_INIT_STATIC void
+SWIG_init(void)
+{
+  SWIG_InitializeModule(0);
+  SWIG_PropagateClientData();
+%}
diff --git a/trunk/Lib/guile/guile_scm_run.swg b/trunk/Lib/guile/guile_scm_run.swg
new file mode 100644
index 0000000..5da8558
--- /dev/null
+++ b/trunk/Lib/guile/guile_scm_run.swg
@@ -0,0 +1,485 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guile_scm_run.swg
+ * ----------------------------------------------------------------------------- */
+
+#include <libguile.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef SCM (*swig_guile_proc)();
+typedef SCM (*guile_destructor)(SCM);
+
+typedef struct swig_guile_clientdata {
+  guile_destructor destroy;
+  SCM goops_class;
+} swig_guile_clientdata;
+
+#define SWIG_scm2str(s) \
+  SWIG_Guile_scm2newstr(s, NULL)
+#define SWIG_malloc(size) \
+  SCM_MUST_MALLOC(size)
+#define SWIG_free(mem) \
+  scm_must_free(mem)
+#define SWIG_ConvertPtr(s, result, type, flags) \
+  SWIG_Guile_ConvertPtr(s, result, type, flags)
+#define SWIG_MustGetPtr(s, type, argnum, flags) \
+  SWIG_Guile_MustGetPtr(s, type, argnum, flags, FUNC_NAME)
+#define SWIG_NewPointerObj(ptr, type, owner) \
+  SWIG_Guile_NewPointerObj((void*)ptr, type, owner)
+#define SWIG_PointerAddress(object) \
+  SWIG_Guile_PointerAddress(object)
+#define SWIG_PointerType(object) \
+  SWIG_Guile_PointerType(object)
+#define SWIG_IsPointerOfType(object, type) \
+  SWIG_Guile_IsPointerOfType(object, type)
+#define SWIG_IsPointer(object) \
+  SWIG_Guile_IsPointer(object)
+#define SWIG_contract_assert(expr, msg)				\
+  if (!(expr))							\
+    scm_error(scm_str2symbol("swig-contract-assertion-failed"),	\
+	      (char *) FUNC_NAME, (char *) msg,			\
+	      SCM_EOL, SCM_BOOL_F); else
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty) \
+  SWIG_Guile_ConvertMember(obj, ptr, sz, ty, FUNC_NAME)
+#define SWIG_NewMemberObj(ptr, sz, type) \
+  SWIG_Guile_NewMemberObj(ptr, sz, type, FUNC_NAME)
+  
+/* Runtime API */
+static swig_module_info *SWIG_Guile_GetModule(void);
+#define SWIG_GetModule(clientdata) SWIG_Guile_GetModule()
+#define SWIG_SetModule(clientdata, pointer) SWIG_Guile_SetModule(pointer)
+  
+SWIGINTERN char *
+SWIG_Guile_scm2newstr(SCM str, size_t *len) {
+#define FUNC_NAME "SWIG_Guile_scm2newstr"
+  char *ret;
+  size_t l;
+
+  SCM_ASSERT (SCM_STRINGP(str), str, 1, FUNC_NAME);
+  
+  l = SCM_STRING_LENGTH(str);
+  ret = (char *) SWIG_malloc( (l + 1) * sizeof(char));
+  if (!ret) return NULL;
+
+  memcpy(ret, SCM_STRING_CHARS(str), l);
+  ret[l] = '\0';
+  if (len) *len = l;
+  return ret;
+#undef FUNC_NAME
+}
+
+static int swig_initialized = 0;
+static scm_t_bits swig_tag = 0;
+static scm_t_bits swig_collectable_tag = 0;
+static scm_t_bits swig_destroyed_tag = 0;
+static scm_t_bits swig_member_function_tag = 0;
+static SCM swig_make_func = SCM_EOL;
+static SCM swig_keyword = SCM_EOL;
+static SCM swig_symbol = SCM_EOL;
+
+#define SWIG_Guile_GetSmob(x) \
+  ( SCM_NNULLP(x) && SCM_INSTANCEP(x) && SCM_NFALSEP(scm_slot_exists_p(x, swig_symbol)) \
+      ? scm_slot_ref(x, swig_symbol) : (x) )
+
+SWIGINTERN SCM
+SWIG_Guile_NewPointerObj(void *ptr, swig_type_info *type, int owner)
+{
+  if (ptr == NULL)
+    return SCM_EOL;
+  else {
+    SCM smob;
+    swig_guile_clientdata *cdata = (swig_guile_clientdata *) type->clientdata;
+    if (owner)
+      SCM_NEWSMOB2(smob, swig_collectable_tag, ptr, (void *) type);
+    else
+      SCM_NEWSMOB2(smob, swig_tag, ptr, (void *) type);
+
+    if (!cdata || SCM_NULLP(cdata->goops_class) || swig_make_func == SCM_EOL ) {
+      return smob;
+    } else {
+      /* the scm_make() C function only handles the creation of gf,
+	 methods and classes (no instances) the (make ...) function is
+	 later redefined in goops.scm.  So we need to call that
+	 Scheme function. */
+      return scm_apply(swig_make_func,
+		       scm_list_3(cdata->goops_class,
+				  swig_keyword,
+				  smob),
+		       SCM_EOL);
+    }
+  }
+}
+
+SWIGINTERN unsigned long
+SWIG_Guile_PointerAddress(SCM object)
+{
+  SCM smob = SWIG_Guile_GetSmob(object);
+  if (SCM_NULLP(smob)) return 0;
+  else if (SCM_SMOB_PREDICATE(swig_tag, smob)
+	   || SCM_SMOB_PREDICATE(swig_collectable_tag, smob)
+	   || SCM_SMOB_PREDICATE(swig_destroyed_tag, smob)) {
+    return (unsigned long) (void *) SCM_CELL_WORD_1(smob);
+  }
+  else scm_wrong_type_arg("SWIG-Guile-PointerAddress", 1, object);
+}
+
+SWIGINTERN swig_type_info *
+SWIG_Guile_PointerType(SCM object)
+{
+  SCM smob = SWIG_Guile_GetSmob(object);
+  if (SCM_NULLP(smob)) return NULL;
+  else if (SCM_SMOB_PREDICATE(swig_tag, smob)
+	   || SCM_SMOB_PREDICATE(swig_collectable_tag, smob)
+	   || SCM_SMOB_PREDICATE(swig_destroyed_tag, smob)) {
+    return (swig_type_info *) SCM_CELL_WORD_2(smob);
+  }
+  else scm_wrong_type_arg("SWIG-Guile-PointerType", 1, object);
+}
+  
+SWIGINTERN int
+SWIG_Guile_ConvertPtr(SCM s, void **result, swig_type_info *type, int flags)
+{
+  swig_cast_info *cast;
+  swig_type_info *from;
+  SCM smob = SWIG_Guile_GetSmob(s);
+
+  if (SCM_NULLP(smob)) {
+    *result = NULL;
+    return SWIG_OK;
+  } else if (SCM_SMOB_PREDICATE(swig_tag, smob) || SCM_SMOB_PREDICATE(swig_collectable_tag, smob)) {
+    /* we do not accept smobs representing destroyed pointers */
+    from = (swig_type_info *) SCM_CELL_WORD_2(smob);
+    if (!from) return SWIG_ERROR;
+    if (type) {
+      cast = SWIG_TypeCheckStruct(from, type);
+      if (cast) {
+        int newmemory = 0;
+        *result = SWIG_TypeCast(cast, (void *) SCM_CELL_WORD_1(smob), &newmemory);
+        assert(!newmemory); /* newmemory handling not yet implemented */
+        return SWIG_OK;
+      } else {
+        return SWIG_ERROR;
+      }
+    } else {
+      *result = (void *) SCM_CELL_WORD_1(smob);
+      return SWIG_OK;
+    }
+  }
+  return SWIG_ERROR;
+}
+
+SWIGINTERNINLINE void *
+SWIG_Guile_MustGetPtr (SCM s, swig_type_info *type,
+		       int argnum, int flags, const char *func_name)
+{
+  void *result;
+  int res = SWIG_Guile_ConvertPtr(s, &result, type, flags);
+  if (!SWIG_IsOK(res)) {
+    /* type mismatch */
+    scm_wrong_type_arg((char *) func_name, argnum, s);
+  }
+  return result;
+}
+
+SWIGINTERNINLINE int
+SWIG_Guile_IsPointerOfType (SCM s, swig_type_info *type)
+{
+  void *result;
+  if (SWIG_Guile_ConvertPtr(s, &result, type, 0)) {
+    /* type mismatch */
+    return 0;
+  }
+  else return 1;
+}
+
+SWIGINTERNINLINE int
+SWIG_Guile_IsPointer (SCM s)
+{
+  /* module might not be initialized yet, so initialize it */
+  SWIG_Guile_GetModule();
+  return SWIG_Guile_IsPointerOfType (s, NULL);
+}
+
+/* Mark a pointer object non-collectable */
+SWIGINTERN void
+SWIG_Guile_MarkPointerNoncollectable(SCM s)
+{
+  SCM smob = SWIG_Guile_GetSmob(s);
+  if (!SCM_NULLP(smob)) {
+    if (SCM_SMOB_PREDICATE(swig_tag, smob) || SCM_SMOB_PREDICATE(swig_collectable_tag, smob)) {
+      SCM_SET_CELL_TYPE(smob, swig_tag);
+    }
+    else scm_wrong_type_arg(NULL, 0, s);
+  }
+}
+
+/* Mark a pointer object destroyed */
+SWIGINTERN void
+SWIG_Guile_MarkPointerDestroyed(SCM s)
+{
+  SCM smob = SWIG_Guile_GetSmob(s);
+  if (!SCM_NULLP(smob)) {
+    if (SCM_SMOB_PREDICATE(swig_tag, smob) || SCM_SMOB_PREDICATE(swig_collectable_tag, smob)) {
+      SCM_SET_CELL_TYPE(smob, swig_destroyed_tag);
+    }
+    else scm_wrong_type_arg(NULL, 0, s);
+  }
+}
+
+/* Member functions */
+
+SWIGINTERN SCM
+SWIG_Guile_NewMemberObj(void *ptr, size_t sz, swig_type_info *type,
+			const char *func_name)
+{
+  SCM smob;
+  void *copy = malloc(sz);
+  memcpy(copy, ptr, sz);
+  SCM_NEWSMOB2(smob, swig_member_function_tag, copy, (void *) type);
+  return smob;
+}
+
+SWIGINTERN int
+SWIG_Guile_ConvertMember(SCM smob, void *ptr, size_t sz, swig_type_info *type,
+			 const char *func_name)
+{
+  swig_cast_info *cast;
+  swig_type_info *from;
+
+  if (SCM_SMOB_PREDICATE(swig_member_function_tag, smob)) {
+    from = (swig_type_info *) SCM_CELL_WORD_2(smob);
+    if (!from) return SWIG_ERROR;
+    if (type) {
+      cast = SWIG_TypeCheckStruct(from, type);
+      if (!cast) return SWIG_ERROR;
+    }
+    memcpy(ptr, (void *) SCM_CELL_WORD_1(smob), sz);
+    return SWIG_OK;
+  }
+  return SWIG_ERROR;
+}
+     
+
+/* Init */
+
+SWIGINTERN int
+print_swig_aux (SCM swig_smob, SCM port, scm_print_state *pstate, 
+                const char *attribute)
+{
+  swig_type_info *type;
+  
+  type = (swig_type_info *) SCM_CELL_WORD_2(swig_smob);
+  if (type) {
+    scm_puts((char *) "#<", port);
+    scm_puts((char *) attribute, port);
+    scm_puts((char *) "swig-pointer ", port);
+    scm_puts((char *) SWIG_TypePrettyName(type), port);
+    scm_puts((char *) " ", port);
+    scm_intprint((long) SCM_CELL_WORD_1(swig_smob), 16, port);
+    scm_puts((char *) ">", port);
+    /* non-zero means success */
+    return 1;
+  } else {
+    return 0;
+  }
+}
+
+  
+SWIGINTERN int
+print_swig (SCM swig_smob, SCM port, scm_print_state *pstate)
+{
+  return print_swig_aux(swig_smob, port, pstate, "");
+}
+
+SWIGINTERN int
+print_collectable_swig (SCM swig_smob, SCM port, scm_print_state *pstate)
+{
+  return print_swig_aux(swig_smob, port, pstate, "collectable-");
+}
+
+SWIGINTERN int
+print_destroyed_swig (SCM swig_smob, SCM port, scm_print_state *pstate)
+{
+  return print_swig_aux(swig_smob, port, pstate, "destroyed-");
+}
+
+SWIGINTERN int
+print_member_function_swig (SCM swig_smob, SCM port, scm_print_state *pstate)
+{
+  swig_type_info *type;
+  type = (swig_type_info *) SCM_CELL_WORD_2(swig_smob);
+  if (type) {
+    scm_puts((char *) "#<", port);
+    scm_puts((char *) "swig-member-function-pointer ", port);
+    scm_puts((char *) SWIG_TypePrettyName(type), port);
+    scm_puts((char *) " >", port);
+    /* non-zero means success */
+    return 1;
+  } else {
+    return 0;
+  }
+}
+
+SWIGINTERN SCM
+equalp_swig (SCM A, SCM B)
+{
+  if (SCM_CELL_WORD_0(A) == SCM_CELL_WORD_0(B) && SCM_CELL_WORD_1(A) == SCM_CELL_WORD_1(B) 
+      && SCM_CELL_WORD_2(A) == SCM_CELL_WORD_2(B))
+    return SCM_BOOL_T;
+  else return SCM_BOOL_F;
+}
+
+SWIGINTERN size_t
+free_swig(SCM A)
+{
+  swig_type_info *type = (swig_type_info *) SCM_CELL_WORD_2(A);
+  if (type) {
+    if (type->clientdata && ((swig_guile_clientdata *)type->clientdata)->destroy)
+      ((swig_guile_clientdata *)type->clientdata)->destroy(A);
+  } 
+  return 0;
+}
+
+SWIGINTERN size_t
+free_swig_member_function(SCM A)
+{
+  free((swig_type_info *) SCM_CELL_WORD_1(A));
+  return 0;
+}
+
+SWIGINTERN int
+ensure_smob_tag(SCM swig_module,
+		scm_t_bits *tag_variable,
+		const char *smob_name,
+		const char *scheme_variable_name)
+{
+  SCM variable = scm_sym2var(scm_str2symbol(scheme_variable_name),
+			     scm_module_lookup_closure(swig_module),
+			     SCM_BOOL_T);
+  if (SCM_UNBNDP(SCM_VARIABLE_REF(variable))) {
+    *tag_variable = scm_make_smob_type((char*)scheme_variable_name, 0);
+    SCM_VARIABLE_SET(variable,
+		     scm_ulong2num(*tag_variable));
+    return 1;
+  }
+  else {
+    *tag_variable = scm_num2ulong(SCM_VARIABLE_REF(variable), 0,
+				  "SWIG_Guile_Init");
+    return 0;
+  }
+}
+
+SWIGINTERN SCM
+SWIG_Guile_Init ()
+{
+  static SCM swig_module;
+  
+  if (swig_initialized) return swig_module;
+  swig_initialized = 1;
+
+  swig_module = scm_c_resolve_module("Swig swigrun");
+  if (ensure_smob_tag(swig_module, &swig_tag,
+		      "swig-pointer", "swig-pointer-tag")) {
+    scm_set_smob_print(swig_tag, print_swig);
+    scm_set_smob_equalp(swig_tag, equalp_swig);
+  }
+  if (ensure_smob_tag(swig_module, &swig_collectable_tag,
+		      "collectable-swig-pointer", "collectable-swig-pointer-tag")) {
+    scm_set_smob_print(swig_collectable_tag, print_collectable_swig);
+    scm_set_smob_equalp(swig_collectable_tag, equalp_swig);
+    scm_set_smob_free(swig_collectable_tag, free_swig);
+  }
+  if (ensure_smob_tag(swig_module, &swig_destroyed_tag,
+		      "destroyed-swig-pointer", "destroyed-swig-pointer-tag")) {
+    scm_set_smob_print(swig_destroyed_tag, print_destroyed_swig);
+    scm_set_smob_equalp(swig_destroyed_tag, equalp_swig);
+  }
+  if (ensure_smob_tag(swig_module, &swig_member_function_tag,
+		      "swig-member-function-pointer", "swig-member-function-pointer-tag")) {
+    scm_set_smob_print(swig_member_function_tag, print_member_function_swig);
+    scm_set_smob_free(swig_member_function_tag, free_swig_member_function);
+  }
+  swig_make_func = scm_permanent_object(
+  scm_variable_ref(scm_c_module_lookup(scm_c_resolve_module("oop goops"), "make")));
+  swig_keyword = scm_permanent_object(scm_c_make_keyword((char*) "init-smob"));
+  swig_symbol = scm_permanent_object(scm_str2symbol("swig-smob"));
+#ifdef SWIG_INIT_RUNTIME_MODULE
+  SWIG_INIT_RUNTIME_MODULE
+#endif
+
+  return swig_module;
+}
+
+SWIGINTERN swig_module_info *
+SWIG_Guile_GetModule(void)
+{
+  SCM module;
+  SCM variable;
+
+  module = SWIG_Guile_Init();
+
+  variable = scm_sym2var(scm_str2symbol("swig-type-list-address" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME),
+			       scm_module_lookup_closure(module),
+			       SCM_BOOL_T);
+  if (SCM_UNBNDP(SCM_VARIABLE_REF(variable))) {
+    return NULL;
+  } else {
+    return (swig_module_info *) scm_num2ulong(SCM_VARIABLE_REF(variable), 0, "SWIG_Guile_Init");
+  }
+}
+
+SWIGINTERN void
+SWIG_Guile_SetModule(swig_module_info *swig_module)
+{
+  SCM module;
+  SCM variable;
+
+  module = SWIG_Guile_Init();
+    
+  variable = scm_sym2var(scm_str2symbol("swig-type-list-address" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME),
+			       scm_module_lookup_closure(module),
+			       SCM_BOOL_T);
+
+  SCM_VARIABLE_SET(variable, scm_ulong2num((unsigned long) swig_module));
+}
+
+SWIGINTERN int
+SWIG_Guile_GetArgs (SCM *dest, SCM rest,
+		    int reqargs, int optargs,
+		    const char *procname)
+{
+  int i;
+  int num_args_passed = 0;
+  for (i = 0; i<reqargs; i++) {
+    if (!SCM_CONSP(rest))
+      scm_wrong_num_args(scm_makfrom0str((char *) procname));
+    *dest++ = SCM_CAR(rest);
+    rest = SCM_CDR(rest);
+    num_args_passed++;
+  }
+  for (i = 0; i<optargs && SCM_CONSP(rest); i++) {
+    *dest++ = SCM_CAR(rest);
+    rest = SCM_CDR(rest);
+    num_args_passed++;
+  }
+  for (; i<optargs; i++)
+    *dest++ = SCM_UNDEFINED;
+  if (!SCM_NULLP(rest))
+    scm_wrong_num_args(scm_makfrom0str((char *) procname));
+  return num_args_passed;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/guile/guilemain.i b/trunk/Lib/guile/guilemain.i
new file mode 100644
index 0000000..6f4e4d9
--- /dev/null
+++ b/trunk/Lib/guile/guilemain.i
@@ -0,0 +1,47 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guilemain.i
+ *
+ * The main functions for a user augmented guile
+ * version that can handle wrapped calls as generated by SWIG
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <libguile.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Debugger interface (don't change the order of the following lines) */
+#define GDB_TYPE SCM
+#include <libguile/gdb_interface.h>
+GDB_INTERFACE;
+
+static void
+inner_main(void *closure, int argc, char **argv)
+{
+#ifdef SWIGINIT
+  SWIGINIT
+#else
+  SWIG_init();			/* SWIG init function */
+#endif
+  scm_shell(argc, argv);	/* scheme interpreter */
+  /* never reached: scm_shell will perform an exit */
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+  /* put any default initialisation code here: e.g. exit handlers */
+  scm_boot_guile(argc, argv, inner_main, 0); /* make a stack entry for the
+						garbage collector */
+  return 0; /* never reached, but avoids a warning */
+}
+%}
diff --git a/trunk/Lib/guile/interpreter.i b/trunk/Lib/guile/interpreter.i
new file mode 100644
index 0000000..7e8f077
--- /dev/null
+++ b/trunk/Lib/guile/interpreter.i
@@ -0,0 +1,62 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * interpreter.i
+ *
+ * SWIG file for a simple Guile interpreter
+ * ----------------------------------------------------------------------------- */
+
+%{
+
+#include <stdio.h>
+GSCM_status guile_init();
+
+int main(int argc, char **argv) {
+  GSCM_status status;
+  GSCM_top_level toplev;
+  char *eval_answer;
+  char input_str[16384];
+  int done;
+
+  /* start a scheme interpreter */
+  status = gscm_run_scm(argc, argv, 0, stdout, stderr, guile_init, 0, "#t");
+  if (status != GSCM_OK) {
+    fputs(gscm_error_msg(status), stderr);
+    fputc('\n', stderr);
+    printf("Error in startup.\n");
+    exit(1);
+  }
+
+  /* create the top level environment */
+  status = gscm_create_top_level(&toplev);
+  if (status != GSCM_OK) {
+    fputs(gscm_error_msg(status), stderr);
+    fputc('\n', stderr);
+    exit(1);
+  }
+
+  /* now sit in a scheme eval loop: I input the expressions, have guile
+   * evaluate them, and then get another expression.
+   */
+  done = 0;
+  fprintf(stdout,"Guile > ");
+  while (!done) {
+    if (fgets(input_str,16384,stdin) == NULL) {
+      exit(1);
+    } else {
+      if (strncmp(input_str,"quit",4) == 0) exit(1);
+      status = gscm_eval_str(&eval_answer, toplev, input_str);
+      fprintf(stdout,"%s\n", eval_answer);
+      fprintf(stdout,"Guile > ");
+    }
+  }
+
+  /* now clean up and quit */
+  gscm_destroy_top_level(toplev);
+}
+
+%}
+
+
+
diff --git a/trunk/Lib/guile/list-vector.i b/trunk/Lib/guile/list-vector.i
new file mode 100644
index 0000000..d98cae5
--- /dev/null
+++ b/trunk/Lib/guile/list-vector.i
@@ -0,0 +1,491 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * list_vector.i
+ *
+ * Guile typemaps for converting between arrays and Scheme lists or vectors  
+ * ----------------------------------------------------------------------------- */
+
+/* Here is a macro that will define typemaps for converting between C
+   arrays and Scheme lists or vectors when passing arguments to the C
+   function.
+
+   TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(C_TYPE, SCM_TO_C, C_TO_SCM, SCM_TYPE)
+   
+   Supported calling conventions:
+
+   func(int VECTORLENINPUT, [const] C_TYPE *VECTORINPUT)
+
+       Scheme wrapper will take one argument, a vector.  A temporary C
+       array of elements of type C_TYPE will be allocated and filled
+       with the elements of the vectors, converted to C with the
+       SCM_TO_C function.  Length and address of the array are passed
+       to the C function.
+
+       SCM_TYPE is used to describe the Scheme type of the elements in
+       the Guile procedure documentation.
+   
+   func(int LISTLENINPUT, [const] C_TYPE *LISTINPUT)
+
+       Likewise, but the Scheme wrapper will take one argument, a list.
+
+   func(int *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT)
+
+       Scheme wrapper will take no arguments.  Addresses of an integer
+       and a C_TYPE * variable will be passed to the C function.  The
+       C function is expected to return address and length of a
+       freshly allocated array of elements of type C_TYPE through
+       these pointers.  The elements of this array are converted to
+       Scheme with the C_TO_SCM function and returned as a Scheme
+       vector. 
+
+       If the function has a void return value, the vector constructed
+       by this typemap becomes the return value of the Scheme wrapper.
+       Otherwise, the function returns multiple values.  (See
+       the documentation on how to deal with multiple values.)
+
+   func(int *LISTLENOUTPUT, C_TYPE **LISTOUTPUT)
+
+       Likewise, but the Scheme wrapper will return a list instead of
+       a vector.
+
+   It is also allowed to use "size_t LISTLENINPUT" rather than "int
+   LISTLENINPUT".  */
+
+%define TYPEMAP_LIST_VECTOR_INPUT_WITH_EXPR(C_TYPE, SCM_TO_C_EXPR, SCM_TYPE)
+
+  /* input */
+     
+     /* We make use of the new multi-dispatch typemaps here. */
+     
+     %typemap(in, doc="$NAME is a vector of " #SCM_TYPE " values")
+       (int VECTORLENINPUT, C_TYPE *VECTORINPUT),
+       (size_t VECTORLENINPUT, C_TYPE *VECTORINPUT)
+     {
+       SCM_VALIDATE_VECTOR($argnum, $input);
+       $1 = gh_vector_length($input);
+       if ($1 > 0) {
+	 $1_ltype i;
+	 $2 = (C_TYPE *) SWIG_malloc(sizeof(C_TYPE) * $1);
+	 for (i = 0; i<$1; i++) {
+	   SCM swig_scm_value = gh_vector_ref($input, gh_int2scm(i));
+	   $2[i] = SCM_TO_C_EXPR;
+	 }
+       }
+       else $2 = NULL;
+     }
+	 
+     %typemap(in, doc="$NAME is a list of " #SCM_TYPE " values")
+       (int LISTLENINPUT, C_TYPE *LISTINPUT),
+       (size_t LISTLENINPUT, C_TYPE *LISTINPUT)
+     {
+       SCM_VALIDATE_LIST($argnum, $input);
+       $1 = gh_length($input);
+       if ($1 > 0) {
+	 $1_ltype i;
+	 SCM rest;
+	 $2 = (C_TYPE *) SWIG_malloc(sizeof(C_TYPE) * $1);
+	 for (i = 0, rest = $input;
+	      i<$1;
+	      i++, rest = gh_cdr(rest)) {
+	   SCM swig_scm_value = gh_car(rest);
+	   $2[i] = SCM_TO_C_EXPR;
+	 }
+       }
+       else $2 = NULL;
+     }
+
+     /* Do not check for NULL pointers (override checks). */
+
+     %typemap(check) (int VECTORLENINPUT, C_TYPE *VECTORINPUT),
+                     (size_t VECTORLENINPUT, C_TYPE *VECTORINPUT),
+                     (int LISTLENINPUT, C_TYPE *LISTINPUT),
+                     (size_t LISTLENINPUT, C_TYPE *LISTINPUT)
+       "/* no check for NULL pointer */";
+
+     /* Discard the temporary array after the call. */
+
+     %typemap(freearg) (int VECTORLENINPUT, C_TYPE *VECTORINPUT),
+                     (size_t VECTORLENINPUT, C_TYPE *VECTORINPUT),
+                     (int LISTLENINPUT, C_TYPE *LISTINPUT),
+                     (size_t LISTLENINPUT, C_TYPE *LISTINPUT)
+       {if ($2!=NULL) SWIG_free($2);}
+
+%enddef
+
+  /* output */
+
+%define TYPEMAP_LIST_VECTOR_OUTPUT_WITH_EXPR(C_TYPE, C_TO_SCM_EXPR, SCM_TYPE)
+
+     /* First we make temporary variables ARRAYLENTEMP and ARRAYTEMP,
+	whose addresses we pass to the C function.  We ignore both
+	arguments for Scheme. */
+
+     %typemap(in,numinputs=0) (int *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT)
+                        (int arraylentemp, C_TYPE *arraytemp),
+                      (int *LISTLENOUTPUT, C_TYPE **LISTOUTPUT)
+                        (int arraylentemp, C_TYPE *arraytemp),
+		      (size_t *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT)
+                        (size_t arraylentemp, C_TYPE *arraytemp),
+                      (size_t *LISTLENOUTPUT, C_TYPE **LISTOUTPUT)
+                        (size_t arraylentemp, C_TYPE *arraytemp)
+     %{
+       $1 = &arraylentemp;
+       $2 = &arraytemp;
+     %}
+
+     /* In the ARGOUT typemaps, we convert the array into a vector or
+        a list and append it to the results. */
+
+     %typemap(argout, doc="$NAME (a vector of " #SCM_TYPE " values)") 
+          (int *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT),
+	  (size_t *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT)
+     {
+       $*1_ltype i;
+       SCM res = gh_make_vector(gh_int2scm(*$1),
+				SCM_BOOL_F);
+       for (i = 0; i<*$1; i++) {
+	 C_TYPE swig_c_value = (*$2)[i];
+	 SCM elt = C_TO_SCM_EXPR;
+	 gh_vector_set_x(res, gh_int2scm(i), elt);
+       }
+       SWIG_APPEND_VALUE(res);
+     }
+
+     %typemap(argout, doc="$NAME (a list of " #SCM_TYPE " values)")
+          (int *LISTLENOUTPUT, C_TYPE **LISTOUTPUT),
+	  (size_t *LISTLENOUTPUT, C_TYPE **LISTOUTPUT)
+     {
+       int i;
+       SCM res = SCM_EOL;
+       for (i = ((int)(*$1)) - 1; i>=0; i--) {
+         C_TYPE swig_c_value = (*$2)[i];
+	 SCM elt = C_TO_SCM_EXPR;
+	 res = gh_cons(elt, res);
+       }
+       SWIG_APPEND_VALUE(res);
+     }
+
+     /* In the FREEARG typemaps, get rid of the C vector.  
+        (This can be overridden if you want to keep the C vector.) */
+
+     %typemap(freearg) 
+          (int *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT),
+	  (size_t *VECTORLENOUTPUT, C_TYPE **VECTOROUTPUT), 
+	  (int *LISTLENOUTPUT, C_TYPE **LISTOUTPUT),
+	  (size_t *LISTLENOUTPUT, C_TYPE **LISTOUTPUT)
+     {
+        if ((*$2)!=NULL) free(*$2);
+     }
+
+%enddef
+
+%define TYPEMAP_LIST_VECTOR_INPUT_OUTPUT_WITH_EXPR(C_TYPE, SCM_TO_C_EXPR, C_TO_SCM_EXPR, SCM_TYPE)
+  TYPEMAP_LIST_VECTOR_INPUT_WITH_EXPR(C_TYPE, SCM_TO_C_EXPR, SCM_TYPE)
+  TYPEMAP_LIST_VECTOR_OUTPUT_WITH_EXPR(C_TYPE, C_TO_SCM_EXPR, SCM_TYPE)
+%enddef
+
+%define TYPEMAP_LIST_VECTOR_INPUT(C_TYPE, SCM_TO_C, SCM_TYPE)
+  TYPEMAP_LIST_VECTOR_INPUT_WITH_EXPR
+     (C_TYPE, SCM_TO_C(swig_scm_value), SCM_TYPE)
+%enddef
+
+%define TYPEMAP_LIST_VECTOR_OUTPUT(C_TYPE, C_TO_SCM, SCM_TYPE)
+  TYPEMAP_LIST_VECTOR_OUTPUT_WITH_EXPR
+     (C_TYPE, C_TO_SCM(swig_c_value), SCM_TYPE)
+%enddef
+
+%define TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(C_TYPE, SCM_TO_C, C_TO_SCM, SCM_TYPE)
+  TYPEMAP_LIST_VECTOR_INPUT_OUTPUT_WITH_EXPR
+     (C_TYPE, SCM_TO_C(swig_scm_value), C_TO_SCM(swig_c_value), SCM_TYPE)
+%enddef
+
+/* We use the macro to define typemaps for some standard types. */
+
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(bool, gh_scm2bool, gh_bool2scm, boolean);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(char, gh_scm2char, gh_char2scm, char);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(unsigned char, gh_scm2char, gh_char2scm, char);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(int, gh_scm2int, gh_int2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(short, gh_scm2int, gh_int2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(long, gh_scm2long, gh_long2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(ptrdiff_t, gh_scm2long, gh_long2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(unsigned int, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(unsigned short, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(unsigned long, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(size_t, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(float, gh_scm2double, gh_double2scm, real);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(double, gh_scm2double, gh_double2scm, real);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(char *, SWIG_scm2str, gh_str02scm, string);
+TYPEMAP_LIST_VECTOR_INPUT_OUTPUT(const char *, SWIG_scm2str, gh_str02scm, string);
+
+/* For the char *, free all strings after converting */
+
+     %typemap(freearg) 
+          (int *VECTORLENOUTPUT, char ***VECTOROUTPUT),
+	  (size_t *VECTORLENOUTPUT, char ***VECTOROUTPUT), 
+	  (int *LISTLENOUTPUT, char ***LISTOUTPUT),
+    (size_t *LISTLENOUTPUT, char ***LISTOUTPUT),
+    (int *VECTORLENOUTPUT, const char ***VECTOROUTPUT),
+    (size_t *VECTORLENOUTPUT, const char ***VECTOROUTPUT), 
+    (int *LISTLENOUTPUT, const char ***LISTOUTPUT),
+    (size_t *LISTLENOUTPUT, const char ***LISTOUTPUT)
+    {
+	 if ((*$2)!=NULL) {
+	     int i;
+	     for (i = 0; i < *$1; i++) {
+		 if ((*$2)[i] != NULL) free((*$2)[i]);
+	     }
+	     free(*$2);
+	 }
+     }
+
+%typemap(freearg) (int VECTORLENINPUT, char **VECTORINPUT),
+    (size_t VECTORLENINPUT, char **VECTORINPUT), 
+    (int LISTLENINPUT, char **LISTINPUT),
+    (size_t LISTLENINPUT, char **LISTINPUT),
+    (int VECTORLENINPUT, const char **VECTORINPUT),
+    (size_t VECTORLENINPUT, const char **VECTORINPUT), 
+    (int LISTLENINPUT, const char **LISTINPUT),
+    (size_t LISTLENINPUT, const char **LISTINPUT)
+{
+    if (($2)!=NULL) {
+	int i;
+	for (i = 0; i< $1; i++)
+	    if (($2)[i] != NULL) free(($2)[i]);
+	free($2);
+    }
+}
+
+
+/* Following is a macro that emits typemaps that are much more
+   flexible.  (They are also messier.)  It supports multiple parallel
+   lists and vectors (sharing one length argument each).
+
+   TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(C_TYPE, SCM_TO_C, C_TO_SCM, SCM_TYPE)
+   
+   Supported calling conventions:
+
+   func(int PARALLEL_VECTORLENINPUT, [const] C_TYPE *PARALLEL_VECTORINPUT, ...)  or
+   func([const] C_TYPE *PARALLEL_VECTORINPUT, ..., int PARALLEL_VECTORLENINPUT)
+
+   func(int PARALLEL_LISTLENINPUT, [const] C_TYPE *PARALLEL_LISTINPUT, ...) or
+   func([const] C_TYPE *PARALLEL_LISTINPUT, ..., int PARALLEL_LISTLENINPUT)
+
+   func(int *PARALLEL_VECTORLENOUTPUT, C_TYPE **PARALLEL_VECTOROUTPUT, ...) or
+   func(C_TYPE **PARALLEL_VECTOROUTPUT, int *PARALLEL_VECTORLENOUTPUT, ...)
+
+   func(int *PARALLEL_LISTLENOUTPUT, C_TYPE **PARALLEL_LISTOUTPUT) or
+   func(C_TYPE **PARALLEL_LISTOUTPUT, int *PARALLEL_LISTLENOUTPUT)
+
+   It is also allowed to use "size_t PARALLEL_LISTLENINPUT" rather than "int
+   PARALLEL_LISTLENINPUT".  */
+
+%define TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_WITH_EXPR(C_TYPE, SCM_TO_C_EXPR, SCM_TYPE)
+
+  /* input */
+     
+     /* Passing data is a little complicated here; just remember:
+	IGNORE typemaps come first, then IN, then CHECK.  But if
+	IGNORE is given, IN won't be used for this type.
+
+	We need to "ignore" one of the parameters because there shall
+	be only one argument on the Scheme side.  Here we only
+	initialize the array length to 0 but save its address for a
+	later change.  */
+     
+     %typemap(in,numinputs=0) int PARALLEL_VECTORLENINPUT (int *_global_vector_length),
+		      size_t PARALLEL_VECTORLENINPUT (size_t *_global_vector_length)
+     {		      
+       $1 = 0;
+       _global_vector_length = &$1;
+     }
+
+     %typemap(in,numinputs=0) int PARALLEL_LISTLENINPUT (int *_global_list_length),   
+		      size_t PARALLEL_LISTLENINPUT (size_t *_global_list_length)
+     {		      
+       $1 = 0;
+       _global_list_length = &$1;
+     }
+
+     /* All the work is done in IN. */
+
+     %typemap(in, doc="$NAME is a vector of " #SCM_TYPE " values") 
+		  C_TYPE *PARALLEL_VECTORINPUT,
+		  const C_TYPE *PARALLEL_VECTORINPUT
+     {
+       SCM_VALIDATE_VECTOR($argnum, $input);
+       *_global_vector_length = gh_vector_length($input);
+       if (*_global_vector_length > 0) {
+	 int i;
+	 $1 = (C_TYPE *) SWIG_malloc(sizeof(C_TYPE)
+			       * (*_global_vector_length));
+	 for (i = 0; i<*_global_vector_length; i++) {
+	   SCM swig_scm_value = gh_vector_ref($input, gh_int2scm(i));
+	   $1[i] = SCM_TO_C_EXPR;
+	 }
+       }
+       else $1 = NULL;
+     }
+	 
+     %typemap(in, doc="$NAME is a list of " #SCM_TYPE " values") 
+		  C_TYPE *PARALLEL_LISTINPUT,
+		  const C_TYPE *PARALLEL_LISTINPUT
+     {
+       SCM_VALIDATE_LIST($argnum, $input);
+       *_global_list_length = gh_length($input);
+       if (*_global_list_length > 0) {
+	 int i;
+	 SCM rest;
+	 $1 = (C_TYPE *) SWIG_malloc(sizeof(C_TYPE)
+			       * (*_global_list_length));
+	 for (i = 0, rest = $input;
+	      i<*_global_list_length;
+	      i++, rest = gh_cdr(rest)) {
+	   SCM swig_scm_value = gh_car(rest);
+	   $1[i] = SCM_TO_C_EXPR;
+	 }
+       }
+       else $1 = NULL;
+     }
+
+     /* Don't check for NULL pointers (override checks). */
+
+     %typemap(check) C_TYPE *PARALLEL_VECTORINPUT, 
+		     const C_TYPE *PARALLEL_VECTORINPUT,
+		     C_TYPE *PARALLEL_LISTINPUT, 
+		     const C_TYPE *PARALLEL_LISTINPUT
+       "/* no check for NULL pointer */";
+
+     /* Discard the temporary array after the call. */
+
+     %typemap(freearg) C_TYPE *PARALLEL_VECTORINPUT, 
+		       const C_TYPE *PARALLEL_VECTORINPUT,
+		       C_TYPE *PARALLEL_LISTINPUT, 
+		       const C_TYPE *PARALLEL_LISTINPUT
+       {if ($1!=NULL) SWIG_free($1);}
+
+%enddef
+
+%define TYPEMAP_PARALLEL_LIST_VECTOR_OUTPUT_WITH_EXPR(C_TYPE, C_TO_SCM_EXPR, SCM_TYPE)
+
+  /* output */
+
+     /* First we make a temporary variable ARRAYLENTEMP, use its
+        address as the ...LENOUTPUT argument for the C function and
+        "ignore" the ...LENOUTPUT argument for Scheme.  */
+
+     %typemap(in,numinputs=0) int *PARALLEL_VECTORLENOUTPUT (int _global_arraylentemp),
+		      size_t *PARALLEL_VECTORLENOUTPUT (size_t _global_arraylentemp),
+		      int *PARALLEL_LISTLENOUTPUT   (int _global_arraylentemp),
+		      size_t *PARALLEL_LISTLENOUTPUT   (size_t _global_arraylentemp)
+       "$1 = &_global_arraylentemp;";
+
+     /* We also need to ignore the ...OUTPUT argument. */
+
+     %typemap(in,numinputs=0) C_TYPE **PARALLEL_VECTOROUTPUT (C_TYPE *arraytemp),
+		      C_TYPE **PARALLEL_LISTOUTPUT   (C_TYPE *arraytemp)
+       "$1 = &arraytemp;";
+
+     /* In the ARGOUT typemaps, we convert the array into a vector or
+        a list and append it to the results. */
+
+     %typemap(argout, doc="$NAME (a vector of " #SCM_TYPE " values)") 
+		      C_TYPE **PARALLEL_VECTOROUTPUT
+     {
+       int i;
+       SCM res = gh_make_vector(gh_int2scm(_global_arraylentemp),
+				SCM_BOOL_F);
+       for (i = 0; i<_global_arraylentemp; i++) {
+         C_TYPE swig_c_value = (*$1)[i];
+	 SCM elt = C_TO_SCM_EXPR;
+	 gh_vector_set_x(res, gh_int2scm(i), elt);
+       }
+       SWIG_APPEND_VALUE(res);
+     }
+
+     %typemap(argout, doc="$NAME (a list of " #SCM_TYPE " values)") 
+		      C_TYPE **PARALLEL_LISTOUTPUT
+     {
+       int i;
+       SCM res = SCM_EOL;
+       if (_global_arraylentemp > 0) {
+         for (i = _global_arraylentemp - 1; i>=0; i--) {
+	   C_TYPE swig_c_value = (*$1)[i];	 
+	   SCM elt = C_TO_SCM_EXPR;
+	   res = gh_cons(elt, res);
+         }
+       }
+       SWIG_APPEND_VALUE(res);
+     }
+
+     /* In the FREEARG typemaps, get rid of the C vector.  
+        (This can be overridden if you want to keep the C vector.) */
+
+     %typemap(freearg) C_TYPE **PARALLEL_VECTOROUTPUT, 
+		       C_TYPE **PARALLEL_LISTOUTPUT
+     {
+        if ((*$1)!=NULL) free(*$1);
+     }
+
+%enddef
+
+%define TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT_WITH_EXPR(C_TYPE, SCM_TO_C_EXPR, C_TO_SCM_EXPR, SCM_TYPE)
+  TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_WITH_EXPR(C_TYPE, SCM_TO_C_EXPR, SCM_TYPE)
+  TYPEMAP_PARALLEL_LIST_VECTOR_OUTPUT_WITH_EXPR(C_TYPE, C_TO_SCM_EXPR, SCM_TYPE)
+%enddef
+
+%define TYPEMAP_PARALLEL_LIST_VECTOR_INPUT(C_TYPE, SCM_TO_C, SCM_TYPE)
+  TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_WITH_EXPR
+     (C_TYPE, SCM_TO_C(swig_scm_value), SCM_TYPE)
+%enddef
+
+%define TYPEMAP_PARALLEL_LIST_VECTOR_OUTPUT(C_TYPE, C_TO_SCM, SCM_TYPE)
+  TYPEMAP_PARALLEL_LIST_VECTOR_OUTPUT_WITH_EXPR
+     (C_TYPE, C_TO_SCM(swig_c_value), SCM_TYPE)
+%enddef
+
+%define TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(C_TYPE, SCM_TO_C, C_TO_SCM, SCM_TYPE)
+  TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT_WITH_EXPR
+    (C_TYPE, SCM_TO_C(swig_scm_value), C_TO_SCM(swig_c_value), SCM_TYPE)
+%enddef
+
+/* We use the macro to define typemaps for some standard types. */
+
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(bool, gh_scm2bool, gh_bool2scm, boolean);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(char, gh_scm2char, gh_char2scm, char);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(unsigned char, gh_scm2char, gh_char2scm, char);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(int, gh_scm2int, gh_int2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(short, gh_scm2int, gh_int2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(long, gh_scm2long, gh_long2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(ptrdiff_t, gh_scm2long, gh_long2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(unsigned int, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(unsigned short, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(unsigned long, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(size_t, gh_scm2ulong, gh_ulong2scm, integer);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(float, gh_scm2double, gh_double2scm, real);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(double, gh_scm2double, gh_double2scm, real);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(char *, SWIG_scm2str, gh_str02scm, string);
+TYPEMAP_PARALLEL_LIST_VECTOR_INPUT_OUTPUT(const char *, SWIG_scm2str, gh_str02scm, string);
+
+%typemap(freearg) char **PARALLEL_LISTINPUT, char **PARALLEL_VECTORINPUT,
+    const char **PARALLEL_LISTINPUT, const char **PARALLEL_VECTORINPUT
+{
+    if (($1)!=NULL) {
+	int i;
+	for (i = 0; i<*_global_list_length; i++)
+	    if (($1)[i] != NULL) SWIG_free(($1)[i]);
+	SWIG_free($1);
+    }
+}
+
+%typemap(freearg) char ***PARALLEL_LISTOUTPUT, char ***PARALLEL_VECTOROUTPUT,
+    const char ***PARALLEL_LISTOUTPUT, const char ***PARALLEL_VECTOROUTPUT
+{
+    if ((*$1)!=NULL) {
+	int i;
+	for (i = 0; i<_global_arraylentemp; i++)
+	    if ((*$1)[i] != NULL) free((*$1)[i]);
+	free(*$1);
+    }
+}
diff --git a/trunk/Lib/guile/pointer-in-out.i b/trunk/Lib/guile/pointer-in-out.i
new file mode 100644
index 0000000..bc64387
--- /dev/null
+++ b/trunk/Lib/guile/pointer-in-out.i
@@ -0,0 +1,105 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pointer-in-out.i
+ *
+ * Guile typemaps for passing pointers indirectly 
+ * ----------------------------------------------------------------------------- */
+
+/* Here is a macro that will define typemaps for passing C pointers indirectly.
+  
+   TYPEMAP_POINTER_INPUT_OUTPUT(PTRTYPE, SCM_TYPE)
+
+   Supported calling conventions (in this example, PTRTYPE is int *):
+
+   func(int **INPUT)
+
+       Scheme wrapper will take one argument, a wrapped C pointer.
+       The address of a variable containing this pointer will be
+       passed to the function.
+
+   func(int **INPUT_CONSUMED)
+
+       Likewise, but mark the pointer object as not garbage
+       collectable.
+
+   func(int **INPUT_DESTROYED)
+
+       Likewise, but mark the pointer object as destroyed.
+       
+   func(int **OUTPUT)
+
+       Scheme wrapper will take no arguments.  The address of an int *
+       variable will be passed to the function.  The function is
+       expected to modify the variable; its value is wrapped and
+       becomes an extra return value.  (See the documentation on how
+       to deal with multiple values.)
+   
+   func(int **OUTPUT_NONCOLLECTABLE)
+
+       Likewise, but make the pointer object not garbage collectable.
+   
+   func(int **BOTH)
+   func(int **INOUT)
+
+       This annotation combines INPUT and OUTPUT.
+
+*/
+
+%define TYPEMAP_POINTER_INPUT_OUTPUT(PTRTYPE, SCM_TYPE)
+
+%typemap(in, doc="$NAME is of type <" #SCM_TYPE ">") PTRTYPE *INPUT(PTRTYPE temp)
+{
+    if (SWIG_ConvertPtr($input, (void **) &temp, $*descriptor, 0)) {
+	scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+    }
+    $1 = &temp;
+}
+
+%typemap(in, doc="$NAME is of type <" #SCM_TYPE "> and is consumed by the function") PTRTYPE *INPUT_CONSUMED(PTRTYPE temp)
+{
+    if (SWIG_ConvertPtr($input, (void **) &temp, $*descriptor, 0)) {
+	scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+    }
+    SWIG_Guile_MarkPointerNoncollectable($input);
+    $1 = &temp;
+}
+
+%typemap(in, doc="$NAME is of type <" #SCM_TYPE "> and is consumed by the function") PTRTYPE *INPUT_DESTROYED(PTRTYPE temp)
+{
+    if (SWIG_ConvertPtr($input, (void **) &temp, $*descriptor, 0)) {
+	scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+    }
+    SWIG_Guile_MarkPointerDestroyed($input);
+    $1 = &temp;
+}
+
+%typemap(in, numinputs=0) PTRTYPE *OUTPUT(PTRTYPE temp),
+                          PTRTYPE *OUTPUT_NONCOLLECTABLE(PTRTYPE temp)
+     "$1 = &temp;";
+
+%typemap(argout, doc="<" #SCM_TYPE ">") PTRTYPE *OUTPUT
+     "SWIG_APPEND_VALUE(SWIG_NewPointerObj(*$1, $*descriptor, 1));"; 
+
+%typemap(argout, doc="<" #SCM_TYPE ">") PTRTYPE *OUTPUT_NONCOLLECTABLE
+     "SWIG_APPEND_VALUE(SWIG_NewPointerObj(*$1, $*descriptor, 0));"; 
+
+%typemap(in) PTRTYPE *BOTH = PTRTYPE *INPUT;
+%typemap(argout) PTRTYPE *BOTH = PTRTYPE *OUTPUT;
+%typemap(in) PTRTYPE *INOUT = PTRTYPE *INPUT;
+%typemap(argout) PTRTYPE *INOUT = PTRTYPE *OUTPUT;
+
+/* As a special convenience measure, also attach docs involving
+   SCM_TYPE to the standard pointer typemaps */
+
+%typemap(in, doc="$NAME is of type <" #SCM_TYPE ">") PTRTYPE {
+  if (SWIG_ConvertPtr($input, (void **) &$1, $descriptor, 0))
+    scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+}
+
+%typemap(out, doc="<" #SCM_TYPE ">") PTRTYPE {
+    $result = SWIG_NewPointerObj ($1, $descriptor, $owner);
+}
+
+%enddef
diff --git a/trunk/Lib/guile/ports.i b/trunk/Lib/guile/ports.i
new file mode 100644
index 0000000..0d0e142
--- /dev/null
+++ b/trunk/Lib/guile/ports.i
@@ -0,0 +1,56 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ports.i
+ *
+ * Guile typemaps for handling ports
+ * ----------------------------------------------------------------------------- */
+
+%{
+  #ifndef _POSIX_SOURCE
+  /* This is needed on Solaris for fdopen(). */
+  #  define _POSIX_SOURCE 199506L
+  #endif
+  #include <stdio.h>
+  #include <errno.h>
+  #include <unistd.h>
+%}
+
+/* This typemap for FILE * accepts
+   (1) FILE * pointer objects,
+   (2) Scheme file ports.  In this case, it creates a temporary C stream
+       which reads or writes from a dup'ed file descriptor.
+ */
+
+%typemap(in, doc="$NAME is a file port or a FILE * pointer") FILE *
+  ( int closep )
+{
+  if (SWIG_ConvertPtr($input, (void**) &($1), $1_descriptor, 0) == 0) {
+    closep = 0;
+  }
+  else if(!(SCM_FPORTP($input)))
+    scm_wrong_type_arg("$name", $argnum, $input);
+  else {
+    int fd;
+    if (SCM_OUTPUT_PORT_P($input))
+      scm_force_output($input);
+    fd=dup(SCM_FPORT_FDES($input));
+    if(fd==-1) 
+      scm_misc_error("$name", strerror(errno), SCM_EOL);
+    $1=fdopen(fd,
+		   SCM_OUTPUT_PORT_P($input)
+		   ? (SCM_INPUT_PORT_P($input)
+		      ? "r+" : "w")
+		   : "r");
+    if($1==NULL)
+      scm_misc_error("$name", strerror(errno), SCM_EOL);
+    closep = 1;
+  }
+}
+
+%typemap(freearg) FILE*  {
+  if (closep$argnum)
+    fclose($1);
+}
+
diff --git a/trunk/Lib/guile/std_common.i b/trunk/Lib/guile/std_common.i
new file mode 100644
index 0000000..ace5d65
--- /dev/null
+++ b/trunk/Lib/guile/std_common.i
@@ -0,0 +1,27 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_common.i
+ *
+ * SWIG typemaps for STL - common utilities
+ * ----------------------------------------------------------------------------- */
+
+%include <std/std_except.i>
+
+%apply size_t { std::size_t };
+
+#define SWIG_bool2scm(b) gh_bool2scm(b ? 1 : 0)
+#define SWIG_string2scm(s) gh_str02scm(s.c_str())
+
+%{
+#include <string>
+
+inline std::string SWIG_scm2string(SCM x) {
+    char* temp;
+    temp = SWIG_scm2str(x);
+    std::string s(temp);
+    if (temp) SWIG_free(temp);
+    return s;
+}
+%}
diff --git a/trunk/Lib/guile/std_deque.i b/trunk/Lib/guile/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/guile/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/guile/std_except.i b/trunk/Lib/guile/std_except.i
new file mode 100644
index 0000000..61bf481
--- /dev/null
+++ b/trunk/Lib/guile/std_except.i
@@ -0,0 +1,12 @@
+// TODO: STL exception handling
+// Note that the generic std_except.i file did not work
+%{
+#include <stdexcept>
+%}
+
+namespace std {
+  %ignore exception;
+  struct exception {
+  };
+}
+
diff --git a/trunk/Lib/guile/std_map.i b/trunk/Lib/guile/std_map.i
new file mode 100644
index 0000000..cc53e15
--- /dev/null
+++ b/trunk/Lib/guile/std_map.i
@@ -0,0 +1,1351 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+//
+// The aim of all that follows would be to integrate std::map with
+// Guile as much as possible, namely, to allow the user to pass and
+// be returned Scheme association lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+//
+//   -- f(std::map<T>), f(const std::map<T>&), f(const std::map<T>*):
+//      the parameter being read-only, either a Scheme alist or a
+//      previously wrapped std::map<T> can be passed.
+//   -- f(std::map<T>&), f(std::map<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::map
+//      can be passed.
+//   -- std::map<T> f():
+//      the map is returned by copy; therefore, a Scheme alist
+//      is returned which is most easily used in other Scheme functions
+//   -- std::map<T>& f(), std::map<T>* f(), const std::map<T>& f(),
+//      const std::map<T>* f():
+//      the map is returned by reference; therefore, a wrapped std::map
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                $1 = std::map<K,T >();
+            } else if (gh_pair_p($input)) {
+                $1 = std::map<K,T >();
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    K* k;
+                    T* x;
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) != 0) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    (($1_type &)$1)[*k] = *x;
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (gh_pair_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    K* k;
+                    T* x;
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) != 0) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    temp[*k] = *x;
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            SCM alist = SCM_EOL;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                K* key = new K(i->first);
+                T* val = new T(i->second);
+                SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                SCM x = SWIG_NewPointerObj(val,$descriptor(T *), 1);
+                SCM entry = gh_cons(k,x);
+                alist = gh_cons(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            /* native sequence? */
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                /* check the first element only */
+                K* k;
+                T* x;
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (SWIG_ConvertPtr(key,(void**) &k,
+                                    $descriptor(K *), 0) != 0) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) == 0) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) == 0)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped map? */
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            /* native sequence? */
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                /* check the first element only */
+                K* k;
+                T* x;
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (SWIG_ConvertPtr(key,(void**) &k,
+                                    $descriptor(K *), 0) != 0) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) == 0) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) == 0)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped map? */
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& __getitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            SCM keys() {
+                SCM result = SCM_EOL;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    K* key = new K(i->first);
+                    SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                    result = gh_cons(k,result);
+                }
+                return result;
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                $1 = std::map<K,T >();
+            } else if (gh_pair_p($input)) {
+                $1 = std::map<K,T >();
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    T* x;
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    if (!CHECK(key))
+                        SWIG_exception(SWIG_TypeError,
+                                       "map<" #K "," #T "> expected");
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) != 0) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    (($1_type &)$1)[CONVERT_FROM(key)] = *x;
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (gh_pair_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    T* x;
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    if (!CHECK(key))
+                        SWIG_exception(SWIG_TypeError,
+                                       "map<" #K "," #T "> expected");
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) != 0) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    temp[CONVERT_FROM(key)] = *x;
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            SCM alist = SCM_EOL;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                T* val = new T(i->second);
+                SCM k = CONVERT_TO(i->first);
+                SCM x = SWIG_NewPointerObj(val,$descriptor(T *), 1);
+                SCM entry = gh_cons(k,x);
+                alist = gh_cons(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            // native sequence?
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                // check the first element only
+                T* x;
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (!CHECK(key)) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) == 0) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) == 0)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            // native sequence?
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                // check the first element only
+                T* x;
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (!CHECK(key)) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) == 0) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) == 0)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& __getitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            SCM keys() {
+                SCM result = SCM_EOL;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    SCM k = CONVERT_TO(i->first);
+                    result = gh_cons(k,result);
+                }
+                return result;
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                $1 = std::map<K,T >();
+            } else if (gh_pair_p($input)) {
+                $1 = std::map<K,T >();
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    K* k;
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (!CHECK(val)) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        if (!CHECK(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    (($1_type &)$1)[*k] = CONVERT_FROM(val);
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (gh_pair_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    K* k;
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (!CHECK(val)) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        if (!CHECK(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    temp[*k] = CONVERT_FROM(val);
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            SCM alist = SCM_EOL;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                K* key = new K(i->first);
+                SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                SCM x = CONVERT_TO(i->second);
+                SCM entry = gh_cons(k,x);
+                alist = gh_cons(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            // native sequence?
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                // check the first element only
+                K* k;
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (SWIG_ConvertPtr(val,(void **) &k,
+                                    $descriptor(K *), 0) != 0) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK(val)) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (CHECK(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            // native sequence?
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                // check the first element only
+                K* k;
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (SWIG_ConvertPtr(val,(void **) &k,
+                                    $descriptor(K *), 0) != 0) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK(val)) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (CHECK(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T __getitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            SCM keys() {
+                SCM result = SCM_EOL;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    K* key = new K(i->first);
+                    SCM k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                    result = gh_cons(k,result);
+                }
+                return result;
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                $1 = std::map<K,T >();
+            } else if (gh_pair_p($input)) {
+                $1 = std::map<K,T >();
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    if (!CHECK_K(key))
+                        SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    if (!CHECK_T(val)) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        if (!CHECK_T(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    (($1_type &)$1)[CONVERT_K_FROM(key)] = 
+                                               CONVERT_T_FROM(val);
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (gh_null_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (gh_pair_p($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                SCM alist = $input;
+                while (!gh_null_p(alist)) {
+                    SCM entry, key, val;
+                    entry = gh_car(alist);
+                    if (!gh_pair_p(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = gh_car(entry);
+                    val = gh_cdr(entry);
+                    if (!CHECK_K(key))
+                        SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    if (!CHECK_T(val)) {
+                        if (!gh_pair_p(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = gh_car(val);
+                        if (!CHECK_T(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    temp[CONVERT_K_FROM(key)] = CONVERT_T_FROM(val);
+                    alist = gh_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            SCM alist = SCM_EOL;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                SCM k = CONVERT_K_TO(i->first);
+                SCM x = CONVERT_T_TO(i->second);
+                SCM entry = gh_cons(k,x);
+                alist = gh_cons(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            // native sequence?
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                // check the first element only
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (!CHECK_K(key)) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK_T(val)) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (CHECK_T(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            // native sequence?
+            if (gh_null_p($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                // check the first element only
+                SCM head = gh_car($input);
+                if (gh_pair_p(head)) {
+                    SCM key = gh_car(head);
+                    SCM val = gh_cdr(head);
+                    if (!CHECK_K(key)) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK_T(val)) {
+                            $1 = 1;
+                        } else if (gh_pair_p(val)) {
+                            val = gh_car(val);
+                            if (CHECK_T(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T __getitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(K key, T x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            SCM keys() {
+                SCM result = SCM_EOL;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    SCM k = CONVERT_K_TO(i->first);
+                    result = gh_cons(k,result);
+                }
+                return result;
+            }
+        }
+    };
+    %enddef
+
+
+    specialize_std_map_on_key(bool,gh_boolean_p,
+                              gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_key(int,gh_number_p,
+                              gh_scm2long,gh_long2scm);
+    specialize_std_map_on_key(short,gh_number_p,
+                              gh_scm2long,gh_long2scm);
+    specialize_std_map_on_key(long,gh_number_p,
+                              gh_scm2long,gh_long2scm);
+    specialize_std_map_on_key(unsigned int,gh_number_p,
+                              gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_key(unsigned short,gh_number_p,
+                              gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_key(unsigned long,gh_number_p,
+                              gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_key(double,gh_number_p,
+                              gh_scm2double,gh_double2scm);
+    specialize_std_map_on_key(float,gh_number_p,
+                              gh_scm2double,gh_double2scm);
+    specialize_std_map_on_key(std::string,gh_string_p,
+                              SWIG_scm2string,SWIG_string2scm);
+
+    specialize_std_map_on_value(bool,gh_boolean_p,
+                                gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_value(int,gh_number_p,
+                                gh_scm2long,gh_long2scm);
+    specialize_std_map_on_value(short,gh_number_p,
+                                gh_scm2long,gh_long2scm);
+    specialize_std_map_on_value(long,gh_number_p,
+                                gh_scm2long,gh_long2scm);
+    specialize_std_map_on_value(unsigned int,gh_number_p,
+                                gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_value(unsigned short,gh_number_p,
+                                gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_value(unsigned long,gh_number_p,
+                                gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_value(double,gh_number_p,
+                                gh_scm2double,gh_double2scm);
+    specialize_std_map_on_value(float,gh_number_p,
+                                gh_scm2double,gh_double2scm);
+    specialize_std_map_on_value(std::string,gh_string_p,
+                                SWIG_scm2string,SWIG_string2scm);
+
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_map_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+}
diff --git a/trunk/Lib/guile/std_pair.i b/trunk/Lib/guile/std_pair.i
new file mode 100644
index 0000000..f8c2ea6
--- /dev/null
+++ b/trunk/Lib/guile/std_pair.i
@@ -0,0 +1,871 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+//
+// See std_vector.i for the rationale of typemap application
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class T, class U> struct pair {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                T* x;
+                U* y;
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                $1 = std::make_pair(*x,*y);
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                      std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                      std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                T* x;
+                U* y;
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                temp = std::make_pair(*x,*y);
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            T* x = new T($1.first);
+            U* y = new U($1.second);
+            SCM first = SWIG_NewPointerObj(x,$descriptor(T *), 1);
+            SCM second = SWIG_NewPointerObj(y,$descriptor(U *), 1);
+            $result = gh_cons(first,second);
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                T* x;
+                U* y;
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) == 0 &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) == 0) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                T* x;
+                U* y;
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) == 0 &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) == 0) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_pair_on_first(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class U> struct pair<T,U> {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                U* y;
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                if (!CHECK(first))
+                    SWIG_exception(SWIG_TypeError,
+                                   "map<" #T "," #U "> expected");
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                $1 = std::make_pair(CONVERT_FROM(first),*y);
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                       std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                       std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                U* y;
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                if (!CHECK(first))
+                    SWIG_exception(SWIG_TypeError,
+                                   "map<" #T "," #U "> expected");
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                temp = std::make_pair(CONVERT_FROM(first),*y);
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            U* y = new U($1.second);
+            SCM second = SWIG_NewPointerObj(y,$descriptor(U *), 1);
+            $result = gh_cons(CONVERT_TO($1.first),second);
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                U* y;
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (CHECK(first) &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) == 0) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                U* y;
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (CHECK(first) &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) == 0) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+    %enddef
+
+    %define specialize_std_pair_on_second(U,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class T> struct pair<T,U> {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                T* x;
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                if (!CHECK(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "map<" #T "," #U "> expected");
+                $1 = std::make_pair(*x,CONVERT_FROM(second));
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                      std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                      std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                T* x;
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                if (!CHECK(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "map<" #T "," #U "> expected");
+                temp = std::make_pair(*x,CONVERT_FROM(second));
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            T* x = new T($1.first);
+            SCM first = SWIG_NewPointerObj(x,$descriptor(T *), 1);
+            $result = gh_cons(first,CONVERT_TO($1.second));
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                T* x;
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) == 0 &&
+                    CHECK(second)) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                T* x;
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) == 0 &&
+                    CHECK(second)) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+    %enddef
+
+    %define specialize_std_pair_on_both(T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO,
+                                        U,CHECK_U,CONVERT_U_FROM,CONVERT_U_TO)
+    template<> struct pair<T,U> {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                if (!CHECK_T(first) || !CHECK_U(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "map<" #T "," #U "> expected");
+                $1 = std::make_pair(CONVERT_T_FROM(first),
+                                    CONVERT_U_FROM(second));
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                      std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                      std::pair<T,U>* m) {
+            if (gh_pair_p($input)) {
+                SCM first, second;
+                first = gh_car($input);
+                second = gh_cdr($input);
+                if (!CHECK_T(first) || !CHECK_U(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "map<" #T "," #U "> expected");
+                temp = std::make_pair(CONVERT_T_FROM(first),
+                                      CONVERT_U_FROM(second));
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            $result = gh_cons(CONVERT_T_TO($1.first),
+                              CONVERT_U_TO($1.second));
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (CHECK_T(first) && CHECK_U(second)) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $&1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (gh_pair_p($input)) {
+                SCM first = gh_car($input);
+                SCM second = gh_cdr($input);
+                if (CHECK_T(first) && CHECK_U(second)) {
+                    $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                    $1_descriptor, 0) == 0)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+    %enddef
+
+
+    specialize_std_pair_on_first(bool,gh_boolean_p,
+                              gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_first(int,gh_number_p,
+                              gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_first(short,gh_number_p,
+                              gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_first(long,gh_number_p,
+                              gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_first(unsigned int,gh_number_p,
+                              gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_first(unsigned short,gh_number_p,
+                              gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_first(unsigned long,gh_number_p,
+                              gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_first(double,gh_number_p,
+                              gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_first(float,gh_number_p,
+                              gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_first(std::string,gh_string_p,
+                              SWIG_scm2string,SWIG_string2scm);
+
+    specialize_std_pair_on_second(bool,gh_boolean_p,
+                                gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_second(int,gh_number_p,
+                                gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_second(short,gh_number_p,
+                                gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_second(long,gh_number_p,
+                                gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_second(unsigned int,gh_number_p,
+                                gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_second(unsigned short,gh_number_p,
+                                gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_second(unsigned long,gh_number_p,
+                                gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_second(double,gh_number_p,
+                                gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_second(float,gh_number_p,
+                                gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_second(std::string,gh_string_p,
+                                SWIG_scm2string,SWIG_string2scm);
+
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(int,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(short,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(long,gh_number_p,
+                               gh_scm2long,gh_long2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(double,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(float,gh_number_p,
+                               gh_scm2double,gh_double2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               bool,gh_boolean_p,
+                               gh_scm2bool,SWIG_bool2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               int,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               short,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               long,gh_number_p,
+                               gh_scm2long,gh_long2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               unsigned int,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               unsigned short,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               unsigned long,gh_number_p,
+                               gh_scm2ulong,gh_ulong2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               double,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               float,gh_number_p,
+                               gh_scm2double,gh_double2scm);
+    specialize_std_pair_on_both(std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm,
+                               std::string,gh_string_p,
+                               SWIG_scm2string,SWIG_string2scm);
+}
diff --git a/trunk/Lib/guile/std_string.i b/trunk/Lib/guile/std_string.i
new file mode 100644
index 0000000..f80a65c
--- /dev/null
+++ b/trunk/Lib/guile/std_string.i
@@ -0,0 +1,90 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string
+ * ----------------------------------------------------------------------------- */
+
+// ------------------------------------------------------------------------
+// std::string is typemapped by value
+// This can prevent exporting methods which return a string
+// in order for the user to modify it.
+// However, I think I'll wait until someone asks for it...
+// ------------------------------------------------------------------------
+
+%include <exception.i>
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+    %naturalvar string;
+
+    class string;
+
+    %typemap(typecheck) string = char *;
+    %typemap(typecheck) const string & = char *;
+
+    %typemap(in) string (char* tempptr) {
+        if (gh_string_p($input)) {
+            tempptr = SWIG_scm2str($input);
+            $1.assign(tempptr);
+            if (tempptr) SWIG_free(tempptr);
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(in) const string & (std::string temp,
+                                 char* tempptr) {
+        if (gh_string_p($input)) {
+            tempptr = SWIG_scm2str($input);
+            temp.assign(tempptr);
+            if (tempptr) SWIG_free(tempptr);
+            $1 = &temp;
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(in) string * (char* tempptr) {
+        if (gh_string_p($input)) {
+            tempptr = SWIG_scm2str($input);
+            $1 = new std::string(tempptr);
+            if (tempptr) SWIG_free(tempptr);
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(out) string {
+        $result = gh_str02scm($1.c_str());
+    }
+
+    %typemap(out) const string & {
+        $result = gh_str02scm($1->c_str());
+    }
+
+    %typemap(out) string * {
+        $result = gh_str02scm($1->c_str());
+    }
+
+    %typemap(varin) string {
+        if (gh_string_p($input)) {
+	    char *tempptr = SWIG_scm2str($input);
+            $1.assign(tempptr);
+            if (tempptr) SWIG_free(tempptr);
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(varout) string {
+        $result = gh_str02scm($1.c_str());
+    }
+
+}
diff --git a/trunk/Lib/guile/std_vector.i b/trunk/Lib/guile/std_vector.i
new file mode 100644
index 0000000..145db94
--- /dev/null
+++ b/trunk/Lib/guile/std_vector.i
@@ -0,0 +1,413 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * SWIG typemaps for std::vector
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// Guile as much as possible, namely, to allow the user to pass and 
+// be returned Guile vectors or lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&), f(const std::vector<T>*):
+//      the parameter being read-only, either a Guile sequence or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f():
+//      the vector is returned by copy; therefore, a Guile vector of T:s 
+//      is returned which is most easily used in other Guile functions
+//   -- std::vector<T>& f(), std::vector<T>* f(), const std::vector<T>& f(),
+//      const std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    
+    template<class T> class vector {
+        %typemap(in) vector<T> {
+            if (gh_vector_p($input)) {
+                unsigned long size = gh_vector_length($input);
+                $1 = std::vector<T >(size);
+                for (unsigned long i=0; i<size; i++) {
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(i));
+                    (($1_type &)$1)[i] =
+                        *((T*) SWIG_MustGetPtr(o,$descriptor(T *),$argnum, 0));
+                }
+            } else if (gh_null_p($input)) {
+                $1 = std::vector<T >();
+            } else if (gh_pair_p($input)) {
+                SCM head, tail;
+                $1 = std::vector<T >();
+                tail = $input;
+                while (!gh_null_p(tail)) {
+                    head = gh_car(tail);
+                    tail = gh_cdr(tail);
+                    $1.push_back(*((T*)SWIG_MustGetPtr(head,
+                                                       $descriptor(T *),
+                                                       $argnum, 0)));
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const vector<T>& (std::vector<T> temp),
+                     const vector<T>* (std::vector<T> temp) {
+            if (gh_vector_p($input)) {
+                unsigned long size = gh_vector_length($input);
+                temp = std::vector<T >(size);
+                $1 = &temp;
+                for (unsigned long i=0; i<size; i++) {
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(i));
+                    temp[i] = *((T*) SWIG_MustGetPtr(o,
+                                                     $descriptor(T *),
+                                                     $argnum, 0));
+                }
+            } else if (gh_null_p($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+            } else if (gh_pair_p($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+                SCM head, tail;
+                tail = $input;
+                while (!gh_null_p(tail)) {
+                    head = gh_car(tail);
+                    tail = gh_cdr(tail);
+                    temp.push_back(*((T*) SWIG_MustGetPtr(head,
+                                                          $descriptor(T *),
+                                                          $argnum, 0)));
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) vector<T> {
+            $result = gh_make_vector(gh_long2scm($1.size()),SCM_UNSPECIFIED);
+            for (unsigned int i=0; i<$1.size(); i++) {
+                T* x = new T((($1_type &)$1)[i]);
+                gh_vector_set_x($result,gh_long2scm(i),
+                                SWIG_NewPointerObj(x, $descriptor(T *), 1));
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            /* native sequence? */
+            if (gh_vector_p($input)) {
+                unsigned int size = gh_vector_length($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(0));
+                    T* x;
+                    if (SWIG_ConvertPtr(o,(void**) &x,
+                                          $descriptor(T *), 0) != -1)
+                        $1 = 1;
+                    else
+                        $1 = 0;
+                }
+            } else if (gh_null_p($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                /* check the first element only */
+                T* x;
+                SCM head = gh_car($input);
+                if (SWIG_ConvertPtr(head,(void**) &x,
+                                      $descriptor(T *), 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                      $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            /* native sequence? */
+            if (gh_vector_p($input)) {
+                unsigned int size = gh_vector_length($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(0));
+                    if (SWIG_ConvertPtr(o,(void**) &x,
+                                          $descriptor(T *), 0) != -1)
+                        $1 = 1;
+                    else
+                        $1 = 0;
+                }
+            } else if (gh_null_p($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                /* check the first element only */
+                T* x;
+                SCM head = gh_car($input);
+                if (SWIG_ConvertPtr(head,(void**) &x,
+                                      $descriptor(T *), 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                      $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T>&);
+        %rename(length) size;
+        unsigned int size() const;
+        %rename("empty?") empty;
+        bool empty() const;
+        %rename("clear!") clear;
+        void clear();
+        %rename("set!") set;
+        %rename("pop!") pop;
+        %rename("push!") push_back;
+        void push_back(const T& x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T& ref(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, const T& x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+    %define specialize_stl_vector(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<> class vector<T> {
+        %typemap(in) vector<T> {
+            if (gh_vector_p($input)) {
+                unsigned long size = gh_vector_length($input);
+                $1 = std::vector<T >(size);
+                for (unsigned long i=0; i<size; i++) {
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(i));
+                    if (CHECK(o))
+                        (($1_type &)$1)[i] = (T)(CONVERT_FROM(o));
+                    else
+                        scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+                }
+            } else if (gh_null_p($input)) {
+                $1 = std::vector<T >();
+            } else if (gh_pair_p($input)) {
+                SCM v = gh_list_to_vector($input);
+                unsigned long size = gh_vector_length(v);
+                $1 = std::vector<T >(size);
+                for (unsigned long i=0; i<size; i++) {
+                    SCM o = gh_vector_ref(v,gh_ulong2scm(i));
+                    if (CHECK(o))
+                        (($1_type &)$1)[i] = (T)(CONVERT_FROM(o));
+                    else
+                        scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const vector<T>& (std::vector<T> temp),
+                     const vector<T>* (std::vector<T> temp) {
+            if (gh_vector_p($input)) {
+                unsigned long size = gh_vector_length($input);
+                temp = std::vector<T >(size);
+                $1 = &temp;
+                for (unsigned long i=0; i<size; i++) {
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(i));
+                    if (CHECK(o))
+                        temp[i] = (T)(CONVERT_FROM(o));
+                    else
+                        scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+                }
+            } else if (gh_null_p($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+            } else if (gh_pair_p($input)) {
+                SCM v = gh_list_to_vector($input);
+                unsigned long size = gh_vector_length(v);
+                temp = std::vector<T >(size);
+                $1 = &temp;
+                for (unsigned long i=0; i<size; i++) {
+                    SCM o = gh_vector_ref(v,gh_ulong2scm(i));
+                    if (CHECK(o))
+                        temp[i] = (T)(CONVERT_FROM(o));
+                    else
+                        scm_wrong_type_arg(FUNC_NAME, $argnum, $input);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) vector<T> {
+            $result = gh_make_vector(gh_long2scm($1.size()),SCM_UNSPECIFIED);
+            for (unsigned int i=0; i<$1.size(); i++) {
+                SCM x = CONVERT_TO((($1_type &)$1)[i]);
+                gh_vector_set_x($result,gh_long2scm(i),x);
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            /* native sequence? */
+            if (gh_vector_p($input)) {
+                unsigned int size = gh_vector_length($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(0));
+                    $1 = CHECK(o) ? 1 : 0;
+                }
+            } else if (gh_null_p($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                /* check the first element only */
+                T* x;
+                SCM head = gh_car($input);
+                $1 = CHECK(head) ? 1 : 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                $1 = (SWIG_ConvertPtr($input,(void **) &v, 
+                                        $&1_descriptor, 0) != -1) ? 1 : 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            /* native sequence? */
+            if (gh_vector_p($input)) {
+                unsigned int size = gh_vector_length($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    SCM o = gh_vector_ref($input,gh_ulong2scm(0));
+                    $1 = CHECK(o) ? 1 : 0;
+                }
+            } else if (gh_null_p($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (gh_pair_p($input)) {
+                /* check the first element only */
+                T* x;
+                SCM head = gh_car($input);
+                $1 = CHECK(head) ? 1 : 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                $1 = (SWIG_ConvertPtr($input,(void **) &v, 
+                                        $1_descriptor, 0) != -1) ? 1 : 0;
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T>&);
+        %rename(length) size;
+        unsigned int size() const;
+        %rename("empty?") empty;
+        bool empty() const;
+        %rename("clear!") clear;
+        void clear();
+        %rename("set!") set;
+        %rename("pop!") pop;
+        %rename("push!") push_back;
+        void push_back(T x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T ref(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, T x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+    %enddef
+
+    specialize_stl_vector(bool,gh_boolean_p,gh_scm2bool,SWIG_bool2scm);
+    specialize_stl_vector(char,gh_number_p,gh_scm2long,gh_long2scm);
+    specialize_stl_vector(int,gh_number_p,gh_scm2long,gh_long2scm);
+    specialize_stl_vector(long,gh_number_p,gh_scm2long,gh_long2scm);
+    specialize_stl_vector(short,gh_number_p,gh_scm2long,gh_long2scm);
+    specialize_stl_vector(unsigned char,gh_number_p,gh_scm2ulong,gh_ulong2scm);
+    specialize_stl_vector(unsigned int,gh_number_p,gh_scm2ulong,gh_ulong2scm);
+    specialize_stl_vector(unsigned long,gh_number_p,gh_scm2ulong,gh_ulong2scm);
+    specialize_stl_vector(unsigned short,gh_number_p,gh_scm2ulong,gh_ulong2scm);
+    specialize_stl_vector(float,gh_number_p,gh_scm2double,gh_double2scm);
+    specialize_stl_vector(double,gh_number_p,gh_scm2double,gh_double2scm);
+    specialize_stl_vector(std::string,gh_string_p,SWIG_scm2string,SWIG_string2scm);
+}
+
diff --git a/trunk/Lib/guile/stl.i b/trunk/Lib/guile/stl.i
new file mode 100644
index 0000000..66b72e0
--- /dev/null
+++ b/trunk/Lib/guile/stl.i
@@ -0,0 +1,15 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/guile/swigrun.i b/trunk/Lib/guile/swigrun.i
new file mode 100644
index 0000000..4b9ea2c
--- /dev/null
+++ b/trunk/Lib/guile/swigrun.i
@@ -0,0 +1,49 @@
+/* -*- mode: c -*- */
+
+%module swigrun
+
+#ifdef SWIGGUILE_SCM
+
+/* Hook the runtime module initialization
+   into the shared initialization function SWIG_Guile_Init. */
+%runtime %{
+/* Hook the runtime module initialization
+   into the shared initialization function SWIG_Guile_Init. */
+#include <libguile.h>
+#ifdef __cplusplus
+extern "C"
+#endif
+SCM scm_init_Swig_swigrun_module (void);
+#define SWIG_INIT_RUNTIME_MODULE scm_init_Swig_swigrun_module();
+%}
+
+/* The runtime type system from common.swg */
+
+typedef struct swig_type_info swig_type_info;
+
+const char *
+SWIG_TypeName(const swig_type_info *type);
+
+const char *
+SWIG_TypePrettyName(const swig_type_info *type);
+
+swig_type_info *
+SWIG_TypeQuery(const char *);
+
+/* Language-specific stuff */
+
+%apply bool { int };
+
+int
+SWIG_IsPointer(SCM object);
+
+int
+SWIG_IsPointerOfType(SCM object, swig_type_info *type);
+
+unsigned long
+SWIG_PointerAddress(SCM object);
+
+swig_type_info *
+SWIG_PointerType(SCM object);
+
+#endif
diff --git a/trunk/Lib/guile/typemaps.i b/trunk/Lib/guile/typemaps.i
new file mode 100644
index 0000000..d9f9728
--- /dev/null
+++ b/trunk/Lib/guile/typemaps.i
@@ -0,0 +1,454 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Guile-specific typemaps
+ * ----------------------------------------------------------------------------- */
+
+/* Pointers */
+
+%typemap(in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, 0);
+}
+%typemap(freearg) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "";
+
+%typemap(in) void * {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, NULL, $argnum, 0);
+}
+%typemap(freearg) void * "";
+
+%typemap(varin) SWIGTYPE * {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0);
+}
+
+%typemap(varin) SWIGTYPE & {
+  $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0));
+}
+
+%typemap(varin) SWIGTYPE [] {
+  scm_wrong_type_arg((char *) FUNC_NAME, 1, $input);
+}
+
+%typemap(varin) SWIGTYPE [ANY] {
+  void *temp;
+  int ii;
+  $1_basetype *b = 0;
+  temp = SWIG_MustGetPtr($input, $1_descriptor, 1, 0);
+  b = ($1_basetype *) $1;
+  for (ii = 0; ii < $1_size; ii++) b[ii] = *(($1_basetype *) temp + ii);
+}
+
+%typemap(varin) void * {
+  $1 = SWIG_MustGetPtr($input, NULL, 1, 0);
+}
+
+%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  $result = SWIG_NewPointerObj ($1, $descriptor, $owner);
+}
+
+%typemap(out) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC {
+  swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor,(void **) &$1);
+  $result = SWIG_NewPointerObj ($1, ty, $owner);
+}
+    
+%typemap(varout) SWIGTYPE *, SWIGTYPE [] {
+  $result = SWIG_NewPointerObj ($1, $descriptor, 0);
+}
+
+%typemap(varout) SWIGTYPE & {
+  $result = SWIG_NewPointerObj((void *) &$1, $1_descriptor, 0);
+}
+
+%typemap(throws) SWIGTYPE {
+  $&ltype temp = new $ltype($1);
+  scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	    gh_list(SWIG_NewPointerObj(temp, $&descriptor, 1),
+		    SCM_UNDEFINED));
+}
+
+%typemap(throws) SWIGTYPE & {
+  scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	    gh_list(SWIG_NewPointerObj(&$1, $descriptor, 1),
+		    SCM_UNDEFINED));
+}
+
+%typemap(throws) SWIGTYPE * {
+  scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	    gh_list(SWIG_NewPointerObj($1, $descriptor, 1),
+		    SCM_UNDEFINED));
+}
+
+%typemap(throws) SWIGTYPE [] {
+  scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	    gh_list(SWIG_NewPointerObj($1, $descriptor, 1),
+		    SCM_UNDEFINED));
+}
+
+/* Change of object ownership, and interaction of destructor-like functions and the
+   garbage-collector */
+
+%typemap(in, doc="$NAME is of type <$type> and gets destroyed by the function") SWIGTYPE *DESTROYED {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, 0);
+}
+
+%typemap(freearg) SWIGTYPE *DESTROYED {
+  SWIG_Guile_MarkPointerDestroyed($input);
+}
+
+%typemap(in, doc="$NAME is of type <$type> and is consumed by the function") SWIGTYPE *CONSUMED {
+  $1 = ($1_ltype)SWIG_MustGetPtr($input, $descriptor, $argnum, 0);
+  SWIG_Guile_MarkPointerNoncollectable($input);
+}
+
+/* Pass-by-value */
+
+%typemap(in) SWIGTYPE($&1_ltype argp) {
+  argp = ($&1_ltype)SWIG_MustGetPtr($input, $&1_descriptor, $argnum, 0);
+  $1 = *argp;
+}
+
+%typemap(varin) SWIGTYPE {
+  $&1_ltype argp;
+  argp = ($&1_ltype)SWIG_MustGetPtr($input, $&1_descriptor, 1, 0);
+  $1 = *argp;
+}
+
+%typemap(out) SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  resultptr = new $1_ltype((const $1_ltype &) $1);
+  $result =  SWIG_NewPointerObj (resultptr, $&1_descriptor, 1);
+} 
+#else
+{
+  $&1_ltype resultptr;
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 1);
+}
+#endif
+
+%typemap(varout) SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  resultptr = new $1_ltype((const $1_ltype&) $1);
+  $result =  SWIG_NewPointerObj (resultptr, $&1_descriptor, 0);
+} 
+#else
+{
+  $&1_ltype resultptr;
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 0);
+}
+#endif
+
+/* Enums */
+
+%typemap(in)     enum SWIGTYPE  { $1 = ($1_type) gh_scm2int($input); }
+/* The complicated construction below needed to deal with anonymous
+   enums, which cannot be cast to. */
+%typemap(varin)  enum SWIGTYPE  {
+  if (sizeof(int) != sizeof($1)) {
+    scm_error(scm_str2symbol("swig-error"),
+	      (char *) FUNC_NAME,
+	      (char *) "enum variable '$name' cannot be set",
+	      SCM_EOL, SCM_BOOL_F); 
+  }
+  * (int *) &($1) = gh_scm2int($input);
+}
+%typemap(out)    enum SWIGTYPE  { $result = gh_int2scm($1); }
+%typemap(varout) enum SWIGTYPE  { $result = gh_int2scm($1); }
+%typemap(throws) enum SWIGTYPE {
+  scm_throw(gh_symbol2scm((char *) "swig-exception"),
+     gh_list(gh_int2scm($1), SCM_UNDEFINED));
+}
+
+/* The SIMPLE_MAP_WITH_EXPR macro below defines the whole set of
+   typemaps needed for simple types.
+   -- SCM_TO_C_EXPR is a C expression that translates the Scheme value
+      "swig_scm_value" to a C value.
+   -- C_TO_SCM_EXPR is a C expression that translates the C value
+      "swig_c_value" to a Scheme value. */
+
+%define SIMPLE_MAP_WITH_EXPR(C_NAME, SCM_TO_C_EXPR, C_TO_SCM_EXPR, SCM_NAME)
+ %typemap (in,     doc="$NAME is of type <" #SCM_NAME ">") C_NAME
+     { SCM swig_scm_value = $input;
+       $1 = SCM_TO_C_EXPR; }
+ %typemap (varin,  doc="NEW-VALUE is of type <" #SCM_NAME ">") C_NAME
+     { SCM swig_scm_value = $input;
+       $1 = SCM_TO_C_EXPR; }
+ %typemap (out,    doc="<" #SCM_NAME ">") C_NAME
+     { C_NAME swig_c_value = $1;
+       $result = C_TO_SCM_EXPR; }
+ %typemap (varout, doc="<" #SCM_NAME ">") C_NAME
+     { C_NAME swig_c_value = $1;
+       $result = C_TO_SCM_EXPR; }
+ /* INPUT and OUTPUT */
+ %typemap (in, doc="$NAME is of type <" #SCM_NAME ">)")
+     C_NAME *INPUT(C_NAME temp) {
+       SCM swig_scm_value = $input;
+       temp = (C_NAME) SCM_TO_C_EXPR; $1 = &temp; }
+ %typemap (in,numinputs=0)      C_NAME *OUTPUT (C_NAME temp)
+     {$1 = &temp;}
+ %typemap (argout,doc="$name (of type <" #SCM_NAME ">)") C_NAME *OUTPUT
+     { C_NAME swig_c_value = *$1;
+       SWIG_APPEND_VALUE(C_TO_SCM_EXPR); }
+ %typemap (in)          C_NAME *BOTH = C_NAME *INPUT;
+ %typemap (argout)      C_NAME *BOTH = C_NAME *OUTPUT;
+ %typemap (in)          C_NAME *INOUT = C_NAME *INPUT;
+ %typemap (argout)      C_NAME *INOUT = C_NAME *OUTPUT;
+ /* Const primitive references.  Passed by value */
+ %typemap(in, doc="$NAME is of type <" #SCM_NAME ">") const C_NAME & (C_NAME temp)
+     { SCM swig_scm_value = $input;
+       temp = SCM_TO_C_EXPR;
+       $1 = &temp; }
+ %typemap(out, doc="<" #SCM_NAME ">")  const C_NAME &
+     { C_NAME swig_c_value = *$1;
+       $result = C_TO_SCM_EXPR; }
+ /* Throw typemap */
+ %typemap(throws) C_NAME {
+   C_NAME swig_c_value = $1;
+   scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	     gh_list(C_TO_SCM_EXPR, SCM_UNDEFINED));
+ }
+%enddef
+
+/* The SIMPLE_MAP macro below defines the whole set of typemaps needed
+   for simple types.  It generates slightly simpler code than the
+   macro above, but it is only suitable for very simple conversion
+   expressions. */
+
+%define SIMPLE_MAP(C_NAME, SCM_TO_C, C_TO_SCM, SCM_NAME)
+ %typemap (in,     doc="$NAME is of type <" #SCM_NAME ">")
+     C_NAME {$1 = ($1_ltype) SCM_TO_C($input);}
+ %typemap (varin,  doc="NEW-VALUE is of type <" #SCM_NAME ">")
+     C_NAME {$1 = ($1_ltype) SCM_TO_C($input);}
+ %typemap (out,    doc="<" #SCM_NAME ">")
+     C_NAME {$result = C_TO_SCM($1);}
+ %typemap (varout, doc="<" #SCM_NAME ">")
+     C_NAME {$result = C_TO_SCM($1);}
+ /* INPUT and OUTPUT */
+ %typemap (in, doc="$NAME is of type <" #SCM_NAME ">)")
+     C_NAME *INPUT(C_NAME temp), C_NAME &INPUT(C_NAME temp) {
+   temp = (C_NAME) SCM_TO_C($input); $1 = &temp;
+ }
+ %typemap (in,numinputs=0)      C_NAME *OUTPUT (C_NAME temp), C_NAME &OUTPUT(C_NAME temp)
+   {$1 = &temp;}
+ %typemap (argout,doc="$name (of type <" #SCM_NAME ">)") C_NAME *OUTPUT, C_NAME &OUTPUT
+   {SWIG_APPEND_VALUE(C_TO_SCM(*$1));}
+ %typemap (in)          C_NAME *BOTH = C_NAME *INPUT;
+ %typemap (argout)      C_NAME *BOTH = C_NAME *OUTPUT;
+ %typemap (in)          C_NAME *INOUT = C_NAME *INPUT;
+ %typemap (argout)      C_NAME *INOUT = C_NAME *OUTPUT;
+ %typemap (in)          C_NAME &INOUT = C_NAME &INPUT;
+ %typemap (argout)      C_NAME &INOUT = C_NAME &OUTPUT;
+ /* Const primitive references.  Passed by value */
+ %typemap(in, doc="$NAME is of type <" #SCM_NAME ">") const C_NAME & (C_NAME temp) {
+   temp = SCM_TO_C($input);
+   $1 = ($1_ltype) &temp;
+ }
+ %typemap(out, doc="<" #SCM_NAME ">")  const C_NAME & {
+   $result = C_TO_SCM(*$1);
+ }
+ /* Throw typemap */
+ %typemap(throws) C_NAME {
+   scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	     gh_list(C_TO_SCM($1), SCM_UNDEFINED));
+ }
+%enddef
+
+ SIMPLE_MAP(bool, gh_scm2bool, gh_bool2scm, boolean);
+ SIMPLE_MAP(char, gh_scm2char, gh_char2scm, char);
+ SIMPLE_MAP(unsigned char, gh_scm2char, gh_char2scm, char);
+ SIMPLE_MAP(signed char, gh_scm2char, gh_char2scm, char);
+ SIMPLE_MAP(int, gh_scm2int, gh_int2scm, integer);
+ SIMPLE_MAP(short, gh_scm2short, gh_int2scm, integer);
+ SIMPLE_MAP(long, gh_scm2long, gh_long2scm, integer);
+ SIMPLE_MAP(ptrdiff_t, gh_scm2long, gh_long2scm, integer);
+ SIMPLE_MAP(unsigned int, gh_scm2uint, gh_ulong2scm, integer);
+ SIMPLE_MAP(unsigned short, gh_scm2ushort, gh_ulong2scm, integer);
+ SIMPLE_MAP(unsigned long, gh_scm2ulong, gh_ulong2scm, integer);
+ SIMPLE_MAP(size_t, gh_scm2ulong, gh_ulong2scm, integer);
+ SIMPLE_MAP(float, gh_scm2double, gh_double2scm, real);
+ SIMPLE_MAP(double, gh_scm2double, gh_double2scm, real);
+// SIMPLE_MAP(char *, SWIG_scm2str, gh_str02scm, string);
+// SIMPLE_MAP(const char *, SWIG_scm2str, gh_str02scm, string);
+
+/* Define long long typemaps -- uses functions that are only defined
+   in recent versions of Guile, availability also depends on Guile's
+   configuration. */
+
+SIMPLE_MAP(long long, gh_scm2long_long, gh_long_long2scm, integer);
+SIMPLE_MAP(unsigned long long, gh_scm2ulong_long, gh_ulong_long2scm, integer);
+
+/* Strings */
+
+ %typemap (in,     doc="$NAME is a string")      char *(int must_free = 0) {
+  $1 = ($1_ltype)SWIG_scm2str($input);
+  must_free = 1;
+ }
+ %typemap (varin,  doc="NEW-VALUE is a string")  char * {$1 = ($1_ltype)SWIG_scm2str($input);}
+ %typemap (out,    doc="<string>")              char * {$result = gh_str02scm((const char *)$1);}
+ %typemap (varout, doc="<string>")              char * {$result = gh_str02scm($1);}
+ %typemap (in, doc="$NAME is a string")          char * *INPUT(char * temp, int must_free = 0) {
+   temp = (char *) SWIG_scm2str($input); $1 = &temp;
+   must_free = 1;
+ }
+ %typemap (in,numinputs=0)  char * *OUTPUT (char * temp)
+   {$1 = &temp;}
+ %typemap (argout,doc="$NAME (a string)") char * *OUTPUT
+   {SWIG_APPEND_VALUE(gh_str02scm(*$1));}
+ %typemap (in)          char * *BOTH = char * *INPUT;
+ %typemap (argout)      char * *BOTH = char * *OUTPUT;
+ %typemap (in)          char * *INOUT = char * *INPUT;
+ %typemap (argout)      char * *INOUT = char * *OUTPUT;
+
+/* SWIG_scm2str makes a malloc'ed copy of the string, so get rid of it after
+   the function call. */
+
+%typemap (freearg) char * "if (must_free$argnum && $1) SWIG_free($1);";
+%typemap (freearg) char **INPUT, char **BOTH "if (must_free$argnum && (*$1)) SWIG_free(*$1);"
+%typemap (freearg) char **OUTPUT "SWIG_free(*$1);"
+  
+/* But this shall not apply if we try to pass a single char by
+   reference. */
+
+%typemap (freearg) char *OUTPUT, char *BOTH "";
+
+/* If we set a string variable, delete the old result first, unless const. */
+
+%typemap (varin) char * {
+    if ($1) free($1);
+    $1 = ($1_ltype) SWIG_scm2str($input);
+}
+
+%typemap (varin) const char * {
+    $1 = ($1_ltype) SWIG_scm2str($input);
+}
+
+%typemap(throws) char * {
+  scm_throw(gh_symbol2scm((char *) "swig-exception"),
+	    gh_list(gh_str02scm($1), SCM_UNDEFINED));
+}
+
+/* Void */
+
+%typemap (out,doc="") void "gswig_result = SCM_UNSPECIFIED;";
+
+/* SCM is passed through */
+
+typedef unsigned long SCM;
+%typemap (in) SCM "$1=$input;";
+%typemap (out) SCM "$result=$1;";
+%typecheck(SWIG_TYPECHECK_POINTER) SCM "$1=1;";
+
+/* ------------------------------------------------------------
+ * String & length
+ * ------------------------------------------------------------ */
+
+%typemap(in) (char *STRING, int LENGTH) {
+    size_t temp;
+    $1 = ($1_ltype) gh_scm2newstr($input, &temp);
+    $2 = ($2_ltype) temp;
+}
+
+/* ------------------------------------------------------------
+ * CLASS::* (member function pointer) typemaps
+ * taken from typemaps/swigtype.swg
+ * ------------------------------------------------------------ */
+
+#define %set_output(obj)                  $result = obj
+#define %set_varoutput(obj)               $result = obj
+#define %argument_fail(code, type, name, argn)	scm_wrong_type_arg((char *) FUNC_NAME, argn, $input);
+#define %as_voidptr(ptr)		(void*)(ptr)
+
+%typemap(in) SWIGTYPE (CLASS::*) {  
+  int res = SWIG_ConvertMember($input, %as_voidptr(&$1), sizeof($type),$descriptor);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum); 
+  }
+}
+
+%typemap(out,noblock=1) SWIGTYPE (CLASS::*) {
+  %set_output(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor));
+}
+
+%typemap(varin) SWIGTYPE (CLASS::*) {
+  int res = SWIG_ConvertMember($input,%as_voidptr(&$1), sizeof($type), $descriptor);
+  if (!SWIG_IsOK(res)) {
+    scm_wrong_type_arg((char *) FUNC_NAME, 1, $input);
+  }
+}
+
+%typemap(varout,noblock=1) SWIGTYPE (CLASS::*) {
+  %set_varoutput(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor));
+}
+
+/* ------------------------------------------------------------
+ * Typechecking rules
+ * ------------------------------------------------------------ */
+
+/* adapted from python.swg */
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 int, short, long,
+ 	 unsigned int, unsigned short, unsigned long,
+	 signed char, unsigned char,
+	 long long, unsigned long long,
+         size_t, ptrdiff_t,
+         std::size_t, std::ptrdiff_t,
+	 const int &, const short &, const long &,
+ 	 const unsigned int &, const unsigned short &, const unsigned long &,
+	 const long long &, const unsigned long long &,
+         const size_t &, const ptrdiff_t &,
+         const std::size_t &, const std::ptrdiff_t &,
+	 enum SWIGTYPE
+{
+  $1 = SCM_NFALSEP(scm_integer_p($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_BOOL)
+	bool, bool&, const bool&
+{
+  $1 = SCM_BOOLP($input) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE)
+	float, double,
+	const float &, const double &
+{
+  $1 = SCM_NFALSEP(scm_real_p($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_CHAR) char {
+  $1 = SCM_CHARP($input) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char * {
+  $1 = SCM_STRINGP($input) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  void *ptr;
+  int res = SWIG_ConvertPtr($input, &ptr, $1_descriptor, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
+  void *ptr;
+  int res = SWIG_ConvertPtr($input, &ptr, $&descriptor, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  int res = SWIG_ConvertPtr($input, &ptr, 0, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+/* typemaps.i ends here */
diff --git a/trunk/Lib/inttypes.i b/trunk/Lib/inttypes.i
new file mode 100644
index 0000000..0cc8194
--- /dev/null
+++ b/trunk/Lib/inttypes.i
@@ -0,0 +1,94 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * inttypes.i
+ *
+ * SWIG library file  for ISO C99 types: 7.8 Format conversion of integer types <inttypes.h>
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <inttypes.h>
+%}
+
+%include <stdint.i>
+%include <wchar.i>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef SWIGWORDSIZE64
+  
+  /* We have to define the `uintmax_t' type using `ldiv_t'.  */
+  typedef struct
+  {
+    long int quot;		/* Quotient.  */
+    long int rem;		/* Remainder.  */
+  } imaxdiv_t;
+  
+#else
+  
+  /* We have to define the `uintmax_t' type using `lldiv_t'.  */
+  typedef struct
+  {
+    long long int quot;		/* Quotient.  */
+    long long int rem;		/* Remainder.  */
+  } imaxdiv_t;
+
+#endif
+
+  /* Compute absolute value of N.  */
+  extern intmax_t imaxabs (intmax_t n);
+
+  /* Return the `imaxdiv_t' representation of the value of NUMER over DENOM. */
+  extern imaxdiv_t imaxdiv (intmax_t numer, intmax_t denom);
+  
+  /* Like `strtol' but convert to `intmax_t'.  */
+  extern intmax_t strtoimax (const char *nptr, char **endptr, int base);
+  
+  /* Like `strtoul' but convert to `uintmax_t'.  */
+  extern uintmax_t strtoumax (const char *nptr, char ** endptr, int base);
+
+#ifdef SWIG_WCHAR
+  /* Like `wcstol' but convert to `intmax_t'.  */
+  extern intmax_t wcstoimax (const wchar_t *nptr, wchar_t **endptr, int base);
+  
+  /* Like `wcstoul' but convert to `uintmax_t'.  */
+  extern uintmax_t wcstoumax (const wchar_t *nptr, wchar_t ** endptr, int base);
+#endif
+
+#ifdef SWIGWORDSIZE64
+  
+  /* Like `strtol' but convert to `intmax_t'.  */
+  extern  intmax_t strtoimax (const char *nptr, char **endptr, int base);
+  
+  /* Like `strtoul' but convert to `uintmax_t'.  */
+  extern  uintmax_t strtoumax (const char *nptr, char **endptr,int base);
+  
+#ifdef SWIG_WCHAR
+  /* Like `wcstol' but convert to `intmax_t'.  */
+  extern  intmax_t wcstoimax (const wchar_t *nptr, wchar_t **endptr, int base);
+  
+  /* Like `wcstoul' but convert to `uintmax_t'.  */
+  extern  uintmax_t wcstoumax (const wchar_t *nptr, wchar_t **endptr, int base);
+#endif
+  
+#else /* SWIGWORDSIZE32 */
+  
+  /* Like `strtol' but convert to `intmax_t'.  */
+  extern  intmax_t strtoimax (const char *nptr, char **endptr, int base);
+  
+  /* Like `strtoul' but convert to `uintmax_t'.  */
+  extern  uintmax_t strtoumax (const char *nptr, char **endptr, int base);
+  
+#ifdef SWIG_WCHAR
+  /* Like `wcstol' but convert to `intmax_t'.  */
+  extern  uintmax_t wcstoumax (const wchar_t *nptr, wchar_t **endptr, int base);
+#endif
+
+#endif	/* SWIGWORDSIZE32 */
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/java/arrays_java.i b/trunk/Lib/java/arrays_java.i
new file mode 100644
index 0000000..95510c3
--- /dev/null
+++ b/trunk/Lib/java/arrays_java.i
@@ -0,0 +1,391 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * arrays_java.i
+ *
+ * These typemaps give more natural support for arrays. The typemaps are not efficient
+ * as there is a lot of copying of the array values whenever the array is passed to C/C++ 
+ * from Java and vice versa. The Java array is expected to be the same size as the C array.
+ * An exception is thrown if they are not.
+ *
+ * Example usage:
+ * Wrapping:
+ *
+ *   %include <arrays_java.i>
+ *   %inline %{
+ *       short FiddleSticks[3];
+ *   %}
+ *
+ * Use from Java like this:
+ *
+ *   short[] fs = new short[] {10, 11, 12};
+ *   example.setFiddleSticks(fs);
+ *   fs = example.getFiddleSticks();
+ * ----------------------------------------------------------------------------- */
+
+/* Primitive array support is a combination of SWIG macros and functions in order to reduce 
+ * code bloat and aid maintainability. The SWIG preprocessor expands the macros into functions 
+ * for inclusion in the generated code. */
+
+/* Array support functions declarations macro */
+%define JAVA_ARRAYS_DECL(CTYPE, JNITYPE, JAVATYPE, JFUNCNAME)
+%{
+int SWIG_JavaArrayIn##JFUNCNAME (JNIEnv *jenv, JNITYPE **jarr, CTYPE **carr, JNITYPE##Array input);
+void SWIG_JavaArrayArgout##JFUNCNAME (JNIEnv *jenv, JNITYPE *jarr, CTYPE *carr, JNITYPE##Array input);
+JNITYPE##Array SWIG_JavaArrayOut##JFUNCNAME (JNIEnv *jenv, CTYPE *result, jsize sz);
+%}
+%enddef
+
+/* Array support functions macro */
+%define JAVA_ARRAYS_IMPL(CTYPE, JNITYPE, JAVATYPE, JFUNCNAME)
+%{
+/* CTYPE[] support */
+int SWIG_JavaArrayIn##JFUNCNAME (JNIEnv *jenv, JNITYPE **jarr, CTYPE **carr, JNITYPE##Array input) {
+  int i;
+  jsize sz;
+  if (!input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null array");
+    return 0;
+  }
+  sz = JCALL1(GetArrayLength, jenv, input);
+  *jarr = JCALL2(Get##JAVATYPE##ArrayElements, jenv, input, 0);
+  if (!*jarr)
+    return 0; %}
+#ifdef __cplusplus
+%{  *carr = new CTYPE[sz]; %}
+#else
+%{  *carr = (CTYPE*) calloc(sz, sizeof(CTYPE)); %}
+#endif
+%{  if (!*carr) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed");
+    return 0;
+  }
+  for (i=0; i<sz; i++)
+    JAVA_TYPEMAP_ARRAY_ELEMENT_ASSIGN(CTYPE)
+  return 1;
+}
+
+void SWIG_JavaArrayArgout##JFUNCNAME (JNIEnv *jenv, JNITYPE *jarr, CTYPE *carr, JNITYPE##Array input) {
+  int i;
+  jsize sz = JCALL1(GetArrayLength, jenv, input);
+  for (i=0; i<sz; i++)
+    jarr[i] = (JNITYPE)carr[i];
+  JCALL3(Release##JAVATYPE##ArrayElements, jenv, input, jarr, 0);
+}
+
+JNITYPE##Array SWIG_JavaArrayOut##JFUNCNAME (JNIEnv *jenv, CTYPE *result, jsize sz) {
+  JNITYPE *arr;
+  int i;
+  JNITYPE##Array jresult = JCALL1(New##JAVATYPE##Array, jenv, sz);
+  if (!jresult)
+    return NULL;
+  arr = JCALL2(Get##JAVATYPE##ArrayElements, jenv, jresult, 0);
+  if (!arr)
+    return NULL;
+  for (i=0; i<sz; i++)
+    arr[i] = (JNITYPE)result[i];
+  JCALL3(Release##JAVATYPE##ArrayElements, jenv, jresult, arr, 0);
+  return jresult;
+}
+%}
+%enddef
+
+%{
+#if defined(SWIG_NOINCLUDE) || defined(SWIG_NOARRAYS)
+%}
+
+#ifdef __cplusplus
+JAVA_ARRAYS_DECL(bool, jboolean, Boolean, Bool)       /* bool[] */
+#endif
+
+JAVA_ARRAYS_DECL(signed char, jbyte, Byte, Schar)     /* signed char[] */
+JAVA_ARRAYS_DECL(unsigned char, jshort, Short, Uchar) /* unsigned char[] */
+JAVA_ARRAYS_DECL(short, jshort, Short, Short)         /* short[] */
+JAVA_ARRAYS_DECL(unsigned short, jint, Int, Ushort)   /* unsigned short[] */
+JAVA_ARRAYS_DECL(int, jint, Int, Int)                 /* int[] */
+JAVA_ARRAYS_DECL(unsigned int, jlong, Long, Uint)     /* unsigned int[] */
+JAVA_ARRAYS_DECL(long, jint, Int, Long)               /* long[] */
+JAVA_ARRAYS_DECL(unsigned long, jlong, Long, Ulong)   /* unsigned long[] */
+JAVA_ARRAYS_DECL(jlong, jlong, Long, Longlong)        /* long long[] */
+JAVA_ARRAYS_DECL(float, jfloat, Float, Float)         /* float[] */
+JAVA_ARRAYS_DECL(double, jdouble, Double, Double)     /* double[] */
+
+%{
+#else
+%}
+
+#ifdef __cplusplus
+/* Bool array element assignment different to other types to keep Visual C++ quiet */
+#define JAVA_TYPEMAP_ARRAY_ELEMENT_ASSIGN(CTYPE) (*carr)[i] = ((*jarr)[i] != 0);
+JAVA_ARRAYS_IMPL(bool, jboolean, Boolean, Bool)       /* bool[] */
+#undef JAVA_TYPEMAP_ARRAY_ELEMENT_ASSIGN
+#endif
+
+#define JAVA_TYPEMAP_ARRAY_ELEMENT_ASSIGN(CTYPE) (*carr)[i] = (CTYPE)(*jarr)[i];
+JAVA_ARRAYS_IMPL(signed char, jbyte, Byte, Schar)     /* signed char[] */
+JAVA_ARRAYS_IMPL(unsigned char, jshort, Short, Uchar) /* unsigned char[] */
+JAVA_ARRAYS_IMPL(short, jshort, Short, Short)         /* short[] */
+JAVA_ARRAYS_IMPL(unsigned short, jint, Int, Ushort)   /* unsigned short[] */
+JAVA_ARRAYS_IMPL(int, jint, Int, Int)                 /* int[] */
+JAVA_ARRAYS_IMPL(unsigned int, jlong, Long, Uint)     /* unsigned int[] */
+JAVA_ARRAYS_IMPL(long, jint, Int, Long)               /* long[] */
+JAVA_ARRAYS_IMPL(unsigned long, jlong, Long, Ulong)   /* unsigned long[] */
+JAVA_ARRAYS_IMPL(jlong, jlong, Long, Longlong)        /* long long[] */
+JAVA_ARRAYS_IMPL(float, jfloat, Float, Float)         /* float[] */
+JAVA_ARRAYS_IMPL(double, jdouble, Double, Double)     /* double[] */
+
+%{
+#endif
+%}
+
+
+/* The rest of this file has the array typemaps */
+
+/* Arrays of primitive types use the following macro. The array typemaps use support functions. */
+%define JAVA_ARRAYS_TYPEMAPS(CTYPE, JTYPE, JNITYPE, JFUNCNAME, JNIDESC)
+
+%typemap(jni) CTYPE[ANY], CTYPE[]               %{JNITYPE##Array%}
+%typemap(jtype) CTYPE[ANY], CTYPE[]             %{JTYPE[]%}
+%typemap(jstype) CTYPE[ANY], CTYPE[]            %{JTYPE[]%}
+
+%typemap(in) CTYPE[] (JNITYPE *jarr)
+%{  if (!SWIG_JavaArrayIn##JFUNCNAME(jenv, &jarr, &$1, $input)) return $null; %}
+%typemap(in) CTYPE[ANY] (JNITYPE *jarr)
+%{  if ($input && JCALL1(GetArrayLength, jenv, $input) != $1_size) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "incorrect array size");
+    return $null;
+  }
+  if (!SWIG_JavaArrayIn##JFUNCNAME(jenv, &jarr, &$1, $input)) return $null; %}
+%typemap(argout) CTYPE[ANY], CTYPE[] 
+%{ SWIG_JavaArrayArgout##JFUNCNAME(jenv, jarr$argnum, $1, $input); %}
+%typemap(out) CTYPE[ANY]
+%{$result = SWIG_JavaArrayOut##JFUNCNAME(jenv, $1, $1_dim0); %}
+%typemap(out) CTYPE[] 
+%{$result = SWIG_JavaArrayOut##JFUNCNAME(jenv, $1, FillMeInAsSizeCannotBeDeterminedAutomatically); %}
+%typemap(freearg) CTYPE[ANY], CTYPE[] 
+#ifdef __cplusplus
+%{ delete [] $1; %}
+#else
+%{ free($1); %}
+#endif
+
+%typemap(javain) CTYPE[ANY], CTYPE[] "$javainput"
+%typemap(javaout) CTYPE[ANY], CTYPE[] {
+    return $jnicall;
+  }
+
+%enddef
+
+JAVA_ARRAYS_TYPEMAPS(bool, boolean, jboolean, Bool, "[Z")       /* bool[ANY] */
+JAVA_ARRAYS_TYPEMAPS(signed char, byte, jbyte, Schar, "[B")     /* signed char[ANY] */
+JAVA_ARRAYS_TYPEMAPS(unsigned char, short, jshort, Uchar, "[S") /* unsigned char[ANY] */
+JAVA_ARRAYS_TYPEMAPS(short, short, jshort, Short, "[S")         /* short[ANY] */
+JAVA_ARRAYS_TYPEMAPS(unsigned short, int, jint, Ushort, "[I")   /* unsigned short[ANY] */
+JAVA_ARRAYS_TYPEMAPS(int, int, jint, Int, "[I")                 /* int[ANY] */
+JAVA_ARRAYS_TYPEMAPS(unsigned int, long, jlong, Uint, "[J")     /* unsigned int[ANY] */
+JAVA_ARRAYS_TYPEMAPS(long, int, jint, Long, "[I")               /* long[ANY] */
+JAVA_ARRAYS_TYPEMAPS(unsigned long, long, jlong, Ulong, "[J")   /* unsigned long[ANY] */
+JAVA_ARRAYS_TYPEMAPS(long long, long, jlong, Longlong, "[J")    /* long long[ANY] */
+JAVA_ARRAYS_TYPEMAPS(float, float, jfloat, Float, "[F")         /* float[ANY] */
+JAVA_ARRAYS_TYPEMAPS(double, double, jdouble, Double, "[D")     /* double[ANY] */
+
+
+%typecheck(SWIG_TYPECHECK_BOOL_ARRAY) /* Java boolean[] */
+    bool[ANY], bool[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT8_ARRAY) /* Java byte[] */
+    signed char[ANY], signed char[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT16_ARRAY) /* Java short[] */
+    unsigned char[ANY], unsigned char[],
+    short[ANY], short[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT32_ARRAY) /* Java int[] */
+    unsigned short[ANY], unsigned short[],
+    int[ANY], int[],
+    long[ANY], long[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT64_ARRAY) /* Java long[] */
+    unsigned int[ANY], unsigned int[],
+    unsigned long[ANY], unsigned long[],
+    long long[ANY], long long[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT128_ARRAY) /* Java BigInteger[] */
+    unsigned long long[ANY], unsigned long long[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT_ARRAY) /* Java float[] */
+    float[ANY], float[]
+    ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY) /* Java double[] */
+    double[ANY], double[]
+    ""
+
+
+/* Arrays of proxy classes. The typemaps in this macro make it possible to treat an array of 
+ * class/struct/unions as an array of Java classes. 
+ * Use the following macro to use these typemaps for an array of class/struct/unions called name:
+ * JAVA_ARRAYSOFCLASSES(name) 
+ * Note that multiple copies of the class/struct is made when using the array as a parameter input. */
+%define JAVA_ARRAYSOFCLASSES(ARRAYSOFCLASSES)
+
+%typemap(jni) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[] "jlongArray"
+%typemap(jtype) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[] "long[]"
+%typemap(jstype) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[] "$javaclassname[]"
+
+%typemap(javain) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[] "$javaclassname.cArrayUnwrap($javainput)"
+%typemap(javaout) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[] {
+    return $javaclassname.cArrayWrap($jnicall, $owner);
+  }
+
+%typemap(in) ARRAYSOFCLASSES[] (jlong *jarr, jsize sz)
+{
+  int i;
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null array");
+    return $null;
+  }
+  sz = JCALL1(GetArrayLength, jenv, $input);
+  jarr = JCALL2(GetLongArrayElements, jenv, $input, 0);
+  if (!jarr) {
+    return $null;
+  }
+#ifdef __cplusplus
+  $1 = new $*1_ltype[sz];
+#else
+  $1 = ($1_ltype) calloc(sz, sizeof($*1_ltype));
+#endif
+  if (!$1) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed");
+    return $null;
+  }
+  for (i=0; i<sz; i++) {
+    $1[i] = **($&1_ltype)&jarr[i];
+  }
+}
+
+%typemap(in) ARRAYSOFCLASSES[ANY] (jlong *jarr, jsize sz)
+{
+  int i;
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null array");
+    return $null;
+  }
+  sz = JCALL1(GetArrayLength, jenv, $input);
+  if (sz != $1_size) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "incorrect array size");
+    return $null;
+  }
+  jarr = JCALL2(GetLongArrayElements, jenv, $input, 0);
+  if (!jarr) {
+    return $null;
+  }
+#ifdef __cplusplus
+  $1 = new $*1_ltype[sz];
+#else
+  $1 = ($1_ltype) calloc(sz, sizeof($*1_ltype));
+#endif
+  if (!$1) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed");
+    return $null;
+  }
+  for (i=0; i<sz; i++) {
+    $1[i] = **($&1_ltype)&jarr[i];
+  }
+}
+
+%typemap(argout) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[]
+{
+  int i;
+  for (i=0; i<sz$argnum; i++) {
+    **($&1_ltype)&jarr$argnum[i] = $1[i];
+  }
+  JCALL3(ReleaseLongArrayElements, jenv, $input, jarr$argnum, 0);
+}
+
+%typemap(out) ARRAYSOFCLASSES[ANY]
+{
+  jlong *arr;
+  int i;
+  $result = JCALL1(NewLongArray, jenv, $1_dim0);
+  if (!$result) {
+    return $null;
+  }
+  arr = JCALL2(GetLongArrayElements, jenv, $result, 0);
+  if (!arr) {
+    return $null;
+  }
+  for (i=0; i<$1_dim0; i++) {
+    arr[i] = 0;
+    *($&1_ltype)&arr[i] = &$1[i];
+  }
+  JCALL3(ReleaseLongArrayElements, jenv, $result, arr, 0);
+}
+
+%typemap(freearg) ARRAYSOFCLASSES[ANY], ARRAYSOFCLASSES[]
+#ifdef __cplusplus
+%{ delete [] $1; %}
+#else
+%{ free($1); %}
+#endif
+
+/* Add some code to the proxy class of the array type for converting between type used in 
+ * JNI class (long[]) and type used in proxy class ( ARRAYSOFCLASSES[] ) */
+%typemap(javacode) ARRAYSOFCLASSES %{
+  protected static long[] cArrayUnwrap($javaclassname[] arrayWrapper) {
+      long[] cArray = new long[arrayWrapper.length];
+      for (int i=0; i<arrayWrapper.length; i++)
+        cArray[i] = $javaclassname.getCPtr(arrayWrapper[i]);
+      return cArray;
+  }
+
+  protected static $javaclassname[] cArrayWrap(long[] cArray, boolean cMemoryOwn) {
+    $javaclassname[] arrayWrapper = new $javaclassname[cArray.length];
+    for (int i=0; i<cArray.length; i++)
+      arrayWrapper[i] = new $javaclassname(cArray[i], cMemoryOwn);
+    return arrayWrapper;
+  }
+%}
+
+%enddef /* JAVA_ARRAYSOFCLASSES */
+
+
+/* Arrays of enums. 
+ * Use the following to use these typemaps for an array of enums called name:
+ * %apply ARRAYSOFENUMS[ANY] { name[ANY] }; */
+%typemap(jni) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] "jintArray"
+%typemap(jtype) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] "int[]"
+%typemap(jstype) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] "int[]"
+
+%typemap(javain) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] "$javainput"
+%typemap(javaout) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] {
+    return $jnicall;
+  }
+
+%typemap(in) ARRAYSOFENUMS[] (jint *jarr)
+%{  if (!SWIG_JavaArrayInInt(jenv, &jarr, (int **)&$1, $input)) return $null; %}
+%typemap(in) ARRAYSOFENUMS[ANY] (jint *jarr) {
+  if ($input && JCALL1(GetArrayLength, jenv, $input) != $1_size) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "incorrect array size");
+    return $null;
+  }
+  if (!SWIG_JavaArrayInInt(jenv, &jarr, (int **)&$1, $input)) return $null;
+}
+%typemap(argout) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] 
+%{ SWIG_JavaArrayArgoutInt(jenv, jarr$argnum, (int *)$1, $input); %}
+%typemap(out) ARRAYSOFENUMS[ANY] 
+%{$result = SWIG_JavaArrayOutInt(jenv, (int *)$1, $1_dim0); %}
+%typemap(freearg) ARRAYSOFENUMS[ANY], ARRAYSOFENUMS[] 
+#ifdef __cplusplus
+%{ delete [] $1; %}
+#else
+%{ free($1); %}
+#endif
+
diff --git a/trunk/Lib/java/boost_shared_ptr.i b/trunk/Lib/java/boost_shared_ptr.i
new file mode 100644
index 0000000..1f555bf
--- /dev/null
+++ b/trunk/Lib/java/boost_shared_ptr.i
@@ -0,0 +1,192 @@
+%include <shared_ptr.i>
+
+%define SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, CONST, TYPE...)
+
+%naturalvar TYPE;
+%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+
+// destructor mods
+%feature("unref") TYPE 
+//"if (debug_shared) { cout << \"deleting use_count: \" << (*smartarg1).use_count() << \" [\" << (boost::get_deleter<SWIG_null_deleter>(*smartarg1) ? std::string(\"CANNOT BE DETERMINED SAFELY\") : ( (*smartarg1).get() ? (*smartarg1)->getValue() : std::string(\"NULL PTR\") )) << \"]\" << endl << flush; }\n"
+                               "(void)arg1; delete smartarg1;"
+
+
+// plain value
+%typemap(in) CONST TYPE ($&1_type argp = 0) %{
+  argp = (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0;
+  if (!argp) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type");
+    return $null;
+  }
+  $1 = *argp; %}
+%typemap(out) CONST TYPE 
+%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)); %}
+
+// plain pointer
+%typemap(in) CONST TYPE * (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) %{
+  smartarg = *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input;
+  $1 = (TYPE *)(smartarg ? smartarg->get() : 0); %}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE * %{
+  *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0;
+%}
+
+// plain reference
+%typemap(in) CONST TYPE & %{
+  $1 = ($1_ltype)((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0);
+  if(!$1) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null");
+    return $null;
+  } %}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE &
+%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner); %}
+
+// plain pointer by reference
+%typemap(in) CONST TYPE *& ($*1_ltype temp = 0)
+%{ temp = ((*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input) ? (*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$input)->get() : 0);
+   $1 = &temp; %}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE *&
+%{ *(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > **)&$result = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner); %}
+
+// shared_ptr by value
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > ($&1_type argp)
+%{ argp = *($&1_ltype*)&$input; 
+   if (argp) $1 = *argp; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >
+%{ *($&1_ltype*)&$result = $1 ? new $1_ltype($1) : 0; %}
+
+// shared_ptr by reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & ($*1_ltype tempnull)
+%{ $1 = $input ? *($&1_ltype)&$input : &tempnull; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &
+%{ *($&1_ltype)&$result = *$1 ? new $*1_ltype(*$1) : 0; %} 
+
+// shared_ptr by pointer
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * ($*1_ltype tempnull)
+%{ $1 = $input ? *($&1_ltype)&$input : &tempnull; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *
+%{ *($&1_ltype)&$result = ($1 && *$1) ? new $*1_ltype(*$1) : 0;
+   if ($owner) delete $1; %}
+
+// shared_ptr by pointer reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& (SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempnull, $*1_ltype temp = 0)
+%{ temp = $input ? *($1_ltype)&$input : &tempnull;
+   $1 = &temp; %}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *&
+%{ *($1_ltype)&$result = (*$1 && **$1) ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(**$1) : 0; %} 
+
+// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug
+%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+
+
+%typemap (jni)    SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "jlong"
+%typemap (jtype)  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "long"
+%typemap (jstype) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "PROXYCLASS"
+
+%typemap(javain) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >, 
+                 SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                 SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                 SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& "PROXYCLASS.getCPtr($javainput)"
+
+%typemap(javaout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new PROXYCLASS(cPtr, true);
+  }
+%typemap(javaout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new PROXYCLASS(cPtr, true);
+  }
+%typemap(javaout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new PROXYCLASS(cPtr, true);
+  }
+%typemap(javaout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new PROXYCLASS(cPtr, true);
+  }
+
+
+%typemap(javaout) CONST TYPE {
+    return new PROXYCLASS($jnicall, true);
+  }
+%typemap(javaout) CONST TYPE & {
+    return new PROXYCLASS($jnicall, true);
+  }
+%typemap(javaout) CONST TYPE * {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new PROXYCLASS(cPtr, true);
+  }
+%typemap(javaout) CONST TYPE *& {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new PROXYCLASS(cPtr, true);
+  }
+
+// Base proxy classes
+%typemap(javabody) TYPE %{
+  private long swigCPtr;
+  private boolean swigCMemOwnBase;
+
+  protected $javaclassname(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwnBase = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+// Derived proxy classes
+%typemap(javabody_derived) TYPE %{
+  private long swigCPtr;
+  private boolean swigCMemOwnDerived;
+
+  protected $javaclassname(long cPtr, boolean cMemoryOwn) {
+    super($imclassname.$javaclassname_SWIGSharedPtrUpcast(cPtr), true);
+    swigCMemOwnDerived = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  protected static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") TYPE {
+    if(swigCPtr != 0 && swigCMemOwnBase) {
+      swigCMemOwnBase = false;
+      $jnicall;
+    }
+    swigCPtr = 0;
+  }
+
+%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized") TYPE {
+    if(swigCPtr != 0 && swigCMemOwnDerived) {
+      swigCMemOwnDerived = false;
+      $jnicall;
+    }
+    swigCPtr = 0;
+    super.delete();
+  }
+
+// CONST version needed ???? also for C#
+%typemap(jtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast "long"
+%typemap(jtype, nopgcpp="1") SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > swigSharedPtrUpcast "long"
+
+
+%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+%enddef
+
diff --git a/trunk/Lib/java/director.swg b/trunk/Lib/java/director.swg
new file mode 100644
index 0000000..fa58867
--- /dev/null
+++ b/trunk/Lib/java/director.swg
@@ -0,0 +1,191 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * director.swg
+ *
+ * This file contains support for director classes that proxy
+ * method calls from C++ to Java extensions.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+
+#if defined(DEBUG_DIRECTOR_OWNED)
+#include <iostream>
+#endif
+
+namespace Swig {
+  /* Java object wrapper */
+  class JObjectWrapper {
+  public:
+    JObjectWrapper() : jthis_(NULL), weak_global_(true) {
+    }
+
+    ~JObjectWrapper() {
+      jthis_ = NULL;
+      weak_global_ = true;
+    }
+
+    bool set(JNIEnv *jenv, jobject jobj, bool mem_own, bool weak_global) {
+      if (!jthis_) {
+        weak_global_ = weak_global;
+        if (jobj)
+          jthis_ = ((weak_global_ || !mem_own) ? jenv->NewWeakGlobalRef(jobj) : jenv->NewGlobalRef(jobj));
+#if defined(DEBUG_DIRECTOR_OWNED)
+        std::cout << "JObjectWrapper::set(" << jobj << ", " << (weak_global ? "weak_global" : "global_ref") << ") -> " << jthis_ << std::endl;
+#endif
+        return true;
+      } else {
+#if defined(DEBUG_DIRECTOR_OWNED)
+        std::cout << "JObjectWrapper::set(" << jobj << ", " << (weak_global ? "weak_global" : "global_ref") << ") -> already set" << std::endl;
+#endif
+        return false;
+      }
+    }
+
+    jobject get(JNIEnv *jenv) const {
+#if defined(DEBUG_DIRECTOR_OWNED)
+      std::cout << "JObjectWrapper::get(";
+      if (jthis_)
+        std::cout << jthis_;
+      else
+        std::cout << "null";
+      std::cout << ") -> return new local ref" << std::endl;
+#endif
+      return (jthis_ ? jenv->NewLocalRef(jthis_) : jthis_);
+    }
+
+    void release(JNIEnv *jenv) {
+#if defined(DEBUG_DIRECTOR_OWNED)
+      std::cout << "JObjectWrapper::release(" << jthis_ << "): " << (weak_global_ ? "weak global ref" : "global ref") << std::endl;
+#endif
+      if (jthis_) {
+        if (weak_global_) {
+          if (jenv->IsSameObject(jthis_, NULL) == JNI_FALSE)
+            jenv->DeleteWeakGlobalRef((jweak)jthis_);
+        } else
+          jenv->DeleteGlobalRef(jthis_);
+      }
+
+      jthis_ = NULL;
+      weak_global_ = true;
+    }
+
+    jobject peek() {
+      return jthis_;
+    }
+
+    /* Java proxy releases ownership of C++ object, C++ object is now
+       responsible for destruction (creates NewGlobalRef to pin Java
+       proxy) */
+    void java_change_ownership(JNIEnv *jenv, jobject jself, bool take_or_release) {
+      if (take_or_release) {  /* Java takes ownership of C++ object's lifetime. */
+        if (!weak_global_) {
+          jenv->DeleteGlobalRef(jthis_);
+          jthis_ = jenv->NewWeakGlobalRef(jself);
+          weak_global_ = true;
+        }
+      } else { /* Java releases ownership of C++ object's lifetime */
+        if (weak_global_) {
+          jenv->DeleteWeakGlobalRef((jweak)jthis_);
+          jthis_ = jenv->NewGlobalRef(jself);
+          weak_global_ = false;
+        }
+      }
+    }
+
+  private:
+    /* pointer to Java object */
+    jobject jthis_;
+    /* Local or global reference flag */
+    bool weak_global_;
+  };
+
+  /* director base class */
+  class Director {
+    /* pointer to Java virtual machine */
+    JavaVM *swig_jvm_;
+
+  protected:
+#if defined (_MSC_VER) && (_MSC_VER<1300)
+    class JNIEnvWrapper;
+    friend class JNIEnvWrapper;
+#endif
+    /* Utility class for managing the JNI environment */
+    class JNIEnvWrapper {
+      const Director *director_;
+      JNIEnv *jenv_;
+    public:
+      JNIEnvWrapper(const Director *director) : director_(director), jenv_(0) {
+#if defined(SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON)
+        // Attach a daemon thread to the JVM. Useful when the JVM should not wait for 
+        // the thread to exit upon shutdown. Only for jdk-1.4 and later.
+        director_->swig_jvm_->AttachCurrentThreadAsDaemon((void **) &jenv_, NULL);
+#else
+        director_->swig_jvm_->AttachCurrentThread((void **) &jenv_, NULL);
+#endif
+      }
+      ~JNIEnvWrapper() {
+#if !defined(SWIG_JAVA_NO_DETACH_CURRENT_THREAD)
+        // Some JVMs, eg jdk-1.4.2 and lower on Solaris have a bug and crash with the DetachCurrentThread call.
+        // However, without this call, the JVM hangs on exit when the thread was not created by the JVM and creates a memory leak.
+        director_->swig_jvm_->DetachCurrentThread();
+#endif
+      }
+      JNIEnv *getJNIEnv() const {
+        return jenv_;
+      }
+    };
+
+    /* Java object wrapper */
+    JObjectWrapper swig_self_;
+
+    /* Disconnect director from Java object */
+    void swig_disconnect_director_self(const char *disconn_method) {
+      JNIEnvWrapper jnienv(this) ;
+      JNIEnv *jenv = jnienv.getJNIEnv() ;
+      jobject jobj = swig_self_.peek();
+#if defined(DEBUG_DIRECTOR_OWNED)
+      std::cout << "Swig::Director::disconnect_director_self(" << jobj << ")" << std::endl;
+#endif
+      if (jobj && jenv->IsSameObject(jobj, NULL) == JNI_FALSE) {
+        jmethodID disconn_meth = jenv->GetMethodID(jenv->GetObjectClass(jobj), disconn_method, "()V");
+        if (disconn_meth) {
+#if defined(DEBUG_DIRECTOR_OWNED)
+          std::cout << "Swig::Director::disconnect_director_self upcall to " << disconn_method << std::endl;
+#endif
+          jenv->CallVoidMethod(jobj, disconn_meth);
+        }
+      }
+    }
+
+  public:
+    Director(JNIEnv *jenv) : swig_jvm_((JavaVM *) NULL), swig_self_() {
+      /* Acquire the Java VM pointer */
+      jenv->GetJavaVM(&swig_jvm_);
+    }
+
+    virtual ~Director() {
+      JNIEnvWrapper jnienv(this) ;
+      JNIEnv *jenv = jnienv.getJNIEnv() ;
+      swig_self_.release(jenv);
+    }
+
+    bool swig_set_self(JNIEnv *jenv, jobject jself, bool mem_own, bool weak_global) {
+      return swig_self_.set(jenv, jself, mem_own, weak_global);
+    }
+
+    jobject swig_get_self(JNIEnv *jenv) const {
+      return swig_self_.get(jenv);
+    }
+
+    // Change C++ object's ownership, relative to Java
+    void swig_java_change_ownership(JNIEnv *jenv, jobject jself, bool take_or_release) {
+      swig_self_.java_change_ownership(jenv, jself, take_or_release);
+    }
+  };
+}
+
+#endif /* __cplusplus */
+
+
diff --git a/trunk/Lib/java/enums.swg b/trunk/Lib/java/enums.swg
new file mode 100644
index 0000000..1a8f89b
--- /dev/null
+++ b/trunk/Lib/java/enums.swg
@@ -0,0 +1,120 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enums.swg
+ *
+ * Include this file in order for C/C++ enums to be wrapped by proper Java enums.
+ * Note that the JNI layer handles the enum as an int. The Java enum has extra
+ * code generated to store the C++ int value. This is required for C++ enums that
+ * specify a value for the enum item, as native Java enums do not support this.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(jni) const enum SWIGTYPE & "jint"
+%typemap(jtype) const enum SWIGTYPE & "int"
+%typemap(jstype) const enum SWIGTYPE & "$*javaclassname"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE &  %{ $result = (jint)*$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin, descriptor="L$packagepath/$*javaclassname;") const enum SWIGTYPE &    "$input = (jint)$1_name;"
+%typemap(javadirectorin) const enum SWIGTYPE & "$*javaclassname.swigToEnum($jniinput)"
+%typemap(javadirectorout) const enum SWIGTYPE & "($javacall).swigValue()"
+
+%typecheck(SWIG_TYPECHECK_POINTER) const enum SWIGTYPE & ""
+
+%typemap(throws) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) const enum SWIGTYPE & "$javainput.swigValue()"
+%typemap(javaout) const enum SWIGTYPE & {
+    return $*javaclassname.swigToEnum($jnicall);
+  }
+
+
+// enum SWIGTYPE typemaps
+%typemap(jni) enum SWIGTYPE "jint"
+%typemap(jtype) enum SWIGTYPE "int"
+%typemap(jstype) enum SWIGTYPE "$javaclassname"
+
+%typemap(in) enum SWIGTYPE  %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE  %{ $result = (jint)$1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin, descriptor="L$packagepath/$javaclassname;") enum SWIGTYPE    "$input = (jint) $1;"
+%typemap(javadirectorin) enum SWIGTYPE "$javaclassname.swigToEnum($jniinput)"
+%typemap(javadirectorout) enum SWIGTYPE "($javacall).swigValue()"
+
+%typecheck(SWIG_TYPECHECK_POINTER) enum SWIGTYPE ""
+
+%typemap(throws) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) enum SWIGTYPE "$javainput.swigValue()"
+%typemap(javaout) enum SWIGTYPE {
+    return $javaclassname.swigToEnum($jnicall);
+  }
+
+%typemap(javaclassmodifiers) enum SWIGTYPE "public enum"
+%typemap(javabase)           enum SWIGTYPE ""
+%typemap(javacode)           enum SWIGTYPE ""
+%typemap(javaimports)        enum SWIGTYPE ""
+%typemap(javainterfaces)     enum SWIGTYPE ""
+%typemap(javabody)           enum SWIGTYPE ""
+
+/*
+ * SwigNext static inner class used instead of a static int as static fields cannot be accessed from enum initialisers.
+ * The swigToEnum method is used to find the Java enum from a C++ enum integer value. The default one here takes 
+ * advantage of the fact that most enums do not have initial values specified, so the lookup is fast. If initial
+ * values are specified then a lengthy linear search through all possible enums might occur. Specific typemaps could be
+ * written to possibly optimise this lookup by taking advantage of characteristics peculiar to the targeted enum.
+ */
+%typemap(javabody) enum SWIGTYPE %{
+  public final int swigValue() {
+    return swigValue;
+  }
+
+  public static $javaclassname swigToEnum(int swigValue) {
+    $javaclassname[] swigValues = $javaclassname.class.getEnumConstants();
+    if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
+      return swigValues[swigValue];
+    for ($javaclassname swigEnum : swigValues)
+      if (swigEnum.swigValue == swigValue)
+        return swigEnum;
+    throw new IllegalArgumentException("No enum " + $javaclassname.class + " with value " + swigValue);
+  }
+
+  @SuppressWarnings("unused")
+  private $javaclassname() {
+    this.swigValue = SwigNext.next++;
+  }
+
+  @SuppressWarnings("unused")
+  private $javaclassname(int swigValue) {
+    this.swigValue = swigValue;
+    SwigNext.next = swigValue+1;
+  }
+
+  @SuppressWarnings("unused")
+  private $javaclassname($javaclassname swigEnum) {
+    this.swigValue = swigEnum.swigValue;
+    SwigNext.next = this.swigValue+1;
+  }
+
+  private final int swigValue;
+
+  private static class SwigNext {
+    private static int next = 0;
+  }
+%}
+
+%javaenum(proper);
+
diff --git a/trunk/Lib/java/enumsimple.swg b/trunk/Lib/java/enumsimple.swg
new file mode 100644
index 0000000..f45774d
--- /dev/null
+++ b/trunk/Lib/java/enumsimple.swg
@@ -0,0 +1,74 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enumsimple.swg
+ *
+ * This file provides backwards compatible enum wrapping. SWIG versions 1.3.21
+ * and earlier wrapped global enums with constant integers in the module class
+ * or Constants interface. Enums declared within a C++ class were wrapped by
+ * constant integers in the Java proxy class.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(jni) const enum SWIGTYPE & "jint"
+%typemap(jtype) const enum SWIGTYPE & "int"
+%typemap(jstype) const enum SWIGTYPE & "int"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE &  %{ $result = (jint)*$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin, descriptor="I") const enum SWIGTYPE &    "$input = (jint)$1_name;"
+%typemap(javadirectorin) const enum SWIGTYPE & "$jniinput"
+%typemap(javadirectorout) const enum SWIGTYPE & "$javacall"
+
+%typecheck(SWIG_TYPECHECK_INT32) const enum SWIGTYPE & ""
+
+%typemap(throws) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) const enum SWIGTYPE & "$javainput"
+%typemap(javaout) const enum SWIGTYPE & {
+    return $jnicall;
+  }
+
+
+// enum SWIGTYPE typemaps
+%typemap(jni) enum SWIGTYPE "jint"
+%typemap(jtype) enum SWIGTYPE "int"
+%typemap(jstype) enum SWIGTYPE "int"
+
+%typemap(in) enum SWIGTYPE  %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE  %{ $result = (jint)$1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin, descriptor="I") enum SWIGTYPE    "$input = (jint) $1;"
+%typemap(javadirectorin) enum SWIGTYPE "$jniinput"
+%typemap(javadirectorout) enum SWIGTYPE "$javacall"
+
+%typecheck(SWIG_TYPECHECK_INT32) enum SWIGTYPE ""
+
+%typemap(throws) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) enum SWIGTYPE "$javainput"
+%typemap(javaout) enum SWIGTYPE {
+    return $jnicall;
+  }
+
+%typemap(javaclassmodifiers) enum SWIGTYPE ""
+%typemap(javabase)           enum SWIGTYPE ""
+%typemap(javacode)           enum SWIGTYPE ""
+%typemap(javaimports)        enum SWIGTYPE ""
+%typemap(javainterfaces)     enum SWIGTYPE ""
+%typemap(javabody)           enum SWIGTYPE ""
+
+%javaenum(simple);
+
diff --git a/trunk/Lib/java/enumtypesafe.swg b/trunk/Lib/java/enumtypesafe.swg
new file mode 100644
index 0000000..a49a9d1
--- /dev/null
+++ b/trunk/Lib/java/enumtypesafe.swg
@@ -0,0 +1,121 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enumtypesafe.swg
+ *
+ * Include this file in order for C/C++ enums to be wrapped by the so called
+ * typesafe enum pattern. Each enum has an equivalent Java class named after the
+ * enum and each enum item is a static instance of this class.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(jni) const enum SWIGTYPE & "jint"
+%typemap(jtype) const enum SWIGTYPE & "int"
+%typemap(jstype) const enum SWIGTYPE & "$*javaclassname"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE &  %{ $result = (jint)*$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin, descriptor="L$packagepath/$*javaclassname;") const enum SWIGTYPE &    "$input = (jint)$1_name;"
+%typemap(javadirectorin) const enum SWIGTYPE & "$*javaclassname.swigToEnum($jniinput)"
+%typemap(javadirectorout) const enum SWIGTYPE & "($javacall).swigValue()"
+
+%typecheck(SWIG_TYPECHECK_POINTER) const enum SWIGTYPE & ""
+
+%typemap(throws) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) const enum SWIGTYPE & "$javainput.swigValue()"
+%typemap(javaout) const enum SWIGTYPE & {
+    return $*javaclassname.swigToEnum($jnicall);
+  }
+
+// enum SWIGTYPE typemaps
+%typemap(jni) enum SWIGTYPE "jint"
+%typemap(jtype) enum SWIGTYPE "int"
+%typemap(jstype) enum SWIGTYPE "$javaclassname"
+
+%typemap(in) enum SWIGTYPE  %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE  %{ $result = (jint)$1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin, descriptor="L$packagepath/$javaclassname;") enum SWIGTYPE    "$input = (jint) $1;"
+%typemap(javadirectorin) enum SWIGTYPE "$javaclassname.swigToEnum($jniinput)"
+%typemap(javadirectorout) enum SWIGTYPE "($javacall).swigValue()"
+
+%typecheck(SWIG_TYPECHECK_POINTER) enum SWIGTYPE ""
+
+%typemap(throws) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) enum SWIGTYPE "$javainput.swigValue()"
+%typemap(javaout) enum SWIGTYPE {
+    return $javaclassname.swigToEnum($jnicall);
+  }
+
+// '$static' will be replaced with either 'static' or nothing depending on whether the enum is an inner Java class or not
+%typemap(javaclassmodifiers) enum SWIGTYPE "public final $static class"
+%typemap(javabase)           enum SWIGTYPE ""
+%typemap(javacode)           enum SWIGTYPE ""
+%typemap(javaimports)        enum SWIGTYPE ""
+%typemap(javainterfaces)     enum SWIGTYPE ""
+%typemap(javabody)           enum SWIGTYPE ""
+
+/*
+ * The swigToEnum method is used to find the Java enum from a C++ enum integer value. The default one here takes 
+ * advantage of the fact that most enums do not have initial values specified, so the lookup is fast. If initial
+ * values are specified then a lengthy linear search through all possible enums might occur. Specific typemaps could be
+ * written to possibly optimise this lookup by taking advantage of characteristics peculiar to the targeted enum.
+ * The special variable, $enumvalues, is replaced with a comma separated list of all the enum values.
+ */
+%typemap(javabody) enum SWIGTYPE %{
+  public final int swigValue() {
+    return swigValue;
+  }
+
+  public String toString() {
+    return swigName;
+  }
+
+  public static $javaclassname swigToEnum(int swigValue) {
+    if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
+      return swigValues[swigValue];
+    for (int i = 0; i < swigValues.length; i++)
+      if (swigValues[i].swigValue == swigValue)
+        return swigValues[i];
+    throw new IllegalArgumentException("No enum " + $javaclassname.class + " with value " + swigValue);
+  }
+
+  private $javaclassname(String swigName) {
+    this.swigName = swigName;
+    this.swigValue = swigNext++;
+  }
+
+  private $javaclassname(String swigName, int swigValue) {
+    this.swigName = swigName;
+    this.swigValue = swigValue;
+    swigNext = swigValue+1;
+  }
+
+  private $javaclassname(String swigName, $javaclassname swigEnum) {
+    this.swigName = swigName;
+    this.swigValue = swigEnum.swigValue;
+    swigNext = this.swigValue+1;
+  }
+
+  private static $javaclassname[] swigValues = { $enumvalues };
+  private static int swigNext = 0;
+  private final int swigValue;
+  private final String swigName;
+%}
+
+%javaenum(typesafe);
+
diff --git a/trunk/Lib/java/enumtypeunsafe.swg b/trunk/Lib/java/enumtypeunsafe.swg
new file mode 100644
index 0000000..bda0551
--- /dev/null
+++ b/trunk/Lib/java/enumtypeunsafe.swg
@@ -0,0 +1,75 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * enumtypeunsafe.swg
+ *
+ * Include this file in order for C/C++ enums to be wrapped by integers values.
+ * Each enum has an equivalent class named after the enum and the enum items are
+ * wrapped by constant integers within this class. The enum items are not
+ * typesafe as they are all integers.
+ * ----------------------------------------------------------------------------- */
+
+// const enum SWIGTYPE & typemaps
+%typemap(jni) const enum SWIGTYPE & "jint"
+%typemap(jtype) const enum SWIGTYPE & "int"
+%typemap(jstype) const enum SWIGTYPE & "int"
+
+%typemap(in) const enum SWIGTYPE & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+%typemap(out) const enum SWIGTYPE &  %{ $result = (jint)*$1; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const enum SWIGTYPE &
+%{ static $*1_ltype temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+%typemap(directorin, descriptor="I") const enum SWIGTYPE &    "$input = (jint)$1_name;"
+%typemap(javadirectorin) const enum SWIGTYPE & "$jniinput"
+%typemap(javadirectorout) const enum SWIGTYPE & "$javacall"
+
+%typecheck(SWIG_TYPECHECK_INT32) const enum SWIGTYPE & ""
+
+%typemap(throws) const enum SWIGTYPE &
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) const enum SWIGTYPE & "$javainput"
+%typemap(javaout) const enum SWIGTYPE & {
+    return $jnicall;
+  }
+
+
+// enum SWIGTYPE typemaps
+%typemap(jni) enum SWIGTYPE "jint"
+%typemap(jtype) enum SWIGTYPE "int"
+%typemap(jstype) enum SWIGTYPE "int"
+
+%typemap(in) enum SWIGTYPE  %{ $1 = ($1_ltype)$input; %}
+%typemap(out) enum SWIGTYPE  %{ $result = (jint)$1; %}
+
+%typemap(directorout) enum SWIGTYPE  %{ $result = ($1_ltype)$input; %}
+%typemap(directorin, descriptor="I") enum SWIGTYPE    "$input = (jint) $1;"
+%typemap(javadirectorin) enum SWIGTYPE "$jniinput"
+%typemap(javadirectorout) enum SWIGTYPE "$javacall"
+
+%typecheck(SWIG_TYPECHECK_INT32) enum SWIGTYPE ""
+
+%typemap(throws) enum SWIGTYPE
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); %}
+
+%typemap(javain) enum SWIGTYPE "$javainput"
+%typemap(javaout) enum SWIGTYPE {
+    return $jnicall;
+  }
+
+// '$static' will be replaced with either 'static' or nothing depending on whether the enum is an inner Java class or not
+%typemap(javaclassmodifiers) enum SWIGTYPE "public final $static class"
+%typemap(javabase)           enum SWIGTYPE ""
+%typemap(javacode)           enum SWIGTYPE ""
+%typemap(javaimports)        enum SWIGTYPE ""
+%typemap(javainterfaces)     enum SWIGTYPE ""
+%typemap(javabody)           enum SWIGTYPE ""
+
+%javaenum(typeunsafe);
+
diff --git a/trunk/Lib/java/java.swg b/trunk/Lib/java/java.swg
new file mode 100644
index 0000000..b7c5607
--- /dev/null
+++ b/trunk/Lib/java/java.swg
@@ -0,0 +1,1208 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * java.swg
+ *
+ * Java typemaps
+ * ----------------------------------------------------------------------------- */
+
+%include <javahead.swg>
+
+/* The jni, jtype and jstype typemaps work together and so there should be one of each. 
+ * The jni typemap contains the JNI type used in the JNI (C/C++) code. 
+ * The jtype typemap contains the Java type used in the JNI intermediary class. 
+ * The jstype typemap contains the Java type used in the Java proxy classes, type wrapper classes and module class. */
+
+/* Primitive types */
+%typemap(jni) bool,               const bool &               "jboolean"
+%typemap(jni) char,               const char &               "jchar"
+%typemap(jni) signed char,        const signed char &        "jbyte"
+%typemap(jni) unsigned char,      const unsigned char &      "jshort"
+%typemap(jni) short,              const short &              "jshort"
+%typemap(jni) unsigned short,     const unsigned short &     "jint"
+%typemap(jni) int,                const int &                "jint"
+%typemap(jni) unsigned int,       const unsigned int &       "jlong"
+%typemap(jni) long,               const long &               "jint"
+%typemap(jni) unsigned long,      const unsigned long &      "jlong"
+%typemap(jni) long long,          const long long &          "jlong"
+%typemap(jni) unsigned long long, const unsigned long long & "jobject"
+%typemap(jni) float,              const float &              "jfloat"
+%typemap(jni) double,             const double &             "jdouble"
+%typemap(jni) void                                           "void"
+
+%typemap(jtype) bool,               const bool &               "boolean"
+%typemap(jtype) char,               const char &               "char"
+%typemap(jtype) signed char,        const signed char &        "byte"
+%typemap(jtype) unsigned char,      const unsigned char &      "short"
+%typemap(jtype) short,              const short &              "short"
+%typemap(jtype) unsigned short,     const unsigned short &     "int"
+%typemap(jtype) int,                const int &                "int"
+%typemap(jtype) unsigned int,       const unsigned int &       "long"
+%typemap(jtype) long,               const long &               "int"
+%typemap(jtype) unsigned long,      const unsigned long &      "long"
+%typemap(jtype) long long,          const long long &          "long"
+%typemap(jtype) unsigned long long, const unsigned long long & "java.math.BigInteger"
+%typemap(jtype) float,              const float &              "float"
+%typemap(jtype) double,             const double &             "double"
+%typemap(jtype) void                                           "void"
+
+%typemap(jstype) bool,               const bool &               "boolean"
+%typemap(jstype) char,               const char &               "char"
+%typemap(jstype) signed char,        const signed char &        "byte"
+%typemap(jstype) unsigned char,      const unsigned char &      "short"
+%typemap(jstype) short,              const short &              "short"
+%typemap(jstype) unsigned short,     const unsigned short &     "int"
+%typemap(jstype) int,                const int &                "int"
+%typemap(jstype) unsigned int,       const unsigned int &       "long"
+%typemap(jstype) long,               const long &               "int"
+%typemap(jstype) unsigned long,      const unsigned long &      "long"
+%typemap(jstype) long long,          const long long &          "long"
+%typemap(jstype) unsigned long long, const unsigned long long & "java.math.BigInteger"
+%typemap(jstype) float,              const float &              "float"
+%typemap(jstype) double,             const double &             "double"
+%typemap(jstype) void                                           "void"
+
+%typemap(jni) char *, char *&, char[ANY], char[]               "jstring"
+%typemap(jtype) char *, char *&, char[ANY], char[]               "String"
+%typemap(jstype) char *, char *&, char[ANY], char[]               "String"
+
+/* JNI types */
+%typemap(jni) jboolean      "jboolean"
+%typemap(jni) jchar         "jchar"
+%typemap(jni) jbyte         "jbyte"
+%typemap(jni) jshort        "jshort"
+%typemap(jni) jint          "jint"
+%typemap(jni) jlong         "jlong"
+%typemap(jni) jfloat        "jfloat"
+%typemap(jni) jdouble       "jdouble"
+%typemap(jni) jstring       "jstring"
+%typemap(jni) jobject       "jobject"
+%typemap(jni) jbooleanArray "jbooleanArray"
+%typemap(jni) jcharArray    "jcharArray"
+%typemap(jni) jbyteArray    "jbyteArray"
+%typemap(jni) jshortArray   "jshortArray"
+%typemap(jni) jintArray     "jintArray"
+%typemap(jni) jlongArray    "jlongArray"
+%typemap(jni) jfloatArray   "jfloatArray"
+%typemap(jni) jdoubleArray  "jdoubleArray"
+%typemap(jni) jobjectArray  "jobjectArray"
+
+%typemap(jtype) jboolean      "boolean"
+%typemap(jtype) jchar         "char"
+%typemap(jtype) jbyte         "byte"
+%typemap(jtype) jshort        "short"
+%typemap(jtype) jint          "int"
+%typemap(jtype) jlong         "long"
+%typemap(jtype) jfloat        "float"
+%typemap(jtype) jdouble       "double"
+%typemap(jtype) jstring       "String"
+%typemap(jtype) jobject       "Object"
+%typemap(jtype) jbooleanArray "boolean[]"
+%typemap(jtype) jcharArray    "char[]"
+%typemap(jtype) jbyteArray    "byte[]"
+%typemap(jtype) jshortArray   "short[]"
+%typemap(jtype) jintArray     "int[]"
+%typemap(jtype) jlongArray    "long[]"
+%typemap(jtype) jfloatArray   "float[]"
+%typemap(jtype) jdoubleArray  "double[]"
+%typemap(jtype) jobjectArray  "Object[]"
+
+%typemap(jstype) jboolean      "boolean"
+%typemap(jstype) jchar         "char"
+%typemap(jstype) jbyte         "byte"
+%typemap(jstype) jshort        "short"
+%typemap(jstype) jint          "int"
+%typemap(jstype) jlong         "long"
+%typemap(jstype) jfloat        "float"
+%typemap(jstype) jdouble       "double"
+%typemap(jstype) jstring       "String"
+%typemap(jstype) jobject       "Object"
+%typemap(jstype) jbooleanArray "boolean[]"
+%typemap(jstype) jcharArray    "char[]"
+%typemap(jstype) jbyteArray    "byte[]"
+%typemap(jstype) jshortArray   "short[]"
+%typemap(jstype) jintArray     "int[]"
+%typemap(jstype) jlongArray    "long[]"
+%typemap(jstype) jfloatArray   "float[]"
+%typemap(jstype) jdoubleArray  "double[]"
+%typemap(jstype) jobjectArray  "Object[]"
+
+/* Non primitive types */
+%typemap(jni) SWIGTYPE "jlong"
+%typemap(jtype) SWIGTYPE "long"
+%typemap(jstype) SWIGTYPE "$&javaclassname"
+
+%typemap(jni) SWIGTYPE [] "jlong"
+%typemap(jtype) SWIGTYPE [] "long"
+%typemap(jstype) SWIGTYPE [] "$javaclassname"
+
+%typemap(jni) SWIGTYPE * "jlong"
+%typemap(jtype) SWIGTYPE * "long"
+%typemap(jstype) SWIGTYPE * "$javaclassname"
+
+%typemap(jni) SWIGTYPE & "jlong"
+%typemap(jtype) SWIGTYPE & "long"
+%typemap(jstype) SWIGTYPE & "$javaclassname"
+
+/* pointer to a class member */
+%typemap(jni) SWIGTYPE (CLASS::*) "jlong"
+%typemap(jtype) SWIGTYPE (CLASS::*) "long"
+%typemap(jstype) SWIGTYPE (CLASS::*) "$javaclassname"
+
+/* The following are the in, out, freearg, argout typemaps. These are the JNI code generating typemaps for converting from Java to C and visa versa. */
+
+/* primitive types */
+%typemap(in) bool
+%{ $1 = $input ? true : false; %}
+
+%typemap(directorout) bool
+%{ $result = $input ? true : false; %}
+
+%typemap(javadirectorin) bool "$jniinput"
+%typemap(javadirectorout) bool "$javacall"
+
+%typemap(in) char, 
+             signed char, 
+             unsigned char, 
+             short, 
+             unsigned short, 
+             int, 
+             unsigned int, 
+             long, 
+             unsigned long, 
+             long long, 
+             float, 
+             double
+%{ $1 = ($1_ltype)$input; %}
+
+%typemap(directorout) char, 
+             signed char, 
+             unsigned char, 
+             short, 
+             unsigned short, 
+             int, 
+             unsigned int, 
+             long, 
+             unsigned long, 
+             long long, 
+             float, 
+             double
+%{ $result = ($1_ltype)$input; %}
+
+%typemap(directorin, descriptor="Z") bool             "$input = (jboolean) $1;"
+%typemap(directorin, descriptor="C") char             "$input = (jint) $1;"
+%typemap(directorin, descriptor="B") signed char      "$input = (jbyte) $1;"
+%typemap(directorin, descriptor="S") unsigned char    "$input = (jshort) $1;"
+%typemap(directorin, descriptor="S") short            "$input = (jshort) $1;"
+%typemap(directorin, descriptor="I") unsigned short   "$input = (jint) $1;"
+%typemap(directorin, descriptor="I") int              "$input = (jint) $1;"
+%typemap(directorin, descriptor="J") unsigned int     "$input = (jlong) $1;"
+%typemap(directorin, descriptor="I") long             "$input = (jint) $1;"
+%typemap(directorin, descriptor="J") unsigned long    "$input = (jlong) $1;"
+%typemap(directorin, descriptor="J") long long        "$input = (jlong) $1;"
+%typemap(directorin, descriptor="F") float            "$input = (jfloat) $1;"
+%typemap(directorin, descriptor="D") double           "$input = (jdouble) $1;"
+
+%typemap(javadirectorin) char, 
+                         signed char, 
+                         unsigned char, 
+                         short, 
+                         unsigned short, 
+                         int, 
+                         unsigned int, 
+                         long, 
+                         unsigned long, 
+                         long long, 
+                         float, 
+                         double
+  "$jniinput"
+
+%typemap(javadirectorout) char, 
+                          signed char, 
+                          unsigned char, 
+                          short, 
+                          unsigned short, 
+                          int, 
+                          unsigned int, 
+                          long, 
+                          unsigned long, 
+                          long long, 
+                          float, 
+                          double
+  "$javacall"
+
+%typemap(out) bool           %{ $result = (jboolean)$1; %}
+%typemap(out) char           %{ $result = (jchar)$1; %}
+%typemap(out) signed char    %{ $result = (jbyte)$1; %}
+%typemap(out) unsigned char  %{ $result = (jshort)$1; %}
+%typemap(out) short          %{ $result = (jshort)$1; %}
+%typemap(out) unsigned short %{ $result = (jint)$1; %}
+%typemap(out) int            %{ $result = (jint)$1; %}
+%typemap(out) unsigned int   %{ $result = (jlong)$1; %}
+%typemap(out) long           %{ $result = (jint)$1; %}
+%typemap(out) unsigned long  %{ $result = (jlong)$1; %}
+%typemap(out) long long      %{ $result = (jlong)$1; %}
+%typemap(out) float          %{ $result = (jfloat)$1; %}
+%typemap(out) double         %{ $result = (jdouble)$1; %}
+
+/* unsigned long long */
+/* Convert from BigInteger using the toByteArray member function */
+%typemap(in) unsigned long long { 
+  jclass clazz;
+  jmethodID mid;
+  jbyteArray ba;
+  jbyte* bae;
+  jsize sz;
+  int i;
+
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+    return $null;
+  }
+  clazz = JCALL1(GetObjectClass, jenv, $input);
+  mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+  ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+  bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  sz = JCALL1(GetArrayLength, jenv, ba);
+  $1 = 0;
+  for(i=0; i<sz; i++) {
+    $1 = ($1 << 8) | ($1_type)(unsigned char)bae[i];
+  }
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+%typemap(directorout) unsigned long long { 
+  jclass clazz;
+  jmethodID mid;
+  jbyteArray ba;
+  jbyte* bae;
+  jsize sz;
+  int i;
+
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+    return $null;
+  }
+  clazz = JCALL1(GetObjectClass, jenv, $input);
+  mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+  ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+  bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  sz = JCALL1(GetArrayLength, jenv, ba);
+  $result = 0;
+  for(i=0; i<sz; i++) {
+    $result = ($result << 8) | ($1_type)(unsigned char)bae[i];
+  }
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+
+/* Convert to BigInteger - byte array holds number in 2's complement big endian format */
+%typemap(out) unsigned long long { 
+  jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+  jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+  jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+  jobject bigint;
+  int i;
+
+  bae[0] = 0;
+  for(i=1; i<9; i++ ) {
+    bae[i] = (jbyte)($1>>8*(8-i));
+  }
+
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+  bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+  $result = bigint;
+}
+
+/* Convert to BigInteger (see out typemap) */
+%typemap(directorin, descriptor="Ljava/math/BigInteger;") unsigned long long, const unsigned long long & {
+  jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+  jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+  jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+  jobject bigint;
+  int swig_i;
+
+  bae[0] = 0;
+  for(swig_i=1; swig_i<9; swig_i++ ) {
+    bae[swig_i] = (jbyte)($1>>8*(8-swig_i));
+  }
+
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+  bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+  $input = bigint;
+}
+
+%typemap(javadirectorin) unsigned long long "$jniinput"
+%typemap(javadirectorout) unsigned long long "$javacall"
+
+/* char * - treat as String */
+%typemap(in, noblock=1) char * {
+ $1 = 0;
+  if ($input) {
+    $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+    if (!$1) return $null;
+  }
+}
+
+%typemap(directorout, noblock=1, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) char * {
+  $1 = 0;
+  if ($input) {
+    $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+    if (!$result) return $null;
+  }
+}
+
+%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * {
+ $input = 0;
+  if ($1) {
+    $input = JCALL1(NewStringUTF, jenv, (const char *)$1);
+    if (!$input) return $null;
+  }
+}
+
+%typemap(freearg, noblock=1) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); }
+%typemap(out, noblock=1) char * { if($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); }
+%typemap(javadirectorin) char * "$jniinput"
+%typemap(javadirectorout) char * "$javacall"
+
+/* char *& - treat as String */
+%typemap(in, noblock=1) char *& ($*1_ltype temp = 0) {
+ $1 = 0;
+  if ($input) {
+    temp = ($*1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+    if (!temp) return $null;
+  }
+  $1 = &temp;
+}
+%typemap(freearg, noblock=1) char *& { if ($1 && *$1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)*$1); }
+%typemap(out, noblock=1) char *& { if(*$1) $result = JCALL1(NewStringUTF, jenv, (const char *)*$1); }
+
+%typemap(out) void ""
+%typemap(javadirectorin) void "$jniinput"
+%typemap(javadirectorout) void "$javacall"
+%typemap(directorin, descriptor="V") void ""
+
+/* primitive types by reference */
+%typemap(in) const bool & ($*1_ltype temp)
+%{ temp = $input ? true : false; 
+   $1 = &temp; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const bool &
+%{ static $*1_ltype temp;
+   temp = $input ? true : false; 
+   $result = &temp; %}
+
+%typemap(javadirectorin) const bool & "$jniinput"
+%typemap(javadirectorout) const bool & "$javacall"
+
+%typemap(in) const char & ($*1_ltype temp), 
+             const signed char & ($*1_ltype temp), 
+             const unsigned char & ($*1_ltype temp), 
+             const short & ($*1_ltype temp), 
+             const unsigned short & ($*1_ltype temp), 
+             const int & ($*1_ltype temp), 
+             const unsigned int & ($*1_ltype temp), 
+             const long & ($*1_ltype temp), 
+             const unsigned long & ($*1_ltype temp), 
+             const long long & ($*1_ltype temp), 
+             const float & ($*1_ltype temp), 
+             const double & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input; 
+   $1 = &temp; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const char &,
+             const signed char &,
+             const unsigned char &,
+             const short &,
+             const unsigned short &,
+             const int &,
+             const unsigned int &,
+             const long &,
+             const unsigned long &,
+             const long long &,
+             const float &,
+             const double &
+%{ static $*1_ltype temp;
+   temp = ($*1_ltype)$input; 
+   $result = &temp; %}
+
+%typemap(directorin, descriptor="Z") const bool &           "$input = (jboolean)$1_name;"
+%typemap(directorin, descriptor="C") const char &           "$input = (jchar)$1_name;"
+%typemap(directorin, descriptor="B") const signed char &    "$input = (jbyte)$1_name;"
+%typemap(directorin, descriptor="S") const unsigned char &  "$input = (jshort)$1_name;"
+%typemap(directorin, descriptor="S") const short &          "$input = (jshort)$1_name;"
+%typemap(directorin, descriptor="I") const unsigned short & "$input = (jint)$1_name;"
+%typemap(directorin, descriptor="I") const int &            "$input = (jint)$1_name;"
+%typemap(directorin, descriptor="J") const unsigned int &   "$input = (jlong)$1_name;"
+%typemap(directorin, descriptor="I") const long &           "$input = (jint)$1_name;"
+%typemap(directorin, descriptor="J") const unsigned long &  "$input = (jlong)$1_name;"
+%typemap(directorin, descriptor="J") const long long &      "$input = (jlong)$1_name;"
+%typemap(directorin, descriptor="F") const float &          "$input = (jfloat)$1_name;"
+%typemap(directorin, descriptor="D") const double &         "$input = (jdouble)$1_name;"
+
+%typemap(javadirectorin) const char & ($*1_ltype temp), 
+                         const signed char & ($*1_ltype temp), 
+                         const unsigned char & ($*1_ltype temp), 
+                         const short & ($*1_ltype temp), 
+                         const unsigned short & ($*1_ltype temp), 
+                         const int & ($*1_ltype temp), 
+                         const unsigned int & ($*1_ltype temp), 
+                         const long & ($*1_ltype temp), 
+                         const unsigned long & ($*1_ltype temp), 
+                         const long long & ($*1_ltype temp), 
+                         const float & ($*1_ltype temp), 
+                         const double & ($*1_ltype temp)
+  "$jniinput"
+
+%typemap(javadirectorout) const char & ($*1_ltype temp), 
+                          const signed char & ($*1_ltype temp), 
+                          const unsigned char & ($*1_ltype temp), 
+                          const short & ($*1_ltype temp), 
+                          const unsigned short & ($*1_ltype temp), 
+                          const int & ($*1_ltype temp), 
+                          const unsigned int & ($*1_ltype temp), 
+                          const long & ($*1_ltype temp), 
+                          const unsigned long & ($*1_ltype temp), 
+                          const long long & ($*1_ltype temp), 
+                          const float & ($*1_ltype temp), 
+                          const double & ($*1_ltype temp)
+  "$javacall"
+
+
+%typemap(out) const bool &           %{ $result = (jboolean)*$1; %}
+%typemap(out) const char &           %{ $result = (jchar)*$1; %}
+%typemap(out) const signed char &    %{ $result = (jbyte)*$1; %}
+%typemap(out) const unsigned char &  %{ $result = (jshort)*$1; %}
+%typemap(out) const short &          %{ $result = (jshort)*$1; %}
+%typemap(out) const unsigned short & %{ $result = (jint)*$1; %}
+%typemap(out) const int &            %{ $result = (jint)*$1; %}
+%typemap(out) const unsigned int &   %{ $result = (jlong)*$1; %}
+%typemap(out) const long &           %{ $result = (jint)*$1; %}
+%typemap(out) const unsigned long &  %{ $result = (jlong)*$1; %}
+%typemap(out) const long long &      %{ $result = (jlong)*$1; %}
+%typemap(out) const float &          %{ $result = (jfloat)*$1; %}
+%typemap(out) const double &         %{ $result = (jdouble)*$1; %}
+
+/* const unsigned long long & */
+/* Similar to unsigned long long */
+%typemap(in) const unsigned long long & ($*1_ltype temp) { 
+  jclass clazz;
+  jmethodID mid;
+  jbyteArray ba;
+  jbyte* bae;
+  jsize sz;
+  int i;
+
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+    return $null;
+  }
+  clazz = JCALL1(GetObjectClass, jenv, $input);
+  mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+  ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+  bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  sz = JCALL1(GetArrayLength, jenv, ba);
+  $1 = &temp;
+  temp = 0;
+  for(i=0; i<sz; i++) {
+    temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i];
+  }
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const unsigned long long & { 
+  static $*1_ltype temp;
+  jclass clazz;
+  jmethodID mid;
+  jbyteArray ba;
+  jbyte* bae;
+  jsize sz;
+  int i;
+
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+    return $null;
+  }
+  clazz = JCALL1(GetObjectClass, jenv, $input);
+  mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+  ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+  bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  sz = JCALL1(GetArrayLength, jenv, ba);
+  $result = &temp;
+  temp = 0;
+  for(i=0; i<sz; i++) {
+    temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i];
+  }
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+%typemap(out) const unsigned long long & { 
+  jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+  jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+  jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+  jobject bigint;
+  int i;
+
+  bae[0] = 0;
+  for(i=1; i<9; i++ ) {
+    bae[i] = (jbyte)(*$1>>8*(8-i));
+  }
+
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+  bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+  $result = bigint;
+}
+
+%typemap(javadirectorin) const unsigned long long & "$jniinput"
+%typemap(javadirectorout) const unsigned long long & "$javacall"
+
+/* Default handling. Object passed by value. Convert to a pointer */
+%typemap(in) SWIGTYPE ($&1_type argp)
+%{ argp = *($&1_ltype*)&$input; 
+   if (!argp) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type");
+     return $null;
+   }
+   $1 = *argp; %}
+
+%typemap(directorout) SWIGTYPE ($&1_type argp)
+%{ argp = *($&1_ltype*)&$input; 
+   if (!argp) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type");
+     return $null;
+   }
+   $result = *argp; %}
+
+%typemap(out) SWIGTYPE 
+#ifdef __cplusplus
+%{ *($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %}
+#else
+{
+  $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype));
+  memmove($1ptr, &$1, sizeof($1_type));
+  *($&1_ltype*)&$result = $1ptr;
+}
+#endif
+
+%typemap(directorin,descriptor="L$packagepath/$&javaclassname;") SWIGTYPE 
+%{ $input = 0;
+   *(($&1_ltype*)&$input) = &$1; %}
+%typemap(javadirectorin) SWIGTYPE "new $&javaclassname($jniinput, false)"
+%typemap(javadirectorout) SWIGTYPE "$&javaclassname.getCPtr($javacall)"
+
+/* Generic pointers and references */
+%typemap(in) SWIGTYPE *, SWIGTYPE (CLASS::*) %{ $1 = *($&1_ltype)&$input; %}
+%typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input;
+  if(!$1) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null");
+    return $null;
+  } %}
+%typemap(out) SWIGTYPE *, SWIGTYPE (CLASS::*)
+%{ *($&1_ltype)&$result = $1; %} 
+%typemap(out) SWIGTYPE &
+%{ *($&1_ltype)&$result = $1; %} 
+
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE *, SWIGTYPE (CLASS::*)
+%{ $result = *($&1_ltype)&$input; %}
+%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE *, SWIGTYPE (CLASS::*)
+%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %}
+
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE &
+%{ if (!$input) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type");
+     return $null;
+   }
+   $result = *($&1_ltype)&$input; %}
+%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE &
+%{ *($&1_ltype)&$input = ($1_ltype) &$1; %}
+
+%typemap(javadirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "new $javaclassname($jniinput, false)"
+%typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$javaclassname.getCPtr($javacall)"
+
+/* Default array handling */
+%typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %}
+%typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %} 
+%typemap(freearg) SWIGTYPE [ANY], SWIGTYPE [] ""
+
+/* char arrays - treat as String */
+%typemap(in, noblock=1) char[ANY], char[] {
+  $1 = 0;
+  if ($input) {
+    $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+    if (!$1) return $null;
+  }
+}
+
+%typemap(directorout, noblock=1) char[ANY], char[] {
+  $1 = 0;
+  if ($input) {
+    $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+    if (!$result) return $null;
+  }
+}
+
+%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char[ANY], char[] {
+  $input = 0;
+  if ($1) {
+    $input = JCALL1(NewStringUTF, jenv, (const char *)$1);
+    if (!$input) return $null;
+  }
+}
+
+%typemap(argout) char[ANY], char[] ""
+%typemap(freearg, noblock=1) char[ANY], char[] { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); }
+%typemap(out, noblock=1) char[ANY], char[] { if($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); }
+%typemap(javadirectorin) char[ANY], char[] "$jniinput"
+%typemap(javadirectorout) char[ANY], char[] "$javacall"
+
+/* JNI types */
+%typemap(in) jboolean,
+             jchar,
+             jbyte,
+             jshort,
+             jint,
+             jlong,
+             jfloat,
+             jdouble,
+             jstring,
+             jobject,
+             jbooleanArray,
+             jcharArray,
+             jbyteArray,
+             jshortArray,
+             jintArray,
+             jlongArray,
+             jfloatArray,
+             jdoubleArray,
+             jobjectArray
+%{ $1 = $input; %}
+
+%typemap(directorout) jboolean,
+             jchar,
+             jbyte,
+             jshort,
+             jint,
+             jlong,
+             jfloat,
+             jdouble,
+             jstring,
+             jobject,
+             jbooleanArray,
+             jcharArray,
+             jbyteArray,
+             jshortArray,
+             jintArray,
+             jlongArray,
+             jfloatArray,
+             jdoubleArray,
+             jobjectArray
+%{ $result = $input; %}
+
+%typemap(out) jboolean,
+              jchar,
+              jbyte,
+              jshort,
+              jint,
+              jlong,
+              jfloat,
+              jdouble,
+              jstring,
+              jobject,
+              jbooleanArray,
+              jcharArray,
+              jbyteArray,
+              jshortArray,
+              jintArray,
+              jlongArray,
+              jfloatArray,
+              jdoubleArray,
+              jobjectArray
+%{ $result = $1; %}
+
+%typemap(directorin,descriptor="Z")  jboolean       "$input = $1;"
+%typemap(directorin,descriptor="C")  jchar          "$input = $1;"
+%typemap(directorin,descriptor="B")  jbyte          "$input = $1;"
+%typemap(directorin,descriptor="S")  jshort         "$input = $1;"
+%typemap(directorin,descriptor="I")  jint           "$input = $1;"
+%typemap(directorin,descriptor="J")  jlong          "$input = $1;"
+%typemap(directorin,descriptor="F")  jfloat         "$input = $1;"
+%typemap(directorin,descriptor="D")  jdouble        "$input = $1;"
+%typemap(directorin,descriptor="Ljava/lang/String;")            jstring        "$input = $1;"
+%typemap(directorin,descriptor="Ljava/lang/Object;",nouse="1")  jobject        "$input = $1;"
+%typemap(directorin,descriptor="[Z")  jbooleanArray "$input = $1;"
+%typemap(directorin,descriptor="[C")  jcharArray    "$input = $1;"
+%typemap(directorin,descriptor="[B")  jbyteArray    "$input = $1;"
+%typemap(directorin,descriptor="[S")  jshortArray   "$input = $1;"
+%typemap(directorin,descriptor="[I")  jintArray     "$input = $1;"
+%typemap(directorin,descriptor="[J")  jlongArray    "$input = $1;"
+%typemap(directorin,descriptor="[F")  jfloatArray   "$input = $1;"
+%typemap(directorin,descriptor="[D")  jdoubleArray  "$input = $1;"
+%typemap(directorin,descriptor="[Ljava/lang/Object;",nouse="1") jobjectArray   "$input = $1;"
+
+%typemap(javadirectorin) jboolean,
+                         jchar,
+                         jbyte,
+                         jshort,
+                         jint,
+                         jlong,
+                         jfloat,
+                         jdouble,
+                         jstring,
+                         jobject,
+                         jbooleanArray,
+                         jcharArray,
+                         jbyteArray,
+                         jshortArray,
+                         jintArray,
+                         jlongArray,
+                         jfloatArray,
+                         jdoubleArray,
+                         jobjectArray
+  "$jniinput"
+
+%typemap(javadirectorout) jboolean,
+                          jchar,
+                          jbyte,
+                          jshort,
+                          jint,
+                          jlong,
+                          jfloat,
+                          jdouble,
+                          jstring,
+                          jobject,
+                          jbooleanArray,
+                          jcharArray,
+                          jbyteArray,
+                          jshortArray,
+                          jintArray,
+                          jlongArray,
+                          jfloatArray,
+                          jdoubleArray,
+                          jobjectArray
+  "$javacall"
+
+/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions 
+ * that cannot be overloaded in Java as more than one C++ type maps to a single Java type */
+
+%typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */
+    jboolean,
+    bool,
+    const bool &
+    ""
+
+%typecheck(SWIG_TYPECHECK_CHAR) /* Java char */
+    jchar,
+    char, 
+    const char &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT8) /* Java byte */
+    jbyte,
+    signed char,
+    const signed char &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT16) /* Java short */
+    jshort,
+    unsigned char, 
+    short, 
+    const unsigned char &, 
+    const short &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT32) /* Java int */
+    jint,
+    unsigned short, 
+    int, 
+    long, 
+    const unsigned short &, 
+    const int &, 
+    const long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT64) /* Java long */
+    jlong,
+    unsigned int, 
+    unsigned long, 
+    long long, 
+    const unsigned int &, 
+    const unsigned long &, 
+    const long long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */
+    unsigned long long,
+    const unsigned long long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */
+    jfloat,
+    float,
+    const float &
+    ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */
+    jdouble,
+    double,
+    const double &
+    ""
+
+%typecheck(SWIG_TYPECHECK_STRING) /* Java String */
+    jstring,
+    char *,
+    char *&,
+    char[ANY],
+    char []
+    ""
+
+%typecheck(SWIG_TYPECHECK_BOOL_ARRAY) /* Java boolean[] */
+    jbooleanArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_CHAR_ARRAY) /* Java char[] */
+    jcharArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT8_ARRAY) /* Java byte[] */
+    jbyteArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT16_ARRAY) /* Java short[] */
+    jshortArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT32_ARRAY) /* Java int[] */
+    jintArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT64_ARRAY) /* Java long[] */
+    jlongArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT_ARRAY) /* Java float[] */
+    jfloatArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY) /* Java double[] */
+    jdoubleArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_OBJECT_ARRAY) /* Java jobject[] */
+    jobjectArray
+    ""
+
+%typecheck(SWIG_TYPECHECK_POINTER) /* Default */
+    SWIGTYPE, 
+    SWIGTYPE *, 
+    SWIGTYPE &, 
+    SWIGTYPE [],
+    SWIGTYPE (CLASS::*)
+    ""
+
+
+/* Exception handling */
+
+%typemap(throws) int, 
+                 long, 
+                 short, 
+                 unsigned int, 
+                 unsigned long, 
+                 unsigned short
+%{ char error_msg[256];
+   sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1);
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg);
+   return $null; %}
+
+%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY]
+%{ (void)$1;
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown");
+   return $null; %}
+
+%typemap(throws) char *
+%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1);
+   return $null; %}
+
+
+/* Typemaps for code generation in proxy classes and Java type wrapper classes */
+
+/* The javain typemap is used for converting function parameter types from the type 
+ * used in the proxy, module or type wrapper class to the type used in the JNI class. */
+%typemap(javain) bool,               const bool &,
+                 char,               const char &,
+                 signed char,        const signed char &,
+                 unsigned char,      const unsigned char &,
+                 short,              const short &,
+                 unsigned short,     const unsigned short &,
+                 int,                const int &,
+                 unsigned int,       const unsigned int &,
+                 long,               const long &,
+                 unsigned long,      const unsigned long &,
+                 long long,          const long long &,
+                 unsigned long long, const unsigned long long &,
+                 float,              const float &,
+                 double,             const double &
+    "$javainput"
+%typemap(javain) char *, char *&, char[ANY], char[] "$javainput"
+%typemap(javain) jboolean,
+                 jchar,
+                 jbyte,
+                 jshort,
+                 jint,
+                 jlong,
+                 jfloat,
+                 jdouble,
+                 jstring,
+                 jobject,
+                 jbooleanArray,
+                 jcharArray,
+                 jbyteArray,
+                 jshortArray,
+                 jintArray,
+                 jlongArray,
+                 jfloatArray,
+                 jdoubleArray,
+                 jobjectArray
+    "$javainput"
+%typemap(javain) SWIGTYPE "$&javaclassname.getCPtr($javainput)"
+%typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "$javaclassname.getCPtr($javainput)"
+
+/* The javaout typemap is used for converting function return types from the return type
+ * used in the JNI class to the type returned by the proxy, module or type wrapper class. */
+%typemap(javaout) bool,               const bool &,
+                  char,               const char &,
+                  signed char,        const signed char &,
+                  unsigned char,      const unsigned char &,
+                  short,              const short &,
+                  unsigned short,     const unsigned short &,
+                  int,                const int &,
+                  unsigned int,       const unsigned int &,
+                  long,               const long &,
+                  unsigned long,      const unsigned long &,
+                  long long,          const long long &,
+                  unsigned long long, const unsigned long long &,
+                  float,              const float &,
+                  double,             const double & {
+    return $jnicall;
+  }
+%typemap(javaout) char *, char *&, char[ANY], char[] {
+    return $jnicall;
+  }
+%typemap(javaout) jboolean,
+                  jchar,
+                  jbyte,
+                  jshort,
+                  jint,
+                  jlong,
+                  jfloat,
+                  jdouble,
+                  jstring,
+                  jobject,
+                  jbooleanArray,
+                  jcharArray,
+                  jbyteArray,
+                  jshortArray,
+                  jintArray,
+                  jlongArray,
+                  jfloatArray,
+                  jdoubleArray,
+                  jobjectArray {
+    return $jnicall;
+  }
+%typemap(javaout) void {
+    $jnicall;
+  }
+%typemap(javaout) SWIGTYPE {
+    return new $&javaclassname($jnicall, true);
+  }
+%typemap(javaout) SWIGTYPE & {
+    return new $javaclassname($jnicall, $owner);
+  }
+%typemap(javaout) SWIGTYPE *, SWIGTYPE [], SWIGTYPE (CLASS::*) {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new $javaclassname(cPtr, $owner);
+  }
+
+/* Pointer reference typemaps */
+%typemap(jni) SWIGTYPE *& "jlong"
+%typemap(jtype) SWIGTYPE *& "long"
+%typemap(jstype) SWIGTYPE *& "$*javaclassname"
+%typemap(javain) SWIGTYPE *& "$*javaclassname.getCPtr($javainput)"
+%typemap(javaout) SWIGTYPE *& {
+    long cPtr = $jnicall;
+    return (cPtr == 0) ? null : new $*javaclassname(cPtr, $owner);
+  }
+%typemap(in) SWIGTYPE *& ($*1_ltype temp = 0)
+%{ temp = *($1_ltype)&$input;
+   $1 = &temp; %}
+%typemap(out) SWIGTYPE *&
+%{ *($1_ltype)&$result = *$1; %} 
+
+/* Array reference typemaps */
+%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) }
+
+/* Typemaps used for the generation of proxy and type wrapper class code */
+%typemap(javabase)             SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(javaclassmodifiers)   SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class"
+%typemap(javacode)             SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(javaimports)          SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(javainterfaces)       SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+
+/* javabody typemaps */
+
+%define SWIG_JAVABODY_METHODS(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPENAME...)
+// Base proxy classes
+%typemap(javabody) TYPENAME %{
+  private long swigCPtr;
+  protected boolean swigCMemOwn;
+
+  PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) {
+    swigCMemOwn = cMemoryOwn;
+    swigCPtr = cPtr;
+  }
+
+  CPTR_VISIBILITY static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+// Derived proxy classes
+%typemap(javabody_derived) TYPENAME %{
+  private long swigCPtr;
+
+  PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) {
+    super($imclassname.SWIG$javaclassnameUpcast(cPtr), cMemoryOwn);
+    swigCPtr = cPtr;
+  }
+
+  CPTR_VISIBILITY static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+%enddef
+
+/* Set the default for SWIGTYPE: pointer constructor is protected,
+   getCPtr is protected. Season to your own taste! */
+
+SWIG_JAVABODY_METHODS(protected, protected, SWIGTYPE)
+
+// Typewrapper classes
+%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+  private long swigCPtr;
+
+  protected $javaclassname(long cPtr, boolean futureUse) {
+    swigCPtr = cPtr;
+  }
+
+  protected $javaclassname() {
+    swigCPtr = 0;
+  }
+
+  protected static long getCPtr($javaclassname obj) {
+    return (obj == null) ? 0 : obj.swigCPtr;
+  }
+%}
+
+%typemap(javafinalize) SWIGTYPE %{
+  protected void finalize() {
+    delete();
+  }
+%}
+
+/*
+ * Java constructor typemaps:
+ *
+ * The javaconstruct typemap is inserted when a proxy class's constructor is generated.
+ * This typemap allows control over what code is executed in the constructor as
+ * well as specifying who owns the underlying C/C++ object. Normally, Java has
+ * ownership and the underlying C/C++ object is deallocated when the Java object
+ * is finalized (swigCMemOwn is true.) If swigCMemOwn is false, C/C++ is
+ * ultimately responsible for deallocating the underlying object's memory.
+ *
+ * The SWIG_PROXY_CONSTRUCTOR macro defines the javaconstruct typemap for a proxy
+ * class for a particular TYPENAME. OWNERSHIP is passed as the value of
+ * swigCMemOwn to the pointer constructor method.  WEAKREF determines which kind
+ * of Java object reference will be used by the C++ director class (WeakGlobalRef
+ * vs. GlobalRef.)
+ *
+ * The SWIG_DIRECTOR_OWNED macro sets the ownership of director-based proxy
+ * classes and the weak reference flag to false, meaning that the underlying C++
+ * object will be reclaimed by C++.
+ */
+
+%define SWIG_PROXY_CONSTRUCTOR(OWNERSHIP, WEAKREF, TYPENAME...)
+%typemap(javaconstruct,directorconnect="\n    $imclassname.$javaclassname_director_connect(this, swigCPtr, swigCMemOwn, WEAKREF);") TYPENAME {
+    this($imcall, OWNERSHIP);$directorconnect
+  }
+%enddef
+
+%define SWIG_DIRECTOR_OWNED(TYPENAME...)
+SWIG_PROXY_CONSTRUCTOR(true, false, TYPENAME)
+%enddef
+
+// Set the default for SWIGTYPE: Java owns the C/C++ object.
+SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE)
+
+%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE {
+    if(swigCPtr != 0 && swigCMemOwn) {
+      swigCMemOwn = false;
+      $jnicall;
+    }
+    swigCPtr = 0;
+  }
+
+%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE {
+    if(swigCPtr != 0 && swigCMemOwn) {
+      swigCMemOwn = false;
+      $jnicall;
+    }
+    swigCPtr = 0;
+    super.delete();
+  }
+
+%typemap(directordisconnect, methodname="swigDirectorDisconnect") SWIGTYPE %{
+  protected void $methodname() {
+    swigCMemOwn = false;
+    $jnicall;
+  }
+%}
+
+%typemap(directorowner_release, methodname="swigReleaseOwnership") SWIGTYPE %{
+  public void $methodname() {
+    swigCMemOwn = false;
+    $jnicall;
+  }
+%}
+
+%typemap(directorowner_take, methodname="swigTakeOwnership") SWIGTYPE %{
+  public void $methodname() {
+    swigCMemOwn = true;
+    $jnicall;
+  }
+%}
+
+/* Java specific directives */
+#define %javaconst(flag)            %feature("java:const","flag")
+#define %javaconstvalue(value)      %feature("java:constvalue",value)
+#define %javaenum(wrapapproach)     %feature("java:enum","wrapapproach")
+#define %javamethodmodifiers        %feature("java:methodmodifiers")
+#define %javaexception(exceptionclasses) %feature("except",throws=exceptionclasses)
+#define %nojavaexception                 %feature("except","",throws="")
+
+%pragma(java) jniclassclassmodifiers="class"
+%pragma(java) moduleclassmodifiers="public class"
+
+/* Some ANSI C typemaps */
+
+%apply unsigned long { size_t };
+%apply const unsigned long & { const size_t & };
+
+/* java keywords */
+%include <javakw.swg>
+
+// Default enum handling
+%include <enumtypesafe.swg>
+
diff --git a/trunk/Lib/java/javahead.swg b/trunk/Lib/java/javahead.swg
new file mode 100644
index 0000000..4aa0c84
--- /dev/null
+++ b/trunk/Lib/java/javahead.swg
@@ -0,0 +1,103 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * javahead.swg
+ *
+ * Java support code
+ * ----------------------------------------------------------------------------- */
+
+
+/* JNI function calls require different calling conventions for C and C++. These JCALL macros are used so 
+ * that the same typemaps can be used for generating code for both C and C++. The SWIG preprocessor can expand
+ * the macros thereby generating the correct calling convention. It is thus essential that all typemaps that
+ * use the macros are not within %{ %} brackets as they won't be run through the SWIG preprocessor. */
+#ifdef __cplusplus
+#   define JCALL0(func, jenv) jenv->func()
+#   define JCALL1(func, jenv, ar1) jenv->func(ar1)
+#   define JCALL2(func, jenv, ar1, ar2) jenv->func(ar1, ar2)
+#   define JCALL3(func, jenv, ar1, ar2, ar3) jenv->func(ar1, ar2, ar3)
+#   define JCALL4(func, jenv, ar1, ar2, ar3, ar4) jenv->func(ar1, ar2, ar3, ar4)
+#   define JCALL5(func, jenv, ar1, ar2, ar3, ar4, ar5) jenv->func(ar1, ar2, ar3, ar4, ar5)
+#   define JCALL6(func, jenv, ar1, ar2, ar3, ar4, ar5, ar6) jenv->func(ar1, ar2, ar3, ar4, ar5, ar6)
+#   define JCALL7(func, jenv, ar1, ar2, ar3, ar4, ar5, ar6, ar7) jenv->func(ar1, ar2, ar3, ar4, ar5, ar6, ar7)
+#else
+#   define JCALL0(func, jenv) (*jenv)->func(jenv)
+#   define JCALL1(func, jenv, ar1) (*jenv)->func(jenv, ar1)
+#   define JCALL2(func, jenv, ar1, ar2) (*jenv)->func(jenv, ar1, ar2)
+#   define JCALL3(func, jenv, ar1, ar2, ar3) (*jenv)->func(jenv, ar1, ar2, ar3)
+#   define JCALL4(func, jenv, ar1, ar2, ar3, ar4) (*jenv)->func(jenv, ar1, ar2, ar3, ar4)
+#   define JCALL5(func, jenv, ar1, ar2, ar3, ar4, ar5) (*jenv)->func(jenv, ar1, ar2, ar3, ar4, ar5)
+#   define JCALL6(func, jenv, ar1, ar2, ar3, ar4, ar5, ar6) (*jenv)->func(jenv, ar1, ar2, ar3, ar4, ar5, ar6)
+#   define JCALL7(func, jenv, ar1, ar2, ar3, ar4, ar5, ar6, ar7) (*jenv)->func(jenv, ar1, ar2, ar3, ar4, ar5, ar6, ar7)
+#endif
+
+%insert(runtime) %{
+/* Fix for jlong on some versions of gcc on Windows */
+#if defined(__GNUC__) && !defined(__INTELC__)
+  typedef long long __int64;
+#endif
+
+/* Fix for jlong on 64-bit x86 Solaris */
+#if defined(__x86_64)
+# ifdef _LP64
+#   undef _LP64
+# endif
+#endif
+
+#include <jni.h>
+#include <stdlib.h>
+#include <string.h>
+%}
+
+%insert(runtime) %{
+/* Support for throwing Java exceptions */
+typedef enum {
+  SWIG_JavaOutOfMemoryError = 1, 
+  SWIG_JavaIOException, 
+  SWIG_JavaRuntimeException, 
+  SWIG_JavaIndexOutOfBoundsException,
+  SWIG_JavaArithmeticException,
+  SWIG_JavaIllegalArgumentException,
+  SWIG_JavaNullPointerException,
+  SWIG_JavaDirectorPureVirtual,
+  SWIG_JavaUnknownError
+} SWIG_JavaExceptionCodes;
+
+typedef struct {
+  SWIG_JavaExceptionCodes code;
+  const char *java_exception;
+} SWIG_JavaExceptions_t;
+%}
+
+%insert(runtime) {
+static void SWIGUNUSED SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg) {
+  jclass excep;
+  static const SWIG_JavaExceptions_t java_exceptions[] = {
+    { SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" },
+    { SWIG_JavaIOException, "java/io/IOException" },
+    { SWIG_JavaRuntimeException, "java/lang/RuntimeException" },
+    { SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" },
+    { SWIG_JavaArithmeticException, "java/lang/ArithmeticException" },
+    { SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" },
+    { SWIG_JavaNullPointerException, "java/lang/NullPointerException" },
+    { SWIG_JavaDirectorPureVirtual, "java/lang/RuntimeException" },
+    { SWIG_JavaUnknownError,  "java/lang/UnknownError" },
+    { (SWIG_JavaExceptionCodes)0,  "java/lang/UnknownError" } };
+  const SWIG_JavaExceptions_t *except_ptr = java_exceptions;
+
+  while (except_ptr->code != code && except_ptr->code)
+    except_ptr++;
+
+  JCALL0(ExceptionClear, jenv);
+  excep = JCALL1(FindClass, jenv, except_ptr->java_exception);
+  if (excep)
+    JCALL2(ThrowNew, jenv, excep, msg);
+}
+}
+
+%insert(runtime) %{
+/* Contract support */
+
+#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, msg); return nullreturn; } else
+%}
diff --git a/trunk/Lib/java/javakw.swg b/trunk/Lib/java/javakw.swg
new file mode 100644
index 0000000..99cd547
--- /dev/null
+++ b/trunk/Lib/java/javakw.swg
@@ -0,0 +1,70 @@
+#ifndef JAVA_JAVAKW_SWG_
+#define JAVA_JAVAKW_SWG_
+
+/* Warnings for Java keywords */
+#define JAVAKW(x) %keywordwarn("'" `x` "' is a java keyword, renaming to '_"`x`"'",rename="_%s")  `x`
+
+/*
+   from
+   http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html 
+*/
+
+JAVAKW(abstract);
+JAVAKW(double);
+JAVAKW(int);
+JAVAKW(strictfp);
+JAVAKW(boolean);
+JAVAKW(else);
+JAVAKW(interface);
+JAVAKW(super);
+JAVAKW(break);
+JAVAKW(extends);	
+JAVAKW(long);	
+JAVAKW(switch);
+JAVAKW(byte);	
+JAVAKW(final);	
+JAVAKW(native);	
+JAVAKW(synchronized);
+JAVAKW(case);	
+JAVAKW(finally);	
+JAVAKW(new);	
+JAVAKW(this);
+JAVAKW(catch);	
+JAVAKW(float);	
+JAVAKW(package);	
+JAVAKW(throw);
+JAVAKW(char);	
+JAVAKW(for);	
+JAVAKW(private);	
+JAVAKW(throws);
+JAVAKW(class);	
+JAVAKW(goto); 	
+JAVAKW(protected);	
+JAVAKW(transient);
+JAVAKW(const); 	
+JAVAKW(if);	
+JAVAKW(public);	
+JAVAKW(try);
+JAVAKW(continue);	
+JAVAKW(implements);	
+JAVAKW(return);	
+JAVAKW(void);
+JAVAKW(default);	
+JAVAKW(import);	
+JAVAKW(short);	
+JAVAKW(volatile);
+JAVAKW(do);	
+JAVAKW(instanceof);	
+JAVAKW(static);	
+JAVAKW(while);
+
+
+/* others bad names */
+
+/* Note here that only *::clone() is bad, and *::clone(int) is ok */
+%namewarn("321:clone() is a java bad method name") *::clone();
+
+
+#undef JAVAKW
+
+#endif //JAVA_JAVAKW_SWG_
diff --git a/trunk/Lib/java/std_common.i b/trunk/Lib/java/std_common.i
new file mode 100644
index 0000000..cee11e8
--- /dev/null
+++ b/trunk/Lib/java/std_common.i
@@ -0,0 +1,5 @@
+%include <std_except.i>
+
+%apply size_t { std::size_t };
+%apply const size_t& { const std::size_t& };
+
diff --git a/trunk/Lib/java/std_deque.i b/trunk/Lib/java/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/java/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/java/std_except.i b/trunk/Lib/java/std_except.i
new file mode 100644
index 0000000..15be1de
--- /dev/null
+++ b/trunk/Lib/java/std_except.i
@@ -0,0 +1,33 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_except.i
+ *
+ * Typemaps used by the STL wrappers that throw exceptions.
+ * These typemaps are used when methods are declared with an STL exception specification, such as
+ *   size_t at() const throw (std::out_of_range);
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <stdexcept>
+%}
+
+namespace std 
+{
+  %ignore exception;
+  struct exception {};
+}
+
+%typemap(throws) std::bad_exception     "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;"
+%typemap(throws) std::domain_error      "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;"
+%typemap(throws) std::exception         "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;"
+%typemap(throws) std::invalid_argument  "SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, $1.what());\n return $null;"
+%typemap(throws) std::length_error      "SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, $1.what());\n return $null;"
+%typemap(throws) std::logic_error       "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;"
+%typemap(throws) std::out_of_range      "SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, $1.what());\n return $null;"
+%typemap(throws) std::overflow_error    "SWIG_JavaThrowException(jenv, SWIG_JavaArithmeticException, $1.what());\n return $null;"
+%typemap(throws) std::range_error       "SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, $1.what());\n return $null;"
+%typemap(throws) std::runtime_error     "SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.what());\n return $null;"
+%typemap(throws) std::underflow_error   "SWIG_JavaThrowException(jenv, SWIG_JavaArithmeticException, $1.what());\n return $null;"
+
diff --git a/trunk/Lib/java/std_map.i b/trunk/Lib/java/std_map.i
new file mode 100644
index 0000000..00967d3
--- /dev/null
+++ b/trunk/Lib/java/std_map.i
@@ -0,0 +1,179 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        typedef size_t size_type;
+        typedef ptrdiff_t difference_type;
+        typedef K key_type;
+        typedef T mapped_type;
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            const T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, T x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    // add specializations here
+
+}
diff --git a/trunk/Lib/java/std_pair.i b/trunk/Lib/java/std_pair.i
new file mode 100644
index 0000000..dc0604d
--- /dev/null
+++ b/trunk/Lib/java/std_pair.i
@@ -0,0 +1,37 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+namespace std {
+
+  template<class T, class U> struct pair {
+
+    pair();
+    pair(T first, U second);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+  };
+
+  // add specializations here
+
+}
diff --git a/trunk/Lib/java/std_string.i b/trunk/Lib/java/std_string.i
new file mode 100644
index 0000000..789e17a
--- /dev/null
+++ b/trunk/Lib/java/std_string.i
@@ -0,0 +1,120 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * Typemaps for std::string and const std::string&
+ * These are mapped to a Java String and are passed around by value.
+ *
+ * To use non-const std::string references use the following %apply.  Note 
+ * that they are passed by value.
+ * %apply const std::string & {std::string &};
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+%naturalvar string;
+
+class string;
+
+// string
+%typemap(jni) string "jstring"
+%typemap(jtype) string "String"
+%typemap(jstype) string "String"
+%typemap(javadirectorin) string "$jniinput"
+%typemap(javadirectorout) string "$javacall"
+
+%typemap(in) string 
+%{ if(!$input) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::string");
+     return $null;
+    } 
+    const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); 
+    if (!$1_pstr) return $null;
+    $1.assign($1_pstr);
+    jenv->ReleaseStringUTFChars($input, $1_pstr); %}
+
+%typemap(directorout) string 
+%{ if(!$input) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::string");
+     return $null;
+   } 
+   const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); 
+   if (!$1_pstr) return $null;
+   $result.assign($1_pstr);
+   jenv->ReleaseStringUTFChars($input, $1_pstr); %}
+
+%typemap(directorin,descriptor="Ljava/lang/String;") string 
+%{ $input = jenv->NewStringUTF($1.c_str()); %}
+
+%typemap(out) string 
+%{ $result = jenv->NewStringUTF($1.c_str()); %}
+
+%typemap(javain) string "$javainput"
+
+%typemap(javaout) string {
+    return $jnicall;
+  }
+
+%typemap(typecheck) string = char *;
+
+%typemap(throws) string
+%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.c_str());
+   return $null; %}
+
+// const string &
+%typemap(jni) const string & "jstring"
+%typemap(jtype) const string & "String"
+%typemap(jstype) const string & "String"
+%typemap(javadirectorin) const string & "$jniinput"
+%typemap(javadirectorout) const string & "$javacall"
+
+%typemap(in) const string &
+%{ if(!$input) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::string");
+     return $null;
+   }
+   const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); 
+   if (!$1_pstr) return $null;
+   std::string $1_str($1_pstr);
+   $1 = &$1_str;
+   jenv->ReleaseStringUTFChars($input, $1_pstr); %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const string &
+%{ if(!$input) {
+     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::string");
+     return $null;
+   }
+   const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); 
+   if (!$1_pstr) return $null;
+   /* possible thread/reentrant code problem */
+   static std::string $1_str;
+   $1_str = $1_pstr;
+   $result = &$1_str;
+   jenv->ReleaseStringUTFChars($input, $1_pstr); %}
+
+%typemap(directorin,descriptor="Ljava/lang/String;") const string &
+%{ $input = jenv->NewStringUTF($1.c_str()); %}
+
+%typemap(out) const string & 
+%{ $result = jenv->NewStringUTF($1->c_str()); %}
+
+%typemap(javain) const string & "$javainput"
+
+%typemap(javaout) const string & {
+    return $jnicall;
+  }
+
+%typemap(typecheck) const string & = char *;
+
+%typemap(throws) const string &
+%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1.c_str());
+   return $null; %}
+
+}
+
diff --git a/trunk/Lib/java/std_vector.i b/trunk/Lib/java/std_vector.i
new file mode 100644
index 0000000..92fa25a
--- /dev/null
+++ b/trunk/Lib/java/std_vector.i
@@ -0,0 +1,54 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+%{
+#include <vector>
+#include <stdexcept>
+%}
+
+namespace std {
+    
+    template<class T> class vector {
+      public:
+        typedef size_t size_type;
+        typedef T value_type;
+        typedef const value_type& const_reference;
+        vector();
+        vector(size_type n);
+        size_type size() const;
+        size_type capacity() const;
+        void reserve(size_type n);
+        %rename(isEmpty) empty;
+        bool empty() const;
+        void clear();
+        %rename(add) push_back;
+        void push_back(const value_type& x);
+        %extend {
+            const_reference get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, const value_type& val) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = val;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+}
+
+%define specialize_std_vector(T)
+#warning "specialize_std_vector - specialization for type T no longer needed"
+%enddef
+
diff --git a/trunk/Lib/java/std_wstring.i b/trunk/Lib/java/std_wstring.i
new file mode 100644
index 0000000..9891765
--- /dev/null
+++ b/trunk/Lib/java/std_wstring.i
@@ -0,0 +1,175 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_wstring.i
+ *
+ * Typemaps for std::wstring and const std::wstring&
+ *
+ * These are mapped to a Java String and are passed around by value.
+ * Warning: Unicode / multibyte characters are handled differently on different 
+ * OSs so the std::wstring typemaps may not always work as intended.
+ *
+ * To use non-const std::wstring references use the following %apply.  Note 
+ * that they are passed by value.
+ * %apply const std::wstring & {std::wstring &};
+ * ----------------------------------------------------------------------------- */
+
+namespace std {
+
+%naturalvar wstring;
+
+class wstring;
+
+// wstring
+%typemap(jni) wstring "jstring"
+%typemap(jtype) wstring "String"
+%typemap(jstype) wstring "String"
+%typemap(javadirectorin) wstring "$jniinput"
+%typemap(javadirectorout) wstring "$javacall"
+
+%typemap(in) wstring
+%{if(!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::wstring");
+    return $null;
+  }
+  const jchar *$1_pstr = jenv->GetStringChars($input, 0);
+  if (!$1_pstr) return $null;
+  jsize $1_len = jenv->GetStringLength($input);
+  if ($1_len) {
+    $1.reserve($1_len);
+    for (jsize i = 0; i < $1_len; ++i) {
+      $1.push_back((wchar_t)$1_pstr[i]);
+    }
+  }
+  jenv->ReleaseStringChars($input, $1_pstr);
+ %}
+
+%typemap(directorout) wstring
+%{if(!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::wstring");
+    return $null;
+  }
+  const jchar *$1_pstr = jenv->GetStringChars($input, 0);
+  if (!$1_pstr) return $null;
+  jsize $1_len = jenv->GetStringLength($input);
+  if ($1_len) {
+    $result.reserve($1_len);
+    for (jsize i = 0; i < $1_len; ++i) {
+      $result.push_back((wchar_t)$1_pstr[i]);
+    }
+  }
+  jenv->ReleaseStringChars($input, $1_pstr);
+ %}
+
+%typemap(directorin,descriptor="Ljava/lang/String;") wstring {
+  jsize $1_len = $1.length();
+  jchar *conv_buf = new jchar[$1_len];
+  for (jsize i = 0; i < $1_len; ++i) {
+    conv_buf[i] = (jchar)$1[i];
+  }
+  $input = jenv->NewString(conv_buf, $1_len);
+  delete [] conv_buf;
+}
+
+%typemap(out) wstring
+%{jsize $1_len = $1.length();
+  jchar *conv_buf = new jchar[$1_len];
+  for (jsize i = 0; i < $1_len; ++i) {
+    conv_buf[i] = (jchar)$1[i];
+  }
+  $result = jenv->NewString(conv_buf, $1_len);
+  delete [] conv_buf; %}
+
+%typemap(javain) wstring "$javainput"
+
+%typemap(javaout) wstring {
+    return $jnicall;
+  }
+
+//%typemap(typecheck) wstring = wchar_t *;
+
+%typemap(throws) wstring
+%{ std::string message($1.begin(), $1.end());
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, message.c_str());
+   return $null; %}
+
+// const wstring &
+%typemap(jni) const wstring & "jstring"
+%typemap(jtype) const wstring & "String"
+%typemap(jstype) const wstring & "String"
+%typemap(javadirectorin) const wstring & "$jniinput"
+%typemap(javadirectorout) const wstring & "$javacall"
+
+%typemap(in) const wstring &
+%{if(!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::wstring");
+    return $null;
+  }
+  const jchar *$1_pstr = jenv->GetStringChars($input, 0);
+  if (!$1_pstr) return $null;
+  jsize $1_len = jenv->GetStringLength($input);
+  std::wstring $1_str;
+  if ($1_len) {
+    $1_str.reserve($1_len);
+    for (jsize i = 0; i < $1_len; ++i) {
+      $1_str.push_back((wchar_t)$1_pstr[i]);
+    }
+  }
+  $1 = &$1_str;
+  jenv->ReleaseStringChars($input, $1_pstr);
+ %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const wstring & 
+%{if(!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null std::wstring");
+    return $null;
+  }
+  const jchar *$1_pstr = jenv->GetStringChars($input, 0);
+  if (!$1_pstr) return $null;
+  jsize $1_len = jenv->GetStringLength($input);
+  /* possible thread/reentrant code problem */
+  static std::wstring $1_str;
+  if ($1_len) {
+    $1_str.reserve($1_len);
+    for (jsize i = 0; i < $1_len; ++i) {
+      $1_str.push_back((wchar_t)$1_pstr[i]);
+    }
+  }
+  $result = &$1_str;
+  jenv->ReleaseStringChars($input, $1_pstr); %}
+
+%typemap(directorin,descriptor="Ljava/lang/String;") const wstring & {
+  jsize $1_len = $1.length();
+  jchar *conv_buf = new jchar[$1_len];
+  for (jsize i = 0; i < $1_len; ++i) {
+    conv_buf[i] = (jchar)($1)[i];
+  }
+  $input = jenv->NewString(conv_buf, $1_len);
+  delete [] conv_buf;
+}
+
+%typemap(out) const wstring & 
+%{jsize $1_len = $1->length();
+  jchar *conv_buf = new jchar[$1_len];
+  for (jsize i = 0; i < $1_len; ++i) {
+    conv_buf[i] = (jchar)(*$1)[i];
+  }
+  $result = jenv->NewString(conv_buf, $1_len);
+  delete [] conv_buf; %}
+
+%typemap(javain) const wstring & "$javainput"
+
+%typemap(javaout) const wstring & {
+    return $jnicall;
+  }
+
+//%typemap(typecheck) const wstring & = wchar_t *;
+
+%typemap(throws) const wstring &
+%{ std::string message($1.begin(), $1.end());
+   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, message.c_str());
+   return $null; %}
+
+}
+
diff --git a/trunk/Lib/java/stl.i b/trunk/Lib/java/stl.i
new file mode 100644
index 0000000..b8d7a65
--- /dev/null
+++ b/trunk/Lib/java/stl.i
@@ -0,0 +1,13 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/java/typemaps.i b/trunk/Lib/java/typemaps.i
new file mode 100644
index 0000000..59f7af9
--- /dev/null
+++ b/trunk/Lib/java/typemaps.i
@@ -0,0 +1,449 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Pointer and reference handling typemap library
+ *
+ * These mappings provide support for input/output arguments and common
+ * uses for C/C++ pointers and C++ references.
+ * ----------------------------------------------------------------------------- */
+
+/*
+INPUT typemaps
+--------------
+
+These typemaps remap a C pointer or C++ reference to be an "INPUT" value which is
+passed by value instead of reference.
+
+The following typemaps can be applied to turn a pointer or reference into a simple
+input value.  That is, instead of passing a pointer or reference to an object,
+you would use a real value instead.
+
+        bool               *INPUT, bool               &INPUT
+        signed char        *INPUT, signed char        &INPUT
+        unsigned char      *INPUT, unsigned char      &INPUT
+        short              *INPUT, short              &INPUT
+        unsigned short     *INPUT, unsigned short     &INPUT
+        int                *INPUT, int                &INPUT
+        unsigned int       *INPUT, unsigned int       &INPUT
+        long               *INPUT, long               &INPUT
+        unsigned long      *INPUT, unsigned long      &INPUT
+        long long          *INPUT, long long          &INPUT
+        unsigned long long *INPUT, unsigned long long &INPUT
+        float              *INPUT, float              &INPUT
+        double             *INPUT, double             &INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include <typemaps.i>
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+In Java you could then use it like this:
+        double answer = modulename.fadd(10.0, 20.0);
+
+There are no char *INPUT typemaps, however you can apply the signed char * typemaps instead:
+        %include <typemaps.i>
+        %apply signed char *INPUT {char *input};
+        void f(char *input);
+*/
+
+%define INPUT_TYPEMAP(TYPE, JNITYPE, JTYPE, JNIDESC)
+%typemap(jni) TYPE *INPUT, TYPE &INPUT "JNITYPE"
+%typemap(jtype) TYPE *INPUT, TYPE &INPUT "JTYPE"
+%typemap(jstype) TYPE *INPUT, TYPE &INPUT "JTYPE"
+%typemap(javain) TYPE *INPUT, TYPE &INPUT "$javainput"
+%typemap(javadirectorin) TYPE *INPUT, TYPE &INPUT "$jniinput"
+%typemap(javadirectorout) TYPE *INPUT, TYPE &INPUT "$javacall"
+
+%typemap(in) TYPE *INPUT, TYPE &INPUT
+%{ $1 = ($1_ltype)&$input; %}
+
+%typemap(freearg) TYPE *INPUT, TYPE &INPUT ""
+
+%typemap(directorout) TYPE *INPUT, TYPE &INPUT
+%{ $result = ($1_ltype)&$input; %}
+
+%typemap(directorin,descriptor=JNIDESC) TYPE &INPUT
+%{ *(($&1_ltype) $input) = (JNITYPE *) &$1; %}
+
+%typemap(directorin,descriptor=JNIDESC) TYPE *INPUT
+%{ *(($&1_ltype) $input) = (JNITYPE *) $1; %}
+
+%typemap(typecheck) TYPE *INPUT = TYPE;
+%typemap(typecheck) TYPE &INPUT = TYPE;
+%enddef
+
+INPUT_TYPEMAP(bool, jboolean, boolean, "Z");
+INPUT_TYPEMAP(signed char, jbyte, byte, "B");
+INPUT_TYPEMAP(unsigned char, jshort, short, "S");
+INPUT_TYPEMAP(short, jshort, short, "S");
+INPUT_TYPEMAP(unsigned short, jint, int, "I");
+INPUT_TYPEMAP(int, jint, int, "I");
+INPUT_TYPEMAP(unsigned int, jlong, long, "J");
+INPUT_TYPEMAP(long, jint, int, "I");
+INPUT_TYPEMAP(unsigned long, jlong, long, "J");
+INPUT_TYPEMAP(long long, jlong, long, "J");
+INPUT_TYPEMAP(unsigned long long, jobject, java.math.BigInteger, "Ljava/math/BigInteger;");
+INPUT_TYPEMAP(float, jfloat, float, "F");
+INPUT_TYPEMAP(double, jdouble, double, "D");
+
+#undef INPUT_TYPEMAP
+
+/* Convert from BigInteger using the toByteArray member function */
+/* Overrides the typemap in the INPUT_TYPEMAP macro */
+%typemap(in) unsigned long long *INPUT($*1_ltype temp), unsigned long long &INPUT($*1_ltype temp) {
+  jclass clazz;
+  jmethodID mid;
+  jbyteArray ba;
+  jbyte* bae;
+  jsize sz;
+  int i;
+
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+    return $null;
+  }
+  clazz = JCALL1(GetObjectClass, jenv, $input);
+  mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+  ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+  bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  sz = JCALL1(GetArrayLength, jenv, ba);
+  temp = 0;
+  for(i=0; i<sz; i++) {
+    temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i];
+  }
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+  $1 = &temp;
+}
+
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   An array replaces the c pointer or reference parameter. 
+// The output value is returned in this array passed in. 
+
+/*
+OUTPUT typemaps
+---------------
+
+The following typemaps can be applied to turn a pointer or reference into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  This works by a 
+Java array being passed as a parameter where a c pointer or reference is required. 
+As with any Java function, the array is passed by reference so that 
+any modifications to the array will be picked up in the calling function.
+Note that the array passed in MUST have at least one element, but as the 
+c function does not require any input, the value can be set to anything.
+
+        bool               *OUTPUT, bool               &OUTPUT
+        signed char        *OUTPUT, signed char        &OUTPUT
+        unsigned char      *OUTPUT, unsigned char      &OUTPUT
+        short              *OUTPUT, short              &OUTPUT
+        unsigned short     *OUTPUT, unsigned short     &OUTPUT
+        int                *OUTPUT, int                &OUTPUT
+        unsigned int       *OUTPUT, unsigned int       &OUTPUT
+        long               *OUTPUT, long               &OUTPUT
+        unsigned long      *OUTPUT, unsigned long      &OUTPUT
+        long long          *OUTPUT, long long          &OUTPUT
+        unsigned long long *OUTPUT, unsigned long long &OUTPUT
+        float              *OUTPUT, float              &OUTPUT
+        double             *OUTPUT, double             &OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters):
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The Java output of the function would be the function return value and the 
+value in the single element array. In Java you would use it like this:
+
+    double[] ptr = {0.0};
+    double fraction = modulename.modf(5.0,ptr);
+
+There are no char *OUTPUT typemaps, however you can apply the signed char * typemaps instead:
+        %include <typemaps.i>
+        %apply signed char *OUTPUT {char *output};
+        void f(char *output);
+*/
+
+/* Java BigInteger[] */
+%typecheck(SWIG_TYPECHECK_INT128_ARRAY) SWIGBIGINTEGERARRAY ""
+
+%define OUTPUT_TYPEMAP(TYPE, JNITYPE, JTYPE, JAVATYPE, JNIDESC, TYPECHECKTYPE)
+%typemap(jni) TYPE *OUTPUT, TYPE &OUTPUT %{JNITYPE##Array%}
+%typemap(jtype) TYPE *OUTPUT, TYPE &OUTPUT "JTYPE[]"
+%typemap(jstype) TYPE *OUTPUT, TYPE &OUTPUT "JTYPE[]"
+%typemap(javain) TYPE *OUTPUT, TYPE &OUTPUT "$javainput"
+%typemap(javadirectorin) TYPE *OUTPUT, TYPE &OUTPUT "$jniinput"
+%typemap(javadirectorout) TYPE *OUTPUT, TYPE &OUTPUT "$javacall"
+
+%typemap(in) TYPE *OUTPUT($*1_ltype temp), TYPE &OUTPUT($*1_ltype temp)
+{
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null");
+    return $null;
+  }
+  if (JCALL1(GetArrayLength, jenv, $input) == 0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
+    return $null;
+  }
+  $1 = &temp; 
+}
+
+%typemap(freearg) TYPE *OUTPUT, TYPE &OUTPUT ""
+
+%typemap(argout) TYPE *OUTPUT, TYPE &OUTPUT 
+{
+  JNITYPE jvalue = (JNITYPE)temp$argnum;
+  JCALL4(Set##JAVATYPE##ArrayRegion, jenv, $input, 0, 1, &jvalue);
+}
+
+%typemap(directorout,warning="Need to provide TYPE *OUTPUT directorout typemap") TYPE *OUTPUT, TYPE &OUTPUT {
+}
+
+%typemap(directorin,descriptor=JNIDESC) TYPE &OUTPUT
+%{ *(($&1_ltype) $input = &$1; %}
+
+%typemap(directorin,descriptor=JNIDESC,warning="Need to provide TYPE *OUTPUT directorin typemap, TYPE array length is unknown") TYPE *OUTPUT
+{
+}
+
+%typemap(typecheck) TYPE *INOUT = TYPECHECKTYPE;
+%typemap(typecheck) TYPE &INOUT = TYPECHECKTYPE;
+%enddef
+
+OUTPUT_TYPEMAP(bool, jboolean, boolean, Boolean, "[Ljava/lang/Boolean;", jbooleanArray);
+OUTPUT_TYPEMAP(signed char, jbyte, byte, Byte, "[Ljava/lang/Byte;", jbyteArray);               
+OUTPUT_TYPEMAP(unsigned char, jshort, short, Short, "[Ljava/lang/Short;", jshortArray);              
+OUTPUT_TYPEMAP(short, jshort, short, Short, "[Ljava/lang/Short;", jshortArray);              
+OUTPUT_TYPEMAP(unsigned short, jint, int, Int, "[Ljava/lang/Integer;", jintArray);                
+OUTPUT_TYPEMAP(int, jint, int, Int, "[Ljava/lang/Integer;", jintArray);                
+OUTPUT_TYPEMAP(unsigned int, jlong, long, Long, "[Ljava/lang/Long;", jlongArray);               
+OUTPUT_TYPEMAP(long, jint, int, Int, "[Ljava/lang/Integer;", jintArray);                
+OUTPUT_TYPEMAP(unsigned long, jlong, long, Long, "[Ljava/lang/Long;", jlongArray);               
+OUTPUT_TYPEMAP(long long, jlong, long, Long, "[Ljava/lang/Long;", jlongArray);               
+OUTPUT_TYPEMAP(unsigned long long, jobject, java.math.BigInteger, NOTUSED, "[Ljava/lang/BigInteger;", SWIGBIGINTEGERARRAY);
+OUTPUT_TYPEMAP(float, jfloat, float, Float, "[Ljava/lang/Float;", jfloatArray);              
+OUTPUT_TYPEMAP(double, jdouble, double, Double, "[Ljava/lang/Double;", jdoubleArray);             
+
+#undef OUTPUT_TYPEMAP
+
+/* Convert to BigInteger - byte array holds number in 2's complement big endian format */
+/* Use first element in BigInteger array for output */
+/* Overrides the typemap in the OUTPUT_TYPEMAP macro */
+%typemap(argout) unsigned long long *OUTPUT, unsigned long long &OUTPUT { 
+  jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+  jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+  jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+  jobject bigint;
+  int i;
+
+  bae[0] = 0;
+  for(i=1; i<9; i++ ) {
+    bae[i] = (jbyte)(temp$argnum>>8*(8-i));
+  }
+
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+  bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+  JCALL3(SetObjectArrayElement, jenv, $input, 0, bigint);
+}
+
+/*
+INOUT typemaps
+--------------
+
+Mappings for a parameter that is both an input and an output parameter
+
+The following typemaps can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" typemaps described earlier.  Output values are
+returned as an element in a Java array.
+
+        bool               *INOUT, bool               &INOUT
+        signed char        *INOUT, signed char        &INOUT
+        unsigned char      *INOUT, unsigned char      &INOUT
+        short              *INOUT, short              &INOUT
+        unsigned short     *INOUT, unsigned short     &INOUT
+        int                *INOUT, int                &INOUT
+        unsigned int       *INOUT, unsigned int       &INOUT
+        long               *INOUT, long               &INOUT
+        unsigned long      *INOUT, unsigned long      &INOUT
+        long long          *INOUT, long long          &INOUT
+        unsigned long long *INOUT, unsigned long long &INOUT
+        float              *INOUT, float              &INOUT
+        double             *INOUT, double             &INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+This works similarly to C in that the mapping directly modifies the
+input value - the input must be an array with a minimum of one element. 
+The element in the array is the input and the output is the element in 
+the array.
+
+       double x[] = {5.0};
+       neg(x);
+
+The implementation of the OUTPUT and INOUT typemaps is different to other 
+languages in that other languages will return the output value as part 
+of the function return value. This difference is due to Java being a typed language.
+
+There are no char *INOUT typemaps, however you can apply the signed char * typemaps instead:
+        %include <typemaps.i>
+        %apply signed char *INOUT {char *inout};
+        void f(char *inout);
+*/
+
+%define INOUT_TYPEMAP(TYPE, JNITYPE, JTYPE, JAVATYPE, JNIDESC, TYPECHECKTYPE)
+%typemap(jni) TYPE *INOUT, TYPE &INOUT %{JNITYPE##Array%}
+%typemap(jtype) TYPE *INOUT, TYPE &INOUT "JTYPE[]"
+%typemap(jstype) TYPE *INOUT, TYPE &INOUT "JTYPE[]"
+%typemap(javain) TYPE *INOUT, TYPE &INOUT "$javainput"
+%typemap(javadirectorin) TYPE *INOUT, TYPE &INOUT "$jniinput"
+%typemap(javadirectorout) TYPE *INOUT, TYPE &INOUT "$javacall"
+
+%typemap(in) TYPE *INOUT, TYPE &INOUT {
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null");
+    return $null;
+  }
+  if (JCALL1(GetArrayLength, jenv, $input) == 0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
+    return $null;
+  }
+  $1 = ($1_ltype) JCALL2(Get##JAVATYPE##ArrayElements, jenv, $input, 0); 
+}
+
+%typemap(freearg) TYPE *INOUT, TYPE &INOUT ""
+
+%typemap(argout) TYPE *INOUT, TYPE &INOUT
+{ JCALL3(Release##JAVATYPE##ArrayElements, jenv, $input, (JNITYPE *)$1, 0); }
+
+%typemap(directorout,warning="Need to provide TYPE *INOUT directorout typemap") TYPE *INOUT, TYPE &INOUT {
+}
+
+%typemap(directorin,descriptor=JNIDESC) TYPE &INOUT
+%{ *(($&1_ltype)&$input) = &$1; %}
+
+%typemap(directorin,descriptor=JNIDESC,warning="Need to provide TYPE *INOUT directorin typemap, TYPE array length is unknown") TYPE *INOUT, TYPE &INOUT
+{
+}
+
+%typemap(typecheck) TYPE *INOUT = TYPECHECKTYPE;
+%typemap(typecheck) TYPE &INOUT = TYPECHECKTYPE;
+%enddef
+
+INOUT_TYPEMAP(bool, jboolean, boolean, Boolean, "[Ljava/lang/Boolean;", jbooleanArray); 
+INOUT_TYPEMAP(signed char, jbyte, byte, Byte, "[Ljava/lang/Byte;", jbyteArray); 
+INOUT_TYPEMAP(unsigned char, jshort, short, Short, "[Ljava/lang/Short;", jshortArray);     
+INOUT_TYPEMAP(short, jshort, short, Short, "[Ljava/lang/Short;", jshortArray);
+INOUT_TYPEMAP(unsigned short, jint, int, Int, "[Ljava/lang/Integer;", jintArray); 
+INOUT_TYPEMAP(int, jint, int, Int, "[Ljava/lang/Integer;", jintArray);
+INOUT_TYPEMAP(unsigned int, jlong, long, Long, "[Ljava/lang/Long;", jlongArray); 
+INOUT_TYPEMAP(long, jint, int, Int, "[Ljava/lang/Integer;", jintArray);
+INOUT_TYPEMAP(unsigned long, jlong, long, Long, "[Ljava/lang/Long;", jlongArray); 
+INOUT_TYPEMAP(long long, jlong, long, Long, "[Ljava/lang/Long;", jlongArray);
+INOUT_TYPEMAP(unsigned long long, jobject, java.math.BigInteger, NOTUSED, "[Ljava.math.BigInteger;", SWIGBIGINTEGERARRAY);
+INOUT_TYPEMAP(float, jfloat, float, Float, "[Ljava/lang/Float;", jfloatArray);
+INOUT_TYPEMAP(double, jdouble, double, Double, "[Ljava/lang/Double;", jdoubleArray); 
+
+#undef INOUT_TYPEMAP
+
+/* Override typemaps in the INOUT_TYPEMAP macro for booleans to fix casts
+   as a jboolean isn't always the same size as a bool */
+%typemap(in) bool *INOUT (bool btemp, jboolean *jbtemp), bool &INOUT (bool btemp, jboolean *jbtemp) {
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null");
+    return $null;
+  }
+  if (JCALL1(GetArrayLength, jenv, $input) == 0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
+    return $null;
+  }
+  jbtemp = JCALL2(GetBooleanArrayElements, jenv, $input, 0);
+  btemp = (*jbtemp) ? true : false;
+  $1 = &btemp;
+}
+
+%typemap(argout) bool *INOUT, bool &INOUT {
+  *jbtemp$argnum = btemp$argnum ? (jboolean)1 : (jboolean)0;
+  JCALL3(ReleaseBooleanArrayElements, jenv, $input , (jboolean *)jbtemp$argnum, 0);
+}
+
+/* Override the typemap in the INOUT_TYPEMAP macro for unsigned long long */
+%typemap(in) unsigned long long *INOUT ($*1_ltype temp), unsigned long long &INOUT ($*1_ltype temp) { 
+  jobject bigint;
+  jclass clazz;
+  jmethodID mid;
+  jbyteArray ba;
+  jbyte* bae;
+  jsize sz;
+  int i;
+
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null");
+    return $null;
+  }
+  if (JCALL1(GetArrayLength, jenv, $input) == 0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
+    return $null;
+  }
+  bigint = JCALL2(GetObjectArrayElement, jenv, $input, 0);
+  if (!bigint) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array element null");
+    return $null;
+  }
+  clazz = JCALL1(GetObjectClass, jenv, bigint);
+  mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+  ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, bigint, mid);
+  bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+  sz = JCALL1(GetArrayLength, jenv, ba);
+  temp = 0;
+  for(i=0; i<sz; i++) {
+    temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i];
+  }
+  JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+  $1 = &temp;
+}
+
+%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT;
+%typemap(argout) unsigned long long &INOUT = unsigned long long &OUTPUT;
diff --git a/trunk/Lib/java/various.i b/trunk/Lib/java/various.i
new file mode 100644
index 0000000..733b8fa
--- /dev/null
+++ b/trunk/Lib/java/various.i
@@ -0,0 +1,151 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * various.i
+ *
+ * SWIG Typemap library for Java.
+ * Various useful typemaps.
+ * ----------------------------------------------------------------------------- */
+
+/* 
+ * char **STRING_ARRAY typemaps. 
+ * These typemaps are for C String arrays which are NULL terminated.
+ *   char *values[] = { "one", "two", "three", NULL }; // note NULL
+ * char ** is mapped to a Java String[].
+ *
+ * Example usage wrapping:
+ *   %apply char **STRING_ARRAY { char **input };
+ *   char ** foo(char **input);
+ *  
+ * Java usage:
+ *   String numbers[] = { "one", "two", "three" };
+ *   String[] ret = modulename.foo( numbers };
+ */
+%typemap(jni) char **STRING_ARRAY "jobjectArray"
+%typemap(jtype) char **STRING_ARRAY "String[]"
+%typemap(jstype) char **STRING_ARRAY "String[]"
+%typemap(in) char **STRING_ARRAY (jint size) {
+    int i = 0;
+    size = JCALL1(GetArrayLength, jenv, $input);
+#ifdef __cplusplus
+    $1 = new char*[size+1];
+#else
+    $1 = (char **)calloc(size+1, sizeof(char *));
+#endif
+    for (i = 0; i<size; i++) {
+        jstring j_string = (jstring)JCALL2(GetObjectArrayElement, jenv, $input, i);
+        const char *c_string = JCALL2(GetStringUTFChars, jenv, j_string, 0);
+#ifdef __cplusplus
+        $1[i] = new char [strlen(c_string)+1];
+#else
+        $1[i] = (char *)calloc(strlen(c_string)+1, sizeof(const char *));
+#endif
+        strcpy($1[i], c_string);
+        JCALL2(ReleaseStringUTFChars, jenv, j_string, c_string);
+        JCALL1(DeleteLocalRef, jenv, j_string);
+    }
+    $1[i] = 0;
+}
+
+%typemap(freearg) char **STRING_ARRAY {
+    int i;
+    for (i=0; i<size$argnum-1; i++)
+#ifdef __cplusplus
+      delete[] $1[i];
+    delete[] $1;
+#else
+      free($1[i]);
+    free($1);
+#endif
+}
+
+%typemap(out) char **STRING_ARRAY {
+    int i;
+    int len=0;
+    jstring temp_string;
+    const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
+
+    while ($1[len]) len++;    
+    jresult = JCALL3(NewObjectArray, jenv, len, clazz, NULL);
+    /* exception checking omitted */
+
+    for (i=0; i<len; i++) {
+      temp_string = JCALL1(NewStringUTF, jenv, *result++);
+      JCALL3(SetObjectArrayElement, jenv, jresult, i, temp_string);
+      JCALL1(DeleteLocalRef, jenv, temp_string);
+    }
+}
+
+%typemap(javain) char **STRING_ARRAY "$javainput"
+%typemap(javaout) char **STRING_ARRAY  {
+    return $jnicall;
+  }
+
+/* 
+ * char **STRING_OUT typemaps. 
+ * These are typemaps for returning strings when using a C char ** parameter type.
+ * The returned string appears in the 1st element of the passed in Java String array.
+ *
+ * Example usage wrapping:
+ *   void foo(char **string_out);
+ *  
+ * Java usage:
+ *   String stringOutArray[] = { "" };
+ *   modulename.foo(stringOutArray);
+ *   System.out.println( stringOutArray[0] );
+ */
+%typemap(jni) char **STRING_OUT "jobjectArray"
+%typemap(jtype) char **STRING_OUT "String[]"
+%typemap(jstype) char **STRING_OUT "String[]"
+%typemap(javain) char **STRING_OUT "$javainput"
+
+%typemap(in) char **STRING_OUT($*1_ltype temp) {
+  if (!$input) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null");
+    return $null;
+  }
+  if (JCALL1(GetArrayLength, jenv, $input) == 0) {
+    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
+    return $null;
+  }
+  $1 = &temp; 
+}
+
+%typemap(argout) char **STRING_OUT {
+  jstring jnewstring = NULL;
+  if($1) {
+     jnewstring = JCALL1(NewStringUTF, jenv, *$1);
+  }
+  JCALL3(SetObjectArrayElement, jenv, $input, 0, jnewstring); 
+}
+
+/* 
+ * char *BYTE typemaps. 
+ * These are input typemaps for mapping a Java byte[] array to a C char array.
+ * Note that as a Java array is used and thus passeed by reference, the C routine 
+ * can return data to Java via the parameter.
+ *
+ * Example usage wrapping:
+ *   void foo(char *array);
+ *  
+ * Java usage:
+ *   byte b[] = new byte[20];
+ *   modulename.foo(b);
+ */
+%typemap(jni) char *BYTE "jbyteArray"
+%typemap(jtype) char *BYTE "byte[]"
+%typemap(jstype) char *BYTE "byte[]"
+%typemap(in) char *BYTE {
+    $1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0); 
+}
+
+%typemap(argout) char *BYTE {
+    JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *) $1, 0); 
+}
+
+%typemap(javain) char *BYTE "$javainput"
+
+/* Prevent default freearg typemap from being used */
+%typemap(freearg) char *BYTE ""
+
diff --git a/trunk/Lib/linkruntime.c b/trunk/Lib/linkruntime.c
new file mode 100644
index 0000000..ddc7812
--- /dev/null
+++ b/trunk/Lib/linkruntime.c
@@ -0,0 +1,22 @@
+#ifndef SWIGEXPORT
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   if defined(STATIC_LINKED)
+#     define SWIGEXPORT
+#   else
+#     define SWIGEXPORT __declspec(dllexport)
+#   endif
+# else
+#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
+#     define SWIGEXPORT __attribute__ ((visibility("default")))
+#   else
+#     define SWIGEXPORT
+#   endif
+# endif
+#endif
+
+static void *ptr = 0;
+SWIGEXPORT void *
+SWIG_ReturnGlobalTypeList(void *t) {
+ if (!ptr && !t) ptr = t;
+ return ptr;
+}
diff --git a/trunk/Lib/lua/_std_common.i b/trunk/Lib/lua/_std_common.i
new file mode 100644
index 0000000..33cc513
--- /dev/null
+++ b/trunk/Lib/lua/_std_common.i
@@ -0,0 +1,96 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * _std_common.i
+ *
+ * std::helpers for LUA
+ * ----------------------------------------------------------------------------- */
+
+%include <std_except.i> // the general exepctions
+
+/*
+The basic idea here, is instead of trying to feed SWIG all the
+horribly templated STL code, to give it a neatened version.
+
+These %defines cover some of the more common methods
+so the class declarations become just a set of %defines
+
+*/
+
+/* #define for basic container features
+note: I allow front(), back() & pop_back() to throw execptions
+upon empty containers, rather than coredump
+(as we have'nt defined the methods, we can use %extend to add with
+new features)
+
+*/
+%define %STD_CONTAINER_METHODS(CLASS,T)
+public:
+	CLASS();
+	CLASS(const CLASS&);
+	unsigned int size() const;
+	unsigned int max_size() const;
+	bool empty() const;
+	void clear();
+	%extend {	// the extra stuff which must be checked
+		T front()const throw (std::out_of_range){ // only read front & back
+			if (self->empty())
+				throw std::out_of_range("in "#CLASS"::front()");
+			return self->front();
+		}
+		T back()const throw (std::out_of_range){ // not write to them
+			if (self->empty())
+				throw std::out_of_range("in "#CLASS"::back()");
+			return self->back();
+		}
+	}
+%enddef
+
+/* push/pop for front/back
+also note: front & back are read only methods, not used for writing
+*/
+%define %STD_FRONT_ACCESS_METHODS(CLASS,T)
+public:
+	void push_front(const T& val);
+	%extend {	// must check this
+		void pop_front() throw (std::out_of_range){
+			if (self->empty())
+				throw std::out_of_range("in "#CLASS"::pop_front()");
+			self->pop_back();
+		}
+	}
+%enddef
+
+%define %STD_BACK_ACCESS_METHODS(CLASS,T)
+public:
+	void push_back(const T& val);
+	%extend {	// must check this
+		void pop_back() throw (std::out_of_range){
+			if (self->empty())
+				throw std::out_of_range("in "#CLASS"::pop_back()");
+			self->pop_back();
+		}
+	}
+%enddef
+
+/*
+Random access methods
+*/
+%define %STD_RANDOM_ACCESS_METHODS(CLASS,T)
+	%extend // this is a extra bit of SWIG code
+	{
+		// [] is replaced by __getitem__ & __setitem__
+		// simply throws a string, which causes a lua error
+		T __getitem__(unsigned int idx) throw (std::out_of_range){
+			if (idx>=self->size())
+				throw std::out_of_range("in "#CLASS"::__getitem__()");
+			return (*self)[idx];
+		}
+		void __setitem__(unsigned int idx,const T& val) throw (std::out_of_range){
+			if (idx>=self->size())
+				throw std::out_of_range("in "#CLASS"::__setitem__()");
+			(*self)[idx]=val;
+		}
+	};
+%enddef
diff --git a/trunk/Lib/lua/carrays.i b/trunk/Lib/lua/carrays.i
new file mode 100644
index 0000000..9a210d2
--- /dev/null
+++ b/trunk/Lib/lua/carrays.i
@@ -0,0 +1,8 @@
+/* Small change to the standard carrays.i
+renaming the field to __getitem__ & __setitem__ 
+for operator[] access
+*/
+%rename(__getitem) *::getitem; // the v=X[i] (get operator)
+%rename(__setitem) *::setitem; // the X[i]=v (set operator)
+
+%include <../carrays.i>
diff --git a/trunk/Lib/lua/lua.swg b/trunk/Lib/lua/lua.swg
new file mode 100644
index 0000000..b6d8886
--- /dev/null
+++ b/trunk/Lib/lua/lua.swg
@@ -0,0 +1,235 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * lua.swg
+ *
+ * SWIG Configuration File for Lua.
+ * This file is parsed by SWIG before reading any other interface file.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ *                          includes
+ * ----------------------------------------------------------------------------- */
+
+%include <luatypemaps.swg>          /* The typemaps */
+%include <luaruntime.swg>          /* The runtime stuff */
+
+//%include <typemaps/swigmacros.swg>
+/* -----------------------------------------------------------------------------
+ *                          constants typemaps
+ * ----------------------------------------------------------------------------- */
+// this basically adds to a table of constants
+%typemap(consttab) int, unsigned int, short, unsigned short, long, unsigned long, unsigned char, signed char, bool, enum SWIGTYPE
+       { SWIG_LUA_INT,     (char *)"$symname", (long) $value, 0, 0, 0}
+
+%typemap(consttab) float, double
+       { SWIG_LUA_FLOAT,   (char *)"$symname", 0, (double) $value, 0, 0}
+
+%typemap(consttab) long long, unsigned long long, signed long long
+       { SWIG_LUA_FLOAT,   (char *)"$symname", 0, (double) $value, 0, 0}
+
+%typemap(consttab) const long long&, const unsigned long long&, const signed long long&
+       { SWIG_LUA_FLOAT,   (char *)"$symname", 0, (double) *$value, 0, 0}
+
+%typemap(consttab) char *, const char *, char [], const char []
+       { SWIG_LUA_STRING,  (char *)"$symname", 0, 0, (void *)$value, 0}
+
+// note: char is treated as a seperate special type
+// signed char & unsigned char are numbers
+%typemap(consttab) char
+       { SWIG_LUA_CHAR,  (char *)"$symname", (long)$value, 0, 0, 0}
+
+%typemap(consttab) long long, unsigned long long
+       { SWIG_LUA_STRING, (char *) "$symname", 0, 0, (void *)"$value", 0}
+
+%typemap(consttab) SWIGTYPE *, SWIGTYPE &, SWIGTYPE []
+       { SWIG_LUA_POINTER, (char *)"$symname", 0, 0, (void *)$value, &$1_descriptor}
+
+// member function pointers
+%typemap(consttab) SWIGTYPE (CLASS::*)
+       { SWIG_LUA_BINARY,  (char *)"$symname", sizeof($type), 0, (void *)&$value, &$1_descriptor}
+
+
+/* -----------------------------------------------------------------------------
+ *                          Overloaded operator support
+ * ----------------------------------------------------------------------------- */
+// lua calls the + operator '__add'
+// python likes to call it '__add__'
+// Assuming most SWIGers will probably use the __add__ if they extend their classes
+// we have two sets of renames
+// one to rename the operator+() to __add()
+//	(this lets SWIG rename the operator overloads)
+// another is to rename __add__() to __add()
+//	(this means that people who wrote SWIG code to do that add will also work)
+
+#ifdef __cplusplus
+// this is extra renaming for lua
+// not all operators are supported, so only those that are, are listed
+%rename(__add)			*::operator+;
+%rename(__sub)			*::operator-;
+%rename(__mul)			*::operator*;
+%rename(__div)			*::operator/;
+%rename(__unm)      *::operator-();
+%rename(__unm)      *::operator-() const;
+
+%rename(__eq)			*::operator==;	
+%ignore *::operator!=;      // note: Lua does not have a notequal operator
+						// it just uses 'not (a==b)'
+%rename(__lt)			*::operator<;
+%ignore *::operator>;   	// ditto less than vs greater than
+%rename(__le)			*::operator<=;	
+%ignore *::operator>=;  // ditto less than vs greater than
+%ignore *::operator!;  // does not support not
+
+%rename(__call)			*::operator();	// the fn call operator
+
+// lua does not support overloading of:
+// 	logical/bitwise operators
+// 	assign operator
+// 	+=,-=,*=, etc
+// therefore ignoring them for now
+// it also doesn't support non class operators
+// eg friends or XX operator+(XX,XX)
+// also ignoring
+// note: some of these might be better to rename, but not doing that for now
+%ignore *::operator&&;	%ignore operator&&;
+%ignore *::operator||;	%ignore operator||;
+%ignore *::operator+=;
+%ignore *::operator-=;
+%ignore *::operator*=;
+%ignore *::operator/=;
+%ignore *::operator%=;
+%ignore *::operator++;	%ignore *::operator--;
+
+%ignore *::operator=;	// note: this might be better to rename to assign() or similar
+
+%ignore operator+;
+%ignore operator-;
+%ignore operator*;
+%ignore operator/;
+%ignore operator%;
+%ignore operator[];
+%ignore operator>;	%ignore operator>=;	
+%ignore operator<;	%ignore operator<=;
+%ignore operator==;	%ignore operator!=;
+
+
+// renaming the python operators to be compatible with lua
+// this means that if a developer has written a fn __add__()
+// it will be used for the lua +
+%rename(__add)			*::__add__;
+%rename(__sub)			*::__sub__;
+%rename(__mul)			*::__mul__;
+%rename(__div)			*::__div__;
+%rename(__unm)			*::__neg__;		// lua calls unary minus,'unm' not 'neg'
+%rename(__tostring)		*::__str__;		// both map to __tostring
+%rename(__tostring)		*::__repr__;	// both map to __tostring
+
+
+%rename(__pow)			*::__pow__;		// lua power '^' operator
+%rename(__concat)		*::__concat__;  // lua concat '..' operator
+%rename(__eq)			*::__eq__;
+%rename(__lt)			*::__lt__;
+%rename(__le)			*::__le__;
+%rename(__call)			*::__call__;	// the fn call operator()
+
+// the [] operator has two parts, the get & the set
+%rename(__getitem)			*::__getitem__;	// the v=X[i] (get operator)
+%rename(__setitem)			*::__setitem__;	// the X[i]=v (set operator)
+
+
+#endif
+
+
+/* ------------------------------------------------------------
+ *                              Exceptions
+ * ------------------------------------------------------------ */
+/* Confession: I dont really like C++ exceptions
+The python/lua ones are great, but C++ ones I dont like
+(mainly because I cannot get the stack trace out of it)
+Therefore I have not bothered to try doing much in this
+
+Therefore currently its just enough to get a few test cases running ok
+
+note: if you wish to throw anything related to std::exception
+use %include <std_except.i> instead
+*/
+
+// number as number+error
+%typemap(throws) int,unsigned int,signed int,
+				long,unsigned long,signed long,
+				short,unsigned short,signed short,
+				float,double,
+				long long,unsigned long long,
+				unsigned char, signed char,
+                int&,unsigned int&,signed int&,
+				long&,unsigned long&,signed long&,
+				short&,unsigned short&,signed short&,
+				float&,double&,
+				long long&,unsigned long long&,
+				unsigned char&, signed char&
+%{lua_pushnumber(L,(lua_Number)$1);SWIG_fail; %}
+
+%typemap(throws) bool,bool& 
+%{lua_pushboolean(L,(int)($1==true));SWIG_fail; %}
+
+// enum as number+error
+%typemap(throws) enum SWIGTYPE
+%{lua_pushnumber(L,(lua_Number)(int)$1);SWIG_fail; %}
+
+// strings are just sent as errors
+%typemap(throws) char*, const char*
+%{lua_pushstring(L,$1);SWIG_fail;%}
+
+// char is changed to a string
+%typemap(throws) char
+%{lua_pushfstring(L,"%c",$1);SWIG_fail;%}
+
+/*
+Throwing object is a serious problem:
+Assuming some code throws a 'FooBar'
+There are a few options:
+- return a pointer to it: but its unclear how long this will last for.
+- return a copy of it: but not all objects are copyable
+	(see exception_partial_info in the test suite for a case where you cannot do this)
+- convert to a string & throw that
+	its not so useful, but it works (this is more lua like).
+The third option (though not nice) is used
+For a more useful solution: see std_except for more details
+*/
+
+// basic typemap for structs, classes, pointers & references
+// convert to string and error
+%typemap(throws) SWIGTYPE
+%{(void)$1; /* ignore it */
+lua_pushfstring(L,"object exception:%s",SWIG_TypePrettyName($1_descriptor));
+SWIG_fail;%}
+
+// code to make a copy of the object and return this
+// if you have a function which throws a FooBar & you want SWIG to return a copy of the object as its error
+// then use one of the below
+//	%apply SWIGTYPE EXCEPTION_BY_VAL {FooBar};
+//	%apply SWIGTYPE& EXCEPTION_BY_VAL {FooBar&}; // note: need & twice
+%typemap(throws) SWIGTYPE EXCEPTION_BY_VAL
+%{SWIG_NewPointerObj(L,(void *)new $1_ltype(($1_ltype &) $1),$&1_descriptor,1);
+SWIG_fail;%}
+
+// similar for object reference
+// note: swig typemaps seem a little confused around here, therefore we use $basetype
+%typemap(throws) SWIGTYPE& EXCEPTION_BY_VAL
+%{SWIG_NewPointerObj(L,(void *)new $basetype($1),$1_descriptor,1);
+SWIG_fail;%}
+
+
+// note: no support for object pointers
+// its not clear how long the pointer is valid for, therefore not supporting it
+
+/* -----------------------------------------------------------------------------
+ *                          extras
+ * ----------------------------------------------------------------------------- */
+// this %define is to allow insertion of lua source code into the wrapper file
+#define %luacode  %insert("luacode")
+
+
+/* ------------------------------ end lua.swg  ------------------------------ */
diff --git a/trunk/Lib/lua/lua_fnptr.i b/trunk/Lib/lua/lua_fnptr.i
new file mode 100644
index 0000000..c7df6f5
--- /dev/null
+++ b/trunk/Lib/lua/lua_fnptr.i
@@ -0,0 +1,128 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * lua_fnptr.i
+ *
+ * SWIG Library file containing the main typemap code to support Lua modules.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ *                          Basic function pointer support
+ * ----------------------------------------------------------------------------- */
+/*
+The structure: SWIGLUA_FN provides a simple (local only) wrappering for a function.
+
+For example if you wanted to have a C/C++ function take a lua function as a parameter.
+You could declare it as:
+  int my_func(int a, int b, SWIGLUA_FN fn);
+note: it should be passed by value, not byref or as a pointer.
+
+The SWIGLUA_FN holds a pointer to the lua_State, and the stack index where the function is held.
+The macro SWIGLUA_FN_GET() will put a copy of the lua function at the top of the stack.
+After that its fairly simple to write the rest of the code (assuming know how to use lua),
+just push the parameters, call the function and return the result.
+
+  int my_func(int a, int b, SWIGLUA_FN fn)
+  {
+    SWIGLUA_FN_GET(fn);
+    lua_pushnumber(fn.L,a);
+    lua_pushnumber(fn.L,b);
+    lua_call(fn.L,2,1);    // 2 in, 1 out
+    return luaL_checknumber(fn.L,-1);
+  }
+
+SWIG will automatically performs the wrappering of the arguments in and out.
+
+However: if you wish to store the function between calls, look to the SWIGLUA_REF below.
+
+*/
+// this is for the C code only, we don't want SWIG to wrapper it for us.
+%{
+typedef struct{
+  lua_State* L; /* the state */
+  int idx;      /* the index on the stack */
+}SWIGLUA_FN;
+
+#define SWIGLUA_FN_GET(fn) {lua_pushvalue(fn.L,fn.idx);}
+%}
+
+// the actual typemap
+%typemap(in,checkfn="lua_isfunction") SWIGLUA_FN
+%{  $1.L=L; $1.idx=$input; %}
+
+/* -----------------------------------------------------------------------------
+ *                          Storing lua object support
+ * ----------------------------------------------------------------------------- */
+/*
+The structure: SWIGLUA_REF provides a mechanism to store object (usually functions)
+between calls to the interpreter.
+
+For example if you wanted to have a C/C++ function take a lua function as a parameter.
+Then call it later, You could declare it as:
+  SWIGLUA_REF myref;
+  void set_func(SWIGLUA_REF ref);
+  SWIGLUA_REF get_func();
+  void call_func(int val);
+note: it should be passed by value, not byref or as a pointer.
+
+The SWIGLUA_REF holds a pointer to the lua_State, and an integer reference to the object.
+Because it holds a permenet ref to an object, the SWIGLUA_REF must be handled with a bit more care.
+It should be initalised to {0,0}. The function swiglua_ref_set() should be used to set it.
+swiglua_ref_clear() should be used to clear it when not in use, and swiglua_ref_get() to get the
+data back.
+
+Note: the typemap does not check that the object is in fact a function,
+if you need that you must add it yourself.
+
+
+  int my_func(int a, int b, SWIGLUA_FN fn)
+  {
+    SWIGLUA_FN_GET(fn);
+    lua_pushnumber(fn.L,a);
+    lua_pushnumber(fn.L,b);
+    lua_call(fn.L,2,1);    // 2 in, 1 out
+    return luaL_checknumber(fn.L,-1);
+  }
+
+SWIG will automatically performs the wrappering of the arguments in and out.
+
+However: if you wish to store the function between calls, look to the SWIGLUA_REF below.
+
+*/
+
+%{
+typedef struct{
+  lua_State* L; /* the state */
+  int ref;      /* a ref in the lua global index */
+}SWIGLUA_REF;
+
+
+void swiglua_ref_clear(SWIGLUA_REF* pref){
+ 	if (pref->L!=0 && pref->ref!=LUA_NOREF && pref->ref!=LUA_REFNIL){
+		luaL_unref(pref->L,LUA_REGISTRYINDEX,pref->ref);
+	}
+	pref->L=0; pref->ref=0;
+}
+
+void swiglua_ref_set(SWIGLUA_REF* pref,lua_State* L,int idx){
+//	swiglua_ref_clear(pref); /* just in case */
+	pref->L=L;
+	lua_pushvalue(L,idx);                 /* copy obj to top */
+	pref->ref=luaL_ref(L,LUA_REGISTRYINDEX); /* remove obj from top & put into registry */
+}
+
+void swiglua_ref_get(SWIGLUA_REF* pref){
+	if (pref->L!=0)
+		lua_rawgeti(pref->L,LUA_REGISTRYINDEX,pref->ref);
+}
+
+%}
+
+%typemap(in) SWIGLUA_REF
+%{  swiglua_ref_set(&$1,L,$input); %}
+
+%typemap(out) SWIGLUA_REF
+%{  if ($1.L!=0)  {swiglua_ref_get(&$1);} else {lua_pushnil(L);}
+  SWIG_arg++; %}
+
diff --git a/trunk/Lib/lua/luarun.swg b/trunk/Lib/lua/luarun.swg
new file mode 100644
index 0000000..32e1b16
--- /dev/null
+++ b/trunk/Lib/lua/luarun.swg
@@ -0,0 +1,778 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * luarun.swg
+ *
+ * This file contains the runtime support for Lua modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "lua.h"
+#include "lauxlib.h"
+#include <stdlib.h>  /* for malloc */
+#include <assert.h>  /* for a few sanity tests */
+
+/* -----------------------------------------------------------------------------
+ * global swig types
+ * ----------------------------------------------------------------------------- */
+/* Constant table */
+#define SWIG_LUA_INT     1
+#define SWIG_LUA_FLOAT   2
+#define SWIG_LUA_STRING  3
+#define SWIG_LUA_POINTER 4
+#define SWIG_LUA_BINARY  5
+#define SWIG_LUA_CHAR    6
+
+/* Structure for variable linking table */
+typedef struct {
+  const char *name;
+  lua_CFunction get;
+  lua_CFunction set;
+} swig_lua_var_info;
+
+/* Constant information structure */
+typedef struct {
+    int type;
+    char *name;
+    long lvalue;
+    double dvalue;
+    void   *pvalue;
+    swig_type_info **ptype;
+} swig_lua_const_info;
+
+typedef struct {
+  const char     *name;
+  lua_CFunction   method;
+} swig_lua_method;
+
+typedef struct {
+  const char     *name;
+  lua_CFunction   getmethod;
+  lua_CFunction   setmethod;
+} swig_lua_attribute;
+
+typedef struct swig_lua_class {
+  const char    *name;
+  swig_type_info   **type;
+  lua_CFunction  constructor;
+  void    (*destructor)(void *);
+  swig_lua_method   *methods;
+  swig_lua_attribute     *attributes;
+  struct swig_lua_class **bases;
+  const char **base_names;
+} swig_lua_class;
+
+/* this is the struct for wrappering all pointers in SwigLua
+*/
+typedef struct {
+  swig_type_info   *type;
+  int     own;  /* 1 if owned & must be destroyed */
+  void        *ptr;
+} swig_lua_userdata;
+
+/* this is the struct for wrapping arbitary packed binary data
+(currently it is only used for member function pointers)
+the data ordering is similar to swig_lua_userdata, but it is currently not possible
+to tell the two structures apart within Swig, other than by looking at the type
+*/
+typedef struct {
+  swig_type_info   *type;
+  int     own;  /* 1 if owned & must be destroyed */
+  char data[1];       /* arbitary amount of data */    
+} swig_lua_rawdata;
+
+/* Common SWIG API */
+#define SWIG_NewPointerObj(L, ptr, type, owner)       SWIG_Lua_NewPointerObj(L, (void *)ptr, type, owner)
+#define SWIG_ConvertPtr(L,idx, ptr, type, flags)    SWIG_Lua_ConvertPtr(L,idx,ptr,type,flags)
+#define SWIG_MustGetPtr(L,idx, type,flags, argnum,fnname)  SWIG_Lua_MustGetPtr(L,idx, type,flags, argnum,fnname)
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(L, idx, ptr, sz, ty)       SWIG_Lua_ConvertPacked(L, idx, ptr, sz, ty)
+#define SWIG_NewMemberObj(L, ptr, sz, type)      SWIG_Lua_NewPackedObj(L, ptr, sz, type)
+
+/* Runtime API */
+#define SWIG_GetModule(clientdata) SWIG_Lua_GetModule((lua_State*)(clientdata))
+#define SWIG_SetModule(clientdata, pointer) SWIG_Lua_SetModule((lua_State*) (clientdata), pointer)
+#define SWIG_MODULE_CLIENTDATA_TYPE lua_State*
+
+/* Contract support */
+#define SWIG_contract_assert(expr, msg)  \
+  if (!(expr)) { lua_pushstring(L, (char *) msg); goto fail; } else
+
+/* helper #defines */
+#define SWIG_fail {goto fail;}
+#define SWIG_fail_arg(func_name,argnum,type) \
+  {lua_pushfstring(L,"Error in %s (arg %d), expected '%s' got '%s'",\
+  func_name,argnum,type,SWIG_Lua_typename(L,argnum));\
+  goto fail;}
+#define SWIG_fail_ptr(func_name,argnum,type) \
+  SWIG_fail_arg(func_name,argnum,(type && type->str)?type->str:"void*")
+#define SWIG_check_num_args(func_name,a,b) \
+  if (lua_gettop(L)<a || lua_gettop(L)>b) \
+  {lua_pushfstring(L,"Error in %s expected %d..%d args, got %d",func_name,a,b,lua_gettop(L));\
+  goto fail;}
+
+
+#define SWIG_Lua_get_table(L,n) \
+  (lua_pushstring(L, n), lua_rawget(L,-2))
+
+#define SWIG_Lua_add_function(L,n,f) \
+  (lua_pushstring(L, n), \
+      lua_pushcfunction(L, f), \
+      lua_rawset(L,-3))
+
+/* special helper for allowing 'nil' for usertypes */
+#define SWIG_isptrtype(L,I) (lua_isuserdata(L,I) || lua_isnil(L,I))
+
+#ifdef __cplusplus
+/* Special helper for member function pointers 
+it gets the address, casts it, then dereferences it */
+//#define SWIG_mem_fn_as_voidptr(a)  (*((char**)&(a)))
+#endif
+
+/* storing/access of swig_module_info */
+SWIGRUNTIME swig_module_info *
+SWIG_Lua_GetModule(lua_State* L) {
+  swig_module_info *ret = 0;
+  lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  lua_rawget(L,LUA_REGISTRYINDEX);
+  if (lua_islightuserdata(L,-1))
+    ret=(swig_module_info*)lua_touserdata(L,-1);
+  lua_pop(L,1);  /* tidy */
+  return ret;
+}
+
+SWIGRUNTIME void
+SWIG_Lua_SetModule(lua_State* L, swig_module_info *module) {
+  /* add this all into the Lua registry: */
+  lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  lua_pushlightuserdata(L,(void*)module);
+  lua_rawset(L,LUA_REGISTRYINDEX);
+}
+
+/* -----------------------------------------------------------------------------
+ * global variable support code: modules
+ * ----------------------------------------------------------------------------- */
+
+/* this function is called when trying to set an immutable.
+default value is to print an error.
+This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */
+SWIGINTERN int SWIG_Lua_set_immutable(lua_State* L)
+{
+/*  there should be 1 param passed in: the new value */
+#ifndef SWIGLUA_IGNORE_SET_IMMUTABLE
+  lua_pop(L,1);  /* remove it */
+  lua_pushstring(L,"This variable is immutable");
+  lua_error(L);
+#endif
+    return 0;   /* should not return anything */
+}
+
+/* the module.get method used for getting linked data */
+SWIGINTERN int SWIG_Lua_module_get(lua_State* L)
+{
+/*  there should be 2 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  printf("SWIG_Lua_module_get %p(%s) '%s'\n",
+   lua_topointer(L,1),lua_typename(L,lua_type(L,1)),
+   lua_tostring(L,2));
+*/
+  /* get the metatable */
+  assert(lua_istable(L,1));  /* just in case */
+  lua_getmetatable(L,1);  /* get the metatable */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get");  /* get the .get table */
+  lua_remove(L,3);  /* remove metatable */
+  if (lua_istable(L,-1))
+  {
+    /* look for the key in the .get table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    lua_remove(L,3);  /* remove .get */
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_call(L,0,1);
+      return 1;
+    }
+    lua_pop(L,1);  /* remove the top */
+  }
+  lua_pop(L,1);  /* remove the .get */
+  lua_pushnil(L);  /* return a nil */
+    return 1;
+}
+
+/* the module.set method used for setting linked data */
+SWIGINTERN int SWIG_Lua_module_set(lua_State* L)
+{
+/*  there should be 3 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  (3) any for the new value
+*/
+  /* get the metatable */
+  assert(lua_istable(L,1));  /* just in case */
+  lua_getmetatable(L,1);  /* get the metatable */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".set");  /* get the .set table */
+  lua_remove(L,4);  /* remove metatable */
+  if (lua_istable(L,-1))
+  {
+    /* look for the key in the .set table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    lua_remove(L,4);  /* remove .set */
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_pushvalue(L,3);  /* value */
+      lua_call(L,1,0);
+      return 0;
+    }
+  }
+  lua_settop(L,3);  /* reset back to start */
+  /* we now have the table, key & new value, so just set directly */
+  lua_rawset(L,1);  /* add direct */
+  return 0;
+}
+
+/* registering a module in lua */
+SWIGINTERN void  SWIG_Lua_module_begin(lua_State* L,const char* name)
+{
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_pushstring(L,name);
+  lua_newtable(L);   /* the table */
+  /* add meta table */
+  lua_newtable(L);    /* the meta table */
+  SWIG_Lua_add_function(L,"__index",SWIG_Lua_module_get);
+  SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_module_set);
+  lua_pushstring(L,".get");
+  lua_newtable(L);    /* the .get table */
+  lua_rawset(L,-3);  /* add .get into metatable */
+  lua_pushstring(L,".set");
+  lua_newtable(L);    /* the .set table */
+  lua_rawset(L,-3);  /* add .set into metatable */
+  lua_setmetatable(L,-2);  /* sets meta table in module */
+  lua_rawset(L,-3);        /* add module into parent */
+  SWIG_Lua_get_table(L,name);   /* get the table back out */
+}
+
+/* ending the register */
+SWIGINTERN void  SWIG_Lua_module_end(lua_State* L)
+{
+  lua_pop(L,1);       /* tidy stack (remove module) */
+}
+
+/* adding a linked variable to the module */
+SWIGINTERN void SWIG_Lua_module_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn)
+{
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_getmetatable(L,-1);  /* get the metatable */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* should be a table: */
+  SWIG_Lua_add_function(L,name,getFn);
+  lua_pop(L,1);       /* tidy stack (remove table) */
+  if (setFn)  /* if there is a set fn */
+  {
+    SWIG_Lua_get_table(L,".set"); /* find the .set table */
+    assert(lua_istable(L,-1));  /* should be a table: */
+    SWIG_Lua_add_function(L,name,setFn);
+    lua_pop(L,1);       /* tidy stack (remove table) */
+  }
+  lua_pop(L,1);       /* tidy stack (remove meta) */
+}
+
+/* adding a function module */
+SWIGINTERN void  SWIG_Lua_module_add_function(lua_State* L,const char* name,lua_CFunction fn)
+{
+  SWIG_Lua_add_function(L,name,fn);
+}
+
+/* -----------------------------------------------------------------------------
+ * global variable support code: classes
+ * ----------------------------------------------------------------------------- */
+
+/* the class.get method, performs the lookup of class attributes */
+SWIGINTERN int  SWIG_Lua_class_get(lua_State* L)
+{
+/*  there should be 2 params passed in
+  (1) userdata (not the meta table)
+  (2) string name of the attribute
+*/
+  assert(lua_isuserdata(L,-2));  /* just in case */
+  lua_getmetatable(L,-2);    /* get the meta table */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  /* look for the key in the .get table */
+  lua_pushvalue(L,2);  /* key */
+  lua_rawget(L,-2);
+  lua_remove(L,-2); /* stack tidy, remove .get table */
+  if (lua_iscfunction(L,-1))
+  {  /* found it so call the fn & return its value */
+    lua_pushvalue(L,1);  /* the userdata */
+    lua_call(L,1,1);  /* 1 value in (userdata),1 out (result) */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  lua_pop(L,1);  /* remove whatever was there */
+  /* ok, so try the .fn table */
+  SWIG_Lua_get_table(L,".fn"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_pushvalue(L,2);  /* key */
+  lua_rawget(L,-2);  /* look for the fn */
+  lua_remove(L,-2); /* stack tidy, remove .fn table */
+  if (lua_isfunction(L,-1)) /* note: if its a C function or lua function */
+  {  /* found it so return the fn & let lua call it */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  lua_pop(L,1);  /* remove whatever was there */
+  /* NEW: looks for the __getitem() fn
+  this is a user provided get fn */
+  SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */
+  if (lua_iscfunction(L,-1))  /* if its there */
+  {  /* found it so call the fn & return its value */
+    lua_pushvalue(L,1);  /* the userdata */
+    lua_pushvalue(L,2);  /* the parameter */
+    lua_call(L,2,1);  /* 2 value in (userdata),1 out (result) */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  return 0;  /* sorry not known */
+}
+
+/* the class.set method, performs the lookup of class attributes */
+SWIGINTERN int  SWIG_Lua_class_set(lua_State* L)
+{
+/*  there should be 3 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  (3) any for the new value
+printf("SWIG_Lua_class_set %p(%s) '%s' %p(%s)\n",
+      lua_topointer(L,1),lua_typename(L,lua_type(L,1)),
+      lua_tostring(L,2),
+      lua_topointer(L,3),lua_typename(L,lua_type(L,3)));*/
+
+  assert(lua_isuserdata(L,1));  /* just in case */
+  lua_getmetatable(L,1);    /* get the meta table */
+  assert(lua_istable(L,-1));  /* just in case */
+
+  SWIG_Lua_get_table(L,".set"); /* find the .set table */
+  if (lua_istable(L,-1))
+  {
+    /* look for the key in the .set table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_pushvalue(L,1);  /* userdata */
+      lua_pushvalue(L,3);  /* value */
+      lua_call(L,2,0);
+      return 0;
+    }
+    lua_pop(L,1);  /* remove the value */
+  }
+  lua_pop(L,1);  /* remove the value .set table */
+  /* NEW: looks for the __setitem() fn
+  this is a user provided set fn */
+  SWIG_Lua_get_table(L,"__setitem"); /* find the fn */
+  if (lua_iscfunction(L,-1))  /* if its there */
+  {  /* found it so call the fn & return its value */
+    lua_pushvalue(L,1);  /* the userdata */
+    lua_pushvalue(L,2);  /* the parameter */
+    lua_pushvalue(L,3);  /* the value */
+    lua_call(L,3,0);  /* 3 values in ,0 out */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  return 0;
+}
+
+/* the class.destruct method called by the interpreter */
+SWIGINTERN int  SWIG_Lua_class_destruct(lua_State* L)
+{
+/*  there should be 1 params passed in
+  (1) userdata (not the meta table) */
+  swig_lua_userdata* usr;
+  swig_lua_class* clss;
+  assert(lua_isuserdata(L,-1));  /* just in case */
+  usr=(swig_lua_userdata*)lua_touserdata(L,-1);  /* get it */
+  /* if must be destroyed & has a destructor */
+  if (usr->own) /* if must be destroyed */
+  {
+    clss=(swig_lua_class*)usr->type->clientdata;  /* get the class */
+    if (clss && clss->destructor)  /* there is a destroy fn */
+    {
+      clss->destructor(usr->ptr);  /* bye bye */
+    }
+  }
+  return 0;
+}
+
+/* gets the swig class registry (or creates it) */
+SWIGINTERN void  SWIG_Lua_get_class_registry(lua_State* L)
+{
+  /* add this all into the swig registry: */
+  lua_pushstring(L,"SWIG");
+  lua_rawget(L,LUA_REGISTRYINDEX);  /* get the registry */
+  if (!lua_istable(L,-1))  /* not there */
+  {  /* must be first time, so add it */
+    lua_pop(L,1);  /* remove the result */
+    lua_pushstring(L,"SWIG");
+    lua_newtable(L);
+    lua_rawset(L,LUA_REGISTRYINDEX);
+    /* then get it */
+    lua_pushstring(L,"SWIG");
+    lua_rawget(L,LUA_REGISTRYINDEX);
+  }
+}
+
+/* helper fn to get the classes metatable from the register */
+SWIGINTERN void  SWIG_Lua_get_class_metatable(lua_State* L,const char* cname)
+{
+  SWIG_Lua_get_class_registry(L);  /* get the registry */
+  lua_pushstring(L,cname);  /* get the name */
+  lua_rawget(L,-2);    /* get it */
+  lua_remove(L,-2);    /* tidy up (remove registry) */
+}
+
+/* helper add a variable to a registered class */
+SWIGINTERN void  SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn)
+{
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_add_function(L,name,getFn);
+  lua_pop(L,1);       /* tidy stack (remove table) */
+  if (setFn)
+  {
+    SWIG_Lua_get_table(L,".set"); /* find the .set table */
+    assert(lua_istable(L,-1));  /* just in case */
+    SWIG_Lua_add_function(L,name,setFn);
+    lua_pop(L,1);       /* tidy stack (remove table) */
+  }
+}
+
+/* helper to recursively add class details (attributes & operations) */
+SWIGINTERN void  SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss)
+{
+  int i;
+  /* call all the base classes first: we can then override these later: */
+  for(i=0;clss->bases[i];i++)
+  {
+    SWIG_Lua_add_class_details(L,clss->bases[i]);
+  }
+  /* add fns */
+  for(i=0;clss->attributes[i].name;i++){
+    SWIG_Lua_add_class_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod);
+  }
+  /* add methods to the metatable */
+  SWIG_Lua_get_table(L,".fn"); /* find the .fn table */
+  assert(lua_istable(L,-1));  /* just in case */
+  for(i=0;clss->methods[i].name;i++){
+    SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method);
+  }
+  lua_pop(L,1);       /* tidy stack (remove table) */
+  /*   add operator overloads
+    these look ANY method which start with "__" and assume they
+    are operator overloads & add them to the metatable
+    (this might mess up is someone defines a method __gc (the destructor)*/
+  for(i=0;clss->methods[i].name;i++){
+    if (clss->methods[i].name[0]=='_' && clss->methods[i].name[1]=='_'){
+      SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method);
+    }
+  }
+}
+
+/* set up the base classes pointers.
+Each class structure has a list of pointers to the base class structures.
+This function fills them.
+It cannot be done at compile time, as this will not work with hireachies
+spread over more than one swig file. 
+Therefore it must be done at runtime, querying the SWIG type system.
+*/
+SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss)
+{
+  int i=0;
+  swig_module_info* module=SWIG_GetModule(L);
+  for(i=0;clss->base_names[i];i++)
+  {
+    if (clss->bases[i]==0) /* not found yet */
+    {
+      /* lookup and cache the base class */
+      swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]);
+      if (info) clss->bases[i] = (swig_lua_class *) info->clientdata;
+    }
+  }	
+}
+
+/* performs the entire class registration process */
+SWIGINTERN void  SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss)
+{
+  /*  add its constructor to module with the name of the class
+  so you can do MyClass(...) as well as new_MyClass(...)
+  BUT only if a constructor is defined
+  (this overcomes the problem of pure virtual classes without constructors)*/
+  if (clss->constructor)
+    SWIG_Lua_add_function(L,clss->name,clss->constructor);
+
+  SWIG_Lua_get_class_registry(L);  /* get the registry */
+  lua_pushstring(L,clss->name);  /* get the name */
+  lua_newtable(L);    /* create the metatable */
+  /* add string of class name called ".type" */
+  lua_pushstring(L,".type");
+  lua_pushstring(L,clss->name);
+  lua_rawset(L,-3);
+  /* add a table called ".get" */
+  lua_pushstring(L,".get");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add a table called ".set" */
+  lua_pushstring(L,".set");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add a table called ".fn" */
+  lua_pushstring(L,".fn");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add accessor fns for using the .get,.set&.fn */
+  SWIG_Lua_add_function(L,"__index",SWIG_Lua_class_get);
+  SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_class_set);
+  SWIG_Lua_add_function(L,"__gc",SWIG_Lua_class_destruct);
+  /* add it */
+  lua_rawset(L,-3);  /* metatable into registry */
+  lua_pop(L,1);      /* tidy stack (remove registry) */
+
+  SWIG_Lua_get_class_metatable(L,clss->name);
+  SWIG_Lua_add_class_details(L,clss);  /* recursive adding of details (atts & ops) */
+  lua_pop(L,1);      /* tidy stack (remove class metatable) */
+}
+
+/* -----------------------------------------------------------------------------
+ * Class/structure conversion fns
+ * ----------------------------------------------------------------------------- */
+
+/* helper to add metatable to new lua object */
+SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State* L,swig_type_info *type)
+{
+  if (type->clientdata)  /* there is clientdata: so add the metatable */
+  {
+    SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->name);
+    if (lua_istable(L,-1))
+    {
+      lua_setmetatable(L,-2);
+    }
+    else
+    {
+      lua_pop(L,1);
+    }
+  }
+}
+
+/* pushes a new object into the lua stack */
+SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type, int own)
+{
+  swig_lua_userdata* usr;
+  if (!ptr){
+    lua_pushnil(L);
+    return;
+  }
+  usr=(swig_lua_userdata*)lua_newuserdata(L,sizeof(swig_lua_userdata));  /* get data */
+  usr->ptr=ptr;  /* set the ptr */
+  usr->type=type;
+  usr->own=own;
+  _SWIG_Lua_AddMetatable(L,type); /* add metatable */
+}
+
+/* takes a object from the lua stack & converts it into an object of the correct type
+ (if possible) */
+SWIGRUNTIME int  SWIG_Lua_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags)
+{
+  swig_lua_userdata* usr;
+  swig_cast_info *cast;
+  if (lua_isnil(L,index)){*ptr=0; return SWIG_OK;}    /* special case: lua nil => NULL pointer */
+  usr=(swig_lua_userdata*)lua_touserdata(L,index);  /* get data */
+  if (usr)
+  {
+    if (flags & SWIG_POINTER_DISOWN) /* must disown the object */
+    {
+        usr->own=0;
+    }
+    if (!type)            /* special cast void*, no casting fn */
+    {
+      *ptr=usr->ptr;
+      return SWIG_OK; /* ok */
+    }
+    cast=SWIG_TypeCheckStruct(usr->type,type); /* performs normal type checking */
+    if (cast)
+    {
+      int newmemory = 0;
+      *ptr=SWIG_TypeCast(cast,usr->ptr,&newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+      return SWIG_OK;  /* ok */
+    }
+  }
+  return SWIG_ERROR;  /* error */
+}
+
+SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State* L,int index,swig_type_info *type,int flags,
+       int argnum,const char* func_name){
+  void* result;
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){
+    lua_pushfstring(L,"Error in %s, expected a %s at argument number %d\n",
+      func_name,(type && type->str)?type->str:"void*",argnum);
+    lua_error(L);
+  }
+  return result;
+}
+
+/* pushes a packed userdata. user for member fn pointers only */
+SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State* L,void* ptr,size_t size,swig_type_info *type)
+{
+  swig_lua_rawdata* raw;
+  assert(ptr); /* not acceptable to pass in a NULL value */
+  raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size);  /* alloc data */
+  raw->type=type;
+  raw->own=0;
+  memcpy(raw->data,ptr,size); /* copy the data */
+  _SWIG_Lua_AddMetatable(L,type); /* add metatable */
+}
+    
+/* converts a packed userdata. user for member fn pointers only */
+SWIGRUNTIME int  SWIG_Lua_ConvertPacked(lua_State* L,int index,void* ptr,size_t size,swig_type_info *type)
+{
+  swig_lua_rawdata* raw;
+  raw=(swig_lua_rawdata*)lua_touserdata(L,index);  /* get data */
+  if (!raw) return SWIG_ERROR;  /* error */
+  if (type==0 || type==raw->type) /* void* or identical type */
+  {
+    memcpy(ptr,raw->data,size); /* copy it */
+    return SWIG_OK; /* ok */
+  }
+  return SWIG_ERROR;  /* error */
+}
+
+/* a function to get the typestring of a piece of data */
+SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp)
+{
+  swig_lua_userdata* usr;
+  if (lua_isuserdata(L,tp))
+  {
+    usr=(swig_lua_userdata*)lua_touserdata(L,1);  /* get data */
+    if (usr && usr->type && usr->type->str)
+      return usr->type->str;
+    return "userdata (unknown type)";
+  }
+  return lua_typename(L,lua_type(L,tp));
+}
+
+/* lua callable function to get the userdata's type */
+SWIGRUNTIME int SWIG_Lua_type(lua_State* L)
+{
+  lua_pushstring(L,SWIG_Lua_typename(L,1));
+  return 1;
+}
+
+/* lua callable function to compare userdata's value
+the issue is that two userdata may point to the same thing
+but to lua, they are different objects */
+SWIGRUNTIME int SWIG_Lua_equal(lua_State* L)
+{
+  int result;
+  swig_lua_userdata *usr1,*usr2;
+  if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2))  /* just in case */
+    return 0;  /* nil reply */
+  usr1=(swig_lua_userdata*)lua_touserdata(L,1);  /* get data */
+  usr2=(swig_lua_userdata*)lua_touserdata(L,2);  /* get data */
+  /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/
+  result=(usr1->ptr==usr2->ptr);
+   lua_pushboolean(L,result);
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * global variable support code: class/struct typemap functions
+ * ----------------------------------------------------------------------------- */
+
+/* Install Constants */
+SWIGINTERN void
+SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]) {
+  int i;
+  for (i = 0; constants[i].type; i++) {
+    switch(constants[i].type) {
+    case SWIG_LUA_INT:
+      lua_pushstring(L,constants[i].name);
+      lua_pushnumber(L,(lua_Number)constants[i].lvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_FLOAT:
+      lua_pushstring(L,constants[i].name);
+      lua_pushnumber(L,(lua_Number)constants[i].dvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_CHAR:
+      lua_pushstring(L,constants[i].name);
+      lua_pushfstring(L,"%c",(char)constants[i].lvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_STRING:
+      lua_pushstring(L,constants[i].name);
+      lua_pushstring(L,(char *) constants[i].pvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_POINTER:
+      lua_pushstring(L,constants[i].name);
+      SWIG_NewPointerObj(L,constants[i].pvalue, *(constants[i]).ptype,0);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_BINARY:
+      lua_pushstring(L,constants[i].name);
+      SWIG_NewMemberObj(L,constants[i].pvalue,constants[i].lvalue,*(constants[i]).ptype);
+      lua_rawset(L,-3);
+      break;
+    default:
+      break;
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * executing lua code from within the wrapper
+ * ----------------------------------------------------------------------------- */
+
+#ifndef SWIG_DOSTRING_FAIL /* Allows redefining of error function */
+#define SWIG_DOSTRING_FAIL(S) fprintf(stderr,"%s\n",S)
+#endif
+/* Executes a C string in Lua a really simple way of calling lua from C
+Unfortunately lua keeps changing its API's, so we need a conditional compile
+In lua 5.0.X its lua_dostring()
+In lua 5.1.X its luaL_dostring()
+*/
+SWIGINTERN int 
+SWIG_Lua_dostring(lua_State *L, const char* str) {
+  int ok,top;
+  if (str==0 || str[0]==0) return 0; /* nothing to do */
+  top=lua_gettop(L); /* save stack */
+#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501))
+  ok=luaL_dostring(L,str);	/* looks like this is lua 5.1.X or later, good */
+#else
+  ok=lua_dostring(L,str);	/* might be lua 5.0.x, using lua_dostring */
+#endif
+  if (ok!=0) {
+    SWIG_DOSTRING_FAIL(lua_tostring(L,-1));
+  }
+  lua_settop(L,top); /* restore the stack */
+  return ok;
+}    
+
+#ifdef __cplusplus
+}
+#endif
+
+/* ------------------------------ end luarun.swg  ------------------------------ */
diff --git a/trunk/Lib/lua/luaruntime.swg b/trunk/Lib/lua/luaruntime.swg
new file mode 100644
index 0000000..b82cd56
--- /dev/null
+++ b/trunk/Lib/lua/luaruntime.swg
@@ -0,0 +1,77 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * luaruntime.swg
+ *
+ * all the runtime code for .
+ * ----------------------------------------------------------------------------- */
+
+%runtime "swigrun.swg";         /* Common C API type-checking code */
+%runtime "luarun.swg";          /* Lua runtime stuff */
+
+%insert(initbeforefunc) "swiginit.swg"
+
+%insert(initbeforefunc) %{
+
+/* Forward declaration of where the user's %init{} gets inserted */
+void SWIG_init_user(lua_State* L );
+    
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* this is the initialization function
+  added at the very end of the code
+  the function is always called SWIG_init, but an eariler #define will rename it
+*/
+SWIGEXPORT int SWIG_init(lua_State* L)
+{
+  int i;
+  /* start with global table */
+  lua_pushvalue(L,LUA_GLOBALSINDEX);
+  /* SWIG's internal initalisation */
+  SWIG_InitializeModule((void*)L);
+  SWIG_PropagateClientData();
+  /* add a global fn */
+  SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type);
+  SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal);
+  /* begin the module (its a table with the same name as the module) */
+  SWIG_Lua_module_begin(L,SWIG_name);
+  /* add commands/functions */
+  for (i = 0; swig_commands[i].name; i++){
+    SWIG_Lua_module_add_function(L,swig_commands[i].name,swig_commands[i].func);
+  }
+  /* add variables */
+  for (i = 0; swig_variables[i].name; i++){
+    SWIG_Lua_module_add_variable(L,swig_variables[i].name,swig_variables[i].get,swig_variables[i].set);
+  }
+  /* set up base class pointers (the hierachy) */
+  for (i = 0; swig_types[i]; i++){
+    if (swig_types[i]->clientdata){
+      SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata));
+    }
+  }
+  /* additional registration structs & classes in lua */
+  for (i = 0; swig_types[i]; i++){
+    if (swig_types[i]->clientdata){
+      SWIG_Lua_class_register(L,(swig_lua_class*)(swig_types[i]->clientdata));
+    }
+  }
+  /* constants */
+  SWIG_Lua_InstallConstants(L,swig_constants);
+  /* invoke user-specific initialization */
+  SWIG_init_user(L);
+  /* end module */
+  lua_pop(L,1);  /* tidy stack (remove module table)*/
+  lua_pop(L,1);  /* tidy stack (remove global table)*/
+  return 1;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+%}
+
+/* Note: the initialization function is closed after all code is generated */
+
diff --git a/trunk/Lib/lua/luatypemaps.swg b/trunk/Lib/lua/luatypemaps.swg
new file mode 100644
index 0000000..0941c9d
--- /dev/null
+++ b/trunk/Lib/lua/luatypemaps.swg
@@ -0,0 +1,371 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * luatypemaps.swg
+ *
+ * basic typemaps for Lua.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ *                          standard typemaps
+ * ----------------------------------------------------------------------------- */
+/* NEW LANGUAGE NOTE:
+   the 'checkfn' param is something that I added for typemap(in)
+   it is an optional fn call to check the type of the lua object
+   the fn call must be of the form
+     int checkfn(lua_State *L, int index);
+   and return 1/0 depending upon if this is the correct type
+   For the typemap(out), an additional SWIG_arg parmeter must be incremented
+   to reflect the number of values returned (normally SWIG_arg++; will do)
+*/
+// numbers
+%typemap(in,checkfn="lua_isnumber") int,short,long,
+             unsigned int,unsigned short,unsigned long,
+             signed char,unsigned char,
+             float,double
+%{$1 = ($type)lua_tonumber(L, $input);%}
+
+%typemap(out) int,short,long,
+             unsigned int,unsigned short,unsigned long,
+             signed char,unsigned char,
+             float,double
+%{  lua_pushnumber(L, (lua_Number) $1); SWIG_arg++;%}
+
+// we must also provide typemaps for privitives by const reference:
+// given a function:
+//	int intbyref(const int& i);
+// SWIG assumes that this code will need a pointer to int to be passed in
+// (this might be ok for objects by const ref, but not for numeric primitives)
+// therefore we add a set of typemaps to fix this (for both in & out)
+%typemap(in,checkfn="lua_isnumber") const int&($basetype temp)
+%{ temp=($basetype)lua_tonumber(L,$input); $1=&temp;%}
+
+%typemap(out) const int&
+%{  lua_pushnumber(L, (lua_Number) *$1); SWIG_arg++;%}
+
+// for the other numbers we can just use an apply statement to cover them
+%apply const int & {const short&,const long&,
+             const unsigned int&,const unsigned short&,const unsigned long&,
+             const signed char&,const unsigned char&,
+             const float&,const double&};
+
+/* enums have to be handled slightly differently
+	VC++ .net will not allow a cast from lua_Number(double) to enum directly.
+*/
+%typemap(in,checkfn="lua_isnumber") enum SWIGTYPE
+%{$1 = ($type)(int)lua_tonumber(L, $input);%}
+
+%typemap(out) enum SWIGTYPE
+%{  lua_pushnumber(L, (lua_Number)(int)($1)); SWIG_arg++;%}
+
+// and const refs
+%typemap(in,checkfn="lua_isnumber") const enum SWIGTYPE &($basetype temp)
+%{ temp=($basetype)(int)lua_tonumber(L,$input); $1=&temp;%}
+%typemap(out) const enum SWIGTYPE &
+%{  lua_pushnumber(L, (lua_Number) *$1); SWIG_arg++;%}
+
+
+// boolean (which is a special type in lua)
+// note: lua_toboolean() returns 1 or 0
+// note: 1 & 0 are not booleans in lua, only true & false
+%typemap(in,checkfn="lua_isboolean") bool
+%{$1 = (lua_toboolean(L, $input)!=0);%}
+
+%typemap(out) bool
+%{  lua_pushboolean(L,(int)($1!=0)); SWIG_arg++;%}
+
+// for const bool&, SWIG treats this as a const bool* so we must dereference it
+%typemap(in,checkfn="lua_isboolean") const bool& (bool temp)
+%{temp=(lua_toboolean(L, $input)!=0);
+  $1=&temp;%}
+
+%typemap(out) const bool&
+%{  lua_pushboolean(L,(int)((*$1)!=0)); SWIG_arg++;%}
+
+// strings (char* and char[])
+%typemap(in,checkfn="lua_isstring") const char*, char*
+%{$1 = ($ltype)lua_tostring(L, $input);%}
+
+%typemap(in,checkfn="lua_isstring") const char[ANY], char[ANY]
+%{$1 = ($ltype)lua_tostring(L, $input);%}
+
+%typemap(out) const char*, char*
+%{  lua_pushstring(L,(const char*)$1); SWIG_arg++;%}
+
+%typemap(out) const char[ANY], char[ANY]
+%{  lua_pushstring(L,(const char*)$1); SWIG_arg++;%}
+
+// char's
+// currently treating chars as small strings, not as numbers
+// (however signed & unsigned char's are numbers...)
+%typemap(in,checkfn="lua_isstring") char
+%{$1 = (lua_tostring(L, $input))[0];%}
+
+%typemap(out) char
+%{  lua_pushfstring(L,"%c",$1); SWIG_arg++;%}
+
+// by const ref
+%typemap(in,checkfn="lua_isstring") const char& (char temp)
+%{temp = (lua_tostring(L, $input))[0]; $1=&temp;%}
+
+%typemap(out) const char&
+%{  lua_pushfstring(L,"%c",*$1); SWIG_arg++;%}
+
+// pointers and references
+// under SWIG rules, it is ok, to have a pass in a lua nil,
+// it should be converted to a SWIG NULL.
+// This will only be allowed for pointers & arrays, not refs or by value
+// the checkfn lua_isuserdata will only work for userdata
+// the checkfn SWIG_isptrtype will work for both userdata and nil's
+%typemap(in,checkfn="SWIG_isptrtype") SWIGTYPE*,SWIGTYPE[]
+%{
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,$input,(void**)&$1,$descriptor,$disown))){
+    SWIG_fail_ptr("$symname",$argnum,$descriptor);
+  }
+%}
+
+%typemap(in,checkfn="lua_isuserdata") SWIGTYPE&
+%{
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,$input,(void**)&$1,$descriptor,$disown))){
+    SWIG_fail_ptr("$symname",$argnum,$descriptor);
+  }
+%}
+
+// out is simple
+%typemap(out) SWIGTYPE*,SWIGTYPE&
+%{SWIG_NewPointerObj(L,$1,$descriptor,$owner); SWIG_arg++; %}
+
+// dynamic casts
+// this uses the SWIG_TypeDynamicCast() which relies on RTTI to find out what the pointer really is
+// the we return it as the correct type
+%typemap(out) SWIGTYPE *DYNAMIC,
+              SWIGTYPE &DYNAMIC
+{
+  swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor, (void **) &$1);
+  SWIG_NewPointerObj(L,(void*)$1,ty,$owner); SWIG_arg++; 
+}
+
+
+// passing objects by value
+// SWIG_ConvertPtr wants an object pointer (the $&ltype argp)
+// then dereferences it to get the object
+%typemap(in,checkfn="lua_isuserdata") SWIGTYPE ($&ltype argp)
+%{
+   if (!SWIG_IsOK(SWIG_ConvertPtr(L,$input,(void**)&argp,$&descriptor,0))){
+     SWIG_fail_ptr("$symname",$argnum,$&descriptor);
+   }
+   $1 = *argp;
+%}
+
+// Also needed for object ptrs by const ref
+// eg A* const& ref_pointer(A* const& a);
+// found in mixed_types.i
+%typemap(in,checkfn="lua_isuserdata") SWIGTYPE *&($*ltype temp)
+%{temp=($*ltype)SWIG_MustGetPtr(L,$input,$*descriptor,0,$argnum,"$symname");
+$1=&temp;%}
+
+%typemap(out) SWIGTYPE *&
+%{SWIG_NewPointerObj(L,*$1,$*descriptor,$owner); SWIG_arg++; %}
+
+
+// DISOWN-ing typemaps
+// if you have an object pointer which must be disowned, use this typemap
+// eg. for void destroy_foo(Foo* toDie);
+// use %apply SWIGTYPE* DISOWN {Foo* toDie};
+// you could just use %delobject, but this is more flexible
+%typemap(in,checkfn="SWIG_isptrtype") SWIGTYPE* DISOWN,SWIGTYPE DISOWN[]
+%{  if (!SWIG_IsOK(SWIG_ConvertPtr(L,$input,(void**)&$1,$descriptor,SWIG_POINTER_DISOWN))){
+    SWIG_fail_ptr("$symname",$argnum,$descriptor);
+  }
+%}
+
+
+// Primitive types--return by value
+// must make a new object, copy the data & return the new object
+// Note: the brackets are {...} and not %{..%}, because we want them to be included in the wrapper
+// this is because typemap(out) does not support local variables, like in typemap(in) does
+// and we need the $&1_ltype resultptr; to be declared
+#ifdef __cplusplus
+%typemap(out) SWIGTYPE
+{
+  $&1_ltype resultptr = new $1_ltype((const $1_ltype &) $1);
+  SWIG_NewPointerObj(L,(void *) resultptr,$&1_descriptor,1); SWIG_arg++;
+}
+#else
+%typemap(out) SWIGTYPE
+{
+  $&1_ltype resultptr;
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  SWIG_NewPointerObj(L,(void *) resultptr,$&1_descriptor,1); SWIG_arg++;
+}
+#endif
+
+// member function pointer
+// a member fn ptr is not 4 bytes like a normal pointer, but 8 bytes (at least on mingw)
+// so the standard wrappering cannot be done
+// nor can you cast a member function pointer to a void* (obviously)
+// therefore a special wrappering functions SWIG_ConvertMember() & SWIG_NewMemberObj() were written
+#ifdef __cplusplus
+%typemap(in,checkfn="lua_isuserdata") SWIGTYPE (CLASS::*)
+%{
+  if (!SWIG_IsOK(SWIG_ConvertMember(L,$input,(void*)(&$1),sizeof($type),$descriptor)))
+    SWIG_fail_ptr("$symname",$argnum,$descriptor);
+%}
+
+%typemap(out) SWIGTYPE (CLASS::*)
+%{ 
+  SWIG_NewMemberObj(L,(void*)(&$1),sizeof($type),$descriptor); SWIG_arg++; 
+%}
+#endif
+
+
+// void (must be empty without the SWIG_arg++)
+%typemap(out) void "";
+
+/* void* is a special case
+A function void fn(void*) should take any kind of pointer as a parameter (just like C/C++ does)
+but if its an output, then it should be wrappered like any other SWIG object (using default typemap)
+*/
+%typemap(in,checkfn="SWIG_isptrtype") void*
+%{$1=($1_ltype)SWIG_MustGetPtr(L,$input,0,0,$argnum,"$symname");%}
+
+/* long long is another special case:
+as lua only supports one numeric type (lua_Number), we will just
+cast it to that & accept the loss of precision.
+An alternative solution would be a long long struct or class
+with the relevant operators.
+*/
+%apply long {long long, signed long long, unsigned long long};
+%apply const long& {const long long&, const signed long long&, const unsigned long long&};
+
+/* It is possible to also pass a lua_State* into a function, so
+void fn(int a, float b, lua_State* s) is wrappable as
+> fn(1,4.3) -- note: the state is implicitly passed in
+*/
+%typemap(in, numinputs=0) lua_State* 
+%{$1 = L;%}
+
+
+
+/* -----------------------------------------------------------------------------
+ *                          typecheck rules
+ * ----------------------------------------------------------------------------- */
+/* These are needed for the overloaded functions
+These define the detection routines which will spot what
+parmeters match which function
+*/
+
+// unfortunately lua only considers one type of number
+// so all numbers (int,float,double) match
+// you could add an advanced fn to get type & check if its integral
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 int, short, long,
+ 	 unsigned int, unsigned short, unsigned long,
+	 signed char, unsigned char,
+	 long long, unsigned long long, signed long long,
+	 const int &, const short &, const long &,
+ 	 const unsigned int &, const unsigned short &, const unsigned long &,
+	 const signed char&, const unsigned char&,
+	 const long long &, const unsigned long long &,
+	 enum SWIGTYPE,	const enum SWIGTYPE&,
+	 float, double, const float &, const double&
+{
+  $1 = lua_isnumber(L,$input);
+}
+
+%typecheck(SWIG_TYPECHECK_BOOL)
+    bool, const bool &
+{
+  $1 = lua_isboolean(L,$input);
+}
+
+// special check for a char (string of length 1)
+%typecheck(SWIG_TYPECHECK_CHAR) char, const char& {
+  $1 = lua_isstring(L,$input) && (lua_strlen(L,$input)==1);
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char *, char[] {
+  $1 = lua_isstring(L,$input);
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE [] {
+  void *ptr;
+  if (SWIG_isptrtype(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, $1_descriptor, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE & {
+  void *ptr;
+  if (lua_isuserdata(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, $1_descriptor, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
+  void *ptr;
+  if (lua_isuserdata(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, $&1_descriptor, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  if (SWIG_isptrtype(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, 0, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+// Also needed for object ptrs by const ref
+// eg const A* ref_pointer(A* const& a);
+// found in mixed_types.i
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE* const &
+{
+  void *ptr;
+  if (lua_isuserdata(L,$input)==0 || SWIG_ConvertPtr(L,$input, (void **) &ptr, $*descriptor, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ *                          Others
+ * ----------------------------------------------------------------------------- */
+
+// Array reference typemaps
+%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) }
+
+// size_t (which is just a unsigned long)
+%apply unsigned long { size_t };
+%apply const unsigned long & { const size_t & };
+
+
+/* -----------------------------------------------------------------------------
+ *                          Specials
+ * ----------------------------------------------------------------------------- */
+// swig::LANGUAGE_OBJ was added to allow containers of native objects
+// however its rather difficult to do this in lua, as you cannot hold pointers
+// to native objects (they are held in the interpreter)
+// therefore for now: just ignoring this feature
+#ifdef __cplusplus
+%ignore swig::LANGUAGE_OBJ;
+
+//%inline %{
+%{
+namespace swig {
+typedef struct{} LANGUAGE_OBJ;
+}
+%}
+
+#endif // __cplusplus
diff --git a/trunk/Lib/lua/std_common.i b/trunk/Lib/lua/std_common.i
new file mode 100644
index 0000000..cee11e8
--- /dev/null
+++ b/trunk/Lib/lua/std_common.i
@@ -0,0 +1,5 @@
+%include <std_except.i>
+
+%apply size_t { std::size_t };
+%apply const size_t& { const std::size_t& };
+
diff --git a/trunk/Lib/lua/std_deque.i b/trunk/Lib/lua/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/lua/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/lua/std_except.i b/trunk/Lib/lua/std_except.i
new file mode 100644
index 0000000..ce148ef
--- /dev/null
+++ b/trunk/Lib/lua/std_except.i
@@ -0,0 +1,43 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * Typemaps used by the STL wrappers that throw exceptions.
+ * These typemaps are used when methods are declared with an STL exception
+ * specification, such as:
+ *   size_t at() const throw (std::out_of_range);
+ *
+ * std_except.i
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <stdexcept>
+%}
+%include <exception.i>
+
+namespace std 
+{
+  %ignore exception; // not sure if I should ignore this...
+  class exception 
+  {
+  public:
+    exception() throw() { }
+    virtual ~exception() throw();
+    virtual const char* what() const throw();
+  }; 
+}
+
+// normally object which are thrown are returned to interpreter as errors
+// (which potentally may have problems if they are not copied)
+// therefore all classes based upon std::exception are converted to their strings & returned as errors
+%typemap(throws) std::bad_exception     "SWIG_exception(SWIG_RuntimeError, $1.what());"
+%typemap(throws) std::domain_error      "SWIG_exception(SWIG_ValueError, $1.what());"
+%typemap(throws) std::exception         "SWIG_exception(SWIG_SystemError, $1.what());"
+%typemap(throws) std::invalid_argument  "SWIG_exception(SWIG_ValueError, $1.what());"
+%typemap(throws) std::length_error      "SWIG_exception(SWIG_IndexError, $1.what());"
+%typemap(throws) std::logic_error       "SWIG_exception(SWIG_RuntimeError, $1.what());"
+%typemap(throws) std::out_of_range      "SWIG_exception(SWIG_IndexError, $1.what());"
+%typemap(throws) std::overflow_error    "SWIG_exception(SWIG_OverflowError, $1.what());"
+%typemap(throws) std::range_error       "SWIG_exception(SWIG_IndexError, $1.what());"
+%typemap(throws) std::runtime_error     "SWIG_exception(SWIG_RuntimeError, $1.what());"
+%typemap(throws) std::underflow_error   "SWIG_exception(SWIG_RuntimeError, $1.what());"
diff --git a/trunk/Lib/lua/std_map.i b/trunk/Lib/lua/std_map.i
new file mode 100644
index 0000000..dd22443
--- /dev/null
+++ b/trunk/Lib/lua/std_map.i
@@ -0,0 +1,63 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        typedef size_t size_type;
+        typedef ptrdiff_t difference_type;
+        typedef K key_type;
+        typedef T mapped_type;
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            const T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+}
diff --git a/trunk/Lib/lua/std_pair.i b/trunk/Lib/lua/std_pair.i
new file mode 100644
index 0000000..1b20f74
--- /dev/null
+++ b/trunk/Lib/lua/std_pair.i
@@ -0,0 +1,45 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * std::pair typemaps for LUA
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <utility>
+%}
+/*
+A really cut down version of the pair class.
+
+this is not useful on its owns is it needs a %template definition with it
+
+eg.
+namespace std {
+    %template(IntPair) pair<int, int>;
+    %template(make_IntPair) make_pair<int, int>;
+}
+
+
+*/
+
+
+
+namespace std {
+  template <class T, class U > struct pair {
+    typedef T first_type;
+    typedef U second_type;
+
+    pair();
+    pair(T first, U second);
+    pair(const pair& p);
+
+    T first;
+    U second;
+  };
+
+  template <class T, class U >
+  pair<T,U> make_pair(const T&,const U&);
+
+}
diff --git a/trunk/Lib/lua/std_string.i b/trunk/Lib/lua/std_string.i
new file mode 100644
index 0000000..fa58f10
--- /dev/null
+++ b/trunk/Lib/lua/std_string.i
@@ -0,0 +1,155 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * std::string typemaps for LUA
+ * ----------------------------------------------------------------------------- */
+
+%{
+	#include <string>
+%}
+/*
+Only std::string and const std::string& are typemaped
+they are converted to the Lua strings automatically
+
+std::string& and std::string* are not
+they must be explicitly managed (see below)
+
+eg.
+
+std::string test_value(std::string x) {
+   return x;
+}
+
+can be used as
+
+s="hello world"
+s2=test_value(s)
+assert(s==s2)
+
+*/
+
+%naturalvar std::string;
+
+/*
+Bug report #1526022 by neomantra
+Lua strings and std::string can contain embeded zero's
+Therefore a standard out typemap should not be:
+  lua_pushstring(L,$1.c_str());
+but
+  lua_pushlstring(L,$1.data(),$1.size());
+
+Similarly for getting the string
+  $1 = (char*)lua_tostring(L, $input);
+becomes
+  $1.assign(lua_tostring(L,$input),lua_strlen(L,$input));
+  
+Not using: lua_tolstring() as this is only found in Lua 5.1 & not 5.0.2
+*/
+
+%typemap(in,checkfn="lua_isstring") std::string
+%{$1.assign(lua_tostring(L,$input),lua_strlen(L,$input));%}
+%typemap(out) std::string
+%{ lua_pushlstring(L,$1.data(),$1.size()); SWIG_arg++;%}
+
+%typemap(in,checkfn="lua_isstring")	const std::string& (std::string temp)
+%{temp.assign(lua_tostring(L,$input),lua_strlen(L,$input)); $1=&temp;%}
+
+%typemap(out) const std::string&
+%{ lua_pushlstring(L,$1->data(),$1->size()); SWIG_arg++;%}
+
+// for throwing of any kind of string, string ref's and string pointers
+// we convert all to lua strings
+%typemap(throws) std::string,std::string&,const std::string&
+%{ lua_pushlstring(L,$1.data(),$1.size()); SWIG_fail;%}
+%typemap(throws) std::string*,const std::string*
+%{ lua_pushlstring(L,$1->data(),$1->size()); SWIG_fail;%}
+
+// and the typechecks
+%typecheck(SWIG_TYPECHECK_STRING) std::string,const std::string& {
+  $1 = lua_isstring(L,$input);
+}
+
+/*
+std::string& can be wrappered, but you must inform SWIG if it is in or out
+
+eg:
+void fn(std::string& str);
+Is this an in/out/inout value?
+
+Therefore you need the usual
+%apply (std::string& INOUT) {(std::string& str)};
+or
+%apply std::string& INOUT {std::string& str};
+typemaps to tell SWIG what to do.
+*/
+
+%typemap(in) std::string &INPUT=const std::string &;
+%typemap(in, numinputs=0) std::string &OUTPUT (std::string temp)
+%{ $1 = &temp; %}
+%typemap(argout) std::string &OUTPUT
+%{ lua_pushlstring(L,$1->data(),$1->size()); SWIG_arg++;%}
+%typemap(in) std::string &INOUT =const std::string &;
+%typemap(argout) std::string &INOUT = std::string &OUTPUT;
+
+/*
+For const std::string* and std::string* is not clear
+is this a pointer or an array?
+
+Therefore just leaving it as is
+(there is some rough code below which could be used if needed
+
+// SWIG wraps const ref's as pointer
+// typemaps to deal with this and const ptrs
+%typemap(in,checkfn="lua_isstring")
+	const std::string& INPUT(std::string temp),
+	const std::string* INPUT(std::string temp)
+%{temp=(char*)lua_tostring(L, $input); $1=&temp;%}
+%typemap(out) const std::string&, const std::string*
+%{  lua_pushstring(L,$1->c_str()); SWIG_arg++;%}
+
+// the non-const pointer version
+%typemap(in) std::string *INPUT=const std::string *INPUT;
+%typemap(in, numinputs=0) std::string *OUTPUT (std::string temp)
+%{ $1 = &temp; %}
+%typemap(argout) std::string *OUTPUT
+%{  lua_pushstring(L,$1->c_str()); SWIG_arg++;%}
+%typemap(in) std::string *INOUT = std::string *INPUT;
+%typemap(argout) std::string *INOUT = std::string *OUTPUT;
+
+*/
+
+/*
+A really cut down version of the string class
+
+This provides basic mapping of lua strings <-> std::string
+and little else
+(the std::string has a lot of unneeded functions anyway)
+
+note: no fn's taking the const string&
+as this is overloaded by the const char* version
+*/
+namespace std {
+
+    class string {
+      public:
+        string();
+        string(const char*);
+        //string(const string&);
+        unsigned int size() const;
+        unsigned int length() const;
+        bool empty() const;
+        // no support for operator[]
+        const char* c_str()const;
+        const char* data()const;
+        // assign does not return a copy of this object
+        // (no point in a scripting language)
+        void assign(const char*);
+        //void assign(const string&);
+        // no support for all the other features
+        // its probably better to do it in lua
+    };
+}
+
diff --git a/trunk/Lib/lua/std_vector.i b/trunk/Lib/lua/std_vector.i
new file mode 100644
index 0000000..c677808
--- /dev/null
+++ b/trunk/Lib/lua/std_vector.i
@@ -0,0 +1,134 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * std::vector typemaps for LUA
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <vector>
+%}
+%include <std_except.i> // the general exepctions
+/*
+A really cut down version of the vector class.
+
+Note: this does not match the true std::vector class
+but instead is an approximate, so that SWIG knows how to wrapper it.
+(Eg, all access is by value, not ref, as SWIG turns refs to pointers)
+
+And no support for iterators & insert/erase
+
+It would be useful to have a vector<->Lua table conversion routine
+
+*/
+namespace std {
+
+	template<class T>
+    class vector {
+      public:
+        vector();
+        vector(unsigned int);
+        vector(const vector&);
+        vector(unsigned int,T);
+        unsigned int size() const;
+        unsigned int max_size() const;
+        bool empty() const;
+        void clear();
+        void push_back(T val);
+        void pop_back();
+        T front()const; // only read front & back
+        T back()const;  // not write to them
+        // operator [] given later:
+
+		%extend // this is a extra bit of SWIG code
+		{
+			// [] is replaced by __getitem__ & __setitem__
+			// simply throws a string, which causes a lua error
+			T __getitem__(unsigned int idx) throw (std::out_of_range)
+			{
+				if (idx>=self->size())
+					throw std::out_of_range("in vector::__getitem__()");
+				return (*self)[idx];
+			}
+			void __setitem__(unsigned int idx,T val) throw (std::out_of_range)
+			{
+				if (idx>=self->size())
+					throw std::out_of_range("in vector::__setitem__()");
+				(*self)[idx]=val;
+			}
+		};
+    };
+
+}
+
+/*
+Vector<->LuaTable fns
+These look a bit like the array<->LuaTable fns
+but are templated, not %defined
+(you must have template support for STL)
+
+*/
+/*
+%{
+// reads a table into a vector of numbers
+// lua numbers will be cast into the type required (rounding may occur)
+// return 0 if non numbers found in the table
+// returns new'ed ptr if ok
+template<class T>
+std::vector<T>* SWIG_read_number_vector(lua_State* L,int index)
+{
+	int i=0;
+	std::vector<T>* vec=new std::vector<T>();
+	while(1)
+	{
+		lua_rawgeti(L,index,i+1);
+		if (!lua_isnil(L,-1))
+		{
+			lua_pop(L,1);
+			break;	// finished
+		}
+		if (!lua_isnumber(L,-1))
+		{
+			lua_pop(L,1);
+			delete vec;
+			return 0;	// error
+		}
+		vec->push_back((T)lua_tonumber(L,-1));
+		lua_pop(L,1);
+		++i;
+	}
+	return vec;	// ok
+}
+// writes a vector of numbers out as a lua table
+template<class T>
+int SWIG_write_number_vector(lua_State* L,std::vector<T> *vec)
+{
+	lua_newtable(L);
+	for(int i=0;i<vec->size();++i)
+	{
+		lua_pushnumber(L,(double)((*vec)[i]));
+		lua_rawseti(L,-2,i+1);// -1 is the number, -2 is the table
+	}
+}
+%}
+
+// then the typemaps
+
+%define SWIG_TYPEMAP_NUM_VECTOR(T)
+
+// in
+%typemap(in) std::vector<T> *INPUT
+%{	$1 = SWIG_read_number_vector<T>(L,$input);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) std::vector<T> *INPUT
+%{	delete $1;%}
+
+// out
+%typemap(argout) std::vector<T> *OUTPUT
+%{	SWIG_write_number_vector(L,$1); SWIG_arg++; %}
+
+%enddef
+*/
diff --git a/trunk/Lib/lua/stl.i b/trunk/Lib/lua/stl.i
new file mode 100644
index 0000000..b8d7a65
--- /dev/null
+++ b/trunk/Lib/lua/stl.i
@@ -0,0 +1,13 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/lua/typemaps.i b/trunk/Lib/lua/typemaps.i
new file mode 100644
index 0000000..fa0c0d0
--- /dev/null
+++ b/trunk/Lib/lua/typemaps.i
@@ -0,0 +1,562 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.swg
+ *
+ * SWIG Library file containing the main typemap code to support Lua modules.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ *                          Basic inout typemaps
+ * ----------------------------------------------------------------------------- */
+/*
+These provide the basic ability for passing in & out of standard numeric data types
+(int,long,float,double, etc)
+
+The basic code looks like this:
+
+%typemap(in,checkfn="lua_isnumber") int *INPUT(int temp), int &INPUT(int temp)
+%{ temp = (int)lua_tonumber(L,$input);
+   $1 = &temp; %}
+
+%typemap(in, numinputs=0) int *OUTPUT (int temp)
+%{ $1 = &temp; %}
+
+%typemap(argout) int *OUTPUT
+%{  lua_pushnumber(L, (double) *$1); SWIG_arg++;%}
+
+%typemap(in) int *INOUT = int *INPUT;
+%typemap(argout) int *INOUT = int *OUTPUT;
+
+However the code below is a mixture of #defines & such, so nowhere as easy to read
+
+To make you code work correctly its not just a matter of %including this file
+You also have to give SWIG the hints on which to use where
+
+eg
+extern int add_pointer(int* a1,int* a2); // a1 & a2 are pointer values to be added
+extern void swap(int* s1, int* s2);	// does the swap
+
+You will need to either change the argument names
+extern int add_pointer(int* INPUT,int* INPUT);
+
+or provide a %apply statement
+
+%apply int* INOUT{ int *s1, int *s2 };
+	// if SWIG sees int* s1, int* s2, assume they are inout params
+*/
+
+
+%define SWIG_NUMBER_TYPEMAP(TYPE)
+%typemap(in,checkfn="lua_isnumber")	TYPE *INPUT($*ltype temp), TYPE &INPUT($*ltype temp)
+%{ temp = ($*ltype)lua_tonumber(L,$input);
+   $1 = &temp; %}
+%typemap(in, numinputs=0) TYPE *OUTPUT ($*ltype temp)
+%{ $1 = &temp; %}
+%typemap(argout) TYPE *OUTPUT
+%{  lua_pushnumber(L, (lua_Number) *$1); SWIG_arg++;%}
+%typemap(in) TYPE *INOUT = TYPE *INPUT;
+%typemap(argout) TYPE *INOUT = TYPE *OUTPUT;
+%typemap(in) TYPE &OUTPUT = TYPE *OUTPUT;
+%typemap(argout) TYPE &OUTPUT = TYPE *OUTPUT;
+%typemap(in) TYPE &INOUT = TYPE *INPUT;
+%typemap(argout) TYPE &INOUT = TYPE *OUTPUT;
+// const version (the $*ltype is the basic number without ptr or const's)
+%typemap(in,checkfn="lua_isnumber")	const TYPE *INPUT($*ltype temp)
+%{ temp = ($*ltype)lua_tonumber(L,$input);
+   $1 = &temp; %}
+%enddef
+
+// now the code
+SWIG_NUMBER_TYPEMAP(int); SWIG_NUMBER_TYPEMAP(unsigned int); SWIG_NUMBER_TYPEMAP(signed int);
+SWIG_NUMBER_TYPEMAP(short); SWIG_NUMBER_TYPEMAP(unsigned short); SWIG_NUMBER_TYPEMAP(signed short);
+SWIG_NUMBER_TYPEMAP(long); SWIG_NUMBER_TYPEMAP(unsigned long); SWIG_NUMBER_TYPEMAP(signed long);
+SWIG_NUMBER_TYPEMAP(float);
+SWIG_NUMBER_TYPEMAP(double);
+SWIG_NUMBER_TYPEMAP(enum SWIGTYPE);
+// also for long longs's
+SWIG_NUMBER_TYPEMAP(long long); SWIG_NUMBER_TYPEMAP(unsigned long long); SWIG_NUMBER_TYPEMAP(signed long long);
+
+// note we dont do char, as a char* is probably a string not a ptr to a single char
+
+// similar for booleans
+%typemap(in,checkfn="lua_isboolean") bool *INPUT(bool temp), bool &INPUT(bool temp)
+%{ temp = (lua_toboolean(L,$input)!=0);
+   $1 = &temp; %}
+
+%typemap(in, numinputs=0) bool *OUTPUT (bool temp),bool &OUTPUT (bool temp)
+%{ $1 = &temp; %}
+
+%typemap(argout) bool *OUTPUT,bool &OUTPUT
+%{  lua_pushboolean(L, (int)((*$1)!=0)); SWIG_arg++;%}
+
+%typemap(in) bool *INOUT = bool *INPUT;
+%typemap(argout) bool *INOUT = bool *OUTPUT;
+%typemap(in) bool &INOUT = bool &INPUT;
+%typemap(argout) bool &INOUT = bool &OUTPUT;
+
+/* -----------------------------------------------------------------------------
+ *                          Basic Array typemaps
+ * ----------------------------------------------------------------------------- */
+/*
+I have no idea why this kind of code does not exist in SWIG as standard,
+but here is it.
+This code will convert to/from 1D numeric arrays.
+In order to reduce code bloat, there are a few macros
+and quite a few functions defined
+(unfortunately this makes it a lot less clear)
+
+assuming we have functions
+void process_array(int arr[3]);	// nice fixed size array
+void process_var_array(float arr[],int len);	// variable sized array
+void process_var_array_inout(double* arr,int len);	// variable sized array
+			// data passed in & out
+void process_enum_inout_array_var(enum Days *arrinout, int len);	// using enums
+void return_array_5(int arrout[5]);	// out array only
+
+in order to wrap them correctly requires a typemap
+
+// inform SWIG of the correct typemap
+// For fixed length, you must specify it as <type> INPUT[ANY]
+%apply (int INPUT[ANY]) {(int arr[3])};
+// variable length arrays are just the same
+%apply (float INPUT[],int) {(float arr[],int len)};
+// it is also ok, to map the TYPE* instead of a TYPE[]
+%apply (double *INOUT,int) {(double arr*,int len)};
+// for the enum's you must use enum SWIGTYPE
+%apply (enum SWIGTYPE *INOUT,int) {(enum Days *arrinout, int len)};
+// fixed length out if also fine
+%apply (int OUTPUT[ANY]) {(int arrout[5])};
+
+Generally, you could use %typemap(...)=...
+but the %apply is neater & easier
+
+a few things of note:
+* all Lua tables are indexed from 1, all C/C++ arrays are indexed from 0
+	therefore t={6,5,3} -- t[1]==6, t[2]==5, t[3]==3
+	when passed to process_array(int arr[3]) becomes
+	arr[0]==6, arr[1]==5, arr[2]==3
+* for OUTPUT arrays, no array need be passed in, the fn will return a Lua table
+	so for the above mentioned return_array_5() would look like
+	arr=return_array_5() -- no parameters passed in
+* for INOUT arrays, a table must be passed in, and a new table will be returned
+	(this is consistant with the way that numbers are processed)
+	if you want just use
+	arr={...}
+	arr=process_var_array_inout(arr)	-- arr is replaced by the new version
+
+The following are not yet supported:
+* variable length output only array (inout's work ok)
+* multidimentional arrays
+* arrays of objects/structs
+* arrays of pointers
+
+*/
+
+/*
+The internals of the array managment stuff
+helper fns/macros
+SWIG_ALLOC_ARRAY(TYPE,LEN)	// returns a typed array TYPE[LEN]
+SWIG_FREE_ARRAY(PTR)		// delete the ptr (if not zero)
+
+// counts the specified table & gets the size
+// integer version
+int SWIG_itable_size(lua_State* L, int index);
+// other version
+int SWIG_table_size(lua_State* L, int index);
+
+SWIG_DECLARE_TYPEMAP_ARR_FN(NAME,TYPE)
+// this fn declares up 4 functions for helping to read/write tables
+// these can then be called by the macros ...
+// all assume the table is an integer indexes from 1
+// but the C array is a indexed from 0
+	// created a fixed size array, reads the specified table
+	// and then fills the array with numbers
+	// returns ptr to the array if ok, or 0 for error
+	// (also pushes a error message to the stack)
+TYPE* SWIG_get_NAME_num_array_fixed(lua_State* L, int index, int size);
+	// as per SWIG_get_NAME_num_array_fixed()
+	// but reads the entire table & creates an array of the correct size
+	// (if the table is empty, it returns an error rather than a zero length array)
+TYPE* SWIG_get_NAME_num_array_var(lua_State* L, int index, int* size);
+	// writes a table to Lua with all the specified numbers
+void SWIG_write_NAME_num_array(lua_State* L,TYPE *array,int size);
+	// read the specified table, and fills the array with numbers
+	// returns 1 of ok (only fails if it doesnt find numbers)
+	// helper fn (called by SWIG_get_NAME_num_array_*() fns)
+int SWIG_read_NAME_num_array(lua_State* L,int index,TYPE *array,int size);
+
+*/
+
+/* Reported that you don't need to check for NULL for delete & free
+There probably is some compiler that its not true for, so the code is left here just in case.
+#ifdef __cplusplus	
+#define SWIG_ALLOC_ARRAY(TYPE,LEN) 	new TYPE[LEN]
+#define SWIG_FREE_ARRAY(PTR)		if(PTR){delete[] PTR;}
+#else
+#define SWIG_ALLOC_ARRAY(TYPE,LEN) 	(TYPE *)malloc(LEN*sizeof(TYPE))
+#define SWIG_FREE_ARRAY(PTR)		if(PTR){free(PTR);}
+#endif
+*/
+%{
+#ifdef __cplusplus	/* generic alloc/dealloc fns*/
+#define SWIG_ALLOC_ARRAY(TYPE,LEN) 	new TYPE[LEN]
+#define SWIG_FREE_ARRAY(PTR)		delete[] PTR;
+#else
+#define SWIG_ALLOC_ARRAY(TYPE,LEN) 	(TYPE *)malloc(LEN*sizeof(TYPE))
+#define SWIG_FREE_ARRAY(PTR)		free(PTR);
+#endif
+/* counting the size of arrays:*/
+SWIGINTERN int SWIG_itable_size(lua_State* L, int index)
+{
+	int n=0;
+	while(1){
+		lua_rawgeti(L,index,n+1);
+		if (lua_isnil(L,-1))break;
+		++n;
+		lua_pop(L,1);
+	}
+	lua_pop(L,1);
+	return n;
+}
+
+SWIGINTERN int SWIG_table_size(lua_State* L, int index)
+{
+	int n=0;
+	lua_pushnil(L);  /* first key*/
+	while (lua_next(L, index) != 0) {
+		++n;
+		lua_pop(L, 1);  /* removes `value'; keeps `key' for next iteration*/
+	}
+	return n;
+}
+
+/* super macro to declare array typemap helper fns */
+#define SWIG_DECLARE_TYPEMAP_ARR_FN(NAME,TYPE)\
+	SWIGINTERN int SWIG_read_##NAME##_num_array(lua_State* L,int index,TYPE *array,int size){\
+		int i;\
+		for (i = 0; i < size; i++) {\
+			lua_rawgeti(L,index,i+1);\
+			if (lua_isnumber(L,-1)){\
+				array[i] = (TYPE)lua_tonumber(L,-1);\
+			} else {\
+				lua_pop(L,1);\
+				return 0;\
+			}\
+			lua_pop(L,1);\
+		}\
+		return 1;\
+	}\
+	SWIGINTERN TYPE* SWIG_get_##NAME##_num_array_fixed(lua_State* L, int index, int size){\
+		TYPE *array;\
+		if (!lua_istable(L,index) || SWIG_itable_size(L,index) != size) {\
+			lua_pushfstring(L,"expected a table of size %d",size);\
+			return 0;\
+		}\
+		array=SWIG_ALLOC_ARRAY(TYPE,size);\
+		if (!SWIG_read_##NAME##_num_array(L,index,array,size)){\
+			lua_pushstring(L,"table must contain numbers");\
+			SWIG_FREE_ARRAY(array);\
+			return 0;\
+		}\
+		return array;\
+	}\
+	SWIGINTERN TYPE* SWIG_get_##NAME##_num_array_var(lua_State* L, int index, int* size)\
+	{\
+		TYPE *array;\
+		if (!lua_istable(L,index)) {\
+			lua_pushstring(L,"expected a table");\
+			return 0;\
+		}\
+		*size=SWIG_itable_size(L,index);\
+		if (*size<1){\
+			lua_pushstring(L,"table appears to be empty");\
+			return 0;\
+		}\
+		array=SWIG_ALLOC_ARRAY(TYPE,*size);\
+		if (!SWIG_read_##NAME##_num_array(L,index,array,*size)){\
+			lua_pushstring(L,"table must contain numbers");\
+			SWIG_FREE_ARRAY(array);\
+			return 0;\
+		}\
+		return array;\
+	}\
+	SWIGINTERN void SWIG_write_##NAME##_num_array(lua_State* L,TYPE *array,int size){\
+		int i;\
+		lua_newtable(L);\
+		for (i = 0; i < size; i++){\
+			lua_pushnumber(L,(lua_Number)array[i]);\
+			lua_rawseti(L,-2,i+1);/* -1 is the number, -2 is the table*/ \
+		}\
+	}
+%}
+
+/*
+This is one giant macro to define the typemaps & the helpers
+for array handling
+*/
+%define SWIG_TYPEMAP_NUM_ARR(NAME,TYPE)
+%{SWIG_DECLARE_TYPEMAP_ARR_FN(NAME,TYPE);%}
+
+// fixed size array's
+%typemap(in) TYPE INPUT[ANY]
+%{	$1 = SWIG_get_##NAME##_num_array_fixed(L,$input,$1_dim0);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) TYPE INPUT[ANY]
+%{	SWIG_FREE_ARRAY($1);%}
+
+// variable size array's
+%typemap(in) (TYPE *INPUT,int)
+%{	$1 = SWIG_get_##NAME##_num_array_var(L,$input,&$2);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) (TYPE *INPUT,int)
+%{	SWIG_FREE_ARRAY($1);%}
+
+// out fixed arrays
+%typemap(in,numinputs=0) TYPE OUTPUT[ANY]
+%{  $1 = SWIG_ALLOC_ARRAY(TYPE,$1_dim0); %}
+
+%typemap(argout) TYPE OUTPUT[ANY]
+%{	SWIG_write_##NAME##_num_array(L,$1,$1_dim0); SWIG_arg++; %}
+
+%typemap(freearg) TYPE OUTPUT[ANY]
+%{	SWIG_FREE_ARRAY($1); %}
+
+// inout fixed arrays
+%typemap(in) TYPE INOUT[ANY]=TYPE INPUT[ANY];
+%typemap(argout) TYPE INOUT[ANY]=TYPE OUTPUT[ANY];
+%typemap(freearg) TYPE INOUT[ANY]=TYPE INPUT[ANY];
+// inout variable arrays
+%typemap(in) (TYPE *INOUT,int)=(TYPE *INPUT,int);
+%typemap(argout) (TYPE *INOUT,int)
+%{	SWIG_write_##NAME##_num_array(L,$1,$2); SWIG_arg++; %}
+%typemap(freearg) (TYPE *INOUT,int)=(TYPE *INPUT,int);
+
+// TODO out variable arrays (is there a standard form for such things?)
+
+// referencing so that (int *INPUT,int) and (int INPUT[],int) are the same
+%typemap(in) (TYPE INPUT[],int)=(TYPE *INPUT,int);
+%typemap(freearg) (TYPE INPUT[],int)=(TYPE *INPUT,int);
+
+%enddef
+
+// the following line of code
+// declares the C helper fns for the array typemaps
+// as well as defining typemaps for
+// fixed len arrays in & out, & variable length arrays in
+
+SWIG_TYPEMAP_NUM_ARR(int,int);
+SWIG_TYPEMAP_NUM_ARR(uint,unsigned int);
+SWIG_TYPEMAP_NUM_ARR(short,short);
+SWIG_TYPEMAP_NUM_ARR(ushort,unsigned short);
+SWIG_TYPEMAP_NUM_ARR(long,long);
+SWIG_TYPEMAP_NUM_ARR(ulong,unsigned long);
+SWIG_TYPEMAP_NUM_ARR(float,float);
+SWIG_TYPEMAP_NUM_ARR(double,double);
+
+// again enums are a problem so they need their own type
+// we use the int conversion routine & recast it
+%typemap(in) enum SWIGTYPE INPUT[ANY]
+%{	$1 = ($ltype)SWIG_get_int_num_array_fixed(L,$input,$1_dim0);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) enum SWIGTYPE INPUT[ANY]
+%{	SWIG_FREE_ARRAY($1);%}
+
+// variable size array's
+%typemap(in) (enum SWIGTYPE *INPUT,int)
+%{	$1 = ($ltype)SWIG_get_int_num_array_var(L,$input,&$2);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) (enum SWIGTYPE *INPUT,int)
+%{	SWIG_FREE_ARRAY($1);%}
+
+// out fixed arrays
+%typemap(in,numinputs=0) enum SWIGTYPE OUTPUT[ANY]
+%{  $1 = SWIG_ALLOC_ARRAY(enum SWIGTYPE,$1_dim0); %}
+
+%typemap(argout) enum SWIGTYPE OUTPUT[ANY]
+%{	SWIG_write_int_num_array(L,(int*)$1,$1_dim0); SWIG_arg++; %}
+
+%typemap(freearg) enum SWIGTYPE OUTPUT[ANY]
+%{	SWIG_FREE_ARRAY($1); %}
+
+// inout fixed arrays
+%typemap(in) enum SWIGTYPE INOUT[ANY]=enum SWIGTYPE INPUT[ANY];
+%typemap(argout) enum SWIGTYPE INOUT[ANY]=enum SWIGTYPE OUTPUT[ANY];
+%typemap(freearg) enum SWIGTYPE INOUT[ANY]=enum SWIGTYPE INPUT[ANY];
+// inout variable arrays
+%typemap(in) (enum SWIGTYPE *INOUT,int)=(enum SWIGTYPE *INPUT,int);
+%typemap(argout) (enum SWIGTYPE *INOUT,int)
+%{	SWIG_write_int_num_array(L,(int*)$1,$2); SWIG_arg++; %}
+%typemap(freearg) (enum SWIGTYPE *INOUT,int)=(enum SWIGTYPE *INPUT,int);
+
+
+/* Surprisingly pointer arrays are easier:
+this is because all ptr arrays become void**
+so only a few fns are needed & a few casts
+
+The function defined are
+	// created a fixed size array, reads the specified table
+	// and then fills the array with pointers (checking the type)
+	// returns ptr to the array if ok, or 0 for error
+	// (also pushes a error message to the stack)
+void** SWIG_get_ptr_array_fixed(lua_State* L, int index, int size,swig_type_info *type);
+	// as per SWIG_get_ptr_array_fixed()
+	// but reads the entire table & creates an array of the correct size
+	// (if the table is empty, it returns an error rather than a zero length array)
+void** SWIG_get_ptr_array_var(lua_State* L, int index, int* size,swig_type_info *type);
+	// writes a table to Lua with all the specified pointers
+	// all pointers have the ownership value 'own' (normally 0)
+void SWIG_write_ptr_array(lua_State* L,void **array,int size,int own);
+	// read the specified table, and fills the array with ptrs
+	// returns 1 of ok (only fails if it doesnt find correct type of ptrs)
+	// helper fn (called by SWIG_get_ptr_array_*() fns)
+int SWIG_read_ptr_array(lua_State* L,int index,void **array,int size,swig_type_info *type);
+
+The key thing to remember is that it is assumed that there is no
+modification of pointers ownership in the arrays
+
+eg A fn:
+void pointers_in(TYPE* arr[],int len);
+will make copies of the pointer into a temp array and then pass it into the fn
+Lua does not remeber that this fn held the pointers, so it is not safe to keep
+these pointers until later
+
+eg A fn:
+void pointers_out(TYPE* arr[3]);
+will return a table containing three pointers
+however these pointers are NOT owned by Lua, merely borrowed
+so if the C/C++ frees then Lua is not aware
+
+*/
+
+%{
+SWIGINTERN int SWIG_read_ptr_array(lua_State* L,int index,void **array,int size,swig_type_info *type){
+	int i;
+	for (i = 0; i < size; i++) {
+		lua_rawgeti(L,index,i+1);
+		if (!lua_isuserdata(L,-1) || SWIG_ConvertPtr(L,-1,&array[i],type,0)==-1){
+			lua_pop(L,1);
+			return 0;
+		}
+		lua_pop(L,1);
+	}
+	return 1;
+}
+SWIGINTERN void** SWIG_get_ptr_array_fixed(lua_State* L, int index, int size,swig_type_info *type){
+	void **array;
+	if (!lua_istable(L,index) || SWIG_itable_size(L,index) != size) {
+		lua_pushfstring(L,"expected a table of size %d",size);
+		return 0;
+	}
+	array=SWIG_ALLOC_ARRAY(void*,size);
+	if (!SWIG_read_ptr_array(L,index,array,size,type)){
+		lua_pushfstring(L,"table must contain pointers of type %s",type->name);
+		SWIG_FREE_ARRAY(array);
+		return 0;
+	}
+	return array;
+}
+SWIGINTERN void** SWIG_get_ptr_array_var(lua_State* L, int index, int* size,swig_type_info *type){
+	void **array;
+	if (!lua_istable(L,index)) {
+		lua_pushstring(L,"expected a table");
+		return 0;
+	}
+	*size=SWIG_itable_size(L,index);
+	if (*size<1){
+		lua_pushstring(L,"table appears to be empty");
+		return 0;
+	}
+	array=SWIG_ALLOC_ARRAY(void*,*size);
+	if (!SWIG_read_ptr_array(L,index,array,*size,type)){
+		lua_pushfstring(L,"table must contain pointers of type %s",type->name);
+		SWIG_FREE_ARRAY(array);
+		return 0;
+	}
+	return array;
+}
+SWIGINTERN void SWIG_write_ptr_array(lua_State* L,void **array,int size,swig_type_info *type,int own){
+	int i;
+	lua_newtable(L);
+	for (i = 0; i < size; i++){
+		SWIG_NewPointerObj(L,array[i],type,own);
+		lua_rawseti(L,-2,i+1);/* -1 is the number, -2 is the table*/
+	}
+}
+%}
+
+// fixed size array's
+%typemap(in) SWIGTYPE* INPUT[ANY]
+%{	$1 = ($ltype)SWIG_get_ptr_array_fixed(L,$input,$1_dim0,$*1_descriptor);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) SWIGTYPE* INPUT[ANY]
+%{	SWIG_FREE_ARRAY($1);%}
+
+// variable size array's
+%typemap(in) (SWIGTYPE **INPUT,int)
+%{	$1 = ($ltype)SWIG_get_ptr_array_var(L,$input,&$2,$*1_descriptor);
+	if (!$1) SWIG_fail;%}
+
+%typemap(freearg) (SWIGTYPE **INPUT,int)
+%{	SWIG_FREE_ARRAY($1);%}
+
+// out fixed arrays
+%typemap(in,numinputs=0) SWIGTYPE* OUTPUT[ANY]
+%{  $1 = SWIG_ALLOC_ARRAY($*1_type,$1_dim0); %}
+
+%typemap(argout) SWIGTYPE* OUTPUT[ANY]
+%{	SWIG_write_ptr_array(L,(void**)$1,$1_dim0,$*1_descriptor,0); SWIG_arg++; %}
+
+%typemap(freearg) SWIGTYPE* OUTPUT[ANY]
+%{	SWIG_FREE_ARRAY($1); %}
+
+// inout fixed arrays
+%typemap(in) SWIGTYPE* INOUT[ANY]=SWIGTYPE* INPUT[ANY];
+%typemap(argout) SWIGTYPE* INOUT[ANY]=SWIGTYPE* OUTPUT[ANY];
+%typemap(freearg) SWIGTYPE* INOUT[ANY]=SWIGTYPE* INPUT[ANY];
+// inout variable arrays
+%typemap(in) (SWIGTYPE** INOUT,int)=(SWIGTYPE** INPUT,int);
+%typemap(argout) (SWIGTYPE** INOUT,int)
+%{	SWIG_write_ptr_array(L,(void**)$1,$2,$*1_descriptor,0); SWIG_arg++; %}
+%typemap(freearg) (SWIGTYPE**INOUT,int)=(SWIGTYPE**INPUT,int);
+
+/* -----------------------------------------------------------------------------
+ *                          Pointer-Pointer typemaps
+ * ----------------------------------------------------------------------------- */
+/*
+This code is to deal with the issue for pointer-pointer's
+In particular for factory methods.
+
+for example take the following code segment:
+
+struct iMath;    // some structure
+int Create_Math(iMath** pptr); // its factory (assume it mallocs)
+
+to use it you might have the following C code:
+
+iMath* ptr;
+int ok;
+ok=Create_Math(&ptr);
+// do things with ptr
+//...
+free(ptr);
+
+With the following SWIG code
+%apply SWIGTYPE** OUTPUT{iMath **pptr };
+
+You can get natural wrappering in Lua as follows:
+ok,ptr=Create_Math() -- ptr is a iMath* which is returned with the int
+ptr=nil -- the iMath* will be GC'ed as normal
+*/
+
+%typemap(in,numinputs=0) SWIGTYPE** OUTPUT ($*ltype temp)
+%{  $1 = &temp; %}
+%typemap(argout) SWIGTYPE** OUTPUT
+%{SWIG_NewPointerObj(L,*$1,$*descriptor,1); SWIG_arg++; %}
+
diff --git a/trunk/Lib/lua/wchar.i b/trunk/Lib/lua/wchar.i
new file mode 100644
index 0000000..5b206eb
--- /dev/null
+++ b/trunk/Lib/lua/wchar.i
@@ -0,0 +1,46 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * wchar.i
+ *
+ * Typemaps for the wchar_t type
+ * These are mapped to a Lua string and are passed around by value.
+ *
+ * ----------------------------------------------------------------------------- */
+
+// note: only support for pointer right now, not fixed length strings
+// TODO: determine how long a const wchar_t* is so we can write wstr2str() 
+// & do the output typemap
+
+%{
+#include <stdlib.h>
+	
+wchar_t* str2wstr(const char* str, int len)
+{
+  wchar_t* p;
+  if (str==0 || len<1)  return 0;
+  p=(wchar*)malloc((len+1)*sizeof(wchar_t));
+  if (p==0)	return 0;
+  if (mbstowcs(p, str, len)==-1)
+  {
+    free(p);
+    return 0;
+  }
+  p[len]=0;
+  return p;
+}
+%}
+
+%typemap( in, checkfn="lua_isstring" ) wchar_t*
+%{
+$1 = str2wstr(lua_tostring( L, $input ),lua_strlen( L, $input ));
+if ($1==0) {lua_pushfstring(L,"Error in converting to wchar (arg %d)",$input);goto fail;}
+%}
+
+%typemap( freearg ) wchar_t*
+%{
+free($1);
+%}
+
+%typemap(typecheck) wchar_t * = char *;
\ No newline at end of file
diff --git a/trunk/Lib/math.i b/trunk/Lib/math.i
new file mode 100644
index 0000000..be931d7
--- /dev/null
+++ b/trunk/Lib/math.i
@@ -0,0 +1,85 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * math.i
+ *
+ * SWIG library file for floating point operations.
+ * ----------------------------------------------------------------------------- */
+
+%module math
+%{
+#include <math.h>
+%}
+
+extern double	cos(double x);
+/* Cosine of x */
+
+extern double	sin(double x);
+/* Sine of x */
+
+extern double	tan(double x);
+/* Tangent of x */
+
+extern double	acos(double x);
+/* Inverse cosine in range [-PI/2,PI/2], x in [-1,1]. */
+
+extern double	asin(double x);
+/* Inverse sine in range [0,PI], x in [-1,1]. */
+
+extern double	atan(double x);
+/* Inverse tangent in range [-PI/2,PI/2]. */
+
+extern double	atan2(double y, double x);
+/* Inverse tangent of y/x in range [-PI,PI]. */
+
+extern double	cosh(double x);
+/* Hyperbolic cosine of x */
+
+extern double	sinh(double x);
+/* Hyperbolic sine of x */
+
+extern double	tanh(double x);
+/* Hyperbolic tangent of x */
+
+extern double	exp(double x);
+/* Natural exponential function e^x */
+
+extern double	log(double x);
+/* Natural logarithm ln(x), x > 0 */
+
+extern double	log10(double x);
+/* Base 10 logarithm, x > 0 */
+
+extern double	pow(double x, double y);
+/* Power function x^y. */
+
+extern double	sqrt(double x);
+/* Square root. x >= 0 */
+
+extern double	fabs(double x);
+/* Absolute value of x */
+
+extern double	ceil(double x);
+/* Smallest integer not less than x, as a double */
+
+extern double	floor(double x);
+/* Largest integer not greater than x, as a double */
+
+extern double	fmod(double x, double y);
+/* Floating-point remainder of x/y, with the same sign as x. */
+
+#define M_E		2.7182818284590452354
+#define M_LOG2E		1.4426950408889634074
+#define M_LOG10E	0.43429448190325182765
+#define M_LN2		0.69314718055994530942
+#define M_LN10		2.30258509299404568402
+#define M_PI		3.14159265358979323846
+#define M_PI_2		1.57079632679489661923
+#define M_PI_4		0.78539816339744830962
+#define M_1_PI		0.31830988618379067154
+#define M_2_PI		0.63661977236758134308
+#define M_2_SQRTPI	1.12837916709551257390
+#define M_SQRT2		1.41421356237309504880
+#define M_SQRT1_2	0.70710678118654752440
+
diff --git a/trunk/Lib/modula3/modula3.swg b/trunk/Lib/modula3/modula3.swg
new file mode 100644
index 0000000..6a1b4d9
--- /dev/null
+++ b/trunk/Lib/modula3/modula3.swg
@@ -0,0 +1,750 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * modula3.swg
+ *
+ * Modula3 typemaps
+ * ----------------------------------------------------------------------------- */
+
+%include <modula3head.swg>
+
+/* The ctype, m3rawtype and m3wraptype typemaps work together and so there should be one of each. 
+ * The ctype typemap contains the C type used in the signature of C wrappers for C++ functions. 
+ * The m3rawtype typemap contains the M3 type used in the raw interface.
+ * The m3rawintype typemap contains the M3 type used as function argument.
+ * The m3rawrettype typemap contains the M3 type used as return value.
+ * The m3wraptype typemap contains the M3 type used in the M3 type wrapper classes and module class. */
+
+/* Primitive types */
+%typemap(ctype) bool,               const bool &               "bool"
+%typemap(ctype) char,               const char &               "char"
+%typemap(ctype) signed char,        const signed char &        "signed char"
+%typemap(ctype) unsigned char,      const unsigned char &      "unsigned short"
+%typemap(ctype) short,              const short &              "short"
+%typemap(ctype) unsigned short,     const unsigned short &     "unsigned short"
+%typemap(ctype) int,                const int &                "int"
+%typemap(ctype) unsigned int,       const unsigned int &       "unsigned int"
+%typemap(ctype) long,               const long &               "long"
+%typemap(ctype) unsigned long,      const unsigned long &      "unsigned long"
+%typemap(ctype) long long,          const long long &          "long long"
+%typemap(ctype) unsigned long long, const unsigned long long & "unsigned long long"
+%typemap(ctype) float,              const float &              "float"
+%typemap(ctype) double,             const double &             "double"
+%typemap(ctype) char *                                         "char *"
+%typemap(ctype) void                                           "void"
+
+%typemap(m3rawtype) bool,               const bool &               "BOOLEAN"
+%typemap(m3rawtype) char,               const char &               "C.char"
+%typemap(m3rawtype) signed char,        const signed char &        "C.signed_char"
+%typemap(m3rawtype) unsigned char,      const unsigned char &      "C.unsigned_char"
+%typemap(m3rawtype) short,              const short &              "C.short"
+%typemap(m3rawtype) unsigned short,     const unsigned short &     "C.unsigned_short"
+%typemap(m3rawtype) int,                const int &                "C.int"
+%typemap(m3rawtype) unsigned int,       const unsigned int &       "C.unsigned_int"
+%typemap(m3rawtype) long,               const long &               "C.long"
+%typemap(m3rawtype) unsigned long,      const unsigned long &      "C.unsigned_long"
+%typemap(m3rawtype) long long,          const long long &          "C.long_long"
+%typemap(m3rawtype) unsigned long long, const unsigned long long & "C.unsigned_long_long"
+%typemap(m3rawtype) float,              const float &              "C.float"
+%typemap(m3rawtype) double,             const double &             "C.double"
+%typemap(m3rawtype) long double,        const long double &        "C.long_double"
+%typemap(m3rawtype) char *                                         "C.char_star"
+%typemap(m3rawtype) void                                           ""
+%typemap(m3rawtype) FILE                                           "Cstdio.FILE";
+%typemap(m3rawtype) FILE *                                         "Cstdio.FILE_star";
+
+
+%typemap(m3rawintype) bool *,               bool &,               bool               "BOOLEAN"
+%typemap(m3rawintype) char *,               char &,               char               "C.char"
+%typemap(m3rawintype) signed char *,        signed char &,        signed char        "C.signed_char"
+%typemap(m3rawintype) unsigned char *,      unsigned char &,      unsigned char      "C.unsigned_char"
+%typemap(m3rawintype) short *,              short &,              short              "C.short"
+%typemap(m3rawintype) unsigned short *,     unsigned short &,     unsigned short     "C.unsigned_short"
+%typemap(m3rawintype) int *,                int &,                int                "C.int"
+%typemap(m3rawintype) unsigned int *,       unsigned int &,       unsigned int       "C.unsigned_int"
+%typemap(m3rawintype) long *,               long &,               long               "C.long"
+%typemap(m3rawintype) unsigned long *,      unsigned long &,      unsigned long      "C.unsigned_long"
+%typemap(m3rawintype) long long *,          long long &,          long long          "C.long_long"
+%typemap(m3rawintype) unsigned long long *, unsigned long long &, unsigned long long "C.unsigned_long_long"
+%typemap(m3rawintype) float *,              float &,              float              "C.float"
+%typemap(m3rawintype) double *,             double &,             double             "C.double"
+%typemap(m3rawintype) long double *,        long double &,        long double        "C.long_double"
+%typemap(m3rawintype) char *                                                         "C.char_star"
+%typemap(m3rawintype) void                                                           ""
+%typemap(m3rawintype) void *                                                         "ADDRESS"
+%typemap(m3rawintype) FILE                                                           "Cstdio.FILE";
+%typemap(m3rawintype) FILE *                                                         "Cstdio.FILE_star";
+
+%typemap(m3rawinmode) char *, void *, FILE *  ""
+
+
+%typemap(m3rawrettype) bool,               const bool &               "BOOLEAN"
+%typemap(m3rawrettype) char,               const char &               "C.char"
+%typemap(m3rawrettype) signed char,        const signed char &        "C.signed_char"
+%typemap(m3rawrettype) unsigned char,      const unsigned char &      "C.unsigned_char"
+%typemap(m3rawrettype) short,              const short &              "C.short"
+%typemap(m3rawrettype) unsigned short,     const unsigned short &     "C.unsigned_short"
+%typemap(m3rawrettype) int,                const int &                "C.int"
+%typemap(m3rawrettype) unsigned int,       const unsigned int &       "C.unsigned_int"
+%typemap(m3rawrettype) long,               const long &               "C.long"
+%typemap(m3rawrettype) unsigned long,      const unsigned long &      "C.unsigned_long"
+%typemap(m3rawrettype) long long,          const long long &          "C.long_long"
+%typemap(m3rawrettype) unsigned long long, const unsigned long long & "C.unsigned_long_long"
+%typemap(m3rawrettype) float,              const float &              "C.float"
+%typemap(m3rawrettype) double,             const double &             "C.double"
+%typemap(m3rawrettype) long double,        const long double &        "C.long_double"
+%typemap(m3rawrettype) char *                                         "C.char_star"
+%typemap(m3rawrettype) void                                           ""
+%typemap(m3rawrettype) void *                                         "ADDRESS"
+%typemap(m3rawrettype) FILE                                           "Cstdio.FILE";
+%typemap(m3rawrettype) FILE *                                         "Cstdio.FILE_star";
+
+
+%typemap("m3rawtype:import")
+  char,               const char &,
+  signed char,        const signed char &,
+  unsigned char,      const unsigned char &,
+  short,              const short &,
+  unsigned short,     const unsigned short &,
+  int,                const int &,
+  unsigned int,       const unsigned int &,
+  long,               const long &,
+  unsigned long,      const unsigned long &,
+  long long,          const long long &,
+  unsigned long long, const unsigned long long &,
+  float,              const float &,
+  double,             const double &,
+  long double,        const long double &,
+  char *
+    "Ctypes AS C"
+
+%typemap("m3rawintype:import")
+  char,               const char &,
+  signed char,        const signed char &,
+  unsigned char,      const unsigned char &,
+  short,              const short &,
+  unsigned short,     const unsigned short &,
+  int,                const int &,
+  unsigned int,       const unsigned int &,
+  long,               const long &,
+  unsigned long,      const unsigned long &,
+  long long,          const long long &,
+  unsigned long long, const unsigned long long &,
+  float,              const float &,
+  double,             const double &,
+  long double,        const long double &,
+  char *
+    "Ctypes AS C"
+
+%typemap("m3rawrettype:import")
+  char,               const char &,
+  signed char,        const signed char &,
+  unsigned char,      const unsigned char &,
+  short,              const short &,
+  unsigned short,     const unsigned short &,
+  int,                const int &,
+  unsigned int,       const unsigned int &,
+  long,               const long &,
+  unsigned long,      const unsigned long &,
+  long long,          const long long &,
+  unsigned long long, const unsigned long long &,
+  float,              const float &,
+  double,             const double &,
+  long double,        const long double &,
+  char *
+    "Ctypes AS C"
+
+%typemap("m3rawtype:import")
+  FILE,   FILE *
+    "Cstdio";
+
+%typemap("m3rawintype:import")
+  FILE,   FILE *
+    "Cstdio";
+
+%typemap("m3rawrettype:import")
+  FILE,   FILE *
+    "Cstdio";
+
+%typemap(m3wraptype) bool,               const bool &               "BOOLEAN"
+%typemap(m3wraptype) char,               const char &               "CHAR"
+%typemap(m3wraptype) signed char,        const signed char &        "CHAR"
+%typemap(m3wraptype) unsigned char,      const unsigned char &      "CHAR"
+%typemap(m3wraptype) short,              const short &              "Integer16.T"
+%typemap(m3wraptype) unsigned short,     const unsigned short &     "Cardinal16.T"
+%typemap(m3wraptype) int,                const int &                "INTEGER"
+%typemap(m3wraptype) unsigned int,       const unsigned int &       "CARDINAL"
+%typemap(m3wraptype) long,               const long &               "Integer32.T"
+%typemap(m3wraptype) unsigned long,      const unsigned long &      "Cardinal32.T"
+%typemap(m3wraptype) long long,          const long long &          "Integer64.T"
+%typemap(m3wraptype) unsigned long long, const unsigned long long & "Cardinal64.T"
+%typemap(m3wraptype) float,              const float &              "REAL"
+%typemap(m3wraptype) double,             const double &             "LONGREAL"
+%typemap(m3wraptype) long double,        const long double &        "EXTENDED"
+%typemap(m3wraptype) char *                                         "TEXT"
+%typemap(m3wraptype) void                                           ""
+%typemap(m3wraptype) FILE                                           "Cstdio.FILE";
+%typemap(m3wraptype) FILE *                                         "Cstdio.FILE_star";
+
+%typemap(m3wrapintype) bool,               const bool *,               const bool &               "BOOLEAN"
+%typemap(m3wrapintype) char,               const char *,               const char &               "CHAR"
+%typemap(m3wrapintype) signed char,        const signed char *,        const signed char &        "CHAR"
+%typemap(m3wrapintype) unsigned char,      const unsigned char *,      const unsigned char &      "CHAR"
+%typemap(m3wrapintype) short,              const short *,              const short &              "INTEGER"
+%typemap(m3wrapintype) unsigned short,     const unsigned short *,     const unsigned short &     "CARDINAL"
+%typemap(m3wrapintype) int,                const int *,                const int &                "INTEGER"
+%typemap(m3wrapintype) unsigned int,       const unsigned int *,       const unsigned int &       "CARDINAL"
+%typemap(m3wrapintype) long,               const long *,               const long &               "INTEGER"
+%typemap(m3wrapintype) unsigned long,      const unsigned long *,      const unsigned long &      "CARDINAL"
+%typemap(m3wrapintype) long long,          const long long *,          const long long &          "INTEGER"
+%typemap(m3wrapintype) unsigned long long, const unsigned long long *, const unsigned long long & "CARDINAL"
+%typemap(m3wrapintype) float,              const float *,              const float &              "REAL"
+%typemap(m3wrapintype) double,             const double *,             const double &             "LONGREAL"
+%typemap(m3wrapintype) long double,        const long double *,        const long double &        "EXTENDED"
+%typemap(m3wrapintype) const char *, const char []   "TEXT"
+%typemap(m3wrapintype,numinputs=0) void              ""
+%typemap(m3wrapintype) FILE            "Cstdio.FILE";
+%typemap(m3wrapintype) FILE *          "Cstdio.FILE_star";
+
+
+%typemap(m3wrapouttype) bool,               bool *,               bool &                  "BOOLEAN"
+%typemap(m3wrapouttype) char,               char *,               char &                  "CHAR"
+%typemap(m3wrapouttype) signed char,        signed char *,        signed char &           "CHAR"
+%typemap(m3wrapouttype) unsigned char,      unsigned char *,      unsigned char &         "CHAR"
+%typemap(m3wrapouttype) short,              short *,              short &                 "INTEGER"
+%typemap(m3wrapouttype) unsigned short,     unsigned short *,     unsigned short &        "CARDINAL"
+%typemap(m3wrapouttype) int,                int *,                int &                   "INTEGER"
+%typemap(m3wrapouttype) unsigned int,       unsigned int *,       unsigned int &          "CARDINAL"
+%typemap(m3wrapouttype) long,               long *,               long &                  "INTEGER"
+%typemap(m3wrapouttype) unsigned long,      unsigned long *,      unsigned long &         "CARDINAL"
+%typemap(m3wrapouttype) long long,          long long *,          long long &             "INTEGER"
+%typemap(m3wrapouttype) unsigned long long, unsigned long long *, unsigned long long &    "CARDINAL"
+%typemap(m3wrapouttype) float,              float *,              float &                 "REAL"
+%typemap(m3wrapouttype) double,             double *,             double &                "LONGREAL"
+%typemap(m3wrapouttype) long double,        long double *,        long double &           "EXTENDED"
+%typemap(m3wrapouttype) char *, char []    "TEXT"
+%typemap(m3wrapouttype,numinputs=0) void   ""
+
+%typemap(m3wraprettype) bool,               const bool &               "BOOLEAN"
+%typemap(m3wraprettype) char,               const char &               "CHAR"
+%typemap(m3wraprettype) signed char,        const signed char &        "CHAR"
+%typemap(m3wraprettype) unsigned char,      const unsigned char &      "CHAR"
+%typemap(m3wraprettype) short,              const short &              "INTEGER"
+%typemap(m3wraprettype) unsigned short,     const unsigned short &     "CARDINAL"
+%typemap(m3wraprettype) int,                const int &                "INTEGER"
+%typemap(m3wraprettype) unsigned int,       const unsigned int &       "CARDINAL"
+%typemap(m3wraprettype) long,               const long &               "INTEGER"
+%typemap(m3wraprettype) unsigned long,      const unsigned long &      "CARDINAL"
+%typemap(m3wraprettype) long long,          const long long &          "INTEGER"
+%typemap(m3wraprettype) unsigned long long, const unsigned long long & "CARDINAL"
+%typemap(m3wraprettype) float,              const float &              "REAL"
+%typemap(m3wraprettype) double,             const double &             "LONGREAL"
+%typemap(m3wraprettype) long double,        const long double &        "EXTENDED"
+%typemap(m3wraprettype) char *                                         "TEXT"
+%typemap(m3wraprettype) void                                           ""
+%typemap(m3wraprettype) FILE            "Cstdio.FILE";
+%typemap(m3wraprettype) FILE *          "Cstdio.FILE_star";
+
+
+%typemap(ctype)          char[ANY]               "char *"
+%typemap(m3rawtype)      char[ANY]               "C.char_star"
+%typemap(m3rawintype)    char[ANY]               "C.char_star"
+%typemap(m3rawrettype)   char[ANY]               "C.char_star"
+%typemap(m3wraptype)     char[ANY]               "TEXT"
+%typemap(m3wrapintype)   char[ANY]               "TEXT"
+%typemap(m3wrapouttype)  char[ANY]               "TEXT"
+%typemap(m3wraprettype)  char[ANY]               "TEXT"
+
+%typemap(m3wrapinmode)  const char * %{%}
+%typemap(m3wrapargvar)  const char * %{$1 : C.char_star;%}
+%typemap(m3wrapinconv)  const char * %{$1 := M3toC.SharedTtoS($1_name);%}
+%typemap(m3wrapfreearg) const char * %{M3toC.FreeSharedS($1_name,$1);%}
+%typemap(m3wrapargraw)  const char * %{$1%}
+%typemap("m3wrapargvar:import")  const char * "Ctypes AS C"
+%typemap("m3wrapinconv:import")  const char * "M3toC"
+%typemap("m3wrapfreearg:import") const char * "M3toC"
+
+%typemap(m3wrapretvar)  char * %{result : C.char_star;%}
+%typemap(m3wrapretraw)  char * %{result%}
+%typemap(m3wrapretconv) char * %{M3toC.CopyStoT(result)%}
+%typemap("m3wrapretvar:import")  char * "Ctypes AS C"
+%typemap("m3wrapretconv:import") char * "M3toC"
+
+%typemap(m3wrapinmode)  FILE * %{%}
+
+
+%typemap("m3wraptype:import")
+  FILE,   FILE *
+    "Cstdio";
+
+%typemap("m3wrapintype:import")
+  FILE,   FILE *
+    "Cstdio";
+
+%typemap("m3wraprettype:import")
+  FILE,   FILE *
+    "Cstdio";
+
+
+/* Composed types */
+%typemap(ctype)                SWIGTYPE "$1_type"
+%typemap(m3rawtype)            SWIGTYPE "$1_basetype"
+%typemap(m3rawrettype)         SWIGTYPE "UNTRACED REF $1_basetype"
+%typemap(m3wraptype)           SWIGTYPE "$1_basetype"
+%typemap(m3wrapintype)         SWIGTYPE "$1_basetype"
+%typemap(m3wrapouttype)        SWIGTYPE "$1_basetype"
+%typemap(m3wraprettype)        SWIGTYPE "$1_basetype"
+
+%typemap(ctype)                SWIGTYPE [] "$1_type"
+%typemap(m3rawtype)      const SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype"
+%typemap(m3rawtype)            SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype"
+%typemap(m3rawintype)    const SWIGTYPE [] "(*ARRAY OF*) $1_basetype"
+%typemap(m3rawinmode)    const SWIGTYPE [] "READONLY"
+%typemap(m3rawintype)          SWIGTYPE [] "(*ARRAY OF*) $1_basetype"
+%typemap(m3rawinmode)          SWIGTYPE [] "VAR"
+%typemap(m3rawrettype)   const SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype"
+%typemap(m3rawrettype)         SWIGTYPE [] "UNTRACED REF ARRAY INTEGER OF $1_basetype"
+%typemap(m3wraptype)           SWIGTYPE [] "$1_basetype"
+%typemap(m3wrapintype)   const SWIGTYPE [] "ARRAY OF $1_basetype"
+%typemap(m3wrapinmode)   const SWIGTYPE [] "READONLY"
+%typemap(m3wrapintype)         SWIGTYPE [] "ARRAY OF $1_basetype"
+%typemap(m3wrapinmode)         SWIGTYPE [] "VAR"
+%typemap(m3wrapouttype)        SWIGTYPE [] "ARRAY OF $1_basetype"
+%typemap(m3wraprettype)        SWIGTYPE [] "REF ARRAY OF $1_basetype"
+
+%typemap(ctype)                SWIGTYPE * "$1_type"
+%typemap(m3rawtype)      const SWIGTYPE * "UNTRACED REF $1_basetype"
+%typemap(m3rawtype)            SWIGTYPE * "UNTRACED REF $1_basetype"
+%typemap(m3rawintype)    const SWIGTYPE * "$1_basetype"
+%typemap(m3rawinmode)    const SWIGTYPE * "READONLY"
+%typemap(m3rawintype)          SWIGTYPE * "$1_basetype"
+%typemap(m3rawinmode)          SWIGTYPE * "VAR"
+%typemap(m3rawrettype)   const SWIGTYPE * "UNTRACED REF $1_basetype"
+%typemap(m3rawrettype)         SWIGTYPE * "UNTRACED REF $1_basetype"
+%typemap(m3wraptype)           SWIGTYPE * "$1_basetype"
+%typemap(m3wrapintype)   const SWIGTYPE * "$1_basetype"
+%typemap(m3wrapinmode)   const SWIGTYPE * "READONLY"
+%typemap(m3wrapintype)         SWIGTYPE * "$1_basetype"
+%typemap(m3wrapinmode)         SWIGTYPE * "VAR"
+%typemap(m3wrapouttype)        SWIGTYPE * "$1_basetype"
+%typemap(m3wraprettype)        SWIGTYPE * "UNTRACED REF $1_basetype"
+
+%typemap(ctype)                SWIGTYPE & "$1_type"
+%typemap(m3rawtype)      const SWIGTYPE & "UNTRACED REF $1_basetype"
+%typemap(m3rawtype)            SWIGTYPE & "UNTRACED REF $1_basetype"
+%typemap(m3rawintype)    const SWIGTYPE & "$1_basetype"
+%typemap(m3rawinmode)    const SWIGTYPE & "READONLY"
+%typemap(m3rawintype)          SWIGTYPE & "$1_basetype"
+%typemap(m3rawinmode)          SWIGTYPE & "VAR"
+%typemap(m3rawrettype)   const SWIGTYPE & "UNTRACED REF $1_basetype"
+%typemap(m3rawrettype)         SWIGTYPE & "UNTRACED REF $1_basetype"
+%typemap(m3wraptype)           SWIGTYPE & "$1_basetype"
+%typemap(m3wrapintype)   const SWIGTYPE & "$1_basetype"
+%typemap(m3wrapinmode)   const SWIGTYPE & "READONLY"
+%typemap(m3wrapintype)         SWIGTYPE & "$1_basetype"
+%typemap(m3wrapinmode)         SWIGTYPE & "VAR"
+%typemap(m3wrapouttype)        SWIGTYPE & "$1_basetype"
+%typemap(m3wraprettype)        SWIGTYPE & "UNTRACED REF $1_basetype"
+
+%typemap(ctype)           enum SWIGTYPE "$1_type"
+%typemap(m3rawtype)       enum SWIGTYPE "C.int"
+%typemap(m3rawintype)     enum SWIGTYPE "C.int (* $1_type *)"
+%typemap(m3rawrettype)    enum SWIGTYPE "C.int"
+%typemap(m3wraptype)      enum SWIGTYPE "$*1_type"
+%typemap(m3wrapintype)    enum SWIGTYPE "$1_type"
+%typemap(m3wrapouttype)   enum SWIGTYPE "$1_type"
+%typemap(m3wraprettype)   enum SWIGTYPE "$*1_type"
+
+/* pointer to a class member */
+%typemap(ctype)      SWIGTYPE (CLASS::*) "$1_type"
+%typemap(m3rawtype)  SWIGTYPE (CLASS::*) "REFANY"
+%typemap(m3wraptype) SWIGTYPE (CLASS::*) "$1_basetype"
+
+/* The following are the in, out, freearg, argout typemaps.
+   These are the PInvoke code generating typemaps for converting from C# to C and visa versa. */
+
+/* primitive types */
+%typemap(in) bool
+%{ $1 = $input ? true : false; %}
+
+%typemap(in) char, 
+             signed char, 
+             unsigned char, 
+             short, 
+             unsigned short, 
+             int, 
+             unsigned int, 
+             long, 
+             unsigned long, 
+             long long, 
+             unsigned long long, 
+             float, 
+             double, 
+             enum SWIGTYPE
+%{ $1 = ($1_ltype)$input; %}
+
+%typemap(out) bool               %{ $result = $1; %}
+%typemap(out) char               %{ $result = $1; %}
+%typemap(out) signed char        %{ $result = $1; %}
+%typemap(out) unsigned char      %{ $result = $1; %}
+%typemap(out) short              %{ $result = $1; %}
+%typemap(out) unsigned short     %{ $result = $1; %}
+%typemap(out) int                %{ $result = $1; %}
+%typemap(out) unsigned int       %{ $result = $1; %}
+%typemap(out) long               %{ $result = $1; %}
+%typemap(out) unsigned long      %{ $result = $1; %}
+%typemap(out) long long          %{ $result = $1; %}
+%typemap(out) unsigned long long %{ $result = $1; %}
+%typemap(out) float              %{ $result = $1; %}
+%typemap(out) double             %{ $result = $1; %}
+%typemap(out) enum SWIGTYPE      %{ $result = $1; %}
+
+/* char * - treat as String */
+%typemap(in) char * {
+  $1 = $input;
+}
+//%typemap(freearg) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, $1); }
+//%typemap(out) char * { if($1) $result = JCALL1(NewStringUTF, jenv, $1); }
+
+%typemap(out) void ""
+
+/* primitive types by const reference */
+%typemap(in) const bool & (bool temp)
+%{ temp = $input ? true : false; 
+   $1 = &temp; %}
+
+%typemap(in) const char & (char temp), 
+             const signed char & (signed char temp), 
+             const unsigned char & (unsigned char temp), 
+             const short & (short temp), 
+             const unsigned short & (unsigned short temp), 
+             const int & (int temp), 
+             const unsigned int & (unsigned int temp), 
+             const long & (long temp), 
+             const unsigned long & (unsigned long temp), 
+             const long long & ($*1_ltype temp), 
+             const unsigned long long & ($*1_ltype temp), 
+             const float & (float temp), 
+             const double & (double temp)
+%{ temp = ($*1_ltype)$input; 
+$1 = &temp; %}
+
+%typemap(out) const bool &               %{ $result = *$1; %}
+%typemap(out) const char &               %{ $result = *$1; %}
+%typemap(out) const signed char &        %{ $result = *$1; %}
+%typemap(out) const unsigned char &      %{ $result = *$1; %}
+%typemap(out) const short &              %{ $result = *$1; %}
+%typemap(out) const unsigned short &     %{ $result = *$1; %}
+%typemap(out) const int &                %{ $result = *$1; %}
+%typemap(out) const unsigned int &       %{ $result = *$1; %}
+%typemap(out) const long &               %{ $result = *$1; %}
+%typemap(out) const unsigned long &      %{ $result = *$1; %}
+%typemap(out) const long long &          %{ $result = *$1; %}
+%typemap(out) const unsigned long long & %{ $result = *$1; %}
+%typemap(out) const float &              %{ $result = *$1; %}
+%typemap(out) const double &             %{ $result = *$1; %}
+
+/* Default handling. Object passed by value. Convert to a pointer */
+%typemap(in) SWIGTYPE ($&1_type argp)
+%{ argp = *($&1_ltype*)&$input; 
+   if (!argp) {
+//     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type");
+     RETURN $null;
+   }
+   $1 = *argp; %}
+%typemap(out) SWIGTYPE 
+#ifdef __cplusplus
+%{*($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %}
+#else
+{
+  $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype));
+  memmove($1ptr, &$1, sizeof($1_type));
+  *($&1_ltype*)&$result = $1ptr;
+}
+#endif
+
+/* Generic pointers and references */
+%typemap(in) SWIGTYPE *, SWIGTYPE (CLASS::*) %{ $1 = *($&1_ltype)&$input; %}
+%typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input;
+  if(!$1) {
+    //SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null");
+    RETURN $null;
+  } %}
+%typemap(out) SWIGTYPE *, SWIGTYPE &, SWIGTYPE (CLASS::*) %{ *($&1_ltype)&$result = $1; %} 
+
+
+/* Default array handling */
+%typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %}
+%typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %} 
+
+/* char[ANY] - treat as String */
+%typemap(in) char[ANY] { 
+    $1 = $input;
+}
+
+%typemap(argout) char[ANY] ""
+%typemap(freearg) char[ANY] ""//{ if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, $1); }
+%typemap(out) char[ANY] { if($1) $result = $1; }
+
+
+/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions 
+ * that cannot be overloaded in C# as more than one C++ type maps to a single C# type */
+
+%typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */
+    bool,
+    const bool &
+    ""
+
+%typecheck(SWIG_TYPECHECK_CHAR) /* Java char */
+    char, 
+    const char &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT8) /* Java byte */
+    signed char,
+    const signed char &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT16) /* Java short */
+    unsigned char, 
+    short, 
+    const unsigned char &, 
+    const short &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT32) /* Java int */
+    unsigned short, 
+    int, 
+    long, 
+    const unsigned short &, 
+    const int &, 
+    const long &,
+    enum SWIGTYPE
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT64) /* Java long */
+    unsigned int, 
+    unsigned long, 
+    long long, 
+    const unsigned int &, 
+    const unsigned long &, 
+    const long long &
+    ""
+
+%typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */
+    unsigned long long
+    ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */
+    float,
+    const float &
+    ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */
+    double,
+    const double &
+    ""
+
+%typecheck(SWIG_TYPECHECK_STRING) /* Java String */
+    char *,
+    char[ANY]
+    ""
+
+%typecheck(SWIG_TYPECHECK_POINTER) /* Default */
+    SWIGTYPE, 
+    SWIGTYPE *, 
+    SWIGTYPE &, 
+    SWIGTYPE [],
+    SWIGTYPE (CLASS::*)
+    ""
+
+/* Exception handling */
+
+%typemap(throws) int, 
+                 long, 
+                 short, 
+                 unsigned int, 
+                 unsigned long, 
+                 unsigned short {
+  char error_msg[256];
+  sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1);
+  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg);
+  RETURN $null;
+}
+
+%typemap(throws) SWIGTYPE {
+  (void)$1;
+  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown");
+  RETURN $null;
+}
+
+%typemap(throws) char * {
+  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1);
+  RETURN $null;
+}
+
+
+/* Typemaps for code generation in proxy classes and C# type wrapper classes */
+
+/* The in typemap is used for converting function parameter types from the type 
+ * used in the proxy, module or type wrapper class to the type used in the PInvoke class. */
+%typemap(m3in)     bool,               const bool &,
+                 char,               const char &,
+                 signed char,        const signed char &,
+                 unsigned char,      const unsigned char &,
+                 short,              const short &,
+                 unsigned short,     const unsigned short &,
+                 int,                const int &,
+                 unsigned int,       const unsigned int &,
+                 long,               const long &,
+                 unsigned long,      const unsigned long &,
+                 long long,          const long long &,
+                 unsigned long long, const unsigned long long &,
+                 float,              const float &,
+                 double,             const double &,
+                 char *,
+                 char[ANY],
+                 enum SWIGTYPE 
+    "$input"
+%typemap(m3in) SWIGTYPE "$&*1_type.getCPtr($input)"
+%typemap(m3in) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "$1_basetype.getCPtr($input)"
+
+/* The m3out typemap is used for converting function return types from the return type
+ * used in the PInvoke class to the type returned by the proxy, module or type wrapper class. */
+%typemap(m3out)   bool,               const bool &,
+                  char,               const char &,
+                  signed char,        const signed char &,
+                  unsigned char,      const unsigned char &,
+                  short,              const short &,
+                  unsigned short,     const unsigned short &,
+                  int,                const int &,
+                  unsigned int,       const unsigned int &,
+                  long,               const long &,
+                  unsigned long,      const unsigned long &,
+                  long long,          const long long &,
+                  unsigned long long, const unsigned long long &,
+                  float,              const float &,
+                  double,             const double &,
+                  char *,
+                  char[ANY],
+                  enum SWIGTYPE
+%{$imcall%}
+
+%typemap(m3out) void %{$imcall%}
+
+%typemap(m3out) SWIGTYPE %{
+    RETURN NEW(REF $1_basetype, $imcall);
+%}
+%typemap(m3out) SWIGTYPE & %{
+    RETURN NEW($1_basetype, $imcall, $owner);
+%}
+%typemap(m3out) SWIGTYPE *, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+    cPtr := $imcall;
+    RETURN (cPtr = IntPtr.Zero) ? null : NEW($1_basetype, cPtr, $owner);
+%}
+
+/* Properties */
+%typemap(m3varin) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+PROCEDURE Set$var (value: $vartype) =
+  BEGIN
+    $imcall;
+  END Set$var;
+%}
+
+%typemap(m3varout) bool,               const bool &,
+                   char,               const char &,
+                   signed char,        const signed char &,
+                   unsigned char,      const unsigned char &,
+                   short,              const short &,
+                   unsigned short,     const unsigned short &,
+                   int,                const int &,
+                   unsigned int,       const unsigned int &,
+                   long,               const long &,
+                   unsigned long,      const unsigned long &,
+                   long long,          const long long &,
+                   unsigned long long, const unsigned long long &,
+                   float,              const float &,
+                   double,             const double &,
+                   char *,
+                   char[ANY],
+                   enum SWIGTYPE %{
+PROCEDURE Get$var (): $vartype =
+  BEGIN
+    RETURN $imcall;
+  END Get$var;
+%}
+
+%typemap(m3varout) void %{
+    get {
+      $imcall;
+    } %}
+%typemap(m3varout) SWIGTYPE %{
+    get {
+      RETURN new $&*1_mangle($imcall, true);
+    } %}
+%typemap(m3varout) SWIGTYPE & %{
+    get {
+      RETURN new $1_basetype($imcall, $owner);
+    } %}
+%typemap(m3varout) SWIGTYPE *, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+    get {
+      IntPtr cPtr = $imcall;
+      RETURN (cPtr == IntPtr.Zero) ? null : new $1_basetype(cPtr, $owner);
+    } %}
+
+/* Typemaps used for the generation of proxy and type wrapper class code */
+%typemap(m3base)                      SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(m3classmodifiers)            SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public"
+%typemap(m3code)                      SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(m3imports)                   SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "using System;"
+%typemap(m3interfaces)                SWIGTYPE "IDisposable"
+%typemap(m3interfaces_derived)                  SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(m3ptrconstructormodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "internal"
+
+%typemap(m3finalize) SWIGTYPE %{
+  ~$1_basetype() {
+    Dispose();
+  }
+%}
+
+%typemap(m3destruct, methodname="Dispose") SWIGTYPE {
+    if(swigCPtr != IntPtr.Zero && swigCMemOwn) {
+      $imcall;
+      swigCMemOwn = false;
+    }
+    swigCPtr = IntPtr.Zero;
+    GC.SuppressFinalize(this);
+  }
+
+%typemap(m3destruct_derived, methodname="Dispose") SWIGTYPE {
+    if(swigCPtr != IntPtr.Zero && swigCMemOwn) {
+      $imcall;
+      swigCMemOwn = false;
+    }
+    swigCPtr = IntPtr.Zero;
+    GC.SuppressFinalize(this);
+    base.Dispose();
+  }
+
+%typemap(m3getcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
+  internal static IntPtr getCPtr($1_basetype obj) {
+    RETURN (obj == null) ? IntPtr.Zero : obj.swigCPtr;
+  }
+%}
+
+/* M3 specific directives */
+#define %m3multiretval        %feature("modula3:multiretval")
+#define %constnumeric(num)    %feature("constnumeric","num")
+
+%pragma(modula3) moduleimports=%{
+IMPORT BlaBla;
+%}
+
+%pragma(modula3) imclassimports=%{
+FROM BlaBla IMPORT Bla;
+%}
+
+/* Some ANSI C typemaps */
+
+%apply unsigned long { size_t };
diff --git a/trunk/Lib/modula3/modula3head.swg b/trunk/Lib/modula3/modula3head.swg
new file mode 100644
index 0000000..b2426be
--- /dev/null
+++ b/trunk/Lib/modula3/modula3head.swg
@@ -0,0 +1,67 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * modula3head.swg
+ *
+ * Modula3 support code
+ * ----------------------------------------------------------------------------- */
+
+%insert(runtime) %{
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+%}
+
+#if 0
+%insert(runtime) %{
+/* Support for throwing Modula3 exceptions */
+typedef enum {
+  SWIG_JavaOutOfMemoryError = 1, 
+  SWIG_JavaIOException, 
+  SWIG_JavaRuntimeException, 
+  SWIG_JavaIndexOutOfBoundsException,
+  SWIG_JavaArithmeticException,
+  SWIG_JavaIllegalArgumentException,
+  SWIG_JavaNullPointerException,
+  SWIG_JavaUnknownError
+} SWIG_JavaExceptionCodes;
+
+typedef struct {
+  SWIG_JavaExceptionCodes code;
+  const char *java_exception;
+} SWIG_JavaExceptions_t;
+
+#if defined(SWIG_NOINCLUDE)
+void SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg);
+#else
+%}
+%insert(runtime) {
+void SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg) {
+  jclass excep;
+  static const SWIG_JavaExceptions_t java_exceptions[] = {
+    { SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" },
+    { SWIG_JavaIOException, "java/io/IOException" },
+    { SWIG_JavaRuntimeException, "java/lang/RuntimeException" },
+    { SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" },
+    { SWIG_JavaArithmeticException, "java/lang/ArithmeticException" },
+    { SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" },
+    { SWIG_JavaNullPointerException, "java/lang/NullPointerException" },
+    { SWIG_JavaUnknownError,  "java/lang/UnknownError" },
+    { (SWIG_JavaExceptionCodes)0,  "java/lang/UnknownError" } };
+  const SWIG_JavaExceptions_t *except_ptr = java_exceptions;
+
+  while (except_ptr->code != code && except_ptr->code)
+    except_ptr++;
+
+  JCALL0(ExceptionClear, jenv);
+  excep = JCALL1(FindClass, jenv, except_ptr->java_exception);
+  if (excep)
+    JCALL2(ThrowNew, jenv, excep, msg);
+}
+}
+%insert(runtime) %{
+#endif
+%}
+#endif
diff --git a/trunk/Lib/modula3/typemaps.i b/trunk/Lib/modula3/typemaps.i
new file mode 100644
index 0000000..79ddfda
--- /dev/null
+++ b/trunk/Lib/modula3/typemaps.i
@@ -0,0 +1,77 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Pointer and reference handling typemap library
+ *
+ * These mappings provide support for input/output arguments and common
+ * uses for C/C++ pointers and C++ references.
+ * ----------------------------------------------------------------------------- */
+
+/* These typemaps will eventually probably maybe make their way into named typemaps
+ * OUTPUT * and OUTPUT & as they currently break functions that return a pointer or 
+ * reference. */
+
+%typemap(ctype) bool *,               bool &               "bool *"
+%typemap(ctype)                       char &               "char *"
+%typemap(ctype) signed char *,        signed char &        "signed char *"
+%typemap(ctype) unsigned char *,      unsigned char &      "unsigned short *"
+%typemap(ctype) short *,              short &              "short *"
+%typemap(ctype) unsigned short *,     unsigned short &     "unsigned short *"
+%typemap(ctype) int *,                int &                "int *"
+%typemap(ctype) unsigned int *,       unsigned int &       "unsigned int *"
+%typemap(ctype) long *,               long &               "long *"
+%typemap(ctype) unsigned long *,      unsigned long &      "unsigned long *"
+%typemap(ctype) long long *,          long long &          "long long *"
+%typemap(ctype) unsigned long long *, unsigned long long & "unsigned long long *"
+%typemap(ctype) float *,              float &              "float *"
+%typemap(ctype) double *,             double &             "double *"
+
+%typemap(imtype) bool *,               bool &               "ref bool"
+%typemap(imtype)                       char &               "ref char"
+%typemap(imtype) signed char *,        signed char &        "ref sbyte"
+%typemap(imtype) unsigned char *,      unsigned char &      "ref byte"
+%typemap(imtype) short *,              short &              "ref short"
+%typemap(imtype) unsigned short *,     unsigned short &     "ref ushort"
+%typemap(imtype) int *,                int &                "ref int"
+%typemap(imtype) unsigned int *,       unsigned int &       "ref uint"
+%typemap(imtype) long *,               long &               "ref int"
+%typemap(imtype) unsigned long *,      unsigned long &      "ref uint"
+%typemap(imtype) long long *,          long long &          "ref long"
+%typemap(imtype) unsigned long long *, unsigned long long & "ref ulong"
+%typemap(imtype) float *,              float &              "ref float"
+%typemap(imtype) double *,             double &             "ref double"
+
+%typemap(cstype) bool *,               bool &               "ref bool"
+%typemap(cstype)                       char &               "ref char"
+%typemap(cstype) signed char *,        signed char &        "ref sbyte"
+%typemap(cstype) unsigned char *,      unsigned char &      "ref byte"
+%typemap(cstype) short *,              short &              "ref short"
+%typemap(cstype) unsigned short *,     unsigned short &     "ref ushort"
+%typemap(cstype) int *,                int &                "ref int"
+%typemap(cstype) unsigned int *,       unsigned int &       "ref uint"
+%typemap(cstype) long *,               long &               "ref int"
+%typemap(cstype) unsigned long *,      unsigned long &      "ref uint"
+%typemap(cstype) long long *,          long long &          "ref long"
+%typemap(cstype) unsigned long long *, unsigned long long & "ref ulong"
+%typemap(cstype) float *,              float &              "ref float"
+%typemap(cstype) double *,             double &             "ref double"
+
+%typemap(csin)   bool *,               bool &,
+                                       char &,
+                 signed char *,        signed char &,
+                 unsigned char *,      unsigned char &,
+                 short *,              short &,
+                 unsigned short *,     unsigned short &,
+                 int *,                int &,
+                 unsigned int *,       unsigned int &,
+                 long *,               long &,
+                 unsigned long *,      unsigned long &,
+                 long long *,          long long &,
+                 unsigned long long *, unsigned long long &,
+                 float *,              float &,
+                 double *,             double &
+    "ref $csinput"
+
diff --git a/trunk/Lib/mzscheme/Makefile b/trunk/Lib/mzscheme/Makefile
new file mode 100644
index 0000000..ff66f9e
--- /dev/null
+++ b/trunk/Lib/mzscheme/Makefile
@@ -0,0 +1,4 @@
+
+co::
+	co RCS/*.i* RCS/*.swg*
+
diff --git a/trunk/Lib/mzscheme/mzrun.swg b/trunk/Lib/mzscheme/mzrun.swg
new file mode 100644
index 0000000..3b05d24
--- /dev/null
+++ b/trunk/Lib/mzscheme/mzrun.swg
@@ -0,0 +1,511 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * mzrun.swg
+ * ----------------------------------------------------------------------------- */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <escheme.h>
+#include <assert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Common SWIG API */
+  
+#define SWIG_ConvertPtr(s, result, type, flags) \
+  SWIG_MzScheme_ConvertPtr(s, result, type, flags)
+#define SWIG_NewPointerObj(ptr, type, owner) \
+  SWIG_MzScheme_NewPointerObj((void *)ptr, type, owner)
+#define SWIG_MustGetPtr(s, type, argnum, flags) \
+  SWIG_MzScheme_MustGetPtr(s, type, argnum, flags, FUNC_NAME, argc, argv)
+
+#define SWIG_contract_assert(expr,msg) \
+ if (!(expr)) { \
+    char *m=(char *) scheme_malloc(strlen(msg)+1000); \
+    sprintf(m,"SWIG contract, assertion failed: function=%s, message=%s", \
+            (char *) FUNC_NAME,(char *) msg); \
+    scheme_signal_error(m); \
+ }
+
+/* Runtime API */
+#define SWIG_GetModule(clientdata) SWIG_MzScheme_GetModule((Scheme_Env *)(clientdata))
+#define SWIG_SetModule(clientdata, pointer) SWIG_MzScheme_SetModule((Scheme_Env *) (clientdata), pointer)
+#define SWIG_MODULE_CLIENTDATA_TYPE Scheme_Env *
+
+/* MzScheme-specific SWIG API */
+  
+#define SWIG_malloc(size) SWIG_MzScheme_Malloc(size, FUNC_NAME)
+#define SWIG_free(mem) free(mem)
+#define SWIG_NewStructFromPtr(ptr,type) \
+        _swig_convert_struct_##type##(ptr)
+
+#define MAXVALUES 6
+#define swig_make_boolean(b) (b ? scheme_true : scheme_false)
+
+static long
+SWIG_convert_integer(Scheme_Object *o,
+		     long lower_bound, long upper_bound, 
+		     const char *func_name, int argnum, int argc,
+		     Scheme_Object **argv)
+{
+  long value;
+  int status = scheme_get_int_val(o, &value);
+  if (!status)
+    scheme_wrong_type(func_name, "integer", argnum, argc, argv);
+  if (value < lower_bound || value > upper_bound)
+    scheme_wrong_type(func_name, "integer", argnum, argc, argv);
+  return value;
+}
+
+static int
+SWIG_is_integer(Scheme_Object *o)
+{
+  long value;
+  return scheme_get_int_val(o, &value);
+}
+
+static unsigned long
+SWIG_convert_unsigned_integer(Scheme_Object *o,
+			      unsigned long lower_bound, unsigned long upper_bound, 
+			      const char *func_name, int argnum, int argc,
+			      Scheme_Object **argv)
+{
+  unsigned long value;
+  int status = scheme_get_unsigned_int_val(o, &value);
+  if (!status)
+    scheme_wrong_type(func_name, "integer", argnum, argc, argv);
+  if (value < lower_bound || value > upper_bound)
+    scheme_wrong_type(func_name, "integer", argnum, argc, argv);
+  return value;
+}
+
+static int
+SWIG_is_unsigned_integer(Scheme_Object *o)
+{
+  unsigned long value;
+  return scheme_get_unsigned_int_val(o, &value);
+}
+  
+/* ----------------------------------------------------------------------- 
+ * mzscheme 30X support code
+ * Contributed by Hans Oesterholt
+ * ----------------------------------------------------------------------- */
+
+#ifndef SCHEME_STR_VAL
+#define MZSCHEME30X 1
+#endif
+
+#ifdef MZSCHEME30X 
+/* 
+ * This is MZSCHEME 299.100 or higher (30x).  From version 299.100 of
+ * mzscheme upwards, strings are in unicode. These functions convert
+ * to and from utf8 encodings of these strings.  NB! strlen(s) will be
+ * the size in bytes of the string, not the actual length.
+ */
+#define SCHEME_STR_VAL(obj)  	       SCHEME_BYTE_STR_VAL(scheme_char_string_to_byte_string(obj))
+#define SCHEME_STRLEN_VAL(obj)         SCHEME_BYTE_STRLEN_VAL(scheme_char_string_to_byte_string(obj))
+#define SCHEME_STRINGP(obj)            SCHEME_CHAR_STRINGP(obj)
+#define scheme_make_string(s)          scheme_make_utf8_string(s)
+#define scheme_make_sized_string(s,l)  scheme_make_sized_utf8_string(s,l)
+#define scheme_make_sized_offset_string(s,d,l) \
+                   scheme_make_sized_offset_utf8_string(s,d,l)
+#define SCHEME_MAKE_STRING(s) scheme_make_utf8_string(s)
+#else
+#define SCHEME_MAKE_STRING(s) scheme_make_string_without_copying(s)
+#endif
+/* ----------------------------------------------------------------------- 
+ * End of mzscheme 30X support code 
+ * ----------------------------------------------------------------------- */
+  
+struct swig_mz_proxy {
+  Scheme_Type mztype;
+  swig_type_info *type;
+  void *object;
+};
+
+static Scheme_Type swig_type;
+
+static void 
+mz_free_swig(void *p, void *data) {
+  struct swig_mz_proxy *proxy = (struct swig_mz_proxy *) p;
+  if (SCHEME_NULLP((Scheme_Object*)p) || SCHEME_TYPE((Scheme_Object*)p) != swig_type)
+    return;
+  if (proxy->type) {
+    if (proxy->type->clientdata) {
+      ((Scheme_Prim *)proxy->type->clientdata)(1, (Scheme_Object **)&proxy);
+    }
+  }
+}
+
+static Scheme_Object *
+SWIG_MzScheme_NewPointerObj(void *ptr, swig_type_info *type, int owner) {
+  struct swig_mz_proxy *new_proxy;
+  new_proxy = (struct swig_mz_proxy *) scheme_malloc(sizeof(struct swig_mz_proxy));
+  new_proxy->mztype = swig_type;
+  new_proxy->type = type;
+  new_proxy->object = ptr;
+  if (owner) {
+    scheme_add_finalizer(new_proxy, mz_free_swig, NULL);
+  }
+  return (Scheme_Object *) new_proxy;
+}
+
+static int
+SWIG_MzScheme_ConvertPtr(Scheme_Object *s, void **result, swig_type_info *type, int flags) {
+  swig_cast_info *cast;
+
+  if (SCHEME_NULLP(s)) {
+    *result = NULL;
+    return 0;
+  } else if (SCHEME_TYPE(s) == swig_type) {
+    struct swig_mz_proxy *proxy = (struct swig_mz_proxy *) s;
+    if (type) {
+      cast = SWIG_TypeCheckStruct(proxy->type, type);
+      if (cast) {
+        int newmemory = 0;
+        *result = SWIG_TypeCast(cast, proxy->object, &newmemory);
+        assert(!newmemory); /* newmemory handling not yet implemented */
+        return 0;
+      } else {
+        return 1;
+      }
+    } else {
+      *result = proxy->object;
+      return 0;
+    }
+  }
+  return 1;
+}
+
+static SWIGINLINE void *
+SWIG_MzScheme_MustGetPtr(Scheme_Object *s, swig_type_info *type, 
+                         int argnum, int flags, const char *func_name,
+                         int argc, Scheme_Object **argv) {
+  void *result;
+  if (SWIG_MzScheme_ConvertPtr(s, &result, type, flags)) {
+    scheme_wrong_type(func_name, type->str ? type->str : "void *", argnum - 1, argc, argv);
+  }
+  return result;
+}
+
+static SWIGINLINE void *
+SWIG_MzScheme_Malloc(size_t size, const char *func_name) {
+  void *p = malloc(size);
+  if (p == NULL) {
+    scheme_signal_error("swig-memory-error");
+  } else return p;
+}
+
+static Scheme_Object *
+SWIG_MzScheme_PackageValues(int num, Scheme_Object **values) {
+    /* ignore first value if void */
+    if (num > 0 && SCHEME_VOIDP(values[0]))
+	num--, values++;
+    if (num == 0) return scheme_void;
+    else if (num == 1) return values[0];
+    else return scheme_values(num, values);
+}
+
+#ifndef scheme_make_inspector
+#define scheme_make_inspector(x,y) \
+        _scheme_apply(scheme_builtin_value("make-inspector"), x, y)
+#endif
+
+/* Function to create a new struct. */
+static Scheme_Object *
+SWIG_MzScheme_new_scheme_struct (Scheme_Env* env, const char* basename, 
+				 int num_fields, char** field_names)
+{
+    Scheme_Object *new_type;
+    int count_out, i;
+    Scheme_Object **struct_names;
+    Scheme_Object **vals;
+    Scheme_Object **a = (Scheme_Object**) \
+        scheme_malloc(num_fields*sizeof(Scheme_Object*));
+    
+    for (i=0; i<num_fields; ++i) {
+        a[i] = (Scheme_Object*) scheme_intern_symbol(field_names[i]);
+    }
+
+    new_type = scheme_make_struct_type(scheme_intern_symbol(basename),
+                                       NULL /*super_type*/,
+                                       scheme_make_inspector(0, NULL),
+                                       num_fields,
+                                       0 /* auto_fields */,
+                                       NULL /* auto_val */,
+                                       NULL /* properties */
+#ifdef MZSCHEME30X
+				       ,NULL /* Guard */
+#endif
+				       );
+    struct_names = scheme_make_struct_names(scheme_intern_symbol(basename),
+                                            scheme_build_list(num_fields,a),
+                                            0 /*flags*/, &count_out);
+    vals = scheme_make_struct_values(new_type, struct_names, count_out, 0);
+
+    for (i = 0; i < count_out; i++)
+        scheme_add_global_symbol(struct_names[i], vals[i],env);
+
+    return new_type;
+}
+
+/*** DLOPEN PATCH ******************************************************
+ * Contributed by Hans Oesterholt-Dijkema (jan. 2006)
+ ***********************************************************************/
+
+#if defined(_WIN32) || defined(__WIN32__)
+#define __OS_WIN32
+#endif
+
+#ifdef __OS_WIN32
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#endif
+
+  static char **mz_dlopen_libraries=NULL;
+  static void **mz_libraries=NULL;
+  static char **mz_dynload_libpaths=NULL;
+
+  static void mz_set_dlopen_libraries(const char *_libs)
+  {
+    int   i,k,n;
+    int   mz_dynload_debug=(1==0);
+    char *extra_paths[1000];
+    char *EP;
+    
+    {
+      char *dbg=getenv("MZ_DYNLOAD_DEBUG");
+      if (dbg!=NULL) {
+	mz_dynload_debug=atoi(dbg);
+      }
+    }
+
+    {
+      char *ep=getenv("MZ_DYNLOAD_LIBPATH");
+      int   i,k,j;
+      k=0;
+      if (ep!=NULL) {
+	EP=strdup(ep);
+	for(i=0,j=0;EP[i]!='\0';i++) {
+	  if (EP[i]==':') {
+	    EP[i]='\0';
+	    extra_paths[k++]=&EP[j];
+	    j=i+1;
+	  }
+	}
+	if (j!=i) {
+	  extra_paths[k++]=&EP[j];
+	}
+      }
+      else {
+	EP=strdup("");
+      }
+      extra_paths[k]=NULL;
+      k+=1;
+
+      if (mz_dynload_debug) {
+	fprintf(stderr,"SWIG:mzscheme:MZ_DYNLOAD_LIBPATH=%s\n",(ep==NULL) ? "(null)" : ep);
+	fprintf(stderr,"SWIG:mzscheme:extra_paths[%d]\n",k-1);
+	for(i=0;i<k-1;i++) {
+	  fprintf(stderr,"SWIG:mzscheme:extra_paths[%d]=%s\n",i,extra_paths[i]);
+	}
+      }
+
+      mz_dynload_libpaths=(char **) malloc(sizeof(char *)*k);
+      for(i=0;i<k;i++) {
+	if (extra_paths[i]!=NULL) {
+	  mz_dynload_libpaths[i]=strdup(extra_paths[i]);
+	}
+	else {
+	  mz_dynload_libpaths[i]=NULL;
+	}
+      }
+
+      if (mz_dynload_debug) {
+	int i;
+	for(i=0;extra_paths[i]!=NULL;i++) {
+	  fprintf(stderr,"SWIG:mzscheme:%s\n",extra_paths[i]);
+	}
+      }
+    }
+
+    {
+#ifdef MZ_DYNLOAD_LIBS
+      char *libs=(char *) malloc((strlen(MZ_DYNLOAD_LIBS)+1)*sizeof(char));
+      strcpy(libs,MZ_DYNLOAD_LIBS);
+#else
+      char *libs=(char *) malloc((strlen(_libs)+1)*sizeof(char));
+      strcpy(libs,_libs);
+#endif
+      
+      for(i=0,n=strlen(libs),k=0;i<n;i++) {
+	if (libs[i]==',') { k+=1; }
+      }
+      k+=1;
+      mz_dlopen_libraries=(char **) malloc(sizeof(char *)*(k+1));
+      mz_dlopen_libraries[0]=libs;
+      for(i=0,k=1,n=strlen(libs);i<n;i++) {
+	if (libs[i]==',') {
+	  libs[i]='\0';
+	  mz_dlopen_libraries[k++]=&libs[i+1];
+	  i+=1;
+	}
+      }
+      
+      if (mz_dynload_debug) {
+	fprintf(stderr,"k=%d\n",k);
+      }
+      mz_dlopen_libraries[k]=NULL;
+      
+      free(EP);
+    }
+  }
+
+  static void *mz_load_function(char *function)
+  {
+    int mz_dynload_debug=(1==0);
+    
+    {
+      char *dbg=getenv("MZ_DYNLOAD_DEBUG");
+      if (dbg!=NULL) {
+	mz_dynload_debug=atoi(dbg);
+      }
+    }
+
+    if (mz_dlopen_libraries==NULL) {
+      return NULL;
+    }
+    else {
+      if (mz_libraries==NULL) {
+        int i,n;
+        for(n=0;mz_dlopen_libraries[n]!=NULL;n++);
+	if (mz_dynload_debug) {
+	  fprintf(stderr,"SWIG:mzscheme:n=%d\n",n);
+	}
+        mz_libraries=(void **) malloc(sizeof(void*)*n);
+        for(i=0;i<n;i++) { 
+	  if (mz_dynload_debug) {
+	   fprintf(stderr,"SWIG:mzscheme:loading %s\n",mz_dlopen_libraries[i]);
+	  }
+#ifdef __OS_WIN32
+	  mz_libraries[i]=(void *) LoadLibrary(mz_dlopen_libraries[i]); 
+#else
+	  mz_libraries[i]=(void *) dlopen(mz_dlopen_libraries[i],RTLD_LAZY); 
+#endif
+	  if (mz_libraries[i]==NULL) {
+	    int k;
+	    char *libp;
+	    for(k=0;mz_dynload_libpaths[k]!=NULL && mz_libraries[i]==NULL;k++) {
+	      int L=strlen(mz_dynload_libpaths[k])+strlen("\\")+strlen(mz_dlopen_libraries[i])+1;
+	      libp=(char *) malloc(L*sizeof(char));
+#ifdef __OS_WIN32
+	      sprintf(libp,"%s\\%s",mz_dynload_libpaths[k],mz_dlopen_libraries[i]);
+	      mz_libraries[i]=(void *) LoadLibrary(libp); 
+#else
+	      sprintf(libp,"%s/%s",mz_dynload_libpaths[k],mz_dlopen_libraries[i]);
+	      mz_libraries[i]=(void *) dlopen(libp,RTLD_LAZY); 
+#endif
+	      if (mz_dynload_debug) {
+		fprintf(stderr,"SWIG:mzscheme:trying %s --> %p\n",libp,mz_libraries[i]);
+	      }
+	      free(libp);
+	    }
+	  }
+        }
+      }
+      {
+        int i;
+        void *func=NULL;
+
+        for(i=0;mz_dlopen_libraries[i]!=NULL && func==NULL;i++) {
+          if (mz_libraries[i]!=NULL) {
+#ifdef __OS_WIN32
+            func=GetProcAddress(mz_libraries[i],function);
+#else
+            func=dlsym(mz_libraries[i],function);
+#endif
+          }
+	  if (mz_dynload_debug) {
+	    fprintf(stderr,
+		    "SWIG:mzscheme:library:%s;dlopen=%p,function=%s,func=%p\n",
+		    mz_dlopen_libraries[i],mz_libraries[i],function,func
+		    );
+	  }
+        }
+
+        return func;
+      }
+    }
+  }
+
+/*** DLOPEN PATCH ******************************************************
+ * Contributed by Hans Oesterholt-Dijkema (jan. 2006)
+ ***********************************************************************/
+
+/* The interpreter will store a pointer to this structure in a global
+   variable called swig-runtime-data-type-pointer.  The instance of this
+   struct is only used if no other module has yet been loaded */
+struct swig_mzscheme_runtime_data {
+  swig_module_info *module_head;
+  Scheme_Type type;
+};
+static struct swig_mzscheme_runtime_data swig_mzscheme_runtime_data;
+
+
+static swig_module_info *
+SWIG_MzScheme_GetModule(Scheme_Env *env) {
+  Scheme_Object *pointer, *symbol;
+  struct swig_mzscheme_runtime_data *data;
+
+  /* first check if pointer already created */
+  symbol = scheme_intern_symbol("swig-runtime-data-type-pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  pointer = scheme_lookup_global(symbol, env);
+  if (pointer && SCHEME_CPTRP(pointer)) {
+      data = (struct swig_mzscheme_runtime_data *) SCHEME_CPTR_VAL(pointer);
+      swig_type = data->type;
+      return data->module_head;
+  } else {
+      return NULL;
+  }
+}
+
+static void
+SWIG_MzScheme_SetModule(Scheme_Env *env, swig_module_info *module) {
+  Scheme_Object *pointer, *symbol;
+  struct swig_mzscheme_runtime_data *data;
+
+  /* first check if pointer already created */
+  symbol = scheme_intern_symbol("swig-runtime-data-type-pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  pointer = scheme_lookup_global(symbol, env);
+  if (pointer && SCHEME_CPTRP(pointer)) {
+    data = (struct swig_mzscheme_runtime_data *) SCHEME_CPTR_VAL(pointer);
+    swig_type = data->type;
+    data->module_head = module;
+  } else {
+    /* create a new type for wrapped pointer values */
+    swig_type = scheme_make_type((char *)"swig");
+    swig_mzscheme_runtime_data.module_head = module;
+    swig_mzscheme_runtime_data.type = swig_type;
+    
+    /* create a new pointer */
+#ifndef MZSCHEME30X
+    pointer = scheme_make_cptr((void *) &swig_mzscheme_runtime_data, "swig_mzscheme_runtime_data");
+#else
+    pointer = scheme_make_cptr((void *) &swig_mzscheme_runtime_data,
+			       scheme_make_byte_string("swig_mzscheme_runtime_data"));
+#endif
+    scheme_add_global_symbol(symbol, pointer, env);
+  }
+}
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/trunk/Lib/mzscheme/mzscheme.swg b/trunk/Lib/mzscheme/mzscheme.swg
new file mode 100644
index 0000000..ed4b2ec
--- /dev/null
+++ b/trunk/Lib/mzscheme/mzscheme.swg
@@ -0,0 +1,58 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * mzscheme.swg
+ *
+ * SWIG Configuration File for MzScheme.
+ * This file is parsed by SWIG before reading any other interface file.
+ * ----------------------------------------------------------------------------- */
+
+/* Include headers */
+%runtime "swigrun.swg"     // Common C API type-checking code
+%runtime "mzrun.swg"
+
+%define SWIG_APPEND_VALUE(value)
+   values[lenv++] = value
+%enddef
+
+/* Definitions */
+#define SWIG_malloc(size) swig_malloc(size, FUNC_NAME)
+#define SWIG_free(mem) free(mem)
+
+#define SWIG_convert_short(o)					\
+  SWIG_convert_integer(o, - (1 << (8 * sizeof(short) - 1)),	\
+		       (1 << (8 * sizeof(short) - 1)) - 1,	\
+		       FUNC_NAME, $argnum-1, argc, argv)
+#define SWIG_convert_int(o)					\
+  SWIG_convert_integer(o, INT_MIN, INT_MAX,			\
+		       FUNC_NAME, $argnum-1, argc, argv)
+#define SWIG_convert_long(o)					\
+  SWIG_convert_integer(o, LONG_MIN, LONG_MAX,			\
+		       FUNC_NAME, $argnum-1, argc, argv)
+#define SWIG_convert_unsigned_short(o)				\
+  SWIG_convert_unsigned_integer(o, 0,				\
+		       (1 << (8 * sizeof(short))) - 1,		\
+		       FUNC_NAME, $argnum-1, argc, argv)
+#define SWIG_convert_unsigned_int(o)				\
+  SWIG_convert_unsigned_integer(o, 0, UINT_MAX,			\
+		       FUNC_NAME, $argnum-1, argc, argv)
+#define SWIG_convert_unsigned_long(o)				\
+  SWIG_convert_unsigned_integer(o, 0, ULONG_MAX,		\
+		       FUNC_NAME, $argnum-1, argc, argv)
+
+/* Guile compatibility kludges */
+#define SCM_VALIDATE_VECTOR(argnum, value) (void)0
+#define SCM_VALIDATE_LIST(argnum, value) (void)0
+
+/* Read in standard typemaps. */
+%include <typemaps.i>
+
+%insert(init) "swiginit.swg"
+
+%init %{
+Scheme_Object *scheme_reload(Scheme_Env *env) {
+  Scheme_Env *menv = SWIG_MZSCHEME_CREATE_MENV(env);
+
+  SWIG_InitializeModule((void *) env);
+%}
diff --git a/trunk/Lib/mzscheme/std_common.i b/trunk/Lib/mzscheme/std_common.i
new file mode 100644
index 0000000..8732f81
--- /dev/null
+++ b/trunk/Lib/mzscheme/std_common.i
@@ -0,0 +1,23 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_common.i
+ *
+ * SWIG typemaps for STL - common utilities
+ * ----------------------------------------------------------------------------- */
+
+%include <std/std_except.i>
+
+%apply size_t { std::size_t };
+
+%{
+#include <string>
+
+std::string swig_scm_to_string(Scheme_Object* x) {
+    return std::string(SCHEME_STR_VAL(x));
+}
+Scheme_Object* swig_make_string(const std::string& s) {
+    return scheme_make_string(s.c_str());
+}
+%}
diff --git a/trunk/Lib/mzscheme/std_deque.i b/trunk/Lib/mzscheme/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/mzscheme/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/mzscheme/std_map.i b/trunk/Lib/mzscheme/std_map.i
new file mode 100644
index 0000000..aff720d
--- /dev/null
+++ b/trunk/Lib/mzscheme/std_map.i
@@ -0,0 +1,1351 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+//
+// The aim of all that follows would be to integrate std::map with
+// MzScheme as much as possible, namely, to allow the user to pass and
+// be returned Scheme association lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+//
+//   -- f(std::map<T>), f(const std::map<T>&), f(const std::map<T>*):
+//      the parameter being read-only, either a Scheme alist or a
+//      previously wrapped std::map<T> can be passed.
+//   -- f(std::map<T>&), f(std::map<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::map
+//      can be passed.
+//   -- std::map<T> f():
+//      the map is returned by copy; therefore, a Scheme alist
+//      is returned which is most easily used in other Scheme functions
+//   -- std::map<T>& f(), std::map<T>* f(), const std::map<T>& f(),
+//      const std::map<T>* f():
+//      the map is returned by reference; therefore, a wrapped std::map
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                $1 = std::map<K,T >();
+            } else if (SCHEME_PAIRP($input)) {
+                $1 = std::map<K,T >();
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    K* k;
+                    T* x;
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) == -1) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    (($1_type &)$1)[*k] = *x;
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (SCHEME_PAIRP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    K* k;
+                    T* x;
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) == -1) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    temp[*k] = *x;
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            Scheme_Object* alist = scheme_null;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                K* key = new K(i->first);
+                T* val = new T(i->second);
+                Scheme_Object* k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                Scheme_Object* x = SWIG_NewPointerObj(val,$descriptor(T *), 1);
+                Scheme_Object* entry = scheme_make_pair(k,x);
+                alist = scheme_make_pair(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            /* native sequence? */
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                /* check the first element only */
+                K* k;
+                T* x;
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (SWIG_ConvertPtr(key,(void**) &k,
+                                    $descriptor(K *), 0) == -1) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) != -1) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped map? */
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            /* native sequence? */
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                /* check the first element only */
+                K* k;
+                T* x;
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (SWIG_ConvertPtr(key,(void**) &k,
+                                    $descriptor(K *), 0) == -1) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) != -1) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped map? */
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& __getitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            Scheme_Object* keys() {
+                Scheme_Object* result = scheme_null;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    K* key = new K(i->first);
+                    Scheme_Object* k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                    result = scheme_make_pair(k,result);
+                }
+                return result;
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                $1 = std::map<K,T >();
+            } else if (SCHEME_PAIRP($input)) {
+                $1 = std::map<K,T >();
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    T* x;
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    if (!CHECK(key))
+                        SWIG_exception(SWIG_TypeError,
+                                       "map<" #K "," #T "> expected");
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) == -1) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    (($1_type &)$1)[CONVERT_FROM(key)] = *x;
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (SCHEME_PAIRP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    T* x;
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    if (!CHECK(key))
+                        SWIG_exception(SWIG_TypeError,
+                                       "map<" #K "," #T "> expected");
+                    if (SWIG_ConvertPtr(val,(void**) &x,
+                                    $descriptor(T *), 0) == -1) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        x = (T*) SWIG_MustGetPtr(val,$descriptor(T *),$argnum, 0);
+                    }
+                    temp[CONVERT_FROM(key)] = *x;
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            Scheme_Object* alist = scheme_null;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                T* val = new T(i->second);
+                Scheme_Object* k = CONVERT_TO(i->first);
+                Scheme_Object* x = SWIG_NewPointerObj(val,$descriptor(T *), 1);
+                Scheme_Object* entry = scheme_make_pair(k,x);
+                alist = scheme_make_pair(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            // native sequence?
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                // check the first element only
+                T* x;
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (!CHECK(key)) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) != -1) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            // native sequence?
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                // check the first element only
+                T* x;
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (!CHECK(key)) {
+                        $1 = 0;
+                    } else {
+                        if (SWIG_ConvertPtr(val,(void**) &x,
+                                        $descriptor(T *), 0) != -1) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (SWIG_ConvertPtr(val,(void**) &x,
+                                            $descriptor(T *), 0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& __getitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            Scheme_Object* keys() {
+                Scheme_Object* result = scheme_null;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    Scheme_Object* k = CONVERT_TO(i->first);
+                    result = scheme_make_pair(k,result);
+                }
+                return result;
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                $1 = std::map<K,T >();
+            } else if (SCHEME_PAIRP($input)) {
+                $1 = std::map<K,T >();
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    K* k;
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (!CHECK(val)) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        if (!CHECK(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    (($1_type &)$1)[*k] = CONVERT_FROM(val);
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (SCHEME_PAIRP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    K* k;
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    k = (K*) SWIG_MustGetPtr(key,$descriptor(K *),$argnum, 0);
+                    if (!CHECK(val)) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        if (!CHECK(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    temp[*k] = CONVERT_FROM(val);
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            Scheme_Object* alist = scheme_null;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                K* key = new K(i->first);
+                Scheme_Object* k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                Scheme_Object* x = CONVERT_TO(i->second);
+                Scheme_Object* entry = scheme_make_pair(k,x);
+                alist = scheme_make_pair(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            // native sequence?
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                // check the first element only
+                K* k;
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (SWIG_ConvertPtr(val,(void **) &k,
+                                    $descriptor(K *), 0) == -1) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK(val)) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (CHECK(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            // native sequence?
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                // check the first element only
+                K* k;
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (SWIG_ConvertPtr(val,(void **) &k,
+                                    $descriptor(K *), 0) == -1) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK(val)) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (CHECK(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T __getitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            Scheme_Object* keys() {
+                Scheme_Object* result = scheme_null;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    K* key = new K(i->first);
+                    Scheme_Object* k = SWIG_NewPointerObj(key,$descriptor(K *), 1);
+                    result = scheme_make_pair(k,result);
+                }
+                return result;
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        %typemap(in) map<K,T> (std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                $1 = std::map<K,T >();
+            } else if (SCHEME_PAIRP($input)) {
+                $1 = std::map<K,T >();
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    if (!CHECK_K(key))
+                        SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    if (!CHECK_T(val)) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        if (!CHECK_T(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    (($1_type &)$1)[CONVERT_K_FROM(key)] = 
+                                               CONVERT_T_FROM(val);
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const map<K,T>& (std::map<K,T> temp,
+                                      std::map<K,T>* m),
+                     const map<K,T>* (std::map<K,T> temp,
+                                      std::map<K,T>* m) {
+            if (SCHEME_NULLP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+            } else if (SCHEME_PAIRP($input)) {
+                temp = std::map<K,T >();
+                $1 = &temp;
+                Scheme_Object* alist = $input;
+                while (!SCHEME_NULLP(alist)) {
+                    Scheme_Object *entry, *key, *val;
+                    entry = scheme_car(alist);
+                    if (!SCHEME_PAIRP(entry))
+                        SWIG_exception(SWIG_TypeError,"alist expected");
+                    key = scheme_car(entry);
+                    val = scheme_cdr(entry);
+                    if (!CHECK_K(key))
+                        SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    if (!CHECK_T(val)) {
+                        if (!SCHEME_PAIRP(val))
+                            SWIG_exception(SWIG_TypeError,"alist expected");
+                        val = scheme_car(val);
+                        if (!CHECK_T(val))
+                            SWIG_exception(SWIG_TypeError,
+                                           "map<" #K "," #T "> expected");
+                    }
+                    temp[CONVERT_K_FROM(key)] = CONVERT_T_FROM(val);
+                    alist = scheme_cdr(alist);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) map<K,T> {
+            Scheme_Object* alist = scheme_null;
+            for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                  i!=$1.rend(); ++i) {
+                Scheme_Object* k = CONVERT_K_TO(i->first);
+                Scheme_Object* x = CONVERT_T_TO(i->second);
+                Scheme_Object* entry = scheme_make_pair(k,x);
+                alist = scheme_make_pair(entry,alist);
+            }
+            $result = alist;
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) map<K,T> {
+            // native sequence?
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                // check the first element only
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (!CHECK_K(key)) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK_T(val)) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (CHECK_T(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_MAP) const map<K,T>&,
+                                       const map<K,T>* {
+            // native sequence?
+            if (SCHEME_NULLP($input)) {
+                /* an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                // check the first element only
+                Scheme_Object* head = scheme_car($input);
+                if (SCHEME_PAIRP(head)) {
+                    Scheme_Object* key = scheme_car(head);
+                    Scheme_Object* val = scheme_cdr(head);
+                    if (!CHECK_K(key)) {
+                        $1 = 0;
+                    } else {
+                        if (CHECK_T(val)) {
+                            $1 = 1;
+                        } else if (SCHEME_PAIRP(val)) {
+                            val = scheme_car(val);
+                            if (CHECK_T(val))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        } else {
+                            $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                // wrapped map?
+                std::map<K,T >* m;
+                if (SWIG_ConvertPtr($input,(void **) &m,
+                                $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %rename("length") size;
+        %rename("null?") empty;
+        %rename("clear!") clear;
+        %rename("ref") __getitem__;
+        %rename("set!") __setitem__;
+        %rename("delete!") __delitem__;
+        %rename("has-key?") has_key;
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T __getitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void __setitem__(K key, T x) {
+                (*self)[key] = x;
+            }
+            void __delitem__(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+            Scheme_Object* keys() {
+                Scheme_Object* result = scheme_null;
+                for (std::map<K,T >::reverse_iterator i=$1.rbegin(); 
+                                                      i!=$1.rend(); ++i) {
+                    Scheme_Object* k = CONVERT_K_TO(i->first);
+                    result = scheme_make_pair(k,result);
+                }
+                return result;
+            }
+        }
+    };
+    %enddef
+
+
+    specialize_std_map_on_key(bool,SCHEME_BOOLP,
+                              SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_key(int,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_key(short,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_key(long,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_key(unsigned int,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_key(unsigned short,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_key(unsigned long,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_key(double,SCHEME_REALP,
+                              scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_key(float,SCHEME_REALP,
+                              scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_key(std::string,SCHEME_STRINGP,
+                              swig_scm_to_string,swig_make_string);
+
+    specialize_std_map_on_value(bool,SCHEME_BOOLP,
+                                SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_value(int,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_value(short,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_value(long,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_value(unsigned int,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_value(unsigned short,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_value(unsigned long,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_value(double,SCHEME_REALP,
+                                scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_value(float,SCHEME_REALP,
+                                scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_value(std::string,SCHEME_STRINGP,
+                                swig_scm_to_string,swig_make_string);
+
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_map_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+}
diff --git a/trunk/Lib/mzscheme/std_pair.i b/trunk/Lib/mzscheme/std_pair.i
new file mode 100644
index 0000000..2ac331e
--- /dev/null
+++ b/trunk/Lib/mzscheme/std_pair.i
@@ -0,0 +1,873 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+
+// ------------------------------------------------------------------------
+// std::pair
+//
+// See std_vector.i for the rationale of typemap application
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class T, class U> struct pair {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                U* y;
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                $1 = std::make_pair(*x,*y);
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                       std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                       std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                U* y;
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                temp = std::make_pair(*x,*y);
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            T* x = new T($1.first);
+            U* y = new U($1.second);
+            Scheme_Object* first = SWIG_NewPointerObj(x,$descriptor(T *), 1);
+            Scheme_Object* second = SWIG_NewPointerObj(y,$descriptor(U *), 1);
+            $result = scheme_make_pair(first,second);
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                U* y;
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) != -1 &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) != -1) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                U* y;
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) != -1 &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) != -1) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+
+    // specializations for built-ins
+
+    %define specialize_std_pair_on_first(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class U> struct pair<T,U> {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                U* y;
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                if (!CHECK(first))
+                    SWIG_exception(SWIG_TypeError,
+                                   "pair<" #T "," #U "> expected");
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                $1 = std::make_pair(CONVERT_FROM(first),*y);
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                       std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                       std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                U* y;
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                if (!CHECK(first))
+                    SWIG_exception(SWIG_TypeError,
+                                   "pair<" #T "," #U "> expected");
+                y = (U*) SWIG_MustGetPtr(second,$descriptor(U *),$argnum, 0);
+                temp = std::make_pair(CONVERT_FROM(first),*y);
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            U* y = new U($1.second);
+            Scheme_Object* second = SWIG_NewPointerObj(y,$descriptor(U *), 1);
+            $result = scheme_make_pair(CONVERT_TO($1.first),second);
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                U* y;
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (CHECK(first) &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) != -1) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                U* y;
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (CHECK(first) &&
+                    SWIG_ConvertPtr(second,(void**) &y,
+                                    $descriptor(U *), 0) != -1) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+    %enddef
+
+    %define specialize_std_pair_on_second(U,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class T> struct pair<T,U> {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                if (!CHECK(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "pair<" #T "," #U "> expected");
+                $1 = std::make_pair(*x,CONVERT_FROM(second));
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                       std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                       std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                if (!CHECK(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "pair<" #T "," #U "> expected");
+                temp = std::make_pair(*x,CONVERT_FROM(second));
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            T* x = new T($1.first);
+            Scheme_Object* first = SWIG_NewPointerObj(x,$descriptor(T *), 1);
+            $result = scheme_make_pair(first,CONVERT_TO($1.second));
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) != -1 &&
+                    CHECK(second)) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                T* x;
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (SWIG_ConvertPtr(first,(void**) &x,
+                                    $descriptor(T *), 0) != -1 &&
+                    CHECK(second)) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+    %enddef
+
+    %define specialize_std_pair_on_both(T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO,
+                                        U,CHECK_U,CONVERT_U_FROM,CONVERT_U_TO)
+    template<> struct pair<T,U> {
+        %typemap(in) pair<T,U> (std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                Scheme_Object *first, *second;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                if (!CHECK_T(first) || !CHECK_U(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "pair<" #T "," #U "> expected");
+                $1 = make_pair(CONVERT_T_FROM(first),
+                               CONVERT_U_FROM(second));
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const pair<T,U>& (std::pair<T,U> temp,
+                                       std::pair<T,U>* m),
+                     const pair<T,U>* (std::pair<T,U> temp,
+                                       std::pair<T,U>* m) {
+            if (SCHEME_PAIRP($input)) {
+                Scheme_Object *first, *second;
+            T *x;
+                first = scheme_car($input);
+                second = scheme_cdr($input);
+                x = (T*) SWIG_MustGetPtr(first,$descriptor(T *),$argnum, 0);
+                if (!CHECK_T(first) || !CHECK_U(second))
+                    SWIG_exception(SWIG_TypeError,
+                                   "pair<" #T "," #U "> expected");
+                temp = make_pair(CONVERT_T_FROM(first),
+                               CONVERT_U_FROM(second));
+                $1 = &temp;
+            } else {
+                $1 = ($1_ltype)
+                    SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) pair<T,U> {
+            $result = scheme_make_pair(CONVERT_T_TO($1.first),
+                                       CONVERT_U_TO($1.second));
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) pair<T,U> {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (CHECK_T(first) && CHECK_U(second)) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_PAIR) const pair<T,U>&,
+                                        const pair<T,U>* {
+            /* native pair? */
+            if (SCHEME_PAIRP($input)) {
+                Scheme_Object* first = scheme_car($input);
+                Scheme_Object* second = scheme_cdr($input);
+                if (CHECK_T(first) && CHECK_U(second)) {
+                        $1 = 1;
+                } else {
+                    $1 = 0;
+                }
+            } else {
+                /* wrapped pair? */
+                std::pair<T,U >* p;
+                if (SWIG_ConvertPtr($input,(void **) &p,
+                                    $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        pair();
+        pair(T first, U second);
+        pair(const pair& p);
+
+        template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+        T first;
+        U second;
+    };
+    %enddef
+
+
+    specialize_std_pair_on_first(bool,SCHEME_BOOLP,
+                              SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_first(int,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_first(short,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_first(long,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_first(unsigned int,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_first(unsigned short,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_first(unsigned long,SCHEME_INTP,
+                              SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_first(double,SCHEME_REALP,
+                              scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_first(float,SCHEME_REALP,
+                              scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_first(std::string,SCHEME_STRINGP,
+                              swig_scm_to_string,swig_make_string);
+
+    specialize_std_pair_on_second(bool,SCHEME_BOOLP,
+                                SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_second(int,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_second(short,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_second(long,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_second(unsigned int,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_second(unsigned short,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_second(unsigned long,SCHEME_INTP,
+                                SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_second(double,SCHEME_REALP,
+                                scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_second(float,SCHEME_REALP,
+                                scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_second(std::string,SCHEME_STRINGP,
+                                swig_scm_to_string,swig_make_string);
+
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               bool,SCHEME_BOOLP,
+                               SCHEME_TRUEP,swig_make_boolean);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               unsigned int,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               unsigned short,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               unsigned long,SCHEME_INTP,
+                               SCHEME_INT_VAL,scheme_make_integer_value);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               double,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               float,SCHEME_REALP,
+                               scheme_real_to_double,scheme_make_double);
+    specialize_std_pair_on_both(std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string,
+                               std::string,SCHEME_STRINGP,
+                               swig_scm_to_string,swig_make_string);
+}
diff --git a/trunk/Lib/mzscheme/std_string.i b/trunk/Lib/mzscheme/std_string.i
new file mode 100644
index 0000000..c9a82ef
--- /dev/null
+++ b/trunk/Lib/mzscheme/std_string.i
@@ -0,0 +1,60 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string types
+ * ----------------------------------------------------------------------------- */
+
+// ------------------------------------------------------------------------
+// std::string is typemapped by value
+// This can prevent exporting methods which return a string
+// in order for the user to modify it.
+// However, I think I'll wait until someone asks for it...
+// ------------------------------------------------------------------------
+
+%include <exception.i>
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+    %naturalvar string;
+
+    class string;
+
+    /* Overloading check */
+
+    %typemap(typecheck) string = char *;
+    %typemap(typecheck) const string & = char *;
+
+    %typemap(in) string {
+        if (SCHEME_STRINGP($input))
+            $1.assign(SCHEME_STR_VAL($input));
+        else
+            SWIG_exception(SWIG_TypeError, "string expected");
+    }
+
+    %typemap(in) const string & (std::string temp) {
+        if (SCHEME_STRINGP($input)) {
+            temp.assign(SCHEME_STR_VAL($input));
+            $1 = &temp;
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(out) string {
+        $result = scheme_make_string($1.c_str());
+    }
+
+    %typemap(out) const string & {
+        $result = scheme_make_string($1->c_str());
+    }
+
+}
+
+
diff --git a/trunk/Lib/mzscheme/std_vector.i b/trunk/Lib/mzscheme/std_vector.i
new file mode 100644
index 0000000..90a52fc
--- /dev/null
+++ b/trunk/Lib/mzscheme/std_vector.i
@@ -0,0 +1,436 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * SWIG typemaps for std::vector
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// MzScheme as much as possible, namely, to allow the user to pass and 
+// be returned MzScheme vectors or lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&), f(const std::vector<T>*):
+//      the parameter being read-only, either a MzScheme sequence or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f():
+//      the vector is returned by copy; therefore, a MzScheme vector of T:s 
+//      is returned which is most easily used in other MzScheme functions
+//   -- std::vector<T>& f(), std::vector<T>* f(), const std::vector<T>& f(),
+//      const std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    
+    template<class T> class vector {
+        %typemap(in) vector<T> {
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                $1 = std::vector<T >(size);
+                Scheme_Object** items = SCHEME_VEC_ELS($input);
+                for (unsigned int i=0; i<size; i++) {
+                    (($1_type &)$1)[i] =
+                        *((T*) SWIG_MustGetPtr(items[i],
+                                               $descriptor(T *),
+                                               $argnum, 0));
+                }
+            } else if (SCHEME_NULLP($input)) {
+                $1 = std::vector<T >();
+            } else if (SCHEME_PAIRP($input)) {
+                Scheme_Object *head, *tail;
+                $1 = std::vector<T >();
+                tail = $input;
+                while (!SCHEME_NULLP(tail)) {
+                    head = scheme_car(tail);
+                    tail = scheme_cdr(tail);
+                    $1.push_back(*((T*)SWIG_MustGetPtr(head,
+                                                       $descriptor(T *),
+                                                       $argnum, 0)));
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const vector<T>& (std::vector<T> temp),
+                     const vector<T>* (std::vector<T> temp) {
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                temp = std::vector<T >(size);
+                $1 = &temp;
+                Scheme_Object** items = SCHEME_VEC_ELS($input);
+                for (unsigned int i=0; i<size; i++) {
+                    temp[i] = *((T*) SWIG_MustGetPtr(items[i],
+                                                     $descriptor(T *),
+                                                     $argnum, 0));
+                }
+            } else if (SCHEME_NULLP($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+            } else if (SCHEME_PAIRP($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+                Scheme_Object *head, *tail;
+                tail = $input;
+                while (!SCHEME_NULLP(tail)) {
+                    head = scheme_car(tail);
+                    tail = scheme_cdr(tail);
+                    temp.push_back(*((T*) SWIG_MustGetPtr(head,
+                                                          $descriptor(T *),
+                                                          $argnum, 0)));
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum, 0);
+            }
+        }
+        %typemap(out) vector<T> {
+            $result = scheme_make_vector($1.size(),scheme_undefined);
+            Scheme_Object** els = SCHEME_VEC_ELS($result);
+            for (unsigned int i=0; i<$1.size(); i++) {
+                T* x = new T((($1_type &)$1)[i]);
+                els[i] = SWIG_NewPointerObj(x,$descriptor(T *), 1);
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            /* native sequence? */
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    Scheme_Object** items = SCHEME_VEC_ELS($input);
+                    if (SWIG_ConvertPtr(items[0],(void**) &x,
+                                    $descriptor(T *), 0) != -1)
+                        $1 = 1;
+                    else
+                        $1 = 0;
+                }
+            } else if (SCHEME_NULLP($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                /* check the first element only */
+                T* x;
+                Scheme_Object *head = scheme_car($input);
+                if (SWIG_ConvertPtr(head,(void**) &x,
+                                $descriptor(T *), 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $&1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            /* native sequence? */
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    Scheme_Object** items = SCHEME_VEC_ELS($input);
+                    if (SWIG_ConvertPtr(items[0],(void**) &x,
+                                    $descriptor(T *), 0) != -1)
+                        $1 = 1;
+                    else
+                        $1 = 0;
+                }
+            } else if (SCHEME_NULLP($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                /* check the first element only */
+                T* x;
+                Scheme_Object *head = scheme_car($input);
+                if (SWIG_ConvertPtr(head,(void**) &x,
+                                $descriptor(T *), 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $1_descriptor, 0) != -1)
+                    $1 = 1;
+                else
+                    $1 = 0;
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T>&);
+        %rename(length) size;
+        unsigned int size() const;
+        %rename("empty?") empty;
+        bool empty() const;
+        %rename("clear!") clear;
+        void clear();
+        %rename("set!") set;
+        %rename("pop!") pop;
+        %rename("push!") push_back;
+        void push_back(const T& x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T& ref(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, const T& x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_vector(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<> class vector<T> {
+        %typemap(in) vector<T> {
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                $1 = std::vector<T >(size);
+                Scheme_Object** items = SCHEME_VEC_ELS($input);
+                for (unsigned int i=0; i<size; i++) {
+                    Scheme_Object* o = items[i];
+                    if (CHECK(o))
+                        (($1_type &)$1)[i] = (T)(CONVERT_FROM(o));
+                    else
+                        scheme_wrong_type(FUNC_NAME, "vector<" #T ">", 
+                                          $argnum - 1, argc, argv);
+                }
+            } else if (SCHEME_NULLP($input)) {
+                $1 = std::vector<T >();
+            } else if (SCHEME_PAIRP($input)) {
+                Scheme_Object *head, *tail;
+                $1 = std::vector<T >();
+                tail = $input;
+                while (!SCHEME_NULLP(tail)) {
+                    head = scheme_car(tail);
+                    tail = scheme_cdr(tail);
+                    if (CHECK(head))
+                        $1.push_back((T)(CONVERT_FROM(head)));
+                    else
+                        scheme_wrong_type(FUNC_NAME, "vector<" #T ">", 
+                                          $argnum - 1, argc, argv);
+                }
+            } else {
+                $1 = *(($&1_type)
+                       SWIG_MustGetPtr($input,$&1_descriptor,$argnum, 0));
+            }
+        }
+        %typemap(in) const vector<T>& (std::vector<T> temp),
+                     const vector<T>* (std::vector<T> temp) {
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                temp = std::vector<T >(size);
+                $1 = &temp;
+                Scheme_Object** items = SCHEME_VEC_ELS($input);
+                for (unsigned int i=0; i<size; i++) {
+                    Scheme_Object* o = items[i];
+                    if (CHECK(o))
+                        temp[i] = (T)(CONVERT_FROM(o));
+                    else
+                        scheme_wrong_type(FUNC_NAME, "vector<" #T ">", 
+                                          $argnum - 1, argc, argv);
+                }
+            } else if (SCHEME_NULLP($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+            } else if (SCHEME_PAIRP($input)) {
+                temp = std::vector<T >();
+                $1 = &temp;
+                Scheme_Object *head, *tail;
+                tail = $input;
+                while (!SCHEME_NULLP(tail)) {
+                    head = scheme_car(tail);
+                    tail = scheme_cdr(tail);
+                    if (CHECK(head))
+                        temp.push_back((T)(CONVERT_FROM(head)));
+                    else
+                        scheme_wrong_type(FUNC_NAME, "vector<" #T ">", 
+                                          $argnum - 1, argc, argv);
+                }
+            } else {
+                $1 = ($1_ltype) SWIG_MustGetPtr($input,$1_descriptor,$argnum - 1, 0);
+            }
+        }
+        %typemap(out) vector<T> {
+            $result = scheme_make_vector($1.size(),scheme_undefined);
+            Scheme_Object** els = SCHEME_VEC_ELS($result);
+            for (unsigned int i=0; i<$1.size(); i++)
+                els[i] = CONVERT_TO((($1_type &)$1)[i]);
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            /* native sequence? */
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    Scheme_Object** items = SCHEME_VEC_ELS($input);
+                    $1 = CHECK(items[0]) ? 1 : 0;
+                }
+            } else if (SCHEME_NULLP($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                /* check the first element only */
+                T* x;
+                Scheme_Object *head = scheme_car($input);
+                $1 = CHECK(head) ? 1 : 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                $1 = (SWIG_ConvertPtr($input,(void **) &v, 
+                                  $&1_descriptor, 0) != -1) ? 1 : 0;
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            /* native sequence? */
+            if (SCHEME_VECTORP($input)) {
+                unsigned int size = SCHEME_VEC_SIZE($input);
+                if (size == 0) {
+                    /* an empty sequence can be of any type */
+                    $1 = 1;
+                } else {
+                    /* check the first element only */
+                    T* x;
+                    Scheme_Object** items = SCHEME_VEC_ELS($input);
+                    $1 = CHECK(items[0]) ? 1 : 0;
+                }
+            } else if (SCHEME_NULLP($input)) {
+                /* again, an empty sequence can be of any type */
+                $1 = 1;
+            } else if (SCHEME_PAIRP($input)) {
+                /* check the first element only */
+                T* x;
+                Scheme_Object *head = scheme_car($input);
+                $1 = CHECK(head) ? 1 : 0;
+            } else {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                $1 = (SWIG_ConvertPtr($input,(void **) &v, 
+                                  $1_descriptor, 0) != -1) ? 1 : 0;
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T>&);
+        %rename(length) size;
+        unsigned int size() const;
+        %rename("empty?") empty;
+        bool empty() const;
+        %rename("clear!") clear;
+        void clear();
+        %rename("set!") set;
+        %rename("pop!") pop;
+        %rename("push!") push_back;
+        void push_back(T x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T ref(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, T x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+    %enddef
+
+    specialize_std_vector(bool,SCHEME_BOOLP,SCHEME_TRUEP,\
+                          swig_make_boolean);
+    specialize_std_vector(char,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(int,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(short,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(long,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(unsigned char,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(unsigned int,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(unsigned short,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(unsigned long,SCHEME_INTP,SCHEME_INT_VAL,\
+                          scheme_make_integer_value);
+    specialize_std_vector(float,SCHEME_REALP,scheme_real_to_double,\
+                          scheme_make_double);
+    specialize_std_vector(double,SCHEME_REALP,scheme_real_to_double,\
+                          scheme_make_double);
+    specialize_std_vector(std::string,SCHEME_STRINGP,swig_scm_to_string,\
+                          swig_make_string);
+
+}
+
diff --git a/trunk/Lib/mzscheme/stl.i b/trunk/Lib/mzscheme/stl.i
new file mode 100644
index 0000000..946e4b7
--- /dev/null
+++ b/trunk/Lib/mzscheme/stl.i
@@ -0,0 +1,14 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/mzscheme/typemaps.i b/trunk/Lib/mzscheme/typemaps.i
new file mode 100644
index 0000000..3348932
--- /dev/null
+++ b/trunk/Lib/mzscheme/typemaps.i
@@ -0,0 +1,354 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ * ----------------------------------------------------------------------------- */
+
+/* The MzScheme module handles all types uniformly via typemaps. Here
+   are the definitions.  */
+
+/* Pointers */
+
+%typemap(in) SWIGTYPE * {
+  $1 = ($ltype) SWIG_MustGetPtr($input, $descriptor, $argnum, 0);
+}
+
+%typemap(in) void * {
+  $1 = SWIG_MustGetPtr($input, NULL, $argnum, 0);
+}
+
+%typemap(varin) SWIGTYPE * {
+  $1 = ($ltype) SWIG_MustGetPtr($input, $descriptor, 1, 0);
+}
+
+%typemap(varin) SWIGTYPE & {
+  $1 = *(($1_ltype)SWIG_MustGetPtr($input, $descriptor, 1, 0));
+}
+
+%typemap(varin) SWIGTYPE [ANY] {
+  void *temp;
+  int ii;
+  $1_basetype *b = 0;
+  temp = SWIG_MustGetPtr($input, $1_descriptor, 1, 0);
+  b = ($1_basetype *) $1;
+  for (ii = 0; ii < $1_size; ii++) b[ii] = *(($1_basetype *) temp + ii);
+}
+  
+
+%typemap(varin) void * {
+  $1 = SWIG_MustGetPtr($input, NULL, 1, 0);
+}
+
+%typemap(out) SWIGTYPE * {
+  $result = SWIG_NewPointerObj ($1, $descriptor, $owner);
+}
+
+%typemap(out) SWIGTYPE *DYNAMIC {
+  swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor,(void **) &$1);
+  $result = SWIG_NewPointerObj ($1, ty, $owner);
+}
+    
+%typemap(varout) SWIGTYPE *, SWIGTYPE [] {
+  $result = SWIG_NewPointerObj ($1, $descriptor, 0);
+}
+
+%typemap(varout) SWIGTYPE & {
+  $result = SWIG_NewPointerObj((void *) &$1, $1_descriptor, 0);
+}
+
+/* C++ References */
+
+#ifdef __cplusplus
+
+%typemap(in) SWIGTYPE &, const SWIGTYPE & { 
+  $1 = ($ltype) SWIG_MustGetPtr($input, $descriptor, $argnum, 0);
+  if ($1 == NULL) scheme_signal_error("swig-type-error (null reference)");
+}
+
+%typemap(out) SWIGTYPE &, const SWIGTYPE & {
+  $result = SWIG_NewPointerObj ($1, $descriptor, $owner);
+}
+
+%typemap(out) SWIGTYPE &DYNAMIC {
+  swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor,(void **) &$1);
+  $result = SWIG_NewPointerObj ($1, ty, $owner);
+}
+
+#endif
+
+/* Arrays */
+
+%typemap(in) SWIGTYPE[] {
+  $1 = ($ltype) SWIG_MustGetPtr($input, $descriptor, $argnum, 0);
+}
+
+%typemap(out) SWIGTYPE[] {
+  $result = SWIG_NewPointerObj ($1, $descriptor, $owner);
+}
+
+/* Enums */
+%typemap(in) enum SWIGTYPE {
+  if (!SWIG_is_integer($input)) 
+      scheme_wrong_type(FUNC_NAME, "integer", $argnum - 1, argc, argv);
+  $1 = ($1_type) SWIG_convert_int($input);
+}
+
+%typemap(varin) enum SWIGTYPE {
+  if (!SWIG_is_integer($input)) 
+      scheme_wrong_type(FUNC_NAME, "integer", 0, argc, argv);
+  $1 = ($1_type) SWIG_convert_int($input);
+}
+
+%typemap(out) enum SWIGTYPE "$result = scheme_make_integer_value($1);";
+%typemap(varout) enum SWIGTYPE "$result = scheme_make_integer_value($1);";
+
+
+/* Pass-by-value */
+
+%typemap(in) SWIGTYPE($&1_ltype argp) {
+  argp = ($&1_ltype) SWIG_MustGetPtr($input, $&1_descriptor, $argnum, 0);
+  $1 = *argp;
+}
+
+%typemap(varin) SWIGTYPE {
+  $&1_ltype argp;
+  argp = ($&1_ltype) SWIG_MustGetPtr($input, $&1_descriptor, 1, 0);
+  $1 = *argp;
+}
+
+
+%typemap(out) SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  resultptr = new $1_ltype(($1_ltype &) $1);
+  $result =  SWIG_NewPointerObj (resultptr, $&1_descriptor, 1);
+} 
+#else
+{
+  $&1_ltype resultptr;
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 1);
+}
+#endif
+
+%typemap(varout) SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  resultptr = new $1_ltype(($1_ltype &) $1);
+  $result =  SWIG_NewPointerObj (resultptr, $&1_descriptor, 0);
+} 
+#else
+{
+  $&1_ltype resultptr;
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  $result = SWIG_NewPointerObj(resultptr, $&1_descriptor, 0);
+}
+#endif
+
+/* The SIMPLE_MAP macro below defines the whole set of typemaps needed
+   for simple types. */
+
+%define SIMPLE_MAP(C_NAME, MZ_PREDICATE, MZ_TO_C, C_TO_MZ, MZ_NAME)
+%typemap(in) C_NAME {
+    if (!MZ_PREDICATE($input))
+	scheme_wrong_type(FUNC_NAME, #MZ_NAME, $argnum - 1, argc, argv);
+    $1 = MZ_TO_C($input);
+}
+%typemap(varin) C_NAME {
+    if (!MZ_PREDICATE($input))
+	scheme_wrong_type(FUNC_NAME, #MZ_NAME, 0, argc, argv);
+    $1 = MZ_TO_C($input);
+}
+%typemap(out) C_NAME {
+    $result = C_TO_MZ($1);
+}
+%typemap(varout) C_NAME {
+    $result = C_TO_MZ($1);
+}
+%typemap(in) C_NAME *INPUT (C_NAME temp) {
+    temp = (C_NAME) MZ_TO_C($input);
+    $1 = &temp;
+}
+%typemap(in,numinputs=0) C_NAME *OUTPUT (C_NAME temp) {
+    $1 = &temp;
+}
+%typemap(argout) C_NAME *OUTPUT {
+    Scheme_Object *s;
+    s = C_TO_MZ(*$1);
+    SWIG_APPEND_VALUE(s);
+}
+%typemap(in) C_NAME *BOTH = C_NAME *INPUT;
+%typemap(argout) C_NAME *BOTH = C_NAME *OUTPUT;
+%typemap(in) C_NAME *INOUT = C_NAME *INPUT;
+%typemap(argout) C_NAME *INOUT = C_NAME *OUTPUT;
+%enddef
+
+SIMPLE_MAP(bool, SCHEME_BOOLP, SCHEME_TRUEP,
+	   swig_make_boolean, boolean);
+SIMPLE_MAP(char, SCHEME_CHARP, SCHEME_CHAR_VAL,
+	   scheme_make_character, character);
+SIMPLE_MAP(unsigned char, SCHEME_CHARP, SCHEME_CHAR_VAL,
+	   scheme_make_character, character);
+SIMPLE_MAP(int, SWIG_is_integer, SWIG_convert_int,
+	   scheme_make_integer_value, integer);
+SIMPLE_MAP(short, SWIG_is_integer, SWIG_convert_short,
+	   scheme_make_integer_value, integer);
+SIMPLE_MAP(long, SWIG_is_integer, SWIG_convert_long,
+	   scheme_make_integer_value, integer);
+SIMPLE_MAP(ptrdiff_t, SWIG_is_integer, SWIG_convert_long,
+	   scheme_make_integer_value, integer);
+SIMPLE_MAP(unsigned int, SWIG_is_unsigned_integer, SWIG_convert_unsigned_int,
+	   scheme_make_integer_value_from_unsigned, integer);
+SIMPLE_MAP(unsigned short, SWIG_is_unsigned_integer, SWIG_convert_unsigned_short,
+	   scheme_make_integer_value_from_unsigned, integer);
+SIMPLE_MAP(unsigned long, SWIG_is_unsigned_integer, SWIG_convert_unsigned_long,
+	   scheme_make_integer_value_from_unsigned, integer);
+SIMPLE_MAP(size_t, SWIG_is_unsigned_integer, SWIG_convert_unsigned_long,
+	   scheme_make_integer_value_from_unsigned, integer);
+SIMPLE_MAP(float, SCHEME_REALP, scheme_real_to_double,
+	   scheme_make_double, real);
+SIMPLE_MAP(double, SCHEME_REALP, scheme_real_to_double,
+	   scheme_make_double, real);
+
+SIMPLE_MAP(char *, SCHEME_STRINGP, SCHEME_STR_VAL, 
+	   SCHEME_MAKE_STRING, string);
+SIMPLE_MAP(const char *, SCHEME_STRINGP, SCHEME_STR_VAL, 
+	   SCHEME_MAKE_STRING, string);
+
+/* For MzScheme 30x:  Use these typemaps if you are not going to use
+   UTF8 encodings in your C code. 
+ SIMPLE_MAP(char *,SCHEME_BYTE_STRINGP, SCHEME_BYTE_STR_VAL,
+ 	   scheme_make_byte_string_without_copying,bytestring);
+ SIMPLE_MAP(const char *,SCHEME_BYTE_STRINGP, SCHEME_BYTE_STR_VAL,
+ 	   scheme_make_byte_string_without_copying,bytestring);
+*/
+
+/* Const primitive references.  Passed by value */
+
+%define REF_MAP(C_NAME, MZ_PREDICATE, MZ_TO_C, C_TO_MZ, MZ_NAME)
+  %typemap(in) const C_NAME & (C_NAME temp) {
+     if (!MZ_PREDICATE($input))
+        scheme_wrong_type(FUNC_NAME, #MZ_NAME, $argnum - 1, argc, argv);
+     temp = MZ_TO_C($input);
+     $1 = &temp;
+  }
+  %typemap(out) const C_NAME & {
+    $result = C_TO_MZ(*$1);
+  }
+%enddef
+
+REF_MAP(bool, SCHEME_BOOLP, SCHEME_TRUEP,
+	   swig_make_boolean, boolean);
+REF_MAP(char, SCHEME_CHARP, SCHEME_CHAR_VAL,
+	   scheme_make_character, character);
+REF_MAP(unsigned char, SCHEME_CHARP, SCHEME_CHAR_VAL,
+	   scheme_make_character, character);
+REF_MAP(int, SWIG_is_integer, SWIG_convert_int,
+	   scheme_make_integer_value, integer);
+REF_MAP(short, SWIG_is_integer, SWIG_convert_short,
+	   scheme_make_integer_value, integer);
+REF_MAP(long, SWIG_is_integer, SWIG_convert_long,
+	   scheme_make_integer_value, integer);
+REF_MAP(unsigned int, SWIG_is_unsigned_integer, SWIG_convert_unsigned_int,
+	   scheme_make_integer_value_from_unsigned, integer);
+REF_MAP(unsigned short, SWIG_is_unsigned_integer, SWIG_convert_unsigned_short,
+	   scheme_make_integer_value_from_unsigned, integer);
+REF_MAP(unsigned long, SWIG_is_unsigned_integer, SWIG_convert_unsigned_long,
+	   scheme_make_integer_value_from_unsigned, integer);
+REF_MAP(float, SCHEME_REALP, scheme_real_to_double,
+	   scheme_make_double, real);
+REF_MAP(double, SCHEME_REALP, scheme_real_to_double,
+	   scheme_make_double, real);
+
+/* Void */
+
+%typemap(out) void "$result = scheme_void;";
+
+/* Pass through Scheme_Object * */
+
+%typemap (in) Scheme_Object * "$1=$input;";
+%typemap (out) Scheme_Object * "$result=$1;";
+%typecheck(SWIG_TYPECHECK_POINTER) Scheme_Object * "$1=1;";
+
+
+/* ------------------------------------------------------------
+ * String & length
+ * ------------------------------------------------------------ */
+
+//%typemap(in) (char *STRING, int LENGTH) {
+//    int temp;
+//    $1 = ($1_ltype) gh_scm2newstr($input, &temp);
+//    $2 = ($2_ltype) temp;
+//}
+
+
+/* ------------------------------------------------------------
+ * Typechecking rules
+ * ------------------------------------------------------------ */
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 int, short, long,
+ 	 unsigned int, unsigned short, unsigned long,
+	 signed char, unsigned char,
+	 long long, unsigned long long,
+	 const int &, const short &, const long &,
+ 	 const unsigned int &, const unsigned short &, const unsigned long &,
+	 const long long &, const unsigned long long &,
+	 enum SWIGTYPE
+{
+  $1 = (SWIG_is_integer($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_BOOL) bool, bool &, const bool &
+{
+  $1 = (SCHEME_BOOLP($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE)
+	float, double,
+	const float &, const double &
+{
+  $1 = (SCHEME_REALP($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char {
+  $1 = (SCHEME_STRINGP($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char * {
+  $1 = (SCHEME_STRINGP($input)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  void *ptr;
+  if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
+  void *ptr;
+  if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0)) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+
diff --git a/trunk/Lib/ocaml/carray.i b/trunk/Lib/ocaml/carray.i
new file mode 100644
index 0000000..bbf1ddd
--- /dev/null
+++ b/trunk/Lib/ocaml/carray.i
@@ -0,0 +1,136 @@
+%insert(mli) %{
+type _value = c_obj
+%}
+
+%insert(ml) %{
+type _value = c_obj
+%}
+
+%define %array_tmap_out(type,what,out_f)
+%typemap(type) what [ANY] {
+    int i;
+    /* $*1_type */
+    $result = caml_array_new($1_dim0);
+    for( i = 0; i < $1_dim0; i++ ) {
+	caml_array_set($result,i,out_f($1[i]));
+    }
+}
+%enddef
+
+%define %array_tmap_in(type,what,in_f)
+%typemap(type) what [ANY] {
+    int i;
+    /* $*1_type */
+    $1 = ($*1_type *)malloc( $1_size );
+    for( i = 0; i < $1_dim0 && i < caml_array_len($input); i++ ) {
+	$1[i] = in_f(caml_array_nth($input,i));
+    }
+}
+
+%typemap(free) what [ANY] {
+    free( (void *)$1 );
+}
+%enddef
+
+%define %make_simple_array_typemap(type,out_f,in_f)
+%array_tmap_out(out,type,out_f);
+%array_tmap_out(varout,type,out_f);
+%array_tmap_out(directorin,type,out_f);
+
+%array_tmap_in(in,type,in_f);
+%array_tmap_in(varin,type,in_f);
+%array_tmap_in(directorout,type,in_f);
+%enddef
+
+%make_simple_array_typemap(bool,caml_val_bool,caml_long_val);
+%make_simple_array_typemap(short,caml_val_short,caml_long_val);
+%make_simple_array_typemap(unsigned short,caml_val_ushort,caml_long_val);
+%make_simple_array_typemap(int,caml_val_int,caml_long_val);
+%make_simple_array_typemap(unsigned int,caml_val_uint,caml_long_val);
+%make_simple_array_typemap(long,caml_val_long,caml_long_val);
+%make_simple_array_typemap(unsigned long,caml_val_ulong,caml_long_val);
+%make_simple_array_typemap(size_t,caml_val_int,caml_long_val);
+%make_simple_array_typemap(float,caml_val_float,caml_double_val);
+%make_simple_array_typemap(double,caml_val_double,caml_double_val);
+
+#ifdef __cplusplus
+%typemap(in) SWIGTYPE [] {
+    int i;
+
+    /* $*1_type */
+    $1 = new $*1_type [$1_dim0];
+    for( i = 0; i < $1_dim0 && i < caml_array_len($input); i++ ) {
+	$1[i] = *(($*1_ltype *) 
+		caml_ptr_val(caml_array_nth($input,i),
+			     $*1_descriptor)) ;
+    }
+}
+#else
+%typemap(in) SWIGTYPE [] {
+    int i;
+
+    /* $*1_type */
+    $1 = ($*1_type *)malloc( $1_size );
+    for( i = 0; i < $1_dim0 && i < caml_array_len($input); i++ ) {
+	$1[i] = *(($*1_ltype)
+		caml_ptr_val(caml_array_nth($input),
+			     $*1_descriptor));
+    }
+}
+#endif
+
+%typemap(out) SWIGTYPE [] {
+    int i;
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    $result = caml_array_new($1_dim0);
+
+    for( i = 0; i < $1_dim0; i++ ) {
+	if( fromval ) {
+	    caml_array_set 
+		($result,
+		 i,
+		 callback(*fromval,caml_val_ptr((void *)&$1[i],$*1_descriptor)));
+	} else {
+	    caml_array_set
+		($result,
+		 i,
+		 caml_val_ptr ((void *)&$1[i],$&1_descriptor));
+	}
+    }
+}
+
+%typemap(in) enum SWIGTYPE [] {
+    int i;
+
+    /* $*1_type */
+    $1 = ($*1_type *)malloc( $1_size );
+    for( i = 0; i < $1_dim0 && i < caml_array_len($input); i++ ) {
+	$1[i] = ($type)
+		caml_long_val_full(caml_array_nth($input),
+			           "$type_marker");
+    }
+}
+
+%typemap(out) enum SWIGTYPE [] {
+    int i;
+    $result = caml_array_new($1_dim0);
+
+    for( i = 0; i < $1_dim0; i++ ) {
+	    caml_array_set 
+		($result,
+		 i,
+		 callback2(*caml_named_value(SWIG_MODULE "_int_to_enum"),
+			   *caml_named_value("$type_marker"),
+			   Val_int($1[i])));
+    }
+}
+
+#ifdef __cplusplus
+%typemap(freearg) SWIGTYPE [ANY] {
+    delete [] $1;
+}
+#else
+%typemap(freearg) SWIGTYPE [ANY] {
+    free( (void *)$1 );
+}
+#endif
diff --git a/trunk/Lib/ocaml/class.swg b/trunk/Lib/ocaml/class.swg
new file mode 100644
index 0000000..0ee304c
--- /dev/null
+++ b/trunk/Lib/ocaml/class.swg
@@ -0,0 +1,66 @@
+(*Stream:class_ctors*)
+let create_$classname_from_ptr raw_ptr =
+  C_obj 
+begin
+  let h = Hashtbl.create 20 in
+    List.iter (fun (nm,fn) -> Hashtbl.replace h nm fn) 
+	[ "nop", (fun args -> C_void) ;
+	  $classbody 
+	 "&", (fun args -> raw_ptr) ;
+       ":parents",
+       (fun args ->
+          C_list
+	  (let out = ref [] in 
+	    Hashtbl.iter (fun x y -> out := (x,y) :: !out) h ;
+          (List.map	
+	     (fun (x,y) ->
+		C_string (String.sub x 2 ((String.length x) - 2)))
+	     (List.filter
+		(fun (x,y) ->
+		   ((String.length x) > 2)
+		   && x.[0] == ':' && x.[1] == ':') !out)))) ;
+       ":classof", (fun args -> C_string "$realname") ;
+       ":methods", (fun args -> 
+	  C_list (let out = ref [] in 
+	    Hashtbl.iter (fun x y -> out := (C_string x) :: !out) h ; !out))
+	] ; 
+	let rec invoke_inner raw_ptr mth arg = 
+	begin
+	  try
+	    let application = Hashtbl.find h mth in
+	      application
+		(match arg with 
+		     C_list l -> (C_list (raw_ptr :: l)) 
+		   | C_void -> (C_list [ raw_ptr ])
+		   | v -> (C_list [ raw_ptr ; v ]))
+	  with Not_found -> 
+		(* Try parent classes *)
+		begin
+		  let parent_classes = [
+		    $baselist
+		  ] in
+		  let rec try_parent plist raw_ptr =
+		    match plist with
+			p :: tl -> 
+			  begin
+			    try
+			      (invoke (p raw_ptr)) mth arg
+			    with (BadMethodName (p,m,s)) -> 
+			      try_parent tl raw_ptr
+			  end
+		      | [] ->
+			  raise (BadMethodName (raw_ptr,mth,"$realname"))
+		  in try_parent parent_classes raw_ptr
+		end
+	end in
+	  (fun mth arg -> invoke_inner raw_ptr mth arg)
+end
+
+let _ = Callback.register 
+          "create_$normalized_from_ptr"
+          create_$classname_from_ptr
+
+
+(*Stream:mli*)
+val create_$classname_from_ptr : c_obj -> c_obj
+
diff --git a/trunk/Lib/ocaml/cstring.i b/trunk/Lib/ocaml/cstring.i
new file mode 100644
index 0000000..e562582
--- /dev/null
+++ b/trunk/Lib/ocaml/cstring.i
@@ -0,0 +1,271 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cstring.i
+ *
+ * This file provides typemaps and macros for dealing with various forms
+ * of C character string handling.   The primary use of this module
+ * is in returning character data that has been allocated or changed in
+ * some way.
+ * ----------------------------------------------------------------------------- */
+
+/* %cstring_input_binary(TYPEMAP, SIZE)
+ * 
+ * Macro makes a function accept binary string data along with
+ * a size.
+ */
+
+%define %cstring_input_binary(TYPEMAP, SIZE)
+%apply (char *STRING, int LENGTH) { (TYPEMAP, SIZE) };
+%enddef
+
+/*
+ * %cstring_bounded_output(TYPEMAP, MAX)
+ *
+ * This macro is used to return a NULL-terminated output string of
+ * some maximum length.  For example:
+ *
+ *     %cstring_bounded_output(char *outx, 512);
+ *     void foo(char *outx) {
+ *         sprintf(outx,"blah blah\n");
+ *     }
+ *
+ */
+
+%define %cstring_bounded_output(TYPEMAP,MAX)
+%typemap(ignore) TYPEMAP(char temp[MAX+1]) {
+    $1 = ($1_ltype) temp;
+}
+%typemap(argout) TYPEMAP {
+    $1[MAX] = 0;
+    $result = caml_list_append($result,caml_val_string(str));
+}
+%enddef
+
+/*
+ * %cstring_chunk_output(TYPEMAP, SIZE)
+ *
+ * This macro is used to return a chunk of binary string data.
+ * Embedded NULLs are okay.  For example:
+ *
+ *     %cstring_chunk_output(char *outx, 512);
+ *     void foo(char *outx) {
+ *         memmove(outx, somedata, 512);
+ *     }
+ *
+ */
+
+%define %cstring_chunk_output(TYPEMAP,SIZE)
+%typemap(ignore) TYPEMAP(char temp[SIZE]) {
+    $1 = ($1_ltype) temp;
+}
+%typemap(argout) TYPEMAP {
+    $result = caml_list_append($result,caml_val_string_len($1,SIZE));
+}
+%enddef
+
+/*
+ * %cstring_bounded_mutable(TYPEMAP, SIZE)
+ *
+ * This macro is used to wrap a string that's going to mutate.
+ *
+ *     %cstring_bounded_mutable(char *in, 512);
+ *     void foo(in *x) {
+ *         while (*x) {
+ *            *x = toupper(*x);
+ *            x++;
+ *         }
+ *     }
+ *
+ */
+
+
+%define %cstring_bounded_mutable(TYPEMAP,MAX)
+%typemap(in) TYPEMAP(char temp[MAX+1]) {
+    char *t = (char *)caml_ptr_val($input);
+    strncpy(temp,t,MAX);
+    $1 = ($1_ltype) temp;
+}
+%typemap(argout) TYPEMAP {
+    $result = caml_list_append($result,caml_val_string_len($1,MAX));
+}
+%enddef
+
+/*
+ * %cstring_mutable(TYPEMAP [, expansion])
+ *
+ * This macro is used to wrap a string that will mutate in place.
+ * It may change size up to a user-defined expansion. 
+ *
+ *     %cstring_mutable(char *in);
+ *     void foo(in *x) {
+ *         while (*x) {
+ *            *x = toupper(*x);
+ *            x++;
+ *         }
+ *     }
+ *
+ */
+
+%define %cstring_mutable(TYPEMAP,...)
+%typemap(in) TYPEMAP {
+   char *t = String_val($input);
+   int   n = string_length($input);
+   $1 = ($1_ltype) t;
+#if #__VA_ARGS__ == ""
+#ifdef __cplusplus
+   $1 = ($1_ltype) new char[n+1];
+#else
+   $1 = ($1_ltype) malloc(n+1);
+#endif
+#else
+#ifdef __cplusplus
+   $1 = ($1_ltype) new char[n+1+__VA_ARGS__];
+#else
+   $1 = ($1_ltype) malloc(n+1+__VA_ARGS__);
+#endif
+#endif
+   memmove($1,t,n);
+   $1[n] = 0;
+}
+
+%typemap(argout) TYPEMAP {
+    $result = caml_list_append($result,caml_val_string($1));
+#ifdef __cplusplus
+   delete[] $1;
+#else
+   free($1);
+#endif
+}
+%enddef
+
+/*
+ * %cstring_output_maxsize(TYPEMAP, SIZE)
+ *
+ * This macro returns data in a string of some user-defined size.
+ *
+ *     %cstring_output_maxsize(char *outx, int max) {
+ *     void foo(char *outx, int max) {
+ *         sprintf(outx,"blah blah\n");
+ *     }
+ */
+
+%define %cstring_output_maxsize(TYPEMAP, SIZE)
+%typemap(in) (TYPEMAP, SIZE) {
+   $2 = caml_val_long($input);
+#ifdef __cplusplus
+   $1 = ($1_ltype) new char[$2+1];
+#else
+   $1 = ($1_ltype) malloc($2+1);
+#endif
+}
+%typemap(argout) (TYPEMAP,SIZE) {
+    $result = caml_list_append($result,caml_val_string($1));
+#ifdef __cplusplus
+   delete [] $1;
+#else
+   free($1);
+#endif
+}
+%enddef
+
+/*
+ * %cstring_output_withsize(TYPEMAP, SIZE)
+ *
+ * This macro is used to return character data along with a size
+ * parameter.
+ *
+ *     %cstring_output_maxsize(char *outx, int *max) {
+ *     void foo(char *outx, int *max) {
+ *         sprintf(outx,"blah blah\n");
+ *         *max = strlen(outx);  
+ *     }
+ */
+
+%define %cstring_output_withsize(TYPEMAP, SIZE)
+%typemap(in) (TYPEMAP, SIZE) {
+   int n = caml_val_long($input);
+#ifdef __cplusplus
+   $1 = ($1_ltype) new char[n+1];
+   $2 = ($2_ltype) new $*1_ltype;
+#else
+   $1 = ($1_ltype) malloc(n+1);
+   $2 = ($2_ltype) malloc(sizeof($*1_ltype));
+#endif
+   *$2 = n;
+}
+%typemap(argout) (TYPEMAP,SIZE) {
+    $result = caml_list_append($result,caml_val_string_len($1,$2));
+#ifdef __cplusplus
+   delete [] $1;
+   delete $2;
+#else
+   free($1);
+   free($2);
+#endif
+}
+%enddef
+
+/*
+ * %cstring_output_allocate(TYPEMAP, RELEASE)
+ *
+ * This macro is used to return character data that was
+ * allocated with new or malloc.
+ *
+ *     %cstring_output_allocated(char **outx, free($1));
+ *     void foo(char **outx) {
+ *         *outx = (char *) malloc(512);
+ *         sprintf(outx,"blah blah\n");
+ *     }
+ */
+
+%define %cstring_output_allocate(TYPEMAP, RELEASE)
+%typemap(ignore) TYPEMAP($*1_ltype temp = 0) {
+   $1 = &temp;
+}
+
+%typemap(argout) TYPEMAP {
+    if (*$1) {
+	$result = caml_list_append($result,caml_val_string($1));
+	RELEASE;
+    } else {
+	$result = caml_list_append($result,caml_val_ptr($1));
+    }
+}
+%enddef
+
+/*
+ * %cstring_output_allocate_size(TYPEMAP, SIZE, RELEASE)
+ *
+ * This macro is used to return character data that was
+ * allocated with new or malloc.
+ *
+ *     %cstring_output_allocated(char **outx, int *sz, free($1));
+ *     void foo(char **outx, int *sz) {
+ *         *outx = (char *) malloc(512);
+ *         sprintf(outx,"blah blah\n");
+ *         *sz = strlen(outx);
+ *     }
+ */
+
+%define %cstring_output_allocate_size(TYPEMAP, SIZE, RELEASE)
+%typemap(ignore) (TYPEMAP, SIZE) ($*1_ltype temp = 0, $*2_ltype tempn) {
+   $1 = &temp;
+   $2 = &tempn;
+}
+
+%typemap(argout)(TYPEMAP,SIZE) {
+    if (*$1) {
+	$result = caml_list_append($result,caml_val_string_len($1,$2));
+	RELEASE;
+    } else 
+	$result = caml_list_append($result,caml_val_ptr($1));
+}
+%enddef
+
+
+
+
+
+
diff --git a/trunk/Lib/ocaml/director.swg b/trunk/Lib/ocaml/director.swg
new file mode 100644
index 0000000..8733316
--- /dev/null
+++ b/trunk/Lib/ocaml/director.swg
@@ -0,0 +1,103 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * director.swg
+ *
+ * This file contains support for director classes that proxy
+ * method calls from C++ to Ocaml extensions.
+ *
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+
+#include <string>
+
+namespace Swig {
+  /* base class for director exceptions */
+  class DirectorException {
+    protected:
+      std::string swig_msg;
+    public:
+      DirectorException(const char* msg="") {
+      }
+      const char *getMessage() const { 
+        return swig_msg.c_str(); 
+      }
+      virtual ~DirectorException() {}
+  };
+
+  /* type mismatch in the return value from a python method call */
+  class DirectorTypeMismatchException : public Swig::DirectorException {
+    public:
+      DirectorTypeMismatchException(const char* msg="") {
+      }
+  };
+
+  /* any python exception that occurs during a director method call */
+  class DirectorMethodException : public Swig::DirectorException {};
+
+  /* attempt to call a pure virtual method via a director method */
+  class DirectorPureVirtualException : public Swig::DirectorException {
+    public:
+      DirectorPureVirtualException(const char* msg="") {
+      }
+
+      static void raise(const char *msg) {
+        throw DirectorPureVirtualException(msg);
+      }
+  };
+
+  /* simple thread abstraction for pthreads on win32 */
+#ifdef __THREAD__
+#define __PTHREAD__
+#if defined(_WIN32) || defined(__WIN32__)
+#define pthread_mutex_lock EnterCriticalSection
+#define pthread_mutex_unlock LeaveCriticalSection
+#define pthread_mutex_t CRITICAL_SECTION
+#define MUTEX_INIT(var) CRITICAL_SECTION var
+#else
+#include <pthread.h>
+#define MUTEX_INIT(var) pthread_mutex_t var = PTHREAD_MUTEX_INITIALIZER 
+#endif
+#endif
+
+  /* director base class */
+  class Director {
+    private:
+      /* pointer to the wrapped ocaml object */
+      CAML_VALUE swig_self;
+      /* flag indicating whether the object is owned by ocaml or c++ */
+      mutable bool swig_disown_flag;
+
+    public:
+      /* wrap a ocaml object, optionally taking ownership */
+      Director(CAML_VALUE self) : swig_self(self), swig_disown_flag(false) {
+        register_global_root(&swig_self);
+      }
+
+      /* discard our reference at destruction */
+      virtual ~Director() {
+        remove_global_root(&swig_self);
+        swig_disown(); 
+        // Disown is safe here because we're just divorcing a reference that
+        // points to us.  
+      }
+
+      /* return a pointer to the wrapped ocaml object */
+      CAML_VALUE swig_get_self() const { 
+	  return swig_self;
+      }
+
+      /* acquire ownership of the wrapped ocaml object (the sense of "disown"
+       * is from ocaml) */
+      void swig_disown() const { 
+        if (!swig_disown_flag) { 
+          swig_disown_flag=true;
+          callback(*caml_named_value("caml_obj_disown"),swig_self);
+        } 
+      }
+  };
+}
+
+#endif /* __cplusplus */
diff --git a/trunk/Lib/ocaml/extra-install.list b/trunk/Lib/ocaml/extra-install.list
new file mode 100644
index 0000000..a63c7fc
--- /dev/null
+++ b/trunk/Lib/ocaml/extra-install.list
@@ -0,0 +1,5 @@
+# see top-level Makefile.in
+# libswigocaml is not needed anymore.
+swigp4.ml
+swig.mli
+swig.ml
diff --git a/trunk/Lib/ocaml/libswigocaml.h b/trunk/Lib/ocaml/libswigocaml.h
new file mode 100644
index 0000000..e752540
--- /dev/null
+++ b/trunk/Lib/ocaml/libswigocaml.h
@@ -0,0 +1,20 @@
+/* Ocaml runtime support */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+    typedef int oc_bool;
+    extern void *nullptr;
+    
+    extern oc_bool isnull( void *v );
+    
+    extern void *get_char_ptr( char *str );
+    extern void *make_ptr_array( int size );
+    extern void *get_ptr( void *arrayptr, int elt );
+    extern void set_ptr( void *arrayptr, int elt, void *elt_v );
+    extern void *offset_ptr( void *ptr, int n );
+
+#ifdef __cplusplus
+};
+#endif
diff --git a/trunk/Lib/ocaml/ocaml.i b/trunk/Lib/ocaml/ocaml.i
new file mode 100644
index 0000000..a46e239
--- /dev/null
+++ b/trunk/Lib/ocaml/ocaml.i
@@ -0,0 +1,61 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ocaml.i
+ *
+ * SWIG Configuration File for Ocaml
+ * ----------------------------------------------------------------------------- */
+
+%runtime %{
+#define SWIGSTATIC static
+%}
+
+/* Insert common stuff */
+%insert(runtime) "swigrun.swg"
+
+/* Include headers */
+%insert(runtime) "ocamldec.swg"
+
+/* Type registration */
+%insert(init) "swiginit.swg"
+%insert(init) "typeregister.swg"
+
+%insert(mlitail) %{
+  val swig_val : c_enum_type -> c_obj -> Swig.c_obj
+%}
+
+%insert(mltail) %{
+  let rec swig_val t v = 
+    match v with
+        C_enum e -> enum_to_int t v
+      | C_list l -> Swig.C_list (List.map (swig_val t) l)
+      | C_array a -> Swig.C_array (Array.map (swig_val t) a)
+      | _ -> Obj.magic v
+%}
+
+/*#ifndef SWIG_NOINCLUDE*/
+%insert(runtime) "ocaml.swg"
+/*#endif*/
+
+%insert(classtemplate) "class.swg"
+
+/* Definitions */
+#define SWIG_malloc(size) swig_malloc(size, FUNC_NAME)
+#define SWIG_free(mem) free(mem)
+
+/* Read in standard typemaps. */
+%include <swig.swg>
+%include <typemaps.i>
+%include <typecheck.i>
+%include <exception.i>
+%include <preamble.swg>
+
+/* ocaml keywords */
+/* There's no need to use this, because of my rewriting machinery.  C++
+ * words never collide with ocaml keywords */
+
+/* still we include the file, but the warning says that the offending
+   name will be properly renamed. Just to let the user to know about
+   it. */
+%include <ocamlkw.swg>
diff --git a/trunk/Lib/ocaml/ocaml.swg b/trunk/Lib/ocaml/ocaml.swg
new file mode 100644
index 0000000..5f8f929
--- /dev/null
+++ b/trunk/Lib/ocaml/ocaml.swg
@@ -0,0 +1,602 @@
+/* -*-c-*- */
+
+/* SWIG pointer structure */
+
+#include <string.h>
+#include <assert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define C_bool 0
+#define C_char 1
+#define C_uchar 2
+#define C_short 3
+#define C_ushort 4
+#define C_int 5
+#define C_uint 6
+#define C_int32 7
+#define C_int64 8
+#define C_float 9
+#define C_double 10
+#define C_ptr 11
+#define C_array 12
+#define C_list 13
+#define C_obj 14
+#define C_string 15
+#define C_enum 16
+#define C_director_core 17
+
+
+/* Cast a pointer if possible; returns 1 if successful */
+    
+    SWIGSTATIC int
+    SWIG_Cast (void *source, swig_type_info *source_type,
+	       void **ptr, swig_type_info *dest_type)
+    {
+	if( !source ) { // Special case for NULL.  This is a popular question
+	    // for other modules on the list, so I want an easy way out...
+	    *ptr = 0;
+	    return 0;
+	}
+
+#ifdef TYPE_CAST_VERBOSE
+	fprintf( stderr, "Trying to cast %s to %s\n", 
+		 source_type ? source_type->str : "<none>",
+		 dest_type ? dest_type->str : "<none>" );
+#endif
+	if (dest_type != source_type) {
+	    /* We have a type mismatch.  Will have to look through our type
+	       mapping table to figure out whether or not we can accept this
+	       datatype. 
+	       --
+	       Ignore typechecks for void *.  Allow any conversion. */
+	    if( !dest_type || !source_type || 
+		!strcmp(dest_type->name,"_p_void") ||
+		!strcmp(source_type->name,"_p_void") ) {
+		*ptr = source;
+		return 0;
+	    } else {
+		swig_cast_info *tc = 
+		    SWIG_TypeCheckStruct(source_type, dest_type );
+#ifdef TYPE_CAST_VERBOSE
+		fprintf( stderr, "Typecheck -> %s\n",
+			 tc ? tc->str : "<none>" );
+#endif
+		if( tc ) {
+		    int newmemory = 0;
+		    *ptr = SWIG_TypeCast(tc, source, &newmemory);
+		    assert(!newmemory); /* newmemory handling not yet implemented */
+		    return 0;
+		} else
+		    return -1;
+	    }
+	} else {
+	    *ptr = source;
+	    return 0;
+	}
+    }
+
+/* Return 0 if successful. */
+    SWIGSTATIC int
+    SWIG_GetPtr(void *inptr, void **outptr, 
+		swig_type_info *intype, swig_type_info *outtype) {
+	if (intype) {
+	    return SWIG_Cast(inptr, intype,
+			     outptr, outtype) == -1;
+	} else {
+	    *outptr = inptr;
+	    return 0;
+	}
+    }
+
+    SWIGSTATIC void caml_print_list( CAML_VALUE v );
+
+    SWIGSTATIC void caml_print_val( CAML_VALUE v ) {
+	switch( SWIG_Tag_val(v) ) {
+	case C_bool:
+	    if( Bool_val(SWIG_Field(v,0)) ) fprintf( stderr, "true " );
+	    else fprintf( stderr, "false " );
+	    break;
+	case C_char:
+	case C_uchar:
+	    fprintf( stderr, "'%c' (\\%03d) ", 
+		     (Int_val(SWIG_Field(v,0)) >= ' ' &&
+		      Int_val(SWIG_Field(v,0)) < 127) ? Int_val(SWIG_Field(v,0)) : '.',
+		     Int_val(SWIG_Field(v,0)) );
+	    break;
+	case C_short:
+	case C_ushort:
+	case C_int:
+	    fprintf( stderr, "%d ", (int)caml_long_val(v) );
+	    break;
+
+	case C_uint:
+	case C_int32:
+	    fprintf( stderr, "%ud ", (unsigned int)caml_long_val(v) );
+	    break;
+	case C_int64:
+	    fprintf( stderr, "%ld ", caml_long_val(v) );
+	    break;
+	case C_float:
+	case C_double:
+	    fprintf( stderr, "%f ", caml_double_val(v) );
+	    break;
+
+	case C_ptr:
+	{
+	    void *vout = 0;
+	    swig_type_info *ty = (swig_type_info *)(long)SWIG_Int64_val(SWIG_Field(v,1));
+	    caml_ptr_val_internal(v,&vout,0);
+	    fprintf( stderr, "PTR(%p,%s) ", 
+		     vout,
+		     ty ? ty->name : "(null)" );
+	}
+	break;
+	case C_array:
+	{
+	    unsigned int i;
+	    for( i = 0; i < Wosize_val( SWIG_Field(v,0) ); i++ ) 
+		caml_print_val( SWIG_Field(SWIG_Field(v,0),i) );
+	}
+	break;
+	case C_list:
+	    caml_print_list( SWIG_Field(v,0) );
+	    break;
+	case C_obj:
+	    fprintf( stderr, "OBJ(%p) ", (void *)SWIG_Field(v,0) );
+	    break;
+	case C_string:
+	{
+	    void *cout;
+	    caml_ptr_val_internal(v,&cout,0);
+	    fprintf( stderr, "'%s' ", (char *)cout );
+	} 
+	break;
+	}
+    }
+
+    SWIGSTATIC void caml_print_list( CAML_VALUE v ) {
+	CAMLparam1(v);
+	while( v && Is_block(v) ) {
+	    fprintf( stderr, "[ " );
+	    caml_print_val( SWIG_Field(v,0) );
+	    fprintf( stderr, "]\n" );
+	    v = SWIG_Field(v,1);
+	}
+	CAMLreturn0;
+    }
+
+    SWIGSTATIC CAML_VALUE caml_list_nth( CAML_VALUE lst, int n ) {
+	CAMLparam1(lst);
+	int i = 0;
+	while( i < n && lst && Is_block(lst) ) {
+	    i++; lst = SWIG_Field(lst,1);
+	}
+	if( lst == Val_unit ) CAMLreturn(Val_unit);
+	else CAMLreturn(SWIG_Field(lst,0));
+    }
+    
+    SWIGSTATIC CAML_VALUE caml_list_append( CAML_VALUE lst, CAML_VALUE elt ) {
+	CAMLparam2(lst,elt);
+	SWIG_CAMLlocal3(v,vt,lh);
+	lh = Val_unit;
+	v = Val_unit;
+
+	/* Appending C_void should have no effect */
+	if( !Is_block(elt) ) return lst;
+
+	while( lst && Is_block(lst) ) {
+	    if( v && v != Val_unit ) {
+		vt = alloc_tuple(2);
+		SWIG_Store_field(v,1,vt);
+		v = vt;
+	    } else {
+		v = lh = alloc_tuple(2);
+	    }
+	    SWIG_Store_field(v,0,SWIG_Field(lst,0));
+	    lst = SWIG_Field(lst,1);
+	}
+
+	if( v && Is_block(v) ) {
+	    vt = alloc_tuple(2);
+	    SWIG_Store_field(v,1,vt);
+	    v = vt;
+	} else {
+	    v = lh = alloc_tuple(2);
+	}
+	SWIG_Store_field(v,0,elt);
+	SWIG_Store_field(v,1,Val_unit);
+
+	CAMLreturn(lh);
+    }
+
+    SWIGSTATIC int caml_list_length( CAML_VALUE lst ) {
+	CAMLparam1(lst);
+	int i = 0;
+	while( lst && Is_block(lst) ) { i++; lst = SWIG_Field(lst,1); }
+	CAMLreturn(i);
+    }
+
+    SWIGSTATIC void caml_array_set( CAML_VALUE arr, int n, CAML_VALUE item ) {
+	CAMLparam2(arr,item);
+	SWIG_Store_field(SWIG_Field(arr,0),n,item);
+	CAMLreturn0;
+    }
+
+    SWIGSTATIC value caml_array_nth( CAML_VALUE arr, int n ) {
+	CAMLparam1(arr);
+	if( SWIG_Tag_val(arr) == C_array )
+	    CAMLreturn(SWIG_Field(SWIG_Field(arr,0),n));
+	else if( SWIG_Tag_val(arr) == C_list )
+	    CAMLreturn(caml_list_nth(arr,0));
+	else
+	    failwith("Need array or list");
+    }
+
+    SWIGSTATIC int caml_array_len( CAML_VALUE arr ) {
+	CAMLparam1(arr);
+	if( SWIG_Tag_val(arr) == C_array )
+	    CAMLreturn(Wosize_val(SWIG_Field(arr,0)));
+	else if( SWIG_Tag_val(arr) == C_list )
+	    CAMLreturn(caml_list_length(arr));
+	else
+	    failwith("Need array or list");
+    }
+
+    SWIGSTATIC CAML_VALUE caml_swig_alloc(int x,int y) {
+	return caml_alloc(x,y);
+    }
+
+    SWIGSTATIC value caml_array_new( int n ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(vv);
+	vv = caml_swig_alloc(1,C_array);
+	SWIG_Store_field(vv,0,alloc_tuple(n));
+	CAMLreturn(vv);
+    }
+    
+    SWIGSTATIC CAML_VALUE caml_val_bool( int b ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(bv);
+	bv = caml_swig_alloc(1,C_bool);
+	SWIG_Store_field(bv,0,Val_bool(b));
+	CAMLreturn(bv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_char( char c ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(cv);
+	cv = caml_swig_alloc(1,C_char);
+	SWIG_Store_field(cv,0,Val_int(c));
+	CAMLreturn(cv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_uchar( unsigned char uc ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(ucv);
+	ucv = caml_swig_alloc(1,C_uchar);
+	SWIG_Store_field(ucv,0,Val_int(uc));
+	CAMLreturn(ucv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_short( short s ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(sv);
+	sv = caml_swig_alloc(1,C_short);
+	SWIG_Store_field(sv,0,Val_int(s));
+	CAMLreturn(sv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_ushort( unsigned short us ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(usv);
+	usv = caml_swig_alloc(1,C_ushort);
+	SWIG_Store_field(usv,0,Val_int(us));
+	CAMLreturn(usv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_int( int i ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(iv);
+	iv = caml_swig_alloc(1,C_int);
+	SWIG_Store_field(iv,0,Val_int(i));
+	CAMLreturn(iv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_uint( unsigned int ui ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(uiv);
+	uiv = caml_swig_alloc(1,C_int);
+	SWIG_Store_field(uiv,0,Val_int(ui));
+	CAMLreturn(uiv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_long( long l ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(lv);
+	lv = caml_swig_alloc(1,C_int64);
+	SWIG_Store_field(lv,0,copy_int64(l));
+	CAMLreturn(lv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_ulong( unsigned long ul ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(ulv);
+	ulv = caml_swig_alloc(1,C_int64);
+	SWIG_Store_field(ulv,0,copy_int64(ul));
+	CAMLreturn(ulv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_float( float f ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(fv);
+	fv = caml_swig_alloc(1,C_float);
+	SWIG_Store_field(fv,0,copy_double((double)f));
+	CAMLreturn(fv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_double( double d ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(fv);
+	fv = caml_swig_alloc(1,C_double);
+	SWIG_Store_field(fv,0,copy_double(d));
+	CAMLreturn(fv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_ptr( void *p, swig_type_info *info ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(vv);
+	vv = caml_swig_alloc(2,C_ptr);
+	SWIG_Store_field(vv,0,copy_int64((long)p));
+	SWIG_Store_field(vv,1,copy_int64((long)info));
+	CAMLreturn(vv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_string( const char *p ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(vv);
+	if( !p ) CAMLreturn(caml_val_ptr( (void *)p, 0 ));
+	vv = caml_swig_alloc(1,C_string);
+	SWIG_Store_field(vv,0,copy_string(p));
+	CAMLreturn(vv);
+    }
+
+    SWIGSTATIC CAML_VALUE caml_val_string_len( const char *p, int len ) {
+	CAMLparam0();
+	SWIG_CAMLlocal1(vv);
+	if( !p || len < 0 ) CAMLreturn(caml_val_ptr( (void *)p, 0 ));
+	vv = caml_swig_alloc(1,C_string);
+	SWIG_Store_field(vv,0,alloc_string(len));
+	memcpy(String_val(SWIG_Field(vv,0)),p,len);
+	CAMLreturn(vv);
+    }
+
+    #define caml_val_obj(v, name) caml_val_obj_helper(v, SWIG_TypeQuery((name)), name)
+    SWIGSTATIC CAML_VALUE caml_val_obj_helper( void *v, swig_type_info *type, char *name) {
+	CAMLparam0();
+	CAMLreturn(callback2(*caml_named_value("caml_create_object_fn"),
+			     caml_val_ptr(v,type),
+			     copy_string(name)));
+    }
+
+    SWIGSTATIC long caml_long_val_full( CAML_VALUE v, char *name ) {
+	CAMLparam1(v);
+	if( !Is_block(v) ) return 0;
+
+	switch( SWIG_Tag_val(v) ) {
+	case C_bool:
+	case C_char:
+	case C_uchar:
+	case C_short:
+	case C_ushort:
+	case C_int:
+	    CAMLreturn(Int_val(SWIG_Field(v,0)));
+	case C_uint:
+	case C_int32:
+	    CAMLreturn(Int32_val(SWIG_Field(v,0)));
+	case C_int64:
+	    CAMLreturn((long)SWIG_Int64_val(SWIG_Field(v,0)));
+	case C_float:
+	case C_double:
+	    CAMLreturn((long)Double_val(SWIG_Field(v,0)));
+	case C_string:
+	    CAMLreturn((long)String_val(SWIG_Field(v,0)));
+	case C_ptr:
+	    CAMLreturn((long)SWIG_Int64_val(SWIG_Field(SWIG_Field(v,0),0)));
+	case C_enum: {
+	    SWIG_CAMLlocal1(ret);
+	    CAML_VALUE *enum_to_int = caml_named_value(SWIG_MODULE "_enum_to_int");
+	    if( !name ) failwith( "Not an enum conversion" );
+	    ret = callback2(*enum_to_int,*caml_named_value(name),v);
+	    CAMLreturn(caml_long_val(ret));
+	}
+	default:
+	    failwith("No conversion to int");
+	}
+    }
+
+    SWIGSTATIC long caml_long_val( CAML_VALUE v ) {
+	return caml_long_val_full(v,0);
+    }
+
+    SWIGSTATIC double caml_double_val( CAML_VALUE v ) {
+	CAMLparam1(v);
+	if( !Is_block(v) ) return 0.0;
+	switch( SWIG_Tag_val(v) ) {
+	case C_bool:
+	case C_char:
+	case C_uchar:
+	case C_short:
+	case C_ushort:
+	case C_int:
+	    CAMLreturn_type(Int_val(SWIG_Field(v,0)));
+	case C_uint:
+	case C_int32:
+	    CAMLreturn_type(Int32_val(SWIG_Field(v,0)));
+	case C_int64:
+	    CAMLreturn_type(SWIG_Int64_val(SWIG_Field(v,0)));
+	case C_float:
+	case C_double:
+	    CAMLreturn_type(Double_val(SWIG_Field(v,0)));
+	default:
+	    fprintf( stderr, "Unknown block tag %d\n", SWIG_Tag_val(v) );
+	    failwith("No conversion to double");
+	}
+    }
+
+    SWIGSTATIC int caml_ptr_val_internal( CAML_VALUE v, void **out, 
+					  swig_type_info *descriptor ) {
+	CAMLparam1(v);
+	void *outptr = NULL;
+        swig_type_info *outdescr = NULL;
+
+	if( v == Val_unit ) {
+	    *out = 0;
+	    CAMLreturn(0);
+	}
+	if( !Is_block(v) ) return -1;
+	switch( SWIG_Tag_val(v) ) {
+	case C_int:
+	    if( !caml_long_val( v ) ) {
+		*out = 0;
+		CAMLreturn(0);
+	    } else {
+		*out = 0;
+		CAMLreturn(1);
+	    }
+	    break;
+	case C_obj:
+	    CAMLreturn
+		(caml_ptr_val_internal
+		 (callback(*caml_named_value("caml_obj_ptr"),v),
+		  out,descriptor));
+	case C_string:
+	    outptr = (void *)String_val(SWIG_Field(v,0));
+	    break;
+	case C_ptr:
+	    outptr = (void *)(long)SWIG_Int64_val(SWIG_Field(v,0));
+            outdescr = (swig_type_info *)(long)SWIG_Int64_val(SWIG_Field(v,1));
+	    break;
+	default:
+	    *out = 0;
+	    CAMLreturn(1);
+	    break;
+	}
+	
+	CAMLreturn(SWIG_GetPtr(outptr,out,outdescr,descriptor));
+    }
+
+    SWIGSTATIC void *caml_ptr_val( CAML_VALUE v, swig_type_info *descriptor ) {
+        CAMLparam0();
+#ifdef TYPE_CAST_VERBOSE
+	caml_print_val( v );
+#endif
+	void *out = NULL;
+	if( !caml_ptr_val_internal( v, &out, descriptor ) )
+	    CAMLreturn_type(out);
+	else
+	    failwith( "No appropriate conversion found." );
+    }
+
+    SWIGSTATIC char *caml_string_val( CAML_VALUE v ) {
+	return (char *)caml_ptr_val( v, 0 );
+    }
+
+    SWIGSTATIC int caml_string_len( CAML_VALUE v ) {
+	switch( SWIG_Tag_val(v) ) {
+	case C_string:
+	    return string_length(SWIG_Field(v,0));
+	default:
+	    return strlen((char *)caml_ptr_val(v,0));
+	}
+    }
+
+    SWIGSTATIC int caml_bool_check( CAML_VALUE v ) {
+	CAMLparam1(v);
+	
+	if( !Is_block(v) ) return 0;
+	
+	switch( SWIG_Tag_val(v) ) {
+	case C_bool:
+	case C_ptr:
+	case C_string:
+	    CAMLreturn(1);
+	default:
+	    CAMLreturn(0);
+	}
+    }
+
+    SWIGSTATIC int caml_int_check( CAML_VALUE v ) {
+	CAMLparam1(v);
+	
+	if( !Is_block(v) ) return 0;
+	
+	switch( SWIG_Tag_val(v) ) {
+	case C_char:
+	case C_uchar:
+	case C_short:
+	case C_ushort:
+	case C_int:
+	case C_uint:
+	case C_int32:
+	case C_int64:
+	    CAMLreturn(1);
+
+	default:
+	    CAMLreturn(0);
+	}
+    }
+
+    SWIGSTATIC int caml_float_check( CAML_VALUE v ) {
+	CAMLparam1(v);
+	if( !Is_block(v) ) return 0;
+
+	switch( SWIG_Tag_val(v) ) {
+	case C_float:
+	case C_double:
+	    CAMLreturn(1);
+
+	default:
+	    CAMLreturn(0);
+	}	
+    }
+
+    SWIGSTATIC int caml_ptr_check( CAML_VALUE v ) {
+	CAMLparam1(v);
+	if( !Is_block(v) ) return 0;
+
+	switch( SWIG_Tag_val(v) ) {
+	case C_string:
+	case C_ptr:
+	case C_int64:
+	    CAMLreturn(1);
+
+	default:
+	    CAMLreturn(0);
+	}	
+    }
+
+    static swig_module_info *SWIG_Ocaml_GetModule() {
+      CAML_VALUE pointer;
+
+      pointer = callback(*caml_named_value("swig_find_type_info"), caml_val_int(0));
+      if (Is_block(pointer) && SWIG_Tag_val(pointer) == C_ptr) {
+        return (swig_module_info *)(void *)(long)SWIG_Int64_val(SWIG_Field(pointer,0));
+      }
+      return 0;
+    }
+
+    static void SWIG_Ocaml_SetModule(swig_module_info *pointer) {
+      CAML_VALUE mod_pointer;
+
+      mod_pointer = caml_val_ptr(pointer, NULL);
+      callback(*caml_named_value("swig_set_type_info"), mod_pointer);
+    }
+
+#ifdef __cplusplus
+}
+#endif
+#undef value
+
diff --git a/trunk/Lib/ocaml/ocamldec.swg b/trunk/Lib/ocaml/ocamldec.swg
new file mode 100644
index 0000000..3b5290f
--- /dev/null
+++ b/trunk/Lib/ocaml/ocamldec.swg
@@ -0,0 +1,172 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ocamldec.swg
+ *
+ * Ocaml runtime code -- declarations
+ * ----------------------------------------------------------------------------- */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+#define SWIGEXT extern "C"
+SWIGEXT {
+#else
+#define SWIGEXT 
+#endif
+#define value caml_value_t
+#define CAML_VALUE caml_value_t
+#include <caml/alloc.h>
+#include <caml/custom.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/callback.h>
+#include <caml/fail.h>
+#include <caml/misc.h>
+
+#define caml_array_set swig_caml_array_set
+
+// Adapted from memory.h and mlvalues.h
+
+#define SWIG_CAMLlocal1(x) \
+  caml_value_t x = 0; \
+  CAMLxparam1 (x)
+
+#define SWIG_CAMLlocal2(x, y) \
+  caml_value_t x = 0, y = 0; \
+  CAMLxparam2 (x, y)
+
+#define SWIG_CAMLlocal3(x, y, z) \
+  caml_value_t x = 0, y = 0, z = 0; \
+  CAMLxparam3 (x, y, z)
+
+#define SWIG_CAMLlocal4(x, y, z, t) \
+  caml_value_t x = 0, y = 0, z = 0, t = 0; \
+  CAMLxparam4 (x, y, z, t)
+
+#define SWIG_CAMLlocal5(x, y, z, t, u) \
+  caml_value_t x = 0, y = 0, z = 0, t = 0, u = 0; \
+  CAMLxparam5 (x, y, z, t, u)
+
+#define SWIG_CAMLlocalN(x, size) \
+  caml_value_t x [(size)] = { 0, /* 0, 0, ... */ }; \
+  CAMLxparamN (x, (size))
+
+#define SWIG_Field(x, i) (((caml_value_t *)(x)) [i])           /* Also an l-value. */
+#define SWIG_Store_field(block, offset, val) do{ \
+  mlsize_t caml__temp_offset = (offset); \
+  caml_value_t caml__temp_val = (val); \
+  modify (&SWIG_Field ((block), caml__temp_offset), caml__temp_val); \
+}while(0)
+
+#define SWIG_Data_custom_val(v) ((void *) &SWIG_Field((v), 1))
+#ifdef ARCH_BIG_ENDIAN
+#define SWIG_Tag_val(val) (((unsigned char *) (val)) [-1])
+                                                 /* Also an l-value. */
+#define SWIG_Tag_hp(hp) (((unsigned char *) (hp)) [sizeof(caml_value_t)-1])
+                                                 /* Also an l-value. */
+#else
+#define SWIG_Tag_val(val) (((unsigned char *) (val)) [-sizeof(caml_value_t)])
+                                                 /* Also an l-value. */
+#define SWIG_Tag_hp(hp) (((unsigned char *) (hp)) [0])
+                                                 /* Also an l-value. */
+#endif
+
+#ifdef CAMLreturn0
+#undef CAMLreturn0
+#endif
+#define CAMLreturn0 do{ \
+  caml_local_roots = caml__frame; \
+  return; \
+}while (0)
+
+#ifdef CAMLreturn
+#undef CAMLreturn
+#endif
+#define CAMLreturn(result) do{ \
+  caml_value_t caml__temp_result = (result); \
+  caml_local_roots = caml__frame; \
+  return (caml__temp_result); \
+}while(0)
+
+#define CAMLreturn_type(result) do{ \
+  caml_local_roots = caml__frame; \
+  return result; \
+}while(0)
+
+#ifdef CAMLnoreturn
+#undef CAMLnoreturn
+#endif
+#define CAMLnoreturn ((void) caml__frame)
+
+
+#ifndef ARCH_ALIGN_INT64
+#define SWIG_Int64_val(v) (*((int64 *) SWIG_Data_custom_val(v)))
+#else
+CAMLextern int64 Int64_val(caml_value_t v);
+#define SWIG_Int64_val(v) Int64_val(v)
+#endif
+
+#define SWIG_NewPointerObj(p,type,flags) caml_val_ptr(p,type)
+#define SWIG_GetModule(clientdata) SWIG_Ocaml_GetModule()
+#define SWIG_SetModule(clientdata, pointer) SWIG_Ocaml_SetModule(pointer)
+
+#define SWIG_contract_assert(expr, msg) if(!(expr)) {failwith(msg);} else
+
+    SWIGSTATIC int
+    SWIG_GetPtr(void *source, void **result, swig_type_info *type, swig_type_info *result_type);
+    
+    SWIGSTATIC void *
+    SWIG_MustGetPtr (CAML_VALUE v,  swig_type_info *type);
+    
+    SWIGSTATIC CAML_VALUE _wrap_delete_void( CAML_VALUE );
+    
+    SWIGSTATIC int enum_to_int( char *name, CAML_VALUE v );
+    SWIGSTATIC CAML_VALUE int_to_enum( char *name, int v );
+
+    SWIGSTATIC CAML_VALUE caml_list_nth( CAML_VALUE lst, int n );
+    SWIGSTATIC CAML_VALUE caml_list_append( CAML_VALUE lst, CAML_VALUE elt );
+    SWIGSTATIC int caml_list_length( CAML_VALUE lst );
+    SWIGSTATIC CAML_VALUE caml_array_new( int n );
+    SWIGSTATIC void caml_array_set( CAML_VALUE arr, int n, CAML_VALUE item );
+    SWIGSTATIC CAML_VALUE caml_array_nth( CAML_VALUE arr, int n );
+    SWIGSTATIC int caml_array_length( CAML_VALUE arr );
+
+    SWIGSTATIC CAML_VALUE caml_val_char( char c );
+    SWIGSTATIC CAML_VALUE caml_val_uchar( unsigned char c );
+
+    SWIGSTATIC CAML_VALUE caml_val_short( short s );
+    SWIGSTATIC CAML_VALUE caml_val_ushort( unsigned short s );
+    
+    SWIGSTATIC CAML_VALUE caml_val_int( int x );
+    SWIGSTATIC CAML_VALUE caml_val_uint( unsigned int x );
+
+    SWIGSTATIC CAML_VALUE caml_val_long( long x );
+    SWIGSTATIC CAML_VALUE caml_val_ulong( unsigned long x );
+
+    SWIGSTATIC CAML_VALUE caml_val_float( float f );
+    SWIGSTATIC CAML_VALUE caml_val_double( double d );
+
+    SWIGSTATIC CAML_VALUE caml_val_ptr( void *p, swig_type_info *descriptor );
+
+    SWIGSTATIC CAML_VALUE caml_val_string( const char *str );
+    SWIGSTATIC CAML_VALUE caml_val_string_len( const char *str, int len );
+
+    SWIGSTATIC long caml_long_val( CAML_VALUE v );
+    SWIGSTATIC double caml_double_val( CAML_VALUE v );
+
+    SWIGSTATIC int caml_ptr_val_internal( CAML_VALUE v, void **out,
+				      swig_type_info *descriptor );
+    SWIGSTATIC void *caml_ptr_val( CAML_VALUE v, swig_type_info *descriptor );
+
+    SWIGSTATIC char *caml_string_val( CAML_VALUE v );
+    SWIGSTATIC int caml_string_len( CAML_VALUE v );
+
+#ifdef __cplusplus
+}
+#endif
+
+/* mzschemedec.swg ends here */
diff --git a/trunk/Lib/ocaml/ocamlkw.swg b/trunk/Lib/ocaml/ocamlkw.swg
new file mode 100644
index 0000000..9b9096e
--- /dev/null
+++ b/trunk/Lib/ocaml/ocamlkw.swg
@@ -0,0 +1,64 @@
+#ifndef OCAML_OCAMLKW_SWG_
+#define OCAML_OCAMLKW_SWG_
+
+/* Warnings for Ocaml keywords */
+#define OCAMLKW(x) %namewarn("314: '" #x "' is a ocaml keyword and it will properly renamed")  #x
+
+/*
+  from
+  http://caml.inria.fr/ocaml/htmlman/manual044.html
+*/
+
+
+OCAMLKW(and);
+OCAMLKW(as);
+OCAMLKW(assert);
+OCAMLKW(begin);
+OCAMLKW(class);
+OCAMLKW(constraint);
+OCAMLKW(do);
+OCAMLKW(done);
+OCAMLKW(downto);
+OCAMLKW(else);
+OCAMLKW(end);
+OCAMLKW(exception);
+OCAMLKW(external);
+OCAMLKW(false);
+OCAMLKW(for);
+OCAMLKW(fun);
+OCAMLKW(function);
+OCAMLKW(functor);
+OCAMLKW(if);
+OCAMLKW(in);
+OCAMLKW(include);
+OCAMLKW(inherit);
+OCAMLKW(initializer);
+OCAMLKW(lazy);
+OCAMLKW(let);
+OCAMLKW(match);
+OCAMLKW(method);
+OCAMLKW(module);
+OCAMLKW(mutable);
+OCAMLKW(new);
+OCAMLKW(object);
+OCAMLKW(of);
+OCAMLKW(open);
+OCAMLKW(or);
+OCAMLKW(private);
+OCAMLKW(rec);
+OCAMLKW(sig);
+OCAMLKW(struct);
+OCAMLKW(then);
+OCAMLKW(to);
+OCAMLKW(true);
+OCAMLKW(try);
+OCAMLKW(type);
+OCAMLKW(val);
+OCAMLKW(virtual);
+OCAMLKW(when);
+OCAMLKW(while);
+OCAMLKW(with);
+
+#undef OCAMLKW
+
+#endif //OCAML_OCAMLKW_SWG_
diff --git a/trunk/Lib/ocaml/preamble.swg b/trunk/Lib/ocaml/preamble.swg
new file mode 100644
index 0000000..39374ce
--- /dev/null
+++ b/trunk/Lib/ocaml/preamble.swg
@@ -0,0 +1,17 @@
+%insert(mli) %{
+exception BadArgs of string
+exception BadMethodName of c_obj * string * string
+exception NotObject of c_obj
+exception NotEnumType of c_obj
+exception LabelNotFromThisEnum of c_obj
+exception InvalidDirectorCall of c_obj
+%}
+
+%insert(ml) %{
+exception BadArgs of string
+exception BadMethodName of c_obj * string * string
+exception NotObject of c_obj
+exception NotEnumType of c_obj
+exception LabelNotFromThisEnum of c_obj
+exception InvalidDirectorCall of c_obj
+%}
\ No newline at end of file
diff --git a/trunk/Lib/ocaml/std_common.i b/trunk/Lib/ocaml/std_common.i
new file mode 100644
index 0000000..b2dff61
--- /dev/null
+++ b/trunk/Lib/ocaml/std_common.i
@@ -0,0 +1,22 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_common.i
+ *
+ * SWIG typemaps for STL - common utilities
+ * ----------------------------------------------------------------------------- */
+
+%include <std/std_except.i>
+
+%apply size_t { std::size_t };
+
+%{
+#include <string>
+    CAML_VALUE SwigString_FromString(const std::string& s) {
+	return caml_val_string((char *)s.c_str());
+    }
+    std::string SwigString_AsString(CAML_VALUE o) {
+	return std::string((char *)caml_ptr_val(o,0));
+    }
+%}
diff --git a/trunk/Lib/ocaml/std_complex.i b/trunk/Lib/ocaml/std_complex.i
new file mode 100644
index 0000000..5192261
--- /dev/null
+++ b/trunk/Lib/ocaml/std_complex.i
@@ -0,0 +1,65 @@
+// -*- C++ -*- 
+#ifndef SWIG_STD_COMPLEX_I_
+#define SWIG_STD_COMPLEX_I_
+
+#ifdef SWIG
+
+%{
+#include <complex>
+%} 
+
+namespace std 
+{
+  template <class T> class complex;  
+  
+  %define specialize_std_complex(T)
+  
+  %typemap(in) complex<T> {
+    if (PyComplex_Check($input)) {
+      $1 = std::complex<T>(PyComplex_RealAsDouble($input),
+			   PyComplex_ImagAsDouble($input));
+    } else if (PyFloat_Check($input)) {
+      $1 = std::complex<T>(PyFloat_AsDouble($input), 0);
+    } else if (PyInt_Check($input)) {
+      $1 = std::complex<T>(PyInt_AsLong($input), 0);
+    }
+    else {
+      PyErr_SetString(PyExc_TypeError,"Expected a complex");
+      SWIG_fail;
+    }
+  }  
+  
+  %typemap(in) const complex<T>& (std::complex<T> temp) {
+    if (PyComplex_Check($input)) {
+      temp = std::complex<T>(PyComplex_RealAsDouble($input),
+			     PyComplex_ImagAsDouble($input));
+      $1 = &temp;
+    } else if (PyFloat_Check($input)) {
+      temp = std::complex<T>(PyFloat_AsDouble($input), 0);
+      $1 = &temp;
+    } else if (PyInt_Check($input)) {
+      temp = std::complex<T>(PyInt_AsLong($input), 0);
+      $1 = &temp;
+    } else {	
+      PyErr_SetString(PyExc_TypeError,"Expected a complex");
+      SWIG_fail;
+    }
+  }
+  
+  %typemap(out) complex<T> {
+    $result = PyComplex_FromDoubles($1.real(), $1.imag());
+  }
+  
+  %typemap(out) const complex<T> & {
+    $result = PyComplex_FromDoubles($1->real(), $1->imag());
+  }
+
+  %enddef  
+     
+  specialize_std_complex(double);
+  specialize_std_complex(float);
+}
+  
+#endif // SWIG
+
+#endif //SWIG_STD_COMPLEX_I_
diff --git a/trunk/Lib/ocaml/std_deque.i b/trunk/Lib/ocaml/std_deque.i
new file mode 100644
index 0000000..44815eb
--- /dev/null
+++ b/trunk/Lib/ocaml/std_deque.i
@@ -0,0 +1,31 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_deque.i
+ *
+ * Default std_deque wrapper
+ * ----------------------------------------------------------------------------- */
+
+%module std_deque
+
+%rename(__getitem__) std::deque::getitem;
+%rename(__setitem__) std::deque::setitem;
+%rename(__delitem__) std::deque::delitem;
+%rename(__getslice__) std::deque::getslice;
+%rename(__setslice__) std::deque::setslice;
+%rename(__delslice__) std::deque::delslice;
+
+%extend std::deque {
+   int __len__() {
+       return (int) self->size();
+   }
+   int __nonzero__() {
+       return ! self->empty();
+   }
+   void append(const T &x) {
+       self->push_back(x);
+   }
+};
+
+%include <_std_deque.i>
diff --git a/trunk/Lib/ocaml/std_list.i b/trunk/Lib/ocaml/std_list.i
new file mode 100644
index 0000000..0aea907
--- /dev/null
+++ b/trunk/Lib/ocaml/std_list.i
@@ -0,0 +1,222 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_list.i
+ *
+ * SWIG typemaps for std::list types
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+%module std_list
+%{
+#include <list>
+#include <stdexcept>
+%}
+
+
+namespace std{
+    template<class T> class list
+    {
+    public:
+	     
+	typedef T &reference;
+	typedef const T& const_reference;
+	typedef T &iterator;
+	typedef const T& const_iterator; 
+	    
+	list();
+	list(unsigned int size, const T& value = T());
+	list(const list<T> &);
+
+	~list();
+	void assign(unsigned int n, const T& value);
+	void swap(list<T> &x);
+
+	const_reference front();
+	const_reference back();
+	const_iterator begin();
+	const_iterator end();
+	     
+	void resize(unsigned int n, T c = T());
+	bool empty() const;
+
+	void push_front(const T& x);
+	void push_back(const T& x);
+
+
+	void pop_front();
+	void pop_back();
+	void clear();
+	unsigned int size() const;
+	unsigned int max_size() const;
+	void resize(unsigned int n, const T& value);
+		
+	void remove(const T& value);
+	void unique();
+	void reverse();
+	void sort();
+             
+	     
+		
+	%extend 
+	    {
+		const_reference __getitem__(int i) throw (std::out_of_range) 
+		    {
+			std::list<T>::iterator first = self->begin(); 
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (i>=0 && i<size)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    return *first;
+			}
+			else throw std::out_of_range("list index out of range");
+		    }
+		void __setitem__(int i, const T& x) throw (std::out_of_range)
+		    {
+			std::list<T>::iterator first = self->begin(); 
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (i>=0 && i<size)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    *first = x;
+			}
+			else throw std::out_of_range("list index out of range");
+		    }
+		void __delitem__(int i) throw (std::out_of_range)
+		    {
+			std::list<T>::iterator first = self->begin(); 
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (i>=0 && i<size)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    self->erase(first);
+			}
+			else throw std::out_of_range("list index out of range");
+		    }	     
+		std::list<T> __getslice__(int i,int j) 
+		    {
+			std::list<T>::iterator first = self->begin();
+			std::list<T>::iterator end = self->end();
+
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (j<0) j += size;
+			if (i<0) i = 0;
+			if (j>size) j = size;
+			if (i>=j) i=j;
+			if (i>=0 && i<size && j>=0)
+			{
+			    for (int k=0;k<i;k++)
+			    {
+				first++;
+			    }
+			    for (int m=0;m<j;m++)
+			    {
+				end++;
+			    }
+			    std::list<T> tmp(j-i);
+			    if (j>i) std::copy(first,end,tmp.begin());
+			    return tmp;
+			}
+			else throw std::out_of_range("list index out of range");
+		    }
+		void __delslice__(int i,int j) 
+		    {
+			std::list<T>::iterator first = self->begin();
+			std::list<T>::iterator end = self->end();
+
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (j<0) j += size;
+			if (i<0) i = 0;
+			if (j>size) j = size;
+	
+			for (int k=0;k<i;k++)
+			{
+			    first++;
+			}
+			for (int m=0;m<=j;m++)
+			{
+			    end++;
+			}		   
+			self->erase(first,end);		
+		    }
+		void __setslice__(int i,int j, const std::list<T>& v) 
+		    {
+			std::list<T>::iterator first = self->begin();
+			std::list<T>::iterator end = self->end();
+
+			int size = int(self->size());
+			if (i<0) i += size;
+			if (j<0) j += size;
+			if (i<0) i = 0;
+			if (j>size) j = size;
+		
+			for (int k=0;k<i;k++)
+			{
+			    first++;
+			}
+			for (int m=0;m<=j;m++)
+			{
+			    end++;
+			}
+			if (int(v.size()) == j-i) 
+			{
+			    std::copy(v.begin(),v.end(),first);
+			}
+			else {
+			    self->erase(first,end);
+			    if (i+1 <= int(self->size())) 
+			    {
+				first = self->begin();
+				for (int k=0;k<i;k++)
+				{
+				    first++;
+				}
+				self->insert(first,v.begin(),v.end());
+			    }
+			    else self->insert(self->end(),v.begin(),v.end());
+			}
+			   	
+		    }
+		unsigned int __len__() 
+		    {
+			return self->size();
+		    }	
+		bool __nonzero__()
+		    {
+			return !(self->empty());
+		    }
+		void append(const T& x)
+		    {
+			self->push_back(x);
+		    }
+		void pop()
+		    {
+			self->pop_back();
+		    }
+	      
+	    };   
+	  
+    };
+}
+
+
+
+
+
+
diff --git a/trunk/Lib/ocaml/std_map.i b/trunk/Lib/ocaml/std_map.i
new file mode 100644
index 0000000..f174f28
--- /dev/null
+++ b/trunk/Lib/ocaml/std_map.i
@@ -0,0 +1,173 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, T x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    // add specializations here
+}
diff --git a/trunk/Lib/ocaml/std_pair.i b/trunk/Lib/ocaml/std_pair.i
new file mode 100644
index 0000000..dc0604d
--- /dev/null
+++ b/trunk/Lib/ocaml/std_pair.i
@@ -0,0 +1,37 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+namespace std {
+
+  template<class T, class U> struct pair {
+
+    pair();
+    pair(T first, U second);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+  };
+
+  // add specializations here
+
+}
diff --git a/trunk/Lib/ocaml/std_string.i b/trunk/Lib/ocaml/std_string.i
new file mode 100644
index 0000000..7add3a0
--- /dev/null
+++ b/trunk/Lib/ocaml/std_string.i
@@ -0,0 +1,179 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string
+ * ----------------------------------------------------------------------------- */
+
+// ------------------------------------------------------------------------
+// std::string is typemapped by value
+// This can prevent exporting methods which return a string
+// in order for the user to modify it.
+// However, I think I'll wait until someone asks for it...
+// ------------------------------------------------------------------------
+
+%include <exception.i>
+
+%{
+#include <string>
+#include <vector>
+    using std::string;
+    using std::vector;
+%}
+
+%include <std_vector.i>
+
+%naturalvar std::string;
+%naturalvar std::wstring;
+
+namespace std {
+    template <class charT> class basic_string {
+    public:
+	typedef charT *pointer;
+	typedef charT &reference;
+	typedef const charT &const_reference;
+	typedef size_t size_type;
+	typedef ptrdiff_t difference_type;
+	basic_string();
+	basic_string( charT *str );
+	size_t size();
+	charT operator []( int pos ) const;
+	charT *c_str() const;
+	basic_string<charT> &operator = ( const basic_string &ws );
+	basic_string<charT> &operator = ( const charT *str );
+	basic_string<charT> &append( const basic_string<charT> &other );
+	basic_string<charT> &append( const charT *str );
+	void push_back( charT c );
+	void clear();
+	void reserve( size_type t );
+	void resize( size_type n, charT c = charT() );
+	int compare( const basic_string<charT> &other ) const;
+	int compare( const charT *str ) const;
+	basic_string<charT> &insert( size_type pos, 
+				     const basic_string<charT> &str );
+	size_type find( const basic_string<charT> &other, int pos = 0 ) const;
+	size_type find( charT c, int pos = 0 ) const;
+	%extend {
+	    bool operator == ( const basic_string<charT> &other ) const {
+		return self->compare( other ) == 0;
+	    }
+	    bool operator != ( const basic_string<charT> &other ) const {
+		return self->compare( other ) != 0;
+	    }
+	    bool operator < ( const basic_string<charT> &other ) const {
+		return self->compare( other ) == -1;
+	    }
+	    bool operator > ( const basic_string<charT> &other ) const {
+		return self->compare( other ) == 1;
+	    }
+	    bool operator <= ( const basic_string<charT> &other ) const {
+		return self->compare( other ) != 1;
+	    }
+	    bool operator >= ( const basic_string<charT> &other ) const {
+		return self->compare( other ) != -1;
+	    }
+	}
+    };
+
+    %template(string) basic_string<char>;
+    %template(wstring) basic_string<wchar_t>;
+    typedef basic_string<char> string;
+    typedef basic_string<wchar_t> wstring;
+
+    /* Overloading check */
+    %typemap(in) string {
+        if (caml_ptr_check($input))
+            $1.assign((char *)caml_ptr_val($input,0),
+                      caml_string_len($input));
+        else
+            SWIG_exception(SWIG_TypeError, "string expected");
+    }
+
+    %typemap(in) const string & (std::string temp) {
+        if (caml_ptr_check($input)) {
+            temp.assign((char *)caml_ptr_val($input,0),
+                        caml_string_len($input));
+            $1 = &temp;
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(in) string & (std::string temp) {
+        if (caml_ptr_check($input)) {
+            temp.assign((char *)caml_ptr_val($input,0),
+                        caml_string_len($input));
+            $1 = &temp;
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(in) string * (std::string *temp) {
+        if (caml_ptr_check($input)) {
+            temp = new std::string((char *)caml_ptr_val($input,0),
+				   caml_string_len($input));
+            $1 = temp;
+        } else {
+            SWIG_exception(SWIG_TypeError, "string expected");
+        }
+    }
+
+    %typemap(free) string * (std::string *temp) {
+	delete temp;
+    }
+
+    %typemap(argout) string & {
+	caml_list_append(swig_result,caml_val_string_len((*$1).c_str(),
+							 (*$1).size()));
+    }
+
+    %typemap(directorout) string {
+	$result.assign((char *)caml_ptr_val($input,0),
+		       caml_string_len($input));
+    }
+
+    %typemap(out) string {
+        $result = caml_val_string_len($1.c_str(),$1.size());
+    }
+
+    %typemap(out) string * {
+	$result = caml_val_string_len((*$1).c_str(),(*$1).size());
+    }
+}
+
+#ifdef ENABLE_CHARPTR_ARRAY
+char **c_charptr_array( const std::vector <string > &str_v );
+
+%{
+  SWIGEXT char **c_charptr_array( const std::vector <string > &str_v ) {
+    char **out = new char *[str_v.size() + 1];
+    out[str_v.size()] = 0;
+    for( int i = 0; i < str_v.size(); i++ ) {
+      out[i] = (char *)str_v[i].c_str();
+    }
+    return out;
+  }
+%}
+#endif
+
+#ifdef ENABLE_STRING_VECTOR
+%template (StringVector) std::vector<string >;
+
+%insert(ml) %{
+  (* Some STL convenience items *)
+
+  let string_array_to_vector sa = 
+    let nv = _new_StringVector C_void in
+      array_to_vector nv (fun x -> C_string x) sa ; nv
+	
+  let c_string_array ar = 
+    _c_charptr_array (string_array_to_vector ar)
+%}
+
+%insert(mli) %{
+  val c_string_array: string array -> c_obj
+%}
+#endif
diff --git a/trunk/Lib/ocaml/std_vector.i b/trunk/Lib/ocaml/std_vector.i
new file mode 100644
index 0000000..91c3355
--- /dev/null
+++ b/trunk/Lib/ocaml/std_vector.i
@@ -0,0 +1,92 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * SWIG typemaps for std::vector types
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// Python as much as possible, namely, to allow the user to pass and 
+// be returned Python tuples or lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&), f(const std::vector<T>*):
+//      the parameter being read-only, either a Python sequence or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f():
+//      the vector is returned by copy; therefore, a Python sequence of T:s 
+//      is returned which is most easily used in other Python functions
+//   -- std::vector<T>& f(), std::vector<T>* f(), const std::vector<T>& f(),
+//      const std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    template <class T> class vector {
+    public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T>&);
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        void push_back(const T& x);
+	T operator [] ( int f );
+	vector <T> &operator = ( vector <T> &other );
+	%extend {
+	    void set( int i, const T &x ) {
+		self->resize(i+1);
+		(*self)[i] = x;
+	    }
+	};
+	%extend {
+	    T *to_array() {
+		T *array = new T[self->size() + 1];
+		for( int i = 0; i < self->size(); i++ ) 
+		    array[i] = (*self)[i];
+		return array;
+	    }
+	};
+    };
+};
+
+%insert(ml) %{
+  
+  let array_to_vector v argcons array = 
+    for i = 0 to (Array.length array) - 1 do
+	(invoke v) "set" (C_list [ C_int i ; (argcons array.(i)) ])
+    done ;
+    v
+    
+  let vector_to_array v argcons array =
+    for i = 0; to (get_int ((invoke v) "size" C_void)) - 1 do
+	array.(i) <- argcons ((invoke v) "[]" (C_int i))
+    done ; 
+    v
+      
+%}
+
+%insert(mli) %{
+    val array_to_vector : c_obj -> ('a -> c_obj) -> 'a array -> c_obj
+    val vector_to_array : c_obj -> (c_obj -> 'a) -> 'a array -> c_obj
+%}
diff --git a/trunk/Lib/ocaml/stl.i b/trunk/Lib/ocaml/stl.i
new file mode 100644
index 0000000..66b72e0
--- /dev/null
+++ b/trunk/Lib/ocaml/stl.i
@@ -0,0 +1,15 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/ocaml/swig.ml b/trunk/Lib/ocaml/swig.ml
new file mode 100644
index 0000000..5dc2de7
--- /dev/null
+++ b/trunk/Lib/ocaml/swig.ml
@@ -0,0 +1,159 @@
+(* -*- tuareg -*- *)
+open Int32
+open Int64
+
+type enum = [ `Int of int ]
+
+type 'a c_obj_t = 
+    C_void
+  | C_bool of bool
+  | C_char of char
+  | C_uchar of char
+  | C_short of int
+  | C_ushort of int
+  | C_int of int
+  | C_uint of int32
+  | C_int32 of int32
+  | C_int64 of int64
+  | C_float of float
+  | C_double of float
+  | C_ptr of int64 * int64
+  | C_array of 'a c_obj_t array
+  | C_list of 'a c_obj_t list
+  | C_obj of (string -> 'a c_obj_t -> 'a c_obj_t)
+  | C_string of string
+  | C_enum of 'a
+  | C_director_core of 'a c_obj_t * 'a c_obj_t option ref
+
+type c_obj = enum c_obj_t
+
+exception BadArgs of string
+exception BadMethodName of string * string
+exception NotObject of c_obj
+exception NotEnumType of c_obj
+exception LabelNotFromThisEnum of c_obj
+exception InvalidDirectorCall of c_obj
+exception NoSuchClass of string
+let rec invoke obj = 
+  match obj with 
+      C_obj o -> o 
+    | C_director_core (o,r) -> invoke o
+    | _ -> raise (NotObject (Obj.magic obj))
+let _ = Callback.register "swig_runmethod" invoke
+
+let fnhelper arg =
+  match arg with C_list l -> l | C_void -> [] | _ -> [ arg ]
+
+let rec get_int x = 
+  match x with
+      C_bool b -> if b then 1 else 0
+    | C_char c
+    | C_uchar c -> (int_of_char c)
+    | C_short s
+    | C_ushort s
+    | C_int s -> s
+    | C_uint u
+    | C_int32 u -> (Int32.to_int u)
+    | C_int64 u -> (Int64.to_int u)
+    | C_float f -> (int_of_float f)
+    | C_double d -> (int_of_float d)
+    | C_ptr (p,q) -> (Int64.to_int p)
+    | C_obj o -> (try (get_int (o "int" C_void))
+		  with _ -> (get_int (o "&" C_void)))
+    | _ -> raise (Failure "Can't convert to int")
+
+let rec get_float x = 
+  match x with
+      C_char c
+    | C_uchar c -> (float_of_int (int_of_char c))
+    | C_short s -> (float_of_int s)
+    | C_ushort s -> (float_of_int s)
+    | C_int s -> (float_of_int s)
+    | C_uint u
+    | C_int32 u -> (float_of_int (Int32.to_int u))
+    | C_int64 u -> (float_of_int (Int64.to_int u))
+    | C_float f -> f
+    | C_double d -> d
+    | C_obj o -> (try (get_float (o "float" C_void))
+		  with _ -> (get_float (o "double" C_void)))
+    | _ -> raise (Failure "Can't convert to float")
+
+let rec get_char x =
+  (char_of_int (get_int x))
+
+let rec get_string x = 
+  match x with 
+      C_string str -> str
+    | _ -> raise (Failure "Can't convert to string")
+
+let rec get_bool x = 
+  match x with
+      C_bool b -> b
+    | _ -> 
+	(try if get_int x != 0 then true else false
+	 with _ -> raise (Failure "Can't convert to bool"))
+
+let disown_object obj = 
+  match obj with
+      C_director_core (o,r) -> r := None
+    | _ -> raise (Failure "Not a director core object")
+let _ = Callback.register "caml_obj_disown" disown_object
+let addr_of obj = 
+  match obj with
+      C_obj _ -> (invoke obj) "&" C_void
+    | C_director_core (self,r) -> (invoke self) "&" C_void
+    | C_ptr _ -> obj
+    | _ -> raise (Failure "Not a pointer.")
+let _ = Callback.register "caml_obj_ptr" addr_of
+
+let make_float f = C_float f
+let make_double f = C_double f
+let make_string s = C_string s
+let make_bool b = C_bool b
+let make_char c = C_char c
+let make_char_i c = C_char (char_of_int c)
+let make_uchar c = C_uchar c
+let make_uchar_i c = C_uchar (char_of_int c)
+let make_short i = C_short i
+let make_ushort i = C_ushort i
+let make_int i = C_int i
+let make_uint i = C_uint (Int32.of_int i)
+let make_int32 i = C_int32 (Int32.of_int i)
+let make_int64 i = C_int64 (Int64.of_int i)
+
+let new_derived_object cfun x_class args =
+  begin
+    let get_object ob =
+      match !ob with
+          None ->
+    raise (NotObject C_void)
+        | Some o -> o in
+    let ob_ref = ref None in
+    let class_fun class_f ob_r =
+      (fun meth args -> class_f (get_object ob_r) meth args) in
+    let new_class = class_fun x_class ob_ref in
+    let dircore = C_director_core (C_obj new_class,ob_ref) in
+    let obj =
+    cfun (match args with
+            C_list argl -> (C_list ((dircore :: argl)))
+	  | C_void -> (C_list [ dircore ])
+          | a -> (C_list [ dircore ; a ])) in
+    ob_ref := Some obj ;
+      obj
+  end
+  
+let swig_current_type_info = ref C_void
+let find_type_info obj = !swig_current_type_info 
+let _ = Callback.register "swig_find_type_info" find_type_info
+let set_type_info obj =
+  match obj with
+    C_ptr _ -> swig_current_type_info := obj ;
+               obj
+    | _ -> raise (Failure "Internal error: passed non pointer to set_type_info")
+let _ = Callback.register "swig_set_type_info" set_type_info
+
+let class_master_list = Hashtbl.create 20
+let register_class_byname nm co = 
+  Hashtbl.replace class_master_list nm (Obj.magic co)
+let create_class nm arg = 
+  try (Obj.magic (Hashtbl.find class_master_list nm)) arg with _ -> raise (NoSuchClass nm)
diff --git a/trunk/Lib/ocaml/swig.mli b/trunk/Lib/ocaml/swig.mli
new file mode 100644
index 0000000..3207b9e
--- /dev/null
+++ b/trunk/Lib/ocaml/swig.mli
@@ -0,0 +1,61 @@
+(* -*- tuareg -*- *)
+
+type enum = [ `Int of int ]
+
+type 'a c_obj_t = 
+    C_void
+  | C_bool of bool
+  | C_char of char
+  | C_uchar of char
+  | C_short of int
+  | C_ushort of int
+  | C_int of int
+  | C_uint of int32
+  | C_int32 of int32
+  | C_int64 of int64
+  | C_float of float
+  | C_double of float
+  | C_ptr of int64 * int64
+  | C_array of 'a c_obj_t array
+  | C_list of 'a c_obj_t list
+  | C_obj of (string -> 'a c_obj_t -> 'a c_obj_t)
+  | C_string of string
+  | C_enum of 'a
+  | C_director_core of 'a c_obj_t * 'a c_obj_t option ref
+
+type c_obj = enum c_obj_t
+
+exception InvalidDirectorCall of c_obj
+exception NoSuchClass of string
+
+val invoke : ('a c_obj_t) -> (string -> 'a c_obj_t -> 'a c_obj_t)
+val fnhelper : 'a c_obj_t -> 'a c_obj_t list
+
+val get_int : 'a c_obj_t -> int
+val get_float : 'a c_obj_t -> float
+val get_string : 'a c_obj_t -> string
+val get_char : 'a c_obj_t -> char
+val get_bool : 'a c_obj_t -> bool
+
+val make_float : float -> 'a c_obj_t
+val make_double : float -> 'a c_obj_t
+val make_string : string -> 'a c_obj_t
+val make_bool : bool -> 'a c_obj_t
+val make_char : char -> 'a c_obj_t
+val make_char_i : int -> 'a c_obj_t
+val make_uchar : char -> 'a c_obj_t
+val make_uchar_i : int -> 'a c_obj_t
+val make_short : int -> 'a c_obj_t
+val make_ushort : int -> 'a c_obj_t
+val make_int : int -> 'a c_obj_t
+val make_uint : int -> 'a c_obj_t
+val make_int32 : int -> 'a c_obj_t
+val make_int64 : int -> 'a c_obj_t
+
+val new_derived_object: 
+  ('a c_obj_t -> 'a c_obj_t) ->
+  ('a c_obj_t -> string -> 'a c_obj_t -> 'a c_obj_t) ->
+  'a c_obj_t -> 'a c_obj_t
+  
+val register_class_byname : string -> ('a c_obj_t -> 'a c_obj_t) -> unit
+val create_class : string -> 'a c_obj_t -> 'a c_obj_t
diff --git a/trunk/Lib/ocaml/swigp4.ml.in b/trunk/Lib/ocaml/swigp4.ml.in
new file mode 100644
index 0000000..0387c0a
--- /dev/null
+++ b/trunk/Lib/ocaml/swigp4.ml.in
@@ -0,0 +1,118 @@
+open Pcaml ;;
+
+let lap x y = x :: y
+let c_ify e @OCAMLLOC@ = 	  
+  match e with
+      <:expr< $int:_$ >> -> <:expr< (C_int $e$) >>
+    | <:expr< $str:_$ >> -> <:expr< (C_string $e$) >>
+    | <:expr< $chr:_$ >> -> <:expr< (C_char $e$) >>
+    | <:expr< $flo:_$ >> -> <:expr< (C_double $e$) >>
+    | <:expr< True    >> -> <:expr< (C_bool $e$) >>
+    | <:expr< False   >> -> <:expr< (C_bool $e$) >>
+    | _ -> <:expr< $e$ >>
+let mk_list args @OCAMLLOC@ f =
+  let rec mk_list_inner args @OCAMLLOC@ f =
+    match args with
+	[] -> <:expr< [] >>
+      | x :: xs ->
+	  (let @OCAMLLOC@ = MLast.loc_of_expr x in
+	     <:expr< [ ($f x @OCAMLLOC@$) ] @ ($mk_list_inner xs @OCAMLLOC@ f$) >>) in
+    match args with
+	[] -> <:expr< (Obj.magic C_void) >>
+      | [ a ] -> <:expr< (Obj.magic $f a @OCAMLLOC@$) >>
+      | _ -> <:expr< (Obj.magic (C_list ($mk_list_inner args @OCAMLLOC@ f$))) >>
+
+EXTEND
+  expr:
+  [ [ e1 = expr ; "'" ; "[" ; e2 = expr ; "]" ->
+	<:expr< (invoke $e1$) "[]" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "->" ; l = LIDENT ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke $e1$) $str:l$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "->" ; u = UIDENT ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke $e1$) $str:u$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "->" ; s = expr LEVEL "simple" ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke $e1$) $s$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "'" ; "." ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke $e1$) "()" ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "'" ; "->" ; l = LIDENT ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke ((invoke $e1$) "->" C_void)) $str:l$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "'" ; "->" ; u = UIDENT ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke ((invoke $e1$) "->" C_void)) $str:u$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "'" ; "->" ; s = expr LEVEL "simple" ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" ->
+	<:expr< (invoke ((invoke $e1$) "->" C_void)) $s$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    | e1 = expr ; "'" ; "++" ->
+	<:expr< (invoke $e1$) "++" C_void >>
+    | e1 = expr ; "'" ; "--" ->
+	<:expr< (invoke $e1$) "--" C_void >>
+    | e1 = expr ; "'" ; "-" ; e2 = expr ->
+	<:expr< (invoke $e1$) "-" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "+" ; e2 = expr -> <:expr< (invoke $e1$) "+" (C_list [ $c_ify e2 @OCAMLLOC@$ ])  >> 
+    | e1 = expr ; "'" ; "*" ; e2 = expr -> <:expr< (invoke $e1$) "*" (C_list [ $c_ify e2 @OCAMLLOC@$ ])  >> 
+    | "'" ; "&" ; e1 = expr -> 
+	<:expr< (invoke $e1$) "&" C_void >> 
+    | "'" ; "!" ; e1 = expr ->
+	<:expr< (invoke $e1$) "!" C_void >>
+    | "'" ; "~" ; e1 = expr ->
+	<:expr< (invoke $e1$) "~" C_void >>
+    | e1 = expr ; "'" ; "/" ; e2 = expr ->
+	<:expr< (invoke $e1$) "/" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "%" ; e2 = expr ->
+	<:expr< (invoke $e1$) "%" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "lsl" ; e2 = expr ->
+	<:expr< (invoke $e1$) ("<" ^ "<") (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "lsr" ; e2 = expr ->
+	<:expr< (invoke $e1$) (">" ^ ">") (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "<" ; e2 = expr ->
+	<:expr< (invoke $e1$) "<" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "<=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "<=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; ">" ; e2 = expr ->
+	<:expr< (invoke $e1$) ">" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; ">=" ; e2 = expr ->
+	<:expr< (invoke $e1$) ">=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "==" ; e2 = expr ->
+	<:expr< (invoke $e1$) "==" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "!=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "!=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "&" ; e2 = expr ->
+	<:expr< (invoke $e1$) "&" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "^" ; e2 = expr ->
+	<:expr< (invoke $e1$) "^" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "|" ; e2 = expr ->
+	<:expr< (invoke $e1$) "|" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "&&" ; e2 = expr ->
+	<:expr< (invoke $e1$) "&&" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "||" ; e2 = expr ->
+	<:expr< (invoke $e1$) "||" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "+=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "+=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "-=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "-=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "*=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "*=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "/=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "/=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "%=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "%=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "lsl" ; "=" ; e2 = expr ->
+	<:expr< (invoke $e1$) ("<" ^ "<=") (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "lsr" ; "=" ; e2 = expr ->
+	<:expr< (invoke $e1$) (">" ^ ">=") (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "&=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "&=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | e1 = expr ; "'" ; "^=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "^=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >> 
+    | e1 = expr ; "'" ; "|=" ; e2 = expr ->
+	<:expr< (invoke $e1$) "|=" (C_list [ $c_ify e2 @OCAMLLOC@$ ]) >>
+    | "'" ; e = expr -> c_ify e @OCAMLLOC@
+    | c = expr ; "as" ; id = LIDENT -> <:expr< $lid:"get_" ^ id$ $c$ >>
+    | c = expr ; "to" ; id = LIDENT -> <:expr< $uid:"C_" ^ id$ $c$ >>
+    | "`" ; "`" ; l = LIDENT -> <:expr< C_enum `$lid:l$ >>
+    | "`" ; "`" ; u = UIDENT -> <:expr< C_enum `$uid:u$ >>
+    | f = expr ; "'" ; "(" ; args = LIST0 (expr LEVEL "simple") SEP "," ; ")" -> 
+	<:expr< $f$ ($mk_list args @OCAMLLOC@ c_ify$) >>
+    ] ] ;
+END ;;
+      
diff --git a/trunk/Lib/ocaml/typecheck.i b/trunk/Lib/ocaml/typecheck.i
new file mode 100644
index 0000000..51e6606
--- /dev/null
+++ b/trunk/Lib/ocaml/typecheck.i
@@ -0,0 +1,179 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typecheck.i
+ *
+ * Typechecking rules
+ * ----------------------------------------------------------------------------- */
+
+%typecheck(SWIG_TYPECHECK_INTEGER) char, signed char, const char &, const signed char & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_char: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER) unsigned char, const unsigned char & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_uchar: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER) short, signed short, const short &, const signed short &, wchar_t {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_short: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER) unsigned short, const unsigned short & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_ushort: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+// XXX arty 
+// Will move enum SWIGTYPE later when I figure out what to do with it...
+
+%typecheck(SWIG_TYPECHECK_INTEGER) int, signed int, const int &, const signed int &, enum SWIGTYPE {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_int: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER) unsigned int, const unsigned int & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_uint: $1 = 1; break;
+      case C_int32: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER) long, signed long, unsigned long, long long, signed long long, unsigned long long, const long &, const signed long &, const unsigned long &, const long long &, const signed long long &, const unsigned long long & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_int64: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_INTEGER) bool, oc_bool, BOOL, const bool &, const oc_bool &, const BOOL & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_bool: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE) float, const float & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_float: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }  
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE) double, const double & {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_double: $1 = 1; break;
+      default: $1 = 0; break;
+      }
+  }  
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char * {
+  if( !Is_block($input) ) $1 = 0;
+  else {
+      switch( SWIG_Tag_val($input) ) {
+      case C_string: $1 = 1; break;
+      case C_ptr: {
+	swig_type_info *typeinfo = 
+	    (swig_type_info *)(long)SWIG_Int64_val(SWIG_Field($input,1));
+	$1 = SWIG_TypeCheck("char *",typeinfo) ||
+	     SWIG_TypeCheck("signed char *",typeinfo) ||
+	     SWIG_TypeCheck("unsigned char *",typeinfo) ||
+	     SWIG_TypeCheck("const char *",typeinfo) ||
+	     SWIG_TypeCheck("const signed char *",typeinfo) ||
+	     SWIG_TypeCheck("const unsigned char *",typeinfo) ||
+	     SWIG_TypeCheck("std::string",typeinfo);
+      } break;
+      default: $1 = 0; break;
+      }
+  }    
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  void *ptr;
+  $1 = !caml_ptr_val_internal($input, &ptr,$descriptor);
+}
+
+#if 0
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
+  void *ptr;
+  $1 = !caml_ptr_val_internal($input, &ptr, $&1_descriptor);
+}
+
+#endif
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  $1 = !caml_ptr_val_internal($input, &ptr, 0);
+}
+
+/* ------------------------------------------------------------
+ * Exception handling
+ * ------------------------------------------------------------ */
+
+%typemap(throws) int, 
+                  long, 
+                  short, 
+                  unsigned int, 
+                  unsigned long, 
+                  unsigned short {
+  SWIG_exception($1,"Thrown exception from C++ (int)");
+}
+
+%typemap(throws) SWIGTYPE CLASS {
+  $&1_ltype temp = new $1_ltype($1);
+  SWIG_exception((int)temp,"Thrown exception from C++ (object)");
+}
+
+%typemap(throws) SWIGTYPE {
+  (void)$1;
+  SWIG_exception(0,"Thrown exception from C++ (unknown)");
+}
+
+%typemap(throws) char * {
+  SWIG_exception(0,$1);
+}
diff --git a/trunk/Lib/ocaml/typemaps.i b/trunk/Lib/ocaml/typemaps.i
new file mode 100644
index 0000000..7f978bf
--- /dev/null
+++ b/trunk/Lib/ocaml/typemaps.i
@@ -0,0 +1,319 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * The Ocaml module handles all types uniformly via typemaps. Here
+ * are the definitions.
+ * ----------------------------------------------------------------------------- */
+
+/* Pointers */
+
+%typemap(in) void ""
+
+%typemap(out) void "$result = Val_int(0);"
+
+%typemap(in) void * {
+    $1 = caml_ptr_val($input,$descriptor);
+}
+
+%typemap(varin) void * {
+    $1 = ($ltype)caml_ptr_val($input,$descriptor);
+}
+
+%typemap(out) void * {
+    $result = caml_val_ptr($1,$descriptor);
+}
+
+%typemap(varout) void * {
+    $result = caml_val_ptr($1,$descriptor);
+}
+
+#ifdef __cplusplus
+
+%typemap(in) SWIGTYPE & {
+    /* %typemap(in) SWIGTYPE & */
+    $1 = ($ltype) caml_ptr_val($input,$1_descriptor);
+}
+
+%typemap(varin) SWIGTYPE & {
+    /* %typemap(varin) SWIGTYPE & */
+    $1 = *(($ltype) caml_ptr_val($input,$1_descriptor));
+}
+
+%typemap(out) SWIGTYPE & {
+    /* %typemap(out) SWIGTYPE & */
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    if( fromval ) {
+	$result = callback(*fromval,caml_val_ptr((void *) &$1,$1_descriptor));
+    } else {
+	$result = caml_val_ptr ((void *) &$1,$1_descriptor);
+    }
+}
+
+#if 0
+%typemap(argout) SWIGTYPE & {
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    if( fromval ) {
+	swig_result =
+	    caml_list_append(swig_result,
+			     callback(*fromval,caml_val_ptr((void *) $1,
+							    $1_descriptor)));
+    } else {
+	swig_result =
+	    caml_list_append(swig_result,
+			     caml_val_ptr ((void *) $1,$1_descriptor));
+    }
+}
+#endif
+
+%typemap(argout) const SWIGTYPE & { }
+
+%typemap(in) SWIGTYPE {
+    $1 = *(($&1_ltype) caml_ptr_val($input,$&1_descriptor)) ;
+}
+
+%typemap(out) SWIGTYPE {
+    /* %typemap(out) SWIGTYPE */
+    $&1_ltype temp = new $ltype((const $1_ltype &) $1);
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    if( fromval ) {
+	$result = callback(*fromval,caml_val_ptr((void *)temp,$&1_descriptor));
+    } else {
+	$result = caml_val_ptr ((void *)temp,$&1_descriptor);
+    }
+}
+
+#else
+
+%typemap(in) SWIGTYPE {
+    $1 = *(($&1_ltype) caml_ptr_val($input,$&1_descriptor)) ;
+}
+
+%typemap(out) SWIGTYPE {
+    /* %typemap(out) SWIGTYPE */
+    void *temp = calloc(1,sizeof($ltype));
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    memmove( temp, &$1, sizeof( $1_type ) );
+    if( fromval ) {
+	$result = callback(*fromval,caml_val_ptr((void *)temp,$&1_descriptor));
+    } else {
+	$result = caml_val_ptr ((void *)temp,$&1_descriptor);
+    }
+}
+
+%apply SWIGTYPE { const SWIGTYPE & };
+
+#endif
+
+/* The SIMPLE_MAP macro below defines the whole set of typemaps needed
+   for simple types. */
+
+%define SIMPLE_MAP(C_NAME, C_TO_MZ, MZ_TO_C)
+/* In */
+%typemap(in) C_NAME {
+    $1 = MZ_TO_C($input);
+}
+%typemap(varin) C_NAME {
+    $1 = MZ_TO_C($input);
+}
+%typemap(in) C_NAME & ($*1_ltype temp) {
+    temp = ($*1_ltype) MZ_TO_C($input);
+    $1 = &temp;
+}
+%typemap(varin) C_NAME & {
+    $1 = MZ_TO_C($input);
+}
+%typemap(directorout) C_NAME {
+    $1 = MZ_TO_C($input);
+}
+%typemap(in) C_NAME *INPUT ($*1_ltype temp) {
+    temp = ($*1_ltype) MZ_TO_C($input);
+    $1 = &temp;
+}
+%typemap(in,numinputs=0) C_NAME *OUTPUT ($*1_ltype temp) {
+    $1 = &temp;
+}
+/* Out */
+%typemap(out) C_NAME {
+    $result = C_TO_MZ($1);
+}
+%typemap(varout) C_NAME {
+    $result = C_TO_MZ($1);
+}
+%typemap(varout) C_NAME & {
+    /* %typemap(varout) C_NAME & (generic) */
+    $result = C_TO_MZ($1);
+}
+%typemap(argout) C_NAME *OUTPUT {
+    swig_result = caml_list_append(swig_result,C_TO_MZ((long)*$1));
+}
+%typemap(out) C_NAME & {
+    /* %typemap(out) C_NAME & (generic) */
+    $result = C_TO_MZ(*$1);
+}
+%typemap(argout) C_NAME & {
+    swig_result = caml_list_append(swig_result,C_TO_MZ((long)*$1));
+}
+%typemap(directorin) C_NAME {
+    args = caml_list_append(args,C_TO_MZ($1_name));
+}
+%enddef
+
+SIMPLE_MAP(bool, caml_val_bool, caml_long_val);
+SIMPLE_MAP(oc_bool, caml_val_bool, caml_long_val);
+SIMPLE_MAP(char, caml_val_char, caml_long_val);
+SIMPLE_MAP(signed char, caml_val_char, caml_long_val);
+SIMPLE_MAP(unsigned char, caml_val_uchar, caml_long_val);
+SIMPLE_MAP(int, caml_val_int, caml_long_val);
+SIMPLE_MAP(short, caml_val_short, caml_long_val);
+SIMPLE_MAP(wchar_t, caml_val_short, caml_long_val);
+SIMPLE_MAP(long, caml_val_long, caml_long_val);
+SIMPLE_MAP(ptrdiff_t, caml_val_int, caml_long_val);
+SIMPLE_MAP(unsigned int, caml_val_uint, caml_long_val);
+SIMPLE_MAP(unsigned short, caml_val_ushort, caml_long_val);
+SIMPLE_MAP(unsigned long, caml_val_ulong, caml_long_val);
+SIMPLE_MAP(size_t, caml_val_int, caml_long_val);
+SIMPLE_MAP(float, caml_val_float, caml_double_val);
+SIMPLE_MAP(double, caml_val_double, caml_double_val);
+SIMPLE_MAP(long long,caml_val_ulong,caml_long_val);
+SIMPLE_MAP(unsigned long long,caml_val_ulong,caml_long_val);
+
+/* Void */
+
+%typemap(out) void "$result = Val_unit;";
+
+/* Pass through value */
+
+%typemap (in) value,caml::value,CAML_VALUE "$1=$input;";
+%typemap (out) value,caml::value,CAML_VALUE "$result=$1;";
+
+/* Arrays */
+
+%typemap(in) ArrayCarrier * {
+    $1 = ($ltype)caml_ptr_val($input,$1_descriptor);
+}
+
+%typemap(out) ArrayCarrier * {
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    if( fromval ) {
+	$result = callback(*fromval,caml_val_ptr((void *)$1,$1_descriptor));
+    } else {
+	$result = caml_val_ptr ((void *)$1,$1_descriptor);
+    }
+}
+
+#if 0
+%include <carray.i>
+#endif
+
+/* Handle char arrays as strings */
+
+%define %char_ptr_in(how)
+%typemap(how)  char *, signed char *, unsigned char * {
+    /* %typemap(how) char * ... */
+    $1 = ($ltype)caml_string_val($input);
+}
+/* Again work around the empty array bound bug */
+%typemap(how) char [ANY], signed char [ANY], unsigned char [ANY] {
+    /* %typemap(how) char [ANY] ... */
+    char *temp = caml_string_val($input);
+    strcpy((char *)$1,temp); 
+    /* strncpy would be better but we might not have an array size */
+}
+%enddef
+
+%char_ptr_in(in);
+%char_ptr_in(varin);
+%char_ptr_in(directorout);
+
+%define %char_ptr_out(how) 
+%typemap(how) 
+    char *, signed char *, unsigned char *, 
+    const char *, const signed char *, const unsigned char * {
+    $result = caml_val_string((char *)$1);
+}
+/* I'd like to use the length here but can't because it might be empty */
+%typemap(how)
+    char [ANY], signed char [ANY], unsigned char [ANY],
+    const char [ANY], const signed char [ANY], const unsigned char [ANY] {
+    $result = caml_val_string((char *)$1);
+}
+%enddef
+
+%char_ptr_out(out);
+%char_ptr_out(varout);
+%char_ptr_out(directorin);
+
+%define %swigtype_ptr_in(how)
+%typemap(how) SWIGTYPE * {
+    /* %typemap(how) SWIGTYPE * */
+    $1 = ($ltype)caml_ptr_val($input,$1_descriptor);
+}
+%typemap(how) SWIGTYPE (CLASS::*) {
+    /* %typemap(how) SWIGTYPE (CLASS::*) */
+    void *v = caml_ptr_val($input,$1_descriptor);
+    memcpy(& $1, &v, sizeof(v));
+}
+%enddef
+
+%define %swigtype_ptr_out(how)
+%typemap(out) SWIGTYPE * {
+    /* %typemap(how) SWIGTYPE *, SWIGTYPE (CLASS::*) */
+    CAML_VALUE *fromval = caml_named_value("create_$ntype_from_ptr");
+    if( fromval ) {
+	$result = callback(*fromval,caml_val_ptr((void *)$1,$1_descriptor));
+    } else {
+	$result = caml_val_ptr ((void *)$1,$1_descriptor);
+    }
+}
+%typemap(how) SWIGTYPE (CLASS::*) {
+    /* %typemap(how) SWIGTYPE *, SWIGTYPE (CLASS::*) */
+    void *v;
+    memcpy(&v,& $1, sizeof(void *));
+    $result = caml_val_ptr (v,$1_descriptor);
+}
+%enddef
+
+%swigtype_ptr_in(in);
+%swigtype_ptr_in(varin);
+%swigtype_ptr_in(directorout);
+%swigtype_ptr_out(out);
+%swigtype_ptr_out(varout);
+%swigtype_ptr_out(directorin);
+
+%define %swigtype_array_fail(how,msg)
+%typemap(how) SWIGTYPE [] {
+    failwith(msg);
+}
+%enddef
+
+%swigtype_array_fail(in,"Array arguments for arbitrary types need a typemap");
+%swigtype_array_fail(varin,"Assignment to global arrays for arbitrary types need a typemap");
+%swigtype_array_fail(out,"Array arguments for arbitrary types need a typemap");
+%swigtype_array_fail(varout,"Array variables need a typemap");
+%swigtype_array_fail(directorin,"Array results with arbitrary types need a typemap");
+%swigtype_array_fail(directorout,"Array arguments with arbitrary types need a typemap");
+
+/* C++ References */
+
+/* Enums */
+%define %swig_enum_in(how)
+%typemap(how) enum SWIGTYPE {
+    $1 = ($type)caml_long_val_full($input,"$type_marker");
+}
+%enddef
+
+%define %swig_enum_out(how)
+%typemap(how) enum SWIGTYPE {
+    $result = callback2(*caml_named_value(SWIG_MODULE "_int_to_enum"),*caml_named_value("$type_marker"),Val_int((int)$1));
+}
+%enddef
+
+%swig_enum_in(in)
+%swig_enum_in(varin)
+%swig_enum_in(directorout)
+%swig_enum_out(out)
+%swig_enum_out(varout)
+%swig_enum_out(directorin)
diff --git a/trunk/Lib/ocaml/typeregister.swg b/trunk/Lib/ocaml/typeregister.swg
new file mode 100644
index 0000000..c3ba904
--- /dev/null
+++ b/trunk/Lib/ocaml/typeregister.swg
@@ -0,0 +1,2 @@
+SWIGEXT void SWIG_init() {
+  SWIG_InitializeModule(0);
diff --git a/trunk/Lib/octave/attribute.i b/trunk/Lib/octave/attribute.i
new file mode 100644
index 0000000..779716c
--- /dev/null
+++ b/trunk/Lib/octave/attribute.i
@@ -0,0 +1 @@
+%include <typemaps/attribute.swg>
diff --git a/trunk/Lib/octave/boost_shared_ptr.i b/trunk/Lib/octave/boost_shared_ptr.i
new file mode 100644
index 0000000..7ae4dda
--- /dev/null
+++ b/trunk/Lib/octave/boost_shared_ptr.i
@@ -0,0 +1,305 @@
+%include <shared_ptr.i>
+
+%define SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, CONST, TYPE...)
+
+%naturalvar TYPE;
+%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+
+// destructor mods
+%feature("unref") TYPE 
+//"if (debug_shared) { cout << \"deleting use_count: \" << (*smartarg1).use_count() << \" [\" << (boost::get_deleter<SWIG_null_deleter>(*smartarg1) ? std::string(\"CANNOT BE DETERMINED SAFELY\") : ( (*smartarg1).get() ? (*smartarg1)->getValue() : std::string(\"NULL PTR\") )) << \"]\" << endl << flush; }\n"
+                               "(void)arg1; delete smartarg1;"
+
+%feature("smartptr", noblock=1) TYPE { SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > }
+
+// plain value
+%typemap(in) CONST TYPE (void *argp, int res = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) {
+    %argument_nullref("$type", $symname, $argnum);
+  } else {
+    $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get());
+    if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+  }
+}
+%typemap(out) CONST TYPE {
+  %set_output(SWIG_NewPointerObj(new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE {
+  void *argp = 0;
+  int newmem = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  if (!argp) {
+    %argument_nullref("$type", $symname, $argnum);
+  } else {
+    $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get());
+    if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+  }
+}
+%typemap(varout) CONST TYPE {
+  %set_varoutput(SWIG_NewPointerObj(new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1)), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// plain pointer
+// Note: $disown not implemented as it will lead to a memory leak of the shared_ptr instance
+%typemap(in) CONST TYPE * (void  *argp = 0, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast(tempshared.get(), $1_ltype);
+  } else {
+    smartarg = %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast((smartarg ? smartarg->get() : 0), $1_ltype);
+  }
+}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE * {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), $owner | SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE * {
+  void *argp = 0;
+  int newmem = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared;
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0;
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast(tempshared.get(), $1_ltype);
+  } else {
+    smartarg = %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast((smartarg ? smartarg->get() : 0), $1_ltype);
+  }
+}
+%typemap(varout, fragment="SWIG_null_deleter") CONST TYPE * {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0;
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// plain reference
+%typemap(in) CONST TYPE & (void  *argp = 0, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast(tempshared.get(), $1_ltype);
+  } else {
+    $1 = %const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $1_ltype);
+  }
+}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE & {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner);
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE & {
+  void *argp = 0;
+  int newmem = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared;
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = *%const_cast(tempshared.get(), $1_ltype);
+  } else {
+    $1 = *%const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $1_ltype);
+  }
+}
+%typemap(varout, fragment="SWIG_null_deleter") CONST TYPE & {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(&$1 SWIG_NO_NULL_DELETER_0);
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// plain pointer by reference
+// Note: $disown not implemented as it will lead to a memory leak of the shared_ptr instance
+%typemap(in) CONST TYPE *& (void  *argp = 0, int res = 0, $*1_ltype temp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    temp = %const_cast(tempshared.get(), $*1_ltype);
+  } else {
+    temp = %const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $*1_ltype);
+  }
+  $1 = &temp;
+}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE *& {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner);
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE *& %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) CONST TYPE *& %{
+#error "varout typemap not implemented"
+%}
+
+// shared_ptr by value
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > (void *argp, int res = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (argp) $1 = *(%reinterpret_cast(argp, $&ltype));
+  if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $&ltype);
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+  int newmem = 0;
+  void *argp = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  $1 = argp ? *(%reinterpret_cast(argp, $&ltype)) : SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE >();
+  if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $&ltype);
+}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1) : 0;
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// shared_ptr by reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & (void *argp, int res = 0, $*1_ltype tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    if (argp) tempshared = *%reinterpret_cast(argp, $ltype);
+    delete %reinterpret_cast(argp, $ltype);
+    $1 = &tempshared;
+  } else {
+    $1 = (argp) ? %reinterpret_cast(argp, $ltype) : &tempshared;
+  }
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = *$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{
+#error "varout typemap not implemented"
+%}
+
+// shared_ptr by pointer
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * (void *argp, int res = 0, $*1_ltype tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    if (argp) tempshared = *%reinterpret_cast(argp, $ltype);
+    delete %reinterpret_cast(argp, $ltype);
+    $1 = &tempshared;
+  } else {
+    $1 = (argp) ? %reinterpret_cast(argp, $ltype) : &tempshared;
+  }
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 && *$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+  if ($owner) delete $1;
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{
+#error "varout typemap not implemented"
+%}
+
+// shared_ptr by pointer reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& (void *argp, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared, $*1_ltype temp = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (argp) tempshared = *%reinterpret_cast(argp, $*ltype);
+  if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $*ltype);
+  temp = &tempshared;
+  $1 = &temp;
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = *$1 && **$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(**$1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& %{
+#error "varout typemap not implemented"
+%}
+
+// Typecheck typemaps
+// Note: SWIG_ConvertPtr with void ** parameter set to 0 instead of using SWIG_ConvertPtrAndOwn, so that the casting 
+// function is not called thereby avoiding a possible smart pointer copy constructor call when casting up the inheritance chain.
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) 
+                      CONST TYPE,
+                      CONST TYPE &,
+                      CONST TYPE *,
+                      CONST TYPE *&,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& {
+  int res = SWIG_ConvertPtr($input, 0, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), 0);
+  $1 = SWIG_CheckState(res);
+}
+
+
+// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug
+%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+
+
+%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+%enddef
+
diff --git a/trunk/Lib/octave/carrays.i b/trunk/Lib/octave/carrays.i
new file mode 100644
index 0000000..454762a
--- /dev/null
+++ b/trunk/Lib/octave/carrays.i
@@ -0,0 +1,5 @@
+%define %array_class(TYPE,NAME)
+  %array_class_wrap(TYPE,NAME,__paren,__paren_asgn)
+%enddef
+
+%include <typemaps/carrays.swg>
diff --git a/trunk/Lib/octave/cdata.i b/trunk/Lib/octave/cdata.i
new file mode 100644
index 0000000..3679659
--- /dev/null
+++ b/trunk/Lib/octave/cdata.i
@@ -0,0 +1 @@
+%include <typemaps/cdata.swg>
diff --git a/trunk/Lib/octave/cmalloc.i b/trunk/Lib/octave/cmalloc.i
new file mode 100644
index 0000000..248f06b
--- /dev/null
+++ b/trunk/Lib/octave/cmalloc.i
@@ -0,0 +1 @@
+%include <typemaps/cmalloc.swg>
diff --git a/trunk/Lib/octave/director.swg b/trunk/Lib/octave/director.swg
new file mode 100644
index 0000000..0d7e6c1
--- /dev/null
+++ b/trunk/Lib/octave/director.swg
@@ -0,0 +1,3 @@
+
+// ***** move the director stuff from octrun.swg here...
+
diff --git a/trunk/Lib/octave/exception.i b/trunk/Lib/octave/exception.i
new file mode 100644
index 0000000..bb0b15c
--- /dev/null
+++ b/trunk/Lib/octave/exception.i
@@ -0,0 +1,6 @@
+%include <typemaps/exception.swg>
+
+
+%insert("runtime") {
+  %define_as(SWIG_exception(code, msg), %block(%error(code, msg); SWIG_fail; ))
+}
diff --git a/trunk/Lib/octave/factory.i b/trunk/Lib/octave/factory.i
new file mode 100644
index 0000000..46a0a87
--- /dev/null
+++ b/trunk/Lib/octave/factory.i
@@ -0,0 +1 @@
+%include <typemaps/factory.swg>
diff --git a/trunk/Lib/octave/implicit.i b/trunk/Lib/octave/implicit.i
new file mode 100644
index 0000000..152c2b0
--- /dev/null
+++ b/trunk/Lib/octave/implicit.i
@@ -0,0 +1,7 @@
+%include <std_common.i>
+%include <typemaps/implicit.swg>
+
+#warning "This file provides the %implicit directive, which is an old and fragile"
+#warning "way to implement the C++ implicit conversion mechanism."
+#warning "Try using the more robust '%implicitconv Type;' directive instead."
+
diff --git a/trunk/Lib/octave/octave.swg b/trunk/Lib/octave/octave.swg
new file mode 100644
index 0000000..872054d
--- /dev/null
+++ b/trunk/Lib/octave/octave.swg
@@ -0,0 +1,8 @@
+%include <typemaps/swigmacros.swg>
+%include <typemaps/fragments.swg>
+%include <octruntime.swg>
+%include <octuserdir.swg>
+%include <octtypemaps.swg>
+%include <octopers.swg>
+
+%define %docstring %feature("docstring") %enddef
diff --git a/trunk/Lib/octave/octcomplex.swg b/trunk/Lib/octave/octcomplex.swg
new file mode 100644
index 0000000..7eb373a
--- /dev/null
+++ b/trunk/Lib/octave/octcomplex.swg
@@ -0,0 +1,95 @@
+/*
+  Defines the As/From conversors for double/float complex, you need to
+  provide complex Type, the Name you want to use in the conversors,
+  the complex Constructor method, and the Real and Imag complex
+  accesor methods.
+
+  See the std_complex.i and ccomplex.i for concret examples.
+*/
+
+/* the common from conversor */
+%define %swig_fromcplx_conv(Type, Real, Imag)
+     %fragment(SWIG_From_frag(Type),"header")
+{
+  SWIGINTERNINLINE octave_value
+    SWIG_From(Type)(%ifcplusplus(const Type&, Type) c)
+    {
+      return octave_value(Complex(Real(c), Imag(c)));
+    }
+}
+%enddef
+
+// the double case
+%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag)
+     %fragment(SWIG_AsVal_frag(Type),"header",
+	       fragment=SWIG_AsVal_frag(double))
+{
+  SWIGINTERN int
+    SWIG_AsVal(Type) (const octave_value& ov, Type* val)
+    {
+      if (ov.is_complex_scalar()) {
+	if (val) {
+	  Complex c(ov.complex_value());
+	  *val=Constructor(c.real(),c.imag());
+	}
+	return SWIG_OK;
+      } else {
+	double d;    
+	int res = SWIG_AddCast(SWIG_AsVal(double)(ov, &d));
+	if (SWIG_IsOK(res)) {
+	  if (val)
+	    *val = Constructor(d, 0.0);
+	  return res;
+	}
+      }
+      return SWIG_TypeError;
+    }
+}
+%swig_fromcplx_conv(Type, Real, Imag);
+%enddef
+
+// the float case
+%define %swig_cplxflt_conv(Type, Constructor, Real, Imag)
+     %fragment(SWIG_AsVal_frag(Type),"header",
+	       fragment=SWIG_AsVal_frag(float)) {
+  SWIGINTERN int
+    SWIG_AsVal(Type)(PyObject *o, Type *val)
+    {
+      if (ov.is_complex_scalar()) {
+	if (val) {
+	  Complex c(ov.complex_value());
+	  double re = c.real();
+	  double im = c.imag();
+	  if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) {
+	    if (val)
+	      *val = Constructor(%numeric_cast(re, float),
+				 %numeric_cast(im, float));
+	    return SWIG_OK;
+	  } else
+	    return SWIG_OverflowError;
+	}
+      } else {
+	float d;    
+	int res = SWIG_AddCast(SWIG_AsVal(float)(ov, &d));
+	if (SWIG_IsOK(res)) {
+	  if (val)
+	    *val = Constructor(d, 0.0);
+	  return res;
+	}
+      }
+      return SWIG_TypeError;
+    }
+}
+
+%swig_fromcplx_conv(Type, Real, Imag);
+%enddef
+
+#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \
+%swig_cplxflt_conv(Type, Constructor, Real, Imag)
+
+
+#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \
+%swig_cplxdbl_conv(Type, Constructor, Real, Imag)
+
+
+     
diff --git a/trunk/Lib/octave/octcontainer.swg b/trunk/Lib/octave/octcontainer.swg
new file mode 100644
index 0000000..bb1122a
--- /dev/null
+++ b/trunk/Lib/octave/octcontainer.swg
@@ -0,0 +1,628 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * octcontainer.swg
+ *
+ * Octave cell <-> C++ container wrapper
+ *
+ * This wrapper, and its iterator, allows a general use (and reuse) of
+ * the the mapping between C++ and Octave, thanks to the C++
+ * templates.
+ *
+ * Of course, it needs the C++ compiler to support templates, but
+ * since we will use this wrapper with the STL containers, that should
+ * be the case.
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <iostream>
+%}
+
+
+#if !defined(SWIG_NO_EXPORT_ITERATOR_METHODS)
+# if !defined(SWIG_EXPORT_ITERATOR_METHODS)
+#  define SWIG_EXPORT_ITERATOR_METHODS SWIG_EXPORT_ITERATOR_METHODS
+# endif
+#endif
+
+%include <octiterators.swg>
+
+// The Octave C++ Wrap
+
+%insert(header) %{
+#include <stdexcept>
+%}
+
+%include <std_except.i>
+
+%fragment(SWIG_Traits_frag(octave_value),"header",fragment="StdTraits") {
+namespace swig {
+  template <>  struct traits<octave_value > {
+    typedef value_category category;
+    static const char* type_name() { return  "octave_value"; }
+  };
+  
+  template <>  struct traits_from<octave_value> {
+    typedef octave_value value_type;
+    static octave_value from(const value_type& val) {
+      return val;
+    }
+  };
+  
+  template <> 
+  struct traits_check<octave_value, value_category> {
+    static bool check(const octave_value&) {
+      return true;
+    }
+  };
+  
+  template <>  struct traits_asval<octave_value > {   
+    typedef octave_value value_type;
+    static int asval(const octave_value& obj, value_type *val) {
+      if (val) *val = obj;
+      return SWIG_OK;
+    }
+  };
+}
+}
+
+%fragment("OctSequence_Base","header")
+{
+%#include <functional>
+
+namespace std {
+  template <>
+  struct less <octave_value>: public binary_function<octave_value, octave_value, bool>
+  {
+    bool
+    operator()(const octave_value& v, const octave_value& w) const
+    { 
+      octave_value res = do_binary_op(octave_value::op_le,v,w);
+      return res.is_true();
+    }
+  };
+}
+
+namespace swig {
+  inline size_t
+  check_index(ptrdiff_t i, size_t size, bool insert = false) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size)
+	return (size_t) (i + size);
+    } else if ( (size_t) i < size ) {
+      return (size_t) i;
+    } else if (insert && ((size_t) i == size)) {
+      return size;
+    }
+    
+    throw std::out_of_range("index out of range");
+  }
+
+  inline size_t
+  slice_index(ptrdiff_t i, size_t size) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size) {
+	return (size_t) (i + size);
+      } else {
+	throw std::out_of_range("index out of range");
+      }
+    } else {
+      return ( (size_t) i < size ) ? ((size_t) i) : size;
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::iterator
+  getpos(Sequence* self, Difference i)  {
+    typename Sequence::iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::const_iterator
+  cgetpos(const Sequence* self, Difference i)  {
+    typename Sequence::const_iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline Sequence*
+  getslice(const Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+
+    if (jj > ii) {
+      typename Sequence::const_iterator vb = self->begin();
+      typename Sequence::const_iterator ve = self->begin();
+      std::advance(vb,ii);
+      std::advance(ve,jj);
+      return new Sequence(vb, ve);
+    } else {
+      return new Sequence();
+    }
+  }
+
+  template <class Sequence, class Difference, class InputSeq>
+  inline void
+  setslice(Sequence* self, Difference i, Difference j, const InputSeq& v) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj < ii) jj = ii;
+    size_t ssize = jj - ii;
+    if (ssize <= v.size()) {
+      typename Sequence::iterator sb = self->begin();
+      typename InputSeq::const_iterator vmid = v.begin();
+      std::advance(sb,ii);
+      std::advance(vmid, jj - ii);
+      self->insert(std::copy(v.begin(), vmid, sb), vmid, v.end());
+    } else {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+      self->insert(sb, v.begin(), v.end());
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline void
+  delslice(Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj > ii) {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+    }
+  }
+}
+}
+
+%fragment("OctSequence_Cont","header",
+	  fragment="StdTraits",
+	  fragment="OctSequence_Base",
+	  fragment="OctSwigIterator_T")
+{
+namespace swig
+{
+  template <class T>
+    struct OctSequence_Ref // * octave can't support these, because of how assignment works
+  {
+    OctSequence_Ref(const octave_value& seq, int index)
+      : _seq(seq), _index(index)
+    {
+    }
+    
+    operator T () const
+    {
+      //      swig::PyObject_var item = OctSequence_GetItem(_seq, _index);
+      octave_value item; // * todo
+      try {
+	return swig::as<T>(item, true);
+      } catch (std::exception& e) {
+	char msg[1024];
+	sprintf(msg, "in sequence element %d ", _index);
+	if (!Octave_Error_Occurred()) {
+	  %type_error(swig::type_name<T>());
+	}
+	SWIG_Octave_AddErrorMsg(msg);
+	SWIG_Octave_AddErrorMsg(e.what());
+	throw;
+      }
+    }
+
+    OctSequence_Ref& operator=(const T& v)
+    {
+      //      OctSequence_SetItem(_seq, _index, swig::from<T>(v));
+      // * todo
+      return *this;
+    }
+
+  private:
+    octave_value _seq;
+    int _index;
+  };
+
+  template <class T>
+  struct OctSequence_ArrowProxy
+  {
+    OctSequence_ArrowProxy(const T& x): m_value(x) {}
+    const T* operator->() const { return &m_value; }
+    operator const T*() const { return &m_value; }
+    T m_value;
+  };
+
+  template <class T, class Reference >
+  struct OctSequence_InputIterator
+  {
+    typedef OctSequence_InputIterator<T, Reference > self;
+
+    typedef std::random_access_iterator_tag iterator_category;
+    typedef Reference reference;
+    typedef T value_type;
+    typedef T* pointer;
+    typedef int difference_type;
+
+    OctSequence_InputIterator()
+    {
+    }
+
+    OctSequence_InputIterator(const octave_value& seq, int index)
+      : _seq(seq), _index(index)
+    {
+    }
+
+    reference operator*() const
+    {
+      return reference(_seq, _index);
+    }
+
+    OctSequence_ArrowProxy<T>
+    operator->() const {
+      return OctSequence_ArrowProxy<T>(operator*());
+    }
+
+    bool operator==(const self& ri) const
+    {
+      return (_index == ri._index);
+    }
+
+    bool operator!=(const self& ri) const
+    {
+      return !(operator==(ri));
+    }
+
+    self& operator ++ ()
+    {
+      ++_index;
+      return *this;
+    }
+
+    self& operator -- ()
+    {
+      --_index;
+      return *this;
+    }
+
+    self& operator += (difference_type n)
+    {
+      _index += n;
+      return *this;
+    }
+
+    self operator +(difference_type n) const
+    {
+      return self(_seq, _index + n);
+    }
+
+    self& operator -= (difference_type n)
+    {
+      _index -= n;
+      return *this;
+    }
+
+    self operator -(difference_type n) const
+    {
+      return self(_seq, _index - n);
+    }
+
+    difference_type operator - (const self& ri) const
+    {
+      return _index - ri._index;
+    }
+
+    bool operator < (const self& ri) const
+    {
+      return _index < ri._index;
+    }
+
+    reference
+    operator[](difference_type n) const
+    {
+      return reference(_seq, _index + n);
+    }
+
+  private:
+    octave_value _seq;
+    difference_type _index;
+  };
+
+  template <class T>
+  struct OctSequence_Cont
+  {
+    typedef OctSequence_Ref<T> reference;
+    typedef const OctSequence_Ref<T> const_reference;
+    typedef T value_type;
+    typedef T* pointer;
+    typedef int difference_type;
+    typedef int size_type;
+    typedef const pointer const_pointer;
+    typedef OctSequence_InputIterator<T, reference> iterator;
+    typedef OctSequence_InputIterator<T, const_reference> const_iterator;
+
+    OctSequence_Cont(const octave_value& seq) : _seq(seq)
+    {
+      // * assert that we have map type etc.
+      /*
+      if (!OctSequence_Check(seq)) {
+	throw std::invalid_argument("a sequence is expected");
+      }
+      _seq = seq;
+      Py_INCREF(_seq);
+      */
+    }
+
+    ~OctSequence_Cont()
+    {
+    }
+
+    size_type size() const
+    {
+      //      return static_cast<size_type>(OctSequence_Size(_seq));
+      return 0; // * todo
+    }
+
+    bool empty() const
+    {
+      return size() == 0;
+    }
+
+    iterator begin()
+    {
+      return iterator(_seq, 0);
+    }
+
+    const_iterator begin() const
+    {
+      return const_iterator(_seq, 0);
+    }
+
+    iterator end()
+    {
+      return iterator(_seq, size());
+    }
+
+    const_iterator end() const
+    {
+      return const_iterator(_seq, size());
+    }
+
+    reference operator[](difference_type n)
+    {
+      return reference(_seq, n);
+    }
+
+    const_reference operator[](difference_type n)  const
+    {
+      return const_reference(_seq, n);
+    }
+
+    bool check(bool set_err = true) const
+    {
+      int s = size();
+      for (int i = 0; i < s; ++i) {
+	//	swig::PyObject_var item = OctSequence_GetItem(_seq, i);
+	octave_value item; // * todo
+	if (!swig::check<value_type>(item)) {
+	  if (set_err) {
+	    char msg[1024];
+	    sprintf(msg, "in sequence element %d", i);
+	    SWIG_Error(SWIG_RuntimeError, msg);
+	  }
+	  return false;
+	}
+      }
+      return true;
+    }
+
+  private:
+    octave_value _seq;
+  };
+
+}
+}
+
+%define %swig_sequence_iterator(Sequence...)
+#if defined(SWIG_EXPORT_ITERATOR_METHODS)
+  class iterator;
+  class reverse_iterator;
+  class const_iterator;
+  class const_reverse_iterator;
+
+  %typemap(out,noblock=1,fragment="OctSequence_Cont")
+    iterator, reverse_iterator, const_iterator, const_reverse_iterator {
+    $result = SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &)),
+				 swig::OctSwigIterator::descriptor(),SWIG_POINTER_OWN);
+  }
+  %typemap(out,fragment="OctSequence_Cont")
+    std::pair<iterator, iterator>, std::pair<const_iterator, const_iterator> {
+    octave_value_list tmpc;
+    tmpc.append(SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).first),
+				   swig::OctSwigIterator::descriptor(),SWIG_POINTER_OWN));
+    tmpc.append(SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).second),
+				   swig::OctSwigIterator::descriptor(),SWIG_POINTER_OWN));
+    $result = Cell(tmpc);
+  }
+
+  %fragment("PyPairBoolOutputIterator","header",fragment=SWIG_From_frag(bool),fragment="OctSequence_Cont") {}
+
+  %typemap(out,fragment="OctPairBoolOutputIterator")
+    std::pair<iterator, bool>, std::pair<const_iterator, bool> {
+    octave_value_list tmpc;
+    tmpc.append(SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).first),
+				   swig::OctSwigIterator::descriptor(),SWIG_POINTER_OWN));
+    tmpc.append(SWIG_From(bool)(%static_cast($1,const $type &).second));
+    $result = Cell(tmpc);
+  }
+
+  %typemap(in,noblock=1,fragment="OctSequence_Cont")
+    iterator(swig::OctSwigIterator *iter = 0, int res),
+    reverse_iterator(swig::OctSwigIterator *iter = 0, int res),
+    const_iterator(swig::OctSwigIterator *iter = 0, int res),
+    const_reverse_iterator(swig::OctSwigIterator *iter = 0, int res) {
+    res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::OctSwigIterator::descriptor(), 0);
+    if (!SWIG_IsOK(res) || !iter) {
+      %argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+    } else {
+      swig::OctSwigIterator_T<$type > *iter_t = dynamic_cast<swig::OctSwigIterator_T<$type > *>(iter);
+      if (iter_t) {
+	$1 = iter_t->get_current();
+      } else {
+	%argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+      }
+    }
+  }
+
+  %typecheck(%checkcode(ITERATOR),noblock=1,fragment="OctSequence_Cont")
+    iterator, reverse_iterator, const_iterator, const_reverse_iterator {
+    swig::OctSwigIterator *iter = 0;
+    int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::OctSwigIterator::descriptor(), 0);
+    $1 = (SWIG_IsOK(res) && iter && (dynamic_cast<swig::OctSwigIterator_T<$type > *>(iter) != 0));
+  }
+
+  %fragment("OctSequence_Cont");
+#endif //SWIG_EXPORT_ITERATOR_METHODS
+%enddef
+
+// The octave container methods
+
+%define %swig_container_methods(Container...)
+%enddef
+
+%define %swig_sequence_methods_common(Sequence...)
+  %swig_sequence_iterator(%arg(Sequence))
+  %swig_container_methods(%arg(Sequence))
+  
+  %fragment("OctSequence_Base");
+
+  %extend {
+    value_type pop() throw (std::out_of_range) {
+      if (self->size() == 0)
+	throw std::out_of_range("pop from empty container");
+      Sequence::value_type x = self->back();
+      self->pop_back();
+      return x;
+    }
+
+    value_type __paren(difference_type i) throw (std::out_of_range) {
+      return *(swig::cgetpos(self, i));
+    }
+
+    void __paren_asgn(difference_type i, value_type x) throw (std::out_of_range) {
+      *(swig::getpos(self,i)) = x;
+    }
+
+    void append(value_type x) {
+      self->push_back(x);
+    }
+  }
+
+%enddef
+
+%define %swig_sequence_methods(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+%enddef
+
+%define %swig_sequence_methods_val(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+%enddef
+
+//
+// Common fragments
+//
+
+%fragment("StdSequenceTraits","header",
+	  fragment="StdTraits",
+	  fragment="OctSequence_Cont")
+{
+namespace swig {
+  template <class OctSeq, class Seq>
+  inline void
+  assign(const OctSeq& octseq, Seq* seq) {
+%#ifdef SWIG_STD_NOASSIGN_STL
+    typedef typename OctSeq::value_type value_type;
+    typename OctSeq::const_iterator it = octseq.begin();
+    for (;it != octseq.end(); ++it) {
+      seq->insert(seq->end(),(value_type)(*it));
+    }
+%#else
+    seq->assign(octseq.begin(), octseq.end());
+%#endif
+  }
+
+  template <class Seq, class T = typename Seq::value_type >
+  struct traits_asptr_stdseq {
+    typedef Seq sequence;
+    typedef T value_type;
+
+    static int asptr(const octave_value& obj, sequence **seq) {
+      if (!obj.is_defined() || Swig::swig_value_deref(obj)) {
+	sequence *p;
+	if (SWIG_ConvertPtr(obj,(void**)&p,
+			    swig::type_info<sequence>(),0) == SWIG_OK) {
+	  if (seq) *seq = p;
+	  return SWIG_OLDOBJ;
+	}
+      } else if (obj.is_cell()) {
+	try {
+	  OctSequence_Cont<value_type> octseq(obj);
+	  if (seq) {
+	    sequence *pseq = new sequence();
+	    assign(octseq, pseq);
+	    *seq = pseq;
+	    return SWIG_NEWOBJ;
+	  } else {
+	    return octseq.check() ? SWIG_OK : SWIG_ERROR;
+	  }
+	} catch (std::exception& e) {
+	  if (seq&&!error_state)
+	    error("swig type error: %s",e.what());
+	  return SWIG_ERROR;
+	}
+      }
+      return SWIG_ERROR;
+    }
+  };
+
+  template <class Seq, class T = typename Seq::value_type >
+  struct traits_from_stdseq {
+    typedef Seq sequence;
+    typedef T value_type;
+    typedef typename Seq::size_type size_type;
+    typedef typename sequence::const_iterator const_iterator;
+
+    static octave_value from(const sequence& seq) {
+#ifdef SWIG_OCTAVE_EXTRA_NATIVE_CONTAINERS
+      swig_type_info *desc = swig::type_info<sequence>();
+      if (desc && desc->clientdata) {
+	return SWIG_NewPointerObj(new sequence(seq), desc, SWIG_POINTER_OWN);
+      }
+#endif
+      size_type size = seq.size();
+      if (size <= (size_type)INT_MAX) {
+	Cell c(size,1);
+	int i = 0;
+	for (const_iterator it = seq.begin();
+	     it != seq.end(); ++it, ++i) {
+	  c(i) = swig::from<value_type>(*it);
+	}
+	return c;
+      } else {
+	error("swig overflow error: sequence size not valid in octave");
+	return octave_value();
+      }
+      return octave_value();
+    }
+  };
+}
+}
+
diff --git a/trunk/Lib/octave/octfragments.swg b/trunk/Lib/octave/octfragments.swg
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/trunk/Lib/octave/octfragments.swg
@@ -0,0 +1 @@
+
diff --git a/trunk/Lib/octave/octiterators.swg b/trunk/Lib/octave/octiterators.swg
new file mode 100644
index 0000000..926361e
--- /dev/null
+++ b/trunk/Lib/octave/octiterators.swg
@@ -0,0 +1,360 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * octiterators.swg
+ *
+ * Users can derive form the OctSwigIterator to implemet their
+ * own iterators. As an example (real one since we use it for STL/STD
+ * containers), the template OctSwigIterator_T does the
+ * implementation for generic C++ iterators.
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+%fragment("OctSwigIterator","header") {  
+namespace swig {
+  struct stop_iteration {
+  };
+
+  struct OctSwigIterator {
+  private:
+    octave_value _seq;
+
+  protected:
+    OctSwigIterator(octave_value seq) : _seq(seq)
+    {
+    }
+      
+  public:
+    virtual ~OctSwigIterator() {}
+
+    virtual octave_value value() const = 0;
+
+    virtual OctSwigIterator *incr(size_t n = 1) = 0;
+
+    virtual OctSwigIterator *decr(size_t n = 1)
+    {
+      throw stop_iteration();
+    }
+
+    virtual ptrdiff_t distance(const OctSwigIterator &x) const
+    {
+      throw std::invalid_argument("operation not supported");
+    }
+
+    virtual bool equal (const OctSwigIterator &x) const
+    {
+      throw std::invalid_argument("operation not supported");
+    }
+    
+    virtual OctSwigIterator *copy() const = 0;
+
+    octave_value next()
+    {
+      octave_value obj = value();
+      incr();
+      return obj;
+    }
+
+    octave_value previous()
+    {
+      decr();
+      return value();
+    }
+
+    OctSwigIterator *advance(ptrdiff_t n)
+    {
+      return  (n > 0) ?  incr(n) : decr(-n);
+    }
+      
+    bool operator == (const OctSwigIterator& x)  const
+    {
+      return equal(x);
+    }
+      
+    bool operator != (const OctSwigIterator& x) const
+    {
+      return ! operator==(x);
+    }
+
+    OctSwigIterator* operator ++ () {
+      incr();
+      return this;
+    }
+
+    OctSwigIterator* operator -- () {
+      decr();
+      return this;
+    }
+      
+    OctSwigIterator* operator + (ptrdiff_t n) const
+    {
+      return copy()->advance(n);
+    }
+
+    OctSwigIterator* operator - (ptrdiff_t n) const
+    {
+      return copy()->advance(-n);
+    }
+      
+    ptrdiff_t operator - (const OctSwigIterator& x) const
+    {
+      return x.distance(*this);
+    }
+      
+    static swig_type_info* descriptor() {
+      static int init = 0;
+      static swig_type_info* desc = 0;
+      if (!init) {
+	desc = SWIG_TypeQuery("swig::OctSwigIterator *");
+	init = 1;
+      }	
+      return desc;
+    }    
+  };
+}
+}
+
+%fragment("OctSwigIterator_T","header",fragment="OctSwigIterator",fragment="StdTraits",fragment="StdIteratorTraits") {
+namespace swig {
+  template<typename OutIterator>
+  class OctSwigIterator_T :  public OctSwigIterator
+  {
+  public:
+    typedef OutIterator out_iterator;
+    typedef typename std::iterator_traits<out_iterator>::value_type value_type;    
+    typedef OctSwigIterator_T<out_iterator> self_type;
+
+    OctSwigIterator_T(out_iterator curr, octave_value seq)
+      : OctSwigIterator(seq), current(curr)
+    {
+    }
+
+    const out_iterator& get_current() const
+    {
+      return current;
+    }
+
+    
+    bool equal (const OctSwigIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return (current == iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }
+    
+    ptrdiff_t distance(const OctSwigIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return std::distance(current, iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }    
+    
+  protected:
+    out_iterator current;
+  };
+  
+  template <class ValueType>
+  struct from_oper 
+  {
+    typedef const ValueType& argument_type;
+    typedef octave_value result_type;
+    result_type operator()(argument_type v) const
+    {
+      return swig::from(v);
+    }
+  };
+
+  template<typename OutIterator, 
+	   typename ValueType = typename std::iterator_traits<OutIterator>::value_type,
+	   typename FromOper = from_oper<ValueType> >
+  class OctSwigIteratorOpen_T :  public OctSwigIterator_T<OutIterator>
+  {
+  public:
+    FromOper from;
+    typedef OutIterator out_iterator;
+    typedef ValueType value_type;
+    typedef OctSwigIterator_T<out_iterator>  base;
+    typedef OctSwigIteratorOpen_T<OutIterator, ValueType, FromOper> self_type;
+    
+    OctSwigIteratorOpen_T(out_iterator curr, octave_value seq)
+      : OctSwigIterator_T<OutIterator>(curr, seq)
+    {
+    }
+    
+    octave_value value() const {
+      return from(static_cast<const value_type&>(*(base::current)));
+    }
+    
+    OctSwigIterator *copy() const
+    {
+      return new self_type(*this);
+    }
+
+    OctSwigIterator *incr(size_t n = 1)
+    {
+      while (n--) {
+	++base::current;
+      }
+      return this;
+    }
+
+    OctSwigIterator *decr(size_t n = 1)
+    {
+      while (n--) {
+	--base::current;
+      }
+      return this;
+    }
+  };
+
+  template<typename OutIterator, 
+	   typename ValueType = typename std::iterator_traits<OutIterator>::value_type,
+	   typename FromOper = from_oper<ValueType> >
+  class OctSwigIteratorClosed_T :  public OctSwigIterator_T<OutIterator>
+  {
+  public:
+    FromOper from;
+    typedef OutIterator out_iterator;
+    typedef ValueType value_type;
+    typedef OctSwigIterator_T<out_iterator>  base;    
+    typedef OctSwigIteratorClosed_T<OutIterator, ValueType, FromOper> self_type;
+    
+    OctSwigIteratorClosed_T(out_iterator curr, out_iterator first, out_iterator last, octave_value seq)
+      : OctSwigIterator_T<OutIterator>(curr, seq), begin(first), end(last)
+    {
+    }
+    
+    octave_value value() const {
+      if (base::current == end) {
+	throw stop_iteration();
+      } else {
+	return from(static_cast<const value_type&>(*(base::current)));
+      }
+    }
+    
+    OctSwigIterator *copy() const
+    {
+      return new self_type(*this);
+    }
+
+    OctSwigIterator *incr(size_t n = 1)
+    {
+      while (n--) {
+	if (base::current == end) {
+	  throw stop_iteration();
+	} else {
+	  ++base::current;
+	}
+      }
+      return this;
+    }
+
+    OctSwigIterator *decr(size_t n = 1)
+    {
+      while (n--) {
+	if (base::current == begin) {
+	  throw stop_iteration();
+	} else {
+	  --base::current;
+	}
+      }
+      return this;
+    }
+
+  private:
+    out_iterator begin;
+    out_iterator end;
+  };
+
+  template<typename OutIter>
+  inline OctSwigIterator*
+  make_output_iterator(const OutIter& current, const OutIter& begin,const OutIter& end, octave_value seq = octave_value())
+  {
+    return new OctSwigIteratorClosed_T<OutIter>(current, begin, end, seq);
+  }
+
+  template<typename OutIter>
+  inline OctSwigIterator*
+  make_output_iterator(const OutIter& current, octave_value seq = octave_value())
+  {
+    return new OctSwigIteratorOpen_T<OutIter>(current, seq);
+  }
+}
+}
+
+
+%fragment("OctSwigIterator");
+namespace swig 
+{
+// Throw a StopIteration exception
+  %ignore stop_iteration;
+  struct stop_iteration {};
+  
+  %typemap(throws) stop_iteration {
+    error("stop_iteration exception");
+    SWIG_fail;
+  }
+
+// Mark methods that return new objects
+  %newobject OctSwigIterator::copy;
+  %newobject OctSwigIterator::operator + (ptrdiff_t n) const;
+  %newobject OctSwigIterator::operator - (ptrdiff_t n) const;
+
+  %nodirector OctSwigIterator;
+
+  %catches(swig::stop_iteration) OctSwigIterator::value() const;
+  %catches(swig::stop_iteration) OctSwigIterator::incr(size_t n = 1);
+  %catches(swig::stop_iteration) OctSwigIterator::decr(size_t n = 1);
+  %catches(std::invalid_argument) OctSwigIterator::distance(const OctSwigIterator &x) const;
+  %catches(std::invalid_argument) OctSwigIterator::equal (const OctSwigIterator &x) const;
+  %catches(swig::stop_iteration) OctSwigIterator::next();
+  %catches(swig::stop_iteration) OctSwigIterator::previous();
+  %catches(swig::stop_iteration) OctSwigIterator::advance(ptrdiff_t n);
+  %catches(swig::stop_iteration) OctSwigIterator::operator += (ptrdiff_t n);
+  %catches(swig::stop_iteration) OctSwigIterator::operator -= (ptrdiff_t n);
+  %catches(swig::stop_iteration) OctSwigIterator::operator + (ptrdiff_t n) const;
+  %catches(swig::stop_iteration) OctSwigIterator::operator - (ptrdiff_t n) const;
+
+
+  struct OctSwigIterator
+  {
+  protected:
+    OctSwigIterator(octave_value seq);
+
+  public:
+    virtual ~OctSwigIterator();
+
+    virtual octave_value value() const = 0;
+
+    virtual OctSwigIterator *incr(size_t n = 1) = 0;
+    
+    virtual OctSwigIterator *decr(size_t n = 1);
+
+    virtual ptrdiff_t distance(const OctSwigIterator &x) const;
+
+    virtual bool equal (const OctSwigIterator &x) const;
+    
+    virtual OctSwigIterator *copy() const = 0;
+
+    octave_value next();
+    octave_value previous();
+    OctSwigIterator *advance(ptrdiff_t n);
+
+    bool operator == (const OctSwigIterator& x)  const;
+    bool operator != (const OctSwigIterator& x) const;
+    OctSwigIterator* operator ++ ();
+    OctSwigIterator* operator -- ();
+    OctSwigIterator* operator + (ptrdiff_t n) const;
+    OctSwigIterator* operator - (ptrdiff_t n) const;
+    ptrdiff_t operator - (const OctSwigIterator& x) const;
+  };
+}
+
diff --git a/trunk/Lib/octave/octopers.swg b/trunk/Lib/octave/octopers.swg
new file mode 100644
index 0000000..a9ccf44
--- /dev/null
+++ b/trunk/Lib/octave/octopers.swg
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------
+ * Overloaded operator support
+ * ------------------------------------------------------------ */
+
+#ifdef __cplusplus
+
+// operators supported in Octave, and the methods they are routed to
+
+// __brace      a{args}
+// __brace_asgn a{args} = rhs
+// __paren      a(args)
+// __paren_asgn a(args) = rhs
+// __str        generates string rep
+
+// __not        !a
+// __uplus      +a
+// __uminus     -a
+// __transpose  a.'
+// __hermitian  a'
+// __incr       a++
+// __decr       a--
+// __add        a + b
+// __sub        a - b
+// __mul        a * b
+// __div        a / b
+// __pow        a ^ b
+// __ldiv       a \ b
+// __lshift     a << b
+// __rshift     a >> b
+// __lt         a < b
+// __le         a <= b
+// __eq         a == b
+// __ge         a >= b
+// __gt         a > b
+// __ne         a != b
+// __el_mul     a .* b
+// __el_div     a ./ b
+// __el_pow     a .^ b
+// __el_ldiv    a .\ b
+// __el_and     a & b
+// __el_or      a | b
+
+// operators supported in C++, and the methods that route to them
+
+%rename(__add)       *::operator+;
+%rename(__add)       *::operator+();
+%rename(__add)       *::operator+() const;
+%rename(__sub)       *::operator-;
+%rename(__uminus)    *::operator-();
+%rename(__uminus)    *::operator-() const;
+%rename(__mul)       *::operator*;
+%rename(__div)       *::operator/;
+%rename(__mod)       *::operator%;
+%rename(__lshift)    *::operator<<;
+%rename(__rshift)    *::operator>>;
+%rename(__el_and)    *::operator&&;
+%rename(__el_or)     *::operator||;
+%rename(__xor)       *::operator^;
+%rename(__invert)    *::operator~;
+%rename(__lt)        *::operator<;
+%rename(__le)        *::operator<=;
+%rename(__gt)        *::operator>;
+%rename(__ge)        *::operator>=;
+%rename(__eq)        *::operator==;
+%rename(__ne)        *::operator!=;
+%rename(__not)       *::operator!;
+%rename(__incr)      *::operator++;
+%rename(__decr)      *::operator--;
+%rename(__paren)     *::operator();
+%rename(__brace)     *::operator[];
+
+// Ignored inplace operators
+%ignoreoperator(PLUSEQ)     operator+=;
+%ignoreoperator(MINUSEQ)    operator-=;
+%ignoreoperator(MULEQ)      operator*=;
+%ignoreoperator(DIVEQ)      operator/=;
+%ignoreoperator(MODEQ)      operator%=;
+%ignoreoperator(LSHIFTEQ)   operator<<=;
+%ignoreoperator(RSHIFTEQ)   operator>>=;
+%ignoreoperator(ANDEQ)      operator&=;
+%ignoreoperator(OREQ)       operator|=;
+%ignoreoperator(XOREQ)      operator^=;
+
+// Ignored operators
+%ignoreoperator(EQ)         operator=;
+%ignoreoperator(ARROWSTAR)  operator->*;
+
+#endif /* __cplusplus */
diff --git a/trunk/Lib/octave/octprimtypes.swg b/trunk/Lib/octave/octprimtypes.swg
new file mode 100644
index 0000000..6f43f21
--- /dev/null
+++ b/trunk/Lib/octave/octprimtypes.swg
@@ -0,0 +1,232 @@
+/* ------------------------------------------------------------
+ * Primitive Types
+ * ------------------------------------------------------------ */
+
+
+// boolean
+
+%fragment(SWIG_From_frag(bool),"header") {
+SWIGINTERNINLINE octave_value
+  SWIG_From_dec(bool)(bool value)
+{
+  return octave_value(value);
+}
+}
+
+%fragment(SWIG_AsVal_frag(bool),"header",
+	  fragment=SWIG_AsVal_frag(long)) {
+SWIGINTERN int
+SWIG_AsVal_dec(bool)(const octave_value& ov, bool *val)
+{
+  if (!ov.is_bool_type())
+    return SWIG_ERROR;
+  if (val)
+    *val = ov.bool_value();
+  return SWIG_OK;
+}
+}
+
+// long
+
+%fragment(SWIG_From_frag(long),"header") {
+  SWIGINTERNINLINE octave_value SWIG_From_dec(long)  (long value)
+    {    
+      return octave_value(value);
+    }
+}
+
+
+%fragment(SWIG_AsVal_frag(long),"header") {
+  SWIGINTERN int SWIG_AsVal_dec(long)(const octave_value& ov, long* val)
+    {
+      if (!ov.is_scalar_type())
+	return SWIG_TypeError;
+      if (ov.is_complex_scalar())
+	return SWIG_TypeError;
+      if (ov.is_double_type()||ov.is_single_type()) {
+	double v=ov.double_value();
+	if (v!=floor(v))
+	  return SWIG_TypeError;
+      }
+      if (val)
+	*val = ov.long_value();
+      return SWIG_OK;
+    }
+}
+
+// unsigned long
+
+%fragment(SWIG_From_frag(unsigned long),"header") {
+  SWIGINTERNINLINE octave_value SWIG_From_dec(unsigned long)  (unsigned long value)
+    {    
+      return octave_value(value);
+    }
+}
+
+
+%fragment(SWIG_AsVal_frag(unsigned long),"header") {
+  SWIGINTERN int SWIG_AsVal_dec(unsigned long)(const octave_value& ov, unsigned long* val)
+    {
+      if (!ov.is_scalar_type())
+	return SWIG_TypeError;
+      if (ov.is_complex_scalar())
+	return SWIG_TypeError;
+      if (ov.is_double_type()||ov.is_single_type()) {
+	double v=ov.double_value();
+	if (v<0)
+	  return SWIG_OverflowError;  
+	if (v!=floor(v))
+	  return SWIG_TypeError;
+      }
+      if (ov.is_int8_type()||ov.is_int16_type()||
+	  ov.is_int32_type()) {
+	long v=ov.long_value();
+	if (v<0)
+	  return SWIG_OverflowError;  
+      }
+      if (ov.is_int64_type()) {
+	long long v=ov.int64_scalar_value().value();
+	if (v<0)
+	  return SWIG_OverflowError;  
+      }
+      if (val)
+	*val = ov.ulong_value();
+      return SWIG_OK;
+    }
+}
+
+// long long
+
+%fragment(SWIG_From_frag(long long),"header") {
+  SWIGINTERNINLINE octave_value SWIG_From_dec(long long)  (long long value)
+    {    
+      return octave_int64(value);
+    }
+}
+
+
+%fragment(SWIG_AsVal_frag(long long),"header") {
+  SWIGINTERN int SWIG_AsVal_dec(long long)(const octave_value& ov, long long* val)
+    {
+      if (!ov.is_scalar_type())
+	return SWIG_TypeError;
+      if (ov.is_complex_scalar())
+	return SWIG_TypeError;
+      if (ov.is_double_type()||ov.is_single_type()) {
+	double v=ov.double_value();
+	if (v!=floor(v))
+	  return SWIG_TypeError;
+      }
+      if (val) {
+	if (ov.is_int64_type())
+	  *val = ov.int64_scalar_value().value();
+	else if (ov.is_uint64_type())
+	  *val = ov.uint64_scalar_value().value();
+	else
+	  *val = ov.long_value();
+      }
+      return SWIG_OK;
+    }
+}
+
+%fragment(SWIG_From_frag(unsigned long long),"header") {
+  SWIGINTERNINLINE octave_value SWIG_From_dec(unsigned long long)  (unsigned long long value)
+    {    
+      return octave_uint64(value);
+    }
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long long),"header") {
+  SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(const octave_value& ov, unsigned long long* val)
+    {
+      if (!ov.is_scalar_type())
+	return SWIG_TypeError;
+      if (ov.is_complex_scalar())
+	return SWIG_TypeError;
+      if (ov.is_double_type()||ov.is_single_type()) {
+	double v=ov.double_value();
+	if (v<0)
+	  return SWIG_OverflowError;  
+	if (v!=floor(v))
+	  return SWIG_TypeError;
+      }
+      if (ov.is_int8_type()||ov.is_int16_type()||
+	  ov.is_int32_type()) {
+	long v=ov.long_value();
+	if (v<0)
+	  return SWIG_OverflowError;  
+      }
+      if (ov.is_int64_type()) {
+	long long v=ov.int64_scalar_value().value();
+	if (v<0)
+	  return SWIG_OverflowError;  
+      }
+      if (val) {
+	if (ov.is_int64_type())
+	  *val = ov.int64_scalar_value().value();
+	else if (ov.is_uint64_type())
+	  *val = ov.uint64_scalar_value().value();
+	else
+	  *val = ov.long_value();
+      }
+      return SWIG_OK;
+    }
+}
+
+// double
+
+%fragment(SWIG_From_frag(double),"header") {
+  SWIGINTERNINLINE octave_value SWIG_From_dec(double)  (double value)
+    {    
+      return octave_value(value);
+    }
+}
+
+
+%fragment(SWIG_AsVal_frag(double),"header") {
+  SWIGINTERN int SWIG_AsVal_dec(double)(const octave_value& ov, double* val)
+    {
+      if (!ov.is_scalar_type())
+	return SWIG_TypeError;
+      if (ov.is_complex_scalar())
+	return SWIG_TypeError;
+      if (val)
+	*val = ov.double_value();
+      return SWIG_OK;
+    }
+}
+
+// const char* (strings)
+
+%fragment("SWIG_AsCharPtrAndSize","header") {
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(octave_value ov, char** cptr, size_t* psize, int *alloc)
+{
+  if (ov.is_cell() && ov.rows() == 1 && ov.columns() == 1)
+    ov = ov.cell_value()(0);
+  if (!ov.is_string())
+    return SWIG_TypeError;
+  
+  std::string str=ov.string_value();
+  size_t len=str.size();
+  char* cstr=(char*)str.c_str();
+  if (alloc) {
+    *cptr = %new_copy_array(cstr, len + 1, char);
+    *alloc = SWIG_NEWOBJ;
+  } else if (cptr)
+    *cptr = cstr;
+  if (psize)
+    *psize = len + 1;
+  return SWIG_OK;
+}
+}
+
+%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") {
+SWIGINTERNINLINE octave_value
+SWIG_FromCharPtrAndSize(const char* carray, size_t size)
+{
+  return std::string(carray,carray+size);
+}
+}
+
+
diff --git a/trunk/Lib/octave/octrun.swg b/trunk/Lib/octave/octrun.swg
new file mode 100644
index 0000000..07aa47c
--- /dev/null
+++ b/trunk/Lib/octave/octrun.swg
@@ -0,0 +1,1284 @@
+
+
+SWIGRUNTIME bool SWIG_check_num_args(const char *func_name, int num_args, int max_args, int min_args, int varargs) {
+  if (num_args > max_args && !varargs)
+    error("function %s takes at most %i arguments", func_name, max_args);
+  else if (num_args < min_args)
+    error("function %s requires at least %i arguments", func_name, min_args);
+  else
+    return true;
+  return false;
+}
+
+SWIGRUNTIME octave_value_list *SWIG_Octave_AppendOutput(octave_value_list *ovl, const octave_value &ov) {
+  ovl->append(ov);
+  return ovl;
+}
+
+SWIGRUNTIME octave_value SWIG_ErrorType(int code) {
+  switch (code) {
+  case SWIG_MemoryError:
+    return "SWIG_MemoryError";
+  case SWIG_IOError:
+    return "SWIG_IOError";
+  case SWIG_RuntimeError:
+    return "SWIG_RuntimeError";
+  case SWIG_IndexError:
+    return "SWIG_IndexError";
+  case SWIG_TypeError:
+    return "SWIG_TypeError";
+  case SWIG_DivisionByZero:
+    return "SWIG_DivisionByZero";
+  case SWIG_OverflowError:
+    return "SWIG_OverflowError";
+  case SWIG_SyntaxError:
+    return "SWIG_SyntaxError";
+  case SWIG_ValueError:
+    return "SWIG_ValueError";
+  case SWIG_SystemError:
+    return "SWIG_SystemError";
+  case SWIG_AttributeError:
+    return "SWIG_AttributeError";
+  }
+  return "SWIG unknown error";
+}
+
+SWIGRUNTIME octave_value SWIG_Error(int code, const char *msg) {
+  octave_value type(SWIG_ErrorType(code));
+  std::string r = msg;
+  r += " (" + type.string_value() + ")";
+  error(r.c_str());
+  return octave_value(r);
+}
+
+#define SWIG_fail                                       goto fail
+
+#define SWIG_Octave_ConvertPtr(obj, pptr, type, flags)  SWIG_Octave_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Octave_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Octave_ConvertPtrAndOwn(obj, pptr, type, flags, own)
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Octave_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Octave_NewPointerObj(ptr, type, flags)
+#define swig_owntype                                    int
+
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Octave_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Octave_NewPackedObj(ptr, sz, type)
+
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_ConvertPtr(obj, pptr, type, 0)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_NewPointerObj(ptr, type, 0)
+
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Octave_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Octave_NewPackedObj(ptr, sz, type)
+
+#define SWIG_GetModule(clientdata) SWIG_Octave_GetModule(clientdata)
+#define SWIG_SetModule(clientdata, pointer) SWIG_Octave_SetModule(clientdata,pointer);
+#define SWIG_MODULE_CLIENTDATA_TYPE void*
+
+#define Octave_Error_Occurred() 0
+#define SWIG_Octave_AddErrorMsg(msg) {;}
+
+SWIGRUNTIME swig_module_info *SWIG_Octave_GetModule(void *clientdata);
+SWIGRUNTIME void SWIG_Octave_SetModule(void *clientdata, swig_module_info *pointer);
+
+// For backward compatibility only
+#define SWIG_POINTER_EXCEPTION  0
+#define SWIG_arg_fail(arg)      0
+
+// Runtime API implementation
+
+#include <map>
+#include <vector>
+#include <string>
+
+typedef octave_value_list(*octave_func) (const octave_value_list &, int);
+class octave_swig_type;
+
+namespace Swig {
+  class Director;
+
+  SWIGRUNTIME void swig_register_director(octave_swig_type *self, void *ptr, Director *d);
+  SWIGRUNTIME void swig_director_destroyed(octave_swig_type *self, Director *d);
+  SWIGRUNTIME void swig_director_set_self(Director *d, octave_swig_type *self);
+
+  SWIGRUNTIME octave_base_value *swig_value_ref(octave_swig_type *ost);
+  SWIGRUNTIME octave_swig_type *swig_value_deref(octave_value ov);
+  SWIGRUNTIME octave_swig_type *swig_value_deref(const octave_base_value &ov);
+
+  typedef std::map < void *, Director * > rtdir_map;
+
+  SWIGINTERN rtdir_map &get_rtdir_map() {
+    static swig_module_info *module = 0;
+    if (!module)
+      module = SWIG_GetModule(0);
+    assert(module);
+    if (!module->clientdata)
+      module->clientdata = new rtdir_map;
+    return *(rtdir_map *) module->clientdata;
+  }
+
+  SWIGINTERNINLINE void set_rtdir(void *vptr, Director *d) {
+    get_rtdir_map()[vptr] = d;
+  }
+
+  SWIGINTERNINLINE void erase_rtdir(void *vptr) {
+    get_rtdir_map().erase(vptr);
+  }
+
+  SWIGINTERNINLINE Director *get_rtdir(void *vptr) {
+    rtdir_map::const_iterator pos = get_rtdir_map().find(vptr);
+    Director *rtdir = (pos != get_rtdir_map().end())? pos->second : 0;
+    return rtdir;
+  }
+}
+
+  struct swig_octave_member {
+    const char *name;
+    octave_func method;
+    octave_func get_method;
+    octave_func set_method;
+    int flags;			// 1 static, 2 global
+    const char *doc;
+    bool is_static() const {
+      return flags &1;
+    } bool is_global() const {
+      return flags &2;
+    }
+  };
+
+  struct swig_octave_class {
+    const char *name;
+    swig_type_info **type;
+    int director;
+    octave_func constructor;
+    const char *constructor_doc;
+    octave_func destructor;
+    const swig_octave_member *members;
+    const char **base_names;
+    const swig_type_info **base;
+  };
+
+  // octave_swig_type plays the role of both the shadow class and the class 
+  // representation within Octave, since there is no support for classes.
+  //
+  // These should really be decoupled, with the class support added to Octave
+  // and the shadow class given by an m-file script. That would dramatically 
+  // reduce the runtime complexity, and be more in line w/ other modules.
+
+  class octave_swig_type:public octave_base_value {
+    struct cpp_ptr {
+      void *ptr;
+      bool destroyed;
+      cpp_ptr(void *_ptr):ptr(_ptr), destroyed(false) {
+      }};
+    typedef std::pair < const swig_type_info *, cpp_ptr > type_ptr_pair;
+
+    mutable swig_module_info *module;
+
+    const swig_type_info *construct_type;	// type of special type object
+    std::vector < type_ptr_pair > types;	// our c++ base classes
+    int own;			// whether we call c++ destructors when we die
+
+    typedef std::pair < const swig_octave_member *, octave_value > member_value_pair;
+    typedef std::map < std::string, member_value_pair > member_map;
+    member_map members;
+    bool always_static;
+
+    const swig_octave_member *find_member(const swig_type_info *type, const std::string &name) {
+      if (!type->clientdata)
+	return 0;
+      swig_octave_class *c = (swig_octave_class *) type->clientdata;
+      const swig_octave_member *m;
+      for (m = c->members; m->name; ++m)
+	if (m->name == name)
+	  return m;
+      for (int j = 0; c->base_names[j]; ++j) {
+	if (!c->base[j]) {
+	  if (!module)
+	    module = SWIG_GetModule(0);
+	  assert(module);
+	  c->base[j] = SWIG_MangledTypeQueryModule(module, module, c->base_names[j]);
+	}
+	if (!c->base[j])
+	  return 0;
+	if ((m = find_member(c->base[j], name)))
+	  return m;
+      }
+      return 0;
+    }
+
+    member_value_pair *find_member(const std::string &name, bool insert_if_not_found) {
+      member_map::iterator it = members.find(name);
+      if (it != members.end())
+	return &it->second;
+      const swig_octave_member *m;
+      for (unsigned int j = 0; j < types.size(); ++j)
+	if ((m = find_member(types[j].first, name)))
+	  return &members.insert(std::make_pair(name, std::make_pair(m, octave_value()))).first->second;
+      if (!insert_if_not_found)
+	return 0;
+      return &members[name];
+    }
+
+    const swig_type_info *find_base(const std::string &name, const swig_type_info *base) {
+      if (!base) {
+	for (unsigned int j = 0; j < types.size(); ++j) {
+	  assert(types[j].first->clientdata);
+	  swig_octave_class *cj = (swig_octave_class *) types[j].first->clientdata;
+	  if (cj->name == name)
+	    return types[j].first;
+	}
+	return 0;
+      }
+      assert(base->clientdata);
+      swig_octave_class *c = (swig_octave_class *) base->clientdata;
+      for (int j = 0; c->base_names[j]; ++j) {
+	if (!c->base[j]) {
+	  if (!module)
+	    module = SWIG_GetModule(0);
+	  assert(module);
+	  c->base[j] = SWIG_MangledTypeQueryModule(module, module, c->base_names[j]);
+	}
+	if (!c->base[j])
+	  return 0;
+	assert(c->base[j]->clientdata);
+	swig_octave_class *cj = (swig_octave_class *) c->base[j]->clientdata;
+	if (cj->name == name)
+	  return c->base[j];
+      }
+      return 0;
+    }
+
+    void load_members(const swig_octave_class* c,member_map& out) const {
+      for (const swig_octave_member *m = c->members; m->name; ++m) {
+	if (out.find(m->name) == out.end())
+	  out.insert(std::make_pair(m->name, std::make_pair(m, octave_value())));
+      }
+      for (int j = 0; c->base_names[j]; ++j) {
+	if (!c->base[j]) {
+	  if (!module)
+	    module = SWIG_GetModule(0);
+	  assert(module);
+	  c->base[j] = SWIG_MangledTypeQueryModule(module, module, c->base_names[j]);
+	}
+	if (!c->base[j])
+	  continue;
+	assert(c->base[j]->clientdata);
+	const swig_octave_class *cj =
+	  (const swig_octave_class *) c->base[j]->clientdata;
+	load_members(cj,out);
+      }
+    }
+
+    void load_members(member_map& out) const {
+      out=members;
+      for (unsigned int j = 0; j < types.size(); ++j)
+	if (types[j].first->clientdata)
+	  load_members((const swig_octave_class *) types[j].first->clientdata, out);
+    }
+
+    octave_value_list member_invoke(member_value_pair *m, const octave_value_list &args, int nargout) {
+      if (m->second.is_defined())
+	return m->second.subsref("(", std::list < octave_value_list > (1, args), nargout);
+      else if (m->first && m->first->method)
+	return m->first->method(args, nargout);
+      error("member not defined or not invocable");
+      return octave_value_list();
+    }
+
+    bool dispatch_unary_op(const std::string &symbol, octave_value &ret) {
+      member_value_pair *m = find_member(symbol, false);
+      if (!m || m->first->is_static() || m->first->is_global())
+	return false;
+      octave_value_list args;
+      args.append(as_value());
+      octave_value_list argout(member_invoke(m, args, 1));
+      if (argout.length() < 1)
+	return false;
+      ret = argout(0);
+      return true;
+    }
+
+    bool dispatch_binary_op(const std::string &symbol, const octave_base_value &rhs, octave_value &ret) {
+      member_value_pair *m = find_member(symbol, false);
+      if (!m || m->first->is_static() || m->first->is_global())
+	return false;
+      octave_value_list args;
+      args.append(as_value());
+      args.append(make_value_hack(rhs));
+      octave_value_list argout(member_invoke(m, args, 1));
+      if (argout.length() < 1)
+	return false;
+      ret = argout(0);
+      return true;
+    }
+
+    bool dispatch_index_op(const std::string &symbol, const octave_value_list &rhs, octave_value_list &ret) {
+      member_value_pair *m = find_member(symbol, false);
+      if (!m || m->first->is_static() || m->first->is_global())
+	return false;
+      octave_value_list args;
+      args.append(as_value());
+      args.append(rhs);
+      octave_value_list argout(member_invoke(m, args, 1));
+      if (argout.length() >= 1)
+	ret = argout(0);
+      return true;
+    }
+
+    octave_value_list member_deref(member_value_pair *m, const octave_value_list &args) {
+      if (m->second.is_defined())
+	return m->second;
+      else if (m->first) {
+	if (m->first->get_method)
+	  return m->first->get_method(args, 1);
+	else if (m->first->method)
+	  return octave_value(new octave_builtin(m->first->method));
+      }
+      error("undefined member");
+      return octave_value_list();
+    }
+
+    static octave_value make_value_hack(const octave_base_value &x) {
+      ((octave_swig_type &) x).count++;
+      return octave_value((octave_base_value *) &x);
+    }
+
+    octave_swig_type(const octave_swig_type &x);
+    octave_swig_type &operator=(const octave_swig_type &rhs);
+  public:
+
+    octave_swig_type(void *_ptr = 0, const swig_type_info *_type = 0, int _own = 0,
+		     bool _always_static = false)
+      :	module(0), construct_type(_ptr ? 0 : _type), own(_own), 
+      always_static(_always_static) {
+      if (_type || _ptr)
+	types.push_back(std::make_pair(_type, _ptr));
+      if (_ptr) {
+	Swig::Director *d = Swig::get_rtdir(_ptr);
+	if (d)
+	  Swig::swig_director_set_self(d, this);
+      }
+    }
+
+    ~octave_swig_type() {
+      if (own) {
+	++count;
+	for (unsigned int j = 0; j < types.size(); ++j) {
+	  if (!types[j].first || !types[j].first->clientdata)
+	    continue;
+	  swig_octave_class *c = (swig_octave_class *) types[j].first->clientdata;
+	  if (c->destructor && !types[j].second.destroyed && types[j].second.ptr) {
+	    c->destructor(as_value(), 0);
+	  }
+	}
+      }
+      for (unsigned int j = 0; j < types.size(); ++j)
+	Swig::erase_rtdir(types[j].second.ptr);
+    }
+
+    octave_value as_value() {
+      ++count;
+      return Swig::swig_value_ref(this);
+    }
+
+    void incref() {
+      ++count;
+    }
+
+    void decref() {
+      if (!--count)
+	delete this;
+    }
+
+    long swig_this() const {
+      if (!types.size())
+	return (long) this;
+      return (long) types[0].second.ptr;
+    }
+    const char* help_text() const {
+      if (!types.size())
+	return 0;
+      if (!types[0].first->clientdata)
+	return 0;
+      swig_octave_class *c = (swig_octave_class *) types[0].first->clientdata;
+      return c->constructor_doc;
+    }
+
+    std::string swig_type_name() const {
+      // * need some way to manually name subclasses.
+      // * eg optional first arg to subclass(), or named_subclass()
+      std::string ret;
+      for (unsigned int j = 0; j < types.size(); ++j) {
+	if (j)
+	  ret += "_";
+	if (types[j].first->clientdata) {
+	  swig_octave_class *c = (swig_octave_class *) types[j].first->clientdata;
+	  ret += c->name;
+	} else
+	  ret += types[j].first->name;
+      }
+      return ret;
+    }
+
+    void merge(octave_swig_type &rhs) {
+      rhs.own = 0;
+      for (unsigned int j = 0; j < rhs.types.size(); ++j) {
+	assert(!rhs.types[j].second.destroyed);
+	Swig::Director *d = Swig::get_rtdir(rhs.types[j].second.ptr);
+	if (d)
+	  Swig::swig_director_set_self(d, this);
+      }
+      types.insert(types.end(), rhs.types.begin(), rhs.types.end());
+      members.insert(rhs.members.begin(), rhs.members.end());
+      rhs.types.clear();
+      rhs.members.clear();
+    }
+
+    void install_global() {
+      for (member_map::const_iterator it = members.begin(); it != members.end(); ++it) {
+	if (it->second.first && it->second.first->method)
+	  install_builtin_function(it->second.first->method, it->first,
+				   it->second.first->doc?it->second.first->doc:std::string());
+	else if (it->second.second.is_defined()) {
+	  link_to_global_variable(curr_sym_tab->lookup(it->first, true));
+	  set_global_value(it->first, it->second.second);
+	  
+	  octave_swig_type *ost = Swig::swig_value_deref(it->second.second);
+	  if (ost) {
+	    const char* h = ost->help_text();
+	    if (h) {
+	      symbol_record *sr = global_sym_tab->lookup (it->first, true);
+	      sr->document(h);
+	    }
+	  }
+	}
+      }
+    }
+
+    void *cast(swig_type_info *type, int *_own, int flags) {
+      if (_own)
+	*_own = own;
+      if (flags &SWIG_POINTER_DISOWN)
+	own = 0;
+      if (!type && types.size())
+	return types[0].second.ptr;
+      for (unsigned int j = 0; j < types.size(); ++j)
+	if (type == types[j].first)
+	  return types[j].second.ptr;
+      for (unsigned int j = 0; j < types.size(); ++j) {
+	swig_cast_info *tc = SWIG_TypeCheck(types[j].first->name, type);
+	if (!tc)
+	  continue;
+	int newmemory = 0;
+	void *vptr = SWIG_TypeCast(tc, types[j].second.ptr, &newmemory);
+	assert(!newmemory);	// newmemory handling not yet implemented
+	return vptr;
+      }
+      return 0;
+    }
+
+    bool is_owned() const {
+      return own;
+    }
+
+    void director_destroyed(Swig::Director *d) {
+      bool found = false;
+      for (unsigned int j = 0; j < types.size(); ++j) {
+	Swig::Director *dj = Swig::get_rtdir(types[j].second.ptr);
+	if (dj == d) {
+	  types[j].second.destroyed = true;
+	  found = true;
+	}
+      }
+      assert(found);
+    }
+
+    void assign(const std::string &name, const octave_value &ov) {
+      members[name] = std::make_pair((const swig_octave_member *) 0, ov);
+    }
+
+    void assign(const std::string &name, const swig_octave_member *m) {
+      members[name] = std::make_pair(m, octave_value());
+    }
+
+    octave_base_value *clone() const {
+      // pass-by-value is probably not desired, and is harder;
+      // requires calling copy constructors of contained types etc.
+      assert(0);
+      *(int *) 0 = 0;
+      return 0;
+    }
+
+    octave_base_value *empty_clone() const {
+      return new octave_swig_type();
+    }
+
+    bool is_defined() const {
+      return true;
+    }
+
+    virtual bool is_map() const {
+      return true;
+    }
+
+    virtual octave_value subsref(const std::string &ops, const std::list < octave_value_list > &idx) {
+      octave_value_list ovl = subsref(ops, idx, 1);
+      return ovl.length()? ovl(0) : octave_value();
+    }
+
+    virtual octave_value_list subsref(const std::string &ops, const std::list < octave_value_list > &idx, int nargout) {
+      assert(ops.size() > 0);
+      assert(ops.size() == idx.size());
+
+      std::list < octave_value_list >::const_iterator idx_it = idx.begin();
+      int skip = 0;
+      octave_value_list sub_ovl;
+
+      // constructor invocation
+      if (ops[skip] == '(' && construct_type) {
+	assert(construct_type->clientdata);
+	swig_octave_class *c = (swig_octave_class *) construct_type->clientdata;
+	if (!c->constructor) {
+	  error("cannot create instance");
+	  return octave_value_list();
+	}
+	octave_value_list args;
+	if (c->director)
+	  args.append(Swig::swig_value_ref(new octave_swig_type(this, 0, 0)));
+	args.append(*idx_it++);
+	++skip;
+	sub_ovl = c->constructor(args, nargout);
+      }
+      // member dereference or invocation
+      else if (ops[skip] == '.') {
+	std::string subname;
+	const swig_type_info *base = 0;	// eg, a.base.base_cpp_mem
+	for (;;) {
+	  octave_value_list subname_ovl(*idx_it++);
+	  ++skip;
+	  assert(subname_ovl.length() == 1 && subname_ovl(0).is_string());
+	  subname = subname_ovl(0).string_value();
+
+	  const swig_type_info *next_base = find_base(subname, base);
+	  if (!next_base || skip >= (int) ops.size() || ops[skip] != '.')
+	    break;
+	  base = next_base;
+	}
+
+	member_value_pair tmp, *m = &tmp;
+	if (!base || !(m->first = find_member(base, subname)))
+	  m = find_member(subname, false);
+	if (!m) {
+	  error("member not found");
+	  return octave_value_list();
+	}
+
+	octave_value_list args;
+	if (!always_static &&
+	    (!m->first || (!m->first->is_static() && !m->first->is_global())))
+	  args.append(as_value());
+	if (skip < (int) ops.size() && ops[skip] == '(' && 
+	    ((m->first && m->first->method) || m->second.is_function() || 
+	     m->second.is_function_handle())) {
+	  args.append(*idx_it++);
+	  ++skip;
+	  sub_ovl = member_invoke(m, args, nargout);
+	} else {
+	  sub_ovl = member_deref(m, args);
+	}
+      }
+      // index operator
+      else {
+	if (ops[skip] == '(' || ops[skip] == '{') {
+	  const char *op_name = ops[skip] == '(' ? "__paren" : "__brace";
+	  octave_value_list args;
+	  args.append(*idx_it++);
+	  ++skip;
+	  if (!dispatch_index_op(op_name, args, sub_ovl)) {
+	    error("error evaluating index operator");
+	    return octave_value_list();
+	  }
+	} else {
+	  error("unsupported subsref");
+	  return octave_value_list();
+	}
+      }
+
+      if (skip >= (int) ops.size())
+	return sub_ovl;
+      if (sub_ovl.length() < 1) {
+	error("bad subs ref");
+	return octave_value_list();
+      }
+      return sub_ovl(0).next_subsref(nargout, ops, idx, skip);
+    }
+
+    octave_value subsasgn(const std::string &ops, const std::list < octave_value_list > &idx, const octave_value &rhs) {
+      assert(ops.size() > 0);
+      assert(ops.size() == idx.size());
+
+      std::list < octave_value_list >::const_iterator idx_it = idx.begin();
+      int skip = 0;
+
+      if (ops.size() > 1) {
+	std::list < octave_value_list >::const_iterator last = idx.end();
+	--last;
+	std::list < octave_value_list > next_idx(idx.begin(), last);
+	octave_value next_ov = subsref(ops.substr(0, ops.size() - 1), next_idx);
+	next_ov.subsasgn(ops.substr(ops.size() - 1), std::list < octave_value_list > (1, *last), rhs);
+      }
+
+      else if (ops[skip] == '(' || ops[skip] == '{') {
+	const char *op_name = ops[skip] == '(' ? "__paren_asgn" : "__brace_asgn";
+	member_value_pair *m = find_member(op_name, false);
+	if (m) {
+	  octave_value_list args;
+	  args.append(as_value());
+	  args.append(*idx_it);
+	  args.append(rhs);
+	  member_invoke(m, args, 1);
+	} else
+	  error("%s member not found", op_name);
+      }
+
+      else if (ops[skip] == '.') {
+	octave_value_list subname_ovl(*idx_it++);
+	++skip;
+	assert(subname_ovl.length() == 1 &&subname_ovl(0).is_string());
+	std::string subname = subname_ovl(0).string_value();
+
+	member_value_pair *m = find_member(subname, true);
+	if (!m->first || !m->first->set_method) {
+	  m->first = 0;
+	  m->second = rhs;
+	} else if (m->first->set_method) {
+	  octave_value_list args;
+	  if (!m->first->is_static() && !m->first->is_global())
+	    args.append(as_value());
+	  args.append(rhs);
+	  m->first->set_method(args, 1);
+	} else
+	  error("member not assignable");
+      } else
+	error("unsupported subsasgn");
+
+      return as_value();
+    }
+
+    virtual bool is_string() const {
+      octave_swig_type *nc_this = const_cast < octave_swig_type *>(this);
+      return !!nc_this->find_member("__str", false);
+    }
+
+    virtual std::string string_value(bool force = false) const {
+      octave_swig_type *nc_this = const_cast < octave_swig_type *>(this);
+      member_value_pair *m = nc_this->find_member("__str", false);
+      if (!m) {
+	error("__str method not defined");
+	return std::string();
+      }
+      octave_value_list outarg = nc_this->member_invoke(m, octave_value_list(nc_this->as_value()), 1);
+      if (outarg.length() < 1 || !outarg(0).is_string()) {
+	error("__str method did not return a string");
+	return std::string();
+      }
+      return outarg(0).string_value();
+    }
+
+    /*
+    virtual Octave_map map_value() const {
+      octave_swig_type *nc_this = const_cast < octave_swig_type *>(this);
+      member_value_pair *m = nc_this->find_member("__str", false);
+      if (!m) {
+	error("__map method not defined");
+	return std::string();
+      }
+      octave_value_list outarg = nc_this->member_invoke(m, octave_value_list(nc_this->as_value()), 1);
+      if (outarg.length() < 1 || !outarg(0).is_map()) {
+	error("__map method did not return a string");
+	return std::string();
+      }
+      return outarg(0).map_value();
+    }
+    */
+
+    virtual string_vector map_keys() const {
+      member_map tmp;
+      load_members(tmp);
+
+      string_vector keys(tmp.size());
+      int k = 0;
+      for (member_map::iterator it = tmp.begin(); it != tmp.end(); ++it)
+	keys(k++) = it->first;
+
+      return keys;
+    }
+
+    virtual octave_value convert_to_str(bool pad = false, bool force = false, char type = '"') const {
+      return string_value();
+    }
+
+    virtual octave_value convert_to_str_internal(bool pad, bool force, char type) const {
+      return string_value();
+    }
+
+    static bool dispatch_global_op(const std::string &symbol, const octave_value_list &args, octave_value &ret) {
+      // we assume that "op_"-prefixed functions are installed in global namespace
+      // (rather than any module namespace).
+
+      octave_value fcn = get_global_value(symbol, true);
+      if (!fcn.is_function() && !fcn.is_function_handle())
+	return false;
+      ret = fcn.subsref("(", std::list < octave_value_list > (1, args));
+      return true;
+    }
+
+    static octave_value dispatch_unary_op(const octave_base_value &x, const char *op_name) {
+      octave_swig_type *ost = Swig::swig_value_deref(x);
+      assert(ost);
+
+      octave_value ret;
+      if (ost->dispatch_unary_op(std::string("__") + op_name, ret))
+	return ret;
+      std::string symbol = "op_" + ost->swig_type_name() + "_" + op_name;
+      octave_value_list args;
+      args.append(make_value_hack(x));
+      if (dispatch_global_op(symbol, args, ret))
+	return ret;
+
+      error("could not dispatch unary operator");
+      return octave_value();
+    }
+
+    static octave_value dispatch_binary_op(const octave_base_value &lhs, const octave_base_value &rhs, const char *op_name) {
+      octave_swig_type *lhs_ost = Swig::swig_value_deref(lhs);
+      octave_swig_type *rhs_ost = Swig::swig_value_deref(rhs);
+
+      octave_value ret;
+      if (lhs_ost && lhs_ost->dispatch_binary_op(std::string("__") + op_name, rhs, ret))
+	return ret;
+
+      std::string symbol;
+      octave_value_list args;
+      args.append(make_value_hack(lhs));
+      args.append(make_value_hack(rhs));
+
+      symbol = "op_";
+      symbol += lhs_ost ? lhs_ost->swig_type_name() : lhs.type_name();
+      symbol += "_";
+      symbol += op_name;
+      symbol += "_";
+      symbol += rhs_ost ? rhs_ost->swig_type_name() : rhs.type_name();
+      if (dispatch_global_op(symbol, args, ret))
+	return ret;
+
+      symbol = "op_";
+      symbol += lhs_ost ? lhs_ost->swig_type_name() : lhs.type_name();
+      symbol += "_";
+      symbol += op_name;
+      symbol += "_";
+      symbol += "any";
+      if (dispatch_global_op(symbol, args, ret))
+	return ret;
+
+      symbol = "op_";
+      symbol += "any";
+      symbol += "_";
+      symbol += op_name;
+      symbol += "_";
+      symbol += rhs_ost ? rhs_ost->swig_type_name() : rhs.type_name();
+      if (dispatch_global_op(symbol, args, ret))
+	return ret;
+
+      error("could not dispatch binary operator");
+      return octave_value();
+    }
+
+    void print(std::ostream &os, bool pr_as_read_syntax = false) const {
+      if (is_string()) {
+	os << string_value();
+	return;
+      }
+
+      member_map tmp;
+      load_members(tmp);
+
+      os << "{" << std::endl;
+      for (unsigned int j = 0; j < types.size(); ++j) {
+	if (types[j].first->clientdata) {
+	  const swig_octave_class *c = (const swig_octave_class *) types[j].first->clientdata;
+	  os << "  " << c->name << ", ptr = " << types[j].second.ptr << std::endl;
+	} else {
+	  os << "  " << types[j].first->name << ", ptr = " << types[j].second.ptr << std::endl;
+	}
+      }
+      for (member_map::const_iterator it = tmp.begin(); it != tmp.end(); ++it) {
+	if (it->second.first) {
+	  const char *objtype = it->second.first->method ? "method" : "variable";
+	  const char *modifier = (it->second.first->flags &1) ? "static " : (it->second.first->flags &2) ? "global " : "";
+	  os << "  " << it->second.first->name << " (" << modifier << objtype << ")" << std::endl;
+	  assert(it->second.first->name == it->first);
+	} else {
+	  os << "  " << it->first << std::endl;
+	}
+      }
+      os << "}" << std::endl;
+    }
+  };
+
+  // Octave tries hard to preserve pass-by-value semantics. Eg, assignments
+  // will call clone() via make_unique() if there is more than one outstanding 
+  // reference to the lhs, and forces the clone's reference count to 1 
+  // (so you can't just increment your own count and return this).
+  //
+  // One way to fix this (without modifying Octave) is to add a level of
+  // indirection such that clone copies ref-counted pointer and we keep 
+  // pass-by-ref semantics (which are more natural/expected for C++ bindings).
+  //
+  // Supporting both pass-by-{ref,value} and toggling via %feature/option 
+  // might be nice.
+
+  class octave_swig_ref:public octave_base_value {
+    octave_swig_type *ptr;
+  public:
+    octave_swig_ref(octave_swig_type *_ptr = 0)
+      :ptr(_ptr) { }
+
+    ~octave_swig_ref()
+      { if (ptr) ptr->decref(); }
+
+    octave_swig_type *get_ptr() const
+      { return ptr; }
+
+    octave_base_value *clone() const
+      { if (ptr) ptr->incref(); return new octave_swig_ref(ptr); }
+
+    octave_base_value *empty_clone() const
+      { return new octave_swig_ref(0); }
+
+    bool is_defined() const
+      { return ptr->is_defined(); }
+
+    virtual bool is_map() const 
+      { return ptr->is_map(); }
+
+    virtual octave_value subsref(const std::string &ops, const std::list < octave_value_list > &idx) 
+      { return ptr->subsref(ops, idx); }
+
+    virtual octave_value_list subsref(const std::string &ops, const std::list < octave_value_list > &idx, int nargout)
+      { return ptr->subsref(ops, idx, nargout); }
+
+    octave_value subsasgn(const std::string &ops, const std::list < octave_value_list > &idx, const octave_value &rhs)
+      { return ptr->subsasgn(ops, idx, rhs); }
+
+    virtual bool is_string() const 
+      { return ptr->is_string(); }
+
+    virtual std::string string_value(bool force = false) const 
+      { return ptr->string_value(force); }
+
+    virtual string_vector map_keys() const
+      { return ptr->map_keys(); }
+
+    virtual octave_value convert_to_str(bool pad = false, bool force = false, char type = '"') const
+      { return ptr->convert_to_str(pad, force, type); }
+
+    virtual octave_value convert_to_str_internal(bool pad, bool force, char type) const
+      { return ptr->convert_to_str_internal(pad, force, type); }
+
+    void print(std::ostream &os, bool pr_as_read_syntax = false) const
+      { return ptr->print(os, pr_as_read_syntax); }
+
+  private:
+    DECLARE_OCTAVE_ALLOCATOR;
+    DECLARE_OV_TYPEID_FUNCTIONS_AND_DATA;
+  };
+  DEFINE_OCTAVE_ALLOCATOR(octave_swig_ref);
+  DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_swig_ref, "swig_ref", "swig_ref");
+
+  class octave_swig_packed:public octave_base_value {
+    swig_type_info *type;
+    std::vector < char > buf;
+  public:
+
+    octave_swig_packed(swig_type_info *_type = 0, const void *_buf = 0, size_t _buf_len = 0)
+      :	type(_type), buf((const char*)_buf, (const char*)_buf + _buf_len) {
+    }
+
+    bool copy(swig_type_info *outtype, void *ptr, size_t sz) const {
+      if (outtype && outtype != type)
+	return false;
+      assert(sz <= buf.size());
+      std::copy(buf.begin(), buf.begin()+sz, (char*)ptr);
+      return true;
+    }
+
+    octave_base_value *clone() const {
+      return new octave_swig_packed(*this);
+    }
+
+    octave_base_value *empty_clone() const {
+      return new octave_swig_packed();
+    }
+
+    bool is_defined() const {
+      return true;
+    }
+
+    void print(std::ostream &os, bool pr_as_read_syntax = false) const {
+      os << "swig packed type: name = " << (type ? type->name : std::string()) << ", len = " << buf.size() << std::endl;
+    }
+  private:
+    DECLARE_OCTAVE_ALLOCATOR;
+    DECLARE_OV_TYPEID_FUNCTIONS_AND_DATA;
+  };
+  DEFINE_OCTAVE_ALLOCATOR(octave_swig_packed);
+  DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_swig_packed, "swig_packed", "swig_packed");
+
+  static octave_value_list octave_set_immutable(const octave_value_list &args, int nargout) {
+    error("attempt to set immutable member variable");
+    return octave_value_list();
+  }
+
+  struct octave_value_ref {
+    const octave_value_list &ovl;
+    int j;
+
+    octave_value_ref(const octave_value_list &_ovl, int _j)
+      :ovl(_ovl), j(_j) { }
+
+    operator  octave_value() const {
+      return ovl(j);
+    }
+
+    octave_value operator*() const {
+      return ovl(j);
+    }
+  };
+
+  octave_value_list swig_subclass(const octave_value_list &args, int nargout) {
+    octave_swig_type *top = new octave_swig_type;
+    for (int j = 0; j < args.length(); ++j) {
+      if (args(j).type_id() == octave_swig_ref::static_type_id()) {
+	octave_swig_ref *osr = static_cast < octave_swig_ref *>(args(j).internal_rep());
+	octave_swig_type *ost = osr->get_ptr();
+	if (!ost->is_owned()) {
+	  error("cannot subclass object not constructed on octave side");
+	  return octave_value_list();
+	}
+	top->merge(*ost);
+      } else if (args(j).is_function_handle()) {
+	top->assign(args(j).fcn_handle_value()->fcn_name(), args(j));
+      } else if (args(j).is_string()) {
+	if (j + 1 >= args.length()) {
+	  error("member assignments must be of string,value form");
+	  return octave_value_list();
+	}
+	top->assign(args(j).string_value(), args(j + 1));
+	++j;
+      } else {
+	error("invalid arguments to subclass");
+	return octave_value_list();
+      }
+    }
+    return octave_value(Swig::swig_value_ref(top));
+  }
+
+  octave_value_list swig_type(const octave_value_list &args, int nargout) {
+    if (args.length() != 1) {
+      error("swig_typeinfo must be called with only a single object");
+      return octave_value_list();
+    }
+    octave_swig_type *ost = Swig::swig_value_deref(args(0));
+    if (!ost) {
+      error("object is not a swig_ref");
+      return octave_value_list();
+    }
+    return octave_value(ost->swig_type_name());
+  }
+
+  octave_value_list swig_typequery(const octave_value_list &args, int nargout) {
+    if (args.length() != 1 || !args(0).is_string()) {
+      error("swig_typeinfo must be called with single string argument");
+      return octave_value_list();
+    }
+    swig_module_info *module = SWIG_GetModule(0);
+    swig_type_info *type = SWIG_TypeQueryModule(module, module, args(0).string_value().c_str());
+    if (!type)
+      return octave_value("<unknown>");
+    return octave_value(type->name);
+  }
+
+  octave_value_list swig_this(const octave_value_list &args, int nargout) {
+    if (args.length() != 1) {
+      error("swig_typeinfo must be called with only a single object");
+      return octave_value_list();
+    }
+    if (args(0).is_matrix_type() && args(0).rows() == 0 && args(0).columns() == 0)
+      return octave_value(octave_uint64(0));
+    octave_swig_type *ost = Swig::swig_value_deref(args(0));
+    if (!ost) {
+      error("object is not a swig_ref");
+      return octave_value_list();
+    }
+    return octave_value(octave_uint64((unsigned long long) ost->swig_this()));
+  }
+
+#define SWIG_DIRECTORS
+
+namespace Swig {
+  class Director {
+    octave_swig_type *self;
+    bool disowned;
+
+    Director(const Director &x);
+    Director &operator=(const Director &rhs);
+  public:
+
+    Director(void *vptr):self(0), disowned(false) {
+      set_rtdir(vptr, this);
+    }
+
+    ~Director() {
+      swig_director_destroyed(self, this);
+      if (disowned)
+	self->decref();
+    }
+
+    void swig_set_self(octave_swig_type *new_self) {
+      assert(!disowned);
+      self = new_self;
+    }
+
+    octave_swig_type *swig_get_self() const {
+      return self;
+    }
+
+    void swig_disown() {
+      if (disowned)
+	return;
+      disowned = true;
+      self->incref();
+    }
+  };
+
+  struct DirectorTypeMismatchException {
+    static void raise(const char *msg) {
+      // ... todo
+      throw(DirectorTypeMismatchException());
+    }
+
+    static void raise(const octave_value &ov, const char *msg) {
+      // ... todo
+      raise(msg);
+    }
+  };
+  struct DirectorPureVirtualException {
+    static void raise(const char *msg) {
+      // ... todo
+      throw(DirectorPureVirtualException());
+    }
+
+    static void raise(const octave_value &ov, const char *msg) {
+      // ... todo
+      raise(msg);
+    }
+  };
+
+}
+
+  SWIGRUNTIME void swig_acquire_ownership(void *vptr) {
+    //  assert(0);
+    // ... todo
+  }
+
+  SWIGRUNTIME void swig_acquire_ownership_array(void *vptr) {
+    //  assert(0);
+    // ... todo
+  }
+
+  SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own) {
+    //  assert(0);
+    // ... todo
+  }
+
+  namespace Swig {
+    SWIGRUNTIME void swig_director_destroyed(octave_swig_type *self, Director *d) {
+      self->director_destroyed(d);
+    }
+
+    SWIGRUNTIME void swig_director_set_self(Director *d, octave_swig_type *self) {
+      d->swig_set_self(self);
+    }
+
+    SWIGRUNTIME octave_base_value *swig_value_ref(octave_swig_type *ost) {
+      return new octave_swig_ref(ost);
+    }
+
+    SWIGRUNTIME octave_swig_type *swig_value_deref(octave_value ov) {
+      if (ov.is_cell() && ov.rows() == 1 && ov.columns() == 1)
+	ov = ov.cell_value()(0);
+      return swig_value_deref(*ov.internal_rep());
+    }
+
+    SWIGRUNTIME octave_swig_type *swig_value_deref(const octave_base_value &ov) {
+      if (ov.type_id() != octave_swig_ref::static_type_id())
+	return 0;
+      const octave_swig_ref *osr = static_cast < const octave_swig_ref *>(&ov);
+      return osr->get_ptr();
+    }
+
+  }
+
+#define swig_unary_op(name) \
+SWIGRUNTIME octave_value swig_unary_op_##name(const octave_base_value &x) { \
+  return octave_swig_type::dispatch_unary_op(x,#name); \
+}
+#define swig_binary_op(name) \
+SWIGRUNTIME octave_value swig_binary_op_##name(const octave_base_value&lhs,const octave_base_value &rhs) { \
+  return octave_swig_type::dispatch_binary_op(lhs,rhs,#name); \
+}
+#define swigreg_unary_op(name) \
+if (!octave_value_typeinfo::lookup_unary_op(octave_value::op_##name,tid)) \
+octave_value_typeinfo::register_unary_op(octave_value::op_##name,tid,swig_unary_op_##name);
+#define swigreg_binary_op(name) \
+if (!octave_value_typeinfo::lookup_binary_op(octave_value::op_##name,tid1,tid2)) \
+octave_value_typeinfo::register_binary_op(octave_value::op_##name,tid1,tid2,swig_binary_op_##name);
+
+  swig_unary_op(not);
+  swig_unary_op(uplus);
+  swig_unary_op(uminus);
+  swig_unary_op(transpose);
+  swig_unary_op(hermitian);
+  swig_unary_op(incr);
+  swig_unary_op(decr);
+
+  swig_binary_op(add);
+  swig_binary_op(sub);
+  swig_binary_op(mul);
+  swig_binary_op(div);
+  swig_binary_op(pow);
+  swig_binary_op(ldiv);
+  swig_binary_op(lshift);
+  swig_binary_op(rshift);
+  swig_binary_op(lt);
+  swig_binary_op(le);
+  swig_binary_op(eq);
+  swig_binary_op(ge);
+  swig_binary_op(gt);
+  swig_binary_op(ne);
+  swig_binary_op(el_mul);
+  swig_binary_op(el_div);
+  swig_binary_op(el_pow);
+  swig_binary_op(el_ldiv);
+  swig_binary_op(el_and);
+  swig_binary_op(el_or);
+
+  SWIGRUNTIME void SWIG_InstallUnaryOps(int tid) {
+    swigreg_unary_op(not);
+    swigreg_unary_op(uplus);
+    swigreg_unary_op(uminus);
+    swigreg_unary_op(transpose);
+    swigreg_unary_op(hermitian);
+    swigreg_unary_op(incr);
+    swigreg_unary_op(decr);
+  }
+  SWIGRUNTIME void SWIG_InstallBinaryOps(int tid1, int tid2) {
+    swigreg_binary_op(add);
+    swigreg_binary_op(sub);
+    swigreg_binary_op(mul);
+    swigreg_binary_op(div);
+    swigreg_binary_op(pow);
+    swigreg_binary_op(ldiv);
+    swigreg_binary_op(lshift);
+    swigreg_binary_op(rshift);
+    swigreg_binary_op(lt);
+    swigreg_binary_op(le);
+    swigreg_binary_op(eq);
+    swigreg_binary_op(ge);
+    swigreg_binary_op(gt);
+    swigreg_binary_op(ne);
+    swigreg_binary_op(el_mul);
+    swigreg_binary_op(el_div);
+    swigreg_binary_op(el_pow);
+    swigreg_binary_op(el_ldiv);
+    swigreg_binary_op(el_and);
+    swigreg_binary_op(el_or);
+  }
+  SWIGRUNTIME void SWIG_InstallOps(int tid) {
+    // here we assume that tid are conseq integers increasing from zero, and 
+    // that our tid is the last one. might be better to have explicit string 
+    // list of types we should bind to, and use lookup_type to resolve their tid.
+
+    SWIG_InstallUnaryOps(tid);
+    SWIG_InstallBinaryOps(tid, tid);
+    for (int j = 0; j < tid; ++j) {
+      SWIG_InstallBinaryOps(j, tid);
+      SWIG_InstallBinaryOps(tid, j);
+    }
+  }
+
+SWIGRUNTIME octave_value SWIG_Octave_NewPointerObj(void *ptr, swig_type_info *type, int flags) {
+  int own = (flags &SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;
+
+  Swig::Director *d = Swig::get_rtdir(ptr);
+  if (d && d->swig_get_self())
+    return d->swig_get_self()->as_value();
+  return Swig::swig_value_ref(new octave_swig_type(ptr, type, own));
+}
+
+SWIGRUNTIME int SWIG_Octave_ConvertPtrAndOwn(octave_value ov, void **ptr, swig_type_info *type, int flags, int *own) {
+  if (ov.is_cell() && ov.rows() == 1 && ov.columns() == 1)
+    ov = ov.cell_value()(0);
+  if (!ov.is_defined() ||
+      (ov.is_matrix_type() && ov.rows() == 0 && ov.columns() == 0) ) {
+    if (ptr)
+      *ptr = 0;
+    return SWIG_OK;
+  }
+  if (ov.type_id() != octave_swig_ref::static_type_id())
+    return SWIG_ERROR;
+  octave_swig_ref *osr = static_cast < octave_swig_ref *>(ov.internal_rep());
+  octave_swig_type *ost = osr->get_ptr();
+  void *vptr = ost->cast(type, own, flags);
+  if (!vptr)
+    return SWIG_ERROR;
+  if (ptr)
+    *ptr = vptr;
+  return SWIG_OK;
+}
+
+SWIGRUNTIME octave_value SWIG_Octave_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  return new octave_swig_packed(type, (char *) ptr, sz);
+}
+
+SWIGRUNTIME int SWIG_Octave_ConvertPacked(const octave_value &ov, void *ptr, size_t sz, swig_type_info *type) {
+  if (!ov.is_defined())
+    return SWIG_ERROR;
+  if (ov.type_id() != octave_swig_packed::static_type_id())
+    return SWIG_ERROR;
+  octave_swig_packed *ost = static_cast < octave_swig_packed *>(ov.internal_rep());
+  return ost->copy(type, (char *) ptr, sz) ? SWIG_OK : SWIG_ERROR;
+}
+
+void SWIG_Octave_SetConstant(octave_swig_type *module_ns, const std::string &name, const octave_value &ov) {
+  module_ns->assign(name, ov);
+}
+
+SWIGRUNTIME swig_module_info *SWIG_Octave_GetModule(void *clientdata) {
+  octave_value ov = get_global_value("__SWIG_MODULE__" SWIG_TYPE_TABLE_NAME SWIG_RUNTIME_VERSION, true);
+  if (!ov.is_defined() ||
+      ov.type_id() != octave_swig_packed::static_type_id())
+    return 0;
+  const octave_swig_packed* osp = 
+    static_cast < const octave_swig_packed *> (ov.internal_rep());
+  swig_module_info *pointer = 0;
+  osp->copy(0, &pointer, sizeof(swig_module_info *));
+  return pointer;
+}
+
+SWIGRUNTIME void SWIG_Octave_SetModule(void *clientdata, swig_module_info *pointer) {
+  octave_value ov = new octave_swig_packed(0, &pointer, sizeof(swig_module_info *));
+  const char *module_var = "__SWIG_MODULE__" SWIG_TYPE_TABLE_NAME SWIG_RUNTIME_VERSION;
+  link_to_global_variable(curr_sym_tab->lookup(module_var, true));
+  set_global_value(module_var, ov);
+}
diff --git a/trunk/Lib/octave/octruntime.swg b/trunk/Lib/octave/octruntime.swg
new file mode 100644
index 0000000..dd68ca4
--- /dev/null
+++ b/trunk/Lib/octave/octruntime.swg
@@ -0,0 +1,81 @@
+%insert(runtime) %{
+#include <octave/oct.h>
+#include <octave/parse.h>
+#include <octave/ov-fcn-handle.h>
+#include <octave/Cell.h>
+%}
+
+%insert(runtime) "swigrun.swg";
+%insert(runtime) "swigerrors.swg";
+%insert(runtime) "octrun.swg";
+
+%insert(initbeforefunc) "swiginit.swg"
+
+%insert(initbeforefunc) %{
+
+static void SWIG_init_user(octave_swig_type* module_ns);
+
+DEFUN_DLD (SWIG_name,args,nargout,SWIG_name_d) {
+  static bool already_init=false;
+  if (already_init)
+    return octave_value_list();
+  already_init=true;
+
+  octave_swig_ref::register_type();
+  octave_swig_packed::register_type();
+  SWIG_InitializeModule(0);
+  SWIG_PropagateClientData();
+  
+  install_builtin_function(swig_type,"swig_type",std::string());
+  install_builtin_function(swig_typequery,"swig_typequery",std::string());
+  install_builtin_function(swig_this,"swig_this",std::string());
+  install_builtin_function(swig_subclass,"subclass",std::string());
+
+  bool global_option=true; // * swig cli option should control this default
+  for (int j=0;j<args.length();++j)
+    if (args(j).is_string()&&args(j).string_value()=="noglobal")
+      global_option=true;
+    else if (args(j).is_string()&&args(j).string_value()=="noglobal")
+      global_option=false;
+
+  octave_swig_type* cvar_ns=new octave_swig_type;
+  for (int j=0;swig_globals[j].name;++j)
+    if (swig_globals[j].get_method)
+      cvar_ns->assign(swig_globals[j].name,&swig_globals[j]);
+
+  octave_swig_type* module_ns=new octave_swig_type(0, 0, 0, true);
+  module_ns->assign("cvar",Swig::swig_value_ref(cvar_ns));
+  for (int j=0;swig_globals[j].name;++j)
+    if (swig_globals[j].method)
+      module_ns->assign(swig_globals[j].name,&swig_globals[j]);
+
+  // * need better solution here; swig_type -> octave_class mapping is 
+  // * really n-to-1, in some cases such as template partial spec, etc. 
+  // * see failing tests.
+  for (int j=0;swig_types[j];++j)
+    if (swig_types[j]->clientdata) {
+      swig_octave_class* c=(swig_octave_class*)swig_types[j]->clientdata;
+      module_ns->assign(c->name,
+			Swig::swig_value_ref
+			(new octave_swig_type(0,swig_types[j])));
+    }
+
+  SWIG_init_user(module_ns);
+
+  SWIG_InstallOps(octave_swig_ref::static_type_id());
+
+  // the incref is necessary so install_global doesn't destroy module_ns,
+  // as it would if it installed something with the same name as the module.
+  module_ns->incref();
+  if (global_option)
+    module_ns->install_global();
+  module_ns->decref();
+
+  link_to_global_variable(curr_sym_tab->lookup(SWIG_name_d,true));
+  set_global_value(SWIG_name_d,Swig::swig_value_ref(module_ns));
+
+  return octave_value_list();
+}
+
+%}
+
diff --git a/trunk/Lib/octave/octstdcommon.swg b/trunk/Lib/octave/octstdcommon.swg
new file mode 100644
index 0000000..e69c7e6
--- /dev/null
+++ b/trunk/Lib/octave/octstdcommon.swg
@@ -0,0 +1,226 @@
+%fragment("StdTraits","header",fragment="StdTraitsCommon")
+{
+namespace swig {  
+// Traits that provides the from method
+  template <class Type> struct traits_from_ptr {
+    static octave_value from(Type *val, int owner = 0) {
+      return SWIG_NewPointerObj(val, type_info<Type>(), owner);
+    }
+  };
+
+  template <class Type> struct traits_from {
+    static octave_value from(const Type& val) {
+      return traits_from_ptr<Type>::from(new Type(val), 1);
+    }
+  };
+
+  template <class Type> struct traits_from<Type *> {
+    static octave_value from(Type* val) {
+      return traits_from_ptr<Type>::from(val, 0);
+    }
+  };
+
+  template <class Type> struct traits_from<const Type *> {
+    static octave_value from(const Type* val) {
+      return traits_from_ptr<Type>::from(const_cast<Type*>(val), 0);
+    }
+  };
+
+
+  template <class Type>
+  inline octave_value from(const Type& val) {
+    return traits_from<Type>::from(val);
+  }
+
+  template <class Type>
+  inline octave_value from_ptr(Type* val, int owner) {
+    return traits_from_ptr<Type>::from(val, owner);
+  }
+
+    // Traits that provides the asval/as/check method
+  template <class Type>
+  struct traits_asptr {   
+    static int asptr(const octave_value& obj, Type **val) {
+      Type *p;
+      int res = (SWIG_ConvertPtr(obj, (void**)&p, type_info<Type>(), 0) == SWIG_OK) ? SWIG_OLDOBJ : 0;
+      if (SWIG_IsOK(res)) {
+	if (val) *val = p;
+      }
+      return res;
+    }
+  }; 
+
+  template <class Type>
+  inline int asptr(const octave_value& obj, Type **vptr) {
+    return traits_asptr<Type>::asptr(obj, vptr);
+  }
+
+  template <class Type> 
+  struct traits_asval {
+    static int asval(const octave_value& obj, Type *val) {
+      if (val) {
+	Type *p = 0;
+	int res = traits_asptr<Type>::asptr(obj, &p);
+	if (!SWIG_IsOK(res)) return res;	
+	if (p) {
+	  typedef typename noconst_traits<Type>::noconst_type noconst_type;
+	  *(const_cast<noconst_type*>(val)) = *p;
+	  if (SWIG_IsNewObj(res)){
+	    %delete(p);
+	    res = SWIG_DelNewMask(res);
+	  }
+	  return res;
+	} else {
+	  return SWIG_ERROR;
+	}
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+
+  template <class Type> struct traits_asval<Type*> {
+    static int asval(const octave_value& obj, Type **val) {
+      if (val) {
+        typedef typename noconst_traits<Type>::noconst_type noconst_type;
+        noconst_type *p = 0;
+        int res = traits_asptr<noconst_type>::asptr(obj,  &p);
+        if (SWIG_IsOK(res)) {
+          *(const_cast<noconst_type**>(val)) = p;
+	}
+	return res;
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+  
+  template <class Type>
+  inline int asval(const octave_value& obj, Type *val) {
+    return traits_asval<Type>::asval(obj, val);
+  }
+
+  template <class Type> 
+  struct traits_as<Type, value_category> {
+    static Type as(const octave_value& obj, bool throw_error) {
+      Type v;
+      int res = asval(obj, &v);
+      if (!obj.is_defined() || !SWIG_IsOK(res)) {
+	if (!Octave_Error_Occurred()) {
+	  %type_error(swig::type_name<Type>());
+	}
+	if (throw_error) throw std::invalid_argument("bad type");
+      }
+      return v;
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type, pointer_category> {
+    static Type as(const octave_value& obj, bool throw_error) {
+      Type *v = 0;      
+      int res = traits_asptr<Type>::asptr(obj, &v);
+      if (SWIG_IsOK(res) && v) {
+	if (SWIG_IsNewObj(res)) {
+	  Type r(*v);
+	  %delete(v);
+	  return r;
+	} else {
+	  return *v;
+	}
+      } else {
+	// Uninitialized return value, no Type() constructor required.
+	static Type *v_def = (Type*) malloc(sizeof(Type));
+	if (!Octave_Error_Occurred()) {
+	  %type_error(swig::type_name<Type>());
+	}
+	if (throw_error) throw std::invalid_argument("bad type");
+	memset(v_def,0,sizeof(Type));
+	return *v_def;
+      }
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type*, pointer_category> {
+    static Type* as(const octave_value& obj, bool throw_error) {
+      Type *v = 0;      
+      int res = traits_asptr<Type>::asptr(obj, &v);
+      if (SWIG_IsOK(res)) {
+	return v;
+      } else {
+	if (!Octave_Error_Occurred()) {
+	  %type_error(swig::type_name<Type>());
+	}
+	if (throw_error) throw std::invalid_argument("bad type");
+	return 0;
+      }
+    }
+  };
+    
+  template <class Type>
+  inline Type as(const octave_value& obj, bool te = false) {
+    return traits_as<Type, typename traits<Type>::category>::as(obj, te);
+  }
+
+  template <class Type> 
+  struct traits_check<Type, value_category> {
+    static bool check(const octave_value& obj) {
+      int res = asval(obj, (Type *)(0));
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type> 
+  struct traits_check<Type, pointer_category> {
+    static bool check(const octave_value& obj) {
+      int res = asptr(obj, (Type **)(0));
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type>
+  inline bool check(const octave_value& obj) {
+    return traits_check<Type, typename traits<Type>::category>::check(obj);
+  }
+}
+}
+
+%define %specialize_std_container(Type,Check,As,From)
+%{
+namespace swig {
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval(const octave_value& obj, value_type *val) {
+      if (Check(obj)) {
+	if (val) *val = As(obj);
+	return SWIG_OK;
+      }
+      return SWIG_ERROR;
+    }
+  };
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static octave_value from(const value_type& val) {
+      return From(val);
+    }
+  };
+
+  template <> 
+  struct traits_check<Type, value_category> {
+    static int check(const octave_value& obj) {
+      int res = Check(obj);
+      return obj && res ? res : 0;
+    }
+  };
+}
+%}
+%enddef
+
+
+#define specialize_std_vector(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_list(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_deque(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_set(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_multiset(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+
diff --git a/trunk/Lib/octave/octtypemaps.swg b/trunk/Lib/octave/octtypemaps.swg
new file mode 100644
index 0000000..7934f90
--- /dev/null
+++ b/trunk/Lib/octave/octtypemaps.swg
@@ -0,0 +1,97 @@
+
+// Include fundamental fragemt definitions
+%include <typemaps/fragments.swg>
+
+// Look for user fragments file.
+%include <octfragments.swg>
+
+// Octave fragments for primitive types
+%include <octprimtypes.swg>
+
+// Octave fragments for char* strings
+//%include <octstrings.swg>
+
+
+#ifndef SWIG_DIRECTOR_TYPEMAPS
+#define SWIG_DIRECTOR_TYPEMAPS
+#endif
+
+// Octave types
+#define SWIG_Object                      octave_value
+#define VOID_Object                      octave_value()
+
+/*
+// Octave allows implicit conversion
+#define %implicitconv_flag              $implicitconv 
+*/
+
+// append output
+#define SWIG_AppendOutput(result, obj)  SWIG_Octave_AppendOutput(result, obj)
+
+// set constant
+#define SWIG_SetConstant(name, obj)     SWIG_Octave_SetConstant(module_ns,name,obj) 
+
+// raise
+#define SWIG_Octave_Raise(obj, type, desc) error("c++-side threw an exception")
+#define SWIG_Raise(obj, type, desc)     SWIG_Octave_Raise(obj, type, desc)
+
+// Include the unified typemap library
+%include <typemaps/swigtypemaps.swg>
+
+
+%typemap(constcode,noblock=1) int double {
+  SWIG_Octave_SetConstant(module_ns,"$symname",octave_value($value));
+}
+
+%typecheck(SWIG_TYPECHECK_SWIGOBJECT) SWIG_Object "$1 = (*$input).is_defined();";
+%typecheck(SWIG_TYPECHECK_SWIGOBJECT) octave_value_list "$1 = true;";
+
+%typemap(in) (octave_value_list varargs,...) {
+  for (int j=$argnum-1;j<args.length();++j)
+    $1.append(args(j));
+}
+%typecheck(2000) (octave_value_list varargs,...) {
+  $1=1;
+}
+
+%typemap(in) (const octave_value_list& varargs,...) (octave_value_list tmp) {
+  for (int j=$argnum-1;j<args.length();++j)
+    tmp.append(args(j));
+  $1=&tmp;
+}
+%typecheck(2000) (const octave_value_list& varargs,...) {
+  $1=1;
+}
+
+%typemap(out) octave_value_list {
+  _outp->append($1);
+}
+%typemap(out,noblock=1) Octave_map {
+  $result=$1;
+}
+%typemap(out,noblock=1) NDArray {
+  $result=$1;
+}
+%typemap(out,noblock=1) Cell {
+  $result=$1;
+}
+
+/*
+// Smart Pointers
+%typemap(out,noblock=1) const SWIGTYPE & SMARTPOINTER  {
+  $result = SWIG_NewPointerObj(%new_copy(*$1, $*ltype), $descriptor, SWIG_POINTER_OWN | %newpointer_flags);
+}
+
+%typemap(ret) const SWIGTYPE & SMARTPOINTER, SWIGTYPE SMARTPOINTER {
+  octave_swig_type* lobj=Swig::swig_value_deref($result);
+  if (lobj) {
+    std::list<octave_value_list> idx;
+    idx.push_back(octave_value("__deref__"));
+    idx.push_back(octave_value_list());
+    octave_value_list ovl(lobj->subsref(".(",idx));
+    octave_swig_type* robj=ovl.length()>=1?Swig::swig_value_deref(ovl(0)):0;
+    if (robj && !error_state)
+      lobj->append(robj);
+  }
+}
+*/
diff --git a/trunk/Lib/octave/octuserdir.swg b/trunk/Lib/octave/octuserdir.swg
new file mode 100644
index 0000000..ebb11b3
--- /dev/null
+++ b/trunk/Lib/octave/octuserdir.swg
@@ -0,0 +1,72 @@
+/* -------------------------------------------------------------------------
+ *  Special user directives
+ * ------------------------------------------------------------------------- */
+
+/* ------------------------------------------------------------------------- */
+/*
+  Implicit Conversion using the C++ constructor mechanism
+*/
+
+#define %implicitconv      %feature("implicitconv") 
+#define %noimplicitconv    %feature("implicitconv", "0")
+#define %clearimplicitconv %feature("implicitconv", "")
+
+
+/* ------------------------------------------------------------------------- */
+/* 
+   %extend_smart_pointer extend the smart pointer support.
+
+   For example, if you have a smart pointer as:
+	    
+     template <class Type> class RCPtr {
+     public:
+       ...
+       RCPtr(Type *p);
+   	Type * operator->() const;
+   	...
+     };
+     
+   you use the %extend_smart_pointer directive as:
+   
+     %extend_smart_pointer(RCPtr<A>);
+     %template(RCPtr_A)  RCPtr<A>;
+   
+   then, if you have something like:
+
+     RCPtr<A> make_ptr();
+     int foo(A *);
+
+   you can do the following:
+
+     a = make_ptr();
+     b = foo(a);
+
+   ie, swig will accept a RCPtr<A> object where a 'A *' is
+   expected.
+
+   Also, when using vectors
+   
+     %extend_smart_pointer(RCPtr<A>);
+     %template(RCPtr_A) RCPtr<A>;
+     %template(vector_A) std::vector<RCPtr<A> >;
+   	
+   you can type
+
+     a = A();
+     v = vector_A(2)
+     v[0] = a
+
+   ie, an 'A *' object is accepted, via implicit conversion, 
+   where a RCPtr<A> object is expected. Additionally
+
+     x = v[0]
+
+   returns (and sets 'x' as) a copy of v[0], making reference
+   counting possible and consistent.
+*/
+
+%define %extend_smart_pointer(Type...)
+%implicitconv Type;
+%apply const SWIGTYPE& SMARTPOINTER { const Type& };
+%apply SWIGTYPE SMARTPOINTER { Type };
+%enddef
diff --git a/trunk/Lib/octave/std_alloc.i b/trunk/Lib/octave/std_alloc.i
new file mode 100644
index 0000000..35dc051
--- /dev/null
+++ b/trunk/Lib/octave/std_alloc.i
@@ -0,0 +1 @@
+%include <std/std_alloc.i>
diff --git a/trunk/Lib/octave/std_basic_string.i b/trunk/Lib/octave/std_basic_string.i
new file mode 100644
index 0000000..f2dac40
--- /dev/null
+++ b/trunk/Lib/octave/std_basic_string.i
@@ -0,0 +1,103 @@
+#if !defined(SWIG_STD_STRING) 
+#define SWIG_STD_BASIC_STRING
+
+%include <octcontainer.swg>
+
+#define %swig_basic_string(Type...)  %swig_sequence_methods_val(Type)
+
+
+%fragment(SWIG_AsPtr_frag(std::basic_string<char>),"header",
+	  fragment="SWIG_AsCharPtrAndSize") {
+SWIGINTERN int
+SWIG_AsPtr(std::basic_string<char>)(PyObject* obj, std::string **val)
+{
+  static swig_type_info* string_info = 
+    SWIG_TypeQuery("std::basic_string<char> *");
+  std::string *vptr;    
+  if (SWIG_ConvertPtr(obj, (void**)&vptr, string_info, 0) == SWIG_OK) {
+    if (val) *val = vptr;
+    return SWIG_OLDOBJ;
+  } else {
+    PyErr_Clear();
+    char* buf = 0 ; size_t size = 0; int alloc = 0;
+    if (SWIG_AsCharPtrAndSize(obj, &buf, &size, &alloc) == SWIG_OK) {
+      if (buf) {
+	if (val) *val = new std::string(buf, size - 1);
+	if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+	return SWIG_NEWOBJ;
+      }
+    } else {
+      PyErr_Clear();
+    }  
+    if (val) {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+      PyErr_SetString(PyExc_TypeError,"a string is expected");
+      SWIG_PYTHON_THREAD_END_BLOCK;
+    }
+    return 0;
+  }
+}  
+}
+
+%fragment(SWIG_From_frag(std::basic_string<char>),"header",
+	  fragment="SWIG_FromCharPtrAndSize") {
+SWIGINTERNINLINE PyObject*
+  SWIG_From(std::basic_string<char>)(const std::string& s)
+  {
+    return SWIG_FromCharPtrAndSize(s.data(), s.size());
+  }
+}
+
+%include <std/std_basic_string.i>
+%typemaps_asptrfromn(%checkcode(STRING), std::basic_string<char>);
+
+#endif
+
+
+#if !defined(SWIG_STD_WSTRING)
+
+%fragment(SWIG_AsPtr_frag(std::basic_string<wchar_t>),"header",
+	  fragment="SWIG_AsWCharPtrAndSize") {
+SWIGINTERN int
+  SWIG_AsPtr(std::basic_string<wchar_t>)(PyObject* obj, std::wstring **val)
+  {
+    static swig_type_info* string_info = 
+      SWIG_TypeQuery("std::basic_string<wchar_t> *");
+    std::wstring *vptr;    
+    if (SWIG_ConvertPtr(obj, (void**)&vptr, string_info, 0) == SWIG_OK) {
+      if (val) *val = vptr;
+      return SWIG_OLDOBJ;
+    } else {
+      PyErr_Clear();
+      wchar_t *buf = 0 ; size_t size = 0; int alloc = 0;
+      if (SWIG_AsWCharPtrAndSize(obj, &buf, &size, &alloc) == SWIG_OK) {
+	if (buf) {
+	  if (val) *val = new std::wstring(buf, size - 1);
+	  if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+	  return SWIG_NEWOBJ;
+	}
+      } else {
+	PyErr_Clear();
+      }  
+      if (val) {
+	SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	PyErr_SetString(PyExc_TypeError,"a wstring is expected");
+	SWIG_PYTHON_THREAD_END_BLOCK;
+      }
+      return 0;
+    }
+  }
+}
+
+%fragment(SWIG_From_frag(std::basic_string<wchar_t>),"header",
+	  fragment="SWIG_FromWCharPtrAndSize") {
+SWIGINTERNINLINE PyObject*
+  SWIG_From(std::basic_string<wchar_t>)(const std::wstring& s)
+  {
+    return SWIG_FromWCharPtrAndSize(s.data(), s.size());
+  }
+}
+
+%typemaps_asptrfromn(%checkcode(UNISTRING), std::basic_string<wchar_t>);
+
+#endif
diff --git a/trunk/Lib/octave/std_carray.i b/trunk/Lib/octave/std_carray.i
new file mode 100644
index 0000000..1477479
--- /dev/null
+++ b/trunk/Lib/octave/std_carray.i
@@ -0,0 +1,56 @@
+%include <pycontainer.swg>
+
+/*
+%fragment("StdCarrayTraits","header",fragment="StdSequenceTraits")
+{
+namespace swig {
+  template <class T, size_t S>
+  struct traits_asptr<std::carray<T, S> >  {
+    static int asptr(PyObject *obj, std::carray<T, S> **array) {
+      return traits_asptr_stdseq<std::carray<T, S> >::asptr(obj, array);
+    }
+  };
+}
+}
+
+%warnfilter(SWIGWARN_IGNORE_OPERATOR_INDEX) std::carray::operator[];
+
+%extend std::carray {
+  %fragment(SWIG_Traits_frag(std::carray<_Type, _Size >), "header",
+	    fragment="PySwigIterator_T",
+	    fragment=SWIG_Traits_frag(_Type),
+	    fragment="StdCarrayTraits") {
+    namespace swig {
+      template <>  struct traits<std::carray<_Type, _Size > > {
+	typedef pointer_category category;
+	static const char* type_name() {
+	  return "std::carray<" #_Type "," #_Size " >";
+	}
+      };
+    }
+  }
+  
+  %typemaps_asptr(SWIG_TYPECHECK_VECTOR, swig::asptr,
+		  SWIG_Traits_frag(std::carray<_Type, _Size >),
+		  std::carray<_Type, _Size >);
+
+  %typemap(out,noblock=1) iterator, const_iterator {
+    $result = SWIG_NewPointerObj(swig::make_output_iterator((const $type &)$1),
+				 swig::PySwigIterator::descriptor(),SWIG_POINTER_OWN);
+  }
+  
+  inline size_t __len__() const { return self->size(); }
+  
+  inline const _Type& __getitem__(size_t i) const { return (*self)[i]; }
+  
+  inline void __setitem__(size_t i, const _Type& v) { (*self)[i] = v; }
+
+  
+  swig::PySwigIterator* __iter__(PyObject **PYTHON_SELF) {
+    return swig::make_output_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF);
+  }
+}
+
+%include <std/std_carray.swg>
+*/
+
diff --git a/trunk/Lib/octave/std_char_traits.i b/trunk/Lib/octave/std_char_traits.i
new file mode 100644
index 0000000..bf4e6c4
--- /dev/null
+++ b/trunk/Lib/octave/std_char_traits.i
@@ -0,0 +1 @@
+%include <std/std_char_traits.i>
diff --git a/trunk/Lib/octave/std_common.i b/trunk/Lib/octave/std_common.i
new file mode 100644
index 0000000..d13d2d6
--- /dev/null
+++ b/trunk/Lib/octave/std_common.i
@@ -0,0 +1,41 @@
+%include <std/std_except.i>
+%include <octstdcommon.swg>
+
+
+// Generate the traits for a 'primitive' type, such as 'double',
+// for which the SWIG_AsVal and SWIG_From methods are already defined.
+
+%define %traits_ptypen(Type...)
+  %fragment(SWIG_Traits_frag(Type),"header",
+	    fragment=SWIG_AsVal_frag(Type),
+	    fragment=SWIG_From_frag(Type),
+	    fragment="StdTraits") {
+namespace swig {
+  template <> struct traits<Type > {
+    typedef value_category category;
+    static const char* type_name() { return  #Type; }
+  };  
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval(octave_value obj, value_type *val) { 
+      return SWIG_AsVal(Type)(obj, val);
+    }
+  };
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static octave_value from(const value_type& val) {
+      return SWIG_From(Type)(val);
+    }
+  };
+}
+}
+%enddef
+
+%include <std/std_common.i>
+
+//
+// Generates the traits for all the known primitive
+// C++ types (int, double, ...)
+//
+%apply_cpptypes(%traits_ptypen);
+
diff --git a/trunk/Lib/octave/std_complex.i b/trunk/Lib/octave/std_complex.i
new file mode 100644
index 0000000..771728b
--- /dev/null
+++ b/trunk/Lib/octave/std_complex.i
@@ -0,0 +1,22 @@
+/*
+ *  STD C++ complex typemaps
+ */
+
+%include <octcomplex.swg>
+
+%{
+#include <complex> 
+%}
+
+/* defining the complex as/from converters */
+
+%swig_cplxdbl_convn(std::complex<double>, std::complex<double>, std::real, std::imag)
+%swig_cplxflt_convn(std::complex<float>,  std::complex<float>,  std::real, std::imag)
+
+/* defining the typemaps */
+
+%typemaps_primitive(%checkcode(CPLXDBL), std::complex<double>);
+%typemaps_primitive(%checkcode(CPLXFLT), std::complex<float>);
+
+
+
diff --git a/trunk/Lib/octave/std_container.i b/trunk/Lib/octave/std_container.i
new file mode 100644
index 0000000..cab7645
--- /dev/null
+++ b/trunk/Lib/octave/std_container.i
@@ -0,0 +1,2 @@
+%include <octcontainer.swg>
+%include <std/std_container.i>
diff --git a/trunk/Lib/octave/std_deque.i b/trunk/Lib/octave/std_deque.i
new file mode 100644
index 0000000..6866a61
--- /dev/null
+++ b/trunk/Lib/octave/std_deque.i
@@ -0,0 +1,25 @@
+// Deques
+
+%fragment("StdDequeTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::deque<T> >  {
+      static int asptr(octave_value obj, std::deque<T>  **vec) {
+	return traits_asptr_stdseq<std::deque<T> >::asptr(obj, vec);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::deque<T> > {
+      static octave_value from(const std::deque<T> & vec) {
+	return traits_from_stdseq<std::deque<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_deque_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_deque_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_deque.i>
diff --git a/trunk/Lib/octave/std_except.i b/trunk/Lib/octave/std_except.i
new file mode 100644
index 0000000..af98428
--- /dev/null
+++ b/trunk/Lib/octave/std_except.i
@@ -0,0 +1 @@
+%include <typemaps/std_except.swg>
diff --git a/trunk/Lib/octave/std_map.i b/trunk/Lib/octave/std_map.i
new file mode 100644
index 0000000..a54e5f7
--- /dev/null
+++ b/trunk/Lib/octave/std_map.i
@@ -0,0 +1,151 @@
+// Maps
+
+%include <octcontainer.swg>
+
+%fragment("StdMapTraits","header",fragment="StdSequenceTraits")
+{
+  namespace swig {
+    template <class OctSeq, class K, class T >
+    inline void
+    assign(const OctSeq& octseq, std::map<K,T > *map) {
+      typedef typename std::map<K,T>::value_type value_type;
+      typename OctSeq::const_iterator it = octseq.begin();
+      for (;it != octseq.end(); ++it) {
+	map->insert(value_type(it->first, it->second));
+      }
+    }
+
+    template <class K, class T>
+    struct traits_asptr<std::map<K,T> >  {
+      typedef std::map<K,T> map_type;
+      static int asptr(octave_value obj, map_type **val) {
+	/*
+	int res = SWIG_ERROR;
+	if (PyDict_Check(obj)) {
+	  PyObject_var items = PyObject_CallMethod(obj,(char *)"items",NULL);
+	  res = traits_asptr_stdseq<std::map<K,T>, std::pair<K, T> >::asptr(items, val);
+	} else {
+	  map_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<map_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+	*/
+	return SWIG_ERROR;
+      }      
+    };
+      
+    template <class K, class T >
+    struct traits_from<std::map<K,T> >  {
+      typedef std::map<K,T> map_type;
+      typedef typename map_type::const_iterator const_iterator;
+      typedef typename map_type::size_type size_type;
+            
+      static octave_value from(const map_type& map) {
+	/*
+	swig_type_info *desc = swig::type_info<map_type>();
+	if (desc && desc->clientdata) {
+	  return SWIG_NewPointerObj(new map_type(map), desc, SWIG_POINTER_OWN);
+	} else {
+	  size_type size = map.size();
+	  int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1;
+	  if (pysize < 0) {
+	    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	    PyErr_SetString(PyExc_OverflowError,
+			    "map size not valid in python");
+	    SWIG_PYTHON_THREAD_END_BLOCK;
+	    return NULL;
+	  }
+	  PyObject *obj = PyDict_New();
+	  for (const_iterator i= map.begin(); i!= map.end(); ++i) {
+	    swig::PyObject_var key = swig::from(i->first);
+	    swig::PyObject_var val = swig::from(i->second);
+	    PyDict_SetItem(obj, key, val);
+	  }
+	  return obj;
+	}
+	*/
+	return octave_value();
+      }
+    };
+
+    template <class ValueType>
+    struct from_key_oper 
+    {
+      typedef const ValueType& argument_type;
+      typedef octave_value result_type;
+      result_type operator()(argument_type v) const
+      {
+	return swig::from(v.first);
+      }
+    };
+
+    template <class ValueType>
+    struct from_value_oper 
+    {
+      typedef const ValueType& argument_type;
+      typedef octave_value result_type;
+      result_type operator()(argument_type v) const
+      {
+	return swig::from(v.second);
+      }
+    };
+
+    template<class OutIterator, class FromOper, class ValueType = typename OutIterator::value_type>
+    struct OctMapIterator_T : PySwigIteratorClosed_T<OutIterator, ValueType, FromOper>
+    {
+      OctMapIterator_T(OutIterator curr, OutIterator first, OutIterator last, octave_value seq)
+	: PySwigIteratorClosed_T<OutIterator,ValueType,FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+
+
+    template<class OutIterator,
+	     class FromOper = from_key_oper<typename OutIterator::value_type> >
+    struct OctMapKeyIterator_T : OctMapIterator_T<OutIterator, FromOper>
+    {
+      OctMapKeyIterator_T(OutIterator curr, OutIterator first, OutIterator last, octave_value seq)
+	: OctMapIterator_T<OutIterator, FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+
+    template<typename OutIter>
+    inline PySwigIterator*
+    make_output_key_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, octave_value seq = octave_value())
+    {
+      return new OctMapKeyIterator_T<OutIter>(current, begin, end, seq);
+    }
+
+    template<class OutIterator,
+	     class FromOper = from_value_oper<typename OutIterator::value_type> >
+    struct OctMapValueIterator_T : OctMapIterator_T<OutIterator, FromOper>
+    {
+      OctMapValueIterator_T(OutIterator curr, OutIterator first, OutIterator last, octave_value seq)
+	: OctMapIterator_T<OutIterator, FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+    
+
+    template<typename OutIter>
+    inline PySwigIterator*
+    make_output_value_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, octave_value seq = 0)
+    {
+      return new OctMapValueIterator_T<OutIter>(current, begin, end, seq);
+    }
+  }
+}
+
+%define %swig_map_common(Map...)
+  %swig_sequence_iterator(Map);
+  %swig_container_methods(Map);
+%enddef
+
+%define %swig_map_methods(Map...)
+     %swig_map_common(Map)
+%enddef
+
+
+%include <std/std_map.i>
diff --git a/trunk/Lib/octave/std_pair.i b/trunk/Lib/octave/std_pair.i
new file mode 100644
index 0000000..ab028d1
--- /dev/null
+++ b/trunk/Lib/octave/std_pair.i
@@ -0,0 +1,129 @@
+// Pairs
+
+%include <octstdcommon.swg>
+
+//#define SWIG_STD_PAIR_ASVAL
+
+%fragment("StdPairTraits","header",fragment="StdTraits") {
+  namespace swig {
+#ifdef SWIG_STD_PAIR_ASVAL
+    template <class T, class U >
+    struct traits_asval<std::pair<T,U> >  {
+      typedef std::pair<T,U> value_type;
+
+      static int get_pair(const octave_value& first, octave_value second,
+			  std::pair<T,U> *val)
+      {
+	if (val) {
+	  T *pfirst = &(val->first);
+	  int res1 = swig::asval(first, pfirst);
+	  if (!SWIG_IsOK(res1))
+	    return res1;
+	  U *psecond = &(val->second);
+	  int res2 = swig::asval(second, psecond);
+	  if (!SWIG_IsOK(res2))
+	    return res2;
+	  return res1 > res2 ? res1 : res2;
+	} else {
+	  T *pfirst = 0;
+	  int res1 = swig::asval(first, pfirst);
+	  if (!SWIG_IsOK(res1))
+	    return res1;
+	  U *psecond = 0;
+	  int res2 = swig::asval((PyObject*)second, psecond);
+	  if (!SWIG_IsOK(res2))
+	    return res2;
+	  return res1 > res2 ? res1 : res2;
+	}
+      }
+
+      static int asval(const octave_value& obj, std::pair<T,U> *val) {
+	if (obj.is_cell()) {
+	  Cell c=obj.cell_value();
+	  if (c.numel()<2) {
+	    error("pair from Cell array requires at least two elements");
+	    return SWIG_ERROR;
+	  }
+	  return get_pair(c(0),c(1),val);
+	} else {
+	  value_type *p;
+	  int res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<value_type>(),0);
+	  if (SWIG_IsOK(res) && val)
+	    *val = *p;
+	  return res;
+	}
+	return SWIG_ERROR;
+      }
+    };
+
+#else
+    template <class T, class U >
+    struct traits_asptr<std::pair<T,U> >  {
+      typedef std::pair<T,U> value_type;
+
+      static int get_pair(const octave_value& first, octave_value second,
+			  std::pair<T,U> **val) 
+      {
+	if (val) {
+	  value_type *vp = %new_instance(std::pair<T,U>);
+	  T *pfirst = &(vp->first);
+	  int res1 = swig::asval(first, pfirst);
+	  if (!SWIG_IsOK(res1))
+	    return res1;
+	  U *psecond = &(vp->second);
+	  int res2 = swig::asval(second, psecond);
+	  if (!SWIG_IsOK(res2))
+	    return res2;
+	  *val = vp;
+	  return SWIG_AddNewMask(res1 > res2 ? res1 : res2);
+	} else {
+	  T *pfirst = 0;
+	  int res1 = swig::asval(first, pfirst);
+	  if (!SWIG_IsOK(res1))
+	    return res1;
+	  U *psecond = 0;
+	  int res2 = swig::asval(second, psecond);
+	  if (!SWIG_IsOK(res2))
+	    return res2;
+	  return res1 > res2 ? res1 : res2;
+	}
+	return SWIG_ERROR;
+      }
+
+      static int asptr(const octave_value& obj, std::pair<T,U> **val) {
+	if (obj.is_cell()) {
+	  Cell c=obj.cell_value();
+	  if (c.numel()<2) {
+	    error("pair from Cell array requires at least two elements");
+	    return SWIG_ERROR;
+	  }
+	  return get_pair(c(0),c(1),val);
+	} else {
+	  value_type *p;
+	  int res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<value_type>(),0);
+	  if (SWIG_IsOK(res) && val)
+	    *val = p;
+	  return res;
+	}
+	return SWIG_ERROR;
+      }
+    };
+
+#endif
+    template <class T, class U >
+    struct traits_from<std::pair<T,U> >   {
+      static octave_value from(const std::pair<T,U>& val) {
+	Cell c(1,2);
+	c(0)=swig::from(val.first);
+	c(1)=swig::from(val.second);
+	return c;
+      }
+    };
+  }
+}
+
+%define %swig_pair_methods(pair...)
+%enddef
+
+%include <std/std_pair.i>
+
diff --git a/trunk/Lib/octave/std_string.i b/trunk/Lib/octave/std_string.i
new file mode 100644
index 0000000..dc1378a
--- /dev/null
+++ b/trunk/Lib/octave/std_string.i
@@ -0,0 +1 @@
+%include <typemaps/std_string.swg>
diff --git a/trunk/Lib/octave/std_vector.i b/trunk/Lib/octave/std_vector.i
new file mode 100644
index 0000000..2862b5e
--- /dev/null
+++ b/trunk/Lib/octave/std_vector.i
@@ -0,0 +1,26 @@
+// Vectors
+
+%fragment("StdVectorTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::vector<T> >  {
+      static int asptr(const octave_value& obj, std::vector<T> **vec) {
+	return traits_asptr_stdseq<std::vector<T> >::asptr(obj, vec);
+      }
+    };
+    
+    template <class T>
+    struct traits_from<std::vector<T> > {
+      static octave_value from(const std::vector<T>& vec) {
+	return traits_from_stdseq<std::vector<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_vector_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_vector_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_vector.i>
+
diff --git a/trunk/Lib/octave/stl.i b/trunk/Lib/octave/stl.i
new file mode 100644
index 0000000..b29f7d8
--- /dev/null
+++ b/trunk/Lib/octave/stl.i
@@ -0,0 +1,6 @@
+/* initial STL definition. extended as needed in each language */
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
diff --git a/trunk/Lib/octave/typemaps.i b/trunk/Lib/octave/typemaps.i
new file mode 100644
index 0000000..1f9b9c4
--- /dev/null
+++ b/trunk/Lib/octave/typemaps.i
@@ -0,0 +1 @@
+%include <typemaps/typemaps.swg>
diff --git a/trunk/Lib/perl5/Makefile.in b/trunk/Lib/perl5/Makefile.in
new file mode 100644
index 0000000..dde0189
--- /dev/null
+++ b/trunk/Lib/perl5/Makefile.in
@@ -0,0 +1,138 @@
+# ---------------------------------------------------------------
+# SWIG Perl5 Makefile
+# 
+# This file can be used to build various Perl5 extensions with SWIG.
+# By default this file is set up for dynamic loading, but it can
+# be easily customized for static extensions by modifying various
+# portions of the file.
+#
+#        SRCS       = C source files
+#        CXXSRCS    = C++ source files
+#        OBJCSRCS   = Objective-C source files
+#        OBJS       = Additional .o files (compiled previously)
+#        INTERFACE  = SWIG interface file
+#        TARGET     = Name of target module or executable
+#
+# Many portions of this file were created by the SWIG configure
+# script and should already reflect your machine.
+#----------------------------------------------------------------
+
+SRCS          = 
+CXXSRCS       = 
+OBJCSRCS      = 
+OBJS          = 
+INTERFACE     = 
+WRAPFILE      = $(INTERFACE:.i=_wrap.c)
+WRAPOBJ       = $(INTERFACE:.i=_wrap.o)
+TARGET        = module@SO@ # Use this kind of target for dynamic loading
+#TARGET        = myperl  # Use this target for static linking
+
+prefix        = @prefix@
+exec_prefix   = @exec_prefix@
+
+CC            = @CC@
+CXX           = @CXX@
+OBJC          = @CC@ -Wno-import # -Wno-import needed for gcc 
+CFLAGS        = 
+INCLUDES      =
+LIBS          =
+
+# SWIG Options
+#     SWIG      = location of the SWIG executable
+#     SWIGOPT   = SWIG compiler options
+#     SWIGCC    = Compiler used to compile the wrapper file
+
+SWIG          = $(exec_prefix)/bin/swig 
+SWIGOPT       = -perl5 
+SWIGCC        = $(CC) 
+
+# SWIG Library files.  Uncomment this to staticly rebuild Perl
+#SWIGLIB       = -static -lperlmain.i
+
+# Rules for creating .o files from source.
+
+COBJS         = $(SRCS:.c=.o)
+CXXOBJS       = $(CXXSRCS:.cxx=.o)
+OBJCOBJS      = $(OBJCSRCS:.m=.o)
+ALLOBJS       = $(COBJS) $(CXXOBJS) $(OBJCOBJS) $(OBJS)
+
+# Command that will be used to build the final extension.
+BUILD         = $(SWIGCC)
+
+# Uncomment the following if you are using dynamic loading
+CCSHARED      = @CCSHARED@
+BUILD         = @LDSHARED@
+
+# Uncomment the following if you are using dynamic loading with C++ and
+# need to provide additional link libraries (this is not always required).
+
+#DLL_LIBS      = -L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \
+             -L/usr/local/lib -lg++ -lstdc++ -lgcc
+
+# X11 installation (possibly needed if using Perl-Tk)
+
+XLIB          = @XLIBSW@
+XINCLUDE      = @XINCLUDES@
+
+# Perl installation
+
+PERL_INCLUDE  = -I@PERL5EXT@
+PERL_LIB      = -L@PERL5EXT@ -lperl 
+PERL_FLAGS    = -Dbool=char -Dexplicit=
+
+# Tcl installation.  If using Tk you might need this
+
+TCL_INCLUDE   = @TCLINCLUDE@
+TCL_LIB       = @TCLLIB@
+
+# Build libraries (needed for static builds)
+
+LIBM          = @LIBM@
+LIBC          = @LIBC@
+SYSLIBS       = $(LIBM) $(LIBC) @LIBS@
+
+# Build options (uncomment only one these)
+
+#TK_LIB        = $(TCL_LIB) -ltcl -ltk $(XLIB)
+BUILD_LIBS    = $(LIBS) # Dynamic loading
+#BUILD_LIBS    = $(PERL_LIB) $(TK_LIB) $(LIBS) $(SYSLIBS)  # Static linking
+
+# Compilation rules for non-SWIG components
+
+.SUFFIXES: .c .cxx .m
+
+.c.o:
+	$(CC) $(CCSHARED) $(CFLAGS) $(INCLUDES) -c $<
+
+.cxx.o:
+	$(CXX) $(CCSHARED) $(CXXFLAGS) $(INCLUDES) -c $<
+
+.m.o:
+	$(OBJC) $(CCSHARED) $(CFLAGS) $(INCLUDES) -c $<
+
+
+# ----------------------------------------------------------------------
+# Rules for building the extension
+# ----------------------------------------------------------------------
+
+all: $(TARGET)
+
+# Convert the wrapper file into an object file
+
+$(WRAPOBJ) : $(WRAPFILE)
+	$(SWIGCC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(PERL_INCLUDE) $(PERL_FLAGS) $(WRAPFILE)
+
+$(WRAPFILE) : $(INTERFACE)
+	$(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIB) $(INTERFACE)
+
+$(TARGET): $(WRAPOBJ) $(ALLOBJS)
+	$(BUILD) $(WRAPOBJ) $(ALLOBJS) $(BUILD_LIBS) -o $(TARGET)
+
+clean:
+	rm -f $(COBJS) $(CXXOBJS) $(OBJCOBJS) $(WRAPOBJ) $(WRAPFILE) $(TARGET)
+
+
+
+
+
+
diff --git a/trunk/Lib/perl5/Makefile.pl b/trunk/Lib/perl5/Makefile.pl
new file mode 100644
index 0000000..05240f1
--- /dev/null
+++ b/trunk/Lib/perl5/Makefile.pl
@@ -0,0 +1,21 @@
+# File : Makefile.pl
+# MakeMaker file for a SWIG module.  Use this file if you are
+# producing a module for general use or distribution.
+#
+# 1.  Modify the file as appropriate. Replace $module with the
+#     real name of your module and wrapper file.
+# 2.  Run perl as 'perl Makefile.pl'
+# 3.  Type 'make' to build your module
+# 4.  Type 'make install' to install your module.
+# 
+# See "Programming Perl", 2nd. Ed, for more gory details than
+# you ever wanted to know.
+
+use ExtUtils::MakeMaker;
+WriteMakefile(
+     'NAME' => '$module',            # Name of your module
+     'LIBS' => [''],                 # Custom libraries (if any)
+     'OBJECT' => '$module_wrap.o'    # Object files
+);
+
+
diff --git a/trunk/Lib/perl5/attribute.i b/trunk/Lib/perl5/attribute.i
new file mode 100644
index 0000000..779716c
--- /dev/null
+++ b/trunk/Lib/perl5/attribute.i
@@ -0,0 +1 @@
+%include <typemaps/attribute.swg>
diff --git a/trunk/Lib/perl5/carrays.i b/trunk/Lib/perl5/carrays.i
new file mode 100644
index 0000000..8be67ab
--- /dev/null
+++ b/trunk/Lib/perl5/carrays.i
@@ -0,0 +1,2 @@
+%include <typemaps/carrays.swg>
+
diff --git a/trunk/Lib/perl5/cdata.i b/trunk/Lib/perl5/cdata.i
new file mode 100644
index 0000000..3679659
--- /dev/null
+++ b/trunk/Lib/perl5/cdata.i
@@ -0,0 +1 @@
+%include <typemaps/cdata.swg>
diff --git a/trunk/Lib/perl5/cmalloc.i b/trunk/Lib/perl5/cmalloc.i
new file mode 100644
index 0000000..248f06b
--- /dev/null
+++ b/trunk/Lib/perl5/cmalloc.i
@@ -0,0 +1 @@
+%include <typemaps/cmalloc.swg>
diff --git a/trunk/Lib/perl5/cni.i b/trunk/Lib/perl5/cni.i
new file mode 100644
index 0000000..c4d4eaf
--- /dev/null
+++ b/trunk/Lib/perl5/cni.i
@@ -0,0 +1,12 @@
+%warnfilter(SWIGWARN_PARSE_KEYWORD) java::lang::ref;
+
+%{
+#undef STATIC
+%}
+%include <gcj/cni.i>
+%{
+#undef TRUE
+#define TRUE 1
+%}
+
+%include <jstring.i>
diff --git a/trunk/Lib/perl5/cpointer.i b/trunk/Lib/perl5/cpointer.i
new file mode 100644
index 0000000..d824792
--- /dev/null
+++ b/trunk/Lib/perl5/cpointer.i
@@ -0,0 +1 @@
+%include <typemaps/cpointer.swg>
diff --git a/trunk/Lib/perl5/cstring.i b/trunk/Lib/perl5/cstring.i
new file mode 100644
index 0000000..ede9c59
--- /dev/null
+++ b/trunk/Lib/perl5/cstring.i
@@ -0,0 +1 @@
+%include <typemaps/cstring.swg>
diff --git a/trunk/Lib/perl5/exception.i b/trunk/Lib/perl5/exception.i
new file mode 100644
index 0000000..b786f25
--- /dev/null
+++ b/trunk/Lib/perl5/exception.i
@@ -0,0 +1,5 @@
+%include <typemaps/exception.swg>
+
+%insert("runtime") {
+  %define_as(SWIG_exception(code, msg), %block(%error(code, msg); SWIG_fail; ))
+}
diff --git a/trunk/Lib/perl5/extra-install.list b/trunk/Lib/perl5/extra-install.list
new file mode 100644
index 0000000..db93830
--- /dev/null
+++ b/trunk/Lib/perl5/extra-install.list
@@ -0,0 +1,2 @@
+# see top-level Makefile.in
+Makefile.pl noembed.h
diff --git a/trunk/Lib/perl5/factory.i b/trunk/Lib/perl5/factory.i
new file mode 100644
index 0000000..46a0a87
--- /dev/null
+++ b/trunk/Lib/perl5/factory.i
@@ -0,0 +1 @@
+%include <typemaps/factory.swg>
diff --git a/trunk/Lib/perl5/jstring.i b/trunk/Lib/perl5/jstring.i
new file mode 100644
index 0000000..1c179b7
--- /dev/null
+++ b/trunk/Lib/perl5/jstring.i
@@ -0,0 +1,48 @@
+%include <typemaps/valtypes.swg>
+
+%fragment(SWIG_AsVal_frag(jstring),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(jstring)(SV *obj, jstring *val)
+{
+  if (SvPOK(obj)) {
+    if (val) {
+      STRLEN len = 0;
+      char *cstr = SvPV(obj, len); 
+      *val = JvNewStringLatin1(cstr, len);
+    }
+    return SWIG_OK;
+  }
+  return SWIG_ERROR;
+}
+}
+
+%fragment(SWIG_From_frag(jstring),"header") {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(jstring)(jstring val)
+{
+  SV *obj = sv_newmortal();
+  if (!val) {
+    sv_setsv(obj, &PL_sv_undef);
+  } else {
+    jsize len = JvGetStringUTFLength(val);
+    if (!len) {
+      sv_setsv(obj, &PL_sv_undef);
+    } else {
+      char *tmp = %new_array(len, char);
+      JvGetStringUTFRegion(val, 0, len, tmp);
+      sv_setpvn(obj, tmp, len);
+      SvUTF8_on(obj);
+      %delete_array(tmp);
+    }
+  }
+  return obj;
+}
+}
+
+%typemaps_asvalfrom(%checkcode(STRING),
+		    %arg(SWIG_AsVal(jstring)), 
+		    %arg(SWIG_From(jstring)), 
+		    %arg(SWIG_AsVal_frag(jstring)), 
+		    %arg(SWIG_From_frag(jstring)), 
+		    java::lang::String *);
+
diff --git a/trunk/Lib/perl5/noembed.h b/trunk/Lib/perl5/noembed.h
new file mode 100644
index 0000000..a29de61
--- /dev/null
+++ b/trunk/Lib/perl5/noembed.h
@@ -0,0 +1,93 @@
+/* Workaround perl5 global namespace pollution. Note that undefining library
+ * functions like fopen will not solve the problem on all platforms as fopen
+ * might be a macro on Windows but not necessarily on other operating systems. */
+#ifdef do_open
+  #undef do_open
+#endif
+#ifdef do_close
+  #undef do_close
+#endif
+#ifdef scalar
+  #undef scalar
+#endif
+#ifdef list
+  #undef list
+#endif
+#ifdef apply
+  #undef apply
+#endif
+#ifdef convert
+  #undef convert
+#endif
+#ifdef Error
+  #undef Error
+#endif
+#ifdef form
+  #undef form
+#endif
+#ifdef vform
+  #undef vform
+#endif
+#ifdef LABEL
+  #undef LABEL
+#endif
+#ifdef METHOD
+  #undef METHOD
+#endif
+#ifdef Move
+  #undef Move
+#endif
+#ifdef yylex
+  #undef yylex
+#endif
+#ifdef yyparse
+  #undef yyparse
+#endif
+#ifdef yyerror
+  #undef yyerror
+#endif
+#ifdef invert
+  #undef invert
+#endif
+#ifdef ref
+  #undef ref
+#endif
+#ifdef read
+  #undef read
+#endif
+#ifdef write
+  #undef write
+#endif
+#ifdef eof
+  #undef eof
+#endif
+#ifdef bool
+  #undef bool
+#endif
+#ifdef close
+  #undef close
+#endif
+#ifdef rewind
+  #undef rewind
+#endif
+#ifdef free
+  #undef free
+#endif
+#ifdef malloc
+  #undef malloc
+#endif
+#ifdef calloc
+  #undef calloc
+#endif
+#ifdef Stat
+  #undef Stat
+#endif
+#ifdef check
+  #undef check
+#endif
+#ifdef seekdir
+  #undef seekdir
+#endif
+#ifdef open
+  #undef open
+#endif
diff --git a/trunk/Lib/perl5/perl5.swg b/trunk/Lib/perl5/perl5.swg
new file mode 100644
index 0000000..693c2b9
--- /dev/null
+++ b/trunk/Lib/perl5/perl5.swg
@@ -0,0 +1,42 @@
+/* ------------------------------------------------------------
+ * perl.swg
+ *
+ * Perl configuration module.
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ *  Inner macros 
+ * ------------------------------------------------------------ */
+%include <perlmacros.swg>
+
+/* ------------------------------------------------------------
+ *  The runtime part
+ * ------------------------------------------------------------ */
+%include <perlruntime.swg>
+
+/* ------------------------------------------------------------
+ *  Special user directives
+ * ------------------------------------------------------------ */
+%include <perluserdir.swg>
+
+/* ------------------------------------------------------------
+ *  Typemap specializations
+ * ------------------------------------------------------------ */
+%include <perltypemaps.swg>
+
+/* ------------------------------------------------------------
+ *  Overloaded operator support
+ * ------------------------------------------------------------ */
+%include <perlopers.swg>
+
+/* ------------------------------------------------------------
+ * Warnings for Perl keywords 
+ * ------------------------------------------------------------ */
+%include <perlkw.swg>
+
+/* ------------------------------------------------------------
+ * The Perl initialization function 
+ * ------------------------------------------------------------ */
+%include <perlinit.swg>
+
+
diff --git a/trunk/Lib/perl5/perlerrors.swg b/trunk/Lib/perl5/perlerrors.swg
new file mode 100644
index 0000000..024f037
--- /dev/null
+++ b/trunk/Lib/perl5/perlerrors.swg
@@ -0,0 +1,49 @@
+/* -----------------------------------------------------------------------------
+ * error manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGINTERN const char*
+SWIG_Perl_ErrorType(int code) {
+  const char* type = 0;
+  switch(code) {
+  case SWIG_MemoryError:
+    type = "MemoryError";
+    break;
+  case SWIG_IOError:
+    type = "IOError";
+    break;
+  case SWIG_RuntimeError:
+    type = "RuntimeError";
+    break;
+  case SWIG_IndexError:
+    type = "IndexError";
+    break;
+  case SWIG_TypeError:
+    type = "TypeError";
+    break;
+  case SWIG_DivisionByZero:
+    type = "ZeroDivisionError";
+    break;
+  case SWIG_OverflowError:
+    type = "OverflowError";
+    break;
+  case SWIG_SyntaxError:
+    type = "SyntaxError";
+    break;
+  case SWIG_ValueError:
+    type = "ValueError";
+    break;
+  case SWIG_SystemError:
+    type = "SystemError";
+    break;
+  case SWIG_AttributeError:
+    type = "AttributeError";
+    break;
+  default:
+    type = "RuntimeError";
+  }
+  return type;
+}
+
+
+
diff --git a/trunk/Lib/perl5/perlfragments.swg b/trunk/Lib/perl5/perlfragments.swg
new file mode 100644
index 0000000..45d25d1
--- /dev/null
+++ b/trunk/Lib/perl5/perlfragments.swg
@@ -0,0 +1,23 @@
+/*
+
+  Create a file with this name, 'perlfragments.swg', in your working
+  directory and add all the %fragments you want to take precedence
+  over the ones defined by default by swig.
+
+  For example, if you add:
+  
+  %fragment(SWIG_AsVal_frag(int),"header") {
+   SWIGINTERNINLINE int
+   SWIG_AsVal(int)(PyObject *obj, int *val)
+   { 
+     <your code here>;
+   }
+  }
+  
+  this will replace the code used to retrieve an integer value for all
+  the typemaps that need it, including:
+  
+    int, std::vector<int>, std::list<std::pair<int,int> >, etc.
+
+    
+*/
diff --git a/trunk/Lib/perl5/perlhead.swg b/trunk/Lib/perl5/perlhead.swg
new file mode 100644
index 0000000..5437af5
--- /dev/null
+++ b/trunk/Lib/perl5/perlhead.swg
@@ -0,0 +1,102 @@
+#ifdef __cplusplus
+/* Needed on some windows machines---since MS plays funny games with the header files under C++ */
+#include <math.h>
+#include <stdlib.h>
+extern "C" {
+#endif
+#include "EXTERN.h"
+#include "perl.h"
+#include "XSUB.h"
+
+/* Add in functionality missing in older versions of Perl. Much of this is based on Devel-PPPort on cpan. */
+
+/* Add PERL_REVISION, PERL_VERSION, PERL_SUBVERSION if missing */
+#ifndef PERL_REVISION
+#  if !defined(__PATCHLEVEL_H_INCLUDED__) && !(defined(PATCHLEVEL) && defined(SUBVERSION))
+#    define PERL_PATCHLEVEL_H_IMPLICIT
+#    include <patchlevel.h>
+#  endif
+#  if !(defined(PERL_VERSION) || (defined(SUBVERSION) && defined(PATCHLEVEL)))
+#    include <could_not_find_Perl_patchlevel.h>
+#  endif
+#  ifndef PERL_REVISION
+#    define PERL_REVISION       (5)
+#    define PERL_VERSION        PATCHLEVEL
+#    define PERL_SUBVERSION     SUBVERSION
+#  endif
+#endif
+
+#if defined(WIN32) && defined(PERL_OBJECT) && !defined(PerlIO_exportFILE)
+#define PerlIO_exportFILE(fh,fl) (FILE*)(fh)
+#endif
+
+#ifndef SvIOK_UV
+# define SvIOK_UV(sv)       (SvIOK(sv) && (SvUVX(sv) == SvIVX(sv)))
+#endif
+
+#ifndef SvUOK
+# define SvUOK(sv)           SvIOK_UV(sv)
+#endif
+
+#if ((PERL_VERSION < 4) || ((PERL_VERSION == 4) && (PERL_SUBVERSION <= 5)))
+#  define PL_sv_undef               sv_undef
+#  define PL_na	                    na
+#  define PL_errgv                  errgv
+#  define PL_sv_no                  sv_no
+#  define PL_sv_yes                 sv_yes
+#  define PL_markstack_ptr          markstack_ptr
+#endif
+
+#ifndef IVSIZE
+#  ifdef LONGSIZE
+#    define IVSIZE LONGSIZE
+#  else
+#    define IVSIZE 4 /* A bold guess, but the best we can make. */
+#  endif
+#endif
+
+#ifndef INT2PTR
+#  if (IVSIZE == PTRSIZE) && (UVSIZE == PTRSIZE)
+#    define PTRV                  UV
+#    define INT2PTR(any,d)        (any)(d)
+#  else
+#    if PTRSIZE == LONGSIZE
+#      define PTRV                unsigned long
+#    else
+#      define PTRV                unsigned
+#    endif
+#    define INT2PTR(any,d)        (any)(PTRV)(d)
+#  endif
+
+#  define NUM2PTR(any,d)  (any)(PTRV)(d)
+#  define PTR2IV(p)       INT2PTR(IV,p)
+#  define PTR2UV(p)       INT2PTR(UV,p)
+#  define PTR2NV(p)       NUM2PTR(NV,p)
+
+#  if PTRSIZE == LONGSIZE
+#    define PTR2ul(p)     (unsigned long)(p)
+#  else
+#    define PTR2ul(p)     INT2PTR(unsigned long,p)
+#  endif
+#endif /* !INT2PTR */
+
+#ifndef SvPV_nolen
+# define SvPV_nolen(x) SvPV(x,PL_na)
+#endif
+
+#ifndef get_sv
+#  define get_sv perl_get_sv
+#endif
+
+#ifndef ERRSV
+#  define ERRSV get_sv("@",FALSE)
+#endif
+
+#ifndef pTHX_
+#define pTHX_
+#endif   
+
+#include <string.h>
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/perl5/perlinit.swg b/trunk/Lib/perl5/perlinit.swg
new file mode 100644
index 0000000..5509215
--- /dev/null
+++ b/trunk/Lib/perl5/perlinit.swg
@@ -0,0 +1,76 @@
+
+/* Export the SWIG initialization function */
+%header %{
+#ifdef __cplusplus
+extern "C"
+#endif
+#ifndef PERL_OBJECT
+#ifndef MULTIPLICITY
+SWIGEXPORT void SWIG_init (CV* cv);
+#else
+SWIGEXPORT void SWIG_init (pTHXo_ CV* cv);
+#endif
+#else
+SWIGEXPORT void SWIG_init (CV *cv, CPerlObj *);
+#endif
+%}
+
+/* Module initialization function */
+
+%insert(init) "swiginit.swg"
+
+%init %{
+
+#ifdef __cplusplus
+extern "C"
+#endif
+
+XS(SWIG_init) {
+    dXSARGS;
+    int i;
+
+    SWIG_InitializeModule(0);
+
+    /* Install commands */
+    for (i = 0; swig_commands[i].name; i++) {
+      newXS((char*) swig_commands[i].name,swig_commands[i].wrapper, (char*)__FILE__);
+    }
+
+    /* Install variables */
+    for (i = 0; swig_variables[i].name; i++) {
+      SV *sv;
+      sv = get_sv((char*) swig_variables[i].name, TRUE | 0x2 | GV_ADDMULTI);
+      if (swig_variables[i].type) {
+	SWIG_MakePtr(sv,(void *)1, *swig_variables[i].type,0);
+      } else {
+	sv_setiv(sv,(IV) 0);
+      }
+      swig_create_magic(sv, (char *) swig_variables[i].name, swig_variables[i].set, swig_variables[i].get); 
+    }
+
+    /* Install constant */
+    for (i = 0; swig_constants[i].type; i++) {
+      SV *sv;
+      sv = get_sv((char*)swig_constants[i].name, TRUE | 0x2 | GV_ADDMULTI);
+      switch(swig_constants[i].type) {
+      case SWIG_INT:
+	sv_setiv(sv, (IV) swig_constants[i].lvalue);
+	break;
+      case SWIG_FLOAT:
+	sv_setnv(sv, (double) swig_constants[i].dvalue);
+	break;
+      case SWIG_STRING:
+	sv_setpv(sv, (char *) swig_constants[i].pvalue);
+	break;
+      case SWIG_POINTER:
+	SWIG_MakePtr(sv, swig_constants[i].pvalue, *(swig_constants[i].ptype),0);
+	break;
+      case SWIG_BINARY:
+	SWIG_MakePackedObj(sv, swig_constants[i].pvalue, swig_constants[i].lvalue, *(swig_constants[i].ptype));
+	break;
+      default:
+	break;
+      }
+      SvREADONLY_on(sv);
+    }
+%}
diff --git a/trunk/Lib/perl5/perlkw.swg b/trunk/Lib/perl5/perlkw.swg
new file mode 100644
index 0000000..00648e0
--- /dev/null
+++ b/trunk/Lib/perl5/perlkw.swg
@@ -0,0 +1,251 @@
+/* Warnings for Perl keywords */
+#define PERLKW(x) %keywordwarn("'" `x` "' is a perl keyword")  `x`
+#define PERLBN(x) %builtinwarn("'" `x` "' conflicts with a built-in name in perl")  "::" `x`
+
+
+/*
+
+  From  http://www.rocketaware.com/perl/perlfunc/
+
+*/
+
+/* Functions for SCALARs or strings*/
+PERLBN(chomp);
+PERLBN(chop);
+PERLBN(chr);
+PERLBN(crypt);
+PERLBN(hex);
+PERLBN(index);
+PERLBN(lc);
+PERLBN(lcfirst);
+PERLBN(length);
+PERLBN(oct);
+PERLBN(ord);
+PERLBN(pack);
+PERLBN(reverse);
+PERLBN(rindex);
+PERLBN(sprintf);
+PERLBN(substr);
+PERLBN(uc);
+PERLBN(ucfirst);
+
+/* Regular expressions and pattern matching */
+PERLBN(m);
+PERLBN(pos);
+PERLBN(quotemeta);
+PERLBN(split);
+PERLBN(study);
+
+/* Numeric functions */
+PERLBN(abs);
+PERLBN(atan2);
+PERLBN(cos);
+PERLBN(exp);
+PERLBN(hex);
+PERLBN(int);
+PERLBN(log);
+PERLBN(oct);
+PERLBN(rand);
+PERLBN(sin);
+PERLBN(sqrt);
+PERLBN(srand);
+
+
+/* Functions for real @ARRAYs*/
+PERLBN(pop);
+PERLBN(push);
+PERLBN(shift);
+PERLBN(splice);
+PERLBN(unshift);
+
+/* Functions for list data*/ 
+PERLBN(grep);
+PERLBN(join);
+PERLBN(map);
+PERLBN(qw);
+PERLBN(reverse);
+PERLBN(sort);
+PERLBN(unpack);
+
+
+/* Functions for real %HASHes*/
+PERLBN(delete);
+PERLBN(each);
+PERLBN(exists);
+PERLBN(keys);
+PERLBN(values);
+
+
+/* Input and output functions*/
+
+PERLBN(binmode);
+PERLBN(close);
+PERLBN(closedir);
+PERLBN(dbmclose);
+PERLBN(dbmopen);
+PERLBN(die);
+PERLBN(eof);
+PERLBN(fileno);
+PERLBN(flock);
+PERLBN(format);
+PERLBN(getc);
+PERLBN(print);
+PERLBN(printf);
+PERLBN(read);
+PERLBN(readdir);
+PERLBN(rewinddir);
+PERLBN(seek);
+PERLBN(seekdir);
+PERLBN(select);
+PERLBN(syscall);
+PERLBN(sysread);
+PERLBN(sysseek);
+PERLBN(syswrite);
+PERLBN(tell);
+PERLBN(telldir);
+PERLBN(truncate);
+PERLBN(warn);
+PERLBN(write);
+
+
+/* Functions for fixed length data or records*/
+PERLBN(pack);
+PERLBN(read);
+PERLBN(syscall);
+PERLBN(sysread);
+PERLBN(syswrite);
+PERLBN(unpack);
+PERLBN(vec);
+
+
+/* Functions for filehandles, files, or directories */
+PERLBN(chdir);
+PERLBN(chmod);
+PERLBN(chown);
+PERLBN(chroot);
+PERLBN(fcntl);
+PERLBN(glob);
+PERLBN(ioctl);
+PERLBN(link);
+PERLBN(lstat);
+PERLBN(mkdir);
+PERLBN(open);
+PERLBN(opendir);
+PERLBN(readlink);
+PERLBN(rename);
+PERLBN(rmdir);
+PERLBN(stat);
+PERLBN(symlink);
+PERLBN(umask);
+PERLBN(unlink);
+PERLBN(utime);
+
+
+/* Keywords related to the control flow of your perl program */
+PERLKW(caller);
+PERLKW(continue);
+PERLKW(die);
+PERLKW(do);
+PERLKW(dump);
+PERLKW(eval);
+PERLKW(exit);
+PERLKW(goto);
+PERLKW(last);
+PERLKW(next);
+PERLKW(redo);
+PERLKW(return);
+PERLKW(sub);
+PERLKW(wantarray);
+
+
+/* Keywords related to scoping */
+PERLKW(caller);
+PERLKW(import);
+PERLKW(local);
+PERLKW(my);
+PERLKW(package);
+PERLKW(use);
+
+
+/* Miscellaneous functions */
+PERLBN("defined");
+PERLBN(dump);
+PERLBN(eval);
+PERLBN(formline);
+PERLBN(local);
+PERLBN(my);
+PERLBN(reset);
+PERLBN(scalar);
+PERLBN(undef);
+PERLBN(wantarray);
+
+
+/* Functions for processes and process groups */
+PERLBN(alarm);
+PERLBN(exec);
+PERLBN(fork);
+PERLBN(getpgrp);
+PERLBN(getppid);
+PERLBN(getpriority);
+PERLBN(kill);
+PERLBN(pipe);
+PERLBN(setpgrp);
+PERLBN(setpriority);
+PERLBN(sleep);
+PERLBN(system);
+PERLBN(times);
+PERLBN(wait);
+PERLBN(waitpid);
+
+
+/* Keywords related to perl modules */
+PERLKW(do);
+PERLKW(import);
+PERLKW(no);
+PERLKW(package);
+PERLKW(require);
+PERLKW(use);
+
+
+/* Keywords related to classes and object-orientedness */
+PERLKW(bless);
+PERLKW(dbmclose);
+PERLKW(dbmopen);
+PERLKW(package);
+PERLKW(ref);
+PERLKW(tie);
+PERLKW(tied);
+PERLKW(untie);
+PERLKW(use);
+
+/* Functions new in perl5 */
+PERLBN(abs);
+PERLBN(bless);
+PERLBN(chomp);
+PERLBN(chr);
+PERLBN(exists);
+PERLBN(formline);
+PERLBN(glob);
+PERLBN(import);
+PERLBN(lc);
+PERLBN(lcfirst);
+PERLBN(map);
+PERLBN(my);
+PERLBN(no);
+PERLBN(prototype);
+PERLBN(qx);
+PERLBN(qw);
+PERLBN(readline);
+PERLBN(readpipe);
+PERLBN(ref);
+PERLBN(sub);
+PERLBN(sysopen);
+PERLBN(tie);
+PERLBN(tied);
+PERLBN(uc);
+PERLBN(ucfirst);
+PERLBN(untie);
+PERLBN(use);
+
+#undef PERLKW
+#undef PERLBN
diff --git a/trunk/Lib/perl5/perlmacros.swg b/trunk/Lib/perl5/perlmacros.swg
new file mode 100644
index 0000000..4917f6e
--- /dev/null
+++ b/trunk/Lib/perl5/perlmacros.swg
@@ -0,0 +1,2 @@
+%include <typemaps/swigmacros.swg>
+
diff --git a/trunk/Lib/perl5/perlmain.i b/trunk/Lib/perl5/perlmain.i
new file mode 100644
index 0000000..f224b9c
--- /dev/null
+++ b/trunk/Lib/perl5/perlmain.i
@@ -0,0 +1,85 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * perlmain.i
+ *
+ * Code to statically rebuild perl5.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef AUTODOC
+%subsection "perlmain.i"
+%text %{
+This module provides support for building a new version of the
+Perl executable.  This will be necessary on systems that do
+not support shared libraries and may be necessary with C++
+extensions.  
+
+This module may only build a stripped down version of the
+Perl executable.   Thus, it may be necessary (or desirable)
+to hand-edit this file for your particular application.  To
+do this, simply copy this file from swig_lib/perl5/perlmain.i
+to your working directory and make the appropriate modifications.
+
+This library file works with Perl 5.003.  It may work with earlier
+versions, but it hasn't been tested.  As far as I know, this
+library is C++ safe.
+%}
+#endif
+
+%{
+
+static void xs_init _((pTHX));
+static PerlInterpreter *my_perl;
+
+int perl_eval(char *string) {
+  char *argv[2];
+  argv[0] = string;
+  argv[1] = (char *) 0;
+  return perl_call_argv("eval",0,argv);
+}
+
+int
+main(int argc, char **argv, char **env)
+{
+    int exitstatus;
+
+    my_perl = perl_alloc();
+    if (!my_perl)
+       exit(1);
+    perl_construct( my_perl );
+
+    exitstatus = perl_parse( my_perl, xs_init, argc, argv, (char **) NULL );
+    if (exitstatus)
+	exit( exitstatus );
+
+    /* Initialize all of the module variables */
+
+    exitstatus = perl_run( my_perl );
+
+    perl_destruct( my_perl );
+    perl_free( my_perl );
+
+    exit( exitstatus );
+}
+
+/* Register any extra external extensions */
+
+/* Do not delete this line--writemain depends on it */
+/* EXTERN_C void boot_DynaLoader _((CV* cv)); */
+
+static void
+xs_init(pTHX)
+{
+/*  dXSUB_SYS; */
+    char *file = __FILE__;
+    {
+      /*        newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); */
+	newXS(SWIG_name, SWIG_init, file);
+#ifdef SWIGMODINIT
+	SWIGMODINIT
+#endif
+    }
+}
+
+%}
diff --git a/trunk/Lib/perl5/perlopers.swg b/trunk/Lib/perl5/perlopers.swg
new file mode 100644
index 0000000..e7d13b6
--- /dev/null
+++ b/trunk/Lib/perl5/perlopers.swg
@@ -0,0 +1,54 @@
+/* ------------------------------------------------------------
+ * Overloaded operator support
+ * ------------------------------------------------------------ */
+
+#ifdef __cplusplus
+
+// These are auto-supported by the Perl-module
+%rename(__plusplus__) *::operator++;
+%rename(__minmin__)   *::operator--;
+%rename(__add__)      *::operator+;
+%rename(__sub__)      *::operator-;
+%rename(__neg__)      *::operator-();
+%rename(__neg__)      *::operator-() const;
+%rename(__mul__)      *::operator*;
+%rename(__div__)      *::operator/;
+%rename(__eq__)       *::operator==;
+%rename(__ne__)       *::operator!=;
+%rename(__mod__)      *::operator%;
+%rename(__gt__)       *::operator>;
+%rename(__lt__)       *::operator<;
+%rename(__not__)      *::operator!;
+%rename(__le__)       *::operator<=;
+%rename(__ge__)       *::operator>=;
+%rename(__and__)      *::operator&;
+%rename(__or__)       *::operator|;
+%rename(__iadd__)     *::operator+=;  
+%rename(__isub__)     *::operator-=;  
+
+// These are renamed, but no test exists in operator_overload_runme.pl
+%ignoreoperator(EQ)         operator=;
+
+// These are renamed, but no 'use overload...' is added
+%rename(__lshift__)   *::operator<<;
+%rename(__rshift__)   *::operator>>;
+%rename(__xor__)      *::operator^;
+%rename(__invert__)   *::operator~;
+%rename(__call__)     *::operator();
+
+/* Ignored operators */
+%ignoreoperator(LAND)       operator&&;
+%ignoreoperator(LOR)        operator||;
+%ignoreoperator(MULEQ)      operator*=;  
+%ignoreoperator(DIVEQ)      operator/=;  
+%ignoreoperator(MODEQ)      operator%=;  
+%ignoreoperator(LSHIFTEQ)   operator<<=; 
+%ignoreoperator(RSHIFTEQ)   operator>>=; 
+%ignoreoperator(ANDEQ)      operator&=;  
+%ignoreoperator(OREQ)       operator|=;  
+%ignoreoperator(XOREQ)      operator^=;  
+%ignoreoperator(ARROWSTAR)  operator->*;
+%ignoreoperator(INDEX)      operator[];
+
+
+#endif /* __cplusplus */
diff --git a/trunk/Lib/perl5/perlprimtypes.swg b/trunk/Lib/perl5/perlprimtypes.swg
new file mode 100644
index 0000000..ae7bb38
--- /dev/null
+++ b/trunk/Lib/perl5/perlprimtypes.swg
@@ -0,0 +1,328 @@
+/* ------------------------------------------------------------
+ * Primitive Types
+ * ------------------------------------------------------------ */
+
+/* bool */
+
+%fragment(SWIG_From_frag(bool),"header") {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(bool)(bool value)
+{    
+  SV *obj = sv_newmortal();
+  if (value) {
+    sv_setsv(obj, &PL_sv_yes);
+  } else {
+    sv_setsv(obj, &PL_sv_no); 
+  }
+  return obj;
+}
+}
+
+%fragment(SWIG_AsVal_frag(bool),"header",
+	  fragment="SWIG_CanCastAsInteger") {
+SWIGINTERN int
+SWIG_AsVal_dec(bool)(SV *obj, bool* val)
+{
+  if (obj == &PL_sv_yes) {
+    if (val) *val = true;
+    return SWIG_OK;
+  } else if (obj == &PL_sv_no) { 
+    if (val) *val = false;
+    return SWIG_OK;
+  } else {
+    if (val) *val = SvTRUE(obj) ? true: false;
+    return SWIG_AddCast(SWIG_OK);    
+  }
+  return SWIG_TypeError;
+}
+}
+
+
+/* long */
+
+%fragment(SWIG_From_frag(long),"header") {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(long)(long value)
+{    
+  SV *obj = sv_newmortal();
+  sv_setiv(obj, (IV) value);
+  return obj;
+}
+}
+
+%fragment(SWIG_AsVal_frag(long),"header",
+	  fragment="SWIG_CanCastAsInteger") {
+SWIGINTERN int
+SWIG_AsVal_dec(long)(SV *obj, long* val)
+{
+  if (SvIOK(obj)) {
+    if (val) *val = SvIV(obj);
+    return SWIG_OK;
+  } else {
+    int dispatch = 0;
+    const char *nptr = SvPV_nolen(obj);
+    if (nptr) {
+      char *endptr;
+      long v;
+      errno = 0;
+      v = strtol(nptr, &endptr,0);
+      if (errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_Str2NumCast(SWIG_OK);
+	}
+      }
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) {
+	if (val) *val = (long)(d);
+	return res;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* unsigned long */
+
+%fragment(SWIG_From_frag(unsigned long),"header",
+	  fragment=SWIG_AsVal_frag(double)) {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(unsigned long)(unsigned long value)
+{    
+  SV *obj = sv_newmortal();
+  sv_setuv(obj, (UV) value);
+  return obj;
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long),"header",
+	  fragment="SWIG_CanCastAsInteger") {
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long)(SV *obj, unsigned long *val) 
+{
+  if (SvUOK(obj)) {
+    if (val) *val = SvUV(obj);
+    return SWIG_OK;
+  } else  if (SvIOK(obj)) {
+    long v = SvIV(obj);
+    if (v >= 0) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }
+  } else {
+    int dispatch = 0;
+    const char *nptr = SvPV_nolen(obj);
+    if (nptr) {
+      char *endptr;
+      unsigned long v;
+      errno = 0;
+      v = strtoul(nptr, &endptr,0);
+      if (errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_Str2NumCast(SWIG_OK);
+	}
+      }
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) {
+	if (val) *val = (unsigned long)(d);
+	return res;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* long long */
+
+%fragment(SWIG_From_frag(long long),"header",
+	  fragment=SWIG_From_frag(long),
+	  fragment="<limits.h>",
+	  fragment="<stdio.h>") {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(long long)(long long value)
+{
+  if (((long long) LONG_MIN <= value) && (value <= (long long) LONG_MAX)) {
+    return SWIG_From(long)(%numeric_cast(value,long));
+  } else {    
+    char temp[256]; 
+    SV *obj = sv_newmortal();
+    sprintf(temp, "%lld", value);
+    sv_setpv(obj, temp);
+    return obj;
+  }
+}
+}
+
+%fragment(SWIG_AsVal_frag(long long),"header",
+	  fragment="<limits.h>",
+	  fragment="<stdlib.h>",
+	  fragment="SWIG_CanCastAsInteger") {
+
+SWIGINTERN int
+SWIG_AsVal_dec(long long)(SV *obj, long long *val)
+{
+  if (SvIOK(obj)) {
+    if (val) *val = SvIV(obj);
+    return SWIG_OK;
+  } else {
+    int dispatch = 0;
+    const char *nptr = SvPV_nolen(obj);
+    if (nptr) {
+      char *endptr;
+      long long v;
+      errno = 0;
+      v = strtoll(nptr, &endptr,0);
+      if (errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_Str2NumCast(SWIG_OK);
+	}
+      }
+    }
+    if (!dispatch) {
+      const double mant_max = 1LL << DBL_MANT_DIG;
+      const double mant_min = -mant_max;
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, mant_min, mant_max)) {
+	if (val) *val = (long long)(d);
+	return res;
+      }
+    }
+  }
+  return SWIG_TypeError; 
+}
+}
+
+/* unsigned long long */
+
+%fragment(SWIG_From_frag(unsigned long long),"header",
+	  fragment=SWIG_From_frag(long long),
+	  fragment="<limits.h>",
+	  fragment="<stdio.h>") {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(unsigned long long)(unsigned long long value)
+{
+  if (value < (unsigned long long) LONG_MAX) {
+    return SWIG_From(long long)(%numeric_cast(value, long long));
+  } else {
+    char temp[256]; 
+    SV *obj = sv_newmortal();
+    sprintf(temp, "%llu", value);
+    sv_setpv(obj, temp);
+    return obj;
+  }
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long long),"header",
+	  fragment="<limits.h>",
+	  fragment="<stdlib.h>",
+	  fragment="SWIG_CanCastAsInteger") {
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long long)(SV *obj, unsigned long long *val)
+{ 
+  if (SvUOK(obj)) {
+    if (val) *val = SvUV(obj);
+    return SWIG_OK;
+  } else  if (SvIOK(obj)) {
+    long v = SvIV(obj);
+    if (v >= 0) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }
+  } else {
+    int dispatch = 0;
+    const char *nptr = SvPV_nolen(obj);
+    if (nptr) {
+      char *endptr;
+      unsigned long long v;
+      errno = 0;
+      v = strtoull(nptr, &endptr,0);
+      if (errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_Str2NumCast(SWIG_OK);
+	}
+      }
+    }
+    if (!dispatch) {
+      const double mant_max = 1LL << DBL_MANT_DIG;
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, mant_max)) {
+	if (val) *val = (unsigned long long)(d);
+	return res;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* double */
+
+%fragment(SWIG_From_frag(double),"header") {
+SWIGINTERNINLINE SV *
+SWIG_From_dec(double)(double value)
+{    
+  SV *obj = sv_newmortal();
+  sv_setnv(obj, value);
+  return obj;
+}
+}
+
+%fragment(SWIG_AsVal_frag(double),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(double)(SV *obj, double *val)
+{
+  if (SvNIOK(obj)) {
+    if (val) *val = SvNV(obj);
+    return SWIG_OK;
+  } else if (SvIOK(obj)) {
+    if (val) *val = (double) SvIV(obj);
+    return SWIG_AddCast(SWIG_OK);
+  } else {
+    const char *nptr = SvPV_nolen(obj);
+    if (nptr) {
+      char *endptr;
+      double v = strtod(nptr, &endptr);
+      if (errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_Str2NumCast(SWIG_OK);
+	}
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
diff --git a/trunk/Lib/perl5/perlrun.swg b/trunk/Lib/perl5/perlrun.swg
new file mode 100644
index 0000000..54d098d
--- /dev/null
+++ b/trunk/Lib/perl5/perlrun.swg
@@ -0,0 +1,467 @@
+/* -----------------------------------------------------------------------------
+ * perlrun.swg
+ *
+ * This file contains the runtime support for Perl modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef PERL_OBJECT
+#define SWIG_PERL_OBJECT_DECL CPerlObj *SWIGUNUSEDPARM(pPerl),
+#define SWIG_PERL_OBJECT_CALL pPerl,
+#else
+#define SWIG_PERL_OBJECT_DECL
+#define SWIG_PERL_OBJECT_CALL
+#endif
+
+/* Common SWIG API */
+
+/* for raw pointers */
+#define SWIG_ConvertPtr(obj, pp, type, flags)           SWIG_Perl_ConvertPtr(SWIG_PERL_OBJECT_CALL obj, pp, type, flags)
+#define SWIG_NewPointerObj(p, type, flags)              SWIG_Perl_NewPointerObj(SWIG_PERL_OBJECT_CALL p, type, flags)
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, p, s, type)             SWIG_Perl_ConvertPacked(SWIG_PERL_OBJECT_CALL obj, p, s, type)
+#define SWIG_NewPackedObj(p, s, type)	                SWIG_Perl_NewPackedObj(SWIG_PERL_OBJECT_CALL p, s, type)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)
+
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_ConvertPtr(obj, pptr, type, 0)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_NewPointerObj(ptr, type, 0)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_NewPackedObj(ptr, sz, type)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_Perl_GetModule()
+#define SWIG_SetModule(clientdata, pointer)             SWIG_Perl_SetModule(pointer)
+
+
+/* Error manipulation */
+
+#define SWIG_ErrorType(code)                            SWIG_Perl_ErrorType(code)               
+#define SWIG_Error(code, msg)            		sv_setpvf(GvSV(PL_errgv),"%s %s\n", SWIG_ErrorType(code), msg)
+#define SWIG_fail                        		goto fail						    
+
+/* Perl-specific SWIG API */
+
+#define SWIG_MakePtr(sv, ptr, type, flags)              SWIG_Perl_MakePtr(SWIG_PERL_OBJECT_CALL sv, ptr, type, flags)
+#define SWIG_MakePackedObj(sv, p, s, type)	        SWIG_Perl_MakePackedObj(SWIG_PERL_OBJECT_CALL sv, p, s, type)
+#define SWIG_SetError(str)                              SWIG_Error(SWIG_RuntimeError, str)
+
+
+#define SWIG_PERL_DECL_ARGS_1(arg1)                     (SWIG_PERL_OBJECT_DECL arg1)
+#define SWIG_PERL_CALL_ARGS_1(arg1)                     (SWIG_PERL_OBJECT_CALL arg1)
+#define SWIG_PERL_DECL_ARGS_2(arg1, arg2)               (SWIG_PERL_OBJECT_DECL arg1, arg2)
+#define SWIG_PERL_CALL_ARGS_2(arg1, arg2)               (SWIG_PERL_OBJECT_CALL arg1, arg2)
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+/* For backward compatibility only */
+#define SWIG_POINTER_EXCEPTION  0
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define SWIG_OWNER   SWIG_POINTER_OWN
+#define SWIG_SHADOW  SWIG_OWNER << 1
+
+#define SWIG_MAYBE_PERL_OBJECT SWIG_PERL_OBJECT_DECL
+
+/* SWIG Perl macros */
+
+/* Macro to declare an XS function */
+#ifndef XSPROTO
+#   define XSPROTO(name) void name(pTHX_ CV* cv)
+#endif
+
+/* Macro to call an XS function */
+#ifdef PERL_OBJECT 
+#  define SWIG_CALLXS(_name) _name(cv,pPerl) 
+#else 
+#  ifndef MULTIPLICITY 
+#    define SWIG_CALLXS(_name) _name(cv) 
+#  else 
+#    define SWIG_CALLXS(_name) _name(PERL_GET_THX, cv) 
+#  endif 
+#endif 
+
+#ifdef PERL_OBJECT
+#define MAGIC_PPERL  CPerlObj *pPerl = (CPerlObj *) this;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+typedef int (CPerlObj::*SwigMagicFunc)(SV *, MAGIC *);
+#ifdef __cplusplus
+}
+#endif
+
+#define SWIG_MAGIC(a,b) (SV *a, MAGIC *b)
+#define SWIGCLASS_STATIC
+
+#else /* PERL_OBJECT */
+
+#define MAGIC_PPERL
+#define SWIGCLASS_STATIC static SWIGUNUSED
+
+#ifndef MULTIPLICITY
+#define SWIG_MAGIC(a,b) (SV *a, MAGIC *b)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+typedef int (*SwigMagicFunc)(SV *, MAGIC *);
+#ifdef __cplusplus
+}
+#endif
+
+#else /* MULTIPLICITY */
+
+#define SWIG_MAGIC(a,b) (struct interpreter *interp, SV *a, MAGIC *b)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+typedef int (*SwigMagicFunc)(struct interpreter *, SV *, MAGIC *);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MULTIPLICITY */
+#endif /* PERL_OBJECT */
+
+/* Workaround for bug in perl 5.6.x croak and earlier */
+#if (PERL_VERSION < 8)
+#  ifdef PERL_OBJECT
+#    define SWIG_croak_null() SWIG_Perl_croak_null(pPerl)
+static void SWIG_Perl_croak_null(CPerlObj *pPerl)
+#  else
+static void SWIG_croak_null()
+#  endif
+{
+  SV *err=ERRSV;
+#  if (PERL_VERSION < 6)
+  croak("%_", err);
+#  else
+  if (SvOK(err) && !SvROK(err)) croak("%_", err);
+  croak(Nullch);
+#  endif
+}
+#else
+#  define SWIG_croak_null() croak(Nullch)
+#endif
+
+
+/* 
+   Define how strict is the cast between strings and integers/doubles
+   when overloading between these types occurs.
+   
+   The default is making it as strict as possible by using SWIG_AddCast
+   when needed.
+   
+   You can use -DSWIG_PERL_NO_STRICT_STR2NUM at compilation time to
+   disable the SWIG_AddCast, making the casting between string and
+   numbers less strict.
+
+   In the end, we try to solve the overloading between strings and
+   numerical types in the more natural way, but if you can avoid it,
+   well, avoid it using %rename, for example.
+*/
+#ifndef SWIG_PERL_NO_STRICT_STR2NUM
+# ifndef SWIG_PERL_STRICT_STR2NUM
+#  define SWIG_PERL_STRICT_STR2NUM
+# endif
+#endif
+#ifdef SWIG_PERL_STRICT_STR2NUM
+/* string takes precedence */
+#define SWIG_Str2NumCast(x) SWIG_AddCast(x)  
+#else
+/* number takes precedence */
+#define SWIG_Str2NumCast(x) x
+#endif
+
+
+
+#include <stdlib.h>
+
+SWIGRUNTIME const char *
+SWIG_Perl_TypeProxyName(const swig_type_info *type) {
+  if (!type) return NULL;
+  if (type->clientdata != NULL) {
+    return (const char*) type->clientdata;
+  } 
+  else {
+    return type->name;
+  }
+}
+
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeProxyCheck(const char *c, swig_type_info *ty) {
+  SWIG_TypeCheck_Template(( (!iter->type->clientdata && (strcmp(iter->type->name, c) == 0)) 
+			    || (iter->type->clientdata && (strcmp((char*)iter->type->clientdata, c) == 0))), ty);
+}
+
+
+/* Function for getting a pointer value */
+
+SWIGRUNTIME int
+SWIG_Perl_ConvertPtr(SWIG_MAYBE_PERL_OBJECT SV *sv, void **ptr, swig_type_info *_t, int flags) {
+  swig_cast_info *tc;
+  void *voidptr = (void *)0;
+  SV *tsv = 0;
+  /* If magical, apply more magic */
+  if (SvGMAGICAL(sv))
+    mg_get(sv);
+
+  /* Check to see if this is an object */
+  if (sv_isobject(sv)) {
+    IV tmp = 0;
+    tsv = (SV*) SvRV(sv);
+    if ((SvTYPE(tsv) == SVt_PVHV)) {
+      MAGIC *mg;
+      if (SvMAGICAL(tsv)) {
+        mg = mg_find(tsv,'P');
+        if (mg) {
+          sv = mg->mg_obj;
+          if (sv_isobject(sv)) {
+	    tsv = (SV*)SvRV(sv);
+            tmp = SvIV(tsv);
+          }
+        }
+      } else {
+        return SWIG_ERROR;
+      }
+    } else {
+      tmp = SvIV(tsv);
+    }
+    voidptr = INT2PTR(void *,tmp);
+  } else if (! SvOK(sv)) {            /* Check for undef */
+    *(ptr) = (void *) 0;
+    return SWIG_OK;
+  } else if (SvTYPE(sv) == SVt_RV) {  /* Check for NULL pointer */
+    if (!SvROK(sv)) {
+      *(ptr) = (void *) 0;
+      return SWIG_OK;
+    } else {
+      return SWIG_ERROR;
+    }
+  } else {                            /* Don't know what it is */
+    return SWIG_ERROR;
+  }
+  if (_t) {
+    /* Now see if the types match */
+    char *_c = HvNAME(SvSTASH(SvRV(sv)));
+    tc = SWIG_TypeProxyCheck(_c,_t);
+    if (!tc) {
+      return SWIG_ERROR;
+    }
+    {
+      int newmemory = 0;
+      *ptr = SWIG_TypeCast(tc,voidptr,&newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+    }
+  } else {
+    *ptr = voidptr;
+  }
+
+  /* 
+   *  DISOWN implementation: we need a perl guru to check this one.
+   */
+  if (tsv && (flags & SWIG_POINTER_DISOWN)) {
+    /* 
+     *  almost copy paste code from below SWIG_POINTER_OWN setting
+     */
+    SV *obj = sv;
+    HV *stash = SvSTASH(SvRV(obj));
+    GV *gv = *(GV**) hv_fetch(stash, "OWNER", 5, TRUE);
+    if (isGV(gv)) {
+      HV *hv = GvHVn(gv);
+      /*
+       * To set ownership (see below), a newSViv(1) entry is added. 
+       * Hence, to remove ownership, we delete the entry.
+       */
+      if (hv_exists_ent(hv, obj, 0)) {
+	hv_delete_ent(hv, obj, 0, 0);
+      }
+    }
+  }
+  return SWIG_OK;
+}
+
+SWIGRUNTIME void
+SWIG_Perl_MakePtr(SWIG_MAYBE_PERL_OBJECT SV *sv, void *ptr, swig_type_info *t, int flags) {
+  if (ptr && (flags & SWIG_SHADOW)) {
+    SV *self;
+    SV *obj=newSV(0);
+    HV *hash=newHV();
+    HV *stash;
+    sv_setref_pv(obj, (char *) SWIG_Perl_TypeProxyName(t), ptr);
+    stash=SvSTASH(SvRV(obj));
+    if (flags & SWIG_POINTER_OWN) {
+      HV *hv;
+      GV *gv=*(GV**)hv_fetch(stash, "OWNER", 5, TRUE);
+      if (!isGV(gv))
+        gv_init(gv, stash, "OWNER", 5, FALSE);
+      hv=GvHVn(gv);
+      hv_store_ent(hv, obj, newSViv(1), 0);
+    }
+    sv_magic((SV *)hash, (SV *)obj, 'P', Nullch, 0);
+    SvREFCNT_dec(obj);
+    self=newRV_noinc((SV *)hash);
+    sv_setsv(sv, self);
+    SvREFCNT_dec((SV *)self);
+    sv_bless(sv, stash);
+  }
+  else {
+    sv_setref_pv(sv, (char *) SWIG_Perl_TypeProxyName(t), ptr);
+  }
+}
+
+SWIGRUNTIMEINLINE SV *
+SWIG_Perl_NewPointerObj(SWIG_MAYBE_PERL_OBJECT void *ptr, swig_type_info *t, int flags) {
+  SV *result = sv_newmortal();
+  SWIG_MakePtr(result, ptr, t, flags);
+  return result;
+}
+
+SWIGRUNTIME void
+SWIG_Perl_MakePackedObj(SWIG_MAYBE_PERL_OBJECT SV *sv, void *ptr, int sz, swig_type_info *type) {
+  char result[1024];
+  char *r = result;
+  if ((2*sz + 1 + strlen(SWIG_Perl_TypeProxyName(type))) > 1000) return;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  strcpy(r,SWIG_Perl_TypeProxyName(type));
+  sv_setpv(sv, result);
+}
+
+SWIGRUNTIME SV *
+SWIG_Perl_NewPackedObj(SWIG_MAYBE_PERL_OBJECT void *ptr, int sz, swig_type_info *type) {
+  SV *result = sv_newmortal();
+  SWIG_Perl_MakePackedObj(result, ptr, sz, type);
+  return result;
+}
+
+/* Convert a packed value value */
+SWIGRUNTIME int
+SWIG_Perl_ConvertPacked(SWIG_MAYBE_PERL_OBJECT SV *obj, void *ptr, int sz, swig_type_info *ty) {
+  swig_cast_info *tc;
+  const char  *c = 0;
+
+  if ((!obj) || (!SvOK(obj))) return SWIG_ERROR;
+  c = SvPV_nolen(obj);
+  /* Pointer values must start with leading underscore */
+  if (*c != '_') return SWIG_ERROR;
+  c++;
+  c = SWIG_UnpackData(c,ptr,sz);
+  if (ty) {
+    tc = SWIG_TypeCheck(c,ty);
+    if (!tc) return SWIG_ERROR;
+  }
+  return SWIG_OK;
+}
+
+
+/* Macros for low-level exception handling */
+#define SWIG_croak(x)    { SWIG_Error(SWIG_RuntimeError, x); SWIG_fail; }
+
+
+typedef XSPROTO(SwigPerlWrapper);
+typedef SwigPerlWrapper *SwigPerlWrapperPtr;
+
+/* Structure for command table */
+typedef struct {
+  const char         *name;
+  SwigPerlWrapperPtr  wrapper;
+} swig_command_info;
+
+/* Information for constant table */
+
+#define SWIG_INT     1
+#define SWIG_FLOAT   2
+#define SWIG_STRING  3
+#define SWIG_POINTER 4
+#define SWIG_BINARY  5
+
+/* Constant information structure */
+typedef struct swig_constant_info {
+    int              type;
+    const char      *name;
+    long             lvalue;
+    double           dvalue;
+    void            *pvalue;
+    swig_type_info **ptype;
+} swig_constant_info;
+
+
+/* Structure for variable table */
+typedef struct {
+  const char   *name;
+  SwigMagicFunc   set;
+  SwigMagicFunc   get;
+  swig_type_info  **type;
+} swig_variable_info;
+
+/* Magic variable code */
+#ifndef PERL_OBJECT
+#define swig_create_magic(s,a,b,c) _swig_create_magic(s,a,b,c)
+  #ifndef MULTIPLICITY
+     SWIGRUNTIME void _swig_create_magic(SV *sv, char *name, int (*set)(SV *, MAGIC *), int (*get)(SV *,MAGIC *)) 
+  #else
+     SWIGRUNTIME void _swig_create_magic(SV *sv, char *name, int (*set)(struct interpreter*, SV *, MAGIC *), int (*get)(struct interpreter*, SV *,MAGIC *)) 
+  #endif
+#else
+#  define swig_create_magic(s,a,b,c) _swig_create_magic(pPerl,s,a,b,c)
+SWIGRUNTIME void _swig_create_magic(CPerlObj *pPerl, SV *sv, const char *name, int (CPerlObj::*set)(SV *, MAGIC *), int (CPerlObj::*get)(SV *, MAGIC *)) 
+#endif
+{
+  MAGIC *mg;
+  sv_magic(sv,sv,'U',(char *) name,strlen(name));
+  mg = mg_find(sv,'U');
+  mg->mg_virtual = (MGVTBL *) malloc(sizeof(MGVTBL));
+  mg->mg_virtual->svt_get = (SwigMagicFunc) get;
+  mg->mg_virtual->svt_set = (SwigMagicFunc) set;
+  mg->mg_virtual->svt_len = 0;
+  mg->mg_virtual->svt_clear = 0;
+  mg->mg_virtual->svt_free = 0;
+}
+
+
+SWIGRUNTIME swig_module_info *
+SWIG_Perl_GetModule(void) {
+  static void *type_pointer = (void *)0;
+  SV *pointer;
+
+  /* first check if pointer already created */
+  if (!type_pointer) {
+    pointer = get_sv("swig_runtime_data::type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, FALSE | GV_ADDMULTI);
+    if (pointer && SvOK(pointer)) {
+      type_pointer = INT2PTR(swig_type_info **, SvIV(pointer));
+    }
+  }
+
+  return (swig_module_info *) type_pointer;
+}
+
+SWIGRUNTIME void
+SWIG_Perl_SetModule(swig_module_info *module) {
+  SV *pointer;
+
+  /* create a new pointer */
+  pointer = get_sv("swig_runtime_data::type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, TRUE | GV_ADDMULTI);
+  sv_setiv(pointer, PTR2IV(module));
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/perl5/perlruntime.swg b/trunk/Lib/perl5/perlruntime.swg
new file mode 100644
index 0000000..f948023
--- /dev/null
+++ b/trunk/Lib/perl5/perlruntime.swg
@@ -0,0 +1,8 @@
+
+%runtime "swigrun.swg"        // Common C API type-checking code
+%runtime "swigerrors.swg"     // SWIG errors
+%runtime "perlhead.swg"       // Perl includes and fixes
+%runtime "perlerrors.swg"     // Perl errors 
+%runtime "perlrun.swg"        // Perl runtime functions
+%runtime "noembed.h"          // undefine Perl5 macros
+
diff --git a/trunk/Lib/perl5/perlstrings.swg b/trunk/Lib/perl5/perlstrings.swg
new file mode 100644
index 0000000..2083f0b
--- /dev/null
+++ b/trunk/Lib/perl5/perlstrings.swg
@@ -0,0 +1,54 @@
+/* ------------------------------------------------------------
+ *  utility methods for char strings 
+ * ------------------------------------------------------------ */
+
+%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") {
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(SV *obj, char** cptr, size_t* psize, int *alloc)
+{
+  if (SvPOK(obj)) {
+    STRLEN len = 0;
+    char *cstr = SvPV(obj, len); 
+    size_t size = len + 1;
+    if (cptr)  {
+      if (alloc) {
+	if (*alloc == SWIG_NEWOBJ) {
+	  *cptr = %new_copy_array(cstr, size, char);
+	} else {
+	  *cptr = cstr;
+	  *alloc = SWIG_OLDOBJ;
+	}
+      }
+    }
+    if (psize) *psize = size;
+    return SWIG_OK;
+  } else {
+    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+    if (pchar_descriptor) {
+      char* vptr = 0; 
+      if (SWIG_ConvertPtr(obj, (void**)&vptr, pchar_descriptor, 0) == SWIG_OK) {
+	if (cptr) *cptr = vptr;
+	if (psize) *psize = vptr ? (strlen(vptr) + 1) : 0;
+	if (alloc) *alloc = SWIG_OLDOBJ;
+	return SWIG_OK;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_FromCharPtrAndSize","header") {
+SWIGINTERNINLINE SV *
+SWIG_FromCharPtrAndSize(const char* carray, size_t size)
+{
+  SV *obj = sv_newmortal();
+  if (carray) {
+    sv_setpvn(obj, carray, size);
+  } else {
+    sv_setsv(obj, &PL_sv_undef);
+  }
+  return obj;
+}
+}
+
diff --git a/trunk/Lib/perl5/perltypemaps.swg b/trunk/Lib/perl5/perltypemaps.swg
new file mode 100644
index 0000000..c17e410
--- /dev/null
+++ b/trunk/Lib/perl5/perltypemaps.swg
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------
+ *  Typemap specializations for Perl
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ *  Fragment section
+ * ------------------------------------------------------------ */
+
+/*
+  in Perl we need to pass the CPerlObj value, sometimes, so, we define
+  the decl/call macros as needed.
+*/
+
+#define SWIG_AS_DECL_ARGS SWIG_PERL_DECL_ARGS_2
+#define SWIG_AS_CALL_ARGS SWIG_PERL_CALL_ARGS_2
+
+#define SWIG_FROM_DECL_ARGS  SWIG_PERL_DECL_ARGS_1
+#define SWIG_FROM_CALL_ARGS  SWIG_PERL_CALL_ARGS_1
+
+
+/* Include fundamental fragemt definitions */
+%include <typemaps/fragments.swg>
+
+/* Look for user fragments file. */
+%include <perlfragments.swg>
+
+/* Perl fragments for primitive types */
+%include <perlprimtypes.swg>
+
+/* Perl fragments for char* strings */
+%include <perlstrings.swg>
+
+
+/* ------------------------------------------------------------
+ *  Unified typemap section
+ * ------------------------------------------------------------ */
+
+/* No director supported in Perl */
+#ifdef SWIG_DIRECTOR_TYPEMAPS
+#undef SWIG_DIRECTOR_TYPEMAPS
+#endif
+
+
+/* Perl types */
+#define SWIG_Object                      SV *
+
+/* Perl $shadow flag */
+#define %newpointer_flags                $shadow
+#define %newinstance_flags               $shadow
+
+
+/* Complete overload of the output/constant/exception macros */
+
+/* output */
+%define %set_output(obj) $result = obj; argvi++ %enddef
+
+/* append output */
+%define %append_output(obj) if (argvi >= items) EXTEND(sp,1); %set_output(obj) %enddef
+
+/* variable output */
+%define %set_varoutput(obj) sv_setsv($result,obj)  %enddef
+
+/* constant */
+%define %set_constant(name, obj) %begin_block
+  SV *sv = get_sv((char*) SWIG_prefix name, TRUE | 0x2 | GV_ADDMULTI);
+  sv_setsv(sv, obj);
+  SvREADONLY_on(sv);
+%end_block %enddef
+
+/* raise exception */
+%define %raise(obj, type, desc) sv_setsv(GvSV(PL_errgv), obj); SWIG_fail %enddef
+
+/* Include the unified typemap library */
+%include <typemaps/swigtypemaps.swg>
+
+/*  ------------------------------------------------------------
+ *  Perl extra typemaps
+ * ------------------------------------------------------------ */
+
+%typemap(varout,type="$1_descriptor") SWIGTYPE *, SWIGTYPE []  
+    "sv_setiv(SvRV($result),PTR2IV($1));"; 
+
+%typemap(varout,type="$1_descriptor") SWIGTYPE &
+    "sv_setiv(SvRV($result),PTR2IV(&$1));"; 
+
+%typemap(varout,type="$&1_descriptor") SWIGTYPE
+    "sv_setiv(SvRV($result), PTR2IV(&$1));";
+
+%typemap(varout,type="$1_descriptor") SWIGTYPE (CLASS::*) {
+  SWIG_MakePackedObj($result, (void *) &$1, sizeof($1_type), $1_descriptor);
+}
diff --git a/trunk/Lib/perl5/perluserdir.swg b/trunk/Lib/perl5/perluserdir.swg
new file mode 100644
index 0000000..718440e
--- /dev/null
+++ b/trunk/Lib/perl5/perluserdir.swg
@@ -0,0 +1,2 @@
+#define %perlcode  %insert("perl")
+
diff --git a/trunk/Lib/perl5/reference.i b/trunk/Lib/perl5/reference.i
new file mode 100644
index 0000000..d3d745c
--- /dev/null
+++ b/trunk/Lib/perl5/reference.i
@@ -0,0 +1,235 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * reference.i
+ *
+ * Accept Perl references as pointers
+ * ----------------------------------------------------------------------------- */
+
+/*
+The following methods make Perl references work like simple C
+pointers.  References can only be used for simple input/output
+values, not C arrays however.  It should also be noted that 
+REFERENCES are specific to Perl and not supported in other
+scripting languages at this time.
+
+         int            *REFERENCE
+         short          *REFERENCE
+         long           *REFERENCE
+         unsigned int   *REFERENCE
+         unsigned short *REFERENCE
+         unsigned long  *REFERENCE
+         unsigned char  *REFERENCE
+         float          *REFERENCE
+         double         *REFERENCE
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include reference.i
+        void neg(double *REFERENCE);
+
+or you can use the %apply directive :
+
+        %include reference.i
+        %apply double *REFERENCE { double *x };
+        void neg(double *x);
+
+Unlike the INOUT mapping described in typemaps.i, this approach directly
+modifies the value of a Perl reference.  Thus, you could use it
+as follows :
+
+       $x = 3;
+       neg(\$x);
+       print "$x\n";         # Should print out -3.
+
+*/
+
+%typemap(in) double *REFERENCE (double dvalue), double &REFERENCE(double dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if ((!SvNOK(tempsv)) && (!SvIOK(tempsv))) {
+	printf("Received %d\n", SvTYPE(tempsv));
+	SWIG_croak("Expected a double reference.");
+  }
+  dvalue = SvNV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(in) float *REFERENCE (float dvalue), float &REFERENCE(float dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if ((!SvNOK(tempsv)) && (!SvIOK(tempsv))) {
+    SWIG_croak("expected a double reference");
+  }
+  dvalue = (float) SvNV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(in) int *REFERENCE (int dvalue), int &REFERENCE (int dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = SvIV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(in) short *REFERENCE (short dvalue), short &REFERENCE(short dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (short) SvIV(tempsv);
+  $1 = &dvalue;
+}
+%typemap(in) long *REFERENCE (long dvalue), long &REFERENCE(long dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (long) SvIV(tempsv);
+  $1 = &dvalue;
+}
+%typemap(in) unsigned int *REFERENCE (unsigned int dvalue), unsigned int &REFERENCE(unsigned int dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (unsigned int) SvUV(tempsv);
+  $1 = &dvalue;
+}
+%typemap(in) unsigned short *REFERENCE (unsigned short dvalue), unsigned short &REFERENCE(unsigned short dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (unsigned short) SvUV(tempsv);
+  $1 = &dvalue;
+}
+%typemap(in) unsigned long *REFERENCE (unsigned long dvalue), unsigned long &REFERENCE(unsigned long dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (unsigned long) SvUV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(in) unsigned char *REFERENCE (unsigned char dvalue), unsigned char &REFERENCE(unsigned char dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (unsigned char) SvUV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(in) signed char *REFERENCE (signed char dvalue), signed char &REFERENCE(signed char dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (signed char) SvIV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(in) bool *REFERENCE (bool dvalue), bool &REFERENCE(bool dvalue)
+{
+  SV *tempsv;
+  if (!SvROK($input)) {
+    SWIG_croak("expected a reference");
+  }
+  tempsv = SvRV($input);
+  if (!SvIOK(tempsv)) {
+    SWIG_croak("expected a integer reference");
+  }
+  dvalue = (bool) SvIV(tempsv);
+  $1 = &dvalue;
+}
+
+%typemap(argout) double *REFERENCE, double &REFERENCE,
+                 float  *REFERENCE, float &REFERENCE
+{
+  SV *tempsv;
+  tempsv = SvRV($arg);
+  if (!$1) SWIG_croak("expected a reference");
+  sv_setnv(tempsv, (double) *$1);
+}
+
+%typemap(argout)       int            *REFERENCE, int &REFERENCE,
+                       short          *REFERENCE, short &REFERENCE,
+                       long           *REFERENCE, long  &REFERENCE,
+                       signed char    *REFERENCE, unsigned char &REFERENCE,
+                       bool           *REFERENCE, bool &REFERENCE
+{
+  SV *tempsv;
+  tempsv = SvRV($input);
+  if (!$1) SWIG_croak("expected a reference");
+  sv_setiv(tempsv, (IV) *$1);
+}
+
+%typemap(argout)       unsigned int   *REFERENCE, unsigned int &REFERENCE,
+                       unsigned short *REFERENCE, unsigned short &REFERENCE,
+                       unsigned long  *REFERENCE, unsigned long &REFERENCE,
+                       unsigned char  *REFERENCE, unsigned char &REFERENCE
+{
+  SV *tempsv;
+  tempsv = SvRV($input);
+  if (!$1) SWIG_croak("expected a reference");
+  sv_setuv(tempsv, (UV) *$1);
+}
diff --git a/trunk/Lib/perl5/std_common.i b/trunk/Lib/perl5/std_common.i
new file mode 100644
index 0000000..bc25b35
--- /dev/null
+++ b/trunk/Lib/perl5/std_common.i
@@ -0,0 +1,29 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_common.i
+ *
+ * SWIG typemaps for STL - common utilities
+ * ----------------------------------------------------------------------------- */
+
+%include <std/std_except.i>
+
+%apply size_t { std::size_t };
+
+%{
+#include <string>
+
+double SwigSvToNumber(SV* sv) {
+    return SvIOK(sv) ? double(SvIVX(sv)) : SvNVX(sv);
+}
+std::string SwigSvToString(SV* sv) {
+    STRLEN len;
+    char *ptr = SvPV(sv, len);
+    return std::string(ptr, len);
+}
+void SwigSvFromString(SV* sv, const std::string& s) {
+    sv_setpvn(sv,s.data(),s.size());
+}
+%}
+
diff --git a/trunk/Lib/perl5/std_deque.i b/trunk/Lib/perl5/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/perl5/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/perl5/std_except.i b/trunk/Lib/perl5/std_except.i
new file mode 100644
index 0000000..af98428
--- /dev/null
+++ b/trunk/Lib/perl5/std_except.i
@@ -0,0 +1 @@
+%include <typemaps/std_except.swg>
diff --git a/trunk/Lib/perl5/std_list.i b/trunk/Lib/perl5/std_list.i
new file mode 100644
index 0000000..633e40d
--- /dev/null
+++ b/trunk/Lib/perl5/std_list.i
@@ -0,0 +1,368 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_list.i
+ *
+ * SWIG typemaps for std::list types
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// containers
+
+
+// ------------------------------------------------------------------------
+// std::list
+// 
+// The aim of all that follows would be to integrate std::list with 
+// Perl as much as possible, namely, to allow the user to pass and 
+// be returned Perl arrays.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::list<T>), f(const std::list<T>&), f(const std::list<T>*):
+//      the parameter being read-only, either a Perl sequence or a
+//      previously wrapped std::list<T> can be passed.
+//   -- f(std::list<T>&), f(std::list<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::list
+//      can be passed.
+//   -- std::list<T> f():
+//      the list is returned by copy; therefore, a Perl sequence of T:s 
+//      is returned which is most easily used in other Perl functions
+//   -- std::list<T>& f(), std::list<T>* f(), const std::list<T>& f(),
+//      const std::list<T>* f():
+//      the list is returned by reference; therefore, a wrapped std::list
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <list>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    
+    template<class T> class list {
+        %typemap(in) list<T> (std::list<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $&1_descriptor,1) != -1) {
+                $1 = *v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                T* obj;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                        $descriptor(T *),0) != -1) {
+                        $1.push_back(*obj);
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(in) const list<T>& (std::list<T> temp,
+                                       std::list<T>* v),
+                     const list<T>* (std::list<T> temp,
+                                       std::list<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $1_descriptor,1) != -1) {
+                $1 = v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                T* obj;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                        $descriptor(T *),0) != -1) {
+                        temp.push_back(*obj);
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+                $1 = &temp;
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(out) list<T> {
+	    std::list<T>::const_iterator i;
+            unsigned int j;
+            int len = $1.size();
+            SV **svs = new SV*[len];
+            for (i=$1.begin(), j=0; i!=$1.end(); i++, j++) {
+                T* ptr = new T(*i);
+                svs[j] = sv_newmortal();
+                SWIG_MakePtr(svs[j], (void*) ptr, 
+                             $descriptor(T *), $shadow|$owner);
+            }
+            AV *myav = av_make(len, svs);
+            delete[] svs;
+            $result = newRV_noinc((SV*) myav);
+            sv_2mortal($result);
+            argvi++;
+        }
+        %typecheck(SWIG_TYPECHECK_LIST) list<T> {
+            {
+                /* wrapped list? */
+                std::list<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $1_&descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        SV **tv;
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            T* obj;
+                            tv = av_fetch(av, 0, 0);
+                            if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                                $descriptor(T *),0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_LIST) const list<T>&,
+                                          const list<T>* {
+            {
+                /* wrapped list? */
+                std::list<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $1_descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        SV **tv;
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            T* obj;
+                            tv = av_fetch(av, 0, 0);
+                            if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                                $descriptor(T *),0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+      public:
+        list();
+        list(const list<T> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(const T& x);
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_list(T,CHECK_T,TO_T,FROM_T)
+    template<> class list<T> {
+        %typemap(in) list<T> (std::list<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $&1_descriptor,1) != -1){
+                $1 = *v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (CHECK_T(*tv)) {
+                        $1.push_back(TO_T(*tv));
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(in) const list<T>& (std::list<T> temp,
+                                       std::list<T>* v),
+                     const list<T>* (std::list<T> temp,
+                                       std::list<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $1_descriptor,1) != -1) {
+                $1 = v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                T* obj;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (CHECK_T(*tv)) {
+                        temp.push_back(TO_T(*tv));
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+                $1 = &temp;
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(out) list<T> {
+	    std::list<T>::const_iterator i;
+            unsigned int j;
+            int len = $1.size();
+            SV **svs = new SV*[len];
+            for (i=$1.begin(), j=0; i!=$1.end(); i++, j++) {
+                svs[j] = sv_newmortal();
+                FROM_T(svs[j], *i);
+            }
+            AV *myav = av_make(len, svs);
+            delete[] svs;
+            $result = newRV_noinc((SV*) myav);
+            sv_2mortal($result);
+            argvi++;
+        }
+        %typecheck(SWIG_TYPECHECK_LIST) list<T> {
+            {
+                /* wrapped list? */
+                std::list<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $1_&descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        SV **tv;
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            tv = av_fetch(av, 0, 0);
+                            if (CHECK_T(*tv))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_LIST) const list<T>&,
+                                          const list<T>* {
+            {
+                /* wrapped list? */
+                std::list<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $1_descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        SV **tv;
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            tv = av_fetch(av, 0, 0);
+                            if (CHECK_T(*tv))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+      public:
+        list();
+        list(const list<T> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(T x);
+    };
+    %enddef
+
+    specialize_std_list(bool,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(char,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(int,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(short,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(long,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(unsigned char,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(unsigned int,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(unsigned short,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(unsigned long,SvIOK,SvIVX,sv_setiv);
+    specialize_std_list(float,SvNIOK,SwigSvToNumber,sv_setnv);
+    specialize_std_list(double,SvNIOK,SwigSvToNumber,sv_setnv);
+    specialize_std_list(std::string,SvPOK,SvPVX,SwigSvFromString);
+
+}
+
diff --git a/trunk/Lib/perl5/std_map.i b/trunk/Lib/perl5/std_map.i
new file mode 100644
index 0000000..c35f21d
--- /dev/null
+++ b/trunk/Lib/perl5/std_map.i
@@ -0,0 +1,175 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, T x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    // add specializations here
+
+}
diff --git a/trunk/Lib/perl5/std_pair.i b/trunk/Lib/perl5/std_pair.i
new file mode 100644
index 0000000..78142ff
--- /dev/null
+++ b/trunk/Lib/perl5/std_pair.i
@@ -0,0 +1,37 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+namespace std {
+
+  template<class T, class U> struct pair {
+
+    pair();
+    pair(T t, U u);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+  };
+
+  // add specializations here
+
+}
diff --git a/trunk/Lib/perl5/std_string.i b/trunk/Lib/perl5/std_string.i
new file mode 100644
index 0000000..6f34f18
--- /dev/null
+++ b/trunk/Lib/perl5/std_string.i
@@ -0,0 +1,2 @@
+%include <perlstrings.swg>
+%include <typemaps/std_string.swg>
diff --git a/trunk/Lib/perl5/std_vector.i b/trunk/Lib/perl5/std_vector.i
new file mode 100644
index 0000000..b1f722d
--- /dev/null
+++ b/trunk/Lib/perl5/std_vector.i
@@ -0,0 +1,571 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * SWIG typemaps for std::vector types
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// Perl as much as possible, namely, to allow the user to pass and 
+// be returned Perl arrays.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&), f(const std::vector<T>*):
+//      the parameter being read-only, either a Perl sequence or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f():
+//      the vector is returned by copy; therefore, a Perl sequence of T:s 
+//      is returned which is most easily used in other Perl functions
+//   -- std::vector<T>& f(), std::vector<T>* f(), const std::vector<T>& f(),
+//      const std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    
+    template<class T> class vector {
+        %typemap(in) vector<T> (std::vector<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $&1_descriptor,1) != -1) {
+                $1 = *v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                T* obj;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                        $descriptor(T *),0) != -1) {
+                        $1.push_back(*obj);
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(in) const vector<T>& (std::vector<T> temp,
+                                       std::vector<T>* v),
+                     const vector<T>* (std::vector<T> temp,
+                                       std::vector<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $1_descriptor,1) != -1) {
+                $1 = v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                T* obj;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                        $descriptor(T *),0) != -1) {
+                        temp.push_back(*obj);
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+                $1 = &temp;
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(out) vector<T> {
+            int len = $1.size();
+            SV **svs = new SV*[len];
+            for (unsigned int i=0; i<len; i++) {
+                T* ptr = new T($1[i]);
+                svs[i] = sv_newmortal();
+                SWIG_MakePtr(svs[i], (void*) ptr, 
+                             $descriptor(T *), $shadow|$owner);
+            }
+            AV *myav = av_make(len, svs);
+            delete[] svs;
+            $result = newRV_noinc((SV*) myav);
+            sv_2mortal($result);
+            argvi++;
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $&1_descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            T* obj;
+                            SV **tv = av_fetch(av, 0, 0);
+                            if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                                $descriptor(T *),0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $1_descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            T* obj;
+                            SV **tv = av_fetch(av, 0, 0);
+                            if (SWIG_ConvertPtr(*tv, (void **)&obj, 
+                                                $descriptor(T *),0) != -1)
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(const T& x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T& get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, const T& x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+
+    // specializations for pointers
+    template<class T> class vector<T*> {
+        %typemap(in) vector<T*> (std::vector<T*>* v) {
+	    int res = SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor,0);
+            if (SWIG_IsOK(res)){
+                $1 = *v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                I32 len = av_len(av) + 1;
+                for (int i=0; i<len; i++) {
+		    void *v;
+		    SV **tv = av_fetch(av, i, 0);
+		    int res = SWIG_ConvertPtr(*tv, &v, $descriptor(T *),0);
+                    if (SWIG_IsOK(res)) {
+                        $1.push_back(%static_cast(v, T *));
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(in) const vector<T *>& (std::vector<T *> temp,std::vector<T *>* v),
+                     const vector<T *>* (std::vector<T *> temp,std::vector<T *>* v) {
+	    int res = SWIG_ConvertPtr($input,(void **) &v, $1_descriptor,0);
+            if (SWIG_IsOK(res)) {
+                $1 = v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                I32 len = av_len(av) + 1;
+                for (int i=0; i<len; i++) {
+		    void *v;
+		    SV **tv = av_fetch(av, i, 0);
+		    int res = SWIG_ConvertPtr(*tv, &v, $descriptor(T *),0);
+                    if (SWIG_IsOK(res)) {
+                        temp.push_back(%static_cast(v, T *));
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+                $1 = &temp;
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(out) vector<T *> {
+            size_t len = $1.size();
+            SV **svs = new SV*[len];
+            for (size_t i=0; i<len; i++) {
+                T *x = (($1_type &)$1)[i];
+                svs[i] = sv_newmortal();
+		sv_setsv(svs[i], SWIG_NewPointerObj(x, $descriptor(T *), 0));
+            }
+            AV *myav = av_make(len, svs);
+            delete[] svs;
+            $result = newRV_noinc((SV*) myav);
+            sv_2mortal($result);
+            argvi++;
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T *> {
+            {
+                /* wrapped vector? */
+                std::vector<T *>* v;
+		int res = SWIG_ConvertPtr($input,(void **) &v, $&1_descriptor,0);
+                if (SWIG_IsOK(res)) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+			    void *v;
+			    SV **tv = av_fetch(av, 0, 0);
+			    int res = SWIG_ConvertPtr(*tv, &v, $descriptor(T *),0);
+                            if (SWIG_IsOK(res))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T *>&,const vector<T *>* {
+            {
+                /* wrapped vector? */
+                std::vector<T *> *v;
+		int res = SWIG_ConvertPtr($input,%as_voidptrptr(&v), $1_descriptor,0);
+                if (SWIG_IsOK(res)) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+			    void *v;
+			    SV **tv = av_fetch(av, 0, 0);
+			    int res = SWIG_ConvertPtr(*tv, &v, $descriptor(T *),0);
+                            if (SWIG_IsOK(res))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, T *value);
+        vector(const vector<T *> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(T *x);
+        %extend {
+            T *pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T *x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T *get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, T *x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_vector(T,CHECK_T,TO_T,FROM_T)
+    template<> class vector<T> {
+        %typemap(in) vector<T> (std::vector<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $&1_descriptor,1) != -1){
+                $1 = *v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (CHECK_T(*tv)) {
+                        $1.push_back((T)TO_T(*tv));
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(in) const vector<T>& (std::vector<T> temp,
+                                       std::vector<T>* v),
+                     const vector<T>* (std::vector<T> temp,
+                                       std::vector<T>* v) {
+            if (SWIG_ConvertPtr($input,(void **) &v, 
+                                $1_descriptor,1) != -1) {
+                $1 = v;
+            } else if (SvROK($input)) {
+                AV *av = (AV *)SvRV($input);
+                if (SvTYPE(av) != SVt_PVAV)
+                    SWIG_croak("Type error in argument $argnum of $symname. "
+                               "Expected an array of " #T);
+                SV **tv;
+                I32 len = av_len(av) + 1;
+                for (int i=0; i<len; i++) {
+                    tv = av_fetch(av, i, 0);
+                    if (CHECK_T(*tv)) {
+                        temp.push_back((T)TO_T(*tv));
+                    } else {
+                        SWIG_croak("Type error in argument $argnum of "
+                                   "$symname. "
+                                   "Expected an array of " #T);
+                    }
+                }
+                $1 = &temp;
+            } else {
+                SWIG_croak("Type error in argument $argnum of $symname. "
+                           "Expected an array of " #T);
+            }
+        }
+        %typemap(out) vector<T> {
+            size_t len = $1.size();
+            SV **svs = new SV*[len];
+            for (size_t i=0; i<len; i++) {
+                svs[i] = sv_newmortal();
+                FROM_T(svs[i], $1[i]);
+            }
+            AV *myav = av_make(len, svs);
+            delete[] svs;
+            $result = newRV_noinc((SV*) myav);
+            sv_2mortal($result);
+            argvi++;
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $&1_descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            SV **tv = av_fetch(av, 0, 0);
+                            if (CHECK_T(*tv))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            {
+                /* wrapped vector? */
+                std::vector<T >* v;
+                if (SWIG_ConvertPtr($input,(void **) &v, 
+                                    $1_descriptor,0) != -1) {
+                    $1 = 1;
+                } else if (SvROK($input)) {
+                    /* native sequence? */
+                    AV *av = (AV *)SvRV($input);
+                    if (SvTYPE(av) == SVt_PVAV) {
+                        I32 len = av_len(av) + 1;
+                        if (len == 0) {
+                            /* an empty sequence can be of any type */
+                            $1 = 1;
+                        } else {
+                            /* check the first element only */
+                            SV **tv = av_fetch(av, 0, 0);
+                            if (CHECK_T(*tv))
+                                $1 = 1;
+                            else
+                                $1 = 0;
+                        }
+                    }
+                } else {
+                    $1 = 0;
+                }
+            }
+        }
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, T value);
+        vector(const vector<T> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(T x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, T x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+    %enddef
+
+    specialize_std_vector(bool,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(char,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(int,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(short,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(long,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(unsigned char,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(unsigned int,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(unsigned short,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(unsigned long,SvIOK,SvIVX,sv_setiv);
+    specialize_std_vector(float,SvNIOK,SwigSvToNumber,sv_setnv);
+    specialize_std_vector(double,SvNIOK,SwigSvToNumber,sv_setnv);
+    specialize_std_vector(std::string,SvPOK,SwigSvToString,SwigSvFromString);
+}
+
diff --git a/trunk/Lib/perl5/stl.i b/trunk/Lib/perl5/stl.i
new file mode 100644
index 0000000..946e4b7
--- /dev/null
+++ b/trunk/Lib/perl5/stl.i
@@ -0,0 +1,14 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/perl5/typemaps.i b/trunk/Lib/perl5/typemaps.i
new file mode 100644
index 0000000..fc6d8f8
--- /dev/null
+++ b/trunk/Lib/perl5/typemaps.i
@@ -0,0 +1,374 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * The SWIG typemap library provides a language independent mechanism for
+ * supporting output arguments, input values, and other C function
+ * calling mechanisms.  The primary use of the library is to provide a
+ * better interface to certain C function--especially those involving
+ * pointers.
+ * ----------------------------------------------------------------------------- */
+
+#if !defined(SWIG_USE_OLD_TYPEMAPS)
+%include <typemaps/typemaps.swg>
+#else
+
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+
+/*
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+
+         int            *INPUT
+         short          *INPUT
+         long           *INPUT
+         long long      *INPUT
+         unsigned int   *INPUT
+         unsigned short *INPUT
+         unsigned long  *INPUT
+         unsigned long long *INPUT
+         unsigned char  *INPUT
+         bool           *INPUT
+         float          *INPUT
+         double         *INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include typemaps.i
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+
+%define INPUT_TYPEMAP(type, converter) 
+%typemap(in) type *INPUT(type temp), type &INPUT(type temp) {
+  temp = (type) converter($input);
+  $1 = &temp;
+}
+%typemap(typecheck) type *INPUT = type;
+%typemap(typecheck) type &INPUT = type;
+%enddef
+
+INPUT_TYPEMAP(float, SvNV);
+INPUT_TYPEMAP(double, SvNV);
+INPUT_TYPEMAP(int, SvIV);
+INPUT_TYPEMAP(long, SvIV);
+INPUT_TYPEMAP(short, SvIV);
+INPUT_TYPEMAP(signed char, SvIV);
+INPUT_TYPEMAP(unsigned int, SvUV);
+INPUT_TYPEMAP(unsigned long, SvUV);
+INPUT_TYPEMAP(unsigned short, SvUV);
+INPUT_TYPEMAP(unsigned char, SvUV);
+
+%typemap(in) bool *INPUT(bool temp), bool &INPUT(bool temp) {
+  temp = SvIV($input) ? true : false;
+  $1 = &temp;
+}
+%typemap(typecheck) bool *INPUT = bool;
+%typemap(typecheck) bool &INPUT = bool;
+
+%typemap(in) long long *INPUT($*1_ltype temp), long long &INPUT($*1_ltype temp) {
+  temp = strtoll(SvPV_nolen($input), 0, 0);
+  $1 = &temp;
+}
+%typemap(typecheck) long long *INPUT = long long;
+%typemap(typecheck) long long &INPUT = long long;
+
+%typemap(in) unsigned long long *INPUT($*1_ltype temp), unsigned long long &INPUT($*1_ltype temp) {
+  temp = strtoull(SvPV_nolen($input), 0, 0);
+  $1 = &temp;
+}
+%typemap(typecheck) unsigned long long *INPUT = unsigned long long;
+%typemap(typecheck) unsigned long long &INPUT = unsigned long long;
+
+
+#undef INPUT_TYPEMAP
+                 
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a list element.
+
+/*
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, functions will return a Perl array.
+
+         int            *OUTPUT
+         short          *OUTPUT
+         long           *OUTPUT
+         long long      *OUTPUT
+         unsigned int   *OUTPUT
+         unsigned short *OUTPUT
+         unsigned long  *OUTPUT
+         unsigned long long *OUTPUT
+         unsigned char  *OUTPUT
+         bool           *OUTPUT
+         float          *OUTPUT
+         double         *OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters).:
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include typemaps.i
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The Perl output of the function would be an array containing both
+output values. 
+
+*/
+
+// Force the argument to be ignored.
+
+%typemap(in,numinputs=0) int            *OUTPUT(int temp),  int &OUTPUT(int temp),
+                 short          *OUTPUT(short temp), short &OUTPUT(short temp),
+                 long           *OUTPUT(long temp), long &OUTPUT(long temp),
+                 unsigned int   *OUTPUT(unsigned int temp), unsigned int &OUTPUT(unsigned int temp),
+                 unsigned short *OUTPUT(unsigned short temp), unsigned short &OUTPUT(unsigned short temp),
+                 unsigned long  *OUTPUT(unsigned long temp), unsigned long &OUTPUT(unsigned long temp),
+                 unsigned char  *OUTPUT(unsigned char temp), unsigned char &OUTPUT(unsigned char temp),
+                 signed char    *OUTPUT(signed char temp), signed char &OUTPUT(signed char temp),
+                 bool           *OUTPUT(bool temp), bool &OUTPUT(bool temp),
+                 float          *OUTPUT(float temp), float &OUTPUT(float temp),
+                 double         *OUTPUT(double temp), double &OUTPUT(double temp),
+                 long long      *OUTPUT($*1_ltype temp), long long &OUTPUT($*1_ltype temp),
+                 unsigned long long *OUTPUT($*1_ltype temp), unsigned long long &OUTPUT($*1_ltype temp) 
+"$1 = &temp;";
+
+%typemap(argout)  int            *OUTPUT, int &OUTPUT,
+                  short          *OUTPUT, short &OUTPUT,
+                  long           *OUTPUT, long &OUTPUT,
+                  signed char    *OUTPUT, signed char &OUTPUT,
+                  bool           *OUTPUT, bool &OUTPUT
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $result = sv_newmortal();
+  sv_setiv($result,(IV) *($1));
+  argvi++;
+}
+
+%typemap(argout)  unsigned int   *OUTPUT, unsigned int &OUTPUT,
+                  unsigned short *OUTPUT, unsigned short &OUTPUT,
+                  unsigned long  *OUTPUT, unsigned long &OUTPUT,
+                  unsigned char  *OUTPUT, unsigned char &OUTPUT
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $result = sv_newmortal();
+  sv_setuv($result,(UV) *($1));
+  argvi++;
+}
+
+
+
+%typemap(argout) float    *OUTPUT, float &OUTPUT,
+                 double   *OUTPUT, double &OUTPUT
+{
+  if (argvi >= items) {
+    EXTEND(sp,1);
+  }
+  $result = sv_newmortal();
+  sv_setnv($result,(double) *($1));
+  argvi++;
+}
+
+%typemap(argout) long long *OUTPUT, long long &OUTPUT {
+    char temp[256];
+    if (argvi >= items) {
+	EXTEND(sp,1);
+    }
+    sprintf(temp,"%lld", (long long)*($1));
+    $result = sv_newmortal();
+    sv_setpv($result,temp);
+    argvi++;
+}
+
+%typemap(argout) unsigned long long *OUTPUT, unsigned long long &OUTPUT {
+    char temp[256];
+    if (argvi >= items) {
+	EXTEND(sp,1);
+    }
+    sprintf(temp,"%llu", (unsigned long long)*($1));
+    $result = sv_newmortal();
+    sv_setpv($result,temp);
+    argvi++;
+}
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a Perl array.
+
+         int            *INOUT
+         short          *INOUT
+         long           *INOUT
+         long long      *INOUT
+         unsigned int   *INOUT
+         unsigned short *INOUT
+         unsigned long  *INOUT
+         unsigned long long *INOUT
+         unsigned char  *INOUT
+         bool           *INOUT
+         float          *INOUT
+         double         *INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include typemaps.i
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+Unlike C, this mapping does not directly modify the input value.
+Rather, the modified input value shows up as the return value of the
+function.  Thus, to apply this function to a Perl variable you might
+do this :
+
+       $x = neg($x);
+
+*/
+
+%typemap(in) int *INOUT = int *INPUT;
+%typemap(in) short *INOUT = short *INPUT;
+%typemap(in) long *INOUT = long *INPUT;
+%typemap(in) unsigned *INOUT = unsigned *INPUT;
+%typemap(in) unsigned short *INOUT = unsigned short *INPUT;
+%typemap(in) unsigned long *INOUT = unsigned long *INPUT;
+%typemap(in) unsigned char *INOUT = unsigned char *INPUT;
+%typemap(in) signed char *INOUT = signed char *INPUT;
+%typemap(in) bool *INOUT = bool *INPUT;
+%typemap(in) float *INOUT = float *INPUT;
+%typemap(in) double *INOUT = double *INPUT;
+%typemap(in) long long *INOUT = long long *INPUT;
+%typemap(in) unsigned long long *INOUT = unsigned long long *INPUT;
+
+%typemap(in) int &INOUT = int &INPUT;
+%typemap(in) short &INOUT = short &INPUT;
+%typemap(in) long &INOUT = long &INPUT;
+%typemap(in) unsigned &INOUT = unsigned &INPUT;
+%typemap(in) unsigned short &INOUT = unsigned short &INPUT;
+%typemap(in) unsigned long &INOUT = unsigned long &INPUT;
+%typemap(in) unsigned char &INOUT = unsigned char &INPUT;
+%typemap(in) signed char &INOUT = signed char &INPUT;
+%typemap(in) bool &INOUT = bool &INPUT;
+%typemap(in) float &INOUT = float &INPUT;
+%typemap(in) double &INOUT = double &INPUT;
+%typemap(in) long long &INOUT = long long &INPUT;
+%typemap(in) unsigned long long &INOUT = unsigned long long &INPUT;
+
+
+%typemap(argout) int *INOUT = int *OUTPUT;
+%typemap(argout) short *INOUT = short *OUTPUT;
+%typemap(argout) long *INOUT = long *OUTPUT;
+%typemap(argout) unsigned *INOUT = unsigned *OUTPUT;
+%typemap(argout) unsigned short *INOUT = unsigned short *OUTPUT;
+%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT;
+%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT;
+%typemap(argout) signed char *INOUT = signed char *OUTPUT;
+%typemap(argout) bool *INOUT = bool *OUTPUT;
+%typemap(argout) float *INOUT = float *OUTPUT;
+%typemap(argout) double *INOUT = double *OUTPUT;
+%typemap(argout) long long *INOUT = long long *OUTPUT;
+%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT;
+
+
+%typemap(argout) int &INOUT = int &OUTPUT;
+%typemap(argout) short &INOUT = short &OUTPUT;
+%typemap(argout) long &INOUT = long &OUTPUT;
+%typemap(argout) unsigned &INOUT = unsigned &OUTPUT;
+%typemap(argout) unsigned short &INOUT = unsigned short &OUTPUT;
+%typemap(argout) unsigned long &INOUT = unsigned long &OUTPUT;
+%typemap(argout) unsigned char &INOUT = unsigned char &OUTPUT;
+%typemap(argout) signed char &INOUT = signed char &OUTPUT;
+%typemap(argout) bool &INOUT = bool &OUTPUT;
+%typemap(argout) float &INOUT = float &OUTPUT;
+%typemap(argout) double &INOUT = double &OUTPUT;
+%typemap(argout) long long &INOUT = long long &OUTPUT;
+%typemap(argout) unsigned long long &INOUT = unsigned long long &OUTPUT;
+
+
+/* Overloading information */
+
+%typemap(typecheck) double *INOUT = double;
+%typemap(typecheck) bool *INOUT = bool;
+%typemap(typecheck) signed char *INOUT = signed char;
+%typemap(typecheck) unsigned char *INOUT = unsigned char;
+%typemap(typecheck) unsigned long *INOUT = unsigned long;
+%typemap(typecheck) unsigned short *INOUT = unsigned short;
+%typemap(typecheck) unsigned int *INOUT = unsigned int;
+%typemap(typecheck) long *INOUT = long;
+%typemap(typecheck) short *INOUT = short;
+%typemap(typecheck) int *INOUT = int;
+%typemap(typecheck) float *INOUT = float;
+%typemap(typecheck) long long *INOUT = long long;
+%typemap(typecheck) unsigned long long *INOUT = unsigned long long;
+
+%typemap(typecheck) double &INOUT = double;
+%typemap(typecheck) bool &INOUT = bool;
+%typemap(typecheck) signed char &INOUT = signed char;
+%typemap(typecheck) unsigned char &INOUT = unsigned char;
+%typemap(typecheck) unsigned long &INOUT = unsigned long;
+%typemap(typecheck) unsigned short &INOUT = unsigned short;
+%typemap(typecheck) unsigned int &INOUT = unsigned int;
+%typemap(typecheck) long &INOUT = long;
+%typemap(typecheck) short &INOUT = short;
+%typemap(typecheck) int &INOUT = int;
+%typemap(typecheck) float &INOUT = float;
+%typemap(typecheck) long long &INOUT = long long;
+%typemap(typecheck) unsigned long long &INOUT = unsigned long long;
+
+#endif
+
+// --------------------------------------------------------------------
+// Special types
+// --------------------------------------------------------------------
+
+
+%include <reference.i>
diff --git a/trunk/Lib/php4/const.i b/trunk/Lib/php4/const.i
new file mode 100644
index 0000000..6ddd403
--- /dev/null
+++ b/trunk/Lib/php4/const.i
@@ -0,0 +1,53 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * const.i
+ *
+ * Typemaps for constants
+ * ----------------------------------------------------------------------------- */
+
+%typemap(consttab) int,
+                   unsigned int,
+                   short,
+                   unsigned short,
+                   long,
+                   unsigned long,
+                   unsigned char,
+                   signed char,
+                   bool,
+                   enum SWIGTYPE
+  "SWIG_LONG_CONSTANT($symname, $value);";
+
+%typemap(consttab) float,
+                   double
+  "SWIG_DOUBLE_CONSTANT($symname, $value);";
+
+%typemap(consttab) char
+  "SWIG_CHAR_CONSTANT($symname, $value);";
+
+%typemap(consttab) char *,
+                   const char *,
+                   char [],
+                   const char []
+  "SWIG_STRING_CONSTANT($symname, $value);";
+
+%typemap(consttab) SWIGTYPE *,
+                   SWIGTYPE &,
+                   SWIGTYPE [] {
+  /* This actually registers it as a global variable and constant.  I don't
+   * like it, but I can't figure out the zend_constant code... */
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  SWIG_SetPointerZval(z_var, (void*)$value, $1_descriptor, 0);
+  /* zend_hash_add(&EG(symbol_table), "$1", sizeof("$1"), (void *)&z_var,sizeof(zval *), NULL); */
+  zend_constant c;
+  c.value = *z_var;
+  zval_copy_ctor(&c.value);
+  size_t len = sizeof("$1") - 1;
+  c.name = zend_strndup("$1", len);
+  c.name_len = len+1;
+  c.flags = CONST_CS | CONST_PERSISTENT;
+  c.module_number = module_number;
+  zend_register_constant( &c TSRMLS_CC );
+}
diff --git a/trunk/Lib/php4/globalvar.i b/trunk/Lib/php4/globalvar.i
new file mode 100644
index 0000000..a75b1a4
--- /dev/null
+++ b/trunk/Lib/php4/globalvar.i
@@ -0,0 +1,331 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * globalvar.i
+ *
+ * Global variables - add the variable to PHP
+ * ----------------------------------------------------------------------------- */
+
+%typemap(varinit) char *,
+                  char []
+{
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  z_var->type = IS_STRING;
+  if($1) {
+      z_var->value.str.val = estrdup($1);
+      z_var->value.str.len = strlen($1);
+  } else {
+      z_var->value.str.val = 0;
+      z_var->value.str.len = 0;
+  }
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL);
+}
+
+%typemap(varinit) int,
+	          unsigned int,
+                  unsigned short,
+                  short,
+                  unsigned short,
+                  long,
+                  unsigned long,
+                  signed char,
+                  unsigned char,
+                  enum SWIGTYPE
+{
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  z_var->type = IS_LONG;
+  z_var->value.lval = $1;
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL);
+}
+
+%typemap(varinit) bool
+{
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  z_var->type = IS_BOOL;
+  z_var->value.lval = ($1)?1:0;
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var, sizeof(zval *), NULL);
+}
+
+%typemap(varinit) float, double
+{
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  z_var->type = IS_DOUBLE;
+  z_var->value.dval = $1;
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var,
+  sizeof(zval *), NULL);
+}
+
+%typemap(varinit) char
+{
+  zval *z_var;
+  char c[2];
+  MAKE_STD_ZVAL(z_var);
+  c[0] = $1;
+  c[1] = 0;
+  z_var->type = IS_STRING;
+  z_var->value.str.val = estrndup(c, 1);
+  z_var->value.str.len = 1;
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var,
+  sizeof(zval *), NULL);
+}
+
+%typemap(varinit) SWIGTYPE *, SWIGTYPE []
+{
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  SWIG_SetPointerZval(z_var, (void*)$1, $1_descriptor, 0);
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void *)&z_var,
+  sizeof(zval *), NULL);
+}
+
+%typemap(varinit) SWIGTYPE, SWIGTYPE &
+{
+  zval *z_var;
+
+  MAKE_STD_ZVAL(z_var);
+  SWIG_SetPointerZval(z_var, (void*)&$1, $&1_descriptor, 0);
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&z_var,
+  sizeof(zval *), NULL);
+}
+
+%typemap(varinit) char [ANY]
+{
+  zval *z_var;
+  MAKE_STD_ZVAL(z_var);
+  z_var->type = IS_STRING;
+  if ($1) {
+    // varinit char [ANY]
+    ZVAL_STRINGL(z_var,(char*)$1, $1_dim0, 1);
+  }
+  zend_hash_add(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void*)&z_var, sizeof(zval *), NULL);
+}
+
+%typemap(varin) int, unsigned int, short, unsigned short, long, unsigned long, signed char, unsigned char,  enum SWIGTYPE
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  convert_to_long_ex(z_var);
+  if ($1 != ($1_ltype)((*z_var)->value.lval)) {
+    $1 = Z_LVAL_PP(z_var);
+  }
+}
+
+%typemap(varin) bool
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  convert_to_boolean_ex(z_var);
+  if ($1 != ($1_ltype)((*z_var)->value.lval)) {
+    $1 = Z_LVAL_PP(z_var);
+  }
+}
+
+%typemap(varin) double,float
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  convert_to_double_ex(z_var);
+  if ($1 != ($1_ltype)((*z_var)->value.dval)) {
+    $1 = Z_DVAL_PP(z_var);
+  }
+}
+
+%typemap(varin) char
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  convert_to_string_ex(z_var);
+  if ($1 != *((*z_var)->value.str.val)) {
+    $1 = *((*z_var)->value.str.val);
+  }
+}
+
+%typemap(varin) char *
+{
+  zval **z_var;
+  char *s1;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  convert_to_string_ex(z_var);
+  s1 = Z_STRVAL_PP(z_var);
+  if ((s1 == NULL) || ($1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1))) {
+    if (s1)
+      $1 = estrdup(s1);
+    else
+      $1 = NULL;
+  }
+}
+
+
+%typemap(varin) SWIGTYPE []
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if($1) {
+    SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, $owner);
+  }
+}
+
+%typemap(varin) char [ANY]
+{
+ zval **z_var;
+ char *s1;
+
+ zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+ s1 = Z_STRVAL_PP(z_var);
+ if((s1 == NULL) || ($1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1))) {
+  if(s1)
+    strncpy($1, s1, $1_dim0);
+ }
+}
+
+%typemap(varin) SWIGTYPE
+{
+  zval **z_var;
+  $&1_ltype _temp;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if (SWIG_ConvertPtr(*z_var, (void**)&_temp, $&1_descriptor, 0) < 0) {
+    SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor");
+  }
+
+  $1 = *($&1_ltype)_temp;
+
+}
+
+%typemap(varin) SWIGTYPE *, SWIGTYPE &
+{
+  zval **z_var;
+  $1_ltype _temp;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if (SWIG_ConvertPtr(*z_var, (void **)&_temp, $1_descriptor, 0) < 0) { 
+    SWIG_PHP_Error(E_ERROR,"Type error in value of $symname. Expected $&1_descriptor");
+  }
+
+  $1 = ($1_ltype)_temp;
+}
+
+%typemap(varout) int,
+                 unsigned int,
+                 unsigned short,
+                 short,
+                 long,
+                 unsigned long,
+                 signed char,
+                 unsigned char,
+                 enum SWIGTYPE
+{
+  zval **z_var;
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if($1 != ($1_ltype)((*z_var)->value.lval)) {
+    (*z_var)->value.lval = (long)$1;
+  }
+}
+
+//SAMFIX need to cast zval->type, what if zend-hash_find fails? etc?
+%typemap(varout) bool
+{
+  zval **z_var;
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if($1 != ($1_ltype)((*z_var)->value.lval)) {
+    (*z_var)->value.lval = (long)$1;
+  }
+}
+
+%typemap(varout) double, float
+{
+  zval **z_var;
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if($1 != ($1_ltype)((*z_var)->value.dval)) {
+    (*z_var)->value.dval = (double)$1;
+  }
+}
+
+%typemap(varout) char
+{
+  zval **z_var;
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if($1 != *((*z_var)->value.str.val)) {
+    char c[2];
+    efree((*z_var)->value.str.val);
+    c[0] = $1;
+    c[1] = 0;
+    (*z_var)->value.str.val = estrdup(c);
+  }
+}
+
+%typemap(varout) char *
+{
+  zval **z_var;
+  char *s1;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  s1 = Z_STRVAL_PP(z_var);
+  if((s1 == NULL) || ($1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1) )) {
+    if(s1)
+      efree(s1);
+    if($1) {
+      (*z_var)->value.str.val = estrdup($1);
+      (*z_var)->value.str.len = strlen($1) +1;
+    } else {
+      (*z_var)->value.str.val = 0;
+      (*z_var)->value.str.len = 0;
+    }
+ }
+}
+
+%typemap(varout) SWIGTYPE
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  SWIG_SetPointerZval(*z_var, (void*)&$1, $&1_descriptor, 0);
+}
+
+%typemap(varout) SWIGTYPE []
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  if($1) 
+  	SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0);
+}
+
+%typemap(varout) char [ANY]
+{
+  zval **z_var;
+  char *s1;
+deliberate error cos this code looks bogus to me
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  s1 = Z_STRVAL_PP(z_var);
+  if((s1 == NULL) || zend_binary_strcmp(s1, strlen(s1), $1, strlen($1))) {
+    if($1) {
+      (*z_var)->value.str.val = estrdup($1);
+      (*z_var)->value.str.len = strlen($1)+1;
+    } else {
+      (*z_var)->value.str.val = 0;
+      (*z_var)->value.str.len = 0;
+    }
+  }
+}
+
+%typemap(varout) SWIGTYPE *, SWIGTYPE &
+{
+  zval **z_var;
+
+  zend_hash_find(&EG(symbol_table), (char*)"$1", sizeof("$1"), (void**)&z_var);
+  SWIG_SetPointerZval(*z_var, (void*)$1, $1_descriptor, 0);
+}
+
+
diff --git a/trunk/Lib/php4/php4.swg b/trunk/Lib/php4/php4.swg
new file mode 100644
index 0000000..feaee68
--- /dev/null
+++ b/trunk/Lib/php4/php4.swg
@@ -0,0 +1,298 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * php4.swg
+ *
+ * PHP4 configuration file
+ * ----------------------------------------------------------------------------- */
+
+%runtime "swigrun.swg"  // Common C API type-checking code
+%runtime "php4run.swg"	// Php4 runtime functions
+
+%include <php4init.swg> // Php4 initialization routine.
+
+%include <globalvar.i>	// Global variables.
+%include <const.i>
+
+// use %init %{ "/*code goes here*/ " %}
+// or  %minit %{ "/* code goes here*/ " %} to
+// insert code in the PHP_MINIT_FUNCTION
+#define %minit %insert("init")
+
+// use %rinit %{ "/* code goes here*/ " %} to
+// insert code in the PHP_RINIT_FUNCTION
+#define %rinit %insert("rinit")
+
+// use %shutdown %{ " /*code goes here*/ " %} to
+// insert code in the PHP_MSHUTDOWN_FUNCTION
+#define %shutdown  %insert("shutdown")
+#define %mshutdown  %insert("shutdown")
+
+// use %rshutdown %{ " /*code goes here*/" %} to
+// insert code in the PHP_RSHUTDOWN_FUNCTION
+#define %rshutdown  %insert("rshutdown")
+
+/* Typemaps for input parameters by value */
+
+%include <utils.i>
+
+%pass_by_val(bool,CONVERT_BOOL_IN);
+
+%pass_by_val(size_t, CONVERT_INT_IN);
+
+%pass_by_val(enum SWIGTYPE, CONVERT_INT_IN);
+
+%pass_by_val(signed int, CONVERT_INT_IN);
+%pass_by_val(int,CONVERT_INT_IN);
+%pass_by_val(unsigned int,CONVERT_INT_IN);
+
+%pass_by_val(signed short, CONVERT_INT_IN);
+%pass_by_val(short,CONVERT_INT_IN);
+%pass_by_val(unsigned short, CONVERT_INT_IN);
+
+%pass_by_val(signed long, CONVERT_INT_IN);
+%pass_by_val(long, CONVERT_INT_IN);
+%pass_by_val(unsigned long, CONVERT_INT_IN);
+
+%pass_by_val(signed char, CONVERT_INT_IN);
+%pass_by_val(char, CONVERT_CHAR_IN);
+%pass_by_val(unsigned char, CONVERT_INT_IN);
+
+%pass_by_val(float, CONVERT_FLOAT_IN);
+
+%pass_by_val(double, CONVERT_FLOAT_IN);
+
+%pass_by_val(char *, CONVERT_STRING_IN);
+
+// char array can be in/out, though the passed string may not be big enough...
+// so we have to size it
+%typemap(in) char[ANY]
+{
+   convert_to_string_ex($input);
+   $1 = ($1_ltype) Z_STRVAL_PP($input);
+}
+
+/* Object passed by value. Convert to a pointer */
+%typemap(in) SWIGTYPE ($&1_ltype tmp)
+{
+	if(SWIG_ConvertPtr(*$input, (void **) &tmp, $&1_descriptor, 0) < 0 || tmp == NULL) {
+          SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor");
+	}
+	$1 = *tmp;
+}
+
+%typemap(in) SWIGTYPE *,
+	     SWIGTYPE []
+{
+	if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) {
+            SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor");
+	}
+}
+
+%typemap(in) SWIGTYPE &
+{
+	if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0 || $1 == NULL) {
+	    SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $1_descriptor");
+	}
+}
+
+%typemap(in) SWIGTYPE *DISOWN
+{
+  if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, SWIG_POINTER_DISOWN ) < 0) {
+    SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor");
+  }
+}
+%typemap(argout) SWIGTYPE *,
+                 SWIGTYPE [],
+                 SWIGTYPE&;
+
+%typemap(in) void *
+{
+	if(SWIG_ConvertPtr(*$input, (void **) &$1, 0, 0) < 0) {
+	  /* Allow NULL from php for void* */
+	  if ((*$input)->type==IS_NULL) $1=0;
+	  else
+            SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected $&1_descriptor");
+	}
+}
+
+/* Special case when void* is passed by reference so it can be made to point
+   to opaque api structs */
+%typemap(in) void ** ($*1_ltype ptr, int force),
+             void *& ($*1_ltype ptr, int force)
+{
+  /* If they pass NULL by reference, make it into a void*
+     This bit should go in arginit if arginit support init-ing scripting args */
+  if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) {
+    /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */
+    if (!((*$input)->type==IS_NULL && PZVAL_IS_REF(*$input))) {
+      /* wasn't a pre/ref/thing, OR anything like an int thing */
+      SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname.");
+    }
+  }
+  force=0;
+  if (arg1==NULL) {
+#ifdef __cplusplus
+    ptr=new $*1_ltype;
+#else
+    ptr=($*1_ltype) calloc(1,sizeof($*1_ltype));
+#endif
+    $1=&ptr;
+    /* have to passback arg$arg too */
+    force=1;
+  }
+}
+%typemap(argout) void **,
+                 void *&
+{
+  if (force$argnum) {
+    SWIG_SetPointerZval( *$input, (void*) ptr$argnum, $*1_descriptor, 1);
+  }
+}
+
+/* Typemap for output values */
+
+%typemap(out) int,
+              unsigned int,
+              short,
+              unsigned short,
+              long,
+              unsigned long,
+              signed char,
+              unsigned char,
+              bool,
+              size_t,
+              enum SWIGTYPE
+{
+	ZVAL_LONG(return_value,$1);
+}
+
+%typemap(out) bool
+{
+	ZVAL_BOOL(return_value,($1)?1:0);
+}
+
+%typemap(out) float,
+              double
+{
+	ZVAL_DOUBLE(return_value,$1);
+}
+
+%typemap(out) char
+{
+	ZVAL_STRINGL(return_value,&$1, 1, 1);
+}
+
+%typemap(out) char *,
+              char []
+{
+	if(!$1) {
+	  ZVAL_NULL(return_value);
+	} else {
+	  ZVAL_STRING(return_value, (char *)$1, 1);
+	}
+}
+
+%typemap(out) SWIGTYPE *,
+              SWIGTYPE [],
+              SWIGTYPE &
+{
+	SWIG_SetPointerZval(return_value, (void *)$1, $1_descriptor, $owner);
+}
+
+%typemap(out) SWIGTYPE *DYNAMIC,
+              SWIGTYPE &DYNAMIC
+{
+        swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor, (void **) &$1);
+	SWIG_SetPointerZval(return_value, (void *)$1, ty, $owner);
+}
+
+%typemap(out) SWIGTYPE
+#ifdef __cplusplus
+{
+  $&1_ltype resultobj = new $1_ltype((const $1_ltype &) $1);
+  SWIG_SetPointerZval(return_value, (void *)resultobj, $&1_descriptor, 1);
+}
+#else
+{
+  $&1_ltype resultobj = ($&1_ltype) emalloc(sizeof($1_type));
+  memmove(resultobj, &$1, sizeof($1_type));
+  SWIG_SetPointerZval(return_value, (void *)resultobj, $&1_descriptor, 1);
+}
+#endif
+
+%typemap(out) void "";
+
+%typemap(out) char [ANY]
+{
+  RETVAL_STRINGL($1,$1_dim0,1);
+}
+
+// This typecheck does hard checking for proper argument type.  If you want
+// an argument to be converted from a different PHP type, you must convert
+// it yourself before passing it (e.g. (string)4.7 or (int)"6").
+%define %php_typecheck(_type,_prec,is)
+%typemap(typecheck,precedence=_prec) _type
+ " $1 = (Z_TYPE_PP($input) == is); "
+%enddef
+
+%php_typecheck(int,SWIG_TYPECHECK_INTEGER,IS_LONG)
+%php_typecheck(unsigned int,SWIG_TYPECHECK_UINT32,IS_LONG)
+%php_typecheck(short,SWIG_TYPECHECK_INT16,IS_LONG)
+%php_typecheck(unsigned short,SWIG_TYPECHECK_UINT16,IS_LONG)
+%php_typecheck(long,SWIG_TYPECHECK_INT64,IS_LONG)
+%php_typecheck(unsigned long,SWIG_TYPECHECK_UINT64,IS_LONG)
+%php_typecheck(signed char,SWIG_TYPECHECK_INT8,IS_LONG)
+%php_typecheck(unsigned char,SWIG_TYPECHECK_UINT8,IS_LONG)
+%php_typecheck(size_t,SWIG_TYPECHECK_INT16,IS_LONG)
+%php_typecheck(enum SWIGTYPE,SWIG_TYPECHECK_INT8,IS_LONG)
+%php_typecheck(bool,SWIG_TYPECHECK_BOOL,IS_BOOL)
+
+%php_typecheck(char,SWIG_TYPECHECK_CHAR,IS_STRING)
+%php_typecheck(char *,SWIG_TYPECHECK_STRING,IS_STRING)
+%php_typecheck(char [],SWIG_TYPECHECK_STRING,IS_STRING)
+
+%php_typecheck(float,SWIG_TYPECHECK_FLOAT,IS_DOUBLE)
+%php_typecheck(double,SWIG_TYPECHECK_BOOL,IS_DOUBLE)
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE
+ " /* typecheck SWIGTYPE */ "
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *,
+             SWIGTYPE [],
+             SWIGTYPE &
+{
+  void *tmp;
+  _v = (SWIG_ConvertPtr( *$input, (void**)&tmp, $1_descriptor, 0) >= 0);
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void *
+ " /* typecheck void * */ "
+
+
+/* Exception handling */
+
+%typemap(throws) int,
+                 long,
+                 short,
+                 unsigned int,
+                 unsigned long,
+                 unsigned short {
+  char error_msg[256];
+  sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1);
+  SWIG_PHP_Error(E_ERROR, error_msg);
+}
+
+%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{
+  (void)$1;
+  SWIG_PHP_Error(E_ERROR, "C++ $1_type exception thrown");
+%}
+
+%typemap(throws) char * %{
+  SWIG_PHP_Error(E_ERROR, (char *)$1);
+%}
+
+
+/* php keywords */
+%include <php4kw.swg>
diff --git a/trunk/Lib/php4/php4init.swg b/trunk/Lib/php4/php4init.swg
new file mode 100644
index 0000000..b7a0fc9
--- /dev/null
+++ b/trunk/Lib/php4/php4init.swg
@@ -0,0 +1,12 @@
+
+/* ------------------------------------------------------------
+ * The start of the PHP initialization function 
+ * ------------------------------------------------------------ */
+
+%insert(init) "swiginit.swg"
+
+%init %{
+  SWIG_php_minit {
+    SWIG_InitializeModule(0);
+%}
+
diff --git a/trunk/Lib/php4/php4kw.swg b/trunk/Lib/php4/php4kw.swg
new file mode 100644
index 0000000..a6b5194
--- /dev/null
+++ b/trunk/Lib/php4/php4kw.swg
@@ -0,0 +1,461 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * php4kw.swg
+ *
+ * The 'keywords' in PHP are global, ie, the following names are fine
+ * when used as class methods.
+ * ----------------------------------------------------------------------------- */
+
+#define PHPKW(x) %keywordwarn("'" `x` "' is a php keyword, renamed as 'c_" `x` "'",sourcefmt="%(lower)s", rename="c_%s",fullname=1)  `x`
+
+%define PHPCN(x) 
+%keywordwarn("'" `x` "' is a php reserved class name, class renamed as 'c_" `x` "'",%$isclass,rename="c_%s") `x`;
+%keywordwarn("'" `x` "' is a php reserved class name, constructor renamed as 'c_" `x` "'",%$isconstructor,rename="c_%s") `x`;
+%enddef
+
+#define PHPBN1(x) %builtinwarn("'" `x` "' conflicts with a built-in name in php",sourcefmt="%(lower)s",fullname=1)  `x`
+#define PHPBN2(x) %builtinwarn("'" `x` "' conflicts with a built-in name in php")  "::" `x`
+
+
+/*
+   From
+
+     http://aspn.activestate.com/ASPN/docs/PHP/reserved.html
+
+   and reviewed by Olly Betts.
+
+   Further updates from the PHP manual on php.net.
+*/
+
+/* We classify these as kw since PHP will not run if used globally. */
+/* case insensitive */
+PHPKW(and);
+PHPKW(array);
+PHPKW(as);
+PHPKW(break);
+PHPKW(case);
+PHPKW(cfunction); /* No longer reserved in PHP5 */
+PHPKW(class);
+PHPKW(const);
+PHPKW(continue);
+PHPKW(declare);
+PHPKW(default);
+PHPKW(die);
+PHPKW(do);
+PHPKW(echo);
+PHPKW(else);
+PHPKW(elseif);
+PHPKW(empty);
+PHPKW(enddeclare);
+PHPKW(endfor);
+PHPKW(endforeach);
+PHPKW(endif);
+PHPKW(endswitch);
+PHPKW(endwhile);
+PHPKW(eval);
+PHPKW(exit);
+PHPKW(extends);
+PHPKW(for);
+PHPKW(foreach);
+PHPKW(function);
+PHPKW(global);
+PHPKW(if);
+PHPKW(include);
+PHPKW(include_once);
+PHPKW(isset);
+PHPKW(list);
+PHPKW(new);
+PHPKW(old_function); /* No longer reserved in PHP5 */
+PHPKW(or);
+PHPKW(print);
+PHPKW(require);
+PHPKW(require_once);
+PHPKW(return);
+PHPKW(static);
+PHPKW(switch);
+PHPKW(unset);
+PHPKW(use);
+PHPKW(var);
+PHPKW(while);
+PHPKW(xor);
+PHPKW(__FILE__);
+PHPKW(__LINE__);
+PHPKW(__FUNCTION__);
+PHPKW(__CLASS__);
+
+/* Added in PHP5 */
+PHPKW(__halt_compiler);
+PHPKW(abstract);
+PHPKW(catch);
+PHPKW(clone);
+PHPKW(final);
+PHPKW(implements);
+PHPKW(instanceof);
+PHPKW(interface);
+PHPKW(private);
+PHPKW(protected);
+PHPKW(public);
+PHPKW(throw);
+PHPKW(try);
+PHPKW(__METHOD__);
+
+/* We classify these as built-in names since they conflict, but PHP still runs */
+
+/* Type 1: case insensitive */
+PHPBN1(__sleep);
+PHPBN1(__wakeup);
+PHPBN1(not);
+PHPBN1(parent);
+PHPBN1(virtual);
+PHPBN1(NULL);
+PHPBN1(TRUE);
+PHPBN1(FALSE);
+
+/* Type 2: case sensitive */
+/* "Core Predefined Constants" from http://uk2.php.net/manual/en/reserved.constants.php */
+PHPBN2(E_ALL);
+PHPBN2(E_ERROR);
+PHPBN2(E_PARSE);
+PHPBN2(E_WARNING);
+PHPBN2(E_NOTICE);
+PHPBN2(E_CORE_ERROR);
+PHPBN2(E_CORE_WARNING);
+PHPBN2(E_COMPILE_ERROR);
+PHPBN2(E_COMPILE_WARNING);
+PHPBN2(E_USER_ERROR);
+PHPBN2(E_USER_WARNING);
+PHPBN2(E_USER_NOTICE);
+PHPBN2(PHP_OS);
+PHPBN2(PHP_VERSION);
+PHPBN2(PHP_SAPI);
+PHPBN2(PHP_EOL);
+PHPBN2(PHP_INT_MAX);
+PHPBN2(PHP_INT_SIZE);
+PHPBN2(DEFAULT_INCLUDE_PATH);
+PHPBN2(PEAR_INSTALL_DIR);
+PHPBN2(PEAR_EXTENSION_DIR);
+PHPBN2(PHP_EXTENSION_DIR);
+PHPBN2(PHP_PREFIX);
+PHPBN2(PHP_BINDIR);
+PHPBN2(PHP_LIBDIR);
+PHPBN2(PHP_DATADIR);
+PHPBN2(PHP_SYSCONFDIR);
+PHPBN2(PHP_LOCALSTATEDIR);
+PHPBN2(PHP_CONFIG_FILE_PATH);
+PHPBN2(PHP_CONFIG_FILE_SCAN_DIR);
+PHPBN2(PHP_SHLIB_SUFFIX);
+PHPBN2(PHP_OUTPUT_HANDLER_START);
+PHPBN2(PHP_OUTPUT_HANDLER_CONT);
+PHPBN2(PHP_OUTPUT_HANDLER_END);
+/* "Standard Predefined Constants" from http://uk2.php.net/manual/en/reserved.constants.php */
+PHPBN2(EXTR_OVERWRITE);
+PHPBN2(EXTR_SKIP);
+PHPBN2(EXTR_PREFIX_SAME);
+PHPBN2(EXTR_PREFIX_ALL);
+PHPBN2(EXTR_PREFIX_INVALID);
+PHPBN2(EXTR_PREFIX_IF_EXISTS);
+PHPBN2(EXTR_IF_EXISTS);
+PHPBN2(SORT_ASC);
+PHPBN2(SORT_DESC);
+PHPBN2(SORT_REGULAR);
+PHPBN2(SORT_NUMERIC);
+PHPBN2(SORT_STRING);
+PHPBN2(CASE_LOWER);
+PHPBN2(CASE_UPPER);
+PHPBN2(COUNT_NORMAL);
+PHPBN2(COUNT_RECURSIVE);
+PHPBN2(ASSERT_ACTIVE);
+PHPBN2(ASSERT_CALLBACK);
+PHPBN2(ASSERT_BAIL);
+PHPBN2(ASSERT_WARNING);
+PHPBN2(ASSERT_QUIET_EVAL);
+PHPBN2(CONNECTION_ABORTED);
+PHPBN2(CONNECTION_NORMAL);
+PHPBN2(CONNECTION_TIMEOUT);
+PHPBN2(INI_USER);
+PHPBN2(INI_PERDIR);
+PHPBN2(INI_SYSTEM);
+PHPBN2(INI_ALL);
+PHPBN2(M_E);
+PHPBN2(M_LOG2E);
+PHPBN2(M_LOG10E);
+PHPBN2(M_LN2);
+PHPBN2(M_LN10);
+PHPBN2(M_PI);
+PHPBN2(M_PI_2);
+PHPBN2(M_PI_4);
+PHPBN2(M_1_PI);
+PHPBN2(M_2_PI);
+PHPBN2(M_2_SQRTPI);
+PHPBN2(M_SQRT2);
+PHPBN2(M_SQRT1_2);
+PHPBN2(CRYPT_SALT_LENGTH);
+PHPBN2(CRYPT_STD_DES);
+PHPBN2(CRYPT_EXT_DES);
+PHPBN2(CRYPT_MD5);
+PHPBN2(CRYPT_BLOWFISH);
+PHPBN2(DIRECTORY_SEPARATOR);
+PHPBN2(SEEK_SET);
+PHPBN2(SEEK_CUR);
+PHPBN2(SEEK_END);
+PHPBN2(LOCK_SH);
+PHPBN2(LOCK_EX);
+PHPBN2(LOCK_UN);
+PHPBN2(LOCK_NB);
+PHPBN2(HTML_SPECIALCHARS);
+PHPBN2(HTML_ENTITIES);
+PHPBN2(ENT_COMPAT);
+PHPBN2(ENT_QUOTES);
+PHPBN2(ENT_NOQUOTES);
+PHPBN2(INFO_GENERAL);
+PHPBN2(INFO_CREDITS);
+PHPBN2(INFO_CONFIGURATION);
+PHPBN2(INFO_MODULES);
+PHPBN2(INFO_ENVIRONMENT);
+PHPBN2(INFO_VARIABLES);
+PHPBN2(INFO_LICENSE);
+PHPBN2(INFO_ALL);
+PHPBN2(CREDITS_GROUP);
+PHPBN2(CREDITS_GENERAL);
+PHPBN2(CREDITS_SAPI);
+PHPBN2(CREDITS_MODULES);
+PHPBN2(CREDITS_DOCS);
+PHPBN2(CREDITS_FULLPAGE);
+PHPBN2(CREDITS_QA);
+PHPBN2(CREDITS_ALL);
+PHPBN2(STR_PAD_LEFT);
+PHPBN2(STR_PAD_RIGHT);
+PHPBN2(STR_PAD_BOTH);
+PHPBN2(PATHINFO_DIRNAME);
+PHPBN2(PATHINFO_BASENAME);
+PHPBN2(PATHINFO_EXTENSION);
+PHPBN2(PATH_SEPARATOR);
+PHPBN2(CHAR_MAX);
+PHPBN2(LC_CTYPE);
+PHPBN2(LC_NUMERIC);
+PHPBN2(LC_TIME);
+PHPBN2(LC_COLLATE);
+PHPBN2(LC_MONETARY);
+PHPBN2(LC_ALL);
+PHPBN2(LC_MESSAGES);
+PHPBN2(ABDAY_1);
+PHPBN2(ABDAY_2);
+PHPBN2(ABDAY_3);
+PHPBN2(ABDAY_4);
+PHPBN2(ABDAY_5);
+PHPBN2(ABDAY_6);
+PHPBN2(ABDAY_7);
+PHPBN2(DAY_1);
+PHPBN2(DAY_2);
+PHPBN2(DAY_3);
+PHPBN2(DAY_4);
+PHPBN2(DAY_5);
+PHPBN2(DAY_6);
+PHPBN2(DAY_7);
+PHPBN2(ABMON_1);
+PHPBN2(ABMON_2);
+PHPBN2(ABMON_3);
+PHPBN2(ABMON_4);
+PHPBN2(ABMON_5);
+PHPBN2(ABMON_6);
+PHPBN2(ABMON_7);
+PHPBN2(ABMON_8);
+PHPBN2(ABMON_9);
+PHPBN2(ABMON_10);
+PHPBN2(ABMON_11);
+PHPBN2(ABMON_12);
+PHPBN2(MON_1);
+PHPBN2(MON_2);
+PHPBN2(MON_3);
+PHPBN2(MON_4);
+PHPBN2(MON_5);
+PHPBN2(MON_6);
+PHPBN2(MON_7);
+PHPBN2(MON_8);
+PHPBN2(MON_9);
+PHPBN2(MON_10);
+PHPBN2(MON_11);
+PHPBN2(MON_12);
+PHPBN2(AM_STR);
+PHPBN2(PM_STR);
+PHPBN2(D_T_FMT);
+PHPBN2(D_FMT);
+PHPBN2(T_FMT);
+PHPBN2(T_FMT_AMPM);
+PHPBN2(ERA);
+PHPBN2(ERA_YEAR);
+PHPBN2(ERA_D_T_FMT);
+PHPBN2(ERA_D_FMT);
+PHPBN2(ERA_T_FMT);
+PHPBN2(ALT_DIGITS);
+PHPBN2(INT_CURR_SYMBOL);
+PHPBN2(CURRENCY_SYMBOL);
+PHPBN2(CRNCYSTR);
+PHPBN2(MON_DECIMAL_POINT);
+PHPBN2(MON_THOUSANDS_SEP);
+PHPBN2(MON_GROUPING);
+PHPBN2(POSITIVE_SIGN);
+PHPBN2(NEGATIVE_SIGN);
+PHPBN2(INT_FRAC_DIGITS);
+PHPBN2(FRAC_DIGITS);
+PHPBN2(P_CS_PRECEDES);
+PHPBN2(P_SEP_BY_SPACE);
+PHPBN2(N_CS_PRECEDES);
+PHPBN2(N_SEP_BY_SPACE);
+PHPBN2(P_SIGN_POSN);
+PHPBN2(N_SIGN_POSN);
+PHPBN2(DECIMAL_POINT);
+PHPBN2(RADIXCHAR);
+PHPBN2(THOUSANDS_SEP);
+PHPBN2(THOUSEP);
+PHPBN2(GROUPING);
+PHPBN2(YESEXPR);
+PHPBN2(NOEXPR);
+PHPBN2(YESSTR);
+PHPBN2(NOSTR);
+PHPBN2(CODESET);
+PHPBN2(LOG_EMERG);
+PHPBN2(LOG_ALERT);
+PHPBN2(LOG_CRIT);
+PHPBN2(LOG_ERR);
+PHPBN2(LOG_WARNING);
+PHPBN2(LOG_NOTICE);
+PHPBN2(LOG_INFO);
+PHPBN2(LOG_DEBUG);
+PHPBN2(LOG_KERN);
+PHPBN2(LOG_USER);
+PHPBN2(LOG_MAIL);
+PHPBN2(LOG_DAEMON);
+PHPBN2(LOG_AUTH);
+PHPBN2(LOG_SYSLOG);
+PHPBN2(LOG_LPR);
+PHPBN2(LOG_NEWS);
+PHPBN2(LOG_UUCP);
+PHPBN2(LOG_CRON);
+PHPBN2(LOG_AUTHPRIV);
+PHPBN2(LOG_LOCAL0);
+PHPBN2(LOG_LOCAL1);
+PHPBN2(LOG_LOCAL2);
+PHPBN2(LOG_LOCAL3);
+PHPBN2(LOG_LOCAL4);
+PHPBN2(LOG_LOCAL5);
+PHPBN2(LOG_LOCAL6);
+PHPBN2(LOG_LOCAL7);
+PHPBN2(LOG_PID);
+PHPBN2(LOG_CONS);
+PHPBN2(LOG_ODELAY);
+PHPBN2(LOG_NDELAY);
+PHPBN2(LOG_NOWAIT);
+PHPBN2(LOG_PERROR);
+
+/* Added in PHP5 */
+PHPBN2(E_STRICT);
+PHPBN2(__COMPILER_HALT_OFFSET__);
+
+/* Class names reserved by PHP */
+PHPCN(stdClass);
+PHPCN(__PHP_Incomplete_Class);
+PHPCN(Directory);
+
+/* Added in PHP5 (this list apparently depends which extensions you load by default). */
+PHPCN(parent);
+PHPCN(self);
+PHPCN(Exception);
+PHPCN(php_user_filter);
+PHPCN(ErrorException);
+PHPCN(XMLWriter);
+PHPCN(LibXMLError);
+PHPCN(SimpleXMLElement);
+PHPCN(SoapClient);
+PHPCN(SoapVar);
+PHPCN(SoapServer);
+PHPCN(SoapFault);
+PHPCN(SoapParam);
+PHPCN(SoapHeader);
+PHPCN(RecursiveIteratorIterator);
+PHPCN(FilterIterator);
+PHPCN(RecursiveFilterIterator);
+PHPCN(ParentIterator);
+PHPCN(LimitIterator);
+PHPCN(CachingIterator);
+PHPCN(RecursiveCachingIterator);
+PHPCN(IteratorIterator);
+PHPCN(NoRewindIterator);
+PHPCN(AppendIterator);
+PHPCN(InfiniteIterator);
+PHPCN(EmptyIterator);
+PHPCN(ArrayObject);
+PHPCN(ArrayIterator);
+PHPCN(RecursiveArrayIterator);
+PHPCN(SplFileInfo);
+PHPCN(DirectoryIterator);
+PHPCN(RecursiveDirectoryIterator);
+PHPCN(SplFileObject);
+PHPCN(SplTempFileObject);
+PHPCN(SimpleXMLIterator);
+PHPCN(LogicException);
+PHPCN(BadFunctionCallException);
+PHPCN(BadMethodCallException);
+PHPCN(DomainException);
+PHPCN(InvalidArgumentException);
+PHPCN(LengthException);
+PHPCN(OutOfRangeException);
+PHPCN(RuntimeException);
+PHPCN(OutOfBoundsException);
+PHPCN(OverflowException);
+PHPCN(RangeException);
+PHPCN(UnderflowException);
+PHPCN(UnexpectedValueException);
+PHPCN(SplObjectStorage);
+PHPCN(ReflectionException);
+PHPCN(Reflection);
+PHPCN(ReflectionFunction);
+PHPCN(ReflectionParameter);
+PHPCN(ReflectionMethod);
+PHPCN(ReflectionClass);
+PHPCN(ReflectionObject);
+PHPCN(ReflectionProperty);
+PHPCN(ReflectionExtension);
+PHPCN(DOMException);
+PHPCN(DOMStringList);
+PHPCN(DOMNameList);
+PHPCN(DOMImplementationList);
+PHPCN(DOMImplementationSource);
+PHPCN(DOMImplementation);
+PHPCN(DOMNode);
+PHPCN(DOMNameSpaceNode);
+PHPCN(DOMDocumentFragment);
+PHPCN(DOMDocument);
+PHPCN(DOMNodeList);
+PHPCN(DOMNamedNodeMap);
+PHPCN(DOMCharacterData);
+PHPCN(DOMAttr);
+PHPCN(DOMElement);
+PHPCN(DOMText);
+PHPCN(DOMComment);
+PHPCN(DOMTypeinfo);
+PHPCN(DOMUserDataHandler);
+PHPCN(DOMDomError);
+PHPCN(DOMErrorHandler);
+PHPCN(DOMLocator);
+PHPCN(DOMConfiguration);
+PHPCN(DOMCdataSection);
+PHPCN(DOMDocumentType);
+PHPCN(DOMNotation);
+PHPCN(DOMEntity);
+PHPCN(DOMEntityReference);
+PHPCN(DOMProcessingInstruction);
+PHPCN(DOMStringExtend);
+PHPCN(DOMXPath);
+PHPCN(XMLReader);
+PHPCN(SQLiteDatabase);
+PHPCN(SQLiteResult);
+PHPCN(SQLiteUnbuffered);
+PHPCN(SQLiteException);
+
+#undef PHPKW
+#undef PHPBN1
+#undef PHPBN2
+#undef PHPCN
diff --git a/trunk/Lib/php4/php4run.swg b/trunk/Lib/php4/php4run.swg
new file mode 100644
index 0000000..d384527
--- /dev/null
+++ b/trunk/Lib/php4/php4run.swg
@@ -0,0 +1,222 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * php4run.swg
+ *
+ * PHP4 runtime library
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include "zend.h"
+#include "zend_API.h"
+#include "php.h"
+
+#ifdef ZEND_RAW_FENTRY
+/* ZEND_RAW_FENTRY was added somewhere between 5.2.0 and 5.2.3 */
+# define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_RAW_FENTRY((char*)#ZN, N, A, 0)
+#else
+/* This causes warnings from GCC >= 4.2 (assigning a string literal to char*).
+ * But this seems to be unavoidable without directly assuming knowledge of
+ * the structure, which changed between PHP4 and PHP5. */
+# define SWIG_ZEND_NAMED_FE(ZN, N, A) ZEND_NAMED_FE(ZN, N, A)
+#endif
+
+#define SWIG_LONG_CONSTANT(N, V) zend_register_long_constant((char*)#N, sizeof(#N), V, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC)
+#define SWIG_DOUBLE_CONSTANT(N, V) zend_register_double_constant((char*)#N, sizeof(#N), V, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC)
+#define SWIG_STRING_CONSTANT(N, V) zend_register_stringl_constant((char*)#N, sizeof(#N), V, strlen(V), CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC)
+#define SWIG_CHAR_CONSTANT(N, V) do {\
+    static char swig_char = (V);\
+    zend_register_stringl_constant((char*)#N, sizeof(#N), &swig_char, 1, CONST_CS | CONST_PERSISTENT, module_number TSRMLS_CC);\
+} while (0)
+
+/* These TSRMLS_ stuff should already be defined now, but with older php under
+   redhat are not... */
+#ifndef TSRMLS_D
+#define TSRMLS_D
+#endif
+#ifndef TSRMLS_DC
+#define TSRMLS_DC
+#endif
+#ifndef TSRMLS_C
+#define TSRMLS_C
+#endif
+#ifndef TSRMLS_CC
+#define TSRMLS_CC
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/* But in fact SWIG_ConvertPtr is the native interface for getting typed
+   pointer values out of zvals.  We need the TSRMLS_ macros for when we
+   make PHP type calls later as we handle php resources */
+#define SWIG_ConvertPtr(obj,pp,type,flags) SWIG_ZTS_ConvertPtr(obj,pp,type,flags TSRMLS_CC)
+
+
+#define SWIG_fail goto fail
+
+static const char *default_error_msg = "Unknown error occurred";
+static int default_error_code = E_ERROR;
+
+#define SWIG_PHP_Arg_Error_Msg(argnum,extramsg) "Error in argument " #argnum " "#extramsg
+
+#define SWIG_PHP_Error(code,msg) do { SWIG_ErrorCode() = code; SWIG_ErrorMsg() = msg; SWIG_fail; } while (0)
+
+#define SWIG_contract_assert(expr,msg) \
+  if (!(expr) ) { zend_printf("Contract Assert Failed %s\n",msg ); } else
+
+/* Standard SWIG API */
+#define SWIG_GetModule(clientdata) SWIG_Php4_GetModule()
+#define SWIG_SetModule(clientdata, pointer) SWIG_Php4_SetModule(pointer)
+
+/* used to wrap returned objects in so we know whether they are newobject
+   and need freeing, or not */
+typedef struct _swig_object_wrapper {
+  void * ptr;
+  int newobject;
+} swig_object_wrapper;
+
+/* empty zend destructor for types without one */
+static ZEND_RSRC_DTOR_FUNC(SWIG_landfill) { (void)rsrc; }
+
+#define SWIG_SetPointerZval(a,b,c,d) SWIG_ZTS_SetPointerZval(a,b,c,d TSRMLS_CC)
+
+static void
+SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject TSRMLS_DC) {
+  swig_object_wrapper *value=NULL;
+  /*
+   * First test for Null pointers.  Return those as PHP native NULL
+   */
+  if (!ptr ) {
+    ZVAL_NULL(z);
+    return;
+  }
+  if (type->clientdata) {
+    if (! (*(int *)(type->clientdata)))
+      zend_error(E_ERROR, "Type: %s failed to register with zend",type->name);
+    value=(swig_object_wrapper *)emalloc(sizeof(swig_object_wrapper));
+    value->ptr=ptr;
+    value->newobject=newobject;
+    ZEND_REGISTER_RESOURCE(z, value, *(int *)(type->clientdata));
+    return;
+  }
+  zend_error(E_ERROR, "Type: %s not registered with zend",type->name);
+}
+
+/* This pointer conversion routine takes the native pointer p (along with
+   its type name) and converts it by calling appropriate casting functions
+   according to ty.  The resultant pointer is returned, or NULL is returned
+   if the pointer can't be cast.
+
+   Sadly PHP has no API to find a type name from a type id, only from an
+   instance of a resource of the type id, so we have to pass type_name as well.
+
+   The two functions which might call this are:
+   SWIG_ZTS_ConvertResourcePtr which gets the type name from the resource
+   and the registered zend destructors for which we have one per type each
+   with the type name hard wired in. */
+static void *
+SWIG_ZTS_ConvertResourceData(void * p, const char *type_name, swig_type_info *ty TSRMLS_DC) {
+  swig_cast_info *tc;
+  void *result = 0;
+
+  if (!ty) {
+    /* They don't care about the target type, so just pass on the pointer! */
+    return p;
+  }
+
+  if (! type_name) {  
+    /* can't convert p to ptr type ty if we don't know what type p is */
+    return NULL;
+  }
+
+  /* convert and cast p from type_name to ptr as ty. */
+  tc = SWIG_TypeCheck(type_name, ty);
+  if (tc) {
+    int newmemory = 0;
+    result = SWIG_TypeCast(tc, p, &newmemory);
+    assert(!newmemory); /* newmemory handling not yet implemented */
+  }
+  return result;
+}
+
+/* This function returns a pointer of type ty by extracting the pointer
+   and type info from the resource in z.  z must be a resource.
+   If it fails, NULL is returned.
+   It uses SWIG_ZTS_ConvertResourceData to do the real work. */
+static void *
+SWIG_ZTS_ConvertResourcePtr(zval *z, swig_type_info *ty, int flags TSRMLS_DC) {
+  swig_object_wrapper *value;
+  void *p;
+  int type;
+  char *type_name;
+
+  value = (swig_object_wrapper *) zend_list_find(z->value.lval, &type);
+  if ( flags && SWIG_POINTER_DISOWN ) {
+    value->newobject = 0;
+  }
+  p = value->ptr;
+  if (type==-1) return NULL;
+
+  type_name=zend_rsrc_list_get_rsrc_type(z->value.lval TSRMLS_CC);
+
+  return SWIG_ZTS_ConvertResourceData(p, type_name, ty TSRMLS_CC);
+}
+
+/* We allow passing of a RESOURCE pointing to the object or an OBJECT whose
+   _cPtr is a resource pointing to the object */
+static int
+SWIG_ZTS_ConvertPtr(zval *z, void **ptr, swig_type_info *ty, int flags TSRMLS_DC) {
+  if (z == NULL) {
+    *ptr = 0;
+    return 0;
+  }
+
+  switch (z->type) {
+    case IS_OBJECT: {
+      zval ** _cPtr;
+      if (zend_hash_find(HASH_OF(z),(char*)"_cPtr",sizeof("_cPtr"),(void**)&_cPtr)==SUCCESS) {
+	if ((*_cPtr)->type==IS_RESOURCE) {
+	  *ptr = SWIG_ZTS_ConvertResourcePtr(*_cPtr, ty, flags TSRMLS_CC);
+	  return (*ptr == NULL ? -1 : 0);
+	}
+      }
+      break;
+    }
+    case IS_RESOURCE:
+      *ptr = SWIG_ZTS_ConvertResourcePtr(z, ty, flags TSRMLS_CC);
+      return (*ptr == NULL ? -1 : 0);
+    case IS_NULL:
+      *ptr = 0;
+      return 0;
+  }
+
+  return -1;
+}
+
+static char const_name[] = "swig_runtime_data_type_pointer";
+static swig_module_info *SWIG_Php4_GetModule() {
+  zval *pointer;
+  swig_module_info *ret = 0;
+
+  MAKE_STD_ZVAL(pointer);
+
+  TSRMLS_FETCH();
+
+  if (zend_get_constant(const_name, sizeof(const_name), pointer TSRMLS_CC)) {
+    if (pointer->type == IS_LONG) {
+      ret = (swig_module_info *) pointer->value.lval;
+    }
+  } 
+  FREE_ZVAL(pointer);
+  return ret; 
+}
+
+static void SWIG_Php4_SetModule(swig_module_info *pointer) {
+  TSRMLS_FETCH();
+  REGISTER_MAIN_LONG_CONSTANT(const_name, (long) pointer, 0);
+}
diff --git a/trunk/Lib/php4/phppointers.i b/trunk/Lib/php4/phppointers.i
new file mode 100644
index 0000000..91b2c6d
--- /dev/null
+++ b/trunk/Lib/php4/phppointers.i
@@ -0,0 +1,42 @@
+%define %pass_by_ref( TYPE, CONVERT_IN, CONVERT_OUT )
+%typemap(in) TYPE *REF ($*1_ltype tmp),
+             TYPE &REF ($*1_ltype tmp)
+%{
+  /* First Check for SWIG wrapped type */
+  if ( ZVAL_IS_NULL( *$input ) ) {
+      $1 = 0;
+  } else if ( PZVAL_IS_REF( *$input ) ) {
+      /* Not swig wrapped type, so we check if it's a PHP reference type */
+      CONVERT_IN( tmp, $*1_ltype, $input );
+      $1 = &tmp;
+  } else {
+      SWIG_PHP_Error( E_ERROR, SWIG_PHP_Arg_Error_Msg($argnum, Expected a reference) );
+  }
+%}
+%typemap(argout) TYPE *REF,
+                 TYPE &REF
+  "CONVERT_OUT(*$input, tmp$argnum );";
+%enddef
+
+%pass_by_ref( size_t, CONVERT_INT_IN, ZVAL_LONG );
+
+%pass_by_ref( signed int, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( int, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( unsigned int, CONVERT_INT_IN, ZVAL_LONG );
+
+%pass_by_ref( signed short, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( short, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( unsigned short, CONVERT_INT_IN, ZVAL_LONG );
+
+%pass_by_ref( signed long, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( long, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( unsigned long, CONVERT_INT_IN, ZVAL_LONG );
+
+%pass_by_ref( signed char, CONVERT_INT_IN, ZVAL_LONG );
+%pass_by_ref( char, CONVERT_CHAR_IN, ZVAL_STRING );
+%pass_by_ref( unsigned char, CONVERT_INT_IN, ZVAL_LONG );
+
+%pass_by_ref( float, CONVERT_FLOAT_IN, ZVAL_DOUBLE );
+%pass_by_ref( double, CONVERT_FLOAT_IN, ZVAL_DOUBLE );
+
+%pass_by_ref( char *, CONVERT_CHAR_IN, ZVAL_STRING );
diff --git a/trunk/Lib/php4/std_common.i b/trunk/Lib/php4/std_common.i
new file mode 100644
index 0000000..a779649
--- /dev/null
+++ b/trunk/Lib/php4/std_common.i
@@ -0,0 +1,13 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_common.i
+ *
+ * SWIG typemaps for STL - common utilities
+ * ----------------------------------------------------------------------------- */
+
+%include <std/std_except.i>
+
+%apply size_t { std::size_t };
+
diff --git a/trunk/Lib/php4/std_deque.i b/trunk/Lib/php4/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/php4/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/php4/std_map.i b/trunk/Lib/php4/std_map.i
new file mode 100644
index 0000000..c35f21d
--- /dev/null
+++ b/trunk/Lib/php4/std_map.i
@@ -0,0 +1,175 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_map.i
+ *
+ * SWIG typemaps for std::map
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, T x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    // add specializations here
+
+}
diff --git a/trunk/Lib/php4/std_pair.i b/trunk/Lib/php4/std_pair.i
new file mode 100644
index 0000000..dc0604d
--- /dev/null
+++ b/trunk/Lib/php4/std_pair.i
@@ -0,0 +1,37 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * SWIG typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+namespace std {
+
+  template<class T, class U> struct pair {
+
+    pair();
+    pair(T first, U second);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+  };
+
+  // add specializations here
+
+}
diff --git a/trunk/Lib/php4/std_string.i b/trunk/Lib/php4/std_string.i
new file mode 100644
index 0000000..08a7cda
--- /dev/null
+++ b/trunk/Lib/php4/std_string.i
@@ -0,0 +1,73 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string types
+ * ----------------------------------------------------------------------------- */
+
+// ------------------------------------------------------------------------
+// std::string is typemapped by value
+// This can prevent exporting methods which return a string
+// in order for the user to modify it.
+// However, I think I'll wait until someone asks for it...
+// ------------------------------------------------------------------------
+
+%include <exception.i>
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+    %naturalvar string;
+
+    class string;
+
+    %typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) string %{
+      $1 = ( Z_TYPE_PP($input) == IS_STRING ) ? 1 : 0;
+    %}
+
+    %typemap(in) string %{
+        convert_to_string_ex($input);
+        $1.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input));
+    %}
+
+    %typemap(typecheck,precedence=SWIG_TYPECHECK_STRING) const string& %{
+      $1 = ( Z_TYPE_PP($input) == IS_STRING ) ? 1 : 0;
+    %}
+
+    %typemap(out) string %{
+        ZVAL_STRINGL($result, const_cast<char*>($1.data()), $1.size(), 1);
+    %}
+
+    %typemap(out) const string & %{
+        ZVAL_STRINGL($result, const_cast<char*>($1->data()), $1->size(), 1);
+    %}
+
+    %typemap(throws) string %{
+      SWIG_PHP_Error(E_ERROR, (char *)$1.c_str());
+    %}
+
+    %typemap(throws) const string& %{
+      SWIG_PHP_Error(E_ERROR, (char *)$1.c_str());
+    %}
+
+    /* These next two handle a function which takes a non-const reference to
+     * a std::string and modifies the string. */
+    %typemap(in) string & (std::string temp) %{
+        convert_to_string_ex($input);
+        temp.assign(Z_STRVAL_PP($input), Z_STRLEN_PP($input));
+        $1 = &temp;
+    %}
+
+    %typemap(argout) string & %{
+	ZVAL_STRINGL(*($input), const_cast<char*>($1->data()), $1->size(), 1);
+    %}
+
+    /* SWIG will apply the non-const typemap above to const string& without
+     * this more specific typemap. */
+    %typemap(argout) const string & "";
+}
diff --git a/trunk/Lib/php4/std_vector.i b/trunk/Lib/php4/std_vector.i
new file mode 100644
index 0000000..fe084ac
--- /dev/null
+++ b/trunk/Lib/php4/std_vector.i
@@ -0,0 +1,132 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ *
+ * SWIG typemaps for std::vector types
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// PHP as much as possible, namely, to allow the user to pass and 
+// be returned PHP lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&), f(const std::vector<T>*):
+//      the parameter being read-only, either a PHP sequence or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f():
+//      the vector is returned by copy; therefore, a PHP sequence of T:s 
+//      is returned which is most easily used in other PHP functions
+//   -- std::vector<T>& f(), std::vector<T>* f(), const std::vector<T>& f(),
+//      const std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+    
+    template<class T> class vector {
+        // add generic typemaps here
+      public:
+        vector(unsigned int size = 0);
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(const T& x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T& get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, const T& x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_vector(T)
+    template<> class vector<T> {
+        // add specialized typemaps here
+      public:
+        vector(unsigned int size = 0);
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(T x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, T x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+    %enddef
+
+    specialize_std_vector(bool);
+    specialize_std_vector(char);
+    specialize_std_vector(int);
+    specialize_std_vector(short);
+    specialize_std_vector(long);
+    specialize_std_vector(unsigned char);
+    specialize_std_vector(unsigned int);
+    specialize_std_vector(unsigned short);
+    specialize_std_vector(unsigned long);
+    specialize_std_vector(float);
+    specialize_std_vector(double);
+
+}
+
diff --git a/trunk/Lib/php4/stl.i b/trunk/Lib/php4/stl.i
new file mode 100644
index 0000000..66b72e0
--- /dev/null
+++ b/trunk/Lib/php4/stl.i
@@ -0,0 +1,15 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/php4/typemaps.i b/trunk/Lib/php4/typemaps.i
new file mode 100644
index 0000000..c388fdf
--- /dev/null
+++ b/trunk/Lib/php4/typemaps.i
@@ -0,0 +1,171 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i.
+ *
+ * SWIG Typemap library for PHP4.
+ *
+ * This library provides standard typemaps for modifying SWIG's behavior.
+ * With enough entries in this file, I hope that very few people actually
+ * ever need to write a typemap.
+ *
+ * Define macros to define the following typemaps:
+ *
+ * TYPE *INPUT.   Argument is passed in as native variable by value.
+ * TYPE *OUTPUT.  Argument is returned as an array from the function call.
+ * TYPE *INOUT.   Argument is passed in by value, and out as part of returned list
+ * TYPE *REFERENCE.  Argument is passed in as native variable with value
+ *                   semantics.  Variable value is changed with result.
+ *                   Use like this:
+ *                   int foo(int *REFERENCE);
+ *
+ *                   $a = 0;
+ *                   $rc = foo($a);
+ *
+ *                   Even though $a looks like it's passed by value,
+ *                   its value can be changed by foo().
+ * ----------------------------------------------------------------------------- */
+
+%define double_typemap(TYPE)
+%typemap(in) TYPE *INPUT(TYPE temp)
+%{
+  convert_to_double_ex($input);
+  temp = (TYPE) Z_DVAL_PP($input);
+  $1 = &temp;
+%}
+%typemap(argout) TYPE *INPUT "";
+%typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp) "$1 = &temp;";
+%typemap(argout,fragment="t_output_helper") TYPE *OUTPUT
+{
+  zval *o;
+  MAKE_STD_ZVAL(o);
+  ZVAL_DOUBLE(o,temp$argnum);
+  t_output_helper( &$result, o );
+}
+%typemap(in) TYPE *REFERENCE (TYPE dvalue)
+%{
+  convert_to_double_ex($input);
+  dvalue = (TYPE) (*$input)->value.dval;
+  $1 = &dvalue;
+%}
+%typemap(argout) TYPE *REFERENCE
+%{
+  $1->value.dval = (double)(lvalue$argnum);
+  $1->type = IS_DOUBLE;
+%}
+%enddef
+
+%define int_typemap(TYPE)
+%typemap(in) TYPE *INPUT(TYPE temp)
+%{
+  convert_to_long_ex($input);
+  temp = (TYPE) Z_LVAL_PP($input);
+  $1 = &temp;
+%}
+%typemap(argout) TYPE *INPUT "";
+%typemap(in,numinputs=0) TYPE *OUTPUT(TYPE temp) "$1 = &temp;";
+%typemap(argout,fragment="t_output_helper") TYPE *OUTPUT
+{
+  zval *o;
+  MAKE_STD_ZVAL(o);
+  ZVAL_LONG(o,temp$argnum);
+  t_output_helper( &$result, o );
+}
+%typemap(in) TYPE *REFERENCE (TYPE lvalue)
+%{
+  convert_to_long_ex($input);
+  lvalue = (TYPE) (*$input)->value.lval;
+  $1 = &lvalue;
+%}
+%typemap(argout) TYPE *REFERENCE
+%{
+  (*$arg)->value.lval = (long)(lvalue$argnum);
+  (*$arg)->type = IS_LONG;
+%}
+%enddef
+
+double_typemap(float);
+double_typemap(double);
+
+int_typemap(int);
+int_typemap(short);
+int_typemap(long);
+int_typemap(unsigned int);
+int_typemap(unsigned short);
+int_typemap(unsigned long);
+int_typemap(unsigned char);
+
+%typemap(in) float *INOUT = float *INPUT;
+%typemap(in) double *INOUT = double *INPUT;
+
+%typemap(in) int *INOUT = int *INPUT;
+%typemap(in) short *INOUT = short *INPUT;
+%typemap(in) long *INOUT = long *INPUT;
+%typemap(in) unsigned *INOUT = unsigned *INPUT;
+%typemap(in) unsigned short *INOUT = unsigned short *INPUT;
+%typemap(in) unsigned long *INOUT = unsigned long *INPUT;
+%typemap(in) unsigned char *INOUT = unsigned char *INPUT;
+
+%typemap(argout) float *INOUT = float *OUTPUT;
+%typemap(argout) double *INOUT= double *OUTPUT;
+
+%typemap(argout) int *INOUT = int *OUTPUT;
+%typemap(argout) short *INOUT = short *OUTPUT;
+%typemap(argout) long *INOUT= long *OUTPUT;
+%typemap(argout) unsigned short *INOUT= unsigned short *OUTPUT;
+%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT;
+%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT;
+
+%typemap(in) char INPUT[ANY] ( char temp[$1_dim0] )
+%{
+  convert_to_string_ex($input);
+  strncpy(temp,Z_LVAL_PP($input),$1_dim0);
+  $1 = temp;
+%}
+%typemap(in,numinputs=0) char OUTPUT[ANY] ( char temp[$1_dim0] )
+  "$1 = temp;";
+%typemap(argout) char OUTPUT[ANY]
+{
+  zval *o;
+  MAKE_STD_ZVAL(o);
+  ZVAL_STRINGL(o,temp$argnum,$1_dim0);
+  t_output_helper( &$result, o );
+}
+
+%typemap(in,numinputs=0) void **OUTPUT (int force),
+                         void *&OUTPUT (int force)
+%{
+  /* If they pass NULL by reference, make it into a void*
+     This bit should go in arginit if arginit support init-ing scripting args */
+  if(SWIG_ConvertPtr(*$input, (void **) &$1, $1_descriptor, 0) < 0) {
+    /* So... we didn't get a ref or ptr, but we'll accept NULL by reference */
+    if (!((*$input)->type==IS_NULL && PZVAL_IS_REF(*$input))) {
+      /* wasn't a pre/ref/thing, OR anything like an int thing */
+      SWIG_PHP_Error(E_ERROR, "Type error in argument $arg of $symname.");
+    }
+  }
+  force=0;
+  if (arg1==NULL) {
+#ifdef __cplusplus
+    ptr=new $*1_ltype;
+#else
+    ptr=($*1_ltype) calloc(1,sizeof($*1_ltype));
+#endif
+    $1=&ptr;
+    /* have to passback arg$arg too */
+    force=1;
+  }
+%}
+
+%typemap(argout) void **OUTPUT,
+                 void *&OUTPUT
+%{
+  if (force$argnum) {  /* pass back arg$argnum through params ($arg) if we can */
+    if (!PZVAL_IS_REF(*$arg)) {
+      SWIG_PHP_Error(E_WARNING, "Parameter $argnum of $symname wasn't passed by reference");
+    } else {
+      SWIG_SetPointerZval(*$arg, (void *) ptr$argnum, $*1_descriptor, 1);
+    }
+  }
+%}
diff --git a/trunk/Lib/php4/utils.i b/trunk/Lib/php4/utils.i
new file mode 100644
index 0000000..f724118
--- /dev/null
+++ b/trunk/Lib/php4/utils.i
@@ -0,0 +1,59 @@
+
+%define CONVERT_BOOL_IN(lvar,t,invar)
+  convert_to_boolean_ex(invar);
+  lvar = (t) Z_LVAL_PP(invar);
+%enddef
+
+%define CONVERT_INT_IN(lvar,t,invar)
+  convert_to_long_ex(invar);
+  lvar = (t) Z_LVAL_PP(invar);
+%enddef
+
+%define CONVERT_INT_OUT(lvar,invar)
+  lvar = (t) Z_LVAL_PP(invar);
+%enddef
+
+%define CONVERT_FLOAT_IN(lvar,t,invar)
+  convert_to_double_ex(invar);
+  lvar = (t) Z_DVAL_PP(invar);
+%enddef
+
+%define CONVERT_CHAR_IN(lvar,t,invar)
+  convert_to_string_ex(invar);
+  lvar = (t) *Z_STRVAL_PP(invar);
+%enddef
+
+%define CONVERT_STRING_IN(lvar,t,invar)
+  convert_to_string_ex(invar);
+  lvar = (t) Z_STRVAL_PP(invar);
+%enddef
+
+%define %pass_by_val( TYPE, CONVERT_IN )
+%typemap(in) TYPE
+%{
+  CONVERT_IN($1,$1_ltype,$input);
+%}
+%enddef
+
+%fragment("t_output_helper","header") %{
+void
+t_output_helper( zval **target, zval *o) {
+  if ( (*target)->type == IS_ARRAY ) {
+    /* it's already an array, just append */
+    add_next_index_zval( *target, o );
+    return;
+  }
+  if ( (*target)->type == IS_NULL ) {
+    REPLACE_ZVAL_VALUE(target,o,1);
+    return;
+  }
+  zval *tmp;
+  ALLOC_INIT_ZVAL(tmp);
+  *tmp = **target;
+  zval_copy_ctor(tmp);
+  array_init(*target);
+  add_next_index_zval( *target, tmp);
+  add_next_index_zval( *target, o);
+
+}
+%}
diff --git a/trunk/Lib/pike/pike.swg b/trunk/Lib/pike/pike.swg
new file mode 100644
index 0000000..e72da8f
--- /dev/null
+++ b/trunk/Lib/pike/pike.swg
@@ -0,0 +1,317 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pike.swg
+ *
+ * Pike configuration module.
+ * ----------------------------------------------------------------------------- */
+
+%insert(runtime) "swigrun.swg";            // Common C API type-checking code
+%insert(runtime) "pikerun.swg";         // Pike run-time code
+
+%insert(runtime) %{
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include <global.h>
+#include <module.h>
+#include <interpret.h>
+#ifdef __cplusplus
+}
+#endif
+%}
+
+/* -----------------------------------------------------------------------------
+ *                          standard typemaps
+ * ----------------------------------------------------------------------------- */
+
+/* --- Input arguments --- */
+
+/* Primitive datatypes. */
+
+%typemap(in, pikedesc="tInt")
+    int, unsigned int, short, unsigned short,
+    long, unsigned long, char, signed char, unsigned char,
+    bool, enum SWIGTYPE, long long, unsigned long long
+{
+    if ($input.type != T_INT)
+        Pike_error("Bad argument: Expected an integer.\n");
+    $1 = ($1_ltype) $input.u.integer;
+}
+
+%typemap(in, pikedesc="tFloat") float, double {
+    if ($input.type != T_FLOAT)
+        Pike_error("Bad argument: Expected a float.\n");
+    $1 = ($1_ltype) $input.u.float_number;
+}
+
+%typemap(in, pikedesc="tStr") char *, char [ANY] {
+    if ($input.type != T_STRING)
+        Pike_error("Bad argument: Expected a string.\n");
+    $1 = ($1_ltype) STR0($input.u.string);
+}
+
+/* Pointers, references and arrays */
+
+%typemap(in) SWIGTYPE *,
+             SWIGTYPE &,
+             SWIGTYPE []
+	"SWIG_ConvertPtr($input.u.object, (void **) &$1, $1_descriptor, 1);"
+	
+/* Void pointer.  Accepts any kind of pointer */
+%typemap(in) void * "/* FIXME */";
+
+/* Object passed by value. Convert to a pointer */
+%typemap(in) SWIGTYPE ($&1_ltype argp) "/* FIXME */";
+
+/* Pointer to a class member */
+%typemap(in) SWIGTYPE (CLASS::*) "/* FIXME */";
+
+/* Const primitive references.  Passed by value */
+
+%typemap(in, pikedesc="tInt") const int & (int temp),
+	     const short & (short temp),
+             const long  & (long temp),
+             const unsigned int & (unsigned int temp),
+             const unsigned short & (unsigned short temp),
+             const unsigned long & (unsigned long temp),
+	     const char & (char temp),
+             const signed char & (signed char temp),
+             const unsigned char & (unsigned char temp),
+             const bool & (bool temp),
+	     const long long & ($*1_ltype temp),
+	     const unsigned long long & ($*1_ltype temp),
+             const enum SWIGTYPE & ($*1_ltype temp)
+{
+  if ($input.type != T_INT)
+    Pike_error("Bad argument: Expected an integer.\n");
+    temp = ($*1_ltype) $input.u.integer;
+    $1 = &temp;
+}
+
+%typemap(in, pikedesc="tFloat") const float & (float temp),
+	     const double & (double temp)
+{
+  if ($input.type != T_FLOAT)
+    Pike_error("Bad argument: Expected a float.\n");
+    temp = ($*1_ltype) $input.u.float_number;
+    $1 = &temp;
+}
+
+/* -----------------------------------------------------------------------------
+ * Output Typemaps
+ * ----------------------------------------------------------------------------- */
+%typemap(out, pikedesc="tInt")
+    int, unsigned int,
+    short, unsigned short,
+    long, unsigned long,
+    char, signed char, unsigned char, 
+    bool, enum SWIGTYPE
+	"push_int($1);";
+
+%typemap(out, pikedesc="tInt") long long	"push_int64($1);";
+%typemap(out, pikedesc="tInt") unsigned long long	"push_int64($1);";
+%typemap(out, pikedesc="tFloat") float, double	"push_float($1);";
+%typemap(out, pikedesc="tStr") char *		"push_text($1);";
+
+/* Pointers, references, and arrays */
+%typemap(out, pikedesc="tObj") SWIGTYPE*, SWIGTYPE &, SWIGTYPE [] "push_object(SWIG_NewPointerObj((void *) $1, $1_descriptor, $owner));";
+
+/* Void return value; don't push anything */
+%typemap(out, pikedesc="tVoid") void		"";
+
+/* Dynamic casts */
+
+%typemap(out) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC "/* FIXME */";
+
+/* Member pointer */
+%typemap(out) SWIGTYPE (CLASS::*) "/* FIXME */";
+
+/* Special typemap for character array return values */
+%typemap(out, pikedesc="tStr") char [ANY], const char [ANY] "push_text($1);";
+
+/* Primitive types--return by value */
+%typemap(out, pikedesc="tObj") SWIGTYPE 
+#ifdef __cplusplus
+{
+  $&1_ltype resultptr;
+  resultptr = new $1_ltype((const $1_ltype &) $1);
+  push_object(SWIG_NewPointerObj((void *) resultptr, $&1_descriptor, 1));
+}
+#else
+{
+  $&1_ltype resultptr;
+  resultptr = ($&1_ltype) malloc(sizeof($1_type));
+  memmove(resultptr, &$1, sizeof($1_type));
+  push_object(SWIG_NewPointerObj((void *) resultptr, $&1_descriptor, 1));
+}
+#endif
+
+/* References to primitive types.  Return by value */
+
+%typemap(out, pikedesc="tInt") const int &, const unsigned int &,
+              const short &, const unsigned short &,
+              const long &, const unsigned long &,
+              const char &, const signed char &, const unsigned char &,
+              const bool &,
+	      const long long &, const unsigned long long &,
+              const enum SWIGTYPE & ($*1_ltype temp)
+      "push_int(*($1));";
+
+%typemap(out, pikedesc="tFloat") const float &, const double &  "push_float(*($1));";
+
+/************************ Constant Typemaps *****************************/
+
+%typemap(constant)
+    int, unsigned int,
+    short, unsigned short,
+    long, unsigned long,
+    signed char, unsigned char, 
+    bool, enum SWIGTYPE,
+    long long, unsigned long long
+    	"add_integer_constant(\"$symname\", $1, 0);";
+
+%typemap(constant) char
+	"add_integer_constant(\"$symname\", '$1', 0);";
+
+%typemap(constant) long long, unsigned long long
+	"add_integer_constant(\"$symname\", $1, 0);";
+
+%typemap(constant) float, double
+	"add_float_constant(\"$symname\", $1, 0);";
+
+%typemap(constant) char *
+	"add_string_constant(\"$symname\", \"$1\", 0);";
+
+/* ------------------------------------------------------------
+ * String & length
+ * ------------------------------------------------------------ */
+
+%typemap(in, pikedesc="tStr") (char *STRING, int LENGTH) {
+    if ($input.type != T_STRING)
+        Pike_error("Bad argument: Expected a string.\n");
+    $1 = ($1_ltype) STR0($input.u.string);
+    $2 = ($2_ltype) $input.u.string->length;
+}
+
+/* ------------------------------------------------------------
+ * ANSI C typemaps
+ * ------------------------------------------------------------ */
+
+%typemap(in, pikedesc="tInt") size_t {
+    if ($input.type != T_INT)
+        Pike_error("Bad argument: Expected an integer.\n");
+    $1 = ($1_ltype) $input.u.integer;
+}
+
+%typemap(out)      size_t = long;
+
+/* ------------------------------------------------------------
+ * Typechecking rules
+ * ------------------------------------------------------------ */
+
+%typecheck(SWIG_TYPECHECK_INTEGER)
+	 int, short, long,
+ 	 unsigned int, unsigned short, unsigned long,
+	 signed char, unsigned char,
+	 long long, unsigned long long,
+	 const int &, const short &, const long &,
+ 	 const unsigned int &, const unsigned short &, const unsigned long &,
+	 const long long &, const unsigned long long &,
+	 enum SWIGTYPE, enum SWIGTYPE &,
+         bool, const bool & 
+{
+  $1 = ($input.type == T_INT) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_DOUBLE)
+	float, double,
+	const float &, const double &
+{
+  $1 = (($input.type == T_FLOAT) || ($input.type == T_INT)) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_CHAR) char {
+  $1 = ($input.type == T_INT) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_STRING) char * {
+  $1 = ($input.type == T_STRING) ? 1 : 0;
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
+  void *ptr;
+  if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, $1_descriptor, 0) == -1) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
+  void *ptr;
+  if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, $&1_descriptor, 0) == -1) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
+  void *ptr;
+  if (SWIG_ConvertPtr($input.u.object, (void **) &ptr, 0, 0) == -1) {
+    $1 = 0;
+  } else {
+    $1 = 1;
+  }
+}
+
+/* ------------------------------------------------------------
+ * Overloaded operator support
+ * ------------------------------------------------------------ */
+
+#ifdef __cplusplus
+%rename("`+")      *::operator+;
+%rename("`-")      *::operator-;
+%rename("`*")      *::operator*;
+%rename("`/")      *::operator/;
+%rename("`%")      *::operator%;
+%rename("`<<")     *::operator<<;
+%rename("`>>")     *::operator>>;
+%rename("`&")      *::operator&;
+%rename("`|")      *::operator|;
+%rename("`^")      *::operator^;
+%rename("`~")      *::operator~;
+%rename("`<")      *::operator<;
+%rename("`>")      *::operator>;
+%rename("`==")     *::operator==;
+
+/* Special cases */
+%rename("`()")     *::operator();
+
+#endif
+
+/* ------------------------------------------------------------
+ * The start of the Pike initialization function
+ * ------------------------------------------------------------ */
+
+%init "swiginit.swg"
+
+%init %{
+#ifdef __cplusplus
+extern "C"
+#endif
+PIKE_MODULE_EXIT {}
+
+#ifdef __cplusplus
+extern "C"
+#endif
+PIKE_MODULE_INIT
+{
+    struct program *pr;
+    SWIG_InitializeModule(0);
+%}
+
+/* pike keywords */
+%include <pikekw.swg>
diff --git a/trunk/Lib/pike/pikekw.swg b/trunk/Lib/pike/pikekw.swg
new file mode 100644
index 0000000..844b1f1
--- /dev/null
+++ b/trunk/Lib/pike/pikekw.swg
@@ -0,0 +1,55 @@
+#ifndef PIKE_PIKEKW_SWG_
+#define PIKE_PIKEKW_SWG_
+
+/* Warnings for Pike keywords */
+#define PIKEKW(x) %namewarn("314: '" #x "' is a pike keyword")  #x
+
+/*
+   from
+   http://www.http://docs.linux.cz/pike/tutorial_C.html
+
+*/
+
+
+PIKEKW(array);
+PIKEKW(break);
+PIKEKW(case);
+PIKEKW(catch);
+PIKEKW(continue);
+PIKEKW(default);
+PIKEKW(do);
+PIKEKW(else);
+PIKEKW(float);
+PIKEKW(for);
+PIKEKW(foreach);
+PIKEKW(function);
+PIKEKW(gauge);
+PIKEKW(if);
+PIKEKW(inherit);
+PIKEKW(inline);
+PIKEKW(int);
+PIKEKW(lambda);
+PIKEKW(mapping);
+PIKEKW(mixed);
+PIKEKW(multiset);
+PIKEKW(nomask);
+PIKEKW(object);
+PIKEKW(predef);
+PIKEKW(private);
+PIKEKW(program);
+PIKEKW(protected);
+PIKEKW(public);
+PIKEKW(return);
+PIKEKW(sscanf);
+PIKEKW(static);
+PIKEKW(string);
+PIKEKW(switch);
+PIKEKW(typeof);
+PIKEKW(varargs);
+PIKEKW(void);
+PIKEKW(while);
+
+
+#undef PIKEKW
+
+#endif //PIKE_PIKEKW_SWG_
diff --git a/trunk/Lib/pike/pikerun.swg b/trunk/Lib/pike/pikerun.swg
new file mode 100644
index 0000000..875fcf4
--- /dev/null
+++ b/trunk/Lib/pike/pikerun.swg
@@ -0,0 +1,73 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pikerun.swg
+ *
+ * This file contains the runtime support for Pike modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include "object.h"
+#include "program.h"
+#ifdef __cplusplus
+}
+#endif
+
+/* Stores information about a wrapped object */
+typedef struct swig_object_wrapper {
+    void *self;
+    swig_type_info *type;
+} swig_object_wrapper;
+
+#ifdef THIS
+#undef THIS
+#endif
+#define THIS (((swig_object_wrapper *) Pike_fp->current_storage)->self)
+
+#define SWIG_ConvertPtr SWIG_Pike_ConvertPtr
+#define SWIG_NewPointerObj SWIG_Pike_NewPointerObj
+#define SWIG_GetModule(clientdata) SWIG_Pike_GetModule()
+#define SWIG_SetModule(clientdata, pointer) SWIG_Pike_SetModule(pointer)
+
+/* These need to be filled in before type sharing between modules will work */
+static swig_module_info *SWIG_Pike_GetModule() {
+  return 0;
+}
+
+static void SWIG_Pike_SetModule(swig_module_info *pointer) {
+
+}
+
+/* Convert a pointer value */
+static int
+SWIG_Pike_ConvertPtr(struct object *obj, void **ptr, swig_type_info *ty, int flags) {
+    struct program *pr;
+    swig_cast_info *tc;
+    swig_object_wrapper *obj_wrapper;
+    
+    if (ty) {
+        pr = (struct program *) ty->clientdata;
+        obj_wrapper = (swig_object_wrapper *) get_storage(obj, pr);
+        if (obj_wrapper && obj_wrapper->type) {
+            tc = SWIG_TypeCheckStruct(obj_wrapper->type, ty);
+            if (tc) {
+                int newmemory = 0;
+                *ptr = SWIG_TypeCast(tc, obj_wrapper->self, &newmemory);
+                assert(!newmemory); /* newmemory handling not yet implemented */
+                return 0;
+            }
+        }
+    }
+    return -1;
+}
+
+/* Create a new pointer object */
+static struct object *
+SWIG_Pike_NewPointerObj(void *ptr, swig_type_info *type, int own) {
+    return 0;
+}
diff --git a/trunk/Lib/pike/std_string.i b/trunk/Lib/pike/std_string.i
new file mode 100644
index 0000000..ca1fad8
--- /dev/null
+++ b/trunk/Lib/pike/std_string.i
@@ -0,0 +1,63 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_string.i
+ *
+ * SWIG typemaps for std::string
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <string>
+%}
+
+namespace std {
+
+    %naturalvar string;
+
+    class string;
+
+    /* Overloading check */
+
+    %typemap(typecheck) string = char *;
+    %typemap(typecheck) const string & = char *;
+
+    %typemap(in, pikedesc="tStr") string {
+      if ($input.type != T_STRING)
+        Pike_error("Bad argument: Expected a string.\n");
+      $1.assign(STR0($input.u.string));
+    }
+
+    %typemap(in, pikedesc="tStr") const string & (std::string temp) {
+      if ($input.type != T_STRING)
+        Pike_error("Bad argument: Expected a string.\n");
+      temp.assign(STR0($input.u.string));
+      $1 = &temp;
+    }
+
+    %typemap(out, pikedesc="tStr") string "push_text($1.c_str());";
+
+    %typemap(out, pikedesc="tStr") const string & "push_text($1->c_str());";
+    
+    %typemap(directorin) string, const string &, string & "$1_name.c_str()";
+
+    %typemap(directorin) string *, const string * "$1_name->c_str()";
+    
+    %typemap(directorout) string {
+      if ($input.type == T_STRING)
+        $result.assign(STR0($input.u.string));
+      else
+        throw Swig::DirectorTypeMismatchException("string expected");
+    }
+    
+    %typemap(directorout) const string & (std::string temp) {
+      if ($input.type == T_STRING) {
+        temp.assign(STR0($input.u.string));
+        $result = &temp;
+      } else {
+        throw Swig::DirectorTypeMismatchException("string expected");
+      }
+    }
+
+}
+
diff --git a/trunk/Lib/pointer.i b/trunk/Lib/pointer.i
new file mode 100644
index 0000000..16e11b7
--- /dev/null
+++ b/trunk/Lib/pointer.i
@@ -0,0 +1,14 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pointer.i
+ * ----------------------------------------------------------------------------- */
+
+
+%echo "pointer.i is deprecated.  Use cpointer.i instead."
+%echo "See http://www.swig.org/Doc1.3/Library.html"
+
+
+
+
diff --git a/trunk/Lib/python/Makefile.in b/trunk/Lib/python/Makefile.in
new file mode 100644
index 0000000..3243b3d
--- /dev/null
+++ b/trunk/Lib/python/Makefile.in
@@ -0,0 +1,135 @@
+# ---------------------------------------------------------------
+# SWIG Python Makefile
+# 
+# This file can be used to build various Python extensions with SWIG.
+# By default this file is set up for dynamic loading, but it can
+# be easily customized for static extensions by modifying various
+# portions of the file.
+#
+#        SRCS       = C source files
+#        CXXSRCS    = C++ source files
+#        OBJCSRCS   = Objective-C source files
+#        OBJS       = Additional .o files (compiled previously)
+#        INTERFACE  = SWIG interface file
+#        TARGET     = Name of target module or executable
+#
+# Many portions of this file were created by the SWIG configure
+# script and should already reflect your machine.
+#----------------------------------------------------------------
+
+SRCS          = 
+CXXSRCS       = 
+OBJCSRCS      = 
+OBJS          = 
+INTERFACE     = 
+WRAPFILE      = $(INTERFACE:.i=_wrap.c)
+WRAPOBJ       = $(INTERFACE:.i=_wrap.o)
+TARGET        = module@SO@ # Use this kind of target for dynamic loading
+#TARGET        = mypython  # Use this target for static linking
+
+prefix        = @prefix@
+exec_prefix   = @exec_prefix@
+
+CC            = @CC@
+CXX           = @CXX@
+OBJC          = @CC@ -Wno-import # -Wno-import needed for gcc 
+CFLAGS        = 
+INCLUDES      =
+LIBS          =
+
+# SWIG Options
+#     SWIG      = location of the SWIG executable
+#     SWIGOPT   = SWIG compiler options
+#     SWIGCC    = Compiler used to compile the wrapper file
+
+SWIG          = $(exec_prefix)/bin/swig 
+SWIGOPT       = -python 
+SWIGCC        = $(CC) 
+
+# SWIG Library files.  Uncomment if rebuilding the Python interpreter
+#SWIGLIB       = -lembed.i
+
+# Rules for creating .o files from source.
+
+COBJS         = $(SRCS:.c=.o)
+CXXOBJS       = $(CXXSRCS:.cxx=.o)
+OBJCOBJS      = $(OBJCSRCS:.m=.o)
+ALLOBJS       = $(COBJS) $(CXXOBJS) $(OBJCOBJS) $(OBJS)
+
+# Command that will be used to build the final extension.
+BUILD         = $(SWIGCC)
+
+# Uncomment the following if you are using dynamic loading
+CCSHARED      = @CCSHARED@
+BUILD         = @LDSHARED@
+
+# Uncomment the following if you are using dynamic loading with C++ and
+# need to provide additional link libraries (this is not always required).
+
+#DLL_LIBS      = -L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \
+             -L/usr/local/lib -lg++ -lstdc++ -lgcc
+
+# X11 installation (needed if rebuilding Python + tkinter)
+
+XLIB          = @XLIBSW@
+XINCLUDE      = @XINCLUDES@
+
+# Python installation
+
+PY_INCLUDE    = -DHAVE_CONFIG_H @PYINCLUDE@ 
+PY_LIB        = @PYLIB@
+
+# Tcl installation.  Needed if rebuilding Python with tkinter.
+
+TCL_INCLUDE   = @TCLINCLUDE@
+TCL_LIB       = @TCLLIB@
+
+# Build libraries (needed for static builds)
+
+LIBM          = @LIBM@
+LIBC          = @LIBC@
+SYSLIBS       = $(LIBM) $(LIBC) @LIBS@
+
+# Build options (uncomment only one these)
+
+#TKINTER      = $(TCL_LIB) -ltk -ltcl $(XLIB)
+BUILD_LIBS    = $(LIBS) # Dynamic loading
+#BUILD_LIBS    = $(PY_LIB) @PYLINK@ $(TKINTER) $(LIBS) $(SYSLIBS)
+
+# Compilation rules for non-SWIG components
+
+.SUFFIXES: .c .cxx .m
+
+.c.o:
+	$(CC) $(CCSHARED) $(CFLAGS) $(INCLUDES) -c $<
+
+.cxx.o:
+	$(CXX) $(CCSHARED) $(CXXFLAGS) $(INCLUDES) -c $<
+
+.m.o:
+	$(OBJC) $(CCSHARED) $(CFLAGS) $(INCLUDES) -c $<
+
+
+# ----------------------------------------------------------------------
+# Rules for building the extension
+# ----------------------------------------------------------------------
+
+all: $(TARGET)
+
+# Convert the wrapper file into an object file
+
+$(WRAPOBJ) : $(WRAPFILE)
+	$(SWIGCC) -c $(CCSHARED) $(CFLAGS) $(WRAPFILE) $(INCLUDES) $(PY_INCLUDE) 
+
+$(WRAPFILE) : $(INTERFACE)
+	$(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIB) $(INTERFACE)
+
+$(TARGET): $(WRAPOBJ) $(ALLOBJS)
+	$(BUILD) $(WRAPOBJ) $(ALLOBJS) $(BUILD_LIBS) -o $(TARGET)
+
+clean:
+	rm -f $(COBJS) $(CXXOBJS) $(OBJCOBJS) $(WRAPOBJ) $(WRAPFILE) $(TARGET)
+
+
+
+
diff --git a/trunk/Lib/python/README b/trunk/Lib/python/README
new file mode 100644
index 0000000..98ec560
--- /dev/null
+++ b/trunk/Lib/python/README
@@ -0,0 +1,105 @@
+/* -----------------------------------------------------------------------------
+ *
+ *  User interfaces: include these ones as needed
+ *
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ *  Special types and user helpers 
+ * ----------------------------------------------------------------------------- */
+
+argcargv.i		Handler for (int argc, char **argv)
+attribute.i		Convert a pair of set/get methods into a "native" python attribute
+ccomplex.i		C99 complex type
+complex.i		C99 or C++ complex type
+cstring.i		Various forms of C character string handling
+cwstring.i		Various forms of C wchar_t string handling
+embed.i			embedding the Python interpreter in something else
+embed15.i		embedding the Python interpreter in something else
+file.i			FILE C type
+implicit.i		Allow the use of implicit C++ constructors
+wchar.i			wchar_t C type
+
+/* -----------------------------------------------------------------------------
+ *  C++ STD + STL
+ * ----------------------------------------------------------------------------- */
+
+std_alloc.i		allocator 
+std_basic_string.i	basic string
+std_char_traits.i	char traits
+std_complex.i		complex
+std_deque.i		deque	
+std_except.i		exceptions
+std_ios.i		ios
+std_iostream.i		istream/ostream
+std_list.i		list
+std_map.i		map
+std_multimap.i		multimap
+std_multiset.i		multiset
+std_pair.i		pair
+std_set.i		set
+std_sstream.i		string stream
+std_streambuf.i		streambuf
+std_string.i		string
+std_vector.i		vector
+std_wios.i		wios
+std_wiostream.i		wistream/wostream
+std_wsstream.i		wstring stream
+std_wstreambuf.i	wstreambuf
+std_wstring.i		wstring
+
+
+
+/* -----------------------------------------------------------------------------
+/* 
+ *  Implementation files: don't look at them unless you are really drunk
+ *
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ *  Basic files
+ * ----------------------------------------------------------------------------- */
+
+python.swg		Main language file, it just includes what is needed.
+pyuserdir.swg		User visible directives (%pythonnondynamic, etc)
+pymacros.swg		Internal macros used for typemaps
+pyfragments.swg		Allow the user to overload the default fragments
+pyopers.swg		Python operations (+=, *=, etc)
+pythonkw.swg		Python keywords and special names
+pyinit.swg		Python Init method
+
+/* -----------------------------------------------------------------------------
+ *  The runtime part
+ * ----------------------------------------------------------------------------- */
+
+pyruntime.swg		Main runtime file definition
+pyapi.swg		SWIG/Python API declarations
+pyrun.swg		Python run-time code 
+
+/* -----------------------------------------------------------------------------
+ *  Internal typemap specializations
+ * ----------------------------------------------------------------------------- */
+
+pyswigtype.swg		SWIGTYPE
+pystrings.swg		Char strings (char *)
+pywstrings.swg		Wchar Strings (wchar_t *)
+pyprimtypes.swg		Primitive types (shot,int,double,etc)
+pycomplex.swg		PyComplex and helper for C/C++ complex types
+pydocs.swg		Typemaps documentation
+
+/* -----------------------------------------------------------------------------
+ *  C++ STD + STL
+ * ----------------------------------------------------------------------------- */
+
+pycontainer.swg		python container iterators
+std_common.i		general common code for the STD/STL implementation
+std_container.i		general common code for the STD/STL containers
+
+
+/*-----------------------------------------------------------------------------
+ *  Backward compatibility and deprecated
+ * ----------------------------------------------------------------------------- */
+
+std_vectora.i		vector + allocator (allocators are now supported in STD/STL)
+typemaps.i		old in/out typemaps (doesn't need to be included)
+defarg.swg		for processing default arguments with shadow classes
diff --git a/trunk/Lib/python/argcargv.i b/trunk/Lib/python/argcargv.i
new file mode 100644
index 0000000..d5d008a
--- /dev/null
+++ b/trunk/Lib/python/argcargv.i
@@ -0,0 +1,92 @@
+/* ------------------------------------------------------------
+ * --- Argc & Argv ---
+ * ------------------------------------------------------------ */
+
+%fragment("SWIG_AsArgcArgv","header",fragment="SWIG_AsCharPtrAndSize") {
+SWIGINTERN int
+SWIG_AsArgcArgv(PyObject *input,
+		swig_type_info *ppchar_info,
+		size_t *argc, char ***argv, int *owner)
+{  
+  void *vptr;
+  int res = SWIG_ConvertPtr(input, &vptr, ppchar_info, 0);
+  if (!SWIG_IsOK(res)) {
+    int list = 0;
+    PyErr_Clear();
+    list = PyList_Check(input);
+    if (list || PyTuple_Check(input)) {
+      size_t i = 0;
+      size_t size = list ? PyList_Size(input) : PyTuple_Size(input);
+      if (argc) *argc = size;
+      if (argv) {
+	*argv = %new_array(size + 1, char*);
+	for (; i < size; ++i) {
+	  PyObject *obj = list ? PyList_GetItem(input,i) : PyTuple_GetItem(input,i);
+	  char *cptr = 0; size_t sz = 0; int alloc = 0;
+	  res = SWIG_AsCharPtrAndSize(obj, &cptr, &sz, &alloc);
+	  if (SWIG_IsOK(res)) {
+	    if (cptr && sz) {
+	      (*argv)[i] = (alloc == SWIG_NEWOBJ) ? cptr : %new_copy_array(cptr, sz, char);
+	    } else {
+	      (*argv)[i] = 0;
+	    }
+	  } else {
+	    return SWIG_TypeError;
+	  }
+	}
+	(*argv)[i] = 0;
+	if (owner) *owner = 1;
+      } else {
+	for (; i < size; ++i) {
+	  PyObject *obj = list ? PyList_GetItem(input,i) : PyTuple_GetItem(input,i);
+	  res = SWIG_AsCharPtrAndSize(obj, 0, 0, 0);
+	  if (!SWIG_IsOK(res)) return SWIG_TypeError;
+	}
+	if (owner) *owner = 0;
+      }
+      return SWIG_OK;
+    } else {
+      return SWIG_TypeError;
+    }
+  } else {
+    /* seems dangerous, but the user asked for it... */
+    size_t i = 0;
+    if (argv) { while (*argv[i] != 0) ++i;}    
+    if (argc) *argc = i;
+    if (owner) *owner = 0;
+    return SWIG_OK;
+  }
+}
+}
+
+/*
+  This typemap works with either a char**, a python list or a python
+  tuple
+ */
+
+%typemap(in,noblock=0,fragment="SWIG_AsArgcArgv") (int ARGC, char **ARGV) (int res,char **argv = 0, size_t argc = 0, int owner= 0) {
+  res = SWIG_AsArgcArgv($input, $descriptor(char**), &argc, &argv, &owner);
+  if (!SWIG_IsOK(res)) { 
+    $1 = 0; $2 = 0;
+    %argument_fail(SWIG_TypeError, "int ARGC, char **ARGV", $symname, $argnum);
+  } else {  
+    $1 = %static_cast(argc,$1_ltype);
+    $2 = %static_cast(argv, $2_ltype);
+  }
+}
+
+%typemap(typecheck, precedence=SWIG_TYPECHECK_STRING_ARRAY) (int ARGC, char **ARGV) {
+  int res = SWIG_AsArgcArgv($input, $descriptor(char**), 0, 0, 0);
+  $1 = SWIG_IsOK(res);
+}
+
+%typemap(freearg,noblock=1) (int ARGC, char **ARGV)  {
+  if (owner$argnum) {
+    size_t i = argc$argnum;
+    while (i) {
+      %delete_array(argv$argnum[--i]);
+    }
+    %delete_array(argv$argnum);
+  }
+}
+
diff --git a/trunk/Lib/python/attribute.i b/trunk/Lib/python/attribute.i
new file mode 100644
index 0000000..779716c
--- /dev/null
+++ b/trunk/Lib/python/attribute.i
@@ -0,0 +1 @@
+%include <typemaps/attribute.swg>
diff --git a/trunk/Lib/python/boost_shared_ptr.i b/trunk/Lib/python/boost_shared_ptr.i
new file mode 100644
index 0000000..2e34290
--- /dev/null
+++ b/trunk/Lib/python/boost_shared_ptr.i
@@ -0,0 +1,307 @@
+%include <shared_ptr.i>
+
+%define SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, CONST, TYPE...)
+
+%naturalvar TYPE;
+%naturalvar SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+
+// destructor mods
+%feature("unref") TYPE 
+//"if (debug_shared) { cout << \"deleting use_count: \" << (*smartarg1).use_count() << \" [\" << (boost::get_deleter<SWIG_null_deleter>(*smartarg1) ? std::string(\"CANNOT BE DETERMINED SAFELY\") : ( (*smartarg1).get() ? (*smartarg1)->getValue() : std::string(\"NULL PTR\") )) << \"]\" << endl << flush; }\n"
+                               "(void)arg1; delete smartarg1;"
+
+%feature("smartptr", noblock=1) TYPE { SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > }
+
+// plain value
+%typemap(in) CONST TYPE (void *argp, int res = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) {
+    %argument_nullref("$type", $symname, $argnum);
+  } else {
+    $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get());
+    if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+  }
+}
+%typemap(out) CONST TYPE {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1));
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE {
+  void *argp = 0;
+  int newmem = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  if (!argp) {
+    %argument_nullref("$type", $symname, $argnum);
+  } else {
+    $1 = *(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get());
+    if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+  }
+}
+%typemap(varout) CONST TYPE {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(new $1_ltype(($1_ltype &)$1));
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// plain pointer
+// Note: $disown not implemented as it will lead to a memory leak of the shared_ptr instance
+%typemap(in) CONST TYPE * (void  *argp = 0, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast(tempshared.get(), $1_ltype);
+  } else {
+    smartarg = %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast((smartarg ? smartarg->get() : 0), $1_ltype);
+  }
+}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE * {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), $owner | SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE * {
+  void *argp = 0;
+  int newmem = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared;
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartarg = 0;
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast(tempshared.get(), $1_ltype);
+  } else {
+    smartarg = %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast((smartarg ? smartarg->get() : 0), $1_ltype);
+  }
+}
+%typemap(varout, fragment="SWIG_null_deleter") CONST TYPE * {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_0) : 0;
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// plain reference
+%typemap(in) CONST TYPE & (void  *argp = 0, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = %const_cast(tempshared.get(), $1_ltype);
+  } else {
+    $1 = %const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $1_ltype);
+  }
+}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE & {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1 SWIG_NO_NULL_DELETER_$owner);
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE & {
+  void *argp = 0;
+  int newmem = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared;
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    $1 = *%const_cast(tempshared.get(), $1_ltype);
+  } else {
+    $1 = *%const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $1_ltype);
+  }
+}
+%typemap(varout, fragment="SWIG_null_deleter") CONST TYPE & {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(&$1 SWIG_NO_NULL_DELETER_0);
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// plain pointer by reference
+// Note: $disown not implemented as it will lead to a memory leak of the shared_ptr instance
+%typemap(in) CONST TYPE *& (void  *argp = 0, int res = 0, $*1_ltype temp = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    tempshared = *%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    delete %reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *);
+    temp = %const_cast(tempshared.get(), $*1_ltype);
+  } else {
+    temp = %const_cast(%reinterpret_cast(argp, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *)->get(), $*1_ltype);
+  }
+  $1 = &temp;
+}
+%typemap(out, fragment="SWIG_null_deleter") CONST TYPE *& {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1 SWIG_NO_NULL_DELETER_$owner);
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) CONST TYPE *& %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) CONST TYPE *& %{
+#error "varout typemap not implemented"
+%}
+
+// shared_ptr by value
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > (void *argp, int res = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (argp) $1 = *(%reinterpret_cast(argp, $&ltype));
+  if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $&ltype);
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+  int newmem = 0;
+  void *argp = 0;
+  int res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  $1 = argp ? *(%reinterpret_cast(argp, $&ltype)) : SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE >();
+  if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $&ltype);
+}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >($1) : 0;
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+// shared_ptr by reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & (void *argp, int res = 0, $*1_ltype tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    if (argp) tempshared = *%reinterpret_cast(argp, $ltype);
+    delete %reinterpret_cast(argp, $ltype);
+    $1 = &tempshared;
+  } else {
+    $1 = (argp) ? %reinterpret_cast(argp, $ltype) : &tempshared;
+  }
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = *$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > & %{
+#error "varout typemap not implemented"
+%}
+
+// shared_ptr by pointer
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * (void *argp, int res = 0, $*1_ltype tempshared) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (newmem & SWIG_CAST_NEW_MEMORY) {
+    if (argp) tempshared = *%reinterpret_cast(argp, $ltype);
+    delete %reinterpret_cast(argp, $ltype);
+    $1 = &tempshared;
+  } else {
+    $1 = (argp) ? %reinterpret_cast(argp, $ltype) : &tempshared;
+  }
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = $1 && *$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(*$1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+  if ($owner) delete $1;
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > * %{
+#error "varout typemap not implemented"
+%}
+
+// shared_ptr by pointer reference
+%typemap(in) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& (void *argp, int res = 0, SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > tempshared, $*1_ltype temp = 0) {
+  int newmem = 0;
+  res = SWIG_ConvertPtrAndOwn($input, &argp, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), %convertptr_flags, &newmem);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (argp) tempshared = *%reinterpret_cast(argp, $*ltype);
+  if (newmem & SWIG_CAST_NEW_MEMORY) delete %reinterpret_cast(argp, $*ltype);
+  temp = &tempshared;
+  $1 = &temp;
+}
+%typemap(out) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& {
+  SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *smartresult = *$1 && **$1 ? new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >(**$1) : 0;
+  %set_output(SWIG_NewPointerObj(%as_voidptr(smartresult), $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), SWIG_POINTER_OWN));
+}
+
+%typemap(varin) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& %{
+#error "varin typemap not implemented"
+%}
+%typemap(varout) SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& %{
+#error "varout typemap not implemented"
+%}
+
+// Typecheck typemaps
+// Note: SWIG_ConvertPtr with void ** parameter set to 0 instead of using SWIG_ConvertPtrAndOwn, so that the casting 
+// function is not called thereby avoiding a possible smart pointer copy constructor call when casting up the inheritance chain.
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) 
+                      CONST TYPE,
+                      CONST TYPE &,
+                      CONST TYPE *,
+                      CONST TYPE *&,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > &,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *,
+                      SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE > *& {
+  int res = SWIG_ConvertPtr($input, 0, $descriptor(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *), 0);
+  $1 = SWIG_CheckState(res);
+}
+
+
+// various missing typemaps - If ever used (unlikely) ensure compilation error rather than runtime bug
+%typemap(in) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+%typemap(out) CONST TYPE[], CONST TYPE[ANY], CONST TYPE (CLASS::*) %{
+#error "typemaps for $1_type not available"
+%}
+
+
+%template() SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< CONST TYPE >;
+%enddef
+
diff --git a/trunk/Lib/python/carrays.i b/trunk/Lib/python/carrays.i
new file mode 100644
index 0000000..8d6d440
--- /dev/null
+++ b/trunk/Lib/python/carrays.i
@@ -0,0 +1,9 @@
+%define %array_class(TYPE,NAME)
+  %array_class_wrap(TYPE,NAME,__getitem__,__setitem__)
+%enddef
+
+%include <typemaps/carrays.swg>
+
+
+
+
diff --git a/trunk/Lib/python/ccomplex.i b/trunk/Lib/python/ccomplex.i
new file mode 100644
index 0000000..30f797d
--- /dev/null
+++ b/trunk/Lib/python/ccomplex.i
@@ -0,0 +1,29 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ccomplex.i
+ *
+ * C complex typemaps
+ * ISO C99:  7.3 Complex arithmetic <complex.h>
+ * ----------------------------------------------------------------------------- */
+
+
+%include <pycomplex.swg>
+
+%{
+#include <complex.h>
+%}
+
+
+/* C complex constructor */
+#define CCplxConst(r, i) ((r) + I*(i))
+
+%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag);
+%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag);
+%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag);
+
+/* declaring the typemaps */
+%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex);
+%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex);
+%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex);
diff --git a/trunk/Lib/python/cdata.i b/trunk/Lib/python/cdata.i
new file mode 100644
index 0000000..3679659
--- /dev/null
+++ b/trunk/Lib/python/cdata.i
@@ -0,0 +1 @@
+%include <typemaps/cdata.swg>
diff --git a/trunk/Lib/python/cmalloc.i b/trunk/Lib/python/cmalloc.i
new file mode 100644
index 0000000..248f06b
--- /dev/null
+++ b/trunk/Lib/python/cmalloc.i
@@ -0,0 +1 @@
+%include <typemaps/cmalloc.swg>
diff --git a/trunk/Lib/python/cni.i b/trunk/Lib/python/cni.i
new file mode 100644
index 0000000..10a1403
--- /dev/null
+++ b/trunk/Lib/python/cni.i
@@ -0,0 +1,2 @@
+%include <gcj/cni.i>
+%include <jstring.i>
diff --git a/trunk/Lib/python/complex.i b/trunk/Lib/python/complex.i
new file mode 100644
index 0000000..4c3b3c5
--- /dev/null
+++ b/trunk/Lib/python/complex.i
@@ -0,0 +1,6 @@
+#ifdef __cplusplus
+%include <std_complex.i>
+#else
+%include <ccomplex.i>
+#endif
+
diff --git a/trunk/Lib/python/cpointer.i b/trunk/Lib/python/cpointer.i
new file mode 100644
index 0000000..d824792
--- /dev/null
+++ b/trunk/Lib/python/cpointer.i
@@ -0,0 +1 @@
+%include <typemaps/cpointer.swg>
diff --git a/trunk/Lib/python/cstring.i b/trunk/Lib/python/cstring.i
new file mode 100644
index 0000000..ede9c59
--- /dev/null
+++ b/trunk/Lib/python/cstring.i
@@ -0,0 +1 @@
+%include <typemaps/cstring.swg>
diff --git a/trunk/Lib/python/cwstring.i b/trunk/Lib/python/cwstring.i
new file mode 100644
index 0000000..2824d9c
--- /dev/null
+++ b/trunk/Lib/python/cwstring.i
@@ -0,0 +1,3 @@
+%include <pywstrings.swg>
+%include <typemaps/cwstring.swg>
+
diff --git a/trunk/Lib/python/defarg.swg b/trunk/Lib/python/defarg.swg
new file mode 100644
index 0000000..10c9916
--- /dev/null
+++ b/trunk/Lib/python/defarg.swg
@@ -0,0 +1,37 @@
+/* This file defines an internal function for processing default arguments
+   with proxy classes.
+
+   There seems to be no straightforward way to write proxy functions
+   involving default arguments. For example :
+
+             def foo(arg1,arg2,*args):
+                     proxyc.foo(arg1,arg2,args)
+
+   This fails because args is now a tuple and SWIG doesn't know what to
+   do with it.
+
+   This file allows a different approach :
+
+            def foo(arg1,arg2,*args):
+                    proxyc.__call_defarg(proxyc.foo,(arg1,arg2,)+args)
+
+   Basically, we form a new tuple from the object, call this special
+   __call_defarg method and it passes control to the real wrapper function.
+   An ugly hack, but it works.
+*/
+
+SWIGINTERN PyObject *swig_call_defargs(PyObject *self, PyObject *args) {
+  PyObject *func;
+  PyObject *parms;
+  
+  if (!PyArg_ParseTuple(args,"OO",&func,&parms))
+    return NULL;
+  
+  if (!PyCallable_Check(func)) {
+    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+    PyErr_SetString(PyExc_TypeError, "__call_defarg : Need a callable object!");
+    SWIG_PYTHON_THREAD_END_BLOCK;
+    return NULL;
+  }
+  return PyEval_CallObject(func,parms);
+}
diff --git a/trunk/Lib/python/director.swg b/trunk/Lib/python/director.swg
new file mode 100644
index 0000000..176ee33
--- /dev/null
+++ b/trunk/Lib/python/director.swg
@@ -0,0 +1,482 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * director.swg
+ *
+ * This file contains support for director classes that proxy
+ * method calls from C++ to Python extensions.
+ * ----------------------------------------------------------------------------- */
+
+#ifndef SWIG_DIRECTOR_PYTHON_HEADER_
+#define SWIG_DIRECTOR_PYTHON_HEADER_
+
+#ifdef __cplusplus
+
+#include <string>
+#include <iostream>
+#include <exception>
+#include <vector>
+#include <map>
+
+
+/*
+  Use -DSWIG_PYTHON_DIRECTOR_NO_VTABLE if you don't want to generate a 'virtual
+  table', and avoid multiple GetAttr calls to retrieve the python
+  methods.
+*/
+
+#ifndef SWIG_PYTHON_DIRECTOR_NO_VTABLE
+#ifndef SWIG_PYTHON_DIRECTOR_VTABLE
+#define SWIG_PYTHON_DIRECTOR_VTABLE
+#endif
+#endif
+
+
+
+/*
+  Use -DSWIG_DIRECTOR_NO_UEH if you prefer to avoid the use of the
+  Undefined Exception Handler provided by swift
+*/
+#ifndef SWIG_DIRECTOR_NO_UEH
+#ifndef SWIG_DIRECTOR_UEH
+#define SWIG_DIRECTOR_UEH
+#endif
+#endif
+
+
+/*
+  Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the
+  'Swig' namespace. This could be usefull for multi-modules projects.
+*/
+#ifdef SWIG_DIRECTOR_STATIC
+/* Force anonymous (static) namespace */
+#define Swig
+#endif
+
+
+/*
+  Use -DSWIG_DIRECTOR_NORTTI if you prefer to avoid the use of the
+  native C++ RTTI and dynamic_cast<>. But be aware that directors
+  could stop working when using this option.
+*/
+#ifdef SWIG_DIRECTOR_NORTTI
+/* 
+   When we don't use the native C++ RTTI, we implement a minimal one
+   only for Directors.
+*/
+# ifndef SWIG_DIRECTOR_RTDIR
+# define SWIG_DIRECTOR_RTDIR
+#include <map>
+
+namespace Swig {
+  class Director;
+  SWIGINTERN std::map<void*,Director*>& get_rtdir_map() {
+    static std::map<void*,Director*> rtdir_map;
+    return rtdir_map;
+  }
+
+  SWIGINTERNINLINE void set_rtdir(void *vptr, Director *rtdir) {
+    get_rtdir_map()[vptr] = rtdir;
+  }
+
+  SWIGINTERNINLINE Director *get_rtdir(void *vptr) {
+    std::map<void*,Director*>::const_iterator pos = get_rtdir_map().find(vptr);
+    Director *rtdir = (pos != get_rtdir_map().end()) ? pos->second : 0;
+    return rtdir;
+  }
+}
+# endif /* SWIG_DIRECTOR_RTDIR */
+
+# define SWIG_DIRECTOR_CAST(Arg) Swig::get_rtdir(static_cast<void*>(Arg))
+# define SWIG_DIRECTOR_RGTR(Arg1, Arg2) Swig::set_rtdir(static_cast<void*>(Arg1), Arg2)
+
+#else
+
+# define SWIG_DIRECTOR_CAST(Arg) dynamic_cast<Swig::Director*>(Arg)
+# define SWIG_DIRECTOR_RGTR(Arg1, Arg2)
+
+#endif /* SWIG_DIRECTOR_NORTTI */
+
+extern "C" {
+  struct swig_type_info;
+}
+
+namespace Swig {  
+
+  /* memory handler */
+  struct GCItem 
+  {
+    virtual ~GCItem() = 0;
+
+    virtual int get_own() const
+    {
+      return 0;
+    }
+  };
+
+  GCItem::~GCItem()
+  {
+  }
+
+  struct GCItem_var
+  {
+    GCItem_var(GCItem *item = 0) : _item(item)
+    {
+    }
+
+    GCItem_var& operator=(GCItem *item)
+    {
+      GCItem *tmp = _item;
+      _item = item;
+      delete tmp;
+      return *this;
+    }
+
+    ~GCItem_var() 
+    {
+      delete _item;
+    }
+    
+    GCItem * operator->() const
+    {
+      return _item;
+    }
+    
+  private:
+    GCItem *_item;
+  };
+  
+  struct GCItem_Object : GCItem
+  {
+    GCItem_Object(int own) : _own(own)
+    {
+    }
+    
+    virtual ~GCItem_Object() 
+    {
+    }
+
+    int get_own() const
+    {
+      return _own;
+    }
+    
+  private:
+    int _own;
+  };
+
+  template <typename Type>
+  struct GCItem_T : GCItem
+  {
+    GCItem_T(Type *ptr) : _ptr(ptr)
+    {
+    }
+    
+    virtual ~GCItem_T() 
+    {
+      delete _ptr;
+    }
+    
+  private:
+    Type *_ptr;
+  };
+
+  template <typename Type>
+  struct GCArray_T : GCItem
+  {
+    GCArray_T(Type *ptr) : _ptr(ptr)
+    {
+    }
+    
+    virtual ~GCArray_T() 
+    {
+      delete[] _ptr;
+    }
+    
+  private:
+    Type *_ptr;
+  };
+
+  /* base class for director exceptions */
+  class DirectorException {
+  protected:
+    std::string swig_msg;
+  public:
+    DirectorException(PyObject *error, const char* hdr ="", const char* msg ="") 
+      : swig_msg(hdr)
+    {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK; 
+      if (strlen(msg)) {
+        swig_msg += " ";
+        swig_msg += msg;
+      }
+      if (!PyErr_Occurred()) {
+        swig_msg.insert(0, ": ");
+        PyErr_SetString(error, getMessage());
+      } else {
+        SWIG_Python_AddErrorMsg(getMessage());
+      }
+      SWIG_PYTHON_THREAD_END_BLOCK; 
+    }
+
+    const char *getMessage() const
+    { 
+      return swig_msg.c_str(); 
+    }
+
+    static void raise(PyObject *error, const char *msg) 
+    {
+      throw DirectorException(error, msg);
+    }
+
+    static void raise(const char *msg) 
+    {
+      raise(PyExc_RuntimeError, msg);
+    }
+  };
+
+  /* unknown exception handler  */
+  class UnknownExceptionHandler 
+  {
+#ifdef SWIG_DIRECTOR_UEH
+    static void handler()  {
+      try {
+        throw;
+      } catch (DirectorException& e) {
+        std::cerr << "Swig Director exception caught:" << std::endl
+                  << e.getMessage() << std::endl;
+      } catch (std::exception& e) {
+        std::cerr << "std::exception caught: "<< e.what() << std::endl;
+      } catch (...) {
+        std::cerr << "Unknown exception caught." << std::endl;
+      }
+      
+      std::cerr << std::endl
+                << "Python interpreter traceback:" << std::endl;
+      PyErr_Print();
+      std::cerr << std::endl;
+      
+      std::cerr << "This exception was caught by the SWIG unexpected exception handler." << std::endl
+                << "Try using %feature(\"director:except\") to avoid reaching this point." << std::endl
+                << std::endl
+                << "Exception is being re-thrown, program will like abort/terminate." << std::endl;
+      throw;
+    }
+
+  public:
+    
+    std::unexpected_handler old;
+    UnknownExceptionHandler(std::unexpected_handler nh = handler)
+    {
+      old = std::set_unexpected(nh);
+    }
+
+    ~UnknownExceptionHandler()
+    {
+      std::set_unexpected(old);
+    }
+#endif
+  };
+
+  /* type mismatch in the return value from a python method call */
+  class DirectorTypeMismatchException : public Swig::DirectorException {
+  public:
+    DirectorTypeMismatchException(PyObject *error, const char* msg="") 
+      : Swig::DirectorException(error, "Swig director type mismatch", msg)
+    {
+    }
+
+    DirectorTypeMismatchException(const char* msg="") 
+      : Swig::DirectorException(PyExc_TypeError, "Swig director type mismatch", msg)
+    {
+    }
+
+    static void raise(PyObject *error, const char *msg)
+    {
+      throw DirectorTypeMismatchException(error, msg);
+    }
+
+    static void raise(const char *msg)
+    {
+      throw DirectorTypeMismatchException(msg);
+    }
+  };
+
+  /* any python exception that occurs during a director method call */
+  class DirectorMethodException : public Swig::DirectorException {
+  public:
+    DirectorMethodException(const char* msg = "") 
+      : DirectorException(PyExc_RuntimeError, "Swig director method error.", msg)
+    {
+    }    
+
+    static void raise(const char *msg)
+    {
+      throw DirectorMethodException(msg);
+    }
+  };
+
+  /* attempt to call a pure virtual method via a director method */
+  class DirectorPureVirtualException : public Swig::DirectorException
+  {
+  public:
+    DirectorPureVirtualException(const char* msg = "") 
+      : DirectorException(PyExc_RuntimeError, "Swig director pure virtual method called", msg)
+    { 
+    }
+
+    static void raise(const char *msg) 
+    {
+      throw DirectorPureVirtualException(msg);
+    }
+  };
+
+
+#if defined(SWIG_PYTHON_THREADS)
+/*  __THREAD__ is the old macro to activate some thread support */
+# if !defined(__THREAD__)
+#   define __THREAD__ 1
+# endif
+#endif
+
+#ifdef __THREAD__
+# include "pythread.h"
+  class Guard
+  {
+    PyThread_type_lock & mutex_;
+    
+  public:
+    Guard(PyThread_type_lock & mutex) : mutex_(mutex)
+    {
+      PyThread_acquire_lock(mutex_, WAIT_LOCK);
+    }
+    
+    ~Guard()
+    {
+      PyThread_release_lock(mutex_);
+    }
+  };
+# define SWIG_GUARD(mutex) Guard _guard(mutex)
+#else
+# define SWIG_GUARD(mutex) 
+#endif
+
+  /* director base class */
+  class Director {
+  private:
+    /* pointer to the wrapped python object */
+    PyObject* swig_self;
+    /* flag indicating whether the object is owned by python or c++ */
+    mutable bool swig_disown_flag;
+
+    /* decrement the reference count of the wrapped python object */
+    void swig_decref() const { 
+      if (swig_disown_flag) {
+        SWIG_PYTHON_THREAD_BEGIN_BLOCK; 
+        Py_DECREF(swig_self); 
+        SWIG_PYTHON_THREAD_END_BLOCK; 
+      }
+    }
+
+  public:
+    /* wrap a python object, optionally taking ownership */
+    Director(PyObject* self) : swig_self(self), swig_disown_flag(false) {
+      swig_incref();
+    }
+
+
+    /* discard our reference at destruction */
+    virtual ~Director() {
+      swig_decref(); 
+    }
+
+
+    /* return a pointer to the wrapped python object */
+    PyObject *swig_get_self() const { 
+      return swig_self; 
+    }
+
+    /* acquire ownership of the wrapped python object (the sense of "disown"
+     * is from python) */
+    void swig_disown() const { 
+      if (!swig_disown_flag) { 
+        swig_disown_flag=true;
+        swig_incref(); 
+      } 
+    }
+
+    /* increase the reference count of the wrapped python object */
+    void swig_incref() const { 
+      if (swig_disown_flag) {
+        Py_INCREF(swig_self); 
+      }
+    }
+
+    /* methods to implement pseudo protected director members */
+    virtual bool swig_get_inner(const char* /* name */) const {
+      return true;
+    }
+    
+    virtual void swig_set_inner(const char* /* name */, bool /* val */) const {
+    }
+
+  /* ownership management */
+  private:
+    typedef std::map<void*, GCItem_var> ownership_map;
+    mutable ownership_map owner;
+#ifdef __THREAD__
+    static PyThread_type_lock swig_mutex_own;
+#endif
+
+  public:
+    template <typename Type>
+    void swig_acquire_ownership_array(Type *vptr)  const
+    {
+      if (vptr) {
+        SWIG_GUARD(swig_mutex_own);
+        owner[vptr] = new GCArray_T<Type>(vptr);
+      }
+    }
+    
+    template <typename Type>
+    void swig_acquire_ownership(Type *vptr)  const
+    {
+      if (vptr) {
+        SWIG_GUARD(swig_mutex_own);
+        owner[vptr] = new GCItem_T<Type>(vptr);
+      }
+    }
+
+    void swig_acquire_ownership_obj(void *vptr, int own) const
+    {
+      if (vptr && own) {
+        SWIG_GUARD(swig_mutex_own);
+        owner[vptr] = new GCItem_Object(own);
+      }
+    }
+    
+    int swig_release_ownership(void *vptr) const
+    {
+      int own = 0;
+      if (vptr) {
+        SWIG_GUARD(swig_mutex_own);
+        ownership_map::iterator iter = owner.find(vptr);
+        if (iter != owner.end()) {
+          own = iter->second->get_own();
+          owner.erase(iter);
+        }
+      }
+      return own;
+    }
+  };
+
+#ifdef __THREAD__
+  PyThread_type_lock Director::swig_mutex_own = PyThread_allocate_lock();
+#endif
+}
+
+#endif /* __cplusplus */
+
+
+#endif
diff --git a/trunk/Lib/python/embed.i b/trunk/Lib/python/embed.i
new file mode 100644
index 0000000..4855e3d
--- /dev/null
+++ b/trunk/Lib/python/embed.i
@@ -0,0 +1,115 @@
+//
+// embed15.i
+// SWIG file embedding the Python interpreter in something else.
+// This file is based on Python-1.5.  It will not work with
+// earlier versions.
+//
+// This file makes it possible to extend Python and all of its
+// built-in functions without having to hack it's setup script.
+//
+
+
+#ifdef AUTODOC
+%subsection "embed.i"
+%text %{
+This module provides support for building a new version of the
+Python executable.  This will be necessary on systems that do
+not support shared libraries and may be necessary with C++
+extensions.  This file contains everything you need to build
+a new version of Python from include files and libraries normally
+installed with the Python language.
+
+This module will automatically grab all of the Python modules
+present in your current Python executable (including any special
+purpose modules you have enabled such as Tkinter).   Thus, you
+may need to provide additional link libraries when compiling.
+
+This library file only works with Python 1.5.  A version 
+compatible with Python 1.4 is available as embed14.i and
+a Python1.3 version is available as embed13.i.    As far as
+I know, this module is C++ safe.
+%}
+#else
+%echo "embed.i : Using Python 1.5"
+#endif
+
+%wrapper %{
+
+#include <Python.h>
+
+#ifdef __cplusplus
+extern "C"
+#endif
+void SWIG_init();  /* Forward reference */
+
+#define _PyImport_Inittab swig_inittab
+
+/* Grab Python's inittab[] structure */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include <config.c>
+
+#undef _PyImport_Inittab 
+
+/* Now define our own version of it.
+   Hopefully someone does not have more than 1000 built-in modules */
+
+struct _inittab SWIG_Import_Inittab[1000];       
+
+static int  swig_num_modules = 0;
+
+/* Function for adding modules to Python */
+
+static void swig_add_module(char *name, void (*initfunc)()) {
+	SWIG_Import_Inittab[swig_num_modules].name = name;
+	SWIG_Import_Inittab[swig_num_modules].initfunc = initfunc;
+	swig_num_modules++;
+	SWIG_Import_Inittab[swig_num_modules].name = (char *) 0;
+	SWIG_Import_Inittab[swig_num_modules].initfunc = 0;
+}				
+
+/* Function to add all of Python's build in modules to our interpreter */
+
+static void swig_add_builtin() {
+	int i = 0;
+	while (swig_inittab[i].name) {
+		swig_add_module(swig_inittab[i].name, swig_inittab[i].initfunc);
+  	        i++;
+ 	}
+#ifdef SWIGMODINIT
+	SWIGMODINIT	
+#endif
+	/* Add SWIG builtin function */
+	swig_add_module(SWIG_name, SWIG_init);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int Py_Main(int, char **);
+
+#ifdef __cplusplus
+}
+#endif
+
+extern struct _inittab *PyImport_Inittab;
+
+int
+main(int argc, char **argv) {
+	swig_add_builtin();
+	PyImport_Inittab = SWIG_Import_Inittab;
+	return Py_Main(argc,argv);
+}
+
+%}
+
+
+  
+
diff --git a/trunk/Lib/python/embed15.i b/trunk/Lib/python/embed15.i
new file mode 100644
index 0000000..f677d16
--- /dev/null
+++ b/trunk/Lib/python/embed15.i
@@ -0,0 +1,118 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * embed15.i
+ *
+ * SWIG file embedding the Python interpreter in something else.
+ * This file is based on Python-1.5.  It will not work with
+ * earlier versions.
+ *
+ * This file makes it possible to extend Python and all of its
+ * built-in functions without having to hack it's setup script.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef AUTODOC
+%subsection "embed.i"
+%text %{
+This module provides support for building a new version of the
+Python executable.  This will be necessary on systems that do
+not support shared libraries and may be necessary with C++
+extensions.  This file contains everything you need to build
+a new version of Python from include files and libraries normally
+installed with the Python language.
+
+This module will automatically grab all of the Python modules
+present in your current Python executable (including any special
+purpose modules you have enabled such as Tkinter).   Thus, you
+may need to provide additional link libraries when compiling.
+
+This library file only works with Python 1.5.  A version 
+compatible with Python 1.4 is available as embed14.i and
+a Python1.3 version is available as embed13.i.    As far as
+I know, this module is C++ safe.
+%}
+#else
+%echo "embed.i : Using Python 1.5"
+#endif
+
+%wrapper %{
+
+#include <Python.h>
+
+#ifdef __cplusplus
+extern "C"
+#endif
+void SWIG_init();  /* Forward reference */
+
+#define _PyImport_Inittab swig_inittab
+
+/* Grab Python's inittab[] structure */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include <config.c>
+
+#undef _PyImport_Inittab 
+
+/* Now define our own version of it.
+   Hopefully someone does not have more than 1000 built-in modules */
+
+struct _inittab SWIG_Import_Inittab[1000];       
+
+static int  swig_num_modules = 0;
+
+/* Function for adding modules to Python */
+
+static void swig_add_module(char *name, void (*initfunc)()) {
+	SWIG_Import_Inittab[swig_num_modules].name = name;
+	SWIG_Import_Inittab[swig_num_modules].initfunc = initfunc;
+	swig_num_modules++;
+	SWIG_Import_Inittab[swig_num_modules].name = (char *) 0;
+	SWIG_Import_Inittab[swig_num_modules].initfunc = 0;
+}				
+
+/* Function to add all of Python's build in modules to our interpreter */
+
+static void swig_add_builtin() {
+	int i = 0;
+	while (swig_inittab[i].name) {
+		swig_add_module(swig_inittab[i].name, swig_inittab[i].initfunc);
+  	        i++;
+ 	}
+#ifdef SWIGMODINIT
+	SWIGMODINIT	
+#endif
+	/* Add SWIG builtin function */
+	swig_add_module(SWIG_name, SWIG_init);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int Py_Main(int, char **);
+
+#ifdef __cplusplus
+}
+#endif
+
+extern struct _inittab *PyImport_Inittab;
+
+int
+main(int argc, char **argv) {
+	swig_add_builtin();
+	PyImport_Inittab = SWIG_Import_Inittab;
+	return Py_Main(argc,argv);
+}
+
+%}
+
+
+  
+
diff --git a/trunk/Lib/python/exception.i b/trunk/Lib/python/exception.i
new file mode 100644
index 0000000..bb0b15c
--- /dev/null
+++ b/trunk/Lib/python/exception.i
@@ -0,0 +1,6 @@
+%include <typemaps/exception.swg>
+
+
+%insert("runtime") {
+  %define_as(SWIG_exception(code, msg), %block(%error(code, msg); SWIG_fail; ))
+}
diff --git a/trunk/Lib/python/factory.i b/trunk/Lib/python/factory.i
new file mode 100644
index 0000000..46a0a87
--- /dev/null
+++ b/trunk/Lib/python/factory.i
@@ -0,0 +1 @@
+%include <typemaps/factory.swg>
diff --git a/trunk/Lib/python/file.i b/trunk/Lib/python/file.i
new file mode 100644
index 0000000..c0e7d5e
--- /dev/null
+++ b/trunk/Lib/python/file.i
@@ -0,0 +1,43 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * file.i
+ *
+ * Typemaps for FILE*
+ * From the ideas of Luigi Ballabio
+ * ----------------------------------------------------------------------------- */
+
+%types(FILE *);
+
+/* defining basic methods */
+%fragment("SWIG_AsValFilePtr","header") {
+SWIGINTERN int
+SWIG_AsValFilePtr(PyObject *obj, FILE **val) {
+  static swig_type_info* desc = 0;
+  void *vptr = 0;
+  if (!desc) desc = SWIG_TypeQuery("FILE *");
+  if ((SWIG_ConvertPtr(obj, &vptr, desc, 0)) == SWIG_OK) {
+    if (val) *val = (FILE *)vptr;
+    return SWIG_OK;
+  } 
+  if (PyFile_Check(obj)) {
+    if (val) *val =  PyFile_AsFile(obj);
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+
+%fragment("SWIG_AsFilePtr","header",fragment="SWIG_AsValFilePtr") {
+SWIGINTERNINLINE FILE*
+SWIG_AsFilePtr(PyObject *obj) {
+  FILE *val = 0;
+  SWIG_AsValFilePtr(obj, &val);
+  return val;
+}
+}
+
+/* defining the typemaps */
+%typemaps_asval(%checkcode(POINTER), SWIG_AsValFilePtr, "SWIG_AsValFilePtr", FILE*);
diff --git a/trunk/Lib/python/implicit.i b/trunk/Lib/python/implicit.i
new file mode 100644
index 0000000..152c2b0
--- /dev/null
+++ b/trunk/Lib/python/implicit.i
@@ -0,0 +1,7 @@
+%include <std_common.i>
+%include <typemaps/implicit.swg>
+
+#warning "This file provides the %implicit directive, which is an old and fragile"
+#warning "way to implement the C++ implicit conversion mechanism."
+#warning "Try using the more robust '%implicitconv Type;' directive instead."
+
diff --git a/trunk/Lib/python/jstring.i b/trunk/Lib/python/jstring.i
new file mode 100644
index 0000000..bda9523
--- /dev/null
+++ b/trunk/Lib/python/jstring.i
@@ -0,0 +1,72 @@
+%include <typemaps/valtypes.swg>
+
+%fragment(SWIG_AsVal_frag(jstring),"header") {
+SWIGINTERN int
+SWIG_AsVal(jstring)(PyObject *obj, jstring *val)
+{
+  if (obj == Py_None) {
+    if (val) *val = 0;
+    return SWIG_OK;
+  }
+  
+  PyObject *tmp = 0;
+  int isunicode = PyUnicode_Check(obj);
+  if (!isunicode && PyString_Check(obj)) {
+    if (val) {
+      obj = tmp = PyUnicode_FromObject(obj);
+    }
+    isunicode = 1;
+  }
+  if (isunicode) {
+    if (val) {
+      if (sizeof(Py_UNICODE) == sizeof(jchar)) {
+	*val = JvNewString((const jchar *) PyUnicode_AS_UNICODE(obj),PyUnicode_GET_SIZE(obj));
+	return SWIG_NEWOBJ;
+      } else {
+	int len = PyUnicode_GET_SIZE(obj);
+	Py_UNICODE *pchars = PyUnicode_AS_UNICODE(obj);
+	*val = JvAllocString (len);
+	jchar *jchars = JvGetStringChars (*val);	
+	for (int i = 0; i < len; ++i) {
+	  jchars[i] = pchars[i];
+	}
+	return SWIG_NEWOBJ;
+      }
+    }
+    Py_XDECREF(tmp);
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment(SWIG_From_frag(jstring),"header") {
+SWIGINTERNINLINE PyObject *
+SWIG_From(jstring)(jstring val)
+{
+  if (!val) {
+    return SWIG_Py_Void();
+  } 
+  if (sizeof(Py_UNICODE) == sizeof(jchar)) {    
+    return PyUnicode_FromUnicode((const Py_UNICODE *) JvGetStringChars(val),
+				 JvGetStringUTFLength(val));
+  } else {
+    int len = JvGetStringUTFLength(val);
+    Py_UNICODE pchars[len];
+    jchar *jchars = JvGetStringChars(val);
+    
+    for (int i = 0; i < len; i++) {      
+      pchars[i] = jchars[i];
+    }
+    return PyUnicode_FromUnicode((const Py_UNICODE *) pchars, len);
+  }
+}
+}
+
+%typemaps_asvalfrom(%checkcode(STRING),
+		    %arg(SWIG_AsVal(jstring)), 
+		    %arg(SWIG_From(jstring)), 
+		    %arg(SWIG_AsVal_frag(jstring)), 
+		    %arg(SWIG_From_frag(jstring)), 
+		    java::lang::String *);
+
diff --git a/trunk/Lib/python/pyapi.swg b/trunk/Lib/python/pyapi.swg
new file mode 100644
index 0000000..1d5148d
--- /dev/null
+++ b/trunk/Lib/python/pyapi.swg
@@ -0,0 +1,36 @@
+/* -----------------------------------------------------------------------------
+ * Python API portion that goes into the runtime
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* cc-mode */
+#endif
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Constant declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Constant Types */
+#define SWIG_PY_POINTER 4
+#define SWIG_PY_BINARY  5
+
+/* Constant information structure */
+typedef struct swig_const_info {
+  int type;
+  char *name;
+  long lvalue;
+  double dvalue;
+  void   *pvalue;
+  swig_type_info **ptype;
+} swig_const_info;
+
+#ifdef __cplusplus
+#if 0
+{ /* cc-mode */
+#endif
+}
+#endif
+
diff --git a/trunk/Lib/python/pybackward.swg b/trunk/Lib/python/pybackward.swg
new file mode 100644
index 0000000..8305fc7
--- /dev/null
+++ b/trunk/Lib/python/pybackward.swg
@@ -0,0 +1,45 @@
+/* 
+   adding backward compatibility macros
+*/
+
+#define SWIG_arg(x...)     %arg(x)
+#define SWIG_Mangle(x...)  %mangle(x)
+
+#define SWIG_As_frag(Type...)      %fragment_name(As, Type)
+#define SWIG_As_name(Type...)      %symbol_name(As, Type) 
+#define SWIG_As(Type...)     	   SWIG_As_name(Type) SWIG_AS_CALL_ARGS 
+
+#define SWIG_Check_frag(Type...)   %fragment_name(Check, Type)
+#define SWIG_Check_name(Type...)   %symbol_name(Check, Type) 
+#define SWIG_Check(Type...)        SWIG_Check_name(Type) SWIG_AS_CALL_ARGS 
+
+%define %ascheck_methods(Code, Type...)
+%fragment(SWIG_As_frag(Type),"header", fragment=SWIG_AsVal_frag(Type)) {
+SWIGINTERNINLINE Type
+SWIG_As(Type)(PyObject* obj)
+{
+  Type v;
+  int res = SWIG_AsVal(Type)(obj, &v);
+  if (!SWIG_IsOK(res)) {
+    /*
+      this is needed to make valgrind/purify happier. 
+     */
+    memset((void*)&v, 0, sizeof(Type));
+    SWIG_Error(res, "");
+  }
+  return v;
+}
+}
+
+%fragment(SWIG_Check_frag(Type),"header",fragment=SWIG_AsVal_frag(Type)) {
+SWIGINTERNINLINE int
+SWIG_Check(Type)(PyObject* obj)
+{
+  int res = SWIG_AsVal(Type)(obj, (Type*)0);
+  return SWIG_IsOK(res);
+}
+}
+%enddef
+
+%apply_checkctypes(%ascheck_methods)
+
diff --git a/trunk/Lib/python/pyclasses.swg b/trunk/Lib/python/pyclasses.swg
new file mode 100644
index 0000000..0caecd6
--- /dev/null
+++ b/trunk/Lib/python/pyclasses.swg
@@ -0,0 +1,146 @@
+#ifdef __cplusplus
+
+/*
+  PyObject_ptr is used as a replacement of PyObject *, where
+  the INCREF/DECREF are applied as needed.
+
+  You can use PyObject_ptr in a container, such as
+  
+     std::vector<PyObject_ptr>;
+
+  or as a member variable:
+  
+     struct A {
+       PyObject_ptr obj;
+       A(PyObject *o) : _obj(o) {
+       }
+     };
+
+   or as a input/output value 
+
+     PyObject_ptr func(PyObject_ptr obj) {     
+       PyObject_ptr out = PyString_FromFormat("hello %s", PyObject_AsString(obj));
+       Py_DECREF(out);
+       return out;
+     }
+
+   just remember to pair the object creation with the proper DECREF,
+   the same as with plain PyObject *ptr, since PyObject_ptr always add
+   one reference at construction.
+
+   PyObject_ptr is 'visible' at the wrapped side, so you can do:
+
+
+      %template(pyvector) std::vector<swig::PyObject_ptr>;
+
+   and all the proper typemaps will be used.
+   
+*/
+
+namespace swig {
+  %ignore PyObject_ptr;
+  struct PyObject_ptr {};
+  %apply PyObject * {PyObject_ptr};
+  %apply PyObject * const& {PyObject_ptr const&};
+
+  /* For output */
+  %typemap(out,noblock=1)  PyObject_ptr {
+    $result = (PyObject *)$1;
+    Py_INCREF($result);
+  }
+  
+  %typemap(out,noblock=1)  PyObject_ptr const & {
+    $result = (PyObject *)*$1;
+    Py_INCREF($result);
+  }
+  
+}
+
+%{
+namespace swig {
+  class PyObject_ptr {
+  protected:
+    PyObject *_obj;
+
+  public:
+    PyObject_ptr() :_obj(0)
+    {
+    }
+
+    PyObject_ptr(const PyObject_ptr& item) : _obj(item._obj)
+    {
+      Py_XINCREF(_obj);      
+    }
+    
+    PyObject_ptr(PyObject *obj, bool initial_ref = true) :_obj(obj)
+    {
+      if (initial_ref) {
+        Py_XINCREF(_obj);
+      }
+    }
+    
+    PyObject_ptr & operator=(const PyObject_ptr& item) 
+    {
+      Py_XINCREF(item._obj);
+      Py_XDECREF(_obj);
+      _obj = item._obj;
+      return *this;      
+    }
+    
+    ~PyObject_ptr() 
+    {
+      Py_XDECREF(_obj);
+    }
+    
+    operator PyObject *() const
+    {
+      return _obj;
+    }
+
+    PyObject *operator->() const
+    {
+      return _obj;
+    }
+  };
+}
+%}
+
+/*
+  PyObject_var is used to manage 'in the scope' PyObject * variables,
+  as in
+
+  int func () {
+    PyObject_var obj = PyString_FromString("hello");
+  }
+
+  ie, 'obj' is created and destructed in the same scope from
+  a python object that carries at least one reference value.
+  
+  PyObject_var just take care of applying the proper Py_DECREF.
+
+  Hence, this class is purely internal and not visible at the wrapped side.
+ */
+namespace swig {
+  %ignore PyObject_var;
+  struct PyObject_var {};
+  %apply PyObject * {PyObject_var};
+  %apply PyObject * const& {PyObject_var const&};
+}
+
+%{
+namespace swig {
+  struct PyObject_var : PyObject_ptr {
+    PyObject_var(PyObject* obj = 0) : PyObject_ptr(obj, false) { }
+    
+    PyObject_var & operator = (PyObject* obj)
+    {
+      Py_XDECREF(_obj);
+      _obj = obj;
+      return *this;      
+    }
+  };
+}
+%}
+
+
+#endif
diff --git a/trunk/Lib/python/pycomplex.swg b/trunk/Lib/python/pycomplex.swg
new file mode 100644
index 0000000..7914b0e
--- /dev/null
+++ b/trunk/Lib/python/pycomplex.swg
@@ -0,0 +1,86 @@
+/*
+  Defines the As/From conversors for double/float complex, you need to
+  provide complex Type, the Name you want to use in the conversors,
+  the complex Constructor method, and the Real and Imag complex
+  accesor methods.
+
+  See the std_complex.i and ccomplex.i for concret examples.
+*/
+
+/* the common from conversor */
+%define %swig_fromcplx_conv(Type, Real, Imag)
+%fragment(SWIG_From_frag(Type),"header")
+{
+SWIGINTERNINLINE PyObject*
+SWIG_From(Type)(%ifcplusplus(const Type&, Type) c)
+{
+  return PyComplex_FromDoubles(Real(c), Imag(c));
+}
+}
+%enddef
+
+/* the double case */
+%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag)
+%fragment(SWIG_AsVal_frag(Type),"header",
+	  fragment=SWIG_AsVal_frag(double))
+{
+SWIGINTERN int
+SWIG_AsVal(Type) (PyObject *o, Type* val)
+{
+  if (PyComplex_Check(o)) {
+    if (val) *val = Constructor(PyComplex_RealAsDouble(o), PyComplex_ImagAsDouble(o));
+    return SWIG_OK;
+  } else {
+    double d;    
+    int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d));
+    if (SWIG_IsOK(res)) {
+      if (val) *val = Constructor(d, 0.0);
+      return res;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+%swig_fromcplx_conv(Type, Real, Imag);
+%enddef
+
+/* the float case */
+%define %swig_cplxflt_conv(Type, Constructor, Real, Imag)
+%fragment(SWIG_AsVal_frag(Type),"header",
+          fragment=SWIG_AsVal_frag(float)) {
+SWIGINTERN int
+SWIG_AsVal(Type)(PyObject *o, Type *val)
+{
+  if (PyComplex_Check(o)) {
+    double re = PyComplex_RealAsDouble(o);
+    double im = PyComplex_ImagAsDouble(o);
+    if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) {
+      if (val) *val = Constructor(%numeric_cast(re, float),
+				  %numeric_cast(im, float));
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }    
+  } else {
+    float re;
+    int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re));
+    if (SWIG_IsOK(res)) {
+      if (val) *val = Constructor(re, 0.0);
+      return res;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+%swig_fromcplx_conv(Type, Real, Imag);
+%enddef
+
+#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \
+%swig_cplxflt_conv(Type, Constructor, Real, Imag)
+
+
+#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \
+%swig_cplxdbl_conv(Type, Constructor, Real, Imag)
+
+
diff --git a/trunk/Lib/python/pycontainer.swg b/trunk/Lib/python/pycontainer.swg
new file mode 100644
index 0000000..ed0eb7f
--- /dev/null
+++ b/trunk/Lib/python/pycontainer.swg
@@ -0,0 +1,763 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pycontainer.swg
+ *
+ * Python sequence <-> C++ container wrapper
+ *
+ * This wrapper, and its iterator, allows a general use (and reuse) of
+ * the the mapping between C++ and Python, thanks to the C++
+ * templates.
+ *
+ * Of course, it needs the C++ compiler to support templates, but
+ * since we will use this wrapper with the STL containers, that should
+ * be the case.
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <iostream>
+%}
+
+
+#if !defined(SWIG_NO_EXPORT_ITERATOR_METHODS)
+# if !defined(SWIG_EXPORT_ITERATOR_METHODS)
+#  define SWIG_EXPORT_ITERATOR_METHODS SWIG_EXPORT_ITERATOR_METHODS
+# endif
+#endif
+
+%include <pyiterators.swg>
+
+/**** The PySequence C++ Wrap ***/
+
+%insert(header) %{
+#include <stdexcept>
+%}
+
+%include <std_except.i>
+
+%fragment(SWIG_Traits_frag(swig::PyObject_ptr),"header",fragment="StdTraits") {
+namespace swig {
+  template <>  struct traits<PyObject_ptr > {
+    typedef value_category category;
+    static const char* type_name() { return  "PyObject_ptr"; }
+  };
+  
+  template <>  struct traits_from<PyObject_ptr> {
+    typedef PyObject_ptr value_type;
+    static PyObject *from(const value_type& val) {
+      PyObject *obj = static_cast<PyObject *>(val);
+      Py_XINCREF(obj);
+      return obj;
+    }
+  };
+  
+  template <> 
+  struct traits_check<PyObject_ptr, value_category> {
+    static bool check(PyObject_ptr) {
+      return true;
+    }
+  };
+  
+  template <>  struct traits_asval<PyObject_ptr > {   
+    typedef PyObject_ptr value_type;
+    static int asval(PyObject *obj, value_type *val) {
+      if (val) *val = obj;
+      return SWIG_OK;
+    }
+  };
+}
+}
+
+%fragment(SWIG_Traits_frag(swig::PyObject_var),"header",fragment="StdTraits") {
+namespace swig {
+  template <>  struct traits<PyObject_var > {
+    typedef value_category category;
+    static const char* type_name() { return  "PyObject_var"; }
+  };
+  
+  template <>  struct traits_from<PyObject_var> {
+    typedef PyObject_var value_type;
+    static PyObject *from(const value_type& val) {
+      PyObject *obj = static_cast<PyObject *>(val);
+      Py_XINCREF(obj);
+      return obj;
+    }
+  };
+  
+  template <> 
+  struct traits_check<PyObject_var, value_category> {
+    static bool check(PyObject_var) {
+      return true;
+    }
+  };
+  
+  template <>  struct traits_asval<PyObject_var > {   
+    typedef PyObject_var value_type;
+    static int asval(PyObject *obj, value_type *val) {
+      if (val) *val = obj;
+      return SWIG_OK;
+    }
+  };
+} 
+}
+
+%fragment("PySequence_Base","header")
+{
+%#include <functional>
+
+namespace std {
+  template <>
+  struct less <PyObject *>: public binary_function<PyObject *, PyObject *, bool>
+  {
+    bool
+    operator()(PyObject * v, PyObject *w) const
+    { 
+      bool res;
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+      res = PyObject_Compare(v, w) < 0;
+      SWIG_PYTHON_THREAD_END_BLOCK;
+      return res;
+    }
+  };
+
+  template <>
+  struct less <swig::PyObject_ptr>: public binary_function<swig::PyObject_ptr, swig::PyObject_ptr, bool>
+  {
+    bool
+    operator()(const swig::PyObject_ptr& v, const swig::PyObject_ptr& w) const
+    {
+      return std::less<PyObject *>()(v, w);
+    }
+  };
+
+  template <>
+  struct less <swig::PyObject_var>: public binary_function<swig::PyObject_var, swig::PyObject_var, bool>
+  {
+    bool
+    operator()(const swig::PyObject_var& v, const swig::PyObject_var& w) const
+    {
+      return std::less<PyObject *>()(v, w);
+    }
+  };
+
+}
+
+namespace swig {
+  template <> struct traits<PyObject *> {
+    typedef value_category category;
+    static const char* type_name() { return "PyObject *"; }
+  };  
+
+  template <>  struct traits_asval<PyObject * > {   
+    typedef PyObject * value_type;
+    static int asval(PyObject *obj, value_type *val) {
+      if (val) *val = obj;
+      return SWIG_OK;
+    }
+  };
+
+  template <> 
+  struct traits_check<PyObject *, value_category> {
+    static bool check(PyObject *) {
+      return true;
+    }
+  };
+
+  template <>  struct traits_from<PyObject *> {
+    typedef PyObject * value_type;
+    static PyObject *from(const value_type& val) {
+      Py_XINCREF(val);
+      return val;
+    }
+  };
+  
+}
+
+namespace swig {
+  inline size_t
+  check_index(ptrdiff_t i, size_t size, bool insert = false) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size)
+	return (size_t) (i + size);
+    } else if ( (size_t) i < size ) {
+      return (size_t) i;
+    } else if (insert && ((size_t) i == size)) {
+      return size;
+    }
+    
+    throw std::out_of_range("index out of range");
+  }
+
+  inline size_t
+  slice_index(ptrdiff_t i, size_t size) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size) {
+	return (size_t) (i + size);
+      } else {
+	throw std::out_of_range("index out of range");
+      }
+    } else {
+      return ( (size_t) i < size ) ? ((size_t) i) : size;
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::iterator
+  getpos(Sequence* self, Difference i)  {
+    typename Sequence::iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::const_iterator
+  cgetpos(const Sequence* self, Difference i)  {
+    typename Sequence::const_iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline Sequence*
+  getslice(const Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+
+    if (jj > ii) {
+      typename Sequence::const_iterator vb = self->begin();
+      typename Sequence::const_iterator ve = self->begin();
+      std::advance(vb,ii);
+      std::advance(ve,jj);
+      return new Sequence(vb, ve);
+    } else {
+      return new Sequence();
+    }
+  }
+
+  template <class Sequence, class Difference, class InputSeq>
+  inline void
+  setslice(Sequence* self, Difference i, Difference j, const InputSeq& v) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj < ii) jj = ii;
+    size_t ssize = jj - ii;
+    if (ssize <= v.size()) {
+      typename Sequence::iterator sb = self->begin();
+      typename InputSeq::const_iterator vmid = v.begin();
+      std::advance(sb,ii);
+      std::advance(vmid, jj - ii);
+      self->insert(std::copy(v.begin(), vmid, sb), vmid, v.end());
+    } else {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+      self->insert(sb, v.begin(), v.end());
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline void
+  delslice(Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj > ii) {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+    }
+  }
+}
+}
+
+%fragment("PySequence_Cont","header",
+	  fragment="StdTraits",
+	  fragment="PySequence_Base",
+	  fragment="PySwigIterator_T")
+{
+namespace swig
+{
+  template <class T>
+  struct PySequence_Ref
+  {
+    PySequence_Ref(PyObject* seq, int index)
+      : _seq(seq), _index(index)
+    {
+    }
+    
+    operator T () const
+    {
+      swig::PyObject_var item = PySequence_GetItem(_seq, _index);
+      try {
+	return swig::as<T>(item, true);
+      } catch (std::exception& e) {
+	char msg[1024];
+	sprintf(msg, "in sequence element %d ", _index);
+	if (!PyErr_Occurred()) {
+	  ::%type_error(swig::type_name<T>());
+	}
+	SWIG_Python_AddErrorMsg(msg);
+	SWIG_Python_AddErrorMsg(e.what());
+	throw;
+      }
+    }
+
+    PySequence_Ref& operator=(const T& v)
+    {
+      PySequence_SetItem(_seq, _index, swig::from<T>(v));
+      return *this;
+    }
+
+  private:
+    PyObject* _seq;
+    int _index;
+  };
+
+  template <class T>
+  struct PySequence_ArrowProxy
+  {
+    PySequence_ArrowProxy(const T& x): m_value(x) {}
+    const T* operator->() const { return &m_value; }
+    operator const T*() const { return &m_value; }
+    T m_value;
+  };
+
+  template <class T, class Reference >
+  struct PySequence_InputIterator
+  {
+    typedef PySequence_InputIterator<T, Reference > self;
+
+    typedef std::random_access_iterator_tag iterator_category;
+    typedef Reference reference;
+    typedef T value_type;
+    typedef T* pointer;
+    typedef int difference_type;
+
+    PySequence_InputIterator()
+    {
+    }
+
+    PySequence_InputIterator(PyObject* seq, int index)
+      : _seq(seq), _index(index)
+    {
+    }
+
+    reference operator*() const
+    {
+      return reference(_seq, _index);
+    }
+
+    PySequence_ArrowProxy<T>
+    operator->() const {
+      return PySequence_ArrowProxy<T>(operator*());
+    }
+
+    bool operator==(const self& ri) const
+    {
+      return (_index == ri._index) && (_seq == ri._seq);
+    }
+
+    bool operator!=(const self& ri) const
+    {
+      return !(operator==(ri));
+    }
+
+    self& operator ++ ()
+    {
+      ++_index;
+      return *this;
+    }
+
+    self& operator -- ()
+    {
+      --_index;
+      return *this;
+    }
+
+    self& operator += (difference_type n)
+    {
+      _index += n;
+      return *this;
+    }
+
+    self operator +(difference_type n) const
+    {
+      return self(_seq, _index + n);
+    }
+
+    self& operator -= (difference_type n)
+    {
+      _index -= n;
+      return *this;
+    }
+
+    self operator -(difference_type n) const
+    {
+      return self(_seq, _index - n);
+    }
+
+    difference_type operator - (const self& ri) const
+    {
+      return _index - ri._index;
+    }
+
+    bool operator < (const self& ri) const
+    {
+      return _index < ri._index;
+    }
+
+    reference
+    operator[](difference_type n) const
+    {
+      return reference(_seq, _index + n);
+    }
+
+  private:
+    PyObject* _seq;
+    difference_type _index;
+  };
+
+  template <class T>
+  struct PySequence_Cont
+  {
+    typedef PySequence_Ref<T> reference;
+    typedef const PySequence_Ref<T> const_reference;
+    typedef T value_type;
+    typedef T* pointer;
+    typedef int difference_type;
+    typedef int size_type;
+    typedef const pointer const_pointer;
+    typedef PySequence_InputIterator<T, reference> iterator;
+    typedef PySequence_InputIterator<T, const_reference> const_iterator;
+
+    PySequence_Cont(PyObject* seq) : _seq(0)
+    {
+      if (!PySequence_Check(seq)) {
+	throw std::invalid_argument("a sequence is expected");
+      }
+      _seq = seq;
+      Py_INCREF(_seq);
+    }
+
+    ~PySequence_Cont()
+    {
+      Py_XDECREF(_seq);
+    }
+
+    size_type size() const
+    {
+      return static_cast<size_type>(PySequence_Size(_seq));
+    }
+
+    bool empty() const
+    {
+      return size() == 0;
+    }
+
+    iterator begin()
+    {
+      return iterator(_seq, 0);
+    }
+
+    const_iterator begin() const
+    {
+      return const_iterator(_seq, 0);
+    }
+
+    iterator end()
+    {
+      return iterator(_seq, size());
+    }
+
+    const_iterator end() const
+    {
+      return const_iterator(_seq, size());
+    }
+
+    reference operator[](difference_type n)
+    {
+      return reference(_seq, n);
+    }
+
+    const_reference operator[](difference_type n)  const
+    {
+      return const_reference(_seq, n);
+    }
+
+    bool check(bool set_err = true) const
+    {
+      int s = size();
+      for (int i = 0; i < s; ++i) {
+	swig::PyObject_var item = PySequence_GetItem(_seq, i);
+	if (!swig::check<value_type>(item)) {
+	  if (set_err) {
+	    char msg[1024];
+	    sprintf(msg, "in sequence element %d", i);
+	    SWIG_Error(SWIG_RuntimeError, msg);
+	  }
+	  return false;
+	}
+      }
+      return true;
+    }
+
+  private:
+    PyObject* _seq;
+  };
+
+}
+}
+
+%define %swig_sequence_iterator(Sequence...)
+#if defined(SWIG_EXPORT_ITERATOR_METHODS)
+  class iterator;
+  class reverse_iterator;
+  class const_iterator;
+  class const_reverse_iterator;
+
+  %typemap(out,noblock=1,fragment="PySequence_Cont")
+    iterator, reverse_iterator, const_iterator, const_reverse_iterator {
+    $result = SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &)),
+				 swig::PySwigIterator::descriptor(),SWIG_POINTER_OWN);
+  }
+  %typemap(out,noblock=1,fragment="PySequence_Cont")
+    std::pair<iterator, iterator>, std::pair<const_iterator, const_iterator> {
+    $result = PyTuple_New(2);
+    PyTuple_SetItem($result,0,SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).first),
+						 swig::PySwigIterator::descriptor(),SWIG_POINTER_OWN));
+    PyTuple_SetItem($result,1,SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).second),
+						 swig::PySwigIterator::descriptor(),SWIG_POINTER_OWN));    
+  }
+
+  %fragment("PyPairBoolOutputIterator","header",fragment=SWIG_From_frag(bool),fragment="PySequence_Cont") {}
+
+  %typemap(out,noblock=1,fragment="PyPairBoolOutputIterator")
+    std::pair<iterator, bool>, std::pair<const_iterator, bool> {
+    $result = PyTuple_New(2);
+    PyTuple_SetItem($result,0,SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).first),
+					       swig::PySwigIterator::descriptor(),SWIG_POINTER_OWN));    
+    PyTuple_SetItem($result,1,SWIG_From(bool)(%static_cast($1,const $type &).second));
+  }
+
+  %typemap(in,noblock=1,fragment="PySequence_Cont")
+    iterator(swig::PySwigIterator *iter = 0, int res),
+    reverse_iterator(swig::PySwigIterator *iter = 0, int res),
+    const_iterator(swig::PySwigIterator *iter = 0, int res),
+    const_reverse_iterator(swig::PySwigIterator *iter = 0, int res) {
+    res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::PySwigIterator::descriptor(), 0);
+    if (!SWIG_IsOK(res) || !iter) {
+      %argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+    } else {
+      swig::PySwigIterator_T<$type > *iter_t = dynamic_cast<swig::PySwigIterator_T<$type > *>(iter);
+      if (iter_t) {
+	$1 = iter_t->get_current();
+      } else {
+	%argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+      }
+    }
+  }
+
+  %typecheck(%checkcode(ITERATOR),noblock=1,fragment="PySequence_Cont")
+    iterator, reverse_iterator, const_iterator, const_reverse_iterator {
+    swig::PySwigIterator *iter = 0;
+    int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::PySwigIterator::descriptor(), 0);
+    $1 = (SWIG_IsOK(res) && iter && (dynamic_cast<swig::PySwigIterator_T<$type > *>(iter) != 0));
+  }
+
+  %fragment("PySequence_Cont");
+
+  %newobject iterator(PyObject **PYTHON_SELF);
+  %extend  {
+    swig::PySwigIterator* iterator(PyObject **PYTHON_SELF) {
+      return swig::make_output_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF);
+    }
+
+    %pythoncode {def __iter__(self): return self.iterator()}
+  }
+#endif //SWIG_EXPORT_ITERATOR_METHODS
+%enddef
+
+
+/**** The python container methods  ****/
+
+
+%define %swig_container_methods(Container...)
+
+  %newobject __getslice__;
+
+  %extend {
+    bool __nonzero__() const {
+      return !(self->empty());
+    }
+
+    size_type __len__() const {
+      return self->size();
+    }
+  }
+%enddef
+
+%define %swig_sequence_methods_common(Sequence...)
+  %swig_sequence_iterator(%arg(Sequence))
+  %swig_container_methods(%arg(Sequence))
+  
+  %fragment("PySequence_Base");
+
+  %extend {
+    value_type pop() throw (std::out_of_range) {
+      if (self->size() == 0)
+	throw std::out_of_range("pop from empty container");
+      Sequence::value_type x = self->back();
+      self->pop_back();
+      return x;
+    }
+
+    Sequence* __getslice__(difference_type i, difference_type j) throw (std::out_of_range) {
+      return swig::getslice(self, i, j);
+    }
+
+    void __setslice__(difference_type i, difference_type j, const Sequence& v) 
+      throw (std::out_of_range, std::invalid_argument) {
+      swig::setslice(self, i, j, v);
+    }
+
+    void __delslice__(difference_type i, difference_type j) throw (std::out_of_range) {
+      swig::delslice(self, i, j);
+    }
+
+    void __delitem__(difference_type i) throw (std::out_of_range) {
+      self->erase(swig::getpos(self,i));
+    }
+  }
+%enddef
+
+%define %swig_sequence_methods(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+  %extend {
+    const value_type& __getitem__(difference_type i) const throw (std::out_of_range) {
+      return *(swig::cgetpos(self, i));
+    }
+
+    void __setitem__(difference_type i, const value_type& x) throw (std::out_of_range) {
+      *(swig::getpos(self,i)) = x;
+    }
+
+    void append(const value_type& x) {
+      self->push_back(x);
+    }
+ }
+%enddef
+
+%define %swig_sequence_methods_val(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+  %extend {
+    value_type __getitem__(difference_type i) throw (std::out_of_range) {
+      return *(swig::cgetpos(self, i));
+    }
+
+    void __setitem__(difference_type i, value_type x) throw (std::out_of_range) {
+      *(swig::getpos(self,i)) = x;
+    }
+
+    void append(value_type x) {
+      self->push_back(x);
+    }
+ }
+%enddef
+
+
+
+//
+// Common fragments
+//
+
+%fragment("StdSequenceTraits","header",
+	  fragment="StdTraits",
+	  fragment="PySequence_Cont")
+{
+namespace swig {
+  template <class PySeq, class Seq>
+  inline void
+  assign(const PySeq& pyseq, Seq* seq) {
+    // seq->assign(pyseq.begin(), pyseq.end()); // not used as not always implemented
+    typedef typename PySeq::value_type value_type;
+    typename PySeq::const_iterator it = pyseq.begin();
+    for (;it != pyseq.end(); ++it) {
+      seq->insert(seq->end(),(value_type)(*it));
+    }
+  }
+
+  template <class Seq, class T = typename Seq::value_type >
+  struct traits_asptr_stdseq {
+    typedef Seq sequence;
+    typedef T value_type;
+
+    static int asptr(PyObject *obj, sequence **seq) {
+      if (obj == Py_None || SWIG_Python_GetSwigThis(obj)) {
+	sequence *p;
+	if (::SWIG_ConvertPtr(obj,(void**)&p,
+			      swig::type_info<sequence>(),0) == SWIG_OK) {
+	  if (seq) *seq = p;
+	  return SWIG_OLDOBJ;
+	}
+      } else if (PySequence_Check(obj)) {
+	try {
+	  PySequence_Cont<value_type> pyseq(obj);
+	  if (seq) {
+	    sequence *pseq = new sequence();
+	    assign(pyseq, pseq);
+	    *seq = pseq;
+	    return SWIG_NEWOBJ;
+	  } else {
+	    return pyseq.check() ? SWIG_OK : SWIG_ERROR;
+	  }
+	} catch (std::exception& e) {
+	  if (seq) {
+	    if (!PyErr_Occurred()) {
+	      PyErr_SetString(PyExc_TypeError, e.what());
+	    }
+	  }
+	  return SWIG_ERROR;
+	}
+      }
+      return SWIG_ERROR;
+    }
+  };
+
+  template <class Seq, class T = typename Seq::value_type >
+  struct traits_from_stdseq {
+    typedef Seq sequence;
+    typedef T value_type;
+    typedef typename Seq::size_type size_type;
+    typedef typename sequence::const_iterator const_iterator;
+
+    static PyObject *from(const sequence& seq) {
+%#ifdef SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS
+      swig_type_info *desc = swig::type_info<sequence>();
+      if (desc && desc->clientdata) {
+	return SWIG_NewPointerObj(new sequence(seq), desc, SWIG_POINTER_OWN);
+      }
+%#endif
+      size_type size = seq.size();
+      if (size <= (size_type)INT_MAX) {
+	PyObject *obj = PyTuple_New((int)size);
+	int i = 0;
+	for (const_iterator it = seq.begin();
+	     it != seq.end(); ++it, ++i) {
+	  PyTuple_SetItem(obj,i,swig::from<value_type>(*it));
+	}
+	return obj;
+      } else {
+	PyErr_SetString(PyExc_OverflowError,"sequence size not valid in python");
+	return NULL;
+      }
+    }
+  };
+}
+}
diff --git a/trunk/Lib/python/pydocs.swg b/trunk/Lib/python/pydocs.swg
new file mode 100644
index 0000000..0091a30
--- /dev/null
+++ b/trunk/Lib/python/pydocs.swg
@@ -0,0 +1,18 @@
+
+// basic doc for primitive types....
+
+#ifdef SWIG_DOC_DOXYGEN_STYLE
+%typemap(doc) SWIGTYPE "@param $1_name $1_type value";
+%typemap(doc) SWIGTYPE* "@param $1_name $1_type value";
+%typemap(doc) const SWIGTYPE& "@param $1_name $1_type value";
+%typemap(doc) enum SWIGTYPE "@param $1_name enum $1_type value";
+#else
+%typemap(doc) SWIGTYPE "$1_name: $1_type value";
+%typemap(doc) SWIGTYPE* "$1_name: $1_type value";
+%typemap(doc) const SWIGTYPE& "$1_name: $1_type value";
+%typemap(doc) enum SWIGTYPE "$1_name: enum $1_type value";
+
+%typemap(doc) SWIGTYPE *INOUT "$1_name: $1_type input/ouput value";
+%typemap(doc) SWIGTYPE *INPUT "$1_name: $1_type input value";
+%typemap(doc) SWIGTYPE *OUTPUT "$1_name: $1_type output value";
+#endif
diff --git a/trunk/Lib/python/pyerrors.swg b/trunk/Lib/python/pyerrors.swg
new file mode 100644
index 0000000..e287e2f
--- /dev/null
+++ b/trunk/Lib/python/pyerrors.swg
@@ -0,0 +1,69 @@
+/* -----------------------------------------------------------------------------
+ * error manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIME PyObject*
+SWIG_Python_ErrorType(int code) {
+  PyObject* type = 0;
+  switch(code) {
+  case SWIG_MemoryError:
+    type = PyExc_MemoryError;
+    break;
+  case SWIG_IOError:
+    type = PyExc_IOError;
+    break;
+  case SWIG_RuntimeError:
+    type = PyExc_RuntimeError;
+    break;
+  case SWIG_IndexError:
+    type = PyExc_IndexError;
+    break;
+  case SWIG_TypeError:
+    type = PyExc_TypeError;
+    break;
+  case SWIG_DivisionByZero:
+    type = PyExc_ZeroDivisionError;
+    break;
+  case SWIG_OverflowError:
+    type = PyExc_OverflowError;
+    break;
+  case SWIG_SyntaxError:
+    type = PyExc_SyntaxError;
+    break;
+  case SWIG_ValueError:
+    type = PyExc_ValueError;
+    break;
+  case SWIG_SystemError:
+    type = PyExc_SystemError;
+    break;
+  case SWIG_AttributeError:
+    type = PyExc_AttributeError;
+    break;
+  default:
+    type = PyExc_RuntimeError;
+  }
+  return type;
+}
+
+
+SWIGRUNTIME void
+SWIG_Python_AddErrorMsg(const char* mesg)
+{
+  PyObject *type = 0;
+  PyObject *value = 0;
+  PyObject *traceback = 0;
+
+  if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback);
+  if (value) {
+    PyObject *old_str = PyObject_Str(value);
+    PyErr_Clear();
+    Py_XINCREF(type);
+    PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
+    Py_DECREF(old_str);
+    Py_DECREF(value);
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, mesg);
+  }
+}
+
+
diff --git a/trunk/Lib/python/pyfragments.swg b/trunk/Lib/python/pyfragments.swg
new file mode 100644
index 0000000..535a45b
--- /dev/null
+++ b/trunk/Lib/python/pyfragments.swg
@@ -0,0 +1,23 @@
+/*
+
+  Create a file with this name, 'pyfragments.swg', in your working
+  directory and add all the %fragments you want to take precedence
+  over the default ones defined by swig.
+
+  For example, if you add:
+  
+  %fragment(SWIG_AsVal_frag(int),"header") {
+   SWIGINTERNINLINE int
+   SWIG_AsVal(int)(PyObject *obj, int *val)
+   { 
+     <your code here>;
+   }
+  }
+  
+  this will replace the code used to retrieve an integer value for all
+  the typemaps that need it, including:
+  
+    int, std::vector<int>, std::list<std::pair<int,int> >, etc.
+
+    
+*/
diff --git a/trunk/Lib/python/pyhead.swg b/trunk/Lib/python/pyhead.swg
new file mode 100644
index 0000000..7839511
--- /dev/null
+++ b/trunk/Lib/python/pyhead.swg
@@ -0,0 +1,88 @@
+
+/* Add PyOS_snprintf for old Pythons */
+#if PY_VERSION_HEX < 0x02020000
+# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM)
+#  define PyOS_snprintf _snprintf
+# else
+#  define PyOS_snprintf snprintf
+# endif
+#endif
+
+/* A crude PyString_FromFormat implementation for old Pythons */
+#if PY_VERSION_HEX < 0x02020000
+
+#ifndef SWIG_PYBUFFER_SIZE
+# define SWIG_PYBUFFER_SIZE 1024
+#endif
+
+static PyObject *
+PyString_FromFormat(const char *fmt, ...) {
+  va_list ap;
+  char buf[SWIG_PYBUFFER_SIZE * 2];
+  int res;
+  va_start(ap, fmt);
+  res = vsnprintf(buf, sizeof(buf), fmt, ap);
+  va_end(ap);
+  return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf);
+}
+#endif
+
+/* Add PyObject_Del for old Pythons */
+#if PY_VERSION_HEX < 0x01060000
+# define PyObject_Del(op) PyMem_DEL((op))
+#endif
+#ifndef PyObject_DEL
+# define PyObject_DEL PyObject_Del
+#endif
+
+/* A crude PyExc_StopIteration exception for old Pythons */
+#if PY_VERSION_HEX < 0x02020000
+# ifndef PyExc_StopIteration
+#  define PyExc_StopIteration PyExc_RuntimeError
+# endif
+# ifndef PyObject_GenericGetAttr
+#  define PyObject_GenericGetAttr 0
+# endif
+#endif
+/* Py_NotImplemented is defined in 2.1 and up. */
+#if PY_VERSION_HEX < 0x02010000
+# ifndef Py_NotImplemented
+#  define Py_NotImplemented PyExc_RuntimeError
+# endif
+#endif
+
+
+/* A crude PyString_AsStringAndSize implementation for old Pythons */
+#if PY_VERSION_HEX < 0x02010000
+# ifndef PyString_AsStringAndSize
+#  define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;}
+# endif
+#endif
+
+/* PySequence_Size for old Pythons */
+#if PY_VERSION_HEX < 0x02000000
+# ifndef PySequence_Size
+#  define PySequence_Size PySequence_Length
+# endif
+#endif
+
+
+/* PyBool_FromLong for old Pythons */
+#if PY_VERSION_HEX < 0x02030000
+static
+PyObject *PyBool_FromLong(long ok)
+{
+  PyObject *result = ok ? Py_True : Py_False;
+  Py_INCREF(result);
+  return result;
+}
+#endif
+
+/* Py_ssize_t for old Pythons */
+/* This code is as recommended by: */
+/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */
+#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
+typedef int Py_ssize_t;
+# define PY_SSIZE_T_MAX INT_MAX
+# define PY_SSIZE_T_MIN INT_MIN
+#endif
diff --git a/trunk/Lib/python/pyinit.swg b/trunk/Lib/python/pyinit.swg
new file mode 100644
index 0000000..e6109b7
--- /dev/null
+++ b/trunk/Lib/python/pyinit.swg
@@ -0,0 +1,288 @@
+/* ------------------------------------------------------------
+ * The start of the Python initialization function 
+ * ------------------------------------------------------------ */
+
+%insert(init) "swiginit.swg"
+
+%init %{
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Python-specific SWIG API */
+#define SWIG_newvarlink()                             SWIG_Python_newvarlink()
+#define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)
+#define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)
+ 
+/* -----------------------------------------------------------------------------
+ * global variable support code.
+ * ----------------------------------------------------------------------------- */
+ 
+typedef struct swig_globalvar {   
+  char       *name;                  /* Name of global variable */
+  PyObject *(*get_attr)(void);       /* Return the current value */
+  int       (*set_attr)(PyObject *); /* Set the value */
+  struct swig_globalvar *next;
+} swig_globalvar;
+
+typedef struct swig_varlinkobject {
+  PyObject_HEAD
+  swig_globalvar *vars;
+} swig_varlinkobject;
+
+SWIGINTERN PyObject *
+swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) {
+  return PyString_FromString("<Swig global variables>");
+}
+
+SWIGINTERN PyObject *
+swig_varlink_str(swig_varlinkobject *v) {
+  PyObject *str = PyString_FromString("(");
+  swig_globalvar  *var;
+  for (var = v->vars; var; var=var->next) {
+    PyString_ConcatAndDel(&str,PyString_FromString(var->name));
+    if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", "));
+  }
+  PyString_ConcatAndDel(&str,PyString_FromString(")"));
+  return str;
+}
+
+SWIGINTERN int
+swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) {
+  PyObject *str = swig_varlink_str(v);
+  fprintf(fp,"Swig global variables ");
+  fprintf(fp,"%s\n", PyString_AsString(str));
+  Py_DECREF(str);
+  return 0;
+}
+
+SWIGINTERN void
+swig_varlink_dealloc(swig_varlinkobject *v) {
+  swig_globalvar *var = v->vars;
+  while (var) {
+    swig_globalvar *n = var->next;
+    free(var->name);
+    free(var);
+    var = n;
+  }
+}
+
+SWIGINTERN PyObject *
+swig_varlink_getattr(swig_varlinkobject *v, char *n) {
+  PyObject *res = NULL;
+  swig_globalvar *var = v->vars;
+  while (var) {
+    if (strcmp(var->name,n) == 0) {
+      res = (*var->get_attr)();
+      break;
+    }
+    var = var->next;
+  }
+  if (res == NULL && !PyErr_Occurred()) {
+    PyErr_SetString(PyExc_NameError,"Unknown C global variable");
+  }
+  return res;
+}
+
+SWIGINTERN int
+swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {
+  int res = 1;
+  swig_globalvar *var = v->vars;
+  while (var) {
+    if (strcmp(var->name,n) == 0) {
+      res = (*var->set_attr)(p);
+      break;
+    }
+    var = var->next;
+  }
+  if (res == 1 && !PyErr_Occurred()) {
+    PyErr_SetString(PyExc_NameError,"Unknown C global variable");
+  }
+  return res;
+}
+
+SWIGINTERN PyTypeObject*
+swig_varlink_type(void) {
+  static char varlink__doc__[] = "Swig var link object";
+  static PyTypeObject varlink_type;
+  static int type_init = 0;  
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+      PyObject_HEAD_INIT(NULL)
+      0,                                  /* Number of items in variable part (ob_size) */
+      (char *)"swigvarlink",              /* Type name (tp_name) */
+      sizeof(swig_varlinkobject),         /* Basic size (tp_basicsize) */
+      0,                                  /* Itemsize (tp_itemsize) */
+      (destructor) swig_varlink_dealloc,   /* Deallocator (tp_dealloc) */ 
+      (printfunc) swig_varlink_print,     /* Print (tp_print) */
+      (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */
+      (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */
+      0,                                  /* tp_compare */
+      (reprfunc) swig_varlink_repr,       /* tp_repr */
+      0,                                  /* tp_as_number */
+      0,                                  /* tp_as_sequence */
+      0,                                  /* tp_as_mapping */
+      0,                                  /* tp_hash */
+      0,                                  /* tp_call */
+      (reprfunc)swig_varlink_str,        /* tp_str */
+      0,                                  /* tp_getattro */
+      0,                                  /* tp_setattro */
+      0,                                  /* tp_as_buffer */
+      0,                                  /* tp_flags */
+      varlink__doc__,                     /* tp_doc */
+      0,                                  /* tp_traverse */
+      0,                                  /* tp_clear */
+      0,                                  /* tp_richcompare */
+      0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+      0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+      0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+    };
+    varlink_type = tmp;
+    varlink_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &varlink_type;
+}
+
+/* Create a variable linking object for use later */
+SWIGINTERN PyObject *
+SWIG_Python_newvarlink(void) {
+  swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type());
+  if (result) {
+    result->vars = 0;
+  }
+  return ((PyObject*) result);
+}
+
+SWIGINTERN void 
+SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
+  swig_varlinkobject *v = (swig_varlinkobject *) p;
+  swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
+  if (gv) {
+    size_t size = strlen(name)+1;
+    gv->name = (char *)malloc(size);
+    if (gv->name) {
+      strncpy(gv->name,name,size);
+      gv->get_attr = get_attr;
+      gv->set_attr = set_attr;
+      gv->next = v->vars;
+    }
+  }
+  v->vars = gv;
+}
+
+SWIGINTERN PyObject *
+SWIG_globals(void) {
+  static PyObject *_SWIG_globals = 0; 
+  if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink();  
+  return _SWIG_globals;
+}
+
+/* -----------------------------------------------------------------------------
+ * constants/methods manipulation
+ * ----------------------------------------------------------------------------- */
+
+/* Install Constants */
+SWIGINTERN void
+SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
+  PyObject *obj = 0;
+  size_t i;
+  for (i = 0; constants[i].type; ++i) {
+    switch(constants[i].type) {
+    case SWIG_PY_POINTER:
+      obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
+      break;
+    case SWIG_PY_BINARY:
+      obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
+      break;
+    default:
+      obj = 0;
+      break;
+    }
+    if (obj) {
+      PyDict_SetItemString(d, constants[i].name, obj);
+      Py_DECREF(obj);
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------*/
+/* Fix SwigMethods to carry the callback ptrs when needed */
+/* -----------------------------------------------------------------------------*/
+
+SWIGINTERN void
+SWIG_Python_FixMethods(PyMethodDef *methods,
+		       swig_const_info *const_table,
+		       swig_type_info **types,
+		       swig_type_info **types_initial) {
+  size_t i;
+  for (i = 0; methods[i].ml_name; ++i) {
+    const char *c = methods[i].ml_doc;
+    if (c && (c = strstr(c, "swig_ptr: "))) {
+      int j;
+      swig_const_info *ci = 0;
+      const char *name = c + 10;
+      for (j = 0; const_table[j].type; ++j) {
+	if (strncmp(const_table[j].name, name, 
+		    strlen(const_table[j].name)) == 0) {
+	  ci = &(const_table[j]);
+	  break;
+	}
+      }
+      if (ci) {
+	size_t shift = (ci->ptype) - types;
+	swig_type_info *ty = types_initial[shift];
+	size_t ldoc = (c - methods[i].ml_doc);
+	size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
+	char *ndoc = (char*)malloc(ldoc + lptr + 10);
+	if (ndoc) {
+	  char *buff = ndoc;
+	  void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;
+	  if (ptr) {
+	    strncpy(buff, methods[i].ml_doc, ldoc);
+	    buff += ldoc;
+	    strncpy(buff, "swig_ptr: ", 10);
+	    buff += 10;
+	    SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);
+	    methods[i].ml_doc = ndoc;
+	  }
+	}
+      }
+    }
+  }
+} 
+
+#ifdef __cplusplus
+}
+#endif
+
+/* -----------------------------------------------------------------------------*
+ *  Partial Init method
+ * -----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+#endif
+SWIGEXPORT void SWIG_init(void) {
+  PyObject *m, *d;
+  
+  /* Fix SwigMethods to carry the callback ptrs when needed */
+  SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);
+  
+  m = Py_InitModule((char *) SWIG_name, SwigMethods);
+  d = PyModule_GetDict(m);
+  
+  SWIG_InitializeModule(0);
+  SWIG_InstallConstants(d,swig_const_table);
+  
+%}
+
diff --git a/trunk/Lib/python/pyiterators.swg b/trunk/Lib/python/pyiterators.swg
new file mode 100644
index 0000000..38f1791
--- /dev/null
+++ b/trunk/Lib/python/pyiterators.swg
@@ -0,0 +1,385 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pyiterators.swg
+ *
+ * Implement a python 'output' iterator for Python 2.2 or higher.
+ *
+ * Users can derive form the PySwigIterator to implement their
+ * own iterators. As an example (real one since we use it for STL/STD
+ * containers), the template PySwigIterator_T does the
+ * implementation for genereic C++ iterators.
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+%fragment("PySwigIterator","header") {  
+namespace swig {
+  struct stop_iteration {
+  };
+
+  struct PySwigIterator {
+  private:
+    PyObject_ptr _seq;
+
+  protected:
+    PySwigIterator(PyObject *seq) : _seq(seq)
+    {
+    }
+      
+  public:
+    virtual ~PySwigIterator() {}
+
+    // Access iterator method, required by Python
+    virtual PyObject *value() const = 0;
+
+    // Forward iterator method, required by Python
+    virtual PySwigIterator *incr(size_t n = 1) = 0;
+    
+    // Backward iterator method, very common in C++, but not required in Python
+    virtual PySwigIterator *decr(size_t /*n*/ = 1)
+    {
+      throw stop_iteration();
+    }
+
+    // Random access iterator methods, but not required in Python
+    virtual ptrdiff_t distance(const PySwigIterator &/*x*/) const
+    {
+      throw std::invalid_argument("operation not supported");
+    }
+
+    virtual bool equal (const PySwigIterator &/*x*/) const
+    {
+      throw std::invalid_argument("operation not supported");
+    }
+    
+    // C++ common/needed methods
+    virtual PySwigIterator *copy() const = 0;
+
+    PyObject *next()     
+    {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK; // disable threads       
+      PyObject *obj = value();
+      incr();       
+      SWIG_PYTHON_THREAD_END_BLOCK; // re-enable threads
+      return obj;     
+    }
+
+    PyObject *previous()
+    {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK; // disable threads       
+      decr();
+      PyObject *obj = value();
+      SWIG_PYTHON_THREAD_END_BLOCK; // re-enable threads       
+      return obj;
+    }
+
+    PySwigIterator *advance(ptrdiff_t n)
+    {
+      return  (n > 0) ?  incr(n) : decr(-n);
+    }
+      
+    bool operator == (const PySwigIterator& x)  const
+    {
+      return equal(x);
+    }
+      
+    bool operator != (const PySwigIterator& x) const
+    {
+      return ! operator==(x);
+    }
+      
+    PySwigIterator& operator += (ptrdiff_t n)
+    {
+      return *advance(n);
+    }
+
+    PySwigIterator& operator -= (ptrdiff_t n)
+    {
+      return *advance(-n);
+    }
+      
+    PySwigIterator* operator + (ptrdiff_t n) const
+    {
+      return copy()->advance(n);
+    }
+
+    PySwigIterator* operator - (ptrdiff_t n) const
+    {
+      return copy()->advance(-n);
+    }
+      
+    ptrdiff_t operator - (const PySwigIterator& x) const
+    {
+      return x.distance(*this);
+    }
+      
+    static swig_type_info* descriptor() {
+      static int init = 0;
+      static swig_type_info* desc = 0;
+      if (!init) {
+	desc = SWIG_TypeQuery("swig::PySwigIterator *");
+	init = 1;
+      }	
+      return desc;
+    }    
+  };
+}
+}
+
+%fragment("PySwigIterator_T","header",fragment="PySwigIterator",fragment="StdTraits",fragment="StdIteratorTraits") {
+namespace swig {
+  template<typename OutIterator>
+  class PySwigIterator_T :  public PySwigIterator
+  {
+  public:
+    typedef OutIterator out_iterator;
+    typedef typename std::iterator_traits<out_iterator>::value_type value_type;    
+    typedef PySwigIterator_T<out_iterator> self_type;
+
+    PySwigIterator_T(out_iterator curr, PyObject *seq)
+      : PySwigIterator(seq), current(curr)
+    {
+    }
+
+    const out_iterator& get_current() const
+    {
+      return current;
+    }
+
+    
+    bool equal (const PySwigIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return (current == iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }
+    
+    ptrdiff_t distance(const PySwigIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return std::distance(current, iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }    
+    
+  protected:
+    out_iterator current;
+  };
+  
+  template <class ValueType>
+  struct from_oper 
+  {
+    typedef const ValueType& argument_type;
+    typedef PyObject *result_type;
+    result_type operator()(argument_type v) const
+    {
+      return swig::from(v);
+    }
+  };
+
+  template<typename OutIterator, 
+	   typename ValueType = typename std::iterator_traits<OutIterator>::value_type,
+	   typename FromOper = from_oper<ValueType> >
+  class PySwigIteratorOpen_T :  public PySwigIterator_T<OutIterator>
+  {
+  public:
+    FromOper from;
+    typedef OutIterator out_iterator;
+    typedef ValueType value_type;
+    typedef PySwigIterator_T<out_iterator>  base;
+    typedef PySwigIteratorOpen_T<OutIterator, ValueType, FromOper> self_type;
+    
+    PySwigIteratorOpen_T(out_iterator curr, PyObject *seq)
+      : PySwigIterator_T<OutIterator>(curr, seq)
+    {
+    }
+    
+    PyObject *value() const {
+      return from(static_cast<const value_type&>(*(base::current)));
+    }
+    
+    PySwigIterator *copy() const
+    {
+      return new self_type(*this);
+    }
+
+    PySwigIterator *incr(size_t n = 1)
+    {
+      while (n--) {
+	++base::current;
+      }
+      return this;
+    }
+
+    PySwigIterator *decr(size_t n = 1)
+    {
+      while (n--) {
+	--base::current;
+      }
+      return this;
+    }
+  };
+
+  template<typename OutIterator, 
+	   typename ValueType = typename std::iterator_traits<OutIterator>::value_type,
+	   typename FromOper = from_oper<ValueType> >
+  class PySwigIteratorClosed_T :  public PySwigIterator_T<OutIterator>
+  {
+  public:
+    FromOper from;
+    typedef OutIterator out_iterator;
+    typedef ValueType value_type;
+    typedef PySwigIterator_T<out_iterator>  base;    
+    typedef PySwigIteratorClosed_T<OutIterator, ValueType, FromOper> self_type;
+    
+    PySwigIteratorClosed_T(out_iterator curr, out_iterator first, out_iterator last, PyObject *seq)
+      : PySwigIterator_T<OutIterator>(curr, seq), begin(first), end(last)
+    {
+    }
+    
+    PyObject *value() const {
+      if (base::current == end) {
+	throw stop_iteration();
+      } else {
+	return from(static_cast<const value_type&>(*(base::current)));
+      }
+    }
+    
+    PySwigIterator *copy() const
+    {
+      return new self_type(*this);
+    }
+
+    PySwigIterator *incr(size_t n = 1)
+    {
+      while (n--) {
+	if (base::current == end) {
+	  throw stop_iteration();
+	} else {
+	  ++base::current;
+	}
+      }
+      return this;
+    }
+
+    PySwigIterator *decr(size_t n = 1)
+    {
+      while (n--) {
+	if (base::current == begin) {
+	  throw stop_iteration();
+	} else {
+	  --base::current;
+	}
+      }
+      return this;
+    }
+
+  private:
+    out_iterator begin;
+    out_iterator end;
+  };
+
+  template<typename OutIter>
+  inline PySwigIterator*
+  make_output_iterator(const OutIter& current, const OutIter& begin,const OutIter& end, PyObject *seq = 0)
+  {
+    return new PySwigIteratorClosed_T<OutIter>(current, begin, end, seq);
+  }
+
+  template<typename OutIter>
+  inline PySwigIterator*
+  make_output_iterator(const OutIter& current, PyObject *seq = 0)
+  {
+    return new PySwigIteratorOpen_T<OutIter>(current, seq);
+  }
+}
+}
+
+
+%fragment("PySwigIterator");
+namespace swig 
+{
+  /*
+    Throw a StopIteration exception
+  */
+  %ignore stop_iteration;
+  struct stop_iteration {};
+  
+  %typemap(throws) stop_iteration {
+    (void)$1;
+    SWIG_SetErrorObj(PyExc_StopIteration, SWIG_Py_Void());
+    SWIG_fail;
+  }
+
+  /* 
+     Mark methods that return new objects
+  */
+  %newobject PySwigIterator::copy;
+  %newobject PySwigIterator::operator + (ptrdiff_t n) const;
+  %newobject PySwigIterator::operator - (ptrdiff_t n) const;
+
+  %nodirector PySwigIterator;
+  %extend PySwigIterator {
+  %pythoncode {def __iter__(self): return self}
+  }
+
+  %catches(swig::stop_iteration) PySwigIterator::value() const;
+  %catches(swig::stop_iteration) PySwigIterator::incr(size_t n = 1);
+  %catches(swig::stop_iteration) PySwigIterator::decr(size_t n = 1);
+  %catches(std::invalid_argument) PySwigIterator::distance(const PySwigIterator &x) const;
+  %catches(std::invalid_argument) PySwigIterator::equal (const PySwigIterator &x) const;
+  %catches(swig::stop_iteration) PySwigIterator::next();
+  %catches(swig::stop_iteration) PySwigIterator::previous();
+  %catches(swig::stop_iteration) PySwigIterator::advance(ptrdiff_t n);
+  %catches(swig::stop_iteration) PySwigIterator::operator += (ptrdiff_t n);
+  %catches(swig::stop_iteration) PySwigIterator::operator -= (ptrdiff_t n);
+  %catches(swig::stop_iteration) PySwigIterator::operator + (ptrdiff_t n) const;
+  %catches(swig::stop_iteration) PySwigIterator::operator - (ptrdiff_t n) const;
+
+
+  struct PySwigIterator
+  {
+  protected:
+    PySwigIterator(PyObject *seq);
+
+  public:
+    virtual ~PySwigIterator();
+
+    // Access iterator method, required by Python
+    virtual PyObject *value() const = 0;
+
+    // Forward iterator method, required by Python
+    virtual PySwigIterator *incr(size_t n = 1) = 0;
+    
+    // Backward iterator method, very common in C++, but not required in Python
+    virtual PySwigIterator *decr(size_t n = 1);
+
+    // Random access iterator methods, but not required in Python
+    virtual ptrdiff_t distance(const PySwigIterator &x) const;
+
+    virtual bool equal (const PySwigIterator &x) const;
+    
+    // C++ common/needed methods
+    virtual PySwigIterator *copy() const = 0;
+
+    PyObject *next();
+    PyObject *previous();
+    PySwigIterator *advance(ptrdiff_t n);
+
+    bool operator == (const PySwigIterator& x)  const;
+    bool operator != (const PySwigIterator& x) const;
+    PySwigIterator& operator += (ptrdiff_t n);
+    PySwigIterator& operator -= (ptrdiff_t n);
+    PySwigIterator* operator + (ptrdiff_t n) const;
+    PySwigIterator* operator - (ptrdiff_t n) const;
+    ptrdiff_t operator - (const PySwigIterator& x) const;
+  };
+}
+
diff --git a/trunk/Lib/python/pymacros.swg b/trunk/Lib/python/pymacros.swg
new file mode 100644
index 0000000..ab7bace
--- /dev/null
+++ b/trunk/Lib/python/pymacros.swg
@@ -0,0 +1,4 @@
+%include <typemaps/swigmacros.swg>
+
+
+
diff --git a/trunk/Lib/python/pyopers.swg b/trunk/Lib/python/pyopers.swg
new file mode 100644
index 0000000..76f1e67
--- /dev/null
+++ b/trunk/Lib/python/pyopers.swg
@@ -0,0 +1,130 @@
+/* ------------------------------------------------------------
+ * Overloaded operator support
+ * ------------------------------------------------------------ */
+
+
+#ifdef __cplusplus
+
+#define %pybinoperator(pyname,oper) %rename(pyname) oper; %pythonmaybecall oper
+
+%pybinoperator(__add__,      *::operator+);
+%pybinoperator(__pos__,      *::operator+());
+%pybinoperator(__pos__,      *::operator+() const);
+%pybinoperator(__sub__,      *::operator-);
+%pybinoperator(__neg__,      *::operator-());
+%pybinoperator(__neg__,      *::operator-() const);
+%pybinoperator(__mul__,      *::operator*);
+%pybinoperator(__div__,      *::operator/);
+%pybinoperator(__mod__,      *::operator%);
+%pybinoperator(__lshift__,   *::operator<<);
+%pybinoperator(__rshift__,   *::operator>>);
+%pybinoperator(__and__,      *::operator&);
+%pybinoperator(__or__,       *::operator|);
+%pybinoperator(__xor__,      *::operator^);
+%pybinoperator(__lt__,       *::operator<);
+%pybinoperator(__le__,       *::operator<=);
+%pybinoperator(__gt__,       *::operator>);
+%pybinoperator(__ge__,       *::operator>=);
+%pybinoperator(__eq__,       *::operator==);
+%pybinoperator(__ne__,       *::operator!=);
+
+
+
+/* Special cases */
+%rename(__invert__)     *::operator~;
+%rename(__call__)       *::operator();
+%rename(__nonzero__)    *::operator bool;
+
+/* Ignored operators */
+%ignoreoperator(LNOT)       operator!;
+%ignoreoperator(LAND)       operator&&;
+%ignoreoperator(LOR)        operator||;
+%ignoreoperator(EQ)         *::operator=;
+%ignoreoperator(PLUSPLUS)   *::operator++;
+%ignoreoperator(MINUSMINUS) *::operator--;
+%ignoreoperator(ARROWSTAR)  *::operator->*;
+%ignoreoperator(INDEX)      *::operator[];
+
+/*
+  Inplace operator declarations.
+
+  They translate the inplace C++ operators (+=, -=, ...)  into the
+  corresponding python equivalents(__iadd__,__isub__), etc,
+  disabling the ownership of the input 'self' pointer, and assigning
+  it to the returning object:  
+
+     %feature("del") *::Operator;
+     %feature("new") *::Operator;
+  
+  This makes the most common case safe, ie:
+
+     A&  A::operator+=(int i) { ...; return *this; }
+    ^^^^                                    ^^^^^^
+
+  will work fine, even when the resulting python object shares the
+  'this' pointer with the input one. The input object is usually
+  deleted after the operation, including the shared 'this' pointer,
+  producing 'strange' seg faults, as reported by Lucriz
+  (lucriz@sitilandia.it).
+
+  If you have an interface that already takes care of that, ie, you
+  already are using inplace operators and you are not getting
+  seg. faults, with the new scheme you could end with 'free' elements
+  that never get deleted (maybe, not sure, it depends). But if that is
+  the case, you could recover the old behaviour using
+
+     %feature("del","") A::operator+=;
+     %feature("new","") A::operator+=;
+
+  which recovers the old behaviour for the class 'A', or if you are
+  100% sure your entire system works fine in the old way, use:
+
+    %feature("del","") *::operator+=;
+    %feature("new","") *::operator+=;
+
+*/
+
+#define %pyinplaceoper(PyOper, Oper) %delobject Oper; %newobject Oper; %rename(PyOper) Oper
+
+%pyinplaceoper(__iadd__   , *::operator +=);
+%pyinplaceoper(__isub__   , *::operator -=);
+%pyinplaceoper(__imul__   , *::operator *=);
+%pyinplaceoper(__idiv__   , *::operator /=);
+%pyinplaceoper(__imod__   , *::operator %=);
+%pyinplaceoper(__iand__   , *::operator &=);
+%pyinplaceoper(__ior__    , *::operator |=);
+%pyinplaceoper(__ixor__   , *::operator ^=);
+%pyinplaceoper(__ilshift__, *::operator <<=);
+%pyinplaceoper(__irshift__, *::operator >>=);
+
+
+/* Finally, in python we need to mark the binary operations to fail as
+ 'maybecall' methods */
+
+#define %pybinopermaybecall(oper) %pythonmaybecall __ ## oper ## __;  %pythonmaybecall __r ## oper ## __
+
+%pybinopermaybecall(add);
+%pybinopermaybecall(pos);
+%pybinopermaybecall(pos);
+%pybinopermaybecall(sub);
+%pybinopermaybecall(neg);
+%pybinopermaybecall(neg);
+%pybinopermaybecall(mul);
+%pybinopermaybecall(div);
+%pybinopermaybecall(mod);
+%pybinopermaybecall(lshift);
+%pybinopermaybecall(rshift);
+%pybinopermaybecall(and);
+%pybinopermaybecall(or);
+%pybinopermaybecall(xor);
+%pybinopermaybecall(lt);
+%pybinopermaybecall(le);
+%pybinopermaybecall(gt);
+%pybinopermaybecall(ge);
+%pybinopermaybecall(eq);
+%pybinopermaybecall(ne);
+
+#endif
+
+
+
diff --git a/trunk/Lib/python/pyprimtypes.swg b/trunk/Lib/python/pyprimtypes.swg
new file mode 100644
index 0000000..63435ee
--- /dev/null
+++ b/trunk/Lib/python/pyprimtypes.swg
@@ -0,0 +1,292 @@
+/* ------------------------------------------------------------
+ * Primitive Types
+ * ------------------------------------------------------------ */
+
+/* boolean */
+
+%fragment(SWIG_From_frag(bool),"header") {
+SWIGINTERNINLINE PyObject*
+  SWIG_From_dec(bool)(bool value)
+{
+  return PyBool_FromLong(value ? 1 : 0);
+}
+}
+
+%fragment(SWIG_AsVal_frag(bool),"header",
+	  fragment=SWIG_AsVal_frag(long)) {
+SWIGINTERN int
+SWIG_AsVal_dec(bool)(PyObject *obj, bool *val)
+{
+  int r = PyObject_IsTrue(obj);
+  if (r == -1)
+    return SWIG_ERROR;
+  if (val) *val = r ? true : false;
+  return SWIG_OK;
+}
+}
+
+/* long */
+
+%fragment(SWIG_From_frag(long),"header") {
+  %define_as(SWIG_From_dec(long),           PyInt_FromLong)
+}
+
+%fragment(SWIG_AsVal_frag(long),"header",
+	  fragment="SWIG_CanCastAsInteger") {
+SWIGINTERN int
+SWIG_AsVal_dec(long)(PyObject *obj, long* val)
+{
+  if (PyInt_Check(obj)) {
+    if (val) *val = PyInt_AsLong(obj);
+    return SWIG_OK;
+  } else if (PyLong_Check(obj)) {
+    long v = PyLong_AsLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+%#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    long v = PyInt_AsLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) {
+	if (val) *val = (long)(d);
+	return res;
+      }
+    }
+  }
+%#endif
+  return SWIG_TypeError;
+}
+}
+
+/* unsigned long */
+
+%fragment(SWIG_From_frag(unsigned long),"header",
+	  fragment=SWIG_From_frag(long)) {
+SWIGINTERNINLINE PyObject* 
+SWIG_From_dec(unsigned long)(unsigned long value)
+{
+  return (value > LONG_MAX) ?
+    PyLong_FromUnsignedLong(value) : PyInt_FromLong(%numeric_cast(value,long)); 
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long),"header",
+	  fragment="SWIG_CanCastAsInteger") {
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long)(PyObject *obj, unsigned long *val) 
+{
+  if (PyInt_Check(obj)) {
+    long v = PyInt_AsLong(obj);
+    if (v >= 0) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }
+  } else if (PyLong_Check(obj)) {
+    unsigned long v = PyLong_AsUnsignedLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+%#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    unsigned long v = PyLong_AsUnsignedLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) {
+	if (val) *val = (unsigned long)(d);
+	return res;
+      }
+    }
+  }
+%#endif
+  return SWIG_TypeError;
+}
+}
+
+/* long long */
+
+%fragment(SWIG_From_frag(long long),"header",
+	  fragment=SWIG_From_frag(long),
+	  fragment="<limits.h>") {
+SWIGINTERNINLINE PyObject* 
+SWIG_From_dec(long long)(long long value)
+{
+  return ((value < LONG_MIN) || (value > LONG_MAX)) ?
+    PyLong_FromLongLong(value) : PyInt_FromLong(%numeric_cast(value,long)); 
+}
+}
+
+%fragment(SWIG_AsVal_frag(long long),"header",
+	  fragment=SWIG_AsVal_frag(long),
+	  fragment="SWIG_CanCastAsInteger",
+	  fragment="<limits.h>") {
+SWIGINTERN int
+SWIG_AsVal_dec(long long)(PyObject *obj, long long *val)
+{
+  int res = SWIG_TypeError;
+  if (PyLong_Check(obj)) {
+    long long v = PyLong_AsLongLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  } else {
+    long v;
+    res = SWIG_AsVal(long)(obj,&v);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = v;
+      return res;
+    }
+  }
+%#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    const double mant_max = 1LL << DBL_MANT_DIG;
+    const double mant_min = -mant_max;
+    double d;
+    res = SWIG_AsVal(double)(obj,&d);
+    if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, mant_min, mant_max)) {
+      if (val) *val = (long long)(d);
+      return SWIG_AddCast(res);
+    }
+    res = SWIG_TypeError;
+  }
+%#endif
+  return res;
+}
+}
+
+/* unsigned long long */
+
+%fragment(SWIG_From_frag(unsigned long long),"header",
+	  fragment=SWIG_From_frag(long long),
+	  fragment="<limits.h>") {
+SWIGINTERNINLINE PyObject* 
+SWIG_From_dec(unsigned long long)(unsigned long long value)
+{
+  return (value > LONG_MAX) ?
+    PyLong_FromUnsignedLongLong(value) : PyInt_FromLong(%numeric_cast(value,long)); 
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long long),"header",
+	  fragment=SWIG_AsVal_frag(unsigned long),
+	  fragment="SWIG_CanCastAsInteger",
+	  fragment="<limits.h>") {
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long long)(PyObject *obj, unsigned long long *val)
+{
+  int res = SWIG_TypeError;
+  if (PyLong_Check(obj)) {
+    unsigned long long v = PyLong_AsUnsignedLongLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  } else {
+    unsigned long v;
+    res = SWIG_AsVal(unsigned long)(obj,&v);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = v;
+      return res;
+    }
+  }
+%#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    const double mant_max = 1LL << DBL_MANT_DIG;
+    double d;
+    res = SWIG_AsVal(double)(obj,&d);
+    if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, mant_max)) {
+      if (val) *val = (unsigned long long)(d);
+      return SWIG_AddCast(res);
+    }
+    res = SWIG_TypeError;
+  }
+%#endif
+  return res;
+}
+}
+
+/* double */
+
+%fragment(SWIG_From_frag(double),"header") {
+  %define_as(SWIG_From_dec(double),          PyFloat_FromDouble)
+}
+
+%fragment(SWIG_AsVal_frag(double),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(double)(PyObject *obj, double *val)
+{
+  int res = SWIG_TypeError;
+  if (PyFloat_Check(obj)) {
+    if (val) *val = PyFloat_AsDouble(obj);
+    return SWIG_OK;
+  } else if (PyInt_Check(obj)) {
+    if (val) *val = PyInt_AsLong(obj);
+    return SWIG_OK;
+  } else if (PyLong_Check(obj)) {
+    double v = PyLong_AsDouble(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+%#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    double d = PyFloat_AsDouble(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = d;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      long v = PyLong_AsLong(obj);
+      if (!PyErr_Occurred()) {
+	if (val) *val = v;
+	return SWIG_AddCast(SWIG_AddCast(SWIG_OK));
+      } else {
+	PyErr_Clear();
+      }
+    }
+  }
+%#endif
+  return res;
+}
+}
+
+
+
diff --git a/trunk/Lib/python/pyrun.swg b/trunk/Lib/python/pyrun.swg
new file mode 100644
index 0000000..844a66b
--- /dev/null
+++ b/trunk/Lib/python/pyrun.swg
@@ -0,0 +1,1496 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pyrun.swg
+ *
+ * This file contains the runtime support for Python modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ *
+ * ----------------------------------------------------------------------------- */
+
+/* Common SWIG API */
+
+/* for raw pointers */
+#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(ptr, type, flags)
+#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) 
+#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)
+#define swig_owntype                                    int
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)
+
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(ptr, type, 0)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule()
+#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)
+#define SWIG_NewClientData(obj)                         PySwigClientData_New(obj)
+
+#define SWIG_SetErrorObj                                SWIG_Python_SetErrorObj                            
+#define SWIG_SetErrorMsg                        	SWIG_Python_SetErrorMsg				   
+#define SWIG_ErrorType(code)                    	SWIG_Python_ErrorType(code)                        
+#define SWIG_Error(code, msg)            		SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) 
+#define SWIG_fail                        		goto fail					   
+
+
+/* Runtime API implementation */
+
+/* Error manipulation */
+
+SWIGINTERN void 
+SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) {
+  SWIG_PYTHON_THREAD_BEGIN_BLOCK; 
+  PyErr_SetObject(errtype, obj);
+  Py_DECREF(obj);
+  SWIG_PYTHON_THREAD_END_BLOCK;
+}
+
+SWIGINTERN void 
+SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) {
+  SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+  PyErr_SetString(errtype, (char *) msg);
+  SWIG_PYTHON_THREAD_END_BLOCK;
+}
+
+#define SWIG_Python_Raise(obj, type, desc)  SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj)
+
+/* Set a constant value */
+
+SWIGINTERN void
+SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) {   
+  PyDict_SetItemString(d, (char*) name, obj);
+  Py_DECREF(obj);                            
+}
+
+/* Append a value to the result obj */
+
+SWIGINTERN PyObject*
+SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) {
+#if !defined(SWIG_PYTHON_OUTPUT_TUPLE)
+  if (!result) {
+    result = obj;
+  } else if (result == Py_None) {
+    Py_DECREF(result);
+    result = obj;
+  } else {
+    if (!PyList_Check(result)) {
+      PyObject *o2 = result;
+      result = PyList_New(1);
+      PyList_SetItem(result, 0, o2);
+    }
+    PyList_Append(result,obj);
+    Py_DECREF(obj);
+  }
+  return result;
+#else
+  PyObject*   o2;
+  PyObject*   o3;
+  if (!result) {
+    result = obj;
+  } else if (result == Py_None) {
+    Py_DECREF(result);
+    result = obj;
+  } else {
+    if (!PyTuple_Check(result)) {
+      o2 = result;
+      result = PyTuple_New(1);
+      PyTuple_SET_ITEM(result, 0, o2);
+    }
+    o3 = PyTuple_New(1);
+    PyTuple_SET_ITEM(o3, 0, obj);
+    o2 = result;
+    result = PySequence_Concat(o2, o3);
+    Py_DECREF(o2);
+    Py_DECREF(o3);
+  }
+  return result;
+#endif
+}
+
+/* Unpack the argument tuple */
+
+SWIGINTERN int
+SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs)
+{
+  if (!args) {
+    if (!min && !max) {
+      return 1;
+    } else {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", 
+		   name, (min == max ? "" : "at least "), (int)min);
+      return 0;
+    }
+  }  
+  if (!PyTuple_Check(args)) {
+    PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple");
+    return 0;
+  } else {
+    register Py_ssize_t l = PyTuple_GET_SIZE(args);
+    if (l < min) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+		   name, (min == max ? "" : "at least "), (int)min, (int)l);
+      return 0;
+    } else if (l > max) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+		   name, (min == max ? "" : "at most "), (int)max, (int)l);
+      return 0;
+    } else {
+      register int i;
+      for (i = 0; i < l; ++i) {
+	objs[i] = PyTuple_GET_ITEM(args, i);
+      }
+      for (; l < max; ++l) {
+	objs[l] = 0;
+      }
+      return i + 1;
+    }    
+  }
+}
+
+/* A functor is a function object with one single object argument */
+#if PY_VERSION_HEX >= 0x02020000
+#define SWIG_Python_CallFunctor(functor, obj)	        PyObject_CallFunctionObjArgs(functor, obj, NULL);
+#else
+#define SWIG_Python_CallFunctor(functor, obj)	        PyObject_CallFunction(functor, "O", obj);
+#endif
+
+/*
+  Helper for static pointer initialization for both C and C++ code, for example
+  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);
+*/
+#ifdef __cplusplus
+#define SWIG_STATIC_POINTER(var)  var
+#else
+#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Pointer declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)
+#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)
+
+#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* cc-mode */
+#endif
+#endif
+
+/*  How to access Py_None */
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#  ifndef SWIG_PYTHON_NO_BUILD_NONE
+#    ifndef SWIG_PYTHON_BUILD_NONE
+#      define SWIG_PYTHON_BUILD_NONE
+#    endif
+#  endif
+#endif
+
+#ifdef SWIG_PYTHON_BUILD_NONE
+#  ifdef Py_None
+#   undef Py_None
+#   define Py_None SWIG_Py_None()
+#  endif
+SWIGRUNTIMEINLINE PyObject * 
+_SWIG_Py_None(void)
+{
+  PyObject *none = Py_BuildValue((char*)"");
+  Py_DECREF(none);
+  return none;
+}
+SWIGRUNTIME PyObject * 
+SWIG_Py_None(void)
+{
+  static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None();
+  return none;
+}
+#endif
+
+/* The python void return value */
+
+SWIGRUNTIMEINLINE PyObject * 
+SWIG_Py_Void(void)
+{
+  PyObject *none = Py_None;
+  Py_INCREF(none);
+  return none;
+}
+
+/* PySwigClientData */
+
+typedef struct {
+  PyObject *klass;
+  PyObject *newraw;
+  PyObject *newargs;
+  PyObject *destroy;
+  int delargs;
+  int implicitconv;
+} PySwigClientData;
+
+SWIGRUNTIMEINLINE int 
+SWIG_Python_CheckImplicit(swig_type_info *ty)
+{
+  PySwigClientData *data = (PySwigClientData *)ty->clientdata;
+  return data ? data->implicitconv : 0;
+}
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_ExceptionType(swig_type_info *desc) {
+  PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0;
+  PyObject *klass = data ? data->klass : 0;
+  return (klass ? klass : PyExc_RuntimeError);
+}
+
+
+SWIGRUNTIME PySwigClientData * 
+PySwigClientData_New(PyObject* obj)
+{
+  if (!obj) {
+    return 0;
+  } else {
+    PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData));
+    /* the klass element */
+    data->klass = obj;
+    Py_INCREF(data->klass);
+    /* the newraw method and newargs arguments used to create a new raw instance */
+    if (PyClass_Check(obj)) {
+      data->newraw = 0;
+      data->newargs = obj;
+      Py_INCREF(obj);
+    } else {
+#if (PY_VERSION_HEX < 0x02020000)
+      data->newraw = 0;
+#else
+      data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__");
+#endif
+      if (data->newraw) {
+	Py_INCREF(data->newraw);
+	data->newargs = PyTuple_New(1);
+	PyTuple_SetItem(data->newargs, 0, obj);
+      } else {
+	data->newargs = obj;
+      }
+      Py_INCREF(data->newargs);
+    }
+    /* the destroy method, aka as the C++ delete method */
+    data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__");
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      data->destroy = 0;
+    }
+    if (data->destroy) {
+      int flags;
+      Py_INCREF(data->destroy);
+      flags = PyCFunction_GET_FLAGS(data->destroy);
+#ifdef METH_O
+      data->delargs = !(flags & (METH_O));
+#else
+      data->delargs = 0;
+#endif
+    } else {
+      data->delargs = 0;
+    }
+    data->implicitconv = 0;
+    return data;
+  }
+}
+
+SWIGRUNTIME void 
+PySwigClientData_Del(PySwigClientData* data)
+{
+  Py_XDECREF(data->newraw);
+  Py_XDECREF(data->newargs);
+  Py_XDECREF(data->destroy);
+}
+
+/* =============== PySwigObject =====================*/
+
+typedef struct {
+  PyObject_HEAD
+  void *ptr;
+  swig_type_info *ty;
+  int own;
+  PyObject *next;
+} PySwigObject;
+
+SWIGRUNTIME PyObject *
+PySwigObject_long(PySwigObject *v)
+{
+  return PyLong_FromVoidPtr(v->ptr);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_format(const char* fmt, PySwigObject *v)
+{
+  PyObject *res = NULL;
+  PyObject *args = PyTuple_New(1);
+  if (args) {
+    if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) {
+      PyObject *ofmt = PyString_FromString(fmt);
+      if (ofmt) {
+	res = PyString_Format(ofmt,args);
+	Py_DECREF(ofmt);
+      }
+      Py_DECREF(args);
+    }
+  }
+  return res;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_oct(PySwigObject *v)
+{
+  return PySwigObject_format("%o",v);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_hex(PySwigObject *v)
+{
+  return PySwigObject_format("%x",v);
+}
+
+SWIGRUNTIME PyObject *
+#ifdef METH_NOARGS
+PySwigObject_repr(PySwigObject *v)
+#else
+PySwigObject_repr(PySwigObject *v, PyObject *args)
+#endif
+{
+  const char *name = SWIG_TypePrettyName(v->ty);
+  PyObject *hex = PySwigObject_hex(v);    
+  PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex));
+  Py_DECREF(hex);
+  if (v->next) {
+#ifdef METH_NOARGS
+    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next);
+#else
+    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args);
+#endif
+    PyString_ConcatAndDel(&repr,nrep);
+  }
+  return repr;  
+}
+
+SWIGRUNTIME int
+PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags))
+{
+#ifdef METH_NOARGS
+  PyObject *repr = PySwigObject_repr(v);
+#else
+  PyObject *repr = PySwigObject_repr(v, NULL);
+#endif
+  if (repr) {
+    fputs(PyString_AsString(repr), fp);
+    Py_DECREF(repr);
+    return 0; 
+  } else {
+    return 1; 
+  }
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_str(PySwigObject *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ?
+    PyString_FromString(result) : 0;
+}
+
+SWIGRUNTIME int
+PySwigObject_compare(PySwigObject *v, PySwigObject *w)
+{
+  void *i = v->ptr;
+  void *j = w->ptr;
+  return (i < j) ? -1 : ((i > j) ? 1 : 0);
+}
+
+SWIGRUNTIME PyTypeObject* _PySwigObject_type(void);
+
+SWIGRUNTIME PyTypeObject*
+PySwigObject_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigObject_Check(PyObject *op) {
+  return ((op)->ob_type == PySwigObject_type())
+    || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_New(void *ptr, swig_type_info *ty, int own);
+
+SWIGRUNTIME void
+PySwigObject_dealloc(PyObject *v)
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+  PyObject *next = sobj->next;
+  if (sobj->own == SWIG_POINTER_OWN) {
+    swig_type_info *ty = sobj->ty;
+    PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;
+    PyObject *destroy = data ? data->destroy : 0;
+    if (destroy) {
+      /* destroy is always a VARARGS method */
+      PyObject *res;
+      if (data->delargs) {
+	/* we need to create a temporal object to carry the destroy operation */
+	PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0);
+	res = SWIG_Python_CallFunctor(destroy, tmp);
+	Py_DECREF(tmp);
+      } else {
+	PyCFunction meth = PyCFunction_GET_FUNCTION(destroy);
+	PyObject *mself = PyCFunction_GET_SELF(destroy);
+	res = ((*meth)(mself, v));
+      }
+      Py_XDECREF(res);
+    } 
+#if !defined(SWIG_PYTHON_SILENT_MEMLEAK)
+    else {
+      const char *name = SWIG_TypePrettyName(ty);
+      printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown"));
+    }
+#endif
+  } 
+  Py_XDECREF(next);
+  PyObject_DEL(v);
+}
+
+SWIGRUNTIME PyObject* 
+PySwigObject_append(PyObject* v, PyObject* next)
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+#ifndef METH_O
+  PyObject *tmp = 0;
+  if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL;
+  next = tmp;
+#endif
+  if (!PySwigObject_Check(next)) {
+    return NULL;
+  }
+  sobj->next = next;
+  Py_INCREF(next);
+  return SWIG_Py_Void();
+}
+
+SWIGRUNTIME PyObject* 
+#ifdef METH_NOARGS
+PySwigObject_next(PyObject* v)
+#else
+PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+  if (sobj->next) {    
+    Py_INCREF(sobj->next);
+    return sobj->next;
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+
+SWIGINTERN PyObject*
+#ifdef METH_NOARGS
+PySwigObject_disown(PyObject *v)
+#else
+PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *)v;
+  sobj->own = 0;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+#ifdef METH_NOARGS
+PySwigObject_acquire(PyObject *v)
+#else
+PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *)v;
+  sobj->own = SWIG_POINTER_OWN;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+PySwigObject_own(PyObject *v, PyObject *args)
+{
+  PyObject *val = 0;
+#if (PY_VERSION_HEX < 0x02020000)
+  if (!PyArg_ParseTuple(args,(char *)"|O:own",&val))
+#else
+  if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) 
+#endif
+    {
+      return NULL;
+    } 
+  else
+    {
+      PySwigObject *sobj = (PySwigObject *)v;
+      PyObject *obj = PyBool_FromLong(sobj->own);
+      if (val) {
+#ifdef METH_NOARGS
+	if (PyObject_IsTrue(val)) {
+	  PySwigObject_acquire(v);
+	} else {
+	  PySwigObject_disown(v);
+	}
+#else
+	if (PyObject_IsTrue(val)) {
+	  PySwigObject_acquire(v,args);
+	} else {
+	  PySwigObject_disown(v,args);
+	}
+#endif
+      } 
+      return obj;
+    }
+}
+
+#ifdef METH_O
+static PyMethodDef
+swigobject_methods[] = {
+  {(char *)"disown",  (PyCFunction)PySwigObject_disown,  METH_NOARGS,  (char *)"releases ownership of the pointer"},
+  {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS,  (char *)"aquires ownership of the pointer"},
+  {(char *)"own",     (PyCFunction)PySwigObject_own,     METH_VARARGS, (char *)"returns/sets ownership of the pointer"},
+  {(char *)"append",  (PyCFunction)PySwigObject_append,  METH_O,       (char *)"appends another 'this' object"},
+  {(char *)"next",    (PyCFunction)PySwigObject_next,    METH_NOARGS,  (char *)"returns the next 'this' object"},
+  {(char *)"__repr__",(PyCFunction)PySwigObject_repr,    METH_NOARGS,  (char *)"returns object representation"},
+  {0, 0, 0, 0}  
+};
+#else
+static PyMethodDef
+swigobject_methods[] = {
+  {(char *)"disown",  (PyCFunction)PySwigObject_disown,  METH_VARARGS,  (char *)"releases ownership of the pointer"},
+  {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS,  (char *)"aquires ownership of the pointer"},
+  {(char *)"own",     (PyCFunction)PySwigObject_own,     METH_VARARGS,  (char *)"returns/sets ownership of the pointer"},
+  {(char *)"append",  (PyCFunction)PySwigObject_append,  METH_VARARGS,  (char *)"appends another 'this' object"},
+  {(char *)"next",    (PyCFunction)PySwigObject_next,    METH_VARARGS,  (char *)"returns the next 'this' object"},
+  {(char *)"__repr__",(PyCFunction)PySwigObject_repr,   METH_VARARGS,  (char *)"returns object representation"},
+  {0, 0, 0, 0}  
+};
+#endif
+
+#if PY_VERSION_HEX < 0x02020000
+SWIGINTERN PyObject *
+PySwigObject_getattr(PySwigObject *sobj,char *name)
+{
+  return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name);
+}
+#endif
+
+SWIGRUNTIME PyTypeObject*
+_PySwigObject_type(void) {
+  static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer";
+  
+  static PyNumberMethods PySwigObject_as_number = {
+    (binaryfunc)0, /*nb_add*/
+    (binaryfunc)0, /*nb_subtract*/
+    (binaryfunc)0, /*nb_multiply*/
+    (binaryfunc)0, /*nb_divide*/
+    (binaryfunc)0, /*nb_remainder*/
+    (binaryfunc)0, /*nb_divmod*/
+    (ternaryfunc)0,/*nb_power*/
+    (unaryfunc)0,  /*nb_negative*/
+    (unaryfunc)0,  /*nb_positive*/
+    (unaryfunc)0,  /*nb_absolute*/
+    (inquiry)0,    /*nb_nonzero*/
+    0,		   /*nb_invert*/
+    0,		   /*nb_lshift*/
+    0,		   /*nb_rshift*/
+    0,		   /*nb_and*/
+    0,		   /*nb_xor*/
+    0,		   /*nb_or*/
+    (coercion)0,   /*nb_coerce*/
+    (unaryfunc)PySwigObject_long, /*nb_int*/
+    (unaryfunc)PySwigObject_long, /*nb_long*/
+    (unaryfunc)0,                 /*nb_float*/
+    (unaryfunc)PySwigObject_oct,  /*nb_oct*/
+    (unaryfunc)PySwigObject_hex,  /*nb_hex*/
+#if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */
+#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */
+#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */
+    0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */
+#endif
+  };
+
+  static PyTypeObject pyswigobject_type;  
+  static int type_init = 0;
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+	PyObject_HEAD_INIT(NULL)
+	0,				    /* ob_size */
+	(char *)"PySwigObject",		    /* tp_name */
+	sizeof(PySwigObject),		    /* tp_basicsize */
+	0,			            /* tp_itemsize */
+	(destructor)PySwigObject_dealloc,   /* tp_dealloc */
+	(printfunc)PySwigObject_print,	    /* tp_print */
+#if PY_VERSION_HEX < 0x02020000
+	(getattrfunc)PySwigObject_getattr,  /* tp_getattr */ 
+#else
+	(getattrfunc)0,			    /* tp_getattr */ 
+#endif
+	(setattrfunc)0,			    /* tp_setattr */ 
+	(cmpfunc)PySwigObject_compare,	    /* tp_compare */ 
+	(reprfunc)PySwigObject_repr,	    /* tp_repr */    
+	&PySwigObject_as_number,	    /* tp_as_number */
+	0,				    /* tp_as_sequence */
+	0,				    /* tp_as_mapping */
+	(hashfunc)0,			    /* tp_hash */
+	(ternaryfunc)0,			    /* tp_call */
+	(reprfunc)PySwigObject_str,	    /* tp_str */
+	PyObject_GenericGetAttr,            /* tp_getattro */
+	0,				    /* tp_setattro */
+	0,		                    /* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,	            /* tp_flags */
+	swigobject_doc, 	            /* tp_doc */        
+	0,                                  /* tp_traverse */
+	0,                                  /* tp_clear */
+	0,                                  /* tp_richcompare */
+	0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+	0,                                  /* tp_iter */
+	0,                                  /* tp_iternext */
+	swigobject_methods,		    /* tp_methods */ 
+	0,			            /* tp_members */
+	0,				    /* tp_getset */	    	
+	0,			            /* tp_base */	        
+	0,				    /* tp_dict */	    	
+	0,				    /* tp_descr_get */  	
+	0,				    /* tp_descr_set */  	
+	0,				    /* tp_dictoffset */ 	
+	0,				    /* tp_init */	    	
+	0,				    /* tp_alloc */	    	
+	0,			            /* tp_new */	    	
+	0,	                            /* tp_free */	   
+        0,                                  /* tp_is_gc */  
+	0,				    /* tp_bases */   
+	0,				    /* tp_mro */
+	0,				    /* tp_cache */   
+ 	0,				    /* tp_subclasses */
+	0,				    /* tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+	0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+	0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+    pyswigobject_type = tmp;
+    pyswigobject_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &pyswigobject_type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_New(void *ptr, swig_type_info *ty, int own)
+{
+  PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type());
+  if (sobj) {
+    sobj->ptr  = ptr;
+    sobj->ty   = ty;
+    sobj->own  = own;
+    sobj->next = 0;
+  }
+  return (PyObject *)sobj;
+}
+
+/* -----------------------------------------------------------------------------
+ * Implements a simple Swig Packed type, and use it instead of string
+ * ----------------------------------------------------------------------------- */
+
+typedef struct {
+  PyObject_HEAD
+  void *pack;
+  swig_type_info *ty;
+  size_t size;
+} PySwigPacked;
+
+SWIGRUNTIME int
+PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags))
+{
+  char result[SWIG_BUFFER_SIZE];
+  fputs("<Swig Packed ", fp); 
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    fputs("at ", fp); 
+    fputs(result, fp); 
+  }
+  fputs(v->ty->name,fp); 
+  fputs(">", fp);
+  return 0; 
+}
+  
+SWIGRUNTIME PyObject *
+PySwigPacked_repr(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name);
+  } else {
+    return PyString_FromFormat("<Swig Packed %s>", v->ty->name);
+  }  
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_str(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
+    return PyString_FromFormat("%s%s", result, v->ty->name);
+  } else {
+    return PyString_FromString(v->ty->name);
+  }  
+}
+
+SWIGRUNTIME int
+PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)
+{
+  size_t i = v->size;
+  size_t j = w->size;
+  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
+  return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);
+}
+
+SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void);
+
+SWIGRUNTIME PyTypeObject*
+PySwigPacked_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigPacked_Check(PyObject *op) {
+  return ((op)->ob_type == _PySwigPacked_type()) 
+    || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0);
+}
+
+SWIGRUNTIME void
+PySwigPacked_dealloc(PyObject *v)
+{
+  if (PySwigPacked_Check(v)) {
+    PySwigPacked *sobj = (PySwigPacked *) v;
+    free(sobj->pack);
+  }
+  PyObject_DEL(v);
+}
+
+SWIGRUNTIME PyTypeObject*
+_PySwigPacked_type(void) {
+  static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer";
+  static PyTypeObject pyswigpacked_type;
+  static int type_init = 0;  
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+	PyObject_HEAD_INIT(NULL)
+	0,				    /* ob_size */	
+	(char *)"PySwigPacked",		    /* tp_name */	
+	sizeof(PySwigPacked),		    /* tp_basicsize */	
+	0,				    /* tp_itemsize */	
+	(destructor)PySwigPacked_dealloc,   /* tp_dealloc */	
+	(printfunc)PySwigPacked_print,	    /* tp_print */   	
+	(getattrfunc)0,			    /* tp_getattr */ 	
+	(setattrfunc)0,			    /* tp_setattr */ 	
+	(cmpfunc)PySwigPacked_compare,	    /* tp_compare */ 	
+	(reprfunc)PySwigPacked_repr,	    /* tp_repr */    	
+	0,	                            /* tp_as_number */	
+	0,				    /* tp_as_sequence */
+	0,				    /* tp_as_mapping */	
+	(hashfunc)0,			    /* tp_hash */	
+	(ternaryfunc)0,			    /* tp_call */	
+	(reprfunc)PySwigPacked_str,	    /* tp_str */	
+	PyObject_GenericGetAttr,            /* tp_getattro */
+	0,				    /* tp_setattro */
+	0,		                    /* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,	            /* tp_flags */
+	swigpacked_doc, 	            /* tp_doc */
+	0,                                  /* tp_traverse */
+	0,                                  /* tp_clear */
+	0,                                  /* tp_richcompare */
+	0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+	0,                                  /* tp_iter */
+	0,                                  /* tp_iternext */
+	0,		                    /* tp_methods */ 
+	0,			            /* tp_members */
+	0,				    /* tp_getset */	    	
+	0,			            /* tp_base */	        
+	0,				    /* tp_dict */	    	
+	0,				    /* tp_descr_get */  	
+	0,				    /* tp_descr_set */  	
+	0,				    /* tp_dictoffset */ 	
+	0,				    /* tp_init */	    	
+	0,				    /* tp_alloc */	    	
+	0,			            /* tp_new */	    	
+	0, 	                            /* tp_free */	   
+        0,                                  /* tp_is_gc */  
+	0,				    /* tp_bases */   
+	0,				    /* tp_mro */
+	0,				    /* tp_cache */   
+ 	0,				    /* tp_subclasses */
+	0,				    /* tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+	0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+	0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+    pyswigpacked_type = tmp;
+    pyswigpacked_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &pyswigpacked_type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty)
+{
+  PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type());
+  if (sobj) {
+    void *pack = malloc(size);
+    if (pack) {
+      memcpy(pack, ptr, size);
+      sobj->pack = pack;
+      sobj->ty   = ty;
+      sobj->size = size;
+    } else {
+      PyObject_DEL((PyObject *) sobj);
+      sobj = 0;
+    }
+  }
+  return (PyObject *) sobj;
+}
+
+SWIGRUNTIME swig_type_info *
+PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
+{
+  if (PySwigPacked_Check(obj)) {
+    PySwigPacked *sobj = (PySwigPacked *)obj;
+    if (sobj->size != size) return 0;
+    memcpy(ptr, sobj->pack, size);
+    return sobj->ty;
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIMEINLINE PyObject *
+_SWIG_This(void)
+{
+  return PyString_FromString("this");
+}
+
+SWIGRUNTIME PyObject *
+SWIG_This(void)
+{
+  static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This();
+  return swig_this;
+}
+
+/* #define SWIG_PYTHON_SLOW_GETSET_THIS */
+
+SWIGRUNTIME PySwigObject *
+SWIG_Python_GetSwigThis(PyObject *pyobj) 
+{
+  if (PySwigObject_Check(pyobj)) {
+    return (PySwigObject *) pyobj;
+  } else {
+    PyObject *obj = 0;
+#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000))
+    if (PyInstance_Check(pyobj)) {
+      obj = _PyInstance_Lookup(pyobj, SWIG_This());      
+    } else {
+      PyObject **dictptr = _PyObject_GetDictPtr(pyobj);
+      if (dictptr != NULL) {
+	PyObject *dict = *dictptr;
+	obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0;
+      } else {
+#ifdef PyWeakref_CheckProxy
+	if (PyWeakref_CheckProxy(pyobj)) {
+	  PyObject *wobj = PyWeakref_GET_OBJECT(pyobj);
+	  return wobj ? SWIG_Python_GetSwigThis(wobj) : 0;
+	}
+#endif
+	obj = PyObject_GetAttr(pyobj,SWIG_This());
+	if (obj) {
+	  Py_DECREF(obj);
+	} else {
+	  if (PyErr_Occurred()) PyErr_Clear();
+	  return 0;
+	}
+      }
+    }
+#else
+    obj = PyObject_GetAttr(pyobj,SWIG_This());
+    if (obj) {
+      Py_DECREF(obj);
+    } else {
+      if (PyErr_Occurred()) PyErr_Clear();
+      return 0;
+    }
+#endif
+    if (obj && !PySwigObject_Check(obj)) {
+      /* a PyObject is called 'this', try to get the 'real this'
+	 PySwigObject from it */ 
+      return SWIG_Python_GetSwigThis(obj);
+    }
+    return (PySwigObject *)obj;
+  }
+}
+
+/* Acquire a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_AcquirePtr(PyObject *obj, int own) {
+  if (own == SWIG_POINTER_OWN) {
+    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);
+    if (sobj) {
+      int oldown = sobj->own;
+      sobj->own = own;
+      return oldown;
+    }
+  }
+  return 0;
+}
+
+/* Convert a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {
+  if (!obj) return SWIG_ERROR;
+  if (obj == Py_None) {
+    if (ptr) *ptr = 0;
+    return SWIG_OK;
+  } else {
+    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);
+    if (own)
+      *own = 0;
+    while (sobj) {
+      void *vptr = sobj->ptr;
+      if (ty) {
+	swig_type_info *to = sobj->ty;
+	if (to == ty) {
+	  /* no type cast needed */
+	  if (ptr) *ptr = vptr;
+	  break;
+	} else {
+	  swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+	  if (!tc) {
+	    sobj = (PySwigObject *)sobj->next;
+	  } else {
+	    if (ptr) {
+              int newmemory = 0;
+              *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
+              if (newmemory == SWIG_CAST_NEW_MEMORY) {
+                assert(own);
+                if (own)
+                  *own = *own | SWIG_CAST_NEW_MEMORY;
+              }
+            }
+	    break;
+	  }
+	}
+      } else {
+	if (ptr) *ptr = vptr;
+	break;
+      }
+    }
+    if (sobj) {
+      if (own)
+        *own = *own | sobj->own;
+      if (flags & SWIG_POINTER_DISOWN) {
+	sobj->own = 0;
+      }
+      return SWIG_OK;
+    } else {
+      int res = SWIG_ERROR;
+      if (flags & SWIG_POINTER_IMPLICIT_CONV) {
+	PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;
+	if (data && !data->implicitconv) {
+	  PyObject *klass = data->klass;
+	  if (klass) {
+	    PyObject *impconv;
+	    data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/
+	    impconv = SWIG_Python_CallFunctor(klass, obj);
+	    data->implicitconv = 0;
+	    if (PyErr_Occurred()) {
+	      PyErr_Clear();
+	      impconv = 0;
+	    }
+	    if (impconv) {
+	      PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv);
+	      if (iobj) {
+		void *vptr;
+		res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0);
+		if (SWIG_IsOK(res)) {
+		  if (ptr) {
+		    *ptr = vptr;
+		    /* transfer the ownership to 'ptr' */
+		    iobj->own = 0;
+		    res = SWIG_AddCast(res);
+		    res = SWIG_AddNewMask(res);
+		  } else {
+		    res = SWIG_AddCast(res);		    
+		  }
+		}
+	      }
+	      Py_DECREF(impconv);
+	    }
+	  }
+	}
+      }
+      return res;
+    }
+  }
+}
+
+/* Convert a function ptr value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {
+  if (!PyCFunction_Check(obj)) {
+    return SWIG_ConvertPtr(obj, ptr, ty, 0);
+  } else {
+    void *vptr = 0;
+    
+    /* here we get the method pointer for callbacks */
+    const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
+    const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0;
+    if (desc) {
+      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;
+      if (!desc) return SWIG_ERROR;
+    }
+    if (ty) {
+      swig_cast_info *tc = SWIG_TypeCheck(desc,ty);
+      if (tc) {
+        int newmemory = 0;
+        *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
+        assert(!newmemory); /* newmemory handling not yet implemented */
+      } else {
+        return SWIG_ERROR;
+      }
+    } else {
+      *ptr = vptr;
+    }
+    return SWIG_OK;
+  }
+}
+
+/* Convert a packed value value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {
+  swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz);
+  if (!to) return SWIG_ERROR;
+  if (ty) {
+    if (to != ty) {
+      /* check type cast? */
+      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+      if (!tc) return SWIG_ERROR;
+    }
+  }
+  return SWIG_OK;
+}  
+
+/* -----------------------------------------------------------------------------
+ * Create a new pointer object
+ * ----------------------------------------------------------------------------- */
+
+/*
+  Create a new instance object, whitout calling __init__, and set the
+  'this' attribute.
+*/
+
+SWIGRUNTIME PyObject* 
+SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this)
+{
+#if (PY_VERSION_HEX >= 0x02020000)
+  PyObject *inst = 0;
+  PyObject *newraw = data->newraw;
+  if (newraw) {
+    inst = PyObject_Call(newraw, data->newargs, NULL);
+    if (inst) {
+#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+      PyObject **dictptr = _PyObject_GetDictPtr(inst);
+      if (dictptr != NULL) {
+	PyObject *dict = *dictptr;
+	if (dict == NULL) {
+	  dict = PyDict_New();
+	  *dictptr = dict;
+	  PyDict_SetItem(dict, SWIG_This(), swig_this);
+	}
+      }
+#else
+      PyObject *key = SWIG_This();
+      PyObject_SetAttr(inst, key, swig_this);
+#endif
+    }
+  } else {
+    PyObject *dict = PyDict_New();
+    PyDict_SetItem(dict, SWIG_This(), swig_this);
+    inst = PyInstance_NewRaw(data->newargs, dict);
+    Py_DECREF(dict);
+  }
+  return inst;
+#else
+#if (PY_VERSION_HEX >= 0x02010000)
+  PyObject *inst;
+  PyObject *dict = PyDict_New();
+  PyDict_SetItem(dict, SWIG_This(), swig_this);
+  inst = PyInstance_NewRaw(data->newargs, dict);
+  Py_DECREF(dict);
+  return (PyObject *) inst;
+#else
+  PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);
+  if (inst == NULL) {
+    return NULL;
+  }
+  inst->in_class = (PyClassObject *)data->newargs;
+  Py_INCREF(inst->in_class);
+  inst->in_dict = PyDict_New();
+  if (inst->in_dict == NULL) {
+    Py_DECREF(inst);
+    return NULL;
+  }
+#ifdef Py_TPFLAGS_HAVE_WEAKREFS
+  inst->in_weakreflist = NULL;
+#endif
+#ifdef Py_TPFLAGS_GC
+  PyObject_GC_Init(inst);
+#endif
+  PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this);
+  return (PyObject *) inst;
+#endif
+#endif
+}
+
+SWIGRUNTIME void
+SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this)
+{
+ PyObject *dict;
+#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+ PyObject **dictptr = _PyObject_GetDictPtr(inst);
+ if (dictptr != NULL) {
+   dict = *dictptr;
+   if (dict == NULL) {
+     dict = PyDict_New();
+     *dictptr = dict;
+   }
+   PyDict_SetItem(dict, SWIG_This(), swig_this);
+   return;
+ }
+#endif
+ dict = PyObject_GetAttrString(inst, (char*)"__dict__");
+ PyDict_SetItem(dict, SWIG_This(), swig_this);
+ Py_DECREF(dict);
+} 
+
+
+SWIGINTERN PyObject *
+SWIG_Python_InitShadowInstance(PyObject *args) {
+  PyObject *obj[2];
+  if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) {
+    return NULL;
+  } else {
+    PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]);
+    if (sthis) {
+      PySwigObject_append((PyObject*) sthis, obj[1]);
+    } else {
+      SWIG_Python_SetSwigThis(obj[0], obj[1]);
+    }
+    return SWIG_Py_Void();
+  }
+}
+
+/* Create a new pointer object */
+
+SWIGRUNTIME PyObject *
+SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) {
+  if (!ptr) {
+    return SWIG_Py_Void();
+  } else {
+    int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;
+    PyObject *robj = PySwigObject_New(ptr, type, own);
+    PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0;
+    if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {
+      PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);
+      if (inst) {
+	Py_DECREF(robj);
+	robj = inst;
+      }
+    }
+    return robj;
+  }
+}
+
+/* Create a new packed object */
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Get type list 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_LINK_RUNTIME
+void *SWIG_ReturnGlobalTypeList(void *);
+#endif
+
+SWIGRUNTIME swig_module_info *
+SWIG_Python_GetModule(void) {
+  static void *type_pointer = (void *)0;
+  /* first check if module already created */
+  if (!type_pointer) {
+#ifdef SWIG_LINK_RUNTIME
+    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
+#else
+    type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+				    (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      type_pointer = (void *)0;
+    }
+#endif
+  }
+  return (swig_module_info *) type_pointer;
+}
+
+#if PY_MAJOR_VERSION < 2
+/* PyModule_AddObject function was introduced in Python 2.0.  The following function
+   is copied out of Python/modsupport.c in python version 2.3.4 */
+SWIGINTERN int
+PyModule_AddObject(PyObject *m, char *name, PyObject *o)
+{
+  PyObject *dict;
+  if (!PyModule_Check(m)) {
+    PyErr_SetString(PyExc_TypeError,
+		    "PyModule_AddObject() needs module as first arg");
+    return SWIG_ERROR;
+  }
+  if (!o) {
+    PyErr_SetString(PyExc_TypeError,
+		    "PyModule_AddObject() needs non-NULL value");
+    return SWIG_ERROR;
+  }
+  
+  dict = PyModule_GetDict(m);
+  if (dict == NULL) {
+    /* Internal error -- modules must have a dict! */
+    PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
+		 PyModule_GetName(m));
+    return SWIG_ERROR;
+  }
+  if (PyDict_SetItemString(dict, name, o))
+    return SWIG_ERROR;
+  Py_DECREF(o);
+  return SWIG_OK;
+}
+#endif
+
+SWIGRUNTIME void
+SWIG_Python_DestroyModule(void *vptr)
+{
+  swig_module_info *swig_module = (swig_module_info *) vptr;
+  swig_type_info **types = swig_module->types;
+  size_t i;
+  for (i =0; i < swig_module->size; ++i) {
+    swig_type_info *ty = types[i];
+    if (ty->owndata) {
+      PySwigClientData *data = (PySwigClientData *) ty->clientdata;
+      if (data) PySwigClientData_Del(data);
+    }
+  }
+  Py_DECREF(SWIG_This());
+}
+
+SWIGRUNTIME void
+SWIG_Python_SetModule(swig_module_info *swig_module) {
+  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */
+
+  PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+				   swig_empty_runtime_method_table);
+  PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule);
+  if (pointer && module) {
+    PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
+  } else {
+    Py_XDECREF(pointer);
+  }
+}
+
+/* The python cached type query */
+SWIGRUNTIME PyObject *
+SWIG_Python_TypeCache(void) {
+  static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New();
+  return cache;
+}
+
+SWIGRUNTIME swig_type_info *
+SWIG_Python_TypeQuery(const char *type)
+{
+  PyObject *cache = SWIG_Python_TypeCache();
+  PyObject *key = PyString_FromString(type); 
+  PyObject *obj = PyDict_GetItem(cache, key);
+  swig_type_info *descriptor;
+  if (obj) {
+    descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj);
+  } else {
+    swig_module_info *swig_module = SWIG_Python_GetModule();
+    descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type);
+    if (descriptor) {
+      obj = PyCObject_FromVoidPtr(descriptor, NULL);
+      PyDict_SetItem(cache, key, obj);
+      Py_DECREF(obj);
+    }
+  }
+  Py_DECREF(key);
+  return descriptor;
+}
+
+/* 
+   For backward compatibility only
+*/
+#define SWIG_POINTER_EXCEPTION  0
+#define SWIG_arg_fail(arg)      SWIG_Python_ArgFail(arg)
+#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)
+
+SWIGRUNTIME int
+SWIG_Python_AddErrMesg(const char* mesg, int infront)
+{
+  if (PyErr_Occurred()) {
+    PyObject *type = 0;
+    PyObject *value = 0;
+    PyObject *traceback = 0;
+    PyErr_Fetch(&type, &value, &traceback);
+    if (value) {
+      PyObject *old_str = PyObject_Str(value);
+      Py_XINCREF(type);
+      PyErr_Clear();
+      if (infront) {
+	PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
+      } else {
+	PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
+      }
+      Py_DECREF(old_str);
+    }
+    return 1;
+  } else {
+    return 0;
+  }
+}
+  
+SWIGRUNTIME int
+SWIG_Python_ArgFail(int argnum)
+{
+  if (PyErr_Occurred()) {
+    /* add information about failing argument */
+    char mesg[256];
+    PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum);
+    return SWIG_Python_AddErrMesg(mesg, 1);
+  } else {
+    return 0;
+  }
+}
+
+SWIGRUNTIMEINLINE const char *
+PySwigObject_GetDesc(PyObject *self)
+{
+  PySwigObject *v = (PySwigObject *)self;
+  swig_type_info *ty = v ? v->ty : 0;
+  return ty ? ty->str : (char*)"";
+}
+
+SWIGRUNTIME void
+SWIG_Python_TypeError(const char *type, PyObject *obj)
+{
+  if (type) {
+#if defined(SWIG_COBJECT_TYPES)
+    if (obj && PySwigObject_Check(obj)) {
+      const char *otype = (const char *) PySwigObject_GetDesc(obj);
+      if (otype) {
+	PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received",
+		     type, otype);
+	return;
+      }
+    } else 
+#endif      
+    {
+      const char *otype = (obj ? obj->ob_type->tp_name : 0); 
+      if (otype) {
+	PyObject *str = PyObject_Str(obj);
+	const char *cstr = str ? PyString_AsString(str) : 0;
+	if (cstr) {
+	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
+		       type, otype, cstr);
+	} else {
+	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
+		       type, otype);
+	}
+	Py_XDECREF(str);
+	return;
+      }
+    }   
+    PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
+  } else {
+    PyErr_Format(PyExc_TypeError, "unexpected type is received");
+  }
+}
+
+
+/* Convert a pointer value, signal an exception on a type mismatch */
+SWIGRUNTIME void *
+SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
+  void *result;
+  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
+    PyErr_Clear();
+    if (flags & SWIG_POINTER_EXCEPTION) {
+      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+      SWIG_Python_ArgFail(argnum);
+    }
+  }
+  return result;
+}
+
+
+#ifdef __cplusplus
+#if 0
+{ /* cc-mode */
+#endif
+}
+#endif
diff --git a/trunk/Lib/python/pyruntime.swg b/trunk/Lib/python/pyruntime.swg
new file mode 100644
index 0000000..00f15a1
--- /dev/null
+++ b/trunk/Lib/python/pyruntime.swg
@@ -0,0 +1,13 @@
+%insert(runtime) %{
+/* Python.h has to appear first */
+#include <Python.h>
+%}
+
+%insert(runtime) "swigrun.swg";         /* SWIG API */
+%insert(runtime) "swigerrors.swg";      /* SWIG errors */   
+%insert(runtime) "pyhead.swg";          /* Python includes and fixes */
+%insert(runtime) "pyerrors.swg";        /* Python errors */
+%insert(runtime) "pythreads.swg";       /* Python thread code */
+%insert(runtime) "pyapi.swg";           /* Python API */
+%insert(runtime) "pyrun.swg";           /* Python run-time code */
+
diff --git a/trunk/Lib/python/pystdcommon.swg b/trunk/Lib/python/pystdcommon.swg
new file mode 100644
index 0000000..48b1fdc
--- /dev/null
+++ b/trunk/Lib/python/pystdcommon.swg
@@ -0,0 +1,259 @@
+%fragment("StdTraits","header",fragment="StdTraitsCommon")
+{
+namespace swig {  
+  /*
+    Traits that provides the from method
+  */
+  template <class Type> struct traits_from_ptr {
+    static PyObject *from(Type *val, int owner = 0) {
+      return SWIG_NewPointerObj(val, type_info<Type>(), owner);
+    }
+  };
+
+  template <class Type> struct traits_from {
+    static PyObject *from(const Type& val) {
+      return traits_from_ptr<Type>::from(new Type(val), 1);
+    }
+  };
+
+  template <class Type> struct traits_from<Type *> {
+    static PyObject *from(Type* val) {
+      return traits_from_ptr<Type>::from(val, 0);
+    }
+  };
+
+  template <class Type> struct traits_from<const Type *> {
+    static PyObject *from(const Type* val) {
+      return traits_from_ptr<Type>::from(const_cast<Type*>(val), 0);
+    }
+  };
+
+
+  template <class Type>
+  inline PyObject *from(const Type& val) {
+    return traits_from<Type>::from(val);
+  }
+
+  template <class Type>
+  inline PyObject *from_ptr(Type* val, int owner) {
+    return traits_from_ptr<Type>::from(val, owner);
+  }
+
+  /*
+    Traits that provides the asval/as/check method
+  */
+  template <class Type>
+  struct traits_asptr {   
+    static int asptr(PyObject *obj, Type **val) {
+      Type *p;
+      int res = (SWIG_ConvertPtr(obj, (void**)&p, type_info<Type>(), 0) == SWIG_OK) ? SWIG_OLDOBJ : 0;
+      if (SWIG_IsOK(res)) {
+	if (val) *val = p;
+      }
+      return res;
+    }
+  }; 
+
+  template <class Type>
+  inline int asptr(PyObject *obj, Type **vptr) {
+    return traits_asptr<Type>::asptr(obj, vptr);
+  }
+
+  template <class Type> 
+  struct traits_asval {
+    static int asval(PyObject *obj, Type *val) {
+      if (val) {
+	Type *p = 0;
+	int res = traits_asptr<Type>::asptr(obj, &p);
+	if (!SWIG_IsOK(res)) return res;	
+	if (p) {
+	  typedef typename noconst_traits<Type>::noconst_type noconst_type;
+	  *(const_cast<noconst_type*>(val)) = *p;
+	  if (SWIG_IsNewObj(res)){
+	    %delete(p);
+	    res = SWIG_DelNewMask(res);
+	  }
+	  return res;
+	} else {
+	  return SWIG_ERROR;
+	}
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+
+  template <class Type> struct traits_asval<Type*> {
+    static int asval(PyObject *obj, Type **val) {
+      if (val) {
+        typedef typename noconst_traits<Type>::noconst_type noconst_type;
+        noconst_type *p = 0;
+        int res = traits_asptr<noconst_type>::asptr(obj,  &p);
+        if (SWIG_IsOK(res)) {
+          *(const_cast<noconst_type**>(val)) = p;
+	}
+	return res;
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+  
+  template <class Type>
+  inline int asval(PyObject *obj, Type *val) {
+    return traits_asval<Type>::asval(obj, val);
+  }
+
+  template <class Type> 
+  struct traits_as<Type, value_category> {
+    static Type as(PyObject *obj, bool throw_error) {
+      Type v;
+      int res = asval(obj, &v);
+      if (!obj || !SWIG_IsOK(res)) {
+	if (!PyErr_Occurred()) {
+	  ::%type_error(swig::type_name<Type>());
+	}
+	if (throw_error) throw std::invalid_argument("bad type");
+      }
+      return v;
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type, pointer_category> {
+    static Type as(PyObject *obj, bool throw_error) {
+      Type *v = 0;      
+      int res = (obj ? traits_asptr<Type>::asptr(obj, &v) : SWIG_ERROR);
+      if (SWIG_IsOK(res) && v) {
+	if (SWIG_IsNewObj(res)) {
+	  Type r(*v);
+	  %delete(v);
+	  return r;
+	} else {
+	  return *v;
+	}
+      } else {
+	// Uninitialized return value, no Type() constructor required.
+	static Type *v_def = (Type*) malloc(sizeof(Type));
+	if (!PyErr_Occurred()) {
+	  %type_error(swig::type_name<Type>());
+	}
+	if (throw_error) throw std::invalid_argument("bad type");
+	memset(v_def,0,sizeof(Type));
+	return *v_def;
+      }
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type*, pointer_category> {
+    static Type* as(PyObject *obj, bool throw_error) {
+      Type *v = 0;      
+      int res = (obj ? traits_asptr<Type>::asptr(obj, &v) : SWIG_ERROR);
+      if (SWIG_IsOK(res)) {
+	return v;
+      } else {
+	if (!PyErr_Occurred()) {
+	  %type_error(swig::type_name<Type>());
+	}
+	if (throw_error) throw std::invalid_argument("bad type");
+	return 0;
+      }
+    }
+  };
+    
+  template <class Type>
+  inline Type as(PyObject *obj, bool te = false) {
+    return traits_as<Type, typename traits<Type>::category>::as(obj, te);
+  }
+
+  template <class Type> 
+  struct traits_check<Type, value_category> {
+    static bool check(PyObject *obj) {
+      int res = obj ? asval(obj, (Type *)(0)) : SWIG_ERROR;
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type> 
+  struct traits_check<Type, pointer_category> {
+    static bool check(PyObject *obj) {
+      int res = obj ? asptr(obj, (Type **)(0)) : SWIG_ERROR;
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type>
+  inline bool check(PyObject *obj) {
+    return traits_check<Type, typename traits<Type>::category>::check(obj);
+  }
+}
+}
+
+//
+// Backward compatibility
+//
+
+#ifdef SWIG_PYTHON_BACKWARD_COMP
+%{
+#include <string>
+                                                                              
+PyObject* SwigInt_FromBool(bool b) {
+    return PyInt_FromLong(b ? 1L : 0L);
+}
+double SwigNumber_Check(PyObject* o) {
+    return PyFloat_Check(o) || PyInt_Check(o) || PyLong_Check(o);
+}
+double SwigNumber_AsDouble(PyObject* o) {
+    return PyFloat_Check(o) ? PyFloat_AsDouble(o)
+        : (PyInt_Check(o) ?   double(PyInt_AsLong(o))
+                            : double(PyLong_AsLong(o)));
+}
+PyObject* SwigString_FromString(const std::string& s) {
+    return PyString_FromStringAndSize(s.data(),s.size());
+}
+std::string SwigString_AsString(PyObject* o) {
+    return std::string(PyString_AsString(o));
+}
+%}
+
+#endif
+
+
+%define %specialize_std_container(Type,Check,As,From)
+%{
+namespace swig {
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval(PyObject *obj, value_type *val) {
+      if (Check(obj)) {
+	if (val) *val = As(obj);
+	return SWIG_OK;
+      }
+      return SWIG_ERROR;
+    }
+  };
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static PyObject *from(const value_type& val) {
+      return From(val);
+    }
+  };
+
+  template <> 
+  struct traits_check<Type, value_category> {
+    static int check(PyObject *obj) {
+      int res = Check(obj);
+      return obj && res ? res : 0;
+    }
+  };
+}
+%}
+%enddef
+
+
+#define specialize_std_vector(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_list(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_deque(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_set(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
+#define specialize_std_multiset(Type,Check,As,From) %specialize_std_container(%arg(Type),Check,As,From)
diff --git a/trunk/Lib/python/pystrings.swg b/trunk/Lib/python/pystrings.swg
new file mode 100644
index 0000000..d4d60c4
--- /dev/null
+++ b/trunk/Lib/python/pystrings.swg
@@ -0,0 +1,75 @@
+/* ------------------------------------------------------------
+ *  utility methods for char strings 
+ * ------------------------------------------------------------ */
+%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") {
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc)
+{
+  if (PyString_Check(obj)) {
+    char *cstr; Py_ssize_t len;
+    PyString_AsStringAndSize(obj, &cstr, &len);
+    if (cptr)  {
+      if (alloc) {
+	/* 
+	   In python the user should not be able to modify the inner
+	   string representation. To warranty that, if you define
+	   SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string
+	   buffer is always returned.
+
+	   The default behavior is just to return the pointer value,
+	   so, be careful.
+	*/ 
+%#if defined(SWIG_PYTHON_SAFE_CSTRINGS)
+	if (*alloc != SWIG_OLDOBJ) 
+%#else
+	if (*alloc == SWIG_NEWOBJ) 
+%#endif
+	  {
+	    *cptr = %new_copy_array(cstr, len + 1, char);
+	    *alloc = SWIG_NEWOBJ;
+	  }
+	else {
+	  *cptr = cstr;
+	  *alloc = SWIG_OLDOBJ;
+	}
+      } else {
+	*cptr = PyString_AsString(obj);
+      }
+    }
+    if (psize) *psize = len + 1;
+    return SWIG_OK;
+  } else {
+    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+    if (pchar_descriptor) {
+      void* vptr = 0;
+      if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {
+	if (cptr) *cptr = (char *) vptr;
+	if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0;
+	if (alloc) *alloc = SWIG_OLDOBJ;
+	return SWIG_OK;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") {
+SWIGINTERNINLINE PyObject *
+SWIG_FromCharPtrAndSize(const char* carray, size_t size)
+{
+  if (carray) {
+    if (size > INT_MAX) {
+      swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+      return pchar_descriptor ? 
+	SWIG_NewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void();
+    } else {
+      return PyString_FromStringAndSize(carray, %numeric_cast(size,int));
+    }
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+}
+
+
diff --git a/trunk/Lib/python/python.swg b/trunk/Lib/python/python.swg
new file mode 100644
index 0000000..769d9e1
--- /dev/null
+++ b/trunk/Lib/python/python.swg
@@ -0,0 +1,59 @@
+/* ------------------------------------------------------------
+ * python.swg
+ *
+ * Python configuration module.
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ *  Inner macros
+ * ------------------------------------------------------------ */
+%include <pymacros.swg>
+
+
+/* ------------------------------------------------------------
+ *  The runtime part
+ * ------------------------------------------------------------ */
+%include <pyruntime.swg>
+
+/* ------------------------------------------------------------
+ *  Special user directives
+ * ------------------------------------------------------------ */
+%include <pyuserdir.swg>
+
+/* ------------------------------------------------------------
+ *  Typemap specializations
+ * ------------------------------------------------------------ */
+%include <pytypemaps.swg>
+
+/* ------------------------------------------------------------
+ *  Overloaded operator support
+ * ------------------------------------------------------------ */
+%include <pyopers.swg>
+
+/* ------------------------------------------------------------
+ * Warnings for Python keywords 
+ * ------------------------------------------------------------ */
+%include <pythonkw.swg>
+
+/* ------------------------------------------------------------
+ * The Python autodoc support
+ * ------------------------------------------------------------ */
+%include <pydocs.swg>
+
+/* ------------------------------------------------------------
+ * The Python classes, for C++
+ * ------------------------------------------------------------ */
+%include <pyclasses.swg>
+
+/* ------------------------------------------------------------
+ * The Python initialization function 
+ * ------------------------------------------------------------ */
+%include <pyinit.swg>
+
+
+/* ------------------------------------------------------------
+ * For backward compatibility
+ * ------------------------------------------------------------ */
+%include <pybackward.swg>
+
+
diff --git a/trunk/Lib/python/pythonkw.swg b/trunk/Lib/python/pythonkw.swg
new file mode 100644
index 0000000..2ee2335
--- /dev/null
+++ b/trunk/Lib/python/pythonkw.swg
@@ -0,0 +1,136 @@
+/*
+  Warnings for Python keywords, built-in names and bad names.
+*/
+
+#define PYTHONKW(x) %keywordwarn("'" `x` "' is a python keyword, renaming to '_" `x` "'", rename="_%s")  `x`
+#define PYTHONBN(x) %builtinwarn("'" `x` "' conflicts with a built-in name in python")  "::"`x`
+
+
+/*
+  Warnings for Python keywords 
+  http://www.fnorb.org/docs/1.2/Fnorb-Guide/node62.html
+*/
+
+PYTHONKW(and);
+PYTHONKW(assert);
+PYTHONKW(break);
+PYTHONKW(class);
+PYTHONKW(continue);
+PYTHONKW(def);
+PYTHONKW(del);
+PYTHONKW(elif);
+PYTHONKW(else);
+PYTHONKW(except);
+PYTHONKW(exec);
+PYTHONKW(finally);
+PYTHONKW(for);
+PYTHONKW(from);
+PYTHONKW(global);
+PYTHONKW(if);
+PYTHONKW(import);
+PYTHONKW(in);
+PYTHONKW(is);
+PYTHONKW(lambda);
+PYTHONKW(not);
+PYTHONKW(or);
+PYTHONKW(pass);
+PYTHONKW(print);
+PYTHONKW(raise);
+PYTHONKW(return);
+PYTHONKW(try);
+PYTHONKW(while);
+PYTHONKW(yield);
+
+/*
+  built-in functions
+  http://www.zvon.org/other/python/doc21/lib/built-in-funcs.html
+ */ 
+
+PYTHONBN(abs);
+PYTHONBN(apply);
+PYTHONBN(bool);
+PYTHONBN(buffer);
+PYTHONBN(callable);
+PYTHONBN(chr);
+PYTHONBN(classmethod);
+PYTHONBN(cmp);
+PYTHONBN(coerce);
+PYTHONBN(compile);
+PYTHONBN(complex);
+PYTHONBN(delattr);
+PYTHONBN(dict);
+PYTHONBN(dir);
+PYTHONBN(divmod);
+PYTHONBN(enumerate);
+PYTHONBN(eval);
+PYTHONBN(execfile);
+PYTHONBN(file);
+PYTHONBN(filter);
+PYTHONBN(float);
+PYTHONBN(frozenset);
+PYTHONBN(getattr);
+PYTHONBN(globals);
+PYTHONBN(hasattr);
+PYTHONBN(hash);
+PYTHONBN(hex);
+PYTHONBN(id);
+PYTHONBN(input);
+PYTHONBN(int);
+PYTHONBN(intern);
+PYTHONBN(isinstance);
+PYTHONBN(issubclass);
+PYTHONBN(iter);
+PYTHONBN(len);
+PYTHONBN(list);
+PYTHONBN(locals);
+PYTHONBN(long);
+PYTHONBN(map);
+PYTHONBN(max);
+PYTHONBN(min);
+PYTHONBN(object);
+PYTHONBN(oct);
+PYTHONBN(open);
+PYTHONBN(ord);
+PYTHONBN(pow);
+PYTHONBN(property);
+PYTHONBN(range);
+PYTHONBN(raw_input);
+PYTHONBN(reduce);
+PYTHONBN(reload);
+PYTHONBN(repr);
+PYTHONBN(reversed);
+PYTHONBN(round);
+PYTHONBN(set);
+PYTHONBN(setattr);
+PYTHONBN(slice);
+PYTHONBN(sorted);
+PYTHONBN(staticmethod);
+PYTHONBN(staticmethod);
+PYTHONBN(str);
+PYTHONBN(sum);
+PYTHONBN(super);
+PYTHONBN(tuple);
+PYTHONBN(type);
+PYTHONBN(unichr);
+PYTHONBN(unicode);
+PYTHONBN(vars);
+PYTHONBN(xrange);
+PYTHONBN(zip);
+
+
+/* 
+   built-in names
+   boolean type and None
+*/
+PYTHONBN(True);
+PYTHONBN(False);
+PYTHONBN(None);
+
+
+/* 
+   'self' is also a bad Name
+*/
+PYTHONBN(self);
+
+#undef PYTHONBN
+#undef PYTHONKW
diff --git a/trunk/Lib/python/pythreads.swg b/trunk/Lib/python/pythreads.swg
new file mode 100644
index 0000000..a7552f1
--- /dev/null
+++ b/trunk/Lib/python/pythreads.swg
@@ -0,0 +1,66 @@
+#if defined(SWIG_PYTHON_NO_THREADS)
+#  if defined(SWIG_PYTHON_THREADS)
+#    undef SWIG_PYTHON_THREADS
+#  endif
+#endif
+#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */
+#  if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL)
+#    if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */
+#      define SWIG_PYTHON_USE_GIL
+#    endif
+#  endif
+#  if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */
+#    ifndef SWIG_PYTHON_INITIALIZE_THREADS
+#     define SWIG_PYTHON_INITIALIZE_THREADS  PyEval_InitThreads() 
+#    endif
+#    ifdef __cplusplus /* C++ code */
+       class SWIG_Python_Thread_Block {
+         bool status;
+         PyGILState_STATE state;
+       public:
+         void end() { if (status) { PyGILState_Release(state); status = false;} }
+         SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {}
+         ~SWIG_Python_Thread_Block() { end(); }
+       };
+       class SWIG_Python_Thread_Allow {
+         bool status;
+         PyThreadState *save;
+       public:
+         void end() { if (status) { PyEval_RestoreThread(save); status = false; }}
+         SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {}
+         ~SWIG_Python_Thread_Allow() { end(); }
+       };
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   SWIG_Python_Thread_Block _swig_thread_block
+#      define SWIG_PYTHON_THREAD_END_BLOCK     _swig_thread_block.end()
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   SWIG_Python_Thread_Allow _swig_thread_allow
+#      define SWIG_PYTHON_THREAD_END_ALLOW     _swig_thread_allow.end()
+#    else /* C code */
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   PyGILState_STATE _swig_thread_block = PyGILState_Ensure()
+#      define SWIG_PYTHON_THREAD_END_BLOCK     PyGILState_Release(_swig_thread_block)
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   PyThreadState *_swig_thread_allow = PyEval_SaveThread()
+#      define SWIG_PYTHON_THREAD_END_ALLOW     PyEval_RestoreThread(_swig_thread_allow)
+#    endif
+#  else /* Old thread way, not implemented, user must provide it */
+#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)
+#      define SWIG_PYTHON_INITIALIZE_THREADS
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK)
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_END_BLOCK)
+#      define SWIG_PYTHON_THREAD_END_BLOCK
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW)
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_END_ALLOW)
+#      define SWIG_PYTHON_THREAD_END_ALLOW
+#    endif
+#  endif
+#else /* No thread support */
+#  define SWIG_PYTHON_INITIALIZE_THREADS
+#  define SWIG_PYTHON_THREAD_BEGIN_BLOCK
+#  define SWIG_PYTHON_THREAD_END_BLOCK
+#  define SWIG_PYTHON_THREAD_BEGIN_ALLOW
+#  define SWIG_PYTHON_THREAD_END_ALLOW
+#endif
diff --git a/trunk/Lib/python/pytuplehlp.swg b/trunk/Lib/python/pytuplehlp.swg
new file mode 100644
index 0000000..32e1580
--- /dev/null
+++ b/trunk/Lib/python/pytuplehlp.swg
@@ -0,0 +1,8 @@
+/*
+  Helper function to return output types, now we need to use a list
+  instead of a tuple since all the other types
+  (std::pair,std::vector,std::list,etc) return tuples.
+*/
+
+#warning "Deprecated file: Don't use t_output_helper anymore,"
+#warning "use SWIG_Python_AppendOutput  or %append_output instead."
diff --git a/trunk/Lib/python/pytypemaps.swg b/trunk/Lib/python/pytypemaps.swg
new file mode 100644
index 0000000..2d0aa57
--- /dev/null
+++ b/trunk/Lib/python/pytypemaps.swg
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------
+ *  Typemap specializations for Python
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ *  Fragment section
+ * ------------------------------------------------------------ */
+/* bool is dangerous in Python, change precedence */
+#undef SWIG_TYPECHECK_BOOL
+%define SWIG_TYPECHECK_BOOL             10000 %enddef
+
+/* Include fundamental fragemt definitions */
+%include <typemaps/fragments.swg>
+
+/* Look for user fragments file. */
+%include <pyfragments.swg>
+
+/* Python fragments for fundamental types */
+%include <pyprimtypes.swg>
+
+/* Python fragments for char* strings */
+%include <pystrings.swg>
+
+/* Backward compatibility output helper */
+%fragment("t_output_helper","header") %{
+#define t_output_helper SWIG_Python_AppendOutput
+%}
+
+
+/* ------------------------------------------------------------
+ *  Unified typemap section
+ * ------------------------------------------------------------ */
+
+/* directors are supported in Python */
+#ifndef SWIG_DIRECTOR_TYPEMAPS
+#define SWIG_DIRECTOR_TYPEMAPS
+#endif
+
+
+/* Python types */
+#define SWIG_Object                     PyObject *
+#define VOID_Object                     SWIG_Py_Void()
+
+/* Python allows implicit conversion */
+#define %implicitconv_flag              $implicitconv 
+
+
+/* Overload of the output/constant/exception/dirout handling */
+
+/* append output */
+#define SWIG_AppendOutput(result, obj)  SWIG_Python_AppendOutput(result, obj)
+
+/* set constant */
+#define SWIG_SetConstant(name, obj)     SWIG_Python_SetConstant(d, name,obj) 
+
+/* raise */
+#define SWIG_Raise(obj, type, desc)     SWIG_Python_Raise(obj, type, desc)
+
+/* Include the unified typemap library */
+%include <typemaps/swigtypemaps.swg>
+
+
+/*  ------------------------------------------------------------
+ *  Python extra typemaps
+ * ------------------------------------------------------------ */
+
+/* Get the address of the 'python self' object */
+
+%typemap(in,numinputs=0,noblock=1) PyObject **PYTHON_SELF {
+  $1 = &$self;
+}
+
+
+/* Consttab, needed for callbacks, it should be removed later */
+
+%typemap(consttab) SWIGTYPE ((*)(ANY))  
+{ SWIG_PY_POINTER, (char*)"$symname", 0, 0, (void *)($value), &$descriptor }
+
+%typemap(constcode) SWIGTYPE ((*)(ANY)) "";
+
+
+/* Smart Pointers */
+%typemap(out,noblock=1) const SWIGTYPE & SMARTPOINTER  {
+  $result = SWIG_NewPointerObj(%new_copy(*$1, $*ltype), $descriptor, SWIG_POINTER_OWN | %newpointer_flags);
+}
+
+%typemap(ret,noblock=1) const SWIGTYPE & SMARTPOINTER, SWIGTYPE SMARTPOINTER {
+  if ($result) {
+    PyObject *robj = PyObject_CallMethod($result, (char *)"__deref__", NULL);
+    if (robj && !PyErr_Occurred()) {
+      PySwigObject_append((PyObject *) SWIG_Python_GetSwigThis($result), 
+			  (PyObject *) SWIG_Python_GetSwigThis(robj));
+      Py_DECREF(robj);
+    }
+  }
+}
+
+
diff --git a/trunk/Lib/python/pyuserdir.swg b/trunk/Lib/python/pyuserdir.swg
new file mode 100644
index 0000000..5247ee6
--- /dev/null
+++ b/trunk/Lib/python/pyuserdir.swg
@@ -0,0 +1,245 @@
+/* -------------------------------------------------------------------------
+ *  Special user directives
+ * ------------------------------------------------------------------------- */
+
+/* ------------------------------------------------------------------------- */
+
+/* shadow code */
+#define %shadow      %insert("shadow")
+#define %pythoncode  %insert("python")
+
+
+/* ------------------------------------------------------------------------- */
+/* 
+Use the "nondynamic" feature to make a wrapped class behave as a "nondynamic"
+one, ie, a python class that doesn't dynamically add new attributes.
+
+For example, for the class
+
+%pythonnondynamic A;
+struct A
+{
+  int a;
+  int b;
+};
+
+you will get:
+
+ aa = A()
+ aa.a = 1  # Ok
+ aa.b = 1  # Ok
+ aa.c = 3  # error
+
+Since nondynamic is a feature, if you use it like
+
+ %pythonnondynamic;
+
+it will make all the wrapped classes nondynamic ones.
+
+The implementation is based on this recipe:
+
+   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
+
+and works for modern (-modern) and plain python. We do not use __slots__, 
+so, it works with old python versions.
+
+*/
+
+#define %pythonnondynamic      %feature("python:nondynamic", "1")
+#define %nopythonnondynamic    %feature("python:nondynamic", "0")
+#define %clearpythonnondynamic %feature("python:nondynamic", "")
+#define %pythondynamic         %nopythonnondynamic
+
+
+/* ------------------------------------------------------------------------- */
+/*
+
+Use %pythonmaybecall to flag a method like __add__ or __radd__.  These
+don't produce an error when called, they just return NotImplemented.
+
+These methods "may be called" if needed.
+
+*/
+
+#define %pythonmaybecall      %feature("python:maybecall", "1") 
+#define %nopythonmaybecall    %feature("python:maybecall", "0")
+#define %clearpythonmaybecall %feature("python:maybecall", "")
+
+/* ------------------------------------------------------------------------- */
+/*
+  The %pythoncallback feature produce a more natural callback wrapper
+  than the %callback mechanism, ie, it uses the original name for
+  the callback and callable objects. 
+
+  Just use it as
+
+    %pythoncallback(1) foo;
+    int foo(int a);
+
+    %pythoncallback(1) A::foo;
+    struct A {
+     static int foo(int a);
+    };
+
+    int bar(int, int (*pf)(int));
+
+  then, you can use it as:
+
+   a = foo(1)
+   b = bar(2, foo)
+
+   c = A.foo(3)
+   d = bar(4, A.foo)
+
+
+   If you use it with a member method
+   %pythoncallback(1) A::foom;
+   struct A {
+      int foom(int a);
+   };
+
+   then you can use it as
+
+     r = a.foom(3)             # eval the method
+     mptr = A.foom_cb_ptr      # returns the callback pointer
+
+   where the '_cb_ptr' suffix is added for the callback pointer.
+
+*/
+
+#define %pythoncallback      %feature("python:callback")
+#define %nopythoncallback    %feature("python:callback","0")
+#define %clearpythoncallback %feature("python:callback","")
+
+/* ------------------------------------------------------------------------- */
+/*
+  Support for the old %callback directive name
+*/
+#ifdef %callback
+#undef %callback
+#endif
+
+#ifdef %nocallback
+#undef %nocallback
+#endif
+
+#ifdef %clearcallback
+#undef %clearcallback
+#endif
+
+#define %callback(x)     %feature("python:callback",`x`)
+#define %nocallback      %nopythoncallback
+#define %clearcallback   %clearpythoncallback
+
+/* ------------------------------------------------------------------------- */
+/*
+  Thread support - Advance control
+  
+*/
+
+#define %nothread           %feature("nothread")
+#define %thread             %feature("nothread","0")
+#define %clearnothread      %feature("nothread","")
+
+#define %nothreadblock      %feature("nothreadblock")
+#define %threadblock        %feature("nothreadblock","0")
+#define %clearnothreadblock %feature("nothreadblock","")
+
+#define %nothreadallow      %feature("nothreadallow")
+#define %threadallow        %feature("nothreadallow","0")
+#define %clearnothreadallow %feature("nothreadallow","")
+
+
+/* ------------------------------------------------------------------------- */
+/*
+  Implicit Conversion using the C++ constructor mechanism
+*/
+
+#define %implicitconv      %feature("implicitconv") 
+#define %noimplicitconv    %feature("implicitconv", "0")
+#define %clearimplicitconv %feature("implicitconv", "")
+
+
+/* ------------------------------------------------------------------------- */
+/*
+  Enable keywords paramaters
+*/
+
+#define %kwargs      %feature("kwargs") 
+#define %nokwargs    %feature("kwargs", "0")
+#define %clearkwargs %feature("kwargs", "")
+
+/* ------------------------------------------------------------------------- */
+/*
+  Add python code to the proxy/shadow code 
+  
+   %pythonprepend   - Add code before the C++ function is called
+   %pythonappend    - Add code after the C++ function is called
+*/
+
+#define %pythonprepend       %feature("pythonprepend") 
+#define %clearpythonprepend  %feature("pythonprepend","")
+
+#define %pythonappend         %feature("pythonappend") 
+#define %clearpythonappend    %feature("pythonappend","")
+
+
+
+/* ------------------------------------------------------------------------- */
+/* 
+   %extend_smart_pointer extend the smart pointer support.
+
+   For example, if you have a smart pointer as:
+	    
+     template <class Type> class RCPtr {
+     public:
+       ...
+       RCPtr(Type *p);
+   	Type * operator->() const;
+   	...
+     };
+     
+   you use the %extend_smart_pointer directive as:
+   
+     %extend_smart_pointer(RCPtr<A>);
+     %template(RCPtr_A)  RCPtr<A>;
+   
+   then, if you have something like:
+
+     RCPtr<A> make_ptr();
+     int foo(A *);
+
+   you can do the following:
+
+     a = make_ptr();
+     b = foo(a);
+
+   ie, swig will accept a RCPtr<A> object where a 'A *' is
+   expected.
+
+   Also, when using vectors
+   
+     %extend_smart_pointer(RCPtr<A>);
+     %template(RCPtr_A) RCPtr<A>;
+     %template(vector_A) std::vector<RCPtr<A> >;
+   	
+   you can type
+
+     a = A();
+     v = vector_A(2)
+     v[0] = a
+
+   ie, an 'A *' object is accepted, via implicit conversion, 
+   where a RCPtr<A> object is expected. Additionally
+
+     x = v[0]
+
+   returns (and sets 'x' as) a copy of v[0], making reference
+   counting possible and consistent.
+*/
+
+%define %extend_smart_pointer(Type...)
+%implicitconv Type;
+%apply const SWIGTYPE& SMARTPOINTER { const Type& };
+%apply SWIGTYPE SMARTPOINTER { Type };
+%enddef
diff --git a/trunk/Lib/python/pywstrings.swg b/trunk/Lib/python/pywstrings.swg
new file mode 100644
index 0000000..8254bf8
--- /dev/null
+++ b/trunk/Lib/python/pywstrings.swg
@@ -0,0 +1,61 @@
+/* ------------------------------------------------------------
+ *  utility methods for wchar_t strings 
+ * ------------------------------------------------------------ */
+
+%fragment("SWIG_AsWCharPtrAndSize","header",fragment="<wchar.h>",fragment="SWIG_pwchar_descriptor") {
+SWIGINTERN int
+SWIG_AsWCharPtrAndSize(PyObject *obj, wchar_t **cptr, size_t *psize, int *alloc)
+{
+  PyObject *tmp = 0;
+  int isunicode = PyUnicode_Check(obj);
+  if (!isunicode && PyString_Check(obj)) {
+    if (cptr) {
+      obj = tmp = PyUnicode_FromObject(obj);
+    }
+    isunicode = 1;
+  }
+  if (isunicode) {
+    int len = PyUnicode_GetSize(obj);
+    if (cptr) {
+      *cptr = %new_array(len + 1, wchar_t);
+      PyUnicode_AsWideChar((PyUnicodeObject *)obj, *cptr, len);
+      (*cptr)[len] = 0;
+    }
+    if (psize) *psize = (size_t) len + 1;
+    if (alloc) *alloc = cptr ? SWIG_NEWOBJ : 0;
+    Py_XDECREF(tmp);
+    return SWIG_OK;
+  } else {
+    swig_type_info* pwchar_descriptor = SWIG_pwchar_descriptor();
+    if (pwchar_descriptor) {
+      void * vptr = 0;
+      if (SWIG_ConvertPtr(obj, &vptr, pwchar_descriptor, 0) == SWIG_OK) {
+	if (cptr) *cptr = (wchar_t *)vptr;
+	if (psize) *psize = vptr ? (wcslen((wchar_t *)vptr) + 1) : 0;
+	return SWIG_OK;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_FromWCharPtrAndSize","header",fragment="<wchar.h>",fragment="SWIG_pwchar_descriptor") {
+SWIGINTERNINLINE PyObject *
+SWIG_FromWCharPtrAndSize(const wchar_t * carray, size_t size)
+{
+  if (carray) {
+    if (size > INT_MAX) {
+      swig_type_info* pwchar_descriptor = SWIG_pwchar_descriptor();
+      return pwchar_descriptor ? 
+	SWIG_NewPointerObj(%const_cast(carray,wchar_t *), pwchar_descriptor, 0) : SWIG_Py_Void();
+    } else {
+      return PyUnicode_FromWideChar(carray, %numeric_cast(size,int));
+    }
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+}
+
+
diff --git a/trunk/Lib/python/std_alloc.i b/trunk/Lib/python/std_alloc.i
new file mode 100644
index 0000000..35dc051
--- /dev/null
+++ b/trunk/Lib/python/std_alloc.i
@@ -0,0 +1 @@
+%include <std/std_alloc.i>
diff --git a/trunk/Lib/python/std_basic_string.i b/trunk/Lib/python/std_basic_string.i
new file mode 100644
index 0000000..7d3366d
--- /dev/null
+++ b/trunk/Lib/python/std_basic_string.i
@@ -0,0 +1,103 @@
+#if !defined(SWIG_STD_STRING) 
+#define SWIG_STD_BASIC_STRING
+
+%include <pycontainer.swg>
+
+#define %swig_basic_string(Type...)  %swig_sequence_methods_val(Type)
+
+
+%fragment(SWIG_AsPtr_frag(std::basic_string<char>),"header",
+	  fragment="SWIG_AsCharPtrAndSize") {
+SWIGINTERN int
+SWIG_AsPtr(std::basic_string<char>)(PyObject* obj, std::string **val)
+{
+  static swig_type_info* string_info = 
+    SWIG_TypeQuery("std::basic_string<char> *");
+  std::string *vptr;    
+  if (SWIG_ConvertPtr(obj, (void**)&vptr, string_info, 0) == SWIG_OK) {
+    if (val) *val = vptr;
+    return SWIG_OLDOBJ;
+  } else {
+    PyErr_Clear();
+    char* buf = 0 ; size_t size = 0; int alloc = 0;
+    if (SWIG_AsCharPtrAndSize(obj, &buf, &size, &alloc) == SWIG_OK) {
+      if (buf) {
+	if (val) *val = new std::string(buf, size - 1);
+	if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+	return SWIG_NEWOBJ;
+      }
+    } else {
+      PyErr_Clear();
+    }  
+    if (val) {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+      PyErr_SetString(PyExc_TypeError,"a string is expected");
+      SWIG_PYTHON_THREAD_END_BLOCK;
+    }
+    return 0;
+  }
+}  
+}
+
+%fragment(SWIG_From_frag(std::basic_string<char>),"header",
+	  fragment="SWIG_FromCharPtrAndSize") {
+SWIGINTERNINLINE PyObject*
+  SWIG_From(std::basic_string<char>)(const std::string& s)
+  {
+    return SWIG_FromCharPtrAndSize(s.data(), s.size());
+  }
+}
+
+%include <std/std_basic_string.i>
+%typemaps_asptrfromn(%checkcode(STRING), std::basic_string<char>);
+
+#endif
+
+
+#if !defined(SWIG_STD_WSTRING)
+
+%fragment(SWIG_AsPtr_frag(std::basic_string<wchar_t>),"header",
+	  fragment="SWIG_AsWCharPtrAndSize") {
+SWIGINTERN int
+  SWIG_AsPtr(std::basic_string<wchar_t>)(PyObject* obj, std::wstring **val)
+  {
+    static swig_type_info* string_info = 
+      SWIG_TypeQuery("std::basic_string<wchar_t> *");
+    std::wstring *vptr;    
+    if (SWIG_ConvertPtr(obj, (void**)&vptr, string_info, 0) == SWIG_OK) {
+      if (val) *val = vptr;
+      return SWIG_OLDOBJ;
+    } else {
+      PyErr_Clear();
+      wchar_t *buf = 0 ; size_t size = 0; int alloc = 0;
+      if (SWIG_AsWCharPtrAndSize(obj, &buf, &size, &alloc) == SWIG_OK) {
+	if (buf) {
+	  if (val) *val = new std::wstring(buf, size - 1);
+	  if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+	  return SWIG_NEWOBJ;
+	}
+      } else {
+	PyErr_Clear();
+      }  
+      if (val) {
+	SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	PyErr_SetString(PyExc_TypeError,"a wstring is expected");
+	SWIG_PYTHON_THREAD_END_BLOCK;
+      }
+      return 0;
+    }
+  }
+}
+
+%fragment(SWIG_From_frag(std::basic_string<wchar_t>),"header",
+	  fragment="SWIG_FromWCharPtrAndSize") {
+SWIGINTERNINLINE PyObject*
+  SWIG_From(std::basic_string<wchar_t>)(const std::wstring& s)
+  {
+    return SWIG_FromWCharPtrAndSize(s.data(), s.size());
+  }
+}
+
+%typemaps_asptrfromn(%checkcode(UNISTRING), std::basic_string<wchar_t>);
+
+#endif
diff --git a/trunk/Lib/python/std_carray.i b/trunk/Lib/python/std_carray.i
new file mode 100644
index 0000000..2e40757
--- /dev/null
+++ b/trunk/Lib/python/std_carray.i
@@ -0,0 +1,54 @@
+%include <pycontainer.swg>
+
+
+%fragment("StdCarrayTraits","header",fragment="StdSequenceTraits")
+{
+namespace swig {
+  template <class T, size_t S>
+  struct traits_asptr<std::carray<T, S> >  {
+    static int asptr(PyObject *obj, std::carray<T, S> **array) {
+      return traits_asptr_stdseq<std::carray<T, S> >::asptr(obj, array);
+    }
+  };
+}
+}
+
+%warnfilter(SWIGWARN_IGNORE_OPERATOR_INDEX) std::carray::operator[];
+
+%extend std::carray {
+  %fragment(SWIG_Traits_frag(std::carray<_Type, _Size >), "header",
+	    fragment="PySwigIterator_T",
+	    fragment=SWIG_Traits_frag(_Type),
+	    fragment="StdCarrayTraits") {
+    namespace swig {
+      template <>  struct traits<std::carray<_Type, _Size > > {
+	typedef pointer_category category;
+	static const char* type_name() {
+	  return "std::carray<" #_Type "," #_Size " >";
+	}
+      };
+    }
+  }
+  
+  %typemaps_asptr(SWIG_TYPECHECK_VECTOR, swig::asptr,
+		  SWIG_Traits_frag(std::carray<_Type, _Size >),
+		  std::carray<_Type, _Size >);
+
+  %typemap(out,noblock=1) iterator, const_iterator {
+    $result = SWIG_NewPointerObj(swig::make_output_iterator((const $type &)$1),
+				 swig::PySwigIterator::descriptor(),SWIG_POINTER_OWN);
+  }
+  
+  inline size_t __len__() const { return self->size(); }
+  
+  inline const _Type& __getitem__(size_t i) const { return (*self)[i]; }
+  
+  inline void __setitem__(size_t i, const _Type& v) { (*self)[i] = v; }
+
+  
+  swig::PySwigIterator* __iter__(PyObject **PYTHON_SELF) {
+    return swig::make_output_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF);
+  }
+}
+
+%include <std/std_carray.swg>
diff --git a/trunk/Lib/python/std_char_traits.i b/trunk/Lib/python/std_char_traits.i
new file mode 100644
index 0000000..bf4e6c4
--- /dev/null
+++ b/trunk/Lib/python/std_char_traits.i
@@ -0,0 +1 @@
+%include <std/std_char_traits.i>
diff --git a/trunk/Lib/python/std_common.i b/trunk/Lib/python/std_common.i
new file mode 100644
index 0000000..3290e21
--- /dev/null
+++ b/trunk/Lib/python/std_common.i
@@ -0,0 +1,44 @@
+%include <std/std_except.i>
+%include <pystdcommon.swg>
+
+
+/*
+  Generate the traits for a 'primitive' type, such as 'double',
+  for which the SWIG_AsVal and SWIG_From methods are already defined.
+*/
+
+%define %traits_ptypen(Type...)
+  %fragment(SWIG_Traits_frag(Type),"header",
+	    fragment=SWIG_AsVal_frag(Type),
+	    fragment=SWIG_From_frag(Type),
+	    fragment="StdTraits") {
+namespace swig {
+  template <> struct traits<Type > {
+    typedef value_category category;
+    static const char* type_name() { return  #Type; }
+  };  
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval(PyObject *obj, value_type *val) { 
+      return SWIG_AsVal(Type)(obj, val);
+    }
+  };
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static PyObject *from(const value_type& val) {
+      return SWIG_From(Type)(val);
+    }
+  };
+}
+}
+%enddef
+
+
+%include <std/std_common.i>
+
+//
+// Generates the traits for all the known primitive
+// C++ types (int, double, ...)
+//
+%apply_cpptypes(%traits_ptypen);
+
diff --git a/trunk/Lib/python/std_complex.i b/trunk/Lib/python/std_complex.i
new file mode 100644
index 0000000..4e8fed3
--- /dev/null
+++ b/trunk/Lib/python/std_complex.i
@@ -0,0 +1,22 @@
+/*
+ *  STD C++ complex typemaps
+ */
+
+%include <pycomplex.swg>
+
+%{
+#include <complex> 
+%}
+
+/* defining the complex as/from converters */
+
+%swig_cplxdbl_convn(std::complex<double>, std::complex<double>, std::real, std::imag)
+%swig_cplxflt_convn(std::complex<float>,  std::complex<float>,  std::real, std::imag)
+
+/* defining the typemaps */
+
+%typemaps_primitive(%checkcode(CPLXDBL), std::complex<double>);
+%typemaps_primitive(%checkcode(CPLXFLT), std::complex<float>);
+
+
+
diff --git a/trunk/Lib/python/std_container.i b/trunk/Lib/python/std_container.i
new file mode 100644
index 0000000..d24c157
--- /dev/null
+++ b/trunk/Lib/python/std_container.i
@@ -0,0 +1,2 @@
+%include <pycontainer.swg>
+%include <std/std_container.i>
diff --git a/trunk/Lib/python/std_deque.i b/trunk/Lib/python/std_deque.i
new file mode 100644
index 0000000..b193756
--- /dev/null
+++ b/trunk/Lib/python/std_deque.i
@@ -0,0 +1,27 @@
+/*
+  Deques
+*/
+
+%fragment("StdDequeTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::deque<T> >  {
+      static int asptr(PyObject *obj, std::deque<T>  **vec) {
+	return traits_asptr_stdseq<std::deque<T> >::asptr(obj, vec);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::deque<T> > {
+      static PyObject *from(const std::deque<T> & vec) {
+	return traits_from_stdseq<std::deque<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_deque_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_deque_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_deque.i>
diff --git a/trunk/Lib/python/std_except.i b/trunk/Lib/python/std_except.i
new file mode 100644
index 0000000..af98428
--- /dev/null
+++ b/trunk/Lib/python/std_except.i
@@ -0,0 +1 @@
+%include <typemaps/std_except.swg>
diff --git a/trunk/Lib/python/std_ios.i b/trunk/Lib/python/std_ios.i
new file mode 100644
index 0000000..aa6f099
--- /dev/null
+++ b/trunk/Lib/python/std_ios.i
@@ -0,0 +1,3 @@
+%rename(ios_base_in) std::ios_base::in;
+
+%include <std/std_ios.i>
diff --git a/trunk/Lib/python/std_iostream.i b/trunk/Lib/python/std_iostream.i
new file mode 100644
index 0000000..43d6b0c
--- /dev/null
+++ b/trunk/Lib/python/std_iostream.i
@@ -0,0 +1,8 @@
+namespace std
+{
+%callback(1) endl;
+%callback(1) ends;
+%callback(1) flush;
+}
+
+%include <std/std_iostream.i>
diff --git a/trunk/Lib/python/std_list.i b/trunk/Lib/python/std_list.i
new file mode 100644
index 0000000..baf66d9
--- /dev/null
+++ b/trunk/Lib/python/std_list.i
@@ -0,0 +1,28 @@
+/*
+  Lists
+*/
+
+%fragment("StdListTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T >
+    struct traits_asptr<std::list<T> >  {
+      static int asptr(PyObject *obj, std::list<T> **lis) {
+	return traits_asptr_stdseq<std::list<T> >::asptr(obj, lis);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::list<T> > {
+      static PyObject *from(const std::list<T> & vec) {
+	return traits_from_stdseq<std::list<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_list_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_list_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_list.i>
+
diff --git a/trunk/Lib/python/std_map.i b/trunk/Lib/python/std_map.i
new file mode 100644
index 0000000..12dc23c
--- /dev/null
+++ b/trunk/Lib/python/std_map.i
@@ -0,0 +1,247 @@
+/*
+  Maps
+*/
+
+%fragment("StdMapTraits","header",fragment="StdSequenceTraits")
+{
+  namespace swig {
+    template <class PySeq, class K, class T >
+    inline void
+    assign(const PySeq& pyseq, std::map<K,T > *map) {
+      typedef typename std::map<K,T>::value_type value_type;
+      typename PySeq::const_iterator it = pyseq.begin();
+      for (;it != pyseq.end(); ++it) {
+	map->insert(value_type(it->first, it->second));
+      }
+    }
+
+    template <class K, class T>
+    struct traits_asptr<std::map<K,T> >  {
+      typedef std::map<K,T> map_type;
+      static int asptr(PyObject *obj, map_type **val) {
+	int res = SWIG_ERROR;
+	if (PyDict_Check(obj)) {
+	  PyObject_var items = PyObject_CallMethod(obj,(char *)"items",NULL);
+	  res = traits_asptr_stdseq<std::map<K,T>, std::pair<K, T> >::asptr(items, val);
+	} else {
+	  map_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<map_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+      }      
+    };
+      
+    template <class K, class T >
+    struct traits_from<std::map<K,T> >  {
+      typedef std::map<K,T> map_type;
+      typedef typename map_type::const_iterator const_iterator;
+      typedef typename map_type::size_type size_type;
+            
+      static PyObject *from(const map_type& map) {
+	swig_type_info *desc = swig::type_info<map_type>();
+	if (desc && desc->clientdata) {
+	  return SWIG_NewPointerObj(new map_type(map), desc, SWIG_POINTER_OWN);
+	} else {
+	  size_type size = map.size();
+	  int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1;
+	  if (pysize < 0) {
+	    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	    PyErr_SetString(PyExc_OverflowError,
+			    "map size not valid in python");
+	    SWIG_PYTHON_THREAD_END_BLOCK;
+	    return NULL;
+	  }
+	  PyObject *obj = PyDict_New();
+	  for (const_iterator i= map.begin(); i!= map.end(); ++i) {
+	    swig::PyObject_var key = swig::from(i->first);
+	    swig::PyObject_var val = swig::from(i->second);
+	    PyDict_SetItem(obj, key, val);
+	  }
+	  return obj;
+	}
+      }
+    };
+
+    template <class ValueType>
+    struct from_key_oper 
+    {
+      typedef const ValueType& argument_type;
+      typedef  PyObject *result_type;
+      result_type operator()(argument_type v) const
+      {
+	return swig::from(v.first);
+      }
+    };
+
+    template <class ValueType>
+    struct from_value_oper 
+    {
+      typedef const ValueType& argument_type;
+      typedef  PyObject *result_type;
+      result_type operator()(argument_type v) const
+      {
+	return swig::from(v.second);
+      }
+    };
+
+    template<class OutIterator, class FromOper, class ValueType = typename OutIterator::value_type>
+    struct PyMapIterator_T : PySwigIteratorClosed_T<OutIterator, ValueType, FromOper>
+    {
+      PyMapIterator_T(OutIterator curr, OutIterator first, OutIterator last, PyObject *seq)
+	: PySwigIteratorClosed_T<OutIterator,ValueType,FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+
+
+    template<class OutIterator,
+	     class FromOper = from_key_oper<typename OutIterator::value_type> >
+    struct PyMapKeyIterator_T : PyMapIterator_T<OutIterator, FromOper>
+    {
+      PyMapKeyIterator_T(OutIterator curr, OutIterator first, OutIterator last, PyObject *seq)
+	: PyMapIterator_T<OutIterator, FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+
+    template<typename OutIter>
+    inline PySwigIterator*
+    make_output_key_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, PyObject *seq = 0)
+    {
+      return new PyMapKeyIterator_T<OutIter>(current, begin, end, seq);
+    }
+
+    template<class OutIterator,
+	     class FromOper = from_value_oper<typename OutIterator::value_type> >
+    struct PyMapValueIterator_T : PyMapIterator_T<OutIterator, FromOper>
+    {
+      PyMapValueIterator_T(OutIterator curr, OutIterator first, OutIterator last, PyObject *seq)
+	: PyMapIterator_T<OutIterator, FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+    
+
+    template<typename OutIter>
+    inline PySwigIterator*
+    make_output_value_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, PyObject *seq = 0)
+    {
+      return new PyMapValueIterator_T<OutIter>(current, begin, end, seq);
+    }
+  }
+}
+
+%define %swig_map_common(Map...)
+  %swig_sequence_iterator(Map);
+  %swig_container_methods(Map)
+
+  %extend {
+    mapped_type __getitem__(const key_type& key) const throw (std::out_of_range) {
+      Map::const_iterator i = self->find(key);
+      if (i != self->end())
+	return i->second;
+      else
+	throw std::out_of_range("key not found");
+    }
+    
+    void __delitem__(const key_type& key) throw (std::out_of_range) {
+      Map::iterator i = self->find(key);
+      if (i != self->end())
+	self->erase(i);
+      else
+	throw std::out_of_range("key not found");
+    }
+    
+    bool has_key(const key_type& key) const {
+      Map::const_iterator i = self->find(key);
+      return i != self->end();
+    }
+    
+    PyObject* keys() {
+      Map::size_type size = self->size();
+      int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1;
+      if (pysize < 0) {
+	SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	PyErr_SetString(PyExc_OverflowError,
+			"map size not valid in python");
+	SWIG_PYTHON_THREAD_END_BLOCK;
+	return NULL;
+      }
+      PyObject* keyList = PyList_New(pysize);
+      Map::const_iterator i = self->begin();
+      for (int j = 0; j < pysize; ++i, ++j) {
+	PyList_SET_ITEM(keyList, j, swig::from(i->first));
+      }
+      return keyList;
+    }
+    
+    PyObject* values() {
+      Map::size_type size = self->size();
+      int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1;
+      if (pysize < 0) {
+	SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	PyErr_SetString(PyExc_OverflowError,
+			"map size not valid in python");
+	SWIG_PYTHON_THREAD_END_BLOCK;
+	return NULL;
+      }
+      PyObject* valList = PyList_New(pysize);
+      Map::const_iterator i = self->begin();
+      for (int j = 0; j < pysize; ++i, ++j) {
+	PyList_SET_ITEM(valList, j, swig::from(i->second));
+      }
+      return valList;
+    }
+    
+    PyObject* items() {
+      Map::size_type size = self->size();
+      int pysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1;
+      if (pysize < 0) {
+	SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	PyErr_SetString(PyExc_OverflowError,
+			"map size not valid in python");
+	SWIG_PYTHON_THREAD_END_BLOCK;
+	return NULL;
+      }    
+      PyObject* itemList = PyList_New(pysize);
+      Map::const_iterator i = self->begin();
+      for (int j = 0; j < pysize; ++i, ++j) {
+	PyList_SET_ITEM(itemList, j, swig::from(*i));
+      }
+      return itemList;
+    }
+    
+    // Python 2.2 methods
+    bool __contains__(const key_type& key) {
+      return self->find(key) != self->end();
+    }
+
+    %newobject key_iterator(PyObject **PYTHON_SELF);
+    swig::PySwigIterator* key_iterator(PyObject **PYTHON_SELF) {
+      return swig::make_output_key_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF);
+    }
+
+    %newobject value_iterator(PyObject **PYTHON_SELF);
+    swig::PySwigIterator* value_iterator(PyObject **PYTHON_SELF) {
+      return swig::make_output_value_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF);
+    }
+
+    %pythoncode {def __iter__(self): return self.key_iterator()}    
+    %pythoncode {def iterkeys(self): return self.key_iterator()}
+    %pythoncode {def itervalues(self): return self.value_iterator()}
+    %pythoncode {def iteritems(self): return self.iterator()}
+  }
+%enddef
+
+%define %swig_map_methods(Map...)
+  %swig_map_common(Map)
+  %extend {
+    void __setitem__(const key_type& key, const mapped_type& x) throw (std::out_of_range) {
+      (*self)[key] = x;
+    }
+  }
+%enddef
+
+
+%include <std/std_map.i>
diff --git a/trunk/Lib/python/std_multimap.i b/trunk/Lib/python/std_multimap.i
new file mode 100644
index 0000000..f923af0
--- /dev/null
+++ b/trunk/Lib/python/std_multimap.i
@@ -0,0 +1,79 @@
+/*
+  Multimaps
+*/
+%include <std_map.i>
+
+%fragment("StdMultimapTraits","header",fragment="StdSequenceTraits")
+{
+  namespace swig {
+    template <class PySeq, class K, class T >
+    inline void 
+    assign(const PySeq& pyseq, std::multimap<K,T > *multimap) {
+      typedef typename std::multimap<K,T>::value_type value_type;
+      typename PySeq::const_iterator it = pyseq.begin();
+      for (;it != pyseq.end(); ++it) {
+	multimap->insert(value_type(it->first, it->second));
+      }
+    }
+
+    template <class K, class T>
+    struct traits_asptr<std::multimap<K,T> >  {
+      typedef std::multimap<K,T> multimap_type;
+      static int asptr(PyObject *obj, std::multimap<K,T> **val) {
+	int res = SWIG_ERROR;
+	if (PyDict_Check(obj)) {
+	  PyObject_var items = PyObject_CallMethod(obj,(char *)"items",NULL);
+	  return traits_asptr_stdseq<std::multimap<K,T>, std::pair<K, T> >::asptr(items, val);
+	} else {
+	  multimap_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<multimap_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+      }
+    };
+      
+    template <class K, class T >
+    struct traits_from<std::multimap<K,T> >  {
+      typedef std::multimap<K,T> multimap_type;
+      typedef typename multimap_type::const_iterator const_iterator;
+      typedef typename multimap_type::size_type size_type;
+            
+      static PyObject *from(const multimap_type& multimap) {
+	swig_type_info *desc = swig::type_info<multimap_type>();
+	if (desc && desc->clientdata) {
+	  return SWIG_NewPointerObj(new multimap_type(multimap), desc, SWIG_POINTER_OWN);
+	} else {
+	  size_type size = multimap.size();
+	  int pysize = (size <= (size_type) INT_MAX) ? (int) size : -1;
+	  if (pysize < 0) {
+	    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+	    PyErr_SetString(PyExc_OverflowError,
+			    "multimap size not valid in python");
+	    SWIG_PYTHON_THREAD_END_BLOCK;
+	    return NULL;
+	  }
+	  PyObject *obj = PyDict_New();
+	  for (const_iterator i= multimap.begin(); i!= multimap.end(); ++i) {
+	    swig::PyObject_var key = swig::from(i->first);
+	    swig::PyObject_var val = swig::from(i->second);
+	    PyDict_SetItem(obj, key, val);
+	  }
+	  return obj;
+	}
+      }
+    };
+  }
+}
+
+%define %swig_multimap_methods(Type...) 
+  %swig_map_common(Type);
+  %extend {
+    void __setitem__(const key_type& key, const mapped_type& x) throw (std::out_of_range) {
+      self->insert(Type::value_type(key,x));
+    }
+  }
+%enddef
+
+%include <std/std_multimap.i>
+
diff --git a/trunk/Lib/python/std_multiset.i b/trunk/Lib/python/std_multiset.i
new file mode 100644
index 0000000..35a6890
--- /dev/null
+++ b/trunk/Lib/python/std_multiset.i
@@ -0,0 +1,41 @@
+/*
+  Multisets
+*/
+
+%include <std_set.i>
+
+%fragment("StdMultisetTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class PySeq, class T> 
+    inline void
+    assign(const PySeq& pyseq, std::multiset<T>* seq) {
+      // seq->insert(pyseq.begin(), pyseq.end()); // not used as not always implemented
+      typedef typename PySeq::value_type value_type;
+      typename PySeq::const_iterator it = pyseq.begin();
+      for (;it != pyseq.end(); ++it) {
+	seq->insert(seq->end(),(value_type)(*it));
+      }
+    }
+
+    template <class T>
+    struct traits_asptr<std::multiset<T> >  {
+      static int asptr(PyObject *obj, std::multiset<T> **m) {
+	return traits_asptr_stdseq<std::multiset<T> >::asptr(obj, m);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::multiset<T> > {
+      static PyObject *from(const std::multiset<T>& vec) {
+	return traits_from_stdseq<std::multiset<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_multiset_methods(Set...) %swig_set_methods(Set)
+
+
+
+%include <std/std_multiset.i>
diff --git a/trunk/Lib/python/std_pair.i b/trunk/Lib/python/std_pair.i
new file mode 100644
index 0000000..673e85e
--- /dev/null
+++ b/trunk/Lib/python/std_pair.i
@@ -0,0 +1,139 @@
+/*
+  Pairs
+*/
+%include <pystdcommon.swg>
+
+//#define SWIG_STD_PAIR_ASVAL
+
+%fragment("StdPairTraits","header",fragment="StdTraits") {
+  namespace swig {
+#ifdef SWIG_STD_PAIR_ASVAL
+    template <class T, class U >
+    struct traits_asval<std::pair<T,U> >  {
+      typedef std::pair<T,U> value_type;
+
+      static int get_pair(PyObject* first, PyObject* second,
+			  std::pair<T,U> *val)
+      {
+	if (val) {
+	  T *pfirst = &(val->first);
+	  int res1 = swig::asval((PyObject*)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = &(val->second);
+	  int res2 = swig::asval((PyObject*)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  return res1 > res2 ? res1 : res2;
+	} else {
+	  T *pfirst = 0;
+	  int res1 = swig::asval((PyObject*)first, 0);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = 0;
+	  int res2 = swig::asval((PyObject*)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  return res1 > res2 ? res1 : res2;
+	}	
+      }
+
+      static int asval(PyObject *obj, std::pair<T,U> *val) {
+	int res = SWIG_ERROR;
+	if (PyTuple_Check(obj)) {
+	  if (PyTuple_GET_SIZE(obj) == 2) {
+	    res = get_pair(PyTuple_GET_ITEM(obj,0),PyTuple_GET_ITEM(obj,1), val);
+	  }
+	} else if (PySequence_Check(obj)) {
+	  if (PySequence_Size(obj) == 2) {
+	    swig::PyObject_var first = PySequence_GetItem(obj,0);
+	    swig::PyObject_var second = PySequence_GetItem(obj,1);
+	    res = get_pair(first, second, val);
+	  }
+	} else {
+	  value_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<value_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = *p;
+	}
+	return res;
+      }
+    };
+
+#else
+    template <class T, class U >
+    struct traits_asptr<std::pair<T,U> >  {
+      typedef std::pair<T,U> value_type;
+
+      static int get_pair(PyObject* first, PyObject* second,
+			  std::pair<T,U> **val) 
+      {
+	if (val) {
+	  value_type *vp = %new_instance(std::pair<T,U>);
+	  T *pfirst = &(vp->first);
+	  int res1 = swig::asval((PyObject*)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = &(vp->second);
+	  int res2 = swig::asval((PyObject*)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  *val = vp;
+	  return SWIG_AddNewMask(res1 > res2 ? res1 : res2);
+	} else {
+	  T *pfirst = 0;
+	  int res1 = swig::asval((PyObject*)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = 0;
+	  int res2 = swig::asval((PyObject*)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  return res1 > res2 ? res1 : res2;
+	}	
+      }
+
+      static int asptr(PyObject *obj, std::pair<T,U> **val) {
+	int res = SWIG_ERROR;
+	if (PyTuple_Check(obj)) {
+	  if (PyTuple_GET_SIZE(obj) == 2) {
+	    res = get_pair(PyTuple_GET_ITEM(obj,0),PyTuple_GET_ITEM(obj,1), val);
+	  }
+	} else if (PySequence_Check(obj)) {
+	  if (PySequence_Size(obj) == 2) {
+	    swig::PyObject_var first = PySequence_GetItem(obj,0);
+	    swig::PyObject_var second = PySequence_GetItem(obj,1);
+	    res = get_pair(first, second, val);
+	  }
+	} else {
+	  value_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<value_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+      }
+    };
+
+#endif
+    template <class T, class U >
+    struct traits_from<std::pair<T,U> >   {
+      static PyObject *from(const std::pair<T,U>& val) {
+	PyObject* obj = PyTuple_New(2);
+	PyTuple_SetItem(obj,0,swig::from(val.first));
+	PyTuple_SetItem(obj,1,swig::from(val.second));
+	return obj;
+      }
+    };
+  }
+}
+
+%define %swig_pair_methods(pair...)
+%extend {      
+%pythoncode {def __len__(self): return 2
+def __repr__(self): return str((self.first, self.second))
+def __getitem__(self, index): 
+  if not (index % 2): 
+    return self.first
+  else:
+    return self.second
+def __setitem__(self, index, val):
+  if not (index % 2): 
+    self.first = val
+  else:
+    self.second = val}
+}
+%enddef
+
+%include <std/std_pair.i>
+
diff --git a/trunk/Lib/python/std_set.i b/trunk/Lib/python/std_set.i
new file mode 100644
index 0000000..94ef667
--- /dev/null
+++ b/trunk/Lib/python/std_set.i
@@ -0,0 +1,55 @@
+/*
+  Sets
+*/
+
+%fragment("StdSetTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class PySeq, class T> 
+    inline void 
+    assign(const PySeq& pyseq, std::set<T>* seq) {
+      // seq->insert(pyseq.begin(), pyseq.end()); // not used as not always implemented
+      typedef typename PySeq::value_type value_type;
+      typename PySeq::const_iterator it = pyseq.begin();
+      for (;it != pyseq.end(); ++it) {
+	seq->insert(seq->end(),(value_type)(*it));
+      }
+    }
+
+    template <class T>
+    struct traits_asptr<std::set<T> >  {
+      static int asptr(PyObject *obj, std::set<T> **s) {
+	return traits_asptr_stdseq<std::set<T> >::asptr(obj, s);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::set<T> > {
+      static PyObject *from(const std::set<T>& vec) {
+	return traits_from_stdseq<std::set<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+%define %swig_set_methods(set...)
+  %swig_sequence_iterator(set);
+  %swig_container_methods(set);
+
+  %extend  {
+     void append(value_type x) {
+       self->insert(x);
+     }
+  
+     bool __contains__(value_type x) {
+       return self->find(x) != self->end();
+     }
+
+     value_type __getitem__(difference_type i) const throw (std::out_of_range) {
+       return *(swig::cgetpos(self, i));
+     }
+
+  };
+%enddef
+
+%include <std/std_set.i>
diff --git a/trunk/Lib/python/std_sstream.i b/trunk/Lib/python/std_sstream.i
new file mode 100644
index 0000000..6647df8
--- /dev/null
+++ b/trunk/Lib/python/std_sstream.i
@@ -0,0 +1 @@
+%include <std/std_sstream.i>
diff --git a/trunk/Lib/python/std_streambuf.i b/trunk/Lib/python/std_streambuf.i
new file mode 100644
index 0000000..44b9bb4
--- /dev/null
+++ b/trunk/Lib/python/std_streambuf.i
@@ -0,0 +1 @@
+%include <std/std_streambuf.i>
diff --git a/trunk/Lib/python/std_string.i b/trunk/Lib/python/std_string.i
new file mode 100644
index 0000000..dc1378a
--- /dev/null
+++ b/trunk/Lib/python/std_string.i
@@ -0,0 +1 @@
+%include <typemaps/std_string.swg>
diff --git a/trunk/Lib/python/std_vector.i b/trunk/Lib/python/std_vector.i
new file mode 100644
index 0000000..3f04a30
--- /dev/null
+++ b/trunk/Lib/python/std_vector.i
@@ -0,0 +1,27 @@
+/*
+  Vectors
+*/
+
+%fragment("StdVectorTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::vector<T> >  {
+      static int asptr(PyObject *obj, std::vector<T> **vec) {
+	return traits_asptr_stdseq<std::vector<T> >::asptr(obj, vec);
+      }
+    };
+    
+    template <class T>
+    struct traits_from<std::vector<T> > {
+      static PyObject *from(const std::vector<T>& vec) {
+	return traits_from_stdseq<std::vector<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_vector_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_vector_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_vector.i>
diff --git a/trunk/Lib/python/std_vectora.i b/trunk/Lib/python/std_vectora.i
new file mode 100644
index 0000000..3f084bd
--- /dev/null
+++ b/trunk/Lib/python/std_vectora.i
@@ -0,0 +1,31 @@
+/*
+  Vectors + allocators
+*/
+
+%fragment("StdVectorATraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T, class A>
+      struct traits_asptr<std::vector<T,A> >  {
+      typedef std::vector<T,A> vector_type;
+      typedef T value_type;
+      static int asptr(PyObject *obj, vector_type **vec) {
+	return traits_asptr_stdseq<vector_type>::asptr(obj, vec);
+      }
+    };
+
+    template <class T, class A>
+    struct traits_from<std::vector<T,A> > {
+      typedef std::vector<T,A> vector_type;
+      static PyObject *from(const vector_type& vec) {
+	return traits_from_stdseq<vector_type>::from(vec);
+      }
+    };
+  }
+%}
+
+
+#define %swig_vector_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_vector_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_vectora.i>
diff --git a/trunk/Lib/python/std_wios.i b/trunk/Lib/python/std_wios.i
new file mode 100644
index 0000000..930a57d
--- /dev/null
+++ b/trunk/Lib/python/std_wios.i
@@ -0,0 +1 @@
+%include <std/std_wios.i>
diff --git a/trunk/Lib/python/std_wiostream.i b/trunk/Lib/python/std_wiostream.i
new file mode 100644
index 0000000..d3a5ee7
--- /dev/null
+++ b/trunk/Lib/python/std_wiostream.i
@@ -0,0 +1,10 @@
+namespace std
+{
+%callback(1) wendl;
+%callback(1) wends;
+%callback(1) wflush;
+}
+
+%include <std_basic_string.i>
+%include <std_wstring.i>
+%include <std/std_wiostream.i>
diff --git a/trunk/Lib/python/std_wsstream.i b/trunk/Lib/python/std_wsstream.i
new file mode 100644
index 0000000..8843f56
--- /dev/null
+++ b/trunk/Lib/python/std_wsstream.i
@@ -0,0 +1 @@
+%include <std/std_wsstream.i>
diff --git a/trunk/Lib/python/std_wstreambuf.i b/trunk/Lib/python/std_wstreambuf.i
new file mode 100644
index 0000000..c0f0920
--- /dev/null
+++ b/trunk/Lib/python/std_wstreambuf.i
@@ -0,0 +1 @@
+%include <std/std_wstreambuf.i>
diff --git a/trunk/Lib/python/std_wstring.i b/trunk/Lib/python/std_wstring.i
new file mode 100644
index 0000000..ef86281
--- /dev/null
+++ b/trunk/Lib/python/std_wstring.i
@@ -0,0 +1,3 @@
+%include <pywstrings.swg>
+%include <typemaps/std_wstring.swg>
+
diff --git a/trunk/Lib/python/stl.i b/trunk/Lib/python/stl.i
new file mode 100644
index 0000000..a3566db
--- /dev/null
+++ b/trunk/Lib/python/stl.i
@@ -0,0 +1,7 @@
+/* initial STL definition. extended as needed in each language */
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/python/typemaps.i b/trunk/Lib/python/typemaps.i
new file mode 100644
index 0000000..1c87de6
--- /dev/null
+++ b/trunk/Lib/python/typemaps.i
@@ -0,0 +1,151 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Pointer handling
+ * These mappings provide support for input/output arguments and common
+ * uses for C/C++ pointers.
+ * ----------------------------------------------------------------------------- */
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+/* 
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+
+         int            *INPUT
+         short          *INPUT
+         long           *INPUT
+	 long long      *INPUT
+         unsigned int   *INPUT
+         unsigned short *INPUT
+         unsigned long  *INPUT
+         unsigned long long *INPUT
+         unsigned char  *INPUT
+         bool           *INPUT
+         float          *INPUT
+         double         *INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include <typemaps.i>
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a list element.
+
+/* 
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, they are returned in the form of a Python tuple.
+
+         int            *OUTPUT
+         short          *OUTPUT
+         long           *OUTPUT
+         long long      *OUTPUT
+         unsigned int   *OUTPUT
+         unsigned short *OUTPUT
+         unsigned long  *OUTPUT
+         unsigned long long *OUTPUT
+         unsigned char  *OUTPUT
+         bool           *OUTPUT
+         float          *OUTPUT
+         double         *OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters).K:
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The Python output of the function would be a tuple containing both
+output values. 
+
+*/
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a Python tuple.  
+
+         int            *INOUT
+         short          *INOUT
+         long           *INOUT
+         long long      *INOUT
+         unsigned int   *INOUT
+         unsigned short *INOUT
+         unsigned long  *INOUT
+         unsigned long long *INOUT
+         unsigned char  *INOUT
+         bool           *INOUT
+         float          *INOUT
+         double         *INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+Unlike C, this mapping does not directly modify the input value (since
+this makes no sense in Python).  Rather, the modified input value shows
+up as the return value of the function.  Thus, to apply this function
+to a Python variable you might do this :
+
+       x = neg(x)
+
+Note : previous versions of SWIG used the symbol 'BOTH' to mark
+input/output arguments.   This is still supported, but will be slowly
+phased out in future releases.
+
+*/
+
+%include <typemaps/typemaps.swg>
diff --git a/trunk/Lib/python/wchar.i b/trunk/Lib/python/wchar.i
new file mode 100644
index 0000000..308139a
--- /dev/null
+++ b/trunk/Lib/python/wchar.i
@@ -0,0 +1,21 @@
+#ifdef __cplusplus
+
+%{
+#include <cwchar>
+%}
+
+#else
+
+%{
+#include <wchar.h>
+%}
+
+#endif
+
+%types(wchar_t *);
+%include <pywstrings.swg>
+
+/*
+  Enable swig wchar support.
+*/
+#define SWIG_WCHAR
diff --git a/trunk/Lib/r/cdata.i b/trunk/Lib/r/cdata.i
new file mode 100644
index 0000000..3679659
--- /dev/null
+++ b/trunk/Lib/r/cdata.i
@@ -0,0 +1 @@
+%include <typemaps/cdata.swg>
diff --git a/trunk/Lib/r/exception.i b/trunk/Lib/r/exception.i
new file mode 100644
index 0000000..39cb095
--- /dev/null
+++ b/trunk/Lib/r/exception.i
@@ -0,0 +1,8 @@
+%include <typemaps/exception.swg>
+
+
+%insert("runtime") {
+  %define_as(SWIG_exception(code, msg), 
+%block(switch (code) {case SWIG_IndexError: return Rf_ScalarLogical(NA_LOGICAL); default: %error(code, msg); SWIG_fail;} ))
+}
+
diff --git a/trunk/Lib/r/r.swg b/trunk/Lib/r/r.swg
new file mode 100644
index 0000000..0ab7e11
--- /dev/null
+++ b/trunk/Lib/r/r.swg
@@ -0,0 +1,210 @@
+/* */
+
+
+%insert("header") "swiglabels.swg"
+
+%insert("header") "swigerrors.swg"
+%insert("init") "swiginit.swg"
+%insert("runtime") "swigrun.swg"
+%insert("runtime") "rrun.swg"
+
+%init %{
+SWIGEXPORT void SWIG_init(void) {
+%}
+
+%include <rkw.swg>
+
+#define %Rruntime %insert("s")
+
+#define SWIG_Object SEXP
+#define VOID_Object R_NilValue
+
+#define %append_output(obj) SET_VECTOR_ELT($result, $n, obj)
+
+%define %set_constant(name, obj) %begin_block
+   SEXP _obj = obj;
+   assign(name, _obj);
+%end_block %enddef
+
+%define %raise(obj,type,desc) 
+return R_NilValue;
+%enddef
+
+%insert("sinit") "srun.swg"
+
+%insert("sinitroutine") %{
+SWIG_init();
+SWIG_InitializeModule(0);
+%}
+
+%include <typemaps/swigmacros.swg>
+%typemap(in) (double *x, int len) %{
+   $1 = REAL(x);
+   $2 = Rf_length(x);
+%}
+
+/* XXX
+   Need to worry about inheritance, e.g. if B extends A 
+   and we are looking for an A[], then B elements are okay.
+*/
+%typemap(scheck) SWIGTYPE[ANY]  
+  %{ 
+#      assert(length($input) > $1_dim0)
+      assert(all(sapply($input, class) == "$R_class"))     
+  %}
+
+%typemap(out) void "";
+
+%typemap(in) int *, int[ANY] %{
+  $1 = INTEGER($input);
+%}
+
+%typemap(in) double *, double[ANY] %{
+  $1 = REAL($input);
+%}
+
+/* Shoul dwe recycle to make the length correct.
+   And warn if length() > the dimension. 
+*/
+%typemap(scheck) SWIGTYPE [ANY] %{
+#  assert(length($input) >= $1_dim0)
+%}
+
+/* Handling vector case to avoid warnings,
+   although we just use the first one. */
+%typemap(scheck) unsigned int %{
+  assert(length($input) == 1 && $input >= 0, "All values must be non-negative")
+%}
+
+
+%typemap(scheck) int %{
+  if(length($input) > 1) {
+     Rf_warning("using only the first element of $input")
+  }
+%}
+
+
+%include <typemaps/swigmacros.swg>
+%include <typemaps/fragments.swg>
+%include <rfragments.swg>
+%include <ropers.swg>
+%include <typemaps/swigtypemaps.swg>
+%include <rtype.swg>
+
+%apply int[ANY] { enum SWIGTYPE[ANY] };
+
+%typemap(in,noblock=1) enum SWIGTYPE[ANY] {
+   $1 = %reinterpret_cast(INTEGER($input), $1_ltype);
+}
+
+%typemap(in,noblock=1,fragment="SWIG_strdup") char* {
+   $1 = %reinterpret_cast(SWIG_strdup(CHAR(STRING_ELT($input, 0))), $1_ltype);
+}
+
+%typemap(freearg,noblock=1) char* {
+   free($1);
+}
+
+%typemap(in,noblock=1,fragment="SWIG_strdup") char *[ANY]  {
+   $1 = %reinterpret_cast(SWIG_strdup(CHAR(STRING_ELT($input, 0))), $1_ltype);
+}
+
+%typemap(freearg,noblock=1) char *[ANY]  {
+   free($1);
+}
+
+%typemap(in,noblock=1,fragment="SWIG_strdup") char[ANY] {
+    $1 = SWIG_strdup(CHAR(STRING_ELT($input, 0)));
+}
+
+%typemap(freearg,noblock=1) char[ANY] {
+    free($1);
+}
+
+%typemap(in,noblock=1,fragment="SWIG_strdup") char[] {
+    $1 = SWIG_strdup(CHAR(STRING_ELT($input, 0)));
+}
+
+%typemap(freearg,noblock=1) char[] {
+    free($1);
+}
+
+
+%typemap(memberin) char[] %{
+if ($input) strcpy($1, $input);
+else
+strcpy($1, "");
+%}
+
+%typemap(globalin) char[] %{
+if ($input) strcpy($1, $input);
+else
+strcpy($1, "");
+%}
+
+%typemap(out,noblock=1) char* 
+ {  $result = $1 ? Rf_mkString(%reinterpret_cast($1,char *)) : R_NilValue; }
+
+%typemap(in,noblock=1) char {
+$1 = %static_cast(CHAR(STRING_ELT($input, 0))[0],$1_ltype);
+}
+
+%typemap(out) char 
+ { 
+    char tmp[2] = "x";
+    tmp[0] = $1;    
+    $result = Rf_mkString(tmp); 
+ }
+
+
+%typemap(in,noblock=1) int {
+  $1 = %static_cast(INTEGER($input)[0], $1_ltype);
+}
+
+%typemap(out,noblock=1) int 
+  "$result = Rf_ScalarInteger($1);";
+
+
+%typemap(in,noblock=1) bool 
+  "$1 = LOGICAL($input)[0] ? true : false;";
+
+
+%typemap(out,noblock=1) bool 
+  "$result = Rf_ScalarLogical($1);";
+
+%typemap(in,noblock=1) unsigned int, 
+             unsigned long,
+             float, 
+             double,
+             long 
+{
+  $1 = %static_cast(REAL($input)[0], $1_ltype); 
+}
+
+
+%typemap(out,noblock=1) unsigned int *
+  "$result = ScalarReal(*($1));";
+
+%Rruntime %{
+setMethod('[', "ExternalReference",
+function(x,i,j, ..., drop=TRUE) 
+if (!is.null(x$"__getitem__")) 
+sapply(i, function(n) x$"__getitem__"(i=as.integer(n-1))))
+
+setMethod('[<-' , "ExternalReference",
+function(x,i,j, ..., value) 
+if (!is.null(x$"__setitem__")) {
+sapply(1:length(i), function(n) 
+x$"__setitem__"(i=as.integer(i[n]-1), x=value[n]))
+x
+})
+
+setAs('ExternalReference', 'character',
+function(from) {if (!is.null(from$"__str__")) from$"__str__"()})
+
+setMethod('print', 'ExternalReference',
+function(x) {print(as(x, "character"))})
+%}
+
+
+
diff --git a/trunk/Lib/r/rcontainer.swg b/trunk/Lib/r/rcontainer.swg
new file mode 100644
index 0000000..d6d54d7
--- /dev/null
+++ b/trunk/Lib/r/rcontainer.swg
@@ -0,0 +1,198 @@
+
+//
+// Common fragments
+//
+
+
+/**** The python container methods  ****/
+
+
+
+%fragment("RSequence_Base","header")
+{
+%#include <functional>
+namespace swig {
+  inline size_t
+  check_index(ptrdiff_t i, size_t size, bool insert = false) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size)
+	return (size_t) (i + size);
+    } else if ( (size_t) i < size ) {
+      return (size_t) i;
+    } else if (insert && ((size_t) i == size)) {
+      return size;
+    }
+    
+    throw std::out_of_range("index out of range");
+  }
+
+  inline size_t
+  slice_index(ptrdiff_t i, size_t size) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size) {
+	return (size_t) (i + size);
+      } else {
+	throw std::out_of_range("index out of range");
+      }
+    } else {
+      return ( (size_t) i < size ) ? ((size_t) i) : size;
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::iterator
+  getpos(Sequence* self, Difference i)  {
+    typename Sequence::iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::const_iterator
+  cgetpos(const Sequence* self, Difference i)  {
+    typename Sequence::const_iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline Sequence*
+  getslice(const Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+
+    if (jj > ii) {
+      typename Sequence::const_iterator vb = self->begin();
+      typename Sequence::const_iterator ve = self->begin();
+      std::advance(vb,ii);
+      std::advance(ve,jj);
+      return new Sequence(vb, ve);
+    } else {
+      return new Sequence();
+    }
+  }
+
+  template <class Sequence, class Difference, class InputSeq>
+  inline void
+  setslice(Sequence* self, Difference i, Difference j, const InputSeq& v) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj < ii) jj = ii;
+    size_t ssize = jj - ii;
+    if (ssize <= v.size()) {
+      typename Sequence::iterator sb = self->begin();
+      typename InputSeq::const_iterator vmid = v.begin();
+      std::advance(sb,ii);
+      std::advance(vmid, jj - ii);
+      self->insert(std::copy(v.begin(), vmid, sb), vmid, v.end());
+    } else {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+      self->insert(sb, v.begin(), v.end());
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline void
+  delslice(Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj > ii) {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+    }
+  }
+}
+}
+
+%define %swig_container_methods(Container...)
+
+  %newobject __getslice__;
+
+  %extend {
+    bool __nonzero__() const {
+      return !(self->empty());
+    }
+
+    size_type __len__() const {
+      return self->size();
+    }
+  }
+%enddef
+
+%define %swig_sequence_methods_common(Sequence...)
+//  %swig_sequence_iterator(%arg(Sequence))
+  %swig_container_methods(%arg(Sequence))
+
+  %fragment("RSequence_Base");
+
+  %extend {
+    value_type pop() throw (std::out_of_range) {
+      if (self->size() == 0)
+	throw std::out_of_range("pop from empty container");
+      Sequence::value_type x = self->back();
+      self->pop_back();
+      return x;
+    }
+
+    Sequence* __getslice__(difference_type i, difference_type j) throw (std::out_of_range) {
+      return swig::getslice(self, i, j);
+    }
+
+    void __setslice__(difference_type i, difference_type j, const Sequence& v) 
+      throw (std::out_of_range, std::invalid_argument) {
+      swig::setslice(self, i, j, v);
+    }
+
+    void __delslice__(difference_type i, difference_type j) throw (std::out_of_range) {
+      swig::delslice(self, i, j);
+    }
+
+    void __delitem__(difference_type i) throw (std::out_of_range) {
+      self->erase(swig::getpos(self,i));
+    }
+  }
+%enddef
+
+%define %swig_sequence_methods(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+  %extend {
+    const value_type& __getitem__(difference_type i) const throw (std::out_of_range) {
+      return *(swig::cgetpos(self, i));
+    }
+
+    void __setitem__(difference_type i, const value_type& x) throw (std::out_of_range) {
+      *(swig::getpos(self,i)) = x;
+    }
+
+    void append(const value_type& x) {
+      self->push_back(x);
+    }
+ }
+%enddef
+
+%define %swig_sequence_methods_val(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+  %extend {
+    value_type __getitem__(difference_type i) throw (std::out_of_range) {
+      return *(swig::cgetpos(self, i));
+    }
+
+    void __setitem__(difference_type i, value_type x) throw (std::out_of_range) {
+      *(swig::getpos(self,i)) = x;
+    }
+
+    void append(value_type x) {
+      self->push_back(x);
+    }
+ }
+%enddef
diff --git a/trunk/Lib/r/rfragments.swg b/trunk/Lib/r/rfragments.swg
new file mode 100644
index 0000000..f6191df
--- /dev/null
+++ b/trunk/Lib/r/rfragments.swg
@@ -0,0 +1,174 @@
+#define SWIG_Error(code, msg) Rf_warning(msg); return Rf_ScalarLogical(NA_LOGICAL)
+
+#define SWIG_fail return Rf_ScalarLogical(NA_LOGICAL)
+
+/* for raw pointers */
+#define SWIG_ConvertPtr(oc, ptr, ty, flags)             SWIG_R_ConvertPtr(oc, ptr, ty, flags)
+#define SWIG_ConvertFunctionPtr(oc, ptr, ty)            SWIG_R_ConvertPtr(oc, ptr, ty, 0)
+#define SWIG_NewPointerObj(ptr, ty, flags)              SWIG_R_NewPointerObj(ptr, ty, flags)
+#define SWIG_NewFunctionPtrObj(ptr, ty)                 SWIG_R_NewPointerObj(ptr, ty, 0)
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_R_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, ty)                  SWIG_R_NewPackedObj(ptr, sz, ty)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, ty, flags)      SWIG_ConvertPtr(obj, pptr, ty, flags)
+#define SWIG_NewInstanceObj(ptr, ty, flags)             SWIG_NewPointerObj(ptr, ty, flags)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_R_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, ty)                  SWIG_R_NewPackedObj(ptr, sz, ty)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_R_GetModule()
+#define SWIG_SetModule(clientdata, pointer)             SWIG_R_SetModule(pointer)
+
+%fragment(SWIG_From_frag(long),"header") {
+SWIGINTERNINLINE SEXP
+SWIG_From_dec(long)(long value)
+{
+	return Rf_ScalarInteger((int)value);
+}
+}
+
+%fragment(SWIG_AsVal_frag(long),"header") {
+SWIGINTERNINLINE  int
+SWIG_AsVal_dec(long)(SEXP obj, long *val)
+{
+   if (val) *val = Rf_asInteger(obj);
+   return SWIG_OK;
+}
+}
+
+
+%fragment(SWIG_From_frag(long long),"header") {
+SWIGINTERNINLINE SEXP
+SWIG_From_dec(long long)(long long value)
+{
+	return Rf_ScalarInteger((int)value);
+}
+}
+
+%fragment(SWIG_AsVal_frag(long long),"header") {
+SWIGINTERNINLINE  int
+SWIG_AsVal_dec(long long)(SEXP obj, long long *val)
+{
+   if (val) *val = Rf_asInteger(obj);
+   return SWIG_OK;
+}
+}
+
+%fragment(SWIG_From_frag(unsigned long),"header") {
+SWIGINTERNINLINE SEXP
+SWIG_From_dec(unsigned long)(unsigned long value)
+{
+	return Rf_ScalarInteger((int)value);
+}
+}
+
+
+%fragment(SWIG_AsVal_frag(unsigned long),"header") {
+SWIGINTERNINLINE  int
+SWIG_AsVal_dec(unsigned long)(SEXP obj, unsigned long *val)
+{
+   if (val) *val = Rf_asInteger(obj);
+   return SWIG_OK;
+}
+}
+
+
+%fragment(SWIG_From_frag(unsigned long long),"header") {
+SWIGINTERNINLINE SEXP
+SWIG_From_dec(unsigned long long)(unsigned long long value)
+{
+	return Rf_ScalarInteger((int)value);
+}
+}
+
+
+%fragment(SWIG_AsVal_frag(unsigned long long),"header") {
+SWIGINTERNINLINE  int
+SWIG_AsVal_dec(unsigned long long)(SEXP obj, unsigned long long *val)
+{
+   if (val) *val = Rf_asInteger(obj);
+   return SWIG_OK;
+}
+}
+
+%fragment(SWIG_From_frag(double),"header") {
+SWIGINTERNINLINE SEXP
+SWIG_From_dec(double)(double value)
+{
+	return Rf_ScalarReal(value);
+}
+}
+
+
+%fragment(SWIG_AsVal_frag(double),"header") {
+SWIGINTERNINLINE  int
+SWIG_AsVal_dec(double)(SEXP obj, double *val)
+{
+   if (val) *val = Rf_asReal(obj);
+   return SWIG_OK;
+}
+}
+
+%fragment("SWIG_AsCharPtrAndSize", "header") 
+{
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(SEXP obj, char** cptr, size_t* psize, int *alloc)
+{
+  if (cptr && Rf_isString(obj)) {
+    const char *cstr = CHAR(STRING_ELT(obj, 0));
+    int len = strlen(cstr);
+
+    if (alloc) {
+      if (*alloc == SWIG_NEWOBJ) {
+        *cptr = %new_copy_array(cstr, len + 1, char);
+        *alloc = SWIG_NEWOBJ;
+      } else {
+        *cptr = %reinterpret_cast(malloc(len + 1), char *);
+        *cptr = strcpy(*cptr, cstr);
+        *alloc = SWIG_OLDOBJ;
+      }
+    } else {
+      *cptr = %reinterpret_cast(malloc(len + 1), char *);
+      *cptr = strcpy(*cptr, cstr);
+    }
+    if (psize) *psize = len + 1;
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_strdup","header") 
+{
+SWIGINTERN char *
+SWIG_strdup(const char *str)
+{
+  char *newstr = %reinterpret_cast(malloc(strlen(str) + 1), char *);
+  return strcpy(newstr, str);
+}
+}
+
+# This is modified from the R header files
+
+%fragment("SWIG_FromCharPtrAndSize","header") 
+{
+SWIGINTERN SEXP
+SWIG_FromCharPtrAndSize(const char* carray, size_t size) 
+{
+  SEXP t, c;
+  if (!carray) return R_NilValue;
+  Rf_protect(t = Rf_allocVector(STRSXP, 1));
+  c = Rf_allocVector(CHARSXP, size);
+  strncpy((char *)CHAR(c), carray, size);
+  SET_STRING_ELT(t, 0, c);
+  Rf_unprotect(1);
+  return t;
+}
+}
diff --git a/trunk/Lib/r/rkw.swg b/trunk/Lib/r/rkw.swg
new file mode 100644
index 0000000..2c181fa
--- /dev/null
+++ b/trunk/Lib/r/rkw.swg
@@ -0,0 +1,32 @@
+/*
+  Warnings for R keywords, built-in names and bad names.
+*/
+
+#define RKW(x) %keywordwarn("'" `x` "' is a R keyword, renaming to '_" `x`"'", rename="_%s")  `x`
+
+/*
+  Warnings for R reserved words taken from
+  http://cran.r-project.org/doc/manuals/R-lang.html#Reserved-words
+*/
+
+RKW(if);
+RKW(else);
+RKW(repeat);
+RKW(while);
+RKW(function);
+RKW(for);
+RKW(in);
+RKW(next);
+RKW(break);
+RKW(TRUE);
+RKW(FALSE);
+RKW(NULL);
+RKW(Inf);
+RKW(NaN);
+RKW(NA);
+RKW(NA_integer_);
+RKW(NA_real_);
+RKW(NA_complex_);
+RKW(NA_character_);
+
+#undef RKW
diff --git a/trunk/Lib/r/ropers.swg b/trunk/Lib/r/ropers.swg
new file mode 100644
index 0000000..c02f7b2
--- /dev/null
+++ b/trunk/Lib/r/ropers.swg
@@ -0,0 +1,70 @@
+#ifdef __cplusplus
+
+// These are auto-supported by the Perl-module
+%rename(__plusplus__) *::operator++;
+%rename(__minmin__)   *::operator--;
+%rename(__add__)      *::operator+;
+%rename(__sub__)      *::operator-;
+%rename(__neg__)      *::operator-();
+%rename(__neg__)      *::operator-() const;
+%rename(__mul__)      *::operator*;
+%rename(__div__)      *::operator/;
+%rename(__eq__)       *::operator==;
+%rename(__ne__)       *::operator!=;
+%rename(__mod__)      *::operator%;
+%rename(__gt__)       *::operator>;
+%rename(__lt__)       *::operator<;
+%rename(__not__)      *::operator!;
+
+// These are renamed, but no 'use overload...' is added
+%rename(__lshift__)   *::operator<<;
+%rename(__rshift__)   *::operator>>;
+%rename(__and__)      *::operator&;
+%rename(__or__)       *::operator|;
+%rename(__xor__)      *::operator^;
+%rename(__invert__)   *::operator~;
+%rename(__le__)       *::operator<=;
+%rename(__ge__)       *::operator>=;
+%rename(__call__)     *::operator();
+%rename(__getitem__)  *::operator[];
+
+%rename(__seteq__)    *::operator=;
+
+
+%rename(__land__)       operator&&;
+%rename(__lor__)        operator||;
+%rename(__plusplus__)   *::operator++;
+%rename(__minusminus__) *::operator--;
+%rename(__arrowstar__)  *::operator->*;
+%rename(__index__)      *::operator[];
+
+%rename(Equal) operator =;
+%rename(PlusEqual) operator +=;
+%rename(MinusEqual) operator -=;
+%rename(MultiplyEqual) operator *=;
+%rename(DivideEqual) operator /=;
+%rename(PercentEqual) operator %=;
+%rename(Plus) operator +;
+%rename(Minus) operator -;
+%rename(Multiply) operator *;
+%rename(Divide) operator /;
+%rename(Percent) operator %;
+%rename(Not) operator !;
+%rename(IndexIntoConst) operator[](unsigned idx) const;
+%rename(IndexInto) operator[](unsigned idx);
+%rename(Functor) operator ();
+%rename(EqualEqual) operator ==;
+%rename(NotEqual) operator !=;
+%rename(LessThan) operator <;
+%rename(LessThanEqual) operator <=;
+%rename(GreaterThan) operator >;
+%rename(GreaterThanEqual) operator >=;
+%rename(And) operator &&;
+%rename(Or) operator ||;
+%rename(PlusPlusPrefix) operator++();
+%rename(PlusPlusPostfix) operator++(int);
+%rename(MinusMinusPrefix) operator--();
+%rename(MinusMinusPostfix) operator--(int);
+
+
+#endif
diff --git a/trunk/Lib/r/rrun.swg b/trunk/Lib/r/rrun.swg
new file mode 100644
index 0000000..b5375c2
--- /dev/null
+++ b/trunk/Lib/r/rrun.swg
@@ -0,0 +1,369 @@
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Remove global namespace pollution */
+#if !defined(SWIG_NO_R_NO_REMAP)
+# define R_NO_REMAP
+#endif
+#if !defined(SWIG_NO_STRICT_R_HEADERS)
+# define STRICT_R_HEADERS
+#endif
+
+#include <Rdefines.h>
+#include <Rversion.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#define SWIGR 1
+
+#if R_VERSION >= R_Version(2,6,0)
+#define VMAXTYPE void *
+#else
+#define VMAXTYPE char *
+#endif
+
+/*
+  This is mainly a way to avoid having lots of local variables that may 
+  conflict with those in the routine.
+
+   Change name to R_SWIG_Callb....
+*/
+typedef struct RCallbackFunctionData {
+
+  SEXP fun;
+  SEXP userData;
+
+
+  SEXP expr;
+  SEXP retValue;
+  int errorOccurred;
+
+  SEXP el;  /* Temporary pointer used in the construction of the expression to call the R function. */
+
+  struct RCallbackFunctionData *previous;   /* Stack */
+
+} RCallbackFunctionData;
+
+static RCallbackFunctionData  *callbackFunctionDataStack;
+
+
+SWIGRUNTIME SEXP
+R_SWIG_debug_getCallbackFunctionData()
+{
+  int n, i;
+  SEXP ans;
+  RCallbackFunctionData  *p = callbackFunctionDataStack;
+
+  n = 0;
+  while(p) { 
+    n++;
+    p = p->previous;
+  }
+
+  Rf_protect(ans = Rf_allocVector(VECSXP, n));
+  for(p = callbackFunctionDataStack, i = 0; i < n; p = p->previous, i++) 
+      SET_VECTOR_ELT(ans, i, p->fun);
+
+  Rf_unprotect(1);
+
+  return(ans);
+}
+
+
+
+SWIGRUNTIME RCallbackFunctionData *
+R_SWIG_pushCallbackFunctionData(SEXP fun, SEXP userData)
+{
+   RCallbackFunctionData *el;
+   el = (RCallbackFunctionData *) calloc(1, sizeof(RCallbackFunctionData));
+   el->fun = fun;
+   el->userData = userData;
+   el->previous = callbackFunctionDataStack;
+
+   callbackFunctionDataStack = el;
+
+   return(el);
+}
+
+
+SWIGRUNTIME SEXP
+R_SWIG_R_pushCallbackFunctionData(SEXP fun, SEXP userData)
+{
+    R_SWIG_pushCallbackFunctionData(fun, userData);
+    return R_NilValue;
+}
+
+SWIGRUNTIME RCallbackFunctionData *
+R_SWIG_getCallbackFunctionData()
+{
+  if(!callbackFunctionDataStack) {
+    Rf_error("Supposedly impossible error occurred in the SWIG callback mechanism."
+            "  No callback function data set.");
+  }
+  
+  return callbackFunctionDataStack;
+}
+
+SWIGRUNTIME void
+R_SWIG_popCallbackFunctionData(int doFree)
+{
+  RCallbackFunctionData  *el = NULL;
+  if(!callbackFunctionDataStack)
+    return ; /* Error !!! */
+
+  el = callbackFunctionDataStack ;
+  callbackFunctionDataStack = callbackFunctionDataStack->previous;
+
+  if(doFree)
+     free(el);
+}
+
+
+/*
+  Interface to S function
+      is(obj, type)
+  which is to be used to determine if an 
+  external pointer inherits from the right class.
+
+  Ideally, we would like to be able to do this without an explicit call to the is() function.
+  When the S4 class system uses its own SEXP types, then we will hopefully be able to do this
+  in the C code.
+
+  Should we make the expression static and preserve it to avoid the overhead of 
+  allocating each time.
+*/
+SWIGRUNTIME int
+R_SWIG_checkInherits(SEXP obj, SEXP tag, const char *type)
+{
+  SEXP e, val;
+  int check_err = 0;
+
+  Rf_protect(e = Rf_allocVector(LANGSXP, 3));
+  SETCAR(e, Rf_install("extends"));
+
+  SETCAR(CDR(e), Rf_mkString(CHAR(PRINTNAME(tag))));
+  SETCAR(CDR(CDR(e)), Rf_mkString(type));
+
+  val = R_tryEval(e, R_GlobalEnv, &check_err);
+  Rf_unprotect(1);
+  if(check_err) 
+    return(0);
+
+
+  return(LOGICAL(val)[0]);
+}
+
+
+SWIGRUNTIME void *
+R_SWIG_resolveExternalRef(SEXP arg, const char * const type, const char * const argName, Rboolean nullOk)
+{
+  void *ptr;
+  SEXP orig = arg;
+
+  if(TYPEOF(arg) != EXTPTRSXP) 
+    arg = GET_SLOT(arg, Rf_mkString("ref"));
+
+  
+  if(TYPEOF(arg) != EXTPTRSXP) {
+    Rf_error("argument %s must be an external pointer (from an ExternalReference)", argName);
+  }
+
+
+  ptr = R_ExternalPtrAddr(arg);
+
+  if(ptr == NULL && nullOk == (Rboolean) FALSE) {
+    Rf_error("the external pointer (of type %s) for argument %s has value NULL", argName, type);
+  }
+
+  if(type[0] && R_ExternalPtrTag(arg) != Rf_install(type) && strcmp(type, "voidRef")
+      && !R_SWIG_checkInherits(orig,  R_ExternalPtrTag(arg), type)) {
+    Rf_error("the external pointer for argument %s has tag %s, not the expected value %s",
+             argName, CHAR(PRINTNAME(R_ExternalPtrTag(arg))), type);
+  }
+
+
+  return(ptr);
+}
+
+SWIGRUNTIME void
+R_SWIG_ReferenceFinalizer(SEXP el)
+{
+  void *ptr = R_SWIG_resolveExternalRef(el, "", "<finalizer>",  (Rboolean) 1);
+  fprintf(stderr, "In R_SWIG_ReferenceFinalizer for %p\n", ptr);
+  Rf_PrintValue(el);
+
+  if(ptr) {
+     if(TYPEOF(el) != EXTPTRSXP)
+        el = GET_SLOT(el, Rf_mkString("ref"));
+
+     if(TYPEOF(el) == EXTPTRSXP)
+        R_ClearExternalPtr(el);
+
+     free(ptr);
+  }
+
+  return;
+}
+
+typedef enum {R_SWIG_EXTERNAL, R_SWIG_OWNER } R_SWIG_Owner;
+
+SWIGRUNTIME SEXP
+SWIG_MakePtr(void *ptr, const char *typeName, R_SWIG_Owner owner)
+{
+  SEXP external, r_obj;
+  const char *p = typeName;
+
+  if(typeName[0] == '_')
+     p = typeName + 1;
+
+  Rf_protect(external = R_MakeExternalPtr(ptr, Rf_install(typeName), R_NilValue));
+  Rf_protect(r_obj = NEW_OBJECT(MAKE_CLASS((char *) typeName)));
+
+  if(owner)
+    R_RegisterCFinalizer(external, R_SWIG_ReferenceFinalizer);
+
+  r_obj = SET_SLOT(r_obj, Rf_mkString((char *) "ref"), external);
+  SET_S4_OBJECT(r_obj);
+  Rf_unprotect(2);
+
+  return(r_obj);
+}
+
+
+SWIGRUNTIME SEXP
+R_SWIG_create_SWIG_R_Array(const char *typeName, SEXP ref, int len)
+{
+   SEXP arr;
+
+/*XXX remove the char * cast when we can. MAKE_CLASS should be declared appropriately. */
+   Rf_protect(arr = NEW_OBJECT(MAKE_CLASS((char *) typeName)));
+   Rf_protect(arr = R_do_slot_assign(arr, Rf_mkString("ref"), ref));
+   Rf_protect(arr = R_do_slot_assign(arr, Rf_mkString("dims"), Rf_ScalarInteger(len)));
+
+   Rf_unprotect(3); 			   
+   SET_S4_OBJECT(arr);	
+   return arr;
+}
+
+#define ADD_OUTPUT_ARG(result, pos, value, name)  r_ans = AddOutputArgToReturn(pos, value, name, OutputValues);
+
+SWIGRUNTIME SEXP
+AddOutputArgToReturn(int pos, SEXP value, const char *name, SEXP output)
+{
+  SET_VECTOR_ELT(output, pos, value);
+
+  return(output);
+}
+
+/* Create a new pointer object */
+SWIGRUNTIMEINLINE SEXP
+SWIG_R_NewPointerObj(void *ptr, swig_type_info *type, int flags) {
+  SEXP rptr = R_MakeExternalPtr(ptr, 
+  R_MakeExternalPtr(type, R_NilValue, R_NilValue), R_NilValue); 
+  SET_S4_OBJECT(rptr);
+//  rptr = Rf_setAttrib(rptr, R_ClassSymbol, mkChar(SWIG_TypeName(type)));
+  return rptr;
+}
+
+/* Convert a pointer value */
+SWIGRUNTIMEINLINE int
+SWIG_R_ConvertPtr(SEXP obj, void **ptr, swig_type_info *ty, int flags) {
+  void *vptr;
+  if (!obj) return SWIG_ERROR;
+  if (obj == R_NilValue) {
+    if (ptr) *ptr = NULL;
+    return SWIG_OK;
+  }
+
+  vptr = R_ExternalPtrAddr(obj);
+  if (ty) {
+    swig_type_info *to = (swig_type_info*) 
+      R_ExternalPtrAddr(R_ExternalPtrTag(obj));
+    if (to == ty) {
+      if (ptr) *ptr = vptr;
+    } else {
+      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+      int newmemory = 0;
+      if (ptr) *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+    }
+  } else {
+      if (ptr) *ptr = vptr;
+ }
+  return SWIG_OK;
+}
+
+SWIGRUNTIME swig_module_info *
+SWIG_GetModule(void *v) {
+  static void *type_pointer = (void *)0;
+  return (swig_module_info *) type_pointer;
+}
+
+SWIGRUNTIME void
+SWIG_SetModule(void *v, swig_module_info *swig_module) {
+}
+
+typedef struct {
+  void *pack;
+  swig_type_info *ty;
+  size_t size;
+} RSwigPacked;
+
+/* Create a new packed object */
+
+SWIGRUNTIMEINLINE SEXP RSwigPacked_New(void *ptr, size_t sz,
+		  swig_type_info *ty) {
+  SEXP rptr;
+  RSwigPacked *sobj = 
+  (RSwigPacked*) malloc(sizeof(RSwigPacked));
+  if (sobj) {
+    void *pack = malloc(sz);
+    if (pack) {
+      memcpy(pack, ptr, sz);
+      sobj->pack = pack;
+      sobj->ty   = ty;
+      sobj->size = sz;
+    } else {
+      sobj = 0;
+    }
+  }
+  rptr = R_MakeExternalPtr(sobj, R_NilValue, R_NilValue); 
+  return rptr;
+}
+
+SWIGRUNTIME swig_type_info *
+RSwigPacked_UnpackData(SEXP obj, void *ptr, size_t size)
+{
+    RSwigPacked *sobj = 
+        (RSwigPacked *)R_ExternalPtrAddr(obj);
+    if (sobj->size != size) return 0;
+    memcpy(ptr, sobj->pack, size);
+    return sobj->ty;
+}
+
+SWIGRUNTIMEINLINE SEXP
+SWIG_R_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  return ptr ? RSwigPacked_New((void *) ptr, sz, type) : R_NilValue;
+}
+
+/* Convert a packed value value */
+
+SWIGRUNTIME int
+SWIG_R_ConvertPacked(SEXP obj, void *ptr, size_t sz, swig_type_info *ty) {
+  swig_type_info *to = RSwigPacked_UnpackData(obj, ptr, sz);
+  if (!to) return SWIG_ERROR;
+  if (ty) {
+    if (to != ty) {
+      /* check type cast? */
+      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+      if (!tc) return SWIG_ERROR;
+    }
+  }
+  return SWIG_OK;
+}  
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/r/rstdcommon.swg b/trunk/Lib/r/rstdcommon.swg
new file mode 100644
index 0000000..2232037
--- /dev/null
+++ b/trunk/Lib/r/rstdcommon.swg
@@ -0,0 +1,216 @@
+%fragment("StdTraits","header",fragment="StdTraitsCommon")
+{
+namespace swig {  
+  /*
+    Traits that provides the from method
+  */
+
+  template <class Type> struct traits_from_ptr {
+    static SWIG_Object from(Type *val, int owner = 0) {
+      return SWIG_NewPointerObj(val, type_info<Type>(), owner);
+    }
+  };
+
+  template <class Type> struct traits_from {
+    static SWIG_Object from(const Type& val) {
+      return traits_from_ptr<Type>::from(new Type(val), 1);
+    }
+  };
+
+  template <class Type> struct traits_from<Type *> {
+    static SWIG_Object from(Type* val) {
+      return traits_from_ptr<Type>::from(val, 0);
+    }
+  };
+
+  template <class Type>
+  inline SWIG_Object from(const Type& val) {
+    return traits_from<Type>::from(val);
+  }
+
+  template <class Type>
+  inline SWIG_Object from_ptr(Type* val, int owner) {
+    return traits_from_ptr<Type>::from(val, owner);
+  }
+
+  /*
+    Traits that provides the asval/as/check method
+  */
+  template <class Type>
+  struct traits_asptr {   
+    static int asptr(SWIG_Object obj, Type **val) {
+      Type *p;
+      int res = (SWIG_ConvertPtr(obj, (void**)&p, type_info<Type>(), 0) == SWIG_OK) ? SWIG_OLDOBJ : 0;
+      if (SWIG_IsOK(res)) {
+	if (val) *val = p;
+      }
+      return res;
+    }
+  }; 
+
+  template <class Type>
+  inline int asptr(SWIG_Object obj, Type **vptr) {
+    return traits_asptr<Type>::asptr(obj, vptr);
+  }
+
+  template <class Type> 
+  struct traits_asval {
+    static int asval(SWIG_Object obj, Type *val) {
+      if (val) {
+	Type *p = 0;
+	int res = traits_asptr<Type>::asptr(obj, &p);
+	if (!SWIG_IsOK(res)) return res;	
+	if (p) {
+	  typedef typename noconst_traits<Type>::noconst_type noconst_type;
+	  *(const_cast<noconst_type*>(val)) = *p;
+	  if (SWIG_IsNewObj(res)){
+	    %delete(p);
+	    res = SWIG_DelNewMask(res);
+	  }
+	  return res;
+	} else {
+	  return SWIG_ERROR;
+	}
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+
+  template <class Type> struct traits_asval<Type*> {
+    static int asval(SWIG_Object obj, Type **val) {
+      if (val) {
+        typedef typename noconst_traits<Type>::noconst_type noconst_type;
+        noconst_type *p = 0;
+        int res = traits_asptr<noconst_type>::asptr(obj,  &p);
+        if (SWIG_IsOK(res)) {
+          *(const_cast<noconst_type**>(val)) = p;
+	}
+	return res;
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+  
+  template <class Type>
+  inline int asval(SWIG_Object obj, Type *val) {
+    return traits_asval<Type>::asval(obj, val);
+  }
+
+  template <class Type> 
+  struct traits_as<Type, value_category> {
+    static Type as(SWIG_Object obj, bool throw_error) {
+      Type v;
+      int res = asval(obj, &v);
+      if (!obj || !SWIG_IsOK(res)) {
+//	if (!PyErr_Occurred()) {
+//	  %type_error(swig::type_name<Type>());
+//	}
+	if (throw_error) throw std::invalid_argument("bad type");
+      }
+      return v;
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type, pointer_category> {
+    static Type as(SWIG_Object obj, bool throw_error) {
+      Type *v = 0;      
+      int res = (obj ? traits_asptr<Type>::asptr(obj, &v) : SWIG_ERROR);
+      if (SWIG_IsOK(res) && v) {
+	if (SWIG_IsNewObj(res)) {
+	  Type r(*v);
+	  %delete(v);
+	  return r;
+	} else {
+	  return *v;
+	}
+      } else {
+	// Uninitialized return value, no Type() constructor required.
+	static Type *v_def = (Type*) malloc(sizeof(Type));
+//	if (!PyErr_Occurred()) {
+//	  %type_error(swig::type_name<Type>());
+//	}
+	if (throw_error) throw std::invalid_argument("bad type");
+	memset(v_def,0,sizeof(Type));
+	return *v_def;
+      }
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type*, pointer_category> {
+    static Type* as(SWIG_Object obj, bool throw_error) {
+      Type *v = 0;      
+      int res = (obj ? traits_asptr<Type>::asptr(obj, &v) : SWIG_ERROR);
+      if (SWIG_IsOK(res)) {
+	return v;
+      } else {
+//	if (!PyErr_Occurred()) {
+//	  %type_error(swig::type_name<Type>());
+//	}
+	if (throw_error) throw std::invalid_argument("bad type");
+	return 0;
+      }
+    }
+  };
+    
+  template <class Type>
+  inline Type as(SWIG_Object obj, bool te = false) {
+    return traits_as<Type, typename traits<Type>::category>::as(obj, te);
+  }
+
+  template <class Type> 
+  struct traits_check<Type, value_category> {
+    static bool check(SWIG_Object obj) {
+      int res = obj ? asval(obj, (Type *)(0)) : SWIG_ERROR;
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type> 
+  struct traits_check<Type, pointer_category> {
+    static bool check(SWIG_Object obj) {
+      int res = obj ? asptr(obj, (Type **)(0)) : SWIG_ERROR;
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type>
+  inline bool check(SWIG_Object obj) {
+    return traits_check<Type, typename traits<Type>::category>::check(obj);
+  }
+}
+}
+
+%define %specialize_std_container(Type,Check,As,From)
+%{
+namespace swig {
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval(SWIG_Object obj, value_type *val) {
+      if (Check(obj)) {
+	if (val) *val = As(obj);
+	return SWIG_OK;
+      }
+      return SWIG_ERROR;
+    }
+  };
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static SWIG_Object from(const value_type& val) {
+      return From(val);
+    }
+  };
+
+  template <> 
+  struct traits_check<Type, value_category> {
+    static int check(SWIG_Object obj) {
+      int res = Check(obj);
+      return obj && res ? res : 0;
+    }
+  };
+}
+%}
+%enddef
diff --git a/trunk/Lib/r/rtype.swg b/trunk/Lib/r/rtype.swg
new file mode 100644
index 0000000..9206b5e
--- /dev/null
+++ b/trunk/Lib/r/rtype.swg
@@ -0,0 +1,205 @@
+
+/* These map the primitive C types to the appropriate R type
+   for use in class representations. 
+ */
+
+%typemap("rtype") int, int *, int &      "numeric";
+%apply int {size_t}
+%apply int {std::size_t}
+%apply int {ptrdiff_t}
+%apply int {std::ptrdiff_t}
+
+%typemap("rtype") long, long *    "numeric";
+%typemap("rtype") unsigned long, 
+                  unsigned long * "numeric";
+%typemap("rtype") unsigned int, 
+                  unsigned int *  "numeric";
+%typemap("rtype") double, double*, double & "numeric";
+%typemap("rtype") float, float *, float &  "numeric";
+%typemap("rtype") char *, char ** "character";
+%typemap("rtype") char            "character";
+%typemap("rtype") string, string *, string & "character";
+%typemap("rtype") std::string, std::string *, std::string & "character";
+%typemap("rtype") bool, bool *    "logical";
+%typemap("rtype") enum SWIGTYPE   "character";
+%typemap("rtype") enum SWIGTYPE *   "character";
+%typemap("rtype") enum SWIGTYPE &  "character";
+%typemap("rtype") SWIGTYPE * "$R_class";
+%typemap("rtype") SWIGTYPE & "$R_class";
+%typemap("rtype") SWIGTYPE "$&R_class";
+
+
+
+/* Have to be careful that as(x, "numeric") is different from as.numeric(x).  
+   The latter makes a REALSXP, whereas the former leaves an INTSXP as an
+   INTSXP.
+*/
+
+
+%typemap(scoercein) int, int *, int &
+  %{  $input = as($input, "integer");     %}
+%typemap(scoercein) ptrdiff_t, ptrdiff_t *, ptrdiff_t &
+  %{  $input = as($input, "integer");     %}
+%typemap(scoercein) unsigned long, unsigned long *, unsigned long &
+  %{  $input = as($input, "integer");     %}
+%typemap(scoercein) unsigned int, unsigned int *, unsigned int &
+  %{  $input = as($input, "integer");     %}
+%typemap(scoercein) double, double *, double &
+  %{ %}
+%typemap(scoercein) float, float *, float &
+  %{ %}
+%typemap(scoercein) char, char *, char &
+  %{  $input = as($input, "character");     %}
+%typemap(scoercein) string, string *, string &
+  %{  $input = as($input, "character");     %}
+%typemap(scoercein) std::string, std::string *, std::string &
+  %{  $input = as($input, "character");     %}
+%typemap(scoercein) enum SWIGTYPE 
+  %{  $input = enumToInteger($input, "$R_class") %}
+%typemap(scoercein) enum SWIGTYPE &
+  %{  $input = enumToInteger($input, "$R_class") %}
+%typemap(scoercein) enum SWIGTYPE *
+  %{  $input = enumToInteger($input, "$R_class") %}
+
+
+%typemap(scoercein) SWIGTYPE, SWIGTYPE *, SWIGTYPE &  
+  %{ %}
+
+/*
+%typemap(scoercein) SWIGTYPE * 
+  %{ $input = coerceIfNotSubclass($input, "$R_class") %}
+
+%typemap(scoercein) SWIGTYPE & 
+  %{ $input = coerceIfNotSubclass($input, "$R_class") %}
+
+%typemap(scoercein) SWIGTYPE  
+  %{ $input = coerceIfNotSubclass($input, "$&R_class") %}
+*/
+
+%typemap(scoercein) SWIGTYPE[ANY]  
+ %{
+    if(is.list($input))
+      assert(all(sapply($input, class) == "$R_class"))     
+ %}
+
+
+/* **************************************************************** */
+
+%typemap(scoercein) bool, bool *, bool & 
+		    "$input = as.logical($input) ";
+/*
+%typemap(scoercein) int, 
+                    int *, 
+		    int &,
+                    int[ANY],
+		    size_t,
+		    std::size_t,
+		    size_t &,
+		    std::size_t &
+  "$input = as.integer($input) ";
+
+
+%typemap(scoercein) unsigned int, 
+                    unsigned long,
+                    double, 
+                    float,
+                    long,
+                    long long,
+     	            unsigned int[], 
+                    unsigned long[],
+                    double[], 
+                    float[],
+                    long[],
+                    long long[],
+     	            unsigned int[ANY], 
+                    unsigned long[ANY],
+                    double[ANY], 
+                    float[ANY],
+                    long[ANY],
+                    long long[ANY],
+     	            unsigned int *, 
+                    unsigned long *,
+                    double*, 
+                    float*,
+                    long*,
+                    long long *
+%{  $input = as.numeric($input) %}
+*/
+
+%typemap(scoercein) char *, string, std::string,
+string &, std::string &
+%{  $input = as($input, "character") %}
+
+%typemap(scoerceout) enum SWIGTYPE 
+  %{  $result = enumFromInteger($result, "$R_class") %}
+
+%typemap(scoerceout) enum SWIGTYPE &
+  %{  $result = enumFromInteger($result, "$R_class") %}
+
+%typemap(scoerceout) enum SWIGTYPE *
+  %{  $result = enumToInteger($result, "$R_class") %}
+
+
+%typemap(scoerceout) SWIGTYPE 
+  %{ class($result) <- "$&R_class" %}
+
+%typemap(scoerceout) SWIGTYPE & 
+  %{ class($result) <- "$R_class" %}
+
+%typemap(scoerceout) SWIGTYPE * 
+  %{ class($result) <- "$R_class" %}
+
+/* Override the SWIGTYPE * above. */
+%typemap(scoerceout) char,
+		     char *,
+		     char &,
+		     unsigned int, 
+		     unsigned int &, 
+                     unsigned long,
+                     unsigned long &,
+		     double, 
+		     double &,
+                     float,
+		     float &,
+                     long,
+		     long &,
+                     long long,
+		     long long &,
+                     int,
+		     int &,
+                     bool,
+		     bool &,
+		     string,
+		     std::string,
+		     string &,
+		     std::string &, 
+		     size_t,
+		     std::size_t,
+		     size_t &,
+		     std::size_t &,
+		     void
+ %{    %}
+
+
+#if 0
+ Just examining the values for a SWIGTYPE.
+
+%typemap(scoerceout) SWIGTYPE  %{
+
+  name = $1_name
+  type = $1_type
+  ltype = $1_ltype
+
+  mangle = $1_mangle
+  descriptor = $1_descriptor
+
+  pointer type = $*1_type
+  pointer ltype = $*1_ltype
+
+  pointer descriptor = $*1_descriptor
+  basetype = $*_basetype
+
+%}
+#endif
+
+
diff --git a/trunk/Lib/r/srun.swg b/trunk/Lib/r/srun.swg
new file mode 100644
index 0000000..71a508d
--- /dev/null
+++ b/trunk/Lib/r/srun.swg
@@ -0,0 +1,150 @@
+#                         srun.swg                            #
+#
+# This is the basic code that is needed at run time within R to
+# provide and define the relevant classes.  It is included
+# automatically in the generated code by copying the contents of
+# srun.swg into the newly created binding code.
+
+
+# This could be provided as a separate run-time library but this
+# approach allows the code to to be included directly into the
+# generated bindings and so removes the need to have and install an
+# additional library.  We may however end up with multiple copies of
+# this and some confusion at run-time as to which class to use. This
+# is an issue when we use NAMESPACES as we may need to export certain
+# classes.
+
+######################################################################
+
+if(length(getClassDef("RSWIGStruct")) == 0) 
+  setClass("RSWIGStruct", representation("VIRTUAL"))
+
+
+
+if(length(getClassDef("ExternalReference")) == 0) 
+# Should be virtual but this means it loses its slots currently
+#representation("VIRTUAL")
+  setClass("ExternalReference", representation( ref = "externalptr"))
+
+
+
+if(length(getClassDef("NativeRoutinePointer")) == 0) 
+  setClass("NativeRoutinePointer", 
+              representation(parameterTypes = "character",
+                             returnType = "character",
+                             "VIRTUAL"), 
+              contains = "ExternalReference")
+
+if(length(getClassDef("CRoutinePointer")) == 0) 
+  setClass("CRoutinePointer", contains = "NativeRoutinePointer")
+
+
+if(length(getClassDef("EnumerationValue")) == 0) 
+  setClass("EnumerationValue", contains = "integer")
+
+
+if(!isGeneric("copyToR")) 
+ setGeneric("copyToR",
+            function(value, obj = new(gsub("Ref$", "", class(value)))) 
+               standardGeneric("copyToR"
+           ))
+
+setGeneric("delete", function(obj) standardGeneric("delete"))
+
+
+SWIG_createNewRef = 
+function(className, ..., append = TRUE)
+{
+  f = get(paste("new", className, sep = "_"), mode = "function")
+
+  f(...)
+}
+
+if(!isGeneric("copyToC")) 
+ setGeneric("copyToC", 
+             function(value, obj = RSWIG_createNewRef(class(value)))
+              standardGeneric("copyToC"
+            ))
+
+
+# 
+defineEnumeration =
+function(name, .values, where = topenv(parent.frame()), suffix = "Value")
+{
+   # Mirror the class definitions via the E analogous to .__C__
+  defName = paste(".__E__", name, sep = "")
+  assign(defName,  .values,  envir = where)
+
+  if(nchar(suffix))
+    name = paste(name, suffix, sep = "")
+
+  setClass(name, contains = "EnumerationValue", where = where)
+}
+
+enumToInteger <- function(name,type)
+{
+   if (is.character(name)) {
+   ans <- as.integer(get(paste(".__E__", type, sep = ""))[name])
+   if (is.na(ans)) {warning("enum not found ", name, " ", type)}
+   ans
+   } 
+}
+
+enumFromInteger =
+function(i,type)
+{
+  itemlist <- get(paste(".__E__", type, sep=""))
+  names(itemlist)[match(i, itemlist)]
+}
+
+coerceIfNotSubclass =
+function(obj, type) 
+{
+    if(!is(obj, type)) {as(obj, type)} else obj
+}
+
+
+setClass("SWIGArray", representation(dims = "integer"), contains = "ExternalReference")
+
+setMethod("length", "SWIGArray", function(x) x@dims[1])
+
+
+defineEnumeration("SCopyReferences",
+                   .values = c( "FALSE" = 0, "TRUE" = 1, "DEEP" = 2))
+
+assert = 
+function(condition, message = "")
+{
+  if(!condition)
+    stop(message)
+
+  TRUE
+}
+
+
+if(FALSE) {
+print.SWIGFunction =
+function(x, ...)
+ {
+ }
+}
+
+
+#######################################################################
+
+R_SWIG_getCallbackFunctionStack =
+function()
+{
+    # No PACKAGE argument as we don't know what the DLL is.
+  .Call("R_SWIG_debug_getCallbackFunctionData")
+}
+
+R_SWIG_addCallbackFunctionStack =
+function(fun, userData = NULL)
+{
+    # No PACKAGE argument as we don't know what the DLL is.
+  .Call("R_SWIG_R_pushCallbackFunctionData", fun, userData)
+}
+
+
+#######################################################################
\ No newline at end of file
diff --git a/trunk/Lib/r/std_alloc.i b/trunk/Lib/r/std_alloc.i
new file mode 100644
index 0000000..87fa8d4
--- /dev/null
+++ b/trunk/Lib/r/std_alloc.i
@@ -0,0 +1 @@
+%include <std/std_alloc.i>
\ No newline at end of file
diff --git a/trunk/Lib/r/std_common.i b/trunk/Lib/r/std_common.i
new file mode 100644
index 0000000..fec0efe
--- /dev/null
+++ b/trunk/Lib/r/std_common.i
@@ -0,0 +1,2 @@
+%include <rstdcommon.swg>
+%include <std/std_common.i>
diff --git a/trunk/Lib/r/std_container.i b/trunk/Lib/r/std_container.i
new file mode 100644
index 0000000..076c1c6
--- /dev/null
+++ b/trunk/Lib/r/std_container.i
@@ -0,0 +1,2 @@
+%include <rcontainer.swg>
+%include <std/std_container.i>
diff --git a/trunk/Lib/r/std_deque.i b/trunk/Lib/r/std_deque.i
new file mode 100644
index 0000000..0c757ab
--- /dev/null
+++ b/trunk/Lib/r/std_deque.i
@@ -0,0 +1 @@
+%include<std/std_deque.i>
\ No newline at end of file
diff --git a/trunk/Lib/r/std_except.i b/trunk/Lib/r/std_except.i
new file mode 100644
index 0000000..af98428
--- /dev/null
+++ b/trunk/Lib/r/std_except.i
@@ -0,0 +1 @@
+%include <typemaps/std_except.swg>
diff --git a/trunk/Lib/r/std_pair.i b/trunk/Lib/r/std_pair.i
new file mode 100644
index 0000000..3ac7957
--- /dev/null
+++ b/trunk/Lib/r/std_pair.i
@@ -0,0 +1 @@
+%include<std/std_pair.i>
\ No newline at end of file
diff --git a/trunk/Lib/r/std_string.i b/trunk/Lib/r/std_string.i
new file mode 100644
index 0000000..dc1378a
--- /dev/null
+++ b/trunk/Lib/r/std_string.i
@@ -0,0 +1 @@
+%include <typemaps/std_string.swg>
diff --git a/trunk/Lib/r/std_vector.i b/trunk/Lib/r/std_vector.i
new file mode 100644
index 0000000..0336482
--- /dev/null
+++ b/trunk/Lib/r/std_vector.i
@@ -0,0 +1,10 @@
+%fragment("StdVectorTraits","header")
+%{
+%}
+
+#define %swig_vector_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_vector_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+
+
+%include <std/std_vector.i>
\ No newline at end of file
diff --git a/trunk/Lib/r/stl.i b/trunk/Lib/r/stl.i
new file mode 100644
index 0000000..9656ee6
--- /dev/null
+++ b/trunk/Lib/r/stl.i
@@ -0,0 +1,8 @@
+/* initial STL definition. extended as needed in each language */
+%include std_common.i
+%include std_vector.i
+%include std_string.i
+
+
+
+
diff --git a/trunk/Lib/r/typemaps.i b/trunk/Lib/r/typemaps.i
new file mode 100644
index 0000000..1f9b9c4
--- /dev/null
+++ b/trunk/Lib/r/typemaps.i
@@ -0,0 +1 @@
+%include <typemaps/typemaps.swg>
diff --git a/trunk/Lib/ruby/Makefile.swig b/trunk/Lib/ruby/Makefile.swig
new file mode 100644
index 0000000..a7f3ae3
--- /dev/null
+++ b/trunk/Lib/ruby/Makefile.swig
@@ -0,0 +1,42 @@
+# File : Makefile.swig
+# Makefile for a SWIG module.  Use this file if you are
+# producing a Ruby extension for general use or distribution.
+#
+# 1.  Prepare extconf.rb.
+# 2.  Modify this file as appropriate.
+# 3.  Type 'make -f Makefile.swig' to generate wrapper code and Makefile.
+# 4.  Type 'make' to build your extension.
+# 5.  Type 'make install' to install your extension.
+# 
+
+MODULE    = yourmodule
+FEATURE   = $(MODULE)
+INTERFACE = $(MODULE).i
+RUBY      = ruby
+SWIG      = swig
+
+# for C extension
+SWIGOPT   = -ruby
+WRAPPER   = $(MODULE)_wrap.c
+
+## for C++ extension
+#SWIGOPT   = -ruby -c++
+#WRAPPER   = $(MODULE)_wrap.cc
+
+
+swigall: $(WRAPPER) Makefile
+
+$(WRAPPER): $(INTERFACE)
+	$(SWIG) $(SWIGOPT) -o $@ $(INTERFACE)
+
+Makefile: extconf.rb
+	$(RUBY) extconf.rb
+	@if [ -f Makefile ] ; then\
+		echo "include Makefile.swig" >> Makefile;\
+	fi
+
+swigclean:
+	@if [ -f Makefile ] ; then\
+		make -f Makefile clean;\
+	fi
+	rm -f Makefile $(WRAPPER)
diff --git a/trunk/Lib/ruby/argcargv.i b/trunk/Lib/ruby/argcargv.i
new file mode 100644
index 0000000..ae1f6bb
--- /dev/null
+++ b/trunk/Lib/ruby/argcargv.i
@@ -0,0 +1,48 @@
+/* ------------------------------------------------------------
+ * --- Argc & Argv ---
+ * ------------------------------------------------------------ */
+ 
+/* ------------------------------------------------------------
+
+   Use it as follow:
+
+     %apply (int ARGC, char **ARGV) { (size_t argc, const char **argv) }
+
+     %inline %{
+
+     int mainApp(size_t argc, const char **argv) 
+     {
+       return argc;
+     }
+
+   then in the ruby side:
+
+     args = ["asdf", "asdf2"]
+     mainApp(args);
+
+ * ------------------------------------------------------------ */
+
+%typemap(in) (int ARGC, char **ARGV) {
+  if (rb_obj_is_kind_of($input,rb_cArray)) {
+    int i;
+    int size = RARRAY_LEN($input);
+    $1 = ($1_ltype) size;
+    $2 = (char **) malloc((size+1)*sizeof(char *));
+    VALUE *ptr = RARRAY_PTR($input);
+    for (i=0; i < size; i++, ptr++) {
+      $2[i]= STR2CSTR(*ptr);
+    }    
+    $2[i]=NULL;
+  } else {
+    $1 = 0; $2 = 0;
+    %argument_fail(SWIG_TypeError, "int ARGC, char **ARGV", $symname, $argnum);
+  }
+}
+
+%typemap(typecheck, precedence=SWIG_TYPECHECK_STRING_ARRAY) (int ARGC, char **ARGV) {
+  $1 = rb_obj_is_kind_of($input,rb_cArray);
+}
+
+%typemap(freearg) (int ARGC, char **ARGV) {
+  free((char *) $2);
+}
diff --git a/trunk/Lib/ruby/attribute.i b/trunk/Lib/ruby/attribute.i
new file mode 100644
index 0000000..779716c
--- /dev/null
+++ b/trunk/Lib/ruby/attribute.i
@@ -0,0 +1 @@
+%include <typemaps/attribute.swg>
diff --git a/trunk/Lib/ruby/carrays.i b/trunk/Lib/ruby/carrays.i
new file mode 100644
index 0000000..8f74cd9
--- /dev/null
+++ b/trunk/Lib/ruby/carrays.i
@@ -0,0 +1,6 @@
+%define %array_class(TYPE,NAME)
+  %array_class_wrap(TYPE,NAME,__getitem__,__setitem__)
+%enddef
+
+%include <typemaps/carrays.swg>
+
diff --git a/trunk/Lib/ruby/cdata.i b/trunk/Lib/ruby/cdata.i
new file mode 100644
index 0000000..3679659
--- /dev/null
+++ b/trunk/Lib/ruby/cdata.i
@@ -0,0 +1 @@
+%include <typemaps/cdata.swg>
diff --git a/trunk/Lib/ruby/cmalloc.i b/trunk/Lib/ruby/cmalloc.i
new file mode 100644
index 0000000..248f06b
--- /dev/null
+++ b/trunk/Lib/ruby/cmalloc.i
@@ -0,0 +1 @@
+%include <typemaps/cmalloc.swg>
diff --git a/trunk/Lib/ruby/cni.i b/trunk/Lib/ruby/cni.i
new file mode 100644
index 0000000..10a1403
--- /dev/null
+++ b/trunk/Lib/ruby/cni.i
@@ -0,0 +1,2 @@
+%include <gcj/cni.i>
+%include <jstring.i>
diff --git a/trunk/Lib/ruby/cpointer.i b/trunk/Lib/ruby/cpointer.i
new file mode 100644
index 0000000..d824792
--- /dev/null
+++ b/trunk/Lib/ruby/cpointer.i
@@ -0,0 +1 @@
+%include <typemaps/cpointer.swg>
diff --git a/trunk/Lib/ruby/cstring.i b/trunk/Lib/ruby/cstring.i
new file mode 100644
index 0000000..ede9c59
--- /dev/null
+++ b/trunk/Lib/ruby/cstring.i
@@ -0,0 +1 @@
+%include <typemaps/cstring.swg>
diff --git a/trunk/Lib/ruby/director.swg b/trunk/Lib/ruby/director.swg
new file mode 100644
index 0000000..9a6371a
--- /dev/null
+++ b/trunk/Lib/ruby/director.swg
@@ -0,0 +1,382 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * director.swg
+ *
+ * This file contains support for director classes that proxy
+ * method calls from C++ to Ruby extensions.
+ * ----------------------------------------------------------------------------- */
+
+/*
+  Use -DSWIG_DIRECTOR_NOUEH if you prefer to avoid the use of the
+  Undefined Exception Handler provided by swift
+*/
+#ifndef SWIG_DIRECTOR_NOUEH
+#ifndef SWIG_DIRECTOR_UEH
+#define SWIG_DIRECTOR_UEH
+#endif
+#endif
+
+#ifdef __cplusplus
+
+#include <string>
+#include <iostream>
+#include <map>
+
+namespace Swig {
+  /* memory handler */
+  struct GCItem 
+  {
+    virtual ~GCItem()
+    {
+    }
+
+    virtual ruby_owntype get_own() const
+    {
+      return 0;
+    }
+  };
+  
+  struct GCItem_var
+  {
+    GCItem_var(GCItem *item = 0) : _item(item)
+    {
+    }
+
+    GCItem_var& operator=(GCItem *item)
+    {
+      GCItem *tmp = _item;
+      _item = item;
+      delete tmp;
+      return *this;
+    }
+    
+    ~GCItem_var() 
+    {
+      delete _item;
+    }
+    
+    GCItem * operator->() const
+    {
+      return _item;
+    }
+    
+  private:
+    GCItem *_item;
+  };
+
+
+  template <typename Type>
+  struct GCItem_T : GCItem
+  {
+    GCItem_T(Type *ptr) : _ptr(ptr)
+    {
+    }
+    
+    virtual ~GCItem_T() 
+    {
+      delete _ptr;
+    }
+    
+  private:
+    Type *_ptr;
+  };
+
+  struct GCItem_Object : GCItem
+  {
+    GCItem_Object(ruby_owntype own) : _own(own)
+    {
+    }
+    
+    virtual ~GCItem_Object() 
+    {
+    }
+
+    ruby_owntype get_own() const
+    {
+      return _own;
+    }
+    
+  private:
+    ruby_owntype _own;
+  };
+
+
+  template <typename Type>
+  struct GCArray_T : GCItem
+  {
+    GCArray_T(Type *ptr) : _ptr(ptr)
+    {
+    }
+    
+    virtual ~GCArray_T() 
+    {
+      delete[] _ptr;
+    }
+    
+  private:
+    Type *_ptr;
+  };
+
+
+  /* body args */
+  struct body_args {
+    VALUE recv;
+    ID id;
+    int argc;
+    VALUE *argv;
+  };
+  
+  /* Base class for director exceptions */
+  class DirectorException {
+  protected:
+    VALUE swig_error;
+    std::string swig_msg;
+  protected:
+    DirectorException(VALUE error)
+      : swig_error(error)
+    {
+    }
+    
+    DirectorException(VALUE error, const char* hdr, const char* msg ="") 
+      : swig_error(error), swig_msg(hdr) {
+      if (strlen(msg)) {
+	swig_msg += " ";
+	swig_msg += msg;
+      }
+      if (swig_msg.size()) {
+	VALUE str = rb_str_new(swig_msg.data(), swig_msg.size());
+	swig_error = rb_exc_new3(error, str);
+      } else {
+	swig_error = error;
+      }
+    }
+  public:
+    VALUE getType() const  { 
+      return CLASS_OF(swig_error); 
+    }
+    VALUE getError() const {
+      return swig_error;
+    }
+    const std::string& getMessage() const 
+    {
+      return swig_msg;
+    }
+    
+    virtual ~DirectorException() {}
+  };
+  
+  /* unknown exception handler  */
+
+  class UnknownExceptionHandler 
+  {
+#ifdef SWIG_DIRECTOR_UEH
+    static void handler() {
+      try {
+	throw;
+      } catch (DirectorException& e) {
+	std::cerr << "Swig Director exception caught:" << std::endl
+		  << e.getMessage() << std::endl;
+      } catch (std::exception& e) {
+	std::cerr << "std::exception caught: "<< e.what() << std::endl;
+      } catch (...) {
+	std::cerr << "Unknown exception caught." << std::endl;
+      }      
+      std::cerr << std::endl
+		<< "Ruby interpreter traceback:" << std::endl;
+      std::cerr << std::endl;      
+      std::cerr << "This exception was caught by the SWIG unexpected exception handler." << std::endl
+		<< "Try using %feature(\"director:except\") to avoid reaching this point." << std::endl
+		<< std::endl
+		<< "Exception is being re-thrown, program will like abort/terminate." << std::endl;
+      throw;
+    }
+    
+  public:    
+    std::unexpected_handler old;
+    UnknownExceptionHandler(std::unexpected_handler nh = handler)
+    {
+      old = std::set_unexpected(nh);
+    }
+
+    ~UnknownExceptionHandler()
+    {
+      std::set_unexpected(old);
+    }
+#endif
+  };
+
+
+  /* Type mismatch in the return value from a Ruby method call */
+  class DirectorTypeMismatchException : public Swig::DirectorException {
+  public:
+    DirectorTypeMismatchException(VALUE error, const char *msg="")
+      : Swig::DirectorException(error, "Swig director type mismatch", msg) 
+    {
+    }
+
+    DirectorTypeMismatchException(const char *msg="")
+      : Swig::DirectorException(rb_eTypeError, "Swig director type mismatch", msg) 
+    {
+    }
+
+    static void raise(VALUE error, const char *msg) {
+      throw DirectorTypeMismatchException(error, msg);
+    }
+
+    static void raise(const char *msg) {
+      throw DirectorTypeMismatchException(msg);
+    }
+  };
+
+  /* Any Ruby exception that occurs during a director method call */
+  class DirectorMethodException : public Swig::DirectorException {
+  public:
+    DirectorMethodException(VALUE error) 
+      : Swig::DirectorException(error) {
+    }
+
+    DirectorMethodException(const char* msg = "") 
+      : Swig::DirectorException(rb_eRuntimeError, "Swig director method error.", msg) {
+    }
+    
+    static void raise(VALUE error)
+    {
+      throw DirectorMethodException(error);
+    }    
+  };
+
+  /* Attempted to call a pure virtual method via a director method */
+  class DirectorPureVirtualException : public Swig::DirectorException
+  {
+  public:
+    DirectorPureVirtualException(const char* msg = "") 
+      : DirectorException(rb_eRuntimeError, "Swig director pure virtual method called", msg)
+    { 
+    }
+
+    static void raise(const char *msg) 
+    {
+      throw DirectorPureVirtualException(msg);
+    }
+  };
+
+  /* Simple thread abstraction for pthreads on win32 */
+#ifdef __THREAD__
+# define __PTHREAD__
+# if defined(_WIN32) || defined(__WIN32__)
+#  define pthread_mutex_lock EnterCriticalSection
+#  define pthread_mutex_unlock LeaveCriticalSection
+#  define pthread_mutex_t CRITICAL_SECTION
+#  define SWIG_MUTEX_INIT(var) var
+# else
+#  include <pthread.h>
+#  define SWIG_MUTEX_INIT(var) var = PTHREAD_MUTEX_INITIALIZER 
+# endif
+#endif
+
+#ifdef  __PTHREAD__
+  struct Guard
+  {
+    pthread_mutex_t *_mutex;
+    
+    Guard(pthread_mutex_t &mutex) : _mutex(&mutex)
+    {
+      pthread_mutex_lock(_mutex);
+    }
+    
+    ~Guard()
+    {
+      pthread_mutex_unlock(_mutex);
+    }
+  };
+# define SWIG_GUARD(mutex) Guard _guard(mutex)
+#else
+# define SWIG_GUARD(mutex) 
+#endif
+
+  /* director base class */
+  class Director {
+  private:
+    /* pointer to the wrapped Ruby object */
+    VALUE swig_self;
+    /* flag indicating whether the object is owned by Ruby or c++ */
+    mutable bool swig_disown_flag;
+
+  public:
+    /* wrap a Ruby object, optionally taking ownership */
+    Director(VALUE self) : swig_self(self), swig_disown_flag(false) {
+    }
+
+    /* discard our reference at destruction */
+    virtual ~Director() {
+    }
+
+    /* return a pointer to the wrapped Ruby object */
+    VALUE swig_get_self() const { 
+      return swig_self; 
+    }
+
+    /* acquire ownership of the wrapped Ruby object (the sense of "disown"
+     * is from Ruby) */
+    void swig_disown() const { 
+      if (!swig_disown_flag) { 
+        swig_disown_flag = true;
+      } 
+    }
+
+  /* ownership management */
+  private:
+    typedef std::map<void*, GCItem_var> ownership_map;
+    mutable ownership_map owner;
+#ifdef __PTHREAD__
+    static pthread_mutex_t swig_mutex_own;
+#endif
+
+  public:
+    template <typename Type>
+    void swig_acquire_ownership_array(Type *vptr)  const
+    {
+      if (vptr) {
+	SWIG_GUARD(swig_mutex_own);
+	owner[vptr] = new GCArray_T<Type>(vptr);
+      }
+    }
+    
+    template <typename Type>
+    void swig_acquire_ownership(Type *vptr)  const
+    {
+      if (vptr) {	
+	SWIG_GUARD(swig_mutex_own);
+	owner[vptr] = new GCItem_T<Type>(vptr);
+      }
+    }
+
+    void swig_acquire_ownership_obj(void *vptr, ruby_owntype own) const
+    {
+      if (vptr && own) {
+	SWIG_GUARD(swig_mutex_own);
+	owner[vptr] = new GCItem_Object(own);
+      }
+    }
+    
+    ruby_owntype swig_release_ownership(void *vptr) const
+    {
+      ruby_owntype own = 0;
+      if (vptr) {
+	SWIG_GUARD(swig_mutex_own);
+	ownership_map::iterator iter = owner.find(vptr);
+	if (iter != owner.end()) {
+	  own = iter->second->get_own();
+	  owner.erase(iter);
+	}
+      }
+      return own;
+    }
+  };
+}
+
+#endif /* __cplusplus */
+
+
diff --git a/trunk/Lib/ruby/embed.i b/trunk/Lib/ruby/embed.i
new file mode 100644
index 0000000..ad38190
--- /dev/null
+++ b/trunk/Lib/ruby/embed.i
@@ -0,0 +1,16 @@
+%wrapper %{
+
+#include "ruby.h"
+
+int
+main(argc, argv)
+    int argc;
+    char **argv;
+{
+    ruby_init();
+    ruby_options(argc, argv);
+    ruby_run();
+    return 0;
+}
+
+%}
diff --git a/trunk/Lib/ruby/exception.i b/trunk/Lib/ruby/exception.i
new file mode 100644
index 0000000..1e80d96
--- /dev/null
+++ b/trunk/Lib/ruby/exception.i
@@ -0,0 +1,5 @@
+%include <typemaps/exception.swg>
+
+%insert("runtime") {
+  %define_as(SWIG_exception(code, msg), %block(%error(code, msg);))
+}
diff --git a/trunk/Lib/ruby/extconf.rb b/trunk/Lib/ruby/extconf.rb
new file mode 100644
index 0000000..3bac8cc
--- /dev/null
+++ b/trunk/Lib/ruby/extconf.rb
@@ -0,0 +1,9 @@
+require 'mkmf'
+
+dir_config('yourlib')
+
+if have_header('yourlib.h') and have_library('yourlib', 'yourlib_init')
+  # If you use swig -c option, you may have to link libswigrb.
+  # have_library('swigrb')
+  create_makefile('yourlib')
+end
diff --git a/trunk/Lib/ruby/extra-install.list b/trunk/Lib/ruby/extra-install.list
new file mode 100644
index 0000000..4610fa8
--- /dev/null
+++ b/trunk/Lib/ruby/extra-install.list
@@ -0,0 +1,3 @@
+# see top-level Makefile.in
+Makefile.swig
+extconf.rb
diff --git a/trunk/Lib/ruby/factory.i b/trunk/Lib/ruby/factory.i
new file mode 100644
index 0000000..46a0a87
--- /dev/null
+++ b/trunk/Lib/ruby/factory.i
@@ -0,0 +1 @@
+%include <typemaps/factory.swg>
diff --git a/trunk/Lib/ruby/file.i b/trunk/Lib/ruby/file.i
new file mode 100644
index 0000000..54ed0a6
--- /dev/null
+++ b/trunk/Lib/ruby/file.i
@@ -0,0 +1,32 @@
+// FILE *
+%{
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include "rubyio.h"
+#ifdef __cplusplus
+}
+#endif
+%}
+
+%typemap(in) FILE *READ {
+    OpenFile *of;
+    GetOpenFile($input, of);
+    rb_io_check_readable(of);
+    $1 = GetReadFile(of);
+    rb_read_check($1);
+}
+
+%typemap(in) FILE *READ_NOCHECK {
+    OpenFile *of;
+    GetOpenFile($input, of);
+    rb_io_check_readable(of);
+    $1 = GetReadFile(of);
+}
+
+%typemap(in) FILE *WRITE {
+    OpenFile *of;
+    GetOpenFile($input, of);
+    rb_io_check_writable(of);
+    $1 = GetWriteFile(of);
+}
diff --git a/trunk/Lib/ruby/jstring.i b/trunk/Lib/ruby/jstring.i
new file mode 100644
index 0000000..17efa97
--- /dev/null
+++ b/trunk/Lib/ruby/jstring.i
@@ -0,0 +1,44 @@
+%include <typemaps/valtypes.swg>
+
+%fragment(SWIG_AsVal_frag(jstring),"header") {
+SWIGINTERN int
+SWIG_AsVal(jstring)(VALUE obj, jstring *val)
+{
+  if (NIL_P(obj)){
+    if (val) *val = 0;
+    return SWIG_OK;
+  } 
+  if (TYPE(obj) == T_STRING) {
+    if (val) {
+      char *cstr = rb_string_value_ptr(&(obj));
+      jsize len = RSTRING_LEN(obj);
+      *val = JvNewStringLatin1(cstr, len);
+    }
+    return SWIG_NEWOBJ;
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment(SWIG_From_frag(jstring),"header") {
+SWIGINTERNINLINE VALUE
+SWIG_From(jstring)(jstring val)
+{
+  if (!val) {
+    return Qnil;
+  } else {
+    jint len = JvGetStringUTFLength(val);
+    char buf[len];
+    JvGetStringUTFRegion(val, 0, len, buf);
+    return rb_str_new(buf,len);
+  }
+}
+}
+
+%typemaps_asvalfrom(%checkcode(STRING),
+		    %arg(SWIG_AsVal(jstring)), 
+		    %arg(SWIG_From(jstring)), 
+		    %arg(SWIG_AsVal_frag(jstring)), 
+		    %arg(SWIG_From_frag(jstring)), 
+		    java::lang::String *);
+
diff --git a/trunk/Lib/ruby/progargcargv.i b/trunk/Lib/ruby/progargcargv.i
new file mode 100644
index 0000000..a2843c3
--- /dev/null
+++ b/trunk/Lib/ruby/progargcargv.i
@@ -0,0 +1,34 @@
+/*
+int PROG_ARGC
+char **PROG_ARGV
+
+    Some C function receive argc and argv from C main function.
+    This typemap provides ignore typemap which pass Ruby ARGV contents
+    as argc and argv to C function.
+*/
+
+
+
+// argc and argv
+%typemap(in,numinputs=0) int PROG_ARGC {
+    $1 = RARRAY_LEN(rb_argv) + 1;
+}
+
+%typemap(in,numinputs=0) char **PROG_ARGV {
+    int i, n;
+    VALUE ary = rb_eval_string("[$0] + ARGV");
+    n = RARRAY_LEN(ary);
+    $1 = (char **)malloc(n + 1);
+    for (i = 0; i < n; i++) {
+	VALUE v = rb_obj_as_string(RARRAY_PTR(ary)[i]);
+	$1[i] = (char *)malloc(RSTRING_LEN(v) + 1);
+	strcpy($1[i], RSTRING_PTR(v));
+    }
+}
+
+%typemap(freearg) char **PROG_ARGV {
+    int i, n = RARRAY_LEN(rb_argv) + 1;
+    for (i = 0; i < n; i++) free($1[i]);
+    free($1);
+}
+
diff --git a/trunk/Lib/ruby/ruby.swg b/trunk/Lib/ruby/ruby.swg
new file mode 100644
index 0000000..efa8ec2
--- /dev/null
+++ b/trunk/Lib/ruby/ruby.swg
@@ -0,0 +1,72 @@
+/* ------------------------------------------------------------
+ * ruby.swg
+ *
+ * Ruby configuration module.
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ * The Ruby auto rename rules 
+ * ------------------------------------------------------------ */
+#if defined(SWIG_RUBY_AUTORENAME)
+/* Class names are CamelCase */
+%rename("%(camelcase)s", %$isclass) ""; 
+
+/* Constants created by %constant or #define are UPPER_CASE */
+%rename("%(uppercase)s", %$isconstant) "";
+
+/* SWIG only considers static class members with inline intializers
+	 to be constants.  For examples of what is and isn't considered
+	 a constant by SWIG see naming.i in the Ruby test suite. */
+%rename("%(uppercase)s", %$ismember, %$isvariable,%$isimmutable,%$isstatic,%$hasvalue,%$hasconsttype) ""; 
+
+/* Enums are mapped to constants but all we do is make sure the
+   first letter is uppercase */
+%rename("%(firstuppercase)s", %$isenumitem) "";
+
+/* Method names should be lower_case_with_underscores */
+%rename("%(undercase)s", %$isfunction, %$not %$ismemberget, %$not %$ismemberset) "";
+#endif
+
+/* ------------------------------------------------------------
+ *  Inner macros 
+ * ------------------------------------------------------------ */
+%include <rubymacros.swg>
+
+
+/* ------------------------------------------------------------
+ *  The runtime part
+ * ------------------------------------------------------------ */
+%include <rubyruntime.swg>
+
+/* ------------------------------------------------------------
+ *  Special user directives
+ * ------------------------------------------------------------ */
+%include <rubyuserdir.swg>
+
+/* ------------------------------------------------------------
+ *  Typemap specializations
+ * ------------------------------------------------------------ */
+%include <rubytypemaps.swg>
+
+/* ------------------------------------------------------------
+ *  Overloaded operator support
+ * ------------------------------------------------------------ */
+%include <rubyopers.swg>
+
+/* ------------------------------------------------------------
+ * Warnings for Ruby keywords 
+ * ------------------------------------------------------------ */
+%include <rubykw.swg>
+
+/* ------------------------------------------------------------
+ * Documentation for common Ruby methods 
+ * ------------------------------------------------------------ */
+%include <rubyautodoc.swg>
+
+/* ------------------------------------------------------------
+ * The Ruby initialization function 
+ * ------------------------------------------------------------ */
+%include <rubyinit.swg>
+
+
+
diff --git a/trunk/Lib/ruby/rubyapi.swg b/trunk/Lib/ruby/rubyapi.swg
new file mode 100644
index 0000000..e007757
--- /dev/null
+++ b/trunk/Lib/ruby/rubyapi.swg
@@ -0,0 +1,36 @@
+/* -----------------------------------------------------------------------------
+ * Ruby API portion that goes into the runtime
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+SWIGINTERN VALUE
+SWIG_Ruby_AppendOutput(VALUE target, VALUE o) {
+  if (NIL_P(target)) {
+    target = o;
+  } else {
+    if (TYPE(target) != T_ARRAY) {
+      VALUE o2 = target;
+      target = rb_ary_new();
+      rb_ary_push(target, o2);
+    }
+    rb_ary_push(target, o);
+  }
+  return target;
+}
+
+/* For ruby1.8.4 and earlier. */
+#ifndef RUBY_INIT_STACK
+   RUBY_EXTERN void Init_stack(VALUE* addr);
+#  define RUBY_INIT_STACK \
+   VALUE variable_in_this_stack_frame; \
+   Init_stack(&variable_in_this_stack_frame);
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/trunk/Lib/ruby/rubyautodoc.swg b/trunk/Lib/ruby/rubyautodoc.swg
new file mode 100644
index 0000000..ade4bde
--- /dev/null
+++ b/trunk/Lib/ruby/rubyautodoc.swg
@@ -0,0 +1,110 @@
+/**
+ * @file   rubyautodoc.swg
+ * @author gga
+ * @date   Wed May  2 16:41:59 2007
+ * 
+ * @brief  This file implements autodoc typemaps for some common
+ *         ruby methods.
+ * 
+ * 
+ */
+
+%define AUTODOC(func, str)
+  %feature("autodoc", str) func;
+%enddef
+
+
+AUTODOC(to_i, "Convert $class to an Integer");
+AUTODOC(to_f, "Convert $class to a Float");
+AUTODOC(coerce, "Coerce class to a number");
+AUTODOC(to_a, "Convert $class to an Array");
+AUTODOC(to_s, "Convert class to a String representation");
+AUTODOC(inspect, "Inspect class and its contents");
+
+AUTODOC(at, "Return element at a certain index");
+AUTODOC(__getitem__, "Element accessor/slicing");
+AUTODOC(__setitem__, "Element setter/slicing");
+AUTODOC(slice, "Return a slice (portion of) the $class");
+
+AUTODOC(push, "Add an element at the end of the $class");
+AUTODOC(pop, "Remove and return element at the end of the $class");
+AUTODOC(shift, "Remove and return element at the beginning of the $class");
+AUTODOC(unshift, "Add one or more elements at the beginning of the $class");
+AUTODOC(first, "Return the first element in $class");
+AUTODOC(last, "Return the last element in $class");
+
+
+//
+// Common Object methods
+//
+AUTODOC(hash, "Hashing function for class");
+AUTODOC(dup, "Create a duplicate of the class and unfreeze it if needed");
+AUTODOC(clone, "Create a duplicate of the class");
+
+//
+// Container methods
+//
+AUTODOC(empty, "Check if $class is empty");
+AUTODOC(size, "Size or Length of the $class");
+AUTODOC(insert, "Insert one or more new elements in the $class");
+
+//
+// Iterator methods (block)
+//
+AUTODOC(each, "Iterate thru each element in the $class.  A block must be provided");
+AUTODOC(find, "Find an element in the class");
+AUTODOC(each_key, "Iterate thru each key element in the $class.  A block must be provided");
+AUTODOC(each_value, "Iterate thru each key element in the $class.  A block must be provided");
+AUTODOC(reject, "Iterate thru each element in the $class and reject those that fail a condition returning a new $class.  A block must be provided");
+AUTODOC(reject_bang, "Iterate thru each element in the $class and reject those that fail a condition.  A block must be provided.  $class is modified in place");
+AUTODOC(select, "Iterate thru each element in the $class and select those that match a condition.  A block must be provided");
+AUTODOC(delete_at, "Delete an element at a certain index");
+AUTODOC(__delete__, "Delete a matching element");
+
+
+//
+// Hash methods
+//
+AUTODOC(keys, "Return an Array of key elements");
+AUTODOC(values, "Return an Array of value elements");
+AUTODOC(values_at, "Return an Array of value elements matching the conditions");
+
+
+//
+// Operators
+//
+#ifdef __cplusplus
+AUTODOC(operator==, "Equality comparison operator");
+AUTODOC(operator<=, "Lower or equal comparison operator");
+AUTODOC(operator>=, "Higher or equal comparison operator");
+AUTODOC(operator<, "Lower than comparison operator");
+AUTODOC(operator>, "Higher than comparison operator");
+AUTODOC(operator<<, "Left shifting or appending operator");
+AUTODOC(operator>>, "Right shifting operator or extracting operator");
+AUTODOC(operator+, "Add operator");
+AUTODOC(operator-, "Substraction operator");
+AUTODOC(operator+(), "Positive operator");
+AUTODOC(operator-(), "Negation operator");
+AUTODOC(operator&, "AND operator");
+AUTODOC(operator|, "OR operator");
+AUTODOC(operator^, "XOR operator");
+AUTODOC(operator~, "Invert operator");
+#endif
+AUTODOC(__eq__, "Equality comparison operator");
+AUTODOC(__le__, "Lower or equal comparison operator");
+AUTODOC(__ge__, "Higher or equal comparison operator");
+AUTODOC(__lt__, "Lower than comparison operator");
+AUTODOC(__gt__, "Higher than comparison operator");
+AUTODOC(__lshift__, "Left shifting or appending operator");
+AUTODOC(__rshift__, "Right shifting operator or extracting operator");
+AUTODOC(__add___, "Add operator");
+AUTODOC(__sub__, "Substraction operator");
+AUTODOC(__pos__, "Positive operator");
+AUTODOC(__neg__, "Negation operator");
+AUTODOC(__and__, "AND operator");
+AUTODOC(__or__, "OR operator");
+AUTODOC(__xor__, "XOR operator");
+AUTODOC(__negate__, "Invert operator");
+AUTODOC(__pow__, "Exponential operator");
+AUTODOC(__divmod__, "Modulo of division");
+AUTODOC(__cmp__, "Comparison operator.  Returns < 0 for less than, 0 for equal or > 1 for higher than.");
diff --git a/trunk/Lib/ruby/rubyclasses.swg b/trunk/Lib/ruby/rubyclasses.swg
new file mode 100644
index 0000000..db54826
--- /dev/null
+++ b/trunk/Lib/ruby/rubyclasses.swg
@@ -0,0 +1,395 @@
+#ifdef __cplusplus
+
+/*
+  GC_VALUE is used as a replacement of Ruby's VALUE.
+  GC_VALUE automatically handles registering and unregistering
+  of the underlying Ruby object with the GC.
+
+  It can be used if you want to create STL containers of VALUEs, such as:
+  
+     std::vector< GC_VALUE >;
+
+  or as a member variable:
+  
+     struct A {
+       GC_VALUE _obj;
+       A(VALUE o) : _obj(o) {
+       }
+     };
+
+   or as a input/output value (not much use for this, as VALUE works just as
+   well here, thou):
+
+     GC_VALUE func(GC_VALUE obj) { 
+       GC_VALUE out = rb_obj_classname(obj);
+       return out;
+     }
+
+
+   GC_VALUE is 'visible' at the wrapped side, so you can do:
+
+      %template(RubyVector) std::vector<swig::GC_VALUE>;
+
+   and all the proper typemaps will be used.
+   
+*/
+
+namespace swig {
+
+  %nodirector GC_VALUE;
+
+  // We ignore the constructor so that user can never create a GC_VALUE 
+  // manually
+  %ignore GC_VALUE::GC_VALUE;
+
+  struct GC_VALUE {
+    VALUE inspect() const;
+    VALUE to_s() const;
+    GC_VALUE();
+  protected:
+    GC_VALUE( const GC_VALUE& );
+    ~GC_VALUE();
+  };
+
+  %exception GC_VALUE {};
+
+
+  %apply VALUE   {GC_VALUE};
+
+  // Make sure this is the last typecheck done
+  %typecheck(999999,noblock=1) GC_VALUE, GC_VALUE&, 
+    const GC_VALUE& { $1 = 1; };
+
+  /* For input */
+  %typemap(in,noblock=1) GC_VALUE* (GC_VALUE r), GC_VALUE& (GC_VALUE r)  {
+     r = $input; $1 = &r;
+   }
+
+  /* For output */
+  %typemap(out,noblock=1)  GC_VALUE {
+    $result = (VALUE)$1;
+  }
+  
+  %typemap(out,noblock=1)  GC_VALUE*, GC_VALUE const & {
+    $result = (VALUE)*$1;
+  }
+
+  %ignore LANGUAGE_OBJ;
+  typedef GC_VALUE LANGUAGE_OBJ;
+}
+
+
+%{
+namespace swig {
+  class GC_VALUE {
+  protected:
+    // Hash of all GC_VALUE's currently in use
+    static VALUE _hash;
+
+    VALUE  _obj;
+
+    static ID hash_id;
+    static ID   lt_id;
+    static ID   gt_id;
+    static ID   eq_id;
+    static ID   le_id;
+    static ID   ge_id;
+
+    static ID  pos_id;
+    static ID  neg_id;
+    static ID  inv_id;
+
+    static ID  add_id;
+    static ID  sub_id;
+    static ID  mul_id;
+    static ID  div_id;
+    static ID  mod_id;
+
+    static ID  and_id;
+    static ID   or_id;
+    static ID  xor_id;
+
+    static ID  lshift_id;
+    static ID  rshift_id;
+
+    struct OpArgs
+    {
+      VALUE src;
+      ID    id;
+      int   nargs;
+      VALUE target;
+    };
+
+
+  public:
+    static void initialize()
+    {
+      if ( _hash == Qnil ) 
+	{ 
+	  _hash = rb_hash_new();
+	  rb_gc_register_address( &_hash );
+	}
+    }
+
+    // this function is never called.  Provided for symmetry only.
+    static void cleanup()
+    {
+      rb_gc_unregister_address( &_hash );
+    }
+
+    GC_VALUE() : _obj( Qnil )
+    {
+    }
+
+    GC_VALUE(const GC_VALUE& item) : _obj(item._obj)
+    {
+      GC_register();
+    }
+    
+    GC_VALUE(VALUE obj) :_obj(obj)
+    {
+      GC_register();
+    }
+    
+    ~GC_VALUE() 
+    {
+      GC_unregister();
+    }
+    
+    GC_VALUE & operator=(const GC_VALUE& item) 
+    {
+      GC_unregister();
+      _obj = item._obj;
+      GC_register();
+      return *this;
+    }
+
+    void GC_register()
+    {
+      if ( FIXNUM_P(_obj) || SPECIAL_CONST_P(_obj) || SYMBOL_P(_obj) ) 
+	return;
+      VALUE val = rb_hash_aref( _hash, _obj );
+      unsigned n = FIXNUM_P(val) ? NUM2UINT(val) : 0;
+      ++n;
+      rb_hash_aset( _hash, _obj, INT2NUM(n) );
+    }
+
+    void GC_unregister()
+    {
+      if ( FIXNUM_P(_obj) || SPECIAL_CONST_P(_obj) || SYMBOL_P(_obj) ) 
+	return;
+      // this test should not be needed but I've noticed some very erratic
+      // behavior of none being unregistered in some very rare situations.
+      if ( BUILTIN_TYPE(_obj) == T_NONE ) return;
+
+      VALUE val = rb_hash_aref( _hash, _obj );
+      unsigned n = FIXNUM_P(val) ? NUM2UINT(val) : 1;
+      --n;
+      if ( n )
+	rb_hash_aset( _hash, _obj, INT2NUM(n) );
+      else
+	rb_hash_delete( _hash, _obj );
+    }
+    
+    operator VALUE() const
+    {
+      return _obj;
+    }
+
+    VALUE inspect() const
+    {
+      return rb_inspect(_obj);
+    }
+
+    VALUE to_s() const
+    {
+      return rb_inspect(_obj);
+    }
+
+    static VALUE swig_protect_funcall( VALUE p )
+    {
+      OpArgs* args = (OpArgs*) p;
+      return rb_funcall( args->src, args->id, args->nargs, args->target );
+    }
+
+
+#define GC_VALUE_CMP( op_id, op, cmp, cmpval ) \
+    bool op( const GC_VALUE& other ) const \
+    { \
+      if ( FIXNUM_P(_obj) && FIXNUM_P(other._obj) ) \
+      { \
+	return _obj cmp other._obj; \
+      } \
+      bool  res = false; \
+      VALUE ret = Qnil; \
+      SWIG_RUBY_THREAD_BEGIN_BLOCK; \
+      if ( rb_respond_to( _obj, op_id ) == Qtrue ) \
+	{ \
+	  int status; \
+	  OpArgs  args; \
+          args.src    = _obj; \
+	  args.id     = op_id; \
+	  args.nargs  = 1; \
+	  args.target = VALUE(other); \
+	  ret = rb_protect( PROTECTFUNC(swig_protect_funcall), \
+                            VALUE(&args), &status ); \
+	} \
+      if ( ret == Qnil ) { \
+	VALUE a = rb_funcall(         _obj, hash_id, 0 ); \
+	VALUE b = rb_funcall( VALUE(other), hash_id, 0 ); \
+	res = a cmp b; \
+      } \
+      else \
+	{ \
+	  res = RTEST( ret ); \
+	} \
+      SWIG_RUBY_THREAD_END_BLOCK; \
+      return res; \
+    }
+
+
+    GC_VALUE_CMP( eq_id, operator==, ==, == 0 )
+    GC_VALUE_CMP( lt_id, operator<,  < , <  0 )
+    GC_VALUE_CMP( le_id, operator<=, <=, <= 0 )
+    GC_VALUE_CMP( gt_id, operator>,  > , >  0 )
+    GC_VALUE_CMP( ge_id, operator>=, >=, >= 0 )
+#undef GC_VALUE_CMP
+
+    bool operator!=( const GC_VALUE& other )
+    {
+      return !(this->operator==(other));
+    }
+
+#define GC_VALUE_UNARY( proc_id, op ) \
+    GC_VALUE op() const \
+    { \
+      VALUE ret = Qnil; \
+      SWIG_RUBY_THREAD_BEGIN_BLOCK; \
+      int status; \
+      OpArgs  args; \
+      args.src    = _obj; \
+      args.id     = proc_id; \
+      args.nargs  = 0; \
+      args.target = Qnil; \
+      ret = rb_protect( PROTECTFUNC(swig_protect_funcall), VALUE(&args), \
+			&status ); \
+      SWIG_RUBY_THREAD_END_BLOCK; \
+      return ret; \
+    }
+
+    GC_VALUE_UNARY( pos_id, operator+ )
+    GC_VALUE_UNARY( neg_id, operator- )
+    GC_VALUE_UNARY( inv_id, operator~ )
+#undef GC_VALUE_BINARY
+
+#define GC_VALUE_BINARY( proc_id, op ) \
+    GC_VALUE op( const GC_VALUE& other ) const \
+    { \
+      VALUE ret = Qnil; \
+      SWIG_RUBY_THREAD_BEGIN_BLOCK; \
+      int status; \
+      OpArgs  args; \
+      args.src    = _obj; \
+      args.id     = proc_id; \
+      args.nargs  = 1; \
+      args.target = VALUE(other); \
+      ret = rb_protect( PROTECTFUNC(swig_protect_funcall), VALUE(&args), \
+			&status ); \
+      SWIG_RUBY_THREAD_END_BLOCK; \
+      return GC_VALUE(ret); \
+    }
+
+    GC_VALUE_BINARY( add_id, operator+ );
+    GC_VALUE_BINARY( sub_id, operator- );
+    GC_VALUE_BINARY( mul_id, operator* );
+    GC_VALUE_BINARY( div_id, operator/ );
+    GC_VALUE_BINARY( mod_id, operator% );
+    
+    GC_VALUE_BINARY( and_id, operator& );
+    GC_VALUE_BINARY( xor_id, operator^ );
+    GC_VALUE_BINARY(  or_id, operator| );
+
+    GC_VALUE_BINARY( lshift_id, operator<< );
+    GC_VALUE_BINARY( rshift_id, operator>> );
+#undef GC_VALUE_BINARY
+
+  };
+
+  ID  GC_VALUE::hash_id = rb_intern("hash");
+  ID  GC_VALUE::lt_id = rb_intern("<");
+  ID  GC_VALUE::gt_id = rb_intern(">");
+  ID  GC_VALUE::eq_id = rb_intern("==");
+  ID  GC_VALUE::le_id = rb_intern("<=");
+  ID  GC_VALUE::ge_id = rb_intern(">=");
+
+  ID  GC_VALUE::pos_id = rb_intern("+@");
+  ID  GC_VALUE::neg_id = rb_intern("-@");
+  ID  GC_VALUE::inv_id = rb_intern("~");
+
+  ID  GC_VALUE::add_id = rb_intern("+");
+  ID  GC_VALUE::sub_id = rb_intern("-");
+  ID  GC_VALUE::mul_id = rb_intern("*");
+  ID  GC_VALUE::div_id = rb_intern("/");
+  ID  GC_VALUE::mod_id = rb_intern("%");
+
+  ID  GC_VALUE::and_id = rb_intern("&");
+  ID  GC_VALUE::or_id  = rb_intern("|");
+  ID  GC_VALUE::xor_id = rb_intern("^");
+
+  ID  GC_VALUE::lshift_id = rb_intern("<<");
+  ID  GC_VALUE::rshift_id = rb_intern(">>");
+
+  VALUE GC_VALUE::_hash = Qnil;
+
+  typedef GC_VALUE LANGUAGE_OBJ;
+
+} // namespace swig
+
+%}
+
+
+%init {
+  swig::GC_VALUE::initialize();
+}
+
+
+
+//
+// Fragment that contains traits to properly deal with GC_VALUE.
+// These functions may be invoked as a need of the from(), asval(),
+// asptr() and as() template functors, usually used in %typemaps.
+//
+%fragment(SWIG_Traits_frag(swig::GC_VALUE),"header",fragment="StdTraits") {
+namespace swig {
+  template <>  struct traits<GC_VALUE > {
+    typedef value_category category;
+    static const char* type_name() { return "GC_VALUE"; }
+  };
+  
+  template <>  struct traits_from<GC_VALUE> {
+    typedef GC_VALUE value_type;
+    static VALUE from(const value_type& val) {
+      return static_cast<VALUE>(val);
+    }
+  };
+  
+  template <> 
+  struct traits_check<GC_VALUE, value_category> {
+    static bool check(GC_VALUE) {
+      return true;
+    }
+  };
+  
+  template <>  struct traits_asval<GC_VALUE > {   
+    typedef GC_VALUE value_type;
+    static int asval(VALUE obj, value_type *val) {
+      if (val) *val = obj;
+      return SWIG_OK;
+    }
+  };
+} // swig
+} // %fragment(traits for swig::GC_VALUE)
+
+
+#endif  // __cplusplus
+
diff --git a/trunk/Lib/ruby/rubycomplex.swg b/trunk/Lib/ruby/rubycomplex.swg
new file mode 100644
index 0000000..afdb15e
--- /dev/null
+++ b/trunk/Lib/ruby/rubycomplex.swg
@@ -0,0 +1,129 @@
+/*
+  Defines the As/From conversors for double/float complex, you need to
+  provide complex Type, the Name you want to use in the conversors,
+  the complex Constructor method, and the Real and Imag complex
+  accesor methods.
+
+  See the std_complex.i and ccomplex.i for concrete examples.
+*/
+
+/*
+  Ruby does not have native complex numbers.  They are an extension in the
+  STD library.
+*/
+%{
+  static VALUE swig_rb_cComplex = Qnil;
+  static ID    swig_real_id = 0;
+  static ID    swig_imag_id = 0;
+
+  int Ruby_Is_Complex( VALUE obj )
+    {
+      return ( (rb_respond_to( obj, swig_real_id ) == Qtrue) &&
+	       (rb_respond_to( obj, swig_imag_id ) == Qtrue) );
+    }
+%}
+
+%init {
+  rb_require("complex");
+  swig_rb_cComplex = rb_const_get( rb_cObject, rb_intern("Complex") );
+  if( swig_rb_cComplex == Qnil )
+    rb_warn("Ruby's complex.so not found");
+  swig_real_id = rb_intern("real");
+  swig_imag_id = rb_intern("imag");
+}
+
+/* the common from conversor */
+%define %swig_fromcplx_conv(Type, Real, Imag)
+%fragment(SWIG_From_frag(Type),"header")
+{
+SWIGINTERNINLINE VALUE
+SWIG_From(Type)(%ifcplusplus(const Type&, Type) c)
+{
+  VALUE args[] = { 
+    rb_float_new(Real(c)), 
+    rb_float_new(Imag(c))
+  };
+  return rb_class_new_instance(2, args, swig_rb_cComplex);
+}
+}
+%enddef
+
+/* the double case */
+%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag)
+%fragment(SWIG_AsVal_frag(Type),"header",
+	  fragment=SWIG_AsVal_frag(double))
+{
+SWIGINTERN int
+SWIG_AsVal(Type) (VALUE o, Type* val)
+{
+  if ( Ruby_Is_Complex( o ) ) {
+    if (val) {
+      VALUE real = rb_funcall(o, swig_real_id, 0 );
+      VALUE imag = rb_funcall(o, swig_imag_id, 0 );
+      double re = 0;
+      SWIG_AsVal_double( real, &re );
+      double im = 0;
+      SWIG_AsVal_double( imag, &im );
+      *val = Constructor(re, im);
+    }
+    return SWIG_OK;
+  } else {
+    double d;    
+    int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d));
+    if (SWIG_IsOK(res)) {
+      if (val) *val = Constructor(d, 0.0);
+      return res;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+%swig_fromcplx_conv(Type, Real, Imag);
+%enddef
+
+/* the float case */
+%define %swig_cplxflt_conv(Type, Constructor, Real, Imag)
+%fragment(SWIG_AsVal_frag(Type),"header",
+          fragment=SWIG_AsVal_frag(float),
+          fragment=SWIG_AsVal_frag(double)) {
+SWIGINTERN int
+SWIG_AsVal(Type)(VALUE o, Type *val)
+{
+  if ( Ruby_Is_Complex( o ) ) {
+    VALUE real = rb_funcall(o, swig_real_id, 0 );
+    VALUE imag = rb_funcall(o, swig_imag_id, 0 );
+    double re = 0;
+    SWIG_AsVal_double( real, &re );
+    double im = 0;
+    SWIG_AsVal_double( imag, &im );
+    if ((-FLT_MAX <= re && re <= FLT_MAX) && 
+	(-FLT_MAX <= im && im <= FLT_MAX)) {
+      if (val) *val = Constructor(%numeric_cast(re, float),
+				  %numeric_cast(im, float));
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }
+  } else {
+    float re;
+    int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re));
+    if (SWIG_IsOK(res)) {
+      if (val) *val = Constructor(re, 0.0);
+      return res;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+%swig_fromcplx_conv(Type, Real, Imag);
+%enddef
+
+#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \
+%swig_cplxflt_conv(Type, Constructor, Real, Imag)
+
+
+#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \
+%swig_cplxdbl_conv(Type, Constructor, Real, Imag)
+
+
diff --git a/trunk/Lib/ruby/rubycontainer.swg b/trunk/Lib/ruby/rubycontainer.swg
new file mode 100644
index 0000000..919695e
--- /dev/null
+++ b/trunk/Lib/ruby/rubycontainer.swg
@@ -0,0 +1,1130 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * rubycontainer.swg
+ *
+ * Ruby sequence <-> C++ container wrapper
+ *
+ * This wrapper, and its iterator, allows a general use (and reuse) of
+ * the the mapping between C++ and Ruby, thanks to the C++
+ * templates.
+ *
+ * Of course, it needs the C++ compiler to support templates, but
+ * since we will use this wrapper with the STL containers, that should
+ * be the case.
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <iostream>
+%}
+
+
+#if !defined(SWIG_NO_EXPORT_ITERATOR_METHODS)
+# if !defined(SWIG_EXPORT_ITERATOR_METHODS)
+#  define SWIG_EXPORT_ITERATOR_METHODS SWIG_EXPORT_ITERATOR_METHODS
+# endif
+#endif
+
+%include <rubyiterators.swg>
+
+/**** The RubySequence C++ Wrap ***/
+
+%insert(header) %{
+#include <stdexcept>
+%}
+
+%include <std_except.i>
+
+
+%fragment("RubySequence_Base","header")
+{
+%#include <functional>
+
+
+namespace swig {
+  template < class T >
+  struct yield : public std::unary_function< T, bool >
+  {
+    bool
+    operator()( const T& v ) const
+    { 
+      return RTEST( rb_yield( swig::from< T >(v) ) );
+    }
+  };
+
+
+  inline size_t
+  check_index(ptrdiff_t i, size_t size, bool insert = false) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size)
+	return (size_t) (i + size);
+    } else if ( (size_t) i < size ) {
+      return (size_t) i;
+    } else if (insert && ((size_t) i == size)) {
+      return size;
+    }
+    
+    throw std::out_of_range("index out of range");
+  }
+
+  inline size_t
+  slice_index(ptrdiff_t i, size_t size) {
+    if ( i < 0 ) {
+      if ((size_t) (-i) <= size) {
+	return (size_t) (i + size);
+      } else {
+	throw std::out_of_range("index out of range");
+      }
+    } else {
+      return ( (size_t) i < size ) ? ((size_t) i) : size;
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::iterator
+  getpos(Sequence* self, Difference i)  {
+    typename Sequence::iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline typename Sequence::const_iterator
+  cgetpos(const Sequence* self, Difference i)  {
+    typename Sequence::const_iterator pos = self->begin();
+    std::advance(pos, check_index(i,self->size()));
+    return pos;
+  }
+
+  template <class Sequence, class Difference>
+  inline Sequence*
+  getslice(const Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+
+    if (jj > ii) {
+      typename Sequence::const_iterator vb = self->begin();
+      typename Sequence::const_iterator ve = self->begin();
+      std::advance(vb,ii);
+      std::advance(ve,jj);
+      return new Sequence(vb, ve);
+    } else {
+      return new Sequence();
+    }
+  }
+
+  template <class Sequence, class Difference, class InputSeq>
+  inline void
+  setslice(Sequence* self, Difference i, Difference j, const InputSeq& v) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj < ii) jj = ii;
+    size_t ssize = jj - ii;
+    if (ssize <= v.size()) {
+      typename Sequence::iterator sb = self->begin();
+      typename InputSeq::const_iterator vmid = v.begin();
+      std::advance(sb,ii);
+      std::advance(vmid, jj - ii);
+      self->insert(std::copy(v.begin(), vmid, sb), vmid, v.end());
+    } else {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+      self->insert(sb, v.begin(), v.end());
+    }
+  }
+
+  template <class Sequence, class Difference>
+  inline void
+  delslice(Sequence* self, Difference i, Difference j) {
+    typename Sequence::size_type size = self->size();
+    typename Sequence::size_type ii = swig::check_index(i, size, true);
+    typename Sequence::size_type jj = swig::slice_index(j, size);
+    if (jj > ii) {
+      typename Sequence::iterator sb = self->begin();
+      typename Sequence::iterator se = self->begin();
+      std::advance(sb,ii);
+      std::advance(se,jj);
+      self->erase(sb,se);
+    }
+  }
+}
+}
+
+%fragment("RubySequence_Cont","header",
+	  fragment="StdTraits",
+	  fragment="RubySequence_Base",
+	  fragment="ConstIterator_T")
+{
+namespace swig
+{
+
+  /**
+   * This class is a proxy class for references, used to return and set values
+   * of an element of a Ruby Array of stuff.
+   * It can be used by RubySequence_InputIterator to make it work with STL
+   * algorithms.
+   * 
+   */
+  template <class T>
+  struct RubySequence_Ref
+  {
+    RubySequence_Ref(VALUE  seq, int index)
+      : _seq(seq), _index(index)
+    {
+    }
+    
+    operator T () const
+    {
+      VALUE item = rb_ary_entry(_seq, _index );
+      try {
+	return swig::as<T>(item, true);
+      } catch (std::exception& e) {
+	char msg[1024];
+	sprintf(msg, "in sequence element %d ", _index);
+	VALUE lastErr = rb_gv_get("$!");
+	if ( lastErr == Qnil ) {
+	  %type_error(swig::type_name<T>());
+	}
+	VALUE str = rb_str_new2(msg);
+	str = rb_str_cat2( str, e.what() );
+	SWIG_Ruby_ExceptionType( NULL, str );
+	throw;
+      }
+    }
+
+    RubySequence_Ref& operator=(const T& v)
+    {
+      rb_ary_set(_seq, _index, swig::from< T >(v));
+      return *this;
+    }
+
+  private:
+    VALUE  _seq;
+    int _index;
+  };
+
+
+  /**
+   * This class is a proxy to return a pointer to a class, usually
+   * RubySequence_Ref. 
+   * It can be used by RubySequence_InputIterator to make it work with STL
+   * algorithms.
+   * 
+   */
+  template <class T>
+  struct RubySequence_ArrowProxy
+  {
+    RubySequence_ArrowProxy(const T& x): m_value(x) {}
+    const T* operator->() const { return &m_value; }
+    operator const T*() const { return &m_value; }
+    T m_value;
+  };
+
+
+  /**
+   * Input Iterator.  This adapator class is a random access iterator that 
+   * allows you to use STL algorithms with a Ruby class (a Ruby Array by default).
+   * 
+   */
+  template <class T, class Reference = RubySequence_Ref< T > >
+  struct RubySequence_InputIterator
+  {
+    typedef RubySequence_InputIterator<T, Reference > self;
+
+    typedef std::random_access_iterator_tag iterator_category;
+    typedef Reference reference;
+    typedef T value_type;
+    typedef T* pointer;
+    typedef ptrdiff_t difference_type;
+
+    RubySequence_InputIterator()
+    {
+    }
+
+    RubySequence_InputIterator(VALUE  seq, int index)
+      : _seq(seq), _index(index)
+    {
+    }
+
+    reference operator*() const
+    {
+      return reference(_seq, _index);
+    }
+
+    RubySequence_ArrowProxy<T>
+    operator->() const {
+      return RubySequence_ArrowProxy<T>(operator*());
+    }
+
+    bool operator==(const self& ri) const
+    {
+      return (_index == ri._index) && (_seq == ri._seq);
+    }
+
+    bool operator!=(const self& ri) const
+    {
+      return !(operator==(ri));
+    }
+
+    self& operator ++ ()
+    {
+      ++_index;
+      return *this;
+    }
+
+    self& operator -- ()
+    {
+      --_index;
+      return *this;
+    }
+
+    self& operator += (difference_type n)
+    {
+      _index += n;
+      return *this;
+    }
+
+    self operator +(difference_type n) const
+    {
+      return self(_seq, _index + n);
+    }
+
+    self& operator -= (difference_type n)
+    {
+      _index -= n;
+      return *this;
+    }
+
+    self operator -(difference_type n) const
+    {
+      return self(_seq, _index - n);
+    }
+
+    difference_type operator - (const self& ri) const
+    {
+      return _index - ri._index;
+    }
+
+    bool operator < (const self& ri) const
+    {
+      return _index < ri._index;
+    }
+
+    reference
+    operator[](difference_type n) const
+    {
+      return reference(_seq, _index + n);
+    }
+
+  private:
+    VALUE  _seq;
+    difference_type _index;
+  };
+
+
+  /**
+   * This adaptor class allows you to use a Ruby Array as if it was an STL
+   * container, giving it begin(), end(), and iterators.
+   * 
+   */
+  template <class T>
+  struct RubySequence_Cont
+  {
+    typedef RubySequence_Ref<T> reference;
+    typedef const RubySequence_Ref<T> const_reference;
+    typedef T value_type;
+    typedef T* pointer;
+    typedef int difference_type;
+    typedef int size_type;
+    typedef const pointer const_pointer;
+    typedef RubySequence_InputIterator<T, reference> iterator;
+    typedef RubySequence_InputIterator<T, const_reference> const_iterator;
+
+    RubySequence_Cont(VALUE  seq) : _seq(0)
+    {
+      if (!rb_obj_is_kind_of(seq, rb_cArray)) {
+	throw std::invalid_argument("an Array is expected");
+      }
+      _seq = seq;
+    }
+
+    ~RubySequence_Cont()
+    {
+    }
+
+    size_type size() const
+    {
+      return RARRAY_LEN(_seq);
+    }
+
+    bool empty() const
+    {
+      return size() == 0;
+    }
+
+    iterator begin()
+    {
+      return iterator(_seq, 0);
+    }
+
+    const_iterator begin() const
+    {
+      return const_iterator(_seq, 0);
+    }
+
+    iterator end()
+    {
+      return iterator(_seq, size());
+    }
+
+    const_iterator end() const
+    {
+      return const_iterator(_seq, size());
+    }
+
+    reference operator[](difference_type n)
+    {
+      return reference(_seq, n);
+    }
+
+    const_reference operator[](difference_type n)  const
+    {
+      return const_reference(_seq, n);
+    }
+
+    bool check(bool set_err = false) const
+    {
+      int s = (int) size();
+      for (int i = 0; i < s; ++i) {
+	VALUE item = rb_ary_entry(_seq, i );
+	if (!swig::check<value_type>(item)) {
+	  if (set_err) {
+	    char msg[1024];
+	    sprintf(msg, "in sequence element %d", i);
+	    SWIG_Error(SWIG_RuntimeError, msg);
+	  }
+	  return false;
+	}
+      }
+      return true;
+    }
+
+  private:
+    VALUE  _seq;
+  };
+
+}
+}
+
+/** 
+ * Macros used to typemap an STL iterator -> SWIGIterator conversion.
+ * 
+ */
+%define %swig_sequence_iterator(Sequence...)
+#if defined(SWIG_EXPORT_ITERATOR_METHODS)
+
+  %typemap(out,noblock=1,fragment="RubySequence_Cont")
+    const_iterator, const_reverse_iterator {
+    $result = SWIG_NewPointerObj(swig::make_const_iterator(%static_cast($1,const $type &),
+							   self),
+				 swig::ConstIterator::descriptor(),SWIG_POINTER_OWN);
+  }
+
+  %typemap(out,noblock=1,fragment="RubySequence_Cont")
+    iterator, reverse_iterator {
+    $result = SWIG_NewPointerObj(swig::make_nonconst_iterator(%static_cast($1,const $type &),
+							      self),
+				 swig::Iterator::descriptor(),SWIG_POINTER_OWN);
+  }
+
+  %typemap(out,noblock=1,fragment="RubySequence_Cont")
+    std::pair<const_iterator, const_iterator> {
+    $result = rb_ary_new2(2);
+    RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_const_iterator(%static_cast($1,const $type &).first),
+						swig::ConstIterator::descriptor(),SWIG_POINTER_OWN);
+    RARRAY_PTR($result)[1] = SWIG_NewPointerObj(swig::make_const_iterator(%static_cast($1,const $type &).second),
+						swig::ConstIterator::descriptor(),SWIG_POINTER_OWN);
+    RARRAY_LEN($result) = 2;
+  }
+
+  // std::map/multimap/set allow returning std::pair< iterator, iterator > from
+  // equal_range, but we cannot still modify the key, so the iterator is
+  // const.
+  %typemap(out,noblock=1,fragment="RubySequence_Cont")
+    std::pair<iterator, iterator> {
+    $result = rb_ary_new2(2);
+    RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_const_iterator(%static_cast($1,const $type &).first),
+						swig::ConstIterator::descriptor(),SWIG_POINTER_OWN);
+    RARRAY_PTR($result)[1] = SWIG_NewPointerObj(swig::make_const_iterator(%static_cast($1,const $type &).second),
+						swig::ConstIterator::descriptor(),SWIG_POINTER_OWN);
+    RARRAY_LEN($result) = 2;
+  }
+
+
+  %typemap(in,noblock=1,fragment="RubySequence_Cont")
+    const_iterator(swig::ConstIterator *iter = 0, int res),
+    const_reverse_iterator(swig::ConstIterator *iter = 0, int res) {
+    res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter),
+			  swig::ConstIterator::descriptor(), 0);
+    if (!SWIG_IsOK(res) || !iter) {
+      %argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+    } else {
+      swig::ConstIterator_T<$type > *iter_t = dynamic_cast<swig::ConstIterator_T<$type > *>(iter);
+      if (iter_t) {
+	$1 = iter_t->get_current();
+      } else {
+	%argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+      }
+    }
+  }
+
+  %typemap(in,noblock=1,fragment="RubySequence_Cont")
+    iterator(swig::Iterator *iter = 0, int res),
+    reverse_iterator(swig::Iterator *iter = 0, int res) {
+    res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::Iterator::descriptor(), 0);
+    if (!SWIG_IsOK(res) || !iter) {
+      %argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+    } else {
+      swig::Iterator_T<$type > *iter_t = dynamic_cast<swig::Iterator_T<$type > *>(iter);
+      if (iter_t) {
+	$1 = iter_t->get_current();
+      } else {
+	%argument_fail(SWIG_TypeError, "$type", $symname, $argnum);
+      }
+    }
+  }
+
+  %typecheck(%checkcode(ITERATOR),noblock=1,fragment="RubySequence_Cont")
+    const_iterator, const_reverse_iterator {
+    swig::ConstIterator *iter = 0;
+    int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), 
+			      swig::ConstIterator::descriptor(), 0);
+    $1 = (SWIG_IsOK(res) && iter && (dynamic_cast<swig::ConstIterator_T<$type > *>(iter) != 0));
+  }
+
+  %typecheck(%checkcode(ITERATOR),noblock=1,fragment="RubySequence_Cont")
+    iterator, reverse_iterator {
+    swig::ConstIterator *iter = 0;
+    int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), 
+			      swig::Iterator::descriptor(), 0);
+    $1 = (SWIG_IsOK(res) && iter && (dynamic_cast<swig::Iterator_T<$type > *>(iter) != 0));
+  }
+
+  %fragment("RubySequence_Cont");
+
+//   %newobject iterator;
+//   %newobject const_iterator;
+//   %extend  {
+//     swig::Iterator* iterator(VALUE* RUBY_SELF) {
+//       return swig::make_nonconst_iterator($self->begin(), $self->begin(), 
+// 				             $self->end(), *RUBY_SELF);
+//     }
+
+//     swig::ConstIterator* const_iterator(VALUE* RUBY_SELF) {
+//       return swig::make_const_iterator($self->begin(), $self->begin(), 
+// 					$self->end(), *RUBY_SELF);
+//     }
+//   }
+#endif //SWIG_EXPORT_ITERATOR_METHODS
+%enddef
+
+
+/**** The Ruby container methods  ****/
+
+
+
+%define %swig_container_methods(Container...)
+
+  %extend {
+
+  %newobject dup;
+  Container* dup()
+    {
+      return new Container(*$self);
+    }
+
+  }
+
+%enddef
+
+
+/**
+ * Macro used to define common Ruby printing methods for STL container
+ * 
+ */
+%define %swig_sequence_printing_methods(Sequence...)
+
+  %extend {
+
+  VALUE inspect()
+    {
+      Sequence::const_iterator i = $self->begin();
+      Sequence::const_iterator e = $self->end();
+      VALUE str = rb_str_new2( swig::type_name< Sequence >() );
+      str = rb_str_cat2( str, " [" );
+      bool comma = false;
+      VALUE tmp;
+      for ( ; i != e; ++i, comma = true )
+	{
+	  if (comma) str = rb_str_cat2( str, "," );
+	  tmp = swig::from< Sequence::value_type >( *i );
+	  tmp = rb_inspect( tmp );
+	  str = rb_str_buf_append( str, tmp );
+	}
+      str = rb_str_cat2( str, "]" );
+      return str;
+    }
+
+  VALUE to_a()
+    {
+      Sequence::const_iterator i = $self->begin();
+      Sequence::const_iterator e = $self->end();
+      VALUE ary = rb_ary_new2( std::distance( i, e ) );
+      VALUE tmp;
+      for ( ; i != e; ++i )
+	{
+	  tmp = swig::from< Sequence::value_type >( *i );
+	  rb_ary_push( ary, tmp );
+	}
+      return ary;
+    }
+
+  VALUE to_s()
+    {
+      Sequence::iterator i = $self->begin();
+      Sequence::iterator e = $self->end();
+      VALUE str = rb_str_new2( "" );
+      VALUE tmp;
+      for ( ; i != e; ++i )
+	{
+	  tmp = swig::from< Sequence::value_type >( *i );
+	  tmp = rb_obj_as_string( tmp );
+	  str = rb_str_buf_append( str, tmp );
+	}
+      return str;
+    }
+}
+%enddef
+
+
+/**
+ * Macro used to add common methods to all STL sequence-type containers 
+ * 
+ */
+%define %swig_sequence_methods_common(Sequence...)
+  %swig_container_methods(%arg(Sequence))
+  %swig_sequence_iterator(%arg(Sequence))
+  %swig_sequence_printing_methods(%arg(Sequence))
+
+  %fragment("RubySequence_Base");
+
+  %extend {
+
+
+  VALUE slice( difference_type i, difference_type j )
+    {
+	if ( j <= 0 ) return Qnil;
+	std::size_t len = $self->size();
+	if ( i < 0 ) i = len - i;
+	j += i;
+	if ( static_cast<std::size_t>(j) >= len ) j = len-1;
+
+	VALUE r = Qnil;
+	try {
+	  r = swig::from< const Sequence* >( swig::getslice(self, i, j) );
+	}
+	catch( std::out_of_range )
+	  {
+	  }
+	return r;
+      }
+
+
+    Sequence* each()
+      {
+	if ( !rb_block_given_p() )
+	  rb_raise( rb_eArgError, "no block given");
+
+	VALUE r;
+	Sequence::const_iterator i = self->begin();
+	Sequence::const_iterator e = self->end();
+	for ( ; i != e; ++i )
+	  {
+	    r = swig::from< Sequence::value_type >(*i);
+	    rb_yield(r);
+	  }
+	
+	return self;
+      }
+
+    %newobject select;
+    Sequence* select() {
+      if ( !rb_block_given_p() )
+	rb_raise( rb_eArgError, "no block given" );
+
+      Sequence* r = new Sequence;
+      Sequence::const_iterator i = $self->begin();
+      Sequence::const_iterator e = $self->end();
+      for ( ; i != e; ++i )
+	{
+	  VALUE v = swig::from< Sequence::value_type >(*i);
+	  if ( RTEST( rb_yield(v) ) )
+	    $self->insert( r->end(), *i);
+	}
+	
+      return r;
+    }
+
+    %alias reject_bang "delete_if";
+    Sequence* reject_bang() {
+      if ( !rb_block_given_p() )
+	rb_raise( rb_eArgError, "no block given" );
+
+      Sequence::iterator i = self->begin();
+      Sequence::iterator e = self->end();
+      for ( ; i != e; )
+	{
+	  VALUE r = swig::from< Sequence::value_type >(*i);
+	  if ( RTEST( rb_yield(r) ) ) {
+	    $self->erase(i++);
+            e = self->end();
+	  } else {
+	    ++i;
+          }
+	}
+	
+      return self;
+    }
+
+    VALUE delete_at(difference_type i) {
+      VALUE r = Qnil;
+      try {
+	Sequence::iterator at = swig::getpos(self, i);
+	r = swig::from< Sequence::value_type >( *(at) );
+	$self->erase(at); 
+      }
+      catch (std::out_of_range)
+	{
+	}
+      return r;
+    }
+
+
+    VALUE __delete2__(const value_type& i) {
+      VALUE r = Qnil;
+      return r;
+    }
+
+  }
+%enddef
+
+
+/**
+ * Macro used to add functions for back insertion of values in
+ * STL Sequence containers
+ * 
+ */
+%define %swig_sequence_back_inserters( Sequence... )
+  %extend {
+
+    VALUE pop() {
+      if ($self->empty()) return Qnil;
+      Sequence::value_type x = self->back();
+      $self->pop_back();
+      return swig::from< Sequence::value_type >( x );
+    }
+
+    %alias push "<<";
+    const value_type push( const value_type& e ) {
+      $self->push_back( e );
+      return e;
+    }
+
+    %newobject reject;
+    Sequence* reject() {
+      if ( !rb_block_given_p() )
+	rb_raise( rb_eArgError, "no block given" );
+
+      Sequence* r = new Sequence;
+      std::remove_copy_if( $self->begin(), $self->end(),              
+			   std::back_inserter(*r),
+			   swig::yield< Sequence::value_type >() );
+      return r;
+    }
+
+  }
+%enddef
+
+
+/**
+ * Macro used to add functions for Sequences
+ * 
+ */
+%define %swig_sequence_methods(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence));
+  %swig_sequence_back_inserters(%arg(Sequence));
+
+  %extend {
+
+    VALUE at(difference_type i) const {
+      VALUE r = Qnil;
+      try {
+	r = swig::from< Sequence::value_type >( *(swig::cgetpos(self, i)) );
+      }
+      catch( std::out_of_range )
+	{
+	}
+      return r;
+    }
+
+    VALUE __getitem__(difference_type i, difference_type j) const {
+      if ( j <= 0 ) return Qnil;
+      std::size_t len = $self->size();
+      if ( i < 0 ) i = len - i;
+      j += i; if ( static_cast<std::size_t>(j) >= len ) j = len-1;
+
+      VALUE r = Qnil;
+      try {
+	r = swig::from< const Sequence* >( swig::getslice(self, i, j) );
+      }
+      catch( std::out_of_range )
+	{
+	}
+      return r;
+    }
+
+    VALUE __getitem__(difference_type i) const {
+      VALUE r = Qnil;
+      try {
+	r = swig::from< Sequence::value_type >( *(swig::cgetpos(self, i)) );
+      }
+      catch( std::out_of_range )
+	{
+	}
+      return r;
+    }
+
+    VALUE __getitem__(VALUE i) const {
+      if ( rb_obj_is_kind_of( i, rb_cRange ) == Qfalse )
+	{
+	  rb_raise( rb_eTypeError, "not a valid index or range" );
+	}
+
+      VALUE r = Qnil;
+      static ID id_end   = rb_intern("end");
+      static ID id_start = rb_intern("begin");
+      static ID id_noend = rb_intern("exclude_end?");
+
+      VALUE start = rb_funcall( i, id_start, 0 );
+      VALUE end   = rb_funcall( i, id_end, 0 );
+      bool  noend = ( rb_funcall( i, id_noend, 0 ) == Qtrue );
+
+      int len = $self->size();
+
+      int s = NUM2INT( start );
+      if ( s < 0 ) s = len + s;
+      else if ( s >= len ) return Qnil;
+
+      int e = NUM2INT( end );
+      if ( e < 0 ) e = len + e;
+
+      if ( e < s ) return Qnil; //std::swap( s, e );
+
+      if ( noend ) e -= 1;
+      if ( e >= len ) e = len - 1;
+
+      return swig::from< Sequence* >( swig::getslice(self, s, e+1) );
+    }
+
+    VALUE __setitem__(difference_type i, const value_type& x)
+      {
+	std::size_t len = $self->size();
+	if ( i < 0 ) i = len - i;
+	else if ( static_cast<std::size_t>(i) >= len )
+	  $self->resize( i+1, x );
+	else
+	  *(swig::getpos(self,i)) = x;
+
+	return swig::from< Sequence::value_type >( x );
+      }
+
+    VALUE __setitem__(difference_type i, difference_type j, const Sequence& v) 
+      throw (std::invalid_argument) {
+
+      if ( j <= 0 ) return Qnil;
+      std::size_t len = $self->size();
+      if ( i < 0 ) i = len - i;
+      j += i; 
+      if ( static_cast<std::size_t>(j) >= len ) {
+	$self->resize( j+1, *(v.begin()) );
+	j = len-1;
+      }
+
+      VALUE r = Qnil;
+      swig::setslice(self, i, j, v);
+      r = swig::from< const Sequence* >( &v );
+      return r;
+    }
+
+ }
+%enddef
+
+// ..I don't think %swig_sequence_methods_val are really used at all anymore...
+%define %swig_sequence_methods_val(Sequence...)
+  %swig_sequence_methods_common(%arg(Sequence))
+  %extend {
+
+  VALUE __getitem__(difference_type i) {
+      VALUE r = Qnil;
+      try {
+	r = swig::from< Sequence::value_type >( *(swig::cgetpos(self, i)) );
+      }
+      catch( std::out_of_range )
+	{
+	}
+      return r;
+    }
+
+    VALUE __setitem__(difference_type i, value_type x) {
+      std::size_t len = $self->size();
+      if ( i < 0 ) i = len - i;
+      else if ( static_cast<std::size_t>(i) >= len )
+	$self->resize( i+1, x );
+      else *(swig::getpos(self,i)) = x;
+      return swig::from< Sequence::value_type >( x );
+    }
+ }
+%enddef
+
+
+/**
+ * Macro used to add functions for front insertion of
+ * elements in STL sequence containers that support it.
+ * 
+ */
+%define %swig_sequence_front_inserters( Sequence... )
+
+%extend {
+
+  VALUE shift()
+    {
+      if ($self->empty()) return Qnil;
+      Sequence::value_type x = self->front();
+      $self->erase( $self->begin() );
+      return swig::from< Sequence::value_type >( x );
+    }
+
+  %typemap(in) (int argc, VALUE* argv) {
+    $1 = argc - 1;
+    $2 = argv + 1;
+  }
+
+  Sequence* insert( difference_type pos, int argc, VALUE* argv, ... )
+    {
+      std::size_t len = $self->size();
+      std::size_t   i = swig::check_index( pos, len, true );
+      Sequence::iterator start;
+
+      VALUE elem = argv[0];
+      int idx = 0;
+      try {
+	Sequence::value_type val = swig::as<Sequence::value_type>( elem, true );
+	if ( i >= len ) {
+	  $self->resize(i-1, val);
+	  return $self;
+	}
+	start = $self->begin();
+	std::advance( start, i );
+	$self->insert( start++, val );
+
+	for ( ++idx; idx < argc; ++idx )
+	  {
+	    elem = argv[idx];
+	    val = swig::as<Sequence::value_type>( elem );
+	    $self->insert( start++, val );
+	  }
+
+      } 
+      catch( std::invalid_argument )
+	{
+	  rb_raise( rb_eArgError,
+		    Ruby_Format_TypeError( "", 
+					   swig::type_name<Sequence::value_type>(),
+					   __FUNCTION__, idx+2, elem ));
+	}
+
+
+      return $self;
+    }
+
+  %typemap(in) (int argc, VALUE* argv) {
+    $1 = argc;
+    $2 = argv;
+  }
+
+  Sequence* unshift( int argc, VALUE* argv, ... )
+    {
+      for ( int idx = argc-1; idx >= 0; --idx )
+	{
+	  Sequence::iterator start = $self->begin();
+	  VALUE elem = argv[idx];
+	  try {
+	    Sequence::value_type val = swig::as<Sequence::value_type>( elem, true );
+	    $self->insert( start, val );
+	  }
+	  catch( std::invalid_argument )
+	    {
+	      rb_raise( rb_eArgError,
+			Ruby_Format_TypeError( "", 
+					       swig::type_name<Sequence::value_type>(),
+					       __FUNCTION__, idx+2, elem ));
+	    }
+	}
+
+      return $self;
+    }
+
+}
+%enddef
+
+
+//
+// Common fragments
+//
+
+%fragment("StdSequenceTraits","header",
+	  fragment="StdTraits",
+	  fragment="RubySequence_Cont")
+{
+namespace swig {
+  template <class RubySeq, class Seq>
+  inline void
+  assign(const RubySeq& rubyseq, Seq* seq) {
+    // seq->assign(rubyseq.begin(), rubyseq.end()); // not used as not always implemented
+    typedef typename RubySeq::value_type value_type;
+    typename RubySeq::const_iterator it = rubyseq.begin();
+    for (;it != rubyseq.end(); ++it) {
+      seq->insert(seq->end(),(value_type)(*it));
+    }
+  }
+
+  template <class Seq, class T = typename Seq::value_type >
+  struct traits_asptr_stdseq {
+    typedef Seq sequence;
+    typedef T value_type;
+
+    static int asptr(VALUE obj, sequence **seq) {
+      if (rb_obj_is_kind_of(obj, rb_cArray) == Qtrue) {
+	try {
+	  RubySequence_Cont<value_type> rubyseq(obj);
+	  if (seq) {
+	    sequence *pseq = new sequence();
+	    assign(rubyseq, pseq);
+	    *seq = pseq;
+	    return SWIG_NEWOBJ;
+	  } else {
+	    return rubyseq.check() ? SWIG_OK : SWIG_ERROR;
+	  }
+	} catch (std::exception& e) {
+	  if (seq) {
+	    VALUE lastErr = rb_gv_get("$!");
+	    if (lastErr == Qnil) {
+	      rb_raise(rb_eTypeError, e.what());
+	    }
+	  }
+	  return SWIG_ERROR;
+	}
+      } else {
+	sequence *p;
+	if (SWIG_ConvertPtr(obj,(void**)&p,
+			    swig::type_info<sequence>(),0) == SWIG_OK) {
+	  if (seq) *seq = p;
+	  return SWIG_OLDOBJ;
+	}
+      }
+      return SWIG_ERROR;
+    }
+  };
+
+  // Partial specialization for GC_VALUE's.  No need to typecheck each
+  // element.
+  template< class Seq >
+  struct traits_asptr_stdseq< Seq, swig::GC_VALUE > {
+    typedef Seq sequence;
+    typedef swig::GC_VALUE value_type;
+
+    static int asptr(VALUE obj, sequence **seq) {
+      if (rb_obj_is_kind_of(obj, rb_cArray) == Qtrue) {
+	try {
+	  if (seq) {
+	    RubySequence_Cont<value_type> rubyseq(obj);
+	    sequence *pseq = new sequence();
+	    assign(rubyseq, pseq);
+	    *seq = pseq;
+	    return SWIG_NEWOBJ;
+	  } else {
+	    return true;
+	  }
+	} catch (std::exception& e) {
+	  if (seq) {
+	    VALUE lastErr = rb_gv_get("$!");
+	    if (lastErr == Qnil) {
+	      rb_raise(rb_eTypeError, e.what());
+	    }
+	  }
+	  return SWIG_ERROR;
+	}
+      } else {
+	sequence *p;
+	if (SWIG_ConvertPtr(obj,(void**)&p,
+			    swig::type_info<sequence>(),0) == SWIG_OK) {
+	  if (seq) *seq = p;
+	  return SWIG_OLDOBJ;
+	}
+      }
+      return SWIG_ERROR;
+    }
+  };
+
+  template <class Seq, class T = typename Seq::value_type >
+  struct traits_from_stdseq {
+    typedef Seq sequence;
+    typedef T value_type;
+    typedef typename Seq::size_type size_type;
+    typedef typename sequence::const_iterator const_iterator;
+
+    static VALUE from(const sequence& seq) {
+#ifdef SWIG_RUBY_EXTRA_NATIVE_CONTAINERS
+      swig_type_info *desc = swig::type_info<sequence>();
+      if (desc && desc->clientdata) {
+	return SWIG_NewPointerObj(new sequence(seq), desc, SWIG_POINTER_OWN);
+      }
+#endif
+      size_type size = seq.size();
+      if (size <= (size_type)INT_MAX) {
+	VALUE obj = rb_ary_new2((int)size);
+	int i = 0;
+	for (const_iterator it = seq.begin();
+	     it != seq.end(); ++it, ++i) {
+	  RARRAY_PTR(obj)[i] = swig::from< value_type >(*it);
+	}
+	RARRAY_LEN(obj) = size;
+	rb_obj_freeze(obj);  // treat as immutable result
+	return obj;
+      } else {
+	rb_raise(rb_eRangeError,"sequence size not valid in ruby");
+	return Qnil;
+      }
+    }
+  };
+}
+}
+
+
+%include <rubycontainer_extended.swg>
diff --git a/trunk/Lib/ruby/rubycontainer_extended.swg b/trunk/Lib/ruby/rubycontainer_extended.swg
new file mode 100644
index 0000000..360e399
--- /dev/null
+++ b/trunk/Lib/ruby/rubycontainer_extended.swg
@@ -0,0 +1,139 @@
+/**
+ * @file   rubycontainer_extended.swg
+ * @author gga
+ * @date   Sat May  5 05:36:01 2007
+ * 
+ * @brief  This file contains additional functions that make containers
+ *         behave closer to ruby primitive types.
+ *         However, some of these functions place some restrictions on
+ *         the underlying object inside of the container and the iterator
+ *        (that it has to have an == comparison function, that it has to have 
+ *         an = assignment operator, etc).
+ * 
+ */
+
+
+/** 
+ * Macro used to add extend functions that require operator== in object.
+ * 
+ * @param Container    STL container
+ * @param Type         class inside container
+ *
+ */
+%define %swig_container_with_equal_operator( Container, Type )
+
+  VALUE __delete__( const Type& val ) {
+    VALUE r = Qnil;
+    Container<Type >::iterator e = $self->end();
+    Container<Type >::iterator i = std::remove( $self->begin(), e, val );
+    // remove dangling elements now
+    $self->erase( i, e );
+    
+    if ( i != e )
+      r = swig::from< Type >( val );
+    else if ( rb_block_given_p() )
+      r = rb_yield(Qnil);
+    return r;
+  }
+
+%enddef  // end of  %swig_container_with_equal_operator
+
+
+
+
+/** 
+ * Macro used to add extend functions that require the assignment 
+ * operator (ie. = ) of contained class
+ * 
+ * @param Container    STL container
+ * @param Type         class inside container
+ * 
+ */
+
+%define %swig_container_with_assignment( Container, Type )
+
+
+  //
+  // map!  -- the equivalent of std::transform
+  //
+  Container< Type >* map_bang() {
+
+    if ( !rb_block_given_p() )
+      rb_raise( rb_eArgError, "No block given" );
+
+    VALUE r = Qnil;
+    Container< Type >::iterator i = $self->begin();
+    Container< Type >::iterator e = $self->end();
+
+    try {
+      for ( ; i != e; ++i )
+	{
+	  r = swig::from< Type >( *i );
+	  r = rb_yield( r );
+	  *i = swig::as< Type >( r );
+	}
+    }
+    catch ( const std::invalid_argument& )
+      {
+	rb_raise(rb_eTypeError,
+		 "Yield block did not return a valid element for " #Container);
+      }
+    
+    return $self;
+  }
+
+
+%enddef  // end of  %swig_container_with_assignment
+
+
+
+
+
+/** 
+ * Macro used to add all extended functions to a container
+ * 
+ * @param Container    STL container
+ * @param Type         class inside container
+ * 
+ */
+%define %swig_container_extend( Container, Type )
+
+%extend Container< Type > {
+
+  %swig_container_with_assignment( %arg(Container), Type );
+  %swig_container_with_equal_operator( %arg(Container), Type );
+
+}
+
+%enddef
+
+
+/** 
+ * Private macro used to add all extended functions to C/C++
+ * primitive types
+ * 
+ * @param Container an STL container, like std::vector (with no class template)
+ *
+ */
+%define %__swig_container_extend_primtypes( Container )
+
+%swig_container_extend( %arg( Container ), bool );
+%swig_container_extend( %arg( Container ), char );
+%swig_container_extend( %arg( Container ), short );
+%swig_container_extend( %arg( Container ), int );
+%swig_container_extend( %arg( Container ), unsigned short );
+%swig_container_extend( %arg( Container ), unsigned int );
+%swig_container_extend( %arg( Container ), float );
+%swig_container_extend( %arg( Container ), double );
+%swig_container_extend( %arg( Container ), std::complex );
+%swig_container_extend( %arg( Container ), std::string );
+%swig_container_extend( %arg( Container ), swig::GC_VALUE );
+%swig_container_extend( %arg( Container ), swig::GC_VALUE );
+
+%enddef
+
+
+%__swig_container_extend_primtypes( std::vector );
+%__swig_container_extend_primtypes( std::deque );
+%__swig_container_extend_primtypes( std::list );
+
diff --git a/trunk/Lib/ruby/rubydef.swg b/trunk/Lib/ruby/rubydef.swg
new file mode 100644
index 0000000..956aaee
--- /dev/null
+++ b/trunk/Lib/ruby/rubydef.swg
@@ -0,0 +1 @@
+/* empty file added for backward comp. */
diff --git a/trunk/Lib/ruby/rubyerrors.swg b/trunk/Lib/ruby/rubyerrors.swg
new file mode 100644
index 0000000..e256498
--- /dev/null
+++ b/trunk/Lib/ruby/rubyerrors.swg
@@ -0,0 +1,154 @@
+/* -----------------------------------------------------------------------------
+ * error manipulation
+ * ----------------------------------------------------------------------------- */
+
+
+/* Define some additional error types */
+#define SWIG_ObjectPreviouslyDeletedError  -100
+
+
+/* Define custom exceptions for errors that do not map to existing Ruby
+   exceptions.  Note this only works for C++ since a global cannot be
+   initialized by a funtion in C.  For C, fallback to rb_eRuntimeError.*/
+
+SWIGINTERN VALUE 
+getNullReferenceError(void) {
+  static int init = 0;
+  static VALUE rb_eNullReferenceError ;
+  if (!init) {
+    init = 1;
+    rb_eNullReferenceError = rb_define_class("NullReferenceError", rb_eRuntimeError);
+  }
+  return rb_eNullReferenceError;
+} 
+
+SWIGINTERN VALUE 
+getObjectPreviouslyDeletedError(void) {
+  static int init = 0;
+  static VALUE rb_eObjectPreviouslyDeleted ;
+  if (!init) {
+    init = 1;
+    rb_eObjectPreviouslyDeleted = rb_define_class("ObjectPreviouslyDeleted", rb_eRuntimeError);
+  }
+  return rb_eObjectPreviouslyDeleted;
+} 
+
+
+SWIGINTERN VALUE
+SWIG_Ruby_ErrorType(int SWIG_code) {
+  VALUE type;
+  switch (SWIG_code) {
+  case SWIG_MemoryError:
+    type = rb_eNoMemError;
+    break;
+  case SWIG_IOError:
+    type = rb_eIOError;
+    break;
+  case SWIG_RuntimeError:
+    type = rb_eRuntimeError;
+    break;
+  case SWIG_IndexError:
+    type = rb_eIndexError;
+    break;
+  case SWIG_TypeError:
+    type = rb_eTypeError;
+    break;
+  case SWIG_DivisionByZero:
+    type = rb_eZeroDivError;
+    break;
+  case SWIG_OverflowError:
+    type = rb_eRangeError;
+    break;
+  case SWIG_SyntaxError:
+    type = rb_eSyntaxError;
+    break;
+  case SWIG_ValueError:
+    type = rb_eArgError;
+    break;
+  case SWIG_SystemError:
+    type = rb_eFatal;
+    break;
+  case SWIG_AttributeError:
+    type = rb_eRuntimeError;
+    break;
+  case SWIG_NullReferenceError:
+    type = getNullReferenceError();
+    break;
+  case SWIG_ObjectPreviouslyDeletedError:
+    type = getObjectPreviouslyDeletedError();
+    break;
+  case SWIG_UnknownError:
+    type = rb_eRuntimeError;
+    break;
+  default:
+    type = rb_eRuntimeError;
+  }
+  return type;
+}
+
+
+/* This function is called when a user inputs a wrong argument to
+   a method.
+ */
+SWIGINTERN 
+const char* Ruby_Format_TypeError( const char* msg,
+				   const char* type, 
+				   const char* name, 
+				   const int argn,
+				   VALUE input )
+{
+  char buf[128];
+  VALUE str;
+  VALUE asStr;
+  if ( msg && *msg )
+    {
+      str = rb_str_new2(msg);
+    }
+  else
+    {
+      str = rb_str_new(NULL, 0);
+    }
+
+  str = rb_str_cat2( str, "Expected argument " );
+  sprintf( buf, "%d of type ", argn-1 );
+  str = rb_str_cat2( str, buf );
+  str = rb_str_cat2( str, type );
+  str = rb_str_cat2( str, ", but got " );
+  str = rb_str_cat2( str, rb_obj_classname(input) );
+  str = rb_str_cat2( str, " " );
+  asStr = rb_inspect(input);
+  if ( RSTRING_LEN(asStr) > 30 )
+    {
+      str = rb_str_cat( str, StringValuePtr(asStr), 30 );
+      str = rb_str_cat2( str, "..." );
+    }
+  else
+    {
+      str = rb_str_append( str, asStr );
+    }
+
+  if ( name )
+    {
+      str = rb_str_cat2( str, "\n\tin SWIG method '" );
+      str = rb_str_cat2( str, name );
+      str = rb_str_cat2( str, "'" );
+    }
+
+  return StringValuePtr( str );
+}
+
+/* This function is called when an overloaded method fails */
+SWIGINTERN 
+void Ruby_Format_OverloadedError(
+				 const int argc,
+				 const int maxargs,
+				 const char* method, 
+				 const char* prototypes 
+				 )
+{
+  const char* msg = "Wrong # of arguments";
+  if ( argc <= maxargs ) msg = "Wrong arguments";
+  rb_raise(rb_eArgError,"%s for overloaded method '%s'.\n"  
+	   "Possible C/C++ prototypes are:\n%s",
+	   msg, method, prototypes);
+}
diff --git a/trunk/Lib/ruby/rubyfragments.swg b/trunk/Lib/ruby/rubyfragments.swg
new file mode 100644
index 0000000..3c3b658
--- /dev/null
+++ b/trunk/Lib/ruby/rubyfragments.swg
@@ -0,0 +1,23 @@
+/*
+
+  Create a file with this name, 'rubyfragments.swg', in your working
+  directory and add all the %fragments you want to take precedence
+  over the ones defined by default by swig.
+
+  For example, if you add:
+  
+  %fragment(SWIG_AsVal_frag(int),"header") {
+   SWIGINTERNINLINE int
+   SWIG_AsVal(int)(VALUE obj, int *val)
+   { 
+     <your code here>;
+   }
+  }
+  
+  this will replace the code used to retrieve an integer value for all
+  the typemaps that need it, including:
+  
+    int, std::vector<int>, std::list<std::pair<int,int> >, etc.
+
+    
+*/
diff --git a/trunk/Lib/ruby/rubyhead.swg b/trunk/Lib/ruby/rubyhead.swg
new file mode 100644
index 0000000..8e6e2e7
--- /dev/null
+++ b/trunk/Lib/ruby/rubyhead.swg
@@ -0,0 +1,139 @@
+#include <ruby.h>
+
+/* Remove global macros defined in Ruby's win32.h */
+#ifdef write
+# undef write
+#endif
+#ifdef read
+# undef read
+#endif
+
+
+/* Ruby 1.7 defines NUM2LL(), LL2NUM() and ULL2NUM() macros */
+#ifndef NUM2LL
+#define NUM2LL(x) NUM2LONG((x))
+#endif
+#ifndef LL2NUM
+#define LL2NUM(x) INT2NUM((long) (x))
+#endif
+#ifndef ULL2NUM
+#define ULL2NUM(x) UINT2NUM((unsigned long) (x))
+#endif
+
+/* Ruby 1.7 doesn't (yet) define NUM2ULL() */
+#ifndef NUM2ULL
+#ifdef HAVE_LONG_LONG
+#define NUM2ULL(x) rb_num2ull((x))
+#else
+#define NUM2ULL(x) NUM2ULONG(x)
+#endif
+#endif
+
+/* RSTRING_LEN, etc are new in Ruby 1.9, but ->ptr and ->len no longer work */
+/* Define these for older versions so we can just write code the new way */
+#ifndef RSTRING_LEN
+# define RSTRING_LEN(x) RSTRING(x)->len
+#endif
+#ifndef RSTRING_PTR
+# define RSTRING_PTR(x) RSTRING(x)->ptr
+#endif
+#ifndef RSTRING_END
+# define RSTRING_END(x) (RSTRING_PTR(x) + RSTRING_LEN(x))
+#endif
+#ifndef RARRAY_LEN
+# define RARRAY_LEN(x) RARRAY(x)->len
+#endif
+#ifndef RARRAY_PTR
+# define RARRAY_PTR(x) RARRAY(x)->ptr
+#endif
+#ifndef RFLOAT_VALUE
+# define RFLOAT_VALUE(x) RFLOAT(x)->value
+#endif
+#ifndef DOUBLE2NUM
+# define DOUBLE2NUM(x) rb_float_new(x)
+#endif
+#ifndef RHASH_TBL
+# define RHASH_TBL(x) (RHASH(x)->tbl)
+#endif
+#ifndef RHASH_ITER_LEV
+# define RHASH_ITER_LEV(x) (RHASH(x)->iter_lev)
+#endif
+#ifndef RHASH_IFNONE
+# define RHASH_IFNONE(x) (RHASH(x)->ifnone)
+#endif
+#ifndef RHASH_SIZE
+# define RHASH_SIZE(x) (RHASH(x)->tbl->num_entries)
+#endif
+#ifndef RHASH_EMPTY_P
+# define RHASH_EMPTY_P(x) (RHASH_SIZE(x) == 0)
+#endif
+#ifndef RSTRUCT_LEN
+# define RSTRUCT_LEN(x) RSTRUCT(x)->len
+#endif
+#ifndef RSTRUCT_PTR
+# define RSTRUCT_PTR(x) RSTRUCT(x)->ptr
+#endif
+
+
+
+/*
+ * Need to be very careful about how these macros are defined, especially
+ * when compiling C++ code or C code with an ANSI C compiler.
+ *
+ * VALUEFUNC(f) is a macro used to typecast a C function that implements
+ * a Ruby method so that it can be passed as an argument to API functions
+ * like rb_define_method() and rb_define_singleton_method().
+ *
+ * VOIDFUNC(f) is a macro used to typecast a C function that implements
+ * either the "mark" or "free" stuff for a Ruby Data object, so that it
+ * can be passed as an argument to API functions like Data_Wrap_Struct()
+ * and Data_Make_Struct().
+ */
+ 
+#ifdef __cplusplus
+#  ifndef RUBY_METHOD_FUNC /* These definitions should work for Ruby 1.4.6 */
+#    define PROTECTFUNC(f) ((VALUE (*)()) f)
+#    define VALUEFUNC(f) ((VALUE (*)()) f)
+#    define VOIDFUNC(f)  ((void (*)()) f)
+#  else
+#    ifndef ANYARGS /* These definitions should work for Ruby 1.6 */
+#      define PROTECTFUNC(f) ((VALUE (*)()) f)
+#      define VALUEFUNC(f) ((VALUE (*)()) f)
+#      define VOIDFUNC(f)  ((RUBY_DATA_FUNC) f)
+#    else /* These definitions should work for Ruby 1.7+ */
+#      define PROTECTFUNC(f) ((VALUE (*)(VALUE)) f)
+#      define VALUEFUNC(f) ((VALUE (*)(ANYARGS)) f)
+#      define VOIDFUNC(f)  ((RUBY_DATA_FUNC) f)
+#    endif
+#  endif
+#else
+#  define VALUEFUNC(f) (f)
+#  define VOIDFUNC(f) (f)
+#endif
+
+/* Don't use for expressions have side effect */
+#ifndef RB_STRING_VALUE
+#define RB_STRING_VALUE(s) (TYPE(s) == T_STRING ? (s) : (*(volatile VALUE *)&(s) = rb_str_to_str(s)))
+#endif
+#ifndef StringValue
+#define StringValue(s) RB_STRING_VALUE(s)
+#endif
+#ifndef StringValuePtr
+#define StringValuePtr(s) RSTRING_PTR(RB_STRING_VALUE(s))
+#endif
+#ifndef StringValueLen
+#define StringValueLen(s) RSTRING_LEN(RB_STRING_VALUE(s))
+#endif
+#ifndef SafeStringValue
+#define SafeStringValue(v) do {\
+    StringValue(v);\
+    rb_check_safe_str(v);\
+} while (0)
+#endif
+
+#ifndef HAVE_RB_DEFINE_ALLOC_FUNC
+#define rb_define_alloc_func(klass, func) rb_define_singleton_method((klass), "new", VALUEFUNC((func)), -1)
+#define rb_undef_alloc_func(klass) rb_undef_method(CLASS_OF((klass)), "new")
+#endif
+
+static VALUE _mSWIG = Qnil;
diff --git a/trunk/Lib/ruby/rubyinit.swg b/trunk/Lib/ruby/rubyinit.swg
new file mode 100644
index 0000000..fc6e039
--- /dev/null
+++ b/trunk/Lib/ruby/rubyinit.swg
@@ -0,0 +1 @@
+%insert(initbeforefunc) "swiginit.swg"
diff --git a/trunk/Lib/ruby/rubyiterators.swg b/trunk/Lib/ruby/rubyiterators.swg
new file mode 100644
index 0000000..466ae22
--- /dev/null
+++ b/trunk/Lib/ruby/rubyiterators.swg
@@ -0,0 +1,935 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * rubyiterators.swg
+ *
+ * Implement a C++ 'output' iterator for Ruby.
+ *
+ * Users can derive form the Iterator to implemet their
+ * own iterators. As an example (real one since we use it for STL/STD
+ * containers), the template Iterator_T does the
+ * implementation for generic C++ iterators.
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+
+%fragment("ConstIterator","header") {  
+namespace swig {
+  struct stop_iteration {
+  };
+
+  /** 
+   * Abstract base class used to represent all iterators of STL containers.
+   */
+  struct ConstIterator {
+  public:
+    typedef ConstIterator self_type;
+
+  protected:
+    GC_VALUE _seq;
+
+  protected:
+    ConstIterator(VALUE seq) : _seq(seq)
+    {
+    }
+
+    // Random access iterator methods, but not required in Ruby
+    virtual ptrdiff_t distance(const ConstIterator &x) const
+    {
+      throw std::invalid_argument("distance not supported");
+    }
+
+    virtual bool equal (const ConstIterator &x) const
+    {
+      throw std::invalid_argument("equal not supported");
+    }
+
+    virtual self_type* advance(ptrdiff_t n)
+    {
+      throw std::invalid_argument("advance not supported");
+    }
+      
+  public:
+    virtual ~ConstIterator() {}
+
+    // Access iterator method, required by Ruby
+    virtual VALUE value() const {
+      throw std::invalid_argument("value not supported");
+      return Qnil;
+    };
+
+    virtual VALUE setValue( const VALUE& v ) {
+      throw std::invalid_argument("value= not supported");
+      return Qnil;
+    }
+
+    virtual self_type* next( size_t n = 1 )
+    {
+      return this->advance( n );
+    }
+
+    virtual self_type* previous( size_t n = 1 )
+    {
+      ptrdiff_t nn = n;
+      return this->advance( -nn );
+    }
+
+    virtual VALUE to_s() const {
+      throw std::invalid_argument("to_s not supported");
+      return Qnil;
+    }
+
+    virtual VALUE inspect() const {
+      throw std::invalid_argument("inspect not supported");
+      return Qnil;
+    }
+    
+    virtual ConstIterator *dup() const
+    {
+      throw std::invalid_argument("dup not supported");
+      return NULL;
+    }
+
+    //
+    // C++ common/needed methods.  We emulate a bidirectional
+    // operator, to be compatible with all the STL.
+    // The iterator traits will then tell the STL what type of
+    // iterator we really are.
+    //
+    ConstIterator() : _seq( Qnil )
+    {
+    }
+
+    ConstIterator( const self_type& b ) : _seq( b._seq )
+    {
+    }
+
+    self_type& operator=( const self_type& b )
+    {
+      _seq = b._seq;
+      return *this;
+    }
+
+    bool operator == (const ConstIterator& x)  const
+    {
+      return equal(x);
+    }
+      
+    bool operator != (const ConstIterator& x) const
+    {
+      return ! operator==(x);
+    }
+      
+    // Pre-decrement operator
+    self_type& operator--()
+    {
+      return *previous();
+    }
+
+    // Pre-increment operator
+    self_type& operator++()
+    {
+      return *next();
+    }
+
+    // Post-decrement operator
+    self_type operator--(int)
+    {
+      self_type r = *this;
+      previous();
+      return r;
+    }
+
+    // Post-increment operator
+    self_type operator++(int)
+    {
+      self_type r = *this;
+      next();
+      return r;
+    }
+
+    ConstIterator& operator += (ptrdiff_t n)
+    {
+      return *advance(n);
+    }
+
+    ConstIterator& operator -= (ptrdiff_t n)
+    {
+      return *advance(-n);
+    }
+
+    ConstIterator* operator + (ptrdiff_t n) const
+    {
+      return dup()->advance(n);
+    }
+
+    ConstIterator* operator - (ptrdiff_t n) const
+    {
+      return dup()->advance(-n);
+    }
+      
+    ptrdiff_t operator - (const ConstIterator& x) const
+    {
+      return x.distance(*this);
+    }
+      
+    static swig_type_info* descriptor() {
+      static int init = 0;
+      static swig_type_info* desc = 0;
+      if (!init) {
+	desc = SWIG_TypeQuery("swig::ConstIterator *");
+	init = 1;
+      }	
+      return desc;
+    }
+  };
+
+
+  /**
+   * Abstract base class used to represent all non-const iterators of STL containers.
+   * 
+   */
+  struct Iterator : public ConstIterator {
+  public:
+    typedef Iterator self_type;
+
+  protected:
+    Iterator(VALUE seq) : ConstIterator(seq)
+    {
+    }
+
+    virtual self_type* advance(ptrdiff_t n)
+    {
+      throw std::invalid_argument("operation not supported");
+    }
+
+  public:
+    static swig_type_info* descriptor() {
+      static int init = 0;
+      static swig_type_info* desc = 0;
+      if (!init) {
+	desc = SWIG_TypeQuery("swig::Iterator *");
+	init = 1;
+      }	
+      return desc;
+    }
+    
+    virtual Iterator *dup() const
+    {
+      throw std::invalid_argument("dup not supported");
+      return NULL;
+    }
+      
+    virtual self_type* next( size_t n = 1 )
+    {
+      return this->advance( n );
+    }
+
+    virtual self_type* previous( size_t n = 1 )
+    {
+      ptrdiff_t nn = n;
+      return this->advance( -nn );
+    }
+
+    bool operator == (const ConstIterator& x)  const
+    {
+      return equal(x);
+    }
+      
+    bool operator != (const Iterator& x) const
+    {
+      return ! operator==(x);
+    }
+      
+    Iterator& operator += (ptrdiff_t n)
+    {
+      return *advance(n);
+    }
+
+    Iterator& operator -= (ptrdiff_t n)
+    {
+      return *advance(-n);
+    }
+      
+    Iterator* operator + (ptrdiff_t n) const
+    {
+      return dup()->advance(n);
+    }
+
+    Iterator* operator - (ptrdiff_t n) const
+    {
+      return dup()->advance(-n);
+    }
+      
+    ptrdiff_t operator - (const Iterator& x) const
+    {
+      return x.distance(*this);
+    }
+  };
+
+}
+}
+
+
+%fragment("ConstIterator_T","header",fragment="ConstIterator",fragment="StdTraits",fragment="StdIteratorTraits") {
+namespace swig {
+
+  /** 
+   * Templated base classes for all custom const_iterators.
+   *
+   */
+  template<typename OutConstIterator>
+  class ConstIterator_T :  public ConstIterator
+  {
+  public:
+    typedef OutConstIterator const_iter;
+    typedef typename std::iterator_traits<const_iter>::value_type value_type;    
+    typedef ConstIterator_T<const_iter> self_type;
+
+  protected:
+
+    
+    virtual bool equal (const ConstIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return (current == iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }
+    
+    virtual ptrdiff_t distance(const ConstIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return std::distance(current, iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }
+
+    virtual ConstIterator* advance(ptrdiff_t n)
+    {
+      std::advance( current, n );
+      return this;
+    }
+
+  public:
+    ConstIterator_T() : ConstIterator(Qnil)
+    {
+    }
+
+    ConstIterator_T(const_iter curr, VALUE seq = Qnil)
+      : ConstIterator(seq), current(curr)
+    {
+    }
+
+    const const_iter& get_current() const
+    {
+      return current;
+    }
+
+    const value_type& operator*() const
+    {
+      return *current;
+    }
+
+    virtual VALUE inspect() const
+    {
+      VALUE ret = rb_str_new2("#<");
+      ret = rb_str_cat2( ret, rb_obj_classname(_seq) );
+      ret = rb_str_cat2( ret, "::const_iterator " );
+      VALUE cur = value();
+      ret = rb_str_concat( ret, rb_inspect(cur) );
+      ret = rb_str_cat2( ret, ">" );
+      return ret;
+    }
+
+    virtual VALUE to_s()    const
+    {
+      VALUE ret = rb_str_new2( rb_obj_classname(_seq) );
+      ret = rb_str_cat2( ret, "::const_iterator " );
+      VALUE cur = value();
+      ret = rb_str_concat( ret, rb_obj_as_string(cur) );
+      return ret;
+    }
+
+  protected:
+    const_iter current;
+  };
+
+
+  /** 
+   * Templated base classes for all custom non-const iterators.
+   *
+   */
+  template<typename InOutIterator>
+  class Iterator_T :  public Iterator
+  {
+  public:
+    typedef InOutIterator nonconst_iter;
+
+    // Make this class iterator STL compatible, by using iterator_traits
+    typedef typename std::iterator_traits<nonconst_iter >::iterator_category iterator_category;
+    typedef typename std::iterator_traits<nonconst_iter >::value_type        value_type;
+    typedef typename std::iterator_traits<nonconst_iter >::difference_type   difference_type;
+    typedef typename std::iterator_traits<nonconst_iter >::pointer           pointer;
+    typedef typename std::iterator_traits<nonconst_iter >::reference         reference;
+
+    typedef Iterator                         base;
+    typedef Iterator_T< nonconst_iter > self_type;
+
+  protected:
+
+    virtual bool equal (const ConstIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return (current == iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }
+    
+    virtual ptrdiff_t distance(const ConstIterator &iter) const
+    {
+      const self_type *iters = dynamic_cast<const self_type *>(&iter);
+      if (iters) {
+	return std::distance(current, iters->get_current());
+      } else {
+	throw std::invalid_argument("bad iterator type");
+      }
+    }
+
+    virtual Iterator* advance(ptrdiff_t n)
+    {
+      std::advance( current, n );
+      return this;
+    }
+
+  public:
+
+    Iterator_T(nonconst_iter curr, VALUE seq = Qnil)
+      : Iterator(seq), current(curr)
+    {
+    }
+
+    const nonconst_iter& get_current() const
+    {
+      return current;
+    }
+
+    self_type& operator=( const self_type& b )
+    {
+      base::operator=( b );
+      return *this;
+    }
+    
+    self_type& operator=( const value_type& b )
+    {
+      *current = b;
+      return *this;
+    }
+
+    const value_type& operator*() const
+    {
+      return *current;
+    }
+
+    value_type& operator*()
+    {
+      return *current;
+    }
+    
+    virtual VALUE inspect() const
+    {
+      VALUE ret = rb_str_new2("#<");
+      ret = rb_str_cat2( ret, rb_obj_classname(_seq) );
+      ret = rb_str_cat2( ret, "::iterator " );
+      VALUE cur = value();
+      ret = rb_str_concat( ret, rb_inspect(cur) );
+      ret = rb_str_cat2( ret, ">" );
+      return ret;
+    }
+
+    virtual VALUE to_s()    const
+    {
+      VALUE ret = rb_str_new2( rb_obj_classname(_seq) );
+      ret = rb_str_cat2( ret, "::iterator " );
+      VALUE cur = value();
+      ret = rb_str_concat( ret, rb_obj_as_string(cur) );
+      return ret;
+    }
+
+  protected:
+    nonconst_iter current;
+  };
+
+
+  /**
+   * Auxiliary functor to store the value of a ruby object inside
+   * a reference of a compatible C++ type.  ie: Ruby -> C++
+   * 
+   */
+  template <class ValueType>
+  struct asval_oper 
+  {
+    typedef ValueType    value_type;
+    typedef bool        result_type;
+    bool operator()(VALUE obj, value_type& v) const
+    {
+      return ( swig::asval< value_type >(obj, &v) == SWIG_OK );
+    }
+  };
+
+  /**
+   * Auxiliary functor to return a ruby object from a C++ type. 
+   * ie: C++ -> Ruby
+   * 
+   */
+  template <class ValueType>
+  struct from_oper 
+  {
+    typedef const ValueType& argument_type;
+    typedef VALUE result_type;
+    result_type operator()(argument_type v) const
+    {
+      return swig::from(v);
+    }
+  };
+
+
+  /** 
+   * ConstIterator class for a const_iterator with no end() boundaries.
+   *
+   */
+  template<typename OutConstIterator, 
+	   typename ValueType = typename std::iterator_traits<OutConstIterator>::value_type,
+	   typename FromOper = from_oper<ValueType> >
+  class ConstIteratorOpen_T :  public ConstIterator_T<OutConstIterator>
+  {
+  public:
+    FromOper from;
+    typedef OutConstIterator const_iter;
+    typedef ValueType value_type;
+    typedef ConstIterator_T<const_iter>  base;
+    typedef ConstIteratorOpen_T<OutConstIterator, ValueType, FromOper> self_type;
+    
+    ConstIteratorOpen_T(const_iter curr, VALUE seq = Qnil)
+      : ConstIterator_T<OutConstIterator>(curr, seq)
+    {
+    }
+    
+    virtual VALUE value() const {
+      return from(static_cast<const value_type&>(*(base::current)));
+    }
+    
+    ConstIterator *dup() const
+    {
+      return new self_type(*this);
+    }
+  };
+
+  /** 
+   * Iterator class for an iterator with no end() boundaries.
+   *
+   */
+  template<typename InOutIterator, 
+	   typename ValueType = typename std::iterator_traits<InOutIterator>::value_type,
+	   typename FromOper = from_oper<ValueType>,
+	   typename AsvalOper = asval_oper<ValueType> >
+  class IteratorOpen_T :  public Iterator_T<InOutIterator>
+  {
+  public:
+    FromOper  from;
+    AsvalOper asval;
+    typedef InOutIterator nonconst_iter;
+    typedef ValueType value_type;
+    typedef Iterator_T<nonconst_iter>  base;
+    typedef IteratorOpen_T<InOutIterator, ValueType, FromOper, AsvalOper> self_type;
+
+  public:
+    IteratorOpen_T(nonconst_iter curr, VALUE seq = Qnil)
+      : Iterator_T<InOutIterator>(curr, seq)
+    {
+    }
+    
+    virtual VALUE value() const {
+      return from(static_cast<const value_type&>(*(base::current)));
+    }
+
+    virtual VALUE setValue( const VALUE& v )
+    {
+      value_type& dst = *base::current;
+      if ( asval(v, dst) ) return v;
+      return Qnil;
+    }
+    
+    Iterator *dup() const
+    {
+      return new self_type(*this);
+    }
+  };
+
+  /** 
+   * ConstIterator class for a const_iterator where begin() and end() boundaries are known.
+   *
+   */
+  template<typename OutConstIterator, 
+	   typename ValueType = typename std::iterator_traits<OutConstIterator>::value_type,
+	   typename FromOper = from_oper<ValueType> >
+  class ConstIteratorClosed_T :  public ConstIterator_T<OutConstIterator>
+  {
+  public:
+    FromOper from;
+    typedef OutConstIterator const_iter;
+    typedef ValueType value_type;
+    typedef ConstIterator_T<const_iter>  base;    
+    typedef ConstIteratorClosed_T<OutConstIterator, ValueType, FromOper> self_type;
+    
+  protected:
+    virtual ConstIterator* advance(ptrdiff_t n)
+    {
+      std::advance( base::current, n );
+      if ( base::current == end )
+	throw stop_iteration();
+      return this;
+    }
+
+  public:
+    ConstIteratorClosed_T(const_iter curr, const_iter first, 
+			  const_iter last, VALUE seq = Qnil)
+      : ConstIterator_T<OutConstIterator>(curr, seq), begin(first), end(last)
+    {
+    }
+    
+    virtual VALUE value() const {
+      if (base::current == end) {
+	throw stop_iteration();
+      } else {
+	return from(static_cast<const value_type&>(*(base::current)));
+      }
+    }
+    
+    ConstIterator *dup() const
+    {
+      return new self_type(*this);
+    }
+
+
+  private:
+    const_iter begin;
+    const_iter end;
+  };
+
+  /** 
+   * Iterator class for a iterator where begin() and end() boundaries are known.
+   *
+   */
+  template<typename InOutIterator, 
+	   typename ValueType = typename std::iterator_traits<InOutIterator>::value_type,
+	   typename FromOper = from_oper<ValueType>,
+	   typename AsvalOper = asval_oper<ValueType> >
+  class IteratorClosed_T :  public Iterator_T<InOutIterator>
+  {
+  public:
+    FromOper   from;
+    AsvalOper asval;
+    typedef InOutIterator nonconst_iter;
+    typedef ValueType value_type;
+    typedef Iterator_T<nonconst_iter>  base;
+    typedef IteratorClosed_T<InOutIterator, ValueType, FromOper, AsvalOper> self_type;
+    
+  protected:
+    virtual Iterator* advance(ptrdiff_t n)
+    {
+      std::advance( base::current, n );
+      if ( base::current == end )
+	throw stop_iteration();
+      return this;
+    }
+
+  public:
+    IteratorClosed_T(nonconst_iter curr, nonconst_iter first, 
+		     nonconst_iter last, VALUE seq = Qnil)
+      : Iterator_T<InOutIterator>(curr, seq), begin(first), end(last)
+    {
+    }
+    
+    virtual VALUE value() const {
+      if (base::current == end) {
+	throw stop_iteration();
+      } else {
+	return from(static_cast<const value_type&>(*(base::current)));
+      }
+    }
+    
+    // Iterator setter method, required by Ruby
+    virtual VALUE setValue( const VALUE& v )
+    {
+      if (base::current == end)
+	throw stop_iteration();
+
+      value_type& dst = *base::current;
+      if ( asval( v, dst ) ) return v;
+      return Qnil;
+    }
+    
+    Iterator *dup() const
+    {
+      return new self_type(*this);
+    }
+
+  private:
+    nonconst_iter begin;
+    nonconst_iter end;
+  };
+
+  /* Partial specialization for bools which don't allow de-referencing */
+  template< typename InOutIterator, typename FromOper, typename AsvalOper >
+  class IteratorOpen_T< InOutIterator, bool, FromOper, AsvalOper > : 
+    public Iterator_T<InOutIterator>
+  {
+  public:
+    FromOper   from;
+    AsvalOper asval;
+    typedef InOutIterator nonconst_iter;
+    typedef bool value_type;
+    typedef Iterator_T<nonconst_iter>  base;
+    typedef IteratorOpen_T<InOutIterator, bool, FromOper, AsvalOper> self_type;
+
+    IteratorOpen_T(nonconst_iter curr, VALUE seq = Qnil)
+      : Iterator_T<InOutIterator>(curr, seq)
+    {
+    }
+
+    virtual VALUE value() const {
+      return from(static_cast<const value_type&>(*(base::current)));
+    }
+    
+    virtual VALUE setValue( const VALUE& v )
+    {
+      bool tmp = *base::current;
+      if ( asval( v, tmp ) )
+	{
+	  *base::current = tmp;
+	  return v;
+	}
+      return Qnil;
+    }    
+    
+    Iterator *dup() const
+    {
+      return new self_type(*this);
+    }
+    
+  };
+
+  /* Partial specialization for bools which don't allow de-referencing */
+  template< typename InOutIterator, typename FromOper, typename AsvalOper >
+  class IteratorClosed_T< InOutIterator, bool, FromOper, AsvalOper > : 
+    public Iterator_T<InOutIterator>
+  {
+  public:
+    FromOper   from;
+    AsvalOper asval;
+    typedef InOutIterator nonconst_iter;
+    typedef bool value_type;
+    typedef Iterator_T<nonconst_iter>  base;
+    typedef IteratorClosed_T<InOutIterator, bool, FromOper, AsvalOper> self_type;
+    
+  protected:
+    virtual Iterator* advance(ptrdiff_t n)
+    {
+      std::advance( base::current, n );
+      if ( base::current == end )
+	throw stop_iteration();
+      return this;
+    }
+
+  public:
+    IteratorClosed_T(nonconst_iter curr, nonconst_iter first, 
+		     nonconst_iter last, VALUE seq = Qnil)
+      : Iterator_T<InOutIterator>(curr, seq), begin(first), end(last)
+    {
+    }
+
+    virtual VALUE value() const {
+      if (base::current == end) {
+	throw stop_iteration();
+      } else {
+	return from(static_cast<const value_type&>(*(base::current)));
+      }
+    }
+
+    virtual VALUE setValue( const VALUE& v )
+    {
+      if (base::current == end)
+	throw stop_iteration();
+
+      bool tmp = *base::current;
+      if ( asval( v, tmp ) )
+	{
+	  *base::current = tmp;
+	  return v;
+	}
+      return Qnil;
+    }
+    
+    Iterator *dup() const
+    {
+      return new self_type(*this);
+    }
+
+  private:
+    nonconst_iter begin;
+    nonconst_iter end;
+  };
+
+
+  /** 
+   * Helper function used to wrap a bounded const_iterator.  This is to be used in
+   * a %typemap(out), for example.
+   *
+   */
+  template<typename InOutIter>
+  inline Iterator*
+  make_nonconst_iterator(const InOutIter& current, const InOutIter& begin,
+			 const InOutIter& end, VALUE seq = Qnil)
+  {
+    return new IteratorClosed_T<InOutIter>(current, begin, end, seq);
+  }
+
+  /** 
+   * Helper function used to wrap an unbounded const_iterator.  This is to be used in
+   * a %typemap(out), for example.
+   *
+   */
+  template<typename InOutIter>
+  inline Iterator*
+  make_nonconst_iterator(const InOutIter& current, VALUE seq = Qnil)
+  {
+    return new IteratorOpen_T<InOutIter>(current, seq);
+  }
+
+  /** 
+   * Helper function used to wrap a bounded const_iterator.  This is to be used in
+   * a %typemap(out), for example.
+   *
+   */
+  template<typename OutIter>
+  inline ConstIterator*
+  make_const_iterator(const OutIter& current, const OutIter& begin,
+                       const OutIter& end, VALUE seq = Qnil)
+  {
+    return new ConstIteratorClosed_T<OutIter>(current, begin, end, seq);
+  }
+
+  /** 
+   * Helper function used to wrap an unbounded const_iterator.  This is to be used in
+   * a %typemap(out), for example.
+   *
+   */
+  template<typename OutIter>
+  inline ConstIterator*
+  make_const_iterator(const OutIter& current, VALUE seq = Qnil)
+  {
+    return new ConstIteratorOpen_T<OutIter>(current, seq);
+  }
+}
+}
+
+
+%fragment("ConstIterator");
+
+
+//
+// This part is just so SWIG is aware of the base abstract iterator class.
+//
+namespace swig 
+{
+  /*
+    Throw a StopIteration exception
+  */
+  %ignore stop_iteration;
+  struct stop_iteration {};
+  
+  %typemap(throws) stop_iteration {
+    (void)$1;
+    SWIG_Ruby_ExceptionType(NULL, Qnil);
+    SWIG_fail;
+  }
+
+  /* 
+     Mark methods that return new objects
+  */
+  %newobject ConstIterator::dup;
+  %newobject ConstIterator::operator + (ptrdiff_t n) const;
+  %newobject ConstIterator::operator - (ptrdiff_t n) const;
+
+  %nodirector ConstIterator;
+
+  %catches(swig::stop_iteration)  ConstIterator::value() const;
+  %catches(swig::stop_iteration)  ConstIterator::incr(size_t n = 1);
+  %catches(swig::stop_iteration)  ConstIterator::decr(size_t n = 1);
+  %catches(std::invalid_argument) ConstIterator::distance(const ConstIterator &x) const;
+  %catches(std::invalid_argument) ConstIterator::equal (const ConstIterator &x) const;
+  %catches(swig::stop_iteration)  ConstIterator::next();
+  %catches(swig::stop_iteration)  ConstIterator::previous();
+  %catches(swig::stop_iteration)  ConstIterator::advance(ptrdiff_t n);
+  %catches(swig::stop_iteration)  ConstIterator::operator += (ptrdiff_t n);
+  %catches(swig::stop_iteration)  ConstIterator::operator -= (ptrdiff_t n);
+  %catches(swig::stop_iteration)  ConstIterator::operator + (ptrdiff_t n) const;
+  %catches(swig::stop_iteration)  ConstIterator::operator - (ptrdiff_t n) const;
+
+
+  struct ConstIterator
+  {
+  protected:
+    ConstIterator(VALUE seq);
+
+  public:
+    virtual ~ConstIterator();
+
+    // Access iterator method, required by Ruby
+    virtual VALUE value() const;
+    
+    // C++ common/needed methods
+    virtual ConstIterator *dup() const;
+
+    virtual VALUE inspect()    const;
+    virtual VALUE to_s()    const;
+
+    virtual ConstIterator* next(size_t n = 1);
+    virtual ConstIterator* previous(size_t n = 1);
+
+    bool operator == (const ConstIterator& x)  const;
+    ConstIterator* operator + (ptrdiff_t n) const;
+    ConstIterator* operator - (ptrdiff_t n) const;
+    ptrdiff_t operator - (const ConstIterator& x) const;
+  };
+
+  struct Iterator : public ConstIterator
+  {
+    %rename("value=") setValue( const VALUE& v );
+    virtual VALUE setValue( const VALUE& v );
+
+    virtual Iterator *dup() const;
+
+    virtual Iterator* next(size_t n = 1);
+    virtual Iterator* previous(size_t n = 1);
+
+    virtual VALUE inspect()    const;
+    virtual VALUE to_s()    const;
+
+    bool operator == (const Iterator& x)  const;
+    Iterator* operator + (ptrdiff_t n) const;
+    Iterator* operator - (ptrdiff_t n) const;
+    ptrdiff_t operator - (const Iterator& x) const;
+  };
+
+}
+
diff --git a/trunk/Lib/ruby/rubykw.swg b/trunk/Lib/ruby/rubykw.swg
new file mode 100644
index 0000000..194687b
--- /dev/null
+++ b/trunk/Lib/ruby/rubykw.swg
@@ -0,0 +1,72 @@
+#ifndef RUBY_RUBYKW_SWG_
+#define RUBY_RUBYKW_SWG_
+
+/* Warnings for Ruby keywords */
+#define RUBYKW(x) %keywordwarn("'" `x` "' is a ruby keyword, renaming to 'C_" `x` "'",rename="C_%s",fullname=1)  `x`
+
+/*
+
+   from http://www.rubycentral.com/book/language.html
+
+*/
+
+RUBYKW(BEGIN);
+RUBYKW(END);
+RUBYKW(alias);
+RUBYKW(and);
+RUBYKW(begin);
+RUBYKW(break);
+RUBYKW(case);
+RUBYKW(class);
+RUBYKW(def);
+RUBYKW("defined");
+RUBYKW(do);
+RUBYKW(else);
+RUBYKW(elsif);
+RUBYKW(end);
+RUBYKW(ensure);
+RUBYKW(false);
+RUBYKW(fatal);
+RUBYKW(for);
+RUBYKW(if);
+RUBYKW(in);
+RUBYKW(module);
+RUBYKW(next);
+RUBYKW(nil);
+RUBYKW(not);
+RUBYKW(or);
+RUBYKW(redo);
+RUBYKW(rescue);
+RUBYKW(retry);
+RUBYKW(return);
+RUBYKW(self);
+RUBYKW(super);
+RUBYKW(then);
+RUBYKW(true);
+RUBYKW(undef);
+RUBYKW(unless);
+RUBYKW(until);
+RUBYKW(when);
+RUBYKW(while);
+RUBYKW(yield);
+
+// RUBYKW(FalseClass);
+// RUBYKW(TrueClass);
+// RUBYKW(Numeric);
+// RUBYKW(Integer);
+// RUBYKW(Fixnum);
+// RUBYKW(Float);
+// RUBYKW(Range);
+// RUBYKW(Array);
+// RUBYKW(String);
+// RUBYKW(IO);
+// RUBYKW(File);
+// RUBYKW(FileUtils);
+// RUBYKW(Find);
+// RUBYKW(Struct);
+// RUBYKW(OpenStruct);
+// RUBYKW(Regexp);
+
+#undef RUBYKW
+
+#endif //RUBY_RUBYKW_SWG_
diff --git a/trunk/Lib/ruby/rubymacros.swg b/trunk/Lib/ruby/rubymacros.swg
new file mode 100644
index 0000000..de2a52b
--- /dev/null
+++ b/trunk/Lib/ruby/rubymacros.swg
@@ -0,0 +1,13 @@
+
+// Redefine these macros so argument index for ruby is done properly,
+// ignoring self and we get some more info about the input.
+#define %argfail_fmt(_type,_name,_argn) Ruby_Format_TypeError( "", _type, #_name, _argn, $input )
+
+#define %argnullref_fmt(_type,_name,_argn) Ruby_Format_TypeError(%nullref_fmt(), _type, #_name, _argn, $input)
+
+%{
+#define SWIG_RUBY_THREAD_BEGIN_BLOCK
+#define SWIG_RUBY_THREAD_END_BLOCK
+%}
+
+%include <typemaps/swigmacros.swg>
diff --git a/trunk/Lib/ruby/rubyopers.swg b/trunk/Lib/ruby/rubyopers.swg
new file mode 100644
index 0000000..d1ac8bf
--- /dev/null
+++ b/trunk/Lib/ruby/rubyopers.swg
@@ -0,0 +1,55 @@
+/* ------------------------------------------------------------
+ * Overloaded operator support
+ * ------------------------------------------------------------ */
+
+#ifdef __cplusplus
+
+%rename(__add__)      *::operator+;
+%rename(__pos__)      *::operator+();
+%rename(__pos__)      *::operator+() const;
+%rename(__sub__)      *::operator-;
+%rename(__neg__)      *::operator-();
+%rename(__neg__)      *::operator-() const;
+%rename(__mul__)      *::operator*;
+%rename(__div__)      *::operator/;
+%rename(__mod__)      *::operator%;
+%rename(__lshift__)   *::operator<<;
+%rename(__rshift__)   *::operator>>;
+%rename(__and__)      *::operator&;
+%rename(__or__)       *::operator|;
+%rename(__xor__)      *::operator^;
+%rename(__invert__)   *::operator~;
+%rename(__lt__)       *::operator<;
+%rename(__le__)       *::operator<=;
+%rename(__gt__)       *::operator>;
+%rename(__ge__)       *::operator>=;
+%rename(__eq__)       *::operator==;
+
+/* Special cases */
+%rename(__call__)     *::operator();
+
+/* Ignored inplace operators */
+%ignoreoperator(NOTEQUAL)   operator!=;  
+%ignoreoperator(PLUSEQ)     operator+=;  
+%ignoreoperator(MINUSEQ)    operator-=;  
+%ignoreoperator(MULEQ)      operator*=;  
+%ignoreoperator(DIVEQ)      operator/=;  
+%ignoreoperator(MODEQ)      operator%=;  
+%ignoreoperator(LSHIFTEQ)   operator<<=; 
+%ignoreoperator(RSHIFTEQ)   operator>>=; 
+%ignoreoperator(ANDEQ)      operator&=;  
+%ignoreoperator(OREQ)       operator|=;  
+%ignoreoperator(XOREQ)      operator^=;  
+
+/* Ignored operators */
+%ignoreoperator(LNOT)       operator!;
+%ignoreoperator(LAND)       operator&&;
+%ignoreoperator(LOR)        operator||;
+%ignoreoperator(EQ)         operator=;
+%ignoreoperator(PLUSPLUS)   operator++;
+%ignoreoperator(MINUSMINUS) operator--;
+%ignoreoperator(ARROWSTAR)  operator->*;
+%ignoreoperator(INDEX)      operator[];
+
+
+#endif /* __cplusplus */
diff --git a/trunk/Lib/ruby/rubyprimtypes.swg b/trunk/Lib/ruby/rubyprimtypes.swg
new file mode 100644
index 0000000..c2d5779
--- /dev/null
+++ b/trunk/Lib/ruby/rubyprimtypes.swg
@@ -0,0 +1,220 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * rubyprimtypes.swg
+ *
+ * ----------------------------------------------------------------------------- */
+/* ------------------------------------------------------------
+ * Primitive Types
+ * ------------------------------------------------------------ */
+
+/* auxiliary ruby fail method */
+
+%fragment("SWIG_ruby_failed","header")
+{
+SWIGINTERN VALUE
+SWIG_ruby_failed(void)
+{
+  return Qnil;
+} 
+}
+
+%define %ruby_aux_method(Type, Method, Action)
+SWIGINTERN VALUE SWIG_AUX_##Method##(VALUE *args)
+{
+  VALUE obj = args[0];
+  VALUE type = TYPE(obj);
+  Type *res = (Type *)(args[1]);
+  *res = Action;
+  return obj;
+}
+%enddef
+
+
+/* boolean */
+
+%fragment(SWIG_From_frag(bool),"header") {
+SWIGINTERNINLINE VALUE
+SWIG_From_dec(bool)(bool value)
+{
+  return value ? Qtrue : Qfalse;
+}
+}
+
+%fragment(SWIG_AsVal_frag(bool),"header",
+	  fragment=SWIG_AsVal_frag(int)) {
+SWIGINTERN int
+SWIG_AsVal_dec(bool)(VALUE obj, bool *val)
+{
+  if (obj == Qtrue) {
+    if (val) *val = true;
+    return SWIG_OK;
+  } else if (obj == Qfalse) {
+    if (val) *val = false;
+    return SWIG_OK;
+  } else {
+    int res = 0;
+    if (SWIG_AsVal(int)(obj, &res) == SWIG_OK) {    
+      if (val) *val = res ? true : false;
+      return SWIG_OK;
+    }
+  }  
+  return SWIG_TypeError;
+}
+}
+
+/* long */
+
+%fragment(SWIG_From_frag(long),"header",
+	  fragment="<limits.h>") {
+  %define_as(SWIG_From_dec(long),           LONG2NUM)
+}
+
+%fragment(SWIG_AsVal_frag(long),"header",fragment="SWIG_ruby_failed") {
+%ruby_aux_method(long, NUM2LONG, type == T_FIXNUM ? NUM2LONG(obj) : rb_big2long(obj))
+
+SWIGINTERN int
+SWIG_AsVal_dec(long)(VALUE obj, long* val)
+{
+  VALUE type = TYPE(obj);
+  if ((type == T_FIXNUM) || (type == T_BIGNUM)) {
+    long v;
+    VALUE a[2];
+    a[0] = obj;
+    a[1] = (VALUE)(&v);
+    if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2LONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
+      if (val) *val = v;
+      return SWIG_OK;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* unsigned long */
+
+%fragment(SWIG_From_frag(unsigned long),"header",
+	  fragment=SWIG_From_frag(long)) {
+SWIGINTERNINLINE VALUE
+SWIG_From_dec(unsigned long)(unsigned long value)
+{
+  return ULONG2NUM(value); 
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long),"header",fragment="SWIG_ruby_failed") {
+%ruby_aux_method(unsigned long, NUM2ULONG, type == T_FIXNUM ? NUM2ULONG(obj) : rb_big2ulong(obj))
+
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long)(VALUE obj, unsigned long *val) 
+{
+  VALUE type = TYPE(obj);
+  if ((type == T_FIXNUM) || (type == T_BIGNUM)) {
+    unsigned long v;
+    VALUE a[2];
+    a[0] = obj;
+    a[1] = (VALUE)(&v);
+    if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2ULONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
+      if (val) *val = v;
+      return SWIG_OK;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* long long */
+
+%fragment(SWIG_From_frag(long long),"header",
+	  fragment=SWIG_From_frag(long),
+	  fragment="<limits.h>") {
+SWIGINTERNINLINE VALUE 
+SWIG_From_dec(long long)(long long value)
+{
+  return LL2NUM(value);
+}
+}
+
+%fragment(SWIG_AsVal_frag(long long),"header",fragment="SWIG_ruby_failed") {
+%ruby_aux_method(long long, NUM2LL, type == T_FIXNUM ? NUM2LL(obj) : rb_big2ll(obj))
+
+SWIGINTERN int
+SWIG_AsVal_dec(long long)(VALUE obj, long long *val)
+{
+  VALUE type = TYPE(obj);
+  if ((type == T_FIXNUM) || (type == T_BIGNUM)) {
+    long long v;
+    VALUE a[2];
+    a[0] = obj;
+    a[1] = (VALUE)(&v);
+    if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2LL), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
+      if (val) *val = v;
+      return SWIG_OK;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* unsigned long long */
+
+%fragment(SWIG_From_frag(unsigned long long),"header",
+	  fragment=SWIG_From_frag(long long),
+	  fragment="<limits.h>") {
+SWIGINTERNINLINE VALUE 
+SWIG_From_dec(unsigned long long)(unsigned long long value)
+{
+  return ULL2NUM(value);
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long long),"header",fragment="SWIG_ruby_failed") {
+%ruby_aux_method(long long, NUM2ULL,  type == T_FIXNUM ? NUM2ULL(obj) : rb_big2ull(obj))
+
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long long)(VALUE obj, unsigned long long *val)
+{ 
+  VALUE type = TYPE(obj);
+  if ((type == T_FIXNUM) || (type == T_BIGNUM)) {
+    unsigned long long v;
+    VALUE a[2];
+    a[0] = obj;
+    a[1] = (VALUE)(&v);
+    if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2ULL), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
+      if (val) *val = v;
+      return SWIG_OK;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* double */
+
+%fragment(SWIG_From_frag(double),"header") {
+  %define_as(SWIG_From_dec(double),  rb_float_new)
+}
+
+%fragment(SWIG_AsVal_frag(double),"header",fragment="SWIG_ruby_failed") {
+%ruby_aux_method(double, NUM2DBL, (type == T_FLOAT ? NUM2DBL(obj) : (type == T_FIXNUM ? (double) FIX2INT(obj) : rb_big2dbl(obj))))
+
+SWIGINTERN int
+SWIG_AsVal_dec(double)(VALUE obj, double *val)
+{
+  VALUE type = TYPE(obj);
+  if ((type == T_FLOAT) || (type == T_FIXNUM) || (type == T_BIGNUM)) {
+    double v;
+    VALUE a[2];
+    a[0] = obj;
+    a[1] = (VALUE)(&v);
+    if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2DBL), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) {
+      if (val) *val = v;
+      return SWIG_OK;
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+
diff --git a/trunk/Lib/ruby/rubyrun.swg b/trunk/Lib/ruby/rubyrun.swg
new file mode 100644
index 0000000..24d861d
--- /dev/null
+++ b/trunk/Lib/ruby/rubyrun.swg
@@ -0,0 +1,444 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * rubyrun.swg
+ *
+ * This file contains the runtime support for Ruby modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+/* For backward compatibility only */
+#define SWIG_POINTER_EXCEPTION  0
+
+/* for raw pointers */
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
+#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, own)
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Ruby_NewPointerObj(ptr, type, flags)
+#define SWIG_AcquirePtr(ptr, own)                       SWIG_Ruby_AcquirePtr(ptr, own)
+#define swig_owntype                                    ruby_owntype
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty, flags)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Ruby_NewPackedObj(ptr, sz, type)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)
+
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_ConvertPtr(obj, pptr, type, 0)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_NewPointerObj(ptr, type, 0)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Ruby_NewPackedObj(ptr, sz, type)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_Ruby_GetModule()	
+#define SWIG_SetModule(clientdata, pointer) 		SWIG_Ruby_SetModule(pointer)
+
+
+/* Error manipulation */
+
+#define SWIG_ErrorType(code)                            SWIG_Ruby_ErrorType(code)               
+#define SWIG_Error(code, msg)            		rb_raise(SWIG_Ruby_ErrorType(code), msg)
+#define SWIG_fail                        		goto fail				 
+
+
+/* Ruby-specific SWIG API */
+
+#define SWIG_InitRuntime()                              SWIG_Ruby_InitRuntime()              
+#define SWIG_define_class(ty)                        	SWIG_Ruby_define_class(ty)
+#define SWIG_NewClassInstance(value, ty)             	SWIG_Ruby_NewClassInstance(value, ty)
+#define SWIG_MangleStr(value)                        	SWIG_Ruby_MangleStr(value)		  
+#define SWIG_CheckConvert(value, ty)                 	SWIG_Ruby_CheckConvert(value, ty)	  
+
+#include "assert.h"
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+  VALUE klass;
+  VALUE mImpl;
+  void  (*mark)(void *);
+  void  (*destroy)(void *);
+  int trackObjects;
+} swig_class;
+
+
+/* Global pointer used to keep some internal SWIG stuff */
+static VALUE _cSWIG_Pointer = Qnil;
+static VALUE swig_runtime_data_type_pointer = Qnil;
+
+/* Global IDs used to keep some internal SWIG stuff */
+static ID swig_arity_id = 0;
+static ID swig_call_id  = 0;
+
+/*
+  If your swig extension is to be run within an embedded ruby and has
+  director callbacks, you should set -DRUBY_EMBEDDED during compilation.  
+  This will reset ruby's stack frame on each entry point from the main 
+  program the first time a virtual director function is invoked (in a 
+  non-recursive way).
+  If this is not done, you run the risk of Ruby trashing the stack.
+*/
+
+#ifdef RUBY_EMBEDDED
+
+#  define SWIG_INIT_STACK                            \
+      if ( !swig_virtual_calls ) { RUBY_INIT_STACK } \
+      ++swig_virtual_calls;
+#  define SWIG_RELEASE_STACK --swig_virtual_calls;
+#  define Ruby_DirectorTypeMismatchException(x) \
+          rb_raise( rb_eTypeError, x ); return c_result;
+
+      static unsigned int swig_virtual_calls = 0;
+
+#else  /* normal non-embedded extension */
+
+#  define SWIG_INIT_STACK
+#  define SWIG_RELEASE_STACK
+#  define Ruby_DirectorTypeMismatchException(x) \
+          throw Swig::DirectorTypeMismatchException( x );
+
+#endif  /* RUBY_EMBEDDED */
+
+
+SWIGRUNTIME VALUE 
+getExceptionClass(void) {
+  static int init = 0;
+  static VALUE rubyExceptionClass ;
+  if (!init) {
+    init = 1;
+    rubyExceptionClass = rb_const_get(_mSWIG, rb_intern("Exception"));
+  }
+  return rubyExceptionClass;
+} 
+
+/* This code checks to see if the Ruby object being raised as part
+   of an exception inherits from the Ruby class Exception.  If so,
+   the object is simply returned.  If not, then a new Ruby exception
+   object is created and that will be returned to Ruby.*/
+SWIGRUNTIME VALUE
+SWIG_Ruby_ExceptionType(swig_type_info *desc, VALUE obj) {
+  VALUE exceptionClass = getExceptionClass();
+  if (rb_obj_is_kind_of(obj, exceptionClass)) {
+    return obj;
+  }  else {
+    return rb_exc_new3(rb_eRuntimeError, rb_obj_as_string(obj));
+  }
+}
+
+/* Initialize Ruby runtime support */
+SWIGRUNTIME void
+SWIG_Ruby_InitRuntime(void)
+{
+  if (_mSWIG == Qnil) {
+    _mSWIG = rb_define_module("SWIG");
+    swig_call_id  = rb_intern("call");
+    swig_arity_id = rb_intern("arity");
+  }
+}
+
+/* Define Ruby class for C type */
+SWIGRUNTIME void
+SWIG_Ruby_define_class(swig_type_info *type)
+{
+  VALUE klass;
+  char *klass_name = (char *) malloc(4 + strlen(type->name) + 1);
+  sprintf(klass_name, "TYPE%s", type->name);
+  if (NIL_P(_cSWIG_Pointer)) {
+    _cSWIG_Pointer = rb_define_class_under(_mSWIG, "Pointer", rb_cObject);
+    rb_undef_method(CLASS_OF(_cSWIG_Pointer), "new");
+  }
+  klass = rb_define_class_under(_mSWIG, klass_name, _cSWIG_Pointer);
+  free((void *) klass_name);
+}
+
+/* Create a new pointer object */
+SWIGRUNTIME VALUE
+SWIG_Ruby_NewPointerObj(void *ptr, swig_type_info *type, int flags)
+{
+  int own =  flags & SWIG_POINTER_OWN; 
+  int track;
+  char *klass_name;
+  swig_class *sklass;
+  VALUE klass;
+  VALUE obj;
+  
+  if (!ptr)
+    return Qnil;
+  
+  if (type->clientdata) {
+    sklass = (swig_class *) type->clientdata;
+		
+    /* Are we tracking this class and have we already returned this Ruby object? */
+    track = sklass->trackObjects;
+    if (track) {
+      obj = SWIG_RubyInstanceFor(ptr);
+      
+      /* Check the object's type and make sure it has the correct type.
+        It might not in cases where methods do things like 
+        downcast methods. */
+      if (obj != Qnil) {
+        VALUE value = rb_iv_get(obj, "@__swigtype__");
+        char* type_name = RSTRING_PTR(value);
+				
+        if (strcmp(type->name, type_name) == 0) {
+          return obj;
+        }
+      }
+    }
+
+    /* Create a new Ruby object */
+    obj = Data_Wrap_Struct(sklass->klass, VOIDFUNC(sklass->mark), 
+			   ( own ? VOIDFUNC(sklass->destroy) : 
+			     (track ? VOIDFUNC(SWIG_RubyRemoveTracking) : 0 )
+			     ), ptr);
+
+    /* If tracking is on for this class then track this object. */
+    if (track) {
+      SWIG_RubyAddTracking(ptr, obj);
+    }
+  } else {
+    klass_name = (char *) malloc(4 + strlen(type->name) + 1);
+    sprintf(klass_name, "TYPE%s", type->name);
+    klass = rb_const_get(_mSWIG, rb_intern(klass_name));
+    free((void *) klass_name);
+    obj = Data_Wrap_Struct(klass, 0, 0, ptr);
+  }
+  rb_iv_set(obj, "@__swigtype__", rb_str_new2(type->name));
+  
+  return obj;
+}
+
+/* Create a new class instance (always owned) */
+SWIGRUNTIME VALUE
+SWIG_Ruby_NewClassInstance(VALUE klass, swig_type_info *type)
+{
+  VALUE obj;
+  swig_class *sklass = (swig_class *) type->clientdata;
+  obj = Data_Wrap_Struct(klass, VOIDFUNC(sklass->mark), VOIDFUNC(sklass->destroy), 0);
+  rb_iv_set(obj, "@__swigtype__", rb_str_new2(type->name));
+  return obj;
+}
+
+/* Get type mangle from class name */
+SWIGRUNTIMEINLINE char *
+SWIG_Ruby_MangleStr(VALUE obj)
+{
+  VALUE stype = rb_iv_get(obj, "@__swigtype__");
+  return StringValuePtr(stype);
+}
+
+/* Acquire a pointer value */
+typedef void (*ruby_owntype)(void*);
+
+SWIGRUNTIME ruby_owntype
+SWIG_Ruby_AcquirePtr(VALUE obj, ruby_owntype own) {
+  if (obj) {
+    ruby_owntype oldown = RDATA(obj)->dfree;
+    RDATA(obj)->dfree = own;
+    return oldown;
+  } else {
+    return 0;
+  }
+}
+
+/* Convert a pointer value */
+SWIGRUNTIME int
+SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, ruby_owntype *own)
+{
+  char *c;
+  swig_cast_info *tc;
+  void *vptr = 0;
+
+  /* Grab the pointer */
+  if (NIL_P(obj)) {
+    *ptr = 0;
+    return SWIG_OK;
+  } else {
+    if (TYPE(obj) != T_DATA) {
+      return SWIG_ERROR;
+    }
+    Data_Get_Struct(obj, void, vptr);
+  }
+  
+  if (own) *own = RDATA(obj)->dfree;
+    
+  /* Check to see if the input object is giving up ownership
+     of the underlying C struct or C++ object.  If so then we
+     need to reset the destructor since the Ruby object no 
+     longer owns the underlying C++ object.*/ 
+  if (flags & SWIG_POINTER_DISOWN) {
+    /* Is tracking on for this class? */
+    int track = 0;
+    if (ty && ty->clientdata) {
+      swig_class *sklass = (swig_class *) ty->clientdata;
+      track = sklass->trackObjects;
+    }
+		
+    if (track) {
+      /* We are tracking objects for this class.  Thus we change the destructor
+       * to SWIG_RubyRemoveTracking.  This allows us to
+       * remove the mapping from the C++ to Ruby object
+       * when the Ruby object is garbage collected.  If we don't
+       * do this, then it is possible we will return a reference 
+       * to a Ruby object that no longer exists thereby crashing Ruby. */
+      RDATA(obj)->dfree = SWIG_RubyRemoveTracking;
+    } else {    
+      RDATA(obj)->dfree = 0;
+    }
+  }
+
+  /* Do type-checking if type info was provided */
+  if (ty) {
+    if (ty->clientdata) {
+      if (rb_obj_is_kind_of(obj, ((swig_class *) (ty->clientdata))->klass)) {
+        if (vptr == 0) {
+          /* The object has already been deleted */
+          return SWIG_ObjectPreviouslyDeletedError;
+        }
+        *ptr = vptr;
+        return SWIG_OK;
+      }
+    }
+    if ((c = SWIG_MangleStr(obj)) == NULL) {
+      return SWIG_ERROR;
+    }
+    tc = SWIG_TypeCheck(c, ty);
+    if (!tc) {
+      return SWIG_ERROR;
+    } else {
+      int newmemory = 0;
+      *ptr = SWIG_TypeCast(tc, vptr, &newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+    }
+  } else {
+    *ptr = vptr;
+  }
+  
+  return SWIG_OK;
+}
+
+/* Check convert */
+SWIGRUNTIMEINLINE int
+SWIG_Ruby_CheckConvert(VALUE obj, swig_type_info *ty)
+{
+  char *c = SWIG_MangleStr(obj);
+  if (!c) return 0;
+  return SWIG_TypeCheck(c,ty) != 0;
+}
+
+SWIGRUNTIME VALUE
+SWIG_Ruby_NewPackedObj(void *ptr, int sz, swig_type_info *type) {
+  char result[1024];
+  char *r = result;
+  if ((2*sz + 1 + strlen(type->name)) > 1000) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r, ptr, sz);
+  strcpy(r, type->name);
+  return rb_str_new2(result);
+}
+
+/* Convert a packed value value */
+SWIGRUNTIME int
+SWIG_Ruby_ConvertPacked(VALUE obj, void *ptr, int sz, swig_type_info *ty) {
+  swig_cast_info *tc;
+  const char  *c;
+
+  if (TYPE(obj) != T_STRING) goto type_error;
+  c = StringValuePtr(obj);
+  /* Pointer values must start with leading underscore */
+  if (*c != '_') goto type_error;
+  c++;
+  c = SWIG_UnpackData(c, ptr, sz);
+  if (ty) {
+    tc = SWIG_TypeCheck(c, ty);
+    if (!tc) goto type_error;
+  }
+  return SWIG_OK;
+
+ type_error:
+  return SWIG_ERROR;
+}
+
+SWIGRUNTIME swig_module_info *
+SWIG_Ruby_GetModule(void)
+{
+  VALUE pointer;
+  swig_module_info *ret = 0;
+  VALUE verbose = rb_gv_get("VERBOSE");
+
+ /* temporarily disable warnings, since the pointer check causes warnings with 'ruby -w' */
+  rb_gv_set("VERBOSE", Qfalse);
+  
+  /* first check if pointer already created */
+  pointer = rb_gv_get("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  if (pointer != Qnil) {
+    Data_Get_Struct(pointer, swig_module_info, ret);
+  }
+
+  /* reinstate warnings */
+  rb_gv_set("VERBOSE", verbose);
+  return ret;
+}
+
+SWIGRUNTIME void 
+SWIG_Ruby_SetModule(swig_module_info *pointer)
+{
+  /* register a new class */
+  VALUE cl = rb_define_class("swig_runtime_data", rb_cObject);
+  /* create and store the structure pointer to a global variable */
+  swig_runtime_data_type_pointer = Data_Wrap_Struct(cl, 0, 0, pointer);
+  rb_define_readonly_variable("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, &swig_runtime_data_type_pointer);
+}
+
+/* This function can be used to check whether a proc or method or similarly
+   callable function has been passed.  Usually used in a %typecheck, like:
+
+   %typecheck(c_callback_t, precedence=SWIG_TYPECHECK_POINTER) {
+        $result = SWIG_Ruby_isCallable( $input );
+   }
+ */
+SWIGINTERN
+int SWIG_Ruby_isCallable( VALUE proc )
+{
+  if ( rb_respond_to( proc, swig_call_id ) == Qtrue )
+    return 1;
+  return 0;
+}
+
+/* This function can be used to check the arity (number of arguments)
+   a proc or method can take.  Usually used in a %typecheck.
+   Valid arities will be that equal to minimal or those < 0
+   which indicate a variable number of parameters at the end.
+ */
+SWIGINTERN
+int SWIG_Ruby_arity( VALUE proc, int minimal )
+{
+  if ( rb_respond_to( proc, swig_arity_id ) == Qtrue )
+    {
+      VALUE num = rb_funcall( proc, swig_arity_id, 0 );
+      int arity = NUM2INT(num);
+      if ( arity < 0 && (arity+1) < -minimal ) return 1;
+      if ( arity == minimal ) return 1;
+      return 1;
+    }
+  return 0;
+}
+
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/ruby/rubyruntime.swg b/trunk/Lib/ruby/rubyruntime.swg
new file mode 100644
index 0000000..4121561
--- /dev/null
+++ b/trunk/Lib/ruby/rubyruntime.swg
@@ -0,0 +1,9 @@
+
+%runtime "swiglabels.swg"    /* Common C API type-checking code */
+%runtime "swigrun.swg"       /* Common C API type-checking code */
+%runtime "swigerrors.swg"    /* SWIG errors */   
+%runtime "rubyhead.swg"      /* Ruby includes and fixes */   
+%runtime "rubyerrors.swg"    /* Ruby errors */   
+%runtime "rubytracking.swg"  /* API for tracking C++ classes to Ruby objects */
+%runtime "rubyapi.swg"
+%runtime "rubyrun.swg"
diff --git a/trunk/Lib/ruby/rubystdautodoc.swg b/trunk/Lib/ruby/rubystdautodoc.swg
new file mode 100644
index 0000000..ad70f7f
--- /dev/null
+++ b/trunk/Lib/ruby/rubystdautodoc.swg
@@ -0,0 +1,37 @@
+/**
+ * @file   rubystdautodoc.swg
+ * @author gga
+ * @date   Wed May  2 17:20:39 2007
+ * 
+ * @brief  This file contains autodocs for standard STL functions.
+ * 
+ * 
+ */
+
+//
+// For STL autodocumentation
+//
+AUTODOC(c_str, "Convert class to a String representation");
+AUTODOC(begin, "Return an iterator to the beginning of the $class");
+AUTODOC(end, "Return an iterator to past the end of the $class");
+AUTODOC(rbegin, "Return a reverse iterator to the beginning (the end) of the $class");
+AUTODOC(rend, "Return a reverse iterator to past the end (past the beginning) of the $class");
+AUTODOC(length, "Size or Length of the $class");
+AUTODOC(replace, "Replace all or a portion of the $class");
+AUTODOC(resize, "Resize the size of the $class");
+AUTODOC(capacity, "Reserved capacity of the $class");
+AUTODOC(reserve, "Reserve memory in the $class for a number of elements");
+AUTODOC(erase, "Delete a portion of the $class");
+AUTODOC(max_size, "Maximum size of elements allowed in the $class");
+AUTODOC(iterator, "Return an iterator to the $class");
+AUTODOC(empty, "Check if the $class is empty or not");
+AUTODOC(rfind, "Find an element in reverse usually starting from the end of the $class");
+AUTODOC(assign, "Assign a new $class or portion of it");
+AUTODOC(front, "Return the first element in $class");
+AUTODOC(back, "Return the last element in $class");
+AUTODOC(second, "Return the second element in $class");
+AUTODOC(push_front, "Add an element at the beginning of the $class");
+AUTODOC(push_back, "Add an element at the end of the $class");
+AUTODOC(pop_front, "Remove and return element at the beginning of the $class");
+AUTODOC(pop_back, "Remove and return an element at the end of the $class");
+AUTODOC(clear, "Clear $class contents");
diff --git a/trunk/Lib/ruby/rubystdcommon.swg b/trunk/Lib/ruby/rubystdcommon.swg
new file mode 100644
index 0000000..4e1b9d9
--- /dev/null
+++ b/trunk/Lib/ruby/rubystdcommon.swg
@@ -0,0 +1,265 @@
+
+/* ------------------------------------------------------------
+ * The Ruby classes, for C++
+ * ------------------------------------------------------------ */
+%include <rubyclasses.swg>
+
+%fragment("StdTraits","header",fragment="StdTraitsCommon")
+{
+
+namespace swig {  
+  /*
+    Traits that provides the from method
+  */
+  template <class Type> struct traits_from_ptr {
+    static VALUE from(Type *val, int owner = 0) {
+      return SWIG_NewPointerObj(val, type_info<Type>(), owner);
+    }
+  };
+
+  template <class Type> struct traits_from {
+    static VALUE from(const Type& val) {
+      return traits_from_ptr<Type>::from(new Type(val), 1);
+    }
+  };
+
+  template <class Type> struct traits_from<Type *> {
+    static VALUE from(Type* val) {
+      return traits_from_ptr<Type>::from(val, 0);
+    }
+  };
+
+  template <class Type> struct traits_from<const Type *> {
+    static VALUE from(const Type* val) {
+      return traits_from_ptr<Type>::from(const_cast<Type*>(val), 0);
+    }
+  };
+
+
+  template <class Type>
+  inline VALUE from(const Type& val) {
+    return traits_from<Type>::from(val);
+  }
+
+  template <class Type>
+  inline VALUE from_ptr(Type* val, int owner) {
+    return traits_from_ptr<Type>::from(val, owner);
+  }
+
+  /*
+    Traits that provides the asval/as/check method
+  */
+  template <class Type>
+  struct traits_asptr {   
+    static int asptr(VALUE obj, Type **val) {
+      Type *p;
+      int res = SWIG_ConvertPtr(obj, (void**)&p, type_info<Type>(), 0);
+      if (SWIG_IsOK(res)) {
+	if (val) *val = p;
+      }
+      return res;
+    }
+  }; 
+
+  template <class Type>
+  inline int asptr(VALUE obj, Type **vptr) {
+    return traits_asptr<Type>::asptr(obj, vptr);
+  }
+
+  template <class Type> 
+  struct traits_asval {
+    static int asval(VALUE obj, Type *val) {
+      if (val) {
+	Type *p = 0;
+	int res = traits_asptr<Type>::asptr(obj, &p);
+	if (!SWIG_IsOK(res)) return res;	
+	if (p) {
+	  typedef typename noconst_traits<Type>::noconst_type noconst_type;
+	  *(const_cast<noconst_type*>(val)) = *p;
+	  if (SWIG_IsNewObj(res)){
+	    %delete(p);
+	    res = SWIG_DelNewMask(res);
+	  }
+	  return res;
+	} else {
+	  return SWIG_ERROR;
+	}
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+
+  template <class Type> struct traits_asval<Type*> {
+    static int asval(VALUE obj, Type **val) {
+      if (val) {
+        typedef typename noconst_traits<Type>::noconst_type noconst_type;
+        noconst_type *p = 0;
+        int res = traits_asptr<noconst_type>::asptr(obj,  &p);
+        if (SWIG_IsOK(res)) {
+          *(const_cast<noconst_type**>(val)) = p;
+	}
+	return res;
+      } else {
+	return traits_asptr<Type>::asptr(obj, (Type **)(0));
+      }
+    }
+  };
+  
+  template <class Type>
+  inline int asval(VALUE obj, Type *val) {
+    return traits_asval<Type>::asval(obj, val);
+  }
+
+  template <class Type> 
+  struct traits_as<Type, value_category> {
+    static Type as(VALUE obj, bool throw_error) {
+      Type v;
+      int res = asval(obj, &v);
+      if (!obj || !SWIG_IsOK(res)) {
+	if (throw_error) throw std::invalid_argument("bad type");
+	VALUE lastErr = rb_gv_get("$!");
+	if (lastErr == Qnil) {
+	  %type_error(swig::type_name<Type>());
+	}
+      }
+      return v;
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type, pointer_category> {
+    static Type as(VALUE obj, bool throw_error) {
+      Type *v = 0;      
+      int res = (obj ? traits_asptr<Type>::asptr(obj, &v) : SWIG_ERROR);
+      if (SWIG_IsOK(res) && v) {
+	if (SWIG_IsNewObj(res)) {
+	  Type r(*v);
+	  %delete(v);
+	  return r;
+	} else {
+	  return *v;
+	}
+      } else {
+	// Uninitialized return value, no Type() constructor required.
+	if (throw_error) throw std::invalid_argument("bad type");
+	VALUE lastErr = rb_gv_get("$!");
+	if (lastErr == Qnil) {
+	  %type_error(swig::type_name<Type>());
+	}
+	static Type *v_def = (Type*) malloc(sizeof(Type));
+	memset(v_def,0,sizeof(Type));
+	return *v_def;
+      }
+    }
+  };
+
+  template <class Type> 
+  struct traits_as<Type*, pointer_category> {
+    static Type* as(VALUE obj, bool throw_error) {
+      Type *v = 0;      
+      int res = (obj ? traits_asptr<Type>::asptr(obj, &v) : SWIG_ERROR);
+      if (SWIG_IsOK(res)) {
+	return v;
+      } else {
+	if (throw_error) throw std::invalid_argument("bad type");
+	VALUE lastErr = rb_gv_get("$!");
+	if (lastErr == Qnil) {
+	  %type_error(swig::type_name<Type>());
+	}
+	return 0;
+      }
+    }
+  };
+
+  template <class Type>
+  inline Type as(VALUE obj, bool te = false) {
+    return traits_as< Type, typename traits< Type >::category >::as(obj, te);
+  }
+
+  template <class Type> 
+  struct traits_check<Type, value_category> {
+    static bool check(VALUE obj) {
+      int res = obj ? asval(obj, (Type *)(0)) : SWIG_ERROR;
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type> 
+  struct traits_check<Type, pointer_category> {
+    static bool check(VALUE obj) {
+      int res = obj ? asptr(obj, (Type **)(0)) : SWIG_ERROR;
+      return SWIG_IsOK(res) ? true : false;
+    }
+  };
+
+  template <class Type>
+  inline bool check(VALUE obj) {
+    return traits_check<Type, typename traits<Type>::category>::check(obj);
+  }
+}
+}
+
+
+// Define GC marking template traits for a container type
+%define %create_mark_traits(Type)
+%{
+  namespace swig {
+    template <class T>
+    struct mark_traits {
+      typedef typename Type<T >::const_iterator const_iterator;
+
+      inline void operator()(const Type<T >& c ) const
+      {
+	const_iterator i = c.begin();
+	const_iterator e = c.end();
+	for ( ; i != e; ++i )
+	  {
+	    rb_gc_mark( swig::from( &(*i) ) );
+	  }
+      }
+    };
+
+    // Partial specializations for classes that requires no GC marking
+    // or a special GC marking algorithm.
+    template< >
+    struct mark_traits<bool> {
+      inline void operator()(const Type<bool >& c ) const {}
+    };
+
+    template< >
+    struct mark_traits<char> {
+      inline void operator()(const Type<char >& c ) const {}
+    };
+
+    template< >
+    struct mark_traits<int> {
+      inline void operator()(const Type<int >& c ) const {}
+    };
+
+    template< >
+    struct mark_traits<unsigned> {
+      inline void operator()(const Type<unsigned >& c ) const {}
+    };
+
+    template< >
+    struct mark_traits<GC_VALUE> {
+      typedef Type<GC_VALUE >::const_iterator const_iterator;
+
+      inline void operator()(const Type<GC_VALUE >& c ) const {
+	const_iterator i = c.begin();
+	const_iterator e = c.end();
+	for ( ; i != e; ++i )
+	  {
+	    VALUE v = *i;
+	    if ( FIXNUM_P(v) || SPECIAL_CONST_P(v) || SYMBOL_P(v) ||
+		 ( BUILTIN_TYPE(v) == T_NONE ) ) continue;
+
+	    rb_gc_mark( v );
+	  }
+      }
+    };
+
+  }
+%}
+%enddef
diff --git a/trunk/Lib/ruby/rubystdfunctors.swg b/trunk/Lib/ruby/rubystdfunctors.swg
new file mode 100644
index 0000000..8209382
--- /dev/null
+++ b/trunk/Lib/ruby/rubystdfunctors.swg
@@ -0,0 +1,162 @@
+/**
+ * @file   rubystdfunctors.swg
+ * @date   Sun May  6 00:44:33 2007
+ * 
+ * @brief  This file provides unary and binary functors for STL
+ *         containers, that will invoke a Ruby proc or method to do
+ *         their operation.
+ *
+ *         You can use them in a swig file like:
+ *
+ *         %include <std_set.i>
+ *         %include <std_functors.i>
+ *
+ *         %template< IntSet > std::set< int, swig::BinaryPredicate<> >;
+ *
+ *
+ *         which will then allow calling them from Ruby either like:
+ *  
+ *            # order of set is defined by C++ default
+ *            a = IntSet.new
+ *
+ *            # sort order defined by Ruby proc
+ *            b = IntSet.new( proc { |a,b| a > b } )
+ * 
+ */
+
+%include rubyclasses.swg
+
+
+namespace swig {
+
+  %apply GC_VALUE { UnaryPredicate, BinaryPredicate, UnaryFunction,
+		      BinaryFunction };
+
+  %typecheck(SWIG_TYPECHECK_POINTER,noblock=1) 
+    UnaryPredicate, UnaryPredicate&, UnaryFunction, UnaryFunction&
+  {
+    $1 = SWIG_Ruby_isCallable($input) && SWIG_Ruby_arity($input, 1);
+  }
+
+  %typecheck(SWIG_TYPECHECK_POINTER,noblock=1) 
+    BinaryPredicate, BinaryPredicate&, BinaryFunction, BinaryFunction& {
+    $1 = SWIG_Ruby_isCallable($input) && SWIG_Ruby_arity($input, 2);
+  }
+
+  %typemap(in,noblock=1)  BinaryFunction&, BinaryFunction {
+    $1 = new swig::BinaryFunction< >($input);
+  }
+  %typemap(in,noblock=1) UnaryFunction&, UnaryFunction {
+    $1 = new swig::UnaryFunction< >($input);
+  }
+
+  %typemap(in,noblock=1) BinaryPredicate&, BinaryPredicate {
+    $1 = new swig::BinaryPredicate<>($input);
+  }
+
+  %typemap(in,noblock=1) UnaryPredicate&, UnaryPredicate {
+    $1 = new swig::UnaryPredicate< >($input);
+  }
+
+
+  %ignore BinaryFunction;
+  template< class _T = GC_VALUE >
+  struct BinaryFunction {
+  };
+
+  %ignore UnaryFunction;
+  template< class _T = GC_VALUE >
+  struct UnaryFunction {
+  };
+
+  %ignore BinaryPredicate;
+  template< class _T = GC_VALUE >
+  struct BinaryPredicate {
+  };
+
+  %ignore UnaryPredicate;
+  template< class _T = GC_VALUE >
+  struct UnaryPredicate {
+
+  };
+
+}
+
+
+%fragment("StdFunctors","header",fragment="StdTraits")
+{
+namespace swig {
+
+  static ID call_id = rb_intern("call");
+
+  template <class _T = GC_VALUE, class _DefaultFunc = std::less<GC_VALUE> >
+  struct BinaryPredicate : GC_VALUE, std::binary_function< _T, _T, bool >
+  {
+    BinaryPredicate(VALUE obj = Qnil) : GC_VALUE(obj) { }
+    bool operator()(_T a, _T b) const
+    {
+      if (_obj != Qnil) {
+        SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	VALUE arg1 = swig::from(a);
+	VALUE arg2 = swig::from(b);
+	VALUE res = rb_funcall( _obj, swig::call_id, 2, arg1, arg2);
+        SWIG_RUBY_THREAD_END_BLOCK;
+        return RTEST(res);
+      } else {
+        return _DefaultFunc()(a, b);
+      }
+    }
+  };
+
+  template <class _T = GC_VALUE, class _DefaultFunc = std::less< _T > >
+  struct BinaryFunction : GC_VALUE, std::binary_function< _T, _T, _T >
+  {
+    BinaryFunction(VALUE obj = Qnil) : GC_VALUE(obj) { }
+    _T operator()(_T a, _T b) const
+    {
+      if (_obj != Qnil) {
+        SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	VALUE arg1 = swig::from(a);
+	VALUE arg2 = swig::from(b);
+	VALUE res = rb_funcall( _obj, swig::call_id, 2, arg1, arg2);
+        SWIG_RUBY_THREAD_END_BLOCK;
+        return swig::as<_T >(res);
+      } else {
+        return _DefaultFunc()(a, b);
+      }
+    }
+  };
+
+  template< class _T = GC_VALUE >
+  struct UnaryPredicate : GC_VALUE, std::unary_function< _T, bool >
+  {
+    UnaryPredicate(VALUE obj = Qnil) : GC_VALUE(obj) { }
+    bool operator()(_T a) const
+    {
+      SWIG_RUBY_THREAD_BEGIN_BLOCK;
+      VALUE arg1 = swig::from<_T >(a);
+      VALUE res = rb_funcall( _obj, swig::call_id, 1, arg1);
+      SWIG_RUBY_THREAD_END_BLOCK;
+      return RTEST(res);
+    }
+  };
+
+  template< class _T = GC_VALUE >
+  struct UnaryFunction : GC_VALUE, std::unary_function< _T, _T >
+  {
+    UnaryFunction(VALUE obj = Qnil) : GC_VALUE(obj) { }
+    _T operator()(_T a) const
+    {
+      SWIG_RUBY_THREAD_BEGIN_BLOCK;
+      VALUE arg1 = swig::from(a);
+      VALUE res = rb_funcall( _obj, swig::call_id, 1, VALUE(arg1));
+      SWIG_RUBY_THREAD_END_BLOCK;
+      return swig::as< _T >(res);
+    }
+  };
+
+} // namespace swig
+
+}
+
+
diff --git a/trunk/Lib/ruby/rubystrings.swg b/trunk/Lib/ruby/rubystrings.swg
new file mode 100644
index 0000000..e6b92ef
--- /dev/null
+++ b/trunk/Lib/ruby/rubystrings.swg
@@ -0,0 +1,61 @@
+/* ------------------------------------------------------------
+ *  utility methods for char strings 
+ * ------------------------------------------------------------ */
+
+%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") {
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(VALUE obj, char** cptr, size_t* psize, int *alloc)
+{
+  if (TYPE(obj) == T_STRING) {
+    %#if defined(StringValuePtr)
+    char *cstr = StringValuePtr(obj); 
+    %#else
+    char *cstr = STR2CSTR(obj);
+    %#endif
+    size_t size = RSTRING_LEN(obj) + 1;
+    if (cptr)  {
+      if (alloc) {
+	if (*alloc == SWIG_NEWOBJ) {
+	  *cptr = %new_copy_array(cstr, size, char);
+	} else {
+	  *cptr = cstr;
+	  *alloc = SWIG_OLDOBJ;
+	}
+      }
+    }
+    if (psize) *psize = size;
+    return SWIG_OK;
+  } else {
+    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+    if (pchar_descriptor) {
+      void* vptr = 0;
+      if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {
+	if (cptr) *cptr = (char *)vptr;
+	if (psize) *psize = vptr ? (strlen((char*)vptr) + 1) : 0;
+	if (alloc) *alloc = SWIG_OLDOBJ;
+	return SWIG_OK;
+      }
+    }
+  }  
+  return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") {
+SWIGINTERNINLINE VALUE 
+SWIG_FromCharPtrAndSize(const char* carray, size_t size)
+{
+  if (carray) {
+    if (size > LONG_MAX) {
+      swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+      return pchar_descriptor ? 
+	SWIG_NewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : Qnil;
+    } else {
+      return rb_str_new(carray, %numeric_cast(size,long));
+    }
+  } else {
+    return Qnil;
+  }
+}
+}
+
diff --git a/trunk/Lib/ruby/rubytracking.swg b/trunk/Lib/ruby/rubytracking.swg
new file mode 100644
index 0000000..959d208
--- /dev/null
+++ b/trunk/Lib/ruby/rubytracking.swg
@@ -0,0 +1,160 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * rubytracking.swg
+ *
+ * This file contains support for tracking mappings from 
+ * Ruby objects to C++ objects.  This functionality is needed
+ * to implement mark functions for Ruby's mark and sweep
+ * garbage collector.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Ruby 1.8 actually assumes the first case. */
+#if SIZEOF_VOIDP == SIZEOF_LONG
+#  define SWIG2NUM(v) LONG2NUM((unsigned long)v)
+#  define NUM2SWIG(x) (unsigned long)NUM2LONG(x)
+#elif SIZEOF_VOIDP == SIZEOF_LONG_LONG
+#  define SWIG2NUM(v) LL2NUM((unsigned long long)v)
+#  define NUM2SWIG(x) (unsigned long long)NUM2LL(x)
+#else
+#  error sizeof(void*) is not the same as long or long long
+#endif
+
+
+/* Global Ruby hash table to store Trackings from C/C++
+   structs to Ruby Objects. 
+*/
+static VALUE swig_ruby_trackings = Qnil;
+
+/* Global variable that stores a reference to the ruby
+   hash table delete function. */
+static ID swig_ruby_hash_delete;
+
+/* Setup a Ruby hash table to store Trackings */
+SWIGRUNTIME void SWIG_RubyInitializeTrackings(void) {
+  /* Create a ruby hash table to store Trackings from C++ 
+     objects to Ruby objects. */
+
+  /* Try to see if some other .so has already created a 
+     tracking hash table, which we keep hidden in an instance var
+     in the SWIG module.
+     This is done to allow multiple DSOs to share the same
+     tracking table.
+  */
+  ID trackings_id = rb_intern( "@__trackings__" );
+  VALUE verbose = rb_gv_get("VERBOSE");
+  rb_gv_set("VERBOSE", Qfalse);
+  swig_ruby_trackings = rb_ivar_get( _mSWIG, trackings_id );
+  rb_gv_set("VERBOSE", verbose);
+
+  /* No, it hasn't.  Create one ourselves */ 
+  if ( swig_ruby_trackings == Qnil )
+    {
+      swig_ruby_trackings = rb_hash_new();
+      rb_ivar_set( _mSWIG, trackings_id, swig_ruby_trackings );
+    }
+
+  /* Now store a reference to the hash table delete function
+     so that we only have to look it up once.*/
+  swig_ruby_hash_delete = rb_intern("delete");
+}
+
+/* Get a Ruby number to reference a pointer */
+SWIGRUNTIME VALUE SWIG_RubyPtrToReference(void* ptr) {
+  /* We cast the pointer to an unsigned long
+     and then store a reference to it using
+     a Ruby number object. */
+
+  /* Convert the pointer to a Ruby number */
+  return SWIG2NUM(ptr);
+}
+
+/* Get a Ruby number to reference an object */
+SWIGRUNTIME VALUE SWIG_RubyObjectToReference(VALUE object) {
+  /* We cast the object to an unsigned long
+     and then store a reference to it using
+     a Ruby number object. */
+
+  /* Convert the Object to a Ruby number */
+  return SWIG2NUM(object);
+}
+
+/* Get a Ruby object from a previously stored reference */
+SWIGRUNTIME VALUE SWIG_RubyReferenceToObject(VALUE reference) {
+  /* The provided Ruby number object is a reference
+     to the Ruby object we want.*/
+
+  /* Convert the Ruby number to a Ruby object */
+  return NUM2SWIG(reference);
+}
+
+/* Add a Tracking from a C/C++ struct to a Ruby object */
+SWIGRUNTIME void SWIG_RubyAddTracking(void* ptr, VALUE object) {
+  /* In a Ruby hash table we store the pointer and
+     the associated Ruby object.  The trick here is
+     that we cannot store the Ruby object directly - if
+     we do then it cannot be garbage collected.  So
+     instead we typecast it as a unsigned long and
+     convert it to a Ruby number object.*/
+
+  /* Get a reference to the pointer as a Ruby number */
+  VALUE key = SWIG_RubyPtrToReference(ptr);
+
+  /* Get a reference to the Ruby object as a Ruby number */
+  VALUE value = SWIG_RubyObjectToReference(object);
+
+  /* Store the mapping to the global hash table. */
+  rb_hash_aset(swig_ruby_trackings, key, value);
+}
+
+/* Get the Ruby object that owns the specified C/C++ struct */
+SWIGRUNTIME VALUE SWIG_RubyInstanceFor(void* ptr) {
+  /* Get a reference to the pointer as a Ruby number */
+  VALUE key = SWIG_RubyPtrToReference(ptr);
+
+  /* Now lookup the value stored in the global hash table */
+  VALUE value = rb_hash_aref(swig_ruby_trackings, key);
+	
+  if (value == Qnil) {
+    /* No object exists - return nil. */
+    return Qnil;
+  }
+  else {
+    /* Convert this value to Ruby object */
+    return SWIG_RubyReferenceToObject(value);
+  }
+}
+
+/* Remove a Tracking from a C/C++ struct to a Ruby object.  It
+   is very important to remove objects once they are destroyed
+   since the same memory address may be reused later to create
+   a new object. */
+SWIGRUNTIME void SWIG_RubyRemoveTracking(void* ptr) {
+  /* Get a reference to the pointer as a Ruby number */
+  VALUE key = SWIG_RubyPtrToReference(ptr);
+
+  /* Delete the object from the hash table by calling Ruby's
+     do this we need to call the Hash.delete method.*/
+  rb_funcall(swig_ruby_trackings, swig_ruby_hash_delete, 1, key);
+}
+
+/* This is a helper method that unlinks a Ruby object from its
+   underlying C++ object.  This is needed if the lifetime of the
+   Ruby object is longer than the C++ object */
+SWIGRUNTIME void SWIG_RubyUnlinkObjects(void* ptr) {
+  VALUE object = SWIG_RubyInstanceFor(ptr);
+
+  if (object != Qnil) {
+    DATA_PTR(object) = 0;
+  }
+}
+
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/ruby/rubytypemaps.swg b/trunk/Lib/ruby/rubytypemaps.swg
new file mode 100644
index 0000000..336ee97
--- /dev/null
+++ b/trunk/Lib/ruby/rubytypemaps.swg
@@ -0,0 +1,62 @@
+/* ------------------------------------------------------------
+ *  Typemap specializations for Ruby
+ * ------------------------------------------------------------ */
+/* ------------------------------------------------------------
+ *  Fragment section
+ * ------------------------------------------------------------ */
+/* bool is dangerous in Ruby, change precedence */
+#undef SWIG_TYPECHECK_BOOL
+%define SWIG_TYPECHECK_BOOL             10000 %enddef
+
+/* Include fundamental fragemt definitions */
+%include <typemaps/fragments.swg>
+
+/* Look for user fragments file. */
+%include <rubyfragments.swg>
+
+/* Ruby fragments for primitive types */
+%include <rubyprimtypes.swg>
+
+/* Ruby fragments for char* strings */
+%include <rubystrings.swg>
+
+/* Backward compatibility output helper */
+%fragment("output_helper","header") %{
+#define output_helper SWIG_Ruby_AppendOutput
+%}
+
+/* ------------------------------------------------------------
+ *  Unified typemap section
+ * ------------------------------------------------------------ */
+
+/* Directors are supported in Ruby */
+#ifndef SWIG_DIRECTOR_TYPEMAPS
+#define SWIG_DIRECTOR_TYPEMAPS
+#endif
+
+
+/* Ruby types */
+#define SWIG_Object                      VALUE
+#define VOID_Object                      Qnil
+
+/* Overload of the output/constant/exception handling */
+
+/* append output */
+#define SWIG_AppendOutput(result,obj)    SWIG_Ruby_AppendOutput(result, obj)
+
+/* set constant */
+#define SWIG_SetConstant(name, obj)      rb_define_const($module, name, obj)
+
+/* raise */
+#define SWIG_Raise(obj, type, desc)      rb_exc_raise(SWIG_Ruby_ExceptionType(desc, obj)) 
+
+/* Get the address of the 'Ruby self' object */
+
+%typemap(in,numinputs=0,noblock=1) VALUE* RUBY_SELF {
+  $1 = &self;
+}
+
+/* Include the unified typemap library */
+%include <typemaps/swigtypemaps.swg>
+
+
diff --git a/trunk/Lib/ruby/rubyuserdir.swg b/trunk/Lib/ruby/rubyuserdir.swg
new file mode 100644
index 0000000..2f67c9e
--- /dev/null
+++ b/trunk/Lib/ruby/rubyuserdir.swg
@@ -0,0 +1,10 @@
+#define %alias %feature("alias")
+#define %freefunc %feature("freefunc")
+#define %markfunc %feature("markfunc")
+#define %mixin %feature("mixin")
+#define %predicate %feature("predicate", "1")
+#define %bang %feature("bang", "1")
+#define %trackobjects %feature("trackobjects")
+#define %nooutput %feature("outputs","0")
+#define %initstack %feature("initstack", "1")
+#define %ignorestack %feature("initstack", "0")
diff --git a/trunk/Lib/ruby/rubywstrings.swg b/trunk/Lib/ruby/rubywstrings.swg
new file mode 100644
index 0000000..0cf9d7e
--- /dev/null
+++ b/trunk/Lib/ruby/rubywstrings.swg
@@ -0,0 +1,76 @@
+/**
+ * @file   rubywstrings.swg
+ * @author 
+ * @date   Fri May  4 17:49:40 2007
+ * 
+ * @brief  Currently, Ruby does not support Unicode or WChar properly, so these
+ *         are still treated as char arrays for now.
+ *         There are other libraries available that add support to this in
+ *         ruby including WString, FXString, etc.
+ * 
+ * 
+ */
+
+/* ------------------------------------------------------------
+ *  utility methods for wchar_t strings 
+ * ------------------------------------------------------------ */
+
+%fragment("SWIG_AsWCharPtrAndSize","header",fragment="<wchar.h>",fragment="SWIG_pwchar_descriptor") {
+SWIGINTERN int
+SWIG_AsWCharPtrAndSize(VALUE obj, wchar_t **cptr, size_t *psize, int *alloc)
+{
+  return SWIG_AsCharPtrAndSize( obj, (char**)cptr, psize, alloc);
+//   VALUE tmp = 0;
+//   bool ok = false;
+//   if ( TYPE(obj) == T_STRING ) {
+//     if (cptr) {
+//       obj = tmp = SWIG_Unicode_FromObject(obj);
+//       ok = true;
+//     }
+//   }
+//   if (ok) {
+//     int len = PyUnicode_GetSize(obj);
+//     rb_notimplement();
+//     if (cptr) {
+//       *cptr = %new_array(len + 1, wchar_t);
+//       SWIG_Unicode_AsWideChar((PyUnicodeObject *)obj, *cptr, len);
+//       (*cptr)[len] = 0;
+//     }
+//     if (psize) *psize = (size_t) len + 1;
+//     if (alloc) *alloc = cptr ? SWIG_NEWOBJ : 0;
+//     return SWIG_OK;
+//   } else {
+//     swig_type_info* pwchar_descriptor = SWIG_pwchar_descriptor();
+//     if (pwchar_descriptor) {
+//       void * vptr = 0;
+//       if (SWIG_ConvertPtr(obj, &vptr, pwchar_descriptor, 0) == SWIG_OK) {
+// 	if (cptr) *cptr = (wchar_t *)vptr;
+// 	if (psize) *psize = vptr ? (wcslen((wchar_t *)vptr) + 1) : 0;
+// 	return SWIG_OK;
+//       }
+//     }
+//   }
+//   return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_FromWCharPtrAndSize","header",fragment="<wchar.h>",fragment="SWIG_pwchar_descriptor") {
+SWIGINTERNINLINE VALUE 
+SWIG_FromWCharPtrAndSize(const wchar_t * carray, size_t size)
+{
+  return SWIG_FromCharPtrAndSize( (const char*)carray, size);
+//   if (carray) {
+//     if (size > INT_MAX) {
+//       swig_type_info* pwchar_descriptor = SWIG_pwchar_descriptor();
+//       return pwchar_descriptor ? 
+// 	SWIG_NewPointerObj(%const_cast(carray,wchar_t *), pwchar_descriptor, 0) : Qnil;
+//     } else {
+//       return SWIG_Unicode_FromWideChar(carray, %numeric_cast(size,int));
+//     }
+//   } else {
+//     return Qnil;
+//   }
+}
+}
+
+
diff --git a/trunk/Lib/ruby/std_alloc.i b/trunk/Lib/ruby/std_alloc.i
new file mode 100644
index 0000000..35dc051
--- /dev/null
+++ b/trunk/Lib/ruby/std_alloc.i
@@ -0,0 +1 @@
+%include <std/std_alloc.i>
diff --git a/trunk/Lib/ruby/std_basic_string.i b/trunk/Lib/ruby/std_basic_string.i
new file mode 100644
index 0000000..1351177
--- /dev/null
+++ b/trunk/Lib/ruby/std_basic_string.i
@@ -0,0 +1,97 @@
+#if !defined(SWIG_STD_STRING) 
+#define SWIG_STD_BASIC_STRING
+
+%include <rubycontainer.swg>
+
+#define %swig_basic_string(Type...)  %swig_sequence_methods_val(Type)
+
+
+%traits_swigtype(std::basic_string<char>);
+%fragment(SWIG_Traits_frag(std::basic_string<char>));
+
+
+%fragment(SWIG_AsPtr_frag(std::basic_string<char>),"header",
+	  fragment="SWIG_AsCharPtrAndSize") {
+SWIGINTERN int
+SWIG_AsPtr(std::basic_string<char>)(VALUE obj, std::string **val)
+{
+  static swig_type_info* string_info = 
+    SWIG_TypeQuery("std::basic_string<char> *");
+  std::string *vptr;    
+  if (SWIG_ConvertPtr(obj, (void**)&vptr, string_info, 0) == SWIG_OK) {
+    if (val) *val = vptr;
+    return SWIG_OLDOBJ;
+  } else {
+    char* buf = 0 ; size_t size = 0; int alloc = 0;
+    if (SWIG_AsCharPtrAndSize(obj, &buf, &size, &alloc) == SWIG_OK) {
+      if (buf) {
+	if (val) *val = new std::string(buf, size - 1);
+	if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+	return SWIG_NEWOBJ;
+      }
+    }
+    if (val) {
+      rb_raise( rb_eTypeError, "a string is expected");
+    }
+    return 0;
+  }
+}  
+}
+
+%fragment(SWIG_From_frag(std::basic_string<char>),"header",
+	  fragment="SWIG_FromCharPtrAndSize") {
+SWIGINTERNINLINE VALUE
+  SWIG_From(std::basic_string<char>)(const std::string& s)
+  {
+    return SWIG_FromCharPtrAndSize(s.data(), s.size());
+  }
+}
+
+%include <std/std_basic_string.i>
+%typemaps_asptrfromn(%checkcode(STRING), std::basic_string<char>);
+
+#endif
+
+
+#if !defined(SWIG_STD_WSTRING)
+
+%fragment(SWIG_AsPtr_frag(std::basic_string<wchar_t>),"header",
+	  fragment="SWIG_AsWCharPtrAndSize") {
+SWIGINTERN int
+  SWIG_AsPtr(std::basic_string<wchar_t>)(VALUE obj, std::wstring **val)
+  {
+    static swig_type_info* string_info = 
+      SWIG_TypeQuery("std::basic_string<wchar_t> *");
+    std::wstring *vptr;    
+    if (SWIG_ConvertPtr(obj, (void**)&vptr, string_info, 0) == SWIG_OK) {
+      if (val) *val = vptr;
+      return SWIG_OLDOBJ;
+    } else {
+      wchar_t *buf = 0 ; size_t size = 0; int alloc = 0;
+      if (SWIG_AsWCharPtrAndSize(obj, &buf, &size, &alloc) == SWIG_OK) {
+	if (buf) {
+	  if (val) *val = new std::wstring(buf, size - 1);
+	  if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+	  return SWIG_NEWOBJ;
+	}
+      }
+      if (val) {
+	rb_raise( rb_eTypeError, "a string is expected");
+      }
+      return 0;
+    }
+  }
+}
+
+%fragment(SWIG_From_frag(std::basic_string<wchar_t>),"header",
+	  fragment="SWIG_FromWCharPtrAndSize") {
+SWIGINTERNINLINE VALUE
+  SWIG_From(std::basic_string<wchar_t>)(const std::wstring& s)
+  {
+    return SWIG_FromWCharPtrAndSize(s.data(), s.size());
+  }
+}
+
+%typemaps_asptrfromn(%checkcode(UNISTRING), std::basic_string<wchar_t>);
+
+#endif
diff --git a/trunk/Lib/ruby/std_char_traits.i b/trunk/Lib/ruby/std_char_traits.i
new file mode 100644
index 0000000..bf4e6c4
--- /dev/null
+++ b/trunk/Lib/ruby/std_char_traits.i
@@ -0,0 +1 @@
+%include <std/std_char_traits.i>
diff --git a/trunk/Lib/ruby/std_common.i b/trunk/Lib/ruby/std_common.i
new file mode 100644
index 0000000..16365a4
--- /dev/null
+++ b/trunk/Lib/ruby/std_common.i
@@ -0,0 +1,44 @@
+%include <std/std_except.i>
+%include <rubystdcommon.swg>
+%include <rubystdautodoc.swg>
+
+
+/*
+  Generate the traits for a 'primitive' type, such as 'double',
+  for which the SWIG_AsVal and SWIG_From methods are already defined.
+*/
+
+%define %traits_ptypen(Type...)
+  %fragment(SWIG_Traits_frag(Type),"header",
+	    fragment=SWIG_AsVal_frag(Type),
+	    fragment=SWIG_From_frag(Type),
+	    fragment="StdTraits") {
+namespace swig {
+  template <> struct traits<Type > {
+    typedef value_category category;
+    static const char* type_name() { return  #Type; }
+  };  
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval(VALUE obj, value_type *val) { 
+      return SWIG_AsVal(Type)(obj, val);
+    }
+  };
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static VALUE from(const value_type& val) {
+      return SWIG_From(Type)(val);
+    }
+  };
+}
+}
+%enddef
+
+
+%include <std/std_common.i>
+
+//
+// Generates the traits for all the known primitive
+// C++ types (int, double, ...)
+//
+%apply_cpptypes(%traits_ptypen);
diff --git a/trunk/Lib/ruby/std_complex.i b/trunk/Lib/ruby/std_complex.i
new file mode 100644
index 0000000..dacbea2
--- /dev/null
+++ b/trunk/Lib/ruby/std_complex.i
@@ -0,0 +1,22 @@
+/*
+ *  STD C++ complex typemaps
+ */
+
+%include <rubycomplex.swg>
+
+%{
+#include <complex> 
+%}
+
+/* defining the complex as/from converters */
+
+%swig_cplxdbl_convn(std::complex<double>, std::complex<double>, std::real, std::imag)
+%swig_cplxflt_convn(std::complex<float>,  std::complex<float>,  std::real, std::imag)
+
+/* defining the typemaps */
+
+%typemaps_primitive(%checkcode(CPLXDBL), std::complex<double>);
+%typemaps_primitive(%checkcode(CPLXFLT), std::complex<float>);
+
+
+
diff --git a/trunk/Lib/ruby/std_container.i b/trunk/Lib/ruby/std_container.i
new file mode 100644
index 0000000..8537950
--- /dev/null
+++ b/trunk/Lib/ruby/std_container.i
@@ -0,0 +1,2 @@
+%include <rubycontainer.swg>
+%include <std/std_container.i>
diff --git a/trunk/Lib/ruby/std_deque.i b/trunk/Lib/ruby/std_deque.i
new file mode 100644
index 0000000..38048af
--- /dev/null
+++ b/trunk/Lib/ruby/std_deque.i
@@ -0,0 +1,30 @@
+/*
+  Deques
+*/
+
+%fragment("StdDequeTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::deque<T> >  {
+      static int asptr(VALUE obj, std::deque<T>  **vec) {
+	return traits_asptr_stdseq<std::deque<T> >::asptr(obj, vec);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::deque<T> > {
+      static VALUE from(const std::deque<T> & vec) {
+	return traits_from_stdseq<std::deque<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+%ignore std::deque::push_back;
+%ignore std::deque::pop_back;
+
+#define %swig_deque_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_deque_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%include <std/std_deque.i>
diff --git a/trunk/Lib/ruby/std_except.i b/trunk/Lib/ruby/std_except.i
new file mode 100644
index 0000000..af98428
--- /dev/null
+++ b/trunk/Lib/ruby/std_except.i
@@ -0,0 +1 @@
+%include <typemaps/std_except.swg>
diff --git a/trunk/Lib/ruby/std_functors.i b/trunk/Lib/ruby/std_functors.i
new file mode 100644
index 0000000..54ee97b
--- /dev/null
+++ b/trunk/Lib/ruby/std_functors.i
@@ -0,0 +1,29 @@
+/**
+ * @file   std_functors.i
+ * @date   Sun May  6 00:44:33 2007
+ * 
+ * @brief  This file provides unary and binary functors for STL
+ *         containers, that will invoke a Ruby proc or method to do
+ *         their operation.
+ *
+ *         You can use them in a swig file like:
+ *
+ *         %include <std_set.i>
+ *         %include <std_functors.i>
+ *
+ *         %template< IntSet > std::set< int, swig::BinaryPredicate<int> >;
+ *
+ *
+ *         which will then allow calling them from Ruby either like:
+ *  
+ *            # order of set is defined by C++ default
+ *            a = IntSet.new
+ *
+ *            # sort order defined by Ruby proc
+ *            b = IntSet.new( proc { |a,b| a > b } )
+ * 
+ */
+
+%include <rubystdfunctors.swg>
+
+%fragment("StdFunctors");
diff --git a/trunk/Lib/ruby/std_ios.i b/trunk/Lib/ruby/std_ios.i
new file mode 100644
index 0000000..7aafae2
--- /dev/null
+++ b/trunk/Lib/ruby/std_ios.i
@@ -0,0 +1,14 @@
+
+#pragma SWIG nowarn=801
+
+%rename(ios_base_in) std::ios_base::in;
+
+AUTODOC(cerr, "Standard C++ error stream");
+AUTODOC(cout, "Standard C++ output stream");
+AUTODOC(cin,  "Standard C++ input stream");
+AUTODOC(clog, "Standard C++ logging stream");
+AUTODOC(endl,  "Add an end line to stream");
+AUTODOC(ends,  "Ends stream");
+AUTODOC(flush, "Flush stream");
+
+%include <std/std_ios.i>
diff --git a/trunk/Lib/ruby/std_iostream.i b/trunk/Lib/ruby/std_iostream.i
new file mode 100644
index 0000000..ee36bec
--- /dev/null
+++ b/trunk/Lib/ruby/std_iostream.i
@@ -0,0 +1,12 @@
+namespace std
+{
+%callback("%s") endl;
+%callback("%s") ends;
+%callback("%s") flush;
+}
+
+%warnfilter(365) operator+=;
+%warnfilter(802) std::basic_iostream;  // turn off multiple inheritance warning
+
+%include <std/std_iostream.i>
+
diff --git a/trunk/Lib/ruby/std_list.i b/trunk/Lib/ruby/std_list.i
new file mode 100644
index 0000000..8d4284b
--- /dev/null
+++ b/trunk/Lib/ruby/std_list.i
@@ -0,0 +1,41 @@
+/*
+  Lists
+*/
+
+%fragment("StdListTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T >
+    struct traits_asptr<std::list<T> >  {
+      static int asptr(VALUE obj, std::list<T> **lis) {
+	return traits_asptr_stdseq<std::list<T> >::asptr(obj, lis);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::list<T> > {
+      static VALUE from(const std::list<T> & vec) {
+	return traits_from_stdseq<std::list<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+%ignore std::list::push_back;
+%ignore std::list::pop_back;
+
+#define %swig_list_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_list_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+
+%rename("delete")     std::list::__delete__;
+%rename("reject!")    std::list::reject_bang;
+%rename("map!")       std::list::map_bang;
+%rename("empty?")     std::list::empty;
+%rename("include?" )  std::list::__contains__ const;
+%rename("has_key?" )  std::list::has_key const;
+
+%alias  std::list::push          "<<";
+
+%include <std/std_list.i>
+
diff --git a/trunk/Lib/ruby/std_map.i b/trunk/Lib/ruby/std_map.i
new file mode 100644
index 0000000..cc22fef
--- /dev/null
+++ b/trunk/Lib/ruby/std_map.i
@@ -0,0 +1,417 @@
+//
+//   Maps
+//
+%fragment("StdMapTraits","header",fragment="StdSequenceTraits")
+{
+  namespace swig {
+    template <class RubySeq, class K, class T >
+    inline void
+    assign(const RubySeq& rubyseq, std::map<K,T > *map) {
+      typedef typename std::map<K,T>::value_type value_type;
+      typename RubySeq::const_iterator it = rubyseq.begin();
+      for (;it != rubyseq.end(); ++it) {
+	map->insert(value_type(it->first, it->second));
+      }
+    }
+
+    template <class K, class T>
+    struct traits_asptr<std::map<K,T> >  {
+      typedef std::map<K,T> map_type;
+      static int asptr(VALUE obj, map_type **val) {
+	int res = SWIG_ERROR;
+	if ( TYPE(obj) == T_HASH ) {
+	  static ID id_to_a = rb_intern("to_a");
+	  VALUE items = rb_funcall(obj, id_to_a, 0);
+	  res = traits_asptr_stdseq<std::map<K,T>, std::pair<K, T> >::asptr(items, val);
+	} else {
+	  map_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<map_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+      }
+    };
+      
+    template <class K, class T >
+    struct traits_from<std::map<K,T> >  {
+      typedef std::map<K,T> map_type;
+      typedef typename map_type::const_iterator const_iterator;
+      typedef typename map_type::size_type size_type;
+            
+      static VALUE from(const map_type& map) {
+	swig_type_info *desc = swig::type_info<map_type>();
+	if (desc && desc->clientdata) {
+	  return SWIG_NewPointerObj(new map_type(map), desc, SWIG_POINTER_OWN);
+	} else {
+	  size_type size = map.size();
+	  int rubysize = (size <= (size_type) INT_MAX) ? (int) size : -1;
+	  if (rubysize < 0) {
+	    SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	    rb_raise( rb_eRuntimeError, "map size not valid in Ruby");
+	    SWIG_RUBY_THREAD_END_BLOCK;
+	    return Qnil;
+	  }
+	  VALUE obj = rb_hash_new();
+	  for (const_iterator i= map.begin(); i!= map.end(); ++i) {
+	    VALUE key = swig::from(i->first);
+	    VALUE val = swig::from(i->second);
+	    rb_hash_aset(obj, key, val);
+	  }
+	  return obj;
+	}
+      }
+    };
+
+    template <class ValueType>
+    struct from_key_oper 
+    {
+      typedef const ValueType& argument_type;
+      typedef  VALUE result_type;
+      result_type operator()(argument_type v) const
+      {
+	return swig::from(v.first);
+      }
+    };
+
+    template <class ValueType>
+    struct from_value_oper 
+    {
+      typedef const ValueType& argument_type;
+      typedef  VALUE result_type;
+      result_type operator()(argument_type v) const
+      {
+	return swig::from(v.second);
+      }
+    };
+
+    template<class OutIterator, class FromOper, 
+	     class ValueType = typename OutIterator::value_type>
+    struct MapIterator_T : ConstIteratorClosed_T<OutIterator, ValueType, FromOper>
+    {
+      MapIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq)
+	: ConstIteratorClosed_T<OutIterator,ValueType,FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+
+
+    template<class OutIterator,
+	     class FromOper = from_key_oper<typename OutIterator::value_type> >
+    struct MapKeyIterator_T : MapIterator_T<OutIterator, FromOper>
+    {
+      MapKeyIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq)
+	: MapIterator_T<OutIterator, FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+
+    template<typename OutIter>
+    inline ConstIterator*
+    make_output_key_iterator(const OutIter& current, const OutIter& begin, 
+			     const OutIter& end, VALUE seq = 0)
+    {
+      return new MapKeyIterator_T<OutIter>(current, begin, end, seq);
+    }
+
+    template<class OutIterator,
+	     class FromOper = from_value_oper<typename OutIterator::value_type> >
+    struct MapValueIterator_T : MapIterator_T<OutIterator, FromOper>
+    {
+      MapValueIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq)
+	: MapIterator_T<OutIterator, FromOper>(curr, first, last, seq)
+      {
+      }
+    };
+    
+
+    template<typename OutIter>
+    inline ConstIterator*
+    make_output_value_iterator(const OutIter& current, const OutIter& begin, 
+			       const OutIter& end, VALUE seq = 0)
+    {
+      return new MapValueIterator_T<OutIter>(current, begin, end, seq);
+    }
+  }
+}
+
+%define %swig_map_common(Map...)
+  %swig_container_methods(%arg(Map));
+  // %swig_sequence_iterator(%arg(Map));
+
+  %extend {
+    
+    VALUE __delete__(const key_type& key) {
+      Map::iterator i = self->find(key);
+      if (i != self->end()) {
+	self->erase(i);
+	return swig::from( key );
+      }
+      else {
+	return Qnil;
+      }
+    }
+    
+    bool has_key(const key_type& key) const {
+      Map::const_iterator i = self->find(key);
+      return i != self->end();
+    }
+    
+    VALUE keys() {
+      Map::size_type size = self->size();
+      int rubysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1;
+      if (rubysize < 0) {
+	SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	rb_raise(rb_eRuntimeError, "map size not valid in Ruby");
+	SWIG_RUBY_THREAD_END_BLOCK;
+	return Qnil;
+      }
+      VALUE ary = rb_ary_new2(rubysize);
+      Map::const_iterator i = self->begin();
+      Map::const_iterator e = self->end();
+      for ( ; i != e; ++i ) {
+	rb_ary_push( ary, swig::from(i->first) );
+      }
+      return ary;
+    }
+
+    Map* each()
+      {
+	if ( !rb_block_given_p() )
+	  rb_raise( rb_eArgError, "no block given");
+
+	VALUE k, v;
+	Map::iterator i = self->begin();
+	Map::iterator e = self->end();
+	for ( ; i != e; ++i )
+	  {
+	    const Map::key_type&    key = i->first;
+	    const Map::mapped_type& val = i->second;
+
+	    k = swig::from<Map::key_type>(key);
+	    v = swig::from<Map::mapped_type>(val);
+	    rb_yield_values(2, k, v);
+	  }
+	
+	return self;
+      }
+
+    %newobject select;
+    Map* select() {
+      if ( !rb_block_given_p() )
+	rb_raise( rb_eArgError, "no block given" );
+
+      Map* r = new Map;
+      Map::iterator i = $self->begin();
+      Map::iterator e = $self->end();
+      for ( ; i != e; ++i )
+	{
+	  VALUE k = swig::from<Map::key_type>(i->first);
+	  VALUE v = swig::from<Map::mapped_type>(i->second);
+	  if ( RTEST( rb_yield_values(2, k, v) ) )
+	    $self->insert(r->end(), *i);
+	}
+	
+      return r;
+    }
+
+  %typemap(in) (int argc, VALUE* argv) {
+    $1 = argc;
+    $2 = argv;
+  }
+
+  VALUE values_at(int argc, VALUE* argv, ...) {
+    
+    VALUE r = rb_ary_new();
+    ID   id = rb_intern("[]");
+    swig_type_info* type = swig::type_info< Map >();
+    VALUE me = SWIG_NewPointerObj( $self, type, 0 );
+    for ( int i = 0; i < argc; ++i )
+      {
+	VALUE key = argv[i];
+	VALUE tmp = rb_funcall( me, id, 1, key );
+	rb_ary_push( r, tmp );
+      }
+    
+    return r;
+  }
+
+
+    Map* each_key()
+      {
+	if ( !rb_block_given_p() )
+	  rb_raise( rb_eArgError, "no block given");
+
+	VALUE r;
+	Map::iterator i = self->begin();
+	Map::iterator e = self->end();
+	for ( ; i != e; ++i )
+	  {
+	    r = swig::from( i->first );
+	    rb_yield(r);
+	  }
+	
+	return self;
+      }
+    
+    VALUE values() {
+      Map::size_type size = self->size();
+      int rubysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1;
+      if (rubysize < 0) {
+	SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	rb_raise(rb_eRuntimeError, "map size not valid in Ruby");
+	SWIG_RUBY_THREAD_END_BLOCK;
+	return Qnil;
+      }
+      VALUE ary = rb_ary_new2(rubysize);
+      Map::const_iterator i = self->begin();
+      Map::const_iterator e = self->end();
+      for ( ; i != e; ++i ) {
+	rb_ary_push( ary, swig::from(i->second) );
+      }
+      return ary;
+    }
+    
+    Map* each_value()
+      {
+	if ( !rb_block_given_p() )
+	  rb_raise( rb_eArgError, "no block given");
+
+	VALUE r;
+	Map::iterator i = self->begin();
+	Map::iterator e = self->end();
+	for ( ; i != e; ++i )
+	  {
+	    r = swig::from( i->second );
+	    rb_yield(r);
+	  }
+	
+	return self;
+      }
+
+    VALUE entries() {
+      Map::size_type size = self->size();
+      int rubysize = (size <= (Map::size_type) INT_MAX) ? (int) size : -1;
+      if (rubysize < 0) {
+	SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	rb_raise(rb_eRuntimeError, "map size not valid in Ruby");
+	SWIG_RUBY_THREAD_END_BLOCK;
+	return Qnil;
+      }
+      VALUE ary = rb_ary_new2(rubysize);
+      Map::const_iterator i = self->begin();
+      Map::const_iterator e = self->end();
+      for ( ; i != e; ++i ) {
+	rb_ary_push( ary, swig::from<std::pair<Map::key_type, 
+		     Map::mapped_type> >(*i) );
+      }
+      return ary;
+    }
+    
+    bool __contains__(const key_type& key) {
+      return self->find(key) != self->end();
+    }
+
+    %newobject key_iterator(VALUE *RUBY_SELF);
+    swig::ConstIterator* key_iterator(VALUE *RUBY_SELF) {
+      return swig::make_output_key_iterator($self->begin(), $self->begin(), 
+					    $self->end(), *RUBY_SELF);
+    }
+
+    %newobject value_iterator(VALUE *RUBY_SELF);
+    swig::ConstIterator* value_iterator(VALUE *RUBY_SELF) {
+      return swig::make_output_value_iterator($self->begin(), $self->begin(), 
+					      $self->end(), *RUBY_SELF);
+    }
+
+  }
+%enddef
+
+%define %swig_map_methods(Map...)
+  %swig_map_common(Map)
+  %extend {
+    VALUE __getitem__(const key_type& key) const {
+      Map::const_iterator i = self->find(key);
+      if ( i != self->end() )
+	return swig::from<Map::mapped_type>( i->second );
+      else
+	return Qnil;
+    }
+
+    void __setitem__(const key_type& key, const mapped_type& x) throw (std::out_of_range) {
+      (*self)[key] = x;
+    }
+
+  VALUE inspect()
+    {
+      Map::const_iterator i = $self->begin();
+      Map::const_iterator e = $self->end();
+      VALUE str = rb_str_new2( swig::type_name< Map >() );
+      str = rb_str_cat2( str, " {" );
+      bool comma = false;
+      VALUE tmp;
+      for ( ; i != e; ++i, comma = true )
+	{
+	  if (comma) str = rb_str_cat2( str, "," );
+	  tmp = swig::from< Map::key_type >( i->first );
+	  tmp = rb_inspect( tmp );
+	  str = rb_str_buf_append( str, tmp );
+	  str = rb_str_cat2( str, "=>" );
+	  tmp = swig::from< Map::mapped_type >( i->second );
+	  tmp = rb_inspect( tmp );
+	  str = rb_str_buf_append( str, tmp );
+	}
+      str = rb_str_cat2( str, "}" );
+      return str;
+    }
+
+  VALUE to_a()
+    {
+      Map::const_iterator i = $self->begin();
+      Map::const_iterator e = $self->end();
+      VALUE ary = rb_ary_new2( std::distance( i, e ) );
+      VALUE tmp;
+      for ( ; i != e; ++i )
+	{
+	  // @todo: improve -- this should just be swig::from(*i)
+	  tmp = swig::from< std::pair<Map::key_type, 
+	    Map::mapped_type> >( *i );
+	  rb_ary_push( ary, tmp );
+	}
+      return ary;
+    }
+
+  VALUE to_s()
+    {
+      Map::iterator i = $self->begin();
+      Map::iterator e = $self->end();
+      VALUE str = rb_str_new2( "" );
+      VALUE tmp;
+      for ( ; i != e; ++i )
+	{
+	  // @todo: improve -- this should just be swig::from(*i)
+	  tmp = swig::from< std::pair<Map::key_type, 
+	    Map::mapped_type> >( *i );
+	  tmp = rb_obj_as_string( tmp );
+	  str = rb_str_buf_append( str, tmp );
+	}
+      return str;
+    }
+
+  }
+%enddef
+
+
+%mixin std::map "Enumerable";
+
+
+%rename("delete")     std::map::__delete__;
+%rename("reject!")    std::map::reject_bang;
+%rename("map!")       std::map::map_bang;
+%rename("empty?")     std::map::empty;
+%rename("include?" )  std::map::__contains__ const;
+%rename("has_key?" )  std::map::has_key const;
+
+%alias  std::map::push          "<<";
+
+
+%include <std/std_map.i>
diff --git a/trunk/Lib/ruby/std_multimap.i b/trunk/Lib/ruby/std_multimap.i
new file mode 100644
index 0000000..7fec50d
--- /dev/null
+++ b/trunk/Lib/ruby/std_multimap.i
@@ -0,0 +1,226 @@
+/*
+  Multimaps
+*/
+%include <std_map.i>
+
+%fragment("StdMultimapTraits","header",fragment="StdSequenceTraits")
+{
+  namespace swig {
+    template <class RubySeq, class K, class T >
+    inline void 
+    assign(const RubySeq& rubyseq, std::multimap<K,T > *multimap) {
+      typedef typename std::multimap<K,T>::value_type value_type;
+      typename RubySeq::const_iterator it = rubyseq.begin();
+      for (;it != rubyseq.end(); ++it) {
+	multimap->insert(value_type(it->first, it->second));
+      }
+    }
+
+    template <class K, class T>
+    struct traits_asptr<std::multimap<K,T> >  {
+      typedef std::multimap<K,T> multimap_type;
+      static int asptr(VALUE obj, std::multimap<K,T> **val) {
+	int res = SWIG_ERROR;
+	if ( TYPE(obj) == T_HASH ) {
+	  static ID id_to_a = rb_intern("to_a");
+	  VALUE items = rb_funcall(obj, id_to_a, 0);
+	  return traits_asptr_stdseq<std::multimap<K,T>, std::pair<K, T> >::asptr(items, val);
+	} else {
+	  multimap_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,swig::type_info<multimap_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+      }
+    };
+      
+    template <class K, class T >
+    struct traits_from<std::multimap<K,T> >  {
+      typedef std::multimap<K,T> multimap_type;
+      typedef typename multimap_type::const_iterator const_iterator;
+      typedef typename multimap_type::size_type size_type;
+            
+      static VALUE from(const multimap_type& multimap) {
+	swig_type_info *desc = swig::type_info<multimap_type>();
+	if (desc && desc->clientdata) {
+	  return SWIG_NewPointerObj(new multimap_type(multimap), desc, SWIG_POINTER_OWN);
+	} else {
+	  size_type size = multimap.size();
+	  int rubysize = (size <= (size_type) INT_MAX) ? (int) size : -1;
+	  if (rubysize < 0) {
+	    SWIG_RUBY_THREAD_BEGIN_BLOCK;
+	    rb_raise(rb_eRuntimeError,
+		     "multimap size not valid in Ruby");
+	    SWIG_RUBY_THREAD_END_BLOCK;
+	    return Qnil;
+	  }
+	  VALUE obj = rb_hash_new();
+	  for (const_iterator i= multimap.begin(); i!= multimap.end(); ++i) {
+	    VALUE key = swig::from(i->first);
+	    VALUE val = swig::from(i->second);
+
+	    VALUE oldval = rb_hash_aref( obj, key );
+	    if ( oldval == Qnil )
+	      rb_hash_aset(obj, key, val);
+	    else {
+	      // Multiple values for this key, create array if needed
+	      // and add a new element to it.
+	      VALUE ary;
+	      if ( TYPE(oldval) == T_ARRAY )
+		ary = oldval;
+	      else
+		{
+		  ary = rb_ary_new2(2);
+		  rb_ary_push( ary, oldval );
+		  rb_hash_aset( obj, key, ary );
+		}
+	      rb_ary_push( ary, val );
+	    }
+	    
+	  }
+	  return obj;
+	}
+      }
+    };
+  }
+}
+
+%define %swig_multimap_methods(MultiMap...) 
+  %swig_map_common(%arg(MultiMap));
+
+  %extend {
+    VALUE __getitem__(const key_type& key) const {
+      MultiMap::const_iterator i = self->find(key);
+      if ( i != self->end() )
+	{
+	  MultiMap::const_iterator e = $self->upper_bound(key);
+	  VALUE ary = rb_ary_new();
+	  for ( ; i != e; ++i )
+	    {
+	      rb_ary_push( ary, swig::from<MultiMap::mapped_type>( i->second ) );
+	    }
+	  if ( RARRAY_LEN(ary) == 1 )
+	    return RARRAY_PTR(ary)[0];
+	  return ary;
+	}
+      else
+	return Qnil;
+    }
+
+    void __setitem__(const key_type& key, const mapped_type& x) throw (std::out_of_range) {
+      self->insert(MultiMap::value_type(key,x));
+    }
+
+  VALUE inspect()
+    {
+      MultiMap::iterator i = $self->begin();
+      MultiMap::iterator e = $self->end();
+      VALUE str = rb_str_new2( swig::type_name< MultiMap >() );
+      str = rb_str_cat2( str, " {" );
+      VALUE tmp;
+      while ( i != e )
+	{
+	  const MultiMap::key_type& key    = i->first;
+	  const MultiMap::key_type& oldkey = key;
+	  tmp = swig::from( key );
+	  str = rb_str_buf_append( str, rb_inspect(tmp) );
+	  str = rb_str_cat2( str, "=>" );
+
+	  VALUE vals = rb_ary_new();
+	  for ( ; i != e && key == oldkey; ++i )
+	    {
+	      const MultiMap::mapped_type& val = i->second;
+	      tmp = swig::from( val );
+	      rb_ary_push( vals, tmp );
+	    }
+
+	  if ( RARRAY_LEN(vals) == 1 )
+	    {
+	      str = rb_str_buf_append( str, rb_inspect(tmp) );
+	    }
+	  else
+	    {
+	      str = rb_str_buf_append( str, rb_inspect(vals) );
+	    }
+	}
+      str = rb_str_cat2( str, "}" );
+      return str;
+    }
+
+  VALUE to_a()
+    {
+      MultiMap::const_iterator i = $self->begin();
+      MultiMap::const_iterator e = $self->end();
+      VALUE ary = rb_ary_new2( std::distance( i, e ) );
+      VALUE tmp;
+      while ( i != e )
+	{
+	  const MultiMap::key_type& key    = i->first;
+	  const MultiMap::key_type& oldkey = key;
+	  tmp = swig::from( key );
+	  rb_ary_push( ary, tmp );
+
+	  VALUE vals = rb_ary_new();
+	  for ( ; i != e && key == oldkey; ++i )
+	    {
+	      const MultiMap::mapped_type& val = i->second;
+	      tmp = swig::from( val );
+	      rb_ary_push( vals, tmp );
+	    }
+
+	  if ( RARRAY_LEN(vals) == 1 )
+	    {
+	      rb_ary_push( ary, tmp );
+	    }
+	  else
+	    {
+	      rb_ary_push( ary, vals );
+	    }
+	}
+      return ary;
+    }
+
+  VALUE to_s()
+    {
+      MultiMap::iterator i = $self->begin();
+      MultiMap::iterator e = $self->end();
+      VALUE str = rb_str_new2( "" );
+      VALUE tmp;
+      while ( i != e )
+	{
+	  const MultiMap::key_type& key    = i->first;
+	  const MultiMap::key_type& oldkey = key;
+	  tmp = swig::from( key );
+	  tmp = rb_obj_as_string( tmp );
+	  str = rb_str_buf_append( str, tmp );
+
+	  VALUE vals = rb_ary_new();
+	  for ( ; i != e && key == oldkey; ++i )
+	    {
+	      const MultiMap::mapped_type& val = i->second;
+	      tmp = swig::from( val );
+	      rb_ary_push( vals, tmp );
+	    }
+
+	  tmp = rb_obj_as_string( vals );
+	  str = rb_str_buf_append( str, tmp );
+	}
+      return str;
+    }
+  }
+%enddef
+
+
+%mixin std::multimap "Enumerable";
+
+%rename("delete")     std::multimap::__delete__;
+%rename("reject!")    std::multimap::reject_bang;
+%rename("map!")       std::multimap::map_bang;
+%rename("empty?")     std::multimap::empty;
+%rename("include?" )  std::multimap::__contains__ const;
+%rename("has_key?" )  std::multimap::has_key const;
+
+%alias  std::multimap::push          "<<";
+
+%include <std/std_multimap.i>
+
diff --git a/trunk/Lib/ruby/std_multiset.i b/trunk/Lib/ruby/std_multiset.i
new file mode 100644
index 0000000..87a7b29
--- /dev/null
+++ b/trunk/Lib/ruby/std_multiset.i
@@ -0,0 +1,50 @@
+/*
+  Multisets
+*/
+
+%include <std_set.i>
+
+%fragment("StdMultisetTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class RubySeq, class T> 
+    inline void
+    assign(const RubySeq& rubyseq, std::multiset<T>* seq) {
+      // seq->insert(rubyseq.begin(), rubyseq.end()); // not used as not always implemented
+      typedef typename RubySeq::value_type value_type;
+      typename RubySeq::const_iterator it = rubyseq.begin();
+      for (;it != rubyseq.end(); ++it) {
+	seq->insert(seq->end(),(value_type)(*it));
+      }
+    }
+
+    template <class T>
+    struct traits_asptr<std::multiset<T> >  {
+      static int asptr(VALUE obj, std::multiset<T> **m) {
+	return traits_asptr_stdseq<std::multiset<T> >::asptr(obj, m);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::multiset<T> > {
+      static VALUE from(const std::multiset<T>& vec) {
+	return traits_from_stdseq<std::multiset<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+#define %swig_multiset_methods(Set...) %swig_set_methods(Set)
+
+
+
+%rename("delete")     std::multiset::__delete__;
+%rename("reject!")    std::multiset::reject_bang;
+%rename("map!")       std::multiset::map_bang;
+%rename("empty?")     std::multiset::empty;
+%rename("include?" )  std::multiset::__contains__ const;
+%rename("has_key?" )  std::multiset::has_key const;
+
+%alias  std::multiset::push          "<<";
+
+%include <std/std_multiset.i>
diff --git a/trunk/Lib/ruby/std_pair.i b/trunk/Lib/ruby/std_pair.i
new file mode 100644
index 0000000..cb714e4
--- /dev/null
+++ b/trunk/Lib/ruby/std_pair.i
@@ -0,0 +1,207 @@
+/*
+  Pairs
+*/
+%include <rubystdcommon.swg>
+
+//#define SWIG_STD_PAIR_ASVAL
+
+%fragment("StdPairTraits","header",fragment="StdTraits") {
+  namespace swig {
+
+    template <class T, class U >
+    struct traits_asval<std::pair<T,U> >  {
+      typedef std::pair<T,U> value_type;
+
+      static int get_pair(VALUE first, VALUE second,
+			  std::pair<T,U> *val)
+      {
+	if (val) {
+	  T *pfirst = &(val->first);
+	  int res1 = swig::asval((VALUE)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = &(val->second);
+	  int res2 = swig::asval((VALUE)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  return res1 > res2 ? res1 : res2;
+	} else {
+	  T *pfirst = 0;
+	  int res1 = swig::asval((VALUE)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = 0;
+	  int res2 = swig::asval((VALUE)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  return res1 > res2 ? res1 : res2;
+	}	
+      }
+
+      static int asval(VALUE obj, std::pair<T,U> *val) {
+	int res = SWIG_ERROR;
+	if ( TYPE(obj) == T_ARRAY ) {
+	  if (RARRAY_LEN(obj) == 2) {
+	    VALUE first = rb_ary_entry(obj,0);
+	    VALUE second = rb_ary_entry(obj,1);
+	    res = get_pair(first, second, val);
+	  }
+	} else {
+	  value_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,
+				swig::type_info<value_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = *p;
+	}
+	return res;
+      }
+    };
+
+    template <class T, class U >
+    struct traits_asptr<std::pair<T,U> >  {
+      typedef std::pair<T,U> value_type;
+
+      static int get_pair(VALUE first, VALUE second,
+			  std::pair<T,U> **val) 
+      {
+	if (val) {
+	  value_type *vp = %new_instance(std::pair<T,U>);
+	  T *pfirst = &(vp->first);
+	  int res1 = swig::asval((VALUE)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = &(vp->second);
+	  int res2 = swig::asval((VALUE)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  *val = vp;
+	  return SWIG_AddNewMask(res1 > res2 ? res1 : res2);
+	} else {
+	  T *pfirst = 0;
+	  int res1 = swig::asval((VALUE)first, pfirst);
+	  if (!SWIG_IsOK(res1)) return res1;
+	  U *psecond = 0;
+	  int res2 = swig::asval((VALUE)second, psecond);
+	  if (!SWIG_IsOK(res2)) return res2;
+	  return res1 > res2 ? res1 : res2;
+	}	
+      }
+
+      static int asptr(VALUE obj, std::pair<T,U> **val) {
+	int res = SWIG_ERROR;
+	if ( TYPE(obj) == T_ARRAY ) {
+	  if ( RARRAY_LEN(obj) == 2) {
+	    VALUE first = rb_ary_entry(obj,0);
+	    VALUE second = rb_ary_entry(obj,1);
+	    res = get_pair(first, second, val);
+	  }
+	} else {
+	  value_type *p;
+	  res = SWIG_ConvertPtr(obj,(void**)&p,
+				swig::type_info<value_type>(),0);
+	  if (SWIG_IsOK(res) && val)  *val = p;
+	}
+	return res;
+      }
+    };
+
+
+
+    template <class T, class U >
+    struct traits_from<std::pair<T,U> >   {
+      static VALUE _wrap_pair_second( VALUE self )
+      {
+	std::pair< typename swig::noconst_traits<T >::noconst_type,U>* p = NULL;
+	swig::asptr( self, &p );
+	return swig::from( p->second );
+      }
+
+      static VALUE _wrap_pair_second_eq( VALUE self, VALUE arg )
+      {
+	std::pair< typename swig::noconst_traits<T >::noconst_type,U>* p = NULL;
+	swig::asptr( self, &p );
+	return swig::from( p->second );
+      }
+
+      static VALUE from(const std::pair<T,U>& val) {
+	VALUE obj = rb_ary_new2(2);
+	RARRAY_PTR(obj)[0] = swig::from< 
+	  typename swig::noconst_traits<T >::noconst_type>(val.first);
+	RARRAY_PTR(obj)[1] = swig::from(val.second);
+	RARRAY_LEN(obj) = 2;
+	rb_define_singleton_method(obj, "second",  
+				   VALUEFUNC(_wrap_pair_second), 0 );
+	rb_define_singleton_method(obj, "second=", 
+				   VALUEFUNC(_wrap_pair_second_eq), 1 );
+	rb_obj_freeze(obj); // treat as immutable tuple
+	return obj;
+      }
+    };
+
+  }
+}
+
+// Missing typemap
+%typemap(in) std::pair* (int res) {
+  res = swig::asptr( $input, &$1 );
+  if (!SWIG_IsOK(res))
+    %argument_fail(res, "$1_type", $symname, $argnum); 
+}
+
+
+%define %swig_pair_methods(pair...)
+
+%extend { 
+  VALUE inspect() const
+    {
+      VALUE tmp;
+      VALUE str = rb_str_new2( swig::type_name< pair >() );
+      str = rb_str_cat2( str, " (" );
+      tmp = swig::from( $self->first );
+      tmp = rb_obj_as_string( tmp );
+      str = rb_str_buf_append( str, tmp );
+      str = rb_str_cat2( str, "," );
+      tmp = swig::from( $self->second );
+      tmp = rb_obj_as_string( tmp );
+      str = rb_str_buf_append( str, tmp );
+      str = rb_str_cat2( str, ")" );
+      return str;
+    }
+
+  VALUE to_s() const
+    {
+      VALUE tmp;
+      VALUE str = rb_str_new2( "(" );
+      tmp = swig::from( $self->first );
+      tmp = rb_obj_as_string( tmp );
+      str = rb_str_buf_append( str, tmp );
+      str = rb_str_cat2( str, "," );
+      tmp = swig::from( $self->second );
+      tmp = rb_obj_as_string( tmp );
+      str = rb_str_buf_append( str, tmp );
+      str = rb_str_cat2( str, ")" );
+      return str;
+    }
+
+  VALUE __getitem__( int index )
+    { 
+      if (( index % 2 ) == 0 )
+	return swig::from( $self->first );
+      else
+	return swig::from( $self->second );
+    }
+
+  VALUE __setitem__( int index, VALUE obj )
+    { 
+      int res;
+      if (( index % 2 ) == 0 )
+	{
+	  res = swig::asval( obj, &($self->first) );
+	}
+      else
+	{
+	  res = swig::asval(obj, &($self->second) );
+	}
+      if (!SWIG_IsOK(res))
+	rb_raise( rb_eArgError, "invalid item for " #pair );
+      return obj;
+    }
+
+  } // extend
+
+%enddef
+
+%include <std/std_pair.i>
diff --git a/trunk/Lib/ruby/std_queue.i b/trunk/Lib/ruby/std_queue.i
new file mode 100644
index 0000000..a129367
--- /dev/null
+++ b/trunk/Lib/ruby/std_queue.i
@@ -0,0 +1,33 @@
+/*
+  Queues
+*/
+
+%fragment("StdQueueTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::queue<T> >  {
+      static int asptr(VALUE obj, std::queue<T>  **vec) {
+	return traits_asptr_stdseq<std::queue<T> >::asptr(obj, vec);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::queue<T> > {
+      static VALUE from(const std::queue<T> & vec) {
+	return traits_from_stdseq<std::queue<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+%rename("delete")     std::queue::__delete__;
+%rename("reject!")    std::queue::reject_bang;
+%rename("map!")       std::queue::map_bang;
+%rename("empty?")     std::queue::empty;
+%rename("include?" )  std::queue::__contains__ const;
+%rename("has_key?" )  std::queue::has_key const;
+
+%alias  std::queue::push          "<<";
+
+%include <std/std_queue.i>
diff --git a/trunk/Lib/ruby/std_set.i b/trunk/Lib/ruby/std_set.i
new file mode 100644
index 0000000..64428ab
--- /dev/null
+++ b/trunk/Lib/ruby/std_set.i
@@ -0,0 +1,213 @@
+/*
+  Sets
+*/
+
+%fragment("StdSetTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class RubySeq, class T> 
+    inline void 
+    assign(const RubySeq& rubyseq, std::set<T>* seq) {
+      // seq->insert(rubyseq.begin(), rubyseq.end()); // not used as not always implemented
+      typedef typename RubySeq::value_type value_type;
+      typename RubySeq::const_iterator it = rubyseq.begin();
+      for (;it != rubyseq.end(); ++it) {
+	seq->insert(seq->end(),(value_type)(*it));
+      }
+    }
+
+    template <class T>
+    struct traits_asptr<std::set<T> >  {
+      static int asptr(VALUE obj, std::set<T> **s) {  
+	return traits_asptr_stdseq<std::set<T> >::asptr(obj, s);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::set<T> > {
+      static VALUE from(const std::set<T>& vec) {
+	return traits_from_stdseq<std::set<T> >::from(vec);
+      }
+    };
+
+
+    /** 
+     * Set Iterator class for an iterator with no end() boundaries.
+     *
+     */
+    template<typename InOutIterator, 
+	     typename ValueType = typename std::iterator_traits<InOutIterator>::value_type,
+	     typename FromOper = from_oper<ValueType>,
+	     typename AsvalOper = asval_oper<ValueType> >
+      class SetIteratorOpen_T :  public Iterator_T<InOutIterator>
+    {
+    public:
+      FromOper  from;
+      AsvalOper asval;
+      typedef InOutIterator nonconst_iter;
+      typedef ValueType value_type;
+      typedef Iterator_T<nonconst_iter>  base;
+      typedef SetIteratorOpen_T<InOutIterator, ValueType, FromOper, AsvalOper> self_type;
+
+    public:
+      SetIteratorOpen_T(nonconst_iter curr, VALUE seq = Qnil)
+	: Iterator_T<InOutIterator>(curr, seq)
+      {
+      }
+    
+      virtual VALUE value() const {
+	return from(static_cast<const value_type&>(*(base::current)));
+      }
+
+      // no setValue allowed
+    
+      Iterator *dup() const
+      {
+	return new self_type(*this);
+      }
+    };
+
+
+    /** 
+     * Set Iterator class for a iterator where begin() and end() boundaries
+       are known.
+     *
+     */
+    template<typename InOutIterator, 
+	     typename ValueType = typename std::iterator_traits<InOutIterator>::value_type,
+	     typename FromOper = from_oper<ValueType>,
+	     typename AsvalOper = asval_oper<ValueType> >
+    class SetIteratorClosed_T :  public Iterator_T<InOutIterator>
+    {
+    public:
+      FromOper   from;
+      AsvalOper asval;
+      typedef InOutIterator nonconst_iter;
+      typedef ValueType value_type;
+      typedef Iterator_T<nonconst_iter>  base;
+      typedef SetIteratorClosed_T<InOutIterator, ValueType, FromOper, AsvalOper> self_type;
+    
+    protected:
+      virtual Iterator* advance(ptrdiff_t n)
+      {
+	std::advance( base::current, n );
+	if ( base::current == end )
+	  throw stop_iteration();
+	return this;
+      }
+
+    public:
+      SetIteratorClosed_T(nonconst_iter curr, nonconst_iter first, 
+		       nonconst_iter last, VALUE seq = Qnil)
+	: Iterator_T<InOutIterator>(curr, seq), begin(first), end(last)
+      {
+      }
+    
+      virtual VALUE value() const {
+	if (base::current == end) {
+	  throw stop_iteration();
+	} else {
+	  return from(static_cast<const value_type&>(*(base::current)));
+	}
+      }
+
+      // no setValue allowed
+    
+    
+      Iterator *dup() const
+      {
+	return new self_type(*this);
+      }
+
+    private:
+      nonconst_iter begin;
+      nonconst_iter end;
+    };
+
+    // Template specialization to construct a closed iterator for sets
+    // this turns a nonconst iterator into a const one for ruby to avoid
+    // allowing the user to change the value
+    template< typename InOutIter >
+    inline Iterator*
+    make_set_nonconst_iterator(const InOutIter& current, 
+			       const InOutIter& begin,
+			       const InOutIter& end, 
+			       VALUE seq = Qnil)
+    {
+      return new SetIteratorClosed_T< InOutIter >(current, 
+						  begin, end, seq);
+    }
+
+    // Template specialization to construct an open iterator for sets
+    // this turns a nonconst iterator into a const one for ruby to avoid
+    // allowing the user to change the value
+    template< typename InOutIter >
+    inline Iterator*
+    make_set_nonconst_iterator(const InOutIter& current, 
+			       VALUE seq = Qnil)
+    {
+      return new SetIteratorOpen_T< InOutIter >(current, seq);
+    }
+
+  }
+%}
+
+
+%define %swig_set_methods(set...)
+
+  %swig_sequence_methods_common(%arg(set));
+
+  %fragment("RubyPairBoolOutputIterator","header",fragment=SWIG_From_frag(bool),fragment="RubySequence_Cont") {}
+
+// Redefine std::set iterator/reverse_iterator typemap
+%typemap(out,noblock=1) iterator, reverse_iterator {
+  $result = SWIG_NewPointerObj(swig::make_set_nonconst_iterator(%static_cast($1,const $type &),
+								self),
+			          swig::Iterator::descriptor(),SWIG_POINTER_OWN);
+ }
+
+// Redefine std::set std::pair<iterator, bool> typemap
+  %typemap(out,noblock=1,fragment="RubyPairBoolOutputIterator")
+  std::pair<iterator, bool> {
+    $result = rb_ary_new2(2);
+    RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_set_nonconst_iterator(%static_cast($1,$type &).first),
+						swig::Iterator::descriptor(),SWIG_POINTER_OWN);    
+    RARRAY_PTR($result)[1] = SWIG_From(bool)(%static_cast($1,const $type &).second);
+    RARRAY_LEN($result) = 2;
+   }
+
+  %extend  {
+    %alias push "<<";
+    value_type push(const value_type& x) {
+      self->insert(x);
+      return x;
+    }
+  
+    bool __contains__(const value_type& x) {
+      return self->find(x) != self->end();
+    }
+
+    value_type __getitem__(difference_type i) const throw (std::out_of_range) {
+      return *(swig::cgetpos(self, i));
+    }
+
+  };
+%enddef
+
+
+%mixin std::set "Enumerable";
+
+
+
+%rename("delete")     std::set::__delete__;
+%rename("reject!")    std::set::reject_bang;
+%rename("map!")       std::set::map_bang;
+%rename("empty?")     std::set::empty;
+%rename("include?" )  std::set::__contains__ const;
+%rename("has_key?" )  std::set::has_key const;
+
+%alias  std::set::push          "<<";
+
+
+%include <std/std_set.i>
+
diff --git a/trunk/Lib/ruby/std_sstream.i b/trunk/Lib/ruby/std_sstream.i
new file mode 100644
index 0000000..537a3ae
--- /dev/null
+++ b/trunk/Lib/ruby/std_sstream.i
@@ -0,0 +1,2 @@
+
+%include <std/std_sstream.i>
diff --git a/trunk/Lib/ruby/std_stack.i b/trunk/Lib/ruby/std_stack.i
new file mode 100644
index 0000000..600c81c
--- /dev/null
+++ b/trunk/Lib/ruby/std_stack.i
@@ -0,0 +1,35 @@
+/*
+  Stacks
+*/
+
+%fragment("StdStackTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::stack<T> >  {
+      static int asptr(VALUE obj, std::stack<T>  **vec) {
+	return traits_asptr_stdseq<std::stack<T> >::asptr(obj, vec);
+      }
+    };
+
+    template <class T>
+    struct traits_from<std::stack<T> > {
+      static VALUE from(const std::stack<T> & vec) {
+	return traits_from_stdseq<std::stack<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+
+%rename("delete")     std::stack::__delete__;
+%rename("reject!")    std::stack::reject_bang;
+%rename("map!")       std::stack::map_bang;
+%rename("empty?")     std::stack::empty;
+%rename("include?" )  std::stack::__contains__ const;
+%rename("has_key?" )  std::stack::has_key const;
+
+%alias  std::stack::push          "<<";
+
+
+%include <std/std_stack.i>
diff --git a/trunk/Lib/ruby/std_streambuf.i b/trunk/Lib/ruby/std_streambuf.i
new file mode 100644
index 0000000..44b9bb4
--- /dev/null
+++ b/trunk/Lib/ruby/std_streambuf.i
@@ -0,0 +1 @@
+%include <std/std_streambuf.i>
diff --git a/trunk/Lib/ruby/std_string.i b/trunk/Lib/ruby/std_string.i
new file mode 100644
index 0000000..cac4324
--- /dev/null
+++ b/trunk/Lib/ruby/std_string.i
@@ -0,0 +1,9 @@
+
+%warnfilter(801) std::string;  // wrong class name
+%warnfilter(378) std::basic_string::operator!=;
+
+
+AUTODOC(substr, "Return a portion of the String");
+
+%include <typemaps/std_string.swg>
+
diff --git a/trunk/Lib/ruby/std_vector.i b/trunk/Lib/ruby/std_vector.i
new file mode 100644
index 0000000..67fdcd1
--- /dev/null
+++ b/trunk/Lib/ruby/std_vector.i
@@ -0,0 +1,52 @@
+/*
+  Vectors
+*/
+
+%fragment("StdVectorTraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T>
+    struct traits_asptr<std::vector<T> >  {
+      static int asptr(VALUE obj, std::vector<T> **vec) {
+	return traits_asptr_stdseq<std::vector<T> >::asptr(obj, vec);
+      }
+    };
+    
+    template <class T>
+    struct traits_from<std::vector<T> > {
+      static VALUE from(const std::vector<T>& vec) {
+	return traits_from_stdseq<std::vector<T> >::from(vec);
+      }
+    };
+  }
+%}
+
+
+
+%define %swig_vector_methods(Type...) 
+  %swig_sequence_methods(Type)
+  %swig_sequence_front_inserters(Type);
+%enddef
+
+%define %swig_vector_methods_val(Type...) 
+  %swig_sequence_methods_val(Type);
+  %swig_sequence_front_inserters(Type);
+%enddef
+
+
+%mixin std::vector "Enumerable";
+%ignore std::vector::push_back;
+%ignore std::vector::pop_back;
+
+
+%rename("delete")     std::vector::__delete__;
+%rename("reject!")    std::vector::reject_bang;
+%rename("map!")       std::vector::map_bang;
+%rename("empty?")     std::vector::empty;
+%rename("include?" )  std::vector::__contains__ const;
+%rename("has_key?" )  std::vector::has_key const;
+
+%alias  std::vector::push          "<<";
+
+%include <std/std_vector.i>
+
diff --git a/trunk/Lib/ruby/std_vectora.i b/trunk/Lib/ruby/std_vectora.i
new file mode 100644
index 0000000..1708361
--- /dev/null
+++ b/trunk/Lib/ruby/std_vectora.i
@@ -0,0 +1,36 @@
+/*
+  Vectors + allocators
+*/
+
+%fragment("StdVectorATraits","header",fragment="StdSequenceTraits")
+%{
+  namespace swig {
+    template <class T, class A>
+      struct traits_asptr<std::vector<T,A> >  {
+      typedef std::vector<T,A> vector_type;
+      typedef T value_type;
+      static int asptr(VALUE obj, vector_type **vec) {
+	return traits_asptr_stdseq<vector_type>::asptr(obj, vec);
+      }
+    };
+
+    template <class T, class A>
+    struct traits_from<std::vector<T,A> > {
+      typedef std::vector<T,A> vector_type;
+      static VALUE from(const vector_type& vec) {
+	return traits_from_stdseq<vector_type>::from(vec);
+      }
+    };
+  }
+%}
+
+
+#define %swig_vector_methods(Type...) %swig_sequence_methods(Type)
+#define %swig_vector_methods_val(Type...) %swig_sequence_methods_val(Type);
+
+%mixin std::vector "Enumerable";
+%ignore std::vector::push_back;
+%ignore std::vector::pop_back;
+%alias  std::vector::push "<<";
+
+%include <std/std_vectora.i>
diff --git a/trunk/Lib/ruby/std_wstring.i b/trunk/Lib/ruby/std_wstring.i
new file mode 100644
index 0000000..5ca77c0
--- /dev/null
+++ b/trunk/Lib/ruby/std_wstring.i
@@ -0,0 +1,3 @@
+%include <rubywstrings.swg>
+%include <typemaps/std_wstring.swg>
+
diff --git a/trunk/Lib/ruby/stl.i b/trunk/Lib/ruby/stl.i
new file mode 100644
index 0000000..66b72e0
--- /dev/null
+++ b/trunk/Lib/ruby/stl.i
@@ -0,0 +1,15 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ *
+ * Initial STL definition. extended as needed in each language
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/ruby/timeval.i b/trunk/Lib/ruby/timeval.i
new file mode 100644
index 0000000..91b5691
--- /dev/null
+++ b/trunk/Lib/ruby/timeval.i
@@ -0,0 +1,64 @@
+/*
+  struct timeval *
+  time_t
+
+  Ruby has builtin class Time.  INPUT/OUTPUT typemap for timeval and
+  time_t is provided.
+
+*/
+%{
+#ifdef __cplusplus
+extern "C" {
+#endif
+#ifdef HAVE_SYS_TIME_H
+# include <sys/time.h>
+struct timeval rb_time_timeval(VALUE);
+#endif
+#ifdef __cplusplus
+}
+#endif
+%}
+
+%typemap(in) struct timeval *INPUT (struct timeval temp)
+{
+    if (NIL_P($input))
+	$1 = NULL;
+    else {
+	temp = rb_time_timeval($input);
+	$1 = &temp;
+    }
+}
+
+%typemap(in,numinputs=0) struct timeval *OUTPUT(struct timeval temp)
+{
+    $1 = &temp;
+}
+
+%typemap(argout) struct timeval *OUTPUT
+{
+    $result = rb_time_new($1->tv_sec, $1->tv_usec);
+}
+
+%typemap(out) struct timeval *
+{
+    $result = rb_time_new($1->tv_sec, $1->tv_usec);
+}
+
+%typemap(out) struct timespec *
+{
+    $result = rb_time_new($1->tv_sec, $1->tv_nsec / 1000);
+}
+
+// time_t
+%typemap(in) time_t
+{
+    if (NIL_P($input))
+	$1 = (time_t)-1;
+    else
+	$1 = NUM2LONG(rb_funcall($input, rb_intern("tv_sec"), 0));
+}
+
+%typemap(out) time_t
+{
+    $result = rb_time_new($1, 0);
+}
diff --git a/trunk/Lib/ruby/typemaps.i b/trunk/Lib/ruby/typemaps.i
new file mode 100644
index 0000000..2492e2e
--- /dev/null
+++ b/trunk/Lib/ruby/typemaps.i
@@ -0,0 +1,317 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Pointer handling
+ *
+ * These mappings provide support for input/output arguments and
+ * common uses for C/C++ pointers.  INOUT mappings allow for C/C++
+ * pointer variables in addition to input/output arguments.
+ * ----------------------------------------------------------------------------- */
+
+#if !defined(SWIG_USE_OLD_TYPEMAPS)
+%include <typemaps/typemaps.swg>
+#else
+
+/*
+The SWIG typemap library provides a language independent mechanism for
+supporting output arguments, input values, and other C function
+calling mechanisms.  The primary use of the library is to provide a
+better interface to certain C function--especially those involving
+pointers.
+*/
+
+// ------------------------------------------------------------------------
+// Pointer handling
+//
+// These mappings provide support for input/output arguments and common
+// uses for C/C++ pointers.
+// ------------------------------------------------------------------------
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+/*
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+
+         int                *INPUT
+         short              *INPUT
+         long               *INPUT
+	 long long          *INPUT
+         unsigned int       *INPUT
+         unsigned short     *INPUT
+         unsigned long      *INPUT
+	 unsigned long long *INPUT
+         unsigned char      *INPUT
+	 bool               *INPUT
+         float              *INPUT
+         double             *INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include typemaps.i
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+
+%define INPUT_TYPEMAP(type, converter)
+%typemap(in) type *INPUT($*1_ltype temp), type &INPUT($*1_ltype temp)
+{
+    temp = ($*1_ltype) converter($input);
+    $1 = &temp;
+}
+%typemap(typecheck) type *INPUT = type;
+%typemap(typecheck) type &INPUT = type;
+%enddef
+
+INPUT_TYPEMAP(float, NUM2DBL);
+INPUT_TYPEMAP(double, NUM2DBL);
+INPUT_TYPEMAP(int, NUM2INT);
+INPUT_TYPEMAP(short, NUM2SHRT);
+INPUT_TYPEMAP(long, NUM2LONG);
+INPUT_TYPEMAP(long long, NUM2LL);
+INPUT_TYPEMAP(unsigned int, NUM2UINT);
+INPUT_TYPEMAP(unsigned short, NUM2USHRT);
+INPUT_TYPEMAP(unsigned long, NUM2ULONG);
+INPUT_TYPEMAP(unsigned long long, NUM2ULL);
+INPUT_TYPEMAP(unsigned char, NUM2UINT);
+INPUT_TYPEMAP(signed char, NUM2INT);
+INPUT_TYPEMAP(bool, RTEST);
+
+#undef INPUT_TYPEMAP
+
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a array element.
+
+/*
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, they are returned in the form of a Ruby Array.
+
+         int                *OUTPUT
+         short              *OUTPUT
+         long               *OUTPUT
+	 long long          *OUTPUT
+         unsigned int       *OUTPUT
+         unsigned short     *OUTPUT
+         unsigned long      *OUTPUT
+	 unsigned long long *OUTPUT
+         unsigned char      *OUTPUT
+	 bool               *OUTPUT
+         float              *OUTPUT
+         double             *OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters).K:
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include typemaps.i
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The Ruby output of the function would be a Array containing both
+output values. 
+*/
+
+%define OUTPUT_TYPEMAP(type, converter, convtype)
+%typemap(in,numinputs=0) type *OUTPUT($*1_ltype temp), type &OUTPUT($*1_ltype temp) "$1 = &temp;";
+%typemap(argout, fragment="output_helper") type *OUTPUT, type &OUTPUT {
+   VALUE o = converter(convtype (*$1));
+   $result = output_helper($result, o);
+}
+%enddef
+
+OUTPUT_TYPEMAP(int, INT2NUM, (int));
+OUTPUT_TYPEMAP(short, INT2NUM, (int));
+OUTPUT_TYPEMAP(long, INT2NUM, (long));
+OUTPUT_TYPEMAP(long long, LL2NUM, (long long));
+OUTPUT_TYPEMAP(unsigned int, UINT2NUM, (unsigned int));
+OUTPUT_TYPEMAP(unsigned short, UINT2NUM, (unsigned int));
+OUTPUT_TYPEMAP(unsigned long, UINT2NUM, (unsigned long));
+OUTPUT_TYPEMAP(unsigned long long, ULL2NUM, (unsigned long long));
+OUTPUT_TYPEMAP(unsigned char, UINT2NUM, (unsigned int));
+OUTPUT_TYPEMAP(signed char, INT2NUM, (int));
+OUTPUT_TYPEMAP(float, rb_float_new, (double));
+OUTPUT_TYPEMAP(double, rb_float_new, (double));
+
+#undef OUTPUT_TYPEMAP
+
+%typemap(in,numinputs=0) bool *OUTPUT(bool temp), bool &OUTPUT(bool temp) "$1 = &temp;";
+%typemap(argout, fragment="output_helper") bool *OUTPUT, bool &OUTPUT {
+    VALUE o = (*$1) ? Qtrue : Qfalse;
+    $result = output_helper($result, o);
+}
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a Ruby array.
+
+         int                *INOUT
+         short              *INOUT
+         long               *INOUT
+	 long long          *INOUT
+         unsigned int       *INOUT
+         unsigned short     *INOUT
+         unsigned long      *INOUT
+	 unsigned long long *INOUT
+         unsigned char      *INOUT
+	 bool               *INOUT
+         float              *INOUT
+         double             *INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include typemaps.i
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+Unlike C, this mapping does not directly modify the input value (since
+this makes no sense in Ruby).  Rather, the modified input value shows
+up as the return value of the function.  Thus, to apply this function
+to a Ruby variable you might do this :
+
+       x = neg(x)
+
+Note : previous versions of SWIG used the symbol 'BOTH' to mark
+input/output arguments.   This is still supported, but will be slowly
+phased out in future releases.
+
+*/
+
+%typemap(in) int *INOUT = int *INPUT;
+%typemap(in) short *INOUT = short *INPUT;
+%typemap(in) long *INOUT = long *INPUT;
+%typemap(in) long long *INOUT = long long *INPUT;
+%typemap(in) unsigned *INOUT = unsigned *INPUT;
+%typemap(in) unsigned short *INOUT = unsigned short *INPUT;
+%typemap(in) unsigned long *INOUT = unsigned long *INPUT;
+%typemap(in) unsigned long long *INOUT = unsigned long long *INPUT;
+%typemap(in) unsigned char *INOUT = unsigned char *INPUT;
+%typemap(in) signed char *INOUT = signed char *INPUT;
+%typemap(in) bool *INOUT = bool *INPUT;
+%typemap(in) float *INOUT = float *INPUT;
+%typemap(in) double *INOUT = double *INPUT;
+
+%typemap(in) int &INOUT = int &INPUT;
+%typemap(in) short &INOUT = short &INPUT;
+%typemap(in) long &INOUT = long &INPUT;
+%typemap(in) long long &INOUT = long long &INPUT;
+%typemap(in) unsigned &INOUT = unsigned &INPUT;
+%typemap(in) unsigned short &INOUT = unsigned short &INPUT;
+%typemap(in) unsigned long &INOUT = unsigned long &INPUT;
+%typemap(in) unsigned long long &INOUT = unsigned long long &INPUT;
+%typemap(in) unsigned char &INOUT = unsigned char &INPUT;
+%typemap(in) signed char &INOUT = signed char &INPUT;
+%typemap(in) bool &INOUT = bool &INPUT;
+%typemap(in) float &INOUT = float &INPUT;
+%typemap(in) double &INOUT = double &INPUT;
+
+%typemap(argout) int *INOUT = int *OUTPUT;
+%typemap(argout) short *INOUT = short *OUTPUT;
+%typemap(argout) long *INOUT = long *OUTPUT;
+%typemap(argout) long long *INOUT = long long *OUTPUT;
+%typemap(argout) unsigned *INOUT = unsigned *OUTPUT;
+%typemap(argout) unsigned short *INOUT = unsigned short *OUTPUT;
+%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT;
+%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT;
+%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT;
+%typemap(argout) signed char *INOUT = signed char *OUTPUT;
+%typemap(argout) bool *INOUT = bool *OUTPUT;
+%typemap(argout) float *INOUT = float *OUTPUT;
+%typemap(argout) double *INOUT = double *OUTPUT;
+
+%typemap(argout) int &INOUT = int &OUTPUT;
+%typemap(argout) short &INOUT = short &OUTPUT;
+%typemap(argout) long &INOUT = long &OUTPUT;
+%typemap(argout) long long &INOUT = long long &OUTPUT;
+%typemap(argout) unsigned &INOUT = unsigned &OUTPUT;
+%typemap(argout) unsigned short &INOUT = unsigned short &OUTPUT;
+%typemap(argout) unsigned long &INOUT = unsigned long &OUTPUT;
+%typemap(argout) unsigned long long &INOUT = unsigned long long &OUTPUT;
+%typemap(argout) unsigned char &INOUT = unsigned char &OUTPUT;
+%typemap(argout) signed char &INOUT = signed char &OUTPUT;
+%typemap(argout) bool &INOUT = bool &OUTPUT;
+%typemap(argout) float &INOUT = float &OUTPUT;
+%typemap(argout) double &INOUT = double &OUTPUT;
+
+/* Overloading information */
+
+%typemap(typecheck) double *INOUT = double;
+%typemap(typecheck) signed char *INOUT = signed char;
+%typemap(typecheck) unsigned char *INOUT = unsigned char;
+%typemap(typecheck) unsigned long *INOUT = unsigned long;
+%typemap(typecheck) unsigned long long *INOUT = unsigned long long;
+%typemap(typecheck) unsigned short *INOUT = unsigned short;
+%typemap(typecheck) unsigned int *INOUT = unsigned int;
+%typemap(typecheck) long *INOUT = long;
+%typemap(typecheck) long long *INOUT = long long;
+%typemap(typecheck) short *INOUT = short;
+%typemap(typecheck) int *INOUT = int;
+%typemap(typecheck) float *INOUT = float;
+
+%typemap(typecheck) double &INOUT = double;
+%typemap(typecheck) signed char &INOUT = signed char;
+%typemap(typecheck) unsigned char &INOUT = unsigned char;
+%typemap(typecheck) unsigned long &INOUT = unsigned long;
+%typemap(typecheck) unsigned long long &INOUT = unsigned long long;
+%typemap(typecheck) unsigned short &INOUT = unsigned short;
+%typemap(typecheck) unsigned int &INOUT = unsigned int;
+%typemap(typecheck) long &INOUT = long;
+%typemap(typecheck) long long &INOUT = long long;
+%typemap(typecheck) short &INOUT = short;
+%typemap(typecheck) int &INOUT = int;
+%typemap(typecheck) float &INOUT = float;
+
+#endif
+
+// --------------------------------------------------------------------
+// Special types
+// --------------------------------------------------------------------
+%include <progargcargv.i>
+%include <file.i>
+%include <timeval.i>
diff --git a/trunk/Lib/runtime.swg b/trunk/Lib/runtime.swg
new file mode 100644
index 0000000..1528a52
--- /dev/null
+++ b/trunk/Lib/runtime.swg
@@ -0,0 +1,38 @@
+/* -----------------------------------------------------------------------------*
+   Standard SWIG API for use inside user code.
+ 
+   Don't include this file directly, run the command
+   swig -python -external-runtime
+   Also, read the Modules chapter of the SWIG Manual.
+ 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_MODULE_CLIENTDATA_TYPE
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_TypeQuery(SWIG_MODULE_CLIENTDATA_TYPE clientdata, const char *name) {
+  swig_module_info *module = SWIG_GetModule(clientdata);
+  return SWIG_TypeQueryModule(module, module, name);
+}
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_MangledTypeQuery(SWIG_MODULE_CLIENTDATA_TYPE clientdata, const char *name) {
+  swig_module_info *module = SWIG_GetModule(clientdata);
+  return SWIG_MangledTypeQueryModule(module, module, name);
+}
+
+#else
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_TypeQuery(const char *name) {
+  swig_module_info *module = SWIG_GetModule(NULL);
+  return SWIG_TypeQueryModule(module, module, name);
+}
+
+SWIGRUNTIMEINLINE swig_type_info *
+SWIG_MangledTypeQuery(const char *name) {
+  swig_module_info *module = SWIG_GetModule(NULL);
+  return SWIG_MangledTypeQueryModule(module, module, name);
+}
+
+#endif
diff --git a/trunk/Lib/shared_ptr.i b/trunk/Lib/shared_ptr.i
new file mode 100644
index 0000000..0ccce64
--- /dev/null
+++ b/trunk/Lib/shared_ptr.i
@@ -0,0 +1,57 @@
+// shared_ptr namespaces could be boost or std or std::tr1
+#if !defined(SWIG_SHARED_PTR_NAMESPACE)
+# define SWIG_SHARED_PTR_NAMESPACE boost
+#endif
+
+#if defined(SWIG_SHARED_PTR_SUBNAMESPACE)
+# define SWIG_SHARED_PTR_QNAMESPACE SWIG_SHARED_PTR_NAMESPACE::SWIG_SHARED_PTR_SUBNAMESPACE
+#else
+# define SWIG_SHARED_PTR_QNAMESPACE SWIG_SHARED_PTR_NAMESPACE
+#endif
+
+namespace SWIG_SHARED_PTR_NAMESPACE {
+#if defined(SWIG_SHARED_PTR_SUBNAMESPACE)
+  namespace SWIG_SHARED_PTR_SUBNAMESPACE {
+#endif
+    template <class T> class shared_ptr {
+    };
+#if defined(SWIG_SHARED_PTR_SUBNAMESPACE)
+  }
+#endif
+}
+
+%fragment("SWIG_null_deleter", "header") {
+struct SWIG_null_deleter {
+  void operator() (void const *) const {
+  }
+};
+%#define SWIG_NO_NULL_DELETER_0 , SWIG_null_deleter()
+%#define SWIG_NO_NULL_DELETER_1
+%#define SWIG_NO_NULL_DELETER_SWIG_POINTER_NEW
+%#define SWIG_NO_NULL_DELETER_SWIG_POINTER_OWN
+}
+
+
+// Main user macro for defining shared_ptr typemaps for both const and non-const pointer types
+// For plain classes, do not use for derived classes
+%define SWIG_SHARED_PTR(PROXYCLASS, TYPE...)
+SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, , TYPE)
+SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, const, TYPE)
+%enddef
+
+// Main user macro for defining shared_ptr typemaps for both const and non-const pointer types
+// For derived classes
+%define SWIG_SHARED_PTR_DERIVED(PROXYCLASS, BASECLASSTYPE, TYPE...)
+SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, , TYPE)
+SWIG_SHARED_PTR_TYPEMAPS(PROXYCLASS, const, TYPE)
+%types(SWIG_SHARED_PTR_NAMESPACE::shared_ptr< TYPE > = SWIG_SHARED_PTR_NAMESPACE::shared_ptr< BASECLASSTYPE >) %{
+  *newmemory = SWIG_CAST_NEW_MEMORY;
+  return (void *) new SWIG_SHARED_PTR_NAMESPACE::shared_ptr< BASECLASSTYPE >(*(SWIG_SHARED_PTR_NAMESPACE::shared_ptr< TYPE > *)$from);
+  %}
+%extend TYPE {
+  static SWIG_SHARED_PTR_NAMESPACE::shared_ptr< BASECLASSTYPE > SWIGSharedPtrUpcast(SWIG_SHARED_PTR_NAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast) {
+    return swigSharedPtrUpcast;
+  }
+}
+%enddef
+
diff --git a/trunk/Lib/std/README b/trunk/Lib/std/README
new file mode 100644
index 0000000..5cd759d
--- /dev/null
+++ b/trunk/Lib/std/README
@@ -0,0 +1,22 @@
+/* -----------------------------------------------------------------------------
+ *  C++ STD + STL 
+ * ----------------------------------------------------------------------------- */
+
+std_common.i		general common code 
+std_container.i		general container code 
+std_basic_string.i	basic string
+std_char_traits.i	char traits
+std_complex.i		complex
+std_deque.i		deque	
+std_except.i		exceptions
+std_ios.i		ios
+std_iostream.i		istream/ostream
+std_list.i		list
+std_map.i		map
+std_multimap.i		multimap
+std_multiset.i		multiset
+std_pair.i		pair
+std_set.i		set
+std_streambuf.i		streambuf
+std_vector.i		vector
+std_vectora.i		vector + allocator
diff --git a/trunk/Lib/std/_std_deque.i b/trunk/Lib/std/_std_deque.i
new file mode 100644
index 0000000..026f373
--- /dev/null
+++ b/trunk/Lib/std/_std_deque.i
@@ -0,0 +1,126 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * _std_deque.i
+ *
+ * This file contains a generic definition of std::deque along with
+ * some helper functions.  Specific language modules should include
+ * this file to generate wrappers. 
+ * ----------------------------------------------------------------------------- */
+
+%include <std_except.i>
+
+%{
+#include <deque>
+#include <stdexcept>
+%}
+
+
+/* This macro defines all of the standard methods for a deque.  This
+   is defined as a macro to simplify the task of specialization.  For
+   example,
+
+         template<> class deque<int> {
+         public:
+             %std_deque_methods(int);
+         };
+*/
+
+%define %std_deque_methods(T)
+       typedef T &reference;
+       typedef const T& const_reference;
+
+       deque();
+       deque(unsigned int size, const T& value=T());
+       deque(const deque<T> &);
+      ~deque();
+
+       void assign(unsigned int n, const T& value);
+       void swap(deque<T> &x);
+       unsigned int size() const;
+       unsigned int max_size() const;
+       void resize(unsigned int n, T c = T());
+       bool empty() const;
+       const_reference front();
+       const_reference back();
+       void push_front(const T& x);
+       void push_back(const T& x);
+       void pop_front();
+       void pop_back();
+       void clear();
+
+       /* Some useful extensions */
+       %extend {
+           const_reference getitem(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i<0) i += size;
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("deque index out of range");
+           }
+           void setitem(int i, const T& x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i<0) i+= size;
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("deque index out of range");
+           }
+           void delitem(int i) throw (std::out_of_range) {
+            	int size = int(self->size());
+                if (i<0) i+= size;
+                if (i>=0 && i<size) {
+                    self->erase(self->begin()+i);
+                } else {
+                    throw std::out_of_range("deque index out of range");
+                }
+           }
+	   std::deque<T> getslice(int i, int j) {
+                int size = int(self->size());
+                if (i<0) i = size+i;
+                if (j<0) j = size+j;
+                if (i<0) i = 0;
+                if (j>size) j = size;
+                std::deque<T > tmp(j-i);
+                std::copy(self->begin()+i,self->begin()+j,tmp.begin());
+                return tmp;
+            }
+            void setslice(int i, int j, const std::deque<T>& v) {
+                int size = int(self->size());
+                if (i<0) i = size+i;
+                if (j<0) j = size+j;
+                if (i<0) i = 0;
+                if (j>size) j = size;
+                if (int(v.size()) == j-i) {
+                    std::copy(v.begin(),v.end(),self->begin()+i);
+                } else {
+                    self->erase(self->begin()+i,self->begin()+j);
+                    if (i+1 <= size)
+                        self->insert(self->begin()+i+1,v.begin(),v.end());
+                    else
+                        self->insert(self->end(),v.begin(),v.end());
+                }
+            }
+            void delslice(int i, int j) {
+                int size = int(self->size());
+                if (i<0) i = size+i;
+                if (j<0) j = size+j;
+                if (i<0) i = 0;
+                if (j>size) j = size;
+                self->erase(self->begin()+i,self->begin()+j);
+            }
+       };
+
+%enddef
+
+namespace std {
+    template<class T> class deque {
+    public:
+       %std_deque_methods(T);
+    };
+}
+
+
+
diff --git a/trunk/Lib/std/std_alloc.i b/trunk/Lib/std/std_alloc.i
new file mode 100644
index 0000000..44dc8dc
--- /dev/null
+++ b/trunk/Lib/std/std_alloc.i
@@ -0,0 +1,77 @@
+namespace std
+{
+  /**
+   *  @brief  The "standard" allocator, as per [20.4].
+   *
+   *  The private _Alloc is "SGI" style.  (See comments at the top
+   *  of stl_alloc.h.)
+   *
+   *  The underlying allocator behaves as follows.
+   *    - __default_alloc_template is used via two typedefs
+   *    - "__single_client_alloc" typedef does no locking for threads
+   *    - "__alloc" typedef is threadsafe via the locks
+   *    - __new_alloc is used for memory requests
+   *
+   *  (See @link Allocators allocators info @endlink for more.)
+   */
+  template<typename _Tp>
+    class allocator
+    {
+    public:
+      typedef size_t     size_type;
+      typedef ptrdiff_t  difference_type;
+      typedef _Tp*       pointer;
+      typedef const _Tp* const_pointer;
+      typedef _Tp&       reference;
+      typedef const _Tp& const_reference;
+      typedef _Tp        value_type;
+
+      template<typename _Tp1>
+        struct rebind;
+
+      allocator() throw();
+      
+      allocator(const allocator&) throw();
+      template<typename _Tp1>
+        allocator(const allocator<_Tp1>&) throw();
+      ~allocator() throw();
+      
+
+      pointer
+      address(reference __x) const;
+      
+
+      const_pointer
+      address(const_reference __x) const;
+      
+
+      // NB: __n is permitted to be 0.  The C++ standard says nothing
+      // about what the return value is when __n == 0.
+      _Tp*
+      allocate(size_type __n, const void* = 0);
+
+      // __p is not permitted to be a null pointer.
+      void
+      deallocate(pointer __p, size_type __n);
+
+      size_type
+      max_size() const throw();
+
+      void construct(pointer __p, const _Tp& __val);
+      void destroy(pointer __p);
+    };
+
+  template<>
+    class allocator<void>
+    {
+    public:
+      typedef size_t      size_type;
+      typedef ptrdiff_t   difference_type;
+      typedef void*       pointer;
+      typedef const void* const_pointer;
+      typedef void        value_type;
+
+      template<typename _Tp1>
+        struct rebind;
+    };
+} // namespace std
diff --git a/trunk/Lib/std/std_basic_string.i b/trunk/Lib/std/std_basic_string.i
new file mode 100644
index 0000000..7b0898a
--- /dev/null
+++ b/trunk/Lib/std/std_basic_string.i
@@ -0,0 +1,270 @@
+%include <exception.i>
+%include <std_container.i>
+%include <std_alloc.i>
+%include <std_char_traits.i>
+
+
+%{
+#include <string>
+%}
+
+namespace std
+{
+  %naturalvar basic_string;
+}
+
+
+namespace std {
+
+  template <class _CharT, class _Traits = char_traits<_CharT>, typename _Alloc = allocator<_CharT> > 
+  class basic_string
+  {
+#if !defined(SWIG_STD_MODERN_STL) || defined(SWIG_STD_NOMODERN_STL)
+    %ignore push_back;
+    %ignore clear;
+    %ignore compare;
+    %ignore append;
+#endif
+
+  public:
+    typedef size_t size_type;    
+    typedef ptrdiff_t difference_type;
+    typedef _CharT value_type;
+    typedef value_type reference;
+    typedef value_type const_reference;
+    typedef _Alloc allocator_type;
+    
+    static const size_type npos;
+
+#ifdef SWIG_EXPORT_ITERATOR_METHODS
+  class iterator;
+  class reverse_iterator;
+  class const_iterator;
+  class const_reverse_iterator;
+#endif
+
+
+    %traits_swigtype(_CharT);
+    %fragment(SWIG_Traits_frag(_CharT));
+    
+
+    basic_string(const _CharT* __s, size_type __n);
+
+    // Capacity:
+
+    size_type length() const;
+
+    size_type max_size() const;
+
+    size_type capacity() const;
+
+    void reserve(size_type __res_arg = 0);
+
+
+    // Modifiers:
+
+    basic_string& 
+    append(const basic_string& __str);
+
+    basic_string& 
+    append(const basic_string& __str, size_type __pos, size_type __n);
+
+    basic_string& 
+    append(const _CharT* __s, size_type __n);
+    
+    basic_string& 
+    append(size_type __n, _CharT __c);
+
+    basic_string& 
+    assign(const basic_string& __str);
+
+    basic_string& 
+    assign(const basic_string& __str, size_type __pos, size_type __n);
+    
+    basic_string& 
+    assign(const _CharT* __s, size_type __n);
+
+    basic_string& 
+    insert(size_type __pos1, const basic_string& __str);    
+
+    basic_string& 
+    insert(size_type __pos1, const basic_string& __str,
+	   size_type __pos2, size_type __n);
+
+    basic_string& 
+    insert(size_type __pos, const _CharT* __s, size_type __n);
+
+    basic_string& 
+    insert(size_type __pos, size_type __n, _CharT __c);
+
+    basic_string& 
+    erase(size_type __pos = 0, size_type __n = npos);
+
+    basic_string& 
+    replace(size_type __pos, size_type __n, const basic_string& __str);
+
+    basic_string& 
+    replace(size_type __pos1, size_type __n1, const basic_string& __str,
+	    size_type __pos2, size_type __n2);
+
+    basic_string& 
+    replace(size_type __pos, size_type __n1, const _CharT* __s,
+	    size_type __n2);
+
+    basic_string& 
+    replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c);
+
+
+    size_type 
+    copy(_CharT* __s, size_type __n, size_type __pos = 0) const;    
+
+    // String operations:
+    const _CharT* c_str() const;
+
+    size_type 
+    find(const _CharT* __s, size_type __pos, size_type __n) const;
+    
+    size_type 
+    find(const basic_string& __str, size_type __pos = 0) const;
+
+    size_type 
+    find(_CharT __c, size_type __pos = 0) const;
+
+    size_type 
+    rfind(const basic_string& __str, size_type __pos = npos) const;
+
+    size_type 
+    rfind(const _CharT* __s, size_type __pos, size_type __n) const;
+
+    size_type 
+    rfind(_CharT __c, size_type __pos = npos) const;
+
+    size_type 
+    find_first_of(const basic_string& __str, size_type __pos = 0) const;
+
+    size_type 
+    find_first_of(const _CharT* __s, size_type __pos, size_type __n) const;
+
+    size_type 
+    find_first_of(_CharT __c, size_type __pos = 0) const;
+
+    size_type 
+    find_last_of(const basic_string& __str, size_type __pos = npos) const;
+    
+    size_type 
+    find_last_of(const _CharT* __s, size_type __pos, size_type __n) const;
+
+    size_type 
+    find_last_of(_CharT __c, size_type __pos = npos) const;
+    
+    size_type 
+    find_first_not_of(const basic_string& __str, size_type __pos = 0) const;
+
+    size_type 
+    find_first_not_of(const _CharT* __s, size_type __pos, 
+		      size_type __n) const;
+
+    size_type 
+    find_first_not_of(_CharT __c, size_type __pos = 0) const;
+
+    size_type 
+    find_last_not_of(const basic_string& __str, size_type __pos = npos) const;
+
+    size_type 
+    find_last_not_of(const _CharT* __s, size_type __pos, 
+		     size_type __n) const;
+    
+    size_type 
+    find_last_not_of(_CharT __c, size_type __pos = npos) const;
+
+    basic_string 
+    substr(size_type __pos = 0, size_type __n = npos) const;
+
+    int 
+    compare(const basic_string& __str) const;
+
+    int 
+    compare(size_type __pos, size_type __n, const basic_string& __str) const;
+
+    int 
+    compare(size_type __pos1, size_type __n1, const basic_string& __str,
+	    size_type __pos2, size_type __n2) const;
+
+
+    %ignore pop_back();
+    %ignore front() const;
+    %ignore back() const;
+    %ignore basic_string(size_type n);
+    %std_sequence_methods_val(basic_string);    
+
+
+    %ignore pop();
+
+
+#ifdef %swig_basic_string
+    // Add swig/language extra methods
+    %swig_basic_string(std::basic_string<_CharT, _Traits, _Alloc >);
+#endif
+
+#ifdef SWIG_EXPORT_ITERATOR_METHODS
+
+    
+    class iterator;
+    class reverse_iterator;
+    class const_iterator;
+    class const_reverse_iterator;
+
+
+    void 
+    insert(iterator __p, size_type __n, _CharT __c);
+
+    basic_string& 
+    replace(iterator __i1, iterator __i2, const basic_string& __str);
+
+    basic_string& 
+    replace(iterator __i1, iterator __i2, const _CharT* __s, size_type __n);
+
+    basic_string& 
+    replace(iterator __i1, iterator __i2, size_type __n, _CharT __c);
+
+
+    basic_string& 
+    replace(iterator __i1, iterator __i2, const _CharT* __k1, const _CharT* __k2);
+
+    basic_string& 
+    replace(iterator __i1, iterator __i2, const_iterator __k1, const_iterator __k2);
+#endif
+
+    basic_string& operator +=(const basic_string& v);
+
+    %newobject __add__;   
+    %newobject __radd__;
+    %extend {
+
+      std::basic_string<_CharT,_Traits,_Alloc >* __add__(const basic_string& v) {
+	std::basic_string<_CharT,_Traits,_Alloc >* res = new std::basic_string<_CharT,_Traits,_Alloc >(*self);
+	*res += v;      
+	return res;
+      }
+      
+      std::basic_string<_CharT,_Traits,_Alloc >* __radd__(const basic_string& v) {
+	std::basic_string<_CharT,_Traits,_Alloc >* res = new std::basic_string<_CharT,_Traits,_Alloc >(v);
+	*res += *self;      
+	return res;
+      }
+      
+      std::basic_string<_CharT,_Traits,_Alloc > __str__() {
+	return *self;
+      }
+
+      std::basic_ostream<_CharT, std::char_traits<_CharT> >&
+	__rlshift__(std::basic_ostream<_CharT, std::char_traits<_CharT> >& out) {
+	out << *self;
+	return out;
+      }
+    }
+
+  };
+}
+
+
diff --git a/trunk/Lib/std/std_carray.swg b/trunk/Lib/std/std_carray.swg
new file mode 100644
index 0000000..ebb20ce
--- /dev/null
+++ b/trunk/Lib/std/std_carray.swg
@@ -0,0 +1,64 @@
+%{
+#include <algorithm>
+%}
+
+//
+// std::carray - is really an extension to the 'std' namespace.
+// 
+// A simple fix C array wrapper, more or less as presented in
+//
+//   "The C++ Standarf Library", by Nicolai M. Josuttis
+//
+// which is also derived from the example in
+//
+//   "The C++ Programming Language", by Bjarne Stroustup.
+//
+
+%inline %{
+namespace std {    
+  template <class _Type, size_t _Size>
+  class carray 
+  {
+  public:
+    typedef _Type value_type;    
+    typedef size_t size_type;
+    
+    typedef _Type * iterator;
+    typedef const _Type * const_iterator;
+    
+    carray() { }
+    
+    carray(const carray& c) {
+      std::copy(c.v, c.v + size(), v);
+    }
+    
+    template <class _Iterator>
+    carray(_Iterator first, _Iterator last) {
+      assign(first, last);
+    }
+
+    iterator begin() { return v; }
+    iterator end() { return v + _Size; }
+
+    const_iterator begin() const { return v; }
+    const_iterator end() const { return v + _Size; }
+    
+    _Type& operator[](size_t i) { return v[i]; }
+    const _Type& operator[](size_t i) const { return v[i]; }
+
+    static size_t size() { return _Size; }    
+
+    template <class _Iterator>
+    void assign(_Iterator first, _Iterator last)  {
+      if (std::distance(first,last) == size()) {
+	std::copy(first, last, v);
+      } else {
+	throw std::length_error("bad range length");
+      }
+    }
+      
+  private:
+    _Type v[_Size];
+  };
+}
+%}
diff --git a/trunk/Lib/std/std_char_traits.i b/trunk/Lib/std/std_char_traits.i
new file mode 100644
index 0000000..b9b4def
--- /dev/null
+++ b/trunk/Lib/std/std_char_traits.i
@@ -0,0 +1,140 @@
+%include <std_common.i>
+#if defined(SWIG_WCHAR)
+%include <wchar.i>
+#endif
+
+namespace std 
+{
+  
+  /// 21.1.2 Basis for explicit _Traits specialization 
+  /// NB: That for any given actual character type this definition is
+  /// probably wrong.
+  template<class _CharT>
+  struct char_traits
+  {
+  };
+
+
+  /// 21.1.4  char_traits specializations
+  template<>
+  struct char_traits<char> {
+    typedef char 		char_type;
+    typedef int 	        int_type;
+    typedef streampos 	pos_type;
+    typedef streamoff 	off_type;
+    typedef mbstate_t 	state_type;
+
+    static void 
+    assign(char_type& __c1, const char_type& __c2);
+    
+    static bool 
+    eq(const char_type& __c1, const char_type& __c2);
+
+    static bool 
+    lt(const char_type& __c1, const char_type& __c2);
+
+    static int 
+    compare(const char_type* __s1, const char_type* __s2, size_t __n);
+
+    static size_t
+    length(const char_type* __s);
+
+    static const char_type* 
+    find(const char_type* __s, size_t __n, const char_type& __a);
+
+    static char_type* 
+    move(char_type* __s1, const char_type* __s2, size_t __n);
+
+    static char_type* 
+    copy(char_type* __s1, const char_type* __s2, size_t __n);
+
+    static char_type* 
+    assign(char_type* __s, size_t __n, char_type __a);
+
+    static char_type 
+    to_char_type(const int_type& __c);
+
+    // To keep both the byte 0xff and the eof symbol 0xffffffff
+    // from ending up as 0xffffffff.
+    static int_type 
+    to_int_type(const char_type& __c);
+
+    static bool 
+    eq_int_type(const int_type& __c1, const int_type& __c2);
+
+    static int_type 
+    eof() ;
+
+    static int_type 
+    not_eof(const int_type& __c);
+  };
+
+
+#if defined(SWIG_WCHAR)
+  template<>
+  struct char_traits<wchar_t>
+  {
+    typedef wchar_t 		char_type;
+    typedef wint_t 		int_type;
+    typedef streamoff 	off_type;
+    typedef wstreampos 	pos_type;
+    typedef mbstate_t 	state_type;
+      
+    static void 
+    assign(char_type& __c1, const char_type& __c2);
+
+    static bool 
+    eq(const char_type& __c1, const char_type& __c2);
+
+    static bool 
+    lt(const char_type& __c1, const char_type& __c2);
+
+    static int 
+    compare(const char_type* __s1, const char_type* __s2, size_t __n);
+
+    static size_t
+    length(const char_type* __s);
+
+    static const char_type* 
+    find(const char_type* __s, size_t __n, const char_type& __a);
+
+    static char_type* 
+    move(char_type* __s1, const char_type* __s2, int_type __n);
+
+    static char_type* 
+    copy(char_type* __s1, const char_type* __s2, size_t __n);
+
+    static char_type* 
+    assign(char_type* __s, size_t __n, char_type __a);
+
+    static char_type 
+    to_char_type(const int_type& __c) ;
+
+    static int_type 
+    to_int_type(const char_type& __c) ;
+
+    static bool 
+    eq_int_type(const int_type& __c1, const int_type& __c2);
+
+    static int_type 
+    eof() ;
+
+    static int_type 
+    not_eof(const int_type& __c);
+  };
+#endif
+}
+
+namespace std {
+#ifndef SWIG_STL_WRAP_TRAITS
+%template() char_traits<char>;
+#if defined(SWIG_WCHAR)
+%template() char_traits<wchar_t>;
+#endif
+#else
+%template(char_traits_c) char_traits<char>;
+#if defined(SWIG_WCHAR)
+%template(char_traits_w) char_traits<wchar_t>;
+#endif
+#endif
+}
diff --git a/trunk/Lib/std/std_common.i b/trunk/Lib/std/std_common.i
new file mode 100644
index 0000000..8b133c2
--- /dev/null
+++ b/trunk/Lib/std/std_common.i
@@ -0,0 +1,238 @@
+%include <std/std_except.i>
+
+//
+// Use the following macro with modern STL implementations
+//
+//#define SWIG_STD_MODERN_STL
+//
+// Use this to deactive the previous definition, when using gcc-2.95
+// or similar old compilers.
+//
+//#define SWIG_STD_NOMODERN_STL
+
+// Here, we identify compilers we know have problems with STL.
+%{
+#if defined(__GNUC__)
+#  if __GNUC__ == 2 && __GNUC_MINOR <= 96
+#     define SWIG_STD_NOMODERN_STL
+#  endif
+#endif
+%}
+
+//
+// Common code for supporting the STD C++ namespace
+//
+
+%{
+#include <string>
+#include <stdexcept>
+%}
+
+
+%fragment("StdIteratorTraits","header") %{
+#if defined(__SUNPRO_CC) && defined(_RWSTD_VER)
+#  if !defined(SWIG_NO_STD_NOITERATOR_TRAITS_STL)
+#    define SWIG_STD_NOITERATOR_TRAITS_STL
+#  endif
+#endif
+
+#if !defined(SWIG_STD_NOITERATOR_TRAITS_STL)
+#include <iterator>
+#else
+namespace std {
+  template <class Iterator>
+  struct iterator_traits {
+    typedef ptrdiff_t difference_type;
+    typedef typename Iterator::value_type value_type;
+  };
+
+  template <class Iterator, class Category,class T, class Reference, class Pointer, class Distance>
+  struct iterator_traits<__reverse_bi_iterator<Iterator,Category,T,Reference,Pointer,Distance> > {
+    typedef Distance difference_type;
+    typedef T value_type;
+  };
+
+  template <class T>
+  struct iterator_traits<T*> {
+    typedef T value_type;
+    typedef ptrdiff_t difference_type;
+  };
+
+  template<typename _InputIterator>
+  inline typename iterator_traits<_InputIterator>::difference_type
+  distance(_InputIterator __first, _InputIterator __last)
+  {
+    typename iterator_traits<_InputIterator>::difference_type __n = 0;
+    while (__first != __last) {
+      ++__first; ++__n;
+    }
+    return __n;
+  }
+}
+#endif
+%}
+
+%fragment("StdTraitsCommon","header") %{
+namespace swig {  
+  template <class Type>
+  struct noconst_traits {
+    typedef Type noconst_type;
+  };
+
+  template <class Type>
+  struct noconst_traits<const Type> {
+    typedef Type noconst_type;
+  };
+
+  /*
+    type categories
+  */
+  struct pointer_category { };  
+  struct value_category { };
+
+  /*
+    General traits that provides type_name and type_info
+  */
+  template <class Type> struct traits { };
+
+  template <class Type>
+  inline const char* type_name() {
+    return traits<typename noconst_traits<Type >::noconst_type >::type_name();
+  }
+
+  template <class Type> 
+  struct traits_info {
+    static swig_type_info *type_query(std::string name) {
+      name += " *";
+      return SWIG_TypeQuery(name.c_str());
+    }    
+    static swig_type_info *type_info() {
+      static swig_type_info *info = type_query(type_name<Type>());
+      return info;
+    }
+  };
+
+  template <class Type>
+  inline swig_type_info *type_info() {
+    return traits_info<Type>::type_info();
+  }
+
+  /*
+    Partial specialization for pointers
+  */
+  template <class Type> struct traits <Type *> {
+    typedef pointer_category category;
+    static std::string make_ptr_name(const char* name) {
+      std::string ptrname = name;
+      ptrname += " *";
+      return ptrname;
+    }    
+    static const char* type_name() {
+      static std::string name = make_ptr_name(swig::type_name<Type>());
+      return name.c_str();
+    }
+  };
+
+  template <class Type, class Category> 
+  struct traits_as { };
+ 
+  template <class Type, class Category> 
+  struct traits_check { };
+
+}
+%}
+ 
+/*
+  Generate the traits for a swigtype
+*/
+
+%define %traits_swigtype(Type...)
+%fragment(SWIG_Traits_frag(Type),"header",fragment="StdTraits") {
+  namespace swig {
+    template <>  struct traits<Type > {
+      typedef pointer_category category;
+      static const char* type_name() { return  #Type; }
+    };
+  }
+}
+%enddef
+
+
+
+/*
+  Generate the typemaps for a class that has 'value' traits
+*/
+
+%define %typemap_traits(Code,Type...)
+  %typemaps_asvalfrom(%arg(Code),
+		     %arg(swig::asval<Type >),
+		     %arg(swig::from),
+		     %arg(SWIG_Traits_frag(Type)),
+		     %arg(SWIG_Traits_frag(Type)),
+		     Type);
+%enddef
+
+/*
+  Generate the typemaps for a class that behaves more like a 'pointer' or
+  plain wrapped Swigtype.
+*/
+
+%define %typemap_traits_ptr(Code,Type...)
+  %typemaps_asptrfrom(%arg(Code),
+		     %arg(swig::asptr),
+		     %arg(swig::from),
+		     %arg(SWIG_Traits_frag(Type)),
+		     %arg(SWIG_Traits_frag(Type)),
+		     Type);
+%enddef
+
+
+/*
+  Equality methods
+*/
+%define %std_equal_methods(Type...)
+%extend Type {
+  bool operator == (const Type& v) {
+    return *self == v;
+  }
+  
+  bool operator != (const Type& v) {
+    return *self != v;
+  }  
+}
+
+%enddef
+
+/*
+  Order methods
+*/
+
+%define %std_order_methods(Type...)
+%extend Type {
+  bool operator > (const Type& v) {
+    return *self > v;
+  }
+  
+  bool operator < (const Type& v) {
+    return *self < v;
+  }
+
+  bool operator >= (const Type& v) {
+    return *self >= v;
+  }
+
+  bool operator <= (const Type& v) {
+    return *self <= v;
+  }
+}
+%enddef
+
+/*
+  Comparison methods
+*/
+
+%define %std_comp_methods(Type...)
+%std_equal_methods(Type )
+%std_order_methods(Type )
+%enddef
+
diff --git a/trunk/Lib/std/std_container.i b/trunk/Lib/std/std_container.i
new file mode 100644
index 0000000..66a9efa
--- /dev/null
+++ b/trunk/Lib/std/std_container.i
@@ -0,0 +1,109 @@
+%include <std_common.i>
+%include <exception.i>
+%include <std_alloc.i>
+
+%{
+#include <algorithm>
+%}
+
+// Common container methods
+
+%define %std_container_methods(container...)
+  container();
+  container(const container&);
+
+  bool empty() const;
+  size_type size() const;
+  void clear();
+
+  void swap(container& v);
+
+  allocator_type get_allocator() const;
+
+  #ifdef SWIG_EXPORT_ITERATOR_METHODS
+  class iterator;
+  class reverse_iterator;
+  class const_iterator;
+  class const_reverse_iterator;
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_reverse_iterator rbegin() const;
+  const_reverse_iterator rend() const;
+  #endif
+
+%enddef
+
+// Common sequence
+
+%define %std_sequence_methods_common(sequence)
+  
+  %std_container_methods(%arg(sequence));
+  
+  sequence(size_type size);
+  void pop_back();
+  
+  void resize(size_type new_size);
+  
+  #ifdef SWIG_EXPORT_ITERATOR_METHODS
+  iterator erase(iterator pos);
+  iterator erase(iterator first, iterator last);
+  #endif
+  
+%enddef
+
+
+%define %std_sequence_methods(sequence)
+  
+  %std_sequence_methods_common(%arg(sequence));
+  
+  sequence(size_type size, const value_type& value);
+  void push_back(const value_type& x);  
+
+  const value_type& front() const;
+  const value_type& back() const;
+ 
+  void assign(size_type n, const value_type& x);
+
+  void resize(size_type new_size, const value_type& x);
+  
+  #ifdef SWIG_EXPORT_ITERATOR_METHODS
+  iterator insert(iterator pos, const value_type& x);
+  void insert(iterator pos, size_type n, const value_type& x);
+  #endif
+  
+%enddef
+
+%define %std_sequence_methods_val(sequence...)
+  
+  %std_sequence_methods_common(%arg(sequence));
+  
+  sequence(size_type size, value_type value);
+  void push_back(value_type x);  
+
+  value_type front() const;
+  value_type back() const;
+ 
+  void assign(size_type n, value_type x);
+
+  void resize(size_type new_size, value_type x);
+  
+  #ifdef SWIG_EXPORT_ITERATOR_METHODS
+  iterator insert(iterator pos, value_type x);
+  void insert(iterator pos, size_type n, value_type x);
+  #endif
+  
+%enddef
+
+
+//
+// Ignore member methods for Type with no default constructor
+//
+%define %std_nodefconst_type(Type...)
+%feature("ignore") std::vector<Type >::vector(size_type size);
+%feature("ignore") std::vector<Type >::resize(size_type size);
+%feature("ignore") std::deque<Type >::deque(size_type size);
+%feature("ignore") std::deque<Type >::resize(size_type size);
+%feature("ignore") std::list<Type >::list(size_type size);
+%feature("ignore") std::list<Type >::resize(size_type size);
+%enddef
diff --git a/trunk/Lib/std/std_deque.i b/trunk/Lib/std/std_deque.i
new file mode 100644
index 0000000..a99763b
--- /dev/null
+++ b/trunk/Lib/std/std_deque.i
@@ -0,0 +1,127 @@
+//
+// std::deque
+
+%include <std_container.i>
+
+// Deque
+
+%define %std_deque_methods(deque...)  
+  %std_sequence_methods(deque)
+
+  void pop_front();
+  void push_front(const value_type& x);
+%enddef
+
+%define %std_deque_methods_val(deque...)
+  %std_sequence_methods_val(deque)
+
+  void pop_front();
+  void push_front(value_type x);
+%enddef
+
+// ------------------------------------------------------------------------
+// std::deque
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::deque<T>), f(const std::deque<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::deque<T> can be passed.
+//   -- f(std::deque<T>&), f(std::deque<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::deque
+//      can be passed.
+//   -- std::deque<T> f(), const std::deque<T>& f():
+//      the deque is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::deque<T>& f(), std::deque<T>* f():
+//      the deque is returned by reference; therefore, a wrapped std::deque
+//      is returned
+//   -- const std::deque<T>* f(), f(const std::deque<T>*):
+//      for consistency, they expect and return a plain deque pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <deque>
+%}
+
+// exported classes
+
+namespace std {
+
+  template<class _Tp, class _Alloc = allocator<_Tp> > 
+  class deque {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Tp value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::deque<_Tp, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdDequeTraits") {
+      namespace swig {
+	template <>  struct traits<std::deque<_Tp, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::deque<" #_Tp " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_DEQUE, std::deque<_Tp, _Alloc >);
+  
+#ifdef %swig_deque_methods
+    // Add swig/language extra methods
+    %swig_deque_methods(std::deque<_Tp, _Alloc >);
+#endif
+
+    %std_deque_methods(deque);
+  };
+
+  template<class _Tp, class _Alloc > 
+  class deque<_Tp*, _Alloc > {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Tp* value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type reference;
+    typedef value_type const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::deque<_Tp*, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdDequeTraits") {
+      namespace swig {
+	template <>  struct traits<std::deque<_Tp*, _Alloc > > {
+	  typedef value_category category;
+	  static const char* type_name() {
+	    return "std::deque<" #_Tp " * >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_DEQUE, std::deque<_Tp*, _Alloc >);
+
+#ifdef %swig_deque_methods_val
+    // Add swig/language extra methods
+    %swig_deque_methods_val(std::deque<_Tp*, _Alloc >);
+#endif
+
+    %std_deque_methods_val(std::deque<_Tp*, _Alloc >);
+  };
+
+}
+
diff --git a/trunk/Lib/std/std_except.i b/trunk/Lib/std/std_except.i
new file mode 100644
index 0000000..75b8d0f
--- /dev/null
+++ b/trunk/Lib/std/std_except.i
@@ -0,0 +1,68 @@
+#if defined(SWIGJAVA) || defined(SWIGCSHARP)
+#error "do not use this version of std_except.i"
+#endif
+
+%{
+#include <stdexcept>
+%}
+
+#if defined(SWIG_STD_EXCEPTIONS_AS_CLASSES)
+
+namespace std {
+  struct exception 
+  {
+    virtual ~exception() throw();
+    virtual const char* what() const throw();
+  };
+
+  struct bad_exception : exception 
+  {
+  };
+
+  struct logic_error : exception 
+  {
+    logic_error(const string& msg);
+  };
+
+  struct domain_error : logic_error 
+  {
+    domain_error(const string& msg);
+  };
+
+  struct invalid_argument : logic_error 
+  {
+    invalid_argument(const string& msg);
+  };
+
+  struct length_error : logic_error 
+  {
+    length_error(const string& msg);
+  };
+
+  struct out_of_range : logic_error 
+  {
+    out_of_range(const string& msg);
+  };
+
+  struct runtime_error : exception 
+  {
+    runtime_error(const string& msg);
+  };
+
+  struct range_error : runtime_error 
+  {
+    range_error(const string& msg);
+  };
+
+  struct overflow_error : runtime_error 
+  {
+    overflow_error(const string& msg);
+  };
+
+  struct underflow_error : runtime_error 
+  {
+    underflow_error(const string& msg);
+  };
+}
+
+#endif
diff --git a/trunk/Lib/std/std_ios.i b/trunk/Lib/std/std_ios.i
new file mode 100644
index 0000000..75484f3
--- /dev/null
+++ b/trunk/Lib/std/std_ios.i
@@ -0,0 +1,260 @@
+%include <std_char_traits.i>
+%include <std_basic_string.i>
+%include <std_except.i>
+%{
+#ifndef SWIG_STD_NOMODERN_STL
+# include <ios>
+#else
+# include <streambuf.h>
+#endif
+%}
+
+namespace std {
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_streambuf;
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_istream;
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_ostream;
+
+  // 27.4.2  Class ios_base
+  typedef size_t streamsize;
+
+  class locale;
+  
+  
+  class ios_base
+  {
+  public:
+    
+#ifdef SWIG_NESTED_CLASSES
+    // 27.4.2.1.1  Class ios_base::failure
+    class failure : public exception
+    {
+    public:
+      explicit failure(const string& __str) throw();
+    };
+#endif
+
+    // 27.4.2.1.2  Type ios_base::fmtflags
+    typedef int fmtflags;
+    // 27.4.2.1.2  Type fmtflags
+    static const fmtflags boolalpha ;
+    static const fmtflags dec ;
+    static const fmtflags fixed ;
+    static const fmtflags hex ;
+    static const fmtflags internal ;
+    static const fmtflags left ;
+    static const fmtflags oct ;
+    static const fmtflags right ;
+    static const fmtflags scientific ;
+    static const fmtflags showbase ;
+    static const fmtflags showpoint ;
+    static const fmtflags showpos ;
+    static const fmtflags skipws ;
+    static const fmtflags unitbuf ;
+    static const fmtflags uppercase ;
+    static const fmtflags adjustfield ;
+    static const fmtflags basefield ;
+    static const fmtflags floatfield ;
+
+    // 27.4.2.1.3  Type ios_base::iostate
+    typedef int iostate;
+    static const iostate badbit ;
+    static const iostate eofbit ;
+    static const iostate failbit ;
+    static const iostate goodbit ;
+
+    // 27.4.2.1.4  Type openmode
+    typedef int openmode;
+    static const openmode app ;
+    static const openmode ate ;
+    static const openmode binary ;
+    static const openmode in ;
+    static const openmode out ;
+    static const openmode trunc ;
+
+    // 27.4.2.1.5  Type seekdir
+    typedef int seekdir;
+    static const seekdir beg ;
+    static const seekdir cur ;
+    static const seekdir end ;
+
+
+    // Callbacks;
+    enum event
+      {
+	erase_event,
+	imbue_event,
+	copyfmt_event
+      };
+
+    typedef void (*event_callback) (event, ios_base&, int);
+
+    void 
+    register_callback(event_callback __fn, int __index);
+
+    // Fmtflags state:
+    inline fmtflags 
+    flags() const ;
+
+    inline fmtflags 
+    flags(fmtflags __fmtfl);
+
+    inline fmtflags 
+    setf(fmtflags __fmtfl);
+
+    inline fmtflags 
+    setf(fmtflags __fmtfl, fmtflags __mask);
+
+    inline void 
+    unsetf(fmtflags __mask) ;
+
+    inline streamsize 
+    precision() const ;
+
+    inline streamsize 
+    precision(streamsize __prec);
+
+    inline streamsize 
+    width() const ;
+
+    inline streamsize 
+    width(streamsize __wide);
+
+    static bool 
+    sync_with_stdio(bool __sync = true);
+
+    // Locales:
+    locale 
+    imbue(const locale& __loc);
+
+    inline locale 
+    getloc() const { return _M_ios_locale; }
+
+    // Storage:
+    static int 
+    xalloc() throw();
+
+    inline long& 
+    iword(int __ix);
+
+    inline void*& 
+    pword(int __ix);
+
+    // Destructor
+    ~ios_base();
+
+  protected:
+    ios_base();
+
+  //50.  Copy constructor and assignment operator of ios_base
+  private:
+    ios_base(const ios_base&);
+
+    ios_base& 
+    operator=(const ios_base&);
+  };
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_ios : public ios_base
+  {
+  public:
+    // Types:
+    typedef _CharT 				char_type;
+    typedef typename _Traits::int_type 	int_type;
+    typedef typename _Traits::pos_type 	pos_type;
+    typedef typename _Traits::off_type 	off_type;
+    typedef _Traits 				traits_type;
+      
+  public:
+
+    iostate 
+    rdstate() const;
+
+    void 
+    clear(iostate __state = goodbit);
+
+    void 
+    setstate(iostate __state);
+
+    bool 
+    good() const;
+
+    bool 
+    eof() const;
+
+    bool 
+    fail() const;
+
+    bool 
+    bad() const;
+
+    iostate 
+    exceptions() const;
+
+    void 
+    exceptions(iostate __except);
+
+    // Constructor/destructor:
+    explicit 
+    basic_ios(basic_streambuf<_CharT, _Traits>* __sb) : ios_base();
+
+    virtual 
+    ~basic_ios() ;
+      
+    // Members:
+    basic_ostream<_CharT, _Traits>*
+    tie() const;
+
+    basic_ostream<_CharT, _Traits>*
+    tie(basic_ostream<_CharT, _Traits>* __tiestr);
+
+    basic_streambuf<_CharT, _Traits>*
+    rdbuf() const;
+
+    basic_streambuf<_CharT, _Traits>* 
+    rdbuf(basic_streambuf<_CharT, _Traits>* __sb);
+
+    basic_ios&
+    copyfmt(const basic_ios& __rhs);
+
+    char_type 
+    fill() const;
+
+    char_type 
+    fill(char_type __ch);
+
+    // Locales:
+    locale 
+    imbue(const locale& __loc);
+
+    char 
+    narrow(char_type __c, char __dfault) const;
+
+    char_type 
+    widen(char __c) const;
+     
+  protected:
+    // 27.4.5.1  basic_ios constructors
+    basic_ios();
+  private:
+    ios_base(const ios_base&);
+
+    ios_base& 
+    operator=(const ios_base&);
+  };
+  
+}
+
+namespace std {
+  %template(ios) basic_ios<char>;
+#if defined(SWIG_WCHAR)
+  %template(wios) basic_ios<wchar_t>;
+#endif
+}
+
+  
diff --git a/trunk/Lib/std/std_iostream.i b/trunk/Lib/std/std_iostream.i
new file mode 100644
index 0000000..7a33afe
--- /dev/null
+++ b/trunk/Lib/std/std_iostream.i
@@ -0,0 +1,339 @@
+/* 
+   For wchar support, you need to include the wchar.i file
+   before this file, ie:
+   
+   %include <wchar.i>
+   %include <std_iostream.i>
+
+   or equivalently, just include
+
+   %include <std_wiostream.i>
+*/
+
+%include <std_ios.i>
+%include <std_basic_string.i>
+%include <std_string.i>
+#if defined(SWIG_WCHAR)
+%include <std_wstring.i>
+#endif
+
+%{
+#include <iostream>
+%}
+
+
+namespace std
+{
+  // 27.6.2.1 Template class basic_ostream
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_ostream : virtual public basic_ios<_CharT, _Traits>
+  {
+  public:
+    // Types (inherited from basic_ios (27.4.4)):
+    typedef _CharT                     		char_type;
+    typedef typename _Traits::int_type 		int_type;
+    typedef typename _Traits::pos_type 		pos_type;
+    typedef typename _Traits::off_type 		off_type;
+    typedef _Traits                    		traits_type;
+      
+    // 27.6.2.2 Constructor/destructor:
+    explicit 
+    basic_ostream(basic_streambuf<_CharT, _Traits>* __sb);
+
+    virtual 
+    ~basic_ostream();
+    
+    // 27.6.2.5 Formatted output:
+    // 27.6.2.5.3  basic_ostream::operator<<
+    basic_ostream<_CharT, _Traits>&
+    operator<<(basic_ostream<_CharT, _Traits>& (*__pf)(basic_ostream<_CharT, _Traits>&));
+
+      
+    basic_ostream<_CharT, _Traits>&
+    operator<<(basic_ios<_CharT, _Traits>& (*__pf)(basic_ios<_CharT, _Traits>&));
+
+
+    basic_ostream<_CharT, _Traits>&
+    operator<<(ios_base& (*__pf) (ios_base&));
+    
+    // 27.6.2.5.2 Arithmetic Inserters
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(long __n);
+    
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(unsigned long __n);
+    
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(bool __n);
+    
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(short __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(unsigned short __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(int __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(unsigned int __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(long long __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(unsigned long long __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(double __f);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(float __f);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(long double __f);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(const void* __p);
+
+    basic_ostream<_CharT, _Traits>& 
+    operator<<(basic_streambuf<_CharT, _Traits>* __sb);
+
+    %extend {
+      std::basic_ostream<_CharT, _Traits >& 
+	operator<<(const std::basic_string<_CharT,_Traits, std::allocator<_CharT> >& s)
+	{
+	  *self << s;
+	  return *self;
+	}
+    }
+
+    // Unformatted output:
+    basic_ostream<_CharT, _Traits>& 
+    put(char_type __c);
+
+    basic_ostream<_CharT, _Traits>& 
+    write(const char_type* __s, streamsize __n);
+
+    basic_ostream<_CharT, _Traits>& 
+    flush();
+
+    // Seeks:
+    pos_type 
+    tellp();
+
+    basic_ostream<_CharT, _Traits>& 
+    seekp(pos_type);
+
+    basic_ostream<_CharT, _Traits>& 
+    seekp(off_type, ios_base::seekdir);
+
+  };
+
+  // 27.6.1.1 Template class basic_istream
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_istream : virtual public basic_ios<_CharT, _Traits>
+  {
+  public:
+    // Types (inherited from basic_ios (27.4.4)):
+    typedef _CharT                     		char_type;
+    typedef typename _Traits::int_type 		int_type;
+    typedef typename _Traits::pos_type 		pos_type;
+    typedef typename _Traits::off_type 		off_type;
+    typedef _Traits                    		traits_type;
+
+
+  public:
+    // 27.6.1.1.1 Constructor/destructor:
+    explicit 
+    basic_istream(basic_streambuf<_CharT, _Traits>* __sb);
+
+    virtual 
+    ~basic_istream();
+
+    // 27.6.1.2.3 basic_istream::operator>>
+    basic_istream<_CharT, _Traits>&
+    operator>>(basic_istream<_CharT, _Traits>& (*__pf)(basic_istream<_CharT, _Traits>&));
+    
+    basic_istream<_CharT, _Traits>&
+    operator>>(basic_ios<_CharT, _Traits>& (*__pf)(basic_ios<_CharT, _Traits>&));
+    
+    basic_istream<_CharT, _Traits>&
+    operator>>(ios_base& (*__pf)(ios_base&));
+      
+    // 27.6.1.2.2 Arithmetic Extractors
+    basic_istream<_CharT, _Traits>& 
+    operator>>(bool& __n);
+      
+    basic_istream<_CharT, _Traits>& 
+    operator>>(short& __n);
+      
+    basic_istream<_CharT, _Traits>& 
+    operator>>(unsigned short& __n);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(int& __n);
+      
+    basic_istream<_CharT, _Traits>& 
+    operator>>(unsigned int& __n);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(long& __n);
+      
+    basic_istream<_CharT, _Traits>& 
+    operator>>(unsigned long& __n);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(long long& __n);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(unsigned long long& __n);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(float& __f);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(double& __f);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(long double& __f);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(void*& __p);
+
+    basic_istream<_CharT, _Traits>& 
+    operator>>(basic_streambuf<_CharT, _Traits>* __sb);
+      
+    // 27.6.1.3 Unformatted input:
+    inline streamsize 
+    gcount(void) const;
+      
+    int_type 
+    get(void);
+
+    basic_istream<_CharT, _Traits>& 
+    get(char_type& __c);
+
+    basic_istream<_CharT, _Traits>& 
+    get(char_type* __s, streamsize __n, char_type __delim);
+
+    inline basic_istream<_CharT, _Traits>& 
+    get(char_type* __s, streamsize __n);
+
+    basic_istream<_CharT, _Traits>&
+    get(basic_streambuf<_CharT, _Traits>& __sb, char_type __delim);
+
+    inline basic_istream<_CharT, _Traits>&
+    get(basic_streambuf<_CharT, _Traits>& __sb);
+
+    basic_istream<_CharT, _Traits>& 
+    getline(char_type* __s, streamsize __n, char_type __delim);
+
+    inline basic_istream<_CharT, _Traits>& 
+    getline(char_type* __s, streamsize __n);
+
+    basic_istream<_CharT, _Traits>& 
+    ignore(streamsize __n = 1, int_type __delim = _Traits::eof());
+      
+    int_type 
+    peek(void);
+      
+    basic_istream<_CharT, _Traits>& 
+    read(char_type* __s, streamsize __n);
+
+    streamsize 
+    readsome(char_type* __s, streamsize __n);
+      
+    basic_istream<_CharT, _Traits>& 
+    putback(char_type __c);
+
+    basic_istream<_CharT, _Traits>& 
+    unget(void);
+
+    int 
+    sync(void);
+
+    pos_type 
+    tellg(void);
+
+    basic_istream<_CharT, _Traits>& 
+    seekg(pos_type);
+
+    basic_istream<_CharT, _Traits>& 
+    seekg(off_type, ios_base::seekdir);
+  };  
+
+  // 27.6.1.5 Template class basic_iostream
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_iostream
+    : public basic_istream<_CharT, _Traits>, 
+      public basic_ostream<_CharT, _Traits>
+  {
+  public:
+    typedef _CharT                     		char_type;
+    typedef typename _Traits::int_type 		int_type;
+    typedef typename _Traits::pos_type 		pos_type;
+    typedef typename _Traits::off_type 		off_type;
+    typedef _Traits                    		traits_type;
+
+    explicit 
+    basic_iostream(basic_streambuf<_CharT, _Traits>* __sb);
+
+    virtual 
+    ~basic_iostream();    
+  };
+
+  typedef basic_ostream<char> ostream ;
+  typedef basic_istream<char> istream;
+  typedef basic_iostream<char> iostream;
+
+  extern istream cin;
+  extern ostream cout;
+  extern ostream cerr;
+  extern ostream clog;
+
+#if defined(SWIG_WCHAR)
+  typedef basic_ostream<wchar_t>  wostream;
+  typedef basic_istream<wchar_t>  wistream;
+  typedef basic_iostream<wchar_t> wiostream;
+
+  extern wistream wcin;
+  extern wostream wcout;
+  extern wostream wcerr;
+  extern wostream wclog;
+#endif
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  std::basic_ostream<_CharT, _Traits>& 
+  endl(std::basic_ostream<_CharT, _Traits>&);
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  std::basic_ostream<_CharT, _Traits>& 
+  ends(std::basic_ostream<_CharT, _Traits>&);
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  std::basic_ostream<_CharT, _Traits>& 
+  flush(std::basic_ostream<_CharT, _Traits>&);
+}
+
+namespace std {
+  %template(ostream) basic_ostream<char>;
+  %template(istream) basic_istream<char>;
+  %template(iostream) basic_iostream<char>;
+
+  %template(endl) endl<char, std::char_traits<char> >;
+  %template(ends) ends<char, std::char_traits<char> >;
+  %template(flush) flush<char, std::char_traits<char> >;
+
+#if defined(SWIG_WCHAR)
+  %template(wostream) basic_ostream<wchar_t>;
+  %template(wistream) basic_istream<wchar_t>;
+  %template(wiostream) basic_iostream<wchar_t>;  
+
+  %template(wendl) endl<wchar_t, std::char_traits<wchar_t> >;
+  %template(wends) ends<wchar_t, std::char_traits<wchar_t> >;
+  %template(wflush) flush<wchar_t, std::char_traits<wchar_t> >;  
+#endif
+}
+
diff --git a/trunk/Lib/std/std_list.i b/trunk/Lib/std/std_list.i
new file mode 100644
index 0000000..e089351
--- /dev/null
+++ b/trunk/Lib/std/std_list.i
@@ -0,0 +1,148 @@
+//
+// std::list
+//
+
+%include <std_container.i>
+
+// List
+
+%define %std_list_methods(list)
+  %std_sequence_methods(list)
+  
+  void pop_front();
+  void push_front(const value_type& x);
+  		
+  void reverse();
+  
+%enddef
+
+
+%define %std_list_methods_val(list)
+  %std_sequence_methods_val(list)
+  
+  void pop_front();
+  void push_front(value_type x);
+  		
+  void remove(value_type x);
+  void unique();
+  void reverse();
+  void sort();
+  
+  void merge(list& x);
+%enddef
+
+// ------------------------------------------------------------------------
+// std::list
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::list<T>), f(const std::list<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::list<T> can be passed.
+//   -- f(std::list<T>&), f(std::list<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::list
+//      can be passed.
+//   -- std::list<T> f(), const std::list<T>& f():
+//      the list is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::list<T>& f(), std::list<T>* f():
+//      the list is returned by reference; therefore, a wrapped std::list
+//      is returned
+//   -- const std::list<T>* f(), f(const std::list<T>*):
+//      for consistency, they expect and return a plain list pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <list>
+%}
+
+// exported classes
+
+namespace std {
+
+  template<class _Tp, class _Alloc = allocator<_Tp>  > 
+  class list {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Tp value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::list<_Tp, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdListTraits") {
+      namespace swig {
+	template <>  struct traits<std::list<_Tp, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::list<" #_Tp ", " #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_LIST, std::list<_Tp, _Alloc >);
+
+#ifdef %swig_list_methods
+    // Add swig/language extra methods
+    %swig_list_methods(std::list<_Tp, _Alloc >);
+#endif
+  
+    %std_list_methods(list);
+  };
+
+  template<class _Tp, class _Alloc >
+  class list<_Tp*, _Alloc> {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Tp* value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type reference;
+    typedef value_type const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::list<_Tp*, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdListTraits") {
+      namespace swig {
+	template <>  struct traits<std::list<_Tp*, _Alloc > > {
+	  typedef value_category category;
+	  static const char* type_name() {
+	    return "std::list<" #_Tp " *," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_LIST, std::list<_Tp*, _Alloc >);
+
+#ifdef %swig_list_methods_val
+    // Add swig/language extra methods
+    %swig_list_methods_val(std::list<_Tp*, _Alloc >);
+#endif
+
+    %std_list_methods_val(list);
+  };
+
+}
+
+%define %std_extequal_list(...)
+%extend std::list<__VA_ARGS__ > { 
+  void remove(const value_type& x) { self->remove(x); }  
+  void merge(std::list<__VA_ARGS__ >& x){ self->merge(x); }  
+  void unique() { self->unique(); }  
+  void sort() { self->sort(); }  
+}
+%enddef
+
diff --git a/trunk/Lib/std/std_map.i b/trunk/Lib/std/std_map.i
new file mode 100644
index 0000000..0520841
--- /dev/null
+++ b/trunk/Lib/std/std_map.i
@@ -0,0 +1,124 @@
+//
+// std::map
+//
+
+%include <std_pair.i>
+%include <std_container.i>
+
+%define %std_map_methods_common(map...)
+  %std_container_methods(map);
+
+  size_type erase(const key_type& x);
+  size_type count(const key_type& x) const;
+
+#ifdef SWIG_EXPORT_ITERATOR_METHODS
+//  iterator insert(iterator position, const value_type& x);
+  void erase(iterator position);
+  void erase(iterator first, iterator last);
+
+  iterator find(const key_type& x);
+  iterator lower_bound(const key_type& x);
+  iterator upper_bound(const key_type& x);
+#endif
+%enddef
+
+%define %std_map_methods(map...)
+  %std_map_methods_common(map);
+
+  #ifdef SWIG_EXPORT_ITERATOR_METHODS
+//  iterator insert(const value_type& x);
+  #endif
+%enddef
+
+
+// ------------------------------------------------------------------------
+// std::map
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::map<T>), f(const std::map<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::map<T> can be passed.
+//   -- f(std::map<T>&), f(std::map<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::map
+//      can be passed.
+//   -- std::map<T> f(), const std::map<T>& f():
+//      the map is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::map<T>& f(), std::map<T>* f():
+//      the map is returned by reference; therefore, a wrapped std::map
+//      is returned
+//   -- const std::map<T>* f(), f(const std::map<T>*):
+//      for consistency, they expect and return a plain map pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+  template<class _Key, class _Tp, class _Compare = std::less<_Key >,
+	   class _Alloc = allocator<std::pair<const _Key, _Tp > > >
+  class map {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Key key_type;
+    typedef _Tp mapped_type;
+    typedef std::pair<const _Key, _Tp> value_type;
+
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Key);
+    %traits_swigtype(_Tp);	    
+
+    %fragment(SWIG_Traits_frag(std::pair< _Key, _Tp >), "header",
+	      fragment=SWIG_Traits_frag(_Key),
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdPairTraits") {
+      namespace swig {
+	template <>  struct traits<std::pair< _Key, _Tp > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::pair<" #_Key "," #_Tp " >";
+	  }
+	};
+      }
+    }
+
+    %fragment(SWIG_Traits_frag(std::map<_Key, _Tp, _Compare, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >),
+	      fragment="StdMapTraits") {
+      namespace swig {
+	template <>  struct traits<std::map<_Key, _Tp, _Compare, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::map<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_MAP, std::map<_Key, _Tp, _Compare, _Alloc >);
+
+    map( const _Compare& );
+
+#ifdef %swig_map_methods
+    // Add swig/language extra methods
+    %swig_map_methods(std::map<_Key, _Tp, _Compare, _Alloc >);
+#endif
+  
+    %std_map_methods(map);
+  };
+
+}
diff --git a/trunk/Lib/std/std_multimap.i b/trunk/Lib/std/std_multimap.i
new file mode 100644
index 0000000..f165e5f
--- /dev/null
+++ b/trunk/Lib/std/std_multimap.i
@@ -0,0 +1,87 @@
+//
+// std::map
+//
+
+%include <std_map.i>
+
+
+%define %std_multimap_methods(mmap...)
+  %std_map_methods_common(mmap);
+
+#ifdef SWIG_EXPORT_ITERATOR_METHODS
+  std::pair<iterator,iterator> equal_range(const key_type& x);
+  std::pair<const_iterator,const_iterator> equal_range(const key_type& x) const;
+#endif
+%enddef
+
+// ------------------------------------------------------------------------
+// std::multimap
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::multimap<T>), f(const std::multimap<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::multimap<T> can be passed.
+//   -- f(std::multimap<T>&), f(std::multimap<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::multimap
+//      can be passed.
+//   -- std::multimap<T> f(), const std::multimap<T>& f():
+//      the map is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::multimap<T>& f(), std::multimap<T>* f():
+//      the map is returned by reference; therefore, a wrapped std::multimap
+//      is returned
+//   -- const std::multimap<T>* f(), f(const std::multimap<T>*):
+//      for consistency, they expect and return a plain map pointer.
+// ------------------------------------------------------------------------
+
+
+// exported class
+
+
+namespace std {
+  template<class _Key, class _Tp, class _Compare = std::less<_Key >,
+	   class _Alloc = allocator<std::pair<const _Key, _Tp > > >
+  class multimap {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Key key_type;
+    typedef _Tp mapped_type;
+    typedef std::pair<const _Key, _Tp> value_type;
+
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Key);
+    %traits_swigtype(_Tp);	    
+
+    %fragment(SWIG_Traits_frag(std::multimap<_Key, _Tp, _Compare, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(std::pair<_Key, _Tp >),
+	      fragment="StdMultimapTraits") {
+      namespace swig {
+	template <>  struct traits<std::multimap<_Key, _Tp, _Compare, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::multimap<" #_Key "," #_Tp "," #_Compare "," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_MULTIMAP, std::multimap<_Key, _Tp, _Compare, _Alloc >);
+  
+    multimap( const _Compare& );
+
+#ifdef %swig_multimap_methods
+    // Add swig/language extra methods
+    %swig_multimap_methods(std::multimap<_Key, _Tp, _Compare, _Alloc >);
+#endif
+
+    %std_multimap_methods(multimap);
+  };
+}
diff --git a/trunk/Lib/std/std_multiset.i b/trunk/Lib/std/std_multiset.i
new file mode 100644
index 0000000..98a7fb9
--- /dev/null
+++ b/trunk/Lib/std/std_multiset.i
@@ -0,0 +1,83 @@
+//
+// std::set
+//
+
+%include <std_set.i>
+
+// Multiset
+
+%define %std_multiset_methods(multiset...)
+  %std_set_methods_common(multiset);
+%enddef
+
+
+// ------------------------------------------------------------------------
+// std::multiset
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::multiset<T>), f(const std::multiset<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::multiset<T> can be passed.
+//   -- f(std::multiset<T>&), f(std::multiset<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::multiset
+//      can be passed.
+//   -- std::multiset<T> f(), const std::multiset<T>& f():
+//      the set is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::multiset<T>& f(), std::multiset<T>* f():
+//      the set is returned by reference; therefore, a wrapped std::multiset
+//      is returned
+//   -- const std::multiset<T>* f(), f(const std::multiset<T>*):
+//      for consistency, they expect and return a plain set pointer.
+// ------------------------------------------------------------------------
+
+
+// exported classes
+
+namespace std {
+
+  //multiset
+
+  template <class _Key, class _Compare = std::less<_Key>,
+	    class _Alloc = allocator<_Key> >
+  class multiset {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Key value_type;
+    typedef _Key key_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Key);
+
+    %fragment(SWIG_Traits_frag(std::multiset<_Key, _Compare, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Key),
+	      fragment="StdMultisetTraits") {
+      namespace swig {
+	template <>  struct traits<std::multiset<_Key, _Compare, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::multiset<" #_Key "," #_Compare "," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_MULTISET, std::multiset<_Key, _Compare, _Alloc >);
+
+    multiset( const _Compare& );
+
+#ifdef %swig_multiset_methods
+    // Add swig/language extra methods
+    %swig_multiset_methods(std::multiset<_Key, _Compare, _Alloc >);
+#endif
+  
+    %std_multiset_methods(multiset);
+  };
+}
diff --git a/trunk/Lib/std/std_pair.i b/trunk/Lib/std/std_pair.i
new file mode 100644
index 0000000..7c83277
--- /dev/null
+++ b/trunk/Lib/std/std_pair.i
@@ -0,0 +1,163 @@
+%include <std_common.i>
+
+%{
+#include <utility>
+%}
+
+
+namespace std {
+  template <class T, class U > struct pair {      
+    typedef T first_type;
+    typedef U second_type;
+    
+    %traits_swigtype(T);
+    %traits_swigtype(U);
+
+    %fragment(SWIG_Traits_frag(std::pair<T,U >), "header",
+	      fragment=SWIG_Traits_frag(T),
+	      fragment=SWIG_Traits_frag(U),
+	      fragment="StdPairTraits") {
+      namespace swig {
+	template <>  struct traits<std::pair<T,U > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::pair<" #T "," #U " >";
+	  }
+	};
+      }
+    }
+
+#ifndef SWIG_STD_PAIR_ASVAL
+    %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair<T,U >);
+#else
+    %typemap_traits(SWIG_TYPECHECK_PAIR, std::pair<T,U >);
+#endif
+
+    pair();
+    pair(T first, U second);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+
+#ifdef %swig_pair_methods
+    // Add swig/language extra methods
+    %swig_pair_methods(std::pair<T,U >)
+#endif
+  };
+
+  // ***
+  // The following specializations should dissapear or get 
+  // simplified when a 'const SWIGTYPE*&' can be defined
+  // ***
+  template <class T, class U > struct pair<T, U*> {      
+    typedef T first_type;
+    typedef U* second_type;
+    
+    %traits_swigtype(T);
+    %traits_swigtype(U);
+      
+    %fragment(SWIG_Traits_frag(std::pair<T,U* >), "header",
+	      fragment=SWIG_Traits_frag(T),
+	      fragment=SWIG_Traits_frag(U),
+	      fragment="StdPairTraits") {
+      namespace swig {
+	template <>  struct traits<std::pair<T,U* > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::pair<" #T "," #U " * >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair<T,U* >);
+
+    pair();
+    pair(T __a, U* __b);
+    pair(const pair& __p);
+
+    T first;
+    U* second;
+
+#ifdef %swig_pair_methods
+    // Add swig/language extra methods
+    %swig_pair_methods(std::pair<T,U*>)
+#endif
+  };
+
+  template <class T, class U > struct pair<T*, U> {      
+    typedef T* first_type;
+    typedef U second_type;
+    
+    %traits_swigtype(T);
+    %traits_swigtype(U);
+      
+    %fragment(SWIG_Traits_frag(std::pair<T*,U >), "header",
+	      fragment=SWIG_Traits_frag(T),
+	      fragment=SWIG_Traits_frag(U),
+	      fragment="StdPairTraits") {
+      namespace swig {
+	template <>  struct traits<std::pair<T*,U > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::pair<" #T " *," #U " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_PAIR, std::pair<T*,U >);
+
+    pair();
+    pair(T* __a, U __b);
+    pair(const pair& __p);
+
+    T* first;
+    U second;
+
+#ifdef %swig_pair_methods
+    // Add swig/language extra methods
+    %swig_pair_methods(std::pair<T*,U >)
+#endif
+  };
+
+  template <class T, class U > struct pair<T*, U*> {
+    typedef T* first_type;
+    typedef U* second_type;
+
+    %traits_swigtype(T);
+    %traits_swigtype(U);
+      
+    %fragment(SWIG_Traits_frag(std::pair<T*,U* >), "header",
+	      fragment=SWIG_Traits_frag(T),
+	      fragment=SWIG_Traits_frag(U),
+	      fragment="StdPairTraits") {
+      namespace swig {
+	template <>  struct traits<std::pair<T*,U* > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::pair<" #T " *," #U " * >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits(SWIG_TYPECHECK_PAIR, std::pair<T*,U* >);
+
+    pair();
+    pair(T* __a, U* __b);
+    pair(const pair& __p);
+
+    T* first;
+    U* second;
+ 
+#ifdef %swig_pair_methods
+    // Add swig/language extra methods
+    %swig_pair_methods(std::pair<T*,U*>)
+#endif
+  };
+
+}
diff --git a/trunk/Lib/std/std_queue.i b/trunk/Lib/std/std_queue.i
new file mode 100644
index 0000000..42273ee
--- /dev/null
+++ b/trunk/Lib/std/std_queue.i
@@ -0,0 +1,129 @@
+/**
+ * @file   std_queue.i
+ * @date   Sun May  6 01:48:07 2007
+ * 
+ * @brief  A wrapping of std::queue for Ruby.
+ * 
+ * 
+ */
+
+%include <std_container.i>
+
+// Queue
+
+%define %std_queue_methods(queue...)
+  queue();
+  queue( const _Sequence& );
+
+  bool empty() const;
+  size_type size() const;
+  const value_type& front() const;
+  const value_type& back() const;
+  void pop();
+  void push( const value_type& );
+%enddef
+
+%define %std_queue_methods_val(queue...) 
+  %std_queue_methods(queue)
+%enddef
+
+// ------------------------------------------------------------------------
+// std::queue
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::queue<T>), f(const std::queue<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::queue<T> can be passed.
+//   -- f(std::queue<T>&), f(std::queue<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::queue
+//      can be passed.
+//   -- std::queue<T> f(), const std::queue<T>& f():
+//      the queue is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::queue<T>& f(), std::queue<T>* f():
+//      the queue is returned by reference; therefore, a wrapped std::queue
+//      is returned
+//   -- const std::queue<T>* f(), f(const std::queue<T>*):
+//      for consistency, they expect and return a plain queue pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <queue>
+%}
+
+// exported classes
+
+namespace std {
+
+  template<class _Tp, class _Sequence = std::deque<_Tp> > 
+  class queue {
+  public:
+    typedef size_t size_type;
+    typedef _Tp value_type;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Sequence container_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::queue<_Tp, _Sequence >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdQueueTraits") {
+      namespace swig {
+	template <>  struct traits<std::queue<_Tp, _Sequence > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::queue<" #_Tp "," #_Sequence " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_QUEUE, std::queue<_Tp, _Sequence >);
+  
+#ifdef %swig_queue_methods
+    // Add swig/language extra methods
+    %swig_queue_methods(std::queue<_Tp, _Sequence >);
+#endif
+
+    %std_queue_methods(queue);
+  };
+
+  template<class _Tp, class _Sequence > 
+  class queue<_Tp*, _Sequence > {
+  public:
+    typedef size_t size_type;
+    typedef _Tp value_type;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Sequence container_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::queue<_Tp*, _Sequence >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdQueueTraits") {
+      namespace swig {
+	template <>  struct traits<std::queue<_Tp*, _Sequence > > {
+	  typedef value_category category;
+	  static const char* type_name() {
+	    return "std::queue<" #_Tp "," #_Sequence " * >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_QUEUE, std::queue<_Tp*, _Sequence >);
+
+#ifdef %swig_queue_methods_val
+    // Add swig/language extra methods
+    %swig_queue_methods_val(std::queue<_Tp*, _Sequence >);
+#endif
+
+    %std_queue_methods_val(std::queue<_Tp*, _Sequence >);
+  };
+
+}
+
diff --git a/trunk/Lib/std/std_set.i b/trunk/Lib/std/std_set.i
new file mode 100644
index 0000000..16f0f14
--- /dev/null
+++ b/trunk/Lib/std/std_set.i
@@ -0,0 +1,119 @@
+//
+// std::set
+//
+
+%include <std_container.i>
+%include <std_pair.i>
+
+// Set
+%define %std_set_methods_common(set...)
+  set();
+  set( const set& );
+
+  bool empty() const;
+  size_type size() const;
+  void clear();
+
+  void swap(set& v);
+
+
+  size_type erase(const key_type& x);
+  size_type count(const key_type& x) const;
+  
+#ifdef SWIG_EXPORT_ITERATOR_METHODS
+  class iterator;
+  class reverse_iterator;
+
+  iterator begin();
+  iterator end();
+  reverse_iterator rbegin();
+  reverse_iterator rend();
+
+  void erase(iterator pos);
+  void erase(iterator first, iterator last);
+
+  iterator find(const key_type& x);
+  iterator lower_bound(const key_type& x);
+  iterator upper_bound(const key_type& x);
+  std::pair<iterator,iterator> equal_range(const key_type& x);
+#endif
+%enddef
+
+%define %std_set_methods(set...)
+  %std_set_methods_common(set);
+#ifdef SWIG_EXPORT_ITERATOR_METHODS
+  std::pair<iterator,bool> insert(const value_type& __x);
+#endif
+%enddef
+
+// ------------------------------------------------------------------------
+// std::set
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::set<T>), f(const std::set<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::set<T> can be passed.
+//   -- f(std::set<T>&), f(std::set<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::set
+//      can be passed.
+//   -- std::set<T> f(), const std::set<T>& f():
+//      the set is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::set<T>& f(), std::set<T>* f():
+//      the set is returned by reference; therefore, a wrapped std::set
+//      is returned
+//   -- const std::set<T>* f(), f(const std::set<T>*):
+//      for consistency, they expect and return a plain set pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <set>
+%}
+
+// exported classes
+
+namespace std {
+
+  template <class _Key, class _Compare = std::less<_Key>,
+	    class _Alloc = allocator<_Key> >
+  class set {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Key value_type;
+    typedef _Key key_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Key);
+
+    %fragment(SWIG_Traits_frag(std::set<_Key, _Compare, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Key),
+	      fragment="StdSetTraits") {
+      namespace swig {
+	template <>  struct traits<std::set<_Key, _Compare, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::set<" #_Key "," #_Compare "," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_SET, std::set<_Key, _Compare, _Alloc >);
+
+    set( const _Compare& );
+
+#ifdef %swig_set_methods
+    // Add swig/language extra methods
+    %swig_set_methods(std::set<_Key, _Compare, _Alloc >);
+#endif
+  
+    %std_set_methods(set);
+  };
+}
diff --git a/trunk/Lib/std/std_sstream.i b/trunk/Lib/std/std_sstream.i
new file mode 100644
index 0000000..12bccef
--- /dev/null
+++ b/trunk/Lib/std/std_sstream.i
@@ -0,0 +1,195 @@
+/* 
+   For wchar support, you need to include the wchar.i file
+   before this file, ie:
+   
+   %include <wchar.i>
+   %include <std_sstream.i>
+
+   or equivalently, just include
+
+   %include <std_wsstream.i>
+*/
+
+%include <std_alloc.i>
+%include <std_basic_string.i>
+%include <std_string.i>
+%include <std_ios.i>
+#if defined(SWIG_WCHAR)
+%include <std_wstring.i>
+#endif
+%include <std_streambuf.i>
+%include <std_iostream.i>
+
+%{
+#include <sstream>
+%}
+
+
+namespace std
+{
+  template<typename _CharT, typename _Traits = char_traits<_CharT>,
+	   typename _Alloc = allocator<_CharT> >
+    class basic_stringbuf : public basic_streambuf<_CharT, _Traits>
+    {
+    public:
+      // Types:
+      typedef _CharT 					char_type;
+      typedef _Traits 					traits_type;
+// 251. basic_stringbuf missing allocator_type
+      typedef _Alloc				       	allocator_type;
+      typedef typename traits_type::int_type 		int_type;
+      typedef typename traits_type::pos_type 		pos_type;
+      typedef typename traits_type::off_type 		off_type;
+
+    public:
+      // Constructors:
+      explicit
+      basic_stringbuf(ios_base::openmode __mode = ios_base::in | ios_base::out);
+
+      explicit
+      basic_stringbuf(const basic_string<_CharT, _Traits, _Alloc>& __str,
+		      ios_base::openmode __mode = ios_base::in | ios_base::out);
+
+      // Get and set:
+      basic_string<_CharT, _Traits, _Alloc>
+      str() const;
+
+      void
+      str(const basic_string<_CharT, _Traits, _Alloc>& __s);
+
+    };
+
+
+  // 27.7.2  Template class basic_istringstream
+  template<typename _CharT, typename _Traits = char_traits<_CharT>,
+	   typename _Alloc = allocator<_CharT> >
+  class basic_istringstream : public basic_istream<_CharT, _Traits>
+  {
+    public:
+      // Types:
+      typedef _CharT 					char_type;
+      typedef _Traits 					traits_type;
+// 251. basic_stringbuf missing allocator_type
+      typedef _Alloc				       	allocator_type;
+      typedef typename traits_type::int_type 		int_type;
+      typedef typename traits_type::pos_type 		pos_type;
+      typedef typename traits_type::off_type 		off_type;
+
+
+    public:
+      // Constructors:
+      explicit
+      basic_istringstream(ios_base::openmode __mode = ios_base::in);
+
+      explicit
+      basic_istringstream(const basic_string<_CharT, _Traits, _Alloc>& __str,
+			  ios_base::openmode __mode = ios_base::in);
+
+      ~basic_istringstream();
+
+      // Members:
+      basic_stringbuf<_CharT, _Traits, _Alloc>*
+      rdbuf() const;
+
+      basic_string<_CharT, _Traits, _Alloc>
+      str() const;
+
+      void
+      str(const basic_string<_CharT, _Traits, _Alloc>& __s);
+    };
+
+
+  // 27.7.3  Template class basic_ostringstream
+  template<typename _CharT, typename _Traits = char_traits<_CharT>,
+	   typename _Alloc = allocator<_CharT> >
+  class basic_ostringstream : public basic_ostream<_CharT, _Traits>
+  {
+    public:
+      // Types:
+      typedef _CharT 					char_type;
+      typedef _Traits 					traits_type;
+// 251. basic_stringbuf missing allocator_type
+      typedef _Alloc				       	allocator_type;
+      typedef typename traits_type::int_type 		int_type;
+      typedef typename traits_type::pos_type 		pos_type;
+      typedef typename traits_type::off_type 		off_type;
+
+
+    public:
+     // Constructors/destructor:
+      explicit
+      basic_ostringstream(ios_base::openmode __mode = ios_base::out);
+
+      explicit
+      basic_ostringstream(const basic_string<_CharT, _Traits, _Alloc>& __str,
+			  ios_base::openmode __mode = ios_base::out);
+
+      ~basic_ostringstream();
+
+      // Members:
+      basic_stringbuf<_CharT, _Traits, _Alloc>*
+      rdbuf() const;
+
+      basic_string<_CharT, _Traits, _Alloc>
+      str() const;
+
+#if 0
+      void
+      str(const basic_string<_CharT, _Traits, _Alloc>& __s);
+#endif
+    };
+
+
+  // 27.7.4  Template class basic_stringstream
+  template<typename _CharT, typename _Traits = char_traits<_CharT>,
+	   typename _Alloc = allocator<_CharT> >
+  class basic_stringstream : public basic_iostream<_CharT, _Traits>
+  {
+    public:
+      // Types:
+      typedef _CharT 					char_type;
+      typedef _Traits 					traits_type;
+// 251. basic_stringbuf missing allocator_type
+      typedef _Alloc				       	allocator_type;
+      typedef typename traits_type::int_type 		int_type;
+      typedef typename traits_type::pos_type 		pos_type;
+      typedef typename traits_type::off_type 		off_type;
+
+    public:
+      // Constructors/destructors
+      explicit
+      basic_stringstream(ios_base::openmode __m = ios_base::out | ios_base::in);
+
+      explicit
+      basic_stringstream(const basic_string<_CharT, _Traits, _Alloc>& __str,
+			 ios_base::openmode __m = ios_base::out | ios_base::in);
+
+      ~basic_stringstream();
+
+      // Members:
+      basic_stringbuf<_CharT, _Traits, _Alloc>*
+      rdbuf() const;
+
+      basic_string<_CharT, _Traits, _Alloc>
+      str() const;
+
+      void
+      str(const basic_string<_CharT, _Traits, _Alloc>& __s);
+    };
+
+
+} // namespace std
+
+
+namespace std {
+  %template(istringstream) basic_istringstream<char>;
+  %template(ostringstream) basic_ostringstream<char>;
+  %template(stringstream)  basic_stringstream<char>;
+
+
+#if defined(SWIG_WCHAR)
+  %template(wistringstream) basic_istringstream<wchar_t>;
+  %template(wostringstream) basic_ostringstream<wchar_t>;
+  %template(wstringstream)  basic_stringstream<wchar_t>;
+#endif
+}
diff --git a/trunk/Lib/std/std_stack.i b/trunk/Lib/std/std_stack.i
new file mode 100644
index 0000000..fb900a5
--- /dev/null
+++ b/trunk/Lib/std/std_stack.i
@@ -0,0 +1,128 @@
+/**
+ * @file   std_stack.i
+ * @date   Sun May  6 01:48:07 2007
+ * 
+ * @brief  A wrapping of std::stack for Ruby.
+ * 
+ * 
+ */
+
+%include <std_container.i>
+
+// Stack
+
+%define %std_stack_methods(stack...)
+  stack();
+  stack( const _Sequence& );
+
+  bool empty() const;
+  size_type size() const;
+  const value_type& top() const;
+  void pop();
+  void push( const value_type& );
+%enddef
+
+%define %std_stack_methods_val(stack...) 
+  %std_stack_methods(stack)
+%enddef
+
+// ------------------------------------------------------------------------
+// std::stack
+// 
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::stack<T>), f(const std::stack<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::stack<T> can be passed.
+//   -- f(std::stack<T>&), f(std::stack<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::stack
+//      can be passed.
+//   -- std::stack<T> f(), const std::stack<T>& f():
+//      the stack is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::stack<T>& f(), std::stack<T>* f():
+//      the stack is returned by reference; therefore, a wrapped std::stack
+//      is returned
+//   -- const std::stack<T>* f(), f(const std::stack<T>*):
+//      for consistency, they expect and return a plain stack pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <stack>
+%}
+
+// exported classes
+
+namespace std {
+
+  template<class _Tp, class _Sequence = std::deque<_Tp> > 
+  class stack {
+  public:
+    typedef size_t size_type;
+    typedef _Tp value_type;
+    typedef value_type& reference;
+    typedef const value_type& const_reference;
+    typedef _Sequence container_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::stack<_Tp, _Sequence >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdStackTraits") {
+      namespace swig {
+	template <>  struct traits<std::stack<_Tp, _Sequence > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::stack<" #_Tp "," #_Sequence " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_STACK, std::stack<_Tp, _Sequence >);
+  
+#ifdef %swig_stack_methods
+    // Add swig/language extra methods
+    %swig_stack_methods(std::stack<_Tp, _Sequence >);
+#endif
+
+    %std_stack_methods(stack);
+  };
+
+  template<class _Tp, class _Sequence > 
+  class stack<_Tp*, _Sequence > {
+  public:
+    typedef size_t size_type;
+    typedef _Sequence::value_type value_type;
+    typedef value_type reference;
+    typedef value_type const_reference;
+    typedef _Sequence container_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::stack<_Tp*, _Sequence >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdStackTraits") {
+      namespace swig {
+	template <>  struct traits<std::stack<_Tp*, _Sequence > > {
+	  typedef value_category category;
+	  static const char* type_name() {
+	    return "std::stack<" #_Tp "," #_Sequence " * >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_STACK, std::stack<_Tp*, _Sequence >);
+
+#ifdef %swig_stack_methods_val
+    // Add swig/language extra methods
+    %swig_stack_methods_val(std::stack<_Tp*, _Sequence >);
+#endif
+
+    %std_stack_methods_val(std::stack<_Tp*, _Sequence >);
+  };
+
+}
+
diff --git a/trunk/Lib/std/std_streambuf.i b/trunk/Lib/std/std_streambuf.i
new file mode 100644
index 0000000..7efb19c
--- /dev/null
+++ b/trunk/Lib/std/std_streambuf.i
@@ -0,0 +1,94 @@
+%include <std_ios.i>
+%{
+#ifndef SWIG_STD_NOMODERN_STL
+#include <streambuf>
+#else
+#include <streambuf.h>
+#endif
+%}
+
+namespace std {
+
+  template<typename _CharT, typename _Traits = char_traits<_CharT> >
+  class basic_streambuf 
+  {
+  public:
+    // Types:
+    typedef _CharT 					char_type;
+    typedef _Traits 					traits_type;
+    typedef typename traits_type::int_type 		int_type;
+    typedef typename traits_type::pos_type 		pos_type;
+    typedef typename traits_type::off_type 		off_type;
+
+  public:
+    virtual 
+    ~basic_streambuf();
+
+    // Locales:
+    locale 
+    pubimbue(const locale &__loc);
+
+    locale   
+    getloc() const; 
+
+    // Buffer and positioning:
+    basic_streambuf<_CharT, _Traits>* 
+    pubsetbuf(char_type* __s, streamsize __n);
+
+    pos_type 
+    pubseekoff(off_type __off, ios_base::seekdir __way, 
+	       ios_base::openmode __mode = std::ios_base::in | std::ios_base::out);
+
+    pos_type 
+    pubseekpos(pos_type __sp,
+	       ios_base::openmode __mode = std::ios_base::in | std::ios_base::out);
+
+    int 
+    pubsync() ;
+
+    // Get and put areas:
+    // Get area:
+    streamsize 
+    in_avail();
+
+    int_type 
+    snextc();
+
+    int_type 
+    sbumpc();
+
+    int_type 
+    sgetc();
+
+    streamsize 
+    sgetn(char_type* __s, streamsize __n);
+
+    // Putback:
+    int_type 
+    sputbackc(char_type __c);
+
+    int_type 
+    sungetc();
+
+    // Put area:
+    int_type 
+    sputc(char_type __c);
+
+    streamsize 
+    sputn(const char_type* __s, streamsize __n);
+
+  protected:
+    basic_streambuf();
+
+  private:
+    basic_streambuf(const basic_streambuf&);
+
+  }; 
+}
+
+namespace std {
+  %template(streambuf) basic_streambuf<char>;
+#if defined(SWIG_WCHAR)
+  %template(wstreambuf) basic_streambuf<wchar_t>;
+#endif
+}
diff --git a/trunk/Lib/std/std_string.i b/trunk/Lib/std/std_string.i
new file mode 100644
index 0000000..35fcdd1
--- /dev/null
+++ b/trunk/Lib/std/std_string.i
@@ -0,0 +1,13 @@
+%include <std/std_basic_string.i>
+
+/* plain strings */
+
+namespace std
+{
+  %std_comp_methods(basic_string<char>);
+  %naturalvar string;
+  typedef basic_string<char> string;
+}
+
+
+%template(string) std::basic_string<char>;
diff --git a/trunk/Lib/std/std_vector.i b/trunk/Lib/std/std_vector.i
new file mode 100644
index 0000000..ab1435b
--- /dev/null
+++ b/trunk/Lib/std/std_vector.i
@@ -0,0 +1,184 @@
+//
+// std::vector
+//
+
+%include <std_container.i>
+
+// Vector
+
+%define %std_vector_methods(vector...)
+  %std_sequence_methods(vector)
+  
+  void reserve(size_type n);
+  size_type capacity() const;
+%enddef
+
+
+%define %std_vector_methods_val(vector...)
+  %std_sequence_methods_val(vector)
+  
+  void reserve(size_type n);
+  size_type capacity() const;
+%enddef
+
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// as much as possible, namely, to allow the user to pass and 
+// be returned tuples or lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&):
+//      the parameter being read-only, either a sequence or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter may be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f(), const std::vector<T>& f():
+//      the vector is returned by copy; therefore, a sequence of T:s 
+//      is returned which is most easily used in other functions
+//   -- std::vector<T>& f(), std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+//   -- const std::vector<T>* f(), f(const std::vector<T>*):
+//      for consistency, they expect and return a plain vector pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+%}    
+
+// exported classes
+
+
+namespace std {
+
+  template<class _Tp, class _Alloc = allocator< _Tp > >
+  class vector {
+  public:
+    typedef size_t size_type;
+    typedef ptrdiff_t difference_type;
+    typedef _Tp value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef _Tp& reference;
+    typedef const _Tp& const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::vector<_Tp, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdVectorTraits") {
+      namespace swig {
+	template <>  struct traits<std::vector<_Tp, _Alloc > > {
+	  typedef pointer_category category;
+	  static const char* type_name() {
+	    return "std::vector<" #_Tp "," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp, _Alloc >);
+
+#ifdef %swig_vector_methods
+    // Add swig/language extra methods
+    %swig_vector_methods(std::vector<_Tp, _Alloc >);
+#endif
+  
+    %std_vector_methods(vector);
+  };
+
+  // ***
+  // This specialization should dissapear or get simplified when
+  // a 'const SWIGTYPE*&' can be defined
+  // ***
+  template<class _Tp, class _Alloc >
+  class vector<_Tp*, _Alloc > {
+  public:
+    typedef size_t size_type;    
+    typedef ptrdiff_t difference_type;
+    typedef _Tp* value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type reference;
+    typedef value_type const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(_Tp);
+
+    %fragment(SWIG_Traits_frag(std::vector<_Tp*, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(_Tp),
+	      fragment="StdVectorTraits") {
+      namespace swig {
+	template <>  struct traits<std::vector<_Tp*, _Alloc > > {
+	  typedef value_category category;
+	  static const char* type_name() {
+	    return "std::vector<" #_Tp " *," #_Alloc " >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp*, _Alloc >);
+
+#ifdef %swig_vector_methods_val
+    // Add swig/language extra methods
+    %swig_vector_methods_val(std::vector<_Tp*, _Alloc >);
+#endif
+
+    %std_vector_methods_val(vector);
+  };
+
+  // ***
+  // ***
+  // bool specialization
+
+  template<class _Alloc > 
+  class vector<bool,_Alloc > {
+  public:
+    typedef size_t size_type;    
+    typedef ptrdiff_t difference_type;
+    typedef bool value_type;
+    typedef value_type* pointer;
+    typedef const value_type* const_pointer;
+    typedef value_type reference;
+    typedef value_type const_reference;
+    typedef _Alloc allocator_type;
+
+    %traits_swigtype(bool);
+
+    %fragment(SWIG_Traits_frag(std::vector<bool, _Alloc >), "header",
+	      fragment=SWIG_Traits_frag(bool),
+	      fragment="StdVectorTraits") {
+      namespace swig {
+	template <>  struct traits<std::vector<bool, _Alloc > > {
+	  typedef value_category category;
+	  static const char* type_name() {
+	    return "std::vector<bool, _Alloc >";
+	  }
+	};
+      }
+    }
+
+    %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<bool, _Alloc >);
+
+
+#ifdef %swig_vector_methods_val
+    // Add swig/language extra methods
+    %swig_vector_methods_val(std::vector<bool, _Alloc >);
+#endif
+
+    %std_vector_methods_val(vector);
+
+#if defined(SWIG_STD_MODERN_STL) && !defined(SWIG_STD_NOMODERN_STL) 
+    void flip();
+#endif
+
+  };
+
+}
diff --git a/trunk/Lib/std/std_vectora.i b/trunk/Lib/std/std_vectora.i
new file mode 100644
index 0000000..0e83dc9
--- /dev/null
+++ b/trunk/Lib/std/std_vectora.i
@@ -0,0 +1,7 @@
+//
+// We keep this file only for backward compatibility, since std_vector.i
+// now uses the std::allocator parameter.
+//
+
+%include <std_vector.i>
+
diff --git a/trunk/Lib/std/std_wios.i b/trunk/Lib/std/std_wios.i
new file mode 100644
index 0000000..e9c5dd4
--- /dev/null
+++ b/trunk/Lib/std/std_wios.i
@@ -0,0 +1,7 @@
+/*
+  Provide 'std_ios.i' with wchar support.
+*/
+
+%include <wchar.i>
+%include <std_ios.i>
+
diff --git a/trunk/Lib/std/std_wiostream.i b/trunk/Lib/std/std_wiostream.i
new file mode 100644
index 0000000..b9bef90
--- /dev/null
+++ b/trunk/Lib/std/std_wiostream.i
@@ -0,0 +1,7 @@
+/*
+  Provide 'std_iostream.i' with wchar support.
+*/
+
+%include <wchar.i>
+%include <std_iostream.i>
+
diff --git a/trunk/Lib/std/std_wsstream.i b/trunk/Lib/std/std_wsstream.i
new file mode 100644
index 0000000..4c663fc
--- /dev/null
+++ b/trunk/Lib/std/std_wsstream.i
@@ -0,0 +1,7 @@
+/*
+  Provide 'std_sstream.i' with wchar support.
+*/
+
+%include <wchar.i>
+%include <std_sstream.i>
+
diff --git a/trunk/Lib/std/std_wstreambuf.i b/trunk/Lib/std/std_wstreambuf.i
new file mode 100644
index 0000000..86ac6af
--- /dev/null
+++ b/trunk/Lib/std/std_wstreambuf.i
@@ -0,0 +1,7 @@
+/*
+  Provide 'std_streambuf.i' with wchar support.
+*/
+
+%include <wchar.i>
+%include <std_streambuf.i>
+
diff --git a/trunk/Lib/std/std_wstring.i b/trunk/Lib/std/std_wstring.i
new file mode 100644
index 0000000..e54d212
--- /dev/null
+++ b/trunk/Lib/std/std_wstring.i
@@ -0,0 +1,14 @@
+%include <wchar.i>
+%include <std/std_basic_string.i>
+
+/* wide strings */
+
+namespace std
+{
+  %std_comp_methods(basic_string<wchar_t>);
+  %naturalvar wstring;
+  typedef basic_string<wchar_t> wstring;
+}
+
+%template(wstring) std::basic_string<wchar_t>;
+
diff --git a/trunk/Lib/std_except.i b/trunk/Lib/std_except.i
new file mode 100644
index 0000000..af9803a
--- /dev/null
+++ b/trunk/Lib/std_except.i
@@ -0,0 +1,58 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_except.i
+ *
+ * SWIG library file with typemaps to handle and throw STD exceptions in a
+ * language and STL independent way, i.e., the target language doesn't
+ * require to support STL but only the 'exception.i' mechanism.
+ *
+ * These typemaps are used when methods are declared with an STD
+ * exception specification, such as
+ *
+ *   size_t at() const throw (std::out_of_range);
+ *
+ * The typemaps here are based on the language independent
+ * 'exception.i' library. If that is working in your target language,
+ * this file will work.
+ * 
+ * If the target language doesn't implement a robust 'exception.i'
+ * mechanism, or you prefer other ways to map the STD exceptions, write
+ * a new std_except.i file in the target library directory.
+ * ----------------------------------------------------------------------------- */
+
+#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGGUILE) || defined(SWIGUTL)
+#error "This version of std_except.i should not be used"
+#endif
+
+%{
+#include <stdexcept>
+%}
+
+%include <exception.i>
+
+
+%define %std_exception_map(Exception, Code)
+  %typemap(throws,noblock=1) Exception {
+    SWIG_exception(Code, $1.what());
+  }
+  %ignore Exception;
+  struct Exception {
+  };
+%enddef
+
+namespace std {
+  %std_exception_map(bad_exception,      SWIG_SystemError);
+  %std_exception_map(domain_error,       SWIG_ValueError);
+  %std_exception_map(exception,          SWIG_SystemError);
+  %std_exception_map(invalid_argument,   SWIG_ValueError);
+  %std_exception_map(length_error,       SWIG_IndexError);
+  %std_exception_map(logic_error,        SWIG_RuntimeError);
+  %std_exception_map(out_of_range,       SWIG_IndexError);
+  %std_exception_map(overflow_error,     SWIG_OverflowError);
+  %std_exception_map(range_error,        SWIG_OverflowError);
+  %std_exception_map(runtime_error,      SWIG_RuntimeError);
+  %std_exception_map(underflow_error,    SWIG_OverflowError);
+}
+
diff --git a/trunk/Lib/stdint.i b/trunk/Lib/stdint.i
new file mode 100644
index 0000000..7b48ca3
--- /dev/null
+++ b/trunk/Lib/stdint.i
@@ -0,0 +1,109 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stdint.i
+ *
+ * SWIG library file for ISO C99 types: 7.18 Integer types <stdint.h>
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <stdint.h>		// Use the C99 official header
+%}
+
+%include <swigarch.i>
+
+/* Exact integral types.  */
+
+/* Signed.  */
+
+typedef signed char		int8_t;
+typedef short int		int16_t;
+typedef int			int32_t;
+#if defined(SWIGWORDSIZE64)
+typedef long int		int64_t;
+#else
+typedef long long int		int64_t;
+#endif
+
+/* Unsigned.  */
+typedef unsigned char		uint8_t;
+typedef unsigned short int	uint16_t;
+typedef unsigned int		uint32_t;
+#if defined(SWIGWORDSIZE64)
+typedef unsigned long int	uint64_t;
+#else
+typedef unsigned long long int	uint64_t;
+#endif
+
+
+/* Small types.  */
+
+/* Signed.  */
+typedef signed char		int_least8_t;
+typedef short int		int_least16_t;
+typedef int			int_least32_t;
+#if defined(SWIGWORDSIZE64)
+typedef long int		int_least64_t;
+#else
+typedef long long int		int_least64_t;
+#endif
+
+/* Unsigned.  */
+typedef unsigned char		uint_least8_t;
+typedef unsigned short int	uint_least16_t;
+typedef unsigned int		uint_least32_t;
+#if defined(SWIGWORDSIZE64)
+typedef unsigned long int	uint_least64_t;
+#else
+typedef unsigned long long int	uint_least64_t;
+#endif
+
+
+/* Fast types.  */
+
+/* Signed.  */
+typedef signed char		int_fast8_t;
+#if defined(SWIGWORDSIZE64)
+typedef long int		int_fast16_t;
+typedef long int		int_fast32_t;
+typedef long int		int_fast64_t;
+#else
+typedef int			int_fast16_t;
+typedef int			int_fast32_t;
+typedef long long int		int_fast64_t;
+#endif
+
+/* Unsigned.  */
+typedef unsigned char		uint_fast8_t;
+#if defined(SWIGWORDSIZE64)
+typedef unsigned long int	uint_fast16_t;
+typedef unsigned long int	uint_fast32_t;
+typedef unsigned long int	uint_fast64_t;
+#else
+typedef unsigned int		uint_fast16_t;
+typedef unsigned int		uint_fast32_t;
+typedef unsigned long long int	uint_fast64_t;
+#endif
+
+
+/* Types for `void *' pointers.  */
+#if defined(SWIGWORDSIZE64)
+typedef long int		intptr_t;
+typedef unsigned long int	uintptr_t;
+#else
+typedef int			intptr_t;
+typedef unsigned int		uintptr_t;
+#endif
+
+
+/* Largest integral types.  */
+#if defined(SWIGWORDSIZE64)
+typedef long int		intmax_t;
+typedef unsigned long int	uintmax_t;
+#else
+typedef long long int		intmax_t;
+typedef unsigned long long int	uintmax_t;
+#endif
+
+
diff --git a/trunk/Lib/stl.i b/trunk/Lib/stl.i
new file mode 100644
index 0000000..c3ade01
--- /dev/null
+++ b/trunk/Lib/stl.i
@@ -0,0 +1,10 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ * ----------------------------------------------------------------------------- */
+
+#warning "stl.i not implemented for this target"
+#define SWIG_STL_UNIMPL
+
diff --git a/trunk/Lib/swig.swg b/trunk/Lib/swig.swg
new file mode 100644
index 0000000..6f40a8f
--- /dev/null
+++ b/trunk/Lib/swig.swg
@@ -0,0 +1,670 @@
+/* -----------------------------------------------------------------------------
+ * swig.swg
+ *
+ * Common macro definitions for various SWIG directives.  This file is always 
+ * included at the top of each input file.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * User Directives 
+ * ----------------------------------------------------------------------------- */
+
+/* Deprecated SWIG directives */
+
+#define %disabledoc     %warn "104:%disabledoc is deprecated"
+#define %enabledoc      %warn "105:%enabledoc is deprecated"
+#define %doconly        %warn "106:%doconly is deprecated"
+#define %style          %warn "107:%style is deprecated" /##/
+#define %localstyle     %warn "108:%localstyle is deprecated" /##/
+#define %title          %warn "109:%title is deprecated" /##/
+#define %section        %warn "110:%section is deprecated" /##/
+#define %subsection     %warn "111:%subsection is deprecated" /##/
+#define %subsubsection  %warn "112:%subsubsection is deprecated" /##/
+#define %new            %warn "117:%new is deprecated. Use %newobject"
+#define %text           %insert("null")
+
+/* Code insertion directives such as %wrapper %{ ... %} */
+
+#define %init        %insert("init")
+#define %wrapper     %insert("wrapper")
+#define %header      %insert("header")
+#define %runtime     %insert("runtime")
+
+/* Class extension */
+
+#define %addmethods  %warn "113:%addmethods is now %extend" %extend
+
+/* %ignore directive */
+
+#define %ignore         %rename($ignore)
+#define %ignorewarn(x)  %rename("$ignore:" x)
+
+/* Access control directives */
+
+#define %readonly    %warn "114:%readonly is deprecated. Use %immutable; " %feature("immutable");
+#define %readwrite   %warn "115:%readwrite is deprecated. Use %mutable; " %feature("immutable","");
+
+#define %immutable       %feature("immutable")
+#define %noimmutable     %feature("immutable","0")
+#define %clearimmutable  %feature("immutable","")
+#define %mutable         %clearimmutable
+
+/* Generation of default constructors/destructors (old form, don't use) */
+#define %nodefault       %feature("nodefault","1")
+#define %default         %feature("nodefault","0")
+#define %clearnodefault  %feature("nodefault","")
+#define %makedefault     %clearnodefault
+
+/* Disable the generation of implicit default constructor */
+#define %nodefaultctor       %feature("nodefaultctor","1")
+#define %defaultctor         %feature("nodefaultctor","0")
+#define %clearnodefaultctor  %feature("nodefaultctor","")
+
+/* Disable the generation of implicit default destructor (dangerous) */
+#define %nodefaultdtor       %feature("nodefaultdtor","1")
+#define %defaultdtor         %feature("nodefaultdtor","0")
+#define %clearnodefaultdtor  %feature("nodefaultdtor","")
+
+/* Enable the generation of copy constructor */
+#define %copyctor       %feature("copyctor","1")
+#define %nocopyctor     %feature("copyctor","0")
+#define %clearcopyctor  %feature("copyctor","")
+
+/* Force the old nodefault behavior, ie disable both constructor and destructor */
+#define %oldnodefault       %feature("oldnodefault","1")
+#define %nooldnodefault     %feature("oldnodefault","0")
+#define %clearoldnodefault  %feature("oldnodefault","")
+
+/* the %exception directive */
+#ifdef SWIGCSHARP
+#define %exception      %feature("except", canthrow=1)
+#else
+#define %exception      %feature("except")
+#endif
+#define %noexception    %feature("except","0")
+#define %clearexception %feature("except","")
+
+/* the %allowexception directive allows the %exception feature to
+   be applied to set/get variable methods */
+#define %allowexception      %feature("allowexcept")
+#define %noallowexception    %feature("allowexcept","0")
+#define %clearallowexception %feature("allowexcept","")
+
+/* the %exceptionvar directive, as %exception but it is only applied
+   to set/get variable methods. You don't need to use the
+   %allowexception directive when using %exceptionvar.
+*/
+#ifdef SWIGCSHARP
+#define %exceptionvar      %feature("exceptvar", canthrow=1)
+#else
+#define %exceptionvar      %feature("exceptvar")
+#endif
+#define %noexceptionvar    %feature("exceptvar","0")
+#define %clearexceptionvar %feature("exceptvar","")
+
+/* the %catches directive */
+#define %catches(tlist...)    %feature("catches","("`tlist`")")
+#define %clearcatches         %feature("catches","")
+
+/* the %exceptionclass directive */
+#define %exceptionclass      %feature("exceptionclass")
+#define %noexceptionclass    %feature("exceptionclass","0")
+#define %clearexceptionclass %feature("exceptionclass","")
+
+/* the %newobject directive */
+#define %newobject        %feature("new")
+#define %nonewobject      %feature("new","0")
+#define %clearnewobject   %feature("new","")
+
+/* the %delobject directive */
+#define %delobject        %feature("del")
+#define %nodelobject      %feature("del","0")
+#define %cleardelobject   %feature("del","")
+
+/* the %refobject/%unrefobject directives */
+#define %refobject         %feature("ref")
+#define %norefobject       %feature("ref","0")
+#define %clearrefobject    %feature("ref","")
+
+#define %unrefobject       %feature("unref")
+#define %nounrefobject     %feature("unref","0")
+#define %clearunrefobject  %feature("unref","")
+
+/* Directives for callback functions (experimental) */
+#define %callback(x)    %feature("callback",`x`)
+#define %nocallback     %feature("callback","0")
+#define %clearcallback  %feature("callback","")
+
+/* the %fastdispatch directive */
+#define %fastdispatch        %feature("fastdispatch")
+#define %nofastdispatch      %feature("fastdispatch","0")
+#define %clearfastdispatch   %feature("fastdispatch","")
+
+/* directors directives */
+#define %director      %feature("director")
+#define %nodirector    %feature("director","0")
+#define %cleardirector %feature("director","")
+
+/* naturalvar directives */
+#define %naturalvar      %feature("naturalvar")
+#define %nonaturalvar    %feature("naturalvar","0")
+#define %clearnaturalvar %feature("naturalvar","")
+
+/* valuewrapper directives */
+#define %valuewrapper        %feature("valuewrapper",)
+#define %clearvaluewrapper   %feature("valuewrapper","")
+#define %novaluewrapper      %feature("novaluewrapper")
+#define %clearnovaluewrapper %feature("novaluewrapper","")
+
+/* Contract support - Experimental and undocumented */
+#define %contract      %feature("contract")
+#define %nocontract    %feature("contract","0")
+#define %clearcontract %feature("contract","")
+
+/* Macro for setting a dynamic cast function */
+%define DYNAMIC_CAST(mangle,func)
+%init %{
+   mangle->dcast = (swig_dycast_func) func;
+%}
+%enddef
+
+/* aggregation support */
+/*
+  This macro performs constant aggregation.  Basically the idea of
+  constant aggregation is that you can group a collection of constants
+  together.  For example, suppose you have some code like this:
+
+       #define UP  1
+       #define DOWN 2
+       #define LEFT 3
+       #define RIGHT 4
+
+  Now, suppose you had a function like this:
+
+       int move(int direction)
+
+  In this case, you might want to restrict the direction argument to
+  one of the supplied constant names. To do this, you could write some
+  typemap code by hand.  Alternatively, you can use the
+  %aggregate_check macro defined here to create a simple check
+  function for you.  Here is an example:
+
+    %aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);
+
+  Now, using a typemap
+
+    %typemap(check) int direction {
+      if (!check_direction($1)) SWIG_exception(SWIG_ValueError,"Bad direction.");
+    }
+
+  or a contract (better)
+
+    %contract move(int x) {
+    require:
+        check_direction(x);
+    }
+
+*/
+   
+%define %aggregate_check(TYPE, NAME, FIRST, ...)
+%wrapper %{
+static int NAME(TYPE x) {
+    static  TYPE values[] = { FIRST, ##__VA_ARGS__ };
+    static  int size = sizeof(values);
+    int     i,j;
+    for (i = 0, j = 0; i < size; i+=sizeof(TYPE),j++) {
+        if (x == values[j]) return 1; 
+    }
+    return 0;
+}
+%}
+%enddef
+
+
+/* -----------------------------------------------------------------------------
+ * %rename predicates
+ * ----------------------------------------------------------------------------- */
+/* 
+   Predicates to be used with %rename, for example:
+
+   - to rename all the functions:
+
+     %rename("%(utitle)s", %$isfunction) "";
+
+   - to rename only the member methods:
+
+     %rename("m_%(utitle)s", %$isfunction, %$ismember) "";
+
+   - to rename only the global functions:
+
+      %rename("m_%(utitle)s", %$isfunction, %$not %$ismember) "";
+
+     or
+
+      %rename("g_%(utitle)s", %$isfunction, %$isglobal) "";
+
+   - to ignore the enumitems in a given class:
+
+     %rename("$ignore", %$isenumitem, %$classname="MyClass") "";
+
+   we use the prefix '%$' to avoid clashings with other swig
+   macros/directives.
+
+*/
+
+%define %$not            "not" %enddef 
+%define %$isenum         "match"="enum"  %enddef
+%define %$isenumitem     "match"="enumitem"  %enddef
+%define %$isaccess       "match"="access"   %enddef
+%define %$isclass        "match"="class","notmatch$template$templatetype"="class"   %enddef
+%define %$isextend       "match"="extend"  %enddef
+%define %$isextend       "match"="extend"  %enddef
+%define %$isconstructor  "match"="constructor"  %enddef
+%define %$isdestructor   "match"="destructor"  %enddef
+%define %$isnamespace    "match"="namespace"  %enddef
+%define %$istemplate     "match"="template"  %enddef
+%define %$isconstant     "match"="constant"  %enddef  /* %constant definition */
+
+%define %$isunion        "match$kind"="union"  %enddef
+%define %$isfunction     "match$kind"="function"  %enddef
+%define %$isvariable     "match$kind"="variable"  %enddef
+%define %$isimmutable    "match$feature:immutable"="1"  %enddef
+%define %$hasconsttype   "match$hasconsttype"="1"  %enddef
+%define %$hasvalue       "match$hasvalue"="1"  %enddef
+%define %$isextension    "match$isextension"="1"  %enddef
+
+%define %$isstatic       "match$storage"="static"  %enddef
+%define %$isfriend       "match$storage"="friend"  %enddef
+%define %$istypedef      "match$storage"="typedef"  %enddef
+%define %$isvirtual      "match$storage"="virtual"  %enddef
+%define %$isexplicit     "match$storage"="explicit"  %enddef
+%define %$isextern       "match$storage"="extern"  %enddef
+
+%define %$ismember       "match$ismember"="1"  %enddef
+%define %$isglobal       %not %ismember  %enddef
+%define %$innamespace    "match$parentNode$nodeType"="namespace"  %enddef
+
+%define %$ispublic       "match$access"="public"  %enddef
+%define %$isprotected    "match$access"="protected"  %enddef
+%define %$isprivate      "match$access"="private"  %enddef
+
+%define %$ismemberget    "match$memberget"="1"  %enddef
+%define %$ismemberset    "match$memberset"="1"  %enddef
+
+%define %$classname      %ismember,match$parentNode$name  %enddef
+
+/* -----------------------------------------------------------------------------
+ * Include all the warnings labels and macros 
+ * ----------------------------------------------------------------------------- */
+
+%include <swigwarnings.swg>
+
+/* -----------------------------------------------------------------------------
+ * Default handling of certain overloaded operators 
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+%ignoreoperator(NEW)     operator new;
+%ignoreoperator(DELETE)  operator delete;
+%ignoreoperator(NEWARR)  operator new[];
+%ignoreoperator(DELARR)  operator delete[];
+
+/* add C++ operator aliases */
+%rename("operator &&") operator and;    // `and'    `&&'
+%rename("operator ||") operator or;     // `or'     `||'
+%rename("operator !")  operator not;    // `not'     `!'
+%rename("operator &=") operator and_eq; // `and_eq'  `&='
+%rename("operator &")  operator bitand; // `bitand'  `&'
+%rename("operator |")  operator bitor;  // `bitor'   `|'
+%rename("operator ~")  operator compl;  // `compl'   `~'
+%rename("operator !=") operator not_eq; // `not_eq'  `!='
+%rename("operator |=") operator or_eq;  // `or_eq'   `|='
+%rename("operator ^")  operator xor;    // `xor'     `^'
+%rename("operator ^=") operator xor_eq; // `xor_eq'  `^='
+
+/* Smart pointer handling */
+
+%rename(__deref__) *::operator->;
+%rename(__ref__)   *::operator*();
+%rename(__ref__)   *::operator*() const;
+
+/* Define std namespace */
+namespace std {
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Default char * and C array typemaps
+ * ----------------------------------------------------------------------------- */
+
+/* Set up the typemap for handling new return strings */
+
+#ifdef __cplusplus
+%typemap(newfree) char * "delete [] $1;";
+#else
+%typemap(newfree) char * "free($1);";
+#endif
+
+/* Default typemap for handling char * members */
+
+#ifdef __cplusplus
+%typemap(memberin) char * {
+  if ($1) delete [] $1;
+  if ($input) {
+     $1 = ($1_type) (new char[strlen((const char *)$input)+1]);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+%typemap(memberin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * {
+  if ($input) {
+     $1 = ($1_type) (new char[strlen((const char *)$input)+1]);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+%typemap(globalin) char * {
+  if ($1) delete [] $1;
+  if ($input) {
+     $1 = ($1_type) (new char[strlen((const char *)$input)+1]);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+%typemap(globalin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * {
+  if ($input) {
+     $1 = ($1_type) (new char[strlen((const char *)$input)+1]);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+#else
+%typemap(memberin) char * {
+  if ($1) free((char *)$1);
+  if ($input) {
+     $1 = ($1_type) malloc(strlen((const char *)$input)+1);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+%typemap(memberin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * {
+  if ($input) {
+     $1 = ($1_type) malloc(strlen((const char *)$input)+1);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+%typemap(globalin) char * {
+  if ($1) free((char *)$1);
+  if ($input) {
+     $1 = ($1_type) malloc(strlen((const char *)$input)+1);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+%typemap(globalin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const char * {
+  if ($input) {
+     $1 = ($1_type) malloc(strlen((const char *)$input)+1);
+     strcpy((char *)$1, (const char *)$input);
+  } else {
+     $1 = 0;
+  }
+}
+
+#endif
+
+/* Character array handling */
+
+%typemap(memberin) char [ANY] {
+  if ($input) strncpy((char *)$1, (const char *)$input, $1_dim0);
+  else $1[0] = 0;
+}
+
+%typemap(globalin) char [ANY] {
+  if ($input) strncpy((char *)$1, (const char *)$input, $1_dim0);
+  else $1[0] = 0;
+}
+
+%typemap(memberin) char [] {
+  if ($input) strcpy((char *)$1, (const char *)$input);
+  else $1[0] = 0;
+}
+
+%typemap(globalin) char [] {
+  if ($input) strcpy((char *)$1, (const char *)$input);
+  else $1[0] = 0;
+}
+
+/* memberin/globalin typemap for arrays. */
+
+%typemap(memberin) SWIGTYPE [ANY] {
+  size_t ii;
+  $1_basetype *b = ($1_basetype *) $1;
+  for (ii = 0; ii < (size_t)$1_size; ii++) b[ii] = *(($1_basetype *) $input + ii);
+}
+
+%typemap(globalin) SWIGTYPE [ANY] {
+  size_t ii;
+  $1_basetype *b = ($1_basetype *) $1;
+  for (ii = 0; ii < (size_t)$1_size; ii++) b[ii] = *(($1_basetype *) $input + ii);
+}
+
+/* memberin/globalin typemap for double arrays. */
+
+%typemap(memberin) SWIGTYPE [ANY][ANY] {
+  $basetype (*inp)[$dim1] = ($basetype (*)[$dim1])($input);
+  $basetype (*dest)[$dim1] = ($basetype (*)[$dim1])($1);
+  size_t ii = 0;
+  for (; ii < $dim0; ++ii) {
+    $basetype *ip = inp[ii];
+    $basetype *dp = dest[ii];
+    size_t jj = 0;
+    for (; jj < $dim1; ++jj) dp[jj] = ip[jj];
+  }
+}
+
+%typemap(globalin) SWIGTYPE [ANY][ANY] {
+  $basetype (*inp)[$dim1] = ($basetype (*)[$dim1])($input);
+  $basetype (*dest)[$dim1] = ($basetype (*)[$dim1])($1);
+  size_t ii = 0;
+  for (; ii < $dim0; ++ii) {
+    $basetype *ip = inp[ii];
+    $basetype *dp = dest[ii];
+    size_t jj = 0;
+    for (; jj < $dim1; ++jj) dp[jj] = ip[jj];
+  }
+}
+
+/* Typemap for variable length arguments sentinel value.  Used
+   by the %varargs directive. */
+
+%typemap(in,numinputs=0) SWIGTYPE *VARARGS_SENTINEL, SWIGTYPE VARARGS_SENTINEL "";
+
+
+/* -----------------------------------------------------------------------------
+ * Overloading support
+ * ----------------------------------------------------------------------------- */
+
+/*
+ * Function/method overloading support.   This is done through typemaps,
+ * but also involve a precedence level. 
+ */
+
+/* Macro for overload resolution */
+
+%define %typecheck(_x...) %typemap(typecheck, precedence=_x) %enddef
+
+/* Macros for precedence levels */
+
+%define SWIG_TYPECHECK_POINTER       0     %enddef
+%define SWIG_TYPECHECK_ITERATOR      5     %enddef
+%define SWIG_TYPECHECK_VOIDPTR       10    %enddef
+%define SWIG_TYPECHECK_BOOL          15    %enddef
+%define SWIG_TYPECHECK_UINT8         20    %enddef
+%define SWIG_TYPECHECK_INT8          25    %enddef
+%define SWIG_TYPECHECK_UINT16        30    %enddef
+%define SWIG_TYPECHECK_INT16         35    %enddef
+%define SWIG_TYPECHECK_UINT32        40    %enddef
+%define SWIG_TYPECHECK_INT32         45    %enddef
+%define SWIG_TYPECHECK_SIZE          47    %enddef
+%define SWIG_TYPECHECK_PTRDIFF       48    %enddef
+%define SWIG_TYPECHECK_UINT64        50    %enddef
+%define SWIG_TYPECHECK_INT64         55    %enddef
+%define SWIG_TYPECHECK_UINT128       60    %enddef
+%define SWIG_TYPECHECK_INT128        65    %enddef
+%define SWIG_TYPECHECK_INTEGER       70    %enddef
+%define SWIG_TYPECHECK_FLOAT         80    %enddef
+%define SWIG_TYPECHECK_DOUBLE        90    %enddef
+%define SWIG_TYPECHECK_CPLXFLT       95    %enddef
+%define SWIG_TYPECHECK_CPLXDBL      100    %enddef
+%define SWIG_TYPECHECK_COMPLEX      105    %enddef
+%define SWIG_TYPECHECK_UNICHAR      110    %enddef
+%define SWIG_TYPECHECK_STDUNISTRING 115    %enddef
+%define SWIG_TYPECHECK_UNISTRING    120    %enddef
+%define SWIG_TYPECHECK_CHAR         130    %enddef
+%define SWIG_TYPECHECK_STDSTRING    135    %enddef
+%define SWIG_TYPECHECK_STRING       140    %enddef
+%define SWIG_TYPECHECK_PAIR         150    %enddef
+%define SWIG_TYPECHECK_VECTOR       160    %enddef
+%define SWIG_TYPECHECK_DEQUE        170    %enddef
+%define SWIG_TYPECHECK_LIST         180    %enddef
+%define SWIG_TYPECHECK_SET          190    %enddef
+%define SWIG_TYPECHECK_MULTISET     200    %enddef
+%define SWIG_TYPECHECK_MAP          210    %enddef
+%define SWIG_TYPECHECK_MULTIMAP     220    %enddef
+%define SWIG_TYPECHECK_STACK        230    %enddef
+%define SWIG_TYPECHECK_QUEUE        240    %enddef
+
+%define SWIG_TYPECHECK_BOOL_ARRAY        1015    %enddef
+%define SWIG_TYPECHECK_INT8_ARRAY        1025    %enddef
+%define SWIG_TYPECHECK_INT16_ARRAY       1035    %enddef
+%define SWIG_TYPECHECK_INT32_ARRAY       1045    %enddef
+%define SWIG_TYPECHECK_INT64_ARRAY       1055    %enddef
+%define SWIG_TYPECHECK_INT128_ARRAY      1065    %enddef
+%define SWIG_TYPECHECK_FLOAT_ARRAY       1080    %enddef
+%define SWIG_TYPECHECK_DOUBLE_ARRAY      1090    %enddef
+%define SWIG_TYPECHECK_CHAR_ARRAY        1130    %enddef
+%define SWIG_TYPECHECK_STRING_ARRAY      1140    %enddef
+%define SWIG_TYPECHECK_OBJECT_ARRAY      1150    %enddef
+
+%define SWIG_TYPECHECK_BOOL_PTR          2015    %enddef
+%define SWIG_TYPECHECK_UINT8_PTR         2020    %enddef
+%define SWIG_TYPECHECK_INT8_PTR          2025    %enddef
+%define SWIG_TYPECHECK_UINT16_PTR        2030    %enddef
+%define SWIG_TYPECHECK_INT16_PTR         2035    %enddef
+%define SWIG_TYPECHECK_UINT32_PTR        2040    %enddef
+%define SWIG_TYPECHECK_INT32_PTR         2045    %enddef
+%define SWIG_TYPECHECK_UINT64_PTR        2050    %enddef
+%define SWIG_TYPECHECK_INT64_PTR         2055    %enddef
+%define SWIG_TYPECHECK_FLOAT_PTR         2080    %enddef
+%define SWIG_TYPECHECK_DOUBLE_PTR        2090    %enddef
+%define SWIG_TYPECHECK_CHAR_PTR          2130    %enddef
+
+
+%define SWIG_TYPECHECK_SWIGOBJECT        5000    %enddef
+
+
+/* -----------------------------------------------------------------------------
+ *  Runtime code
+ * ----------------------------------------------------------------------------- */
+
+/*  The SwigValueWrapper class  */
+
+/*  
+ * This template wrapper is used to handle C++ objects that are passed or 
+ * returned by value.   This is necessary to handle objects that define
+ * no default-constructor (making it difficult for SWIG to properly declare
+ * local variables).
+ *
+ * The wrapper is used as follows.  First consider a function like this:
+ *
+ *      Vector cross_product(Vector a, Vector b)
+ *
+ * Now, if Vector is defined as a C++ class with no default constructor, 
+ * code is generated as follows:
+ *
+ *     Vector *wrap_cross_product(Vector *inarg1, Vector *inarg2) {
+ *          SwigValueWrapper<Vector>  arg1;
+ *          SwigValueWrapper<Vector>  arg2;
+ *          SwigValueWrapper<Vector> result;
+ *
+ *          arg1 = *inarg1;
+ *          arg2 = *inarg2;
+ *          ...            
+ *          result = cross_product(arg1,arg2);
+ *          ...
+ *          return new Vector(result);
+ *    }
+ *         
+ * In the wrappers, the template SwigValueWrapper simply provides a thin
+ * layer around a Vector *.  However, it does this in a way that allows
+ * the object to be bound after the variable declaration (which is not possible
+ * with the bare object when it lacks a default constructor).  
+ *
+ * An observant reader will notice that the code after the variable declarations
+ * is *identical* to the code used for classes that do define default constructors.
+ * Thus, this neat trick allows us to fix this special case without having to
+ * make massive changes to typemaps and other parts of the SWIG code generator.
+ *
+ * Note: this code is not included when SWIG runs in C-mode, when classes
+ * define default constructors, or when pointers and references are used.
+ * SWIG tries to avoid doing this except in very special circumstances.
+ *
+ * Note: This solution suffers from making a large number of copies
+ * of the underlying object.  However, this is needed in the interest of
+ * safety and in order to cover all of the possible ways in which a value
+ * might be assigned.  For example:
+ *
+ *       arg1 = *inarg1;       // Assignment from a pointer
+ *       arg1 = Vector(1,2,3); // Assignment from a value  
+ *
+ * This wrapping technique was suggested by William Fulton and is henceforth
+ * known as the "Fulton Transform" :-).
+ */
+
+#ifdef __cplusplus
+%insert("runtime") %{
+#ifdef __cplusplus
+template<typename T> class SwigValueWrapper {
+    T *tt;
+public:
+    SwigValueWrapper() : tt(0) { }
+    SwigValueWrapper(const SwigValueWrapper<T>& rhs) : tt(new T(*rhs.tt)) { }
+    SwigValueWrapper(const T& t) : tt(new T(t)) { }
+    ~SwigValueWrapper() { delete tt; } 
+    SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; }
+    operator T&() const { return *tt; }
+    T *operator&() { return tt; }
+private:
+    SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
+};%}
+
+/*
+ * SwigValueInit() is a generic initialisation solution as the following approach:
+ * 
+ *       T c_result = T();
+ * 
+ * doesn't compile for all types for example:
+ * 
+ *       unsigned int c_result = unsigned int();
+ */
+%insert("runtime") %{
+template <typename T> T SwigValueInit() {
+  return T();
+}
+#endif
+%}
+#endif
+
+/*  The swiglabels  */
+
+%insert("runtime") "swiglabels.swg"
+
+
diff --git a/trunk/Lib/swigarch.i b/trunk/Lib/swigarch.i
new file mode 100644
index 0000000..260b608
--- /dev/null
+++ b/trunk/Lib/swigarch.i
@@ -0,0 +1,65 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigarch.i
+ *
+ * SWIG library file for 32bit/64bit code specialization and checking.
+ *
+ * Use only in extreme cases, when no arch. independent code can be
+ * generated
+ * 
+ * To activate architecture specific code, use
+ *
+ *     swig -DSWIGWORDSIZE32
+ *
+ * or
+ *
+ *     swig -DSWIGWORDSIZE64
+ *
+ * Note that extra checking code will be added to the wrapped code,
+ * which will prevent the compilation in a different architecture.
+ *
+ * If you don't specify the SWIGWORDSIZE (the default case), swig will
+ * generate architecture independent and/or 32bits code, with no extra
+ * checking code added.
+ * ----------------------------------------------------------------------------- */
+
+#if !defined(SWIGWORDSIZE32) &&  !defined(SWIGWORDSIZE64)
+# if (__WORDSIZE == 32)
+#  define SWIGWORDSIZE32
+# endif
+#endif
+  
+#if !defined(SWIGWORDSIZE64) &&  !defined(SWIGWORDSIZE32) 
+# if defined(__x86_64) || defined(__x86_64__) || (__WORDSIZE == 64)
+#  define SWIGWORDSIZE64
+# endif
+#endif
+
+
+#ifdef SWIGWORDSIZE32
+%{
+#define SWIGWORDSIZE32
+#ifndef LONG_MAX
+#include <limits.h>
+#endif
+#if (__WORDSIZE == 64) || (LONG_MAX != INT_MAX)
+# error "SWIG wrapped code invalid in 64 bit architecture, regenarete code using -DSWIGWORDSIZE64"
+#endif
+%}
+#endif
+
+#ifdef SWIGWORDSIZE64
+%{
+#define SWIGWORDSIZE64
+#ifndef LONG_MAX
+#include <limits.h>
+#endif
+#if (__WORDSIZE == 32) || (LONG_MAX == INT_MAX)
+# error "SWIG wrapped code invalid in 32 bit architecture, regenarete code using -DSWIGWORDSIZE32"
+#endif
+%}
+#endif
+  
+
diff --git a/trunk/Lib/swigerrors.swg b/trunk/Lib/swigerrors.swg
new file mode 100644
index 0000000..32857c4
--- /dev/null
+++ b/trunk/Lib/swigerrors.swg
@@ -0,0 +1,16 @@
+/*  Errors in SWIG */
+#define  SWIG_UnknownError    	   -1 
+#define  SWIG_IOError        	   -2 
+#define  SWIG_RuntimeError   	   -3 
+#define  SWIG_IndexError     	   -4 
+#define  SWIG_TypeError      	   -5 
+#define  SWIG_DivisionByZero 	   -6 
+#define  SWIG_OverflowError  	   -7 
+#define  SWIG_SyntaxError    	   -8 
+#define  SWIG_ValueError     	   -9 
+#define  SWIG_SystemError    	   -10
+#define  SWIG_AttributeError 	   -11
+#define  SWIG_MemoryError    	   -12 
+#define  SWIG_NullReferenceError   -13
+
+
diff --git a/trunk/Lib/swiginit.swg b/trunk/Lib/swiginit.swg
new file mode 100644
index 0000000..903ac54
--- /dev/null
+++ b/trunk/Lib/swiginit.swg
@@ -0,0 +1,236 @@
+/* -----------------------------------------------------------------------------
+ * Type initialization:
+ * This problem is tough by the requirement that no dynamic 
+ * memory is used. Also, since swig_type_info structures store pointers to 
+ * swig_cast_info structures and swig_cast_info structures store pointers back
+ * to swig_type_info structures, we need some lookup code at initialization. 
+ * The idea is that swig generates all the structures that are needed. 
+ * The runtime then collects these partially filled structures. 
+ * The SWIG_InitializeModule function takes these initial arrays out of 
+ * swig_module, and does all the lookup, filling in the swig_module.types
+ * array with the correct data and linking the correct swig_cast_info
+ * structures together.
+ *
+ * The generated swig_type_info structures are assigned staticly to an initial 
+ * array. We just loop through that array, and handle each type individually.
+ * First we lookup if this type has been already loaded, and if so, use the
+ * loaded structure instead of the generated one. Then we have to fill in the
+ * cast linked list. The cast data is initially stored in something like a
+ * two-dimensional array. Each row corresponds to a type (there are the same
+ * number of rows as there are in the swig_type_initial array). Each entry in
+ * a column is one of the swig_cast_info structures for that type.
+ * The cast_initial array is actually an array of arrays, because each row has
+ * a variable number of columns. So to actually build the cast linked list,
+ * we find the array of casts associated with the type, and loop through it 
+ * adding the casts to the list. The one last trick we need to do is making
+ * sure the type pointer in the swig_cast_info struct is correct.
+ *
+ * First off, we lookup the cast->type name to see if it is already loaded. 
+ * There are three cases to handle:
+ *  1) If the cast->type has already been loaded AND the type we are adding
+ *     casting info to has not been loaded (it is in this module), THEN we
+ *     replace the cast->type pointer with the type pointer that has already
+ *     been loaded.
+ *  2) If BOTH types (the one we are adding casting info to, and the 
+ *     cast->type) are loaded, THEN the cast info has already been loaded by
+ *     the previous module so we just ignore it.
+ *  3) Finally, if cast->type has not already been loaded, then we add that
+ *     swig_cast_info to the linked list (because the cast->type) pointer will
+ *     be correct.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* c-mode */
+#endif
+#endif
+
+#if 0
+#define SWIGRUNTIME_DEBUG
+#endif
+
+
+SWIGRUNTIME void
+SWIG_InitializeModule(void *clientdata) {
+  size_t i;
+  swig_module_info *module_head, *iter;
+  int found, init;
+
+  clientdata = clientdata;
+
+  /* check to see if the circular list has been setup, if not, set it up */
+  if (swig_module.next==0) {
+    /* Initialize the swig_module */
+    swig_module.type_initial = swig_type_initial;
+    swig_module.cast_initial = swig_cast_initial;
+    swig_module.next = &swig_module;
+    init = 1;
+  } else {
+    init = 0;
+  }
+
+  /* Try and load any already created modules */
+  module_head = SWIG_GetModule(clientdata);
+  if (!module_head) {
+    /* This is the first module loaded for this interpreter */
+    /* so set the swig module into the interpreter */
+    SWIG_SetModule(clientdata, &swig_module);
+    module_head = &swig_module;
+  } else {
+    /* the interpreter has loaded a SWIG module, but has it loaded this one? */
+    found=0;
+    iter=module_head;
+    do {
+      if (iter==&swig_module) {
+        found=1;
+        break;
+      }
+      iter=iter->next;
+    } while (iter!= module_head);
+
+    /* if the is found in the list, then all is done and we may leave */
+    if (found) return;
+    /* otherwise we must add out module into the list */
+    swig_module.next = module_head->next;
+    module_head->next = &swig_module;
+  }
+
+  /* When multiple interpeters are used, a module could have already been initialized in
+     a different interpreter, but not yet have a pointer in this interpreter.
+     In this case, we do not want to continue adding types... everything should be
+     set up already */
+  if (init == 0) return;
+
+  /* Now work on filling in swig_module.types */
+#ifdef SWIGRUNTIME_DEBUG
+  printf("SWIG_InitializeModule: size %d\n", swig_module.size);
+#endif
+  for (i = 0; i < swig_module.size; ++i) {
+    swig_type_info *type = 0;
+    swig_type_info *ret;
+    swig_cast_info *cast;
+  
+#ifdef SWIGRUNTIME_DEBUG
+    printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
+#endif
+
+    /* if there is another module already loaded */
+    if (swig_module.next != &swig_module) {
+      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
+    }
+    if (type) {
+      /* Overwrite clientdata field */
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: found type %s\n", type->name);
+#endif
+      if (swig_module.type_initial[i]->clientdata) {
+	type->clientdata = swig_module.type_initial[i]->clientdata;
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name);
+#endif
+      }
+    } else {
+      type = swig_module.type_initial[i];
+    }
+
+    /* Insert casting types */
+    cast = swig_module.cast_initial[i];
+    while (cast->type) {
+    
+      /* Don't need to add information already in the list */
+      ret = 0;
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: look cast %s\n", cast->type->name);
+#endif
+      if (swig_module.next != &swig_module) {
+        ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
+#ifdef SWIGRUNTIME_DEBUG
+	if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name);
+#endif
+      }
+      if (ret) {
+	if (type == swig_module.type_initial[i]) {
+#ifdef SWIGRUNTIME_DEBUG
+	  printf("SWIG_InitializeModule: skip old type %s\n", ret->name);
+#endif
+	  cast->type = ret;
+	  ret = 0;
+	} else {
+	  /* Check for casting already in the list */
+	  swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);
+#ifdef SWIGRUNTIME_DEBUG
+	  if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name);
+#endif
+	  if (!ocast) ret = 0;
+	}
+      }
+
+      if (!ret) {
+#ifdef SWIGRUNTIME_DEBUG
+	printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name);
+#endif
+        if (type->cast) {
+          type->cast->prev = cast;
+          cast->next = type->cast;
+        }
+        type->cast = cast;
+      }
+      cast++;
+    }
+    /* Set entry in modules->types array equal to the type */
+    swig_module.types[i] = type;
+  }
+  swig_module.types[i] = 0;
+
+#ifdef SWIGRUNTIME_DEBUG
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+  for (i = 0; i < swig_module.size; ++i) {
+    int j = 0;
+    swig_cast_info *cast = swig_module.cast_initial[i];
+    printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
+    while (cast->type) {
+      printf("SWIG_InitializeModule: cast type %s\n", cast->type->name);
+      cast++;
+      ++j;
+    }
+  printf("---- Total casts: %d\n",j);
+  }
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+#endif
+}
+
+/* This function will propagate the clientdata field of type to
+* any new swig_type_info structures that have been added into the list
+* of equivalent types.  It is like calling
+* SWIG_TypeClientData(type, clientdata) a second time.
+*/
+SWIGRUNTIME void
+SWIG_PropagateClientData(void) {
+  size_t i;
+  swig_cast_info *equiv;
+  static int init_run = 0;
+
+  if (init_run) return;
+  init_run = 1;
+
+  for (i = 0; i < swig_module.size; i++) {
+    if (swig_module.types[i]->clientdata) {
+      equiv = swig_module.types[i]->cast;
+      while (equiv) {
+        if (!equiv->converter) {
+          if (equiv->type && !equiv->type->clientdata)
+            SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
+        }
+        equiv = equiv->next;
+      }
+    }
+  }
+}
+
+#ifdef __cplusplus
+#if 0
+{ /* c-mode */
+#endif
+}
+#endif
diff --git a/trunk/Lib/swiglabels.swg b/trunk/Lib/swiglabels.swg
new file mode 100644
index 0000000..b943afb
--- /dev/null
+++ b/trunk/Lib/swiglabels.swg
@@ -0,0 +1,108 @@
+/* -----------------------------------------------------------------------------
+ *  This section contains generic SWIG labels for method/variable
+ *  declarations/attributes, and other compiler dependent labels.
+ * ----------------------------------------------------------------------------- */
+
+/* template workaround for compilers that cannot correctly implement the C++ standard */
+#ifndef SWIGTEMPLATEDISAMBIGUATOR
+# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# elif defined(__HP_aCC)
+/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
+/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# else
+#  define SWIGTEMPLATEDISAMBIGUATOR
+# endif
+#endif
+
+/* inline attribute */
+#ifndef SWIGINLINE
+# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
+#   define SWIGINLINE inline
+# else
+#   define SWIGINLINE
+# endif
+#endif
+
+/* attribute recognised by some compilers to avoid 'unused' warnings */
+#ifndef SWIGUNUSED
+# if defined(__GNUC__)
+#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+#     define SWIGUNUSED __attribute__ ((__unused__)) 
+#   else
+#     define SWIGUNUSED
+#   endif
+# elif defined(__ICC)
+#   define SWIGUNUSED __attribute__ ((__unused__)) 
+# else
+#   define SWIGUNUSED 
+# endif
+#endif
+
+#ifndef SWIG_MSC_UNSUPPRESS_4505
+# if defined(_MSC_VER)
+#   pragma warning(disable : 4505) /* unreferenced local function has been removed */
+# endif 
+#endif
+
+#ifndef SWIGUNUSEDPARM
+# ifdef __cplusplus
+#   define SWIGUNUSEDPARM(p)
+# else
+#   define SWIGUNUSEDPARM(p) p SWIGUNUSED 
+# endif
+#endif
+
+/* internal SWIG method */
+#ifndef SWIGINTERN
+# define SWIGINTERN static SWIGUNUSED
+#endif
+
+/* internal inline SWIG method */
+#ifndef SWIGINTERNINLINE
+# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
+#endif
+
+/* exporting methods */
+#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+#  ifndef GCC_HASCLASSVISIBILITY
+#    define GCC_HASCLASSVISIBILITY
+#  endif
+#endif
+
+#ifndef SWIGEXPORT
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   if defined(STATIC_LINKED)
+#     define SWIGEXPORT
+#   else
+#     define SWIGEXPORT __declspec(dllexport)
+#   endif
+# else
+#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
+#     define SWIGEXPORT __attribute__ ((visibility("default")))
+#   else
+#     define SWIGEXPORT
+#   endif
+# endif
+#endif
+
+/* calling conventions for Windows */
+#ifndef SWIGSTDCALL
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   define SWIGSTDCALL __stdcall
+# else
+#   define SWIGSTDCALL
+# endif 
+#endif
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
+#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
+# define _SCL_SECURE_NO_DEPRECATE
+#endif
+
diff --git a/trunk/Lib/swigrun.i b/trunk/Lib/swigrun.i
new file mode 100644
index 0000000..17a1409
--- /dev/null
+++ b/trunk/Lib/swigrun.i
@@ -0,0 +1,11 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigrun.i
+ *
+ * Empty module (for now).  Placeholder for runtime libs
+ * ----------------------------------------------------------------------------- */
+
+%module swigrun
+
diff --git a/trunk/Lib/swigrun.swg b/trunk/Lib/swigrun.swg
new file mode 100644
index 0000000..9ee676a
--- /dev/null
+++ b/trunk/Lib/swigrun.swg
@@ -0,0 +1,569 @@
+/* -----------------------------------------------------------------------------
+ * swigrun.swg
+ *
+ * This file contains generic CAPI SWIG runtime support for pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+/* This should only be incremented when either the layout of swig_type_info changes,
+   or for whatever reason, the runtime changes incompatibly */
+#define SWIG_RUNTIME_VERSION "4"
+
+/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
+#ifdef SWIG_TYPE_TABLE
+# define SWIG_QUOTE_STRING(x) #x
+# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
+# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
+#else
+# define SWIG_TYPE_TABLE_NAME
+#endif
+
+/*
+  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
+  creating a static or dynamic library from the swig runtime code.
+  In 99.9% of the cases, swig just needs to declare them as 'static'.
+  
+  But only do this if is strictly necessary, ie, if you have problems
+  with your compiler or so.
+*/
+
+#ifndef SWIGRUNTIME
+# define SWIGRUNTIME SWIGINTERN
+#endif
+
+#ifndef SWIGRUNTIMEINLINE
+# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
+#endif
+
+/*  Generic buffer size */
+#ifndef SWIG_BUFFER_SIZE
+# define SWIG_BUFFER_SIZE 1024
+#endif
+
+/* Flags for pointer conversions */
+#define SWIG_POINTER_DISOWN        0x1
+#define SWIG_CAST_NEW_MEMORY       0x2
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_OWN           0x1
+
+
+/* 
+   Flags/methods for returning states.
+   
+   The swig conversion methods, as ConvertPtr, return and integer 
+   that tells if the conversion was successful or not. And if not,
+   an error code can be returned (see swigerrors.swg for the codes).
+   
+   Use the following macros/flags to set or process the returning
+   states.
+   
+   In old swig versions, you usually write code as:
+
+     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
+       // success code
+     } else {
+       //fail code
+     }
+
+   Now you can be more explicit as:
+
+    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+    } else {
+      // fail code
+    }
+
+   that seems to be the same, but now you can also do
+
+    Type *ptr;
+    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+      if (SWIG_IsNewObj(res) {
+        ...
+	delete *ptr;
+      } else {
+        ...
+      }
+    } else {
+      // fail code
+    }
+    
+   I.e., now SWIG_ConvertPtr can return new objects and you can
+   identify the case and take care of the deallocation. Of course that
+   requires also to SWIG_ConvertPtr to return new result values, as
+
+      int SWIG_ConvertPtr(obj, ptr,...) {         
+        if (<obj is ok>) {			       
+          if (<need new object>) {		       
+            *ptr = <ptr to new allocated object>; 
+            return SWIG_NEWOBJ;		       
+          } else {				       
+            *ptr = <ptr to old object>;	       
+            return SWIG_OLDOBJ;		       
+          } 				       
+        } else {				       
+          return SWIG_BADOBJ;		       
+        }					       
+      }
+
+   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
+   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
+   swig errors code.
+
+   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
+   allows to return the 'cast rank', for example, if you have this
+
+       int food(double)
+       int fooi(int);
+
+   and you call
+ 
+      food(1)   // cast rank '1'  (1 -> 1.0)
+      fooi(1)   // cast rank '0'
+
+   just use the SWIG_AddCast()/SWIG_CheckState()
+
+
+ */
+#define SWIG_OK                    (0) 
+#define SWIG_ERROR                 (-1)
+#define SWIG_IsOK(r)               (r >= 0)
+#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)  
+
+/* The CastRankLimit says how many bits are used for the cast rank */
+#define SWIG_CASTRANKLIMIT         (1 << 8)
+/* The NewMask denotes the object was created (using new/malloc) */
+#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
+/* The TmpMask is for in/out typemaps that use temporal objects */
+#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
+/* Simple returning values */
+#define SWIG_BADOBJ                (SWIG_ERROR)
+#define SWIG_OLDOBJ                (SWIG_OK)
+#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
+#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
+/* Check, add and del mask methods */
+#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
+#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
+#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
+#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
+#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
+#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
+
+
+/* Cast-Rank Mode */
+#if defined(SWIG_CASTRANK_MODE)
+#  ifndef SWIG_TypeRank
+#    define SWIG_TypeRank             unsigned long
+#  endif
+#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
+#    define SWIG_MAXCASTRANK          (2)
+#  endif
+#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
+#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
+SWIGINTERNINLINE int SWIG_AddCast(int r) { 
+  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
+}
+SWIGINTERNINLINE int SWIG_CheckState(int r) { 
+  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; 
+}
+#else /* no cast-rank mode */
+#  define SWIG_AddCast
+#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
+#endif
+
+
+
+
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void *(*swig_converter_func)(void *, int *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
+
+/* Structure to store information on one type */
+typedef struct swig_type_info {
+  const char             *name;			/* mangled name of this type */
+  const char             *str;			/* human readable name of this type */
+  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
+  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
+  void                   *clientdata;		/* language specific type data */
+  int                    owndata;		/* flag if the structure owns the clientdata */
+} swig_type_info;
+
+/* Structure to store a type and conversion function used for casting */
+typedef struct swig_cast_info {
+  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
+  swig_converter_func     converter;		/* function to cast the void pointers */
+  struct swig_cast_info  *next;			/* pointer to next cast in linked list */
+  struct swig_cast_info  *prev;			/* pointer to the previous cast */
+} swig_cast_info;
+
+/* Structure used to store module information
+ * Each module generates one structure like this, and the runtime collects
+ * all of these structures and stores them in a circularly linked list.*/
+typedef struct swig_module_info {
+  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
+  size_t                 size;		        /* Number of types in this module */
+  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
+  swig_type_info         **type_initial;	/* Array of initially generated type structures */
+  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
+  void                    *clientdata;		/* Language specific module data */
+} swig_module_info;
+
+/* 
+  Compare two type names skipping the space characters, therefore
+  "char*" == "char *" and "Class<int>" == "Class<int >", etc.
+
+  Return 0 when the two name types are equivalent, as in
+  strncmp, but skipping ' '.
+*/
+SWIGRUNTIME int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+		  const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
+  }
+  return (int)((l1 - f1) - (l2 - f2));
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if not equal, 1 if equal
+*/
+SWIGRUNTIME int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
+*/
+SWIGRUNTIME int
+SWIG_TypeCompare(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+
+/* think of this as a c++ template<> or a scheme macro */
+#define SWIG_TypeCheck_Template(comparison, ty)         \
+  if (ty) {                                             \
+    swig_cast_info *iter = ty->cast;                    \
+    while (iter) {                                      \
+      if (comparison) {                                 \
+        if (iter == ty->cast) return iter;              \
+        /* Move iter to the top of the linked list */   \
+        iter->prev->next = iter->next;                  \
+        if (iter->next)                                 \
+          iter->next->prev = iter->prev;                \
+        iter->next = ty->cast;                          \
+        iter->prev = 0;                                 \
+        if (ty->cast) ty->cast->prev = iter;            \
+        ty->cast = iter;                                \
+        return iter;                                    \
+      }                                                 \
+      iter = iter->next;                                \
+    }                                                   \
+  }                                                     \
+  return 0
+
+/*
+  Check the typename
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheck(const char *c, swig_type_info *ty) {
+  SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);
+}
+
+/* Same as previous function, except strcmp is replaced with a pointer comparison */
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {
+  SWIG_TypeCheck_Template(iter->type == from, into);
+}
+
+/*
+  Cast a pointer up an inheritance hierarchy
+*/
+SWIGRUNTIMEINLINE void *
+SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {
+  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);
+}
+
+/* 
+   Dynamic pointer casting. Down an inheritance hierarchy
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
+  swig_type_info *lastty = ty;
+  if (!ty || !ty->dcast) return ty;
+  while (ty && (ty->dcast)) {
+    ty = (*ty->dcast)(ptr);
+    if (ty) lastty = ty;
+  }
+  return lastty;
+}
+
+/*
+  Return the name associated with this type
+*/
+SWIGRUNTIMEINLINE const char *
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
+
+/*
+  Return the pretty name associated with this type,
+  that is an unmangled type name in a form presentable to the user.
+*/
+SWIGRUNTIME const char *
+SWIG_TypePrettyName(const swig_type_info *type) {
+  /* The "str" field contains the equivalent pretty names of the
+     type, separated by vertical-bar characters.  We choose
+     to print the last name, as it is often (?) the most
+     specific. */
+  if (!type) return NULL;
+  if (type->str != NULL) {
+    const char *last_name = type->str;
+    const char *s;
+    for (s = type->str; *s; s++)
+      if (*s == '|') last_name = s+1;
+    return last_name;
+  }
+  else
+    return type->name;
+}
+
+/* 
+   Set the clientdata field for a type
+*/
+SWIGRUNTIME void
+SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
+  swig_cast_info *cast = ti->cast;
+  /* if (ti->clientdata == clientdata) return; */
+  ti->clientdata = clientdata;
+  
+  while (cast) {
+    if (!cast->converter) {
+      swig_type_info *tc = cast->type;
+      if (!tc->clientdata) {
+	SWIG_TypeClientData(tc, clientdata);
+      }
+    }    
+    cast = cast->next;
+  }
+}
+SWIGRUNTIME void
+SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
+  SWIG_TypeClientData(ti, clientdata);
+  ti->owndata = 1;
+}
+  
+/*
+  Search for a swig_type_info structure only by mangled name
+  Search is a O(log #types)
+  
+  We start searching at module start, and finish searching when start == end.  
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_MangledTypeQueryModule(swig_module_info *start, 
+                            swig_module_info *end, 
+		            const char *name) {
+  swig_module_info *iter = start;
+  do {
+    if (iter->size) {
+      register size_t l = 0;
+      register size_t r = iter->size - 1;
+      do {
+	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
+	register size_t i = (l + r) >> 1; 
+	const char *iname = iter->types[i]->name;
+	if (iname) {
+	  register int compare = strcmp(name, iname);
+	  if (compare == 0) {	    
+	    return iter->types[i];
+	  } else if (compare < 0) {
+	    if (i) {
+	      r = i - 1;
+	    } else {
+	      break;
+	    }
+	  } else if (compare > 0) {
+	    l = i + 1;
+	  }
+	} else {
+	  break; /* should never happen */
+	}
+      } while (l <= r);
+    }
+    iter = iter->next;
+  } while (iter != end);
+  return 0;
+}
+
+/*
+  Search for a swig_type_info structure for either a mangled name or a human readable name.
+  It first searches the mangled names of the types, which is a O(log #types)
+  If a type is not found it then searches the human readable names, which is O(#types).
+  
+  We start searching at module start, and finish searching when start == end.  
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeQueryModule(swig_module_info *start, 
+                     swig_module_info *end, 
+		     const char *name) {
+  /* STEP 1: Search the name field using binary search */
+  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
+  if (ret) {
+    return ret;
+  } else {
+    /* STEP 2: If the type hasn't been found, do a complete search
+       of the str field (the human readable name) */
+    swig_module_info *iter = start;
+    do {
+      register size_t i = 0;
+      for (; i < iter->size; ++i) {
+	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
+	  return iter->types[i];
+      }
+      iter = iter->next;
+    } while (iter != end);
+  }
+  
+  /* neither found a match */
+  return 0;
+}
+
+/* 
+   Pack binary data into a string
+*/
+SWIGRUNTIME char *
+SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static const char hex[17] = "0123456789abcdef";
+  register const unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    register unsigned char uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+
+/* 
+   Unpack binary data from a string
+*/
+SWIGRUNTIME const char *
+SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  register unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu = u + sz;
+  for (; u != eu; ++u) {
+    register char d = *(c++);
+    register unsigned char uu;
+    if ((d >= '0') && (d <= '9'))
+      uu = ((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = ((d - ('a'-10)) << 4);
+    else 
+      return (char *) 0;
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (d - ('a'-10));
+    else 
+      return (char *) 0;
+    *u = uu;
+  }
+  return c;
+}
+
+/* 
+   Pack 'void *' into a string buffer.
+*/
+SWIGRUNTIME char *
+SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+  char *r = buff;
+  if ((2*sizeof(void *) + 2) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,&ptr,sizeof(void *));
+  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
+  strcpy(r,name);
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      *ptr = (void *) 0;
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sizeof(void *));
+}
+
+SWIGRUNTIME char *
+SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+  char *r = buff;
+  size_t lname = (name ? strlen(name) : 0);
+  if ((2*sz + 2 + lname) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  if (lname) {
+    strncpy(r,name,lname+1);
+  } else {
+    *r = 0;
+  }
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      memset(ptr,0,sz);
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sz);
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/trunk/Lib/swigwarnings.swg b/trunk/Lib/swigwarnings.swg
new file mode 100644
index 0000000..21498eb
--- /dev/null
+++ b/trunk/Lib/swigwarnings.swg
@@ -0,0 +1,128 @@
+/*
+  Include the internal swig macro codes. These macros correspond to
+  the one found in Source/Include/swigwarn.h plus the 'SWIG' prefix.
+  
+  For example, in the include file 'swigwarn.h' you will find
+
+    #define WARN_TYPEMAP_CHARLEAK ...
+
+  and in the 'swigwarn.swg' interface, you will see
+
+    %define SWIGWARN_TYPEMAP_CHARLEAK ...
+
+  This code can be used in warning filters as follows:
+
+    %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK);
+
+  Warnings messages used in typemaps. Message names will be the same
+  as those in Lib/swigwarn.swg but with the suffix _MSG.
+   
+  For example, for the code SWIGWARN_TYPEMAP_CHARLEAK, once you use
+
+    %typemapmsg(CHARLEAK,<msg>);
+
+  you use the message in your typemap as
+
+    %typemap(varin,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) char * 
+
+  while you suppress the warning using
+
+    %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK);
+
+  as described above.
+*/
+
+/* -----------------------------------------------------------------------------
+ * SWIG warning codes
+ * ----------------------------------------------------------------------------- */
+
+%include <swigwarn.swg>
+
+/* -----------------------------------------------------------------------------
+ * Auxiliary macros
+ * ----------------------------------------------------------------------------- */
+
+/* Macro to define warning messages */
+#define %_warningmsg(Val, Msg...) `Val`":"Msg 
+#define %warningmsg(Val, Msg...) %_warningmsg(Val, Msg)
+
+/* -----------------------------------------------------------------------------
+ *  Typemap related warning messages
+ * ----------------------------------------------------------------------------- */
+
+%define SWIGWARN_TYPEMAP_CHARLEAK_MSG         "451:Setting a const char * variable may leak memory." %enddef
+%define SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG     "454:Setting a pointer/reference variable may leak memory." %enddef
+%define SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG    "470:Thread/reentrant unsafe wrapping, consider returning by value instead." %enddef
+%define SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG  "473:Returning a pointer or reference in a director method is not recommended." %enddef
+
+/* -----------------------------------------------------------------------------
+ * Operator related warning messages 
+ * ----------------------------------------------------------------------------- */
+
+%define SWIGWARN_IGNORE_OPERATOR_NEW_MSG        "350:operator new ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_DELETE_MSG     "351:operator delete ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_PLUS_MSG       "352:operator+ ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MINUS_MSG      "353:operator- ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MUL_MSG        "354:operator* ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_DIV_MSG        "355:operator/ ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MOD_MSG        "356:operator% ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_XOR_MSG        "357:operator^ ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_AND_MSG        "358:operator& ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_OR_MSG         "359:operator| ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_NOT_MSG        "360:operator~ ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LNOT_MSG       "361:operator! ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_EQ_MSG         "362:operator= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LT_MSG         "363:operator< ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_GT_MSG         "364:operator> ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_PLUSEQ_MSG     "365:operator+= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MINUSEQ_MSG    "366:operator-= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MULEQ_MSG      "367:operator*= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_DIVEQ_MSG      "368:operator/= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MODEQ_MSG      "369:operator%= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_XOREQ_MSG      "370:operator^= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_ANDEQ_MSG      "371:operator&= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_OREQ_MSG       "372:operator|= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LSHIFT_MSG     "373:operator<< ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_RSHIFT_MSG     "374:operator>> ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LSHIFTEQ_MSG   "375:operator<<= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_RSHIFTEQ_MSG   "376:operator>>= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_EQUALTO_MSG    "377:operator== ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_NOTEQUAL_MSG   "378:operator!= ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LTEQUAL_MSG    "379:operator<= ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_GTEQUAL_MSG    "380:operator>= ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LAND_MSG       "381:operator&& ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_LOR_MSG        "382:operator|| ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_PLUSPLUS_MSG   "383:operator++ ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_MINUSMINUS_MSG "384:operator-- ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_COMMA_MSG      "385:operator-- ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_ARROWSTAR_MSG  "386:operator->* ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_ARROW_MSG      "387:operator-> ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_CALL_MSG       "388:operator() ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_INDEX_MSG      "389:operator[] ignored (consider using %%extend)"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_UPLUS_MSG      "390:operator+ ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_UMINUS_MSG     "391:operator- ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_UMUL_MSG       "392:operator* ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_UAND_MSG       "393:operator& ignored" %enddef
+%define SWIGWARN_IGNORE_OPERATOR_NEWARR_MSG     "394:operator new[] ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_DELARR_MSG     "395:operator delete[] ignored"  %enddef
+%define SWIGWARN_IGNORE_OPERATOR_REF_MSG        "396:operator*() ignored" %enddef
+
+#define %ignoreoperator(Oper) %ignorewarn(SWIGWARN_IGNORE_OPERATOR_##Oper##_MSG)
+
+/* -----------------------------------------------------------------------------
+ * Macros for keyword and built-in names 
+ * ----------------------------------------------------------------------------- */
+
+#define %keywordwarn(msg...) %namewarn(%warningmsg(SWIGWARN_PARSE_KEYWORD, msg)) 
+#define %builtinwarn(msg...) %namewarn(%warningmsg(SWIGWARN_PARSE_BUILTIN_NAME, msg), %$isfunction)
+
+
+/* -----------------------------------------------------------------------------
+ * Warning filter feature
+ * ----------------------------------------------------------------------------- */
+
+#define %_warnfilter(filter...) %feature("warnfilter",`filter`)
+#define %warnfilter(filter...) %_warnfilter(filter)
+
+
+
diff --git a/trunk/Lib/tcl/Makefile.in b/trunk/Lib/tcl/Makefile.in
new file mode 100644
index 0000000..523349b
--- /dev/null
+++ b/trunk/Lib/tcl/Makefile.in
@@ -0,0 +1,133 @@
+# ---------------------------------------------------------------
+# SWIG Tcl/Tk Makefile
+# 
+# This file can be used to build various Tcl extensions with SWIG.
+# By default this file is set up for dynamic loading, but it can
+# be easily customized for static extensions by modifying various
+# portions of the file.  
+#
+#        SRCS       = C source files
+#        CXXSRCS    = C++ source files
+#        OBJCSRCS   = Objective-C source files
+#        OBJS       = Additional .o files (compiled previously)
+#        INTERFACE  = SWIG interface file
+#        TARGET     = Name of target module or executable
+#
+# Many portions of this file were created by the SWIG configure
+# script and should already reflect your machine. However, you
+# may need to modify the Makefile to reflect your specific
+# application.
+#----------------------------------------------------------------
+
+SRCS          = 
+CXXSRCS       = 
+OBJCSRCS      = 
+OBJS          = 
+INTERFACE     = 
+WRAPFILE      = $(INTERFACE:.i=_wrap.c)
+WRAPOBJ       = $(INTERFACE:.i=_wrap.o)
+TARGET        = module@SO@ # Use this kind of target for dynamic loading
+#TARGET        = my_tclsh  # Use this target for static linking
+
+prefix        = @prefix@
+exec_prefix   = @exec_prefix@
+
+CC            = @CC@
+CXX           = @CXX@
+OBJC          = @CC@ -Wno-import # -Wno-import needed for gcc 
+CFLAGS        = 
+INCLUDES      =
+LIBS          =
+
+# SWIG Options
+#     SWIG      = location of the SWIG executable
+#     SWIGOPT   = SWIG compiler options
+#     SWIGCC    = Compiler used to compile the wrapper file
+
+SWIG          = $(exec_prefix)/bin/swig 
+SWIGOPT       = -tcl # use -tcl8 for Tcl 8.0
+SWIGCC        = $(CC) 
+
+# SWIG Library files.  Uncomment one of these for rebuilding tclsh or wish
+#SWIGLIB       = -ltclsh.i
+#SWIGLIB       = -lwish.i
+
+# Rules for creating .o files from source.
+
+COBJS         = $(SRCS:.c=.o)
+CXXOBJS       = $(CXXSRCS:.cxx=.o)
+OBJCOBJS      = $(OBJCSRCS:.m=.o)
+ALLOBJS       = $(COBJS) $(CXXOBJS) $(OBJCOBJS) $(OBJS)
+
+# Command that will be used to build the final extension.
+BUILD         = $(SWIGCC)
+
+# Uncomment the following if you are using dynamic loading
+CCSHARED      = @CCSHARED@
+BUILD         = @LDSHARED@
+
+# Uncomment the following if you are using dynamic loading with C++ and
+# need to provide additional link libraries (this is not always required).
+
+#DLL_LIBS      = -L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \
+             -L/usr/local/lib -lg++ -lstdc++ -lgcc
+
+# X11 installation (needed to rebuild Tk extensions)
+
+XLIB          = @XLIBSW@
+XINCLUDE      = @XINCLUDES@
+
+# Tcl installation (where is Tcl/Tk located)
+
+TCL_INCLUDE   = @TCLINCLUDE@
+TCL_LIB       = @TCLLIB@
+
+# Build libraries (needed for static builds)
+
+LIBM          = @LIBM@
+LIBC          = @LIBC@
+SYSLIBS       = $(LIBM) $(LIBC) @LIBS@
+
+# Build options (uncomment only one these)
+
+BUILD_LIBS    = $(LIBS) # Dynamic loading
+#BUILD_LIBS    = $(TCL_LIB) -ltcl $(LIBS) $(SYSLIBS) # tclsh  
+#BUILD_LIBS    = $(TCL_LIB) -ltk -ltcl $(XLIB) $(LIBS) $(SYSLIBS) # wish
+
+# Compilation rules for non-SWIG components
+
+.SUFFIXES: .c .cxx .m
+
+.c.o:
+	$(CC) $(CCSHARED) $(CFLAGS) $(INCLUDES) -c $<
+
+.cxx.o:
+	$(CXX) $(CCSHARED) $(CXXFLAGS) $(INCLUDES) -c $<
+
+.m.o:
+	$(OBJC) $(CCSHARED) $(CFLAGS) $(INCLUDES) -c $<
+
+
+# ----------------------------------------------------------------------
+# Rules for building the extension
+# ----------------------------------------------------------------------
+
+all: $(TARGET)
+
+# Convert the wrapper file into an object file
+
+$(WRAPOBJ) : $(WRAPFILE)
+	$(SWIGCC) -c $(CCSHARED) $(CFLAGS) $(WRAPFILE) $(INCLUDES) $(TCL_INCLUDE) 
+
+$(WRAPFILE) : $(INTERFACE)
+	$(SWIG) $(SWIGOPT) -o $(WRAPFILE) $(SWIGLIB) $(INTERFACE)
+
+$(TARGET): $(WRAPOBJ) $(ALLOBJS)
+	$(BUILD) $(WRAPOBJ) $(ALLOBJS) $(BUILD_LIBS) -o $(TARGET)
+
+clean:
+	rm -f $(COBJS) $(CXXOBJS) $(OBJCOBJS) $(WRAPOBJ) $(WRAPFILE) $(TARGET)
+
+
+
+
diff --git a/trunk/Lib/tcl/attribute.i b/trunk/Lib/tcl/attribute.i
new file mode 100644
index 0000000..779716c
--- /dev/null
+++ b/trunk/Lib/tcl/attribute.i
@@ -0,0 +1 @@
+%include <typemaps/attribute.swg>
diff --git a/trunk/Lib/tcl/carrays.i b/trunk/Lib/tcl/carrays.i
new file mode 100644
index 0000000..0236672
--- /dev/null
+++ b/trunk/Lib/tcl/carrays.i
@@ -0,0 +1,4 @@
+%include <typemaps/carrays.swg>
+
+
+
diff --git a/trunk/Lib/tcl/cdata.i b/trunk/Lib/tcl/cdata.i
new file mode 100644
index 0000000..3679659
--- /dev/null
+++ b/trunk/Lib/tcl/cdata.i
@@ -0,0 +1 @@
+%include <typemaps/cdata.swg>
diff --git a/trunk/Lib/tcl/cmalloc.i b/trunk/Lib/tcl/cmalloc.i
new file mode 100644
index 0000000..248f06b
--- /dev/null
+++ b/trunk/Lib/tcl/cmalloc.i
@@ -0,0 +1 @@
+%include <typemaps/cmalloc.swg>
diff --git a/trunk/Lib/tcl/cni.i b/trunk/Lib/tcl/cni.i
new file mode 100644
index 0000000..10a1403
--- /dev/null
+++ b/trunk/Lib/tcl/cni.i
@@ -0,0 +1,2 @@
+%include <gcj/cni.i>
+%include <jstring.i>
diff --git a/trunk/Lib/tcl/cpointer.i b/trunk/Lib/tcl/cpointer.i
new file mode 100644
index 0000000..d824792
--- /dev/null
+++ b/trunk/Lib/tcl/cpointer.i
@@ -0,0 +1 @@
+%include <typemaps/cpointer.swg>
diff --git a/trunk/Lib/tcl/cstring.i b/trunk/Lib/tcl/cstring.i
new file mode 100644
index 0000000..ede9c59
--- /dev/null
+++ b/trunk/Lib/tcl/cstring.i
@@ -0,0 +1 @@
+%include <typemaps/cstring.swg>
diff --git a/trunk/Lib/tcl/cwstring.i b/trunk/Lib/tcl/cwstring.i
new file mode 100644
index 0000000..b17ca76
--- /dev/null
+++ b/trunk/Lib/tcl/cwstring.i
@@ -0,0 +1,2 @@
+%include <tclwstrings.swg>
+%include <typemaps/cwstring.swg>
diff --git a/trunk/Lib/tcl/exception.i b/trunk/Lib/tcl/exception.i
new file mode 100644
index 0000000..4d22797
--- /dev/null
+++ b/trunk/Lib/tcl/exception.i
@@ -0,0 +1,6 @@
+%include <typemaps/exception.swg>
+
+
+%insert("runtime") {
+  %define_as(SWIG_exception(code, msg), %block(%error(code, msg); return TCL_ERROR;))
+}
diff --git a/trunk/Lib/tcl/factory.i b/trunk/Lib/tcl/factory.i
new file mode 100644
index 0000000..46a0a87
--- /dev/null
+++ b/trunk/Lib/tcl/factory.i
@@ -0,0 +1 @@
+%include <typemaps/factory.swg>
diff --git a/trunk/Lib/tcl/jstring.i b/trunk/Lib/tcl/jstring.i
new file mode 100644
index 0000000..7fb7b89
--- /dev/null
+++ b/trunk/Lib/tcl/jstring.i
@@ -0,0 +1,42 @@
+%include <typemaps/valtypes.swg>
+
+%fragment(SWIG_AsVal_frag(jstring),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(jstring)(Tcl_Obj * obj, jstring *val)
+{
+  int len = 0;
+  const char *cstr = Tcl_GetStringFromObj(obj, &len);
+  if (!cstr || (strcmp(cstr,"NULL") == 0)) {
+    if (val) *val = 0;
+    return SWIG_OK;
+  } else {
+    int len = 0;
+    const Tcl_UniChar *ucstr = Tcl_GetUnicodeFromObj(obj,&len);
+    if (val) {
+      *val = JvNewString((const jchar*)ucstr, len);
+    }
+  }
+  
+  return SWIG_NEWOBJ;
+}
+}
+
+%fragment(SWIG_From_frag(jstring),"header") {
+SWIGINTERNINLINE Tcl_Obj *
+SWIG_From_dec(jstring)(jstring val)
+{
+  if (!val) {
+    return Tcl_NewStringObj("NULL",-1);
+  } else {
+    return Tcl_NewUnicodeObj((Tcl_UniChar *)JvGetStringChars(val),JvGetStringUTFLength(val));
+  }
+}
+}
+
+%typemaps_asvalfrom(%checkcode(STRING),
+		    %arg(SWIG_AsVal(jstring)), 
+		    %arg(SWIG_From(jstring)), 
+		    %arg(SWIG_AsVal_frag(jstring)), 
+		    %arg(SWIG_From_frag(jstring)), 
+		    java::lang::String *);
+
diff --git a/trunk/Lib/tcl/mactclinit.c b/trunk/Lib/tcl/mactclinit.c
new file mode 100644
index 0000000..5dcf8e7
--- /dev/null
+++ b/trunk/Lib/tcl/mactclinit.c
@@ -0,0 +1,93 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * mactclinit.c
+ * ----------------------------------------------------------------------------- */
+
+/* 
+ * tclMacAppInit.c --
+ *
+ *	Provides a version of the Tcl_AppInit procedure for the example shell.
+ *
+ * Copyright (c) 1993-1994 Lockheed Missle & Space Company, AI Center
+ * Copyright (c) 1995-1997 Sun Microsystems, Inc.
+ *
+ * See the file "license.terms" for information on usage and redistribution
+ * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ *
+ * SCCS: @(#) tclMacAppInit.c 1.17 97/01/21 18:13:34
+ */
+
+#include "tcl.h"
+#include "tclInt.h"
+#include "tclMacInt.h"
+
+#if defined(THINK_C)
+#   include <console.h>
+#elif defined(__MWERKS__)
+#   include <SIOUX.h>
+short InstallConsole _ANSI_ARGS_((short fd));
+#endif
+
+
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * MacintoshInit --
+ *
+ *	This procedure calls initalization routines to set up a simple
+ *	console on a Macintosh.  This is necessary as the Mac doesn't
+ *	have a stdout & stderr by default.
+ *
+ * Results:
+ *	Returns TCL_OK if everything went fine.  If it didn't the 
+ *	application should probably fail.
+ *
+ * Side effects:
+ *	Inits the appropiate console package.
+ *
+ *----------------------------------------------------------------------
+ */
+
+#ifdef __cplusplus
+extern "C"
+#endif
+extern int
+MacintoshInit()
+{
+#if defined(THINK_C)
+
+    /* Set options for Think C console package */
+    /* The console package calls the Mac init calls */
+    console_options.pause_atexit = 0;
+    console_options.title = "\pTcl Interpreter";
+		
+#elif defined(__MWERKS__)
+
+    /* Set options for CodeWarrior SIOUX package */
+    SIOUXSettings.autocloseonquit = true;
+    SIOUXSettings.showstatusline = true;
+    SIOUXSettings.asktosaveonclose = false;
+    InstallConsole(0);
+    SIOUXSetTitle("\pTcl Interpreter");
+		
+#elif defined(applec)
+
+    /* Init packages used by MPW SIOW package */
+    InitGraf((Ptr)&qd.thePort);
+    InitFonts();
+    InitWindows();
+    InitMenus();
+    TEInit();
+    InitDialogs(nil);
+    InitCursor();
+		
+#endif
+
+    TclMacSetEventProc((TclMacConvertEventPtr) SIOUXHandleOneEvent);
+    
+    /* No problems with initialization */
+    return TCL_OK;
+}
diff --git a/trunk/Lib/tcl/mactkinit.c b/trunk/Lib/tcl/mactkinit.c
new file mode 100644
index 0000000..bfe7402
--- /dev/null
+++ b/trunk/Lib/tcl/mactkinit.c
@@ -0,0 +1,236 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * mactkinit.c
+ *
+ * This is a support file needed to build a new version of Wish.
+ * Normally, this capability is found in TkAppInit.c, but this creates
+ * tons of namespace problems for many applications.
+ * ----------------------------------------------------------------------------- */
+   
+#include <Gestalt.h>
+#include <ToolUtils.h>
+#include <Fonts.h>
+#include <Dialogs.h>
+#include <SegLoad.h>
+#include <Traps.h>
+
+#include "tk.h"
+#include "tkInt.h"
+#include "tkMacInt.h"
+
+typedef int (*TclMacConvertEventPtr) _ANSI_ARGS_((EventRecord *eventPtr));
+Tcl_Interp *gStdoutInterp = NULL;
+
+void 	TclMacSetEventProc _ANSI_ARGS_((TclMacConvertEventPtr procPtr));
+int 	TkMacConvertEvent _ANSI_ARGS_((EventRecord *eventPtr));
+
+/*
+ * Prototypes for functions the ANSI library needs to link against.
+ */
+short			InstallConsole _ANSI_ARGS_((short fd));
+void			RemoveConsole _ANSI_ARGS_((void));
+long			WriteCharsToConsole _ANSI_ARGS_((char *buff, long n));
+long			ReadCharsFromConsole _ANSI_ARGS_((char *buff, long n));
+char *			__ttyname _ANSI_ARGS_((long fildes));
+short			SIOUXHandleOneEvent _ANSI_ARGS_((EventRecord *event));
+
+/*
+ * Forward declarations for procedures defined later in this file:
+ */
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * MacintoshInit --
+ *
+ *	This procedure calls Mac specific initilization calls.  Most of
+ *	these calls must be made as soon as possible in the startup
+ *	process.
+ *
+ * Results:
+ *	Returns TCL_OK if everything went fine.  If it didn't the 
+ *	application should probably fail.
+ *
+ * Side effects:
+ *	Inits the application.
+ *
+ *----------------------------------------------------------------------
+ */
+
+int
+MacintoshInit()
+{
+    int i;
+    long result, mask = 0x0700; 		/* mask = system 7.x */
+
+    /*
+     * Tk needs us to set the qd pointer it uses.  This is needed
+     * so Tk doesn't have to assume the availablity of the qd global
+     * variable.  Which in turn allows Tk to be used in code resources.
+     */
+    tcl_macQdPtr = &qd;
+
+    InitGraf(&tcl_macQdPtr->thePort);
+    InitFonts();
+    InitWindows();
+    InitMenus();
+    InitDialogs((long) NULL);		
+    InitCursor();
+
+    /*
+     * Make sure we are running on system 7 or higher
+     */
+     
+    if ((NGetTrapAddress(_Gestalt, ToolTrap) == 
+    	    NGetTrapAddress(_Unimplemented, ToolTrap))
+    	    || (((Gestalt(gestaltSystemVersion, &result) != noErr)
+	    || (mask != (result & mask))))) {
+	panic("Tcl/Tk requires System 7 or higher.");
+    }
+
+    /*
+     * Make sure we have color quick draw 
+     * (this means we can't run on 68000 macs)
+     */
+     
+    if (((Gestalt(gestaltQuickdrawVersion, &result) != noErr)
+	    || (result < gestalt32BitQD13))) {
+	panic("Tk requires Color QuickDraw.");
+    }
+
+    
+    FlushEvents(everyEvent, 0);
+    SetEventMask(everyEvent);
+
+    /*
+     * Set up stack & heap sizes
+     */
+    /* TODO: stack size
+       size = StackSpace();
+       SetAppLimit(GetAppLimit() - 8192);
+     */
+    MaxApplZone();
+    for (i = 0; i < 4; i++) {
+	(void) MoreMasters();
+    }
+
+    TclMacSetEventProc(TkMacConvertEvent);
+    TkConsoleCreate();
+
+    return TCL_OK;
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * SetupMainInterp --
+ *
+ *	This procedure calls initalization routines require a Tcl 
+ *	interp as an argument.  This call effectively makes the passed
+ *	iterpreter the "main" interpreter for the application.
+ *
+ * Results:
+ *	Returns TCL_OK if everything went fine.  If it didn't the 
+ *	application should probably fail.
+ *
+ * Side effects:
+ *	More initilization.
+ *
+ *----------------------------------------------------------------------
+ */
+
+int
+SetupMainInterp(
+    Tcl_Interp *interp)
+{
+    /*
+     * Initialize the console only if we are running as an interactive
+     * application.
+     */
+
+    TkMacInitAppleEvents(interp);
+    TkMacInitMenus(interp);
+
+    if (strcmp(Tcl_GetVar(interp, "tcl_interactive", TCL_GLOBAL_ONLY), "1")
+	    == 0) {
+	if (TkConsoleInit(interp) == TCL_ERROR) {
+	    goto error;
+	}
+    }
+
+    /*
+     * Attach the global interpreter to tk's expected global console
+     */
+
+    gStdoutInterp = interp;
+
+    return TCL_OK;
+
+error:
+    panic(interp->result);
+    return TCL_ERROR;
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * InstallConsole, RemoveConsole, etc. --
+ *
+ *	The following functions provide the UI for the console package.
+ *	Users wishing to replace SIOUX with their own console package 
+ *	need only provide the four functions below in a library.
+ *
+ * Results:
+ *	See SIOUX documentation for details.
+ *
+ * Side effects:
+ *	See SIOUX documentation for details.
+ *
+ *----------------------------------------------------------------------
+ */
+
+short 
+InstallConsole(short fd)
+{
+#pragma unused (fd)
+
+	return 0;
+}
+
+void 
+RemoveConsole(void)
+{
+}
+
+long 
+WriteCharsToConsole(char *buffer, long n)
+{
+    TkConsolePrint(gStdoutInterp, TCL_STDOUT, buffer, n);
+    return n;
+}
+
+long 
+ReadCharsFromConsole(char *buffer, long n)
+{
+    return 0;
+}
+
+extern char *
+__ttyname(long fildes)
+{
+    static char *devicename = "null device";
+
+    if (fildes >= 0 && fildes <= 2) {
+	return (devicename);
+    }
+    
+    return (0L);
+}
+
+short
+SIOUXHandleOneEvent(EventRecord *event)
+{
+    return 0;
+}
diff --git a/trunk/Lib/tcl/std_common.i b/trunk/Lib/tcl/std_common.i
new file mode 100644
index 0000000..3a6f470
--- /dev/null
+++ b/trunk/Lib/tcl/std_common.i
@@ -0,0 +1,20 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_common.i
+ *
+ * SWIG typemaps for STL - common utilities
+ * ----------------------------------------------------------------------------- */
+
+%include <std/std_except.i>
+
+%types(std::size_t);
+%apply size_t { std::size_t };
+%apply const unsigned long& { const std::size_t& };
+
+%types(std::ptrdiff_t);
+%apply long { std::ptrdiff_t };
+%apply const long& { const std::ptrdiff_t& };
+
+
diff --git a/trunk/Lib/tcl/std_deque.i b/trunk/Lib/tcl/std_deque.i
new file mode 100644
index 0000000..cb98f6c
--- /dev/null
+++ b/trunk/Lib/tcl/std_deque.i
@@ -0,0 +1 @@
+%include <std/_std_deque.i>
diff --git a/trunk/Lib/tcl/std_except.i b/trunk/Lib/tcl/std_except.i
new file mode 100644
index 0000000..af98428
--- /dev/null
+++ b/trunk/Lib/tcl/std_except.i
@@ -0,0 +1 @@
+%include <typemaps/std_except.swg>
diff --git a/trunk/Lib/tcl/std_map.i b/trunk/Lib/tcl/std_map.i
new file mode 100644
index 0000000..006a62e
--- /dev/null
+++ b/trunk/Lib/tcl/std_map.i
@@ -0,0 +1,173 @@
+//
+// SWIG typemaps for std::map
+// Luigi Ballabio
+// Jan. 2003
+//
+// Common implementation
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::map
+// ------------------------------------------------------------------------
+
+%{
+#include <map>
+#include <algorithm>
+#include <stdexcept>
+%}
+
+// exported class
+
+namespace std {
+
+    template<class K, class T> class map {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO)
+
+    template<class T> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T& get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, const T& x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO)
+    template<class K> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(const K& key, T x) {
+                (*self)[key] = x;
+            }
+            void del(const K& key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(const K& key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    %define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO,
+                                       T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO)
+    template<> class map<K,T> {
+        // add typemaps here
+      public:
+        map();
+        map(const map<K,T> &);
+        
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %extend {
+            T get(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    return i->second;
+                else
+                    throw std::out_of_range("key not found");
+            }
+            void set(K key, T x) {
+                (*self)[key] = x;
+            }
+            void del(K key) throw (std::out_of_range) {
+                std::map<K,T >::iterator i = self->find(key);
+                if (i != self->end())
+                    self->erase(i);
+                else
+                    throw std::out_of_range("key not found");
+            }
+            bool has_key(K key) {
+                std::map<K,T >::iterator i = self->find(key);
+                return i != self->end();
+            }
+        }
+    };
+    %enddef
+
+    // add specializations here
+
+}
diff --git a/trunk/Lib/tcl/std_pair.i b/trunk/Lib/tcl/std_pair.i
new file mode 100644
index 0000000..52e9667
--- /dev/null
+++ b/trunk/Lib/tcl/std_pair.i
@@ -0,0 +1,37 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_pair.i
+ *
+ * Typemaps for std::pair
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+%include <exception.i>
+
+// ------------------------------------------------------------------------
+// std::pair
+// ------------------------------------------------------------------------
+
+%{
+#include <utility>
+%}
+
+namespace std {
+
+  template<class T, class U> struct pair {
+
+    pair();
+    pair(T first, U second);
+    pair(const pair& p);
+
+    template <class U1, class U2> pair(const pair<U1, U2> &p);
+
+    T first;
+    U second;
+  };
+
+  // add specializations here
+
+}
diff --git a/trunk/Lib/tcl/std_string.i b/trunk/Lib/tcl/std_string.i
new file mode 100644
index 0000000..5b31b28
--- /dev/null
+++ b/trunk/Lib/tcl/std_string.i
@@ -0,0 +1,2 @@
+%include <typemaps/std_string.swg>
+
diff --git a/trunk/Lib/tcl/std_vector.i b/trunk/Lib/tcl/std_vector.i
new file mode 100644
index 0000000..d913f00
--- /dev/null
+++ b/trunk/Lib/tcl/std_vector.i
@@ -0,0 +1,422 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * std_vector.i
+ * ----------------------------------------------------------------------------- */
+
+%include <std_common.i>
+
+// ------------------------------------------------------------------------
+// std::vector
+// 
+// The aim of all that follows would be to integrate std::vector with 
+// Tcl as much as possible, namely, to allow the user to pass and 
+// be returned Tcl lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+// 
+//   -- f(std::vector<T>), f(const std::vector<T>&), f(const std::vector<T>*):
+//      the parameter being read-only, either a Tcl list or a
+//      previously wrapped std::vector<T> can be passed.
+//   -- f(std::vector<T>&), f(std::vector<T>*):
+//      the parameter must be modified; therefore, only a wrapped std::vector
+//      can be passed.
+//   -- std::vector<T> f():
+//      the vector is returned by copy; therefore, a Tcl list of T:s 
+//      is returned which is most easily used in other Tcl functions procs
+//   -- std::vector<T>& f(), std::vector<T>* f(), const std::vector<T>& f(),
+//      const std::vector<T>* f():
+//      the vector is returned by reference; therefore, a wrapped std::vector
+//      is returned
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+#include <string>
+
+Tcl_Obj* SwigString_FromString(const std::string &s) {
+    return Tcl_NewStringObj(s.data(), (int)s.length());
+}
+
+int Tcl_GetBoolFromObj(Tcl_Interp *interp, Tcl_Obj *o, bool *val) {
+  int v;
+  int res = Tcl_GetBooleanFromObj(interp, o, &v);
+  if (res == TCL_OK) {
+    *val = v ? true : false;
+  }
+  return res;  
+}
+ 
+int SwigString_AsString(Tcl_Interp *interp, Tcl_Obj *o, std::string *val) {
+    int len;
+    const char* temp = Tcl_GetStringFromObj(o, &len);
+    if (temp == NULL)
+        return TCL_ERROR;
+    val->assign(temp, len);
+    return TCL_OK;
+}
+
+// behaviour of this is such as the real Tcl_GetIntFromObj
+template <typename Type>
+int SwigInt_As(Tcl_Interp *interp, Tcl_Obj *o, Type *val) {
+    int temp_val, return_val;
+    return_val = Tcl_GetIntFromObj(interp, o, &temp_val);
+    *val = (Type) temp_val;
+    return return_val;
+}
+
+// behaviour of this is such as the real Tcl_GetDoubleFromObj
+template <typename Type>
+int SwigDouble_As(Tcl_Interp *interp, Tcl_Obj *o, Type *val) {
+    int return_val;
+    double temp_val;
+    return_val = Tcl_GetDoubleFromObj(interp, o, &temp_val);
+    *val = (Type) temp_val;
+    return return_val;
+}
+
+%}
+
+// exported class
+
+namespace std {
+    
+    template<class T> class vector {
+        %typemap(in) vector<T> (std::vector<T> *v) {
+            Tcl_Obj **listobjv;
+            int       nitems;
+            int       i;
+            T*        temp;
+
+            if (SWIG_ConvertPtr($input, (void **) &v, \
+                                $&1_descriptor, 0) == 0){
+                $1 = *v;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, \
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    return TCL_ERROR;
+                $1 = std::vector<T>();
+                for (i = 0; i < nitems; i++) {
+                    if ((SWIG_ConvertPtr(listobjv[i],(void **) &temp,
+                                         $descriptor(T *),0)) != 0) {
+                        char message[] = 
+                            "list of " #T " expected";
+                        Tcl_SetResult(interp, message, TCL_VOLATILE);
+                        return TCL_ERROR;
+                    }
+                    $1.push_back(*temp);
+                } 
+            }
+        }
+
+        %typemap(in) const vector<T>* (std::vector<T> *v, std::vector<T> w),
+                     const vector<T>& (std::vector<T> *v, std::vector<T> w) {
+            Tcl_Obj **listobjv;
+            int       nitems;
+            int       i;
+            T*        temp;
+
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $&1_descriptor, 0) == 0) {
+                $1 = v;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    return TCL_ERROR;
+                w = std::vector<T>();
+                for (i = 0; i < nitems; i++) {
+                    if ((SWIG_ConvertPtr(listobjv[i],(void **) &temp,
+                                         $descriptor(T *),0)) != 0) {
+                        char message[] = 
+                            "list of " #T " expected";
+                        Tcl_SetResult(interp, message, TCL_VOLATILE);
+                        return TCL_ERROR;
+                    }
+                    w.push_back(*temp);
+                } 
+                $1 = &w;
+            }
+        }
+
+        %typemap(out) vector<T> {
+            for (unsigned int i=0; i<$1.size(); i++) {
+                T* ptr = new T((($1_type &)$1)[i]);
+                Tcl_ListObjAppendElement(interp, $result, \
+                                         SWIG_NewInstanceObj(ptr, 
+                                                             $descriptor(T *), 
+                                                             0));
+            }
+        }
+
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            Tcl_Obj **listobjv;
+            int       nitems;
+            T*        temp;
+            std::vector<T> *v;
+            
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $&1_descriptor, 0) == 0) {
+                /* wrapped vector */
+                $1 = 1;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    $1 = 0;
+                else
+                    if (nitems == 0)
+                        $1 = 1;
+                //check the first value to see if it is of correct type
+                    else if ((SWIG_ConvertPtr(listobjv[0],
+                                              (void **) &temp, 
+                                              $descriptor(T *),0)) != 0)
+                        $1 = 0;
+                    else
+                        $1 = 1;
+            }
+        }
+        
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+                                          const vector<T>* {
+            Tcl_Obj **listobjv;
+            int       nitems;
+            T*         temp;
+            std::vector<T> *v;
+
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $1_descriptor, 0) == 0){
+                /* wrapped vector */
+                $1 = 1;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    $1 = 0;
+                else
+                    if (nitems == 0)
+                        $1 = 1;
+                //check the first value to see if it is of correct type
+                    else if ((SWIG_ConvertPtr(listobjv[0],
+                                              (void **) &temp,
+                                              $descriptor(T *),0)) != 0)
+                        $1 = 0;
+                    else
+                        $1 = 1;
+            }
+        }
+      
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(const T& x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T& get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i<0) i += size;
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, const T& x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i<0) i+= size;
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+
+
+    // specializations for built-ins
+
+    %define specialize_std_vector(T, CONVERT_FROM, CONVERT_TO)
+    template<> class vector<T> {
+
+        %typemap(in) vector<T> (std::vector<T> *v){
+            Tcl_Obj **listobjv;
+            int       nitems;
+            int       i;
+            T         temp;
+
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $&1_descriptor, 0) == 0) {
+                $1 = *v;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    return TCL_ERROR;					      
+                $1 = std::vector<T>();
+                for (i = 0; i < nitems; i++) {
+                    if (CONVERT_FROM(interp, listobjv[i], &temp) == TCL_ERROR)
+                        return TCL_ERROR;
+                    $1.push_back(temp);
+                } 
+            }
+        }
+      
+        %typemap(in) const vector<T>& (std::vector<T> *v,std::vector<T> w),
+                     const vector<T>* (std::vector<T> *v,std::vector<T> w) {
+            Tcl_Obj **listobjv;
+            int       nitems;
+            int       i;
+            T         temp;
+
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $1_descriptor, 0) == 0) {
+                $1 = v;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    return TCL_ERROR;
+                w = std::vector<T>();
+                for (i = 0; i < nitems; i++) {
+                    if (CONVERT_FROM(interp, listobjv[i], &temp) == TCL_ERROR)
+                        return TCL_ERROR;
+                    w.push_back(temp);
+                } 
+                $1 = &w;
+            }
+        }
+
+        %typemap(out) vector<T> {
+            for (unsigned int i=0; i<$1.size(); i++) {
+                Tcl_ListObjAppendElement(interp, $result, \
+                                         CONVERT_TO((($1_type &)$1)[i]));
+            }
+        }
+       
+        %typecheck(SWIG_TYPECHECK_VECTOR) vector<T> {
+            Tcl_Obj **listobjv;
+            int       nitems;
+            T         temp;
+            std::vector<T> *v;
+
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $&1_descriptor, 0) == 0){
+                /* wrapped vector */
+                $1 = 1;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    $1 = 0;
+                else
+                    if (nitems == 0)
+                        $1 = 1;
+                //check the first value to see if it is of correct type
+                if (CONVERT_FROM(interp, listobjv[0], &temp) == TCL_ERROR)
+                    $1 = 0;
+                else
+                    $1 = 1;
+            }
+        }      
+
+        %typecheck(SWIG_TYPECHECK_VECTOR) const vector<T>&,
+	                                      const vector<T>*{
+            Tcl_Obj **listobjv;
+            int       nitems;
+            T         temp;
+            std::vector<T> *v;
+
+            if(SWIG_ConvertPtr($input, (void **) &v, \
+                               $1_descriptor, 0) == 0){
+                /* wrapped vector */
+                $1 = 1;
+            } else {
+                // It isn't a vector<T> so it should be a list of T's
+                if(Tcl_ListObjGetElements(interp, $input, 
+                                          &nitems, &listobjv) == TCL_ERROR)
+                    $1 = 0;
+                else
+                    if (nitems == 0)
+                        $1 = 1;
+                //check the first value to see if it is of correct type
+                if (CONVERT_FROM(interp, listobjv[0], &temp) == TCL_ERROR)
+                    $1 = 0;
+                else
+                    $1 = 1;
+            }
+        }
+        
+      public:
+        vector(unsigned int size = 0);
+        vector(unsigned int size, const T& value);
+        vector(const vector<T> &);
+
+        unsigned int size() const;
+        bool empty() const;
+        void clear();
+        %rename(push) push_back;
+        void push_back(T x);
+        %extend {
+            T pop() throw (std::out_of_range) {
+                if (self->size() == 0)
+                    throw std::out_of_range("pop from empty vector");
+                T x = self->back();
+                self->pop_back();
+                return x;
+            }
+            T get(int i) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i<0) i += size;
+                if (i>=0 && i<size)
+                    return (*self)[i];
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+            void set(int i, T x) throw (std::out_of_range) {
+                int size = int(self->size());
+                if (i<0) i+= size;
+                if (i>=0 && i<size)
+                    (*self)[i] = x;
+                else
+                    throw std::out_of_range("vector index out of range");
+            }
+        }
+    };
+    %enddef
+
+    specialize_std_vector(bool, Tcl_GetBoolFromObj, Tcl_NewBooleanObj);
+    specialize_std_vector(char, SwigInt_As<char>,Tcl_NewIntObj);
+    specialize_std_vector(int, Tcl_GetIntFromObj,Tcl_NewIntObj);
+    specialize_std_vector(short, SwigInt_As<short>, Tcl_NewIntObj);
+    specialize_std_vector(long, SwigInt_As<long>, Tcl_NewIntObj);
+    specialize_std_vector(unsigned char, 
+                          SwigInt_As<unsigned char>, Tcl_NewIntObj);
+    specialize_std_vector(unsigned int, 
+                          SwigInt_As<unsigned int>, Tcl_NewIntObj);
+    specialize_std_vector(unsigned short, 
+                          SwigInt_As<unsigned short>, Tcl_NewIntObj);
+    specialize_std_vector(unsigned long, 
+                          SwigInt_As<unsigned long>, Tcl_NewIntObj);
+    specialize_std_vector(double, Tcl_GetDoubleFromObj, Tcl_NewDoubleObj);
+    specialize_std_vector(float, SwigDouble_As<float>, Tcl_NewDoubleObj);
+    specialize_std_vector(std::string, 
+                          SwigString_AsString, SwigString_FromString);
+
+}
+
+
diff --git a/trunk/Lib/tcl/std_wstring.i b/trunk/Lib/tcl/std_wstring.i
new file mode 100644
index 0000000..f132614
--- /dev/null
+++ b/trunk/Lib/tcl/std_wstring.i
@@ -0,0 +1,2 @@
+%include <tclwstrings.swg>
+%include <typemaps/std_wstring.swg>
diff --git a/trunk/Lib/tcl/stl.i b/trunk/Lib/tcl/stl.i
new file mode 100644
index 0000000..afd1213
--- /dev/null
+++ b/trunk/Lib/tcl/stl.i
@@ -0,0 +1,14 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stl.i
+ * ----------------------------------------------------------------------------- */
+
+/* initial STL definition. extended as needed in each language */
+%include <std_common.i>
+%include <std_string.i>
+%include <std_vector.i>
+%include <std_map.i>
+%include <std_pair.i>
+
diff --git a/trunk/Lib/tcl/tcl8.swg b/trunk/Lib/tcl/tcl8.swg
new file mode 100644
index 0000000..c33cc76
--- /dev/null
+++ b/trunk/Lib/tcl/tcl8.swg
@@ -0,0 +1,45 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tcl8.swg
+ *
+ * Tcl configuration module.
+ * ----------------------------------------------------------------------------- */
+
+/* ------------------------------------------------------------
+ *  Inner macros 
+ * ------------------------------------------------------------ */
+%include <tclmacros.swg>
+
+/* ------------------------------------------------------------
+ *  The runtime part
+ * ------------------------------------------------------------ */
+%include <tclruntime.swg>
+
+/* ------------------------------------------------------------
+ *  Special user directives
+ * ------------------------------------------------------------ */
+%include <tcluserdir.swg>
+
+/* ------------------------------------------------------------
+ *  Typemap specializations
+ * ------------------------------------------------------------ */
+%include <tcltypemaps.swg>
+
+/* ------------------------------------------------------------
+ *  Overloaded operator support
+ * ------------------------------------------------------------ */
+%include <tclopers.swg>
+
+/* ------------------------------------------------------------
+ * Warnings for Tcl keywords 
+ * ------------------------------------------------------------ */
+%include <tclkw.swg>
+
+/* ------------------------------------------------------------
+ * The Tcl initialization function 
+ * ------------------------------------------------------------ */
+%include <tclinit.swg>
+
+
diff --git a/trunk/Lib/tcl/tclapi.swg b/trunk/Lib/tcl/tclapi.swg
new file mode 100644
index 0000000..6b67327
--- /dev/null
+++ b/trunk/Lib/tcl/tclapi.swg
@@ -0,0 +1,107 @@
+/* -----------------------------------------------------------------------------
+ * SWIG API. Portion that goes into the runtime
+ * ----------------------------------------------------------------------------- */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Constant declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Constant Types */
+#define SWIG_TCL_POINTER 4
+#define SWIG_TCL_BINARY  5
+
+/* Constant information structure */
+typedef struct swig_const_info {
+    int type;
+    char *name;
+    long lvalue;
+    double dvalue;
+    void   *pvalue;
+    swig_type_info **ptype;
+} swig_const_info;
+
+typedef int   (*swig_wrapper)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []);
+typedef int   (*swig_wrapper_func)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []);
+typedef char *(*swig_variable_func)(ClientData, Tcl_Interp *, char *, char *, int);
+typedef void  (*swig_delete_func)(ClientData);
+
+typedef struct swig_method {
+  const char     *name;
+  swig_wrapper   method;
+} swig_method;
+
+typedef struct swig_attribute {
+  const char     *name;
+  swig_wrapper   getmethod;
+  swig_wrapper   setmethod;
+} swig_attribute;
+
+typedef struct swig_class {
+  const char         *name;
+  swig_type_info   **type;
+  swig_wrapper       constructor;
+  void              (*destructor)(void *);
+  swig_method        *methods;
+  swig_attribute     *attributes;
+  struct swig_class **bases;
+  const char              **base_names;
+  swig_module_info   *module;
+} swig_class;
+
+typedef struct swig_instance {
+  Tcl_Obj       *thisptr;
+  void          *thisvalue;
+  swig_class   *classptr;
+  int            destroy;
+  Tcl_Command    cmdtok;
+} swig_instance;
+
+/* Structure for command table */
+typedef struct {
+  const char *name;
+  int       (*wrapper)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []);
+  ClientData  clientdata;
+} swig_command_info;
+
+/* Structure for variable linking table */
+typedef struct {
+  const char *name;
+  void *addr;
+  char * (*get)(ClientData, Tcl_Interp *, char *, char *, int);
+  char * (*set)(ClientData, Tcl_Interp *, char *, char *, int);
+} swig_var_info;
+
+
+/* -----------------------------------------------------------------------------*
+ *  Install a constant object 
+ * -----------------------------------------------------------------------------*/
+
+static Tcl_HashTable   swigconstTable;
+static int             swigconstTableinit = 0;
+
+SWIGINTERN void
+SWIG_Tcl_SetConstantObj(Tcl_Interp *interp, const char* name, Tcl_Obj *obj) {
+  int newobj;
+  Tcl_ObjSetVar2(interp,Tcl_NewStringObj(name,-1), NULL, obj, TCL_GLOBAL_ONLY);
+  Tcl_SetHashValue(Tcl_CreateHashEntry(&swigconstTable, name, &newobj), (ClientData) obj);
+}
+
+SWIGINTERN Tcl_Obj *
+SWIG_Tcl_GetConstantObj(const char *key) {
+  Tcl_HashEntry *entryPtr;
+  if (!swigconstTableinit) return 0;
+  entryPtr = Tcl_FindHashEntry(&swigconstTable, key);
+  if (entryPtr) {
+    return (Tcl_Obj *) Tcl_GetHashValue(entryPtr);
+  }
+  return 0;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+
diff --git a/trunk/Lib/tcl/tclerrors.swg b/trunk/Lib/tcl/tclerrors.swg
new file mode 100644
index 0000000..889d3ad
--- /dev/null
+++ b/trunk/Lib/tcl/tclerrors.swg
@@ -0,0 +1,76 @@
+/* -----------------------------------------------------------------------------
+ * error manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGINTERN const char*
+SWIG_Tcl_ErrorType(int code) {
+  const char* type = 0;
+  switch(code) {
+  case SWIG_MemoryError:
+    type = "MemoryError";
+    break;
+  case SWIG_IOError:
+    type = "IOError";
+    break;
+  case SWIG_RuntimeError:
+    type = "RuntimeError";
+    break;
+  case SWIG_IndexError:
+    type = "IndexError";
+    break;
+  case SWIG_TypeError:
+    type = "TypeError";
+    break;
+  case SWIG_DivisionByZero:
+    type = "ZeroDivisionError";
+    break;
+  case SWIG_OverflowError:
+    type = "OverflowError";
+    break;
+  case SWIG_SyntaxError:
+    type = "SyntaxError";
+    break;
+  case SWIG_ValueError:
+    type = "ValueError";
+    break;
+  case SWIG_SystemError:
+    type = "SystemError";
+    break;
+  case SWIG_AttributeError:
+    type = "AttributeError";
+    break;
+  default:
+    type = "RuntimeError";
+  }
+  return type;
+}
+
+
+SWIGINTERN void
+SWIG_Tcl_SetErrorObj(Tcl_Interp *interp, const char *ctype, Tcl_Obj *obj)
+{
+  Tcl_ResetResult(interp);
+  Tcl_SetObjResult(interp, obj);
+  Tcl_SetErrorCode(interp, "SWIG", ctype, NULL);
+}
+
+SWIGINTERN void
+SWIG_Tcl_SetErrorMsg(Tcl_Interp *interp, const char *ctype, const char *mesg)
+{
+  Tcl_ResetResult(interp);
+  Tcl_SetErrorCode(interp, "SWIG", ctype, NULL);
+  Tcl_AppendResult(interp, ctype, " ", mesg, NULL);
+  /*
+  Tcl_AddErrorInfo(interp, ctype);
+  Tcl_AddErrorInfo(interp, " ");
+  Tcl_AddErrorInfo(interp, mesg);
+  */
+}
+
+SWIGINTERNINLINE void
+SWIG_Tcl_AddErrorMsg(Tcl_Interp *interp, const char* mesg)
+{
+  Tcl_AddErrorInfo(interp, mesg);
+}
+
+
diff --git a/trunk/Lib/tcl/tclfragments.swg b/trunk/Lib/tcl/tclfragments.swg
new file mode 100644
index 0000000..ba6398c
--- /dev/null
+++ b/trunk/Lib/tcl/tclfragments.swg
@@ -0,0 +1,22 @@
+/*
+
+  Create a file with this name, 'tclfragments.swg', in your working
+  directory and add all the %fragments you want to take precedence
+  over the ones defined by default by swig.
+
+  For example, if you add:
+  
+  %fragment(SWIG_AsVal_frag(int),"header") {
+   SWIGINTERNINLINE int
+   SWIG_AsVal_dec(int)(TclObject *obj, int *val)
+   { 
+     <your code here>;
+   }
+  }
+  
+  this will replace the code used to retrieve an integer value for all
+  the typemaps that need it, including:
+  
+    int, std::vector<int>, std::list<std::pair<int,int> >, etc.
+
+*/
diff --git a/trunk/Lib/tcl/tclinit.swg b/trunk/Lib/tcl/tclinit.swg
new file mode 100644
index 0000000..93d984a
--- /dev/null
+++ b/trunk/Lib/tcl/tclinit.swg
@@ -0,0 +1,106 @@
+/* ------------------------------------------------------------
+ * The start of the Tcl initialization function 
+ * ------------------------------------------------------------ */
+
+%insert(init) "swiginit.swg"
+
+/* This initialization code exports the module initialization function */
+
+%header %{
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#ifdef MAC_TCL
+#pragma export on
+#endif
+SWIGEXPORT int SWIG_init(Tcl_Interp *);
+#ifdef MAC_TCL
+#pragma export off
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+%}
+
+%init %{
+#ifdef __cplusplus
+extern "C" {   
+#endif
+
+/* -----------------------------------------------------------------------------
+ * constants/methods manipulation
+ * ----------------------------------------------------------------------------- */
+
+/* Install Constants */
+
+SWIGINTERN void
+SWIG_Tcl_InstallConstants(Tcl_Interp *interp, swig_const_info constants[]) {
+  int i;
+  Tcl_Obj *obj;
+
+  if (!swigconstTableinit) {
+    Tcl_InitHashTable(&swigconstTable, TCL_STRING_KEYS);
+    swigconstTableinit = 1;
+  }
+  for (i = 0; constants[i].type; i++) {
+    switch(constants[i].type) {
+    case SWIG_TCL_POINTER:
+      obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
+      break;
+    case SWIG_TCL_BINARY:
+      obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
+      break;
+    default:
+      obj = 0;
+      break;
+    }
+    if (obj) {
+      SWIG_Tcl_SetConstantObj(interp, constants[i].name, obj);
+    }
+  }
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/* -----------------------------------------------------------------------------*
+ *  Partial Init method
+ * -----------------------------------------------------------------------------*/
+
+SWIGEXPORT int SWIG_init(Tcl_Interp *interp) {
+  int i;
+  if (interp == 0) return TCL_ERROR;
+#ifdef USE_TCL_STUBS
+  if (Tcl_InitStubs(interp, (char*)"8.1", 0) == NULL) {
+    return TCL_ERROR;
+  }
+#endif  
+  Tcl_PkgProvide(interp, (char*)SWIG_name, (char*)SWIG_version);
+  
+#ifdef SWIG_namespace
+  Tcl_Eval(interp, "namespace eval " SWIG_namespace " { }");
+#endif
+  
+  SWIG_InitializeModule((void *) interp);
+  SWIG_PropagateClientData();
+  
+  for (i = 0; swig_commands[i].name; i++) {
+    Tcl_CreateObjCommand(interp, (char *) swig_commands[i].name, (swig_wrapper_func) swig_commands[i].wrapper,
+			 swig_commands[i].clientdata, NULL);
+  }
+  for (i = 0; swig_variables[i].name; i++) {
+    Tcl_SetVar(interp, (char *) swig_variables[i].name, (char *) "", TCL_GLOBAL_ONLY);
+    Tcl_TraceVar(interp, (char *) swig_variables[i].name, TCL_TRACE_READS | TCL_GLOBAL_ONLY, 
+		 (Tcl_VarTraceProc *) swig_variables[i].get, (ClientData) swig_variables[i].addr);
+    Tcl_TraceVar(interp, (char *) swig_variables[i].name, TCL_TRACE_WRITES | TCL_GLOBAL_ONLY, 
+		 (Tcl_VarTraceProc *) swig_variables[i].set, (ClientData) swig_variables[i].addr);
+  }
+
+  SWIG_Tcl_InstallConstants(interp, swig_constants);
+
+%}
+
+/* Note: the initialization function is closed after all code is generated */
diff --git a/trunk/Lib/tcl/tclinterp.i b/trunk/Lib/tcl/tclinterp.i
new file mode 100644
index 0000000..48cdb60
--- /dev/null
+++ b/trunk/Lib/tcl/tclinterp.i
@@ -0,0 +1,20 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tclinterp.i
+ *
+ * Tcl_Interp *interp
+ *
+ * Passes the current Tcl_Interp value directly to a C function.
+ * This can be used to work with existing wrapper functions or
+ * if you just need the interp value for some reason.  When used,
+ * the 'interp' parameter becomes hidden in the Tcl interface--that
+ * is, you don't specify it explicitly. SWIG fills in its value
+ * automatically.
+ * ----------------------------------------------------------------------------- */
+
+%typemap(in,numinputs=0) Tcl_Interp *interp {
+  $1 = interp;
+}
+
diff --git a/trunk/Lib/tcl/tclkw.swg b/trunk/Lib/tcl/tclkw.swg
new file mode 100644
index 0000000..e96e885
--- /dev/null
+++ b/trunk/Lib/tcl/tclkw.swg
@@ -0,0 +1,10 @@
+#ifndef TCL_TCLKW_SWG_
+#define TCL_TCLKW_SWG_
+
+// Some special reserved words in classes
+
+%keywordwarn("cget is a tcl reserved method name") *::cget;
+%keywordwarn("configure is a tcl reserved method name") *::configure;
+
+
+#endif //_TCL_TCLKW_SWG_
diff --git a/trunk/Lib/tcl/tclmacros.swg b/trunk/Lib/tcl/tclmacros.swg
new file mode 100644
index 0000000..ab7bace
--- /dev/null
+++ b/trunk/Lib/tcl/tclmacros.swg
@@ -0,0 +1,4 @@
+%include <typemaps/swigmacros.swg>
+
+
+
diff --git a/trunk/Lib/tcl/tclopers.swg b/trunk/Lib/tcl/tclopers.swg
new file mode 100644
index 0000000..26b7420
--- /dev/null
+++ b/trunk/Lib/tcl/tclopers.swg
@@ -0,0 +1,46 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tclopers.swg
+ *
+ * C++ overloaded operators.
+ *
+ * These declarations define how SWIG is going to rename C++
+ * overloaded operators in Tcl.  Since Tcl allows identifiers
+ * to be essentially any valid string, we'll just use the
+ * normal operator names.
+ * ----------------------------------------------------------------------------- */
+
+
+#ifdef __cplusplus
+%rename("+")         *::operator+;
+//%rename("u+")        *::operator+();     // Unary +
+//%rename("u+")        *::operator+() const;     // Unary +
+%rename("-")         *::operator-;
+//%rename("u-")        *::operator-();     // Unary -
+//%rename("u-")        *::operator-() const;     // Unary -
+%rename("*")         *::operator*;
+%rename("/")         *::operator/;
+%rename("<<")        *::operator<<;
+%rename(">>")        *::operator>>;
+%rename("&")         *::operator&;
+%rename("|")         *::operator|;
+%rename("^")         *::operator^;
+%rename("%")         *::operator%;
+%rename("=")         *::operator=;
+
+/* Ignored operators */
+%ignoreoperator(NOTEQUAL) operator!=;
+%ignoreoperator(PLUSEQ)   operator+=;
+%ignoreoperator(MINUSEQ)  operator-=;
+%ignoreoperator(MULEQ)    operator*=;
+%ignoreoperator(DIVEQ)    operator/=;
+%ignoreoperator(MODEQ)    operator%=;
+%ignoreoperator(LSHIFTEQ) operator<<=;
+%ignoreoperator(RSHIFTEQ) operator>>=;
+%ignoreoperator(ANDEQ)    operator&=;
+%ignoreoperator(OREQ)     operator|=;
+%ignoreoperator(XOREQ)    operator^=;
+
+#endif
diff --git a/trunk/Lib/tcl/tclprimtypes.swg b/trunk/Lib/tcl/tclprimtypes.swg
new file mode 100644
index 0000000..e781798
--- /dev/null
+++ b/trunk/Lib/tcl/tclprimtypes.swg
@@ -0,0 +1,239 @@
+/* ------------------------------------------------------------
+ * Primitive Types
+ * ------------------------------------------------------------ */
+
+/* boolean */
+
+%fragment(SWIG_From_frag(bool),"header") {
+  %define_as(SWIG_From_dec(bool),           Tcl_NewBooleanObj)
+}
+
+%fragment(SWIG_AsVal_frag(bool),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(bool)(Tcl_Obj *obj, bool *val)
+{
+  int v;
+  if (Tcl_GetBooleanFromObj(0, obj, &v) == TCL_OK) {
+    if (val) *val = v ? true : false;
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* long */
+
+%fragment(SWIG_From_frag(long),"header",
+	  fragment="<limits.h>") {
+SWIGINTERNINLINE Tcl_Obj* 
+SWIG_From_dec(long)(long value)
+{
+  if (((long) INT_MIN <= value) && (value <= (long) INT_MAX)) {
+    return Tcl_NewIntObj(%numeric_cast(value,int));
+  } else {
+    return Tcl_NewLongObj(value);
+  }
+}
+}
+
+%fragment(SWIG_AsVal_frag(long),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(long)(Tcl_Obj *obj, long* val)
+{
+  long v;
+  if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) {
+    if (val) *val = (long) v;
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* unsigned long */
+
+%fragment(SWIG_From_frag(unsigned long),"header",
+	  fragment=SWIG_From_frag(long),
+	  fragment="<stdio.h>") {
+SWIGINTERNINLINE Tcl_Obj* 
+SWIG_From_dec(unsigned long)(unsigned long value)
+{
+  if (value < (unsigned long) LONG_MAX) {
+    return SWIG_From(long)(%numeric_cast(value, long));
+  } else {
+    char temp[256]; 
+    sprintf(temp, "%lu", value);
+    return Tcl_NewStringObj(temp,-1);
+  }
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long),"header",
+	  fragment="<limits.h>") {
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long)(Tcl_Obj *obj, unsigned long *val) {
+  long v;
+  if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) {
+    if (v >= 0) {
+      if (val) *val = (unsigned long) v;
+      return SWIG_OK;
+    }
+    /* If v is negative, then this could be a negative number, or an
+       unsigned value which doesn't fit in a signed long, so try to
+       get it as a string so we can distinguish these cases. */
+  }
+  {
+    int len = 0;
+    const char *nptr = Tcl_GetStringFromObj(obj, &len);
+    if (nptr && len > 0) {
+      char *endptr;
+      unsigned long v;
+      if (*nptr == '-') return SWIG_OverflowError;
+      errno = 0;
+      v = strtoul(nptr, &endptr,0);
+      if (nptr[0] == '\0' || *endptr != '\0')
+	return SWIG_TypeError;
+      if (v == ULONG_MAX && errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_OK;
+	}
+      }
+    }
+  }
+  
+  return SWIG_TypeError;
+}
+}
+
+/* long long */
+
+%fragment(SWIG_From_frag(long long),"header",
+	  fragment=SWIG_From_frag(long),
+	  fragment="<limits.h>",
+	  fragment="<stdio.h>") {
+SWIGINTERNINLINE Tcl_Obj* 
+SWIG_From_dec(long long)(long long value)
+{
+  if (((long long) LONG_MIN <= value) && (value <= (long long) LONG_MAX)) {
+    return SWIG_From(long)(%numeric_cast(value,long));
+  } else {    
+    char temp[256]; 
+    sprintf(temp, "%lld", value);
+    return Tcl_NewStringObj(temp,-1);
+  }
+}
+}
+
+%fragment(SWIG_AsVal_frag(long long),"header",
+	  fragment="<limits.h>",
+	  fragment="<stdlib.h>") {
+SWIGINTERN int
+SWIG_AsVal_dec(long long)(Tcl_Obj *obj, long long *val)
+{
+  long v;
+  if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) {
+    if (val) *val = v;
+    return SWIG_OK;
+  } else {
+    int len = 0;
+    const char *nptr = Tcl_GetStringFromObj(obj, &len);
+    if (nptr && len > 0) {
+      char *endptr;
+      long long v;
+      errno = 0;
+      v = strtoll(nptr, &endptr,0);
+      if (nptr[0] == '\0' || *endptr != '\0')
+	return SWIG_TypeError;
+      if ((v == LLONG_MAX || v == LLONG_MIN) && errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_OK;
+	}
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* unsigned long long */
+
+%fragment(SWIG_From_frag(unsigned long long),"header",
+	  fragment=SWIG_From_frag(long long),
+	  fragment="<limits.h>",
+	  fragment="<stdio.h>") {
+SWIGINTERNINLINE Tcl_Obj* 
+SWIG_From_dec(unsigned long long)(unsigned long long value)
+{
+  if (value < (unsigned long long) LONG_MAX) {
+    return SWIG_From(long long)(%numeric_cast(value, long long));
+  } else {
+    char temp[256]; 
+    sprintf(temp, "%llu", value);
+    return Tcl_NewStringObj(temp,-1);
+  }
+}
+}
+
+%fragment(SWIG_AsVal_frag(unsigned long long),"header",
+	  fragment=SWIG_AsVal_frag(unsigned long),
+	  fragment="<limits.h>",
+	  fragment="<stdlib.h>") {
+SWIGINTERN int
+SWIG_AsVal_dec(unsigned long long)(Tcl_Obj *obj, unsigned long long *val)
+{
+  long v;
+  if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) {
+    if (val) *val = (unsigned long) v;
+    return SWIG_OK;
+  } else {
+    int len = 0;
+    const char *nptr = Tcl_GetStringFromObj(obj, &len);
+    if (nptr && len > 0) {
+      char *endptr;
+      unsigned long long v;
+      if (*nptr == '-') return SWIG_OverflowError;
+      errno = 0;
+      v = strtoull(nptr, &endptr,0);
+      if (nptr[0] == '\0' || *endptr != '\0')
+	return SWIG_TypeError;
+      if (v == ULLONG_MAX && errno == ERANGE) {
+	errno = 0;
+	return SWIG_OverflowError;
+      } else {
+	if (*endptr == '\0') {
+	  if (val) *val = v;
+	  return SWIG_OK;
+	}
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* double */
+
+%fragment(SWIG_From_frag(double),"header") {
+  %define_as(SWIG_From(double),         Tcl_NewDoubleObj)
+}
+
+%fragment(SWIG_AsVal_frag(double),"header") {
+SWIGINTERN int
+SWIG_AsVal_dec(double)(Tcl_Obj *obj, double *val)
+{
+  double v;
+  if (Tcl_GetDoubleFromObj(0, obj, &v) == TCL_OK) {
+    if (val) *val = v;
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
diff --git a/trunk/Lib/tcl/tclresult.i b/trunk/Lib/tcl/tclresult.i
new file mode 100644
index 0000000..ca01064
--- /dev/null
+++ b/trunk/Lib/tcl/tclresult.i
@@ -0,0 +1,30 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tclresult.i
+ * ----------------------------------------------------------------------------- */
+
+/*
+int Tcl_Result
+
+      Makes the integer return code of a function the return value 
+      of a SWIG generated wrapper function.  For example :
+
+            int foo() {
+                  ... do stuff ...
+                  return TCL_OK;
+            }      
+
+      could be wrapped as follows :
+
+            %include typemaps.i
+            %apply int Tcl_Result { int foo };
+            int foo();
+*/
+
+// If return code is a Tcl_Result, simply pass it on
+
+%typemap(out) int Tcl_Result {
+  return $1;
+}
diff --git a/trunk/Lib/tcl/tclrun.swg b/trunk/Lib/tcl/tclrun.swg
new file mode 100644
index 0000000..6387fb0
--- /dev/null
+++ b/trunk/Lib/tcl/tclrun.swg
@@ -0,0 +1,695 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tclrun.swg
+ *
+ * This file contains the runtime support for Tcl modules and includes
+ * code for managing global variables and pointer type checking.
+ * ----------------------------------------------------------------------------- */
+
+/* Common SWIG API */
+
+/* for raw pointers */
+#define SWIG_ConvertPtr(oc, ptr, ty, flags)             SWIG_Tcl_ConvertPtr(interp, oc, ptr, ty, flags)
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Tcl_NewPointerObj(ptr, type, flags)
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Tcl_ConvertPacked(interp, obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Tcl_NewPackedObj(ptr, sz, type)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_Tcl_ConvertPtr(interp, obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(thisvalue, type, flags)     SWIG_Tcl_NewInstanceObj(interp, thisvalue, type, flags)
+
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Tcl_ConvertPtr(interp, obj, pptr, type, 0)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Tcl_NewPointerObj(ptr, type, 0)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Tcl_ConvertPacked(interp,obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Tcl_NewPackedObj(ptr, sz, type)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_Tcl_GetModule((Tcl_Interp *) (clientdata))	     
+#define SWIG_SetModule(clientdata, pointer)          	SWIG_Tcl_SetModule((Tcl_Interp *) (clientdata), pointer)
+
+
+/* Error manipulation */
+
+#define SWIG_ErrorType(code)                            SWIG_Tcl_ErrorType(code)                                      
+#define SWIG_Error(code, msg)            		SWIG_Tcl_SetErrorMsg(interp, SWIG_Tcl_ErrorType(code), msg)
+#define SWIG_fail                        		goto fail						    
+
+
+/* Tcl-specific SWIG API */
+
+#define SWIG_Acquire(ptr)                               SWIG_Tcl_Acquire(ptr)                                     
+#define SWIG_MethodCommand                           	SWIG_Tcl_MethodCommand				       
+#define SWIG_Disown(ptr)                             	SWIG_Tcl_Disown(ptr)				       
+#define SWIG_ConvertPtrFromString(c, ptr, ty, flags) 	SWIG_Tcl_ConvertPtrFromString(interp, c, ptr, ty, flags)  
+#define SWIG_MakePtr(c, ptr, ty, flags)              	SWIG_Tcl_MakePtr(c, ptr, ty, flags)		       
+#define SWIG_PointerTypeFromString(c)                	SWIG_Tcl_PointerTypeFromString(c)			       
+#define SWIG_GetArgs                                 	SWIG_Tcl_GetArgs					       
+#define SWIG_GetConstantObj(key)                     	SWIG_Tcl_GetConstantObj(key)			       
+#define SWIG_ObjectConstructor                       	SWIG_Tcl_ObjectConstructor				       
+#define SWIG_Thisown(ptr)                            	SWIG_Tcl_Thisown(ptr)				       
+#define SWIG_ObjectDelete                            	SWIG_Tcl_ObjectDelete				       
+
+
+#define SWIG_TCL_DECL_ARGS_2(arg1, arg2)                (Tcl_Interp *interp SWIGUNUSED, arg1, arg2)
+#define SWIG_TCL_CALL_ARGS_2(arg1, arg2)                (interp, arg1, arg2)
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+/* For backward compatibility only */
+#define SWIG_POINTER_EXCEPTION  0
+#define SWIG_GetConstant        SWIG_GetConstantObj
+#define SWIG_Tcl_GetConstant    SWIG_Tcl_GetConstantObj
+
+#include "assert.h"
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* cc-mode */
+#endif
+#endif
+
+/* Object support */
+
+SWIGRUNTIME Tcl_HashTable*
+SWIG_Tcl_ObjectTable(void) {
+  static Tcl_HashTable  swigobjectTable;
+  static int            swigobjectTableinit = 0;
+  if (!swigobjectTableinit) {
+    Tcl_InitHashTable(&swigobjectTable, TCL_ONE_WORD_KEYS);
+    swigobjectTableinit = 1;
+  }
+  return &swigobjectTable;
+}
+
+/* Acquire ownership of a pointer */
+SWIGRUNTIME void
+SWIG_Tcl_Acquire(void *ptr) {
+  int newobj;
+  Tcl_CreateHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr, &newobj);
+}
+
+SWIGRUNTIME int
+SWIG_Tcl_Thisown(void *ptr) {
+  if (Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr)) {
+    return 1;
+  }
+  return 0;
+}
+
+/* Disown a pointer.  Returns 1 if we owned it to begin with */
+SWIGRUNTIME int
+SWIG_Tcl_Disown(void *ptr) {
+  Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr);
+  if (entryPtr) {
+    Tcl_DeleteHashEntry(entryPtr);
+    return 1;
+  }
+  return 0;
+}
+
+/* Convert a pointer value */
+SWIGRUNTIME int
+SWIG_Tcl_ConvertPtrFromString(Tcl_Interp *interp, const char *c, void **ptr, swig_type_info *ty, int flags) {
+  swig_cast_info *tc;
+  /* Pointer values must start with leading underscore */
+  while (*c != '_') {
+    *ptr = (void *) 0;
+    if (strcmp(c,"NULL") == 0) return SWIG_OK;
+
+    /* Empty string: not a pointer */
+    if (*c == 0) return SWIG_ERROR; 
+
+    /* Hmmm. It could be an object name. */
+
+    /* Check if this is a command at all. Prevents <c> cget -this         */
+    /* from being called when c is not a command, firing the unknown proc */
+    if (Tcl_VarEval(interp,"info commands ", c, (char *) NULL) == TCL_OK) {
+      Tcl_Obj *result = Tcl_GetObjResult(interp);
+      if (*(Tcl_GetStringFromObj(result, NULL)) == 0) {
+        /* It's not a command, so it can't be a pointer */
+        Tcl_ResetResult(interp);
+        return SWIG_ERROR;
+      }
+    } else {
+      /* This will only fail if the argument is multiple words. */
+      /* Multiple words are also not commands.                  */
+      Tcl_ResetResult(interp);
+      return SWIG_ERROR;
+    }
+
+    /* Check if this is really a SWIG pointer */
+    if (Tcl_VarEval(interp,c," cget -this", (char *) NULL) != TCL_OK) {
+      Tcl_ResetResult(interp);
+      return SWIG_ERROR;
+    }
+
+    c = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL);
+  }
+
+  c++;
+  c = SWIG_UnpackData(c,ptr,sizeof(void *));
+  if (ty) {
+    tc = c ? SWIG_TypeCheck(c,ty) : 0;
+    if (!tc) {
+      return SWIG_ERROR;
+    }
+    if (flags & SWIG_POINTER_DISOWN) {
+      SWIG_Disown((void *) *ptr);
+    }
+    {
+      int newmemory = 0;
+      *ptr = SWIG_TypeCast(tc,(void *) *ptr,&newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+    }
+  }
+  return SWIG_OK;
+}
+
+/* Convert a pointer value */
+SWIGRUNTIMEINLINE int
+SWIG_Tcl_ConvertPtr(Tcl_Interp *interp, Tcl_Obj *oc, void **ptr, swig_type_info *ty, int flags) {
+  return SWIG_Tcl_ConvertPtrFromString(interp, Tcl_GetStringFromObj(oc,NULL), ptr, ty, flags);
+}
+
+/* Convert a pointer value */
+SWIGRUNTIME char *
+SWIG_Tcl_PointerTypeFromString(char *c) {
+  char d;
+  /* Pointer values must start with leading underscore. NULL has no type */
+  if (*c != '_') {
+    return 0;
+  }
+  c++;
+  /* Extract hex value from pointer */
+  while ((d = *c)) {
+    if (!(((d >= '0') && (d <= '9')) || ((d >= 'a') && (d <= 'f')))) break;
+    c++;
+  }
+  return c;
+}
+
+/* Convert a packed value value */
+SWIGRUNTIME int
+SWIG_Tcl_ConvertPacked(Tcl_Interp *SWIGUNUSEDPARM(interp) , Tcl_Obj *obj, void *ptr, int sz, swig_type_info *ty) {
+  swig_cast_info *tc;
+  const char  *c;
+
+  if (!obj) goto type_error;
+  c = Tcl_GetStringFromObj(obj,NULL);
+  /* Pointer values must start with leading underscore */
+  if (*c != '_') goto type_error;
+  c++;
+  c = SWIG_UnpackData(c,ptr,sz);
+  if (ty) {
+    tc = SWIG_TypeCheck(c,ty);
+    if (!tc) goto type_error;
+  }
+  return SWIG_OK;
+
+ type_error:
+
+  return SWIG_ERROR;
+}
+
+
+/* Take a pointer and convert it to a string */
+SWIGRUNTIME void
+SWIG_Tcl_MakePtr(char *c, void *ptr, swig_type_info *ty, int flags) {
+  if (ptr) {
+    *(c++) = '_';
+    c = SWIG_PackData(c,&ptr,sizeof(void *));
+    strcpy(c,ty->name);
+  } else {
+    strcpy(c,(char *)"NULL");
+  }
+  flags = 0;
+}
+
+/* Create a new pointer object */
+SWIGRUNTIMEINLINE Tcl_Obj *
+SWIG_Tcl_NewPointerObj(void *ptr, swig_type_info *type, int flags) {
+  Tcl_Obj *robj;
+  char result[SWIG_BUFFER_SIZE];
+  SWIG_MakePtr(result,ptr,type,flags);
+  robj = Tcl_NewStringObj(result,-1);
+  return robj;
+}
+
+SWIGRUNTIME Tcl_Obj *
+SWIG_Tcl_NewPackedObj(void *ptr, int sz, swig_type_info *type) {
+  char result[1024];
+  char *r = result;
+  if ((2*sz + 1 + strlen(type->name)) > 1000) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  strcpy(r,type->name);
+  return Tcl_NewStringObj(result,-1);
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Get type list 
+ * -----------------------------------------------------------------------------*/
+
+SWIGRUNTIME swig_module_info * 
+SWIG_Tcl_GetModule(Tcl_Interp *interp) {
+  const char *data;
+  swig_module_info *ret = 0;
+  
+  /* first check if pointer already created */
+  data = Tcl_GetVar(interp, (char *)"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, TCL_GLOBAL_ONLY);
+  if (data) {
+    SWIG_UnpackData(data, &ret, sizeof(swig_type_info **));
+  }
+
+  return ret;
+}
+
+SWIGRUNTIME void
+SWIG_Tcl_SetModule(Tcl_Interp *interp, swig_module_info *module) {
+  char buf[SWIG_BUFFER_SIZE];
+  char *data;
+
+  /* create a new pointer */
+  data = SWIG_PackData(buf, &module, sizeof(swig_type_info **));
+  *data = 0;
+  Tcl_SetVar(interp, (char *)"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, buf, 0);
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Object auxiliars
+ * -----------------------------------------------------------------------------*/
+
+
+SWIGRUNTIME void
+SWIG_Tcl_ObjectDelete(ClientData clientData) {
+  swig_instance *si = (swig_instance *) clientData;
+  if ((si) && (si->destroy) && (SWIG_Disown(si->thisvalue))) {
+    if (si->classptr->destructor) {
+      (si->classptr->destructor)(si->thisvalue);
+    }
+  }
+  Tcl_DecrRefCount(si->thisptr);
+  free(si);
+}
+
+/* Function to invoke object methods given an instance */
+SWIGRUNTIME int
+SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST _objv[]) {
+  char *method,   *attrname;
+  swig_instance   *inst = (swig_instance *) clientData;
+  swig_method     *meth;
+  swig_attribute  *attr;
+  Tcl_Obj         *oldarg;
+  Tcl_Obj         **objv;
+  int              rcode;
+  swig_class      *cls;
+  swig_class      *cls_stack[64];
+  int              cls_stack_bi[64];
+  int              cls_stack_top = 0;
+  int              numconf = 2;
+  int              bi;
+
+  objv = (Tcl_Obj **) _objv;
+  if (objc < 2) {
+    Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC);
+    return TCL_ERROR;
+  }
+  method = Tcl_GetStringFromObj(objv[1],NULL);
+  if (strcmp(method,"-acquire") == 0) {
+    inst->destroy = 1;
+    SWIG_Acquire(inst->thisvalue);
+    return TCL_OK;
+  }
+  if (strcmp(method,"-disown") == 0) {
+    if (inst->destroy) {
+      SWIG_Disown(inst->thisvalue);
+    }
+    inst->destroy = 0;
+    return TCL_OK;
+  }
+  if (strcmp(method,"-delete") == 0) {
+    Tcl_DeleteCommandFromToken(interp,inst->cmdtok);
+    return TCL_OK;
+  }
+  cls_stack[cls_stack_top] = inst->classptr;
+  cls_stack_bi[cls_stack_top] = -1;
+  cls = inst->classptr;
+  while (1) {
+    bi = cls_stack_bi[cls_stack_top];
+    cls = cls_stack[cls_stack_top];
+    if (bi != -1) {
+      if (!cls->bases[bi] && cls->base_names[bi]) {
+        /* lookup and cache the base class */
+	swig_type_info *info = SWIG_TypeQueryModule(cls->module, cls->module, cls->base_names[bi]);
+	if (info) cls->bases[bi] = (swig_class *) info->clientdata;
+      }
+      cls = cls->bases[bi];
+      if (cls) {
+        cls_stack_bi[cls_stack_top]++;
+        cls_stack_top++;
+        cls_stack[cls_stack_top] = cls;
+        cls_stack_bi[cls_stack_top] = -1;
+        continue;
+      }
+    }
+    if (!cls) {
+      cls_stack_top--;
+      if (cls_stack_top < 0) break;
+      else continue;
+    }
+    cls_stack_bi[cls_stack_top]++;
+
+    meth = cls->methods;
+    /* Check for methods */
+    while (meth && meth->name) {
+      if (strcmp(meth->name,method) == 0) {
+        oldarg = objv[1];
+        objv[1] = inst->thisptr;
+        Tcl_IncrRefCount(inst->thisptr);
+        rcode = (*meth->method)(clientData,interp,objc,objv);
+        objv[1] = oldarg;
+        Tcl_DecrRefCount(inst->thisptr);
+        return rcode;
+      }
+      meth++;
+    }
+    /* Check class methods for a match */
+    if (strcmp(method,"cget") == 0) {
+      if (objc < 3) {
+        Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC);
+        return TCL_ERROR;
+      }
+      attrname = Tcl_GetStringFromObj(objv[2],NULL);
+      attr = cls->attributes;
+      while (attr && attr->name) {
+        if ((strcmp(attr->name, attrname) == 0) && (attr->getmethod)) {
+          oldarg = objv[1];
+          objv[1] = inst->thisptr;
+          Tcl_IncrRefCount(inst->thisptr);
+          rcode = (*attr->getmethod)(clientData,interp,2, objv);
+          objv[1] = oldarg;
+          Tcl_DecrRefCount(inst->thisptr);
+          return rcode;
+        }
+        attr++;
+      }
+      if (strcmp(attrname, "-this") == 0) {
+        Tcl_SetObjResult(interp, Tcl_DuplicateObj(inst->thisptr));
+        return TCL_OK;
+      }
+      if (strcmp(attrname, "-thisown") == 0) {
+        if (SWIG_Thisown(inst->thisvalue)) {
+          Tcl_SetResult(interp,(char*)"1",TCL_STATIC);
+        } else {
+          Tcl_SetResult(interp,(char*)"0",TCL_STATIC);
+        }
+        return TCL_OK;
+      }
+    } else if (strcmp(method, "configure") == 0) {
+      int i;
+      if (objc < 4) {
+        Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC);
+        return TCL_ERROR;
+      }
+      i = 2;
+      while (i < objc) {
+        attrname = Tcl_GetStringFromObj(objv[i],NULL);
+        attr = cls->attributes;
+        while (attr && attr->name) {
+          if ((strcmp(attr->name, attrname) == 0) && (attr->setmethod)) {
+            oldarg = objv[i];
+            objv[i] = inst->thisptr;
+            Tcl_IncrRefCount(inst->thisptr);
+            rcode = (*attr->setmethod)(clientData,interp,3, &objv[i-1]);
+            objv[i] = oldarg;
+            Tcl_DecrRefCount(inst->thisptr);
+            if (rcode != TCL_OK) return rcode;
+            numconf += 2;
+          }
+          attr++;
+        }
+        i+=2;
+      }
+    }
+  }
+  if (strcmp(method,"configure") == 0) {
+    if (numconf >= objc) {
+      return TCL_OK;
+    } else {
+      Tcl_SetResult(interp,(char *) "Invalid attribute name.", TCL_STATIC);
+      return TCL_ERROR;
+    }
+  }
+  if (strcmp(method,"cget") == 0) {
+    Tcl_SetResult(interp,(char *) "Invalid attribute name.", TCL_STATIC);
+    return TCL_ERROR;
+  }
+  Tcl_SetResult(interp, (char *) "Invalid method. Must be one of: configure cget -acquire -disown -delete", TCL_STATIC);
+  cls = inst->classptr;
+  bi = 0;
+  while (cls) {
+    meth = cls->methods;
+    while (meth && meth->name) {
+      char *cr = (char *) Tcl_GetStringResult(interp);
+      size_t meth_len = strlen(meth->name);
+      char* where = strchr(cr,':');
+      while(where) {
+        where = strstr(where, meth->name);
+        if(where) {
+          if(where[-1] == ' ' && (where[meth_len] == ' ' || where[meth_len]==0)) {
+            break;
+          } else {
+            where++;
+          }
+        }
+      }
+
+      if (!where)
+        Tcl_AppendElement(interp, (char *) meth->name);
+      meth++;
+    }
+    cls = inst->classptr->bases[bi++];
+  }
+  return TCL_ERROR;
+}
+
+/* This function takes the current result and turns it into an object command */
+SWIGRUNTIME Tcl_Obj *
+SWIG_Tcl_NewInstanceObj(Tcl_Interp *interp, void *thisvalue, swig_type_info *type, int flags) {
+  Tcl_Obj *robj = SWIG_NewPointerObj(thisvalue, type,0);
+  /* Check to see if this pointer belongs to a class or not */
+  if ((type->clientdata) && (interp)) {
+    Tcl_CmdInfo    ci;
+    char          *name;
+    name = Tcl_GetStringFromObj(robj,NULL);
+    if (!Tcl_GetCommandInfo(interp,name, &ci) || (flags)) {
+      swig_instance *newinst = (swig_instance *) malloc(sizeof(swig_instance));
+      newinst->thisptr = Tcl_DuplicateObj(robj);
+      Tcl_IncrRefCount(newinst->thisptr);
+      newinst->thisvalue = thisvalue;
+      newinst->classptr = (swig_class *) type->clientdata;
+      newinst->destroy = flags;
+      newinst->cmdtok = Tcl_CreateObjCommand(interp, Tcl_GetStringFromObj(robj,NULL), (swig_wrapper_func) SWIG_MethodCommand, (ClientData) newinst, (swig_delete_func) SWIG_ObjectDelete);
+      if (flags) {
+        SWIG_Acquire(thisvalue);
+      }
+    }
+  }
+  return robj;
+}
+
+/* Function to create objects */
+SWIGRUNTIME int
+SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
+  Tcl_Obj          *newObj = 0;
+  void             *thisvalue = 0;
+  swig_instance   *newinst = 0;
+  swig_class      *classptr = (swig_class *) clientData;
+  swig_wrapper     cons = 0;
+  char             *name = 0;
+  int               firstarg = 0;
+  int               thisarg = 0;
+  int               destroy = 1;
+
+  if (!classptr) {
+    Tcl_SetResult(interp, (char *) "swig: internal runtime error. No class object defined.", TCL_STATIC);
+    return TCL_ERROR;
+  }
+  cons = classptr->constructor;
+  if (objc > 1) {
+    char *s = Tcl_GetStringFromObj(objv[1],NULL);
+    if (strcmp(s,"-this") == 0) {
+      thisarg = 2;
+      cons = 0;
+    } else if (strcmp(s,"-args") == 0) {
+      firstarg = 1;
+    } else if (objc == 2) {
+      firstarg = 1;
+      name = s;
+    } else if (objc >= 3) {
+      char *s1;
+      name = s;
+      s1 = Tcl_GetStringFromObj(objv[2],NULL);
+      if (strcmp(s1,"-this") == 0) {
+	thisarg = 3;
+	cons = 0;
+      } else {
+	firstarg = 1;
+      }
+    }
+  }
+  if (cons) {
+    int result;
+    result = (*cons)(0, interp, objc-firstarg, &objv[firstarg]);
+    if (result != TCL_OK) {
+      return result;
+    }
+    newObj = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
+    if (!name) name = Tcl_GetStringFromObj(newObj,NULL);
+  } else if (thisarg > 0) {
+    if (thisarg < objc) {
+      destroy = 0;
+      newObj = Tcl_DuplicateObj(objv[thisarg]);
+      if (!name) name = Tcl_GetStringFromObj(newObj,NULL);
+    } else {
+      Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC);
+      return TCL_ERROR;
+    }
+  } else {
+    Tcl_SetResult(interp, (char *) "No constructor available.", TCL_STATIC);
+    return TCL_ERROR;
+  }
+  if (SWIG_Tcl_ConvertPtr(interp,newObj, (void **) &thisvalue, *(classptr->type), 0) != SWIG_OK) {
+    Tcl_DecrRefCount(newObj);
+    return TCL_ERROR;
+  }
+  newinst = (swig_instance *) malloc(sizeof(swig_instance));
+  newinst->thisptr = newObj;
+  Tcl_IncrRefCount(newObj);
+  newinst->thisvalue = thisvalue;
+  newinst->classptr = classptr;
+  newinst->destroy = destroy;
+  if (destroy) {
+    SWIG_Acquire(thisvalue);
+  }
+  newinst->cmdtok = Tcl_CreateObjCommand(interp,name, (swig_wrapper) SWIG_MethodCommand, (ClientData) newinst, (swig_delete_func) SWIG_ObjectDelete);
+  return TCL_OK;
+}
+
+/* -----------------------------------------------------------------------------*
+ *   Get arguments 
+ * -----------------------------------------------------------------------------*/
+SWIGRUNTIME int
+SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char *fmt, ...) {
+  int        argno = 0, opt = 0;
+  long       tempi;
+  double     tempd;
+  const char *c;
+  va_list    ap;
+  void      *vptr;
+  Tcl_Obj   *obj = 0;
+  swig_type_info *ty;
+
+  va_start(ap,fmt);
+  for (c = fmt; (*c && (*c != ':') && (*c != ';')); c++,argno++) {
+    if (*c == '|') {
+      opt = 1;
+      c++;
+    }
+    if (argno >= (objc-1)) {
+      if (!opt) {
+        Tcl_SetResult(interp, (char *) "Wrong number of arguments ", TCL_STATIC);
+        goto argerror;
+      } else {
+        va_end(ap);
+        return TCL_OK;
+      }
+    }
+
+    vptr = va_arg(ap,void *);
+    if (vptr) {
+      if (isupper(*c)) {
+        obj = SWIG_Tcl_GetConstantObj(Tcl_GetStringFromObj(objv[argno+1],0));
+        if (!obj) obj = objv[argno+1];
+      } else {
+        obj = objv[argno+1];
+      }
+      switch(*c) {
+      case 'i': case 'I':
+      case 'l': case 'L':
+      case 'h': case 'H':
+      case 'b': case 'B':
+        if (Tcl_GetLongFromObj(interp,obj,&tempi) != TCL_OK) goto argerror;
+        if ((*c == 'i') || (*c == 'I')) *((int *)vptr) = (int)tempi;
+        else if ((*c == 'l') || (*c == 'L')) *((long *)vptr) = (long)tempi;
+        else if ((*c == 'h') || (*c == 'H')) *((short*)vptr) = (short)tempi;
+        else if ((*c == 'b') || (*c == 'B')) *((unsigned char *)vptr) = (unsigned char)tempi;
+        break;
+      case 'f': case 'F':
+      case 'd': case 'D':
+        if (Tcl_GetDoubleFromObj(interp,obj,&tempd) != TCL_OK) goto argerror;
+        if ((*c == 'f') || (*c == 'F')) *((float *) vptr) = (float)tempd;
+        else if ((*c == 'd') || (*c == 'D')) *((double*) vptr) = tempd;
+        break;
+      case 's': case 'S':
+        if (*(c+1) == '#') {
+          int *vlptr = (int *) va_arg(ap, void *);
+          *((char **) vptr) = Tcl_GetStringFromObj(obj, vlptr);
+          c++;
+        } else {
+          *((char **)vptr) = Tcl_GetStringFromObj(obj,NULL);
+        }
+        break;
+      case 'c': case 'C':
+        *((char *)vptr) = *(Tcl_GetStringFromObj(obj,NULL));
+        break;
+      case 'p': case 'P':
+        ty = (swig_type_info *) va_arg(ap, void *);
+        if (SWIG_Tcl_ConvertPtr(interp, obj, (void **) vptr, ty, 0) != SWIG_OK) goto argerror;
+        break;
+      case 'o': case 'O':
+        *((Tcl_Obj **)vptr) = objv[argno+1];
+        break;
+      default:
+        break;
+      }
+    }
+  }
+
+  if ((*c != ';') && ((objc-1) > argno)) {
+    Tcl_SetResult(interp, (char *) "Wrong # args.", TCL_STATIC);
+    goto argerror;
+  }
+  va_end(ap);
+  return TCL_OK;
+
+ argerror:
+  {
+    char temp[32];
+    sprintf(temp,"%d", argno+1);
+    c = strchr(fmt,':');
+    if (!c) c = strchr(fmt,';');
+    if (!c) c = (char *)"";
+    Tcl_AppendResult(interp,c," argument ", temp, NULL);
+    va_end(ap);
+    return TCL_ERROR;
+  }
+}
+
+#ifdef __cplusplus
+#if 0
+{ /* cc-mode */
+#endif
+}
+#endif
diff --git a/trunk/Lib/tcl/tclruntime.swg b/trunk/Lib/tcl/tclruntime.swg
new file mode 100644
index 0000000..bb4edd7
--- /dev/null
+++ b/trunk/Lib/tcl/tclruntime.swg
@@ -0,0 +1,15 @@
+/* tcl.h has to appear first */
+%insert(runtime) %{
+#include <stdio.h>
+#include <tcl.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+%}
+
+%insert(runtime) "swigrun.swg";         /* Common C API type-checking code */
+%insert(runtime) "swigerrors.swg"       /* SWIG errors */   
+%insert(runtime) "tclerrors.swg";       /* Tcl Errors */
+%insert(runtime) "tclapi.swg";          /* Tcl API */
+%insert(runtime) "tclrun.swg";          /* Tcl run-time code */
diff --git a/trunk/Lib/tcl/tclsh.i b/trunk/Lib/tcl/tclsh.i
new file mode 100644
index 0000000..2e8ed33
--- /dev/null
+++ b/trunk/Lib/tcl/tclsh.i
@@ -0,0 +1,88 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tclsh.i
+ *
+ * SWIG File for building new tclsh program
+ * ----------------------------------------------------------------------------- */
+
+#ifdef AUTODOC
+%subsection "tclsh.i"
+%text %{
+This module provides the Tcl_AppInit() function needed to build a 
+new version of the tclsh executable.   This file should not be used
+when using dynamic loading.   To make an interface file work with
+both static and dynamic loading, put something like this in your
+interface file :
+
+     #ifdef STATIC
+     %include <tclsh.i>
+     #endif
+%}
+#endif
+
+%{
+
+/* A TCL_AppInit() function that lets you build a new copy
+ * of tclsh.
+ *
+ * The macro SWIG_init contains the name of the initialization
+ * function in the wrapper file.
+ */
+
+#ifndef SWIG_RcFileName
+char *SWIG_RcFileName = "~/.myapprc";
+#endif
+
+
+#ifdef MAC_TCL
+extern int		MacintoshInit _ANSI_ARGS_((void));
+#endif
+
+int Tcl_AppInit(Tcl_Interp *interp){
+
+  if (Tcl_Init(interp) == TCL_ERROR) 
+    return TCL_ERROR;
+
+  /* Now initialize our functions */
+
+  if (SWIG_init(interp) == TCL_ERROR)
+    return TCL_ERROR;
+#if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 5
+   Tcl_SetVar(interp, (char *) "tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY);
+#else
+   tcl_RcFileName = SWIG_RcFileName;
+#endif
+#ifdef SWIG_RcRsrcName
+  Tcl_SetVar(interp, (char *) "tcl_rcRsrcName",SWIG_RcRsrcName,TCL_GLOBAL);
+#endif
+  
+  return TCL_OK;
+}
+
+#if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 4
+int main(int argc, char **argv) {
+#ifdef MAC_TCL
+    char *newArgv[2];
+    
+    if (MacintoshInit()  != TCL_OK) {
+	Tcl_Exit(1);
+    }
+
+    argc = 1;
+    newArgv[0] = "tclsh";
+    newArgv[1] = NULL;
+    argv = newArgv;
+#endif
+
+  Tcl_Main(argc, argv, Tcl_AppInit);
+  return(0);
+
+}
+#else
+extern int main();
+#endif
+
+%}
+
diff --git a/trunk/Lib/tcl/tclstrings.swg b/trunk/Lib/tcl/tclstrings.swg
new file mode 100644
index 0000000..540d627
--- /dev/null
+++ b/trunk/Lib/tcl/tclstrings.swg
@@ -0,0 +1,31 @@
+/* ------------------------------------------------------------
+ *  utility methods for char strings 
+ * ------------------------------------------------------------ */
+
+%fragment("SWIG_AsCharPtrAndSize","header") {
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(Tcl_Obj *obj, char** cptr, size_t* psize, int *alloc)
+{ 
+  int len = 0;
+  char *cstr = Tcl_GetStringFromObj(obj, &len);
+  if (cstr) {
+    if (cptr)  *cptr = cstr;
+    if (psize) *psize = len + 1;
+    if (alloc) *alloc = SWIG_OLDOBJ;
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+
+%fragment("SWIG_FromCharPtrAndSize","header",
+	  fragment="<limits.h>") {
+SWIGINTERNINLINE Tcl_Obj *
+SWIG_FromCharPtrAndSize(const char* carray, size_t size)
+{
+  return (size < INT_MAX) ? Tcl_NewStringObj(carray, %numeric_cast(size,int)) : NULL;
+}
+}
+
+
diff --git a/trunk/Lib/tcl/tcltypemaps.swg b/trunk/Lib/tcl/tcltypemaps.swg
new file mode 100644
index 0000000..7199e67
--- /dev/null
+++ b/trunk/Lib/tcl/tcltypemaps.swg
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------
+ *  Typemap specializations for Tcl
+ * ------------------------------------------------------------ */
+
+/* ------------------------------------------------------------
+ *  Fragment section
+ * ------------------------------------------------------------ */
+
+/*
+  in Tcl we need to pass the interp value, so, we define the decl/call
+  macros as needed.
+*/
+
+#define SWIG_AS_DECL_ARGS SWIG_TCL_DECL_ARGS_2
+#define SWIG_AS_CALL_ARGS SWIG_TCL_CALL_ARGS_2
+
+
+/* Include fundamental fragemt definitions */
+%include <typemaps/fragments.swg>
+
+/* Look for user fragments file. */
+%include <tclfragments.swg>
+
+/* Tcl fragments for primitve types */
+%include <tclprimtypes.swg>
+
+/* Tcl fragments for char* strings */
+%include <tclstrings.swg>
+
+
+/* ------------------------------------------------------------
+ *  Unified typemap section
+ * ------------------------------------------------------------ */
+
+/* No director supported in Tcl */
+#ifdef SWIG_DIRECTOR_TYPEMAPS
+#undef SWIG_DIRECTOR_TYPEMAPS
+#endif
+
+
+/* Tcl types */
+#define SWIG_Object                      Tcl_Obj *
+
+/* Overload of the output/constant/exception handling */
+
+/* output */
+#define %set_output(obj)                 Tcl_SetObjResult(interp,obj)
+
+/* append output */
+#define %append_output(obj)              Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp),obj)
+
+/* set constant */
+#define SWIG_SetConstant(name, obj)      SWIG_Tcl_SetConstantObj(interp, name, obj)
+
+/* raise */
+#define SWIG_Raise(obj,type,desc)        SWIG_Tcl_SetErrorObj(interp,type,obj)
+
+
+/* Include the unified typemap library */
+%include <typemaps/swigtypemaps.swg>
+
+
+/* ------------------------------------------------------------
+ *  Tcl extra typemaps
+ * ------------------------------------------------------------ */
+
+#if 1
+// Old 1.3.25 typemaps needed to avoid premature object deletion
+%typemap(out,noblock=1) SWIGTYPE *INSTANCE, SWIGTYPE &INSTANCE, SWIGTYPE INSTANCE[] {
+  Tcl_SetObjResult(interp, SWIG_NewInstanceObj( %as_voidptr($1), $1_descriptor,0));
+}
+
+%typemap(out) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC {
+  swig_type_info *ty = SWIG_TypeDynamicCast($1_descriptor,%as_voidptrptr(&$1));
+  Tcl_SetObjResult(interp,SWIG_NewInstanceObj(%as_voidptr($1), ty,0));
+}
+
+#endif
+
+%typemap(throws,noblock=1) SWIGTYPE CLASS {
+  SWIG_set_result(SWIG_NewInstanceObj(%as_voidptr(SWIG_new_copy($1, $1_ltype)), $&1_descriptor, 1));
+  SWIG_fail;
+}
+
+%typemap(out)    SWIGTYPE    =  SWIGTYPE INSTANCE;
+%typemap(out)    SWIGTYPE *  =  SWIGTYPE *INSTANCE;
+%typemap(out)    SWIGTYPE &  =  SWIGTYPE &INSTANCE;
+%typemap(out)    SWIGTYPE [] =  SWIGTYPE INSTANCE[];
+%typemap(varout) SWIGTYPE    =  SWIGTYPE INSTANCE;
diff --git a/trunk/Lib/tcl/tcluserdir.swg b/trunk/Lib/tcl/tcluserdir.swg
new file mode 100644
index 0000000..d5b41fb
--- /dev/null
+++ b/trunk/Lib/tcl/tcluserdir.swg
@@ -0,0 +1,5 @@
+/* -----------------------------------------------------------------------------
+ *  Special user directives
+ * ----------------------------------------------------------------------------- */
+
+
diff --git a/trunk/Lib/tcl/tclwstrings.swg b/trunk/Lib/tcl/tclwstrings.swg
new file mode 100644
index 0000000..2d344c2
--- /dev/null
+++ b/trunk/Lib/tcl/tclwstrings.swg
@@ -0,0 +1,70 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tclwstrings.wg
+ *
+ * Utility methods for wchar strings 
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <wchar.h>
+%}
+
+%fragment("SWIG_AsWCharPtrAndSize","header") {
+SWIGINTERN int
+SWIG_AsWCharPtrAndSize(Tcl_Obj *obj, wchar_t** cptr, size_t* psize, int *alloc)
+{ 
+  int len = 0;
+  Tcl_UniChar *ustr = Tcl_GetUnicodeFromObj(obj, &len);
+  if (ustr) {
+    if (cptr)  {
+      Tcl_Encoding encoding = NULL;
+      char *src = (char *) ustr;
+      int srcLen = (len)*sizeof(Tcl_UniChar);
+      int dstLen = sizeof(wchar_t)*(len + 1);
+      char *dst = %new_array(dstLen, char);
+      int flags = 0;
+      Tcl_EncodingState *statePtr = 0;
+      int srcRead = 0;
+      int dstWrote = 0;
+      int dstChars = 0;
+      Tcl_UtfToExternal(0, encoding, src, srcLen, flags, statePtr, dst,
+			dstLen, &srcRead, &dstWrote, &dstChars);
+      
+      if (alloc) *alloc = SWIG_NEWOBJ;
+    }
+    if (psize) *psize = len + 1;
+    return SWIG_OK;
+  }
+  return SWIG_TypeError;
+}
+}
+
+%fragment("SWIG_FromWCharPtrAndSize","header") {
+SWIGINTERNINLINE Tcl_Obj *
+SWIG_FromWCharPtrAndSize(const wchar_t* carray, size_t size)
+{
+  Tcl_Obj *res = NULL;
+  if (size < INT_MAX) {
+    Tcl_Encoding encoding = NULL;
+    char *src = (char *) carray;
+    int srcLen = (int)(size*sizeof(wchar_t));
+    int dstLen = (int)(size*sizeof(Tcl_UniChar));
+    char *dst = %new_array(dstLen, char);
+    int flags = 0;
+    Tcl_EncodingState *statePtr = 0;
+    int srcRead = 0;
+    int dstWrote = 0;
+    int dstChars = 0;
+    
+    Tcl_ExternalToUtf(0, encoding, src, srcLen, flags, statePtr, dst,
+		      dstLen, &srcRead, &dstWrote, &dstChars);
+    
+    res = Tcl_NewUnicodeObj((Tcl_UniChar*)dst, (int)size);
+    %delete_array(dst);
+  }
+  return res;
+}
+}
+
diff --git a/trunk/Lib/tcl/typemaps.i b/trunk/Lib/tcl/typemaps.i
new file mode 100644
index 0000000..7c9e04a
--- /dev/null
+++ b/trunk/Lib/tcl/typemaps.i
@@ -0,0 +1,467 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.i
+ *
+ * Swig typemap library for Tcl8.  This file contains various sorts
+ * of typemaps for modifying Swig's code generation.
+ * ----------------------------------------------------------------------------- */
+
+#if !defined(SWIG_USE_OLD_TYPEMAPS)
+%include <typemaps/typemaps.swg>
+#else
+
+/*
+The SWIG typemap library provides a language independent mechanism for
+supporting output arguments, input values, and other C function
+calling mechanisms.  The primary use of the library is to provide a
+better interface to certain C function--especially those involving
+pointers.
+*/
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+/*
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+
+         int            *INPUT
+         short          *INPUT
+         long           *INPUT
+         long long      *INPUT
+         unsigned int   *INPUT
+         unsigned short *INPUT
+         unsigned long  *INPUT
+         unsigned long long *INPUT
+         unsigned char  *INPUT
+         bool           *INPUT
+         float          *INPUT
+         double         *INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include typemaps.i
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+
+%typemap(in) double *INPUT(double temp), double &INPUT(double temp)
+{
+  if (Tcl_GetDoubleFromObj(interp,$input,&temp) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  $1 = &temp;
+}
+
+%typemap(in) float *INPUT(double dvalue, float  temp), float &INPUT(double dvalue, float temp) 
+{
+  if (Tcl_GetDoubleFromObj(interp,$input,&dvalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (float) dvalue;
+  $1 = &temp;
+}
+
+%typemap(in) int  *INPUT(int temp), int &INPUT(int temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&temp) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  $1 = &temp;
+}
+
+%typemap(in) short *INPUT(int ivalue, short temp), short &INPUT(int ivalue, short temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (short) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) long *INPUT(int ivalue, long temp), long &INPUT(int ivalue, long temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (long) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) unsigned int  *INPUT(int ivalue, unsigned int temp), 
+             unsigned int  &INPUT(int ivalue, unsigned int temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (unsigned int) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) unsigned short *INPUT(int ivalue, unsigned short temp),
+             unsigned short &INPUT(int ivalue, unsigned short temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (unsigned short) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) unsigned long *INPUT(int ivalue, unsigned long temp),
+             unsigned long &INPUT(int ivalue, unsigned long temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (unsigned long) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) unsigned char *INPUT(int ivalue, unsigned char temp),
+             unsigned char &INPUT(int ivalue, unsigned char temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (unsigned char) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) signed char *INPUT(int ivalue, signed char temp),
+             signed char &INPUT(int ivalue, signed char temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = (signed char) ivalue;
+  $1 = &temp;
+}
+
+%typemap(in) bool *INPUT(int ivalue, bool temp),
+             bool &INPUT(int ivalue, bool temp)
+{
+  if (Tcl_GetIntFromObj(interp,$input,&ivalue) == TCL_ERROR) {
+    SWIG_fail;
+  }
+  temp = ivalue ? true : false;
+  $1 = &temp;
+}
+
+%typemap(in) long long *INPUT($*1_ltype temp), 
+             long long &INPUT($*1_ltype temp)
+{
+  temp = ($*1_ltype) strtoll(Tcl_GetStringFromObj($input,NULL),0,0);
+  $1 = &temp;
+}
+
+%typemap(in) unsigned long long *INPUT($*1_ltype temp), 
+             unsigned long long &INPUT($*1_ltype temp)
+{
+  temp = ($*1_ltype) strtoull(Tcl_GetStringFromObj($input,NULL),0,0);
+  $1 = &temp;
+}
+  
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a list element.
+
+/*
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, they are returned in the form of a Tcl list.
+
+         int            *OUTPUT
+         short          *OUTPUT
+         long           *OUTPUT
+         long long      *OUTPUT
+         unsigned int   *OUTPUT
+         unsigned short *OUTPUT
+         unsigned long  *OUTPUT
+         unsigned long long *OUTPUT
+         unsigned char  *OUTPUT
+         bool           *OUTPUT
+         float          *OUTPUT
+         double         *OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters).K:
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include typemaps.i
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The Tcl output of the function would be a list containing both
+output values. 
+
+*/
+
+%typemap(in,numinputs=0)     int            *OUTPUT(int temp),
+                     short          *OUTPUT(short temp),
+                     long           *OUTPUT(long temp),
+                     unsigned int   *OUTPUT(unsigned int temp),
+                     unsigned short *OUTPUT(unsigned short temp),
+                     unsigned long  *OUTPUT(unsigned long temp),
+                     unsigned char  *OUTPUT(unsigned char temp),
+	             signed char    *OUTPUT(signed char temp),
+                     bool           *OUTPUT(bool temp),
+                     float          *OUTPUT(float temp),
+                     double         *OUTPUT(double temp),
+                     long long      *OUTPUT($*1_ltype temp),
+                     unsigned long long *OUTPUT($*1_ltype temp),
+	             int            &OUTPUT(int temp),
+                     short          &OUTPUT(short temp),
+                     long           &OUTPUT(long temp),
+                     unsigned int   &OUTPUT(unsigned int temp),
+                     unsigned short &OUTPUT(unsigned short temp),
+                     unsigned long  &OUTPUT(unsigned long temp),
+                     signed char    &OUTPUT(signed char temp),
+                     bool           &OUTPUT(bool temp),
+                     unsigned char  &OUTPUT(unsigned char temp),
+                     float          &OUTPUT(float temp),
+                     double         &OUTPUT(double temp),
+                     long long      &OUTPUT($*1_ltype temp),
+                     unsigned long long &OUTPUT($*1_ltype temp)
+"$1 = &temp;";
+
+%typemap(argout)     int     *OUTPUT, int &OUTPUT,
+                     short   *OUTPUT, short &OUTPUT,
+                     long    *OUTPUT, long &OUTPUT,
+                     unsigned int   *OUTPUT, unsigned int &OUTPUT,
+                     unsigned short *OUTPUT, unsigned short &OUTPUT,
+                     unsigned long  *OUTPUT, unsigned long &OUTPUT,
+                     unsigned char  *OUTPUT, unsigned char &OUTPUT,
+                     signed char    *OUTPUT, signed char  &OUTPUT,
+                     bool           *OUTPUT, bool &OUTPUT
+{
+  Tcl_Obj *o;
+  o = Tcl_NewIntObj((int) *($1));
+  Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp),o);
+}
+
+%typemap(argout) float    *OUTPUT, float &OUTPUT,
+                 double   *OUTPUT, double &OUTPUT
+{
+  Tcl_Obj *o;
+  o = Tcl_NewDoubleObj((double) *($1));
+  Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp),o);
+}
+
+%typemap(argout) long long *OUTPUT, long long &OUTPUT
+{
+  char temp[256];
+  Tcl_Obj *o;
+  sprintf(temp,"%lld",(long long)*($1));
+  o = Tcl_NewStringObj(temp,-1);
+  Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp),o);
+}
+
+%typemap(argout) unsigned long long *OUTPUT, unsigned long long &OUTPUT
+{
+  char temp[256];
+  Tcl_Obj *o;
+  sprintf(temp,"%llu",(unsigned long long)*($1));
+  o = Tcl_NewStringObj(temp,-1);
+  Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp),o);
+}
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a Tcl list.
+
+         int            *INOUT
+         short          *INOUT
+         long           *INOUT
+         long long      *INOUT
+         unsigned int   *INOUT
+         unsigned short *INOUT
+         unsigned long  *INOUT
+         unsigned long long *INOUT
+         unsigned char  *INOUT
+         bool           *INOUT
+         float          *INOUT
+         double         *INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include typemaps.i
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include typemaps.i
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+Unlike C, this mapping does not directly modify the input value (since
+this makes no sense in Tcl).  Rather, the modified input value shows
+up as the return value of the function.  Thus, to apply this function
+to a Tcl variable you might do this :
+
+       set x [neg $x]
+
+*/
+
+
+%typemap(in) int *INOUT = int *INPUT;
+%typemap(in) short *INOUT = short *INPUT;
+%typemap(in) long *INOUT = long *INPUT;
+%typemap(in) unsigned int *INOUT = unsigned int *INPUT;
+%typemap(in) unsigned short *INOUT = unsigned short *INPUT;
+%typemap(in) unsigned long *INOUT = unsigned long *INPUT;
+%typemap(in) unsigned char *INOUT = unsigned char *INPUT;
+%typemap(in) signed char *INOUT = signed char *INPUT;
+%typemap(in) bool *INOUT = bool *INPUT;
+%typemap(in) float *INOUT = float *INPUT;
+%typemap(in) double *INOUT = double *INPUT;
+%typemap(in) long long *INOUT = long long *INPUT;
+%typemap(in) unsigned long long *INOUT = unsigned long long *INPUT;
+
+%typemap(in) int &INOUT = int &INPUT;
+%typemap(in) short &INOUT = short &INPUT;
+%typemap(in) long &INOUT = long &INPUT;
+%typemap(in) unsigned int &INOUT = unsigned int &INPUT;
+%typemap(in) unsigned short &INOUT = unsigned short &INPUT;
+%typemap(in) unsigned long &INOUT = unsigned long &INPUT;
+%typemap(in) unsigned char &INOUT = unsigned char &INPUT;
+%typemap(in) signed char &INOUT = signed char &INPUT;
+%typemap(in) bool &INOUT = bool &INPUT;
+%typemap(in) float &INOUT = float &INPUT;
+%typemap(in) double &INOUT = double &INPUT;
+%typemap(in) long long &INOUT = long long &INPUT;
+%typemap(in) unsigned long long &INOUT = unsigned long long &INPUT;
+
+%typemap(argout) int *INOUT = int *OUTPUT;
+%typemap(argout) short *INOUT = short *OUTPUT;
+%typemap(argout) long *INOUT = long *OUTPUT;
+%typemap(argout) unsigned int *INOUT = unsigned int *OUTPUT;
+%typemap(argout) unsigned short *INOUT = unsigned short *OUTPUT;
+%typemap(argout) unsigned long *INOUT = unsigned long *OUTPUT;
+%typemap(argout) unsigned char *INOUT = unsigned char *OUTPUT;
+%typemap(argout) signed char *INOUT = signed char *OUTPUT;
+%typemap(argout) bool *INOUT = bool *OUTPUT;
+%typemap(argout) float *INOUT = float *OUTPUT;
+%typemap(argout) double *INOUT = double *OUTPUT;
+%typemap(argout) long long *INOUT = long long *OUTPUT;
+%typemap(argout) unsigned long long *INOUT = unsigned long long *OUTPUT;
+
+%typemap(argout) int &INOUT = int &OUTPUT;
+%typemap(argout) short &INOUT = short &OUTPUT;
+%typemap(argout) long &INOUT = long &OUTPUT;
+%typemap(argout) unsigned int &INOUT = unsigned int &OUTPUT;
+%typemap(argout) unsigned short &INOUT = unsigned short &OUTPUT;
+%typemap(argout) unsigned long &INOUT = unsigned long &OUTPUT;
+%typemap(argout) unsigned char &INOUT = unsigned char &OUTPUT;
+%typemap(argout) signed char &INOUT = signed char &OUTPUT;
+%typemap(argout) bool &INOUT = bool &OUTPUT;
+%typemap(argout) float &INOUT = float &OUTPUT;
+%typemap(argout) double &INOUT = double &OUTPUT;
+%typemap(argout) long long &INOUT = long long &OUTPUT;
+%typemap(argout) unsigned long long &INOUT = unsigned long long &OUTPUT;
+
+
+/* Overloading information */
+
+%typemap(typecheck) double *INPUT = double;
+%typemap(typecheck) bool *INPUT = bool;
+%typemap(typecheck) signed char *INPUT = signed char;
+%typemap(typecheck) unsigned char *INPUT = unsigned char;
+%typemap(typecheck) unsigned long *INPUT = unsigned long;
+%typemap(typecheck) unsigned short *INPUT = unsigned short;
+%typemap(typecheck) unsigned int *INPUT = unsigned int;
+%typemap(typecheck) long *INPUT = long;
+%typemap(typecheck) short *INPUT = short;
+%typemap(typecheck) int *INPUT = int;
+%typemap(typecheck) float *INPUT = float;
+%typemap(typecheck) long long *INPUT = long long;
+%typemap(typecheck) unsigned long long *INPUT = unsigned long long;
+
+%typemap(typecheck) double &INPUT = double;
+%typemap(typecheck) bool &INPUT = bool;
+%typemap(typecheck) signed char &INPUT = signed char;
+%typemap(typecheck) unsigned char &INPUT = unsigned char;
+%typemap(typecheck) unsigned long &INPUT = unsigned long;
+%typemap(typecheck) unsigned short &INPUT = unsigned short;
+%typemap(typecheck) unsigned int &INPUT = unsigned int;
+%typemap(typecheck) long &INPUT = long;
+%typemap(typecheck) short &INPUT = short;
+%typemap(typecheck) int &INPUT = int;
+%typemap(typecheck) float &INPUT = float;
+%typemap(typecheck) long long &INPUT = long long;
+%typemap(typecheck) unsigned long long &INPUT = unsigned long long;
+
+%typemap(typecheck) double *INOUT = double;
+%typemap(typecheck) bool *INOUT = bool;
+%typemap(typecheck) signed char *INOUT = signed char;
+%typemap(typecheck) unsigned char *INOUT = unsigned char;
+%typemap(typecheck) unsigned long *INOUT = unsigned long;
+%typemap(typecheck) unsigned short *INOUT = unsigned short;
+%typemap(typecheck) unsigned int *INOUT = unsigned int;
+%typemap(typecheck) long *INOUT = long;
+%typemap(typecheck) short *INOUT = short;
+%typemap(typecheck) int *INOUT = int;
+%typemap(typecheck) float *INOUT = float;
+%typemap(typecheck) long long *INOUT = long long;
+%typemap(typecheck) unsigned long long *INOUT = unsigned long long;
+
+%typemap(typecheck) double &INOUT = double;
+%typemap(typecheck) bool &INOUT = bool;
+%typemap(typecheck) signed char &INOUT = signed char;
+%typemap(typecheck) unsigned char &INOUT = unsigned char;
+%typemap(typecheck) unsigned long &INOUT = unsigned long;
+%typemap(typecheck) unsigned short &INOUT = unsigned short;
+%typemap(typecheck) unsigned int &INOUT = unsigned int;
+%typemap(typecheck) long &INOUT = long;
+%typemap(typecheck) short &INOUT = short;
+%typemap(typecheck) int &INOUT = int;
+%typemap(typecheck) float &INOUT = float;
+%typemap(typecheck) long long &INOUT = long long;
+%typemap(typecheck) unsigned long long &INOUT = unsigned long long;
+
+#endif
+
+// --------------------------------------------------------------------
+// Special types
+// --------------------------------------------------------------------
+
+%include <tclinterp.i>
+%include <tclresult.i>
diff --git a/trunk/Lib/tcl/wish.i b/trunk/Lib/tcl/wish.i
new file mode 100644
index 0000000..077ded6
--- /dev/null
+++ b/trunk/Lib/tcl/wish.i
@@ -0,0 +1,149 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * wish.i
+ *
+ * SWIG File for making wish
+ * ----------------------------------------------------------------------------- */
+
+#ifdef AUTODOC
+%subsection "wish.i"
+%text %{
+This module provides the Tk_AppInit() function needed to build a 
+new version of the wish executable.   Like tclsh.i, this file should
+not be used with dynamic loading.  To make an interface file work with
+both static and dynamic loading, put something like this in your
+interface file :
+
+     #ifdef STATIC
+     %include <wish.i>
+     #endif
+
+A startup file may be specified by defining the symbol SWIG_RcFileName
+as follows (this should be included in a code-block) :
+
+     #define SWIG_RcFileName    "~/.mywishrc"
+%}
+#endif
+
+%{
+
+
+/* Initialization code for wish */
+
+#include <tk.h>
+
+#ifndef SWIG_RcFileName
+char *SWIG_RcFileName = "~/.wishrc";
+#endif
+
+#ifdef MAC_TCL
+extern int	MacintoshInit _ANSI_ARGS_((void));
+extern int	SetupMainInterp _ANSI_ARGS_((Tcl_Interp *interp));
+#endif
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * Tcl_AppInit --
+ *
+ *	This procedure performs application-specific initialization.
+ *	Most applications, especially those that incorporate additional
+ *	packages, will have their own version of this procedure.
+ *
+ * Results:
+ *	Returns a standard Tcl completion code, and leaves an error
+ *	message in interp->result if an error occurs.
+ *
+ * Side effects:
+ *	Depends on the startup script.
+ *
+ *----------------------------------------------------------------------
+ */
+
+int Tcl_AppInit(Tcl_Interp *interp)
+{
+#ifndef MAC_TCL
+    Tk_Window main;
+    main = Tk_MainWindow(interp);
+#endif
+    /*
+     * Call the init procedures for included packages.  Each call should
+     * look like this:
+     *
+     * if (Mod_Init(interp) == TCL_ERROR) {
+     *     return TCL_ERROR;
+     * }
+     *
+     * where "Mod" is the name of the module.
+     */
+
+    if (Tcl_Init(interp) == TCL_ERROR) {
+	return TCL_ERROR;
+    }
+
+    if (Tk_Init(interp) == TCL_ERROR) {
+	return TCL_ERROR;
+    }
+
+    /*
+     * Call Tcl_CreateCommand for application-specific commands, if
+     * they weren't already created by the init procedures called above.
+     */
+
+    if (SWIG_init(interp) == TCL_ERROR) {
+      return TCL_ERROR;
+    }
+    
+#ifdef MAC_TCL
+    SetupMainInterp(interp);
+#endif
+        
+    /*
+     * Specify a user-specific startup file to invoke if the application
+     * is run interactively.  Typically the startup file is "~/.apprc"
+     * where "app" is the name of the application.  If this line is deleted
+     * then no user-specific startup file will be run under any conditions.
+     */
+
+#if TCL_MAJOR_VERSION >= 8 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 5
+   Tcl_SetVar(interp, (char *) "tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY);
+#else
+   tcl_RcFileName = SWIG_RcFileName;
+#endif
+
+/* For Macintosh might also want this */
+
+#ifdef MAC_TCL
+#ifdef SWIG_RcRsrcName
+    Tcl_SetVar(interp, (char *) "tcl_rcRsrcName",SWIG_RcRsrcName,TCL_GLOBAL_ONLY);
+#endif
+#endif
+    return TCL_OK;
+}
+
+#if TK_MAJOR_VERSION >= 4
+int main(int argc, char **argv) {
+
+#ifdef MAC_TCL
+  char *newArgv[2];
+  if (MacintoshInit() != TCL_OK) {
+      Tcl_Exit(1);
+  }
+  argc = 1;
+  newArgv[0] = "Wish";
+  newArgv[1] = NULL;
+  argv = newArgv;
+#endif
+  Tk_Main(argc, argv, Tcl_AppInit);
+  return(0);
+}
+#else
+extern int main();
+#endif
+
+%}
+
+
+
diff --git a/trunk/Lib/typemaps/README b/trunk/Lib/typemaps/README
new file mode 100644
index 0000000..6513457
--- /dev/null
+++ b/trunk/Lib/typemaps/README
@@ -0,0 +1,54 @@
+Still in development, but if you are interested into looking around,
+start with
+
+
+     swigtypemaps.swg
+
+which is the head file. Also read the docs for %fragments in 
+
+     fragments.swg 
+
+and follow the definitions in one of the supported languages:
+
+     python, perl, ruby, tcl
+
+
+
+
+/* -----------------------------------------------------------------------------
+ *  Internal typemap specializations
+ * ----------------------------------------------------------------------------- */
+
+
+carrays.swg		Implement the carrays.i library
+cdata.swg		Implement the cdata.i library
+cmalloc.swg		Implement the cmalloc.i library
+cpointer.swg		Implement the cpointer.i library
+cstring.swg		Implement the cstring.i library typemaps for char *
+cwstring.swg		Implement the cstring.i library typemaps for wchar_t *
+exception.swg		Implement the exception.i library
+implicit.swg		Allow the use of implicit C++ constructors
+
+string.swg		Typemaps for char * string
+wstring.swg		Typemaps for wchar_t * string
+std_string.swg		Typemaps for std::string
+std_wstring.swg		Typemaps for std::wstring
+swigtype.swg		Typemaps for the SWIGTYPE type
+void.swg		Typemaps for the 'void' type
+enumint.swg		Typemaps for enums treated as 'int' 
+swigobject.swg		Typemaps for the SWIG_Object as in PyObject, Tcl_Obj, etc.
+misctypes.swg		Typemaps for miscellaneos types (size_t, ptrdiff_t, etc)
+ptrtypes.swg		Typemaps for types with a 'ptr' behavior
+valtypes.swg		Typemaps for 'by value' types
+inoutlist.swg		IN/OUTPUT/INOUT typemaps, where the OUTPUT values are returned in a list
+primtypes.swg		Common macros to manage primitive types (short,int,double,etc)
+
+cstrings.swg		Common macros to implemented the cstring/cwstring libraries
+std_strings.swg		Common macros to implemented the std::string/std::wstring typemaps
+strings.swg		Common macros and typemaps for string and wstring (char *, wchar_t *)
+
+swigmacros.swg		Basic macros 
+fragments.swg		Macros for fragment manipulations
+
+
+typemaps.swg		The old typemaps.i library, not needed anymore
diff --git a/trunk/Lib/typemaps/attribute.swg b/trunk/Lib/typemaps/attribute.swg
new file mode 100644
index 0000000..f6335be
--- /dev/null
+++ b/trunk/Lib/typemaps/attribute.swg
@@ -0,0 +1,205 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * attribute.swg
+ *
+ * Attribute implementation
+ * ----------------------------------------------------------------------------- */
+
+/*
+  The following macros convert a pair of set/get methods
+  into a "native" attribute.
+
+  Use %attribute when you have a pair of get/set methods
+  like in:
+
+      %attribute(A, int, a, get_a, set_a);
+
+      struct A
+      {
+        int get_a() const;
+        void set_a(int aa);
+      };
+
+  If you don't provide a 'set' method, a 'read-only' attribute
+  is generated, ie, like in:
+
+      %attribute(A, int, c, get_c);
+
+  Use %attributeref when you have const/non-const reference
+  access methods, like in:
+
+      %attributeref(A, int, b);
+
+      struct A
+      {
+        const int& b() const;
+        int& b();
+      };
+
+      %attributeref(B, int, c);
+
+      struct B
+      {
+        int& c();
+      };
+
+  You can also use
+
+      %attributeref(Class, AttributeType, AttributeName, AccessorMethod)
+
+  if the internal C++ reference methods have a different name from the
+  attribute you want, so
+
+      %attributeref(B, int, d, c);
+
+  is the same as the last example, but instead of the attribute 'c' being
+  called 'c', it is called 'd'.
+
+  Now you can use the attributes like so:
+
+      x = A()
+      x.a = 3        # calls A::set_a
+      print x.a      # calls A::get_a
+
+      x.b = 3        # calls A::b()
+      print x.b      # calls A::b() const
+
+  Use %attribute2 instead of %attribute to indicate that reference-pointer
+  translation is required. You use %attribute2 instead of %attribute in
+  cases like this:
+ 
+  %attribute2(MyClass, MyFoo, Foo, GetFoo, SetFoo);
+  %inline %{
+    struct MyFoo { 
+      int x;
+    };
+    class MyClass {
+      MyFoo foo;
+    public:
+      MyFoo& GetFoo() { return foo; }
+      void SetFoo(const MyFoo& other) { foo = other; }
+    };
+  %}
+
+  Here, the data type of the property is a wrapped type (MyFoo) and on the
+  C++ side it is passed by reference. The problem is that the SWIG wrapper will
+  pass around a pointer (MyFoo *) which is not compatible with the reference
+  type of the accessors (MyFoo &). Therefore, if you use %attribute, you'll get
+  an error from your C/C++ compiler. %attribute2 translates between a pointer
+  and a reference to eliminate the error. In case you're confused, let's make it
+  simple: just use %attribute at first, but if the C/C++ compiler gives an error
+  while compiling the wrapper, try %attribute2 instead.
+
+  NOTE: remember that if the type contains commas, such as 'std::pair<int,int>',
+  you need to use the macro like:
+
+  %attributeref(A, %arg(std::pair<int,int>), pval);
+
+  where %arg() 'normalizes' the type to be understood as a single
+  argument, otherwise the macro will get confused by the comma.
+*/
+
+//
+// Define SWIG_ATTRIBUTE_TEMPLATE if you want to use templates instead of macros for the C++ get and set wrapper methods
+// Does not always generate compileable code, use at your peril!
+//
+//#define SWIG_ATTRIBUTE_TEMPLATE
+
+%define %attribute_custom(Class, AttributeType, AttributeName, GetMethod, SetMethod, GetMethodCall, SetMethodCall)
+  %ignore Class::GetMethod();
+  %ignore Class::GetMethod() const;
+  #if #SetMethod != #AttributeName
+    %ignore Class::SetMethod;
+  #endif
+  %extend Class {
+    AttributeType AttributeName;
+  }
+#if defined(__cplusplus) && defined(SWIG_ATTRIBUTE_TEMPLATE)
+  %{
+    template < class C > inline AttributeType %mangle(Class) ##_## AttributeName ## _get(const C* self_) {
+      return GetMethodCall;
+    }
+    template < class C > inline AttributeType %mangle(Class) ##_## AttributeName ## _get(C* self_) {
+      return GetMethodCall;
+    }
+    template < class C > inline void %mangle(Class) ##_## AttributeName ## _set(C* self_, AttributeType val_) {
+      SetMethodCall;
+    }
+  %}
+#else
+  %{
+    #define %mangle(Class) ##_## AttributeName ## _get(self_) GetMethodCall
+    #define %mangle(Class) ##_## AttributeName ## _set(self_, val_) SetMethodCall
+  %}
+#endif
+%enddef
+
+%define %attribute_readonly(Class, AttributeType, AttributeName, GetMethod, GetMethodCall)
+  %ignore Class::GetMethod();
+  %ignore Class::GetMethod() const;
+  %immutable Class::AttributeName;
+  %extend Class {
+    AttributeType AttributeName;
+  }
+#if defined(__cplusplus) && defined(SWIG_ATTRIBUTE_TEMPLATE)
+  %{
+    template < class C > inline AttributeType %mangle(Class) ##_## AttributeName ## _get(const C* self_) {
+      return GetMethodCall;
+    }
+    template < class C > inline AttributeType %mangle(Class) ##_## AttributeName ## _get(C* self_) {
+      return GetMethodCall;
+    }
+  %}
+#else
+  %{
+    #define %mangle(Class) ##_## AttributeName ## _get(self_) GetMethodCall
+  %}
+#endif
+%enddef
+
+
+// User macros
+
+%define %attribute(Class, AttributeType, AttributeName, GetMethod, SetMethod...)
+  #if #SetMethod != ""
+    %attribute_custom(Class, AttributeType, AttributeName, GetMethod, SetMethod, self_->GetMethod(), self_->SetMethod(val_))
+  #else
+    %attribute_readonly(Class, AttributeType, AttributeName, GetMethod, self_->GetMethod())
+  #endif
+%enddef
+
+%define %attribute2(Class, AttributeType, AttributeName, GetMethod, SetMethod...)
+  #if #SetMethod != ""
+    %attribute_custom(Class, AttributeType, AttributeName, GetMethod, SetMethod, &self_->GetMethod(), self_->SetMethod(*val_))
+  #else
+    %attribute_readonly(Class, AttributeType, AttributeName, GetMethod, &self_->GetMethod())
+  #endif
+%enddef
+
+%define %attributeref(Class, AttributeType, AttributeName, AccessorMethod...)
+  #if #AccessorMethod != ""
+    %attribute_custom(Class, AttributeType, AttributeName, AccessorMethod, AccessorMethod, self_->AccessorMethod(), self_->AccessorMethod() = val_)
+  #else
+    %attribute_custom(Class, AttributeType, AttributeName, AttributeName, AttributeName, self_->AttributeName(), self_->AttributeName() = val_)
+  #endif
+%enddef
+
+%define %attribute2ref(Class, AttributeType, AttributeName, AccessorMethod...)
+  #if #AccessorMethod != ""
+    %attribute_custom(Class, AttributeType, AttributeName, AccessorMethod, AccessorMethod, &self_->AccessorMethod(), self_->AccessorMethod() = *val_)
+  #else
+    %attribute_custom(Class, AttributeType, AccessorMethod, AccessorMethod, AccessorMethod, &self_->AccessorMethod(), self_->AccessorMethod() = *val_)
+  #endif
+%enddef
+
+// deprecated (same as %attributeref, but there is an argument order inconsistency)
+%define %attribute_ref(Class, AttributeType, AccessorMethod, AttributeName...)
+  #if #AttributeName != ""
+    %attribute_custom(Class, AttributeType, AttributeName, AccessorMethod, AccessorMethod, self_->AccessorMethod(), self_->AccessorMethod() = val_)
+  #else
+    %attribute_custom(Class, AttributeType, AccessorMethod, AccessorMethod, AccessorMethod, self_->AccessorMethod(), self_->AccessorMethod() = val_)
+  #endif
+%enddef
+
diff --git a/trunk/Lib/typemaps/carrays.swg b/trunk/Lib/typemaps/carrays.swg
new file mode 100644
index 0000000..27ca117
--- /dev/null
+++ b/trunk/Lib/typemaps/carrays.swg
@@ -0,0 +1,117 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * carrays.swg
+ *
+ * This library file contains macros that can be used to manipulate simple
+ * pointers as arrays.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * %array_functions(TYPE,NAME)
+ *
+ * Generates functions for creating and accessing elements of a C array
+ * (as pointers).  Creates the following functions:
+ *
+ *        TYPE *new_NAME(int nelements)
+ *        void delete_NAME(TYPE *);
+ *        TYPE NAME_getitem(TYPE *, int index);
+ *        void NAME_setitem(TYPE *, int index, TYPE value);
+ * 
+ * ----------------------------------------------------------------------------- */
+
+%define %array_functions(TYPE,NAME) 
+%{
+  static TYPE *new_##NAME(size_t nelements) { 
+    return %new_array(nelements, TYPE);
+  }
+
+  static void delete_##NAME(TYPE *ary) {
+    %delete_array(ary);
+  }
+
+  static TYPE NAME##_getitem(TYPE *ary, size_t index) {
+    return ary[index];
+  }
+  static void NAME##_setitem(TYPE *ary, size_t index, TYPE value) {
+    ary[index] = value;
+  }
+%}
+
+TYPE *new_##NAME(size_t nelements);
+void delete_##NAME(TYPE *ary);
+TYPE NAME##_getitem(TYPE *ary, size_t index);
+void NAME##_setitem(TYPE *ary, size_t index, TYPE value);
+
+%enddef
+
+
+/* -----------------------------------------------------------------------------
+ * %array_class(TYPE,NAME)
+ *
+ * Generates a class wrapper around a C array.  The class has the following
+ * interface:
+ *
+ *          struct NAME {
+ *              NAME(int nelements);
+ *             ~NAME();
+ *              TYPE getitem(int index);
+ *              void setitem(int index, TYPE value);
+ *              TYPE * cast();
+ *              static NAME *frompointer(TYPE *t);
+ *         }
+ *
+ * Use
+ *
+ *    %array_class_wrap(TYPE,NAME,GET,SET) 
+ *
+ * if you want  different names for the get/set methods.
+ * ----------------------------------------------------------------------------- */
+
+%define %array_class_wrap(TYPE,NAME,getitem,setitem)
+%{
+typedef TYPE NAME;
+%}
+
+
+typedef struct NAME {
+} NAME;
+
+%extend NAME {
+
+  NAME(size_t nelements) {
+    return %new_array(nelements, TYPE);
+  }
+
+  ~NAME() {
+    %delete_array(self);
+  }
+  
+  TYPE getitem(size_t index) {
+    return self[index];
+  }
+
+  void setitem(size_t index, TYPE value) {
+    self[index] = value;
+  }
+
+  TYPE * cast() {
+    return self;
+  }
+
+  static NAME *frompointer(TYPE *t) {
+    return %static_cast(t, NAME *);
+  }
+};
+
+%types(NAME = TYPE);
+
+%enddef
+
+
+#ifndef %array_class
+%define %array_class(TYPE,NAME)
+  %array_class_wrap(TYPE,NAME,getitem,setitem)
+%enddef
+#endif
diff --git a/trunk/Lib/typemaps/cdata.swg b/trunk/Lib/typemaps/cdata.swg
new file mode 100644
index 0000000..32b3f5a
--- /dev/null
+++ b/trunk/Lib/typemaps/cdata.swg
@@ -0,0 +1,78 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cdata.swg
+ *
+ * This library file contains macros for manipulating raw C data as strings.
+ * ----------------------------------------------------------------------------- */
+
+%{
+typedef struct SWIGCDATA {
+    char *data;
+    size_t   len;
+} SWIGCDATA;
+%}
+
+/* -----------------------------------------------------------------------------
+ * Typemaps for returning binary data
+ * ----------------------------------------------------------------------------- */
+
+%typemap(out,noblock=1,fragment="SWIG_FromCharPtrAndSize") SWIGCDATA {
+  %set_output(SWIG_FromCharPtrAndSize($1.data,$1.len));
+}
+%typemap(in) (const void *indata, int inlen) = (char *STRING, int SIZE);
+
+
+/* -----------------------------------------------------------------------------
+ * %cdata(TYPE [, NAME]) 
+ *
+ * Convert raw C data to a binary string.
+ * ----------------------------------------------------------------------------- */
+
+%define %cdata(TYPE,NAME...)
+
+%insert("header") {
+#ifdef __cplusplus
+extern "C"  {    
+#endif
+#if #NAME == ""
+static SWIGCDATA cdata_##TYPE(TYPE *ptr, size_t nelements)
+#else
+static SWIGCDATA cdata_##NAME(TYPE *ptr, size_t nelements)
+#endif
+{
+  SWIGCDATA d;
+  d.data = (char *) ptr;
+#if #TYPE != "void"
+  d.len  = nelements*sizeof(TYPE);
+#else
+  d.len  = nelements;
+#endif
+   return d;
+}
+#ifdef __cplusplus
+}
+#endif 
+}
+
+#ifdef __cplusplus
+extern "C"
+#endif
+#if #NAME == ""
+SWIGCDATA cdata_##TYPE(TYPE *ptr, size_t nelements = 1);
+#else
+SWIGCDATA cdata_##NAME(TYPE *ptr, size_t nelements = 1);
+#endif
+%enddef
+
+%rename(cdata) ::cdata_void(void *ptr, size_t nelements = 1);
+
+%cdata(void);
+
+/* Memory move function */
+void memmove(void *data, const void *indata, size_t inlen);
+
+
+
+
diff --git a/trunk/Lib/typemaps/cmalloc.swg b/trunk/Lib/typemaps/cmalloc.swg
new file mode 100644
index 0000000..15f9629
--- /dev/null
+++ b/trunk/Lib/typemaps/cmalloc.swg
@@ -0,0 +1,113 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cmalloc.swg
+ *
+ * This library file contains macros that can be used to create objects using
+ * the C malloc function.
+ * ----------------------------------------------------------------------------- */
+
+%{
+#include <stdlib.h>
+%}
+
+/* %malloc(TYPE [, NAME = TYPE])
+   %calloc(TYPE [, NAME = TYPE])
+   %realloc(TYPE [, NAME = TYPE])
+   %free(TYPE [, NAME = TYPE])
+   %allocators(TYPE [,NAME = TYPE])
+
+   Creates functions for allocating/reallocating memory.
+
+   TYPE *malloc_NAME(size_t nbytes = sizeof(TYPE);
+   TYPE *calloc_NAME(size_t nobj=1, size_t size=sizeof(TYPE));
+   TYPE *realloc_NAME(TYPE *ptr, size_t nbytes);
+   void free_NAME(TYPE *ptr);
+
+*/
+
+%define %malloc(TYPE,NAME...)
+#if #NAME != ""
+%rename(malloc_##NAME) ::malloc(size_t nbytes);
+#else
+%rename(malloc_##TYPE) ::malloc(size_t nbytes);
+#endif
+
+#if #TYPE != "void"
+%typemap(default) size_t nbytes "$1 = (size_t) sizeof(TYPE);"
+#endif
+TYPE *malloc(size_t nbytes);
+%typemap(default) size_t nbytes;
+%enddef
+
+%define %calloc(TYPE,NAME...)
+#if #NAME != ""
+%rename(calloc_##NAME) ::calloc(size_t nobj, size_t sz);
+#else
+%rename(calloc_##TYPE) ::calloc(size_t nobj, size_t sz);
+#endif
+#if #TYPE != "void"
+%typemap(default) size_t sz "$1 = (size_t) sizeof(TYPE);"
+#else
+%typemap(default) size_t sz "$1 = 1;"
+#endif
+%typemap(default) size_t nobj "$1 = 1;"
+TYPE *calloc(size_t nobj, size_t sz);
+%typemap(default) size_t sz;
+%typemap(default) size_t nobj;
+%enddef
+
+%define %realloc(TYPE,NAME...)
+%insert("header") {
+#if #NAME != ""
+TYPE *realloc_##NAME(TYPE *ptr, size_t nitems)
+#else
+TYPE *realloc_##TYPE(TYPE *ptr, size_t nitems)
+#endif
+{
+#if #TYPE != "void"
+return (TYPE *) realloc(ptr, nitems*sizeof(TYPE));
+#else
+return (TYPE *) realloc(ptr, nitems);
+#endif
+}
+}
+#if #NAME != ""
+TYPE *realloc_##NAME(TYPE *ptr, size_t nitems);
+#else
+TYPE *realloc_##TYPE(TYPE *ptr, size_t nitems);
+#endif
+%enddef
+
+%define %free(TYPE,NAME...)
+#if #NAME != ""
+%rename(free_##NAME) ::free(TYPE *ptr);
+#else
+%rename(free_##TYPE) ::free(TYPE *ptr);
+#endif
+void free(TYPE *ptr);
+%enddef
+
+%define %sizeof(TYPE,NAME...)
+#if #NAME != ""
+%constant size_t sizeof_##NAME = sizeof(TYPE);
+#else
+%constant size_t sizeof_##TYPE = sizeof(TYPE);
+#endif
+%enddef
+
+%define %allocators(TYPE,NAME...)
+%malloc(TYPE,NAME)
+%calloc(TYPE,NAME)
+%realloc(TYPE,NAME)
+%free(TYPE,NAME)
+#if #TYPE != "void"
+%sizeof(TYPE,NAME)
+#endif
+%enddef
+
+
+
+
+
diff --git a/trunk/Lib/typemaps/cpointer.swg b/trunk/Lib/typemaps/cpointer.swg
new file mode 100644
index 0000000..ce1af16
--- /dev/null
+++ b/trunk/Lib/typemaps/cpointer.swg
@@ -0,0 +1,160 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cpointer.swg
+ *
+ * This library file contains macros that can be used to manipulate simple
+ * pointer objects.
+ *
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * %pointer_class(type,name)
+ *
+ * Places a simple proxy around a simple type like 'int', 'float', or whatever.
+ * The proxy provides this interface:
+ *
+ *       class type {
+ *       public:
+ *           type();
+ *          ~type();
+ *           type value();
+ *           void assign(type value);
+ *       };
+ *         
+ * Example:
+ *
+ *    %pointer_class(int, intp);
+ *
+ *    int add(int *x, int *y) { return *x + *y; }
+ *
+ * In python (with proxies)
+ *
+ *    >>> a = intp()
+ *    >>> a.assign(10)
+ *    >>> a.value()
+ *    10
+ *    >>> b = intp()
+ *    >>> b.assign(20)
+ *    >>> print add(a,b)
+ *    30
+ *
+ * As a general rule, this macro should not be used on class/structures that
+ * are already defined in the interface.
+ * ----------------------------------------------------------------------------- */
+
+
+%define %pointer_class(TYPE, NAME)
+%{
+typedef TYPE NAME;
+%}
+
+typedef struct {
+} NAME;
+
+%extend NAME {
+  NAME() {
+    return %new_instance(TYPE);
+  }
+  ~NAME() {
+    if (self) %delete(self);
+  }
+}
+
+%extend NAME {
+
+  void assign(TYPE value) {
+    *self = value;
+  }
+  TYPE value() {
+    return *self;
+  }
+  TYPE * cast() {
+    return self;
+  }
+  static NAME * frompointer(TYPE *t) {
+    return (NAME *) t;
+  }
+}
+
+%types(NAME = TYPE);
+
+%enddef
+
+/* ----------------------------------------------------------------------------- 
+ * %pointer_functions(type,name)
+ *
+ * Create functions for allocating/deallocating pointers.   This can be used
+ * if you don't want to create a proxy class or if the pointer is complex.
+ *
+ *    %pointer_functions(int, intp)
+ *
+ *    int add(int *x, int *y) { return *x + *y; }
+ *
+ * In python (with proxies)
+ *
+ *    >>> a = copy_intp(10)
+ *    >>> intp_value(a)
+ *    10
+ *    >>> b = new_intp()
+ *    >>> intp_assign(b,20)
+ *    >>> print add(a,b)
+ *    30
+ *    >>> delete_intp(a)
+ *    >>> delete_intp(b)
+ * 
+ * ----------------------------------------------------------------------------- */
+
+%define %pointer_functions(TYPE,NAME)
+%{
+  static TYPE *new_##NAME() { 
+    return %new_instance(TYPE);
+  }
+  
+  static TYPE *copy_##NAME(TYPE value) { 
+    return %new_copy(value, TYPE);
+  }
+
+  static void delete_##NAME(TYPE *self) { 
+    if (self) %delete(self);
+  }
+
+  static void NAME ##_assign(TYPE *self, TYPE value) {
+    *self = value;
+  }
+
+  static TYPE NAME ##_value(TYPE *self) {
+    return *self;
+  }
+%}
+
+TYPE *new_##NAME();
+TYPE *copy_##NAME(TYPE value);
+void  delete_##NAME(TYPE *self);
+void  NAME##_assign(TYPE *self, TYPE value);
+TYPE  NAME##_value(TYPE *self);
+
+%enddef
+
+/* -----------------------------------------------------------------------------
+ * %pointer_cast(type1,type2,name)
+ *
+ * Generates a pointer casting function.
+ * ----------------------------------------------------------------------------- */
+
+%define %pointer_cast(TYPE1,TYPE2,NAME)
+%inline %{
+TYPE2 NAME(TYPE1 x) {
+   return %static_cast(x, TYPE2);
+}
+%}
+%enddef
+
+
+
+
+
+
+
+
diff --git a/trunk/Lib/typemaps/cstring.swg b/trunk/Lib/typemaps/cstring.swg
new file mode 100644
index 0000000..e774c43
--- /dev/null
+++ b/trunk/Lib/typemaps/cstring.swg
@@ -0,0 +1,9 @@
+%include <typemaps/cstrings.swg>
+
+%typemaps_cstring(%cstring,
+		 char,
+		 SWIG_AsCharPtr,
+		 SWIG_AsCharPtrAndSize,
+		 SWIG_FromCharPtr,
+		 SWIG_FromCharPtrAndSize);
+
diff --git a/trunk/Lib/typemaps/cstrings.swg b/trunk/Lib/typemaps/cstrings.swg
new file mode 100644
index 0000000..9144da7
--- /dev/null
+++ b/trunk/Lib/typemaps/cstrings.swg
@@ -0,0 +1,292 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cstrings.swg
+ *
+ * This file provides typemaps and macros for dealing with various forms
+ * of C character string handling.   The primary use of this module
+ * is in returning character data that has been allocated or changed in
+ * some way.
+ * ----------------------------------------------------------------------------- */
+
+%define %typemaps_cstring(Name, Char,
+			  SWIG_AsCharPtr,
+			  SWIG_AsCharPtrAndSize,
+			  SWIG_FromCharPtr,
+			  SWIG_FromCharPtrAndSize)
+
+
+/* %cstring_input_binary(TYPEMAP, SIZE)
+ * 
+ * Macro makes a function accept binary string data along with
+ * a size.  For example:
+ *
+ *     %cstring_input_binary(Char *buff, int size);
+ *     void foo(Char *buff, int size) {
+ *     }
+ *
+ */
+
+%define Name ## _input_binary(TYPEMAP, SIZE)                   
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize) (TYPEMAP, SIZE) 
+  (int res, Char *buf = 0, size_t size = 0, int alloc = 0)  {
+  res = SWIG_AsCharPtrAndSize($input, &buf, &size, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "(TYPEMAP, SIZE)", $symname, $argnum);
+  }
+  $1 = ($1_ltype) buf;					       
+  $2 = ($2_ltype) size - 1;				       
+}
+%typemap(freearg,noblock=1,match="in") (TYPEMAP, SIZE) {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+%enddef								
+
+
+
+/*
+ * %cstring_bounded_output(TYPEMAP, MAX)
+ *
+ * This macro is used to return a NULL-terminated output string of
+ * some maximum length.  For example:
+ *
+ *     %cstring_bounded_output(Char *outx, 512);
+ *     void foo(Char *outx) {
+ *         sprintf(outx,"blah blah\n");
+ *     }
+ *
+ */
+
+%define Name ## _bounded_output(TYPEMAP,MAX)        
+%typemap(in,noblock=1,numinputs=0) TYPEMAP (Char temp[MAX+1])  {
+  $1 = ($1_ltype) temp;
+}
+%typemap(freearg,match="in") TYPEMAP "";
+%typemap(argout,noblock=1,fragment= #SWIG_FromCharPtr ) TYPEMAP {
+  $1[MAX] = 0;  
+  %append_output(SWIG_FromCharPtr($1));
+}
+%enddef
+
+
+
+/*
+ * %cstring_chunk_output(TYPEMAP, SIZE)
+ *
+ * This macro is used to return a chunk of binary string data.
+ * Embedded NULLs are okay.  For example:
+ *
+ *     %cstring_chunk_output(Char *outx, 512);
+ *     void foo(Char *outx) {
+ *         memmove(outx, somedata, 512);
+ *     }
+ *
+ */
+
+%define Name ## _chunk_output(TYPEMAP,SIZE)           
+%typemap(in,noblock=1,numinputs=0) TYPEMAP(Char temp[SIZE]) {
+  $1 = ($1_ltype) temp;
+}
+%typemap(freearg,match="in") TYPEMAP "";
+%typemap(argout,noblock=1,fragment= #SWIG_FromCharPtrAndSize) TYPEMAP {
+  %append_output(SWIG_FromCharPtrAndSize($1,SIZE));
+}
+%enddef
+
+
+
+/*
+ * %cstring_bounded_mutable(TYPEMAP, SIZE)
+ *
+ * This macro is used to wrap a string that's going to mutate.
+ *
+ *     %cstring_bounded_mutable(Char *in, 512);
+ *     void foo(in *x) {
+ *         while (*x) {
+ *            *x = toupper(*x);
+ *            x++;
+ *         }
+ *     }
+ *
+ */
+
+
+%define Name ## _bounded_mutable(TYPEMAP,MAX)                              
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize) TYPEMAP 
+  (int res,Char temp[MAX+1], Char *t = 0, size_t n = 0, int alloc = 0) {  
+  res = SWIG_AsCharPtrAndSize($input, &t, &n, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "TYPEMAP", $symname, $argnum);
+  }
+  if ( n > (size_t) MAX ) n = (size_t) MAX;
+  memcpy(temp, t, sizeof(Char)*n);
+  if (alloc == SWIG_NEWOBJ) %delete_array(t);
+  temp[n - 1] = 0;                                                             
+  $1 = ($1_ltype) temp;                                                    
+}
+%typemap(freearg,match="in") TYPEMAP "";
+%typemap(argout,noblock=1,fragment=#SWIG_FromCharPtr) TYPEMAP {
+  $1[MAX] = 0;
+  %append_output(SWIG_FromCharPtr($1));
+}
+%enddef
+
+
+/*
+ * %cstring_mutable(TYPEMAP [, expansion])
+ *
+ * This macro is used to wrap a string that will mutate in place.
+ * It may change size up to a user-defined expansion. 
+ *
+ *     %cstring_mutable(Char *in);
+ *     void foo(in *x) {
+ *         while (*x) {
+ *            *x = toupper(*x);
+ *            x++;
+ *         }
+ *     }
+ *
+ */
+
+%define Name ## _mutable(TYPEMAP,EXP...)                  
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize) TYPEMAP 
+ (int res, Char* t = 0, size_t n = 0, int alloc = 0, size_t expansion = 0) {
+#if #EXP != ""
+  expansion += EXP;
+#endif
+  res = SWIG_AsCharPtrAndSize($input, &t, &n, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "TYPEMAP", $symname, $argnum);
+  }
+  $1 = %new_array(n+expansion, $*1_ltype);          
+  memcpy($1,t,sizeof(Char)*n);
+  if (alloc == SWIG_NEWOBJ) %delete_array(t);
+  $1[n-1] = 0;
+}
+%typemap(freearg,match="in") TYPEMAP "";
+%typemap(argout,noblock=1,fragment=#SWIG_FromCharPtr) TYPEMAP { 
+  %append_output(SWIG_FromCharPtr($1));
+  %delete_array($1);                                  
+}
+%enddef
+
+
+/*
+ * %cstring_output_maxsize(TYPEMAP, SIZE)
+ *
+ * This macro returns data in a string of some user-defined size.
+ *
+ *     %cstring_output_maxsize(Char *outx, int max) {
+ *     void foo(Char *outx, int max) {
+ *         sprintf(outx,"blah blah\n");
+ *     }
+ */
+
+%define Name ## _output_maxsize(TYPEMAP, SIZE)                       
+%typemap(in,noblock=1,fragment=SWIG_AsVal_frag(size_t)) (TYPEMAP, SIZE) (int res, size_t size, Char *buff = 0) {   
+  res = SWIG_AsVal(size_t)($input, &size);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "(TYPEMAP, SIZE)", $symname, $argnum);
+  }
+  buff= %new_array(size+1, Char);
+  $2 = %numeric_cast(size, $2_ltype);
+  $1 = %static_cast(buff, $1_ltype);
+}
+%typemap(freearg,noblock=1,match="in") (TYPEMAP,SIZE) {
+  if (buff$argnum) %delete_array(buff$argnum);
+} 
+%typemap(argout,noblock=1,fragment=#SWIG_FromCharPtr) (TYPEMAP,SIZE) { 
+  %append_output(SWIG_FromCharPtr($1));
+}
+%enddef
+
+/*
+ * %cstring_output_withsize(TYPEMAP, SIZE)
+ *
+ * This macro is used to return Character data along with a size
+ * parameter.
+ *
+ *     %cstring_output_maxsize(Char *outx, int *max) {
+ *     void foo(Char *outx, int *max) {
+ *         sprintf(outx,"blah blah\n");
+ *         *max = strlen(outx);  
+ *     }
+ */
+
+%define Name ## _output_withsize(TYPEMAP, SIZE)                        
+%typemap(in,noblock=1,fragment=SWIG_AsVal_frag(size_t)) (TYPEMAP, SIZE) (int res, size_t n, Char *buff = 0, $*2_ltype size) {    
+  res = SWIG_AsVal(size_t)($input, &n);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "(TYPEMAP, SIZE)", $symname, $argnum);
+  }
+  buff= %new_array(n+1, Char);
+  $1 = %static_cast(buff, $1_ltype);
+  size = %numeric_cast(n,$*2_ltype);
+  $2 = &size;
+}								       
+%typemap(freearg,noblock=1,match="in")(TYPEMAP,SIZE) {
+  if (buff$argnum) %delete_array(buff$argnum);
+} 
+%typemap(argout,noblock=1,fragment=#SWIG_FromCharPtrAndSize) (TYPEMAP,SIZE) { 
+  %append_output(SWIG_FromCharPtrAndSize($1,*$2));
+}
+%enddef
+
+
+/*
+ * %cstring_output_allocate(TYPEMAP, RELEASE)
+ *
+ * This macro is used to return Character data that was
+ * allocated with new or malloc.
+ *
+ *     %cstring_output_allocated(Char **outx, free($1));
+ *     void foo(Char **outx) {
+ *         *outx = (Char *) malloc(512);
+ *         sprintf(outx,"blah blah\n");
+ *     }
+ */
+ 
+%define Name ## _output_allocate(TYPEMAP, RELEASE)           
+%typemap(in,noblock=1,numinputs=0) TYPEMAP($*1_ltype temp = 0) {
+  $1 = &temp;
+}
+%typemap(freearg,match="in") TYPEMAP "";
+%typemap(argout,noblock=1,fragment=#SWIG_FromCharPtr) TYPEMAP { 
+  if (*$1) {
+    %append_output(SWIG_FromCharPtr(*$1));
+    RELEASE;					  	     
+  }					  	     
+}							     
+%enddef
+
+
+/*
+ * %cstring_output_allocate_size(TYPEMAP, SIZE, RELEASE)
+ *
+ * This macro is used to return Character data that was
+ * allocated with new or malloc.
+ *
+ *     %cstring_output_allocated(Char **outx, int *sz, free($1));
+ *     void foo(Char **outx, int *sz) {
+ *         *outx = (Char *) malloc(512);
+ *         sprintf(outx,"blah blah\n");
+ *         *sz = strlen(outx);
+ *     }
+ */
+
+%define Name ## _output_allocate_size(TYPEMAP, SIZE, RELEASE)
+%typemap(in,noblock=1,numinputs=0) (TYPEMAP, SIZE) ($*1_ltype temp = 0, $*2_ltype tempn) {
+  $1 = &temp; $2 = &tempn;
+}
+%typemap(freearg,match="in") (TYPEMAP,SIZE) "";
+%typemap(argout,noblock=1,fragment=#SWIG_FromCharPtrAndSize)(TYPEMAP,SIZE) {   
+  if (*$1) {
+    %append_output(SWIG_FromCharPtrAndSize(*$1,*$2));
+    RELEASE;
+  }
+}
+%enddef
+
+%enddef
+
diff --git a/trunk/Lib/typemaps/cwstring.swg b/trunk/Lib/typemaps/cwstring.swg
new file mode 100644
index 0000000..933f9a3
--- /dev/null
+++ b/trunk/Lib/typemaps/cwstring.swg
@@ -0,0 +1,10 @@
+%include <typemaps/cstrings.swg>
+%include <typemaps/wstring.swg>
+
+%typemaps_cstring(%cwstring,
+		 wchar_t,
+		 SWIG_AsWCharPtr,
+		 SWIG_AsWCharPtrAndSize,
+		 SWIG_FromWCharPtr,
+		 SWIG_FromWCharPtrAndSize);
+
diff --git a/trunk/Lib/typemaps/enumint.swg b/trunk/Lib/typemaps/enumint.swg
new file mode 100644
index 0000000..854d6f3
--- /dev/null
+++ b/trunk/Lib/typemaps/enumint.swg
@@ -0,0 +1,28 @@
+/* ------------------------------------------------------------
+ *  Enums mapped as integer values
+ * ------------------------------------------------------------ */
+
+%apply int { enum SWIGTYPE };
+%apply const int& { const enum SWIGTYPE& };
+
+%typemap(in,fragment=SWIG_AsVal_frag(int),noblock=1) const enum SWIGTYPE& (int val, int ecode, $basetype temp) {  
+  ecode = SWIG_AsVal(int)($input, &val);
+  if (!SWIG_IsOK(ecode)) {
+    %argument_fail(ecode, "$type", $symname, $argnum);
+  } else {
+    temp = %static_cast(val,$basetype);
+    $1 = &temp;
+  }
+}
+
+%typemap(varin,fragment=SWIG_AsVal_frag(int),noblock=1) enum SWIGTYPE {
+  if (sizeof(int) != sizeof($1)) {
+    %variable_fail(SWIG_AttributeError,"$type", "arch, read-only $name");
+  }  else {
+    int ecode = SWIG_AsVal(int)($input, %reinterpret_cast(&$1,int*));
+    if (!SWIG_IsOK(ecode)) {
+      %variable_fail(ecode, "$type", "$name");
+    }
+  }
+}
+
diff --git a/trunk/Lib/typemaps/exception.swg b/trunk/Lib/typemaps/exception.swg
new file mode 100644
index 0000000..17a819c
--- /dev/null
+++ b/trunk/Lib/typemaps/exception.swg
@@ -0,0 +1,89 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * exceptions.swg
+ *
+ * This SWIG library file provides language independent exception handling
+ * ----------------------------------------------------------------------------- */
+
+%include <typemaps/swigmacros.swg>
+
+
+/* macros for error manipulation */
+#define %nullref_fmt()                     "invalid null reference "		   
+#define %varfail_fmt(_type,_name)          "in variable '"`_name`"' of type '"`_type`"'"
+#ifndef %argfail_fmt
+#define %argfail_fmt(_type,_name,_argn)    "in method '" `_name` "', argument " `_argn`" of type '" `_type`"'"
+#endif
+#define %outfail_fmt(_type)                "in output value of type '"_type"'"
+#ifndef	%argnullref_fmt
+#define %argnullref_fmt(_type,_name,_argn) %nullref_fmt() %argfail_fmt(_type, _name, _argn)
+#endif  
+#define %varnullref_fmt(_type,_name)       %nullref_fmt() %varfail_fmt(_type, _name)  		   
+#define %outnullref_fmt(_type)             %nullref_fmt() %outfail_fmt(_type)         
+
+/* setting an error */
+#define %error(code,msg...)               SWIG_Error(code, msg)
+#define %type_error(msg...)               SWIG_Error(SWIG_TypeError,  msg)
+
+
+
+%insert("runtime") {
+
+%define_as(SWIG_exception_fail(code, msg), %block(%error(code, msg); SWIG_fail))
+
+%define_as(SWIG_contract_assert(expr, msg), if (!(expr)) { %error(SWIG_RuntimeError, msg); SWIG_fail; } else)
+
+}
+
+#ifdef __cplusplus
+/*
+  You can use the SWIG_CATCH_STDEXCEPT macro with the %exception
+  directive as follows:
+
+  %exception {
+    try {
+      $action
+    }
+    catch (my_except& e) {
+      ...
+    }
+    SWIG_CATCH_STDEXCEPT // catch std::exception
+    catch (...) {
+     SWIG_exception_fail(SWIG_UnknownError, "Unknown exception");
+    }
+  }
+*/
+%{
+#include <stdexcept>
+%}
+%define SWIG_CATCH_STDEXCEPT
+  /* catching std::exception  */
+  catch (std::invalid_argument& e) {
+    SWIG_exception_fail(SWIG_ValueError, e.what() );
+  } catch (std::domain_error& e) {
+    SWIG_exception_fail(SWIG_ValueError, e.what() );
+  } catch (std::overflow_error& e) {
+    SWIG_exception_fail(SWIG_OverflowError, e.what() );
+  } catch (std::out_of_range& e) {
+    SWIG_exception_fail(SWIG_IndexError, e.what() );
+  } catch (std::length_error& e) {
+    SWIG_exception_fail(SWIG_IndexError, e.what() );
+  } catch (std::runtime_error& e) {
+    SWIG_exception_fail(SWIG_RuntimeError, e.what() );
+  } catch (std::exception& e) {
+    SWIG_exception_fail(SWIG_SystemError, e.what() );
+  }
+%enddef
+%define SWIG_CATCH_UNKNOWN
+  catch (std::exception& e) {
+    SWIG_exception_fail(SWIG_SystemError, e.what() );
+  }
+  catch (...) {
+    SWIG_exception_fail(SWIG_UnknownError, "unknown exception");
+  }
+%enddef
+
+
+#endif /* __cplusplus */
diff --git a/trunk/Lib/typemaps/factory.swg b/trunk/Lib/typemaps/factory.swg
new file mode 100644
index 0000000..bccceb1
--- /dev/null
+++ b/trunk/Lib/typemaps/factory.swg
@@ -0,0 +1,88 @@
+/*
+  Implement a more natural wrap for factory methods, for example, if
+  you have:
+
+  ----  geometry.h --------
+       struct Geometry {                          
+         enum GeomType{			     
+           POINT,				     
+           CIRCLE				     
+         };					     
+         					     
+         virtual ~Geometry() {}    		     
+         virtual int draw() = 0;
+	 
+	 //
+	 // Factory method for all the Geometry objects
+	 //
+         static Geometry *create(GeomType i);     
+       };					     
+       					     
+       struct Point : Geometry  {		     
+         int draw() { return 1; }		     
+         double width() { return 1.0; }    	     
+       };					     
+       					     
+       struct Circle : Geometry  {		     
+         int draw() { return 2; }		     
+         double radius() { return 1.5; }          
+       }; 					     
+       
+       //
+       // Factory method for all the Geometry objects
+       //
+       Geometry *Geometry::create(GeomType type) {
+         switch (type) {			     
+         case POINT: return new Point();	     
+         case CIRCLE: return new Circle(); 	     
+         default: return 0;			     
+         }					     
+       }					    
+  ----  geometry.h --------
+
+
+  You can use the %factory with the Geometry::create method as follows:
+
+    %newobject Geometry::create;
+    %factory(Geometry *Geometry::create, Point, Circle);
+    %include "geometry.h"
+
+  and Geometry::create will return a 'Point' or 'Circle' instance
+  instead of the plain 'Geometry' type. For example, in python:
+
+    circle = Geometry.create(Geometry.CIRCLE)
+    r = circle.radius()
+
+  where circle is a Circle proxy instance.
+
+  NOTES: remember to fully qualify all the type names and don't
+  use %factory inside a namespace declaration, ie, instead of
+  
+     namespace Foo {
+       %factory(Geometry *Geometry::create, Point, Circle);
+     }
+
+  use
+
+     %factory(Foo::Geometry *Foo::Geometry::create, Foo::Point,  Foo::Circle);   
+
+     
+*/
+
+%define %_factory_dispatch(Type) 
+if (!dcast) {
+  Type *dobj = dynamic_cast<Type *>($1);
+  if (dobj) {
+    dcast = 1;
+    %set_output(SWIG_NewPointerObj(%as_voidptr(dobj),$descriptor(Type *), $owner | %newpointer_flags));
+  }   
+}%enddef
+
+%define %factory(Method,Types...)
+%typemap(out) Method {
+  int dcast = 0;
+  %formacro(%_factory_dispatch, Types)
+  if (!dcast) {
+    %set_output(SWIG_NewPointerObj(%as_voidptr($1),$descriptor, $owner | %newpointer_flags));
+  }
+}%enddef
diff --git a/trunk/Lib/typemaps/fragments.swg b/trunk/Lib/typemaps/fragments.swg
new file mode 100644
index 0000000..6d3e202
--- /dev/null
+++ b/trunk/Lib/typemaps/fragments.swg
@@ -0,0 +1,458 @@
+/*
+  Fragments:
+  ==========
+
+  Second to typemaps, fragments are one the most powerful and
+  dangerous swig features. So, if you are starting to read about them,
+  make sure you read all of this document.
+
+  Basics:
+  =======
+
+  Fragments provide a way to include or generate code into "on-demand"
+  as the typemaps could require.
+
+  For example, if you have a very long typemap
+
+  %typemap(in) MyClass * {
+    MyClass *value = 0;
+
+    <very long typemap>
+    ....
+    value = somewhere_converted_from_input_object_here($input);
+    ...
+    <very long typemap>
+  
+    $result = value;
+  }
+
+  very soon you will discover yourself copying the same long
+  conversion code in several typemaps, such as varin, directorout,
+  etc. Also, you will discover that swig copes verbatim the same very
+  long conversion code for every argument that requires it, making the
+  code very large too.
+
+  To eliminate this automatic or manual code copying, we define a
+  fragment that includes the common conversion code:
+
+  %fragment("AsMyClass","header") {
+     MyClass *AsMyClass(PyObject *obj) {
+        MyClass *value = 0;
+        <very long conversion>
+        ....
+        value = somewhere_converted_from_input_object_here(obj);
+        ...
+        <very long conversion>
+  
+        return value;
+     }
+  }
+
+  %typemap(in,fragment="AsMyClass") MyClass * {
+    $result = AsMyClass($input);
+  }
+
+  %typemap(varin,fragment="AsMyClass") MyClass * {
+    $result = AsMyClass($input);
+  }
+
+  When the 'in' or 'varin' typemaps for MyClass are invoked, the
+  fragment "AsMyClass" is added to the "header" section, and then the
+  typemap code is emitted. Hence, the method AsMyClass will be
+  included in the wrapping code and it will be available at the time
+  the typemap is applied.
+
+  To define a fragment then you need a name, a section where it goes,
+  and the code. Usually the section refers to the "header" part, and
+  both string and braces forms are accepted, ie:
+
+    %fragment("my_name","header") { ... }
+    %fragment("my_name","header") "...";
+
+  To ensure all the fragment/typemap engine works as expected, there
+  are some rules that fragments follow:
+
+  1.- A fragment is added to the wrapping code only once, ie, for the
+      method:
+      
+        int foo(MyClass *a, MyClass *b);
+
+     the wrapped code will look as much as:
+
+      MyClass *AsMyClass(PyObject *obj) {
+        .....
+      }
+      
+      int _wrap_foo(...) {
+        ....
+        arg1 = AsMyClass(obj1);
+        arg2 = AsMyClass(obj2);
+        ...
+	result = foo(arg1, arg2);
+      }
+
+
+     even when there will be duplicated typemap to process 'a' and
+     'b', the 'AsMyClass' method will be defined only once.
+
+     
+  2.- A fragment can only defined once, and the first definition
+      is the only one taking in account. All other definitions of the
+      same fragments are silently ignored. For example, you can have
+
+
+        %fragment("AsMyClass","header") { <definition 1> }
+	....
+        %fragment("AsMyClass","header") { <definition 2> }
+     
+      and then only the first definition is considered. In this way
+      you can change the 'system' fragments by including yours first.
+
+      Note that this behavior is opposite to the typemaps, where the
+      last typemap applied or defined prevails. Fragment follows the
+      first-in-first-out convention since they are intended to be
+      "global", while typemaps intend to be "locally" specialized.
+      
+  3.- Fragments names can not contain commas.
+ 	
+
+  A fragment can include one or more additional fragments, for example:
+
+    %fragment("<limits.h>", "header")  {
+      #include <limits.h>
+    }
+
+
+    %fragment("AsMyClass", "header", fragment="<limits.h>") {
+      MyClass *AsMyClass(PyObject *obj) {
+        MyClass *value = 0;
+	int ival = somewhere_converted_from_input_object_here(obj)
+	...
+        if  (ival < CHAR_MIN) {
+	   value = something_from_ival(ival);
+        } else {
+	...
+	}
+	...
+        return value;
+      }
+    }
+
+  in this case, when the "AsMyClass" fragment is emitted, it also
+  trigger the inclusion of the "<limits.h>" fragment.
+
+  You can add as many fragments as you want, for example
+
+    %fragment("bigfragment","header", fragment="frag1", fragment="frag2", fragment="frag3") "";
+
+  here, when the "bigfragment" is included, the three fragments "frag1",
+  "frag2" and "frag3" are included. Note that as "bigframent" is defined
+  empty, "", it does not add any code by itself, buy only trigger the
+  inclusion of the other fragments.
+  
+  In a typemap you can also include more than one fragment, but since the
+  syntax is different, you need to specify them in a 'comma separated'
+  list, for example, considering the previous example:
+ 
+     %typemap(in,fragment="frag1,frag2,frag3") {...}
+
+  is equivalent to
+
+     %typemap(in,fragment="bigfragment") {...}
+
+  
+  Finally, you can force the inclusion of a fragment at any moment as follow:
+
+     %fragment("bigfragment");
+
+  which is very useful inside a template class, for example. 
+
+
+  Fragment type specialization
+  ============================
+  
+  Fragments can be "type specialized". The syntax is as follows
+ 									   
+    %fragment("name","header") { a type independent fragment }
+    %fragment("name" {Type}, "header") { a type dependent fragment  }
+ 									   
+  and they can also, as typemaps, be used inside templates, for exampe:
+ 									   
+     template <class T>					              
+     struct A {						              
+        %fragment("incode"{A<T>},"header") {			              
+ 	  'incode' specialized fragment 
+ 	}							   	    
+ 									   
+ 	%typemap(in,fragment="incode"{A<T>}) {		   	    
+           here we use the 'type specialized' 		   	    
+           fragment "incode"{A<T>}			              
+ 	}
+     };							              
+  
+   which could seems a not much interesting feature, but is
+   fundamental for automatic typemap and template specialization.
+
+
+  Fragments and automatic typemap specialization:
+  ===============================================
+
+  Since fragments can be type specialized, they can be elegantly used
+  to specialized typemaps .
+
+  For example, if you have something like:
+
+    %fragment("incode"{float}, "header") {
+      float in_method_float(PyObject *obj) {
+        ...
+      }
+    }
+
+    %fragment("incode"{long}, "header") {
+      float in_method_long(PyObject *obj) {
+        ...
+      }
+    }
+    
+    %define %my_typemaps(Type) 
+    %typemaps(in,fragment="incode"{Type}) {
+      value = in_method_##Type(obj);
+    }
+    %enddef
+
+    %my_typemaps(float);
+    %my_typemaps(long);
+
+  then the proper "incode"{float,double} fragment will be included,
+  and the proper in_method_{float,double} will be called.
+
+  Since this is a recurrent fragment use, we provide a couple of
+  macros that make the automatic generation of typemaps easier:
+
+
+  Consider for example the following code:
+
+      %fragment(SWIG_From_frag(bool),"header") {     
+      static PyObject*		      
+      SWIG_From_dec(bool)(bool value)	       
+      {					       
+        PyObject *obj = value ? Py_True : Py_False;  
+        Py_INCREF(obj);			       
+        return obj;				       
+      }					       
+      }					       
+      					 
+      %typemap(out,fragment=SWIG_From_frag(bool)) bool {
+        $result = SWIG_From(bool)($1));
+      }
+
+  Here the macros
+
+      SWIG_From_frag  => fragment 
+      SWIG_From_dec   => declaration 
+      SWIG_From       => call 
+      
+  allow you to define/include a fragment, and declare and call the
+  'from-bool' method as needed. In the simpler case, these macros 
+  just return something like
+
+      SWIG_From_frag(bool)  => "SWIG_From_bool"
+      SWIG_From_dec(bool)   =>  SWIG_From_bool
+      SWIG_From(bool)       =>  SWIG_From_bool
+
+  But they are specialized for the different languages requirements,
+  such as perl or tcl that requires passing the interpreter pointer,
+  and also they can manage C++ ugly types, for example:
+  
+      SWIG_From_frag(std::complex<double>)  => "SWIG_From_std_complex_Sl_double_Sg_"
+      SWIG_From_dec(std::complex<double>)   =>  SWIG_From_std_complex_Sl_double_Sg_
+      SWIG_From(std::complex<double>)       =>  SWIG_From_std_complex_Sl_double_Sg_
+
+
+  Hence, to declare methods to use with typemaps, always use the
+  SWIG_From* macros. In the same way, the SWIG_AsVal* and SWIG_AsPtr*
+  set of macros are provided.
+    
+*/
+
+
+/* -----------------------------------------------------------------------------
+ * Define the basic macros to 'normalize' the type fragments
+ * ----------------------------------------------------------------------------- */
+
+#ifndef SWIG_AS_DECL_ARGS
+#define SWIG_AS_DECL_ARGS
+#endif
+
+#ifndef SWIG_FROM_DECL_ARGS
+#define SWIG_FROM_DECL_ARGS
+#endif
+
+#ifndef SWIG_AS_CALL_ARGS
+#define SWIG_AS_CALL_ARGS
+#endif
+
+#ifndef SWIG_FROM_CALL_ARGS
+#define SWIG_FROM_CALL_ARGS
+#endif
+
+#define %fragment_name(Name, Type...)     %string_name(Name) "_" {Type}
+
+#define SWIG_Traits_frag(Type...) %fragment_name(Traits, Type) 
+#define SWIG_AsPtr_frag(Type...)  %fragment_name(AsPtr, Type)	 
+#define SWIG_AsVal_frag(Type...)  %fragment_name(AsVal, Type)	 
+#define SWIG_From_frag(Type...)   %fragment_name(From, Type)	 
+
+#define SWIG_AsVal_name(Type...)  %symbol_name(AsVal, Type) 
+#define SWIG_AsPtr_name(Type...)  %symbol_name(AsPtr, Type) 
+#define SWIG_From_name(Type...)   %symbol_name(From, Type)  
+
+#define SWIG_AsVal_dec(Type...)   SWIG_AsVal_name(Type) SWIG_AS_DECL_ARGS
+#define SWIG_AsPtr_dec(Type...)   SWIG_AsPtr_name(Type) SWIG_AS_DECL_ARGS
+#define SWIG_From_dec(Type...)    SWIG_From_name(Type)  SWIG_FROM_DECL_ARGS 
+
+#define SWIG_AsVal(Type...)       SWIG_AsVal_name(Type) SWIG_AS_CALL_ARGS 
+#define SWIG_AsPtr(Type...)  	  SWIG_AsPtr_name(Type) SWIG_AS_CALL_ARGS 	 
+#define SWIG_From(Type...)   	  SWIG_From_name(Type)  SWIG_FROM_CALL_ARGS 
+
+/* ------------------------------------------------------------
+ * common fragments 
+ * ------------------------------------------------------------ */
+
+/* Default compiler options for gcc allow long_long but not LLONG_MAX. 
+ * Define SWIG_NO_LLONG_MAX if this added limits support is not wanted. */
+%fragment("<limits.h>","header") %{
+#include <limits.h>
+#if !defined(SWIG_NO_LLONG_MAX)
+# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)
+#   define LLONG_MAX __LONG_LONG_MAX__
+#   define LLONG_MIN (-LLONG_MAX - 1LL)
+#   define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
+# endif
+#endif
+%}
+
+%fragment("<math.h>","header") %{
+#include <math.h>
+%}
+
+%fragment("<wchar.h>","header") %{
+#include <wchar.h>
+#include <limits.h>
+#ifndef WCHAR_MIN
+#  define WCHAR_MIN 0
+#endif
+#ifndef WCHAR_MAX
+#  define WCHAR_MAX 65535
+#endif
+%}
+
+%fragment("<float.h>","header") %{
+#include <float.h>
+%}
+
+%fragment("<stdio.h>","header") %{
+#include <stdio.h>
+#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM)
+# ifndef snprintf
+#  define snprintf _snprintf
+# endif
+#endif
+%}
+
+%fragment("<stdlib.h>","header") %{
+#include <stdlib.h>
+#ifdef _MSC_VER
+# ifndef strtoull
+#  define strtoull _strtoui64
+# endif
+# ifndef strtoll
+#  define strtoll _strtoi64
+# endif
+#endif
+%}
+
+/* -----------------------------------------------------------------------------
+ * special macros for fragments
+ * ----------------------------------------------------------------------------- */
+
+/* Macros to derive numeric types */
+
+%define %numeric_type_from(Type, Base)
+%fragment(SWIG_From_frag(Type),"header",
+	  fragment=SWIG_From_frag(Base)) {
+SWIGINTERNINLINE SWIG_Object
+SWIG_From_dec(Type)(Type value)
+{    
+  return SWIG_From(Base)(value);
+}
+}
+%enddef
+
+%define %numeric_type_asval(Type, Base, Frag, OverflowCond)
+%fragment(SWIG_AsVal_frag(Type),"header",
+	  fragment=Frag,
+	  fragment=SWIG_AsVal_frag(Base)) {
+SWIGINTERN int
+SWIG_AsVal_dec(Type)(SWIG_Object obj, Type *val)
+{
+  Base v;
+  int res = SWIG_AsVal(Base)(obj, &v);
+  if (SWIG_IsOK(res)) {
+    if (OverflowCond) {
+      return SWIG_OverflowError;
+    } else {
+      if (val) *val = %numeric_cast(v, Type);
+    }
+  }  
+  return res;
+}
+}
+%enddef
+
+#define %numeric_signed_type_asval(Type, Base, Frag, Min, Max) \
+%numeric_type_asval(Type, Base, Frag, (v < Min || v > Max))
+
+#define %numeric_unsigned_type_asval(Type, Base, Frag, Max) \
+%numeric_type_asval(Type, Base, Frag, (v > Max))
+
+
+/* Macro for 'signed long' derived types */
+
+%define %numeric_slong(Type, Frag, Min, Max)
+%numeric_type_from(Type, long)
+%numeric_signed_type_asval(Type, long, Frag , Min, Max)
+%enddef
+
+/* Macro for 'unsigned long' derived types */
+
+%define %numeric_ulong(Type, Frag, Max)
+%numeric_type_from(Type, unsigned long)
+%numeric_unsigned_type_asval(Type, unsigned long, Frag, Max)
+%enddef
+
+
+/* Macro for 'double' derived types */
+
+%define %numeric_double(Type, Frag, Min, Max)
+%numeric_type_from(Type, double)
+%numeric_signed_type_asval(Type, double, Frag , Min, Max)
+%enddef
+
+
+/* Macros for missing fragments */
+
+%define %ensure_fragment(Fragment)
+%fragment(`Fragment`,"header") {
+%#error "Swig language implementation must provide the Fragment fragment"
+}
+%enddef
+
+%define %ensure_type_fragments(Type)
+%fragment(SWIG_From_frag(Type),"header") {
+%#error "Swig language implementation must provide a SWIG_From_frag(Type) fragment"
+}
+%fragment(SWIG_AsVal_frag(Type),"header") {
+%#error "Swig language implementation must provide a SWIG_AsVal_frag(Type) fragment"
+}
+%enddef
diff --git a/trunk/Lib/typemaps/implicit.swg b/trunk/Lib/typemaps/implicit.swg
new file mode 100644
index 0000000..24bb3dc
--- /dev/null
+++ b/trunk/Lib/typemaps/implicit.swg
@@ -0,0 +1,208 @@
+/*
+  The %implict macro allows a SwigType (Class) to be accepted
+  as an input parameter and use its implicit constructors when needed.
+
+  For example:
+
+
+  %implicit(A, int, double, B);
+
+  %inline 
+  {
+    struct B { };  
+    struct A
+    {
+      int ii;
+      A(int i) { ii = 1; }
+      A(double d) { ii = 2; }
+      A(const B& b) { ii = 3; }
+    };
+  
+    int get(A a) { return a.ii; }
+  }
+
+  Here, you can call 'get' as 
+
+    get(1)    ==> get(A(1))
+    get(2.0)  ==> get(A(2.0))
+    get(B())  ==> get(A(B()))
+
+   and swig will construct an 'A' temporal variable using the
+   corresponding implicit constructor.
+
+
+  The plain implicit macro takes care of simple type list. If it doesn't
+  work because you are passing template types with commas, then use
+  the %implicit_{1,2,3} versions and/or the %arg macro.
+
+*/
+
+%define %implicit_type(Type...)
+%traits_swigtype(Type);
+%enddef
+
+%define %implicit_frag(Type...) ,fragment=SWIG_Traits_frag(Type) %enddef
+
+%define %implicit_code(Type...)
+{
+  Type _v;
+  int res = swig::asval<Type >(obj, &_v);  
+  if (SWIG_IsOK(res)) {
+    if (val) *val = new value_type(static_cast<const Type& >(_v));
+    return SWIG_AddNewMask(res);
+  }
+}
+%enddef
+
+/* implicit */
+
+%define %implicit(Type, ...)
+
+%formacro_1(%implicit_type,__VA_ARGS__);
+
+%fragment(SWIG_Traits_frag(Type),"header",
+	  fragment="StdTraits"
+          %formacro_1(%implicit_frag,__VA_ARGS__)) %{
+namespace swig {
+  template <>  struct traits<Type > {   
+    typedef pointer_category category;
+    static const char* type_name() { return "Type"; }
+  };
+   
+  template <> struct traits_asptr< Type > {
+  typedef Type value_type;
+  static int asptr(SWIG_Object obj, value_type **val) { 
+    Type *vptr;
+    static swig_type_info* desc = SWIG_TypeQuery("Type *");
+    int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = vptr;
+      return res;
+    } else {
+      %formacro_1(%implicit_code,__VA_ARGS__)
+    }
+    return SWIG_TypeError;
+  }
+ };
+}
+%}
+
+%typemap_traits_ptr(%checkcode(POINTER),Type);
+%enddef
+
+/* implicit_1 */
+
+
+%define %implicit_1(Type, Imp1)
+%traits_swigtype(Imp1);
+
+%fragment(SWIG_Traits_frag(Type),"header",
+	  fragment="StdTraits",
+	  fragment=SWIG_Traits_frag(Imp1)) %{
+namespace swig {
+  template <>  struct traits< Type > {   
+    typedef pointer_category category;
+    static const char* type_name() { return "Type"; }
+  };
+   
+  template <> struct traits_asptr< Type > {   
+  typedef Type value_type;
+  static int asptr(SWIG_Object obj, value_type **val) { 
+    Type *vptr;
+    static swig_type_info* desc = SWIG_TypeQuery("Type *");
+    int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = vptr;
+      return res;
+    } else {
+      %implicit_code(Imp1);
+    }
+    return SWIG_TypeError;
+  }
+ };
+}
+%}
+
+%typemap_traits_ptr(%checkcode(POINTER),Type);
+
+%enddef
+
+/* implicit_2 */
+
+%define %implicit_2(Type, Imp1, Imp2)
+%traits_swigtype(Imp1);
+%traits_swigtype(Imp2);
+
+%fragment(SWIG_Traits_frag(Type),"header",
+	  fragment="StdTraits",
+	  fragment=SWIG_Traits_frag(Imp1),
+	  fragment=SWIG_Traits_frag(Imp2)) %{
+namespace swig {
+  template <>  struct traits< Type > {   
+    typedef pointer_category category;
+    static const char* type_name() { return "Type"; }
+  };
+
+  template <> struct traits_asptr< Type > {   
+  typedef Type value_type;
+  static int asptr(SWIG_Object obj, value_type **val) { 
+    Type *vptr;
+    static swig_type_info* desc = SWIG_TypeQuery("Type *");
+    int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = vptr;
+      return SWIG_OLDOBJ;
+    } else {
+      %implicit_code(Imp1);
+      %implicit_code(Imp2);
+    }
+    return SWIG_TypeError;
+  }
+ };
+}
+%}
+
+%typemap_traits_ptr(%checkcode(POINTER),Type);
+%enddef
+
+
+/* implicit_3 */
+
+%define %implicit_3(Type, Imp1, Imp2, Imp3)
+%traits_swigtype(Imp1);
+%traits_swigtype(Imp2);
+%traits_swigtype(Imp3);
+
+%fragment(SWIG_Traits_frag(Type),"header",
+	  fragment="StdTraits",
+	  fragment=SWIG_Traits_frag(Imp1),
+	  fragment=SWIG_Traits_frag(Imp2),
+	  fragment=SWIG_Traits_frag(Imp3)) %{
+namespace swig {
+  template <>  struct traits< Type > {   
+    typedef pointer_category category;
+    static const char* type_name() { return "Type"; }
+  };
+
+  template <> struct traits_asptr< Type > {   
+    typedef Type value_type;
+    static int asptr(SWIG_Object obj, value_type **val) { 
+    Type *vptr;
+    static swig_type_info* desc = SWIG_TypeQuery("Type *");
+    int res = SWIG_ConvertPtr(obj, (void **)&vptr, desc, 0);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = vptr;
+      return res;
+    } else {
+      %implicit_code(Imp1);
+      %implicit_code(Imp2);
+      %implicit_code(Imp3);
+    }
+    return SWIG_TypeError;
+  }
+ };
+}
+%}
+
+%typemap_traits_ptr(%checkcode(POINTER),Type);
+%enddef
diff --git a/trunk/Lib/typemaps/inoutlist.swg b/trunk/Lib/typemaps/inoutlist.swg
new file mode 100644
index 0000000..23fda85
--- /dev/null
+++ b/trunk/Lib/typemaps/inoutlist.swg
@@ -0,0 +1,296 @@
+/*  ------------------------------------------------------------
+ *
+ * Define the IN/OUTPUT typemaps assuming the output parameters are
+ * returned in a list, i.e., they are not directly modified.
+ *
+ * The user should provide the %append_output(result, obj) method,
+ * via a macro, which append a particular object to the result.
+ *
+ *
+ * In Tcl, for example, the file is used as:
+ *
+ *   #define %append_output(obj) Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp),obj);
+ *   %include <typemaps/inoutlist.swg>
+ *
+ * while in Python it is used as:
+ *
+ *   #define %append_output(obj) $result = SWIG_Python_AppendResult($result, obj)
+ *   %include <typemaps/inoutlist.swg>
+ *
+ * where the method SWIG_Python_AppendResult is defined inside the
+ * %append_output fragment.
+ *
+ * If you forget to define %append_output, this file will generate
+ * an error.
+ *
+ * ------------------------------------------------------------ */
+
+
+//
+// Uncomment the following definition if you don't want the in/out
+// typemaps by default, ie, you prefer to use typemaps.i.
+//
+//#define SWIG_INOUT_NODEF
+
+//
+// Use the following definition to enable the INPUT parameters to
+// accept both 'by value' and 'pointer' objects.
+//
+#define SWIG_INPUT_ACCEPT_PTRS
+
+// ------------------------------------------------------------------------
+// Pointer handling
+//
+// These mappings provide support for input/output arguments and common
+// uses for C/C++ pointers.
+// ------------------------------------------------------------------------
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+/* 
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+#if defined(SWIG_INPUT_ACCEPT_PTRS)
+#define %check_input_ptr(input,arg,desc,disown) (SWIG_IsOK((res = SWIG_ConvertPtr(input,%as_voidptrptr(arg),desc,disown))))
+#else
+#define %check_input_ptr(input,arg,desc,disown) (SWIG_IsOK((res = SWIG_ERROR)))
+#endif
+
+%define %_value_input_typemap(code, asval_meth, asval_frag, Type)
+  %typemap(in,noblock=1,fragment=asval_frag) Type *INPUT ($*ltype temp, int res = 0) {
+    if (!%check_input_ptr($input,&$1,$descriptor,$disown)) {
+      Type val; 
+      int ecode = asval_meth($input, &val);
+      if (!SWIG_IsOK(ecode)) { 
+	%argument_fail(ecode, "$*ltype",$symname, $argnum);
+      }
+      temp = %static_cast(val, $*ltype);
+      $1 = &temp;
+      res = SWIG_AddTmpMask(ecode);
+    }
+  }
+  %typemap(in,noblock=1,fragment=asval_frag) Type &INPUT($*ltype temp, int res = 0) {
+    if (!%check_input_ptr($input,&$1,$descriptor,$disown)) {
+      Type val;
+      int ecode = asval_meth($input, &val);
+      if (!SWIG_IsOK(ecode)) { 
+	%argument_fail(ecode, "$*ltype",$symname, $argnum);
+      }
+      temp = %static_cast(val, $*ltype);
+      $1 = &temp;
+      res = SWIG_AddTmpMask(ecode);
+    }
+  }
+  %typemap(freearg,noblock=1,match="in") Type *INPUT, Type &INPUT {
+    if (SWIG_IsNewObj(res$argnum)) %delete($1);
+  }
+  %typemap(typecheck,noblock=1,precedence=code,fragment=asval_frag) Type *INPUT, Type &INPUT {
+    void *ptr = 0;
+    int res = asval_meth($input, 0);
+    $1 = SWIG_CheckState(res);
+    if (!$1) {
+      $1 = %check_input_ptr($input,&ptr,$1_descriptor,0);
+    }
+  }
+%enddef
+
+%define %_ptr_input_typemap(code,asptr_meth,asptr_frag,Type)
+  %typemap(in,noblock=1,fragment=asptr_frag) Type *INPUT(int res = 0) {  
+    res = asptr_meth($input, &$1);
+    if (!SWIG_IsOK(res)) {
+      %argument_fail(res,"$type",$symname, $argnum);
+    }
+    res = SWIG_AddTmpMask(res);
+  }
+  %typemap(in,noblock=1,fragment=asptr_frag) Type &INPUT(int res = 0) {  
+    res = asptr_meth($input, &$1);
+    if (!SWIG_IsOK(res)) { 
+      %argument_fail(res,"$type",$symname, $argnum);
+    }     
+    if (!$1) { 
+      %argument_nullref("$type",$symname, $argnum);
+    }
+    res = SWIG_AddTmpMask(res);
+  }
+  %typemap(freearg,noblock=1,match="in") Type *INPUT, Type &INPUT {
+    if (SWIG_IsNewObj(res$argnum)) %delete($1);
+  }
+  %typemap(typecheck,noblock=1,precedence=code,fragment=asptr_frag) Type *INPUT, Type &INPUT {
+    int res = asptr_meth($input, (Type**)0);
+    $1 = SWIG_CheckState(res);
+  }
+%enddef
+
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a list element.
+
+/* 
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, they are returned in the form of a list.
+
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters):
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The output of the function would be a list containing both output
+values.
+
+*/
+
+%define %_value_output_typemap(from_meth, from_frag, Type)
+ %typemap(in,numinputs=0,noblock=1) 
+   Type *OUTPUT ($*1_ltype temp, int res = SWIG_TMPOBJ), 
+   Type &OUTPUT ($*1_ltype temp, int res = SWIG_TMPOBJ) {
+   $1 = &temp;
+ }
+ %typemap(argout,noblock=1,fragment=from_frag) Type *OUTPUT, Type &OUTPUT {
+   if (SWIG_IsTmpObj(res$argnum)) {
+     %append_output(from_meth((*$1)));
+   } else {
+     int new_flags = SWIG_IsNewObj(res$argnum) ? (SWIG_POINTER_OWN | %newpointer_flags) : %newpointer_flags;
+     %append_output(SWIG_NewPointerObj((void*)($1), $1_descriptor, new_flags));
+   }
+ }
+%enddef
+
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a list.  
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+Unlike C, this mapping does not directly modify the input value.
+Rather, the modified input value shows up as the return value of the
+function.  Thus, to apply this function to a variable you might do
+this :
+
+       x = neg(x)
+
+Note : previous versions of SWIG used the symbol 'BOTH' to mark
+input/output arguments.   This is still supported, but will be slowly
+phased out in future releases.
+
+*/
+
+%define %_value_inout_typemap(Type)
+ %typemap(in) Type *INOUT = Type *INPUT;
+ %typemap(in) Type &INOUT = Type &INPUT;
+ %typemap(typecheck) Type *INOUT = Type *INPUT;
+ %typemap(typecheck) Type &INOUT = Type &INPUT;
+ %typemap(argout) Type *INOUT = Type *OUTPUT;
+ %typemap(argout) Type &INOUT = Type &OUTPUT;
+%enddef
+
+
+%define %_ptr_inout_typemap(Type)
+ %_value_inout_typemap(%arg(Type))
+ %typemap(typecheck) Type *INOUT = Type *INPUT;
+ %typemap(typecheck) Type &INOUT = Type &INPUT;
+ %typemap(freearg) Type *INOUT = Type *INPUT;
+ %typemap(freearg) Type &INOUT = Type &INPUT;
+%enddef
+
+#ifndef SWIG_INOUT_NODEF
+
+%define %value_input_typemap(code,asval_meth, asval_frag, Type...)
+  %_value_input_typemap(%arg(code),%arg(asval_meth),%arg(asval_frag),%arg(Type))
+%enddef
+
+%define %ptr_input_typemap(code,asval_meth,asval_frag,Type...)		
+  %_ptr_input_typemap(%arg(code),%arg(asval_meth),%arg(asval_frag),%arg(Type))
+%enddef
+
+%define %value_output_typemap(from_meth,from_frag,Type...)		
+  %_value_output_typemap(%arg(from_meth),%arg(from_frag),%arg(Type))
+%enddef
+
+#define %value_inout_typemap(Type...) %_value_inout_typemap(%arg(Type))
+#define %ptr_inout_typemap(Type...) %_ptr_inout_typemap(%arg(Type))
+
+#else /* You need to include typemaps.i */
+
+
+#define %value_output_typemap(Type...)
+#define %value_input_typemap(Type...)
+#define %value_inout_typemap(Type...)
+#define %ptr_input_typemap(Type...)
+#define %ptr_inout_typemap(Type...)
+
+#endif /* SWIG_INOUT_DEFAULT */
+
+/*----------------------------------------------------------------------
+  Front ends.
+  
+  use the following macros to define your own IN/OUTPUT/INOUT typemaps
+  
+  ------------------------------------------------------------------------*/
+%define %typemaps_inout(Code, AsValMeth, FromMeth, AsValFrag, FromFrag, Type...)
+  %_value_input_typemap(%arg(Code), %arg(AsValMeth), 
+			    %arg(AsValFrag), %arg(Type));
+  %_value_output_typemap(%arg(FromMeth), %arg(FromFrag), %arg(Type));
+  %_value_inout_typemap(%arg(Type));
+%enddef
+
+%define %typemaps_inoutn(Code,Type...)
+  %typemaps_inout(%arg(Code),
+		 %arg(SWIG_AsVal(Type)), 
+		 %arg(SWIG_From(Type)), 
+		 %arg(SWIG_AsVal_frag(Type)), 
+		 %arg(SWIG_From_frag(Type)), 
+		 %arg(Type));
+%enddef
diff --git a/trunk/Lib/typemaps/misctypes.swg b/trunk/Lib/typemaps/misctypes.swg
new file mode 100644
index 0000000..09c81d7
--- /dev/null
+++ b/trunk/Lib/typemaps/misctypes.swg
@@ -0,0 +1,21 @@
+
+/* ------------------------------------------------------------
+ * --- ANSI/Posix C/C++ types ---
+ * ------------------------------------------------------------ */
+
+
+#ifdef __cplusplus
+
+%apply size_t { std::size_t };
+%apply const size_t& { const std::size_t& };
+
+%apply ptrdiff_t { std::ptrdiff_t };
+%apply const ptrdiff_t& { const std::ptrdiff_t& };
+
+#ifndef SWIG_INOUT_NODEF
+%apply size_t& { std::size_t& };
+%apply ptrdiff_t& { std::ptrdiff_t& };
+#endif
+
+#endif
+
diff --git a/trunk/Lib/typemaps/primtypes.swg b/trunk/Lib/typemaps/primtypes.swg
new file mode 100644
index 0000000..42728e5
--- /dev/null
+++ b/trunk/Lib/typemaps/primtypes.swg
@@ -0,0 +1,321 @@
+/* ------------------------------------------------------------
+ * Primitive type fragments and macros 
+ * ------------------------------------------------------------ */
+
+/*
+  This file provide fragments and macros for the C/C++ primitive types. 
+
+  The file defines default fragments for the following types:
+
+    bool
+    signed char
+    unsigned char
+    signed wchar_t     // in C++
+    unsigned wchar_t   // in C++
+    short
+    unsigned short
+    int
+    unsigned int
+    float
+    size_t
+    ptrdiff_t
+
+  which can always be redefined in the swig target language if needed.
+  
+  The fragments for the following types, however, need to be defined
+  in the target language always:
+
+    long
+    unsigned long
+    long long
+    unsigned long long
+    double
+ 
+  If they are not provided, an #error directive will appear in the
+  wrapped code.
+
+  --------------------------------------------------------------------
+  
+  This file provides the macro
+
+    %typemaps_primitive(CheckCode, Type)
+
+  which generate the typemaps for a primitive type with a given
+  checkcode. It is assumed that the primitive type is 'normalized' and
+  the corresponding SWIG_AsVal(Type) and SWIG_From(Type) methods are
+  provided via fragments.
+  
+   
+  The following auxiliary macros (explained with bash pseudo code) are
+  also defined:
+
+    %apply_ctypes(Macro)
+      for i in C Type
+      do
+        Macro($i)
+      done
+
+    %apply_cpptypes(Macro)
+      for i in C++ Type
+      do
+        Macro($i)
+      done
+
+    %apply_ctypes_2(Macro2)
+       for i in C Type
+       do
+         for j in C Type
+         do
+            Macro_2($i, $j)
+         done
+       done
+
+    %apply_cpptypes_2(Macro2)
+       for i in C++ Type
+       do
+         for j in C++ Type
+         do
+            Macro_2($i, $j)
+         done
+       done
+
+    %apply_checkctypes(Macro2)
+       for i in Check Type
+       do
+         Macro2(%checkcode($i), $i)
+       done
+
+*/
+
+
+/* ------------------------------------------------------------
+ * Primitive type fragments 
+ * ------------------------------------------------------------ */
+/* boolean */
+
+%fragment(SWIG_From_frag(bool),"header",fragment=SWIG_From_frag(long)) {
+SWIGINTERN SWIG_Object
+SWIG_From_dec(bool)(bool value)
+{    
+  return SWIG_From(long)(value ? 1 : 0);
+}
+}
+
+%fragment(SWIG_AsVal_frag(bool),"header",fragment=SWIG_AsVal_frag(long)) {
+SWIGINTERN int
+SWIG_AsVal_dec(bool)(SWIG_Object obj, bool *val)
+{
+  long v;
+  int res = SWIG_AsVal(long)(obj, val ? &v : 0);
+  if (SWIG_IsOK(res)) {    
+    if (val) *val = v ? true : false;
+    return res;
+  }  
+  return SWIG_TypeError;
+}
+}
+
+/* signed/unsigned char */
+
+%numeric_slong(signed char,     "<limits.h>", SCHAR_MIN, SCHAR_MAX)
+%numeric_ulong(unsigned char,   "<limits.h>", UCHAR_MAX)
+
+/* short/unsigned short */
+
+%numeric_slong(short,           "<limits.h>", SHRT_MIN, SHRT_MAX)
+%numeric_ulong(unsigned short,  "<limits.h>", USHRT_MAX)
+
+/* int/unsigned int */
+
+%numeric_slong(int,             "<limits.h>", INT_MIN, INT_MAX)
+%numeric_ulong(unsigned int,    "<limits.h>", UINT_MAX)
+
+/* signed/unsigned wchar_t */
+
+#ifdef __cplusplus
+%numeric_slong(signed wchar_t,   "<wchar.h>", WCHAR_MIN, WCHAR_MAX)
+%numeric_ulong(unsigned wchar_t, "<wchar.h>", UWCHAR_MAX)
+#endif
+
+/* float */
+
+%numeric_double(float,           "<float.h>", -FLT_MAX, FLT_MAX)
+
+/* long/unsigned long */
+
+%ensure_type_fragments(long)
+%ensure_type_fragments(unsigned long)
+
+/* long long/unsigned long long */
+
+%ensure_type_fragments(long long)
+%ensure_type_fragments(unsigned long long)
+
+/* double */
+
+%ensure_type_fragments(double)
+
+/* size_t */
+
+%fragment(SWIG_From_frag(size_t),"header",fragment=SWIG_From_frag(unsigned long)) {
+SWIGINTERNINLINE SWIG_Object
+SWIG_From_dec(size_t)(size_t value)
+{    
+  return SWIG_From(unsigned long)(%numeric_cast(value, unsigned long));
+}
+}
+
+%fragment(SWIG_AsVal_frag(size_t),"header",fragment=SWIG_AsVal_frag(unsigned long)) {
+SWIGINTERNINLINE int
+SWIG_AsVal_dec(size_t)(SWIG_Object obj, size_t *val)
+{
+  unsigned long v;
+  int res = SWIG_AsVal(unsigned long)(obj, val ? &v : 0);
+  if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, size_t);
+  return res;
+}
+}
+
+/* ptrdiff_t */
+
+%fragment(SWIG_From_frag(ptrdiff_t),"header",fragment=SWIG_From_frag(long)) {
+SWIGINTERNINLINE SWIG_Object
+SWIG_From_dec(ptrdiff_t)(ptrdiff_t value)
+{    
+  return SWIG_From(long)(%numeric_cast(value,long));
+}
+}
+
+%fragment(SWIG_AsVal_frag(ptrdiff_t),"header",fragment=SWIG_AsVal_frag(long)) {
+SWIGINTERNINLINE int
+SWIG_AsVal_dec(ptrdiff_t)(SWIG_Object obj, ptrdiff_t *val)
+{
+  long v;
+  int res = SWIG_AsVal(long)(obj, val ? &v : 0);
+  if (SWIG_IsOK(res) && val) *val = %numeric_cast(v, ptrdiff_t);
+  return res;
+}
+}
+
+
+%fragment("SWIG_CanCastAsInteger","header",
+	  fragment=SWIG_AsVal_frag(double),
+	  fragment="<float.h>",
+	  fragment="<math.h>") {
+SWIGINTERNINLINE int
+SWIG_CanCastAsInteger(double *d, double min, double max) {
+  double x = *d;
+  if ((min <= x && x <= max)) {
+   double fx = floor(x);
+   double cx = ceil(x);
+   double rd =  ((x - fx) < 0.5) ? fx : cx; /* simple rint */
+   if ((errno == EDOM) || (errno == ERANGE)) {
+     errno = 0;
+   } else {
+     double summ, reps, diff;
+     if (rd < x) {
+       diff = x - rd;
+     } else if (rd > x) {
+       diff = rd - x;
+     } else {
+       return 1;
+     }
+     summ = rd + x;
+     reps = diff/summ;
+     if (reps < 8*DBL_EPSILON) {
+       *d = rd;
+       return 1;
+     }
+   }
+  }
+  return 0;
+}
+}
+
+/* ------------------------------------------------------------
+ * Generate the typemaps for primitive type 
+ * ------------------------------------------------------------ */
+
+#define %typemaps_primitive(Code, Type) %typemaps_asvalfromn(%arg(Code), Type)
+
+/* ------------------------------------------------------------
+ * Primitive Type Macros
+ * ------------------------------------------------------------ */
+
+/* useful macros to derive typemap declarations from primitive types */
+
+%define _apply_macro(macro, arg2, arg1...)
+#if #arg1 != ""
+macro(%arg(arg1),arg2);
+#else
+macro(arg2);
+#endif
+%enddef
+
+/* Apply macro to the C-types */
+%define %apply_ctypes(Macro, Arg2...)
+_apply_macro(Macro, bool               , Arg2);
+_apply_macro(Macro, signed char        , Arg2);
+_apply_macro(Macro, unsigned char      , Arg2);
+_apply_macro(Macro, short              , Arg2);
+_apply_macro(Macro, unsigned short     , Arg2);
+_apply_macro(Macro, int                , Arg2);
+_apply_macro(Macro, unsigned int       , Arg2);
+_apply_macro(Macro, long               , Arg2);
+_apply_macro(Macro, unsigned long      , Arg2);
+_apply_macro(Macro, long long          , Arg2);
+_apply_macro(Macro, unsigned long long , Arg2);
+_apply_macro(Macro, float              , Arg2);
+_apply_macro(Macro, double             , Arg2);
+_apply_macro(Macro, char               , Arg2);
+_apply_macro(Macro, wchar_t            , Arg2);
+_apply_macro(Macro, size_t             , Arg2);
+_apply_macro(Macro, ptrdiff_t          , Arg2);
+%enddef
+
+/* apply the Macro2(Type1, Type2) to all  C types  */
+#define %apply_ctypes_2(Macro2) %apply_ctypes(%apply_ctypes, Macro2)
+
+
+/* apply the Macro(Type) to all  C++ types  */
+%define %apply_cpptypes(Macro, Arg2...)
+%apply_ctypes(Macro, Arg2)
+_apply_macro(Macro, std::size_t, Arg2);
+_apply_macro(Macro, std::ptrdiff_t, Arg2);
+_apply_macro(Macro, std::string, Arg2);
+_apply_macro(Macro, std::wstring, Arg2);
+_apply_macro(Macro, std::complex<float>, Arg2);
+_apply_macro(Macro, std::complex<double>, Arg2);
+%enddef
+
+/* apply the Macro2(Type1, Type2) to all  C++ types  */
+#define %apply_cpptypes_2(Macro2) %apply_cpptypes(%apply_cpptypes, Macro2)
+
+/* apply the Macro2(CheckCode,Type) to all  Checked Types */
+%define %apply_checkctypes(Macro2)
+Macro2(%checkcode(BOOL),    bool);
+Macro2(%checkcode(INT8),    signed char);
+Macro2(%checkcode(UINT8),   unsigned char);
+Macro2(%checkcode(INT16),   short);
+Macro2(%checkcode(UINT16),  unsigned short);
+Macro2(%checkcode(INT32),   int);
+Macro2(%checkcode(UINT32),  unsigned int);
+Macro2(%checkcode(INT64),   long);
+Macro2(%checkcode(UINT64),  unsigned long);
+Macro2(%checkcode(INT128),  long long);
+Macro2(%checkcode(UINT128), unsigned long long);
+Macro2(%checkcode(FLOAT),   float);
+Macro2(%checkcode(DOUBLE),  double);
+Macro2(%checkcode(CHAR),    char);
+Macro2(%checkcode(UNICHAR), wchar_t);
+Macro2(%checkcode(SIZE),    size_t);
+Macro2(%checkcode(PTRDIFF), ptrdiff_t);
+%enddef
+
+
+/* ------------------------------------------------------------
+ * Generate the typemaps for all the primitive types with checkcode
+ * ------------------------------------------------------------ */
+
+%apply_checkctypes(%typemaps_primitive);
+
diff --git a/trunk/Lib/typemaps/ptrtypes.swg b/trunk/Lib/typemaps/ptrtypes.swg
new file mode 100644
index 0000000..803377a
--- /dev/null
+++ b/trunk/Lib/typemaps/ptrtypes.swg
@@ -0,0 +1,211 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ptrtypes.swg
+ *
+ * Value typemaps (Type, const Type&) for "Ptr" types, such as swig
+ * wrapped classes, that define the AsPtr/From methods
+ *
+ * To apply them, just use one of the following macros:
+ *
+ *    %typemaps_asptr(CheckCode, AsPtrMeth, AsPtrFrag, Type)
+ *    %typemaps_asptrfrom(CheckCode, AsPtrMeth, FromMeth, AsPtrFrag, FromFrag, Type)
+ *
+ * or the simpler and normalize form:
+ *
+ *    %typemaps_asptrfromn(CheckCode, Type)
+ *
+ * Also, you can use the individual typemap definitions:
+ *
+ *    %ptr_in_typemap(asptr_meth,frag,Type)
+ *    %ptr_varin_typemap(asptr_meth,frag,Type)
+ *    %ptr_typecheck_typemap(check,asptr_meth,frag,Type)
+ *    %ptr_directorout_typemap(asptr_meth,frag,Type)
+ * ----------------------------------------------------------------------------- */
+
+%include <typemaps/valtypes.swg>
+
+/* in */
+
+%define %ptr_in_typemap(asptr_meth,frag,Type...)
+  %typemap(in,fragment=frag) Type {
+    Type *ptr = (Type *)0;
+    int res = asptr_meth($input, &ptr);
+    if (!SWIG_IsOK(res) || !ptr) { 
+      %argument_fail((ptr ? res : SWIG_TypeError), "$type", $symname, $argnum); 
+    }
+    $1 = *ptr;
+    if (SWIG_IsNewObj(res)) %delete(ptr);
+  }
+  %typemap(freearg) Type "";
+  %typemap(in,fragment=frag) const Type & (int res = SWIG_OLDOBJ) {
+    Type *ptr = (Type *)0;
+    res = asptr_meth($input, &ptr);
+    if (!SWIG_IsOK(res)) { %argument_fail(res,"$type",$symname, $argnum); }
+    if (!ptr) { %argument_nullref("$type",$symname, $argnum); }
+    $1 = ptr;
+  }
+  %typemap(freearg,noblock=1) const Type &  {
+    if (SWIG_IsNewObj(res$argnum)) %delete($1);
+  }
+%enddef
+
+/* varin */
+
+%define %ptr_varin_typemap(asptr_meth,frag,Type...)
+  %typemap(varin,fragment=frag) Type {
+    Type *ptr = (Type *)0;
+    int res = asptr_meth($input, &ptr);
+    if (!SWIG_IsOK(res) || !ptr) { 
+      %variable_fail((ptr ? res : SWIG_TypeError), "$type", "$name"); 
+    }
+    $1 = *ptr;
+    if (SWIG_IsNewObj(res)) %delete(ptr);
+  }
+%enddef
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+/* directorout */
+
+%define %ptr_directorout_typemap(asptr_meth,frag,Type...)
+  %typemap(directorargout,noblock=1,fragment=frag) Type *DIRECTOROUT ($*ltype temp) {
+    Type *swig_optr = 0;
+    int swig_ores = $input ? asptr_meth($input, &swig_optr) : 0;
+    if (!SWIG_IsOK(swig_ores) || !swig_optr) { 
+      %dirout_fail((swig_optr ? swig_ores : SWIG_TypeError),"$type");
+    }
+    temp = *swig_optr;
+    $result = &temp;
+    if (SWIG_IsNewObj(swig_ores)) %delete(swig_optr);
+  }
+
+  %typemap(directorout,noblock=1,fragment=frag) Type {
+    Type *swig_optr = 0;
+    int swig_ores = asptr_meth($input, &swig_optr);
+    if (!SWIG_IsOK(swig_ores) || !swig_optr) { 
+      %dirout_fail((swig_optr ? swig_ores : SWIG_TypeError),"$type");
+    }
+    $result = *swig_optr;
+    if (SWIG_IsNewObj(swig_ores)) %delete(swig_optr);
+  }
+
+  %typemap(directorout,noblock=1,fragment=frag,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) Type* {
+    Type *swig_optr = 0;
+    int swig_ores = asptr_meth($input, &swig_optr);
+    if (!SWIG_IsOK(swig_ores)) { 
+      %dirout_fail(swig_ores,"$type");
+    }    
+    $result = swig_optr;
+    if (SWIG_IsNewObj(swig_ores)) {
+      swig_acquire_ownership(swig_optr);
+    }
+  }
+  %typemap(directorfree,noblock=1) Type*
+  {
+    if (director)  {
+      director->swig_release_ownership(%as_voidptr($input));
+    }
+  }
+
+  %typemap(directorout,noblock=1,fragment=frag,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) Type& {
+    Type *swig_optr = 0;
+    int swig_ores = asptr_meth($input, &swig_optr);
+    if (!SWIG_IsOK(swig_ores)) { 
+      %dirout_fail(swig_ores,"$type");
+    } else {
+      if (!swig_optr) { 
+	%dirout_nullref("$type");
+      } 
+    }    
+    $result = swig_optr;
+    if (SWIG_IsNewObj(swig_ores)) {
+      swig_acquire_ownership(swig_optr);
+    }
+  }
+  %typemap(directorfree,noblock=1) Type&
+  {
+    if (director) {
+      director->swig_release_ownership(%as_voidptr($input));
+    }
+  }
+
+
+  %typemap(directorout,fragment=frag) Type &DIRECTOROUT = Type
+
+%enddef
+
+#else
+
+#define %ptr_directorout_typemap(asptr_meth,frag,Type...) 
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
+/* typecheck */
+
+%define %ptr_typecheck_typemap(check,asptr_meth,frag,Type...)
+%typemap(typecheck,noblock=1,precedence=check,fragment=frag) Type * {
+  int res = asptr_meth($input, (Type**)(0));
+  $1 = SWIG_CheckState(res);
+}
+
+%typemap(typecheck,noblock=1,precedence=check,fragment=frag) Type, const Type& {  
+  int res = asptr_meth($input, (Type**)(0));
+  $1 = SWIG_CheckState(res);
+}
+%enddef
+
+
+/*---------------------------------------------------------------------
+ * typemap definition for types with asptr method
+ *---------------------------------------------------------------------*/
+
+%define %typemaps_asptr(CheckCode, AsPtrMeth, AsPtrFrag, Type...)
+  %fragment(SWIG_AsVal_frag(Type),"header",fragment=SWIG_AsPtr_frag(Type)) {
+    SWIGINTERNINLINE int
+    SWIG_AsVal(Type)(SWIG_Object obj, Type *val)
+    {
+      Type *v = (Type *)0;
+      int res = SWIG_AsPtr(Type)(obj, &v);
+      if (!SWIG_IsOK(res)) return res;
+      if (v) {
+	if (val) *val = *v;
+	if (SWIG_IsNewObj(res)) {
+	  %delete(v);
+	  res = SWIG_DelNewMask(res);
+	}
+	return res;
+      }
+      return SWIG_ERROR;
+    }
+  }
+  %ptr_in_typemap(%arg(AsPtrMeth), %arg(AsPtrFrag), Type);
+  %ptr_varin_typemap(%arg(AsPtrMeth), %arg(AsPtrFrag), Type);
+  %ptr_directorout_typemap(%arg(AsPtrMeth), %arg(AsPtrFrag), Type);
+  %ptr_typecheck_typemap(%arg(CheckCode), %arg(AsPtrMeth),%arg(AsPtrFrag), Type);
+  %ptr_input_typemap(%arg(CheckCode),%arg(AsPtrMeth),%arg(AsPtrFrag),Type);
+%enddef
+
+/*---------------------------------------------------------------------
+ * typemap definition for types with asptr/from methods
+ *---------------------------------------------------------------------*/
+
+%define %typemaps_asptrfrom(CheckCode, AsPtrMeth, FromMeth, AsPtrFrag, FromFrag, Type...)
+  %typemaps_asptr(%arg(CheckCode), %arg(AsPtrMeth), %arg(AsPtrFrag), Type)
+  %typemaps_from(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_output_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+  %ptr_inout_typemap(Type);
+%enddef
+
+/*---------------------------------------------------------------------
+ * typemap definition for types  with for 'normalized' asptr/from methods
+ *---------------------------------------------------------------------*/
+
+%define %typemaps_asptrfromn(CheckCode, Type...)
+%typemaps_asptrfrom(%arg(CheckCode),
+		   %arg(SWIG_AsPtr(Type)), 
+		   %arg(SWIG_From(Type)), 
+		   %arg(SWIG_AsPtr_frag(Type)), 
+		   %arg(SWIG_From_frag(Type)), 
+		   Type);
+%enddef
diff --git a/trunk/Lib/typemaps/std_except.swg b/trunk/Lib/typemaps/std_except.swg
new file mode 100644
index 0000000..3ce479a
--- /dev/null
+++ b/trunk/Lib/typemaps/std_except.swg
@@ -0,0 +1,96 @@
+%include <typemaps/exception.swg>
+%include <std/std_except.i>
+
+/* 
+   Mark all of std exception classes as "exception classes" via
+   the "exceptionclass" feature.
+   
+   If needed, you can disable it by using %noexceptionclass.
+*/
+
+%define %std_exception_map(Exception, Code)
+  %exceptionclass  Exception; 
+#if !defined(SWIG_STD_EXCEPTIONS_AS_CLASSES)
+  %typemap(throws,noblock=1) Exception {
+    SWIG_exception_fail(Code, $1.what());
+  }
+  %ignore Exception;
+  struct Exception {
+  };
+#endif
+%enddef
+
+namespace std {
+  %std_exception_map(bad_exception,      SWIG_SystemError);
+  %std_exception_map(domain_error,       SWIG_ValueError);
+  %std_exception_map(exception,          SWIG_SystemError);
+  %std_exception_map(invalid_argument,   SWIG_ValueError);
+  %std_exception_map(length_error,       SWIG_IndexError);
+  %std_exception_map(logic_error,        SWIG_RuntimeError);
+  %std_exception_map(out_of_range,       SWIG_IndexError);
+  %std_exception_map(overflow_error,     SWIG_OverflowError);
+  %std_exception_map(range_error,        SWIG_OverflowError);
+  %std_exception_map(runtime_error,      SWIG_RuntimeError);
+  %std_exception_map(underflow_error,    SWIG_OverflowError);
+}
+
+#if defined(SWIG_STD_EXCEPTIONS_AS_CLASSES)
+
+namespace std {
+  struct exception 
+  {
+    virtual ~exception() throw();
+    virtual const char* what() const throw();
+  };
+
+  struct bad_exception : exception 
+  {
+  };
+
+  struct logic_error : exception 
+  {
+    logic_error(const string& msg);
+  };
+
+  struct domain_error : logic_error 
+  {
+    domain_error(const string& msg);
+  };
+
+  struct invalid_argument : logic_error 
+  {
+    invalid_argument(const string& msg);
+  };
+
+  struct length_error : logic_error 
+  {
+    length_error(const string& msg);
+  };
+
+  struct out_of_range : logic_error 
+  {
+    out_of_range(const string& msg);
+  };
+
+  struct runtime_error : exception 
+  {
+    runtime_error(const string& msg);
+  };
+
+  struct range_error : runtime_error 
+  {
+    range_error(const string& msg);
+  };
+
+  struct overflow_error : runtime_error 
+  {
+    overflow_error(const string& msg);
+  };
+
+  struct underflow_error : runtime_error 
+  {
+    underflow_error(const string& msg);
+  };
+}
+
+#endif
diff --git a/trunk/Lib/typemaps/std_string.swg b/trunk/Lib/typemaps/std_string.swg
new file mode 100644
index 0000000..691bf2c
--- /dev/null
+++ b/trunk/Lib/typemaps/std_string.swg
@@ -0,0 +1,27 @@
+//
+// String
+//
+
+
+#ifndef SWIG_STD_BASIC_STRING
+#define SWIG_STD_STRING
+
+%include <typemaps/std_strings.swg>
+
+%{
+#include <string>
+%}
+  
+namespace std
+{
+  %naturalvar string;
+  class string;
+}
+
+%typemaps_std_string(std::string, char, SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, %checkcode(STDSTRING));
+
+#else
+
+%include <std/std_string.i>
+
+#endif
diff --git a/trunk/Lib/typemaps/std_strings.swg b/trunk/Lib/typemaps/std_strings.swg
new file mode 100644
index 0000000..b7e8f6d
--- /dev/null
+++ b/trunk/Lib/typemaps/std_strings.swg
@@ -0,0 +1,82 @@
+
+/* defining the String asptr/from methods */
+
+%define %std_string_asptr(String, Char, SWIG_AsCharPtrAndSize, Frag)
+%fragment(SWIG_AsPtr_frag(String),"header",fragment=Frag) {
+SWIGINTERN int
+SWIG_AsPtr_dec(String)(SWIG_Object obj, String **val) 
+{
+  Char* buf = 0 ; size_t size = 0; int alloc = SWIG_OLDOBJ;
+  if (SWIG_IsOK((SWIG_AsCharPtrAndSize(obj, &buf, &size, &alloc)))) {
+    if (buf) {
+      if (val) *val = new String(buf, size - 1);
+      if (alloc == SWIG_NEWOBJ) %delete_array(buf);
+      return SWIG_NEWOBJ;
+    } else {
+      if (val) *val = 0;
+      return SWIG_OLDOBJ;
+    }
+  } else {
+    static int init = 0;
+    static swig_type_info* descriptor = 0;
+    if (!init) {
+      descriptor = SWIG_TypeQuery(#String " *");
+      init = 1;
+    }
+    if (descriptor) {
+      String *vptr;
+      int res = SWIG_ConvertPtr(obj, (void**)&vptr, descriptor, 0);
+      if (SWIG_IsOK(res) && val) *val = vptr;
+      return res;
+    }
+  }
+  return SWIG_ERROR;
+}
+}
+%enddef
+
+%define %std_string_from(String, SWIG_FromCharPtrAndSize, Frag)
+%fragment(SWIG_From_frag(String),"header",fragment=Frag) {
+SWIGINTERNINLINE SWIG_Object
+SWIG_From_dec(String)(const String& s)
+{
+  if (s.size()) {
+    return SWIG_FromCharPtrAndSize(s.data(), s.size());
+  } else {
+    return SWIG_FromCharPtrAndSize(s.c_str(), 0);
+  }
+}
+}
+%enddef
+
+%define %std_string_asval(String)
+%fragment(SWIG_AsVal_frag(String),"header", fragment=SWIG_AsPtr_frag(String)) {
+SWIGINTERN int
+SWIG_AsVal_dec(String)(SWIG_Object obj, String *val)
+{
+  String* v = (String *) 0;
+  int res = SWIG_AsPtr(String)(obj, &v);
+  if (!SWIG_IsOK(res)) return res;
+  if (v) {
+    if (val) *val = *v;
+    if (SWIG_IsNewObj(res)) {
+      %delete(v);
+      res = SWIG_DelNewMask(res);
+    }
+    return res;
+  }
+  return SWIG_ERROR;
+}
+}
+%enddef
+
+
+%define %typemaps_std_string(String, Char, AsPtrMethod, FromMethod, CheckCode)
+
+%std_string_asptr(String, Char, AsPtrMethod, #AsPtrMethod)
+%std_string_asval(String)
+%std_string_from(String, FromMethod, #FromMethod)
+
+%typemaps_asptrfromn(%arg(CheckCode), String);
+
+%enddef
diff --git a/trunk/Lib/typemaps/std_wstring.swg b/trunk/Lib/typemaps/std_wstring.swg
new file mode 100644
index 0000000..670685f
--- /dev/null
+++ b/trunk/Lib/typemaps/std_wstring.swg
@@ -0,0 +1,26 @@
+%include <typemaps/wstring.swg>
+
+#ifndef SWIG_STD_BASIC_STRING
+#define SWIG_STD_WSTRING
+
+%include <typemaps/std_strings.swg>
+
+%{
+#include <cwchar>
+#include <string>
+%}
+
+namespace std
+{
+  %naturalvar wstring;
+  class wstring;
+}
+
+%typemaps_std_string(std::wstring, wchar_t, SWIG_AsWCharPtrAndSize, SWIG_FromWCharPtrAndSize, %checkcode(STDUNISTRING));
+
+
+#else
+
+%include <std/std_wstring.i>
+
+#endif
diff --git a/trunk/Lib/typemaps/string.swg b/trunk/Lib/typemaps/string.swg
new file mode 100644
index 0000000..279ee2a
--- /dev/null
+++ b/trunk/Lib/typemaps/string.swg
@@ -0,0 +1,24 @@
+%ensure_fragment(SWIG_AsCharPtrAndSize)
+%ensure_fragment(SWIG_FromCharPtrAndSize)
+
+%types(char *);
+
+%fragment("SWIG_pchar_descriptor","header") {
+SWIGINTERN swig_type_info*
+SWIG_pchar_descriptor(void)
+{
+  static int init = 0;
+  static swig_type_info* info = 0;
+  if (!init) {
+    info = SWIG_TypeQuery("_p_char");
+    init = 1;
+  }
+  return info;
+}
+}
+
+
+%include <typemaps/strings.swg>
+%typemaps_string(%checkcode(STRING), %checkcode(CHAR),
+		 char, Char, SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, strlen,
+		"<limits.h>", CHAR_MIN, CHAR_MAX)
diff --git a/trunk/Lib/typemaps/strings.swg b/trunk/Lib/typemaps/strings.swg
new file mode 100644
index 0000000..04fa28f
--- /dev/null
+++ b/trunk/Lib/typemaps/strings.swg
@@ -0,0 +1,594 @@
+//
+// Use the macro SWIG_PRESERVE_CARRAY_SIZE if you prefer to preserve
+// the size of char arrays, ie
+//  ------------------------------------------
+//       C Side             =>   Language Side
+//  ------------------------------------------
+//   char name[5] = "hola"  =>   'hola\0'
+//
+// the default behaviour is 
+//
+//   char name[5] = "hola"  =>   'hola'
+//
+//
+//#define SWIG_PRESERVE_CARRAY_SIZE
+
+/* ------------------------------------------------------------
+ *  String typemaps for type Char (char or wchar_t)
+ * ------------------------------------------------------------ */
+
+%define %_typemap_string(StringCode, 
+			 Char,
+			 SWIG_AsCharPtrAndSize,
+			 SWIG_FromCharPtrAndSize,
+			 SWIG_CharPtrLen,
+			 SWIG_AsCharPtr,
+			 SWIG_FromCharPtr,
+			 SWIG_AsCharArray)
+
+/* in */
+
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtr) 
+  Char * (int res, Char *buf = 0, int alloc = 0),
+  const Char * (int res, Char *buf = 0, int alloc = 0) {
+  res = SWIG_AsCharPtr($input, &buf, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum);
+  }
+  $1 = %reinterpret_cast(buf, $1_ltype);
+}
+%typemap(freearg,noblock=1,match="in") Char *, const Char * {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtr) Char const*& (int res, Char *buf = 0, int alloc = 0) {
+  res = SWIG_AsCharPtr($input, &buf, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum);
+  }
+  $1 = &buf;
+}    
+%typemap(freearg, noblock=1,match="in") Char const*& {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+
+/* out */
+
+%typemap(out,noblock=1,fragment=#SWIG_FromCharPtr) Char *, const Char* {
+  %set_output(SWIG_FromCharPtr((const Char *)$1));
+}
+
+
+%typemap(out,noblock=1,fragment=#SWIG_FromCharPtr) Char const*& {
+  %set_output(SWIG_FromCharPtr(*$1));
+}
+
+%typemap(newfree,noblock=1) Char * {
+  %delete_array($1);
+}
+
+/* varin */
+
+%typemap(varin,fragment=#SWIG_AsCharPtrAndSize) Char * {
+  Char *cptr = 0; size_t csize = 0; int alloc = SWIG_NEWOBJ;
+  int res = SWIG_AsCharPtrAndSize($input, &cptr, &csize, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res,"$type","$name");
+  }
+  if ($1) %delete_array($1);
+  if (alloc == SWIG_NEWOBJ) {
+    $1 = cptr;
+  } else {
+    $1 = csize ? ($1_type)%new_copy_array(cptr, csize, Char) : 0;
+  }
+}
+
+%typemap(varin,fragment=#SWIG_AsCharPtrAndSize,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const Char * {
+  Char *cptr = 0; size_t csize = 0; int alloc = SWIG_NEWOBJ;
+  int res = SWIG_AsCharPtrAndSize($input, &cptr, &csize, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  if (alloc == SWIG_NEWOBJ) {
+    $1 = cptr;
+  } else {
+    $1 = csize ? ($1_type)%new_copy_array(cptr, csize, Char) : 0;
+  }
+}
+
+/* varout */
+
+%typemap(varout,noblock=1,fragment=#SWIG_FromCharPtr) Char*, const Char* {
+  %set_varoutput(SWIG_FromCharPtr($1));
+}
+
+/* memberin */
+
+%typemap(memberin,noblock=1) Char * {
+  if ($1) %delete_array($1);
+  if ($input) {
+    size_t size = SWIG_CharPtrLen(%reinterpret_cast($input, const Char *)) + 1;
+    $1 = ($1_type)%new_copy_array(%reinterpret_cast($input, const Char *), size, Char);
+  } else {
+    $1 = 0;
+  }
+}
+
+%typemap(memberin,noblock=1,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const Char * {
+  if ($input) {
+    size_t size = SWIG_CharPtrLen(%reinterpret_cast(%reinterpret_cast($input, const Char *), const Char *)) + 1;
+    $1 = ($1_type)%new_copy_array($input, size, Char);
+  } else {
+    $1 = 0;
+  }
+}
+
+/* globalin */
+
+%typemap(globalin,noblock=1) Char * {
+  if ($1) %delete_array($1);
+  if ($input) {
+    size_t size = SWIG_CharPtrLen(%reinterpret_cast(%reinterpret_cast($input, const Char *), const Char *)) + 1;
+    $1 = ($1_type)%new_copy_array($input, size, Char);
+  } else {
+    $1 = 0;
+  }
+}
+
+%typemap(globalin,noblock=1,warning=SWIGWARN_TYPEMAP_CHARLEAK_MSG) const Char * {
+  if ($input) {
+    size_t size = SWIG_CharPtrLen($input) + 1;
+    $1 = ($1_type)%new_copy_array($input, size, Char);
+  } else {
+    $1 = 0;
+  }
+}
+
+/* constant */
+
+%typemap(constcode,noblock=1,fragment=#SWIG_FromCharPtr)
+  Char *, Char const*, Char * const, Char const* const {
+  %set_constant("$symname", SWIG_FromCharPtr($value));
+}
+
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+
+%typemap(directorin,noblock=1,fragment=#SWIG_FromCharPtr)
+  Char *, Char const*, Char *const, Char const *const, 
+  Char const *&, Char *const &, Char const *const & {
+  $input = SWIG_FromCharPtr((const Char *)$1_name);
+}
+
+
+/* directorout */
+
+%typemap(directorout,noblock=1,fragment=#SWIG_AsCharPtr,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG)
+  Char * (int res, Char* buf = 0, int alloc = SWIG_NEWOBJ) {
+  res = SWIG_AsCharPtr($input, &buf, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %dirout_fail(res, "$type");
+  }
+  if (alloc == SWIG_NEWOBJ) {
+    swig_acquire_ownership_array(buf);
+  }
+  $result = %reinterpret_cast(buf, $1_ltype);
+}
+%typemap(directorfree,noblock=1) Char *
+{
+  if (director) {
+    director->swig_release_ownership(%as_voidptr($input));
+  }
+}
+
+
+%typemap(directorout,noblock=1,fragment=#SWIG_AsCharPtr,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) 
+  Char * const& (int res, Char* buf = 0, int alloc = SWIG_NEWOBJ),
+  Char const* const& (int res, Char* buf = 0, int alloc = SWIG_NEWOBJ) { 
+  res = SWIG_AsCharPtr($input, &buf, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %dirout_fail(res, "$type");
+  }
+  static $*1_ltype tmp = buf;
+  $result = &tmp;
+  if (alloc == SWIG_NEWOBJ) {
+    swig_acquire_ownership_array(buf);
+  }
+}
+%typemap(directorfree,noblock=1)
+  Char * const&, Char const* const& {
+  if (director) {
+    director->swig_release_ownership(%as_voidptr(*$input));
+  }
+}
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
+/* typecheck */
+
+%typemap(typecheck,noblock=1,precedence=StringCode,
+	 fragment=#SWIG_AsCharPtr) Char *, Char const*& {
+  int res = SWIG_AsCharPtr($input, 0, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+
+/* throws */
+
+%typemap(throws,noblock=1,fragment=#SWIG_FromCharPtr) Char * {
+  %raise(SWIG_FromCharPtr($1), "$type", 0);
+}
+
+
+/* ------------------------------------------------------------
+ *  Unknown size const Character array Char[ANY] handling
+ * ------------------------------------------------------------ */
+
+%apply Char* { Char [] };
+%apply const Char* { const Char [] };
+
+%typemap(varin,noblock=1,warning="462:Unable to set variable of type Char []") Char []
+{
+  %variable_fail(SWIG_AttributeError, "$type", "read-only $name");
+}
+
+
+/* ------------------------------------------------------------
+ *  Fixed size Character array Char[ANY] handling
+ * ------------------------------------------------------------ */
+
+/*  memberin and globalin typemaps  */
+
+%typemap(memberin,noblock=1) Char [ANY]
+{
+  if ($input) memcpy($1,$input,$1_dim0*sizeof(Char));
+  else memset($1,0,$1_dim0*sizeof(Char));
+}
+
+%typemap(globalin,noblock=1) Char [ANY]
+{
+  if ($input) memcpy($1,$input,$1_dim0*sizeof(Char));
+  else memset($1,0,$1_dim0*sizeof(Char));
+}
+
+/* in */
+
+%typemap(in,noblock=1,fragment=#SWIG_AsCharArray)
+  Char [ANY] (Char temp[$1_dim0], int res), 
+  const Char [ANY](Char temp[$1_dim0], int res)
+{  
+  res = SWIG_AsCharArray($input, temp, $1_dim0);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum);
+  }
+  $1 = %reinterpret_cast(temp, $1_ltype);
+}
+%typemap(freearg) Char [ANY], const Char [ANY] "";
+
+%typemap(in,noblock=1,fragment=#SWIG_AsCharArray) const Char (&)[ANY] (Char temp[$1_dim0], int res)
+{  
+  res = SWIG_AsCharArray($input, temp, $1_dim0);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum);
+  }
+  $1 = &temp;
+}
+%typemap(freearg) const Char (&)[ANY] "";
+
+%typemap(out,fragment=#SWIG_FromCharPtrAndSize)
+  Char [ANY], const Char[ANY] 
+{
+  size_t size = $1_dim0;
+%#ifndef SWIG_PRESERVE_CARRAY_SIZE
+  while (size && ($1[size - 1] == '\0')) --size;
+%#endif
+   %set_output(SWIG_FromCharPtrAndSize($1, size));
+}
+
+/* varin */
+
+%typemap(varin,fragment=#SWIG_AsCharArray) Char [ANY]
+{
+  int res = SWIG_AsCharArray($input, $1, $1_dim0);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+}
+
+/* varout */
+
+%typemap(varout,noblock=1,fragment=#SWIG_FromCharPtrAndSize)
+  Char [ANY], const Char [ANY] {
+  size_t size = $1_dim0;
+%#ifndef SWIG_PRESERVE_CARRAY_SIZE
+  while (size && ($1[size - 1] == '\0')) --size;
+%#endif
+  %set_varoutput(SWIG_FromCharPtrAndSize($1, size));
+}
+
+/* constant */
+
+%typemap(constcode,fragment=#SWIG_FromCharPtrAndSize)
+  Char [ANY], const Char [ANY]
+{
+  size_t size = $value_dim0;
+%#ifndef SWIG_PRESERVE_CARRAY_SIZE
+  while (size && ($value[size - 1] == '\0')) --size;
+%#endif
+  %set_constant("$symname", SWIG_FromCharPtrAndSize($value,size));
+}
+
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+%typemap(directorin,fragment=#SWIG_FromCharPtrAndSize)
+  Char [ANY], const Char [ANY] 
+{
+  size_t size = $1_dim0;
+%#ifndef SWIG_PRESERVE_CARRAY_SIZE
+  while (size && ($1_name[size - 1] == '\0')) --size;
+%#endif
+  $input = SWIG_FromCharPtrAndSize($1_name, size);
+}
+
+/* directorout */
+
+%typemap(directorout,noblock=1,fragment=#SWIG_AsCharArray)
+  Char [ANY] (Char temp[$result_dim0]),
+  const Char [ANY] (Char temp[$result_dim0], int res)
+{ 
+  res = SWIG_AsCharArray($input, temp, $result_dim0);
+  if (!SWIG_IsOK(res)) {
+    %dirout_fail(res, "$type");
+  }
+  $result = temp;
+}
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
+/* typecheck */
+
+%typemap(typecheck,noblock=1,precedence=StringCode,
+	 fragment=#SWIG_AsCharArray)  
+  Char [ANY], const Char[ANY] {
+  int res = SWIG_AsCharArray($input, (Char *)0, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+
+/* throws */
+
+%typemap(throws,fragment=#SWIG_FromCharPtrAndSize)
+  Char [ANY], const Char[ANY]
+{
+  size_t size = $1_dim0;
+%#ifndef SWIG_PRESERVE_CARRAY_SIZE
+  while (size && ($1[size - 1] == '\0')) --size;
+%#endif
+  %raise(SWIG_FromCharPtrAndSize($1, size), "$type", 0); 
+}
+
+/* -------------------------------------------------------------------
+ * --- Really fix size Char arrays, including '\0'chars at the end ---
+ * ------------------------------------------------------------------- */
+
+%typemap(varout,noblock=1,fragment=#SWIG_FromCharPtrAndSize)
+  Char FIXSIZE[ANY], const Char FIXSIZE[ANY]
+{
+  %set_varoutput(SWIG_FromCharPtrAndSize($1, $1_dim0));
+}
+
+%typemap(out,noblock=1,fragment=#SWIG_FromCharPtrAndSize)
+  Char FIXSIZE[ANY], const Char FIXSIZE[ANY]
+{
+  %set_output(SWIG_FromCharPtrAndSize($1, $1_dim0));
+}
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+%typemap(directorin,noblock=1,fragment=#SWIG_FromCharPtrAndSize)
+  Char FIXSIZE[ANY], const Char FIXSIZE[ANY]
+{
+  $input = SWIG_FromCharPtrAndSize($1_name, $1_dim0);
+}
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
+%typemap(throws,noblock=1,fragment=#SWIG_FromCharPtrAndSize)
+  Char FIXSIZE[ANY], const Char FIXSIZE[ANY] {
+  %raise(SWIG_FromCharPtrAndSize($1, $1_dim0), "$type", 0); 
+}
+
+/* ------------------------------------------------------------
+ * --- String & length ---
+ * ------------------------------------------------------------ */
+
+/* Here len doesn't include the '0' terminator */
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize) 
+  (Char *STRING, size_t LENGTH) (int res, Char *buf = 0, size_t size = 0, int alloc = 0),
+  (const Char *STRING, size_t LENGTH) (int res, Char *buf = 0, size_t size = 0, int alloc = 0)
+{
+  res = SWIG_AsCharPtrAndSize($input, &buf, &size, &alloc);
+  if (!SWIG_IsOK(res)) { 
+    %argument_fail(res,"$type",$symname, $argnum);
+  }  
+  $1 = %reinterpret_cast(buf, $1_ltype);
+  $2 = %numeric_cast(size - 1, $2_ltype);
+}
+%typemap(freearg,noblock=1,match="in") (Char *STRING, size_t LENGTH) {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+/* old 'int' form */
+%typemap(in) (Char *STRING, int LENGTH) = (Char *STRING, size_t LENGTH);
+%typemap(freearg) (Char *STRING, int LENGTH) = (Char *STRING, size_t LENGTH);
+
+
+/* Here size includes the '0' terminator */
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize)
+  (Char *STRING, size_t SIZE) (int res, Char *buf = 0, size_t size = 0, int alloc = 0),
+  (const Char *STRING, size_t SIZE) (int res, Char *buf = 0, size_t size = 0, int alloc = 0)
+{
+  res = SWIG_AsCharPtrAndSize($input, &buf, &size, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum);
+  }
+  $1 = %reinterpret_cast(buf, $1_ltype);
+  $2 = %numeric_cast(size, $2_ltype);
+}
+%typemap(freearg,noblock=1,match="in") (Char *STRING, size_t SIZE) {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+/* old 'int' form */
+%typemap(in) (Char *STRING, int SIZE) = (Char *STRING, size_t SIZE);
+%typemap(freearg) (Char *STRING, int SIZE) = (Char *STRING, size_t SIZE);
+
+
+/* reverse order versions */
+
+/* Here len doesn't include the '0' terminator */
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize) 
+  (size_t LENGTH, Char *STRING) (int res, Char *buf = 0, size_t size = 0, int alloc = 0),
+  (size_t LENGHT, const Char *STRING) (int res, Char *buf = 0, size_t size = 0, int alloc = 0)
+{
+  res = SWIG_AsCharPtrAndSize($input, &buf, &size, &alloc);
+  if (!SWIG_IsOK(res)) { 
+    %argument_fail(res,"$type",$symname, $argnum);
+  }  
+  $2 = %reinterpret_cast(buf, $2_ltype) ;
+  $1 = %numeric_cast(size - 1, $1_ltype) ;
+}
+%typemap(freearg, noblock=1, match="in") (size_t LENGTH, Char *STRING) {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+/* old 'int' form */
+%typemap(in) (int LENGTH, Char *STRING) = (size_t LENGTH, Char *STRING);
+%typemap(freearg) (int LENGTH, Char *STRING) = (size_t LENGTH, Char *STRING);
+
+/* Here size includes the '0' terminator */
+%typemap(in,noblock=1,fragment=#SWIG_AsCharPtrAndSize)
+  (size_t SIZE, Char *STRING) (int res, Char *buf = 0, size_t size = 0, int alloc = 0),
+  (size_t SIZE, const Char *STRING) (int res, Char *buf = 0, size_t size = 0, int alloc = 0)
+{
+  res = SWIG_AsCharPtrAndSize($input, &buf, &size, &alloc);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type",$symname, $argnum);
+  }
+  $2 = %reinterpret_cast(buf, $2_ltype) ;
+  $1 = %numeric_cast(size, $1_ltype) ;
+}
+%typemap(freearg, noblock=1, match="in") (size_t SIZE, Char *STRING) {
+  if (alloc$argnum == SWIG_NEWOBJ) %delete_array(buf$argnum);
+}
+/* old 'int' form */
+%typemap(in) (int SIZE, Char *STRING) = (size_t SIZE, Char *STRING);
+%typemap(freearg) (int SIZE, Char *STRING) = (size_t SIZE, Char *STRING);
+
+
+%enddef
+
+
+/* ------------------------------------------------------------
+ * --- String fragment methods ---
+ * ------------------------------------------------------------ */
+
+
+%define %typemaps_string(StringCode, CharCode,
+			 Char, CharName,
+			 SWIG_AsCharPtrAndSize,
+			 SWIG_FromCharPtrAndSize,
+			 SWIG_CharPtrLen,
+			 FragLimits, CHAR_MIN, CHAR_MAX)
+  
+%fragment("SWIG_From"#CharName"Ptr","header",fragment=#SWIG_FromCharPtrAndSize) {
+SWIGINTERNINLINE SWIG_Object 
+SWIG_From##CharName##Ptr(const Char *cptr)
+{ 
+  return SWIG_FromCharPtrAndSize(cptr, (cptr ? SWIG_CharPtrLen(cptr) : 0));
+}
+}
+
+%fragment("SWIG_From"#CharName"Array","header",fragment=#SWIG_FromCharPtrAndSize) {
+SWIGINTERNINLINE SWIG_Object 
+SWIG_From##CharName##Array(const Char *cptr, size_t size)
+{ 
+  return SWIG_FromCharPtrAndSize(cptr, size);
+}
+}
+
+%fragment("SWIG_As" #CharName "Ptr","header",fragment=#SWIG_AsCharPtrAndSize) {
+%define_as(SWIG_As##CharName##Ptr(obj, val, alloc), SWIG_AsCharPtrAndSize(obj, val, NULL, alloc))
+}
+
+%fragment("SWIG_As" #CharName "Array","header",fragment=#SWIG_AsCharPtrAndSize) {
+SWIGINTERN int
+SWIG_As##CharName##Array(SWIG_Object obj, Char *val, size_t size)
+{ 
+  Char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ;
+  int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc);
+  if (SWIG_IsOK(res)) {
+    if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize;
+    if (csize <= size) {
+      if (val) {
+	if (csize) memcpy(val, cptr, csize*sizeof(Char));
+	if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(Char));
+      }
+      if (alloc == SWIG_NEWOBJ) {
+	%delete_array(cptr);
+	res = SWIG_DelNewMask(res);
+      }      
+      return res;
+    }
+    if (alloc == SWIG_NEWOBJ) %delete_array(cptr);
+  }
+  return SWIG_TypeError;
+}
+}
+
+/* Char */
+
+%fragment(SWIG_From_frag(Char),"header",fragment=#SWIG_FromCharPtrAndSize) {
+SWIGINTERNINLINE SWIG_Object
+SWIG_From_dec(Char)(Char c) 
+{ 
+  return SWIG_FromCharPtrAndSize(&c,1);
+}
+}
+
+%fragment(SWIG_AsVal_frag(Char),"header",
+	  fragment="SWIG_As"#CharName"Array",
+	  fragment=FragLimits,
+	  fragment=SWIG_AsVal_frag(long)) {
+SWIGINTERN int
+SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val)
+{    
+  int res = SWIG_As##CharName##Array(obj, val, 1);
+  if (!SWIG_IsOK(res)) {
+    long v;
+    res = SWIG_AddCast(SWIG_AsVal(long)(obj, &v));
+    if (SWIG_IsOK(res)) {
+      if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) {
+	if (val) *val = %numeric_cast(v, Char);
+      } else {
+	res = SWIG_OverflowError;
+      }
+    }
+  }
+  return res;
+}
+}
+
+%typemaps_asvalfromn(CharCode, Char);
+
+%_typemap_string(StringCode, 
+		 Char,
+		 SWIG_AsCharPtrAndSize,
+		 SWIG_FromCharPtrAndSize,
+		 SWIG_CharPtrLen,
+		 SWIG_As##CharName##Ptr,
+		 SWIG_From##CharName##Ptr,
+		 SWIG_As##CharName##Array)
+
+%enddef
diff --git a/trunk/Lib/typemaps/swigmacros.swg b/trunk/Lib/typemaps/swigmacros.swg
new file mode 100644
index 0000000..928f4ec
--- /dev/null
+++ b/trunk/Lib/typemaps/swigmacros.swg
@@ -0,0 +1,245 @@
+/* -----------------------------------------------------------------------------
+ * SWIG API. Portion only visible from SWIG
+ * ----------------------------------------------------------------------------- */
+/*
+  This file implements the internal macros of the 'SWIG API', which
+  are useful to implement all the SWIG target languges.
+
+  Basic preprocessor macros:
+  --------------------------
+
+    %arg(Arg)               Safe argument wrap
+    %str(Arg)               Stringtify the argument 
+    %begin_block            Begin a execution block  
+    %end_block              End a execution block   
+    %block(Block)           Execute Block as a excecution block
+    %define_as(Def, Val)    Define 'Def' as 'Val', expanding Def and Val first
+    %ifcplusplus(V1, V2)    if C++ Mode; then V1; else V2; fi
+
+
+  Casting Operations:
+  -------------------
+  
+  Swig provides the following casting macros, which implement the
+  corresponding C++ casting operations:
+
+    %const_cast(a, Type)         const_cast<Type >(a)			       
+    %static_cast(a, Type)      	 static_cast<Type >(a)			       
+    %reinterpret_cast(a, Type) 	 reinterpret_cast<Type >(a)		       
+    %numeric_cast(a, Type)     	 static_cast<Type >(a)			       
+    %as_voidptr(a)            	 const_cast<void *>(static_cast<const void *>(a)) 
+    %as_voidptrptr(a)        	 reinterpret_cast<void **>(a)                     
+  
+  or their C unsafe versions. In C++ we use the safe version unless
+  SWIG_NO_CPLUSPLUS_CAST is defined (usually via the -nocppcast swig flag).
+
+
+  Memory allocation:
+  ------------------
+  
+  These allocation/freeing macros are safe to use in C or C++ and
+  dispatch the proper new/delete/delete[] or free/malloc calls as
+  needed.
+  
+    %new_instance(Type)             Allocate a new instance of given Type
+    %new_copy(value,Type)           Allocate and initialize a new instance with 'value'
+    %new_array(size,Type)           Allocate a new array with given size and Type
+    %new_copy_array(cptr,size,Type) Allocate and initialize a new array from 'cptr'
+    %delete(cptr)                   Delete an instance  
+    %delete_array(cptr)             Delete an array
+
+
+  Auxiliary loop macros:
+  ----------------------
+
+    %formacro(Macro, Args...) or %formacro_1(Macro, Args...)
+       for i in Args
+       do 
+          Macro($i)
+       done
+
+    %formacro_2(Macro2, Args...)
+       for i,j in Args
+       do 
+          Macro2($i, $j)
+       done
+
+
+  Flags and conditional macros:
+  -----------------------------
+
+     %mark_flag(flag)
+       flag := True
+
+     %evalif(flag,expr) 
+       if flag; then
+         expr
+       fi
+
+     %evalif_2(flag1 flag2,expr) 
+       if flag1 and flag2; then
+         expr
+       fi
+
+
+*/
+/* -----------------------------------------------------------------------------
+ * Basic preprocessor macros 
+ * ----------------------------------------------------------------------------- */
+
+#define %arg(Arg...)        Arg
+#define %str(Arg)           `Arg`
+#ifndef %begin_block
+#  define %begin_block      do {
+#endif
+#ifndef %end_block
+#  define %end_block        } while(0)
+#endif
+#define %block(Block...)    %begin_block Block; %end_block
+
+/* define a new macro */
+%define %define_as(Def, Val...)%#define Def Val %enddef
+
+/* include C++ or else value */
+%define %ifcplusplus(cppval, nocppval)
+#ifdef __cplusplus
+cppval
+#else
+nocppval
+#endif
+%enddef
+
+/* insert the SWIGVERSION in the interface and the wrapper code */
+#if SWIG_VERSION
+%insert("header") {
+%define_as(SWIGVERSION,  SWIG_VERSION)
+%#define SWIG_VERSION SWIGVERSION
+}
+#endif  
+
+
+
+/* -----------------------------------------------------------------------------
+ * Casting operators
+ * ----------------------------------------------------------------------------- */
+
+#if defined(SWIG_NO_CPLUSPLUS_CAST)
+/* Disable 'modern' cplusplus casting operators */
+# if defined(SWIG_CPLUSPLUS_CAST)
+#   undef SWIG_CPLUSPLUS_CAST
+# endif
+#endif
+
+#if defined(__cplusplus) && defined(SWIG_CPLUSPLUS_CAST)
+# define %const_cast(a,Type...)       const_cast< Type >(a)
+# define %static_cast(a,Type...)      static_cast< Type >(a)
+# define %reinterpret_cast(a,Type...) reinterpret_cast< Type >(a)
+# define %numeric_cast(a,Type...)     static_cast< Type >(a)
+#else /* C case */
+# define %const_cast(a,Type...)       (Type)(a)
+# define %static_cast(a,Type...)      (Type)(a)
+# define %reinterpret_cast(a,Type...) (Type)(a)
+# define %numeric_cast(a,Type...)     (Type)(a)
+#endif /* __cplusplus */
+
+
+#define %as_voidptr(a)               SWIG_as_voidptr(a)
+#define %as_voidptrptr(a)            SWIG_as_voidptrptr(a)
+
+%insert("header") {
+%define_as(SWIG_as_voidptr(a),    %const_cast(%static_cast(a,const void *), void *))
+%define_as(SWIG_as_voidptrptr(a), ((void)%as_voidptr(*a),%reinterpret_cast(a, void**)))
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Allocating/freeing elements 
+ * ----------------------------------------------------------------------------- */
+
+#if defined(__cplusplus) 
+# define %new_instance(Type...)             (new Type)
+# define %new_copy(val,Type...)             (new Type(%static_cast(val, const Type&)))
+# define %new_array(size,Type...)           (new Type[size])
+# define %new_copy_array(ptr,size,Type...)  %reinterpret_cast(memcpy(%new_array(size,Type), ptr, sizeof(Type)*(size)), Type*)
+# define %delete(cptr)                      delete cptr
+# define %delete_array(cptr)                delete[] cptr
+#else /* C case */
+# define %new_instance(Type...)             (Type *)malloc(sizeof(Type))
+# define %new_copy(val,Type...)             (Type *)memcpy(%new_instance(Type),&val,sizeof(Type))
+# define %new_array(size,Type...)           (Type *)malloc((size)*sizeof(Type))
+# define %new_copy_array(ptr,size,Type...)  (Type *)memcpy(%new_array(size,Type), ptr, sizeof(Type)*(size))
+# define %delete(cptr)                      free((char*)cptr)
+# define %delete_array(cptr)                free((char*)cptr)
+#endif /* __cplusplus */
+
+/* -----------------------------------------------------------------------------
+ * Swig names and mangling
+ * ----------------------------------------------------------------------------- */
+
+#define %mangle(Type...)                  #@Type
+#define %descriptor(Type...)               SWIGTYPE_ ## #@Type
+#define %string_name(Name)                "SWIG_" %str(Name)
+#define %symbol_name(Name, Type...)       SWIG_ ## Name ## _ #@Type
+#define %checkcode(Code)           	  SWIG_TYPECHECK_ ## Code
+
+
+/* -----------------------------------------------------------------------------
+ * Auxiliary loop macros 
+ * ----------------------------------------------------------------------------- */
+
+
+/* for loop for macro with one argument */
+%define %_formacro_1(macro, arg1,...)macro(arg1)
+#if #__VA_ARGS__ != "__fordone__"
+%_formacro_1(macro, __VA_ARGS__)
+#endif
+%enddef
+
+/* for loop for macro with one argument */
+%define %formacro_1(macro,...)%_formacro_1(macro,__VA_ARGS__,__fordone__)%enddef
+%define %formacro(macro,...)%_formacro_1(macro,__VA_ARGS__,__fordone__)%enddef
+
+/* for loop for macro with two arguments */
+%define %_formacro_2(macro, arg1, arg2, ...)macro(arg1, arg2)
+#if #__VA_ARGS__ != "__fordone__"
+%_formacro_2(macro, __VA_ARGS__)
+#endif
+%enddef
+
+/* for loop for macro with two arguments */
+%define %formacro_2(macro,...)%_formacro_2(macro, __VA_ARGS__, __fordone__)%enddef
+
+/* -----------------------------------------------------------------------------
+ * Swig flags
+ * ----------------------------------------------------------------------------- */
+
+/* 
+  mark a flag, ie, define a macro name but ignore it in
+  the interface. 
+  
+  the flag can be later used with %evalif
+*/
+
+%define %mark_flag(x) %define x 1 %enddef %enddef
+
+
+/*
+  %evalif and %evalif_2 are use to evaluate or process 
+  an expression if the given predicate is 'true' (1).
+*/
+%define %_evalif(_x,_expr) 
+#if _x == 1
+_expr
+#endif
+%enddef
+
+%define %_evalif_2(_x,_y,_expr) 
+#if _x == 1 && _y == 1
+_expr
+#endif
+%enddef
+
+%define %evalif(_x,_expr...) %_evalif(%arg(_x),%arg(_expr)) %enddef
+
+%define %evalif_2(_x,_y,_expr...) %_evalif_2(%arg(_x),%arg(_y),%arg(_expr)) %enddef
+
diff --git a/trunk/Lib/typemaps/swigobject.swg b/trunk/Lib/typemaps/swigobject.swg
new file mode 100644
index 0000000..e89b630
--- /dev/null
+++ b/trunk/Lib/typemaps/swigobject.swg
@@ -0,0 +1,37 @@
+/* ------------------------------------------------------------
+ * Language Object *  - Just pass straight through unmodified
+ * ------------------------------------------------------------ */
+
+%typemap(in)   SWIG_Object "$1 = $input;";
+
+%typemap(in,noblock=1)   SWIG_Object const & ($*ltype temp)
+{
+  temp = %static_cast($input, $*ltype);
+  $1 = &temp;
+}
+
+%typemap(out,noblock=1) SWIG_Object {
+  %set_output($1);
+}
+
+%typemap(out,noblock=1)  SWIG_Object const & {
+  %set_output(*$1);
+}
+
+%typecheck(SWIG_TYPECHECK_SWIGOBJECT) SWIG_Object "$1 = ($input != 0);";
+
+%typemap(throws,noblock=1) SWIG_Object {
+  %raise($1, "$type", 0);
+}
+
+%typemap(constcode,noblock=1) SWIG_Object {
+  %set_constant("$symname", $value);
+}
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+%typemap(directorin) SWIG_Object "$input = $1_name";
+%typemap(directorout) SWIG_Object "$result = $input;";
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
diff --git a/trunk/Lib/typemaps/swigtype.swg b/trunk/Lib/typemaps/swigtype.swg
new file mode 100644
index 0000000..f5c88a7
--- /dev/null
+++ b/trunk/Lib/typemaps/swigtype.swg
@@ -0,0 +1,604 @@
+/* -----------------------------------------------------------------------------
+ * --- Input arguments --- 
+ * ----------------------------------------------------------------------------- */
+/* Pointers and arrays */
+%typemap(in, noblock=1) SWIGTYPE *(void  *argp = 0, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp,$descriptor, $disown | %convertptr_flags);
+  if (!SWIG_IsOK(res)) { 
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  $1 = %reinterpret_cast(argp, $ltype);
+}
+%typemap(freearg) SWIGTYPE * "";
+
+%typemap(in, noblock=1) SWIGTYPE [] (void *argp = 0, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp,$descriptor, $disown | %convertptr_flags);
+  if (!SWIG_IsOK(res)) { 
+    %argument_fail(res, "$type", $symname, $argnum); 
+  } 
+  $1 = %reinterpret_cast(argp, $ltype);
+}
+%typemap(freearg) SWIGTYPE [] "";
+
+
+%typemap(in, noblock=1) SWIGTYPE* const&  (void *argp = 0, int res = 0, $*ltype temp) {
+  res = SWIG_ConvertPtr($input, &argp, $*descriptor, $disown | %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$*ltype", $symname, $argnum); 
+  }
+  temp = %reinterpret_cast(argp, $*ltype);
+  $1 = &temp;
+}
+%typemap(freearg) SWIGTYPE* const& "";
+
+
+/* Reference */
+%typemap(in, noblock=1) SWIGTYPE & (void *argp = 0, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  $1 = %reinterpret_cast(argp, $ltype);
+}
+%typemap(freearg) SWIGTYPE & "";
+
+#if defined(__cplusplus) && defined(%implicitconv_flag)
+%typemap(in,noblock=1,implicitconv=1) const SWIGTYPE & (void *argp = 0, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags | %implicitconv_flag);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  $1 = %reinterpret_cast(argp, $ltype);
+}
+%typemap(freearg,noblock=1,match="in",implicitconv=1) const SWIGTYPE &
+{
+  if (SWIG_IsNewObj(res$argnum)) %delete($1);
+}
+#else
+%typemap(in,noblock=1) const SWIGTYPE & (void *argp, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
+  $1 = %reinterpret_cast(argp, $ltype);
+}
+#endif
+
+/* By value */
+#if defined(__cplusplus) && defined(%implicitconv_flag)
+%typemap(in,implicitconv=1) SWIGTYPE (void *argp, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp, $&descriptor, %convertptr_flags | %implicitconv_flag);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }  
+  if (!argp) { 
+    %argument_nullref("$type", $symname, $argnum);
+  } else {
+    $&ltype temp = %reinterpret_cast(argp, $&ltype);
+    $1 = *temp;
+    if (SWIG_IsNewObj(res)) %delete(temp);
+  }
+}
+#else
+%typemap(in) SWIGTYPE (void *argp, int res = 0) {
+  res = SWIG_ConvertPtr($input, &argp, $&descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }  
+  if (!argp) { 
+    %argument_nullref("$type", $symname, $argnum);
+  } else {
+    $1 = *(%reinterpret_cast(argp, $&ltype));
+  }
+}
+#endif
+
+
+/* -----------------------------------------------------------------------------
+ * --- Output arguments --- 
+ * ----------------------------------------------------------------------------- */
+
+/* Pointers, references */
+%typemap(out,noblock=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE[] {
+  %set_output(SWIG_NewPointerObj(%as_voidptr($1), $descriptor, $owner | %newpointer_flags));
+}
+
+%typemap(out, noblock=1) SWIGTYPE* const& {
+  %set_output(SWIG_NewPointerObj(%as_voidptr(*$1), $*descriptor, $owner | %newpointer_flags));
+}
+
+/* Return by value */
+%typemap(out, noblock=1) SWIGTYPE {
+  %set_output(SWIG_NewPointerObj(%new_copy($1, $ltype), $&descriptor, SWIG_POINTER_OWN | %newpointer_flags));
+}
+
+/* -----------------------------------------------------------------------------
+ * --- Variable input --- 
+ * ----------------------------------------------------------------------------- */
+
+/* memberin/globalin/varin, for fix arrays. */
+
+%typemap(memberin) SWIGTYPE [ANY] {
+  if ($input) {
+    size_t ii = 0;
+    for (; ii < (size_t)$dim0; ++ii) $1[ii] = $input[ii];
+  } else {
+    %variable_nullref("$type","$name");
+  }
+}
+
+%typemap(globalin) SWIGTYPE [ANY] {
+  if ($input) {
+    size_t ii = 0;
+    for (; ii < (size_t)$dim0; ++ii) $1[ii] = $input[ii];
+  } else {
+    %variable_nullref("$type","$name");
+  }
+}
+
+%typemap(varin) SWIGTYPE [ANY] {
+  $basetype *inp = 0;
+  int res = SWIG_ConvertPtr($input, %as_voidptrptr(&inp), $descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  } else if (inp) {
+    size_t ii = 0;
+    for (; ii < (size_t)$dim0; ++ii) $1[ii] = inp[ii];
+  } else {
+    %variable_nullref("$type", "$name");
+  }
+}
+
+
+/* memberin/globalin/varin, for fix double arrays. */
+
+%typemap(memberin) SWIGTYPE [ANY][ANY] {
+  if ($input) {
+    size_t ii = 0;
+    for (; ii < (size_t)$dim0; ++ii) {
+      if ($input[ii]) {
+	size_t jj = 0;
+	for (; jj < (size_t)$dim1; ++jj) $1[ii][jj] = $input[ii][jj];
+      } else {
+	%variable_nullref("$type","$name");
+      }
+    }
+  } else {
+    %variable_nullref("$type","$name");
+  }
+}
+
+%typemap(globalin) SWIGTYPE [ANY][ANY] {
+  if ($input) {
+    size_t ii = 0;
+    for (; ii < (size_t)$dim0; ++ii) {
+      if ($input[ii]) {
+	size_t jj = 0;
+	for (; jj < (size_t)$dim1; ++jj) $1[ii][jj] = $input[ii][jj];
+      } else {
+	%variable_nullref("$type","$name");
+      }
+    }
+  } else {
+    %variable_nullref("$type","$name");
+  }
+}
+
+%typemap(varin) SWIGTYPE [ANY][ANY] {
+  $basetype (*inp)[$dim1] = 0;
+  int res = SWIG_ConvertPtr($input, %as_voidptrptr(&inp), $descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  } else if (inp) {
+    size_t ii = 0;
+    for (; ii < (size_t)$dim0; ++ii) {
+      if (inp[ii]) {
+	size_t jj = 0;
+	for (; jj < (size_t)$dim1; ++jj) $1[ii][jj] = inp[ii][jj];
+      } else {
+	%variable_nullref("$type", "$name");
+      }
+    }
+  } else {
+    %variable_nullref("$type", "$name");
+  }
+}
+
+/* Pointers, references, and variable size arrays */
+
+%typemap(varin,warning=SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) SWIGTYPE * {
+  void *argp = 0;
+  int res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags);  
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  $1 = %reinterpret_cast(argp, $ltype);
+}
+
+%typemap(varin,noblock=1,warning="462:Unable to set dimensionless array variable") SWIGTYPE []
+{
+  %variable_fail(SWIG_AttributeError, "$type", "read-only $name");
+}
+
+%typemap(varin,warning=SWIGWARN_TYPEMAP_SWIGTYPELEAK_MSG) SWIGTYPE & {
+  void *argp = 0;
+  int res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  if (!argp) {
+    %variable_nullref("$type", "$name");
+  }
+  $1 = *(%reinterpret_cast(argp, $ltype));
+}
+
+#if defined(__cplusplus) && defined(%implicitconv_flag)
+%typemap(varin,implicitconv=1) SWIGTYPE {
+  void *argp = 0;
+  int res = SWIG_ConvertPtr($input, &argp, $&descriptor, %convertptr_flags | %implicitconv_flag);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  if (!argp) {
+    %variable_nullref("$type", "$name");
+  } else {
+    $&type temp;
+    temp  = %reinterpret_cast(argp, $&type);
+    $1 = *temp;
+    if (SWIG_IsNewObj(res)) %delete(temp);
+  }
+}
+#else
+%typemap(varin) SWIGTYPE {
+  void *argp = 0;
+  int res = SWIG_ConvertPtr($input, &argp, $&descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  if (!argp) {
+    %variable_nullref("$type", "$name");
+  } else {
+    $1 = *(%reinterpret_cast(argp, $&type));
+  }
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * --- Variable output --- 
+ * ----------------------------------------------------------------------------- */
+
+/* Pointers and arrays */
+%typemap(varout, noblock=1) SWIGTYPE * {
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr($1), $descriptor, %newpointer_flags));
+}
+
+%typemap(varout, noblock=1) SWIGTYPE [] {
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr($1), $descriptor, %newpointer_flags));
+}
+
+/* References */
+%typemap(varout, noblock=1) SWIGTYPE & {
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(&$1), $descriptor, %newpointer_flags));
+}
+
+/* Value */
+%typemap(varout, noblock=1) SWIGTYPE {
+  %set_varoutput(SWIG_NewPointerObj(%as_voidptr(&$1), $&descriptor, %newpointer_flags));
+}
+
+/* ------------------------------------------------------------
+ * --- Typechecking rules ---
+ * ------------------------------------------------------------ */
+
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE * {
+  void *vptr = 0;
+  int res = SWIG_ConvertPtr($input, &vptr, $descriptor, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE & {
+  void *vptr = 0;
+  int res = SWIG_ConvertPtr($input, &vptr, $descriptor, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+#if defined(__cplusplus) && defined(%implicitconv_flag)
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1,implicitconv=1) const SWIGTYPE & {
+  int res = SWIG_ConvertPtr($input, 0, $descriptor, %implicitconv_flag);
+  $1 = SWIG_CheckState(res);
+}
+
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1,implicitconv=1) SWIGTYPE {
+  int res = SWIG_ConvertPtr($input, 0, $&descriptor, %implicitconv_flag);
+  $1 = SWIG_CheckState(res);
+}
+#else
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) const SWIGTYPE & {
+  void *vptr = 0;
+  int res = SWIG_ConvertPtr($input, &vptr, $descriptor, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE {
+  void *vptr = 0;
+  int res = SWIG_ConvertPtr($input, &vptr, $&descriptor, 0);
+  $1 = SWIG_CheckState(res);
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * --- Director typemaps --- *  
+ * ----------------------------------------------------------------------------- */
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+
+%typemap(directorin,noblock=1) SWIGTYPE*, SWIGTYPE* const& {
+  $input = SWIG_NewPointerObj(%as_voidptr($1_name), $descriptor, %newpointer_flags);
+}
+
+%typemap(directorin,noblock=1) SWIGTYPE {
+  $input = SWIG_NewPointerObj(%as_voidptr(&$1_name), $&descriptor, %newpointer_flags);
+}
+
+%typemap(directorin,noblock=1) SWIGTYPE& {
+  $input = SWIG_NewPointerObj(%as_voidptr(&$1_name), $descriptor, %newpointer_flags);
+}
+
+/* directorout */
+#if defined(__cplusplus) && defined(%implicitconv_flag)
+%typemap(directorout,noblock=1,implicitconv=1) SWIGTYPE (void * swig_argp, int swig_res = 0) {
+  swig_res = SWIG_ConvertPtr($input,&swig_argp,$&descriptor, %convertptr_flags | %implicitconv_flag);
+  if (!SWIG_IsOK(swig_res)) {
+    %dirout_fail(swig_res,"$type");
+  }
+  $result = *(%reinterpret_cast(swig_argp, $&ltype));
+  if (SWIG_IsNewObj(swig_res)) %delete(%reinterpret_cast(swig_argp, $&ltype));
+}
+#else
+%typemap(directorout,noblock=1) SWIGTYPE (void * swig_argp, int swig_res = 0) {
+  swig_res = SWIG_ConvertPtr($input,&swig_argp,$&descriptor, %convertptr_flags);
+  if (!SWIG_IsOK(swig_res)) {
+    %dirout_fail(swig_res,"$type");
+  }
+  $result = *(%reinterpret_cast(swig_argp, $&ltype));
+}
+#endif
+
+%typemap(directorout,noblock=1,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) 
+  SWIGTYPE *(void *swig_argp, int swig_res, swig_owntype own) {
+  swig_res = SWIG_ConvertPtrAndOwn($input, &swig_argp, $descriptor, %convertptr_flags | SWIG_POINTER_DISOWN, &own);
+  if (!SWIG_IsOK(swig_res)) {
+    %dirout_fail(swig_res,"$type");
+  }
+  $result = %reinterpret_cast(swig_argp, $ltype);
+  swig_acquire_ownership_obj(%as_voidptr($result), own /* & TODO: SWIG_POINTER_OWN */);
+}
+%typemap(directorfree,noblock=1,match="directorout") SWIGTYPE * {
+  if (director) {
+    SWIG_AcquirePtr($result, director->swig_release_ownership(%as_voidptr($input)));
+  }
+}
+
+%typemap(directorout,noblock=1,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) 
+  SWIGTYPE &(void *swig_argp, int swig_res, swig_owntype own) {
+  swig_res = SWIG_ConvertPtrAndOwn($input, &swig_argp, $descriptor, %convertptr_flags | SWIG_POINTER_DISOWN, &own);
+  if (!SWIG_IsOK(swig_res)) {
+    %dirout_fail(swig_res,"$type");
+  }
+  if (!swig_argp) { %dirout_nullref("$type"); }
+  $result = %reinterpret_cast(swig_argp, $ltype);
+  swig_acquire_ownership_obj(%as_voidptr($result), own /* & TODO: SWIG_POINTER_OWN */);
+}
+%typemap(directorfree,noblock=1,match="directorout") SWIGTYPE & {
+  if (director) {
+    SWIG_AcquirePtr($result, director->swig_release_ownership(%as_voidptr($input)));
+  }
+}
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
+
+/* ------------------------------------------------------------
+ * --- Constants ---
+ * ------------------------------------------------------------ */
+
+%typemap(constcode,noblock=1) SWIGTYPE *, SWIGTYPE &, SWIGTYPE []{ 
+  %set_constant("$symname", SWIG_NewPointerObj(%as_voidptr($value),$descriptor,%newpointer_flags));
+}
+
+%typemap(constcode,noblock=1) SWIGTYPE {
+  %set_constant("$symname", SWIG_NewPointerObj(%as_voidptr(&$value),$&descriptor,%newpointer_flags));
+}
+
+/* ------------------------------------------------------------
+ * --- Exception handling ---
+ * ------------------------------------------------------------ */
+
+%typemap(throws,noblock=1) SWIGTYPE {
+  %raise(SWIG_NewPointerObj(%new_copy($1, $ltype),$&descriptor,SWIG_POINTER_OWN), "$type", $&descriptor);
+}
+
+%typemap(throws,noblock=1) SWIGTYPE * {
+  %raise(SWIG_NewPointerObj(%as_voidptr($1),$descriptor,0), "$type", $descriptor);
+}
+
+%typemap(throws,noblock=1) SWIGTYPE [ANY] {
+  %raise(SWIG_NewPointerObj(%as_voidptr($1),$descriptor,0), "$type", $descriptor);
+}
+
+%typemap(throws,noblock=1) SWIGTYPE & {
+  %raise(SWIG_NewPointerObj(%as_voidptr(&$1),$descriptor,0), "$type", $descriptor);
+}
+
+%typemap(throws,noblock=1) (...) {
+  SWIG_exception_fail(SWIG_RuntimeError,"unknown exception");
+}
+
+/* ------------------------------------------------------------
+ * --- CLASS::* typemaps --- 
+ * ------------------------------------------------------------ */
+
+%typemap(in) SWIGTYPE (CLASS::*) {  
+  int res = SWIG_ConvertMember($input, %as_voidptr(&$1), sizeof($type),$descriptor);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum); 
+  }
+}
+
+%typemap(out,noblock=1) SWIGTYPE (CLASS::*) {
+  %set_output(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor));
+}
+
+%typemap(varin) SWIGTYPE (CLASS::*) {
+  int res = SWIG_ConvertMember($input,%as_voidptr(&$1), sizeof($type), $descriptor);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name"); 
+  }
+}
+
+%typemap(varout,noblock=1) SWIGTYPE (CLASS::*) {
+  %set_varoutput(SWIG_NewMemberObj(%as_voidptr(&$1), sizeof($type), $descriptor));
+}
+
+%typemap(constcode,noblock=1) SWIGTYPE (CLASS::*) {
+  %set_constant("$symname", SWIG_NewMemberObj(%as_voidptr(&$value), sizeof($type), $descriptor));
+}
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+
+%typemap(directorin,noblock=1) SWIGTYPE (CLASS::*) {
+  $input = SWIG_NewMemberObj(%as_voidptr(&$1_name), sizeof($type), $descriptor);
+}
+
+/* directorout */
+
+%typemap(directorout) SWIGTYPE (CLASS::*) {
+  int swig_res = SWIG_ConvertMember($input,%as_voidptr(&$result), sizeof($type), $descriptor);
+  if (!SWIG_IsOK(swig_res)) {
+    %dirout_fail(swig_res,"$type");
+  }
+}
+#endif
+
+/* ------------------------------------------------------------
+ * --- function ptr typemaps --- 
+ * ------------------------------------------------------------ */
+
+/*
+  ISO C++ doesn't allow direct casting of a function ptr to a object
+  ptr. So, maybe the ptr sizes are not the same, and we need to take
+  some providences.
+ */
+%typemap(in) SWIGTYPE ((*)(ANY)) {
+  int res = SWIG_ConvertFunctionPtr($input, (void**)(&$1), $descriptor);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type",$symname, $argnum); 
+  }
+}
+
+%typecheck(SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE ((*)(ANY)) {
+  void *ptr = 0;
+  int res = SWIG_ConvertFunctionPtr($input, &ptr, $descriptor);
+  $1 = SWIG_CheckState(res);
+}
+
+
+%typemap(out, noblock=1) SWIGTYPE ((*)(ANY)) {
+  %set_output(SWIG_NewFunctionPtrObj((void *)($1), $descriptor));
+}
+
+%typemap(varin) SWIGTYPE ((*)(ANY)) {
+  int res = SWIG_ConvertFunctionPtr($input, (void**)(&$1), $descriptor);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name"); 
+  }
+}
+
+%typemap(varout,noblock=1) SWIGTYPE ((*)(ANY)) {  
+  %set_varoutput(SWIG_NewFunctionPtrObj((void *)($1), $descriptor));
+}
+
+%typemap(constcode, noblock=1) SWIGTYPE ((*)(ANY)){
+  %set_constant("$symname", SWIG_NewFunctionPtrObj((void *)$value, $descriptor));
+}
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+
+%typemap(directorin,noblock=1) SWIGTYPE ((*)(ANY)) {
+  $input = SWIG_NewFunctionPtrObj((void*)($1_name), $descriptor);
+}
+
+/* directorout */
+
+%typemap(directorout) SWIGTYPE ((*)(ANY)) {
+  int swig_res = SWIG_ConvertFunctionPtr($input,(void**)(&$result),$descriptor);
+  if (!SWIG_IsOK(swig_res)) {
+    %dirout_fail(swig_res,"$type");
+  }
+}
+#endif
+
+
+/* ------------------------------------------------------------
+ * --- Special typemaps ---
+ * ------------------------------------------------------------ */
+
+/* VARARGS_SENTINEL typemap. Used by the %varargs directive. */
+
+%typemap(in,numinputs=0) SWIGTYPE *VARARGS_SENTINEL, SWIGTYPE VARARGS_SENTINEL "";
+
+
+/* DISOWN typemap */
+
+%typemap(in, noblock=1) SWIGTYPE *DISOWN (int res = 0) {
+  res = SWIG_ConvertPtr($input, %as_voidptrptr(&$1), $descriptor, SWIG_POINTER_DISOWN | %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %argument_fail(res,"$type", $symname, $argnum);
+  }
+}
+
+%typemap(varin) SWIGTYPE *DISOWN {
+  void *temp = 0;
+  int res = SWIG_ConvertPtr($input, &temp, $descriptor, SWIG_POINTER_DISOWN | %convertptr_flags);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  $1 = ($ltype) temp;
+}
+
+/* DYNAMIC typemap */
+
+%typemap(out,noblock=1) SWIGTYPE *DYNAMIC, SWIGTYPE &DYNAMIC {
+  %set_output(SWIG_NewPointerObj(%as_voidptr($1), SWIG_TypeDynamicCast($descriptor, %as_voidptrptr(&$1)), $owner | %newpointer_flags));
+}
+
+/* INSTANCE typemap */
+
+%typemap(out,noblock=1) SWIGTYPE INSTANCE {
+  %set_output(SWIG_NewInstanceObj(%new_copy($1, $1_ltype), $&1_descriptor, SWIG_POINTER_OWN | %newinstance_flags));
+}
+
+%typemap(out,noblock=1) SWIGTYPE *INSTANCE, SWIGTYPE &INSTANCE, SWIGTYPE INSTANCE[] {
+  %set_output(SWIG_NewInstanceObj(%as_voidptr($1), $1_descriptor, $owner | %newinstance_flags));
+}
+
+%typemap(varout,noblock=1) SWIGTYPE *INSTANCE, SWIGTYPE INSTANCE[] {
+  %set_varoutput(SWIG_NewInstanceObj(%as_voidptr($1), $1_descriptor, %newinstance_flags));
+}
+
+%typemap(varout,noblock=1) SWIGTYPE &INSTANCE {
+  %set_varoutput(SWIG_NewInstanceObj(%as_voidptr($1), $1_descriptor, %newinstance_flags));
+}
+
+%typemap(varout,noblock=1) SWIGTYPE INSTANCE {
+  %set_varoutput(SWIG_NewInstanceObj(%as_voidptr(&$1), $&1_descriptor, %newinstance_flags));
+}
diff --git a/trunk/Lib/typemaps/swigtypemaps.swg b/trunk/Lib/typemaps/swigtypemaps.swg
new file mode 100644
index 0000000..08abab0
--- /dev/null
+++ b/trunk/Lib/typemaps/swigtypemaps.swg
@@ -0,0 +1,170 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigtypemaps.swg
+ *
+ * Unified Typemap Library frontend
+ * ----------------------------------------------------------------------------- */
+
+/*
+  This file provides the frontend to the Unified Typemap Library.
+
+  When using this library in a SWIG target language, you need to
+  define a minimum set of fragments, specialize a couple of macros,
+  and then include this file.
+
+  Typically you will create a 'mytypemaps.swg' file in each target
+  languge, where you will have the following sections:
+
+    === mytypemaps.swg ===
+
+    //  Fragment section 
+    %include <typemaps/fragments.swg>
+    <include target language fragments>
+
+    // Unified typemap section 
+    <specialized the typemap library macros>
+    %include <typemaps/swigtypemaps.swg>
+
+    // Local typemap section 
+    <add/replace extra target language typemaps>
+
+    === mytypemaps.swg ===
+
+  While we add more docs, please take a look at the following cases
+  to see how you specialized the unified typemap library for a new
+  target language:
+
+      Lib/python/pytypemaps.swg
+      Lib/tcl/tcltypemaps.swg
+      Lib/ruby/rubytypemaps.swg
+      Lib/perl5/perltypemaps.swg
+    
+*/
+
+#define SWIGUTL SWIGUTL
+
+/* -----------------------------------------------------------------------------
+ *   Language specialization section. 
+ *
+ *   Tune these macros for each language as needed.
+ * ----------------------------------------------------------------------------- */
+
+/*
+  The SWIG target language object must be provided.
+  For example in python you define:
+
+    #define SWIG_Object PyObject *
+*/
+
+#if !defined(SWIG_Object) 
+#error "SWIG_Object must be defined as the SWIG target language object"
+#endif
+
+/*==== flags for new/convert methods ====*/
+
+
+#ifndef %convertptr_flags
+%define %convertptr_flags  0 %enddef
+#endif
+
+#ifndef %newpointer_flags
+%define %newpointer_flags  0 %enddef
+#endif
+
+#ifndef %newinstance_flags
+%define %newinstance_flags 0 %enddef
+#endif
+
+/*==== set output ====*/
+
+#ifndef %set_output
+/* simple set output operation */
+#define %set_output(obj)                  $result = obj
+#endif
+
+/*==== set variable output  ====*/
+
+#ifndef %set_varoutput
+/* simple set varoutput operation */
+#define %set_varoutput(obj)               $result = obj
+#endif
+
+/*==== append output ====*/
+
+#ifndef %append_output
+#if defined(SWIG_AppendOutput)
+/* simple append operation */
+#define %append_output(obj)               $result = SWIG_AppendOutput($result,obj) 
+#else
+#error "Language must define SWIG_AppendOutput or %append_output"
+#endif
+#endif
+
+/*==== set constant ====*/
+
+#ifndef %set_constant
+#if defined(SWIG_SetConstant)
+/* simple set constant operation */
+#define %set_constant(name,value)         SWIG_SetConstant(name,value)
+#else
+#error "Language must define SWIG_SetConstant or %set_constant"
+#endif
+#endif
+
+/*==== raise an exception ====*/
+
+#ifndef %raise
+#if defined(SWIG_Raise)
+/* simple raise operation */
+#define %raise(obj, type, desc)           SWIG_Raise(obj, type, desc); SWIG_fail
+#else
+#error "Language must define SWIG_Raise or %raise"
+#endif
+#endif
+
+/*==== director output exception ====*/
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+#ifndef SWIG_DirOutFail
+#define SWIG_DirOutFail(code, msg)        Swig::DirectorTypeMismatchException::raise(SWIG_ErrorType(code), msg)
+#endif
+#endif
+
+
+/* -----------------------------------------------------------------------------
+ *  Language independent definitions
+ * ----------------------------------------------------------------------------- */
+
+#define %error_block(Block...)                 %block(Block)
+#define %default_code(code)                    SWIG_ArgError(code)  
+#define %argument_fail(code, type, name, argn) SWIG_exception_fail(%default_code(code), %argfail_fmt(type, name, argn))
+#define %argument_nullref(type, name, argn)    SWIG_exception_fail(SWIG_ValueError, %argnullref_fmt(type, name, argn))
+#define %variable_fail(code, type, name)       SWIG_exception_fail(%default_code(code), %varfail_fmt(type, name))
+#define %variable_nullref(type, name)          SWIG_exception_fail(SWIG_ValueError, %varnullref_fmt(type, name))
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+#define %dirout_fail(code, type)          SWIG_DirOutFail(%default_code(code), %outfail_fmt(type))
+#define %dirout_nullref(type)             SWIG_DirOutFail(SWIG_ValueError, %outnullref_fmt(type))
+#endif
+
+/* -----------------------------------------------------------------------------
+ *  All the typemaps
+ * ----------------------------------------------------------------------------- */
+
+
+%include <typemaps/fragments.swg>
+%include <typemaps/exception.swg>
+%include <typemaps/swigtype.swg>
+%include <typemaps/void.swg>
+%include <typemaps/swigobject.swg>
+%include <typemaps/valtypes.swg>
+%include <typemaps/ptrtypes.swg>
+%include <typemaps/inoutlist.swg>
+%include <typemaps/primtypes.swg>
+%include <typemaps/string.swg>
+%include <typemaps/misctypes.swg>
+%include <typemaps/enumint.swg>
+
+
diff --git a/trunk/Lib/typemaps/traits.swg b/trunk/Lib/typemaps/traits.swg
new file mode 100644
index 0000000..b39eb39
--- /dev/null
+++ b/trunk/Lib/typemaps/traits.swg
@@ -0,0 +1,307 @@
+//
+// Use the following macro with modern STL implementations
+//
+//#define SWIG_STD_MODERN_STL
+//
+// Use this to deactive the previous definition, when using gcc-2.95
+// or similar old compilers.
+//
+//#define SWIG_STD_NOMODERN_STL
+
+// Here, we identify compilers we now have problems with STL.
+%{
+#if defined(__GNUC__)
+#  if __GNUC__ == 2 && __GNUC_MINOR <= 96
+#     define SWIG_STD_NOMODERN_STL
+#  endif
+#endif
+%}
+
+//
+// Common code for supporting the STD C++ namespace
+//
+
+%{
+#include <string>
+#include <stdexcept>
+%}
+
+%fragment("Traits","header") 
+{
+namespace swig {  
+  /*
+    type categories
+  */
+  struct pointer_category { };  
+  struct value_category { };
+
+  /*
+    General traits that provides type_name and type_info
+  */
+  template <class Type> struct traits { };
+
+  template <class Type>
+  inline const char* type_name() {
+    return traits<Type>::type_name();
+  }
+
+  template <class Type> 
+  struct traits_info {
+    static swig_type_info *type_query(std::string name) {
+      name += " *";
+      return SWIG_TypeQuery(name.c_str());
+    }    
+    static swig_type_info *type_info() {
+      static swig_type_info *info = type_query(type_name<Type>());
+      return info;
+    }
+  };
+
+  template <class Type>
+  inline swig_type_info *type_info() {
+    return traits_info<Type>::type_info();
+  }
+
+  /*
+    Partial specialization for pointers
+  */
+  template <class Type> struct traits <Type *> {
+    typedef pointer_category category;
+    static std::string make_ptr_name(const char* name) {
+      std::string ptrname = name;
+      ptrname += " *";
+      return ptrname;
+    }    
+    static const char* type_name() {
+      static std::string name = make_ptr_name(swig::type_name<Type>());
+      return name.c_str();
+    }
+  };
+
+ 
+  template <class Type, class Category = typename traits<Type>::category > 
+  struct traits_check { };
+
+  /*
+    Traits that provides the from method for an unknown type
+  */
+  template <int flags, class Type> struct traits_from_ptr {
+    static SWIG_Object from SWIG_FROM_DECL_ARGS(Type *val) {
+      return SWIG_NewPointerObj(val, type_info<Type>(), flags);
+    }
+  };
+
+  template <class Type> struct traits_from {
+    static SWIG_Object from SWIG_FROM_DECL_ARGS(const Type& val) {
+      return traits_from_ptr<SWIG_POINTER_OWN, Type>::from(new Type(val));
+    }
+  };
+
+  template <class Type> struct traits_from<Type *> {
+    static SWIG_Object from SWIG_FROM_DECL_ARGS(Type* val) {
+      return traits_from_ptr<0, Type>::from(val);
+    }
+  };
+
+  template <class Type>
+  inline SWIG_Object from SWIG_FROM_DECL_ARGS(const Type& val) {
+    return traits_from<Type>::from(val);
+  }
+
+  /*
+    Traits that provides the asptr/asval method for an unknown type
+  */
+  template <class Type>
+  struct traits_asptr {   
+    static int asptr SWIG_AS_DECL_ARGS (SWIG_Object obj, Type **val) {
+      Type *p;
+      int res = SWIG_ConvertPtr(obj, %as_voidptrptr(&p), type_info<Type>(), 0);
+      if (SWIG_IsOK(res) && val) *val = p;
+      return res;
+    }
+  }; 
+
+  template <class Type>
+  inline int asptr SWIG_AS_DECL_ARGS(SWIG_Object obj, Type **vptr) {
+    return traits_asptr<Type>::asptr SWIG_AS_CALL_ARGS(obj, vptr);
+  }
+
+  template <class Type> 
+  struct traits_asval {
+    static int asval SWIG_AS_DECL_ARGS(SWIG_Object obj, Type *val) {
+      if (val) {
+	Type *p = 0;
+	int res = traits_asptr<Type>::asptr SWIG_AS_CALL_ARGS(obj, &p);
+	if (SWIG_IsOK(res) && p) {
+	  *val = *p;
+	  if (SWIG_IsNewObj(res)) {
+	    %delete(p);
+	    res = SWIG_DelNewMask(res);
+	  }
+	}
+	return res;
+      } else {
+	return traits_asptr<Type>::asptr SWIG_AS_CALL_ARGS(obj, (Type **)(0));
+      }
+    }
+  };
+  
+  template <class Type>
+  inline int asval SWIG_AS_DECL_ARGS (SWIG_Object obj, Type *val) {
+    return traits_asval<Type>::asval SWIG_AS_CALL_ARGS(obj, val);
+  }
+
+  /*
+    Traits that provides the check method for an unknown type
+  */
+#define SWIG_CHECK_DECL_ARGS(obj) SWIG_AS_DECL_ARGS(obj, void * = 0)
+#define SWIG_CHECK_CALL_ARGS(obj) SWIG_AS_CALL_ARGS(obj, 0)
+
+  template <class Type> 
+  struct traits_checkval {
+    static int check SWIG_CHECK_DECL_ARGS(SWIG_Object obj) {
+      if (obj) {
+	int res = asval SWIG_AS_CALL_ARGS(obj, (Type *)(0));
+	return SWIG_CheckState(res);
+      } else {
+	return 0;
+      }
+    }
+  };
+
+  template <class Type> 
+  struct traits_checkptr {
+    static int check SWIG_CHECK_DECL_ARGS(SWIG_Object obj) {
+      if (obj) {
+	int res = asptr SWIG_AS_CALL_ARGS(obj, (Type **)(0));
+	return SWIG_CheckState(res);
+      } else {
+	return 0;
+      }
+    }
+  };
+
+  template <class Type> 
+  struct traits_check<Type, value_category> : traits_checkval<Type> {
+  };
+
+  template <class Type> 
+  struct traits_check<Type, pointer_category> : traits_checkptr<Type> {
+  };
+
+  template <class Type>
+  inline int check SWIG_CHECK_DECL_ARGS(SWIG_Object obj) {
+    return traits_check<Type>::check SWIG_CHECK_CALL_ARGS(obj);
+  }
+
+}
+}
+ 
+/*
+  Generate the traits for an unknown SWIGTYPE
+*/
+
+%define %traits_swigtype(Type...)
+%fragment(SWIG_Traits_frag(Type),"header",fragment="Traits") {
+  namespace swig {
+    template <>  struct traits<Type > {
+      typedef pointer_category category;
+      static const char* type_name() { return  #Type; }
+    };
+  }
+}
+%enddef
+
+
+/*
+  Generate the traits for a 'value' type, such as 'double',
+  for which the SWIG_AsVal and SWIG_From methods are already defined.
+*/
+
+%define %traits_value(Type...)
+%fragment(SWIG_Traits_frag(Type),"header",
+	  fragment=SWIG_AsVal_frag(Type),
+	  fragment=SWIG_From_frag(Type),
+	  fragment="Traits") {
+namespace swig {
+  template <> struct traits<Type > {
+    typedef value_category category;
+    static const char* type_name() { return  #Type; }
+  };  
+
+  template <>  struct traits_asval<Type > {   
+    typedef Type value_type;
+    static int asval SWIG_AS_DECL_ARGS (SWIG_Object obj, value_type *val) {
+      return SWIG_AsVal(Type)(obj, val);
+    }
+  };
+
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static SWIG_Object from SWIG_FROM_DECL_ARGS (const value_type& val) {
+      return SWIG_From(Type)(val);
+    }
+  };
+}
+}
+%enddef
+
+/*
+  Generate the traits for a 'pointer' type, such as 'std::string',
+  for which the SWIG_AsPtr and SWIG_From methods are already defined.
+*/
+
+%define %traits_pointer(Type...)
+%fragment(SWIG_Traits_frag(Type),"header",
+	  fragment=SWIG_AsVal_frag(Type),
+	  fragment=SWIG_From_frag(Type),
+	  fragment="Traits") {
+namespace swig {
+  template <> struct traits<Type > {
+    typedef pointer_category category;
+    static const char* type_name() { return  #Type; }
+  };  
+    
+  template <>  struct traits_asptr<Type > {   
+    typedef Type value_type;
+    static int asptr SWIG_AS_DECL_ARGS (SWIG_Object obj, value_type **val) {
+      return SWIG_AsPtr(Type)(obj, val);
+    }
+  };
+
+  template <>  struct traits_from<Type > {
+    typedef Type value_type;
+    static SWIG_Object from SWIG_FROM_DECL_ARGS (const value_type& val) {
+      return SWIG_From(Type)(val);
+    }
+  };
+}
+}
+%enddef
+
+/*
+  Generate the typemaps for a class that has 'value' traits
+*/
+
+%define %typemap_traits_value(Code,Type...)
+  %typemaps_asvalfrom(%arg(Code),
+		      %arg(swig::asval),
+		      %arg(swig::from),
+		      %arg(SWIG_Traits_frag(Type)),
+		      %arg(SWIG_Traits_frag(Type)),
+		      Type);
+%enddef
+
+/*
+  Generate the typemaps for a class that has 'pointer' traits
+*/
+
+%define %typemap_traits_pointer(Code,Type...)
+  %typemaps_asptrfrom(%arg(Code),
+		      %arg(swig::asptr),
+		      %arg(swig::from),
+		      %arg(SWIG_Traits_frag(Type)),
+		      %arg(SWIG_Traits_frag(Type)),
+		      Type);
+%enddef
+
diff --git a/trunk/Lib/typemaps/typemaps.swg b/trunk/Lib/typemaps/typemaps.swg
new file mode 100644
index 0000000..6e75057
--- /dev/null
+++ b/trunk/Lib/typemaps/typemaps.swg
@@ -0,0 +1,160 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemaps.swg
+ *
+ * Tcl Pointer handling
+ *
+ * These mappings provide support for input/output arguments and common
+ * uses for C/C++ pointers.
+ * ----------------------------------------------------------------------------- */
+
+// INPUT typemaps.
+// These remap a C pointer to be an "INPUT" value which is passed by value
+// instead of reference.
+
+/* 
+The following methods can be applied to turn a pointer into a simple
+"input" value.  That is, instead of passing a pointer to an object,
+you would use a real value instead.
+
+         int            *INPUT
+         short          *INPUT
+         long           *INPUT
+	 long long      *INPUT
+         unsigned int   *INPUT
+         unsigned short *INPUT
+         unsigned long  *INPUT
+         unsigned long long *INPUT
+         unsigned char  *INPUT
+         bool           *INPUT
+         float          *INPUT
+         double         *INPUT
+         
+To use these, suppose you had a C function like this :
+
+        double fadd(double *a, double *b) {
+               return *a+*b;
+        }
+
+You could wrap it with SWIG as follows :
+        
+        %include <typemaps.i>
+        double fadd(double *INPUT, double *INPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INPUT { double *a, double *b };
+        double fadd(double *a, double *b);
+
+*/
+
+// OUTPUT typemaps.   These typemaps are used for parameters that
+// are output only.   The output value is appended to the result as
+// a list element.
+
+/* 
+The following methods can be applied to turn a pointer into an "output"
+value.  When calling a function, no input value would be given for
+a parameter, but an output value would be returned.  In the case of
+multiple output values, they are returned in the form of a Tcl tuple.
+
+         int            *OUTPUT
+         short          *OUTPUT
+         long           *OUTPUT
+         long long      *OUTPUT
+         unsigned int   *OUTPUT
+         unsigned short *OUTPUT
+         unsigned long  *OUTPUT
+         unsigned long long *OUTPUT
+         unsigned char  *OUTPUT
+         bool           *OUTPUT
+         float          *OUTPUT
+         double         *OUTPUT
+         
+For example, suppose you were trying to wrap the modf() function in the
+C math library which splits x into integral and fractional parts (and
+returns the integer part in one of its parameters).K:
+
+        double modf(double x, double *ip);
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        double modf(double x, double *OUTPUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *OUTPUT { double *ip };
+        double modf(double x, double *ip);
+
+The Tcl output of the function would be a tuple containing both
+output values. 
+
+*/
+
+// INOUT
+// Mappings for an argument that is both an input and output
+// parameter
+
+/*
+The following methods can be applied to make a function parameter both
+an input and output value.  This combines the behavior of both the
+"INPUT" and "OUTPUT" methods described earlier.  Output values are
+returned in the form of a Tcl tuple.  
+
+         int            *INOUT
+         short          *INOUT
+         long           *INOUT
+         long long      *INOUT
+         unsigned int   *INOUT
+         unsigned short *INOUT
+         unsigned long  *INOUT
+         unsigned long long *INOUT
+         unsigned char  *INOUT
+         bool           *INOUT
+         float          *INOUT
+         double         *INOUT
+         
+For example, suppose you were trying to wrap the following function :
+
+        void neg(double *x) {
+             *x = -(*x);
+        }
+
+You could wrap it with SWIG as follows :
+
+        %include <typemaps.i>
+        void neg(double *INOUT);
+
+or you can use the %apply directive :
+
+        %include <typemaps.i>
+        %apply double *INOUT { double *x };
+        void neg(double *x);
+
+Unlike C, this mapping does not directly modify the input value (since
+this makes no sense in Tcl).  Rather, the modified input value shows
+up as the return value of the function.  Thus, to apply this function
+to a Tcl variable you might do this :
+
+       x = neg(x)
+
+Note : previous versions of SWIG used the symbol 'BOTH' to mark
+input/output arguments.   This is still supported, but will be slowly
+phased out in future releases.
+
+*/
+
+
+#if defined(SWIG_INOUT_NODEF)
+
+%apply_checkctypes(%typemaps_inoutn)
+
+%apply size_t& { std::size_t& };
+%apply ptrdiff_t& { std::ptrdiff_t& };
+
+#endif
diff --git a/trunk/Lib/typemaps/valtypes.swg b/trunk/Lib/typemaps/valtypes.swg
new file mode 100644
index 0000000..cd11430
--- /dev/null
+++ b/trunk/Lib/typemaps/valtypes.swg
@@ -0,0 +1,216 @@
+/*---------------------------------------------------------------------
+ * Value typemaps (Type, const Type&) for value types, such as
+ * fundamental types (int, double), that define the AsVal/From
+ * methods.
+ *
+ * To apply them, just use one of the following macros:
+ *
+ *   %typemaps_from(FromMeth, FromFrag, Type)
+ *   %typemaps_asval(CheckCode, AsValMeth, AsValFrag, Type)
+ *   %typemaps_asvalfrom(CheckCode, AsValMeth, FromMeth, AsValFrag, FromFrag, Type)
+ *
+ * or the simpler and normalize form:
+ *
+ *   %typemaps_asvalfromn(CheckCode, Type)
+ *
+ * Also, you can use the individual typemap definitions:
+ *
+ *    %value_in_typemap(asval_meth,frag,Type)
+ *    %value_varin_typemap(asval_meth,frag,Type)
+ *    %value_typecheck_typemap(checkcode,asval_meth,frag,Type)
+ *    %value_directorout_typemap(asval_meth,frag,Type)
+ *
+ *    %value_out_typemap(from_meth,frag,Type)
+ *    %value_varout_typemap(from_meth,frag,Type)
+ *    %value_constcode_typemap(from_meth,frag,Type)
+ *    %value_directorin_typemap(from_meth,frag,Type)
+ *    %value_throws_typemap(from_meth,frag,Type)
+ *
+ *---------------------------------------------------------------------*/
+
+/* in */
+
+%define %value_in_typemap(asval_meth,frag,Type...)
+  %typemap(in,noblock=1,fragment=frag) Type (Type val, int ecode = 0) {
+    ecode = asval_meth($input, &val);
+    if (!SWIG_IsOK(ecode)) {
+      %argument_fail(ecode, "$ltype", $symname, $argnum);
+    } 
+    $1 = %static_cast(val,$ltype);
+  }
+  %typemap(freearg) Type "";
+  %typemap(in,noblock=1,fragment=frag) const Type & ($*ltype temp, Type val, int ecode = 0) {  
+    ecode = asval_meth($input, &val);
+    if (!SWIG_IsOK(ecode)) {
+      %argument_fail(ecode, "$*ltype", $symname, $argnum);
+    } 
+    temp = %static_cast(val, $*ltype);
+    $1 = &temp;
+  }
+  %typemap(freearg) const Type& "";
+%enddef
+
+/* out */
+
+%define %value_out_typemap(from_meth,frag,Type...)
+  %typemap(out,noblock=1,fragment=frag) Type, const Type {
+    %set_output(from_meth(%static_cast($1,Type))); 
+  }
+  %typemap(out,noblock=1,fragment=frag) const Type& {
+    %set_output(from_meth(%static_cast(*$1,Type))); 
+  }
+%enddef
+
+/* varin */
+
+%define %value_varin_typemap(asval_meth,frag,Type...)
+  %typemap(varin,fragment=frag) Type {
+    Type val;
+    int res = asval_meth($input, &val);
+    if (!SWIG_IsOK(res)) {
+      %variable_fail(res, "$type", "$name");
+    }
+    $1 = %static_cast(val,$ltype);
+  }
+%enddef
+
+/* varout */
+
+%define %value_varout_typemap(from_meth,frag,Type...)
+  %typemap(varout,noblock=1,fragment=frag) Type, const Type&  {
+    %set_varoutput(from_meth(%static_cast($1,Type)));
+  }
+%enddef
+
+/* constant installation code */
+
+%define %value_constcode_typemap(from_meth,frag,Type...)
+  %typemap(constcode,noblock=1,fragment=frag) Type {
+    %set_constant("$symname", from_meth(%static_cast($value,Type)));
+  }
+%enddef
+
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+
+%define %value_directorin_typemap(from_meth,frag,Type...)
+  %typemap(directorin,noblock=1,fragment=frag) Type *DIRECTORIN {
+    $input = from_meth(%static_cast(*$1_name,Type)); 
+  }
+  %typemap(directorin,noblock=1,fragment=frag) Type, const Type& {
+    $input = from_meth(%static_cast($1_name,Type)); 
+  }
+%enddef
+
+/* directorout */
+
+%define %value_directorout_typemap(asval_meth,frag,Type...)
+  %typemap(directorargout,noblock=1,fragment=frag) Type *DIRECTOROUT {
+    Type swig_val;
+    int swig_res = asval_meth($input, &swig_val);
+    if (!SWIG_IsOK(swig_res)) {
+      %dirout_fail(swig_res, "$type");
+    } 
+    *$result = %static_cast(swig_val, $type);
+  }
+  %typemap(directorout,noblock=1,fragment=frag) Type {
+    Type swig_val;
+    int swig_res = asval_meth($input, &swig_val);
+    if (!SWIG_IsOK(swig_res)) {
+      %dirout_fail(swig_res, "$type");
+    }
+    $result = %static_cast(swig_val,$type);
+  }
+  %typemap(directorout,noblock=1,fragment=frag,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) const Type& {  
+    Type swig_val;
+    int swig_res = asval_meth($input, &swig_val);
+    if (!SWIG_IsOK(swig_res)) {
+      %dirout_fail(swig_res, "$type");
+    } 
+    $basetype *temp = new $basetype(($basetype)swig_val);
+    swig_acquire_ownership(temp);
+    $result = temp;
+  }
+  %typemap(directorfree,noblock=1) const Type & {
+    if (director) {
+      director->swig_release_ownership(%as_voidptr($input));
+    }
+  }
+  %typemap(directorout,fragment=frag) Type &DIRECTOROUT = Type
+%enddef
+
+#else
+
+#define %value_directorin_typemap(from_meth,frag,Type...)
+#define %value_directorout_typemap(asval_meth,frag,Type...)
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
+
+/* throws */
+
+%define %value_throws_typemap(from_meth,frag,Type...)
+  %typemap(throws,noblock=1,fragment=frag) Type {
+    %raise(from_meth(%static_cast($1,Type)), "$type", 0);
+  }
+%enddef
+
+/* typecheck */
+
+%define %value_typecheck_typemap(check,asval_meth,frag,Type...)
+  %typemap(typecheck,precedence=check,fragment=frag) Type, const Type& {
+    int res = asval_meth($input, NULL);
+    $1 = SWIG_CheckState(res);
+  }
+%enddef
+
+/*---------------------------------------------------------------------
+ * typemap definition for types with AsVal methods
+ *---------------------------------------------------------------------*/
+%define %typemaps_asval(CheckCode, AsValMeth, AsValFrag, Type...)
+  %value_in_typemap(%arg(AsValMeth), %arg(AsValFrag), Type);
+  %value_varin_typemap(%arg(AsValMeth), %arg(AsValFrag), Type);
+  %value_directorout_typemap(%arg(AsValMeth), %arg(AsValFrag), Type);
+  %value_typecheck_typemap(%arg(CheckCode), %arg(AsValMeth), %arg(AsValFrag), Type);
+  %value_input_typemap(%arg(CheckCode), %arg(AsValMeth), %arg(AsValFrag), Type);
+%enddef
+
+
+/*---------------------------------------------------------------------
+ * typemap definition for types with from method
+ *---------------------------------------------------------------------*/
+%define %typemaps_from(FromMeth, FromFrag, Type...)
+  %value_out_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_varout_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_constcode_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_directorin_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_throws_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_output_typemap(%arg(FromMeth), %arg(FromFrag), Type);
+%enddef
+
+
+/*---------------------------------------------------------------------
+ * typemap definition for types with alval/from method
+ *---------------------------------------------------------------------*/
+
+%define %typemaps_asvalfrom(CheckCode, AsValMeth, FromMeth,
+			   AsValFrag, FromFrag, Type...)
+  %typemaps_asval(%arg(CheckCode), %arg(AsValMeth), %arg(AsValFrag), Type);
+  %typemaps_from(%arg(FromMeth), %arg(FromFrag), Type);
+  %value_inout_typemap(Type);
+%enddef
+
+
+/*---------------------------------------------------------------------
+ * typemap definition for types  with for 'normalized' asval/from methods
+ *---------------------------------------------------------------------*/
+%define %typemaps_asvalfromn(CheckCode, Type...)
+  %typemaps_asvalfrom(%arg(CheckCode),
+		     SWIG_AsVal(Type), 
+		     SWIG_From(Type), 
+		     %arg(SWIG_AsVal_frag(Type)),
+		     %arg(SWIG_From_frag(Type)), 
+		     Type);
+%enddef
diff --git a/trunk/Lib/typemaps/void.swg b/trunk/Lib/typemaps/void.swg
new file mode 100644
index 0000000..aa12583
--- /dev/null
+++ b/trunk/Lib/typemaps/void.swg
@@ -0,0 +1,84 @@
+/* ------------------------------------------------------------
+ * Void * -  Accepts any kind of pointer
+ * ------------------------------------------------------------ */
+
+/* in */
+
+%typemap(in,noblock=1) void * (int res) {
+  res = SWIG_ConvertPtr($input,%as_voidptrptr(&$1), 0, $disown);
+  if (!SWIG_IsOK(res)) { 
+    %argument_fail(res, "$type", $symname, $argnum); 
+  }
+}
+%typemap(freearg) void * "";
+
+%typemap(in,noblock=1) void * const& ($*ltype temp = 0, int res) {
+  res = SWIG_ConvertPtr($input, %as_voidptrptr(&temp), 0, $disown);
+  if (!SWIG_IsOK(res)) { 
+    %argument_fail(res, "Stype", $symname, $argnum); 
+  }
+  $1 =  &temp;
+}
+%typemap(freearg) void * const& "";
+
+
+/* out */
+
+#if defined(VOID_Object)
+%typemap(out,noblock=1) void { $result = VOID_Object; }
+#else
+%typemap(out,noblock=1) void {}
+#endif
+
+/* varin */
+
+%typemap(varin) void * {
+  void *temp = 0;
+  int res = SWIG_ConvertPtr($input, &temp, 0, SWIG_POINTER_DISOWN);
+  if (!SWIG_IsOK(res)) {
+    %variable_fail(res, "$type", "$name");
+  }
+  $1 = ($1_ltype) temp;
+}
+
+/* typecheck */
+
+%typecheck(SWIG_TYPECHECK_VOIDPTR, noblock=1) void *
+{
+  void *ptr = 0;
+  int res = SWIG_ConvertPtr($input, &ptr, 0, 0);
+  $1 = SWIG_CheckState(res);
+}
+
+#if defined(SWIG_DIRECTOR_TYPEMAPS)
+
+/* directorin */
+
+%typemap(directorin,noblock=1) void *, void const*, void *const, void const *const, 
+  void const *&, void *const &, void const *const & {
+  $input = SWIG_NewPointerObj(%as_voidptr($1_name), $descriptor, %newpointer_flags);
+}
+
+/* directorout */
+
+%typemap(directorout,noblock=1) void * (void *argp, int res) {
+  res = SWIG_ConvertPtr($input, &argp, 0, 0);
+  if (!SWIG_IsOK(res)) {
+    %dirout_fail(res,"$type");
+  }
+  $result = %reinterpret_cast(argp, $ltype);
+}
+
+%typemap(directorout,noblock=1,warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) void * const& (void *argp, int res) {
+  res = SWIG_ConvertPtr($input, &argp, 0, $disown);
+  if (!SWIG_IsOK(res)) { 
+    %dirout_fail(res,"$type");
+  }
+  static $*ltype temp = %reinterpret_cast(argp, $*ltype);
+  $result =  &temp;
+}
+
+
+
+#endif /* SWIG_DIRECTOR_TYPEMAPS */
+
diff --git a/trunk/Lib/typemaps/wstring.swg b/trunk/Lib/typemaps/wstring.swg
new file mode 100644
index 0000000..2567dc7
--- /dev/null
+++ b/trunk/Lib/typemaps/wstring.swg
@@ -0,0 +1,25 @@
+%ensure_fragment(SWIG_AsWCharPtrAndSize)
+%ensure_fragment(SWIG_FromWCharPtrAndSize)
+
+
+%types(wchar_t *);
+
+%fragment("SWIG_pwchar_descriptor","header") {
+SWIGINTERN swig_type_info*
+SWIG_pwchar_descriptor()
+{
+  static int init = 0;
+  static swig_type_info* info = 0;
+  if (!init) {
+    info = SWIG_TypeQuery("_p_wchar_t");
+    init = 1;
+  }
+  return info;
+}
+}
+
+%include <typemaps/strings.swg>
+%typemaps_string(%checkcode(UNISTRING), %checkcode(UNICHAR),
+		 wchar_t, WChar, SWIG_AsWCharPtrAndSize, SWIG_FromWCharPtrAndSize, wcslen,
+		"<wchar.h>", WCHAR_MIN, WCHAR_MAX)
+
diff --git a/trunk/Lib/uffi/uffi.swg b/trunk/Lib/uffi/uffi.swg
new file mode 100644
index 0000000..78bd235
--- /dev/null
+++ b/trunk/Lib/uffi/uffi.swg
@@ -0,0 +1,103 @@
+/* Define a C preprocessor symbol that can be used in interface files
+   to distinguish between the SWIG language modules. */ 
+
+#define SWIG_UFFI
+
+/* Typespecs for basic types. */
+
+%typemap(ffitype) char ":char";
+%typemap(ffitype) unsigned char ":unsigned-char";
+%typemap(ffitype) signed char ":char";
+%typemap(ffitype) short ":short";
+%typemap(ffitype) signed short ":short";
+%typemap(ffitype) unsigned short ":unsigned-short";
+%typemap(ffitype) int ":int";
+%typemap(ffitype) signed int ":int";
+%typemap(ffitype) unsigned int ":unsigned-int";
+%typemap(ffitype) long ":long";
+%typemap(ffitype) signed long ":long";
+%typemap(ffitype) unsigned long ":unsigned-long";
+%typemap(ffitype) float ":float";
+%typemap(ffitype) double ":double";
+%typemap(ffitype) char * ":cstring";
+%typemap(ffitype) void * ":pointer-void";
+%typemap(ffitype) void ":void";
+
+// FIXME: This is guesswork
+typedef long size_t;
+
+%wrapper %{
+;; $Id$
+
+(eval-when (compile eval)
+
+;;; You can define your own identifier converter if you want.
+;;; Use the -identifier-converter command line argument to
+;;; specify its name. 
+  
+(defun identifier-convert-null (id &key type)
+  (declare (ignore type))
+  (read-from-string id))
+
+(defun identifier-convert-lispify (cname &key type)
+  (assert (stringp cname))
+  (if (eq type :constant)
+      (setf cname (format nil "*~A*" cname)))
+  (setf cname (replace-regexp cname "_" "-"))
+  (let ((lastcase :other)
+        newcase char res)
+    (dotimes (n (length cname))
+      (setf char (schar cname n))
+      (if* (alpha-char-p char)
+         then
+              (setf newcase (if (upper-case-p char) :upper :lower))
+
+              (when (or (and (eq lastcase :upper) (eq newcase :lower))
+                        (and (eq lastcase :lower) (eq newcase :upper)))
+                ;; case change... add a dash                                    
+                (push #\- res)
+                (setf newcase :other))
+
+              (push (char-downcase char) res)
+
+              (setf lastcase newcase)
+
+         else
+              (push char res)
+              (setf lastcase :other)))
+    (read-from-string (coerce (nreverse res) 'string))))
+
+(defun identifier-convert-low-level (cname &key type)
+  (assert (stringp cname))
+  (if (eq type :constant)
+    (setf cname (format nil "+~A+" cname)))
+  (setf cname (substitute #\- #\_ cname))
+  (if (eq type :operator)
+    (setf cname (format nil "%~A" cname)))
+  (if (eq type :constant-function)
+    nil)
+  (read-from-string cname))
+
+
+
+(defmacro swig-defconstant (string value &key (export T))
+  (let ((symbol (funcall *swig-identifier-converter* string :type :constant)))
+    `(eval-when (compile load eval)
+       (uffi:def-constant ,symbol ,value ,export))))
+
+(defmacro swig-defun (name &rest rest)
+  (let ((symbol (funcall *swig-identifier-converter* name :type :operator)))
+    `(eval-when (compile load eval)
+      (uffi:def-function (,name ,symbol) ,@rest)
+      (export (quote ,symbol)))))
+
+(defmacro swig-def-struct (name &rest fields)
+  "Declare a struct object"
+  (let ((symbol (funcall *swig-identifier-converter* name :type :type)))
+    `(eval-when (compile load eval)
+       (uffi:def-struct ,symbol ,@fields)
+       (export (quote ,symbol)))))
+ 
+
+) ;; eval-when
+%}
diff --git a/trunk/Lib/wchar.i b/trunk/Lib/wchar.i
new file mode 100644
index 0000000..f106a35
--- /dev/null
+++ b/trunk/Lib/wchar.i
@@ -0,0 +1,14 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * wchar.i
+ * ----------------------------------------------------------------------------- */
+
+/*
+  wchar_t not supported, unless otherwise specified in the target language.
+*/
+
+#if defined(SWIG_WCHAR)
+#undef SWIG_WCHAR
+#endif
diff --git a/trunk/Lib/windows.i b/trunk/Lib/windows.i
new file mode 100644
index 0000000..08ddc2b
--- /dev/null
+++ b/trunk/Lib/windows.i
@@ -0,0 +1,152 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * windows.i
+ *
+ * SWIG library file to support types found in windows.h as well as Microsoft
+ * integral type extensions. The types are set for 32 bit Windows.
+ * ----------------------------------------------------------------------------- */
+
+// Support for non ISO (Windows) integral types
+%apply unsigned char { unsigned __int8 };
+%apply const unsigned char& { const unsigned __int8& };
+
+%apply signed char { __int8 };
+%apply const signed char& { const __int8& };
+
+%apply unsigned short { unsigned __int16 };
+%apply const unsigned short& { const unsigned __int16& };
+
+%apply short { __int16 };
+%apply const short& { const __int16& };
+
+%apply unsigned int { unsigned __int32 };
+%apply const unsigned int& { const unsigned __int32& };
+
+%apply int { __int32 };
+%apply const int& { const __int32& };
+
+%apply unsigned long long { unsigned __int64 };
+%apply const unsigned long long& { const unsigned __int64& };
+
+%apply long long { __int64 };
+%apply const long long& { const __int64& };
+
+
+// Workaround Microsoft calling conventions
+#define __cdecl
+#define __fastcall
+#define __far
+#define __forceinline
+#define __fortran
+#define __inline
+#define __pascal
+#define __stdcall
+#define __syscall
+#define _cdecl
+#define _fastcall
+#define _inline
+#define _pascal
+#define _stdcall
+#define WINAPI
+#define __declspec(WINDOWS_EXTENDED_ATTRIBUTE)
+
+#define __w64
+
+// Types from windef.h
+typedef unsigned long ULONG;
+typedef ULONG *PULONG;
+typedef unsigned short USHORT;
+typedef USHORT *PUSHORT;
+typedef unsigned char UCHAR;
+typedef UCHAR *PUCHAR;
+typedef char *PSZ;
+typedef unsigned long DWORD;
+typedef int BOOL;
+typedef unsigned char BYTE;
+typedef unsigned short WORD;
+typedef float FLOAT;
+typedef FLOAT *PFLOAT;
+typedef BOOL *PBOOL;
+typedef BOOL *LPBOOL;
+typedef BYTE *PBYTE;
+typedef BYTE *LPBYTE;
+typedef int *PINT;
+typedef int *LPINT;
+typedef WORD *PWORD;
+typedef WORD *LPWORD;
+typedef long *LPLONG;
+typedef DWORD *PDWORD;
+typedef DWORD *LPDWORD;
+typedef void *LPVOID;
+typedef const void *LPCVOID;
+typedef int INT;
+typedef unsigned int UINT;
+typedef unsigned int *PUINT;
+
+// Types from basetsd.h
+typedef signed char INT8, *PINT8;
+typedef signed short INT16, *PINT16;
+typedef signed int INT32, *PINT32;
+typedef signed __int64 INT64, *PINT64;
+typedef unsigned char UINT8, *PUINT8;
+typedef unsigned short UINT16, *PUINT16;
+typedef unsigned int UINT32, *PUINT32;
+typedef unsigned __int64 UINT64, *PUINT64;
+typedef signed int LONG32, *PLONG32;
+typedef unsigned int ULONG32, *PULONG32;
+typedef unsigned int DWORD32, *PDWORD32;
+typedef __w64 int INT_PTR, *PINT_PTR;
+typedef __w64 unsigned int UINT_PTR, *PUINT_PTR;
+typedef __w64 long LONG_PTR, *PLONG_PTR;
+typedef __w64 unsigned long ULONG_PTR, *PULONG_PTR;
+typedef unsigned short UHALF_PTR, *PUHALF_PTR;
+typedef short HALF_PTR, *PHALF_PTR;
+typedef __w64 long SHANDLE_PTR;
+typedef __w64 unsigned long HANDLE_PTR;
+typedef ULONG_PTR SIZE_T, *PSIZE_T;
+typedef LONG_PTR SSIZE_T, *PSSIZE_T;
+typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
+typedef __int64 LONG64, *PLONG64;
+typedef unsigned __int64 ULONG64, *PULONG64;
+typedef unsigned __int64 DWORD64, *PDWORD64;
+
+// Types from winnt.h
+typedef void *PVOID;
+typedef void *PVOID64;
+typedef char CHAR;
+typedef short SHORT;
+typedef long LONG;
+typedef CHAR *PCHAR;
+typedef CHAR *LPCH, *PCH;
+typedef const CHAR *LPCCH, *PCCH;
+typedef CHAR *NPSTR;
+typedef CHAR *LPSTR, *PSTR;
+typedef const CHAR *LPCSTR, *PCSTR;
+typedef char TCHAR, *PTCHAR;
+typedef unsigned char TBYTE , *PTBYTE ;
+typedef LPSTR LPTCH, PTCH;
+typedef LPSTR PTSTR, LPTSTR, PUTSTR, LPUTSTR;
+typedef LPCSTR PCTSTR, LPCTSTR, PCUTSTR, LPCUTSTR;
+typedef SHORT *PSHORT;
+typedef LONG *PLONG;
+typedef void *HANDLE;
+typedef HANDLE *PHANDLE;
+typedef BYTE FCHAR;
+typedef WORD FSHORT;
+typedef DWORD FLONG;
+typedef LONG HRESULT;
+typedef char CCHAR;
+typedef DWORD LCID;
+typedef PDWORD PLCID;
+typedef WORD LANGID;
+typedef __int64 LONGLONG;
+typedef unsigned __int64 ULONGLONG;
+typedef LONGLONG *PLONGLONG;
+typedef ULONGLONG *PULONGLONG;
+typedef ULONGLONG DWORDLONG;
+typedef DWORDLONG *PDWORDLONG;
+typedef BYTE BOOLEAN;
+typedef BOOLEAN *PBOOLEAN;
+
diff --git a/trunk/Lib/xml/typemaps.i b/trunk/Lib/xml/typemaps.i
new file mode 100644
index 0000000..2973613
--- /dev/null
+++ b/trunk/Lib/xml/typemaps.i
@@ -0,0 +1,3 @@
+// --------------------------------------------------------------------
+// Empty file for %include to work
+// --------------------------------------------------------------------
diff --git a/trunk/Lib/xml/xml.swg b/trunk/Lib/xml/xml.swg
new file mode 100644
index 0000000..c7bdbad
--- /dev/null
+++ b/trunk/Lib/xml/xml.swg
@@ -0,0 +1 @@
+/* nothing special */
\ No newline at end of file
diff --git a/trunk/Makefile.in b/trunk/Makefile.in
new file mode 100644
index 0000000..ebfc036
--- /dev/null
+++ b/trunk/Makefile.in
@@ -0,0 +1,536 @@
+#######################################################################
+# $Id$
+#######################################################################
+
+prefix      = @prefix@
+exec_prefix = @exec_prefix@
+srcdir      = @srcdir@
+datarootdir = @datarootdir@
+
+##############################################################################
+# Compiler and system configuration
+##############################################################################
+
+SHELL       = /bin/sh
+SWIG_LIB    = @swig_lib@
+BIN_DIR     = @bindir@
+TARGET_NOEXE= swig
+TARGET      = $(TARGET_NOEXE)@EXEEXT@
+SOURCE      = Source
+DOCS        = Doc/Manual
+
+swig: libfiles source
+
+source:
+	@cd $(SOURCE) && $(MAKE)
+
+libfiles: $(srcdir)/Lib/swigwarn.swg
+
+# Files required just for the tarball
+maintainer: libfiles
+	@cd $(SOURCE) && $(MAKE) CParse/parser.h
+
+.PHONY: source libfiles maintainer
+
+#####################################################################
+# All the languages SWIG speaks (when it wants to)
+#####################################################################
+
+skip-tcl	= test -n "@SKIP_TCL@"
+skip-perl5	= test -n "@SKIP_PERL5@"
+skip-python	= test -n "@SKIP_PYTHON@"
+skip-java	= test -n "@SKIP_JAVA@"
+skip-guilescm   = test -n "@SKIP_GUILESCM@"
+skip-guile	= test -n "@SKIP_GUILE@"
+skip-mzscheme	= test -n "@SKIP_MZSCHEME@"
+skip-ruby	= test -n "@SKIP_RUBY@"
+skip-php4	= test -n "@SKIP_PHP4@"
+skip-ocaml      = test -n "@SKIP_OCAML@"
+skip-octave     = test -n "@SKIP_OCTAVE@"
+skip-pike       = test -n "@SKIP_PIKE@"
+skip-chicken	= test -n "@SKIP_CHICKEN@"
+skip-csharp	= test -n "@SKIP_CSHARP@"
+skip-modula3	= test -n "@SKIP_MODULA3@"
+skip-lua    	= test -n "@SKIP_LUA@"
+skip-allegrocl  = test -n "@SKIP_ALLEGROCL@"
+skip-clisp	= test -n "@SKIP_CLISP@"
+skip-cffi	= test -n "@SKIP_CFFI@"
+skip-uffi	= test -n "@SKIP_UFFI@"
+skip-r		= test -n "@SKIP_R@"
+
+# Additional dependencies for some tests
+skip-gcj        = test -n "@SKIP_GCJ@"
+
+#####################################################################
+# CHECK
+#####################################################################
+
+ACTION = check
+
+chk-set-swiglib		= SWIG_LIB=@ROOT_DIR@/Lib
+chk-set-swig		= SWIG=@ROOT_DIR@/$(TARGET)
+chk-set-env = $(chk-set-swiglib) $(chk-set-swig)
+
+check-aliveness:
+	test -x ./$(TARGET)
+	./$(TARGET) -version
+	./$(TARGET) -help
+	@$(skip-tcl)      || ./$(TARGET) -tcl      -help
+	@$(skip-perl5)    || ./$(TARGET) -perl     -help
+	@$(skip-python)   || ./$(TARGET) -python   -help
+	@$(skip-java)     || ./$(TARGET) -java     -help
+	@$(skip-guile)    || ./$(TARGET) -guile    -help
+	@$(skip-mzscheme) || ./$(TARGET) -mzscheme -help
+	@$(skip-ruby)     || ./$(TARGET) -ruby     -help
+	@$(skip-ocaml)    || ./$(TARGET) -ocaml    -help
+	@$(skip-octave)   || ./$(TARGET) -octave   -help
+	@$(skip-php4)     || ./$(TARGET) -php4     -help
+	@$(skip-pike)     || ./$(TARGET) -pike     -help
+	@$(skip-chicken)  || ./$(TARGET) -chicken  -help
+	@$(skip-csharp)   || ./$(TARGET) -csharp   -help
+	@$(skip-modula3)  || ./$(TARGET) -modula3  -help
+	@$(skip-lua)      || ./$(TARGET) -lua      -help
+	@$(skip-r) 	  || ./$(TARGET) -r        -help
+
+# Checks examples for compilation (does not run them)
+check-examples:					\
+	check-tcl-examples			\
+	check-perl5-examples			\
+	check-python-examples			\
+	check-java-examples			\
+	check-guile-examples			\
+	check-mzscheme-examples			\
+	check-ruby-examples			\
+	check-ocaml-examples			\
+	check-octave-examples			\
+	check-php4-examples			\
+	check-pike-examples			\
+	check-chicken-examples                  \
+	check-csharp-examples                   \
+	check-modula3-examples                  \
+	check-lua-examples			\
+	check-allegrocl-examples		\
+	check-clisp-examples			\
+	check-uffi-examples			\
+	check-cffi-examples			\
+	check-r-examples
+
+tcl_examples       :=$(shell sed '/^\#/d' $(srcdir)/Examples/tcl/check.list)
+perl5_examples     :=$(shell sed '/^\#/d' $(srcdir)/Examples/perl5/check.list)
+python_examples    :=$(shell sed '/^\#/d' $(srcdir)/Examples/python/check.list)
+java_examples      :=$(shell sed '/^\#/d' $(srcdir)/Examples/java/check.list)
+guile_examples     :=$(shell sed '/^\#/d' $(srcdir)/Examples/guile/check.list)
+mzscheme_examples  :=$(shell sed '/^\#/d' $(srcdir)/Examples/mzscheme/check.list)
+ruby_examples      :=$(shell sed '/^\#/d' $(srcdir)/Examples/ruby/check.list)
+ocaml_examples     :=$(shell sed '/^\#/d' $(srcdir)/Examples/ocaml/check.list)
+octave_examples    :=$(shell sed '/^\#/d' $(srcdir)/Examples/octave/check.list)
+php4_examples      :=$(shell sed '/^\#/d' $(srcdir)/Examples/php4/check.list)
+pike_examples      :=$(shell sed '/^\#/d' $(srcdir)/Examples/pike/check.list)
+chicken_examples   :=$(shell sed '/^\#/d' $(srcdir)/Examples/chicken/check.list)
+csharp_examples    :=$(shell sed '/^\#/d' $(srcdir)/Examples/csharp/check.list)
+modula3_examples   :=$(shell sed '/^\#/d' $(srcdir)/Examples/modula3/check.list)
+lua_examples       :=$(shell sed '/^\#/d' $(srcdir)/Examples/lua/check.list)
+allegrocl_examples :=
+clisp_examples     :=
+uffi_examples      :=
+cffi_examples      :=
+r_examples         :=$(shell sed '/^\#/d' $(srcdir)/Examples/r/check.list)
+
+# all examples
+check-%-examples :
+	@if test -z "$(skip-$*)"; then				\
+	  echo $* unknown;					\
+	  exit 1;						\
+	fi
+	@if $(skip-$*); then					\
+	  echo skipping $* $(ACTION);				\
+	else							\
+	  $(MAKE) -k -s $($*_examples:=.actionexample) LANGUAGE=$* ACTION=$(ACTION); \
+	fi
+
+# individual example
+%.actionexample:
+	@echo $(ACTION)ing Examples/$(LANGUAGE)/$*
+	@(cd Examples/$(LANGUAGE)/$* && $(MAKE) -s $(chk-set-env) $(ACTION))
+
+# gcj individual example
+java.actionexample:
+	@if $(skip-gcj); then					\
+          echo "skipping Examples/$(LANGUAGE)/java $(ACTION) (gcj test)";	\
+        else							\
+	  echo $(ACTION)ing Examples/$(LANGUAGE)/java;		\
+	  (cd Examples/$(LANGUAGE)/java && $(MAKE) -s $(chk-set-env) $(ACTION)) \
+	fi;							\
+
+gifplot-library:
+	@echo $(ACTION)ing Examples/GIFPlot/Lib
+	@cd Examples/GIFPlot/Lib && $(MAKE) -k -s $(ACTION)
+
+check-gifplot:					\
+	check-tcl-gifplot			\
+	check-perl5-gifplot			\
+	check-python-gifplot			\
+	check-java-gifplot			\
+	check-guile-gifplot			\
+	check-mzscheme-gifplot			\
+	check-ruby-gifplot			\
+	check-ocaml-gifplot			\
+	check-octave-gifplot			\
+	check-php4-gifplot			\
+	check-pike-gifplot			\
+	check-chicken-gifplot                   \
+#	check-lua-gifplot                  	\
+#	check-csharp-gifplot                    \
+#	check-modula3-gifplot
+
+check-%-gifplot: gifplot-library
+	@if test -z "$(skip-$*)"; then				\
+	  echo $* unknown;					\
+	  exit 1;						\
+	fi
+	@passed=true;						\
+	up=`$(srcdir)/Tools/capitalize $*`;			\
+	dir="Examples/GIFPlot/$$up";				\
+	if $(skip-$*); then					\
+	  echo skipping $$up $(ACTION);				\
+	elif [ ! -f $$dir/check.list ]; then			\
+	  echo skipping $$up $(ACTION) "(no $$dir/check.list)";	\
+	else							\
+	  all=`sed '/^#/d' $$dir/check.list`;			\
+	  for a in $$all; do					\
+	    echo $(ACTION)ing $$dir/$$a;			\
+	    (cd $$dir/$$a &&					\
+	    $(MAKE) -k -s $(chk-set-env) $(ACTION))		\
+	    || passed=false;					\
+	  done;							\
+	fi;							\
+	test $$passed = true
+
+# Checks testcases in the test-suite excluding those which are known to be broken
+check-test-suite:				\
+	check-tcl-test-suite			\
+	check-perl5-test-suite			\
+	check-python-test-suite			\
+	check-java-test-suite			\
+	check-guilescm-test-suite		\
+	check-guile-test-suite			\
+	check-mzscheme-test-suite		\
+	check-ruby-test-suite			\
+	check-ocaml-test-suite			\
+	check-octave-test-suite			\
+	check-php4-test-suite			\
+	check-pike-test-suite			\
+	check-csharp-test-suite			\
+	check-modula3-test-suite		\
+	check-lua-test-suite			\
+	check-allegrocl-test-suite		\
+	check-clisp-test-suite			\
+	check-uffi-test-suite			\
+	check-cffi-test-suite			\
+	check-chicken-test-suite		\
+	check-r-test-suite
+
+check-%-test-suite:
+	@if test -z "$(skip-$*)"; then					\
+	  echo $* unknown;						\
+	  exit 1;							\
+	fi
+	@passed=true;							\
+	dir="Examples/test-suite/$*";					\
+	if $(skip-$*); then						\
+	  echo skipping $* test-suite $(ACTION);			\
+	elif [ ! -d $$dir ]; then					\
+	  echo warning: cannot $(ACTION) $* test-suite "(no dir $$dir)";\
+	else								\
+	  echo $(ACTION)ing $* test-suite;				\
+	  (cd $$dir && $(MAKE) -k -s $(ACTION))				\
+	  || passed=false;						\
+	fi;								\
+	test $$passed = true
+
+# Partial test-suite check - it only invokes SWIG, ie no compilation and no runtime testing
+partialcheck-test-suite:
+	@$(MAKE) -k -s check-test-suite ACTION=partialcheck
+
+partialcheck-%-test-suite:
+	@$(MAKE) -k -s check-$*-test-suite ACTION=partialcheck
+
+check: check-aliveness check-examples check-gifplot check-test-suite
+
+# Run known-to-be-broken as well as not broken testcases in the test-suite
+all-test-suite:					\
+	all-tcl-test-suite			\
+	all-perl5-test-suite			\
+	all-python-test-suite			\
+	all-java-test-suite			\
+	all-guilescm-test-suite			\
+	all-guile-test-suite			\
+	all-mzscheme-test-suite			\
+	all-ruby-test-suite			\
+	all-ocaml-test-suite			\
+	all-octave-test-suite			\
+	all-php4-test-suite			\
+	all-pike-test-suite			\
+	all-csharp-test-suite			\
+	all-modula3-test-suite			\
+	all-lua-test-suite			\
+	all-allegrocl-test-suite		\
+	all-clisp-test-suite			\
+	all-uffi-test-suite			\
+	all-cffi-test-suite			\
+	all-chicken-test-suite			\
+	all-r-test-suite
+
+all-%-test-suite:
+	@$(MAKE) -k -s check-$*-test-suite ACTION=all
+
+# Run known-to-be-broken testcases in the test-suite
+broken-test-suite:				\
+	broken-tcl-test-suite			\
+	broken-perl5-test-suite			\
+	broken-python-test-suite		\
+	broken-java-test-suite			\
+	broken-guilescm-test-suite		\
+	broken-guile-test-suite			\
+	broken-mzscheme-test-suite		\
+	broken-ruby-test-suite			\
+	broken-ocaml-test-suite			\
+	broken-octave-test-suite		\
+	broken-php4-test-suite			\
+	broken-pike-test-suite			\
+	broken-csharp-test-suite		\
+	broken-modula3-test-suite		\
+	broken-lua-test-suite			\
+	broken-allegrocl-test-suite		\
+	broken-clisp-test-suite			\
+	broken-uffi-test-suite			\
+	broken-cffi-test-suite			\
+	broken-chicken-test-suite		\
+	broken-r-test-suite
+
+broken-%-test-suite:
+	@$(MAKE) -k -s check-$*-test-suite ACTION=broken
+
+#####################################################################
+# CLEAN
+#####################################################################
+
+clean: clean-objects clean-libfiles clean-examples clean-gifplot clean-test-suite clean-docs
+
+clean-objects: clean-source
+
+clean-source:
+	@echo cleaning Source
+	@cd $(SOURCE) && $(MAKE) -s clean
+	@rm -f $(TARGET)
+
+clean-libfiles:
+	@rm -f $(srcdir)/Lib/swigwarn.swg
+
+clean-examples:
+	@$(MAKE) -k -s check-examples ACTION=clean
+
+clean-gifplot:
+	@$(MAKE) -k -s check-gifplot ACTION=clean
+
+clean-test-suite:
+	@$(MAKE) -k -s check-test-suite ACTION=clean
+
+clean-%-examples:
+	@$(MAKE) -k -s check-$*-examples ACTION=clean
+
+clean-%-test-suite:
+	@$(MAKE) -k -s check-$*-test-suite ACTION=clean
+
+clean-%-gifplot:
+	@$(MAKE) -k -s check-$*-gifplot ACTION=clean
+
+clean-docs:
+	@echo cleaning Docs
+	@test -d $(DOCS) || exit 0; cd $(DOCS) && $(MAKE) -s clean
+
+maintainer-clean: clean-libfiles
+	@cd $(SOURCE) && $(MAKE) maintainer-clean
+
+#####################################################################
+# DISTCLEAN
+#####################################################################
+
+DISTCLEAN-DEAD = config.status config.log config.cache swig.spec Makefile mkmf.log libtool
+
+distclean: distclean-objects clean-examples clean-gifplot distclean-test-suite clean-docs distclean-dead
+
+distclean-objects: distclean-source
+
+distclean-source:
+	@echo distcleaning Source
+	@cd $(SOURCE) && $(MAKE) -s distclean
+	@rm -f $(TARGET)
+
+distclean-test-suite:
+	@echo distcleaning Examples/test-suite
+	@$(MAKE) -k -s noskip-test-suite ACTION=distclean
+
+noskip-test-suite:				\
+	noskip-tcl-test-suite			\
+	noskip-perl5-test-suite			\
+	noskip-python-test-suite		\
+	noskip-java-test-suite			\
+	noskip-guilescm-test-suite		\
+	noskip-guile-test-suite			\
+	noskip-mzscheme-test-suite		\
+	noskip-ruby-test-suite			\
+	noskip-ocaml-test-suite			\
+	noskip-octave-test-suite		\
+	noskip-php4-test-suite			\
+	noskip-pike-test-suite			\
+	noskip-csharp-test-suite		\
+	noskip-lua-test-suite			\
+	noskip-allegrocl-test-suite		\
+	noskip-clisp-test-suite			\
+	noskip-uffi-test-suite			\
+	noskip-cffi-test-suite			\
+	noskip-chicken-test-suite		\
+	noskip-r-test-suite
+
+noskip-%-test-suite:
+	dir="Examples/test-suite/$*";					\
+	if [ ! -d $$dir ]; then						\
+	  echo warning: cannot $(ACTION) $* test-suite "(no dir $$dir)";\
+	else								\
+	  echo $(ACTION)ing $$dir;					\
+	  (cd $$dir && $(MAKE) -k -s $(ACTION))				\
+	fi;
+
+distclean-dead:
+	rm -f $(DISTCLEAN-DEAD)
+
+#####################################################################
+# Update the Lib/swigwarn.swg file
+# Note: Generated into the source tree rather than build tree
+#####################################################################
+
+$(srcdir)/Lib/swigwarn.swg: $(srcdir)/Source/Include/swigwarn.h
+	mkdir -p Lib
+	echo "/* Automatically generated file containing all the swig warning codes.  */" > $@
+	echo "/* Do not modify this file by hand, change 'Source/Include/swigwarn.h'  */" >> $@
+	echo "/* and use the command 'make Lib/swigwarn.swg' instead.                 */" >> $@
+	echo >> $@; echo >> $@
+	awk '/#define WARN/{$$1="%define"; $$2="SWIG"$$2; $$3=sprintf("%d %%enddef", $$3); print $$0; next;}\
+	      /#/{next;} {print $0}' < $? >> $@
+
+#####################################################################
+# TARGETS: install & friends
+#####################################################################
+
+INSTALL         = @abs_srcdir@/Tools/config/install-sh -c
+INSTALL_DATA    = ${INSTALL} -m 644
+INSTALL_PROGRAM = ${INSTALL} -m 755
+MKINSTDIRS      = @abs_srcdir@/Tools/config/install-sh -m 0755 -d
+# Use standard autoconf approach to transform executable name using --program-prefix and --program-suffix
+transform	= @program_transform_name@
+
+install: install-main install-lib
+	@echo "Installation complete"
+
+install-main:
+	@echo "Installing SWIG executable"
+	@$(MKINSTDIRS) $(DESTDIR)$(BIN_DIR)
+	@echo "Installing $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@"
+	@$(INSTALL_PROGRAM) $(TARGET) $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@
+
+lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php4 ocaml octave \
+	pike chicken csharp modula3 allegrocl clisp lua cffi uffi r
+
+lib-modules = std
+
+
+install-lib: 
+	@echo "Installing the SWIG library"
+	@$(MKINSTDIRS) $(DESTDIR)$(SWIG_LIB)
+	@for file in $(srcdir)/Lib/*.i $(srcdir)/Lib/*.swg ; do \
+	    i=`basename $$file` ;				\
+	    echo "Installing $(DESTDIR)$(SWIG_LIB)/$$i";	\
+            $(INSTALL_DATA) $$file $(DESTDIR)$(SWIG_LIB)/$$i;	\
+	    done;
+	@for lang in $(lib-languages) $(lib-modules);		\
+	    do							\
+	    echo "Installing language specific files for $$lang"; \
+	    dst=$(DESTDIR)$(SWIG_LIB)/$$lang;			\
+	    $(MKINSTDIRS) $$dst;				\
+	     (doti="`cd $(srcdir)/Lib/$$lang && ls *.i 2>/dev/null || echo ''`"; \
+	      dotswg="`cd $(srcdir)/Lib/$$lang && ls *.swg 2>/dev/null || echo ''`"; \
+	      if [ -f $(srcdir)/Lib/$$lang/extra-install.list ]; then	\
+		  extra="`sed '/^#/d' $(srcdir)/Lib/$$lang/extra-install.list`";	\
+	      fi;						\
+	      files="`echo $$doti $$dotswg $$extra`";		\
+	      if [ x"$$files" = x ]; then			\
+		  echo "Installing nothing from Lib/$$lang";	\
+	      else for file in $$doti $$dotswg $$extra;		\
+		  do						\
+		  echo "Installing $$dst/$$file";		\
+		  $(INSTALL_DATA) $(srcdir)/Lib/$$lang/$$file $$dst/$$file; \
+		  done;						\
+	      fi) ; 						\
+	done
+
+
+#####################################################################
+# TARGETS: uninstall & friends
+#####################################################################
+
+uninstall: uninstall-main uninstall-lib
+	@echo "Uninstall complete"
+
+uninstall-main:
+	@echo "Uninstalling SWIG executable $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@"
+	rm -f $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@
+
+uninstall-lib:
+	@echo "Uninstalling the SWIG library"
+	rm -rf $(DESTDIR)$(SWIG_LIB)/
+
+############################################################################
+# DIST and other maintenance
+############################################################################
+
+# distribution directory
+dd = @PACKAGE_NAME@-@PACKAGE_VERSION@
+srpm = @PACKAGE_NAME@-@PACKAGE_VERSION@
+
+dist:
+	@echo "not implemented"
+	false
+
+srcrpm:
+	rm -fr $(srpm) $(srpm).src.rpm
+	echo "TODO: update to use svn instead of cvs"
+	cvs export -d $(srpm) -r HEAD SWIG
+	cp swig.spec $(srpm)
+	tar -cf - $(srpm) | gzip --best > $(srpm).tar.gz
+	rm -fr $(srpm)
+	rpmbuild -ts $(srpm).tar.gz
+
+# Update the autoconf files for detecting host/targets. Automake will do this in
+# version 1.10 for our case of not having a top level Makefile.am. Until then we
+# can fetch them manually and will have to commit them to CVS.
+configfiles:
+	wget ftp://ftp.gnu.org/pub/gnu/config/config.guess -O Tools/config/config.guess
+	chmod a+x Tools/config/config.guess
+	wget ftp://ftp.gnu.org/pub/gnu/config/config.sub -O Tools/config/config.sub
+	chmod a+x Tools/config/config.sub
+
+# Regenerate Makefile if Makefile.in or config.status have changed.
+Makefile: $(srcdir)/Makefile.in config.status
+	$(SHELL) ./config.status
+
+# This target is usually called from Source/Makefile when configure.in has
+# changed.
+am--refresh: $(srcdir)/configure
+
+$(srcdir)/configure: $(srcdir)/configure.in
+	@echo "Build system is out of date.  If the following commands fail, please reconfigure by hand (rerun: ./autogen.sh && ./configure)"
+	cd $(srcdir) && ./autogen.sh
+	$(SHELL) ./config.status --recheck
+
+# Makefile ends here
diff --git a/trunk/Misc/fileheader b/trunk/Misc/fileheader
new file mode 100644
index 0000000..dcdbdeb
--- /dev/null
+++ b/trunk/Misc/fileheader
@@ -0,0 +1,10 @@
+/* ----------------------------------------------------------------------------- 
+ * file.c
+ *
+ *     This file does a bunch of stuff.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
diff --git a/trunk/NEW b/trunk/NEW
new file mode 100644
index 0000000..b329eb8
--- /dev/null
+++ b/trunk/NEW
@@ -0,0 +1,267 @@
+New Features and Important Changes, v1.3
+
+Author(s) :  David Beazley
+
+March 21, 2003
+
+1. Introduction
+---------------
+This document briefly explains some of the most important changes made
+since the release of SWIG1.1.  The goal is to provide information for
+people who want to upgrade an older SWIG interface to the new version.
+
+Most changes pertain to the internal implementation of SWIG and the
+organization of the core, parser, and language modules.  As a SWIG
+user, almost all of these changes are hidden from view except for a
+few important cases where changes to the core have dramatically
+altered SWIG's old behavior.
+
+2. Types and typemaps
+---------------------
+2.1 Variables of the form 'const type *' are no longer wrapped as
+     constants, but as C global variables.  The earlier SWIG behavior
+     was incorrect due to Dave's misinterpretation of 'const' in the C 
+     language specification.   
+
+     If you have written an interface that expects to create
+     constants using 'const type *' you will need to rewrite those 
+     specifications using a new %constant directive like this:
+
+       %constant(type *) name = value;
+
+2.2  SWIG generally has better support for pointers, 'const',
+     arrays, and pointers to functions.
+
+2.3  Typemaps are now applied to a more precisely defined set
+     of datatypes.  For example, consider the following
+     typemap:
+
+           %typemap(in) foo * {
+                ... get a foo ...
+           }
+
+     In SWIG1.1, this typemap would get applied to 'foo *',
+     'foo &', 'foo []', 'foo[][]', and so forth.
+
+     In SWIG1.3, this typemap *only* gets applied to 'foo *' and
+     'const foo *'. It does *NOT* get mapped to the other 
+     variants listed above.
+
+2.4  Bug fix.  SWIG now correctly handles typemaps of the form
+
+          %typemap(in) Object {
+               ... get an object ...
+          }
+
+2.5  The memberout typemap is no longer available and is withdrawn.
+     The old implementation was essentially useless because of the
+     way in which code was generated.
+
+2.6  The memberin typemap is now inserted inline in the generated 
+     wrapper code.  This provides access to scripting-specific
+     variables in the wrapper function.
+
+2.7  SWIG-1.3.10 features a total rewrite of the typemap system.
+     Typemaps now use a different variable naming scheme.  Typemaps
+     for arguments look like this:
+
+       %typemap(in) sometype {
+           $1 = convert value ($input);
+       }
+
+     The variable $1 replaces $target and the variable $input replaces
+     $source.
+
+     For output values, typemaps look like this:
+
+       %typemap(out) sometype {
+          $result = create result ($1);
+       }
+
+     The variable $1 replaces $source and the variable $result replaces
+     $target.
+
+     See Doc/Manual/Typemaps.html for a full description of the new
+     typemap system.
+
+2.8  Multi-argument typemaps are now supported.   This solves a common
+     problem that occurs with functions like this
+
+        void foo(char *buffer, int len);
+
+     where you would like to make the two arguments operate as a single
+     object in the target language.
+
+2.9  Types such as 'const int &', 'const double &', are passed as
+     values instead of pointers.
+
+2.10 C++ namespaces are now supported.
+
+3. Type checking
+----------------
+
+SWIG no longer uses the functions SWIG_GetPtr() and SWIG_MakePtr() to
+parse datatypes in wrapper code.  This is because the type of a
+pointer is no longer associated with a string, but with a special
+"swig_type_info *" object.  If you are not using typemaps, this change
+should cause no noticable effects.  However, if you have written
+typemaps to handle pointers, here are the essential details:
+
+3.1  Type name mangling is different in SWIG1.3.  For a type of
+     "int **", SWIG1.1 used to produce a name of the form
+     "_int_pp".  SWIG1.3 on the other hand, produces a name
+      of the form "_p_p_int".   There are a number of reasons for
+      changing the format, but I'd rather not go into it here. You'll
+      just have to learn to live with it :-).
+
+3.2  Types are described by a special "swig_type_info *" object.   Everywhere
+     a string was used before, an object of this type will be used.  
+     The "swig_type_info *" for a given type can always be obtained
+     using macros involving the mangled typename in 3.1.  For example,
+     the type object of of 'int **' is 'SWIGTYPE_p_p_int'.
+
+3.3  Instead of SWIG_GetPtr, a function of the following form is used:
+
+        int SWIG_ConvertPtr(ScriptObj *o, void **ptr, swig_type_info *ty, int flags);
+
+     Note: the function name may differ in certain implementations (read
+     the source). For example:
+
+        int SWIG_ConvertPtr(ScriptObj *o, void **ptr, SWIGTYPE_p_p_int,0);
+
+     Passing a value of '0' for the type will accept any pointer. This
+     works kind of like 'void *'.  The flags argument is reserved for
+     future expansion.
+
+3.4. To create a pointer object, one uses a function similar to 
+ 
+        ScriptObj *SWIG_NewPointer(void *ptr, swig_type_info *ty, int flags);
+
+     It works in a similar manner:
+
+         p = SWIG_NewPointer(ptr, SWIGTYPE_p_p_int, 0);
+
+     You will have to read the source to get the exact function name
+     used.  The flags argument is implementation specific and reserved
+     for future expansion.
+
+3.5. If, for whatever reason, you need to obtain the 'swig_type_info *'
+     outside the context of a wrapper file, you can use the
+     SWIG_TypeQuery() function. For example:
+
+         swig_type_info *ty = SWIG_TypeQuery("int **");
+
+     this function returns an appropriate type_info structure or NULL
+     if no such type is registered.
+
+3.6  SWIG does not generate swig_type_info structures for types that are
+     not actually used in an interface file.   As a result, the type
+     checking tables for SWIG1.3 tend to be much smaller than for SWIG1.1.
+
+*** Note: The old string-based type checking scheme is not going to
+return to SWIG so do not ask for backwards compatibility.  The new
+scheme is substantially faster, it is less error-prone, it requires no
+dynamic memory allocation, it works better with the runtime libraries, 
+and it is simpler to implement than the old string based approach.
+
+4. Deprecated Features (incomplete list)
+----------------------------------------
+
+4.1 Documentation system.  The old documentation system has been removed
+    entirely.  I expect it to return someday, but it will have a much
+    different form (probably influenced by XML).
+
+4.2 The %val and %out directives.  These directives used to attach
+    properties to function parameters such as
+
+           void foo(%val int *ptr);
+
+    The same effect can now be achieved with typemaps:
+
+           void foo(int *INPUT);
+
+
+4.3 Extensions to the %module and %init directive are no longer
+    supported. For example:
+
+        %module example, foo, bar
+
+    This used to perform a special kind of multi-module 
+    initialization for static linking.   If you really
+    need to do this, you will have to manually insert
+    code into the module initialization function.
+
+4.4 %ifdef, %ifndef, %endif, %if, %elif, %else directives are
+    withdrawn. SWIG now has a real preprocessor.
+
+4.5 %checkout directive removed.
+
+4.6 %except and %new are deprecated.
+
+4.7 %readonly and %readwrite are deprecated.  Use %immutable instead.
+
+4.8 The %addmethods directive has been renamed to %extend.
+
+5. Language specific changes
+----------------------------
+
+5.1 Python shadow classes are much more efficient and pass the shadow objects
+    directly to the C wrappers.
+
+5.2 Tcl code generation is substantially improved--especially for C++.
+    
+5.3 Tcl module can now link to global variables of any type.
+
+5.4 Perl shadow classes improved and optimized somewhat.
+
+5.5 The Guile module represents pointers as smobs.  (They used to be
+    mangled into strings.)  Memory leaks and type conversion bugs have been
+    fixed.  The Guile module system, including dynamic loading, and
+    exceptions are supported.  A typemap-driven procedure-documentation
+    system has been added (requires Guile 1.4).  Procedures-with-setters
+    can be generated.
+
+5.6 The Python module now automatically creates shadow class objects from the
+    C wrappers.  This fixes a bunch of hard problems related to typemaps,
+    exception handling, and more.
+
+6. New Features
+---------------
+
+6.1 Java module added
+
+6.2 Ruby module added
+
+6.3 Mzscheme module added.
+
+6.4 Integrated preprocessor.  You can now use C macros in SWIG interface files.
+
+6.5 PHP module added.
+
+6.6 %rename directive is greatly enhanced to deal with overloaded functions.
+
+6.7 Support for simple templates
+
+6.8 Support for overloaded operators.
+
+6.9 %feature directive.
+
+6.10 Ocaml module added.
+
+6.11 XML module added.
+
+6.12 CHICKEN module added.
+
+6.13 C# module added.
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/trunk/README b/trunk/README
new file mode 100644
index 0000000..2898130
--- /dev/null
+++ b/trunk/README
@@ -0,0 +1,545 @@
+SWIG (Simplified Wrapper and Interface Generator)
+
+Version: 1.3.36 (24 June 2008)
+
+Tagline: SWIG is a compiler that integrates C and C++ with languages
+         including Perl, Python, Tcl, Ruby, PHP, Java, Ocaml, Lua,
+         Scheme (Guile, MzScheme, CHICKEN), Pike, C#, Modula-3,
+         Common Lisp (CLISP, Allegro CL, CFFI, UFFI), Octave and R.
+
+SWIG reads annotated C/C++ header files and creates wrapper code (glue
+code) in order to make the corresponding C/C++ libraries available to
+the listed languages, or to extend C/C++ programs with a scripting
+language.
+
+This distribution represents the latest development release of SWIG.
+The guilty parties working on this are:
+
+Active Developers:
+ William Fulton (wsf@fultondesigns.co.uk)               (SWIG core, Java, C#, Windows, Cygwin)
+ Olly Betts (olly@survex.com)                           (PHP)
+ John Lenz                                              (Guile, MzScheme updates, Chicken module, runtime system)
+ Mark Gossage (mark@gossage.cjb.net)                    (Lua)
+ Joseph Wang (joe@gnacademy.org)                        (R)
+ Gonzalo Garramuno (ggarra@advancedsl.com.ar)           (Ruby, Ruby's UTL)
+ Xavier Delacour (xavier.delacour@gmail.com)            (Octave)
+
+Major contributors include:
+ Dave Beazley (dave-swig@dabeaz.com)                    (SWIG core, Python, Tcl, Perl)
+ Henning Thielemann (swig@henning-thielemann.de)        (Modula3)
+ Matthias Köppe (mkoeppe@mail.math.uni-magdeburg.de)    (Guile, MzScheme)
+ Luigi Ballabio (luigi.ballabio@fastwebnet.it)          (STL wrapping)
+ Mikel Bancroft (mikel@franz.com)                       (Allegro CL)
+ Surendra Singhi (efuzzyone@netscape.net)               (CLISP, CFFI)
+ Marcelo Matus (mmatus@acms.arizona.edu)                (SWIG core, Python, UTL[python,perl,tcl,ruby])
+ Art Yerkes (ayerkes@speakeasy.net)                     (Ocaml)
+ Lyle Johnson (lyle@users.sourceforge.net)              (Ruby)
+ Charlie Savage (cfis@interserv.com)                    (Ruby)
+ Thien-Thi Nguyen (ttn@glug.org)                        (build/test/misc)
+ Richard Palmer (richard@magicality.org)                (PHP)
+ Sam Liddicott - Anonova Ltd (saml@liddicott.com)       (PHP)
+ Tim Hockin - Sun Microsystems (thockin@sun.com)        (PHP)
+ Kevin Ruland                                           (PHP)
+ Shibukawa Yoshiki                                      (Japanese Translation)
+ Jason Stewart (jason@openinformatics.com)              (Perl5)
+ Loic Dachary                                           (Perl5)
+ David Fletcher                                         (Perl5)
+ Gary Holt                                              (Perl5)
+ Masaki Fukushima                                       (Ruby)
+ Scott Michel (scottm@cs.ucla.edu)                      (Java directors)
+ Tiger Feng (songyanf@cs.uchicago.edu)                  (SWIG core)
+ Mark Rose (mrose@stm.lbl.gov)                          (Directors)
+ Jonah Beckford (beckford@usermail.com)                 (CHICKEN)
+ Ahmon Dancy (dancy@franz.com)				(Allegro CL)
+ Dirk Gerrits                                           (Allegro CL)
+ Neil Cawse                                             (C#)
+ Harco de Hilster                                       (Java)
+ Alexey Dyachenko (dyachenko@fromru.com)                (Tcl)
+ Bob Techentin                                          (Tcl)
+ Martin Froehlich <MartinFroehlich@ACM.org>             (Guile)
+ Marcio Luis Teixeira <marciot@holly.colostate.edu>     (Guile)
+ Duncan Temple Lang                                     (R)
+
+Past contributors include:
+ James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran
+ Kovuk, Oleg Tolmatcev, Tal Shalif, Lluis Padro, Chris Seatory, Igor Bely, Robin Dunn
+ (See CHANGES for a more complete list).
+
+Portions also copyrighted by companies/corporations;
+ Network Applied Communication Laboratory, Inc
+ Information-technology Promotion Agency, Japan
+
+Up-to-date SWIG related information can be found at
+
+        http://www.swig.org
+
+A SWIG FAQ and other hints can be found on the SWIG Wiki:
+
+       http://www.dabeaz.com/cgi-bin/wiki.pl
+
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!                      IMPORTANT                         !!!!!!!
+!!!!!!!                                                        !!!!!!!
+!!!!!!! Previous SWIG-1.1 users should read the documentation  !!!!!!!
+!!!!!!! file Doc/Manual/SWIG.html before trying to use SWIG-1.3!!!!!!!
+!!!!!!! on existing SWIG interfaces.  This is the most current !!!!!!!
+!!!!!!! documentation that describes new 1.3 features and      !!!!!!!
+!!!!!!! incompatibilities.                                     !!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+What's New?
+===========
+
+SWIG-1.3.36 summary:
+- Enhancement to directors to wrap all protected members
+- Optimisation feature for objects returned by value
+- A few bugs fixes in the PHP, Java, Ruby, R, C#, Python, Lua and 
+  Perl modules
+- Other minor generic bug fixes
+
+SWIG-1.3.35 summary:
+- Octave language module added
+- Bug fixes in Python, Lua, Java, C#, Perl modules
+- A few other generic bugs and runtime assertions fixed
+
+SWIG-1.3.34 summary:
+- shared_ptr support for Python
+- Support for latest R - version 2.6
+- Various minor improvements/bug fixes for R, Lua, Python, Java, C#
+- A few other generic bug fixes, mainly for templates and using statements
+
+SWIG-1.3.33 summary:
+- Fix regression for Perl where C++ wrappers would not compile
+- Fix regression parsing macros
+
+SWIG-1.3.32 summary:
+- shared_ptr support for Java and C#
+- Enhanced STL support for Ruby
+- Windows support for R
+- Fixed long-standing memory leak in PHP Module
+- Numerous fixes and minor enhancements for Allegrocl, C#, cffi, Chicken, Guile,
+  Java, Lua, Ocaml, Perl, PHP, Python, Ruby, Tcl.
+- Improved warning support
+
+SWIG-1.3.31 summary:
+- Python modern classes regression fix
+
+SWIG-1.3.30 summary:
+- Python-2.5 support
+- New language module: R
+- Director support added for C#
+- Numerous director fixes and improvements
+- Improved mingw/msys support
+- Better constants support in Guile and chicken modules
+- Support for generating PHP5 class wrappers
+- Important Java premature garbage collection fix
+- Minor improvements/fixes in cffi, php, allegrocl, perl, chicken, lua, ruby,
+  ocaml, python, java, c# and guile language modules
+- Many many other bug fixes
+
+SWIG-1.3.29 summary:
+- Numerous important bug fixes
+- Few minor new features
+- Some performance improvements in generated code for Python
+
+SWIG-1.3.28 summary:
+- More powerful renaming (%rename) capability.
+- More user friendly warning handling.
+- Add finer control for default constructors and destructors. We discourage
+  the use of the 'nodefault' option, which disables both constructors and
+  destructors, leading to possible memory leaks. Use instead 'nodefaultctor'
+  and/or 'nodefaultdtor'.
+- Automatic copy constructor wrapper generation via the 'copyctor' option/feature.
+- Better handling of Windows extensions and types.
+- Better runtime error reporting.
+- Add the %catches directive to catch and dispatch exceptions.
+- Add the %naturalvar directive for more 'natural' variable wrapping.
+- Better default handling of std::string variables using the %naturalvar directive.
+- Add the %allowexcept and %exceptionvar directives to handle exceptions when
+  accessing a variable.
+- Add the %delobject directive to mark methods that act like destructors.
+- Add the -fastdispatch option to enable smaller and faster overload dispatch
+  mechanism.
+- Template support for %rename, %feature and %typemap improved.
+- Add/doc more debug options, such as -dump_module, -debug_typemaps, etc.
+- Unified typemap library (UTL) potentially providing core typemaps for all
+  scripting languages based on the recently evolving Python typemaps.
+- New language module: Common Lisp with CFFI.
+- Python, Ruby, Perl and Tcl use the new UTL, many old reported and hidden 
+  errors with typemaps are now fixed.
+- Initial Java support for languages using the UTL via GCJ, you can now use 
+  Java libraries in your favorite script language using gcj + swig.
+- Tcl support for std::wstring.
+- PHP4 module update, many error fixes and actively maintained again.
+- Allegrocl support for C++, also enhanced C support.
+- Ruby support for bang methods.
+- Ruby support for user classes as native exceptions.
+- Perl improved dispatching in overloaded functions via the new cast and rank
+  mechanism.
+- Perl improved backward compatibility, 5.004 and later tested and working.
+- Python improved backward compatibility, 1.5.2 and later tested and working.
+- Python can use the same cast/rank mechanism via the -castmode option.
+- Python implicit conversion mechanism similar to C++, via the %implicitconv
+  directive (replaces and improves the implicit.i library). 
+- Python threading support added.
+- Python STL support improved, iterators are supported and STL containers can
+  use now the native PyObject type.
+- Python many performance options and improvements, try the -O option to test
+  all of them. Python runtime benchmarks show up to 20 times better performance
+  compared to 1.3.27 and older versions.
+- Python support for 'multi-inheritance' on the python side.
+- Python simplified proxy classes, now swig doesn't need to generate the
+  additional 'ClassPtr' classes.
+- Python extended support for smart pointers.
+- Python better support for static member variables.
+- Python backward compatibility improved, many projects that used to work
+  only with  swig-1.3.21 to swig-1.3.24 are working again with swig-1.3.28
+- Python test-suite is now 'valgrinded' before release, and swig also
+  reports memory leaks due to missing destructors.
+- Minor bug fixes and improvements to the Lua, Ruby, Java, C#, Python, Guile,
+  Chicken, Tcl and Perl modules.
+
+SWIG-1.3.27 summary:
+- Fix bug in anonymous typedef structures which was leading to strange behaviour
+
+SWIG-1.3.26 summary:
+- New language modules: Lua, CLISP and Common Lisp with UFFI.
+- Big overhaul to the PHP module.
+- Change to the way 'extern' is handled.
+- Minor bug fixes specific to  C#, Java, Modula3, Ocaml, Allegro CL,
+  XML, Lisp s-expressions, Tcl, Ruby and Python modules.
+- Other minor improvements and bug fixes.
+
+SWIG-1.3.25 summary:
+- Improved runtime type system.  Speed of module loading improved in
+  modules with lots of types.  SWIG_RUNTIME_VERSION has been increased
+  from 1 to 2, but the API is exactly the same; only internal changes
+  were made.
+- The languages that use the runtime type system now support external
+  access to the runtime type system.
+- Various improvements with typemaps and template handling.
+- Fewer warnings in generated code.
+- Improved colour documentation.
+- Many C# module improvements (exception handling, prevention of early
+  garbage collection, C# attributes support added, more flexible type
+  marshalling/asymmetric types.)
+- Minor improvements and bug fixes specific to the C#, Java, TCL, Guile,
+  Chicken, MzScheme, Perl, Php, Python, Ruby and Ocaml modules).
+- Various other bug fixes and memory leak fixes.
+
+SWIG-1.3.24 summary:
+- Improved enum handling
+- More runtime library options
+- More bugs fixes for templates and template default arguments, directors
+  and other areas.
+- Better smart pointer support, including data members, static members
+  and %extend.
+
+SWIG-1.3.23 summary:
+- Improved support for callbacks
+- Python docstring support and better error handling
+- C++ default argument support for Java and C# added.
+- Improved c++ default argument support for the scripting languages plus
+  option to use original (compact) default arguments.
+- %feature and %ignore/%rename bug fixes and mods - they might need default
+  arguments specified to maintain compatible behaviour when using the new
+  default arguments wrapping.
+- Runtime library changes: Runtime code can now exist in more than one module
+  and so need not be compiled into just one module
+- Further improved support for templates and namespaces
+- Overloaded templated function support added
+- More powerful default typemaps (mixed default typemaps)
+- Some important %extend and director code bug fixes
+- Guile now defaults to using SCM API.  The old interface can be obtained by
+  the -gh option.
+- Various minor improvements and bug fixes for C#, Chicken, Guile, Java, 
+  MzScheme, Perl, Python and Ruby
+- Improved dependencies generation for constructing Makefiles.
+
+SWIG-1.3.22 summary:
+- Improved exception handling and translation of C errors or C++
+  exceptions into target language exceptions.
+- Improved enum support, mapping to built-in Java 1.5 enums and C#
+  enums or the typesafe enum pattern for these two languages.
+- Python - much better STL suppport and support for std::wstring,
+  wchar_t and FILE *.
+- Initial support for Modula3 and Allegro CL.
+- 64 bit TCL support.
+- Java and C#'s proxy classes are now nearly 100% generated from
+  typemaps and/or features for finer control on the generated code.
+- SWIG runtime library support deprecation.
+- Improved documentation. SWIG now additionally provides documentation
+  in the form of a single HTML page as well as a pdf document.
+- Enhanced C++ friend declaration support.
+- Better support for reference counted classes.
+- Various %fragment improvements.
+- RPM fixes.
+- Various minor improvements and bug fixes for C#, Chicken, Guile, Java, 
+  MzScheme, Perl, Php, Python, Ruby and XML.
+
+
+The SWIG-1.3.x development releases offer a huge number of improvements
+over older SWIG-1.1 releases. These improvements include:
+
+   - Support for C++ overloaded functions and methods.
+   - Support for C++ smart pointers.
+   - Support for C++ namespaces
+   - Support for C++ overloaded operators.
+   - Support for C++ templates including member templates.
+   - Support for C++ template specialization and partial specialization.
+   - Support for C++ friend declarations.
+   - Parsing support for almost all C/C++ datatypes.
+   - Automatic translation of C++ exception specifiers.
+   - Contract support.
+   - A full C preprocessor with macro expansion. Includes C99 variadic macros.
+   - Java, Ruby, MzScheme, PHP4, OCAML, Pike, CHICKEN, XML and C# modules
+     added.  Guile module improved.
+   - Director support - upcalls for C++ virtual functions into the target 
+     language proxy class.
+   - Better code generation.   SWIG is better able to make optimizations
+     in order to generate less code.
+   - Testing framework part of the distribution ("make -k check" support).
+   - A lot of minor bug fixes and cleanup.
+   - Better Windows support.
+
+If you used SWIG-1.1, a number of old features are missing from SWIG-1.3.
+
+   - The SWIG-1.1 documentation system is gone and hasn't been
+     replaced yet.  This is on the long-term to-do list.
+
+   - The Tcl7.x and Perl4 modules are deprecated and no longer
+     included.
+
+   - A wide variety of old SWIG command-line options and
+     obscure features are gone.
+
+   - A lot of old %pragma directives and obscure undocumented
+     customization features have been eliminated.  The same
+     functionality is now available through other means.
+
+   - Objective C support doesn't work right now.  No ETA as to
+     when it will return.
+
+Although we are making some attempt to preserve backwards
+compatibility with interfaces written for SWIG-1.1, SWIG-1.3
+incorporates a number of very substantial modifications to type
+handling, typemaps, and wrapper code generation.  Therefore, if you
+are making extensive use of advanced SWIG features, interfaces written
+for SWIG-1.1 may not work.  We apologize for the inconvenience, but
+these changes are needed in order to fix a number of annoying
+"features" in SWIG-1.1.  Hopefully the list of new features will
+provide enough incentive for you to upgrade (and that the
+modifications to your interfaces will only be minor).
+
+In addition, SWIG-1.3 makes no attempt to be compatible with SWIG-1.1 at
+the C++ API level so language modules written for SWIG-1.1 will most
+definitely not work with this release.
+
+See the documentation for details of the SWIG_VERSION preprocessor
+symbol if you have backward compatibility issues and need to use more
+than one version of SWIG.
+
+The files NEW and CHANGES describe in some detail all of the important
+changes that have been made to the system.  Experienced users would be
+well advised to read this.
+
+Release Notes
+=============
+Please see the CHANGES files for a detailed list of bug fixes and
+new features. A summary of the changes is included in this README file.
+
+Windows Installation
+====================
+Please see the Doc/Manual/Windows.html file for instructions on installing
+SWIG on Windows and running the examples. The Windows distribution is
+called swigwin and includes a prebuilt SWIG executable, swig.exe, included in
+the same directory as this README file. Otherwise it is exactly the same as
+the main SWIG distribution. There is no need to download anything else.
+
+Unix Installation
+=================
+You must use GNU `make' to build SWIG.
+
+http://www.gnu.org/software/make/
+
+To build and install SWIG, simply type the following:
+
+     % ./configure
+     % make
+     % make install
+
+By default SWIG installs itself in /usr/local.  If you need to install SWIG in
+a different location or in your home directory, use the --prefix option
+to ./configure.  For example:
+
+     % ./configure --prefix=/home/yourname/projects
+     % make
+     % make install
+
+Note: the directory given to --prefix must be an absolute pathname.  Do *NOT* use
+the ~ shell-escape to refer to your home directory.  SWIG won't work properly
+if you do this.
+
+The file INSTALL details more about using configure. Also try
+
+     % ./configure --help.
+
+The configure script will attempt to locate various packages on your machine
+including Tcl, Perl5, Python and all the other target languages that SWIG
+uses.  Don't panic if you get 'not found' messages--SWIG does not need these
+packages to compile or run.   The configure script is actually looking for
+these packages so that you can try out the SWIG examples contained
+in the 'Examples' directory without having to hack Makefiles.
+
+Please see the Documentation section below on installing documentation as
+none is installed by default.
+
+SWIG used to include a set of runtime libraries for some languages for working
+with multiple modules. These are no longer built during the installation stage.
+However, users can build them just like any wrapper module as described in
+the documentation, Doc/Manual/Modules.html. The CHANGES file also lists some
+examples which build the runtime library.
+
+Notes:
+
+(1) If you checked the code out via SVN, you will have to run ./autogen.sh
+    before typing 'configure'.    In addition, a full build of SWIG requires
+    the use of bison.
+
+Macintosh OS X Installation
+============================
+SWIG is known to work on various flavors of OS X.  Follow the Unix installation
+instructions above.   However, as of this writing, there is still great deal of
+inconsistency with how shared libaries are handled by various scripting languages
+on OS X.   We've tried to resolve these differences to the extent of our knowledge.
+This release was most recently checked with the Panther release of OS X on a 
+Macintosh G5 system.   Your mileage may vary.
+
+Users of OS X should be aware that Darwin handles shared libraries and linking in 
+a radically different way than most Unix systems.  In order to test SWIG and run
+the examples, SWIG configures itself to use flat namespaces and to allow undefined 
+symbols (-flat_namespace -undefined suppress).  This mostly closely follows the Unix 
+model and makes it more likely that the SWIG examples will work with whatever 
+installation of software you might have.   However, this is generally not the recommended
+technique for building larger extension modules.  Instead, you should utilize
+Darwin's two-level namespaces.  Some details about this can be found here
+
+http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNamespaces.html
+
+Needless to say, you might have to experiment a bit to get things working at first.
+
+Testing
+=======
+If you want to test SWIG before installation, type the following:
+
+    % make -k check
+
+'make -k check' requires at least one of the target languages to be
+installed.  If it fails, it may mean that you have an uninstalled
+language module or that the file 'Examples/Makefile' has been
+incorrectly configured.  It may also fail due to compiler issues such
+as broken C++ compiler.  Even if 'make -k check' fails, there is a
+pretty good chance SWIG still works correctly---you will just have to
+mess around with one of the examples and some makefiles to get it to work.
+
+The testing suite executed by 'make -k check' is designed to stress-test
+many parts of the implementation including obscure corner cases. If some
+of these tests fail or generate warning messages, there is no reason for
+alarm---the test may be related to some new SWIG feature or a difficult bug
+that we're trying to resolve.  Chances are that SWIG will work just fine
+for you. Note that if you have more than one CPU/core, then you can use
+parallel make can be used to speed up the check as it does take quite some
+time to run, for example:
+
+    % make -j2 -k check
+
+Also, SWIG's support for C++ is sufficiently advanced that certain
+tests may fail on older C++ compilers (for instance if your compiler
+does not support member templates).   These errors are harmless if you
+don't intend to use these features in your own programs.
+
+Note: The test-suite currently contains around 250 tests.  If you
+have many different target languages installed and a slow machine, it
+might take more than an hour to run the test-suite.
+
+Examples
+========
+The Examples directory contains a variety of examples of using SWIG
+and it has some browsable documentation.  Simply point your browser to
+the file "Example/index.html".
+
+The Examples directory also includes Visual C++ project (.dsp) files for
+building some of the examples on Windows.
+
+Known Issues
+============
+There are minor known bugs, details of which are in the bug tracker, see
+http://www.swig.org/bugs.html.
+
+Troubleshooting
+===============
+In order to operate correctly, SWIG relies upon a set of library
+files.  If after building SWIG, you get error messages like this,
+
+    % swig foo.i
+    :1. Unable to find 'swig.swg'
+    :3. Unable to find 'tcl8.swg'
+
+it means that SWIG has either been incorrectly configured or
+installed.  To fix this:
+
+    1.  Make sure you remembered to do a 'make install' and that
+        the installation actually worked.  Make sure you have
+        write permission on the install directory.
+
+    2.  If that doesn't work, type 'swig -swiglib' to find out
+        where SWIG thinks its library is located.
+
+    3.  If the location is not where you expect, perhaps
+        you supplied a bad option to configure.  Use
+        ./configure --prefix=pathname to set the SWIG install
+        location.   Also, make sure you don't include a shell
+        escape character such as ~ when you specify the path.
+
+    4.  The SWIG library can be changed by setting the SWIG_LIB
+        environment variable.  However, you really shouldn't
+        have to do this.
+
+If you are having other troubles, you might look at the SWIG Wiki at
+http://www.dabeaz.com/cgi-bin/wiki.pl.
+
+Documentation
+=============
+The Doc/Manual directory contains the most recent set of updated
+documentation for this release. The documentation is available in
+three different formats, each of which contains identical content.
+These format are, pdf (SWIGDocumentation.pdf), single
+page html (Doc/Manual/SWIGDocumentation.html) or multiple page html
+(other files in Doc/Manual). Please select your chosen format and
+copy/install to wherever takes your fancy.
+
+This is a development release and the documentation is largely, but 
+not entirely up to date.  We are working on it, but there
+was a lot of old documentation and it is taking some time to
+update and complete. Please be patient or volunteer to help.
+
+There is some technical developer documentation available in the
+Doc/Devel subdirectory.  This is not necessarily up-to-date, but it
+has some information on SWIG internals.
+
+Participate!
+============
+Please report any errors and submit patches (if possible)!  We only
+have access to a limited variety of hardware (Linux, Solaris, OS-X,
+and Windows). All contributions help.
+
+If you would like to join the SWIG development team or contribute a
+language module to the distribution, please contact the swig-dev
+mailing list, details at http://www.swig.org/mail.html.
+
+
+ -- The SWIG Maintainers
+
+
+
diff --git a/trunk/Source/CParse/cparse.h b/trunk/Source/CParse/cparse.h
new file mode 100644
index 0000000..06a901c
--- /dev/null
+++ b/trunk/Source/CParse/cparse.h
@@ -0,0 +1,72 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cparse.h
+ *
+ * SWIG parser module.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id$ */
+
+#ifndef SWIG_CPARSE_H_
+#define SWIG_CPARSE_H_
+
+#include "swig.h"
+#include "swigwarn.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* cscanner.c */
+  extern String *cparse_file;
+  extern int cparse_line;
+  extern int cparse_cplusplus;
+  extern int cparse_start_line;
+
+  extern void Swig_cparse_cplusplus(int);
+  extern void scanner_file(File *);
+  extern void scanner_next_token(int);
+  extern void skip_balanced(int startchar, int endchar);
+  extern void skip_decl(void);
+  extern void scanner_check_typedef(void);
+  extern void scanner_ignore_typedef(void);
+  extern void scanner_last_id(int);
+  extern void scanner_clear_rename(void);
+  extern void scanner_set_location(String_or_char *, int line);
+  extern void Swig_cparse_follow_locators(int);
+  extern void start_inline(char *, int);
+  extern String *scanner_ccode;
+  extern int yylex();
+
+/* parser.y */
+  extern SwigType *Swig_cparse_type(String *);
+  extern Node *Swig_cparse(File *);
+  extern Hash *Swig_cparse_features();
+  extern void SWIG_cparse_set_compact_default_args(int defargs);
+  extern int SWIG_cparse_template_reduce(int treduce);
+
+/* util.c */
+  extern void Swig_cparse_replace_descriptor(String *s);
+  extern void cparse_normalize_void(Node *);
+  extern Parm *Swig_cparse_parm(String *s);
+  extern ParmList *Swig_cparse_parms(String *s);
+
+
+/* templ.c */
+  extern int Swig_cparse_template_expand(Node *n, String *rname, ParmList *tparms, Symtab *tscope);
+  extern Node *Swig_cparse_template_locate(String *name, ParmList *tparms, Symtab *tscope);
+  extern void Swig_cparse_debug_templates(int);
+
+#ifdef __cplusplus
+}
+#endif
+#define SWIG_WARN_NODE_BEGIN(Node) \
+ { \
+  String *wrnfilter = Node ? Getattr(Node,"feature:warnfilter") : 0; \
+  if (wrnfilter) Swig_warnfilter(wrnfilter,1)
+#define SWIG_WARN_NODE_END(Node) \
+  if (wrnfilter) Swig_warnfilter(wrnfilter,0); \
+ }
+#endif
diff --git a/trunk/Source/CParse/cscanner.c b/trunk/Source/CParse/cscanner.c
new file mode 100644
index 0000000..032c71f
--- /dev/null
+++ b/trunk/Source/CParse/cscanner.c
@@ -0,0 +1,903 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * scanner.c
+ *
+ * SWIG tokenizer.  This file is a wrapper around the generic C scanner
+ * found in Swig/scanner.c.   Extra logic is added both to accomodate the
+ * bison-based grammar and certain peculiarities of C++ parsing (e.g.,
+ * operator overloading, typedef resolution, etc.).  This code also splits
+ * C identifiers up into keywords and SWIG directives.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_cscanner_c[] = "$Id$";
+
+#include "cparse.h"
+#include "parser.h"
+#include <string.h>
+#include <ctype.h>
+
+/* Scanner object */
+static Scanner *scan = 0;
+
+/* Global string containing C code. Used by the parser to grab code blocks */
+DOHString *scanner_ccode = 0;
+
+/* Error reporting/location information */
+int     cparse_line = 1;
+String *cparse_file = 0;
+int     cparse_start_line = 0;
+
+/* C++ mode */
+int cparse_cplusplus = 0;
+
+/* Private vars */
+static int scan_init = 0;
+static int num_brace = 0;
+static int last_brace = 0;
+static int last_id = 0;
+static int rename_active = 0;
+static int expanding_macro = 0;
+static int follow_locators = 0;
+
+/* -----------------------------------------------------------------------------
+ * Swig_cparse_cplusplus()
+ * ----------------------------------------------------------------------------- */
+
+void Swig_cparse_cplusplus(int v) {
+  cparse_cplusplus = v;
+}
+
+/* ----------------------------------------------------------------------
+ * locator()
+ *
+ * Support for locator strings.   These are strings of the form
+ * @SWIG:filename,line,id@ emitted by the SWIG preprocessor.  They
+ * are primarily used for macro line number reporting 
+ * ---------------------------------------------------------------------- */
+
+typedef struct Locator {
+  String         *filename;
+  int             line_number;
+  struct Locator *next;
+} Locator;
+
+static Locator *locs = 0;
+
+/* we just use the locator to mark when active/deactive the linecounting */
+
+static void scanner_locator(String *loc) {
+  if (!follow_locators) {
+    if (Equal(loc, "/*@SWIG@*/")) {
+      /* End locator. */
+      if (expanding_macro)
+	--expanding_macro;
+    } else {
+      /* Begin locator. */
+      ++expanding_macro;
+    }
+    /* Freeze line number processing in Scanner */
+    Scanner_freeze_line(scan,expanding_macro);
+  } else {
+    int c;
+    Locator *l;
+    Seek(loc, 7, SEEK_SET);
+    c = Getc(loc);
+    if (c == '@') {
+      /* Empty locator.  We pop the last location off */
+      if (locs) {
+	Scanner_set_location(scan,locs->filename,locs->line_number);
+	cparse_file = locs->filename;
+	cparse_line = locs->line_number;
+	l = locs->next;
+	free(locs);
+	locs = l;
+      }
+      return;
+    }
+
+    /* We're going to push a new location */
+    l = (Locator *) malloc(sizeof(Locator));
+    l->filename = cparse_file;
+    l->line_number = cparse_line;
+    l->next = locs;
+    locs = l;
+
+    /* Now, parse the new location out of the locator string */
+    {
+      String *fn = NewStringEmpty();
+      /*      Putc(c, fn); */
+      
+      while ((c = Getc(loc)) != EOF) {
+	if ((c == '@') || (c == ','))
+	  break;
+	Putc(c, fn);
+      }
+      cparse_file = Swig_copy_string(Char(fn));
+      Clear(fn);
+      cparse_line = 1;
+      /* Get the line number */
+      while ((c = Getc(loc)) != EOF) {
+	if ((c == '@') || (c == ','))
+	  break;
+	Putc(c, fn);
+      }
+      cparse_line = atoi(Char(fn));
+      Clear(fn);
+      
+      /* Get the rest of it */
+      while ((c = Getc(loc)) != EOF) {
+	if (c == '@')
+	  break;
+	Putc(c, fn);
+      }
+      /*  Printf(stderr,"location: %s:%d\n",cparse_file,cparse_line); */
+      Scanner_set_location(scan,cparse_file,cparse_line);
+      Delete(fn);
+    }
+  }
+}
+
+void Swig_cparse_follow_locators(int v) {
+   follow_locators = v;
+}
+
+
+/* ----------------------------------------------------------------------------
+ * scanner_init()
+ *
+ * Initialize buffers
+ * ------------------------------------------------------------------------- */
+
+void scanner_init() {
+  scan = NewScanner();
+  Scanner_idstart(scan,"%");
+  scan_init = 1;
+  scanner_ccode = NewStringEmpty();
+}
+
+/* ----------------------------------------------------------------------------
+ * scanner_file(DOHFile *f)
+ *
+ * Start reading from new file
+ * ------------------------------------------------------------------------- */
+void scanner_file(DOHFile * f) {
+  if (!scan_init) scanner_init();
+  Scanner_clear(scan);
+  Scanner_push(scan,f);
+}
+
+/* ----------------------------------------------------------------------------
+ * start_inline(char *text, int line)
+ *
+ * Take a chunk of text and recursively feed it back into the scanner.  Used
+ * by the %inline directive.
+ * ------------------------------------------------------------------------- */
+
+void start_inline(char *text, int line) {
+  String *stext = NewString(text);
+
+  Seek(stext,0,SEEK_SET);
+  Setfile(stext,cparse_file);
+  Setline(stext,line);
+  Scanner_push(scan,stext);
+  Delete(stext);
+}
+
+/* -----------------------------------------------------------------------------
+ * skip_balanced()
+ *
+ * Skips a piece of code enclosed in begin/end symbols such as '{...}' or
+ * (...).  Ignores symbols inside comments or strings.
+ * ----------------------------------------------------------------------------- */
+
+void skip_balanced(int startchar, int endchar) {
+  Clear(scanner_ccode);
+
+  if (Scanner_skip_balanced(scan,startchar,endchar) < 0) {
+    Swig_error(Scanner_file(scan),Scanner_errline(scan), "Missing '%c'. Reached end of input.\n", endchar);
+    return;
+  }
+
+  cparse_line = Scanner_line(scan);
+  cparse_file = Scanner_file(scan);
+
+  Append(scanner_ccode, Scanner_text(scan));
+  if (endchar == '}')
+    num_brace--;
+  return;
+}
+
+/* ----------------------------------------------------------------------------
+ * void skip_decl(void)
+ *
+ * This tries to skip over an entire declaration.   For example
+ *
+ *  friend ostream& operator<<(ostream&, const char *s);
+ *
+ * or
+ *  friend ostream& operator<<(ostream&, const char *s) { };
+ *
+ * ------------------------------------------------------------------------- */
+
+void skip_decl(void) {
+  int tok;
+  int done = 0;
+  int start_line = Scanner_line(scan);
+
+  while (!done) {
+    tok = Scanner_token(scan);
+    if (tok == 0) {
+      if (!Swig_error_count()) {
+	Swig_error(cparse_file, start_line, "Missing semicolon. Reached end of input.\n");
+      }
+      return;
+    }
+    if (tok == SWIG_TOKEN_LBRACE) {
+      if (Scanner_skip_balanced(scan,'{','}') < 0) {
+	Swig_error(cparse_file, start_line, "Missing '}'. Reached end of input.\n");
+      }
+      break;
+    }
+    if (tok == SWIG_TOKEN_SEMI) {
+      done = 1;
+    }
+  }
+  cparse_file = Scanner_file(scan);
+  cparse_line = Scanner_line(scan);
+}
+
+/* ----------------------------------------------------------------------------
+ * int yylook()
+ *
+ * Lexical scanner.
+ * ------------------------------------------------------------------------- */
+
+int yylook(void) {
+
+  int tok = 0;
+
+  while (1) {
+    if ((tok = Scanner_token(scan)) == 0)
+      return 0;
+    if (tok == SWIG_TOKEN_ERROR) {
+      Swig_error(Scanner_file(scan), Scanner_errline(scan), Scanner_errmsg(scan));
+      continue;
+    }
+    cparse_start_line = Scanner_start_line(scan);
+    cparse_line = Scanner_line(scan);
+    cparse_file = Scanner_file(scan);
+
+    switch(tok) {
+    case SWIG_TOKEN_ID:
+      return ID;
+    case SWIG_TOKEN_LPAREN: 
+      return LPAREN;
+    case SWIG_TOKEN_RPAREN: 
+      return RPAREN;
+    case SWIG_TOKEN_SEMI:
+      return SEMI;
+    case SWIG_TOKEN_COMMA:
+      return COMMA;
+    case SWIG_TOKEN_STAR:
+      return STAR;
+    case SWIG_TOKEN_RBRACE:
+      num_brace--;
+      if (num_brace < 0) {
+	Swig_error(cparse_file, cparse_line, "Syntax error. Extraneous '}'\n");
+	num_brace = 0;
+      } else {
+	return RBRACE;
+      }
+      break;
+    case SWIG_TOKEN_LBRACE:
+      last_brace = num_brace;
+      num_brace++;
+      return LBRACE;
+    case SWIG_TOKEN_EQUAL:
+      return EQUAL;
+    case SWIG_TOKEN_EQUALTO:
+      return EQUALTO;
+    case SWIG_TOKEN_PLUS:
+      return PLUS;
+    case SWIG_TOKEN_MINUS:
+      return MINUS;
+    case SWIG_TOKEN_SLASH:
+      return SLASH;
+    case SWIG_TOKEN_AND:
+      return AND;
+    case SWIG_TOKEN_LAND:
+      return LAND;
+    case SWIG_TOKEN_OR:
+      return OR;
+    case SWIG_TOKEN_LOR:
+      return LOR;
+    case SWIG_TOKEN_XOR:
+      return XOR;
+    case SWIG_TOKEN_NOT:
+      return NOT;
+    case SWIG_TOKEN_LNOT:
+      return LNOT;
+    case SWIG_TOKEN_NOTEQUAL:
+      return NOTEQUALTO;
+    case SWIG_TOKEN_LBRACKET:
+      return LBRACKET;
+    case SWIG_TOKEN_RBRACKET:
+      return RBRACKET;
+    case SWIG_TOKEN_QUESTION:
+      return QUESTIONMARK;
+    case SWIG_TOKEN_LESSTHAN:
+      return LESSTHAN;
+    case SWIG_TOKEN_LTEQUAL:
+      return LESSTHANOREQUALTO;
+    case SWIG_TOKEN_LSHIFT:
+      return LSHIFT;
+    case SWIG_TOKEN_GREATERTHAN:
+      return GREATERTHAN;
+    case SWIG_TOKEN_GTEQUAL:
+      return GREATERTHANOREQUALTO;
+    case SWIG_TOKEN_RSHIFT:
+      return RSHIFT;
+    case SWIG_TOKEN_PERIOD:
+      return PERIOD;
+    case SWIG_TOKEN_MODULO:
+      return MODULO;
+    case SWIG_TOKEN_COLON:
+      return COLON;
+    case SWIG_TOKEN_DCOLONSTAR:
+      return DSTAR;
+      
+    case SWIG_TOKEN_DCOLON:
+      {
+	int nexttok = Scanner_token(scan);
+	if (nexttok == SWIG_TOKEN_STAR) {
+	  return DSTAR;
+	} else if (nexttok == SWIG_TOKEN_NOT) {
+	  return DCNOT;
+	} else {
+	  Scanner_pushtoken(scan,nexttok,Scanner_text(scan));
+	  if (!last_id) {
+	    scanner_next_token(DCOLON);
+	    return NONID;
+	  } else {
+	    return DCOLON;
+	  }
+	}
+      }
+      break;
+      
+      /* Look for multi-character sequences */
+      
+    case SWIG_TOKEN_RSTRING:
+      yylval.type = NewString(Scanner_text(scan));
+      return TYPE_RAW;
+      
+    case SWIG_TOKEN_STRING:
+      yylval.id = Swig_copy_string(Char(Scanner_text(scan)));
+      return STRING;
+      
+    case SWIG_TOKEN_CHAR:
+      yylval.str = NewString(Scanner_text(scan));
+      if (Len(yylval.str) == 0) {
+	Swig_error(cparse_file, cparse_line, "Empty character constant\n");
+	Printf(stdout,"%d\n", Len(Scanner_text(scan)));
+      }
+      return CHARCONST;
+      
+      /* Numbers */
+      
+    case SWIG_TOKEN_INT:
+      return NUM_INT;
+      
+    case SWIG_TOKEN_UINT:
+      return NUM_UNSIGNED;
+      
+    case SWIG_TOKEN_LONG:
+      return NUM_LONG;
+      
+    case SWIG_TOKEN_ULONG:
+      return NUM_ULONG;
+      
+    case SWIG_TOKEN_LONGLONG:
+      return NUM_LONGLONG;
+      
+    case SWIG_TOKEN_ULONGLONG:
+      return NUM_ULONGLONG;
+      
+    case SWIG_TOKEN_DOUBLE:
+    case SWIG_TOKEN_FLOAT:
+      return NUM_FLOAT;
+      
+    case SWIG_TOKEN_POUND:
+      Scanner_skip_line(scan);
+      yylval.id = Swig_copy_string(Char(Scanner_text(scan)));
+      return POUND;
+      break;
+      
+    case SWIG_TOKEN_CODEBLOCK:
+      yylval.str = NewString(Scanner_text(scan));
+      return HBLOCK;
+      
+    case SWIG_TOKEN_COMMENT:
+      {
+	String *cmt = Scanner_text(scan);
+	char *loc = Char(cmt);
+	if ((strncmp(loc,"/*@SWIG",7) == 0) && (loc[Len(cmt)-3] == '@')) {
+	  scanner_locator(cmt);
+	}
+      }
+      break;
+    case SWIG_TOKEN_ENDLINE:
+      break;
+    case SWIG_TOKEN_BACKSLASH:
+      break;
+    default:
+      Swig_error(cparse_file, cparse_line, "Illegal token '%s'.\n", Scanner_text(scan));
+      return (ILLEGAL);
+    }
+  }
+}
+
+static int check_typedef = 0;
+
+void scanner_set_location(String_or_char *file, int line) {
+  Scanner_set_location(scan,file,line-1);
+}
+
+void scanner_check_typedef() {
+  check_typedef = 1;
+}
+
+void scanner_ignore_typedef() {
+  check_typedef = 0;
+}
+
+void scanner_last_id(int x) {
+  last_id = x;
+}
+
+void scanner_clear_rename() {
+  rename_active = 0;
+}
+
+/* Used to push a ficticious token into the scanner */
+static int next_token = 0;
+void scanner_next_token(int tok) {
+  next_token = tok;
+}
+
+/* ----------------------------------------------------------------------------
+ * int yylex()
+ *
+ * Gets the lexene and returns tokens.
+ * ------------------------------------------------------------------------- */
+
+int yylex(void) {
+
+  int l;
+  char *yytext;
+
+  if (!scan_init) {
+    scanner_init();
+  }
+
+  if (next_token) {
+    l = next_token;
+    next_token = 0;
+    return l;
+  }
+
+  l = yylook();
+
+  /*   Printf(stdout, "%s:%d:::%d: '%s'\n", cparse_file, cparse_line, l, Scanner_text(scan)); */
+
+  if (l == NONID) {
+    last_id = 1;
+  } else {
+    last_id = 0;
+  }
+
+  /* We got some sort of non-white space object.  We set the start_line
+     variable unless it has already been set */
+
+  if (!cparse_start_line) {
+    cparse_start_line = cparse_line;
+  }
+
+  /* Copy the lexene */
+
+  switch (l) {
+
+  case NUM_INT:
+  case NUM_FLOAT:
+  case NUM_ULONG:
+  case NUM_LONG:
+  case NUM_UNSIGNED:
+  case NUM_LONGLONG:
+  case NUM_ULONGLONG:
+    if (l == NUM_INT)
+      yylval.dtype.type = T_INT;
+    if (l == NUM_FLOAT)
+      yylval.dtype.type = T_DOUBLE;
+    if (l == NUM_ULONG)
+      yylval.dtype.type = T_ULONG;
+    if (l == NUM_LONG)
+      yylval.dtype.type = T_LONG;
+    if (l == NUM_UNSIGNED)
+      yylval.dtype.type = T_UINT;
+    if (l == NUM_LONGLONG)
+      yylval.dtype.type = T_LONGLONG;
+    if (l == NUM_ULONGLONG)
+      yylval.dtype.type = T_ULONGLONG;
+    yylval.dtype.val = NewString(Scanner_text(scan));
+    yylval.dtype.bitfield = 0;
+    yylval.dtype.throws = 0;
+    return (l);
+
+  case ID:
+    yytext = Char(Scanner_text(scan));
+    if (yytext[0] != '%') {
+      /* Look for keywords now */
+
+      if (strcmp(yytext, "int") == 0) {
+	yylval.type = NewSwigType(T_INT);
+	return (TYPE_INT);
+      }
+      if (strcmp(yytext, "double") == 0) {
+	yylval.type = NewSwigType(T_DOUBLE);
+	return (TYPE_DOUBLE);
+      }
+      if (strcmp(yytext, "void") == 0) {
+	yylval.type = NewSwigType(T_VOID);
+	return (TYPE_VOID);
+      }
+      if (strcmp(yytext, "char") == 0) {
+	yylval.type = NewSwigType(T_CHAR);
+	return (TYPE_CHAR);
+      }
+      if (strcmp(yytext, "wchar_t") == 0) {
+	yylval.type = NewSwigType(T_WCHAR);
+	return (TYPE_WCHAR);
+      }
+      if (strcmp(yytext, "short") == 0) {
+	yylval.type = NewSwigType(T_SHORT);
+	return (TYPE_SHORT);
+      }
+      if (strcmp(yytext, "long") == 0) {
+	yylval.type = NewSwigType(T_LONG);
+	return (TYPE_LONG);
+      }
+      if (strcmp(yytext, "float") == 0) {
+	yylval.type = NewSwigType(T_FLOAT);
+	return (TYPE_FLOAT);
+      }
+      if (strcmp(yytext, "signed") == 0) {
+	yylval.type = NewSwigType(T_INT);
+	return (TYPE_SIGNED);
+      }
+      if (strcmp(yytext, "unsigned") == 0) {
+	yylval.type = NewSwigType(T_UINT);
+	return (TYPE_UNSIGNED);
+      }
+      if (strcmp(yytext, "bool") == 0) {
+	yylval.type = NewSwigType(T_BOOL);
+	return (TYPE_BOOL);
+      }
+
+      /* Non ISO (Windows) C extensions */
+      if (strcmp(yytext, "__int8") == 0) {
+	yylval.type = NewString(yytext);
+	return (TYPE_NON_ISO_INT8);
+      }
+      if (strcmp(yytext, "__int16") == 0) {
+	yylval.type = NewString(yytext);
+	return (TYPE_NON_ISO_INT16);
+      }
+      if (strcmp(yytext, "__int32") == 0) {
+	yylval.type = NewString(yytext);
+	return (TYPE_NON_ISO_INT32);
+      }
+      if (strcmp(yytext, "__int64") == 0) {
+	yylval.type = NewString(yytext);
+	return (TYPE_NON_ISO_INT64);
+      }
+
+      /* C++ keywords */
+      if (cparse_cplusplus) {
+	if (strcmp(yytext, "and") == 0)
+	  return (LAND);
+	if (strcmp(yytext, "or") == 0)
+	  return (LOR);
+	if (strcmp(yytext, "not") == 0)
+	  return (LNOT);
+	if (strcmp(yytext, "class") == 0)
+	  return (CLASS);
+	if (strcmp(yytext, "private") == 0)
+	  return (PRIVATE);
+	if (strcmp(yytext, "public") == 0)
+	  return (PUBLIC);
+	if (strcmp(yytext, "protected") == 0)
+	  return (PROTECTED);
+	if (strcmp(yytext, "friend") == 0)
+	  return (FRIEND);
+	if (strcmp(yytext, "virtual") == 0)
+	  return (VIRTUAL);
+	if (strcmp(yytext, "operator") == 0) {
+	  int nexttok;
+	  String *s = NewString("operator ");
+
+	  /* If we have an operator, we have to collect the operator symbol and attach it to
+             the operator identifier.   To do this, we need to scan ahead by several tokens.
+             Cases include:
+
+             (1) If the next token is an operator as determined by Scanner_isoperator(),
+                 it means that the operator applies to one of the standard C++ mathematical,
+                 assignment, or logical operator symbols (e.g., '+','<=','==','&', etc.)
+                 In this case, we merely append the symbol text to the operator string above.
+
+             (2) If the next token is (, we look for ).  This is operator ().
+             (3) If the next token is [, we look for ].  This is operator [].
+	     (4) If the next token is an identifier.  The operator is possibly a conversion operator.
+                      (a) Must check for special case new[] and delete[]
+
+             Error handling is somewhat tricky here.  We'll try to back out gracefully if we can.
+ 
+	  */
+
+	  nexttok = Scanner_token(scan);
+	  if (Scanner_isoperator(nexttok)) {
+	    /* One of the standard C/C++ symbolic operators */
+	    Append(s,Scanner_text(scan));
+	    yylval.str = s;
+	    return OPERATOR;
+	  } else if (nexttok == SWIG_TOKEN_LPAREN) {
+	    /* Function call operator.  The next token MUST be a RPAREN */
+	    nexttok = Scanner_token(scan);
+	    if (nexttok != SWIG_TOKEN_RPAREN) {
+	      Swig_error(Scanner_file(scan),Scanner_line(scan),"Syntax error. Bad operator name.\n");
+	    } else {
+	      Append(s,"()");
+	      yylval.str = s;
+	      return OPERATOR;
+	    }
+	  } else if (nexttok == SWIG_TOKEN_LBRACKET) {
+	    /* Array access operator.  The next token MUST be a RBRACKET */
+	    nexttok = Scanner_token(scan);
+	    if (nexttok != SWIG_TOKEN_RBRACKET) {
+	      Swig_error(Scanner_file(scan),Scanner_line(scan),"Syntax error. Bad operator name.\n");	      
+	    } else {
+	      Append(s,"[]");
+	      yylval.str = s;
+	      return OPERATOR;
+	    }
+	  } else if (nexttok == SWIG_TOKEN_ID) {
+	    /* We have an identifier.  This could be any number of things. It could be a named version of
+               an operator (e.g., 'and_eq') or it could be a conversion operator.   To deal with this, we're
+               going to read tokens until we encounter a ( or ;.  Some care is needed for formatting. */
+	    int needspace = 1;
+	    int termtoken = 0;
+	    const char *termvalue = 0;
+
+	    Append(s,Scanner_text(scan));
+	    while (1) {
+
+	      nexttok = Scanner_token(scan);
+	      if (nexttok <= 0) {
+		Swig_error(Scanner_file(scan),Scanner_line(scan),"Syntax error. Bad operator name.\n");	      
+	      }
+	      if (nexttok == SWIG_TOKEN_LPAREN) {
+		termtoken = SWIG_TOKEN_LPAREN;
+		termvalue = "(";
+		break;
+	      } else if (nexttok == SWIG_TOKEN_SEMI) {
+		termtoken = SWIG_TOKEN_SEMI;
+		termvalue = ";";
+		break;
+	      } else if (nexttok == SWIG_TOKEN_ID) {
+		if (needspace) {
+		  Append(s," ");
+		}
+		Append(s,Scanner_text(scan));
+	      } else {
+		Append(s,Scanner_text(scan));
+		needspace = 0;
+	      }
+	    }
+	    yylval.str = s;
+	    if (!rename_active) {
+	      String *cs;
+	      char *t = Char(s) + 9;
+	      if (!((strcmp(t, "new") == 0)
+		    || (strcmp(t, "delete") == 0)
+		    || (strcmp(t, "new[]") == 0)
+		    || (strcmp(t, "delete[]") == 0)
+		    || (strcmp(t, "and") == 0)
+		    || (strcmp(t, "and_eq") == 0)
+		    || (strcmp(t, "bitand") == 0)
+		    || (strcmp(t, "bitor") == 0)
+		    || (strcmp(t, "compl") == 0)
+		    || (strcmp(t, "not") == 0)
+		    || (strcmp(t, "not_eq") == 0)
+		    || (strcmp(t, "or") == 0)
+		    || (strcmp(t, "or_eq") == 0)
+		    || (strcmp(t, "xor") == 0)
+		    || (strcmp(t, "xor_eq") == 0)
+		    )) {
+		/*              retract(strlen(t)); */
+
+		/* The operator is a conversion operator.   In order to deal with this, we need to feed the
+                   type information back into the parser.  For now this is a hack.  Needs to be cleaned up later. */
+		cs = NewString(t);
+		if (termtoken) Append(cs,termvalue);
+		Seek(cs,0,SEEK_SET);
+		Setline(cs,cparse_line);
+		Setfile(cs,cparse_file);
+		Scanner_push(scan,cs);
+		Delete(cs);
+		return COPERATOR;
+	      }
+	    }
+	    if (termtoken)
+              Scanner_pushtoken(scan, termtoken, termvalue);
+	    return (OPERATOR);
+	  }
+	}
+	if (strcmp(yytext, "throw") == 0)
+	  return (THROW);
+	if (strcmp(yytext, "try") == 0)
+	  return (yylex());
+	if (strcmp(yytext, "catch") == 0)
+	  return (CATCH);
+	if (strcmp(yytext, "inline") == 0)
+	  return (yylex());
+	if (strcmp(yytext, "mutable") == 0)
+	  return (yylex());
+	if (strcmp(yytext, "explicit") == 0)
+	  return (EXPLICIT);
+	if (strcmp(yytext, "export") == 0)
+	  return (yylex());
+	if (strcmp(yytext, "typename") == 0)
+	  return (TYPENAME);
+	if (strcmp(yytext, "template") == 0) {
+	  yylval.ivalue = cparse_line;
+	  return (TEMPLATE);
+	}
+	if (strcmp(yytext, "delete") == 0) {
+	  return (DELETE_KW);
+	}
+	if (strcmp(yytext, "using") == 0) {
+	  return (USING);
+	}
+	if (strcmp(yytext, "namespace") == 0) {
+	  return (NAMESPACE);
+	}
+      } else {
+	if (strcmp(yytext, "class") == 0) {
+	  Swig_warning(WARN_PARSE_CLASS_KEYWORD, cparse_file, cparse_line, "class keyword used, but not in C++ mode.\n");
+	}
+	if (strcmp(yytext, "complex") == 0) {
+	  yylval.type = NewSwigType(T_COMPLEX);
+	  return (TYPE_COMPLEX);
+	}
+	if (strcmp(yytext, "restrict") == 0)
+	  return (yylex());
+      }
+
+      /* Misc keywords */
+
+      if (strcmp(yytext, "extern") == 0)
+	return (EXTERN);
+      if (strcmp(yytext, "const") == 0)
+	return (CONST_QUAL);
+      if (strcmp(yytext, "static") == 0)
+	return (STATIC);
+      if (strcmp(yytext, "struct") == 0)
+	return (STRUCT);
+      if (strcmp(yytext, "union") == 0)
+	return (UNION);
+      if (strcmp(yytext, "enum") == 0)
+	return (ENUM);
+      if (strcmp(yytext, "sizeof") == 0)
+	return (SIZEOF);
+
+      if (strcmp(yytext, "typedef") == 0) {
+	yylval.ivalue = 0;
+	return (TYPEDEF);
+      }
+
+      /* Ignored keywords */
+
+      if (strcmp(yytext, "volatile") == 0)
+	return (VOLATILE);
+      if (strcmp(yytext, "register") == 0)
+	return (REGISTER);
+      if (strcmp(yytext, "inline") == 0)
+	return (yylex());
+
+      /* SWIG directives */
+    } else {
+      if (strcmp(yytext, "%module") == 0)
+	return (MODULE);
+      if (strcmp(yytext, "%insert") == 0)
+	return (INSERT);
+      if (strcmp(yytext, "%name") == 0)
+	return (NAME);
+      if (strcmp(yytext, "%rename") == 0) {
+	rename_active = 1;
+	return (RENAME);
+      }
+      if (strcmp(yytext, "%namewarn") == 0) {
+	rename_active = 1;
+	return (NAMEWARN);
+      }
+      if (strcmp(yytext, "%includefile") == 0)
+	return (INCLUDE);
+      if (strcmp(yytext, "%val") == 0) {
+	Swig_warning(WARN_DEPRECATED_VAL, cparse_file, cparse_line, "%%val directive deprecated (ignored).\n");
+	return (yylex());
+      }
+      if (strcmp(yytext, "%out") == 0) {
+	Swig_warning(WARN_DEPRECATED_OUT, cparse_file, cparse_line, "%%out directive deprecated (ignored).\n");
+	return (yylex());
+      }
+      if (strcmp(yytext, "%constant") == 0)
+	return (CONSTANT);
+      if (strcmp(yytext, "%typedef") == 0) {
+	yylval.ivalue = 1;
+	return (TYPEDEF);
+      }
+      if (strcmp(yytext, "%native") == 0)
+	return (NATIVE);
+      if (strcmp(yytext, "%pragma") == 0)
+	return (PRAGMA);
+      if (strcmp(yytext, "%extend") == 0)
+	return (EXTEND);
+      if (strcmp(yytext, "%fragment") == 0)
+	return (FRAGMENT);
+      if (strcmp(yytext, "%inline") == 0)
+	return (INLINE);
+      if (strcmp(yytext, "%typemap") == 0)
+	return (TYPEMAP);
+      if (strcmp(yytext, "%feature") == 0)
+	return (FEATURE);
+      if (strcmp(yytext, "%except") == 0)
+	return (EXCEPT);
+      if (strcmp(yytext, "%importfile") == 0)
+	return (IMPORT);
+      if (strcmp(yytext, "%echo") == 0)
+	return (ECHO);
+      if (strcmp(yytext, "%apply") == 0)
+	return (APPLY);
+      if (strcmp(yytext, "%clear") == 0)
+	return (CLEAR);
+      if (strcmp(yytext, "%types") == 0)
+	return (TYPES);
+      if (strcmp(yytext, "%parms") == 0)
+	return (PARMS);
+      if (strcmp(yytext, "%varargs") == 0)
+	return (VARARGS);
+      if (strcmp(yytext, "%template") == 0) {
+	return (SWIGTEMPLATE);
+      }
+      if (strcmp(yytext, "%warn") == 0)
+	return (WARN);
+    }
+    /* Have an unknown identifier, as a last step, we'll do a typedef lookup on it. */
+
+    /* Need to fix this */
+    if (check_typedef) {
+      if (SwigType_istypedef(yytext)) {
+	yylval.type = NewString(yytext);
+	return (TYPE_TYPEDEF);
+      }
+    }
+    yylval.id = Swig_copy_string(yytext);
+    last_id = 1;
+    return (ID);
+  case POUND:
+    return yylex();
+  default:
+    return (l);
+  }
+}
diff --git a/trunk/Source/CParse/parser.y b/trunk/Source/CParse/parser.y
new file mode 100644
index 0000000..58e0c0c
--- /dev/null
+++ b/trunk/Source/CParse/parser.y
@@ -0,0 +1,5975 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * parser.y
+ *
+ * YACC parser for SWIG.   The grammar is a somewhat broken subset of C/C++.
+ * This file is a bit of a mess and probably needs to be rewritten at
+ * some point.  Beware.
+ * ----------------------------------------------------------------------------- */
+
+%{
+
+#define yylex yylex
+
+char cvsroot_parser_y[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+#include "preprocessor.h"
+#include <ctype.h>
+
+/* We do this for portability */
+#undef alloca
+#define alloca malloc
+
+/* -----------------------------------------------------------------------------
+ *                               Externals
+ * ----------------------------------------------------------------------------- */
+
+int  yyparse();
+
+/* NEW Variables */
+
+static Node    *top = 0;      /* Top of the generated parse tree */
+static int      unnamed = 0;  /* Unnamed datatype counter */
+static Hash    *extendhash = 0;     /* Hash table of added methods */
+static Hash    *classes = 0;        /* Hash table of classes */
+static Symtab  *prev_symtab = 0;
+static Node    *current_class = 0;
+String  *ModuleName = 0;
+static Node    *module_node = 0;
+static String  *Classprefix = 0;  
+static String  *Namespaceprefix = 0;
+static int      inclass = 0;
+static char    *last_cpptype = 0;
+static int      inherit_list = 0;
+static Parm    *template_parameters = 0;
+static int      extendmode   = 0;
+static int      compact_default_args = 0;
+static int      template_reduce = 0;
+static int      cparse_externc = 0;
+
+static int      max_class_levels = 0;
+static int      class_level = 0;
+static Node   **class_decl = NULL;
+
+/* -----------------------------------------------------------------------------
+ *                            Assist Functions
+ * ----------------------------------------------------------------------------- */
+
+
+ 
+/* Called by the parser (yyparse) when an error is found.*/
+static void yyerror (const char *e) {
+  (void)e;
+}
+
+static Node *new_node(const String_or_char *tag) {
+  Node *n = NewHash();
+  set_nodeType(n,tag);
+  Setfile(n,cparse_file);
+  Setline(n,cparse_line);
+  return n;
+}
+
+/* Copies a node.  Does not copy tree links or symbol table data (except for
+   sym:name) */
+
+static Node *copy_node(Node *n) {
+  Node *nn;
+  Iterator k;
+  nn = NewHash();
+  Setfile(nn,Getfile(n));
+  Setline(nn,Getline(n));
+  for (k = First(n); k.key; k = Next(k)) {
+    String *ci;
+    String *key = k.key;
+    char *ckey = Char(key);
+    if ((strcmp(ckey,"nextSibling") == 0) ||
+	(strcmp(ckey,"previousSibling") == 0) ||
+	(strcmp(ckey,"parentNode") == 0) ||
+	(strcmp(ckey,"lastChild") == 0)) {
+      continue;
+    }
+    if (Strncmp(key,"csym:",5) == 0) continue;
+    /* We do copy sym:name.  For templates */
+    if ((strcmp(ckey,"sym:name") == 0) || 
+	(strcmp(ckey,"sym:weak") == 0) ||
+	(strcmp(ckey,"sym:typename") == 0)) {
+      String *ci = Copy(k.item);
+      Setattr(nn,key, ci);
+      Delete(ci);
+      continue;
+    }
+    if (strcmp(ckey,"sym:symtab") == 0) {
+      Setattr(nn,"sym:needs_symtab", "1");
+    }
+    /* We don't copy any other symbol table attributes */
+    if (strncmp(ckey,"sym:",4) == 0) {
+      continue;
+    }
+    /* If children.  We copy them recursively using this function */
+    if (strcmp(ckey,"firstChild") == 0) {
+      /* Copy children */
+      Node *cn = k.item;
+      while (cn) {
+	Node *copy = copy_node(cn);
+	appendChild(nn,copy);
+	Delete(copy);
+	cn = nextSibling(cn);
+      }
+      continue;
+    }
+    /* We don't copy the symbol table.  But we drop an attribute 
+       requires_symtab so that functions know it needs to be built */
+
+    if (strcmp(ckey,"symtab") == 0) {
+      /* Node defined a symbol table. */
+      Setattr(nn,"requires_symtab","1");
+      continue;
+    }
+    /* Can't copy nodes */
+    if (strcmp(ckey,"node") == 0) {
+      continue;
+    }
+    if ((strcmp(ckey,"parms") == 0) || (strcmp(ckey,"pattern") == 0) || (strcmp(ckey,"throws") == 0)
+	|| (strcmp(ckey,"kwargs") == 0)) {
+      ParmList *pl = CopyParmList(k.item);
+      Setattr(nn,key,pl);
+      Delete(pl);
+      continue;
+    }
+    /* Looks okay.  Just copy the data using Copy */
+    ci = Copy(k.item);
+    Setattr(nn, key, ci);
+    Delete(ci);
+  }
+  return nn;
+}
+
+/* -----------------------------------------------------------------------------
+ *                              Variables
+ * ----------------------------------------------------------------------------- */
+
+static char  *typemap_lang = 0;    /* Current language setting */
+
+static int cplus_mode  = 0;
+static String  *class_rename = 0;
+
+/* C++ modes */
+
+#define  CPLUS_PUBLIC    1
+#define  CPLUS_PRIVATE   2
+#define  CPLUS_PROTECTED 3
+
+/* include types */
+static int   import_mode = 0;
+
+void SWIG_typemap_lang(const char *tm_lang) {
+  typemap_lang = Swig_copy_string(tm_lang);
+}
+
+void SWIG_cparse_set_compact_default_args(int defargs) {
+  compact_default_args = defargs;
+}
+
+int SWIG_cparse_template_reduce(int treduce) {
+  template_reduce = treduce;
+  return treduce;  
+}
+
+/* -----------------------------------------------------------------------------
+ *                           Assist functions
+ * ----------------------------------------------------------------------------- */
+
+static int promote_type(int t) {
+  if (t <= T_UCHAR || t == T_CHAR) return T_INT;
+  return t;
+}
+
+/* Perform type-promotion for binary operators */
+static int promote(int t1, int t2) {
+  t1 = promote_type(t1);
+  t2 = promote_type(t2);
+  return t1 > t2 ? t1 : t2;
+}
+
+static String *yyrename = 0;
+
+/* Forward renaming operator */
+
+static String *resolve_node_scope(String *cname);
+
+
+Hash *Swig_cparse_features() {
+  static Hash   *features_hash = 0;
+  if (!features_hash) features_hash = NewHash();
+  return features_hash;
+}
+
+static String *feature_identifier_fix(String *s) {
+  if (SwigType_istemplate(s)) {
+    String *tp, *ts, *ta, *tq;
+    tp = SwigType_templateprefix(s);
+    ts = SwigType_templatesuffix(s);
+    ta = SwigType_templateargs(s);
+    tq = Swig_symbol_type_qualify(ta,0);
+    Append(tp,tq);
+    Append(tp,ts);
+    Delete(ts);
+    Delete(ta);
+    Delete(tq);
+    return tp;
+  } else {
+    return NewString(s);
+  }
+}
+
+/* Generate the symbol table name for an object */
+/* This is a bit of a mess. Need to clean up */
+static String *add_oldname = 0;
+
+
+
+static String *make_name(Node *n, String *name,SwigType *decl) {
+  int destructor = name && (*(Char(name)) == '~');
+
+  if (yyrename) {
+    String *s = NewString(yyrename);
+    Delete(yyrename);
+    yyrename = 0;
+    if (destructor  && (*(Char(s)) != '~')) {
+      Insert(s,0,"~");
+    }
+    return s;
+  }
+
+  if (!name) return 0;
+  return Swig_name_make(n,Namespaceprefix,name,decl,add_oldname);
+}
+
+/* Generate an unnamed identifier */
+static String *make_unnamed() {
+  unnamed++;
+  return NewStringf("$unnamed%d$",unnamed);
+}
+
+/* Return if the node is a friend declaration */
+static int is_friend(Node *n) {
+  return Cmp(Getattr(n,"storage"),"friend") == 0;
+}
+
+static int is_operator(String *name) {
+  return Strncmp(name,"operator ", 9) == 0;
+}
+
+
+/* Add declaration list to symbol table */
+static int  add_only_one = 0;
+
+static void add_symbols(Node *n) {
+  String *decl;
+  String *wrn = 0;
+  if (inclass && n) {
+    cparse_normalize_void(n);
+  }
+  while (n) {
+    String *symname = 0;
+    /* for friends, we need to pop the scope once */
+    String *old_prefix = 0;
+    Symtab *old_scope = 0;
+    int isfriend = inclass && is_friend(n);
+    int iscdecl = Cmp(nodeType(n),"cdecl") == 0;
+    int only_csymbol = 0;
+    if (extendmode) {
+      Setattr(n,"isextension","1");
+    }
+    
+    if (inclass) {
+      String *name = Getattr(n, "name");
+      if (isfriend) {
+	/* for friends, we need to add the scopename if needed */
+	String *prefix = name ? Swig_scopename_prefix(name) : 0;
+	old_prefix = Namespaceprefix;
+	old_scope = Swig_symbol_popscope();
+	Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+	if (!prefix) {
+	  if (name && !is_operator(name) && Namespaceprefix) {
+	    String *nname = NewStringf("%s::%s", Namespaceprefix, name);
+	    Setattr(n,"name",nname);
+	    Delete(nname);
+	  }
+	} else {
+	  Symtab *st = Swig_symbol_getscope(prefix);
+	  String *ns = st ? Getattr(st,"name") : prefix;
+	  String *base  = Swig_scopename_last(name);
+	  String *nname = NewStringf("%s::%s", ns, base);
+	  Setattr(n,"name",nname);
+	  Delete(nname);
+	  Delete(base);
+	  Delete(prefix);
+	}
+	Namespaceprefix = 0;
+      } else {
+	/* for member functions, we need to remove the redundant
+	   class scope if provided, as in
+	   
+	   struct Foo {
+	   int Foo::method(int a);
+	   };
+	   
+	*/
+	String *prefix = name ? Swig_scopename_prefix(name) : 0;
+	if (prefix) {
+	  if (Classprefix && (Equal(prefix,Classprefix))) {
+	    String *base = Swig_scopename_last(name);
+	    Setattr(n,"name",base);
+	    Delete(base);
+	  }
+	  Delete(prefix);
+	}
+
+        /*
+	if (!Getattr(n,"parentNode") && class_level) set_parentNode(n,class_decl[class_level - 1]);
+        */
+	Setattr(n,"ismember","1");
+      }
+    }
+    if (!isfriend && inclass) {
+      if ((cplus_mode != CPLUS_PUBLIC)) {
+	only_csymbol = 1;
+	if (cplus_mode == CPLUS_PROTECTED) {
+	  Setattr(n,"access", "protected");
+	  only_csymbol = !Swig_need_protected(n);
+	} else {
+	  Setattr(n,"access", "private");
+	  /* private are needed only when they are pure virtuals - why? */
+	  if ((Cmp(Getattr(n,"storage"),"virtual") == 0) && (Cmp(Getattr(n,"value"),"0") == 0)) {
+	    only_csymbol = 0;
+	  }
+	}
+      } else {
+	  Setattr(n,"access", "public");
+      }
+    }
+    if (Getattr(n,"sym:name")) {
+      n = nextSibling(n);
+      continue;
+    }
+    decl = Getattr(n,"decl");
+    if (!SwigType_isfunction(decl)) {
+      String *name = Getattr(n,"name");
+      String *makename = Getattr(n,"parser:makename");
+      if (iscdecl) {	
+	String *storage = Getattr(n, "storage");
+	if (Cmp(storage,"typedef") == 0) {
+	  Setattr(n,"kind","typedef");
+	} else {
+	  SwigType *type = Getattr(n,"type");
+	  String *value = Getattr(n,"value");
+	  Setattr(n,"kind","variable");
+	  if (value && Len(value)) {
+	    Setattr(n,"hasvalue","1");
+	  }
+	  if (type) {
+	    SwigType *ty;
+	    SwigType *tmp = 0;
+	    if (decl) {
+	      ty = tmp = Copy(type);
+	      SwigType_push(ty,decl);
+	    } else {
+	      ty = type;
+	    }
+	    if (!SwigType_ismutable(ty)) {
+	      SetFlag(n,"hasconsttype");
+	      SetFlag(n,"feature:immutable");
+	    }
+	    if (tmp) Delete(tmp);
+	  }
+	  if (!type) {
+	    Printf(stderr,"notype name %s\n", name);
+	  }
+	}
+      }
+      Swig_features_get(Swig_cparse_features(), Namespaceprefix, name, 0, n);
+      if (makename) {
+	symname = make_name(n, makename,0);
+        Delattr(n,"parser:makename"); /* temporary information, don't leave it hanging around */
+      } else {
+        makename = name;
+	symname = make_name(n, makename,0);
+      }
+      
+      if (!symname) {
+	symname = Copy(Getattr(n,"unnamed"));
+      }
+      if (symname) {
+	wrn = Swig_name_warning(n, Namespaceprefix, symname,0);
+      }
+    } else {
+      String *name = Getattr(n,"name");
+      SwigType *fdecl = Copy(decl);
+      SwigType *fun = SwigType_pop_function(fdecl);
+      if (iscdecl) {	
+	Setattr(n,"kind","function");
+      }
+      
+      Swig_features_get(Swig_cparse_features(),Namespaceprefix,name,fun,n);
+
+      symname = make_name(n, name,fun);
+      wrn = Swig_name_warning(n, Namespaceprefix,symname,fun);
+      
+      Delete(fdecl);
+      Delete(fun);
+      
+    }
+    if (!symname) {
+      n = nextSibling(n);
+      continue;
+    }
+    if (only_csymbol || GetFlag(n,"feature:ignore")) {
+      /* Only add to C symbol table and continue */
+      Swig_symbol_add(0, n);
+    } else if (strncmp(Char(symname),"$ignore",7) == 0) {
+      char *c = Char(symname)+7;
+      SetFlag(n,"feature:ignore");
+      if (strlen(c)) {
+	SWIG_WARN_NODE_BEGIN(n);
+	Swig_warning(0,Getfile(n), Getline(n), "%s\n",c+1);
+	SWIG_WARN_NODE_END(n);
+      }
+      Swig_symbol_add(0, n);
+    } else {
+      Node *c;
+      if ((wrn) && (Len(wrn))) {
+	String *metaname = symname;
+	if (!Getmeta(metaname,"already_warned")) {
+	  SWIG_WARN_NODE_BEGIN(n);
+	  Swig_warning(0,Getfile(n),Getline(n), "%s\n", wrn);
+	  SWIG_WARN_NODE_END(n);
+	  Setmeta(metaname,"already_warned","1");
+	}
+      }
+      c = Swig_symbol_add(symname,n);
+
+      if (c != n) {
+        /* symbol conflict attempting to add in the new symbol */
+        if (Getattr(n,"sym:weak")) {
+          Setattr(n,"sym:name",symname);
+        } else {
+          String *e = NewStringEmpty();
+          String *en = NewStringEmpty();
+          String *ec = NewStringEmpty();
+          int redefined = Swig_need_redefined_warn(n,c,inclass);
+          if (redefined) {
+            Printf(en,"Identifier '%s' redefined (ignored)",symname);
+            Printf(ec,"previous definition of '%s'",symname);
+          } else {
+            Printf(en,"Redundant redeclaration of '%s'",symname);
+            Printf(ec,"previous declaration of '%s'",symname);
+          }
+          if (Cmp(symname,Getattr(n,"name"))) {
+            Printf(en," (Renamed from '%s')", SwigType_namestr(Getattr(n,"name")));
+          }
+          Printf(en,",");
+          if (Cmp(symname,Getattr(c,"name"))) {
+            Printf(ec," (Renamed from '%s')", SwigType_namestr(Getattr(c,"name")));
+          }
+          Printf(ec,".");
+	  SWIG_WARN_NODE_BEGIN(n);
+          if (redefined) {
+            Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en);
+            Swig_warning(WARN_PARSE_REDEFINED,Getfile(c),Getline(c),"%s\n",ec);
+          } else if (!is_friend(n) && !is_friend(c)) {
+            Swig_warning(WARN_PARSE_REDUNDANT,Getfile(n),Getline(n),"%s\n",en);
+            Swig_warning(WARN_PARSE_REDUNDANT,Getfile(c),Getline(c),"%s\n",ec);
+          }
+	  SWIG_WARN_NODE_END(n);
+          Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(n),Getline(n),en,
+                 Getfile(c),Getline(c),ec);
+          Setattr(n,"error",e);
+	  Delete(e);
+          Delete(en);
+          Delete(ec);
+        }
+      }
+    }
+    /* restore the class scope if needed */
+    if (isfriend) {
+      Swig_symbol_setscope(old_scope);
+      if (old_prefix) {
+	Delete(Namespaceprefix);
+	Namespaceprefix = old_prefix;
+      }
+    }
+    Delete(symname);
+
+    if (add_only_one) return;
+    n = nextSibling(n);
+  }
+}
+
+
+/* add symbols a parse tree node copy */
+
+static void add_symbols_copy(Node *n) {
+  String *name;
+  int    emode = 0;
+  while (n) {
+    char *cnodeType = Char(nodeType(n));
+
+    if (strcmp(cnodeType,"access") == 0) {
+      String *kind = Getattr(n,"kind");
+      if (Strcmp(kind,"public") == 0) {
+	cplus_mode = CPLUS_PUBLIC;
+      } else if (Strcmp(kind,"private") == 0) {
+	cplus_mode = CPLUS_PRIVATE;
+      } else if (Strcmp(kind,"protected") == 0) {
+	cplus_mode = CPLUS_PROTECTED;
+      }
+      n = nextSibling(n);
+      continue;
+    }
+
+    add_oldname = Getattr(n,"sym:name");
+    if ((add_oldname) || (Getattr(n,"sym:needs_symtab"))) {
+      if (add_oldname) {
+	DohIncref(add_oldname);
+	/*  Disable this, it prevents %rename to work with templates */
+	/* If already renamed, we used that name  */
+	/*
+	if (Strcmp(add_oldname, Getattr(n,"name")) != 0) {
+	  Delete(yyrename);
+	  yyrename = Copy(add_oldname);
+	}
+	*/
+      }
+      Delattr(n,"sym:needs_symtab");
+      Delattr(n,"sym:name");
+
+      add_only_one = 1;
+      add_symbols(n);
+
+      if (Getattr(n,"partialargs")) {
+	Swig_symbol_cadd(Getattr(n,"partialargs"),n);
+      }
+      add_only_one = 0;
+      name = Getattr(n,"name");
+      if (Getattr(n,"requires_symtab")) {
+	Swig_symbol_newscope();
+	Swig_symbol_setscopename(name);
+	Delete(Namespaceprefix);
+	Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+      }
+      if (strcmp(cnodeType,"class") == 0) {
+	inclass = 1;
+	current_class = n;
+	if (Strcmp(Getattr(n,"kind"),"class") == 0) {
+	  cplus_mode = CPLUS_PRIVATE;
+	} else {
+	  cplus_mode = CPLUS_PUBLIC;
+	}
+      }
+      if (strcmp(cnodeType,"extend") == 0) {
+	emode = cplus_mode;
+	cplus_mode = CPLUS_PUBLIC;
+      }
+      add_symbols_copy(firstChild(n));
+      if (strcmp(cnodeType,"extend") == 0) {
+	cplus_mode = emode;
+      }
+      if (Getattr(n,"requires_symtab")) {
+	Setattr(n,"symtab", Swig_symbol_popscope());
+	Delattr(n,"requires_symtab");
+	Delete(Namespaceprefix);
+	Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+      }
+      if (add_oldname) {
+	Delete(add_oldname);
+	add_oldname = 0;
+      }
+      if (strcmp(cnodeType,"class") == 0) {
+	inclass = 0;
+	current_class = 0;
+      }
+    } else {
+      if (strcmp(cnodeType,"extend") == 0) {
+	emode = cplus_mode;
+	cplus_mode = CPLUS_PUBLIC;
+      }
+      add_symbols_copy(firstChild(n));
+      if (strcmp(cnodeType,"extend") == 0) {
+	cplus_mode = emode;
+      }
+    }
+    n = nextSibling(n);
+  }
+}
+
+/* Extension merge.  This function is used to handle the %extend directive
+   when it appears before a class definition.   To handle this, the %extend
+   actually needs to take precedence.  Therefore, we will selectively nuke symbols
+   from the current symbol table, replacing them with the added methods */
+
+static void merge_extensions(Node *cls, Node *am) {
+  Node *n;
+  Node *csym;
+
+  n = firstChild(am);
+  while (n) {
+    String *symname;
+    if (Strcmp(nodeType(n),"constructor") == 0) {
+      symname = Getattr(n,"sym:name");
+      if (symname) {
+	if (Strcmp(symname,Getattr(n,"name")) == 0) {
+	  /* If the name and the sym:name of a constructor are the same,
+             then it hasn't been renamed.  However---the name of the class
+             itself might have been renamed so we need to do a consistency
+             check here */
+	  if (Getattr(cls,"sym:name")) {
+	    Setattr(n,"sym:name", Getattr(cls,"sym:name"));
+	  }
+	}
+      } 
+    }
+
+    symname = Getattr(n,"sym:name");
+    DohIncref(symname);
+    if ((symname) && (!Getattr(n,"error"))) {
+      /* Remove node from its symbol table */
+      Swig_symbol_remove(n);
+      csym = Swig_symbol_add(symname,n);
+      if (csym != n) {
+	/* Conflict with previous definition.  Nuke previous definition */
+	String *e = NewStringEmpty();
+	String *en = NewStringEmpty();
+	String *ec = NewStringEmpty();
+	Printf(ec,"Identifier '%s' redefined by %%extend (ignored),",symname);
+	Printf(en,"%%extend definition of '%s'.",symname);
+	SWIG_WARN_NODE_BEGIN(n);
+	Swig_warning(WARN_PARSE_REDEFINED,Getfile(csym),Getline(csym),"%s\n",ec);
+	Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en);
+	SWIG_WARN_NODE_END(n);
+	Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(csym),Getline(csym),ec, 
+	       Getfile(n),Getline(n),en);
+	Setattr(csym,"error",e);
+	Delete(e);
+	Delete(en);
+	Delete(ec);
+	Swig_symbol_remove(csym);              /* Remove class definition */
+	Swig_symbol_add(symname,n);            /* Insert extend definition */
+      }
+    }
+    n = nextSibling(n);
+  }
+}
+
+static void append_previous_extension(Node *cls, Node *am) {
+  Node *n, *ne;
+  Node *pe = 0;
+  Node *ae = 0;
+
+  if (!am) return;
+  
+  n = firstChild(am);
+  while (n) {
+    ne = nextSibling(n);
+    set_nextSibling(n,0);
+    /* typemaps and fragments need to be prepended */
+    if (((Cmp(nodeType(n),"typemap") == 0) || (Cmp(nodeType(n),"fragment") == 0)))  {
+      if (!pe) pe = new_node("extend");
+      appendChild(pe, n);
+    } else {
+      if (!ae) ae = new_node("extend");
+      appendChild(ae, n);
+    }    
+    n = ne;
+  }
+  if (pe) prependChild(cls,pe);
+  if (ae) appendChild(cls,ae);
+}
+ 
+
+/* Check for unused %extend.  Special case, don't report unused
+   extensions for templates */
+ 
+static void check_extensions() {
+  Iterator ki;
+
+  if (!extendhash) return;
+  for (ki = First(extendhash); ki.key; ki = Next(ki)) {
+    if (!Strchr(ki.key,'<')) {
+      SWIG_WARN_NODE_BEGIN(ki.item);
+      Swig_warning(WARN_PARSE_EXTEND_UNDEF,Getfile(ki.item), Getline(ki.item), "%%extend defined for an undeclared class %s.\n", ki.key);
+      SWIG_WARN_NODE_END(ki.item);
+    }
+  }
+}
+
+/* Check a set of declarations to see if any are pure-abstract */
+
+static List *pure_abstract(Node *n) {
+  List *abs = 0;
+  while (n) {
+    if (Cmp(nodeType(n),"cdecl") == 0) {
+      String *decl = Getattr(n,"decl");
+      if (SwigType_isfunction(decl)) {
+	String *init = Getattr(n,"value");
+	if (Cmp(init,"0") == 0) {
+	  if (!abs) {
+	    abs = NewList();
+	  }
+	  Append(abs,n);
+	  Setattr(n,"abstract","1");
+	}
+      }
+    } else if (Cmp(nodeType(n),"destructor") == 0) {
+      if (Cmp(Getattr(n,"value"),"0") == 0) {
+	if (!abs) {
+	  abs = NewList();
+	}
+	Append(abs,n);
+	Setattr(n,"abstract","1");
+      }
+    }
+    n = nextSibling(n);
+  }
+  return abs;
+}
+
+/* Make a classname */
+
+static String *make_class_name(String *name) {
+  String *nname = 0;
+  if (Namespaceprefix) {
+    nname= NewStringf("%s::%s", Namespaceprefix, name);
+  } else {
+    nname = NewString(name);
+  }
+  if (SwigType_istemplate(nname)) {
+    String *prefix, *args, *qargs;
+    prefix = SwigType_templateprefix(nname);
+    args   = SwigType_templateargs(nname);
+    qargs  = Swig_symbol_type_qualify(args,0);
+    Append(prefix,qargs);
+    Delete(nname);
+    Delete(args);
+    Delete(qargs);
+    nname = prefix;
+  }
+  return nname;
+}
+
+static List *make_inherit_list(String *clsname, List *names) {
+  int i, ilen;
+  String *derived;
+  List *bases = NewList();
+
+  if (Namespaceprefix) derived = NewStringf("%s::%s", Namespaceprefix,clsname);
+  else derived = NewString(clsname);
+
+  ilen = Len(names);
+  for (i = 0; i < ilen; i++) {
+    Node *s;
+    String *base;
+    String *n = Getitem(names,i);
+    /* Try to figure out where this symbol is */
+    s = Swig_symbol_clookup(n,0);
+    if (s) {
+      while (s && (Strcmp(nodeType(s),"class") != 0)) {
+	/* Not a class.  Could be a typedef though. */
+	String *storage = Getattr(s,"storage");
+	if (storage && (Strcmp(storage,"typedef") == 0)) {
+	  String *nn = Getattr(s,"type");
+	  s = Swig_symbol_clookup(nn,Getattr(s,"sym:symtab"));
+	} else {
+	  break;
+	}
+      }
+      if (s && ((Strcmp(nodeType(s),"class") == 0) || (Strcmp(nodeType(s),"template") == 0))) {
+	String *q = Swig_symbol_qualified(s);
+	Append(bases,s);
+	if (q) {
+	  base = NewStringf("%s::%s", q, Getattr(s,"name"));
+	  Delete(q);
+	} else {
+	  base = NewString(Getattr(s,"name"));
+	}
+      } else {
+	base = NewString(n);
+      }
+    } else {
+      base = NewString(n);
+    }
+    if (base) {
+      Swig_name_inherit(base,derived);
+      Delete(base);
+    }
+  }
+  return bases;
+}
+
+/* If the class name is qualified.  We need to create or lookup namespace entries */
+
+static Symtab *get_global_scope() {
+  Symtab *symtab = Swig_symbol_current();
+  Node   *pn = parentNode(symtab);
+  while (pn) {
+    symtab = pn;
+    pn = parentNode(symtab);
+    if (!pn) break;
+  }
+  Swig_symbol_setscope(symtab);
+  return symtab;
+}
+ 
+/* Remove the block braces, { and }, if the 'noblock' attribute is set.
+ * Node *kw can be either a Hash or Parmlist. */
+static String *remove_block(Node *kw, const String *inputcode) {
+  String *modified_code = 0;
+  while (kw) {
+   String *name = Getattr(kw,"name");
+   if (name && (Cmp(name,"noblock") == 0)) {
+     char *cstr = Char(inputcode);
+     size_t len = Len(inputcode);
+     if (len && cstr[0] == '{') {
+       --len; ++cstr; 
+       if (len && cstr[len - 1] == '}') { --len; }
+       /* we now remove the extra spaces */
+       while (len && isspace((int)cstr[0])) { --len; ++cstr; }
+       while (len && isspace((int)cstr[len - 1])) { --len; }
+       modified_code = NewStringWithSize(cstr, len);
+       break;
+     }
+   }
+   kw = nextSibling(kw);
+  }
+  return modified_code;
+}
+
+
+static Node *nscope = 0;
+static Node *nscope_inner = 0;
+static String *resolve_node_scope(String *cname) {
+  Symtab *gscope = 0;
+  nscope = 0;
+  nscope_inner = 0;  
+  if (Swig_scopename_check(cname)) {
+    Node   *ns;
+    String *prefix = Swig_scopename_prefix(cname);
+    String *base = Swig_scopename_last(cname);
+    if (prefix && (Strncmp(prefix,"::",2) == 0)) {
+      /* Use the global scope */
+      String *nprefix = NewString(Char(prefix)+2);
+      Delete(prefix);
+      prefix= nprefix;
+      gscope = get_global_scope();
+    }    
+    if (!prefix || (Len(prefix) == 0)) {
+      /* Use the global scope, but we need to add a 'global' namespace.  */
+      if (!gscope) gscope = get_global_scope();
+      /* note that this namespace is not the "unnamed" one,
+	 and we don't use Setattr(nscope,"name", ""),
+	 because the unnamed namespace is private */
+      nscope = new_node("namespace");
+      Setattr(nscope,"symtab", gscope);;
+      nscope_inner = nscope;
+      return base;
+    }
+    /* Try to locate the scope */
+    ns = Swig_symbol_clookup(prefix,0);
+    if (!ns) {
+      Swig_error(cparse_file,cparse_line,"Undefined scope '%s'\n", prefix);
+    } else {
+      Symtab *nstab = Getattr(ns,"symtab");
+      if (!nstab) {
+	Swig_error(cparse_file,cparse_line,
+		   "'%s' is not defined as a valid scope.\n", prefix);
+	ns = 0;
+      } else {
+	/* Check if the node scope is the current scope */
+	String *tname = Swig_symbol_qualifiedscopename(0);
+	String *nname = Swig_symbol_qualifiedscopename(nstab);
+	if (tname && (Strcmp(tname,nname) == 0)) {
+	  ns = 0;
+	  cname = base;
+	}
+	Delete(tname);
+	Delete(nname);
+      }
+      if (ns) {
+	/* we will try to create a new node using the namespaces we
+	   can find in the scope name */
+	List *scopes;
+	String *sname;
+	Iterator si;
+	String *name = NewString(prefix);
+	scopes = NewList();
+	while (name) {
+	  String *base = Swig_scopename_last(name);
+	  String *tprefix = Swig_scopename_prefix(name);
+	  Insert(scopes,0,base);
+	  Delete(base);
+	  Delete(name);
+	  name = tprefix;
+	}
+	for (si = First(scopes); si.item; si = Next(si)) {
+	  Node *ns1,*ns2;
+	  sname = si.item;
+	  ns1 = Swig_symbol_clookup(sname,0);
+	  assert(ns1);
+	  if (Strcmp(nodeType(ns1),"namespace") == 0) {
+	    if (Getattr(ns1,"alias")) {
+	      ns1 = Getattr(ns1,"namespace");
+	    }
+	  } else {
+	    /* now this last part is a class */
+	    si = Next(si);
+	    ns1 = Swig_symbol_clookup(sname,0);
+	    /*  or a nested class tree, which is unrolled here */
+	    for (; si.item; si = Next(si)) {
+	      if (si.item) {
+		Printf(sname,"::%s",si.item);
+	      }
+	    }
+	    /* we get the 'inner' class */
+	    nscope_inner = Swig_symbol_clookup(sname,0);
+	    /* set the scope to the inner class */
+	    Swig_symbol_setscope(Getattr(nscope_inner,"symtab"));
+	    /* save the last namespace prefix */
+	    Delete(Namespaceprefix);
+	    Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+	    /* and return the node name, including the inner class prefix */
+	    break;
+	  }
+	  /* here we just populate the namespace tree as usual */
+	  ns2 = new_node("namespace");
+	  Setattr(ns2,"name",sname);
+	  Setattr(ns2,"symtab", Getattr(ns1,"symtab"));
+	  add_symbols(ns2);
+	  Swig_symbol_setscope(Getattr(ns1,"symtab"));
+	  Delete(Namespaceprefix);
+	  Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+	  if (nscope_inner) {
+	    if (Getattr(nscope_inner,"symtab") != Getattr(ns2,"symtab")) {
+	      appendChild(nscope_inner,ns2);
+	      Delete(ns2);
+	    }
+	  }
+	  nscope_inner = ns2;
+	  if (!nscope) nscope = ns2;
+	}
+	cname = base;
+	Delete(scopes);
+      }
+    }
+    Delete(prefix);
+  }
+  return cname;
+}
+ 
+
+
+
+
+/* Structures for handling code fragments built for nested classes */
+
+typedef struct Nested {
+  String   *code;        /* Associated code fragment */
+  int      line;         /* line number where it starts */
+  char     *name;        /* Name associated with this nested class */
+  char     *kind;        /* Kind of class */
+  int      unnamed;      /* unnamed class */
+  SwigType *type;        /* Datatype associated with the name */
+  struct Nested   *next;        /* Next code fragment in list */
+} Nested;
+
+/* Some internal variables for saving nested class information */
+
+static Nested      *nested_list = 0;
+
+/* Add a function to the nested list */
+
+static void add_nested(Nested *n) {
+  Nested *n1;
+  if (!nested_list) nested_list = n;
+  else {
+    n1 = nested_list;
+    while (n1->next) n1 = n1->next;
+    n1->next = n;
+  }
+}
+
+/* Dump all of the nested class declarations to the inline processor
+ * However.  We need to do a few name replacements and other munging
+ * first.  This function must be called before closing a class! */
+
+static Node *dump_nested(const char *parent) {
+  Nested *n,*n1;
+  Node *ret = 0;
+  n = nested_list;
+  if (!parent) {
+    nested_list = 0;
+    return 0;
+  }
+  while (n) {
+    Node *retx;
+    SwigType *nt;
+    /* Token replace the name of the parent class */
+    Replace(n->code, "$classname", parent, DOH_REPLACE_ANY);
+
+    /* Fix up the name of the datatype (for building typedefs and other stuff) */
+    Append(n->type,parent);
+    Append(n->type,"_");
+    Append(n->type,n->name);
+
+    /* Add the appropriate declaration to the C++ processor */
+    retx = new_node("cdecl");
+    Setattr(retx,"name",n->name);
+    nt = Copy(n->type);
+    Setattr(retx,"type",nt);
+    Delete(nt);
+    Setattr(retx,"nested",parent);
+    if (n->unnamed) {
+      Setattr(retx,"unnamed","1");
+    }
+    
+    add_symbols(retx);
+    if (ret) {
+      set_nextSibling(retx,ret);
+      Delete(ret);
+    }
+    ret = retx;
+
+    /* Insert a forward class declaration */
+    /* Disabled: [ 597599 ] union in class: incorrect scope 
+       retx = new_node("classforward");
+       Setattr(retx,"kind",n->kind);
+       Setattr(retx,"name",Copy(n->type));
+       Setattr(retx,"sym:name", make_name(n->type,0));
+       set_nextSibling(retx,ret);
+       ret = retx; 
+    */
+
+    /* Make all SWIG created typedef structs/unions/classes unnamed else 
+       redefinition errors occur - nasty hack alert.*/
+
+    {
+      const char* types_array[3] = {"struct", "union", "class"};
+      int i;
+      for (i=0; i<3; i++) {
+	char* code_ptr = Char(n->code);
+	while (code_ptr) {
+	  /* Replace struct name (as in 'struct name {...}' ) with whitespace
+	     name will be between struct and opening brace */
+	
+	  code_ptr = strstr(code_ptr, types_array[i]);
+	  if (code_ptr) {
+	    char *open_bracket_pos;
+	    code_ptr += strlen(types_array[i]);
+	    open_bracket_pos = strchr(code_ptr, '{');
+	    if (open_bracket_pos) { 
+	      /* Make sure we don't have something like struct A a; */
+	      char* semi_colon_pos = strchr(code_ptr, ';');
+	      if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos)))
+		while (code_ptr < open_bracket_pos)
+		  *code_ptr++ = ' ';
+	    }
+	  }
+	}
+      }
+    }
+    
+    {
+      /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */
+      char* code_ptr = Char(n->code);
+      while (code_ptr) {
+	code_ptr = strstr(code_ptr, "%constant");
+	if (code_ptr) {
+	  char* directive_end_pos = strchr(code_ptr, ';');
+	  if (directive_end_pos) { 
+            while (code_ptr <= directive_end_pos)
+              *code_ptr++ = ' ';
+	  }
+	}
+      }
+    }
+    {
+      Node *head = new_node("insert");
+      String *code = NewStringf("\n%s\n",n->code);
+      Setattr(head,"code", code);
+      Delete(code);
+      set_nextSibling(head,ret);
+      Delete(ret);      
+      ret = head;
+    }
+      
+    /* Dump the code to the scanner */
+    start_inline(Char(n->code),n->line);
+
+    n1 = n->next;
+    Delete(n->code);
+    free(n);
+    n = n1;
+  }
+  nested_list = 0;
+  return ret;
+}
+
+Node *Swig_cparse(File *f) {
+  scanner_file(f);
+  top = 0;
+  yyparse();
+  return top;
+}
+
+static void single_new_feature(const char *featurename, String *val, Hash *featureattribs, char *declaratorid, SwigType *type, ParmList *declaratorparms, String *qualifier) {
+  String *fname;
+  String *name;
+  String *fixname;
+  SwigType *t = Copy(type);
+
+  /* Printf(stdout, "single_new_feature: [%s] [%s] [%s] [%s] [%s] [%s]\n", featurename, val, declaratorid, t, ParmList_str_defaultargs(declaratorparms), qualifier); */
+
+  fname = NewStringf("feature:%s",featurename);
+  if (declaratorid) {
+    fixname = feature_identifier_fix(declaratorid);
+  } else {
+    fixname = NewStringEmpty();
+  }
+  if (Namespaceprefix) {
+    name = NewStringf("%s::%s",Namespaceprefix, fixname);
+  } else {
+    name = fixname;
+  }
+
+  if (declaratorparms) Setmeta(val,"parms",declaratorparms);
+  if (!Len(t)) t = 0;
+  if (t) {
+    if (qualifier) SwigType_push(t,qualifier);
+    if (SwigType_isfunction(t)) {
+      SwigType *decl = SwigType_pop_function(t);
+      if (SwigType_ispointer(t)) {
+	String *nname = NewStringf("*%s",name);
+	Swig_feature_set(Swig_cparse_features(), nname, decl, fname, val, featureattribs);
+	Delete(nname);
+      } else {
+	Swig_feature_set(Swig_cparse_features(), name, decl, fname, val, featureattribs);
+      }
+      Delete(decl);
+    } else if (SwigType_ispointer(t)) {
+      String *nname = NewStringf("*%s",name);
+      Swig_feature_set(Swig_cparse_features(),nname,0,fname,val, featureattribs);
+      Delete(nname);
+    }
+  } else {
+    /* Global feature, that is, feature not associated with any particular symbol */
+    Swig_feature_set(Swig_cparse_features(),name,0,fname,val, featureattribs);
+  }
+  Delete(fname);
+  Delete(name);
+}
+
+/* Add a new feature to the Hash. Additional features are added if the feature has a parameter list (declaratorparms)
+ * and one or more of the parameters have a default argument. An extra feature is added for each defaulted parameter,
+ * simulating the equivalent overloaded method. */
+static void new_feature(const char *featurename, String *val, Hash *featureattribs, char *declaratorid, SwigType *type, ParmList *declaratorparms, String *qualifier) {
+
+  ParmList *declparms = declaratorparms;
+
+  /* remove the { and } braces if the noblock attribute is set */
+  String *newval = remove_block(featureattribs, val);
+  val = newval ? newval : val;
+
+  /* Add the feature */
+  single_new_feature(featurename, val, featureattribs, declaratorid, type, declaratorparms, qualifier);
+
+  /* Add extra features if there are default parameters in the parameter list */
+  if (type) {
+    while (declparms) {
+      if (ParmList_has_defaultargs(declparms)) {
+
+        /* Create a parameter list for the new feature by copying all
+           but the last (defaulted) parameter */
+        ParmList* newparms = CopyParmListMax(declparms, ParmList_len(declparms)-1);
+
+        /* Create new declaration - with the last parameter removed */
+        SwigType *newtype = Copy(type);
+        Delete(SwigType_pop_function(newtype)); /* remove the old parameter list from newtype */
+        SwigType_add_function(newtype,newparms);
+
+        single_new_feature(featurename, Copy(val), featureattribs, declaratorid, newtype, newparms, qualifier);
+        declparms = newparms;
+      } else {
+        declparms = 0;
+      }
+    }
+  }
+}
+
+/* check if a function declaration is a plain C object */
+static int is_cfunction(Node *n) {
+  if (!cparse_cplusplus || cparse_externc) return 1;
+  if (Cmp(Getattr(n,"storage"),"externc") == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+/* If the Node is a function with parameters, check to see if any of the parameters
+ * have default arguments. If so create a new function for each defaulted argument. 
+ * The additional functions form a linked list of nodes with the head being the original Node n. */
+static void default_arguments(Node *n) {
+  Node *function = n;
+
+  if (function) {
+    ParmList *varargs = Getattr(function,"feature:varargs");
+    if (varargs) {
+      /* Handles the %varargs directive by looking for "feature:varargs" and 
+       * substituting ... with an alternative set of arguments.  */
+      Parm     *p = Getattr(function,"parms");
+      Parm     *pp = 0;
+      while (p) {
+	SwigType *t = Getattr(p,"type");
+	if (Strcmp(t,"v(...)") == 0) {
+	  if (pp) {
+	    ParmList *cv = Copy(varargs);
+	    set_nextSibling(pp,cv);
+	    Delete(cv);
+	  } else {
+	    ParmList *cv =  Copy(varargs);
+	    Setattr(function,"parms", cv);
+	    Delete(cv);
+	  }
+	  break;
+	}
+	pp = p;
+	p = nextSibling(p);
+      }
+    }
+
+    /* Do not add in functions if kwargs is being used or if user wants old default argument wrapping
+       (one wrapped method per function irrespective of number of default arguments) */
+    if (compact_default_args 
+	|| is_cfunction(function) 
+	|| GetFlag(function,"feature:compactdefaultargs") 
+	|| GetFlag(function,"feature:kwargs")) {
+      ParmList *p = Getattr(function,"parms");
+      if (p) 
+        Setattr(p,"compactdefargs", "1"); /* mark parameters for special handling */
+      function = 0; /* don't add in extra methods */
+    }
+  }
+
+  while (function) {
+    ParmList *parms = Getattr(function,"parms");
+    if (ParmList_has_defaultargs(parms)) {
+
+      /* Create a parameter list for the new function by copying all
+         but the last (defaulted) parameter */
+      ParmList* newparms = CopyParmListMax(parms,ParmList_len(parms)-1);
+
+      /* Create new function and add to symbol table */
+      {
+	SwigType *ntype = Copy(nodeType(function));
+	char *cntype = Char(ntype);
+        Node *new_function = new_node(ntype);
+        SwigType *decl = Copy(Getattr(function,"decl"));
+        int constqualifier = SwigType_isconst(decl);
+	String *ccode = Copy(Getattr(function,"code"));
+	String *cstorage = Copy(Getattr(function,"storage"));
+	String *cvalue = Copy(Getattr(function,"value"));
+	SwigType *ctype = Copy(Getattr(function,"type"));
+	String *cthrow = Copy(Getattr(function,"throw"));
+
+        Delete(SwigType_pop_function(decl)); /* remove the old parameter list from decl */
+        SwigType_add_function(decl,newparms);
+        if (constqualifier)
+          SwigType_add_qualifier(decl,"const");
+
+        Setattr(new_function,"name", Getattr(function,"name"));
+        Setattr(new_function,"code", ccode);
+        Setattr(new_function,"decl", decl);
+        Setattr(new_function,"parms", newparms);
+        Setattr(new_function,"storage", cstorage);
+        Setattr(new_function,"value", cvalue);
+        Setattr(new_function,"type", ctype);
+        Setattr(new_function,"throw", cthrow);
+
+	Delete(ccode);
+	Delete(cstorage);
+	Delete(cvalue);
+	Delete(ctype);
+	Delete(cthrow);
+	Delete(decl);
+
+        {
+          Node *throws = Getattr(function,"throws");
+	  ParmList *pl = CopyParmList(throws);
+          if (throws) Setattr(new_function,"throws",pl);
+	  Delete(pl);
+        }
+
+        /* copy specific attributes for global (or in a namespace) template functions - these are not templated class methods */
+        if (strcmp(cntype,"template") == 0) {
+          Node *templatetype = Getattr(function,"templatetype");
+          Node *symtypename = Getattr(function,"sym:typename");
+          Parm *templateparms = Getattr(function,"templateparms");
+          if (templatetype) {
+	    Node *tmp = Copy(templatetype);
+	    Setattr(new_function,"templatetype",tmp);
+	    Delete(tmp);
+	  }
+          if (symtypename) {
+	    Node *tmp = Copy(symtypename);
+	    Setattr(new_function,"sym:typename",tmp);
+	    Delete(tmp);
+	  }
+          if (templateparms) {
+	    Parm *tmp = CopyParmList(templateparms);
+	    Setattr(new_function,"templateparms",tmp);
+	    Delete(tmp);
+	  }
+        } else if (strcmp(cntype,"constructor") == 0) {
+          /* only copied for constructors as this is not a user defined feature - it is hard coded in the parser */
+          if (GetFlag(function,"feature:new")) SetFlag(new_function,"feature:new");
+        }
+
+        add_symbols(new_function);
+        /* mark added functions as ones with overloaded parameters and point to the parsed method */
+        Setattr(new_function,"defaultargs", n);
+
+        /* Point to the new function, extending the linked list */
+        set_nextSibling(function, new_function);
+	Delete(new_function);
+        function = new_function;
+	
+	Delete(ntype);
+      }
+    } else {
+      function = 0;
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * tag_nodes()
+ *
+ * Used by the parser to mark subtypes with extra information.
+ * ----------------------------------------------------------------------------- */
+
+static void tag_nodes(Node *n, const String_or_char *attrname, DOH *value) {
+  while (n) {
+    Setattr(n, attrname, value);
+    tag_nodes(firstChild(n), attrname, value);
+    n = nextSibling(n);
+  }
+}
+
+%}
+
+%union {
+  char  *id;
+  List  *bases;
+  struct Define {
+    String *val;
+    String *rawval;
+    int     type;
+    String *qualifier;
+    String *bitfield;
+    Parm   *throws;
+    String *throwf;
+  } dtype;
+  struct {
+    char *type;
+    String *filename;
+    int   line;
+  } loc;
+  struct {
+    char      *id;
+    SwigType  *type;
+    String    *defarg;
+    ParmList  *parms;
+    short      have_parms;
+    ParmList  *throws;
+    String    *throwf;
+  } decl;
+  Parm         *tparms;
+  struct {
+    String     *op;
+    Hash       *kwargs;
+  } tmap;
+  struct {
+    String     *type;
+    String     *us;
+  } ptype;
+  SwigType     *type;
+  String       *str;
+  Parm         *p;
+  ParmList     *pl;
+  int           ivalue;
+  Node         *node;
+};
+
+%token <id> ID
+%token <str> HBLOCK
+%token <id> POUND 
+%token <id> STRING
+%token <loc> INCLUDE IMPORT INSERT
+%token <str> CHARCONST 
+%token <dtype> NUM_INT NUM_FLOAT NUM_UNSIGNED NUM_LONG NUM_ULONG NUM_LONGLONG NUM_ULONGLONG
+%token <ivalue> TYPEDEF
+%token <type> TYPE_INT TYPE_UNSIGNED TYPE_SHORT TYPE_LONG TYPE_FLOAT TYPE_DOUBLE TYPE_CHAR TYPE_WCHAR TYPE_VOID TYPE_SIGNED TYPE_BOOL TYPE_COMPLEX TYPE_TYPEDEF TYPE_RAW TYPE_NON_ISO_INT8 TYPE_NON_ISO_INT16 TYPE_NON_ISO_INT32 TYPE_NON_ISO_INT64
+%token LPAREN RPAREN COMMA SEMI EXTERN INIT LBRACE RBRACE PERIOD
+%token CONST_QUAL VOLATILE REGISTER STRUCT UNION EQUAL SIZEOF MODULE LBRACKET RBRACKET
+%token ILLEGAL CONSTANT
+%token NAME RENAME NAMEWARN EXTEND PRAGMA FEATURE VARARGS
+%token ENUM
+%token CLASS TYPENAME PRIVATE PUBLIC PROTECTED COLON STATIC VIRTUAL FRIEND THROW CATCH EXPLICIT
+%token USING
+%token <node> NAMESPACE
+%token NATIVE INLINE
+%token TYPEMAP EXCEPT ECHO APPLY CLEAR SWIGTEMPLATE FRAGMENT
+%token WARN 
+%token LESSTHAN GREATERTHAN MODULO DELETE_KW
+%token LESSTHANOREQUALTO GREATERTHANOREQUALTO EQUALTO NOTEQUALTO
+%token QUESTIONMARK
+%token TYPES PARMS
+%token NONID DSTAR DCNOT
+%token <ivalue> TEMPLATE
+%token <str> OPERATOR
+%token <str> COPERATOR
+%token PARSETYPE PARSEPARM PARSEPARMS
+
+%left  CAST
+%left  QUESTIONMARK
+%left  LOR
+%left  LAND
+%left  OR
+%left  XOR
+%left  AND
+%left  EQUALTO NOTEQUALTO
+%left  GREATERTHAN LESSTHAN GREATERTHANOREQUALTO LESSTHANOREQUALTO
+%left  LSHIFT RSHIFT
+%left  PLUS MINUS
+%left  STAR SLASH MODULUS
+%left  UMINUS NOT LNOT
+%left  DCOLON
+
+%type <node>     program interface declaration swig_directive ;
+
+/* SWIG directives */
+%type <node>     extend_directive apply_directive clear_directive constant_directive ;
+%type <node>     echo_directive except_directive fragment_directive include_directive inline_directive ;
+%type <node>     insert_directive module_directive name_directive native_directive ;
+%type <node>     pragma_directive rename_directive feature_directive varargs_directive typemap_directive ;
+%type <node>     types_directive template_directive warn_directive ;
+
+/* C declarations */
+%type <node>     c_declaration c_decl c_decl_tail c_enum_decl c_enum_forward_decl c_constructor_decl ;
+%type <node>     enumlist edecl;
+
+/* C++ declarations */
+%type <node>     cpp_declaration cpp_class_decl cpp_forward_class_decl cpp_template_decl;
+%type <node>     cpp_members cpp_member;
+%type <node>     cpp_constructor_decl cpp_destructor_decl cpp_protection_decl cpp_conversion_operator;
+%type <node>     cpp_swig_directive cpp_temp_possible cpp_nested cpp_opt_declarators ;
+%type <node>     cpp_using_decl cpp_namespace_decl cpp_catch_decl ;
+%type <node>     kwargs options;
+
+/* Misc */
+%type <dtype>    initializer cpp_const ;
+%type <id>       storage_class;
+%type <pl>       parms  ptail rawparms varargs_parms;
+%type <pl>       templateparameters templateparameterstail;
+%type <p>        parm valparm rawvalparms valparms valptail ;
+%type <p>        typemap_parm tm_list tm_tail ;
+%type <p>        templateparameter ;
+%type <id>       templcpptype cpptype access_specifier;
+%type <node>     base_specifier
+%type <type>     type rawtype type_right ;
+%type <bases>    base_list inherit raw_inherit;
+%type <dtype>    definetype def_args etype;
+%type <dtype>    expr exprnum exprcompound valexpr;
+%type <id>       ename ;
+%type <id>       template_decl;
+%type <str>      type_qualifier ;
+%type <id>       type_qualifier_raw;
+%type <id>       idstring idstringopt;
+%type <id>       pragma_lang;
+%type <str>      pragma_arg;
+%type <loc>      includetype;
+%type <type>     pointer primitive_type;
+%type <decl>     declarator direct_declarator notso_direct_declarator parameter_declarator typemap_parameter_declarator nested_decl;
+%type <decl>     abstract_declarator direct_abstract_declarator ctor_end;
+%type <tmap>     typemap_type;
+%type <str>      idcolon idcolontail idcolonnt idcolontailnt idtemplate stringbrace stringbracesemi;
+%type <id>       string stringnum ;
+%type <tparms>   template_parms;
+%type <dtype>    cpp_end cpp_vend;
+%type <ivalue>   rename_namewarn;
+%type <ptype>    type_specifier primitive_type_list ;
+%type <node>     fname stringtype;
+%type <node>     featattr;
+
+%%
+
+/* ======================================================================
+ *                          High-level Interface file
+ *
+ * An interface is just a sequence of declarations which may be SWIG directives
+ * or normal C declarations.
+ * ====================================================================== */
+
+program        :  interface {
+                   if (!classes) classes = NewHash();
+		   Setattr($1,"classes",classes); 
+		   Setattr($1,"name",ModuleName);
+		   
+		   if ((!module_node) && ModuleName) {
+		     module_node = new_node("module");
+		     Setattr(module_node,"name",ModuleName);
+		   }
+		   Setattr($1,"module",module_node);
+		   check_extensions();
+	           top = $1;
+               }
+               | PARSETYPE parm SEMI {
+                 top = Copy(Getattr($2,"type"));
+		 Delete($2);
+               }
+               | PARSETYPE error {
+                 top = 0;
+               }
+               | PARSEPARM parm SEMI {
+                 top = $2;
+               }
+               | PARSEPARM error {
+                 top = 0;
+               }
+               | PARSEPARMS LPAREN parms RPAREN SEMI {
+                 top = $3;
+               }
+               | PARSEPARMS error SEMI {
+                 top = 0;
+               }
+               ;
+
+interface      : interface declaration {  
+                   /* add declaration to end of linked list (the declaration isn't always a single declaration, sometimes it is a linked list itself) */
+                   appendChild($1,$2);
+                   $$ = $1;
+               }
+               | empty {
+                   $$ = new_node("top");
+               }
+               ;
+
+declaration    : swig_directive { $$ = $1; }
+               | c_declaration { $$ = $1; } 
+               | cpp_declaration { $$ = $1; }
+               | SEMI { $$ = 0; }
+               | error {
+                  $$ = 0;
+		  Swig_error(cparse_file, cparse_line,"Syntax error in input(1).\n");
+		  exit(1);
+               }
+/* Out of class constructor/destructor declarations */
+               | c_constructor_decl { 
+                  if ($$) {
+   		      add_symbols($$);
+                  }
+                  $$ = $1; 
+	       }              
+
+/* Out of class conversion operator.  For example:
+     inline A::operator char *() const { ... }.
+
+   This is nearly impossible to parse normally.  We just let the
+   first part generate a syntax error and then resynchronize on the
+   COPERATOR token---discarding the rest of the definition. Ugh.
+
+ */
+
+               | error COPERATOR {
+                  $$ = 0;
+                  skip_decl();
+               }
+               ;
+
+/* ======================================================================
+ *                           SWIG DIRECTIVES 
+ * ====================================================================== */
+  
+swig_directive : extend_directive { $$ = $1; }
+               | apply_directive { $$ = $1; }
+ 	       | clear_directive { $$ = $1; }
+               | constant_directive { $$ = $1; }
+               | echo_directive { $$ = $1; }
+               | except_directive { $$ = $1; }
+               | fragment_directive { $$ = $1; }
+               | include_directive { $$ = $1; }
+               | inline_directive { $$ = $1; }
+               | insert_directive { $$ = $1; }
+               | module_directive { $$ = $1; }
+               | name_directive { $$ = $1; }
+               | native_directive { $$ = $1; }
+               | pragma_directive { $$ = $1; }
+               | rename_directive { $$ = $1; }
+               | feature_directive { $$ = $1; }
+               | varargs_directive { $$ = $1; }
+               | typemap_directive { $$ = $1; }
+               | types_directive  { $$ = $1; }
+               | template_directive { $$ = $1; }
+               | warn_directive { $$ = $1; }
+               ;
+
+/* ------------------------------------------------------------
+   %extend classname { ... } 
+   ------------------------------------------------------------ */
+
+extend_directive : EXTEND options idcolon LBRACE {
+               Node *cls;
+	       String *clsname;
+	       cplus_mode = CPLUS_PUBLIC;
+	       if (!classes) classes = NewHash();
+	       if (!extendhash) extendhash = NewHash();
+	       clsname = make_class_name($3);
+	       cls = Getattr(classes,clsname);
+	       if (!cls) {
+		 /* No previous definition. Create a new scope */
+		 Node *am = Getattr(extendhash,clsname);
+		 if (!am) {
+		   Swig_symbol_newscope();
+		   Swig_symbol_setscopename($3);
+		   prev_symtab = 0;
+		 } else {
+		   prev_symtab = Swig_symbol_setscope(Getattr(am,"symtab"));
+		 }
+		 current_class = 0;
+	       } else {
+		 /* Previous class definition.  Use its symbol table */
+		 prev_symtab = Swig_symbol_setscope(Getattr(cls,"symtab"));
+		 current_class = cls;
+		 extendmode = 1;
+	       }
+	       Classprefix = NewString($3);
+	       Namespaceprefix= Swig_symbol_qualifiedscopename(0);
+	       Delete(clsname);
+	     } cpp_members RBRACE {
+               String *clsname;
+	       extendmode = 0;
+               $$ = new_node("extend");
+	       Setattr($$,"symtab",Swig_symbol_popscope());
+	       if (prev_symtab) {
+		 Swig_symbol_setscope(prev_symtab);
+	       }
+	       Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+               clsname = make_class_name($3);
+	       Setattr($$,"name",clsname);
+
+	       /* Mark members as extend */
+
+	       tag_nodes($6,"feature:extend",(char*) "1");
+	       if (current_class) {
+		 /* We add the extension to the previously defined class */
+		 appendChild($$,$6);
+		 appendChild(current_class,$$);
+	       } else {
+		 /* We store the extensions in the extensions hash */
+		 Node *am = Getattr(extendhash,clsname);
+		 if (am) {
+		   /* Append the members to the previous extend methods */
+		   appendChild(am,$6);
+		 } else {
+		   appendChild($$,$6);
+		   Setattr(extendhash,clsname,$$);
+		 }
+	       }
+	       current_class = 0;
+	       Delete(Classprefix);
+	       Delete(clsname);
+	       Classprefix = 0;
+	       prev_symtab = 0;
+	       $$ = 0;
+
+	     }
+             ;
+
+/* ------------------------------------------------------------
+   %apply
+   ------------------------------------------------------------ */
+
+apply_directive : APPLY typemap_parm LBRACE tm_list RBRACE {
+                    $$ = new_node("apply");
+                    Setattr($$,"pattern",Getattr($2,"pattern"));
+		    appendChild($$,$4);
+               };
+
+/* ------------------------------------------------------------
+   %clear
+   ------------------------------------------------------------ */
+
+clear_directive : CLEAR tm_list SEMI {
+		 $$ = new_node("clear");
+		 appendChild($$,$2);
+               }
+               ;
+
+/* ------------------------------------------------------------
+   %constant name = value;
+   %constant type name = value;
+   ------------------------------------------------------------ */
+
+constant_directive :  CONSTANT ID EQUAL definetype SEMI {
+		   if (($4.type != T_ERROR) && ($4.type != T_SYMBOL)) {
+		     SwigType *type = NewSwigType($4.type);
+		     $$ = new_node("constant");
+		     Setattr($$,"name",$2);
+		     Setattr($$,"type",type);
+		     Setattr($$,"value",$4.val);
+		     if ($4.rawval) Setattr($$,"rawval", $4.rawval);
+		     Setattr($$,"storage","%constant");
+		     SetFlag($$,"feature:immutable");
+		     add_symbols($$);
+		     Delete(type);
+		   } else {
+		     if ($4.type == T_ERROR) {
+		       Swig_warning(WARN_PARSE_UNSUPPORTED_VALUE,cparse_file,cparse_line,"Unsupported constant value (ignored)\n");
+		     }
+		     $$ = 0;
+		   }
+
+	       }
+
+               | CONSTANT type declarator def_args SEMI {
+		 if (($4.type != T_ERROR) && ($4.type != T_SYMBOL)) {
+		   SwigType_push($2,$3.type);
+		   /* Sneaky callback function trick */
+		   if (SwigType_isfunction($2)) {
+		     SwigType_add_pointer($2);
+		   }
+		   $$ = new_node("constant");
+		   Setattr($$,"name",$3.id);
+		   Setattr($$,"type",$2);
+		   Setattr($$,"value",$4.val);
+		   if ($4.rawval) Setattr($$,"rawval", $4.rawval);
+		   Setattr($$,"storage","%constant");
+		   SetFlag($$,"feature:immutable");
+		   add_symbols($$);
+		 } else {
+		     if ($4.type == T_ERROR) {
+		       Swig_warning(WARN_PARSE_UNSUPPORTED_VALUE,cparse_file,cparse_line,"Unsupported constant value\n");
+		     }
+		   $$ = 0;
+		 }
+               }
+               | CONSTANT error SEMI {
+		 Swig_warning(WARN_PARSE_BAD_VALUE,cparse_file,cparse_line,"Bad constant value (ignored).\n");
+		 $$ = 0;
+	       }
+               ;
+
+/* ------------------------------------------------------------
+   %echo "text"
+   %echo %{ ... %}
+   ------------------------------------------------------------ */
+
+echo_directive : ECHO HBLOCK {
+		 char temp[64];
+		 Replace($2,"$file",cparse_file, DOH_REPLACE_ANY);
+		 sprintf(temp,"%d", cparse_line);
+		 Replace($2,"$line",temp,DOH_REPLACE_ANY);
+		 Printf(stderr,"%s\n", $2);
+		 Delete($2);
+                 $$ = 0;
+	       }
+               | ECHO string {
+		 char temp[64];
+		 String *s = NewString($2);
+		 Replace(s,"$file",cparse_file, DOH_REPLACE_ANY);
+		 sprintf(temp,"%d", cparse_line);
+		 Replace(s,"$line",temp,DOH_REPLACE_ANY);
+		 Printf(stderr,"%s\n", s);
+		 Delete(s);
+                 $$ = 0;
+               }
+               ;
+
+/* ------------------------------------------------------------
+   %except(lang) { ... }
+   %except { ... }
+   %except(lang);   
+   %except;
+   ------------------------------------------------------------ */
+
+except_directive : EXCEPT LPAREN ID RPAREN LBRACE {
+                    skip_balanced('{','}');
+		    $$ = 0;
+		    Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated.  Use %%exception instead.\n");
+	       }
+
+               | EXCEPT LBRACE {
+                    skip_balanced('{','}');
+		    $$ = 0;
+		    Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated.  Use %%exception instead.\n");
+               }
+
+               | EXCEPT LPAREN ID RPAREN SEMI {
+		 $$ = 0;
+		 Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated.  Use %%exception instead.\n");
+               }
+
+               | EXCEPT SEMI {
+		 $$ = 0;
+		 Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated.  Use %%exception instead.\n");
+	       }
+               ;
+
+/* fragment keyword arguments */
+stringtype    : string LBRACE parm RBRACE {		 
+                 $$ = NewHash();
+                 Setattr($$,"value",$1);
+		 Setattr($$,"type",Getattr($3,"type"));
+               }
+               ;
+
+fname         : string {
+                 $$ = NewHash();
+                 Setattr($$,"value",$1);
+              }
+              | stringtype {
+                $$ = $1;
+              }
+              ;
+
+/* ------------------------------------------------------------
+   %fragment(name, section) %{ ... %}
+   %fragment("name" {type}, "section") %{ ... %}
+   %fragment("name", "section", fragment="fragment1", fragment="fragment2") %{ ... %}
+   Also as above but using { ... }
+   %fragment("name");
+   ------------------------------------------------------------ */
+
+fragment_directive: FRAGMENT LPAREN fname COMMA kwargs RPAREN HBLOCK {
+                   Hash *p = $5;
+		   $$ = new_node("fragment");
+		   Setattr($$,"value",Getattr($3,"value"));
+		   Setattr($$,"type",Getattr($3,"type"));
+		   Setattr($$,"section",Getattr(p,"name"));
+		   Setattr($$,"kwargs",nextSibling(p));
+		   Setattr($$,"code",$7);
+                 }
+                 | FRAGMENT LPAREN fname COMMA kwargs RPAREN LBRACE {
+		   Hash *p = $5;
+		   String *code;
+                   skip_balanced('{','}');
+		   $$ = new_node("fragment");
+		   Setattr($$,"value",Getattr($3,"value"));
+		   Setattr($$,"type",Getattr($3,"type"));
+		   Setattr($$,"section",Getattr(p,"name"));
+		   Setattr($$,"kwargs",nextSibling(p));
+		   Delitem(scanner_ccode,0);
+		   Delitem(scanner_ccode,DOH_END);
+		   code = Copy(scanner_ccode);
+		   Setattr($$,"code",code);
+		   Delete(code);
+                 }
+                 | FRAGMENT LPAREN fname RPAREN SEMI {
+		   $$ = new_node("fragment");
+		   Setattr($$,"value",Getattr($3,"value"));
+		   Setattr($$,"type",Getattr($3,"type"));
+		   Setattr($$,"emitonly","1");
+		 }
+                 ;
+
+/* ------------------------------------------------------------
+   %includefile "filename" [ declarations ] 
+   %importfile  "filename" [ declarations ]
+   ------------------------------------------------------------ */
+
+include_directive: includetype options string LBRACKET {
+                     $1.filename = Copy(cparse_file);
+		     $1.line = cparse_line;
+		     scanner_set_location(NewString($3),1);
+               } interface RBRACKET {
+                     String *mname = 0;
+                     $$ = $6;
+		     scanner_set_location($1.filename,$1.line);
+		     if (strcmp($1.type,"include") == 0) set_nodeType($$,"include");
+		     if (strcmp($1.type,"import") == 0) {
+		       mname = $2 ? Getattr($2,"module") : 0;
+		       set_nodeType($$,"import");
+		       if (import_mode) --import_mode;
+		     }
+		     
+		     Setattr($$,"name",$3);
+		     /* Search for the module (if any) */
+		     {
+			 Node *n = firstChild($$);
+			 while (n) {
+			     if (Strcmp(nodeType(n),"module") == 0) {
+			         if (mname) {
+				   Setattr(n,"name", mname);
+				   mname = 0;
+				 }
+				 Setattr($$,"module",Getattr(n,"name"));
+				 break;
+			     }
+			     n = nextSibling(n);
+			 }
+			 if (mname) {
+			   /* There is no module node in the import
+			      node, ie, you imported a .h file
+			      directly.  We are forced then to create
+			      a new import node with a module node.
+			   */			      
+			   Node *nint = new_node("import");
+			   Node *mnode = new_node("module");
+			   Setattr(mnode,"name", mname);
+			   appendChild(nint,mnode);
+			   Delete(mnode);
+			   appendChild(nint,firstChild($$));
+			   $$ = nint;
+			   Setattr($$,"module",mname);
+			 }
+		     }
+		     Setattr($$,"options",$2);
+               }
+               ;
+
+includetype    : INCLUDE { $$.type = (char *) "include"; }
+               | IMPORT  { $$.type = (char *) "import"; ++import_mode;}
+               ;
+
+/* ------------------------------------------------------------
+   %inline %{ ... %}
+   ------------------------------------------------------------ */
+
+inline_directive : INLINE HBLOCK {
+                 String *cpps;
+		 if (Namespaceprefix) {
+		   Swig_error(cparse_file, cparse_start_line, "%%inline directive inside a namespace is disallowed.\n");
+
+		   $$ = 0;
+		 } else {
+		   $$ = new_node("insert");
+		   Setattr($$,"code",$2);
+		   /* Need to run through the preprocessor */
+		   Setline($2,cparse_start_line);
+		   Setfile($2,cparse_file);
+		   Seek($2,0,SEEK_SET);
+		   cpps = Preprocessor_parse($2);
+		   start_inline(Char(cpps), cparse_start_line);
+		   Delete($2);
+		   Delete(cpps);
+		 }
+		 
+	       }
+               | INLINE LBRACE {
+                 String *cpps;
+		 int start_line = cparse_line;
+		 skip_balanced('{','}');
+		 if (Namespaceprefix) {
+		   Swig_error(cparse_file, cparse_start_line, "%%inline directive inside a namespace is disallowed.\n");
+		   
+		   $$ = 0;
+		 } else {
+		   String *code;
+                   $$ = new_node("insert");
+		   Delitem(scanner_ccode,0);
+		   Delitem(scanner_ccode,DOH_END);
+		   code = Copy(scanner_ccode);
+		   Setattr($$,"code", code);
+		   Delete(code);		   
+		   cpps=Copy(scanner_ccode);
+		   start_inline(Char(cpps), start_line);
+		   Delete(cpps);
+		 }
+               }
+                ;
+
+/* ------------------------------------------------------------
+   %{ ... %}
+   %insert(section) "filename"
+   %insert("section") "filename"
+   %insert(section) %{ ... %}
+   %insert("section") %{ ... %}
+   ------------------------------------------------------------ */
+
+insert_directive : HBLOCK {
+                 $$ = new_node("insert");
+		 Setattr($$,"code",$1);
+	       }
+               | INSERT LPAREN idstring RPAREN string {
+		 String *code = NewStringEmpty();
+		 $$ = new_node("insert");
+		 Setattr($$,"section",$3);
+		 Setattr($$,"code",code);
+		 if (Swig_insert_file($5,code) < 0) {
+		   Swig_error(cparse_file, cparse_line, "Couldn't find '%s'.\n", $5);
+		   $$ = 0;
+		 } 
+               }
+               | INSERT LPAREN idstring RPAREN HBLOCK {
+		 $$ = new_node("insert");
+		 Setattr($$,"section",$3);
+		 Setattr($$,"code",$5);
+               }
+               | INSERT LPAREN idstring RPAREN LBRACE {
+		 String *code;
+                 skip_balanced('{','}');
+		 $$ = new_node("insert");
+		 Setattr($$,"section",$3);
+		 Delitem(scanner_ccode,0);
+		 Delitem(scanner_ccode,DOH_END);
+		 code = Copy(scanner_ccode);
+		 Setattr($$,"code", code);
+		 Delete(code);
+	       }
+               ;
+      
+/* ------------------------------------------------------------
+    %module modname
+    %module "modname"
+   ------------------------------------------------------------ */
+
+module_directive: MODULE options idstring {
+                 $$ = new_node("module");
+		 if ($2) {
+		   Setattr($$,"options",$2);
+		   if (Getattr($2,"directors")) {
+		     Wrapper_director_mode_set(1);
+		   } 
+		   if (Getattr($2,"dirprot")) {
+		     Wrapper_director_protected_mode_set(1);
+		   } 
+		   if (Getattr($2,"allprotected")) {
+		     Wrapper_all_protected_mode_set(1);
+		   } 
+		   if (Getattr($2,"templatereduce")) {
+		     template_reduce = 1;
+		   }
+		   if (Getattr($2,"notemplatereduce")) {
+		     template_reduce = 0;
+		   }
+		 }
+		 if (!ModuleName) ModuleName = NewString($3);
+		 if (!import_mode) {
+		   /* first module included, we apply global
+		      ModuleName, which can be modify by -module */
+		   String *mname = Copy(ModuleName);
+		   Setattr($$,"name",mname);
+		   Delete(mname);
+		 } else { 
+		   /* import mode, we just pass the idstring */
+		   Setattr($$,"name",$3);   
+		 }		 
+		 if (!module_node) module_node = $$;
+	       }
+               ;
+
+/* ------------------------------------------------------------
+   %name(newname)    declaration
+   %name("newname")  declaration
+   ------------------------------------------------------------ */
+
+name_directive : NAME LPAREN idstring RPAREN {
+                 Swig_warning(WARN_DEPRECATED_NAME,cparse_file,cparse_line, "%%name is deprecated.  Use %%rename instead.\n");
+		 Delete(yyrename);
+                 yyrename = NewString($3);
+		 $$ = 0;
+               }
+               | NAME LPAREN RPAREN {
+		 Swig_warning(WARN_DEPRECATED_NAME,cparse_file,cparse_line, "%%name is deprecated.  Use %%rename instead.\n");
+		 $$ = 0;
+		 Swig_error(cparse_file,cparse_line,"Missing argument to %%name directive.\n");
+	       }
+               ;
+
+
+/* ------------------------------------------------------------
+   %native(scriptname) name;
+   %native(scriptname) type name (parms);
+   ------------------------------------------------------------ */
+
+native_directive : NATIVE LPAREN ID RPAREN storage_class ID SEMI {
+                 $$ = new_node("native");
+		 Setattr($$,"name",$3);
+		 Setattr($$,"wrap:name",$6);
+	         add_symbols($$);
+	       }
+               | NATIVE LPAREN ID RPAREN storage_class type declarator SEMI {
+		 if (!SwigType_isfunction($7.type)) {
+		   Swig_error(cparse_file,cparse_line,"%%native declaration '%s' is not a function.\n", $7.id);
+		   $$ = 0;
+		 } else {
+		     Delete(SwigType_pop_function($7.type));
+		     /* Need check for function here */
+		     SwigType_push($6,$7.type);
+		     $$ = new_node("native");
+	             Setattr($$,"name",$3);
+		     Setattr($$,"wrap:name",$7.id);
+		     Setattr($$,"type",$6);
+		     Setattr($$,"parms",$7.parms);
+		     Setattr($$,"decl",$7.type);
+		 }
+	         add_symbols($$);
+	       }
+               ;
+
+/* ------------------------------------------------------------
+   %pragma(lang) name=value
+   %pragma(lang) name
+   %pragma name = value
+   %pragma name
+   ------------------------------------------------------------ */
+
+pragma_directive : PRAGMA pragma_lang ID EQUAL pragma_arg {
+                 $$ = new_node("pragma");
+		 Setattr($$,"lang",$2);
+		 Setattr($$,"name",$3);
+		 Setattr($$,"value",$5);
+	       }
+              | PRAGMA pragma_lang ID {
+		$$ = new_node("pragma");
+		Setattr($$,"lang",$2);
+		Setattr($$,"name",$3);
+	      }
+              ;
+
+pragma_arg    : string { $$ = NewString($1); }
+              | HBLOCK { $$ = $1; }
+              ;
+
+pragma_lang   : LPAREN ID RPAREN { $$ = $2; }
+              | empty { $$ = (char *) "swig"; }
+              ;
+
+/* ------------------------------------------------------------
+   %rename identifier newname;
+   %rename identifier "newname";
+   ------------------------------------------------------------ */
+
+rename_directive : rename_namewarn declarator idstring SEMI {
+                SwigType *t = $2.type;
+		Hash *kws = NewHash();
+		String *fixname;
+		fixname = feature_identifier_fix($2.id);
+		Setattr(kws,"name",$3);
+		if (!Len(t)) t = 0;
+		/* Special declarator check */
+		if (t) {
+		  if (SwigType_isfunction(t)) {
+		    SwigType *decl = SwigType_pop_function(t);
+		    if (SwigType_ispointer(t)) {
+		      String *nname = NewStringf("*%s",fixname);
+		      if ($1) {
+			Swig_name_rename_add(Namespaceprefix, nname,decl,kws,$2.parms);
+		      } else {
+			Swig_name_namewarn_add(Namespaceprefix,nname,decl,kws);
+		      }
+		      Delete(nname);
+		    } else {
+		      if ($1) {
+			Swig_name_rename_add(Namespaceprefix,(fixname),decl,kws,$2.parms);
+		      } else {
+			Swig_name_namewarn_add(Namespaceprefix,(fixname),decl,kws);
+		      }
+		    }
+		    Delete(decl);
+		  } else if (SwigType_ispointer(t)) {
+		    String *nname = NewStringf("*%s",fixname);
+		    if ($1) {
+		      Swig_name_rename_add(Namespaceprefix,(nname),0,kws,$2.parms);
+		    } else {
+		      Swig_name_namewarn_add(Namespaceprefix,(nname),0,kws);
+		    }
+		    Delete(nname);
+		  }
+		} else {
+		  if ($1) {
+		    Swig_name_rename_add(Namespaceprefix,(fixname),0,kws,$2.parms);
+		  } else {
+		    Swig_name_namewarn_add(Namespaceprefix,(fixname),0,kws);
+		  }
+		}
+                $$ = 0;
+		scanner_clear_rename();
+              }
+              | rename_namewarn LPAREN kwargs RPAREN declarator cpp_const SEMI {
+		String *fixname;
+		Hash *kws = $3;
+		SwigType *t = $5.type;
+		fixname = feature_identifier_fix($5.id);
+		if (!Len(t)) t = 0;
+		/* Special declarator check */
+		if (t) {
+		  if ($6.qualifier) SwigType_push(t,$6.qualifier);
+		  if (SwigType_isfunction(t)) {
+		    SwigType *decl = SwigType_pop_function(t);
+		    if (SwigType_ispointer(t)) {
+		      String *nname = NewStringf("*%s",fixname);
+		      if ($1) {
+			Swig_name_rename_add(Namespaceprefix, nname,decl,kws,$5.parms);
+		      } else {
+			Swig_name_namewarn_add(Namespaceprefix,nname,decl,kws);
+		      }
+		      Delete(nname);
+		    } else {
+		      if ($1) {
+			Swig_name_rename_add(Namespaceprefix,(fixname),decl,kws,$5.parms);
+		      } else {
+			Swig_name_namewarn_add(Namespaceprefix,(fixname),decl,kws);
+		      }
+		    }
+		    Delete(decl);
+		  } else if (SwigType_ispointer(t)) {
+		    String *nname = NewStringf("*%s",fixname);
+		    if ($1) {
+		      Swig_name_rename_add(Namespaceprefix,(nname),0,kws,$5.parms);
+		    } else {
+		      Swig_name_namewarn_add(Namespaceprefix,(nname),0,kws);
+		    }
+		    Delete(nname);
+		  }
+		} else {
+		  if ($1) {
+		    Swig_name_rename_add(Namespaceprefix,(fixname),0,kws,$5.parms);
+		  } else {
+		    Swig_name_namewarn_add(Namespaceprefix,(fixname),0,kws);
+		  }
+		}
+                $$ = 0;
+		scanner_clear_rename();
+              }
+              | rename_namewarn LPAREN kwargs RPAREN string SEMI {
+		if ($1) {
+		  Swig_name_rename_add(Namespaceprefix,$5,0,$3,0);
+		} else {
+		  Swig_name_namewarn_add(Namespaceprefix,$5,0,$3);
+		}
+		$$ = 0;
+		scanner_clear_rename();
+              }
+              ;
+
+rename_namewarn : RENAME {
+		    $$ = 1;
+                } 
+                | NAMEWARN {
+                    $$ = 0;
+                };
+
+
+/* ------------------------------------------------------------
+   Feature targeting a symbol name (non-global feature):
+
+     %feature(featurename) name "val";
+     %feature(featurename, val) name;
+
+   where "val" could instead be the other bracket types, that is,
+   { val } or %{ val %} or indeed omitted whereupon it defaults to "1".
+   Or, the global feature which does not target a symbol name:
+
+     %feature(featurename) "val";
+     %feature(featurename, val);
+
+   An empty val (empty string) clears the feature.
+   Any number of feature attributes can optionally be added, for example
+   a non-global feature with 2 attributes:
+
+     %feature(featurename, attrib1="attribval1", attrib2="attribval2") name "val";
+     %feature(featurename, val, attrib1="attribval1", attrib2="attribval2") name;
+   ------------------------------------------------------------ */
+
+                  /* Non-global feature */
+feature_directive : FEATURE LPAREN idstring RPAREN declarator cpp_const stringbracesemi {
+                    String *val = $7 ? NewString($7) : NewString("1");
+                    new_feature($3, val, 0, $5.id, $5.type, $5.parms, $6.qualifier);
+                    $$ = 0;
+                  }
+                  | FEATURE LPAREN idstring COMMA stringnum RPAREN declarator cpp_const SEMI {
+                    String *val = Len($5) ? NewString($5) : 0;
+                    new_feature($3, val, 0, $7.id, $7.type, $7.parms, $8.qualifier);
+                    $$ = 0;
+                  }
+                  | FEATURE LPAREN idstring featattr RPAREN declarator cpp_const stringbracesemi {
+                    String *val = $8 ? NewString($8) : NewString("1");
+                    new_feature($3, val, $4, $6.id, $6.type, $6.parms, $7.qualifier);
+                    $$ = 0;
+                  }
+                  | FEATURE LPAREN idstring COMMA stringnum featattr RPAREN declarator cpp_const SEMI {
+                    String *val = Len($5) ? NewString($5) : 0;
+                    new_feature($3, val, $6, $8.id, $8.type, $8.parms, $9.qualifier);
+                    $$ = 0;
+                  }
+
+                  /* Global feature */
+                  | FEATURE LPAREN idstring RPAREN stringbracesemi {
+                    String *val = $5 ? NewString($5) : NewString("1");
+                    new_feature($3, val, 0, 0, 0, 0, 0);
+                    $$ = 0;
+                  }
+                  | FEATURE LPAREN idstring COMMA stringnum RPAREN SEMI {
+                    String *val = Len($5) ? NewString($5) : 0;
+                    new_feature($3, val, 0, 0, 0, 0, 0);
+                    $$ = 0;
+                  }
+                  | FEATURE LPAREN idstring featattr RPAREN stringbracesemi {
+                    String *val = $6 ? NewString($6) : NewString("1");
+                    new_feature($3, val, $4, 0, 0, 0, 0);
+                    $$ = 0;
+                  }
+                  | FEATURE LPAREN idstring COMMA stringnum featattr RPAREN SEMI {
+                    String *val = Len($5) ? NewString($5) : 0;
+                    new_feature($3, val, $6, 0, 0, 0, 0);
+                    $$ = 0;
+                  }
+                  ;
+
+stringbracesemi : stringbrace { $$ = $1; }
+                | SEMI { $$ = 0; }
+                | PARMS LPAREN parms RPAREN SEMI { $$ = $3; } 
+                ;
+
+featattr        : COMMA idstring EQUAL stringnum {
+		  $$ = NewHash();
+		  Setattr($$,"name",$2);
+		  Setattr($$,"value",$4);
+                }
+                | COMMA idstring EQUAL stringnum featattr {
+		  $$ = NewHash();
+		  Setattr($$,"name",$2);
+		  Setattr($$,"value",$4);
+                  set_nextSibling($$,$5);
+                }
+		;
+
+/* %varargs() directive. */
+
+varargs_directive : VARARGS LPAREN varargs_parms RPAREN declarator cpp_const SEMI {
+                 Parm *val;
+		 String *name;
+		 SwigType *t;
+		 if (Namespaceprefix) name = NewStringf("%s::%s", Namespaceprefix, $5.id);
+		 else name = NewString($5.id);
+		 val = $3;
+		 if ($5.parms) {
+		   Setmeta(val,"parms",$5.parms);
+		 }
+		 t = $5.type;
+		 if (!Len(t)) t = 0;
+		 if (t) {
+		   if ($6.qualifier) SwigType_push(t,$6.qualifier);
+		   if (SwigType_isfunction(t)) {
+		     SwigType *decl = SwigType_pop_function(t);
+		     if (SwigType_ispointer(t)) {
+		       String *nname = NewStringf("*%s",name);
+		       Swig_feature_set(Swig_cparse_features(), nname, decl, "feature:varargs", val, 0);
+		       Delete(nname);
+		     } else {
+		       Swig_feature_set(Swig_cparse_features(), name, decl, "feature:varargs", val, 0);
+		     }
+		     Delete(decl);
+		   } else if (SwigType_ispointer(t)) {
+		     String *nname = NewStringf("*%s",name);
+		     Swig_feature_set(Swig_cparse_features(),nname,0,"feature:varargs",val, 0);
+		     Delete(nname);
+		   }
+		 } else {
+		   Swig_feature_set(Swig_cparse_features(),name,0,"feature:varargs",val, 0);
+		 }
+		 Delete(name);
+		 $$ = 0;
+              };
+
+varargs_parms   : parms { $$ = $1; }
+                | NUM_INT COMMA parm { 
+		  int i;
+		  int n;
+		  Parm *p;
+		  n = atoi(Char($1.val));
+		  if (n <= 0) {
+		    Swig_error(cparse_file, cparse_line,"Argument count in %%varargs must be positive.\n");
+		    $$ = 0;
+		  } else {
+		    $$ = Copy($3);
+		    Setattr($$,"name","VARARGS_SENTINEL");
+		    for (i = 0; i < n; i++) {
+		      p = Copy($3);
+		      set_nextSibling(p,$$);
+		      Delete($$);
+		      $$ = p;
+		    }
+		  }
+                }
+               ;
+
+
+/* ------------------------------------------------------------
+   %typemap(method) type { ... }
+   %typemap(method) type "..."
+   %typemap(method) type;    - typemap deletion
+   %typemap(method) type1,type2,... = type;    - typemap copy
+   %typemap type1,type2,... = type;            - typemap copy
+   ------------------------------------------------------------ */
+
+typemap_directive :  TYPEMAP LPAREN typemap_type RPAREN tm_list stringbrace {
+		   $$ = 0;
+		   if ($3.op) {
+		     String *code = 0;
+		     $$ = new_node("typemap");
+		     Setattr($$,"method",$3.op);
+		     if ($3.kwargs) {
+		       ParmList *kw = $3.kwargs;
+                       code = remove_block(kw, $6);
+		       Setattr($$,"kwargs", $3.kwargs);
+		     }
+		     code = code ? code : NewString($6);
+		     Setattr($$,"code", code);
+		     Delete(code);
+		     appendChild($$,$5);
+		   }
+	       }
+               | TYPEMAP LPAREN typemap_type RPAREN tm_list SEMI {
+		 $$ = 0;
+		 if ($3.op) {
+		   $$ = new_node("typemap");
+		   Setattr($$,"method",$3.op);
+		   appendChild($$,$5);
+		 }
+	       }
+               | TYPEMAP LPAREN typemap_type RPAREN tm_list EQUAL typemap_parm SEMI {
+		   $$ = 0;
+		   if ($3.op) {
+		     $$ = new_node("typemapcopy");
+		     Setattr($$,"method",$3.op);
+		     Setattr($$,"pattern", Getattr($7,"pattern"));
+		     appendChild($$,$5);
+		   }
+	       }
+               ;
+
+/* typemap method type (lang,method) or (method) */
+
+typemap_type   : kwargs {
+		 Hash *p;
+		 String *name;
+		 p = nextSibling($1);
+		 if (p && (!Getattr(p,"value"))) {
+ 		   /* this is the deprecated two argument typemap form */
+ 		   Swig_warning(WARN_DEPRECATED_TYPEMAP_LANG,cparse_file, cparse_line,
+				"Specifying the language name in %%typemap is deprecated - use #ifdef SWIG<LANG> instead.\n");
+		   /* two argument typemap form */
+		   name = Getattr($1,"name");
+		   if (!name || (Strcmp(name,typemap_lang))) {
+		     $$.op = 0;
+		     $$.kwargs = 0;
+		   } else {
+		     $$.op = Getattr(p,"name");
+		     $$.kwargs = nextSibling(p);
+		   }
+		 } else {
+		   /* one-argument typemap-form */
+		   $$.op = Getattr($1,"name");
+		   $$.kwargs = p;
+		 }
+                }
+               ;
+
+tm_list        : typemap_parm tm_tail {
+                 $$ = $1;
+		 set_nextSibling($$,$2);
+		}
+               ;
+
+tm_tail        : COMMA typemap_parm tm_tail {
+                 $$ = $2;
+		 set_nextSibling($$,$3);
+                }
+               | empty { $$ = 0;}
+               ;
+
+typemap_parm   : type typemap_parameter_declarator {
+                  Parm *parm;
+		  SwigType_push($1,$2.type);
+		  $$ = new_node("typemapitem");
+		  parm = NewParm($1,$2.id);
+		  Setattr($$,"pattern",parm);
+		  Setattr($$,"parms", $2.parms);
+		  Delete(parm);
+		  /*		  $$ = NewParm($1,$2.id);
+				  Setattr($$,"parms",$2.parms); */
+                }
+               | LPAREN parms RPAREN {
+                  $$ = new_node("typemapitem");
+		  Setattr($$,"pattern",$2);
+		  /*		  Setattr($$,"multitype",$2); */
+               }
+               | LPAREN parms RPAREN LPAREN parms RPAREN {
+		 $$ = new_node("typemapitem");
+		 Setattr($$,"pattern", $2);
+		 /*                 Setattr($$,"multitype",$2); */
+		 Setattr($$,"parms",$5);
+               }
+               ;
+
+/* ------------------------------------------------------------
+   %types(parmlist); 
+   %types(parmlist) %{ ... %}
+   ------------------------------------------------------------ */
+
+types_directive : TYPES LPAREN parms RPAREN stringbracesemi {
+                   $$ = new_node("types");
+		   Setattr($$,"parms",$3);
+                   if ($5)
+		     Setattr($$,"convcode",NewString($5));
+               }
+               ;
+
+/* ------------------------------------------------------------
+   %template(name) tname<args>;
+   ------------------------------------------------------------ */
+
+template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN valparms GREATERTHAN SEMI {
+                  Parm *p, *tp;
+		  Node *n;
+		  Node *tnode = 0;
+		  Symtab *tscope = 0;
+		  int     specialized = 0;
+
+		  $$ = 0;
+
+		  tscope = Swig_symbol_current();          /* Get the current scope */
+
+		  /* If the class name is qualified, we need to create or lookup namespace entries */
+		  if (!inclass) {
+		    $5 = resolve_node_scope($5);
+		  }
+
+		  /*
+		    We use the new namespace entry 'nscope' only to
+		    emit the template node. The template parameters are
+		    resolved in the current 'tscope'.
+
+		    This is closer to the C++ (typedef) behavior.
+		  */
+		  n = Swig_cparse_template_locate($5,$7,tscope);
+
+		  /* Patch the argument types to respect namespaces */
+		  p = $7;
+		  while (p) {
+		    SwigType *value = Getattr(p,"value");
+		    if (!value) {
+		      SwigType *ty = Getattr(p,"type");
+		      if (ty) {
+			SwigType *rty = 0;
+			int reduce = template_reduce;
+			if (reduce || !SwigType_ispointer(ty)) {
+			  rty = Swig_symbol_typedef_reduce(ty,tscope);
+			  if (!reduce) reduce = SwigType_ispointer(rty);
+			}
+			ty = reduce ? Swig_symbol_type_qualify(rty,tscope) : Swig_symbol_type_qualify(ty,tscope);
+			Setattr(p,"type",ty);
+			Delete(ty);
+			Delete(rty);
+		      }
+		    } else {
+		      value = Swig_symbol_type_qualify(value,tscope);
+		      Setattr(p,"value",value);
+		      Delete(value);
+		    }
+
+		    p = nextSibling(p);
+		  }
+
+		  /* Look for the template */
+		  {
+                    Node *nn = n;
+                    Node *linklistend = 0;
+                    while (nn) {
+                      Node *templnode = 0;
+                      if (Strcmp(nodeType(nn),"template") == 0) {
+                        int nnisclass = (Strcmp(Getattr(nn,"templatetype"),"class") == 0); /* if not a templated class it is a templated function */
+                        Parm *tparms = Getattr(nn,"templateparms");
+                        if (!tparms) {
+                          specialized = 1;
+                        }
+                        if (nnisclass && !specialized && ((ParmList_len($7) > ParmList_len(tparms)))) {
+                          Swig_error(cparse_file, cparse_line, "Too many template parameters. Maximum of %d.\n", ParmList_len(tparms));
+                        } else if (nnisclass && !specialized && ((ParmList_len($7) < ParmList_numrequired(tparms)))) {
+                          Swig_error(cparse_file, cparse_line, "Not enough template parameters specified. %d required.\n", ParmList_numrequired(tparms));
+                        } else if (!nnisclass && ((ParmList_len($7) != ParmList_len(tparms)))) {
+                          /* must be an overloaded templated method - ignore it as it is overloaded with a different number of template parameters */
+                          nn = Getattr(nn,"sym:nextSibling"); /* repeat for overloaded templated functions */
+                          continue;
+                        } else {
+			  String *tname = Copy($5);
+                          int def_supplied = 0;
+                          /* Expand the template */
+			  Node *templ = Swig_symbol_clookup($5,0);
+			  Parm *targs = templ ? Getattr(templ,"templateparms") : 0;
+
+                          ParmList *temparms;
+                          if (specialized) temparms = CopyParmList($7);
+                          else temparms = CopyParmList(tparms);
+
+                          /* Create typedef's and arguments */
+                          p = $7;
+                          tp = temparms;
+                          if (!p && ParmList_len(p) != ParmList_len(temparms)) {
+                            /* we have no template parameters supplied in %template for a template that has default args*/
+                            p = tp;
+                            def_supplied = 1;
+                          }
+
+                          while (p) {
+                            String *value = Getattr(p,"value");
+                            if (def_supplied) {
+                              Setattr(p,"default","1");
+                            }
+                            if (value) {
+                              Setattr(tp,"value",value);
+                            } else {
+                              SwigType *ty = Getattr(p,"type");
+                              if (ty) {
+                                Setattr(tp,"type",ty);
+                              }
+                              Delattr(tp,"value");
+                            }
+			    /* fix default arg values */
+			    if (targs) {
+			      Parm *pi = temparms;
+			      Parm *ti = targs;
+			      String *tv = Getattr(tp,"value");
+			      if (!tv) tv = Getattr(tp,"type");
+			      while(pi != tp) {
+				String *name = Getattr(ti,"name");
+				String *value = Getattr(pi,"value");
+				if (!value) value = Getattr(pi,"type");
+				Replaceid(tv, name, value);
+				pi = nextSibling(pi);
+				ti = nextSibling(ti);
+			      }
+			    }
+                            p = nextSibling(p);
+                            tp = nextSibling(tp);
+                            if (!p && tp) {
+                              p = tp;
+                              def_supplied = 1;
+                            }
+                          }
+
+                          templnode = copy_node(nn);
+                          /* We need to set the node name based on name used to instantiate */
+                          Setattr(templnode,"name",tname);
+			  Delete(tname);
+                          if (!specialized) {
+                            Delattr(templnode,"sym:typename");
+                          } else {
+                            Setattr(templnode,"sym:typename","1");
+                          }
+                          if ($3) {
+			    /*
+			       Comment this out for 1.3.28. We need to
+			       re-enable it later but first we need to
+			       move %ignore from using %rename to use
+			       %feature(ignore).
+
+			       String *symname = Swig_name_make(templnode,0,$3,0,0);
+			    */
+			    String *symname = $3;
+                            Swig_cparse_template_expand(templnode,symname,temparms,tscope);
+                            Setattr(templnode,"sym:name",symname);
+                          } else {
+                            static int cnt = 0;
+                            String *nname = NewStringf("__dummy_%d__", cnt++);
+                            Swig_cparse_template_expand(templnode,nname,temparms,tscope);
+                            Setattr(templnode,"sym:name",nname);
+			    Delete(nname);
+                            Setattr(templnode,"feature:onlychildren",
+                                    "typemap,typemapitem,typemapcopy,typedef,types,fragment");
+                          }
+                          Delattr(templnode,"templatetype");
+                          Setattr(templnode,"template",nn);
+                          tnode = templnode;
+                          Setfile(templnode,cparse_file);
+                          Setline(templnode,cparse_line);
+                          Delete(temparms);
+
+                          add_symbols_copy(templnode);
+
+                          if (Strcmp(nodeType(templnode),"class") == 0) {
+
+                            /* Identify pure abstract methods */
+                            Setattr(templnode,"abstract", pure_abstract(firstChild(templnode)));
+
+                            /* Set up inheritance in symbol table */
+                            {
+                              Symtab  *csyms;
+                              List *baselist = Getattr(templnode,"baselist");
+                              csyms = Swig_symbol_current();
+                              Swig_symbol_setscope(Getattr(templnode,"symtab"));
+                              if (baselist) {
+                                List *bases = make_inherit_list(Getattr(templnode,"name"),baselist);
+                                if (bases) {
+                                  Iterator s;
+                                  for (s = First(bases); s.item; s = Next(s)) {
+                                    Symtab *st = Getattr(s.item,"symtab");
+                                    if (st) {
+				      Setfile(st,Getfile(s.item));
+				      Setline(st,Getline(s.item));
+                                      Swig_symbol_inherit(st);
+                                    }
+                                  }
+				  Delete(bases);
+                                }
+                              }
+                              Swig_symbol_setscope(csyms);
+                            }
+
+                            /* Merge in addmethods for this class */
+
+			    /* !!! This may be broken.  We may have to add the
+			       addmethods at the beginning of the class */
+
+                            if (extendhash) {
+                              String *stmp = 0;
+                              String *clsname;
+                              Node *am;
+                              if (Namespaceprefix) {
+                                clsname = stmp = NewStringf("%s::%s", Namespaceprefix, Getattr(templnode,"name"));
+                              } else {
+                                clsname = Getattr(templnode,"name");
+                              }
+                              am = Getattr(extendhash,clsname);
+                              if (am) {
+                                Symtab *st = Swig_symbol_current();
+                                Swig_symbol_setscope(Getattr(templnode,"symtab"));
+                                /*			    Printf(stdout,"%s: %s %x %x\n", Getattr(templnode,"name"), clsname, Swig_symbol_current(), Getattr(templnode,"symtab")); */
+                                merge_extensions(templnode,am);
+                                Swig_symbol_setscope(st);
+				append_previous_extension(templnode,am);
+                                Delattr(extendhash,clsname);
+                              }
+			      if (stmp) Delete(stmp);
+                            }
+                            /* Add to classes hash */
+                            if (!classes) classes = NewHash();
+
+                            {
+                              if (Namespaceprefix) {
+                                String *temp = NewStringf("%s::%s", Namespaceprefix, Getattr(templnode,"name"));
+                                Setattr(classes,temp,templnode);
+				Delete(temp);
+                              } else {
+				String *qs = Swig_symbol_qualifiedscopename(templnode);
+                                Setattr(classes, qs,templnode);
+				Delete(qs);
+                              }
+                            }
+                          }
+                        }
+
+                        /* all the overloaded templated functions are added into a linked list */
+                        if (nscope_inner) {
+                          /* non-global namespace */
+                          if (templnode) {
+                            appendChild(nscope_inner,templnode);
+			    Delete(templnode);
+                            if (nscope) $$ = nscope;
+                          }
+                        } else {
+                          /* global namespace */
+                          if (!linklistend) {
+                            $$ = templnode;
+                          } else {
+                            set_nextSibling(linklistend,templnode);
+			    Delete(templnode);
+                          }
+                          linklistend = templnode;
+                        }
+                      }
+                      nn = Getattr(nn,"sym:nextSibling"); /* repeat for overloaded templated functions. If a templated class there will never be a sibling. */
+                    }
+		  }
+	          Swig_symbol_setscope(tscope);
+		  Delete(Namespaceprefix);
+		  Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+                }
+               ;
+
+/* ------------------------------------------------------------
+   %warn "text"
+   %warn(no)
+   ------------------------------------------------------------ */
+
+warn_directive : WARN string {
+		  Swig_warning(0,cparse_file, cparse_line,"%s\n", $2);
+		  $$ = 0;
+               }
+               ;
+
+/* ======================================================================
+ *                              C Parsing
+ * ====================================================================== */
+
+c_declaration   : c_decl {
+                    $$ = $1; 
+                    if ($$) {
+   		      add_symbols($$);
+                      default_arguments($$);
+   	            }
+                }
+                | c_enum_decl { $$ = $1; }
+                | c_enum_forward_decl { $$ = $1; }
+
+/* An extern C type declaration, disable cparse_cplusplus if needed. */
+
+                | EXTERN string LBRACE {
+		  if (Strcmp($2,"C") == 0) {
+		    cparse_externc = 1;
+		  }
+		} interface RBRACE {
+		  cparse_externc = 0;
+		  if (Strcmp($2,"C") == 0) {
+		    Node *n = firstChild($5);
+		    $$ = new_node("extern");
+		    Setattr($$,"name",$2);
+		    appendChild($$,n);
+		    while (n) {
+		      SwigType *decl = Getattr(n,"decl");
+		      if (SwigType_isfunction(decl)) {
+			Setattr(n,"storage","externc");
+		      }
+		      n = nextSibling(n);
+		    }
+		  } else {
+		     Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2);
+		    $$ = new_node("extern");
+		    Setattr($$,"name",$2);
+		    appendChild($$,firstChild($5));
+		  }
+                }
+                ;
+
+/* ------------------------------------------------------------
+   A C global declaration of some kind (may be variable, function, typedef, etc.)
+   ------------------------------------------------------------ */
+
+c_decl  : storage_class type declarator initializer c_decl_tail {
+              $$ = new_node("cdecl");
+	      if ($4.qualifier) SwigType_push($3.type,$4.qualifier);
+	      Setattr($$,"type",$2);
+	      Setattr($$,"storage",$1);
+	      Setattr($$,"name",$3.id);
+	      Setattr($$,"decl",$3.type);
+	      Setattr($$,"parms",$3.parms);
+	      Setattr($$,"value",$4.val);
+	      Setattr($$,"throws",$4.throws);
+	      Setattr($$,"throw",$4.throwf);
+	      if (!$5) {
+		if (Len(scanner_ccode)) {
+		  String *code = Copy(scanner_ccode);
+		  Setattr($$,"code",code);
+		  Delete(code);
+		}
+	      } else {
+		Node *n = $5;
+		/* Inherit attributes */
+		while (n) {
+		  String *type = Copy($2);
+		  Setattr(n,"type",type);
+		  Setattr(n,"storage",$1);
+		  n = nextSibling(n);
+		  Delete(type);
+		}
+	      }
+	      if ($4.bitfield) {
+		Setattr($$,"bitfield", $4.bitfield);
+	      }
+
+	      /* Look for "::" declarations (ignored) */
+	      if (Strstr($3.id,"::")) {
+                /* This is a special case. If the scope name of the declaration exactly
+                   matches that of the declaration, then we will allow it. Otherwise, delete. */
+                String *p = Swig_scopename_prefix($3.id);
+		if (p) {
+		  if ((Namespaceprefix && Strcmp(p,Namespaceprefix) == 0) ||
+		      (inclass && Strcmp(p,Classprefix) == 0)) {
+		    String *lstr = Swig_scopename_last($3.id);
+		    Setattr($$,"name",lstr);
+		    Delete(lstr);
+		    set_nextSibling($$,$5);
+		  } else {
+		    Delete($$);
+		    $$ = $5;
+		  }
+		  Delete(p);
+		} else {
+		  Delete($$);
+		  $$ = $5;
+		}
+	      } else {
+		set_nextSibling($$,$5);
+	      }
+           }
+           ;
+
+/* Allow lists of variables and functions to be built up */
+
+c_decl_tail    : SEMI { 
+                   $$ = 0;
+                   Clear(scanner_ccode); 
+               }
+               | COMMA declarator initializer c_decl_tail {
+		 $$ = new_node("cdecl");
+		 if ($3.qualifier) SwigType_push($2.type,$3.qualifier);
+		 Setattr($$,"name",$2.id);
+		 Setattr($$,"decl",$2.type);
+		 Setattr($$,"parms",$2.parms);
+		 Setattr($$,"value",$3.val);
+		 Setattr($$,"throws",$3.throws);
+		 Setattr($$,"throw",$3.throwf);
+		 if ($3.bitfield) {
+		   Setattr($$,"bitfield", $3.bitfield);
+		 }
+		 if (!$4) {
+		   if (Len(scanner_ccode)) {
+		     String *code = Copy(scanner_ccode);
+		     Setattr($$,"code",code);
+		     Delete(code);
+		   }
+		 } else {
+		   set_nextSibling($$,$4);
+		 }
+	       }
+               | LBRACE { 
+                   skip_balanced('{','}');
+                   $$ = 0;
+               }
+              ;
+
+initializer   : def_args { 
+                   $$ = $1; 
+                   $$.qualifier = 0;
+		   $$.throws = 0;
+		   $$.throwf = 0;
+              }
+              | type_qualifier def_args { 
+                   $$ = $2; 
+		   $$.qualifier = $1;
+		   $$.throws = 0;
+		   $$.throwf = 0;
+	      }
+              | THROW LPAREN parms RPAREN def_args { 
+		   $$ = $5; 
+                   $$.qualifier = 0;
+		   $$.throws = $3;
+		   $$.throwf = NewString("1");
+              }
+              | type_qualifier THROW LPAREN parms RPAREN def_args { 
+                   $$ = $6; 
+                   $$.qualifier = $1;
+		   $$.throws = $4;
+		   $$.throwf = NewString("1");
+              }
+              ;
+
+
+/* ------------------------------------------------------------
+   enum Name;
+   ------------------------------------------------------------ */
+
+c_enum_forward_decl : storage_class ENUM ID SEMI {
+		   SwigType *ty = 0;
+		   $$ = new_node("enumforward");
+		   ty = NewStringf("enum %s", $3);
+		   Setattr($$,"name",$3);
+		   Setattr($$,"type",ty);
+		   Setattr($$,"sym:weak", "1");
+		   add_symbols($$);
+	      }
+              ;
+
+/* ------------------------------------------------------------
+   enum { ... }
+ * ------------------------------------------------------------ */
+
+c_enum_decl : storage_class ENUM ename LBRACE enumlist RBRACE SEMI {
+		  SwigType *ty = 0;
+                  $$ = new_node("enum");
+		  ty = NewStringf("enum %s", $3);
+		  Setattr($$,"name",$3);
+		  Setattr($$,"type",ty);
+		  appendChild($$,$5);
+		  add_symbols($$);       /* Add to tag space */
+		  add_symbols($5);       /* Add enum values to id space */
+               }
+               | storage_class ENUM ename LBRACE enumlist RBRACE declarator c_decl_tail {
+		 Node *n;
+		 SwigType *ty = 0;
+		 String   *unnamed = 0;
+		 int       unnamedinstance = 0;
+
+		 $$ = new_node("enum");
+		 if ($3) {
+		   Setattr($$,"name",$3);
+		   ty = NewStringf("enum %s", $3);
+		 } else if ($7.id) {
+		   unnamed = make_unnamed();
+		   ty = NewStringf("enum %s", unnamed);
+		   Setattr($$,"unnamed",unnamed);
+                   /* name is not set for unnamed enum instances, e.g. enum { foo } Instance; */
+		   if ($1 && Cmp($1,"typedef") == 0) {
+		     Setattr($$,"name",$7.id);
+                   } else {
+                     unnamedinstance = 1;
+                   }
+		   Setattr($$,"storage",$1);
+		 }
+		 if ($7.id && Cmp($1,"typedef") == 0) {
+		   Setattr($$,"tdname",$7.id);
+                   Setattr($$,"allows_typedef","1");
+                 }
+		 appendChild($$,$5);
+		 n = new_node("cdecl");
+		 Setattr(n,"type",ty);
+		 Setattr(n,"name",$7.id);
+		 Setattr(n,"storage",$1);
+		 Setattr(n,"decl",$7.type);
+		 Setattr(n,"parms",$7.parms);
+		 Setattr(n,"unnamed",unnamed);
+
+                 if (unnamedinstance) {
+		   SwigType *cty = NewString("enum ");
+		   Setattr($$,"type",cty);
+		   Setattr($$,"unnamedinstance","1");
+		   Setattr(n,"unnamedinstance","1");
+		   Delete(cty);
+                 }
+		 if ($8) {
+		   Node *p = $8;
+		   set_nextSibling(n,p);
+		   while (p) {
+		     SwigType *cty = Copy(ty);
+		     Setattr(p,"type",cty);
+		     Setattr(p,"unnamed",unnamed);
+		     Setattr(p,"storage",$1);
+		     Delete(cty);
+		     p = nextSibling(p);
+		   }
+		 } else {
+		   if (Len(scanner_ccode)) {
+		     String *code = Copy(scanner_ccode);
+		     Setattr(n,"code",code);
+		     Delete(code);
+		   }
+		 }
+
+                 /* Ensure that typedef enum ABC {foo} XYZ; uses XYZ for sym:name, like structs.
+                  * Note that class_rename/yyrename are bit of a mess so used this simple approach to change the name. */
+                 if ($7.id && $3 && Cmp($1,"typedef") == 0) {
+		   String *name = NewString($7.id);
+                   Setattr($$, "parser:makename", name);
+		   Delete(name);
+                 }
+
+		 add_symbols($$);       /* Add enum to tag space */
+		 set_nextSibling($$,n);
+		 Delete(n);
+		 add_symbols($5);       /* Add enum values to id space */
+	         add_symbols(n);
+		 Delete(unnamed);
+	       }
+               ;
+
+c_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end {
+                   /* This is a sick hack.  If the ctor_end has parameters,
+                      and the parms parameter only has 1 parameter, this
+                      could be a declaration of the form:
+
+                         type (id)(parms)
+
+			 Otherwise it's an error. */
+                    int err = 0;
+                    $$ = 0;
+
+		    if ((ParmList_len($4) == 1) && (!Swig_scopename_check($2))) {
+		      SwigType *ty = Getattr($4,"type");
+		      String *name = Getattr($4,"name");
+		      err = 1;
+		      if (!name) {
+			$$ = new_node("cdecl");
+			Setattr($$,"type",$2);
+			Setattr($$,"storage",$1);
+			Setattr($$,"name",ty);
+
+			if ($6.have_parms) {
+			  SwigType *decl = NewStringEmpty();
+			  SwigType_add_function(decl,$6.parms);
+			  Setattr($$,"decl",decl);
+			  Setattr($$,"parms",$6.parms);
+			  if (Len(scanner_ccode)) {
+			    String *code = Copy(scanner_ccode);
+			    Setattr($$,"code",code);
+			    Delete(code);
+			  }
+			}
+			if ($6.defarg) {
+			  Setattr($$,"value",$6.defarg);
+			}
+			Setattr($$,"throws",$6.throws);
+			Setattr($$,"throw",$6.throwf);
+			err = 0;
+		      }
+		    }
+		    if (err) {
+		      Swig_error(cparse_file,cparse_line,"Syntax error in input(2).\n");
+		      exit(1);
+		    }
+                }
+                ;
+
+/* ======================================================================
+ *                       C++ Support
+ * ====================================================================== */
+
+cpp_declaration : cpp_class_decl {  $$ = $1; }
+                | cpp_forward_class_decl { $$ = $1; }
+                | cpp_template_decl { $$ = $1; }
+                | cpp_using_decl { $$ = $1; }
+                | cpp_namespace_decl { $$ = $1; }
+                | cpp_catch_decl { $$ = 0; }
+                ;
+
+cpp_class_decl  :
+
+/* A simple class/struct/union definition */
+                storage_class cpptype idcolon inherit LBRACE {
+                   List *bases = 0;
+		   Node *scope = 0;
+		   $$ = new_node("class");
+		   Setline($$,cparse_start_line);
+		   Setattr($$,"kind",$2);
+		   if ($4) {
+		     Setattr($$,"baselist", Getattr($4,"public"));
+		     Setattr($$,"protectedbaselist", Getattr($4,"protected"));
+		     Setattr($$,"privatebaselist", Getattr($4,"private"));
+		   }
+		   Setattr($$,"allows_typedef","1");
+
+		   /* preserve the current scope */
+		   prev_symtab = Swig_symbol_current();
+		  
+		   /* If the class name is qualified.  We need to create or lookup namespace/scope entries */
+		   scope = resolve_node_scope($3);
+		   Setfile(scope,cparse_file);
+		   Setline(scope,cparse_line);
+		   $3 = scope;
+		   
+		   /* support for old nested classes "pseudo" support, such as:
+
+		         %rename(Ala__Ola) Ala::Ola;
+			class Ala::Ola {
+			public:
+			    Ola() {}
+		         };
+
+		      this should disappear when a proper implementation is added.
+		   */
+		   if (nscope_inner && Strcmp(nodeType(nscope_inner),"namespace") != 0) {
+		     if (Namespaceprefix) {
+		       String *name = NewStringf("%s::%s", Namespaceprefix, $3);		       
+		       $3 = name;
+		       Namespaceprefix = 0;
+		       nscope_inner = 0;
+		     }
+		   }
+		   Setattr($$,"name",$3);
+
+		   Delete(class_rename);
+                   class_rename = make_name($$,$3,0);
+		   Classprefix = NewString($3);
+		   /* Deal with inheritance  */
+		   if ($4) {
+		     bases = make_inherit_list($3,Getattr($4,"public"));
+		   }
+		   if (SwigType_istemplate($3)) {
+		     String *fbase, *tbase, *prefix;
+		     prefix = SwigType_templateprefix($3);
+		     if (Namespaceprefix) {
+		       fbase = NewStringf("%s::%s", Namespaceprefix,$3);
+		       tbase = NewStringf("%s::%s", Namespaceprefix, prefix);
+		     } else {
+		       fbase = Copy($3);
+		       tbase = Copy(prefix);
+		     }
+		     Swig_name_inherit(tbase,fbase);
+		     Delete(fbase);
+		     Delete(tbase);
+		     Delete(prefix);
+		   }
+                   if (strcmp($2,"class") == 0) {
+		     cplus_mode = CPLUS_PRIVATE;
+		   } else {
+		     cplus_mode = CPLUS_PUBLIC;
+		   }
+		   Swig_symbol_newscope();
+		   Swig_symbol_setscopename($3);
+		   if (bases) {
+		     Iterator s;
+		     for (s = First(bases); s.item; s = Next(s)) {
+		       Symtab *st = Getattr(s.item,"symtab");
+		       if (st) {
+			 Setfile(st,Getfile(s.item));
+			 Setline(st,Getline(s.item));
+			 Swig_symbol_inherit(st); 
+		       }
+		     }
+		     Delete(bases);
+		   }
+		   Delete(Namespaceprefix);
+		   Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+		   cparse_start_line = cparse_line;
+
+		   /* If there are active template parameters, we need to make sure they are
+                      placed in the class symbol table so we can catch shadows */
+
+		   if (template_parameters) {
+		     Parm *tp = template_parameters;
+		     while(tp) {
+		       String *tpname = Copy(Getattr(tp,"name"));
+		       Node *tn = new_node("templateparm");
+		       Setattr(tn,"name",tpname);
+		       Swig_symbol_cadd(tpname,tn);
+		       tp = nextSibling(tp);
+		       Delete(tpname);
+		     }
+		   }
+		   if (class_level >= max_class_levels) {
+		       if (!max_class_levels) {
+			   max_class_levels = 16;
+		       } else {
+			   max_class_levels *= 2;
+		       }
+		       class_decl = realloc(class_decl, sizeof(Node*) * max_class_levels);
+		       if (!class_decl) {
+			   Swig_error(cparse_file, cparse_line, "realloc() failed\n");
+		       }
+		   }
+		   class_decl[class_level++] = $$;
+		   inclass = 1;
+               } cpp_members RBRACE cpp_opt_declarators {
+		 Node *p;
+		 SwigType *ty;
+		 Symtab *cscope = prev_symtab;
+		 Node *am = 0;
+		 String *scpname = 0;
+		 $$ = class_decl[--class_level];
+		 inclass = 0;
+		 
+		 /* Check for pure-abstract class */
+		 Setattr($$,"abstract", pure_abstract($7));
+		 
+		 /* This bit of code merges in a previously defined %extend directive (if any) */
+		 
+		 if (extendhash) {
+		   String *clsname = Swig_symbol_qualifiedscopename(0);
+		   am = Getattr(extendhash,clsname);
+		   if (am) {
+		     merge_extensions($$,am);
+		     Delattr(extendhash,clsname);
+		   }
+		   Delete(clsname);
+		 }
+		 if (!classes) classes = NewHash();
+		 scpname = Swig_symbol_qualifiedscopename(0);
+		 Setattr(classes,scpname,$$);
+		 Delete(scpname);
+
+		 appendChild($$,$7);
+		 
+		 if (am) append_previous_extension($$,am);
+
+		 p = $9;
+		 if (p) {
+		   set_nextSibling($$,p);
+		 }
+		 
+		 if (cparse_cplusplus && !cparse_externc) {
+		   ty = NewString($3);
+		 } else {
+		   ty = NewStringf("%s %s", $2,$3);
+		 }
+		 while (p) {
+		   Setattr(p,"storage",$1);
+		   Setattr(p,"type",ty);
+		   p = nextSibling(p);
+		 }
+		 /* Dump nested classes */
+		 {
+		   String *name = $3;
+		   if ($9) {
+		     SwigType *decltype = Getattr($9,"decl");
+		     if (Cmp($1,"typedef") == 0) {
+		       if (!decltype || !Len(decltype)) {
+			 String *cname;
+			 name = Getattr($9,"name");
+			 cname = Copy(name);
+			 Setattr($$,"tdname",cname);
+			 Delete(cname);
+
+			 /* Use typedef name as class name */
+			 if (class_rename && (Strcmp(class_rename,$3) == 0)) {
+			   Delete(class_rename);
+			   class_rename = NewString(name);
+			 }
+			 if (!Getattr(classes,name)) {
+			   Setattr(classes,name,$$);
+			 }
+			 Setattr($$,"decl",decltype);
+		       }
+		     }
+		   }
+		   appendChild($$,dump_nested(Char(name)));
+		 }
+
+		 if (cplus_mode != CPLUS_PUBLIC) {
+		 /* we 'open' the class at the end, to allow %template
+		    to add new members */
+		   Node *pa = new_node("access");
+		   Setattr(pa,"kind","public");
+		   cplus_mode = CPLUS_PUBLIC;
+		   appendChild($$,pa);
+		   Delete(pa);
+		 }
+
+		 Setattr($$,"symtab",Swig_symbol_popscope());
+
+		 Classprefix = 0;
+		 if (nscope_inner) {
+		   /* this is tricky */
+		   /* we add the declaration in the original namespace */
+		   appendChild(nscope_inner,$$);
+		   Swig_symbol_setscope(Getattr(nscope_inner,"symtab"));
+		   Delete(Namespaceprefix);
+		   Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+		   add_symbols($$);
+		   if (nscope) $$ = nscope;
+		   /* but the variable definition in the current scope */
+		   Swig_symbol_setscope(cscope);
+		   Delete(Namespaceprefix);
+		   Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+		   add_symbols($9);
+		 } else {
+		   Delete(yyrename);
+		   yyrename = Copy(class_rename);
+		   Delete(Namespaceprefix);
+		   Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+
+		   add_symbols($$);
+		   add_symbols($9);
+		 }
+		 Swig_symbol_setscope(cscope);
+		 Delete(Namespaceprefix);
+		 Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+	       }
+
+/* An unnamed struct, possibly with a typedef */
+
+             | storage_class cpptype LBRACE {
+	       String *unnamed;
+	       unnamed = make_unnamed();
+	       $$ = new_node("class");
+	       Setline($$,cparse_start_line);
+	       Setattr($$,"kind",$2);
+	       Setattr($$,"storage",$1);
+	       Setattr($$,"unnamed",unnamed);
+	       Setattr($$,"allows_typedef","1");
+	       Delete(class_rename);
+	       class_rename = make_name($$,0,0);
+	       if (strcmp($2,"class") == 0) {
+		 cplus_mode = CPLUS_PRIVATE;
+	       } else {
+		 cplus_mode = CPLUS_PUBLIC;
+	       }
+	       Swig_symbol_newscope();
+	       cparse_start_line = cparse_line;
+	       if (class_level >= max_class_levels) {
+		   if (!max_class_levels) {
+		       max_class_levels = 16;
+		   } else {
+		       max_class_levels *= 2;
+		   }
+		   class_decl = realloc(class_decl, sizeof(Node*) * max_class_levels);
+		   if (!class_decl) {
+		       Swig_error(cparse_file, cparse_line, "realloc() failed\n");
+		   }
+	       }
+	       class_decl[class_level++] = $$;
+	       inclass = 1;
+	       Classprefix = NewStringEmpty();
+	       Delete(Namespaceprefix);
+	       Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+             } cpp_members RBRACE declarator c_decl_tail {
+	       String *unnamed;
+	       Node *n;
+	       Classprefix = 0;
+	       $$ = class_decl[--class_level];
+	       inclass = 0;
+	       unnamed = Getattr($$,"unnamed");
+
+	       /* Check for pure-abstract class */
+	       Setattr($$,"abstract", pure_abstract($5));
+
+	       n = new_node("cdecl");
+	       Setattr(n,"name",$7.id);
+	       Setattr(n,"unnamed",unnamed);
+	       Setattr(n,"type",unnamed);
+	       Setattr(n,"decl",$7.type);
+	       Setattr(n,"parms",$7.parms);
+	       Setattr(n,"storage",$1);
+	       if ($8) {
+		 Node *p = $8;
+		 set_nextSibling(n,p);
+		 while (p) {
+		   String *type = Copy(unnamed);
+		   Setattr(p,"name",$7.id);
+		   Setattr(p,"unnamed",unnamed);
+		   Setattr(p,"type",type);
+		   Delete(type);
+		   Setattr(p,"storage",$1);
+		   p = nextSibling(p);
+		 }
+	       }
+	       set_nextSibling($$,n);
+	       Delete(n);
+	       {
+		 /* If a proper typedef name was given, we'll use it to set the scope name */
+		 String *name = 0;
+		 if ($1 && (strcmp($1,"typedef") == 0)) {
+		   if (!Len($7.type)) {	
+		     String *scpname = 0;
+		     name = $7.id;
+		     Setattr($$,"tdname",name);
+		     Setattr($$,"name",name);
+		     Swig_symbol_setscopename(name);
+
+		     /* If a proper name was given, we use that as the typedef, not unnamed */
+		     Clear(unnamed);
+		     Append(unnamed, name);
+		     
+		     n = nextSibling(n);
+		     set_nextSibling($$,n);
+
+		     /* Check for previous extensions */
+		     if (extendhash) {
+		       String *clsname = Swig_symbol_qualifiedscopename(0);
+		       Node *am = Getattr(extendhash,clsname);
+		       if (am) {
+			 /* Merge the extension into the symbol table */
+			 merge_extensions($$,am);
+			 append_previous_extension($$,am);
+			 Delattr(extendhash,clsname);
+		       }
+		       Delete(clsname);
+		     }
+		     if (!classes) classes = NewHash();
+		     scpname = Swig_symbol_qualifiedscopename(0);
+		     Setattr(classes,scpname,$$);
+		     Delete(scpname);
+		   } else {
+		     Swig_symbol_setscopename((char*)"<unnamed>");
+		   }
+		 }
+		 appendChild($$,$5);
+		 appendChild($$,dump_nested(Char(name)));
+	       }
+	       /* Pop the scope */
+	       Setattr($$,"symtab",Swig_symbol_popscope());
+	       if (class_rename) {
+		 Delete(yyrename);
+		 yyrename = NewString(class_rename);
+	       }
+	       Delete(Namespaceprefix);
+	       Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+	       add_symbols($$);
+	       add_symbols(n);
+	       Delete(unnamed);
+              }
+             ;
+
+cpp_opt_declarators :  SEMI { $$ = 0; }
+                    |  declarator c_decl_tail {
+                        $$ = new_node("cdecl");
+                        Setattr($$,"name",$1.id);
+                        Setattr($$,"decl",$1.type);
+                        Setattr($$,"parms",$1.parms);
+			set_nextSibling($$,$2);
+                    }
+                    ;
+/* ------------------------------------------------------------
+   class Name;
+   ------------------------------------------------------------ */
+
+cpp_forward_class_decl : storage_class cpptype idcolon SEMI {
+              if ($1 && (Strcmp($1,"friend") == 0)) {
+		/* Ignore */
+                $$ = 0; 
+	      } else {
+		$$ = new_node("classforward");
+		Setfile($$,cparse_file);
+		Setline($$,cparse_line);
+		Setattr($$,"kind",$2);
+		Setattr($$,"name",$3);
+		Setattr($$,"sym:weak", "1");
+		add_symbols($$);
+	      }
+             }
+             ;
+
+/* ------------------------------------------------------------
+   template<...> decl
+   ------------------------------------------------------------ */
+
+cpp_template_decl : TEMPLATE LESSTHAN template_parms GREATERTHAN { template_parameters = $3; } cpp_temp_possible {
+		      String *tname = 0;
+		      int     error = 0;
+
+		      /* check if we get a namespace node with a class declaration, and retrieve the class */
+		      Symtab *cscope = Swig_symbol_current();
+		      Symtab *sti = 0;
+		      Node *ntop = $6;
+		      Node *ni = ntop;
+		      SwigType *ntype = ni ? nodeType(ni) : 0;
+		      while (ni && Strcmp(ntype,"namespace") == 0) {
+			sti = Getattr(ni,"symtab");
+			ni = firstChild(ni);
+			ntype = nodeType(ni);
+		      }
+		      if (sti) {
+			Swig_symbol_setscope(sti);
+			Delete(Namespaceprefix);
+			Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+			$6 = ni;
+		      }
+
+                      template_parameters = 0;
+                      $$ = $6;
+		      if ($$) tname = Getattr($$,"name");
+		      
+		      /* Check if the class is a template specialization */
+		      if (($$) && (Strchr(tname,'<')) && (!is_operator(tname))) {
+			/* If a specialization.  Check if defined. */
+			Node *tempn = 0;
+			{
+			  String *tbase = SwigType_templateprefix(tname);
+			  tempn = Swig_symbol_clookup_local(tbase,0);
+			  if (!tempn || (Strcmp(nodeType(tempn),"template") != 0)) {
+			    SWIG_WARN_NODE_BEGIN(tempn);
+			    Swig_warning(WARN_PARSE_TEMPLATE_SP_UNDEF, Getfile($$),Getline($$),"Specialization of non-template '%s'.\n", tbase);
+			    SWIG_WARN_NODE_END(tempn);
+			    tempn = 0;
+			    error = 1;
+			  }
+			  Delete(tbase);
+			}
+			Setattr($$,"specialization","1");
+			Setattr($$,"templatetype",nodeType($$));
+			set_nodeType($$,"template");
+			/* Template partial specialization */
+			if (tempn && ($3) && ($6)) {
+			  List   *tlist;
+			  String *targs = SwigType_templateargs(tname);
+			  tlist = SwigType_parmlist(targs);
+			  /*			  Printf(stdout,"targs = '%s' %s\n", targs, tlist); */
+			  if (!Getattr($$,"sym:weak")) {
+			    Setattr($$,"sym:typename","1");
+			  }
+			  
+			  if (Len(tlist) != ParmList_len(Getattr(tempn,"templateparms"))) {
+			    Swig_error(Getfile($$),Getline($$),"Inconsistent argument count in template partial specialization. %d %d\n", Len(tlist), ParmList_len(Getattr(tempn,"templateparms")));
+			    
+			  } else {
+
+			  /* This code builds the argument list for the partial template
+                             specialization.  This is a little hairy, but the idea is as
+                             follows:
+
+                             $3 contains a list of arguments supplied for the template.
+                             For example template<class T>.
+
+                             tlist is a list of the specialization arguments--which may be
+                             different.  For example class<int,T>.
+
+                             tp is a copy of the arguments in the original template definition.
+     
+                             The patching algorithm walks through the list of supplied
+                             arguments ($3), finds the position in the specialization arguments
+                             (tlist), and then patches the name in the argument list of the
+                             original template.
+			  */
+
+			  {
+			    String *pn;
+			    Parm *p, *p1;
+			    int i, nargs;
+			    Parm *tp = CopyParmList(Getattr(tempn,"templateparms"));
+			    nargs = Len(tlist);
+			    p = $3;
+			    while (p) {
+			      for (i = 0; i < nargs; i++){
+				pn = Getattr(p,"name");
+				if (Strcmp(pn,SwigType_base(Getitem(tlist,i))) == 0) {
+				  int j;
+				  Parm *p1 = tp;
+				  for (j = 0; j < i; j++) {
+				    p1 = nextSibling(p1);
+				  }
+				  Setattr(p1,"name",pn);
+				  Setattr(p1,"partialarg","1");
+				}
+			      }
+			      p = nextSibling(p);
+			    }
+			    p1 = tp;
+			    i = 0;
+			    while (p1) {
+			      if (!Getattr(p1,"partialarg")) {
+				Delattr(p1,"name");
+				Setattr(p1,"type", Getitem(tlist,i));
+			      } 
+			      i++;
+			      p1 = nextSibling(p1);
+			    }
+			    Setattr($$,"templateparms",tp);
+			    Delete(tp);
+			  }
+#if 0
+			  /* Patch the parameter list */
+			  if (tempn) {
+			    Parm *p,*p1;
+			    ParmList *tp = CopyParmList(Getattr(tempn,"templateparms"));
+			    p = $3;
+			    p1 = tp;
+			    while (p && p1) {
+			      String *pn = Getattr(p,"name");
+			      Printf(stdout,"pn = '%s'\n", pn);
+			      if (pn) Setattr(p1,"name",pn);
+			      else Delattr(p1,"name");
+			      pn = Getattr(p,"type");
+			      if (pn) Setattr(p1,"type",pn);
+			      p = nextSibling(p);
+			      p1 = nextSibling(p1);
+			    }
+			    Setattr($$,"templateparms",tp);
+			    Delete(tp);
+			  } else {
+			    Setattr($$,"templateparms",$3);
+			  }
+#endif
+			  Delattr($$,"specialization");
+			  Setattr($$,"partialspecialization","1");
+			  /* Create a specialized name for matching */
+			  {
+			    Parm *p = $3;
+			    String *fname = NewString(Getattr($$,"name"));
+			    String *ffname = 0;
+
+			    char   tmp[32];
+			    int    i, ilen;
+			    while (p) {
+			      String *n = Getattr(p,"name");
+			      if (!n) {
+				p = nextSibling(p);
+				continue;
+			      }
+			      ilen = Len(tlist);
+			      for (i = 0; i < ilen; i++) {
+				if (Strstr(Getitem(tlist,i),n)) {
+				  sprintf(tmp,"$%d",i+1);
+				  Replaceid(fname,n,tmp);
+				}
+			      }
+			      p = nextSibling(p);
+			    }
+			    /* Patch argument names with typedef */
+			    {
+			      Iterator tt;
+			      List *tparms = SwigType_parmlist(fname);
+			      ffname = SwigType_templateprefix(fname);
+			      Append(ffname,"<(");
+			      for (tt = First(tparms); tt.item; ) {
+				SwigType *rtt = Swig_symbol_typedef_reduce(tt.item,0);
+				SwigType *ttr = Swig_symbol_type_qualify(rtt,0);
+				Append(ffname,ttr);
+				tt = Next(tt);
+				if (tt.item) Putc(',',ffname);
+				Delete(rtt);
+				Delete(ttr);
+			      }
+			      Delete(tparms);
+			      Append(ffname,")>");
+			    }
+			    {
+			      String *partials = Getattr(tempn,"partials");
+			      if (!partials) {
+				partials = NewList();
+				Setattr(tempn,"partials",partials);
+				Delete(partials);
+			      }
+			      /*			      Printf(stdout,"partial: fname = '%s', '%s'\n", fname, Swig_symbol_typedef_reduce(fname,0)); */
+			      Append(partials,ffname);
+			    }
+			    Setattr($$,"partialargs",ffname);
+			    Swig_symbol_cadd(ffname,$$);
+			  }
+			  }
+			  Delete(tlist);
+			  Delete(targs);
+			} else {
+			  /* Need to resolve exact specialization name */
+			  /* add default args from generic template */
+			  String *ty = Swig_symbol_template_deftype(tname,0);
+			  String *fname = Swig_symbol_type_qualify(ty,0);
+			  Swig_symbol_cadd(fname,$$);
+			  Delete(ty);
+			  Delete(fname);
+			}
+		      }  else if ($$) {
+			Setattr($$,"templatetype",nodeType($6));
+			set_nodeType($$,"template");
+			Setattr($$,"templateparms", $3);
+			if (!Getattr($$,"sym:weak")) {
+			  Setattr($$,"sym:typename","1");
+			}
+			add_symbols($$);
+                        default_arguments($$);
+			/* We also place a fully parameterized version in the symbol table */
+			{
+			  Parm *p;
+			  String *fname = NewStringf("%s<(", Getattr($$,"name"));
+			  p = $3;
+			  while (p) {
+			    String *n = Getattr(p,"name");
+			    if (!n) n = Getattr(p,"type");
+			    Append(fname,n);
+			    p = nextSibling(p);
+			    if (p) Putc(',',fname);
+			  }
+			  Append(fname,")>");
+			  Swig_symbol_cadd(fname,$$);
+			}
+		      }
+		      $$ = ntop;
+		      Swig_symbol_setscope(cscope);
+		      Delete(Namespaceprefix);
+		      Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+		      if (error) $$ = 0;
+                  }
+                | TEMPLATE cpptype idcolon {
+		  Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n");
+                   $$ = 0; 
+                }
+                ;
+
+cpp_temp_possible:  c_decl {
+		  $$ = $1;
+                }
+                | cpp_class_decl {
+                   $$ = $1;
+                }
+                | cpp_constructor_decl {
+                   $$ = $1;
+                }
+                | cpp_template_decl {
+		  $$ = 0;
+                }
+                | cpp_forward_class_decl {
+                  $$ = $1;
+                }
+                | cpp_conversion_operator {
+                  $$ = $1;
+                }
+                ;
+
+template_parms  : templateparameters {
+		   /* Rip out the parameter names */
+		  Parm *p = $1;
+		  $$ = $1;
+
+		  while (p) {
+		    String *name = Getattr(p,"name");
+		    if (!name) {
+		      /* Hmmm. Maybe it's a 'class T' parameter */
+		      char *type = Char(Getattr(p,"type"));
+		      /* Template template parameter */
+		      if (strncmp(type,"template<class> ",16) == 0) {
+			type += 16;
+		      }
+		      if ((strncmp(type,"class ",6) == 0) || (strncmp(type,"typename ", 9) == 0)) {
+			char *t = strchr(type,' ');
+			Setattr(p,"name", t+1);
+		      } else {
+			/*
+			 Swig_error(cparse_file, cparse_line, "Missing template parameter name\n");
+			 $$.rparms = 0;
+			 $$.parms = 0;
+			 break; */
+		      }
+		    }
+		    p = nextSibling(p);
+		  }
+                 }
+                 ;
+
+templateparameters : templateparameter templateparameterstail {
+                      set_nextSibling($1,$2);
+                      $$ = $1;
+                   }
+                   | empty { $$ = 0; }
+                   ;
+
+templateparameter : templcpptype {
+		    $$ = NewParm(NewString($1), 0);
+                  }
+                  | parm {
+                    $$ = $1;
+                  }
+                  ;
+
+templateparameterstail : COMMA templateparameter templateparameterstail {
+                         set_nextSibling($2,$3);
+                         $$ = $2;
+                       }
+                       | empty { $$ = 0; }
+                       ;
+
+/* Namespace support */
+
+cpp_using_decl : USING idcolon SEMI {
+                  String *uname = Swig_symbol_type_qualify($2,0);
+		  String *name = Swig_scopename_last($2);
+                  $$ = new_node("using");
+		  Setattr($$,"uname",uname);
+		  Setattr($$,"name", name);
+		  Delete(uname);
+		  Delete(name);
+		  add_symbols($$);
+             }
+             | USING NAMESPACE idcolon SEMI {
+	       Node *n = Swig_symbol_clookup($3,0);
+	       if (!n) {
+		 Swig_error(cparse_file, cparse_line, "Nothing known about namespace '%s'\n", $3);
+		 $$ = 0;
+	       } else {
+
+		 while (Strcmp(nodeType(n),"using") == 0) {
+		   n = Getattr(n,"node");
+		 }
+		 if (n) {
+		   if (Strcmp(nodeType(n),"namespace") == 0) {
+		     Symtab *current = Swig_symbol_current();
+		     Symtab *symtab = Getattr(n,"symtab");
+		     $$ = new_node("using");
+		     Setattr($$,"node",n);
+		     Setattr($$,"namespace", $3);
+		     if (current != symtab) {
+		       Swig_symbol_inherit(symtab);
+		     }
+		   } else {
+		     Swig_error(cparse_file, cparse_line, "'%s' is not a namespace.\n", $3);
+		     $$ = 0;
+		   }
+		 } else {
+		   $$ = 0;
+		 }
+	       }
+             }
+             ;
+
+cpp_namespace_decl : NAMESPACE idcolon LBRACE { 
+                Hash *h;
+                $1 = Swig_symbol_current();
+		h = Swig_symbol_clookup($2,0);
+		if (h && ($1 == Getattr(h,"sym:symtab")) && (Strcmp(nodeType(h),"namespace") == 0)) {
+		  if (Getattr(h,"alias")) {
+		    h = Getattr(h,"namespace");
+		    Swig_warning(WARN_PARSE_NAMESPACE_ALIAS, cparse_file, cparse_line, "Namespace alias '%s' not allowed here. Assuming '%s'\n",
+				 $2, Getattr(h,"name"));
+		    $2 = Getattr(h,"name");
+		  }
+		  Swig_symbol_setscope(Getattr(h,"symtab"));
+		} else {
+		  Swig_symbol_newscope();
+		  Swig_symbol_setscopename($2);
+		}
+		Delete(Namespaceprefix);
+		Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+             } interface RBRACE {
+                Node *n = $5;
+		set_nodeType(n,"namespace");
+		Setattr(n,"name",$2);
+                Setattr(n,"symtab", Swig_symbol_popscope());
+		Swig_symbol_setscope($1);
+		$$ = n;
+		Delete(Namespaceprefix);
+		Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+		add_symbols($$);
+             } 
+             | NAMESPACE LBRACE {
+	       Hash *h;
+	       $1 = Swig_symbol_current();
+	       h = Swig_symbol_clookup((char *)"    ",0);
+	       if (h && (Strcmp(nodeType(h),"namespace") == 0)) {
+		 Swig_symbol_setscope(Getattr(h,"symtab"));
+	       } else {
+		 Swig_symbol_newscope();
+		 /* we don't use "__unnamed__", but a long 'empty' name */
+		 Swig_symbol_setscopename("    ");
+	       }
+	       Namespaceprefix = 0;
+             } interface RBRACE {
+	       $$ = $4;
+	       set_nodeType($$,"namespace");
+	       Setattr($$,"unnamed","1");
+	       Setattr($$,"symtab", Swig_symbol_popscope());
+	       Swig_symbol_setscope($1);
+	       Delete(Namespaceprefix);
+	       Namespaceprefix = Swig_symbol_qualifiedscopename(0);
+	       add_symbols($$);
+             }
+             | NAMESPACE ID EQUAL idcolon SEMI {
+	       /* Namespace alias */
+	       Node *n;
+	       $$ = new_node("namespace");
+	       Setattr($$,"name",$2);
+	       Setattr($$,"alias",$4);
+	       n = Swig_symbol_clookup($4,0);
+	       if (!n) {
+		 Swig_error(cparse_file, cparse_line, "Unknown namespace '%s'\n", $4);
+		 $$ = 0;
+	       } else {
+		 if (Strcmp(nodeType(n),"namespace") != 0) {
+		   Swig_error(cparse_file, cparse_line, "'%s' is not a namespace\n",$4);
+		   $$ = 0;
+		 } else {
+		   while (Getattr(n,"alias")) {
+		     n = Getattr(n,"namespace");
+		   }
+		   Setattr($$,"namespace",n);
+		   add_symbols($$);
+		   /* Set up a scope alias */
+		   Swig_symbol_alias($2,Getattr(n,"symtab"));
+		 }
+	       }
+             }
+             ;
+
+cpp_members  : cpp_member cpp_members {
+                   $$ = $1;
+                   /* Insert cpp_member (including any siblings) to the front of the cpp_members linked list */
+		   if ($$) {
+		     Node *p = $$;
+		     Node *pp =0;
+		     while (p) {
+		       pp = p;
+		       p = nextSibling(p);
+		     }
+		     set_nextSibling(pp,$2);
+		   } else {
+		     $$ = $2;
+		   }
+             }
+             | EXTEND LBRACE { 
+                  if (cplus_mode != CPLUS_PUBLIC) {
+		     Swig_error(cparse_file,cparse_line,"%%extend can only be used in a public section\n");
+		  }
+             } cpp_members RBRACE cpp_members {
+	       $$ = new_node("extend");
+	       tag_nodes($4,"feature:extend",(char*) "1");
+	       appendChild($$,$4);
+	       set_nextSibling($$,$6);
+	     }
+             | include_directive { $$ = $1; }
+             | empty { $$ = 0;}
+	     | error {
+	       int start_line = cparse_line;
+	       skip_decl();
+	       Swig_error(cparse_file,start_line,"Syntax error in input(3).\n");
+	       exit(1);
+	       } cpp_members { 
+		 $$ = $3;
+   	     }
+             ;
+
+/* ======================================================================
+ *                         C++ Class members
+ * ====================================================================== */
+
+/* A class member.  May be data or a function. Static or virtual as well */
+
+cpp_member   : c_declaration { $$ = $1; }
+             | cpp_constructor_decl { 
+                 $$ = $1; 
+		 if (extendmode) {
+		   String *symname;
+		   symname= make_name($$,Getattr($$,"name"), Getattr($$,"decl"));
+		   if (Strcmp(symname,Getattr($$,"name")) == 0) {
+		     /* No renaming operation.  Set name to class name */
+		     Delete(yyrename);
+		     yyrename = NewString(Getattr(current_class,"sym:name"));
+		   } else {
+		     Delete(yyrename);
+		     yyrename = symname;
+		   }
+		 }
+		 add_symbols($$);
+                 default_arguments($$);
+             }
+             | cpp_destructor_decl { $$ = $1; }
+             | cpp_protection_decl { $$ = $1; }
+             | cpp_swig_directive { $$ = $1; }
+             | cpp_conversion_operator { $$ = $1; }
+             | cpp_forward_class_decl { $$ = $1; }
+             | cpp_nested { $$ = $1; }
+             | storage_class idcolon SEMI { $$ = 0; }
+             | cpp_using_decl { $$ = $1; }
+             | cpp_template_decl { $$ = $1; }
+             | cpp_catch_decl { $$ = 0; }
+             | template_directive { $$ = $1; }
+             | warn_directive { $$ = $1; }
+             | anonymous_bitfield { $$ = 0; }
+             | fragment_directive {$$ = $1; }
+             | types_directive {$$ = $1; }
+             | SEMI { $$ = 0; }
+             ;
+
+/* Possibly a constructor */
+/* Note: the use of 'type' is here to resolve a shift-reduce conflict.  For example:
+            typedef Foo ();
+            typedef Foo (*ptr)();
+*/
+  
+cpp_constructor_decl : storage_class type LPAREN parms RPAREN ctor_end {
+              if (Classprefix) {
+		 SwigType *decl = NewStringEmpty();
+		 $$ = new_node("constructor");
+		 Setattr($$,"storage",$1);
+		 Setattr($$,"name",$2);
+		 Setattr($$,"parms",$4);
+		 SwigType_add_function(decl,$4);
+		 Setattr($$,"decl",decl);
+		 Setattr($$,"throws",$6.throws);
+		 Setattr($$,"throw",$6.throwf);
+		 if (Len(scanner_ccode)) {
+		   String *code = Copy(scanner_ccode);
+		   Setattr($$,"code",code);
+		   Delete(code);
+		 }
+		 SetFlag($$,"feature:new");
+	      } else {
+		$$ = 0;
+              }
+              }
+              ;
+
+/* A destructor (hopefully) */
+
+cpp_destructor_decl : NOT idtemplate LPAREN parms RPAREN cpp_end {
+               String *name = NewStringf("%s",$2);
+	       if (*(Char(name)) != '~') Insert(name,0,"~");
+               $$ = new_node("destructor");
+	       Setattr($$,"name",name);
+	       Delete(name);
+	       if (Len(scanner_ccode)) {
+		 String *code = Copy(scanner_ccode);
+		 Setattr($$,"code",code);
+		 Delete(code);
+	       }
+	       {
+		 String *decl = NewStringEmpty();
+		 SwigType_add_function(decl,$4);
+		 Setattr($$,"decl",decl);
+		 Delete(decl);
+	       }
+	       Setattr($$,"throws",$6.throws);
+	       Setattr($$,"throw",$6.throwf);
+	       add_symbols($$);
+	      }
+
+/* A virtual destructor */
+
+              | VIRTUAL NOT idtemplate LPAREN parms RPAREN cpp_vend {
+		String *name;
+		char *c = 0;
+		$$ = new_node("destructor");
+	       /* Check for template names.  If the class is a template
+		  and the constructor is missing the template part, we
+		  add it */
+	        if (Classprefix) {
+                  c = strchr(Char(Classprefix),'<');
+                  if (c && !Strchr($3,'<')) {
+                    $3 = NewStringf("%s%s",$3,c);
+                  }
+		}
+		Setattr($$,"storage","virtual");
+	        name = NewStringf("%s",$3);
+		if (*(Char(name)) != '~') Insert(name,0,"~");
+		Setattr($$,"name",name);
+		Delete(name);
+		Setattr($$,"throws",$7.throws);
+		Setattr($$,"throw",$7.throwf);
+		if ($7.val) {
+		  Setattr($$,"value","0");
+		}
+		if (Len(scanner_ccode)) {
+		  String *code = Copy(scanner_ccode);
+		  Setattr($$,"code",code);
+		  Delete(code);
+		}
+		{
+		  String *decl = NewStringEmpty();
+		  SwigType_add_function(decl,$5);
+		  Setattr($$,"decl",decl);
+		  Delete(decl);
+		}
+
+		add_symbols($$);
+	      }
+              ;
+
+
+/* C++ type conversion operator */
+cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAREN cpp_vend {
+                 $$ = new_node("cdecl");
+                 Setattr($$,"type",$3);
+		 Setattr($$,"name",$2);
+		 Setattr($$,"storage",$1);
+
+		 SwigType_add_function($4,$6);
+		 if ($8.qualifier) {
+		   SwigType_push($4,$8.qualifier);
+		 }
+		 Setattr($$,"decl",$4);
+		 Setattr($$,"parms",$6);
+		 Setattr($$,"conversion_operator","1");
+		 add_symbols($$);
+              }
+               | storage_class COPERATOR type AND LPAREN parms RPAREN cpp_vend {
+		 SwigType *decl;
+                 $$ = new_node("cdecl");
+                 Setattr($$,"type",$3);
+		 Setattr($$,"name",$2);
+		 Setattr($$,"storage",$1);
+		 decl = NewStringEmpty();
+		 SwigType_add_reference(decl);
+		 SwigType_add_function(decl,$6);
+		 if ($8.qualifier) {
+		   SwigType_push(decl,$8.qualifier);
+		 }
+		 Setattr($$,"decl",decl);
+		 Setattr($$,"parms",$6);
+		 Setattr($$,"conversion_operator","1");
+		 add_symbols($$);
+	       }
+
+              | storage_class COPERATOR type LPAREN parms RPAREN cpp_vend {
+		String *t = NewStringEmpty();
+		$$ = new_node("cdecl");
+		Setattr($$,"type",$3);
+		Setattr($$,"name",$2);
+		 Setattr($$,"storage",$1);
+		SwigType_add_function(t,$5);
+		if ($7.qualifier) {
+		  SwigType_push(t,$7.qualifier);
+		}
+		Setattr($$,"decl",t);
+		Setattr($$,"parms",$5);
+		Setattr($$,"conversion_operator","1");
+		add_symbols($$);
+              }
+              ;
+
+/* isolated catch clause. */
+
+cpp_catch_decl : CATCH LPAREN parms RPAREN LBRACE {
+                 skip_balanced('{','}');
+                 $$ = 0;
+               }
+               ;
+
+/* public: */
+cpp_protection_decl : PUBLIC COLON { 
+                $$ = new_node("access");
+		Setattr($$,"kind","public");
+                cplus_mode = CPLUS_PUBLIC;
+              }
+
+/* private: */
+              | PRIVATE COLON { 
+                $$ = new_node("access");
+                Setattr($$,"kind","private");
+		cplus_mode = CPLUS_PRIVATE;
+	      }
+
+/* protected: */
+
+              | PROTECTED COLON { 
+		$$ = new_node("access");
+		Setattr($$,"kind","protected");
+		cplus_mode = CPLUS_PROTECTED;
+	      }
+              ;
+
+
+/* ----------------------------------------------------------------------
+   Nested structure.    This is a sick "hack".   If we encounter
+   a nested structure, we're going to grab the text of its definition and
+   feed it back into the scanner.  In the meantime, we need to grab
+   variable declaration information and generate the associated wrapper
+   code later.  Yikes!
+
+   This really only works in a limited sense.   Since we use the
+   code attached to the nested class to generate both C/C++ code,
+   it can't have any SWIG directives in it.  It also needs to be parsable
+   by SWIG or this whole thing is going to puke.
+   ---------------------------------------------------------------------- */
+
+/* A struct sname { } id;  declaration */
+
+cpp_nested :   storage_class cpptype ID LBRACE { cparse_start_line = cparse_line; skip_balanced('{','}');
+	      } nested_decl SEMI {
+	        $$ = 0;
+		if (cplus_mode == CPLUS_PUBLIC) {
+		  if ($6.id && strcmp($2, "class") != 0) {
+		    Nested *n = (Nested *) malloc(sizeof(Nested));
+		    n->code = NewStringEmpty();
+		    Printv(n->code, "typedef ", $2, " ",
+			   Char(scanner_ccode), " $classname_", $6.id, ";\n", NIL);
+
+		    n->name = Swig_copy_string($6.id);
+		    n->line = cparse_start_line;
+		    n->type = NewStringEmpty();
+		    n->kind = $2;
+		    n->unnamed = 0;
+		    SwigType_push(n->type, $6.type);
+		    n->next = 0;
+		    add_nested(n);
+		  } else {
+		    Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", $2);
+		    if (strcmp($2, "class") == 0) {
+		      /* For now, just treat the nested class as a forward
+		       * declaration (SF bug #909387). */
+		      $$ = new_node("classforward");
+		      Setfile($$,cparse_file);
+		      Setline($$,cparse_line);
+		      Setattr($$,"kind",$2);
+		      Setattr($$,"name",$3);
+		      Setattr($$,"sym:weak", "1");
+		      add_symbols($$);
+		    }
+		  }
+		}
+	      }
+/* A struct { } id;  declaration */
+              | storage_class cpptype LBRACE { cparse_start_line = cparse_line; skip_balanced('{','}');
+              } nested_decl SEMI {
+	        $$ = 0;
+		if (cplus_mode == CPLUS_PUBLIC) {
+		  if (strcmp($2,"class") == 0) {
+		    Swig_warning(WARN_PARSE_NESTED_CLASS,cparse_file, cparse_line,"Nested class not currently supported (ignored)\n");
+		    /* Generate some code for a new class */
+		  } else if ($5.id) {
+		    /* Generate some code for a new class */
+		    Nested *n = (Nested *) malloc(sizeof(Nested));
+		    n->code = NewStringEmpty();
+		    Printv(n->code, "typedef ", $2, " " ,
+			    Char(scanner_ccode), " $classname_", $5.id, ";\n",NIL);
+		    n->name = Swig_copy_string($5.id);
+		    n->line = cparse_start_line;
+		    n->type = NewStringEmpty();
+		    n->kind = $2;
+		    n->unnamed = 1;
+		    SwigType_push(n->type,$5.type);
+		    n->next = 0;
+		    add_nested(n);
+		  } else {
+		    Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", $2);
+		  }
+		}
+	      }
+/* A  'class name : base_list { };'  declaration, always ignored */
+/*****
+     This fixes derived_nested.i, but it adds one shift/reduce. Anyway,
+     we are waiting for the nested class support.
+ *****/
+              | storage_class cpptype idcolon COLON base_list LBRACE { cparse_start_line = cparse_line; skip_balanced('{','}');
+              } SEMI {
+	        $$ = 0;
+		if (cplus_mode == CPLUS_PUBLIC) {
+		  Swig_warning(WARN_PARSE_NESTED_CLASS,cparse_file, cparse_line,"Nested class not currently supported (ignored)\n");
+		}
+	      }
+/*
+              | TEMPLATE LESSTHAN template_parms GREATERTHAN cpptype idcolon LBRACE { cparse_start_line = cparse_line; skip_balanced('{','}');
+              } SEMI {
+	        $$ = 0;
+		if (cplus_mode == CPLUS_PUBLIC) {
+		  Swig_warning(WARN_PARSE_NESTED_CLASS,cparse_file, cparse_line,"Nested class not currently supported (ignored)\n");
+		}
+	      }
+*/
+              ;
+
+nested_decl   : declarator { $$ = $1;}
+              | empty { $$.id = 0; }
+              ;
+
+
+/* These directives can be included inside a class definition */
+
+cpp_swig_directive: pragma_directive { $$ = $1; }
+
+/* A constant (includes #defines) inside a class */
+             | constant_directive { $$ = $1; }
+
+/* This is the new style rename */
+
+             | name_directive { $$ = $1; }
+
+/* rename directive */
+             | rename_directive { $$ = $1; }
+             | feature_directive { $$ = $1; }
+             | varargs_directive { $$ = $1; }
+             | insert_directive { $$ = $1; }
+             | typemap_directive { $$ = $1; }
+             | apply_directive { $$ = $1; }
+             | clear_directive { $$ = $1; }
+             | echo_directive { $$ = $1; }
+             ;
+
+cpp_end        : cpp_const SEMI {
+	            Clear(scanner_ccode);
+		    $$.throws = $1.throws;
+		    $$.throwf = $1.throwf;
+               }
+               | cpp_const LBRACE { 
+		    skip_balanced('{','}'); 
+		    $$.throws = $1.throws;
+		    $$.throwf = $1.throwf;
+	       }
+               ;
+
+cpp_vend       : cpp_const SEMI { 
+                     Clear(scanner_ccode);
+                     $$.val = 0;
+                     $$.qualifier = $1.qualifier;
+                     $$.bitfield = 0;
+                     $$.throws = $1.throws;
+                     $$.throwf = $1.throwf;
+                }
+               | cpp_const EQUAL definetype SEMI { 
+                     Clear(scanner_ccode);
+                     $$.val = $3.val;
+                     $$.qualifier = $1.qualifier;
+                     $$.bitfield = 0;
+                     $$.throws = $1.throws; 
+                     $$.throwf = $1.throwf; 
+               }
+               | cpp_const LBRACE { 
+                     skip_balanced('{','}');
+                     $$.val = 0;
+                     $$.qualifier = $1.qualifier;
+                     $$.bitfield = 0;
+                     $$.throws = $1.throws; 
+                     $$.throwf = $1.throwf; 
+               }
+               ;
+
+
+anonymous_bitfield :  storage_class type COLON expr SEMI { };
+
+/* ====================================================================== 
+ *                       PRIMITIVES
+ * ====================================================================== */
+
+storage_class  : EXTERN { $$ = "extern"; }
+               | EXTERN string { 
+                   if (strcmp($2,"C") == 0) {
+		     $$ = "externc";
+		   } else {
+		     Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2);
+		     $$ = 0;
+		   }
+               }
+               | STATIC { $$ = "static"; }
+               | TYPEDEF { $$ = "typedef"; }
+               | VIRTUAL { $$ = "virtual"; }
+               | FRIEND { $$ = "friend"; }
+               | EXPLICIT { $$ = "explicit"; }
+               | empty { $$ = 0; }
+               ;
+
+/* ------------------------------------------------------------------------------
+   Function parameter lists
+   ------------------------------------------------------------------------------ */
+
+parms          : rawparms {
+                 Parm *p;
+		 $$ = $1;
+		 p = $1;
+                 while (p) {
+		   Replace(Getattr(p,"type"),"typename ", "", DOH_REPLACE_ANY);
+		   p = nextSibling(p);
+                 }
+               }
+    	       ;
+
+rawparms          : parm ptail {
+                  set_nextSibling($1,$2);
+                  $$ = $1;
+		}
+               | empty { $$ = 0; }
+               ;
+
+ptail          : COMMA parm ptail {
+                 set_nextSibling($2,$3);
+		 $$ = $2;
+                }
+               | empty { $$ = 0; }
+               ;
+
+
+parm           : rawtype parameter_declarator {
+                   SwigType_push($1,$2.type);
+		   $$ = NewParm($1,$2.id);
+		   Setfile($$,cparse_file);
+		   Setline($$,cparse_line);
+		   if ($2.defarg) {
+		     Setattr($$,"value",$2.defarg);
+		   }
+		}
+
+                | TEMPLATE LESSTHAN cpptype GREATERTHAN cpptype idcolon def_args {
+                  $$ = NewParm(NewStringf("template<class> %s %s", $5,$6), 0);
+		  Setfile($$,cparse_file);
+		  Setline($$,cparse_line);
+                  if ($7.val) {
+                    Setattr($$,"value",$7.val);
+                  }
+                }
+                | PERIOD PERIOD PERIOD {
+		  SwigType *t = NewString("v(...)");
+		  $$ = NewParm(t, 0);
+		  Setfile($$,cparse_file);
+		  Setline($$,cparse_line);
+		}
+		;
+
+valparms        : rawvalparms {
+                 Parm *p;
+		 $$ = $1;
+		 p = $1;
+                 while (p) {
+		   if (Getattr(p,"type")) {
+		     Replace(Getattr(p,"type"),"typename ", "", DOH_REPLACE_ANY);
+		   }
+		   p = nextSibling(p);
+                 }
+               }
+    	       ;
+
+rawvalparms     : valparm valptail {
+                  set_nextSibling($1,$2);
+                  $$ = $1;
+		}
+               | empty { $$ = 0; }
+               ;
+
+valptail       : COMMA valparm valptail {
+                 set_nextSibling($2,$3);
+		 $$ = $2;
+                }
+               | empty { $$ = 0; }
+               ;
+
+
+valparm        : parm {
+		  $$ = $1;
+		  {
+		    /* We need to make a possible adjustment for integer parameters. */
+		    SwigType *type;
+		    Node     *n = 0;
+
+		    while (!n) {
+		      type = Getattr($1,"type");
+		      n = Swig_symbol_clookup(type,0);     /* See if we can find a node that matches the typename */
+		      if ((n) && (Strcmp(nodeType(n),"cdecl") == 0)) {
+			SwigType *decl = Getattr(n,"decl");
+			if (!SwigType_isfunction(decl)) {
+			  String *value = Getattr(n,"value");
+			  if (value) {
+			    String *v = Copy(value);
+			    Setattr($1,"type",v);
+			    Delete(v);
+			    n = 0;
+			  }
+			}
+		      } else {
+			break;
+		      }
+		    }
+		  }
+
+               }
+               | valexpr {
+                  $$ = NewParm(0,0);
+                  Setfile($$,cparse_file);
+		  Setline($$,cparse_line);
+		  Setattr($$,"value",$1.val);
+               }
+               ;
+
+def_args       : EQUAL definetype { 
+                  $$ = $2; 
+		  if ($2.type == T_ERROR) {
+		    Swig_warning(WARN_PARSE_BAD_DEFAULT,cparse_file, cparse_line, "Can't set default argument (ignored)\n");
+		    $$.val = 0;
+		    $$.rawval = 0;
+		    $$.bitfield = 0;
+		    $$.throws = 0;
+		    $$.throwf = 0;
+		  }
+               }
+               | EQUAL definetype LBRACKET expr RBRACKET { 
+		  $$ = $2;
+		  if ($2.type == T_ERROR) {
+		    Swig_warning(WARN_PARSE_BAD_DEFAULT,cparse_file, cparse_line, "Can't set default argument (ignored)\n");
+		    $$ = $2;
+		    $$.val = 0;
+		    $$.rawval = 0;
+		    $$.bitfield = 0;
+		    $$.throws = 0;
+		    $$.throwf = 0;
+		  } else {
+		    $$.val = NewStringf("%s[%s]",$2.val,$4.val); 
+		  }		  
+               }
+               | EQUAL LBRACE {
+		 skip_balanced('{','}');
+		 $$.val = 0;
+		 $$.rawval = 0;
+                 $$.type = T_INT;
+		 $$.bitfield = 0;
+		 $$.throws = 0;
+		 $$.throwf = 0;
+	       }
+               | COLON expr { 
+		 $$.val = 0;
+		 $$.rawval = 0;
+		 $$.type = 0;
+		 $$.bitfield = $2.val;
+		 $$.throws = 0;
+		 $$.throwf = 0;
+	       }
+               | empty {
+                 $$.val = 0;
+                 $$.rawval = 0;
+                 $$.type = T_INT;
+		 $$.bitfield = 0;
+		 $$.throws = 0;
+		 $$.throwf = 0;
+               }
+               ;
+
+parameter_declarator : declarator def_args {
+                 $$ = $1;
+		 $$.defarg = $2.rawval ? $2.rawval : $2.val;
+            }
+            | abstract_declarator def_args {
+              $$ = $1;
+	      $$.defarg = $2.rawval ? $2.rawval : $2.val;
+            }
+            | def_args {
+   	      $$.type = 0;
+              $$.id = 0;
+	      $$.defarg = $1.rawval ? $1.rawval : $1.val;
+            }
+            ;
+
+typemap_parameter_declarator : declarator {
+                 $$ = $1;
+		 if (SwigType_isfunction($1.type)) {
+		   Delete(SwigType_pop_function($1.type));
+		 } else if (SwigType_isarray($1.type)) {
+		   SwigType *ta = SwigType_pop_arrays($1.type);
+		   if (SwigType_isfunction($1.type)) {
+		     Delete(SwigType_pop_function($1.type));
+		   } else {
+		     $$.parms = 0;
+		   }
+		   SwigType_push($1.type,ta);
+		   Delete(ta);
+		 } else {
+		   $$.parms = 0;
+		 }
+            }
+            | abstract_declarator {
+              $$ = $1;
+	      if (SwigType_isfunction($1.type)) {
+		Delete(SwigType_pop_function($1.type));
+	      } else if (SwigType_isarray($1.type)) {
+		SwigType *ta = SwigType_pop_arrays($1.type);
+		if (SwigType_isfunction($1.type)) {
+		  Delete(SwigType_pop_function($1.type));
+		} else {
+		  $$.parms = 0;
+		}
+		SwigType_push($1.type,ta);
+		Delete(ta);
+	      } else {
+		$$.parms = 0;
+	      }
+            }
+            | empty {
+   	      $$.type = 0;
+              $$.id = 0;
+	      $$.parms = 0;
+	      }
+            ;
+
+
+declarator :  pointer notso_direct_declarator {
+              $$ = $2;
+	      if ($$.type) {
+		SwigType_push($1,$$.type);
+		Delete($$.type);
+	      }
+	      $$.type = $1;
+           }
+           | pointer AND notso_direct_declarator {
+              $$ = $3;
+	      SwigType_add_reference($1);
+              if ($$.type) {
+		SwigType_push($1,$$.type);
+		Delete($$.type);
+	      }
+	      $$.type = $1;
+           }
+           | direct_declarator {
+              $$ = $1;
+	      if (!$$.type) $$.type = NewStringEmpty();
+           }
+           | AND notso_direct_declarator { 
+	     $$ = $2;
+	     $$.type = NewStringEmpty();
+	     SwigType_add_reference($$.type);
+	     if ($2.type) {
+	       SwigType_push($$.type,$2.type);
+	       Delete($2.type);
+	     }
+           }
+           | idcolon DSTAR notso_direct_declarator { 
+	     SwigType *t = NewStringEmpty();
+
+	     $$ = $3;
+	     SwigType_add_memberpointer(t,$1);
+	     if ($$.type) {
+	       SwigType_push(t,$$.type);
+	       Delete($$.type);
+	     }
+	     $$.type = t;
+	     } 
+           | pointer idcolon DSTAR notso_direct_declarator { 
+	     SwigType *t = NewStringEmpty();
+	     $$ = $4;
+	     SwigType_add_memberpointer(t,$2);
+	     SwigType_push($1,t);
+	     if ($$.type) {
+	       SwigType_push($1,$$.type);
+	       Delete($$.type);
+	     }
+	     $$.type = $1;
+	     Delete(t);
+	   }
+           | pointer idcolon DSTAR AND notso_direct_declarator { 
+	     $$ = $5;
+	     SwigType_add_memberpointer($1,$2);
+	     SwigType_add_reference($1);
+	     if ($$.type) {
+	       SwigType_push($1,$$.type);
+	       Delete($$.type);
+	     }
+	     $$.type = $1;
+	   }
+           | idcolon DSTAR AND notso_direct_declarator { 
+	     SwigType *t = NewStringEmpty();
+	     $$ = $4;
+	     SwigType_add_memberpointer(t,$1);
+	     SwigType_add_reference(t);
+	     if ($$.type) {
+	       SwigType_push(t,$$.type);
+	       Delete($$.type);
+	     } 
+	     $$.type = t;
+	   }
+           ;
+
+notso_direct_declarator : idcolon {
+                /* Note: This is non-standard C.  Template declarator is allowed to follow an identifier */
+                 $$.id = Char($1);
+		 $$.type = 0;
+		 $$.parms = 0;
+		 $$.have_parms = 0;
+                  }
+                  | NOT idcolon {
+                  $$.id = Char(NewStringf("~%s",$2));
+                  $$.type = 0;
+                  $$.parms = 0;
+                  $$.have_parms = 0;
+                  }
+
+/* This generate a shift-reduce conflict with constructors */
+                 | LPAREN idcolon RPAREN {
+                  $$.id = Char($2);
+                  $$.type = 0;
+                  $$.parms = 0;
+                  $$.have_parms = 0;
+                  }
+
+/*
+                  | LPAREN AND idcolon RPAREN {
+                     $$.id = Char($3);
+                     $$.type = 0;
+                     $$.parms = 0;
+                     $$.have_parms = 0;
+                  }
+*/
+/* Technically, this should be LPAREN declarator RPAREN, but we get reduce/reduce conflicts */
+                  | LPAREN pointer notso_direct_declarator RPAREN {
+		    $$ = $3;
+		    if ($$.type) {
+		      SwigType_push($2,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = $2;
+                  }
+                  | LPAREN idcolon DSTAR notso_direct_declarator RPAREN {
+		    SwigType *t;
+		    $$ = $4;
+		    t = NewStringEmpty();
+		    SwigType_add_memberpointer(t,$2);
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+		    }
+                  | notso_direct_declarator LBRACKET RBRACKET { 
+		    SwigType *t;
+		    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_array(t,(char*)"");
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+                  }
+                  | notso_direct_declarator LBRACKET expr RBRACKET { 
+		    SwigType *t;
+		    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_array(t,$3.val);
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+                  }
+                  | notso_direct_declarator LPAREN parms RPAREN {
+		    SwigType *t;
+                    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_function(t,$3);
+		    if (!$$.have_parms) {
+		      $$.parms = $3;
+		      $$.have_parms = 1;
+		    }
+		    if (!$$.type) {
+		      $$.type = t;
+		    } else {
+		      SwigType_push(t, $$.type);
+		      Delete($$.type);
+		      $$.type = t;
+		    }
+		  }
+                  ;
+
+direct_declarator : idcolon {
+                /* Note: This is non-standard C.  Template declarator is allowed to follow an identifier */
+                 $$.id = Char($1);
+		 $$.type = 0;
+		 $$.parms = 0;
+		 $$.have_parms = 0;
+                  }
+
+                  | NOT idcolon {
+                  $$.id = Char(NewStringf("~%s",$2));
+                  $$.type = 0;
+                  $$.parms = 0;
+                  $$.have_parms = 0;
+                  }
+
+/* This generate a shift-reduce conflict with constructors */
+/*
+                  | LPAREN idcolon RPAREN {
+                  $$.id = Char($2);
+                  $$.type = 0;
+                  $$.parms = 0;
+                  $$.have_parms = 0;
+                  }
+*/
+/* Technically, this should be LPAREN declarator RPAREN, but we get reduce/reduce conflicts */
+                  | LPAREN pointer direct_declarator RPAREN {
+		    $$ = $3;
+		    if ($$.type) {
+		      SwigType_push($2,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = $2;
+                  }
+                  | LPAREN AND direct_declarator RPAREN {
+                    $$ = $3;
+		    if (!$$.type) {
+		      $$.type = NewStringEmpty();
+		    }
+		    SwigType_add_reference($$.type);
+                  }
+                  | LPAREN idcolon DSTAR direct_declarator RPAREN {
+		    SwigType *t;
+		    $$ = $4;
+		    t = NewStringEmpty();
+		    SwigType_add_memberpointer(t,$2);
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+		    }
+                  | direct_declarator LBRACKET RBRACKET { 
+		    SwigType *t;
+		    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_array(t,(char*)"");
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+                  }
+                  | direct_declarator LBRACKET expr RBRACKET { 
+		    SwigType *t;
+		    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_array(t,$3.val);
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+                  }
+                  | direct_declarator LPAREN parms RPAREN {
+		    SwigType *t;
+                    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_function(t,$3);
+		    if (!$$.have_parms) {
+		      $$.parms = $3;
+		      $$.have_parms = 1;
+		    }
+		    if (!$$.type) {
+		      $$.type = t;
+		    } else {
+		      SwigType_push(t, $$.type);
+		      Delete($$.type);
+		      $$.type = t;
+		    }
+		  }
+                  ;
+
+abstract_declarator : pointer {
+		    $$.type = $1;
+                    $$.id = 0;
+		    $$.parms = 0;
+		    $$.have_parms = 0;
+                  }
+                  | pointer direct_abstract_declarator { 
+                     $$ = $2;
+                     SwigType_push($1,$2.type);
+		     $$.type = $1;
+		     Delete($2.type);
+                  }
+                  | pointer AND {
+		    $$.type = $1;
+		    SwigType_add_reference($$.type);
+		    $$.id = 0;
+		    $$.parms = 0;
+		    $$.have_parms = 0;
+		  }
+                  | pointer AND direct_abstract_declarator {
+		    $$ = $3;
+		    SwigType_add_reference($1);
+		    if ($$.type) {
+		      SwigType_push($1,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = $1;
+                  }
+                  | direct_abstract_declarator {
+		    $$ = $1;
+                  }
+                  | AND direct_abstract_declarator {
+		    $$ = $2;
+		    $$.type = NewStringEmpty();
+		    SwigType_add_reference($$.type);
+		    if ($2.type) {
+		      SwigType_push($$.type,$2.type);
+		      Delete($2.type);
+		    }
+                  }
+                  | AND { 
+                    $$.id = 0;
+                    $$.parms = 0;
+		    $$.have_parms = 0;
+                    $$.type = NewStringEmpty();
+		    SwigType_add_reference($$.type);
+                  }
+                  | idcolon DSTAR { 
+		    $$.type = NewStringEmpty();
+                    SwigType_add_memberpointer($$.type,$1);
+                    $$.id = 0;
+                    $$.parms = 0;
+		    $$.have_parms = 0;
+      	          }
+                  | pointer idcolon DSTAR { 
+		    SwigType *t = NewStringEmpty();
+                    $$.type = $1;
+		    $$.id = 0;
+		    $$.parms = 0;
+		    $$.have_parms = 0;
+		    SwigType_add_memberpointer(t,$2);
+		    SwigType_push($$.type,t);
+		    Delete(t);
+                  }
+                  | pointer idcolon DSTAR direct_abstract_declarator { 
+		    $$ = $4;
+		    SwigType_add_memberpointer($1,$2);
+		    if ($$.type) {
+		      SwigType_push($1,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = $1;
+                  }
+                  ;
+
+direct_abstract_declarator : direct_abstract_declarator LBRACKET RBRACKET { 
+		    SwigType *t;
+		    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_array(t,(char*)"");
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+                  }
+                  | direct_abstract_declarator LBRACKET expr RBRACKET { 
+		    SwigType *t;
+		    $$ = $1;
+		    t = NewStringEmpty();
+		    SwigType_add_array(t,$3.val);
+		    if ($$.type) {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		    }
+		    $$.type = t;
+                  }
+                  | LBRACKET RBRACKET { 
+		    $$.type = NewStringEmpty();
+		    $$.id = 0;
+		    $$.parms = 0;
+		    $$.have_parms = 0;
+		    SwigType_add_array($$.type,(char*)"");
+                  }
+                  | LBRACKET expr RBRACKET { 
+		    $$.type = NewStringEmpty();
+		    $$.id = 0;
+		    $$.parms = 0;
+		    $$.have_parms = 0;
+		    SwigType_add_array($$.type,$2.val);
+		  }
+                  | LPAREN abstract_declarator RPAREN {
+                    $$ = $2;
+		  }
+                  | direct_abstract_declarator LPAREN parms RPAREN {
+		    SwigType *t;
+                    $$ = $1;
+		    t = NewStringEmpty();
+                    SwigType_add_function(t,$3);
+		    if (!$$.type) {
+		      $$.type = t;
+		    } else {
+		      SwigType_push(t,$$.type);
+		      Delete($$.type);
+		      $$.type = t;
+		    }
+		    if (!$$.have_parms) {
+		      $$.parms = $3;
+		      $$.have_parms = 1;
+		    }
+		  }
+                  | LPAREN parms RPAREN {
+                    $$.type = NewStringEmpty();
+                    SwigType_add_function($$.type,$2);
+		    $$.parms = $2;
+		    $$.have_parms = 1;
+		    $$.id = 0;
+                  }
+                  ;
+
+
+pointer    : STAR type_qualifier pointer { 
+               $$ = NewStringEmpty();
+               SwigType_add_pointer($$);
+	       SwigType_push($$,$2);
+	       SwigType_push($$,$3);
+	       Delete($3);
+           }
+           | STAR pointer {
+	     $$ = NewStringEmpty();
+	     SwigType_add_pointer($$);
+	     SwigType_push($$,$2);
+	     Delete($2);
+	     } 
+           | STAR type_qualifier { 
+	     	$$ = NewStringEmpty();	
+		SwigType_add_pointer($$);
+	        SwigType_push($$,$2);
+           }
+           | STAR {
+	      $$ = NewStringEmpty();
+	      SwigType_add_pointer($$);
+           }
+           ;
+
+type_qualifier : type_qualifier_raw {
+	          $$ = NewStringEmpty();
+	          if ($1) SwigType_add_qualifier($$,$1);
+               }
+               | type_qualifier_raw type_qualifier {
+		  $$ = $2;
+	          if ($1) SwigType_add_qualifier($$,$1);
+               }
+               ;
+
+type_qualifier_raw :  CONST_QUAL { $$ = "const"; }
+                   |  VOLATILE { $$ = "volatile"; }
+                   |  REGISTER { $$ = 0; }
+                   ;
+
+/* Data type must be a built in type or an identifier for user-defined types
+   This type can be preceded by a modifier. */
+
+type            : rawtype {
+                   $$ = $1;
+                   Replace($$,"typename ","", DOH_REPLACE_ANY);
+                }
+                ;
+
+rawtype       : type_qualifier type_right {
+                   $$ = $2;
+	           SwigType_push($$,$1);
+               }
+               | type_right { $$ = $1; }
+               | type_right type_qualifier {
+		  $$ = $1;
+	          SwigType_push($$,$2);
+	       }
+               | type_qualifier type_right type_qualifier {
+		  $$ = $2;
+	          SwigType_push($$,$3);
+	          SwigType_push($$,$1);
+	       }
+               ;
+
+type_right     : primitive_type { $$ = $1;
+                  /* Printf(stdout,"primitive = '%s'\n", $$);*/
+                }
+               | TYPE_BOOL { $$ = $1; }
+               | TYPE_VOID { $$ = $1; }
+               | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); }
+               | ENUM idcolon { $$ = NewStringf("enum %s", $2); }
+               | TYPE_RAW { $$ = $1; }
+
+               | idcolon {
+		  $$ = $1;
+               }
+               | cpptype idcolon { 
+		 $$ = NewStringf("%s %s", $1, $2);
+               }
+               ;
+
+primitive_type : primitive_type_list {
+		 if (!$1.type) $1.type = NewString("int");
+		 if ($1.us) {
+		   $$ = NewStringf("%s %s", $1.us, $1.type);
+		   Delete($1.us);
+                   Delete($1.type);
+		 } else {
+                   $$ = $1.type;
+		 }
+		 if (Cmp($$,"signed int") == 0) {
+		   Delete($$);
+		   $$ = NewString("int");
+                 } else if (Cmp($$,"signed long") == 0) {
+		   Delete($$);
+                   $$ = NewString("long");
+                 } else if (Cmp($$,"signed short") == 0) {
+		   Delete($$);
+		   $$ = NewString("short");
+		 } else if (Cmp($$,"signed long long") == 0) {
+		   Delete($$);
+		   $$ = NewString("long long");
+		 }
+               }
+               ;
+
+primitive_type_list : type_specifier { 
+                 $$ = $1;
+               }
+               | type_specifier primitive_type_list {
+                    if ($1.us && $2.us) {
+		      Swig_error(cparse_file, cparse_line, "Extra %s specifier.\n", $2.us);
+		    }
+                    $$ = $2;
+                    if ($1.us) $$.us = $1.us;
+		    if ($1.type) {
+		      if (!$2.type) $$.type = $1.type;
+		      else {
+			int err = 0;
+			if ((Cmp($1.type,"long") == 0)) {
+			  if ((Cmp($2.type,"long") == 0) || (Strncmp($2.type,"double",6) == 0)) {
+			    $$.type = NewStringf("long %s", $2.type);
+			  } else if (Cmp($2.type,"int") == 0) {
+			    $$.type = $1.type;
+			  } else {
+			    err = 1;
+			  }
+			} else if ((Cmp($1.type,"short")) == 0) {
+			  if (Cmp($2.type,"int") == 0) {
+			    $$.type = $1.type;
+			  } else {
+			    err = 1;
+			  }
+			} else if (Cmp($1.type,"int") == 0) {
+			  $$.type = $2.type;
+			} else if (Cmp($1.type,"double") == 0) {
+			  if (Cmp($2.type,"long") == 0) {
+			    $$.type = NewString("long double");
+			  } else if (Cmp($2.type,"complex") == 0) {
+			    $$.type = NewString("double complex");
+			  } else {
+			    err = 1;
+			  }
+			} else if (Cmp($1.type,"float") == 0) {
+			  if (Cmp($2.type,"complex") == 0) {
+			    $$.type = NewString("float complex");
+			  } else {
+			    err = 1;
+			  }
+			} else if (Cmp($1.type,"complex") == 0) {
+			  $$.type = NewStringf("%s complex", $2.type);
+			} else {
+			  err = 1;
+			}
+			if (err) {
+			  Swig_error(cparse_file, cparse_line, "Extra %s specifier.\n", $1.type);
+			}
+		      }
+		    }
+               }
+               ; 
+
+
+type_specifier : TYPE_INT { 
+		    $$.type = NewString("int");
+                    $$.us = 0;
+               }
+               | TYPE_SHORT { 
+                    $$.type = NewString("short");
+                    $$.us = 0;
+                }
+               | TYPE_LONG { 
+                    $$.type = NewString("long");
+                    $$.us = 0;
+                }
+               | TYPE_CHAR { 
+                    $$.type = NewString("char");
+                    $$.us = 0;
+                }
+               | TYPE_WCHAR { 
+                    $$.type = NewString("wchar_t");
+                    $$.us = 0;
+                }
+               | TYPE_FLOAT { 
+                    $$.type = NewString("float");
+                    $$.us = 0;
+                }
+               | TYPE_DOUBLE { 
+                    $$.type = NewString("double");
+                    $$.us = 0;
+                }
+               | TYPE_SIGNED { 
+                    $$.us = NewString("signed");
+                    $$.type = 0;
+                }
+               | TYPE_UNSIGNED { 
+                    $$.us = NewString("unsigned");
+                    $$.type = 0;
+                }
+               | TYPE_COMPLEX { 
+                    $$.type = NewString("complex");
+                    $$.us = 0;
+                }
+               | TYPE_NON_ISO_INT8 { 
+                    $$.type = NewString("__int8");
+                    $$.us = 0;
+                }
+               | TYPE_NON_ISO_INT16 { 
+                    $$.type = NewString("__int16");
+                    $$.us = 0;
+                }
+               | TYPE_NON_ISO_INT32 { 
+                    $$.type = NewString("__int32");
+                    $$.us = 0;
+                }
+               | TYPE_NON_ISO_INT64 { 
+                    $$.type = NewString("__int64");
+                    $$.us = 0;
+                }
+               ;
+
+definetype     : { /* scanner_check_typedef(); */ } expr {
+                   $$ = $2;
+		   if ($$.type == T_STRING) {
+		     $$.rawval = NewStringf("\"%(escape)s\"",$$.val);
+		   } else if ($$.type != T_CHAR) {
+		     $$.rawval = 0;
+		   }
+		   $$.bitfield = 0;
+		   $$.throws = 0;
+		   $$.throwf = 0;
+		   scanner_ignore_typedef();
+                }
+/*
+                | string {
+                   $$.val = NewString($1);
+		   $$.rawval = NewStringf("\"%(escape)s\"",$$.val);
+                   $$.type = T_STRING;
+		   $$.bitfield = 0;
+		   $$.throws = 0;
+		   $$.throwf = 0;
+		}
+*/
+                ;
+
+/* Some stuff for handling enums */
+
+ename          :  ID { $$ = $1; }
+               |  empty { $$ = (char *) 0;}
+               ;
+
+enumlist       :  enumlist COMMA edecl { 
+
+                  /* Ignore if there is a trailing comma in the enum list */
+                  if ($3) {
+                    Node *leftSibling = Getattr($1,"_last");
+                    if (!leftSibling) {
+                      leftSibling=$1;
+                    }
+                    set_nextSibling(leftSibling,$3);
+                    Setattr($1,"_last",$3);
+                  }
+		  $$ = $1;
+               }
+               |  edecl { 
+                   $$ = $1; 
+                   if ($1) {
+                     Setattr($1,"_last",$1);
+                   }
+               }
+               ;
+
+edecl          :  ID {
+		   SwigType *type = NewSwigType(T_INT);
+		   $$ = new_node("enumitem");
+		   Setattr($$,"name",$1);
+		   Setattr($$,"type",type);
+		   SetFlag($$,"feature:immutable");
+		   Delete(type);
+		 }
+                 | ID EQUAL etype {
+		   $$ = new_node("enumitem");
+		   Setattr($$,"name",$1);
+		   Setattr($$,"enumvalue", $3.val);
+	           if ($3.type == T_CHAR) {
+		     SwigType *type = NewSwigType(T_CHAR);
+		     Setattr($$,"value",NewStringf("\'%(escape)s\'", $3.val));
+		     Setattr($$,"type",type);
+		     Delete(type);
+		   } else {
+		     SwigType *type = NewSwigType(T_INT);
+		     Setattr($$,"value",$1);
+		     Setattr($$,"type",type);
+		     Delete(type);
+		   }
+		   SetFlag($$,"feature:immutable");
+                 }
+                 | empty { $$ = 0; }
+                 ;
+
+etype            : expr {
+                   $$ = $1;
+		   if (($$.type != T_INT) && ($$.type != T_UINT) &&
+		       ($$.type != T_LONG) && ($$.type != T_ULONG) &&
+		       ($$.type != T_SHORT) && ($$.type != T_USHORT) &&
+		       ($$.type != T_SCHAR) && ($$.type != T_UCHAR) &&
+		       ($$.type != T_CHAR)) {
+		     Swig_error(cparse_file,cparse_line,"Type error. Expecting an int\n");
+		   }
+		   if ($$.type == T_CHAR) $$.type = T_INT;
+                }
+               ;
+
+/* Arithmetic expressions.  Used for constants, C++ templates, and other cool stuff. */
+
+expr           : valexpr { $$ = $1; }
+               | type {
+		 Node *n;
+		 $$.val = $1;
+		 $$.type = T_INT;
+		 /* Check if value is in scope */
+		 n = Swig_symbol_clookup($1,0);
+		 if (n) {
+                   /* A band-aid for enum values used in expressions. */
+                   if (Strcmp(nodeType(n),"enumitem") == 0) {
+                     String *q = Swig_symbol_qualified(n);
+                     if (q) {
+                       $$.val = NewStringf("%s::%s", q, Getattr(n,"name"));
+                       Delete(q);
+                     }
+                   }
+		 }
+               }
+	       ;
+
+valexpr        : exprnum { $$ = $1; }
+               | string {
+		    $$.val = NewString($1);
+                    $$.type = T_STRING;
+               }
+               | SIZEOF LPAREN type parameter_declarator RPAREN {
+		  SwigType_push($3,$4.type);
+		  $$.val = NewStringf("sizeof(%s)",SwigType_str($3,0));
+		  $$.type = T_ULONG;
+               }
+               | exprcompound { $$ = $1; }
+               | CHARCONST {
+		  $$.val = NewString($1);
+		  if (Len($$.val)) {
+		    $$.rawval = NewStringf("'%(escape)s'", $$.val);
+		  } else {
+		    $$.rawval = NewString("'\\0'");
+		  }
+		  $$.type = T_CHAR;
+		  $$.bitfield = 0;
+		  $$.throws = 0;
+		  $$.throwf = 0;
+	       }
+
+/* grouping */
+               |  LPAREN expr RPAREN %prec CAST {
+   	            $$.val = NewStringf("(%s)",$2.val);
+		    $$.type = $2.type;
+   	       }
+
+/* A few common casting operations */
+
+               | LPAREN expr RPAREN expr %prec CAST {
+                 $$ = $4;
+		 if ($4.type != T_STRING) {
+		   $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $4.val);
+		 }
+ 	       }
+               | LPAREN expr pointer RPAREN expr %prec CAST {
+                 $$ = $5;
+		 if ($5.type != T_STRING) {
+		   SwigType_push($2.val,$3);
+		   $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $5.val);
+		 }
+ 	       }
+               | LPAREN expr AND RPAREN expr %prec CAST {
+                 $$ = $5;
+		 if ($5.type != T_STRING) {
+		   SwigType_add_reference($2.val);
+		   $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $5.val);
+		 }
+ 	       }
+               | LPAREN expr pointer AND RPAREN expr %prec CAST {
+                 $$ = $6;
+		 if ($6.type != T_STRING) {
+		   SwigType_push($2.val,$3);
+		   SwigType_add_reference($2.val);
+		   $$.val = NewStringf("(%s) %s", SwigType_str($2.val,0), $6.val);
+		 }
+ 	       }
+               | AND expr {
+		 $$ = $2;
+                 $$.val = NewStringf("&%s",$2.val);
+	       }
+               | STAR expr {
+		 $$ = $2;
+                 $$.val = NewStringf("*%s",$2.val);
+	       }
+               ;
+
+exprnum        :  NUM_INT { $$ = $1; }
+               |  NUM_FLOAT { $$ = $1; }
+               |  NUM_UNSIGNED { $$ = $1; }
+               |  NUM_LONG { $$ = $1; }
+               |  NUM_ULONG { $$ = $1; }
+               |  NUM_LONGLONG { $$ = $1; }
+               |  NUM_ULONGLONG { $$ = $1; }
+               ;
+
+exprcompound   : expr PLUS expr {
+		 $$.val = NewStringf("%s+%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr MINUS expr {
+		 $$.val = NewStringf("%s-%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr STAR expr {
+		 $$.val = NewStringf("%s*%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr SLASH expr {
+		 $$.val = NewStringf("%s/%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr MODULUS expr {
+		 $$.val = NewStringf("%s%%%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr AND expr {
+		 $$.val = NewStringf("%s&%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr OR expr {
+		 $$.val = NewStringf("%s|%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr XOR expr {
+		 $$.val = NewStringf("%s^%s",$1.val,$3.val);
+		 $$.type = promote($1.type,$3.type);
+	       }
+               | expr LSHIFT expr {
+		 $$.val = NewStringf("%s << %s",$1.val,$3.val);
+		 $$.type = promote_type($1.type);
+	       }
+               | expr RSHIFT expr {
+		 $$.val = NewStringf("%s >> %s",$1.val,$3.val);
+		 $$.type = promote_type($1.type);
+	       }
+               | expr LAND expr {
+		 $$.val = NewStringf("%s&&%s",$1.val,$3.val);
+		 $$.type = T_INT;
+	       }
+               | expr LOR expr {
+		 $$.val = NewStringf("%s||%s",$1.val,$3.val);
+		 $$.type = T_INT;
+	       }
+               | expr EQUALTO expr {
+		 $$.val = NewStringf("%s==%s",$1.val,$3.val);
+		 $$.type = T_INT;
+	       }
+               | expr NOTEQUALTO expr {
+		 $$.val = NewStringf("%s!=%s",$1.val,$3.val);
+		 $$.type = T_INT;
+	       }
+/* Sadly this causes 2 reduce-reduce conflicts with templates.  FIXME resolve these.
+               | expr GREATERTHAN expr {
+		 $$.val = NewStringf("%s SWIG_LT %s", $1.val, $3.val);
+		 $$.type = T_INT;
+	       }
+               | expr LESSTHAN expr {
+		 $$.val = NewStringf("%s SWIG_GT %s", $1.val, $3.val);
+		 $$.type = T_INT;
+	       }
+*/
+               | expr GREATERTHANOREQUALTO expr {
+		 /* Putting >= in the expression literally causes an infinite
+		  * loop somewhere in the type system.  Just workaround for now
+		  * - SWIG_GE is defined in swiglabels.swg. */
+		 $$.val = NewStringf("%s SWIG_GE %s", $1.val, $3.val);
+		 $$.type = T_INT;
+	       }
+               | expr LESSTHANOREQUALTO expr {
+		 $$.val = NewStringf("%s SWIG_LE %s", $1.val, $3.val);
+		 $$.type = T_INT;
+	       }
+	       | expr QUESTIONMARK expr COLON expr %prec QUESTIONMARK {
+		 $$.val = NewStringf("%s?%s:%s", $1.val, $3.val, $5.val);
+		 /* This may not be exactly right, but is probably good enough
+		  * for the purposes of parsing constant expressions. */
+		 $$.type = promote($3.type, $5.type);
+	       }
+               | MINUS expr %prec UMINUS {
+		 $$.val = NewStringf("-%s",$2.val);
+		 $$.type = $2.type;
+	       }
+               | PLUS expr %prec UMINUS {
+                 $$.val = NewStringf("+%s",$2.val);
+		 $$.type = $2.type;
+	       }
+               | NOT expr {
+		 $$.val = NewStringf("~%s",$2.val);
+		 $$.type = $2.type;
+	       }
+               | LNOT expr {
+                 $$.val = NewStringf("!%s",$2.val);
+		 $$.type = T_INT;
+	       }
+               | type LPAREN {
+		 String *qty;
+                 skip_balanced('(',')');
+		 qty = Swig_symbol_type_qualify($1,0);
+		 if (SwigType_istemplate(qty)) {
+		   String *nstr = SwigType_namestr(qty);
+		   Delete(qty);
+		   qty = nstr;
+		 }
+		 $$.val = NewStringf("%s%s",qty,scanner_ccode);
+		 Clear(scanner_ccode);
+		 $$.type = T_INT;
+		 Delete(qty);
+               }
+               ;
+
+inherit        : raw_inherit {
+		 $$ = $1;
+               }
+               ;
+
+raw_inherit     : COLON { inherit_list = 1; } base_list { $$ = $3; inherit_list = 0; }
+                | empty { $$ = 0; }
+                ;
+
+base_list      : base_specifier {
+		   Hash *list = NewHash();
+		   Node *base = $1;
+		   Node *name = Getattr(base,"name");
+		   List *lpublic = NewList();
+		   List *lprotected = NewList();
+		   List *lprivate = NewList();
+		   Setattr(list,"public",lpublic);
+		   Setattr(list,"protected",lprotected);
+		   Setattr(list,"private",lprivate);
+		   Delete(lpublic);
+		   Delete(lprotected);
+		   Delete(lprivate);
+		   Append(Getattr(list,Getattr(base,"access")),name);
+	           $$ = list;
+               }
+
+               | base_list COMMA base_specifier {
+		   Hash *list = $1;
+		   Node *base = $3;
+		   Node *name = Getattr(base,"name");
+		   Append(Getattr(list,Getattr(base,"access")),name);
+                   $$ = list;
+               }
+               ;
+
+base_specifier : opt_virtual idcolon {
+		 $$ = NewHash();
+		 Setfile($$,cparse_file);
+		 Setline($$,cparse_line);
+		 Setattr($$,"name",$2);
+                 if (last_cpptype && (Strcmp(last_cpptype,"struct") != 0)) {
+		   Setattr($$,"access","private");
+		   Swig_warning(WARN_PARSE_NO_ACCESS,cparse_file,cparse_line,
+				"No access specifier given for base class %s (ignored).\n",$2);
+                 } else {
+		   Setattr($$,"access","public");
+		 }
+               }
+	       | opt_virtual access_specifier opt_virtual idcolon {
+		 $$ = NewHash();
+		 Setfile($$,cparse_file);
+		 Setline($$,cparse_line);
+		 Setattr($$,"name",$4);
+		 Setattr($$,"access",$2);
+	         if (Strcmp($2,"public") != 0) {
+		   Swig_warning(WARN_PARSE_PRIVATE_INHERIT, cparse_file, 
+				cparse_line,"%s inheritance ignored.\n", $2);
+		 }
+               }
+               ;
+
+access_specifier :  PUBLIC { $$ = (char*)"public"; }
+               | PRIVATE { $$ = (char*)"private"; }
+               | PROTECTED { $$ = (char*)"protected"; }
+               ;
+
+
+templcpptype   : CLASS { 
+                   $$ = (char*)"class"; 
+		   if (!inherit_list) last_cpptype = $$;
+               }
+               | TYPENAME { 
+                   $$ = (char *)"typename"; 
+		   if (!inherit_list) last_cpptype = $$;
+               }
+               ;
+
+cpptype        : templcpptype {
+                 $$ = $1;
+               }
+               | STRUCT { 
+                   $$ = (char*)"struct"; 
+		   if (!inherit_list) last_cpptype = $$;
+               }
+               | UNION {
+                   $$ = (char*)"union"; 
+		   if (!inherit_list) last_cpptype = $$;
+               }
+               ;
+
+opt_virtual    : VIRTUAL
+               | empty
+               ;
+
+cpp_const      : type_qualifier {
+                    $$.qualifier = $1;
+                    $$.throws = 0;
+                    $$.throwf = 0;
+               }
+               | THROW LPAREN parms RPAREN {
+                    $$.qualifier = 0;
+                    $$.throws = $3;
+                    $$.throwf = NewString("1");
+               }
+               | type_qualifier THROW LPAREN parms RPAREN {
+                    $$.qualifier = $1;
+                    $$.throws = $4;
+                    $$.throwf = NewString("1");
+               }
+               | empty { 
+                    $$.qualifier = 0; 
+                    $$.throws = 0;
+                    $$.throwf = 0;
+               }
+               ;
+
+ctor_end       : cpp_const ctor_initializer SEMI { 
+                    Clear(scanner_ccode); 
+                    $$.have_parms = 0; 
+                    $$.defarg = 0; 
+		    $$.throws = $1.throws;
+		    $$.throwf = $1.throwf;
+               }
+               | cpp_const ctor_initializer LBRACE { 
+                    skip_balanced('{','}'); 
+                    $$.have_parms = 0; 
+                    $$.defarg = 0; 
+                    $$.throws = $1.throws;
+                    $$.throwf = $1.throwf;
+               }
+               | LPAREN parms RPAREN SEMI { 
+                    Clear(scanner_ccode); 
+                    $$.parms = $2; 
+                    $$.have_parms = 1; 
+                    $$.defarg = 0; 
+		    $$.throws = 0;
+		    $$.throwf = 0;
+               }
+               | LPAREN parms RPAREN LBRACE {
+                    skip_balanced('{','}'); 
+                    $$.parms = $2; 
+                    $$.have_parms = 1; 
+                    $$.defarg = 0; 
+                    $$.throws = 0;
+                    $$.throwf = 0;
+               }
+               | EQUAL definetype SEMI { 
+                    $$.have_parms = 0; 
+                    $$.defarg = $2.val; 
+                    $$.throws = 0;
+                    $$.throwf = 0;
+               }
+               ;
+
+ctor_initializer : COLON mem_initializer_list
+               | empty
+               ;
+
+mem_initializer_list : mem_initializer
+               | mem_initializer_list COMMA mem_initializer
+               ;
+
+mem_initializer : idcolon LPAREN {
+	            skip_balanced('(',')');
+                    Clear(scanner_ccode);
+            	}
+                ;
+
+template_decl : LESSTHAN valparms GREATERTHAN { 
+                     String *s = NewStringEmpty();
+                     SwigType_add_template(s,$2);
+                     $$ = Char(s);
+		     scanner_last_id(1);
+                 }
+               | empty { $$ = (char*)"";  }
+               ;
+
+idstring       : ID { $$ = $1; }
+               | string { $$ = $1; }
+               ;
+
+idstringopt    : idstring { $$ = $1; }
+               | empty { $$ = 0; }
+               ;
+ 
+idcolon        : idtemplate idcolontail { 
+                  $$ = 0;
+		  if (!$$) $$ = NewStringf("%s%s", $1,$2);
+      	          Delete($2);
+               }
+               | NONID DCOLON idtemplate idcolontail { 
+		 $$ = NewStringf("::%s%s",$3,$4);
+                 Delete($4);
+               }
+               | idtemplate {
+		 $$ = NewString($1);
+   	       }     
+               | NONID DCOLON idtemplate {
+		 $$ = NewStringf("::%s",$3);
+               }
+               | OPERATOR {
+                 $$ = NewString($1);
+	       }
+               | NONID DCOLON OPERATOR {
+                 $$ = NewStringf("::%s",$3);
+               }
+               ;
+
+idcolontail    : DCOLON idtemplate idcolontail {
+                   $$ = NewStringf("::%s%s",$2,$3);
+		   Delete($3);
+               }
+               | DCOLON idtemplate {
+                   $$ = NewStringf("::%s",$2);
+               }
+               | DCOLON OPERATOR {
+                   $$ = NewStringf("::%s",$2);
+               }
+/*               | DCOLON COPERATOR {
+                 $$ = NewString($2);                 
+		 } */
+
+               | DCNOT idtemplate {
+		 $$ = NewStringf("::~%s",$2);
+               }
+               ;
+
+
+idtemplate    : ID template_decl {
+                  $$ = NewStringf("%s%s",$1,$2);
+		  /*		  if (Len($2)) {
+		    scanner_last_id(1);
+		    } */
+              }
+              ;
+
+/* Identifier, but no templates */
+idcolonnt     : ID idcolontailnt { 
+                  $$ = 0;
+		  if (!$$) $$ = NewStringf("%s%s", $1,$2);
+      	          Delete($2);
+               }
+               | NONID DCOLON ID idcolontailnt { 
+		 $$ = NewStringf("::%s%s",$3,$4);
+                 Delete($4);
+               }
+               | ID {
+		 $$ = NewString($1);
+   	       }     
+               | NONID DCOLON ID {
+		 $$ = NewStringf("::%s",$3);
+               }
+               | OPERATOR {
+                 $$ = NewString($1);
+	       }
+               | NONID DCOLON OPERATOR {
+                 $$ = NewStringf("::%s",$3);
+               }
+               ;
+
+idcolontailnt   : DCOLON ID idcolontailnt {
+                   $$ = NewStringf("::%s%s",$2,$3);
+		   Delete($3);
+               }
+               | DCOLON ID {
+                   $$ = NewStringf("::%s",$2);
+               }
+               | DCOLON OPERATOR {
+                   $$ = NewStringf("::%s",$2);
+               }
+               | DCNOT ID {
+		 $$ = NewStringf("::~%s",$2);
+               }
+               ;
+
+/* Concatenated strings */
+string         : string STRING { 
+                   $$ = (char *) malloc(strlen($1)+strlen($2)+1);
+                   strcpy($$,$1);
+                   strcat($$,$2);
+               }
+               | STRING { $$ = $1;}
+               ; 
+
+stringbrace    : string {
+		 $$ = NewString($1);
+               }
+               | LBRACE {
+                  skip_balanced('{','}');
+		  $$ = NewString(scanner_ccode);
+               }
+              | HBLOCK {
+		 $$ = $1;
+              }
+               ;
+
+options        : LPAREN kwargs RPAREN {
+                  Hash *n;
+                  $$ = NewHash();
+                  n = $2;
+                  while(n) {
+                     String *name, *value;
+                     name = Getattr(n,"name");
+                     value = Getattr(n,"value");
+		     if (!value) value = (String *) "1";
+                     Setattr($$,name, value);
+		     n = nextSibling(n);
+		  }
+               }   
+               | empty { $$ = 0; };
+
+ 
+/* Keyword arguments */
+kwargs         : idstring EQUAL stringnum {
+		 $$ = NewHash();
+		 Setattr($$,"name",$1);
+		 Setattr($$,"value",$3);
+               }
+               | idstring EQUAL stringnum COMMA kwargs {
+		 $$ = NewHash();
+		 Setattr($$,"name",$1);
+		 Setattr($$,"value",$3);
+		 set_nextSibling($$,$5);
+               }
+               | idstring {
+                 $$ = NewHash();
+                 Setattr($$,"name",$1);
+	       }
+               | idstring COMMA kwargs {
+                 $$ = NewHash();
+                 Setattr($$,"name",$1);
+                 set_nextSibling($$,$3);
+               }
+               | idstring EQUAL stringtype  {
+                 $$ = $3;
+		 Setattr($$,"name",$1);
+               }
+               | idstring EQUAL stringtype COMMA kwargs {
+                 $$ = $3;
+		 Setattr($$,"name",$1);
+		 set_nextSibling($$,$5);
+               }
+               ;
+
+stringnum      : string {
+		 $$ = $1;
+               }
+               | exprnum {
+                 $$ = Char($1.val);
+               }
+               ;
+
+empty          :   ;
+
+%%
+
+SwigType *Swig_cparse_type(String *s) {
+   String *ns;
+   ns = NewStringf("%s;",s);
+   Seek(ns,0,SEEK_SET);
+   scanner_file(ns);
+   top = 0;
+   scanner_next_token(PARSETYPE);
+   yyparse();
+   /*   Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */
+   return top;
+}
+
+
+Parm *Swig_cparse_parm(String *s) {
+   String *ns;
+   ns = NewStringf("%s;",s);
+   Seek(ns,0,SEEK_SET);
+   scanner_file(ns);
+   top = 0;
+   scanner_next_token(PARSEPARM);
+   yyparse();
+   /*   Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */
+   Delete(ns);
+   return top;
+}
+
+
+ParmList *Swig_cparse_parms(String *s) {
+   String *ns;
+   char *cs = Char(s);
+   if (cs && cs[0] != '(') {
+     ns = NewStringf("(%s);",s);
+   } else {
+     ns = NewStringf("%s;",s);
+   }   
+   Seek(ns,0,SEEK_SET);
+   scanner_file(ns);
+   top = 0;
+   scanner_next_token(PARSEPARMS);
+   yyparse();
+   /*   Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */
+   return top;
+}
+
diff --git a/trunk/Source/CParse/templ.c b/trunk/Source/CParse/templ.c
new file mode 100644
index 0000000..8142125
--- /dev/null
+++ b/trunk/Source/CParse/templ.c
@@ -0,0 +1,672 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * templ.c
+ *
+ * Expands a template into a specialized version.   
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_templ_c[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+
+static int template_debug = 0;
+
+
+String *baselists[3];
+
+void SwigType_template_init() {
+  baselists[0] = "baselist";
+  baselists[1] = "protectedbaselist";
+  baselists[2] = "privatebaselist";
+}
+
+
+static void add_parms(ParmList *p, List *patchlist, List *typelist) {
+  while (p) {
+    SwigType *ty = Getattr(p, "type");
+    SwigType *val = Getattr(p, "value");
+    Append(typelist, ty);
+    Append(typelist, val);
+    Append(patchlist, val);
+    p = nextSibling(p);
+  }
+}
+
+void Swig_cparse_debug_templates(int x) {
+  template_debug = x;
+}
+
+/* -----------------------------------------------------------------------------
+ * cparse_template_expand()
+ *
+ * Expands a template node into a specialized version.  This is done by
+ * patching typenames and other aspects of the node according to a list of
+ * template parameters
+ * ----------------------------------------------------------------------------- */
+
+static int cparse_template_expand(Node *n, String *tname, String *rname, String *templateargs, List *patchlist, List *typelist, List *cpatchlist) {
+  static int expanded = 0;
+  int ret;
+  String *nodeType;
+  if (!n)
+    return 0;
+  nodeType = nodeType(n);
+  if (Getattr(n, "error"))
+    return 0;
+
+  if (Equal(nodeType, "template")) {
+    /* Change the node type back to normal */
+    if (!expanded) {
+      expanded = 1;
+      set_nodeType(n, Getattr(n, "templatetype"));
+      ret = cparse_template_expand(n, tname, rname, templateargs, patchlist, typelist, cpatchlist);
+      expanded = 0;
+      return ret;
+    } else {
+      /* Called when template appears inside another template */
+      /* Member templates */
+
+      set_nodeType(n, Getattr(n, "templatetype"));
+      ret = cparse_template_expand(n, tname, rname, templateargs, patchlist, typelist, cpatchlist);
+      set_nodeType(n, "template");
+      return ret;
+    }
+  } else if (Equal(nodeType, "cdecl")) {
+    /* A simple C declaration */
+    SwigType *t, *v, *d;
+    String *code;
+    t = Getattr(n, "type");
+    v = Getattr(n, "value");
+    d = Getattr(n, "decl");
+
+    code = Getattr(n, "code");
+
+    Append(typelist, t);
+    Append(typelist, d);
+    Append(patchlist, v);
+    Append(cpatchlist, code);
+
+    if (Getattr(n, "conversion_operator")) {
+      Append(cpatchlist, Getattr(n, "name"));
+      if (Getattr(n, "sym:name")) {
+	Append(cpatchlist, Getattr(n, "sym:name"));
+      }
+    }
+
+    add_parms(Getattr(n, "parms"), cpatchlist, typelist);
+    add_parms(Getattr(n, "throws"), cpatchlist, typelist);
+
+  } else if (Equal(nodeType, "class")) {
+    /* Patch base classes */
+    {
+      int b = 0;
+      for (b = 0; b < 3; ++b) {
+	List *bases = Getattr(n, baselists[b]);
+	if (bases) {
+	  int i;
+	  int ilen = Len(bases);
+	  for (i = 0; i < ilen; i++) {
+	    String *name = Copy(Getitem(bases, i));
+	    Setitem(bases, i, name);
+	    Append(typelist, name);
+	  }
+	}
+      }
+    }
+    /* Patch children */
+    {
+      Node *cn = firstChild(n);
+      while (cn) {
+	cparse_template_expand(cn, tname, rname, templateargs, patchlist, typelist, cpatchlist);
+	cn = nextSibling(cn);
+      }
+    }
+  } else if (Equal(nodeType, "constructor")) {
+    String *name = Getattr(n, "name");
+    if (!(Getattr(n, "templatetype"))) {
+      String *symname;
+      String *stripped_name = SwigType_templateprefix(name);
+      if (Strstr(tname, stripped_name)) {
+	Replaceid(name, stripped_name, tname);
+      }
+      Delete(stripped_name);
+      symname = Getattr(n, "sym:name");
+      if (symname) {
+	stripped_name = SwigType_templateprefix(symname);
+	if (Strstr(tname, stripped_name)) {
+	  Replaceid(symname, stripped_name, tname);
+	}
+	Delete(stripped_name);
+      }
+      if (strchr(Char(name), '<')) {
+	Append(patchlist, Getattr(n, "name"));
+      } else {
+	Append(name, templateargs);
+      }
+      name = Getattr(n, "sym:name");
+      if (name) {
+	if (strchr(Char(name), '<')) {
+	  Clear(name);
+	  Append(name, rname);
+	} else {
+	  String *tmp = Copy(name);
+	  Replace(tmp, tname, rname, DOH_REPLACE_ANY);
+	  Clear(name);
+	  Append(name, tmp);
+	  Delete(tmp);
+	}
+      }
+      /* Setattr(n,"sym:name",name); */
+    }
+    Append(cpatchlist, Getattr(n, "code"));
+    Append(typelist, Getattr(n, "decl"));
+    add_parms(Getattr(n, "parms"), cpatchlist, typelist);
+    add_parms(Getattr(n, "throws"), cpatchlist, typelist);
+  } else if (Equal(nodeType, "destructor")) {
+    String *name = Getattr(n, "name");
+    if (name && strchr(Char(name), '<')) {
+      Append(patchlist, Getattr(n, "name"));
+    } else {
+      Append(name, templateargs);
+    }
+    name = Getattr(n, "sym:name");
+    if (name && strchr(Char(name), '<')) {
+      String *sn = Copy(tname);
+      Setattr(n, "sym:name", sn);
+      Delete(sn);
+    } else {
+      Replace(name, tname, rname, DOH_REPLACE_ANY);
+    }
+    /* Setattr(n,"sym:name",name); */
+    Append(cpatchlist, Getattr(n, "code"));
+  } else if (Equal(nodeType, "using")) {
+    String *uname = Getattr(n, "uname");
+    if (uname && strchr(Char(uname), '<')) {
+      Append(patchlist, uname);
+    }
+    if (Getattr(n, "namespace")) {
+      /* Namespace link.   This is nasty.  Is other namespace defined? */
+
+    }
+  } else {
+    /* Look for obvious parameters */
+    Node *cn;
+    Append(cpatchlist, Getattr(n, "code"));
+    Append(typelist, Getattr(n, "type"));
+    Append(typelist, Getattr(n, "decl"));
+    add_parms(Getattr(n, "parms"), cpatchlist, typelist);
+    add_parms(Getattr(n, "kwargs"), cpatchlist, typelist);
+    add_parms(Getattr(n, "pattern"), cpatchlist, typelist);
+    add_parms(Getattr(n, "throws"), cpatchlist, typelist);
+    cn = firstChild(n);
+    while (cn) {
+      cparse_template_expand(cn, tname, rname, templateargs, patchlist, typelist, cpatchlist);
+      cn = nextSibling(cn);
+    }
+  }
+  return 0;
+}
+
+static
+String *partial_arg(String *s, String *p) {
+  char *c;
+  char *cp = Char(p);
+  String *prefix;
+  String *newarg;
+
+  /* Find the prefix on the partial argument */
+
+  c = strchr(cp, '$');
+  if (!c) {
+    return Copy(s);
+  }
+  prefix = NewStringWithSize(cp, c - cp);
+  newarg = Copy(s);
+  Replace(newarg, prefix, "", DOH_REPLACE_ANY | DOH_REPLACE_FIRST);
+  Delete(prefix);
+  return newarg;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cparse_template_expand()
+ * ----------------------------------------------------------------------------- */
+
+int Swig_cparse_template_expand(Node *n, String *rname, ParmList *tparms, Symtab *tscope) {
+  List *patchlist, *cpatchlist, *typelist;
+  String *templateargs;
+  String *tname;
+  String *iname;
+  String *tbase;
+  patchlist = NewList();
+  cpatchlist = NewList();
+  typelist = NewList();
+
+  {
+    String *tmp = NewStringEmpty();
+    if (tparms) {
+      SwigType_add_template(tmp, tparms);
+    }
+    templateargs = Copy(tmp);
+    Delete(tmp);
+  }
+
+  tname = Copy(Getattr(n, "name"));
+  tbase = Swig_scopename_last(tname);
+
+  /* Look for partial specialization matching */
+  if (Getattr(n, "partialargs")) {
+    Parm *p, *tp;
+    ParmList *ptargs = SwigType_function_parms(Getattr(n, "partialargs"));
+    p = ptargs;
+    tp = tparms;
+    while (p && tp) {
+      SwigType *ptype;
+      SwigType *tptype;
+      SwigType *partial_type;
+      ptype = Getattr(p, "type");
+      tptype = Getattr(tp, "type");
+      if (ptype && tptype) {
+	partial_type = partial_arg(tptype, ptype);
+	/*      Printf(stdout,"partial '%s' '%s'  ---> '%s'\n", tptype, ptype, partial_type); */
+	Setattr(tp, "type", partial_type);
+	Delete(partial_type);
+      }
+      p = nextSibling(p);
+      tp = nextSibling(tp);
+    }
+    assert(ParmList_len(ptargs) == ParmList_len(tparms));
+    Delete(ptargs);
+  }
+
+  /*
+    Parm *p = tparms;
+    while (p) {
+      Printf(stdout, "tparm: '%s' '%s' '%s'\n", Getattr(p, "name"), Getattr(p, "type"), Getattr(p, "value"));
+      p = nextSibling(p);
+    }
+  */
+
+  /*  Printf(stdout,"targs = '%s'\n", templateargs);
+     Printf(stdout,"rname = '%s'\n", rname);
+     Printf(stdout,"tname = '%s'\n", tname);  */
+  cparse_template_expand(n, tname, rname, templateargs, patchlist, typelist, cpatchlist);
+
+  /* Set the name */
+  {
+    String *name = Getattr(n, "name");
+    if (name) {
+      Append(name, templateargs);
+    }
+    iname = name;
+  }
+
+  /* Patch all of the types */
+  {
+    Parm *tp = Getattr(n, "templateparms");
+    Parm *p = tparms;
+    /*    Printf(stdout,"%s\n", ParmList_str_defaultargs(tp)); */
+
+    if (tp) {
+      Symtab *tsdecl = Getattr(n, "sym:symtab");
+      while (p && tp) {
+	String *name, *value, *valuestr, *tydef, *tmp, *tmpr;
+	int sz, i;
+	String *dvalue = 0;
+	String *qvalue = 0;
+
+	name = Getattr(tp, "name");
+	value = Getattr(p, "value");
+	tydef = Getattr(p, "typedef");
+
+	if (name) {
+	  if (!value)
+	    value = Getattr(p, "type");
+	  qvalue = Swig_symbol_typedef_reduce(value, tsdecl);
+	  dvalue = Swig_symbol_type_qualify(qvalue, tsdecl);
+	  if (SwigType_istemplate(dvalue)) {
+	    String *ty = Swig_symbol_template_deftype(dvalue, tscope);
+	    Delete(dvalue);
+	    dvalue = ty;
+	  }
+
+	  assert(dvalue);
+	  valuestr = SwigType_str(dvalue, 0);
+	  /* Need to patch default arguments */
+	  {
+	    Parm *rp = nextSibling(p);
+	    while (rp) {
+	      String *rvalue = Getattr(rp, "value");
+	      if (rvalue) {
+		Replace(rvalue, name, dvalue, DOH_REPLACE_ID);
+	      }
+	      rp = nextSibling(rp);
+	    }
+	  }
+	  sz = Len(patchlist);
+	  for (i = 0; i < sz; i++) {
+	    String *s = Getitem(patchlist, i);
+	    Replace(s, name, dvalue, DOH_REPLACE_ID);
+	  }
+	  sz = Len(typelist);
+	  for (i = 0; i < sz; i++) {
+	    String *s = Getitem(typelist, i);
+	    /*      Replace(s,name,value, DOH_REPLACE_ID); */
+	    /*      Printf(stdout,"name = '%s', value = '%s', tbase = '%s', iname='%s' s = '%s' --> ", name, dvalue, tbase, iname, s); */
+	    SwigType_typename_replace(s, name, dvalue);
+	    SwigType_typename_replace(s, tbase, iname);
+	    /*      Printf(stdout,"'%s'\n", s); */
+	  }
+
+	  if (!tydef) {
+	    tydef = dvalue;
+	  }
+	  tmp = NewStringf("#%s", name);
+	  tmpr = NewStringf("\"%s\"", valuestr);
+
+	  sz = Len(cpatchlist);
+	  for (i = 0; i < sz; i++) {
+	    String *s = Getitem(cpatchlist, i);
+	    Replace(s, tmp, tmpr, DOH_REPLACE_ID);
+	    /*  Replace(s,name,tydef, DOH_REPLACE_ID); */
+	    Replace(s, name, valuestr, DOH_REPLACE_ID);
+	  }
+	  Delete(tmp);
+	  Delete(tmpr);
+	  Delete(valuestr);
+	  Delete(dvalue);
+	  Delete(qvalue);
+	}
+	p = nextSibling(p);
+	tp = nextSibling(tp);
+	if (!p)
+	  p = tp;
+      }
+    } else {
+      /* No template parameters at all.  This could be a specialization */
+      int i, sz;
+      sz = Len(typelist);
+      for (i = 0; i < sz; i++) {
+	String *s = Getitem(typelist, i);
+	SwigType_typename_replace(s, tbase, iname);
+      }
+    }
+  }
+
+  /* Patch bases */
+  {
+    List *bases = Getattr(n, "baselist");
+    if (bases) {
+      Iterator b;
+      for (b = First(bases); b.item; b = Next(b)) {
+	String *qn = Swig_symbol_type_qualify(b.item, tscope);
+	Clear(b.item);
+	Append(b.item, qn);
+	Delete(qn);
+      }
+    }
+  }
+  Delete(patchlist);
+  Delete(cpatchlist);
+  Delete(typelist);
+  Delete(tbase);
+  Delete(tname);
+  Delete(templateargs);
+
+  /*  set_nodeType(n,"template"); */
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * template_locate()
+ *
+ * Search for a template that matches name with given parameters.
+ * ----------------------------------------------------------------------------- */
+
+static Node *template_locate(String *name, Parm *tparms, Symtab *tscope) {
+  Node *n;
+  String *tname, *rname = 0;
+  Node *templ;
+  List *mpartials = 0;
+  Parm *p;
+  Parm *parms;
+  Parm *targs;
+  ParmList *expandedparms;
+
+  tname = Copy(name);
+  parms = CopyParmList(tparms);
+
+  /* Search for generic template */
+  templ = Swig_symbol_clookup(name, 0);
+
+  /* Add default values from generic template */
+  if (templ) {
+    Symtab *tsdecl = Getattr(templ, "sym:symtab");
+
+    targs = Getattr(templ, "templateparms");
+    expandedparms = Swig_symbol_template_defargs(parms, targs, tscope, tsdecl);
+  } else {
+    expandedparms = parms;
+  }
+
+
+  /* reduce the typedef */
+  p = expandedparms;
+  while (p) {
+    SwigType *ty = Getattr(p, "type");
+    if (ty) {
+      SwigType *nt = Swig_symbol_type_qualify(ty, tscope);
+      Setattr(p, "type", nt);
+      Delete(nt);
+    }
+    p = nextSibling(p);
+  }
+
+  SwigType_add_template(tname, expandedparms);
+
+  if (template_debug) {
+    Printf(stdout, "\n%s:%d: template_debug: Searching for %s\n", cparse_file, cparse_line, tname);
+  }
+
+  /* Search for an exact specialization.
+     Example: template<> class name<int> { ... } */
+  {
+    if (template_debug) {
+      Printf(stdout, "    searching: '%s' (exact specialization)\n", tname);
+    }
+    n = Swig_symbol_clookup_local(tname, 0);
+    if (!n) {
+      SwigType *rname = Swig_symbol_typedef_reduce(tname, tscope);
+      if (!Equal(rname, tname)) {
+	if (template_debug) {
+	  Printf(stdout, "    searching: '%s' (exact specialization)\n", rname);
+	}
+	n = Swig_symbol_clookup_local(rname, 0);
+      }
+      Delete(rname);
+    }
+    if (n) {
+      Node *tn;
+      String *nodeType = nodeType(n);
+      if (Equal(nodeType, "template"))
+	goto success;
+      tn = Getattr(n, "template");
+      if (tn) {
+	n = tn;
+	goto success;		/* Previously wrapped by a template return that */
+      }
+      Swig_error(cparse_file, cparse_line, "'%s' is not defined as a template. (%s)\n", name, nodeType(n));
+      Delete(tname);
+      Delete(parms);
+      return 0;			/* Found a match, but it's not a template of any kind. */
+    }
+  }
+
+  /* Search for partial specialization. 
+     Example: template<typename T> class name<T *> { ... } */
+
+  /* Generate reduced template name (stripped of extraneous pointers, etc.) */
+
+  rname = NewStringf("%s<(", name);
+  p = parms;
+  while (p) {
+    String *t;
+    t = Getattr(p, "type");
+    if (!t)
+      t = Getattr(p, "value");
+    if (t) {
+      String *ty = Swig_symbol_typedef_reduce(t, tscope);
+      String *tb = SwigType_base(ty);
+      String *td = SwigType_default(ty);
+      Replaceid(td, "enum SWIGTYPE", tb);
+      Replaceid(td, "SWIGTYPE", tb);
+      Append(rname, td);
+      Delete(tb);
+      Delete(ty);
+      Delete(td);
+    }
+    p = nextSibling(p);
+    if (p) {
+      Append(rname, ",");
+    }
+  }
+  Append(rname, ")>");
+
+  mpartials = NewList();
+  if (templ) {
+    /* First, we search using an exact type prototype */
+    Parm *p;
+    char tmp[32];
+    int i;
+    List *partials;
+    String *ss;
+    Iterator pi;
+
+    partials = Getattr(templ, "partials");
+    if (partials) {
+      for (pi = First(partials); pi.item; pi = Next(pi)) {
+	ss = Copy(pi.item);
+	p = parms;
+	i = 1;
+	while (p) {
+	  String *t, *tn;
+	  sprintf(tmp, "$%d", i);
+	  t = Getattr(p, "type");
+	  if (!t)
+	    t = Getattr(p, "value");
+	  if (t) {
+	    String *ty = Swig_symbol_typedef_reduce(t, tscope);
+	    tn = SwigType_base(ty);
+	    Replaceid(ss, tmp, tn);
+	    Delete(tn);
+	    Delete(ty);
+	  }
+	  i++;
+	  p = nextSibling(p);
+	}
+	if (template_debug) {
+	  Printf(stdout, "    searching: '%s' (partial specialization - %s)\n", ss, pi.item);
+	}
+	if ((Equal(ss, tname)) || (Equal(ss, rname))) {
+	  Append(mpartials, pi.item);
+	}
+	Delete(ss);
+      }
+    }
+  }
+
+  if (template_debug) {
+    Printf(stdout, "    Matched partials: %s\n", mpartials);
+  }
+
+  if (Len(mpartials)) {
+    String *s = Getitem(mpartials, 0);
+    n = Swig_symbol_clookup_local(s, 0);
+    if (Len(mpartials) > 1) {
+      if (n) {
+	Swig_warning(WARN_PARSE_TEMPLATE_AMBIG, cparse_file, cparse_line, "Instantiation of template '%s' is ambiguous,\n", SwigType_namestr(tname));
+	Swig_warning(WARN_PARSE_TEMPLATE_AMBIG, Getfile(n), Getline(n), "  instantiation '%s' is used.\n", SwigType_namestr(Getattr(n, "name")));
+      }
+    }
+  }
+
+  if (!n) {
+    n = templ;
+  }
+  if (!n) {
+    Swig_error(cparse_file, cparse_line, "Template '%s' undefined.\n", name);
+  } else if (n) {
+    String *nodeType = nodeType(n);
+    if (!Equal(nodeType, "template")) {
+      Swig_error(cparse_file, cparse_line, "'%s' is not defined as a template. (%s)\n", name, nodeType);
+      n = 0;
+    }
+  }
+success:
+  Delete(tname);
+  Delete(rname);
+  Delete(mpartials);
+  if ((template_debug) && (n)) {
+    Printf(stdout, "Node: %p\n", n);
+    Swig_print_node(n);
+  }
+  Delete(parms);
+  return n;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_cparse_template_locate()
+ *
+ * Search for a template that matches name with given parameters.
+ * For templated classes finds the specialized template should there be one.
+ * For templated functions finds the unspecialized template even if a specialized
+ * template exists.
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_cparse_template_locate(String *name, Parm *tparms, Symtab *tscope) {
+  Node *n = template_locate(name, tparms, tscope);	/* this function does what we want for templated classes */
+
+  if (n) {
+    String *nodeType = nodeType(n);
+    int isclass = 0;
+    assert(Equal(nodeType, "template"));
+    isclass = (Equal(Getattr(n, "templatetype"), "class"));
+    if (!isclass) {
+      /* If not a templated class we must have a templated function.
+         The template found is not necessarily the one we want when dealing with templated
+         functions. We don't want any specialized templated functions as they won't have
+         the default parameters. Lets look for the unspecialized template. Also make sure
+         the number of template parameters is correct as it is possible to overload a
+         templated function with different numbers of template parameters. */
+
+      if (template_debug) {
+	Printf(stdout, "    Not a templated class, seeking most appropriate templated function\n");
+      }
+
+      n = Swig_symbol_clookup_local(name, 0);
+      while (n) {
+	Parm *tparmsfound = Getattr(n, "templateparms");
+	if (ParmList_len(tparms) == ParmList_len(tparmsfound)) {
+	  /* successful match */
+	  break;
+	}
+	/* repeat until we find a match with correct number of templated parameters */
+	n = Getattr(n, "sym:nextSibling");
+      }
+
+      if (!n) {
+	Swig_error(cparse_file, cparse_line, "Template '%s' undefined.\n", name);
+      }
+
+      if ((template_debug) && (n)) {
+	Printf(stdout, "Templated function found: %p\n", n);
+	Swig_print_node(n);
+      }
+    }
+  }
+
+  return n;
+}
diff --git a/trunk/Source/CParse/util.c b/trunk/Source/CParse/util.c
new file mode 100644
index 0000000..efae410
--- /dev/null
+++ b/trunk/Source/CParse/util.c
@@ -0,0 +1,88 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * util.c
+ *
+ * Parsing utilities.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_util_c[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+
+/* -----------------------------------------------------------------------------
+ * Swig_cparse_replace_descriptor()
+ *
+ * Replaces type descriptor string $descriptor() with the SWIG type descriptor
+ * string.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_cparse_replace_descriptor(String *s) {
+  char tmp[512];
+  String *arg = 0;
+  SwigType *t;
+  char *c = 0;
+
+  while ((c = strstr(Char(s), "$descriptor("))) {
+    char *d = tmp;
+    int level = 0;
+    while (*c) {
+      if (*c == '(')
+	level++;
+      if (*c == ')') {
+	level--;
+	if (level == 0) {
+	  break;
+	}
+      }
+      *d = *c;
+      d++;
+      c++;
+    }
+    *d = 0;
+    arg = NewString(tmp + 12);
+    t = Swig_cparse_type(arg);
+    Delete(arg);
+    arg = 0;
+
+    if (t) {
+      String *mangle;
+      String *descriptor;
+
+      mangle = SwigType_manglestr(t);
+      descriptor = NewStringf("SWIGTYPE%s", mangle);
+      SwigType_remember(t);
+      *d = ')';
+      d++;
+      *d = 0;
+      Replace(s, tmp, descriptor, DOH_REPLACE_ANY);
+      Delete(mangle);
+      Delete(descriptor);
+      Delete(t);
+    } else {
+      Swig_error(Getfile(s), Getline(s), "Bad $descriptor() macro.\n");
+      break;
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * cparse_normalize_void()
+ *
+ * This function is used to replace arguments of the form (void) with empty
+ * arguments in C++
+ * ----------------------------------------------------------------------------- */
+
+void cparse_normalize_void(Node *n) {
+  String *decl = Getattr(n, "decl");
+  Parm *parms = Getattr(n, "parms");
+
+  if (SwigType_isfunction(decl)) {
+    if ((ParmList_len(parms) == 1) && (SwigType_type(Getattr(parms, "type")) == T_VOID)) {
+      Replaceall(decl, "f(void).", "f().");
+      Delattr(n, "parms");
+    }
+  }
+}
diff --git a/trunk/Source/DOH/README b/trunk/Source/DOH/README
new file mode 100644
index 0000000..1e94810
--- /dev/null
+++ b/trunk/Source/DOH/README
@@ -0,0 +1,118 @@
+DOH  (Dave's Object Hack)
+
+Overview:
+---------
+DOH is a small C library that provides a number of simple yet powerful
+data structures. The data structures are built around a dynamic typing
+model in which any given object is allowed to support one or more
+classes of operations.  Furthermore, a simple garbage collection
+scheme and a variety of interesting library methods are available.
+All and all, the operation of DOH makes massive abuse of the C type
+system and would probably make the language purists scream and
+performance addicts run away in horror.  However, I really don't
+care--so there! However, for the rest of us, DOH is actually kind of
+fun to use. This is only a short description of the methods and is no
+way meant to be exhaustive.
+
+Common Operations (for all types)
+---------------------------------
+Delete(obj)             Decrease the reference count and destroy if zero
+Copy(obj)               Make a copy of an object.
+Clear(obj)              Clear an object.
+Setscope(obj)           Set scope of an object (guru's only)
+Str(obj)                Create a string representation of obj.
+Data(obj)               Return pointer to raw data in an object
+Char(obj)               Convert to a char *
+Len(obj)                Length of an object
+Hash(obj)               Hash value (used for mapping)
+Cmp(obj1,obj2)          Compare two objects.
+Name(obj)               Return the object name
+First(obj)              Return first object (iterator)
+Next(obj)               Return next object
+Dump(obj,out)           Serialize on out
+Load(in)                Unserialize from in
+First(obj)              Iterator
+Next(iter)              Next iterator
+
+Mapping Operations (for hash table behavior)
+--------------------------------------------
+Getattr(hash,key)              Get an attribute
+Setattr(hash,key,value)        Set an attribute
+Delattr(hash,key)              Delete an attribute
+First(hash)                    Get first object (iterator)
+Next(hash)                     Get next object
+GetInt(hash,key)               Get attribute as an 'int'
+SetInt(hash,key,ivalue)        Set attribute as an 'int'
+GetDouble(hash,key)            Get attribute as a 'double'
+SetDouble(hash,key,dvalue)     Set Attribute as a 'double'
+GetChar(hash,key)              Get attribute as a 'char *'
+
+Sequence Operations
+-------------------
+Getitem(list,index)             Get an item
+Setitem(list,index,val)         Set an item
+Delitem(list,index,val)         Delete an item
+Insert(list,index,val)          Insert an item
+Append(list,val)                Append to end
+Push(list,val)                  Insert at beginning
+
+File Operations
+---------------
+Read(obj,buffer,len)            Read data
+Write(obj,buffer,len)           Write data
+Getc(obj)                       Get a character
+Putc(ch,obj)                    Put a character
+Ungetc(ch,obj)                  Put character back on input stream
+Seek(obj,offset,whence)         Seek
+Tell(obj)                       Return file pointer
+Close(obj)                      Close
+
+String Operations
+-----------------
+Replace(obj, orig, rep, flags)  Replace occurences of orig with rep.
+Chop(obj)                       Remove trailing whitespace
+
+flags is one of the following:
+     DOH_REPLACE_ANY
+     DOH_REPLACE_NOQUOTE
+     DOH_REPLACE_ID
+     DOH_REPLACE_FIRST
+             
+Callable Operations
+-------------------
+Call(obj, args)                 Perform a function call with arguments args.
+
+Miscellaneous library functions
+-------------------------------
+NewScope()                      Create a new scope
+DelScope(s)                     Delete scope s
+Readline(in)                    Read a line of input from in
+Printf(out,fmt,...)             Formatted output
+DohEncoding(name, fn)           Register a format encoding for Printf
+
+Currently Available datatypes
+------------------------------
+NewString(char *initial)                  Strings
+NewHash()                                 Hash
+NewList()                                 List
+NewVoid(void *ptr, void (*del)(void *))   Void
+NewFile(char *file, char *mode)           File
+NewCallable(DOH *(*func)(DOH *, DOH *))   Callable object
+
+
+Odds and ends:
+
+  1.   All objects are of type 'DOH *'
+  2.   When in doubt, see rule (1)
+  3.   In certain cases, DOH performs implicit conversions
+       of 'char *' to an appropriate DOH string representation. 
+       For operations involving files, DOH works with many
+       kinds of objects including FILE *, DOH File objects,
+       and DOH strings.  Don't even ask how this works.
+
+  4.   More complete documentation is forthcoming.
+
+
+
+
+
diff --git a/trunk/Source/DOH/base.c b/trunk/Source/DOH/base.c
new file mode 100644
index 0000000..dcb0140
--- /dev/null
+++ b/trunk/Source/DOH/base.c
@@ -0,0 +1,943 @@
+/* -----------------------------------------------------------------------------
+ * base.c 
+ *
+ *     This file contains the function entry points for dispatching methods on
+ *     DOH objects.  A number of small utility functions are also included.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_base_c[] = "$Id$";
+
+#include "dohint.h"
+
+/* -----------------------------------------------------------------------------
+ * DohDelete()
+ * ----------------------------------------------------------------------------- */
+
+#ifndef SWIG_DEBUG_DELETE
+#define SWIG_DEBUG_DELETE 0
+#endif
+
+void DohDelete(DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+
+  if (!obj)
+    return;
+#if SWIG_DEBUG_DELETE
+  if (!DohCheck(b)) {
+    fputs("DOH: Fatal error. Attempt to delete a non-doh object.\n", stderr);
+    abort();
+  }
+#endif
+  if (b->flag_intern)
+    return;
+  assert(b->refcount > 0);
+  b->refcount--;
+  if (b->refcount <= 0) {
+    objinfo = b->type;
+    if (objinfo->doh_del) {
+      (objinfo->doh_del) (b);
+    } else {
+      if (b->data)
+	DohFree(b->data);
+    }
+    DohObjFree(b);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * DohCopy()
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohCopy(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+
+  if (!obj)
+    return 0;
+  objinfo = b->type;
+  if (objinfo->doh_copy) {
+    DohBase *bc = (DohBase *) (objinfo->doh_copy) (b);
+    if ((bc) && b->meta) {
+      bc->meta = Copy(b->meta);
+    }
+    return (DOH *) bc;
+  }
+  return 0;
+}
+
+void DohIncref(DOH *obj) {
+  Incref(obj);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohClear()
+ * ----------------------------------------------------------------------------- */
+
+void DohClear(DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_clear)
+    (objinfo->doh_clear) (b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohStr()
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohStr(const DOH *obj) {
+  char buffer[512];
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(b)) {
+    objinfo = b->type;
+    if (objinfo->doh_str) {
+      return (objinfo->doh_str) (b);
+    }
+    sprintf(buffer, "<Object '%s' at %p>", objinfo->objname, (void *) b);
+    return NewString(buffer);
+  } else {
+    return NewString(obj);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * DohDump()
+ * ----------------------------------------------------------------------------- */
+
+int DohDump(const DOH *obj, DOH *out) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_dump) {
+    return (objinfo->doh_dump) (b, out);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohLen() - Defaults to strlen() if not a DOH object
+ * ----------------------------------------------------------------------------- */
+int DohLen(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (!b)
+    return 0;
+  if (DohCheck(b)) {
+    objinfo = b->type;
+    if (objinfo->doh_len) {
+      return (objinfo->doh_len) (b);
+    }
+    return 0;
+  } else {
+    return strlen((char *) obj);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * DohHashVal()
+ * ----------------------------------------------------------------------------- */
+
+int DohHashval(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  /* obj is already checked and/or converted into DohBase* */
+  /*  if (DohCheck(b)) */
+  {
+    objinfo = b->type;
+    if (objinfo->doh_hashval) {
+      return (objinfo->doh_hashval) (b);
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohData()
+ * ----------------------------------------------------------------------------- */
+
+void *DohData(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if (objinfo->doh_data) {
+      return (objinfo->doh_data) (b);
+    }
+    return 0;
+  }
+  return (void *) obj;
+}
+
+/* -----------------------------------------------------------------------------
+ * RawData()
+ * ----------------------------------------------------------------------------- */
+
+static void *RawData(DohBase *b) {
+  DohObjInfo *objinfo = b->type;
+  return (objinfo->doh_data) ? (objinfo->doh_data) (b) : 0;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * DohCmp()
+ * ----------------------------------------------------------------------------- */
+
+int DohCmp(const DOH *obj1, const DOH *obj2) {
+  DohBase *b1, *b2;
+  DohObjInfo *b1info, *b2info;
+  int c1, c2;
+  b1 = (DohBase *) obj1;
+  b2 = (DohBase *) obj2;
+  c1 = DohCheck(b1);
+  c2 = DohCheck(b2);
+  /* most of the times, obj2 is a plain c string */
+  if (!c1 || !c2) {
+    if ((b1 == 0) && (b2 == 0))
+      return 0;
+    if (b1 && !b2)
+      return 1;
+    if (!b1 && b2)
+      return -1;
+    return strcmp((char *) (c1 ? RawData(b1) : (void *) obj1), (char *) (c2 ? RawData(b2) : (void *) obj2));
+  }
+  b1info = b1->type;
+  b2info = b2->type;
+  if ((b1info == b2info) && (b1info->doh_cmp))
+    return (b1info->doh_cmp) (b1, b2);
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohEqual()
+ * ----------------------------------------------------------------------------- */
+
+int DohEqual(const DOH *obj1, const DOH *obj2) {
+  DohBase *b1 = (DohBase *) obj1;
+  DohBase *b2 = (DohBase *) obj2;
+  if (!b1) {
+    return !b2;
+  } else if (!b2) {
+    return 0;
+  } else {
+    DohObjInfo *b1info = 0;
+    DohObjInfo *b2info = 0;
+    if (DohCheck(b1)) {
+      b1info = b1->type;
+      if (DohCheck(b2)) {
+	b2info = b2->type;
+      } else {
+	int len = (b1info->doh_len) (b1);
+	char *cobj = (char *) obj2;
+	return len == (int) strlen(cobj) ? (memcmp(RawData(b1), cobj, len) == 0) : 0;
+      }
+    } else if (DohCheck(b2)) {
+      int len = (b2->type->doh_len) (b2);
+      char *cobj = (char *) obj1;
+      return len == (int) strlen(cobj) ? (memcmp(RawData(b2), cobj, len) == 0) : 0;
+    } else {
+      return strcmp((char *) obj1, (char *) obj2) == 0;
+    }
+
+    if (!b1info) {
+      return obj1 == obj2;
+    } else if ((b1info == b2info)) {
+      return b1info->doh_equal ? (b1info->doh_equal) (b1, b2) : (b1info->doh_cmp ? (b1info->doh_cmp) (b1, b2) == 0 : (b1 == b2));
+    } else {
+      return 0;
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * DohFirst()
+ * ----------------------------------------------------------------------------- */
+
+DohIterator DohFirst(DOH *obj) {
+  DohIterator iter;
+  DohBase *b;
+  DohObjInfo *binfo;
+
+  b = (DohBase *) obj;
+  if (DohCheck(b)) {
+    binfo = b->type;
+    if (binfo->doh_first) {
+      return (binfo->doh_first) (b);
+    }
+  }
+  iter.object = 0;
+  iter.item = 0;
+  iter.key = 0;
+  iter._current = 0;
+  iter._index = 0;
+  return iter;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohNext()
+ * ----------------------------------------------------------------------------- */
+
+DohIterator DohNext(DohIterator iter) {
+  DohIterator niter;
+
+  if (iter.object) {
+    DohBase *b;
+    DohObjInfo *binfo;
+
+    b = (DohBase *) iter.object;
+    binfo = b->type;
+    if (binfo->doh_next) {
+      return (binfo->doh_next) (iter);
+    }
+  }
+  niter = iter;
+  return niter;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohIsMapping()
+ * ----------------------------------------------------------------------------- */
+int DohIsMapping(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (!DohCheck(b))
+    return 0;
+  objinfo = b->type;
+  if (objinfo->doh_hash)
+    return 1;
+  else
+    return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetattr()
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohGetattr(DOH *obj, const DOH *name) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_hash && objinfo->doh_hash->doh_getattr) {
+    DOH *r = (objinfo->doh_hash->doh_getattr) (b, (DOH *) name);
+    return (r == DohNone) ? 0 : r;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetattr()
+ * ----------------------------------------------------------------------------- */
+
+int DohSetattr(DOH *obj, const DOH *name, const DOH *value) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_hash && objinfo->doh_hash->doh_setattr) {
+    return (objinfo->doh_hash->doh_setattr) (b, (DOH *) name, (DOH *) value);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohDelattr()
+ * ----------------------------------------------------------------------------- */
+
+int DohDelattr(DOH *obj, const DOH *name) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_hash && objinfo->doh_hash->doh_delattr) {
+    return (objinfo->doh_hash->doh_delattr) (b, (DOH *) name);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohCheckattr()
+ * ----------------------------------------------------------------------------- */
+
+int DohCheckattr(DOH *obj, const DOH *name, const DOH *value) {
+  DOH *attr = Getattr(obj,name);
+  if (!attr) return 0;
+  return DohEqual(attr,value);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohKeys()
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohKeys(DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo && objinfo->doh_hash->doh_keys) {
+    return (objinfo->doh_hash->doh_keys) (b);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetInt()
+ * ----------------------------------------------------------------------------- */
+
+int DohGetInt(DOH *obj, const DOH *name) {
+  DOH *val;
+  val = Getattr(obj, (DOH *) name);
+  if (!val)
+    return 0;
+  if (DohIsString(val)) {
+    return atoi((char *) Data(val));
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetDouble()
+ * ----------------------------------------------------------------------------- */
+
+double DohGetDouble(DOH *obj, const DOH *name) {
+  DOH *val;
+  val = Getattr(obj, (DOH *) name);
+  if (!val)
+    return 0;
+  if (DohIsString(val)) {
+    return atof((char *) Data(val));
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetChar()
+ * ----------------------------------------------------------------------------- */
+
+char *DohGetChar(DOH *obj, const DOH *name) {
+  DOH *val;
+  val = Getattr(obj, (DOH *) name);
+  if (!val)
+    return 0;
+  if (DohIsString(val)) {
+    return (char *) Data(val);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetFlagAttr() / DohGetFlag()
+ * A flag is unset if the attribute (name) does not exist on the node (obj),
+ * or it is set to "0". If the attribute is set to any other value,
+ * the flag is set.
+ * 
+ * DohGetFlag()     returns if the flag is set or not
+ * DohGetFlagAttr() returns the flag value if is set, NULL otherwise
+ * ----------------------------------------------------------------------------- */
+
+
+DOH *DohGetFlagAttr(DOH *obj, const DOH *name) {
+  DOH *val = Getattr(obj, (DOH *) name);
+  if (!val) {
+    return NULL;
+  } else {
+    const char *cval = Char(val);
+    if (!cval)
+      return val;
+    return (strcmp(cval, "0") != 0) ? val : NULL;
+  }
+}
+
+int DohGetFlag(DOH *obj, const DOH *name) {
+  return DohGetFlagAttr(obj, name) ? 1 : 0;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * DohGetVoid()
+ * ----------------------------------------------------------------------------- */
+
+void *DohGetVoid(DOH *obj, const DOH *name) {
+  DOH *val;
+  val = Getattr(obj, (DOH *) name);
+  if (!val)
+    return 0;
+  return (void *) Data(val);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetInt()
+ * ----------------------------------------------------------------------------- */
+
+void DohSetInt(DOH *obj, const DOH *name, int value) {
+  DOH *temp;
+  temp = NewStringEmpty();
+  Printf(temp, "%d", value);
+  Setattr(obj, (DOH *) name, temp);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetDouble()
+ * ----------------------------------------------------------------------------- */
+
+void DohSetDouble(DOH *obj, const DOH *name, double value) {
+  DOH *temp;
+  temp = NewStringEmpty();
+  Printf(temp, "%0.17f", value);
+  Setattr(obj, (DOH *) name, temp);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetChar()
+ * ----------------------------------------------------------------------------- */
+
+void DohSetChar(DOH *obj, const DOH *name, char *value) {
+  Setattr(obj, (DOH *) name, NewString(value));
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetFlag()
+ * ----------------------------------------------------------------------------- */
+
+void DohSetFlagAttr(DOH *obj, const DOH *name, const DOH *attr) {
+  Setattr(obj, (DOH *) name, attr ? attr : NewString("0"));
+}
+
+void DohSetFlag(DOH *obj, const DOH *name) {
+  Setattr(obj, (DOH *) name, NewString("1"));
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetVoid()
+ * ----------------------------------------------------------------------------- */
+
+void DohSetVoid(DOH *obj, const DOH *name, void *value) {
+  Setattr(obj, (DOH *) name, NewVoid(value, 0));
+}
+
+/* -----------------------------------------------------------------------------
+ * DohIsSequence()
+ * ----------------------------------------------------------------------------- */
+
+int DohIsSequence(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (!DohCheck(b))
+    return 0;
+  objinfo = b->type;
+  if (objinfo->doh_list)
+    return 1;
+  else
+    return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetitem()
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohGetitem(DOH *obj, int index) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_list && objinfo->doh_list->doh_getitem) {
+    return (objinfo->doh_list->doh_getitem) (b, index);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetitem()
+ * ----------------------------------------------------------------------------- */
+
+int DohSetitem(DOH *obj, int index, const DOH *value) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_list && objinfo->doh_list->doh_setitem) {
+    return (objinfo->doh_list->doh_setitem) (b, index, (DOH *) value);
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohDelitem()
+ * ----------------------------------------------------------------------------- */
+
+int DohDelitem(DOH *obj, int index) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_list && objinfo->doh_list->doh_delitem) {
+    return (objinfo->doh_list->doh_delitem) (b, index);
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohInsertitem()
+ * ----------------------------------------------------------------------------- */
+
+int DohInsertitem(DOH *obj, int index, const DOH *value) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_list && objinfo->doh_list->doh_insitem) {
+    return (objinfo->doh_list->doh_insitem) (b, index, (DOH *) value);
+  }
+  return -1;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * DohDelslice()
+ * ----------------------------------------------------------------------------- */
+
+int DohDelslice(DOH *obj, int sindex, int eindex) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo = b->type;
+  if (objinfo->doh_list && objinfo->doh_list->doh_delslice) {
+    return (objinfo->doh_list->doh_delslice) (b, sindex, eindex);
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohIsFile()
+ * ----------------------------------------------------------------------------- */
+
+int DohIsFile(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (!DohCheck(b))
+    return 0;
+  objinfo = b->type;
+  if (objinfo->doh_file)
+    return 1;
+  else
+    return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohRead()
+ * ----------------------------------------------------------------------------- */
+
+int DohRead(DOH *obj, void *buffer, int length) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if ((objinfo->doh_file) && (objinfo->doh_file->doh_read)) {
+      return (objinfo->doh_file->doh_read) (b, buffer, length);
+    }
+    return -1;
+  }
+  /* Hmmm.  Not a file.  Maybe it's a real FILE */
+  return fread(buffer, 1, length, (FILE *) b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohWrite()
+ * ----------------------------------------------------------------------------- */
+
+int DohWrite(DOH *obj, void *buffer, int length) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if ((objinfo->doh_file) && (objinfo->doh_file->doh_write)) {
+      return (objinfo->doh_file->doh_write) (b, buffer, length);
+    }
+    return -1;
+  }
+  /* Hmmm.  Not a file.  Maybe it's a real FILE */
+  return fwrite(buffer, 1, length, (FILE *) b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSeek()
+ * ----------------------------------------------------------------------------- */
+
+int DohSeek(DOH *obj, long offset, int whence) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if ((objinfo->doh_file) && (objinfo->doh_file->doh_seek)) {
+      return (objinfo->doh_file->doh_seek) (b, offset, whence);
+    }
+    return -1;
+  }
+  return fseek((FILE *) b, offset, whence);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohTell()
+ * ----------------------------------------------------------------------------- */
+
+long DohTell(DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if ((objinfo->doh_file) && (objinfo->doh_file->doh_tell)) {
+      return (objinfo->doh_file->doh_tell) (b);
+    }
+    return -1;
+  }
+  return ftell((FILE *) b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetc()
+ * ----------------------------------------------------------------------------- */
+
+int DohGetc(DOH *obj) {
+  static DOH *lastdoh = 0;
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (obj == lastdoh) {
+    objinfo = b->type;
+    return (objinfo->doh_file->doh_getc) (b);
+  }
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if (objinfo->doh_file->doh_getc) {
+      lastdoh = obj;
+      return (objinfo->doh_file->doh_getc) (b);
+    }
+    return EOF;
+  }
+  return fgetc((FILE *) b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohPutc()
+ * ----------------------------------------------------------------------------- */
+
+int DohPutc(int ch, DOH *obj) {
+  static DOH *lastdoh = 0;
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+
+  if (obj == lastdoh) {
+    objinfo = b->type;
+    return (objinfo->doh_file->doh_putc) (b, ch);
+  }
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if (objinfo->doh_file->doh_putc) {
+      lastdoh = obj;
+      return (objinfo->doh_file->doh_putc) (b, ch);
+    }
+    return EOF;
+  }
+  return fputc(ch, (FILE *) b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohUngetc()
+ * ----------------------------------------------------------------------------- */
+
+int DohUngetc(int ch, DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if (objinfo->doh_file->doh_ungetc) {
+      return (objinfo->doh_file->doh_ungetc) (b, ch);
+    }
+    return EOF;
+  }
+  return ungetc(ch, (FILE *) b);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohClose()
+ * ----------------------------------------------------------------------------- */
+
+int DohClose(DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (DohCheck(obj)) {
+    objinfo = b->type;
+    if (objinfo->doh_file->doh_close) {
+      return (objinfo->doh_file->doh_close) (b);
+    }
+    return 0;
+  }
+  return fclose((FILE *) obj);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohIsString()
+ * ----------------------------------------------------------------------------- */
+
+int DohIsString(const DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  DohObjInfo *objinfo;
+  if (!DohCheck(b))
+    return 0;
+  objinfo = b->type;
+  if (objinfo->doh_string)
+    return 1;
+  else
+    return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohReplace()
+ * ----------------------------------------------------------------------------- */
+
+int DohReplace(DOH *src, const DOH *token, const DOH *rep, int flags) {
+  DohBase *b = (DohBase *) src;
+  DohObjInfo *objinfo;
+  if (!token)
+    return 0;
+  if (!rep)
+    rep = "";
+  if (DohIsString(src)) {
+    objinfo = b->type;
+    if (objinfo->doh_string->doh_replace) {
+      return (objinfo->doh_string->doh_replace) (b, (DOH *) token, (DOH *) rep, flags);
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohChop()
+ * ----------------------------------------------------------------------------- */
+
+void DohChop(DOH *src) {
+  DohBase *b = (DohBase *) src;
+  DohObjInfo *objinfo;
+  if (DohIsString(src)) {
+    objinfo = b->type;
+    if (objinfo->doh_string->doh_chop) {
+      (objinfo->doh_string->doh_chop) (b);
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetFile()
+ * ----------------------------------------------------------------------------- */
+void DohSetfile(DOH *ho, DOH *file) {
+  DohBase *h = (DohBase *) ho;
+  DohObjInfo *objinfo;
+  if (!h)
+    return;
+  objinfo = h->type;
+  if (objinfo->doh_setfile)
+    (objinfo->doh_setfile) (h, file);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetFile()
+ * ----------------------------------------------------------------------------- */
+DOH *DohGetfile(DOH *ho) {
+  DohBase *h = (DohBase *) ho;
+  DohObjInfo *objinfo;
+  if (!h)
+    return 0;
+  objinfo = h->type;
+  if (objinfo->doh_getfile)
+    return (objinfo->doh_getfile) (h);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetLine()
+ * ----------------------------------------------------------------------------- */
+void DohSetline(DOH *ho, int l) {
+  DohBase *h = (DohBase *) ho;
+  DohObjInfo *objinfo;
+  if (!h)
+    return;
+  objinfo = h->type;
+  if (objinfo->doh_setline)
+    (objinfo->doh_setline) (h, l);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetLine()
+ * ----------------------------------------------------------------------------- */
+int DohGetline(DOH *ho) {
+  DohBase *h = (DohBase *) ho;
+  DohObjInfo *objinfo;
+  if (!h)
+    return 0;
+  objinfo = h->type;
+  if (objinfo->doh_getline)
+    return (objinfo->doh_getline) (h);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetmeta()
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohGetmeta(DOH *ho, const DOH *name) {
+  DohBase *h = (DohBase *) ho;
+  if (!DohCheck(ho))
+    return 0;
+  if (!h->meta)
+    return 0;
+  return DohGetattr(h->meta, name);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohGetmeta()
+ * ----------------------------------------------------------------------------- */
+
+int DohSetmeta(DOH *ho, const DOH *name, const DOH *value) {
+  DohBase *h = (DohBase *) ho;
+  if (!DohCheck(ho))
+    return 0;
+  if (!h->meta)
+    h->meta = NewHash();
+  return DohSetattr(h->meta, name, value);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohDelmeta()
+ * ----------------------------------------------------------------------------- */
+
+int DohDelmeta(DOH *ho, const DOH *name) {
+  DohBase *h = (DohBase *) ho;
+  if (!DohCheck(ho))
+    return 0;
+  if (!h->meta)
+    return 0;
+  return DohDelattr(h->meta, name);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSetmark()
+ * ----------------------------------------------------------------------------- */
+
+void DohSetmark(DOH *ho, int x) {
+  DohBase *h = (DohBase *) ho;
+  h->flag_usermark = x;
+}
+
+int DohGetmark(DOH *ho) {
+  DohBase *h = (DohBase *) ho;
+  return h->flag_usermark;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohCall()
+ *
+ * Invokes a function via DOH.  A Function is represented by a hash table with
+ * the following attributes:
+ *
+ *       "builtin"    -  Pointer to built-in function (if any)
+ *
+ * (Additional attributes may be added later)
+ * 
+ * Returns a DOH object with result on success. Returns NULL on error
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohCall(DOH *func, DOH *args) {
+  DOH *result;
+  DOH *(*builtin) (DOH *);
+
+  builtin = (DOH *(*)(DOH *)) GetVoid(func, "builtin");
+  if (!builtin)
+    return 0;
+  result = (*builtin) (args);
+  return result;
+}
diff --git a/trunk/Source/DOH/doh.h b/trunk/Source/DOH/doh.h
new file mode 100644
index 0000000..7ab244f
--- /dev/null
+++ b/trunk/Source/DOH/doh.h
@@ -0,0 +1,439 @@
+/* -----------------------------------------------------------------------------
+ * doh.h
+ *
+ *     This file describes of the externally visible functions in DOH.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.
+ *
+ * $Id$
+ * ----------------------------------------------------------------------------- */
+
+#ifndef _DOH_H
+#define _DOH_H
+
+#ifndef MACSWIG
+#include "swigconfig.h"
+#endif
+
+#include <stdio.h>
+#include <stdarg.h>
+
+/* Set the namespace prefix for DOH API functions. This can be used to control
+   visibility of the functions in libraries */
+
+/* Set this macro if you want to change DOH linkage. You would do this if you
+   wanted to hide DOH in a library using a different set of names.  Note: simply
+   change "Doh" to a new name. */
+
+/*
+#define DOH_NAMESPACE(x) Doh ## x
+*/
+
+#ifdef DOH_NAMESPACE
+
+/* Namespace control.  These macros define all of the public API names in DOH */
+
+#define DohCheck           DOH_NAMESPACE(Check)
+#define DohIntern          DOH_NAMESPACE(Intern)
+#define DohDelete          DOH_NAMESPACE(Delete)
+#define DohCopy            DOH_NAMESPACE(Copy)
+#define DohClear           DOH_NAMESPACE(Clear)
+#define DohStr             DOH_NAMESPACE(Str)
+#define DohData            DOH_NAMESPACE(Data)
+#define DohDump            DOH_NAMESPACE(Dump)
+#define DohLen             DOH_NAMESPACE(Len)
+#define DohHashval         DOH_NAMESPACE(Hashval)
+#define DohCmp             DOH_NAMESPACE(Cmp)
+#define DohEqual           DOH_NAMESPACE(Equal)
+#define DohIncref          DOH_NAMESPACE(Incref)
+#define DohCheckattr       DOH_NAMESPACE(Checkattr)
+#define DohSetattr         DOH_NAMESPACE(Setattr)
+#define DohDelattr         DOH_NAMESPACE(Delattr)
+#define DohKeys            DOH_NAMESPACE(Keys)
+#define DohGetInt          DOH_NAMESPACE(GetInt)
+#define DohGetDouble       DOH_NAMESPACE(GetDouble)
+#define DohGetChar         DOH_NAMESPACE(GetChar)
+#define DohSetChar         DOH_NAMESPACE(SetChar)
+#define DohSetInt          DOH_NAMESPACE(SetInt)
+#define DohSetDouble       DOH_NAMESPACE(SetDouble)
+#define DohSetVoid         DOH_NAMESPACE(SetVoid)
+#define DohGetVoid         DOH_NAMESPACE(GetVoid)
+#define DohGetitem         DOH_NAMESPACE(Getitem)
+#define DohSetitem         DOH_NAMESPACE(Setitem)
+#define DohDelitem         DOH_NAMESPACE(Delitem)
+#define DohInsertitem      DOH_NAMESPACE(Insertitem)
+#define DohDelslice        DOH_NAMESPACE(Delslice)
+#define DohWrite           DOH_NAMESPACE(Write)
+#define DohRead            DOH_NAMESPACE(Read)
+#define DohSeek            DOH_NAMESPACE(Seek)
+#define DohTell            DOH_NAMESPACE(Tell)
+#define DohGetc            DOH_NAMESPACE(Getc)
+#define DohPutc            DOH_NAMESPACE(Putc)
+#define DohUngetc          DOH_NAMESPACE(Ungetc)
+#define DohGetline         DOH_NAMESPACE(Getline)
+#define DohSetline         DOH_NAMESPACE(Setline)
+#define DohGetfile         DOH_NAMESPACE(Getfile)
+#define DohSetfile         DOH_NAMESPACE(Setfile)
+#define DohReplace         DOH_NAMESPACE(Replace)
+#define DohChop            DOH_NAMESPACE(Chop)
+#define DohGetmeta         DOH_NAMESPACE(Getmeta)
+#define DohSetmeta         DOH_NAMESPACE(Setmeta)
+#define DohDelmeta         DOH_NAMESPACE(Delmeta)
+#define DohEncoding        DOH_NAMESPACE(Encoding)
+#define DohPrintf          DOH_NAMESPACE(Printf)
+#define DohvPrintf         DOH_NAMESPACE(vPrintf)
+#define DohPrintv          DOH_NAMESPACE(Printv)
+#define DohReadline        DOH_NAMESPACE(Readline)
+#define DohIsMapping       DOH_NAMESPACE(IsMapping)
+#define DohIsSequence      DOH_NAMESPACE(IsSequence)
+#define DohIsString        DOH_NAMESPACE(IsString)
+#define DohIsFile          DOH_NAMESPACE(IsFile)
+#define DohNewString       DOH_NAMESPACE(NewString)
+#define DohNewStringEmpty  DOH_NAMESPACE(NewStringEmpty)
+#define DohNewStringWithSize  DOH_NAMESPACE(NewStringWithSize)
+#define DohNewStringf      DOH_NAMESPACE(NewStringf)
+#define DohStrcmp          DOH_NAMESPACE(Strcmp)
+#define DohStrncmp         DOH_NAMESPACE(Strncmp)
+#define DohStrstr          DOH_NAMESPACE(Strstr)
+#define DohStrchr          DOH_NAMESPACE(Strchr)
+#define DohNewFile         DOH_NAMESPACE(NewFile)
+#define DohNewFileFromFile DOH_NAMESPACE(NewFileFromFile)
+#define DohNewFileFromFd   DOH_NAMESPACE(NewFileFromFd)
+#define DohFileErrorDisplay   DOH_NAMESPACE(FileErrorDisplay)
+#define DohClose           DOH_NAMESPACE(Close)
+#define DohCopyto          DOH_NAMESPACE(Copyto)
+#define DohNewList         DOH_NAMESPACE(NewList)
+#define DohNewHash         DOH_NAMESPACE(NewHash)
+#define DohNewVoid         DOH_NAMESPACE(NewVoid)
+#define DohSplit           DOH_NAMESPACE(Split)
+#define DohSplitLines      DOH_NAMESPACE(SplitLines)
+#define DohNone            DOH_NAMESPACE(None)
+#define DohCall            DOH_NAMESPACE(Call)
+#define DohObjMalloc       DOH_NAMESPACE(ObjMalloc)
+#define DohObjFree         DOH_NAMESPACE(ObjFree)
+#define DohMemoryDebug     DOH_NAMESPACE(MemoryDebug)
+#define DohStringType      DOH_NAMESPACE(StringType)
+#define DohListType        DOH_NAMESPACE(ListType)
+#define DohHashType        DOH_NAMESPACE(HashType)
+#define DohFileType        DOH_NAMESPACE(FileType)
+#define DohVoidType        DOH_NAMESPACE(VoidType)
+#define DohIterator        DOH_NAMESPACE(Iterator)
+#define DohFirst           DOH_NAMESPACE(First)
+#define DohNext            DOH_NAMESPACE(Next)
+#endif
+
+#define DOH_MAJOR_VERSION 0
+#define DOH_MINOR_VERSION 1
+
+typedef void DOH;
+
+/*
+ * With dynamic typing, all DOH objects are technically of type 'void *'.
+ * However, to clarify the reading of source code, the following symbolic
+ * names are used.
+ */
+
+#define DOHString          DOH
+#define DOHList            DOH
+#define DOHHash            DOH
+#define DOHFile            DOH
+#define DOHVoid            DOH
+#define DOHString_or_char  DOH
+#define DOHObj_or_char     DOH
+
+#define DOH_BEGIN          -1
+#define DOH_END            -2
+#define DOH_CUR            -3
+#define DOH_CURRENT        -3
+
+/* Iterator objects */
+
+typedef struct {
+  void *key;			/* Current key (if any)       */
+  void *item;			/* Current item               */
+  void *object;			/* Object being iterated over */
+  void *_current;		/* Internal use */
+  int _index;			/* Internal use */
+} DohIterator;
+
+/* Memory management */
+
+#ifndef DohMalloc
+#define DohMalloc malloc
+#endif
+#ifndef DohRealloc
+#define DohRealloc realloc
+#endif
+#ifndef DohFree
+#define DohFree free
+#endif
+
+extern int DohCheck(const DOH *ptr);	/* Check if a DOH object */
+extern void DohIntern(DOH *);	/* Intern an object      */
+
+/* Basic object methods.  Common to most objects */
+
+extern void DohDelete(DOH *obj);	/* Delete an object      */
+extern DOH *DohCopy(const DOH *obj);
+extern void DohClear(DOH *obj);
+extern DOHString *DohStr(const DOH *obj);
+extern void *DohData(const DOH *obj);
+extern int DohDump(const DOH *obj, DOHFile * out);
+extern int DohLen(const DOH *obj);
+extern int DohHashval(const DOH *obj);
+extern int DohCmp(const DOH *obj1, const DOH *obj2);
+extern int DohEqual(const DOH *obj1, const DOH *obj2);
+extern void DohIncref(DOH *obj);
+
+/* Mapping methods */
+
+extern DOH *DohGetattr(DOH *obj, const DOHString_or_char *name);
+extern int DohSetattr(DOH *obj, const DOHString_or_char *name, const DOHObj_or_char * value);
+extern int DohDelattr(DOH *obj, const DOHString_or_char *name);
+extern int DohCheckattr(DOH *obj, const DOHString_or_char *name, const DOHString_or_char *value);
+extern DOH *DohKeys(DOH *obj);
+extern int DohGetInt(DOH *obj, const DOHString_or_char *name);
+extern void DohSetInt(DOH *obj, const DOHString_or_char *name, int);
+extern double DohGetDouble(DOH *obj, const DOHString_or_char *name);
+extern void DohSetDouble(DOH *obj, const DOHString_or_char *name, double);
+extern char *DohGetChar(DOH *obj, const DOHString_or_char *name);
+extern void DohSetChar(DOH *obj, const DOH *name, char *value);
+extern void *DohGetFlagAttr(DOH *obj, const DOHString_or_char *name);
+extern int DohGetFlag(DOH *obj, const DOHString_or_char *name);
+extern void DohSetFlagAttr(DOH *obj, const DOHString_or_char *name, const DOHString_or_char *attr);
+extern void DohSetFlag(DOH *obj, const DOHString_or_char *name);
+extern void *DohGetVoid(DOH *obj, const DOHString_or_char *name);
+extern void DohSetVoid(DOH *obj, const DOHString_or_char *name, void *value);
+
+/* Sequence methods */
+
+extern DOH *DohGetitem(DOH *obj, int index);
+extern int DohSetitem(DOH *obj, int index, const DOHObj_or_char * value);
+extern int DohDelitem(DOH *obj, int index);
+extern int DohInsertitem(DOH *obj, int index, const DOHObj_or_char * value);
+extern int DohDelslice(DOH *obj, int sindex, int eindex);
+
+/* File methods */
+
+extern int DohWrite(DOHFile * obj, void *buffer, int length);
+extern int DohRead(DOHFile * obj, void *buffer, int length);
+extern int DohSeek(DOHFile * obj, long offset, int whence);
+extern long DohTell(DOHFile * obj);
+extern int DohGetc(DOHFile * obj);
+extern int DohPutc(int ch, DOHFile * obj);
+extern int DohUngetc(int ch, DOHFile * obj);
+
+
+
+/* Iterators */
+extern DohIterator DohFirst(DOH *obj);
+extern DohIterator DohNext(DohIterator x);
+
+/* Positional */
+
+extern int DohGetline(DOH *obj);
+extern void DohSetline(DOH *obj, int line);
+extern DOH *DohGetfile(DOH *obj);
+extern void DohSetfile(DOH *obj, DOH *file);
+
+  /* String Methods */
+
+extern int DohReplace(DOHString * src, const DOHString_or_char *token, const DOHString_or_char *rep, int flags);
+extern void DohChop(DOHString * src);
+
+/* Meta-variables */
+extern DOH *DohGetmeta(DOH *, const DOH *);
+extern int DohSetmeta(DOH *, const DOH *, const DOH *value);
+extern int DohDelmeta(DOH *, const DOH *);
+
+  /* Utility functions */
+
+extern void DohEncoding(char *name, DOH *(*fn) (DOH *s));
+extern int DohPrintf(DOHFile * obj, const char *format, ...);
+extern int DohvPrintf(DOHFile * obj, const char *format, va_list ap);
+extern int DohPrintv(DOHFile * obj, ...);
+extern DOH *DohReadline(DOHFile * in);
+
+  /* Miscellaneous */
+
+extern int DohIsMapping(const DOH *obj);
+extern int DohIsSequence(const DOH *obj);
+extern int DohIsString(const DOH *obj);
+extern int DohIsFile(const DOH *obj);
+
+extern void DohSetmark(DOH *obj, int x);
+extern int DohGetmark(DOH *obj);
+
+/* -----------------------------------------------------------------------------
+ * Strings.
+ * ----------------------------------------------------------------------------- */
+
+extern DOHString *DohNewStringEmpty();
+extern DOHString *DohNewString(const DOH *c);
+extern DOHString *DohNewStringWithSize(const DOH *c, int len);
+extern DOHString *DohNewStringf(const DOH *fmt, ...);
+
+extern int DohStrcmp(const DOHString_or_char *s1, const DOHString_or_char *s2);
+extern int DohStrncmp(const DOHString_or_char *s1, const DOHString_or_char *s2, int n);
+extern char *DohStrstr(const DOHString_or_char *s1, const DOHString_or_char *s2);
+extern char *DohStrchr(const DOHString_or_char *s1, int ch);
+
+/* String replacement flags */
+
+#define   DOH_REPLACE_ANY         0x01
+#define   DOH_REPLACE_NOQUOTE     0x02
+#define   DOH_REPLACE_ID          0x04
+#define   DOH_REPLACE_FIRST       0x08
+#define   DOH_REPLACE_ID_BEGIN    0x10
+#define   DOH_REPLACE_ID_END      0x20
+
+#define Replaceall(s,t,r)  DohReplace(s,t,r,DOH_REPLACE_ANY)
+#define Replaceid(s,t,r)   DohReplace(s,t,r,DOH_REPLACE_ID)
+
+/* -----------------------------------------------------------------------------
+ * Files
+ * ----------------------------------------------------------------------------- */
+
+extern DOHFile *DohNewFile(DOH *file, const char *mode);
+extern DOHFile *DohNewFileFromFile(FILE *f);
+extern DOHFile *DohNewFileFromFd(int fd);
+extern void DohFileErrorDisplay(DOHString * filename);
+extern int DohClose(DOH *file);
+extern int DohCopyto(DOHFile * input, DOHFile * output);
+
+
+/* -----------------------------------------------------------------------------
+ * List
+ * ----------------------------------------------------------------------------- */
+
+extern DOHList *DohNewList();
+extern void DohSortList(DOH *lo, int (*cmp) (const DOH *, const DOH *));
+
+/* -----------------------------------------------------------------------------
+ * Hash
+ * ----------------------------------------------------------------------------- */
+
+extern DOHHash *DohNewHash();
+
+/* -----------------------------------------------------------------------------
+ * Void
+ * ----------------------------------------------------------------------------- */
+
+extern DOHVoid *DohNewVoid(void *ptr, void (*del) (void *));
+extern DOHList *DohSplit(DOHFile * input, char ch, int nsplits);
+extern DOHList *DohSplitLines(DOHFile * input);
+extern DOH *DohNone;
+
+extern void DohMemoryDebug(void);
+
+#ifndef DOH_LONG_NAMES
+/* Macros to invoke the above functions.  Includes the location of
+   the caller to simplify debugging if something goes wrong */
+
+#define Delete             DohDelete
+#define Copy               DohCopy
+#define Clear              DohClear
+#define Str                DohStr
+#define Dump               DohDump
+#define Getattr            DohGetattr
+#define Setattr            DohSetattr
+#define Delattr            DohDelattr
+#define Checkattr          DohCheckattr
+#define Hashval            DohHashval
+#define Getitem            DohGetitem
+#define Setitem            DohSetitem
+#define Delitem            DohDelitem
+#define Insert             DohInsertitem
+#define Delslice           DohDelslice
+#define Append(s,x)        DohInsertitem(s,DOH_END,x)
+#define Push(s,x)          DohInsertitem(s,DOH_BEGIN,x)
+#define Len                DohLen
+#define Data               DohData
+#define Char               (char *) Data
+#define Cmp                DohCmp
+#define Equal              DohEqual
+#define Setline            DohSetline
+#define Getline            DohGetline
+#define Setfile            DohSetfile
+#define Getfile            DohGetfile
+#define Write              DohWrite
+#define Read               DohRead
+#define Seek               DohSeek
+#define Tell               DohTell
+#define Printf             DohPrintf
+#define Printv             DohPrintv
+#define Getc               DohGetc
+#define Putc               DohPutc
+#define Ungetc             DohUngetc
+
+/* #define StringPutc         DohStringPutc */
+/* #define StringGetc         DohStringGetc */
+/* #define StringUngetc       DohStringUngetc */
+/* #define StringAppend       Append */
+/* #define StringLen          DohStringLen */
+/* #define StringChar         DohStringChar */
+/* #define StringEqual        DohStringEqual */
+
+#define Close              DohClose
+#define vPrintf            DohvPrintf
+#define GetInt             DohGetInt
+#define GetDouble          DohGetDouble
+#define GetChar            DohGetChar
+#define GetVoid            DohGetVoid
+#define GetFlagAttr        DohGetFlagAttr
+#define GetFlag            DohGetFlag
+#define SetInt             DohSetInt
+#define SetDouble          DohSetDouble
+#define SetChar            DohSetattr
+#define SetVoid            DohSetVoid
+#define SetFlagAttr        DohSetFlagAttr
+#define SetFlag            DohSetFlag
+#define UnsetFlag(o,n)     DohSetFlagAttr(o,n,NULL)
+#define ClearFlag(o,n)     DohSetFlagAttr(o,n,"")
+#define Readline           DohReadline
+#define Replace            DohReplace
+#define Chop               DohChop
+#define Getmeta            DohGetmeta
+#define Setmeta            DohSetmeta
+#define Delmeta            DohDelmeta
+#define NewString          DohNewString
+#define NewStringEmpty     DohNewStringEmpty
+#define NewStringWithSize  DohNewStringWithSize
+#define NewStringf         DohNewStringf
+#define NewHash            DohNewHash
+#define NewList            DohNewList
+#define NewFile            DohNewFile
+#define NewFileFromFile    DohNewFileFromFile
+#define NewFileFromFd      DohNewFileFromFd
+#define FileErrorDisplay   DohFileErrorDisplay
+#define Close              DohClose
+#define NewVoid            DohNewVoid
+#define Keys               DohKeys
+#define Strcmp             DohStrcmp
+#define Strncmp            DohStrncmp
+#define Strstr             DohStrstr
+#define Strchr             DohStrchr
+#define Copyto             DohCopyto
+#define Split              DohSplit
+#define SplitLines         DohSplitLines
+#define Setmark            DohSetmark
+#define Getmark            DohGetmark
+#define None               DohNone
+#define Call               DohCall
+#define First              DohFirst
+#define Next               DohNext
+#define Iterator           DohIterator
+#define SortList           DohSortList
+#endif
+
+#ifdef NIL
+#undef NIL
+#endif
+
+#define NIL  (char *) NULL
+
+
+#endif				/* DOH_H */
diff --git a/trunk/Source/DOH/dohint.h b/trunk/Source/DOH/dohint.h
new file mode 100644
index 0000000..1fc5eb7
--- /dev/null
+++ b/trunk/Source/DOH/dohint.h
@@ -0,0 +1,133 @@
+
+/* -----------------------------------------------------------------------------
+ * dohint.h
+ *
+ *     This file describes internally managed objects.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.
+ *
+ * $Id$
+ * ----------------------------------------------------------------------------- */
+
+#ifndef _DOHINT_H
+#define _DOHINT_H
+
+#include "doh.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <ctype.h>
+#include <stdarg.h>
+
+/* Hash objects */
+typedef struct {
+  DOH *(*doh_getattr) (DOH *obj, DOH *name);	/* Get attribute */
+  int (*doh_setattr) (DOH *obj, DOH *name, DOH *value);	/* Set attribute */
+  int (*doh_delattr) (DOH *obj, DOH *name);	/* Del attribute */
+  DOH *(*doh_keys) (DOH *obj);	/* All keys as a list */
+} DohHashMethods;
+
+/* List objects */
+typedef struct {
+  DOH *(*doh_getitem) (DOH *obj, int index);	/* Get item      */
+  int (*doh_setitem) (DOH *obj, int index, DOH *value);	/* Set item      */
+  int (*doh_delitem) (DOH *obj, int index);	/* Delete item   */
+  int (*doh_insitem) (DOH *obj, int index, DOH *value);	/* Insert item   */
+  int (*doh_delslice) (DOH *obj, int sindex, int eindex);	/* Delete slice  */
+} DohListMethods;
+
+/* File methods */
+typedef struct {
+  int (*doh_read) (DOH *obj, void *buffer, int nbytes);	/* Read bytes */
+  int (*doh_write) (DOH *obj, void *buffer, int nbytes);	/* Write bytes */
+  int (*doh_putc) (DOH *obj, int ch);	/* Put character */
+  int (*doh_getc) (DOH *obj);	/* Get character */
+  int (*doh_ungetc) (DOH *obj, int ch);	/* Unget character */
+  int (*doh_seek) (DOH *obj, long offset, int whence);	/* Seek */
+  long (*doh_tell) (DOH *obj);	/* Tell */
+  int (*doh_close) (DOH *obj);	/* Close */
+} DohFileMethods;
+
+/* String methods */
+typedef struct {
+  int (*doh_replace) (DOH *obj, DOH *old, DOH *rep, int flags);
+  void (*doh_chop) (DOH *obj);
+} DohStringMethods;
+
+/* -----------------------------------------------------------------------------
+ * DohObjInfo
+ * ----------------------------------------------------------------------------- */
+
+typedef struct DohObjInfo {
+  char *objname;		/* Object name        */
+
+  /* Basic object methods */
+  void (*doh_del) (DOH *obj);	/* Delete object      */
+  DOH *(*doh_copy) (DOH *obj);	/* Copy and object    */
+  void (*doh_clear) (DOH *obj);	/* Clear an object    */
+
+  /* I/O methods */
+  DOH *(*doh_str) (DOH *obj);	/* Make a full string */
+  void *(*doh_data) (DOH *obj);	/* Return raw data    */
+  int (*doh_dump) (DOH *obj, DOH *out);	/* Serialize on out   */
+
+  /* Length and hash values */
+  int (*doh_len) (DOH *obj);
+  int (*doh_hashval) (DOH *obj);
+
+  /* Compare */
+  int (*doh_cmp) (DOH *obj1, DOH *obj2);
+
+  /* Equal */
+  int (*doh_equal) (DOH *obj1, DOH *obj2);
+
+  /* Iterators */
+  DohIterator (*doh_first) (DOH *obj);
+  DohIterator (*doh_next) (DohIterator);
+
+  /* Positional */
+  void (*doh_setfile) (DOH *obj, DOHString_or_char *file);
+  DOH *(*doh_getfile) (DOH *obj);
+  void (*doh_setline) (DOH *obj, int line);
+  int (*doh_getline) (DOH *obj);
+
+  DohHashMethods *doh_hash;	/* Hash methods       */
+  DohListMethods *doh_list;	/* List methods       */
+  DohFileMethods *doh_file;	/* File methods       */
+  DohStringMethods *doh_string;	/* String methods     */
+  void *doh_reserved;		/* Reserved           */
+  void *clientdata;		/* User data          */
+} DohObjInfo;
+
+typedef struct {
+  void *data;			/* Data pointer */
+  DohObjInfo *type;
+  void *meta;			/* Meta data */
+  unsigned int flag_intern:1;	/* Interned object */
+  unsigned int flag_marked:1;	/* Mark flag. Used to avoid recursive loops in places */
+  unsigned int flag_user:1;	/* User flag */
+  unsigned int flag_usermark:1;	/* User marked */
+  unsigned int refcount:28;	/* Reference count (max 16 million) */
+} DohBase;
+
+/* Macros for decrefing and increfing (safe for null objects). */
+
+#define Decref(a)         if (a) ((DohBase *) a)->refcount--
+#define Incref(a)         if (a) ((DohBase *) a)->refcount++
+#define Refcount(a)       ((DohBase *) a)->refcount
+
+/* Macros for manipulating objects in a safe manner */
+#define ObjData(a)        ((DohBase *)a)->data
+#define ObjSetMark(a,x)   ((DohBase *)a)->flag_marked = x
+#define ObjGetMark(a)     ((DohBase *)a)->flag_marked
+#define ObjType(a)        ((DohBase *)a)->type
+
+extern DOH *DohObjMalloc(DohObjInfo *type, void *data);	/* Allocate a DOH object */
+extern void DohObjFree(DOH *ptr);	/* Free a DOH object     */
+
+#endif				/* DOHINT_H */
diff --git a/trunk/Source/DOH/file.c b/trunk/Source/DOH/file.c
new file mode 100644
index 0000000..8c53978
--- /dev/null
+++ b/trunk/Source/DOH/file.c
@@ -0,0 +1,296 @@
+/* ----------------------------------------------------------------------------- 
+ * file.c
+ *
+ *     This file implements a file-like object that can be built around an 
+ *     ordinary FILE * or integer file descriptor.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_file_c[] = "$Id$";
+
+#include "dohint.h"
+
+#ifdef DOH_INTFILE
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+typedef struct {
+  FILE *filep;
+  int fd;
+  int closeondel;
+} DohFile;
+
+/* -----------------------------------------------------------------------------
+ * DelFile()
+ * ----------------------------------------------------------------------------- */
+
+static void DelFile(DOH *fo) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->closeondel) {
+    if (f->filep) {
+      fclose(f->filep);
+    }
+#ifdef DOH_INTFILE
+    if (f->fd) {
+      close(f->fd);
+    }
+#endif
+  }
+  DohFree(f);
+}
+
+/* -----------------------------------------------------------------------------
+ * File_read()
+ * ----------------------------------------------------------------------------- */
+
+static int File_read(DOH *fo, void *buffer, int len) {
+  DohFile *f = (DohFile *) ObjData(fo);
+
+  if (f->filep) {
+    return fread(buffer, 1, len, f->filep);
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    return read(f->fd, buffer, len);
+#endif
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_write()
+ * ----------------------------------------------------------------------------- */
+
+static int File_write(DOH *fo, void *buffer, int len) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    int ret = (int) fwrite(buffer, 1, len, f->filep);
+    int err = (ret != len) ? ferror(f->filep) : 0;
+    return err ? -1 : ret;
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    return write(f->fd, buffer, len);
+#endif
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_seek()
+ * ----------------------------------------------------------------------------- */
+
+static int File_seek(DOH *fo, long offset, int whence) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    return fseek(f->filep, offset, whence);
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    return lseek(f->fd, offset, whence);
+#endif
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_tell()
+ * ----------------------------------------------------------------------------- */
+
+static long File_tell(DOH *fo) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    return ftell(f->filep);
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    return lseek(f->fd, 0, SEEK_CUR);
+#endif
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_putc()
+ * ----------------------------------------------------------------------------- */
+
+static int File_putc(DOH *fo, int ch) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    return fputc(ch, f->filep);
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    char c;
+    c = (char) ch;
+    return write(f->fd, &c, 1);
+#endif
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_getc()
+ * ----------------------------------------------------------------------------- */
+
+static int File_getc(DOH *fo) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    return fgetc(f->filep);
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    unsigned char c;
+    if (read(f->fd, &c, 1) < 0)
+      return EOF;
+    return c;
+#endif
+  }
+  return EOF;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_ungetc()
+ *
+ * Put a character back onto the input
+ * ----------------------------------------------------------------------------- */
+
+static int File_ungetc(DOH *fo, int ch) {
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    return ungetc(ch, f->filep);
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    /* Not implemented yet */
+#endif
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * File_close()
+ *
+ * Close the file
+ * ----------------------------------------------------------------------------- */
+
+static int File_close(DOH *fo) {
+  int ret = 0;
+  DohFile *f = (DohFile *) ObjData(fo);
+  if (f->filep) {
+    ret = fclose(f->filep);
+    f->filep = 0;
+  } else if (f->fd) {
+#ifdef DOH_INTFILE
+    ret = close(f->fd);
+    f->fd = 0;
+#endif
+  }
+  return ret;
+}
+
+static DohFileMethods FileFileMethods = {
+  File_read,
+  File_write,
+  File_putc,
+  File_getc,
+  File_ungetc,
+  File_seek,
+  File_tell,
+  File_close,			/* close */
+};
+
+static DohObjInfo DohFileType = {
+  "DohFile",			/* objname      */
+  DelFile,			/* doh_del      */
+  0,				/* doh_copy     */
+  0,				/* doh_clear    */
+  0,				/* doh_str      */
+  0,				/* doh_data     */
+  0,				/* doh_dump     */
+  0,				/* doh_len      */
+  0,				/* doh_hash     */
+  0,				/* doh_cmp      */
+  0,				/* doh_equal    */
+  0,				/* doh_first    */
+  0,				/* doh_next     */
+  0,				/* doh_setfile  */
+  0,				/* doh_getfile  */
+  0,				/* doh_setline  */
+  0,				/* doh_getline  */
+  0,				/* doh_mapping  */
+  0,				/* doh_sequence */
+  &FileFileMethods,		/* doh_file     */
+  0,				/* doh_string   */
+  0,				/* doh_callable */
+  0,				/* doh_position */
+};
+
+/* -----------------------------------------------------------------------------
+ * NewFile()
+ *
+ * Create a new file from a given filename and mode.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohNewFile(DOH *fn, const char *mode) {
+  DohFile *f;
+  FILE *file;
+  char *filename;
+
+  filename = Char(fn);
+  file = fopen(filename, mode);
+  if (!file)
+    return 0;
+
+  f = (DohFile *) DohMalloc(sizeof(DohFile));
+  if (!f) {
+    fclose(file);
+    return 0;
+  }
+  f->filep = file;
+  f->fd = 0;
+  f->closeondel = 1;
+  return DohObjMalloc(&DohFileType, f);
+}
+
+/* -----------------------------------------------------------------------------
+ * NewFileFromFile()
+ *
+ * Create a file object from an already open FILE *.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohNewFileFromFile(FILE *file) {
+  DohFile *f;
+  f = (DohFile *) DohMalloc(sizeof(DohFile));
+  if (!f)
+    return 0;
+  f->filep = file;
+  f->fd = 0;
+  f->closeondel = 0;
+  return DohObjMalloc(&DohFileType, f);
+}
+
+/* -----------------------------------------------------------------------------
+ * NewFileFromFd()
+ *
+ * Create a file object from an already open FILE *.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohNewFileFromFd(int fd) {
+  DohFile *f;
+  f = (DohFile *) DohMalloc(sizeof(DohFile));
+  if (!f)
+    return 0;
+  f->filep = 0;
+  f->fd = fd;
+  f->closeondel = 0;
+  return DohObjMalloc(&DohFileType, f);
+}
+
+/* -----------------------------------------------------------------------------
+ * FileErrorDisplay()
+ *
+ * Display cause of one of the NewFile functions failing.
+ * ----------------------------------------------------------------------------- */
+
+void DohFileErrorDisplay(DOHString * filename) {
+  Printf(stderr, "Unable to open file %s: %s\n", filename, strerror(errno));
+}
diff --git a/trunk/Source/DOH/fio.c b/trunk/Source/DOH/fio.c
new file mode 100644
index 0000000..f544cee
--- /dev/null
+++ b/trunk/Source/DOH/fio.c
@@ -0,0 +1,589 @@
+/* ----------------------------------------------------------------------------- 
+ * fio.c
+ *
+ *     This file implements a number of standard I/O operations included
+ *     formatted output, readline, and splitting.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_fio_c[] = "$Id$";
+
+#include "dohint.h"
+
+#define OBUFLEN  512
+
+static DOH *encodings = 0;	/* Encoding hash */
+
+/* -----------------------------------------------------------------------------
+ * Writen()
+ *
+ * Write's N characters of output and retries until all characters are
+ * written.  This is useful should a write operation encounter a spurious signal.
+ * ----------------------------------------------------------------------------- */
+
+static int Writen(DOH *out, void *buffer, int len) {
+  int nw = len, ret;
+  char *cb = (char *) buffer;
+  while (nw) {
+    ret = Write(out, cb, nw);
+    if (ret < 0)
+      return -1;
+    nw = nw - ret;
+    cb += ret;
+  }
+  return len;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohEncoding()
+ *
+ * Registers a new printf encoding method.  An encoder function should accept
+ * two file-like objects and operate as a filter.
+ * ----------------------------------------------------------------------------- */
+
+void DohEncoding(char *name, DOH *(*fn) (DOH *s)) {
+  if (!encodings)
+    encodings = NewHash();
+  Setattr(encodings, (void *) name, NewVoid((void *) fn, 0));
+}
+
+/* internal function for processing an encoding */
+static DOH *encode(char *name, DOH *s) {
+  DOH *handle, *ns;
+  DOH *(*fn) (DOH *);
+  long pos;
+  char *cfmt = strchr(name, ':');
+  DOH *tmp = 0;
+  if (cfmt) {
+    tmp = NewString(cfmt + 1);
+    Append(tmp, s);
+    Setfile(tmp, Getfile((DOH *) s));
+    Setline(tmp, Getline((DOH *) s));
+    *cfmt = '\0';
+  }
+  if (!encodings || !(handle = Getattr(encodings, name))) {
+    return Copy(s);
+  }
+  if (tmp)
+    s = tmp;
+  pos = Tell(s);
+  Seek(s, 0, SEEK_SET);
+  fn = (DOH *(*)(DOH *)) Data(handle);
+  ns = (*fn) (s);
+  Seek(s, pos, SEEK_SET);
+  if (tmp)
+    Delete(tmp);
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohvPrintf()
+ *
+ * DOH implementation of printf.  Output can be directed to any file-like object
+ * including bare FILE * objects.  The same formatting codes as printf are
+ * recognized with two extensions:
+ *
+ *       %s          - Prints a "char *" or the string representation of any
+ *                     DOH object.  This will implicitly result in a call to
+ *                     Str(obj).
+ *
+ *       %(encoder)* - Filters the output through an encoding function registered
+ *                     with DohEncoder().
+ *
+ * Note: This function is not particularly memory efficient with large strings.
+ * It's better to use Dump() or some other method instead.
+ * ----------------------------------------------------------------------------- */
+
+int DohvPrintf(DOH *so, const char *format, va_list ap) {
+  static char *fmt_codes = "dioxXucsSfeEgGpn";
+  int state = 0;
+  const char *p = format;
+  char newformat[256];
+  char obuffer[OBUFLEN];
+  char *fmt = 0;
+  char temp[64];
+  int widthval = 0;
+  int precval = 0;
+  int maxwidth;
+  char *w = 0;
+  int ivalue;
+  double dvalue;
+  void *pvalue;
+  char *stemp;
+  int nbytes = 0;
+  char encoder[128], *ec = 0;
+  int plevel = 0;
+
+  memset(newformat, 0, sizeof(newformat));
+
+  while (*p) {
+    switch (state) {
+    case 0:			/* Ordinary text */
+      if (*p != '%') {
+	Putc(*p, so);
+	nbytes++;
+      } else {
+	fmt = newformat;
+	widthval = 0;
+	precval = 0;
+	*(fmt++) = *p;
+	encoder[0] = 0;
+	state = 10;
+      }
+      break;
+    case 10:			/* Look for a width and precision */
+      if (isdigit((int) *p) && (*p != '0')) {
+	w = temp;
+	*(w++) = *p;
+	*(fmt++) = *p;
+	state = 20;
+      } else if (strchr(fmt_codes, *p)) {
+	/* Got one of the formatting codes */
+	p--;
+	state = 100;
+      } else if (*p == '*') {
+	/* Width field is specified in the format list */
+	widthval = va_arg(ap, int);
+	sprintf(temp, "%d", widthval);
+	for (w = temp; *w; w++) {
+	  *(fmt++) = *w;
+	}
+	state = 30;
+      } else if (*p == '%') {
+	Putc(*p, so);
+	fmt = newformat;
+	nbytes++;
+	state = 0;
+      } else if (*p == '(') {
+	++plevel;
+	ec = encoder;
+	state = 60;
+      } else {
+	*(fmt++) = *p;
+      }
+      break;
+
+    case 20:			/* Hmmm. At the start of a width field */
+      if (isdigit((int) *p)) {
+	*(w++) = *p;
+	*(fmt++) = *p;
+      } else if (strchr(fmt_codes, *p)) {
+	/* Got one of the formatting codes */
+	/* Figure out width */
+	*w = 0;
+	widthval = atoi(temp);
+	p--;
+	state = 100;
+      } else if (*p == '.') {
+	*w = 0;
+	widthval = atoi(temp);
+	w = temp;
+	*(fmt++) = *p;
+	state = 40;
+      } else {
+	/* ??? */
+	*w = 0;
+	widthval = atoi(temp);
+	state = 50;
+      }
+      break;
+
+    case 30:			/* Parsed a width from an argument.  Look for a . */
+      if (*p == '.') {
+	w = temp;
+	*(fmt++) = *p;
+	state = 40;
+      } else if (strchr(fmt_codes, *p)) {
+	/* Got one of the formatting codes */
+	/* Figure out width */
+	p--;
+	state = 100;
+      } else {
+	/* hmmm. Something else. */
+	state = 50;
+      }
+      break;
+
+    case 40:
+      /* Start of precision expected */
+      if (isdigit((int) *p) && (*p != '0')) {
+	*(fmt++) = *p;
+	*(w++) = *p;
+	state = 41;
+      } else if (*p == '*') {
+	/* Precision field is specified in the format list */
+	precval = va_arg(ap, int);
+	sprintf(temp, "%d", precval);
+	for (w = temp; *w; w++) {
+	  *(fmt++) = *w;
+	}
+	state = 50;
+      } else if (strchr(fmt_codes, *p)) {
+	p--;
+	state = 100;
+      } else {
+	*(fmt++) = *p;
+	state = 50;
+      }
+      break;
+    case 41:
+      if (isdigit((int) *p)) {
+	*(fmt++) = *p;
+	*(w++) = *p;
+      } else if (strchr(fmt_codes, *p)) {
+	/* Got one of the formatting codes */
+	/* Figure out width */
+	*w = 0;
+	precval = atoi(temp);
+	p--;
+	state = 100;
+      } else {
+	*w = 0;
+	precval = atoi(temp);
+	*(fmt++) = *p;
+	state = 50;
+      }
+      break;
+      /* Hang out, wait for format specifier */
+    case 50:
+      if (strchr(fmt_codes, *p)) {
+	p--;
+	state = 100;
+      } else {
+	*(fmt++) = *p;
+      }
+      break;
+
+      /* Got an encoding header */
+    case 60:
+      if (*p == '(') {
+	++plevel;
+	*ec = *p;
+	ec++;
+      } else if (*p == ')') {
+	--plevel;
+	if (plevel <= 0) {
+	  *ec = 0;
+	  state = 10;
+	} else {
+	  *ec = *p;
+	  ec++;
+	}
+      } else {
+	*ec = *p;
+	ec++;
+      }
+      break;
+    case 100:
+      /* Got a formatting code */
+      if (widthval < precval)
+	maxwidth = precval;
+      else
+	maxwidth = widthval;
+      if ((*p == 's') || (*p == 'S')) {	/* Null-Terminated string */
+	DOH *doh;
+	DOH *Sval;
+	DOH *enc = 0;
+	doh = va_arg(ap, DOH *);
+	if (DohCheck(doh)) {
+	  /* Is a DOH object. */
+	  if (DohIsString(doh)) {
+	    Sval = doh;
+	  } else {
+	    Sval = Str(doh);
+	  }
+	  if (strlen(encoder)) {
+	    enc = encode(encoder, Sval);
+	    maxwidth = maxwidth + strlen(newformat) + Len(enc);
+	  } else {
+	    maxwidth = maxwidth + strlen(newformat) + Len(Sval);
+	  }
+	  *(fmt++) = 's';
+	  *fmt = 0;
+	  if ((maxwidth + 1) < OBUFLEN) {
+	    stemp = obuffer;
+	  } else {
+	    stemp = (char *) DohMalloc(maxwidth + 1);
+	  }
+	  if (enc) {
+	    nbytes += sprintf(stemp, newformat, Data(enc));
+	  } else {
+	    nbytes += sprintf(stemp, newformat, Data(Sval));
+	  }
+	  if (Writen(so, stemp, strlen(stemp)) < 0)
+	    return -1;
+	  if ((DOH *) Sval != doh) {
+	    Delete(Sval);
+	  }
+	  if (enc)
+	    Delete(enc);
+	  if (*p == 'S') {
+	    Delete(doh);
+	  }
+	  if (stemp != obuffer) {
+	    DohFree(stemp);
+	  }
+	} else {
+	  if (!doh)
+	    doh = (char *) "";
+
+	  if (strlen(encoder)) {
+	    DOH *s = NewString(doh);
+	    Seek(s, 0, SEEK_SET);
+	    enc = encode(encoder, s);
+	    Delete(s);
+	    doh = Char(enc);
+	  } else {
+	    enc = 0;
+	  }
+	  maxwidth = maxwidth + strlen(newformat) + strlen((char *) doh);
+	  *(fmt++) = 's';
+	  *fmt = 0;
+	  if ((maxwidth + 1) < OBUFLEN) {
+	    stemp = obuffer;
+	  } else {
+	    stemp = (char *) DohMalloc(maxwidth + 1);
+	  }
+	  nbytes += sprintf(stemp, newformat, doh);
+	  if (Writen(so, stemp, strlen(stemp)) < 0)
+	    return -1;
+	  if (stemp != obuffer) {
+	    DohFree(stemp);
+	  }
+	  if (enc)
+	    Delete(enc);
+	}
+      } else {
+	*(fmt++) = *p;
+	*fmt = 0;
+	maxwidth = maxwidth + strlen(newformat) + 64;
+
+	/* Only allocate a buffer if it is too big to fit.  Shouldn't have to do
+	   this very often */
+
+	if (maxwidth < OBUFLEN)
+	  stemp = obuffer;
+	else
+	  stemp = (char *) DohMalloc(maxwidth + 1);
+	switch (*p) {
+	case 'd':
+	case 'i':
+	case 'o':
+	case 'u':
+	case 'x':
+	case 'X':
+	case 'c':
+	  ivalue = va_arg(ap, int);
+	  nbytes += sprintf(stemp, newformat, ivalue);
+	  break;
+	case 'f':
+	case 'g':
+	case 'e':
+	case 'E':
+	case 'G':
+	  dvalue = va_arg(ap, double);
+	  nbytes += sprintf(stemp, newformat, dvalue);
+	  break;
+	case 'p':
+	  pvalue = va_arg(ap, void *);
+	  nbytes += sprintf(stemp, newformat, pvalue);
+	  break;
+	default:
+	  break;
+	}
+	if (Writen(so, stemp, strlen(stemp)) < 0)
+	  return -1;
+	if (stemp != obuffer)
+	  DohFree(stemp);
+      }
+      state = 0;
+      break;
+    }
+    p++;
+  }
+  if (state) {
+    int r;
+    *fmt = 0;
+    r = Writen(so, fmt, strlen(fmt));
+    if (r < 0)
+      return -1;
+    nbytes += r;
+  }
+  return nbytes;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohPrintf()
+ *
+ * Variable length argument entry point to Printf
+ * ----------------------------------------------------------------------------- */
+
+int DohPrintf(DOH *obj, const char *format, ...) {
+  va_list ap;
+  int ret;
+  va_start(ap, format);
+  ret = DohvPrintf(obj, format, ap);
+  va_end(ap);
+  return ret;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohPrintv()
+ * 
+ * Print a null-terminated variable length list of DOH objects
+ * ----------------------------------------------------------------------------- */
+
+int DohPrintv(DOHFile * f, ...) {
+  va_list ap;
+  int ret = 0;
+  DOH *obj;
+  va_start(ap, f);
+  while (1) {
+    obj = va_arg(ap, void *);
+    if ((!obj) || (obj == DohNone))
+      break;
+    if (DohCheck(obj)) {
+      ret += DohDump(obj, f);
+    } else {
+      ret += DohWrite(f, obj, strlen((char *) obj));
+    }
+  }
+  va_end(ap);
+  return ret;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * DohCopyto()
+ *
+ * Copies all of the input from an input stream to an output stream. Returns the
+ * number of bytes copied.
+ * ----------------------------------------------------------------------------- */
+
+int DohCopyto(DOH *in, DOH *out) {
+  int nbytes = 0, ret;
+  int nwrite = 0, wret;
+  char *cw;
+  char buffer[16384];
+
+  if ((!in) || (!out))
+    return 0;
+  while (1) {
+    ret = Read(in, buffer, 16384);
+    if (ret > 0) {
+      nwrite = ret;
+      cw = buffer;
+      while (nwrite) {
+	wret = Write(out, cw, nwrite);
+	if (wret < 0)
+	  return -1;
+	nwrite = nwrite - wret;
+	cw += wret;
+      }
+      nbytes += ret;
+    } else {
+      return nbytes;
+    }
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * DohSplit()
+ *
+ * Split an input stream into a list of strings delimited by the specified
+ * character.  Optionally accepts a maximum number of splits to perform.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohSplit(DOH *in, char ch, int nsplits) {
+  DOH *list;
+  DOH *str;
+  int c;
+
+  list = NewList();
+
+  if (DohIsString(in)) {
+    Seek(in, 0, SEEK_SET);
+  }
+
+  while (1) {
+    str = NewStringEmpty();
+    do {
+      c = Getc(in);
+    } while ((c != EOF) && (c == ch));
+    if (c != EOF) {
+      Putc(c, str);
+      while (1) {
+	c = Getc(in);
+	if ((c == EOF) || ((c == ch) && (nsplits != 0)))
+	  break;
+	Putc(c, str);
+      }
+      nsplits--;
+    }
+    Append(list, str);
+    Delete(str);
+    if (c == EOF)
+      break;
+  }
+  return list;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohSplitLines()
+ *
+ * Split an input stream into a list of strings delimited by newline characters.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohSplitLines(DOH *in) {
+  DOH *list;
+  DOH *str;
+  int c = 0;
+
+  list = NewList();
+
+  if (DohIsString(in)) {
+    Seek(in, 0, SEEK_SET);
+  }
+
+  while (c != EOF) {
+    str = NewStringEmpty();
+    while ((c = Getc(in)) != '\n' && c != EOF) {
+      Putc(c, str);
+    }
+    Append(list, str);
+    Delete(str);
+  }
+  return list;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * DohReadline()
+ *
+ * Read a single input line and return it as a string.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohReadline(DOH *in) {
+  char c;
+  int n = 0;
+  DOH *s = NewStringEmpty();
+  while (1) {
+    if (Read(in, &c, 1) < 0) {
+      if (n == 0) {
+	Delete(s);
+	return 0;
+      }
+      return s;
+    }
+    if (c == '\n')
+      return s;
+    if (c == '\r')
+      continue;
+    Putc(c, s);
+    n++;
+  }
+}
diff --git a/trunk/Source/DOH/hash.c b/trunk/Source/DOH/hash.c
new file mode 100644
index 0000000..62aef10
--- /dev/null
+++ b/trunk/Source/DOH/hash.c
@@ -0,0 +1,551 @@
+/* -----------------------------------------------------------------------------
+ * hash.c
+ *
+ *     Implements a simple hash table object.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_hash_c[] = "$Id$";
+
+#include "dohint.h"
+
+extern DohObjInfo DohHashType;
+
+/* Hash node */
+typedef struct HashNode {
+  DOH *key;
+  DOH *object;
+  struct HashNode *next;
+} HashNode;
+
+/* Hash object */
+typedef struct Hash {
+  DOH *file;
+  int line;
+  HashNode **hashtable;
+  int hashsize;
+  int nitems;
+} Hash;
+
+/* Key interning structure */
+typedef struct KeyValue {
+  char *cstr;
+  DOH *sstr;
+  struct KeyValue *left;
+  struct KeyValue *right;
+} KeyValue;
+
+static KeyValue *root = 0;
+
+/* Find or create a key in the interned key table */
+static DOH *find_key(DOH *doh_c) {
+  char *c = (char *) doh_c;
+  KeyValue *r, *s;
+  int d = 0;
+  /* OK, sure, we use a binary tree for maintaining interned
+     symbols.  Then we use their hash values for accessing secondary
+     hash tables. */
+  r = root;
+  s = 0;
+  while (r) {
+    s = r;
+    d = strcmp(r->cstr, c);
+    if (d == 0)
+      return r->sstr;
+    if (d < 0)
+      r = r->left;
+    else
+      r = r->right;
+  }
+  /*  fprintf(stderr,"Interning '%s'\n", c); */
+  r = (KeyValue *) DohMalloc(sizeof(KeyValue));
+  r->cstr = (char *) DohMalloc(strlen(c) + 1);
+  strcpy(r->cstr, c);
+  r->sstr = NewString(c);
+  DohIntern(r->sstr);
+  r->left = 0;
+  r->right = 0;
+  if (!s) {
+    root = r;
+  } else {
+    if (d < 0)
+      s->left = r;
+    else
+      s->right = r;
+  }
+  return r->sstr;
+}
+
+#define HASH_INIT_SIZE   7
+
+/* Create a new hash node */
+static HashNode *NewNode(DOH *k, void *obj) {
+  HashNode *hn = (HashNode *) DohMalloc(sizeof(HashNode));
+  hn->key = k;
+  Incref(hn->key);
+  hn->object = obj;
+  Incref(obj);
+  hn->next = 0;
+  return hn;
+}
+
+/* Delete a hash node */
+static void DelNode(HashNode *hn) {
+  Delete(hn->key);
+  Delete(hn->object);
+  DohFree(hn);
+}
+
+/* -----------------------------------------------------------------------------
+ * DelHash()
+ *
+ * Delete a hash table.
+ * ----------------------------------------------------------------------------- */
+
+static void DelHash(DOH *ho) {
+  Hash *h = (Hash *) ObjData(ho);
+  HashNode *n, *next;
+  int i;
+
+  for (i = 0; i < h->hashsize; i++) {
+    n = h->hashtable[i];
+    while (n) {
+      next = n->next;
+      DelNode(n);
+      n = next;
+    }
+  }
+  DohFree(h->hashtable);
+  h->hashtable = 0;
+  h->hashsize = 0;
+  DohFree(h);
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_clear()
+ *
+ * Clear all of the entries in the hash table.
+ * ----------------------------------------------------------------------------- */
+
+static void Hash_clear(DOH *ho) {
+  Hash *h = (Hash *) ObjData(ho);
+  HashNode *n, *next;
+  int i;
+
+  for (i = 0; i < h->hashsize; i++) {
+    n = h->hashtable[i];
+    while (n) {
+      next = n->next;
+      DelNode(n);
+      n = next;
+    }
+    h->hashtable[i] = 0;
+  }
+  h->nitems = 0;
+}
+
+/* resize the hash table */
+static void resize(Hash *h) {
+  HashNode *n, *next, **table;
+  int oldsize, newsize;
+  int i, p, hv;
+
+  if (h->nitems < 2 * h->hashsize)
+    return;
+
+  /* Too big. We have to rescale everything now */
+  oldsize = h->hashsize;
+
+  /* Calculate a new size */
+  newsize = 2 * oldsize + 1;
+  p = 3;
+  while (p < (newsize >> 1)) {
+    if (((newsize / p) * p) == newsize) {
+      newsize += 2;
+      p = 3;
+      continue;
+    }
+    p = p + 2;
+  }
+
+  table = (HashNode **) DohMalloc(newsize * sizeof(HashNode *));
+  for (i = 0; i < newsize; i++) {
+    table[i] = 0;
+  }
+
+  /* Walk down the old set of nodes and re-place */
+  h->hashsize = newsize;
+  for (i = 0; i < oldsize; i++) {
+    n = h->hashtable[i];
+    while (n) {
+      hv = Hashval(n->key) % newsize;
+      next = n->next;
+      n->next = table[hv];
+      table[hv] = n;
+      n = next;
+    }
+  }
+  DohFree(h->hashtable);
+  h->hashtable = table;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_setattr()
+ *
+ * Set an attribute in the hash table.  Deletes the existing entry if it already
+ * exists.
+ * ----------------------------------------------------------------------------- */
+
+static int Hash_setattr(DOH *ho, DOH *k, DOH *obj) {
+  int hv;
+  HashNode *n, *prev;
+  Hash *h = (Hash *) ObjData(ho);
+
+  if (!obj) {
+    return DohDelattr(ho, k);
+  }
+  if (!DohCheck(k))
+    k = find_key(k);
+  if (!DohCheck(obj)) {
+    obj = NewString((char *) obj);
+    Decref(obj);
+  }
+  hv = (Hashval(k)) % h->hashsize;
+  n = h->hashtable[hv];
+  prev = 0;
+  while (n) {
+    if (Cmp(n->key, k) == 0) {
+      /* Node already exists.  Just replace its contents */
+      if (n->object == obj) {
+	/* Whoa. Same object.  Do nothing */
+	return 1;
+      }
+      Delete(n->object);
+      n->object = obj;
+      Incref(obj);
+      return 1;			/* Return 1 to indicate a replacement */
+    } else {
+      prev = n;
+      n = n->next;
+    }
+  }
+  /* Add this to the table */
+  n = NewNode(k, obj);
+  if (prev)
+    prev->next = n;
+  else
+    h->hashtable[hv] = n;
+  h->nitems++;
+  resize(h);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_getattr()
+ *
+ * Get an attribute from the hash table. Returns 0 if it doesn't exist.
+ * ----------------------------------------------------------------------------- */
+typedef int (*binop) (DOH *obj1, DOH *obj2);
+
+
+static DOH *Hash_getattr(DOH *h, DOH *k) {
+  DOH *obj = 0;
+  Hash *ho = (Hash *) ObjData(h);
+  DOH *ko = DohCheck(k) ? k : find_key(k);
+  int hv = Hashval(ko) % ho->hashsize;
+  DohObjInfo *k_type = ((DohBase*)ko)->type;
+  HashNode *n = ho->hashtable[hv];
+  if (k_type->doh_equal) {
+    binop equal = k_type->doh_equal;
+    while (n) {
+      DohBase *nk = (DohBase *)n->key;
+      if ((k_type == nk->type) && equal(ko, nk)) obj = n->object;
+      n = n->next;
+    }
+  } else {
+    binop cmp = k_type->doh_cmp;
+    while (n) {
+      DohBase *nk = (DohBase *)n->key;
+      if ((k_type == nk->type) && (cmp(ko, nk) == 0)) obj = n->object;
+      n = n->next;
+    }
+  }
+  return obj;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_delattr()
+ *
+ * Delete an object from the hash table.
+ * ----------------------------------------------------------------------------- */
+
+static int Hash_delattr(DOH *ho, DOH *k) {
+  HashNode *n, *prev;
+  int hv;
+  Hash *h = (Hash *) ObjData(ho);
+
+  if (!DohCheck(k))
+    k = find_key(k);
+  hv = Hashval(k) % h->hashsize;
+  n = h->hashtable[hv];
+  prev = 0;
+  while (n) {
+    if (Cmp(n->key, k) == 0) {
+      /* Found it, kill it */
+
+      if (prev) {
+	prev->next = n->next;
+      } else {
+	h->hashtable[hv] = n->next;
+      }
+      DelNode(n);
+      h->nitems--;
+      return 1;
+    }
+    prev = n;
+    n = n->next;
+  }
+  return 0;
+}
+
+static DohIterator Hash_firstiter(DOH *ho) {
+  DohIterator iter;
+  Hash *h = (Hash *) ObjData(ho);
+  iter.object = ho;
+  iter._current = 0;
+  iter.item = 0;
+  iter.key = 0;
+  iter._index = 0;		/* Index in hash table */
+  while ((iter._index < h->hashsize) && !h->hashtable[iter._index])
+    iter._index++;
+
+  if (iter._index >= h->hashsize) {
+    return iter;
+  }
+  iter._current = h->hashtable[iter._index];
+  iter.item = ((HashNode *) iter._current)->object;
+  iter.key = ((HashNode *) iter._current)->key;
+
+  /* Actually save the next slot in the hash.  This makes it possible to
+     delete the item being iterated over without trashing the universe */
+  iter._current = ((HashNode *) iter._current)->next;
+  return iter;
+}
+
+static DohIterator Hash_nextiter(DohIterator iter) {
+  Hash *h = (Hash *) ObjData(iter.object);
+  if (!iter._current) {
+    iter._index++;
+    while ((iter._index < h->hashsize) && !h->hashtable[iter._index]) {
+      iter._index++;
+    }
+    if (iter._index >= h->hashsize) {
+      iter.item = 0;
+      iter.key = 0;
+      iter._current = 0;
+      return iter;
+    }
+    iter._current = h->hashtable[iter._index];
+  }
+  iter.key = ((HashNode *) iter._current)->key;
+  iter.item = ((HashNode *) iter._current)->object;
+
+  /* Store the next node to iterator on */
+  iter._current = ((HashNode *) iter._current)->next;
+  return iter;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_keys(DOH *)
+ *
+ * Return a list of keys
+ * ----------------------------------------------------------------------------- */
+
+static DOH *Hash_keys(DOH *so) {
+  DOH *keys;
+  Iterator i;
+
+  keys = NewList();
+  for (i = First(so); i.key; i = Next(i)) {
+    Append(keys, i.key);
+  }
+  return keys;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_str()
+ *
+ * Create a string representation of a hash table (mainly for debugging).
+ * ----------------------------------------------------------------------------- */
+
+static DOH *Hash_str(DOH *ho) {
+  int i, j;
+  HashNode *n;
+  DOH *s;
+  static int indent = 4;
+  Hash *h = (Hash *) ObjData(ho);
+
+  s = NewStringEmpty();
+  if (ObjGetMark(ho)) {
+    Printf(s, "Hash(0x%x)", ho);
+    return s;
+  }
+  ObjSetMark(ho, 1);
+  Printf(s, "Hash {\n");
+  for (i = 0; i < h->hashsize; i++) {
+    n = h->hashtable[i];
+    while (n) {
+      for (j = 0; j < indent; j++)
+	Putc(' ', s);
+      indent += 4;
+      Printf(s, "'%s' : %s, \n", n->key, n->object);
+      indent -= 4;
+      n = n->next;
+    }
+  }
+  for (j = 0; j < (indent - 4); j++)
+    Putc(' ', s);
+  Printf(s, "}\n");
+  ObjSetMark(ho, 0);
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash_len()
+ *
+ * Return number of entries in the hash table.
+ * ----------------------------------------------------------------------------- */
+
+static int Hash_len(DOH *ho) {
+  Hash *h = (Hash *) ObjData(ho);
+  return h->nitems;
+}
+
+/* -----------------------------------------------------------------------------
+ * CopyHash()
+ *
+ * Make a copy of a hash table.  Note: this is a shallow copy.
+ * ----------------------------------------------------------------------------- */
+
+static DOH *CopyHash(DOH *ho) {
+  Hash *h, *nh;
+  HashNode *n;
+  DOH *nho;
+
+  int i;
+  h = (Hash *) ObjData(ho);
+  nh = (Hash *) DohMalloc(sizeof(Hash));
+  nh->hashsize = h->hashsize;
+  nh->hashtable = (HashNode **) DohMalloc(nh->hashsize * sizeof(HashNode *));
+  for (i = 0; i < nh->hashsize; i++) {
+    nh->hashtable[i] = 0;
+  }
+  nh->nitems = 0;
+  nh->line = h->line;
+  nh->file = h->file;
+  if (nh->file)
+    Incref(nh->file);
+
+  nho = DohObjMalloc(&DohHashType, nh);
+  for (i = 0; i < h->hashsize; i++) {
+    n = h->hashtable[i];
+    while (n) {
+      Hash_setattr(nho, n->key, n->object);
+      n = n->next;
+    }
+  }
+  return nho;
+}
+
+
+
+static void Hash_setfile(DOH *ho, DOH *file) {
+  DOH *fo;
+  Hash *h = (Hash *) ObjData(ho);
+
+  if (!DohCheck(file)) {
+    fo = NewString(file);
+    Decref(fo);
+  } else
+    fo = file;
+  Incref(fo);
+  Delete(h->file);
+  h->file = fo;
+}
+
+static DOH *Hash_getfile(DOH *ho) {
+  Hash *h = (Hash *) ObjData(ho);
+  return h->file;
+}
+
+static void Hash_setline(DOH *ho, int line) {
+  Hash *h = (Hash *) ObjData(ho);
+  h->line = line;
+}
+
+static int Hash_getline(DOH *ho) {
+  Hash *h = (Hash *) ObjData(ho);
+  return h->line;
+}
+
+/* -----------------------------------------------------------------------------
+ * type information
+ * ----------------------------------------------------------------------------- */
+
+static DohHashMethods HashHashMethods = {
+  Hash_getattr,
+  Hash_setattr,
+  Hash_delattr,
+  Hash_keys,
+};
+
+DohObjInfo DohHashType = {
+  "Hash",			/* objname */
+  DelHash,			/* doh_del */
+  CopyHash,			/* doh_copy */
+  Hash_clear,			/* doh_clear */
+  Hash_str,			/* doh_str */
+  0,				/* doh_data */
+  0,				/* doh_dump */
+  Hash_len,			/* doh_len */
+  0,				/* doh_hash    */
+  0,				/* doh_cmp */
+  0,				/* doh_equal    */
+  Hash_firstiter,		/* doh_first    */
+  Hash_nextiter,		/* doh_next     */
+  Hash_setfile,			/* doh_setfile */
+  Hash_getfile,			/* doh_getfile */
+  Hash_setline,			/* doh_setline */
+  Hash_getline,			/* doh_getline */
+  &HashHashMethods,		/* doh_mapping */
+  0,				/* doh_sequence */
+  0,				/* doh_file */
+  0,				/* doh_string */
+  0,				/* doh_positional */
+  0,
+};
+
+/* -----------------------------------------------------------------------------
+ * NewHash()
+ *
+ * Create a new hash table.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohNewHash() {
+  Hash *h;
+  int i;
+  h = (Hash *) DohMalloc(sizeof(Hash));
+  h->hashsize = HASH_INIT_SIZE;
+  h->hashtable = (HashNode **) DohMalloc(h->hashsize * sizeof(HashNode *));
+  for (i = 0; i < h->hashsize; i++) {
+    h->hashtable[i] = 0;
+  }
+  h->nitems = 0;
+  h->file = 0;
+  h->line = 0;
+  return DohObjMalloc(&DohHashType, h);
+}
diff --git a/trunk/Source/DOH/list.c b/trunk/Source/DOH/list.c
new file mode 100644
index 0000000..a45731d
--- /dev/null
+++ b/trunk/Source/DOH/list.c
@@ -0,0 +1,377 @@
+/* ----------------------------------------------------------------------------- 
+ * list.c
+ *
+ *     Implements a simple list object.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_list_c[] = "$Id$";
+
+#include "dohint.h"
+
+typedef struct List {
+  int maxitems;			/* Max size  */
+  int nitems;			/* Num items */
+  DOH *file;
+  int line;
+  DOH **items;
+} List;
+
+extern DohObjInfo DohListType;
+
+/* Doubles amount of memory in a list */
+static
+void more(List *l) {
+  l->items = (void **) DohRealloc(l->items, l->maxitems * 2 * sizeof(void *));
+  assert(l->items);
+  l->maxitems *= 2;
+}
+
+/* -----------------------------------------------------------------------------
+ * CopyList()
+ *
+ * Make a shallow copy of a list.
+ * ----------------------------------------------------------------------------- */
+static DOH *CopyList(DOH *lo) {
+  List *l, *nl;
+  int i;
+  l = (List *) ObjData(lo);
+  nl = (List *) DohMalloc(sizeof(List));
+  nl->nitems = l->nitems;
+  nl->maxitems = l->maxitems;
+  nl->items = (void **) DohMalloc(l->maxitems * sizeof(void *));
+  for (i = 0; i < l->nitems; i++) {
+    nl->items[i] = l->items[i];
+    Incref(nl->items[i]);
+  }
+  nl->file = l->file;
+  if (nl->file)
+    Incref(nl->file);
+  nl->line = l->line;
+  return DohObjMalloc(&DohListType, nl);
+}
+
+/* -----------------------------------------------------------------------------
+ * DelList()
+ *
+ * Delete a list.
+ * ----------------------------------------------------------------------------- */
+
+static void DelList(DOH *lo) {
+  List *l = (List *) ObjData(lo);
+  int i;
+  for (i = 0; i < l->nitems; i++)
+    Delete(l->items[i]);
+  DohFree(l->items);
+  DohFree(l);
+}
+
+/* -----------------------------------------------------------------------------
+ * List_clear()
+ *
+ * Remove all of the list entries, but keep the list object intact.
+ * ----------------------------------------------------------------------------- */
+
+static void List_clear(DOH *lo) {
+  List *l = (List *) ObjData(lo);
+  int i;
+  for (i = 0; i < l->nitems; i++) {
+    Delete(l->items[i]);
+  }
+  l->nitems = 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_insert()
+ *
+ * Insert an item into the list. If the item is not a DOH object, it is assumed
+ * to be a 'char *' and is used to construct an equivalent string object.
+ * ----------------------------------------------------------------------------- */
+
+static int List_insert(DOH *lo, int pos, DOH *item) {
+  List *l = (List *) ObjData(lo);
+  int i;
+
+  if (!item)
+    return -1;
+  if (!DohCheck(item)) {
+    item = NewString(item);
+    Decref(item);
+  }
+  if (pos == DOH_END)
+    pos = l->nitems;
+  if (pos < 0)
+    pos = 0;
+  if (pos > l->nitems)
+    pos = l->nitems;
+  if (l->nitems == l->maxitems)
+    more(l);
+  for (i = l->nitems; i > pos; i--) {
+    l->items[i] = l->items[i - 1];
+  }
+  l->items[pos] = item;
+  Incref(item);
+  l->nitems++;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_remove()
+ *
+ * Remove an item from a list.
+ * ----------------------------------------------------------------------------- */
+
+static int List_remove(DOH *lo, int pos) {
+  List *l = (List *) ObjData(lo);
+  int i;
+  if (pos == DOH_END)
+    pos = l->nitems - 1;
+  if (pos == DOH_BEGIN)
+    pos = 0;
+  assert(!((pos < 0) || (pos >= l->nitems)));
+  Delete(l->items[pos]);
+  for (i = pos; i < l->nitems - 1; i++) {
+    l->items[i] = l->items[i + 1];
+  }
+  l->nitems--;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_len()
+ *
+ * Return the number of elements in the list
+ * ----------------------------------------------------------------------------- */
+
+static int List_len(DOH *lo) {
+  List *l = (List *) ObjData(lo);
+  return l->nitems;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_get()
+ *
+ * Get the nth item from the list.
+ * ----------------------------------------------------------------------------- */
+
+static DOH *List_get(DOH *lo, int n) {
+  List *l = (List *) ObjData(lo);
+  if (n == DOH_END)
+    n = l->nitems - 1;
+  if (n == DOH_BEGIN)
+    n = 0;
+  assert(!((n < 0) || (n >= l->nitems)));
+  return l->items[n];
+}
+
+/* -----------------------------------------------------------------------------
+ * List_set()
+ *
+ * Set the nth item in the list replacing any previous item. 
+ * ----------------------------------------------------------------------------- */
+
+static int List_set(DOH *lo, int n, DOH *val) {
+  List *l = (List *) ObjData(lo);
+  if (!val)
+    return -1;
+  assert(!((n < 0) || (n >= l->nitems)));
+  if (!DohCheck(val)) {
+    val = NewString(val);
+    Decref(val);
+  }
+  Delete(l->items[n]);
+  l->items[n] = val;
+  Incref(val);
+  Delete(val);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_first()
+ *
+ * Return the first item in the list.
+ * ----------------------------------------------------------------------------- */
+
+static DohIterator List_first(DOH *lo) {
+  DohIterator iter;
+  List *l = (List *) ObjData(lo);
+  iter.object = lo;
+  iter._index = 0;
+  iter._current = 0;
+  iter.key = 0;
+  if (l->nitems > 0) {
+    iter.item = l->items[0];
+  } else {
+    iter.item = 0;
+  }
+  return iter;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_next()
+ * 
+ * Return the next item in the list.
+ * ----------------------------------------------------------------------------- */
+
+static DohIterator List_next(DohIterator iter) {
+  List *l = (List *) ObjData(iter.object);
+  iter._index = iter._index + 1;
+  if (iter._index >= l->nitems) {
+    iter.item = 0;
+    iter.key = 0;
+  } else {
+    iter.item = l->items[iter._index];
+  }
+  return iter;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_str()
+ *
+ * Create a string representation of the list.
+ * ----------------------------------------------------------------------------- */
+static DOH *List_str(DOH *lo) {
+  DOH *s;
+  int i;
+  List *l = (List *) ObjData(lo);
+  s = NewStringEmpty();
+  if (ObjGetMark(lo)) {
+    Printf(s, "List(%x)", lo);
+    return s;
+  }
+  ObjSetMark(lo, 1);
+  Printf(s, "List[ ");
+  for (i = 0; i < l->nitems; i++) {
+    Printf(s, "%s", l->items[i]);
+    if ((i + 1) < l->nitems)
+      Printf(s, ", ");
+  }
+  Printf(s, " ]\n");
+  ObjSetMark(lo, 0);
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * List_dump()
+ *
+ * Dump the items to an output stream.
+ * ----------------------------------------------------------------------------- */
+
+static int List_dump(DOH *lo, DOH *out) {
+  int nsent = 0;
+  int i, ret;
+  List *l = (List *) ObjData(lo);
+  for (i = 0; i < l->nitems; i++) {
+    ret = Dump(l->items[i], out);
+    if (ret < 0)
+      return -1;
+    nsent += ret;
+  }
+  return nsent;
+}
+
+static void List_setfile(DOH *lo, DOH *file) {
+  DOH *fo;
+  List *l = (List *) ObjData(lo);
+
+  if (!DohCheck(file)) {
+    fo = NewString(file);
+    Decref(fo);
+  } else
+    fo = file;
+  Incref(fo);
+  Delete(l->file);
+  l->file = fo;
+}
+
+static DOH *List_getfile(DOH *lo) {
+  List *l = (List *) ObjData(lo);
+  return l->file;
+}
+
+static void List_setline(DOH *lo, int line) {
+  List *l = (List *) ObjData(lo);
+  l->line = line;
+}
+
+static int List_getline(DOH *lo) {
+  List *l = (List *) ObjData(lo);
+  return l->line;
+}
+
+static DohListMethods ListListMethods = {
+  List_get,
+  List_set,
+  List_remove,
+  List_insert,
+  0,				/* delslice */
+};
+
+DohObjInfo DohListType = {
+  "List",			/* objname */
+  DelList,			/* doh_del */
+  CopyList,			/* doh_copy */
+  List_clear,			/* doh_clear */
+  List_str,			/* doh_str */
+  0,				/* doh_data */
+  List_dump,			/* doh_dump */
+  List_len,			/* doh_len */
+  0,				/* doh_hash    */
+  0,				/* doh_cmp */
+  0,				/* doh_equal    */
+  List_first,			/* doh_first    */
+  List_next,			/* doh_next     */
+  List_setfile,			/* doh_setfile */
+  List_getfile,			/* doh_getfile */
+  List_setline,			/* doh_setline */
+  List_getline,			/* doh_getline */
+  0,				/* doh_mapping */
+  &ListListMethods,		/* doh_sequence */
+  0,				/* doh_file */
+  0,				/* doh_string */
+  0,				/* doh_callable */
+  0,				/* doh_position */
+};
+
+/* -----------------------------------------------------------------------------
+ * NewList()
+ *
+ * Create a new list.
+ * ----------------------------------------------------------------------------- */
+
+#define MAXLISTITEMS 8
+
+DOH *DohNewList() {
+  List *l;
+  int i;
+  l = (List *) DohMalloc(sizeof(List));
+  l->nitems = 0;
+  l->maxitems = MAXLISTITEMS;
+  l->items = (void **) DohMalloc(l->maxitems * sizeof(void *));
+  for (i = 0; i < MAXLISTITEMS; i++) {
+    l->items[i] = 0;
+  }
+  l->file = 0;
+  l->line = 0;
+  return DohObjMalloc(&DohListType, l);
+}
+
+static int (*List_sort_compare_func) (const DOH *, const DOH *);
+static int List_qsort_compare(const void *a, const void *b) {
+  return List_sort_compare_func(*((DOH **) a), *((DOH **) b));
+}
+
+/* Sort a list */
+void DohSortList(DOH *lo, int (*cmp) (const DOH *, const DOH *)) {
+  List *l = (List *) ObjData(lo);
+  if (cmp) {
+    List_sort_compare_func = cmp;
+  } else {
+    List_sort_compare_func = DohCmp;
+  }
+  qsort(l->items, l->nitems, sizeof(DOH *), List_qsort_compare);
+}
diff --git a/trunk/Source/DOH/memory.c b/trunk/Source/DOH/memory.c
new file mode 100644
index 0000000..1c6063e
--- /dev/null
+++ b/trunk/Source/DOH/memory.c
@@ -0,0 +1,220 @@
+/* ----------------------------------------------------------------------------- 
+ * memory.c
+ *
+ *     This file implements all of DOH's memory management including allocation
+ *     of objects and checking of objects.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_memory_c[] = "$Id$";
+
+#include "dohint.h"
+
+#ifndef DOH_POOL_SIZE
+#define DOH_POOL_SIZE         16384
+#endif
+
+static int PoolSize = DOH_POOL_SIZE;
+
+DOH *DohNone = 0;		/* The DOH None object */
+
+typedef struct pool {
+  DohBase *ptr;			/* Start of pool */
+  int len;			/* Length of pool */
+  int blen;			/* Byte length of pool */
+  int current;			/* Current position for next allocation */
+  char *pbeg;			/* Beg of pool */
+  char *pend;			/* End of pool */
+  struct pool *next;		/* Next pool */
+} Pool;
+
+static DohBase *FreeList = 0;	/* List of free objects */
+static Pool *Pools = 0;
+static int pools_initialized = 0;
+
+/* ----------------------------------------------------------------------
+ * CreatePool() - Create a new memory pool 
+ * ---------------------------------------------------------------------- */
+
+static void CreatePool() {
+  Pool *p = 0;
+  p = (Pool *) DohMalloc(sizeof(Pool));
+  assert(p);
+  p->ptr = (DohBase *) DohMalloc(sizeof(DohBase) * PoolSize);
+  assert(p->ptr);
+  memset(p->ptr, 0, sizeof(DohBase) * PoolSize);
+  p->len = PoolSize;
+  p->blen = PoolSize * sizeof(DohBase);
+  p->current = 0;
+  p->pbeg = ((char *) p->ptr);
+  p->pend = p->pbeg + p->blen;
+  p->next = Pools;
+  Pools = p;
+}
+
+/* ----------------------------------------------------------------------
+ * InitPools() - Initialize the memory allocator
+ * ---------------------------------------------------------------------- */
+
+static void InitPools() {
+  if (pools_initialized)
+    return;
+  CreatePool();			/* Create initial pool */
+  pools_initialized = 1;
+  DohNone = NewVoid(0, 0);	/* Create the None object */
+  DohIntern(DohNone);
+}
+
+/* ----------------------------------------------------------------------
+ * DohCheck()
+ *
+ * Returns 1 if an arbitrary pointer is a DOH object.
+ * ---------------------------------------------------------------------- */
+
+int DohCheck(const DOH *ptr) {
+  register Pool *p = Pools;
+  register char *cptr = (char *) ptr;
+  while (p) {
+    if ((cptr >= p->pbeg) && (cptr < p->pend))
+      return 1;
+    /*
+       pptr = (char *) p->ptr;
+       if ((cptr >= pptr) && (cptr < (pptr+(p->current*sizeof(DohBase))))) return 1; */
+    p = p->next;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DohIntern()
+ * ----------------------------------------------------------------------------- */
+
+void DohIntern(DOH *obj) {
+  DohBase *b = (DohBase *) obj;
+  b->flag_intern = 1;
+}
+
+/* ----------------------------------------------------------------------
+ * DohObjMalloc()
+ *
+ * Allocate memory for a new object.
+ * ---------------------------------------------------------------------- */
+
+DOH *DohObjMalloc(DohObjInfo *type, void *data) {
+  DohBase *obj;
+  if (!pools_initialized)
+    InitPools();
+  if (FreeList) {
+    obj = FreeList;
+    FreeList = (DohBase *) obj->data;
+  } else {
+    while (Pools->current == Pools->len) {
+      CreatePool();
+    }
+    obj = Pools->ptr + Pools->current;
+    ++Pools->current;
+  }
+  obj->type = type;
+  obj->data = data;
+  obj->meta = 0;
+  obj->refcount = 1;
+  obj->flag_intern = 0;
+  obj->flag_marked = 0;
+  obj->flag_user = 0;
+  obj->flag_usermark = 0;
+  return (DOH *) obj;
+}
+
+/* ----------------------------------------------------------------------
+ * DohObjFree() - Free a DOH object
+ * ---------------------------------------------------------------------- */
+
+void DohObjFree(DOH *ptr) {
+  DohBase *b, *meta;
+  b = (DohBase *) ptr;
+  if (b->flag_intern)
+    return;
+  meta = (DohBase *) b->meta;
+  b->data = (void *) FreeList;
+  b->meta = 0;
+  b->type = 0;
+  FreeList = b;
+  if (meta) {
+    Delete(meta);
+  }
+}
+
+/* ----------------------------------------------------------------------
+ * DohMemoryDebug()
+ *
+ * Display memory usage statistics
+ * ---------------------------------------------------------------------- */
+
+void DohMemoryDebug(void) {
+  extern DohObjInfo DohStringType;
+  extern DohObjInfo DohListType;
+  extern DohObjInfo DohHashType;
+
+  Pool *p;
+  int totsize = 0;
+  int totused = 0;
+  int totfree = 0;
+
+  int numstring = 0;
+  int numlist = 0;
+  int numhash = 0;
+
+  printf("Memory statistics:\n\n");
+  printf("Pools:\n");
+
+  p = Pools;
+  while (p) {
+    /* Calculate number of used, free items */
+    int i;
+    int nused = 0, nfree = 0;
+    for (i = 0; i < p->len; i++) {
+      if (p->ptr[i].refcount <= 0)
+	nfree++;
+      else {
+	nused++;
+	if (p->ptr[i].type == &DohStringType)
+	  numstring++;
+	else if (p->ptr[i].type == &DohListType)
+	  numlist++;
+	else if (p->ptr[i].type == &DohHashType)
+	  numhash++;
+      }
+    }
+    printf("    Pool %8p: size = %10d. used = %10d. free = %10d\n", (void *) p, p->len, nused, nfree);
+    totsize += p->len;
+    totused += nused;
+    totfree += nfree;
+    p = p->next;
+  }
+  printf("\n    Total:          size = %10d, used = %10d, free = %10d\n", totsize, totused, totfree);
+
+  printf("\nObject types\n");
+  printf("    Strings   : %d\n", numstring);
+  printf("    Lists     : %d\n", numlist);
+  printf("    Hashes    : %d\n", numhash);
+
+#if 0
+  p = Pools;
+  while (p) {
+    int i;
+    for (i = 0; i < p->len; i++) {
+      if (p->ptr[i].refcount > 0) {
+	if (p->ptr[i].type == &DohStringType) {
+	  Printf(stdout, "%s\n", p->ptr + i);
+	}
+      }
+    }
+    p = p->next;
+  }
+#endif
+
+}
diff --git a/trunk/Source/DOH/string.c b/trunk/Source/DOH/string.c
new file mode 100644
index 0000000..1498d71
--- /dev/null
+++ b/trunk/Source/DOH/string.c
@@ -0,0 +1,1158 @@
+/* -----------------------------------------------------------------------------
+ * string.c
+ *
+ *     Implements a string object that supports both sequence operations and
+ *     file semantics.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_string_c[] = "$Id$";
+
+#include "dohint.h"
+
+extern DohObjInfo DohStringType;
+
+typedef struct String {
+  DOH *file;
+  int line;
+  int maxsize;			/* Max size allocated */
+  int len;			/* Current length     */
+  int hashkey;			/* Hash key value     */
+  int sp;			/* Current position   */
+  char *str;			/* String data        */
+} String;
+
+/* -----------------------------------------------------------------------------
+ * void *String_data() - Return as a 'void *'
+ * ----------------------------------------------------------------------------- */
+
+static void *String_data(DOH *so) {
+  String *s = (String *) ObjData(so);
+  s->str[s->len] = 0;
+  return (void *) s->str;
+}
+
+/* static char *String_char(DOH *so) {
+  return (char *) String_data(so);
+}
+*/
+
+/* -----------------------------------------------------------------------------
+ * int String_dump() - Serialize a string onto out
+ * ----------------------------------------------------------------------------- */
+
+static int String_dump(DOH *so, DOH *out) {
+  int nsent;
+  int ret;
+  String *s = (String *) ObjData(so);
+  nsent = 0;
+  while (nsent < s->len) {
+    ret = Write(out, s->str + nsent, (s->len - nsent));
+    if (ret < 0)
+      return ret;
+    nsent += ret;
+  }
+  return nsent;
+}
+
+/* -----------------------------------------------------------------------------
+ * CopyString() - Copy a string
+ * ----------------------------------------------------------------------------- */
+
+static DOH *CopyString(DOH *so) {
+  String *str;
+  String *s = (String *) ObjData(so);
+  str = (String *) DohMalloc(sizeof(String));
+  str->hashkey = s->hashkey;
+  str->sp = s->sp;
+  str->line = s->line;
+  str->file = s->file;
+  if (str->file)
+    Incref(str->file);
+  str->str = (char *) DohMalloc(s->len + 1);
+  memcpy(str->str, s->str, s->len);
+  str->maxsize = s->len;
+  str->len = s->len;
+  str->str[str->len] = 0;
+
+  return DohObjMalloc(&DohStringType, str);
+}
+
+/* -----------------------------------------------------------------------------
+ * DelString() - Delete a string
+ * ----------------------------------------------------------------------------- */
+
+static void DelString(DOH *so) {
+  String *s = (String *) ObjData(so);
+  DohFree(s->str);
+  DohFree(s);
+}
+
+/* -----------------------------------------------------------------------------
+ * DohString_len() - Length of a string
+ * ----------------------------------------------------------------------------- */
+
+static int String_len(DOH *so) {
+  String *s = (String *) ObjData(so);
+  return s->len;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * int String_cmp() - Compare two strings
+ * ----------------------------------------------------------------------------- */
+
+static int String_cmp(DOH *so1, DOH *so2) {
+  String *s1, *s2;
+  char *c1, *c2;
+  int maxlen, i;
+  s1 = (String *) ObjData(so1);
+  s2 = (String *) ObjData(so2);
+  maxlen = s1->len;
+  if (s2->len < maxlen)
+    maxlen = s2->len;
+  c1 = s1->str;
+  c2 = s2->str;
+  for (i = maxlen; i; --i, c1++, c2++) {
+    if (*c1 != *c2)
+      break;
+  }
+  if (i != 0) {
+    if (*c1 < *c2)
+      return -1;
+    else
+      return 1;
+  }
+  if (s1->len == s2->len)
+    return 0;
+  if (s1->len > s2->len)
+    return 1;
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_equal() - Say if two string are equal
+ * ----------------------------------------------------------------------------- */
+
+static int String_equal(DOH *so1, DOH *so2) {
+  String *s1 = (String *) ObjData(so1);
+  String *s2 = (String *) ObjData(so2);
+  register int len = s1->len;
+  if (len != s2->len) {
+    return 0;
+  } else {
+    register char *c1 = s1->str;
+    register char *c2 = s2->str;
+#if 0
+    register int mlen = len >> 2;
+    register int i = mlen;
+    for (; i; --i) {
+      if (*(c1++) != *(c2++))
+	return 0;
+      if (*(c1++) != *(c2++))
+	return 0;
+      if (*(c1++) != *(c2++))
+	return 0;
+      if (*(c1++) != *(c2++))
+	return 0;
+    }
+    for (i = len - (mlen << 2); i; --i) {
+      if (*(c1++) != *(c2++))
+	return 0;
+    }
+    return 1;
+#else
+    return memcmp(c1, c2, len) == 0;
+#endif
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_hash() - Compute string hash value
+ * ----------------------------------------------------------------------------- */
+
+static int String_hash(DOH *so) {
+  String *s = (String *) ObjData(so);
+  if (s->hashkey >= 0) {
+    return s->hashkey;
+  } else {
+    register char *c = s->str;
+    register int len = s->len > 50 ? 50 : s->len;
+    register int h = 0;
+    register int mlen = len >> 2;
+    register int i = mlen;
+    for (; i; --i) {
+      h = (h << 5) + *(c++);
+      h = (h << 5) + *(c++);
+      h = (h << 5) + *(c++);
+      h = (h << 5) + *(c++);
+    }
+    for (i = len - (mlen << 2); i; --i) {
+      h = (h << 5) + *(c++);
+    }
+    h &= 0x7fffffff;
+    s->hashkey = h;
+    return h;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * DohString_append(String *s, const char *newstr) - Append to s
+ * ----------------------------------------------------------------------------- */
+
+void DohString_append(DOH *so, DOH *str) {
+  int oldlen, newlen, newmaxsize, l, sp;
+  char *tc;
+  String *s = (String *) ObjData(so);
+  char *newstr = 0;
+
+  if (DohCheck(str)) {
+    String *ss = (String *) ObjData(str);
+    newstr = (char *) String_data((DOH *) str);
+    l = ss->len;
+  } else {
+    newstr = (char *) (str);
+    l = (int) strlen(newstr);
+  }
+  if (!newstr)
+    return;
+  s->hashkey = -1;
+
+  oldlen = s->len;
+  newlen = oldlen + l + 1;
+  if (newlen >= s->maxsize - 1) {
+    newmaxsize = 2 * s->maxsize;
+    if (newlen >= newmaxsize - 1)
+      newmaxsize = newlen + 1;
+    s->str = (char *) DohRealloc(s->str, newmaxsize);
+    assert(s->str);
+    s->maxsize = newmaxsize;
+  }
+  tc = s->str;
+  memcpy(tc + oldlen, newstr, l + 1);
+  sp = s->sp;
+  if (sp >= oldlen) {
+    int i = oldlen + l - sp;
+    tc += sp;
+    for (; i; --i) {
+      if (*(tc++) == '\n')
+	s->line++;
+    }
+    s->sp = oldlen + l;
+  }
+  s->len += l;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * void String_clear() - Clear a string
+ * ----------------------------------------------------------------------------- */
+
+static void String_clear(DOH *so) {
+  String *s = (String *) ObjData(so);
+  s->hashkey = -1;
+  s->len = 0;
+  *(s->str) = 0;
+  s->sp = 0;
+  s->line = 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * void String_insert() - Insert a string
+ * ----------------------------------------------------------------------------- */
+
+static int String_insert(DOH *so, int pos, DOH *str) {
+  String *s;
+  char *nstr;
+  int len;
+  char *data;
+
+  if (pos == DOH_END) {
+    DohString_append(so, str);
+    return 0;
+  }
+
+
+  s = (String *) ObjData(so);
+  s->hashkey = -1;
+  if (DohCheck(str)) {
+    String *ss = (String *) ObjData(str);
+    data = (char *) String_data(str);
+    len = ss->len;
+  } else {
+    data = (char *) (str);
+    len = (int) strlen(data);
+  }
+  nstr = s->str;
+
+  if (pos < 0)
+    pos = 0;
+  else if (pos > s->len)
+    pos = s->len;
+
+  /* See if there is room to insert the new data */
+  while (s->maxsize <= s->len + len) {
+    int newsize = 2 * s->maxsize;
+    s->str = (char *) DohRealloc(s->str, newsize);
+    assert(s->str);
+    s->maxsize = newsize;
+  }
+  memmove(s->str + pos + len, s->str + pos, (s->len - pos));
+  memcpy(s->str + pos, data, len);
+  if (s->sp >= pos) {
+    int i;
+
+    for (i = 0; i < len; i++) {
+      if (data[i] == '\n')
+	s->line++;
+    }
+    s->sp += len;
+  }
+  s->len += len;
+  s->str[s->len] = 0;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_delitem() - Delete a character
+ * ----------------------------------------------------------------------------- */
+
+static int String_delitem(DOH *so, int pos) {
+  String *s = (String *) ObjData(so);
+  s->hashkey = -1;
+  if (pos == DOH_END)
+    pos = s->len - 1;
+  if (pos == DOH_BEGIN)
+    pos = 0;
+  if (s->len == 0)
+    return 0;
+
+  if (s->sp > pos) {
+    s->sp--;
+    assert(s->sp >= 0);
+    if (s->str[pos] == '\n')
+      s->line--;
+  }
+  memmove(s->str + pos, s->str + pos + 1, ((s->len - 1) - pos));
+  s->len--;
+  s->str[s->len] = 0;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_delslice() -  Delete a range
+ * ----------------------------------------------------------------------------- */
+
+static int String_delslice(DOH *so, int sindex, int eindex) {
+  String *s = (String *) ObjData(so);
+  int size;
+  if (s->len == 0)
+    return 0;
+  s->hashkey = -1;
+  if (eindex == DOH_END)
+    eindex = s->len;
+  if (sindex == DOH_BEGIN)
+    sindex = 0;
+
+  size = eindex - sindex;
+  if (s->sp > sindex) {
+    /* Adjust the file pointer and line count */
+    int i, end;
+    if (s->sp > eindex) {
+      end = eindex;
+      s->sp -= size;
+    } else {
+      end = s->sp;
+      s->sp = sindex;
+    }
+    for (i = sindex; i < end; i++) {
+      if (s->str[i] == '\n')
+	s->line--;
+    }
+    assert(s->sp >= 0);
+  }
+  memmove(s->str + sindex, s->str + eindex, s->len - eindex);
+  s->len -= size;
+  s->str[s->len] = 0;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * DOH *String_str() - Returns a string (used by printing commands)
+ * ----------------------------------------------------------------------------- */
+
+static DOH *String_str(DOH *so) {
+  String *s = (String *) ObjData(so);
+  s->str[s->len] = 0;
+  return NewString(s->str);
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_read() - Read data from a string
+ * ----------------------------------------------------------------------------- */
+
+static int String_read(DOH *so, void *buffer, int len) {
+  int reallen, retlen;
+  char *cb;
+  String *s = (String *) ObjData(so);
+  if ((s->sp + len) > s->len)
+    reallen = (s->len - s->sp);
+  else
+    reallen = len;
+
+  cb = (char *) buffer;
+  retlen = reallen;
+
+  if (reallen > 0) {
+    memmove(cb, s->str + s->sp, reallen);
+    s->sp += reallen;
+  }
+  return retlen;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_write() - Write data to a string
+ * ----------------------------------------------------------------------------- */
+static int String_write(DOH *so, void *buffer, int len) {
+  int newlen;
+  String *s = (String *) ObjData(so);
+  s->hashkey = -1;
+  if (s->sp > s->len)
+    s->sp = s->len;
+  newlen = s->sp + len + 1;
+  if (newlen > s->maxsize) {
+    s->str = (char *) DohRealloc(s->str, newlen);
+    assert(s->str);
+    s->maxsize = newlen;
+    s->len = s->sp + len;
+  }
+  if ((s->sp + len) > s->len)
+    s->len = s->sp + len;
+  memmove(s->str + s->sp, buffer, len);
+  s->sp += len;
+  s->str[s->len] = 0;
+  return len;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_seek() - Seek to a new position
+ * ----------------------------------------------------------------------------- */
+
+static int String_seek(DOH *so, long offset, int whence) {
+  int pos, nsp, inc;
+  String *s = (String *) ObjData(so);
+  if (whence == SEEK_SET)
+    pos = 0;
+  else if (whence == SEEK_CUR)
+    pos = s->sp;
+  else if (whence == SEEK_END) {
+    pos = s->len;
+    offset = -offset;
+  } else
+    pos = s->sp;
+
+  nsp = pos + offset;
+  if (nsp < 0)
+    nsp = 0;
+  if (s->len > 0 && nsp > s->len)
+    nsp = s->len;
+
+  inc = (nsp > s->sp) ? 1 : -1;
+
+  {
+#if 0
+    register int sp = s->sp;
+    register char *tc = s->str;
+    register int len = s->len;
+    while (sp != nsp) {
+      int prev = sp + inc;
+      if (prev >= 0 && prev <= len && tc[prev] == '\n')
+	s->line += inc;
+      sp += inc;
+    }
+#else
+    register int sp = s->sp;
+    register char *tc = s->str;
+    if (inc > 0) {
+      while (sp != nsp) {
+	if (tc[++sp] == '\n')
+	  ++s->line;
+      }
+    } else {
+      while (sp != nsp) {
+	if (tc[--sp] == '\n')
+	  --s->line;
+      }
+    }
+#endif
+    s->sp = sp;
+  }
+  assert(s->sp >= 0);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * long String_tell() - Return current position
+ * ----------------------------------------------------------------------------- */
+
+static long String_tell(DOH *so) {
+  String *s = (String *) ObjData(so);
+  return (long) (s->sp);
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_putc()
+ * ----------------------------------------------------------------------------- */
+
+static int String_putc(DOH *so, int ch) {
+  String *s = (String *) ObjData(so);
+  register int len = s->len;
+  register int sp = s->sp;
+  s->hashkey = -1;
+  if (sp >= len) {
+    register int maxsize = s->maxsize;
+    register char *tc = s->str;
+    if (len > (maxsize - 2)) {
+      maxsize *= 2;
+      tc = (char *) DohRealloc(tc, maxsize);
+      assert(tc);
+      s->maxsize = (int) maxsize;
+      s->str = tc;
+    }
+    tc += sp;
+    *tc = (char) ch;
+    *(++tc) = 0;
+    s->len = s->sp = sp + 1;
+  } else {
+    s->str[s->sp++] = (char) ch;
+  }
+  if (ch == '\n')
+    s->line++;
+  return ch;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_getc()
+ * ----------------------------------------------------------------------------- */
+
+static int String_getc(DOH *so) {
+  int c;
+  String *s = (String *) ObjData(so);
+  if (s->sp >= s->len)
+    c = EOF;
+  else
+    c = (int)(unsigned char) s->str[s->sp++];
+  if (c == '\n')
+    s->line++;
+  return c;
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_ungetc()
+ * ----------------------------------------------------------------------------- */
+
+static int String_ungetc(DOH *so, int ch) {
+  String *s = (String *) ObjData(so);
+  if (ch == EOF)
+    return ch;
+  if (s->sp <= 0)
+    return EOF;
+  s->sp--;
+  if (ch == '\n')
+    s->line--;
+  return ch;
+}
+
+/* -----------------------------------------------------------------------------
+ * replace_simple(String *str, char *token, char *rep, int flags, int count)
+ *
+ * Replaces count non-overlapping occurrences of token with rep in a string.   
+ * ----------------------------------------------------------------------------- */
+
+static char *end_quote(char *s) {
+  char *qs;
+  char qc;
+  char *q;
+  char *nl;
+  qc = *s;
+  qs = s;
+  while (1) {
+    q = strpbrk(s + 1, "\"\'");
+    nl = strchr(s + 1, '\n');
+    if (nl && (nl < q)) {
+      /* A new line appears before the end of the string */
+      if (*(nl - 1) == '\\') {
+	s = nl + 1;
+	continue;
+      }
+      /* String was terminated by a newline.  Wing it */
+      return qs;
+    }
+    if (!q && nl) {
+      return qs;
+    }
+    if (!q)
+      return 0;
+    if ((*q == qc) && (*(q - 1) != '\\'))
+      return q;
+    s = q;
+  }
+}
+
+static char *match_simple(char *base, char *s, char *token, int tokenlen) {
+  (void) base;
+  (void) tokenlen;
+  return strstr(s, token);
+}
+
+static char *match_identifier(char *base, char *s, char *token, int tokenlen) {
+  while (s) {
+    s = strstr(s, token);
+    if (!s)
+      return 0;
+    if ((s > base) && (isalnum((int) *(s - 1)) || (*(s - 1) == '_'))) {
+      s += tokenlen;
+      continue;
+    }
+    if (isalnum((int) *(s + tokenlen)) || (*(s + tokenlen) == '_')) {
+      s += tokenlen;
+      continue;
+    }
+    return s;
+  }
+  return 0;
+}
+
+
+static char *match_identifier_begin(char *base, char *s, char *token, int tokenlen) {
+  while (s) {
+    s = strstr(s, token);
+    if (!s)
+      return 0;
+    if ((s > base) && (isalnum((int) *(s - 1)) || (*(s - 1) == '_'))) {
+      s += tokenlen;
+      continue;
+    }
+    return s;
+  }
+  return 0;
+}
+
+static char *match_identifier_end(char *base, char *s, char *token, int tokenlen) {
+  (void) base;
+  while (s) {
+    s = strstr(s, token);
+    if (!s)
+      return 0;
+    if (isalnum((int) *(s + tokenlen)) || (*(s + tokenlen) == '_')) {
+      s += tokenlen;
+      continue;
+    }
+    return s;
+  }
+  return 0;
+}
+
+static int replace_simple(String *str, char *token, char *rep, int flags, int count, char *(*match) (char *, char *, char *, int)) {
+  int tokenlen;			/* Length of the token */
+  int replen;			/* Length of the replacement */
+  int delta, expand = 0;
+  int ic;
+  int rcount = 0;
+  int noquote = 0;
+  char *c, *s, *t, *first;
+  char *q, *q2;
+  register char *base;
+  int i;
+
+  /* Figure out if anything gets replaced */
+  if (!strlen(token))
+    return 0;
+
+  base = str->str;
+  tokenlen = strlen(token);
+  s = (*match) (base, base, token, tokenlen);
+
+  if (!s)
+    return 0;			/* No matches.  Who cares */
+
+  str->hashkey = -1;
+
+  if (flags & DOH_REPLACE_NOQUOTE)
+    noquote = 1;
+
+  /* If we are not replacing inside quotes, we need to do a little extra work */
+  if (noquote) {
+    q = strpbrk(base, "\"\'");
+    if (!q) {
+      noquote = 0;		/* Well, no quotes to worry about. Oh well */
+    } else {
+      while (q && (q < s)) {
+	/* First match was found inside a quote.  Try to find another match */
+	q2 = end_quote(q);
+	if (!q2) {
+	  return 0;
+	}
+	if (q2 > s) {
+	  /* Find next match */
+	  s = (*match) (base, q2 + 1, token, tokenlen);
+	}
+	if (!s)
+	  return 0;		/* Oh well, no matches */
+	q = strpbrk(q2 + 1, "\"\'");
+	if (!q)
+	  noquote = 0;		/* No more quotes */
+      }
+    }
+  }
+
+  first = s;
+  replen = strlen(rep);
+
+  delta = (replen - tokenlen);
+
+  if (delta <= 0) {
+    /* String is either shrinking or staying the same size */
+    /* In this case, we do the replacement in place without memory reallocation */
+    ic = count;
+    t = s;			/* Target of memory copies */
+    while (ic && s) {
+      if (replen) {
+	memcpy(t, rep, replen);
+	t += replen;
+      }
+      rcount++;
+      expand += delta;
+      /* Find the next location */
+      s += tokenlen;
+      if (ic == 1)
+	break;
+      c = (*match) (base, s, token, tokenlen);
+
+      if (noquote) {
+	q = strpbrk(s, "\"\'");
+	if (!q) {
+	  noquote = 0;
+	} else {
+	  while (q && (q < c)) {
+	    /* First match was found inside a quote.  Try to find another match */
+	    q2 = end_quote(q);
+	    if (!q2) {
+	      c = 0;
+	      break;
+	    }
+	    if (q2 > c)
+	      c = (*match) (base, q2 + 1, token, tokenlen);
+	    if (!c)
+	      break;
+	    q = strpbrk(q2 + 1, "\"\'");
+	    if (!q)
+	      noquote = 0;	/* No more quotes */
+	  }
+	}
+      }
+      if (delta) {
+	if (c) {
+	  memmove(t, s, c - s);
+	  t += (c - s);
+	} else {
+	  memmove(t, s, (str->str + str->len) - s + 1);
+	}
+      } else {
+	t += (c - s);
+      }
+      s = c;
+      ic--;
+    }
+    if (s && delta) {
+      memmove(t, s, (str->str + str->len) - s + 1);
+    }
+    str->len += expand;
+    str->str[str->len] = 0;
+    if (str->sp >= str->len)
+      str->sp += expand;	/* Fix the end of file pointer */
+    return rcount;
+  }
+  /* The string is expanding as a result of the replacement */
+  /* Figure out how much expansion is going to occur and allocate a new string */
+  {
+    char *ns;
+    int newsize;
+
+    rcount++;
+    ic = count - 1;
+    s += tokenlen;
+    while (ic && (c = (*match) (base, s, token, tokenlen))) {
+      if (noquote) {
+	q = strpbrk(s, "\"\'");
+	if (!q) {
+	  break;
+	} else {
+	  while (q && (q < c)) {
+	    /* First match was found inside a quote.  Try to find another match */
+	    q2 = end_quote(q);
+	    if (!q2) {
+	      c = 0;
+	      break;
+	    }
+	    if (q2 > c) {
+	      c = (*match) (base, q2 + 1, token, tokenlen);
+	      if (!c)
+		break;
+	    }
+	    q = strpbrk(q2 + 1, "\"\'");
+	    if (!q)
+	      noquote = 0;
+	  }
+	}
+      }
+      if (c) {
+	rcount++;
+	ic--;
+	s = c + tokenlen;
+      } else {
+	break;
+      }
+    }
+
+    expand = delta * rcount;	/* Total amount of expansion for the replacement */
+    newsize = str->maxsize;
+    while ((str->len + expand) >= newsize)
+      newsize *= 2;
+
+    ns = (char *) DohMalloc(newsize);
+    assert(ns);
+    t = ns;
+    s = first;
+
+    /* Copy the first part of the string */
+    if (first > str->str) {
+      memcpy(t, str->str, (first - str->str));
+      t += (first - str->str);
+    }
+    for (i = 0; i < rcount; i++) {
+      memcpy(t, rep, replen);
+      t += replen;
+      s += tokenlen;
+      c = (*match) (base, s, token, tokenlen);
+      if (noquote) {
+	q = strpbrk(s, "\"\'");
+	if (!q) {
+	  noquote = 0;
+	} else {
+	  while (q && (q < c)) {
+	    /* First match was found inside a quote.  Try to find another match */
+	    q2 = end_quote(q);
+	    if (!q2) {
+	      c = 0;
+	      break;
+	    }
+	    if (q2 > c) {
+	      c = (*match) (base, q2 + 1, token, tokenlen);
+	      if (!c)
+		break;
+	    }
+	    q = strpbrk(q2 + 1, "\"\'");
+	    if (!q)
+	      noquote = 0;	/* No more quotes */
+	  }
+	}
+      }
+      if (i < (rcount - 1)) {
+	memcpy(t, s, c - s);
+	t += (c - s);
+      } else {
+	memcpy(t, s, (str->str + str->len) - s + 1);
+      }
+      s = c;
+    }
+    c = str->str;
+    str->str = ns;
+    if (str->sp >= str->len)
+      str->sp += expand;
+    str->len += expand;
+    str->str[str->len] = 0;
+    str->maxsize = newsize;
+    DohFree(c);
+    return rcount;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * int String_replace()
+ * ----------------------------------------------------------------------------- */
+
+static int String_replace(DOH *stro, DOH *token, DOH *rep, int flags) {
+  int count = -1;
+  String *str = (String *) ObjData(stro);
+
+  if (flags & DOH_REPLACE_FIRST)
+    count = 1;
+
+  if (flags & DOH_REPLACE_ID_END) {
+    return replace_simple(str, Char(token), Char(rep), flags, count, match_identifier_end);
+  } else if (flags & DOH_REPLACE_ID_BEGIN) {
+    return replace_simple(str, Char(token), Char(rep), flags, count, match_identifier_begin);
+  } else if (flags & DOH_REPLACE_ID) {
+    return replace_simple(str, Char(token), Char(rep), flags, count, match_identifier);
+  } else {
+    return replace_simple(str, Char(token), Char(rep), flags, count, match_simple);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * void String_chop(DOH *str)
+ * ----------------------------------------------------------------------------- */
+
+static void String_chop(DOH *so) {
+  char *c;
+  String *str = (String *) ObjData(so);
+  /* Replace trailing whitespace */
+  c = str->str + str->len - 1;
+  while ((str->len > 0) && (isspace((int) *c))) {
+    if (str->sp >= str->len) {
+      str->sp--;
+      if (*c == '\n')
+	str->line--;
+    }
+    str->len--;
+    c--;
+  }
+  str->str[str->len] = 0;
+  assert(str->sp >= 0);
+  str->hashkey = -1;
+}
+
+static void String_setfile(DOH *so, DOH *file) {
+  DOH *fo;
+  String *str = (String *) ObjData(so);
+
+  if (!DohCheck(file)) {
+    fo = NewString(file);
+    Decref(fo);
+  } else
+    fo = file;
+  Incref(fo);
+  Delete(str->file);
+  str->file = fo;
+}
+
+static DOH *String_getfile(DOH *so) {
+  String *str = (String *) ObjData(so);
+  return str->file;
+}
+
+static void String_setline(DOH *so, int line) {
+  String *str = (String *) ObjData(so);
+  str->line = line;
+}
+
+static int String_getline(DOH *so) {
+  String *str = (String *) ObjData(so);
+  return str->line;
+}
+
+static DohListMethods StringListMethods = {
+  0,				/* doh_getitem */
+  0,				/* doh_setitem */
+  String_delitem,		/* doh_delitem */
+  String_insert,		/* doh_insitem */
+  String_delslice,		/* doh_delslice */
+};
+
+static DohFileMethods StringFileMethods = {
+  String_read,
+  String_write,
+  String_putc,
+  String_getc,
+  String_ungetc,
+  String_seek,
+  String_tell,
+  0,				/* close */
+};
+
+static DohStringMethods StringStringMethods = {
+  String_replace,
+  String_chop,
+};
+
+DohObjInfo DohStringType = {
+  "String",			/* objname */
+  DelString,			/* doh_del */
+  CopyString,			/* doh_copy */
+  String_clear,			/* doh_clear */
+  String_str,			/* doh_str */
+  String_data,			/* doh_data */
+  String_dump,			/* doh_dump */
+  String_len,	    	        /* doh_len */
+  String_hash,			/* doh_hash    */
+  String_cmp,			/* doh_cmp */
+  String_equal,	    	        /* doh_equal */
+  0,				/* doh_first    */
+  0,				/* doh_next     */
+  String_setfile,		/* doh_setfile */
+  String_getfile,		/* doh_getfile */
+  String_setline,		/* doh_setline */
+  String_getline,		/* doh_getline */
+  0,				/* doh_mapping */
+  &StringListMethods,		/* doh_sequence */
+  &StringFileMethods,		/* doh_file */
+  &StringStringMethods,		/* doh_string */
+  0,				/* doh_position */
+  0
+};
+
+
+#define INIT_MAXSIZE  16
+
+/* -----------------------------------------------------------------------------
+ * NewString(const char *c) - Create a new string
+ * ----------------------------------------------------------------------------- */
+
+DOHString *DohNewString(const DOH *so) {
+  int l = 0, max;
+  String *str;
+  char *s;
+  int hashkey = -1;
+  if (DohCheck(so)) {
+    str = (String *) ObjData(so);
+    s = (char *) String_data((String *) so);
+    l = s ? str->len : 0;
+    hashkey = str->hashkey;
+  } else {
+    s = (char *) so;
+    l = s ? (int) strlen(s) : 0;
+  }
+
+  str = (String *) DohMalloc(sizeof(String));
+  str->hashkey = hashkey;
+  str->sp = 0;
+  str->line = 1;
+  str->file = 0;
+  max = INIT_MAXSIZE;
+  if (s) {
+    if ((l + 1) > max)
+      max = l + 1;
+  }
+  str->str = (char *) DohMalloc(max);
+  str->maxsize = max;
+  if (s) {
+    strcpy(str->str, s);
+    str->len = l;
+    str->sp = l;
+  } else {
+    str->str[0] = 0;
+    str->len = 0;
+  }
+  return DohObjMalloc(&DohStringType, str);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * NewStringEmpty() - Create a new string
+ * ----------------------------------------------------------------------------- */
+
+DOHString *DohNewStringEmpty() {
+  int max = INIT_MAXSIZE;
+  String *str = (String *) DohMalloc(sizeof(String));
+  str->hashkey = 0;
+  str->sp = 0;
+  str->line = 1;
+  str->file = 0;
+  str->str = (char *) DohMalloc(max);
+  str->maxsize = max;
+  str->str[0] = 0;
+  str->len = 0;
+  return DohObjMalloc(&DohStringType, str);
+}
+
+/* -----------------------------------------------------------------------------
+ * NewStringWithSize(const char *c, int len) - Create a new string
+ * ----------------------------------------------------------------------------- */
+
+DOHString *DohNewStringWithSize(const DOH *so, int len) {
+  int l = 0, max;
+  String *str;
+  char *s;
+  if (DohCheck(so)) {
+    s = (char *) String_data((String *) so);
+  } else {
+    s = (char *) so;
+  }
+
+  str = (String *) DohMalloc(sizeof(String));
+  str->hashkey = -1;
+  str->sp = 0;
+  str->line = 1;
+  str->file = 0;
+  max = INIT_MAXSIZE;
+  if (s) {
+    l = (int) len;
+    if ((l + 1) > max)
+      max = l + 1;
+  }
+  str->str = (char *) DohMalloc(max);
+  str->maxsize = max;
+  if (s) {
+    strncpy(str->str, s, len);
+    str->len = l;
+    str->sp = l;
+  } else {
+    str->str[0] = 0;
+    str->len = 0;
+  }
+  return DohObjMalloc(&DohStringType, str);
+}
+
+/* -----------------------------------------------------------------------------
+ * NewStringf(DOH *fmt, ...)
+ *
+ * Create a new string from a list of objects.
+ * ----------------------------------------------------------------------------- */
+
+DOHString *DohNewStringf(const DOH *fmt, ...) {
+  va_list ap;
+  DOH *r;
+  va_start(ap, fmt);
+  r = NewStringEmpty();
+  DohvPrintf(r, Char(fmt), ap);
+  va_end(ap);
+  return (DOHString *) r;
+}
+
+/* -----------------------------------------------------------------------------
+ * Strcmp()
+ * Strncmp()
+ * Strstr()
+ * Strchr()
+ *
+ * Some utility functions.
+ * ----------------------------------------------------------------------------- */
+
+int DohStrcmp(const DOHString_or_char *s1, const DOHString_or_char *s2) {
+  const char *c1 = Char(s1);
+  const char *c2 = Char(s2);
+  if (c1 && c2) {
+    return strcmp(c1, c2);
+  } else {
+    return c1 < c2;
+  }
+}
+
+int DohStrncmp(const DOHString_or_char *s1, const DOHString_or_char *s2, int n) {
+  return strncmp(Char(s1), Char(s2), n);
+}
+
+char *DohStrstr(const DOHString_or_char *s1, const DOHString_or_char *s2) {
+  char *p1 = Char(s1);
+  char *p2 = Char(s2);
+  return p1 == 0 || p2 == 0 || *p2 == '\0' ? p1 : strstr(p1, p2);
+}
+
+char *DohStrchr(const DOHString_or_char *s1, int ch) {
+  return strchr(Char(s1), ch);
+}
diff --git a/trunk/Source/DOH/void.c b/trunk/Source/DOH/void.c
new file mode 100644
index 0000000..0be0156
--- /dev/null
+++ b/trunk/Source/DOH/void.c
@@ -0,0 +1,96 @@
+/* ----------------------------------------------------------------------------- 
+ * void.c
+ *
+ *     Implements a "void" object that is really just a DOH container around
+ *     an arbitrary C object represented as a void *.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 1999-2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_void_c[] = "$Id$";
+
+#include "dohint.h"
+
+typedef struct {
+  void *ptr;
+  void (*del) (void *);
+} VoidObj;
+
+/* -----------------------------------------------------------------------------
+ * Void_delete()
+ *
+ * Delete a void object. Invokes the destructor supplied at the time of creation.
+ * ----------------------------------------------------------------------------- */
+
+static void Void_delete(DOH *vo) {
+  VoidObj *v = (VoidObj *) ObjData(vo);
+  if (v->del)
+    (*v->del) (v->ptr);
+  DohFree(v);
+}
+
+/* -----------------------------------------------------------------------------
+ * Void_copy()
+ *
+ * Copies a void object.  This is only a shallow copy. The object destruction
+ * function is not copied in order to avoid potential double-free problems.
+ * ----------------------------------------------------------------------------- */
+
+static DOH *Void_copy(DOH *vo) {
+  VoidObj *v = (VoidObj *) ObjData(vo);
+  return NewVoid(v->ptr, 0);
+}
+
+/* -----------------------------------------------------------------------------
+ * Void_data()
+ *
+ * Returns the void * stored in the object.
+ * ----------------------------------------------------------------------------- */
+
+static void *Void_data(DOH *vo) {
+  VoidObj *v = (VoidObj *) ObjData(vo);
+  return v->ptr;
+}
+
+static DohObjInfo DohVoidType = {
+  "VoidObj",			/* objname */
+  Void_delete,			/* doh_del */
+  Void_copy,			/* doh_copy */
+  0,				/* doh_clear */
+  0,				/* doh_str */
+  Void_data,			/* doh_data */
+  0,				/* doh_dump */
+  0,				/* doh_len */
+  0,				/* doh_hash    */
+  0,				/* doh_cmp */
+  0,				/* doh_equal    */
+  0,				/* doh_first    */
+  0,				/* doh_next     */
+  0,				/* doh_setfile */
+  0,				/* doh_getfile */
+  0,				/* doh_setline */
+  0,				/* doh_getline */
+  0,				/* doh_mapping */
+  0,				/* doh_sequence */
+  0,				/* doh_file  */
+  0,				/* doh_string */
+  0,				/* doh_reserved */
+  0,				/* clientdata */
+};
+
+/* -----------------------------------------------------------------------------
+ * NewVoid()
+ *
+ * Creates a new Void object given a void * and an optional destructor function.
+ * ----------------------------------------------------------------------------- */
+
+DOH *DohNewVoid(void *obj, void (*del) (void *)) {
+  VoidObj *v;
+  v = (VoidObj *) DohMalloc(sizeof(VoidObj));
+  v->ptr = obj;
+  v->del = del;
+  return DohObjMalloc(&DohVoidType, v);
+}
diff --git a/trunk/Source/Include/swigwarn.h b/trunk/Source/Include/swigwarn.h
new file mode 100644
index 0000000..174e8b0
--- /dev/null
+++ b/trunk/Source/Include/swigwarn.h
@@ -0,0 +1,259 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigwarn.h
+ *
+ * SWIG warning message numbers
+ * This file serves as the main registry of warning message numbers.  Some of these
+ * numbers are used internally in the C/C++ source code of SWIG.   However, some
+ * of the numbers are used in SWIG configuration files (swig.swg and others).
+ *
+ * The numbers are roughly organized into a few different classes by functionality.
+ *
+ * Even though symbolic constants are used in the SWIG source, this is
+ * not always the case in SWIG interface files.  Do not change the
+ * numbers in this file.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id$ */
+
+#ifndef SWIGWARN_H_
+#define SWIGWARN_H_
+
+#define WARN_NONE                     0
+
+/* -- Deprecated features -- */
+
+#define WARN_DEPRECATED_EXTERN        101
+#define WARN_DEPRECATED_VAL           102
+#define WARN_DEPRECATED_OUT           103
+#define WARN_DEPRECATED_DISABLEDOC    104
+#define WARN_DEPRECATED_ENABLEDOC     105
+#define WARN_DEPRECATED_DOCONLY       106
+#define WARN_DEPRECATED_STYLE         107
+#define WARN_DEPRECATED_LOCALSTYLE    108
+#define WARN_DEPRECATED_TITLE         109
+#define WARN_DEPRECATED_SECTION       110
+#define WARN_DEPRECATED_SUBSECTION    111
+#define WARN_DEPRECATED_SUBSUBSECTION 112
+#define WARN_DEPRECATED_ADDMETHODS    113
+#define WARN_DEPRECATED_READONLY      114
+#define WARN_DEPRECATED_READWRITE     115
+#define WARN_DEPRECATED_EXCEPT        116
+#define WARN_DEPRECATED_NEW           117
+#define WARN_DEPRECATED_EXCEPT_TM     118
+#define WARN_DEPRECATED_IGNORE_TM     119
+#define WARN_DEPRECATED_OPTC          120
+#define WARN_DEPRECATED_NAME          121
+#define WARN_DEPRECATED_NOEXTERN      122
+#define WARN_DEPRECATED_NODEFAULT     123
+#define WARN_DEPRECATED_TYPEMAP_LANG  124
+
+/* -- Preprocessor -- */
+
+#define WARN_PP_MISSING_FILE          201
+#define WARN_PP_EVALUATION            202
+#define WARN_PP_INCLUDEALL_IMPORTALL  203
+#define WARN_PP_CPP_WARNING           204
+#define WARN_PP_CPP_ERROR             205
+
+/* -- C/C++ Parser -- */
+
+#define WARN_PARSE_CLASS_KEYWORD      301
+#define WARN_PARSE_REDEFINED          302
+#define WARN_PARSE_EXTEND_UNDEF       303
+#define WARN_PARSE_UNSUPPORTED_VALUE  304
+#define WARN_PARSE_BAD_VALUE          305
+#define WARN_PARSE_PRIVATE            306
+#define WARN_PARSE_BAD_DEFAULT        307
+#define WARN_PARSE_NAMESPACE_ALIAS    308
+#define WARN_PARSE_PRIVATE_INHERIT    309
+#define WARN_PARSE_TEMPLATE_REPEAT    310
+#define WARN_PARSE_TEMPLATE_PARTIAL   311
+#define WARN_PARSE_NESTED_CLASS       312
+#define WARN_PARSE_UNDEFINED_EXTERN   313
+#define WARN_PARSE_KEYWORD            314
+#define WARN_PARSE_USING_UNDEF        315
+#define WARN_PARSE_MODULE_REPEAT      316
+#define WARN_PARSE_TEMPLATE_SP_UNDEF  317
+#define WARN_PARSE_TEMPLATE_AMBIG     318
+#define WARN_PARSE_NO_ACCESS          319
+#define WARN_PARSE_EXPLICIT_TEMPLATE  320
+#define WARN_PARSE_BUILTIN_NAME       321
+#define WARN_PARSE_REDUNDANT          322
+#define WARN_PARSE_REC_INHERITANCE    323
+
+#define WARN_IGNORE_OPERATOR_NEW        350	/* new */
+#define WARN_IGNORE_OPERATOR_DELETE     351	/* delete */
+#define WARN_IGNORE_OPERATOR_PLUS       352	/* + */
+#define WARN_IGNORE_OPERATOR_MINUS      353	/* - */
+#define WARN_IGNORE_OPERATOR_MUL        354	/* * */
+#define WARN_IGNORE_OPERATOR_DIV        355	/* / */
+#define WARN_IGNORE_OPERATOR_MOD        356	/* % */
+#define WARN_IGNORE_OPERATOR_XOR        357	/* ^ */
+#define WARN_IGNORE_OPERATOR_AND        358	/* & */
+#define WARN_IGNORE_OPERATOR_OR         359	/* | */
+#define WARN_IGNORE_OPERATOR_NOT        360	/* ~ */
+#define WARN_IGNORE_OPERATOR_LNOT       361	/* ! */
+#define WARN_IGNORE_OPERATOR_EQ         362	/* = */
+#define WARN_IGNORE_OPERATOR_LT         363	/* < */
+#define WARN_IGNORE_OPERATOR_GT         364	/* > */
+#define WARN_IGNORE_OPERATOR_PLUSEQ     365	/* += */
+#define WARN_IGNORE_OPERATOR_MINUSEQ    366	/* -= */
+#define WARN_IGNORE_OPERATOR_MULEQ      367	/* *= */
+#define WARN_IGNORE_OPERATOR_DIVEQ      368	/* /= */
+#define WARN_IGNORE_OPERATOR_MODEQ      369	/* %= */
+#define WARN_IGNORE_OPERATOR_XOREQ      370	/* ^= */
+#define WARN_IGNORE_OPERATOR_ANDEQ      371	/* &= */
+#define WARN_IGNORE_OPERATOR_OREQ       372	/* |= */
+#define WARN_IGNORE_OPERATOR_LSHIFT     373	/* << */
+#define WARN_IGNORE_OPERATOR_RSHIFT     374	/* >> */
+#define WARN_IGNORE_OPERATOR_LSHIFTEQ   375	/* <<= */
+#define WARN_IGNORE_OPERATOR_RSHIFTEQ   376	/* >>= */
+#define WARN_IGNORE_OPERATOR_EQUALTO    377	/* == */
+#define WARN_IGNORE_OPERATOR_NOTEQUAL   378	/* != */
+#define WARN_IGNORE_OPERATOR_LTEQUAL    379	/* <= */
+#define WARN_IGNORE_OPERATOR_GTEQUAL    380	/* >= */
+#define WARN_IGNORE_OPERATOR_LAND       381	/* && */
+#define WARN_IGNORE_OPERATOR_LOR        382	/* || */
+#define WARN_IGNORE_OPERATOR_PLUSPLUS   383	/* ++ */
+#define WARN_IGNORE_OPERATOR_MINUSMINUS 384	/* -- */
+#define WARN_IGNORE_OPERATOR_COMMA      385	/* , */
+#define WARN_IGNORE_OPERATOR_ARROWSTAR  386	/* ->* */
+#define WARN_IGNORE_OPERATOR_ARROW      387	/* -> */
+#define WARN_IGNORE_OPERATOR_CALL       388	/* () */
+#define WARN_IGNORE_OPERATOR_INDEX      389	/* [] */
+#define WARN_IGNORE_OPERATOR_UPLUS      390	/* + */
+#define WARN_IGNORE_OPERATOR_UMINUS     391	/* - */
+#define WARN_IGNORE_OPERATOR_UMUL       392	/* * */
+#define WARN_IGNORE_OPERATOR_UAND       393	/* & */
+#define WARN_IGNORE_OPERATOR_NEWARR     394	/* new [] */
+#define WARN_IGNORE_OPERATOR_DELARR     395	/* delete [] */
+#define WARN_IGNORE_OPERATOR_REF        396	/* operator *() */
+
+/* 394-399 are reserved */
+
+/* -- Type system and typemaps -- */
+
+#define WARN_TYPE_UNDEFINED_CLASS     401
+#define WARN_TYPE_INCOMPLETE          402
+#define WARN_TYPE_ABSTRACT            403
+#define WARN_TYPE_REDEFINED           404
+
+#define WARN_TYPEMAP_SOURCETARGET     450
+#define WARN_TYPEMAP_CHARLEAK         451
+#define WARN_TYPEMAP_SWIGTYPE         452
+#define WARN_TYPEMAP_APPLY_UNDEF      453
+#define WARN_TYPEMAP_SWIGTYPELEAK     454
+
+#define WARN_TYPEMAP_IN_UNDEF         460
+#define WARN_TYPEMAP_OUT_UNDEF        461
+#define WARN_TYPEMAP_VARIN_UNDEF      462
+#define WARN_TYPEMAP_VAROUT_UNDEF     463
+#define WARN_TYPEMAP_CONST_UNDEF      464
+#define WARN_TYPEMAP_UNDEF            465
+#define WARN_TYPEMAP_VAR_UNDEF        466
+#define WARN_TYPEMAP_TYPECHECK        467
+#define WARN_TYPEMAP_THROW            468
+#define WARN_TYPEMAP_DIRECTORIN_UNDEF  469
+#define WARN_TYPEMAP_THREAD_UNSAFE     470	/* mostly used in directorout typemaps */
+#define WARN_TYPEMAP_DIRECTOROUT_UNDEF 471
+#define WARN_TYPEMAP_TYPECHECK_UNDEF   472
+#define WARN_TYPEMAP_DIRECTOROUT_PTR   473
+#define WARN_TYPEMAP_OUT_OPTIMAL_IGNORED  474
+#define WARN_TYPEMAP_OUT_OPTIMAL_MULTIPLE 475
+
+/* -- Fragments -- */
+#define WARN_FRAGMENT_NOT_FOUND       490
+
+/* -- General code generation -- */
+
+#define WARN_LANG_OVERLOAD_DECL       501
+#define WARN_LANG_OVERLOAD_CONSTRUCT  502
+#define WARN_LANG_IDENTIFIER          503
+#define WARN_LANG_RETURN_TYPE         504
+#define WARN_LANG_VARARGS             505
+#define WARN_LANG_VARARGS_KEYWORD     506
+#define WARN_LANG_NATIVE_UNIMPL       507
+#define WARN_LANG_DEREF_SHADOW        508
+#define WARN_LANG_OVERLOAD_SHADOW     509
+#define WARN_LANG_FRIEND_IGNORE       510
+#define WARN_LANG_OVERLOAD_KEYWORD    511
+#define WARN_LANG_OVERLOAD_CONST      512
+#define WARN_LANG_CLASS_UNNAMED       513
+#define WARN_LANG_DIRECTOR_VDESTRUCT  514
+#define WARN_LANG_DISCARD_CONST       515
+#define WARN_LANG_OVERLOAD_IGNORED    516
+#define WARN_LANG_DIRECTOR_ABSTRACT   517
+#define WARN_LANG_PORTABILITY_FILENAME 518
+#define WARN_LANG_TEMPLATE_METHOD_IGNORE 519
+
+/* -- Reserved (600-799) -- */
+
+/* -- Language module specific warnings (800 - 999) -- */
+
+#define WARN_RUBY_WRONG_NAME                  801
+#define WARN_RUBY_MULTIPLE_INHERITANCE        802
+
+#define WARN_JAVA_TYPEMAP_JNI_UNDEF           810
+#define WARN_JAVA_TYPEMAP_JTYPE_UNDEF         811
+#define WARN_JAVA_TYPEMAP_JSTYPE_UNDEF        812
+#define WARN_JAVA_MULTIPLE_INHERITANCE        813
+#define WARN_JAVA_TYPEMAP_GETCPTR_UNDEF       814
+#define WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF      815
+#define WARN_JAVA_TYPEMAP_JAVABODY_UNDEF      816
+#define WARN_JAVA_TYPEMAP_JAVAOUT_UNDEF       817
+#define WARN_JAVA_TYPEMAP_JAVAIN_UNDEF        818
+#define WARN_JAVA_TYPEMAP_JAVADIRECTORIN_UNDEF    819
+#define WARN_JAVA_TYPEMAP_JAVADIRECTOROUT_UNDEF   820
+#define WARN_JAVA_COVARIANT_RET               822
+#define WARN_JAVA_TYPEMAP_JAVACONSTRUCT_UNDEF 823
+#define WARN_JAVA_TYPEMAP_DIRECTORIN_NODESC   824
+#define WARN_JAVA_NO_DIRECTORCONNECT_ATTR     825
+
+/* please leave 810-829 free for Java */
+
+#define WARN_CSHARP_TYPEMAP_CTYPE_UNDEF       830
+#define WARN_CSHARP_TYPEMAP_CSTYPE_UNDEF      831
+#define WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF     832
+#define WARN_CSHARP_MULTIPLE_INHERITANCE      833
+#define WARN_CSHARP_TYPEMAP_GETCPTR_UNDEF     834
+#define WARN_CSHARP_TYPEMAP_CLASSMOD_UNDEF    835
+#define WARN_CSHARP_TYPEMAP_CSBODY_UNDEF      836
+#define WARN_CSHARP_TYPEMAP_CSOUT_UNDEF       837
+#define WARN_CSHARP_TYPEMAP_CSIN_UNDEF        838
+#define WARN_CSHARP_TYPEMAP_CSDIRECTORIN_UNDEF    839
+#define WARN_CSHARP_TYPEMAP_CSDIRECTOROUT_UNDEF   840
+#define WARN_CSHARP_COVARIANT_RET             842
+#define WARN_CSHARP_TYPEMAP_CSCONSTRUCT_UNDEF 843
+#define WARN_CSHARP_EXCODE                    844
+#define WARN_CSHARP_CANTHROW                  845
+#define WARN_CSHARP_NO_DIRECTORCONNECT_ATTR   846
+
+/* please leave 830-849 free for C# */
+
+#define WARN_MODULA3_TYPEMAP_TYPE_UNDEF        850
+#define WARN_MODULA3_TYPEMAP_GETCPTR_UNDEF     851
+#define WARN_MODULA3_TYPEMAP_CLASSMOD_UNDEF    852
+#define WARN_MODULA3_TYPEMAP_PTRCONSTMOD_UNDEF 853
+#define WARN_MODULA3_TYPEMAP_MULTIPLE_RETURN   854
+#define WARN_MODULA3_MULTIPLE_INHERITANCE      855
+#define WARN_MODULA3_TYPECONSTRUCTOR_UNKNOWN   856
+#define WARN_MODULA3_UNKNOWN_PRAGMA            857
+#define WARN_MODULA3_BAD_ENUMERATION           858
+#define WARN_MODULA3_DOUBLE_ID                 859
+#define WARN_MODULA3_BAD_IMPORT                860
+
+/* please leave 850-869 free for Modula 3 */
+
+#define WARN_PHP4_MULTIPLE_INHERITANCE         870
+#define WARN_PHP4_UNKNOWN_PRAGMA               871
+
+/* please leave 870-889 free for Php */
+
+
+/* Feel free to claim any number in this space that's not currently being used. Just make sure you
+   add an entry here */
+
+#endif
diff --git a/trunk/Source/Makefile.am b/trunk/Source/Makefile.am
new file mode 100644
index 0000000..a726713
--- /dev/null
+++ b/trunk/Source/Makefile.am
@@ -0,0 +1,145 @@
+## Process this file with automake to produce Makefile.in
+
+# subdir-objects generates object files using the directory structure of the source files.
+AUTOMAKE_OPTIONS = foreign nostdinc subdir-objects 1.7.2
+
+SOURCE_DIR=$(top_srcdir)/Source
+BUILD_SOURCE_DIR=$(top_builddir)/Source
+
+SWIG_CXX_DEFS = @SWILL@
+
+AM_CFLAGS =	-I$(BUILD_SOURCE_DIR)/Include	\
+		-I$(BUILD_SOURCE_DIR)/CParse	\
+		-I$(SOURCE_DIR)/Include		\
+		-I$(SOURCE_DIR)/DOH		\
+		-I$(SOURCE_DIR)/CParse		\
+		-I$(SOURCE_DIR)/Preprocessor	\
+		-I$(SOURCE_DIR)/Swig		\
+		-I$(SOURCE_DIR)/Modules
+
+AM_CXXFLAGS =	$(AM_CFLAGS)			\
+		$(SWIG_CXX_DEFS)
+
+AM_YFLAGS = -d
+
+BUILT_SOURCES = CParse/parser.h
+eswig_SOURCES =	CParse/cscanner.c		\
+		CParse/parser.y			\
+		CParse/templ.c			\
+		CParse/util.c			\
+		DOH/base.c			\
+		DOH/file.c			\
+		DOH/fio.c			\
+		DOH/hash.c			\
+		DOH/list.c			\
+		DOH/memory.c			\
+		DOH/string.c			\
+		DOH/void.c			\
+		Modules/allegrocl.cxx		\
+		Modules/allocate.cxx		\
+		Modules/browser.cxx		\
+		Modules/cffi.cxx		\
+		Modules/chicken.cxx		\
+		Modules/clisp.cxx		\
+		Modules/contract.cxx		\
+		Modules/csharp.cxx		\
+		Modules/directors.cxx		\
+		Modules/emit.cxx		\
+		Modules/guile.cxx		\
+		Modules/java.cxx		\
+		Modules/lang.cxx		\
+		Modules/lua.cxx			\
+		Modules/main.cxx		\
+		Modules/modula3.cxx		\
+		Modules/module.cxx		\
+		Modules/mzscheme.cxx		\
+		Modules/ocaml.cxx		\
+		Modules/octave.cxx		\
+		Modules/overload.cxx		\
+		Modules/perl5.cxx		\
+		Modules/php4.cxx		\
+		Modules/pike.cxx		\
+		Modules/python.cxx		\
+		Modules/r.cxx			\
+		Modules/ruby.cxx		\
+		Modules/s-exp.cxx		\
+		Modules/swigmain.cxx		\
+		Modules/tcl8.cxx		\
+		Modules/typepass.cxx		\
+		Modules/uffi.cxx		\
+		Modules/utils.cxx		\
+		Modules/xml.cxx			\
+		Preprocessor/cpp.c		\
+		Preprocessor/expr.c		\
+		Swig/cwrap.c			\
+		Swig/deprecate.c		\
+		Swig/error.c			\
+		Swig/fragment.c			\
+		Swig/getopt.c			\
+		Swig/include.c			\
+		Swig/misc.c			\
+		Swig/naming.c			\
+		Swig/parms.c			\
+		Swig/scanner.c			\
+		Swig/stype.c			\
+		Swig/symbol.c			\
+		Swig/tree.c			\
+		Swig/typeobj.c			\
+		Swig/typemap.c			\
+		Swig/typesys.c			\
+		Swig/warn.c			\
+		Swig/wrapfunc.c			
+
+bin_PROGRAMS = eswig
+eswig_LDADD   = @SWIGLIBS@
+
+# Override the link stage to avoid using Libtool
+CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
+
+# The executable is copied to the root directory for installation and running the test-suite.
+# This occurs on each invocation of make and is a step towards providing support for multiple 
+# build directories.
+all-local: eswig@EXEEXT@
+	cp -f $(top_builddir)/Source/eswig@EXEEXT@ $(top_builddir)/swig@EXEEXT@
+
+clean-local:
+	rm -f $(top_builddir)/swig@EXEEXT@
+	rm -f core @EXTRA_CLEAN@
+
+
+# Beautify the code.
+# Note that this works well on C code, but does some odd joining of lines for C++ code.
+# Compiling with -DNDEBUG and no optimisations will allow one to do a binary diff of the
+# swig executable as a way of checking before and after the 'beautifying'.
+# Single files can be beautified with the beautify-file target, eg: 'make beautify-file INDENTFILE=chosenfile.c'
+
+SWIGTYPEDEFS=-T File -T DohObjInfo -T Parm -T Language -T List -T Typetab -T ModuleFactory -T ErrorMessageFormat -T Symtab -T Hash -T String -T DohBase -T Node -T String_or_char -T SwigType -T Dispatcher -T Wrapper -T DohStringMethods -T DohFileMethods -T DohListMethods -T DohHashMethods -T DOH -T DohIterator -T ParmList -T FILE -T HashNode -T DOHString_or_char
+INDENTBAKSDIR=../IndentBaks
+
+beautify:
+	rm -rf $(INDENTBAKSDIR)
+	mkdir $(INDENTBAKSDIR)
+	mkdir $(INDENTBAKSDIR)/CParse
+	mkdir $(INDENTBAKSDIR)/DOH
+	mkdir $(INDENTBAKSDIR)/Modules
+	mkdir $(INDENTBAKSDIR)/Preprocessor
+	mkdir $(INDENTBAKSDIR)/Swig
+	mkdir $(INDENTBAKSDIR)/Include
+	(csources=`find . -name "*.c"` && \
+	hsources=`find . -name "*.h"` && \
+	cxxsources=`find . -name "*.cxx"` && \
+	for file in $$csources $$hsources $$cxxsources; do \
+	  $(MAKE) beautify-file INDENTFILE=$$file; \
+	done; )
+
+beautify-file:
+	test -e $(INDENTBAKSDIR) || (echo $(INDENTBAKSDIR) directory does not exist && exit 1;)
+	test -n "$(INDENTFILE)" || (echo INDENTFILE not defined && exit 1;)
+	test -e $(INDENTFILE) || (echo File does not exist: $(INDENTFILE) && exit 1;)
+	cp $(INDENTFILE) $(INDENTBAKSDIR)/$(INDENTFILE);
+	unix2dos $(INDENTFILE)
+	dos2unix $(INDENTFILE)
+	indent -kr --honour-newlines --line-length160 --indent-level2 --braces-on-func-def-line --leave-optional-blank-lines $(SWIGTYPEDEFS) $(INDENTFILE) -o $(INDENTFILE).tmp;
+	cat $(INDENTFILE).tmp | sed -e 's/const const /const /' > $(INDENTFILE);
+	rm $(INDENTFILE).tmp;
+
diff --git a/trunk/Source/Modules/README b/trunk/Source/Modules/README
new file mode 100644
index 0000000..058779d
--- /dev/null
+++ b/trunk/Source/Modules/README
@@ -0,0 +1,9 @@
+06/25/2002
+
+This directory contains all of the SWIG language modules.  Many of these
+modules contain code that dates back to SWIG1.0.  The module API has changed
+a lot in the development releases so this is fairly messy.  We're working on
+cleaning it up, but you'll have to bear with us until it's done.
+
+-- Dave
+
diff --git a/trunk/Source/Modules/allegrocl.cxx b/trunk/Source/Modules/allegrocl.cxx
new file mode 100644
index 0000000..a968e50
--- /dev/null
+++ b/trunk/Source/Modules/allegrocl.cxx
@@ -0,0 +1,3114 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * allegrocl.cxx
+ *
+ * ALLEGROCL language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_allegrocl_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+#include <ctype.h>
+
+// #define ALLEGROCL_DEBUG
+// #define ALLEGROCL_WRAP_DEBUG
+// #define ALLEGROCL_TYPE_DEBUG
+// #define ALLEGROCL_CLASS_DEBUG
+
+static File *f_cl = 0;
+String *f_clhead = NewString("");
+String *f_clwrap = NewString("(swig-in-package ())\n\n");
+static File *f_cxx;
+static File *f_cxx_header = 0;
+static File *f_cxx_wrapper = 0;
+
+static String *module_name = 0;
+static String *swig_package = 0;
+
+const char *identifier_converter = "identifier-convert-null";
+
+static bool CWrap = true;	// generate wrapper file for C code by default. most correct.
+static bool Generate_Wrapper = false;
+static bool unique_swig_package = false;
+
+static String *current_namespace = NewString("");
+static String *current_package = NewString("");
+static Hash *defined_namespace_packages = NewHash();
+static Node *in_class = 0;
+
+static Node *first_linked_type = 0;
+static Hash *defined_foreign_types = NewHash();
+static Hash *defined_foreign_ltypes = NewHash();
+
+static String *anon_type_name = NewString("anontype");
+static int anon_type_count = 0;
+
+// stub
+String *convert_literal(String *num_param, String *type, bool try_to_split = true);
+
+class ALLEGROCL:public Language {
+public:
+  virtual void main(int argc, char *argv[]);
+  virtual int top(Node *n);
+  virtual int functionWrapper(Node *n);
+  virtual int namespaceDeclaration(Node *n);
+  virtual int constructorHandler(Node *n);
+  virtual int destructorHandler(Node *n);
+  virtual int globalvariableHandler(Node *n);
+  virtual int variableWrapper(Node *n);
+  virtual int constantWrapper(Node *n);
+  virtual int memberfunctionHandler(Node *n);
+  virtual int membervariableHandler(Node *n);
+  virtual int classHandler(Node *n);
+  virtual int emit_one(Node *n);
+  virtual int enumDeclaration(Node *n);
+  virtual int enumvalueDeclaration(Node *n);
+  virtual int typedefHandler(Node *n);
+  virtual int classforwardDeclaration(Node *n);
+  virtual int templateDeclaration(Node *n);
+  virtual int validIdentifier(String *s);
+private:
+  int emit_defun(Node *n, File *f_cl);
+  int emit_dispatch_defun(Node *n);
+  int emit_buffered_defuns(Node *n);
+  int cClassHandler(Node *n);
+  int cppClassHandler(Node *n);
+};
+static ALLEGROCL *allegrocl = 0;
+
+static String *trim(String *str) {
+  char *c = Char(str);
+  while (*c != '\0' && isspace((int) *c))
+    ++c;
+  String *result = NewString(c);
+  Chop(result);
+  return result;
+}
+
+int is_integer(String *s) {
+  char *c = Char(s);
+  if (c[0] == '#' && (c[1] == 'x' || c[1] == 'o'))
+    c += 2;
+
+  while (*c) {
+    if (!isdigit(*c))
+      return 0;
+    c++;
+  }
+  return 1;
+}
+
+String *class_from_class_or_class_ref(String *type) {
+  SwigType *stripped = SwigType_strip_qualifiers(type);
+  if (SwigType_isclass(stripped))
+    return stripped;
+
+  if (SwigType_ispointer(stripped) || SwigType_isreference(stripped)) {
+    // Printf(stderr,"It is a pointer/reference. Is it a class?\n");
+    SwigType_pop(stripped);
+    if (SwigType_isclass(stripped)) {
+      return stripped;
+    }
+  }
+  return 0;
+}
+
+String *lookup_defined_foreign_type(String *k) {
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "Looking up defined type '%s'.\n  Found: '%s'\n", k, Getattr(defined_foreign_types, k));
+#endif
+
+  return Getattr(defined_foreign_types, k);
+}
+
+String *listify_namespace(String *namespaze) {
+  if (Len(namespaze) == 0)
+    return NewString("()");
+  String *result = NewStringf("(\"%s\")", namespaze);
+  Replaceall(result, "::", "\" \"");
+  return result;
+}
+
+String *namespaced_name(Node *n, String *ns = current_namespace) {
+
+  return NewStringf("%s%s%s", ns, (Len(ns) != 0) ? "::" : "", Getattr(n, "sym:name"));
+}
+
+// "Namespace::Nested::Class2::Baz" -> "Baz"
+static String *strip_namespaces(String *str) {
+  char *result = Char(str);
+  String *stripped_one;
+  while ((stripped_one = Strstr(result, "::")))
+    result = Char(stripped_one) + 2;
+  return NewString(result);
+}
+
+static String *namespace_of(String *str) {
+  char *p = Char(str);
+  char *start = Char(str);
+  char *result = 0;
+  String *stripped_one;
+
+  while ((stripped_one = Strstr(p, "::"))) {
+    p = Char(stripped_one) + 2;
+  }
+  if (p > start) {
+    int len = p - start - 1;
+    result = (char *) malloc(len);
+    strncpy(result, start, len - 1);
+    result[len - 1] = 0;
+  }
+  return Char(result);
+}
+
+void add_linked_type(Node *n) {
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "Adding linked node of type: %s(%s) %s(%x)\n\n", nodeType(n), Getattr(n, "storage"), Getattr(n, "name"), n);
+#endif
+  if (!first_linked_type) {
+    first_linked_type = n;
+    Setattr(n, "allegrocl:last_linked_type", n);
+  } else {
+    Node *t = Getattr(first_linked_type, "allegrocl:last_linked_type");
+    Setattr(t, "allegrocl:next_linked_type", n);
+    Setattr(first_linked_type, "allegrocl:last_linked_type", n);
+  }
+}
+
+void replace_linked_type(Node *old, Node *new_node) {
+  Node *prev = Getattr(old, "allegrocl:prev_linked_type");
+
+  Setattr(new_node, "allegrocl:next_linked_type", Getattr(old, "allegrocl:next_linked_type"));
+  if (prev)
+    Setattr(prev, "allegrocl:next_linked_type", new_node);
+  Delattr(old, "allegrocl:next_linked_type");
+  Delattr(old, "allegrocl:prev_linked_type");
+
+  // check if we're replacing the first link.
+  if (first_linked_type == old) {
+    first_linked_type = new_node;
+    Setattr(first_linked_type, "allegrocl:last_linked_type", Getattr(old, "allegrocl:last_linked_type"));
+  }
+  // check if we're replacing the last link.
+  if (Getattr(first_linked_type, "allegrocl:last_linked_type") == old)
+    Setattr(first_linked_type, "allegrocl:last_linked_type", new_node);
+}
+
+void insert_linked_type_at(Node *old, Node *new_node, int before = 1) {
+  Node *p = 0;
+
+  if (!first_linked_type) {
+    add_linked_type(new_node);
+    return;
+  }
+
+  if (!before) {
+    Setattr(new_node, "allegrocl:next_linked_type", Getattr(old, "allegrocl:next_linked_type"));
+    Setattr(old, "allegrocl:next_linked_type", new_node);
+    if (Getattr(first_linked_type, "allegrocl:last_linked_type") == old)
+      Setattr(first_linked_type, "allegrocl:last_linked_type", new_node);
+  } else {
+    Node *c = first_linked_type;
+    while (c) {
+      if (c == old) {
+	break;
+      } else {
+	p = c;
+	c = Getattr(c, "allegrocl:next_linked_type");
+      }
+    }
+    if (c == old) {
+      Setattr(new_node, "allegrocl:next_linked_type", c);
+      if (first_linked_type == c) {
+	first_linked_type = new_node;
+	Setattr(first_linked_type, "allegrocl:last_linked_type", Getattr(c, "allegrocl:last_linked_type"));
+	Delattr(c, "allegrocl:last_linked_type");
+      }
+      if (p)
+	Setattr(p, "allegrocl:next_linked_type", new_node);
+    }
+  }
+}
+
+Node *find_linked_type_by_name(String *name) {
+  Node *p = 0;
+  Node *c = first_linked_type;
+
+  // Printf(stderr,"in find_linked_type_by_name '%s'...", name);
+  while (c) {
+    String *key = Getattr(c, "name");
+    if (!Strcmp(key, name)) {
+      break;
+    } else {
+      p = c;
+      c = Getattr(c, "allegrocl:next_linked_type");
+    }
+  }
+  // Printf(stderr,"exit find_linked_type_by_name.\n");
+
+  if (p && c)
+    Setattr(c, "allegrocl:prev_linked_type", p);
+  // Printf(stderr,"find_linked_type_by_name: DONE\n");
+  return c;
+}
+
+Node *get_primary_synonym_of(Node *n) {
+  Node *p = Getattr(n, "allegrocl:synonym-of");
+  Node *prim = n;
+
+  // Printf(stderr, "getting primary synonym of %x\n", n);
+  while (p) {
+    // Printf(stderr, "   found one! %x\n", p);
+    prim = p;
+    p = Getattr(p, "allegrocl:synonym-of");
+  }
+  // Printf(stderr,"get_primary_syn: DONE. returning %s(%x)\n", Getattr(prim,"name"),prim);
+  return prim;
+}
+
+void add_forward_referenced_type(Node *n, int overwrite = 0) {
+  String *k = Getattr(n, "name");
+  String *name = Getattr(n, "sym:name");
+  String *ns = listify_namespace(current_namespace);
+
+  String *val = Getattr(defined_foreign_types, k);
+
+  if (!val || overwrite) {
+#ifdef ALLEGROCL_TYPE_DEBUG
+    Printf(stderr, "Adding forward reference for %s (overwrite=%d)\n", k, overwrite);
+#endif
+    Setattr(defined_foreign_types, Copy(k), NewString("forward-reference"));
+
+    String *mangled_lname_gen = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", name, ns);
+
+    Setattr(defined_foreign_ltypes, Copy(k), mangled_lname_gen);
+    //    Printf(f_cl, ";; forward reference stub\n"
+    //           "(swig-def-foreign-class \"%s\" (ff:foreign-pointer) (:class ))\n\n"
+    //     , name);
+
+#ifdef ALLEGROCL_CLASS_DEBUG
+    Printf(stderr, "Linking forward reference type = %s(%x)\n", k, n);
+#endif
+    add_linked_type(n);
+  }
+}
+
+void add_defined_foreign_type(Node *n, int overwrite = 0, String *k = 0, String *name = 0, String *ns = current_namespace) {
+
+  String *val;
+  String *ns_list = listify_namespace(ns);
+  String *templated = n ? Getattr(n, "template") : 0;
+  String *cDeclName = n ? Getattr(n, "classDeclaration:name") : 0;
+
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "IN A-D-F-T. (n=%x, ow=%d, k=%s, name=%s, ns=%s\n", n, overwrite, k, name, ns);
+  Printf(stderr, "    templated = '%x', classDecl = '%x'\n", templated, cDeclName);
+#endif
+  if (n) {
+    if (!name)
+      name = Getattr(n, "sym:name");
+    if (!name)
+      name = strip_namespaces(Getattr(n, "name"));
+    if (templated) {
+      k = namespaced_name(n);
+    } else {
+      String *kind_of_type = Getattr(n, "kind");
+
+      /*
+         For typedefs of the form:
+
+         typedef __xxx { ... } xxx;
+
+         add_defined_foreign_type will be called once via classHandler
+         to define the type for 'struct __xxx', and once via typedefHandler
+         to associate xxx with 'struct __xxx'. 
+
+         We create the following type to identifier mappings:
+
+         struct __xxx -> (swig-insert-id "xxx")    via classHand
+         xxx -> (swig-insert-id "xxx")    via typedefHand
+
+         and all references to this typedef'd struct will appear in 
+         generated code as 'xxx'. For non-typedef'd structs, the
+         classHand mapping will be
+
+         struct __xxx -> (swig-insert-id "__xxx")
+       */
+      // Swig_print_node(n);
+      String *unnamed = Getattr(n, "unnamed");
+      if (kind_of_type && (!Strcmp(kind_of_type, "struct")
+			   || !Strcmp(kind_of_type, "union")) && cDeclName && !unnamed) {
+	k = NewStringf("%s %s", kind_of_type, cDeclName);
+      } else {
+	if (!Strcmp(nodeType(n), "enum") && unnamed) {
+	  name = NewStringf("%s%d", anon_type_name, anon_type_count++);
+	  k = NewStringf("enum %s", name);
+	  Setattr(n, "allegrocl:name", name);
+
+	} else {
+	  k = k ? k : Getattr(n, "name");
+	}
+      }
+    }
+    // Swig_print_node(n);
+  }
+
+  if (SwigType_istemplate(name)) {
+    String *temp = strip_namespaces(SwigType_templateprefix(name));
+    name = NewStringf("%s%s%s", temp, SwigType_templateargs(name), SwigType_templatesuffix(name));
+  }
+
+  val = lookup_defined_foreign_type(k);
+
+  int is_fwd_ref = 0;
+  if (val)
+    is_fwd_ref = !Strcmp(val, "forward-reference");
+
+  if (!val || overwrite || is_fwd_ref) {
+#ifdef ALLEGROCL_CLASS_DEBUG
+    Printf(stderr, "Adding defined type '%s' = '%s' '%s' (overwrite=%d, in-class=%d)\n", k, ns, name, overwrite, in_class);
+#endif
+    String *mangled_name_gen = NewStringf("#.(swig-insert-id \"%s\" %s :type :type)", name, ns_list);
+    String *mangled_lname_gen = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", name, ns_list);
+
+    Setattr(defined_foreign_types, Copy(k), Copy(mangled_name_gen));
+    Setattr(defined_foreign_ltypes, Copy(k), Copy(mangled_lname_gen));
+
+    if (CPlusPlus) {
+      bool cpp_struct = Strstr(k, "struct ") ? true : false;
+      bool cpp_union = Strstr(k, "union ") ? true : false;
+
+      String *cpp_type = 0;
+      if (cpp_struct) {
+	cpp_type = Copy(k);
+	Replaceall(cpp_type, "struct ", "");
+      } else if (cpp_union) {
+	cpp_type = Copy(k);
+	Replaceall(cpp_type, "union ", "");
+      }
+
+      if (cpp_struct || cpp_union) {
+#ifdef ALLEGROCL_CLASS_DEBUG
+	Printf(stderr, " Also adding defined type '%s' = '%s' '%s' (overwrite=%d)\n", cpp_type, ns, name, overwrite);
+#endif
+	Setattr(defined_foreign_types, Copy(cpp_type), Copy(mangled_name_gen));
+	Setattr(defined_foreign_ltypes, Copy(cpp_type), Copy(mangled_lname_gen));
+      }
+    }
+#ifdef ALLEGROCL_CLASS_DEBUG
+    Printf(stderr, "looking to add %s/%s(%x) to linked_type_list...\n", k, name, n);
+#endif
+    if (is_fwd_ref) {
+      // Printf(stderr,"*** 1\n");
+      add_linked_type(n);
+    } else {
+      // Printf(stderr,"*** 1-a\n");
+      if (SwigType_istemplate(k)) {
+	SwigType *resolved = SwigType_typedef_resolve_all(k);
+	// Printf(stderr,"*** 1-b\n");
+	Node *match = find_linked_type_by_name(resolved);
+	Node *new_node = 0;
+	// Printf(stderr, "*** temp-1\n");
+	if (n) {
+	  new_node = n;
+	} else {
+#ifdef ALLEGROCL_CLASS_DEBUG
+	  Printf(stderr, "Creating a new templateInst:\n");
+	  Printf(stderr, "       name = %s\n", resolved);
+	  Printf(stderr, "   sym:name = %s\n", name);
+	  Printf(stderr, "  real-name = %s\n", k);
+	  Printf(stderr, "       type = %s\n", resolved);
+	  Printf(stderr, "         ns = %s\n\n", ns);
+#endif
+	  new_node = NewHash();
+	  Setattr(new_node, "nodeType", "templateInst");
+	  Setattr(new_node, "name", Copy(resolved));
+	  Setattr(new_node, "sym:name", Copy(name));
+	  Setattr(new_node, "real-name", Copy(k));
+	  Setattr(new_node, "type", Copy(resolved));
+	  Setattr(new_node, "allegrocl:namespace", ns);
+	  Setattr(new_node, "allegrocl:package", ns);
+	}
+
+	if (!match) {
+	  if (!Strcmp(nodeType(new_node), "templateInst") && in_class) {
+	    /* this is an implicit template instantiation found while
+	       walking a class. need to insert this into the
+	       linked_type list before the current class definition */
+#ifdef ALLEGROCL_CLASS_DEBUG
+	    Printf(stderr, "trying to insert a templateInst before a class\n");
+#endif
+	    insert_linked_type_at(in_class, new_node);
+#ifdef ALLEGROCL_CLASS_DEBUG
+	    Printf(stderr, "DID IT!\n");
+#endif
+	  } else {
+	    // Printf(stderr,"*** 3\n");
+	    add_linked_type(new_node);
+	  }
+	  Setattr(new_node, "allegrocl:synonym:is-primary", "1");
+	} else {
+	  // a synonym type was found (held in variable 'match')
+	  // Printf(stderr, "setting primary synonym of %x to %x\n", new_node, match);
+	  if (new_node == match)
+	    Printf(stderr, "Hey-4 * - '%s' is a synonym of iteself!\n", Getattr(new_node, "name"));
+	  Setattr(new_node, "allegrocl:synonym-of", match);
+	  // Printf(stderr,"*** 4\n");
+	  add_linked_type(new_node);
+	}
+      } else {
+	Node *match;
+
+	if (!Strcmp(nodeType(n), "cdecl") && !Strcmp(Getattr(n, "storage"), "typedef")) {
+	  SwigType *type = SwigType_strip_qualifiers(Getattr(n, "type"));
+#ifdef ALLEGROCL_CLASS_DEBUG
+	  Printf(stderr, "Examining typedef '%s' for class references.\n", type);
+#endif
+	  if (SwigType_isclass(type)) {
+#ifdef ALLEGROCL_CLASS_DEBUG
+	    Printf(stderr, "Found typedef of a class '%s'\n", type);
+#endif
+	    /* 
+	       For the following parsed expression:
+
+	       typedef struct __xxx { ... } xxx;
+
+	       if n is of kind "class" (defining the class 'struct __xxx'
+	       then we add n to the linked type list.
+
+	       if n is "cdecl" node of storage "typedef" (to note
+	       that xxx is equivalent to 'struct __xxx' then we don't
+	       want to add this node to the linked type list.
+	     */
+	    String *defined_type = lookup_defined_foreign_type(type);
+	    String *defined_key_type = lookup_defined_foreign_type(k);
+
+	    if ((Strstr(type, "struct ") || Strstr(type, "union "))
+		&& defined_type && !Strcmp(defined_type, defined_key_type)) {
+	      // mark as a synonym but don't add to linked_type list
+	      // Printf(stderr,"*** 4.8\n");
+	      Setattr(n, "allegrocl:synonym", "1");
+	    } else {
+	      SwigType *lookup_type = SwigType_istemplate(type) ? SwigType_typedef_resolve_all(type) : Copy(type);
+	      match = find_linked_type_by_name(lookup_type);
+	      if (match) {
+		Setattr(n, "allegrocl:synonym", "1");
+		Setattr(n, "allegrocl:synonym-of", match);
+		Setattr(n, "real-name", Copy(lookup_type));
+
+		// Printf(stderr, "*** pre-5: found match of '%s'(%x)\n", Getattr(match,"name"),match);
+		// if(n == match) Printf(stderr, "Hey-5 *** setting synonym of %x to %x\n", n, match);
+		// Printf(stderr,"*** 5\n");
+		add_linked_type(n);
+	      } else {
+#ifdef ALLEGROCL_CLASS_DEBUG
+		Printf(stderr, "Creating classfoward node for struct stub in typedef.\n");
+#endif
+		Node *new_node = NewHash();
+		String *symname = Copy(type);
+		Replaceall(symname, "struct ", "");
+		Setattr(new_node, "nodeType", "classforward");
+		Setattr(new_node, "name", Copy(type));
+		Setattr(new_node, "sym:name", symname);
+		Setattr(new_node, "allegrocl:namespace", ns);
+		Setattr(new_node, "allegrocl:package", ns);
+
+		String *mangled_new_name = NewStringf("#.(swig-insert-id \"%s\" %s)", symname, ns_list);
+		String *mangled_new_lname = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)", symname, ns_list);
+		Setattr(defined_foreign_types, Copy(symname), Copy(mangled_new_name));
+		Setattr(defined_foreign_ltypes, Copy(symname), Copy(mangled_new_lname));
+
+		// Printf(stderr,"Weird! Can't find the type!\n");
+		add_forward_referenced_type(new_node);
+		add_linked_type(new_node);
+
+		Setattr(n, "allegrocl:synonym", "1");
+		Setattr(n, "allegrocl:synonym-of", new_node);
+
+		add_linked_type(n);
+	      }
+	      Delete(lookup_type);
+	    }
+	  } else {
+	    // check if it's a pointer or reference to a class.
+	    // Printf(stderr,"Checking if '%s' is a p. or r. to a class\n", type);
+	    String *class_ref = class_from_class_or_class_ref(type);
+	    if (class_ref) {
+	      match = find_linked_type_by_name(class_ref);
+	      Setattr(n, "allegrocl:synonym", "1");
+	      Setattr(n, "allegrocl:synonym-of", match);
+	      add_linked_type(n);
+	    }
+	  }
+	  Delete(type);
+	  // synonym types have already been added.
+	  // Printf(stderr,"*** 10\n");
+	  if (!Getattr(n, "allegrocl:synonym"))
+	    add_linked_type(n);
+	} else if (Getattr(n, "template")) {
+	  // Printf(stderr, "this is a class template node(%s)\n", nodeType(n));
+	  String *resolved = SwigType_typedef_resolve_all(Getattr(n, "name"));
+
+#ifdef ALLEGROCL_CLASS_DEBUG
+	  Printf(stderr, "   looking up %s for linked type match with %s...\n", Getattr(n, "sym:name"), resolved);
+#endif
+	  match = find_linked_type_by_name(resolved);
+	  if (!match) {
+#ifdef ALLEGROCL_CLASS_DEBUG
+	    Printf(stderr, "found no implicit instantiation of %%template node %s(%x)\n", Getattr(n, "name"), n);
+#endif
+	    add_linked_type(n);
+	  } else {
+	    Node *primary = get_primary_synonym_of(match);
+
+	    Setattr(n, "allegrocl:synonym:is-primary", "1");
+	    Delattr(primary, "allegrocl:synonym:is-primary");
+	    if (n == match)
+	      Printf(stderr, "Hey-7 * setting synonym of %x to %x\n (match = %x)", primary, n, match);
+	    Setattr(primary, "allegrocl:synonym-of", n);
+	    // Printf(stderr,"*** 7\n");
+	    add_linked_type(n);
+	  }
+	} else {
+#ifdef ALLEGROCL_CLASS_DEBUG
+	  Printf(stderr, "linking type '%s'(%x)\n", k, n);
+#endif
+	  // Printf(stderr,"*** 8\n");
+	  add_linked_type(n);
+	}
+      }
+    }
+    Delete(mangled_name_gen);
+    Delete(mangled_lname_gen);
+  } else {
+    Swig_warning(WARN_TYPE_REDEFINED, Getfile(n), Getline(n), "Attempting to store a foreign type that exists: %s (%s)\n", k, val);
+  }
+
+  Delete(ns_list);
+
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "OUT A-D-F-T\n");
+#endif
+}
+
+void note_implicit_template_instantiation(SwigType *t) {
+  // the namespace of the implicit instantiation is not necessarily
+  // current_namespace. Attempt to cull this from the type.
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "culling namespace of '%s' from '%s'\n", t, SwigType_templateprefix(t));
+#endif
+  String *implicit_ns = namespace_of(SwigType_templateprefix(t));
+  add_defined_foreign_type(0, 0, t, t, implicit_ns ? implicit_ns : current_namespace);
+}
+
+String *get_ffi_type(SwigType *ty, const String_or_char *name) {
+  /* lookup defined foreign type.
+     if it exists, it will return a form suitable for placing
+     into lisp code to generate the def-foreign-type name */
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "inside g_f_t: looking up '%s' '%s'\n", ty, name);
+#endif
+
+  String *found_type = lookup_defined_foreign_type(ty);
+
+  if (found_type) {
+#ifdef ALLEGROCL_TYPE_DEBUG
+    Printf(stderr, "found_type '%s'\n", found_type);
+#endif
+    return (Strcmp(found_type, "forward-reference") ? Copy(found_type) : NewString(":void"));
+  } else {
+    Hash *typemap = Swig_typemap_search("ffitype", ty, name, 0);
+
+    if (typemap) {
+      String *typespec = Getattr(typemap, "code");
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+      Printf(stderr, "g-f-t: found ffitype typemap '%s'\n%s\n", typespec, typemap);
+#endif
+      return NewString(typespec);
+    }
+
+    if (SwigType_istemplate(ty)) {
+      note_implicit_template_instantiation(ty);
+      return Copy(lookup_defined_foreign_type(ty));
+    }
+  }
+  return 0;
+}
+
+String *lookup_defined_foreign_ltype(String *l) {
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "Looking up defined ltype '%s'.\n  Found: '%s'\n", l, Getattr(defined_foreign_ltypes, l));
+#endif
+  return Getattr(defined_foreign_ltypes, l);
+}
+
+/* walk type and return string containing lisp version.
+   recursive. */
+String *internal_compose_foreign_type(SwigType *ty) {
+
+  SwigType *tok;
+  String *ffiType = NewString("");
+
+  // for a function type, need to walk the parm list.
+  while (Len(ty) != 0) {
+    tok = SwigType_pop(ty);
+
+    if (SwigType_isfunction(tok)) {
+      // Generate Function wrapper
+      Printf(ffiType, "(:function ");
+      // walk parm list
+      List *pl = SwigType_parmlist(tok);
+
+      Printf(ffiType, "(");	// start parm list
+      for (Iterator i = First(pl); i.item; i = Next(i)) {
+	SwigType *f_arg = SwigType_strip_qualifiers(i.item);
+	Printf(ffiType, "%s ", internal_compose_foreign_type(f_arg));
+	Delete(f_arg);
+      }
+      Printf(ffiType, ")");	// end parm list.
+
+      // do function return type.
+      Printf(ffiType, " %s)", internal_compose_foreign_type(ty));
+      break;
+    } else if (SwigType_ispointer(tok) || SwigType_isreference(tok)) {
+      Printf(ffiType, "(* %s)", internal_compose_foreign_type(ty));
+    } else if (SwigType_isarray(tok)) {
+      Printf(ffiType, "(:array %s", internal_compose_foreign_type(ty));
+      String *atype = NewString("int");
+      String *dim = convert_literal(SwigType_array_getdim(tok, 0), atype);
+      Delete(atype);
+      if (is_integer(dim)) {
+	Printf(ffiType, " %s)", dim);
+      } else {
+	Printf(ffiType, " #| %s |#)", SwigType_array_getdim(tok, 0));
+      }
+    } else if (SwigType_ismemberpointer(tok)) {
+      // temp
+      Printf(ffiType, "(* %s)", internal_compose_foreign_type(ty));
+    } else {
+      String *res = get_ffi_type(tok, "");
+      if (res) {
+	Printf(ffiType, "%s", res);
+      } else {
+	SwigType *resolved_type = SwigType_typedef_resolve(tok);
+	if (resolved_type) {
+	  res = get_ffi_type(resolved_type, "");
+	  if (res) {
+	  } else {
+	    res = internal_compose_foreign_type(resolved_type);
+	  }
+	  if (res)
+	    Printf(ffiType, "%s", res);
+	}
+//         while(resolved_type) {
+//        // the resolved_type may expand into something like p.NS1::NS2::SomeType
+//        // for which get_ffi_type will not find any match (due to the p.).
+//        // Printf(stderr, "\n  in resolved type loop on '%s'\n", resolved_type);
+//           res = get_ffi_type(resolved_type, "");
+//           if (res) {
+//             Printf(ffiType, "%s", res);
+//             break;
+//           } else {
+//          resolved_type = SwigType_typedef_resolve(resolved_type);
+//           }
+//       }
+	if (!res) {
+	  if (Strstr(tok, "struct ")) {
+	    Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(tok), Getline(tok), "Unable to find definition of '%s', assuming forward reference.\n", tok);
+	  } else {
+	    Printf(stderr, "Unable to compose foreign type of: '%s'\n", tok);
+	  }
+	  Printf(ffiType, "(* :void)");
+	}
+      }
+    }
+  }
+  return ffiType;
+}
+
+String *compose_foreign_type(SwigType *ty, String *id = 0) {
+
+  Hash *lookup_res = Swig_typemap_search("ffitype", ty, id, 0);
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "compose_foreign_type: ENTER (%s)...\n ", ty);
+  String *id_ref = SwigType_str(ty, id);
+  Printf(stderr, "looking up typemap for %s, found '%s'(%x)\n",
+	 id_ref, lookup_res ? Getattr(lookup_res, "code") : 0, lookup_res);
+#endif
+  /* should we allow named lookups in the typemap here? YES! */
+  /* unnamed lookups should be found in get_ffi_type, called
+     by internal_compose_foreign_type(), below. */
+  if(id && lookup_res) {
+#ifdef ALLEGROCL_TYPE_DEBUG
+    Printf(stderr, "compose_foreign_type: EXIT-1 (%s)\n ", Getattr(lookup_res, "code"));
+#endif
+    return NewString(Getattr(lookup_res, "code"));
+  }
+
+  SwigType *temp = SwigType_strip_qualifiers(ty);
+  String *res = internal_compose_foreign_type(temp);
+  Delete(temp);
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "compose_foreign_type: EXIT (%s)\n ", res);
+#endif
+
+  return res;
+}
+
+void update_package_if_needed(Node *n, File *f = f_clwrap) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "update_package: ENTER... \n");
+  Printf(stderr, "  current_package = '%s'\n", current_package);
+  Printf(stderr, "     node_package = '%s'\n", Getattr(n, "allegrocl:package"));
+  Printf(stderr, "   node(%x) = '%s'\n", n, Getattr(n, "name"));
+#endif
+  String *node_package = Getattr(n, "allegrocl:package");
+  if (Strcmp(current_package, node_package)) {
+    String *lispy_package = listify_namespace(node_package);
+
+    Delete(current_package);
+    current_package = Copy(node_package);
+    Printf(f, "\n(swig-in-package %s)\n", lispy_package);
+    Delete(lispy_package);
+  }
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "update_package: EXIT.\n");
+#endif
+}
+
+static String *mangle_name(Node *n, char const *prefix = "ACL", String *ns = current_namespace) {
+  String *suffix = Getattr(n, "sym:overname");
+  String *pre_mangled_name = NewStringf("%s_%s__%s%s", prefix, ns, Getattr(n, "sym:name"), suffix);
+  String *mangled_name = Swig_name_mangle(pre_mangled_name);
+  Delete(pre_mangled_name);
+  return mangled_name;
+}
+
+/* utilities */
+
+/* remove a pointer from ffitype. non-destructive. 
+   (* :char) ==> :char
+   (* (:array :int 30)) ==> (:array :int 30) */
+String *dereference_ffitype(String *ffitype) {
+   char *start;
+   char *temp = Char(ffitype);
+   String *reduced_type = 0;
+
+   if(temp && temp[0] == '(' && temp[1] == '*') {
+      temp += 2;
+
+      // walk past start of pointer references
+      while(*temp == ' ') temp++;
+      start = temp;
+      // temp = Char(reduced_type);
+      reduced_type = NewString(start);
+      temp = Char(reduced_type);
+      // walk to end of string. remove closing paren
+      while(*temp != '\0') temp++;
+      *(--temp) = '\0';
+   }
+
+   return reduced_type ? reduced_type : Copy(ffitype);
+}
+
+/* returns new string w/ parens stripped */
+String *strip_parens(String *string) {
+  string = Copy(string);
+  Replaceall(string, "(", "");
+  Replaceall(string, ")", "");
+  return string;
+}
+
+int ALLEGROCL::validIdentifier(String *s) {
+  char *c = Char(s);
+
+  bool got_dot = false;
+  bool only_dots = true;
+
+  /* Check that s is a valid common lisp symbol. There's a lot of leeway here.
+     A common lisp symbol is essentially any token that's not a number and
+     does not consist of only dots. 
+
+     We are expressly not allowing spaces in identifiers here, but spaces
+     could be added via the identifier converter. */
+  while (*c) {
+    if (*c == '.') {
+      got_dot = true;
+    } else {
+      only_dots = false;
+    }
+    if (!isgraph(*c))
+      return 0;
+    c++;
+  }
+
+  return (got_dot && only_dots) ? 0 : 1;
+}
+
+String *infix_to_prefix(String *val, char split_op, const String *op, String *type) {
+  List *ored = Split(val, split_op, -1);
+
+  // some float hackery
+  if (((split_op == '+') || (split_op == '-')) && Len(ored) == 2 &&
+      (SwigType_type(type) == T_FLOAT || SwigType_type(type) == T_DOUBLE || SwigType_type(type) == T_LONGDOUBLE)) {
+    // check that we're not splitting a float
+    String *possible_result = convert_literal(val, type, false);
+    if (possible_result)
+      return possible_result;
+
+  }
+  // try parsing the split results. if any part fails, kick out.
+  bool part_failed = false;
+  if (Len(ored) > 1) {
+    String *result = NewStringf("(%s", op);
+    for (Iterator i = First(ored); i.item; i = Next(i)) {
+      String *converted = convert_literal(i.item, type);
+      if (converted) {
+	Printf(result, " %s", converted);
+	Delete(converted);
+      } else {
+	part_failed = true;
+	break;
+      }
+    }
+    Printf(result, ")");
+    Delete(ored);
+    return part_failed ? 0 : result;
+  } else {
+    Delete(ored);
+  }
+  return 0;
+}
+
+/* To be called by code generating the lisp interface
+   Will return a containing the literal based on type.
+   Will return null if there are problems.
+
+   try_to_split defaults to true (see stub above).
+ */
+String *convert_literal(String *literal, String *type, bool try_to_split) {
+  String *num_param = Copy(literal);
+  String *trimmed = trim(num_param);
+  String *num = strip_parens(trimmed), *res = 0;
+  char *s = Char(num);
+
+  String *ns = listify_namespace(current_namespace);
+
+  // very basic parsing of infix expressions.
+  if (try_to_split) {
+    if ((res = infix_to_prefix(num, '|', "logior", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '&', "logand", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '^', "logxor", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '*', "*", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '/', "/", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '+', "+", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '-', "-", type)))
+      return res;
+    //  if( (res = infix_to_prefix(num, '<<', "ash", type)) ) return res;  
+  }
+
+  if (SwigType_type(type) == T_FLOAT || SwigType_type(type) == T_DOUBLE || SwigType_type(type) == T_LONGDOUBLE) {
+    // Use CL syntax for float literals 
+    String *oldnum = Copy(num);
+
+    // careful. may be a float identifier or float constant.
+    char *num_start = Char(num);
+    char *num_end = num_start + strlen(num_start) - 1;
+
+    bool is_literal = isdigit(*num_start) || (*num_start == '.');
+
+    String *lisp_exp = 0;
+    if (is_literal) {
+      if (*num_end == 'f' || *num_end == 'F') {
+	lisp_exp = NewString("f");
+      } else {
+	lisp_exp = NewString("d");
+      }
+
+      if (*num_end == 'l' || *num_end == 'L' || *num_end == 'f' || *num_end == 'F') {
+	*num_end = '\0';
+	num_end--;
+      }
+
+      int exponents = Replaceall(num, "e", lisp_exp) + Replaceall(num, "E", lisp_exp);
+
+      if (!exponents)
+	Printf(num, "%s0", lisp_exp);
+
+      if (exponents > 1 || (exponents + Replaceall(num, ".", ".") == 0)) {
+	// Printf(stderr, "Can't parse '%s' as type '%s'.\n", oldnum, type);
+	Delete(num);
+	num = 0;
+      }
+    } else {
+      String *id = NewStringf("#.(swig-insert-id \"%s\" %s :type :constant)",
+			      num, ns);
+      Delete(num);
+      num = id;
+    }
+
+    Delete(oldnum);
+    Delete(trimmed);
+    Delete(ns);
+    return num;
+  } else if (SwigType_type(type) == T_CHAR) {
+    /* Use CL syntax for character literals */
+    Delete(num);
+    Delete(trimmed);
+    return NewStringf("#\\%s", num_param);
+  } else if (SwigType_type(type) == T_STRING) {
+    /* Use CL syntax for string literals */
+    Delete(num);
+    Delete(trimmed);
+    return NewStringf("\"%s\"", num_param);
+  } else if (Len(num) >= 1 && (isdigit(s[0]) || s[0] == '+' || s[0] == '-')) {
+    /* use CL syntax for numbers */
+    String *oldnum = Copy(num);
+    int usuffixes = Replaceall(num, "u", "") + Replaceall(num, "U", "");
+    int lsuffixes = Replaceall(num, "l", "") + Replaceall(num, "L", "");
+    if (usuffixes > 1 || lsuffixes > 1) {
+      Printf(stderr, "Weird!! number %s looks invalid.\n", oldnum);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    s = Char(num);
+    if (s[0] == '0' && Len(num) >= 2) {
+      /*octal or hex */
+      res = NewStringf("#%c%s", tolower(s[1]) == 'x' ? 'x' : 'o', s + 2);
+      Delete(num);
+    } else {
+      res = num;
+    }
+    Delete(oldnum);
+    Delete(trimmed);
+    return res;
+  } else if (allegrocl->validIdentifier(num)) {
+    /* convert C/C++ identifiers to CL symbols */
+    res = NewStringf("#.(swig-insert-id \"%s\" %s :type :constant)", num, ns);
+    Delete(num);
+    Delete(trimmed);
+    Delete(ns);
+    return res;
+  } else {
+    Delete(trimmed);
+    return num;
+  }
+}
+
+
+void emit_stub_class(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_stub_class: ENTER... '%s'(%x)\n", Getattr(n, "sym:name"), n);
+#endif
+
+
+  String *name = Getattr(n, "sym:name");
+
+  if (Getattr(n, "allegrocl:synonym:already-been-stubbed"))
+    return;
+
+  if (SwigType_istemplate(name)) {
+    String *temp = strip_namespaces(SwigType_templateprefix(name));
+    name = NewStringf("%s%s%s", temp, SwigType_templateargs(name), SwigType_templatesuffix(name));
+
+    Delete(temp);
+  } else {
+    name = strip_namespaces(name);
+  }
+
+  // Printf(f_clhead, ";; from emit-stub-class\n");
+  update_package_if_needed(n, f_clhead);
+  Printf(f_clhead, ";; class template stub.\n");
+  Printf(f_clhead, "(swig-def-foreign-stub \"%s\")\n", name);
+
+  Setattr(n, "allegrocl:synonym:already-been-stubbed", "1");
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_stub_class: EXIT\n");
+#endif
+}
+
+void emit_synonym(Node *synonym) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_synonym: ENTER... \n");
+#endif
+
+  // Printf(stderr,"in emit_synonym for %s(%x)\n", Getattr(synonym,"name"),synonym);
+  int is_tempInst = !Strcmp(nodeType(synonym), "templateInst");
+  String *synonym_type;
+
+  Node *of = get_primary_synonym_of(synonym);
+
+  if (is_tempInst) {
+    // Printf(stderr, "*** using real-name '%s'\n", Getattr(synonym,"real-name"));
+    synonym_type = Getattr(synonym, "real-name");
+  } else {
+    // Printf(stderr, "*** using name '%s'\n", Getattr(synonym,"name"));
+    synonym_type = Getattr(synonym, "name");
+  }
+
+  String *synonym_ns = listify_namespace(Getattr(synonym, "allegrocl:namespace"));
+  String *syn_ltype, *syn_type, *of_ltype;
+  // String *of_cdeclname = Getattr(of,"allegrocl:classDeclarationName");
+  String *of_ns = Getattr(of, "allegrocl:namespace");
+  String *of_ns_list = listify_namespace(of_ns);
+  // String *of_name = of_cdeclname ? NewStringf("struct %s", Getattr(of,"name")) : NewStringf("%s::%s", of_ns, Getattr(of,"sym:name"));
+  // String *of_name = NewStringf("%s::%s", of_ns, Getattr(of,"sym:name"));
+  String *of_name = namespaced_name(of, of_ns);
+
+  if (CPlusPlus && !Strcmp(nodeType(synonym), "cdecl")) {
+	  syn_ltype = NewStringf("#.(swig-insert-id \"%s\" %s :type :class)",
+				 strip_namespaces(Getattr(synonym, "real-name")), synonym_ns);
+	  syn_type = NewStringf("#.(swig-insert-id \"%s\" %s :type :type)",
+				strip_namespaces(Getattr(synonym, "real-name")), synonym_ns);
+  } else {
+	  syn_ltype = lookup_defined_foreign_ltype(synonym_type);
+	  syn_type = lookup_defined_foreign_type(synonym_type);
+  }
+
+  of_ltype = lookup_defined_foreign_ltype(of_name);
+
+  // Printf(f_clhead,";; from emit-synonym\n");
+  Printf(f_clhead, "(swig-def-synonym-type %s\n   %s\n   %s)\n", syn_ltype, of_ltype, syn_type);
+
+  Delete(synonym_ns);
+  Delete(of_ns_list);
+  Delete(of_name);
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_synonym: EXIT\n");
+#endif
+}
+
+void emit_full_class(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_full_class: ENTER... \n");
+#endif
+
+  String *name = Getattr(n, "sym:name");
+  String *kind = Getattr(n, "kind");
+
+  // Printf(stderr,"in emit_full_class: '%s'(%x).", Getattr(n,"name"),n);
+  if (Getattr(n, "allegrocl:synonym-of")) {
+    // Printf(stderr,"but it's a synonym of something.\n");
+    update_package_if_needed(n, f_clhead);
+    emit_synonym(n);
+    return;
+  }
+  // collect superclasses
+  String *bases = Getattr(n, "bases");
+  String *supers = NewString("(");
+  if (bases) {
+    int first = 1;
+    for (Iterator i = First(bases); i.item; i = Next(i)) {
+      if (!first)
+	Printf(supers, " ");
+      String *s = lookup_defined_foreign_ltype(Getattr(i.item, "name"));
+      // String *name = Getattr(i.item,"name");
+      if (s) {
+	Printf(supers, "%s", s);
+      } else {
+#ifdef ALLEGROCL_TYPE_DEBUG
+	Printf(stderr, "emit_templ_inst: did not find ltype for base class %s (%s)", Getattr(i.item, "name"), Getattr(n, "allegrocl:namespace"));
+#endif
+      }
+    }
+  } else {
+    Printf(supers, "ff:foreign-pointer");
+  }
+
+  Printf(supers, ")");
+
+  // Walk children to generate type definition.
+  String *slotdefs = NewString("   ");
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "  walking children...\n");
+#endif
+
+  Node *c;
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    String *storage_type = Getattr(c, "storage");
+    if ((!Strcmp(nodeType(c), "cdecl") && (!storage_type || Strcmp(storage_type, "typedef")))) {
+      String *access = Getattr(c, "access");
+
+      // hack. why would decl have a value of "variableHandler" and now "0"?
+      String *childDecl = Getattr(c, "decl");
+      // Printf(stderr,"childDecl = '%s' (%s)\n", childDecl, Getattr(c,"view"));
+      if (!Strcmp(childDecl, "0"))
+	childDecl = NewString("");
+
+      SwigType *childType;
+      String *cname;
+
+      // don't include types for private slots (yet). spr33959.
+      if(access && Strcmp(access,"public")) {
+	      childType = NewStringf("int");
+	      cname = NewString("nil");
+      } else {
+	      childType = NewStringf("%s%s", childDecl, Getattr(c, "type"));
+	      cname = Copy(Getattr(c, "name"));
+      }
+
+      if (!SwigType_isfunction(childType)) {
+	// Printf(slotdefs, ";;; member functions don't appear as slots.\n ");
+	// Printf(slotdefs, ";; ");
+	String *ns = listify_namespace(Getattr(n, "allegrocl:package"));
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+	Printf(stderr, "slot name = '%s' ns = '%s' class-of '%s' and type = '%s'\n", cname, ns, name, childType);
+#endif
+	Printf(slotdefs, "(#.(swig-insert-id \"%s\" %s :type :slot :class \"%s\") %s)", cname, ns, name, compose_foreign_type(childType));
+	Delete(ns);
+	if (access && Strcmp(access, "public"))
+	  Printf(slotdefs, " ;; %s member", access);
+
+	Printf(slotdefs, "\n   ");
+      }
+      Delete(childType);
+      Delete(cname);
+    }
+  }
+
+  String *ns_list = listify_namespace(Getattr(n, "allegrocl:namespace"));
+  update_package_if_needed(n, f_clhead);
+  Printf(f_clhead, "(swig-def-foreign-class \"%s\"\n %s\n  (:%s\n%s))\n\n", name, supers, kind, slotdefs);
+
+  Delete(supers);
+  Delete(ns_list);
+
+  Setattr(n, "allegrocl:synonym:already-been-stubbed", "1");
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_full_class: EXIT\n");
+#endif
+
+}
+
+void emit_class(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_class: ENTER... '%s'(%x)\n", Getattr(n, "sym:name"), n);
+#endif
+
+  int is_tempInst = !Strcmp(nodeType(n), "templateInst");
+
+  String *ns_list = listify_namespace(Getattr(n, "allegrocl:namespace"));
+  String *name = Getattr(n, is_tempInst ? "real-name" : "name");
+
+  if (SwigType_istemplate(name)) {
+    String *temp = strip_namespaces(SwigType_templateprefix(name));
+    name = NewStringf("%s%s%s", temp, SwigType_templateargs(name), SwigType_templatesuffix(name));
+
+    Delete(temp);
+  } else {
+    name = strip_namespaces(name);
+  }
+
+  if (Getattr(n, "allegrocl:synonym:is-primary")) {
+    // Printf(stderr,"  is primary... ");
+    if (is_tempInst) {
+      emit_stub_class(n);
+    } else {
+      emit_full_class(n);
+    }
+  } else {
+    // Node *primary = Getattr(n,"allegrocl:synonym-of");
+    Node *primary = get_primary_synonym_of(n);
+    if (primary && (primary != n)) {
+      // Printf(stderr,"  emitting synonym... ");
+      emit_stub_class(primary);
+      update_package_if_needed(n, f_clhead);
+      emit_synonym(n);
+    } else {
+      emit_full_class(n);
+    }
+  }
+  // Printf(stderr,"DONE\n");
+  Delete(name);
+  Delete(ns_list);
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_class: EXIT\n");
+#endif
+}
+
+void emit_typedef(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_typedef: ENTER... \n");
+#endif
+
+  String *name;
+  String *sym_name = Getattr(n, "sym:name");
+  String *type = NewStringf("%s%s", Getattr(n, "decl"), Getattr(n, "type"));
+  String *lisp_type = compose_foreign_type(type);
+  Delete(type);
+  Node *in_class = Getattr(n, "allegrocl:typedef:in-class");
+
+  // Printf(stderr,"in emit_typedef: '%s'(%x).",Getattr(n,"name"),n);
+  if (Getattr(n, "allegrocl:synonym-of")) {
+    // Printf(stderr," but it's a synonym of something.\n");
+    emit_synonym(n);
+    return;
+  }
+
+  if (in_class) {
+    String *class_name = Getattr(in_class, "name");
+    if (SwigType_istemplate(class_name)) {
+      String *temp = strip_namespaces(SwigType_templateprefix(class_name));
+      class_name = NewStringf("%s%s%s", temp, SwigType_templateargs(class_name), SwigType_templatesuffix(class_name));
+      Delete(temp);
+    }
+
+    name = NewStringf("%s__%s", class_name, sym_name);
+    Setattr(n, "allegrocl:in-class", in_class);
+  } else {
+    name = sym_name ? Copy(sym_name) : Copy(Getattr(n, "name"));
+  }
+
+  // leave these in for now. might want to change these to def-foreign-class at some point.
+//  Printf(f_clhead, ";; %s\n", SwigType_typedef_resolve_all(lisp_type));
+  // Swig_print_node(n);
+  Printf(f_clhead, "(swig-def-foreign-type \"%s\"\n  %s)\n", name, lisp_type);
+
+  Delete(name);
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_typedef: EXIT\n");
+#endif
+}
+
+void emit_enum_type_no_wrap(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_enum_type_no_wrap: ENTER... \n");
+#endif
+
+  String *unnamed = Getattr(n, "unnamed");
+  String *name;
+  //  SwigType *enumtype;
+
+  name = unnamed ? Getattr(n, "allegrocl:name") : Getattr(n, "sym:name");
+  SwigType *tmp = NewStringf("enum %s", unnamed ? unnamed : name);
+
+  Hash *typemap = Swig_typemap_search("ffitype", tmp, 0, 0);
+  String *enumtype = Getattr(typemap, "code");
+  // enumtype = compose_foreign_type(tmp);
+  Delete(tmp);
+
+  if (name) {
+    String *ns = listify_namespace(current_namespace);
+
+    Printf(f_clhead, "(swig-def-foreign-type \"%s\" %s)\n", name, enumtype);
+    Delete(ns);
+
+    // walk children.
+    Node *c;
+    for (c = firstChild(n); c; c = nextSibling(c)) {
+      if (!Getattr(c, "error")) {
+	String *val = Getattr(c, "enumvalue");
+	if (!val)
+	  val = Getattr(c, "enumvalueex");
+	String *converted_val = convert_literal(val, Getattr(c, "type"));
+	String *valname = Getattr(c, "sym:name");
+
+	if (converted_val) {
+	  Printf(f_clhead, "(swig-defconstant \"%s\" %s)\n", valname, converted_val);
+	  Delete(converted_val);
+	} else {
+	  Swig_warning(WARN_LANG_DISCARD_CONST, Getfile(n), Getline(n), "Unable to parse enum value '%s'. Setting to NIL\n", val);
+	  Printf(f_clhead, "(swig-defconstant \"%s\" nil #| %s |#)\n", valname, val);
+	}
+      }
+    }
+  }
+  Printf(f_clhead, "\n");
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_enum_type_no_wrap: EXIT\n");
+#endif
+
+}
+
+void emit_enum_type(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_enum_type: ENTER... \n");
+#endif
+
+  if (!Generate_Wrapper) {
+    emit_enum_type_no_wrap(n);
+    return;
+  }
+
+  String *unnamed = Getattr(n, "unnamed");
+  String *name;
+  // SwigType *enumtype;
+
+  name = unnamed ? Getattr(n, "allegrocl:name") : Getattr(n, "sym:name");
+  SwigType *tmp = NewStringf("enum %s", unnamed ? unnamed : name);
+  // SwigType *tmp = NewStringf("enum ACL_SWIG_ENUM_NAME");
+
+  Hash *typemap = Swig_typemap_search("ffitype", tmp, 0, 0);
+  String *enumtype = Getattr(typemap, "code");
+
+  // enumtype = compose_foreign_type(tmp);
+  Delete(tmp);
+
+  if (name) {
+    String *ns = listify_namespace(current_namespace);
+
+    Printf(f_clhead, "(swig-def-foreign-type \"%s\" %s)\n", name, enumtype);
+    Delete(ns);
+
+    // walk children.
+    Node *c;
+    for(c = firstChild(n); c; c=nextSibling(c)) {
+      String *mangled_name = mangle_name(c, "ACL_ENUM", Getattr(c,"allegrocl:package"));
+      Printf(f_clhead, "(swig-defvar \"%s\" \"%s\" :type :constant :ftype :signed-long)\n", Getattr(c, "sym:name"), mangled_name);
+      Delete(mangled_name);
+    }
+  }
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_enum_type: EXIT\n");
+#endif
+
+}
+
+void emit_default_linked_type(Node *n) {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_default_linked_type: ENTER... \n");
+#endif
+
+  // catchall for non class types.
+  if (!Strcmp(nodeType(n), "classforward")) {
+    Printf(f_clhead, ";; forward referenced stub.\n");
+    Printf(f_clhead, "(swig-def-foreign-class \"%s\" (ff:foreign-pointer) (:class ))\n\n", Getattr(n, "sym:name"));
+  } else if (!Strcmp(nodeType(n), "enum")) {
+    emit_enum_type(n);
+  } else {
+    Printf(stderr, "Don't know how to emit node type '%s' named '%s'\n", nodeType(n), Getattr(n, "name"));
+  }
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_default_linked_type: EXIT\n");
+#endif
+
+}
+
+void dump_linked_types(File *f) {
+  Node *n = first_linked_type;
+  int i = 0;
+  while (n) {
+    Printf(f, "%d: (%x) node '%s' name '%s'\n", i++, n, nodeType(n), Getattr(n, "sym:name"));
+
+    Node *t = Getattr(n, "allegrocl:synonym-of");
+    if (t)
+      Printf(f, "     synonym-of %s(%x)\n", Getattr(t, "name"), t);
+    n = Getattr(n, "allegrocl:next_linked_type");
+  }
+}
+
+void emit_linked_types() {
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_linked_types: ENTER... ");
+#endif
+
+  Node *n = first_linked_type;
+
+  while (n) {
+    String *node_type = nodeType(n);
+
+    // Printf(stderr,"emitting node %s(%x) of type %s.", Getattr(n,"name"),n, nodeType(n));
+    if (!Strcmp(node_type, "class") || !Strcmp(node_type, "templateInst")) {
+      // may need to emit a stub, so it will update the package itself.
+      // Printf(stderr," Passing to emit_class.");
+      emit_class(n);
+    } else if (!Strcmp(nodeType(n), "cdecl")) {
+      // Printf(stderr," Passing to emit_typedef.");
+      update_package_if_needed(n, f_clhead);
+      emit_typedef(n);
+    } else {
+      // Printf(stderr," Passing to default_emitter.");
+      update_package_if_needed(n, f_clhead);
+      emit_default_linked_type(n);
+    }
+
+    n = Getattr(n, "allegrocl:next_linked_type");
+    // Printf(stderr,"returned.\n");
+  }
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_linked_types: EXIT\n");
+#endif
+}
+
+extern "C" Language *swig_allegrocl(void) {
+  return (allegrocl = new ALLEGROCL());
+}
+
+void ALLEGROCL::main(int argc, char *argv[]) {
+  int i;
+
+  SWIG_library_directory("allegrocl");
+  SWIG_config_file("allegrocl.swg");
+
+  for (i = 1; i < argc; i++) {
+    if (!strcmp(argv[i], "-identifier-converter")) {
+      char *conv = argv[i + 1];
+
+      if (!conv)
+	Swig_arg_error();
+
+      Swig_mark_arg(i);
+      Swig_mark_arg(i + 1);
+      i++;
+
+      /* check for built-ins */
+      if (!strcmp(conv, "lispify")) {
+	identifier_converter = "identifier-convert-lispify";
+      } else if (!strcmp(conv, "null")) {
+	identifier_converter = "identifier-convert-null";
+      } else {
+	/* Must be user defined */
+	char *idconv = new char[strlen(conv) + 1];
+	strcpy(idconv, conv);
+	identifier_converter = idconv;
+      }
+    } else if (!strcmp(argv[i], "-cwrap")) {
+      CWrap = true;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-nocwrap")) {
+      CWrap = false;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-isolate")) {
+      unique_swig_package = true;
+      Swig_mark_arg(i);
+    }
+
+    if (!strcmp(argv[i], "-help")) {
+      fprintf(stdout, "Allegro CL Options (available with -allegrocl)\n");
+      fprintf(stdout,
+	      "    -identifier-converter <type or funcname>\n"
+	      "\tSpecifies the type of conversion to do on C identifiers to convert\n"
+	      "\tthem to symbols.  There are two built-in converters:  'null' and\n"
+	      "\t 'lispify'.  The default is 'null'.  If you supply a name other\n"
+	      "\tthan one of the built-ins, then a function by that name will be\n"
+	      "\tcalled to convert identifiers to symbols.\n"
+	      "\n"
+	      "   -[no]cwrap\n"
+	      "\tTurn on or turn off generation of an intermediate C file when\n" "\tcreating a C interface. By default this is only done for C++ code.\n");
+
+    }
+
+  }
+
+  allow_overloading();
+}
+
+int ALLEGROCL::top(Node *n) {
+  module_name = Getattr(n, "name");
+  String *cxx_filename = Getattr(n, "outfile");
+  String *cl_filename = NewString("");
+
+  swig_package = unique_swig_package ? NewStringf("swig.%s", module_name) : NewString("swig");
+
+  Printf(cl_filename, "%s%s.cl", SWIG_output_directory(), Swig_file_basename(Getattr(n,"infile")));
+
+  f_cl = NewFile(cl_filename, "w");
+  if (!f_cl) {
+    Printf(stderr, "Unable to open %s for writing\n", cl_filename);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  Generate_Wrapper = CPlusPlus || CWrap;
+
+  if (Generate_Wrapper) {
+    f_cxx = NewFile(cxx_filename, "w");
+    if (!f_cxx) {
+      Close(f_cl);
+      Delete(f_cl);
+      Printf(stderr, "Unable to open %s for writing\n", cxx_filename);
+      SWIG_exit(EXIT_FAILURE);
+    }
+  } else
+    f_cxx = NewString("");
+
+  f_cxx_header = f_cxx;
+  f_cxx_wrapper = NewString("");
+
+  Swig_register_filebyname("header", f_cxx_header);
+  Swig_register_filebyname("wrapper", f_cxx_wrapper);
+  Swig_register_filebyname("runtime", f_cxx);
+  Swig_register_filebyname("lisp", f_clwrap);
+  Swig_register_filebyname("lisphead", f_cl);
+
+  Printf(f_cl, ";; This is an automatically generated file.  Make changes in\n"
+	 ";; the definition file, not here.\n\n"
+	 "(defpackage :%s\n"
+	 "  (:use :common-lisp :ff :excl)\n"
+	 "  (:export #:*swig-identifier-converter* #:*swig-module-name*\n"
+	 "           #:*void* #:*swig-export-list*))\n"
+	 "(in-package :%s)\n\n"
+	 "(eval-when (compile load eval)\n"
+	 "  (defparameter *swig-identifier-converter* '%s)\n"
+	 "  (defparameter *swig-module-name* :%s))\n\n", swig_package, swig_package, identifier_converter, module_name);
+  Printf(f_cl, "(defpackage :%s\n" "  (:use :common-lisp :%s :ff :excl))\n\n", module_name, swig_package);
+
+  Printf(f_clhead, "(in-package :%s)\n", module_name);
+
+  // Swig_print_tree(n);
+
+  Language::top(n);
+
+  //  SwigType_emit_type_table(f_cxx,f_cxx_wrapper);
+
+  // Swig_print_tree(n);
+#ifdef ALLEGROCL_TYPE_DEBUG
+  dump_linked_types(stderr);
+#endif
+  emit_linked_types();
+
+  Printf(f_clwrap, "\n(cl::in-package :%s)\n", swig_package);
+  Printf(f_clwrap, "\n(macrolet ((swig-do-export ()\n");
+  Printf(f_clwrap, "                 `(dolist (s ',*swig-export-list*)\n");
+  Printf(f_clwrap, "                    (apply #'export s))))\n");
+  Printf(f_clwrap, "   (swig-do-export))\n");
+  Printf(f_clwrap, "\n(setq *swig-export-list* nil)\n");
+
+  Printf(f_cl, "%s\n", f_clhead);
+  Printf(f_cl, "%s\n", f_clwrap);
+
+  Close(f_cl);
+  Delete(f_cl);			// Delete the handle, not the file
+  Delete(f_clhead);
+  Delete(f_clwrap);
+
+  Close(f_cxx);
+  Delete(f_cxx);
+  Delete(f_cxx_wrapper);
+
+  // Swig_print_tree(n);
+
+  return SWIG_OK;
+}
+
+/* very shamelessly 'borrowed' from overload.cxx, which
+   keeps the below Swig_overload_rank() code to itself.
+   We don't need a dispatch function in the C++ wrapper
+   code; we want it over on the lisp side. */
+
+#define MAX_OVERLOAD 256
+
+/* Overload "argc" and "argv" */
+// String *argv_template_string;
+// String *argc_template_string;
+
+struct Overloaded {
+  Node *n;			/* Node                               */
+  int argc;			/* Argument count                     */
+  ParmList *parms;		/* Parameters used for overload check */
+  int error;			/* Ambiguity error                    */
+};
+
+/* -----------------------------------------------------------------------------
+ * Swig_overload_rank()
+ *
+ * This function takes an overloaded declaration and creates a list that ranks
+ * all overloaded methods in an order that can be used to generate a dispatch 
+ * function.
+ * Slight difference in the way this function is used by scripting languages and
+ * statically typed languages. The script languages call this method via 
+ * Swig_overload_dispatch() - where wrappers for all overloaded methods are generated,
+ * however sometimes the code can never be executed. The non-scripting languages
+ * call this method via Swig_overload_check() for each overloaded method in order
+ * to determine whether or not the method should be wrapped. Note the slight
+ * difference when overloading methods that differ by const only. The
+ * scripting languages will ignore the const method, whereas the non-scripting
+ * languages ignore the first method parsed.
+ * ----------------------------------------------------------------------------- */
+
+static List *Swig_overload_rank(Node *n, bool script_lang_wrapping) {
+  Overloaded nodes[MAX_OVERLOAD];
+  int nnodes = 0;
+  Node *o = Getattr(n, "sym:overloaded");
+  Node *c;
+
+  if (!o)
+    return 0;
+
+  c = o;
+  while (c) {
+    if (Getattr(c, "error")) {
+      c = Getattr(c, "sym:nextSibling");
+      continue;
+    }
+    /*    if (SmartPointer && Getattr(c,"cplus:staticbase")) {
+       c = Getattr(c,"sym:nextSibling");
+       continue;
+       } */
+
+    /* Make a list of all the declarations (methods) that are overloaded with
+     * this one particular method name */
+    if (Getattr(c, "wrap:name")) {
+      nodes[nnodes].n = c;
+      nodes[nnodes].parms = Getattr(c, "wrap:parms");
+      nodes[nnodes].argc = emit_num_required(nodes[nnodes].parms);
+      nodes[nnodes].error = 0;
+      nnodes++;
+    }
+    c = Getattr(c, "sym:nextSibling");
+  }
+
+  /* Sort the declarations by required argument count */
+  {
+    int i, j;
+    for (i = 0; i < nnodes; i++) {
+      for (j = i + 1; j < nnodes; j++) {
+	if (nodes[i].argc > nodes[j].argc) {
+	  Overloaded t = nodes[i];
+	  nodes[i] = nodes[j];
+	  nodes[j] = t;
+	}
+      }
+    }
+  }
+
+  /* Sort the declarations by argument types */
+  {
+    int i, j;
+    for (i = 0; i < nnodes - 1; i++) {
+      if (nodes[i].argc == nodes[i + 1].argc) {
+	for (j = i + 1; (j < nnodes) && (nodes[j].argc == nodes[i].argc); j++) {
+	  Parm *p1 = nodes[i].parms;
+	  Parm *p2 = nodes[j].parms;
+	  int differ = 0;
+	  int num_checked = 0;
+	  while (p1 && p2 && (num_checked < nodes[i].argc)) {
+	    //    Printf(stdout,"p1 = '%s', p2 = '%s'\n", Getattr(p1,"type"), Getattr(p2,"type"));
+	    if (checkAttribute(p1, "tmap:in:numinputs", "0")) {
+	      p1 = Getattr(p1, "tmap:in:next");
+	      continue;
+	    }
+	    if (checkAttribute(p2, "tmap:in:numinputs", "0")) {
+	      p2 = Getattr(p2, "tmap:in:next");
+	      continue;
+	    }
+	    String *t1 = Getattr(p1, "tmap:typecheck:precedence");
+	    String *t2 = Getattr(p2, "tmap:typecheck:precedence");
+	    if ((!t1) && (!nodes[i].error)) {
+	      Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[i].n), Getline(nodes[i].n),
+			   "Overloaded %s(%s) not supported (no type checking rule for '%s').\n",
+			   Getattr(nodes[i].n, "name"), ParmList_str_defaultargs(Getattr(nodes[i].n, "parms")), SwigType_str(Getattr(p1, "type"), 0));
+	      nodes[i].error = 1;
+	    } else if ((!t2) && (!nodes[j].error)) {
+	      Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[j].n), Getline(nodes[j].n),
+			   "Overloaded %s(%s) not supported (no type checking rule for '%s').\n",
+			   Getattr(nodes[j].n, "name"), ParmList_str_defaultargs(Getattr(nodes[j].n, "parms")), SwigType_str(Getattr(p2, "type"), 0));
+	      nodes[j].error = 1;
+	    }
+	    if (t1 && t2) {
+	      int t1v, t2v;
+	      t1v = atoi(Char(t1));
+	      t2v = atoi(Char(t2));
+	      differ = t1v - t2v;
+	    } else if (!t1 && t2)
+	      differ = 1;
+	    else if (t1 && !t2)
+	      differ = -1;
+	    else if (!t1 && !t2)
+	      differ = -1;
+	    num_checked++;
+	    if (differ > 0) {
+	      Overloaded t = nodes[i];
+	      nodes[i] = nodes[j];
+	      nodes[j] = t;
+	      break;
+	    } else if ((differ == 0) && (Strcmp(t1, "0") == 0)) {
+	      t1 = Getattr(p1, "ltype");
+	      if (!t1) {
+		t1 = SwigType_ltype(Getattr(p1, "type"));
+		if (Getattr(p1, "tmap:typecheck:SWIGTYPE")) {
+		  SwigType_add_pointer(t1);
+		}
+		Setattr(p1, "ltype", t1);
+	      }
+	      t2 = Getattr(p2, "ltype");
+	      if (!t2) {
+		t2 = SwigType_ltype(Getattr(p2, "type"));
+		if (Getattr(p2, "tmap:typecheck:SWIGTYPE")) {
+		  SwigType_add_pointer(t2);
+		}
+		Setattr(p2, "ltype", t2);
+	      }
+
+	      /* Need subtype check here.  If t2 is a subtype of t1, then we need to change the
+	         order */
+
+	      if (SwigType_issubtype(t2, t1)) {
+		Overloaded t = nodes[i];
+		nodes[i] = nodes[j];
+		nodes[j] = t;
+	      }
+
+	      if (Strcmp(t1, t2) != 0) {
+		differ = 1;
+		break;
+	      }
+	    } else if (differ) {
+	      break;
+	    }
+	    if (Getattr(p1, "tmap:in:next")) {
+	      p1 = Getattr(p1, "tmap:in:next");
+	    } else {
+	      p1 = nextSibling(p1);
+	    }
+	    if (Getattr(p2, "tmap:in:next")) {
+	      p2 = Getattr(p2, "tmap:in:next");
+	    } else {
+	      p2 = nextSibling(p2);
+	    }
+	  }
+	  if (!differ) {
+	    /* See if declarations differ by const only */
+	    String *d1 = Getattr(nodes[i].n, "decl");
+	    String *d2 = Getattr(nodes[j].n, "decl");
+	    if (d1 && d2) {
+	      String *dq1 = Copy(d1);
+	      String *dq2 = Copy(d2);
+	      if (SwigType_isconst(d1)) {
+		Delete(SwigType_pop(dq1));
+	      }
+	      if (SwigType_isconst(d2)) {
+		Delete(SwigType_pop(dq2));
+	      }
+	      if (Strcmp(dq1, dq2) == 0) {
+
+		if (SwigType_isconst(d1) && !SwigType_isconst(d2)) {
+		  if (script_lang_wrapping) {
+		    // Swap nodes so that the const method gets ignored (shadowed by the non-const method)
+		    Overloaded t = nodes[i];
+		    nodes[i] = nodes[j];
+		    nodes[j] = t;
+		  }
+		  differ = 1;
+		  if (!nodes[j].error) {
+		    if (script_lang_wrapping) {
+		      Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[j].n), Getline(nodes[j].n),
+				   "Overloaded %s(%s) const ignored. Non-const method at %s:%d used.\n",
+				   Getattr(nodes[j].n, "name"), ParmList_errorstr(nodes[j].parms), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    } else {
+		      if (!Getattr(nodes[j].n, "overload:ignore"))
+			Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+				     "Overloaded method %s(%s) ignored. Method %s(%s) const at %s:%d used.\n",
+				     Getattr(nodes[j].n, "name"), ParmList_errorstr(nodes[j].parms),
+				     Getattr(nodes[i].n, "name"), ParmList_errorstr(nodes[i].parms), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    }
+		  }
+		  nodes[j].error = 1;
+		} else if (!SwigType_isconst(d1) && SwigType_isconst(d2)) {
+		  differ = 1;
+		  if (!nodes[j].error) {
+		    if (script_lang_wrapping) {
+		      Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[j].n), Getline(nodes[j].n),
+				   "Overloaded %s(%s) const ignored. Non-const method at %s:%d used.\n",
+				   Getattr(nodes[j].n, "name"), ParmList_errorstr(nodes[j].parms), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    } else {
+		      if (!Getattr(nodes[j].n, "overload:ignore"))
+			Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+				     "Overloaded method %s(%s) const ignored. Method %s(%s) at %s:%d used.\n",
+				     Getattr(nodes[j].n, "name"), ParmList_errorstr(nodes[j].parms),
+				     Getattr(nodes[i].n, "name"), ParmList_errorstr(nodes[i].parms), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    }
+		  }
+		  nodes[j].error = 1;
+		}
+	      }
+	      Delete(dq1);
+	      Delete(dq2);
+	    }
+	  }
+	  if (!differ) {
+	    if (!nodes[j].error) {
+	      if (script_lang_wrapping) {
+		Swig_warning(WARN_LANG_OVERLOAD_SHADOW, Getfile(nodes[j].n), Getline(nodes[j].n),
+			     "Overloaded %s(%s)%s is shadowed by %s(%s)%s at %s:%d.\n",
+			     Getattr(nodes[j].n, "name"), ParmList_errorstr(nodes[j].parms),
+			     SwigType_isconst(Getattr(nodes[j].n, "decl")) ? " const" : "",
+			     Getattr(nodes[i].n, "name"), ParmList_errorstr(nodes[i].parms),
+			     SwigType_isconst(Getattr(nodes[i].n, "decl")) ? " const" : "", Getfile(nodes[i].n), Getline(nodes[i].n));
+	      } else {
+		if (!Getattr(nodes[j].n, "overload:ignore"))
+		  Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+			       "Overloaded method %s(%s)%s ignored. Method %s(%s)%s at %s:%d used.\n",
+			       Getattr(nodes[j].n, "name"), ParmList_errorstr(nodes[j].parms),
+			       SwigType_isconst(Getattr(nodes[j].n, "decl")) ? " const" : "",
+			       Getattr(nodes[i].n, "name"), ParmList_errorstr(nodes[i].parms),
+			       SwigType_isconst(Getattr(nodes[i].n, "decl")) ? " const" : "", Getfile(nodes[i].n), Getline(nodes[i].n));
+	      }
+	      nodes[j].error = 1;
+	    }
+	  }
+	}
+      }
+    }
+  }
+  List *result = NewList();
+  {
+    int i;
+    for (i = 0; i < nnodes; i++) {
+      if (nodes[i].error)
+	Setattr(nodes[i].n, "overload:ignore", "1");
+      Append(result, nodes[i].n);
+      //      Printf(stdout,"[ %d ] %s\n", i, ParmList_errorstr(nodes[i].parms));
+      //      Swig_print_node(nodes[i].n);
+    }
+  }
+  return result;
+}
+
+/* end shameless borrowing */
+
+int any_varargs(ParmList *pl) {
+  Parm *p;
+
+  for (p = pl; p; p = nextSibling(p)) {
+    if (SwigType_isvarargs(Getattr(p, "type")))
+      return 1;
+  }
+
+  return 0;
+}
+
+String *get_lisp_type(SwigType *ty, const String_or_char *name) {
+  Hash *typemap = Swig_typemap_search("lisptype", ty, name, 0);
+  if (typemap) {
+    String *typespec = Getattr(typemap, "code");
+    return NewString(typespec);
+  } else {
+    return NewString("");
+  }
+}
+
+Node *parent_node_skipping_extends(Node *n) {
+  Node *result = n;
+  do {
+    result = parentNode(result);
+  }
+  while (Cmp("extend", nodeType(result)) == 0);
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * emit_num_lin_arguments()
+ *
+ * Calculate the total number of arguments.   This function is safe for use
+ * with multi-valued typemaps which may change the number of arguments in
+ * strange ways.
+ * ----------------------------------------------------------------------------- */
+
+int emit_num_lin_arguments(ParmList *parms) {
+  Parm *p = parms;
+  int nargs = 0;
+
+  while (p) {
+    // Printf(stderr,"enla: '%s' lin='%x'\n", Getattr(p,"name"), Getattr(p,"tmap:lin"));
+    if (Getattr(p, "tmap:lin")) {
+      nargs += GetInt(p, "tmap:lin:numinputs");
+      p = Getattr(p, "tmap:lin:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  /* DB 04/02/2003: Not sure this is necessary with tmap:in:numinputs */
+  /*
+     if (parms && (p = Getattr(parms,"emit:varargs"))) {
+     if (!nextSibling(p)) {
+     nargs--;
+     }
+     }
+   */
+  return nargs;
+}
+
+String *id_converter_type(SwigType const *type) {
+  SwigType *t = Copy(type);
+  String *result = 0;
+
+  if (SwigType_ispointer(t)) {
+    SwigType_pop(t);
+    String *pointee = id_converter_type(t);
+    result = NewStringf("(:* %s)", pointee);
+    Delete(pointee);
+  } else if (SwigType_ismemberpointer(t)) {
+    String *klass = SwigType_parm(t);
+    SwigType_pop(t);
+    String *member = id_converter_type(t);
+    result = NewStringf("(:member \"%s\" %s)", klass, member);
+    Delete(klass);
+    Delete(member);
+  } else if (SwigType_isreference(t)) {
+    SwigType_pop(t);
+    String *referencee = id_converter_type(t);
+    result = NewStringf("(:& %s)", referencee);
+    Delete(referencee);
+  } else if (SwigType_isarray(t)) {
+    String *size = SwigType_parm(t);
+    SwigType_pop(t);
+    String *element_type = id_converter_type(t);
+    result = NewStringf("(:array %s \"%s\")", element_type, size);
+    Delete(size);
+    Delete(element_type);
+  } else if (SwigType_isfunction(t)) {
+    result = NewString("(:function (");
+    String *parmlist_str = SwigType_parm(t);
+    List *parms = SwigType_parmlist(parmlist_str);
+
+    for (Iterator i = First(parms); i.item;) {
+      String *parm = id_converter_type((SwigType *) i.item);
+      Printf(result, "%s", parm);
+      i = Next(i);
+      if (i.item)
+	Printf(result, " ");
+      Delete(parm);
+    }
+    SwigType_pop(t);
+    String *ret = id_converter_type(t);
+    Printf(result, ") %s)", ret);
+
+    Delete(parmlist_str);
+    Delete(parms);
+    Delete(ret);
+  } else if (SwigType_isqualifier(t)) {
+    result = NewString("(:qualified (");
+    String *qualifiers_str = Copy(SwigType_parm(t));	// ?!
+    // Replaceall below SEGVs if we don't put the Copy here...
+    SwigType_pop(t);
+    String *qualifiee = id_converter_type(t);
+
+    Replaceall(qualifiers_str, " ", " :");
+    if (Len(qualifiers_str) > 0)
+      Printf(result, ":");
+    Printf(result, "%s) %s)", qualifiers_str, qualifiee);
+
+    Delete(qualifiers_str);
+    Delete(qualifiee);
+  } else if (SwigType_istemplate(t)) {
+    result = NewStringf("(:template \"%s\")", t);
+  } else {			/* if (SwigType_issimple(t)) */
+
+    if (Strstr(Char(t), "::")) {
+      result = listify_namespace(t);
+    } else {
+      result = NewStringf("\"%s\"", t);
+    }
+  }
+
+  Delete(t);
+  return result;
+}
+
+static ParmList *parmlist_with_names(ParmList *pl) {
+  ParmList *pl2 = CopyParmList(pl);
+  for (Parm *p = pl, *p2 = pl2; p2; p = nextSibling(p), p2 = nextSibling(p2)) {
+    if (!Getattr(p2, "name"))
+      Setattr(p2, "name", Getattr(p2, "lname"));
+    Setattr(p2, "name", strip_namespaces(Getattr(p2, "name")));
+    Setattr(p2, "tmap:ctype", Getattr(p, "tmap:ctype"));
+
+    String *temp = Getattr(p, "tmap:lin");
+    if (temp) {
+      Setattr(p2, "tmap:lin", temp);
+      Setattr(p2, "tmap:lin:next", Getattr(p, "tmap:lin:next"));
+    }
+  }
+  return pl2;
+}
+
+static String *parmlist_str_id_converter(ParmList *pl) {
+  String *result = NewString("");
+  for (Parm *p = pl; p;) {
+    String *lispy_type = id_converter_type(Getattr(p, "type"));
+    Printf(result, "(\"%s\" %s)", Getattr(p, "name"), lispy_type);
+    Delete(lispy_type);
+    if ((p = nextSibling(p)))
+      Printf(result, " ");
+  }
+  return result;
+}
+
+String *collect_others_args(Node *overload) {
+  String *overloaded_from = Getattr(overload, "sym:overloaded");
+  String *others_args = NewString("");
+  int first_overload = 1;
+
+  for (Node *overload2 = overloaded_from; overload2; overload2 = Getattr(overload2, "sym:nextSibling")) {
+    if (overload2 == overload || GetInt(overload2, "overload:ignore"))
+      continue;
+
+    ParmList *opl = parmlist_with_names(Getattr(overload2, "wrap:parms"));
+    String *args = parmlist_str_id_converter(opl);
+    if (!first_overload)
+      Printf(others_args, "\n                           ");
+    Printf(others_args, "(%s)", args);
+    Delete(args);
+    Delete(opl);
+    first_overload = 0;
+  }
+  return others_args;
+}
+
+struct IDargs {
+  String *name;
+  String *type;
+  String *klass;
+  String *arity;
+
+  IDargs():name(0), type(0), klass(0), arity(0) {
+  } String *full_quoted_str() {
+    String *result = no_others_quoted_str();
+    if (arity)
+      Printf(result, " :arity %s", arity);
+    return result;
+  }
+
+  String *no_others_quoted_str() {
+    String *result = NewString("");
+    Printf(result, "\"%s\" :type :%s", name, type);
+    if (klass)
+      Printf(result, " :class \"%s\"", klass);
+    return result;
+  }
+
+  String *noname_str() {
+    String *result = NewString("");
+    Printf(result, " :type :%s", type);
+    if (klass)
+      Printf(result, " :class \"%s\"", klass);
+    if (arity)
+      Printf(result, " :arity %s", arity);
+    return result;
+  }
+};
+IDargs *id_converter_arguments(Node *n) {
+  IDargs *result = (IDargs *) GetVoid(n, "allegrocl:id-converter-args");
+  if (!result)
+    result = new IDargs;
+
+  // Base name
+  if (!result->name) {
+    result->name = Getattr(n, "allegrocl:old-sym:name");
+    if (!result->name)
+      result->name = Getattr(n, "sym:name");
+    result->name = Copy(result->name);
+  }
+  // :type
+  if (result->type)
+    Delete(result->type);
+  if (!Getattr(n, "allegrocl:kind"))
+    Setattr(n, "allegrocl:kind", "function");
+  if (Strstr(Getattr(n, "name"), "operator "))
+    Replaceall(Getattr(n, "allegrocl:kind"), "function", "operator");
+  if (Strstr(Getattr(n, "allegrocl:kind"), "variable")) {
+    int name_end = Len(Getattr(n, "sym:name")) - 4;
+    char *str = Char(Getattr(n, "sym:name"));
+    String *get_set = NewString(str + name_end + 1);
+    result->type = Copy(Getattr(n, "allegrocl:kind"));
+    Replaceall(result->type, "variable", "");
+    Printf(result->type, "%ster", get_set);
+    Delete(get_set);
+  } else {
+    result->type = Copy(Getattr(n, "allegrocl:kind"));
+  }
+
+  // :class
+  if (Strstr(result->type, "member ")) {
+    Replaceall(result->type, "member ", "");
+    if (!result->klass)
+      result->klass = Copy(Getattr(parent_node_skipping_extends(n), "sym:name"));
+  }
+  // :arity
+  if (Getattr(n, "sym:overloaded")) {
+    if (result->arity)
+      Delete(result->arity);
+    result->arity = NewStringf("%d",
+			       // emit_num_arguments(Getattr(n, "wrap:parms")));
+			       emit_num_lin_arguments(Getattr(n, "wrap:parms")));
+    // Printf(stderr, "got arity of '%s' node '%s' '%x'\n", result->arity, Getattr(n,"name"), Getattr(n,"wrap:parms"));
+  }
+
+  SetVoid(n, "allegrocl:id-converter-args", result);
+  return result;
+}
+
+int ALLEGROCL::emit_buffered_defuns(Node *n) {
+
+  Node *overloaded_from = Getattr(n, "sym:overloaded");
+
+  String *wrap;
+
+  if (!overloaded_from) {
+    wrap = Getattr(n, "allegrocl:lisp-wrap");
+
+    Printf(f_clwrap, "%s\n", wrap);
+    Delattr(n, "allegrocl:lisp-wrap");
+    Delete(wrap);
+  } else {
+    for (Node *overload = overloaded_from; overload; overload = Getattr(overload, "sym:nextSibling")) {
+      String *others_args = collect_others_args(overload);
+      wrap = Getattr(overload, "allegrocl:lisp-wrap");
+
+      Replaceall(wrap, "@@OTHERS-ARGS-GO-HERE@@", others_args);
+//        IDargs* id_args = id_converter_arguments(overload);
+//        Replaceall(id_args->others_args, "@@OTHERS-ARGS-GO-HERE@@", others_args);
+
+      if (!GetInt(overload, "overload:ignore"))
+	Printf(f_clwrap, "%s", wrap);
+
+      Delattr(overload, "allegrocl:lisp-wrap");
+      Delete(wrap);
+    }
+  }
+  return SWIG_OK;
+}
+
+String *dispatching_type(Parm *p) {
+  String *result = 0;
+
+  String *parsed = Getattr(p, "type");	//Swig_cparse_type(Getattr(p,"tmap:ctype"));
+  String *cl_t = SwigType_typedef_resolve_all(parsed);
+
+  Hash *typemap = Swig_typemap_search("lispclass", parsed, Getattr(p, "name"), 0);
+  //  Printf(stderr,"inspecting type '%s' for class\n", parsed);
+  //  Printf(stderr," cfcocr = '%s' res_all = '%s'\n",
+  //     class_from_class_or_class_ref(parsed), cl_t);
+  if (typemap) {
+    result = Copy(Getattr(typemap, "code"));
+  } else {
+    String *lookup_type = class_from_class_or_class_ref(parsed);
+    if (lookup_type)
+      result = lookup_defined_foreign_ltype(lookup_type);
+  }
+
+  //  if (!result && SwigType_ispointer(cl_t)) {
+  //    SwigType_pop(cl_t);
+  //    result = lookup_defined_foreign_ltype(cl_t);
+  //  }
+
+  if (!result)
+    result = NewStringf("ff:foreign-pointer");
+
+  // Delete(parsed);
+  Delete(cl_t);
+  return result;
+}
+
+String *defmethod_lambda_list(Node *overload) {
+  String *result = NewString("");
+
+  ParmList *parms = Getattr(overload, "wrap:parms");
+  Parm *p;
+  int a;
+
+  for (a = 0, p = parms; p; p = nextSibling(p), ++a) {
+    if (a != 0)
+      Printf(result, " ");
+    Printf(result, "(arg%d ", a);
+    Printf(result, "%s", dispatching_type(p));
+    Printf(result, ")");
+  }
+
+  return result;
+}
+
+int ALLEGROCL::emit_dispatch_defun(Node *n) {
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_dispatch_defun: ENTER... ");
+#endif
+  List *overloads = Swig_overload_rank(n, true);
+
+  String *id_args = id_converter_arguments(n)->no_others_quoted_str();
+  Printf(f_clwrap, "(swig-dispatcher (%s :arities (", id_args);
+
+  int last_arity = -1;
+  for (Iterator i = First(overloads); i.item; i = Next(i)) {
+    int arity = emit_num_lin_arguments(Getattr(i.item, "wrap:parms"));
+    if (arity == last_arity)
+      continue;
+
+    Printf(f_clwrap, "%s%d", last_arity == -1 ? "" : " ", arity);
+
+    last_arity = arity;
+  }
+  Printf(f_clwrap, ")))\n");
+
+  Delete(id_args);
+  Delete(overloads);
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_dispatch_defun: EXIT\n");
+#endif
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::emit_defun(Node *n, File *fcl) {
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_defun: ENTER... ");
+#endif
+
+#ifdef ALLEGROCL_DEBUG
+  int auto_generated = Cmp(Getattr(n, "view"), "globalfunctionHandler");
+  Printf(stderr, "%s%sfunction %s%s%s\n", auto_generated ? "> " : "", Getattr(n, "sym:overloaded")
+	 ? "overloaded " : "", current_namespace, (current_namespace) > 0 ? "::" : "", Getattr(n, "sym:name"));
+  Printf(stderr, "  (view: %s)\n", Getattr(n, "view"));
+#endif
+
+  String *funcname = Getattr(n, "allegrocl:old-sym:name");
+  if (!funcname)
+    funcname = Getattr(n, "sym:name");
+  String *mangled_name = Getattr(n, "wrap:name");
+  ParmList *pl = parmlist_with_names(Getattr(n, "wrap:parms"));
+
+  // attach typemap info.
+  Wrapper *wrap = NewWrapper();
+  Swig_typemap_attach_parms("lin", pl, wrap);
+  // Swig_typemap_attach_parms("ffitype", pl, wrap);
+  Swig_typemap_lookup("lout", n, "result", 0);
+
+  SwigType *result_type = Swig_cparse_type(Getattr(n, "tmap:ctype"));
+  // prime the pump, with support for OUTPUT, INOUT typemaps.
+  Printf(wrap->code,
+	 "(cl::let ((ACL_ffresult %s:*void*)\n        ACL_result)\n  $body\n  (cl::if (cl::eq ACL_ffresult %s:*void*)\n    (cl::values-list ACL_result)\n   (cl::values-list (cl::cons ACL_ffresult ACL_result))))",
+	 swig_package, swig_package);
+
+  Parm *p;
+  int largnum = 0, argnum = 0, first = 1;
+  // int varargs=0;
+  if (Generate_Wrapper) {
+    String *extra_parms = id_converter_arguments(n)->noname_str();
+    if (Getattr(n, "sym:overloaded"))
+      Printf(fcl, "(swig-defmethod (\"%s\" \"%s\"%s)\n", funcname, mangled_name, extra_parms);
+    else
+      Printf(fcl, "(swig-defun (\"%s\" \"%s\"%s)\n", funcname, mangled_name, extra_parms);
+    Delete(extra_parms);
+  }
+  // Just C
+  else {
+    Printf(fcl, "(swig-defun (\"%s\" \"%s\")\n", funcname, Generate_Wrapper ? mangled_name : funcname);
+  }
+
+  //////////////////////////////////////
+  // Lisp foreign call parameter list //
+  //////////////////////////////////////
+  Printf(fcl, "  (");
+
+  /* Special cases */
+
+  if (ParmList_len(pl) == 0) {
+    Printf(fcl, ":void");
+/*  } else if (any_varargs(pl)) {
+    Printf(fcl, "#| varargs |#");
+    varargs=1; */
+  } else {
+    String *largs = NewString("");
+
+    for (p = pl; p; p = nextSibling(p), argnum++, largnum++) {
+      // SwigType *argtype=Getattr(p, "type");
+      SwigType *argtype = Swig_cparse_type(Getattr(p, "tmap:ctype"));
+
+      if (!first) {
+	Printf(fcl, "\n   ");
+      }
+
+      if (SwigType_isvarargs(argtype)) {
+	Printf(stderr, "Function %s (line %d) contains varargs, which is not directly supported. Use %%varargs instead.\n", Getattr(n, "name"), Getline(n));
+      } else {
+	String *argname = NewStringf("PARM%d_%s", largnum, Getattr(p, "name"));
+
+	// Swig_print_node(p);
+	// Printf(stderr,"%s\n", Getattr(p,"tmap:lin"));
+	String *ffitype = compose_foreign_type(argtype, Getattr(p,"name"));
+	String *deref_ffitype;
+
+	deref_ffitype = dereference_ffitype(ffitype);
+
+/*
+	String *temp = Copy(argtype);
+
+	if (SwigType_ispointer(temp)) {
+	  SwigType_pop(temp);
+	  deref_ffitype = compose_foreign_type(temp);
+	} else {
+	  deref_ffitype = Copy(ffitype);
+	}
+
+	Delete(temp);
+*/
+	// String *lisptype=get_lisp_type(argtype, argname);
+	String *lisptype = get_lisp_type(Getattr(p, "type"), Getattr(p, "name"));
+
+#ifdef ALLEGROCL_DEBUG
+	Printf(stderr, "lisptype of '%s' '%s' = '%s'\n",
+	       Getattr(p, "type"), Getattr(p, "name"), lisptype);
+#endif
+
+	// while we're walking the parameters, generating LIN
+	// wrapper code...
+	Setattr(p, "lname", NewStringf("SWIG_arg%d", largnum));
+
+	String *parm_code = Getattr(p, "tmap:lin");
+	if (parm_code) {
+	  String *lname = Getattr(p, "lname");
+
+	  Printf(largs, " %s", lname);
+	  Replaceall(parm_code, "$in_fftype", ffitype); // must come before $in
+	  Replaceall(parm_code, "$in", argname);
+	  Replaceall(parm_code, "$out", lname);
+	  Replaceall(parm_code, "$*in_fftype", deref_ffitype);
+	  Replaceall(wrap->code, "$body", parm_code);
+	}
+
+	String *dispatchtype = Getattr(n, "sym:overloaded") ? dispatching_type(p) : NewString("");
+
+	// if this parameter has been removed from the C/++ wrapper
+	// it shouldn't be in the lisp wrapper either.
+	if (!checkAttribute(p, "tmap:in:numinputs", "0")) {
+	  Printf(fcl, "(%s %s %s %s %s)",
+		 // parms in the ff wrapper, but not in the lisp wrapper.
+		 (checkAttribute(p, "tmap:lin:numinputs", "0") ? ":p-" : ":p+"), argname, dispatchtype, ffitype, lisptype);
+
+	  first = 0;
+	}
+
+	Delete(ffitype);
+	Delete(lisptype);
+      }
+    }
+
+    Printf(wrap->locals, "%s", largs);
+  }
+
+  String *lout = Getattr(n, "tmap:lout");
+  Replaceall(lout, "$owner", GetFlag(n, "feature:new") ? "t" : "nil");
+
+  Replaceall(wrap->code, "$body", lout);
+  // $lclass handling.
+  String *lclass = (String *) 0;
+  SwigType *parsed = Swig_cparse_type(Getattr(n, "tmap:ctype"));
+  //  SwigType *cl_t = SwigType_typedef_resolve_all(parsed);
+  SwigType *cl_t = class_from_class_or_class_ref(parsed);
+  String *out_ffitype = compose_foreign_type(parsed);
+  String *deref_out_ffitype;
+  String *out_temp = Copy(parsed);
+
+  if (SwigType_ispointer(out_temp)) {
+    SwigType_pop(out_temp);
+    deref_out_ffitype = compose_foreign_type(out_temp);
+  } else {
+    deref_out_ffitype = Copy(out_ffitype);
+  }
+
+  Delete(out_temp);
+
+  Delete(parsed);
+
+  int isPtrReturn = 0;
+
+  if (cl_t) {
+    lclass = lookup_defined_foreign_ltype(cl_t);
+    isPtrReturn = 1;
+  }
+  //  if (SwigType_ispointer(cl_t)) {
+  //    isPtrReturn = 1;
+  //    SwigType_pop(cl_t);
+  //    lclass = lookup_defined_foreign_ltype(cl_t);
+  //  }
+
+  int ff_foreign_ptr = 0;
+  if (!lclass) {
+    ff_foreign_ptr = 1;
+    lclass = NewStringf("ff:foreign-pointer");
+  }
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "for output wrapping %s: type=%s, ctype=%s\n", Getattr(n, "name"),
+	 Getattr(n, "type"), Swig_cparse_type(Getattr(n, "tmap:ctype")));
+#endif
+
+  if (lclass)
+    Replaceall(wrap->code, "$lclass", lclass);
+  if (out_ffitype)
+    Replaceall(wrap->code, "$out_fftype", out_ffitype);
+  if (deref_out_ffitype)
+    Replaceall(wrap->code, "$*out_fftype", deref_out_ffitype);
+  //  if(Replaceall(wrap->code,"$lclass", lclass) && !isPtrReturn) {
+  //    Swig_warning(WARN_LANG_RETURN_TYPE,Getfile(n), Getline(n),
+  //                 "While Wrapping %s, replaced a $lclass reference when return type is non-pointer %s!\n",
+  //                 Getattr(n,"name"), cl_t);
+  //  }
+
+  Replaceall(wrap->code, "$body", NewStringf("(swig-ff-call%s)", wrap->locals));
+//   Replaceall(wrap->code,"$body", 
+//           (!Strcmp(result_type,"void") ?
+//            NewStringf("(swig-ff-call%s)", wrap->locals) :
+//            NewStringf("(push (swig-ff-call%s) ACL_result)", wrap->locals)));
+  String *ldestructor = Copy(lclass);
+  if (ff_foreign_ptr)
+    Replaceall(ldestructor, ldestructor, "identity");
+  else
+    Replaceall(ldestructor, ":type :class", ":type :destructor");
+  Replaceall(wrap->code, "$ldestructor", ldestructor);
+  Delete(ldestructor);
+
+  Printf(fcl, ")\n");		/* finish arg list */
+
+  /////////////////////////////////////////////////////
+  // Lisp foreign call return type and optimizations //
+  /////////////////////////////////////////////////////
+  Printf(fcl, "  (:returning (%s %s)", compose_foreign_type(result_type), get_lisp_type(Getattr(n, "type"), "result"));
+
+  for (Iterator option = First(n); option.item; option = Next(option)) {
+    if (Strncmp("feature:ffargs:", option.key, 15))
+      continue;
+    String *option_val = option.item;
+    String *option_name = NewString(Char(option.key) + 14);
+    Replaceall(option_name, "_", "-");
+
+    // TODO: varargs vs call-direct ?
+    Printf(fcl, "\n   %s %s", option_name, option_val);
+
+    Delete(option_name);
+  }
+
+  Printf(fcl, ")\n  %s)\n\n", wrap->code);
+  // Wrapper_print(wrap, stderr);
+
+  Delete(result_type);
+  Delete(mangled_name);
+  Delete(pl);
+  DelWrapper(wrap);
+
+#ifdef ALLEGROCL_WRAP_DEBUG
+  Printf(stderr, "emit_defun: EXIT\n");
+#endif
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::functionWrapper(Node *n) {
+
+  ParmList *parms = CopyParmList(Getattr(n, "parms"));
+  Wrapper *f = NewWrapper();
+
+  String *raw_return_type = Swig_typemap_lookup("ctype", n, "", 0);
+  SwigType *return_type = Swig_cparse_type(raw_return_type);
+  SwigType *resolved = SwigType_typedef_resolve_all(return_type);
+  int is_void_return = (Cmp(resolved, "void") == 0);
+
+  Delete(resolved);
+
+  if (!is_void_return) {
+    String *lresult_init = NewStringf("= (%s)0", raw_return_type);
+    Wrapper_add_localv(f, "lresult",
+		       SwigType_lstr(SwigType_ltype(return_type), "lresult"),
+		       lresult_init, NIL);
+    Delete(lresult_init);
+  }
+  // Emit all of the local variables for holding arguments.
+  emit_parameter_variables(parms, f);
+
+  // Attach the standard typemaps 
+  Swig_typemap_attach_parms("ctype", parms, f);
+  Swig_typemap_attach_parms("lin", parms, f);
+  emit_attach_parmmaps(parms, f);
+
+  String *mangled = mangle_name(n);
+  Node *overloaded = Getattr(n, "sym:overloaded");
+
+  // Parameter overloading
+  Setattr(n, "wrap:parms", parms);
+  Setattr(n, "wrap:name", mangled);
+
+  if (overloaded) {
+    // emit warnings when overloading is impossible on the lisp side.
+    // basically Swig_overload_check(n), but with script_lang_wrapping
+    // set to true.
+    Delete(Swig_overload_rank(n, true));
+    if (Getattr(n, "overload:ignore")) {
+      // if we're the last overload, make sure to force the emit
+      // of the rest of the overloads before we leave.
+      Printf(stderr, "ignored overload %s(%x)\n", Getattr(n, "name"), Getattr(n, "sym:nextSibling"));
+      if (!Getattr(n, "sym:nextSibling")) {
+	update_package_if_needed(n);
+	emit_buffered_defuns(n);
+	emit_dispatch_defun(n);
+      }
+      DelWrapper(f);
+      return SWIG_OK;
+    }
+  }
+  // Get number of required and total arguments 
+  int num_arguments = emit_num_arguments(parms);
+  int gencomma = 0;
+
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "Walking parameters for %s '%s'\n", Getattr(n, "allegrocl:kind"), Getattr(n, "name"));
+#endif
+  // Now walk the function parameter list and generate code to get arguments
+  String *name_and_parms = NewStringf("%s (", mangled);
+  int i;
+  Parm *p;
+  for (i = 0, p = parms; i < num_arguments; i++) {
+
+    while (p && checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    if (!p)
+      break;
+
+    SwigType *c_parm_type = Swig_cparse_type(Getattr(p, "tmap:ctype"));
+    String *arg = NewStringf("l%s", Getattr(p, "lname"));
+
+    // Emit parameter declaration
+    if (gencomma)
+      Printf(name_and_parms, ", ");
+    String *parm_decl = SwigType_str(c_parm_type, arg);
+    Printf(name_and_parms, "%s", parm_decl);
+#ifdef ALLEGROCL_DEBUG
+    Printf(stderr, "  param: %s\n", parm_decl);
+#endif
+    Delete(parm_decl);
+    gencomma = 1;
+
+    // Emit parameter conversion code
+    String *parm_code = Getattr(p, "tmap:in");
+    //if (!parm_code) {
+    //  Swig_warning(...);
+    //  p = nextSibling(p);
+    /*} else */  {
+      // canThrow(n, "in", p);
+      Replaceall(parm_code, "$input", arg);
+      Setattr(p, "emit:input", arg);
+      Printf(f->code, "%s\n", parm_code);
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    Delete(arg);
+  }
+  Printf(name_and_parms, ")");
+
+  // Emit the function definition
+  String *signature = SwigType_str(return_type, name_and_parms);
+  Printf(f->def, "EXPORT %s {", signature);
+  if (CPlusPlus)
+    Printf(f->code, "  try {\n");
+
+  String *actioncode = emit_action(n);
+
+  String *result_convert = Swig_typemap_lookup_out("out", n, "result", f, actioncode);
+  Replaceall(result_convert, "$result", "lresult");
+  Printf(f->code, "%s\n", result_convert);
+  Printf(f->code, "    return lresult;\n");
+  Delete(result_convert);
+  emit_return_variable(n, Getattr(n, "type"), f);
+
+  if (CPlusPlus) {
+    Printf(f->code, "  } catch (...) {\n");
+    if (!is_void_return)
+      Printf(f->code, "    return (%s)0;\n", raw_return_type);
+    Printf(f->code, "  }\n");
+  }
+  Printf(f->code, "}\n");
+
+  /* print this when in C mode? make this a command-line arg? */
+  if (Generate_Wrapper)
+    Wrapper_print(f, f_cxx);
+
+  String *f_buffer = NewString("");
+
+  emit_defun(n, f_buffer);
+  Setattr(n, "allegrocl:lisp-wrap", f_buffer);
+
+  if (!overloaded || !Getattr(n, "sym:nextSibling")) {
+    update_package_if_needed(n);
+    emit_buffered_defuns(n);
+    // this is the last overload.
+    if (overloaded) {
+      emit_dispatch_defun(n);
+    }
+  }
+
+  DelWrapper(f);
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::namespaceDeclaration(Node *n) {
+  // Empty namespaces are not worth DEFPACKAGEing.
+  // Swig_print_node(n);
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "namespaceDecl: '%s'(0x%x) (fc=0x%x)\n", Getattr(n, "sym:name"), n, firstChild(n));
+#endif
+
+  if (!firstChild(n))
+    return SWIG_OK;
+
+  String *name = Getattr(n, "sym:name");
+
+  String *old_namespace = current_namespace;
+  if (Cmp(current_namespace, "") == 0)
+    current_namespace = NewStringf("%s", name);
+  else
+    current_namespace = NewStringf("%s::%s", current_namespace, name);
+
+  if (!GetInt(defined_namespace_packages, current_namespace)) {
+    SetInt(defined_namespace_packages, current_namespace, 1);
+    String *lispy_namespace = listify_namespace(current_namespace);
+    Printf(f_clhead, "(swig-defpackage %s)\n", lispy_namespace);
+    Delete(lispy_namespace);
+  }
+
+  emit_children(n);
+
+  Delete(current_namespace);
+  current_namespace = old_namespace;
+  return SWIG_OK;
+}
+
+int ALLEGROCL::constructorHandler(Node *n) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "constructor %s\n", Getattr(n, "name"));
+#endif
+  // Swig_print_node(n);
+  Setattr(n, "allegrocl:kind", "constructor");
+  Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name"));
+
+  // Let SWIG generate a global forwarding function.
+  return Language::constructorHandler(n);
+}
+
+int ALLEGROCL::destructorHandler(Node *n) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "destructor %s\n", Getattr(n, "name"));
+#endif
+
+  Setattr(n, "allegrocl:kind", "destructor");
+  Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name"));
+
+  // Let SWIG generate a global forwarding function.
+  return Language::destructorHandler(n);
+}
+
+int ALLEGROCL::constantWrapper(Node *n) {
+
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "constant %s\n", Getattr(n, "name"));
+#endif
+
+  if (Generate_Wrapper) {
+    // Setattr(n,"wrap:name",mangle_name(n, "ACLPP"));
+    String *const_type = Getattr(n, "type");
+
+    String *const_val = 0;
+    String *raw_const = Getattr(n, "value");
+
+    if (SwigType_type(const_type) == T_STRING) {
+      const_val = NewStringf("\"%s\"", raw_const);
+    } else if (SwigType_type(const_type) == T_CHAR) {
+      const_val = NewStringf("'%s'", raw_const);
+    } else {
+      const_val = Copy(raw_const);
+    }
+
+    SwigType_add_qualifier(const_type, "const");
+    SwigType_add_qualifier(const_type, "static");
+
+    String *ppcname = NewStringf("ACLppc_%s", Getattr(n, "name"));
+    Printf(f_cxx, "static const %s = %s;\n", SwigType_lstr(const_type, ppcname), const_val);
+
+    Setattr(n, "name", ppcname);
+    SetFlag(n, "feature:immutable");
+
+    Delete(const_val);
+    return variableWrapper(n);
+  }
+
+  String *type = Getattr(n, "type");
+  String *value = Getattr(n, "value");
+  String *converted_value = convert_literal(value, type);
+  String *name = Getattr(n, "sym:name");
+
+  Setattr(n, "allegrocl:kind", "constant");
+  Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name"));
+
+#if 0
+  Printf(stdout, "constant %s is of type %s. value: %s\n", name, type, converted_value);
+#endif
+
+  if (converted_value) {
+    Printf(f_clwrap, "(swig-defconstant \"%s\" %s)\n", name, converted_value);
+  } else {
+    Swig_warning(WARN_LANG_DISCARD_CONST, Getfile(n), Getline(n), "Unable to parse constant value '%s'. Setting to NIL\n", value);
+    Printf(f_clwrap, "(swig-defconstant \"%s\" nil #| %s |#)\n", name, value);
+  }
+
+  Delete(converted_value);
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::globalvariableHandler(Node *n) {
+  if (Generate_Wrapper)
+    return Language::globalvariableHandler(n);
+
+  // String *name = Getattr(n, "name");
+  SwigType *type = Getattr(n, "type");
+  SwigType *ctype;
+  SwigType *rtype = SwigType_typedef_resolve_all(type);
+
+  int pointer_added = 0;
+
+  if (SwigType_isclass(rtype)) {
+    SwigType_add_pointer(type);
+    SwigType_add_pointer(rtype);
+    pointer_added = 1;
+  }
+
+  ctype = SwigType_str(type, 0);
+  // EXPORT <SwigType_str> <mangled_name>;
+  // <SwigType_str> <mangled_name> = <name>;
+  //  Printf(f_cxx, "EXPORT %s %s;\n%s %s = %s%s;\n", ctype, mangled_name,
+  //     ctype, mangled_name, (pointer_added ? "&" : ""), name);
+
+  Printf(f_clwrap, "(swig-defvar \"%s\" \"%s\" :type %s)\n",
+	 Getattr(n, "sym:name"), Getattr(n, "sym:name"), ((SwigType_isconst(type)) ? ":constant" : ":variable"));
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::variableWrapper(Node *n) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "variable %s\n", Getattr(n, "name"));
+#endif
+  Setattr(n, "allegrocl:kind", "variable");
+  Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name"));
+
+  // Let SWIG generate a get/set function pair.
+  if (Generate_Wrapper)
+    return Language::variableWrapper(n);
+
+  String *name = Getattr(n, "name");
+  SwigType *type = Getattr(n, "type");
+  SwigType *ctype;
+  SwigType *rtype = SwigType_typedef_resolve_all(type);
+
+  String *mangled_name = mangle_name(n);
+
+  int pointer_added = 0;
+
+  if (SwigType_isclass(rtype)) {
+    SwigType_add_pointer(type);
+    SwigType_add_pointer(rtype);
+    pointer_added = 1;
+  }
+
+  ctype = SwigType_str(type, 0);
+  // EXPORT <SwigType_str> <mangled_name>;
+  // <SwigType_str> <mangled_name> = <name>;
+  Printf(f_cxx, "EXPORT %s %s;\n%s %s = %s%s;\n", ctype, mangled_name, ctype, mangled_name, (pointer_added ? "&" : ""), name);
+
+  Printf(f_cl, "(swig-defvar \"%s\" :type %s)\n", mangled_name, ((SwigType_isconst(type)) ? ":constant" : ":variable"));
+  /*
+     Printf(f_cxx, "// swigtype: %s\n", SwigType_typedef_resolve_all(Getattr(n,"type")));
+     Printf(f_cxx, "// vwrap: %s\n", compose_foreign_type(SwigType_strip_qualifiers(Copy(rtype))));
+   */
+
+  Delete(mangled_name);
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::memberfunctionHandler(Node *n) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "member function %s::%s\n", Getattr(parent_node_skipping_extends(n), "name"), Getattr(n, "name"));
+#endif
+  Setattr(n, "allegrocl:kind", "member function");
+  Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name"));
+
+  // Let SWIG generate a global forwarding function.
+  return Language::memberfunctionHandler(n);
+}
+
+int ALLEGROCL::membervariableHandler(Node *n) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "member variable %s::%s\n", Getattr(parent_node_skipping_extends(n), "name"), Getattr(n, "name"));
+#endif
+  Setattr(n, "allegrocl:kind", "member variable");
+  Setattr(n, "allegrocl:old-sym:name", Getattr(n, "sym:name"));
+
+  // Let SWIG generate a get/set function pair.
+  return Language::membervariableHandler(n);
+}
+
+int ALLEGROCL::typedefHandler(Node *n) {
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "In typedefHAND\n");
+  // Swig_print_node(n);
+#endif
+
+  SwigType *typedef_type = Getattr(n,"type");
+  // has the side-effect of noting any implicit
+  // template instantiations in type.
+  String *ff_type = compose_foreign_type(typedef_type);
+
+  String *sym_name = Getattr(n, "sym:name");
+
+  String *name;
+  String *type_ref;
+
+  if (in_class) {
+#ifdef ALLEGROCL_TYPE_DEBUG
+    Printf(stderr, "  typedef in class '%s'(%x)\n", Getattr(in_class, "sym:name"), in_class);
+#endif
+    Setattr(n, "allegrocl:typedef:in-class", in_class);
+  }
+
+  if (in_class) {
+    String *class_name = Getattr(in_class, "name");
+    name = NewStringf("%s__%s", class_name, sym_name);
+    type_ref = NewStringf("%s::%s", class_name, sym_name);
+    Setattr(n, "allegrocl:in-class", in_class);
+  } else {
+    name = Copy(sym_name);
+    type_ref = Copy(Getattr(n, "name"));
+  }
+
+  Setattr(n, "allegrocl:namespace", current_namespace);
+
+  String *lookup = lookup_defined_foreign_type(typedef_type);
+
+  // Printf(stderr, "** lookup='%s'(%x), ff_type='%s', strstr = '%d'\n", lookup, lookup, ff_type, !Strstr(ff_type,"void"));
+
+  if(lookup || (!lookup && !Strstr(ff_type,"void")))
+	  add_defined_foreign_type(n, 0, type_ref, name);
+  else add_forward_referenced_type(n);
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "Out typedefHAND\n");
+#endif
+
+  Delete(ff_type);
+
+  return SWIG_OK;
+}
+
+// forward referenced classes are added specially to defined_foreign_types
+int ALLEGROCL::classforwardDeclaration(Node *n) {
+  add_forward_referenced_type(n);
+  return SWIG_OK;
+}
+
+int ALLEGROCL::classHandler(Node *n) {
+#ifdef ALLEGROCL_DEBUG
+  Printf(stderr, "class %s::%s\n", current_namespace, Getattr(n, "sym:name"));
+#endif
+
+  if (Generate_Wrapper)
+    return cppClassHandler(n);
+  else
+    return cClassHandler(n);
+}
+
+int ALLEGROCL::cClassHandler(Node *n) {
+  //  String *cDeclName = Getattr(n,"classDeclaration:name");
+  // String *name= Getattr(n, "sym:name"); 
+  //  String *kind = Getattr(n,"kind");
+  // Node *c;
+
+  /* Add this structure to the known lisp types */
+  // Printf(stderr, "Adding %s foreign type\n", name);
+  String *ns = listify_namespace(current_namespace);
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "In cClassHAND\n");
+#endif
+
+  add_defined_foreign_type(n);
+
+  Delete(ns);
+
+#ifdef ALLEGROCL_TYPE_DEBUG
+  Printf(stderr, "Out cClassHAND\n");
+#endif
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::cppClassHandler(Node *n) {
+
+  // String *name=Getattr(n, "sym:name");
+  // String *kind = Getattr(n,"kind");
+
+  /* Template instantiation.
+     Careful. 
+     SWIG does not create instantiations of templated classes whenever
+     it sees a templated class reference (say, as a return type, or
+     in a parameter list).
+
+     The %template directive results in a templated class instantiation
+     that will actually be seen by <LANG> :: classHandler().
+
+     In this case, we don't want to error if the type already exists;
+     the point is to force the creation of wrappers for the templated
+     class.
+   */
+  String *templated = Getattr(n, "template");
+  String *t_name;
+  // String *ns = listify_namespace(current_namespace);
+
+  if (templated) {
+    t_name = namespaced_name(n);
+  } else {
+    t_name = Getattr(n, "name");
+  }
+
+  Setattr(n, "allegrocl:namespace", current_namespace);
+
+  /* Add this structure to the known lisp types.
+     Class may contain references to the type currently being
+     defined */
+  if (!templated || !lookup_defined_foreign_type(t_name)) {
+#ifdef ALLEGROCL_CLASS_DEBUG
+    Printf(stderr, "Adding %s foreign type\n", Getattr(n, "sym:name"));
+#endif
+    add_defined_foreign_type(n);
+  } else {
+#ifdef ALLEGROCL_CLASS_DEBUG
+    Printf(stderr, "cppClassHand: type %s already exists. Assuming %%template instantiation for wrapping purposes.\n", Getattr(n, "sym:name"));
+#endif
+    add_defined_foreign_type(n, 1);
+  }
+
+  // Generate slot accessors, constructor, and destructor.
+  Node *prev_class = in_class;
+  in_class = n;
+
+  Node *c;
+  // walk all member variables.
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "   MANUALLY walking class members... \n");
+#endif
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    // ping the types of all children--even protected and private
+    // so their types can be added to the linked_type_list.
+    SwigType *childType = NewStringf("%s%s", Getattr(c, "decl"),
+				     Getattr(c, "type"));
+    if (!SwigType_isfunction(childType))
+      Delete(compose_foreign_type(childType));
+
+    Delete(childType);
+  }
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "   MANUAL walk DONE.\n");
+#endif
+
+  // this will walk all necessary methods.
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "   LANGUAGE walk of children...\n");
+#endif
+  Language::classHandler(n);
+#ifdef ALLEGROCL_CLASS_DEBUG
+  Printf(stderr, "   LANGUAGE walk DONE\n");
+#endif
+  in_class = prev_class;
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::emit_one(Node *n) {
+  // When the current package does not correspond with the current
+  // namespace we need to generate an IN-PACKAGE form, unless the
+  // current node is another namespace node.
+  if (Cmp(nodeType(n), "namespace") != 0 && Cmp(current_package, current_namespace) != 0) {
+    String *lispy_namespace = listify_namespace(current_namespace);
+    Printf(f_clwrap, "(swig-in-package %s)\n", lispy_namespace);
+    Delete(lispy_namespace);
+    Delete(current_package);
+    current_package = NewStringf("%s", current_namespace);
+  }
+
+  Setattr(n, "allegrocl:package", current_package);
+
+  return Language::emit_one(n);
+}
+
+int ALLEGROCL::enumDeclaration(Node *n) {
+
+  if (Getattr(n, "sym:name")) {
+    add_defined_foreign_type(n);
+  }
+  Node *c;
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    ALLEGROCL::enumvalueDeclaration(c);
+    // since we walk our own children, we need to add
+    // the current package ourselves.
+    Setattr(c, "allegrocl:package", current_package);
+  }
+  return SWIG_OK;
+}
+
+
+int ALLEGROCL::enumvalueDeclaration(Node *n) {
+
+  /* print this when in C mode? make this a command-line arg? */
+
+  if (Generate_Wrapper) {
+    String *mangled_name = mangle_name(n, "ACL_ENUM");
+
+    Printf(f_cxx, "EXPORT const %s %s = %s;\n", Getattr(n, "type"), mangled_name, Getattr(n, "value"));
+
+    Delete(mangled_name);
+  }
+
+  return SWIG_OK;
+}
+
+int ALLEGROCL::templateDeclaration(Node *n) {
+
+  String *type = Getattr(n, "templatetype");
+
+  // Printf(stderr, "tempDecl: %s %s\n", Getattr(n,"name"),
+  //        type);
+  // Swig_print_node(n);
+
+  if (!Strcmp(type, "cdecl")) {
+    SwigType *ty = NewStringf("%s%s", Getattr(n, "decl"),
+			      Getattr(n, "type"));
+    Delete(ty);
+  }
+
+  Delete(type);
+
+  return SWIG_OK;
+}
diff --git a/trunk/Source/Modules/allocate.cxx b/trunk/Source/Modules/allocate.cxx
new file mode 100644
index 0000000..e8397e6
--- /dev/null
+++ b/trunk/Source/Modules/allocate.cxx
@@ -0,0 +1,956 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * allocate.cxx
+ *
+ * This module tries to figure out which classes and structures support
+ * default constructors and destructors in C++.   There are several rules that
+ * define this behavior including pure abstract methods, private sections,
+ * and non-default constructors in base classes.  See the ARM or
+ * Doc/Manual/SWIGPlus.html for details.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_allocate_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+
+static int virtual_elimination_mode = 0;	/* set to 0 on default */
+
+/* Set virtual_elimination_mode */
+void Wrapper_virtual_elimination_mode_set(int flag) {
+  virtual_elimination_mode = flag;
+}
+
+/* Helper function to assist with abstract class checking.  
+   This is a major hack. Sorry.  */
+
+extern "C" {
+  static String *search_decl = 0;	/* Declarator being searched */
+  static int check_implemented(Node *n) {
+    String *decl;
+    if (!n)
+       return 0;
+    while (n) {
+      if (Strcmp(nodeType(n), "cdecl") == 0) {
+	decl = Getattr(n, "decl");
+	if (SwigType_isfunction(decl)) {
+	  SwigType *decl1 = SwigType_typedef_resolve_all(decl);
+	  SwigType *decl2 = SwigType_pop_function(decl1);
+	  if (Strcmp(decl2, search_decl) == 0) {
+	    if (!Getattr(n, "abstract")) {
+	      Delete(decl1);
+	      Delete(decl2);
+	      return 1;
+	    }
+	  }
+	  Delete(decl1);
+	  Delete(decl2);
+	}
+      }
+      n = Getattr(n, "csym:nextSibling");
+    }
+    return 0;
+  }
+}
+
+class Allocate:public Dispatcher {
+  Node *inclass;
+  int extendmode;
+
+  /* Checks if a function, n, is the same as any in the base class, ie if the method is polymorphic.
+   * Also checks for methods which will be hidden (ie a base has an identical non-virtual method).
+   * Both methods must have public access for a match to occur. */
+  int function_is_defined_in_bases(Node *n, Node *bases) {
+
+    if (!bases)
+      return 0;
+
+    String *this_decl = Getattr(n, "decl");
+    if (!this_decl)
+       return 0;
+
+    String *name = Getattr(n, "name");
+    String *this_type = Getattr(n, "type");
+    String *resolved_decl = SwigType_typedef_resolve_all(this_decl);
+
+    // Search all base classes for methods with same signature
+    for (int i = 0; i < Len(bases); i++) {
+      Node *b = Getitem(bases, i);
+      Node *base = firstChild(b);
+      while (base) {
+	if (Strcmp(nodeType(base), "extend") == 0) {
+	  // Loop through all the %extend methods
+	  Node *extend = firstChild(base);
+	  while (extend) {
+	    if (function_is_defined_in_bases_seek(n, b, extend, this_decl, name, this_type, resolved_decl)) {
+	      Delete(resolved_decl);
+	      return 1;
+	    }
+	    extend = nextSibling(extend);
+	  }
+	} else if (Strcmp(nodeType(base), "using") == 0) {
+	  // Loop through all the using declaration methods
+	  Node *usingdecl = firstChild(base);
+	  while (usingdecl) {
+	    if (function_is_defined_in_bases_seek(n, b, usingdecl, this_decl, name, this_type, resolved_decl)) {
+	      Delete(resolved_decl);
+	      return 1;
+	    }
+	    usingdecl = nextSibling(usingdecl);
+	  }
+	} else {
+	  // normal methods
+	  if (function_is_defined_in_bases_seek(n, b, base, this_decl, name, this_type, resolved_decl)) {
+	    Delete(resolved_decl);
+	    return 1;
+	  }
+	}
+	base = nextSibling(base);
+      }
+    }
+    Delete(resolved_decl);
+    resolved_decl = 0;
+    for (int j = 0; j < Len(bases); j++) {
+      Node *b = Getitem(bases, j);
+      if (function_is_defined_in_bases(n, Getattr(b, "allbases")))
+	return 1;
+    }
+    return 0;
+  }
+
+  /* Helper function for function_is_defined_in_bases */
+  int function_is_defined_in_bases_seek(Node *n, Node *b, Node *base, String *this_decl, String *name, String *this_type, String *resolved_decl) {
+
+    String *base_decl = Getattr(base, "decl");
+    SwigType *base_type = Getattr(base, "type");
+    if (base_decl && base_type) {
+      if (checkAttribute(base, "name", name) && !GetFlag(b, "feature:ignore") /* whole class is ignored */ ) {
+	if (SwigType_isfunction(resolved_decl) && SwigType_isfunction(base_decl)) {
+	  // We have found a method that has the same name as one in a base class
+	  bool covariant_returntype = false;
+	  bool returntype_match = Strcmp(base_type, this_type) == 0 ? true : false;
+	  bool decl_match = Strcmp(base_decl, this_decl) == 0 ? true : false;
+	  if (returntype_match && decl_match) {
+	    // Exact match - we have found a method with identical signature
+	    // No typedef resolution was done, but skipping it speeds things up slightly
+	  } else {
+	    // Either we have:
+	    //  1) matching methods but are one of them uses a different typedef (return type or parameter) to the one in base class' method
+	    //  2) matching polymorphic methods with covariant return type
+	    //  3) a non-matching method (ie an overloaded method of some sort)
+	    //  4) a matching method which is not polymorphic, ie it hides the base class' method
+
+	    // Check if fully resolved return types match (including
+	    // covariant return types)
+	    if (!returntype_match) {
+	      String *this_returntype = function_return_type(n);
+	      String *base_returntype = function_return_type(base);
+	      returntype_match = Strcmp(this_returntype, base_returntype) == 0 ? true : false;
+	      if (!returntype_match) {
+		covariant_returntype = SwigType_issubtype(this_returntype, base_returntype) ? true : false;
+		returntype_match = covariant_returntype;
+	      }
+	      Delete(this_returntype);
+	      Delete(base_returntype);
+	    }
+	    // The return types must match at this point, for the whole method to match
+	    if (returntype_match && !decl_match) {
+	      // Now need to check the parameter list
+	      // First do an inexpensive parameter count
+	      ParmList *this_parms = Getattr(n, "parms");
+	      ParmList *base_parms = Getattr(base, "parms");
+	      if (ParmList_len(this_parms) == ParmList_len(base_parms)) {
+		// Number of parameters are the same, now check that all the parameters match
+		SwigType *base_fn = NewString("");
+		SwigType *this_fn = NewString("");
+		SwigType_add_function(base_fn, base_parms);
+		SwigType_add_function(this_fn, this_parms);
+		base_fn = SwigType_typedef_resolve_all(base_fn);
+		this_fn = SwigType_typedef_resolve_all(this_fn);
+		if (Strcmp(base_fn, this_fn) == 0) {
+		  // Finally check that the qualifiers match
+		  int base_qualifier = SwigType_isqualifier(resolved_decl);
+		  int this_qualifier = SwigType_isqualifier(base_decl);
+		  if (base_qualifier == this_qualifier) {
+		    decl_match = true;
+		  }
+		}
+		Delete(base_fn);
+		Delete(this_fn);
+	      }
+	    }
+	  }
+	  //Printf(stderr,"look %s %s %d %d\n",base_decl, this_decl, returntype_match, decl_match);
+
+	  if (decl_match && returntype_match) {
+	    // Found an identical method in the base class
+	    bool this_wrapping_protected_members = is_member_director(n) ? true : false;	// This should really check for dirprot rather than just being a director method
+	    bool base_wrapping_protected_members = is_member_director(base) ? true : false;	// This should really check for dirprot rather than just being a director method
+	    bool both_have_public_access = is_public(n) && is_public(base);
+	    bool both_have_protected_access = (is_protected(n) && this_wrapping_protected_members) && (is_protected(base) && base_wrapping_protected_members);
+	    bool both_have_private_access = is_private(n) && is_private(base);
+	    if (checkAttribute(base, "storage", "virtual")) {
+	      // Found a polymorphic method.
+	      // Mark the polymorphic method, in case the virtual keyword was not used.
+	      Setattr(n, "storage", "virtual");
+
+	      if (both_have_public_access || both_have_protected_access) {
+		if (!is_non_public_base(inclass, b))
+		  Setattr(n, "override", base);	// Note C# definition of override, ie access must be the same
+	      } else if (!both_have_private_access) {
+		// Different access
+		if (this_wrapping_protected_members || base_wrapping_protected_members)
+		  if (!is_non_public_base(inclass, b))
+		    Setattr(n, "hides", base);	// Note C# definition of hiding, ie hidden if access is different
+	      }
+	      // Try and find the most base's covariant return type
+	      SwigType *most_base_covariant_type = Getattr(base, "covariant");
+	      if (!most_base_covariant_type && covariant_returntype)
+		most_base_covariant_type = function_return_type(base, false);
+
+	      if (!most_base_covariant_type) {
+		// Eliminate the derived virtual method.
+		if (virtual_elimination_mode)
+		  if (both_have_public_access)
+		    if (!is_non_public_base(inclass, b))
+		      if (!Swig_symbol_isoverloaded(n)) {
+			// Don't eliminate if an overloaded method as this hides the method
+			// in the scripting languages: the dispatch function will hide the base method if ignored.
+			SetFlag(n, "feature:ignore");
+		      }
+	      } else {
+		// Some languages need to know about covariant return types
+		Setattr(n, "covariant", most_base_covariant_type);
+	      }
+
+	    } else {
+	      // Found an identical method in the base class, but it is not polymorphic.
+	      if (both_have_public_access || both_have_protected_access)
+		if (!is_non_public_base(inclass, b))
+		  Setattr(n, "hides", base);
+	    }
+	    if (both_have_public_access || both_have_protected_access)
+	      return 1;
+	  }
+	}
+      }
+    }
+    return 0;
+  }
+
+  /* Determines whether the base class, b, is in the list of private
+   * or protected base classes for class n. */
+  bool is_non_public_base(Node *n, Node *b) {
+    bool non_public_base = false;
+    Node *bases = Getattr(n, "privatebases");
+    if (bases) {
+      for (int i = 0; i < Len(bases); i++) {
+	Node *base = Getitem(bases, i);
+	if (base == b)
+	  non_public_base = true;
+      }
+    }
+    bases = Getattr(n, "protectedbases");
+    if (bases) {
+      for (int i = 0; i < Len(bases); i++) {
+	Node *base = Getitem(bases, i);
+	if (base == b)
+	  non_public_base = true;
+      }
+    }
+    return non_public_base;
+  }
+
+  /* Returns the return type for a function. The node n should be a function.
+     If resolve is true the fully returned type is fully resolved.
+     Caller is responsible for deleting returned string. */
+  String *function_return_type(Node *n, bool resolve = true) {
+    String *decl = Getattr(n, "decl");
+    SwigType *type = Getattr(n, "type");
+    String *ty = NewString(type);
+    SwigType_push(ty, decl);
+    if (SwigType_isqualifier(ty))
+      Delete(SwigType_pop(ty));
+    Delete(SwigType_pop_function(ty));
+    if (resolve) {
+      String *unresolved = ty;
+      ty = SwigType_typedef_resolve_all(unresolved);
+      Delete(unresolved);
+    }
+    return ty;
+  }
+
+  /* Checks if a class member is the same as inherited from the class bases */
+  int class_member_is_defined_in_bases(Node *member, Node *classnode) {
+    Node *bases;		/* bases is the closest ancestors of classnode */
+    int defined = 0;
+
+    bases = Getattr(classnode, "allbases");
+    if (!bases)
+      return 0;
+
+    {
+      int old_mode = virtual_elimination_mode;
+      if (is_member_director(classnode, member))
+	virtual_elimination_mode = 0;
+
+      if (function_is_defined_in_bases(member, bases)) {
+	defined = 1;
+      }
+
+      virtual_elimination_mode = old_mode;
+    }
+
+    if (defined)
+      return 1;
+    else
+      return 0;
+  }
+
+  /* Checks to see if a class is abstract through inheritance,
+     and saves the first node that seems to be abstract.
+   */
+  int is_abstract_inherit(Node *n, Node *base = 0, int first = 0) {
+    if (!first && (base == n))
+      return 0;
+    if (!base) {
+      /* Root node */
+      Symtab *stab = Getattr(n, "symtab");	/* Get symbol table for node */
+      Symtab *oldtab = Swig_symbol_setscope(stab);
+      int ret = is_abstract_inherit(n, n, 1);
+      Swig_symbol_setscope(oldtab);
+      return ret;
+    }
+    List *abstract = Getattr(base, "abstract");
+    if (abstract) {
+      int dabstract = 0;
+      int len = Len(abstract);
+      for (int i = 0; i < len; i++) {
+	Node *nn = Getitem(abstract, i);
+	String *name = Getattr(nn, "name");
+	if (!name)
+	  continue;
+	String *base_decl = Getattr(nn, "decl");
+	if (base_decl)
+	  base_decl = SwigType_typedef_resolve_all(base_decl);
+	if (Strchr(name, '~'))
+	  continue;		/* Don't care about destructors */
+
+	if (SwigType_isfunction(base_decl)) {
+	  search_decl = SwigType_pop_function(base_decl);
+	}
+	Node *dn = Swig_symbol_clookup_local_check(name, 0, check_implemented);
+	Delete(search_decl);
+	Delete(base_decl);
+
+	if (!dn) {
+	  List *nabstract = Getattr(n, "abstract");
+	  if (!nabstract) {
+	    nabstract = NewList();
+	    Setattr(n, "abstract", nabstract);
+	    Delete(nabstract);
+	  }
+	  Append(nabstract, nn);
+	  if (!Getattr(n, "abstract:firstnode")) {
+	    Setattr(n, "abstract:firstnode", nn);
+	  }
+	  dabstract = base != n;
+	}
+      }
+      if (dabstract)
+	return 1;
+    }
+    List *bases = Getattr(base, "allbases");
+    if (!bases)
+      return 0;
+    for (int i = 0; i < Len(bases); i++) {
+      if (is_abstract_inherit(n, Getitem(bases, i))) {
+	return 1;
+      }
+    }
+    return 0;
+  }
+
+
+  /* Grab methods used by smart pointers */
+
+  List *smart_pointer_methods(Node *cls, List *methods, int isconst, String *classname = 0) {
+    if (!methods) {
+      methods = NewList();
+    }
+
+    Node *c = firstChild(cls);
+    String *kind = Getattr(cls, "kind");
+    int mode = PUBLIC;
+    if (kind && (Strcmp(kind, "class") == 0))
+      mode = PRIVATE;
+
+    while (c) {
+      if (Getattr(c, "error") || GetFlag(c, "feature:ignore")) {
+	c = nextSibling(c);
+	continue;
+      }
+      if (!isconst && (Strcmp(nodeType(c), "extend") == 0)) {
+	methods = smart_pointer_methods(c, methods, isconst, Getattr(cls, "name"));
+      } else if (Strcmp(nodeType(c), "cdecl") == 0) {
+	if (!GetFlag(c, "feature:ignore")) {
+	  String *storage = Getattr(c, "storage");
+	  if (!((Cmp(storage, "typedef") == 0))
+	      && !((Cmp(storage, "friend") == 0))) {
+	    String *name = Getattr(c, "name");
+	    String *symname = Getattr(c, "sym:name");
+	    Node *e = Swig_symbol_clookup_local(name, 0);
+	    if (e && is_public(e) && !GetFlag(e, "feature:ignore") && (Cmp(symname, Getattr(e, "sym:name")) == 0)) {
+	      Swig_warning(WARN_LANG_DEREF_SHADOW, Getfile(e), Getline(e), "Declaration of '%s' shadows declaration accessible via operator->(),\n", name);
+	      Swig_warning(WARN_LANG_DEREF_SHADOW, Getfile(c), Getline(c), "previous declaration of '%s'.\n", name);
+	    } else {
+	      /* Make sure node with same name doesn't already exist */
+	      int k;
+	      int match = 0;
+	      for (k = 0; k < Len(methods); k++) {
+		e = Getitem(methods, k);
+		if (Cmp(symname, Getattr(e, "sym:name")) == 0) {
+		  match = 1;
+		  break;
+		}
+		if ((!symname || (!Getattr(e, "sym:name"))) && (Cmp(name, Getattr(e, "name")) == 0)) {
+		  match = 1;
+		  break;
+		}
+	      }
+	      if (!match) {
+		Node *cc = c;
+		while (cc) {
+		  Node *cp = cc;
+		  if (classname) {
+		    Setattr(cp, "classname", classname);
+		  }
+		  Setattr(cp, "allocate:smartpointeraccess", "1");
+		  /* If constant, we have to be careful */
+		  if (isconst) {
+		    SwigType *decl = Getattr(cp, "decl");
+		    if (decl) {
+		      if (SwigType_isfunction(decl)) {	/* If method, we only add if it's a const method */
+			if (SwigType_isconst(decl)) {
+			  Append(methods, cp);
+			}
+		      } else {
+			Append(methods, cp);
+		      }
+		    } else {
+		      Append(methods, cp);
+		    }
+		  } else {
+		    Append(methods, cp);
+		  }
+		  cc = Getattr(cc, "sym:nextSibling");
+		}
+	      }
+	    }
+	  }
+	}
+      }
+
+      if (Strcmp(nodeType(c), "access") == 0) {
+	kind = Getattr(c, "kind");
+	if (Strcmp(kind, "public") == 0)
+	  mode = PUBLIC;
+	else
+	  mode = PRIVATE;
+      }
+      c = nextSibling(c);
+    }
+    /* Look for methods in base classes */
+    {
+      Node *bases = Getattr(cls, "bases");
+      int k;
+      for (k = 0; k < Len(bases); k++) {
+	smart_pointer_methods(Getitem(bases, k), methods, isconst);
+      }
+    }
+    /* Remove protected/private members */
+    {
+      for (int i = 0; i < Len(methods);) {
+	Node *n = Getitem(methods, i);
+	if (!is_public(n)) {
+	  Delitem(methods, i);
+	  continue;
+	}
+	i++;
+      }
+    }
+    return methods;
+  }
+
+  void mark_exception_classes(ParmList *p) {
+    while (p) {
+      SwigType *ty = Getattr(p, "type");
+      SwigType *t = SwigType_typedef_resolve_all(ty);
+      if (SwigType_isreference(t) || SwigType_ispointer(t) || SwigType_isarray(t)) {
+	Delete(SwigType_pop(t));
+      }
+      Node *c = Swig_symbol_clookup(t, 0);
+      if (c) {
+	if (!GetFlag(c, "feature:exceptionclass")) {
+	  SetFlag(c, "feature:exceptionclass");
+	}
+      }
+      p = nextSibling(p);
+      Delete(t);
+    }
+  }
+
+
+  void process_exceptions(Node *n) {
+    ParmList *catchlist = 0;
+    /* 
+       the "catchlist" attribute is used to emit the block
+
+       try {$action;} 
+       catch <list of catches>;
+
+       in emit.cxx
+
+       and is either constructued from the "feature:catches" feature
+       or copied from the node "throws" list.
+     */
+    String *scatchlist = Getattr(n, "feature:catches");
+    if (scatchlist) {
+      catchlist = Swig_cparse_parms(scatchlist);
+      if (catchlist) {
+	Setattr(n, "catchlist", catchlist);
+	mark_exception_classes(catchlist);
+	Delete(catchlist);
+      }
+    }
+    ParmList *throws = Getattr(n, "throws");
+    if (throws) {
+      /* if there is no an explicit catchlist, 
+         we catch everything in the throwlist */
+      if (!catchlist) {
+	Setattr(n, "catchlist", throws);
+      }
+      mark_exception_classes(throws);
+    }
+  }
+
+public:
+Allocate():
+  inclass(NULL), extendmode(0) {
+  }
+
+  virtual int top(Node *n) {
+    cplus_mode = PUBLIC;
+    inclass = 0;
+    extendmode = 0;
+    emit_children(n);
+    return SWIG_OK;
+  }
+
+  virtual int importDirective(Node *n) {
+    return emit_children(n);
+  }
+  virtual int includeDirective(Node *n) {
+    return emit_children(n);
+  }
+  virtual int externDeclaration(Node *n) {
+    return emit_children(n);
+  }
+  virtual int namespaceDeclaration(Node *n) {
+    return emit_children(n);
+  }
+  virtual int extendDirective(Node *n) {
+    extendmode = 1;
+    emit_children(n);
+    extendmode = 0;
+    return SWIG_OK;
+  }
+
+  virtual int classDeclaration(Node *n) {
+    Symtab *symtab = Swig_symbol_current();
+    Swig_symbol_setscope(Getattr(n, "symtab"));
+
+    if (!CPlusPlus) {
+      /* Always have default constructors/destructors in C */
+      Setattr(n, "allocate:default_constructor", "1");
+      Setattr(n, "allocate:default_destructor", "1");
+    }
+
+    if (Getattr(n, "allocate:visit"))
+      return SWIG_OK;
+    Setattr(n, "allocate:visit", "1");
+
+    /* Always visit base classes first */
+    {
+      List *bases = Getattr(n, "bases");
+      if (bases) {
+	for (int i = 0; i < Len(bases); i++) {
+	  Node *b = Getitem(bases, i);
+	  classDeclaration(b);
+	}
+      }
+    }
+
+    inclass = n;
+    String *kind = Getattr(n, "kind");
+    if (Strcmp(kind, "class") == 0) {
+      cplus_mode = PRIVATE;
+    } else {
+      cplus_mode = PUBLIC;
+    }
+
+    emit_children(n);
+
+    /* Check if the class is abstract via inheritance.   This might occur if a class didn't have
+       any pure virtual methods of its own, but it didn't implement all of the pure methods in
+       a base class */
+    if (!Getattr(n, "abstract") && is_abstract_inherit(n)) {
+      if (((Getattr(n, "allocate:public_constructor") || (!GetFlag(n, "feature:nodefault") && !Getattr(n, "allocate:has_constructor"))))) {
+	if (!GetFlag(n, "feature:notabstract")) {
+	  Node *na = Getattr(n, "abstract:firstnode");
+	  if (na) {
+	    Swig_warning(WARN_TYPE_ABSTRACT, Getfile(n), Getline(n),
+			 "Class '%s' might be abstract, " "no constructors generated,\n", SwigType_namestr(Getattr(n, "name")));
+	    Swig_warning(WARN_TYPE_ABSTRACT, Getfile(na), Getline(na), "Method %s might not be implemented.\n", Swig_name_decl(na));
+	    if (!Getattr(n, "abstract")) {
+	      List *abstract = NewList();
+	      Append(abstract, na);
+	      Setattr(n, "abstract", abstract);
+	      Delete(abstract);
+	    }
+	  }
+	}
+      }
+    }
+
+    if (!Getattr(n, "allocate:has_constructor")) {
+      /* No constructor is defined.  We need to check a few things */
+      /* If class is abstract.  No default constructor. Sorry */
+      if (Getattr(n, "abstract")) {
+	Delattr(n, "allocate:default_constructor");
+      }
+      if (!Getattr(n, "allocate:default_constructor")) {
+	/* Check base classes */
+	List *bases = Getattr(n, "allbases");
+	int allows_default = 1;
+
+	for (int i = 0; i < Len(bases); i++) {
+	  Node *n = Getitem(bases, i);
+	  /* If base class does not allow default constructor, we don't allow it either */
+	  if (!Getattr(n, "allocate:default_constructor") && (!Getattr(n, "allocate:default_base_constructor"))) {
+	    allows_default = 0;
+	  }
+	}
+	if (allows_default) {
+	  Setattr(n, "allocate:default_constructor", "1");
+	}
+      }
+    }
+    if (!Getattr(n, "allocate:has_copy_constructor")) {
+      if (Getattr(n, "abstract")) {
+	Delattr(n, "allocate:copy_constructor");
+      }
+      if (!Getattr(n, "allocate:copy_constructor")) {
+	/* Check base classes */
+	List *bases = Getattr(n, "allbases");
+	int allows_copy = 1;
+
+	for (int i = 0; i < Len(bases); i++) {
+	  Node *n = Getitem(bases, i);
+	  /* If base class does not allow copy constructor, we don't allow it either */
+	  if (!Getattr(n, "allocate:copy_constructor") && (!Getattr(n, "allocate:copy_base_constructor"))) {
+	    allows_copy = 0;
+	  }
+	}
+	if (allows_copy) {
+	  Setattr(n, "allocate:copy_constructor", "1");
+	}
+      }
+    }
+
+    if (!Getattr(n, "allocate:has_destructor")) {
+      /* No destructor was defined.  We need to check a few things here too */
+      List *bases = Getattr(n, "allbases");
+      int allows_destruct = 1;
+
+      for (int i = 0; i < Len(bases); i++) {
+	Node *n = Getitem(bases, i);
+	/* If base class does not allow default destructor, we don't allow it either */
+	if (!Getattr(n, "allocate:default_destructor") && (!Getattr(n, "allocate:default_base_destructor"))) {
+	  allows_destruct = 0;
+	}
+      }
+      if (allows_destruct) {
+	Setattr(n, "allocate:default_destructor", "1");
+      }
+    }
+
+    if (!Getattr(n, "allocate:has_assign")) {
+      /* No destructor was defined.  We need to check a few things here too */
+      List *bases = Getattr(n, "allbases");
+      int allows_assign = 1;
+
+      for (int i = 0; i < Len(bases); i++) {
+	Node *n = Getitem(bases, i);
+	/* If base class does not allow default destructor, we don't allow it either */
+	if (Getattr(n, "allocate:has_assign")) {
+	  allows_assign = !Getattr(n, "allocate:noassign");
+	}
+      }
+      if (!allows_assign) {
+	Setattr(n, "allocate:noassign", "1");
+      }
+    }
+
+    if (!Getattr(n, "allocate:has_new")) {
+      /* No destructor was defined.  We need to check a few things here too */
+      List *bases = Getattr(n, "allbases");
+      int allows_new = 1;
+
+      for (int i = 0; i < Len(bases); i++) {
+	Node *n = Getitem(bases, i);
+	/* If base class does not allow default destructor, we don't allow it either */
+	if (Getattr(n, "allocate:has_new")) {
+	  allows_new = !Getattr(n, "allocate:nonew");
+	}
+      }
+      if (!allows_new) {
+	Setattr(n, "allocate:nonew", "1");
+      }
+    }
+
+    /* Check if base classes allow smart pointers, but might be hidden */
+    if (!Getattr(n, "allocate:smartpointer")) {
+      Node *sp = Swig_symbol_clookup((char *) "operator ->", 0);
+      if (sp) {
+	/* Look for parent */
+	Node *p = parentNode(sp);
+	if (Strcmp(nodeType(p), "extend") == 0) {
+	  p = parentNode(p);
+	}
+	if (Strcmp(nodeType(p), "class") == 0) {
+	  if (GetFlag(p, "feature:ignore")) {
+	    Setattr(n, "allocate:smartpointer", Getattr(p, "allocate:smartpointer"));
+	  }
+	}
+      }
+    }
+
+    /* Only care about default behavior.  Remove temporary values */
+    Setattr(n, "allocate:visit", "1");
+    inclass = 0;
+    Swig_symbol_setscope(symtab);
+    return SWIG_OK;
+  }
+
+  virtual int accessDeclaration(Node *n) {
+    String *kind = Getattr(n, "kind");
+    if (Cmp(kind, "public") == 0) {
+      cplus_mode = PUBLIC;
+    } else if (Cmp(kind, "private") == 0) {
+      cplus_mode = PRIVATE;
+    } else if (Cmp(kind, "protected") == 0) {
+      cplus_mode = PROTECTED;
+    }
+    return SWIG_OK;
+  }
+
+  virtual int usingDeclaration(Node *n) {
+
+    Node *c = 0;
+    for (c = firstChild(n); c; c = nextSibling(c)) {
+      if (Strcmp(nodeType(c), "cdecl") == 0) {
+	process_exceptions(c);
+
+	if (inclass)
+	  class_member_is_defined_in_bases(c, inclass);
+      }
+    }
+
+    return SWIG_OK;
+  }
+
+  virtual int cDeclaration(Node *n) {
+
+    process_exceptions(n);
+
+    if (inclass) {
+      /* check whether the member node n is defined in class node in class's bases */
+      class_member_is_defined_in_bases(n, inclass);
+
+      /* Check to see if this is a static member or not.  If so, we add an attribute
+         cplus:staticbase that saves the current class */
+
+      if (checkAttribute(n, "storage", "static")) {
+	Setattr(n, "cplus:staticbase", inclass);
+      }
+
+      String *name = Getattr(n, "name");
+      if (cplus_mode != PUBLIC) {
+	if (Strcmp(name, "operator =") == 0) {
+	  /* Look for a private assignment operator */
+	  Setattr(inclass, "allocate:has_assign", "1");
+	  Setattr(inclass, "allocate:noassign", "1");
+	} else if (Strcmp(name, "operator new") == 0) {
+	  /* Look for a private new operator */
+	  Setattr(inclass, "allocate:has_new", "1");
+	  Setattr(inclass, "allocate:nonew", "1");
+	}
+      } else {
+	if (Strcmp(name, "operator =") == 0) {
+	  Setattr(inclass, "allocate:has_assign", "1");
+	} else if (Strcmp(name, "operator new") == 0) {
+	  Setattr(inclass, "allocate:has_new", "1");
+	}
+	/* Look for smart pointer operator */
+	if ((Strcmp(name, "operator ->") == 0) && (!GetFlag(n, "feature:ignore"))) {
+	  /* Look for version with no parameters */
+	  Node *sn = n;
+	  while (sn) {
+	    if (!Getattr(sn, "parms")) {
+	      SwigType *type = SwigType_typedef_resolve_all(Getattr(sn, "type"));
+	      SwigType_push(type, Getattr(sn, "decl"));
+	      Delete(SwigType_pop_function(type));
+	      SwigType *base = SwigType_base(type);
+	      Node *sc = Swig_symbol_clookup(base, 0);
+	      if ((sc) && (Strcmp(nodeType(sc), "class") == 0)) {
+		if (SwigType_check_decl(type, "p.")) {
+		  /* Need to check if type is a const pointer */
+		  int isconst = 0;
+		  Delete(SwigType_pop(type));
+		  if (SwigType_isconst(type)) {
+		    isconst = 1;
+		    Setattr(inclass, "allocate:smartpointerconst", "1");
+		  }
+		  List *methods = smart_pointer_methods(sc, 0, isconst);
+		  Setattr(inclass, "allocate:smartpointer", methods);
+		  Setattr(inclass, "allocate:smartpointerbase", base);
+		} else {
+		  /* Hmmm.  The return value is not a pointer.  If the type is a value
+		     or reference.  We're going to chase it to see if another operator->()
+		     can be found */
+
+		  if ((SwigType_check_decl(type, "")) || (SwigType_check_decl(type, "r."))) {
+		    Node *nn = Swig_symbol_clookup((char *) "operator ->", Getattr(sc, "symtab"));
+		    if (nn) {
+		      Delete(base);
+		      Delete(type);
+		      sn = nn;
+		      continue;
+		    }
+		  }
+		}
+	      }
+	      Delete(base);
+	      Delete(type);
+	      break;
+	    }
+	  }
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+  virtual int constructorDeclaration(Node *n) {
+    if (!inclass)
+      return SWIG_OK;
+    Parm *parms = Getattr(n, "parms");
+
+    process_exceptions(n);
+    if (!extendmode) {
+      if (!ParmList_numrequired(parms)) {
+	/* Class does define a default constructor */
+	/* However, we had better see where it is defined */
+	if (cplus_mode == PUBLIC) {
+	  Setattr(inclass, "allocate:default_constructor", "1");
+	} else if (cplus_mode == PROTECTED) {
+	  Setattr(inclass, "allocate:default_base_constructor", "1");
+	}
+      }
+      /* Class defines some kind of constructor. May or may not be public */
+      Setattr(inclass, "allocate:has_constructor", "1");
+      if (cplus_mode == PUBLIC) {
+	Setattr(inclass, "allocate:public_constructor", "1");
+      }
+    } else {
+      Setattr(inclass, "allocate:has_constructor", "1");
+      Setattr(inclass, "allocate:public_constructor", "1");
+    }
+
+
+    /* See if this is a copy constructor */
+    if (parms && (ParmList_numrequired(parms) == 1)) {
+      /* Look for a few cases. X(const X &), X(X &), X(X *) */
+      int copy_constructor = 0;
+      SwigType *type = Getattr(inclass, "name");
+      String *tn = NewStringf("r.q(const).%s", type);
+      String *cc = SwigType_typedef_resolve_all(tn);
+      SwigType *rt = SwigType_typedef_resolve_all(Getattr(parms, "type"));
+      if (SwigType_istemplate(type)) {
+	String *tmp = Swig_symbol_template_deftype(cc, 0);
+	Delete(cc);
+	cc = tmp;
+	tmp = Swig_symbol_template_deftype(rt, 0);
+	Delete(rt);
+	rt = tmp;
+      }
+      if (Strcmp(cc, rt) == 0) {
+	copy_constructor = 1;
+      } else {
+	Delete(cc);
+	cc = NewStringf("r.%s", Getattr(inclass, "name"));
+	if (Strcmp(cc, Getattr(parms, "type")) == 0) {
+	  copy_constructor = 1;
+	} else {
+	  Delete(cc);
+	  cc = NewStringf("p.%s", Getattr(inclass, "name"));
+	  String *ty = SwigType_strip_qualifiers(Getattr(parms, "type"));
+	  if (Strcmp(cc, ty) == 0) {
+	    copy_constructor = 1;
+	  }
+	  Delete(ty);
+	}
+      }
+      Delete(cc);
+      Delete(rt);
+      Delete(tn);
+
+      if (copy_constructor) {
+	Setattr(n, "copy_constructor", "1");
+	Setattr(inclass, "allocate:has_copy_constructor", "1");
+	if (cplus_mode == PUBLIC) {
+	  Setattr(inclass, "allocate:copy_constructor", "1");
+	} else if (cplus_mode == PROTECTED) {
+	  Setattr(inclass, "allocate:copy_base_constructor", "1");
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+  virtual int destructorDeclaration(Node *n) {
+    (void) n;
+    if (!inclass)
+      return SWIG_OK;
+    if (!extendmode) {
+      Setattr(inclass, "allocate:has_destructor", "1");
+      if (cplus_mode == PUBLIC) {
+	Setattr(inclass, "allocate:default_destructor", "1");
+      } else if (cplus_mode == PROTECTED) {
+	Setattr(inclass, "allocate:default_base_destructor", "1");
+      }
+    }
+    return SWIG_OK;
+  }
+};
+
+void Swig_default_allocators(Node *n) {
+  if (!n)
+    return;
+  Allocate *a = new Allocate;
+  a->top(n);
+  delete a;
+}
diff --git a/trunk/Source/Modules/browser.cxx b/trunk/Source/Modules/browser.cxx
new file mode 100644
index 0000000..b1bc734
--- /dev/null
+++ b/trunk/Source/Modules/browser.cxx
@@ -0,0 +1,413 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * browser.cxx
+ *
+ * A web-base parse tree browser using SWILL.   This is an optional
+ * feature that's normally disabled.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_browser_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#ifdef SWIG_SWILL
+extern "C" {
+#include "swill.h"
+} static FILE *out = 0;
+static Node *view_top = 0;
+
+class Browser:public Dispatcher {
+  void show_checkbox(Node *t, Node *n) {
+    int v = 0;
+    if (Getmeta(n, "visible")) {
+      v = 1;
+    }
+    if (v) {
+      Printf(out, "<a name=\"n%x\"></a>[<a href=\"hide.html?node=0x%x&hn=0x%x#n%x\">-</a>] ", n, t, n, n);
+    } else {
+      Printf(out, "<a name=\"n%x\"></a>[<a href=\"show.html?node=0x%x&hn=0x%x#n%x\">+</a>] ", n, t, n, n);
+    }
+  }
+  void show_attributes(Node *obj) {
+    if (!Getmeta(obj, "visible"))
+      return;
+    String *os = NewString("");
+    String *k;
+    Iterator ki;
+    ki = First(obj);
+    while (ki.key) {
+      k = ki.key;
+      if ((Cmp(k, "nodeType") == 0) || (Cmp(k, "firstChild") == 0) || (Cmp(k, "lastChild") == 0) ||
+	  (Cmp(k, "parentNode") == 0) || (Cmp(k, "nextSibling") == 0) || (Cmp(k, "previousSibling") == 0) || (*(Char(k)) == '$')) {
+	/* Do nothing */
+      } else if (Cmp(k, "parms") == 0) {
+	String *o = NewString("");
+	Printf(o, "%s", ParmList_protostr(Getattr(obj, k)));
+	Replaceall(o, "&", "&amp;");
+	Replaceall(o, "<", "&lt;");
+	Replaceall(o, ">", "&gt;");
+	Printf(os, "<a href=\"data.html?n=0x%x\">?</a> %-12s - %s\n", Getattr(obj, k), k, o);
+	Delete(o);
+      } else {
+	DOH *o;
+	char *trunc = "";
+	if (DohIsString(Getattr(obj, k))) {
+	  o = Str(Getattr(obj, k));
+	  if (Len(o) > 70) {
+	    trunc = "...";
+	  }
+	  Replaceall(o, "&", "&amp;");
+	  Replaceall(o, "<", "&lt;");
+	  Printf(os, "<a href=\"data.html?n=0x%x\">?</a> %-12s - \"%(escape)-0.70s%s\"\n", Getattr(obj, k), k, o, trunc);
+	  Delete(o);
+	} else {
+	  Printf(os, "<a href=\"data.html?n=0x%x\">?</a> %-12s - 0x%x\n", Getattr(obj, k), k, Getattr(obj, k));
+	}
+      }
+      ki = Next(ki);
+    }
+    Printf(out, "<FONT color=\"#660000\"><pre>\n%s</pre></FONT>\n", Char(os));
+    Delete(os);
+  }
+
+public:
+  virtual int emit_one(Node *n) {
+    char *tag = Char(nodeType(n));
+    char *file = Char(Getfile(n));
+    int line = Getline(n);
+    char *name = GetChar(n, "name");
+
+    show_checkbox(view_top, n);
+    Printf(out, "<b><a href=\"index.html?node=0x%x\">%s</a></b>", n, tag);
+    if (name) {
+      Printf(out, " (%s)", name);
+    }
+    Printf(out, ".  %s:%d\n", file, line);
+    Printf(out, "<br>");
+    Dispatcher::emit_one(n);
+    return SWIG_OK;
+  }
+  virtual int emit_children(Node *n) {
+    if (Getmeta(n, "visible")) {
+      Printf(out, "<blockquote>\n");
+      Dispatcher::emit_children(n);
+      Printf(out, "</blockquote>\n");
+    }
+    return SWIG_OK;
+  }
+  virtual int defaultHandler(Node *n) {
+    show_attributes(n);
+    return SWIG_OK;
+  }
+  virtual int top(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+  virtual int includeDirective(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+  virtual int importDirective(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+
+  virtual int extendDirective(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+  virtual int classDeclaration(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+
+  virtual int templateDeclaration(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+
+  virtual int enumDeclaration(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+  virtual int typemapDirective(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+  virtual int namespaceDeclaration(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+  virtual int usingDeclaration(Node *n) {
+    show_attributes(n);
+    emit_children(n);
+    return SWIG_OK;
+  }
+
+};
+
+static int browser_exit = 0;
+static Node *tree_top = 0;
+static Browser *browse = 0;
+
+/* ----------------------------------------------------------------------
+ * exit_handler()      - Force the browser to exit
+ * ---------------------------------------------------------------------- */
+
+void exit_handler(FILE *f) {
+  browser_exit = 1;
+  Printf(f, "Terminated.\n");
+}
+
+/* ----------------------------------------------------------------------
+ * node_handler()      - Generate information about a specific node
+ * ---------------------------------------------------------------------- */
+
+static void display(FILE *f, Node *n) {
+  /* Print standard HTML header */
+
+  Printf(f, "<HTML><HEAD><TITLE>SWIG-%s</TITLE></HEAD><BODY BGCOLOR=\"#ffffff\">\n", Swig_package_version());
+  Printf(f, "<b>SWIG-%s</b><br>\n", Swig_package_version());
+  Printf(f, "[ <a href=\"exit.html\">Exit</a> ]");
+  Printf(f, " [ <a href=\"index.html?node=0x%x\">Top</a> ]", tree_top);
+  if (n != tree_top) {
+    Printf(f, " [ <a href=\"index.html?node=0x%x\">Up</a> ]", parentNode(n));
+  }
+  Printf(f, " [ <a href=\"symbol.html\">Symbols</a> ]");
+  Printf(f, "<br><hr><p>\n");
+
+  out = f;
+
+  browse->emit_one(n);
+
+  /* Print standard footer */
+  Printf(f, "<br><hr></BODY></HTML>\n");
+
+}
+
+void node_handler(FILE *f) {
+  Node *n = 0;
+  if (!swill_getargs("p(node)", &n)) {
+    n = tree_top;
+  }
+  view_top = n;
+  display(f, n);
+}
+
+
+/* ----------------------------------------------------------------------
+ * hide_handler()      - Hide a node 
+ * ---------------------------------------------------------------------- */
+
+void hide_handler(FILE *f) {
+  Node *n = 0;
+  if (!swill_getargs("p(hn)", &n)) {
+    n = 0;
+  }
+  if (n) {
+    Delmeta(n, "visible");
+  }
+  node_handler(f);
+}
+
+void show_handler(FILE *f) {
+  Node *n = 0;
+  if (!swill_getargs("p(hn)", &n)) {
+    n = 0;
+  }
+  if (n) {
+    Setmeta(n, "visible", "1");
+  }
+  node_handler(f);
+}
+
+void raw_data(FILE *out, Node *obj) {
+  if (!obj)
+    return;
+  if (DohIsMapping(obj)) {
+    String *k;
+    Iterator ki;
+    String *os = NewString("");
+    Printf(os, "Hash {\n");
+    ki = First(obj);
+    while (ki.key) {
+      k = ki.key;
+      DOH *o;
+      const char *trunc = "";
+      if (DohIsString(Getattr(obj, k))) {
+	o = Str(Getattr(obj, k));
+	if (Len(o) > 70) {
+	  trunc = "...";
+	}
+	Replaceall(o, "<", "&lt;");
+	Printf(os, "    <a href=\"data.html?n=0x%x\">?</a> %-12s - \"%(escape)-0.70s%s\"\n", Getattr(obj, k), k, o, trunc);
+	Delete(o);
+      } else {
+	Printf(os, "    <a href=\"data.html?n=0x%x\">?</a> %-12s - 0x%x\n", Getattr(obj, k), k, Getattr(obj, k));
+      }
+      ki = Next(ki);
+    }
+    Printf(os, "}\n");
+    Printf(out, "<FONT color=\"#660000\"><pre>\n%s</pre></FONT>\n", Char(os));
+    Delete(os);
+  } else if (DohIsString(obj)) {
+    String *o = Str(obj);
+    Replaceall(o, "<", "&lt;");
+    Printf(out, "<FONT color=\"#660000\"><pre>\n%s</pre></FONT>\n", Char(o));
+    Delete(o);
+  } else if (DohIsSequence(obj)) {
+    int i;
+    String *os = NewString("");
+    Printf(os, "List [\n");
+    for (i = 0; i < Len(obj); i++) {
+      DOH *o = Getitem(obj, i);
+      const char *trunc = "";
+      if (DohIsString(o)) {
+	String *s = Str(o);
+	if (Len(s) > 70) {
+	  trunc = "...";
+	}
+	Replaceall(o, "<", "&lt;");
+	Printf(os, "    <a href=\"data.html?n=0x%x\">?</a> [%d] - \"%(escape)-0.70s%s\"\n", o, i, s, trunc);
+	Delete(s);
+      } else {
+	Printf(os, "    <a href=\"data.html?n=0x%x\">?</a> [%d] - 0x%x\n", o, i, o);
+      }
+    }
+    Printf(os, "\n]\n");
+    Printf(out, "<FONT color=\"#660000\"><pre>\n%s</pre></FONT>\n", Char(os));
+    Delete(os);
+  }
+}
+
+void data_handler(FILE *f) {
+  DOH *n = 0;
+  if (!swill_getargs("p(n)", &n)) {
+    n = 0;
+  }
+  Printf(f, "<HTML><HEAD><TITLE>SWIG-%s</TITLE></HEAD><BODY BGCOLOR=\"#ffffff\">\n", Swig_package_version());
+  Printf(f, "<b>SWIG-%s</b><br>\n", Swig_package_version());
+  Printf(f, "[ <a href=\"exit.html\">Exit</a> ]");
+  Printf(f, " [ <a href=\"index.html?node=0x%x\">Top</a> ]", tree_top);
+  Printf(f, "<br><hr><p>\n");
+  if (n) {
+    raw_data(f, n);
+  }
+  /* Print standard footer */
+  Printf(f, "<br><hr></BODY></HTML>\n");
+}
+
+void symbol_handler(FILE *f) {
+  Symtab *sym;
+  char *name = 0;
+
+  Printf(f, "<HTML><HEAD><TITLE>SWIG-%s</TITLE></HEAD><BODY BGCOLOR=\"#ffffff\">\n", Swig_package_version());
+  Printf(f, "<b>SWIG-%s</b><br>\n", Swig_package_version());
+  Printf(f, "[ <a href=\"exit.html\">Exit</a> ]");
+  Printf(f, " [ <a href=\"index.html?node=0x%x\">Top</a> ]", tree_top);
+  Printf(f, " [ <a href=\"symbol.html\">Symbols</a> ]");
+  Printf(f, "<br><hr><p>\n");
+
+  if (!swill_getargs("p(sym)|s(name)", &sym, &name)) {
+    sym = Swig_symbol_getscope("");
+    name = 0;
+  }
+  if (!sym) {
+    Printf(f, "No symbol table specified!\n");
+    return;
+  }
+  {
+    String *q = Swig_symbol_qualifiedscopename(sym);
+    if (!Len(q)) {
+      Printf(f, "<b>Symbol table: :: (global)</b><br>\n");
+    } else {
+      Printf(f, "<b>Symbol table: %s</b><br>\n", q);
+    }
+    Delete(q);
+  }
+
+  fprintf(f, "<p><form action=\"symbol.html\" method=GET>\n");
+  fprintf(f, "Symbol lookup: <input type=text name=name size=40></input><br>\n");
+  fprintf(f, "<input type=hidden name=sym value=\"0x%x\">\n", sym);
+  fprintf(f, "Submit : <input type=submit></input>\n");
+  fprintf(f, "</form>");
+
+  if (name) {
+    Node *n = Swig_symbol_clookup(name, sym);
+    Printf(f, "Symbol '%s':\n", name);
+    Printf(f, "<blockquote>\n");
+    if (!n) {
+      Printf(f, "Not defined!\n");
+    } else {
+      raw_data(f, n);
+    }
+    Printf(f, "</blockquote>\n");
+  }
+
+  Printf(f, "<p><b>Nested scopes</b><br>\n");
+  Printf(f, "<blockquote><pre>\n");
+  {
+    Hash *h;
+    h = firstChild(sym);
+    while (h) {
+      Printf(f, "<a href=\"symbol.html?sym=0x%x\">%s</a>\n", h, Getattr(h, "name"));
+      h = nextSibling(h);
+    }
+  }
+  Printf(f, "</pre></blockquote>\n");
+
+  Printf(f, "<p><b>Symbol table contents</b></br>\n");
+  raw_data(f, Getattr(sym, "symtab"));
+  Printf(f, "<br><hr></BODY></HTML>\n");
+
+}
+#endif
+
+void Swig_browser(Node *top, int port) {
+#ifdef SWIG_SWILL
+  int sport;
+  browser_exit = 0;
+
+  /* Initialize the server */
+  sport = swill_init(port);
+  if (sport < 0) {
+    Printf(stderr, "Couldn't open socket on port %d. Sorry.\n", port);
+    return;
+  }
+  browse = new Browser();
+  Setmeta(top, "visible", "1");
+  tree_top = top;
+
+  Printf(stderr, "SWIG: Tree browser listening on port %d\n", sport);
+
+  swill_handle("exit.html", exit_handler, 0);
+  swill_handle("index.html", node_handler, 0);
+  swill_handle("hide.html", hide_handler, 0);
+  swill_handle("show.html", show_handler, 0);
+  swill_handle("data.html", data_handler, 0);
+  swill_handle("symbol.html", symbol_handler, 0);
+  swill_netscape("index.html");
+
+  while (!browser_exit) {
+    swill_serve();
+  }
+  Printf(stderr, "Browser terminated.\n");
+  swill_close();
+  delete browse;
+  return;
+#else
+  (void) top;
+  (void) port;
+#endif
+}
diff --git a/trunk/Source/Modules/cffi.cxx b/trunk/Source/Modules/cffi.cxx
new file mode 100644
index 0000000..736564d
--- /dev/null
+++ b/trunk/Source/Modules/cffi.cxx
@@ -0,0 +1,1065 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cffi.cxx
+ *
+ * cffi language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_cffi_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+#include <ctype.h>
+
+//#define CFFI_DEBUG
+//#define CFFI_WRAP_DEBUG
+
+class CFFI:public Language {
+public:
+  String *f_cl;
+  String *f_clhead;
+  String *f_clwrap;
+  bool CWrap;     // generate wrapper file for C code?  
+  File *f_cxx;
+  File *f_cxx_header;
+  File *f_cxx_wrapper;
+  File *f_clos;
+
+  String *module;
+  virtual void main(int argc, char *argv[]);
+  virtual int top(Node *n);
+  virtual int functionWrapper(Node *n);
+  virtual int variableWrapper(Node *n);
+  virtual int constantWrapper(Node *n);
+  //  virtual int classDeclaration(Node *n);
+  virtual int enumDeclaration(Node *n);
+  virtual int typedefHandler(Node *n);
+
+  //c++ specific code
+  virtual int constructorHandler(Node *n);
+  virtual int destructorHandler(Node *n);
+  virtual int memberfunctionHandler(Node *n);
+  virtual int membervariableHandler(Node *n);
+  virtual int classHandler(Node *n);
+
+private:
+  void emit_defun(Node *n, String *name);
+  void emit_defmethod(Node *n);
+  void emit_initialize_instance(Node *n);
+  void emit_getter(Node *n);
+  void emit_setter(Node *n);
+  void emit_class(Node *n);
+  void emit_struct_union(Node *n, bool un);
+  void emit_export(Node *n, String *name);
+  void emit_inline(Node *n, String *name);
+  String *lispy_name(char *name);
+  String *lispify_name(Node *n, String *ty, const char *flag, bool kw = false);
+  String *convert_literal(String *num_param, String *type, bool try_to_split = true);
+  String *infix_to_prefix(String *val, char split_op, const String *op, String *type);
+  String *strip_parens(String *string);
+  String *trim(String *string);
+  int generate_typedef_flag;
+  bool no_swig_lisp;
+};
+
+void CFFI::main(int argc, char *argv[]) {
+  int i;
+
+  SWIG_library_directory("cffi");
+  SWIG_config_file("cffi.swg");
+  generate_typedef_flag = 0;
+  no_swig_lisp = false;
+  CWrap = false;
+  for (i = 1; i < argc; i++) {
+    if (!Strcmp(argv[i], "-help")) {
+      Printf(stdout, "cffi Options (available with -cffi)\n");
+      Printf(stdout,
+       "   -generate-typedef\n"
+       "\tIf this option is given then defctype will be used to generate\n"
+       "\tshortcuts according to the typedefs in the input.\n"
+       "   -[no]cwrap\n"
+       "\tTurn on or turn off generation of an intermediate C file when\n"
+       "\tcreating a C interface. By default this is only done for C++ code.\n"
+       "   -[no]swig-lisp\n"
+       "\tTurns on or off generation of code for helper lisp macro, functions,\n"
+       "\tetc. which SWIG uses while generating wrappers. These macros, functions\n" "\tmay still be used by generated wrapper code.\n");
+    } else if (!strcmp(argv[i], "-cwrap")) {
+      CWrap = true;
+      Swig_mark_arg(i);
+    } else if ((Strcmp(argv[i], "-generate-typedef") == 0)) {
+      generate_typedef_flag = 1;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-nocwrap")) {
+      CWrap = false;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-swig-lisp")) {
+      no_swig_lisp = false;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-noswig-lisp")) {
+      no_swig_lisp = true;
+      Swig_mark_arg(i);
+    }
+
+  }
+  f_clhead = NewString("");
+  f_clwrap = NewString("");
+  f_cl = NewString("");
+
+  allow_overloading();
+}
+
+int CFFI::top(Node *n) {
+  File *f_null = NewString("");
+  module = Getattr(n, "name");
+
+  String *cxx_filename = Getattr(n, "outfile");
+  String *lisp_filename = NewString("");
+
+  Printf(lisp_filename, "%s%s.lisp", SWIG_output_directory(), module);
+
+  File *f_lisp = NewFile(lisp_filename, "w");
+  NewFile(lisp_filename, "w");
+  if (!f_lisp) {
+    FileErrorDisplay(lisp_filename);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  if (CPlusPlus || CWrap) {
+    f_cxx = NewFile(cxx_filename, "w");
+    if (!f_cxx) {
+      Close(f_lisp);
+      Delete(f_lisp);
+      Printf(stderr, "Unable to open %s for writing\n", cxx_filename);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    String *clos_filename = NewString("");
+    Printf(clos_filename, "%s%s-clos.lisp", SWIG_output_directory(), module);
+    f_clos = NewFile(clos_filename, "w");
+    if (!f_clos) {
+      Close(f_lisp);
+      Delete(f_lisp);
+      Printf(stderr, "Unable to open %s for writing\n", cxx_filename);
+      SWIG_exit(EXIT_FAILURE);
+    }
+  } else {
+    f_cxx = NewString("");
+    f_clos = NewString("");
+  }
+
+  f_cxx_header = f_cxx;
+  f_cxx_wrapper = NewString("");
+
+  Swig_register_filebyname("header", f_cxx_header);
+  Swig_register_filebyname("wrapper", f_cxx_wrapper);
+  Swig_register_filebyname("runtime", f_cxx);
+  Swig_register_filebyname("lisphead", f_clhead);
+  if (!no_swig_lisp)
+    Swig_register_filebyname("swiglisp", f_cl);
+  else
+    Swig_register_filebyname("swiglisp", f_null);
+
+  Language::top(n);
+  Printf(f_lisp, "%s\n", f_clhead);
+  Printf(f_lisp, "%s\n", f_cl);
+  Printf(f_lisp, "%s\n", f_clwrap);
+
+  Close(f_lisp);
+  Delete(f_lisp);   // Deletes the handle, not the file
+  Delete(f_cl);
+  Delete(f_clhead);
+  Delete(f_clwrap);
+  Close(f_cxx);
+  Delete(f_cxx);
+  Delete(f_cxx_wrapper);
+  Delete(f_null);
+
+  return SWIG_OK;
+}
+
+int CFFI::classHandler(Node *n) {
+#ifdef CFFI_DEBUG
+  Printf(stderr, "class %s::%s\n", "some namespace",  //current_namespace,
+   Getattr(n, "sym:name"));
+#endif
+  String *name = Getattr(n, "sym:name");
+  String *kind = Getattr(n, "kind");
+
+  // maybe just remove this check and get rid of the else clause below.
+  if (Strcmp(kind, "struct") == 0) {
+    emit_struct_union(n, false);
+    return SWIG_OK;
+  } else if (Strcmp(kind, "union") == 0) {
+    emit_struct_union(n, true);
+    return SWIG_OK;
+  } else if (Strcmp(kind, "class") == 0) {
+    emit_class(n);
+    Language::classHandler(n);
+  } else {
+    Printf(stderr, "Don't know how to deal with %s kind of class yet.\n", kind);
+    Printf(stderr, " (name: %s)\n", name);
+    SWIG_exit(EXIT_FAILURE);
+    return SWIG_OK;
+  }
+
+  return SWIG_OK;
+}
+
+int CFFI::constructorHandler(Node *n) {
+#ifdef CFFI_DEBUG
+  Printf(stderr, "constructor %s\n", Getattr(n, "name"));
+  Printf(stderr, "constructor %s\n and %s and %s", Getattr(n, "kind"), Getattr(n, "sym:name"), Getattr(n, "allegrocl:old-sym:name"));
+#endif
+  Setattr(n, "cffi:constructorfunction", "1");
+  // Let SWIG generate a global forwarding function.
+  return Language::constructorHandler(n);
+}
+
+int CFFI::destructorHandler(Node *n) {
+#ifdef CFFI_DEBUG
+  Printf(stderr, "destructor %s\n", Getattr(n, "name"));
+#endif
+
+  // Let SWIG generate a global forwarding function.
+  return Language::destructorHandler(n);
+}
+
+void CFFI::emit_defmethod(Node *n) {
+  String *args_placeholder = NewStringf("");
+  String *args_call = NewStringf("");
+
+  ParmList *pl = Getattr(n, "parms");
+  int argnum = 0;
+  Node *parent = parentNode(n);
+  bool first = 0;
+  
+  for (Parm *p = pl; p; p = nextSibling(p), argnum++) {
+    String *argname = Getattr(p, "name");
+    String *ffitype = Swig_typemap_lookup("lispclass", p, "", 0);
+
+    int tempargname = 0;
+
+    if(!first)
+      first = true;
+    else
+      Printf(args_placeholder, " ");
+      
+    if (!argname) {
+      argname = NewStringf("arg%d", argnum);
+      tempargname = 1;
+    } else if (Strcmp(argname, "t") == 0 || Strcmp(argname, "T") == 0) {
+      argname = NewStringf("t-arg%d", argnum);
+      tempargname = 1;
+    }
+    if (Len(ffitype) > 0)
+      Printf(args_placeholder, "(%s %s)", argname, ffitype);
+    else
+      Printf(args_placeholder, "%s", argname);
+
+    if (ffitype && Strcmp(ffitype, lispify_name(parent, lispy_name(Char(Getattr(parent, "sym:name"))), "'classname")) == 0)
+      Printf(args_call, " (ff-pointer %s)", argname);
+    else
+      Printf(args_call, " %s", argname);
+
+    Delete(ffitype);
+
+    if (tempargname)
+      Delete(argname);
+  }
+
+  String *method_name = Getattr(n, "name");
+  int x = Replace(method_name, "operator ", "", DOH_REPLACE_FIRST); //  
+
+  if (x == 1)
+    Printf(f_clos, "(cl:shadow \"%s\")\n", method_name);
+
+  Printf(f_clos, "(cl:defmethod %s (%s)\n  (%s%s))\n\n",
+         lispify_name(n, lispy_name(Char(method_name)), "'method"), args_placeholder,
+         lispify_name(n, Getattr(n, "sym:name"), "'function"), args_call);
+
+}
+
+void CFFI::emit_initialize_instance(Node *n) {
+  String *args_placeholder = NewStringf("");
+  String *args_call = NewStringf("");
+
+  ParmList *pl = Getattr(n, "parms");
+  int argnum = 0;
+  Node *parent = parentNode(n);
+
+  for (Parm *p = pl; p; p = nextSibling(p), argnum++) {
+    String *argname = Getattr(p, "name");
+    String *ffitype = Swig_typemap_lookup("lispclass", p, "", 0);
+
+    int tempargname = 0;
+    if (!argname) {
+      argname = NewStringf("arg%d", argnum);
+      tempargname = 1;
+    } else if (Strcmp(argname, "t") == 0 || Strcmp(argname, "T") == 0) {
+      argname = NewStringf("t-arg%d", argnum);
+      tempargname = 1;
+    }
+    if (Len(ffitype) > 0)
+      Printf(args_placeholder, " (%s %s)", argname, ffitype);
+    else
+      Printf(args_placeholder, " %s", argname);
+
+    if (Strcmp(ffitype, lispify_name(parent, lispy_name(Char(Getattr(parent, "sym:name"))), "'classname")) == 0)
+      Printf(args_call, " (ff-pointer %s)", argname);
+    else
+      Printf(args_call, " %s", argname);
+
+    Delete(ffitype);
+
+    if (tempargname)
+      Delete(argname);
+  }
+
+  Printf(f_clos, "(cl:defmethod initialize-instance :after ((obj %s) &key%s)\n  (setf (slot-value obj 'ff-pointer) (%s%s)))\n\n",
+         lispify_name(parent, lispy_name(Char(Getattr(parent, "sym:name"))), "'class"), args_placeholder,
+         lispify_name(n, Getattr(n, "sym:name"), "'function"), args_call);
+
+}
+
+void CFFI::emit_setter(Node *n) {
+  Node *p = parentNode(n);
+  Printf(f_clos, "(cl:defmethod (cl:setf %s) (arg0 (obj %s))\n  (%s (ff-pointer obj) arg0))\n\n",
+         lispify_name(n, Getattr(n, "name"), "'method"),
+         lispify_name(p, lispy_name(Char(Getattr(p, "sym:name"))), "'class"), lispify_name(n, Getattr(n, "sym:name"), "'function"));
+}
+
+
+void CFFI::emit_getter(Node *n) {
+  Node *p = parentNode(n);
+  Printf(f_clos, "(cl:defmethod %s ((obj %s))\n  (%s (ff-pointer obj)))\n\n",
+         lispify_name(n, Getattr(n, "name"), "'method"),
+         lispify_name(p, lispy_name(Char(Getattr(p, "sym:name"))), "'class"), lispify_name(n, Getattr(n, "sym:name"), "'function"));
+}
+
+int CFFI::memberfunctionHandler(Node *n) {
+  // Let SWIG generate a global forwarding function.
+  Setattr(n, "cffi:memberfunction", "1");
+  return Language::memberfunctionHandler(n);
+}
+
+int CFFI::membervariableHandler(Node *n) {
+  // Let SWIG generate a get/set function pair.
+  Setattr(n, "cffi:membervariable", "1");
+  return Language::membervariableHandler(n);
+}
+
+int CFFI::functionWrapper(Node *n) {
+
+  ParmList *parms = Getattr(n, "parms");
+  String *iname = Getattr(n, "sym:name");
+  Wrapper *f = NewWrapper();
+
+  String *raw_return_type = Swig_typemap_lookup("ctype", n, "", 0);
+  SwigType *return_type = Swig_cparse_type(raw_return_type);
+  SwigType *resolved = SwigType_typedef_resolve_all(return_type);
+  int is_void_return = (Cmp(resolved, "void") == 0);
+  Delete(resolved);
+
+  if (!is_void_return) {
+    String *lresult_init = NewStringf("lresult = (%s)0", raw_return_type);
+    Wrapper_add_localv(f, "lresult", raw_return_type, lresult_init, NIL);
+    Delete(lresult_init);
+  }
+
+  String *overname = 0;
+  if (Getattr(n, "sym:overloaded")) {
+    overname = Getattr(n, "sym:overname");
+  } else {
+    if (!addSymbol(iname, n)) {
+      DelWrapper(f);
+      return SWIG_ERROR;
+    }
+  }
+
+  String *wname = Swig_name_wrapper(iname);
+  if (overname) {
+    Append(wname, overname);
+  }
+  Setattr(n, "wrap:name", wname);
+
+  // Emit all of the local variables for holding arguments.
+  emit_parameter_variables(parms, f);
+
+  // Attach the standard typemaps 
+  Swig_typemap_attach_parms("ctype", parms, f);
+  emit_attach_parmmaps(parms, f);
+
+  int num_arguments = emit_num_arguments(parms);
+  String *name_and_parms = NewStringf("%s (", wname);
+  int i;
+  Parm *p;
+  int gencomma = 0;
+
+#ifdef CFFI_DEBUG
+  Printf(stderr, "function  -  %s - %d\n", Getattr(n, "name"), num_arguments);
+#endif
+
+  for (i = 0, p = parms; i < num_arguments; i++) {
+
+    while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    SwigType *c_parm_type = Swig_cparse_type(Getattr(p, "tmap:ctype"));
+    String *arg = NewStringf("l%s", Getattr(p, "lname"));
+
+    // Emit parameter declaration
+    if (gencomma)
+      Printf(name_and_parms, ", ");
+    String *parm_decl = SwigType_str(c_parm_type, arg);
+    Printf(name_and_parms, "%s", parm_decl);
+#ifdef CFFI_DEBUG
+    Printf(stderr, "  param: %s\n", parm_decl);
+#endif
+    Delete(parm_decl);
+    gencomma = 1;
+
+    // Emit parameter conversion code
+    String *parm_code = Getattr(p, "tmap:in");
+    {
+      Replaceall(parm_code, "$input", arg);
+      Setattr(p, "emit:input", arg);
+      Printf(f->code, "%s\n", parm_code);
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    Delete(arg);
+  }
+  Printf(name_and_parms, ")");
+
+  // Emit the function definition
+  String *signature = SwigType_str(return_type, name_and_parms);
+  Printf(f->def, "EXPORT %s {", signature);
+  Printf(f->code, "  try {\n");
+
+  String *actioncode = emit_action(n);
+
+  String *result_convert = Swig_typemap_lookup_out("out", n, "result", f, actioncode);
+  Replaceall(result_convert, "$result", "lresult");
+  Printf(f->code, "%s\n", result_convert);
+  if(!is_void_return) Printf(f->code, "    return lresult;\n");
+  Delete(result_convert);
+  emit_return_variable(n, Getattr(n, "type"), f);
+
+  Printf(f->code, "  } catch (...) {\n");
+  if (!is_void_return)
+    Printf(f->code, "    return (%s)0;\n", raw_return_type);
+  Printf(f->code, "  }\n");
+  Printf(f->code, "}\n");
+
+  if (CPlusPlus)
+    Wrapper_print(f, f_cxx);
+
+  if (CPlusPlus) {
+    emit_defun(n, wname);
+    if (Getattr(n, "cffi:memberfunction"))
+      emit_defmethod(n);
+    else if (Getattr(n, "cffi:membervariable")) {
+      if (Getattr(n, "memberget"))
+        emit_getter(n);
+      else if (Getattr(n, "memberset"))
+        emit_setter(n);
+    }
+    else if (Getattr(n, "cffi:constructorfunction")) {
+      emit_initialize_instance(n);
+    }
+  } else
+    emit_defun(n, iname);
+
+  //   if (!overloaded || !Getattr(n, "sym:nextSibling")) {
+  //     update_package_if_needed(n);
+  //     emit_buffered_defuns(n);
+  //     // this is the last overload.
+  //     if (overloaded) {
+  //       emit_dispatch_defun(n);
+  //     }
+  //   }
+
+  Delete(wname);
+  DelWrapper(f);
+
+  return SWIG_OK;
+}
+
+
+void CFFI::emit_defun(Node *n, String *name) {
+
+  //   String *storage=Getattr(n,"storage");
+  //   if(!storage || (Strcmp(storage,"extern") && Strcmp(storage,"externc")))
+  //     return SWIG_OK;
+
+  String *func_name = Getattr(n, "sym:name");
+
+  ParmList *pl = Getattr(n, "parms");
+
+  int argnum = 0;
+
+  func_name = lispify_name(n, func_name, "'function");
+
+  emit_inline(n, func_name);
+
+  Printf(f_cl, "\n(cffi:defcfun (\"%s\" %s)", name, func_name);
+  String *ffitype = Swig_typemap_lookup("cout", n, ":pointer", 0);
+
+  Printf(f_cl, " %s", ffitype);
+  Delete(ffitype);
+
+  for (Parm *p = pl; p; p = nextSibling(p), argnum++) {
+
+    if (SwigType_isvarargs(Getattr(p, "type"))) {
+      Printf(f_cl, "\n  %s", NewString("&rest"));
+      continue;
+    }
+
+    String *argname = Getattr(p, "name");
+
+    ffitype = Swig_typemap_lookup("cin", p, "", 0);
+
+    int tempargname = 0;
+    if (!argname) {
+
+      argname = NewStringf("arg%d", argnum);
+      tempargname = 1;
+    } else if (Strcmp(argname, "t") == 0 || Strcmp(argname, "T") == 0) {
+      argname = NewStringf("t_arg%d", argnum);
+      tempargname = 1;
+    }
+
+    Printf(f_cl, "\n  (%s %s)", argname, ffitype);
+
+    Delete(ffitype);
+
+    if (tempargname)
+      Delete(argname);
+  }
+  Printf(f_cl, ")\n");    /* finish arg list */
+
+  emit_export(n, func_name);
+}
+
+
+int CFFI::constantWrapper(Node *n) {
+  String *type = Getattr(n, "type");
+  String *converted_value = convert_literal(Getattr(n, "value"), type);
+  String *name = lispify_name(n, Getattr(n, "sym:name"), "'constant");
+
+  if (Strcmp(name, "t") == 0 || Strcmp(name, "T") == 0)
+    name = NewStringf("t_var");
+
+  Printf(f_cl, "\n(cl:defconstant %s %s)\n", name, converted_value);
+  Delete(converted_value);
+
+  emit_export(n, name);
+  return SWIG_OK;
+}
+
+int CFFI::variableWrapper(Node *n) {
+  //  String *storage=Getattr(n,"storage");
+  //  Printf(stdout,"\"%s\" %s)\n",storage,Getattr(n, "sym:name"));
+
+  //  if(!storage || (Strcmp(storage,"extern") && Strcmp(storage,"externc")))
+  //    return SWIG_OK;
+
+  String *var_name = Getattr(n, "sym:name");
+  String *lisp_type = Swig_typemap_lookup("cin", n, "", 0);
+  String *lisp_name = lispify_name(n, var_name, "'variable");
+
+  if (Strcmp(lisp_name, "t") == 0 || Strcmp(lisp_name, "T") == 0)
+    lisp_name = NewStringf("t_var");
+
+  Printf(f_cl, "\n(cffi:defcvar (\"%s\" %s)\n %s)\n", var_name, lisp_name, lisp_type);
+
+  Delete(lisp_type);
+
+  emit_export(n, lisp_name);
+  return SWIG_OK;
+}
+
+int CFFI::typedefHandler(Node *n) {
+  if (generate_typedef_flag && strncmp(Char(Getattr(n, "type")), "enum", 4)) {
+    String *lisp_name = lispify_name(n, Getattr(n, "name"), "'typename");
+    Printf(f_cl, "\n(cffi:defctype %s %s)\n", lisp_name, Swig_typemap_lookup("cin", n, "", 0));
+    emit_export(n, lisp_name);
+  }
+  return Language::typedefHandler(n);
+}
+
+int CFFI::enumDeclaration(Node *n) {
+  String *name = Getattr(n, "sym:name");
+  bool slot_name_keywords;
+  String *lisp_name = 0;
+  if (name && Len(name) != 0) {
+    lisp_name = lispify_name(n, name, "'enumname");
+    if (GetFlag(n, "feature:bitfield")) {
+      Printf(f_cl, "\n(cffi:defbitfield %s", lisp_name);
+    } else {
+      Printf(f_cl, "\n(cffi:defcenum %s", lisp_name);
+    }
+    slot_name_keywords = true;
+
+    //Registering the enum name to the cin and cout typemaps
+    Parm *pattern = NewParm(name, NULL);
+    Swig_typemap_register("cin", pattern, lisp_name, NULL, NULL);
+    Swig_typemap_register("cout", pattern, lisp_name, NULL, NULL);
+    Delete(pattern);
+    //Registering with the kind, i.e., enum
+    pattern = NewParm(NewStringf("enum %s", name), NULL);
+    Swig_typemap_register("cin", pattern, lisp_name, NULL, NULL);
+    Swig_typemap_register("cout", pattern, lisp_name, NULL, NULL);
+    Delete(pattern);
+
+  } else {
+    Printf(f_cl, "\n(defanonenum %s", name);
+    slot_name_keywords = false;
+  }
+
+  for (Node *c = firstChild(n); c; c = nextSibling(c)) {
+
+    String *slot_name = lispify_name(c, Getattr(c, "name"), "'enumvalue", slot_name_keywords);
+    String *value = Getattr(c, "enumvalue");
+
+    if (!value || GetFlag(n, "feature:bitfield:ignore_values"))
+      Printf(f_cl, "\n\t%s", slot_name);
+    else {
+      String *type = Getattr(c, "type");
+      String *converted_value = convert_literal(value, type);
+      Printf(f_cl, "\n\t(%s %s)", slot_name, converted_value);
+      Delete(converted_value);
+    }
+    Delete(value);
+  }
+
+  Printf(f_cl, ")\n");
+
+  // No need to export keywords
+  if (lisp_name && Len(lisp_name) != 0) {
+    emit_export(n, lisp_name);
+  } else {
+    for (Node *c = firstChild(n); c; c = nextSibling(c))
+      emit_export(c, lispify_name(c, Getattr(c, "name"), "'enumvalue"));
+  }
+
+  return SWIG_OK;
+}
+void CFFI::emit_class(Node *n) {
+
+#ifdef CFFI_WRAP_DEBUG
+  Printf(stderr, "emit_class: ENTER... '%s'(%x)\n", Getattr(n, "sym:name"), n);
+#endif
+
+  String *name = Getattr(n, "sym:name");
+  String *lisp_name = lispify_name(n, lispy_name(Char(name)), "'classname");
+
+  String *bases = Getattr(n, "bases");
+  String *supers = NewString("(");
+  if (bases) {
+    int first = 1;
+    for (Iterator i = First(bases); i.item; i = Next(i)) {
+      if (!first)
+  Printf(supers, " ");
+      String *s = Getattr(i.item, "name");
+      Printf(supers, "%s", lispify_name(i.item, s, "'classname"));
+    }
+  } else {
+    // Printf(supers,"ff:foreign-pointer");
+  }
+
+  Printf(supers, ")");
+  Printf(f_clos, "\n(cl:defclass %s%s", lisp_name, supers);
+  Printf(f_clos, "\n  ((ff-pointer :reader ff-pointer)))\n\n");
+
+  Parm *pattern = NewParm(Getattr(n, "name"), NULL);
+
+  Swig_typemap_register("lispclass", pattern, lisp_name, NULL, NULL);
+  SwigType_add_pointer(Getattr(pattern, "type"));
+  Swig_typemap_register("lispclass", pattern, lisp_name, NULL, NULL);
+  SwigType_add_qualifier(Getattr(pattern, "type"), "const");
+  Swig_typemap_register("lispclass", pattern, lisp_name, NULL, NULL);
+  SwigType_del_pointer(Getattr(pattern, "type"));
+  SwigType_add_reference(Getattr(pattern, "type"));
+  Swig_typemap_register("lispclass", pattern, lisp_name, NULL, NULL);
+
+#ifdef CFFI_WRAP_DEBUG
+  Printf(stderr, "  pattern %s  name %s .. ... %s .\n", pattern, lisp_name);
+#endif
+
+  Delete(pattern);
+
+  // Walk children to generate type definition.
+  String *slotdefs = NewString("   ");
+
+#ifdef CFFI_WRAP_DEBUG
+  Printf(stderr, "  walking children...\n");
+#endif
+
+  Node *c;
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    String *storage_type = Getattr(c, "storage");
+    if ((!Strcmp(nodeType(c), "cdecl") && (!storage_type || Strcmp(storage_type, "typedef")))) {
+      String *access = Getattr(c, "access");
+
+      // hack. why would decl have a value of "variableHandler" and now "0"?
+      String *childDecl = Getattr(c, "decl");
+      // Printf(stderr,"childDecl = '%s' (%s)\n", childDecl, Getattr(c,"view"));
+      if (!Strcmp(childDecl, "0"))
+  childDecl = NewString("");
+
+      SwigType *childType = NewStringf("%s%s", childDecl,
+               Getattr(c, "type"));
+      String *cname = (access && Strcmp(access, "public")) ? NewString("nil") : Copy(Getattr(c, "name"));
+
+      if (!SwigType_isfunction(childType)) {
+  // Printf(slotdefs, ";;; member functions don't appear as slots.\n ");
+  // Printf(slotdefs, ";; ");
+  //        String *ns = listify_namespace(Getattr(n, "cffi:package"));
+  String *ns = NewString("");
+#ifdef CFFI_WRAP_DEBUG
+  Printf(stderr, "slot name = '%s' ns = '%s' class-of '%s' and type = '%s'\n", cname, ns, name, childType);
+#endif
+  Printf(slotdefs, "(#.(swig-insert-id \"%s\" %s :type :slot :class \"%s\") %s)", cname, ns, name, childType);  //compose_foreign_type(childType)
+  Delete(ns);
+  if (access && Strcmp(access, "public"))
+    Printf(slotdefs, " ;; %s member", access);
+
+  Printf(slotdefs, "\n   ");
+      }
+      Delete(childType);
+      Delete(cname);
+    }
+  }
+
+
+  //   String *ns_list = listify_namespace(Getattr(n,"cffi:namespace"));
+  //   update_package_if_needed(n,f_clhead);
+  //   Printf(f_clos, 
+  //          "(swig-def-foreign-class \"%s\"\n %s\n  (:%s\n%s))\n\n", 
+  //          name, supers, kind, slotdefs);
+
+  Delete(supers);
+  //  Delete(ns_list);
+
+  //  Parm *pattern = NewParm(name,NULL);
+  // Swig_typemap_register("cin",pattern,lisp_name,NULL,NULL);  
+  //Swig_typemap_register("cout",pattern,lisp_name,NULL,NULL);
+  //Delete(pattern);
+
+#ifdef CFFI_WRAP_DEBUG
+  Printf(stderr, "emit_class: EXIT\n");
+#endif
+}
+
+// Includes structs
+void CFFI::emit_struct_union(Node *n, bool un = false) {
+#ifdef CFFI_DEBUG
+  Printf(stderr, "struct/union %s\n", Getattr(n, "name"));
+  Printf(stderr, "struct/union %s\n and %s", Getattr(n, "kind"), Getattr(n, "sym:name"));
+#endif
+
+  String *name = Getattr(n, "sym:name");
+  String *kind = Getattr(n, "kind");
+
+  if (Strcmp(kind, "struct") != 0 && Strcmp(kind, "union") != 0) {
+    Printf(stderr, "Don't know how to deal with %s kind of class yet.\n", kind);
+    Printf(stderr, " (name: %s)\n", name);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  String *lisp_name = lispify_name(n, name, "'classname");
+
+  //Register the struct/union name to the cin and cout typemaps
+
+  Parm *pattern = NewParm(name, NULL);
+  Swig_typemap_register("cin", pattern, lisp_name, NULL, NULL);
+  Swig_typemap_register("cout", pattern, lisp_name, NULL, NULL);
+  Delete(pattern);
+  //Registering with the kind, i.e., struct or union
+  pattern = NewParm(NewStringf("%s %s", kind, name), NULL);
+  Swig_typemap_register("cin", pattern, lisp_name, NULL, NULL);
+  Swig_typemap_register("cout", pattern, lisp_name, NULL, NULL);
+  Delete(pattern);
+
+  if (un) {
+    Printf(f_cl, "\n(cffi:defcunion %s", lisp_name);
+  } else
+    Printf(f_cl, "\n(cffi:defcstruct %s", lisp_name);
+
+
+  for (Node *c = firstChild(n); c; c = nextSibling(c)) {
+#ifdef CFFI_DEBUG
+    Printf(stderr, "struct/union %s\n", Getattr(c, "name"));
+    Printf(stderr, "struct/union %s and %s \n", Getattr(c, "kind"), Getattr(c, "sym:name"));
+#endif
+
+    if (Strcmp(nodeType(c), "cdecl")) {
+      //C declaration ignore
+      //        Printf(stderr, "Structure %s has a slot that we can't deal with.\n",
+      //               name);
+      //        Printf(stderr, "nodeType: %s, name: %s, type: %s\n", 
+      //               nodeType(c),
+      //               Getattr(c, "name"),
+      //               Getattr(c, "type"));
+      //       SWIG_exit(EXIT_FAILURE);
+    } else {
+      SwigType *childType = NewStringf("%s%s", Getattr(c, "decl"),
+               Getattr(c, "type"));
+
+      Hash *typemap = Swig_typemap_search("cin", childType, "", 0);
+      String *typespec = NewString("");
+      if (typemap) {
+  typespec = NewString(Getattr(typemap, "code"));
+      }
+
+      String *slot_name = lispify_name(c, Getattr(c, "sym:name"), "'slotname");
+      if (Strcmp(slot_name, "t") == 0 || Strcmp(slot_name, "T") == 0)
+  slot_name = NewStringf("t_var");
+
+      Printf(f_cl, "\n\t(%s %s)", slot_name, typespec);
+
+      Delete(typespec);
+    }
+  }
+
+  Printf(f_cl, ")\n");
+
+  emit_export(n, lisp_name);
+  for (Node *child = firstChild(n); child; child = nextSibling(child)) {
+    if (!Strcmp(nodeType(child), "cdecl")) {
+      emit_export(child, lispify_name(child, Getattr(child, "sym:name"), "'slotname"));
+    }
+  }
+
+  /* Add this structure to the known lisp types */
+  //Printf(stdout, "Adding %s foreign type\n", name);
+  //  add_defined_foreign_type(name);
+
+}
+
+void CFFI::emit_export(Node *n, String *name) {
+  if (GetInt(n, "feature:export"))
+    Printf(f_cl, "\n(cl:export '%s)\n", name);
+}
+
+void CFFI::emit_inline(Node *n, String *name) {
+  if (GetInt(n, "feature:inline"))
+    Printf(f_cl, "\n(cl:declaim (cl:inline %s))\n", name);
+}
+
+String *CFFI::lispify_name(Node *n, String *ty, const char *flag, bool kw) {
+  String *intern_func = Getattr(n, "feature:intern_function");
+  if (intern_func) {
+    if (Strcmp(intern_func, "1") == 0)
+      intern_func = NewStringf("swig-lispify");
+    return NewStringf("#.(%s \"%s\" %s%s)", intern_func, ty, flag, kw ? " :keyword" : "");
+  } else if (kw)
+    return NewStringf(":%s", ty);
+  else
+    return ty;
+}
+
+/* utilities */
+/* returns new string w/ parens stripped */
+String *CFFI::strip_parens(String *string) {
+  char *s = Char(string), *p;
+  int len = Len(string);
+  String *res;
+
+  if (len == 0 || s[0] != '(' || s[len - 1] != ')') {
+    return NewString(string);
+  }
+
+  p = (char *) malloc(len - 2 + 1);
+  if (!p) {
+    Printf(stderr, "Malloc failed\n");
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  strncpy(p, s + 1, len - 1);
+  p[len - 2] = 0;   /* null terminate */
+
+  res = NewString(p);
+  free(p);
+
+  return res;
+}
+
+String *CFFI::trim(String *str) {
+  char *c = Char(str);
+  while (*c != '\0' && isspace((int) *c))
+    ++c;
+  String *result = NewString(c);
+  Chop(result);
+  return result;
+}
+
+String *CFFI::infix_to_prefix(String *val, char split_op, const String *op, String *type) {
+  List *ored = Split(val, split_op, -1);
+
+  // some float hackery
+  //i don't understand it, if you do then please explain
+  //   if ( ((split_op == '+') || (split_op == '-')) && Len(ored) == 2 &&
+  //        (SwigType_type(type) == T_FLOAT || SwigType_type(type) == T_DOUBLE ||
+  //    SwigType_type(type) == T_LONGDOUBLE) ) {
+  //     // check that we're not splitting a float
+  //     String *possible_result = convert_literal(val, type, false);
+  //     if (possible_result) return possible_result;
+
+  //   }
+
+  // try parsing the split results. if any part fails, kick out.
+  bool part_failed = false;
+  if (Len(ored) > 1) {
+    String *result = NewStringf("(%s", op);
+    for (Iterator i = First(ored); i.item; i = Next(i)) {
+      String *converted = convert_literal(i.item, type);
+      if (converted) {
+  Printf(result, " %s", converted);
+  Delete(converted);
+      } else {
+  part_failed = true;
+  break;
+      }
+    }
+    Printf(result, ")");
+    Delete(ored);
+    return part_failed ? 0 : result;
+  } else {
+    Delete(ored);
+  }
+  return 0;
+}
+
+/* To be called by code generating the lisp interface
+   Will return a String containing the literal based on type.
+   Will return null if there are problems.
+
+   try_to_split defaults to true (see stub above).
+*/
+String *CFFI::convert_literal(String *literal, String *type, bool try_to_split) {
+  String *num_param = Copy(literal);
+  String *trimmed = trim(num_param);
+  String *num = strip_parens(trimmed), *res = 0;
+  Delete(trimmed);
+  char *s = Char(num);
+
+  // very basic parsing of infix expressions.
+  if (try_to_split) {
+    if ((res = infix_to_prefix(num, '|', "cl:logior", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '&', "cl:logand", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '^', "cl:logxor", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '*', "cl:*", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '/', "cl:/", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '+', "cl:+", type)))
+      return res;
+    if ((res = infix_to_prefix(num, '-', "cl:-", type)))
+      return res;
+  }
+
+  if (SwigType_type(type) == T_FLOAT || SwigType_type(type) == T_DOUBLE || SwigType_type(type) == T_LONGDOUBLE) {
+    // Use CL syntax for float literals 
+
+    // careful. may be a float identifier or float constant.
+    char *num_start = Char(num);
+    char *num_end = num_start + strlen(num_start) - 1;
+
+    bool is_literal = isdigit(*num_start) || (*num_start == '.') || (*num_start == '+') || (*num_start == '-');
+
+    String *lisp_exp = 0;
+    if (is_literal) {
+      if (*num_end == 'f' || *num_end == 'F') {
+        lisp_exp = NewString("f");
+      } else {
+        lisp_exp = NewString("d");
+      }
+
+      if (*num_end == 'l' || *num_end == 'L' || *num_end == 'f' || *num_end == 'F') {
+        *num_end = '\0';
+        num_end--;
+      }
+
+      int exponents = Replaceall(num, "e", lisp_exp) + Replaceall(num, "E", lisp_exp);
+
+      if (!exponents)
+        Printf(num, "%s0", lisp_exp);
+
+      if (exponents > 1 || (exponents + Replaceall(num, ".", ".") == 0)) {
+        Delete(num);
+        num = 0;
+      }
+    }
+    return num;
+  } else if (SwigType_type(type) == T_CHAR) {
+    /* Use CL syntax for character literals */
+    String* result = NewStringf("#\\%c", s[2]);
+    Delete(num);
+    //    Printf(stderr, "%s  %c %d", s, s[2], s);
+    return result;
+  } else if (SwigType_type(type) == T_STRING) {
+    /* Use CL syntax for string literals */
+    String* result = NewStringf("\"%s\"", num_param);
+    Delete(num);
+    return result;
+  } else if (SwigType_type(type) == T_INT || SwigType_type(type) == T_UINT) {
+    // Printf(stderr, "Is a T_INT or T_UINT %s, before replaceall\n", s);
+    Replaceall(num, "u", "");
+    Replaceall(num, "U", "");
+    Replaceall(num, "l", "");
+    Replaceall(num, "L", "");
+
+    int i, j;
+    if (sscanf(s, "%d >> %d", &i, &j) == 2) {
+      String* result = NewStringf("(cl:ash %d -%d)", i, j);
+      Delete(num);
+      return result;
+    } else if (sscanf(s, "%d << %d", &i, &j) == 2) {
+      String* result = NewStringf("(cl:ash %d %d)", i, j);
+      Delete(num);
+      return result;
+    }
+  }
+
+  if (Len(num) >= 2 && s[0] == '0') { /* octal or hex */
+    if (s[1] == 'x'){
+      DohReplace(num,"0","#",DOH_REPLACE_FIRST);
+    }
+    else{
+      DohReplace(num,"0","#o",DOH_REPLACE_FIRST);
+    }
+  }
+  return num;
+}
+
+//less flexible as it does the conversion in C, the lispify name does the conversion in lisp
+String *CFFI::lispy_name(char *name) {
+  bool helper = false;
+  String *new_name = NewString("");
+  for (unsigned int i = 0; i < strlen(name); i++) {
+    if (name[i] == '_' || name[i] == '-') {
+      Printf(new_name, "%c", '-');
+      helper = false;
+    } else if (name[i] >= 'A' && name[i] <= 'Z') {
+      if (helper)
+  Printf(new_name, "%c", '-');
+      Printf(new_name, "%c", ('a' + (name[i] - 'A')));
+      helper = false;
+    } else {
+      helper = true;
+      Printf(new_name, "%c", name[i]);
+    }
+  }
+  return new_name;
+}
+
+extern "C" Language *swig_cffi(void) {
+  return new CFFI();
+}
diff --git a/trunk/Source/Modules/chicken.cxx b/trunk/Source/Modules/chicken.cxx
new file mode 100644
index 0000000..2298d29
--- /dev/null
+++ b/trunk/Source/Modules/chicken.cxx
@@ -0,0 +1,1545 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * chicken.cxx
+ *
+ * CHICKEN language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_chicken_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#include <ctype.h>
+
+static const char *chicken_usage = (char *) "\
+\
+CHICKEN Options (available with -chicken)\n\
+     -proxy                 - Export TinyCLOS class definitions\n\
+     -closprefix <prefix>   - Prepend <prefix> to all clos identifiers\n\
+     -useclassprefix        - Prepend the class name to all clos identifiers\n\
+     -unhideprimitive       - Unhide the primitive: symbols\n\
+     -nounit                - Do not (declare (unit ...)) in scheme file\n\
+     -noclosuses            - Do not (declare (uses ...)) in scheme file\n\
+     -nocollection          - Do not register pointers with chicken garbage\n\
+                              collector and export destructors\n\
+\n";
+
+static char *module = 0;
+static char *chicken_path = (char *) "chicken";
+static int num_methods = 0;
+
+static File *f_runtime = 0;
+static File *f_header = 0;
+static File *f_wrappers = 0;
+static File *f_init = 0;
+static String *chickentext = 0;
+static String *closprefix = 0;
+static String *swigtype_ptr = 0;
+
+
+static String *f_sym_size = 0;
+
+/* some options */
+static int declare_unit = 1;
+static int no_collection = 0;
+static int clos_uses = 1;
+
+/* C++ Support + Clos Classes */
+static int clos = 0;
+static String *c_class_name = 0;
+static String *class_name = 0;
+static String *short_class_name = 0;
+
+static int in_class = 0;
+static int have_constructor = 0;
+static bool exporting_destructor = false;
+static bool exporting_constructor = false;
+static String *constructor_name = 0;
+static String *member_name = 0;
+
+/* sections of the .scm code */
+static String *scm_const_defs = 0;
+static String *clos_class_defines = 0;
+static String *clos_methods = 0;
+
+/* Some clos options */
+static int useclassprefix = 0;
+static String *clossymnameprefix = 0;
+static int hide_primitive = 1;
+static Hash *primitive_names = 0;
+
+/* Used for overloading constructors */
+static int has_constructor_args = 0;
+static List *constructor_arg_types = 0;
+static String *constructor_dispatch = 0;
+
+static Hash *overload_parameter_lists = 0;
+
+class CHICKEN:public Language {
+public:
+
+  virtual void main(int argc, char *argv[]);
+  virtual int top(Node *n);
+  virtual int functionWrapper(Node *n);
+  virtual int variableWrapper(Node *n);
+  virtual int constantWrapper(Node *n);
+  virtual int classHandler(Node *n);
+  virtual int memberfunctionHandler(Node *n);
+  virtual int membervariableHandler(Node *n);
+  virtual int constructorHandler(Node *n);
+  virtual int destructorHandler(Node *n);
+  virtual int validIdentifier(String *s);
+  virtual int staticmembervariableHandler(Node *n);
+  virtual int staticmemberfunctionHandler(Node *n);
+  virtual int importDirective(Node *n);
+
+protected:
+  void addMethod(String *scheme_name, String *function);
+  /* Return true iff T is a pointer type */
+  int isPointer(SwigType *t);
+  void dispatchFunction(Node *n);
+
+  String *chickenNameMapping(String *, String_or_char *);
+  String *chickenPrimitiveName(String *);
+
+  String *runtimeCode();
+  String *defaultExternalRuntimeFilename();
+  String *buildClosFunctionCall(List *types, String_or_char *closname, String_or_char *funcname);
+};
+
+/* -----------------------------------------------------------------------
+ * swig_chicken()    - Instantiate module
+ * ----------------------------------------------------------------------- */
+
+static Language *new_swig_chicken() {
+  return new CHICKEN();
+}
+
+extern "C" {
+  Language *swig_chicken(void) {
+    return new_swig_chicken();
+  }
+}
+
+void CHICKEN::main(int argc, char *argv[]) {
+  int i;
+
+  SWIG_library_directory(chicken_path);
+
+  // Look for certain command line options
+  for (i = 1; i < argc; i++) {
+    if (argv[i]) {
+      if (strcmp(argv[i], "-help") == 0) {
+	fputs(chicken_usage, stdout);
+	SWIG_exit(0);
+      } else if (strcmp(argv[i], "-proxy") == 0) {
+	clos = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-closprefix") == 0) {
+	if (argv[i + 1]) {
+	  clossymnameprefix = NewString(argv[i + 1]);
+	  Swig_mark_arg(i);
+	  Swig_mark_arg(i + 1);
+	  i++;
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-useclassprefix") == 0) {
+	useclassprefix = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-unhideprimitive") == 0) {
+	hide_primitive = 0;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nounit") == 0) {
+	declare_unit = 0;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-noclosuses") == 0) {
+	clos_uses = 0;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nocollection") == 0) {
+	no_collection = 1;
+	Swig_mark_arg(i);
+      }
+    }
+  }
+
+  if (!clos)
+    hide_primitive = 0;
+
+  // Add a symbol for this module
+  Preprocessor_define("SWIGCHICKEN 1", 0);
+
+  // Set name of typemaps
+
+  SWIG_typemap_lang("chicken");
+
+  // Read in default typemaps */
+  SWIG_config_file("chicken.swg");
+  allow_overloading();
+}
+
+int CHICKEN::top(Node *n) {
+  String *chicken_filename = NewString("");
+  File *f_scm;
+  String *scmmodule;
+
+  /* Initialize all of the output files */
+  String *outfile = Getattr(n, "outfile");
+
+  f_runtime = NewFile(outfile, "w");
+  if (!f_runtime) {
+    FileErrorDisplay(outfile);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  f_init = NewString("");
+  f_header = NewString("");
+  f_wrappers = NewString("");
+  chickentext = NewString("");
+  closprefix = NewString("");
+  f_sym_size = NewString("");
+  primitive_names = NewHash();
+  overload_parameter_lists = NewHash();
+
+  /* Register file targets with the SWIG file handler */
+  Swig_register_filebyname("header", f_header);
+  Swig_register_filebyname("wrapper", f_wrappers);
+  Swig_register_filebyname("runtime", f_runtime);
+  Swig_register_filebyname("init", f_init);
+
+  Swig_register_filebyname("chicken", chickentext);
+  Swig_register_filebyname("closprefix", closprefix);
+
+  clos_class_defines = NewString("");
+  clos_methods = NewString("");
+  scm_const_defs = NewString("");
+
+  Printf(f_runtime, "/* -*- buffer-read-only: t -*- vi: set ro: */\n");
+  Swig_banner(f_runtime);
+
+  Printf(f_runtime, "/* Implementation : CHICKEN */\n\n");
+
+  if (no_collection)
+    Printf(f_runtime, "#define SWIG_CHICKEN_NO_COLLECTION 1\n");
+
+  /* Set module name */
+  module = Swig_copy_string(Char(Getattr(n, "name")));
+  scmmodule = NewString(module);
+  Replaceall(scmmodule, "_", "-");
+
+  Printf(f_header, "#define SWIG_init swig_%s_init\n", module);
+  Printf(f_header, "#define SWIG_name \"%s\"\n", scmmodule);
+
+  Printf(f_wrappers, "#ifdef __cplusplus\n");
+  Printf(f_wrappers, "extern \"C\" {\n");
+  Printf(f_wrappers, "#endif\n\n");
+
+  Language::top(n);
+
+  SwigType_emit_type_table(f_runtime, f_wrappers);
+
+  Printf(f_wrappers, "#ifdef __cplusplus\n");
+  Printf(f_wrappers, "}\n");
+  Printf(f_wrappers, "#endif\n");
+
+  Printf(f_init, "C_kontinue (continuation, ret);\n");
+  Printf(f_init, "}\n\n");
+
+  Printf(f_init, "#ifdef __cplusplus\n");
+  Printf(f_init, "}\n");
+  Printf(f_init, "#endif\n");
+
+  Printf(chicken_filename, "%s%s.scm", SWIG_output_directory(), module);
+  if ((f_scm = NewFile(chicken_filename, "w")) == 0) {
+    FileErrorDisplay(chicken_filename);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  Printv(f_scm,
+	 ";; -*- buffer-read-only: t -*- vi: set ro:\n",
+	 ";; This file was created automatically by SWIG.\n", ";; Don't modify this file, modify the SWIG interface instead.\n", NIL);
+  if (declare_unit)
+    Printv(f_scm, "(declare (unit ", scmmodule, "))\n\n", NIL);
+  Printv(f_scm, "(declare \n",
+	 tab4, "(hide swig-init swig-init-return)\n",
+	 tab4, "(foreign-declare \"C_extern void swig_", module, "_init(C_word,C_word,C_word) C_noret;\"))\n", NIL);
+  Printv(f_scm, "(define swig-init (##core#primitive \"swig_", module, "_init\"))\n", NIL);
+  Printv(f_scm, "(define swig-init-return (swig-init))\n\n", NIL);
+
+  if (clos) {
+    //Printf (f_scm, "(declare (uses tinyclos))\n");
+    //New chicken versions have tinyclos as an egg
+    Printf(f_scm, "(require-extension tinyclos)\n");
+    Replaceall(closprefix, "$module", scmmodule);
+    Printf(f_scm, "%s\n", closprefix);
+    Printf(f_scm, "%s\n", clos_class_defines);
+    Printf(f_scm, "%s\n", clos_methods);
+  } else {
+    Printf(f_scm, "%s\n", scm_const_defs);
+  }
+
+  Printf(f_scm, "%s\n", chickentext);
+
+
+  Close(f_scm);
+  Delete(f_scm);
+
+  char buftmp[20];
+  sprintf(buftmp, "%d", num_methods);
+  Replaceall(f_init, "$nummethods", buftmp);
+  Replaceall(f_init, "$symsize", f_sym_size);
+
+  if (hide_primitive)
+    Replaceall(f_init, "$veclength", buftmp);
+  else
+    Replaceall(f_init, "$veclength", "0");
+
+  Delete(chicken_filename);
+  Delete(chickentext);
+  Delete(closprefix);
+  Delete(overload_parameter_lists);
+
+  Delete(clos_class_defines);
+  Delete(clos_methods);
+  Delete(scm_const_defs);
+
+  /* Close all of the files */
+  Delete(primitive_names);
+  Delete(scmmodule);
+  Dump(f_header, f_runtime);
+  Dump(f_wrappers, f_runtime);
+  Wrapper_pretty_print(f_init, f_runtime);
+  Delete(f_header);
+  Delete(f_wrappers);
+  Delete(f_sym_size);
+  Delete(f_init);
+  Close(f_runtime);
+  Delete(f_runtime);
+  return SWIG_OK;
+}
+
+int CHICKEN::functionWrapper(Node *n) {
+
+  String *name = Getattr(n, "name");
+  String *iname = Getattr(n, "sym:name");
+  SwigType *d = Getattr(n, "type");
+  ParmList *l = Getattr(n, "parms");
+
+  Parm *p;
+  int i;
+  String *wname;
+  Wrapper *f;
+  String *mangle = NewString("");
+  String *get_pointers;
+  String *cleanup;
+  String *argout;
+  String *tm;
+  String *overname = 0;
+  String *declfunc = 0;
+  String *scmname;
+  bool any_specialized_arg = false;
+  List *function_arg_types = NewList();
+
+  int num_required;
+  int num_arguments;
+  int have_argout;
+
+  Printf(mangle, "\"%s\"", SwigType_manglestr(d));
+
+  if (Getattr(n, "sym:overloaded")) {
+    overname = Getattr(n, "sym:overname");
+  } else {
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+  }
+
+  f = NewWrapper();
+  wname = NewString("");
+  get_pointers = NewString("");
+  cleanup = NewString("");
+  argout = NewString("");
+  declfunc = NewString("");
+  scmname = NewString(iname);
+  Replaceall(scmname, "_", "-");
+
+  /* Local vars */
+  Wrapper_add_local(f, "resultobj", "C_word resultobj");
+
+  /* Write code to extract function parameters. */
+  emit_parameter_variables(l, f);
+
+  /* Attach the standard typemaps */
+  emit_attach_parmmaps(l, f);
+  Setattr(n, "wrap:parms", l);
+
+  /* Get number of required and total arguments */
+  num_arguments = emit_num_arguments(l);
+  num_required = emit_num_required(l);
+
+  Append(wname, Swig_name_wrapper(iname));
+  if (overname) {
+    Append(wname, overname);
+  }
+  // Check for interrupts
+  Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
+
+  Printv(f->def, "static ", "void ", wname, " (C_word argc, C_word closure, C_word continuation", NIL);
+  Printv(declfunc, "void ", wname, "(C_word,C_word,C_word", NIL);
+
+  /* Generate code for argument marshalling */
+  for (i = 0, p = l; i < num_arguments; i++) {
+
+    while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    SwigType *pt = Getattr(p, "type");
+    String *ln = Getattr(p, "lname");
+
+    Printf(f->def, ", C_word scm%d", i + 1);
+    Printf(declfunc, ",C_word");
+
+    /* Look for an input typemap */
+    if ((tm = Getattr(p, "tmap:in"))) {
+      String *parse = Getattr(p, "tmap:in:parse");
+      if (!parse) {
+        String *source = NewStringf("scm%d", i + 1);
+	Replaceall(tm, "$source", source);
+	Replaceall(tm, "$target", ln);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);	/* Save the location of
+						   the object */
+
+	if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+	  Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	} else {
+	  Replaceall(tm, "$disown", "0");
+	}
+
+	if (i >= num_required)
+	  Printf(get_pointers, "if (argc-2>%i && (%s)) {\n", i, source);
+	Printv(get_pointers, tm, "\n", NIL);
+	if (i >= num_required)
+	  Printv(get_pointers, "}\n", NIL);
+
+	if (clos) {
+	  if (i < num_required) {
+	    if (strcmp("void", Char(pt)) != 0) {
+	      Node *class_node = 0;
+	      String *clos_code = Getattr(p, "tmap:in:closcode");
+	      class_node = classLookup(pt);
+	      if (clos_code && class_node) {
+		String *class_name = NewStringf("<%s>", Getattr(class_node, "sym:name"));
+		Replaceall(class_name, "_", "-");
+		Append(function_arg_types, class_name);
+		Append(function_arg_types, Copy(clos_code));
+		any_specialized_arg = true;
+		Delete(class_name);
+	      } else {
+		Append(function_arg_types, "<top>");
+		Append(function_arg_types, "$input");
+	      }
+	    }
+	  }
+	}
+        Delete(source);
+      }
+
+      p = Getattr(p, "tmap:in:next");
+      continue;
+    } else {
+      Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+      break;
+    }
+  }
+
+  /* finish argument marshalling */
+
+  Printf(f->def, ") {");
+  Printf(declfunc, ")");
+
+  if (num_required != num_arguments) {
+    Append(function_arg_types, "^^##optional$$");
+  }
+
+  /* First check the number of arguments is correct */
+  if (num_arguments != num_required)
+    Printf(f->code, "if (argc-2<%i || argc-2>%i) C_bad_argc(argc,%i);\n", num_required, num_arguments, num_required + 2);
+  else
+    Printf(f->code, "if (argc!=%i) C_bad_argc(argc,%i);\n", num_arguments + 2, num_arguments + 2);
+
+  /* Now piece together the first part of the wrapper function */
+  Printv(f->code, get_pointers, NIL);
+
+  /* Insert constraint checking code */
+  for (p = l; p;) {
+    if ((tm = Getattr(p, "tmap:check"))) {
+      Replaceall(tm, "$target", Getattr(p, "lname"));
+      Printv(f->code, tm, "\n", NIL);
+      p = Getattr(p, "tmap:check:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  /* Insert cleanup code */
+  for (p = l; p;) {
+    if ((tm = Getattr(p, "tmap:freearg"))) {
+      Replaceall(tm, "$source", Getattr(p, "lname"));
+      Printv(cleanup, tm, "\n", NIL);
+      p = Getattr(p, "tmap:freearg:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  /* Insert argument output code */
+  have_argout = 0;
+  for (p = l; p;) {
+    if ((tm = Getattr(p, "tmap:argout"))) {
+
+      if (!have_argout) {
+	have_argout = 1;
+	// Print initial argument output code
+	Printf(argout, "SWIG_Chicken_SetupArgout\n");
+      }
+
+      Replaceall(tm, "$source", Getattr(p, "lname"));
+      Replaceall(tm, "$target", "resultobj");
+      Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+      Replaceall(tm, "$input", Getattr(p, "emit:input"));
+      Printf(argout, "%s", tm);
+      p = Getattr(p, "tmap:argout:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  Setattr(n, "wrap:name", wname);
+
+  /* Emit the function call */
+  String *actioncode = emit_action(n);
+
+  /* Return the function value */
+  if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+    Replaceall(tm, "$source", "result");
+    Replaceall(tm, "$target", "resultobj");
+    Replaceall(tm, "$result", "resultobj");
+    if (GetFlag(n, "feature:new")) {
+      Replaceall(tm, "$owner", "1");
+    } else {
+      Replaceall(tm, "$owner", "0");
+    }
+
+    Printf(f->code, "%s", tm);
+
+    if (have_argout)
+      Printf(f->code, "\nSWIG_APPEND_VALUE(resultobj);\n");
+
+  } else {
+    Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
+  }
+  emit_return_variable(n, d, f);
+
+  /* Insert the argumetn output code */
+  Printv(f->code, argout, NIL);
+
+  /* Output cleanup code */
+  Printv(f->code, cleanup, NIL);
+
+  /* Look to see if there is any newfree cleanup code */
+  if (GetFlag(n, "feature:new")) {
+    if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printf(f->code, "%s\n", tm);
+    }
+  }
+
+  /* See if there is any return cleanup code */
+  if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+    Replaceall(tm, "$source", "result");
+    Printf(f->code, "%s\n", tm);
+  }
+
+
+  if (have_argout) {
+    Printf(f->code, "C_kontinue(continuation,C_SCHEME_END_OF_LIST);\n");
+  } else {
+    if (exporting_constructor && clos && hide_primitive) {
+      /* Don't return a proxy, the wrapped CLOS class is the proxy */
+      Printf(f->code, "C_kontinue(continuation,resultobj);\n");
+    } else {
+      // make the continuation the proxy creation function, if one exists
+      Printv(f->code, "{\n",
+	     "C_word func;\n",
+	     "SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
+	     "if (C_swig_is_closurep(func))\n",
+	     "  ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
+	     "else\n", "  C_kontinue(continuation, resultobj);\n", "}\n", NIL);
+    }
+  }
+
+  /* Error handling code */
+#ifdef USE_FAIL
+  Printf(f->code, "fail:\n");
+  Printv(f->code, cleanup, NIL);
+  Printf(f->code, "swig_panic (\"failure in " "'$symname' SWIG function wrapper\");\n");
+#endif
+  Printf(f->code, "}\n");
+
+  /* Substitute the cleanup code */
+  Replaceall(f->code, "$cleanup", cleanup);
+
+  /* Substitute the function name */
+  Replaceall(f->code, "$symname", iname);
+  Replaceall(f->code, "$result", "resultobj");
+
+  /* Dump the function out */
+  Printv(f_wrappers, "static ", declfunc, " C_noret;\n", NIL);
+  Wrapper_print(f, f_wrappers);
+
+  /* Now register the function with the interpreter.   */
+  if (!Getattr(n, "sym:overloaded")) {
+    if (exporting_destructor && !no_collection) {
+      Printf(f_init, "((swig_chicken_clientdata *)(SWIGTYPE%s->clientdata))->destroy = (swig_chicken_destructor) %s;\n", swigtype_ptr, wname);
+    } else {
+      addMethod(scmname, wname);
+    }
+
+    /* Only export if we are not in a class, or if in a class memberfunction */
+    if (!in_class || member_name) {
+      String *method_def;
+      String *clos_name;
+      if (in_class)
+	clos_name = NewString(member_name);
+      else
+	clos_name = chickenNameMapping(scmname, (char *) "");
+
+      if (!any_specialized_arg) {
+	method_def = NewString("");
+	Printv(method_def, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")", NIL);
+      } else {
+	method_def = buildClosFunctionCall(function_arg_types, clos_name, chickenPrimitiveName(scmname));
+      }
+      Printv(clos_methods, method_def, "\n", NIL);
+      Delete(clos_name);
+      Delete(method_def);
+    }
+
+    if (have_constructor && !has_constructor_args && any_specialized_arg) {
+      has_constructor_args = 1;
+      constructor_arg_types = Copy(function_arg_types);
+    }
+  } else {
+    /* add function_arg_types to overload hash */
+    List *flist = Getattr(overload_parameter_lists, scmname);
+    if (!flist) {
+      flist = NewList();
+      Setattr(overload_parameter_lists, scmname, flist);
+    }
+
+    Append(flist, Copy(function_arg_types));
+
+    if (!Getattr(n, "sym:nextSibling")) {
+      dispatchFunction(n);
+    }
+  }
+
+
+  Delete(wname);
+  Delete(get_pointers);
+  Delete(cleanup);
+  Delete(declfunc);
+  Delete(mangle);
+  Delete(function_arg_types);
+  DelWrapper(f);
+  return SWIG_OK;
+}
+
+int CHICKEN::variableWrapper(Node *n) {
+  char *name = GetChar(n, "name");
+  char *iname = GetChar(n, "sym:name");
+  SwigType *t = Getattr(n, "type");
+  ParmList *l = Getattr(n, "parms");
+
+  String *wname = NewString("");
+  String *mangle = NewString("");
+  String *tm;
+  String *tm2 = NewString("");;
+  String *argnum = NewString("0");
+  String *arg = NewString("argv[0]");
+  Wrapper *f;
+  String *overname = 0;
+  String *scmname;
+
+  int num_required;
+  int num_arguments;
+
+  scmname = NewString(iname);
+  Replaceall(scmname, "_", "-");
+
+  Printf(mangle, "\"%s\"", SwigType_manglestr(t));
+
+  if (Getattr(n, "sym:overloaded")) {
+    overname = Getattr(n, "sym:overname");
+  } else {
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+  }
+
+  f = NewWrapper();
+
+  /* Attach the standard typemaps */
+  emit_attach_parmmaps(l, f);
+  Setattr(n, "wrap:parms", l);
+
+  /* Get number of required and total arguments */
+  num_arguments = emit_num_arguments(l);
+  num_required = emit_num_required(l);
+
+  // evaluation function names
+  Append(wname, Swig_name_wrapper(iname));
+  if (overname) {
+    Append(wname, overname);
+  }
+  Setattr(n, "wrap:name", wname);
+
+  // Check for interrupts
+  Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
+
+  if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) {
+
+    Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL);
+    Printv(f->def, "static " "void ", wname, "(C_word argc, C_word closure, " "C_word continuation, C_word value) {\n", NIL);
+
+    Wrapper_add_local(f, "resultobj", "C_word resultobj");
+
+    Printf(f->code, "if (argc!=2 && argc!=3) C_bad_argc(argc,2);\n");
+
+    /* Check for a setting of the variable value */
+    if (!GetFlag(n, "feature:immutable")) {
+      Printf(f->code, "if (argc > 2) {\n");
+      if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	Replaceall(tm, "$source", "value");
+	Replaceall(tm, "$target", name);
+	Replaceall(tm, "$input", "value");
+	/* Printv(f->code, tm, "\n",NIL); */
+	emit_action_code(n, f->code, tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
+      }
+      Printf(f->code, "}\n");
+    }
+
+    String *varname;
+    if (SwigType_istemplate((char *) name)) {
+      varname = SwigType_namestr((char *) name);
+    } else {
+      varname = name;
+    }
+
+    // Now return the value of the variable - regardless
+    // of evaluating or setting.
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+      Replaceall(tm, "$source", varname);
+      Replaceall(tm, "$varname", varname);
+      Replaceall(tm, "$target", "resultobj");
+      Replaceall(tm, "$result", "resultobj");
+      /* Printf(f->code, "%s\n", tm); */
+      emit_action_code(n, f->code, tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+    }
+
+    Printv(f->code, "{\n",
+	   "C_word func;\n",
+	   "SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
+	   "if (C_swig_is_closurep(func))\n",
+	   "  ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
+	   "else\n", "  C_kontinue(continuation, resultobj);\n", "}\n", NIL);
+
+    /* Error handling code */
+#ifdef USE_FAIL
+    Printf(f->code, "fail:\n");
+    Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name);
+#endif
+    Printf(f->code, "}\n");
+
+    Wrapper_print(f, f_wrappers);
+
+    /* Now register the variable with the interpreter.   */
+    addMethod(scmname, wname);
+
+    if (!in_class || member_name) {
+      String *clos_name;
+      if (in_class)
+	clos_name = NewString(member_name);
+      else
+	clos_name = chickenNameMapping(scmname, (char *) "");
+
+      Node *class_node = classLookup(t);
+      String *clos_code = Getattr(n, "tmap:varin:closcode");
+      if (class_node && clos_code && !GetFlag(n, "feature:immutable")) {
+	Replaceall(clos_code, "$input", "(car lst)");
+	Printv(clos_methods, "(define (", clos_name, " . lst) (if (null? lst) (", chickenPrimitiveName(scmname), ") (",
+	       chickenPrimitiveName(scmname), " ", clos_code, ")))\n", NIL);
+      } else {
+	/* Simply re-export the procedure */
+	if (GetFlag(n, "feature:immutable") && GetFlag(n, "feature:constasvar")) {
+	  Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL);
+	  Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL);
+	} else {
+	  Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL);
+	}
+      }
+      Delete(clos_name);
+    }
+  } else {
+    Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
+  }
+
+  Delete(wname);
+  Delete(argnum);
+  Delete(arg);
+  Delete(tm2);
+  Delete(mangle);
+  DelWrapper(f);
+  return SWIG_OK;
+}
+
+/* ------------------------------------------------------------
+ * constantWrapper()
+ * ------------------------------------------------------------ */
+
+int CHICKEN::constantWrapper(Node *n) {
+
+  char *name = GetChar(n, "name");
+  char *iname = GetChar(n, "sym:name");
+  SwigType *t = Getattr(n, "type");
+  ParmList *l = Getattr(n, "parms");
+  String *value = Getattr(n, "value");
+
+  String *proc_name = NewString("");
+  String *wname = NewString("");
+  String *mangle = NewString("");
+  String *tm;
+  String *tm2 = NewString("");
+  String *source = NewString("");
+  String *argnum = NewString("0");
+  String *arg = NewString("argv[0]");
+  Wrapper *f;
+  String *overname = 0;
+  String *scmname;
+  String *rvalue;
+  SwigType *nctype;
+
+  int num_required;
+  int num_arguments;
+
+  scmname = NewString(iname);
+  Replaceall(scmname, "_", "-");
+
+  Printf(source, "swig_const_%s", iname);
+  Replaceall(source, "::", "__");
+
+  Printf(mangle, "\"%s\"", SwigType_manglestr(t));
+
+  if (Getattr(n, "sym:overloaded")) {
+    overname = Getattr(n, "sym:overname");
+  } else {
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+  }
+
+  Append(wname, Swig_name_wrapper(iname));
+  if (overname) {
+    Append(wname, overname);
+  }
+
+  nctype = NewString(t);
+  if (SwigType_isconst(nctype)) {
+    Delete(SwigType_pop(nctype));
+  }
+
+  if (SwigType_type(nctype) == T_STRING) {
+    rvalue = NewStringf("\"%s\"", value);
+  } else if (SwigType_type(nctype) == T_CHAR) {
+    rvalue = NewStringf("\'%s\'", value);
+  } else {
+    rvalue = NewString(value);
+  }
+
+  /* Special hook for member pointer */
+  if (SwigType_type(t) == T_MPOINTER) {
+    Printf(f_header, "static %s = %s;\n", SwigType_str(t, source), rvalue);
+  } else {
+    if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
+      Replaceall(tm, "$source", rvalue);
+      Replaceall(tm, "$target", source);
+      Replaceall(tm, "$result", source);
+      Replaceall(tm, "$value", rvalue);
+      Printf(f_header, "%s\n", tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+  }
+
+  f = NewWrapper();
+
+  /* Attach the standard typemaps */
+  emit_attach_parmmaps(l, f);
+  Setattr(n, "wrap:parms", l);
+
+  /* Get number of required and total arguments */
+  num_arguments = emit_num_arguments(l);
+  num_required = emit_num_required(l);
+
+  // evaluation function names
+
+  // Check for interrupts
+  Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
+
+  if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) {
+
+    Setattr(n, "wrap:name", wname);
+    Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word) C_noret;\n", NIL);
+
+    Printv(f->def, "static ", "void ", wname, "(C_word argc, C_word closure, " "C_word continuation) {\n", NIL);
+
+    Wrapper_add_local(f, "resultobj", "C_word resultobj");
+
+    Printf(f->code, "if (argc!=2) C_bad_argc(argc,2);\n");
+
+    // Return the value of the variable
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+
+      Replaceall(tm, "$source", source);
+      Replaceall(tm, "$varname", source);
+      Replaceall(tm, "$target", "resultobj");
+      Replaceall(tm, "$result", "resultobj");
+      /* Printf(f->code, "%s\n", tm); */
+      emit_action_code(n, f->code, tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+    }
+
+    Printv(f->code, "{\n",
+	   "C_word func;\n",
+	   "SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
+	   "if (C_swig_is_closurep(func))\n",
+	   "  ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
+	   "else\n", "  C_kontinue(continuation, resultobj);\n", "}\n", NIL);
+
+    /* Error handling code */
+#ifdef USE_FAIL
+    Printf(f->code, "fail:\n");
+    Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name);
+#endif
+    Printf(f->code, "}\n");
+
+    Wrapper_print(f, f_wrappers);
+
+    /* Now register the variable with the interpreter.   */
+    addMethod(scmname, wname);
+
+    if (!in_class || member_name) {
+      String *clos_name;
+      if (in_class)
+	clos_name = NewString(member_name);
+      else
+	clos_name = chickenNameMapping(scmname, (char *) "");
+      if (GetFlag(n, "feature:constasvar")) {
+	Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL);
+	Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL);
+      } else {
+	Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL);
+      }
+      Delete(clos_name);
+    }
+
+  } else {
+    Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
+  }
+
+  Delete(wname);
+  Delete(nctype);
+  Delete(proc_name);
+  Delete(argnum);
+  Delete(arg);
+  Delete(tm2);
+  Delete(mangle);
+  Delete(source);
+  Delete(rvalue);
+  DelWrapper(f);
+  return SWIG_OK;
+}
+
+int CHICKEN::classHandler(Node *n) {
+  /* Create new strings for building up a wrapper function */
+  have_constructor = 0;
+  constructor_dispatch = 0;
+  constructor_name = 0;
+
+  c_class_name = NewString(Getattr(n, "sym:name"));
+  class_name = NewString("");
+  short_class_name = NewString("");
+  Printv(class_name, "<", c_class_name, ">", NIL);
+  Printv(short_class_name, c_class_name, NIL);
+  Replaceall(class_name, "_", "-");
+  Replaceall(short_class_name, "_", "-");
+
+  if (!addSymbol(class_name, n))
+    return SWIG_ERROR;
+
+  /* Handle inheritance */
+  String *base_class = NewString("");
+  List *baselist = Getattr(n, "bases");
+  if (baselist && Len(baselist)) {
+    Iterator base = First(baselist);
+    while (base.item) {
+      if (!Getattr(base.item, "feature:ignore"))
+	Printv(base_class, "<", Getattr(base.item, "sym:name"), "> ", NIL);
+      base = Next(base);
+    }
+  }
+
+  Replaceall(base_class, "_", "-");
+
+  String *scmmod = NewString(module);
+  Replaceall(scmmod, "_", "-");
+
+  Printv(clos_class_defines, "(define ", class_name, "\n", "  (make <swig-metaclass-", scmmod, "> 'name \"", short_class_name, "\"\n", NIL);
+  Delete(scmmod);
+
+  if (Len(base_class)) {
+    Printv(clos_class_defines, "    'direct-supers (list ", base_class, ")\n", NIL);
+  } else {
+    Printv(clos_class_defines, "    'direct-supers (list <object>)\n", NIL);
+  }
+
+  Printf(clos_class_defines, "    'direct-slots (list 'swig-this\n");
+
+  String *mangled_classname = Swig_name_mangle(Getattr(n, "sym:name"));
+
+  SwigType *ct = NewStringf("p.%s", Getattr(n, "name"));
+  swigtype_ptr = SwigType_manglestr(ct);
+
+  Printf(f_runtime, "static swig_chicken_clientdata _swig_chicken_clientdata%s = { 0 };\n", mangled_classname);
+  Printv(f_init, "SWIG_TypeClientData(SWIGTYPE", swigtype_ptr, ", (void *) &_swig_chicken_clientdata", mangled_classname, ");\n", NIL);
+  SwigType_remember(ct);
+
+  /* Emit all of the members */
+
+  in_class = 1;
+  Language::classHandler(n);
+  in_class = 0;
+
+  Printf(clos_class_defines, ")))\n\n");
+
+  if (have_constructor) {
+    Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", "  (swig-initialize obj initargs ", NIL);
+    if (constructor_arg_types) {
+      String *initfunc_name = NewStringf("%s@@SWIG@initmethod", class_name);
+      String *func_call = buildClosFunctionCall(constructor_arg_types, initfunc_name, chickenPrimitiveName(constructor_name));
+      Printf(clos_methods, "%s)\n)\n", initfunc_name);
+      Printf(clos_methods, "(declare (hide %s))\n", initfunc_name);
+      Printf(clos_methods, "%s\n", func_call);
+      Delete(func_call);
+      Delete(initfunc_name);
+      Delete(constructor_arg_types);
+      constructor_arg_types = 0;
+    } else if (constructor_dispatch) {
+      Printf(clos_methods, "%s)\n)\n", constructor_dispatch);
+      Delete(constructor_dispatch);
+      constructor_dispatch = 0;
+    } else {
+      Printf(clos_methods, "%s)\n)\n", chickenPrimitiveName(constructor_name));
+    }
+    Delete(constructor_name);
+    constructor_name = 0;
+  } else {
+    Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", "  (swig-initialize obj initargs (lambda x #f)))\n", NIL);
+  }
+
+  /* export class initialization function */
+  if (clos) {
+    String *funcname = NewString(mangled_classname);
+    Printf(funcname, "_swig_chicken_setclosclass");
+    String *closfuncname = NewString(funcname);
+    Replaceall(closfuncname, "_", "-");
+
+    Printv(f_wrappers, "static void ", funcname, "(C_word,C_word,C_word,C_word) C_noret;\n",
+	   "static void ", funcname, "(C_word argc, C_word closure, C_word continuation, C_word cl) {\n",
+	   "  C_trace(\"", funcname, "\");\n",
+	   "  if (argc!=3) C_bad_argc(argc,3);\n",
+	   "  swig_chicken_clientdata *cdata = (swig_chicken_clientdata *) SWIGTYPE", swigtype_ptr, "->clientdata;\n",
+	   "  cdata->gc_proxy_create = CHICKEN_new_gc_root();\n",
+	   "  CHICKEN_gc_root_set(cdata->gc_proxy_create, cl);\n", "  C_kontinue(continuation, C_SCHEME_UNDEFINED);\n", "}\n", NIL);
+    addMethod(closfuncname, funcname);
+
+    Printv(clos_methods, "(", chickenPrimitiveName(closfuncname), " (lambda (x lst) (if lst ",
+	   "(cons (make ", class_name, " 'swig-this x) lst) ", "(make ", class_name, " 'swig-this x))))\n\n", NIL);
+    Delete(closfuncname);
+    Delete(funcname);
+  }
+
+  Delete(mangled_classname);
+  Delete(swigtype_ptr);
+  swigtype_ptr = 0;
+
+  Delete(class_name);
+  Delete(short_class_name);
+  Delete(c_class_name);
+  class_name = 0;
+  short_class_name = 0;
+  c_class_name = 0;
+
+  return SWIG_OK;
+}
+
+int CHICKEN::memberfunctionHandler(Node *n) {
+  String *iname = Getattr(n, "sym:name");
+  String *proc = NewString(iname);
+  Replaceall(proc, "_", "-");
+
+  member_name = chickenNameMapping(proc, short_class_name);
+  Language::memberfunctionHandler(n);
+  Delete(member_name);
+  member_name = NULL;
+  Delete(proc);
+
+  return SWIG_OK;
+}
+
+int CHICKEN::staticmemberfunctionHandler(Node *n) {
+  String *iname = Getattr(n, "sym:name");
+  String *proc = NewString(iname);
+  Replaceall(proc, "_", "-");
+
+  member_name = NewStringf("%s-%s", short_class_name, proc);
+  Language::staticmemberfunctionHandler(n);
+  Delete(member_name);
+  member_name = NULL;
+  Delete(proc);
+
+  return SWIG_OK;
+}
+
+int CHICKEN::membervariableHandler(Node *n) {
+  String *iname = Getattr(n, "sym:name");
+  //String *pb = SwigType_typedef_resolve_all(SwigType_base(Getattr(n, "type")));
+
+  Language::membervariableHandler(n);
+
+  String *proc = NewString(iname);
+  Replaceall(proc, "_", "-");
+
+  //Node *class_node = Swig_symbol_clookup(pb, Getattr(n, "sym:symtab"));
+  Node *class_node = classLookup(Getattr(n, "type"));
+
+  //String *getfunc = NewStringf("%s-%s-get", short_class_name, proc);
+  //String *setfunc = NewStringf("%s-%s-set", short_class_name, proc);
+  String *getfunc = Swig_name_get(Swig_name_member(c_class_name, iname));
+  Replaceall(getfunc, "_", "-");
+  String *setfunc = Swig_name_set(Swig_name_member(c_class_name, iname));
+  Replaceall(setfunc, "_", "-");
+
+  Printv(clos_class_defines, "        (list '", proc, " ':swig-virtual ':swig-get ", chickenPrimitiveName(getfunc), NIL);
+
+  if (!GetFlag(n, "feature:immutable")) {
+    if (class_node) {
+      Printv(clos_class_defines, " ':swig-set (lambda (x y) (", chickenPrimitiveName(setfunc), " x (slot-ref y 'swig-this))))\n", NIL);
+    } else {
+      Printv(clos_class_defines, " ':swig-set ", chickenPrimitiveName(setfunc), ")\n", NIL);
+    }
+  } else {
+    Printf(clos_class_defines, ")\n");
+  }
+
+  Delete(proc);
+  Delete(setfunc);
+  Delete(getfunc);
+  return SWIG_OK;
+}
+
+int CHICKEN::staticmembervariableHandler(Node *n) {
+  String *iname = Getattr(n, "sym:name");
+  String *proc = NewString(iname);
+  Replaceall(proc, "_", "-");
+
+  member_name = NewStringf("%s-%s", short_class_name, proc);
+  Language::staticmembervariableHandler(n);
+  Delete(member_name);
+  member_name = NULL;
+  Delete(proc);
+
+  return SWIG_OK;
+}
+
+int CHICKEN::constructorHandler(Node *n) {
+  have_constructor = 1;
+  has_constructor_args = 0;
+
+
+  exporting_constructor = true;
+  Language::constructorHandler(n);
+  exporting_constructor = false;
+
+  has_constructor_args = 1;
+
+  String *iname = Getattr(n, "sym:name");
+  constructor_name = Swig_name_construct(iname);
+  Replaceall(constructor_name, "_", "-");
+  return SWIG_OK;
+}
+
+int CHICKEN::destructorHandler(Node *n) {
+
+  if (no_collection)
+    member_name = NewStringf("delete-%s", short_class_name);
+
+  exporting_destructor = true;
+  Language::destructorHandler(n);
+  exporting_destructor = false;
+
+  if (no_collection) {
+    Delete(member_name);
+    member_name = NULL;
+  }
+
+  return SWIG_OK;
+}
+
+int CHICKEN::importDirective(Node *n) {
+  String *modname = Getattr(n, "module");
+  if (modname && clos_uses) {
+
+    // Find the module node for this imported module.  It should be the
+    // first child but search just in case.
+    Node *mod = firstChild(n);
+    while (mod && Strcmp(nodeType(mod), "module") != 0)
+      mod = nextSibling(mod);
+
+    if (mod) {
+      String *name = Getattr(mod, "name");
+      if (name) {
+	Printf(closprefix, "(declare (uses %s))\n", name);
+      }
+    }
+  }
+
+  return Language::importDirective(n);
+}
+
+String *CHICKEN::buildClosFunctionCall(List *types, String_or_char *closname, String_or_char *funcname) {
+  String *method_signature = NewString("");
+  String *func_args = NewString("");
+  String *func_call = NewString("");
+
+  Iterator arg_type;
+  int arg_count = 0;
+  int optional_arguments = 0;
+
+  for (arg_type = First(types); arg_type.item; arg_type = Next(arg_type)) {
+    if (Strcmp(arg_type.item, "^^##optional$$") == 0) {
+      optional_arguments = 1;
+    } else {
+      Printf(method_signature, " (arg%i %s)", arg_count, arg_type.item);
+      arg_type = Next(arg_type);
+      if (!arg_type.item)
+	break;
+
+      String *arg = NewStringf("arg%i", arg_count);
+      String *access_arg = Copy(arg_type.item);
+
+      Replaceall(access_arg, "$input", arg);
+      Printf(func_args, " %s", access_arg);
+
+      Delete(arg);
+      Delete(access_arg);
+    }
+    arg_count++;
+  }
+
+  if (optional_arguments) {
+    Printf(func_call, "(define-method (%s %s . args) (apply %s %s args))", closname, method_signature, funcname, func_args);
+  } else {
+    Printf(func_call, "(define-method (%s %s) (%s %s))", closname, method_signature, funcname, func_args);
+  }
+
+  Delete(method_signature);
+  Delete(func_args);
+
+  return func_call;
+}
+
+extern "C" {
+
+  /* compares based on non-primitive names */
+  static int compareTypeListsHelper(const DOH *a, const DOH *b, int opt_equal) {
+    List *la = (List *) a;
+    List *lb = (List *) b;
+
+    Iterator ia = First(la);
+    Iterator ib = First(lb);
+
+    while (ia.item && ib.item) {
+      int ret = Strcmp(ia.item, ib.item);
+      if (ret)
+	return ret;
+      ia = Next(Next(ia));
+      ib = Next(Next(ib));
+    } if (opt_equal && ia.item && Strcmp(ia.item, "^^##optional$$") == 0)
+      return 0;
+    if (ia.item)
+      return -1;
+    if (opt_equal && ib.item && Strcmp(ib.item, "^^##optional$$") == 0)
+      return 0;
+    if (ib.item)
+      return 1;
+
+    return 0;
+  }
+
+  static int compareTypeLists(const DOH *a, const DOH *b) {
+    return compareTypeListsHelper(a, b, 0);
+  }
+}
+
+void CHICKEN::dispatchFunction(Node *n) {
+  /* Last node in overloaded chain */
+
+  int maxargs;
+  String *tmp = NewString("");
+  String *dispatch = Swig_overload_dispatch(n, "%s (2+$numargs,closure," "continuation$commaargs);", &maxargs);
+
+  /* Generate a dispatch wrapper for all overloaded functions */
+
+  Wrapper *f = NewWrapper();
+  String *iname = Getattr(n, "sym:name");
+  String *wname = NewString("");
+  String *scmname = NewString(iname);
+  Replaceall(scmname, "_", "-");
+
+  Append(wname, Swig_name_wrapper(iname));
+
+  Printv(f->def, "static void real_", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL);
+
+  Printv(f->def, "static void real_", wname, "(C_word oldargc, C_word closure, C_word continuation, C_word args) {", NIL);
+
+  Wrapper_add_local(f, "argc", "int argc");
+  Printf(tmp, "C_word argv[%d]", maxargs + 1);
+  Wrapper_add_local(f, "argv", tmp);
+  Wrapper_add_local(f, "ii", "int ii");
+  Wrapper_add_local(f, "t", "C_word t = args");
+  Printf(f->code, "if (!C_swig_is_list (args)) {\n");
+  Printf(f->code, "  swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, " "\"Argument #1 must be a list of overloaded arguments\");\n");
+  Printf(f->code, "}\n");
+  Printf(f->code, "argc = C_unfix (C_i_length (args));\n");
+  Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++, t = C_block_item (t, 1)) {\n", maxargs);
+  Printf(f->code, "argv[ii] = C_block_item (t, 0);\n");
+  Printf(f->code, "}\n");
+
+  Printv(f->code, dispatch, "\n", NIL);
+  Printf(f->code, "swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE," "\"No matching function for overloaded '%s'\");\n", iname);
+  Printv(f->code, "}\n", NIL);
+  Wrapper_print(f, f_wrappers);
+  addMethod(scmname, wname);
+
+  DelWrapper(f);
+  f = NewWrapper();
+
+  /* varargs */
+  Printv(f->def, "void ", wname, "(C_word, C_word, C_word, ...) C_noret;\n", NIL);
+  Printv(f->def, "void ", wname, "(C_word c, C_word t0, C_word t1, ...) {", NIL);
+  Printv(f->code,
+	 "C_word t2;\n",
+	 "va_list v;\n",
+	 "C_word *a, c2 = c;\n",
+	 "C_save_rest (t1, c2, 2);\n", "a = C_alloc((c-2)*3);\n", "t2 = C_restore_rest (a, C_rest_count (0));\n", "real_", wname, " (3, t0, t1, t2);\n", NIL);
+  Printv(f->code, "}\n", NIL);
+  Wrapper_print(f, f_wrappers);
+
+  /* Now deal with overloaded function when exporting clos */
+  if (clos) {
+    List *flist = Getattr(overload_parameter_lists, scmname);
+    if (flist) {
+      Delattr(overload_parameter_lists, scmname);
+
+      SortList(flist, compareTypeLists);
+
+      String *clos_name;
+      int construct = 0;
+      if (have_constructor && !has_constructor_args) {
+	has_constructor_args = 1;
+	constructor_dispatch = NewStringf("%s@SWIG@new@dispatch", short_class_name);
+	clos_name = Copy(constructor_dispatch);
+	construct = 1;
+	Printf(clos_methods, "(declare (hide %s))\n", clos_name);
+      } else if (in_class)
+	clos_name = NewString(member_name);
+      else
+	clos_name = chickenNameMapping(scmname, (char *) "");
+
+      Iterator f;
+      List *prev = 0;
+      int all_primitive = 1;
+
+      /* first check for duplicates and an empty call */
+      String *newlist = NewList();
+      for (f = First(flist); f.item; f = Next(f)) {
+	/* check if cur is a duplicate of prev */
+	if (prev && compareTypeListsHelper(f.item, prev, 1) == 0) {
+	  Delete(f.item);
+	} else {
+	  Append(newlist, f.item);
+	  prev = f.item;
+	  Iterator j;
+	  for (j = First(f.item); j.item; j = Next(j)) {
+	    if (Strcmp(j.item, "^^##optional$$") != 0 && Strcmp(j.item, "<top>") != 0)
+	      all_primitive = 0;
+	  }
+	}
+      }
+      Delete(flist);
+      flist = newlist;
+
+      if (all_primitive) {
+	Printf(clos_methods, "(define %s %s)\n", clos_name, chickenPrimitiveName(scmname));
+      } else {
+	for (f = First(flist); f.item; f = Next(f)) {
+	  /* now export clos code for argument */
+	  String *func_call = buildClosFunctionCall(f.item, clos_name, chickenPrimitiveName(scmname));
+	  Printf(clos_methods, "%s\n", func_call);
+	  Delete(f.item);
+	  Delete(func_call);
+	}
+      }
+
+      Delete(clos_name);
+      Delete(flist);
+    }
+  }
+
+  DelWrapper(f);
+  Delete(dispatch);
+  Delete(tmp);
+  Delete(wname);
+}
+
+int CHICKEN::isPointer(SwigType *t) {
+  return SwigType_ispointer(SwigType_typedef_resolve_all(t));
+}
+
+void CHICKEN::addMethod(String *scheme_name, String *function) {
+  String *sym = NewString("");
+  if (clos) {
+    Append(sym, "primitive:");
+  }
+  Append(sym, scheme_name);
+
+  /* add symbol to Chicken internal symbol table */
+  if (hide_primitive) {
+    Printv(f_init, "{\n",
+	   "  C_word *p0 = a;\n", "  *(a++)=C_CLOSURE_TYPE|1;\n", "  *(a++)=(C_word)", function, ";\n", "  C_mutate(return_vec++, (C_word)p0);\n", "}\n", NIL);
+  } else {
+    Printf(f_sym_size, "+C_SIZEOF_INTERNED_SYMBOL(%d)", Len(sym));
+    Printf(f_init, "sym = C_intern (&a, %d, \"%s\");\n", Len(sym), sym);
+    Printv(f_init, "C_mutate ((C_word*)sym+1, (*a=C_CLOSURE_TYPE|1, a[1]=(C_word)", function, ", tmp=(C_word)a, a+=2, tmp));\n", NIL);
+  }
+
+  if (hide_primitive) {
+    Setattr(primitive_names, scheme_name, NewStringf("(vector-ref swig-init-return %i)", num_methods));
+  } else {
+    Setattr(primitive_names, scheme_name, Copy(sym));
+  }
+
+  num_methods++;
+
+  Delete(sym);
+}
+
+String *CHICKEN::chickenPrimitiveName(String *name) {
+  String *value = Getattr(primitive_names, name);
+  if (value)
+    return value;
+  else {
+    Swig_error(input_file, line_number, "Internal Error: attempting to reference non-existant primitive name %s\n", name);
+    return NewString("#f");
+  }
+}
+
+int CHICKEN::validIdentifier(String *s) {
+  char *c = Char(s);
+  /* Check whether we have an R5RS identifier. */
+  /* <identifier> --> <initial> <subsequent>* | <peculiar identifier> */
+  /* <initial> --> <letter> | <special initial> */
+  if (!(isalpha(*c) || (*c == '!') || (*c == '$') || (*c == '%')
+	|| (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
+	|| (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
+	|| (*c == '^') || (*c == '_') || (*c == '~'))) {
+    /* <peculiar identifier> --> + | - | ... */
+    if ((strcmp(c, "+") == 0)
+	|| strcmp(c, "-") == 0 || strcmp(c, "...") == 0)
+      return 1;
+    else
+      return 0;
+  }
+  /* <subsequent> --> <initial> | <digit> | <special subsequent> */
+  while (*c) {
+    if (!(isalnum(*c) || (*c == '!') || (*c == '$') || (*c == '%')
+	  || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
+	  || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
+	  || (*c == '^') || (*c == '_') || (*c == '~') || (*c == '+')
+	  || (*c == '-') || (*c == '.') || (*c == '@')))
+      return 0;
+    c++;
+  }
+  return 1;
+}
+
+  /* ------------------------------------------------------------
+   * closNameMapping()
+   * Maps the identifier from C++ to the CLOS based on command 
+   * line parameters and such.
+   * If class_name = "" that means the mapping is for a function or
+   * variable not attached to any class.
+   * ------------------------------------------------------------ */
+String *CHICKEN::chickenNameMapping(String *name, String_or_char *class_name) {
+  String *n = NewString("");
+
+  if (Strcmp(class_name, "") == 0) {
+    // not part of a class, so no class name to prefix
+    if (clossymnameprefix) {
+      Printf(n, "%s%s", clossymnameprefix, name);
+    } else {
+      Printf(n, "%s", name);
+    }
+  } else {
+    if (useclassprefix) {
+      Printf(n, "%s-%s", class_name, name);
+    } else {
+      if (clossymnameprefix) {
+	Printf(n, "%s%s", clossymnameprefix, name);
+      } else {
+	Printf(n, "%s", name);
+      }
+    }
+  }
+  return n;
+}
+
+String *CHICKEN::runtimeCode() {
+  String *s = Swig_include_sys("chickenrun.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'chickenrun.swg'\n");
+    s = NewString("");
+  }
+  return s;
+}
+
+String *CHICKEN::defaultExternalRuntimeFilename() {
+  return NewString("swigchickenrun.h");
+}
diff --git a/trunk/Source/Modules/clisp.cxx b/trunk/Source/Modules/clisp.cxx
new file mode 100644
index 0000000..823f22e
--- /dev/null
+++ b/trunk/Source/Modules/clisp.cxx
@@ -0,0 +1,501 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * clisp.cxx
+ *
+ * clisp language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_clisp_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+class CLISP:public Language {
+public:
+  File *f_cl;
+  String *module;
+  virtual void main(int argc, char *argv[]);
+  virtual int top(Node *n);
+  virtual int functionWrapper(Node *n);
+  virtual int variableWrapper(Node *n);
+  virtual int constantWrapper(Node *n);
+  virtual int classDeclaration(Node *n);
+  virtual int enumDeclaration(Node *n);
+  virtual int typedefHandler(Node *n);
+  List *entries;
+private:
+  String *get_ffi_type(SwigType *ty);
+  String *convert_literal(String *num_param, String *type);
+  String *strip_parens(String *string);
+  int extern_all_flag;
+  int generate_typedef_flag;
+  int is_function;
+};
+
+void CLISP::main(int argc, char *argv[]) {
+  int i;
+
+  SWIG_library_directory("clisp");
+  SWIG_config_file("clisp.swg");
+  generate_typedef_flag = 0;
+  extern_all_flag = 0;
+
+  for (i = 1; i < argc; i++) {
+    if (!strcmp(argv[i], "-help")) {
+      Printf(stdout, "clisp Options (available with -clisp)\n");
+      Printf(stdout,
+	     " -extern-all\n"
+	     "\t If this option is given then clisp definitions for all the functions\n"
+	     "and global variables will be created otherwise only definitions for \n"
+	     "externed functions and variables are created.\n"
+	     " -generate-typedef\n"
+	     "\t If this option is given then def-c-type will be used to generate shortcuts\n"
+	     "according to the typedefs in the input.\n");
+    } else if ((Strcmp(argv[i], "-extern-all") == 0)) {
+      extern_all_flag = 1;
+      Swig_mark_arg(i);
+    } else if ((Strcmp(argv[i], "-generate-typedef") == 0)) {
+      generate_typedef_flag = 1;
+      Swig_mark_arg(i);
+    }
+  }
+}
+
+int CLISP::top(Node *n) {
+
+  File *f_null = NewString("");
+  module = Getattr(n, "name");
+  String *output_filename;
+  entries = NewList();
+
+  /* Get the output file name */
+  String *outfile = Getattr(n, "outfile");
+
+  if (!outfile)
+    output_filename = outfile;
+  else {
+    output_filename = NewString("");
+    Printf(output_filename, "%s%s.lisp", SWIG_output_directory(), module);
+  }
+
+  f_cl = NewFile(output_filename, "w+");
+  if (!f_cl) {
+    FileErrorDisplay(output_filename);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  Swig_register_filebyname("header", f_null);
+  Swig_register_filebyname("runtime", f_null);
+  Swig_register_filebyname("wrapper", f_null);
+
+  String *header =
+      NewStringf
+      (";; This is an automatically generated file. \n;;Make changes as you feel are necessary (but remember if you try to regenerate this file, your changes will be lost). \n\n(defpackage :%s\n  (:use :common-lisp :ffi)",
+       module);
+
+  Language::top(n);
+
+  Iterator i;
+
+  long len = Len(entries);
+  if (len > 0) {
+    Printf(header, "\n  (:export");
+  }
+  //else nothing to export
+
+  for (i = First(entries); i.item; i = Next(i)) {
+    Printf(header, "\n\t:%s", i.item);
+  }
+
+  if (len > 0) {
+    Printf(header, ")");
+  }
+
+  Printf(header, ")\n");
+  Printf(header, "\n(in-package :%s)\n", module);
+  Printf(header, "\n(default-foreign-language :stdc)\n");
+
+  len = Tell(f_cl);
+
+  Printf(f_cl, "%s", header);
+
+  long end = Tell(f_cl);
+
+  for (len--; len >= 0; len--) {
+    end--;
+    Seek(f_cl, len, SEEK_SET);
+    int ch = Getc(f_cl);
+    Seek(f_cl, end, SEEK_SET);
+    Putc(ch, f_cl);
+  }
+
+  Seek(f_cl, 0, SEEK_SET);
+  Write(f_cl, Char(header), Len(header));
+
+  Close(f_cl);
+  Delete(f_cl);			// Deletes the handle, not the file
+
+  return SWIG_OK;
+}
+
+
+int CLISP::functionWrapper(Node *n) {
+  is_function = 1;
+  String *storage = Getattr(n, "storage");
+  if (!extern_all_flag && (!storage || (Strcmp(storage, "extern") && Strcmp(storage, "externc"))))
+    return SWIG_OK;
+
+  String *func_name = Getattr(n, "sym:name");
+
+  ParmList *pl = Getattr(n, "parms");
+
+  int argnum = 0, first = 1;
+
+  Printf(f_cl, "\n(ffi:def-call-out %s\n\t(:name \"%s\")\n", func_name, func_name);
+
+  Append(entries, func_name);
+
+  if (ParmList_len(pl) != 0) {
+    Printf(f_cl, "\t(:arguments ");
+  }
+  for (Parm *p = pl; p; p = nextSibling(p), argnum++) {
+
+    String *argname = Getattr(p, "name");
+    //    SwigType *argtype;
+
+    String *ffitype = get_ffi_type(Getattr(p, "type"));
+
+    int tempargname = 0;
+
+    if (!argname) {
+      argname = NewStringf("arg%d", argnum);
+      tempargname = 1;
+    }
+
+    if (!first) {
+      Printf(f_cl, "\n\t\t");
+    }
+    Printf(f_cl, "(%s %s)", argname, ffitype);
+    first = 0;
+
+    Delete(ffitype);
+
+    if (tempargname)
+      Delete(argname);
+  }
+  if (ParmList_len(pl) != 0) {
+    Printf(f_cl, ")\n");	/* finish arg list */
+  }
+  String *ffitype = get_ffi_type(Getattr(n, "type"));
+  if (Strcmp(ffitype, "NIL")) {	//when return type is not nil
+    Printf(f_cl, "\t(:return-type %s)\n", ffitype);
+  }
+  Printf(f_cl, "\t(:library +library-name+))\n");
+
+  return SWIG_OK;
+}
+
+
+int CLISP::constantWrapper(Node *n) {
+  is_function = 0;
+  String *type = Getattr(n, "type");
+  String *converted_value = convert_literal(Getattr(n, "value"), type);
+  String *name = Getattr(n, "sym:name");
+
+  Printf(f_cl, "\n(defconstant %s %s)\n", name, converted_value);
+  Append(entries, name);
+  Delete(converted_value);
+
+  return SWIG_OK;
+}
+
+int CLISP::variableWrapper(Node *n) {
+  is_function = 0;
+  //  SwigType *type=;
+  String *storage = Getattr(n, "storage");
+
+  if (!extern_all_flag && (!storage || (Strcmp(storage, "extern") && Strcmp(storage, "externc"))))
+    return SWIG_OK;
+
+  String *var_name = Getattr(n, "sym:name");
+  String *lisp_type = get_ffi_type(Getattr(n, "type"));
+  Printf(f_cl, "\n(ffi:def-c-var %s\n (:name \"%s\")\n (:type %s)\n", var_name, var_name, lisp_type);
+  Printf(f_cl, "\t(:library +library-name+))\n");
+  Append(entries, var_name);
+
+  Delete(lisp_type);
+  return SWIG_OK;
+}
+
+int CLISP::typedefHandler(Node *n) {
+  if (generate_typedef_flag) {
+    is_function = 0;
+    Printf(f_cl, "\n(ffi:def-c-type %s %s)\n", Getattr(n, "name"), get_ffi_type(Getattr(n, "type")));
+  }
+
+  return Language::typedefHandler(n);
+}
+
+int CLISP::enumDeclaration(Node *n) {
+  is_function = 0;
+  String *name = Getattr(n, "sym:name");
+
+  Printf(f_cl, "\n(ffi:def-c-enum %s ", name);
+
+  for (Node *c = firstChild(n); c; c = nextSibling(c)) {
+
+    String *slot_name = Getattr(c, "name");
+    String *value = Getattr(c, "enumvalue");
+
+    Printf(f_cl, "(%s %s)", slot_name, value);
+
+    Append(entries, slot_name);
+
+    Delete(value);
+  }
+
+  Printf(f_cl, ")\n");
+  return SWIG_OK;
+}
+
+
+// Includes structs
+int CLISP::classDeclaration(Node *n) {
+  is_function = 0;
+  String *name = Getattr(n, "sym:name");
+  String *kind = Getattr(n, "kind");
+
+  if (Strcmp(kind, "struct")) {
+    Printf(stderr, "Don't know how to deal with %s kind of class yet.\n", kind);
+    Printf(stderr, " (name: %s)\n", name);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+
+  Printf(f_cl, "\n(ffi:def-c-struct %s", name);
+
+  Append(entries, NewStringf("make-%s", name));
+
+  for (Node *c = firstChild(n); c; c = nextSibling(c)) {
+
+    if (Strcmp(nodeType(c), "cdecl")) {
+      Printf(stderr, "Structure %s has a slot that we can't deal with.\n", name);
+      Printf(stderr, "nodeType: %s, name: %s, type: %s\n", nodeType(c), Getattr(c, "name"), Getattr(c, "type"));
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    String *temp = Copy(Getattr(c, "decl"));
+    Append(temp, Getattr(c, "type"));	//appending type to the end, otherwise wrong type
+    String *lisp_type = get_ffi_type(temp);
+    Delete(temp);
+
+    String *slot_name = Getattr(c, "sym:name");
+    Printf(f_cl, "\n\t(%s %s)", slot_name, lisp_type);
+
+    Append(entries, NewStringf("%s-%s", name, slot_name));
+
+    Delete(lisp_type);
+  }
+
+  Printf(f_cl, ")\n");
+
+  /* Add this structure to the known lisp types */
+  //Printf(stdout, "Adding %s foreign type\n", name);
+  //  add_defined_foreign_type(name);
+
+  return SWIG_OK;
+}
+
+/* utilities */
+/* returns new string w/ parens stripped */
+String *CLISP::strip_parens(String *string) {
+  char *s = Char(string), *p;
+  int len = Len(string);
+  String *res;
+
+  if (len == 0 || s[0] != '(' || s[len - 1] != ')') {
+    return NewString(string);
+  }
+
+  p = (char *) malloc(len - 2 + 1);
+  if (!p) {
+    Printf(stderr, "Malloc failed\n");
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  strncpy(p, s + 1, len - 1);
+  p[len - 2] = 0;		/* null terminate */
+
+  res = NewString(p);
+  free(p);
+
+  return res;
+}
+
+String *CLISP::convert_literal(String *num_param, String *type) {
+  String *num = strip_parens(num_param), *res;
+  char *s = Char(num);
+
+  /* Make sure doubles use 'd' instead of 'e' */
+  if (!Strcmp(type, "double")) {
+    String *updated = Copy(num);
+    if (Replace(updated, "e", "d", DOH_REPLACE_ANY) > 1) {
+      Printf(stderr, "Weird!! number %s looks invalid.\n", num);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Delete(num);
+    return updated;
+  }
+
+  if (SwigType_type(type) == T_CHAR) {
+    /* Use CL syntax for character literals */
+    return NewStringf("#\\%s", num_param);
+  } else if (SwigType_type(type) == T_STRING) {
+    /* Use CL syntax for string literals */
+    return NewStringf("\"%s\"", num_param);
+  }
+
+  if (Len(num) < 2 || s[0] != '0') {
+    return num;
+  }
+
+  /* octal or hex */
+
+  res = NewStringf("#%c%s", s[1] == 'x' ? 'x' : 'o', s + 2);
+  Delete(num);
+
+  return res;
+}
+
+String *CLISP::get_ffi_type(SwigType *ty) {
+  Hash *typemap = Swig_typemap_search("in", ty, "", 0);
+  if (typemap) {
+    String *typespec = Getattr(typemap, "code");
+    return NewString(typespec);
+  } else if (SwigType_ispointer(ty)) {
+    SwigType *cp = Copy(ty);
+    SwigType_del_pointer(cp);
+    String *inner_type = get_ffi_type(cp);
+
+    if (SwigType_isfunction(cp)) {
+      return inner_type;
+    }
+
+    SwigType *base = SwigType_base(ty);
+    String *base_name = SwigType_str(base, 0);
+
+    String *str;
+    if (!Strcmp(base_name, "int") || !Strcmp(base_name, "float") || !Strcmp(base_name, "short")
+	|| !Strcmp(base_name, "double") || !Strcmp(base_name, "long") || !Strcmp(base_name, "char")) {
+
+      str = NewStringf("(ffi:c-ptr %s)", inner_type);
+    } else {
+      str = NewStringf("(ffi:c-pointer %s)", inner_type);
+    }
+    Delete(base_name);
+    Delete(base);
+    Delete(cp);
+    Delete(inner_type);
+    return str;
+  } else if (SwigType_isarray(ty)) {
+    SwigType *cp = Copy(ty);
+    String *array_dim = SwigType_array_getdim(ty, 0);
+
+    if (!Strcmp(array_dim, "")) {	//dimension less array convert to pointer
+      Delete(array_dim);
+      SwigType_del_array(cp);
+      SwigType_add_pointer(cp);
+      String *str = get_ffi_type(cp);
+      Delete(cp);
+      return str;
+    } else {
+      SwigType_pop_arrays(cp);
+      String *inner_type = get_ffi_type(cp);
+      Delete(cp);
+
+      int ndim = SwigType_array_ndim(ty);
+      String *dimension;
+      if (ndim == 1) {
+	dimension = array_dim;
+      } else {
+	dimension = array_dim;
+	for (int i = 1; i < ndim; i++) {
+	  array_dim = SwigType_array_getdim(ty, i);
+	  Append(dimension, " ");
+	  Append(dimension, array_dim);
+	  Delete(array_dim);
+	}
+	String *temp = dimension;
+	dimension = NewStringf("(%s)", dimension);
+	Delete(temp);
+      }
+      String *str;
+      if (is_function)
+	str = NewStringf("(ffi:c-ptr (ffi:c-array %s %s))", inner_type, dimension);
+      else
+	str = NewStringf("(ffi:c-array %s %s)", inner_type, dimension);
+
+      Delete(inner_type);
+      Delete(dimension);
+      return str;
+    }
+  } else if (SwigType_isfunction(ty)) {
+    SwigType *cp = Copy(ty);
+    SwigType *fn = SwigType_pop_function(cp);
+    String *args = NewString("");
+    ParmList *pl = SwigType_function_parms(fn);
+    if (ParmList_len(pl) != 0) {
+      Printf(args, "(:arguments ");
+    }
+    int argnum = 0, first = 1;
+    for (Parm *p = pl; p; p = nextSibling(p), argnum++) {
+      String *argname = Getattr(p, "name");
+      SwigType *argtype = Getattr(p, "type");
+      String *ffitype = get_ffi_type(argtype);
+
+      int tempargname = 0;
+
+      if (!argname) {
+	argname = NewStringf("arg%d", argnum);
+	tempargname = 1;
+      }
+      if (!first) {
+	Printf(args, "\n\t\t");
+      }
+      Printf(args, "(%s %s)", argname, ffitype);
+      first = 0;
+      Delete(ffitype);
+      if (tempargname)
+	Delete(argname);
+    }
+    if (ParmList_len(pl) != 0) {
+      Printf(args, ")\n");	/* finish arg list */
+    }
+    String *ffitype = get_ffi_type(cp);
+    String *str = NewStringf("(ffi:c-function %s \t\t\t\t(:return-type %s))", args, ffitype);
+    Delete(fn);
+    Delete(args);
+    Delete(cp);
+    Delete(ffitype);
+    return str;
+  }
+  String *str = SwigType_str(ty, 0);
+  if (str) {
+    char *st = Strstr(str, "struct");
+    if (st) {
+      st += 7;
+      return NewString(st);
+    }
+    char *cl = Strstr(str, "class");
+    if (cl) {
+      cl += 6;
+      return NewString(cl);
+    }
+  }
+  return str;
+}
+
+extern "C" Language *swig_clisp(void) {
+  return new CLISP();
+}
diff --git a/trunk/Source/Modules/contract.cxx b/trunk/Source/Modules/contract.cxx
new file mode 100644
index 0000000..9bf8dec
--- /dev/null
+++ b/trunk/Source/Modules/contract.cxx
@@ -0,0 +1,346 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * contract.cxx
+ *
+ * Support for Wrap by Contract in SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_contract_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+/* Contract structure.  This holds rules about the different kinds of contract sections
+   and their combination rules */
+
+struct contract {
+  const char *section;
+  const char *combiner;
+};
+/* Contract rules.  This table defines what contract sections are recognized as well as
+   how contracts are to combined via inheritance */
+
+static contract Rules[] = {
+  {"require:", "&&"},
+  {"ensure:", "||"},
+  {NULL, NULL}
+};
+
+/* ----------------------------------------------------------------------------
+ * class Contracts:
+ *
+ * This class defines the functions that need to be used in 
+ *         "wrap by contract" module.
+ * ------------------------------------------------------------------------- */
+
+class Contracts:public Dispatcher {
+  String *make_expression(String *s, Node *n);
+  void substitute_parms(String *s, ParmList *p, int method);
+public:
+  Hash *ContractSplit(Node *n);
+  int emit_contract(Node *n, int method);
+  int cDeclaration(Node *n);
+  int constructorDeclaration(Node *n);
+  int externDeclaration(Node *n);
+  int extendDirective(Node *n);
+  int importDirective(Node *n);
+  int includeDirective(Node *n);
+  int classDeclaration(Node *n);
+  virtual int top(Node *n);
+};
+
+static int Contract_Mode = 0;	/* contract option */
+static int InClass = 0;		/* Parsing C++ or not */
+static int InConstructor = 0;
+static Node *CurrentClass = 0;
+
+/* Set the contract mode, default is 0 (not open) */
+/* Normally set in main.cxx, when get the "-contracts" option */
+void Swig_contract_mode_set(int flag) {
+  Contract_Mode = flag;
+}
+
+/* Get the contract mode */
+int Swig_contract_mode_get() {
+  return Contract_Mode;
+}
+
+/* Apply contracts */
+void Swig_contracts(Node *n) {
+
+  Contracts *a = new Contracts;
+  a->top(n);
+  delete a;
+}
+
+/* Split the whole contract into preassertion, postassertion and others */
+Hash *Contracts::ContractSplit(Node *n) {
+
+  String *contract = Getattr(n, "feature:contract");
+  Hash *result;
+  if (!contract)
+    return NULL;
+
+  result = NewHash();
+  String *current_section = NewString("");
+  const char *current_section_name = Rules[0].section;
+  List *l = SplitLines(contract);
+
+  Iterator i;
+  for (i = First(l); i.item; i = Next(i)) {
+    int found = 0;
+    if (Strchr(i.item, '{'))
+      continue;
+    if (Strchr(i.item, '}'))
+      continue;
+    for (int j = 0; Rules[j].section; j++) {
+      if (Strstr(i.item, Rules[j].section)) {
+	if (Len(current_section)) {
+	  Setattr(result, current_section_name, current_section);
+	  current_section = Getattr(result, Rules[j].section);
+	  if (!current_section)
+	    current_section = NewString("");
+	}
+	current_section_name = Rules[j].section;
+	found = 1;
+	break;
+      }
+    }
+    if (!found)
+      Append(current_section, i.item);
+  }
+  if (Len(current_section))
+    Setattr(result, current_section_name, current_section);
+  return result;
+}
+
+/* This function looks in base classes and collects contracts found */
+void inherit_contracts(Node *c, Node *n, Hash *contracts, Hash *messages) {
+
+  Node *b, *temp;
+  String *name, *type, *local_decl, *base_decl;
+  List *bases;
+  int found = 0;
+
+  bases = Getattr(c, "bases");
+  if (!bases)
+    return;
+
+  name = Getattr(n, "name");
+  type = Getattr(n, "type");
+  local_decl = Getattr(n, "decl");
+  if (local_decl) {
+    local_decl = SwigType_typedef_resolve_all(local_decl);
+  } else {
+    return;
+  }
+  /* Width first search */
+  for (int i = 0; i < Len(bases); i++) {
+    b = Getitem(bases, i);
+    temp = firstChild(b);
+    while (temp) {
+      base_decl = Getattr(temp, "decl");
+      if (base_decl) {
+	base_decl = SwigType_typedef_resolve_all(base_decl);
+	if ((checkAttribute(temp, "storage", "virtual")) &&
+	    (checkAttribute(temp, "name", name)) && (checkAttribute(temp, "type", type)) && (!Strcmp(local_decl, base_decl))) {
+	  /* Yes, match found. */
+	  Hash *icontracts = Getattr(temp, "contract:rules");
+	  Hash *imessages = Getattr(temp, "contract:messages");
+	  found = 1;
+	  if (icontracts && imessages) {
+	    /* Add inherited contracts and messages to the contract rules above */
+	    int j = 0;
+	    for (j = 0; Rules[j].section; j++) {
+	      String *t = Getattr(contracts, Rules[j].section);
+	      String *s = Getattr(icontracts, Rules[j].section);
+	      if (s) {
+		if (t) {
+		  Insert(t, 0, "(");
+		  Printf(t, ") %s (%s)", Rules[j].combiner, s);
+		  String *m = Getattr(messages, Rules[j].section);
+		  Printf(m, " %s [%s from %s]", Rules[j].combiner, Getattr(imessages, Rules[j].section), Getattr(b, "name"));
+		} else {
+		  Setattr(contracts, Rules[j].section, NewString(s));
+		  Setattr(messages, Rules[j].section, NewStringf("[%s from %s]", Getattr(imessages, Rules[j].section), Getattr(b, "name")));
+		}
+	      }
+	    }
+	  }
+	}
+	Delete(base_decl);
+      }
+      temp = nextSibling(temp);
+    }
+  }
+  Delete(local_decl);
+  if (!found) {
+    for (int j = 0; j < Len(bases); j++) {
+      b = Getitem(bases, j);
+      inherit_contracts(b, n, contracts, messages);
+    }
+  }
+}
+
+/* This function cleans up the assertion string by removing some extraneous characters.
+   Splitting the assertion into pieces */
+
+String *Contracts::make_expression(String *s, Node *n) {
+  String *str_assert, *expr = 0;
+  List *list_assert;
+
+  str_assert = NewString(s);
+  /* Omit all useless characters and split by ; */
+  Replaceall(str_assert, "\n", "");
+  Replaceall(str_assert, "{", "");
+  Replaceall(str_assert, "}", "");
+  Replace(str_assert, " ", "", DOH_REPLACE_ANY | DOH_REPLACE_NOQUOTE);
+  Replace(str_assert, "\t", "", DOH_REPLACE_ANY | DOH_REPLACE_NOQUOTE);
+
+  list_assert = Split(str_assert, ';', -1);
+  Delete(str_assert);
+
+  /* build up new assertion */
+  str_assert = NewString("");
+  Iterator ei;
+
+  for (ei = First(list_assert); ei.item; ei = Next(ei)) {
+    expr = ei.item;
+    if (Len(expr)) {
+      Replaceid(expr, Getattr(n, "name"), "result");
+      if (Len(str_assert))
+	Append(str_assert, "&&");
+      Printf(str_assert, "(%s)", expr);
+    }
+  }
+  Delete(list_assert);
+  return str_assert;
+}
+
+/* This function substitutes parameter names for argument names in the
+   contract specification.  Note: it is assumed that the wrapper code 
+   uses arg1 for self and arg2..argn for arguments. */
+
+void Contracts::substitute_parms(String *s, ParmList *p, int method) {
+  int argnum = 1;
+  char argname[32];
+
+  if (method) {
+    Replaceid(s, "$self", "arg1");
+    argnum++;
+  }
+  while (p) {
+    sprintf(argname, "arg%d", argnum);
+    String *name = Getattr(p, "name");
+    if (name) {
+      Replaceid(s, name, argname);
+    }
+    argnum++;
+    p = nextSibling(p);
+  }
+}
+
+int Contracts::emit_contract(Node *n, int method) {
+  Hash *contracts;
+  Hash *messages;
+  String *c;
+
+  ParmList *cparms;
+
+  if (!Getattr(n, "feature:contract"))
+    return SWIG_ERROR;
+
+  /* Get contract parameters */
+  cparms = Getmeta(Getattr(n, "feature:contract"), "parms");
+
+  /*  Split contract into preassert & postassert */
+  contracts = ContractSplit(n);
+  if (!contracts)
+    return SWIG_ERROR;
+
+  /* This messages hash is used to hold the error messages that will be displayed on
+     failed contract. */
+
+  messages = NewHash();
+
+  /* Take the different contract expressions and clean them up a bit */
+  Iterator i;
+  for (i = First(contracts); i.item; i = Next(i)) {
+    String *e = make_expression(i.item, n);
+    substitute_parms(e, cparms, method);
+    Setattr(contracts, i.key, e);
+
+    /* Make a string containing error messages */
+    Setattr(messages, i.key, NewString(e));
+  }
+
+  /* If we're in a class. We need to inherit other assertions. */
+  if (InClass) {
+    inherit_contracts(CurrentClass, n, contracts, messages);
+  }
+
+  /* Save information */
+  Setattr(n, "contract:rules", contracts);
+  Setattr(n, "contract:messages", messages);
+
+  /* Okay.  Generate the contract runtime code. */
+
+  if ((c = Getattr(contracts, "require:"))) {
+    Setattr(n, "contract:preassert", NewStringf("SWIG_contract_assert(%s, \"Contract violation: require: %s\");\n", c, Getattr(messages, "require:")));
+  }
+  if ((c = Getattr(contracts, "ensure:"))) {
+    Setattr(n, "contract:postassert", NewStringf("SWIG_contract_assert(%s, \"Contract violation: ensure: %s\");\n", c, Getattr(messages, "ensure:")));
+  }
+  return SWIG_OK;
+}
+
+int Contracts::cDeclaration(Node *n) {
+  int ret = SWIG_OK;
+  String *decl = Getattr(n, "decl");
+
+  /* Not a function.  Don't even bother with it (for now) */
+  if (!SwigType_isfunction(decl))
+    return SWIG_OK;
+
+  if (Getattr(n, "feature:contract"))
+    ret = emit_contract(n, (InClass && !checkAttribute(n, "storage", "static")));
+  return ret;
+}
+
+int Contracts::constructorDeclaration(Node *n) {
+  int ret = SWIG_OK;
+  InConstructor = 1;
+  if (Getattr(n, "feature:contract"))
+    ret = emit_contract(n, 0);
+  InConstructor = 0;
+  return ret;
+}
+
+int Contracts::externDeclaration(Node *n) {
+  return emit_children(n);
+}
+int Contracts::extendDirective(Node *n) {
+  return emit_children(n);
+}
+int Contracts::importDirective(Node *n) {
+  return emit_children(n);
+}
+int Contracts::includeDirective(Node *n) {
+  return emit_children(n);
+}
+
+int Contracts::classDeclaration(Node *n) {
+  int ret = SWIG_OK;
+  InClass = 1;
+  CurrentClass = n;
+  emit_children(n);
+  InClass = 0;
+  CurrentClass = 0;
+  return ret;
+}
+
+int Contracts::top(Node *n) {
+  emit_children(n);
+  return SWIG_OK;
+}
diff --git a/trunk/Source/Modules/csharp.cxx b/trunk/Source/Modules/csharp.cxx
new file mode 100644
index 0000000..7ea1017
--- /dev/null
+++ b/trunk/Source/Modules/csharp.cxx
@@ -0,0 +1,3894 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * csharp.cxx
+ *
+ * C# language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_csharp_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include <limits.h>		// for INT_MAX
+#include "cparse.h"
+#include <ctype.h>
+
+/* Hash type used for upcalls from C/C++ */
+typedef DOH UpcallData;
+
+class CSHARP:public Language {
+  static const char *usage;
+  const String *empty_string;
+  const String *public_string;
+  const String *protected_string;
+
+  Hash *swig_types_hash;
+  File *f_runtime;
+  File *f_runtime_h;
+  File *f_header;
+  File *f_wrappers;
+  File *f_init;
+  File *f_directors;
+  File *f_directors_h;
+  List *filenames_list;
+
+  bool proxy_flag;		// Flag for generating proxy classes
+  bool native_function_flag;	// Flag for when wrapping a native function
+  bool enum_constant_flag;	// Flag for when wrapping an enum or constant
+  bool static_flag;		// Flag for when wrapping a static functions or member variables
+  bool variable_wrapper_flag;	// Flag for when wrapping a nonstatic member variable
+  bool wrapping_member_flag;	// Flag for when wrapping a member variable/enum/const
+  bool global_variable_flag;	// Flag for when wrapping a global variable
+  bool old_variable_names;	// Flag for old style variable names in the intermediary class
+  bool generate_property_declaration_flag;	// Flag for generating properties
+
+  String *imclass_name;		// intermediary class name
+  String *module_class_name;	// module class name
+  String *imclass_class_code;	// intermediary class code
+  String *proxy_class_def;
+  String *proxy_class_code;
+  String *module_class_code;
+  String *proxy_class_name;
+  String *variable_name;	//Name of a variable being wrapped
+  String *proxy_class_constants_code;
+  String *module_class_constants_code;
+  String *enum_code;
+  String *dllimport;		// DllImport attribute name
+  String *namespce;		// Optional namespace name
+  String *imclass_imports;	//intermediary class imports from %pragma
+  String *module_imports;	//module imports from %pragma
+  String *imclass_baseclass;	//inheritance for intermediary class class from %pragma
+  String *module_baseclass;	//inheritance for module class from %pragma
+  String *imclass_interfaces;	//interfaces for intermediary class class from %pragma
+  String *module_interfaces;	//interfaces for module class from %pragma
+  String *imclass_class_modifiers;	//class modifiers for intermediary class overriden by %pragma
+  String *module_class_modifiers;	//class modifiers for module class overriden by %pragma
+  String *upcasts_code;		//C++ casts for inheritance hierarchies C++ code
+  String *imclass_cppcasts_code;	//C++ casts up inheritance hierarchies intermediary class code
+  String *director_callback_typedefs;	// Director function pointer typedefs for callbacks
+  String *director_callbacks;	// Director callback function pointer member variables
+  String *director_delegate_callback;	// Director callback method that delegates are set to call
+  String *director_delegate_definitions;	// Director delegates definitions in proxy class
+  String *director_delegate_instances;	// Director delegates member variables in proxy class
+  String *director_method_types;	// Director method types
+  String *director_connect_parms;	// Director delegates parameter list for director connect call
+  String *destructor_call;	//C++ destructor call if any
+
+  // Director method stuff:
+  List *dmethods_seq;
+  Hash *dmethods_table;
+  int n_dmethods;
+  int n_directors;
+  int first_class_dmethod;
+  int curr_class_dmethod;
+
+  enum EnumFeature { SimpleEnum, TypeunsafeEnum, TypesafeEnum, ProperEnum };
+
+  static Parm *NewParmFromNode(SwigType *type, const String_or_char *name, Node *n) {
+    Parm *p = NewParm(type, name);
+    Setfile(p, Getfile(n));
+    Setline(p, Getline(n));
+    return p;
+  }
+
+public:
+
+  /* -----------------------------------------------------------------------------
+   * CSHARP()
+   * ----------------------------------------------------------------------------- */
+
+   CSHARP():empty_string(NewString("")),
+      public_string(NewString("public")),
+      protected_string(NewString("protected")),
+      swig_types_hash(NULL),
+      f_runtime(NULL),
+      f_runtime_h(NULL),
+      f_header(NULL),
+      f_wrappers(NULL),
+      f_init(NULL),
+      f_directors(NULL),
+      f_directors_h(NULL),
+      filenames_list(NULL),
+      proxy_flag(true),
+      native_function_flag(false),
+      enum_constant_flag(false),
+      static_flag(false),
+      variable_wrapper_flag(false),
+      wrapping_member_flag(false),
+      global_variable_flag(false),
+      old_variable_names(false),
+      generate_property_declaration_flag(false),
+      imclass_name(NULL),
+      module_class_name(NULL),
+      imclass_class_code(NULL),
+      proxy_class_def(NULL),
+      proxy_class_code(NULL),
+      module_class_code(NULL),
+      proxy_class_name(NULL),
+      variable_name(NULL),
+      proxy_class_constants_code(NULL),
+      module_class_constants_code(NULL),
+      enum_code(NULL),
+      dllimport(NULL),
+      namespce(NULL),
+      imclass_imports(NULL),
+      module_imports(NULL),
+      imclass_baseclass(NULL),
+      module_baseclass(NULL),
+      imclass_interfaces(NULL),
+      module_interfaces(NULL),
+      imclass_class_modifiers(NULL),
+      module_class_modifiers(NULL),
+      upcasts_code(NULL),
+      imclass_cppcasts_code(NULL),
+      director_callback_typedefs(NULL),
+      director_callbacks(NULL),
+      director_delegate_callback(NULL),
+      director_delegate_definitions(NULL),
+      director_delegate_instances(NULL),
+      director_method_types(NULL),
+      director_connect_parms(NULL),
+      destructor_call(NULL),
+      dmethods_seq(NULL),
+      dmethods_table(NULL),
+      n_dmethods(0),
+      n_directors(0) {
+    /* for now, multiple inheritance in directors is disabled, this
+       should be easy to implement though */
+    director_multiple_inheritance = 0;
+    director_language = 1;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getProxyName()
+   *
+   * Test to see if a type corresponds to something wrapped with a proxy class
+   * Return NULL if not otherwise the proxy class name
+   * ----------------------------------------------------------------------------- */
+  
+   String *getProxyName(SwigType *t) {
+    if (proxy_flag) {
+      Node *n = classLookup(t);
+      if (n) {
+	return Getattr(n, "sym:name");
+      }
+    }
+    return NULL;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * directorClassName()
+   * ----------------------------------------------------------------------------- */
+
+  String *directorClassName(Node *n) {
+    String *dirclassname;
+    const char *attrib = "director:classname";
+
+    if (!(dirclassname = Getattr(n, attrib))) {
+      String *classname = Getattr(n, "sym:name");
+
+      dirclassname = NewStringf("SwigDirector_%s", classname);
+      Setattr(n, attrib, dirclassname);
+    }
+
+    return dirclassname;
+  }
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+
+    SWIG_library_directory("csharp");
+
+    // Look for certain command line options
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-dllimport") == 0) {
+	  if (argv[i + 1]) {
+	    dllimport = NewString("");
+	    Printf(dllimport, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-namespace") == 0) {
+	  if (argv[i + 1]) {
+	    namespce = NewString("");
+	    Printf(namespce, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if ((strcmp(argv[i], "-noproxy") == 0)) {
+	  Swig_mark_arg(i);
+	  proxy_flag = false;
+	} else if (strcmp(argv[i], "-oldvarnames") == 0) {
+	  Swig_mark_arg(i);
+	  old_variable_names = true;
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  Printf(stdout, "%s\n", usage);
+	}
+      }
+    }
+
+    // Add a symbol to the parser for conditional compilation
+    Preprocessor_define("SWIGCSHARP 1", 0);
+
+    // Add typemap definitions
+    SWIG_typemap_lang("csharp");
+    SWIG_config_file("csharp.swg");
+
+    allow_overloading();
+  }
+
+  /* ---------------------------------------------------------------------
+   * top()
+   * --------------------------------------------------------------------- */
+
+  virtual int top(Node *n) {
+
+    // Get any options set in the module directive
+    Node *optionsnode = Getattr(Getattr(n, "module"), "options");
+
+    if (optionsnode) {
+      if (Getattr(optionsnode, "imclassname"))
+	imclass_name = Copy(Getattr(optionsnode, "imclassname"));
+      /* check if directors are enabled for this module.  note: this 
+       * is a "master" switch, without which no director code will be
+       * emitted.  %feature("director") statements are also required
+       * to enable directors for individual classes or methods.
+       *
+       * use %module(directors="1") modulename at the start of the 
+       * interface file to enable director generation.
+       */
+      if (Getattr(optionsnode, "directors")) {
+	allow_directors();
+      }
+      if (Getattr(optionsnode, "dirprot")) {
+	allow_dirprot();
+      }
+      allow_allprotected(GetFlag(optionsnode, "allprotected"));
+    }
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+    String *outfile_h = Getattr(n, "outfile_h");
+
+    if (!outfile) {
+      Printf(stderr, "Unable to determine outfile\n");
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    if (directorsEnabled()) {
+      if (!outfile_h) {
+        Printf(stderr, "Unable to determine outfile_h\n");
+        SWIG_exit(EXIT_FAILURE);
+      }
+      f_runtime_h = NewFile(outfile_h, "w");
+      if (!f_runtime_h) {
+	FileErrorDisplay(outfile_h);
+	SWIG_exit(EXIT_FAILURE);
+      }
+    }
+
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+    f_directors_h = NewString("");
+    f_directors = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("director", f_directors);
+    Swig_register_filebyname("director_h", f_directors_h);
+
+    swig_types_hash = NewHash();
+    filenames_list = NewList();
+
+    // Make the intermediary class and module class names. The intermediary class name can be set in the module directive.
+    if (!imclass_name) {
+      imclass_name = NewStringf("%sPINVOKE", Getattr(n, "name"));
+      module_class_name = Copy(Getattr(n, "name"));
+    } else {
+      // Rename the module name if it is the same as intermediary class name - a backwards compatibility solution
+      if (Cmp(imclass_name, Getattr(n, "name")) == 0)
+	module_class_name = NewStringf("%sModule", Getattr(n, "name"));
+      else
+	module_class_name = Copy(Getattr(n, "name"));
+    }
+
+    imclass_class_code = NewString("");
+    proxy_class_def = NewString("");
+    proxy_class_code = NewString("");
+    module_class_constants_code = NewString("");
+    imclass_baseclass = NewString("");
+    imclass_interfaces = NewString("");
+    imclass_class_modifiers = NewString("");
+    module_class_code = NewString("");
+    module_baseclass = NewString("");
+    module_interfaces = NewString("");
+    module_imports = NewString("");
+    module_class_modifiers = NewString("");
+    imclass_imports = NewString("");
+    imclass_cppcasts_code = NewString("");
+    director_connect_parms = NewString("");
+    upcasts_code = NewString("");
+    dmethods_seq = NewList();
+    dmethods_table = NewHash();
+    n_dmethods = 0;
+    n_directors = 0;
+    if (!namespce)
+      namespce = NewString("");
+    if (!dllimport)
+      dllimport = Copy(module_class_name);
+
+    Swig_banner(f_runtime);	// Print the SWIG banner message
+
+    if (directorsEnabled()) {
+      Printf(f_runtime, "#define SWIG_DIRECTORS\n");
+
+      /* Emit initial director header and director code: */
+      Swig_banner(f_directors_h);
+      Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module_class_name);
+      Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module_class_name);
+
+      Printf(f_directors, "\n\n");
+      Printf(f_directors, "/* ---------------------------------------------------\n");
+      Printf(f_directors, " * C++ director class methods\n");
+      Printf(f_directors, " * --------------------------------------------------- */\n\n");
+      if (outfile_h)
+	Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h));
+    }
+
+    Swig_name_register((char *) "wrapper", (char *) "CSharp_%f");
+    if (old_variable_names) {
+      Swig_name_register((char *) "set", (char *) "set_%v");
+      Swig_name_register((char *) "get", (char *) "get_%v");
+    }
+
+    Printf(f_wrappers, "\n#ifdef __cplusplus\n");
+    Printf(f_wrappers, "extern \"C\" {\n");
+    Printf(f_wrappers, "#endif\n\n");
+
+    /* Emit code */
+    Language::top(n);
+
+    if (directorsEnabled()) {
+      // Insert director runtime into the f_runtime file (make it occur before %header section)
+      Swig_insert_file("director.swg", f_runtime);
+    }
+    // Generate the intermediary class
+    {
+      String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), imclass_name);
+      File *f_im = NewFile(filen, "w");
+      if (!f_im) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the intermediary class file
+      emitBanner(f_im);
+
+      addOpenNamespace(namespce, f_im);
+
+      if (imclass_imports)
+	Printf(f_im, "%s\n", imclass_imports);
+
+      if (Len(imclass_class_modifiers) > 0)
+	Printf(f_im, "%s ", imclass_class_modifiers);
+      Printf(f_im, "%s ", imclass_name);
+
+      if (imclass_baseclass && *Char(imclass_baseclass))
+	Printf(f_im, ": %s ", imclass_baseclass);
+      if (Len(imclass_interfaces) > 0)
+	Printv(f_im, "implements ", imclass_interfaces, " ", NIL);
+      Printf(f_im, "{\n");
+
+      // Add the intermediary class methods
+      Replaceall(imclass_class_code, "$module", module_class_name);
+      Replaceall(imclass_class_code, "$imclassname", imclass_name);
+      Replaceall(imclass_class_code, "$dllimport", dllimport);
+      Printv(f_im, imclass_class_code, NIL);
+      Printv(f_im, imclass_cppcasts_code, NIL);
+
+      // Finish off the class
+      Printf(f_im, "}\n");
+      addCloseNamespace(namespce, f_im);
+
+      Close(f_im);
+    }
+
+    // Generate the C# module class
+    {
+      String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), module_class_name);
+      File *f_module = NewFile(filen, "w");
+      if (!f_module) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the module class file
+      emitBanner(f_module);
+
+      addOpenNamespace(namespce, f_module);
+
+      if (module_imports)
+	Printf(f_module, "%s\n", module_imports);
+
+      if (Len(module_class_modifiers) > 0)
+	Printf(f_module, "%s ", module_class_modifiers);
+      Printf(f_module, "%s ", module_class_name);
+
+      if (module_baseclass && *Char(module_baseclass))
+	Printf(f_module, ": %s ", module_baseclass);
+      if (Len(module_interfaces) > 0)
+	Printv(f_module, "implements ", module_interfaces, " ", NIL);
+      Printf(f_module, "{\n");
+
+      Replaceall(module_class_code, "$module", module_class_name);
+      Replaceall(module_class_constants_code, "$module", module_class_name);
+
+      Replaceall(module_class_code, "$imclassname", imclass_name);
+      Replaceall(module_class_constants_code, "$imclassname", imclass_name);
+
+      Replaceall(module_class_code, "$dllimport", dllimport);
+      Replaceall(module_class_constants_code, "$dllimport", dllimport);
+
+      // Add the wrapper methods
+      Printv(f_module, module_class_code, NIL);
+
+      // Write out all the global constants
+      Printv(f_module, module_class_constants_code, NIL);
+
+      // Finish off the class
+      Printf(f_module, "}\n");
+      addCloseNamespace(namespce, f_module);
+
+      Close(f_module);
+    }
+
+    if (upcasts_code)
+      Printv(f_wrappers, upcasts_code, NIL);
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n");
+    Printf(f_wrappers, "}\n");
+    Printf(f_wrappers, "#endif\n");
+
+    // Output a C# type wrapper class for each SWIG type
+    for (Iterator swig_type = First(swig_types_hash); swig_type.key; swig_type = Next(swig_type)) {
+      emitTypeWrapperClass(swig_type.key, swig_type.item);
+    }
+
+    // Check for overwriting file problems on filesystems that are case insensitive
+    Iterator it1;
+    Iterator it2;
+    for (it1 = First(filenames_list); it1.item; it1 = Next(it1)) {
+      String *item1_lower = Swig_string_lower(it1.item);
+      for (it2 = Next(it1); it2.item; it2 = Next(it2)) {
+	String *item2_lower = Swig_string_lower(it2.item);
+	if (it1.item && it2.item) {
+	  if (Strcmp(item1_lower, item2_lower) == 0) {
+	    Swig_warning(WARN_LANG_PORTABILITY_FILENAME, input_file, line_number,
+			 "Portability warning: File %s will be overwritten by %s on case insensitive filesystems such as "
+			 "Windows' FAT32 and NTFS unless the class/module name is renamed\n", it1.item, it2.item);
+	  }
+	}
+	Delete(item2_lower);
+      }
+      Delete(item1_lower);
+    }
+
+    Delete(swig_types_hash);
+    swig_types_hash = NULL;
+    Delete(filenames_list);
+    filenames_list = NULL;
+    Delete(imclass_name);
+    imclass_name = NULL;
+    Delete(imclass_class_code);
+    imclass_class_code = NULL;
+    Delete(proxy_class_def);
+    proxy_class_def = NULL;
+    Delete(proxy_class_code);
+    proxy_class_code = NULL;
+    Delete(module_class_constants_code);
+    module_class_constants_code = NULL;
+    Delete(imclass_baseclass);
+    imclass_baseclass = NULL;
+    Delete(imclass_interfaces);
+    imclass_interfaces = NULL;
+    Delete(imclass_class_modifiers);
+    imclass_class_modifiers = NULL;
+    Delete(module_class_name);
+    module_class_name = NULL;
+    Delete(module_class_code);
+    module_class_code = NULL;
+    Delete(module_baseclass);
+    module_baseclass = NULL;
+    Delete(module_interfaces);
+    module_interfaces = NULL;
+    Delete(module_imports);
+    module_imports = NULL;
+    Delete(module_class_modifiers);
+    module_class_modifiers = NULL;
+    Delete(imclass_imports);
+    imclass_imports = NULL;
+    Delete(imclass_cppcasts_code);
+    imclass_cppcasts_code = NULL;
+    Delete(upcasts_code);
+    upcasts_code = NULL;
+    Delete(dmethods_seq);
+    dmethods_seq = NULL;
+    Delete(dmethods_table);
+    dmethods_table = NULL;
+    Delete(namespce);
+    namespce = NULL;
+    n_dmethods = 0;
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+
+    if (directorsEnabled()) {
+      Dump(f_directors, f_runtime);
+      Dump(f_directors_h, f_runtime_h);
+
+      Printf(f_runtime_h, "\n");
+      Printf(f_runtime_h, "#endif\n");
+
+      Close(f_runtime_h);
+      Delete(f_runtime_h);
+      f_runtime_h = NULL;
+      Delete(f_directors);
+      f_directors = NULL;
+      Delete(f_directors_h);
+      f_directors_h = NULL;
+    }
+
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitBanner()
+   * ----------------------------------------------------------------------------- */
+
+  void emitBanner(File *f) {
+    Printf(f, "/* ----------------------------------------------------------------------------\n");
+    Printf(f, " * This file was automatically generated by SWIG (http://www.swig.org).\n");
+    Printf(f, " * Version %s\n", Swig_package_version());
+    Printf(f, " *\n");
+    Printf(f, " * Do not make changes to this file unless you know what you are doing--modify\n");
+    Printf(f, " * the SWIG interface file instead.\n");
+    Printf(f, " * ----------------------------------------------------------------------------- */\n\n");
+  }
+
+  /*-----------------------------------------------------------------------
+   * Add new director upcall signature
+   *----------------------------------------------------------------------*/
+
+  UpcallData *addUpcallMethod(String *imclass_method, String *class_method, String *decl, String *overloaded_name) {
+    UpcallData *udata;
+    String *imclass_methodidx;
+    String *class_methodidx;
+    Hash *new_udata;
+    String *key = NewStringf("%s|%s", imclass_method, decl);
+
+    ++curr_class_dmethod;
+
+    /* Do we know about this director class already? */
+    if ((udata = Getattr(dmethods_table, key))) {
+      Delete(key);
+      return Getattr(udata, "methodoff");
+    }
+
+    imclass_methodidx = NewStringf("%d", n_dmethods);
+    class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod);
+    n_dmethods++;
+
+    new_udata = NewHash();
+    Append(dmethods_seq, new_udata);
+    Setattr(dmethods_table, key, new_udata);
+
+    Setattr(new_udata, "method", Copy(class_method));
+    // TODO: remove fdesc
+//    Setattr(new_udata, "fdesc", Copy(class_desc));
+//    Setattr(new_udata, "imclass_method", Copy(imclass_method));
+//    Setattr(new_udata, "imclass_methodidx", imclass_methodidx);
+    Setattr(new_udata, "class_methodidx", class_methodidx);
+    Setattr(new_udata, "decl", Copy(decl));
+    Setattr(new_udata, "overname", Copy(overloaded_name));
+
+    Delete(key);
+    return new_udata;
+  }
+
+  /*-----------------------------------------------------------------------
+   * Get director upcall signature
+   *----------------------------------------------------------------------*/
+
+  /*
+     UpcallData * getUpcallMethodData(String *director_class, String *decl) {
+     String             *key = NewStringf("%s|%s", director_class, decl);
+     UpcallData         *udata = Getattr(dmethods_table, key);
+
+     Delete(key);
+     return udata;
+     }
+   */
+
+  /* ----------------------------------------------------------------------
+   * nativeWrapper()
+   * ---------------------------------------------------------------------- */
+
+  virtual int nativeWrapper(Node *n) {
+    String *wrapname = Getattr(n, "wrap:name");
+
+    if (!addSymbol(wrapname, n))
+      return SWIG_ERROR;
+
+    if (Getattr(n, "type")) {
+      Swig_save("nativeWrapper", n, "name", NIL);
+      Setattr(n, "name", wrapname);
+      native_function_flag = true;
+      functionWrapper(n);
+      Swig_restore(n);
+      native_function_flag = false;
+    } else {
+      Printf(stderr, "%s : Line %d. No return type for %%native method %s.\n", input_file, line_number, Getattr(n, "wrap:name"));
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * functionWrapper()
+   * ---------------------------------------------------------------------- */
+
+  virtual int functionWrapper(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    Parm *p;
+    int i;
+    String *c_return_type = NewString("");
+    String *im_return_type = NewString("");
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *body = NewString("");
+    String *im_outattributes = 0;
+    int num_arguments = 0;
+    int num_required = 0;
+    bool is_void_return;
+    String *overloaded_name = getOverloadedName(n);
+
+    if (!Getattr(n, "sym:overloaded")) {
+      if (!addSymbol(Getattr(n, "sym:name"), n))
+	return SWIG_ERROR;
+    }
+
+    /*
+       The rest of this function deals with generating the intermediary class wrapper function (that wraps
+       a c/c++ function) and generating the PInvoke c code. Each C# wrapper function has a 
+       matching PInvoke c function call.
+     */
+
+    // A new wrapper function object
+    Wrapper *f = NewWrapper();
+
+    // Make a wrapper name for this function
+    String *wname = Swig_name_wrapper(overloaded_name);
+
+    /* Attach the non-standard typemaps to the parameter list. */
+    Swig_typemap_attach_parms("ctype", l, f);
+    Swig_typemap_attach_parms("imtype", l, f);
+
+    /* Get return types */
+    if ((tm = Swig_typemap_lookup("ctype", n, "", 0))) {
+      String *ctypeout = Getattr(n, "tmap:ctype:out");	// the type in the ctype typemap's out attribute overrides the type in the typemap
+      if (ctypeout)
+	tm = ctypeout;
+      Printf(c_return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CTYPE_UNDEF, input_file, line_number, "No ctype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    if ((tm = Swig_typemap_lookup("imtype", n, "", 0))) {
+      String *imtypeout = Getattr(n, "tmap:imtype:out");	// the type in the imtype typemap's out attribute overrides the type in the typemap
+      if (imtypeout)
+	tm = imtypeout;
+      Printf(im_return_type, "%s", tm);
+      im_outattributes = Getattr(n, "tmap:imtype:outattributes");
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CSTYPE_UNDEF, input_file, line_number, "No imtype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    is_void_return = (Cmp(c_return_type, "void") == 0);
+    if (!is_void_return)
+      Wrapper_add_localv(f, "jresult", c_return_type, "jresult", NIL);
+
+    Printv(f->def, " SWIGEXPORT ", c_return_type, " SWIGSTDCALL ", wname, "(", NIL);
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+
+    // Parameter overloading
+    Setattr(n, "wrap:parms", l);
+    Setattr(n, "wrap:name", wname);
+
+    // Wrappers not wanted for some methods where the parameters cannot be overloaded in C#
+    if (Getattr(n, "sym:overloaded")) {
+      // Emit warnings for the few cases that can't be overloaded in C# and give up on generating wrapper
+      Swig_overload_check(n);
+      if (Getattr(n, "overload:ignore"))
+	return SWIG_OK;
+    }
+
+    Printv(imclass_class_code, "\n  [DllImport(\"", dllimport, "\", EntryPoint=\"CSharp_", overloaded_name, "\")]\n", NIL);
+
+    if (im_outattributes)
+      Printf(imclass_class_code, "  %s\n", im_outattributes);
+
+    Printf(imclass_class_code, "  public static extern %s %s(", im_return_type, overloaded_name);
+
+
+    /* Get number of required and total arguments */
+    num_arguments = emit_num_arguments(l);
+    num_required = emit_num_required(l);
+    int gencomma = 0;
+
+    // Now walk the function parameter list and generate code to get arguments
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+      String *im_param_type = NewString("");
+      String *c_param_type = NewString("");
+      String *arg = NewString("");
+
+      Printf(arg, "j%s", ln);
+
+      /* Get the ctype types of the parameter */
+      if ((tm = Getattr(p, "tmap:ctype"))) {
+	Printv(c_param_type, tm, NIL);
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CTYPE_UNDEF, input_file, line_number, "No ctype typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      /* Get the intermediary class parameter types of the parameter */
+      if ((tm = Getattr(p, "tmap:imtype"))) {
+	const String *inattributes = Getattr(p, "tmap:imtype:inattributes");
+	Printf(im_param_type, "%s%s", inattributes ? inattributes : empty_string, tm);
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CSTYPE_UNDEF, input_file, line_number, "No imtype typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      /* Add parameter to intermediary class method */
+      if (gencomma)
+	Printf(imclass_class_code, ", ");
+      Printf(imclass_class_code, "%s %s", im_param_type, arg);
+
+      // Add parameter to C function
+      Printv(f->def, gencomma ? ", " : "", c_param_type, " ", arg, NIL);
+
+      gencomma = 1;
+
+      // Get typemap for this argument
+      if ((tm = Getattr(p, "tmap:in"))) {
+	canThrow(n, "in", p);
+	Replaceall(tm, "$source", arg);	/* deprecated */
+	Replaceall(tm, "$target", ln);	/* deprecated */
+	Replaceall(tm, "$arg", arg);	/* deprecated? */
+	Replaceall(tm, "$input", arg);
+	Setattr(p, "emit:input", arg);
+	Printf(f->code, "%s\n", tm);
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+	p = nextSibling(p);
+      }
+      Delete(im_param_type);
+      Delete(c_param_type);
+      Delete(arg);
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	canThrow(n, "check", p);
+	Replaceall(tm, "$target", Getattr(p, "lname"));	/* deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	canThrow(n, "freearg", p);
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	canThrow(n, "argout", p);
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* deprecated */
+	Replaceall(tm, "$target", Getattr(p, "lname"));	/* deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	Replaceall(tm, "$result", "jresult");
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Get any C# exception classes in the throws typemap
+    ParmList *throw_parm_list = NULL;
+    if ((throw_parm_list = Getattr(n, "throws"))) {
+      Swig_typemap_attach_parms("throws", throw_parm_list, f);
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	if ((tm = Getattr(p, "tmap:throws"))) {
+	  canThrow(n, "throws", p);
+	}
+      }
+    }
+
+    String *null_attribute = 0;
+    // Now write code to make the function call
+    if (!native_function_flag) {
+      if (Cmp(nodeType(n), "constant") == 0) {
+        // Wrapping a constant hack
+        Swig_save("functionWrapper", n, "wrap:action", NIL);
+
+        // below based on Swig_VargetToFunction()
+        SwigType *ty = Swig_wrapped_var_type(Getattr(n, "type"), use_naturalvar_mode(n));
+        Setattr(n, "wrap:action", NewStringf("result = (%s) %s;", SwigType_lstr(ty, 0), Getattr(n, "value")));
+      }
+
+      Swig_director_emit_dynamic_cast(n, f);
+      String *actioncode = emit_action(n);
+
+      if (Cmp(nodeType(n), "constant") == 0)
+        Swig_restore(n);
+
+      /* Return value if necessary  */
+      if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+	canThrow(n, "out", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Replaceall(tm, "$target", "jresult");	/* deprecated */
+	Replaceall(tm, "$result", "jresult");
+
+        if (GetFlag(n, "feature:new"))
+          Replaceall(tm, "$owner", "1");
+        else
+          Replaceall(tm, "$owner", "0");
+
+	Printf(f->code, "%s", tm);
+	null_attribute = Getattr(n, "tmap:out:null");
+	if (Len(tm))
+	  Printf(f->code, "\n");
+      } else {
+	Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(t, 0), Getattr(n, "name"));
+      }
+      emit_return_variable(n, t, f);
+    }
+
+    /* Output argument output code */
+    Printv(f->code, outarg, NIL);
+
+    /* Output cleanup code */
+    Printv(f->code, cleanup, NIL);
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	canThrow(n, "newfree", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if (!native_function_flag) {
+      if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+	canThrow(n, "ret", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* Finish C function and intermediary class function definitions */
+    Printf(imclass_class_code, ")");
+    Printf(imclass_class_code, ";\n");
+
+    Printf(f->def, ") {");
+
+    if (!is_void_return)
+      Printv(f->code, "    return jresult;\n", NIL);
+    Printf(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", symname);
+
+    /* Contract macro modification */
+    if (Replaceall(f->code, "SWIG_contract_assert(", "SWIG_contract_assert($null, ") > 0) {
+      Setattr(n, "csharp:canthrow", "1");
+    }
+
+    if (!null_attribute)
+      Replaceall(f->code, "$null", "0");
+    else
+      Replaceall(f->code, "$null", null_attribute);
+
+    /* Dump the function out */
+    if (!native_function_flag) {
+      Wrapper_print(f, f_wrappers);
+
+      // Handle %csexception which sets the canthrow attribute
+      if (Getattr(n, "feature:except:canthrow"))
+	Setattr(n, "csharp:canthrow", "1");
+
+      // A very simple check (it is not foolproof) to help typemap/feature writers for
+      // throwing C# exceptions from unmanaged code. It checks for the common methods which
+      // set a pending C# exception... the 'canthrow' typemap/feature attribute must be set
+      // so that code which checks for pending exceptions is added in the C# proxy method.
+      if (!Getattr(n, "csharp:canthrow")) {
+	if (Strstr(f->code, "SWIG_exception")) {
+	  Swig_warning(WARN_CSHARP_CANTHROW, input_file, line_number,
+		       "Unmanaged code contains a call to SWIG_exception and C# code does not handle pending exceptions via the canthrow attribute.\n");
+	} else if (Strstr(f->code, "SWIG_CSharpSetPendingException")) {
+	  Swig_warning(WARN_CSHARP_CANTHROW, input_file, line_number,
+		       "Unmanaged code contains a call to a SWIG_CSharpSetPendingException method and C# code does not handle pending exceptions via the canthrow attribute.\n");
+	}
+      }
+    }
+
+    if (!(proxy_flag && is_wrapping_class()) && !enum_constant_flag) {
+      moduleClassFunctionHandler(n);
+    }
+
+    /* 
+     * Generate the proxy class properties for public member variables.
+     * Not for enums and constants.
+     */
+    if (proxy_flag && wrapping_member_flag && !enum_constant_flag) {
+      // Capitalize the first letter in the variable in the getter/setter function name
+      bool getter_flag = Cmp(symname, Swig_name_set(Swig_name_member(proxy_class_name, variable_name))) != 0;
+
+      String *getter_setter_name = NewString("");
+      if (!getter_flag)
+	Printf(getter_setter_name, "set");
+      else
+	Printf(getter_setter_name, "get");
+      Putc(toupper((int) *Char(variable_name)), getter_setter_name);
+      Printf(getter_setter_name, "%s", Char(variable_name) + 1);
+
+      Setattr(n, "proxyfuncname", getter_setter_name);
+      Setattr(n, "imfuncname", symname);
+
+      proxyClassFunctionHandler(n);
+      Delete(getter_setter_name);
+    }
+
+    Delete(c_return_type);
+    Delete(im_return_type);
+    Delete(cleanup);
+    Delete(outarg);
+    Delete(body);
+    Delete(overloaded_name);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * variableWrapper()
+   * ----------------------------------------------------------------------- */
+
+  virtual int variableWrapper(Node *n) {
+    Language::variableWrapper(n);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * globalvariableHandler()
+   * ------------------------------------------------------------------------ */
+
+  virtual int globalvariableHandler(Node *n) {
+
+    generate_property_declaration_flag = true;
+    variable_name = Getattr(n, "sym:name");
+    global_variable_flag = true;
+    int ret = Language::globalvariableHandler(n);
+    global_variable_flag = false;
+    generate_property_declaration_flag = false;
+
+    if (proxy_flag) {
+      Printf(module_class_code, "\n  }\n\n");
+    }
+
+    return ret;
+  }
+
+  /* ----------------------------------------------------------------------
+   * enumDeclaration()
+   *
+   * C/C++ enums can be mapped in one of 4 ways, depending on the cs:enum feature specified:
+   * 1) Simple enums - simple constant within the proxy class or module class
+   * 2) Typeunsafe enums - simple constant in a C# class (class named after the c++ enum name)
+   * 3) Typesafe enum - typesafe enum pattern (class named after the c++ enum name)
+   * 4) Proper enums - proper C# enum
+   * Anonymous enums always default to 1)
+   * ---------------------------------------------------------------------- */
+
+  virtual int enumDeclaration(Node *n) {
+
+    if (!ImportMode) {
+      if (getCurrentClass() && (cplus_mode != PUBLIC))
+	return SWIG_NOWRAP;
+
+      enum_code = NewString("");
+      String *symname = Getattr(n, "sym:name");
+      String *constants_code = (proxy_flag && is_wrapping_class())? proxy_class_constants_code : module_class_constants_code;
+      EnumFeature enum_feature = decodeEnumFeature(n);
+      String *typemap_lookup_type = Getattr(n, "name");
+
+      if ((enum_feature != SimpleEnum) && symname && typemap_lookup_type) {
+	// Wrap (non-anonymous) C/C++ enum within a typesafe, typeunsafe or proper C# enum
+
+	// Pure C# baseclass and interfaces
+	const String *pure_baseclass = typemapLookup("csbase", typemap_lookup_type, WARN_NONE);
+	const String *pure_interfaces = typemapLookup("csinterfaces", typemap_lookup_type, WARN_NONE);
+
+	// Class attributes
+	const String *csattributes = typemapLookup("csattributes", typemap_lookup_type, WARN_NONE);
+	if (csattributes && *Char(csattributes))
+	  Printf(enum_code, "%s\n", csattributes);
+
+	// Emit the enum
+	Printv(enum_code, typemapLookup("csclassmodifiers", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers (enum modifiers really)
+	       " ", symname, (*Char(pure_baseclass) || *Char(pure_interfaces)) ? " : " : "", pure_baseclass, ((*Char(pure_baseclass)) && *Char(pure_interfaces)) ?	// Interfaces
+	       ", " : "", pure_interfaces, " {\n", NIL);
+      } else {
+	// Wrap C++ enum with integers - just indicate start of enum with a comment, no comment for anonymous enums of any sort
+	if (symname && !Getattr(n, "unnamedinstance"))
+	  Printf(constants_code, "  // %s \n", symname);
+      }
+
+      // Emit each enum item
+      Language::enumDeclaration(n);
+
+      if ((enum_feature != SimpleEnum) && symname && typemap_lookup_type) {
+	// Wrap (non-anonymous) C/C++ enum within a typesafe, typeunsafe or proper C# enum
+	// Finish the enum declaration
+	// Typemaps are used to generate the enum definition in a similar manner to proxy classes.
+	Printv(enum_code, (enum_feature == ProperEnum) ? "\n" : typemapLookup("csbody", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF),	// main body of class
+	       typemapLookup("cscode", typemap_lookup_type, WARN_NONE),	// extra C# code
+	       "}", NIL);
+
+	Replaceall(enum_code, "$csclassname", symname);
+
+	// Substitute $enumvalues - intended usage is for typesafe enums
+	if (Getattr(n, "enumvalues"))
+	  Replaceall(enum_code, "$enumvalues", Getattr(n, "enumvalues"));
+	else
+	  Replaceall(enum_code, "$enumvalues", "");
+
+	if (proxy_flag && is_wrapping_class()) {
+	  // Enums defined within the C++ class are defined within the proxy class
+
+	  // Add extra indentation
+	  Replaceall(enum_code, "\n", "\n  ");
+	  Replaceall(enum_code, "  \n", "\n");
+
+	  Printv(proxy_class_constants_code, "  ", enum_code, "\n\n", NIL);
+	} else {
+	  // Global enums are defined in their own file
+	  String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), symname);
+	  File *f_enum = NewFile(filen, "w");
+	  if (!f_enum) {
+	    FileErrorDisplay(filen);
+	    SWIG_exit(EXIT_FAILURE);
+	  }
+	  Append(filenames_list, Copy(filen));
+	  Delete(filen);
+	  filen = NULL;
+
+	  // Start writing out the enum file
+	  emitBanner(f_enum);
+
+	  addOpenNamespace(namespce, f_enum);
+
+	  Printv(f_enum, typemapLookup("csimports", typemap_lookup_type, WARN_NONE),	// Import statements
+		 "\n", enum_code, "\n", NIL);
+
+	  addCloseNamespace(namespce, f_enum);
+
+	  Close(f_enum);
+	}
+      } else {
+	// Wrap C++ enum with simple constant
+	Printf(enum_code, "\n");
+	if (proxy_flag && is_wrapping_class())
+	  Printv(proxy_class_constants_code, enum_code, NIL);
+	else
+	  Printv(module_class_constants_code, enum_code, NIL);
+      }
+
+      Delete(enum_code);
+      enum_code = NULL;
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * enumvalueDeclaration()
+   * ---------------------------------------------------------------------- */
+
+  virtual int enumvalueDeclaration(Node *n) {
+    if (getCurrentClass() && (cplus_mode != PUBLIC))
+      return SWIG_NOWRAP;
+
+    Swig_require("enumvalueDeclaration", n, "*name", "?value", NIL);
+    String *symname = Getattr(n, "sym:name");
+    String *value = Getattr(n, "value");
+    String *name = Getattr(n, "name");
+    String *tmpValue;
+
+    // Strange hack from parent method
+    if (value)
+      tmpValue = NewString(value);
+    else
+      tmpValue = NewString(name);
+    // Note that this is used in enumValue() amongst other places
+    Setattr(n, "value", tmpValue);
+
+    {
+      EnumFeature enum_feature = decodeEnumFeature(parentNode(n));
+
+      if ((enum_feature == ProperEnum) && Getattr(parentNode(n), "sym:name") && !Getattr(parentNode(n), "unnamedinstance")) {
+	// Wrap (non-anonymous) C/C++ enum with a proper C# enum
+	// Emit the enum item.
+	if (!Getattr(n, "_last"))	// Only the first enum item has this attribute set
+	  Printf(enum_code, ",\n");
+	Printf(enum_code, "  %s", symname);
+
+	// Check for the %csconstvalue feature
+	String *value = Getattr(n, "feature:cs:constvalue");
+
+	// Note that the enum value must be a true constant and cannot be set from a PINVOKE call, thus no support for %csconst(0)
+	value = value ? value : Getattr(n, "enumvalue");
+	if (value) {
+	  Printf(enum_code, " = %s", value);
+	}
+      } else {
+	// Wrap C/C++ enums with constant integers or use the typesafe enum pattern
+	const String *parent_name = Getattr(parentNode(n), "name");
+	String *typemap_lookup_type = parent_name ? Copy(parent_name) : NewString("int");
+	const String *tm = typemapLookup("cstype", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSTYPE_UNDEF);
+	String *return_type = Copy(tm);
+	Delete(typemap_lookup_type);
+	typemap_lookup_type = NULL;
+
+	// The %csconst feature determines how the constant value is obtained
+	int const_feature_flag = GetFlag(n, "feature:cs:const");
+
+        const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+        methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+
+	if ((enum_feature == TypesafeEnum) && Getattr(parentNode(n), "sym:name") && !Getattr(parentNode(n), "unnamedinstance")) {
+	  // Wrap (non-anonymouse) enum using the typesafe enum pattern
+	  if (Getattr(n, "enumvalue")) {
+	    String *value = enumValue(n);
+	    Printf(enum_code, "  %s static readonly %s %s = new %s(\"%s\", %s);\n", methodmods, return_type, symname, return_type, symname, value);
+	    Delete(value);
+	  } else {
+	    Printf(enum_code, "  %s static readonly %s %s = new %s(\"%s\");\n", methodmods, return_type, symname, return_type, symname);
+	  }
+	} else {
+	  // Simple integer constants
+	  // Note these are always generated for anonymous enums, no matter what enum_feature is specified
+	  // Code generated is the same for SimpleEnum and TypeunsafeEnum -> the class it is generated into is determined later
+	  const char *const_readonly = const_feature_flag ? "const" : "static readonly";
+	  String *value = enumValue(n);
+	  Printf(enum_code, "  %s %s %s %s = %s;\n", methodmods, const_readonly, return_type, symname, value);
+	  Delete(value);
+	}
+      }
+
+      // Add the enum value to the comma separated list being constructed in the enum declaration.
+      String *enumvalues = Getattr(parentNode(n), "enumvalues");
+      if (!enumvalues)
+	Setattr(parentNode(n), "enumvalues", Copy(symname));
+      else
+	Printv(enumvalues, ", ", symname, NIL);
+    }
+
+    Delete(tmpValue);
+    Swig_restore(n);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * constantWrapper()
+   * Used for wrapping constants - #define or %constant.
+   * Also for inline initialised const static primitive type member variables (short, int, double, enums etc).
+   * C# static const variables are generated for these.
+   * If the %csconst(1) feature is used then the C constant value is used to initialise the C# const variable.
+   * If not, a PINVOKE method is generated to get the C constant value for initialisation of the C# const variable.
+   * However, if the %csconstvalue feature is used, it overrides all other ways to generate the initialisation.
+   * Also note that this method might be called for wrapping enum items (when the enum is using %csconst(0)).
+   * ------------------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    String *return_type = NewString("");
+    String *constants_code = NewString("");
+
+    if (!addSymbol(symname, n))
+      return SWIG_ERROR;
+
+    bool is_enum_item = (Cmp(nodeType(n), "enumitem") == 0);
+
+    // The %csconst feature determines how the constant value is obtained
+    int const_feature_flag = GetFlag(n, "feature:cs:const");
+
+    /* Adjust the enum type for the Swig_typemap_lookup.
+     * We want the same jstype typemap for all the enum items so we use the enum type (parent node). */
+    if (is_enum_item) {
+      t = Getattr(parentNode(n), "enumtype");
+      Setattr(n, "type", t);
+    }
+
+    /* Attach the non-standard typemaps to the parameter list. */
+    Swig_typemap_attach_parms("cstype", l, NULL);
+
+    /* Get C# return types */
+    bool classname_substituted_flag = false;
+
+    if ((tm = Swig_typemap_lookup("cstype", n, "", 0))) {
+      String *cstypeout = Getattr(n, "tmap:cstype:out");	// the type in the cstype typemap's out attribute overrides the type in the typemap
+      if (cstypeout)
+	tm = cstypeout;
+      classname_substituted_flag = substituteClassname(t, tm);
+      Printf(return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    // Add the stripped quotes back in
+    String *new_value = NewString("");
+    Swig_save("constantWrapper", n, "value", NIL);
+    if (SwigType_type(t) == T_STRING) {
+      Printf(new_value, "\"%s\"", Copy(Getattr(n, "value")));
+      Setattr(n, "value", new_value);
+    } else if (SwigType_type(t) == T_CHAR) {
+      Printf(new_value, "\'%s\'", Copy(Getattr(n, "value")));
+      Setattr(n, "value", new_value);
+    }
+
+    const String *outattributes = Getattr(n, "tmap:cstype:outattributes");
+    if (outattributes)
+      Printf(constants_code, "  %s\n", outattributes);
+    const String *itemname = (proxy_flag && wrapping_member_flag) ? variable_name : symname;
+
+    const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+    methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+
+    Printf(constants_code, "  %s %s %s %s = ", methodmods, (const_feature_flag ? "const" : "static readonly"), return_type, itemname);
+
+    // Check for the %csconstvalue feature
+    String *value = Getattr(n, "feature:cs:constvalue");
+
+    if (value) {
+      Printf(constants_code, "%s;\n", value);
+    } else if (!const_feature_flag) {
+      // Default enum and constant handling will work with any type of C constant and initialises the C# variable from C through a PINVOKE call.
+
+      if (classname_substituted_flag) {
+	if (SwigType_isenum(t)) {
+	  // This handles wrapping of inline initialised const enum static member variables (not when wrapping enum items - ignored later on)
+	  Printf(constants_code, "(%s)%s.%s();\n", return_type, imclass_name, Swig_name_get(symname));
+	} else {
+	  // This handles function pointers using the %constant directive
+	  Printf(constants_code, "new %s(%s.%s(), false);\n", return_type, imclass_name, Swig_name_get(symname));
+	}
+      } else
+	Printf(constants_code, "%s.%s();\n", imclass_name, Swig_name_get(symname));
+
+      // Each constant and enum value is wrapped with a separate PInvoke function call
+      SetFlag(n, "feature:immutable");
+      enum_constant_flag = true;
+      variableWrapper(n);
+      enum_constant_flag = false;
+    } else {
+      // Alternative constant handling will use the C syntax to make a true C# constant and hope that it compiles as C# code
+      Printf(constants_code, "%s;\n", Getattr(n, "value"));
+    }
+
+    // Emit the generated code to appropriate place
+    // Enums only emit the intermediate and PINVOKE methods, so no proxy or module class wrapper methods needed
+    if (!is_enum_item) {
+      if (proxy_flag && wrapping_member_flag)
+	Printv(proxy_class_constants_code, constants_code, NIL);
+      else
+	Printv(module_class_constants_code, constants_code, NIL);
+    }
+    // Cleanup
+    Swig_restore(n);
+    Delete(new_value);
+    Delete(return_type);
+    Delete(constants_code);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * insertDirective()
+   * ----------------------------------------------------------------------------- */
+
+  virtual int insertDirective(Node *n) {
+    String *code = Getattr(n, "code");
+    Replaceall(code, "$module", module_class_name);
+    Replaceall(code, "$imclassname", imclass_name);
+    Replaceall(code, "$dllimport", dllimport);
+    return Language::insertDirective(n);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * pragmaDirective()
+   *
+   * Valid Pragmas:
+   * imclassbase            - base (extends) for the intermediary class
+   * imclassclassmodifiers  - class modifiers for the intermediary class
+   * imclasscode            - text (C# code) is copied verbatim to the intermediary class
+   * imclassimports         - import statements for the intermediary class
+   * imclassinterfaces      - interface (implements) for the intermediary class
+   *
+   * modulebase              - base (extends) for the module class
+   * moduleclassmodifiers    - class modifiers for the module class
+   * modulecode              - text (C# code) is copied verbatim to the module class
+   * moduleimports           - import statements for the module class
+   * moduleinterfaces        - interface (implements) for the module class
+   *
+   * ----------------------------------------------------------------------------- */
+
+  virtual int pragmaDirective(Node *n) {
+    if (!ImportMode) {
+      String *lang = Getattr(n, "lang");
+      String *code = Getattr(n, "name");
+      String *value = Getattr(n, "value");
+
+      if (Strcmp(lang, "csharp") == 0) {
+
+	String *strvalue = NewString(value);
+	Replaceall(strvalue, "\\\"", "\"");
+
+	if (Strcmp(code, "imclassbase") == 0) {
+	  Delete(imclass_baseclass);
+	  imclass_baseclass = Copy(strvalue);
+	} else if (Strcmp(code, "imclassclassmodifiers") == 0) {
+	  Delete(imclass_class_modifiers);
+	  imclass_class_modifiers = Copy(strvalue);
+	} else if (Strcmp(code, "imclasscode") == 0) {
+	  Printf(imclass_class_code, "%s\n", strvalue);
+	} else if (Strcmp(code, "imclassimports") == 0) {
+	  Delete(imclass_imports);
+	  imclass_imports = Copy(strvalue);
+	} else if (Strcmp(code, "imclassinterfaces") == 0) {
+	  Delete(imclass_interfaces);
+	  imclass_interfaces = Copy(strvalue);
+	} else if (Strcmp(code, "modulebase") == 0) {
+	  Delete(module_baseclass);
+	  module_baseclass = Copy(strvalue);
+	} else if (Strcmp(code, "moduleclassmodifiers") == 0) {
+	  Delete(module_class_modifiers);
+	  module_class_modifiers = Copy(strvalue);
+	} else if (Strcmp(code, "modulecode") == 0) {
+	  Printf(module_class_code, "%s\n", strvalue);
+	} else if (Strcmp(code, "moduleimports") == 0) {
+	  Delete(module_imports);
+	  module_imports = Copy(strvalue);
+	} else if (Strcmp(code, "moduleinterfaces") == 0) {
+	  Delete(module_interfaces);
+	  module_interfaces = Copy(strvalue);
+	} else {
+	  Printf(stderr, "%s : Line %d. Unrecognized pragma.\n", input_file, line_number);
+	}
+	Delete(strvalue);
+      }
+    }
+    return Language::pragmaDirective(n);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitProxyClassDefAndCPPCasts()
+   * ----------------------------------------------------------------------------- */
+
+  void emitProxyClassDefAndCPPCasts(Node *n) {
+    String *c_classname = SwigType_namestr(Getattr(n, "name"));
+    String *c_baseclass = NULL;
+    String *baseclass = NULL;
+    String *c_baseclassname = NULL;
+    String *typemap_lookup_type = Getattr(n, "classtypeobj");
+    bool feature_director = Swig_directorclass(n) ? true : false;
+
+    // Inheritance from pure C# classes
+    Node *attributes = NewHash();
+    const String *pure_baseclass = typemapLookup("csbase", typemap_lookup_type, WARN_NONE, attributes);
+    bool purebase_replace = GetFlag(attributes, "tmap:csbase:replace") ? true : false;
+    Delete(attributes);
+
+    // C++ inheritance
+    if (!purebase_replace) {
+      List *baselist = Getattr(n, "bases");
+      if (baselist) {
+        Iterator base = First(baselist);
+        while (base.item && GetFlag(base.item, "feature:ignore")) {
+          base = Next(base);
+        }
+        if (base.item) {
+          c_baseclassname = Getattr(base.item, "name");
+          baseclass = Copy(getProxyName(c_baseclassname));
+          if (baseclass)
+            c_baseclass = SwigType_namestr(Getattr(base.item, "name"));
+          base = Next(base);
+          /* Warn about multiple inheritance for additional base class(es) */
+          while (base.item) {
+            if (GetFlag(base.item, "feature:ignore")) {
+              base = Next(base);
+              continue;
+            }
+            String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0);
+            String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0);
+            Swig_warning(WARN_CSHARP_MULTIPLE_INHERITANCE, input_file, line_number,
+                         "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in C#.\n", proxyclassname, baseclassname);
+            base = Next(base);
+          }
+        }
+      }
+    }
+
+    const String *wanted_base = baseclass ? baseclass : pure_baseclass;
+    bool derived = baseclass && getProxyName(c_baseclassname);
+
+    if (purebase_replace) {
+      wanted_base = pure_baseclass;
+      derived = false;
+      Delete(baseclass);
+      baseclass = NULL;
+    } else if (Len(pure_baseclass) > 0 && Len(baseclass) > 0) {
+      Swig_warning(WARN_CSHARP_MULTIPLE_INHERITANCE, input_file, line_number,
+		   "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in C#. Perhaps you need the replace attribute in the csbase typemap?\n", typemap_lookup_type, pure_baseclass);
+    }
+
+    // Pure C# interfaces
+    const String *pure_interfaces = typemapLookup(derived ? "csinterfaces_derived" : "csinterfaces", typemap_lookup_type, WARN_NONE);
+    // Start writing the proxy class
+    Printv(proxy_class_def, typemapLookup("csimports", typemap_lookup_type, WARN_NONE),	// Import statements
+	   "\n", NIL);
+
+    // Class attributes
+    const String *csattributes = typemapLookup("csattributes", typemap_lookup_type, WARN_NONE);
+    if (csattributes && *Char(csattributes))
+      Printf(proxy_class_def, "%s\n", csattributes);
+
+    Printv(proxy_class_def, typemapLookup("csclassmodifiers", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers
+	   " $csclassname",	// Class name and base class
+	   (*Char(wanted_base) || *Char(pure_interfaces)) ? " : " : "", wanted_base, (*Char(wanted_base) && *Char(pure_interfaces)) ?	// Interfaces
+	   ", " : "", pure_interfaces, " {", derived ? typemapLookup("csbody_derived", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF) :	// main body of class
+	   typemapLookup("csbody", typemap_lookup_type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF),	// main body of class
+	   NIL);
+
+    // C++ destructor is wrapped by the Dispose method
+    // Note that the method name is specified in a typemap attribute called methodname
+    String *destruct = NewString("");
+    const String *tm = NULL;
+    attributes = NewHash();
+    String *destruct_methodname = NULL;
+    String *destruct_methodmodifiers = NULL;
+    if (derived) {
+      tm = typemapLookup("csdestruct_derived", typemap_lookup_type, WARN_NONE, attributes);
+      destruct_methodname = Getattr(attributes, "tmap:csdestruct_derived:methodname");
+      destruct_methodmodifiers = Getattr(attributes, "tmap:csdestruct_derived:methodmodifiers");
+    } else {
+      tm = typemapLookup("csdestruct", typemap_lookup_type, WARN_NONE, attributes);
+      destruct_methodname = Getattr(attributes, "tmap:csdestruct:methodname");
+      destruct_methodmodifiers = Getattr(attributes, "tmap:csdestruct:methodmodifiers");
+    }
+    if (tm && *Char(tm)) {
+      if (!destruct_methodname) {
+	Swig_error(input_file, line_number, "No methodname attribute defined in csdestruct%s typemap for %s\n", (derived ? "_derived" : ""), proxy_class_name);
+      }
+      if (!destruct_methodmodifiers) {
+	Swig_error(input_file, line_number,
+		   "No methodmodifiers attribute defined in csdestruct%s typemap for %s.\n", (derived ? "_derived" : ""), proxy_class_name);
+      }
+    }
+    // Emit the Finalize and Dispose methods
+    if (tm) {
+      // Finalize method
+      if (*Char(destructor_call)) {
+	Printv(proxy_class_def, typemapLookup("csfinalize", typemap_lookup_type, WARN_NONE), NIL);
+      }
+      // Dispose method
+      Printv(destruct, tm, NIL);
+      if (*Char(destructor_call))
+	Replaceall(destruct, "$imcall", destructor_call);
+      else
+	Replaceall(destruct, "$imcall", "throw new MethodAccessException(\"C++ destructor does not have public access\")");
+      if (*Char(destruct))
+	Printv(proxy_class_def, "\n  ", destruct_methodmodifiers, " ", derived ? "override" : "virtual", " void ", destruct_methodname, "() ", destruct, "\n",
+	       NIL);
+    }
+
+    if (feature_director) {
+      // Generate director connect method
+      // put this in classDirectorEnd ???
+      Printf(proxy_class_code, "  private void SwigDirectorConnect() {\n");
+
+      int i;
+      for (i = first_class_dmethod; i < curr_class_dmethod; ++i) {
+	UpcallData *udata = Getitem(dmethods_seq, i);
+	String *method = Getattr(udata, "method");
+	String *methid = Getattr(udata, "class_methodidx");
+	String *overname = Getattr(udata, "overname");
+	Printf(proxy_class_code, "    if (SwigDerivedClassHasMethod(\"%s\", swigMethodTypes%s))\n", method, methid);
+	Printf(proxy_class_code, "      swigDelegate%s = new SwigDelegate%s_%s(SwigDirector%s);\n", methid, proxy_class_name, methid, overname);
+      }
+      Printf(proxy_class_code, "    %s.%s_director_connect(swigCPtr", imclass_name, proxy_class_name);
+      for (i = first_class_dmethod; i < curr_class_dmethod; ++i) {
+	UpcallData *udata = Getitem(dmethods_seq, i);
+	String *methid = Getattr(udata, "class_methodidx");
+	Printf(proxy_class_code, ", swigDelegate%s", methid);
+      }
+      Printf(proxy_class_code, ");\n");
+      Printf(proxy_class_code, "  }\n");
+
+      if (first_class_dmethod < curr_class_dmethod) {
+	// Only emit if there is at least one director method
+	Printf(proxy_class_code, "\n");
+	Printf(proxy_class_code, "  private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {\n");
+	Printf(proxy_class_code,
+	       "    System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, methodTypes, null);\n");
+	Printf(proxy_class_code, "    bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(%s));\n", proxy_class_name);
+	/* Could add this code to cover corner case where the GetMethod() returns a method which allows type
+	 * promotion, eg it will return foo(double), if looking for foo(int).
+	 if (hasDerivedMethod) {
+	 hasDerivedMethod = false;
+	 if (methodInfo != null)
+	 {
+	 hasDerivedMethod = true;
+	 ParameterInfo[] parameterArray1 = methodInfo.GetParameters();
+	 for (int i=0; i<methodTypes.Length; i++)
+	 {
+	 if (parameterArray1[0].ParameterType != methodTypes[0])
+	 {
+	 hasDerivedMethod = false;
+	 break;
+	 }
+	 }
+	 }
+	 }
+	 */
+	Printf(proxy_class_code, "    return hasDerivedMethod;\n");
+	Printf(proxy_class_code, "  }\n");
+      }
+
+      if (Len(director_delegate_callback) > 0)
+	Printv(proxy_class_code, director_delegate_callback, NIL);
+      if (Len(director_delegate_definitions) > 0)
+	Printv(proxy_class_code, "\n", director_delegate_definitions, NIL);
+      if (Len(director_delegate_instances) > 0)
+	Printv(proxy_class_code, "\n", director_delegate_instances, NIL);
+      if (Len(director_method_types) > 0)
+	Printv(proxy_class_code, "\n", director_method_types, NIL);
+
+      Delete(director_callback_typedefs);
+      director_callback_typedefs = NULL;
+      Delete(director_callbacks);
+      director_callbacks = NULL;
+      Delete(director_delegate_callback);
+      director_delegate_callback = NULL;
+      Delete(director_delegate_definitions);
+      director_delegate_definitions = NULL;
+      Delete(director_delegate_instances);
+      director_delegate_instances = NULL;
+      Delete(director_method_types);
+      director_method_types = NULL;
+      Delete(director_connect_parms);
+      director_connect_parms = NULL;
+    }
+
+    Delete(attributes);
+    Delete(destruct);
+
+    // Emit extra user code
+    Printv(proxy_class_def, typemapLookup("cscode", typemap_lookup_type, WARN_NONE),	// extra C# code
+	   "\n", NIL);
+
+    // Substitute various strings into the above template
+    Replaceall(proxy_class_code, "$csclassname", proxy_class_name);
+    Replaceall(proxy_class_def, "$csclassname", proxy_class_name);
+
+    Replaceall(proxy_class_def, "$module", module_class_name);
+    Replaceall(proxy_class_code, "$module", module_class_name);
+
+    Replaceall(proxy_class_def, "$imclassname", imclass_name);
+    Replaceall(proxy_class_code, "$imclassname", imclass_name);
+
+    Replaceall(proxy_class_def, "$dllimport", dllimport);
+    Replaceall(proxy_class_code, "$dllimport", dllimport);
+
+    // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy)
+    if (derived) {
+      Printv(imclass_cppcasts_code, "\n  [DllImport(\"", dllimport, "\", EntryPoint=\"CSharp_", proxy_class_name, "Upcast", "\")]\n", NIL);
+      Printf(imclass_cppcasts_code, "  public static extern IntPtr $csclassnameUpcast(IntPtr objectRef);\n");
+
+      Replaceall(imclass_cppcasts_code, "$csclassname", proxy_class_name);
+
+      Printv(upcasts_code,
+	     "SWIGEXPORT $cbaseclass * SWIGSTDCALL CSharp_$imclazznameUpcast",
+	     "($cclass *objectRef) {\n", "    return ($cbaseclass *)objectRef;\n" "}\n", "\n", NIL);
+
+      Replaceall(upcasts_code, "$cbaseclass", c_baseclass);
+      Replaceall(upcasts_code, "$imclazzname", proxy_class_name);
+      Replaceall(upcasts_code, "$cclass", c_classname);
+    }
+    Delete(baseclass);
+  }
+
+  /* ----------------------------------------------------------------------
+   * classHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int classHandler(Node *n) {
+
+    File *f_proxy = NULL;
+    if (proxy_flag) {
+      proxy_class_name = NewString(Getattr(n, "sym:name"));
+
+      if (!addSymbol(proxy_class_name, n))
+	return SWIG_ERROR;
+
+      if (Cmp(proxy_class_name, imclass_name) == 0) {
+	Printf(stderr, "Class name cannot be equal to intermediary class name: %s\n", proxy_class_name);
+	SWIG_exit(EXIT_FAILURE);
+      }
+
+      if (Cmp(proxy_class_name, module_class_name) == 0) {
+	Printf(stderr, "Class name cannot be equal to module class name: %s\n", proxy_class_name);
+	SWIG_exit(EXIT_FAILURE);
+      }
+
+      String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), proxy_class_name);
+      f_proxy = NewFile(filen, "w");
+      if (!f_proxy) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the proxy class file
+      emitBanner(f_proxy);
+
+      addOpenNamespace(namespce, f_proxy);
+
+      Clear(proxy_class_def);
+      Clear(proxy_class_code);
+
+      destructor_call = NewString("");
+      proxy_class_constants_code = NewString("");
+    }
+
+    Language::classHandler(n);
+
+    if (proxy_flag) {
+
+      emitProxyClassDefAndCPPCasts(n);
+
+      Replaceall(proxy_class_def, "$module", module_class_name);
+      Replaceall(proxy_class_code, "$module", module_class_name);
+      Replaceall(proxy_class_constants_code, "$module", module_class_name);
+      Replaceall(proxy_class_def, "$imclassname", imclass_name);
+      Replaceall(proxy_class_code, "$imclassname", imclass_name);
+      Replaceall(proxy_class_constants_code, "$imclassname", imclass_name);
+      Replaceall(proxy_class_def, "$dllimport", dllimport);
+      Replaceall(proxy_class_code, "$dllimport", dllimport);
+      Replaceall(proxy_class_constants_code, "$dllimport", dllimport);
+
+      Printv(f_proxy, proxy_class_def, proxy_class_code, NIL);
+
+      // Write out all the constants
+      if (Len(proxy_class_constants_code) != 0)
+	Printv(f_proxy, proxy_class_constants_code, NIL);
+
+      Printf(f_proxy, "}\n");
+      addCloseNamespace(namespce, f_proxy);
+      Close(f_proxy);
+      f_proxy = NULL;
+
+      /* Output the downcast method, if necessary. Note: There's no other really
+         good place to put this code, since Abstract Base Classes (ABCs) can and should have 
+         downcasts, making the constructorHandler() a bad place (because ABCs don't get to
+         have constructors emitted.) */
+      if (GetFlag(n, "feature:javadowncast")) {
+	String *norm_name = SwigType_namestr(Getattr(n, "name"));
+
+	Printf(imclass_class_code, "  public final static native %s downcast%s(long cPtrBase, boolean cMemoryOwn);\n", proxy_class_name, proxy_class_name);
+
+	Wrapper *dcast_wrap = NewWrapper();
+
+	Printf(dcast_wrap->def, "SWIGEXPORT jobject SWIGSTDCALL CSharp_downcast%s(JNIEnv *jenv, jclass jcls, jlong jCPtrBase, jboolean cMemoryOwn) {",
+	       proxy_class_name);
+	Printf(dcast_wrap->code, "  Swig::Director *director = (Swig::Director *) 0;\n");
+	Printf(dcast_wrap->code, "  jobject jresult = (jobject) 0;\n");
+	Printf(dcast_wrap->code, "  %s *obj = *((%s **)&jCPtrBase);\n", norm_name, norm_name);
+	Printf(dcast_wrap->code, "  if (obj) director = dynamic_cast<Swig::Director *>(obj);\n");
+	Printf(dcast_wrap->code, "  if (director) jresult = director->swig_get_self(jenv);\n");
+	Printf(dcast_wrap->code, "  return jresult;\n");
+	Printf(dcast_wrap->code, "}\n");
+
+	Wrapper_print(dcast_wrap, f_wrappers);
+	DelWrapper(dcast_wrap);
+      }
+
+      emitDirectorExtraMethods(n);
+
+      Delete(proxy_class_name);
+      proxy_class_name = NULL;
+      Delete(destructor_call);
+      destructor_call = NULL;
+      Delete(proxy_class_constants_code);
+      proxy_class_constants_code = NULL;
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberfunctionHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int memberfunctionHandler(Node *n) {
+    Language::memberfunctionHandler(n);
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *intermediary_function_name = Swig_name_member(proxy_class_name, overloaded_name);
+      Setattr(n, "proxyfuncname", Getattr(n, "sym:name"));
+      Setattr(n, "imfuncname", intermediary_function_name);
+      proxyClassFunctionHandler(n);
+      Delete(overloaded_name);
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+
+    static_flag = true;
+    Language::staticmemberfunctionHandler(n);
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *intermediary_function_name = Swig_name_member(proxy_class_name, overloaded_name);
+      Setattr(n, "proxyfuncname", Getattr(n, "sym:name"));
+      Setattr(n, "imfuncname", intermediary_function_name);
+      proxyClassFunctionHandler(n);
+      Delete(overloaded_name);
+    }
+    static_flag = false;
+
+    return SWIG_OK;
+  }
+
+
+  /* -----------------------------------------------------------------------------
+   * proxyClassFunctionHandler()
+   *
+   * Function called for creating a C# wrapper function around a c++ function in the 
+   * proxy class. Used for both static and non-static C++ class functions.
+   * C++ class static functions map to C# static functions.
+   * Two extra attributes in the Node must be available. These are "proxyfuncname" - 
+   * the name of the C# class proxy function, which in turn will call "imfuncname" - 
+   * the intermediary (PInvoke) function name in the intermediary class.
+   * ----------------------------------------------------------------------------- */
+
+  void proxyClassFunctionHandler(Node *n) {
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *intermediary_function_name = Getattr(n, "imfuncname");
+    String *proxy_function_name = Getattr(n, "proxyfuncname");
+    String *tm;
+    Parm *p;
+    Parm *last_parm = 0;
+    int i;
+    String *imcall = NewString("");
+    String *return_type = NewString("");
+    String *function_code = NewString("");
+    bool setter_flag = false;
+    String *pre_code = NewString("");
+    String *post_code = NewString("");
+
+    if (!proxy_flag)
+      return;
+
+    // Wrappers not wanted for some methods where the parameters cannot be overloaded in C#
+    if (Getattr(n, "overload:ignore"))
+      return;
+
+    // Don't generate proxy method for additional explicitcall method used in directors
+    if (GetFlag(n, "explicitcall"))
+      return;
+
+    if (l) {
+      if (SwigType_type(Getattr(l, "type")) == T_VOID) {
+	l = nextSibling(l);
+      }
+    }
+
+    /* Attach the non-standard typemaps to the parameter list */
+    Swig_typemap_attach_parms("in", l, NULL);
+    Swig_typemap_attach_parms("cstype", l, NULL);
+    Swig_typemap_attach_parms("csin", l, NULL);
+
+    /* Get return types */
+    if ((tm = Swig_typemap_lookup("cstype", n, "", 0))) {
+      // Note that in the case of polymorphic (covariant) return types, the method's return type is changed to be the base of the C++ return type
+      SwigType *covariant = Getattr(n, "covariant");
+      String *cstypeout = Getattr(n, "tmap:cstype:out");	// the type in the cstype typemap's out attribute overrides the type in the typemap
+      if (cstypeout)
+	tm = cstypeout;
+      substituteClassname(covariant ? covariant : t, tm);
+      Printf(return_type, "%s", tm);
+      if (covariant)
+	Swig_warning(WARN_CSHARP_COVARIANT_RET, input_file, line_number,
+		     "Covariant return types not supported in C#. Proxy method will return %s.\n", SwigType_str(covariant, 0));
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    if (wrapping_member_flag && !enum_constant_flag) {
+      // Properties
+      setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(Swig_name_member(proxy_class_name, variable_name))) == 0);
+      if (setter_flag)
+        Swig_typemap_attach_parms("csvarin", l, NULL);
+    }
+
+    /* Start generating the proxy function */
+    const String *outattributes = Getattr(n, "tmap:cstype:outattributes");
+    if (outattributes)
+      Printf(function_code, "  %s\n", outattributes);
+    const String *csattributes = Getattr(n, "feature:cs:attributes");
+    if (csattributes)
+      Printf(function_code, "  %s\n", csattributes);
+    const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+    if (methodmods) {
+      if (is_smart_pointer()) {
+	// Smart pointer classes do not mirror the inheritance hierarchy of the underlying pointer type, so no virtual/override/new required.
+	String *mmods = Copy(methodmods);
+	Replaceall(mmods, "override", "");
+	Replaceall(mmods, "virtual", "");
+	Replaceall(mmods, "new", "");
+	Chop(mmods);		// remove trailing whitespace
+	Printf(function_code, "  %s ", mmods);
+	Delete(mmods);
+      } else {
+	Printf(function_code, "  %s ", methodmods);
+      }
+    } else {
+      methodmods = (is_public(n) ? public_string : protected_string);
+      Printf(function_code, "  %s ", methodmods);
+      if (!is_smart_pointer()) {
+	// Smart pointer classes do not mirror the inheritance hierarchy of the underlying pointer type, so no virtual/override/new required.
+	if (Getattr(n, "override"))
+	  Printf(function_code, "override ");
+	else if (checkAttribute(n, "storage", "virtual"))
+	  Printf(function_code, "virtual ");
+	if (Getattr(n, "hides"))
+	  Printf(function_code, "new ");
+      }
+    }
+    if (static_flag)
+      Printf(function_code, "static ");
+    Printf(function_code, "%s %s(", return_type, proxy_function_name);
+
+    Printv(imcall, imclass_name, ".$imfuncname(", NIL);
+    if (!static_flag)
+      Printf(imcall, "swigCPtr");
+
+    emit_mark_varargs(l);
+
+    int gencomma = !static_flag;
+
+    /* Output each parameter */
+    for (i = 0, p = l; p; i++) {
+
+      /* Ignored varargs */
+      if (checkAttribute(p, "varargs:ignore", "1")) {
+	p = nextSibling(p);
+	continue;
+      }
+
+      /* Ignored parameters */
+      if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      }
+
+      /* Ignore the 'this' argument for variable wrappers */
+      if (!(variable_wrapper_flag && i == 0)) {
+	SwigType *pt = Getattr(p, "type");
+	String *param_type = NewString("");
+	last_parm = p;
+
+	/* Get the C# parameter type */
+	if ((tm = Getattr(p, "tmap:cstype"))) {
+	  substituteClassname(pt, tm);
+	  const String *inattributes = Getattr(p, "tmap:cstype:inattributes");
+	  Printf(param_type, "%s%s", inattributes ? inattributes : empty_string, tm);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	if (gencomma)
+	  Printf(imcall, ", ");
+
+	String *arg = makeParameterName(n, p, i, setter_flag);
+
+	// Use typemaps to transform type used in C# wrapper function (in proxy class) to type used in PInvoke function (in intermediary class)
+	if ((tm = Getattr(p, "tmap:csin"))) {
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$csinput", arg);
+          String *pre = Getattr(p, "tmap:csin:pre");
+          if (pre) {
+            substituteClassname(pt, pre);
+            Replaceall(pre, "$csinput", arg);
+            if (Len(pre_code) > 0)
+              Printf(pre_code, "\n");
+            Printv(pre_code, pre, NIL);
+          }
+          String *post = Getattr(p, "tmap:csin:post");
+          if (post) {
+            substituteClassname(pt, post);
+            Replaceall(post, "$csinput", arg);
+            if (Len(post_code) > 0)
+              Printf(post_code, "\n");
+            Printv(post_code, post, NIL);
+          }
+	  Printv(imcall, tm, NIL);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSIN_UNDEF, input_file, line_number, "No csin typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	/* Add parameter to proxy function */
+	if (gencomma >= 2)
+	  Printf(function_code, ", ");
+	gencomma = 2;
+	Printf(function_code, "%s %s", param_type, arg);
+
+	Delete(arg);
+	Delete(param_type);
+      }
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    Printf(imcall, ")");
+    Printf(function_code, ")");
+
+    // Transform return type used in PInvoke function (in intermediary class) to type used in C# wrapper function (in proxy class)
+    if ((tm = Swig_typemap_lookup("csout", n, "", 0))) {
+      excodeSubstitute(n, tm, "csout", n);
+      bool is_pre_code = Len(pre_code) > 0;
+      bool is_post_code = Len(post_code) > 0;
+      if (is_pre_code || is_post_code) {
+        Replaceall(tm, "\n ", "\n   "); // add extra indentation to code in typemap
+        if (is_post_code) {
+          Insert(tm, 0, "\n    try ");
+          Printv(tm, " finally {\n", post_code, "\n    }", NIL);
+        } else {
+          Insert(tm, 0, "\n    ");
+        }
+        if (is_pre_code) {
+          Insert(tm, 0, pre_code);
+          Insert(tm, 0, "\n");
+        }
+	Insert(tm, 0, "{");
+	Printf(tm, "\n  }");
+      }
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "true");
+      else
+	Replaceall(tm, "$owner", "false");
+      substituteClassname(t, tm);
+
+      // For director methods: generate code to selectively make a normal polymorphic call or 
+      // an explicit method call - needed to prevent infinite recursion calls in director methods.
+      Node *explicit_n = Getattr(n, "explicitcallnode");
+      if (explicit_n) {
+	String *ex_overloaded_name = getOverloadedName(explicit_n);
+	String *ex_intermediary_function_name = Swig_name_member(proxy_class_name, ex_overloaded_name);
+
+	String *ex_imcall = Copy(imcall);
+	Replaceall(ex_imcall, "$imfuncname", ex_intermediary_function_name);
+	Replaceall(imcall, "$imfuncname", intermediary_function_name);
+
+	String *excode = NewString("");
+	if (!Cmp(return_type, "void"))
+	  Printf(excode, "if (this.GetType() == typeof(%s)) %s; else %s", proxy_class_name, imcall, ex_imcall);
+	else
+	  Printf(excode, "((this.GetType() == typeof(%s)) ? %s : %s)", proxy_class_name, imcall, ex_imcall);
+
+	Clear(imcall);
+	Printv(imcall, excode, NIL);
+	Delete(ex_overloaded_name);
+	Delete(excode);
+      } else {
+	Replaceall(imcall, "$imfuncname", intermediary_function_name);
+      }
+      Replaceall(tm, "$imcall", imcall);
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csout typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    if (wrapping_member_flag && !enum_constant_flag) {
+      // Properties
+      if (generate_property_declaration_flag) {	// Ensure the declaration is generated just once should the property contain both a set and get
+	// Get the C# variable type - obtained differently depending on whether a setter is required.
+	String *variable_type = return_type;
+	if (setter_flag) {
+	  p = last_parm;	// (last parameter is the only parameter for properties)
+	  SwigType *pt = Getattr(p, "type");
+	  if ((tm = Getattr(p, "tmap:cstype"))) {
+	    substituteClassname(pt, tm);
+            String *cstypeout = Getattr(p, "tmap:cstype:out");	// the type in the cstype typemap's out attribute overrides the type in the typemap
+	    variable_type = cstypeout ? cstypeout : tm;
+	  } else {
+	    Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csvarin typemap defined for %s\n", SwigType_str(pt, 0));
+	  }
+	}
+	const String *csattributes = Getattr(n, "feature:cs:attributes");
+	if (csattributes)
+	  Printf(proxy_class_code, "  %s\n", csattributes);
+	const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+	if (!methodmods)
+	  methodmods = (is_public(n) ? public_string : protected_string);
+	Printf(proxy_class_code, "  %s %s%s %s {", methodmods, static_flag ? "static " : "", variable_type, variable_name);
+      }
+      generate_property_declaration_flag = false;
+
+      if (setter_flag) {
+	// Setter method
+	p = last_parm;		// (last parameter is the only parameter for properties)
+	SwigType *pt = Getattr(p, "type");
+	if ((tm = Getattr(p, "tmap:csvarin"))) {
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$imcall", imcall);
+	  excodeSubstitute(n, tm, "csvarin", p);
+	  Printf(proxy_class_code, "%s", tm);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csvarin typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+      } else {
+	// Getter method
+	if ((tm = Swig_typemap_lookup("csvarout", n, "", 0))) {
+	  if (GetFlag(n, "feature:new"))
+	    Replaceall(tm, "$owner", "true");
+	  else
+	    Replaceall(tm, "$owner", "false");
+	  substituteClassname(t, tm);
+	  Replaceall(tm, "$imcall", imcall);
+	  excodeSubstitute(n, tm, "csvarout", n);
+	  Printf(proxy_class_code, "%s", tm);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csvarout typemap defined for %s\n", SwigType_str(t, 0));
+	}
+      }
+    } else {
+      // Normal function call
+      Printf(function_code, " %s\n\n", tm ? (const String *) tm : empty_string);
+      Printv(proxy_class_code, function_code, NIL);
+    }
+
+    Delete(pre_code);
+    Delete(post_code);
+    Delete(function_code);
+    Delete(return_type);
+    Delete(imcall);
+  }
+
+  /* ----------------------------------------------------------------------
+   * constructorHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int constructorHandler(Node *n) {
+
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    Parm *p;
+    int i;
+    String *function_code = NewString("");
+    String *helper_code = NewString(""); // Holds code for the constructor helper method generated only when the csin typemap has code in the pre or post attributes
+    String *helper_args = NewString("");
+    String *pre_code = NewString("");
+    String *post_code = NewString("");
+    String *im_return_type = NewString("");
+    bool feature_director = (parentNode(n) && Swig_directorclass(n));
+
+    Language::constructorHandler(n);
+
+    // Wrappers not wanted for some methods where the parameters cannot be overloaded in C#
+    if (Getattr(n, "overload:ignore"))
+      return SWIG_OK;
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *mangled_overname = Swig_name_construct(overloaded_name);
+      String *imcall = NewString("");
+
+      const String *csattributes = Getattr(n, "feature:cs:attributes");
+      if (csattributes) {
+	Printf(function_code, "  %s\n", csattributes);
+	Printf(helper_code, "  %s\n", csattributes);
+      }
+      const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+      methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+
+      tm = Getattr(n, "tmap:imtype"); // typemaps were attached earlier to the node
+      String *imtypeout = Getattr(n, "tmap:imtype:out");	// the type in the imtype typemap's out attribute overrides the type in the typemap
+      if (imtypeout)
+	tm = imtypeout;
+      Printf(im_return_type, "%s", tm);
+
+      Printf(function_code, "  %s %s(", methodmods, proxy_class_name);
+      Printf(helper_code, "  static private %s SwigConstruct%s(", im_return_type, proxy_class_name);
+
+      Printv(imcall, imclass_name, ".", mangled_overname, "(", NIL);
+
+      /* Attach the non-standard typemaps to the parameter list */
+      Swig_typemap_attach_parms("in", l, NULL);
+      Swig_typemap_attach_parms("cstype", l, NULL);
+      Swig_typemap_attach_parms("csin", l, NULL);
+
+      emit_mark_varargs(l);
+
+      int gencomma = 0;
+
+      /* Output each parameter */
+      for (i = 0, p = l; p; i++) {
+
+	/* Ignored varargs */
+	if (checkAttribute(p, "varargs:ignore", "1")) {
+	  p = nextSibling(p);
+	  continue;
+	}
+
+	/* Ignored parameters */
+	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	  p = Getattr(p, "tmap:in:next");
+	  continue;
+	}
+
+	SwigType *pt = Getattr(p, "type");
+	String *param_type = NewString("");
+
+	/* Get the C# parameter type */
+	if ((tm = Getattr(p, "tmap:cstype"))) {
+	  substituteClassname(pt, tm);
+	  const String *inattributes = Getattr(p, "tmap:cstype:inattributes");
+	  Printf(param_type, "%s%s", inattributes ? inattributes : empty_string, tm);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	if (gencomma)
+	  Printf(imcall, ", ");
+
+	String *arg = makeParameterName(n, p, i, false);
+        String *cshin = 0;
+
+	// Use typemaps to transform type used in C# wrapper function (in proxy class) to type used in PInvoke function (in intermediary class)
+	if ((tm = Getattr(p, "tmap:csin"))) {
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$csinput", arg);
+          String *pre = Getattr(p, "tmap:csin:pre");
+          if (pre) {
+            substituteClassname(pt, pre);
+            Replaceall(pre, "$csinput", arg);
+            if (Len(pre_code) > 0)
+              Printf(pre_code, "\n");
+            Printv(pre_code, pre, NIL);
+          }
+          String *post = Getattr(p, "tmap:csin:post");
+          if (post) {
+            substituteClassname(pt, post);
+            Replaceall(post, "$csinput", arg);
+            if (Len(post_code) > 0)
+              Printf(post_code, "\n");
+            Printv(post_code, post, NIL);
+          }
+          cshin = Getattr(p, "tmap:csin:cshin");
+          if (cshin)
+            Replaceall(cshin, "$csinput", arg);
+	  Printv(imcall, tm, NIL);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSIN_UNDEF, input_file, line_number, "No csin typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	/* Add parameter to proxy function */
+	if (gencomma) {
+	  Printf(function_code, ", ");
+	  Printf(helper_code, ", ");
+	  Printf(helper_args, ", ");
+        }
+	Printf(function_code, "%s %s", param_type, arg);
+	Printf(helper_code, "%s %s", param_type, arg);
+	Printf(helper_args, "%s", cshin ? cshin : arg);
+	++gencomma;
+
+	Delete(cshin);
+	Delete(arg);
+	Delete(param_type);
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      Printf(imcall, ")");
+
+      Printf(function_code, ")");
+      Printf(helper_code, ")");
+
+      /* Insert the csconstruct typemap, doing the replacement for $directorconnect, as needed */
+      Hash *attributes = NewHash();
+      String *construct_tm = Copy(typemapLookup("csconstruct", Getattr(n, "name"),
+						WARN_CSHARP_TYPEMAP_CSCONSTRUCT_UNDEF, attributes));
+      if (construct_tm) {
+	if (!feature_director) {
+	  Replaceall(construct_tm, "$directorconnect", "");
+	} else {
+	  String *connect_attr = Getattr(attributes, "tmap:csconstruct:directorconnect");
+
+	  if (connect_attr) {
+	    Replaceall(construct_tm, "$directorconnect", connect_attr);
+	  } else {
+	    Swig_warning(WARN_CSHARP_NO_DIRECTORCONNECT_ATTR, input_file, line_number, "\"directorconnect\" attribute missing in %s \"csconstruct\" typemap.\n",
+			 Getattr(n, "name"));
+	    Replaceall(construct_tm, "$directorconnect", "");
+	  }
+	}
+
+	Printv(function_code, " ", construct_tm, NIL);
+      }
+
+      excodeSubstitute(n, function_code, "csconstruct", attributes);
+
+      bool is_pre_code = Len(pre_code) > 0;
+      bool is_post_code = Len(post_code) > 0;
+      if (is_pre_code || is_post_code) {
+        Printf(helper_code, " {\n");
+        if (is_pre_code) {
+          Printv(helper_code, pre_code, "\n", NIL);
+        }
+        if (is_post_code) {
+          Printf(helper_code, "    try {\n");
+          Printv(helper_code, "      return ", imcall, ";\n", NIL);
+          Printv(helper_code, "    } finally {\n", post_code, "\n    }", NIL);
+        } else {
+          Printv(helper_code, "    return ", imcall, ";", NIL);
+        }
+        Printf(helper_code, "\n  }\n");
+        String *helper_name = NewStringf("%s.SwigConstruct%s(%s)", proxy_class_name, proxy_class_name, helper_args);
+        String *im_outattributes = Getattr(n, "tmap:imtype:outattributes");
+        if (im_outattributes)
+          Printf(proxy_class_code, "  %s\n", im_outattributes);
+        Printv(proxy_class_code, helper_code, "\n", NIL);
+        Replaceall(function_code, "$imcall", helper_name);
+        Delete(helper_name);
+      } else {
+        Replaceall(function_code, "$imcall", imcall);
+      }
+
+      Printv(proxy_class_code, function_code, "\n", NIL);
+
+      Delete(helper_args);
+      Delete(im_return_type);
+      Delete(pre_code);
+      Delete(post_code);
+      Delete(construct_tm);
+      Delete(attributes);
+      Delete(overloaded_name);
+      Delete(imcall);
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * destructorHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int destructorHandler(Node *n) {
+    Language::destructorHandler(n);
+    String *symname = Getattr(n, "sym:name");
+
+    if (proxy_flag) {
+      Printv(destructor_call, imclass_name, ".", Swig_name_destroy(symname), "(swigCPtr)", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * membervariableHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int membervariableHandler(Node *n) {
+
+    generate_property_declaration_flag = true;
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    variable_wrapper_flag = true;
+    Language::membervariableHandler(n);
+    wrapping_member_flag = false;
+    variable_wrapper_flag = false;
+    generate_property_declaration_flag = false;
+
+    Printf(proxy_class_code, "\n  }\n\n");
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * staticmembervariableHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmembervariableHandler(Node *n) {
+
+    bool static_const_member_flag = (Getattr(n, "value") == 0);
+
+    generate_property_declaration_flag = true;
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    static_flag = true;
+    Language::staticmembervariableHandler(n);
+    wrapping_member_flag = false;
+    static_flag = false;
+    generate_property_declaration_flag = false;
+
+    if (static_const_member_flag)
+      Printf(proxy_class_code, "\n  }\n\n");
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberconstantHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int memberconstantHandler(Node *n) {
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    Language::memberconstantHandler(n);
+    wrapping_member_flag = false;
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getOverloadedName()
+   * ----------------------------------------------------------------------------- */
+
+  String *getOverloadedName(Node *n) {
+
+    /* A C# HandleRef is used for all classes in the SWIG intermediary class.
+     * The intermediary class methods are thus mangled when overloaded to give
+     * a unique name. */
+    String *overloaded_name = NewStringf("%s", Getattr(n, "sym:name"));
+
+    if (Getattr(n, "sym:overloaded")) {
+      Printv(overloaded_name, Getattr(n, "sym:overname"), NIL);
+    }
+
+    return overloaded_name;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * moduleClassFunctionHandler()
+   * ----------------------------------------------------------------------------- */
+
+  void moduleClassFunctionHandler(Node *n) {
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    Parm *p;
+    Parm *last_parm = 0;
+    int i;
+    String *imcall = NewString("");
+    String *return_type = NewString("");
+    String *function_code = NewString("");
+    int num_arguments = 0;
+    int num_required = 0;
+    String *overloaded_name = getOverloadedName(n);
+    String *func_name = NULL;
+    bool setter_flag = false;
+    String *pre_code = NewString("");
+    String *post_code = NewString("");
+
+    if (l) {
+      if (SwigType_type(Getattr(l, "type")) == T_VOID) {
+	l = nextSibling(l);
+      }
+    }
+
+    /* Attach the non-standard typemaps to the parameter list */
+    Swig_typemap_attach_parms("cstype", l, NULL);
+    Swig_typemap_attach_parms("csin", l, NULL);
+
+    /* Get return types */
+    if ((tm = Swig_typemap_lookup("cstype", n, "", 0))) {
+      String *cstypeout = Getattr(n, "tmap:cstype:out");	// the type in the cstype typemap's out attribute overrides the type in the typemap
+      if (cstypeout)
+	tm = cstypeout;
+      substituteClassname(t, tm);
+      Printf(return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    /* Change function name for global variables */
+    if (proxy_flag && global_variable_flag) {
+      // Capitalize the first letter in the variable to create the getter/setter function name
+      func_name = NewString("");
+      setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(variable_name)) == 0);
+      if (setter_flag)
+	Printf(func_name, "set");
+      else
+	Printf(func_name, "get");
+      Putc(toupper((int) *Char(variable_name)), func_name);
+      Printf(func_name, "%s", Char(variable_name) + 1);
+      if (setter_flag)
+        Swig_typemap_attach_parms("csvarin", l, NULL);
+    } else {
+      func_name = Copy(Getattr(n, "sym:name"));
+    }
+
+    /* Start generating the function */
+    const String *outattributes = Getattr(n, "tmap:cstype:outattributes");
+    if (outattributes)
+      Printf(function_code, "  %s\n", outattributes);
+    const String *csattributes = Getattr(n, "feature:cs:attributes");
+    if (csattributes)
+      Printf(function_code, "  %s\n", csattributes);
+    const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+    methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+    Printf(function_code, "  %s static %s %s(", methodmods, return_type, func_name);
+    Printv(imcall, imclass_name, ".", overloaded_name, "(", NIL);
+
+    /* Get number of required and total arguments */
+    num_arguments = emit_num_arguments(l);
+    num_required = emit_num_required(l);
+
+    bool global_or_member_variable = global_variable_flag || (wrapping_member_flag && !enum_constant_flag);
+    int gencomma = 0;
+
+    /* Output each parameter */
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      /* Ignored parameters */
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *param_type = NewString("");
+      last_parm = p;
+
+      /* Get the C# parameter type */
+      if ((tm = Getattr(p, "tmap:cstype"))) {
+	substituteClassname(pt, tm);
+	const String *inattributes = Getattr(p, "tmap:cstype:inattributes");
+	Printf(param_type, "%s%s", inattributes ? inattributes : empty_string, tm);
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      if (gencomma)
+	Printf(imcall, ", ");
+
+      String *arg = makeParameterName(n, p, i, global_or_member_variable);
+
+      // Use typemaps to transform type used in C# wrapper function (in proxy class) to type used in PInvoke function (in intermediary class)
+      if ((tm = Getattr(p, "tmap:csin"))) {
+	substituteClassname(pt, tm);
+	Replaceall(tm, "$csinput", arg);
+	String *pre = Getattr(p, "tmap:csin:pre");
+	if (pre) {
+	  substituteClassname(pt, pre);
+	  Replaceall(pre, "$csinput", arg);
+          if (Len(pre_code) > 0)
+            Printf(pre_code, "\n");
+	  Printv(pre_code, pre, NIL);
+	}
+	String *post = Getattr(p, "tmap:csin:post");
+	if (post) {
+	  substituteClassname(pt, post);
+	  Replaceall(post, "$csinput", arg);
+          if (Len(post_code) > 0)
+            Printf(post_code, "\n");
+	  Printv(post_code, post, NIL);
+	}
+	Printv(imcall, tm, NIL);
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CSIN_UNDEF, input_file, line_number, "No csin typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      /* Add parameter to module class function */
+      if (gencomma >= 2)
+	Printf(function_code, ", ");
+      gencomma = 2;
+      Printf(function_code, "%s %s", param_type, arg);
+
+      p = Getattr(p, "tmap:in:next");
+      Delete(arg);
+      Delete(param_type);
+    }
+
+    Printf(imcall, ")");
+    Printf(function_code, ")");
+
+    // Transform return type used in PInvoke function (in intermediary class) to type used in C# wrapper function (in module class)
+    if ((tm = Swig_typemap_lookup("csout", n, "", 0))) {
+      excodeSubstitute(n, tm, "csout", n);
+      bool is_pre_code = Len(pre_code) > 0;
+      bool is_post_code = Len(post_code) > 0;
+      if (is_pre_code || is_post_code) {
+        Replaceall(tm, "\n ", "\n   "); // add extra indentation to code in typemap
+        if (is_post_code) {
+          Insert(tm, 0, "\n    try ");
+          Printv(tm, " finally {\n", post_code, "\n    }", NIL);
+        } else {
+          Insert(tm, 0, "\n    ");
+        }
+        if (is_pre_code) {
+          Insert(tm, 0, pre_code);
+          Insert(tm, 0, "\n");
+        }
+	Insert(tm, 0, "{");
+	Printf(tm, "\n  }");
+      }
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "true");
+      else
+	Replaceall(tm, "$owner", "false");
+      substituteClassname(t, tm);
+      Replaceall(tm, "$imcall", imcall);
+    } else {
+      Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csout typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    if (proxy_flag && global_variable_flag) {
+      // Properties
+      if (generate_property_declaration_flag) {	// Ensure the declaration is generated just once should the property contain both a set and get
+	// Get the C# variable type - obtained differently depending on whether a setter is required.
+	String *variable_type = return_type;
+	if (setter_flag) {
+	  p = last_parm;	// (last parameter is the only parameter for properties)
+	  SwigType *pt = Getattr(p, "type");
+	  if ((tm = Getattr(p, "tmap:cstype"))) {
+	    substituteClassname(pt, tm);
+            String *cstypeout = Getattr(p, "tmap:cstype:out");	// the type in the cstype typemap's out attribute overrides the type in the typemap
+	    variable_type = cstypeout ? cstypeout : tm;
+	  } else {
+	    Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csvarin typemap defined for %s\n", SwigType_str(pt, 0));
+	  }
+	}
+	const String *csattributes = Getattr(n, "feature:cs:attributes");
+	if (csattributes)
+	  Printf(module_class_code, "  %s\n", csattributes);
+	const String *methodmods = Getattr(n, "feature:cs:methodmodifiers");
+	if (!methodmods)
+	  methodmods = (is_public(n) ? public_string : protected_string);
+	Printf(module_class_code, "  %s static %s %s {", methodmods, variable_type, variable_name);
+      }
+      generate_property_declaration_flag = false;
+
+      if (setter_flag) {
+	// Setter method
+	p = last_parm;		// (last parameter is the only parameter for properties)
+	SwigType *pt = Getattr(p, "type");
+	if ((tm = Getattr(p, "tmap:csvarin"))) {
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$csinput", "value");
+	  Replaceall(tm, "$imcall", imcall);
+	  excodeSubstitute(n, tm, "csvarin", p);
+	  Printf(module_class_code, "%s", tm);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csvarin typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+      } else {
+	// Getter method
+	if ((tm = Swig_typemap_lookup("csvarout", n, "", 0))) {
+	  if (GetFlag(n, "feature:new"))
+	    Replaceall(tm, "$owner", "true");
+	  else
+	    Replaceall(tm, "$owner", "false");
+	  substituteClassname(t, tm);
+	  Replaceall(tm, "$imcall", imcall);
+	  excodeSubstitute(n, tm, "csvarout", n);
+	  Printf(module_class_code, "%s", tm);
+	} else {
+	  Swig_warning(WARN_CSHARP_TYPEMAP_CSOUT_UNDEF, input_file, line_number, "No csvarout typemap defined for %s\n", SwigType_str(t, 0));
+	}
+      }
+    } else {
+      // Normal function call
+      Printf(function_code, " %s\n\n", tm ? (const String *) tm : empty_string);
+      Printv(module_class_code, function_code, NIL);
+    }
+
+    Delete(pre_code);
+    Delete(post_code);
+    Delete(function_code);
+    Delete(return_type);
+    Delete(imcall);
+    Delete(func_name);
+  }
+
+  /*----------------------------------------------------------------------
+   * decodeEnumFeature()
+   * Decode the possible enum features, which are one of:
+   *   %csenum(simple)
+   *   %csenum(typeunsafe) - default
+   *   %csenum(typesafe)
+   *   %csenum(proper)
+   *--------------------------------------------------------------------*/
+
+  EnumFeature decodeEnumFeature(Node *n) {
+    EnumFeature enum_feature = TypeunsafeEnum;
+    String *feature = Getattr(n, "feature:cs:enum");
+    if (feature) {
+      if (Cmp(feature, "simple") == 0)
+	enum_feature = SimpleEnum;
+      else if (Cmp(feature, "typesafe") == 0)
+	enum_feature = TypesafeEnum;
+      else if (Cmp(feature, "proper") == 0)
+	enum_feature = ProperEnum;
+    }
+    return enum_feature;
+  }
+
+  /* -----------------------------------------------------------------------
+   * enumValue()
+   * This method will return a string with an enum value to use in C# generated
+   * code. If the %csconst feature is not used, the string will contain the intermediary
+   * class call to obtain the enum value. The intermediary class and PINVOKE methods to obtain
+   * the enum value will be generated. Otherwise the C/C++ enum value will be used if there
+   * is one and hopefully it will compile as C# code - e.g. 20 as in: enum E{e=20};
+   * The %csconstvalue feature overrides all other ways to generate the constant value.
+   * The caller must delete memory allocated for the returned string.
+   * ------------------------------------------------------------------------ */
+
+  String *enumValue(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+
+    // Check for the %csconstvalue feature
+    String *value = Getattr(n, "feature:cs:constvalue");
+
+    if (!value) {
+      // The %csconst feature determines how the constant value is obtained
+      int const_feature_flag = GetFlag(n, "feature:cs:const");
+
+      if (const_feature_flag) {
+	// Use the C syntax to make a true C# constant and hope that it compiles as C# code
+	value = Getattr(n, "enumvalue") ? Copy(Getattr(n, "enumvalue")) : Copy(Getattr(n, "enumvalueex"));
+      } else {
+	// Get the enumvalue from a PINVOKE call
+	if (!getCurrentClass() || !cparse_cplusplus || !proxy_flag) {
+	  // Strange hack to change the name
+	  Setattr(n, "name", Getattr(n, "value"));	/* for wrapping of enums in a namespace when emit_action is used */
+	  constantWrapper(n);
+	  value = NewStringf("%s.%s()", imclass_name, Swig_name_get(symname));
+	} else {
+	  memberconstantHandler(n);
+	  value = NewStringf("%s.%s()", imclass_name, Swig_name_get(Swig_name_member(proxy_class_name, symname)));
+	}
+      }
+    }
+    return value;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getEnumName()
+   * ----------------------------------------------------------------------------- */
+
+  String *getEnumName(SwigType *t) {
+    Node *enum_name = NULL;
+    Node *n = enumLookup(t);
+    if (n) {
+      String *symname = Getattr(n, "sym:name");
+      if (symname) {
+	// Add in class scope when referencing enum if not a global enum
+	String *scopename_prefix = Swig_scopename_prefix(Getattr(n, "name"));
+	String *proxyname = 0;
+	if (scopename_prefix) {
+	  proxyname = getProxyName(scopename_prefix);
+	}
+	if (proxyname)
+	  enum_name = NewStringf("%s.%s", proxyname, symname);
+	else
+	  enum_name = NewStringf("%s", symname);
+	Delete(scopename_prefix);
+      }
+    }
+
+    return enum_name;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * substituteClassname()
+   *
+   * Substitute $csclassname with the proxy class name for classes/structs/unions that SWIG knows about.
+   * Also substitutes enums with enum name.
+   * Otherwise use the $descriptor name for the C# class name. Note that the $&csclassname substitution
+   * is the same as a $&descriptor substitution, ie one pointer added to descriptor name.
+   * Inputs:
+   *   pt - parameter type
+   *   tm - cstype typemap
+   * Outputs:
+   *   tm - cstype typemap with $csclassname substitution
+   * Return:
+   *   substitution_performed - flag indicating if a substitution was performed
+   * ----------------------------------------------------------------------------- */
+
+  bool substituteClassname(SwigType *pt, String *tm) {
+    bool substitution_performed = false;
+    SwigType *type = Copy(SwigType_typedef_resolve_all(pt));
+    SwigType *strippedtype = SwigType_strip_qualifiers(type);
+
+    if (Strstr(tm, "$csclassname")) {
+      SwigType *classnametype = Copy(strippedtype);
+      substituteClassnameSpecialVariable(classnametype, tm, "$csclassname");
+      substitution_performed = true;
+      Delete(classnametype);
+    }
+    if (Strstr(tm, "$*csclassname")) {
+      SwigType *classnametype = Copy(strippedtype);
+      Delete(SwigType_pop(classnametype));
+      substituteClassnameSpecialVariable(classnametype, tm, "$*csclassname");
+      substitution_performed = true;
+      Delete(classnametype);
+    }
+    if (Strstr(tm, "$&csclassname")) {
+      SwigType *classnametype = Copy(strippedtype);
+      SwigType_add_pointer(classnametype);
+      substituteClassnameSpecialVariable(classnametype, tm, "$&csclassname");
+      substitution_performed = true;
+      Delete(classnametype);
+    }
+
+    Delete(strippedtype);
+    Delete(type);
+
+    return substitution_performed;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * substituteClassnameSpecialVariable()
+   * ----------------------------------------------------------------------------- */
+
+  void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable) {
+    if (SwigType_isenum(classnametype)) {
+      String *enumname = getEnumName(classnametype);
+      if (enumname)
+	Replaceall(tm, classnamespecialvariable, enumname);
+      else
+	Replaceall(tm, classnamespecialvariable, NewStringf("int"));
+    } else {
+      String *classname = getProxyName(classnametype);
+      if (classname) {
+	Replaceall(tm, classnamespecialvariable, classname);	// getProxyName() works for pointers to classes too
+      } else {			// use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved.
+	String *descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(classnametype));
+	Replaceall(tm, classnamespecialvariable, descriptor);
+
+	// Add to hash table so that the type wrapper classes can be created later
+	Setattr(swig_types_hash, descriptor, classnametype);
+	Delete(descriptor);
+      }
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * makeParameterName()
+   *
+   * Inputs: 
+   *   n - Node
+   *   p - parameter node
+   *   arg_num - parameter argument number
+   *   setter  - set this flag when wrapping variables
+   * Return:
+   *   arg - a unique parameter name
+   * ----------------------------------------------------------------------------- */
+
+  String *makeParameterName(Node *n, Parm *p, int arg_num, bool setter) {
+
+    String *arg = 0;
+    String *pn = Getattr(p, "name");
+
+    // Use C parameter name unless it is a duplicate or an empty parameter name
+    int count = 0;
+    ParmList *plist = Getattr(n, "parms");
+    while (plist) {
+      if ((Cmp(pn, Getattr(plist, "name")) == 0))
+        count++;
+      plist = nextSibling(plist);
+    }
+    String *wrn = pn ? Swig_name_warning(p, 0, pn, 0) : 0;
+    arg = (!pn || (count > 1) || wrn) ? NewStringf("arg%d", arg_num) : Copy(pn);
+
+    if (setter && Cmp(arg, "self") != 0) {
+      // Note that in C# properties, the input variable name is always called 'value'
+      Delete(arg);      
+      arg = NewString("value");
+    }
+
+    return arg;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitTypeWrapperClass()
+   * ----------------------------------------------------------------------------- */
+
+  void emitTypeWrapperClass(String *classname, SwigType *type) {
+    String *swigtype = NewString("");
+    String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), classname);
+    File *f_swigtype = NewFile(filen, "w");
+    if (!f_swigtype) {
+      FileErrorDisplay(filen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Append(filenames_list, Copy(filen));
+    Delete(filen);
+    filen = NULL;
+
+    // Start writing out the type wrapper class file
+    emitBanner(f_swigtype);
+
+    addOpenNamespace(namespce, f_swigtype);
+
+    // Pure C# baseclass and interfaces
+    const String *pure_baseclass = typemapLookup("csbase", type, WARN_NONE);
+    const String *pure_interfaces = typemapLookup("csinterfaces", type, WARN_NONE);
+
+    // Emit the class
+    Printv(swigtype, typemapLookup("csimports", type, WARN_NONE),	// Import statements
+	   "\n", NIL);
+
+    // Class attributes
+    const String *csattributes = typemapLookup("csattributes", type, WARN_NONE);
+    if (csattributes && *Char(csattributes))
+      Printf(swigtype, "%s\n", csattributes);
+
+    Printv(swigtype, typemapLookup("csclassmodifiers", type, WARN_CSHARP_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers
+	   " $csclassname",	// Class name and base class
+	   (*Char(pure_baseclass) || *Char(pure_interfaces)) ? " : " : "", pure_baseclass, ((*Char(pure_baseclass)) && *Char(pure_interfaces)) ?	// Interfaces
+	   ", " : "", pure_interfaces, " {", typemapLookup("csbody", type, WARN_CSHARP_TYPEMAP_CSBODY_UNDEF),	// main body of class
+	   typemapLookup("cscode", type, WARN_NONE),	// extra C# code
+	   "}\n", NIL);
+
+    Replaceall(swigtype, "$csclassname", classname);
+    Replaceall(swigtype, "$module", module_class_name);
+    Replaceall(swigtype, "$imclassname", imclass_name);
+    Replaceall(swigtype, "$dllimport", dllimport);
+
+    Printv(f_swigtype, swigtype, NIL);
+
+    addCloseNamespace(namespce, f_swigtype);
+
+    Close(f_swigtype);
+    Delete(swigtype);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * typemapLookup()
+   * ----------------------------------------------------------------------------- */
+
+  const String *typemapLookup(const String *op, String *type, int warning, Node *typemap_attributes = NULL) {
+    String *tm = NULL;
+    const String *code = NULL;
+
+    if ((tm = Swig_typemap_search(op, type, NULL, NULL))) {
+      code = Getattr(tm, "code");
+      if (typemap_attributes)
+	Swig_typemap_attach_kwargs(tm, op, typemap_attributes);
+    }
+
+    if (!code) {
+      code = empty_string;
+      if (warning != WARN_NONE)
+	Swig_warning(warning, input_file, line_number, "No %s typemap defined for %s\n", op, type);
+    }
+
+    return code ? code : empty_string;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * addThrows()
+   // TODO: remove
+   * ----------------------------------------------------------------------------- */
+  void addThrows(Node *, const String *, Node *) {
+  }
+
+  /* -----------------------------------------------------------------------------
+   * canThrow()
+   * Determine whether the code in the typemap can throw a C# exception.
+   * If so, note it for later when excodeSubstitute() is called.
+   * ----------------------------------------------------------------------------- */
+
+  void canThrow(Node *n, const String *typemap, Node *parameter) {
+    String *canthrow_attribute = NewStringf("tmap:%s:canthrow", typemap);
+    String *canthrow = Getattr(parameter, canthrow_attribute);
+    if (canthrow)
+      Setattr(n, "csharp:canthrow", "1");
+    Delete(canthrow_attribute);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * excodeSubstitute()
+   * If a method can throw a C# exception, additional exception code is added to
+   * check for the pending exception so that it can then throw the exception. The
+   * $excode special variable is replaced by the exception code in the excode
+   * typemap attribute.
+   * ----------------------------------------------------------------------------- */
+
+  void excodeSubstitute(Node *n, String *code, const String *typemap, Node *parameter) {
+    String *excode_attribute = NewStringf("tmap:%s:excode", typemap);
+    String *excode = Getattr(parameter, excode_attribute);
+    if (Getattr(n, "csharp:canthrow")) {
+      int count = Replaceall(code, "$excode", excode);
+      if (count < 1 || !excode) {
+	Swig_warning(WARN_CSHARP_EXCODE, input_file, line_number,
+		     "C# exception may not be thrown - no $excode or excode attribute in '%s' typemap.\n", typemap);
+      }
+    } else {
+      Replaceall(code, "$excode", empty_string);
+    }
+    Delete(excode_attribute);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * addOpenNamespace()
+   * ----------------------------------------------------------------------------- */
+
+  void addOpenNamespace(String *namspace, File *file) {
+    if (namspace)
+      if (Len(namspace) > 0)
+	Printf(file, "namespace %s {\n", namspace);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * addCloseNamespace()
+   * ----------------------------------------------------------------------------- */
+
+  void addCloseNamespace(String *namspace, File *file) {
+    if (namspace)
+      if (Len(namspace) > 0)
+	Printf(file, "\n}\n");
+  }
+
+  /*----------------------------------------------------------------------
+   * Start of director methods
+   *--------------------------------------------------------------------*/
+
+#if 0
+  /*----------------------------------------------------------------------
+   * emitDirectorUpcalls()
+   *--------------------------------------------------------------------*/
+
+  void emitDirectorUpcalls() {
+    if (n_dmethods) {
+      Wrapper *w = NewWrapper();
+      String *dmethod_data = NewString("");
+      int n_methods = 0;
+      Iterator udata_iter;
+
+      udata_iter = First(dmethods_seq);
+      while (udata_iter.item) {
+	UpcallData *udata = udata_iter.item;
+	Printf(dmethod_data, "  { \"%s\", \"%s\" }", Getattr(udata, "imclass_method"), Getattr(udata, "imclass_fdesc"));
+	++n_methods;
+
+	udata_iter = Next(udata_iter);
+
+	if (udata_iter.item)
+	  Putc(',', dmethod_data);
+	Putc('\n', dmethod_data);
+      }
+
+
+      Wrapper_print(w, f_wrappers);
+      Delete(dmethod_data);
+      Delete(swig_module_init);
+      DelWrapper(w);
+    }
+  }
+#endif
+
+  /*----------------------------------------------------------------------
+   * emitDirectorExtraMethods()
+   *
+   * This is where the director connect method is
+   * generated.
+   *--------------------------------------------------------------------*/
+  void emitDirectorExtraMethods(Node *n) {
+    if (!Swig_directorclass(n))
+      return;
+
+    // Output the director connect method:
+    String *norm_name = SwigType_namestr(Getattr(n, "name"));
+    String *swig_director_connect = NewStringf("%s_director_connect", proxy_class_name);
+    String *sym_name = Getattr(n, "sym:name");
+    Wrapper *code_wrap;
+
+    Printv(imclass_class_code, "\n  [DllImport(\"", dllimport, "\", EntryPoint=\"CSharp_", swig_director_connect, "\")]\n", NIL);
+    Printf(imclass_class_code, "  public static extern void %s(HandleRef jarg1", swig_director_connect);
+
+    code_wrap = NewWrapper();
+    Printf(code_wrap->def, "SWIGEXPORT void SWIGSTDCALL CSharp_%s(void *objarg", swig_director_connect);
+
+    Printf(code_wrap->code, "  %s *obj = (%s *)objarg;\n", norm_name, norm_name);
+    Printf(code_wrap->code, "  SwigDirector_%s *director = dynamic_cast<SwigDirector_%s *>(obj);\n", sym_name, sym_name);
+    // TODO: if statement not needed?? - Java too
+    Printf(code_wrap->code, "  if (director) {\n");
+    Printf(code_wrap->code, "    director->swig_connect_director(");
+
+    for (int i = first_class_dmethod; i < curr_class_dmethod; ++i) {
+      UpcallData *udata = Getitem(dmethods_seq, i);
+      String *methid = Getattr(udata, "class_methodidx");
+
+      Printf(code_wrap->def, ", ");
+      if (i != first_class_dmethod)
+	Printf(code_wrap->code, ", ");
+      Printf(code_wrap->def, "SwigDirector_%s::SWIG_Callback%s_t callback%s", sym_name, methid, methid);
+      Printf(code_wrap->code, "callback%s", methid);
+      Printf(imclass_class_code, ", %s.SwigDelegate%s_%s delegate%s", sym_name, sym_name, methid, methid);
+    }
+
+    Printf(code_wrap->def, ") {\n");
+    Printf(code_wrap->code, ");\n");
+    Printf(imclass_class_code, ");\n");
+    Printf(code_wrap->code, "  }\n");
+    Printf(code_wrap->code, "}\n");
+
+    Wrapper_print(code_wrap, f_wrappers);
+    DelWrapper(code_wrap);
+
+    Delete(swig_director_connect);
+  }
+
+  /* ---------------------------------------------------------------
+   * classDirectorMethod()
+   *
+   * Emit a virtual director method to pass a method call on to the 
+   * underlying Java object.
+   *
+   * --------------------------------------------------------------- */
+
+  int classDirectorMethod(Node *n, Node *parent, String *super) {
+    String *empty_str = NewString("");
+    String *classname = Getattr(parent, "sym:name");
+    String *c_classname = Getattr(parent, "name");
+    String *name = Getattr(n, "name");
+    String *symname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    SwigType *returntype = Getattr(n, "returntype");
+    String *overloaded_name = getOverloadedName(n);
+    String *storage = Getattr(n, "storage");
+    String *value = Getattr(n, "value");
+    String *decl = Getattr(n, "decl");
+    String *declaration = NewString("");
+    String *tm;
+    Parm *p;
+    int i;
+    Wrapper *w = NewWrapper();
+    ParmList *l = Getattr(n, "parms");
+    bool is_void = !(Cmp(returntype, "void"));
+    String *qualified_return = NewString("");
+    bool pure_virtual = (!(Cmp(storage, "virtual")) && !(Cmp(value, "0")));
+    int status = SWIG_OK;
+    bool output_director = true;
+    String *dirclassname = directorClassName(parent);
+    String *qualified_name = NewStringf("%s::%s", dirclassname, name);
+    SwigType *c_ret_type = NULL;
+    String *jupcall_args = NewString("");
+    String *imclass_dmethod;
+    String *callback_typedef_parms = NewString("");
+    String *delegate_parms = NewString("");
+    String *proxy_method_types = NewString("");
+    String *callback_def = NewString("");
+    String *callback_code = NewString("");
+    String *imcall_args = NewString("");
+    int gencomma = 0;
+    bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
+
+    // Kludge Alert: functionWrapper sets sym:overload properly, but it
+    // isn't at this point, so we have to manufacture it ourselves. At least
+    // we're consistent with the sym:overload name in functionWrapper. (?? when
+    // does the overloaded method name get set?)
+
+    imclass_dmethod = NewStringf("SwigDirector_%s", Swig_name_member(classname, overloaded_name));
+
+    if (returntype) {
+
+      qualified_return = SwigType_rcaststr(returntype, "c_result");
+
+      if (!is_void && !ignored_method) {
+	if (!SwigType_isclass(returntype)) {
+	  if (!(SwigType_ispointer(returntype) || SwigType_isreference(returntype))) {
+            String *construct_result = NewStringf("= SwigValueInit< %s >()", SwigType_lstr(returntype, 0));
+	    Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), construct_result, NIL);
+            Delete(construct_result);
+	  } else {
+	    String *base_typename = SwigType_base(returntype);
+	    String *resolved_typename = SwigType_typedef_resolve_all(base_typename);
+	    Symtab *symtab = Getattr(n, "sym:symtab");
+	    Node *typenode = Swig_symbol_clookup(resolved_typename, symtab);
+
+	    if (SwigType_ispointer(returntype) || (typenode && Getattr(typenode, "abstract"))) {
+	      /* initialize pointers to something sane. Same for abstract
+	         classes when a reference is returned. */
+	      Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), "= 0", NIL);
+	    } else {
+	      /* If returning a reference, initialize the pointer to a sane
+	         default - if a C# exception occurs, then the pointer returns
+	         something other than a NULL-initialized reference. */
+	      String *non_ref_type = Copy(returntype);
+
+	      /* Remove reference and const qualifiers */
+	      Replaceall(non_ref_type, "r.", "");
+	      Replaceall(non_ref_type, "q(const).", "");
+	      Wrapper_add_localv(w, "result_default", "static", SwigType_str(non_ref_type, "result_default"), "=", SwigType_str(non_ref_type, "()"), NIL);
+	      Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), "= &result_default", NIL);
+
+	      Delete(non_ref_type);
+	    }
+
+	    Delete(base_typename);
+	    Delete(resolved_typename);
+	  }
+	} else {
+	  SwigType *vt;
+
+	  vt = cplus_value_type(returntype);
+	  if (!vt) {
+	    Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), NIL);
+	  } else {
+	    Wrapper_add_localv(w, "c_result", SwigType_lstr(vt, "c_result"), NIL);
+	    Delete(vt);
+	  }
+	}
+      }
+
+      /* Create the intermediate class wrapper */
+      Parm *tp = NewParmFromNode(returntype, empty_str, n);
+
+      tm = Swig_typemap_lookup("imtype", tp, "", 0);
+      if (tm) {
+	String *imtypeout = Getattr(tp, "tmap:imtype:out");	// the type in the imtype typemap's out attribute overrides the type in the typemap
+	if (imtypeout)
+	  tm = imtypeout;
+        const String *im_directoroutattributes = Getattr(tp, "tmap:imtype:directoroutattributes");
+        if (im_directoroutattributes) {
+          Printf(callback_def, "  %s\n", im_directoroutattributes);
+          Printf(director_delegate_definitions, "  %s\n", im_directoroutattributes);
+        }
+
+	Printf(callback_def, "  private %s SwigDirector%s(", tm, overloaded_name);
+	if (!ignored_method)
+	  Printf(director_delegate_definitions, "  public delegate %s", tm);
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CSTYPE_UNDEF, input_file, line_number, "No imtype typemap defined for %s\n", SwigType_str(returntype, 0));
+      }
+
+      Parm *retpm = NewParmFromNode(returntype, empty_str, n);
+
+      if ((c_ret_type = Swig_typemap_lookup("ctype", retpm, "", 0))) {
+
+	if (!is_void && !ignored_method) {
+	  String *jretval_decl = NewStringf("%s jresult", c_ret_type);
+	  Wrapper_add_localv(w, "jresult", jretval_decl, "= 0", NIL);
+	  Delete(jretval_decl);
+	}
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CTYPE_UNDEF, input_file, line_number, "No ctype typemap defined for %s\n", SwigType_str(returntype, 0));
+	output_director = false;
+      }
+
+      Delete(retpm);
+    }
+
+    /* Go through argument list, attach lnames for arguments */
+    for (i = 0, p = l; p; p = nextSibling(p), ++i) {
+      String *arg = Getattr(p, "name");
+      String *lname = NewString("");
+
+      if (!arg && Cmp(Getattr(p, "type"), "void")) {
+	lname = NewStringf("arg%d", i);
+	Setattr(p, "name", lname);
+      } else
+	lname = arg;
+
+      Setattr(p, "lname", lname);
+    }
+
+    /* Attach the standard typemaps */
+    Swig_typemap_attach_parms("out", l, 0);
+    Swig_typemap_attach_parms("ctype", l, 0);
+    Swig_typemap_attach_parms("imtype", l, 0);
+    Swig_typemap_attach_parms("cstype", l, 0);
+    Swig_typemap_attach_parms("directorin", l, 0);
+    Swig_typemap_attach_parms("csdirectorin", l, 0);
+
+    /* Preamble code */
+    if (!ignored_method)
+      Printf(w->code, "if (!swig_callback%s) {\n", overloaded_name);
+
+    if (!pure_virtual) {
+      String *super_call = Swig_method_call(super, l);
+      if (is_void) {
+	Printf(w->code, "%s;\n", super_call);
+	if (!ignored_method)
+	  Printf(w->code, "return;\n");
+      } else {
+	Printf(w->code, "return %s;\n", super_call);
+      }
+      Delete(super_call);
+    } else {
+      Printf(w->code, " throw Swig::DirectorPureVirtualException(\"%s::%s\");\n", SwigType_namestr(c_classname), SwigType_namestr(name));
+    }
+
+    if (!ignored_method)
+      Printf(w->code, "} else {\n");
+
+    /* Go through argument list, convert from native to Java */
+    for (p = l; p; /* empty */ ) {
+      /* Is this superfluous? */
+      while (checkAttribute(p, "tmap:directorin:numinputs", "0")) {
+	p = Getattr(p, "tmap:directorin:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Copy(Getattr(p, "name"));
+      String *c_param_type = NULL;
+      String *c_decl = NewString("");
+      String *arg = NewString("");
+
+      Printf(arg, "j%s", ln);
+
+      /* Add various typemap's 'throws' clauses */
+      addThrows(n, "tmap:directorin", p);
+      addThrows(n, "tmap:out", p);
+
+      /* And add to the upcall args */
+      if (gencomma > 0)
+	Printf(jupcall_args, ", ");
+      Printf(jupcall_args, "%s", arg);
+
+      /* Get parameter's intermediary C type */
+      if ((c_param_type = Getattr(p, "tmap:ctype"))) {
+	String *ctypeout = Getattr(p, "tmap:ctype:out");	// the type in the ctype typemap's out attribute overrides the type in the typemap
+	if (ctypeout)
+	  c_param_type = ctypeout;
+
+	Parm *tp = NewParmFromNode(c_param_type, empty_str, n);
+	String *desc_tm = NULL;
+
+	/* Add to local variables */
+	Printf(c_decl, "%s %s", c_param_type, arg);
+	if (!ignored_method)
+	  Wrapper_add_localv(w, arg, c_decl, (!(SwigType_ispointer(pt) || SwigType_isreference(pt)) ? "" : "= 0"), NIL);
+
+	/* Add input marshalling code */
+	if ((desc_tm = Swig_typemap_lookup("directorin", tp, "", 0))
+	    && (tm = Getattr(p, "tmap:directorin"))) {
+
+	  Replaceall(tm, "$input", arg);
+	  Replaceall(tm, "$owner", "0");
+
+	  if (Len(tm))
+	    if (!ignored_method)
+	      Printf(w->code, "%s\n", tm);
+
+	  Delete(tm);
+
+	  /* Add C type to callback typedef */
+	  if (gencomma > 0)
+	    Printf(callback_typedef_parms, ", ");
+	  Printf(callback_typedef_parms, "%s", c_param_type);
+
+	  /* Add parameter to the intermediate class code if generating the
+	   * intermediate's upcall code */
+	  if ((tm = Getattr(p, "tmap:imtype"))) {
+
+	    String *imtypeout = Getattr(p, "tmap:imtype:out");	// the type in the imtype typemap's out attribute overrides the type in the typemap
+	    if (imtypeout)
+	      tm = imtypeout;
+            const String *im_directorinattributes = Getattr(p, "tmap:imtype:directorinattributes");
+
+	    String *din = Copy(Getattr(p, "tmap:csdirectorin"));
+
+	    if (din) {
+	      Replaceall(din, "$module", module_class_name);
+	      Replaceall(din, "$imclassname", imclass_name);
+	      substituteClassname(pt, din);
+	      Replaceall(din, "$iminput", ln);
+
+	      if (gencomma > 0) {
+		Printf(delegate_parms, ", ");
+		Printf(proxy_method_types, ", ");
+		Printf(imcall_args, ", ");
+	      }
+	      Printf(delegate_parms, "%s%s %s", im_directorinattributes ? im_directorinattributes : empty_string, tm, ln);
+
+	      if (Cmp(din, ln)) {
+		Printv(imcall_args, din, NIL);
+	      } else
+		Printv(imcall_args, ln, NIL);
+
+	      /* Get the C# parameter type */
+	      if ((tm = Getattr(p, "tmap:cstype"))) {
+		substituteClassname(pt, tm);
+		Printf(proxy_method_types, "typeof(%s)", tm);
+	      } else {
+		Swig_warning(WARN_CSHARP_TYPEMAP_CSWTYPE_UNDEF, input_file, line_number, "No cstype typemap defined for %s\n", SwigType_str(pt, 0));
+	      }
+	    } else {
+	      Swig_warning(WARN_CSHARP_TYPEMAP_CSDIRECTORIN_UNDEF, input_file, line_number, "No csdirectorin typemap defined for %s\n", SwigType_str(pt, 0));
+	      output_director = false;
+	    }
+	  } else {
+	    Swig_warning(WARN_CSHARP_TYPEMAP_CSTYPE_UNDEF, input_file, line_number, "No imtype typemap defined for %s\n", SwigType_str(pt, 0));
+	    output_director = false;
+	  }
+
+	  p = Getattr(p, "tmap:directorin:next");
+
+	  Delete(desc_tm);
+	} else {
+	  if (!desc_tm) {
+	    Swig_warning(WARN_CSHARP_TYPEMAP_CSDIRECTORIN_UNDEF, input_file, line_number,
+			 "No or improper directorin typemap defined for %s\n", SwigType_str(c_param_type, 0));
+	    p = nextSibling(p);
+	  } else if (!tm) {
+	    Swig_warning(WARN_CSHARP_TYPEMAP_CSDIRECTORIN_UNDEF, input_file, line_number,
+			 "No or improper directorin typemap defined for argument %s\n", SwigType_str(pt, 0));
+	    p = nextSibling(p);
+	  }
+
+	  output_director = false;
+	}
+
+	Delete(tp);
+      } else {
+	Swig_warning(WARN_CSHARP_TYPEMAP_CTYPE_UNDEF, input_file, line_number, "No ctype typemap defined for %s\n", SwigType_str(pt, 0));
+	output_director = false;
+	p = nextSibling(p);
+      }
+
+      gencomma++;
+      Delete(arg);
+      Delete(c_decl);
+      Delete(c_param_type);
+    }
+
+    /* header declaration, start wrapper definition */
+    String *target;
+    SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type;
+    target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0);
+    Printf(w->def, "%s", target);
+    Delete(qualified_name);
+    Delete(target);
+    target = Swig_method_decl(rtype, decl, name, l, 0, 1);
+    Printf(declaration, "    virtual %s", target);
+    Delete(target);
+
+    // Get any Java exception classes in the throws typemap
+    ParmList *throw_parm_list = NULL;
+
+    if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) {
+      int gencomma = 0;
+
+      Append(w->def, " throw(");
+      Append(declaration, " throw(");
+
+      if (throw_parm_list)
+	Swig_typemap_attach_parms("throws", throw_parm_list, 0);
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	if ((tm = Getattr(p, "tmap:throws"))) {
+	  addThrows(n, "tmap:throws", p);
+
+	  if (gencomma++) {
+	    Append(w->def, ", ");
+	    Append(declaration, ", ");
+	  }
+
+	  Printf(w->def, "%s", SwigType_str(Getattr(p, "type"), 0));
+	  Printf(declaration, "%s", SwigType_str(Getattr(p, "type"), 0));
+	}
+      }
+
+      Append(w->def, ")");
+      Append(declaration, ")");
+    }
+
+    Append(w->def, " {");
+    Append(declaration, ";\n");
+
+    /* Finish off the inherited upcall's definition */
+
+    Printf(callback_def, "%s)", delegate_parms);
+    Printf(callback_def, " {\n");
+
+    /* Emit the intermediate class's upcall to the actual class */
+
+    String *upcall = NewStringf("%s(%s)", symname, imcall_args);
+
+    if (!is_void) {
+      Parm *tp = NewParmFromNode(returntype, empty_str, n);
+
+      if ((tm = Swig_typemap_lookup("csdirectorout", tp, "", 0))) {
+	substituteClassname(returntype, tm);
+	Replaceall(tm, "$cscall", upcall);
+
+	Printf(callback_code, "    return %s;\n", tm);
+      }
+
+      Delete(tm);
+      Delete(tp);
+    } else
+      Printf(callback_code, "    %s;\n", upcall);
+
+    Printf(callback_code, "  }\n");
+    Delete(upcall);
+
+    if (!ignored_method) {
+      if (!is_void)
+	Printf(w->code, "jresult = (%s) ", c_ret_type);
+
+      Printf(w->code, "swig_callback%s(%s);\n", overloaded_name, jupcall_args);
+
+      if (!is_void) {
+	String *jresult_str = NewString("jresult");
+	String *result_str = NewString("c_result");
+	Parm *tp = NewParmFromNode(returntype, result_str, n);
+
+	/* Copy jresult into c_result... */
+	if ((tm = Swig_typemap_lookup("directorout", tp, result_str, w))) {
+	  addThrows(n, "tmap:directorout", tp);
+	  Replaceall(tm, "$input", jresult_str);
+	  Replaceall(tm, "$result", result_str);
+	  Printf(w->code, "%s\n", tm);
+	} else {
+	  Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number,
+		       "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(returntype, 0),
+		       SwigType_namestr(c_classname), SwigType_namestr(name));
+	  output_director = false;
+	}
+
+	Delete(tp);
+	Delete(jresult_str);
+	Delete(result_str);
+      }
+
+      /* Terminate wrapper code */
+      Printf(w->code, "}\n");
+      if (!is_void)
+	Printf(w->code, "return %s;", qualified_return);
+    }
+
+    Printf(w->code, "}");
+
+    // We expose virtual protected methods via an extra public inline method which makes a straight call to the wrapped class' method
+    String *inline_extra_method = NewString("");
+    if (dirprot_mode() && !is_public(n) && !pure_virtual) {
+      Printv(inline_extra_method, declaration, NIL);
+      String *extra_method_name = NewStringf("%sSwigPublic", name);
+      Replaceall(inline_extra_method, name, extra_method_name);
+      Replaceall(inline_extra_method, ";\n", " {\n      ");
+      if (!is_void)
+	Printf(inline_extra_method, "return ");
+      String *methodcall = Swig_method_call(super, l);
+      Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
+      Delete(methodcall);
+      Delete(extra_method_name);
+    }
+
+    /* emit code */
+    if (status == SWIG_OK && output_director) {
+      if (!is_void) {
+	Replaceall(w->code, "$null", qualified_return);
+      } else {
+	Replaceall(w->code, "$null", "");
+      }
+      if (!ignored_method)
+	Printv(director_delegate_callback, "\n", callback_def, callback_code, NIL);
+      if (!Getattr(n, "defaultargs")) {
+	Wrapper_print(w, f_directors);
+	Printv(f_directors_h, declaration, NIL);
+	Printv(f_directors_h, inline_extra_method, NIL);
+      }
+    }
+
+    if (!ignored_method) {
+      /* Emit the actual upcall through */
+      UpcallData *udata = addUpcallMethod(imclass_dmethod, symname, decl, overloaded_name);
+      String *methid = Getattr(udata, "class_methodidx");
+
+      Printf(director_callback_typedefs, "    typedef %s (SWIGSTDCALL* SWIG_Callback%s_t)(", c_ret_type, methid);
+      Printf(director_callback_typedefs, "%s);\n", callback_typedef_parms);
+      Printf(director_callbacks, "    SWIG_Callback%s_t swig_callback%s;\n", methid, overloaded_name);
+
+      Printf(director_delegate_definitions, " SwigDelegate%s_%s(%s);\n", classname, methid, delegate_parms);
+      Printf(director_delegate_instances, "  private SwigDelegate%s_%s swigDelegate%s;\n", classname, methid, methid);
+      Printf(director_method_types, "  private static Type[] swigMethodTypes%s = new Type[] { %s };\n", methid, proxy_method_types);
+      Printf(director_connect_parms, "SwigDirector%s%s delegate%s", classname, methid, methid);
+    }
+
+    Delete(qualified_return);
+    Delete(c_ret_type);
+    Delete(declaration);
+    Delete(callback_typedef_parms);
+    Delete(delegate_parms);
+    Delete(proxy_method_types);
+    Delete(callback_def);
+    Delete(callback_code);
+    DelWrapper(w);
+
+    return status;
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorConstructor(Node *n) {
+    Node *parent = parentNode(n);
+    String *decl = Getattr(n, "decl");;
+    String *supername = Swig_class_name(parent);
+    String *classname = directorClassName(parent);
+    String *sub = NewString("");
+    Parm *p;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms;
+    int argidx = 0;
+
+    /* Assign arguments to superclass's parameters, if not already done */
+    for (p = superparms; p; p = nextSibling(p)) {
+      String *pname = Getattr(p, "name");
+
+      if (!pname) {
+	pname = NewStringf("arg%d", argidx++);
+	Setattr(p, "name", pname);
+      }
+    }
+
+    // TODO: Is this copy needed?
+    parms = CopyParmList(superparms);
+
+    if (!Getattr(n, "defaultargs")) {
+      /* constructor */
+      {
+	String *basetype = Getattr(parent, "classtype");
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 0);
+	String *call = Swig_csuperclass_call(0, basetype, superparms);
+	String *classtype = SwigType_namestr(Getattr(n, "name"));
+
+	Printf(f_directors, "%s::%s : %s, %s {\n", classname, target, call, Getattr(parent, "director:ctor"));
+	Printf(f_directors, "  swig_init_callbacks();\n");
+	Printf(f_directors, "}\n\n");
+
+	Delete(classtype);
+	Delete(target);
+	Delete(call);
+      }
+
+      /* constructor header */
+      {
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 1);
+	Printf(f_directors_h, "    %s;\n", target);
+	Delete(target);
+      }
+    }
+
+    Delete(sub);
+    Delete(supername);
+    Delete(parms);
+    return Language::classDirectorConstructor(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorDefaultConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorDefaultConstructor(Node *n) {
+    String *classname = Swig_class_name(n);
+    String *classtype = SwigType_namestr(Getattr(n, "name"));
+    Wrapper *w = NewWrapper();
+
+    Printf(w->def, "SwigDirector_%s::SwigDirector_%s() : %s {", classname, classname, Getattr(n, "director:ctor"));
+    Printf(w->code, "}\n");
+    Wrapper_print(w, f_directors);
+
+    Printf(f_directors_h, "    SwigDirector_%s();\n", classname);
+    DelWrapper(w);
+    Delete(classtype);
+    Delete(classname);
+    return Language::classDirectorDefaultConstructor(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * classDirectorInit()
+   * ------------------------------------------------------------ */
+
+  int classDirectorInit(Node *n) {
+    Delete(none_comparison);
+    none_comparison = NewString("");	// not used
+
+    Delete(director_ctor_code);
+    director_ctor_code = NewString("$director_new");
+
+    Java_director_declaration(n);
+
+    Printf(f_directors_h, "%s {\n", Getattr(n, "director:decl"));
+    Printf(f_directors_h, "\npublic:\n");
+
+    /* Keep track of the director methods for this class */
+    first_class_dmethod = curr_class_dmethod = n_dmethods;
+
+    director_callback_typedefs = NewString("");
+    director_callbacks = NewString("");
+    director_delegate_callback = NewString("");
+    director_delegate_definitions = NewString("");
+    director_delegate_instances = NewString("");
+    director_method_types = NewString("");
+    director_connect_parms = NewString("");
+
+    return Language::classDirectorInit(n);
+  }
+
+  /* ----------------------------------------------------------------------
+   * classDirectorDestructor()
+   * ---------------------------------------------------------------------- */
+
+  int classDirectorDestructor(Node *n) {
+    Node *current_class = getCurrentClass();
+    String *full_classname = Getattr(current_class, "name");
+    String *classname = Swig_class_name(current_class);
+    Wrapper *w = NewWrapper();
+
+    if (Getattr(n, "throw")) {
+      Printf(f_directors_h, "    virtual ~SwigDirector_%s() throw ();\n", classname);
+      Printf(w->def, "SwigDirector_%s::~SwigDirector_%s() throw () {\n", classname, classname);
+    } else {
+      Printf(f_directors_h, "    virtual ~SwigDirector_%s();\n", classname);
+      Printf(w->def, "SwigDirector_%s::~SwigDirector_%s() {\n", classname, classname);
+    }
+
+    /* Ensure that correct directordisconnect typemap's method name is called
+     * here: */
+
+    const String *disconn_tm = NULL;
+    Node *disconn_attr = NewHash();
+    String *disconn_methodname = NULL;
+
+    disconn_tm = typemapLookup("directordisconnect", full_classname, WARN_NONE, disconn_attr);
+    disconn_methodname = Getattr(disconn_attr, "tmap:directordisconnect:methodname");
+
+    Printv(w->code, "}\n", NIL);
+
+    Wrapper_print(w, f_directors);
+
+    DelWrapper(w);
+    Delete(disconn_attr);
+    Delete(classname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorEnd()
+   * ------------------------------------------------------------ */
+
+  int classDirectorEnd(Node *n) {
+    int i;
+    String *director_classname = directorClassName(n);
+
+    Wrapper *w = NewWrapper();
+
+    if (Len(director_callback_typedefs) > 0) {
+      Printf(f_directors_h, "\n%s", director_callback_typedefs);
+    }
+
+    Printf(f_directors_h, "    void swig_connect_director(");
+
+    Printf(w->def, "void %s::swig_connect_director(", director_classname);
+
+    for (i = first_class_dmethod; i < curr_class_dmethod; ++i) {
+      UpcallData *udata = Getitem(dmethods_seq, i);
+      String *methid = Getattr(udata, "class_methodidx");
+      String *overname = Getattr(udata, "overname");
+
+      Printf(f_directors_h, "SWIG_Callback%s_t callback%s", methid, overname);
+      Printf(w->def, "SWIG_Callback%s_t callback%s", methid, overname);
+      Printf(w->code, "swig_callback%s = callback%s;\n", overname, overname);
+      if (i != curr_class_dmethod - 1) {
+	Printf(f_directors_h, ", ");
+	Printf(w->def, ", ");
+      }
+    }
+
+    Printf(f_directors_h, ");\n");
+    Printf(w->def, ") {");
+
+
+    if (Len(director_callback_typedefs) > 0) {
+      Printf(f_directors_h, "\nprivate:\n%s", director_callbacks);
+    }
+    Printf(f_directors_h, "    void swig_init_callbacks();\n");
+    Printf(f_directors_h, "};\n\n");
+    Printf(w->code, "}\n\n");
+
+    Printf(w->code, "void %s::swig_init_callbacks() {\n", director_classname);
+    for (i = first_class_dmethod; i < curr_class_dmethod; ++i) {
+      UpcallData *udata = Getitem(dmethods_seq, i);
+      String *overname = Getattr(udata, "overname");
+      Printf(w->code, "swig_callback%s = 0;\n", overname);
+    }
+    Printf(w->code, "}");
+
+    Wrapper_print(w, f_directors);
+
+    DelWrapper(w);
+
+    return Language::classDirectorEnd(n);
+  }
+
+  /* --------------------------------------------------------------------
+   * classDirectorDisown()
+   * ------------------------------------------------------------------*/
+  virtual int classDirectorDisown(Node *n) {
+    (void) n;
+    return SWIG_OK;
+  }
+
+  /*----------------------------------------------------------------------
+   * extraDirectorProtectedCPPMethodsRequired()
+   *--------------------------------------------------------------------*/
+
+  bool extraDirectorProtectedCPPMethodsRequired() const {
+    return false;
+  }
+
+  /*----------------------------------------------------------------------
+   * Java_director_declaration()
+   *
+   * Generate the director class's declaration
+   * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {"
+   *--------------------------------------------------------------------*/
+ 
+  void Java_director_declaration(Node *n) {
+
+    String *base = Getattr(n, "classtype");
+    String *class_ctor = NewString("Swig::Director()");
+
+    String *classname = Swig_class_name(n);
+    String *directorname = NewStringf("SwigDirector_%s", classname);
+    String *declaration = Swig_class_declaration(n, directorname);
+
+    Printf(declaration, " : public %s, public Swig::Director", base);
+
+    // Stash stuff for later.
+    Setattr(n, "director:decl", declaration);
+    Setattr(n, "director:ctor", class_ctor);
+  }
+
+};				/* class CSHARP */
+
+/* -----------------------------------------------------------------------------
+ * swig_csharp()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_csharp() {
+  return new CSHARP();
+}
+extern "C" Language *swig_csharp(void) {
+  return new_swig_csharp();
+}
+
+/* -----------------------------------------------------------------------------
+ * Static member variables
+ * ----------------------------------------------------------------------------- */
+
+const char *CSHARP::usage = (char *) "\
+C# Options (available with -csharp)\n\
+     -dllimport <dl> - Override DllImport attribute name to <dl>\n\
+     -namespace <nm> - Generate wrappers into C# namespace <nm>\n\
+     -noproxy        - Generate the low-level functional interface instead\n\
+                       of proxy classes\n\
+     -oldvarnames    - old intermediary method names for variable wrappers\n\
+\n";
diff --git a/trunk/Source/Modules/directors.cxx b/trunk/Source/Modules/directors.cxx
new file mode 100644
index 0000000..4363cd8
--- /dev/null
+++ b/trunk/Source/Modules/directors.cxx
@@ -0,0 +1,288 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * directors.cxx
+ *
+ * Director support functions.
+ * Not all of these may be necessary, and some may duplicate existing functionality
+ * in SWIG.  --MR
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_directors_cxx[] = "$Id";
+
+#include "swigmod.h"
+
+/* Swig_csuperclass_call()
+ *
+ * Generates a fully qualified method call, including the full parameter list.
+ * e.g. "base::method(i, j)"
+ *
+ */
+
+String *Swig_csuperclass_call(String *base, String *method, ParmList *l) {
+  String *call = NewString("");
+  int arg_idx = 0;
+  Parm *p;
+  if (base) {
+    Printf(call, "%s::", base);
+  }
+  Printf(call, "%s(", method);
+  for (p = l; p; p = nextSibling(p)) {
+    String *pname = Getattr(p, "name");
+    if (!pname && Cmp(Getattr(p, "type"), "void")) {
+      pname = NewString("");
+      Printf(pname, "arg%d", arg_idx++);
+    }
+    if (p != l)
+      Printf(call, ", ");
+    Printv(call, pname, NIL);
+  }
+  Printf(call, ")");
+  return call;
+}
+
+/* Swig_class_declaration()
+ *
+ * Generate the start of a class/struct declaration.
+ * e.g. "class myclass"
+ *
+ */
+
+String *Swig_class_declaration(Node *n, String *name) {
+  if (!name) {
+    name = Getattr(n, "sym:name");
+  }
+  String *result = NewString("");
+  String *kind = Getattr(n, "kind");
+  Printf(result, "%s %s", kind, name);
+  return result;
+}
+
+String *Swig_class_name(Node *n) {
+  String *name;
+  name = Copy(Getattr(n, "sym:name"));
+  return name;
+}
+
+/* Swig_director_declaration()
+ *
+ * Generate the full director class declaration, complete with base classes.
+ * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {"
+ *
+ */
+
+String *Swig_director_declaration(Node *n) {
+  String *classname = Swig_class_name(n);
+  String *directorname = NewStringf("SwigDirector_%s", classname);
+  String *base = Getattr(n, "classtype");
+  String *declaration = Swig_class_declaration(n, directorname);
+  Printf(declaration, " : public %s, public Swig::Director {\n", base);
+  Delete(classname);
+  Delete(directorname);
+  return declaration;
+}
+
+
+String *Swig_method_call(String_or_char *name, ParmList *parms) {
+  String *func;
+  int i = 0;
+  int comma = 0;
+  Parm *p = parms;
+  SwigType *pt;
+  String *nname;
+
+  func = NewString("");
+  nname = SwigType_namestr(name);
+  Printf(func, "%s(", nname);
+  while (p) {
+    String *pname;
+    pt = Getattr(p, "type");
+    if ((SwigType_type(pt) != T_VOID)) {
+      if (comma)
+	Printf(func, ",");
+      pname = Getattr(p, "name");
+      Printf(func, "%s", pname);
+      comma = 1;
+      i++;
+    }
+    p = nextSibling(p);
+  }
+  Printf(func, ")");
+  return func;
+}
+
+/* Swig_method_decl
+ *
+ * Misnamed and misappropriated!  Taken from SWIG's type string manipulation utilities
+ * and modified to generate full (or partial) type qualifiers for method declarations,
+ * local variable declarations, and return value casting.  More importantly, it merges
+ * parameter type information with actual parameter names to produce a complete method
+ * declaration that fully mirrors the original method declaration.
+ *
+ * There is almost certainly a saner way to do this.
+ *
+ * This function needs to be cleaned up and possibly split into several smaller 
+ * functions.  For instance, attaching default names to parameters should be done in a 
+ * separate function.
+ *
+ */
+
+String *Swig_method_decl(SwigType *returntype, SwigType *decl, const String_or_char *id, List *args, int strip, int values) {
+  String *result;
+  List *elements;
+  String *element = 0, *nextelement;
+  int is_const = 0;
+  int nelements, i;
+  int is_func = 0;
+  int arg_idx = 0;
+
+  if (id) {
+    result = NewString(Char(id));
+  } else {
+    result = NewString("");
+  }
+
+  elements = SwigType_split(decl);
+  nelements = Len(elements);
+  if (nelements > 0) {
+    element = Getitem(elements, 0);
+  }
+  for (i = 0; i < nelements; i++) {
+    if (i < (nelements - 1)) {
+      nextelement = Getitem(elements, i + 1);
+    } else {
+      nextelement = 0;
+    }
+    if (SwigType_isqualifier(element)) {
+      int skip = 0;
+      DOH *q = 0;
+      if (!strip) {
+	q = SwigType_parm(element);
+	if (!Cmp(q, "const")) {
+	  is_const = 1;
+	  is_func = SwigType_isfunction(nextelement);
+	  if (is_func)
+	    skip = 1;
+	  skip = 1;
+	}
+	if (!skip) {
+	  Insert(result, 0, " ");
+	  Insert(result, 0, q);
+	}
+	Delete(q);
+      }
+    } else if (SwigType_isfunction(element)) {
+      Parm *parm;
+      String *p;
+      Append(result, "(");
+      parm = args;
+      while (parm != 0) {
+	String *type = Getattr(parm, "type");
+	String *name = Getattr(parm, "name");
+	if (!name && Cmp(type, "void")) {
+	  name = NewString("");
+	  Printf(name, "arg%d", arg_idx++);
+	  Setattr(parm, "name", name);
+	}
+	if (!name) {
+	  name = NewString("");
+	}
+	p = SwigType_str(type, name);
+	Append(result, p);
+	String *value = Getattr(parm, "value");
+	if (values && (value != 0)) {
+	  Printf(result, " = %s", value);
+	}
+	parm = nextSibling(parm);
+	if (parm != 0)
+	  Append(result, ", ");
+      }
+      Append(result, ")");
+    } else if (returntype) { // This check is intended for conversion operators to a pointer/reference which needs the pointer/reference ignoring in the declaration
+      if (SwigType_ispointer(element)) {
+	Insert(result, 0, "*");
+	if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	  Insert(result, 0, "(");
+	  Append(result, ")");
+	}
+      } else if (SwigType_ismemberpointer(element)) {
+	String *q;
+	q = SwigType_parm(element);
+	Insert(result, 0, "::*");
+	Insert(result, 0, q);
+	if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	  Insert(result, 0, "(");
+	  Append(result, ")");
+	}
+	Delete(q);
+      } else if (SwigType_isreference(element)) {
+	Insert(result, 0, "&");
+      } else if (SwigType_isarray(element)) {
+	DOH *size;
+	Append(result, "[");
+	size = SwigType_parm(element);
+	Append(result, size);
+	Append(result, "]");
+	Delete(size);
+      } else {
+	if (Strcmp(element, "v(...)") == 0) {
+	  Insert(result, 0, "...");
+	} else {
+	  String *bs = SwigType_namestr(element);
+	  Insert(result, 0, " ");
+	  Insert(result, 0, bs);
+	  Delete(bs);
+	}
+      }
+    }
+    element = nextelement;
+  }
+
+  Delete(elements);
+
+  if (is_const) {
+    if (is_func) {
+      Append(result, " ");
+      Append(result, "const");
+    } else {
+      Insert(result, 0, "const ");
+    }
+  }
+
+  Chop(result);
+
+  if (returntype) {
+    Insert(result, 0, " ");
+    String *rtype = SwigType_str(returntype, 0);
+    Insert(result, 0, rtype);
+    Delete(rtype);
+  }
+
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_director_emit_dynamic_cast()
+ *
+ * In order to call protected virtual director methods from the target language, we need
+ * to add an extra dynamic_cast to call the public C++ wrapper in the director class. 
+ * Also for non-static protected members when the allprotected option is on.
+ * ----------------------------------------------------------------------------- */
+void Swig_director_emit_dynamic_cast(Node *n, Wrapper *f) {
+  // TODO: why is the storage element removed in staticmemberfunctionHandler ??
+  if ((!is_public(n) && (is_member_director(n) || GetFlag(n, "explicitcall"))) || 
+      (is_non_virtual_protected_access(n) && !(checkAttribute(n, "staticmemberfunctionHandler:storage", "static") || 
+                                               checkAttribute(n, "storage", "static"))
+                                          && !Equal(nodeType(n), "constructor"))) {
+    Node *parent = Getattr(n, "parentNode");
+    String *symname = Getattr(parent, "sym:name");
+    String *dirname = NewStringf("SwigDirector_%s", symname);
+    String *dirdecl = NewStringf("%s *darg = 0", dirname);
+    Wrapper_add_local(f, "darg", dirdecl);
+    Printf(f->code, "darg = dynamic_cast<%s *>(arg1);\n", dirname);
+    Delete(dirname);
+    Delete(dirdecl);
+  }
+}
+
diff --git a/trunk/Source/Modules/emit.cxx b/trunk/Source/Modules/emit.cxx
new file mode 100644
index 0000000..a4cf8ce
--- /dev/null
+++ b/trunk/Source/Modules/emit.cxx
@@ -0,0 +1,512 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * emit.cxx
+ *
+ * Useful functions for emitting various pieces of code.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_emit_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+/* -----------------------------------------------------------------------------
+ * emit_return_variable()
+ *
+ * Emits a variable declaration for a function return value.
+ * The variable name is always called result.
+ * n => Node of the method being wrapped
+ * rt => the return type
+ * f => the wrapper to generate code into
+ * ----------------------------------------------------------------------------- */
+
+void emit_return_variable(Node *n, SwigType *rt, Wrapper *f) {
+
+  if (!GetFlag(n, "tmap:out:optimal")) {
+    if (rt && (SwigType_type(rt) != T_VOID)) {
+      SwigType *vt = cplus_value_type(rt);
+      SwigType *tt = vt ? vt : rt;
+      SwigType *lt = SwigType_ltype(tt);
+      String *lstr = SwigType_str(lt, "result");
+      if (SwigType_ispointer(lt)) {
+        Wrapper_add_localv(f, "result", lstr, "= 0", NULL);
+      } else {
+        Wrapper_add_local(f, "result", lstr);
+      }
+      if (vt) {
+        Delete(vt);
+      }
+      Delete(lt);
+      Delete(lstr);
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * emit_parameter_variables()
+ *
+ * Emits a list of variable declarations for function parameters.
+ * The variable names are always called arg1, arg2, etc...
+ * l => the parameter list
+ * f => the wrapper to generate code into
+ * ----------------------------------------------------------------------------- */
+
+void emit_parameter_variables(ParmList *l, Wrapper *f) {
+
+  Parm *p;
+  String *tm;
+
+  /* Emit function arguments */
+  Swig_cargs(f, l);
+
+  /* Attach typemaps to parameters */
+  /*  Swig_typemap_attach_parms("ignore",l,f); */
+
+  Swig_typemap_attach_parms("default", l, f);
+  Swig_typemap_attach_parms("arginit", l, f);
+
+  /* Apply the arginit and default */
+  p = l;
+  while (p) {
+    tm = Getattr(p, "tmap:arginit");
+    if (tm) {
+      Replace(tm, "$target", Getattr(p, "lname"), DOH_REPLACE_ANY);
+      Printv(f->code, tm, "\n", NIL);
+      p = Getattr(p, "tmap:arginit:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  /* Apply the default typemap */
+  p = l;
+  while (p) {
+    tm = Getattr(p, "tmap:default");
+    if (tm) {
+      Replace(tm, "$target", Getattr(p, "lname"), DOH_REPLACE_ANY);
+      Printv(f->code, tm, "\n", NIL);
+      p = Getattr(p, "tmap:default:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * emit_attach_parmmaps()
+ *
+ * Attach the standard parameter related typemaps.
+ * ----------------------------------------------------------------------------- */
+
+void emit_attach_parmmaps(ParmList *l, Wrapper *f) {
+  Swig_typemap_attach_parms("in", l, f);
+  Swig_typemap_attach_parms("typecheck", l, 0);
+  Swig_typemap_attach_parms("argout", l, f);
+  Swig_typemap_attach_parms("check", l, f);
+  Swig_typemap_attach_parms("freearg", l, f);
+
+  {
+    /* This is compatibility code to deal with the deprecated "ignore" typemap */
+    Parm *p = l;
+    Parm *np;
+    String *tm;
+    while (p) {
+      tm = Getattr(p, "tmap:in");
+      if (tm && checkAttribute(p, "tmap:in:numinputs", "0")) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	np = Getattr(p, "tmap:in:next");
+	while (p && (p != np)) {
+	  /*	  Setattr(p,"ignore","1");    Deprecate */
+	  p = nextSibling(p);
+	}
+      } else if (tm) {
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+  }
+
+  /* Perform a sanity check on "in" and "freearg" typemaps.  These
+     must exactly match to avoid chaos.  If a mismatch occurs, we
+     nuke the freearg typemap */
+
+  {
+    Parm *p = l;
+    Parm *npin, *npfreearg;
+    while (p) {
+      npin = Getattr(p, "tmap:in:next");
+
+      /*
+         if (Getattr(p,"tmap:ignore")) {
+         npin = Getattr(p,"tmap:ignore:next");
+         } else if (Getattr(p,"tmap:in")) {
+         npin = Getattr(p,"tmap:in:next");
+         }
+       */
+
+      if (Getattr(p, "tmap:freearg")) {
+	npfreearg = Getattr(p, "tmap:freearg:next");
+	if (npin != npfreearg) {
+	  while (p != npin) {
+	    Delattr(p, "tmap:freearg");
+	    Delattr(p, "tmap:freearg:next");
+	    p = nextSibling(p);
+	  }
+	}
+      }
+      p = npin;
+    }
+  }
+
+  /* Check for variable length arguments with no input typemap.
+     If no input is defined, we set this to ignore and print a
+     message.
+   */
+  {
+    Parm *p = l;
+    Parm *lp = 0;
+    while (p) {
+      if (!checkAttribute(p, "tmap:in:numinputs", "0")) {
+	lp = p;
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      }
+      if (SwigType_isvarargs(Getattr(p, "type"))) {
+	Swig_warning(WARN_LANG_VARARGS, input_file, line_number, "Variable length arguments discarded.\n");
+	Setattr(p, "tmap:in", "");
+      }
+      lp = 0;
+      p = nextSibling(p);
+    }
+
+    /* Check if last input argument is variable length argument */
+    if (lp) {
+      p = lp;
+      while (p) {
+	if (SwigType_isvarargs(Getattr(p, "type"))) {
+	  Setattr(l, "emit:varargs", lp);
+	  break;
+	}
+	p = nextSibling(p);
+      }
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * emit_num_arguments()
+ *
+ * Calculate the total number of arguments.   This function is safe for use
+ * with multi-valued typemaps which may change the number of arguments in
+ * strange ways.
+ * ----------------------------------------------------------------------------- */
+
+int emit_num_arguments(ParmList *parms) {
+  Parm *p = parms;
+  int nargs = 0;
+
+  while (p) {
+    if (Getattr(p, "tmap:in")) {
+      nargs += GetInt(p, "tmap:in:numinputs");
+      p = Getattr(p, "tmap:in:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  /* DB 04/02/2003: Not sure this is necessary with tmap:in:numinputs */
+  /*
+     if (parms && (p = Getattr(parms,"emit:varargs"))) {
+     if (!nextSibling(p)) {
+     nargs--;
+     }
+     }
+   */
+  return nargs;
+}
+
+/* -----------------------------------------------------------------------------
+ * emit_num_required()
+ *
+ * Computes the number of required arguments.  This function is safe for
+ * use with multi-valued typemaps and knows how to skip over everything
+ * properly. Note that parameters with default values are counted unless
+ * the compact default args option is on.
+ * ----------------------------------------------------------------------------- */
+
+int emit_num_required(ParmList *parms) {
+  Parm *p = parms;
+  int nargs = 0;
+  Parm *first_default_arg = 0;
+  int compactdefargs = ParmList_is_compactdefargs(p);
+
+  while (p) {
+    if (Getattr(p, "tmap:in") && checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    } else {
+      if (Getattr(p, "tmap:default"))
+	break;
+      if (Getattr(p, "value")) {
+	if (!first_default_arg)
+	  first_default_arg = p;
+	if (compactdefargs)
+	  break;
+      }
+      nargs += GetInt(p, "tmap:in:numinputs");
+      if (Getattr(p, "tmap:in")) {
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+  }
+
+  /* Print error message for non-default arguments following default arguments */
+  /* The error message is printed more than once with most language modules, this ought to be fixed */
+  if (first_default_arg) {
+    p = first_default_arg;
+    while (p) {
+      if (Getattr(p, "tmap:in") && checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	if (!Getattr(p, "value") && (!Getattr(p, "tmap:default"))) {
+	  Swig_error(Getfile(p), Getline(p), "Non-optional argument '%s' follows an optional argument.\n", Getattr(p, "name"));
+	}
+	if (Getattr(p, "tmap:in")) {
+	  p = Getattr(p, "tmap:in:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+  }
+
+  /* DB 04/02/2003: Not sure this is necessary with tmap:in:numinputs */
+  /*
+     if (parms && (p = Getattr(parms,"emit:varargs"))) {
+     if (!nextSibling(p)) {
+     nargs--;
+     }
+     }
+   */
+  return nargs;
+}
+
+/* -----------------------------------------------------------------------------
+ * emit_isvarargs()
+ *
+ * Checks if a function is a varargs function
+ * ----------------------------------------------------------------------------- */
+
+int emit_isvarargs(ParmList *p) {
+  if (!p)
+    return 0;
+  if (Getattr(p, "emit:varargs"))
+    return 1;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * void emit_mark_vararg_parms()
+ *
+ * Marks the vararg parameters which are to be ignored.
+ * Vararg parameters are marked as ignored if there is no 'in' varargs (...) 
+ * typemap.
+ * ----------------------------------------------------------------------------- */
+
+void emit_mark_varargs(ParmList *l) {
+  Parm *p = l;
+  while (p) {
+    if (SwigType_isvarargs(Getattr(p, "type")))
+      if (!Getattr(p, "tmap:in"))
+	Setattr(p, "varargs:ignore", "1");
+    p = nextSibling(p);
+  }
+}
+
+#if 0
+/* replace_contract_args.  This function replaces argument names in contract
+   specifications.   Used in conjunction with the %contract directive. */
+
+static void replace_contract_args(Parm *cp, Parm *rp, String *s) {
+  while (cp && rp) {
+    String *n = Getattr(cp, "name");
+    if (n) {
+      Replace(s, n, Getattr(rp, "lname"), DOH_REPLACE_ID);
+    }
+    cp = nextSibling(cp);
+    rp = nextSibling(rp);
+  }
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * int emit_action_code()
+ *
+ * Emits action code for a wrapper. Adds in exception handling code (%exception).
+ * eaction -> the action code to emit
+ * wrappercode -> the emitted code (output)
+ * ----------------------------------------------------------------------------- */
+int emit_action_code(Node *n, String *wrappercode, String *eaction) {
+  assert(Getattr(n, "wrap:name"));
+
+  /* Look for except feature (%exception) */
+  String *tm = GetFlagAttr(n, "feature:except");
+  if (tm)
+    tm = Copy(tm);
+  if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) {
+    if (Strstr(tm, "$")) {
+      Replaceall(tm, "$name", Getattr(n, "name"));
+      Replaceall(tm, "$symname", Getattr(n, "sym:name"));
+      Replaceall(tm, "$function", eaction); // deprecated
+      Replaceall(tm, "$action", eaction);
+      Replaceall(tm, "$wrapname", Getattr(n, "wrap:name"));
+      String *overloaded = Getattr(n, "sym:overloaded");
+      Replaceall(tm, "$overname", overloaded ? Char(Getattr(n, "sym:overname")) : "");
+
+      if (Strstr(tm, "$decl")) {
+        String *decl = Swig_name_decl(n);
+        Replaceall(tm, "$decl", decl);
+        Delete(decl);
+      }
+      if (Strstr(tm, "$fulldecl")) {
+        String *fulldecl = Swig_name_fulldecl(n);
+        Replaceall(tm, "$fulldecl", fulldecl);
+        Delete(fulldecl);
+      }
+    }
+    Printv(wrappercode, tm, "\n", NIL);
+    Delete(tm);
+    return 1;
+  } else {
+    Printv(wrappercode, eaction, "\n", NIL);
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * int emit_action()
+ *
+ * Emits the call to the wrapped function. 
+ * Adds in exception specification exception handling and %exception code.
+ * ----------------------------------------------------------------------------- */
+String *emit_action(Node *n) {
+  String *actioncode = NewStringEmpty();
+  String *tm;
+  String *action;
+  String *wrap;
+  SwigType *rt;
+  ParmList *catchlist = Getattr(n, "catchlist");
+
+  /* Look for fragments */
+  {
+    String *fragment = Getattr(n, "feature:fragment");
+    if (fragment) {
+      char *c, *tok;
+      String *t = Copy(fragment);
+      c = Char(t);
+      tok = strtok(c, ",");
+      while (tok) {
+	String *fname = NewString(tok);
+	Setfile(fname, Getfile(n));
+	Setline(fname, Getline(n));
+	Swig_fragment_emit(fname);
+	Delete(fname);
+	tok = strtok(NULL, ",");
+      }
+      Delete(t);
+    }
+  }
+
+  /* Emit wrapper code (if any) */
+  wrap = Getattr(n, "wrap:code");
+  if (wrap && Swig_filebyname("header") != Getattr(n, "wrap:code:done")) {
+    File *f_code = Swig_filebyname("header");
+    if (f_code) {
+      Printv(f_code, wrap, NIL);
+    }
+    Setattr(n, "wrap:code:done", f_code);
+  }
+
+  action = Getattr(n, "feature:action");
+  if (!action)
+    action = Getattr(n, "wrap:action");
+  assert(action != 0);
+
+  /* Get the return type */
+  rt = Getattr(n, "type");
+
+  /* Emit contract code (if any) */
+  if (Swig_contract_mode_get()) {
+    /* Preassertion */
+    tm = Getattr(n, "contract:preassert");
+    if (Len(tm)) {
+      Printv(actioncode, tm, "\n", NIL);
+    }
+  }
+  /* Exception handling code */
+
+  /* saves action -> eaction for postcatching exception */
+  String *eaction = NewString("");
+
+  /* If we are in C++ mode and there is an exception specification. We're going to
+     enclose the block in a try block */
+  if (catchlist) {
+    Printf(eaction, "try {\n");
+  }
+
+  Printv(eaction, action, NIL);
+
+  if (catchlist) {
+    int unknown_catch = 0;
+    Printf(eaction, "}\n");
+    for (Parm *ep = catchlist; ep; ep = nextSibling(ep)) {
+      String *em = Swig_typemap_lookup("throws", ep, "_e", 0);
+      if (em) {
+	SwigType *et = Getattr(ep, "type");
+	SwigType *etr = SwigType_typedef_resolve_all(et);
+	if (SwigType_isreference(etr) || SwigType_ispointer(etr) || SwigType_isarray(etr)) {
+	  Printf(eaction, "catch(%s) {", SwigType_str(et, "_e"));
+	} else if (SwigType_isvarargs(etr)) {
+	  Printf(eaction, "catch(...) {");
+	} else {
+	  Printf(eaction, "catch(%s) {", SwigType_str(et, "&_e"));
+	}
+	Printv(eaction, em, "\n", NIL);
+	Printf(eaction, "}\n");
+      } else {
+	Swig_warning(WARN_TYPEMAP_THROW, Getfile(n), Getline(n), "No 'throws' typemap defined for exception type '%s'\n", SwigType_str(Getattr(ep, "type"), 0));
+	unknown_catch = 1;
+      }
+    }
+    if (unknown_catch) {
+      Printf(eaction, "catch(...) { throw; }\n");
+    }
+  }
+
+  /* Look for except typemap (Deprecated) */
+  tm = Swig_typemap_lookup("except", n, "result", 0);
+  if (tm) {
+    Setattr(n, "feature:except", tm);
+    tm = 0;
+  }
+
+  /* emit the except feature code */
+  emit_action_code(n, actioncode, eaction);
+
+  Delete(eaction);
+
+  /* Emit contract code (if any) */
+  if (Swig_contract_mode_get()) {
+    /* Postassertion */
+    tm = Getattr(n, "contract:postassert");
+    if (Len(tm)) {
+      Printv(actioncode, tm, "\n", NIL);
+    }
+  }
+
+  return actioncode;
+}
diff --git a/trunk/Source/Modules/guile.cxx b/trunk/Source/Modules/guile.cxx
new file mode 100644
index 0000000..f5f0800
--- /dev/null
+++ b/trunk/Source/Modules/guile.cxx
@@ -0,0 +1,1752 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * guile.cxx
+ *
+ * Guile language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_guile_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#include <ctype.h>
+
+// Note string broken in half for compilers that can't handle long strings
+static const char *guile_usage = (char *) "\
+Guile Options (available with -guile)\n\
+     -prefix <name>          - Use <name> as prefix [default \"gswig_\"]\n\
+     -package <name>         - Set the path of the module to <name>\n\
+                               (default NULL)\n\
+     -emitsetters            - Emit procedures-with-setters for variables\n\
+                               and structure slots.\n\
+     -onlysetters            - Don't emit traditional getter and setter\n\
+                               procedures for structure slots,\n\
+                               only emit procedures-with-setters.\n\
+     -procdoc <file>         - Output procedure documentation to <file>\n\
+     -procdocformat <format> - Output procedure documentation in <format>;\n\
+                               one of `guile-1.4', `plain', `texinfo'\n\
+     -linkage <lstyle>       - Use linkage protocol <lstyle> (default `simple')\n\
+                               Use `module' for native Guile module linking\n\
+                               (requires Guile >= 1.5.0).  Use `passive' for\n\
+                               passive linking (no C-level module-handling code),\n\
+                               `ltdlmod' for Guile's old dynamic module\n\
+                               convention (Guile <= 1.4), or `hobbit' for hobbit\n\
+                               modules.\n\
+     -scmstub                - Output Scheme file with module declaration and\n\
+                               exports; only with `passive' and `simple' linkage\n\
+     -gh                     - Use the gh_ Guile API. (Guile <= 1.8) \n\
+     -scm                    - Use the scm Guile API. (Guile >= 1.6, default) \n\
+     -proxy                  - Export GOOPS class definitions\n\
+     -emitslotaccessors      - Emit accessor methods for all GOOPS slots\n" "\
+     -primsuffix <suffix>    - Name appended to primitive module when exporting\n\
+                               GOOPS classes. (default = \"primitive\")\n\
+     -goopsprefix <prefix>   - Prepend <prefix> to all goops identifiers\n\
+     -useclassprefix         - Prepend the class name to all goops identifiers\n\
+     -exportprimitive        - Add the (export ...) code from scmstub into the\n\
+                               GOOPS file.\n";
+
+static File *f_runtime = 0;
+static File *f_header = 0;
+static File *f_wrappers = 0;
+static File *f_init = 0;
+
+
+static char *prefix = (char *) "gswig_";
+static char *module = 0;
+static char *package = 0;
+static enum {
+  GUILE_LSTYLE_SIMPLE,		// call `SWIG_init()'
+  GUILE_LSTYLE_PASSIVE,		// passive linking (no module code)
+  GUILE_LSTYLE_MODULE,		// native guile module linking (Guile >= 1.4.1)
+  GUILE_LSTYLE_LTDLMOD_1_4,	// old (Guile <= 1.4) dynamic module convention
+  GUILE_LSTYLE_HOBBIT		// use (hobbit4d link)
+} linkage = GUILE_LSTYLE_SIMPLE;
+
+static File *procdoc = 0;
+static bool scmstub = false;
+static String *scmtext;
+static bool goops = false;
+static String *goopstext;
+static String *goopscode;
+static String *goopsexport;
+
+static enum {
+  GUILE_1_4,
+  PLAIN,
+  TEXINFO
+} docformat = GUILE_1_4;
+
+static int emit_setters = 0;
+static int only_setters = 0;
+static int emit_slot_accessors = 0;
+static int struct_member = 0;
+
+static String *beforereturn = 0;
+static String *return_nothing_doc = 0;
+static String *return_one_doc = 0;
+static String *return_multi_doc = 0;
+
+static String *exported_symbols = 0;
+
+static int use_scm_interface = 1;
+static int exporting_destructor = 0;
+static String *swigtype_ptr = 0;
+
+/* GOOPS stuff */
+static String *primsuffix = 0;
+static String *class_name = 0;
+static String *short_class_name = 0;
+static String *goops_class_methods;
+static int in_class = 0;
+static int have_constructor = 0;
+static int useclassprefix = 0;	// -useclassprefix argument
+static String *goopsprefix = 0;	// -goopsprefix argument
+static int primRenamer = 0;	// if (use-modules ((...) :renamer ...) is exported to GOOPS file
+static int exportprimitive = 0;	// -exportprimitive argument
+static String *memberfunction_name = 0;
+
+extern "C" {
+  static int has_classname(Node *class_node) {
+    return Getattr(class_node, "guile:goopsclassname") != NULL;
+  }
+}
+
+class GUILE:public Language {
+public:
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+    int i, orig_len;
+
+     SWIG_library_directory("guile");
+     SWIG_typemap_lang("guile");
+
+    // Look for certain command line options
+    for (i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-help") == 0) {
+	  fputs(guile_usage, stdout);
+	  SWIG_exit(EXIT_SUCCESS);
+	} else if (strcmp(argv[i], "-prefix") == 0) {
+	  if (argv[i + 1]) {
+	    prefix = new char[strlen(argv[i + 1]) + 2];
+	    strcpy(prefix, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-package") == 0) {
+	  if (argv[i + 1]) {
+	    package = new char[strlen(argv[i + 1]) + 2];
+	    strcpy(package, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-Linkage") == 0 || strcmp(argv[i], "-linkage") == 0) {
+	  if (argv[i + 1]) {
+	    if (0 == strcmp(argv[i + 1], "ltdlmod"))
+	      linkage = GUILE_LSTYLE_LTDLMOD_1_4;
+	    else if (0 == strcmp(argv[i + 1], "hobbit"))
+	      linkage = GUILE_LSTYLE_HOBBIT;
+	    else if (0 == strcmp(argv[i + 1], "simple"))
+	      linkage = GUILE_LSTYLE_SIMPLE;
+	    else if (0 == strcmp(argv[i + 1], "passive"))
+	      linkage = GUILE_LSTYLE_PASSIVE;
+	    else if (0 == strcmp(argv[i + 1], "module"))
+	      linkage = GUILE_LSTYLE_MODULE;
+	    else
+	      Swig_arg_error();
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-procdoc") == 0) {
+	  if (argv[i + 1]) {
+	    procdoc = NewFile(argv[i + 1], (char *) "w");
+	    if (!procdoc) {
+	      FileErrorDisplay(argv[i + 1]);
+	      SWIG_exit(EXIT_FAILURE);
+	    }
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-procdocformat") == 0) {
+	  if (strcmp(argv[i + 1], "guile-1.4") == 0)
+	    docformat = GUILE_1_4;
+	  else if (strcmp(argv[i + 1], "plain") == 0)
+	    docformat = PLAIN;
+	  else if (strcmp(argv[i + 1], "texinfo") == 0)
+	    docformat = TEXINFO;
+	  else
+	    Swig_arg_error();
+	  Swig_mark_arg(i);
+	  Swig_mark_arg(i + 1);
+	  i++;
+	} else if (strcmp(argv[i], "-emit-setters") == 0 || strcmp(argv[i], "-emitsetters") == 0) {
+	  emit_setters = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-only-setters") == 0 || strcmp(argv[i], "-onlysetters") == 0) {
+	  emit_setters = 1;
+	  only_setters = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-emit-slot-accessors") == 0 || strcmp(argv[i], "-emitslotaccessors") == 0) {
+	  emit_slot_accessors = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-scmstub") == 0) {
+	  scmstub = true;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) {
+	  goops = true;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-gh") == 0) {
+	  use_scm_interface = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-scm") == 0) {
+	  use_scm_interface = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-primsuffix") == 0) {
+	  if (argv[i + 1]) {
+	    primsuffix = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-goopsprefix") == 0) {
+	  if (argv[i + 1]) {
+	    goopsprefix = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-useclassprefix") == 0) {
+	  useclassprefix = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-exportprimitive") == 0) {
+	  exportprimitive = 1;
+	  // should use Swig_warning() here?
+	  Swig_mark_arg(i);
+	}
+      }
+    }
+
+    // set default value for primsuffix
+    if (primsuffix == NULL)
+      primsuffix = NewString("primitive");
+
+    //goops support can only be enabled if passive or module linkage is used
+    if (goops) {
+      if (linkage != GUILE_LSTYLE_PASSIVE && linkage != GUILE_LSTYLE_MODULE) {
+	Printf(stderr, "guile: GOOPS support requires passive or module linkage\n");
+	exit(1);
+      }
+    }
+
+    if (goops) {
+      // -proxy implies -emit-setters
+      emit_setters = 1;
+    }
+
+    if ((linkage == GUILE_LSTYLE_PASSIVE && scmstub) || linkage == GUILE_LSTYLE_MODULE)
+      primRenamer = 1;
+
+    if (exportprimitive && primRenamer) {
+      // should use Swig_warning() ?
+      Printf(stderr, "guile: Warning: -exportprimitive only makes sense with passive linkage without a scmstub.\n");
+    }
+    // Make sure `prefix' ends in an underscore
+
+    orig_len = strlen(prefix);
+    if (prefix[orig_len - 1] != '_') {
+      prefix[1 + orig_len] = 0;
+      prefix[orig_len] = '_';
+    }
+
+    /* Add a symbol for this module */
+    Preprocessor_define("SWIGGUILE 1", 0);
+    /* Read in default typemaps */
+    if (use_scm_interface)
+      SWIG_config_file("guile_scm.swg");
+    else
+      SWIG_config_file("guile_gh.swg");
+    allow_overloading();
+
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+
+    scmtext = NewString("");
+    Swig_register_filebyname("scheme", scmtext);
+    exported_symbols = NewString("");
+    goopstext = NewString("");
+    Swig_register_filebyname("goops", goopstext);
+    goopscode = NewString("");
+    goopsexport = NewString("");
+
+    Printf(f_runtime, "/* -*- buffer-read-only: t -*- vi: set ro: */\n");
+    Swig_banner(f_runtime);
+
+    Printf(f_runtime, "/* Implementation : GUILE */\n\n");
+
+    if (!use_scm_interface) {
+      if (SwigRuntime == 1)
+	Printf(f_runtime, "#define SWIG_GLOBAL\n");
+      if (SwigRuntime == 2)
+	Printf(f_runtime, "#define SWIG_NOINCLUDE\n");
+    }
+
+    /* Write out directives and declarations */
+
+    module = Swig_copy_string(Char(Getattr(n, "name")));
+
+    switch (linkage) {
+    case GUILE_LSTYLE_SIMPLE:
+      /* Simple linkage; we have to export the SWIG_init function. The user can
+         rename the function by a #define. */
+      Printf(f_runtime, "#define SWIG_GUILE_INIT_STATIC extern\n");
+      break;
+    default:
+      /* Other linkage; we make the SWIG_init function static */
+      Printf(f_runtime, "#define SWIG_GUILE_INIT_STATIC static\n");
+      break;
+    }
+
+    if (CPlusPlus) {
+      Printf(f_runtime, "extern \"C\" {\n\n");
+    }
+    Printf(f_runtime, "SWIG_GUILE_INIT_STATIC void\nSWIG_init (void);\n");
+    if (CPlusPlus) {
+      Printf(f_runtime, "\n}\n");
+    }
+
+    Language::top(n);
+
+    /* Close module */
+
+    Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
+
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+
+    Printf(f_init, "}\n\n");
+    Printf(f_init, "#ifdef __cplusplus\n}\n#endif\n");
+
+    String *module_name = NewString("");
+
+    if (!module)
+      Printv(module_name, "swig", NIL);
+    else {
+      if (package)
+	Printf(module_name, "%s/%s", package, module);
+      else
+	Printv(module_name, module, NIL);
+    }
+    emit_linkage(module_name);
+
+    Delete(module_name);
+
+    if (procdoc) {
+      Delete(procdoc);
+      procdoc = NULL;
+    }
+    Delete(goopscode);
+    Delete(goopsexport);
+    Delete(goopstext);
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+    return SWIG_OK;
+  }
+
+  void emit_linkage(String *module_name) {
+    String *module_func = NewString("");
+
+    if (CPlusPlus) {
+      Printf(f_init, "extern \"C\" {\n\n");
+    }
+
+    Printv(module_func, module_name, NIL);
+    Replaceall(module_func, "-", "_");
+
+    switch (linkage) {
+    case GUILE_LSTYLE_SIMPLE:
+      Printf(f_init, "\n/* Linkage: simple */\n");
+      break;
+    case GUILE_LSTYLE_PASSIVE:
+      Printf(f_init, "\n/* Linkage: passive */\n");
+      Replaceall(module_func, "/", "_");
+      Insert(module_func, 0, "scm_init_");
+      Append(module_func, "_module");
+
+      Printf(f_init, "SCM\n%s (void)\n{\n", module_func);
+      Printf(f_init, "  SWIG_init();\n");
+      Printf(f_init, "  return SCM_UNSPECIFIED;\n");
+      Printf(f_init, "}\n");
+      break;
+    case GUILE_LSTYLE_LTDLMOD_1_4:
+      Printf(f_init, "\n/* Linkage: ltdlmod */\n");
+      Replaceall(module_func, "/", "_");
+      Insert(module_func, 0, "scm_init_");
+      Append(module_func, "_module");
+      Printf(f_init, "SCM\n%s (void)\n{\n", module_func);
+      {
+	String *mod = NewString(module_name);
+	Replaceall(mod, "/", " ");
+	Printf(f_init, "    scm_register_module_xxx (\"%s\", (void *) SWIG_init);\n", mod);
+	Printf(f_init, "    return SCM_UNSPECIFIED;\n");
+	Delete(mod);
+      }
+      Printf(f_init, "}\n");
+      break;
+    case GUILE_LSTYLE_MODULE:
+      Printf(f_init, "\n/* Linkage: module */\n");
+      Replaceall(module_func, "/", "_");
+      Insert(module_func, 0, "scm_init_");
+      Append(module_func, "_module");
+
+      Printf(f_init, "static void SWIG_init_helper(void *data)\n");
+      Printf(f_init, "{\n    SWIG_init();\n");
+      if (Len(exported_symbols) > 0)
+	Printf(f_init, "    scm_c_export(%sNULL);", exported_symbols);
+      Printf(f_init, "\n}\n\n");
+
+      Printf(f_init, "SCM\n%s (void)\n{\n", module_func);
+      {
+	String *mod = NewString(module_name);
+	if (goops)
+	  Printv(mod, "-", primsuffix, NIL);
+	Replaceall(mod, "/", " ");
+	Printf(f_init, "    scm_c_define_module(\"%s\",\n", mod);
+	Printf(f_init, "      SWIG_init_helper, NULL);\n");
+	Printf(f_init, "    return SCM_UNSPECIFIED;\n");
+	Delete(mod);
+      }
+      Printf(f_init, "}\n");
+      break;
+    case GUILE_LSTYLE_HOBBIT:
+      Printf(f_init, "\n/* Linkage: hobbit */\n");
+      Replaceall(module_func, "/", "_slash_");
+      Insert(module_func, 0, "scm_init_");
+      Printf(f_init, "SCM\n%s (void)\n{\n", module_func);
+      {
+	String *mod = NewString(module_name);
+	Replaceall(mod, "/", " ");
+	Printf(f_init, "    scm_register_module_xxx (\"%s\", (void *) SWIG_init);\n", mod);
+	Printf(f_init, "    return SCM_UNSPECIFIED;\n");
+	Delete(mod);
+      }
+      Printf(f_init, "}\n");
+      break;
+    default:
+      abort();			// for now
+    }
+
+    if (scmstub) {
+      /* Emit Scheme stub if requested */
+      String *primitive_name = NewString(module_name);
+      if (goops)
+	Printv(primitive_name, "-", primsuffix, NIL);
+
+      String *mod = NewString(primitive_name);
+      Replaceall(mod, "/", " ");
+
+      String *fname = NewStringf("%s%s.scm",
+				 SWIG_output_directory(),
+				 primitive_name);
+      Delete(primitive_name);
+      File *scmstubfile = NewFile(fname, (char *) "w");
+      if (!scmstubfile) {
+	FileErrorDisplay(fname);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Delete(fname);
+
+      Printf(scmstubfile, ";;; -*- buffer-read-only: t -*- vi: set ro: */\n");
+      Printf(scmstubfile, ";;; Automatically generated by SWIG; do not edit.\n\n");
+      if (linkage == GUILE_LSTYLE_SIMPLE || linkage == GUILE_LSTYLE_PASSIVE)
+	Printf(scmstubfile, "(define-module (%s))\n\n", mod);
+      Delete(mod);
+      Printf(scmstubfile, "%s", scmtext);
+      if ((linkage == GUILE_LSTYLE_SIMPLE || linkage == GUILE_LSTYLE_PASSIVE)
+	  && Len(exported_symbols) > 0) {
+	String *ex = NewString(exported_symbols);
+	Replaceall(ex, ", ", "\n        ");
+	Replaceall(ex, "\"", "");
+	Chop(ex);
+	Printf(scmstubfile, "\n(export %s)\n", ex);
+	Delete(ex);
+      }
+      Delete(scmstubfile);
+    }
+
+    if (goops) {
+      String *mod = NewString(module_name);
+      Replaceall(mod, "/", " ");
+
+      String *fname = NewStringf("%s%s.scm", SWIG_output_directory(),
+				 module_name);
+      File *goopsfile = NewFile(fname, (char *) "w");
+      if (!goopsfile) {
+	FileErrorDisplay(fname);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Delete(fname);
+      Printf(goopsfile, ";;; -*- buffer-read-only: t -*- vi: set ro: */\n");
+      Printf(goopsfile, ";;; Automatically generated by SWIG; do not edit.\n\n");
+      Printf(goopsfile, "(define-module (%s))\n", mod);
+      Printf(goopsfile, "%s\n", goopstext);
+      Printf(goopsfile, "(use-modules (oop goops) (Swig common))\n");
+      if (primRenamer) {
+	Printf(goopsfile, "(use-modules ((%s-%s) :renamer (symbol-prefix-proc 'primitive:)))\n", mod, primsuffix);
+      }
+      Printf(goopsfile, "%s\n(export %s)", goopscode, goopsexport);
+      if (exportprimitive) {
+	String *ex = NewString(exported_symbols);
+	Replaceall(ex, ", ", "\n        ");
+	Replaceall(ex, "\"", "");
+	Chop(ex);
+	Printf(goopsfile, "\n(export %s)", ex);
+	Delete(ex);
+      }
+      Delete(mod);
+      Delete(goopsfile);
+    }
+
+    Delete(module_func);
+    if (CPlusPlus) {
+      Printf(f_init, "\n}\n");
+    }
+  }
+
+  /* Return true iff T is a pointer type */
+
+  int is_a_pointer(SwigType *t) {
+    return SwigType_ispointer(SwigType_typedef_resolve_all(t));
+  }
+
+  /* Report an error handling the given type. */
+
+  void throw_unhandled_guile_type_error(SwigType *d) {
+    Swig_warning(WARN_TYPEMAP_UNDEF, input_file, line_number, "Unable to handle type %s.\n", SwigType_str(d, 0));
+  }
+
+  /* Write out procedure documentation */
+
+  void write_doc(const String *proc_name, const String *signature, const String *doc, const String *signature2 = NULL) {
+    switch (docformat) {
+    case GUILE_1_4:
+      Printv(procdoc, "\f\n", NIL);
+      Printv(procdoc, "(", signature, ")\n", NIL);
+      if (signature2)
+	Printv(procdoc, "(", signature2, ")\n", NIL);
+      Printv(procdoc, doc, "\n", NIL);
+      break;
+    case PLAIN:
+      Printv(procdoc, "\f", proc_name, "\n\n", NIL);
+      Printv(procdoc, "(", signature, ")\n", NIL);
+      if (signature2)
+	Printv(procdoc, "(", signature2, ")\n", NIL);
+      Printv(procdoc, doc, "\n\n", NIL);
+      break;
+    case TEXINFO:
+      Printv(procdoc, "\f", proc_name, "\n", NIL);
+      Printv(procdoc, "@deffn primitive ", signature, "\n", NIL);
+      if (signature2)
+	Printv(procdoc, "@deffnx primitive ", signature2, "\n", NIL);
+      Printv(procdoc, doc, "\n", NIL);
+      Printv(procdoc, "@end deffn\n\n", NIL);
+      break;
+    }
+  }
+
+  /* returns false if the typemap is an empty string */
+  bool handle_documentation_typemap(String *output,
+				    const String *maybe_delimiter, Parm *p, const String *typemap, const String *default_doc, const String *name = NULL) {
+    String *tmp = NewString("");
+    String *tm;
+    if (!(tm = Getattr(p, typemap))) {
+      Printf(tmp, "%s", default_doc);
+      tm = tmp;
+    }
+    bool result = (Len(tm) > 0);
+    if (maybe_delimiter && Len(output) > 0 && Len(tm) > 0) {
+      Printv(output, maybe_delimiter, NIL);
+    }
+    const String *pn = (name == NULL) ? (const String *) Getattr(p, "name") : name;
+    String *pt = Getattr(p, "type");
+    Replaceall(tm, "$name", pn);	// legacy for $parmname
+    Replaceall(tm, "$type", SwigType_str(pt, 0));
+    /* $NAME is like $name, but marked-up as a variable. */
+    String *ARGNAME = NewString("");
+    if (docformat == TEXINFO)
+      Printf(ARGNAME, "@var{%s}", pn);
+    else
+      Printf(ARGNAME, "%(upper)s", pn);
+    Replaceall(tm, "$NAME", ARGNAME);
+    Replaceall(tm, "$PARMNAME", ARGNAME);
+    Printv(output, tm, NIL);
+    Delete(tmp);
+    return result;
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * Create a function declaration and register it with the interpreter.
+   * ------------------------------------------------------------ */
+
+  virtual int functionWrapper(Node *n) {
+    String *iname = Getattr(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    Parm *p;
+    String *proc_name = 0;
+    char source[256];
+    Wrapper *f = NewWrapper();;
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *signature = NewString("");
+    String *doc_body = NewString("");
+    String *returns = NewString("");
+    String *method_signature = NewString("");
+    String *primitive_args = NewString("");
+    Hash *scheme_arg_names = NewHash();
+    int num_results = 1;
+    String *tmp = NewString("");
+    String *tm;
+    int i;
+    int numargs = 0;
+    int numreq = 0;
+    String *overname = 0;
+    int args_passed_as_array = 0;
+    int scheme_argnum = 0;
+    bool any_specialized_arg = false;
+
+    // Make a wrapper name for this
+    String *wname = Swig_name_wrapper(iname);
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+      args_passed_as_array = 1;
+    } else {
+      if (!addSymbol(iname, n)) {
+        DelWrapper(f);
+	return SWIG_ERROR; 
+      }
+    }
+    if (overname) {
+      Append(wname, overname);
+    }
+    Setattr(n, "wrap:name", wname);
+
+    // Build the name for scheme.
+    proc_name = NewString(iname);
+    Replaceall(proc_name, "_", "-");
+
+    /* Emit locals etc. into f->code; figure out which args to ignore */
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    /* Get number of required and total arguments */
+    numargs = emit_num_arguments(l);
+    numreq = emit_num_required(l);
+
+    /* Declare return variable */
+
+    Wrapper_add_local(f, "gswig_result", "SCM gswig_result");
+    Wrapper_add_local(f, "gswig_list_p", "SWIGUNUSED int gswig_list_p = 0");
+
+    /* Open prototype and signature */
+
+    Printv(f->def, "static SCM\n", wname, " (", NIL);
+    if (args_passed_as_array) {
+      Printv(f->def, "int argc, SCM *argv", NIL);
+    }
+    Printv(signature, proc_name, NIL);
+
+    /* Now write code to extract the parameters */
+
+    for (i = 0, p = l; i < numargs; i++) {
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      int opt_p = (i >= numreq);
+
+      // Produce names of source and target
+      if (args_passed_as_array)
+	sprintf(source, "argv[%d]", i);
+      else
+	sprintf(source, "s_%d", i);
+      String *target = Getattr(p, "lname");
+
+      if (!args_passed_as_array) {
+	if (i != 0)
+	  Printf(f->def, ", ");
+	Printf(f->def, "SCM s_%d", i);
+      }
+      if (opt_p) {
+	Printf(f->code, "    if (%s != SCM_UNDEFINED) {\n", source);
+      }
+      if ((tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$source", source);
+	Replaceall(tm, "$target", target);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);
+	Printv(f->code, tm, "\n", NIL);
+
+	SwigType *pb = SwigType_typedef_resolve_all(SwigType_base(pt));
+	SwigType *pn = Getattr(p, "name");
+	String *argname;
+	scheme_argnum++;
+	if (pn && !Getattr(scheme_arg_names, pn))
+	  argname = pn;
+	else {
+	  /* Anonymous arg or re-used argument name -- choose a name that cannot clash */
+	  argname = NewStringf("%%arg%d", scheme_argnum);
+	}
+
+	if (procdoc) {
+	  if (i == numreq) {
+	    /* First optional argument */
+	    Printf(signature, " #:optional");
+	  }
+	  /* Add to signature (arglist) */
+	  handle_documentation_typemap(signature, " ", p, "tmap:in:arglist", "$name", argname);
+	  /* Document the type of the arg in the documentation body */
+	  handle_documentation_typemap(doc_body, ", ", p, "tmap:in:doc", "$NAME is of type <$type>", argname);
+	}
+
+	if (goops) {
+	  if (i < numreq) {
+	    if (strcmp("void", Char(pt)) != 0) {
+	      Node *class_node = Swig_symbol_clookup_check(pb, Getattr(n, "sym:symtab"),
+							   has_classname);
+	      String *goopsclassname = (class_node == NULL) ? NULL : Getattr(class_node, "guile:goopsclassname");
+	      /* do input conversion */
+	      if (goopsclassname) {
+		Printv(method_signature, " (", argname, " ", goopsclassname, ")", NIL);
+		any_specialized_arg = true;
+	      } else {
+		Printv(method_signature, " ", argname, NIL);
+	      }
+	      Printv(primitive_args, " ", argname, NIL);
+	      Setattr(scheme_arg_names, argname, p);
+	    }
+	  }
+	}
+
+	if (!pn) {
+	  Delete(argname);
+	}
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	throw_unhandled_guile_type_error(pt);
+	p = nextSibling(p);
+      }
+      if (opt_p)
+	Printf(f->code, "    }\n");
+    }
+    if (Len(doc_body) > 0)
+      Printf(doc_body, ".\n");
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+    /* Pass output arguments back to the caller. */
+
+    /* Insert argument output code */
+    String *returns_argout = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	if (procdoc) {
+	  if (handle_documentation_typemap(returns_argout, ", ", p, "tmap:argout:doc", "$NAME (of type $type)")) {
+	    /* A documentation typemap that is not the empty string
+	       indicates that a value is returned to Scheme. */
+	    num_results++;
+	  }
+	}
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    if (use_scm_interface && exporting_destructor) {
+      /* Mark the destructor's argument as destroyed. */
+      String *tm = NewString("SWIG_Guile_MarkPointerDestroyed($input);");
+      Replaceall(tm, "$input", Getattr(l, "emit:input"));
+      Printv(cleanup, tm, "\n", NIL);
+      Delete(tm);
+    }
+
+    /* Close prototype */
+
+    Printf(f->def, ")\n{\n");
+
+    /* Define the scheme name in C. This define is used by several Guile
+       macros. */
+    Printv(f->def, "#define FUNC_NAME \"", proc_name, "\"", NIL);
+
+    // Now write code to make the function call
+    if (!use_scm_interface)
+      Printv(f->code, tab4, "gh_defer_ints();\n", NIL);
+
+    String *actioncode = emit_action(n);
+
+    if (!use_scm_interface)
+      Printv(actioncode, tab4, "gh_allow_ints();\n", NIL);
+
+    // Now have return value, figure out what to do with it.
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      Replaceall(tm, "$result", "gswig_result");
+      Replaceall(tm, "$target", "gswig_result");
+      Replaceall(tm, "$source", "result");
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "1");
+      else
+	Replaceall(tm, "$owner", "0");
+      Printv(f->code, tm, "\n", NIL);
+    } else {
+      throw_unhandled_guile_type_error(d);
+    }
+    emit_return_variable(n, d, f);
+
+    // Documentation
+    if ((tm = Getattr(n, "tmap:out:doc"))) {
+      Printv(returns, tm, NIL);
+      if (Len(tm) > 0)
+	num_results = 1;
+      else
+	num_results = 0;
+    } else {
+      String *s = SwigType_str(d, 0);
+      Chop(s);
+      Printf(returns, "<%s>", s);
+      Delete(s);
+      num_results = 1;
+    }
+    Append(returns, returns_argout);
+
+
+    // Dump the argument output code
+    Printv(f->code, outarg, NIL);
+
+    // Dump the argument cleanup code
+    Printv(f->code, cleanup, NIL);
+
+    // Look for any remaining cleanup
+
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printv(f->code, tm, "\n", NIL);
+      }
+    }
+    // Free any memory allocated by the function being wrapped..
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printv(f->code, tm, "\n", NIL);
+    }
+    // Wrap things up (in a manner of speaking)
+
+    if (beforereturn)
+      Printv(f->code, beforereturn, "\n", NIL);
+    Printv(f->code, "return gswig_result;\n", NIL);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", iname);
+    // Undefine the scheme name
+
+    Printf(f->code, "#undef FUNC_NAME\n");
+    Printf(f->code, "}\n");
+
+    Wrapper_print(f, f_wrappers);
+
+    if (!Getattr(n, "sym:overloaded")) {
+      if (numargs > 10) {
+	int i;
+	/* gh_new_procedure would complain: too many args */
+	/* Build a wrapper wrapper */
+	Printv(f_wrappers, "static SCM\n", wname, "_rest (SCM rest)\n", NIL);
+	Printv(f_wrappers, "{\n", NIL);
+	Printf(f_wrappers, "SCM arg[%d];\n", numargs);
+	Printf(f_wrappers, "SWIG_Guile_GetArgs (arg, rest, %d, %d, \"%s\");\n", numreq, numargs - numreq, proc_name);
+	Printv(f_wrappers, "return ", wname, "(", NIL);
+	Printv(f_wrappers, "arg[0]", NIL);
+	for (i = 1; i < numargs; i++)
+	  Printf(f_wrappers, ", arg[%d]", i);
+	Printv(f_wrappers, ");\n", NIL);
+	Printv(f_wrappers, "}\n", NIL);
+	/* Register it */
+	if (use_scm_interface) {
+	  Printf(f_init, "scm_c_define_gsubr(\"%s\", 0, 0, 1, (swig_guile_proc) %s_rest);\n", proc_name, wname);
+	} else {
+	  Printf(f_init, "gh_new_procedure(\"%s\", (swig_guile_proc) %s_rest, 0, 0, 1);\n", proc_name, wname);
+	}
+      } else if (emit_setters && struct_member && strlen(Char(proc_name)) > 3) {
+	int len = Len(proc_name);
+	const char *pc = Char(proc_name);
+	/* MEMBER-set and MEMBER-get functions. */
+	int is_setter = (pc[len - 3] == 's');
+	if (is_setter) {
+	  Printf(f_init, "SCM setter = ");
+	  struct_member = 2;	/* have a setter */
+	} else
+	  Printf(f_init, "SCM getter = ");
+	if (use_scm_interface) {
+	  /* GOOPS support uses the MEMBER-set and MEMBER-get functions,
+	     so ignore only_setters in this case. */
+	  if (only_setters && !goops)
+	    Printf(f_init, "scm_c_make_gsubr(\"%s\", %d, %d, 0, (swig_guile_proc) %s);\n", proc_name, numreq, numargs - numreq, wname);
+	  else
+	    Printf(f_init, "scm_c_define_gsubr(\"%s\", %d, %d, 0, (swig_guile_proc) %s);\n", proc_name, numreq, numargs - numreq, wname);
+	} else {
+	  if (only_setters && !goops)
+	    Printf(f_init, "scm_make_gsubr(\"%s\", %d, %d, 0, (swig_guile_proc) %s);\n", proc_name, numreq, numargs - numreq, wname);
+	  else
+	    Printf(f_init, "gh_new_procedure(\"%s\", (swig_guile_proc) %s, %d, %d, 0);\n", proc_name, wname, numreq, numargs - numreq);
+	}
+	if (!is_setter) {
+	  /* Strip off "-get" */
+	  char *pws_name = (char *) malloc(sizeof(char) * (len - 3));
+	  strncpy(pws_name, pc, len - 3);
+	  pws_name[len - 4] = 0;
+	  if (struct_member == 2) {
+	    /* There was a setter, so create a procedure with setter */
+	    if (use_scm_interface) {
+	      Printf(f_init, "scm_c_define");
+	    } else {
+	      Printf(f_init, "gh_define");
+	    }
+	    Printf(f_init, "(\"%s\", " "scm_make_procedure_with_setter(getter, setter));\n", pws_name);
+	  } else {
+	    /* There was no setter, so make an alias to the getter */
+	    if (use_scm_interface) {
+	      Printf(f_init, "scm_c_define");
+	    } else {
+	      Printf(f_init, "gh_define");
+	    }
+	    Printf(f_init, "(\"%s\", getter);\n", pws_name);
+	  }
+	  Printf(exported_symbols, "\"%s\", ", pws_name);
+	  free(pws_name);
+	}
+      } else {
+	/* Register the function */
+	if (use_scm_interface) {
+	  if (exporting_destructor) {
+	    Printf(f_init, "((swig_guile_clientdata *)(SWIGTYPE%s->clientdata))->destroy = (guile_destructor) %s;\n", swigtype_ptr, wname);
+	    //Printf(f_init, "SWIG_TypeClientData(SWIGTYPE%s, (void *) %s);\n", swigtype_ptr, wname);
+	  }
+	  Printf(f_init, "scm_c_define_gsubr(\"%s\", %d, %d, 0, (swig_guile_proc) %s);\n", proc_name, numreq, numargs - numreq, wname);
+	} else {
+	  Printf(f_init, "gh_new_procedure(\"%s\", (swig_guile_proc) %s, %d, %d, 0);\n", proc_name, wname, numreq, numargs - numreq);
+	}
+      }
+    } else {			/* overloaded function; don't export the single methods */
+      if (!Getattr(n, "sym:nextSibling")) {
+	/* Emit overloading dispatch function */
+
+	int maxargs;
+	String *dispatch = Swig_overload_dispatch(n, "return %s(argc,argv);", &maxargs);
+
+	/* Generate a dispatch wrapper for all overloaded functions */
+
+	Wrapper *df = NewWrapper();
+	String *dname = Swig_name_wrapper(iname);
+
+	Printv(df->def, "static SCM\n", dname, "(SCM rest)\n{\n", NIL);
+	Printf(df->code, "#define FUNC_NAME \"%s\"\n", proc_name);
+	Printf(df->code, "SCM argv[%d];\n", maxargs);
+	Printf(df->code, "int argc = SWIG_Guile_GetArgs (argv, rest, %d, %d, \"%s\");\n", 0, maxargs, proc_name);
+	Printv(df->code, dispatch, "\n", NIL);
+	Printf(df->code, "scm_misc_error(\"%s\", \"No matching method for generic function `%s'\", SCM_EOL);\n", proc_name, iname);
+	Printf(df->code, "#undef FUNC_NAME\n");
+	Printv(df->code, "}\n", NIL);
+	Wrapper_print(df, f_wrappers);
+	if (use_scm_interface) {
+	  Printf(f_init, "scm_c_define_gsubr(\"%s\", 0, 0, 1, (swig_guile_proc) %s);\n", proc_name, dname);
+	} else {
+	  Printf(f_init, "gh_new_procedure(\"%s\", (swig_guile_proc) %s, 0, 0, 1);\n", proc_name, dname);
+	}
+	DelWrapper(df);
+	Delete(dispatch);
+	Delete(dname);
+      }
+    }
+    Printf(exported_symbols, "\"%s\", ", proc_name);
+
+    if (!in_class || memberfunction_name) {
+      // export wrapper into goops file
+      String *method_def = NewString("");
+      String *goops_name;
+      if (in_class)
+	goops_name = NewString(memberfunction_name);
+      else
+	goops_name = goopsNameMapping(proc_name, (char *) "");
+      String *primitive_name = NewString("");
+      if (primRenamer)
+	Printv(primitive_name, "primitive:", proc_name, NIL);
+      else
+	Printv(primitive_name, proc_name, NIL);
+      Replaceall(method_signature, "_", "-");
+      Replaceall(primitive_args, "_", "-");
+      if (!any_specialized_arg) {
+	/* If there would not be any specialized argument in
+	   the method declaration, we simply re-export the
+	   function.  This is a performance optimization. */
+	Printv(method_def, "(define ", goops_name, " ", primitive_name, ")\n", NIL);
+      } else if (numreq == numargs) {
+	Printv(method_def, "(define-method (", goops_name, method_signature, ")\n", NIL);
+	Printv(method_def, "  (", primitive_name, primitive_args, "))\n", NIL);
+      } else {
+	/* Handle optional args. For the rest argument, use a name
+	   that cannot clash. */
+	Printv(method_def, "(define-method (", goops_name, method_signature, " . %args)\n", NIL);
+	Printv(method_def, "  (apply ", primitive_name, primitive_args, " %args))\n", NIL);
+      }
+      if (in_class) {
+	/* Defer method definition till end of class definition. */
+	Printv(goops_class_methods, method_def, NIL);
+      } else {
+	Printv(goopscode, method_def, NIL);
+      }
+      Printf(goopsexport, "%s ", goops_name);
+      Delete(primitive_name);
+      Delete(goops_name);
+      Delete(method_def);
+    }
+
+    if (procdoc) {
+      String *returns_text = NewString("");
+      if (num_results == 0)
+	Printv(returns_text, return_nothing_doc, NIL);
+      else if (num_results == 1)
+	Printv(returns_text, return_one_doc, NIL);
+      else
+	Printv(returns_text, return_multi_doc, NIL);
+      /* Substitute documentation variables */
+      static const char *numbers[] = { "zero", "one", "two", "three",
+	"four", "five", "six", "seven",
+	"eight", "nine", "ten", "eleven",
+	"twelve"
+      };
+      if (num_results <= 12)
+	Replaceall(returns_text, "$num_values", numbers[num_results]);
+      else {
+	String *num_results_str = NewStringf("%d", num_results);
+	Replaceall(returns_text, "$num_values", num_results_str);
+	Delete(num_results_str);
+      }
+      Replaceall(returns_text, "$values", returns);
+      Printf(doc_body, "\n%s", returns_text);
+      write_doc(proc_name, signature, doc_body);
+      Delete(returns_text);
+    }
+
+    Delete(proc_name);
+    Delete(outarg);
+    Delete(cleanup);
+    Delete(signature);
+    Delete(method_signature);
+    Delete(primitive_args);
+    Delete(doc_body);
+    Delete(returns_argout);
+    Delete(returns);
+    Delete(tmp);
+    Delete(scheme_arg_names);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   *
+   * Create a link to a C variable.
+   * This creates a single function PREFIX_var_VARNAME().
+   * This function takes a single optional argument.   If supplied, it means
+   * we are setting this variable to some value.  If omitted, it means we are
+   * simply evaluating this variable.  Either way, we return the variables
+   * value.
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+
+    String *proc_name;
+    Wrapper *f;
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    f = NewWrapper();
+    // evaluation function names
+
+    String *var_name = Swig_name_wrapper(iname);
+
+    // Build the name for scheme.
+    proc_name = NewString(iname);
+    Replaceall(proc_name, "_", "-");
+    Setattr(n, "wrap:name", proc_name);
+
+    if (1 || (SwigType_type(t) != T_USER) || (is_a_pointer(t))) {
+
+      Printf(f->def, "static SCM\n%s(SCM s_0)\n{\n", var_name);
+
+      /* Define the scheme name in C. This define is used by several Guile
+         macros. */
+      Printv(f->def, "#define FUNC_NAME \"", proc_name, "\"", NIL);
+
+      Wrapper_add_local(f, "gswig_result", "SCM gswig_result");
+
+      if (!GetFlag(n, "feature:immutable")) {
+	/* Check for a setting of the variable value */
+	Printf(f->code, "if (s_0 != SCM_UNDEFINED) {\n");
+	if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	  Replaceall(tm, "$source", "s_0");
+	  Replaceall(tm, "$input", "s_0");
+	  Replaceall(tm, "$target", name);
+	  /* Printv(f->code,tm,"\n",NIL); */
+	  emit_action_code(n, f->code, tm);
+	} else {
+	  throw_unhandled_guile_type_error(t);
+	}
+	Printf(f->code, "}\n");
+      }
+      // Now return the value of the variable (regardless
+      // of evaluating or setting)
+
+      if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+	Replaceall(tm, "$source", name);
+	Replaceall(tm, "$target", "gswig_result");
+	Replaceall(tm, "$result", "gswig_result");
+	/* Printv(f->code,tm,"\n",NIL); */
+	emit_action_code(n, f->code, tm);
+      } else {
+	throw_unhandled_guile_type_error(t);
+      }
+      Printf(f->code, "\nreturn gswig_result;\n");
+      Printf(f->code, "#undef FUNC_NAME\n");
+      Printf(f->code, "}\n");
+
+      Wrapper_print(f, f_wrappers);
+
+      // Now add symbol to the Guile interpreter
+
+      if (!emit_setters || GetFlag(n, "feature:immutable")) {
+	/* Read-only variables become a simple procedure returning the
+	   value; read-write variables become a simple procedure with
+	   an optional argument. */
+	if (use_scm_interface) {
+
+	  if (!goops && GetFlag(n, "feature:constasvar")) {
+	    /* need to export this function as a variable instead of a procedure */
+	    if (scmstub) {
+	      /* export the function in the wrapper, and (set!) it in scmstub */
+	      Printf(f_init, "scm_c_define_gsubr(\"%s\", 0, %d, 0, (swig_guile_proc) %s);\n", proc_name, !GetFlag(n, "feature:immutable"), var_name);
+	      Printf(scmtext, "(set! %s (%s))\n", proc_name, proc_name);
+	    } else {
+	      /* export the variable directly */
+	      Printf(f_init, "scm_c_define(\"%s\", %s(SCM_UNDEFINED));\n", proc_name, var_name);
+	    }
+
+	  } else {
+	    /* Export the function as normal */
+	    Printf(f_init, "scm_c_define_gsubr(\"%s\", 0, %d, 0, (swig_guile_proc) %s);\n", proc_name, !GetFlag(n, "feature:immutable"), var_name);
+	  }
+
+	} else {
+	  Printf(f_init, "\t gh_new_procedure(\"%s\", (swig_guile_proc) %s, 0, %d, 0);\n", proc_name, var_name, !GetFlag(n, "feature:immutable"));
+	}
+      } else {
+	/* Read/write variables become a procedure with setter. */
+	if (use_scm_interface) {
+	  Printf(f_init, "{ SCM p = scm_c_define_gsubr(\"%s\", 0, 1, 0, (swig_guile_proc) %s);\n", proc_name, var_name);
+	  Printf(f_init, "scm_c_define");
+	} else {
+	  Printf(f_init, "\t{ SCM p = gh_new_procedure(\"%s\", (swig_guile_proc) %s, 0, 1, 0);\n", proc_name, var_name);
+	  Printf(f_init, "gh_define");
+	}
+	Printf(f_init, "(\"%s\", " "scm_make_procedure_with_setter(p, p)); }\n", proc_name);
+      }
+      Printf(exported_symbols, "\"%s\", ", proc_name);
+
+      // export wrapper into goops file
+      if (!in_class) {		// only if the variable is not part of a class
+	String *class_name = SwigType_typedef_resolve_all(SwigType_base(t));
+	String *goops_name = goopsNameMapping(proc_name, (char *) "");
+	String *primitive_name = NewString("");
+	if (primRenamer)
+	  Printv(primitive_name, "primitive:", NIL);
+	Printv(primitive_name, proc_name, NIL);
+	/* Simply re-export the procedure */
+	if ((!emit_setters || GetFlag(n, "feature:immutable"))
+	    && GetFlag(n, "feature:constasvar")) {
+	  Printv(goopscode, "(define ", goops_name, " (", primitive_name, "))\n", NIL);
+	} else {
+	  Printv(goopscode, "(define ", goops_name, " ", primitive_name, ")\n", NIL);
+	}
+	Printf(goopsexport, "%s ", goops_name);
+	Delete(primitive_name);
+	Delete(class_name);
+	Delete(goops_name);
+      }
+
+      if (procdoc) {
+	/* Compute documentation */
+	String *signature = NewString("");
+	String *signature2 = NULL;
+	String *doc = NewString("");
+
+	if (GetFlag(n, "feature:immutable")) {
+	  Printv(signature, proc_name, NIL);
+	  if (GetFlag(n, "feature:constasvar")) {
+	    Printv(doc, "Is constant ", NIL);
+	  } else {
+	    Printv(doc, "Returns constant ", NIL);
+	  }
+	  if ((tm = Getattr(n, "tmap:varout:doc"))) {
+	    Printv(doc, tm, NIL);
+	  } else {
+	    String *s = SwigType_str(t, 0);
+	    Chop(s);
+	    Printf(doc, "<%s>", s);
+	    Delete(s);
+	  }
+	} else if (emit_setters) {
+	  Printv(signature, proc_name, NIL);
+	  signature2 = NewString("");
+	  Printv(signature2, "set! (", proc_name, ") ", NIL);
+	  handle_documentation_typemap(signature2, NIL, n, "tmap:varin:arglist", "new-value");
+	  Printv(doc, "Get or set the value of the C variable, \n", NIL);
+	  Printv(doc, "which is of type ", NIL);
+	  handle_documentation_typemap(doc, NIL, n, "tmap:varout:doc", "$1_type");
+	  Printv(doc, ".");
+	} else {
+	  Printv(signature, proc_name, " #:optional ", NIL);
+	  if ((tm = Getattr(n, "tmap:varin:doc"))) {
+	    Printv(signature, tm, NIL);
+	  } else {
+	    String *s = SwigType_str(t, 0);
+	    Chop(s);
+	    Printf(signature, "new-value <%s>", s);
+	    Delete(s);
+	  }
+
+	  Printv(doc, "If NEW-VALUE is provided, " "set C variable to this value.\n", NIL);
+	  Printv(doc, "Returns variable value ", NIL);
+	  if ((tm = Getattr(n, "tmap:varout:doc"))) {
+	    Printv(doc, tm, NIL);
+	  } else {
+	    String *s = SwigType_str(t, 0);
+	    Chop(s);
+	    Printf(doc, "<%s>", s);
+	    Delete(s);
+	  }
+	}
+	write_doc(proc_name, signature, doc, signature2);
+	Delete(signature);
+	if (signature2)
+	  Delete(signature2);
+	Delete(doc);
+      }
+
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
+    }
+    Delete(var_name);
+    Delete(proc_name);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   *
+   * We create a read-only variable.
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *value = Getattr(n, "value");
+    int constasvar = GetFlag(n, "feature:constasvar");
+
+
+    String *proc_name;
+    String *var_name;
+    String *rvalue;
+    Wrapper *f;
+    SwigType *nctype;
+    String *tm;
+
+    f = NewWrapper();
+
+    // Make a static variable;
+    var_name = NewStringf("%sconst_%s", prefix, iname);
+
+    // Strip const qualifier from type if present
+
+    nctype = NewString(type);
+    if (SwigType_isconst(nctype)) {
+      Delete(SwigType_pop(nctype));
+    }
+    // Build the name for scheme.
+    proc_name = NewString(iname);
+    Replaceall(proc_name, "_", "-");
+
+    if ((SwigType_type(nctype) == T_USER) && (!is_a_pointer(nctype))) {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      Delete(var_name);
+      DelWrapper(f);
+      return SWIG_NOWRAP;
+    }
+    // See if there's a typemap
+
+    if (SwigType_type(nctype) == T_STRING) {
+      rvalue = NewStringf("\"%s\"", value);
+    } else if (SwigType_type(nctype) == T_CHAR) {
+      rvalue = NewStringf("\'%s\'", value);
+    } else {
+      rvalue = NewString(value);
+    }
+
+    if ((tm = Swig_typemap_lookup("constant", n, name, 0))) {
+      Replaceall(tm, "$source", rvalue);
+      Replaceall(tm, "$value", rvalue);
+      Replaceall(tm, "$target", name);
+      Printv(f_header, tm, "\n", NIL);
+    } else {
+      // Create variable and assign it a value
+      Printf(f_header, "static %s = %s;\n", SwigType_lstr(nctype, var_name), rvalue);
+    }
+    {
+      /* Hack alert: will cleanup later -- Dave */
+      Node *n = NewHash();
+      Setattr(n, "name", var_name);
+      Setattr(n, "sym:name", iname);
+      Setattr(n, "type", nctype);
+      SetFlag(n, "feature:immutable");
+      if (constasvar) {
+	SetFlag(n, "feature:constasvar");
+      }
+      variableWrapper(n);
+      Delete(n);
+    }
+    Delete(var_name);
+    Delete(nctype);
+    Delete(proc_name);
+    Delete(rvalue);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+  virtual int classDeclaration(Node *n) {
+    String *class_name = NewStringf("<%s>", Getattr(n, "sym:name"));
+    Setattr(n, "guile:goopsclassname", class_name);
+    return Language::classDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+  virtual int classHandler(Node *n) {
+    /* Create new strings for building up a wrapper function */
+    have_constructor = 0;
+
+    class_name = NewString("");
+    short_class_name = NewString("");
+    Printv(class_name, "<", Getattr(n, "sym:name"), ">", NIL);
+    Printv(short_class_name, Getattr(n, "sym:name"), NIL);
+    Replaceall(class_name, "_", "-");
+    Replaceall(short_class_name, "_", "-");
+
+    if (!addSymbol(class_name, n))
+      return SWIG_ERROR;
+
+    /* Handle inheritance */
+    String *base_class = NewString("<");
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist)) {
+      Iterator i = First(baselist);
+      while (i.item) {
+	Printv(base_class, Getattr(i.item, "sym:name"), NIL);
+	i = Next(i);
+	if (i.item) {
+	  Printf(base_class, "> <");
+	}
+      }
+    }
+    Printf(base_class, ">");
+    Replaceall(base_class, "_", "-");
+
+    Printv(goopscode, "(define-class ", class_name, " ", NIL);
+    Printf(goopsexport, "%s ", class_name);
+
+    if (Len(base_class) > 2) {
+      Printv(goopscode, "(", base_class, ")\n", NIL);
+    } else {
+      Printv(goopscode, "(<swig>)\n", NIL);
+    }
+    SwigType *ct = NewStringf("p.%s", Getattr(n, "name"));
+    swigtype_ptr = SwigType_manglestr(ct);
+
+    String *mangled_classname = Swig_name_mangle(Getattr(n, "sym:name"));
+    /* Export clientdata structure */
+    if (use_scm_interface) {
+      Printf(f_runtime, "static swig_guile_clientdata _swig_guile_clientdata%s = { NULL, SCM_EOL };\n", mangled_classname);
+
+      Printv(f_init, "SWIG_TypeClientData(SWIGTYPE", swigtype_ptr, ", (void *) &_swig_guile_clientdata", mangled_classname, ");\n", NIL);
+      SwigType_remember(ct);
+    }
+    Delete(ct);
+
+    /* Emit all of the members */
+    goops_class_methods = NewString("");
+
+    in_class = 1;
+    Language::classHandler(n);
+    in_class = 0;
+
+    Printv(goopscode, "  #:metaclass <swig-metaclass>\n", NIL);
+
+    if (have_constructor)
+      Printv(goopscode, "  #:new-function ", primRenamer ? "primitive:" : "", "new-", short_class_name, "\n", NIL);
+
+    Printf(goopscode, ")\n%s\n", goops_class_methods);
+    Delete(goops_class_methods);
+    goops_class_methods = 0;
+
+
+    /* export class initialization function */
+    if (goops) {
+      /* export the wrapper function */
+      String *funcName = NewString(mangled_classname);
+      Printf(funcName, "_swig_guile_setgoopsclass");
+      String *guileFuncName = NewString(funcName);
+      Replaceall(guileFuncName, "_", "-");
+
+      Printv(f_wrappers, "static SCM ", funcName, "(SCM cl) \n", NIL);
+      Printf(f_wrappers, "#define FUNC_NAME %s\n{\n", guileFuncName);
+      Printv(f_wrappers, "  ((swig_guile_clientdata *)(SWIGTYPE", swigtype_ptr, "->clientdata))->goops_class = cl;\n", NIL);
+      Printf(f_wrappers, "  return SCM_UNSPECIFIED;\n");
+      Printf(f_wrappers, "}\n#undef FUNC_NAME\n\n");
+
+      Printf(f_init, "scm_c_define_gsubr(\"%s\", 1, 0, 0, (swig_guile_proc) %s);\n", guileFuncName, funcName);
+      Printf(exported_symbols, "\"%s\", ", guileFuncName);
+
+      /* export the call to the wrapper function */
+      Printf(goopscode, "(%s%s %s)\n\n", primRenamer ? "primitive:" : "", guileFuncName, class_name);
+
+      Delete(guileFuncName);
+      Delete(funcName);
+    }
+
+    Delete(mangled_classname);
+
+    Delete(swigtype_ptr);
+    swigtype_ptr = 0;
+
+    Delete(class_name);
+    Delete(short_class_name);
+    class_name = 0;
+    short_class_name = 0;
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   * ------------------------------------------------------------ */
+  int memberfunctionHandler(Node *n) {
+    String *iname = Getattr(n, "sym:name");
+    String *proc = NewString(iname);
+    Replaceall(proc, "_", "-");
+
+    memberfunction_name = goopsNameMapping(proc, short_class_name);
+    Language::memberfunctionHandler(n);
+    Delete(memberfunction_name);
+    memberfunction_name = NULL;
+    Delete(proc);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+  int membervariableHandler(Node *n) {
+    String *iname = Getattr(n, "sym:name");
+
+    if (emit_setters) {
+      struct_member = 1;
+      Printf(f_init, "{\n");
+    }
+
+    Language::membervariableHandler(n);
+
+    if (emit_setters) {
+      Printf(f_init, "}\n");
+      struct_member = 0;
+    }
+
+    String *proc = NewString(iname);
+    Replaceall(proc, "_", "-");
+    String *goops_name = goopsNameMapping(proc, short_class_name);
+
+    /* The slot name is never qualified with the class,
+       even if useclassprefix is true. */
+    Printv(goopscode, "  (", proc, " #:allocation #:virtual", NIL);
+    /* GOOPS (at least in Guile 1.6.3) only accepts closures, not
+       primitive procedures for slot-ref and slot-set. */
+    Printv(goopscode, "\n   #:slot-ref (lambda (obj) (", primRenamer ? "primitive:" : "", short_class_name, "-", proc, "-get", " obj))", NIL);
+    if (!GetFlag(n, "feature:immutable")) {
+      Printv(goopscode, "\n   #:slot-set! (lambda (obj value) (", primRenamer ? "primitive:" : "", short_class_name, "-", proc, "-set", " obj value))", NIL);
+    } else {
+      Printf(goopscode, "\n   #:slot-set! (lambda (obj value) (error \"Immutable slot\"))");
+    }
+    if (emit_slot_accessors) {
+      if (GetFlag(n, "feature:immutable")) {
+	Printv(goopscode, "\n   #:getter ", goops_name, NIL);
+      } else {
+	Printv(goopscode, "\n   #:accessor ", goops_name, NIL);
+      }
+      Printf(goopsexport, "%s ", goops_name);
+    }
+    Printv(goopscode, ")\n", NIL);
+    Delete(proc);
+    Delete(goops_name);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constructorHandler()
+   * ------------------------------------------------------------ */
+  int constructorHandler(Node *n) {
+    Language::constructorHandler(n);
+    have_constructor = 1;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * destructorHandler()
+   * ------------------------------------------------------------ */
+  virtual int destructorHandler(Node *n) {
+    exporting_destructor = true;
+    Language::destructorHandler(n);
+    exporting_destructor = false;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * pragmaDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int pragmaDirective(Node *n) {
+    if (!ImportMode) {
+      String *lang = Getattr(n, "lang");
+      String *cmd = Getattr(n, "name");
+      String *value = Getattr(n, "value");
+
+#     define store_pragma(PRAGMANAME)			\
+        if (Strcmp(cmd, #PRAGMANAME) == 0) {		\
+	  if (PRAGMANAME) Delete(PRAGMANAME);		\
+	  PRAGMANAME = value ? NewString(value) : NULL;	\
+	}
+
+      if (Strcmp(lang, "guile") == 0) {
+	store_pragma(beforereturn)
+	    store_pragma(return_nothing_doc)
+	    store_pragma(return_one_doc)
+	    store_pragma(return_multi_doc);
+#     undef store_pragma
+      }
+    }
+    return Language::pragmaDirective(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * goopsNameMapping()
+   * Maps the identifier from C++ to the GOOPS based * on command 
+   * line parameters and such.
+   * If class_name = "" that means the mapping is for a function or
+   * variable not attached to any class.
+   * ------------------------------------------------------------ */
+  String *goopsNameMapping(String *name, String_or_char *class_name) {
+    String *n = NewString("");
+
+    if (Strcmp(class_name, "") == 0) {
+      // not part of a class, so no class name to prefix
+      if (goopsprefix) {
+	Printf(n, "%s%s", goopsprefix, name);
+      } else {
+	Printf(n, "%s", name);
+      }
+    } else {
+      if (useclassprefix) {
+	Printf(n, "%s-%s", class_name, name);
+      } else {
+	if (goopsprefix) {
+	  Printf(n, "%s%s", goopsprefix, name);
+	} else {
+	  Printf(n, "%s", name);
+	}
+      }
+    }
+    return n;
+  }
+
+
+  /* ------------------------------------------------------------
+   * validIdentifier()
+   * ------------------------------------------------------------ */
+
+  virtual int validIdentifier(String *s) {
+    char *c = Char(s);
+    /* Check whether we have an R5RS identifier.  Guile supports a
+       superset of R5RS identifiers, but it's probably a bad idea to use
+       those. */
+    /* <identifier> --> <initial> <subsequent>* | <peculiar identifier> */
+    /* <initial> --> <letter> | <special initial> */
+    if (!(isalpha(*c) || (*c == '!') || (*c == '$') || (*c == '%')
+	  || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
+	  || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
+	  || (*c == '^') || (*c == '_') || (*c == '~'))) {
+      /* <peculiar identifier> --> + | - | ... */
+      if ((strcmp(c, "+") == 0)
+	  || strcmp(c, "-") == 0 || strcmp(c, "...") == 0)
+	return 1;
+      else
+	return 0;
+    }
+    /* <subsequent> --> <initial> | <digit> | <special subsequent> */
+    while (*c) {
+      if (!(isalnum(*c) || (*c == '!') || (*c == '$') || (*c == '%')
+	    || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
+	    || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
+	    || (*c == '^') || (*c == '_') || (*c == '~') || (*c == '+')
+	    || (*c == '-') || (*c == '.') || (*c == '@')))
+	return 0;
+      c++;
+    }
+    return 1;
+  }
+
+  String *runtimeCode() {
+    String *s;
+    if (use_scm_interface) {
+      s = Swig_include_sys("guile_scm_run.swg");
+      if (!s) {
+	Printf(stderr, "*** Unable to open 'guile_scm_run.swg");
+	s = NewString("");
+      }
+    } else {
+      s = Swig_include_sys("guile_gh_run.swg");
+      if (!s) {
+	Printf(stderr, "*** Unable to open 'guile_gh_run.swg");
+	s = NewString("");
+      }
+    }
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    if (use_scm_interface) {
+      return NewString("swigguilerun.h");
+    } else {
+      return NewString("swigguileghrun.h");
+    }
+  }
+};
+
+/* -----------------------------------------------------------------------------
+ * swig_guile()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_guile() {
+  return new GUILE();
+}
+extern "C" Language *swig_guile(void) {
+  return new_swig_guile();
+}
diff --git a/trunk/Source/Modules/java.cxx b/trunk/Source/Modules/java.cxx
new file mode 100644
index 0000000..b92fccd
--- /dev/null
+++ b/trunk/Source/Modules/java.cxx
@@ -0,0 +1,4118 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * java.cxx
+ *
+ * Java language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_java_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include <limits.h>		// for INT_MAX
+#include "cparse.h"
+#include <ctype.h>
+
+/* Hash type used for upcalls from C/C++ */
+typedef DOH UpcallData;
+
+class JAVA:public Language {
+  static const char *usage;
+  const String *empty_string;
+  const String *public_string;
+  const String *protected_string;
+
+  Hash *swig_types_hash;
+  File *f_runtime;
+  File *f_runtime_h;
+  File *f_header;
+  File *f_wrappers;
+  File *f_init;
+  File *f_directors;
+  File *f_directors_h;
+  List *filenames_list;
+
+  bool proxy_flag;		// Flag for generating proxy classes
+  bool nopgcpp_flag;		// Flag for suppressing the premature garbage collection prevention parameter
+  bool native_function_flag;	// Flag for when wrapping a native function
+  bool enum_constant_flag;	// Flag for when wrapping an enum or constant
+  bool static_flag;		// Flag for when wrapping a static functions or member variables
+  bool variable_wrapper_flag;	// Flag for when wrapping a nonstatic member variable
+  bool wrapping_member_flag;	// Flag for when wrapping a member variable/enum/const
+  bool global_variable_flag;	// Flag for when wrapping a global variable
+  bool old_variable_names;	// Flag for old style variable names in the intermediary class
+  bool member_func_flag;	// flag set when wrapping a member function
+
+  String *imclass_name;		// intermediary class name
+  String *module_class_name;	// module class name
+  String *imclass_class_code;	// intermediary class code
+  String *proxy_class_def;
+  String *proxy_class_code;
+  String *module_class_code;
+  String *proxy_class_name;
+  String *variable_name;	//Name of a variable being wrapped
+  String *proxy_class_constants_code;
+  String *module_class_constants_code;
+  String *enum_code;
+  String *package;		// Optional package name
+  String *jnipackage;		// Package name used in the JNI code
+  String *package_path;		// Package name used internally by JNI (slashes)
+  String *imclass_imports;	//intermediary class imports from %pragma
+  String *module_imports;	//module imports from %pragma
+  String *imclass_baseclass;	//inheritance for intermediary class class from %pragma
+  String *module_baseclass;	//inheritance for module class from %pragma
+  String *imclass_interfaces;	//interfaces for intermediary class class from %pragma
+  String *module_interfaces;	//interfaces for module class from %pragma
+  String *imclass_class_modifiers;	//class modifiers for intermediary class overriden by %pragma
+  String *module_class_modifiers;	//class modifiers for module class overriden by %pragma
+  String *upcasts_code;		//C++ casts for inheritance hierarchies C++ code
+  String *imclass_cppcasts_code;	//C++ casts up inheritance hierarchies intermediary class code
+  String *imclass_directors;	// Intermediate class director code
+  String *destructor_call;	//C++ destructor call if any
+
+  // Director method stuff:
+  List *dmethods_seq;
+  Hash *dmethods_table;
+  int n_dmethods;
+  int n_directors;
+  int first_class_dmethod;
+  int curr_class_dmethod;
+
+  enum EnumFeature { SimpleEnum, TypeunsafeEnum, TypesafeEnum, ProperEnum };
+
+  static Parm *NewParmFromNode(SwigType *type, const String_or_char *name, Node *n) {
+    Parm *p = NewParm(type, name);
+    Setfile(p, Getfile(n));
+    Setline(p, Getline(n));
+    return p;
+  }
+
+public:
+
+  /* -----------------------------------------------------------------------------
+   * JAVA()
+   * ----------------------------------------------------------------------------- */
+
+   JAVA():empty_string(NewString("")),
+      public_string(NewString("public")),
+      protected_string(NewString("protected")),
+      swig_types_hash(NULL),
+      f_runtime(NULL),
+      f_runtime_h(NULL),
+      f_header(NULL),
+      f_wrappers(NULL),
+      f_init(NULL),
+      f_directors(NULL),
+      f_directors_h(NULL),
+      filenames_list(NULL),
+      proxy_flag(true),
+      nopgcpp_flag(false),
+      native_function_flag(false),
+      enum_constant_flag(false),
+      static_flag(false),
+      variable_wrapper_flag(false),
+      wrapping_member_flag(false),
+      global_variable_flag(false),
+      old_variable_names(false),
+      member_func_flag(false),
+      imclass_name(NULL),
+      module_class_name(NULL),
+      imclass_class_code(NULL),
+      proxy_class_def(NULL),
+      proxy_class_code(NULL),
+      module_class_code(NULL),
+      proxy_class_name(NULL),
+      variable_name(NULL),
+      proxy_class_constants_code(NULL),
+      module_class_constants_code(NULL),
+      package(NULL),
+      jnipackage(NULL),
+      package_path(NULL),
+      imclass_imports(NULL),
+      module_imports(NULL),
+      imclass_baseclass(NULL),
+      module_baseclass(NULL),
+      imclass_interfaces(NULL),
+      module_interfaces(NULL),
+      imclass_class_modifiers(NULL),
+      module_class_modifiers(NULL),
+      upcasts_code(NULL),
+      imclass_cppcasts_code(NULL),
+      imclass_directors(NULL),
+      destructor_call(NULL),
+      dmethods_seq(NULL),
+      dmethods_table(NULL),
+      n_dmethods(0),
+      n_directors(0) {
+    /* for now, multiple inheritance in directors is disabled, this
+       should be easy to implement though */
+    director_multiple_inheritance = 0;
+    director_language = 1;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getProxyName()
+   *
+   * Test to see if a type corresponds to something wrapped with a proxy class
+   * Return NULL if not otherwise the proxy class name
+   * ----------------------------------------------------------------------------- */
+  
+   String *getProxyName(SwigType *t) {
+    if (proxy_flag) {
+      Node *n = classLookup(t);
+      if (n) {
+	return Getattr(n, "sym:name");
+      }
+    }
+    return NULL;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * makeValidJniName()
+   * ----------------------------------------------------------------------------- */
+
+  String *makeValidJniName(const String *name) {
+    String *valid_jni_name = NewString(name);
+    Replaceall(valid_jni_name, "_", "_1");
+    return valid_jni_name;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * directorClassName()
+   * ----------------------------------------------------------------------------- */
+
+  String *directorClassName(Node *n) {
+    String *dirclassname;
+    const char *attrib = "director:classname";
+
+    if (!(dirclassname = Getattr(n, attrib))) {
+      String *classname = Getattr(n, "sym:name");
+
+      dirclassname = NewStringf("SwigDirector_%s", classname);
+      Setattr(n, attrib, dirclassname);
+    }
+
+    return dirclassname;
+  }
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+
+    SWIG_library_directory("java");
+
+    // Look for certain command line options
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-package") == 0) {
+	  if (argv[i + 1]) {
+	    package = NewString("");
+	    Printf(package, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) {
+	  Printf(stderr, "Deprecated command line option: %s. Proxy classes are now generated by default.\n", argv[i]);
+	  Swig_mark_arg(i);
+	  proxy_flag = true;
+	} else if ((strcmp(argv[i], "-noproxy") == 0)) {
+	  Swig_mark_arg(i);
+	  proxy_flag = false;
+	} else if (strcmp(argv[i], "-nopgcpp") == 0) {
+	  Swig_mark_arg(i);
+	  nopgcpp_flag = true;
+	} else if (strcmp(argv[i], "-oldvarnames") == 0) {
+	  Swig_mark_arg(i);
+	  old_variable_names = true;
+	} else if (strcmp(argv[i], "-jnic") == 0) {
+	  Swig_mark_arg(i);
+	  Printf(stderr, "Deprecated command line option: -jnic. C JNI calling convention now used when -c++ not specified.\n");
+	} else if (strcmp(argv[i], "-nofinalize") == 0) {
+	  Swig_mark_arg(i);
+	  Printf(stderr, "Deprecated command line option: -nofinalize. Use the new javafinalize typemap instead.\n");
+	} else if (strcmp(argv[i], "-jnicpp") == 0) {
+	  Swig_mark_arg(i);
+	  Printf(stderr, "Deprecated command line option: -jnicpp. C++ JNI calling convention now used when -c++ specified.\n");
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  Printf(stdout, "%s\n", usage);
+	}
+      }
+    }
+
+    // Add a symbol to the parser for conditional compilation
+    Preprocessor_define("SWIGJAVA 1", 0);
+
+    // Add typemap definitions
+    SWIG_typemap_lang("java");
+    SWIG_config_file("java.swg");
+
+    allow_overloading();
+  }
+
+  /* ---------------------------------------------------------------------
+   * top()
+   * --------------------------------------------------------------------- */
+
+  virtual int top(Node *n) {
+
+    // Get any options set in the module directive
+    Node *optionsnode = Getattr(Getattr(n, "module"), "options");
+
+    if (optionsnode) {
+      if (Getattr(optionsnode, "jniclassname"))
+	imclass_name = Copy(Getattr(optionsnode, "jniclassname"));
+      /* check if directors are enabled for this module.  note: this 
+       * is a "master" switch, without which no director code will be
+       * emitted.  %feature("director") statements are also required
+       * to enable directors for individual classes or methods.
+       *
+       * use %module(directors="1") modulename at the start of the 
+       * interface file to enable director generation.
+       */
+      if (Getattr(optionsnode, "directors")) {
+	allow_directors();
+      }
+      if (Getattr(optionsnode, "dirprot")) {
+	allow_dirprot();
+      }
+      allow_allprotected(GetFlag(optionsnode, "allprotected"));
+    }
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+    String *outfile_h = Getattr(n, "outfile_h");
+
+    if (!outfile) {
+      Printf(stderr, "Unable to determine outfile\n");
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    if (directorsEnabled()) {
+      if (!outfile_h) {
+        Printf(stderr, "Unable to determine outfile_h\n");
+        SWIG_exit(EXIT_FAILURE);
+      }
+      f_runtime_h = NewFile(outfile_h, "w");
+      if (!f_runtime_h) {
+	FileErrorDisplay(outfile_h);
+	SWIG_exit(EXIT_FAILURE);
+      }
+    }
+
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+    f_directors_h = NewString("");
+    f_directors = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("director", f_directors);
+    Swig_register_filebyname("director_h", f_directors_h);
+
+    swig_types_hash = NewHash();
+    filenames_list = NewList();
+
+    // Make the intermediary class and module class names. The intermediary class name can be set in the module directive.
+    if (!imclass_name) {
+      imclass_name = NewStringf("%sJNI", Getattr(n, "name"));
+      module_class_name = Copy(Getattr(n, "name"));
+    } else {
+      // Rename the module name if it is the same as intermediary class name - a backwards compatibility solution
+      if (Cmp(imclass_name, Getattr(n, "name")) == 0)
+	module_class_name = NewStringf("%sModule", Getattr(n, "name"));
+      else
+	module_class_name = Copy(Getattr(n, "name"));
+    }
+
+    imclass_class_code = NewString("");
+    proxy_class_def = NewString("");
+    proxy_class_code = NewString("");
+    module_class_constants_code = NewString("");
+    imclass_baseclass = NewString("");
+    imclass_interfaces = NewString("");
+    imclass_class_modifiers = NewString("");
+    module_class_code = NewString("");
+    module_baseclass = NewString("");
+    module_interfaces = NewString("");
+    module_imports = NewString("");
+    module_class_modifiers = NewString("");
+    imclass_imports = NewString("");
+    imclass_cppcasts_code = NewString("");
+    imclass_directors = NewString("");
+    upcasts_code = NewString("");
+    dmethods_seq = NewList();
+    dmethods_table = NewHash();
+    n_dmethods = 0;
+    n_directors = 0;
+    if (!package)
+      package = NewString("");
+    jnipackage = NewString("");
+    package_path = NewString("");
+
+    Swig_banner(f_runtime);	// Print the SWIG banner message
+
+    if (directorsEnabled()) {
+      Printf(f_runtime, "#define SWIG_DIRECTORS\n");
+
+      /* Emit initial director header and director code: */
+      Swig_banner(f_directors_h);
+      Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module_class_name);
+      Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module_class_name);
+
+      Printf(f_directors, "\n\n");
+      Printf(f_directors, "/* ---------------------------------------------------\n");
+      Printf(f_directors, " * C++ director class methods\n");
+      Printf(f_directors, " * --------------------------------------------------- */\n\n");
+      if (outfile_h)
+	Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h));
+    }
+
+    String *wrapper_name = NewString("");
+
+    if (Len(package)) {
+      String *jniname = makeValidJniName(package);
+      Printv(jnipackage, jniname, NIL);
+      Delete(jniname);
+      Replaceall(jnipackage, ".", "_");
+      Append(jnipackage, "_");
+      Printv(package_path, package, NIL);
+      Replaceall(package_path, ".", "/");
+    }
+    String *jniname = makeValidJniName(imclass_name);
+    Printf(wrapper_name, "Java_%s%s_%%f", Char(jnipackage), jniname);
+    Delete(jniname);
+
+    Swig_name_register((char *) "wrapper", Char(wrapper_name));
+    if (old_variable_names) {
+      Swig_name_register((char *) "set", (char *) "set_%v");
+      Swig_name_register((char *) "get", (char *) "get_%v");
+    }
+
+    Delete(wrapper_name);
+
+    Printf(f_wrappers, "\n#ifdef __cplusplus\n");
+    Printf(f_wrappers, "extern \"C\" {\n");
+    Printf(f_wrappers, "#endif\n\n");
+
+    /* Emit code */
+    Language::top(n);
+
+    if (directorsEnabled()) {
+      // Insert director runtime into the f_runtime file (make it occur before %header section)
+      Swig_insert_file("director.swg", f_runtime);
+    }
+    // Generate the intermediary class
+    {
+      String *filen = NewStringf("%s%s.java", SWIG_output_directory(), imclass_name);
+      File *f_im = NewFile(filen, "w");
+      if (!f_im) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the intermediary class file
+      emitBanner(f_im);
+
+      if (Len(package) > 0)
+	Printf(f_im, "package %s;\n", package);
+
+      if (imclass_imports)
+	Printf(f_im, "%s\n", imclass_imports);
+
+      if (Len(imclass_class_modifiers) > 0)
+	Printf(f_im, "%s ", imclass_class_modifiers);
+      Printf(f_im, "%s ", imclass_name);
+
+      if (imclass_baseclass && *Char(imclass_baseclass))
+	Printf(f_im, "extends %s ", imclass_baseclass);
+      if (Len(imclass_interfaces) > 0)
+	Printv(f_im, "implements ", imclass_interfaces, " ", NIL);
+      Printf(f_im, "{\n");
+
+      // Add the intermediary class methods
+      Replaceall(imclass_class_code, "$module", module_class_name);
+      Replaceall(imclass_class_code, "$imclassname", imclass_name);
+      Printv(f_im, imclass_class_code, NIL);
+      Printv(f_im, imclass_cppcasts_code, NIL);
+      if (Len(imclass_directors) > 0)
+	Printv(f_im, "\n", imclass_directors, NIL);
+
+      if (n_dmethods > 0) {
+	Putc('\n', f_im);
+	Printf(f_im, "  private final static native void swig_module_init();\n");
+	Printf(f_im, "  static {\n");
+	Printf(f_im, "    swig_module_init();\n");
+	Printf(f_im, "  }\n");
+      }
+      // Finish off the class
+      Printf(f_im, "}\n");
+      Close(f_im);
+    }
+
+    // Generate the Java module class
+    {
+      String *filen = NewStringf("%s%s.java", SWIG_output_directory(), module_class_name);
+      File *f_module = NewFile(filen, "w");
+      if (!f_module) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the module class file
+      emitBanner(f_module);
+
+      if (Len(package) > 0)
+	Printf(f_module, "package %s;\n", package);
+
+      if (module_imports)
+	Printf(f_module, "%s\n", module_imports);
+
+      if (Len(module_class_modifiers) > 0)
+	Printf(f_module, "%s ", module_class_modifiers);
+      Printf(f_module, "%s ", module_class_name);
+
+      if (module_baseclass && *Char(module_baseclass))
+	Printf(f_module, "extends %s ", module_baseclass);
+      if (Len(module_interfaces) > 0) {
+	if (Len(module_class_constants_code) != 0)
+	  Printv(f_module, "implements ", Getattr(n, "name"), "Constants, ", module_interfaces, " ", NIL);
+	else
+	  Printv(f_module, "implements ", module_interfaces, " ", NIL);
+      } else {
+	if (Len(module_class_constants_code) != 0)
+	  Printv(f_module, "implements ", Getattr(n, "name"), "Constants ", NIL);
+      }
+      Printf(f_module, "{\n");
+
+      Replaceall(module_class_code, "$module", module_class_name);
+      Replaceall(module_class_constants_code, "$module", module_class_name);
+
+      Replaceall(module_class_code, "$imclassname", imclass_name);
+      Replaceall(module_class_constants_code, "$imclassname", imclass_name);
+
+      // Add the wrapper methods
+      Printv(f_module, module_class_code, NIL);
+
+      // Finish off the class
+      Printf(f_module, "}\n");
+      Close(f_module);
+    }
+
+    // Generate the Java constants interface
+    if (Len(module_class_constants_code) != 0) {
+      String *filen = NewStringf("%s%sConstants.java", SWIG_output_directory(), module_class_name);
+      File *f_module = NewFile(filen, "w");
+      if (!f_module) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the Java constants interface file
+      emitBanner(f_module);
+
+      if (Len(package) > 0)
+	Printf(f_module, "package %s;\n", package);
+
+      if (module_imports)
+	Printf(f_module, "%s\n", module_imports);
+
+      Printf(f_module, "public interface %sConstants {\n", module_class_name);
+
+      // Write out all the global constants
+      Printv(f_module, module_class_constants_code, NIL);
+
+      // Finish off the Java interface
+      Printf(f_module, "}\n");
+      Close(f_module);
+    }
+
+    if (upcasts_code)
+      Printv(f_wrappers, upcasts_code, NIL);
+
+    emitDirectorUpcalls();
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n");
+    Printf(f_wrappers, "}\n");
+    Printf(f_wrappers, "#endif\n");
+
+    // Output a Java type wrapper class for each SWIG type
+    for (Iterator swig_type = First(swig_types_hash); swig_type.key; swig_type = Next(swig_type)) {
+      emitTypeWrapperClass(swig_type.key, swig_type.item);
+    }
+
+    // Check for overwriting file problems on filesystems that are case insensitive
+    Iterator it1;
+    Iterator it2;
+    for (it1 = First(filenames_list); it1.item; it1 = Next(it1)) {
+      String *item1_lower = Swig_string_lower(it1.item);
+      for (it2 = Next(it1); it2.item; it2 = Next(it2)) {
+	String *item2_lower = Swig_string_lower(it2.item);
+	if (it1.item && it2.item) {
+	  if (Strcmp(item1_lower, item2_lower) == 0) {
+	    Swig_warning(WARN_LANG_PORTABILITY_FILENAME, input_file, line_number,
+			 "Portability warning: File %s will be overwritten by %s on case insensitive filesystems such as "
+			 "Windows' FAT32 and NTFS unless the class/module name is renamed\n", it1.item, it2.item);
+	  }
+	}
+	Delete(item2_lower);
+      }
+      Delete(item1_lower);
+    }
+
+    Delete(swig_types_hash);
+    swig_types_hash = NULL;
+    Delete(filenames_list);
+    filenames_list = NULL;
+    Delete(imclass_name);
+    imclass_name = NULL;
+    Delete(imclass_class_code);
+    imclass_class_code = NULL;
+    Delete(proxy_class_def);
+    proxy_class_def = NULL;
+    Delete(proxy_class_code);
+    proxy_class_code = NULL;
+    Delete(module_class_constants_code);
+    module_class_constants_code = NULL;
+    Delete(imclass_baseclass);
+    imclass_baseclass = NULL;
+    Delete(imclass_interfaces);
+    imclass_interfaces = NULL;
+    Delete(imclass_class_modifiers);
+    imclass_class_modifiers = NULL;
+    Delete(module_class_name);
+    module_class_name = NULL;
+    Delete(module_class_code);
+    module_class_code = NULL;
+    Delete(module_baseclass);
+    module_baseclass = NULL;
+    Delete(module_interfaces);
+    module_interfaces = NULL;
+    Delete(module_imports);
+    module_imports = NULL;
+    Delete(module_class_modifiers);
+    module_class_modifiers = NULL;
+    Delete(imclass_imports);
+    imclass_imports = NULL;
+    Delete(imclass_cppcasts_code);
+    imclass_cppcasts_code = NULL;
+    Delete(imclass_directors);
+    imclass_directors = NULL;
+    Delete(upcasts_code);
+    upcasts_code = NULL;
+    Delete(package);
+    package = NULL;
+    Delete(jnipackage);
+    jnipackage = NULL;
+    Delete(package_path);
+    package_path = NULL;
+    Delete(dmethods_seq);
+    dmethods_seq = NULL;
+    Delete(dmethods_table);
+    dmethods_table = NULL;
+    n_dmethods = 0;
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+
+    if (directorsEnabled()) {
+      Dump(f_directors, f_runtime);
+      Dump(f_directors_h, f_runtime_h);
+
+      Printf(f_runtime_h, "\n");
+      Printf(f_runtime_h, "#endif\n");
+
+      Close(f_runtime_h);
+      Delete(f_runtime_h);
+      f_runtime_h = NULL;
+      Delete(f_directors);
+      f_directors = NULL;
+      Delete(f_directors_h);
+      f_directors_h = NULL;
+    }
+
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitBanner()
+   * ----------------------------------------------------------------------------- */
+
+  void emitBanner(File *f) {
+    Printf(f, "/* ----------------------------------------------------------------------------\n");
+    Printf(f, " * This file was automatically generated by SWIG (http://www.swig.org).\n");
+    Printf(f, " * Version %s\n", Swig_package_version());
+    Printf(f, " *\n");
+    Printf(f, " * Do not make changes to this file unless you know what you are doing--modify\n");
+    Printf(f, " * the SWIG interface file instead.\n");
+    Printf(f, " * ----------------------------------------------------------------------------- */\n\n");
+  }
+
+  /*-----------------------------------------------------------------------
+   * Add new director upcall signature
+   *----------------------------------------------------------------------*/
+
+  UpcallData *addUpcallMethod(String *imclass_method, String *class_method, String *imclass_desc, String *class_desc, String *decl) {
+    UpcallData *udata;
+    String *imclass_methodidx;
+    String *class_methodidx;
+    Hash *new_udata;
+    String *key = NewStringf("%s|%s", imclass_method, decl);
+
+    ++curr_class_dmethod;
+
+    /* Do we know about this director class already? */
+    if ((udata = Getattr(dmethods_table, key))) {
+      Delete(key);
+      return Getattr(udata, "methodoff");
+    }
+
+    imclass_methodidx = NewStringf("%d", n_dmethods);
+    class_methodidx = NewStringf("%d", n_dmethods - first_class_dmethod);
+    n_dmethods++;
+
+    new_udata = NewHash();
+    Append(dmethods_seq, new_udata);
+    Setattr(dmethods_table, key, new_udata);
+
+    Setattr(new_udata, "method", Copy(class_method));
+    Setattr(new_udata, "fdesc", Copy(class_desc));
+    Setattr(new_udata, "imclass_method", Copy(imclass_method));
+    Setattr(new_udata, "imclass_fdesc", Copy(imclass_desc));
+    Setattr(new_udata, "imclass_methodidx", imclass_methodidx);
+    Setattr(new_udata, "class_methodidx", class_methodidx);
+    Setattr(new_udata, "decl", Copy(decl));
+
+    Delete(key);
+    return new_udata;
+  }
+
+  /*-----------------------------------------------------------------------
+   * Get director upcall signature
+   *----------------------------------------------------------------------*/
+
+  UpcallData *getUpcallMethodData(String *director_class, String *decl) {
+    String *key = NewStringf("%s|%s", director_class, decl);
+    UpcallData *udata = Getattr(dmethods_table, key);
+
+    Delete(key);
+    return udata;
+  }
+
+  /* ----------------------------------------------------------------------
+   * nativeWrapper()
+   * ---------------------------------------------------------------------- */
+
+  virtual int nativeWrapper(Node *n) {
+    String *wrapname = Getattr(n, "wrap:name");
+
+    if (!addSymbol(wrapname, n))
+      return SWIG_ERROR;
+
+    if (Getattr(n, "type")) {
+      Swig_save("nativeWrapper", n, "name", NIL);
+      Setattr(n, "name", wrapname);
+      native_function_flag = true;
+      functionWrapper(n);
+      Swig_restore(n);
+      native_function_flag = false;
+    } else {
+      Printf(stderr, "%s : Line %d. No return type for %%native method %s.\n", input_file, line_number, Getattr(n, "wrap:name"));
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * functionWrapper()
+   * ---------------------------------------------------------------------- */
+
+  virtual int functionWrapper(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    Parm *p;
+    int i;
+    String *c_return_type = NewString("");
+    String *im_return_type = NewString("");
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *body = NewString("");
+    int num_arguments = 0;
+    int num_required = 0;
+    int gencomma = 0;
+    bool is_void_return;
+    String *overloaded_name = getOverloadedName(n);
+    String *nondir_args = NewString("");
+    bool is_destructor = (Cmp(Getattr(n, "nodeType"), "destructor") == 0);
+
+    if (!Getattr(n, "sym:overloaded")) {
+      if (!addSymbol(Getattr(n, "sym:name"), n))
+	return SWIG_ERROR;
+    }
+
+    /*
+       The rest of this function deals with generating the intermediary class wrapper function (that wraps
+       a c/c++ function) and generating the JNI c code. Each Java wrapper function has a 
+       matching JNI c function call.
+     */
+
+    // A new wrapper function object
+    Wrapper *f = NewWrapper();
+
+    // Make a wrapper name for this function
+    String *jniname = makeValidJniName(overloaded_name);
+    String *wname = Swig_name_wrapper(jniname);
+
+    Delete(jniname);
+
+    /* Attach the non-standard typemaps to the parameter list. */
+    Swig_typemap_attach_parms("jni", l, f);
+    Swig_typemap_attach_parms("jtype", l, f);
+    Swig_typemap_attach_parms("jstype", l, f);
+
+    /* Get return types */
+    if ((tm = Swig_typemap_lookup("jni", n, "", 0))) {
+      Printf(c_return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JNI_UNDEF, input_file, line_number, "No jni typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    if ((tm = Swig_typemap_lookup("jtype", n, "", 0))) {
+      Printf(im_return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JTYPE_UNDEF, input_file, line_number, "No jtype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    is_void_return = (Cmp(c_return_type, "void") == 0);
+    if (!is_void_return)
+      Wrapper_add_localv(f, "jresult", c_return_type, "jresult = 0", NIL);
+
+    Printv(f->def, "SWIGEXPORT ", c_return_type, " JNICALL ", wname, "(JNIEnv *jenv, jclass jcls", NIL);
+
+    // Usually these function parameters are unused - The code below ensures
+    // that compilers do not issue such a warning if configured to do so.
+
+    Printv(f->code, "    (void)jenv;\n", NIL);
+    Printv(f->code, "    (void)jcls;\n", NIL);
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+
+    // Parameter overloading
+    Setattr(n, "wrap:parms", l);
+    Setattr(n, "wrap:name", wname);
+
+    // Wrappers not wanted for some methods where the parameters cannot be overloaded in Java
+    if (Getattr(n, "sym:overloaded")) {
+      // Emit warnings for the few cases that can't be overloaded in Java and give up on generating wrapper
+      Swig_overload_check(n);
+      if (Getattr(n, "overload:ignore"))
+	return SWIG_OK;
+    }
+
+    Printf(imclass_class_code, "  public final static native %s %s(", im_return_type, overloaded_name);
+
+    /* Get number of required and total arguments */
+    num_arguments = emit_num_arguments(l);
+    num_required = emit_num_required(l);
+
+    // Now walk the function parameter list and generate code to get arguments
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+      String *im_param_type = NewString("");
+      String *c_param_type = NewString("");
+      String *arg = NewString("");
+
+      Printf(arg, "j%s", ln);
+
+      /* Get the JNI C types of the parameter */
+      if ((tm = Getattr(p, "tmap:jni"))) {
+	Printv(c_param_type, tm, NIL);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JNI_UNDEF, input_file, line_number, "No jni typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      /* Get the intermediary class parameter types of the parameter */
+      if ((tm = Getattr(p, "tmap:jtype"))) {
+	Printv(im_param_type, tm, NIL);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JTYPE_UNDEF, input_file, line_number, "No jtype typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      /* Add parameter to intermediary class method */
+      if (gencomma)
+	Printf(imclass_class_code, ", ");
+      Printf(imclass_class_code, "%s %s", im_param_type, arg);
+
+      // Add parameter to C function
+      Printv(f->def, ", ", c_param_type, " ", arg, NIL);
+
+      ++gencomma;
+
+      // Premature garbage collection prevention parameter
+      if (!is_destructor) {
+	String *pgc_parameter = prematureGarbageCollectionPreventionParameter(pt, p);
+	if (pgc_parameter) {
+	  Printf(imclass_class_code, ", %s %s_", pgc_parameter, arg);
+	  Printf(f->def, ", jobject %s_", arg);
+	  Printf(f->code, "    (void)%s_;\n", arg);
+	}
+      }
+      // Get typemap for this argument
+      if ((tm = Getattr(p, "tmap:in"))) {
+	addThrows(n, "tmap:in", p);
+	Replaceall(tm, "$source", arg);	/* deprecated */
+	Replaceall(tm, "$target", ln);	/* deprecated */
+	Replaceall(tm, "$arg", arg);	/* deprecated? */
+	Replaceall(tm, "$input", arg);
+	Setattr(p, "emit:input", arg);
+
+	Printf(nondir_args, "%s\n", tm);
+
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+	p = nextSibling(p);
+      }
+
+      Delete(im_param_type);
+      Delete(c_param_type);
+      Delete(arg);
+    }
+
+    Printv(f->code, nondir_args, NIL);
+    Delete(nondir_args);
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	addThrows(n, "tmap:check", p);
+	Replaceall(tm, "$target", Getattr(p, "lname"));	/* deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	addThrows(n, "tmap:freearg", p);
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	addThrows(n, "tmap:argout", p);
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* deprecated */
+	Replaceall(tm, "$target", Getattr(p, "lname"));	/* deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	Replaceall(tm, "$result", "jresult");
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Get any Java exception classes in the throws typemap
+    ParmList *throw_parm_list = NULL;
+    if ((throw_parm_list = Getattr(n, "throws"))) {
+      Swig_typemap_attach_parms("throws", throw_parm_list, f);
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	if ((tm = Getattr(p, "tmap:throws"))) {
+	  addThrows(n, "tmap:throws", p);
+	}
+      }
+    }
+
+    if (!native_function_flag) {
+      if (Cmp(nodeType(n), "constant") == 0) {
+        // Wrapping a constant hack
+        Swig_save("functionWrapper", n, "wrap:action", NIL);
+
+        // below based on Swig_VargetToFunction()
+        SwigType *ty = Swig_wrapped_var_type(Getattr(n, "type"), use_naturalvar_mode(n));
+        Setattr(n, "wrap:action", NewStringf("result = (%s) %s;", SwigType_lstr(ty, 0), Getattr(n, "value")));
+      }
+
+      // Now write code to make the function call
+      Swig_director_emit_dynamic_cast(n, f);
+      String *actioncode = emit_action(n);
+
+      // Handle exception classes specified in the "except" feature's "throws" attribute
+      addThrows(n, "feature:except", n);
+
+      if (Cmp(nodeType(n), "constant") == 0)
+        Swig_restore(n);
+
+      /* Return value if necessary  */
+      if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+	addThrows(n, "tmap:out", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Replaceall(tm, "$target", "jresult");	/* deprecated */
+	Replaceall(tm, "$result", "jresult");
+
+        if (GetFlag(n, "feature:new"))
+          Replaceall(tm, "$owner", "1");
+        else
+          Replaceall(tm, "$owner", "0");
+
+	Printf(f->code, "%s", tm);
+	if (Len(tm))
+	  Printf(f->code, "\n");
+      } else {
+	Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(t, 0), Getattr(n, "name"));
+      }
+      emit_return_variable(n, t, f);
+    }
+
+    /* Output argument output code */
+    Printv(f->code, outarg, NIL);
+
+    /* Output cleanup code */
+    Printv(f->code, cleanup, NIL);
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	addThrows(n, "tmap:newfree", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if (!native_function_flag) {
+      if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+	addThrows(n, "tmap:ret", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* Finish C function and intermediary class function definitions */
+    Printf(imclass_class_code, ")");
+    generateThrowsClause(n, imclass_class_code);
+    Printf(imclass_class_code, ";\n");
+
+    Printf(f->def, ") {");
+
+    if (!is_void_return)
+      Printv(f->code, "    return jresult;\n", NIL);
+    Printf(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", symname);
+
+    /* Contract macro modification */
+    Replaceall(f->code, "SWIG_contract_assert(", "SWIG_contract_assert($null, ");
+
+    if (!is_void_return)
+      Replaceall(f->code, "$null", "0");
+    else
+      Replaceall(f->code, "$null", "");
+
+    /* Dump the function out */
+    if (!native_function_flag)
+      Wrapper_print(f, f_wrappers);
+
+    if (!(proxy_flag && is_wrapping_class()) && !enum_constant_flag) {
+      moduleClassFunctionHandler(n);
+    }
+
+    /* 
+     * Generate the proxy class getters/setters for public member variables.
+     * Not for enums and constants.
+     */
+    if (proxy_flag && wrapping_member_flag && !enum_constant_flag) {
+      // Capitalize the first letter in the variable to create a JavaBean type getter/setter function name
+      bool getter_flag = Cmp(symname, Swig_name_set(Swig_name_member(proxy_class_name, variable_name))) != 0;
+
+      String *getter_setter_name = NewString("");
+      if (!getter_flag)
+	Printf(getter_setter_name, "set");
+      else
+	Printf(getter_setter_name, "get");
+      Putc(toupper((int) *Char(variable_name)), getter_setter_name);
+      Printf(getter_setter_name, "%s", Char(variable_name) + 1);
+
+      Setattr(n, "proxyfuncname", getter_setter_name);
+      Setattr(n, "imfuncname", symname);
+
+      proxyClassFunctionHandler(n);
+      Delete(getter_setter_name);
+    }
+
+    Delete(c_return_type);
+    Delete(im_return_type);
+    Delete(cleanup);
+    Delete(outarg);
+    Delete(body);
+    Delete(overloaded_name);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * variableWrapper()
+   * ----------------------------------------------------------------------- */
+
+  virtual int variableWrapper(Node *n) {
+    variable_wrapper_flag = true;
+    Language::variableWrapper(n);	/* Default to functions */
+    variable_wrapper_flag = false;
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * globalvariableHandler()
+   * ------------------------------------------------------------------------ */
+
+  virtual int globalvariableHandler(Node *n) {
+
+    variable_name = Getattr(n, "sym:name");
+    global_variable_flag = true;
+    int ret = Language::globalvariableHandler(n);
+    global_variable_flag = false;
+    return ret;
+  }
+
+  /* ----------------------------------------------------------------------
+   * enumDeclaration()
+   *
+   * C/C++ enums can be mapped in one of 4 ways, depending on the java:enum feature specified:
+   * 1) Simple enums - simple constant within the proxy class or module class
+   * 2) Typeunsafe enums - simple constant in a Java class (class named after the c++ enum name)
+   * 3) Typesafe enum - typesafe enum pattern (class named after the c++ enum name)
+   * 4) Proper enums - proper Java enum
+   * Anonymous enums always default to 1)
+   * ---------------------------------------------------------------------- */
+
+  virtual int enumDeclaration(Node *n) {
+
+    if (!ImportMode) {
+      if (getCurrentClass() && (cplus_mode != PUBLIC))
+	return SWIG_NOWRAP;
+
+      enum_code = NewString("");
+      String *symname = Getattr(n, "sym:name");
+      String *constants_code = (proxy_flag && is_wrapping_class())? proxy_class_constants_code : module_class_constants_code;
+      EnumFeature enum_feature = decodeEnumFeature(n);
+      String *typemap_lookup_type = Getattr(n, "name");
+
+      if ((enum_feature != SimpleEnum) && symname && typemap_lookup_type) {
+	// Wrap (non-anonymous) C/C++ enum within a typesafe, typeunsafe or proper Java enum
+
+	// Pure Java baseclass and interfaces
+	const String *pure_baseclass = typemapLookup("javabase", typemap_lookup_type, WARN_NONE);
+	const String *pure_interfaces = typemapLookup("javainterfaces", typemap_lookup_type, WARN_NONE);
+
+	// Emit the enum
+	Printv(enum_code, typemapLookup("javaclassmodifiers", typemap_lookup_type, WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers (enum modifiers really)
+	       " ", symname, *Char(pure_baseclass) ?	// Bases
+	       " extends " : "", pure_baseclass, *Char(pure_interfaces) ?	// Interfaces
+	       " implements " : "", pure_interfaces, " {\n", NIL);
+	if (proxy_flag && is_wrapping_class())
+	  Replaceall(enum_code, "$static ", "static ");
+	else
+	  Replaceall(enum_code, "$static ", "");
+      } else {
+	// Wrap C++ enum with integers - just indicate start of enum with a comment, no comment for anonymous enums of any sort
+	if (symname && !Getattr(n, "unnamedinstance"))
+	  Printf(constants_code, "  // %s \n", symname);
+      }
+
+      // Emit each enum item
+      Language::enumDeclaration(n);
+
+      if ((enum_feature != SimpleEnum) && symname && typemap_lookup_type) {
+	// Wrap (non-anonymous) C/C++ enum within a typesafe, typeunsafe or proper Java enum
+	// Finish the enum declaration
+	// Typemaps are used to generate the enum definition in a similar manner to proxy classes.
+	Printv(enum_code, (enum_feature == ProperEnum) ? ";\n" : "", typemapLookup("javabody", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF),	// main body of class
+	       typemapLookup("javacode", typemap_lookup_type, WARN_NONE),	// extra Java code
+	       "}", NIL);
+
+	Replaceall(enum_code, "$javaclassname", symname);
+
+	// Substitute $enumvalues - intended usage is for typesafe enums
+	if (Getattr(n, "enumvalues"))
+	  Replaceall(enum_code, "$enumvalues", Getattr(n, "enumvalues"));
+	else
+	  Replaceall(enum_code, "$enumvalues", "");
+
+	if (proxy_flag && is_wrapping_class()) {
+	  // Enums defined within the C++ class are defined within the proxy class
+
+	  // Add extra indentation
+	  Replaceall(enum_code, "\n", "\n  ");
+	  Replaceall(enum_code, "  \n", "\n");
+
+	  Printv(proxy_class_constants_code, "  ", enum_code, "\n\n", NIL);
+	} else {
+	  // Global enums are defined in their own file
+	  String *filen = NewStringf("%s%s.java", SWIG_output_directory(), symname);
+	  File *f_enum = NewFile(filen, "w");
+	  if (!f_enum) {
+	    FileErrorDisplay(filen);
+	    SWIG_exit(EXIT_FAILURE);
+	  }
+	  Append(filenames_list, Copy(filen));
+	  Delete(filen);
+	  filen = NULL;
+
+	  // Start writing out the enum file
+	  emitBanner(f_enum);
+
+	  if (Len(package) > 0)
+	    Printf(f_enum, "package %s;\n", package);
+
+	  Printv(f_enum, typemapLookup("javaimports", typemap_lookup_type, WARN_NONE),	// Import statements
+		 "\n", enum_code, "\n", NIL);
+
+	  Printf(f_enum, "\n");
+	  Close(f_enum);
+	}
+      } else {
+	// Wrap C++ enum with simple constant
+	Printf(enum_code, "\n");
+	if (proxy_flag && is_wrapping_class())
+	  Printv(proxy_class_constants_code, enum_code, NIL);
+	else
+	  Printv(module_class_constants_code, enum_code, NIL);
+      }
+
+      Delete(enum_code);
+      enum_code = NULL;
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * enumvalueDeclaration()
+   * ---------------------------------------------------------------------- */
+
+  virtual int enumvalueDeclaration(Node *n) {
+    if (getCurrentClass() && (cplus_mode != PUBLIC))
+      return SWIG_NOWRAP;
+
+    Swig_require("enumvalueDeclaration", n, "*name", "?value", NIL);
+    String *symname = Getattr(n, "sym:name");
+    String *value = Getattr(n, "value");
+    String *name = Getattr(n, "name");
+    String *tmpValue;
+
+    // Strange hack from parent method
+    if (value)
+      tmpValue = NewString(value);
+    else
+      tmpValue = NewString(name);
+    // Note that this is used in enumValue() amongst other places
+    Setattr(n, "value", tmpValue);
+
+    {
+      EnumFeature enum_feature = decodeEnumFeature(parentNode(n));
+
+      if ((enum_feature == ProperEnum) && Getattr(parentNode(n), "sym:name") && !Getattr(parentNode(n), "unnamedinstance")) {
+	// Wrap (non-anonymous) C/C++ enum with a proper Java enum
+	// Emit the enum item.
+	if (!Getattr(n, "_last"))	// Only the first enum item has this attribute set
+	  Printf(enum_code, ",\n");
+	Printf(enum_code, "  %s", symname);
+	if (Getattr(n, "enumvalue")) {
+	  String *value = enumValue(n);
+	  Printf(enum_code, "(%s)", value);
+	  Delete(value);
+	}
+      } else {
+	// Wrap C/C++ enums with constant integers or use the typesafe enum pattern
+	const String *parent_name = Getattr(parentNode(n), "name");
+	String *typemap_lookup_type = parent_name ? Copy(parent_name) : NewString("int");
+	const String *tm = typemapLookup("jstype", typemap_lookup_type, WARN_JAVA_TYPEMAP_JSTYPE_UNDEF);
+	String *return_type = Copy(tm);
+	Delete(typemap_lookup_type);
+	typemap_lookup_type = NULL;
+
+        const String *methodmods = Getattr(n, "feature:java:methodmodifiers");
+        methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+
+	if ((enum_feature == TypesafeEnum) && Getattr(parentNode(n), "sym:name") && !Getattr(parentNode(n), "unnamedinstance")) {
+	  // Wrap (non-anonymouse) enum using the typesafe enum pattern
+	  if (Getattr(n, "enumvalue")) {
+	    String *value = enumValue(n);
+	    Printf(enum_code, "  %s final static %s %s = new %s(\"%s\", %s);\n", methodmods, return_type, symname, return_type, symname, value);
+	    Delete(value);
+	  } else {
+	    Printf(enum_code, "  %s final static %s %s = new %s(\"%s\");\n", methodmods, return_type, symname, return_type, symname);
+	  }
+	} else {
+	  // Simple integer constants
+	  // Note these are always generated for anonymous enums, no matter what enum_feature is specified
+	  // Code generated is the same for SimpleEnum and TypeunsafeEnum -> the class it is generated into is determined later
+	  String *value = enumValue(n);
+	  Printf(enum_code, "  %s final static %s %s = %s;\n", methodmods, return_type, symname, value);
+	  Delete(value);
+	}
+      }
+
+      // Add the enum value to the comma separated list being constructed in the enum declaration.
+      String *enumvalues = Getattr(parentNode(n), "enumvalues");
+      if (!enumvalues)
+	Setattr(parentNode(n), "enumvalues", Copy(symname));
+      else
+	Printv(enumvalues, ", ", symname, NIL);
+    }
+
+    Delete(tmpValue);
+    Swig_restore(n);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * constantWrapper()
+   * Used for wrapping constants - #define or %constant.
+   * Also for inline initialised const static primitive type member variables (short, int, double, enums etc).
+   * Java static final variables are generated for these.
+   * If the %javaconst(1) feature is used then the C constant value is used to initialise the Java final variable.
+   * If not, a JNI method is generated to get the C constant value for initialisation of the Java final variable.
+   * However, if the %javaconstvalue feature is used, it overrides all other ways to generate the initialisation.
+   * Also note that this method might be called for wrapping enum items (when the enum is using %javaconst(0)).
+   * ------------------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    String *return_type = NewString("");
+    String *constants_code = NewString("");
+
+    if (!addSymbol(symname, n))
+      return SWIG_ERROR;
+
+    bool is_enum_item = (Cmp(nodeType(n), "enumitem") == 0);
+
+    // The %javaconst feature determines how the constant value is obtained
+    int const_feature_flag = GetFlag(n, "feature:java:const");
+
+    /* Adjust the enum type for the Swig_typemap_lookup.
+     * We want the same jstype typemap for all the enum items so we use the enum type (parent node). */
+    if (is_enum_item) {
+      t = Getattr(parentNode(n), "enumtype");
+      Setattr(n, "type", t);
+    }
+
+    /* Attach the non-standard typemaps to the parameter list. */
+    Swig_typemap_attach_parms("jstype", l, NULL);
+
+    /* Get Java return types */
+    bool classname_substituted_flag = false;
+
+    if ((tm = Swig_typemap_lookup("jstype", n, "", 0))) {
+      classname_substituted_flag = substituteClassname(t, tm);
+      Printf(return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JSTYPE_UNDEF, input_file, line_number, "No jstype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    // Add the stripped quotes back in
+    String *new_value = NewString("");
+    Swig_save("constantWrapper", n, "value", NIL);
+    if (SwigType_type(t) == T_STRING) {
+      Printf(new_value, "\"%s\"", Copy(Getattr(n, "value")));
+      Setattr(n, "value", new_value);
+    } else if (SwigType_type(t) == T_CHAR) {
+      Printf(new_value, "\'%s\'", Copy(Getattr(n, "value")));
+      Setattr(n, "value", new_value);
+    }
+
+    const String *itemname = (proxy_flag && wrapping_member_flag) ? variable_name : symname;
+    const String *methodmods = Getattr(n, "feature:java:methodmodifiers");
+    methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+
+    Printf(constants_code, "  %s final static %s %s = ", methodmods, return_type, itemname);
+
+    // Check for the %javaconstvalue feature
+    String *value = Getattr(n, "feature:java:constvalue");
+
+    if (value) {
+      Printf(constants_code, "%s;\n", value);
+    } else if (!const_feature_flag) {
+      // Default enum and constant handling will work with any type of C constant and initialises the Java variable from C through a JNI call.
+
+      if (classname_substituted_flag) {
+	if (SwigType_isenum(t)) {
+	  // This handles wrapping of inline initialised const enum static member variables (not when wrapping enum items - ignored later on)
+	  Printf(constants_code, "%s.swigToEnum(%s.%s());\n", return_type, imclass_name, Swig_name_get(symname));
+	} else {
+	  // This handles function pointers using the %constant directive
+	  Printf(constants_code, "new %s(%s.%s(), false);\n", return_type, imclass_name, Swig_name_get(symname));
+	}
+      } else
+	Printf(constants_code, "%s.%s();\n", imclass_name, Swig_name_get(symname));
+
+      // Each constant and enum value is wrapped with a separate JNI function call
+      SetFlag(n, "feature:immutable");
+      enum_constant_flag = true;
+      variableWrapper(n);
+      enum_constant_flag = false;
+    } else {
+      // Alternative constant handling will use the C syntax to make a true Java constant and hope that it compiles as Java code
+      Printf(constants_code, "%s;\n", Getattr(n, "value"));
+    }
+
+    // Emit the generated code to appropriate place
+    // Enums only emit the intermediate and JNI methods, so no proxy or module class wrapper methods needed
+    if (!is_enum_item) {
+      if (proxy_flag && wrapping_member_flag)
+	Printv(proxy_class_constants_code, constants_code, NIL);
+      else
+	Printv(module_class_constants_code, constants_code, NIL);
+    }
+    // Cleanup
+    Swig_restore(n);
+    Delete(new_value);
+    Delete(return_type);
+    Delete(constants_code);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * insertDirective()
+   * ----------------------------------------------------------------------------- */
+
+  virtual int insertDirective(Node *n) {
+    String *code = Getattr(n, "code");
+    Replaceall(code, "$module", module_class_name);
+    Replaceall(code, "$imclassname", imclass_name);
+    return Language::insertDirective(n);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * pragmaDirective()
+   *
+   * Valid Pragmas:
+   * jniclassbase            - base (extends) for the intermediary class
+   * jniclassclassmodifiers  - class modifiers for the intermediary class
+   * jniclasscode            - text (java code) is copied verbatim to the intermediary class
+   * jniclassimports         - import statements for the intermediary class
+   * jniclassinterfaces      - interface (implements) for the intermediary class
+   *
+   * modulebase              - base (extends) for the module class
+   * moduleclassmodifiers    - class modifiers for the module class
+   * modulecode              - text (java code) is copied verbatim to the module class
+   * moduleimports           - import statements for the module class
+   * moduleinterfaces        - interface (implements) for the module class
+   *
+   * ----------------------------------------------------------------------------- */
+
+  virtual int pragmaDirective(Node *n) {
+    if (!ImportMode) {
+      String *lang = Getattr(n, "lang");
+      String *code = Getattr(n, "name");
+      String *value = Getattr(n, "value");
+
+      if (Strcmp(lang, "java") == 0) {
+
+	String *strvalue = NewString(value);
+	Replaceall(strvalue, "\\\"", "\"");
+
+	if (Strcmp(code, "jniclassbase") == 0) {
+	  Delete(imclass_baseclass);
+	  imclass_baseclass = Copy(strvalue);
+	} else if (Strcmp(code, "jniclassclassmodifiers") == 0) {
+	  Delete(imclass_class_modifiers);
+	  imclass_class_modifiers = Copy(strvalue);
+	} else if (Strcmp(code, "jniclasscode") == 0) {
+	  Printf(imclass_class_code, "%s\n", strvalue);
+	} else if (Strcmp(code, "jniclassimports") == 0) {
+	  Delete(imclass_imports);
+	  imclass_imports = Copy(strvalue);
+	} else if (Strcmp(code, "jniclassinterfaces") == 0) {
+	  Delete(imclass_interfaces);
+	  imclass_interfaces = Copy(strvalue);
+	} else if (Strcmp(code, "modulebase") == 0) {
+	  Delete(module_baseclass);
+	  module_baseclass = Copy(strvalue);
+	} else if (Strcmp(code, "moduleclassmodifiers") == 0) {
+	  Delete(module_class_modifiers);
+	  module_class_modifiers = Copy(strvalue);
+	} else if (Strcmp(code, "modulecode") == 0) {
+	  Printf(module_class_code, "%s\n", strvalue);
+	} else if (Strcmp(code, "moduleimports") == 0) {
+	  Delete(module_imports);
+	  module_imports = Copy(strvalue);
+	} else if (Strcmp(code, "moduleinterfaces") == 0) {
+	  Delete(module_interfaces);
+	  module_interfaces = Copy(strvalue);
+	} else if (Strcmp(code, "moduleimport") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use the moduleimports pragma.\n", input_file, line_number);
+	} else if (Strcmp(code, "moduleinterface") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use the moduleinterfaces pragma.\n", input_file, line_number);
+	} else if (Strcmp(code, "modulemethodmodifiers") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%javamethodmodifiers.\n", input_file, line_number);
+	} else if (Strcmp(code, "allshadowimport") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javaimports).\n", input_file, line_number);
+	} else if (Strcmp(code, "allshadowcode") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javacode).\n", input_file, line_number);
+	} else if (Strcmp(code, "allshadowbase") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javabase).\n", input_file, line_number);
+	} else if (Strcmp(code, "allshadowinterface") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javainterfaces).\n", input_file, line_number);
+	} else if (Strcmp(code, "allshadowclassmodifiers") == 0) {
+	  Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javaclassmodifiers).\n", input_file, line_number);
+	} else if (proxy_flag) {
+	  if (Strcmp(code, "shadowcode") == 0) {
+	    Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javacode).\n", input_file, line_number);
+	  } else if (Strcmp(code, "shadowimport") == 0) {
+	    Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javaimports).\n", input_file, line_number);
+	  } else if (Strcmp(code, "shadowbase") == 0) {
+	    Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javabase).\n", input_file, line_number);
+	  } else if (Strcmp(code, "shadowinterface") == 0) {
+	    Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javainterfaces).\n", input_file, line_number);
+	  } else if (Strcmp(code, "shadowclassmodifiers") == 0) {
+	    Printf(stderr, "%s : Line %d. Ignored: Deprecated pragma. Please use %%typemap(javaclassmodifiers).\n", input_file, line_number);
+	  } else {
+	    Printf(stderr, "%s : Line %d. Unrecognized pragma.\n", input_file, line_number);
+	  }
+	} else {
+	  Printf(stderr, "%s : Line %d. Unrecognized pragma.\n", input_file, line_number);
+	}
+	Delete(strvalue);
+      }
+    }
+    return Language::pragmaDirective(n);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitProxyClassDefAndCPPCasts()
+   * ----------------------------------------------------------------------------- */
+
+  void emitProxyClassDefAndCPPCasts(Node *n) {
+    String *c_classname = SwigType_namestr(Getattr(n, "name"));
+    String *c_baseclass = NULL;
+    String *baseclass = NULL;
+    String *c_baseclassname = NULL;
+    String *typemap_lookup_type = Getattr(n, "classtypeobj");
+    bool feature_director = Swig_directorclass(n) ? true : false;
+
+    // Inheritance from pure Java classes
+    Node *attributes = NewHash();
+    const String *pure_baseclass = typemapLookup("javabase", typemap_lookup_type, WARN_NONE, attributes);
+    bool purebase_replace = GetFlag(attributes, "tmap:javabase:replace") ? true : false;
+    Delete(attributes);
+
+    // C++ inheritance
+    if (!purebase_replace) {
+      List *baselist = Getattr(n, "bases");
+      if (baselist) {
+        Iterator base = First(baselist);
+        while (base.item && GetFlag(base.item, "feature:ignore")) {
+          base = Next(base);
+        }
+        if (base.item) {
+          c_baseclassname = Getattr(base.item, "name");
+          baseclass = Copy(getProxyName(c_baseclassname));
+          if (baseclass)
+            c_baseclass = SwigType_namestr(Getattr(base.item, "name"));
+          base = Next(base);
+          /* Warn about multiple inheritance for additional base class(es) */
+          while (base.item) {
+            if (GetFlag(base.item, "feature:ignore")) {
+              base = Next(base);
+              continue;
+            }
+            String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0);
+            String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0);
+            Swig_warning(WARN_JAVA_MULTIPLE_INHERITANCE, input_file, line_number,
+                         "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Java.\n", proxyclassname, baseclassname);
+            base = Next(base);
+          }
+        }
+      }
+    }
+
+    bool derived = baseclass && getProxyName(c_baseclassname);
+    const String *wanted_base = baseclass ? baseclass : pure_baseclass;
+
+    if (purebase_replace) {
+      wanted_base = pure_baseclass;
+      derived = false;
+      Delete(baseclass);
+      baseclass = NULL;
+    } else if (Len(pure_baseclass) > 0 && Len(baseclass) > 0) {
+      Swig_warning(WARN_JAVA_MULTIPLE_INHERITANCE, input_file, line_number,
+		   "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Java. Perhaps you need the replace attribute in the javabase typemap?\n", typemap_lookup_type, pure_baseclass);
+    }
+
+    // Pure Java interfaces
+    const String *pure_interfaces = typemapLookup("javainterfaces", typemap_lookup_type, WARN_NONE);
+
+    // Start writing the proxy class
+    Printv(proxy_class_def, typemapLookup("javaimports", typemap_lookup_type, WARN_NONE),	// Import statements
+	   "\n", typemapLookup("javaclassmodifiers", typemap_lookup_type, WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers
+	   " $javaclassname",	// Class name and bases
+	   (*Char(wanted_base)) ? " extends " : "", wanted_base, *Char(pure_interfaces) ?	// Pure Java interfaces
+	   " implements " : "", pure_interfaces, " {", derived ? typemapLookup("javabody_derived", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF) :	// main body of class
+	   typemapLookup("javabody", typemap_lookup_type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF),	// main body of class
+	   NIL);
+
+    // C++ destructor is wrapped by the delete method
+    // Note that the method name is specified in a typemap attribute called methodname
+    String *destruct = NewString("");
+    const String *tm = NULL;
+    attributes = NewHash();
+    String *destruct_methodname = NULL;
+    String *destruct_methodmodifiers = NULL;
+    if (derived) {
+      tm = typemapLookup("javadestruct_derived", typemap_lookup_type, WARN_NONE, attributes);
+      destruct_methodname = Getattr(attributes, "tmap:javadestruct_derived:methodname");
+      destruct_methodmodifiers = Getattr(attributes, "tmap:javadestruct_derived:methodmodifiers");
+    } else {
+      tm = typemapLookup("javadestruct", typemap_lookup_type, WARN_NONE, attributes);
+      destruct_methodname = Getattr(attributes, "tmap:javadestruct:methodname");
+      destruct_methodmodifiers = Getattr(attributes, "tmap:javadestruct:methodmodifiers");
+    }
+    if (tm && *Char(tm)) {
+      if (!destruct_methodname) {
+	Swig_error(input_file, line_number,
+		   "No methodname attribute defined in javadestruct%s typemap for %s\n", (derived ? "_derived" : ""), proxy_class_name);
+      }
+      if (!destruct_methodmodifiers) {
+	Swig_error(input_file, line_number,
+		   "No methodmodifiers attribute defined in javadestruct%s typemap for %s.\n", (derived ? "_derived" : ""), proxy_class_name);
+      }
+    }
+    // Emit the finalize and delete methods
+    if (tm) {
+      // Finalize method
+      if (*Char(destructor_call)) {
+	Printv(proxy_class_def, typemapLookup("javafinalize", typemap_lookup_type, WARN_NONE), NIL);
+      }
+      // delete method
+      Printv(destruct, tm, NIL);
+      if (*Char(destructor_call))
+	Replaceall(destruct, "$jnicall", destructor_call);
+      else
+	Replaceall(destruct, "$jnicall", "throw new UnsupportedOperationException(\"C++ destructor does not have public access\")");
+      if (*Char(destruct))
+	Printv(proxy_class_def, "\n  ", destruct_methodmodifiers, " void ", destruct_methodname, "() ", destruct, "\n", NIL);
+    }
+
+    /* Insert directordisconnect typemap, if this class has directors enabled */
+    /* Also insert the swigTakeOwnership and swigReleaseOwnership methods */
+    if (feature_director) {
+      String *destruct_jnicall, *release_jnicall, *take_jnicall;
+
+      destruct_jnicall = NewStringf("%s()", destruct_methodname);
+      release_jnicall = NewStringf("%s.%s_change_ownership(this, swigCPtr, false)", imclass_name, proxy_class_name);
+      take_jnicall = NewStringf("%s.%s_change_ownership(this, swigCPtr, true)", imclass_name, proxy_class_name);
+
+      emitCodeTypemap(false, typemap_lookup_type, "directordisconnect", "methodname", destruct_jnicall);
+      emitCodeTypemap(false, typemap_lookup_type, "directorowner_release", "methodname", release_jnicall);
+      emitCodeTypemap(false, typemap_lookup_type, "directorowner_take", "methodname", take_jnicall);
+
+      Delete(destruct_jnicall);
+      Delete(release_jnicall);
+      Delete(take_jnicall);
+    }
+
+    Delete(attributes);
+    Delete(destruct);
+
+    // Emit extra user code
+    Printv(proxy_class_def, typemapLookup("javacode", typemap_lookup_type, WARN_NONE),	// extra Java code
+	   "\n", NIL);
+
+    // Substitute various strings into the above template
+    Replaceall(proxy_class_code, "$javaclassname", proxy_class_name);
+    Replaceall(proxy_class_def, "$javaclassname", proxy_class_name);
+
+    Replaceall(proxy_class_def, "$module", module_class_name);
+    Replaceall(proxy_class_code, "$module", module_class_name);
+
+    Replaceall(proxy_class_def, "$imclassname", imclass_name);
+    Replaceall(proxy_class_code, "$imclassname", imclass_name);
+
+    // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy)
+    if (derived) {
+      Printv(imclass_cppcasts_code, "  public final static native long SWIG$javaclassnameUpcast(long jarg1);\n", NIL);
+
+      Replaceall(imclass_cppcasts_code, "$javaclassname", proxy_class_name);
+
+      Printv(upcasts_code,
+	     "SWIGEXPORT jlong JNICALL Java_$jnipackage$imimclass_SWIG$imclazznameUpcast",
+	     "(JNIEnv *jenv, jclass jcls, jlong jarg1) {\n",
+	     "    jlong baseptr = 0;\n"
+	     "    (void)jenv;\n" "    (void)jcls;\n" "    *($cbaseclass **)&baseptr = *($cclass **)&jarg1;\n" "    return baseptr;\n" "}\n", "\n", NIL);
+
+      String *imimclass = makeValidJniName(imclass_name);
+      String *imclazzname = makeValidJniName(proxy_class_name);
+      Replaceall(upcasts_code, "$cbaseclass", c_baseclass);
+      Replaceall(upcasts_code, "$imclazzname", imclazzname);
+      Replaceall(upcasts_code, "$cclass", c_classname);
+      Replaceall(upcasts_code, "$jnipackage", jnipackage);
+      Replaceall(upcasts_code, "$imimclass", imimclass);
+
+      Delete(imclazzname);
+      Delete(imimclass);
+    }
+    Delete(baseclass);
+  }
+
+  /* ----------------------------------------------------------------------
+   * classHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int classHandler(Node *n) {
+
+    File *f_proxy = NULL;
+    if (proxy_flag) {
+      proxy_class_name = NewString(Getattr(n, "sym:name"));
+
+      if (!addSymbol(proxy_class_name, n))
+	return SWIG_ERROR;
+
+      if (Cmp(proxy_class_name, imclass_name) == 0) {
+	Printf(stderr, "Class name cannot be equal to intermediary class name: %s\n", proxy_class_name);
+	SWIG_exit(EXIT_FAILURE);
+      }
+
+      if (Cmp(proxy_class_name, module_class_name) == 0) {
+	Printf(stderr, "Class name cannot be equal to module class name: %s\n", proxy_class_name);
+	SWIG_exit(EXIT_FAILURE);
+      }
+
+      String *filen = NewStringf("%s%s.java", SWIG_output_directory(), proxy_class_name);
+      f_proxy = NewFile(filen, "w");
+      if (!f_proxy) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Append(filenames_list, Copy(filen));
+      Delete(filen);
+      filen = NULL;
+
+      // Start writing out the proxy class file
+      emitBanner(f_proxy);
+
+      if (Len(package) > 0)
+	Printf(f_proxy, "package %s;\n", package);
+
+      Clear(proxy_class_def);
+      Clear(proxy_class_code);
+
+      destructor_call = NewString("");
+      proxy_class_constants_code = NewString("");
+    }
+
+    Language::classHandler(n);
+
+    if (proxy_flag) {
+
+      emitProxyClassDefAndCPPCasts(n);
+
+      Replaceall(proxy_class_def, "$module", module_class_name);
+      Replaceall(proxy_class_code, "$module", module_class_name);
+      Replaceall(proxy_class_constants_code, "$module", module_class_name);
+      Replaceall(proxy_class_def, "$imclassname", imclass_name);
+      Replaceall(proxy_class_code, "$imclassname", imclass_name);
+      Replaceall(proxy_class_constants_code, "$imclassname", imclass_name);
+      Printv(f_proxy, proxy_class_def, proxy_class_code, NIL);
+
+      // Write out all the constants
+      if (Len(proxy_class_constants_code) != 0)
+	Printv(f_proxy, proxy_class_constants_code, NIL);
+
+      Printf(f_proxy, "}\n");
+      Close(f_proxy);
+      f_proxy = NULL;
+
+      /* Output the downcast method, if necessary. Note: There's no other really
+         good place to put this code, since Abstract Base Classes (ABCs) can and should have 
+         downcasts, making the constructorHandler() a bad place (because ABCs don't get to
+         have constructors emitted.) */
+      if (GetFlag(n, "feature:javadowncast")) {
+	String *jni_imclass_name = makeValidJniName(imclass_name);
+	String *jni_class_name = makeValidJniName(proxy_class_name);
+	String *norm_name = SwigType_namestr(Getattr(n, "name"));
+
+	Printf(imclass_class_code, "  public final static native %s downcast%s(long cPtrBase, boolean cMemoryOwn);\n", proxy_class_name, proxy_class_name);
+
+	Wrapper *dcast_wrap = NewWrapper();
+
+	Printf(dcast_wrap->def, "SWIGEXPORT jobject JNICALL Java_%s%s_downcast%s(JNIEnv *jenv, jclass jcls, jlong jCPtrBase, jboolean cMemoryOwn) {",
+	       jnipackage, jni_imclass_name, jni_class_name);
+	Printf(dcast_wrap->code, "  Swig::Director *director = (Swig::Director *) 0;\n");
+	Printf(dcast_wrap->code, "  jobject jresult = (jobject) 0;\n");
+	Printf(dcast_wrap->code, "  %s *obj = *((%s **)&jCPtrBase);\n", norm_name, norm_name);
+	Printf(dcast_wrap->code, "  if (obj) director = dynamic_cast<Swig::Director *>(obj);\n");
+	Printf(dcast_wrap->code, "  if (director) jresult = director->swig_get_self(jenv);\n");
+	Printf(dcast_wrap->code, "  return jresult;\n");
+	Printf(dcast_wrap->code, "}\n");
+
+	Wrapper_print(dcast_wrap, f_wrappers);
+	DelWrapper(dcast_wrap);
+      }
+
+      emitDirectorExtraMethods(n);
+
+      Delete(proxy_class_name);
+      proxy_class_name = NULL;
+      Delete(destructor_call);
+      destructor_call = NULL;
+      Delete(proxy_class_constants_code);
+      proxy_class_constants_code = NULL;
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberfunctionHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int memberfunctionHandler(Node *n) {
+    member_func_flag = true;
+    Language::memberfunctionHandler(n);
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *intermediary_function_name = Swig_name_member(proxy_class_name, overloaded_name);
+      Setattr(n, "proxyfuncname", Getattr(n, "sym:name"));
+      Setattr(n, "imfuncname", intermediary_function_name);
+      proxyClassFunctionHandler(n);
+      Delete(overloaded_name);
+    }
+    member_func_flag = false;
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+
+    static_flag = true;
+    member_func_flag = true;
+    Language::staticmemberfunctionHandler(n);
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *intermediary_function_name = Swig_name_member(proxy_class_name, overloaded_name);
+      Setattr(n, "proxyfuncname", Getattr(n, "sym:name"));
+      Setattr(n, "imfuncname", intermediary_function_name);
+      proxyClassFunctionHandler(n);
+      Delete(overloaded_name);
+    }
+    static_flag = false;
+    member_func_flag = false;
+
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * proxyClassFunctionHandler()
+   *
+   * Function called for creating a Java wrapper function around a c++ function in the 
+   * proxy class. Used for both static and non-static C++ class functions.
+   * C++ class static functions map to Java static functions.
+   * Two extra attributes in the Node must be available. These are "proxyfuncname" - 
+   * the name of the Java class proxy function, which in turn will call "imfuncname" - 
+   * the intermediary (JNI) function name in the intermediary class.
+   * ----------------------------------------------------------------------------- */
+
+  void proxyClassFunctionHandler(Node *n) {
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *intermediary_function_name = Getattr(n, "imfuncname");
+    String *proxy_function_name = Getattr(n, "proxyfuncname");
+    String *tm;
+    Parm *p;
+    int i;
+    String *imcall = NewString("");
+    String *return_type = NewString("");
+    String *function_code = NewString("");
+    bool setter_flag = false;
+    String *pre_code = NewString("");
+    String *post_code = NewString("");
+
+    if (!proxy_flag)
+      return;
+
+    // Wrappers not wanted for some methods where the parameters cannot be overloaded in Java
+    if (Getattr(n, "overload:ignore"))
+      return;
+
+    // Don't generate proxy method for additional explicitcall method used in directors
+    if (GetFlag(n, "explicitcall"))
+      return;
+
+    if (l) {
+      if (SwigType_type(Getattr(l, "type")) == T_VOID) {
+	l = nextSibling(l);
+      }
+    }
+
+    /* Attach the non-standard typemaps to the parameter list */
+    Swig_typemap_attach_parms("in", l, NULL);
+    Swig_typemap_attach_parms("jtype", l, NULL);
+    Swig_typemap_attach_parms("jstype", l, NULL);
+    Swig_typemap_attach_parms("javain", l, NULL);
+
+    /* Get return types */
+    if ((tm = Swig_typemap_lookup("jstype", n, "", 0))) {
+      // Note that in the case of polymorphic (covariant) return types, the method's return type is changed to be the base of the C++ return type
+      SwigType *covariant = Getattr(n, "covariant");
+      substituteClassname(covariant ? covariant : t, tm);
+      Printf(return_type, "%s", tm);
+      if (covariant)
+	Swig_warning(WARN_JAVA_COVARIANT_RET, input_file, line_number,
+		     "Covariant return types not supported in Java. Proxy method will return %s.\n", SwigType_str(covariant, 0));
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JSTYPE_UNDEF, input_file, line_number, "No jstype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    if (wrapping_member_flag && !enum_constant_flag) {
+      // For wrapping member variables (Javabean setter)
+      setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(Swig_name_member(proxy_class_name, variable_name))) == 0);
+    }
+
+    /* Start generating the proxy function */
+    const String *methodmods = Getattr(n, "feature:java:methodmodifiers");
+    methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+    Printf(function_code, "  %s ", methodmods);
+    if (static_flag)
+      Printf(function_code, "static ");
+    Printf(function_code, "%s %s(", return_type, proxy_function_name);
+
+    Printv(imcall, imclass_name, ".$imfuncname(", NIL);
+    if (!static_flag) {
+      Printf(imcall, "swigCPtr");
+
+      String *this_type = Copy(getClassType());
+      String *name = NewString("self");
+      String *qualifier = Getattr(n, "qualifier");
+      if (qualifier)
+	SwigType_push(this_type, qualifier);
+      SwigType_add_pointer(this_type);
+      Parm *this_parm = NewParm(this_type, name);
+      Swig_typemap_attach_parms("jtype", this_parm, NULL);
+      Swig_typemap_attach_parms("jstype", this_parm, NULL);
+
+      if (prematureGarbageCollectionPreventionParameter(this_type, this_parm))
+	Printf(imcall, ", this");
+
+      Delete(this_parm);
+      Delete(name);
+      Delete(this_type);
+    }
+
+    emit_mark_varargs(l);
+
+    int gencomma = !static_flag;
+
+    /* Output each parameter */
+    for (i = 0, p = l; p; i++) {
+
+      /* Ignored varargs */
+      if (checkAttribute(p, "varargs:ignore", "1")) {
+	p = nextSibling(p);
+	continue;
+      }
+
+      /* Ignored parameters */
+      if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      }
+
+      /* Ignore the 'this' argument for variable wrappers */
+      if (!(variable_wrapper_flag && i == 0) || static_flag) {
+	SwigType *pt = Getattr(p, "type");
+	String *param_type = NewString("");
+
+	/* Get the Java parameter type */
+	if ((tm = Getattr(p, "tmap:jstype"))) {
+	  substituteClassname(pt, tm);
+	  Printf(param_type, "%s", tm);
+	} else {
+	  Swig_warning(WARN_JAVA_TYPEMAP_JSTYPE_UNDEF, input_file, line_number, "No jstype typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	if (gencomma)
+	  Printf(imcall, ", ");
+
+	String *arg = makeParameterName(n, p, i, setter_flag);
+
+	// Use typemaps to transform type used in Java proxy wrapper (in proxy class) to type used in JNI function (in intermediary class)
+	if ((tm = Getattr(p, "tmap:javain"))) {
+	  addThrows(n, "tmap:javain", p);
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$javainput", arg);
+          String *pre = Getattr(p, "tmap:javain:pre");
+          if (pre) {
+            substituteClassname(pt, pre);
+            Replaceall(pre, "$javainput", arg);
+            if (Len(pre_code) > 0)
+              Printf(pre_code, "\n");
+            Printv(pre_code, pre, NIL);
+          }
+          String *post = Getattr(p, "tmap:javain:post");
+          if (post) {
+            substituteClassname(pt, post);
+            Replaceall(post, "$javainput", arg);
+            if (Len(post_code) > 0)
+              Printf(post_code, "\n");
+            Printv(post_code, post, NIL);
+          }
+	  Printv(imcall, tm, NIL);
+	} else {
+	  Swig_warning(WARN_JAVA_TYPEMAP_JAVAIN_UNDEF, input_file, line_number, "No javain typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	/* Add parameter to proxy function */
+	if (gencomma >= 2)
+	  Printf(function_code, ", ");
+	gencomma = 2;
+	Printf(function_code, "%s %s", param_type, arg);
+
+	if (prematureGarbageCollectionPreventionParameter(pt, p)) {
+          String *pgcppname = Getattr(p, "tmap:javain:pgcppname");
+          if (pgcppname) {
+            String *argname = Copy(pgcppname);
+            Replaceall(argname, "$javainput", arg);
+            Printf(imcall, ", %s", argname);
+            Delete(argname);
+          } else {
+            Printf(imcall, ", %s", arg);
+          }
+        }
+
+	Delete(arg);
+	Delete(param_type);
+      }
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    Printf(imcall, ")");
+    Printf(function_code, ")");
+
+    // Transform return type used in JNI function (in intermediary class) to type used in Java wrapper function (in proxy class)
+    if ((tm = Swig_typemap_lookup("javaout", n, "", 0))) {
+      addThrows(n, "tmap:javaout", n);
+      bool is_pre_code = Len(pre_code) > 0;
+      bool is_post_code = Len(post_code) > 0;
+      if (is_pre_code || is_post_code) {
+        Replaceall(tm, "\n ", "\n   "); // add extra indentation to code in typemap
+        if (is_post_code) {
+          Insert(tm, 0, "\n    try ");
+          Printv(tm, " finally {\n", post_code, "\n    }", NIL);
+        } else {
+          Insert(tm, 0, "\n    ");
+        }
+        if (is_pre_code) {
+          Insert(tm, 0, pre_code);
+          Insert(tm, 0, "\n");
+        }
+	Insert(tm, 0, "{");
+	Printf(tm, "\n  }");
+      }
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "true");
+      else
+	Replaceall(tm, "$owner", "false");
+      substituteClassname(t, tm);
+
+      // For director methods: generate code to selectively make a normal polymorphic call or 
+      // an explicit method call - needed to prevent infinite recursion calls in director methods.
+      Node *explicit_n = Getattr(n, "explicitcallnode");
+      if (explicit_n) {
+	String *ex_overloaded_name = getOverloadedName(explicit_n);
+	String *ex_intermediary_function_name = Swig_name_member(proxy_class_name, ex_overloaded_name);
+
+	String *ex_imcall = Copy(imcall);
+	Replaceall(ex_imcall, "$imfuncname", ex_intermediary_function_name);
+	Replaceall(imcall, "$imfuncname", intermediary_function_name);
+
+	String *excode = NewString("");
+	if (!Cmp(return_type, "void"))
+	  Printf(excode, "if (getClass() == %s.class) %s; else %s", proxy_class_name, imcall, ex_imcall);
+	else
+	  Printf(excode, "(getClass() == %s.class) ? %s : %s", proxy_class_name, imcall, ex_imcall);
+
+	Clear(imcall);
+	Printv(imcall, excode, NIL);
+	Delete(ex_overloaded_name);
+	Delete(excode);
+      } else {
+	Replaceall(imcall, "$imfuncname", intermediary_function_name);
+      }
+
+      Replaceall(tm, "$jnicall", imcall);
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JAVAOUT_UNDEF, input_file, line_number, "No javaout typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    generateThrowsClause(n, function_code);
+    Printf(function_code, " %s\n\n", tm ? (const String *) tm : empty_string);
+    Printv(proxy_class_code, function_code, NIL);
+
+    Delete(pre_code);
+    Delete(post_code);
+    Delete(function_code);
+    Delete(return_type);
+    Delete(imcall);
+  }
+
+  /* ----------------------------------------------------------------------
+   * constructorHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int constructorHandler(Node *n) {
+
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    Parm *p;
+    int i;
+    String *function_code = NewString("");
+    String *helper_code = NewString(""); // Holds code for the constructor helper method generated only when the javain typemap has code in the pre or post attributes
+    String *helper_args = NewString("");
+    String *pre_code = NewString("");
+    String *post_code = NewString("");
+    String *im_return_type = NewString("");
+    bool feature_director = (parentNode(n) && Swig_directorclass(n));
+
+    Language::constructorHandler(n);
+
+    // Wrappers not wanted for some methods where the parameters cannot be overloaded in Java
+    if (Getattr(n, "overload:ignore"))
+      return SWIG_OK;
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *mangled_overname = Swig_name_construct(overloaded_name);
+      String *imcall = NewString("");
+
+      const String *methodmods = Getattr(n, "feature:java:methodmodifiers");
+      methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+
+      tm = Getattr(n, "tmap:jtype"); // typemaps were attached earlier to the node
+      Printf(im_return_type, "%s", tm);
+
+      Printf(function_code, "  %s %s(", methodmods, proxy_class_name);
+      Printf(helper_code, "  static private %s SwigConstruct%s(", im_return_type, proxy_class_name);
+
+      Printv(imcall, imclass_name, ".", mangled_overname, "(", NIL);
+
+      /* Attach the non-standard typemaps to the parameter list */
+      Swig_typemap_attach_parms("in", l, NULL);
+      Swig_typemap_attach_parms("jtype", l, NULL);
+      Swig_typemap_attach_parms("jstype", l, NULL);
+      Swig_typemap_attach_parms("javain", l, NULL);
+
+      emit_mark_varargs(l);
+
+      int gencomma = 0;
+
+      /* Output each parameter */
+      for (i = 0, p = l; p; i++) {
+
+	/* Ignored varargs */
+	if (checkAttribute(p, "varargs:ignore", "1")) {
+	  p = nextSibling(p);
+	  continue;
+	}
+
+	/* Ignored parameters */
+	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	  p = Getattr(p, "tmap:in:next");
+	  continue;
+	}
+
+	SwigType *pt = Getattr(p, "type");
+	String *param_type = NewString("");
+
+	/* Get the Java parameter type */
+	if ((tm = Getattr(p, "tmap:jstype"))) {
+	  substituteClassname(pt, tm);
+	  Printf(param_type, "%s", tm);
+	} else {
+	  Swig_warning(WARN_JAVA_TYPEMAP_JSTYPE_UNDEF, input_file, line_number, "No jstype typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	if (gencomma)
+	  Printf(imcall, ", ");
+
+	String *arg = makeParameterName(n, p, i, false);
+
+	// Use typemaps to transform type used in Java wrapper function (in proxy class) to type used in JNI function (in intermediary class)
+	if ((tm = Getattr(p, "tmap:javain"))) {
+	  addThrows(n, "tmap:javain", p);
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$javainput", arg);
+          String *pre = Getattr(p, "tmap:javain:pre");
+          if (pre) {
+            substituteClassname(pt, pre);
+            Replaceall(pre, "$javainput", arg);
+            if (Len(pre_code) > 0)
+              Printf(pre_code, "\n");
+            Printv(pre_code, pre, NIL);
+          }
+          String *post = Getattr(p, "tmap:javain:post");
+          if (post) {
+            substituteClassname(pt, post);
+            Replaceall(post, "$javainput", arg);
+            if (Len(post_code) > 0)
+              Printf(post_code, "\n");
+            Printv(post_code, post, NIL);
+          }
+	  Printv(imcall, tm, NIL);
+	} else {
+	  Swig_warning(WARN_JAVA_TYPEMAP_JAVAIN_UNDEF, input_file, line_number, "No javain typemap defined for %s\n", SwigType_str(pt, 0));
+	}
+
+	/* Add parameter to proxy function */
+	if (gencomma) {
+	  Printf(function_code, ", ");
+	  Printf(helper_code, ", ");
+	  Printf(helper_args, ", ");
+        }
+	Printf(function_code, "%s %s", param_type, arg);
+	Printf(helper_code, "%s %s", param_type, arg);
+	Printf(helper_args, "%s", arg);
+	++gencomma;
+
+	if (prematureGarbageCollectionPreventionParameter(pt, p)) {
+          String *pgcppname = Getattr(p, "tmap:javain:pgcppname");
+          if (pgcppname) {
+            String *argname = Copy(pgcppname);
+            Replaceall(argname, "$javainput", arg);
+            Printf(imcall, ", %s", argname);
+            Delete(argname);
+          } else {
+            Printf(imcall, ", %s", arg);
+          }
+        }
+
+	Delete(arg);
+	Delete(param_type);
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      Printf(imcall, ")");
+
+      Printf(function_code, ")");
+      Printf(helper_code, ")");
+      generateThrowsClause(n, function_code);
+
+      /* Insert the javaconstruct typemap, doing the replacement for $directorconnect, as needed */
+      Hash *attributes = NewHash();
+      String *construct_tm = Copy(typemapLookup("javaconstruct", Getattr(n, "name"),
+						WARN_JAVA_TYPEMAP_JAVACONSTRUCT_UNDEF, attributes));
+      if (construct_tm) {
+	if (!feature_director) {
+	  Replaceall(construct_tm, "$directorconnect", "");
+	} else {
+	  String *connect_attr = Getattr(attributes, "tmap:javaconstruct:directorconnect");
+
+	  if (connect_attr) {
+	    Replaceall(construct_tm, "$directorconnect", connect_attr);
+	  } else {
+	    Swig_warning(WARN_JAVA_NO_DIRECTORCONNECT_ATTR, input_file, line_number, "\"directorconnect\" attribute missing in %s \"javaconstruct\" typemap.\n",
+			 Getattr(n, "name"));
+	    Replaceall(construct_tm, "$directorconnect", "");
+	  }
+	}
+
+	Printv(function_code, " ", construct_tm, "\n", NIL);
+      }
+
+      bool is_pre_code = Len(pre_code) > 0;
+      bool is_post_code = Len(post_code) > 0;
+      if (is_pre_code || is_post_code) {
+        generateThrowsClause(n, helper_code);
+        Printf(helper_code, " {\n");
+        if (is_pre_code) {
+          Printv(helper_code, pre_code, "\n", NIL);
+        }
+        if (is_post_code) {
+          Printf(helper_code, "    try {\n");
+          Printv(helper_code, "      return ", imcall, ";\n", NIL);
+          Printv(helper_code, "    } finally {\n", post_code, "\n    }", NIL);
+        } else {
+          Printv(helper_code, "    return ", imcall, ";", NIL);
+        }
+        Printf(helper_code, "\n  }\n");
+        String *helper_name = NewStringf("%s.SwigConstruct%s(%s)", proxy_class_name, proxy_class_name, helper_args);
+        Printv(proxy_class_code, helper_code, "\n", NIL);
+        Replaceall(function_code, "$imcall", helper_name);
+        Delete(helper_name);
+      } else {
+        Replaceall(function_code, "$imcall", imcall);
+      }
+
+      Printv(proxy_class_code, function_code, "\n", NIL);
+
+      Delete(helper_args);
+      Delete(im_return_type);
+      Delete(pre_code);
+      Delete(post_code);
+      Delete(construct_tm);
+      Delete(attributes);
+      Delete(overloaded_name);
+      Delete(imcall);
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * destructorHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int destructorHandler(Node *n) {
+    Language::destructorHandler(n);
+    String *symname = Getattr(n, "sym:name");
+
+    if (proxy_flag) {
+      Printv(destructor_call, imclass_name, ".", Swig_name_destroy(symname), "(swigCPtr)", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * membervariableHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int membervariableHandler(Node *n) {
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    variable_wrapper_flag = true;
+    Language::membervariableHandler(n);
+    wrapping_member_flag = false;
+    variable_wrapper_flag = false;
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * staticmembervariableHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmembervariableHandler(Node *n) {
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    static_flag = true;
+    Language::staticmembervariableHandler(n);
+    wrapping_member_flag = false;
+    static_flag = false;
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberconstantHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int memberconstantHandler(Node *n) {
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    Language::memberconstantHandler(n);
+    wrapping_member_flag = false;
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getOverloadedName()
+   * ----------------------------------------------------------------------------- */
+
+  String *getOverloadedName(Node *n) {
+
+    /* Although JNI functions are designed to handle overloaded Java functions,
+     * a Java long is used for all classes in the SWIG intermediary class.
+     * The intermediary class methods are thus mangled when overloaded to give
+     * a unique name. */
+    String *overloaded_name = NewStringf("%s", Getattr(n, "sym:name"));
+
+    if (Getattr(n, "sym:overloaded")) {
+      Printv(overloaded_name, Getattr(n, "sym:overname"), NIL);
+    }
+
+    return overloaded_name;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * moduleClassFunctionHandler()
+   * ----------------------------------------------------------------------------- */
+
+  void moduleClassFunctionHandler(Node *n) {
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *tm;
+    Parm *p;
+    int i;
+    String *imcall = NewString("");
+    String *return_type = NewString("");
+    String *function_code = NewString("");
+    int num_arguments = 0;
+    int num_required = 0;
+    String *overloaded_name = getOverloadedName(n);
+    String *func_name = NULL;
+    bool setter_flag = false;
+    String *pre_code = NewString("");
+    String *post_code = NewString("");
+
+    if (l) {
+      if (SwigType_type(Getattr(l, "type")) == T_VOID) {
+	l = nextSibling(l);
+      }
+    }
+
+    /* Attach the non-standard typemaps to the parameter list */
+    Swig_typemap_attach_parms("jstype", l, NULL);
+    Swig_typemap_attach_parms("javain", l, NULL);
+
+    /* Get return types */
+    if ((tm = Swig_typemap_lookup("jstype", n, "", 0))) {
+      substituteClassname(t, tm);
+      Printf(return_type, "%s", tm);
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JSTYPE_UNDEF, input_file, line_number, "No jstype typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    /* Change function name for global variables */
+    if (proxy_flag && global_variable_flag) {
+      // Capitalize the first letter in the variable to create a JavaBean type getter/setter function name
+      func_name = NewString("");
+      setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(variable_name)) == 0);
+      if (setter_flag)
+	Printf(func_name, "set");
+      else
+	Printf(func_name, "get");
+      Putc(toupper((int) *Char(variable_name)), func_name);
+      Printf(func_name, "%s", Char(variable_name) + 1);
+    } else {
+      func_name = Copy(Getattr(n, "sym:name"));
+    }
+
+    /* Start generating the function */
+    const String *methodmods = Getattr(n, "feature:java:methodmodifiers");
+    methodmods = methodmods ? methodmods : (is_public(n) ? public_string : protected_string);
+    Printf(function_code, "  %s static %s %s(", methodmods, return_type, func_name);
+    Printv(imcall, imclass_name, ".", overloaded_name, "(", NIL);
+
+    /* Get number of required and total arguments */
+    num_arguments = emit_num_arguments(l);
+    num_required = emit_num_required(l);
+
+    bool global_or_member_variable = global_variable_flag || (wrapping_member_flag && !enum_constant_flag);
+    int gencomma = 0;
+
+    /* Output each parameter */
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      /* Ignored parameters */
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *param_type = NewString("");
+
+      /* Get the Java parameter type */
+      if ((tm = Getattr(p, "tmap:jstype"))) {
+	substituteClassname(pt, tm);
+	Printf(param_type, "%s", tm);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JSTYPE_UNDEF, input_file, line_number, "No jstype typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      if (gencomma)
+	Printf(imcall, ", ");
+
+      String *arg = makeParameterName(n, p, i, global_or_member_variable);
+
+      // Use typemaps to transform type used in Java wrapper function (in proxy class) to type used in JNI function (in intermediary class)
+      if ((tm = Getattr(p, "tmap:javain"))) {
+	addThrows(n, "tmap:javain", p);
+	substituteClassname(pt, tm);
+	Replaceall(tm, "$javainput", arg);
+	String *pre = Getattr(p, "tmap:javain:pre");
+	if (pre) {
+	  substituteClassname(pt, pre);
+	  Replaceall(pre, "$javainput", arg);
+          if (Len(pre_code) > 0)
+            Printf(pre_code, "\n");
+	  Printv(pre_code, pre, NIL);
+	}
+	String *post = Getattr(p, "tmap:javain:post");
+	if (post) {
+	  substituteClassname(pt, post);
+	  Replaceall(post, "$javainput", arg);
+          if (Len(post_code) > 0)
+            Printf(post_code, "\n");
+	  Printv(post_code, post, NIL);
+	}
+	Printv(imcall, tm, NIL);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JAVAIN_UNDEF, input_file, line_number, "No javain typemap defined for %s\n", SwigType_str(pt, 0));
+      }
+
+      /* Add parameter to module class function */
+      if (gencomma >= 2)
+	Printf(function_code, ", ");
+      gencomma = 2;
+      Printf(function_code, "%s %s", param_type, arg);
+
+      if (prematureGarbageCollectionPreventionParameter(pt, p)) {
+        String *pgcppname = Getattr(p, "tmap:javain:pgcppname");
+        if (pgcppname) {
+          String *argname = Copy(pgcppname);
+          Replaceall(argname, "$javainput", arg);
+          Printf(imcall, ", %s", argname);
+          Delete(argname);
+        } else {
+          Printf(imcall, ", %s", arg);
+        }
+      }
+
+      p = Getattr(p, "tmap:in:next");
+      Delete(arg);
+      Delete(param_type);
+    }
+
+    Printf(imcall, ")");
+    Printf(function_code, ")");
+
+    // Transform return type used in JNI function (in intermediary class) to type used in Java wrapper function (in module class)
+    if ((tm = Swig_typemap_lookup("javaout", n, "", 0))) {
+      addThrows(n, "tmap:javaout", n);
+      bool is_pre_code = Len(pre_code) > 0;
+      bool is_post_code = Len(post_code) > 0;
+      if (is_pre_code || is_post_code) {
+        Replaceall(tm, "\n ", "\n   "); // add extra indentation to code in typemap
+        if (is_post_code) {
+          Insert(tm, 0, "\n    try ");
+          Printv(tm, " finally {\n", post_code, "\n    }", NIL);
+        } else {
+          Insert(tm, 0, "\n    ");
+        }
+        if (is_pre_code) {
+          Insert(tm, 0, pre_code);
+          Insert(tm, 0, "\n");
+        }
+	Insert(tm, 0, "{");
+	Printf(tm, "\n  }");
+      }
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "true");
+      else
+	Replaceall(tm, "$owner", "false");
+      substituteClassname(t, tm);
+      Replaceall(tm, "$jnicall", imcall);
+    } else {
+      Swig_warning(WARN_JAVA_TYPEMAP_JAVAOUT_UNDEF, input_file, line_number, "No javaout typemap defined for %s\n", SwigType_str(t, 0));
+    }
+
+    generateThrowsClause(n, function_code);
+    Printf(function_code, " %s\n\n", tm ? (const String *) tm : empty_string);
+    Printv(module_class_code, function_code, NIL);
+
+    Delete(pre_code);
+    Delete(post_code);
+    Delete(function_code);
+    Delete(return_type);
+    Delete(imcall);
+    Delete(func_name);
+  }
+
+  /*----------------------------------------------------------------------
+   * decodeEnumFeature()
+   * Decode the possible enum features, which are one of:
+   *   %javaenum(simple)
+   *   %javaenum(typeunsafe) - default
+   *   %javaenum(typesafe)
+   *   %javaenum(proper)
+   *--------------------------------------------------------------------*/
+
+  EnumFeature decodeEnumFeature(Node *n) {
+    EnumFeature enum_feature = TypeunsafeEnum;
+    String *feature = Getattr(n, "feature:java:enum");
+    if (feature) {
+      if (Cmp(feature, "simple") == 0)
+	enum_feature = SimpleEnum;
+      else if (Cmp(feature, "typesafe") == 0)
+	enum_feature = TypesafeEnum;
+      else if (Cmp(feature, "proper") == 0)
+	enum_feature = ProperEnum;
+    }
+    return enum_feature;
+  }
+
+  /* -----------------------------------------------------------------------
+   * enumValue()
+   * This method will return a string with an enum value to use in Java generated
+   * code. If the %javaconst feature is not used, the string will contain the intermediary
+   * class call to obtain the enum value. The intermediary class and JNI methods to obtain
+   * the enum value will be generated. Otherwise the C/C++ enum value will be used if there
+   * is one and hopefully it will compile as Java code - e.g. 20 as in: enum E{e=20};
+   * The %javaconstvalue feature overrides all other ways to generate the constant value.
+   * The caller must delete memory allocated for the returned string.
+   * ------------------------------------------------------------------------ */
+
+  String *enumValue(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+
+    // Check for the %javaconstvalue feature
+    String *value = Getattr(n, "feature:java:constvalue");
+
+    if (!value) {
+      // The %javaconst feature determines how the constant value is obtained
+      int const_feature_flag = GetFlag(n, "feature:java:const");
+
+      if (const_feature_flag) {
+	// Use the C syntax to make a true Java constant and hope that it compiles as Java code
+	value = Getattr(n, "enumvalue") ? Copy(Getattr(n, "enumvalue")) : Copy(Getattr(n, "enumvalueex"));
+      } else {
+	// Get the enumvalue from a JNI call
+	if (!getCurrentClass() || !cparse_cplusplus || !proxy_flag) {
+	  // Strange hack to change the name
+	  Setattr(n, "name", Getattr(n, "value"));	/* for wrapping of enums in a namespace when emit_action is used */
+	  constantWrapper(n);
+	  value = NewStringf("%s.%s()", imclass_name, Swig_name_get(symname));
+	} else {
+	  memberconstantHandler(n);
+	  value = NewStringf("%s.%s()", imclass_name, Swig_name_get(Swig_name_member(proxy_class_name, symname)));
+	}
+      }
+    }
+    return value;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getEnumName()
+   *
+   * If jnidescriptor is set, inner class names are separated with '$' otherwise a '.'
+   * ----------------------------------------------------------------------------- */
+
+  String *getEnumName(SwigType *t, bool jnidescriptor) {
+    Node *enum_name = NULL;
+    Node *n = enumLookup(t);
+    if (n) {
+      String *symname = Getattr(n, "sym:name");
+      if (symname) {
+	// Add in class scope when referencing enum if not a global enum
+	String *scopename_prefix = Swig_scopename_prefix(Getattr(n, "name"));
+	String *proxyname = 0;
+	if (scopename_prefix) {
+	  proxyname = getProxyName(scopename_prefix);
+	}
+	if (proxyname) {
+	  const char *class_separator = jnidescriptor ? "$" : ".";
+	  enum_name = NewStringf("%s%s%s", proxyname, class_separator, symname);
+	} else {
+	  enum_name = NewStringf("%s", symname);
+	}
+	Delete(scopename_prefix);
+      }
+    }
+
+    return enum_name;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * substituteClassname()
+   *
+   * Substitute $javaclassname with the proxy class name for classes/structs/unions that SWIG knows about.
+   * Also substitutes enums with enum name.
+   * Otherwise use the $descriptor name for the Java class name. Note that the $&javaclassname substitution
+   * is the same as a $&descriptor substitution, ie one pointer added to descriptor name.
+   * Inputs:
+   *   pt - parameter type
+   *   tm - jstype typemap
+   *   jnidescriptor - if set, inner class names are separated with '$' otherwise a '.'
+   * Outputs:
+   *   tm - jstype typemap with $javaclassname substitution
+   * Return:
+   *   substitution_performed - flag indicating if a substitution was performed
+   * ----------------------------------------------------------------------------- */
+
+  bool substituteClassname(SwigType *pt, String *tm, bool jnidescriptor = false) {
+    bool substitution_performed = false;
+    SwigType *type = Copy(SwigType_typedef_resolve_all(pt));
+    SwigType *strippedtype = SwigType_strip_qualifiers(type);
+
+    if (Strstr(tm, "$javaclassname")) {
+      SwigType *classnametype = Copy(strippedtype);
+      substituteClassnameSpecialVariable(classnametype, tm, "$javaclassname", jnidescriptor);
+      substitution_performed = true;
+      Delete(classnametype);
+    }
+    if (Strstr(tm, "$*javaclassname")) {
+      SwigType *classnametype = Copy(strippedtype);
+      Delete(SwigType_pop(classnametype));
+      substituteClassnameSpecialVariable(classnametype, tm, "$*javaclassname", jnidescriptor);
+      substitution_performed = true;
+      Delete(classnametype);
+    }
+    if (Strstr(tm, "$&javaclassname")) {
+      SwigType *classnametype = Copy(strippedtype);
+      SwigType_add_pointer(classnametype);
+      substituteClassnameSpecialVariable(classnametype, tm, "$&javaclassname", jnidescriptor);
+      substitution_performed = true;
+      Delete(classnametype);
+    }
+
+    Delete(strippedtype);
+    Delete(type);
+
+    return substitution_performed;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * substituteClassnameSpecialVariable()
+   * ----------------------------------------------------------------------------- */
+
+  void substituteClassnameSpecialVariable(SwigType *classnametype, String *tm, const char *classnamespecialvariable, bool jnidescriptor) {
+    if (SwigType_isenum(classnametype)) {
+      String *enumname = getEnumName(classnametype, jnidescriptor);
+      if (enumname)
+	Replaceall(tm, classnamespecialvariable, enumname);
+      else
+	Replaceall(tm, classnamespecialvariable, NewStringf("int"));
+    } else {
+      String *classname = getProxyName(classnametype);
+      if (classname) {
+	Replaceall(tm, classnamespecialvariable, classname);	// getProxyName() works for pointers to classes too
+      } else {			// use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved.
+	String *descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(classnametype));
+	Replaceall(tm, classnamespecialvariable, descriptor);
+
+	// Add to hash table so that the type wrapper classes can be created later
+	Setattr(swig_types_hash, descriptor, classnametype);
+	Delete(descriptor);
+      }
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * makeParameterName()
+   *
+   * Inputs: 
+   *   n - Node
+   *   p - parameter node
+   *   arg_num - parameter argument number
+   *   setter  - set this flag when wrapping variables
+   * Return:
+   *   arg - a unique parameter name
+   * ----------------------------------------------------------------------------- */
+
+  String *makeParameterName(Node *n, Parm *p, int arg_num, bool setter) {
+
+    String *arg = 0;
+    String *pn = Getattr(p, "name");
+
+    // Use C parameter name unless it is a duplicate or an empty parameter name
+    int count = 0;
+    ParmList *plist = Getattr(n, "parms");
+    while (plist) {
+      if ((Cmp(pn, Getattr(plist, "name")) == 0))
+        count++;
+      plist = nextSibling(plist);
+    }
+    String *wrn = pn ? Swig_name_warning(p, 0, pn, 0) : 0;
+    arg = (!pn || (count > 1) || wrn) ? NewStringf("arg%d", arg_num) : Copy(pn);
+
+    if (setter && Cmp(arg, "self") != 0) {
+      // Note that for setters the parameter name is always set but sometimes includes C++ 
+      // scope resolution, so we need to strip off the scope resolution to make a valid name.
+      Delete(arg);
+      arg = NewString("value");	//Swig_scopename_last(pn);
+    }
+
+    return arg;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitTypeWrapperClass()
+   * ----------------------------------------------------------------------------- */
+
+  void emitTypeWrapperClass(String *classname, SwigType *type) {
+    String *swigtype = NewString("");
+    String *filen = NewStringf("%s%s.java", SWIG_output_directory(), classname);
+    File *f_swigtype = NewFile(filen, "w");
+    if (!f_swigtype) {
+      FileErrorDisplay(filen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Append(filenames_list, Copy(filen));
+    Delete(filen);
+    filen = NULL;
+
+    // Start writing out the type wrapper class file
+    emitBanner(f_swigtype);
+
+    if (Len(package) > 0)
+      Printf(f_swigtype, "package %s;\n", package);
+
+    // Pure Java baseclass and interfaces
+    const String *pure_baseclass = typemapLookup("javabase", type, WARN_NONE);
+    const String *pure_interfaces = typemapLookup("javainterfaces", type, WARN_NONE);
+
+    // Emit the class
+    Printv(swigtype, typemapLookup("javaimports", type, WARN_NONE),	// Import statements
+	   "\n", typemapLookup("javaclassmodifiers", type, WARN_JAVA_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers
+	   " $javaclassname",	// Class name and bases
+	   *Char(pure_baseclass) ? " extends " : "", pure_baseclass, *Char(pure_interfaces) ?	// Interfaces
+	   " implements " : "", pure_interfaces, " {", typemapLookup("javabody", type, WARN_JAVA_TYPEMAP_JAVABODY_UNDEF),	// main body of class
+	   typemapLookup("javacode", type, WARN_NONE),	// extra Java code
+	   "}\n", "\n", NIL);
+
+    Replaceall(swigtype, "$javaclassname", classname);
+    Replaceall(swigtype, "$module", module_class_name);
+    Replaceall(swigtype, "$imclassname", imclass_name);
+    Printv(f_swigtype, swigtype, NIL);
+
+    Close(f_swigtype);
+    Delete(swigtype);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * typemapLookup()
+   * ----------------------------------------------------------------------------- */
+
+  const String *typemapLookup(const String *op, String *type, int warning, Node *typemap_attributes = NULL) {
+    String *tm = NULL;
+    const String *code = NULL;
+
+    if ((tm = Swig_typemap_search(op, type, NULL, NULL))) {
+      code = Getattr(tm, "code");
+      if (typemap_attributes)
+	Swig_typemap_attach_kwargs(tm, op, typemap_attributes);
+    }
+
+    if (!code) {
+      code = empty_string;
+      if (warning != WARN_NONE)
+	Swig_warning(warning, input_file, line_number, "No %s typemap defined for %s\n", op, type);
+    }
+
+    return code ? code : empty_string;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * addThrows()
+   *
+   * Adds exception classes to a throws list. The throws list is the list of classes
+   * that will form the Java throws clause. Mainly for checked exceptions.
+   * ----------------------------------------------------------------------------- */
+
+  void addThrows(Node *n, const String *attribute, Node *parameter) {
+    // Get the comma separated exception classes for the throws clause - held in typemap/feature's "throws" attribute
+    String *throws_attribute = NewStringf("%s:throws", attribute);
+    String *throws = Getattr(parameter, throws_attribute);
+
+    if (throws) {
+      String *throws_list = Getattr(n, "java:throwslist");
+      if (!throws_list) {
+	throws_list = NewList();
+	Setattr(n, "java:throwslist", throws_list);
+      }
+      // Put the exception classes in the throws clause into a temporary List
+      List *temp_classes_list = Split(throws, ',', INT_MAX);
+
+      // Add the exception classes to the node throws list, but don't duplicate if already in list
+      if (temp_classes_list && Len(temp_classes_list) > 0) {
+	for (Iterator cls = First(temp_classes_list); cls.item; cls = Next(cls)) {
+	  String *exception_class = NewString(cls.item);
+	  Replaceall(exception_class, " ", "");	// remove spaces
+	  Replaceall(exception_class, "\t", "");	// remove tabs
+	  if (Len(exception_class) > 0) {
+	    // $javaclassname substitution
+	    SwigType *pt = Getattr(parameter, "type");
+	    substituteClassname(pt, exception_class);
+
+	    // Don't duplicate the Java exception class in the throws clause
+	    bool found_flag = false;
+	    for (Iterator item = First(throws_list); item.item; item = Next(item)) {
+	      if (Strcmp(item.item, exception_class) == 0)
+		found_flag = true;
+	    }
+	    if (!found_flag)
+	      Append(throws_list, exception_class);
+	  }
+	  Delete(exception_class);
+	}
+      }
+      Delete(temp_classes_list);
+    }
+    Delete(throws_attribute);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * generateThrowsClause()
+   *
+   * Generates throws clause for checked exception
+   * ----------------------------------------------------------------------------- */
+
+  void generateThrowsClause(Node *n, String *code) {
+    // Add the throws clause into code
+    List *throws_list = Getattr(n, "java:throwslist");
+    if (throws_list) {
+      Iterator cls = First(throws_list);
+      Printf(code, " throws %s", cls.item);
+      while ((cls = Next(cls)).item)
+	Printf(code, ", %s", cls.item);
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * prematureGarbageCollectionPreventionParameter()
+   *
+   * Get the proxy class name for use in an additional generated parameter. The
+   * additional parameter is added to a native method call purely to prevent 
+   * premature garbage collection of proxy classes which pass their C++ class pointer
+   * in a Java long to the JNI layer.
+   * ----------------------------------------------------------------------------- */
+
+  String *prematureGarbageCollectionPreventionParameter(SwigType *t, Parm *p) {
+    String *proxyClassName = 0;
+    String *jtype = NewString(Getattr(p, "tmap:jtype"));
+
+    // Strip C comments
+    String *stripped_jtype = Swig_strip_c_comments(jtype);
+    if (stripped_jtype) {
+      Delete(jtype);
+      jtype = stripped_jtype;
+    }
+
+    // Remove whitespace
+    Replaceall(jtype, " ", "");
+    Replaceall(jtype, "\t", "");
+
+    if (Cmp(jtype, "long") == 0) {
+      if (proxy_flag) {
+	if (!GetFlag(p, "tmap:jtype:nopgcpp") && !nopgcpp_flag) {
+          Node *n = classLookup(t);
+          if (n) {
+            // Found a struct/class parameter passed by value, reference, pointer, or pointer reference
+            proxyClassName = Getattr(n, "sym:name");
+          } else {
+            // Look for proxy class parameters passed to C++ layer using non-default typemaps, ie not one of above types
+            String *jstype = NewString(Getattr(p, "tmap:jstype"));
+            if (jstype) {
+              Hash *classes = getClassHash();
+              if (classes) {
+                // Strip C comments
+                String *stripped_jstype = Swig_strip_c_comments(jstype);
+                if (stripped_jstype) {
+                  Delete(jstype);
+                  jstype = stripped_jstype;
+                }
+                // Remove whitespace
+                Replaceall(jstype, " ", "");
+                Replaceall(jstype, "\t", "");
+
+                Iterator ki;
+                for (ki = First(classes); ki.key; ki = Next(ki)) {
+                  Node *cls = ki.item;
+                  if (cls && !Getattr(cls, "feature:ignore")) {
+                    String *symname = Getattr(cls, "sym:name");
+                    if (symname && Strcmp(symname, jstype) == 0) {
+                      proxyClassName = symname;
+                    }
+                  }
+                }
+              }
+            }
+            Delete(jstype);
+          }
+	}
+      }
+    }
+    Delete(jtype);
+    return proxyClassName;
+  }
+
+  /*----------------------------------------------------------------------
+   * Start of director methods
+   *--------------------------------------------------------------------*/
+
+  /*----------------------------------------------------------------------
+   * getUpcallJNIMethod()
+   *--------------------------------------------------------------------*/
+
+  String *getUpcallJNIMethod(String *descrip) {
+    static struct {
+      char code;
+      const char *method;
+    } upcall_methods[] = {
+      {
+      'B', "CallStaticByteMethod"}, {
+      'C', "CallStaticCharMethod"}, {
+      'D', "CallStaticDoubleMethod"}, {
+      'F', "CallStaticFloatMethod"}, {
+      'I', "CallStaticIntMethod"}, {
+      'J', "CallStaticLongMethod"}, {
+      'L', "CallStaticObjectMethod"}, {
+      'S', "CallStaticShortMethod"}, {
+      'V', "CallStaticVoidMethod"}, {
+      'Z', "CallStaticBooleanMethod"}, {
+      '[', "CallStaticObjectMethod"}
+    };
+
+    char code;
+    int i;
+
+    code = *Char(descrip);
+    for (i = 0; i < (int) (sizeof(upcall_methods) / sizeof(upcall_methods[0])); ++i)
+      if (code == upcall_methods[i].code)
+	return NewString(upcall_methods[i].method);
+    return NULL;
+  }
+
+  /*----------------------------------------------------------------------
+   * emitDirectorUpcalls()
+   *--------------------------------------------------------------------*/
+
+  void emitDirectorUpcalls() {
+    if (n_dmethods) {
+      Wrapper *w = NewWrapper();
+      String *jni_imclass_name = makeValidJniName(imclass_name);
+      String *swig_module_init = NewString("swig_module_init");
+      String *swig_module_init_jni = makeValidJniName(swig_module_init);
+      String *dmethod_data = NewString("");
+      int n_methods = 0;
+      Iterator udata_iter;
+
+      udata_iter = First(dmethods_seq);
+      while (udata_iter.item) {
+	UpcallData *udata = udata_iter.item;
+	Printf(dmethod_data, "  { \"%s\", \"%s\" }", Getattr(udata, "imclass_method"), Getattr(udata, "imclass_fdesc"));
+	++n_methods;
+
+	udata_iter = Next(udata_iter);
+
+	if (udata_iter.item)
+	  Putc(',', dmethod_data);
+	Putc('\n', dmethod_data);
+      }
+
+      Printf(f_runtime, "namespace Swig {\n");
+      Printf(f_runtime, "  static jclass jclass_%s = NULL;\n", imclass_name);
+      Printf(f_runtime, "  static jmethodID director_methids[%d];\n", n_methods);
+      Printf(f_runtime, "}\n");
+
+      Printf(w->def, "SWIGEXPORT void JNICALL Java_%s%s_%s(JNIEnv *jenv, jclass jcls) {", jnipackage, jni_imclass_name, swig_module_init_jni);
+      Printf(w->code, "static struct {\n");
+      Printf(w->code, "  const char *method;\n");
+      Printf(w->code, "  const char *signature;\n");
+      Printf(w->code, "} methods[%d] = {\n", n_methods);
+      Printv(w->code, dmethod_data, NIL);
+      Printf(w->code, "};\n");
+
+      Wrapper_add_local(w, "i", "int i");
+
+      Printf(w->code, "Swig::jclass_%s = (jclass) jenv->NewGlobalRef(jcls);\n", imclass_name);
+      Printf(w->code, "if (!Swig::jclass_%s) return;\n", imclass_name);
+      Printf(w->code, "for (i = 0; i < (int) (sizeof(methods)/sizeof(methods[0])); ++i) {\n");
+      Printf(w->code, "  Swig::director_methids[i] = jenv->GetStaticMethodID(jcls, methods[i].method, methods[i].signature);\n");
+      Printf(w->code, "  if (!Swig::director_methids[i]) return;\n");
+      Printf(w->code, "}\n");
+
+      Printf(w->code, "}\n");
+
+      Wrapper_print(w, f_wrappers);
+      Delete(dmethod_data);
+      Delete(swig_module_init_jni);
+      Delete(swig_module_init);
+      Delete(jni_imclass_name);
+      DelWrapper(w);
+    }
+  }
+
+  /*----------------------------------------------------------------------
+   * emitDirectorExtraMethods()
+   *
+   * This is where the $javaclassname_director_connect is
+   * generated.
+   *--------------------------------------------------------------------*/
+  void emitDirectorExtraMethods(Node *n) {
+    if (!Swig_directorclass(n))
+      return;
+
+    // Output the director connect method:
+    String *jni_imclass_name = makeValidJniName(imclass_name);
+    String *norm_name = SwigType_namestr(Getattr(n, "name"));
+    String *swig_director_connect = NewStringf("%s_director_connect", proxy_class_name);
+    String *swig_director_connect_jni = makeValidJniName(swig_director_connect);
+    String *sym_name = Getattr(n, "sym:name");
+    Wrapper *code_wrap;
+
+    Printf(imclass_class_code, "  public final static native void %s(%s obj, long cptr, boolean mem_own, boolean weak_global);\n",
+	   swig_director_connect, proxy_class_name);
+
+    code_wrap = NewWrapper();
+    Printf(code_wrap->def,
+	   "SWIGEXPORT void JNICALL Java_%s%s_%s(JNIEnv *jenv, jclass jcls, jobject jself, jlong objarg, jboolean jswig_mem_own, "
+	   "jboolean jweak_global) {\n", jnipackage, jni_imclass_name, swig_director_connect_jni);
+    Printf(code_wrap->code, "  %s *obj = *((%s **)&objarg);\n", norm_name, norm_name);
+    Printf(code_wrap->code, "  (void)jcls;\n");
+    Printf(code_wrap->code, "  SwigDirector_%s *director = dynamic_cast<SwigDirector_%s *>(obj);\n", sym_name, sym_name);
+    Printf(code_wrap->code, "  if (director) {\n");
+    Printf(code_wrap->code, "    director->swig_connect_director(jenv, jself, jenv->GetObjectClass(jself), "
+	   "(jswig_mem_own == JNI_TRUE), (jweak_global == JNI_TRUE));\n");
+    Printf(code_wrap->code, "  }\n");
+    Printf(code_wrap->code, "}\n");
+
+    Wrapper_print(code_wrap, f_wrappers);
+    DelWrapper(code_wrap);
+
+    Delete(swig_director_connect_jni);
+    Delete(swig_director_connect);
+
+    // Output the swigReleaseOwnership, swigTakeOwnership methods:
+    String *changeown_method_name = NewStringf("%s_change_ownership", proxy_class_name);
+    String *changeown_jnimethod_name = makeValidJniName(changeown_method_name);
+
+    Printf(imclass_class_code, "  public final static native void %s(%s obj, long cptr, boolean take_or_release);\n", changeown_method_name, proxy_class_name);
+
+    code_wrap = NewWrapper();
+    Printf(code_wrap->def,
+	   "SWIGEXPORT void JNICALL Java_%s%s_%s(JNIEnv *jenv, jclass jcls, jobject jself, jlong objarg, jboolean jtake_or_release) {\n",
+	   jnipackage, jni_imclass_name, changeown_jnimethod_name);
+    Printf(code_wrap->code, "  %s *obj = *((%s **)&objarg);\n", norm_name, norm_name);
+    Printf(code_wrap->code, "  SwigDirector_%s *director = dynamic_cast<SwigDirector_%s *>(obj);\n", sym_name, sym_name);
+    Printf(code_wrap->code, "  (void)jcls;\n");
+    Printf(code_wrap->code, "  if (director) {\n");
+    Printf(code_wrap->code, "    director->swig_java_change_ownership(jenv, jself, jtake_or_release ? true : false);\n");
+    Printf(code_wrap->code, "  }\n");
+    Printf(code_wrap->code, "}\n");
+
+    Wrapper_print(code_wrap, f_wrappers);
+    DelWrapper(code_wrap);
+
+    Delete(changeown_method_name);
+    Delete(changeown_jnimethod_name);
+    Delete(norm_name);
+    Delete(jni_imclass_name);
+  }
+
+  /*----------------------------------------------------------------------
+   * emitCodeTypemap()
+   *
+   * Output a code typemap that uses $methodname and $jnicall, as used
+   * in the directordisconnect, director_release and director_take
+   * typemaps.
+   *--------------------------------------------------------------------*/
+
+  void
+   emitCodeTypemap(bool derived, String *lookup_type, const String *typemap, const String *methodname, const String *jnicall) {
+    const String *tm = NULL;
+    Node *tmattrs = NewHash();
+    String *lookup_tmname = NewString(typemap);
+    String *method_attr_name;
+    String *method_attr;
+
+    if (derived) {
+      Append(lookup_tmname, "_derived");
+    }
+
+    tm = typemapLookup(lookup_tmname, lookup_type, WARN_NONE, tmattrs);
+    method_attr_name = NewStringf("tmap:%s:%s", lookup_tmname, methodname);
+    method_attr = Getattr(tmattrs, method_attr_name);
+
+    if (*Char(tm)) {
+      if (method_attr) {
+	String *codebody = Copy(tm);
+	Replaceall(codebody, "$methodname", method_attr);
+	Replaceall(codebody, "$jnicall", jnicall);
+	Append(proxy_class_def, codebody);
+	Delete(codebody);
+      } else {
+	Swig_error(input_file, line_number, "No %s method name attribute for %s\n", lookup_tmname, proxy_class_name);
+      }
+    } else {
+      Swig_error(input_file, line_number, "No %s typemap for %s\n", lookup_tmname, proxy_class_name);
+    }
+
+    Delete(tmattrs);
+    Delete(lookup_tmname);
+    // Delete(method_attr);
+  }
+
+  /* ---------------------------------------------------------------
+   * Canonicalize the JNI field descriptor
+   *
+   * Replace the $javapackage and $javaclassname family of special
+   * variables with the desired package and Java proxy name as 
+   * required in the JNI field descriptors.
+   * 
+   * !!SFM!! If $packagepath occurs in the field descriptor, but
+   * package_path isn't set (length == 0), then strip it and the
+   * optional trailing '/' from the resulting name.
+   * 
+   * --------------------------------------------------------------- */
+
+  String *canonicalizeJNIDescriptor(String *descriptor_in, Parm *p) {
+    String *pkg_path = Swig_typemap_lookup("javapackage", p, "", 0);
+    SwigType *type = Getattr(p, "type");
+
+    if (pkg_path && Len(pkg_path) != 0) {
+      Replaceall(pkg_path, ".", "/");
+    } else
+      pkg_path = package_path;
+
+    String *descriptor_out = Copy(descriptor_in);
+
+    if (Len(pkg_path) > 0) {
+      Replaceall(descriptor_out, "$packagepath", pkg_path);
+    } else {
+      Replaceall(descriptor_out, "$packagepath/", empty_string);
+      Replaceall(descriptor_out, "$packagepath", empty_string);
+    }
+
+    substituteClassname(type, descriptor_out, true);
+
+    if (pkg_path != package_path)
+      Delete(pkg_path);
+
+    return descriptor_out;
+  }
+
+  /* ---------------------------------------------------------------
+   * classDirectorMethod()
+   *
+   * Emit a virtual director method to pass a method call on to the 
+   * underlying Java object.
+   *
+   * --------------------------------------------------------------- */
+
+  int classDirectorMethod(Node *n, Node *parent, String *super) {
+    String *empty_str = NewString("");
+    String *classname = Getattr(parent, "sym:name");
+    String *c_classname = Getattr(parent, "name");
+    String *name = Getattr(n, "name");
+    String *symname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    SwigType *returntype = Getattr(n, "returntype");
+    String *overloaded_name = getOverloadedName(n);
+    String *storage = Getattr(n, "storage");
+    String *value = Getattr(n, "value");
+    String *decl = Getattr(n, "decl");
+    String *declaration = NewString("");
+    String *tm;
+    Parm *p;
+    int i;
+    Wrapper *w = NewWrapper();
+    ParmList *l = Getattr(n, "parms");
+    bool is_void = !(Cmp(returntype, "void"));
+    String *qualified_return = NewString("");
+    bool pure_virtual = (!(Cmp(storage, "virtual")) && !(Cmp(value, "0")));
+    int status = SWIG_OK;
+    bool output_director = true;
+    String *dirclassname = directorClassName(parent);
+    String *qualified_name = NewStringf("%s::%s", dirclassname, name);
+    String *jnidesc = NewString("");
+    String *classdesc = NewString("");
+    String *jniret_desc = NewString("");
+    String *classret_desc = NewString("");
+    SwigType *c_ret_type = NULL;
+    String *jupcall_args = NewString("swigjobj");
+    String *imclass_dmethod;
+    String *callback_def = NewString("");
+    String *callback_code = NewString("");
+    String *imcall_args = NewString("");
+    int gencomma = 0;
+    int classmeth_off = curr_class_dmethod - first_class_dmethod;
+    bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
+
+    // Kludge Alert: functionWrapper sets sym:overload properly, but it
+    // isn't at this point, so we have to manufacture it ourselves. At least
+    // we're consistent with the sym:overload name in functionWrapper. (?? when
+    // does the overloaded method name get set?)
+
+    imclass_dmethod = NewStringf("SwigDirector_%s", Swig_name_member(classname, overloaded_name));
+
+    if (returntype) {
+
+      qualified_return = SwigType_rcaststr(returntype, "c_result");
+
+      if (!is_void && (!ignored_method || pure_virtual)) {
+	if (!SwigType_isclass(returntype)) {
+	  if (!(SwigType_ispointer(returntype) || SwigType_isreference(returntype))) {
+            String *construct_result = NewStringf("= SwigValueInit< %s >()", SwigType_lstr(returntype, 0));
+	    Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), construct_result, NIL);
+            Delete(construct_result);
+	  } else {
+	    String *base_typename = SwigType_base(returntype);
+	    String *resolved_typename = SwigType_typedef_resolve_all(base_typename);
+	    Symtab *symtab = Getattr(n, "sym:symtab");
+	    Node *typenode = Swig_symbol_clookup(resolved_typename, symtab);
+
+	    if (SwigType_ispointer(returntype) || (typenode && Getattr(typenode, "abstract"))) {
+	      /* initialize pointers to something sane. Same for abstract
+	         classes when a reference is returned. */
+	      Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), "= 0", NIL);
+	    } else {
+	      /* If returning a reference, initialize the pointer to a sane
+	         default - if a Java exception occurs, then the pointer returns
+	         something other than a NULL-initialized reference. */
+	      String *non_ref_type = Copy(returntype);
+
+	      /* Remove reference and const qualifiers */
+	      Replaceall(non_ref_type, "r.", "");
+	      Replaceall(non_ref_type, "q(const).", "");
+	      Wrapper_add_localv(w, "result_default", "static", SwigType_str(non_ref_type, "result_default"), "=", SwigType_str(non_ref_type, "()"), NIL);
+	      Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), "= &result_default", NIL);
+
+	      Delete(non_ref_type);
+	    }
+
+	    Delete(base_typename);
+	    Delete(resolved_typename);
+	  }
+	} else {
+	  SwigType *vt;
+
+	  vt = cplus_value_type(returntype);
+	  if (!vt) {
+	    Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), NIL);
+	  } else {
+	    Wrapper_add_localv(w, "c_result", SwigType_lstr(vt, "c_result"), NIL);
+	    Delete(vt);
+	  }
+	}
+      }
+
+      /* Create the intermediate class wrapper */
+      Parm *tp = NewParmFromNode(returntype, empty_str, n);
+
+      tm = Swig_typemap_lookup("jtype", tp, "", 0);
+      if (tm) {
+	Printf(callback_def, "  public static %s %s(%s self", tm, imclass_dmethod, classname);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JTYPE_UNDEF, input_file, line_number, "No jtype typemap defined for %s\n", SwigType_str(returntype, 0));
+      }
+
+      String *cdesc = NULL;
+      SwigType *covariant = Getattr(n, "covariant");
+      SwigType *adjustedreturntype = covariant ? covariant : returntype;
+      Parm *adjustedreturntypeparm = NewParmFromNode(adjustedreturntype, empty_str, n);
+
+      if ((tm = Swig_typemap_lookup("directorin", adjustedreturntypeparm, "", 0))
+	  && (cdesc = Getattr(adjustedreturntypeparm, "tmap:directorin:descriptor"))) {
+
+	// Note that in the case of polymorphic (covariant) return types, the
+	// method's return type is changed to be the base of the C++ return
+	// type
+	String *jnidesc_canon = canonicalizeJNIDescriptor(cdesc, adjustedreturntypeparm);
+	Append(classret_desc, jnidesc_canon);
+	Delete(jnidesc_canon);
+      } else {
+	Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, "No or improper directorin typemap defined for %s\n", SwigType_str(returntype, 0));
+	output_director = false;
+      }
+
+      /* Get the JNI field descriptor for this return type, add the JNI field descriptor
+         to jniret_desc */
+
+      Parm *retpm = NewParmFromNode(returntype, empty_str, n);
+
+      if ((c_ret_type = Swig_typemap_lookup("jni", retpm, "", 0))) {
+	Parm *tp = NewParmFromNode(c_ret_type, empty_str, n);
+
+	if (!is_void && !ignored_method) {
+	  String *jretval_decl = NewStringf("%s jresult", c_ret_type);
+	  Wrapper_add_localv(w, "jresult", jretval_decl, "= 0", NIL);
+	  Delete(jretval_decl);
+	}
+
+	String *jdesc = NULL;
+	if ((tm = Swig_typemap_lookup("directorin", tp, "", 0))
+	    && (jdesc = Getattr(tp, "tmap:directorin:descriptor"))) {
+
+	  // Objects marshalled passing a Java class across JNI boundary use jobject - the nouse flag indicates this
+	  // We need the specific Java class name instead of the generic 'Ljava/lang/Object;'
+	  if (GetFlag(tp, "tmap:directorin:nouse"))
+	    jdesc = cdesc;
+	  String *jnidesc_canon = canonicalizeJNIDescriptor(jdesc, tp);
+	  Append(jniret_desc, jnidesc_canon);
+	  Delete(jnidesc_canon);
+	} else {
+	  Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
+		       "No or improper directorin typemap defined for %s\n", SwigType_str(c_ret_type, 0));
+	  output_director = false;
+	}
+
+	Delete(tp);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JNI_UNDEF, input_file, line_number, "No jni typemap defined for %s\n", SwigType_str(returntype, 0));
+	output_director = false;
+      }
+
+      Delete(adjustedreturntypeparm);
+      Delete(retpm);
+    }
+
+    /* Go through argument list, attach lnames for arguments */
+    for (i = 0, p = l; p; p = nextSibling(p), ++i) {
+      String *arg = Getattr(p, "name");
+      String *lname = NewString("");
+
+      if (!arg && Cmp(Getattr(p, "type"), "void")) {
+	lname = NewStringf("arg%d", i);
+	Setattr(p, "name", lname);
+      } else
+	lname = arg;
+
+      Setattr(p, "lname", lname);
+    }
+
+    /* Attach the standard typemaps */
+    Swig_typemap_attach_parms("out", l, 0);
+    Swig_typemap_attach_parms("jni", l, 0);
+    Swig_typemap_attach_parms("jtype", l, 0);
+    Swig_typemap_attach_parms("directorin", l, 0);
+    Swig_typemap_attach_parms("javadirectorin", l, 0);
+
+    if (!ignored_method) {
+      /* Add Java environment pointer to wrapper */
+      String *jenvstr = NewString("jenv");
+      String *jobjstr = NewString("swigjobj");
+
+      Wrapper_add_localv(w, "swigjnienv", "JNIEnvWrapper", "swigjnienv(this)", NIL, NIL);
+      Wrapper_add_localv(w, jenvstr, "JNIEnv *", jenvstr, "= swigjnienv.getJNIEnv()", NIL);
+      Wrapper_add_localv(w, jobjstr, "jobject", jobjstr, "= (jobject) NULL", NIL);
+      Delete(jenvstr);
+      Delete(jobjstr);
+
+      /* Preamble code */
+      Printf(w->code, "if (!swig_override[%d]) {\n", classmeth_off);
+    }
+
+    if (!pure_virtual) {
+      String *super_call = Swig_method_call(super, l);
+      if (is_void) {
+	Printf(w->code, "%s;\n", super_call);
+	if (!ignored_method)
+	  Printf(w->code, "return;\n");
+      } else {
+	Printf(w->code, "return %s;\n", super_call);
+      }
+      Delete(super_call);
+    } else {
+      Printf(w->code, "SWIG_JavaThrowException(JNIEnvWrapper(this).getJNIEnv(), SWIG_JavaDirectorPureVirtual, ");
+      Printf(w->code, "\"Attempted to invoke pure virtual method %s::%s.\");\n", SwigType_namestr(c_classname), SwigType_namestr(name));
+
+      /* Make sure that we return something in the case of a pure
+       * virtual method call for syntactical reasons. */
+      if (!is_void)
+	Printf(w->code, "return %s;", qualified_return);
+      else if (!ignored_method)
+	Printf(w->code, "return;\n");
+    }
+
+    if (!ignored_method) {
+      Printf(w->code, "}\n");
+      Printf(w->code, "swigjobj = swig_get_self(jenv);\n");
+      Printf(w->code, "if (swigjobj && jenv->IsSameObject(swigjobj, NULL) == JNI_FALSE) {\n");
+    }
+
+    /* Start the Java field descriptor for the intermediate class's upcall (insert self object) */
+    Parm *tp = NewParmFromNode(c_classname, empty_str, n);
+    String *jdesc;
+
+    if ((tm = Swig_typemap_lookup("directorin", tp, "", 0))
+	&& (jdesc = Getattr(tp, "tmap:directorin:descriptor"))) {
+      String *jni_canon = canonicalizeJNIDescriptor(jdesc, tp);
+      Append(jnidesc, jni_canon);
+      Delete(jni_canon);
+      Delete(tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
+		   "No or improper directorin typemap for type %s used in director method %s::%s\n", SwigType_str(type, 0), SwigType_namestr(c_classname),
+		   SwigType_namestr(name));
+      output_director = false;
+    }
+
+    Delete(tp);
+
+    /* Go through argument list, convert from native to Java */
+    for (p = l; p; /* empty */ ) {
+      /* Is this superfluous? */
+      while (checkAttribute(p, "tmap:directorin:numinputs", "0")) {
+	p = Getattr(p, "tmap:directorin:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Copy(Getattr(p, "name"));
+      String *c_param_type = NULL;
+      String *c_decl = NewString("");
+      String *arg = NewString("");
+
+      Printf(arg, "j%s", ln);
+
+      /* Add various typemap's 'throws' clauses */
+      addThrows(n, "tmap:directorin", p);
+      addThrows(n, "tmap:out", p);
+
+      /* And add to the upcall args */
+      Printf(jupcall_args, ", %s", arg);
+
+      /* Get parameter's intermediary C type */
+      if ((c_param_type = Getattr(p, "tmap:jni"))) {
+	Parm *tp = NewParmFromNode(c_param_type, empty_str, n);
+	String *desc_tm = NULL, *jdesc = NULL, *cdesc = NULL;
+
+	/* Add to local variables */
+	Printf(c_decl, "%s %s", c_param_type, arg);
+	if (!ignored_method)
+	  Wrapper_add_localv(w, arg, c_decl, (!(SwigType_ispointer(pt) || SwigType_isreference(pt)) ? "" : "= 0"), NIL);
+
+	/* Add input marshalling code and update JNI field descriptor */
+	if ((desc_tm = Swig_typemap_lookup("directorin", tp, "", 0))
+	    && (jdesc = Getattr(tp, "tmap:directorin:descriptor"))
+	    && (tm = Getattr(p, "tmap:directorin"))
+	    && (cdesc = Getattr(p, "tmap:directorin:descriptor"))) {
+
+	  // Objects marshalled by passing a Java class across the JNI boundary use jobject as the JNI type - 
+	  // the nouse flag indicates this. We need the specific Java class name instead of the generic 'Ljava/lang/Object;'
+	  if (GetFlag(tp, "tmap:directorin:nouse"))
+	    jdesc = cdesc;
+	  String *jni_canon = canonicalizeJNIDescriptor(jdesc, tp);
+	  Append(jnidesc, jni_canon);
+	  Delete(jni_canon);
+
+	  Replaceall(tm, "$input", arg);
+	  Replaceall(tm, "$owner", "0");
+
+	  if (Len(tm))
+	    if (!ignored_method)
+	      Printf(w->code, "%s\n", tm);
+
+	  Delete(tm);
+
+	  /* Add parameter to the intermediate class code if generating the
+	   * intermediate's upcall code */
+	  if ((tm = Getattr(p, "tmap:jtype"))) {
+	    String *din = Copy(Getattr(p, "tmap:javadirectorin"));
+            addThrows(n, "tmap:javadirectorin", p);
+
+	    if (din) {
+	      Replaceall(din, "$module", module_class_name);
+	      Replaceall(din, "$imclassname", imclass_name);
+	      substituteClassname(pt, din);
+	      Replaceall(din, "$jniinput", ln);
+
+	      if (++gencomma > 1)
+		Printf(imcall_args, ", ");
+	      Printf(callback_def, ", %s %s", tm, ln);
+
+	      if (Cmp(din, ln)) {
+		Printv(imcall_args, din, NIL);
+	      } else
+		Printv(imcall_args, ln, NIL);
+
+	      jni_canon = canonicalizeJNIDescriptor(cdesc, p);
+	      Append(classdesc, jni_canon);
+	      Delete(jni_canon);
+	    } else {
+	      Swig_warning(WARN_JAVA_TYPEMAP_JAVADIRECTORIN_UNDEF, input_file, line_number, "No javadirectorin typemap defined for %s\n", SwigType_str(pt, 0));
+	      output_director = false;
+	    }
+	  } else {
+	    Swig_warning(WARN_JAVA_TYPEMAP_JTYPE_UNDEF, input_file, line_number, "No jtype typemap defined for %s\n", SwigType_str(pt, 0));
+	    output_director = false;
+	  }
+
+	  p = Getattr(p, "tmap:directorin:next");
+
+	  Delete(desc_tm);
+	} else {
+	  if (!desc_tm) {
+	    Swig_warning(WARN_JAVA_TYPEMAP_JAVADIRECTORIN_UNDEF, input_file, line_number,
+			 "No or improper directorin typemap defined for %s\n", SwigType_str(c_param_type, 0));
+	    p = nextSibling(p);
+	  } else if (!jdesc) {
+	    Swig_warning(WARN_JAVA_TYPEMAP_DIRECTORIN_NODESC, input_file, line_number,
+			 "Missing JNI descriptor in directorin typemap defined for %s\n", SwigType_str(c_param_type, 0));
+	    p = Getattr(p, "tmap:directorin:next");
+	  } else if (!tm) {
+	    Swig_warning(WARN_JAVA_TYPEMAP_JAVADIRECTORIN_UNDEF, input_file, line_number,
+			 "No or improper directorin typemap defined for argument %s\n", SwigType_str(pt, 0));
+	    p = nextSibling(p);
+	  } else if (!cdesc) {
+	    Swig_warning(WARN_JAVA_TYPEMAP_DIRECTORIN_NODESC, input_file, line_number,
+			 "Missing JNI descriptor in directorin typemap defined for %s\n", SwigType_str(pt, 0));
+	    p = Getattr(p, "tmap:directorin:next");
+	  }
+
+	  output_director = false;
+	}
+
+	Delete(tp);
+      } else {
+	Swig_warning(WARN_JAVA_TYPEMAP_JNI_UNDEF, input_file, line_number, "No jni typemap defined for %s\n", SwigType_str(pt, 0));
+	output_director = false;
+	p = nextSibling(p);
+      }
+
+      Delete(arg);
+      Delete(c_decl);
+      Delete(c_param_type);
+    }
+
+    /* header declaration, start wrapper definition */
+    String *target;
+    SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type;
+    target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0);
+    Printf(w->def, "%s", target);
+    Delete(qualified_name);
+    Delete(target);
+    target = Swig_method_decl(rtype, decl, name, l, 0, 1);
+    Printf(declaration, "    virtual %s", target);
+    Delete(target);
+
+    // Get any Java exception classes in the throws typemap
+    ParmList *throw_parm_list = NULL;
+
+    if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) {
+      int gencomma = 0;
+
+      Append(w->def, " throw(");
+      Append(declaration, " throw(");
+
+      if (throw_parm_list)
+	Swig_typemap_attach_parms("throws", throw_parm_list, 0);
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	if ((tm = Getattr(p, "tmap:throws"))) {
+	  addThrows(n, "tmap:throws", p);
+
+	  if (gencomma++) {
+	    Append(w->def, ", ");
+	    Append(declaration, ", ");
+	  }
+
+	  Printf(w->def, "%s", SwigType_str(Getattr(p, "type"), 0));
+	  Printf(declaration, "%s", SwigType_str(Getattr(p, "type"), 0));
+	}
+      }
+
+      Append(w->def, ")");
+      Append(declaration, ")");
+    }
+
+    Append(w->def, " {");
+    Append(declaration, ";\n");
+
+    /* Emit the intermediate class's upcall to the actual class */
+
+    String *upcall = NewStringf("self.%s(%s)", symname, imcall_args);
+
+    if (!is_void) {
+      Parm *tp = NewParmFromNode(returntype, empty_str, n);
+
+      if ((tm = Swig_typemap_lookup("javadirectorout", tp, "", 0))) {
+        addThrows(n, "tmap:javadirectorout", tp);
+	substituteClassname(returntype, tm);
+	Replaceall(tm, "$javacall", upcall);
+
+	Printf(callback_code, "    return %s;\n", tm);
+      }
+
+      if ((tm = Swig_typemap_lookup("out", tp, "", 0)))
+        addThrows(n, "tmap:out", tp);
+
+      Delete(tm);
+      Delete(tp);
+    } else
+      Printf(callback_code, "    %s;\n", upcall);
+
+    Printf(callback_code, "  }\n");
+    Delete(upcall);
+
+    /* Finish off the inherited upcall's definition */
+    Putc(')', callback_def);
+    generateThrowsClause(n, callback_def);
+    Printf(callback_def, " {\n");
+
+    if (!ignored_method) {
+      /* Emit the actual upcall through */
+      String *imclass_desc = NewStringf("(%s)%s", jnidesc, jniret_desc);
+      String *class_desc = NewStringf("(%s)%s", classdesc, classret_desc);
+      UpcallData *udata = addUpcallMethod(imclass_dmethod, symname, imclass_desc, class_desc, decl);
+      String *methid = Getattr(udata, "imclass_methodidx");
+      String *methop = getUpcallJNIMethod(jniret_desc);
+
+      if (!is_void)
+	Printf(w->code, "jresult = (%s) ", c_ret_type);
+
+      Printf(w->code, "jenv->%s(Swig::jclass_%s, Swig::director_methids[%s], %s);\n", methop, imclass_name, methid, jupcall_args);
+
+      Printf(w->code, "if (jenv->ExceptionOccurred()) return $null;\n");
+
+      if (!is_void) {
+	String *jresult_str = NewString("jresult");
+	String *result_str = NewString("c_result");
+	Parm *tp = NewParmFromNode(returntype, result_str, n);
+
+	/* Copy jresult into c_result... */
+	if ((tm = Swig_typemap_lookup("directorout", tp, result_str, w))) {
+	  addThrows(n, "tmap:directorout", tp);
+	  Replaceall(tm, "$input", jresult_str);
+	  Replaceall(tm, "$result", result_str);
+	  Printf(w->code, "%s\n", tm);
+	} else {
+	  Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number,
+		       "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(returntype, 0),
+		       SwigType_namestr(c_classname), SwigType_namestr(name));
+	  output_director = false;
+	}
+
+	Delete(tp);
+	Delete(jresult_str);
+	Delete(result_str);
+      }
+
+      Delete(imclass_desc);
+      Delete(class_desc);
+
+      /* Terminate wrapper code */
+      Printf(w->code, "} else {\n");
+      Printf(w->code, "SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, \"null upcall object\");\n");
+      Printf(w->code, "}\n");
+
+      Printf(w->code, "if (swigjobj) jenv->DeleteLocalRef(swigjobj);\n");
+
+      if (!is_void)
+	Printf(w->code, "return %s;", qualified_return);
+    }
+
+    Printf(w->code, "}");
+
+    // We expose virtual protected methods via an extra public inline method which makes a straight call to the wrapped class' method
+    String *inline_extra_method = NewString("");
+    if (dirprot_mode() && !is_public(n) && !pure_virtual) {
+      Printv(inline_extra_method, declaration, NIL);
+      String *extra_method_name = NewStringf("%sSwigPublic", name);
+      Replaceall(inline_extra_method, name, extra_method_name);
+      Replaceall(inline_extra_method, ";\n", " {\n      ");
+      if (!is_void)
+	Printf(inline_extra_method, "return ");
+      String *methodcall = Swig_method_call(super, l);
+      Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
+      Delete(methodcall);
+      Delete(extra_method_name);
+    }
+
+    /* emit code */
+    if (status == SWIG_OK && output_director) {
+      if (!is_void) {
+	Replaceall(w->code, "$null", qualified_return);
+      } else {
+	Replaceall(w->code, "$null", "");
+      }
+      if (!GetFlag(n, "feature:ignore"))
+	Printv(imclass_directors, callback_def, callback_code, NIL);
+      if (!Getattr(n, "defaultargs")) {
+	Wrapper_print(w, f_directors);
+	Printv(f_directors_h, declaration, NIL);
+	Printv(f_directors_h, inline_extra_method, NIL);
+      }
+    }
+
+    Delete(inline_extra_method);
+    Delete(qualified_return);
+    Delete(jnidesc);
+    Delete(c_ret_type);
+    Delete(jniret_desc);
+    Delete(declaration);
+    Delete(callback_def);
+    Delete(callback_code);
+    DelWrapper(w);
+
+    return status;
+  }
+
+  /* ------------------------------------------------------------
+   * directorPrefixArgs()
+   * ------------------------------------------------------------ */
+
+  void directorPrefixArgs(Node *n) {
+    Parm *p;
+
+    /* Need to prepend 'jenv' to the director constructor's argument list */
+
+    String *jenv_type = NewString("JNIEnv");
+
+    SwigType_add_pointer(jenv_type);
+
+    p = NewParmFromNode(jenv_type, NewString("jenv"), n);
+    Setattr(p, "arg:byname", "1");
+    set_nextSibling(p, NULL);
+
+    Setattr(n, "director:prefix_args", p);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorConstructor(Node *n) {
+    Node *parent = parentNode(n);
+    String *decl = Getattr(n, "decl");;
+    String *supername = Swig_class_name(parent);
+    String *classname = directorClassName(parent);
+    String *sub = NewString("");
+    Parm *p;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms;
+    int argidx = 0;
+
+    /* Assign arguments to superclass's parameters, if not already done */
+    for (p = superparms; p; p = nextSibling(p)) {
+      String *pname = Getattr(p, "name");
+
+      if (!pname) {
+	pname = NewStringf("arg%d", argidx++);
+	Setattr(p, "name", pname);
+      }
+    }
+
+    /* insert jenv prefix argument */
+    parms = CopyParmList(superparms);
+
+    String *jenv_type = NewString("JNIEnv");
+    SwigType_add_pointer(jenv_type);
+    p = NewParmFromNode(jenv_type, NewString("jenv"), n);
+    set_nextSibling(p, parms);
+    parms = p;
+
+    directorPrefixArgs(n);
+
+    if (!Getattr(n, "defaultargs")) {
+      /* constructor */
+      {
+	String *basetype = Getattr(parent, "classtype");
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 0);
+	String *call = Swig_csuperclass_call(0, basetype, superparms);
+	String *classtype = SwigType_namestr(Getattr(n, "name"));
+
+	Printf(f_directors, "%s::%s : %s, %s {\n", classname, target, call, Getattr(parent, "director:ctor"));
+	Printf(f_directors, "}\n\n");
+
+	Delete(classtype);
+	Delete(target);
+	Delete(call);
+      }
+
+      /* constructor header */
+      {
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 1);
+	Printf(f_directors_h, "    %s;\n", target);
+	Delete(target);
+      }
+    }
+
+    Delete(sub);
+    Delete(supername);
+    Delete(jenv_type);
+    Delete(parms);
+    return Language::classDirectorConstructor(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorDefaultConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorDefaultConstructor(Node *n) {
+    String *classname = Swig_class_name(n);
+    String *classtype = SwigType_namestr(Getattr(n, "name"));
+    Wrapper *w = NewWrapper();
+
+    Printf(w->def, "SwigDirector_%s::SwigDirector_%s(JNIEnv *jenv) : %s {", classname, classname, Getattr(n, "director:ctor"));
+    Printf(w->code, "}\n");
+    Wrapper_print(w, f_directors);
+
+    Printf(f_directors_h, "    SwigDirector_%s(JNIEnv *jenv);\n", classname);
+    DelWrapper(w);
+    Delete(classtype);
+    Delete(classname);
+    directorPrefixArgs(n);
+    return Language::classDirectorDefaultConstructor(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * classDirectorInit()
+   * ------------------------------------------------------------ */
+
+  int classDirectorInit(Node *n) {
+    Delete(none_comparison);
+    none_comparison = NewString("");	// not used
+
+    Delete(director_ctor_code);
+    director_ctor_code = NewString("$director_new");
+
+    Java_director_declaration(n);
+
+    Printf(f_directors_h, "%s {\n", Getattr(n, "director:decl"));
+    Printf(f_directors_h, "\npublic:\n");
+    Printf(f_directors_h, "    void swig_connect_director(JNIEnv *jenv, jobject jself, jclass jcls, bool swig_mem_own, bool weak_global);\n");
+
+    /* Keep track of the director methods for this class */
+    first_class_dmethod = curr_class_dmethod = n_dmethods;
+
+    return Language::classDirectorInit(n);
+  }
+
+  /* ----------------------------------------------------------------------
+   * classDirectorDestructor()
+   * ---------------------------------------------------------------------- */
+
+  int classDirectorDestructor(Node *n) {
+    Node *current_class = getCurrentClass();
+    String *full_classname = Getattr(current_class, "name");
+    String *classname = Swig_class_name(current_class);
+    Wrapper *w = NewWrapper();
+
+    if (Getattr(n, "throw")) {
+      Printf(f_directors_h, "    virtual ~SwigDirector_%s() throw ();\n", classname);
+      Printf(w->def, "SwigDirector_%s::~SwigDirector_%s() throw () {\n", classname, classname);
+    } else {
+      Printf(f_directors_h, "    virtual ~SwigDirector_%s();\n", classname);
+      Printf(w->def, "SwigDirector_%s::~SwigDirector_%s() {\n", classname, classname);
+    }
+
+    /* Ensure that correct directordisconnect typemap's method name is called
+     * here: */
+
+    const String *disconn_tm = NULL;
+    Node *disconn_attr = NewHash();
+    String *disconn_methodname = NULL;
+
+    disconn_tm = typemapLookup("directordisconnect", full_classname, WARN_NONE, disconn_attr);
+    disconn_methodname = Getattr(disconn_attr, "tmap:directordisconnect:methodname");
+
+    Printv(w->code, "  swig_disconnect_director_self(\"", disconn_methodname, "\");\n", "}\n", NIL);
+
+    Wrapper_print(w, f_directors);
+
+    DelWrapper(w);
+    Delete(disconn_attr);
+    Delete(classname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorEnd()
+   * ------------------------------------------------------------ */
+
+  int classDirectorEnd(Node *n) {
+    String *classname = Getattr(n, "sym:name");
+    String *director_classname = directorClassName(n);
+    String *internal_classname;
+
+    Wrapper *w = NewWrapper();
+
+    if (Len(package_path) > 0)
+      internal_classname = NewStringf("%s/%s", package_path, classname);
+    else
+      internal_classname = NewStringf("%s", classname);
+
+    Wrapper_add_localv(w, "baseclass", "static jclass baseclass", "= 0", NIL);
+    Printf(w->def, "void %s::swig_connect_director(JNIEnv *jenv, jobject jself, jclass jcls, bool swig_mem_own, bool weak_global) {", director_classname);
+
+    if (first_class_dmethod != curr_class_dmethod) {
+      Printf(w->def, "static struct {\n");
+      Printf(w->def, "const char *mname;\n");
+      Printf(w->def, "const char *mdesc;\n");
+      Printf(w->def, "jmethodID base_methid;\n");
+      Printf(w->def, "} methods[] = {\n");
+
+      for (int i = first_class_dmethod; i < curr_class_dmethod; ++i) {
+	UpcallData *udata = Getitem(dmethods_seq, i);
+
+	Printf(w->def, "{ \"%s\", \"%s\", NULL }", Getattr(udata, "method"), Getattr(udata, "fdesc"));
+	if (i != curr_class_dmethod - 1)
+	  Putc(',', w->def);
+	Putc('\n', w->def);
+      }
+
+      Printf(w->def, "};\n");
+    }
+
+    Printf(w->code, "if (swig_set_self(jenv, jself, swig_mem_own, weak_global)) {\n");
+    Printf(w->code, "if (!baseclass) {\n");
+    Printf(w->code, "baseclass = jenv->FindClass(\"%s\");\n", internal_classname);
+    Printf(w->code, "if (!baseclass) return;\n");
+    Printf(w->code, "baseclass = (jclass) jenv->NewGlobalRef(baseclass);\n");
+    Printf(w->code, "}\n");
+
+    int n_methods = curr_class_dmethod - first_class_dmethod;
+
+    if (n_methods) {
+      /* Emit the swig_overrides() method and the swig_override array */
+      Printf(f_directors_h, "public:\n");
+      Printf(f_directors_h, "    bool swig_overrides(int n) {\n");
+      Printf(f_directors_h, "      return (n < %d ? swig_override[n] : false);\n", n_methods);
+      Printf(f_directors_h, "    }\n");
+      Printf(f_directors_h, "protected:\n");
+      Printf(f_directors_h, "    bool swig_override[%d];\n", n_methods);
+
+      /* Emit the code to look up the class's methods, initialize the override array */
+
+      Printf(w->code, "bool derived = (jenv->IsSameObject(baseclass, jcls) ? false : true);\n");
+      Printf(w->code, "for (int i = 0; i < %d; ++i) {\n", n_methods);
+      Printf(w->code, "  if (!methods[i].base_methid) {\n");
+      Printf(w->code, "    methods[i].base_methid = jenv->GetMethodID(baseclass, methods[i].mname, methods[i].mdesc);\n");
+      Printf(w->code, "    if (!methods[i].base_methid) return;\n");
+      Printf(w->code, "  }\n");
+      Printf(w->code, "  swig_override[i] = false;\n");
+      Printf(w->code, "  if (derived) {\n");
+      Printf(w->code, "    jmethodID methid = jenv->GetMethodID(jcls, methods[i].mname, methods[i].mdesc);\n");
+      Printf(w->code, "    swig_override[i] = (methid != methods[i].base_methid);\n");
+      Printf(w->code, "    jenv->ExceptionClear();\n");
+      Printf(w->code, "  }\n");
+      Printf(w->code, "}\n");
+    } else {
+      Printf(f_directors_h, "public:\n");
+      Printf(f_directors_h, "    bool swig_overrides(int n) {\n");
+      Printf(f_directors_h, "      return false;\n");
+      Printf(f_directors_h, "    }\n");
+    }
+
+    Printf(f_directors_h, "};\n\n");
+    Printf(w->code, "}\n");
+    Printf(w->code, "}\n");
+
+    Wrapper_print(w, f_directors);
+
+    DelWrapper(w);
+    Delete(internal_classname);
+
+    return Language::classDirectorEnd(n);
+  }
+
+  /* --------------------------------------------------------------------
+   * classDirectorDisown()
+   * ------------------------------------------------------------------*/
+
+  virtual int classDirectorDisown(Node *n) {
+    (void) n;
+    return SWIG_OK;
+  }
+
+  /*----------------------------------------------------------------------
+   * extraDirectorProtectedCPPMethodsRequired()
+   *--------------------------------------------------------------------*/
+  bool extraDirectorProtectedCPPMethodsRequired() const {
+    return false;
+  }
+
+  /*----------------------------------------------------------------------
+   * Java_director_declaration()
+   *
+   * Generate the director class's declaration
+   * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {"
+   *--------------------------------------------------------------------*/
+
+  void Java_director_declaration(Node *n) {
+    String *base = Getattr(n, "classtype");
+    String *class_ctor = NewString("Swig::Director(jenv)");
+
+    String *classname = Swig_class_name(n);
+    String *directorname = NewStringf("SwigDirector_%s", classname);
+    String *declaration = Swig_class_declaration(n, directorname);
+
+    Printf(declaration, " : public %s, public Swig::Director", base);
+
+    // Stash stuff for later.
+    Setattr(n, "director:decl", declaration);
+    Setattr(n, "director:ctor", class_ctor);
+  }
+
+};				/* class JAVA */
+
+/* -----------------------------------------------------------------------------
+ * swig_java()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_java() {
+  return new JAVA();
+}
+extern "C" Language *swig_java(void) {
+  return new_swig_java();
+}
+
+/* -----------------------------------------------------------------------------
+ * Static member variables
+ * ----------------------------------------------------------------------------- */
+
+const char *JAVA::usage = (char *) "\
+Java Options (available with -java)\n\
+     -nopgcpp        - Suppress premature garbage collection prevention parameter\n\
+     -noproxy        - Generate the low-level functional interface instead\n\
+                       of proxy classes\n\
+     -oldvarnames    - old intermediary method names for variable wrappers\n\
+     -package <name> - set name of the Java package to <name>\n\
+\n";
diff --git a/trunk/Source/Modules/lang.cxx b/trunk/Source/Modules/lang.cxx
new file mode 100644
index 0000000..6718903
--- /dev/null
+++ b/trunk/Source/Modules/lang.cxx
@@ -0,0 +1,3413 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * lang.cxx
+ *
+ * Language base class functions.  Default C++ handling is also implemented here.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_lang_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+#include <ctype.h>
+
+/* default mode settings */
+static int director_mode = 0;
+static int director_protected_mode = 1;
+static int all_protected_mode = 0;
+static int naturalvar_mode = 0;
+
+/* Set director_protected_mode */
+void Wrapper_director_mode_set(int flag) {
+  director_mode = flag;
+}
+
+void Wrapper_director_protected_mode_set(int flag) {
+  director_protected_mode = flag;
+}
+
+void Wrapper_all_protected_mode_set(int flag) {
+  all_protected_mode = flag;
+}
+
+void Wrapper_naturalvar_mode_set(int flag) {
+  naturalvar_mode = flag;
+}
+
+extern "C" {
+  int Swig_director_mode() {
+    return director_mode;
+  }
+  int Swig_director_protected_mode() {
+    return director_protected_mode;
+  }
+  int Swig_all_protected_mode() {
+    return all_protected_mode;
+  }
+}
+
+/* Some status variables used during parsing */
+static int InClass = 0; /* Parsing C++ or not */
+static String *ClassName = 0;	/* This is the real name of the current class */
+static String *ClassPrefix = 0;	/* Class prefix */
+static String *ClassType = 0;	/* Fully qualified type name to use */
+static String *DirectorClassName = 0;	/* Director name of the current class */
+int Abstract = 0;
+int ImportMode = 0;
+int IsVirtual = 0;
+static String *AttributeFunctionGet = 0;
+static String *AttributeFunctionSet = 0;
+static Node *CurrentClass = 0;
+int line_number = 0;
+char *input_file = 0;
+int SmartPointer = 0;
+static Hash *classhash;
+
+extern int GenerateDefault;
+extern int ForceExtern;
+extern int AddExtern;
+
+/* import modes */
+
+#define  IMPORT_MODE     1
+#define  IMPORT_MODULE   2
+
+/* ----------------------------------------------------------------------
+ * Dispatcher::emit_one()
+ *
+ * Dispatch a single node
+ * ---------------------------------------------------------------------- */
+
+int Dispatcher::emit_one(Node *n) {
+  String *wrn;
+  int ret = SWIG_OK;
+
+  char *tag = Char(nodeType(n));
+  if (!tag) {
+    /* Printf(stderr,"SWIG: Fatal internal error. Malformed parse tree
+       node!\n"); */
+    return SWIG_OK;
+  }
+
+  /* Do not proceed if marked with an error */
+
+  if (Getattr(n, "error"))
+    return SWIG_OK;
+
+  /* Look for warnings */
+  wrn = Getattr(n, "feature:warnfilter");
+  if (wrn) {
+    Swig_warnfilter(wrn, 1);
+  }
+
+  /* ============================================================
+   * C/C++ parsing
+   * ============================================================ */
+
+  if (strcmp(tag, "extern") == 0) {
+    ret = externDeclaration(n);
+  } else if (strcmp(tag, "cdecl") == 0) {
+    ret = cDeclaration(n);
+  } else if (strcmp(tag, "enum") == 0) {
+    ret = enumDeclaration(n);
+  } else if (strcmp(tag, "enumitem") == 0) {
+    ret = enumvalueDeclaration(n);
+  } else if (strcmp(tag, "enumforward") == 0) {
+    ret = enumforwardDeclaration(n);
+  } else if (strcmp(tag, "class") == 0) {
+    ret = classDeclaration(n);
+  } else if (strcmp(tag, "classforward") == 0) {
+    ret = classforwardDeclaration(n);
+  } else if (strcmp(tag, "constructor") == 0) {
+    ret = constructorDeclaration(n);
+  } else if (strcmp(tag, "destructor") == 0) {
+    ret = destructorDeclaration(n);
+  } else if (strcmp(tag, "access") == 0) {
+    ret = accessDeclaration(n);
+  } else if (strcmp(tag, "using") == 0) {
+    ret = usingDeclaration(n);
+  } else if (strcmp(tag, "namespace") == 0) {
+    ret = namespaceDeclaration(n);
+  } else if (strcmp(tag, "template") == 0) {
+    ret = templateDeclaration(n);
+  }
+
+  /* ===============================================================
+   *  SWIG directives
+   * =============================================================== */
+
+  else if (strcmp(tag, "top") == 0) {
+    ret = top(n);
+  } else if (strcmp(tag, "extend") == 0) {
+    ret = extendDirective(n);
+  } else if (strcmp(tag, "apply") == 0) {
+    ret = applyDirective(n);
+  } else if (strcmp(tag, "clear") == 0) {
+    ret = clearDirective(n);
+  } else if (strcmp(tag, "constant") == 0) {
+    ret = constantDirective(n);
+  } else if (strcmp(tag, "fragment") == 0) {
+    ret = fragmentDirective(n);
+  } else if (strcmp(tag, "import") == 0) {
+    ret = importDirective(n);
+  } else if (strcmp(tag, "include") == 0) {
+    ret = includeDirective(n);
+  } else if (strcmp(tag, "insert") == 0) {
+    ret = insertDirective(n);
+  } else if (strcmp(tag, "module") == 0) {
+    ret = moduleDirective(n);
+  } else if (strcmp(tag, "native") == 0) {
+    ret = nativeDirective(n);
+  } else if (strcmp(tag, "pragma") == 0) {
+    ret = pragmaDirective(n);
+  } else if (strcmp(tag, "typemap") == 0) {
+    ret = typemapDirective(n);
+  } else if (strcmp(tag, "typemapcopy") == 0) {
+    ret = typemapcopyDirective(n);
+  } else if (strcmp(tag, "typemapitem") == 0) {
+    ret = typemapitemDirective(n);
+  } else if (strcmp(tag, "types") == 0) {
+    ret = typesDirective(n);
+  } else {
+    Printf(stderr, "%s:%d. Unrecognized parse tree node type '%s'\n", input_file, line_number, tag);
+    ret = SWIG_ERROR;
+  }
+  if (wrn) {
+    Swig_warnfilter(wrn, 0);
+  }
+  return ret;
+}
+
+/* ----------------------------------------------------------------------
+ * Dispatcher::emit_children()
+ *
+ * Emit all children that match the given type. type = 0 means all types.
+ * ---------------------------------------------------------------------- */
+
+int Dispatcher::emit_children(Node *n) {
+  Node *c;
+  char *eo = Char(Getattr(n, "feature:emitonlychildren"));
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    if (eo) {
+      const char *tag = Char(nodeType(c));
+      if (strcmp(tag, "cdecl") == 0) {
+	if (checkAttribute(c, "storage", "typedef"))
+	  tag = "typedef";
+      }
+      if (strstr(eo, tag) == 0) {
+	continue;
+      }
+    }
+    emit_one(c);
+  }
+  return SWIG_OK;
+}
+
+
+/* Stubs for dispatcher class.  We don't do anything by default---up to derived class
+   to fill in traversal code */
+
+int Dispatcher::defaultHandler(Node *) {
+  return SWIG_OK;
+}
+int Dispatcher::extendDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::applyDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::clearDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::constantDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::fragmentDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::importDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::includeDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::insertDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::moduleDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::nativeDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::pragmaDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::typemapDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::typemapitemDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::typemapcopyDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::typesDirective(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::cDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::externDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::enumDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::enumvalueDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::enumforwardDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::classDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::templateDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::classforwardDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::constructorDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::destructorDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::accessDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::usingDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+int Dispatcher::namespaceDeclaration(Node *n) {
+  return defaultHandler(n);
+}
+
+
+/* Allocators */
+Language::Language():
+none_comparison(NewString("$arg != 0")),
+director_ctor_code(NewString("")),
+director_prot_ctor_code(0),
+symbols(NewHash()),
+classtypes(NewHash()),
+enumtypes(NewHash()),
+overloading(0),
+multiinput(0),
+cplus_runtime(0),
+directors(0) {
+  argc_template_string = NewString("argc");
+  argv_template_string = NewString("argv[%d]");
+
+  /* Default director constructor code, passed to Swig_ConstructorToFunction */
+  Printv(director_ctor_code, "if ( $comparison ) { /* subclassed */\n", "  $director_new \n", "} else {\n", "  $nondirector_new \n", "}\n", NIL);
+
+  /*
+     Default director 'protected' constructor code, disabled by
+     default. Each language that needs it, has to define it.
+   */
+  director_prot_ctor_code = 0;
+  director_multiple_inheritance = 1;
+  director_language = 0;
+}
+
+Language::~Language() {
+  Delete(symbols);
+  Delete(classtypes);
+  Delete(enumtypes);
+  Delete(director_ctor_code);
+  Delete(none_comparison);
+}
+
+/* ----------------------------------------------------------------------
+   emit_one()
+   ---------------------------------------------------------------------- */
+
+int Language::emit_one(Node *n) {
+  int ret;
+  int oldext;
+  if (!n)
+    return SWIG_OK;
+
+  if (GetFlag(n, "feature:ignore")
+      && !Getattr(n, "feature:onlychildren"))
+    return SWIG_OK;
+
+  oldext = Extend;
+  if (Getattr(n, "feature:extend"))
+    Extend = 1;
+
+  line_number = Getline(n);
+  input_file = Char(Getfile(n));
+
+  /*
+     symtab = Getattr(n,"symtab");
+     if (symtab) {
+     symtab = Swig_symbol_setscope(symtab);
+     }
+   */
+  ret = Dispatcher::emit_one(n);
+  /*
+     if (symtab) {
+     Swig_symbol_setscope(symtab);
+     }
+   */
+  Extend = oldext;
+  return ret;
+}
+
+
+static Parm *nonvoid_parms(Parm *p) {
+  if (p) {
+    SwigType *t = Getattr(p, "type");
+    if (SwigType_type(t) == T_VOID)
+      return 0;
+  }
+  return p;
+}
+
+/* -----------------------------------------------------------------------------
+ * cplus_value_type()
+ *
+ * Returns the alternative value type needed in C++ for class value
+ * types. When swig is not sure about using a plain $ltype value,
+ * since the class doesn't have a default constructor, or it can't be
+ * assigned, you will get back 'SwigValueWrapper<type >'.
+ *
+ * ----------------------------------------------------------------------------- */
+
+SwigType *cplus_value_type(SwigType *t) {
+  return SwigType_alttype(t, 0);
+}
+
+static Node *first_nontemplate(Node *n) {
+  while (n) {
+    if (Strcmp(nodeType(n), "template") != 0)
+      return n;
+    n = Getattr(n, "sym:nextSibling");
+  }
+  return n;
+}
+
+
+
+/* --------------------------------------------------------------------------
+ * swig_pragma()
+ *
+ * Handle swig pragma directives.  
+ * -------------------------------------------------------------------------- */
+
+void swig_pragma(char *lang, char *name, char *value) {
+  if (strcmp(lang, "swig") == 0) {
+    if ((strcmp(name, "make_default") == 0) || ((strcmp(name, "makedefault") == 0))) {
+      GenerateDefault = 1;
+    } else if ((strcmp(name, "no_default") == 0) || ((strcmp(name, "nodefault") == 0))) {
+      Swig_warning(WARN_DEPRECATED_NODEFAULT, "SWIG", 1, "dangerous, use %%nodefaultctor, %%nodefaultdtor instead.\n");
+      GenerateDefault = 0;
+    } else if (strcmp(name, "attributefunction") == 0) {
+      String *nvalue = NewString(value);
+      char *s = strchr(Char(nvalue), ':');
+      if (!s) {
+	Swig_error(input_file, line_number, "Bad value for attributefunction. Expected \"fmtget:fmtset\".\n");
+      } else {
+	*s = 0;
+	AttributeFunctionGet = NewString(Char(nvalue));
+	AttributeFunctionSet = NewString(s + 1);
+      }
+      Delete(nvalue);
+    } else if (strcmp(name, "noattributefunction") == 0) {
+      AttributeFunctionGet = 0;
+      AttributeFunctionSet = 0;
+    }
+  }
+}
+
+/* --------------------------------------------------------------------------
+ * use_naturalvar_mode()
+ * -------------------------------------------------------------------------- */
+int use_naturalvar_mode(Node *n) {
+  if (Getattr(n, "unnamed"))
+    return 0;
+  int nvar = naturalvar_mode || GetFlag(n, "feature:naturalvar");
+  if (!nvar) {
+    /* look for feature in the class */
+    SwigType *ty = Getattr(n, "type");
+    SwigType *fullty = SwigType_typedef_resolve_all(ty);
+    if (SwigType_isclass(fullty)) {
+      Node *m = Copy(n);
+      SwigType *tys = SwigType_strip_qualifiers(fullty);
+      Swig_features_get(Swig_cparse_features(), 0, tys, 0, m);
+      nvar = GetFlag(m, "feature:naturalvar");
+      Delete(tys);
+      Delete(m);
+    }
+    Delete(fullty);
+  }
+  return nvar ? CWRAP_NATURAL_VAR : 0;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::top()   - Top of parsing tree 
+ * ---------------------------------------------------------------------- */
+
+int Language::top(Node *n) {
+  Node *mod = Getattr(n, "module");
+  if (mod) {
+    Node *options = Getattr(mod, "options");
+    if (options) {
+      if (Getattr(options, "naturalvar")) {
+	naturalvar_mode = 1;
+      }
+      if (Getattr(options, "nonaturalvar")) {
+	naturalvar_mode = 0;
+      }
+    }
+  }
+  classhash = Getattr(n, "classes");
+  return emit_children(n);
+}
+
+/* ----------------------------------------------------------------------
+ * Language::extendDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::extendDirective(Node *n) {
+  int oldam = Extend;
+  AccessMode oldmode = cplus_mode;
+  Extend = CWRAP_EXTEND;
+  cplus_mode = PUBLIC;
+
+  emit_children(n);
+
+  Extend = oldam;
+  cplus_mode = oldmode;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::applyDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::applyDirective(Node *n) {
+
+  Parm *pattern = Getattr(n, "pattern");
+  Node *c = firstChild(n);
+  while (c) {
+    Parm *apattern = Getattr(c, "pattern");
+    if (ParmList_len(pattern) != ParmList_len(apattern)) {
+      Swig_error(input_file, line_number, "Can't apply (%s) to (%s).  Number of arguments don't match.\n", ParmList_str(pattern), ParmList_str(apattern));
+    } else {
+      if (!Swig_typemap_apply(pattern, apattern)) {
+	Swig_warning(WARN_TYPEMAP_APPLY_UNDEF, input_file, line_number, "Can't apply (%s). No typemaps are defined.\n", ParmList_str(pattern));
+      }
+    }
+    c = nextSibling(c);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::clearDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::clearDirective(Node *n) {
+  Node *p;
+  for (p = firstChild(n); p; p = nextSibling(p)) {
+    ParmList *pattern = Getattr(p, "pattern");
+    Swig_typemap_clear_apply(pattern);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::constantDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::constantDirective(Node *n) {
+
+  if (CurrentClass && (cplus_mode != PUBLIC))
+    return SWIG_NOWRAP;
+
+  if (!GetFlag(n, "feature:allowexcept")) {
+    UnsetFlag(n, "feature:except");
+  }
+  if (Getattr(n, "feature:exceptvar")) {
+    Setattr(n, "feature:except", Getattr(n, "feature:exceptvar"));
+  }
+
+  if (!ImportMode) {
+    Swig_require("constantDirective", n, "name", "?value", NIL);
+    String *name = Getattr(n, "name");
+    String *value = Getattr(n, "value");
+    if (!value) {
+      value = Copy(name);
+    } else {
+      /*      if (checkAttribute(n,"type","char")) {
+         value = NewString(value);
+         } else {
+         value = NewStringf("%(escape)s", value);
+         }
+       */
+      Setattr(n, "rawvalue", value);
+      value = NewStringf("%(escape)s", value);
+      if (!Len(value))
+	Append(value, "\\0");
+      /*      Printf(stdout,"'%s' = '%s'\n", name, value); */
+    }
+    Setattr(n, "value", value);
+    this->constantWrapper(n);
+    Swig_restore(n);
+    return SWIG_OK;
+  }
+  return SWIG_NOWRAP;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::fragmentDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::fragmentDirective(Node *n) {
+  Swig_fragment_register(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::importDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::importDirective(Node *n) {
+  int oldim = ImportMode;
+  ImportMode = IMPORT_MODE;
+  emit_children(n);
+  ImportMode = oldim;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::includeDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::includeDirective(Node *n) {
+  emit_children(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::insertDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::insertDirective(Node *n) {
+  /* %insert directive */
+  if ((!ImportMode) || Getattr(n, "generated")) {
+    String *code = Getattr(n, "code");
+    String *section = Getattr(n, "section");
+    File *f = 0;
+    if (!section) {		/* %{ ... %} */
+      f = Swig_filebyname("header");
+    } else {
+      f = Swig_filebyname(section);
+    }
+    if (f) {
+      Printf(f, "%s\n", code);
+    } else {
+      Swig_error(input_file, line_number, "Unknown target '%s' for %%insert directive.\n", section);
+    }
+    return SWIG_OK;
+  } else {
+    return SWIG_NOWRAP;
+  }
+}
+
+/* ----------------------------------------------------------------------
+ * Language::moduleDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::moduleDirective(Node *n) {
+  (void) n;
+  /* %module directive */
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::nativeDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::nativeDirective(Node *n) {
+  if (!ImportMode) {
+    return nativeWrapper(n);
+  } else {
+    return SWIG_NOWRAP;
+  }
+}
+
+/* ----------------------------------------------------------------------
+ * Language::pragmaDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::pragmaDirective(Node *n) {
+  /* %pragma directive */
+  if (!ImportMode) {
+    String *lan = Getattr(n, "lang");
+    String *name = Getattr(n, "name");
+    String *value = Getattr(n, "value");
+    swig_pragma(Char(lan), Char(name), Char(value));
+    /*  pragma(Char(lan),Char(name),Char(value)); */
+    return SWIG_OK;
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::typemapDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::typemapDirective(Node *n) {
+  /* %typemap directive */
+  String *method = Getattr(n, "method");
+  String *code = Getattr(n, "code");
+  Parm *kwargs = Getattr(n, "kwargs");
+  Node *items = firstChild(n);
+  static int namewarn = 0;
+
+
+  if (code && (Strstr(code, "$source") || (Strstr(code, "$target")))) {
+    Swig_warning(WARN_TYPEMAP_SOURCETARGET, Getfile(n), Getline(n), "Deprecated typemap feature ($source/$target).\n");
+    if (!namewarn) {
+      Swig_warning(WARN_TYPEMAP_SOURCETARGET, Getfile(n), Getline(n), "The use of $source and $target in a typemap declaration is deprecated.\n\
+For typemaps related to argument input (in,ignore,default,arginit,check), replace\n\
+$source by $input and $target by $1.   For typemaps related to return values (out,\n\
+argout,ret,except), replace $source by $1 and $target by $result.  See the file\n\
+Doc/Manual/Typemaps.html for complete details.\n");
+      namewarn = 1;
+    }
+  }
+
+  if (Strcmp(method, "except") == 0) {
+    Swig_warning(WARN_DEPRECATED_EXCEPT_TM, Getfile(n), Getline(n), "%%typemap(except) is deprecated. Use the %%exception directive.\n");
+  }
+
+  if (Strcmp(method, "in") == 0) {
+    Hash *k;
+    k = kwargs;
+    while (k) {
+      if (checkAttribute(k, "name", "numinputs")) {
+	if (!multiinput && (GetInt(k, "value") > 1)) {
+	  Swig_error(Getfile(n), Getline(n), "Multiple-input typemaps (numinputs > 1) not supported by this target language module.\n");
+	  return SWIG_ERROR;
+	}
+	break;
+      }
+      k = nextSibling(k);
+    }
+    if (!k) {
+      k = NewHash();
+      Setattr(k, "name", "numinputs");
+      Setattr(k, "value", "1");
+      set_nextSibling(k, kwargs);
+      Setattr(n, "kwargs", k);
+      kwargs = k;
+    }
+  }
+
+  if (Strcmp(method, "ignore") == 0) {
+    Swig_warning(WARN_DEPRECATED_IGNORE_TM, Getfile(n), Getline(n), "%%typemap(ignore) has been replaced by %%typemap(in,numinputs=0).\n");
+
+    Clear(method);
+    Append(method, "in");
+    Hash *k = NewHash();
+    Setattr(k, "name", "numinputs");
+    Setattr(k, "value", "0");
+    set_nextSibling(k, kwargs);
+    Setattr(n, "kwargs", k);
+    kwargs = k;
+  }
+
+  /* Replace $descriptor() macros */
+
+  if (code) {
+    Setfile(code, Getfile(n));
+    Setline(code, Getline(n));
+    Swig_cparse_replace_descriptor(code);
+  }
+
+  while (items) {
+    Parm *pattern = Getattr(items, "pattern");
+    Parm *parms = Getattr(items, "parms");
+
+    if (code) {
+      Swig_typemap_register(method, pattern, code, parms, kwargs);
+    } else {
+      Swig_typemap_clear(method, pattern);
+    }
+    items = nextSibling(items);
+  }
+  return SWIG_OK;
+
+}
+
+/* ----------------------------------------------------------------------
+ * Language::typemapcopyDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::typemapcopyDirective(Node *n) {
+  String *method = Getattr(n, "method");
+  Parm *pattern = Getattr(n, "pattern");
+  Node *items = firstChild(n);
+  int nsrc = 0;
+  nsrc = ParmList_len(pattern);
+  while (items) {
+    ParmList *npattern = Getattr(items, "pattern");
+    if (nsrc != ParmList_len(npattern)) {
+      Swig_error(input_file, line_number, "Can't copy typemap. Number of types differ.\n");
+    } else {
+      if (Swig_typemap_copy(method, pattern, npattern) < 0) {
+	Swig_error(input_file, line_number, "Can't copy typemap.\n");
+      }
+    }
+    items = nextSibling(items);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::typesDirective()
+ * ---------------------------------------------------------------------- */
+
+int Language::typesDirective(Node *n) {
+  Parm *parms = Getattr(n, "parms");
+  String *convcode = Getattr(n, "convcode"); /* optional user supplied conversion code for custom casting */
+  while (parms) {
+    SwigType *t = Getattr(parms, "type");
+    String *v = Getattr(parms, "value");
+    if (!v) {
+      SwigType_remember(t);
+    } else {
+      if (SwigType_issimple(t)) {
+	SwigType_inherit(t, v, 0, convcode);
+      }
+    }
+    parms = nextSibling(parms);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::cDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::cDeclaration(Node *n) {
+
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  SwigType *decl = Getattr(n, "decl");
+  String *storage = Getattr(n, "storage");
+  Node *over;
+  File *f_header = 0;
+  SwigType *ty, *fullty;
+
+  /* discards nodes following the access control rules */
+  if (cplus_mode != PUBLIC || !is_public(n)) {
+    /* except for friends, they are not affected by access control */
+    int isfriend = storage && (Cmp(storage, "friend") == 0);
+    if (!isfriend) {
+      /* Check what the director needs. If the method is pure virtual, it is always needed.
+       * Also wrap non-virtual protected members if asked for (allprotected mode). */
+      if (!(directorsEnabled() && ((is_member_director(CurrentClass, n) && need_nonpublic_member(n)) || is_non_virtual_protected_access(n)))) {
+          return SWIG_NOWRAP;
+      }
+#if 0
+// I don't see why this is needed - WSF
+      /* prevent wrapping the method twice due to overload */
+      String *wrapname = NewStringf("nonpublic_%s%s", symname, Getattr(n, "sym:overname"));
+      if (Getattr(CurrentClass, wrapname)) {
+	Delete(wrapname);
+	return SWIG_NOWRAP;
+      }
+      SetFlag(CurrentClass, wrapname);
+      Delete(wrapname);
+#endif
+    }
+  }
+
+  if (Cmp(storage, "typedef") == 0) {
+    Swig_save("cDeclaration", n, "type", NIL);
+    SwigType *t = Copy(type);
+    if (t) {
+      SwigType_push(t, decl);
+      Setattr(n, "type", t);
+      typedefHandler(n);
+    }
+    Swig_restore(n);
+    return SWIG_OK;
+  }
+
+  /* If in import mode, we proceed no further */
+  if (ImportMode)
+    return SWIG_NOWRAP;
+
+  /* If we're in extend mode and there is code, replace the $descriptor macros */
+  if (Extend) {
+    String *code = Getattr(n, "code");
+    if (code) {
+      Setfile(code, Getfile(n));
+      Setline(code, Getline(n));
+      Swig_cparse_replace_descriptor(code);
+    }
+  }
+
+  /* Overloaded symbol check */
+  over = Swig_symbol_isoverloaded(n);
+  if (!overloading) {
+    if (over)
+      over = first_nontemplate(over);
+    if (over && (over != n)) {
+      SwigType *tc = Copy(decl);
+      SwigType *td = SwigType_pop_function(tc);
+      String *oname;
+      String *cname;
+      if (CurrentClass) {
+	oname = NewStringf("%s::%s", ClassName, name);
+	cname = NewStringf("%s::%s", ClassName, Getattr(over, "name"));
+      } else {
+	oname = NewString(name);
+	cname = NewString(Getattr(over, "name"));
+      }
+
+      SwigType *tc2 = Copy(Getattr(over, "decl"));
+      SwigType *td2 = SwigType_pop_function(tc2);
+
+      Swig_warning(WARN_LANG_OVERLOAD_DECL, input_file, line_number, "Overloaded declaration ignored.  %s\n", SwigType_str(td, SwigType_namestr(oname)));
+      Swig_warning(WARN_LANG_OVERLOAD_DECL, Getfile(over), Getline(over), "Previous declaration is %s\n", SwigType_str(td2, SwigType_namestr(cname)));
+
+      Delete(tc2);
+      Delete(td2);
+      Delete(tc);
+      Delete(td);
+      Delete(oname);
+      Delete(cname);
+      return SWIG_NOWRAP;
+    }
+  }
+
+  if (symname && !validIdentifier(symname)) {
+    Swig_warning(WARN_LANG_IDENTIFIER, input_file, line_number, "Can't wrap '%s' unless renamed to a valid identifier.\n", symname);
+    return SWIG_NOWRAP;
+  }
+
+  ty = NewString(type);
+  SwigType_push(ty, decl);
+  fullty = SwigType_typedef_resolve_all(ty);
+  if (SwigType_isfunction(fullty)) {
+    if (!SwigType_isfunction(ty)) {
+      Delete(ty);
+      ty = fullty;
+      fullty = 0;
+      ParmList *parms = SwigType_function_parms(ty);
+      Setattr(n, "parms", parms);
+    }
+    /* Transform the node into a 'function' node and emit */
+    if (!CurrentClass) {
+      f_header = Swig_filebyname("header");
+
+      if (AddExtern) {
+	if (f_header) {
+	  if ((Cmp(storage, "extern") == 0) || (ForceExtern && !storage)) {
+	    /* we don't need the 'extern' part in the C/C++ declaration,
+	       and it produces some problems when namespace and SUN
+	       Studio is used.
+
+	       Printf(f_header,"extern %s", SwigType_str(ty,name));
+
+	       In fact generating extern declarations is quite error prone and is
+	       no longer the default. Getting it right seems impossible with namespaces
+	       and default arguments and when a method is declared with the various Windows
+	       calling conventions - SWIG doesn't understand Windows (non standard) calling
+	       conventions in the first place, so can't regenerate them.
+	     */
+	    String *str = SwigType_str(ty, name);
+	    Printf(f_header, "%s", str);
+	    Delete(str);
+	    {
+	      DOH *t = Getattr(n, "throws");
+	      if (t) {
+		Printf(f_header, " throw(");
+		while (t) {
+		  Printf(f_header, "%s", Getattr(t, "type"));
+		  t = nextSibling(t);
+		  if (t)
+		    Printf(f_header, ",");
+		}
+		Printf(f_header, ")");
+	      }
+	    }
+	    Printf(f_header, ";\n");
+	  } else if (Cmp(storage, "externc") == 0) {
+	    /* here 'extern "C"' is needed */
+	    String *str = SwigType_str(ty, name);
+	    Printf(f_header, "extern \"C\" %s;\n", str);
+	    Delete(str);
+	  }
+	}
+      }
+    }
+    /* This needs to check qualifiers */
+    if (SwigType_isqualifier(ty)) {
+      SwigType *qual = SwigType_pop(ty);
+      Setattr(n, "qualifier", qual);
+      Delete(qual);
+    }
+    Delete(SwigType_pop_function(ty));
+    DohIncref(type);
+    Setattr(n, "type", ty);
+    if (GetFlag(n, "feature:onlychildren") && !GetFlag(n, "feature:ignore")) {
+      // Found an unignored templated method that has a an empty template instantiation (%template())
+      // Ignore it unless it has been %rename'd
+      if (Strncmp(symname, "__dummy_", 8) == 0) {
+        SetFlag(n, "feature:ignore");
+        Swig_warning(WARN_LANG_TEMPLATE_METHOD_IGNORE, input_file, line_number,
+                     "%%template() contains no name. Template method ignored: %s\n", SwigType_str(decl, SwigType_namestr(Getattr(n,"name"))));
+      }
+    }
+    if (!GetFlag(n, "feature:ignore"))
+      functionHandler(n);
+    Setattr(n, "type", type);
+    Delete(ty);
+    Delete(type);
+    return SWIG_OK;
+  } else {
+    /* Some kind of variable declaration */
+    String *declaration = Copy(decl);
+    Delattr(n, "decl");
+    if (Getattr(n, "nested"))
+      SetFlag(n, "feature:immutable");
+    if (!CurrentClass) {
+      if ((Cmp(storage, "extern") == 0) || ForceExtern) {
+	f_header = Swig_filebyname("header");
+	if (AddExtern) {
+	  if (f_header) {
+	    String *str = SwigType_str(ty, name);
+	    Printf(f_header, "extern %s;\n", str);
+	    Delete(str);
+	  }
+	}
+      }
+    }
+    if (!SwigType_ismutable(ty)) {
+      SetFlag(n, "feature:immutable");
+    }
+    /* If an array and elements are const, then read-only */
+    if (SwigType_isarray(ty)) {
+      SwigType *tya = SwigType_array_type(ty);
+      if (SwigType_isconst(tya)) {
+	SetFlag(n, "feature:immutable");
+      }
+      Delete(tya);
+    }
+    DohIncref(type);
+    Setattr(n, "type", ty);
+    variableHandler(n);
+    Setattr(n, "type", type);
+    Setattr(n, "decl", declaration);
+    Delete(ty);
+    Delete(type);
+    Delete(fullty);
+    return SWIG_OK;
+  }
+}
+
+/* ----------------------------------------------------------------------
+ * Language::functionHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::functionHandler(Node *n) {
+  String *storage = Getattr(n, "storage");
+  int isfriend = CurrentClass && Cmp(storage, "friend") == 0;
+  int isstatic = CurrentClass && Cmp(storage, "static") == 0 && !(SmartPointer && Getattr(n, "allocate:smartpointeraccess"));
+  Parm *p = Getattr(n, "parms");
+  if (GetFlag(n, "feature:del")) {
+    /* the method acts like a delete operator, ie, we need to disown the parameter */
+    if (CurrentClass && !isstatic && !isfriend) {
+      SetFlag(n, "feature:self:disown");
+    } else {
+      if (p)
+	SetFlag(p, "wrap:disown");
+    }
+  }
+  if (!CurrentClass) {
+    globalfunctionHandler(n);
+  } else {
+    if (isstatic) {
+      staticmemberfunctionHandler(n);
+    } else if (isfriend) {
+      globalfunctionHandler(n);
+    } else {
+      Node *explicit_n = 0;
+      if (directorsEnabled() && is_member_director(CurrentClass, n) && !extraDirectorProtectedCPPMethodsRequired()) {
+	bool virtual_but_not_pure_virtual = (!(Cmp(storage, "virtual")) && (Cmp(Getattr(n, "value"), "0") != 0));
+	if (virtual_but_not_pure_virtual) {
+	  // Add additional wrapper which makes an explicit call to the virtual method (ie not a virtual call)
+	  explicit_n = Copy(n);
+	  String *new_symname = Copy(Getattr(n, "sym:name"));
+	  String *suffix = Getattr(parentNode(n), "sym:name");
+	  Printv(new_symname, "SwigExplicit", suffix, NIL);
+	  Setattr(explicit_n, "sym:name", new_symname);
+	  Delattr(explicit_n, "storage");
+	  Delattr(explicit_n, "override");
+	  Delattr(explicit_n, "hides");
+	  SetFlag(explicit_n, "explicitcall");
+	  Setattr(n, "explicitcallnode", explicit_n);
+	}
+      }
+
+      memberfunctionHandler(n);
+
+      if (explicit_n) {
+	memberfunctionHandler(explicit_n);
+	Delattr(explicit_n, "explicitcall");
+	Delete(explicit_n);
+      }
+    }
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::globalfunctionHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::globalfunctionHandler(Node *n) {
+
+  Swig_require("globalfunctionHandler", n, "name", "sym:name", "type", "?parms", NIL);
+
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  ParmList *parms = Getattr(n, "parms");
+
+  /* Check for callback mode */
+  String *cb = GetFlagAttr(n, "feature:callback");
+  if (cb) {
+    String *cbname = Getattr(n, "feature:callback:name");
+    if (!cbname) {
+      cbname = NewStringf(cb, symname);
+      Setattr(n, "feature:callback:name", cbname);
+    }
+
+    callbackfunctionHandler(n);
+    if (Cmp(cbname, symname) == 0) {
+      Delete(cbname);
+      Swig_restore(n);
+      return SWIG_NOWRAP;
+    }
+    Delete(cbname);
+  }
+  Setattr(n, "parms", nonvoid_parms(parms));
+  String *call = Swig_cfunction_call(name, parms);
+  String *cres = Swig_cresult(type, "result", call);
+  Setattr(n, "wrap:action", cres);
+  Delete(cres);
+  Delete(call);
+  functionWrapper(n);
+
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::callbackfunctionHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::callbackfunctionHandler(Node *n) {
+  Swig_require("callbackfunctionHandler", n, "name", "*sym:name", "*type", "?value", NIL);
+  String *symname = Getattr(n, "sym:name");
+  String *type = Getattr(n, "type");
+  String *name = Getattr(n, "name");
+  String *parms = Getattr(n, "parms");
+  String *cb = GetFlagAttr(n, "feature:callback");
+  String *cbname = Getattr(n, "feature:callback:name");
+  String *calltype = NewStringf("(%s (*)(%s))(%s)", SwigType_str(type, 0), ParmList_str(parms), SwigType_namestr(name));
+  SwigType *cbty = Copy(type);
+  SwigType_add_function(cbty, parms);
+  SwigType_add_pointer(cbty);
+
+  if (!cbname) {
+    cbname = NewStringf(cb, symname);
+    Setattr(n, "feature:callback:name", cbname);
+  }
+
+  Setattr(n, "sym:name", cbname);
+  Setattr(n, "type", cbty);
+  Setattr(n, "value", calltype);
+
+  Node *ns = Getattr(symbols, cbname);
+  if (!ns)
+    constantWrapper(n);
+
+  Delete(cbname);
+  Delete(cbty);
+
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::memberfunctionHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::memberfunctionHandler(Node *n) {
+
+  Swig_require("memberfunctionHandler", n, "*name", "*sym:name", "*type", "?parms", "?value", NIL);
+
+  String *storage = Getattr(n, "storage");
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  String *value = Getattr(n, "value");
+  ParmList *parms = Getattr(n, "parms");
+  String *cb = GetFlagAttr(n, "feature:callback");
+
+  if (Cmp(storage, "virtual") == 0) {
+    if (Cmp(value, "0") == 0) {
+      IsVirtual = PURE_VIRTUAL;
+    } else {
+      IsVirtual = PLAIN_VIRTUAL;
+    }
+  } else {
+    IsVirtual = 0;
+  }
+  if (cb) {
+    Node *cbn = NewHash();
+    String *cbname = Getattr(n, "feature:callback:name");
+    if (!cbname) {
+      cbname = NewStringf(cb, symname);
+    }
+
+    SwigType *cbty = Copy(type);
+    SwigType_add_function(cbty, parms);
+    SwigType_add_memberpointer(cbty, ClassName);
+    String *cbvalue = NewStringf("&%s::%s", ClassName, name);
+    Setattr(cbn, "sym:name", cbname);
+    Setattr(cbn, "type", cbty);
+    Setattr(cbn, "value", cbvalue);
+    Setattr(cbn, "name", name);
+
+    memberconstantHandler(cbn);
+    Setattr(n, "feature:callback:name", Swig_name_member(ClassPrefix, cbname));
+
+    Delete(cb);
+    Delete(cbn);
+    Delete(cbvalue);
+    Delete(cbty);
+    Delete(cbname);
+    if (Cmp(cbname, symname) == 0) {
+      Swig_restore(n);
+      return SWIG_NOWRAP;
+    }
+  }
+
+  String *fname = Swig_name_member(ClassPrefix, symname);
+  if (Extend && SmartPointer) {
+    if (!Getattr(n, "classname")) {
+      Setattr(n, "classname", Getattr(CurrentClass, "allocate:smartpointerbase"));
+    }
+  }
+  // Set up the type for the cast to this class for use when wrapping const director (virtual) methods.
+  // Note: protected director methods or when allprotected mode turned on.
+  String *director_type = 0;
+  if (!is_public(n) && (is_member_director(CurrentClass, n) || GetFlag(n, "explicitcall") || is_non_virtual_protected_access(n))) {
+    director_type = Copy(DirectorClassName);
+    String *qualifier = Getattr(n, "qualifier");
+    if (qualifier)
+      SwigType_push(director_type, qualifier);
+    SwigType_add_pointer(director_type);
+  }
+
+  int DirectorExtraCall = 0;
+  if (directorsEnabled() && is_member_director(CurrentClass, n) && !SmartPointer)
+    if (extraDirectorProtectedCPPMethodsRequired())
+      DirectorExtraCall = CWRAP_DIRECTOR_TWO_CALLS;
+
+  if (GetFlag(n, "explicitcall"))
+    DirectorExtraCall = CWRAP_DIRECTOR_ONE_CALL;
+
+  Swig_MethodToFunction(n, ClassType, Getattr(n, "template") ? SmartPointer : Extend | SmartPointer | DirectorExtraCall, director_type,
+			is_member_director(CurrentClass, n));
+  Setattr(n, "sym:name", fname);
+
+  functionWrapper(n);
+
+  Delete(director_type);
+  Delete(fname);
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::staticmemberfunctionHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::staticmemberfunctionHandler(Node *n) {
+
+  Swig_require("staticmemberfunctionHandler", n, "*name", "*sym:name", "*type", NIL);
+  Swig_save("staticmemberfunctionHandler", n, "storage", NIL);
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  ParmList *parms = Getattr(n, "parms");
+  String *cb = GetFlagAttr(n, "feature:callback");
+  String *cname, *mrename;
+
+  if (!Extend) {
+    Node *sb = Getattr(n, "cplus:staticbase");
+    String *sname = Getattr(sb, "name");
+    if (is_non_virtual_protected_access(n))
+      cname = NewStringf("%s::%s", DirectorClassName, name);
+    else
+      cname = NewStringf("%s::%s", sname, name);
+  } else {
+    String *mname = Swig_name_mangle(ClassName);
+    cname = Swig_name_member(mname, name);
+    Delete(mname);
+  }
+  mrename = Swig_name_member(ClassPrefix, symname);
+
+  if (Extend) {
+    String *code = Getattr(n, "code");
+    String *defaultargs = Getattr(n, "defaultargs");
+    String *mangled = Swig_name_mangle(mrename);
+    Delete(mrename);
+    mrename = mangled;
+
+    if (Getattr(n, "sym:overloaded") && code) {
+      Append(cname, Getattr(defaultargs ? defaultargs : n, "sym:overname"));
+    }
+
+    if (!defaultargs && code) {
+      /* Hmmm. An added static member.  We have to create a little wrapper for this */
+      Swig_add_extension_code(n, cname, parms, type, code, CPlusPlus, 0);
+    }
+  }
+
+  Setattr(n, "name", cname);
+  Setattr(n, "sym:name", mrename);
+
+  if (cb) {
+    String *cbname = NewStringf(cb, symname);
+    Setattr(n, "feature:callback:name", Swig_name_member(ClassPrefix, cbname));
+    Setattr(n, "feature:callback:staticname", name);
+  }
+  Delattr(n, "storage");
+
+  globalfunctionHandler(n);
+
+  Delete(cname);
+  Delete(mrename);
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::variableHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::variableHandler(Node *n) {
+
+  /* If not a smart-pointer access or added method. We clear
+     feature:except.   There is no way C++ or C would throw
+     an exception merely for accessing a member data.
+
+     Caveat:  Some compilers seem to route attribute access through
+     methods which can generate exceptions.  The feature:allowexcept
+     allows this. Also, the feature:exceptvar can be used to match
+     only variables.
+   */
+  if (!(Extend | SmartPointer)) {
+    if (!GetFlag(n, "feature:allowexcept")) {
+      UnsetFlag(n, "feature:except");
+    }
+    if (Getattr(n, "feature:exceptvar")) {
+      Setattr(n, "feature:except", Getattr(n, "feature:exceptvar"));
+    }
+  }
+
+  if (!CurrentClass) {
+    globalvariableHandler(n);
+  } else {
+    String *storage = Getattr(n, "storage");
+    Swig_save("variableHandler", n, "feature:immutable", NIL);
+    if (SmartPointer) {
+      /* If a smart-pointer and it's a constant access, we have to set immutable */
+      if (Getattr(CurrentClass, "allocate:smartpointerconst")) {
+	SetFlag(n, "feature:immutable");
+      }
+    }
+    if ((Cmp(storage, "static") == 0) && !(SmartPointer && Getattr(n, "allocate:smartpointeraccess"))) {
+      staticmembervariableHandler(n);
+    } else {
+      membervariableHandler(n);
+    }
+    Swig_restore(n);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::globalvariableHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::globalvariableHandler(Node *n) {
+  variableWrapper(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::membervariableHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::membervariableHandler(Node *n) {
+
+  Swig_require("membervariableHandler", n, "*name", "*sym:name", "*type", NIL);
+  Swig_save("membervariableHandler", n, "parms", NIL);
+
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+
+  if (!AttributeFunctionGet) {
+    String *mname = Swig_name_member(ClassPrefix, symname);
+    String *mrename_get = Swig_name_get(mname);
+    String *mrename_set = Swig_name_set(mname);
+    Delete(mname);
+
+    /* Create a function to set the value of the variable */
+
+    int assignable = is_assignable(n);
+
+    if (SmartPointer) {
+      if (Getattr(CurrentClass, "allocate:smartpointerconst")) {
+	assignable = 0;
+      }
+    }
+
+    if (assignable) {
+      int make_set_wrapper = 1;
+      String *tm = 0;
+      String *target = 0;
+      if (!Extend) {
+	if (SmartPointer) {
+	  if (checkAttribute(n, "storage", "static")) {
+	    Node *sn = Getattr(n, "cplus:staticbase");
+	    String *base = Getattr(sn, "name");
+	    target = NewStringf("%s::%s", base, name);
+	  } else {
+	    String *pname = Swig_cparm_name(0, 0);
+	    target = NewStringf("(*%s)->%s", pname, name);
+	    Delete(pname);
+	  }
+	} else {
+	  String *pname = is_non_virtual_protected_access(n) ? NewString("darg") : Swig_cparm_name(0, 0);
+	  target = NewStringf("%s->%s", pname, name);
+	  Delete(pname);
+	}
+	tm = Swig_typemap_lookup("memberin", n, target, 0);
+      }
+      int flags = Extend | SmartPointer | use_naturalvar_mode(n);
+      if (is_non_virtual_protected_access(n))
+        flags = flags | CWRAP_ALL_PROTECTED_ACCESS;
+
+      Swig_MembersetToFunction(n, ClassType, flags);
+      Setattr(n, "memberset", "1");
+      if (!Extend) {
+	/* Check for a member in typemap here */
+
+	if (!tm) {
+	  if (SwigType_isarray(type)) {
+	    Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(type, 0));
+	    make_set_wrapper = 0;
+	  }
+	} else {
+	  String *pname0 = Swig_cparm_name(0, 0);
+	  String *pname1 = Swig_cparm_name(0, 1);
+	  Replace(tm, "$source", pname1, DOH_REPLACE_ANY);
+	  Replace(tm, "$target", target, DOH_REPLACE_ANY);
+	  Replace(tm, "$input", pname1, DOH_REPLACE_ANY);
+	  Replace(tm, "$self", pname0, DOH_REPLACE_ANY);
+	  Setattr(n, "wrap:action", tm);
+	  Delete(tm);
+	  Delete(pname0);
+	  Delete(pname1);
+	}
+	Delete(target);
+      }
+      if (make_set_wrapper) {
+	Setattr(n, "sym:name", mrename_set);
+	functionWrapper(n);
+      } else {
+	SetFlag(n, "feature:immutable");
+      }
+      /* Restore parameters */
+      Setattr(n, "type", type);
+      Setattr(n, "name", name);
+      Setattr(n, "sym:name", symname);
+
+      /* Delete all attached typemaps and typemap attributes */
+      Iterator ki;
+      for (ki = First(n); ki.key; ki = Next(ki)) {
+	if (Strncmp(ki.key, "tmap:", 5) == 0)
+	  Delattr(n, ki.key);
+      }
+    }
+    /* Emit get function */
+    {
+      int flags = Extend | SmartPointer | use_naturalvar_mode(n);
+      if (is_non_virtual_protected_access(n))
+        flags = flags | CWRAP_ALL_PROTECTED_ACCESS;
+      Swig_MembergetToFunction(n, ClassType, flags);
+      Setattr(n, "sym:name", mrename_get);
+      Setattr(n, "memberget", "1");
+      functionWrapper(n);
+    }
+    Delete(mrename_get);
+    Delete(mrename_set);
+
+  } else {
+
+    /* This code is used to support the attributefunction directive 
+       where member variables are converted automagically to 
+       accessor functions */
+
+#if 0
+    Parm *p;
+    String *gname;
+    SwigType *vty;
+    p = NewParm(type, 0);
+    gname = NewStringf(AttributeFunctionGet, symname);
+    if (!Extend) {
+      ActionFunc = Copy(Swig_cmemberget_call(name, type));
+      cpp_member_func(Char(gname), Char(gname), type, 0);
+      Delete(ActionFunc);
+    } else {
+      String *cname = Swig_name_get(name);
+      cpp_member_func(Char(cname), Char(gname), type, 0);
+      Delete(cname);
+    }
+    Delete(gname);
+    if (!GetFlag(n, "feature:immutable")) {
+      gname = NewStringf(AttributeFunctionSet, symname);
+      vty = NewString("void");
+      if (!Extend) {
+	ActionFunc = Copy(Swig_cmemberset_call(name, type));
+	cpp_member_func(Char(gname), Char(gname), vty, p);
+	Delete(ActionFunc);
+      } else {
+	String *cname = Swig_name_set(name);
+	cpp_member_func(Char(cname), Char(gname), vty, p);
+	Delete(cname);
+      }
+      Delete(gname);
+    }
+    ActionFunc = 0;
+#endif
+  }
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::staticmembervariableHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::staticmembervariableHandler(Node *n) {
+  Swig_require("staticmembervariableHandler", n, "*name", "*sym:name", "*type", "?value", NIL);
+  String *value = Getattr(n, "value");
+  String *classname = !SmartPointer ? (is_non_virtual_protected_access(n) ? DirectorClassName : ClassName) : Getattr(CurrentClass, "allocate:smartpointerbase");
+
+  if (!value || !Getattr(n, "hasconsttype")) {
+    String *name = Getattr(n, "name");
+    String *symname = Getattr(n, "sym:name");
+    String *cname, *mrename;
+
+    /* Create the variable name */
+    mrename = Swig_name_member(ClassPrefix, symname);
+    cname = NewStringf("%s::%s", classname, name);
+
+    Setattr(n, "sym:name", mrename);
+    Setattr(n, "name", cname);
+
+    /* Wrap as an ordinary global variable */
+    variableWrapper(n);
+
+    Delete(mrename);
+    Delete(cname);
+  } else {
+
+    /* This is a C++ static member declaration with an initializer and it's const.
+       Certain C++ compilers optimize this out so that there is no linkage to a
+       memory address.  Example:
+
+       class Foo {
+       public:
+         static const int x = 3;
+       };
+
+       Some discussion of this in section 9.4 of the C++ draft standard.
+
+       Also, we have to manage the case:
+
+       class Foo {
+       public:
+       %extend {
+         static const int x = 3;
+       }
+       };
+
+       in which there's no actual Foo::x variable to refer to. In this case,
+       the best we can do is to wrap the given value verbatim.
+     */
+
+
+    String *name = Getattr(n, "name");
+    String *cname = NewStringf("%s::%s", classname, name);
+    if (Extend) {
+      /* the variable is a synthesized one.
+         There's nothing we can do; we just keep the given value */
+    } else {
+      /* we refer to the value as Foo::x */
+      String *value = SwigType_namestr(cname);
+      Setattr(n, "value", value);
+    }
+
+    SwigType *t1 = SwigType_typedef_resolve_all(Getattr(n, "type"));
+    SwigType *t2 = SwigType_strip_qualifiers(t1);
+    Setattr(n, "type", t2);
+    Delete(t1);
+    Delete(t2);
+    SetFlag(n, "wrappedasconstant");
+    memberconstantHandler(n);
+    Delete(cname);
+  }
+
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+
+/* ----------------------------------------------------------------------
+ * Language::externDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::externDeclaration(Node *n) {
+  return emit_children(n);
+}
+
+/* ----------------------------------------------------------------------
+ * Language::enumDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::enumDeclaration(Node *n) {
+  if (!ImportMode) {
+    emit_children(n);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::enumvalueDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::enumvalueDeclaration(Node *n) {
+  if (CurrentClass && (cplus_mode != PUBLIC))
+    return SWIG_NOWRAP;
+
+  Swig_require("enumvalueDeclaration", n, "*name", "?value", NIL);
+  String *value = Getattr(n, "value");
+  String *name = Getattr(n, "name");
+  String *tmpValue;
+
+  if (value)
+    tmpValue = NewString(value);
+  else
+    tmpValue = NewString(name);
+  Setattr(n, "value", tmpValue);
+
+  if (!CurrentClass || !cparse_cplusplus) {
+    Setattr(n, "name", tmpValue);	/* for wrapping of enums in a namespace when emit_action is used */
+    constantWrapper(n);
+  } else {
+    memberconstantHandler(n);
+  }
+
+  Delete(tmpValue);
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::enumforwardDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::enumforwardDeclaration(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * Language::memberconstantHandler()
+ * ----------------------------------------------------------------------------- */
+
+int Language::memberconstantHandler(Node *n) {
+
+  Swig_require("memberconstantHandler", n, "*name", "*sym:name", "value", NIL);
+
+  if (!GetFlag(n, "feature:allowexcept")) {
+    UnsetFlag(n, "feature:except");
+  }
+  if (Getattr(n, "feature:exceptvar")) {
+    Setattr(n, "feature:except", Getattr(n, "feature:exceptvar"));
+  }
+
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+  String *value = Getattr(n, "value");
+
+  String *mrename = Swig_name_member(ClassPrefix, symname);
+  Setattr(n, "sym:name", mrename);
+
+  String *new_name = 0;
+  if (Extend)
+    new_name = Copy(value);
+  else
+    new_name = NewStringf("%s::%s", is_non_virtual_protected_access(n) ? DirectorClassName : ClassName, name);
+  Setattr(n, "name", new_name);
+
+  constantWrapper(n);
+  Delete(mrename);
+  Delete(new_name);
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::typedefHandler() 
+ * ---------------------------------------------------------------------- */
+
+int Language::typedefHandler(Node *n) {
+  /* since this is a recurring issue, we are going to remember the
+     typedef pointer, if already it is not a pointer or reference, as
+     in
+
+     typedef void NT;
+     int func(NT *p); 
+
+     see director_basic.i for example.
+   */
+  SwigType *name = Getattr(n, "name");
+  SwigType *decl = Getattr(n, "decl");
+  if (!SwigType_ispointer(decl) && !SwigType_isreference(decl)) {
+    SwigType *pname = Copy(name);
+    SwigType_add_pointer(pname);
+    SwigType_remember(pname);
+    Delete(pname);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorMethod()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorMethod(Node *n, Node *parent, String *super) {
+  (void) n;
+  (void) parent;
+  (void) super;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorConstructor()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorConstructor(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorDefaultConstructor()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorDefaultConstructor(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+static String *vtable_method_id(Node *n) {
+  String *nodeType = Getattr(n, "nodeType");
+  int is_destructor = (Cmp(nodeType, "destructor") == 0);
+  if (is_destructor)
+    return 0;
+  String *name = Getattr(n, "name");
+  String *decl = Getattr(n, "decl");
+  String *local_decl = SwigType_typedef_resolve_all(decl);
+  String *tmp = SwigType_pop_function(local_decl);
+  Delete(local_decl);
+  local_decl = tmp;
+  Node *method_id = NewStringf("%s|%s", name, local_decl);
+  Delete(local_decl);
+  return method_id;
+}
+
+
+/* ----------------------------------------------------------------------
+ * Language::unrollVirtualMethods()
+ * ---------------------------------------------------------------------- */
+int Language::unrollVirtualMethods(Node *n, Node *parent, List *vm, int default_director, int &virtual_destructor, int protectedbase) {
+  Node *ni;
+  String *nodeType;
+  String *classname;
+  String *decl;
+  bool first_base = false;
+  // recurse through all base classes to build the vtable
+  List *bl = Getattr(n, "bases");
+  if (bl) {
+    Iterator bi;
+    for (bi = First(bl); bi.item; bi = Next(bi)) {
+      if (first_base && !director_multiple_inheritance)
+	break;
+      unrollVirtualMethods(bi.item, parent, vm, default_director, virtual_destructor);
+      first_base = true;
+    }
+  }
+  // recurse through all protected base classes to build the vtable, as needed
+  bl = Getattr(n, "protectedbases");
+  if (bl) {
+    Iterator bi;
+    for (bi = First(bl); bi.item; bi = Next(bi)) {
+      if (first_base && !director_multiple_inheritance)
+	break;
+      unrollVirtualMethods(bi.item, parent, vm, default_director, virtual_destructor, 1);
+      first_base = true;
+    }
+  }
+  // find the methods that need directors
+  classname = Getattr(n, "name");
+  for (ni = Getattr(n, "firstChild"); ni; ni = nextSibling(ni)) {
+    /* we only need to check the virtual members */
+    if (!checkAttribute(ni, "storage", "virtual"))
+      continue;
+    nodeType = Getattr(ni, "nodeType");
+    /* we need to add methods(cdecl) and destructor (to check for throw decl) */
+    int is_destructor = (Cmp(nodeType, "destructor") == 0);
+    if ((Cmp(nodeType, "cdecl") == 0) || is_destructor) {
+      decl = Getattr(ni, "decl");
+      /* extra check for function type and proper access */
+      if (SwigType_isfunction(decl) && (((!protectedbase || dirprot_mode()) && is_public(ni)) || need_nonpublic_member(ni))) {
+	String *name = Getattr(ni, "name");
+	Node *method_id = is_destructor ? NewStringf("~destructor") : vtable_method_id(ni);
+	/* Make sure that the new method overwrites the existing: */
+	int len = Len(vm);
+	const int DO_NOT_REPLACE = -1;
+	int replace = DO_NOT_REPLACE;
+	for (int i = 0; i < len; i++) {
+	  Node *item = Getitem(vm, i);
+	  String *check_vmid = Getattr(item, "vmid");
+
+	  if (Strcmp(method_id, check_vmid) == 0) {
+	    replace = i;
+	    break;
+	  }
+	}
+	/* filling a new method item */
+	String *fqdname = NewStringf("%s::%s", classname, name);
+	Hash *item = NewHash();
+	Setattr(item, "fqdname", fqdname);
+	Node *m = Copy(ni);
+
+	/* Store the complete return type - needed for non-simple return types (pointers, references etc.) */
+	SwigType *ty = NewString(Getattr(m, "type"));
+	SwigType_push(ty, decl);
+	if (SwigType_isqualifier(ty)) {
+	  Delete(SwigType_pop(ty));
+	}
+	Delete(SwigType_pop_function(ty));
+	Setattr(m, "returntype", ty);
+
+	String *mname = NewStringf("%s::%s", Getattr(parent, "name"), name);
+	/* apply the features of the original method found in the base class */
+	Swig_features_get(Swig_cparse_features(), 0, mname, Getattr(m, "decl"), m);
+	Setattr(item, "methodNode", m);
+	Setattr(item, "vmid", method_id);
+	if (replace == DO_NOT_REPLACE)
+	  Append(vm, item);
+	else
+	  Setitem(vm, replace, item);
+
+	Delete(mname);
+      }
+      if (is_destructor) {
+	virtual_destructor = 1;
+      }
+    }
+  }
+
+  /*
+     We delete all the nodirector methods. This prevents the
+     generation of 'empty' director classes.
+
+     But this has to be done outside the previous 'for'
+     an the recursive loop!.
+   */
+  if (n == parent) {
+    int len = Len(vm);
+    for (int i = 0; i < len; i++) {
+      Node *item = Getitem(vm, i);
+      Node *m = Getattr(item, "methodNode");
+      /* retrieve the director features */
+      int mdir = GetFlag(m, "feature:director");
+      int mndir = GetFlag(m, "feature:nodirector");
+      /* 'nodirector' has precedence over 'director' */
+      int dir = (mdir || mndir) ? (mdir && !mndir) : 1;
+      /* check if the method was found only in a base class */
+      Node *p = Getattr(m, "parentNode");
+      if (p != n) {
+	Node *c = Copy(m);
+	Setattr(c, "parentNode", n);
+	int cdir = GetFlag(c, "feature:director");
+	int cndir = GetFlag(c, "feature:nodirector");
+	dir = (cdir || cndir) ? (cdir && !cndir) : dir;
+	Delete(c);
+      }
+      if (dir) {
+	/* be sure the 'nodirector' feature is disabled  */
+	if (mndir)
+	  Delattr(m, "feature:nodirector");
+      } else {
+	/* or just delete from the vm, since is not a director method */
+	Delitem(vm, i);
+	len--;
+	i--;
+      }
+    }
+  }
+
+  return SWIG_OK;
+}
+
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorDisown()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorDisown(Node *n) {
+  Node *disown = NewHash();
+  String *mrename;
+  String *symname = Getattr(n, "sym:name");
+  mrename = Swig_name_disown(symname);	//Getattr(n, "name"));
+  String *type = NewString(ClassType);
+  String *name = NewString("self");
+  SwigType_add_pointer(type);
+  Parm *p = NewParm(type, name);
+  Delete(name);
+  Delete(type);
+  type = NewString("void");
+  String *action = NewString("");
+  Printv(action, "{\n", "Swig::Director *director = dynamic_cast<Swig::Director *>(arg1);\n", "if (director) director->swig_disown();\n", "}\n", NULL);
+  Setattr(disown, "wrap:action", action);
+  Setattr(disown, "name", mrename);
+  Setattr(disown, "sym:name", mrename);
+  Setattr(disown, "type", type);
+  Setattr(disown, "parms", p);
+  Delete(action);
+  Delete(mrename);
+  Delete(type);
+  Delete(p);
+
+  functionWrapper(disown);
+  Delete(disown);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorConstructors()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorConstructors(Node *n) {
+  Node *ni;
+  String *nodeType;
+  Node *parent = Swig_methodclass(n);
+  int default_ctor = Getattr(parent, "allocate:default_constructor") ? 1 : 0;
+  int protected_ctor = 0;
+  int constructor = 0;
+
+  /* emit constructors */
+  for (ni = Getattr(n, "firstChild"); ni; ni = nextSibling(ni)) {
+    nodeType = Getattr(ni, "nodeType");
+    if (Cmp(nodeType, "constructor") == 0) {
+      Parm *parms = Getattr(ni, "parms");
+      if (is_public(ni)) {
+	/* emit public constructor */
+	classDirectorConstructor(ni);
+	constructor = 1;
+	if (default_ctor)
+	  default_ctor = !ParmList_numrequired(parms);
+      } else {
+	/* emit protected constructor if needed */
+	if (need_nonpublic_ctor(ni)) {
+	  classDirectorConstructor(ni);
+	  constructor = 1;
+	  protected_ctor = 1;
+	  if (default_ctor)
+	    default_ctor = !ParmList_numrequired(parms);
+	}
+      }
+    }
+  }
+  /* emit default constructor if needed */
+  if (!constructor) {
+    if (!default_ctor) {
+      /* we get here because the class has no public, protected or
+         default constructor, therefore, the director class can't be
+         created, ie, is kind of abstract. */
+      Swig_warning(WARN_LANG_DIRECTOR_ABSTRACT, Getfile(n), Getline(n), "Director class '%s' can't be constructed\n", SwigType_namestr(Getattr(n, "name")));
+      return SWIG_OK;
+    }
+    classDirectorDefaultConstructor(n);
+    default_ctor = 1;
+  }
+  /* this is just to support old java behavior, ie, the default
+     constructor is always emitted, even when protected, and not
+     needed, since there is a public constructor already defined.  
+
+     (scottm) This code is needed here to make the director_abstract +
+     test generate compileable code (Example2 in director_abastract.i).
+
+     (mmatus) This is very strange, since swig compiled with gcc3.2.3
+     doesn't need it here....
+   */
+  if (!default_ctor && !protected_ctor) {
+    if (Getattr(parent, "allocate:default_base_constructor")) {
+      classDirectorDefaultConstructor(n);
+    }
+  }
+
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorMethods()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorMethods(Node *n) {
+  Node *vtable = Getattr(n, "vtable");
+
+  int len = Len(vtable);
+  for (int i = 0; i < len; i++) {
+    Node *item = Getitem(vtable, i);
+    String *method = Getattr(item, "methodNode");
+    String *fqdname = Getattr(item, "fqdname");
+    if (GetFlag(method, "feature:nodirector"))
+      continue;
+
+    String *type = Getattr(method, "nodeType");
+    if (!Cmp(type, "destructor")) {
+      classDirectorDestructor(method);
+    } else {
+      if (classDirectorMethod(method, n, fqdname) == SWIG_OK) {
+	Setattr(item, "director", "1");
+      }
+    }
+  }
+
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorInit()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorInit(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorDestructor()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorDestructor(Node *n) {
+  /* 
+     Always emit the virtual destructor in the declaration and in the
+     compilation unit.  Been explicit here can't make any damage, and
+     can solve some nasty C++ compiler problems.
+   */
+  File *f_directors = Swig_filebyname("director");
+  File *f_directors_h = Swig_filebyname("director_h");
+  if (Getattr(n, "throw")) {
+    Printf(f_directors_h, "    virtual ~%s() throw ();\n", DirectorClassName);
+    Printf(f_directors, "%s::~%s() throw () {\n}\n\n", DirectorClassName, DirectorClassName);
+  } else {
+    Printf(f_directors_h, "    virtual ~%s();\n", DirectorClassName);
+    Printf(f_directors, "%s::~%s() {\n}\n\n", DirectorClassName, DirectorClassName);
+  }
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirectorEnd()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirectorEnd(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDirector()
+ * ---------------------------------------------------------------------- */
+
+int Language::classDirector(Node *n) {
+  Node *module = Getattr(n, "module");
+  String *classtype = Getattr(n, "classtype");
+  Hash *directormap = 0;
+  if (module) {
+    directormap = Getattr(module, "wrap:directormap");
+    if (directormap == 0) {
+      directormap = NewHash();
+      Setattr(module, "wrap:directormap", directormap);
+    }
+  }
+  List *vtable = NewList();
+  int virtual_destructor = 0;
+  unrollVirtualMethods(n, n, vtable, 0, virtual_destructor);
+
+  // Emit all the using base::member statements for non virtual members (allprotected mode)
+  Node *ni;
+  String *using_protected_members_code = NewString("");
+  for (ni = Getattr(n, "firstChild"); ni; ni = nextSibling(ni)) {
+    Node *nodeType = Getattr(ni, "nodeType");
+    bool cdeclaration = (Cmp(nodeType, "cdecl") == 0);
+    if (cdeclaration && !GetFlag(ni, "feature:ignore")) {
+      if (is_non_virtual_protected_access(ni)) {
+        Node *overloaded = Getattr(ni, "sym:overloaded");
+        // emit the using base::member statement (but only once if the method is overloaded)
+        if (!overloaded || (overloaded && (overloaded == ni)))
+          Printf(using_protected_members_code, "    using %s::%s;\n", SwigType_namestr(ClassName), Getattr(ni, "name"));
+      }
+    }
+  }
+
+  if (virtual_destructor || Len(vtable) > 0) {
+    if (!virtual_destructor) {
+      String *classtype = Getattr(n, "classtype");
+      Swig_warning(WARN_LANG_DIRECTOR_VDESTRUCT, input_file, line_number, "Director base class %s has no virtual destructor.\n", classtype);
+    }
+
+    Setattr(n, "vtable", vtable);
+    if (directormap != 0) {
+      Setattr(directormap, classtype, n);
+    }
+    classDirectorInit(n);
+    classDirectorConstructors(n);
+    classDirectorMethods(n);
+
+    File *f_directors_h = Swig_filebyname("director_h");
+    Printv(f_directors_h, using_protected_members_code, NIL);
+
+    classDirectorEnd(n);
+  }
+  Delete(vtable);
+  Delete(using_protected_members_code);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classDeclaration()
+ * ---------------------------------------------------------------------- */
+
+static void addCopyConstructor(Node *n) {
+  Node *cn = NewHash();
+  set_nodeType(cn, "constructor");
+  Setattr(cn, "access", "public");
+  Setfile(cn, Getfile(n));
+  Setline(cn, Getline(n));
+
+  String *cname = Getattr(n, "name");
+  SwigType *type = Copy(cname);
+  String *last = Swig_scopename_last(cname);
+  String *name = NewStringf("%s::%s", cname, last);
+  String *cc = NewStringf("r.q(const).%s", type);
+  String *decl = NewStringf("f(%s).", cc);
+  String *csymname = Getattr(n, "sym:name");
+  String *oldname = csymname;
+
+  if (Getattr(n, "allocate:has_constructor")) {
+    // to work properly with '%rename Class', we must look
+    // for any other constructor in the class, which has not been
+    // renamed, and use its name as oldname.
+    Node *c;
+    for (c = firstChild(n); c; c = nextSibling(c)) {
+      const char *tag = Char(nodeType(c));
+      if (strcmp(tag, "constructor") == 0) {
+	String *cname = Getattr(c, "name");
+	String *csname = Getattr(c, "sym:name");
+	String *clast = Swig_scopename_last(cname);
+	if (Equal(csname, clast)) {
+	  oldname = csname;
+	  break;
+	}
+      }
+    }
+  }
+
+  String *symname = Swig_name_make(cn, cname, last, decl, oldname);
+  if (Strcmp(symname, "$ignore") != 0) {
+    if (!symname) {
+      symname = Copy(csymname);
+    }
+    Parm *p = NewParm(cc, "other");
+
+    Setattr(cn, "name", name);
+    Setattr(cn, "sym:name", symname);
+    SetFlag(cn, "feature:new");
+    Setattr(cn, "decl", decl);
+    Setattr(cn, "parentNode", n);
+    Setattr(cn, "parms", p);
+    Setattr(cn, "copy_constructor", "1");
+
+    Symtab *oldscope = Swig_symbol_setscope(Getattr(n, "symtab"));
+    Node *on = Swig_symbol_add(symname, cn);
+    Swig_symbol_setscope(oldscope);
+    Swig_features_get(Swig_cparse_features(), 0, name, decl, cn);
+
+    if (on == cn) {
+      Node *access = NewHash();
+      set_nodeType(access, "access");
+      Setattr(access, "kind", "public");
+      appendChild(n, access);
+      appendChild(n, cn);
+      Setattr(n, "has_copy_constructor", "1");
+      Setattr(n, "copy_constructor_decl", decl);
+      Setattr(n, "allocate:copy_constructor", "1");
+      Delete(access);
+    }
+  }
+  Delete(cn);
+  Delete(last);
+  Delete(name);
+  Delete(decl);
+  Delete(symname);
+}
+
+static void addDefaultConstructor(Node *n) {
+  Node *cn = NewHash();
+  set_nodeType(cn, "constructor");
+  Setattr(cn, "access", "public");
+  Setfile(cn, Getfile(n));
+  Setline(cn, Getline(n));
+
+  String *cname = Getattr(n, "name");
+  String *last = Swig_scopename_last(cname);
+  String *name = NewStringf("%s::%s", cname, last);
+  String *decl = NewString("f().");
+  String *csymname = Getattr(n, "sym:name");
+  String *oldname = csymname;
+  String *symname = Swig_name_make(cn, cname, last, decl, oldname);
+  if (Strcmp(symname, "$ignore") != 0) {
+    if (!symname) {
+      symname = Copy(csymname);
+    }
+
+    Setattr(cn, "name", name);
+    Setattr(cn, "sym:name", symname);
+    SetFlag(cn, "feature:new");
+    Setattr(cn, "decl", decl);
+    Setattr(cn, "parentNode", n);
+    Setattr(cn, "default_constructor", "1");
+
+    Symtab *oldscope = Swig_symbol_setscope(Getattr(n, "symtab"));
+    Node *on = Swig_symbol_add(symname, cn);
+    Swig_symbol_setscope(oldscope);
+    Swig_features_get(Swig_cparse_features(), 0, name, decl, cn);
+
+    if (on == cn) {
+      Node *access = NewHash();
+      set_nodeType(access, "access");
+      Setattr(access, "kind", "public");
+      appendChild(n, access);
+      appendChild(n, cn);
+      Setattr(n, "has_default_constructor", "1");
+      Setattr(n, "allocate:default_constructor", "1");
+      Delete(access);
+    }
+  }
+  Delete(cn);
+  Delete(last);
+  Delete(name);
+  Delete(decl);
+  Delete(symname);
+}
+
+static void addDestructor(Node *n) {
+  Node *cn = NewHash();
+  set_nodeType(cn, "destructor");
+  Setattr(cn, "access", "public");
+  Setfile(cn, Getfile(n));
+  Setline(cn, Getline(n));
+
+  String *cname = Getattr(n, "name");
+  String *last = Swig_scopename_last(cname);
+  Insert(last, 0, "~");
+  String *name = NewStringf("%s::%s", cname, last);
+  String *decl = NewString("f().");
+  String *symname = Swig_name_make(cn, cname, last, decl, 0);
+  if (Strcmp(symname, "$ignore") != 0) {
+    if (!symname) {
+      symname = NewStringf("~%s", Getattr(n, "sym:name"));
+    }
+
+    Setattr(cn, "name", name);
+    Setattr(cn, "sym:name", symname);
+    Setattr(cn, "decl", "f().");
+    Setattr(cn, "parentNode", n);
+
+    Symtab *oldscope = Swig_symbol_setscope(Getattr(n, "symtab"));
+    Node *on = Swig_symbol_add(symname, cn);
+    Swig_symbol_setscope(oldscope);
+    Swig_features_get(Swig_cparse_features(), 0, name, decl, cn);
+
+    if (on == cn) {
+      Node *access = NewHash();
+      set_nodeType(access, "access");
+      Setattr(access, "kind", "public");
+      appendChild(n, access);
+      appendChild(n, cn);
+      Setattr(n, "has_destructor", "1");
+      Setattr(n, "allocate:destructor", "1");
+      Delete(access);
+    }
+  }
+  Delete(cn);
+  Delete(last);
+  Delete(name);
+  Delete(decl);
+  Delete(symname);
+}
+
+int Language::classDeclaration(Node *n) {
+  String *ochildren = Getattr(n, "feature:onlychildren");
+  if (ochildren) {
+    Setattr(n, "feature:emitonlychildren", ochildren);
+    emit_children(n);
+    Delattr(n, "feature:emitonlychildren");
+    SetFlag(n, "feature:ignore");
+    return SWIG_NOWRAP;
+  }
+
+  String *kind = Getattr(n, "kind");
+  String *name = Getattr(n, "name");
+  String *tdname = Getattr(n, "tdname");
+  String *symname = Getattr(n, "sym:name");
+
+  char *classname = tdname ? Char(tdname) : Char(name);
+  char *iname = Char(symname);
+  int strip = (tdname || CPlusPlus) ? 1 : 0;
+
+
+  if (!classname) {
+    Swig_warning(WARN_LANG_CLASS_UNNAMED, input_file, line_number, "Can't generate wrappers for unnamed struct/class.\n");
+    return SWIG_NOWRAP;
+  }
+
+  /* Check symbol name for template.   If not renamed. Issue a warning */
+  if (!validIdentifier(symname)) {
+    Swig_warning(WARN_LANG_IDENTIFIER, input_file, line_number, "Can't wrap class %s unless renamed to a valid identifier.\n", SwigType_namestr(symname));
+    return SWIG_NOWRAP;
+  }
+
+  Swig_save("classDeclaration", n, "name", NIL);
+  Setattr(n, "name", classname);
+
+  if (Cmp(kind, "class") == 0) {
+    cplus_mode = PRIVATE;
+  } else {
+    cplus_mode = PUBLIC;
+  }
+
+  ClassName = NewString(classname);
+  ClassPrefix = NewString(iname);
+  if (strip) {
+    ClassType = NewString(classname);
+  } else {
+    ClassType = NewStringf("%s %s", kind, classname);
+  }
+  Setattr(n, "classtypeobj", Copy(ClassType));
+  Setattr(n, "classtype", SwigType_namestr(ClassType));
+
+  InClass = 1;
+  CurrentClass = n;
+
+
+  /* Call classHandler() here */
+  if (!ImportMode) {
+    int dir = 0;
+    if (directorsEnabled()) {
+      int ndir = GetFlag(n, "feature:director");
+      int nndir = GetFlag(n, "feature:nodirector");
+      /* 'nodirector' has precedence over 'director' */
+      dir = (ndir || nndir) ? (ndir && !nndir) : 0;
+    }
+    int abstract = !dir && abstractClassTest(n);
+    int odefault = (GenerateDefault && !GetFlag(n, "feature:nodefault"));
+
+    /* default constructor */
+    if (!abstract && !GetFlag(n, "feature:nodefaultctor") && odefault) {
+      if (!Getattr(n, "has_constructor") && !Getattr(n, "allocate:has_constructor") && (Getattr(n, "allocate:default_constructor"))) {
+	addDefaultConstructor(n);
+      }
+    }
+    /* copy constructor */
+    if (CPlusPlus && !abstract && GetFlag(n, "feature:copyctor")) {
+      if (!Getattr(n, "has_copy_constructor") && !Getattr(n, "allocate:has_copy_constructor")
+	  && (Getattr(n, "allocate:copy_constructor"))
+	  && (!GetFlag(n, "feature:ignore"))) {
+	addCopyConstructor(n);
+      }
+    }
+    /* default destructor */
+    if (!GetFlag(n, "feature:nodefaultdtor") && odefault) {
+      if (!Getattr(n, "has_destructor") && (!Getattr(n, "allocate:has_destructor"))
+	  && (Getattr(n, "allocate:default_destructor"))
+	  && (!GetFlag(n, "feature:ignore"))) {
+	addDestructor(n);
+      }
+    }
+
+    if (dir) {
+      DirectorClassName = NewStringf("SwigDirector_%s", symname);
+      classDirector(n);
+    }
+    /* check for abstract after resolving directors */
+    Abstract = abstractClassTest(n);
+
+    classHandler(n);
+  } else {
+    Abstract = abstractClassTest(n);
+    Language::classHandler(n);
+  }
+
+  InClass = 0;
+  CurrentClass = 0;
+  Delete(ClassType);
+  ClassType = 0;
+  Delete(ClassPrefix);
+  ClassPrefix = 0;
+  Delete(ClassName);
+  ClassName = 0;
+  Delete(DirectorClassName);
+  DirectorClassName = 0;
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::classHandler(Node *n) {
+
+  bool hasDirector = Swig_directorclass(n) ? true : false;
+
+  /* Emit all of the class members */
+  emit_children(n);
+
+  /* Look for smart pointer handling */
+  if (Getattr(n, "allocate:smartpointer")) {
+    List *methods = Getattr(n, "allocate:smartpointer");
+    cplus_mode = PUBLIC;
+    SmartPointer = CWRAP_SMART_POINTER;
+    Iterator c;
+    for (c = First(methods); c.item; c = Next(c)) {
+      emit_one(c.item);
+    }
+    SmartPointer = 0;
+  }
+
+  cplus_mode = PUBLIC;
+
+  /* emit director disown method */
+  if (hasDirector) {
+    classDirectorDisown(n);
+
+    /* Emit additional protected virtual methods - only needed if the language module
+     * codes logic in the C++ layer instead of the director proxy class method - primarily
+     * to catch public use of protected methods by the scripting languages. */
+    if (dirprot_mode() && extraDirectorProtectedCPPMethodsRequired()) {
+      Node *vtable = Getattr(n, "vtable");
+      String *symname = Getattr(n, "sym:name");
+      AccessMode old_mode = cplus_mode;
+      cplus_mode = PROTECTED;
+      int len = Len(vtable);
+      for (int i = 0; i < len; i++) {
+	Node *item = Getitem(vtable, i);
+	Node *method = Getattr(item, "methodNode");
+	SwigType *type = Getattr(method, "nodeType");
+	if (Strcmp(type, "cdecl") != 0)
+	  continue;
+	if (GetFlag(method, "feature:ignore"))
+	  continue;
+	String *methodname = Getattr(method, "sym:name");
+	String *wrapname = NewStringf("%s_%s", symname, methodname);
+	if (!Getattr(symbols, wrapname) && (!is_public(method))) {
+	  Node *m = Copy(method);
+	  Setattr(m, "director", "1");
+	  Setattr(m, "parentNode", n);
+	  cDeclaration(m);
+	  Delete(m);
+	}
+	Delete(wrapname);
+      }
+      cplus_mode = old_mode;
+    }
+  }
+
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::classforwardDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::classforwardDeclaration(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::constructorDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::constructorDeclaration(Node *n) {
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+
+  if (!symname)
+    return SWIG_NOWRAP;
+  if (!CurrentClass)
+    return SWIG_NOWRAP;
+  if (ImportMode)
+    return SWIG_NOWRAP;
+
+  if (Extend) {
+    /* extend default constructor can be safely ignored if there is already one */
+    int num_required = ParmList_numrequired(Getattr(n, "parms"));
+    if ((num_required == 0) && Getattr(CurrentClass, "has_default_constructor")) {
+      return SWIG_NOWRAP;
+    }
+    if ((num_required == 1) && Getattr(CurrentClass, "has_copy_constructor")) {
+      String *ccdecl = Getattr(CurrentClass, "copy_constructor_decl");
+      if (ccdecl && (Strcmp(ccdecl, Getattr(n, "decl")) == 0)) {
+	return SWIG_NOWRAP;
+      }
+    }
+  }
+
+  /* clean protected overloaded constructors, in case they are not needed anymore */
+  Node *over = Swig_symbol_isoverloaded(n);
+  if (over && !Getattr(CurrentClass, "sym:cleanconstructor")) {
+    int dirclass = Swig_directorclass(CurrentClass);
+    Node *nn = over;
+    while (nn) {
+      if (!is_public(nn)) {
+	if (!dirclass || !need_nonpublic_ctor(nn)) {
+	  SetFlag(nn, "feature:ignore");
+	}
+      }
+      nn = Getattr(nn, "sym:nextSibling");
+    }
+    clean_overloaded(over);
+    Setattr(CurrentClass, "sym:cleanconstructor", "1");
+  }
+
+  if ((cplus_mode != PUBLIC)) {
+    /* check only for director classes */
+    if (!Swig_directorclass(CurrentClass) || !need_nonpublic_ctor(n))
+      return SWIG_NOWRAP;
+  }
+
+  /* Name adjustment for %name */
+  Swig_save("constructorDeclaration", n, "sym:name", NIL);
+
+  {
+    String *base = Swig_scopename_last(name);
+    if ((Strcmp(base, symname) == 0) && (Strcmp(symname, ClassPrefix) != 0)) {
+      Setattr(n, "sym:name", ClassPrefix);
+    }
+    Delete(base);
+  }
+
+  /* Only create a constructor if the class is not abstract */
+  if (!Abstract) {
+    Node *over;
+    over = Swig_symbol_isoverloaded(n);
+    if (over)
+      over = first_nontemplate(over);
+    if ((over) && (!overloading)) {
+      /* If the symbol is overloaded.  We check to see if it is a copy constructor.  If so, 
+         we invoke copyconstructorHandler() as a special case. */
+      if (Getattr(n, "copy_constructor") && (!Getattr(CurrentClass, "has_copy_constructor"))) {
+	copyconstructorHandler(n);
+	Setattr(CurrentClass, "has_copy_constructor", "1");
+      } else {
+	if (Getattr(over, "copy_constructor"))
+	  over = Getattr(over, "sym:nextSibling");
+	if (over != n) {
+	  Swig_warning(WARN_LANG_OVERLOAD_CONSTRUCT, input_file, line_number,
+		       "Overloaded constructor ignored.  %s\n", Swig_name_decl(n));
+	  Swig_warning(WARN_LANG_OVERLOAD_CONSTRUCT, Getfile(over), Getline(over),
+		       "Previous declaration is %s\n", Swig_name_decl(over));
+	} else {
+	  constructorHandler(n);
+	}
+      }
+    } else {
+      if (name && (Cmp(Swig_scopename_last(name), Swig_scopename_last(ClassName))) && !(Getattr(n, "template"))) {
+	Swig_warning(WARN_LANG_RETURN_TYPE, input_file, line_number, "Function %s must have a return type.\n", SwigType_namestr(name));
+	Swig_restore(n);
+	return SWIG_NOWRAP;
+      }
+      constructorHandler(n);
+    }
+  }
+  Setattr(CurrentClass, "has_constructor", "1");
+
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * get_director_ctor_code()
+ * ---------------------------------------------------------------------- */
+
+static String *get_director_ctor_code(Node *n, String *director_ctor_code, String *director_prot_ctor_code, List *&abstract) {
+  String *director_ctor = director_ctor_code;
+  int use_director = Swig_directorclass(n);
+  if (use_director) {
+    Node *pn = Swig_methodclass(n);
+    abstract = Getattr(pn, "abstract");
+    if (director_prot_ctor_code) {
+      int is_notabstract = GetFlag(pn, "feature:notabstract");
+      int is_abstract = abstract && !is_notabstract;
+      if (is_protected(n) || is_abstract) {
+	director_ctor = director_prot_ctor_code;
+	Delattr(pn, "abstract");
+      } else {
+	if (is_notabstract) {
+	  Delattr(pn, "abstract");
+	} else {
+	  abstract = 0;
+	}
+      }
+    }
+  }
+  return director_ctor;
+}
+
+
+/* ----------------------------------------------------------------------
+ * Language::constructorHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::constructorHandler(Node *n) {
+  Swig_require("constructorHandler", n, "?name", "*sym:name", "?type", "?parms", NIL);
+  String *symname = Getattr(n, "sym:name");
+  String *mrename = Swig_name_construct(symname);
+  String *nodeType = Getattr(n, "nodeType");
+  int constructor = (!Cmp(nodeType, "constructor"));
+  List *abstract = 0;
+  String *director_ctor = get_director_ctor_code(n, director_ctor_code,
+						 director_prot_ctor_code,
+						 abstract);
+  if (!constructor) {
+    /* if not originally a constructor, still handle it as one */
+    Setattr(n, "handled_as_constructor", "1");
+  }
+
+  Swig_ConstructorToFunction(n, ClassType, none_comparison, director_ctor, CPlusPlus, Getattr(n, "template") ? 0 : Extend);
+  Setattr(n, "sym:name", mrename);
+  functionWrapper(n);
+  Delete(mrename);
+  Swig_restore(n);
+  if (abstract)
+    Setattr(Swig_methodclass(n), "abstract", abstract);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::copyconstructorHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::copyconstructorHandler(Node *n) {
+  Swig_require("copyconstructorHandler", n, "?name", "*sym:name", "?type", "?parms", NIL);
+  String *symname = Getattr(n, "sym:name");
+  String *mrename = Swig_name_copyconstructor(symname);
+  List *abstract = 0;
+  String *director_ctor = get_director_ctor_code(n, director_ctor_code,
+						 director_prot_ctor_code,
+						 abstract);
+  Swig_ConstructorToFunction(n, ClassType, none_comparison, director_ctor, CPlusPlus, Getattr(n, "template") ? 0 : Extend);
+  Setattr(n, "sym:name", mrename);
+  functionWrapper(n);
+  Delete(mrename);
+  Swig_restore(n);
+  if (abstract)
+    Setattr(Swig_methodclass(n), "abstract", abstract);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::destructorDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::destructorDeclaration(Node *n) {
+
+  if (!CurrentClass)
+    return SWIG_NOWRAP;
+  if (cplus_mode != PUBLIC)
+    return SWIG_NOWRAP;
+  if (ImportMode)
+    return SWIG_NOWRAP;
+
+  if (Extend) {
+    /* extend destructor can be safetly ignored if there is already one */
+    if (Getattr(CurrentClass, "has_destructor")) {
+      return SWIG_NOWRAP;
+    }
+  }
+
+  Swig_save("destructorDeclaration", n, "name", "sym:name", NIL);
+
+  char *c = GetChar(n, "name");
+  if (c && (*c == '~'))
+    Setattr(n, "name", c + 1);
+
+  c = GetChar(n, "sym:name");
+  if (c && (*c == '~'))
+    Setattr(n, "sym:name", c + 1);
+
+  /* Name adjustment for %name */
+
+  String *name = Getattr(n, "name");
+  String *symname = Getattr(n, "sym:name");
+
+  if ((Strcmp(name, symname) == 0) || (Strcmp(symname, ClassPrefix) != 0)) {
+    Setattr(n, "sym:name", ClassPrefix);
+  }
+
+  destructorHandler(n);
+
+  Setattr(CurrentClass, "has_destructor", "1");
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::destructorHandler()
+ * ---------------------------------------------------------------------- */
+
+int Language::destructorHandler(Node *n) {
+  Swig_require("destructorHandler", n, "?name", "*sym:name", NIL);
+  Swig_save("destructorHandler", n, "type", "parms", NIL);
+
+  String *symname = Getattr(n, "sym:name");
+  String *mrename;
+  char *csymname = Char(symname);
+  if (csymname && (*csymname == '~'))
+    csymname += 1;
+
+  mrename = Swig_name_destroy(csymname);
+
+  Swig_DestructorToFunction(n, ClassType, CPlusPlus, Extend);
+  Setattr(n, "sym:name", mrename);
+  functionWrapper(n);
+  Delete(mrename);
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::accessDeclaration()
+ * ---------------------------------------------------------------------- */
+
+int Language::accessDeclaration(Node *n) {
+  String *kind = Getattr(n, "kind");
+  if (Cmp(kind, "public") == 0) {
+    cplus_mode = PUBLIC;
+  } else if (Cmp(kind, "private") == 0) {
+    cplus_mode = PRIVATE;
+  } else if (Cmp(kind, "protected") == 0) {
+    cplus_mode = PROTECTED;
+  }
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::namespaceDeclaration()
+ * ----------------------------------------------------------------------------- */
+
+int Language::namespaceDeclaration(Node *n) {
+  if (Getattr(n, "alias"))
+    return SWIG_OK;
+  if (Getattr(n, "unnamed"))
+    return SWIG_OK;
+  emit_children(n);
+  return SWIG_OK;
+}
+
+int Language::validIdentifier(String *s) {
+  char *c = Char(s);
+  while (*c) {
+    if (!(isalnum(*c) || (*c == '_')))
+      return 0;
+    c++;
+  }
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::usingDeclaration()
+ * ----------------------------------------------------------------------------- */
+
+int Language::usingDeclaration(Node *n) {
+  if ((cplus_mode == PUBLIC)) {
+    Node *np = Copy(n);
+    Node *c;
+    for (c = firstChild(np); c; c = nextSibling(c)) {
+      /* it seems for some cases this is needed, like A* A::boo() */
+      if (CurrentClass)
+	Setattr(c, "parentNode", CurrentClass);
+      emit_one(c);
+    }
+    Delete(np);
+  }
+  return SWIG_OK;
+}
+
+/* Stubs. Language modules need to implement these */
+
+/* ----------------------------------------------------------------------
+ * Language::constantWrapper()
+ * ---------------------------------------------------------------------- */
+
+int Language::constantWrapper(Node *n) {
+  String *name = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  String *value = Getattr(n, "value");
+  String *str = SwigType_str(type, name);
+  Printf(stdout, "constantWrapper   : %s = %s\n", str, value);
+  Delete(str);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::variableWrapper()
+ * ---------------------------------------------------------------------- */
+
+int Language::variableWrapper(Node *n) {
+  Swig_require("variableWrapper", n, "*name", "*sym:name", "*type", "?parms", NIL);
+  String *symname = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  String *name = Getattr(n, "name");
+
+  /* If no way to set variables.  We simply create functions */
+  int assignable = is_assignable(n);
+  int flags = use_naturalvar_mode(n);
+  if (!GetFlag(n, "wrappedasconstant"))
+    flags = flags | Extend;
+
+  if (assignable) {
+    int make_set_wrapper = 1;
+    String *tm = Swig_typemap_lookup("globalin", n, name, 0);
+
+    Swig_VarsetToFunction(n, flags);
+    String *sname = Swig_name_set(symname);
+    Setattr(n, "sym:name", sname);
+    Delete(sname);
+
+    if (!tm) {
+      if (SwigType_isarray(type)) {
+	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(type, 0));
+	make_set_wrapper = 0;
+      }
+    } else {
+      String *pname0 = Swig_cparm_name(0, 0);
+      Replace(tm, "$source", pname0, DOH_REPLACE_ANY);
+      Replace(tm, "$target", name, DOH_REPLACE_ANY);
+      Replace(tm, "$input", pname0, DOH_REPLACE_ANY);
+      Setattr(n, "wrap:action", tm);
+      Delete(tm);
+      Delete(pname0);
+    }
+    if (make_set_wrapper) {
+      functionWrapper(n);
+    }
+    /* Restore parameters */
+    Setattr(n, "sym:name", symname);
+    Setattr(n, "type", type);
+    Setattr(n, "name", name);
+
+    /* Delete all attached typemaps and typemap attributes */
+    Iterator ki;
+    for (ki = First(n); ki.key; ki = Next(ki)) {
+      if (Strncmp(ki.key, "tmap:", 5) == 0)
+	Delattr(n, ki.key);
+    }
+  }
+
+  Swig_VargetToFunction(n, flags);
+  String *gname = Swig_name_get(symname);
+  Setattr(n, "sym:name", gname);
+  Delete(gname);
+  functionWrapper(n);
+  Swig_restore(n);
+  return SWIG_OK;
+}
+
+/* ----------------------------------------------------------------------
+ * Language::functionWrapper()
+ * ---------------------------------------------------------------------- */
+
+int Language::functionWrapper(Node *n) {
+  String *name = Getattr(n, "sym:name");
+  SwigType *type = Getattr(n, "type");
+  ParmList *parms = Getattr(n, "parms");
+
+  Printf(stdout, "functionWrapper   : %s\n", SwigType_str(type, NewStringf("%s(%s)", name, ParmList_str_defaultargs(parms))));
+  Printf(stdout, "           action : %s\n", Getattr(n, "wrap:action"));
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::nativeWrapper()
+ * ----------------------------------------------------------------------------- */
+
+int Language::nativeWrapper(Node *n) {
+  (void) n;
+  return SWIG_OK;
+}
+
+void Language::main(int argc, char *argv[]) {
+  (void) argc;
+  (void) argv;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::addSymbol()
+ *
+ * Adds a symbol entry.  Returns 1 if the symbol is added successfully.
+ * Prints an error message and returns 0 if a conflict occurs.
+ * ----------------------------------------------------------------------------- */
+
+int
+Language::addSymbol(const String *s, const Node *n) {
+  Node *c = Getattr(symbols, s);
+  if (c && (c != n)) {
+    Swig_error(input_file, line_number, "'%s' is multiply defined in the generated module.\n", s);
+    Swig_error(Getfile(c), Getline(c), "Previous declaration of '%s'\n", s);
+    return 0;
+  }
+  Setattr(symbols, s, n);
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::symbolLookup()
+ * ----------------------------------------------------------------------------- */
+
+Node *Language::symbolLookup(String *s) {
+  return Getattr(symbols, s);
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::classLookup()
+ *
+ * Tries to locate a class from a type definition
+ * ----------------------------------------------------------------------------- */
+
+Node *Language::classLookup(SwigType *s) {
+  Node *n = 0;
+
+  /* Look in hash of cached values */
+  n = Getattr(classtypes, s);
+  if (!n) {
+    Symtab *stab = 0;
+//    SwigType *lt = SwigType_ltype(s);
+//    SwigType *ty1 = SwigType_typedef_resolve_all(lt);
+    SwigType *ty1 = SwigType_typedef_resolve_all(s);
+    SwigType *ty2 = SwigType_strip_qualifiers(ty1);
+//    Printf(stdout, "   stages... ty1: %s ty2: %s\n", ty1, ty2);
+//    Delete(lt);
+    Delete(ty1);
+//    lt = 0;
+    ty1 = 0;
+
+    String *base = SwigType_base(ty2);
+
+    Replaceall(base, "class ", "");
+    Replaceall(base, "struct ", "");
+    Replaceall(base, "union ", "");
+
+    String *prefix = SwigType_prefix(ty2);
+
+    /* Do a symbol table search on the base type */
+    while (!n) {
+      Hash *nstab;
+      n = Swig_symbol_clookup(base, stab);
+      if (!n)
+	break;
+      if (Strcmp(nodeType(n), "class") == 0)
+	break;
+      n = parentNode(n);
+      if (!n)
+	break;
+      nstab = Getattr(n, "sym:symtab");
+      n = 0;
+      if ((!nstab) || (nstab == stab)) {
+	break;
+      }
+      stab = nstab;
+    }
+    if (n) {
+      /* Found a match.  Look at the prefix.  We only allow
+         the cases where where we want a proxy class for the particular type */
+      if ((Len(prefix) == 0) ||	                // simple type (pass by value)
+	  (Strcmp(prefix, "p.") == 0) ||	// pointer
+	  (Strcmp(prefix, "r.") == 0) ||	// reference
+	  (Strcmp(prefix, "r.p.") == 0) || 	// pointer by reference
+          SwigType_prefix_is_simple_1D_array(prefix)) { // Simple 1D array (not arrays of pointers/references)
+	SwigType *cs = Copy(s);
+	Setattr(classtypes, cs, n);
+	Delete(cs);
+      } else {
+	n = 0;
+      }
+    }
+    Delete(ty2);
+    Delete(base);
+    Delete(prefix);
+  }
+  if (n && (GetFlag(n, "feature:ignore") || Getattr(n, "feature:onlychildren"))) {
+    n = 0;
+  }
+
+  return n;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::enumLookup()
+ *
+ * Finds and returns the Node containing the enum declaration for the (enum) 
+ * type passed in.
+ * ----------------------------------------------------------------------------- */
+
+Node *Language::enumLookup(SwigType *s) {
+  Node *n = 0;
+
+  /* Look in hash of cached values */
+  n = Getattr(enumtypes, s);
+  if (!n) {
+    Symtab *stab = 0;
+    SwigType *lt = SwigType_ltype(s);
+    SwigType *ty1 = SwigType_typedef_resolve_all(lt);
+    SwigType *ty2 = SwigType_strip_qualifiers(ty1);
+    Delete(lt);
+    Delete(ty1);
+    lt = 0;
+    ty1 = 0;
+
+    String *base = SwigType_base(ty2);
+
+    Replaceall(base, "enum ", "");
+    String *prefix = SwigType_prefix(ty2);
+
+    /* Look for type in symbol table */
+    while (!n) {
+      Hash *nstab;
+      n = Swig_symbol_clookup(base, stab);
+      if (!n)
+	break;
+      if (Strcmp(nodeType(n), "enum") == 0)
+	break;
+      n = parentNode(n);
+      if (!n)
+	break;
+      nstab = Getattr(n, "sym:symtab");
+      n = 0;
+      if ((!nstab) || (nstab == stab)) {
+	break;
+      }
+      stab = nstab;
+    }
+    if (n) {
+      /* Found a match.  Look at the prefix.  We only allow simple types. */
+      if (Len(prefix) == 0) {	/* Simple type */
+	Setattr(enumtypes, Copy(s), n);
+      } else {
+	n = 0;
+      }
+    }
+    Delete(ty2);
+    Delete(base);
+    Delete(prefix);
+  }
+  if (n && (GetFlag(n, "feature:ignore"))) {
+    n = 0;
+  }
+
+  return n;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::allow_overloading()
+ * ----------------------------------------------------------------------------- */
+
+void Language::allow_overloading(int val) {
+  overloading = val;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::allow_multiple_input()
+ * ----------------------------------------------------------------------------- */
+
+void Language::allow_multiple_input(int val) {
+  multiinput = val;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::enable_cplus_runtime_mode()
+ * ----------------------------------------------------------------------------- */
+
+void Language::enable_cplus_runtime_mode() {
+  cplus_runtime = 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::cplus_runtime_mode()
+ * ----------------------------------------------------------------------------- */
+
+int Language::cplus_runtime_mode() {
+  return cplus_runtime;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::allow_directors()
+ * ----------------------------------------------------------------------------- */
+
+void Language::allow_directors(int val) {
+  directors = val;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::directorsEnabled()
+ * ----------------------------------------------------------------------------- */
+
+int Language::directorsEnabled() const {
+  return director_language && CPlusPlus && (directors || director_mode);
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::allow_dirprot()
+ * ----------------------------------------------------------------------------- */
+
+void Language::allow_dirprot(int val) {
+  director_protected_mode = val;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::allow_allprotected()
+ * ----------------------------------------------------------------------------- */
+
+void Language::allow_allprotected(int val) {
+  all_protected_mode = val;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::dirprot_mode()
+ * ----------------------------------------------------------------------------- */
+
+int Language::dirprot_mode() const {
+  return directorsEnabled() ? director_protected_mode : 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::need_nonpublic_ctor()
+ * ----------------------------------------------------------------------------- */
+
+int Language::need_nonpublic_ctor(Node *n) {
+  /* 
+     detects when a protected constructor is needed, which is always
+     the case if 'dirprot' mode is used.  However, if that is not the
+     case, we will try to strictly emit what is minimal to don't break
+     the generated, while preserving compatibility with java, which
+     always try to emit the default constructor.
+
+     rules:
+
+     - when dirprot mode is used, the protected constructors are
+     always needed.
+
+     - the protected default constructor is always needed.
+
+     - if dirprot mode is not used, the protected constructors will be
+     needed only if:
+
+     - there is no any public constructor in the class, and
+     - there is no protected default constructor
+
+     In that case, all the declared protected constructors are
+     needed since we don't know which one to pick up.
+
+     Note: given all the complications here, I am always in favor to
+     always enable 'dirprot', since is the C++ idea of protected
+     members, and use %ignore for the method you don't whan to add in
+     the director class.
+   */
+  if (directorsEnabled()) {
+    if (is_protected(n)) {
+      if (dirprot_mode()) {
+	/* when using dirprot mode, the protected constructors are
+	   always needed */
+	return 1;
+      } else {
+	int is_default_ctor = !ParmList_numrequired(Getattr(n, "parms"));
+	if (is_default_ctor) {
+	  /* the default protected constructor is always needed, for java compatibility */
+	  return 1;
+	} else {
+	  /* check if there is a public constructor */
+	  Node *parent = Swig_methodclass(n);
+	  int public_ctor = Getattr(parent, "allocate:default_constructor")
+	      || Getattr(parent, "allocate:public_constructor");
+	  if (!public_ctor) {
+	    /* if not, the protected constructor will be needed only
+	       if there is no protected default constructor declared */
+	    int no_prot_default_ctor = !Getattr(parent, "allocate:default_base_constructor");
+	    return no_prot_default_ctor;
+	  }
+	}
+      }
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::need_nonpublic_member()
+ * ----------------------------------------------------------------------------- */
+int Language::need_nonpublic_member(Node *n) {
+  if (directorsEnabled()) {
+    if (is_protected(n)) {
+      if (dirprot_mode()) {
+	/* when using dirprot mode, the protected members are always needed. */
+	return 1;
+      } else {
+	/* if the method is pure virtual, we need it. */
+	int pure_virtual = (Cmp(Getattr(n, "value"), "0") == 0);
+	return pure_virtual;
+      }
+    }
+  }
+  return 0;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Language::is_smart_pointer()
+ * ----------------------------------------------------------------------------- */
+
+int Language::is_smart_pointer() const {
+  return SmartPointer;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::extraDirectorProtectedCPPMethodsRequired()
+ * ----------------------------------------------------------------------------- */
+
+bool Language::extraDirectorProtectedCPPMethodsRequired() const {
+  return true;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::is_wrapping_class()
+ * ----------------------------------------------------------------------------- */
+
+int Language::is_wrapping_class() {
+  return InClass;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::getCurrentClass()
+ * ----------------------------------------------------------------------------- */
+
+Node *Language::getCurrentClass() const {
+  return CurrentClass;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::getClassName()
+ * ----------------------------------------------------------------------------- */
+
+String *Language::getClassName() const {
+  return ClassName;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::getClassPrefix()
+ * ----------------------------------------------------------------------------- */
+
+String *Language::getClassPrefix() const {
+  return ClassPrefix;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::getClassType()
+ * ----------------------------------------------------------------------------- */
+
+String *Language::getClassType() const {
+  return ClassType;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language::abstractClassTest()
+ * ----------------------------------------------------------------------------- */
+//#define SWIG_DEBUG
+int Language::abstractClassTest(Node *n) {
+  /* check for non public operator new */
+  if (GetFlag(n, "feature:notabstract"))
+    return 0;
+  if (Getattr(n, "allocate:nonew"))
+    return 1;
+  /* now check for the rest */
+  List *abstract = Getattr(n, "abstract");
+  if (!abstract)
+    return 0;
+  int labs = Len(abstract);
+#ifdef SWIG_DEBUG
+  List *bases = Getattr(n, "allbases");
+  Printf(stderr, "testing %s %d %d\n", Getattr(n, "name"), labs, Len(bases));
+#endif
+  if (!labs)
+    return 0;			/*strange, but need to be fixed */
+  if (abstract && !directorsEnabled())
+    return 1;
+  if (!GetFlag(n, "feature:director"))
+    return 1;
+
+  Node *dirabstract = 0;
+  Node *vtable = Getattr(n, "vtable");
+  if (vtable) {
+#ifdef SWIG_DEBUG
+    Printf(stderr, "vtable %s %d %d\n", Getattr(n, "name"), Len(vtable), labs);
+#endif
+    for (int i = 0; i < labs; i++) {
+      Node *ni = Getitem(abstract, i);
+      Node *method_id = vtable_method_id(ni);
+      if (!method_id)
+	continue;
+      bool exists_item = false;
+      int len = Len(vtable);
+      for (int i = 0; i < len; i++) {
+	Node *item = Getitem(vtable, i);
+	String *check_item = Getattr(item, "vmid");
+	if (Strcmp(method_id, check_item) == 0) {
+	  exists_item = true;
+	  break;
+	}
+      }
+#ifdef SWIG_DEBUG
+      Printf(stderr, "method %s %d\n", method_id, exists_item ? 1 : 0);
+#endif
+      Delete(method_id);
+      if (!exists_item) {
+	dirabstract = ni;
+	break;
+      }
+    }
+    if (dirabstract) {
+      if (is_public(dirabstract)) {
+	Swig_warning(WARN_LANG_DIRECTOR_ABSTRACT, Getfile(n), Getline(n),
+		     "Director class '%s' is abstract, abstract method '%s' is not accesible, maybe due to multiple inheritance or 'nodirector' feature\n",
+		     SwigType_namestr(Getattr(n, "name")), Getattr(dirabstract, "name"));
+      } else {
+	Swig_warning(WARN_LANG_DIRECTOR_ABSTRACT, Getfile(n), Getline(n),
+		     "Director class '%s' is abstract, abstract method '%s' is private\n", SwigType_namestr(Getattr(n, "name")), Getattr(dirabstract, "name"));
+      }
+      return 1;
+    }
+  } else {
+    return 1;
+  }
+  return dirabstract ? 1 : 0;
+}
+
+void Language::setSubclassInstanceCheck(String *nc) {
+  none_comparison = nc;
+}
+
+void Language::setOverloadResolutionTemplates(String *argc, String *argv) {
+  Delete(argc_template_string);
+  argc_template_string = Copy(argc);
+  Delete(argv_template_string);
+  argv_template_string = Copy(argv);
+}
+
+int Language::is_assignable(Node *n) {
+  if (GetFlag(n, "feature:immutable"))
+    return 0;
+  SwigType *type = Getattr(n, "type");
+  Node *cn = 0;
+  SwigType *ftd = SwigType_typedef_resolve_all(type);
+  SwigType *td = SwigType_strip_qualifiers(ftd);
+  if (SwigType_type(td) == T_USER) {
+    cn = Swig_symbol_clookup(td, 0);
+    if (cn) {
+      if ((Strcmp(nodeType(cn), "class") == 0)) {
+	if (Getattr(cn, "allocate:noassign")) {
+	  SetFlag(n, "feature:immutable");
+	  Delete(ftd);
+	  Delete(td);
+	  return 0;
+	}
+      }
+    }
+  }
+  Delete(ftd);
+  Delete(td);
+  return 1;
+}
+
+String *Language::runtimeCode() {
+  return NewString("");
+}
+
+String *Language::defaultExternalRuntimeFilename() {
+  return 0;
+}
+
+Hash *Language::getClassHash() const {
+  return classhash;
+}
diff --git a/trunk/Source/Modules/lua.cxx b/trunk/Source/Modules/lua.cxx
new file mode 100644
index 0000000..6113da9
--- /dev/null
+++ b/trunk/Source/Modules/lua.cxx
@@ -0,0 +1,1214 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * lua.cxx
+ *
+ * Lua language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+/* NEW LANGUAGE NOTE:
+ * ver001
+   this is simply a copy of tcl8.cxx, which has been renamed
+ * ver002
+   all non essential code commented out, program now does virtually nothing
+   it prints to stderr the list of functions to wrap, but does not create
+   the XXX_wrap.c file
+ * ver003
+   added back top(), still prints the list of fns to stderr
+   but now creates a rather empty XXX_wrap.c with some basic boilerplate code
+ * ver004
+   very basic version of functionWrapper()
+   also uncommented usage_string() to keep compiler happy
+   this will start producing proper looking code soon (I hope)
+   produced the wrapper code, but without any type conversion (in or out)
+   generates a few warning because of no wrappering
+   does not generate SWIG_init()
+   reason for this is that lua.swg is empty
+   we will need to add code into this to make it work
+ * ver005/6
+   massive rework, basing work on the pike module instead of tcl
+   (pike module it only 1/3 of the size)(though not as complete)
+ * ver007
+   added simple type checking
+ * ver008
+   INPUT, OUTPUT, INOUT typemaps handled (though not all types yet)
+ * ver009
+   class support: ok for basic types, but methods still TDB
+   (code is VERY messed up & needs to be cleaned)
+ 
+ 
+*/
+
+char cvsroot_lua_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+/**** Diagnostics:
+  With the #define REPORT(), you can change the amount of diagnostics given
+  This helps me search the parse tree & figure out what is going on inside SWIG
+  (because its not clear or documented)
+*/
+#define REPORT(T,D)		// no info:
+//#define REPORT(T,D)   {Printf(stdout,T"\n");} // only title
+//#define REPORT(T,D)		{Printf(stdout,T" %p\n",n);} // title & pointer
+//#define REPORT(T,D)   {Printf(stdout,T"\n");display_mapping(D);}      // the works
+//#define REPORT(T,D)   {Printf(stdout,T"\n");if(D)Swig_print_node(D);}      // the works
+
+void display_mapping(DOH *d) {
+  if (d == 0 || !DohIsMapping(d))
+    return;
+  for (DohIterator it = DohFirst(d); it.item; it = DohNext(it)) {
+    if (DohIsString(it.item))
+      Printf(stdout, "  %s = %s\n", it.key, it.item);
+    else if (DohIsMapping(it.item))
+      Printf(stdout, "  %s = <mapping>\n", it.key);
+    else if (DohIsSequence(it.item))
+      Printf(stdout, "  %s = <sequence>\n", it.key);
+    else
+      Printf(stdout, "  %s = <unknown>\n", it.key);
+  }
+}
+
+
+
+/* NEW LANGUAGE NOTE:***********************************************
+ most of the default options are handled by SWIG
+ you can add new ones here
+ (though for now I have not bothered)
+NEW LANGUAGE NOTE:END ************************************************/
+static const char *usage = (char *) "\
+                           Lua Options (available with -lua)\n\
+                           (coming soon.)\n\n";
+
+
+
+/* NEW LANGUAGE NOTE:***********************************************
+ To add a new language, you need to derive your class from
+ Language and the overload various virtual functions
+ (more on this as I figure it out)
+NEW LANGUAGE NOTE:END ************************************************/
+
+class LUA:public Language {
+private:
+
+  File *f_runtime;
+  File *f_header;
+  File *f_wrappers;
+  File *f_init;
+  File *f_initbeforefunc;
+  String *PrefixPlusUnderscore;
+  String *s_cmd_tab;		// table of command names
+  String *s_var_tab;		// table of global variables
+  String *s_const_tab;		// table of global constants
+  String *s_methods_tab;	// table of class methods
+  String *s_attr_tab;		// table of class atributes
+  String *s_luacode;		// luacode to be called during init
+
+  int have_constructor;
+  int have_destructor;
+  String *destructor_action;
+  String *class_name;
+  String *constructor_name;
+
+  enum {
+    NO_CPP,
+    VARIABLE,
+    MEMBER_FUNC,
+    CONSTRUCTOR,
+    DESTRUCTOR,
+    MEMBER_VAR,
+    CLASS_CONST,
+    STATIC_FUNC,
+    STATIC_VAR
+  }current;
+
+public:
+
+  /* ---------------------------------------------------------------------
+   * LUA()
+   *
+   * Initialize member data
+   * --------------------------------------------------------------------- */
+
+  LUA() {
+    f_runtime = 0;
+    f_header = 0;
+    f_wrappers = 0;
+    f_init = 0;
+    f_initbeforefunc = 0;
+    PrefixPlusUnderscore = 0;
+
+    s_cmd_tab = s_var_tab = s_const_tab = s_luacode = 0;
+    current=NO_CPP;
+  }
+
+  /* NEW LANGUAGE NOTE:***********************************************
+     This is called to initalise the system & read any command line args
+     most of this is boilerplate code, except the command line args
+     which depends upon what args your code supports
+     NEW LANGUAGE NOTE:END ************************************************/
+
+  /* ---------------------------------------------------------------------
+  * main()
+  *
+  * Parse command line options and initializes variables.
+  * --------------------------------------------------------------------- */
+
+  virtual void main(int argc, char *argv[]) {
+
+    /* Set location of SWIG library */
+    SWIG_library_directory("lua");
+
+    /* Look for certain command line options */
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+        if (strcmp(argv[i], "-help") == 0) {	// usage flags
+          fputs(usage, stderr);
+        }
+      }
+    }
+
+    /* NEW LANGUAGE NOTE:***********************************************
+     This is the boilerplate code, setting a few #defines
+     and which lib directory to use
+     the SWIG_library_directory() is also boilerplate code
+     but it always seems to be the first line of code
+    NEW LANGUAGE NOTE:END ************************************************/
+    /* Add a symbol to the parser for conditional compilation */
+    Preprocessor_define("SWIGLUA 1", 0);
+
+    /* Set language-specific configuration file */
+    SWIG_config_file("lua.swg");
+
+    /* Set typemap language */
+    SWIG_typemap_lang("lua");
+
+    /* Enable overloaded methods support */
+    allow_overloading();
+  }
+
+
+
+
+  /* NEW LANGUAGE NOTE:***********************************************
+   After calling main, SWIG parses the code to wrap (I believe)
+   then calls top()
+   in this is more boilerplate code to set everything up
+   and a call to Language::top()
+   which begins the code generations by calling the member fns
+   after all that is more boilerplate code to close all down
+   (overall there is virtually nothing here that needs to be edited
+   just use as is)
+  NEW LANGUAGE NOTE:END ************************************************/
+  /* ---------------------------------------------------------------------
+   * top()
+   * --------------------------------------------------------------------- */
+
+  virtual int top(Node *n) {
+    /* Get the module name */
+    String *module = Getattr(n, "name");
+
+    /* Get the output file name */
+    String *outfile = Getattr(n, "outfile");
+
+    /* Open the output file */
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+    f_initbeforefunc = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("initbeforefunc", f_initbeforefunc);
+
+    /* NEW LANGUAGE NOTE:***********************************************
+     s_cmd_tab,s_var_tab & s_const_tab hold the names of the fns for
+     registering with SWIG.
+     These will be filled in when the functions/variables are wrapped &
+     then added to the end of the wrappering code
+     just before it is written to file
+    NEW LANGUAGE NOTE:END ************************************************/
+    // Initialize some variables for the object interface
+    s_cmd_tab = NewString("");
+    s_var_tab = NewString("");
+    //    s_methods_tab    = NewString("");
+    s_const_tab = NewString("");
+    
+    s_luacode = NewString("");
+    Swig_register_filebyname("luacode", s_luacode);
+    
+    current=NO_CPP;
+
+    /* Standard stuff for the SWIG runtime section */
+    Swig_banner(f_runtime);
+    //    if (NoInclude) {
+    //      Printf(f_runtime, "#define SWIG_NOINCLUDE\n");
+    //    }
+
+    //String *init_name = NewStringf("%(title)s_Init", module);
+    //Printf(f_header, "#define SWIG_init    %s\n", init_name);
+    //Printf(f_header, "#define SWIG_name    \"%s\"\n", module);
+    /* SWIG_import is a special function name for importing within Lua5.1 */
+    //Printf(f_header, "#define SWIG_import  luaopen_%s\n\n", module);
+    Printf(f_header, "#define SWIG_name      \"%s\"\n", module);
+    Printf(f_header, "#define SWIG_init      luaopen_%s\n", module);
+    Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module);
+    Printf(f_header, "#define SWIG_LUACODE   luaopen_%s_luacode\n\n", module);
+
+    Printf(s_cmd_tab, "\nstatic const struct luaL_reg swig_commands[] = {\n");
+    Printf(s_var_tab, "\nstatic swig_lua_var_info swig_variables[] = {\n");
+    Printf(s_const_tab, "\nstatic swig_lua_const_info swig_constants[] = {\n");
+    Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
+
+    /* %init code inclusion, effectively in the SWIG_init function */
+    Printf(f_init, "void SWIG_init_user(lua_State* L)\n{\n");
+    Language::top(n);
+    Printf(f_init,"/* exec Lua code if applicable */\nSWIG_Lua_dostring(L,SWIG_LUACODE);\n");
+    Printf(f_init, "}\n");
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n");
+
+    // Done.  Close up the module & write to the wrappers
+    Printv(s_cmd_tab, tab4, "{0,0}\n", "};\n", NIL);
+    Printv(s_var_tab, tab4, "{0,0,0}\n", "};\n", NIL);
+    Printv(s_const_tab, tab4, "{0,0,0,0,0,0}\n", "};\n", NIL);
+    Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL);
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+
+    /* NEW LANGUAGE NOTE:***********************************************
+     this basically combines several of the strings together
+     and then writes it all to a file
+    NEW LANGUAGE NOTE:END ************************************************/
+    Dump(f_header, f_runtime);
+    Dump(f_wrappers, f_runtime);
+    Dump(f_initbeforefunc, f_runtime);
+    /* for the Lua code it needs to be properly excaped to be added into the C/C++ code */
+    EscapeCode(s_luacode);
+    Printf(f_runtime, "const char* SWIG_LUACODE=\n  \"%s\";\n\n",s_luacode);
+    Wrapper_pretty_print(f_init, f_runtime);
+    /* Close all of the files */
+    Delete(s_luacode);
+    Delete(s_cmd_tab);
+    Delete(s_var_tab);
+    Delete(s_const_tab);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Delete(f_initbeforefunc);
+    Close(f_runtime);
+    Delete(f_runtime);
+
+    /* Done */
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * importDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int importDirective(Node *n) {
+    return Language::importDirective(n);
+  }
+
+  /* NEW LANGUAGE NOTE:***********************************************
+   This is it!
+   you get this one right, and most of your work is done
+   but its going to take soem file to get it working right
+   quite a bit of this is generally boilerplate code
+   (or stuff I dont understand)
+   that which matters will have extra added comments
+  NEW LANGUAGE NOTE:END ************************************************/
+  /* ---------------------------------------------------------------------
+   * functionWrapper()
+   *
+   * Create a function declaration and register it with the interpreter.
+   * --------------------------------------------------------------------- */
+
+  virtual int functionWrapper(Node *n) {
+    REPORT("functionWrapper",n);
+
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    //Printf(stdout,"functionWrapper %s %s\n",name,iname);
+    Parm *p;
+    String *tm;
+    int i;
+    //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current);
+    //    int returnval=0;  // number of arguments returned
+
+    String *overname = 0;
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n)) {
+        Printf(stderr,"addSymbol(%s) failed\n",iname);
+        return SWIG_ERROR;
+      }
+    }
+
+    /* NEW LANGUAGE NOTE:***********************************************
+       the wrapper object holds all the wrappering code
+        we need to add a couple of local variables
+    NEW LANGUAGE NOTE:END ************************************************/
+    Wrapper *f = NewWrapper();
+    Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0");
+
+
+    String *wname = Swig_name_wrapper(iname);
+    if (overname) {
+      Append(wname, overname);
+    }
+
+    /* NEW LANGUAGE NOTE:***********************************************
+       the format of a lua fn is:
+         static int wrap_XXX(lua_State* L){...}
+       this line adds this into the wrappering code
+    NEW LANGUAGE NOTE:END ************************************************/
+    Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL);
+
+    /* NEW LANGUAGE NOTE:***********************************************
+       this prints the list of args, eg for a C fn
+       int gcd(int x,int y);
+       it will print
+         int arg1;
+         int arg2;
+    NEW LANGUAGE NOTE:END ************************************************/
+    /* Write code to extract function parameters. */
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    /* Get number of required and total arguments */
+    int num_arguments = emit_num_arguments(l);
+    int num_required = emit_num_required(l);
+    int varargs = emit_isvarargs(l);
+
+    // Check if we have to ignore arguments that are passed by LUA.
+    // Needed for unary minus, where lua passes two arguments and
+    // we have to ignore the second.
+
+    int args_to_ignore = 0;
+    if (Getattr(n, "lua:ignore_args")) {
+      args_to_ignore = GetInt(n, "lua:ignore_args");
+    }
+
+
+    /* Which input argument to start with? */
+    //    int start = (current == MEMBER_FUNC || current == MEMBER_VAR || current == DESTRUCTOR) ? 1 : 0;
+
+    /* Offset to skip over the attribute name */
+    // int offset = (current == MEMBER_VAR) ? 1 : 0;
+
+    /* NEW LANGUAGE NOTE:***********************************************
+       from here on in, it gets rather hairy
+       this is the code to convert from the scripting language to C/C++
+       some of the stuff will refer to the typemaps code written in your swig file
+       (lua.swg), and some is done in the code here
+       I suppose you could do all the conversion on C, but it would be a nightmare to do
+    NEW LANGUAGE NOTE:END ************************************************/
+    /* Generate code for argument marshalling */
+    //    String *description = NewString("");
+    /* NEW LANGUAGE NOTE:***********************************************
+       argument_check is a new feature I added to check types of arguments:
+       eg for int gcd(int,int)
+       I want to check that arg1 & arg2 really are integers
+    NEW LANGUAGE NOTE:END ************************************************/
+    String *argument_check = NewString("");
+    String *argument_parse = NewString("");
+    String *checkfn = NULL;
+    //    String *numoutputs=NULL;
+    char source[64];
+    //Printf(argument_check, "SWIG_check_num_args(\"%s\",%d,%d)\n",name,num_required,num_arguments);
+    Printf(argument_check, "SWIG_check_num_args(\"%s\",%d,%d)\n",name,num_required+args_to_ignore,num_arguments+args_to_ignore);
+
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+        p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+
+      /* Look for an input typemap */
+      sprintf(source, "%d", i + 1);
+      if ((tm = Getattr(p, "tmap:in"))) {
+        Replaceall(tm, "$source", source);
+        Replaceall(tm, "$target", ln);
+        Replaceall(tm, "$input", source);
+        Setattr(p, "emit:input", source);
+        if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+          Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+        } else {
+          Replaceall(tm, "$disown", "0");
+        }
+        /* NEW LANGUAGE NOTE:***********************************************
+           look for a 'checkfn' typemap
+           this an additional parameter added to the in typemap
+           if found the type will be tested for
+           this will result in code either in the
+           argument_check or argument_parse string
+        NEW LANGUAGE NOTE:END ************************************************/
+        if ((checkfn = Getattr(p, "tmap:in:checkfn"))) {
+          if (i < num_required) {
+            Printf(argument_check, "if(!%s(L,%s))", checkfn, source);
+          } else {
+            Printf(argument_check, "if(lua_gettop(L)>=%s && !%s(L,%s))", source, checkfn, source);
+          }
+          Printf(argument_check, " SWIG_fail_arg(\"%s\",%s,\"%s\");\n", name, source, SwigType_str(pt, 0));
+        }
+        /* NEW LANGUAGE NOTE:***********************************************
+           lua states the number of arguments passed to a function using the fn
+           lua_gettop()
+           we can use this to deal with default arguments
+        NEW LANGUAGE NOTE:END ************************************************/
+        if (i < num_required) {
+          Printf(argument_parse, "%s\n", tm);
+        } else {
+          Printf(argument_parse, "if(lua_gettop(L)>=%s){%s}\n", source, tm);
+        }
+        p = Getattr(p, "tmap:in:next");
+        continue;
+      } else {
+        /* NEW LANGUAGE NOTE:***********************************************
+        		   // why is this code not called when I dont have a typemap?
+        		   // instead of giving a warning, no code is generated
+        NEW LANGUAGE NOTE:END ************************************************/
+        Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+        break;
+      }
+    }
+
+    // add all argcheck code
+    Printv(f->code, argument_check, argument_parse, NIL);
+
+    /* Check for trailing varargs */
+    if (varargs) {
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+        Replaceall(tm, "$input", "varargs");
+        Printv(f->code, tm, "\n", NIL);
+      }
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+        Replaceall(tm, "$target", Getattr(p, "lname"));
+        Printv(f->code, tm, "\n", NIL);
+        p = Getattr(p, "tmap:check:next");
+      } else {
+        p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    String *cleanup = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+        Replaceall(tm, "$source", Getattr(p, "lname"));
+        Printv(cleanup, tm, "\n", NIL);
+        p = Getattr(p, "tmap:freearg:next");
+      } else {
+        p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    String *outarg = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+        //          // managing the number of returning variables
+        //        if (numoutputs=Getattr(p,"tmap:argout:numoutputs")){
+        //                      int i=GetInt(p,"tmap:argout:numoutputs");
+        //                      printf("got argout:numoutputs of %d\n",i);
+        //                      returnval+=GetInt(p,"tmap:argout:numoutputs");
+        //        }
+        //        else returnval++;
+        Replaceall(tm, "$source", Getattr(p, "lname"));
+        Replaceall(tm, "$target", "result");
+        Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+        Replaceall(tm, "$input", Getattr(p, "emit:input"));
+        Printv(outarg, tm, "\n", NIL);
+        p = Getattr(p, "tmap:argout:next");
+      } else {
+        p = nextSibling(p);
+      }
+    }
+
+    Setattr(n, "wrap:name", wname);
+
+    /* Emit the function call */
+    String *actioncode = emit_action(n);
+
+    /* NEW LANGUAGE NOTE:***********************************************
+    FIXME:
+    returns 1 if there is a void return type
+    this is because there is a typemap for void
+    NEW LANGUAGE NOTE:END ************************************************/
+    // Return value if necessary
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      // managing the number of returning variables
+      //      if (numoutputs=Getattr(tm,"numoutputs")){
+      //              int i=GetInt(tm,"numoutputs");
+      //              printf("return numoutputs %d\n",i);
+      //              returnval+=GetInt(tm,"numoutputs");
+      //      }
+      //        else returnval++;
+      Replaceall(tm, "$source", "result");
+      if (GetFlag(n, "feature:new")) {
+        Replaceall(tm, "$owner", "1");
+      } else {
+        Replaceall(tm, "$owner", "0");
+      }
+      Printf(f->code, "%s\n", tm);
+      //      returnval++;
+    } else {
+      Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
+    }
+    emit_return_variable(n, d, f);
+
+    /* Output argument output code */
+    Printv(f->code, outarg, NIL);
+
+    /* Output cleanup code */
+    Printv(f->code, cleanup, NIL);
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+        Replaceall(tm, "$source", "result");
+        Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printf(f->code, "%s\n", tm);
+    }
+
+
+    /* Close the function */
+    Printv(f->code, "return SWIG_arg;\n", NIL);
+    // add the failure cleanup code:
+    Printv(f->code, "\nif(0) SWIG_fail;\n", NIL);
+    Printv(f->code, "\nfail:\n", NIL);
+    Printv(f->code, "$cleanup", "lua_error(L);\n", NIL);
+    Printv(f->code, "return SWIG_arg;\n", NIL);
+    Printf(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", iname);
+    Replaceall(f->code, "$result", "result");
+
+    /* Dump the function out */
+    /* in Lua we will not emit the destructor as a wrappered function,
+    Lua will automatically call the destructor when the object is free'd
+    However: you cannot just skip this function as it will not emit
+    any custom destructor (using %extend), as you need to call emit_action()
+    Therefore we go though the whole function, 
+    but do not write the code into the wrapper
+    */
+    if(current!=DESTRUCTOR) {
+       Wrapper_print(f, f_wrappers);
+    }
+    
+    /* NEW LANGUAGE NOTE:***********************************************
+    register the function in SWIG
+    different language mappings seem to use different ideas
+    NEW LANGUAGE NOTE:END ************************************************/
+    /* Now register the function with the interpreter. */
+    if (!Getattr(n, "sym:overloaded")) {
+      //      add_method(n, iname, wname, description);
+      if (current==NO_CPP || current==STATIC_FUNC) // emit normal fns & static fns
+        Printv(s_cmd_tab, tab4, "{ \"", iname, "\", ", Swig_name_wrapper(iname), "},\n", NIL);
+      //      Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", Swig_name_wrapper(iname), "},\n", NIL);
+    } else {
+      if (!Getattr(n, "sym:nextSibling")) {
+        dispatchFunction(n);
+      }
+    }
+
+    Delete(argument_check);
+    Delete(argument_parse);
+
+    Delete(cleanup);
+    Delete(outarg);
+    //    Delete(description);
+    Delete(wname);
+    DelWrapper(f);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * dispatchFunction()
+   *
+   * Emit overloading dispatch function
+   * ------------------------------------------------------------ */
+
+  /* NEW LANGUAGE NOTE:***********************************************
+  This is an extra function used for overloading of functions
+  it checks the args & then calls the relevant fn
+  nost of the real work in again typemaps:
+  look for %typecheck(SWIG_TYPECHECK_*) in the .swg file
+  NEW LANGUAGE NOTE:END ************************************************/
+  void dispatchFunction(Node *n) {
+    /* Last node in overloaded chain */
+
+    int maxargs;
+    String *tmp = NewString("");
+    String *dispatch = Swig_overload_dispatch(n, "return %s(L);", &maxargs);
+
+    /* Generate a dispatch wrapper for all overloaded functions */
+
+    Wrapper *f = NewWrapper();
+    String *symname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(symname);
+
+    //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs);
+
+    Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL);
+    Wrapper_add_local(f, "argc", "int argc");
+    Printf(tmp, "int argv[%d]={1", maxargs + 1);
+    for (int i = 1; i <= maxargs; i++) {
+      Printf(tmp, ",%d", i + 1);
+    }
+    Printf(tmp, "}");
+    Wrapper_add_local(f, "argv", tmp);
+    Printf(f->code, "argc = lua_gettop(L);\n");
+
+    Replaceall(dispatch, "$args", "self,args");
+    Printv(f->code, dispatch, "\n", NIL);
+    
+    Node *sibl = n;
+    while (Getattr(sibl, "sym:previousSibling"))
+      sibl = Getattr(sibl, "sym:previousSibling");	// go all the way up
+    String *protoTypes = NewString("");
+    do {
+      Printf(protoTypes, "\n\"    %s(%s)\\n\"", SwigType_str(Getattr(sibl, "name"), 0), ParmList_protostr(Getattr(sibl, "wrap:parms")));
+    } while ((sibl = Getattr(sibl, "sym:nextSibling")));
+    Printf(f->code, "lua_pushstring(L,\"Wrong arguments for overloaded function '%s'\\n\"\n"
+        "\"  Possible C/C++ prototypes are:\\n\"%s);\n",symname,protoTypes);
+    Delete(protoTypes);
+
+    Printf(f->code, "lua_error(L);return 0;\n");
+    Printv(f->code, "}\n", NIL);
+    Wrapper_print(f, f_wrappers);
+    //add_method(symname,wname,0);
+    if (current==NO_CPP || current==STATIC_FUNC) // emit normal fns & static fns
+      Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL);
+
+    DelWrapper(f);
+    Delete(dispatch);
+    Delete(tmp);
+    Delete(wname);
+  }
+
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+    /* NEW LANGUAGE NOTE:***********************************************
+    Language::variableWrapper(n) will generate two wrapper fns
+    Foo_get & Foo_set by calling functionWrapper()
+    so we will just add these into the variable lists
+    ideally we should not have registered these as functions,
+    only WRT this variable will look into this later.
+    NEW LANGUAGE NOTE:END ************************************************/
+    //    REPORT("variableWrapper", n);
+    String *iname = Getattr(n, "sym:name");
+    current=VARIABLE;
+    // let SWIG generate the wrappers
+    int result = Language::variableWrapper(n);
+    current=NO_CPP;
+    // normally SWIG will generate 2 wrappers, a get and a set
+    // but in certain scenarios (immutable, or if its arrays), it will not
+    String *getName = Swig_name_wrapper(Swig_name_get(iname));
+    String *setName = 0;
+    // checking whether it can be set to or not appears to be a very error prone issue
+    // I refered to the Language::variableWrapper() to find this out
+    bool assignable=is_assignable(n) ? true : false;
+    SwigType *type = Getattr(n, "type");
+    String *tm = Swig_typemap_lookup("globalin", n, iname, 0);
+    if (!tm && SwigType_isarray(type))
+      assignable=false;
+    Delete(tm);
+
+    if (assignable) {
+      setName = Swig_name_wrapper(Swig_name_set(iname));
+    } else {
+      // how about calling a 'this is not settable' error message?
+      setName = NewString("SWIG_Lua_set_immutable"); // error message
+      //setName = NewString("0");
+    }
+    // register the variable
+    Printf(s_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName);
+    Delete(getName);
+    Delete(setName);
+    return result;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+  virtual int constantWrapper(Node *n) {
+    //    REPORT("constantWrapper", n);
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    //String *nsname    = !nspace ? Copy(iname) : NewStringf("%s::%s",ns_name,iname);
+    String *nsname = Copy(iname);
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+    //if (nspace) Setattr(n,"sym:name",nsname);
+
+    /* Special hook for member pointer */
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(iname);
+      Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value);
+      value = Char(wname);
+    }
+
+    if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Replaceall(tm, "$nsname", nsname);
+      Printf(s_const_tab, "%s,\n", tm);
+    } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Replaceall(tm, "$nsname", nsname);
+      Printf(f_init, "%s\n", tm);
+    } else {
+      Delete(nsname);
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+    Delete(nsname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * nativeWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int nativeWrapper(Node *n) {
+    //    REPORT("nativeWrapper", n);
+    String *symname = Getattr(n, "sym:name");
+    String *wrapname = Getattr(n, "wrap:name");
+    if (!addSymbol(wrapname, n))
+      return SWIG_ERROR;
+
+    Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL);
+    //   return Language::nativeWrapper(n); // this does nothing...
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * enumDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumDeclaration(Node *n) {
+    return Language::enumDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * enumvalueDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumvalueDeclaration(Node *n) {
+    return Language::enumvalueDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int classDeclaration(Node *n) {
+    return Language::classDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int classHandler(Node *n) {
+    //REPORT("classHandler", n);
+
+    String *mangled_classname = 0;
+    String *real_classname = 0;
+
+    constructor_name = 0;
+    have_constructor = 0;
+    have_destructor = 0;
+    destructor_action = 0;
+
+    class_name = Getattr(n, "sym:name");
+    if (!addSymbol(class_name, n))
+      return SWIG_ERROR;
+
+    real_classname = Getattr(n, "name");
+    mangled_classname = Swig_name_mangle(real_classname);
+
+    // not sure exactly how this workswhat this works,
+    // but tcl has a static hashtable of all classes emitted and then only emits code for them once.
+    // this fixes issues in test suites: template_default2 & template_specialization
+
+    // * if i understand correctly, this is a bug.
+    // * consider effect on template_specialization_defarg
+
+    static Hash *emitted = NewHash();
+    if (Getattr(emitted, mangled_classname))
+      return SWIG_NOWRAP;
+    Setattr(emitted, mangled_classname, "1");
+
+    s_attr_tab = NewString("");
+    Printf(s_attr_tab, "static swig_lua_attribute swig_");
+    Printv(s_attr_tab, mangled_classname, "_attributes[] = {\n", NIL);
+
+    s_methods_tab = NewString("");
+    Printf(s_methods_tab, "static swig_lua_method swig_");
+    Printv(s_methods_tab, mangled_classname, "_methods[] = {\n", NIL);
+
+    // Generate normal wrappers
+    Language::classHandler(n);
+
+    SwigType *t = Copy(Getattr(n, "name"));
+    SwigType_add_pointer(t);
+
+    // Catch all: eg. a class with only static functions and/or variables will not have 'remembered'
+    String *wrap_class = NewStringf("&_wrap_class_%s", mangled_classname);
+    SwigType_remember_clientdata(t, wrap_class);
+
+    String *rt = Copy(Getattr(n, "classtype"));
+    SwigType_add_pointer(rt);
+
+    // Register the class structure with the type checker
+    //    Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_classname);
+ 
+    // emit a function to be called to delete the object 
+    if (have_destructor) {
+      Printv(f_wrappers, "static void swig_delete_", class_name, "(void *obj) {\n", NIL);
+      if (destructor_action) {
+        Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL);
+        Printv(f_wrappers, destructor_action, "\n", NIL);
+      } else {
+        if (CPlusPlus) {
+          Printv(f_wrappers, "    delete (", SwigType_str(rt, 0), ") obj;\n", NIL);
+        } else {
+          Printv(f_wrappers, "    free((char *) obj);\n", NIL);
+        }
+      }
+      Printf(f_wrappers, "}\n");
+    }
+
+    Printf(s_methods_tab, "    {0,0}\n};\n");
+    Printv(f_wrappers, s_methods_tab, NIL);
+
+    Printf(s_attr_tab, "    {0,0,0}\n};\n");
+    Printv(f_wrappers, s_attr_tab, NIL);
+
+    Delete(s_methods_tab);
+    Delete(s_attr_tab);
+
+    // Handle inheritance
+    // note: with the idea of class hireachied spread over multiple modules
+    // cf test-suite: imports.i
+    // it is not possible to just add the pointers to the base classes to the code
+    // (as sometimes these classes are not present)
+    // therefore we instead hold the name of the base class and a null pointer
+    // at runtime: we can query the swig type manager & see if the class exists
+    // if so, we can get the pointer to the base class & replace the null pointer
+    // if the type does not exist, then we cannot...
+    String *base_class = NewString("");
+    String *base_class_names = NewString("");
+
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist)) {
+      Iterator b;
+      int index = 0;
+      b = First(baselist);
+      while (b.item) {
+        String *bname = Getattr(b.item, "name");
+        if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) {
+          b = Next(b);
+          continue;
+        }
+        // old code: (used the pointer to the base class)
+        //String *bmangle = Swig_name_mangle(bname);
+        //Printf(base_class, "&_wrap_class_%s", bmangle);
+        //Putc(',', base_class);
+        //Delete(bmangle);
+        // new code: stores a null pointer & the name
+        Printf(base_class, "0,");
+        Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname));
+
+        b = Next(b);
+        index++;
+      }
+    }
+
+    Printv(f_wrappers, "static swig_lua_class *swig_", mangled_classname, "_bases[] = {", base_class, "0};\n", NIL);
+    Delete(base_class);
+    Printv(f_wrappers, "static const char *swig_", mangled_classname, "_base_names[] = {", base_class_names, "0};\n", NIL);
+    Delete(base_class_names);
+
+    Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_classname, " = { \"", class_name, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL);
+
+    if (have_constructor) {
+      Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(constructor_name)));
+      Delete(constructor_name);
+      constructor_name = 0;
+    } else {
+      Printf(f_wrappers, "0");
+    }
+
+    if (have_destructor) {
+      Printv(f_wrappers, ", swig_delete_", class_name, NIL);
+    } else {
+      Printf(f_wrappers, ",0");
+    }
+    Printf(f_wrappers, ", swig_%s_methods, swig_%s_attributes, swig_%s_bases, swig_%s_base_names };\n\n", mangled_classname, mangled_classname, mangled_classname, mangled_classname);
+
+    //    Printv(f_wrappers, ", swig_", mangled_classname, "_methods, swig_", mangled_classname, "_attributes, swig_", mangled_classname, "_bases };\n\n", NIL);
+    //    Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_classname, "},\n", NIL);
+    Delete(t);
+    Delete(mangled_classname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberfunctionHandler(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = GetChar(n, "sym:name");
+    //Printf(stdout,"memberfunctionHandler %s %s\n",name,iname);
+
+    // Special case unary minus: LUA passes two parameters for the
+    // wrapper function while we want only one. Tell our
+    // functionWrapper to ignore a parameter.
+
+    if (Cmp(Getattr(n, "sym:name"), "__unm") == 0) {
+      //Printf(stdout, "unary minus: ignore one argument\n");
+      SetInt(n, "lua:ignore_args", 1);
+    }
+
+    String *realname, *rname;
+
+    current = MEMBER_FUNC;
+    Language::memberfunctionHandler(n);
+    current = NO_CPP;
+
+    realname = iname ? iname : name;
+    rname = Swig_name_wrapper(Swig_name_member(class_name, realname));
+    if (!Getattr(n, "sym:nextSibling")) {
+      Printv(s_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL);
+    }
+    Delete(rname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int membervariableHandler(Node *n) {
+    //    REPORT("membervariableHandler",n);
+    String *symname = Getattr(n, "sym:name");
+    String *gname, *sname;
+
+    current = MEMBER_VAR;
+    Language::membervariableHandler(n);
+    current = NO_CPP;
+    gname = Swig_name_wrapper(Swig_name_get(Swig_name_member(class_name, symname)));
+    if (!GetFlag(n, "feature:immutable")) {
+      sname = Swig_name_wrapper(Swig_name_set(Swig_name_member(class_name, symname)));
+    } else {
+      //sname = NewString("0");
+      sname = NewString("SWIG_Lua_set_immutable"); // error message
+    }
+    Printf(s_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,gname,sname);
+    Delete(gname);
+    Delete(sname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constructorHandler()
+   *
+   * Method for adding C++ member constructor
+   * ------------------------------------------------------------ */
+
+  virtual int constructorHandler(Node *n) {
+    //    REPORT("constructorHandler", n);
+    current = CONSTRUCTOR;
+    Language::constructorHandler(n);
+    current = NO_CPP;
+    constructor_name = NewString(Getattr(n, "sym:name"));
+    have_constructor = 1;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * destructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int destructorHandler(Node *n) {
+    REPORT("destructorHandler", n);
+    current = DESTRUCTOR;
+    Language::destructorHandler(n);
+    current = NO_CPP;
+    have_destructor = 1;
+    destructor_action = Getattr(n, "wrap:action");
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   *
+   * Wrap a static C++ function
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    current = STATIC_FUNC;
+    return Language::staticmemberfunctionHandler(n);
+  }
+
+  /* ------------------------------------------------------------
+   * memberconstantHandler()
+   *
+   * Create a C++ constant
+   * ------------------------------------------------------------ */
+
+  virtual int memberconstantHandler(Node *n) {
+    //    REPORT("memberconstantHandler",n);
+    return Language::memberconstantHandler(n);
+  }
+
+  /* ---------------------------------------------------------------------
+   * staticmembervariableHandler()
+   * --------------------------------------------------------------------- */
+
+  virtual int staticmembervariableHandler(Node *n) {
+    //    REPORT("staticmembervariableHandler",n);
+    current = STATIC_VAR;
+    return Language::staticmembervariableHandler(n);
+  }
+
+  /* ---------------------------------------------------------------------
+   * external runtime generation
+   * --------------------------------------------------------------------- */
+
+  /* This is to support the usage
+     SWIG -external-runtime <filename>
+     The code consists of two functions:
+     String *runtimeCode()  // returns a large string with all the runtimes in
+     String *defaultExternalRuntimeFilename() // returns the default filename
+     I am writing a generic solution, even though SWIG-Lua only has one file right now...
+   */
+  String *runtimeCode() {
+    String *s = NewString("");
+    const char *filenames[] = { "luarun.swg", 0
+                              }
+                              ;	// must be 0 termiated
+    String *sfile;
+    for (int i = 0; filenames[i] != 0; i++) {
+      sfile = Swig_include_sys(filenames[i]);
+      if (!sfile) {
+        Printf(stderr, "*** Unable to open '%s'\n", filenames[i]);
+      } else {
+        Append(s, sfile);
+        Delete(sfile);
+      }
+    }
+
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigluarun.h");
+  }
+  
+  /* ---------------------------------------------------------------------
+   * helpers
+   * --------------------------------------------------------------------- */
+
+  /* This is to convert the string of Lua code into a proper string, which can then be
+     emitted into the C/C++ code.
+     Basically is is a lot of search & replacing of odd sequences
+   */
+  void EscapeCode(String* str)
+  {
+    //Printf(f_runtime,"/* original luacode:[[[\n%s\n]]]\n*/\n",str);
+    Chop(str); // trim
+    Replace(str,"\\","\\\\",DOH_REPLACE_ANY); // \ to \\ (this must be done first)
+    Replace(str,"\"","\\\"",DOH_REPLACE_ANY); // " to \"
+    Replace(str,"\n","\\n\"\n  \"",DOH_REPLACE_ANY); // \n to \n"\n" (ie quoting every line)
+    //Printf(f_runtime,"/* hacked luacode:[[[\n%s\n]]]\n*/\n",str);
+  } 
+};
+
+/* NEW LANGUAGE NOTE:***********************************************
+ in order to add you language into swig, you need to make the following changes:
+ - write this file (obviously)
+ - add into the makefile (not 100% clear on how to do this)
+ - edit swigmain.cxx to add your module
+ 
+near the top of swigmain.cxx, look for this code & add you own codes
+======= begin change ==========
+extern "C" {
+  Language *swig_tcl(void);
+  Language *swig_python(void);
+  //etc,etc,etc...
+  Language *swig_lua(void);	// this is my code
+}
+ 
+  //etc,etc,etc...
+ 
+swig_module  modules[] = {
+  {"-guile",     swig_guile,     "Guile"},
+  {"-java",      swig_java,      "Java"},
+  //etc,etc,etc...
+  {"-lua",       swig_lua,       "Lua"},	// this is my code
+  {NULL, NULL, NULL}	// this must come at the end of the list
+};
+======= end change ==========
+ 
+This is all that is needed
+ 
+NEW LANGUAGE NOTE:END ************************************************/
+
+/* -----------------------------------------------------------------------------
+ * swig_lua()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+extern "C" Language *swig_lua(void) {
+  return new LUA();
+}
diff --git a/trunk/Source/Modules/main.cxx b/trunk/Source/Modules/main.cxx
new file mode 100644
index 0000000..901ee81
--- /dev/null
+++ b/trunk/Source/Modules/main.cxx
@@ -0,0 +1,1199 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * main.cxx
+ *
+ * Main entry point to the SWIG core.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_main_cxx[] = "$Id$";
+
+#include "swigconfig.h"
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
+#include "swigmod.h"
+
+#include "swigwarn.h"
+#include "cparse.h"
+#include <ctype.h>
+#include <limits.h>		// for INT_MAX
+
+// Global variables
+
+Language *lang;			// Language method
+int CPlusPlus = 0;
+int Extend = 0;			// Extend flag
+int ForceExtern = 0;		// Force extern mode
+int GenerateDefault = 1;	// Generate default constructors
+int Verbose = 0;
+int AddExtern = 0;
+int NoExcept = 0;
+int SwigRuntime = 0;		// 0 = no option, 1 = -runtime, 2 = -noruntime
+
+/* Suppress warning messages for private inheritance, preprocessor evaluation etc...
+   WARN_PP_EVALUATION            202
+   WARN_PARSE_PRIVATE_INHERIT    309
+   WARN_TYPE_ABSTRACT            403
+   WARN_LANG_OVERLOAD_CONST      512
+   WARN_PARSE_BUILTIN_NAME       321
+   WARN_PARSE_REDUNDANT          322
+ */
+#define EXTRA_WARNINGS "202,309,403,512,321,322"
+
+extern "C" {
+  extern String *ModuleName;
+}
+
+/* usage string split into multiple parts otherwise string is too big for some compilers */
+/* naming conventions for commandline options - no underscores, no capital letters, join words together
+ * except when using a common prefix, then use '-' to separate, eg the debug-xxx options */
+static const char *usage1 = (const char *) "\
+\nGeneral Options\n\
+     -addextern      - Add extra extern declarations\n\
+     -c++            - Enable C++ processing\n\
+     -co <file>      - Check <file> out of the SWIG library\n\
+     -copyctor       - Automatically generate copy constructors wherever possible\n\
+     -cpperraswarn   - Treat the preprocessor #error statement as #warning (default)\n\
+     -copyright      - Display copyright notices\n\
+     -debug-classes  - Display information about the classes found in the interface\n\
+     -debug-module <n>- Display module parse tree at stages 1-4, <n> is a csv list of stages\n\
+     -debug-tags     - Display information about the tags found in the interface\n\
+     -debug-template - Display information for debugging templates\n\
+     -debug-top <n>  - Display entire parse tree at stages 1-4, <n> is a csv list of stages\n\
+     -debug-typedef  - Display information about the types and typedefs in the interface\n\
+     -debug-typemap  - Display information for debugging typemaps\n\
+     -directors      - Turn on director mode for all the classes, mainly for testing\n\
+     -dirprot        - Turn on wrapping of protected members for director classes (default)\n\
+     -D<symbol>      - Define a symbol <symbol> (for conditional compilation)\n\
+     -E              - Preprocess only, does not generate wrapper code\n\
+     -external-runtime [file] - Export the SWIG runtime stack\n\
+     -fakeversion <v>- Make SWIG fake the program version number to <v>\n\
+     -fcompact       - Compile in compact mode\n\
+     -features <list>- Set global features, where <list> is a comma separated list of\n\
+                       features, eg -features directors,autodoc=1\n\
+                       If no explicit value is given to the feature, a default of 1 is used\n\
+";
+
+static const char *usage2 = (const char *) "\
+     -fastdispatch   - Enable fast dispatch mode to produce faster overload dispatcher code\n\
+     -Fmicrosoft     - Display error/warning messages in Microsoft format\n\
+     -Fstandard      - Display error/warning messages in commonly used format\n\
+     -fvirtual       - Compile in virtual elimination mode\n\
+     -help           - This output\n\
+     -I-             - Don't search the current directory\n\
+     -I<dir>         - Look for SWIG files in directory <dir>\n\
+     -ignoremissing  - Ignore missing include files\n\
+     -importall      - Follow all #include statements as imports\n\
+     -includeall     - Follow all #include statements\n\
+     -l<ifile>       - Include SWIG library file <ifile>\n\
+     -macroerrors    - Report errors inside macros\n\
+     -makedefault    - Create default constructors/destructors (the default)\n\
+     -M              - List all dependencies\n\
+     -MD             - Is equivalent to `-M -MF <file>', except `-E' is not implied\n\
+     -MF <file>      - Generate dependencies into <file> and continue generating wrappers\n\
+     -MM             - List dependencies, but omit files in SWIG library\n\
+     -MMD            - Like `-MD', but omit files in SWIG library\n\
+     -module <name>  - Set module name to <name>\n\
+     -MT <target>    - Set the target of the rule emitted by dependency generation\n\
+     -nocontract     - Turn off contract checking\n\
+     -nocpperraswarn - Do not treat the preprocessor #error statement as #warning\n\
+     -nodefault      - Do not generate default constructors nor default destructors\n\
+     -nodefaultctor  - Do not generate implicit default constructors\n\
+     -nodefaultdtor  - Do not generate implicit default destructors\n\
+     -nodirprot      - Do not wrap director protected members\n\
+     -noexcept       - Do not wrap exception specifiers\n\
+     -nofastdispatch - Disable fast dispatch mode (default)\n\
+     -nopreprocess   - Skip the preprocessor step\n\
+";
+
+static const char *usage3 = (const char *) "\
+     -notemplatereduce - Disable reduction of the typedefs in templates\n\
+     -O              - Enable the optimization options: \n\
+                        -fastdispatch -fvirtual \n\
+     -o <outfile>    - Set name of the output file to <outfile>\n\
+     -oh <headfile>  - Set name of the output header file to <headfile>\n\
+     -outdir <dir>   - Set language specific files output directory <dir>\n\
+     -small          - Compile in virtual elimination & compact mode\n\
+     -swiglib        - Report location of SWIG library and exit\n\
+     -templatereduce - Reduce all the typedefs in templates\n\
+     -v              - Run in verbose mode\n\
+     -version        - Display SWIG version number\n\
+     -Wall           - Remove all warning suppression, also implies -Wextra\n\
+     -Wallkw         - Enable keyword warnings for all the supported languages\n\
+     -Werror         - Treat warnings as errors\n\
+     -Wextra         - Adds the following additional warnings: " EXTRA_WARNINGS "\n\
+     -w<list>        - Suppress/add warning messages, eg -w401,+321 - see Warnings.html\n\
+     -xmlout <file>  - Write XML version of the parse tree to <file> after normal processing\n\
+\n\
+Options can also be defined using the SWIG_FEATURES environment variable, for example:\n\
+\n\
+  $ SWIG_FEATURES=\"-Wall\"\n\
+  $ export SWIG_FEATURES\n\
+  $ swig -python interface.i\n\
+\n\
+is equivalent to: \n\
+\n\
+  $ swig -Wall -python interface.i \n\
+\n\
+\n";
+
+// Local variables
+static String *LangSubDir = 0;	// Target language library subdirectory
+static char *SwigLib = 0;	// Library directory
+static String *SwigLibWin = 0;	// Extra Library directory for Windows
+static int freeze = 0;
+static String *lang_config = 0;
+static char *hpp_extension = (char *) "h";
+static char *cpp_extension = (char *) "cxx";
+static char *depends_extension = (char *) "d";
+static String *outdir = 0;
+static String *xmlout = 0;
+static int help = 0;
+static int checkout = 0;
+static int cpp_only = 0;
+static int no_cpp = 0;
+static char *outfile_name = 0;
+static char *outfile_name_h = 0;
+static int tm_debug = 0;
+static int dump_tags = 0;
+static int dump_module = 0;
+static int dump_top = 0;
+static int dump_xml = 0;
+static int browse = 0;
+static int dump_typedef = 0;
+static int dump_classes = 0;
+static int werror = 0;
+static int depend = 0;
+static int depend_only = 0;
+static int memory_debug = 0;
+static int allkw = 0;
+static DOH *libfiles = 0;
+static DOH *cpps = 0;
+static String *dependencies_file = 0;
+static File *f_dependencies_file = 0;
+static String *dependencies_target = 0;
+static int external_runtime = 0;
+static String *external_runtime_name = 0;
+enum { STAGE1=1, STAGE2=2, STAGE3=4, STAGE4=8, STAGEOVERFLOW=16 };
+
+// -----------------------------------------------------------------------------
+// check_suffix(char *name)
+//
+// Checks the suffix of a file to see if we should emit extern declarations.
+// -----------------------------------------------------------------------------
+
+static int check_suffix(const char *name) {
+  const char *c;
+  if (!name)
+    return 0;
+  c = Swig_file_suffix(name);
+  if ((strcmp(c, ".c") == 0) ||
+      (strcmp(c, ".C") == 0) || (strcmp(c, ".cc") == 0) || (strcmp(c, ".cxx") == 0) || (strcmp(c, ".c++") == 0) || (strcmp(c, ".cpp") == 0)) {
+    return 1;
+  }
+  return 0;
+}
+
+// -----------------------------------------------------------------------------
+// install_opts(int argc, char *argv[])
+// Install all command line options as preprocessor symbols
+// ----------------------------------------------------------------------------- 
+
+static void install_opts(int argc, char *argv[]) {
+  int i;
+  int noopt = 0;
+  char *c;
+  for (i = 1; i < (argc - 1); i++) {
+    if (argv[i]) {
+      if ((*argv[i] == '-') && (!isupper(*(argv[i] + 1)))) {
+	String *opt = NewStringf("SWIGOPT%(upper)s", argv[i]);
+	Replaceall(opt, "-", "_");
+	c = Char(opt);
+	noopt = 0;
+	while (*c) {
+	  if (!(isalnum(*c) || (*c == '_'))) {
+	    noopt = 1;
+	    break;
+	  }
+	  c++;
+	}
+	if (((i + 1) < (argc - 1)) && (argv[i + 1]) && (*argv[i + 1] != '-')) {
+	  Printf(opt, " %s", argv[i + 1]);
+	  i++;
+	} else {
+	  Printf(opt, " 1");
+	}
+	if (!noopt) {
+	  /*      Printf(stdout,"%s\n", opt); */
+	  Preprocessor_define(opt, 0);
+	}
+	Delete(opt);
+      }
+    }
+  }
+}
+
+// -----------------------------------------------------------------------------
+// decode_numbers_list(String *numlist)
+// Decode comma separated list into a binary number of the inputs or'd together
+// eg list="1,4" will return (2^0 || 2^3) = 0x1001
+// ----------------------------------------------------------------------------- 
+
+static unsigned int decode_numbers_list(String *numlist) {
+  unsigned int decoded_number = 0;
+  if (numlist) {
+    List *numbers = Split(numlist, ',', INT_MAX);
+    if (numbers && Len(numbers) > 0) {
+      for (Iterator it = First(numbers); it.item; it = Next(it)) {
+        String *numstring = it.item;
+        // TODO: check that it is a number
+        int number = atoi(Char(numstring));
+        if (number > 0 && number <= 16) {
+          decoded_number |= (1 << (number-1));
+        }
+      }
+    }
+  }
+  return decoded_number;
+}
+
+// -----------------------------------------------------------------------------
+// Sets the output directory for language specific (proxy) files if not set and 
+// adds trailing file separator if necessary.
+// ----------------------------------------------------------------------------- 
+
+static void set_outdir(const String *c_wrapper_file_dir) {
+
+  // Add file delimiter if not present in output directory name
+  if (outdir && Len(outdir) != 0) {
+    const char *outd = Char(outdir);
+    if (strcmp(outd + strlen(outd) - strlen(SWIG_FILE_DELIMITER), SWIG_FILE_DELIMITER) != 0)
+      Printv(outdir, SWIG_FILE_DELIMITER, NIL);
+  }
+  // Use the C wrapper file's directory if the output directory has not been set by user
+  if (!outdir)
+    outdir = NewString(c_wrapper_file_dir);
+}
+
+/* This function sets the name of the configuration file */
+void SWIG_config_file(const String_or_char *filename) {
+  lang_config = NewString(filename);
+}
+
+/* Sets the target language subdirectory name */
+void SWIG_library_directory(const char *subdirectory) {
+  LangSubDir = NewString(subdirectory);
+}
+
+// Returns the directory for generating language specific files (non C/C++ files)
+const String *SWIG_output_directory() {
+  assert(outdir);
+  return outdir;
+}
+
+void SWIG_config_cppext(const char *ext) {
+  cpp_extension = (char *) ext;
+}
+
+void SWIG_setfeature(const char *cfeature, const char *cvalue) {
+  Hash *features_hash = Swig_cparse_features();
+  String *name = NewString("");
+  String *fname = NewString(cfeature);
+  String *fvalue = NewString(cvalue);
+  Swig_feature_set(features_hash, name, 0, fname, fvalue, 0);
+  Delete(name);
+  Delete(fname);
+  Delete(fvalue);
+}
+
+
+void SWIG_setfeatures(const char *c) {
+  char feature[64];
+  char *fb = feature;
+  char *fe = fb + 63;
+  Hash *features_hash = Swig_cparse_features();
+  String *name = NewString("");
+  /* Printf(stderr,"all features %s\n", c); */
+  while (*c) {
+    char *f = fb;
+    String *fname = NewString("feature:");
+    String *fvalue = NewString("");
+    while ((f != fe) && *c != '=' && *c != ',' && *c) {
+      *(f++) = *(c++);
+    }
+    *f = 0;
+    Printf(fname, "%s", feature);
+    if (*c && *(c++) == '=') {
+      char value[64];
+      char *v = value;
+      char *ve = v + 63;
+      while ((v != ve) && *c != ',' && *c && !isspace(*c)) {
+	*(v++) = *(c++);
+      }
+      *v = 0;
+      Printf(fvalue, "%s", value);
+    } else {
+      Printf(fvalue, "1");
+    }
+    /* Printf(stderr,"%s %s\n", fname, fvalue);  */
+    Swig_feature_set(features_hash, name, 0, fname, fvalue, 0);
+    Delete(fname);
+    Delete(fvalue);
+  }
+  Delete(name);
+}
+
+/* This function handles the -external-runtime command option */
+static void SWIG_dump_runtime() {
+  String *outfile;
+  File *runtime;
+  String *s;
+
+  outfile = external_runtime_name;
+  if (!outfile) {
+    outfile = lang->defaultExternalRuntimeFilename();
+    if (!outfile) {
+      Printf(stderr, "*** Please provide a filename for the external runtime\n");
+      SWIG_exit(EXIT_FAILURE);
+    }
+  }
+
+  runtime = NewFile(outfile, "w");
+  if (!runtime) {
+    FileErrorDisplay(outfile);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  Swig_banner(runtime);
+
+  s = Swig_include_sys("swiglabels.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'swiglabels.swg'\n");
+    Close(runtime);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Printf(runtime, "%s", s);
+  Delete(s);
+
+  s = Swig_include_sys("swigerrors.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'swigerrors.swg'\n");
+    Close(runtime);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Printf(runtime, "%s", s);
+  Delete(s);
+
+  s = Swig_include_sys("swigerrors.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'swigerrors.swg'\n");
+    Close(runtime);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Printf(runtime, "%s", s);
+  s = Swig_include_sys("swigrun.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'swigrun.swg'\n");
+    Close(runtime);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Printf(runtime, "%s", s);
+  Delete(s);
+
+  s = lang->runtimeCode();
+  Printf(runtime, "%s", s);
+  Delete(s);
+
+  s = Swig_include_sys("runtime.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'runtime.swg'\n");
+    Close(runtime);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Printf(runtime, "%s", s);
+  Delete(s);
+
+  Close(runtime);
+  Delete(runtime);
+  SWIG_exit(EXIT_SUCCESS);
+}
+
+void SWIG_getoptions(int argc, char *argv[]) {
+  int i;
+  // Get options
+  for (i = 1; i < argc; i++) {
+    if (argv[i] && !Swig_check_marked(i)) {
+      if (strncmp(argv[i], "-I-", 3) == 0) {
+	// Don't push/pop directories
+	Swig_set_push_dir(0);
+	Swig_mark_arg(i);
+      } else if (strncmp(argv[i], "-I", 2) == 0) {
+	// Add a new directory search path
+	char *a = Swig_copy_string(argv[i] + 2);
+	Swig_add_directory((DOH *) a);
+	free(a);
+	Swig_mark_arg(i);
+      } else if (strncmp(argv[i], "-D", 2) == 0) {
+	String *d = NewString(argv[i] + 2);
+	Replace(d, (char *) "=", (char *) " ", DOH_REPLACE_ANY | DOH_REPLACE_FIRST);
+	Preprocessor_define((DOH *) d, 0);
+	Delete(d);
+	// Create a symbol
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-E") == 0) {
+	cpp_only = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nopreprocess") == 0) {
+	no_cpp = 1;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-verbose") == 0) || (strcmp(argv[i], "-v") == 0)) {
+	Verbose = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-c++") == 0) {
+	CPlusPlus = 1;
+	Preprocessor_define((DOH *) "__cplusplus __cplusplus", 0);
+	Swig_cparse_cplusplus(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-fcompact") == 0) {
+	Wrapper_compact_print_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-fvirtual") == 0) {
+	Wrapper_virtual_elimination_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-fastdispatch") == 0) {
+	Wrapper_fast_dispatch_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nofastdispatch") == 0) {
+	Wrapper_fast_dispatch_mode_set(0);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-naturalvar") == 0) {
+	Wrapper_naturalvar_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nonaturalvar") == 0) {
+	Wrapper_naturalvar_mode_set(0);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-directors") == 0) {
+	SWIG_setfeature("feature:director", "1");
+	Wrapper_director_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-dirprot") == 0) {
+	Wrapper_director_protected_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nodirprot") == 0) {
+	Wrapper_director_protected_mode_set(0);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-small") == 0) {
+	Wrapper_compact_print_mode_set(1);
+	Wrapper_virtual_elimination_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-runtime") == 0) { // Used to also accept -c. removed in swig-1.3.36
+	Swig_mark_arg(i);
+	Swig_warning(WARN_DEPRECATED_OPTC, "SWIG", 1, "-runtime, -noruntime command line options are deprecated.\n");
+	SwigRuntime = 1;
+      } else if (strcmp(argv[i], "-noruntime") == 0) {
+	Swig_mark_arg(i);
+	Swig_warning(WARN_DEPRECATED_OPTC, "SWIG", 1, "-runtime, -noruntime command line options are deprecated.\n");
+	SwigRuntime = 2;
+      } else if (strcmp(argv[i], "-external-runtime") == 0) {
+	external_runtime = 1;
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  external_runtime_name = NewString(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	  i++;
+	}
+      } else if ((strcmp(argv[i], "-make_default") == 0) || (strcmp(argv[i], "-makedefault") == 0)) {
+	GenerateDefault = 1;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-no_default") == 0) || (strcmp(argv[i], "-nodefault") == 0)) {
+	GenerateDefault = 0;
+	Swig_warning(WARN_DEPRECATED_NODEFAULT, "SWIG", 1, "dangerous, use -nodefaultctor, -nodefaultdtor instead.\n");
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-nodefaultctor") == 0)) {
+	SWIG_setfeature("feature:nodefaultctor", "1");
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-nodefaultdtor") == 0)) {
+	SWIG_setfeature("feature:nodefaultdtor", "1");
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-copyctor") == 0)) {
+	SWIG_setfeature("feature:copyctor", "1");
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-noexcept") == 0) {
+	NoExcept = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-noextern") == 0) {
+	Swig_warning(WARN_DEPRECATED_NOEXTERN, "SWIG", 1, "-noextern command line option is deprecated; extern is no longer generated by default.\n");
+	AddExtern = 0;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-addextern") == 0) {
+	AddExtern = 1;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-debug-template") == 0) || (strcmp(argv[i], "-debug_template") == 0) || (strcmp(argv[i], "-show_templates") == 0)) {
+	Swig_cparse_debug_templates(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-templatereduce") == 0) {
+	SWIG_cparse_template_reduce(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-notemplatereduce") == 0) {
+	SWIG_cparse_template_reduce(0);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-macroerrors") == 0) {
+	Swig_cparse_follow_locators(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-swiglib") == 0) {
+	if (SwigLibWin)
+	  printf("%s\n", Char(SwigLibWin));
+	printf("%s\n", SwigLib);
+	SWIG_exit(EXIT_SUCCESS);
+      } else if (strcmp(argv[i], "-o") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  outfile_name = Swig_copy_string(argv[i + 1]);
+	  if (!outfile_name_h || !dependencies_file) {
+	    char *ext = strrchr(outfile_name, '.');
+	    String *basename = ext ? NewStringWithSize(outfile_name, ext - outfile_name) : NewString(outfile_name);
+	    if (!dependencies_file) {
+	      dependencies_file = NewStringf("%s.%s", basename, depends_extension);
+	    }
+	    if (!outfile_name_h) {
+	      Printf(basename, ".%s", hpp_extension);
+	      outfile_name_h = Swig_copy_string(Char(basename));
+	    }
+	    Delete(basename);
+	  }
+	  Swig_mark_arg(i + 1);
+	  i++;
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-oh") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  outfile_name_h = Swig_copy_string(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	  i++;
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-fakeversion") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  Swig_set_fakeversion(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	  i++;
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-version") == 0) {
+	fprintf(stdout, "\nSWIG Version %s\n", Swig_package_version());
+	fprintf(stdout, "\nCompiled with %s [%s]\n", SWIG_CXX, SWIG_PLATFORM);
+	fprintf(stdout, "Please see %s for reporting bugs and further information\n", PACKAGE_BUGREPORT);
+	SWIG_exit(EXIT_SUCCESS);
+      } else if (strcmp(argv[i], "-copyright") == 0) {
+	fprintf(stdout, "\nSWIG Version %s\n", Swig_package_version());
+	fprintf(stdout, "Copyright (c) 1995-1998\n");
+	fprintf(stdout, "University of Utah and the Regents of the University of California\n");
+	fprintf(stdout, "Copyright (c) 1998-2005\n");
+	fprintf(stdout, "University of Chicago\n");
+	fprintf(stdout, "Copyright (c) 2005-2006\n");
+	fprintf(stdout, "Arizona Board of Regents (University of Arizona)\n");
+	SWIG_exit(EXIT_SUCCESS);
+      } else if (strncmp(argv[i], "-l", 2) == 0) {
+	// Add a new directory search path
+	Append(libfiles, argv[i] + 2);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-co") == 0) {
+	checkout = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-features") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  SWIG_setfeatures(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-freeze") == 0) {
+	freeze = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-includeall") == 0) {
+	Preprocessor_include_all(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-importall") == 0) {
+	Preprocessor_import_all(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-ignoremissing") == 0) {
+	Preprocessor_ignore_missing(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-cpperraswarn") == 0) {
+	Preprocessor_error_as_warning(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nocpperraswarn") == 0) {
+	Preprocessor_error_as_warning(0);
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-debug-typemap") == 0) || (strcmp(argv[i], "-debug_typemap") == 0) || (strcmp(argv[i], "-tm_debug") == 0)) {
+	tm_debug = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-module") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  ModuleName = NewString(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-M") == 0) {
+	depend = 1;
+	depend_only = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-MM") == 0) {
+	depend = 2;
+	depend_only = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-MF") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  dependencies_file = NewString(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-MD") == 0) {
+	depend = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-MMD") == 0) {
+	depend = 2;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-MT") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+          if (!dependencies_target)
+            dependencies_target = NewString(argv[i + 1]);
+          else
+            Printf(dependencies_target, " %s", argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-outdir") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  outdir = NewString(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-Wall") == 0) {
+	Swig_mark_arg(i);
+	Swig_warnall();
+      } else if (strcmp(argv[i], "-Wallkw") == 0) {
+	allkw = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-Werror") == 0) {
+	werror = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-Wextra") == 0) {
+	Swig_mark_arg(i);
+        Swig_warnfilter(EXTRA_WARNINGS, 0);
+      } else if (strncmp(argv[i], "-w", 2) == 0) {
+	Swig_mark_arg(i);
+	Swig_warnfilter(argv[i] + 2, 1);
+      } else if ((strcmp(argv[i], "-debug-tags") == 0) || (strcmp(argv[i], "-dump_tags") == 0)) {
+	dump_tags = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-debug-top") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  String *dump_list = NewString(argv[i + 1]);
+	  dump_top = decode_numbers_list(dump_list);
+          if (dump_top < STAGE1 || dump_top >= STAGEOVERFLOW)
+            Swig_arg_error();
+          else
+            Swig_mark_arg(i + 1);
+          Delete(dump_list);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-debug-module") == 0) {
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  String *dump_list = NewString(argv[i + 1]);
+	  dump_module = decode_numbers_list(dump_list);
+          if (dump_module < STAGE1 || dump_module >= STAGEOVERFLOW)
+            Swig_arg_error();
+          else
+            Swig_mark_arg(i + 1);
+          Delete(dump_list);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if ((strcmp(argv[i], "-dump_tree") == 0) || (strcmp(argv[i], "-dump_top") == 0)) {
+	dump_top |= STAGE4;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-dump_module") == 0) {
+	dump_module |= STAGE4;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-dump_parse_module") == 0) {
+	dump_module |= STAGE1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-dump_parse_top") == 0) {
+	dump_top |= STAGE1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-dump_xml") == 0) {
+	dump_xml = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-xmlout") == 0) {
+	dump_xml = 1;
+	Swig_mark_arg(i);
+	if (argv[i + 1]) {
+	  xmlout = NewString(argv[i + 1]);
+	  Swig_mark_arg(i + 1);
+	} else {
+	  Swig_arg_error();
+	}
+      } else if (strcmp(argv[i], "-nocontract") == 0) {
+	Swig_mark_arg(i);
+	Swig_contract_mode_set(0);
+      } else if (strcmp(argv[i], "-browse") == 0) {
+	browse = 1;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-debug-typedef") == 0) || (strcmp(argv[i], "-dump_typedef") == 0)) {
+	dump_typedef = 1;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-debug-classes") == 0) || (strcmp(argv[i], "-dump_classes") == 0)) {
+	dump_classes = 1;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-debug-memory") == 0) || (strcmp(argv[i], "-dump_memory") == 0)) {
+	memory_debug = 1;
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-Fstandard") == 0) {
+	Swig_error_msg_format(EMF_STANDARD);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-Fmicrosoft") == 0) {
+	Swig_error_msg_format(EMF_MICROSOFT);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-O") == 0) {
+	Wrapper_virtual_elimination_mode_set(1);
+	Wrapper_fast_dispatch_mode_set(1);
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-help") == 0) {
+	fputs(usage1, stdout);
+	fputs(usage2, stdout);
+	fputs(usage3, stdout);
+	Swig_mark_arg(i);
+	help = 1;
+      }
+    }
+  }
+}
+
+
+
+
+
+int SWIG_main(int argc, char *argv[], Language *l) {
+  char *c;
+  extern void Swig_print_xml(Node *obj, String *filename);
+
+  /* Initialize the SWIG core */
+  Swig_init();
+
+  // Default warning suppression
+  Swig_warnfilter(EXTRA_WARNINGS, 1);
+
+  // Initialize the preprocessor
+  Preprocessor_init();
+
+  lang = l;
+
+  // Set up some default symbols (available in both SWIG interface files
+  // and C files)
+
+  Preprocessor_define((DOH *) "SWIG 1", 0);
+  Preprocessor_define((DOH *) "__STDC__", 0);
+#ifdef MACSWIG
+  Preprocessor_define((DOH *) "SWIGMAC 1", 0);
+#endif
+#ifdef SWIGWIN32
+  Preprocessor_define((DOH *) "SWIGWIN32 1", 0);
+#endif
+
+  // Set the SWIG version value in format 0xAABBCC from package version expected to be in format A.B.C
+  String *package_version = NewString(PACKAGE_VERSION); /* Note that the fakeversion has not been set at this point */
+  char *token = strtok(Char(package_version), ".");
+  String *vers = NewString("SWIG_VERSION 0x");
+  int count = 0;
+  while (token) {
+    int len = strlen(token);
+    assert(len == 1 || len == 2);
+    Printf(vers, "%s%s", (len == 1) ? "0" : "", token);
+    token = strtok(NULL, ".");
+    count++;
+  }
+  Delete(package_version);
+  assert(count == 3);		// Check version format is correct
+
+  /* Turn on contracts */
+
+  Swig_contract_mode_set(1);
+  Preprocessor_define(vers, 0);
+
+  /* Turn off directors mode */
+  Wrapper_director_mode_set(0);
+  Wrapper_director_protected_mode_set(1);
+
+  // Create Library search directories
+
+  // Check for SWIG_LIB environment variable
+  if ((c = getenv("SWIG_LIB")) == (char *) 0) {
+#if defined(_WIN32)
+    char buf[MAX_PATH];
+    char *p;
+    if (!(GetModuleFileName(0, buf, MAX_PATH) == 0 || (p = strrchr(buf, '\\')) == 0)) {
+      *(p + 1) = '\0';
+      SwigLibWin = NewStringf("%sLib", buf);	// Native windows installation path
+    }
+    SwigLib = Swig_copy_string(SWIG_LIB_WIN_UNIX);	// Unix installation path using a drive letter (for msys/mingw)
+#else
+    SwigLib = Swig_copy_string(SWIG_LIB);
+#endif
+  } else {
+    SwigLib = Swig_copy_string(c);
+  }
+
+  libfiles = NewList();
+
+  /* Check for SWIG_FEATURES environment variable */
+
+  SWIG_getoptions(argc, argv);
+
+  // Define the __cplusplus symbol
+  if (CPlusPlus)
+    Preprocessor_define((DOH *) "__cplusplus __cplusplus", 0);
+
+  // Parse language dependent options
+  lang->main(argc, argv);
+
+  if (help) {
+    Printf(stdout, "\nNote: 'swig -<lang> -help' displays options for a specific target language.\n\n");
+    SWIG_exit(EXIT_SUCCESS);	// Exit if we're in help mode
+  }
+  // Check all of the options to make sure we're cool.
+  // Don't check for an input file if -external-runtime is passed
+  Swig_check_options(external_runtime ? 0 : 1);
+
+  install_opts(argc, argv);
+
+  // Add language dependent directory to the search path
+  {
+    String *rl = NewString("");
+    Printf(rl, ".%sswig_lib%s%s", SWIG_FILE_DELIMITER, SWIG_FILE_DELIMITER, LangSubDir);
+    Swig_add_directory(rl);
+    if (SwigLibWin) {
+      rl = NewString("");
+      Printf(rl, "%s%s%s", SwigLibWin, SWIG_FILE_DELIMITER, LangSubDir);
+      Swig_add_directory(rl);
+    }
+    rl = NewString("");
+    Printf(rl, "%s%s%s", SwigLib, SWIG_FILE_DELIMITER, LangSubDir);
+    Swig_add_directory(rl);
+  }
+
+  Swig_add_directory((String *) "." SWIG_FILE_DELIMITER "swig_lib");
+  if (SwigLibWin)
+    Swig_add_directory((String *) SwigLibWin);
+  Swig_add_directory((String *) SwigLib);
+
+  if (Verbose) {
+    printf("LangSubDir: %s\n", Char(LangSubDir));
+    printf("Search paths:\n");
+    List *sp = Swig_search_path();
+    Iterator s;
+    for (s = First(sp); s.item; s = Next(s)) {
+      Printf(stdout, "   %s\n", s.item);
+    }
+  }
+  // handle the -external-runtime argument
+  if (external_runtime)
+    SWIG_dump_runtime();
+
+  // If we made it this far, looks good. go for it....
+
+  input_file = argv[argc - 1];
+
+  // If the user has requested to check out a file, handle that
+  if (checkout) {
+    DOH *s;
+    char *outfile = input_file;
+    if (outfile_name)
+      outfile = outfile_name;
+
+    if (Verbose)
+      printf("Handling checkout...\n");
+
+    s = Swig_include(input_file);
+    if (!s) {
+      fprintf(stderr, "Unable to locate '%s' in the SWIG library.\n", input_file);
+    } else {
+      FILE *f = fopen(outfile, "r");
+      if (f) {
+	fclose(f);
+	fprintf(stderr, "File '%s' already exists. Checkout aborted.\n", outfile);
+      } else {
+	f = fopen(outfile, "w");
+	if (!f) {
+	  fprintf(stderr, "Unable to create file '%s'\n", outfile);
+	} else {
+	  if (Verbose)
+	    fprintf(stdout, "'%s' checked out from the SWIG library.\n", input_file);
+	  fputs(Char(s), f);
+	  fclose(f);
+	}
+      }
+    }
+  } else {
+    // Check the suffix for a .c file.  If so, we're going to
+    // declare everything we see as "extern"
+
+    ForceExtern = check_suffix(input_file);
+
+    // Run the preprocessor
+    if (Verbose)
+      printf("Preprocessing...\n");
+
+    {
+      int i;
+      String *fs = NewString("");
+      FILE *df = Swig_open(input_file);
+      if (!df) {
+	char *cfile = Char(input_file);
+	if (cfile && cfile[0] == '-') {
+	  Printf(stderr, "Unable to find option or file '%s', ", input_file);
+	  Printf(stderr, "use 'swig -help' for more information.\n");
+	} else {
+	  Printf(stderr, "Unable to find file '%s'.\n", input_file);
+	}
+	SWIG_exit(EXIT_FAILURE);
+      }
+      fclose(df);
+      if (!no_cpp) {
+	Printf(fs, "%%include <swig.swg>\n");
+	if (allkw) {
+	  Printf(fs, "%%include <allkw.swg>\n");
+	}
+	if (lang_config) {
+	  Printf(fs, "\n%%include <%s>\n", lang_config);
+	}
+	Printf(fs, "%%include \"%s\"\n", Swig_last_file());
+	for (i = 0; i < Len(libfiles); i++) {
+	  Printf(fs, "\n%%include \"%s\"\n", Getitem(libfiles, i));
+	}
+	Seek(fs, 0, SEEK_SET);
+	cpps = Preprocessor_parse(fs);
+	Delete(fs);
+      } else {
+	df = Swig_open(input_file);
+	cpps = NewFileFromFile(df);
+      }
+      if (Swig_error_count()) {
+	SWIG_exit(EXIT_FAILURE);
+      }
+      if (cpp_only) {
+	Printf(stdout, "%s", cpps);
+	SWIG_exit(EXIT_SUCCESS);
+      }
+      if (depend) {
+	String *outfile;
+	if (!outfile_name) {
+	  if (CPlusPlus || lang->cplus_runtime_mode()) {
+	    outfile = NewStringf("%s_wrap.%s", Swig_file_basename(input_file), cpp_extension);
+	  } else {
+	    outfile = NewStringf("%s_wrap.c", Swig_file_basename(input_file));
+	  }
+	} else {
+	  outfile = NewString(outfile_name);
+	}
+	if (dependencies_file && Len(dependencies_file) != 0) {
+	  f_dependencies_file = NewFile(dependencies_file, "w");
+	  if (!f_dependencies_file) {
+	    FileErrorDisplay(dependencies_file);
+	    SWIG_exit(EXIT_FAILURE);
+	  }
+	} else if (!depend_only) {
+	  String *filename = NewStringf("%s_wrap.%s", Swig_file_basename(input_file), depends_extension);
+	  f_dependencies_file = NewFile(filename, "w");
+	  if (!f_dependencies_file) {
+	    FileErrorDisplay(filename);
+	    SWIG_exit(EXIT_FAILURE);
+	  }
+	} else
+	  f_dependencies_file = stdout;
+	if (dependencies_target) {
+	  Printf(f_dependencies_file, "%s: ", dependencies_target);
+	} else {
+	  Printf(f_dependencies_file, "%s: ", outfile);
+	}
+	List *files = Preprocessor_depend();
+	for (int i = 0; i < Len(files); i++) {
+	  if ((depend != 2) || ((depend == 2) && (Strncmp(Getitem(files, i), SwigLib, Len(SwigLib)) != 0))) {
+	    Printf(f_dependencies_file, "\\\n %s ", Getitem(files, i));
+	  }
+	}
+	Printf(f_dependencies_file, "\n");
+	if (f_dependencies_file != stdout)
+	  Close(f_dependencies_file);
+	if (depend_only)
+	  SWIG_exit(EXIT_SUCCESS);
+      }
+      Seek(cpps, 0, SEEK_SET);
+    }
+
+    /* Register a null file with the file handler */
+    Swig_register_filebyname("null", NewString(""));
+
+    // Pass control over to the specific language interpreter
+    if (Verbose) {
+      fprintf(stdout, "Starting language-specific parse...\n");
+      fflush(stdout);
+    }
+
+    Node *top = Swig_cparse(cpps);
+
+    if (dump_top & STAGE1) {
+      Printf(stdout, "debug-top stage 1\n");
+      Swig_print_tree(top);
+    }
+    if (dump_module & STAGE1) {
+      Printf(stdout, "debug-module stage 1\n");
+      Swig_print_tree(Getattr(top, "module"));
+    }
+
+    if (Verbose) {
+      Printf(stdout, "Processing types...\n");
+    }
+    Swig_process_types(top);
+
+    if (dump_top & STAGE2) {
+      Printf(stdout, "debug-top stage 2\n");
+      Swig_print_tree(top);
+    }
+    if (dump_module & STAGE2) {
+      Printf(stdout, "debug-module stage 2\n");
+      Swig_print_tree(Getattr(top, "module"));
+    }
+
+    if (Verbose) {
+      Printf(stdout, "C++ analysis...\n");
+    }
+    Swig_default_allocators(top);
+
+    if (dump_top & STAGE3) {
+      Printf(stdout, "debug-top stage 3\n");
+      Swig_print_tree(top);
+    }
+    if (dump_module & STAGE3) {
+      Printf(stdout, "debug-module stage 3\n");
+      Swig_print_tree(Getattr(top, "module"));
+    }
+
+    if (Verbose) {
+      Printf(stdout, "Generating wrappers...\n");
+    }
+
+    if (dump_classes) {
+      Hash *classes = Getattr(top, "classes");
+      if (classes) {
+	Printf(stdout, "Classes\n");
+	Printf(stdout, "------------\n");
+	Iterator ki;
+	for (ki = First(classes); ki.key; ki = Next(ki)) {
+	  Printf(stdout, "%s\n", ki.key);
+	}
+      }
+    }
+
+    if (dump_typedef) {
+      SwigType_print_scope(0);
+    }
+
+    if (dump_tags) {
+      Swig_print_tags(top, 0);
+    }
+    if (top) {
+      if (!Getattr(top, "name")) {
+	Printf(stderr, "*** No module name specified using %%module or -module.\n");
+	SWIG_exit(EXIT_FAILURE);
+      } else {
+	/* Set some filename information on the object */
+	Setattr(top, "infile", input_file);
+	if (!outfile_name) {
+	  if (CPlusPlus || lang->cplus_runtime_mode()) {
+	    Setattr(top, "outfile", NewStringf("%s_wrap.%s", Swig_file_basename(input_file), cpp_extension));
+	  } else {
+	    Setattr(top, "outfile", NewStringf("%s_wrap.c", Swig_file_basename(input_file)));
+	  }
+	} else {
+	  Setattr(top, "outfile", outfile_name);
+	}
+	if (!outfile_name_h) {
+	  Setattr(top, "outfile_h", NewStringf("%s_wrap.%s", Swig_file_basename(input_file), hpp_extension));
+	} else {
+	  Setattr(top, "outfile_h", outfile_name_h);
+	}
+	set_outdir(Swig_file_dirname(Getattr(top, "outfile")));
+	if (Swig_contract_mode_get()) {
+	  Swig_contracts(top);
+	}
+	lang->top(top);
+	if (browse) {
+	  Swig_browser(top, 0);
+	}
+      }
+    }
+    if (dump_top & STAGE4) {
+      Printf(stdout, "debug-top stage 4\n");
+      Swig_print_tree(top);
+    }
+    if (dump_module & STAGE4) {
+      Printf(stdout, "debug-module stage 4\n");
+      Swig_print_tree(Getattr(top, "module"));
+    }
+    if (dump_xml && top) {
+      Swig_print_xml(top, xmlout);
+    }
+    Delete(top);
+  }
+  if (tm_debug)
+    Swig_typemap_debug();
+  if (memory_debug)
+    DohMemoryDebug();
+
+  // Deletes
+  Delete(libfiles);
+  Preprocessor_delete();
+
+  while (freeze) {
+  }
+
+  if ((werror) && (Swig_warn_count())) {
+    return Swig_warn_count();
+  }
+  return Swig_error_count();
+}
+
+// --------------------------------------------------------------------------
+// SWIG_exit(int exit_code)
+//
+// Cleanup and either freeze or exit
+// --------------------------------------------------------------------------
+
+void SWIG_exit(int exit_code) {
+  while (freeze) {
+  }
+  exit(exit_code);
+}
diff --git a/trunk/Source/Modules/modula3.cxx b/trunk/Source/Modules/modula3.cxx
new file mode 100644
index 0000000..6cb24d3
--- /dev/null
+++ b/trunk/Source/Modules/modula3.cxx
@@ -0,0 +1,3964 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * modula3.cxx
+ *
+ * Modula3 language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_modula3_cxx[] = "$Id$";
+
+/*
+  Text formatted with
+    indent -sob -br -ce -nut -npsl
+*/
+
+/*
+  Report:
+   - It's not a good concept to use member variables or global variables
+     for passing parameters to functions.
+     It's not a good concept to use functions of superclasses for specific services.
+     E.g. For SWIG this means: Generating accessor functions for member variables
+     is the most common but no general task to be processed in membervariableHandler.
+     Better provide a service function which generates accessor function code
+     and equip this service function with all parameters needed for input (parse node)
+     and output (generated code).
+   - How can I make globalvariableHandler not to generate
+     interface functions to two accessor functions
+     (that don't exist) ?
+   - How can I generate a typemap that turns every C reference argument into
+     its Modula 3 counterpart, that is
+       void test(Complex &z);
+       PROCEDURE test(VAR z:Complex);
+   - neither $*n_mangle nor $*n_type nor $*n_ltype return the type without
+     pointer converted to Modula3 equivalent,
+     $*n_mangle is the variant closest to what I expect
+   - using a typemap like
+         typemap(m3wrapintype) int * %{VAR $1_name: INTEGER%}
+     has the advantages:
+       - one C parameter can be turned into multiple M3 parameters
+       - the argument can be renamed
+   - using typemaps like
+         typemap(m3wrapinmode) int * "VAR"
+         typemap(m3wrapintype) int * "INTEGER"
+     has the advantages:
+       - multiple parameters with same type and default value can be bundled
+       - more conform to the other language modules
+   - Where takes the reduction of multi-typemaps place?
+     How can I preserve all parameters for functions of the intermediary class?
+     The answer is Getattrs(n,"tmap:m3rawintype:next")
+   - Char() can be used to transform a String to (char *)
+     which can be used for output with printf
+   - What is the while (checkAttribute()) loop in functionWrapper good for?
+     Appearently for skipping (numinputs=0) typemaps.
+   - SWIGTYPE const * - typemap is ignored, whereas
+     SWIGTYPE *       - typemap is invoked, why?
+     Had it been (const SWIGTYPE *) instead?
+   - enumeration items should definitely be equipped
+     with its plain numerical value
+     One could add tag 'numvalue' in CParse/parser.y,
+     but it is still possible that someone declares an
+     enumeration using a symbolic constant.
+     I have quickly hacked
+     that the successive number is assigned
+     if "enumvalue" has suffix "+1".
+     The ultimate solution would be to generate a C program
+     which includes the header and outputs all constants.
+     This program might be compiled and run
+     by 'make' or by SWIG and the resulting output is fed back to SWIG.
+   - It's a bad idea to interpret feature value ""
+     'disable feature' because the value ""
+     might be sensible in case of feature:modula3:oldprefix.
+   - What's the difference between "sym:name" and "name" ?
+     "name" is the original name and
+     "sym:name" is probably modified by the user using %rename
+   - Is it possible for 'configure' to find out if m3pp is installed
+     and to invoke it for generated Modula3 files?
+   - It would be better to separate an arguments purpose and its name,
+     because an output variable with name "OUTPUT" is not very descriptive.
+     In case of PLPlot this could be solved by typedefs
+     that assign special purposes to the array types.
+   - Can one interpret $n_basetype as the identifier matched with SWIGTYPE ?
+
+  Swig's odds:
+   - arguments of type (Node *) for SWIG functions
+     should be most often better (const Node *):
+     Swig_symbol_qualified, Getattr, nodeType, parentNode
+   - unique identifier style instead of
+     NewString, Getattr, firstChild
+   - 'class'.name is qualified,
+     'enum'.name and 'enumitem'.name is not
+   - Swig_symbol_qualified() returns NIL for enumeration nodes
+
+   - Is there a function that creates a C representation of a SWIG type string?
+
+  ToDo:
+   - create WeakRefs only for resources returned by function marked with %newobject
+      -> part of output conversion
+   - clean typemap conception
+      - should a multi-typemap for m3wrapouttype skip the corresponding input parameters?
+        when yes - How to handle inout-arguments? In this case like in-argument.
+   - C++ classes
+   - C++ exceptions
+   - allow for moving RECORD and OBJECT definitions
+     to separate files, with the main type called T
+   - call-back functions
+   - special option: fast access to class members by pointer arithmetic,
+       member offsets can be determined by a C++ program that print them.
+   - emit enumeration definitions when its first item is declared,
+       currently enumerations are emitted at the beginning of the file
+
+  Done:
+   - addThrow should convert the typemap by itself
+      - not possible because routine for attaching mapped types to parameter nodes
+        won't work for the function node
+   - turning error codes into exceptions
+      -> part of output value checking
+   - create WeakRefs for resources allocated by the library
+      -> part of output conversion
+   - TRY..FINALLY..END; can be omitted
+      - if there is no m3wrapfreearg
+      - no exception can be raised in the body (empty RAISES) list
+*/
+
+#include "swigmod.h"
+
+#include <limits.h>		// for INT_MAX
+#include <ctype.h>
+
+const char usageArgDir[] = "m3wrapargdir typemap expect values: in, out, inout\n";
+
+class MODULA3:public Language {
+public:
+  enum block_type { no_block, constant, variable, blocktype, revelation };
+
+private:
+  struct M3File {
+    String *f;
+    Hash *import;
+    block_type bt;
+    /* VC++ 6 doesn't allow the access to 'no_block'
+       if it is a private member of MODULA3 class */
+    M3File():f(NewString("")), import(NewHash()), bt(no_block) {
+    }
+    ~M3File() {
+      Delete(f);
+      Delete(import);
+    }
+
+    /* -----------------------------------------------------------------------------
+     * enterBlock()
+     *
+     * Make sure that a given declaration is written to the right declaration block,
+     * that is constants are written after "CONST" and so on ...
+     * ----------------------------------------------------------------------------- */
+    void enterBlock(block_type newbt) {
+      static const char *ident[] = { "", "\nCONST\n", "\nVAR\n", "\nTYPE\n", "\nREVEAL\n" };
+#ifdef DEBUG
+      if ((bt < 0) || (4 < bt)) {
+	printf("bt %d out of range\n", bt);
+      }
+#endif
+      if (newbt != bt) {
+	Append(f, ident[newbt]);
+	bt = newbt;
+      }
+    }
+
+  };
+
+  static const char *usage;
+  const String *empty_string;
+
+  Hash *swig_types_hash;
+  File *f_runtime;
+  File *f_header;
+  File *f_wrappers;
+  File *f_init;
+
+  bool proxy_flag;		// Flag for generating proxy classes
+  bool have_default_constructor_flag;
+  bool native_function_flag;	// Flag for when wrapping a native function
+  bool enum_constant_flag;	// Flag for when wrapping an enum or constant
+  bool static_flag;		// Flag for when wrapping a static functions or member variables
+  bool variable_wrapper_flag;	// Flag for when wrapping a nonstatic member variable
+  bool wrapping_member_flag;	// Flag for when wrapping a member variable/enum/const
+  bool global_variable_flag;	// Flag for when wrapping a global variable
+  bool old_variable_names;	// Flag for old style variable names in the intermediary class
+  bool unsafe_module;
+
+  String *m3raw_name;		// raw interface name
+  M3File m3raw_intf;		// raw interface
+  M3File m3raw_impl;		// raw implementation (usually empty)
+  String *m3wrap_name;		// wrapper module
+  M3File m3wrap_intf;
+  M3File m3wrap_impl;
+  String *m3makefile;
+  String *targetlibrary;
+  String *proxy_class_def;
+  String *proxy_class_code;
+  String *proxy_class_name;
+  String *variable_name;	//Name of a variable being wrapped
+  String *variable_type;	//Type of this variable
+  String *enumeration_name;	//Name of the current enumeration type
+  Hash *enumeration_items;	//and its members
+  int enumeration_max;
+  Hash *enumeration_coll;	//Collection of all enumerations.
+  /* The items are nodes with members:
+     "items"  - hash of with key 'itemname' and content 'itemvalue'
+     "max"    - maximum value in item list
+   */
+  String *constant_values;
+  String *constantfilename;
+  String *renamefilename;
+  String *typemapfilename;
+  String *m3raw_imports;	//intermediary class imports from %pragma
+  String *module_imports;	//module imports from %pragma
+  String *m3raw_baseclass;	//inheritance for intermediary class class from %pragma
+  String *module_baseclass;	//inheritance for module class from %pragma
+  String *m3raw_interfaces;	//interfaces for intermediary class class from %pragma
+  String *module_interfaces;	//interfaces for module class from %pragma
+  String *m3raw_class_modifiers;	//class modifiers for intermediary class overriden by %pragma
+  String *m3wrap_modifiers;	//class modifiers for module class overriden by %pragma
+  String *upcasts_code;		//C++ casts for inheritance hierarchies C++ code
+  String *m3raw_cppcasts_code;	//C++ casts up inheritance hierarchies intermediary class code
+  String *destructor_call;	//C++ destructor call if any
+  String *outfile;
+
+  enum type_additions { none, pointer, reference };
+
+public:
+
+  /* -----------------------------------------------------------------------------
+   * MODULA3()
+   * ----------------------------------------------------------------------------- */
+
+MODULA3():
+  empty_string(NewString("")),
+      swig_types_hash(NULL),
+      f_runtime(NULL),
+      f_header(NULL),
+      f_wrappers(NULL),
+      f_init(NULL),
+      proxy_flag(true),
+      have_default_constructor_flag(false),
+      native_function_flag(false),
+      enum_constant_flag(false),
+      static_flag(false),
+      variable_wrapper_flag(false),
+      wrapping_member_flag(false),
+      global_variable_flag(false),
+      old_variable_names(false),
+      unsafe_module(false),
+      m3raw_name(NULL),
+      m3raw_intf(),
+      m3raw_impl(),
+      m3wrap_name(NULL),
+      m3wrap_intf(),
+      m3wrap_impl(),
+      m3makefile(NULL),
+      targetlibrary(NULL),
+      proxy_class_def(NULL),
+      proxy_class_code(NULL),
+      proxy_class_name(NULL),
+      variable_name(NULL),
+      variable_type(NULL),
+      enumeration_name(NULL),
+      enumeration_items(NULL),
+      enumeration_max(0),
+      enumeration_coll(NULL),
+      constant_values(NULL),
+      constantfilename(NULL),
+      renamefilename(NULL),
+      typemapfilename(NULL),
+      m3raw_imports(NULL),
+      module_imports(NULL),
+      m3raw_baseclass(NULL),
+      module_baseclass(NULL),
+      m3raw_interfaces(NULL),
+      module_interfaces(NULL),
+      m3raw_class_modifiers(NULL),
+      m3wrap_modifiers(NULL),
+      upcasts_code(NULL),
+      m3raw_cppcasts_code(NULL),
+      destructor_call(NULL),
+      outfile(NULL) {
+  }
+
+  /************** some utility functions ***************/
+
+  /* -----------------------------------------------------------------------------
+   * getMappedType()
+   *
+   * Return the type of 'p' mapped by 'map'.
+   * Print a standard warning if 'p' can't be mapped.
+   * ----------------------------------------------------------------------------- */
+
+  String *getMappedType(Node *p, const char *map) {
+    String *mapattr = NewString("tmap:");
+    Append(mapattr, map);
+
+    String *tm = Getattr(p, mapattr);
+    if (tm == NIL) {
+      Swig_warning(WARN_MODULA3_TYPEMAP_TYPE_UNDEF, input_file, line_number,
+		   "No '%s' typemap defined for type '%s'\n", map, SwigType_str(Getattr(p, "type"), 0));
+    }
+    Delete(mapattr);
+    return tm;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getMappedTypeNew()
+   *
+   * Similar to getMappedType but uses Swig_type_lookup_new.
+   * ----------------------------------------------------------------------------- */
+
+  String *getMappedTypeNew(Node *n, const char *map, const char *lname = "", bool warn = true) {
+    String *tm = Swig_typemap_lookup(map, n, lname, 0);
+    if ((tm == NIL) && warn) {
+      Swig_warning(WARN_MODULA3_TYPEMAP_TYPE_UNDEF, input_file, line_number,
+		   "No '%s' typemap defined for type '%s'\n", map, SwigType_str(Getattr(n, "type"), 0));
+    }
+    return tm;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * attachMappedType()
+   *
+   * Obtain the type mapped by 'map' and attach it to the node
+   * ----------------------------------------------------------------------------- */
+
+  void attachMappedType(Node *n, const char *map, const char *lname = "") {
+    String *tm = Swig_typemap_lookup(map, n, lname, 0);
+    if (tm != NIL) {
+      String *attr = NewStringf("tmap:%s", map);
+      Setattr(n, attr, tm);
+      Delete(attr);
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * skipIgnored()
+   *
+   * Skip all parameters that have 'numinputs=0'
+   * with respect to a given typemap.
+   * ----------------------------------------------------------------------------- */
+
+  Node *skipIgnored(Node *p, const char *map) {
+    String *niattr = NewStringf("tmap:%s:numinputs", map);
+    String *nextattr = NewStringf("tmap:%s:next", map);
+
+    while ((p != NIL) && checkAttribute(p, niattr, "0")) {
+      p = Getattr(p, nextattr);
+    }
+
+    Delete(nextattr);
+    Delete(niattr);
+    return p;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * isInParam()
+   * isOutParam()
+   *
+   * Check if the parameter is intended for input or for output.
+   * ----------------------------------------------------------------------------- */
+
+  bool isInParam(Node *p) {
+    String *dir = Getattr(p, "tmap:m3wrapargdir");
+//printf("dir for %s: %s\n", Char(Getattr(p,"name")), Char(dir));
+    if ((dir == NIL) || (Strcmp(dir, "in") == 0)
+	|| (Strcmp(dir, "inout") == 0)) {
+      return true;
+    } else if (Strcmp(dir, "out") == 0) {
+      return false;
+    } else {
+      printf(usageArgDir);
+      return false;
+    }
+  }
+
+  bool isOutParam(Node *p) {
+    String *dir = Getattr(p, "tmap:m3wrapargdir");
+    if ((dir == NIL) || (Strcmp(dir, "in") == 0)) {
+      return false;
+    } else if ((Strcmp(dir, "out") == 0) || (Strcmp(dir, "inout") == 0)) {
+      return true;
+    } else {
+      printf(usageArgDir);
+      return false;
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * printAttrs()
+   *
+   * For debugging: Show all attributes of a node and their values.
+   * ----------------------------------------------------------------------------- */
+  void printAttrs(Node *n) {
+    Iterator it;
+    for (it = First(n); it.key != NIL; it = Next(it)) {
+      printf("%s = %s\n", Char(it.key), Char(Getattr(n, it.key)));
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * hasPrefix()
+   *
+   * Check if a string have a given prefix.
+   * ----------------------------------------------------------------------------- */
+  bool hasPrefix(const String *str, const String *prefix) {
+    int len_prefix = Len(prefix);
+    return (Len(str) > len_prefix)
+	&& (Strncmp(str, prefix, len_prefix) == 0);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getQualifiedName()
+   *
+   * Return fully qualified identifier of n.
+   * ----------------------------------------------------------------------------- */
+#if 0
+  // Swig_symbol_qualified returns NIL for enumeration nodes
+  String *getQualifiedName(Node *n) {
+    String *qual = Swig_symbol_qualified(n);
+    String *name = Getattr(n, "name");
+    if (hasContent(qual)) {
+      return NewStringf("%s::%s", qual, name);
+    } else {
+      return name;
+    }
+  }
+#else
+  String *getQualifiedName(Node *n) {
+    String *name = Copy(Getattr(n, "name"));
+    n = parentNode(n);
+    while (n != NIL) {
+      const String *type = nodeType(n);
+      if ((Strcmp(type, "class") == 0) || (Strcmp(type, "struct") == 0) || (Strcmp(type, "namespace") == 0)) {
+	String *newname = NewStringf("%s::%s", Getattr(n, "name"), name);
+	Delete(name);
+	//name = newname;
+	// Hmpf, the class name is already qualified.
+	return newname;
+      }
+      n = parentNode(n);
+    }
+    //printf("qualified name: %s\n", Char(name));
+    return name;
+  }
+#endif
+
+  /* -----------------------------------------------------------------------------
+   * nameToModula3()
+   *
+   * Turn usual C identifiers like "this_is_an_identifier"
+   * into usual Modula 3 identifier like "thisIsAnIdentifier"
+   * ----------------------------------------------------------------------------- */
+  String *nameToModula3(const String *sym, bool leadingCap) {
+    int len_sym = Len(sym);
+    char *csym = Char(sym);
+    char *m3sym = new char[len_sym + 1];
+    int i, j;
+    bool cap = leadingCap;
+    for (i = 0, j = 0; j < len_sym; j++) {
+      char c = csym[j];
+      if ((c == '_') || (c == ':')) {
+	cap = true;
+      } else {
+	if (isdigit(c)) {
+	  m3sym[i] = c;
+	  cap = true;
+	} else {
+	  if (cap) {
+	    m3sym[i] = (char)toupper(c);
+	  } else {
+	    m3sym[i] = (char)tolower(c);
+	  }
+	  cap = false;
+	}
+	i++;
+      }
+    }
+    m3sym[i] = 0;
+    String *result = NewString(m3sym);
+    delete[]m3sym;
+    return result;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * capitalizeFirst()
+   *
+   * Make the first character upper case.
+   * ----------------------------------------------------------------------------- */
+  String *capitalizeFirst(const String *str) {
+    return NewStringf("%c%s", toupper(*Char(str)), Char(str) + 1);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * prefixedNameToModula3()
+   *
+   * If feature modula3:oldprefix and modula3:newprefix is present
+   * and the C identifier has leading 'oldprefix'
+   * then it is replaced by the 'newprefix'.
+   * The rest is converted to Modula style.
+   * ----------------------------------------------------------------------------- */
+  String *prefixedNameToModula3(Node *n, const String *sym, bool leadingCap) {
+    String *oldPrefix = Getattr(n, "feature:modula3:oldprefix");
+    String *newPrefix = Getattr(n, "feature:modula3:newprefix");
+    String *result = NewString("");
+    char *short_sym = Char(sym);
+    // if at least one prefix feature is present
+    // the replacement takes place
+    if ((oldPrefix != NIL) || (newPrefix != NIL)) {
+      if ((oldPrefix == NIL) || hasPrefix(sym, oldPrefix)) {
+	short_sym += Len(oldPrefix);
+	if (newPrefix != NIL) {
+	  Append(result, newPrefix);
+	}
+      }
+    }
+    String *suffix = nameToModula3(short_sym, leadingCap || hasContent(newPrefix));
+    Append(result, suffix);
+    Delete(suffix);
+    return result;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * hasContent()
+   *
+   * Check if the string exists and contains something.
+   * ----------------------------------------------------------------------------- */
+  bool hasContent(const String *str) {
+    return (str != NIL) && (Strcmp(str, "") != 0);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * openWriteFile()
+   *
+   * Caution: The file must be freshly allocated and will be destroyed
+   *          by this routine.
+   * ----------------------------------------------------------------------------- */
+
+  File *openWriteFile(String *name) {
+    File *file = NewFile(name, "w");
+    if (!file) {
+      FileErrorDisplay(name);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Delete(name);
+    return file;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * aToL()
+   *
+   * like atol but with additional user warning
+   * ----------------------------------------------------------------------------- */
+
+  long aToL(const String *value) {
+    char *endptr;
+    long numvalue = strtol(Char(value), &endptr, 0);
+    if (*endptr != 0) {
+      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "The string <%s> does not denote a numeric value.\n", value);
+    }
+    return numvalue;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * strToL()
+   *
+   * like strtol but returns if the conversion was successful
+   * ----------------------------------------------------------------------------- */
+
+  bool strToL(const String *value, long &numvalue) {
+    char *endptr;
+    numvalue = strtol(Char(value), &endptr, 0);
+    return (*endptr == 0);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * evalExpr()
+   *
+   * Evaluate simple expression as they may occur in "enumvalue" attributes.
+   * ----------------------------------------------------------------------------- */
+
+  bool evalExpr(String *value, long &numvalue) {
+    // Split changes file status of String and thus cannot receive 'const' strings
+//printf("evaluate <%s>\n", Char(value));
+    List *summands = Split(value, '+', INT_MAX);
+    Iterator sm = First(summands);
+    numvalue = 0;
+    for (; sm.item != NIL; sm = Next(sm)) {
+      String *smvalue = Getattr(constant_values, sm.item);
+      long smnumvalue;
+      if (smvalue != NIL) {
+	if (!strToL(smvalue, smnumvalue)) {
+//printf("evaluation: abort 0 <%s>\n", Char(smvalue));
+	  return false;
+	}
+      } else {
+	if (!strToL(sm.item, smnumvalue)) {
+//printf("evaluation: abort 1 <%s>\n", Char(sm));
+	  return false;
+	}
+      }
+      numvalue += smnumvalue;
+    }
+//printf("evaluation: return %ld\n", numvalue);
+    return true;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * log2()
+   *
+   * Determine the position of the single bit of a power of two.
+   * Returns true if the given number is a power of two.
+   * ----------------------------------------------------------------------------- */
+
+  bool log2(long n, long &exp) {
+    exp = 0;
+    while (n > 0) {
+      if ((n & 1) != 0) {
+	return n == 1;
+      }
+      exp++;
+      n >>= 1;
+    }
+    return false;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * writeArg
+   *
+   * Write a function argument or RECORD entry definition.
+   * Bundles arguments of same type and default value.
+   * 'name.next==NIL' denotes the end of the entry or argument list.
+   * ----------------------------------------------------------------------------- */
+
+  bool equalNilStr(const String *str0, const String *str1) {
+    if (str0 == NIL) {
+      return (str1 == NIL);
+      //return (str0==NIL) == (str1==NIL);
+    } else {
+      return (str1 != NIL) && (Cmp(str0, str1) == 0);
+      //return Cmp(str0,str1)==0;
+    }
+  }
+
+  struct writeArgState {
+    String *mode, *name, *type, *value;
+    bool hold;
+     writeArgState():mode(NIL), name(NIL), type(NIL), value(NIL), hold(false) {
+    }
+  };
+
+  void writeArg(File *f, writeArgState & state, String *mode, String *name, String *type, String *value) {
+    /* skip the first argument,
+       only store the information for the next call in this case */
+    if (state.name != NIL) {
+      if ((!state.hold) && (state.mode != NIL)) {
+	Printf(f, "%s ", state.mode);
+      }
+      if ((name != NIL) && equalNilStr(state.mode, mode) && equalNilStr(state.type, type) && (state.value == NIL) && (value == NIL)
+	  /* the same expression may have different values
+	     due to side effects of the called function */
+	  /*equalNilStr(state.value,value) */
+	  ) {
+	Printf(f, "%s, ", state.name);
+	state.hold = true;
+      } else {
+	Append(f, state.name);
+	if (state.type != NIL) {
+	  Printf(f, ": %s", state.type);
+	}
+	if (state.value != NIL) {
+	  Printf(f, ":= %s", state.value);
+	}
+	Append(f, ";\n");
+	state.hold = false;
+      }
+    }
+    /* at the next call the current argument will be the previous one */
+    state.mode = mode;
+    state.name = name;
+    state.type = type;
+    state.value = value;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getProxyName()
+   *
+   * Test to see if a type corresponds to something wrapped with a proxy class
+   * Return NULL if not otherwise the proxy class name
+   * ----------------------------------------------------------------------------- */
+
+  String *getProxyName(SwigType *t) {
+    if (proxy_flag) {
+      Node *n = classLookup(t);
+      if (n) {
+	return Getattr(n, "sym:name");
+      }
+    }
+    return NULL;
+  }
+
+  /*************** language processing ********************/
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+
+    SWIG_library_directory("modula3");
+
+    // Look for certain command line options
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-generateconst") == 0) {
+	  if (argv[i + 1]) {
+	    constantfilename = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-generaterename") == 0) {
+	  if (argv[i + 1]) {
+	    renamefilename = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-generatetypemap") == 0) {
+	  if (argv[i + 1]) {
+	    typemapfilename = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-noproxy") == 0) {
+	  Swig_mark_arg(i);
+	  proxy_flag = false;
+	} else if (strcmp(argv[i], "-oldvarnames") == 0) {
+	  Swig_mark_arg(i);
+	  old_variable_names = true;
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  Printf(stdout, "%s\n", usage);
+	}
+      }
+    }
+
+    // Add a symbol to the parser for conditional compilation
+    Preprocessor_define("SWIGMODULA3 1", 0);
+
+    // Add typemap definitions
+    SWIG_typemap_lang("modula3");
+    SWIG_config_file("modula3.swg");
+
+    allow_overloading();
+  }
+
+  /* ---------------------------------------------------------------------
+   * top()
+   * --------------------------------------------------------------------- */
+
+  virtual int top(Node *n) {
+    if (hasContent(constantfilename) || hasContent(renamefilename) || hasContent(typemapfilename)) {
+      int result = SWIG_OK;
+      if (hasContent(constantfilename)) {
+	result = generateConstantTop(n) && result;
+      }
+      if (hasContent(renamefilename)) {
+	result = generateRenameTop(n) && result;
+      }
+      if (hasContent(typemapfilename)) {
+	result = generateTypemapTop(n) && result;
+      }
+      return result;
+    } else {
+      return generateM3Top(n);
+    }
+  }
+
+  void scanConstant(File *file, Node *n) {
+    Node *child = firstChild(n);
+    while (child != NIL) {
+      String *constname = NIL;
+      String *type = nodeType(child);
+      if ((Strcmp(type, "enumitem") == 0)
+	  || (Strcmp(type, "constant") == 0)) {
+#if 1
+	constname = getQualifiedName(child);
+#else
+	constname = Getattr(child, "value");
+	if ((!hasContent(constname))
+	    || (('0' <= *Char(constname)) && (*Char(constname) <= '9'))) {
+	  constname = Getattr(child, "name");
+	}
+#endif
+      }
+      if (constname != NIL) {
+	Printf(file, "  printf(\"%%%%constnumeric(%%Lg) %s;\\n\", (long double)%s);\n", constname, constname);
+      }
+      scanConstant(file, child);
+      child = nextSibling(child);
+    }
+  }
+
+  int generateConstantTop(Node *n) {
+    File *file = openWriteFile(NewStringf("%s.c", constantfilename));
+    if (CPlusPlus) {
+      Printf(file, "#include <cstdio>\n");
+    } else {
+      Printf(file, "#include <stdio.h>\n");
+    }
+    Printf(file, "#include \"%s\"\n", input_file);
+    Printf(file, "\n");
+    Printf(file, "int main (int argc, char *argv[]) {\n");
+    Printf(file, "\
+/*This progam must work for floating point numbers and integers.\n\
+  Thus all numbers are converted to double precision floating point format.*/\n");
+    scanConstant(file, n);
+    Printf(file, "  return 0;\n");
+    Printf(file, "}\n");
+    Close(file);
+    return SWIG_OK;
+  }
+
+  void scanRename(File *file, Node *n) {
+    Node *child = firstChild(n);
+    while (child != NIL) {
+      String *type = nodeType(child);
+      if (Strcmp(type, "cdecl") == 0) {
+	ParmList *p = Getattr(child, "parms");
+	if (p != NIL) {
+	  String *name = getQualifiedName(child);
+	  String *m3name = nameToModula3(name, true);
+	  /*don't know how to get the original C type identifiers */
+	  //String *arguments = createCSignature (child);
+	  Printf(file, "%%rename(\"%s\") %s;\n", m3name, name);
+	  /*Printf(file, "%%rename(\"%s\") %s %s(%s);\n",
+	     m3name, Getattr(n,"type"), name, arguments); */
+	  Delete(name);
+	  Delete(m3name);
+	  //Delete (arguments);
+	}
+      }
+      scanRename(file, child);
+      child = nextSibling(child);
+    }
+  }
+
+  int generateRenameTop(Node *n) {
+    File *file = openWriteFile(NewStringf("%s.i", renamefilename));
+    Printf(file, "\
+/* This file was generated from %s\n\
+   by SWIG with option -generaterename. */\n\
+\n", input_file);
+    scanRename(file, n);
+    Close(file);
+    return SWIG_OK;
+  }
+
+  void scanTypemap(File *file, Node *n) {
+    Node *child = firstChild(n);
+    while (child != NIL) {
+      String *type = nodeType(child);
+      //printf("nodetype %s\n", Char(type));
+      String *storage = Getattr(child, "storage");
+      if ((Strcmp(type, "class") == 0) || ((Strcmp(type, "cdecl") == 0) && (storage != NIL)
+					   && (Strcmp(storage, "typedef") == 0))) {
+	String *name = getQualifiedName(child);
+	String *m3name = nameToModula3(name, true);
+	Printf(file, "%%typemap(\"m3wrapintype\") %s %%{%s%%}\n", name, m3name);
+	Printf(file, "%%typemap(\"m3rawintype\") %s %%{%s%%}\n", name, m3name);
+	Printf(file, "\n");
+      }
+      scanTypemap(file, child);
+      child = nextSibling(child);
+    }
+  }
+
+  int generateTypemapTop(Node *n) {
+    File *file = openWriteFile(NewStringf("%s.i", typemapfilename));
+    Printf(file, "\
+/* This file was generated from %s\n\
+   by SWIG with option -generatetypemap. */\n\
+\n", input_file);
+    scanTypemap(file, n);
+    Close(file);
+    return SWIG_OK;
+  }
+
+  int generateM3Top(Node *n) {
+    /* Initialize all of the output files */
+    outfile = Getattr(n, "outfile");
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+
+    m3makefile = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+
+    Swig_register_filebyname("m3rawintf", m3raw_intf.f);
+    Swig_register_filebyname("m3rawimpl", m3raw_impl.f);
+    Swig_register_filebyname("m3wrapintf", m3wrap_intf.f);
+    Swig_register_filebyname("m3wrapimpl", m3wrap_impl.f);
+    Swig_register_filebyname("m3makefile", m3makefile);
+
+    swig_types_hash = NewHash();
+
+    String *name = Getattr(n, "name");
+    // Make the intermediary class and module class names. The intermediary class name can be set in the module directive.
+    Node *optionsnode = Getattr(Getattr(n, "module"), "options");
+    if (optionsnode != NIL) {
+      String *m3raw_name_tmp = Getattr(optionsnode, "m3rawname");
+      if (m3raw_name_tmp != NIL) {
+	m3raw_name = Copy(m3raw_name_tmp);
+      }
+    }
+    if (m3raw_name == NIL) {
+      m3raw_name = NewStringf("%sRaw", name);
+    }
+    Setattr(m3wrap_impl.import, m3raw_name, "");
+
+    m3wrap_name = Copy(name);
+
+    proxy_class_def = NewString("");
+    proxy_class_code = NewString("");
+    m3raw_baseclass = NewString("");
+    m3raw_interfaces = NewString("");
+    m3raw_class_modifiers = NewString("");	// package access only to the intermediary class by default
+    m3raw_imports = NewString("");
+    m3raw_cppcasts_code = NewString("");
+    m3wrap_modifiers = NewString("public");
+    module_baseclass = NewString("");
+    module_interfaces = NewString("");
+    module_imports = NewString("");
+    upcasts_code = NewString("");
+
+    Swig_banner(f_runtime);	// Print the SWIG banner message
+
+    Swig_name_register((char *) "wrapper", (char *) "Modula3_%f");
+    if (old_variable_names) {
+      Swig_name_register((char *) "set", (char *) "set_%v");
+      Swig_name_register((char *) "get", (char *) "get_%v");
+    }
+
+    Printf(f_wrappers, "\n#ifdef __cplusplus\n");
+    Printf(f_wrappers, "extern \"C\" {\n");
+    Printf(f_wrappers, "#endif\n\n");
+
+    constant_values = NewHash();
+    scanForConstPragmas(n);
+    enumeration_coll = NewHash();
+    collectEnumerations(enumeration_coll, n);
+
+    /* Emit code */
+    Language::top(n);
+
+    // Generate m3makefile
+    // This will be unnecessary if SWIG is invoked from Quake.
+    {
+      File *file = openWriteFile(NewStringf("%sm3makefile", Swig_file_dirname(outfile)));
+
+      Printf(file, "%% automatically generated quake file for %s\n\n", name);
+
+      /* Write the fragments written by '%insert'
+         collected while 'top' processed the parse tree */
+      Printv(file, m3makefile, NIL);
+
+      Printf(file, "import(\"libm3\")\n");
+      //Printf(file, "import_lib(\"%s\",\"/usr/lib\")\n", name);
+      Printf(file, "module(\"%s\")\n", m3raw_name);
+      Printf(file, "module(\"%s\")\n\n", m3wrap_name);
+
+      if (targetlibrary != NIL) {
+	Printf(file, "library(\"%s\")\n", targetlibrary);
+      } else {
+	Printf(file, "library(\"m3%s\")\n", name);
+      }
+      Close(file);
+    }
+
+    // Generate the raw interface
+    {
+      File *file = openWriteFile(NewStringf("%s%s.i3", Swig_file_dirname(outfile), m3raw_name));
+
+      emitBanner(file);
+
+      Printf(file, "INTERFACE %s;\n\n", m3raw_name);
+
+      emitImportStatements(m3raw_intf.import, file);
+      Printf(file, "\n");
+
+      // Write the interface generated within 'top'
+      Printv(file, m3raw_intf.f, NIL);
+
+      Printf(file, "\nEND %s.\n", m3raw_name);
+      Close(file);
+    }
+
+    // Generate the raw module
+    {
+      File *file = openWriteFile(NewStringf("%s%s.m3", Swig_file_dirname(outfile), m3raw_name));
+
+      emitBanner(file);
+
+      Printf(file, "MODULE %s;\n\n", m3raw_name);
+
+      emitImportStatements(m3raw_impl.import, file);
+      Printf(file, "\n");
+
+      // will be empty usually
+      Printv(file, m3raw_impl.f, NIL);
+
+      Printf(file, "BEGIN\nEND %s.\n", m3raw_name);
+      Close(file);
+    }
+
+    // Generate the interface for the comfort wrappers
+    {
+      File *file = openWriteFile(NewStringf("%s%s.i3", Swig_file_dirname(outfile), m3wrap_name));
+
+      emitBanner(file);
+
+      Printf(file, "INTERFACE %s;\n", m3wrap_name);
+
+      emitImportStatements(m3wrap_intf.import, file);
+      Printf(file, "\n");
+
+      {
+	Iterator it = First(enumeration_coll);
+	if (it.key != NIL) {
+	  Printf(file, "TYPE\n");
+	}
+	for (; it.key != NIL; it = Next(it)) {
+	  Printf(file, "\n");
+	  emitEnumeration(file, it.key, it.item);
+	}
+      }
+
+      // Add the wrapper methods
+      Printv(file, m3wrap_intf.f, NIL);
+
+      // Finish off the class
+      Printf(file, "\nEND %s.\n", m3wrap_name);
+      Close(file);
+    }
+
+    // Generate the wrapper routines implemented in Modula 3
+    {
+      File *file = openWriteFile(NewStringf("%s%s.m3", Swig_file_dirname(outfile), m3wrap_name));
+
+      emitBanner(file);
+
+      if (unsafe_module) {
+	Printf(file, "UNSAFE ");
+      }
+      Printf(file, "MODULE %s;\n\n", m3wrap_name);
+
+      emitImportStatements(m3wrap_impl.import, file);
+      Printf(file, "\n");
+
+      // Add the wrapper methods
+      Printv(file, m3wrap_impl.f, NIL);
+
+      Printf(file, "\nBEGIN\nEND %s.\n", m3wrap_name);
+      Close(file);
+    }
+
+    if (upcasts_code)
+      Printv(f_wrappers, upcasts_code, NIL);
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n");
+    Printf(f_wrappers, "}\n");
+    Printf(f_wrappers, "#endif\n");
+
+    // Output a Modula 3 type wrapper class for each SWIG type
+    for (Iterator swig_type = First(swig_types_hash); swig_type.item != NIL; swig_type = Next(swig_type)) {
+      emitTypeWrapperClass(swig_type.key, swig_type.item);
+    }
+
+    Delete(swig_types_hash);
+    swig_types_hash = NULL;
+    Delete(constant_values);
+    constant_values = NULL;
+    Delete(enumeration_coll);
+    enumeration_coll = NULL;
+    Delete(m3raw_name);
+    m3raw_name = NULL;
+    Delete(m3raw_baseclass);
+    m3raw_baseclass = NULL;
+    Delete(m3raw_interfaces);
+    m3raw_interfaces = NULL;
+    Delete(m3raw_class_modifiers);
+    m3raw_class_modifiers = NULL;
+    Delete(m3raw_imports);
+    m3raw_imports = NULL;
+    Delete(m3raw_cppcasts_code);
+    m3raw_cppcasts_code = NULL;
+    Delete(proxy_class_def);
+    proxy_class_def = NULL;
+    Delete(proxy_class_code);
+    proxy_class_code = NULL;
+    Delete(m3wrap_name);
+    m3wrap_name = NULL;
+    Delete(m3wrap_modifiers);
+    m3wrap_modifiers = NULL;
+    Delete(targetlibrary);
+    targetlibrary = NULL;
+    Delete(module_baseclass);
+    module_baseclass = NULL;
+    Delete(module_interfaces);
+    module_interfaces = NULL;
+    Delete(module_imports);
+    module_imports = NULL;
+    Delete(upcasts_code);
+    upcasts_code = NULL;
+    Delete(constantfilename);
+    constantfilename = NULL;
+    Delete(renamefilename);
+    renamefilename = NULL;
+    Delete(typemapfilename);
+    typemapfilename = NULL;
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitBanner()
+   * ----------------------------------------------------------------------------- */
+
+  void emitBanner(File *f) {
+    Printf(f, "\
+(*******************************************************************************\n\
+ * This file was automatically generated by SWIG (http://www.swig.org/).\n\
+ * Version %s\n\
+ *\n\
+ * Do not make changes to this file unless you know what you are doing --\n\
+ * modify the SWIG interface file instead.\n\
+ *******************************************************************************)\n\n", Swig_package_version());
+  }
+
+  /* ----------------------------------------------------------------------
+   * nativeWrapper()
+   * ---------------------------------------------------------------------- */
+
+  virtual int nativeWrapper(Node *n) {
+    String *wrapname = Getattr(n, "wrap:name");
+
+    if (!addSymbol(wrapname, n))
+      return SWIG_ERROR;
+
+    if (Getattr(n, "type")) {
+      Swig_save("nativeWrapper", n, "name", NIL);
+      Setattr(n, "name", wrapname);
+      native_function_flag = true;
+      functionWrapper(n);
+      Swig_restore(n);
+      native_function_flag = false;
+    } else {
+      Printf(stderr, "%s : Line %d. No return type for %%native method %s.\n", input_file, line_number, Getattr(n, "wrap:name"));
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * functionWrapper()
+   * ---------------------------------------------------------------------- */
+
+  virtual int functionWrapper(Node *n) {
+    String *type = nodeType(n);
+    String *funcType = Getattr(n, "modula3:functype");
+    String *rawname = Getattr(n, "name");
+    String *symname = Getattr(n, "sym:name");
+    String *capname = capitalizeFirst(symname);
+    //String *wname = Swig_name_wrapper(symname);
+
+    //printf("function: %s\n", Char(symname));
+    //printf(" purpose: %s\n", Char(funcType));
+
+    if (Strcmp(type, "cdecl") == 0) {
+      if (funcType == NIL) {
+	// no wrapper needed for plain functions
+	emitM3RawPrototype(n, rawname, symname);
+	emitM3Wrapper(n, symname);
+      } else if (Strcmp(funcType, "method") == 0) {
+	Setattr(n, "modula3:funcname", capname);
+	emitCWrapper(n, capname);
+	emitM3RawPrototype(n, capname, capname);
+	emitM3Wrapper(n, capname);
+      } else if (Strcmp(funcType, "accessor") == 0) {
+	/*
+	 * Generate the proxy class properties for public member variables.
+	 * Not for enums and constants.
+	 */
+	if (proxy_flag && wrapping_member_flag && !enum_constant_flag) {
+	  // Capitalize the first letter in the function name
+	  Setattr(n, "proxyfuncname", capname);
+	  Setattr(n, "imfuncname", symname);
+	  if (hasPrefix(capname, "Set")) {
+	    Setattr(n, "modula3:setname", capname);
+	  } else {
+	    Setattr(n, "modula3:getname", capname);
+	  }
+
+	  emitCWrapper(n, capname);
+	  emitM3RawPrototype(n, capname, capname);
+	  emitM3Wrapper(n, capname);
+	  //proxyClassFunctionHandler(n);
+	}
+#ifdef DEBUG
+      } else {
+	Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Function type <%s> unknown.\n", Char(funcType));
+#endif
+      }
+    } else if ((Strcmp(type, "constructor") == 0) || (Strcmp(type, "destructor") == 0)) {
+      emitCWrapper(n, capname);
+      emitM3RawPrototype(n, capname, capname);
+      emitM3Wrapper(n, capname);
+    }
+// a Java relict
+#if 0
+    if (!(proxy_flag && is_wrapping_class()) && !enum_constant_flag) {
+      emitM3Wrapper(n, capname);
+    }
+#endif
+
+    Delete(capname);
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * emitCWrapper()
+   *
+   * Generate the wrapper in C which calls C++ methods.
+   * ---------------------------------------------------------------------- */
+
+  virtual int emitCWrapper(Node *n, const String *wname) {
+    String *rawname = Getattr(n, "name");
+    String *c_return_type = NewString("");
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *body = NewString("");
+    Hash *throws_hash = NewHash();
+    ParmList *l = Getattr(n, "parms");
+    SwigType *t = Getattr(n, "type");
+    String *symname = Getattr(n, "sym:name");
+
+    if (!Getattr(n, "sym:overloaded")) {
+      if (!addSymbol(wname, n)) {
+	return SWIG_ERROR;
+      }
+    }
+    // A new wrapper function object
+    Wrapper *f = NewWrapper();
+
+    /* Attach the non-standard typemaps to the parameter list. */
+    Swig_typemap_attach_parms("ctype", l, f);
+
+    /* Get return types */
+    {
+      String *tm = getMappedTypeNew(n, "ctype", "");
+      if (tm != NIL) {
+	Printf(c_return_type, "%s", tm);
+      }
+    }
+
+    bool is_void_return = (Cmp(c_return_type, "void") == 0);
+    if (!is_void_return) {
+      Wrapper_add_localv(f, "cresult", c_return_type, "cresult = 0", NIL);
+    }
+
+    Printv(f->def, " SWIGEXPORT ", c_return_type, " ", wname, "(", NIL);
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    // Generate signature and argument conversion for C wrapper
+    {
+      Parm *p;
+      attachParameterNames(n, "tmap:name", "c:wrapname", "m3arg%d");
+      bool gencomma = false;
+      for (p = skipIgnored(l, "in"); p != NULL; p = skipIgnored(p, "in")) {
+
+	String *arg = Getattr(p, "c:wrapname");
+	{
+	  /* Get the ctype types of the parameter */
+	  String *c_param_type = getMappedType(p, "ctype");
+	  // Add parameter to C function
+	  Printv(f->def, gencomma ? ", " : "", c_param_type, " ", arg, NIL);
+	  Delete(c_param_type);
+	  gencomma = true;
+	}
+
+	// Get typemap for this argument
+	String *tm = getMappedType(p, "in");
+	if (tm != NIL) {
+	  addThrows(throws_hash, "in", p);
+	  Replaceall(tm, "$input", arg);
+	  Setattr(p, "emit:input", arg);	/*??? */
+	  Printf(f->code, "%s\n", tm);
+	  p = Getattr(p, "tmap:in:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    /* Insert constraint checking code */
+    {
+      Parm *p;
+      for (p = l; p;) {
+	String *tm = Getattr(p, "tmap:check");
+	if (tm != NIL) {
+	  addThrows(throws_hash, "check", p);
+	  Replaceall(tm, "$target", Getattr(p, "lname"));	/* deprecated */
+	  Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	  Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	  Printv(f->code, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:check:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    /* Insert cleanup code */
+    {
+      Parm *p;
+      for (p = l; p;) {
+	String *tm = Getattr(p, "tmap:freearg");
+	if (tm != NIL) {
+	  addThrows(throws_hash, "freearg", p);
+	  Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* deprecated */
+	  Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	  Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	  Printv(cleanup, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:freearg:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    /* Insert argument output code */
+    {
+      Parm *p;
+      for (p = l; p;) {
+	String *tm = Getattr(p, "tmap:argout");
+	if (tm != NIL) {
+	  addThrows(throws_hash, "argout", p);
+	  Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* deprecated */
+	  Replaceall(tm, "$target", Getattr(p, "lname"));	/* deprecated */
+	  Replaceall(tm, "$arg", Getattr(p, "emit:input"));	/* deprecated? */
+	  Replaceall(tm, "$result", "cresult");
+	  Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	  Printv(outarg, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:argout:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    // Get any Modula 3 exception classes in the throws typemap
+    ParmList *throw_parm_list = NULL;
+    if ((throw_parm_list = Getattr(n, "throws"))) {
+      Swig_typemap_attach_parms("throws", throw_parm_list, f);
+      Parm *p;
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	addThrows(throws_hash, "throws", p);
+      }
+    }
+
+    if (Cmp(nodeType(n), "constant") == 0) {
+      // Wrapping a constant hack
+      Swig_save("functionWrapper", n, "wrap:action", NIL);
+
+      // below based on Swig_VargetToFunction()
+      SwigType *ty = Swig_wrapped_var_type(Getattr(n, "type"), use_naturalvar_mode(n));
+      Setattr(n, "wrap:action", NewStringf("result = (%s) %s;", SwigType_lstr(ty, 0), Getattr(n, "value")));
+    }
+
+    Setattr(n, "wrap:name", wname);
+
+    // Now write code to make the function call
+    if (!native_function_flag) {
+      String *actioncode = emit_action(n);
+
+      if (Cmp(nodeType(n), "constant") == 0) {
+        Swig_restore(n);
+      }
+
+      /* Return value if necessary  */
+      String *tm;
+      if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+	addThrows(throws_hash, "out", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Replaceall(tm, "$target", "cresult");	/* deprecated */
+	Replaceall(tm, "$result", "cresult");
+	Printf(f->code, "%s", tm);
+	if (hasContent(tm))
+	  Printf(f->code, "\n");
+      } else {
+	Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(t, 0), rawname);
+      }
+      emit_return_variable(n, t, f);
+    }
+
+    /* Output argument output code */
+    Printv(f->code, outarg, NIL);
+
+    /* Output cleanup code */
+    Printv(f->code, cleanup, NIL);
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      String *tm = Swig_typemap_lookup("newfree", n, "result", 0);
+      if (tm != NIL) {
+	addThrows(throws_hash, "newfree", n);
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if (!native_function_flag) {
+      String *tm = Swig_typemap_lookup("ret", n, "result", 0);
+      if (tm != NIL) {
+	Replaceall(tm, "$source", "result");	/* deprecated */
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* Finish C wrapper */
+    Printf(f->def, ") {");
+
+    if (!is_void_return)
+      Printv(f->code, "    return cresult;\n", NIL);
+    Printf(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", symname);
+
+    if (!is_void_return) {
+      Replaceall(f->code, "$null", "0");
+    } else {
+      Replaceall(f->code, "$null", "");
+    }
+
+    /* Dump the function out */
+    if (!native_function_flag) {
+      Wrapper_print(f, f_wrappers);
+    }
+
+    Delete(c_return_type);
+    Delete(cleanup);
+    Delete(outarg);
+    Delete(body);
+    Delete(throws_hash);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * emitM3RawPrototype()
+   *
+   * Generate an EXTERNAL procedure declaration in Modula 3
+   * which is the interface to an existing C routine or a C wrapper.
+   * ---------------------------------------------------------------------- */
+
+  virtual int emitM3RawPrototype(Node *n, const String *cname, const String *m3name) {
+    String *im_return_type = NewString("");
+    //String   *symname = Getattr(n,"sym:name");
+    ParmList *l = Getattr(n, "parms");
+
+    /* Attach the non-standard typemaps to the parameter list. */
+    Swig_typemap_attach_parms("m3rawinmode", l, NULL);
+    Swig_typemap_attach_parms("m3rawintype", l, NULL);
+
+    /* Get return types */
+    bool has_return;
+    {
+      String *tm = getMappedTypeNew(n, "m3rawrettype", "");
+      if (tm != NIL) {
+	Printf(im_return_type, "%s", tm);
+      }
+      has_return = hasContent(tm);
+    }
+
+    /* cname is the original name if 'n' denotes a C function
+       and it is the relabeled name (sym:name) if 'n' denotes a C++ method or similar */
+    m3raw_intf.enterBlock(no_block);
+    Printf(m3raw_intf.f, "\n<* EXTERNAL %s *>\nPROCEDURE %s (", cname, m3name);
+
+    // Generate signature for raw interface
+    {
+      Parm *p;
+      writeArgState state;
+      attachParameterNames(n, "tmap:rawinname", "modula3:rawname", "arg%d");
+      for (p = skipIgnored(l, "m3rawintype"); p != NULL; p = skipIgnored(p, "m3rawintype")) {
+
+	/* Get argument passing mode, should be one of VALUE, VAR, READONLY */
+	String *mode = Getattr(p, "tmap:m3rawinmode");
+	String *argname = Getattr(p, "modula3:rawname");
+	String *im_param_type = getMappedType(p, "m3rawintype");
+	addImports(m3raw_intf.import, "m3rawintype", p);
+
+	writeArg(m3raw_intf.f, state, mode, argname, im_param_type, NIL);
+	if (im_param_type != NIL) {
+	  p = Getattr(p, "tmap:m3rawintype:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+      writeArg(m3raw_intf.f, state, NIL, NIL, NIL, NIL);
+    }
+
+    /* Finish M3 raw prototype */
+    Printf(m3raw_intf.f, ")");
+    // neither a C wrapper nor a plain C function may throw an exception
+    //generateThrowsClause(throws_hash, m3raw_intf.f);
+    if (has_return) {
+      Printf(m3raw_intf.f, ": %s", im_return_type);
+    }
+    Printf(m3raw_intf.f, ";\n");
+
+    Delete(im_return_type);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * variableWrapper()
+   * ----------------------------------------------------------------------- */
+
+  virtual int variableWrapper(Node *n) {
+    Language::variableWrapper(n);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * globalvariableHandler()
+   * ----------------------------------------------------------------------- */
+
+  virtual int globalvariableHandler(Node *n) {
+    SwigType *t = Getattr(n, "type");
+    String *tm;
+
+    // Get the variable type
+    if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) {
+      substituteClassname(t, tm);
+    }
+
+    variable_name = Getattr(n, "sym:name");
+    variable_type = Copy(tm);
+
+    // Get the variable type expressed in terms of Modula 3 equivalents of C types
+    if ((tm = getMappedTypeNew(n, "m3rawtype", ""))) {
+      m3raw_intf.enterBlock(no_block);
+      Printf(m3raw_intf.f, "\n<* EXTERNAL *> VAR %s: %s;\n", variable_name, tm);
+    }
+    // Output the property's accessor methods
+    /*
+       global_variable_flag = true;
+       int ret = Language::globalvariableHandler(n);
+       global_variable_flag = false;
+     */
+
+    Printf(m3wrap_impl.f, "\n\n");
+
+    //return ret;
+    return 1;
+  }
+
+  long getConstNumeric(Node *n) {
+    String *constnumeric = Getfeature(n, "constnumeric");
+    String *name = Getattr(n, "name");
+    long numvalue;
+    if (constnumeric == NIL) {
+      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Feature 'constnumeric' is necessary to obtain value of %s.\n", name);
+      return 0;
+    } else if (!strToL(constnumeric, numvalue)) {
+      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number,
+		   "The feature 'constnumeric' of %s specifies value <%s> which is not an integer constant.\n", name, constnumeric);
+      return 0;
+    } else {
+      return numvalue;
+    }
+  }
+
+  /* ------------------------------------------------------------------------
+   * generateIntConstant()
+   *
+   * Considers node as an integer constant definition
+   * and generate a Modula 3 constant definition.
+   * ------------------------------------------------------------------------ */
+  void generateIntConstant(Node *n, String *name) {
+    String *value = Getattr(n, "value");
+    String *type = Getfeature(n, "modula3:constint:type");
+    String *conv = Getfeature(n, "modula3:constint:conv");
+
+    if (name == NIL) {
+      name = Getattr(n, "sym:name");
+    }
+
+    long numvalue;
+    bool isSimpleNum = strToL(value, numvalue);
+    if (!isSimpleNum) {
+      numvalue = getConstNumeric(n);
+    }
+
+    String *m3value;
+    if ((conv == NIL) || ((Strcmp(conv, "set:int") != 0) && (Strcmp(conv, "int:set") != 0))) {
+      /* The original value of the constant has precedence over
+         'constnumeric' feature since we like to keep
+         the style (that is the base) of simple numeric constants */
+      if (isSimpleNum) {
+	if (hasPrefix(value, "0x")) {
+	  m3value = NewStringf("16_%s", Char(value) + 2);
+	} else if ((Len(value) > 1) && (*Char(value) == '0')) {
+	  m3value = NewStringf("8_%s", Char(value) + 1);
+	} else {
+	  m3value = Copy(value);
+	}
+	/* If we cannot easily obtain the value of a numeric constant,
+	   we use the results given by a C compiler. */
+      } else {
+	m3value = Copy(Getfeature(n, "constnumeric"));
+      }
+    } else {
+      // if the value can't be converted, it is ignored
+      if (convertInt(numvalue, numvalue, conv)) {
+	m3value = NewStringf("%d", numvalue);
+      } else {
+	m3value = NIL;
+      }
+    }
+
+    if (m3value != NIL) {
+      m3wrap_intf.enterBlock(constant);
+      Printf(m3wrap_intf.f, "%s", name);
+      if (hasContent(type)) {
+	Printf(m3wrap_intf.f, ": %s", type);
+      }
+      Printf(m3wrap_intf.f, " = %s;\n", m3value);
+      Delete(m3value);
+    }
+  }
+
+  /* -----------------------------------------------------------------------
+   * generateSetConstant()
+   *
+   * Considers node as a set constant definition
+   * and generate a Modula 3 constant definition.
+   * ------------------------------------------------------------------------ */
+  void generateSetConstant(Node *n, String *name) {
+    String *value = Getattr(n, "value");
+    String *type = Getfeature(n, "modula3:constset:type");
+    String *setname = Getfeature(n, "modula3:constset:set");
+    String *basename = Getfeature(n, "modula3:constset:base");
+    String *conv = Getfeature(n, "modula3:constset:conv");
+
+    m3wrap_intf.enterBlock(constant);
+
+    Printf(m3wrap_intf.f, "%s", name);
+    if (type != NIL) {
+      Printf(m3wrap_intf.f, ":%s ", type);
+    }
+    Printf(m3wrap_intf.f, " = %s{", setname);
+
+    long numvalue = 0;
+    if (!strToL(value, numvalue)) {
+      numvalue = getConstNumeric(n);
+    }
+    convertInt(numvalue, numvalue, conv);
+
+    bool isIntType = Strcmp(basename, "CARDINAL") == 0;
+    Hash *items = NIL;
+    if (!isIntType) {
+      Hash *enumeration = Getattr(enumeration_coll, basename);
+      if (enumeration == NIL) {
+	Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "There is no enumeration <%s> as needed for the set.\n", setname);
+	isIntType = true;
+      } else {
+	items = Getattr(enumeration, "items");
+      }
+    }
+
+    bool gencomma = false;
+    int bitpos = 0;
+    while (numvalue > 0) {
+      if ((numvalue & 1) != 0) {
+	if (isIntType) {
+	  if (gencomma) {
+	    Printv(m3wrap_intf.f, ",", NIL);
+	  }
+	  gencomma = true;
+	  Printf(m3wrap_intf.f, "%d", bitpos);
+	} else {
+	  char bitval[15];
+	  sprintf(bitval, "%d", bitpos);
+	  String *bitname = Getattr(items, bitval);
+	  if (bitname == NIL) {
+	    Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Enumeration <%s> has no value <%s>.\n", setname, bitval);
+	  } else {
+	    if (gencomma) {
+	      Printv(m3wrap_intf.f, ",", NIL);
+	    }
+	    gencomma = true;
+	    Printf(m3wrap_intf.f, "%s.%s", basename, bitname);
+	  }
+	}
+      }
+      numvalue >>= 1;
+      bitpos++;
+    }
+    Printf(m3wrap_intf.f, "};\n");
+  }
+
+  void generateConstant(Node *n) {
+    // any of the special interpretation disables the default behaviour
+    String *enumitem = Getfeature(n, "modula3:enumitem:name");
+    String *constset = Getfeature(n, "modula3:constset:name");
+    String *constint = Getfeature(n, "modula3:constint:name");
+    if (hasContent(enumitem) || hasContent(constset) || hasContent(constint)) {
+      if (hasContent(constset)) {
+	generateSetConstant(n, constset);
+      }
+      if (hasContent(constint)) {
+	generateIntConstant(n, constint);
+      }
+    } else {
+      String *value = Getattr(n, "value");
+      String *name = Getattr(n, "sym:name");
+      if (name == NIL) {
+	name = Getattr(n, "name");
+      }
+      m3wrap_intf.enterBlock(constant);
+      Printf(m3wrap_intf.f, "%s = %s;\n", name, value);
+    }
+  }
+
+#if 0
+  void generateEnumerationItem(const String *name, const String *value, int numvalue) {
+    String *oldsymname = Getattr(enumeration_items, value);
+    if (oldsymname != NIL) {
+      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "The value <%s> is already assigned to <%s>.\n", value, oldsymname);
+    }
+    Setattr(enumeration_items, value, name);
+    if (enumeration_max < numvalue) {
+      enumeration_max = numvalue;
+    }
+  }
+#endif
+
+  void emitEnumeration(File *file, String *name, Node *n) {
+    Printf(file, "%s = {", name);
+    int i;
+    bool gencomma = false;
+    int max = aToL(Getattr(n, "max"));
+    Hash *items = Getattr(n, "items");
+    for (i = 0; i <= max; i++) {
+      if (gencomma) {
+	Printf(file, ",");
+      }
+      Printf(file, "\n");
+      gencomma = true;
+      char numstr[15];
+      sprintf(numstr, "%d", i);
+      String *name = Getattr(items, numstr);
+      if (name != NIL) {
+	Printv(file, name, NIL);
+      } else {
+	Printf(file, "Dummy%d", i);
+      }
+    }
+    Printf(file, "\n};\n");
+  }
+
+  /* -----------------------------------------------------------------------
+   * constantWrapper()
+   *
+   * Handles constants and enumeration items.
+   * ------------------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    generateConstant(n);
+    return SWIG_OK;
+  }
+
+#if 0
+// enumerations are handled like constant definitions
+  /* -----------------------------------------------------------------------------
+   * enumDeclaration()
+   * ----------------------------------------------------------------------------- */
+
+  virtual int enumDeclaration(Node *n) {
+    String *symname = nameToModula3(Getattr(n, "sym:name"), true);
+    enumerationStart(symname);
+    int result = Language::enumDeclaration(n);
+    enumerationStop();
+    Delete(symname);
+    return result;
+  }
+#endif
+
+  /* -----------------------------------------------------------------------------
+   * enumvalueDeclaration()
+   * ----------------------------------------------------------------------------- */
+
+  virtual int enumvalueDeclaration(Node *n) {
+    generateConstant(n);
+    /*
+       This call would continue processing in the constantWrapper
+       which cannot handle values like "RED+1".
+       return Language::enumvalueDeclaration(n);
+     */
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * pragmaDirective()
+   *
+   * Valid Pragmas:
+   * imclassbase            - base (extends) for the intermediary class
+   * imclassclassmodifiers  - class modifiers for the intermediary class
+   * imclasscode            - text (Modula 3 code) is copied verbatim to the intermediary class
+   * imclassimports         - import statements for the intermediary class
+   * imclassinterfaces      - interface (implements) for the intermediary class
+   *
+   * modulebase              - base (extends) for the module class
+   * moduleclassmodifiers    - class modifiers for the module class
+   * modulecode              - text (Modula 3 code) is copied verbatim to the module class
+   * moduleimports           - import statements for the module class
+   * moduleinterfaces        - interface (implements) for the module class
+   *
+   * ----------------------------------------------------------------------------- */
+
+  virtual int pragmaDirective(Node *n) {
+    if (!ImportMode) {
+      String *lang = Getattr(n, "lang");
+      String *code = Getattr(n, "name");
+      String *value = Getattr(n, "value");
+
+      if (Strcmp(lang, "modula3") == 0) {
+
+	String *strvalue = NewString(value);
+	Replaceall(strvalue, "\\\"", "\"");
+/*
+        bool isEnumItem = Strcmp(code, "enumitem") == 0;
+        bool isSetItem  = Strcmp(code, "setitem")  == 0;
+*/
+	if (Strcmp(code, "imclassbase") == 0) {
+	  Delete(m3raw_baseclass);
+	  m3raw_baseclass = Copy(strvalue);
+	} else if (Strcmp(code, "imclassclassmodifiers") == 0) {
+	  Delete(m3raw_class_modifiers);
+	  m3raw_class_modifiers = Copy(strvalue);
+	} else if (Strcmp(code, "imclasscode") == 0) {
+	  Printf(m3raw_intf.f, "%s\n", strvalue);
+	} else if (Strcmp(code, "imclassimports") == 0) {
+	  Delete(m3raw_imports);
+	  m3raw_imports = Copy(strvalue);
+	} else if (Strcmp(code, "imclassinterfaces") == 0) {
+	  Delete(m3raw_interfaces);
+	  m3raw_interfaces = Copy(strvalue);
+	} else if (Strcmp(code, "modulebase") == 0) {
+	  Delete(module_baseclass);
+	  module_baseclass = Copy(strvalue);
+	} else if (Strcmp(code, "moduleclassmodifiers") == 0) {
+	  Delete(m3wrap_modifiers);
+	  m3wrap_modifiers = Copy(strvalue);
+	} else if (Strcmp(code, "modulecode") == 0) {
+	  Printf(m3wrap_impl.f, "%s\n", strvalue);
+	} else if (Strcmp(code, "moduleimports") == 0) {
+	  Delete(module_imports);
+	  module_imports = Copy(strvalue);
+	} else if (Strcmp(code, "moduleinterfaces") == 0) {
+	  Delete(module_interfaces);
+	  module_interfaces = Copy(strvalue);
+	} else if (Strcmp(code, "unsafe") == 0) {
+	  unsafe_module = true;
+	} else if (Strcmp(code, "library") == 0) {
+	  if (targetlibrary != NULL) {
+	    Delete(targetlibrary);
+	  }
+	  targetlibrary = Copy(strvalue);
+	} else if (Strcmp(code, "enumitem") == 0) {
+	} else if (Strcmp(code, "constset") == 0) {
+	} else if (Strcmp(code, "constint") == 0) {
+	} else if (Strcmp(code, "makesetofenum") == 0) {
+	  m3wrap_intf.enterBlock(blocktype);
+	  Printf(m3wrap_intf.f, "%sSet = SET OF %s;\n", value, value);
+	} else {
+	  Swig_warning(WARN_MODULA3_UNKNOWN_PRAGMA, input_file, line_number, "Unrecognized pragma <%s>.\n", code);
+	}
+	Delete(strvalue);
+      }
+    }
+    return Language::pragmaDirective(n);
+  }
+
+  void Setfeature(Node *n, const char *feature, const String *value, bool warn = false) {
+    //printf("tag feature <%s> with value <%s>\n", feature, Char(value));
+    String *attr = NewStringf("feature:%s", feature);
+    if ((Setattr(n, attr, value) != 0) && warn) {
+      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Feature <%s> of %s did already exist.\n", feature, Getattr(n, "name"));
+    }
+    Delete(attr);
+  }
+
+  String *Getfeature(Node *n, const char *feature) {
+    //printf("retrieve feature <%s> with value <%s>\n", feature, Char(value));
+    String *attr = NewStringf("feature:%s", feature);
+    String *result = Getattr(n, attr);
+    Delete(attr);
+    return result;
+  }
+
+  bool convertInt(long in, long &out, const String *mode) {
+    if ((mode == NIL) || (Strcmp(mode, "int:int") == 0) || (Strcmp(mode, "set:set") == 0)) {
+      out = in;
+      return true;
+    } else if (Strcmp(mode, "set:int") == 0) {
+      return log2(in, out);
+    } else if (Strcmp(mode, "int:set") == 0) {
+      out = 1L << in;
+      return unsigned (in) < (sizeof(out) * 8);
+    } else {
+      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown integer conversion method <%s>.\n", mode);
+      return false;
+    }
+  }
+
+  void collectEnumerations(Hash *enums, Node *n) {
+    Node *child = firstChild(n);
+    while (child != NIL) {
+      String *name = Getattr(child, "name");
+      const bool isConstant = Strcmp(nodeType(child), "constant") == 0;
+      const bool isEnumItem = Strcmp(nodeType(child), "enumitem") == 0;
+      if (isConstant || isEnumItem) {
+//printf("%s%s name %s\n", isConstant?"constant":"", isEnumItem?"enumitem":"", Char(name));
+	{
+	  String *m3name = Getfeature(child, "modula3:enumitem:name");
+	  String *m3enum = Getfeature(child, "modula3:enumitem:enum");
+	  String *conv = Getfeature(child, "modula3:enumitem:conv");
+
+	  if (m3enum != NIL) {
+//printf("m3enum %s\n", Char(m3enum));
+	    if (m3name == NIL) {
+	      m3name = name;
+	    }
+
+	    long max = -1;
+	    Hash *items;
+	    Hash *enumnode = Getattr(enums, m3enum);
+	    if (enumnode == NIL) {
+	      enumnode = NewHash();
+	      items = NewHash();
+	      Setattr(enumnode, "items", items);
+	      Setattr(enums, m3enum, enumnode);
+	    } else {
+	      String *maxstr = Getattr(enumnode, "max");
+	      if (maxstr != NIL) {
+		max = aToL(maxstr);
+	      }
+	      items = Getattr(enumnode, "items");
+	    }
+	    long numvalue;
+	    String *value = Getattr(child, "value");
+//printf("value: %s\n", Char(value));
+	    if ((value == NIL) || (!strToL(value, numvalue))) {
+	      value = Getattr(child, "enumvalue");
+	      if ((value == NIL) || (!evalExpr(value, numvalue))) {
+		numvalue = getConstNumeric(child);
+	      }
+//printf("constnumeric: %s\n", Char(value));
+	    }
+	    Setattr(constant_values, name, NewStringf("%d", numvalue));
+	    if (convertInt(numvalue, numvalue, conv)) {
+	      String *newvalue = NewStringf("%d", numvalue);
+	      String *oldname = Getattr(items, newvalue);
+	      if (oldname != NIL) {
+		Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "The value <%s> is already assigned to <%s>.\n", value, oldname);
+	      }
+//printf("items %lx, set %s = %s\n", (long) items, Char(newvalue), Char(m3name));
+	      Setattr(items, newvalue, m3name);
+	      if (max < numvalue) {
+		max = numvalue;
+	      }
+	      Setattr(enumnode, "max", NewStringf("%d", max));
+	    }
+	  }
+	}
+      }
+
+      collectEnumerations(enums, child);
+      child = nextSibling(child);
+    }
+  }
+
+  enum const_pragma_type { cpt_none, cpt_constint, cpt_constset, cpt_enumitem };
+
+  struct const_id_pattern {
+    String *prefix, *parentEnum;
+  };
+
+  void tagConstants(Node *first, String *parentEnum, const const_id_pattern & pat, const String *pragma, List *convdesc) {
+    Node *n = first;
+    while (n != NIL) {
+      String *name = getQualifiedName(n);
+      bool isConstant = Strcmp(nodeType(n), "constant") == 0;
+      bool isEnumItem = Strcmp(nodeType(n), "enumitem") == 0;
+      if ((isConstant || isEnumItem) && ((pat.prefix == NIL) || (hasPrefix(name, pat.prefix))) && ((pat.parentEnum == NIL) || ((parentEnum != NIL)
+															       &&
+															       (Strcmp
+																(pat.parentEnum, parentEnum)
+																== 0)))) {
+	//printf("tag %s\n", Char(name));
+	String *srctype = Getitem(convdesc, 1);
+	String *relationstr = Getitem(convdesc, 3);
+	List *relationdesc = Split(relationstr, ',', 2);
+
+	// transform name from C to Modula3 style
+	String *srcstyle = NIL;
+	String *newprefix = NIL;
+	{
+	  //printf("name conversion <%s>\n", Char(Getitem(convdesc,2)));
+	  List *namedesc = Split(Getitem(convdesc, 2), ',', INT_MAX);
+	  Iterator nameit = First(namedesc);
+	  for (; nameit.item != NIL; nameit = Next(nameit)) {
+	    List *nameassign = Split(nameit.item, '=', 2);
+	    String *tag = Getitem(nameassign, 0);
+	    String *data = Getitem(nameassign, 1);
+	    //printf("name conv <%s> = <%s>\n", Char(tag), Char(data));
+	    if (Strcmp(tag, "srcstyle") == 0) {
+	      srcstyle = Copy(data);
+	    } else if (Strcmp(tag, "prefix") == 0) {
+	      newprefix = Copy(data);
+	    } else {
+	      Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown name conversion tag <%s> with value <%s>.\n", tag, data);
+	    }
+	    Delete(nameassign);
+	  }
+	  Delete(namedesc);
+	}
+	const char *stem = Char(name);
+	if (pat.prefix != NIL) {
+	  //printf("pat.prefix %s for %s\n", Char(pat.prefix), Char(name));
+	  stem += Len(pat.prefix);
+	}
+	String *newname;
+	if (Strcmp(srcstyle, "underscore") == 0) {
+	  if (newprefix != NIL) {
+	    String *newstem = nameToModula3(stem, true);
+	    newname = NewStringf("%s%s", newprefix, newstem);
+	    Delete(newstem);
+	  } else {
+	    newname = nameToModula3(stem, true);
+	  }
+	} else {
+	  if (srcstyle != NIL) {
+	    Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown C identifier style <%s>.\n", srcstyle);
+	  }
+	  newname = Copy(name);
+	}
+
+	if (Strcmp(pragma, "enumitem") == 0) {
+	  if (Len(relationdesc) != 1) {
+	    Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Expected <enumeration>, got <%s>.\n", relationstr);
+	  }
+	  Setfeature(n, "modula3:enumitem:name", newname, true);
+	  Setfeature(n, "modula3:enumitem:enum", relationstr, true);
+	  Setfeature(n, "modula3:enumitem:conv", NewStringf("%s:int", srctype), true);
+	} else if (Strcmp(pragma, "constint") == 0) {
+	  if (Len(relationdesc) != 1) {
+	    Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Expected <ordinal type>, got <%s>.\n", relationstr);
+	  }
+	  Setfeature(n, "modula3:constint:name", newname, true);
+	  Setfeature(n, "modula3:constint:type", Getitem(relationdesc, 0), true);
+	  Setfeature(n, "modula3:constint:conv", NewStringf("%s:int", srctype), true);
+	} else if (Strcmp(pragma, "constset") == 0) {
+	  if (Len(relationdesc) != 2) {
+	    Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Expected <set type,base type>, got <%s>.\n", relationstr);
+	  }
+	  String *settype = Getitem(relationdesc, 0);
+	  Setfeature(n, "modula3:constset:name", newname, true);
+	  //Setfeature(n,"modula3:constset:type",settype,true);
+	  Setfeature(n, "modula3:constset:set", settype, true);
+	  Setfeature(n, "modula3:constset:base", Getitem(relationdesc, 1), true);
+	  Setfeature(n, "modula3:constset:conv", NewStringf("%s:set", srctype), true);
+	}
+
+	Delete(newname);
+	Delete(relationdesc);
+      }
+
+      if (Strcmp(nodeType(n), "enum") == 0) {
+	//printf("explore enum %s, qualification %s\n", Char(name), Char(Swig_symbol_qualified(n)));
+	tagConstants(firstChild(n), name, pat, pragma, convdesc);
+      } else {
+	tagConstants(firstChild(n), NIL, pat, pragma, convdesc);
+      }
+      n = nextSibling(n);
+    }
+  }
+
+  void scanForConstPragmas(Node *n) {
+    Node *child = firstChild(n);
+    while (child != NIL) {
+      const String *type = nodeType(child);
+      if (Strcmp(type, "pragma") == 0) {
+	const String *lang = Getattr(child, "lang");
+	const String *code = Getattr(child, "name");
+	String *value = Getattr(child, "value");
+
+	if (Strcmp(lang, "modula3") == 0) {
+	  const_pragma_type cpt = cpt_none;
+	  if (Strcmp(code, "constint") == 0) {
+	    cpt = cpt_constint;
+	  } else if (Strcmp(code, "constset") == 0) {
+	    cpt = cpt_constset;
+	  } else if (Strcmp(code, "enumitem") == 0) {
+	    cpt = cpt_enumitem;
+	  }
+	  if (cpt != cpt_none) {
+	    const_id_pattern pat = { NIL, NIL };
+
+	    List *convdesc = Split(value, ';', 4);
+	    List *patterndesc = Split(Getitem(convdesc, 0), ',', INT_MAX);
+	    Iterator patternit;
+	    for (patternit = First(patterndesc); patternit.item != NIL; patternit = Next(patternit)) {
+	      List *patternassign = Split(patternit.item, '=', 2);
+	      String *tag = Getitem(patternassign, 0);
+	      String *data = Getitem(patternassign, 1);
+	      if (Strcmp(tag, "prefix") == 0) {
+		pat.prefix = Copy(data);
+	      } else if (Strcmp(tag, "enum") == 0) {
+		pat.parentEnum = Copy(data);
+	      } else {
+		Swig_warning(WARN_MODULA3_BAD_ENUMERATION, input_file, line_number, "Unknown identification tag <%s> with value <%s>.\n", tag, data);
+	      }
+	      Delete(patternassign);
+	    }
+	    tagConstants(child, NIL, pat, code, convdesc);
+
+	    Delete(patterndesc);
+	  }
+	}
+      }
+      scanForConstPragmas(child);
+      child = nextSibling(child);
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitProxyClassDefAndCPPCasts()
+   * ----------------------------------------------------------------------------- */
+
+  void emitProxyClassDefAndCPPCasts(Node *n) {
+    String *c_classname = SwigType_namestr(Getattr(n, "name"));
+    String *c_baseclass = NULL;
+    String *baseclass = NULL;
+    String *c_baseclassname = NULL;
+    String *classDeclarationName = Getattr(n, "classDeclaration:name");
+
+    /* Deal with inheritance */
+    List *baselist = Getattr(n, "bases");
+    if (baselist != NIL) {
+      Iterator base = First(baselist);
+      c_baseclassname = Getattr(base.item, "name");
+      baseclass = Copy(getProxyName(c_baseclassname));
+      if (baseclass) {
+	c_baseclass = SwigType_namestr(Getattr(base.item, "name"));
+      }
+      base = Next(base);
+      if (base.item != NIL) {
+	Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, input_file,
+		     line_number,
+		     "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Modula 3.\n",
+		     classDeclarationName, Getattr(base.item, "name"));
+      }
+    }
+
+    bool derived = baseclass && getProxyName(c_baseclassname);
+    if (!baseclass)
+      baseclass = NewString("");
+
+    // Inheritance from pure Modula 3 classes
+    const String *pure_baseclass = typemapLookup("m3base", classDeclarationName, WARN_NONE);
+    if (hasContent(pure_baseclass) && hasContent(baseclass)) {
+      Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, input_file,
+		   line_number,
+		   "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Modula 3.\n", classDeclarationName, pure_baseclass);
+    }
+    // Pure Modula 3 interfaces
+    const String *pure_interfaces = typemapLookup(derived ? "m3interfaces_derived" : "m3interfaces",
+						  classDeclarationName, WARN_NONE);
+
+    // Start writing the proxy class
+    Printv(proxy_class_def, typemapLookup("m3imports", classDeclarationName, WARN_NONE),	// Import statements
+	   "\n", typemapLookup("m3classmodifiers", classDeclarationName, WARN_MODULA3_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers
+	   " class $m3classname",	// Class name and bases
+	   (derived || *Char(pure_baseclass) || *Char(pure_interfaces)) ? " : " : "", baseclass, pure_baseclass, ((derived || *Char(pure_baseclass)) && *Char(pure_interfaces)) ?	// Interfaces
+	   ", " : "", pure_interfaces, " {\n", "  private IntPtr swigCPtr;\n",	// Member variables for memory handling
+	   derived ? "" : "  protected bool swigCMemOwn;\n", "\n", "  ", typemapLookup("m3ptrconstructormodifiers", classDeclarationName, WARN_MODULA3_TYPEMAP_PTRCONSTMOD_UNDEF),	// pointer constructor modifiers
+	   " $m3classname(IntPtr cPtr, bool cMemoryOwn) ",	// Constructor used for wrapping pointers
+	   derived ?
+	   ": base($imclassname.$m3classnameTo$baseclass(cPtr), cMemoryOwn) {\n"
+	   : "{\n    swigCMemOwn = cMemoryOwn;\n", "    swigCPtr = cPtr;\n", "  }\n", NIL);
+
+    if (!have_default_constructor_flag) {	// All proxy classes need a constructor
+      Printv(proxy_class_def, "\n", "  protected $m3classname() : this(IntPtr.Zero, false) {\n", "  }\n", NIL);
+    }
+    // C++ destructor is wrapped by the Dispose method
+    // Note that the method name is specified in a typemap attribute called methodname
+    String *destruct = NewString("");
+    const String *tm = NULL;
+    Node *attributes = NewHash();
+    String *destruct_methodname = NULL;
+    if (derived) {
+      tm = typemapLookup("m3destruct_derived", classDeclarationName, WARN_NONE, attributes);
+      destruct_methodname = Getattr(attributes, "tmap:m3destruct_derived:methodname");
+    } else {
+      tm = typemapLookup("m3destruct", classDeclarationName, WARN_NONE, attributes);
+      destruct_methodname = Getattr(attributes, "tmap:m3destruct:methodname");
+    }
+    if (!destruct_methodname) {
+      Swig_error(input_file, line_number, "No methodname attribute defined in m3destruct%s typemap for %s\n", (derived ? "_derived" : ""), proxy_class_name);
+    }
+    // Emit the Finalize and Dispose methods
+    if (tm) {
+      // Finalize method
+      if (*Char(destructor_call)) {
+	Printv(proxy_class_def, typemapLookup("m3finalize", classDeclarationName, WARN_NONE), NIL);
+      }
+      // Dispose method
+      Printv(destruct, tm, NIL);
+      if (*Char(destructor_call))
+	Replaceall(destruct, "$imcall", destructor_call);
+      else
+	Replaceall(destruct, "$imcall", "throw new MethodAccessException(\"C++ destructor does not have public access\")");
+      if (*Char(destruct))
+	Printv(proxy_class_def, "\n  public ", derived ? "override" : "virtual", " void ", destruct_methodname, "() ", destruct, "\n", NIL);
+    }
+    Delete(attributes);
+    Delete(destruct);
+
+    // Emit various other methods
+    Printv(proxy_class_def, typemapLookup("m3getcptr", classDeclarationName, WARN_MODULA3_TYPEMAP_GETCPTR_UNDEF),	// getCPtr method
+	   typemapLookup("m3code", classDeclarationName, WARN_NONE),	// extra Modula 3 code
+	   "\n", NIL);
+
+    // Substitute various strings into the above template
+    Replaceall(proxy_class_def, "$m3classname", proxy_class_name);
+    Replaceall(proxy_class_code, "$m3classname", proxy_class_name);
+
+    Replaceall(proxy_class_def, "$baseclass", baseclass);
+    Replaceall(proxy_class_code, "$baseclass", baseclass);
+
+    Replaceall(proxy_class_def, "$imclassname", m3raw_name);
+    Replaceall(proxy_class_code, "$imclassname", m3raw_name);
+
+    // Add code to do C++ casting to base class (only for classes in an inheritance hierarchy)
+    if (derived) {
+      Printv(m3raw_cppcasts_code, "\n  [DllImport(\"", m3wrap_name, "\", EntryPoint=\"Modula3_", proxy_class_name, "To", baseclass, "\")]\n", NIL);
+      Printv(m3raw_cppcasts_code, "  public static extern IntPtr ", "$m3classnameTo$baseclass(IntPtr objectRef);\n", NIL);
+
+      Replaceall(m3raw_cppcasts_code, "$m3classname", proxy_class_name);
+      Replaceall(m3raw_cppcasts_code, "$baseclass", baseclass);
+
+      Printv(upcasts_code,
+	     "SWIGEXPORT long Modula3_$imclazznameTo$imbaseclass",
+	     "(long objectRef) {\n",
+	     "    long baseptr = 0;\n" "    *($cbaseclass **)&baseptr = *($cclass **)&objectRef;\n" "    return baseptr;\n" "}\n", "\n", NIL);
+
+      Replaceall(upcasts_code, "$imbaseclass", baseclass);
+      Replaceall(upcasts_code, "$cbaseclass", c_baseclass);
+      Replaceall(upcasts_code, "$imclazzname", proxy_class_name);
+      Replaceall(upcasts_code, "$cclass", c_classname);
+    }
+    Delete(baseclass);
+  }
+
+  /* ----------------------------------------------------------------------
+   * getAttrString()
+   *
+   * If necessary create and return the string
+   * associated with a certain attribute of 'n'.
+   * ---------------------------------------------------------------------- */
+
+  String *getAttrString(Node *n, const char *attr) {
+    String *str = Getattr(n, attr);
+    if (str == NIL) {
+      str = NewString("");
+      Setattr(n, attr, str);
+    }
+    return str;
+  }
+
+  /* ----------------------------------------------------------------------
+   * getMethodDeclarations()
+   *
+   * If necessary create and return the handle
+   * where the methods of the current access can be written to.
+   * 'n' must be a member of a struct or a class.
+   * ---------------------------------------------------------------------- */
+
+  String *getMethodDeclarations(Node *n) {
+    String *acc_str = Getattr(n, "access");
+    String *methodattr;
+    if (acc_str == NIL) {
+      methodattr = NewString("modula3:method:public");
+    } else {
+      methodattr = NewStringf("modula3:method:%s", acc_str);
+    }
+    String *methods = getAttrString(parentNode(n), Char(methodattr));
+    Delete(methodattr);
+    return methods;
+  }
+
+  /* ----------------------------------------------------------------------
+   * classHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int classHandler(Node *n) {
+
+    File *f_proxy = NULL;
+    proxy_class_name = Copy(Getattr(n, "sym:name"));
+    //String *rawname = Getattr(n,"name");
+
+    if (proxy_flag) {
+      if (!addSymbol(proxy_class_name, n))
+	return SWIG_ERROR;
+
+      if (Cmp(proxy_class_name, m3raw_name) == 0) {
+	Printf(stderr, "Class name cannot be equal to intermediary class name: %s\n", proxy_class_name);
+	SWIG_exit(EXIT_FAILURE);
+      }
+
+      if (Cmp(proxy_class_name, m3wrap_name) == 0) {
+	Printf(stderr, "Class name cannot be equal to module class name: %s\n", proxy_class_name);
+	SWIG_exit(EXIT_FAILURE);
+      }
+
+      String *filen = NewStringf("%s%s.m3", Swig_file_dirname(outfile), proxy_class_name);
+      f_proxy = NewFile(filen, "w");
+      if (!f_proxy) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Delete(filen);
+      filen = NULL;
+
+      emitBanner(f_proxy);
+
+      Clear(proxy_class_def);
+      Clear(proxy_class_code);
+
+      have_default_constructor_flag = false;
+      destructor_call = NewString("");
+    }
+
+    /* This will invoke memberfunctionHandler, membervariableHandler ...
+       and finally it may invoke functionWrapper
+       for wrappers and member variable accessors.
+       It will invoke Language:constructorDeclaration
+       which decides whether to call MODULA3::constructorHandler */
+    Language::classHandler(n);
+
+    {
+      String *kind = Getattr(n, "kind");
+      if (Cmp(kind, "struct") == 0) {
+	String *entries = NewString("");
+	Node *child;
+	writeArgState state;
+	for (child = firstChild(n); child != NIL; child = nextSibling(child)) {
+	  String *childType = nodeType(child);
+	  if (Strcmp(childType, "cdecl") == 0) {
+	    String *member = Getattr(child, "sym:name");
+	    ParmList *pl = Getattr(child, "parms");
+	    if (pl == NIL) {
+	      // Get the variable type in Modula 3 type equivalents
+	      String *m3ct = getMappedTypeNew(child, "m3rawtype", "");
+
+	      writeArg(entries, state, NIL, member, m3ct, NIL);
+	    }
+	  }
+	}
+	writeArg(entries, state, NIL, NIL, NIL, NIL);
+
+	m3raw_intf.enterBlock(blocktype);
+	Printf(m3raw_intf.f, "%s =\nRECORD\n%sEND;\n", proxy_class_name, entries);
+
+	Delete(entries);
+
+      } else if (Cmp(kind, "class") == 0) {
+	enum access_privilege { acc_public, acc_protected, acc_private };
+	int max_acc = acc_public;
+
+	const char *acc_name[3] = { "public", "protected", "private" };
+	String *methods[3];
+	int acc;
+	for (acc = acc_public; acc <= acc_private; acc++) {
+	  String *methodattr = NewStringf("modula3:method:%s", acc_name[acc]);
+	  methods[acc] = Getattr(n, methodattr);
+	  Delete(methodattr);
+	  max_acc = max_acc > acc ? max_acc : acc;
+	}
+
+	/* Determine the name of the base class */
+	String *baseclassname = NewString("");
+	{
+	  List *baselist = Getattr(n, "bases");
+	  if (baselist) {
+	    /* Look for the first (principal?) base class -
+	       Modula 3 does not support multiple inheritance */
+	    Iterator base = First(baselist);
+	    Append(baseclassname, Getattr(base.item, "sym:name"));
+	    base = Next(base);
+	    if (base.item != NIL) {
+	      Swig_warning(WARN_MODULA3_MULTIPLE_INHERITANCE, input_file,
+			   line_number,
+			   "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Modula 3.\n",
+			   proxy_class_name, Getattr(base.item, "name"));
+	    }
+	  }
+	}
+
+	/* the private class of the base class and only this
+	   need a pointer to the C++ object */
+	bool need_private = !hasContent(baseclassname);
+	max_acc = need_private ? acc_private : max_acc;
+
+	/* Declare C++ object as abstract pointer in Modula 3 */
+	/* The revelation system does not allow us
+	   to imitate the whole class hierarchy of the C++ library,
+	   but at least we can distinguish between classes of different roots. */
+	if (hasContent(baseclassname)) {
+	  m3raw_intf.enterBlock(blocktype);
+	  Printf(m3raw_intf.f, "%s = %s;\n", proxy_class_name, baseclassname);
+	} else {
+	  m3raw_intf.enterBlock(blocktype);
+	  Printf(m3raw_intf.f, "%s <: ADDRESS;\n", proxy_class_name);
+	  m3raw_impl.enterBlock(revelation);
+	  Printf(m3raw_impl.f, "%s = UNTRACED BRANDED REF RECORD (*Dummy*) END;\n", proxy_class_name);
+	}
+
+	String *superclass;
+	m3wrap_intf.enterBlock(blocktype);
+	if (hasContent(methods[acc_public])) {
+	  superclass = NewStringf("%sPublic", proxy_class_name);
+	} else if (hasContent(baseclassname)) {
+	  superclass = Copy(baseclassname);
+	} else {
+	  superclass = NewString("ROOT");
+	}
+	Printf(m3wrap_intf.f, "%s <: %s;\n", proxy_class_name, superclass);
+	Delete(superclass);
+
+	{
+	  static const char *acc_m3suffix[] = { "Public", "Protected", "Private" };
+	  int acc;
+	  for (acc = acc_public; acc <= acc_private; acc++) {
+	    bool process_private = (acc == acc_private) && need_private;
+	    if (hasContent(methods[acc]) || process_private) {
+	      String *subclass = NewStringf("%s%s", proxy_class_name, acc_m3suffix[acc]);
+	      /*
+	         m3wrap_intf.enterBlock(revelation);
+	         Printf(m3wrap_intf.f, "%s <: %s;\n", proxy_class_name, subclass);
+	       */
+	      if (acc == max_acc) {
+		m3wrap_intf.enterBlock(revelation);
+		Printf(m3wrap_intf.f, "%s =\n", proxy_class_name);
+	      } else {
+		m3wrap_intf.enterBlock(blocktype);
+		Printf(m3wrap_intf.f, "%s =\n", subclass);
+	      }
+	      Printf(m3wrap_intf.f, "%s BRANDED OBJECT\n", baseclassname);
+	      if (process_private) {
+		Setattr(m3wrap_intf.import, m3raw_name, "");
+		Printf(m3wrap_intf.f, "cxxObj:%s.%s;\n", m3raw_name, proxy_class_name);
+	      }
+	      if (hasContent(methods[acc])) {
+		Printf(m3wrap_intf.f, "METHODS\n%s", methods[acc]);
+	      }
+	      if (acc == max_acc) {
+		String *overrides = Getattr(n, "modula3:override");
+		Printf(m3wrap_intf.f, "OVERRIDES\n%s", overrides);
+	      }
+	      Printf(m3wrap_intf.f, "END;\n");
+	      Delete(baseclassname);
+	      baseclassname = subclass;
+	    }
+	  }
+	}
+
+	Delete(methods[acc_public]);
+	Delete(methods[acc_protected]);
+	Delete(methods[acc_private]);
+
+      } else {
+	Swig_warning(WARN_MODULA3_TYPECONSTRUCTOR_UNKNOWN, input_file, line_number, "Unknown type constructor %s\n", kind);
+      }
+    }
+
+    if (proxy_flag) {
+
+      emitProxyClassDefAndCPPCasts(n);
+
+      Printv(f_proxy, proxy_class_def, proxy_class_code, NIL);
+
+      Printf(f_proxy, "}\n");
+      Close(f_proxy);
+      f_proxy = NULL;
+
+      Delete(proxy_class_name);
+      proxy_class_name = NULL;
+      Delete(destructor_call);
+      destructor_call = NULL;
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberfunctionHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int memberfunctionHandler(Node *n) {
+    //printf("begin memberfunctionHandler(%s)\n", Char(Getattr(n,"name")));
+    Setattr(n, "modula3:functype", "method");
+    Language::memberfunctionHandler(n);
+
+    {
+      /* Language::memberfunctionHandler will remove the mapped types
+         that emitM3Wrapper may attach */
+      ParmList *pl = Getattr(n, "parms");
+      Swig_typemap_attach_parms("m3wrapinmode", pl, NULL);
+      Swig_typemap_attach_parms("m3wrapinname", pl, NULL);
+      Swig_typemap_attach_parms("m3wrapintype", pl, NULL);
+      Swig_typemap_attach_parms("m3wrapindefault", pl, NULL);
+      attachParameterNames(n, "tmap:m3wrapinname", "autoname", "arg%d");
+      String *rettype = getMappedTypeNew(n, "m3wrapouttype", "");
+
+      String *methodname = Getattr(n, "sym:name");
+/*
+      if (methodname==NIL) {
+        methodname = Getattr(n,"name");
+      }
+*/
+      String *arguments = createM3Signature(n);
+      String *storage = Getattr(n, "storage");
+      String *overridden = Getattr(n, "override");
+      bool isVirtual = (storage != NIL) && (Strcmp(storage, "virtual") == 0);
+      bool isOverridden = (overridden != NIL)
+	  && (Strcmp(overridden, "1") == 0);
+      if ((!isVirtual) || (!isOverridden)) {
+	{
+	  String *methods = getMethodDeclarations(n);
+	  Printf(methods, "%s(%s)%s%s;%s\n",
+		 methodname, arguments,
+		 hasContent(rettype) ? ": " : "", hasContent(rettype) ? (const String *) rettype : "", isVirtual ? "  (* base method *)" : "");
+	}
+	{
+	  /* this was attached by functionWrapper
+	     invoked by Language::memberfunctionHandler */
+	  String *fname = Getattr(n, "modula3:funcname");
+	  String *overrides = getAttrString(parentNode(n), "modula3:override");
+	  Printf(overrides, "%s := %s;\n", methodname, fname);
+	}
+      }
+    }
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *intermediary_function_name = Swig_name_member(proxy_class_name, overloaded_name);
+      Setattr(n, "proxyfuncname", Getattr(n, "sym:name"));
+      Setattr(n, "imfuncname", intermediary_function_name);
+      proxyClassFunctionHandler(n);
+      Delete(overloaded_name);
+    }
+    //printf("end memberfunctionHandler(%s)\n", Char(Getattr(n,"name")));
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+
+    static_flag = true;
+    Language::staticmemberfunctionHandler(n);
+
+    if (proxy_flag) {
+      String *overloaded_name = getOverloadedName(n);
+      String *intermediary_function_name = Swig_name_member(proxy_class_name, overloaded_name);
+      Setattr(n, "proxyfuncname", Getattr(n, "sym:name"));
+      Setattr(n, "imfuncname", intermediary_function_name);
+      proxyClassFunctionHandler(n);
+      Delete(overloaded_name);
+    }
+    static_flag = false;
+
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * proxyClassFunctionHandler()
+   *
+   * Function called for creating a Modula 3 wrapper function around a c++ function in the 
+   * proxy class. Used for both static and non-static C++ class functions.
+   * C++ class static functions map to Modula 3 static functions.
+   * Two extra attributes in the Node must be available. These are "proxyfuncname" - 
+   * the name of the Modula 3 class proxy function, which in turn will call "imfuncname" - 
+   * the intermediary (PInvoke) function name in the intermediary class.
+   * ----------------------------------------------------------------------------- */
+
+  void proxyClassFunctionHandler(Node *n) {
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    Hash *throws_hash = NewHash();
+    String *intermediary_function_name = Getattr(n, "imfuncname");
+    String *proxy_function_name = Getattr(n, "proxyfuncname");
+    String *tm;
+    Parm *p;
+    int i;
+    String *imcall = NewString("");
+    String *return_type = NewString("");
+    String *function_code = NewString("");
+    bool setter_flag = false;
+
+    if (!proxy_flag)
+      return;
+
+    if (l) {
+      if (SwigType_type(Getattr(l, "type")) == T_VOID) {
+	l = nextSibling(l);
+      }
+    }
+
+    /* Attach the non-standard typemaps to the parameter list */
+    Swig_typemap_attach_parms("in", l, NULL);
+    Swig_typemap_attach_parms("m3wraptype", l, NULL);
+    Swig_typemap_attach_parms("m3in", l, NULL);
+
+    /* Get return types */
+    if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) {
+      substituteClassname(t, tm);
+      Printf(return_type, "%s", tm);
+    }
+
+    if (proxy_flag && wrapping_member_flag && !enum_constant_flag) {
+      // Properties
+      setter_flag = (Cmp(Getattr(n, "sym:name"), Swig_name_set(Swig_name_member(proxy_class_name, variable_name)))
+		     == 0);
+    }
+
+    /* Start generating the proxy function */
+    Printf(function_code, "  %s ", Getattr(n, "feature:modula3:methodmodifiers"));
+    if (static_flag)
+      Printf(function_code, "static ");
+    if (Getattr(n, "override"))
+      Printf(function_code, "override ");
+    else if (checkAttribute(n, "storage", "virtual"))
+      Printf(function_code, "virtual ");
+
+    Printf(function_code, "%s %s(", return_type, proxy_function_name);
+
+    Printv(imcall, m3raw_name, ".", intermediary_function_name, "(", NIL);
+    if (!static_flag)
+      Printv(imcall, "swigCPtr", NIL);
+
+    emit_mark_varargs(l);
+
+    int gencomma = !static_flag;
+
+    /* Output each parameter */
+    for (i = 0, p = l; p; i++) {
+
+      /* Ignored varargs */
+      if (checkAttribute(p, "varargs:ignore", "1")) {
+	p = nextSibling(p);
+	continue;
+      }
+
+      /* Ignored parameters */
+      if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      }
+
+      /* Ignore the 'this' argument for variable wrappers */
+      if (!(variable_wrapper_flag && i == 0)) {
+	SwigType *pt = Getattr(p, "type");
+	String *param_type = NewString("");
+
+	/* Get the Modula 3 parameter type */
+	if ((tm = getMappedType(p, "m3wraptype"))) {
+	  substituteClassname(pt, tm);
+	  Printf(param_type, "%s", tm);
+	}
+
+	if (gencomma)
+	  Printf(imcall, ", ");
+
+	String *arg = variable_wrapper_flag ? NewString("value") : makeParameterName(n,
+										     p,
+										     i);
+
+	// Use typemaps to transform type used in Modula 3 wrapper function (in proxy class) to type used in PInvoke function (in intermediary class)
+	if ((tm = getMappedType(p, "in"))) {
+	  addThrows(throws_hash, "in", p);
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$input", arg);
+	  Printv(imcall, tm, NIL);
+	}
+
+	/* Add parameter to proxy function */
+	if (gencomma >= 2)
+	  Printf(function_code, ", ");
+	gencomma = 2;
+	Printf(function_code, "%s %s", param_type, arg);
+
+	Delete(arg);
+	Delete(param_type);
+      }
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    Printf(imcall, ")");
+    Printf(function_code, ")");
+
+    // Transform return type used in PInvoke function (in intermediary class) to type used in Modula 3 wrapper function (in proxy class)
+    if ((tm = getMappedTypeNew(n, "m3out", ""))) {
+      addThrows(throws_hash, "m3out", n);
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "true");
+      else
+	Replaceall(tm, "$owner", "false");
+      substituteClassname(t, tm);
+      Replaceall(tm, "$imcall", imcall);
+    }
+
+    generateThrowsClause(throws_hash, function_code);
+    Printf(function_code, " %s\n\n", tm ? (const String *) tm : empty_string);
+
+    if (proxy_flag && wrapping_member_flag && !enum_constant_flag) {
+      // Properties
+      if (setter_flag) {
+	// Setter method
+	if ((tm = getMappedTypeNew(n, "m3varin", ""))) {
+	  if (GetFlag(n, "feature:new"))
+	    Replaceall(tm, "$owner", "true");
+	  else
+	    Replaceall(tm, "$owner", "false");
+	  substituteClassname(t, tm);
+	  Replaceall(tm, "$imcall", imcall);
+	  Printf(proxy_class_code, "%s", tm);
+	}
+      } else {
+	// Getter method
+	if ((tm = getMappedTypeNew(n, "m3varout", ""))) {
+	  if (GetFlag(n, "feature:new"))
+	    Replaceall(tm, "$owner", "true");
+	  else
+	    Replaceall(tm, "$owner", "false");
+	  substituteClassname(t, tm);
+	  Replaceall(tm, "$imcall", imcall);
+	  Printf(proxy_class_code, "%s", tm);
+	}
+      }
+    } else {
+      // Normal function call
+      Printv(proxy_class_code, function_code, NIL);
+    }
+
+    Delete(function_code);
+    Delete(return_type);
+    Delete(imcall);
+    Delete(throws_hash);
+  }
+
+  /* ----------------------------------------------------------------------
+   * constructorHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int constructorHandler(Node *n) {
+    // this invokes functionWrapper
+    Language::constructorHandler(n);
+
+    if (proxy_flag) {
+      ParmList *l = Getattr(n, "parms");
+
+      Hash *throws_hash = NewHash();
+      String *overloaded_name = getOverloadedName(n);
+      String *imcall = NewString("");
+
+      Printf(proxy_class_code, "  %s %s(", Getattr(n, "feature:modula3:methodmodifiers"), proxy_class_name);
+      Printv(imcall, " : this(", m3raw_name, ".", Swig_name_construct(overloaded_name), "(", NIL);
+
+      /* Attach the non-standard typemaps to the parameter list */
+      Swig_typemap_attach_parms("in", l, NULL);
+      Swig_typemap_attach_parms("m3wraptype", l, NULL);
+      Swig_typemap_attach_parms("m3in", l, NULL);
+
+      emit_mark_varargs(l);
+
+      int gencomma = 0;
+
+      String *tm;
+      Parm *p = l;
+      int i;
+
+      /* Output each parameter */
+      for (i = 0; p; i++) {
+
+	/* Ignored varargs */
+	if (checkAttribute(p, "varargs:ignore", "1")) {
+	  p = nextSibling(p);
+	  continue;
+	}
+
+	/* Ignored parameters */
+	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	  p = Getattr(p, "tmap:in:next");
+	  continue;
+	}
+
+	SwigType *pt = Getattr(p, "type");
+	String *param_type = NewString("");
+
+	/* Get the Modula 3 parameter type */
+	if ((tm = getMappedType(p, "m3wraptype"))) {
+	  substituteClassname(pt, tm);
+	  Printf(param_type, "%s", tm);
+	}
+
+	if (gencomma)
+	  Printf(imcall, ", ");
+
+	String *arg = makeParameterName(n, p, i);
+
+	// Use typemaps to transform type used in Modula 3 wrapper function (in proxy class) to type used in PInvoke function (in intermediary class)
+	if ((tm = getMappedType(p, "in"))) {
+	  addThrows(throws_hash, "in", p);
+	  substituteClassname(pt, tm);
+	  Replaceall(tm, "$input", arg);
+	  Printv(imcall, tm, NIL);
+	}
+
+	/* Add parameter to proxy function */
+	if (gencomma)
+	  Printf(proxy_class_code, ", ");
+	Printf(proxy_class_code, "%s %s", param_type, arg);
+	gencomma = 1;
+
+	Delete(arg);
+	Delete(param_type);
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      Printf(imcall, "), true)");
+
+      Printf(proxy_class_code, ")");
+      Printf(proxy_class_code, "%s", imcall);
+      generateThrowsClause(throws_hash, proxy_class_code);
+      Printf(proxy_class_code, " {\n");
+      Printf(proxy_class_code, "  }\n\n");
+
+      if (!gencomma)		// We must have a default constructor
+	have_default_constructor_flag = true;
+
+      Delete(overloaded_name);
+      Delete(imcall);
+      Delete(throws_hash);
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * destructorHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int destructorHandler(Node *n) {
+    Language::destructorHandler(n);
+    String *symname = Getattr(n, "sym:name");
+
+    if (proxy_flag) {
+      Printv(destructor_call, m3raw_name, ".", Swig_name_destroy(symname), "(swigCPtr)", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * membervariableHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int membervariableHandler(Node *n) {
+    //printf("begin membervariableHandler(%s)\n", Char(Getattr(n,"name")));
+    SwigType *t = Getattr(n, "type");
+    String *tm;
+
+    // Get the variable type
+    if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) {
+      substituteClassname(t, tm);
+    }
+
+    variable_name = Getattr(n, "sym:name");
+    //printf("member variable: %s\n", Char(variable_name));
+
+    // Output the property's field declaration and accessor methods
+    Printf(proxy_class_code, "  public %s %s {", tm, variable_name);
+
+    Setattr(n, "modula3:functype", "accessor");
+    wrapping_member_flag = true;
+    variable_wrapper_flag = true;
+    Language::membervariableHandler(n);
+    wrapping_member_flag = false;
+    variable_wrapper_flag = false;
+
+    Printf(proxy_class_code, "\n  }\n\n");
+
+    {
+      String *methods = getMethodDeclarations(n);
+      String *overrides = getAttrString(parentNode(n), "modula3:override");
+      SwigType *type = Getattr(n, "type");
+      String *m3name = capitalizeFirst(variable_name);
+      //String *m3name    = nameToModula3(variable_name,true);
+      if (!SwigType_isconst(type)) {
+	{
+	  String *inmode = getMappedTypeNew(n, "m3wrapinmode", "", false);
+	  String *intype = getMappedTypeNew(n, "m3wrapintype", "");
+	  Printf(methods, "set%s(%s val:%s);\n", m3name, (inmode != NIL) ? (const String *) inmode : "", intype);
+	}
+	{
+	  /* this was attached by functionWrapper
+	     invoked by Language::memberfunctionHandler */
+	  String *fname = Getattr(n, "modula3:setname");
+	  Printf(overrides, "set%s := %s;\n", m3name, fname);
+	}
+      }
+      {
+	{
+	  String *outtype = getMappedTypeNew(n, "m3wrapouttype", "");
+	  Printf(methods, "get%s():%s;\n", m3name, outtype);
+	}
+	{
+	  /* this was attached by functionWrapper
+	     invoked by Language::memberfunctionHandler */
+	  String *fname = Getattr(n, "modula3:getname");
+	  Printf(overrides, "get%s := %s;\n", m3name, fname);
+	}
+      }
+      Delete(m3name);
+    }
+    //printf("end membervariableHandler(%s)\n", Char(Getattr(n,"name")));
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * staticmembervariableHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmembervariableHandler(Node *n) {
+
+    bool static_const_member_flag = (Getattr(n, "value") == 0);
+    if (static_const_member_flag) {
+      SwigType *t = Getattr(n, "type");
+      String *tm;
+
+      // Get the variable type
+      if ((tm = getMappedTypeNew(n, "m3wraptype", ""))) {
+	substituteClassname(t, tm);
+      }
+      // Output the property's field declaration and accessor methods
+      Printf(proxy_class_code, "  public static %s %s {", tm, Getattr(n, "sym:name"));
+    }
+
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    static_flag = true;
+    Language::staticmembervariableHandler(n);
+    wrapping_member_flag = false;
+    static_flag = false;
+
+    if (static_const_member_flag)
+      Printf(proxy_class_code, "\n  }\n\n");
+
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberconstantHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int memberconstantHandler(Node *n) {
+    variable_name = Getattr(n, "sym:name");
+    wrapping_member_flag = true;
+    Language::memberconstantHandler(n);
+    wrapping_member_flag = false;
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * getOverloadedName()
+   * ----------------------------------------------------------------------------- */
+
+  String *getOverloadedName(Node *n) {
+    String *overloaded_name = Copy(Getattr(n, "sym:name"));
+
+    if (Getattr(n, "sym:overloaded")) {
+      Printv(overloaded_name, Getattr(n, "sym:overname"), NIL);
+    }
+
+    return overloaded_name;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitM3Wrapper()
+   * It is also used for set and get methods of global variables.
+   * ----------------------------------------------------------------------------- */
+
+  void emitM3Wrapper(Node *n, const String *func_name) {
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    Hash *throws_hash = NewHash();
+    int num_exceptions = 0;
+    int num_returns = 0;
+    String *rawcall = NewString("");
+    String *reccall = NewString("");
+    String *local_variables = NewString("");
+    String *local_constants = NewString("");
+    String *incheck = NewString("");
+    String *outcheck = NewString("");
+    String *setup = NewString("");
+    String *cleanup = NewString("");
+    String *outarg = NewString("");	/* don't mix up with 'autark' :-] */
+    String *storeout = NewString("");
+    String *result_name = NewString("");
+    String *return_variables = NewString("");
+    const char *result_return = "ret";
+    String *function_code = NewString("");
+    /*several names for the same function */
+    String *raw_name = Getattr(n, "name");	/*original C function name */
+    //String     *func_name = Getattr(n,"sym:name");  /*final Modula3 name chosen by the user*/
+    bool setter_flag = false;
+    int multiretval = GetFlag(n, "feature:modula3:multiretval");
+
+    if (l) {
+      if (SwigType_type(Getattr(l, "type")) == T_VOID) {
+	l = nextSibling(l);
+      }
+    }
+
+    /* Attach the non-standard typemaps to the parameter list */
+    Swig_typemap_attach_parms("m3wrapargvar", l, NULL);
+    Swig_typemap_attach_parms("m3wrapargconst", l, NULL);
+    Swig_typemap_attach_parms("m3wrapargraw", l, NULL);
+    Swig_typemap_attach_parms("m3wrapargdir", l, NULL);
+    Swig_typemap_attach_parms("m3wrapinmode", l, NULL);
+    Swig_typemap_attach_parms("m3wrapinname", l, NULL);
+    Swig_typemap_attach_parms("m3wrapintype", l, NULL);
+    Swig_typemap_attach_parms("m3wrapindefault", l, NULL);
+    Swig_typemap_attach_parms("m3wrapinconv", l, NULL);
+    Swig_typemap_attach_parms("m3wrapincheck", l, NULL);
+    Swig_typemap_attach_parms("m3wrapoutname", l, NULL);
+    Swig_typemap_attach_parms("m3wrapouttype", l, NULL);
+    Swig_typemap_attach_parms("m3wrapoutconv", l, NULL);
+    Swig_typemap_attach_parms("m3wrapoutcheck", l, NULL);
+
+    attachMappedType(n, "m3wrapretraw");
+    attachMappedType(n, "m3wrapretname");
+    attachMappedType(n, "m3wraprettype");
+    attachMappedType(n, "m3wrapretvar");
+    attachMappedType(n, "m3wrapretconv");
+    attachMappedType(n, "m3wrapretcheck");
+
+    Swig_typemap_attach_parms("m3wrapfreearg", l, NULL);
+
+/*
+    Swig_typemap_attach_parms("m3wrapargvar:throws", l, NULL);
+    Swig_typemap_attach_parms("m3wrapargraw:throws", l, NULL);
+    Swig_typemap_attach_parms("m3wrapinconv:throws", l, NULL);
+    Swig_typemap_attach_parms("m3wrapincheck:throws", l, NULL);
+    Swig_typemap_attach_parms("m3wrapoutconv:throws", l, NULL);
+    Swig_typemap_attach_parms("m3wrapoutcheck:throws", l, NULL);
+
+    attachMappedType(n, "m3wrapretvar:throws");
+    attachMappedType(n, "m3wrapretconv:throws");
+    attachMappedType(n, "m3wrapretcheck:throws");
+
+    Swig_typemap_attach_parms("m3wrapfreearg:throws", l, NULL);
+*/
+
+    /* Attach argument names to the parameter list */
+    /* should be a separate procedure making use of hashes */
+    attachParameterNames(n, "tmap:m3wrapinname", "autoname", "arg%d");
+
+    /* Get return types */
+    String *result_m3rawtype = Copy(getMappedTypeNew(n, "m3rawrettype", ""));
+    String *result_m3wraptype = Copy(getMappedTypeNew(n, "m3wraprettype", ""));
+    bool has_return_raw = hasContent(result_m3rawtype);
+    bool has_return_m3 = hasContent(result_m3wraptype);
+    if (has_return_m3) {
+      num_returns++;
+      //printf("%s: %s\n", Char(func_name),Char(result_m3wraptype));
+    }
+
+    String *arguments = createM3Signature(n);
+
+    /* Create local variables or RECORD fields for return values
+       and determine return type that might result from a converted VAR argument. */
+    {
+      writeArgState state;
+      if (multiretval && has_return_m3) {
+	writeArg(return_variables, state, NIL, NewString(result_return), result_m3wraptype, NIL);
+      }
+
+      Parm *p = skipIgnored(l, "m3wrapouttype");
+      while (p != NIL) {
+
+	String *arg = Getattr(p, "tmap:m3wrapoutname");
+	if (arg == NIL) {
+	  arg = Getattr(p, "name");
+	}
+
+	String *tm = Getattr(p, "tmap:m3wrapouttype");
+	if (tm != NIL) {
+	  if (isOutParam(p)) {
+	    if (!multiretval) {
+	      if (num_returns == 0) {
+		Printv(result_name, arg, NIL);
+		Clear(result_m3wraptype);
+		Printv(result_m3wraptype, tm, NIL);
+	      } else {
+		Swig_warning(WARN_MODULA3_TYPEMAP_MULTIPLE_RETURN,
+			     input_file, line_number,
+			     "Typemap m3wrapargdir set to 'out' for %s implies a RETURN value, but the routine %s has already one.\nUse %%multiretval feature.\n",
+			     SwigType_str(Getattr(p, "type"), 0), raw_name);
+	      }
+	    }
+	    num_returns++;
+	    addImports(m3wrap_intf.import, "m3wrapouttype", p);
+	    writeArg(return_variables, state, NIL, arg, tm, NIL);
+	  }
+	  p = skipIgnored(Getattr(p, "tmap:m3wrapouttype:next"), "m3wrapouttype");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+      writeArg(return_variables, state, NIL, NIL, NIL, NIL);
+
+      if (multiretval) {
+	Printv(result_name, "result", NIL);
+	Printf(result_m3wraptype, "%sResult", func_name);
+	m3wrap_intf.enterBlock(blocktype);
+	Printf(m3wrap_intf.f, "%s =\nRECORD\n%sEND;\n", result_m3wraptype, return_variables);
+	Printf(local_variables, "%s: %s;\n", result_name, result_m3wraptype);
+      } else {
+	Append(local_variables, return_variables);
+      }
+    }
+
+    /* Declare local constants e.g. for storing argument names. */
+    {
+      Parm *p = l;
+      while (p != NIL) {
+
+	String *arg = Getattr(p, "autoname");
+
+	String *tm = Getattr(p, "tmap:m3wrapargconst");
+	if (tm != NIL) {
+	  addImports(m3wrap_impl.import, "m3wrapargconst", p);
+	  Replaceall(tm, "$input", arg);
+	  Printv(local_constants, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:m3wrapargconst:next");
+	} else {
+	  p = nextSibling(p);
+	}
+
+      }
+    }
+
+    /* Declare local variables e.g. for converted input values. */
+    {
+      String *tm = getMappedTypeNew(n, "m3wrapretvar", "", false);
+      if (tm != NIL) {
+	addImports(m3wrap_impl.import, "m3wrapretvar", n);
+	addThrows(throws_hash, "m3wrapretvar", n);
+	Printv(local_variables, tm, "\n", NIL);
+      }
+
+      Parm *p = l;
+      while (p != NIL) {
+
+	String *arg = Getattr(p, "autoname");
+
+	tm = Getattr(p, "tmap:m3wrapargvar");
+	if (tm != NIL) {
+	  /* exceptions that may be raised but can't be catched,
+	     thus we won't count them in num_exceptions */
+	  addImports(m3wrap_impl.import, "m3wrapargvar", p);
+	  addThrows(throws_hash, "m3wrapargvar", p);
+	  Replaceall(tm, "$input", arg);
+	  Printv(local_variables, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:m3wrapargvar:next");
+	} else {
+	  p = nextSibling(p);
+	}
+
+      }
+    }
+
+    /* Convert input values from Modula 3 to C. */
+    {
+      Parm *p = l;
+      while (p != NIL) {
+
+	String *arg = Getattr(p, "autoname");
+
+	String *tm = Getattr(p, "tmap:m3wrapinconv");
+	if (tm != NIL) {
+	  addImports(m3wrap_impl.import, "m3wrapinconv", p);
+	  num_exceptions += addThrows(throws_hash, "m3wrapinconv", p);
+	  Replaceall(tm, "$input", arg);
+	  Printv(setup, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:m3wrapinconv:next");
+	} else {
+	  p = nextSibling(p);
+	}
+
+      }
+    }
+
+    /* Generate checks for input value integrity. */
+    {
+      Parm *p = l;
+      while (p != NIL) {
+
+	String *arg = Getattr(p, "autoname");
+
+	String *tm = Getattr(p, "tmap:m3wrapincheck");
+	if (tm != NIL) {
+	  addImports(m3wrap_impl.import, "m3wrapincheck", p);
+	  num_exceptions += addThrows(throws_hash, "m3wrapincheck", p);
+	  Replaceall(tm, "$input", arg);
+	  Printv(incheck, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:m3wrapincheck:next");
+	} else {
+	  p = nextSibling(p);
+	}
+
+      }
+    }
+
+    Printv(rawcall, m3raw_name, ".", func_name, "(", NIL);
+    /* Arguments to the raw C function */
+    {
+      bool gencomma = false;
+      Parm *p = l;
+      while (p != NIL) {
+	if (gencomma) {
+	  Printf(rawcall, ", ");
+	}
+	gencomma = true;
+	addImports(m3wrap_impl.import, "m3wrapargraw", p);
+	num_exceptions += addThrows(throws_hash, "m3wrapargraw", p);
+
+	String *arg = Getattr(p, "autoname");
+	String *qualarg = NewString("");
+	if (!isInParam(p)) {
+	  String *tmparg = Getattr(p, "tmap:m3wrapoutname");
+	  if (tmparg != NIL) {
+	    arg = tmparg;
+	  }
+	  if (multiretval /*&& isOutParam(p) - automatically fulfilled */ ) {
+	    Printf(qualarg, "%s.", result_name);
+	  }
+	}
+	Append(qualarg, arg);
+	Setattr(p, "m3outarg", qualarg);
+
+	String *tm = Getattr(p, "tmap:m3wrapargraw");
+	if (tm != NIL) {
+	  Replaceall(tm, "$input", arg);
+	  Replaceall(tm, "$output", qualarg);
+	  Printv(rawcall, tm, NIL);
+	  p = Getattr(p, "tmap:m3wrapargraw:next");
+	} else {
+	  //Printv(rawcall, Getattr(p,"lname"), NIL);
+	  Printv(rawcall, qualarg, NIL);
+	  p = nextSibling(p);
+	}
+	Delete(qualarg);
+      }
+    }
+    Printf(rawcall, ")");
+
+    /* Check for error codes and integrity of results */
+    {
+      String *tm = getMappedTypeNew(n, "m3wrapretcheck", "", false);
+      if (tm != NIL) {
+	addImports(m3wrap_impl.import, "m3wrapretcheck", n);
+	num_exceptions += addThrows(throws_hash, "m3wrapretcheck", n);
+	Printv(outcheck, tm, "\n", NIL);
+      }
+
+      Parm *p = l;
+      while (p != NIL) {
+	tm = Getattr(p, "tmap:m3wrapoutcheck");
+	if (tm != NIL) {
+	  String *arg = Getattr(p, "autoname");
+	  String *outarg = Getattr(p, "m3outarg");
+	  addImports(m3wrap_impl.import, "m3wrapoutcheck", p);
+	  num_exceptions += addThrows(throws_hash, "m3wrapoutcheck", p);
+	  //substituteClassname(Getattr(p,"type"), tm);
+	  Replaceall(tm, "$input", arg);
+	  Replaceall(tm, "$output", outarg);
+	  Printv(outcheck, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:m3wrapoutcheck:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    /* Convert the results to Modula 3 data structures and
+       put them in the record prepared for returning */
+    {
+      /* m3wrapretconv is processed
+         when it is clear if there is some output conversion and checking code */
+      Parm *p = l;
+      while (p != NIL) {
+	String *tm = Getattr(p, "tmap:m3wrapoutconv");
+	if (tm != NIL) {
+	  String *arg = Getattr(p, "autoname");
+	  String *outarg = Getattr(p, "m3outarg");
+	  addImports(m3wrap_impl.import, "m3wrapoutconv", n);
+	  num_exceptions += addThrows(throws_hash, "m3wrapoutconv", p);
+	  //substituteClassname(Getattr(p,"type"), tm);
+	  Replaceall(tm, "$input", arg);
+	  Replaceall(tm, "$output", outarg);
+	  Printf(storeout, "%s := %s;\n", outarg, tm);
+	  p = Getattr(p, "tmap:m3wrapoutconv:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    /* Generate cleanup code */
+    {
+      Parm *p = l;
+      while (p != NIL) {
+	String *tm = Getattr(p, "tmap:m3wrapfreearg");
+	if (tm != NIL) {
+	  String *arg = Getattr(p, "autoname");
+	  String *outarg = Getattr(p, "m3outarg");
+	  addImports(m3wrap_impl.import, "m3wrapfreearg", p);
+	  num_exceptions += addThrows(throws_hash, "m3wrapfreearg", p);
+	  //substituteClassname(Getattr(p,"type"), tm);
+	  Replaceall(tm, "$input", arg);
+	  Replaceall(tm, "$output", outarg);
+	  Printv(cleanup, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:m3wrapfreearg:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+    }
+
+    {
+      /* Currently I don't know how a typemap similar to the original 'out' typemap
+         could help returning the return value. */
+      /* Receive result from call to raw library function */
+      if (!has_return_raw) {
+	/*
+	   rawcall(arg1);
+	   result.val := arg1;
+	   RETURN result;
+	 */
+	/*
+	   rawcall(arg1);
+	   RETURN arg1;
+	 */
+	Printf(reccall, "%s;\n", rawcall);
+
+	if (hasContent(result_name)) {
+	  Printf(outarg, "RETURN %s;\n", result_name);
+	}
+      } else {
+	/*
+	   arg0 := rawcall(arg1);
+	   result.ret := Convert(arg0);
+	   result.val := arg1;
+	   RETURN result;
+	 */
+	/*
+	   arg0 := rawcall();
+	   RETURN Convert(arg0);
+	 */
+	/*
+	   RETURN rawcall();
+	 */
+	String *return_raw = getMappedTypeNew(n, "m3wrapretraw", "", false);
+	String *return_conv = getMappedTypeNew(n, "m3wrapretconv", "", false);
+
+	/* immediate RETURN would skip result checking */
+	if ((hasContent(outcheck) || hasContent(storeout)
+	     || hasContent(cleanup)) && (!hasContent(result_name))
+	    && (return_raw == NIL)) {
+	  Printv(result_name, "result", NIL);
+	  Printf(local_variables, "%s: %s;\n", result_name, result_m3wraptype);
+	}
+
+	String *result_lvalue = Copy(result_name);
+	if (multiretval) {
+	  Printf(result_lvalue, ".%s", result_return);
+	}
+	if (return_raw != NIL) {
+	  Printf(reccall, "%s := %s;\n", return_raw, rawcall);
+	} else if (hasContent(result_name)) {
+	  Printf(reccall, "%s := %s;\n", result_lvalue, rawcall);
+	} else {
+	  Printf(outarg, "RETURN %s;\n", rawcall);
+	}
+	if (return_conv != NIL) {
+	  addImports(m3wrap_impl.import, "m3wrapretconv", n);
+	  num_exceptions += addThrows(throws_hash, "m3wrapretconv", n);
+	  if (hasContent(result_name)) {
+	    Printf(reccall, "%s := %s;\n", result_lvalue, return_conv);
+	    Printf(outarg, "RETURN %s;\n", result_name);
+	  } else {
+	    Printf(outarg, "RETURN %s;\n", return_conv);
+	  }
+	} else {
+	  if (hasContent(result_name)) {
+	    Printf(outarg, "RETURN %s;\n", result_name);
+	  }
+	}
+      }
+    }
+
+    /* Create procedure header */
+    {
+      String *header = NewStringf("PROCEDURE %s (%s)",
+				  func_name, arguments);
+
+      if ((num_returns > 0) || multiretval) {
+	Printf(header, ": %s", result_m3wraptype);
+      }
+      generateThrowsClause(throws_hash, header);
+
+      Append(function_code, header);
+
+      m3wrap_intf.enterBlock(no_block);
+      Printf(m3wrap_intf.f, "%s;\n\n", header);
+    }
+
+    {
+      String *body = NewStringf("%s%s%s%s%s",
+				incheck,
+				setup,
+				reccall,
+				outcheck,
+				storeout);
+
+      String *exc_handler;
+      if (hasContent(cleanup) && (num_exceptions > 0)) {
+	exc_handler = NewStringf("TRY\n%sFINALLY\n%sEND;\n", body, cleanup);
+      } else {
+	exc_handler = NewStringf("%s%s", body, cleanup);
+      }
+
+      Printf(function_code, " =\n%s%s%s%sBEGIN\n%s%sEND %s;\n\n",
+	     hasContent(local_constants) ? "CONST\n" : "", local_constants,
+	     hasContent(local_variables) ? "VAR\n" : "", local_variables, exc_handler, outarg, func_name);
+
+      Delete(exc_handler);
+      Delete(body);
+    }
+
+    m3wrap_impl.enterBlock(no_block);
+    if (proxy_flag && global_variable_flag) {
+      // Properties
+      if (setter_flag) {
+	// Setter method
+	String *tm = getMappedTypeNew(n, "m3varin", "");
+	if (tm != NIL) {
+	  if (GetFlag(n, "feature:new")) {
+	    Replaceall(tm, "$owner", "true");
+	  } else {
+	    Replaceall(tm, "$owner", "false");
+	  }
+	  substituteClassname(t, tm);
+	  Replaceall(tm, "$rawcall", rawcall);
+	  Replaceall(tm, "$vartype", variable_type);	/* $type is already replaced by some super class */
+	  Replaceall(tm, "$var", variable_name);
+	  Printf(m3wrap_impl.f, "%s", tm);
+	}
+      } else {
+	// Getter method
+	String *tm = getMappedTypeNew(n, "m3varout", "");
+	if (tm != NIL) {
+	  if (GetFlag(n, "feature:new"))
+	    Replaceall(tm, "$owner", "true");
+	  else
+	    Replaceall(tm, "$owner", "false");
+	  substituteClassname(t, tm);
+	  Replaceall(tm, "$rawcall", rawcall);
+	  Replaceall(tm, "$vartype", variable_type);
+	  Replaceall(tm, "$var", variable_name);
+	  Printf(m3wrap_impl.f, "%s", tm);
+	}
+      }
+    } else {
+      // Normal function call
+      Printv(m3wrap_impl.f, function_code, NIL);
+    }
+
+    Delete(arguments);
+    Delete(return_variables);
+    Delete(local_variables);
+    Delete(local_constants);
+    Delete(outarg);
+    Delete(incheck);
+    Delete(outcheck);
+    Delete(setup);
+    Delete(cleanup);
+    Delete(storeout);
+    Delete(function_code);
+    Delete(result_name);
+    Delete(result_m3wraptype);
+    Delete(reccall);
+    Delete(rawcall);
+    Delete(throws_hash);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * substituteClassname()
+   *
+   * Substitute $m3classname with the proxy class name for classes/structs/unions that SWIG knows about.
+   * Otherwise use the $descriptor name for the Modula 3 class name. Note that the $&m3classname substitution
+   * is the same as a $&descriptor substitution, ie one pointer added to descriptor name.
+   * Inputs:
+   *   pt - parameter type
+   *   tm - m3wraptype typemap
+   * Outputs:
+   *   tm - m3wraptype typemap with $m3classname substitution
+   * Return:
+   *   substitution_performed - flag indicating if a substitution was performed
+   * ----------------------------------------------------------------------------- */
+
+  bool substituteClassname(SwigType *pt, String *tm) {
+    bool substitution_performed = false;
+    if (Strstr(tm, "$m3classname") || Strstr(tm, "$&m3classname")) {
+      String *classname = getProxyName(pt);
+      if (classname) {
+	Replaceall(tm, "$&m3classname", classname);	// getProxyName() works for pointers to classes too
+	Replaceall(tm, "$m3classname", classname);
+      } else {			// use $descriptor if SWIG does not know anything about this type. Note that any typedefs are resolved.
+	String *descriptor = NULL;
+	SwigType *type = Copy(SwigType_typedef_resolve_all(pt));
+
+	if (Strstr(tm, "$&m3classname")) {
+	  SwigType_add_pointer(type);
+	  descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(type));
+	  Replaceall(tm, "$&m3classname", descriptor);
+	} else {		// $m3classname
+	  descriptor = NewStringf("SWIGTYPE%s", SwigType_manglestr(type));
+	  Replaceall(tm, "$m3classname", descriptor);
+	}
+
+	// Add to hash table so that the type wrapper classes can be created later
+	Setattr(swig_types_hash, descriptor, type);
+	Delete(descriptor);
+	Delete(type);
+      }
+      substitution_performed = true;
+    }
+    return substitution_performed;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * makeParameterName()
+   *
+   * Inputs: 
+   *   n - Node
+   *   p - parameter node
+   *   arg_num - parameter argument number
+   * Return:
+   *   arg - a unique parameter name
+   * ----------------------------------------------------------------------------- */
+
+  String *makeParameterName(Node *n, Parm *p, int arg_num) {
+
+    // Use C parameter name unless it is a duplicate or an empty parameter name
+    String *pn = Getattr(p, "name");
+    int count = 0;
+    ParmList *plist = Getattr(n, "parms");
+    while (plist) {
+      if ((Cmp(pn, Getattr(plist, "name")) == 0))
+	count++;
+      plist = nextSibling(plist);
+    }
+    String *arg = (!pn || (count > 1)) ? NewStringf("arg%d",
+						    arg_num) : Copy(Getattr(p,
+									    "name"));
+
+    return arg;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * attachParameterNames()
+   *
+   * Inputs: 
+   *   n      - Node of a function declaration
+   *   tmid   - attribute name for overriding C argument names,
+   *              e.g. "tmap:m3wrapinname",
+   *              don't forget to attach the mapped types before
+   *   nameid - attribute for attaching the names,
+   *              e.g. "modula3:inname"
+   *   fmt    - format for the argument name containing %d
+   *              e.g. "arg%d"
+   * ----------------------------------------------------------------------------- */
+
+  void attachParameterNames(Node *n, const char *tmid, const char *nameid, const char *fmt) {
+    /* Use C parameter name if present and unique,
+       otherwise create an 'arg%d' name */
+    Hash *hash = NewHash();
+    Parm *p = Getattr(n, "parms");
+    int count = 0;
+    while (p != NIL) {
+      String *name = Getattr(p, tmid);
+      if (name == NIL) {
+	name = Getattr(p, "name");
+      }
+      String *newname;
+      if ((!hasContent(name)) || (Getattr(hash, name) != NIL)) {
+	newname = NewStringf(fmt, count);
+      } else {
+	newname = Copy(name);
+      }
+      if (1 == Setattr(hash, newname, "1")) {
+	Swig_warning(WARN_MODULA3_DOUBLE_ID, input_file, line_number, "Argument '%s' twice.\n", newname);
+      }
+      Setattr(p, nameid, newname);
+//      Delete(newname);
+      p = nextSibling(p);
+      count++;
+    }
+    Delete(hash);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * createM3Signature()
+   *
+   * Create signature of M3 wrapper procedure
+   * Call attachParameterNames and attach mapped types before!
+   *   m3wrapintype, m3wrapinmode, m3wrapindefault
+   * ----------------------------------------------------------------------------- */
+
+  String *createM3Signature(Node *n) {
+    String *arguments = NewString("");
+    Parm *p = skipIgnored(Getattr(n, "parms"), "m3wrapintype");
+    writeArgState state;
+    while (p != NIL) {
+
+      /* Get the M3 parameter type */
+      String *tm = getMappedType(p, "m3wrapintype");
+      if (tm != NIL) {
+	if (isInParam(p)) {
+	  addImports(m3wrap_intf.import, "m3wrapintype", p);
+	  addImports(m3wrap_impl.import, "m3wrapintype", p);
+	  String *mode = Getattr(p, "tmap:m3wrapinmode");
+	  String *deflt = Getattr(p, "tmap:m3wrapindefault");
+	  String *arg = Getattr(p, "autoname");
+	  SwigType *pt = Getattr(p, "type");
+	  substituteClassname(pt, tm);	/* do we need this ? */
+
+	  writeArg(arguments, state, mode, arg, tm, deflt);
+	}
+	p = skipIgnored(Getattr(p, "tmap:m3wrapintype:next"), "m3wrapintype");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+    writeArg(arguments, state, NIL, NIL, NIL, NIL);
+    return (arguments);
+  }
+
+/* not used any longer
+    - try SwigType_str if required again */
+#if 0
+  /* -----------------------------------------------------------------------------
+   * createCSignature()
+   *
+   * Create signature of C function
+   * ----------------------------------------------------------------------------- */
+
+  String *createCSignature(Node *n) {
+    String *arguments = NewString("");
+    bool gencomma = false;
+    Node *p;
+    for (p = Getattr(n, "parms"); p != NIL; p = nextSibling(p)) {
+      if (gencomma) {
+	Append(arguments, ",");
+      }
+      gencomma = true;
+      String *type = Getattr(p, "type");
+      String *ctype = getMappedTypeNew(type, "ctype");
+      Append(arguments, ctype);
+    }
+    return arguments;
+  }
+#endif
+
+  /* -----------------------------------------------------------------------------
+   * emitTypeWrapperClass()
+   * ----------------------------------------------------------------------------- */
+
+  void emitTypeWrapperClass(String *classname, SwigType *type) {
+    String *filen = NewStringf("%s%s.m3", Swig_file_dirname(outfile), classname);
+    File *f_swigtype = NewFile(filen, "w");
+    if (!f_swigtype) {
+      FileErrorDisplay(filen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    String *swigtype = NewString("");
+
+    // Emit banner name
+    emitBanner(f_swigtype);
+
+    // Pure Modula 3 baseclass and interfaces
+    const String *pure_baseclass = typemapLookup("m3base", type, WARN_NONE);
+    const String *pure_interfaces = typemapLookup("m3interfaces", type, WARN_NONE);
+
+    // Emit the class
+    Printv(swigtype, typemapLookup("m3imports", type, WARN_NONE),	// Import statements
+	   "\n", typemapLookup("m3classmodifiers", type, WARN_MODULA3_TYPEMAP_CLASSMOD_UNDEF),	// Class modifiers
+	   " class $m3classname",	// Class name and bases
+	   *Char(pure_baseclass) ? " : " : "", pure_baseclass, *Char(pure_interfaces) ?	// Interfaces
+	   " : " : "", pure_interfaces, " {\n", "  private IntPtr swigCPtr;\n", "\n", "  ", typemapLookup("m3ptrconstructormodifiers", type, WARN_MODULA3_TYPEMAP_PTRCONSTMOD_UNDEF),	// pointer constructor modifiers
+	   " $m3classname(IntPtr cPtr, bool bFutureUse) {\n",	// Constructor used for wrapping pointers
+	   "    swigCPtr = cPtr;\n", "  }\n", "\n", "  protected $m3classname() {\n",	// Default constructor
+	   "    swigCPtr = IntPtr.Zero;\n", "  }\n", typemapLookup("m3getcptr", type, WARN_MODULA3_TYPEMAP_GETCPTR_UNDEF),	// getCPtr method
+	   typemapLookup("m3code", type, WARN_NONE),	// extra Modula 3 code
+	   "}\n", "\n", NIL);
+
+    Replaceall(swigtype, "$m3classname", classname);
+    Printv(f_swigtype, swigtype, NIL);
+
+    Close(f_swigtype);
+    Delete(filen);
+    Delete(swigtype);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * typemapLookup()
+   * ----------------------------------------------------------------------------- */
+
+  const String *typemapLookup(const String *op, String *type, int warning, Node *typemap_attributes = NULL) {
+    String *tm = NULL;
+    const String *code = NULL;
+
+    if ((tm = Swig_typemap_search(op, type, NULL, NULL))) {
+      code = Getattr(tm, "code");
+      if (typemap_attributes)
+	Swig_typemap_attach_kwargs(tm, op, typemap_attributes);
+    }
+
+    if (!code) {
+      code = empty_string;
+      if (warning != WARN_NONE)
+	Swig_warning(warning, input_file, line_number, "No %s typemap defined for %s\n", op, type);
+    }
+
+    return code ? code : empty_string;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * addThrows()
+   *
+   * Add all exceptions to a hash that are associated with the 'typemap'.
+   * Return number the number of these exceptions.
+   * ----------------------------------------------------------------------------- */
+
+  int addThrows(Hash *throws_hash, const String *typemap, Node *parameter) {
+    // Get the comma separated throws clause - held in "throws" attribute in the typemap passed in
+    int len = 0;
+    String *throws_attribute = NewStringf("%s:throws", typemap);
+
+    addImports(m3wrap_intf.import, throws_attribute, parameter);
+    addImports(m3wrap_impl.import, throws_attribute, parameter);
+
+    String *throws = getMappedTypeNew(parameter, Char(throws_attribute), "", false);
+    //printf("got exceptions %s for %s\n", Char(throws), Char(throws_attribute));
+
+    if (throws) {
+      // Put the exception classes in the throws clause into a temporary List
+      List *temp_classes_list = Split(throws, ',', INT_MAX);
+      len = Len(temp_classes_list);
+
+      // Add the exception classes to the node throws list, but don't duplicate if already in list
+      if (temp_classes_list /*&& hasContent(temp_classes_list) */ ) {
+	for (Iterator cls = First(temp_classes_list); cls.item != NIL; cls = Next(cls)) {
+	  String *exception_class = NewString(cls.item);
+	  Replaceall(exception_class, " ", "");	// remove spaces
+	  Replaceall(exception_class, "\t", "");	// remove tabs
+	  if (hasContent(exception_class)) {
+	    // $m3classname substitution
+	    SwigType *pt = Getattr(parameter, "type");
+	    substituteClassname(pt, exception_class);
+	    // Don't duplicate the exception class in the throws clause
+	    //printf("add exception %s\n", Char(exception_class));
+	    Setattr(throws_hash, exception_class, "1");
+	  }
+	  Delete(exception_class);
+	}
+      }
+      Delete(temp_classes_list);
+    }
+    Delete(throws_attribute);
+    return len;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * generateThrowsClause()
+   * ----------------------------------------------------------------------------- */
+
+  void generateThrowsClause(Hash *throws_hash, String *code) {
+    // Add the throws clause into code
+    if (Len(throws_hash) > 0) {
+      Iterator cls = First(throws_hash);
+      Printf(code, " RAISES {%s", cls.key);
+      for (cls = Next(cls); cls.key != NIL; cls = Next(cls)) {
+	Printf(code, ", %s", cls.key);
+      }
+      Printf(code, "}");
+    }
+  }
+
+  /* -----------------------------------------------------------------------------
+   * addImports()
+   *
+   * Add all imports that are needed for contents of 'typemap'.
+   * ----------------------------------------------------------------------------- */
+
+  void addImports(Hash *imports_hash, const String *typemap, Node *node) {
+    // Get the comma separated throws clause - held in "throws" attribute in the typemap passed in
+    String *imports_attribute = NewStringf("%s:import", typemap);
+    String *imports = getMappedTypeNew(node, Char(imports_attribute), "", false);
+    //printf("got imports %s for %s\n", Char(imports), Char(imports_attribute));
+
+    if (imports != NIL) {
+      List *import_list = Split(imports, ',', INT_MAX);
+
+      // Add the exception classes to the node imports list, but don't duplicate if already in list
+      if (import_list != NIL) {
+	for (Iterator imp = First(import_list); imp.item != NIL; imp = Next(imp)) {
+	  List *import_pair = Split(imp.item, ' ', 3);
+	  if (Len(import_pair) == 1) {
+	    Setattr(imports_hash, Getitem(import_pair, 0), "");
+	  } else if ((Len(import_pair) == 3)
+		     && Strcmp(Getitem(import_pair, 1), "AS") == 0) {
+	    Setattr(imports_hash, Getitem(import_pair, 0), Getitem(import_pair, 2));
+	  } else {
+	    Swig_warning(WARN_MODULA3_BAD_IMPORT, input_file, line_number,
+			 "Malformed import '%s' for typemap '%s' defined for type '%s'\n", imp, typemap, SwigType_str(Getattr(node, "type"), 0));
+	  }
+	  Delete(import_pair);
+	}
+      }
+      Delete(import_list);
+    }
+    Delete(imports_attribute);
+  }
+
+  /* -----------------------------------------------------------------------------
+   * emitImportStatements()
+   * ----------------------------------------------------------------------------- */
+
+  void emitImportStatements(Hash *imports_hash, String *code) {
+    // Add the imports statements into code
+    Iterator imp = First(imports_hash);
+    while (imp.key != NIL) {
+      Printf(code, "IMPORT %s", imp.key);
+      String *imp_as = imp.item;
+      if (hasContent(imp_as)) {
+	Printf(code, " AS %s", imp_as);
+      }
+      Printf(code, ";\n");
+      imp = Next(imp);
+    }
+  }
+
+};				/* class MODULA3 */
+
+/* -----------------------------------------------------------------------------
+ * swig_modula3()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+extern "C" Language *swig_modula3(void) {
+  return new MODULA3();
+}
+
+/* -----------------------------------------------------------------------------
+ * Static member variables
+ * ----------------------------------------------------------------------------- */
+
+const char *MODULA3::usage = (char *) "\
+Modula 3 Options (available with -modula3)\n\
+     -generateconst <file>   - generate code for computing numeric values of constants\n\
+     -generaterename <file>  - generate suggestions for %rename\n\
+     -generatetypemap <file> - generate templates for some basic typemaps\n\
+     -oldvarnames    - old intermediary method names for variable wrappers\n\
+\n";
+
+/*
+     -generateconst <file> - stem of the .c source file for computing the numeric values of constants\n\
+     -generaterename <file> - stem of the .i source file containing %rename suggestions\n\
+     -generatetypemap <file> - stem of the .i source file containing typemap patterns\n\
+*/
diff --git a/trunk/Source/Modules/module.cxx b/trunk/Source/Modules/module.cxx
new file mode 100644
index 0000000..6a0d6bb
--- /dev/null
+++ b/trunk/Source/Modules/module.cxx
@@ -0,0 +1,57 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * module.cxx
+ *
+ * This file is responsible for the module system.  
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_module_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+struct Module {
+  ModuleFactory fac;
+  char *name;
+  Module *next;
+   Module(const char *n, ModuleFactory f) {
+    fac = f;
+    name = new char[strlen(n) + 1];
+     strcpy(name, n);
+     next = 0;
+  } ~Module() {
+    delete[]name;
+  }
+};
+
+static Module *modules = 0;
+
+/* -----------------------------------------------------------------------------
+ * void Swig_register_module()
+ *
+ * Register a module.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_register_module(const char *n, ModuleFactory f) {
+  Module *m = new Module(n, f);
+  m->next = modules;
+  modules = m;
+}
+
+/* -----------------------------------------------------------------------------
+ * Language *Swig_find_module()
+ *
+ * Given a command line option, locates the factory function.
+ * ----------------------------------------------------------------------------- */
+
+ModuleFactory Swig_find_module(const char *name) {
+  Module *m = modules;
+  while (m) {
+    if (strcmp(m->name, name) == 0) {
+      return m->fac;
+    }
+    m = m->next;
+  }
+  return 0;
+}
diff --git a/trunk/Source/Modules/mzscheme.cxx b/trunk/Source/Modules/mzscheme.cxx
new file mode 100644
index 0000000..78d4a4b
--- /dev/null
+++ b/trunk/Source/Modules/mzscheme.cxx
@@ -0,0 +1,826 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * mzscheme.cxx
+ *
+ * Mzscheme language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_mzscheme_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#include <ctype.h>
+
+static const char *usage = (char *) "\
+Mzscheme Options (available with -mzscheme)\n\
+     -prefix <name>                         - Set a prefix <name> to be prepended to all names\n\
+     -declaremodule                         - Create extension that declares a module\n\
+     -noinit                                - Do not emit scheme_initialize, scheme_reload,\n\
+                                              scheme_module_name functions\n\
+     -dynamic-load <library>,[library,...]  - Do not link with these libraries, dynamic load\n\
+                                              them\n\
+";
+
+static String *fieldnames_tab = 0;
+static String *convert_tab = 0;
+static String *convert_proto_tab = 0;
+static String *struct_name = 0;
+static String *mangled_struct_name = 0;
+
+static char *prefix = 0;
+static bool declaremodule = false;
+static bool noinit = false;
+//DLOPEN PATCH
+static char *load_libraries = NULL;
+//DLOPEN PATCH
+static String *module = 0;
+static char *mzscheme_path = (char *) "mzscheme";
+static String *init_func_def = 0;
+
+static File *f_runtime = 0;
+static File *f_header = 0;
+static File *f_wrappers = 0;
+static File *f_init = 0;
+
+// Used for garbage collection
+static int exporting_destructor = 0;
+static String *swigtype_ptr = 0;
+static String *cls_swigtype = 0;
+
+class MZSCHEME:public Language {
+public:
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+
+    int i;
+
+     SWIG_library_directory(mzscheme_path);
+
+    // Look for certain command line options
+    for (i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stdout);
+	  SWIG_exit(0);
+	} else if (strcmp(argv[i], "-prefix") == 0) {
+	  if (argv[i + 1]) {
+	    prefix = new char[strlen(argv[i + 1]) + 2];
+	    strcpy(prefix, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-declaremodule") == 0) {
+	  declaremodule = true;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noinit") == 0) {
+	  noinit = true;
+	  Swig_mark_arg(i);
+	}
+// DLOPEN PATCH
+	else if (strcmp(argv[i], "-dynamic-load") == 0) {
+	  load_libraries = new char[strlen(argv[i + 1]) + 2];
+	  strcpy(load_libraries, argv[i + 1]);
+	  Swig_mark_arg(i++);
+	  Swig_mark_arg(i);
+	}
+// DLOPEN PATCH
+      }
+    }
+
+    // If a prefix has been specified make sure it ends in a '_'
+
+    if (prefix) {
+      if (prefix[strlen(prefix)] != '_') {
+	prefix[strlen(prefix) + 1] = 0;
+	prefix[strlen(prefix)] = '_';
+      }
+    } else
+      prefix = (char *) "swig_";
+
+    // Add a symbol for this module
+
+    Preprocessor_define("SWIGMZSCHEME 1", 0);
+
+    // Set name of typemaps
+
+    SWIG_typemap_lang("mzscheme");
+
+    // Read in default typemaps */
+    SWIG_config_file("mzscheme.swg");
+    allow_overloading();
+
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+
+    init_func_def = NewString("");
+    Swig_register_filebyname("init", init_func_def);
+
+    Printf(f_runtime, "/* -*- buffer-read-only: t -*- vi: set ro: */\n");
+    Swig_banner(f_runtime);
+
+    module = Getattr(n, "name");
+
+    Language::top(n);
+
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+    if (!noinit) {
+      if (declaremodule) {
+	Printf(f_init, "#define SWIG_MZSCHEME_CREATE_MENV(env) scheme_primitive_module(scheme_intern_symbol(\"%s\"), env)\n", module);
+      } else {
+	Printf(f_init, "#define SWIG_MZSCHEME_CREATE_MENV(env) (env)\n");
+      }
+      Printf(f_init, "%s\n", Char(init_func_def));
+      if (declaremodule) {
+	Printf(f_init, "\tscheme_finish_primitive_module(menv);\n");
+      }
+      Printf(f_init, "\treturn scheme_void;\n}\n");
+      Printf(f_init, "Scheme_Object *scheme_initialize(Scheme_Env *env) {\n");
+
+      // DLOPEN PATCH
+      if (load_libraries) {
+	Printf(f_init, "mz_set_dlopen_libraries(\"%s\");\n", load_libraries);
+      }
+      // DLOPEN PATCH
+
+      Printf(f_init, "\treturn scheme_reload(env);\n");
+      Printf(f_init, "}\n");
+
+      Printf(f_init, "Scheme_Object *scheme_module_name(void) {\n");
+      if (declaremodule) {
+	Printf(f_init, "   return scheme_intern_symbol((char*)\"%s\");\n", module);
+      } else {
+	Printf(f_init, "   return scheme_make_symbol((char*)\"%s\");\n", module);
+      }
+      Printf(f_init, "}\n");
+    }
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * Create a function declaration and register it with the interpreter.
+   * ------------------------------------------------------------ */
+
+  void throw_unhandled_mzscheme_type_error(SwigType *d) {
+    Swig_warning(WARN_TYPEMAP_UNDEF, input_file, line_number, "Unable to handle type %s.\n", SwigType_str(d, 0));
+  }
+
+  /* Return true iff T is a pointer type */
+
+  int
+   is_a_pointer(SwigType *t) {
+    return SwigType_ispointer(SwigType_typedef_resolve_all(t));
+  }
+
+  virtual int functionWrapper(Node *n) {
+    char *iname = GetChar(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    Parm *p;
+
+    Wrapper *f = NewWrapper();
+    String *proc_name = NewString("");
+    String *source = NewString("");
+    String *target = NewString("");
+    String *arg = NewString("");
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *build = NewString("");
+    String *tm;
+    int argout_set = 0;
+    int i = 0;
+    int numargs;
+    int numreq;
+    String *overname = 0;
+
+    // PATCH DLOPEN
+    if (load_libraries) {
+      ParmList *parms = Getattr(n, "parms");
+      SwigType *type = Getattr(n, "type");
+      String *name = NewString("caller");
+      Setattr(n, "wrap:action", Swig_cresult(type, "result", Swig_cfunction_call(name, parms)));
+    }
+    // PATCH DLOPEN
+
+    // Make a wrapper name for this
+    String *wname = Swig_name_wrapper(iname);
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n)) {
+        DelWrapper(f);
+	return SWIG_ERROR;
+      }
+    }
+    if (overname) {
+      Append(wname, overname);
+    }
+    Setattr(n, "wrap:name", wname);
+
+    // Build the name for Scheme.
+    Printv(proc_name, iname, NIL);
+    Replaceall(proc_name, "_", "-");
+
+    // writing the function wrapper function
+    Printv(f->def, "static Scheme_Object *", wname, " (", NIL);
+    Printv(f->def, "int argc, Scheme_Object **argv", NIL);
+    Printv(f->def, ")\n{", NIL);
+
+    /* Define the scheme name in C. This define is used by several
+       macros. */
+    Printv(f->def, "#define FUNC_NAME \"", proc_name, "\"", NIL);
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    numargs = emit_num_arguments(l);
+    numreq = emit_num_required(l);
+
+    // DLOPEN PATCH
+    /* Add the holder for the pointer to the function to be opened */
+    if (load_libraries) {
+      Wrapper_add_local(f, "_function_loaded", "static int _function_loaded=(1==0)");
+      Wrapper_add_local(f, "_the_function", "static void *_the_function=NULL");
+      {
+	String *parms = ParmList_protostr(l);
+	String *func = NewStringf("(*caller)(%s)", parms);
+	Wrapper_add_local(f, "caller", SwigType_lstr(d, func));	/*"(*caller)()")); */
+      }
+    }
+    // DLOPEN PATCH
+
+    // adds local variables
+    Wrapper_add_local(f, "lenv", "int lenv = 1");
+    Wrapper_add_local(f, "values", "Scheme_Object *values[MAXVALUES]");
+
+    // DLOPEN PATCH
+    if (load_libraries) {
+      Printf(f->code, "if (!_function_loaded) { _the_function=mz_load_function(\"%s\");_function_loaded=(1==1); }\n", iname);
+      Printf(f->code, "if (!_the_function) { scheme_signal_error(\"Cannot load C function '%s'\"); }\n", iname);
+      Printf(f->code, "caller=_the_function;\n");
+    }
+    // DLOPEN PATCH
+
+    // Now write code to extract the parameters (this is super ugly)
+
+    for (i = 0, p = l; i < numargs; i++) {
+      /* Skip ignored arguments */
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+
+      // Produce names of source and target
+      Clear(source);
+      Clear(target);
+      Clear(arg);
+      Printf(source, "argv[%d]", i);
+      Printf(target, "%s", ln);
+      Printv(arg, Getattr(p, "name"), NIL);
+
+      if (i >= numreq) {
+	Printf(f->code, "if (argc > %d) {\n", i);
+      }
+      // Handle parameter types.
+      if ((tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$source", source);
+	Replaceall(tm, "$target", target);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	// no typemap found
+	// check if typedef and resolve
+	throw_unhandled_mzscheme_type_error(pt);
+	p = nextSibling(p);
+      }
+      if (i >= numreq) {
+	Printf(f->code, "}\n");
+      }
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Pass output arguments back to the caller.
+
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* Deprecated */
+	Replaceall(tm, "$target", Getattr(p, "lname"));	/* Deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+	argout_set = 1;
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Free up any memory allocated for the arguments.
+
+    /* Insert cleanup code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Now write code to make the function call
+
+    String *actioncode = emit_action(n);
+
+    // Now have return value, figure out what to do with it.
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      Replaceall(tm, "$source", "result");
+      Replaceall(tm, "$target", "values[0]");
+      Replaceall(tm, "$result", "values[0]");
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "1");
+      else
+	Replaceall(tm, "$owner", "0");
+      Printv(f->code, tm, "\n", NIL);
+    } else {
+      throw_unhandled_mzscheme_type_error(d);
+    }
+    emit_return_variable(n, d, f);
+
+    // Dump the argument output code
+    Printv(f->code, Char(outarg), NIL);
+
+    // Dump the argument cleanup code
+    Printv(f->code, Char(cleanup), NIL);
+
+    // Look for any remaining cleanup
+
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printv(f->code, tm, "\n", NIL);
+      }
+    }
+    // Free any memory allocated by the function being wrapped..
+
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printv(f->code, tm, "\n", NIL);
+    }
+    // Wrap things up (in a manner of speaking)
+
+    Printv(f->code, tab4, "return SWIG_MzScheme_PackageValues(lenv, values);\n", NIL);
+    Printf(f->code, "#undef FUNC_NAME\n");
+    Printv(f->code, "}\n", NIL);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", iname);
+
+    Wrapper_print(f, f_wrappers);
+
+    if (!Getattr(n, "sym:overloaded")) {
+
+      // Now register the function
+      char temp[256];
+      sprintf(temp, "%d", numargs);
+      if (exporting_destructor) {
+	Printf(init_func_def, "SWIG_TypeClientData(SWIGTYPE%s, (void *) %s);\n", swigtype_ptr, wname);
+      } else {
+	Printf(init_func_def, "scheme_add_global(\"%s\", scheme_make_prim_w_arity(%s,\"%s\",%d,%d),menv);\n", proc_name, wname, proc_name, numreq, numargs);
+      }
+    } else {
+      if (!Getattr(n, "sym:nextSibling")) {
+	/* Emit overloading dispatch function */
+
+	int maxargs;
+	String *dispatch = Swig_overload_dispatch(n, "return %s(argc,argv);", &maxargs);
+
+	/* Generate a dispatch wrapper for all overloaded functions */
+
+	Wrapper *df = NewWrapper();
+	String *dname = Swig_name_wrapper(iname);
+
+	Printv(df->def, "static Scheme_Object *\n", dname, "(int argc, Scheme_Object **argv) {", NIL);
+	Printv(df->code, dispatch, "\n", NIL);
+	Printf(df->code, "scheme_signal_error(\"No matching function for overloaded '%s'\");\n", iname);
+	Printv(df->code, "}\n", NIL);
+	Wrapper_print(df, f_wrappers);
+	Printf(init_func_def, "scheme_add_global(\"%s\", scheme_make_prim_w_arity(%s,\"%s\",%d,%d),menv);\n", proc_name, dname, proc_name, 0, maxargs);
+	DelWrapper(df);
+	Delete(dispatch);
+	Delete(dname);
+      }
+    }
+
+    Delete(proc_name);
+    Delete(source);
+    Delete(target);
+    Delete(arg);
+    Delete(outarg);
+    Delete(cleanup);
+    Delete(build);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   *
+   * Create a link to a C variable.
+   * This creates a single function _wrap_swig_var_varname().
+   * This function takes a single optional argument.   If supplied, it means
+   * we are setting this variable to some value.  If omitted, it means we are
+   * simply evaluating this variable.  Either way, we return the variables
+   * value.
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+
+    String *proc_name = NewString("");
+    String *tm;
+    String *tm2 = NewString("");;
+    String *argnum = NewString("0");
+    String *arg = NewString("argv[0]");
+    Wrapper *f;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    f = NewWrapper();
+
+    // evaluation function names
+    String *var_name = Swig_name_wrapper(iname);
+
+    // Build the name for scheme.
+    Printv(proc_name, iname, NIL);
+    Replaceall(proc_name, "_", "-");
+    Setattr(n, "wrap:name", proc_name);
+
+    if ((SwigType_type(t) != T_USER) || (is_a_pointer(t))) {
+
+      Printf(f->def, "static Scheme_Object *%s(int argc, Scheme_Object** argv) {\n", var_name);
+      Printv(f->def, "#define FUNC_NAME \"", proc_name, "\"", NIL);
+
+      Wrapper_add_local(f, "swig_result", "Scheme_Object *swig_result");
+
+      if (!GetFlag(n, "feature:immutable")) {
+	/* Check for a setting of the variable value */
+	Printf(f->code, "if (argc) {\n");
+	if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	  Replaceall(tm, "$source", "argv[0]");
+	  Replaceall(tm, "$target", name);
+	  Replaceall(tm, "$input", "argv[0]");
+	  /* Printv(f->code, tm, "\n",NIL); */
+	  emit_action_code(n, f->code, tm);
+	} else {
+	  throw_unhandled_mzscheme_type_error(t);
+	}
+	Printf(f->code, "}\n");
+      }
+      // Now return the value of the variable (regardless
+      // of evaluating or setting)
+
+      if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+	Replaceall(tm, "$source", name);
+	Replaceall(tm, "$target", "swig_result");
+	Replaceall(tm, "$result", "swig_result");
+	/* Printf (f->code, "%s\n", tm); */
+	emit_action_code(n, f->code, tm);
+      } else {
+	throw_unhandled_mzscheme_type_error(t);
+      }
+      Printf(f->code, "\nreturn swig_result;\n");
+      Printf(f->code, "#undef FUNC_NAME\n");
+      Printf(f->code, "}\n");
+
+      Wrapper_print(f, f_wrappers);
+
+      // Now add symbol to the MzScheme interpreter
+
+      Printv(init_func_def,
+	     "scheme_add_global(\"", proc_name, "\", scheme_make_prim_w_arity(", var_name, ", \"", proc_name, "\", ", "0", ", ", "1", "), menv);\n", NIL);
+
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
+    }
+    Delete(var_name);
+    Delete(proc_name);
+    Delete(argnum);
+    Delete(arg);
+    Delete(tm2);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *value = Getattr(n, "value");
+
+    String *var_name = NewString("");
+    String *proc_name = NewString("");
+    String *rvalue = NewString("");
+    String *temp = NewString("");
+    String *tm;
+
+    // Make a static variable;
+
+    Printf(var_name, "_wrap_const_%s", Swig_name_mangle(Getattr(n, "sym:name")));
+
+    // Build the name for scheme.
+    Printv(proc_name, iname, NIL);
+    Replaceall(proc_name, "_", "-");
+
+    if ((SwigType_type(type) == T_USER) && (!is_a_pointer(type))) {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+    // See if there's a typemap
+
+    Printv(rvalue, value, NIL);
+    if ((SwigType_type(type) == T_CHAR) && (is_a_pointer(type) == 1)) {
+      temp = Copy(rvalue);
+      Clear(rvalue);
+      Printv(rvalue, "\"", temp, "\"", NIL);
+    }
+    if ((SwigType_type(type) == T_CHAR) && (is_a_pointer(type) == 0)) {
+      Delete(temp);
+      temp = Copy(rvalue);
+      Clear(rvalue);
+      Printv(rvalue, "'", temp, "'", NIL);
+    }
+    if ((tm = Swig_typemap_lookup("constant", n, name, 0))) {
+      Replaceall(tm, "$source", rvalue);
+      Replaceall(tm, "$value", rvalue);
+      Replaceall(tm, "$target", name);
+      Printf(f_init, "%s\n", tm);
+    } else {
+      // Create variable and assign it a value
+
+      Printf(f_header, "static %s = ", SwigType_lstr(type, var_name));
+      if ((SwigType_type(type) == T_STRING)) {
+	Printf(f_header, "\"%s\";\n", value);
+      } else if (SwigType_type(type) == T_CHAR) {
+	Printf(f_header, "\'%s\';\n", value);
+      } else {
+	Printf(f_header, "%s;\n", value);
+      }
+
+      // Now create a variable declaration
+
+      {
+	/* Hack alert: will cleanup later -- Dave */
+	Node *n = NewHash();
+	Setattr(n, "name", var_name);
+	Setattr(n, "sym:name", iname);
+	Setattr(n, "type", type);
+	SetFlag(n, "feature:immutable");
+	variableWrapper(n);
+	Delete(n);
+      }
+    }
+    Delete(proc_name);
+    Delete(rvalue);
+    Delete(temp);
+    return SWIG_OK;
+  }
+
+  virtual int destructorHandler(Node *n) {
+    exporting_destructor = true;
+    Language::destructorHandler(n);
+    exporting_destructor = false;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+  virtual int classHandler(Node *n) {
+    String *mangled_classname = 0;
+    String *real_classname = 0;
+    String *scm_structname = NewString("");
+    SwigType *ctype_ptr = NewStringf("p.%s", Getattr(n, "classtype"));
+
+    SwigType *t = NewStringf("p.%s", Getattr(n, "name"));
+    swigtype_ptr = SwigType_manglestr(t);
+    Delete(t);
+
+    cls_swigtype = SwigType_manglestr(Getattr(n, "name"));
+
+
+    fieldnames_tab = NewString("");
+    convert_tab = NewString("");
+    convert_proto_tab = NewString("");
+
+    struct_name = Getattr(n, "sym:name");
+    mangled_struct_name = Swig_name_mangle(Getattr(n, "sym:name"));
+
+    Printv(scm_structname, struct_name, NIL);
+    Replaceall(scm_structname, "_", "-");
+
+    real_classname = Getattr(n, "name");
+    mangled_classname = Swig_name_mangle(real_classname);
+
+    Printv(fieldnames_tab, "static const char *_swig_struct_", cls_swigtype, "_field_names[] = { \n", NIL);
+
+    Printv(convert_proto_tab, "static Scheme_Object *_swig_convert_struct_", cls_swigtype, "(", SwigType_str(ctype_ptr, "ptr"), ");\n", NIL);
+
+    Printv(convert_tab, "static Scheme_Object *_swig_convert_struct_", cls_swigtype, "(", SwigType_str(ctype_ptr, "ptr"), ")\n {\n", NIL);
+
+    Printv(convert_tab,
+	   tab4, "Scheme_Object *obj;\n", tab4, "Scheme_Object *fields[_swig_struct_", cls_swigtype, "_field_names_cnt];\n", tab4, "int i = 0;\n\n", NIL);
+
+    /* Generate normal wrappers */
+    Language::classHandler(n);
+
+    Printv(convert_tab, tab4, "obj = scheme_make_struct_instance(", "_swig_struct_type_", cls_swigtype, ", i, fields);\n", NIL);
+    Printv(convert_tab, tab4, "return obj;\n}\n\n", NIL);
+
+    Printv(fieldnames_tab, "};\n", NIL);
+
+    Printv(f_header, "static Scheme_Object *_swig_struct_type_", cls_swigtype, ";\n", NIL);
+
+    Printv(f_header, fieldnames_tab, NIL);
+    Printv(f_header, "#define  _swig_struct_", cls_swigtype, "_field_names_cnt (sizeof(_swig_struct_", cls_swigtype, "_field_names)/sizeof(char*))\n", NIL);
+
+    Printv(f_header, convert_proto_tab, NIL);
+    Printv(f_wrappers, convert_tab, NIL);
+
+    Printv(init_func_def, "_swig_struct_type_", cls_swigtype,
+	   " = SWIG_MzScheme_new_scheme_struct(menv, \"", scm_structname, "\", ",
+	   "_swig_struct_", cls_swigtype, "_field_names_cnt,", "(char**) _swig_struct_", cls_swigtype, "_field_names);\n", NIL);
+
+    Delete(mangled_classname);
+    Delete(swigtype_ptr);
+    swigtype_ptr = 0;
+    Delete(fieldnames_tab);
+    Delete(convert_tab);
+    Delete(ctype_ptr);
+    Delete(convert_proto_tab);
+    struct_name = 0;
+    mangled_struct_name = 0;
+    Delete(cls_swigtype);
+    cls_swigtype = 0;
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int membervariableHandler(Node *n) {
+    Language::membervariableHandler(n);
+
+    if (!is_smart_pointer()) {
+      String *symname = Getattr(n, "sym:name");
+      String *name = Getattr(n, "name");
+      SwigType *type = Getattr(n, "type");
+      String *swigtype = SwigType_manglestr(Getattr(n, "type"));
+      String *tm = 0;
+      String *access_mem = NewString("");
+      SwigType *ctype_ptr = NewStringf("p.%s", Getattr(n, "type"));
+
+      Printv(fieldnames_tab, tab4, "\"", symname, "\",\n", NIL);
+      Printv(access_mem, "(ptr)->", name, NIL);
+      if ((SwigType_type(type) == T_USER) && (!is_a_pointer(type))) {
+	Printv(convert_tab, tab4, "fields[i++] = ", NIL);
+	Printv(convert_tab, "_swig_convert_struct_", swigtype, "((", SwigType_str(ctype_ptr, ""), ")&((ptr)->", name, "));\n", NIL);
+      } else if ((tm = Swig_typemap_lookup("varout", n, access_mem, 0))) {
+	Replaceall(tm, "$result", "fields[i++]");
+	Printv(convert_tab, tm, "\n", NIL);
+      } else
+	Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported member variable type %s (ignored).\n", SwigType_str(type, 0));
+
+      Delete(access_mem);
+    }
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------
+   * validIdentifer()
+   * ------------------------------------------------------------ */
+
+  virtual int validIdentifier(String *s) {
+    char *c = Char(s);
+    /* Check whether we have an R5RS identifier. */
+    /* <identifier> --> <initial> <subsequent>* | <peculiar identifier> */
+    /* <initial> --> <letter> | <special initial> */
+    if (!(isalpha(*c) || (*c == '!') || (*c == '$') || (*c == '%')
+	  || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
+	  || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
+	  || (*c == '^') || (*c == '_') || (*c == '~'))) {
+      /* <peculiar identifier> --> + | - | ... */
+      if ((strcmp(c, "+") == 0)
+	  || strcmp(c, "-") == 0 || strcmp(c, "...") == 0)
+	return 1;
+      else
+	return 0;
+    }
+    /* <subsequent> --> <initial> | <digit> | <special subsequent> */
+    while (*c) {
+      if (!(isalnum(*c) || (*c == '!') || (*c == '$') || (*c == '%')
+	    || (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
+	    || (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
+	    || (*c == '^') || (*c == '_') || (*c == '~') || (*c == '+')
+	    || (*c == '-') || (*c == '.') || (*c == '@')))
+	return 0;
+      c++;
+    }
+    return 1;
+  }
+
+  String *runtimeCode() {
+    String *s = Swig_include_sys("mzrun.swg");
+    if (!s) {
+      Printf(stderr, "*** Unable to open 'mzrun.swg'\n");
+      s = NewString("");
+    }
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigmzrun.h");
+  }
+};
+
+/* -----------------------------------------------------------------------------
+ * swig_mzscheme()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_mzscheme() {
+  return new MZSCHEME();
+}
+extern "C" Language *swig_mzscheme(void) {
+  return new_swig_mzscheme();
+}
diff --git a/trunk/Source/Modules/ocaml.cxx b/trunk/Source/Modules/ocaml.cxx
new file mode 100755
index 0000000..9f5677b
--- /dev/null
+++ b/trunk/Source/Modules/ocaml.cxx
@@ -0,0 +1,1869 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ocaml.cxx
+ *
+ * Ocaml language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_ocaml_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#include <ctype.h>
+
+static const char *usage = (char *)
+    ("Ocaml Options (available with -ocaml)\n"
+     "-prefix <name>  - Set a prefix <name> to be prepended to all names\n"
+     "-where          - Emit library location\n"
+     "-suffix <name>  - Change .cxx to something else\n" "-oldvarnames    - old intermediary method names for variable wrappers\n" "\n");
+
+static int classmode = 0;
+static int in_constructor = 0, in_destructor = 0, in_copyconst = 0;
+static int const_enum = 0;
+static int static_member_function = 0;
+static int generate_sizeof = 0;
+static char *prefix = 0;
+static char *ocaml_path = (char *) "ocaml";
+static bool old_variable_names = false;
+static String *classname = 0;
+static String *module = 0;
+static String *init_func_def = 0;
+static String *f_classtemplate = 0;
+static String *name_qualifier = 0;
+
+static Hash *seen_enums = 0;
+static Hash *seen_enumvalues = 0;
+static Hash *seen_constructors = 0;
+
+static File *f_header = 0;
+static File *f_runtime = 0;
+static File *f_wrappers = 0;
+static File *f_directors = 0;
+static File *f_directors_h = 0;
+static File *f_init = 0;
+static File *f_mlout = 0;
+static File *f_mliout = 0;
+static File *f_mlbody = 0;
+static File *f_mlibody = 0;
+static File *f_mltail = 0;
+static File *f_mlitail = 0;
+static File *f_enumtypes_type = 0;
+static File *f_enumtypes_value = 0;
+static File *f_class_ctors = 0;
+static File *f_class_ctors_end = 0;
+static File *f_enum_to_int = 0;
+static File *f_int_to_enum = 0;
+
+class OCAML:public Language {
+public:
+
+  OCAML() {
+    director_prot_ctor_code = NewString("");
+    Printv(director_prot_ctor_code,
+	   "if ( $comparison ) { /* subclassed */\n",
+	   "  $director_new \n", "} else {\n", "  failwith(\"accessing abstract class or protected constructor\"); \n", "}\n", NIL);
+    director_multiple_inheritance = 1;
+    director_language = 1;
+  }
+ 
+  String *Swig_class_name(Node *n) {
+    String *name;
+    name = Copy(Getattr(n, "sym:name"));
+    return name;
+  }
+
+  void PrintIncludeArg() {
+    Printv(stdout, SWIG_LIB, SWIG_FILE_DELIMITER, ocaml_path, "\n", NIL);
+  }
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+    int i;
+
+    prefix = 0;
+
+    SWIG_library_directory(ocaml_path);
+
+    // Look for certain command line options
+    for (i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stdout);
+	  SWIG_exit(0);
+	} else if (strcmp(argv[i], "-where") == 0) {
+	  PrintIncludeArg();
+	  SWIG_exit(0);
+	} else if (strcmp(argv[i], "-prefix") == 0) {
+	  if (argv[i + 1]) {
+	    prefix = new char[strlen(argv[i + 1]) + 2];
+	    strcpy(prefix, argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-suffix") == 0) {
+	  if (argv[i + 1]) {
+	    SWIG_config_cppext(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else
+	    Swig_arg_error();
+	} else if (strcmp(argv[i], "-oldvarnames") == 0) {
+	  Swig_mark_arg(i);
+	  old_variable_names = true;
+	}
+      }
+    }
+
+    // If a prefix has been specified make sure it ends in a '_'
+
+    if (prefix) {
+      if (prefix[strlen(prefix)] != '_') {
+	prefix[strlen(prefix) + 1] = 0;
+	prefix[strlen(prefix)] = '_';
+      }
+    } else
+      prefix = (char *) "swig_";
+
+    // Add a symbol for this module
+
+    Preprocessor_define("SWIGOCAML 1", 0);
+    // Set name of typemaps
+
+    SWIG_typemap_lang("ocaml");
+
+    // Read in default typemaps */
+    SWIG_config_file("ocaml.i");
+    allow_overloading();
+
+  }
+
+  /* Swig_director_declaration()
+   *
+   * Generate the full director class declaration, complete with base classes.
+   * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {"
+   *
+   */
+
+  String *Swig_director_declaration(Node *n) {
+    String *classname = Swig_class_name(n);
+    String *directorname = NewStringf("SwigDirector_%s", classname);
+    String *base = Getattr(n, "classtype");
+    String *declaration = Swig_class_declaration(n, directorname);
+    Printf(declaration, " : public %s, public Swig::Director {\n", base);
+    Delete(classname);
+    Delete(directorname);
+    return declaration;
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   *
+   * Recognize the %module, and capture the module name.
+   * Create the default enum cases.
+   * Set up the named outputs:
+   *
+   *  init
+   *  ml
+   *  mli
+   *  wrapper
+   *  header
+   *  runtime
+   *  directors
+   *  directors_h
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+    /* Set comparison with none for ConstructorToFunction */
+    setSubclassInstanceCheck(NewString("caml_list_nth(args,0) != Val_unit"));
+
+    /* check if directors are enabled for this module.  note: this 
+     * is a "master" switch, without which no director code will be
+     * emitted.  %feature("director") statements are also required
+     * to enable directors for individual classes or methods.
+     *
+     * use %module(directors="1") modulename at the start of the 
+     * interface file to enable director generation.
+     */
+    {
+      Node *module = Getattr(n, "module");
+      if (module) {
+	Node *options = Getattr(module, "options");
+	if (options) {
+	  if (Getattr(options, "directors")) {
+	    allow_directors();
+	  }
+	  if (Getattr(options, "dirprot")) {
+	    allow_dirprot();
+	  }
+	  if (Getattr(options, "sizeof")) {
+	    generate_sizeof = 1;
+	  }
+	}
+      }
+    }
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+    f_directors = NewString("");
+    f_directors_h = NewString("");
+    f_enumtypes_type = NewString("");
+    f_enumtypes_value = NewString("");
+    init_func_def = NewString("");
+    f_mlbody = NewString("");
+    f_mlibody = NewString("");
+    f_mltail = NewString("");
+    f_mlitail = NewString("");
+    f_class_ctors = NewString("");
+    f_class_ctors_end = NewString("");
+    f_enum_to_int = NewString("");
+    f_int_to_enum = NewString("");
+    f_classtemplate = NewString("");
+
+    module = Getattr(n, "name");
+
+    seen_constructors = NewHash();
+    seen_enums = NewHash();
+    seen_enumvalues = NewHash();
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("init", init_func_def);
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("mli", f_mlibody);
+    Swig_register_filebyname("ml", f_mlbody);
+    Swig_register_filebyname("mlitail", f_mlitail);
+    Swig_register_filebyname("mltail", f_mltail);
+    Swig_register_filebyname("director", f_directors);
+    Swig_register_filebyname("director_h", f_directors_h);
+    Swig_register_filebyname("classtemplate", f_classtemplate);
+    Swig_register_filebyname("class_ctors", f_class_ctors);
+
+    if (old_variable_names) {
+      Swig_name_register("set", "%v__set__");
+      Swig_name_register("get", "%v__get__");
+    }
+
+    Printf(f_runtime, "/* -*- buffer-read-only: t -*- vi: set ro: */\n");
+    Printf(f_runtime, "#define SWIG_MODULE \"%s\"\n", module);
+    /* Module name */
+    Printf(f_mlbody, "let module_name = \"%s\"\n", module);
+    Printf(f_mlibody, "val module_name : string\n");
+    Printf(f_enum_to_int,
+	   "let enum_to_int x (v : c_obj) =\n"
+	   "   match v with\n"
+	   "     C_enum _y ->\n"
+	   "     (let y = _y in match (x : c_enum_type) with\n"
+	   "       `unknown -> " "         (match y with\n" "           `Int x -> (Swig.C_int x)\n" "           | _ -> raise (LabelNotFromThisEnum v))\n");
+
+    Printf(f_int_to_enum, "let int_to_enum x y =\n" "    match (x : c_enum_type) with\n" "      `unknown -> C_enum (`Int y)\n");
+
+    Swig_banner(f_runtime);
+
+    if (directorsEnabled()) {
+      Printf(f_runtime, "#define SWIG_DIRECTORS\n");
+    }
+
+    /* Produce the enum_to_int and int_to_enum functions */
+
+    Printf(f_enumtypes_type, "open Swig\n" "type c_enum_type = [ \n  `unknown\n");
+    Printf(f_enumtypes_value, "type c_enum_value = [ \n  `Int of int\n");
+    String *mlfile = NewString("");
+    String *mlifile = NewString("");
+
+    Printv(mlfile, module, ".ml", NIL);
+    Printv(mlifile, module, ".mli", NIL);
+
+    String *mlfilen = NewStringf("%s%s", SWIG_output_directory(), mlfile);
+    if ((f_mlout = NewFile(mlfilen, "w")) == 0) {
+      FileErrorDisplay(mlfilen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    String *mlifilen = NewStringf("%s%s", SWIG_output_directory(), mlifile);
+    if ((f_mliout = NewFile(mlifilen, "w")) == 0) {
+      FileErrorDisplay(mlifilen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    Language::top(n);
+
+    Printf(f_enum_to_int, ") | _ -> (C_int (get_int v))\n" "let _ = Callback.register \"%s_enum_to_int\" enum_to_int\n", module);
+    Printf(f_mlibody, "val enum_to_int : c_enum_type -> c_obj -> Swig.c_obj\n");
+
+    Printf(f_int_to_enum, "let _ = Callback.register \"%s_int_to_enum\" int_to_enum\n", module);
+    Printf(f_mlibody, "val int_to_enum : c_enum_type -> int -> c_obj\n");
+    Printf(f_init, "#define SWIG_init f_%s_init\n" "%s" "}\n", module, init_func_def);
+    Printf(f_mlbody, "external f_init : unit -> unit = \"f_%s_init\" ;;\n" "let _ = f_init ()\n", module);
+    Printf(f_enumtypes_type, "]\n");
+    Printf(f_enumtypes_value, "]\n\n" "type c_obj = c_enum_value c_obj_t\n");
+
+    if (directorsEnabled()) {
+      // Insert director runtime into the f_runtime file (make it occur before %header section)
+      Swig_insert_file("director.swg", f_runtime);
+    }
+
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+    /* Close all of the files */
+    Dump(f_directors_h, f_header);
+    Dump(f_header, f_runtime);
+    Dump(f_directors, f_wrappers);
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+
+    Dump(f_enumtypes_type, f_mlout);
+    Dump(f_enumtypes_value, f_mlout);
+    Dump(f_mlbody, f_mlout);
+    Dump(f_enum_to_int, f_mlout);
+    Dump(f_int_to_enum, f_mlout);
+    Delete(f_int_to_enum);
+    Delete(f_enum_to_int);
+    Dump(f_class_ctors, f_mlout);
+    Dump(f_class_ctors_end, f_mlout);
+    Dump(f_mltail, f_mlout);
+    Close(f_mlout);
+    Delete(f_mlout);
+
+    Dump(f_enumtypes_type, f_mliout);
+    Dump(f_enumtypes_value, f_mliout);
+    Dump(f_mlibody, f_mliout);
+    Dump(f_mlitail, f_mliout);
+    Close(f_mliout);
+    Delete(f_mliout);
+
+    return SWIG_OK;
+  }
+
+  /* Produce an error for the given type */
+  void throw_unhandled_ocaml_type_error(SwigType *d, const char *types) {
+    Swig_warning(WARN_TYPEMAP_UNDEF, input_file, line_number, "Unable to handle type %s (%s).\n", SwigType_str(d, 0), types);
+  }
+
+  /* Return true iff T is a pointer type */
+  int
+   is_a_pointer(SwigType *t) {
+    return SwigType_ispointer(SwigType_typedef_resolve_all(t));
+  }
+
+  /*
+   * Delete one reference from a given type.
+   */
+
+  void oc_SwigType_del_reference(SwigType *t) {
+    char *c = Char(t);
+    if (strncmp(c, "q(", 2) == 0) {
+      Delete(SwigType_pop(t));
+      c = Char(t);
+    }
+    if (strncmp(c, "r.", 2)) {
+      printf("Fatal error. SwigType_del_pointer applied to non-pointer.\n");
+      abort();
+    }
+    Replace(t, "r.", "", DOH_REPLACE_ANY | DOH_REPLACE_FIRST);
+  }
+
+  void oc_SwigType_del_array(SwigType *t) {
+    char *c = Char(t);
+    if (strncmp(c, "q(", 2) == 0) {
+      Delete(SwigType_pop(t));
+      c = Char(t);
+    }
+    if (strncmp(c, "a(", 2) == 0) {
+      Delete(SwigType_pop(t));
+    }
+  }
+
+  /* 
+   * Return true iff T is a reference type 
+   */
+
+  int
+   is_a_reference(SwigType *t) {
+    return SwigType_isreference(SwigType_typedef_resolve_all(t));
+  }
+
+  int
+   is_an_array(SwigType *t) {
+    return SwigType_isarray(SwigType_typedef_resolve_all(t));
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * Create a function declaration and register it with the interpreter.
+   * ------------------------------------------------------------ */
+
+  virtual int functionWrapper(Node *n) {
+    char *iname = GetChar(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    String *return_type_normalized = normalizeTemplatedClassName(d);
+    ParmList *l = Getattr(n, "parms");
+    int director_method = 0;
+    Parm *p;
+
+    Wrapper *f = NewWrapper();
+    String *proc_name = NewString("");
+    String *source = NewString("");
+    String *target = NewString("");
+    String *arg = NewString("");
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *build = NewString("");
+    String *tm;
+    int argout_set = 0;
+    int i = 0;
+    int numargs;
+    int numreq;
+    int newobj = GetFlag(n, "feature:new");
+    String *nodeType = Getattr(n, "nodeType");
+    int destructor = (!Cmp(nodeType, "destructor"));
+    String *overname = 0;
+    bool isOverloaded = Getattr(n, "sym:overloaded") ? true : false;
+
+    // Make a wrapper name for this
+    String *wname = Swig_name_wrapper(iname);
+    if (isOverloaded) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n)) {
+        DelWrapper(f);
+	return SWIG_ERROR;
+      }
+    }
+    if (overname) {
+      Append(wname, overname);
+    }
+    /* Do this to disambiguate functions emitted from different modules */
+    Append(wname, module);
+
+    Setattr(n, "wrap:name", wname);
+
+    // Build the name for Scheme.
+    Printv(proc_name, "_", iname, NIL);
+    String *mangled_name = mangleNameForCaml(proc_name);
+
+    if (classmode && in_constructor) {	// Emit constructor for object
+      String *mangled_name_nounder = NewString((char *) (Char(mangled_name)) + 1);
+      Printf(f_class_ctors_end, "let %s clst = _%s clst\n", mangled_name_nounder, mangled_name_nounder);
+      Printf(f_mlibody, "val %s : c_obj -> c_obj\n", mangled_name_nounder);
+      Delete(mangled_name_nounder);
+    } else if (classmode && in_destructor) {
+      Printf(f_class_ctors, "    \"~\", %s ;\n", mangled_name);
+    } else if (classmode && !in_constructor && !in_destructor && !static_member_function) {
+      String *opname = Copy(Getattr(n, "memberfunctionHandler:sym:name"));
+
+      Replaceall(opname, "operator ", "");
+
+      if (strstr(Char(mangled_name), "__get__")) {
+	String *set_name = Copy(mangled_name);
+	if (!GetFlag(n, "feature:immutable")) {
+	  Replaceall(set_name, "__get__", "__set__");
+	  Printf(f_class_ctors, "    \"%s\", (fun args -> " "if args = (C_list [ raw_ptr ]) then %s args else %s args) ;\n", opname, mangled_name, set_name);
+	  Delete(set_name);
+	} else {
+	  Printf(f_class_ctors, "    \"%s\", (fun args -> " "if args = (C_list [ raw_ptr ]) then %s args else C_void) ;\n", opname, mangled_name);
+	}
+      } else if (strstr(Char(mangled_name), "__set__")) {
+	;			/* Nothing ... handled by the case above */
+      } else {
+	Printf(f_class_ctors, "    \"%s\", %s ;\n", opname, mangled_name);
+      }
+
+      Delete(opname);
+    }
+
+    if (classmode && in_constructor) {
+      Setattr(seen_constructors, mangled_name, "true");
+    }
+    // writing the function wrapper function
+    Printv(f->def, "SWIGEXT CAML_VALUE ", wname, " (", NIL);
+    Printv(f->def, "CAML_VALUE args", NIL);
+    Printv(f->def, ")\n{", NIL);
+
+    /* Define the scheme name in C. This define is used by several
+       macros. */
+    //Printv(f->def, "#define FUNC_NAME \"", mangled_name, "\"", NIL);
+
+    // adds local variables
+    Wrapper_add_local(f, "args", "CAMLparam1(args)");
+    Wrapper_add_local(f, "ret", "SWIG_CAMLlocal2(swig_result,rv)");
+    Wrapper_add_local(f, "_v", "int _v = 0");
+    if (isOverloaded) {
+      Wrapper_add_local(f, "i", "int i");
+      Wrapper_add_local(f, "argc", "int argc = caml_list_length(args)");
+      Wrapper_add_local(f, "argv", "CAML_VALUE *argv");
+
+      Printv(f->code,
+	     "argv = (CAML_VALUE *)malloc( argc * sizeof( CAML_VALUE ) );\n"
+	     "for( i = 0; i < argc; i++ ) {\n" "  argv[i] = caml_list_nth(args,i);\n" "}\n", NIL);
+    }
+    d = SwigType_typedef_qualified(d);
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    numargs = emit_num_arguments(l);
+    numreq = emit_num_required(l);
+
+    Printf(f->code, "swig_result = Val_unit;\n");
+
+    // Now write code to extract the parameters (this is super ugly)
+
+    for (i = 0, p = l; i < numargs; i++) {
+      /* Skip ignored arguments */
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+      pt = SwigType_typedef_qualified(pt);
+
+      // Produce names of source and target
+      Clear(source);
+      Clear(target);
+      Clear(arg);
+      Printf(source, "caml_list_nth(args,%d)", i);
+      Printf(target, "%s", ln);
+      Printv(arg, Getattr(p, "name"), NIL);
+
+      if (i >= numreq) {
+	Printf(f->code, "if (caml_list_length(args) > %d) {\n", i);
+      }
+      // Handle parameter types.
+      if ((tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$source", source);
+	Replaceall(tm, "$target", target);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	// no typemap found
+	// check if typedef and resolve
+	throw_unhandled_ocaml_type_error(pt, "in");
+	p = nextSibling(p);
+      }
+      if (i >= numreq) {
+	Printf(f->code, "}\n");
+      }
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Pass output arguments back to the caller.
+
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));	/* Deprecated */
+	Replaceall(tm, "$target", Getattr(p, "lname"));	/* Deprecated */
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Replaceall(tm, "$ntype", normalizeTemplatedClassName(Getattr(p, "type")));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+	argout_set = 1;
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Free up any memory allocated for the arguments.
+
+    /* Insert cleanup code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* if the object is a director, and the method call originated from its
+     * underlying python object, resolve the call by going up the c++ 
+     * inheritance chain.  otherwise try to resolve the method in python.  
+     * without this check an infinite loop is set up between the director and 
+     * shadow class method calls.
+     */
+
+    // NOTE: this code should only be inserted if this class is the
+    // base class of a director class.  however, in general we haven't
+    // yet analyzed all classes derived from this one to see if they are
+    // directors.  furthermore, this class may be used as the base of
+    // a director class defined in a completely different module at a
+    // later time, so this test must be included whether or not directorbase
+    // is true.  we do skip this code if directors have not been enabled
+    // at the command line to preserve source-level compatibility with
+    // non-polymorphic swig.  also, if this wrapper is for a smart-pointer
+    // method, there is no need to perform the test since the calling object
+    // (the smart-pointer) and the director object (the "pointee") are
+    // distinct.
+
+    director_method = is_member_director(n) && !is_smart_pointer() && !destructor;
+    if (director_method) {
+      Wrapper_add_local(f, "director", "Swig::Director *director = 0");
+      Printf(f->code, "director = dynamic_cast<Swig::Director *>(arg1);\n");
+      Wrapper_add_local(f, "upcall", "bool upcall = false");
+      Append(f->code, "upcall = (director);\n");
+    }
+
+    // Now write code to make the function call
+    Swig_director_emit_dynamic_cast(n, f);
+    String *actioncode = emit_action(n);
+
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      Replaceall(tm, "$source", "swig_result");
+      Replaceall(tm, "$target", "rv");
+      Replaceall(tm, "$result", "rv");
+      Replaceall(tm, "$ntype", return_type_normalized);
+      Printv(f->code, tm, "\n", NIL);
+    } else {
+      throw_unhandled_ocaml_type_error(d, "out");
+    }
+    emit_return_variable(n, d, f);
+
+    // Dump the argument output code
+    Printv(f->code, Char(outarg), NIL);
+
+    // Dump the argument cleanup code
+    Printv(f->code, Char(cleanup), NIL);
+
+    // Look for any remaining cleanup
+
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "swig_result");
+	Printv(f->code, tm, "\n", NIL);
+      }
+    }
+    // Free any memory allocated by the function being wrapped..
+
+    if ((tm = Swig_typemap_lookup("swig_result", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printv(f->code, tm, "\n", NIL);
+    }
+    // Wrap things up (in a manner of speaking)
+
+    Printv(f->code, tab4, "swig_result = caml_list_append(swig_result,rv);\n", NIL);
+    if (isOverloaded)
+      Printv(f->code, "free(argv);\n", NIL);
+    Printv(f->code, tab4, "CAMLreturn(swig_result);\n", NIL);
+    Printv(f->code, "}\n", NIL);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", iname);
+
+    Wrapper_print(f, f_wrappers);
+
+    if (isOverloaded) {
+      if (!Getattr(n, "sym:nextSibling")) {
+	int maxargs;
+	Wrapper *df = NewWrapper();
+	String *dispatch = Swig_overload_dispatch(n,
+						  "free(argv);\n" "CAMLreturn(%s(args));\n",
+						  &maxargs);
+
+	Wrapper_add_local(df, "_v", "int _v = 0");
+	Wrapper_add_local(df, "argv", "CAML_VALUE *argv");
+
+	/* Undifferentiate name .. this is the dispatch function */
+	wname = Swig_name_wrapper(iname);
+	/* Do this to disambiguate functions emitted from different
+	 * modules */
+	Append(wname, module);
+
+	Printv(df->def,
+	       "SWIGEXT CAML_VALUE ", wname, "(CAML_VALUE args) {\n" "  CAMLparam1(args);\n" "  int i;\n" "  int argc = caml_list_length(args);\n", NIL);
+	Printv(df->code,
+	       "argv = (CAML_VALUE *)malloc( argc * sizeof( CAML_VALUE ) );\n"
+	       "for( i = 0; i < argc; i++ ) {\n" "  argv[i] = caml_list_nth(args,i);\n" "}\n", NIL);
+	Printv(df->code, dispatch, "\n", NIL);
+	Printf(df->code, "failwith(\"No matching function for overloaded '%s'\");\n", iname);
+	Printv(df->code, "}\n", NIL);
+	Wrapper_print(df, f_wrappers);
+
+	DelWrapper(df);
+	Delete(dispatch);
+      }
+    }
+
+    Printf(f_mlbody,
+	   "external %s_f : c_obj list -> c_obj list = \"%s\" ;;\n"
+	   "let %s arg = match %s_f (fnhelper arg) with\n"
+	   "  [] -> C_void\n"
+	   "| [x] -> (if %s then Gc.finalise \n"
+	   "  (fun x -> ignore ((invoke x) \"~\" C_void)) x) ; x\n"
+	   "| lst -> C_list lst ;;\n", mangled_name, wname, mangled_name, mangled_name, newobj ? "true" : "false");
+
+    if (!classmode || in_constructor || in_destructor || static_member_function)
+      Printf(f_mlibody, "val %s : c_obj -> c_obj\n", mangled_name);
+
+    Delete(proc_name);
+    Delete(source);
+    Delete(target);
+    Delete(arg);
+    Delete(outarg);
+    Delete(cleanup);
+    Delete(build);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   *
+   * Create a link to a C variable.
+   * This creates a single function _wrap_swig_var_varname().
+   * This function takes a single optional argument.   If supplied, it means
+   * we are setting this variable to some value.  If omitted, it means we are
+   * simply evaluating this variable.  In the set case we return C_void.
+   *
+   * symname is the name of the variable with respect to C.  This 
+   * may need to differ from the original name in the case of enums.
+   * enumvname is the name of the variable with respect to ocaml.  This
+   * will vary if the variable has been renamed.
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+    char *name = GetChar(n, "feature:symname");
+    String *iname = Getattr(n, "feature:enumvname");
+    String *mname = mangleNameForCaml(iname);
+    SwigType *t = Getattr(n, "type");
+
+    String *proc_name = NewString("");
+    String *tm;
+    String *tm2 = NewString("");;
+    String *argnum = NewString("0");
+    String *arg = NewString("SWIG_Field(args,0)");
+    Wrapper *f;
+
+    if (!name) {
+      name = GetChar(n, "name");
+    }
+
+    if (!iname) {
+      iname = Getattr(n, "sym:name");
+      mname = mangleNameForCaml(NewString(iname));
+    }
+
+    if (!iname || !addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    f = NewWrapper();
+
+    // evaluation function names
+    String *var_name = Swig_name_wrapper(iname);
+
+    // Build the name for scheme.
+    Printv(proc_name, iname, NIL);
+    Setattr(n, "wrap:name", proc_name);
+
+    Printf(f->def, "SWIGEXT CAML_VALUE %s(CAML_VALUE args) {\n", var_name);
+    // Printv(f->def, "#define FUNC_NAME \"", proc_name, "\"", NIL);
+
+    Wrapper_add_local(f, "swig_result", "CAML_VALUE swig_result");
+
+    if (!GetFlag(n, "feature:immutable")) {
+      /* Check for a setting of the variable value */
+      Printf(f->code, "if (args != Val_int(0)) {\n");
+      if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	Replaceall(tm, "$source", "args");
+	Replaceall(tm, "$target", name);
+	Replaceall(tm, "$input", "args");
+	/* Printv(f->code, tm, "\n",NIL); */
+	emit_action_code(n, f->code, tm);
+      } else if ((tm = Swig_typemap_lookup("in", n, name, 0))) {
+	Replaceall(tm, "$source", "args");
+	Replaceall(tm, "$target", name);
+	Replaceall(tm, "$input", "args");
+	Printv(f->code, tm, "\n", NIL);
+      } else {
+	throw_unhandled_ocaml_type_error(t, "varin/in");
+      }
+      Printf(f->code, "}\n");
+    }
+    // Now return the value of the variable (regardless
+    // of evaluating or setting)
+
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+      Replaceall(tm, "$source", name);
+      Replaceall(tm, "$target", "swig_result");
+      Replaceall(tm, "$result", "swig_result");
+      emit_action_code(n, f->code, tm);
+    } else if ((tm = Swig_typemap_lookup("out", n, name, 0))) {
+      Replaceall(tm, "$source", name);
+      Replaceall(tm, "$target", "swig_result");
+      Replaceall(tm, "$result", "swig_result");
+      Printf(f->code, "%s\n", tm);
+    } else {
+      throw_unhandled_ocaml_type_error(t, "varout/out");
+    }
+
+    Printf(f->code, "\nreturn swig_result;\n");
+    Printf(f->code, "}\n");
+
+    Wrapper_print(f, f_wrappers);
+
+    // Now add symbol to the Ocaml interpreter
+
+    if (GetFlag(n, "feature:immutable")) {
+      Printf(f_mlbody, "external _%s : c_obj -> Swig.c_obj = \"%s\" \n", mname, var_name);
+      Printf(f_mlibody, "val _%s : c_obj -> Swig.c_obj\n", iname);
+      if (const_enum) {
+	Printf(f_enum_to_int, " | `%s -> _%s C_void\n", mname, mname);
+	Printf(f_int_to_enum, " if y = (get_int (_%s C_void)) then `%s else\n", mname, mname);
+      }
+    } else {
+      Printf(f_mlbody, "external _%s : c_obj -> c_obj = \"%s\"\n", mname, var_name);
+      Printf(f_mlibody, "external _%s : c_obj -> c_obj = \"%s\"\n", mname, var_name);
+    }
+
+    Delete(var_name);
+    Delete(proc_name);
+    Delete(argnum);
+    Delete(arg);
+    Delete(tm2);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmemberfunctionHandler --
+   * Overridden to set static_member_function 
+   * ------------------------------------------------------------ */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    int rv;
+    static_member_function = 1;
+    rv = Language::staticmemberfunctionHandler(n);
+    static_member_function = 0;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   *
+   * The one trick here is that we have to make sure we rename the
+   * constant to something useful that doesn't collide with the
+   * original if any exists.
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *name = Getattr(n, "feature:symname");
+    SwigType *type = Getattr(n, "type");
+    String *value = Getattr(n, "value");
+    String *qvalue = Getattr(n, "qualified:value");
+    String *rvalue = NewString("");
+    String *temp = 0;
+
+    if (qvalue)
+      value = qvalue;
+
+    if (!name) {
+      name = mangleNameForCaml(Getattr(n, "name"));
+      Insert(name, 0, "_swig_wrap_");
+      Setattr(n, "feature:symname", name);
+    }
+    // See if there's a typemap
+
+    Printv(rvalue, value, NIL);
+    if ((SwigType_type(type) == T_CHAR) && (is_a_pointer(type) == 1)) {
+      temp = Copy(rvalue);
+      Clear(rvalue);
+      Printv(rvalue, "\"", temp, "\"", NIL);
+      Delete(temp);
+    }
+    if ((SwigType_type(type) == T_CHAR) && (is_a_pointer(type) == 0)) {
+      temp = Copy(rvalue);
+      Clear(rvalue);
+      Printv(rvalue, "'", temp, "'", NIL);
+      Delete(temp);
+    }
+    // Create variable and assign it a value
+
+    Printf(f_header, "static %s = ", SwigType_lstr(type, name));
+    if ((SwigType_type(type) == T_STRING)) {
+      Printf(f_header, "\"%s\";\n", value);
+    } else if (SwigType_type(type) == T_CHAR) {
+      Printf(f_header, "\'%s\';\n", value);
+    } else {
+      Printf(f_header, "%s;\n", value);
+    }
+
+    SetFlag(n, "feature:immutable");
+    variableWrapper(n);
+    return SWIG_OK;
+  }
+
+  int constructorHandler(Node *n) {
+    int ret;
+
+    in_constructor = 1;
+    ret = Language::constructorHandler(n);
+    in_constructor = 0;
+
+    return ret;
+  }
+
+  /* destructorHandler:
+   * Turn on destructor flag to inform decisions in functionWrapper
+   */
+
+  int destructorHandler(Node *n) {
+    int ret;
+
+    in_destructor = 1;
+    ret = Language::destructorHandler(n);
+    in_destructor = 0;
+
+    return ret;
+  }
+
+  /* copyconstructorHandler:
+   * Turn on constructor and copyconstructor flags for functionWrapper
+   */
+
+  int copyconstructorHandler(Node *n) {
+    int ret;
+
+    in_copyconst = 1;
+    in_constructor = 1;
+    ret = Language::copyconstructorHandler(n);
+    in_constructor = 0;
+    in_copyconst = 0;
+
+    return ret;
+  }
+
+    /**
+     * A simple, somewhat general purpose function for writing to multiple
+     * streams from a source template.  This allows the user to define the
+     * class definition in ways different from the one I have here if they
+     * want to.  It will also make the class definition system easier to
+     * fiddle with when I want to change methods, etc.
+     */
+
+  void Multiwrite(String *s) {
+    char *find_marker = strstr(Char(s), "(*Stream:");
+    while (find_marker) {
+      char *next = strstr(find_marker, "*)");
+      find_marker += strlen("(*Stream:");
+
+      if (next) {
+	int num_chars = next - find_marker;
+	String *stream_name = NewString(find_marker);
+	Delslice(stream_name, num_chars, Len(stream_name));
+	File *fout = Swig_filebyname(stream_name);
+	if (fout) {
+	  next += strlen("*)");
+	  char *following = strstr(next, "(*Stream:");
+	  find_marker = following;
+	  if (!following)
+	    following = next + strlen(next);
+	  String *chunk = NewString(next);
+	  Delslice(chunk, following - next, Len(chunk));
+	  Printv(fout, chunk, NIL);
+	}
+      }
+    }
+  }
+
+  bool isSimpleType(String *name) {
+    char *ch = Char(name);
+
+    return !(strchr(ch, '(') || strchr(ch, '<') || strchr(ch, ')') || strchr(ch, '>'));
+  }
+
+  /* We accept all chars in identifiers because we use strings to index
+   * them. */
+  int validIdentifier(String *name) {
+    return Len(name) > 0 ? 1 : 0;
+  }
+
+  /* classHandler
+   * 
+   * Create a "class" definition for ocaml.  I thought quite a bit about
+   * how I should do this part of it, and arrived here, using a function
+   * invocation to select a method, and dispatch.  This can obviously be
+   * done better, but I can't see how, given that I want to support 
+   * overloaded methods, out parameters, and operators.
+   *
+   * I needed a system that would do this:
+   *
+   *  a Be able to call these methods:
+   *   int foo( int x );
+   *   float foo( int x, int &out );
+   *
+   *  b Be typeable, even in the presence of mutually dependent classes.
+   *
+   *  c Support some form of operator invocation.
+   *
+   * (c) I chose strings for the method names so that "+=" would be a
+   * valid method name, and the somewhat natural << (invoke x) "+=" y >>
+   * would work.
+   *
+   * (a) (b) Since the c_obj type exists, it's easy to return C_int in one
+   * case and C_list [ C_float ; C_int ] in the other.  This makes tricky
+   * problems with out parameters disappear; they're simply appended to the
+   * return list.
+   *
+   * (b) Since every item that comes from C++ is the same type, there is no
+   * problem with the following:
+   *
+   * class Foo;
+   * class Bar { Foo *toFoo(); }
+   * class Foo { Bar *toBar(); }
+   *
+   * Since the Objective caml types of Foo and Bar are the same.  Now that
+   * I correctly incorporate SWIG's typechecking, this isn't a big deal.
+   *
+   * The class is in the form of a function returning a c_obj.  The c_obj
+   * is a C_obj containing a function which invokes a method on the
+   * underlying object given its type.
+   *
+   * The name emitted here is normalized before being sent to
+   * Callback.register, because we need this string to look up properly
+   * when the typemap passes the descriptor string.  I've been considering
+   * some, possibly more forgiving method that would do some transformations
+   * on the $descriptor in order to find a potential match.  This is for
+   * later.
+   *
+   * Important things to note:
+   *
+   * We rely on exception handling (BadMethodName) in order to call an
+   * ancestor.  This can be improved.
+   *
+   * The method used to get :classof could be improved to look at the type
+   * info that the base pointer contains.  It's really an error to have a
+   * SWIG-generated object that does not contain type info, since the
+   * existence of the object means that SWIG knows the type.
+   *
+   * :parents could use :classof to tell what class it is and make a better
+   * decision.  This could be nice, (i.e. provide a run-time graph of C++
+   * classes represented);.
+   *
+   * I can't think of a more elegant way of converting a C_obj fun to a
+   * pointer than "operator &"... 
+   *
+   * Added a 'sizeof' that will allow you to do the expected thing.
+   * This should help users to fill buffer structs and the like (as is
+   * typical in windows-styled code).  It's only enabled if you give
+   * %feature(sizeof) and then, only for simple types.
+   *
+   * Overall, carrying the list of methods and base classes has worked well.
+   * It allows me to give the Ocaml user introspection over their objects.
+   */
+
+  int classHandler(Node *n) {
+    String *name = Getattr(n, "name");
+
+    if (!name)
+      return SWIG_OK;
+
+    String *mangled_sym_name = mangleNameForCaml(name);
+    String *this_class_def = NewString(f_classtemplate);
+    String *name_normalized = normalizeTemplatedClassName(name);
+    String *old_class_ctors = f_class_ctors;
+    String *base_classes = NewString("");
+    f_class_ctors = NewString("");
+    bool sizeof_feature = generate_sizeof && isSimpleType(name);
+
+
+    classname = mangled_sym_name;
+    classmode = true;
+    int rv = Language::classHandler(n);
+    classmode = false;
+
+    if (sizeof_feature) {
+      Printf(f_wrappers,
+	     "SWIGEXT CAML_VALUE _wrap_%s_sizeof( CAML_VALUE args ) {\n"
+	     "    CAMLparam1(args);\n" "    CAMLreturn(Val_int(sizeof(%s)));\n" "}\n", mangled_sym_name, name_normalized);
+
+      Printf(f_mlbody, "external __%s_sizeof : unit -> int = " "\"_wrap_%s_sizeof\"\n", classname, mangled_sym_name);
+    }
+
+
+    /* Insert sizeof operator for concrete classes */
+    if (sizeof_feature) {
+      Printv(f_class_ctors, "\"sizeof\" , (fun args -> C_int (__", classname, "_sizeof ())) ;\n", NIL);
+    }
+    /* Handle up-casts in a nice way */
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist)) {
+      Iterator b;
+      b = First(baselist);
+      while (b.item) {
+	String *bname = Getattr(b.item, "name");
+	if (bname) {
+	  String *base_create = NewString("");
+	  Printv(base_create, "(create_class \"", bname, "\")", NIL);
+	  Printv(f_class_ctors, "   \"::", bname, "\", (fun args -> ", base_create, " args) ;\n", NIL);
+	  Printv(base_classes, base_create, " ;\n", NIL);
+	}
+	b = Next(b);
+      }
+    }
+
+    Replaceall(this_class_def, "$classname", classname);
+    Replaceall(this_class_def, "$normalized", name_normalized);
+    Replaceall(this_class_def, "$realname", name);
+    Replaceall(this_class_def, "$baselist", base_classes);
+    Replaceall(this_class_def, "$classbody", f_class_ctors);
+
+    Delete(f_class_ctors);
+    f_class_ctors = old_class_ctors;
+
+    // Actually write out the class definition
+
+    Multiwrite(this_class_def);
+
+    Setattr(n, "ocaml:ctor", classname);
+
+    return rv;
+  }
+
+  String *normalizeTemplatedClassName(String *name) {
+    String *name_normalized = SwigType_typedef_resolve_all(name);
+    bool took_action;
+
+    do {
+      took_action = false;
+
+      if (is_a_pointer(name_normalized)) {
+	SwigType_del_pointer(name_normalized);
+	took_action = true;
+      }
+
+      if (is_a_reference(name_normalized)) {
+	oc_SwigType_del_reference(name_normalized);
+	took_action = true;
+      }
+
+      if (is_an_array(name_normalized)) {
+	oc_SwigType_del_array(name_normalized);
+	took_action = true;
+      }
+    } while (took_action);
+
+    return SwigType_str(name_normalized, 0);
+  }
+
+  /*
+   * Produce the symbol name that ocaml will use when referring to the 
+   * target item.  I wonder if there's a better way to do this:
+   *
+   * I shudder to think about doing it with a hash lookup, but that would
+   * make a couple of things easier:
+   */
+
+  String *mangleNameForCaml(String *s) {
+    String *out = Copy(s);
+    Replaceall(out, " ", "_xx");
+    Replaceall(out, "::", "_xx");
+    Replaceall(out, ",", "_x");
+    Replaceall(out, "+", "_xx_plus");
+    Replaceall(out, "-", "_xx_minus");
+    Replaceall(out, "<", "_xx_ldbrace");
+    Replaceall(out, ">", "_xx_rdbrace");
+    Replaceall(out, "!", "_xx_not");
+    Replaceall(out, "%", "_xx_mod");
+    Replaceall(out, "^", "_xx_xor");
+    Replaceall(out, "*", "_xx_star");
+    Replaceall(out, "&", "_xx_amp");
+    Replaceall(out, "|", "_xx_or");
+    Replaceall(out, "(", "_xx_lparen");
+    Replaceall(out, ")", "_xx_rparen");
+    Replaceall(out, "[", "_xx_lbrace");
+    Replaceall(out, "]", "_xx_rbrace");
+    Replaceall(out, "~", "_xx_bnot");
+    Replaceall(out, "=", "_xx_equals");
+    Replaceall(out, "/", "_xx_slash");
+    Replaceall(out, ".", "_xx_dot");
+    return out;
+  }
+
+  String *fully_qualify_enum_name(Node *n, String *name) {
+    Node *parent = 0;
+    String *qualification = NewString("");
+    String *fully_qualified_name = NewString("");
+    String *parent_type = 0;
+    String *normalized_name;
+
+    parent = parentNode(n);
+    while (parent) {
+      parent_type = nodeType(parent);
+      if (Getattr(parent, "name")) {
+	String *parent_copy = NewStringf("%s::", Getattr(parent, "name"));
+	if (!Cmp(parent_type, "class") || !Cmp(parent_type, "namespace"))
+	  Insert(qualification, 0, parent_copy);
+	Delete(parent_copy);
+      }
+      if (!Cmp(parent_type, "class"))
+	break;
+      parent = parentNode(parent);
+    }
+
+    Printf(fully_qualified_name, "%s%s", qualification, name);
+
+    normalized_name = normalizeTemplatedClassName(fully_qualified_name);
+    if (!strncmp(Char(normalized_name), "enum ", 5)) {
+      Insert(normalized_name, 5, qualification);
+    }
+
+    return normalized_name;
+  }
+
+  /* Benedikt Grundmann inspired --> Enum wrap styles */
+
+  int enumvalueDeclaration(Node *n) {
+    String *name = Getattr(n, "name");
+    String *qvalue = 0;
+
+    if (name_qualifier) {
+      qvalue = Copy(name_qualifier);
+      Printv(qvalue, name, NIL);
+    }
+
+    if (const_enum && name && !Getattr(seen_enumvalues, name)) {
+      Setattr(seen_enumvalues, name, "true");
+      SetFlag(n, "feature:immutable");
+      Setattr(n, "feature:enumvalue", "1");	// this does not appear to be used
+
+      if (qvalue)
+	Setattr(n, "qualified:value", qvalue);
+
+      String *evname = SwigType_manglestr(qvalue);
+      Insert(evname, 0, "SWIG_ENUM_");
+
+      Setattr(n, "feature:enumvname", name);
+      Setattr(n, "feature:symname", evname);
+      Delete(evname);
+      Printf(f_enumtypes_value, "| `%s\n", name);
+
+      return Language::enumvalueDeclaration(n);
+    } else
+      return SWIG_OK;
+  }
+
+  /* -------------------------------------------------------------------
+   * This function is a bit uglier than it deserves.
+   *
+   * I used to direct lookup the name of the enum.  Now that certain fixes
+   * have been made in other places, the names of enums are now fully
+   * qualified, which is a good thing, overall, but requires me to do
+   * some legwork.
+   *
+   * The other thing that uglifies this function is the varying way that
+   * typedef enum and enum are handled.  I need to produce consistent names,
+   * which means looking up and registering by typedef and enum name. */
+  int enumDeclaration(Node *n) {
+    String *name = Getattr(n, "name");
+    String *oname = name ? NewString(name) : NULL;
+    /* name is now fully qualified */
+    String *fully_qualified_name = NewString(name);
+    bool seen_enum = false;
+    if (name_qualifier)
+      Delete(name_qualifier);
+    char *strip_position;
+    name_qualifier = fully_qualify_enum_name(n, NewString(""));
+
+    /* Recent changes have distrubed enum and template naming again.
+     * Will try to keep it consistent by can't guarantee much given
+     * that these things move around a lot.
+     *
+     * I need to figure out a way to isolate this module better.
+     */
+    if (oname) {
+      strip_position = strstr(Char(oname), "::");
+
+      while (strip_position) {
+	strip_position += 2;
+	oname = NewString(strip_position);
+	strip_position = strstr(Char(oname), "::");
+      }
+    }
+
+    seen_enum = oname ? (Getattr(seen_enums, fully_qualified_name) ? true : false) : false;
+
+    if (oname && !seen_enum) {
+      const_enum = true;
+      Printf(f_enum_to_int, "| `%s -> (match y with\n", oname);
+      Printf(f_int_to_enum, "| `%s -> C_enum (\n", oname);
+      /* * * * A note about enum name resolution * * * *
+       * This code should now work, but I think we can do a bit better.
+       * The problem I'm having is that swig isn't very precise about
+       * typedef name resolution.  My opinion is that SwigType_typedef
+       * resolve_all should *always* return the enum tag if one exists,
+       * rather than the admittedly friendlier enclosing typedef.
+       * 
+       * This would make one of the cases below unnecessary. 
+       * * * */
+      Printf(f_mlbody, "let _ = Callback.register \"%s_marker\" (`%s)\n", fully_qualified_name, oname);
+      if (!strncmp(Char(fully_qualified_name), "enum ", 5)) {
+	String *fq_noenum = NewString(Char(fully_qualified_name) + 5);
+	Printf(f_mlbody,
+	       "let _ = Callback.register \"%s_marker\" (`%s)\n" "let _ = Callback.register \"%s_marker\" (`%s)\n", fq_noenum, oname, fq_noenum, name);
+      }
+
+      Printf(f_enumtypes_type, "| `%s\n", oname);
+      Insert(fully_qualified_name, 0, "enum ");
+      Setattr(seen_enums, fully_qualified_name, n);
+    }
+
+    int ret = Language::enumDeclaration(n);
+
+    if (const_enum) {
+      Printf(f_int_to_enum, "`Int y)\n");
+      Printf(f_enum_to_int, "| `Int x -> Swig.C_int x\n" "| _ -> raise (LabelNotFromThisEnum v))\n");
+    }
+
+    const_enum = false;
+
+    return ret;
+  }
+
+  /* ----------------------------------------------------------------------------
+   * BEGIN C++ Director Class modifications
+   * ------------------------------------------------------------------------- */
+
+  /*
+   * Modified polymorphism code for Ocaml language module.
+   * Original:
+   * C++/Python polymorphism demo code, copyright (C) 2002 Mark Rose 
+   * <mrose@stm.lbl.gov>
+   *
+   * TODO
+   *
+   * Move some boilerplate code generation to Swig_...() functions.
+   *
+   */
+
+  /* ---------------------------------------------------------------
+   * classDirectorMethod()
+   *
+   * Emit a virtual director method to pass a method call on to the 
+   * underlying Python object.
+   *
+   * --------------------------------------------------------------- */
+
+  int classDirectorMethod(Node *n, Node *parent, String *super) {
+    int is_void = 0;
+    int is_pointer = 0;
+    String *storage;
+    String *value;
+    String *decl;
+    String *type;
+    String *name;
+    String *classname;
+    String *c_classname = Getattr(parent, "name");
+    String *declaration;
+    ParmList *l;
+    Wrapper *w;
+    String *tm;
+    String *wrap_args = NewString("");
+    String *return_type;
+    int status = SWIG_OK;
+    int idx;
+    bool pure_virtual = false;
+    bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
+
+    storage = Getattr(n, "storage");
+    value = Getattr(n, "value");
+    classname = Getattr(parent, "sym:name");
+    type = Getattr(n, "type");
+    name = Getattr(n, "name");
+
+    if (Cmp(storage, "virtual") == 0) {
+      if (Cmp(value, "0") == 0) {
+	pure_virtual = true;
+      }
+    }
+
+    w = NewWrapper();
+    declaration = NewString("");
+    Wrapper_add_local(w, "swig_result", "CAMLparam0();\n" "SWIG_CAMLlocal2(swig_result,args)");
+
+    /* determine if the method returns a pointer */
+    decl = Getattr(n, "decl");
+    is_pointer = SwigType_ispointer_return(decl);
+    is_void = (!Cmp(type, "void") && !is_pointer);
+
+    /* form complete return type */
+    return_type = Copy(type);
+    {
+      SwigType *t = Copy(decl);
+      SwigType *f = 0;
+      f = SwigType_pop_function(t);
+      SwigType_push(return_type, t);
+      Delete(f);
+      Delete(t);
+    }
+
+    /* virtual method definition */
+    l = Getattr(n, "parms");
+    String *target;
+    String *pclassname = NewStringf("SwigDirector_%s", classname);
+    String *qualified_name = NewStringf("%s::%s", pclassname, name);
+    SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type;
+    target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0);
+    Printf(w->def, "%s {", target);
+    Delete(qualified_name);
+    Delete(target);
+    /* header declaration */
+    target = Swig_method_decl(rtype, decl, name, l, 0, 1);
+    Printf(declaration, "    virtual %s;", target);
+    Delete(target);
+
+    /* declare method return value 
+     * if the return value is a reference or const reference, a specialized typemap must
+     * handle it, including declaration of c_result ($result).
+     */
+    if (!is_void) {
+      if (!(ignored_method && !pure_virtual)) {
+	Wrapper_add_localv(w, "c_result", SwigType_lstr(return_type, "c_result"), NIL);
+      }
+    }
+
+    if (ignored_method) {
+      if (!pure_virtual) {
+	if (!is_void)
+	  Printf(w->code, "return ");
+	String *super_call = Swig_method_call(super, l);
+	Printf(w->code, "%s;\n", super_call);
+	Delete(super_call);
+      } else {
+	Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname),
+	       SwigType_namestr(name));
+      }
+    } else {
+      /* attach typemaps to arguments (C/C++ -> Ocaml) */
+      String *arglist = NewString("");
+
+      Swig_typemap_attach_parms("in", l, 0);
+      Swig_typemap_attach_parms("directorin", l, 0);
+      Swig_typemap_attach_parms("directorargout", l, w);
+
+      Parm *p;
+      int num_arguments = emit_num_arguments(l);
+      int i;
+      char source[256];
+
+      int outputs = 0;
+      if (!is_void)
+	outputs++;
+
+      /* build argument list and type conversion string */
+      for (i = 0, idx = 0, p = l; i < num_arguments; i++) {
+
+	while (Getattr(p, "tmap:ignore")) {
+	  p = Getattr(p, "tmap:ignore:next");
+	}
+
+	if (Getattr(p, "tmap:directorargout") != 0)
+	  outputs++;
+
+	String *pname = Getattr(p, "name");
+	String *ptype = Getattr(p, "type");
+
+	Putc(',', arglist);
+	if ((tm = Getattr(p, "tmap:directorin")) != 0) {
+	  Replaceall(tm, "$input", pname);
+	  Replaceall(tm, "$owner", "0");
+	  if (Len(tm) == 0)
+	    Append(tm, pname);
+	  Printv(wrap_args, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:directorin:next");
+	  continue;
+	} else if (Cmp(ptype, "void")) {
+	  /* special handling for pointers to other C++ director classes.
+	   * ideally this would be left to a typemap, but there is currently no
+	   * way to selectively apply the dynamic_cast<> to classes that have
+	   * directors.  in other words, the type "SwigDirector_$1_lname" only exists
+	   * for classes with directors.  we avoid the problem here by checking
+	   * module.wrap::directormap, but it's not clear how to get a typemap to
+	   * do something similar.  perhaps a new default typemap (in addition
+	   * to SWIGTYPE) called DIRECTORTYPE?
+	   */
+	  if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) {
+	    Node *module = Getattr(parent, "module");
+	    Node *target = Swig_directormap(module, ptype);
+	    sprintf(source, "obj%d", idx++);
+	    String *nonconst = 0;
+	    /* strip pointer/reference --- should move to Swig/stype.c */
+	    String *nptype = NewString(Char(ptype) + 2);
+	    /* name as pointer */
+	    String *ppname = Copy(pname);
+	    if (SwigType_isreference(ptype)) {
+	      Insert(ppname, 0, "&");
+	    }
+	    /* if necessary, cast away const since Python doesn't support it! */
+	    if (SwigType_isconst(nptype)) {
+	      nonconst = NewStringf("nc_tmp_%s", pname);
+	      String *nonconst_i = NewStringf("= const_cast<%s>(%s)", SwigType_lstr(ptype, 0), ppname);
+	      Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL);
+	      Delete(nonconst_i);
+	      Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number,
+			   "Target language argument '%s' discards const in director method %s::%s.\n", SwigType_str(ptype, pname),
+			   SwigType_namestr(c_classname), SwigType_namestr(name));
+	    } else {
+	      nonconst = Copy(ppname);
+	    }
+	    Delete(nptype);
+	    Delete(ppname);
+	    String *mangle = SwigType_manglestr(ptype);
+	    if (target) {
+	      String *director = NewStringf("director_%s", mangle);
+	      Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL);
+	      Wrapper_add_localv(w, source, "CAML_VALUE", source, "= Val_unit", NIL);
+	      Printf(wrap_args, "%s = dynamic_cast<Swig::Director *>(%s);\n", director, nonconst);
+	      Printf(wrap_args, "if (!%s) {\n", director);
+	      Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
+	      Printf(wrap_args, "} else {\n");
+	      Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director);
+	      Printf(wrap_args, "}\n");
+	      Delete(director);
+	      Printv(arglist, source, NIL);
+	    } else {
+	      Wrapper_add_localv(w, source, "CAML_VALUE", source, "= Val_unit", NIL);
+	      Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
+	      //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", 
+	      //       source, nonconst, base);
+	      Printv(arglist, source, NIL);
+	    }
+	    Delete(mangle);
+	    Delete(nonconst);
+	  } else {
+	    Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
+			 "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0),
+			 SwigType_namestr(c_classname), SwigType_namestr(name));
+	    status = SWIG_NOWRAP;
+	    break;
+	  }
+	}
+	p = nextSibling(p);
+      }
+
+      Printv(w->code, "swig_result = Val_unit;\n", 0);
+      Printf(w->code, "args = Val_unit;\n");
+
+      /* wrap complex arguments to values */
+      Printv(w->code, wrap_args, NIL);
+
+      /* pass the method call on to the Python object */
+      Printv(w->code,
+	     "swig_result = caml_swig_alloc(1,C_list);\n" "SWIG_Store_field(swig_result,0,args);\n" "args = swig_result;\n" "swig_result = Val_unit;\n", 0);
+      Printf(w->code, "swig_result = " "callback3(*caml_named_value(\"swig_runmethod\")," "swig_get_self(),copy_string(\"%s\"),args);\n", Getattr(n, "name"));
+      /* exception handling */
+      tm = Swig_typemap_lookup("director:except", n, "result", 0);
+      if (!tm) {
+	tm = Getattr(n, "feature:director:except");
+      }
+      if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) {
+	Printf(w->code, "if (result == NULL) {\n");
+	Printf(w->code, "  CAML_VALUE error = *caml_named_value(\"director_except\");\n");
+	Replaceall(tm, "$error", "error");
+	Printv(w->code, Str(tm), "\n", NIL);
+	Printf(w->code, "}\n");
+      }
+
+      /*
+       * Python method may return a simple object, or a tuple.
+       * for in/out aruments, we have to extract the appropriate values from the 
+       * argument list, then marshal everything back to C/C++ (return value and
+       * output arguments).
+       */
+
+      /* marshal return value and other outputs (if any) from value to C/C++ 
+       * type */
+
+      String *cleanup = NewString("");
+      String *outarg = NewString("");
+
+      idx = 0;
+
+      /* this seems really silly.  the node's type excludes 
+       * qualifier/pointer/reference markers, which have to be retrieved 
+       * from the decl field to construct return_type.  but the typemap
+       * lookup routine uses the node's type, so we have to swap in and
+       * out the correct type.  it's not just me, similar silliness also
+       * occurs in Language::cDeclaration().
+       */
+      Setattr(n, "type", return_type);
+      tm = Swig_typemap_lookup("directorout", n, "c_result", w);
+      Setattr(n, "type", type);
+      if (tm == 0) {
+	String *name = NewString("c_result");
+	tm = Swig_typemap_search("directorout", return_type, name, NULL);
+	Delete(name);
+      }
+      if (tm != 0) {
+	Replaceall(tm, "$input", "swig_result");
+	/* TODO check this */
+	if (Getattr(n, "wrap:disown")) {
+	  Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	} else {
+	  Replaceall(tm, "$disown", "0");
+	}
+	Replaceall(tm, "$result", "c_result");
+	Printv(w->code, tm, "\n", NIL);
+      }
+
+      /* marshal outputs */
+      for (p = l; p;) {
+	if ((tm = Getattr(p, "tmap:directorargout")) != 0) {
+	  Replaceall(tm, "$input", "swig_result");
+	  Replaceall(tm, "$result", Getattr(p, "name"));
+	  Printv(w->code, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:directorargout:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+
+      Delete(arglist);
+      Delete(cleanup);
+      Delete(outarg);
+    }
+
+    /* any existing helper functions to handle this? */
+    if (!is_void) {
+      if (!(ignored_method && !pure_virtual)) {
+	/* A little explanation:
+	 * The director_enum test case makes a method whose return type
+	 * is an enum type.  return_type here is "int".  gcc complains
+	 * about an implicit enum conversion, and although i don't strictly
+	 * agree with it, I'm working on fixing the error:
+	 *
+	 * Below is what I came up with.  It's not great but it should
+	 * always essentially work.
+	 */
+	if (!SwigType_isreference(return_type)) {
+	  Printf(w->code, "CAMLreturn_type((%s)c_result);\n", SwigType_lstr(return_type, ""));
+	} else {
+	  Printf(w->code, "CAMLreturn_type(*c_result);\n");
+	}
+      }
+    }
+
+    Printf(w->code, "}\n");
+
+    // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method
+    String *inline_extra_method = NewString("");
+    if (dirprot_mode() && !is_public(n) && !pure_virtual) {
+      Printv(inline_extra_method, declaration, NIL);
+      String *extra_method_name = NewStringf("%sSwigPublic", name);
+      Replaceall(inline_extra_method, name, extra_method_name);
+      Replaceall(inline_extra_method, ";\n", " {\n      ");
+      if (!is_void)
+	Printf(inline_extra_method, "return ");
+      String *methodcall = Swig_method_call(super, l);
+      Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
+      Delete(methodcall);
+      Delete(extra_method_name);
+    }
+
+    /* emit the director method */
+    if (status == SWIG_OK) {
+      if (!Getattr(n, "defaultargs")) {
+	Wrapper_print(w, f_directors);
+	Printv(f_directors_h, declaration, NIL);
+	Printv(f_directors_h, inline_extra_method, NIL);
+      }
+    }
+
+    /* clean up */
+    Delete(wrap_args);
+    Delete(return_type);
+    Delete(pclassname);
+    DelWrapper(w);
+    return status;
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorConstructor(Node *n) {
+    Node *parent = Getattr(n, "parentNode");
+    String *sub = NewString("");
+    String *decl = Getattr(n, "decl");
+    String *supername = Swig_class_name(parent);
+    String *classname = NewString("");
+    Printf(classname, "SwigDirector_%s", supername);
+
+    /* insert self parameter */
+    Parm *p, *q;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms = CopyParmList(superparms);
+    String *type = NewString("CAML_VALUE");
+    p = NewParm(type, NewString("self"));
+    q = Copy(p);
+    set_nextSibling(q, superparms);
+    set_nextSibling(p, parms);
+    parms = p;
+
+    if (!Getattr(n, "defaultargs")) {
+      /* constructor */
+      {
+	Wrapper *w = NewWrapper();
+	String *call;
+	String *basetype = Getattr(parent, "classtype");
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 0);
+	call = Swig_csuperclass_call(0, basetype, superparms);
+	Printf(w->def, "%s::%s: %s, Swig::Director(self) { }", classname, target, call);
+	Delete(target);
+	Wrapper_print(w, f_directors);
+	Delete(call);
+	DelWrapper(w);
+      }
+
+      /* constructor header */
+      {
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 1);
+	Printf(f_directors_h, "    %s;\n", target);
+	Delete(target);
+      }
+    }
+
+    Setattr(n, "parms", q);
+    Language::classDirectorConstructor(n);
+
+    Delete(sub);
+    Delete(classname);
+    Delete(supername);
+    //Delete(parms);        
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorDefaultConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorDefaultConstructor(Node *n) {
+    String *classname;
+    classname = Swig_class_name(n);
+
+    /* insert self parameter */
+    Parm *p, *q;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms = CopyParmList(superparms);
+    String *type = NewString("CAML_VALUE");
+    p = NewParm(type, NewString("self"));
+    q = Copy(p);
+    set_nextSibling(p, parms);
+    parms = p;
+
+    {
+      Wrapper *w = NewWrapper();
+      Printf(w->def, "SwigDirector_%s::SwigDirector_%s(CAML_VALUE self) : Swig::Director(self) { }", classname, classname);
+      Wrapper_print(w, f_directors);
+      DelWrapper(w);
+    }
+    Printf(f_directors_h, "    SwigDirector_%s(CAML_VALUE self);\n", classname);
+    Delete(classname);
+    Setattr(n, "parms", q);
+    return Language::classDirectorDefaultConstructor(n);
+  }
+
+  int classDirectorInit(Node *n) {
+    String *declaration = Swig_director_declaration(n);
+    Printf(f_directors_h, "\n" "%s\n" "public:\n", declaration);
+    Delete(declaration);
+    return Language::classDirectorInit(n);
+  }
+
+  int classDirectorEnd(Node *n) {
+    Printf(f_directors_h, "};\n\n");
+    return Language::classDirectorEnd(n);
+  }
+
+  /* ---------------------------------------------------------------------
+   * typedefHandler
+   *
+   * This is here in order to maintain the correct association between
+   * typedef names and enum names. 
+   *
+   * Since I implement enums as polymorphic variant tags, I need to call
+   * back into ocaml to evaluate them.  This requires a string that can
+   * be generated in the typemaps, and also at SWIG time to be the same
+   * string.  The problem that arises is that SWIG variously generates
+   * enum e_name_tag
+   * e_name_tag
+   * e_typedef_name
+   * for
+   * typedef enum e_name_tag { ... } e_typedef_name;
+   * 
+   * Since I need these strings to be consistent, I must maintain a correct
+   * association list between typedef and enum names.
+   * --------------------------------------------------------------------- */
+  int typedefHandler(Node *n) {
+    String *type = Getattr(n, "type");
+    Node *enum_node = type ? Getattr(seen_enums, type) : 0;
+    if (enum_node) {
+      String *name = Getattr(enum_node, "name");
+
+      Printf(f_mlbody, "let _ = Callback.register \"%s_marker\" (`%s)\n", Getattr(n, "name"), name);
+
+    }
+    return SWIG_OK;
+  }
+
+  String *runtimeCode() {
+    String *s = Swig_include_sys("ocaml.swg");
+    if (!s) {
+      Printf(stderr, "*** Unable to open 'ocaml.swg'\n");
+      s = NewString("");
+    }
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigocamlrun.h");
+  }
+};
+
+/* -------------------------------------------------------------------------
+ * swig_ocaml()    - Instantiate module
+ * ------------------------------------------------------------------------- */
+
+static Language *new_swig_ocaml() {
+  return new OCAML();
+}
+extern "C" Language *swig_ocaml(void) {
+  return new_swig_ocaml();
+}
diff --git a/trunk/Source/Modules/octave.cxx b/trunk/Source/Modules/octave.cxx
new file mode 100644
index 0000000..d582e8a
--- /dev/null
+++ b/trunk/Source/Modules/octave.cxx
@@ -0,0 +1,1398 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * octave.cxx
+ *
+ * Octave language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_octave_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+static const char *usage = (char *) "\
+Octave Options (available with -octave)\n\
+     (none yet)\n\n";
+
+
+class OCTAVE:public Language {
+private:
+  File *f_runtime;
+  File *f_header;
+  File *f_doc;
+  File *f_wrappers;
+  File *f_init;
+  File *f_initbeforefunc;
+  File *f_directors;
+  File *f_directors_h;
+  String *s_global_tab;
+  String *s_members_tab;
+  String *class_name;
+
+  int have_constructor;
+  int have_destructor;
+  String *constructor_name;
+
+  Hash *docs;
+
+public:
+   OCTAVE():f_runtime(0), f_header(0), f_doc(0), f_wrappers(0),
+	    f_init(0), f_initbeforefunc(0), f_directors(0), f_directors_h(0), 
+	    s_global_tab(0), s_members_tab(0), class_name(0) {
+     enable_cplus_runtime_mode();
+     allow_overloading();
+     director_multiple_inheritance = 1;
+     director_language = 1;
+     docs = NewHash();
+   }
+
+  virtual void main(int argc, char *argv[]) {
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stderr);
+	}
+      }
+    }
+
+    SWIG_library_directory("octave");
+    Preprocessor_define("SWIGOCTAVE 1", 0);
+    SWIG_config_file("octave.swg");
+    SWIG_typemap_lang("octave");
+    allow_overloading();
+  }
+
+  virtual int top(Node *n) {
+    {
+      Node *mod = Getattr(n, "module");
+      if (mod) {
+	Node *options = Getattr(mod, "options");
+	if (options) {
+	  int dirprot = 0;
+	  if (Getattr(options, "dirprot")) {
+	    dirprot = 1;
+	  }
+	  if (Getattr(options, "nodirprot")) {
+	    dirprot = 0;
+	  }
+	  if (Getattr(options, "directors")) {
+	    allow_directors();
+	    if (dirprot)
+	      allow_dirprot();
+	  }
+	}
+      }
+    }
+
+    String *module = Getattr(n, "name");
+    String *outfile = Getattr(n, "outfile");
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_header = NewString("");
+    f_doc = NewString("");
+    f_wrappers = NewString("");
+    f_init = NewString("");
+    f_initbeforefunc = NewString("");
+    f_directors_h = NewString("");
+    f_directors = NewString("");
+    s_global_tab = NewString("");
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("doc", f_doc);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("initbeforefunc", f_initbeforefunc);
+    Swig_register_filebyname("director", f_directors);
+    Swig_register_filebyname("director_h", f_directors_h);
+    Swig_banner(f_runtime);
+    Printf(f_runtime, "#define SWIG_name_d      \"%s\"\n", module);
+    Printf(f_runtime, "#define SWIG_name        %s\n", module);
+
+    if (directorsEnabled()) {
+      Swig_banner(f_directors_h);
+      if (dirprot_mode()) {
+	//      Printf(f_directors_h, "#include <map>\n");
+	//      Printf(f_directors_h, "#include <string>\n\n");
+      }
+    }
+
+
+    Printf(s_global_tab, "\nstatic const struct swig_octave_member swig_globals[] = {\n");
+    Printf(f_init, "static void SWIG_init_user(octave_swig_type* module_ns)\n{\n");
+
+    if (!CPlusPlus)
+      Printf(f_header,"extern \"C\" {\n");
+
+    Language::top(n);
+
+    if (!CPlusPlus)
+      Printf(f_header,"}\n");
+
+    if (Len(docs))
+      emit_doc_texinfo();
+
+    if (directorsEnabled())
+      Swig_insert_file("director.swg", f_runtime);
+
+    Printf(f_init, "}\n");
+    Printf(s_global_tab, "{0,0,0,0,0}\n};\n");
+
+    Printv(f_wrappers, s_global_tab, NIL);
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+    Dump(f_header, f_runtime);
+    Dump(f_doc, f_runtime);
+    if (directorsEnabled()) {
+      Dump(f_directors_h, f_runtime);
+      Dump(f_directors, f_runtime);
+    }
+    Dump(f_wrappers, f_runtime);
+    Dump(f_initbeforefunc, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+
+    Delete(s_global_tab);
+    Delete(f_initbeforefunc);
+    Delete(f_init);
+    Delete(f_wrappers);
+    Delete(f_doc);
+    Delete(f_header);
+    Delete(f_directors);
+    Delete(f_directors_h);
+    Close(f_runtime);
+    Delete(f_runtime);
+
+    return SWIG_OK;
+  }
+
+  String *texinfo_escape(String *_s) {
+    const char* s=(const char*)Data(_s);
+    while (*s&&(*s=='\t'||*s=='\r'||*s=='\n'||*s==' '))
+      ++s;
+    String *r = NewString("");
+    for (int j=0;s[j];++j) {
+      if (s[j] == '\n') {
+	Append(r, "\\n\\\n");
+      } else if (s[j] == '\r') {
+	Append(r, "\\r");
+      } else if (s[j] == '\t') {
+	Append(r, "\\t");
+      } else if (s[j] == '\\') {
+	Append(r, "\\\\");
+      } else if (s[j] == '\'') {
+	Append(r, "\\\'");
+      } else if (s[j] == '\"') {
+	Append(r, "\\\"");
+      } else
+	Putc(s[j], r);
+    }
+    return r;
+  }
+  void emit_doc_texinfo() {
+    for (Iterator it = First(docs); it.key; it = Next(it)) {
+      String *wrap_name = it.key;
+
+      String *synopsis = Getattr(it.item, "synopsis");
+      String *decl_info = Getattr(it.item, "decl_info");
+      String *cdecl_info = Getattr(it.item, "cdecl_info");
+      String *args_info = Getattr(it.item, "args_info");
+
+      String *doc_str = NewString("");
+      Printv(doc_str, synopsis, decl_info, cdecl_info, args_info, NIL);
+      String *escaped_doc_str = texinfo_escape(doc_str);
+
+      if (Len(doc_str)>0) {
+	Printf(f_doc,"const char* %s_texinfo = ",wrap_name);
+	Printf(f_doc,"\"-*- texinfo -*-\\n\\\n%s", escaped_doc_str);
+	if (Len(decl_info))
+	  Printf(f_doc,"\\n\\\n@end deftypefn");
+	Printf(f_doc,"\";\n");
+      }
+
+      Delete(escaped_doc_str);
+      Delete(doc_str);
+      Delete(wrap_name);
+    }
+    Printf(f_doc,"\n");
+  }
+  bool is_empty_doc_node(Node* n) {
+    if (!n)
+      return true;
+    String *synopsis = Getattr(n, "synopsis");
+    String *decl_info = Getattr(n, "decl_info");
+    String *cdecl_info = Getattr(n, "cdecl_info");
+    String *args_info = Getattr(n, "args_info");
+    return !Len(synopsis) && !Len(decl_info) && 
+      !Len(cdecl_info) && !Len(args_info);
+  }
+  String *texinfo_name(Node* n) {
+    String *tname = NewString("");
+    String *iname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(iname);
+    Node* d = Getattr(docs, wname);
+
+    if (is_empty_doc_node(d))
+      Printf(tname, "0");
+    else
+      Printf(tname, "%s_texinfo", wname);
+
+    return tname;
+  }
+  void process_autodoc(Node *n) {
+    String *iname = Getattr(n, "sym:name");
+    String *name = Getattr(n, "name");
+    String *wname = Swig_name_wrapper(iname);
+    String *str = Getattr(n, "feature:docstring");
+    bool autodoc_enabled = !Cmp(Getattr(n, "feature:autodoc"), "1");
+    Node* d = Getattr(docs, wname);
+    if (!d) {
+      d = NewHash();
+      Setattr(d, "synopsis", NewString(""));
+      Setattr(d, "decl_info", NewString(""));
+      Setattr(d, "cdecl_info", NewString(""));
+      Setattr(d, "args_info", NewString(""));
+      Setattr(docs, wname, d);
+    }
+
+    String *synopsis = Getattr(d, "synopsis");
+    String *decl_info = Getattr(d, "decl_info");
+    //    String *cdecl_info = Getattr(d, "cdecl_info");
+    String *args_info = Getattr(d, "args_info");
+
+    // * couldn't we just emit the docs here?
+
+    if (autodoc_enabled) {
+      String *decl_str = NewString("");
+      String *args_str = NewString("");
+      make_autodocParmList(n, decl_str, args_str);
+      Append(decl_info, "@deftypefn {Loadable Function} ");
+
+      SwigType *type = Getattr(n, "type");
+      if (type && Strcmp(type, "void")) {
+	type = SwigType_base(type);
+	Node *lookup = Swig_symbol_clookup(type, 0);
+	if (lookup)
+	  type = Getattr(lookup, "sym:name");
+	Append(decl_info, "@var{retval} = ");
+	String *type_str = NewString("");
+	Printf(type_str, "@var{retval} is of type %s. ", type);
+	Append(args_str, type_str);
+	Delete(type_str);
+      }
+
+      Append(decl_info, name);
+      Append(decl_info, " (");
+      Append(decl_info, decl_str);
+      Append(decl_info, ")\n");
+      Append(args_info, args_str);
+      Delete(decl_str);
+      Delete(args_str);
+    }
+
+    if (str && Len(str) > 0) {
+      // strip off {} if necessary
+      char *t = Char(str);
+      if (*t == '{') {
+	Delitem(str, 0);
+	Delitem(str, DOH_END);
+      }
+
+      // emit into synopsis section
+      Append(synopsis, str);
+    }
+  }
+
+  virtual int importDirective(Node *n) {
+    String *modname = Getattr(n, "module");
+    if (modname)
+      Printf(f_init, "feval(\"%s\",octave_value_list(),0);\n", modname);
+    return Language::importDirective(n);
+  }
+
+  const char *get_implicitconv_flag(Node *n) {
+    int conv = 0;
+    if (n && GetFlag(n, "feature:implicitconv")) {
+      conv = 1;
+    }
+    return conv ? "SWIG_POINTER_IMPLICIT_CONV" : "0";
+  }
+
+  void make_autodocParmList(Node *n, String *decl_str, String *args_str) {
+    String *pdocs = Copy(Getattr(n, "feature:pdocs"));
+    ParmList *plist = CopyParmList(Getattr(n, "parms"));
+    Parm *p;
+    Parm *pnext;
+    Node *lookup;
+
+    if (pdocs)
+      Append(pdocs, "\n");
+
+    Swig_typemap_attach_parms("in", plist, 0);
+    Swig_typemap_attach_parms("doc", plist, 0);
+
+    for (p = plist; p; p = pnext) {
+      String *name = 0;
+      String *type = 0;
+      String *value = 0;
+      String *ptype = 0;
+      String *pdoc = Getattr(p, "tmap:doc");
+      if (pdoc) {
+	name = Getattr(p, "tmap:doc:name");
+	type = Getattr(p, "tmap:doc:type");
+	value = Getattr(p, "tmap:doc:value");
+	ptype = Getattr(p, "tmap:doc:pytype");
+      }
+
+      name = name ? name : Getattr(p, "name");
+      type = type ? type : Getattr(p, "type");
+      value = value ? value : Getattr(p, "value");
+
+      String *tex_name = NewString("");
+      if (name)
+	Printf(tex_name, "@var{%s}", name);
+      else
+	Printf(tex_name, "@var{?}");
+
+      String *tm = Getattr(p, "tmap:in");
+      if (tm) {
+	pnext = Getattr(p, "tmap:in:next");
+      } else {
+	pnext = nextSibling(p);
+      }
+
+      if (Len(decl_str))
+	Append(decl_str, ", ");
+      Append(decl_str, tex_name);
+
+      if (value) {
+	if (Strcmp(value, "NULL") == 0)
+	  value = NewString("nil");
+	else if (Strcmp(value, "true") == 0 || Strcmp(value, "TRUE") == 0)
+	  value = NewString("true");
+	else if (Strcmp(value, "false") == 0 || Strcmp(value, "FALSE") == 0)
+	  value = NewString("false");
+	else {
+	  lookup = Swig_symbol_clookup(value, 0);
+	  if (lookup)
+	    value = Getattr(lookup, "sym:name");
+	}
+	Printf(decl_str, " = %s", value);
+      }
+
+      if (type) {
+	String *type_str = NewString("");
+	type = SwigType_base(type);
+	lookup = Swig_symbol_clookup(type, 0);
+	if (lookup)
+	  type = Getattr(lookup, "sym:name");
+	Printf(type_str, "%s is of type %s. ", tex_name, type);
+	Append(args_str, type_str);
+	Delete(type_str);
+      }
+
+      Delete(tex_name);
+    }
+    if (pdocs)
+      Setattr(n, "feature:pdocs", pdocs);
+    Delete(plist);
+  }
+
+  virtual int functionWrapper(Node *n) {
+    Wrapper *f = NewWrapper();
+    Parm *p;
+    String *tm;
+    int j;
+
+    String *nodeType = Getattr(n, "nodeType");
+    int constructor = (!Cmp(nodeType, "constructor"));
+    int destructor = (!Cmp(nodeType, "destructor"));
+    String *storage = Getattr(n, "storage");
+
+    bool overloaded = !!Getattr(n, "sym:overloaded");
+    bool last_overload = overloaded && !Getattr(n, "sym:nextSibling");
+    String *iname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(iname);
+    String *overname = Copy(wname);
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+
+    if (!overloaded && !addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    if (overloaded)
+      Append(overname, Getattr(n, "sym:overname"));
+
+    Printv(f->def, "static octave_value_list ", overname, " (const octave_value_list& args, int nargout) {", NIL);
+
+    emit_parameter_variables(l, f);
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    int num_arguments = emit_num_arguments(l);
+    int num_required = emit_num_required(l);
+    int varargs = emit_isvarargs(l);
+    char source[64];
+
+    Printf(f->code, "if (!SWIG_check_num_args(\"%s\",args.length(),%i,%i,%i)) " 
+	   "{\n SWIG_fail;\n }\n", iname, num_arguments, num_required, varargs);
+
+    if (constructor && num_arguments == 1 && num_required == 1) {
+      if (Cmp(storage, "explicit") == 0) {
+	Node *parent = Swig_methodclass(n);
+	if (GetFlag(parent, "feature:implicitconv")) {
+	  String *desc = NewStringf("SWIGTYPE%s", SwigType_manglestr(Getattr(n, "type")));
+	  Printf(f->code, "if (SWIG_CheckImplicit(%s)) SWIG_fail;\n", desc);
+	  Delete(desc);
+	}
+      }
+    }
+
+    for (j = 0, p = l; j < num_arguments; ++j) {
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+
+      String *tm = Getattr(p, "tmap:in");
+      if (tm) {
+	if (!tm || checkAttribute(p, "tmap:in:numinputs", "0")) {
+	  p = nextSibling(p);
+	  continue;
+	}
+
+	sprintf(source, "args(%d)", j);
+	Setattr(p, "emit:input", source);
+
+	Replaceall(tm, "$source", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+
+	if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+	  Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	} else {
+	  Replaceall(tm, "$disown", "0");
+	}
+
+	if (Getattr(p, "tmap:in:implicitconv")) {
+	  const char *convflag = "0";
+	  if (!Getattr(p, "hidden")) {
+	    SwigType *ptype = Getattr(p, "type");
+	    convflag = get_implicitconv_flag(classLookup(ptype));
+	  }
+	  Replaceall(tm, "$implicitconv", convflag);
+	  Setattr(p, "implicitconv", convflag);
+	}
+
+	String *getargs = NewString("");
+	if (j >= num_required)
+	  Printf(getargs, "if (%d<args.length()) {\n%s\n}", j, tm);
+	else
+	  Printv(getargs, tm, NIL);
+	Printv(f->code, getargs, "\n", NIL);
+	Delete(getargs);
+
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+	break;
+      }
+    }
+
+    // Check for trailing varargs
+    if (varargs) {
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$input", "varargs");
+	Printv(f->code, tm, "\n", NIL);
+      }
+    }
+
+    // Insert constraint checking code
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Insert cleanup code
+    String *cleanup = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	if (Getattr(p, "tmap:freearg:implicitconv")) {
+	  const char *convflag = "0";
+	  if (!Getattr(p, "hidden")) {
+	    SwigType *ptype = Getattr(p, "type");
+	    convflag = get_implicitconv_flag(classLookup(ptype));
+	  }
+	  if (strcmp(convflag, "0") == 0) {
+	    tm = 0;
+	  }
+	}
+	if (tm && (Len(tm) != 0)) {
+	  Replaceall(tm, "$source", Getattr(p, "lname"));
+	  Printv(cleanup, tm, "\n", NIL);
+	}
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    // Insert argument output code
+    String *outarg = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$target", "_outp");
+	Replaceall(tm, "$result", "_outp");
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    int director_method = is_member_director(n) && !is_smart_pointer() && !destructor;
+    if (director_method) {
+      Wrapper_add_local(f, "upcall", "bool upcall = false");
+      Append(f->code, "upcall = !!dynamic_cast<Swig::Director*>(arg1);\n");
+    }
+
+    Setattr(n, "wrap:name", overname);
+
+    Swig_director_emit_dynamic_cast(n, f);
+    String *actioncode = emit_action(n);
+
+    Wrapper_add_local(f, "_out", "octave_value_list _out");
+    Wrapper_add_local(f, "_outp", "octave_value_list *_outp=&_out");
+    Wrapper_add_local(f, "_outv", "octave_value _outv");
+
+    // Return the function value
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      Replaceall(tm, "$source", "result");
+      Replaceall(tm, "$target", "_outv");
+      Replaceall(tm, "$result", "_outv");
+
+      if (GetFlag(n, "feature:new"))
+	Replaceall(tm, "$owner", "1");
+      else
+	Replaceall(tm, "$owner", "0");
+
+      Printf(f->code, "%s\n", tm);
+      Printf(f->code, "if (_outv.is_defined()) _outp = " "SWIG_Octave_AppendOutput(_outp, _outv);\n");
+      Delete(tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), iname);
+    }
+    emit_return_variable(n, d, f);
+
+    Printv(f->code, outarg, NIL);
+    Printv(f->code, cleanup, NIL);
+
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Replaceall(tm, "$result", "_outv");
+      Printf(f->code, "%s\n", tm);
+      Delete(tm);
+    }
+
+    Printf(f->code, "fail:\n");	// we should free locals etc if this happens
+    Printf(f->code, "return _out;\n");
+    Printf(f->code, "}\n");
+
+    Replaceall(f->code, "$symname", iname);
+    Wrapper_print(f, f_wrappers);
+    DelWrapper(f);
+
+    if (last_overload)
+      dispatchFunction(n);
+
+    if (!overloaded || last_overload) {
+      process_autodoc(n);
+      String *tname = texinfo_name(n);
+      Printf(s_global_tab, "{\"%s\",%s,0,0,2,%s},\n", iname, wname, tname);
+      Delete(tname);
+    }
+
+    Delete(overname);
+    Delete(wname);
+    Delete(cleanup);
+    Delete(outarg);
+
+    return SWIG_OK;
+  }
+
+  void dispatchFunction(Node *n) {
+    Wrapper *f = NewWrapper();
+
+    String *iname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(iname);
+    int maxargs;
+    String *dispatch = Swig_overload_dispatch(n, "return %s(args, nargout);", &maxargs);
+    String *tmp = NewString("");
+
+    Printv(f->def, "static octave_value_list ", wname, " (const octave_value_list& args, int nargout) {", NIL);
+    Wrapper_add_local(f, "argc", "int argc = args.length()");
+    Printf(tmp, "octave_value_ref argv[%d]={", maxargs);
+    for (int j = 0; j < maxargs; ++j)
+      Printf(tmp, "%soctave_value_ref(args,%d)", j ? "," : " ", j);
+    Printf(tmp, "}");
+    Wrapper_add_local(f, "argv", tmp);
+    Printv(f->code, dispatch, "\n", NIL);
+    Printf(f->code, "error(\"No matching function for overload\");\n", iname);
+    Printf(f->code, "return octave_value_list();\n");
+    Printv(f->code, "}\n", NIL);
+
+    Wrapper_print(f, f_wrappers);
+    Delete(tmp);
+    DelWrapper(f);
+    Delete(dispatch);
+    Delete(wname);
+  }
+
+  virtual int variableWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    String *tm;
+    Wrapper *getf = NewWrapper();
+    Wrapper *setf = NewWrapper();
+
+    String *getname = Swig_name_get(iname);
+    String *setname = Swig_name_set(iname);
+
+    Printf(setf->def, "static octave_value_list _wrap_%s(const octave_value_list& args,int nargout) {", setname);
+    Printf(setf->def, "if (!SWIG_check_num_args(\"%s_set\",args.length(),1,1,0)) return octave_value_list();", iname);
+    if (is_assignable(n)) {
+      Setattr(n, "wrap:name", setname);
+      if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	Replaceall(tm, "$source", "args(0)");
+	Replaceall(tm, "$target", name);
+	Replaceall(tm, "$input", "args(0)");
+	if (Getattr(n, "tmap:varin:implicitconv")) {
+	  Replaceall(tm, "$implicitconv", get_implicitconv_flag(n));
+	}
+	emit_action_code(n, setf->code, tm);
+	Delete(tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
+      }
+      Append(setf->code, "fail:\n");
+      Printf(setf->code, "return octave_value_list();\n");
+    } else {
+      Printf(setf->code, "return octave_set_immutable(args,nargout);");
+    }
+    Append(setf->code, "}\n");
+    Wrapper_print(setf, f_wrappers);
+
+    Setattr(n, "wrap:name", getname);
+    int addfail = 0;
+    Printf(getf->def, "static octave_value_list _wrap_%s(const octave_value_list& args,int nargout) {", getname);
+    Wrapper_add_local(getf, "obj", "octave_value obj");
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+      Replaceall(tm, "$source", name);
+      Replaceall(tm, "$target", "obj");
+      Replaceall(tm, "$result", "obj");
+      addfail = emit_action_code(n, getf->code, tm);
+      Delete(tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+    }
+    Append(getf->code, "  return obj;\n");
+    if (addfail) {
+      Append(getf->code, "fail:\n");
+      Append(getf->code, "  return octave_value_list();\n");
+    }
+    Append(getf->code, "}\n");
+    Wrapper_print(getf, f_wrappers);
+
+    Printf(s_global_tab, "{\"%s\",0,_wrap_%s,_wrap_%s,2,0},\n", iname, getname, setname);
+
+    return SWIG_OK;
+  }
+
+  virtual int constantWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(iname);
+      String *str = SwigType_str(type, wname);
+      Printf(f_header, "static %s = %s;\n", str, value);
+      Delete(str);
+      value = wname;
+    }
+    if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Replaceall(tm, "$nsname", iname);
+      Printf(f_init, "%s\n", tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+
+    return SWIG_OK;
+  }
+
+  virtual int nativeWrapper(Node *n) {
+    return Language::nativeWrapper(n);
+  }
+
+  virtual int enumDeclaration(Node *n) {
+    return Language::enumDeclaration(n);
+  }
+
+  virtual int enumvalueDeclaration(Node *n) {
+    return Language::enumvalueDeclaration(n);
+  }
+
+  virtual int classDeclaration(Node *n) {
+    return Language::classDeclaration(n);
+  }
+
+  virtual int classHandler(Node *n) {
+    have_constructor = 0;
+    have_destructor = 0;
+    constructor_name = 0;
+
+    class_name = Getattr(n, "sym:name");
+
+    if (!addSymbol(class_name, n))
+      return SWIG_ERROR;
+
+    // This is a bug, due to the fact that swig_type -> octave_class mapping
+    // is 1-to-n.
+    static Hash *emitted = NewHash();
+    String *mangled_classname = Swig_name_mangle(Getattr(n, "name"));
+    if (Getattr(emitted, mangled_classname)) {
+      Delete(mangled_classname);
+      return SWIG_NOWRAP;
+    }
+    Setattr(emitted, mangled_classname, "1");
+    Delete(mangled_classname);
+
+    assert(!s_members_tab);
+    s_members_tab = NewString("");
+    Printv(s_members_tab, "static swig_octave_member swig_", class_name, "_members[] = {\n", NIL);
+
+    Language::classHandler(n);
+
+    SwigType *t = Copy(Getattr(n, "name"));
+    SwigType_add_pointer(t);
+
+    String *wrap_class = NewStringf("&_wrap_class_%s", class_name);
+    SwigType_remember_clientdata(t, wrap_class);
+
+    int use_director = Swig_directorclass(n);
+    if (use_director) {
+      String *disown_shadow = NewString("");
+      Printf(disown_shadow, "static octave_value_list _wrap_disown_%s_shadow " "(const octave_value_list& args, int nargout) {\n", class_name);
+      Printf(disown_shadow, "  if (args.length()!=1) {\n");
+      Printf(disown_shadow, "    error(\"disown takes no arguments\");\n");
+      Printf(disown_shadow, "    return octave_value_list();\n");
+      Printf(disown_shadow, "  }\n");
+      Printf(disown_shadow, "  _wrap_disown_%s (args, nargout);\n", class_name);
+      Printf(disown_shadow, "  return args;\n");
+      Printf(disown_shadow, "}\n");
+      Printv(f_wrappers, disown_shadow, NIL);
+      Delete(disown_shadow);
+      Printf(s_members_tab, "{\"__disown\",_wrap_disown_%s_shadow,0,0,0,0},\n", class_name);
+    }
+
+    Printf(s_members_tab, "{0,0,0,0}\n};\n");
+    Printv(f_wrappers, s_members_tab, NIL);
+
+    String *base_class_names = NewString("");
+    String *base_class = NewString("");
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist)) {
+      Iterator b;
+      int index = 0;
+      b = First(baselist);
+      while (b.item) {
+	String *bname = Getattr(b.item, "name");
+	if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) {
+	  b = Next(b);
+	  continue;
+	}
+
+	String *bname_mangled = SwigType_manglestr(SwigType_add_pointer(Copy(bname)));
+	Printf(base_class_names, "\"%s\",", bname_mangled);
+	Printf(base_class, "0,");
+	b = Next(b);
+	index++;
+	Delete(bname_mangled);
+      }
+    }
+
+    Printv(f_wrappers, "static const char *swig_", class_name, "_base_names[] = {", base_class_names, "0};\n", NIL);
+    Printv(f_wrappers, "static const swig_type_info *swig_", class_name, "_base[] = {", base_class, "0};\n", NIL);
+    Printv(f_wrappers, "static swig_octave_class _wrap_class_", class_name, " = {\"", class_name, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL);
+    Printv(f_wrappers, Swig_directorclass(n) ? "1," : "0,", NIL);
+    if (have_constructor) {
+      String *cname = Swig_name_construct(constructor_name);
+      String *wcname = Swig_name_wrapper(cname);
+      String *tname = texinfo_name(n);
+      Printf(f_wrappers, "%s,%s,", wcname, tname);
+      Delete(tname);
+      Delete(wcname);
+      Delete(cname);
+    } else
+      Printv(f_wrappers, "0,0,", NIL);
+    if (have_destructor)
+      Printv(f_wrappers, "_wrap_delete_", class_name, ",", NIL);
+    else
+      Printv(f_wrappers, "0", ",", NIL);
+    Printf(f_wrappers, "swig_%s_members,swig_%s_base_names,swig_%s_base };\n\n", class_name, class_name, class_name);
+
+    Delete(base_class);
+    Delete(base_class_names);
+    Delete(t);
+    Delete(s_members_tab);
+    s_members_tab = 0;
+    class_name = 0;
+
+    return SWIG_OK;
+  }
+
+  virtual int memberfunctionHandler(Node *n) {
+    Language::memberfunctionHandler(n);
+
+    assert(s_members_tab);
+    assert(class_name);
+    String *name = Getattr(n, "name");
+    String *iname = GetChar(n, "sym:name");
+    String *realname = iname ? iname : name;
+    String *rname = Swig_name_wrapper(Swig_name_member(class_name, realname));
+
+    if (!Getattr(n, "sym:nextSibling")) {
+      String *tname = texinfo_name(n);
+      Printf(s_members_tab, "{\"%s\",%s,0,0,0,%s},\n", 
+	     realname, rname, tname);
+      Delete(tname);
+    }
+
+    Delete(rname);
+    return SWIG_OK;
+  }
+
+  virtual int membervariableHandler(Node *n) {
+    Setattr(n, "feature:autodoc", "0");
+
+    Language::membervariableHandler(n);
+
+    assert(s_members_tab);
+    assert(class_name);
+    String *symname = Getattr(n, "sym:name");
+    String *getname = Swig_name_wrapper(Swig_name_get(Swig_name_member(class_name, symname)));
+    String *setname = GetFlag(n, "feature:immutable") ?
+	NewString("octave_set_immutable") : Swig_name_wrapper(Swig_name_set(Swig_name_member(class_name, symname)));
+    assert(s_members_tab);
+
+    Printf(s_members_tab, "{\"%s\",0,%s,%s,0,0},\n", symname, getname, setname);
+
+    Delete(getname);
+    Delete(setname);
+    return SWIG_OK;
+  }
+
+  virtual int constructorHandler(Node *n) {
+    have_constructor = 1;
+    if (!constructor_name)
+      constructor_name = NewString(Getattr(n, "sym:name"));
+
+    int use_director = Swig_directorclass(n);
+    if (use_director) {
+      Parm *parms = Getattr(n, "parms");
+      Parm *self;
+      String *name = NewString("self");
+      String *type = NewString("void");
+      SwigType_add_pointer(type);
+      self = NewParm(type, name);
+      Delete(type);
+      Delete(name);
+      Setattr(self, "lname", "self_obj");
+      if (parms)
+	set_nextSibling(self, parms);
+      Setattr(n, "parms", self);
+      Setattr(n, "wrap:self", "1");
+      Setattr(n, "hidden", "1");
+      Delete(self);
+    }
+
+    return Language::constructorHandler(n);;
+  }
+
+  virtual int destructorHandler(Node *n) {
+    have_destructor = 1;
+    return Language::destructorHandler(n);;
+  }
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    Language::staticmemberfunctionHandler(n);
+
+    assert(s_members_tab);
+    assert(class_name);
+    String *name = Getattr(n, "name");
+    String *iname = GetChar(n, "sym:name");
+    String *realname = iname ? iname : name;
+    String *rname = Swig_name_wrapper(Swig_name_member(class_name, realname));
+
+    if (!Getattr(n, "sym:nextSibling")) {
+      String *tname = texinfo_name(n);
+      Printf(s_members_tab, "{\"%s\",%s,0,0,1,%s},\n", 
+	     realname, rname, tname);
+      Delete(tname);
+    }
+    
+    Delete(rname);
+    return SWIG_OK;
+  }
+
+  virtual int memberconstantHandler(Node *n) {
+    return Language::memberconstantHandler(n);
+  }
+
+  virtual int staticmembervariableHandler(Node *n) {
+    Setattr(n, "feature:autodoc", "0");
+
+    Language::staticmembervariableHandler(n);
+
+    if (!GetFlag(n, "wrappedasconstant")) {
+      assert(s_members_tab);
+      assert(class_name);
+      String *symname = Getattr(n, "sym:name");
+      String *getname = Swig_name_wrapper(Swig_name_get(Swig_name_member(class_name, symname)));
+      String *setname = GetFlag(n, "feature:immutable") ?
+	  NewString("octave_set_immutable") : Swig_name_wrapper(Swig_name_set(Swig_name_member(class_name, symname)));
+      assert(s_members_tab);
+
+      Printf(s_members_tab, "{\"%s\",0,%s,%s,1,0},\n", symname, getname, setname);
+
+      Delete(getname);
+      Delete(setname);
+    }
+    return SWIG_OK;
+  }
+
+  int classDirectorInit(Node *n) {
+    String *declaration = Swig_director_declaration(n);
+    Printf(f_directors_h, "\n");
+    Printf(f_directors_h, "%s\n", declaration);
+    Printf(f_directors_h, "public:\n");
+    Delete(declaration);
+    return Language::classDirectorInit(n);
+  }
+
+  int classDirectorEnd(Node *n) {
+    Printf(f_directors_h, "};\n\n");
+    return Language::classDirectorEnd(n);
+  }
+
+  int classDirectorConstructor(Node *n) {
+    Node *parent = Getattr(n, "parentNode");
+    String *sub = NewString("");
+    String *decl = Getattr(n, "decl");
+    String *supername = Swig_class_name(parent);
+    String *classname = NewString("");
+    Printf(classname, "SwigDirector_%s", supername);
+
+    // insert self parameter
+    Parm *p;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms = CopyParmList(superparms);
+    String *type = NewString("void");
+    SwigType_add_pointer(type);
+    p = NewParm(type, NewString("self"));
+    set_nextSibling(p, parms);
+    parms = p;
+
+    if (!Getattr(n, "defaultargs")) {
+      // constructor
+      {
+	Wrapper *w = NewWrapper();
+	String *call;
+	String *basetype = Getattr(parent, "classtype");
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 0);
+	call = Swig_csuperclass_call(0, basetype, superparms);
+	Printf(w->def, "%s::%s: %s," "\nSwig::Director(static_cast<%s*>(this)) { \n", classname, target, call, basetype);
+	Append(w->def, "}\n");
+	Delete(target);
+	Wrapper_print(w, f_directors);
+	Delete(call);
+	DelWrapper(w);
+      }
+
+      // constructor header
+      {
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 1);
+	Printf(f_directors_h, "    %s;\n", target);
+	Delete(target);
+      }
+    }
+
+    Delete(sub);
+    Delete(classname);
+    Delete(supername);
+    Delete(parms);
+    return Language::classDirectorConstructor(n);
+  }
+
+  int classDirectorDefaultConstructor(Node *n) {
+    String *classname = Swig_class_name(n);
+    {
+      Wrapper *w = NewWrapper();
+      Printf(w->def, "SwigDirector_%s::SwigDirector_%s(void* self) :"
+	     "\nSwig::Director((octave_swig_type*)self,static_cast<%s*>(this)) { \n", classname, classname, classname);
+      Append(w->def, "}\n");
+      Wrapper_print(w, f_directors);
+      DelWrapper(w);
+    }
+    Printf(f_directors_h, "    SwigDirector_%s(octave_swig_type* self);\n", classname);
+    Delete(classname);
+    return Language::classDirectorDefaultConstructor(n);
+  }
+
+  int classDirectorMethod(Node *n, Node *parent, String *super) {
+    int is_void = 0;
+    int is_pointer = 0;
+    String *decl;
+    String *type;
+    String *name;
+    String *classname;
+    String *c_classname = Getattr(parent, "name");
+    String *declaration;
+    ParmList *l;
+    Wrapper *w;
+    String *tm;
+    String *wrap_args = NewString("");
+    String *return_type;
+    String *value = Getattr(n, "value");
+    String *storage = Getattr(n, "storage");
+    bool pure_virtual = false;
+    int status = SWIG_OK;
+    int idx;
+    bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
+
+    if (Cmp(storage, "virtual") == 0) {
+      if (Cmp(value, "0") == 0) {
+	pure_virtual = true;
+      }
+    }
+
+    classname = Getattr(parent, "sym:name");
+    type = Getattr(n, "type");
+    name = Getattr(n, "name");
+
+    w = NewWrapper();
+    declaration = NewString("");
+
+    // determine if the method returns a pointer
+    decl = Getattr(n, "decl");
+    is_pointer = SwigType_ispointer_return(decl);
+    is_void = (!Cmp(type, "void") && !is_pointer);
+
+    // form complete return type
+    return_type = Copy(type);
+    {
+      SwigType *t = Copy(decl);
+      SwigType *f = 0;
+      f = SwigType_pop_function(t);
+      SwigType_push(return_type, t);
+      Delete(f);
+      Delete(t);
+    }
+
+    // virtual method definition
+    l = Getattr(n, "parms");
+    String *target;
+    String *pclassname = NewStringf("SwigDirector_%s", classname);
+    String *qualified_name = NewStringf("%s::%s", pclassname, name);
+    SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type;
+    target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0);
+    Printf(w->def, "%s", target);
+    Delete(qualified_name);
+    Delete(target);
+
+    // header declaration
+    target = Swig_method_decl(rtype, decl, name, l, 0, 1);
+    Printf(declaration, "    virtual %s", target);
+    Delete(target);
+
+    // Get any exception classes in the throws typemap
+    ParmList *throw_parm_list = 0;
+
+    if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) {
+      Parm *p;
+      int gencomma = 0;
+
+      Append(w->def, " throw(");
+      Append(declaration, " throw(");
+
+      if (throw_parm_list)
+	Swig_typemap_attach_parms("throws", throw_parm_list, 0);
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	if ((tm = Getattr(p, "tmap:throws"))) {
+	  if (gencomma++) {
+	    Append(w->def, ", ");
+	    Append(declaration, ", ");
+	  }
+	  String *str = SwigType_str(Getattr(p, "type"), 0);
+	  Append(w->def, str);
+	  Append(declaration, str);
+	  Delete(str);
+	}
+      }
+
+      Append(w->def, ")");
+      Append(declaration, ")");
+    }
+
+    Append(w->def, " {");
+    Append(declaration, ";\n");
+
+    // declare method return value 
+    // if the return value is a reference or const reference, a specialized typemap must
+    // handle it, including declaration of c_result ($result).
+    if (!is_void) {
+      if (!(ignored_method && !pure_virtual)) {
+	String *cres = SwigType_lstr(return_type, "c_result");
+	Printf(w->code, "%s;\n", cres);
+	Delete(cres);
+      }
+    }
+
+    if (ignored_method) {
+      if (!pure_virtual) {
+	if (!is_void)
+	  Printf(w->code, "return ");
+	String *super_call = Swig_method_call(super, l);
+	Printf(w->code, "%s;\n", super_call);
+	Delete(super_call);
+      } else {
+	Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname),
+	       SwigType_namestr(name));
+      }
+    } else {
+      // attach typemaps to arguments (C/C++ -> Python)
+      String *parse_args = NewString("");
+
+      Swig_typemap_attach_parms("in", l, 0);
+      Swig_typemap_attach_parms("directorin", l, 0);
+      Swig_typemap_attach_parms("directorargout", l, w);
+
+      Parm *p;
+
+      int outputs = 0;
+      if (!is_void)
+	outputs++;
+
+      // build argument list and type conversion string
+      idx = 0;
+      p = l;
+      int use_parse = 0;
+      while (p != NULL) {
+	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	  p = Getattr(p, "tmap:in:next");
+	  continue;
+	}
+
+	if (Getattr(p, "tmap:directorargout") != 0)
+	  outputs++;
+
+	String *pname = Getattr(p, "name");
+	String *ptype = Getattr(p, "type");
+	Wrapper_add_local(w, "tmpv", "octave_value tmpv");
+
+	if ((tm = Getattr(p, "tmap:directorin")) != 0) {
+	  String *parse = Getattr(p, "tmap:directorin:parse");
+	  if (!parse) {
+	    Replaceall(tm, "$input", "tmpv");
+	    Replaceall(tm, "$owner", "0");
+	    Printv(wrap_args, tm, "\n", NIL);
+	    Printf(wrap_args, "args.append(tmpv);\n");
+	    Putc('O', parse_args);
+	  } else {
+	    use_parse = 1;
+	    Append(parse_args, parse);
+	    Replaceall(tm, "$input", pname);
+	    Replaceall(tm, "$owner", "0");
+	    if (Len(tm) == 0)
+	      Append(tm, pname);
+	  }
+	  p = Getattr(p, "tmap:directorin:next");
+	  continue;
+	} else if (Cmp(ptype, "void")) {
+	  Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
+		       "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0),
+		       SwigType_namestr(c_classname), SwigType_namestr(name));
+	  status = SWIG_NOWRAP;
+	  break;
+	}
+	p = nextSibling(p);
+      }
+
+      String *method_name = Getattr(n, "sym:name");
+
+      Printv(w->code, wrap_args, NIL);
+
+      // emit method invocation
+      Wrapper_add_local(w, "args", "octave_value_list args");
+      Wrapper_add_local(w, "out", "octave_value_list out");
+      Wrapper_add_local(w, "idx", "std::list<octave_value_list> idx");
+      Printf(w->code, "idx.push_back(octave_value_list(\"%s\"));\n", method_name);
+      Printf(w->code, "idx.push_back(args);\n");
+      Printf(w->code, "out=swig_get_self()->subsref(\".(\",idx,%d);\n", outputs);
+
+      String *cleanup = NewString("");
+      String *outarg = NewString("");
+      idx = 0;
+
+      // marshal return value
+      if (!is_void) {
+	Printf(w->code, "if (out.length()<%d) {\n", outputs);
+	Printf(w->code, "Swig::DirectorTypeMismatchException::raise(\"Octave "
+	       "method %s.%s failed to return the required number " "of arguments.\");\n", classname, method_name);
+	Printf(w->code, "}\n");
+
+	Setattr(n, "type", return_type);
+	tm = Swig_typemap_lookup("directorout", n, "result", w);
+	Setattr(n, "type", type);
+	if (tm == 0) {
+	  String *name = NewString("result");
+	  tm = Swig_typemap_search("directorout", return_type, name, NULL);
+	  Delete(name);
+	}
+	if (tm != 0) {
+	  char temp[24];
+	  sprintf(temp, "out(%d)", idx);
+	  Replaceall(tm, "$input", temp);
+	  //    Replaceall(tm, "$argnum", temp);
+	  Replaceall(tm, "$disown", Getattr(n, "wrap:disown") ? "SWIG_POINTER_DISOWN" : "0");
+	  if (Getattr(n, "tmap:directorout:implicitconv")) {
+	    Replaceall(tm, "$implicitconv", get_implicitconv_flag(n));
+	  }
+	  Replaceall(tm, "$result", "c_result");
+	  Printv(w->code, tm, "\n", NIL);
+	  Delete(tm);
+	} else {
+	  Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number,
+		       "Unable to use return type %s in director method %s::%s (skipping method).\n",
+		       SwigType_str(return_type, 0), SwigType_namestr(c_classname), SwigType_namestr(name));
+	  status = SWIG_ERROR;
+	}
+      }
+      idx++;
+
+      // marshal outputs
+      for (p = l; p;) {
+	if ((tm = Getattr(p, "tmap:directorargout")) != 0) {
+	  char temp[24];
+	  sprintf(temp, "out(%d)", idx);
+	  Replaceall(tm, "$input", temp);
+	  Replaceall(tm, "$result", Getattr(p, "name"));
+	  Printv(w->code, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:directorargout:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+
+      Delete(parse_args);
+      Delete(cleanup);
+      Delete(outarg);
+    }
+
+    if (!is_void) {
+      if (!(ignored_method && !pure_virtual)) {
+	String *rettype = SwigType_str(return_type, 0);
+	if (!SwigType_isreference(return_type)) {
+	  Printf(w->code, "return (%s) c_result;\n", rettype);
+	} else {
+	  Printf(w->code, "return (%s) *c_result;\n", rettype);
+	}
+	Delete(rettype);
+      }
+    }
+
+    Append(w->code, "}\n");
+
+    // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method
+    String *inline_extra_method = NewString("");
+    if (dirprot_mode() && !is_public(n) && !pure_virtual) {
+      Printv(inline_extra_method, declaration, NIL);
+      String *extra_method_name = NewStringf("%sSwigPublic", name);
+      Replaceall(inline_extra_method, name, extra_method_name);
+      Replaceall(inline_extra_method, ";\n", " {\n      ");
+      if (!is_void)
+	Printf(inline_extra_method, "return ");
+      String *methodcall = Swig_method_call(super, l);
+      Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
+      Delete(methodcall);
+      Delete(extra_method_name);
+    }
+    // emit the director method
+    if (status == SWIG_OK) {
+      if (!Getattr(n, "defaultargs")) {
+	Wrapper_print(w, f_directors);
+	Printv(f_directors_h, declaration, NIL);
+	Printv(f_directors_h, inline_extra_method, NIL);
+      }
+    }
+    // clean up
+    Delete(wrap_args);
+    Delete(return_type);
+    Delete(pclassname);
+    DelWrapper(w);
+    return status;
+  }
+
+  String *runtimeCode() {
+    String *s = NewString("");
+    String *srun = Swig_include_sys("octrun.swg");
+    if (!srun) {
+      Printf(stderr, "*** Unable to open 'octrun.swg'\n");
+    } else {
+      Append(s, srun);
+      Delete(srun);
+    }
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigoctaverun.h");
+  }
+};
+
+extern "C" Language *swig_octave(void) {
+  return new OCTAVE();
+}
diff --git a/trunk/Source/Modules/overload.cxx b/trunk/Source/Modules/overload.cxx
new file mode 100644
index 0000000..d169138
--- /dev/null
+++ b/trunk/Source/Modules/overload.cxx
@@ -0,0 +1,788 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * overload.cxx
+ *
+ * This file is used to analyze overloaded functions and methods.
+ * It looks at signatures and tries to gather information for
+ * building a dispatch function.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_overload_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#define MAX_OVERLOAD 4096
+
+/* Overload "argc" and "argv" */
+String *argv_template_string;
+String *argc_template_string;
+
+struct Overloaded {
+  Node *n;			/* Node                               */
+  int argc;			/* Argument count                     */
+  ParmList *parms;		/* Parameters used for overload check */
+  int error;			/* Ambiguity error                    */
+};
+
+static int fast_dispatch_mode = 0;
+static int cast_dispatch_mode = 0;
+
+/* Set fast_dispatch_mode */
+void Wrapper_fast_dispatch_mode_set(int flag) {
+  fast_dispatch_mode = flag;
+}
+
+void Wrapper_cast_dispatch_mode_set(int flag) {
+  cast_dispatch_mode = flag;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_overload_rank()
+ *
+ * This function takes an overloaded declaration and creates a list that ranks
+ * all overloaded methods in an order that can be used to generate a dispatch 
+ * function.
+ * Slight difference in the way this function is used by scripting languages and
+ * statically typed languages. The script languages call this method via 
+ * Swig_overload_dispatch() - where wrappers for all overloaded methods are generated,
+ * however sometimes the code can never be executed. The non-scripting languages
+ * call this method via Swig_overload_check() for each overloaded method in order
+ * to determine whether or not the method should be wrapped. Note the slight
+ * difference when overloading methods that differ by const only. The
+ * scripting languages will ignore the const method, whereas the non-scripting
+ * languages ignore the first method parsed.
+ * ----------------------------------------------------------------------------- */
+
+static List *Swig_overload_rank(Node *n, bool script_lang_wrapping) {
+  Overloaded nodes[MAX_OVERLOAD];
+  int nnodes = 0;
+  Node *o = Getattr(n, "sym:overloaded");
+  Node *c;
+
+  if (!o)
+    return 0;
+
+  c = o;
+  while (c) {
+    if (Getattr(c, "error")) {
+      c = Getattr(c, "sym:nextSibling");
+      continue;
+    }
+    /*    if (SmartPointer && Getattr(c,"cplus:staticbase")) {
+       c = Getattr(c,"sym:nextSibling");
+       continue;
+       } */
+
+    /* Make a list of all the declarations (methods) that are overloaded with
+     * this one particular method name */
+    if (Getattr(c, "wrap:name")) {
+      assert(nnodes < MAX_OVERLOAD);
+      nodes[nnodes].n = c;
+      nodes[nnodes].parms = Getattr(c, "wrap:parms");
+      nodes[nnodes].argc = emit_num_required(nodes[nnodes].parms);
+      nodes[nnodes].error = 0;
+      nnodes++;
+    }
+    c = Getattr(c, "sym:nextSibling");
+  }
+
+  /* Sort the declarations by required argument count */
+  {
+    int i, j;
+    for (i = 0; i < nnodes; i++) {
+      for (j = i + 1; j < nnodes; j++) {
+	if (nodes[i].argc > nodes[j].argc) {
+	  Overloaded t = nodes[i];
+	  nodes[i] = nodes[j];
+	  nodes[j] = t;
+	}
+      }
+    }
+  }
+
+  /* Sort the declarations by argument types */
+  {
+    int i, j;
+    for (i = 0; i < nnodes - 1; i++) {
+      if (nodes[i].argc == nodes[i + 1].argc) {
+	for (j = i + 1; (j < nnodes) && (nodes[j].argc == nodes[i].argc); j++) {
+	  Parm *p1 = nodes[i].parms;
+	  Parm *p2 = nodes[j].parms;
+	  int differ = 0;
+	  int num_checked = 0;
+	  while (p1 && p2 && (num_checked < nodes[i].argc)) {
+	    //    Printf(stdout,"p1 = '%s', p2 = '%s'\n", Getattr(p1,"type"), Getattr(p2,"type"));
+	    if (checkAttribute(p1, "tmap:in:numinputs", "0")) {
+	      p1 = Getattr(p1, "tmap:in:next");
+	      continue;
+	    }
+	    if (checkAttribute(p2, "tmap:in:numinputs", "0")) {
+	      p2 = Getattr(p2, "tmap:in:next");
+	      continue;
+	    }
+	    String *t1 = Getattr(p1, "tmap:typecheck:precedence");
+	    String *t2 = Getattr(p2, "tmap:typecheck:precedence");
+	    if ((!t1) && (!nodes[i].error)) {
+	      Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[i].n), Getline(nodes[i].n),
+			   "Overloaded method %s not supported (no type checking rule for '%s').\n",
+			   Swig_name_decl(nodes[i].n), SwigType_str(Getattr(p1, "type"), 0));
+	      nodes[i].error = 1;
+	    } else if ((!t2) && (!nodes[j].error)) {
+	      Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[j].n), Getline(nodes[j].n),
+			   "Overloaded method %s not supported (no type checking rule for '%s').\n",
+			   Swig_name_decl(nodes[j].n), SwigType_str(Getattr(p2, "type"), 0));
+	      nodes[j].error = 1;
+	    }
+	    if (t1 && t2) {
+	      int t1v, t2v;
+	      t1v = atoi(Char(t1));
+	      t2v = atoi(Char(t2));
+	      differ = t1v - t2v;
+	    } else if (!t1 && t2)
+	      differ = 1;
+	    else if (t1 && !t2)
+	      differ = -1;
+	    else if (!t1 && !t2)
+	      differ = -1;
+	    num_checked++;
+	    if (differ > 0) {
+	      Overloaded t = nodes[i];
+	      nodes[i] = nodes[j];
+	      nodes[j] = t;
+	      break;
+	    } else if ((differ == 0) && (Strcmp(t1, "0") == 0)) {
+	      t1 = Getattr(p1, "ltype");
+	      if (!t1) {
+		t1 = SwigType_ltype(Getattr(p1, "type"));
+		if (Getattr(p1, "tmap:typecheck:SWIGTYPE")) {
+		  SwigType_add_pointer(t1);
+		}
+		Setattr(p1, "ltype", t1);
+	      }
+	      t2 = Getattr(p2, "ltype");
+	      if (!t2) {
+		t2 = SwigType_ltype(Getattr(p2, "type"));
+		if (Getattr(p2, "tmap:typecheck:SWIGTYPE")) {
+		  SwigType_add_pointer(t2);
+		}
+		Setattr(p2, "ltype", t2);
+	      }
+
+	      /* Need subtype check here.  If t2 is a subtype of t1, then we need to change the
+	         order */
+
+	      if (SwigType_issubtype(t2, t1)) {
+		Overloaded t = nodes[i];
+		nodes[i] = nodes[j];
+		nodes[j] = t;
+	      }
+
+	      if (Strcmp(t1, t2) != 0) {
+		differ = 1;
+		break;
+	      }
+	    } else if (differ) {
+	      break;
+	    }
+	    if (Getattr(p1, "tmap:in:next")) {
+	      p1 = Getattr(p1, "tmap:in:next");
+	    } else {
+	      p1 = nextSibling(p1);
+	    }
+	    if (Getattr(p2, "tmap:in:next")) {
+	      p2 = Getattr(p2, "tmap:in:next");
+	    } else {
+	      p2 = nextSibling(p2);
+	    }
+	  }
+	  if (!differ) {
+	    /* See if declarations differ by const only */
+	    String *d1 = Getattr(nodes[i].n, "decl");
+	    String *d2 = Getattr(nodes[j].n, "decl");
+	    if (d1 && d2) {
+	      String *dq1 = Copy(d1);
+	      String *dq2 = Copy(d2);
+	      if (SwigType_isconst(d1)) {
+		Delete(SwigType_pop(dq1));
+	      }
+	      if (SwigType_isconst(d2)) {
+		Delete(SwigType_pop(dq2));
+	      }
+	      if (Strcmp(dq1, dq2) == 0) {
+
+		if (SwigType_isconst(d1) && !SwigType_isconst(d2)) {
+		  if (script_lang_wrapping) {
+		    // Swap nodes so that the const method gets ignored (shadowed by the non-const method)
+		    Overloaded t = nodes[i];
+		    nodes[i] = nodes[j];
+		    nodes[j] = t;
+		  }
+		  differ = 1;
+		  if (!nodes[j].error) {
+		    if (script_lang_wrapping) {
+		      Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[j].n), Getline(nodes[j].n),
+				   "Overloaded method %s ignored. Non-const method %s at %s:%d used.\n",
+				   Swig_name_decl(nodes[j].n), Swig_name_decl(nodes[i].n), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    } else {
+		      if (!Getattr(nodes[j].n, "overload:ignore"))
+			Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+				     "Overloaded method %s ignored. Method %s at %s:%d used.\n",
+				     Swig_name_decl(nodes[j].n), Swig_name_decl(nodes[i].n), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    }
+		  }
+		  nodes[j].error = 1;
+		} else if (!SwigType_isconst(d1) && SwigType_isconst(d2)) {
+		  differ = 1;
+		  if (!nodes[j].error) {
+		    if (script_lang_wrapping) {
+		      Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[j].n), Getline(nodes[j].n),
+				   "Overloaded method %s ignored. Non-const method %s at %s:%d used.\n",
+				   Swig_name_decl(nodes[j].n), Swig_name_decl(nodes[i].n), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    } else {
+		      if (!Getattr(nodes[j].n, "overload:ignore"))
+			Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+				     "Overloaded method %s ignored. Method %s at %s:%d used.\n",
+				     Swig_name_decl(nodes[j].n), Swig_name_decl(nodes[i].n), Getfile(nodes[i].n), Getline(nodes[i].n));
+		    }
+		  }
+		  nodes[j].error = 1;
+		}
+	      }
+	      Delete(dq1);
+	      Delete(dq2);
+	    }
+	  }
+	  if (!differ) {
+	    if (!nodes[j].error) {
+	      if (script_lang_wrapping) {
+		Swig_warning(WARN_LANG_OVERLOAD_SHADOW, Getfile(nodes[j].n), Getline(nodes[j].n),
+			     "Overloaded method %s is shadowed by %s at %s:%d.\n",
+			     Swig_name_decl(nodes[j].n), Swig_name_decl(nodes[i].n),
+			     Getfile(nodes[i].n), Getline(nodes[i].n));
+	      } else {
+		if (!Getattr(nodes[j].n, "overload:ignore"))
+		  Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+			       "Overloaded method %s ignored. Method %s at %s:%d used.\n",
+			       Swig_name_decl(nodes[j].n), Swig_name_decl(nodes[i].n),
+			       Getfile(nodes[i].n), Getline(nodes[i].n));
+	      }
+	      nodes[j].error = 1;
+	    }
+	  }
+	}
+      }
+    }
+  }
+  List *result = NewList();
+  {
+    int i;
+    for (i = 0; i < nnodes; i++) {
+      if (nodes[i].error)
+	Setattr(nodes[i].n, "overload:ignore", "1");
+      Append(result, nodes[i].n);
+      //      Printf(stdout,"[ %d ] %s\n", i, ParmList_errorstr(nodes[i].parms));
+      //      Swig_print_node(nodes[i].n);
+    }
+  }
+  return result;
+}
+
+// /* -----------------------------------------------------------------------------
+//  * print_typecheck()
+//  * ----------------------------------------------------------------------------- */
+
+static bool print_typecheck(String *f, int j, Parm *pj) {
+  char tmp[256];
+  sprintf(tmp, Char(argv_template_string), j);
+  String *tm = Getattr(pj, "tmap:typecheck");
+  if (tm) {
+    Replaceid(tm, Getattr(pj, "lname"), "_v");
+    String *conv = Getattr(pj, "implicitconv");
+    if (conv) {
+      Replaceall(tm, "$implicitconv", conv);
+    } else {
+      Replaceall(tm, "$implicitconv", "0");
+    }
+    Replaceall(tm, "$input", tmp);
+    Printv(f, tm, "\n", NIL);
+    return true;
+  } else
+    return false;
+}
+
+/* -----------------------------------------------------------------------------
+ * ReplaceFormat()
+ * ----------------------------------------------------------------------------- */
+
+static String *ReplaceFormat(const String_or_char *fmt, int j) {
+  String *lfmt = NewString(fmt);
+  char buf[50];
+  sprintf(buf, "%d", j);
+  Replaceall(lfmt, "$numargs", buf);
+  int i;
+  String *commaargs = NewString("");
+  for (i = 0; i < j; i++) {
+    Printv(commaargs, ", ", NIL);
+    Printf(commaargs, Char(argv_template_string), i);
+  }
+  Replaceall(lfmt, "$commaargs", commaargs);
+  return lfmt;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_overload_dispatch()
+ *
+ * Generate a dispatch function.  argc is assumed to hold the argument count.
+ * argv is the argument vector.
+ *
+ * Note that for C++ class member functions, Swig_overload_dispatch() assumes
+ * that argc includes the "self" argument and that the first element of argv[]
+ * is the "self" argument. So for a member function:
+ *
+ *     Foo::bar(int x, int y, int z);
+ *
+ * the argc should be 4 (not 3!) and the first element of argv[] would be
+ * the appropriate scripting language reference to "self". For regular
+ * functions (and static class functions) the argc and argv only include
+ * the regular function arguments.
+ * ----------------------------------------------------------------------------- */
+
+/*
+  Cast dispatch mechanism.
+*/
+String *Swig_overload_dispatch_cast(Node *n, const String_or_char *fmt, int *maxargs) {
+  int i, j;
+
+  *maxargs = 1;
+
+  String *f = NewString("");
+  String *sw = NewString("");
+  Printf(f, "{\n");
+  Printf(f, "unsigned long _index = 0;\n");
+  Printf(f, "SWIG_TypeRank _rank = 0; \n");
+
+  /* Get a list of methods ranked by precedence values and argument count */
+  List *dispatch = Swig_overload_rank(n, true);
+  int nfunc = Len(dispatch);
+
+  /* Loop over the functions */
+
+  bool emitcheck = 1;
+  for (i = 0; i < nfunc; i++) {
+    int fn = 0;
+    Node *ni = Getitem(dispatch, i);
+    Parm *pi = Getattr(ni, "wrap:parms");
+    int num_required = emit_num_required(pi);
+    int num_arguments = emit_num_arguments(pi);
+    if (num_arguments > *maxargs)
+      *maxargs = num_arguments;
+    int varargs = emit_isvarargs(pi);
+
+    if (!varargs) {
+      if (num_required == num_arguments) {
+	Printf(f, "if (%s == %d) {\n", argc_template_string, num_required);
+      } else {
+	Printf(f, "if ((%s >= %d) && (%s <= %d)) {\n", argc_template_string, num_required, argc_template_string, num_arguments);
+      }
+    } else {
+      Printf(f, "if (%s >= %d) {\n", argc_template_string, num_required);
+    }
+    Printf(f, "SWIG_TypeRank _ranki = 0;\n");
+    Printf(f, "SWIG_TypeRank _rankm = 0;\n");
+    if (num_arguments)
+      Printf(f, "SWIG_TypeRank _pi = 1;\n");
+
+    /* create a list with the wrappers that collide with the
+       current one based on argument number */
+    List *coll = NewList();
+    for (int k = i + 1; k < nfunc; k++) {
+      Node *nk = Getitem(dispatch, k);
+      Parm *pk = Getattr(nk, "wrap:parms");
+      int nrk = emit_num_required(pk);
+      int nak = emit_num_arguments(pk);
+      if ((nrk >= num_required && nrk <= num_arguments) || (nak >= num_required && nak <= num_arguments) || (nrk <= num_required && nak >= num_arguments))
+	Append(coll, nk);
+    }
+
+    // printf("overload: %s coll=%d\n", Char(Getattr(n, "sym:name")), Len(coll));
+
+    int num_braces = 0;
+    bool test = (num_arguments > 0);
+    if (test) {
+      int need_v = 1;
+      j = 0;
+      Parm *pj = pi;
+      while (pj) {
+	if (checkAttribute(pj, "tmap:in:numinputs", "0")) {
+	  pj = Getattr(pj, "tmap:in:next");
+	  continue;
+	}
+
+	String *tm = Getattr(pj, "tmap:typecheck");
+	if (tm) {
+	  /* normalise for comparison later */
+	  Replaceid(tm, Getattr(pj, "lname"), "_v");
+
+	  /* if all the wrappers have the same type check on this
+	     argument we can optimize it out */
+	  for (int k = 0; k < Len(coll) && !emitcheck; k++) {
+	    Node *nk = Getitem(coll, k);
+	    Parm *pk = Getattr(nk, "wrap:parms");
+	    int nak = emit_num_arguments(pk);
+	    if (nak <= j)
+	      continue;
+	    int l = 0;
+	    Parm *pl = pk;
+	    /* finds arg j on the collider wrapper */
+	    while (pl && l <= j) {
+	      if (checkAttribute(pl, "tmap:in:numinputs", "0")) {
+		pl = Getattr(pl, "tmap:in:next");
+		continue;
+	      }
+	      if (l == j) {
+		/* we are at arg j, so we compare the tmaps now */
+		String *tml = Getattr(pl, "tmap:typecheck");
+		/* normalise it before comparing */
+		if (tml)
+		  Replaceid(tml, Getattr(pl, "lname"), "_v");
+		if (!tml || Cmp(tm, tml))
+		  emitcheck = 1;
+		//printf("tmap: %s[%d] (%d) => %s\n\n",
+		//       Char(Getattr(nk, "sym:name")),
+		//       l, emitcheck, tml?Char(tml):0);
+	      }
+	      Parm *pl1 = Getattr(pl, "tmap:in:next");
+	      if (pl1)
+		pl = pl1;
+	      else
+		pl = nextSibling(pl);
+	      l++;
+	    }
+	  }
+
+	  if (emitcheck) {
+	    if (need_v) {
+	      Printf(f, "int _v = 0;\n");
+	      need_v = 0;
+	    }
+	    if (j >= num_required) {
+	      Printf(f, "if (%s > %d) {\n", argc_template_string, j);
+	      num_braces++;
+	    }
+	    String *tmp = NewStringf(argv_template_string, j);
+
+	    String *conv = Getattr(pj, "implicitconv");
+	    if (conv) {
+	      Replaceall(tm, "$implicitconv", conv);
+	    } else {
+	      Replaceall(tm, "$implicitconv", "0");
+	    }
+	    Replaceall(tm, "$input", tmp);
+	    Printv(f, "{\n", tm, "}\n", NIL);
+	    fn = i + 1;
+	    Printf(f, "if (!_v) goto check_%d;\n", fn);
+	    Printf(f, "_ranki += _v*_pi;\n");
+	    Printf(f, "_rankm += _pi;\n");
+	    Printf(f, "_pi *= SWIG_MAXCASTRANK;\n");
+	  }
+	}
+	if (!Getattr(pj, "tmap:in:SWIGTYPE") && Getattr(pj, "tmap:typecheck:SWIGTYPE")) {
+	  /* we emit  a warning if the argument defines the 'in' typemap, but not the 'typecheck' one */
+	  Swig_warning(WARN_TYPEMAP_TYPECHECK_UNDEF, Getfile(ni), Getline(ni),
+		       "Overloaded method %s with no explicit typecheck typemap for arg %d of type '%s'\n",
+		       Swig_name_decl(n), j, SwigType_str(Getattr(pj, "type"), 0));
+	}
+	Parm *pj1 = Getattr(pj, "tmap:in:next");
+	if (pj1)
+	  pj = pj1;
+	else
+	  pj = nextSibling(pj);
+	j++;
+      }
+    }
+
+    /* close braces */
+    for ( /* empty */ ; num_braces > 0; num_braces--)
+      Printf(f, "}\n");
+
+    Printf(f, "if (!_index || (_ranki < _rank)) {\n");
+    Printf(f, " _rank = _ranki; _index = %d;\n", i + 1);
+    Printf(f, " if (_rank == _rankm) goto dispatch;\n");
+    Printf(f, "}\n");
+    String *lfmt = ReplaceFormat(fmt, num_arguments);
+    Printf(sw, "case %d:\n", i + 1);
+    Printf(sw, Char(lfmt), Getattr(ni, "wrap:name"));
+    Printf(sw, "\n");
+
+    Printf(f, "}\n");		/* braces closes "if" for this method */
+    if (fn)
+      Printf(f, "check_%d:\n\n", fn);
+
+    Delete(lfmt);
+    Delete(coll);
+  }
+  Delete(dispatch);
+  Printf(f, "dispatch:\n");
+  Printf(f, "switch(_index) {\n");
+  Printf(f, "%s", sw);
+  Printf(f, "}\n");
+
+  Printf(f, "}\n");
+  return f;
+}
+
+/*
+  Fast dispatch mechanism, provided by  Salvador Fandi~no Garc'ia (#930586).
+*/
+String *Swig_overload_dispatch_fast(Node *n, const String_or_char *fmt, int *maxargs) {
+  int i, j;
+
+  *maxargs = 1;
+
+  String *f = NewString("");
+
+  /* Get a list of methods ranked by precedence values and argument count */
+  List *dispatch = Swig_overload_rank(n, true);
+  int nfunc = Len(dispatch);
+
+  /* Loop over the functions */
+
+  for (i = 0; i < nfunc; i++) {
+    int fn = 0;
+    Node *ni = Getitem(dispatch, i);
+    Parm *pi = Getattr(ni, "wrap:parms");
+    int num_required = emit_num_required(pi);
+    int num_arguments = emit_num_arguments(pi);
+    if (num_arguments > *maxargs)
+      *maxargs = num_arguments;
+    int varargs = emit_isvarargs(pi);
+
+    if (!varargs) {
+      if (num_required == num_arguments) {
+	Printf(f, "if (%s == %d) {\n", argc_template_string, num_required);
+      } else {
+	Printf(f, "if ((%s >= %d) && (%s <= %d)) {\n", argc_template_string, num_required, argc_template_string, num_arguments);
+      }
+    } else {
+      Printf(f, "if (%s >= %d) {\n", argc_template_string, num_required);
+    }
+
+    /* create a list with the wrappers that collide with the
+       current one based on argument number */
+    List *coll = NewList();
+    for (int k = i + 1; k < nfunc; k++) {
+      Node *nk = Getitem(dispatch, k);
+      Parm *pk = Getattr(nk, "wrap:parms");
+      int nrk = emit_num_required(pk);
+      int nak = emit_num_arguments(pk);
+      if ((nrk >= num_required && nrk <= num_arguments) || (nak >= num_required && nak <= num_arguments) || (nrk <= num_required && nak >= num_arguments))
+	Append(coll, nk);
+    }
+
+    // printf("overload: %s coll=%d\n", Char(Getattr(n, "sym:name")), Len(coll));
+
+    int num_braces = 0;
+    bool test = (Len(coll) > 0 && num_arguments);
+    if (test) {
+      int need_v = 1;
+      j = 0;
+      Parm *pj = pi;
+      while (pj) {
+	if (checkAttribute(pj, "tmap:in:numinputs", "0")) {
+	  pj = Getattr(pj, "tmap:in:next");
+	  continue;
+	}
+
+	String *tm = Getattr(pj, "tmap:typecheck");
+	if (tm) {
+	  /* normalise for comparison later */
+	  Replaceid(tm, Getattr(pj, "lname"), "_v");
+
+	  /* if all the wrappers have the same type check on this
+	     argument we can optimize it out */
+	  bool emitcheck = 0;
+	  for (int k = 0; k < Len(coll) && !emitcheck; k++) {
+	    Node *nk = Getitem(coll, k);
+	    Parm *pk = Getattr(nk, "wrap:parms");
+	    int nak = emit_num_arguments(pk);
+	    if (nak <= j)
+	      continue;
+	    int l = 0;
+	    Parm *pl = pk;
+	    /* finds arg j on the collider wrapper */
+	    while (pl && l <= j) {
+	      if (checkAttribute(pl, "tmap:in:numinputs", "0")) {
+		pl = Getattr(pl, "tmap:in:next");
+		continue;
+	      }
+	      if (l == j) {
+		/* we are at arg j, so we compare the tmaps now */
+		String *tml = Getattr(pl, "tmap:typecheck");
+		/* normalise it before comparing */
+		if (tml)
+		  Replaceid(tml, Getattr(pl, "lname"), "_v");
+		if (!tml || Cmp(tm, tml))
+		  emitcheck = 1;
+		//printf("tmap: %s[%d] (%d) => %s\n\n",
+		//       Char(Getattr(nk, "sym:name")),
+		//       l, emitcheck, tml?Char(tml):0);
+	      }
+	      Parm *pl1 = Getattr(pl, "tmap:in:next");
+	      if (pl1)
+		pl = pl1;
+	      else
+		pl = nextSibling(pl);
+	      l++;
+	    }
+	  }
+
+	  if (emitcheck) {
+	    if (need_v) {
+	      Printf(f, "int _v = 0;\n");
+	      need_v = 0;
+	    }
+	    if (j >= num_required) {
+	      Printf(f, "if (%s > %d) {\n", argc_template_string, j);
+	      num_braces++;
+	    }
+	    String *tmp = NewStringf(argv_template_string, j);
+
+	    String *conv = Getattr(pj, "implicitconv");
+	    if (conv) {
+	      Replaceall(tm, "$implicitconv", conv);
+	    } else {
+	      Replaceall(tm, "$implicitconv", "0");
+	    }
+	    Replaceall(tm, "$input", tmp);
+	    Printv(f, "{\n", tm, "}\n", NIL);
+	    fn = i + 1;
+	    Printf(f, "if (!_v) goto check_%d;\n", fn);
+	  }
+	}
+	if (!Getattr(pj, "tmap:in:SWIGTYPE") && Getattr(pj, "tmap:typecheck:SWIGTYPE")) {
+	  /* we emit  a warning if the argument defines the 'in' typemap, but not the 'typecheck' one */
+	  Swig_warning(WARN_TYPEMAP_TYPECHECK_UNDEF, Getfile(ni), Getline(ni),
+		       "Overloaded method %s with no explicit typecheck typemap for arg %d of type '%s'\n",
+		       Swig_name_decl(n), j, SwigType_str(Getattr(pj, "type"), 0));
+	}
+	Parm *pj1 = Getattr(pj, "tmap:in:next");
+	if (pj1)
+	  pj = pj1;
+	else
+	  pj = nextSibling(pj);
+	j++;
+      }
+    }
+
+    /* close braces */
+    for ( /* empty */ ; num_braces > 0; num_braces--)
+      Printf(f, "}\n");
+
+
+    String *lfmt = ReplaceFormat(fmt, num_arguments);
+    Printf(f, Char(lfmt), Getattr(ni, "wrap:name"));
+
+    Printf(f, "}\n");		/* braces closes "if" for this method */
+    if (fn)
+      Printf(f, "check_%d:\n\n", fn);
+
+    Delete(lfmt);
+    Delete(coll);
+  }
+  Delete(dispatch);
+  return f;
+}
+
+String *Swig_overload_dispatch(Node *n, const String_or_char *fmt, int *maxargs) {
+
+  if (fast_dispatch_mode || GetFlag(n, "feature:fastdispatch")) {
+    return Swig_overload_dispatch_fast(n, fmt, maxargs);
+  }
+
+  int i, j;
+
+  *maxargs = 1;
+
+  String *f = NewString("");
+
+  /* Get a list of methods ranked by precedence values and argument count */
+  List *dispatch = Swig_overload_rank(n, true);
+  int nfunc = Len(dispatch);
+
+  /* Loop over the functions */
+
+  for (i = 0; i < nfunc; i++) {
+    Node *ni = Getitem(dispatch, i);
+    Parm *pi = Getattr(ni, "wrap:parms");
+    int num_required = emit_num_required(pi);
+    int num_arguments = emit_num_arguments(pi);
+    if (num_arguments > *maxargs)
+      *maxargs = num_arguments;
+    int varargs = emit_isvarargs(pi);
+
+    if (!varargs) {
+      if (num_required == num_arguments) {
+	Printf(f, "if (%s == %d) {\n", argc_template_string, num_required);
+      } else {
+	Printf(f, "if ((%s >= %d) && (%s <= %d)) {\n", argc_template_string, num_required, argc_template_string, num_arguments);
+      }
+    } else {
+      Printf(f, "if (%s >= %d) {\n", argc_template_string, num_required);
+    }
+
+    if (num_arguments) {
+      Printf(f, "int _v;\n");
+    }
+
+    int num_braces = 0;
+    j = 0;
+    Parm *pj = pi;
+    while (pj) {
+      if (checkAttribute(pj, "tmap:in:numinputs", "0")) {
+	pj = Getattr(pj, "tmap:in:next");
+	continue;
+      }
+      if (j >= num_required) {
+	String *lfmt = ReplaceFormat(fmt, num_arguments);
+	Printf(f, "if (%s <= %d) {\n", argc_template_string, j);
+	Printf(f, Char(lfmt), Getattr(ni, "wrap:name"));
+	Printf(f, "}\n");
+	Delete(lfmt);
+      }
+      if (print_typecheck(f, j, pj)) {
+	Printf(f, "if (_v) {\n");
+	num_braces++;
+      }
+      if (!Getattr(pj, "tmap:in:SWIGTYPE") && Getattr(pj, "tmap:typecheck:SWIGTYPE")) {
+	/* we emit  a warning if the argument defines the 'in' typemap, but not the 'typecheck' one */
+	Swig_warning(WARN_TYPEMAP_TYPECHECK_UNDEF, Getfile(ni), Getline(ni),
+		     "Overloaded method %s with no explicit typecheck typemap for arg %d of type '%s'\n",
+		     Swig_name_decl(n), j, SwigType_str(Getattr(pj, "type"), 0));
+      }
+      Parm *pk = Getattr(pj, "tmap:in:next");
+      if (pk)
+	pj = pk;
+      else
+	pj = nextSibling(pj);
+      j++;
+    }
+    String *lfmt = ReplaceFormat(fmt, num_arguments);
+    Printf(f, Char(lfmt), Getattr(ni, "wrap:name"));
+    Delete(lfmt);
+    /* close braces */
+    for ( /* empty */ ; num_braces > 0; num_braces--)
+      Printf(f, "}\n");
+    Printf(f, "}\n");		/* braces closes "if" for this method */
+  }
+  Delete(dispatch);
+  return f;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_overload_check()
+ * ----------------------------------------------------------------------------- */
+void Swig_overload_check(Node *n) {
+  Swig_overload_rank(n, false);
+}
diff --git a/trunk/Source/Modules/perl5.cxx b/trunk/Source/Modules/perl5.cxx
new file mode 100644
index 0000000..6e706fc
--- /dev/null
+++ b/trunk/Source/Modules/perl5.cxx
@@ -0,0 +1,1763 @@
+/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
+ *  vim:expandtab:shiftwidth=2:tabstop=8:smarttab:
+ */
+
+/* ----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * perl5.cxx
+ *
+ * Perl5 language module for SWIG.
+ * ------------------------------------------------------------------------- */
+
+char cvsroot_perl5_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+static int treduce = SWIG_cparse_template_reduce(0);
+
+#include <ctype.h>
+
+static const char *usage = (char *) "\
+Perl5 Options (available with -perl5)\n\
+     -static         - Omit code related to dynamic loading\n\
+     -nopm           - Do not generate the .pm file\n\
+     -proxy          - Create proxy classes\n\
+     -noproxy        - Don't create proxy classes\n\
+     -const          - Wrap constants as constants and not variables (implies -proxy)\n\
+     -nocppcast      - Disable C++ casting operators, useful for generating bugs\n\
+     -cppcast        - Enable C++ casting operators\n\
+     -compat         - Compatibility mode\n\n";
+
+static int compat = 0;
+
+static int no_pmfile = 0;
+
+static int export_all = 0;
+
+/*
+ * pmfile
+ *   set by the -pm flag, overrides the name of the .pm file
+ */
+static String *pmfile = 0;
+
+/*
+ * module
+ *   set by the %module directive, e.g. "Xerces". It will determine
+ *   the name of the .pm file, and the dynamic library, and the name
+ *   used by any module wanting to %import the module.
+ */
+static String *module = 0;
+
+/*
+ * namespace_module
+ *   the fully namespace qualified name of the module. It will be used
+ *   to set the package namespace in the .pm file, as well as the name
+ *   of the initialization methods in the glue library. This will be
+ *   the same as module, above, unless the %module directive is given
+ *   the 'package' option, e.g. %module(package="Foo::Bar") "baz"
+ */
+static String       *namespace_module = 0;
+
+/*
+ * cmodule
+ *   the namespace of the internal glue code, set to the value of
+ *   module with a 'c' appended
+ */
+static String *cmodule = 0;
+
+/*
+ * dest_package
+ *   an optional namespace to put all classes into. Specified by using
+ *   the %module(package="Foo::Bar") "baz" syntax
+ */
+static String       *dest_package = 0;
+
+static String *command_tab = 0;
+static String *constant_tab = 0;
+static String *variable_tab = 0;
+
+static File *f_runtime = 0;
+static File *f_header = 0;
+static File *f_wrappers = 0;
+static File *f_init = 0;
+static File *f_pm = 0;
+static String *pm;		/* Package initialization code */
+static String *magic;		/* Magic variable wrappers     */
+
+static int staticoption = 0;
+
+// controlling verbose output
+static int          verbose = 0;
+
+/* The following variables are used to manage Perl5 classes */
+
+static int blessed = 1;		/* Enable object oriented features */
+static int do_constants = 0;	/* Constant wrapping */
+static List *classlist = 0;	/* List of classes */
+static int have_constructor = 0;
+static int have_destructor = 0;
+static int have_data_members = 0;
+static String *class_name = 0;	/* Name of the class (what Perl thinks it is) */
+static String *real_classname = 0;	/* Real name of C/C++ class */
+static String *fullclassname = 0;
+
+static String *pcode = 0;	/* Perl code associated with each class */
+						  /* static  String   *blessedmembers = 0;     *//* Member data associated with each class */
+static int member_func = 0;	/* Set to 1 when wrapping a member function */
+static String *func_stubs = 0;	/* Function stubs */
+static String *const_stubs = 0;	/* Constant stubs */
+static int num_consts = 0;	/* Number of constants */
+static String *var_stubs = 0;	/* Variable stubs */
+static String *exported = 0;	/* Exported symbols */
+static String *pragma_include = 0;
+static String *additional_perl_code = 0;	/* Additional Perl code from %perlcode %{ ... %} */
+static Hash *operators = 0;
+static int have_operators = 0;
+
+class PERL5:public Language {
+public:
+
+  PERL5():Language () {
+    Clear(argc_template_string);
+    Printv(argc_template_string, "items", NIL);
+    Clear(argv_template_string);
+    Printv(argv_template_string, "ST(%d)", NIL);
+  }
+
+  /* Test to see if a type corresponds to something wrapped with a shadow class */
+  Node *is_shadow(SwigType *t) {
+    Node *n;
+    n = classLookup(t);
+    /*  Printf(stdout,"'%s' --> '%x'\n", t, n); */
+    if (n) {
+      if (!Getattr(n, "perl5:proxy")) {
+	setclassname(n);
+      }
+      return Getattr(n, "perl5:proxy");
+    }
+    return 0;
+  }
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+    int i = 1;
+    int cppcast = 1;
+
+    SWIG_library_directory("perl5");
+
+    for (i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-package") == 0) {
+	  Printv(stderr,
+		 "*** -package is no longer supported\n*** use the directive '%module A::B::C' in your interface file instead\n*** see the Perl section in the manual for details.\n", NIL);
+	  SWIG_exit(EXIT_FAILURE);
+	} else if (strcmp(argv[i], "-interface") == 0) {
+	  Printv(stderr,
+		 "*** -interface is no longer supported\n*** use the directive '%module A::B::C' in your interface file instead\n*** see the Perl section in the manual for details.\n", NIL);
+	  SWIG_exit(EXIT_FAILURE);
+	} else if (strcmp(argv[i], "-exportall") == 0) {
+	  export_all = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-static") == 0) {
+	  staticoption = 1;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) {
+	  blessed = 1;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-noproxy") == 0)) {
+	  blessed = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-const") == 0) {
+	  do_constants = 1;
+	  blessed = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nopm") == 0) {
+	  no_pmfile = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-pm") == 0) {
+	  Swig_mark_arg(i);
+	  i++;
+	  pmfile = NewString(argv[i]);
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i],"-v") == 0) {
+	    Swig_mark_arg(i);
+	    verbose++;
+	} else if (strcmp(argv[i], "-cppcast") == 0) {
+	  cppcast = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nocppcast") == 0) {
+	  cppcast = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-compat") == 0) {
+	  compat = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stdout);
+	}
+      }
+    }
+
+    if (cppcast) {
+      Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
+    }
+
+    Preprocessor_define("SWIGPERL 1", 0);
+    Preprocessor_define("SWIGPERL5 1", 0);
+    SWIG_typemap_lang("perl5");
+    SWIG_config_file("perl5.swg");
+    allow_overloading();
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+
+    classlist = NewList();
+
+    pm = NewString("");
+    func_stubs = NewString("");
+    var_stubs = NewString("");
+    const_stubs = NewString("");
+    exported = NewString("");
+    magic = NewString("");
+    pragma_include = NewString("");
+    additional_perl_code = NewString("");
+
+    command_tab = NewString("static swig_command_info swig_commands[] = {\n");
+    constant_tab = NewString("static swig_constant_info swig_constants[] = {\n");
+    variable_tab = NewString("static swig_variable_info swig_variables[] = {\n");
+
+    Swig_banner(f_runtime);
+
+    Printf(f_runtime, "#define SWIGPERL\n");
+    Printf(f_runtime, "#define SWIG_CASTRANK_MODE\n");
+
+
+    // Is the imported module in another package?  (IOW, does it use the
+    // %module(package="name") option and it's different than the package
+    // of this module.)
+    Node *mod = Getattr(n, "module");
+    Node *options = Getattr(mod, "options");
+    module = Copy(Getattr(n,"name"));
+
+    if (verbose > 0) {
+      fprintf(stdout, "top: using module: %s\n", Char(module));
+    }
+
+    dest_package = options ? Getattr(options, "package") : 0;
+    if (dest_package) {
+      namespace_module = Copy(dest_package);
+      if (verbose > 0) {
+	fprintf(stdout, "top: Found package: %s\n",Char(dest_package));
+      }
+    } else {
+      namespace_module = Copy(module);
+      if (verbose > 0) {
+	fprintf(stdout, "top: No package found\n");
+      }
+    }
+    String *underscore_module = Copy(module);
+    Replaceall(underscore_module,":","_");
+
+    if (verbose > 0) {
+      fprintf(stdout, "top: using namespace_module: %s\n", Char(namespace_module));
+    }
+
+    /* If we're in blessed mode, change the package name to "packagec" */
+
+    if (blessed) {
+      cmodule = NewStringf("%sc",namespace_module);
+    } else {
+      cmodule = NewString(namespace_module);
+    }
+
+    /* Create a .pm file
+     * Need to strip off any prefixes that might be found in
+     * the module name */
+
+    if (no_pmfile) {
+      f_pm = NewString(0);
+    } else {
+      if (pmfile == NULL) {
+	char *m = Char(module) + Len(module);
+	while (m != Char(module)) {
+	  if (*m == ':') {
+	    m++;
+	    break;
+	  }
+	  m--;
+	}
+	pmfile = NewStringf("%s.pm", m);
+      }
+      String *filen = NewStringf("%s%s", SWIG_output_directory(), pmfile);
+      if ((f_pm = NewFile(filen, "w")) == 0) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Delete(filen);
+      filen = NULL;
+      Swig_register_filebyname("pm", f_pm);
+      Swig_register_filebyname("perl", f_pm);
+    }
+    {
+      String *boot_name = NewStringf("boot_%s", underscore_module);
+      Printf(f_header,"#define SWIG_init    %s\n\n", boot_name);
+      Printf(f_header,"#define SWIG_name   \"%s::%s\"\n", cmodule, boot_name);
+      Printf(f_header,"#define SWIG_prefix \"%s::\"\n", cmodule);
+      Delete(boot_name);
+    }
+
+    Printf(f_pm, "# This file was automatically generated by SWIG (http://www.swig.org).\n");
+    Printf(f_pm, "# Version %s\n", Swig_package_version());
+    Printf(f_pm, "#\n");
+    Printf(f_pm, "# Don't modify this file, modify the SWIG interface instead.\n");
+    Printf(f_pm, "\n");
+
+    Printf(f_pm, "package %s;\n", module);
+
+    /* 
+     * If the package option has been given we are placing our
+     *   symbols into some other packages namespace, so we do not
+     *   mess with @ISA or require for that package
+     */
+    if (dest_package) {
+      Printf(f_pm,"use base qw(DynaLoader);\n");
+    } else {
+      Printf(f_pm,"use base qw(Exporter);\n");
+      if (!staticoption) {
+	Printf(f_pm,"use base qw(DynaLoader);\n");
+      }
+    }
+
+    /* Start creating magic code */
+
+    Printv(magic,
+           "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n",
+	   "#ifdef PERL_OBJECT\n",
+	   "#define MAGIC_CLASS _wrap_", underscore_module, "_var::\n",
+	   "class _wrap_", underscore_module, "_var : public CPerlObj {\n",
+	   "public:\n",
+	   "#else\n",
+	   "#define MAGIC_CLASS\n",
+	   "#endif\n",
+	   "SWIGCLASS_STATIC int swig_magic_readonly(pTHX_ SV *SWIGUNUSEDPARM(sv), MAGIC *SWIGUNUSEDPARM(mg)) {\n",
+	   tab4, "MAGIC_PPERL\n", tab4, "croak(\"Value is read-only.\");\n", tab4, "return 0;\n", "}\n", NIL);
+
+    Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
+
+    /* emit wrappers */
+    Language::top(n);
+
+    String *base = NewString("");
+
+    /* Dump out variable wrappers */
+
+    Printv(magic, "\n\n#ifdef PERL_OBJECT\n", "};\n", "#endif\n", NIL);
+    Printv(magic, "\n#ifdef __cplusplus\n}\n#endif\n", NIL);
+
+    Printf(f_header, "%s\n", magic);
+
+    String *type_table = NewString("");
+
+    /* Patch the type table to reflect the names used by shadow classes */
+    if (blessed) {
+      Iterator cls;
+      for (cls = First(classlist); cls.item; cls = Next(cls)) {
+	String *pname = Getattr(cls.item, "perl5:proxy");
+	if (pname) {
+	  SwigType *type = Getattr(cls.item, "classtypeobj");
+	  if (!type)
+	    continue;		/* If unnamed class, no type will be found */
+	  type = Copy(type);
+
+	  SwigType_add_pointer(type);
+	  String *mangled = SwigType_manglestr(type);
+	  SwigType_remember_mangleddata(mangled, NewStringf("\"%s\"", pname));
+	  Delete(type);
+	  Delete(mangled);
+	}
+      }
+    }
+    SwigType_emit_type_table(f_runtime, type_table);
+
+    Printf(f_wrappers, "%s", type_table);
+    Delete(type_table);
+
+    Printf(constant_tab, "{0,0,0,0,0,0}\n};\n");
+    Printv(f_wrappers, constant_tab, NIL);
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n");
+
+    Printf(f_init, "\t ST(0) = &PL_sv_yes;\n");
+    Printf(f_init, "\t XSRETURN(1);\n");
+    Printf(f_init, "}\n");
+
+    /* Finish off tables */
+    Printf(variable_tab, "{0,0,0,0}\n};\n");
+    Printv(f_wrappers, variable_tab, NIL);
+
+    Printf(command_tab, "{0,0}\n};\n");
+    Printv(f_wrappers, command_tab, NIL);
+
+
+    Printf(f_pm, "package %s;\n", cmodule);
+
+    if (!staticoption) {
+      Printf(f_pm,"bootstrap %s;\n", module);
+    } else {
+      Printf(f_pm,"package %s;\n", cmodule);
+      Printf(f_pm,"boot_%s();\n", underscore_module);
+    }
+
+    Printf(f_pm, "package %s;\n", module);
+    /* 
+     * If the package option has been given we are placing our
+     *   symbols into some other packages namespace, so we do not
+     *   mess with @EXPORT
+     */
+    if (!dest_package) {
+      Printf(f_pm,"@EXPORT = qw(%s);\n", exported);
+    }
+
+    Printf(f_pm, "%s", pragma_include);
+
+    if (blessed) {
+
+      /*
+       * These methods will be duplicated if package 
+       *   has been specified, so we do not output them
+       */
+      if (!dest_package) {
+	Printv(base, "\n# ---------- BASE METHODS -------------\n\n", "package ", namespace_module, ";\n\n", NIL);
+
+	/* Write out the TIE method */
+
+	Printv(base, "sub TIEHASH {\n", tab4, "my ($classname,$obj) = @_;\n", tab4, "return bless $obj, $classname;\n", "}\n\n", NIL);
+
+	/* Output a CLEAR method.   This is just a place-holder, but by providing it we
+	 * can make declarations such as
+	 *     %$u = ( x => 2, y=>3, z =>4 );
+	 *
+	 * Where x,y,z are the members of some C/C++ object. */
+
+	Printf(base, "sub CLEAR { }\n\n");
+
+	/* Output default firstkey/nextkey methods */
+
+	Printf(base, "sub FIRSTKEY { }\n\n");
+	Printf(base, "sub NEXTKEY { }\n\n");
+
+	/* Output a FETCH method.  This is actually common to all classes */
+	Printv(base,
+	       "sub FETCH {\n",
+	       tab4, "my ($self,$field) = @_;\n", tab4, "my $member_func = \"swig_${field}_get\";\n", tab4, "$self->$member_func();\n", "}\n\n", NIL);
+
+	/* Output a STORE method.   This is also common to all classes (might move to base class) */
+
+	Printv(base,
+	       "sub STORE {\n",
+	       tab4, "my ($self,$field,$newval) = @_;\n",
+	       tab4, "my $member_func = \"swig_${field}_set\";\n", tab4, "$self->$member_func($newval);\n", "}\n\n", NIL);
+
+	/* Output a 'this' method */
+
+	Printv(base, "sub this {\n", tab4, "my $ptr = shift;\n", tab4, "return tied(%$ptr);\n", "}\n\n", NIL);
+
+	Printf(f_pm, "%s", base);
+      }
+
+      /* Emit function stubs for stand-alone functions */
+      Printf(f_pm, "\n# ------- FUNCTION WRAPPERS --------\n\n");
+      Printf(f_pm, "package %s;\n\n", namespace_module);
+      Printf(f_pm, "%s", func_stubs);
+
+      /* Emit package code for different classes */
+      Printf(f_pm, "%s", pm);
+
+      if (num_consts > 0) {
+	/* Emit constant stubs */
+	Printf(f_pm, "\n# ------- CONSTANT STUBS -------\n\n");
+	Printf(f_pm, "package %s;\n\n", namespace_module);
+	Printf(f_pm, "%s", const_stubs);
+      }
+
+      /* Emit variable stubs */
+
+      Printf(f_pm, "\n# ------- VARIABLE STUBS --------\n\n");
+      Printf(f_pm, "package %s;\n\n", namespace_module);
+      Printf(f_pm, "%s", var_stubs);
+    }
+
+    /* Add additional Perl code at the end */
+    Printf(f_pm, "%s", additional_perl_code);
+
+    Printf(f_pm, "1;\n");
+    Close(f_pm);
+    Delete(f_pm);
+    Delete(base);
+    Delete(dest_package);
+    Delete(underscore_module);
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    Delete(f_runtime);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * importDirective(Node *n)
+   * ------------------------------------------------------------ */
+
+  virtual int importDirective(Node *n) {
+    if (blessed) {
+      String *modname = Getattr(n, "module");
+      if (modname) {
+	Printf(f_pm, "require %s;\n", modname);
+      }
+    }
+    return Language::importDirective(n);
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int functionWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *overname = 0;
+
+    Parm *p;
+    int i;
+    Wrapper *f;
+    char source[256], temp[256];
+    String *tm;
+    String *cleanup, *outarg;
+    int num_saved = 0;
+    int num_arguments, num_required;
+    int varargs = 0;
+
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n))
+	return SWIG_ERROR;
+    }
+
+    f = NewWrapper();
+    cleanup = NewString("");
+    outarg = NewString("");
+
+    String *wname = Swig_name_wrapper(iname);
+    if (overname) {
+      Append(wname, overname);
+    }
+    Setattr(n, "wrap:name", wname);
+    Printv(f->def, "XS(", wname, ") {\n", "{\n",	/* scope to destroy C++ objects before croaking */
+	   NIL);
+
+    emit_parameter_variables(l, f);
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    num_arguments = emit_num_arguments(l);
+    num_required = emit_num_required(l);
+    varargs = emit_isvarargs(l);
+
+    Wrapper_add_local(f, "argvi", "int argvi = 0");
+
+    /* Check the number of arguments */
+    if (!varargs) {
+      Printf(f->code, "    if ((items < %d) || (items > %d)) {\n", num_required, num_arguments);
+    } else {
+      Printf(f->code, "    if (items < %d) {\n", num_required);
+    }
+    Printf(f->code, "        SWIG_croak(\"Usage: %s\");\n", usage_func(Char(iname), d, l));
+    Printf(f->code, "}\n");
+
+    /* Write code to extract parameters. */
+    i = 0;
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      /* Skip ignored arguments */
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+
+      /* Produce string representation of source and target arguments */
+      sprintf(source, "ST(%d)", i);
+      String *target = Getattr(p, "lname");
+
+      if (i >= num_required) {
+	Printf(f->code, "    if (items > %d) {\n", i);
+      }
+      if ((tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$target", target);
+	Replaceall(tm, "$source", source);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);	/* Save input location */
+
+	if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+	  Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	} else {
+	  Replaceall(tm, "$disown", "0");
+	}
+
+	Printf(f->code, "%s\n", tm);
+	p = Getattr(p, "tmap:in:next");
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+	p = nextSibling(p);
+      }
+      if (i >= num_required) {
+	Printf(f->code, "    }\n");
+      }
+    }
+
+    if (varargs) {
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+	sprintf(source, "ST(%d)", i);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);
+	Printf(f->code, "if (items >= %d) {\n", i);
+	Printv(f->code, tm, "\n", NIL);
+	Printf(f->code, "}\n");
+      }
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (i = 0, p = l; p; i++) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    num_saved = 0;
+    for (i = 0, p = l; p; i++) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	SwigType *t = Getattr(p, "type");
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$target", "ST(argvi)");
+	Replaceall(tm, "$result", "ST(argvi)");
+	if (is_shadow(t)) {
+	  Replaceall(tm, "$shadow", "SWIG_SHADOW");
+	} else {
+	  Replaceall(tm, "$shadow", "0");
+	}
+
+	String *in = Getattr(p, "emit:input");
+	if (in) {
+	  sprintf(temp, "_saved[%d]", num_saved);
+	  Replaceall(tm, "$arg", temp);
+	  Replaceall(tm, "$input", temp);
+	  Printf(f->code, "_saved[%d] = %s;\n", num_saved, in);
+	  num_saved++;
+	}
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* If there were any saved arguments, emit a local variable for them */
+    if (num_saved) {
+      sprintf(temp, "_saved[%d]", num_saved);
+      Wrapper_add_localv(f, "_saved", "SV *", temp, NIL);
+    }
+
+    /* Now write code to make the function call */
+
+    Swig_director_emit_dynamic_cast(n, f);
+    String *actioncode = emit_action(n);
+
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      SwigType *t = Getattr(n, "type");
+      Replaceall(tm, "$source", "result");
+      Replaceall(tm, "$target", "ST(argvi)");
+      Replaceall(tm, "$result", "ST(argvi)");
+      if (is_shadow(t)) {
+	Replaceall(tm, "$shadow", "SWIG_SHADOW");
+      } else {
+	Replaceall(tm, "$shadow", "0");
+      }
+      if (GetFlag(n, "feature:new")) {
+	Replaceall(tm, "$owner", "SWIG_OWNER");
+      } else {
+	Replaceall(tm, "$owner", "0");
+      }
+      Printf(f->code, "%s\n", tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
+    }
+    emit_return_variable(n, d, f);
+
+    /* If there were any output args, take care of them. */
+
+    Printv(f->code, outarg, NIL);
+
+    /* If there was any cleanup, do that. */
+
+    Printv(f->code, cleanup, NIL);
+
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printf(f->code, "%s\n", tm);
+    }
+
+    Printv(f->code, "XSRETURN(argvi);\n", "fail:\n", cleanup, "SWIG_croak_null();\n" "}\n" "}\n", NIL);
+
+    /* Add the dXSARGS last */
+
+    Wrapper_add_local(f, "dXSARGS", "dXSARGS");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+    Replaceall(f->code, "$symname", iname);
+
+    /* Dump the wrapper function */
+
+    Wrapper_print(f, f_wrappers);
+
+    /* Now register the function */
+
+    if (!Getattr(n, "sym:overloaded")) {
+      Printf(command_tab, "{\"%s::%s\", %s},\n", cmodule, iname, wname);
+    } else if (!Getattr(n, "sym:nextSibling")) {
+      /* Generate overloaded dispatch function */
+      int maxargs;
+      String *dispatch = Swig_overload_dispatch_cast(n, "++PL_markstack_ptr; SWIG_CALLXS(%s); return;", &maxargs);
+
+      /* Generate a dispatch wrapper for all overloaded functions */
+
+      Wrapper *df = NewWrapper();
+      String *dname = Swig_name_wrapper(iname);
+
+      Printv(df->def, "XS(", dname, ") {\n", NIL);
+
+      Wrapper_add_local(df, "dXSARGS", "dXSARGS");
+      Printv(df->code, dispatch, "\n", NIL);
+      Printf(df->code, "croak(\"No matching function for overloaded '%s'\");\n", iname);
+      Printf(df->code, "XSRETURN(0);\n");
+      Printv(df->code, "}\n", NIL);
+      Wrapper_print(df, f_wrappers);
+      Printf(command_tab, "{\"%s::%s\", %s},\n", cmodule, iname, dname);
+      DelWrapper(df);
+      Delete(dispatch);
+      Delete(dname);
+    }
+    if (!Getattr(n, "sym:nextSibling")) {
+      if (export_all) {
+	Printf(exported, "%s ", iname);
+      }
+
+      /* --------------------------------------------------------------------
+       * Create a stub for this function, provided it's not a member function
+       * -------------------------------------------------------------------- */
+
+      if ((blessed) && (!member_func)) {
+	Printv(func_stubs, "*", iname, " = *", cmodule, "::", iname, ";\n", NIL);
+      }
+
+    }
+    Delete(cleanup);
+    Delete(outarg);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   * ------------------------------------------------------------ */
+  virtual int variableWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    Wrapper *getf, *setf;
+    String *tm;
+    String *getname = Swig_name_get(iname);
+    String *setname = Swig_name_set(iname);
+
+    String *get_name = Swig_name_wrapper(getname);
+    String *set_name = Swig_name_wrapper(setname);
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    getf = NewWrapper();
+    setf = NewWrapper();
+
+    /* Create a Perl function for setting the variable value */
+
+    if (!GetFlag(n, "feature:immutable")) {
+      Setattr(n, "wrap:name", set_name);
+      Printf(setf->def, "SWIGCLASS_STATIC int %s(pTHX_ SV* sv, MAGIC * SWIGUNUSEDPARM(mg)) {\n", set_name);
+      Printv(setf->code, tab4, "MAGIC_PPERL\n", NIL);
+
+      /* Check for a few typemaps */
+      tm = Swig_typemap_lookup("varin", n, name, 0);
+      if (tm) {
+	Replaceall(tm, "$source", "sv");
+	Replaceall(tm, "$target", name);
+	Replaceall(tm, "$input", "sv");
+	/* Printf(setf->code,"%s\n", tm); */
+	emit_action_code(n, setf->code, tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
+	return SWIG_NOWRAP;
+      }
+      Printf(setf->code, "fail:\n");
+      Printf(setf->code, "    return 1;\n}\n");
+      Replaceall(setf->code, "$symname", iname);
+      Wrapper_print(setf, magic);
+    }
+
+    /* Now write a function to evaluate the variable */
+    Setattr(n, "wrap:name", get_name);
+    int addfail = 0;
+    Printf(getf->def, "SWIGCLASS_STATIC int %s(pTHX_ SV *sv, MAGIC *SWIGUNUSEDPARM(mg)) {\n", get_name);
+    Printv(getf->code, tab4, "MAGIC_PPERL\n", NIL);
+
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+      Replaceall(tm, "$target", "sv");
+      Replaceall(tm, "$result", "sv");
+      Replaceall(tm, "$source", name);
+      if (is_shadow(t)) {
+	Replaceall(tm, "$shadow", "SWIG_SHADOW");
+      } else {
+	Replaceall(tm, "$shadow", "0");
+      }
+      /* Printf(getf->code,"%s\n", tm); */
+      addfail = emit_action_code(n, getf->code, tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+      DelWrapper(setf);
+      DelWrapper(getf);
+      return SWIG_NOWRAP;
+    }
+    Printf(getf->code, "    return 1;\n");
+    if (addfail) {
+      Append(getf->code, "fail:\n");
+      Append(getf->code, "  return 0;\n");
+    }
+    Append(getf->code, "}\n");
+
+
+    Replaceall(getf->code, "$symname", iname);
+    Wrapper_print(getf, magic);
+
+    String *tt = Getattr(n, "tmap:varout:type");
+    if (tt) {
+      String *tm = NewStringf("&SWIGTYPE%s", SwigType_manglestr(t));
+      if (Replaceall(tt, "$1_descriptor", tm)) {
+	SwigType_remember(t);
+      }
+      Delete(tm);
+      SwigType *st = Copy(t);
+      SwigType_add_pointer(st);
+      tm = NewStringf("&SWIGTYPE%s", SwigType_manglestr(st));
+      if (Replaceall(tt, "$&1_descriptor", tm)) {
+	SwigType_remember(st);
+      }
+      Delete(tm);
+      Delete(st);
+    } else {
+      tt = (String *) "0";
+    }
+    /* Now add symbol to the PERL interpreter */
+    if (GetFlag(n, "feature:immutable")) {
+      Printv(variable_tab, tab4, "{ \"", cmodule, "::", iname, "\", MAGIC_CLASS swig_magic_readonly, MAGIC_CLASS ", get_name, ",", tt, " },\n", NIL);
+
+    } else {
+      Printv(variable_tab, tab4, "{ \"", cmodule, "::", iname, "\", MAGIC_CLASS ", set_name, ", MAGIC_CLASS ", get_name, ",", tt, " },\n", NIL);
+    }
+
+    /* If we're blessed, try to figure out what to do with the variable
+       1.  If it's a Perl object of some sort, create a tied-hash
+       around it.
+       2.  Otherwise, just hack Perl's symbol table */
+
+    if (blessed) {
+      if (is_shadow(t)) {
+	Printv(var_stubs,
+	       "\nmy %__", iname, "_hash;\n",
+	       "tie %__", iname, "_hash,\"", is_shadow(t), "\", $",
+	       cmodule, "::", iname, ";\n", "$", iname, "= \\%__", iname, "_hash;\n", "bless $", iname, ", ", is_shadow(t), ";\n", NIL);
+      } else {
+	Printv(var_stubs, "*", iname, " = *", cmodule, "::", iname, ";\n", NIL);
+      }
+    }
+    if (export_all)
+      Printf(exported, "$%s ", iname);
+
+    DelWrapper(setf);
+    DelWrapper(getf);
+    Delete(getname);
+    Delete(setname);
+    Delete(set_name);
+    Delete(get_name);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    /* Special hook for member pointer */
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(iname);
+      Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value);
+      value = Char(wname);
+    }
+
+    if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      if (is_shadow(type)) {
+	Replaceall(tm, "$shadow", "SWIG_SHADOW");
+      } else {
+	Replaceall(tm, "$shadow", "0");
+      }
+      Printf(constant_tab, "%s,\n", tm);
+    } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      if (is_shadow(type)) {
+	Replaceall(tm, "$shadow", "SWIG_SHADOW");
+      } else {
+	Replaceall(tm, "$shadow", "0");
+      }
+      Printf(f_init, "%s\n", tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+
+    if (blessed) {
+      if (is_shadow(type)) {
+	Printv(var_stubs,
+	       "\nmy %__", iname, "_hash;\n",
+	       "tie %__", iname, "_hash,\"", is_shadow(type), "\", $",
+	       cmodule, "::", iname, ";\n", "$", iname, "= \\%__", iname, "_hash;\n", "bless $", iname, ", ", is_shadow(type), ";\n", NIL);
+      } else if (do_constants) {
+	Printv(const_stubs, "sub ", name, " () { $", cmodule, "::", name, " }\n", NIL);
+	num_consts++;
+      } else {
+	Printv(var_stubs, "*", iname, " = *", cmodule, "::", iname, ";\n", NIL);
+      }
+    }
+    if (export_all) {
+      if (do_constants && !is_shadow(type)) {
+	Printf(exported, "%s ", name);
+      } else {
+	Printf(exported, "$%s ", iname);
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * usage_func()
+   * ------------------------------------------------------------ */
+  char *usage_func(char *iname, SwigType *, ParmList *l) {
+    static String *temp = 0;
+    Parm *p;
+    int i;
+
+    if (!temp)
+      temp = NewString("");
+    Clear(temp);
+    Printf(temp, "%s(", iname);
+
+    /* Now go through and print parameters */
+    p = l;
+    i = 0;
+    while (p != 0) {
+      SwigType *pt = Getattr(p, "type");
+      String *pn = Getattr(p, "name");
+      if (!checkAttribute(p,"tmap:in:numinputs","0")) {
+	/* If parameter has been named, use that.   Otherwise, just print a type  */
+	if (SwigType_type(pt) != T_VOID) {
+	  if (Len(pn) > 0) {
+	    Printf(temp, "%s", pn);
+	  } else {
+	    Printf(temp, "%s", SwigType_str(pt, 0));
+	  }
+	}
+	i++;
+	p = nextSibling(p);
+	if (p)
+	  if (!checkAttribute(p,"tmap:in:numinputs","0"))
+	    Putc(',', temp);
+      } else {
+	p = nextSibling(p);
+	if (p)
+	  if ((i > 0) && (!checkAttribute(p,"tmap:in:numinputs","0")))
+	    Putc(',', temp);
+      }
+    }
+    Printf(temp, ");");
+    return Char(temp);
+  }
+
+  /* ------------------------------------------------------------
+   * nativeWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int nativeWrapper(Node *n) {
+    String *name = Getattr(n, "sym:name");
+    String *funcname = Getattr(n, "wrap:name");
+
+    if (!addSymbol(funcname, n))
+      return SWIG_ERROR;
+
+    Printf(command_tab, "{\"%s::%s\", %s},\n", cmodule, name, funcname);
+    if (export_all)
+      Printf(exported, "%s ", name);
+    if (blessed) {
+      Printv(func_stubs, "*", name, " = *", cmodule, "::", name, ";\n", NIL);
+    }
+    return SWIG_OK;
+  }
+
+/* ----------------------------------------------------------------------------
+ *                      OBJECT-ORIENTED FEATURES
+ *
+ * These extensions provide a more object-oriented interface to C++
+ * classes and structures.    The code here is based on extensions
+ * provided by David Fletcher and Gary Holt.
+ *
+ * I have generalized these extensions to make them more general purpose
+ * and to resolve object-ownership problems.
+ *
+ * The approach here is very similar to the Python module :
+ *       1.   All of the original methods are placed into a single
+ *            package like before except that a 'c' is appended to the
+ *            package name.
+ *
+ *       2.   All methods and function calls are wrapped with a new
+ *            perl function.   While possibly inefficient this allows
+ *            us to catch complex function arguments (which are hard to
+ *            track otherwise).
+ *
+ *       3.   Classes are represented as tied-hashes in a manner similar
+ *            to Gary Holt's extension.   This allows us to access
+ *            member data.
+ *
+ *       4.   Stand-alone (global) C functions are modified to take
+ *            tied hashes as arguments for complex datatypes (if
+ *            appropriate).
+ *
+ *       5.   Global variables involving a class/struct is encapsulated
+ *            in a tied hash.
+ *
+ * ------------------------------------------------------------------------- */
+
+
+  void setclassname(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    String *fullname;
+    String *actualpackage;
+    Node *clsmodule = Getattr(n, "module");
+
+    if (!clsmodule) {
+      /* imported module does not define a module name.   Oh well */
+      return;
+    }
+
+    /* Do some work on the class name */
+    if (verbose > 0) {
+      fprintf(stdout, "setclassname: Found sym:name: %s\n", Char(symname));
+      fprintf(stdout, "setclassname: Found module: %s\n", Char(clsmodule));
+      fprintf(stdout, "setclassname: No package found\n");
+    }
+
+    if (dest_package) {
+      fullname = NewStringf("%s::%s", namespace_module, symname);
+    } else {
+      actualpackage = Getattr(clsmodule,"name");
+
+      if (verbose > 0) {
+	fprintf(stdout, "setclassname: Found actualpackage: %s\n", Char(actualpackage));
+      }
+      if ((!compat) && (!Strchr(symname,':'))) {
+	fullname = NewStringf("%s::%s",actualpackage,symname);
+      } else {
+	fullname = NewString(symname);
+      }
+    }
+    if (verbose > 0) {
+      fprintf(stdout, "setclassname: setting proxy: %s\n", Char(fullname));
+    }
+    Setattr(n, "perl5:proxy", fullname);
+  }
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+  virtual int classDeclaration(Node *n) {
+    /* Do some work on the class name */
+    if (!Getattr(n, "feature:onlychildren")) {
+      if (blessed) {
+	setclassname(n);
+	Append(classlist, n);
+      }
+    }
+
+    return Language::classDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int classHandler(Node *n) {
+
+    if (blessed) {
+      have_constructor = 0;
+      have_operators = 0;
+      have_destructor = 0;
+      have_data_members = 0;
+      operators = NewHash();
+
+      class_name = Getattr(n, "sym:name");
+
+      if (!addSymbol(class_name, n))
+	return SWIG_ERROR;
+
+      /* Use the fully qualified name of the Perl class */
+      if (!compat) {
+	fullclassname = NewStringf("%s::%s", namespace_module, class_name);
+      } else {
+	fullclassname = NewString(class_name);
+      }
+      real_classname = Getattr(n, "name");
+      pcode = NewString("");
+      // blessedmembers = NewString("");
+    }
+
+    /* Emit all of the members */
+    Language::classHandler(n);
+
+
+    /* Finish the rest of the class */
+    if (blessed) {
+      /* Generate a client-data entry */
+      SwigType *ct = NewStringf("p.%s", real_classname);
+      Printv(f_init, "SWIG_TypeClientData(SWIGTYPE", SwigType_manglestr(ct), ", (void*) \"", fullclassname, "\");\n", NIL);
+      SwigType_remember(ct);
+      Delete(ct);
+
+      Printv(pm, "\n############# Class : ", fullclassname, " ##############\n", "\npackage ", fullclassname, ";\n", NIL);
+
+      if (have_operators) {
+	Printf(pm, "use overload\n");
+	Iterator ki;
+	for (ki = First(operators); ki.key; ki = Next(ki)) {
+	  char *name = Char(ki.key);
+	  //        fprintf(stderr,"found name: <%s>\n", name);
+	  if (strstr(name, "__eq__")) {
+	    Printv(pm, tab4, "\"==\" => sub { $_[0]->__eq__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__ne__")) {
+	    Printv(pm, tab4, "\"!=\" => sub { $_[0]->__ne__($_[1])},\n",NIL);
+	    // there are no tests for this in operator_overload_runme.pl
+	    // it is likely to be broken
+	    //	  } else if (strstr(name, "__assign__")) {
+	    //	    Printv(pm, tab4, "\"=\" => sub { $_[0]->__assign__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__str__")) {
+	    Printv(pm, tab4, "'\"\"' => sub { $_[0]->__str__()},\n",NIL);
+	  } else if (strstr(name, "__plusplus__")) {
+	    Printv(pm, tab4, "\"++\" => sub { $_[0]->__plusplus__()},\n",NIL);
+	  } else if (strstr(name, "__minmin__")) {
+	    Printv(pm, tab4, "\"--\" => sub { $_[0]->__minmin__()},\n",NIL);
+	  } else if (strstr(name, "__add__")) {
+	    Printv(pm, tab4, "\"+\" => sub { $_[0]->__add__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__sub__")) {
+	    Printv(pm, tab4, "\"-\" => sub {  if( not $_[2] ) { $_[0]->__sub__($_[1]) }\n",NIL);
+	    Printv(pm, tab8, "elsif( $_[0]->can('__rsub__') ) { $_[0]->__rsub__($_[1]) }\n",NIL);
+	    Printv(pm, tab8, "else { die(\"reverse subtraction not supported\") }\n",NIL);
+	    Printv(pm, tab8, "},\n",NIL);
+	  } else if (strstr(name, "__mul__")) {
+	    Printv(pm, tab4, "\"*\" => sub { $_[0]->__mul__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__div__")) {
+	    Printv(pm, tab4, "\"/\" => sub { $_[0]->__div__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__mod__")) {
+	    Printv(pm, tab4, "\"%\" => sub { $_[0]->__mod__($_[1])},\n",NIL);
+	    // there are no tests for this in operator_overload_runme.pl
+	    // it is likely to be broken
+	    //	  } else if (strstr(name, "__and__")) {
+	    //	    Printv(pm, tab4, "\"&\" => sub { $_[0]->__and__($_[1])},\n",NIL);
+
+	    // there are no tests for this in operator_overload_runme.pl
+	    // it is likely to be broken
+	    //	  } else if (strstr(name, "__or__")) {
+	    //	    Printv(pm, tab4, "\"|\" => sub { $_[0]->__or__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__gt__")) {
+	    Printv(pm, tab4, "\">\" => sub { $_[0]->__gt__($_[1])},\n",NIL);
+          } else if (strstr(name, "__ge__")) {
+            Printv(pm, tab4, "\">=\" => sub { $_[0]->__ge__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__not__")) {
+	    Printv(pm, tab4, "\"!\" => sub { $_[0]->__not__()},\n",NIL);
+	  } else if (strstr(name, "__lt__")) {
+	    Printv(pm, tab4, "\"<\" => sub { $_[0]->__lt__($_[1])},\n",NIL);
+          } else if (strstr(name, "__le__")) {
+            Printv(pm, tab4, "\"<=\" => sub { $_[0]->__le__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__pluseq__")) {
+	    Printv(pm, tab4, "\"+=\" => sub { $_[0]->__pluseq__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__mineq__")) {
+	    Printv(pm, tab4, "\"-=\" => sub { $_[0]->__mineq__($_[1])},\n",NIL);
+	  } else if (strstr(name, "__neg__")) {
+	    Printv(pm, tab4, "\"neg\" => sub { $_[0]->__neg__()},\n",NIL);
+	  } else {
+	    fprintf(stderr,"Unknown operator: %s\n", name);
+	  }
+	}
+	Printv(pm, tab4,
+               "\"=\" => sub { my $class = ref($_[0]); $class->new($_[0]) },\n", NIL);
+	Printv(pm, tab4, "\"fallback\" => 1;\n", NIL);
+      }
+      // make use strict happy
+      Printv(pm, "use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);\n", NIL);
+
+      /* If we are inheriting from a base class, set that up */
+
+      Printv(pm, "@ISA = qw(", NIL);
+
+      /* Handle inheritance */
+      List *baselist = Getattr(n, "bases");
+      if (baselist && Len(baselist)) {
+	Iterator b;
+	b = First(baselist);
+	while (b.item) {
+	  String *bname = Getattr(b.item, "perl5:proxy");
+	  if (!bname) {
+	    b = Next(b);
+	    continue;
+	  }
+	  Printv(pm, " ", bname, NIL);
+	  b = Next(b);
+	}
+      }
+
+      /* Module comes last */
+      if (!compat || Cmp(namespace_module, fullclassname)) {
+	Printv(pm, " ", namespace_module, NIL);
+      }
+
+      Printf(pm, " );\n");
+
+      /* Dump out a hash table containing the pointers that we own */
+      Printf(pm, "%%OWNER = ();\n");
+      if (have_data_members || have_destructor)
+	Printf(pm, "%%ITERATORS = ();\n");
+
+      /* Dump out the package methods */
+
+      Printv(pm, pcode, NIL);
+      Delete(pcode);
+
+      /* Output methods for managing ownership */
+
+      Printv(pm,
+	     "sub DISOWN {\n",
+	     tab4, "my $self = shift;\n",
+	     tab4, "my $ptr = tied(%$self);\n",
+	     tab4, "delete $OWNER{$ptr};\n",
+	     "}\n\n", "sub ACQUIRE {\n", tab4, "my $self = shift;\n", tab4, "my $ptr = tied(%$self);\n", tab4, "$OWNER{$ptr} = 1;\n", "}\n\n", NIL);
+
+      /* Only output the following methods if a class has member data */
+
+      Delete(operators);
+      operators = 0;
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberfunctionHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+
+    member_func = 1;
+    Language::memberfunctionHandler(n);
+    member_func = 0;
+
+    if ((blessed) && (!Getattr(n, "sym:nextSibling"))) {
+
+      if (Strstr(symname, "__eq__")) {
+	DohSetInt(operators, "__eq__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__ne__")) {
+	DohSetInt(operators, "__ne__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__assign__")) {
+	DohSetInt(operators, "__assign__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__str__")) {
+	DohSetInt(operators, "__str__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__add__")) {
+	DohSetInt(operators, "__add__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__sub__")) {
+	DohSetInt(operators, "__sub__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__mul__")) {
+	DohSetInt(operators, "__mul__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__div__")) {
+	DohSetInt(operators, "__div__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__mod__")) {
+	DohSetInt(operators, "__mod__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__and__")) {
+	DohSetInt(operators, "__and__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__or__")) {
+	DohSetInt(operators, "__or__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__not__")) {
+	DohSetInt(operators, "__not__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__gt__")) {
+	DohSetInt(operators, "__gt__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__ge__")) {
+	DohSetInt(operators, "__ge__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__lt__")) {
+	DohSetInt(operators, "__lt__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__le__")) {
+	DohSetInt(operators, "__le__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__neg__")) {
+	DohSetInt(operators, "__neg__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__plusplus__")) {
+	DohSetInt(operators, "__plusplus__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__minmin__")) {
+	DohSetInt(operators, "__minmin__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__mineq__")) {
+	DohSetInt(operators, "__mineq__", 1);
+	have_operators = 1;
+      } else if (Strstr(symname, "__pluseq__")) {
+	DohSetInt(operators, "__pluseq__", 1);
+	have_operators = 1;
+      }
+
+      if (Getattr(n, "feature:shadow")) {
+	String *plcode = perlcode(Getattr(n, "feature:shadow"), 0);
+	String *plaction = NewStringf("%s::%s", cmodule, Swig_name_member(class_name, symname));
+	Replaceall(plcode, "$action", plaction);
+	Delete(plaction);
+	Printv(pcode, plcode, NIL);
+      } else {
+	Printv(pcode, "*", symname, " = *", cmodule, "::", Swig_name_member(class_name, symname), ";\n", NIL);
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   *
+   * Adds an instance member.
+   * ----------------------------------------------------------------------------- */
+
+  virtual int membervariableHandler(Node *n) {
+
+    String *symname = Getattr(n, "sym:name");
+    /* SwigType *t  = Getattr(n,"type"); */
+
+    /* Emit a pair of get/set functions for the variable */
+
+    member_func = 1;
+    Language::membervariableHandler(n);
+    member_func = 0;
+
+    if (blessed) {
+
+      Printv(pcode, "*swig_", symname, "_get = *", cmodule, "::", Swig_name_get(Swig_name_member(class_name, symname)), ";\n", NIL);
+      Printv(pcode, "*swig_", symname, "_set = *", cmodule, "::", Swig_name_set(Swig_name_member(class_name, symname)), ";\n", NIL);
+
+      /* Now we need to generate a little Perl code for this */
+
+      /* if (is_shadow(t)) {
+
+       *//* This is a Perl object that we have already seen.  Add an
+         entry to the members list *//*
+         Printv(blessedmembers,
+         tab4, symname, " => '", is_shadow(t), "',\n",
+         NIL);
+
+         }
+       */
+    }
+    have_data_members++;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constructorDeclaration()
+   *
+   * Emits a blessed constructor for our class.    In addition to our construct
+   * we manage a Perl hash table containing all of the pointers created by
+   * the constructor.   This prevents us from accidentally trying to free
+   * something that wasn't necessarily allocated by malloc or new
+   * ------------------------------------------------------------ */
+
+  virtual int constructorHandler(Node *n) {
+
+    String *symname = Getattr(n, "sym:name");
+
+    member_func = 1;
+    Language::constructorHandler(n);
+
+    if ((blessed) && (!Getattr(n, "sym:nextSibling"))) {
+      if (Getattr(n, "feature:shadow")) {
+	String *plcode = perlcode(Getattr(n, "feature:shadow"), 0);
+	String *plaction = NewStringf("%s::%s", module, Swig_name_member(class_name, symname));
+	Replaceall(plcode, "$action", plaction);
+	Delete(plaction);
+	Printv(pcode, plcode, NIL);
+      } else {
+	if ((Cmp(symname, class_name) == 0)) {
+	  /* Emit a blessed constructor  */
+	  Printf(pcode, "sub new {\n");
+	} else {
+	  /* Constructor doesn't match classname so we'll just use the normal name  */
+	  Printv(pcode, "sub ", Swig_name_construct(symname), " () {\n", NIL);
+	}
+
+	Printv(pcode,
+	       tab4, "my $pkg = shift;\n",
+	       tab4, "my $self = ", cmodule, "::", Swig_name_construct(symname), "(@_);\n", tab4, "bless $self, $pkg if defined($self);\n", "}\n\n", NIL);
+
+	have_constructor = 1;
+      }
+    }
+    member_func = 0;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------ 
+   * destructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int destructorHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    member_func = 1;
+    Language::destructorHandler(n);
+    if (blessed) {
+      if (Getattr(n, "feature:shadow")) {
+	String *plcode = perlcode(Getattr(n, "feature:shadow"), 0);
+	String *plaction = NewStringf("%s::%s", module, Swig_name_member(class_name, symname));
+	Replaceall(plcode, "$action", plaction);
+	Delete(plaction);
+	Printv(pcode, plcode, NIL);
+      } else {
+	Printv(pcode,
+	       "sub DESTROY {\n",
+	       tab4, "return unless $_[0]->isa('HASH');\n",
+	       tab4, "my $self = tied(%{$_[0]});\n",
+	       tab4, "return unless defined $self;\n",
+	       tab4, "delete $ITERATORS{$self};\n",
+	       tab4, "if (exists $OWNER{$self}) {\n",
+	       tab8, cmodule, "::", Swig_name_destroy(symname), "($self);\n", tab8, "delete $OWNER{$self};\n", tab4, "}\n}\n\n", NIL);
+	have_destructor = 1;
+      }
+    }
+    member_func = 0;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    member_func = 1;
+    Language::staticmemberfunctionHandler(n);
+    member_func = 0;
+    if ((blessed) && (!Getattr(n, "sym:nextSibling"))) {
+      String *symname = Getattr(n, "sym:name");
+      Printv(pcode, "*", symname, " = *", cmodule, "::", Swig_name_member(class_name, symname), ";\n", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmembervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int staticmembervariableHandler(Node *n) {
+    Language::staticmembervariableHandler(n);
+    if (blessed) {
+      String *symname = Getattr(n, "sym:name");
+      Printv(pcode, "*", symname, " = *", cmodule, "::", Swig_name_member(class_name, symname), ";\n", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberconstantHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberconstantHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    int oldblessed = blessed;
+
+    /* Create a normal constant */
+    blessed = 0;
+    Language::memberconstantHandler(n);
+    blessed = oldblessed;
+
+    if (blessed) {
+      Printv(pcode, "*", symname, " = *", cmodule, "::", Swig_name_member(class_name, symname), ";\n", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * pragma()
+   *
+   * Pragma directive.
+   *
+   * %pragma(perl5) code="String"              # Includes a string in the .pm file
+   * %pragma(perl5) include="file.pl"          # Includes a file in the .pm file
+   * ------------------------------------------------------------ */
+
+  virtual int pragmaDirective(Node *n) {
+    String *lang;
+    String *code;
+    String *value;
+    if (!ImportMode) {
+      lang = Getattr(n, "lang");
+      code = Getattr(n, "name");
+      value = Getattr(n, "value");
+      if (Strcmp(lang, "perl5") == 0) {
+	if (Strcmp(code, "code") == 0) {
+	  /* Dump the value string into the .pm file */
+	  if (value) {
+	    Printf(pragma_include, "%s\n", value);
+	  }
+	} else if (Strcmp(code, "include") == 0) {
+	  /* Include a file into the .pm file */
+	  if (value) {
+	    FILE *f = Swig_open(value);
+	    if (!f) {
+	      Printf(stderr, "%s : Line %d. Unable to locate file %s\n", input_file, line_number, value);
+	    } else {
+	      char buffer[4096];
+	      while (fgets(buffer, 4095, f)) {
+		Printf(pragma_include, "%s", buffer);
+	      }
+	    }
+	    fclose(f);
+	  }
+	} else {
+	  Printf(stderr, "%s : Line %d. Unrecognized pragma.\n", input_file, line_number);
+	}
+      }
+    }
+    return Language::pragmaDirective(n);
+  }
+
+  /* ------------------------------------------------------------
+   * perlcode()     - Output perlcode code into the shadow file
+   * ------------------------------------------------------------ */
+
+  String *perlcode(String *code, const String *indent) {
+    String *out = NewString("");
+    String *temp;
+    char *t;
+    if (!indent)
+      indent = "";
+
+    temp = NewString(code);
+
+    t = Char(temp);
+    if (*t == '{') {
+      Delitem(temp, 0);
+      Delitem(temp, DOH_END);
+    }
+
+    /* Split the input text into lines */
+    List *clist = DohSplitLines(temp);
+    Delete(temp);
+    int initial = 0;
+    String *s = 0;
+    Iterator si;
+    /* Get the initial indentation */
+
+    for (si = First(clist); si.item; si = Next(si)) {
+      s = si.item;
+      if (Len(s)) {
+	char *c = Char(s);
+	while (*c) {
+	  if (!isspace(*c))
+	    break;
+	  initial++;
+	  c++;
+	}
+	if (*c && !isspace(*c))
+	  break;
+	else {
+	  initial = 0;
+	}
+      }
+    }
+    while (si.item) {
+      s = si.item;
+      if (Len(s) > initial) {
+	char *c = Char(s);
+	c += initial;
+	Printv(out, indent, c, "\n", NIL);
+      } else {
+	Printv(out, "\n", NIL);
+      }
+      si = Next(si);
+    }
+    Delete(clist);
+    return out;
+  }
+
+  /* ------------------------------------------------------------
+   * insertDirective()
+   * 
+   * Hook for %insert directive.
+   * ------------------------------------------------------------ */
+
+  virtual int insertDirective(Node *n) {
+    String *code = Getattr(n, "code");
+    String *section = Getattr(n, "section");
+
+    if ((!ImportMode) && (Cmp(section, "perl") == 0)) {
+      Printv(additional_perl_code, code, NIL);
+    } else {
+      Language::insertDirective(n);
+    }
+    return SWIG_OK;
+  }
+
+  String *runtimeCode() {
+    String *s = NewString("");
+    String *shead = Swig_include_sys("perlhead.swg");
+    if (!shead) {
+      Printf(stderr, "*** Unable to open 'perlhead.swg'\n");
+    } else {
+      Append(s, shead);
+      Delete(shead);
+    }
+    String *serrors = Swig_include_sys("perlerrors.swg");
+    if (!serrors) {
+      Printf(stderr, "*** Unable to open 'perlerrors.swg'\n");
+    } else {
+      Append(s, serrors);
+      Delete(serrors);
+    }
+    String *srun = Swig_include_sys("perlrun.swg");
+    if (!srun) {
+      Printf(stderr, "*** Unable to open 'perlrun.swg'\n");
+    } else {
+      Append(s, srun);
+      Delete(srun);
+    }
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigperlrun.h");
+  }
+};
+
+/* -----------------------------------------------------------------------------
+ * swig_perl5()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_perl5() {
+  return new PERL5();
+}
+extern "C" Language *swig_perl5(void) {
+  return new_swig_perl5();
+}
diff --git a/trunk/Source/Modules/php4.cxx b/trunk/Source/Modules/php4.cxx
new file mode 100644
index 0000000..42d71e7
--- /dev/null
+++ b/trunk/Source/Modules/php4.cxx
@@ -0,0 +1,2771 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * php4.cxx
+ *
+ * Php language module for SWIG.
+ * -----------------------------------------------------------------------------
+ */
+
+/* FIXME: PHP5 OO wrapping TODO list:
+ *
+ * Short term:
+ *
+ * Sort out auto-renaming of method and class names which are reserved
+ *   words (e.g. empty, clone, exception, etc.) vs -php4/-php5 in some
+ *   sane way.
+ *
+ * Sort out wrapping of static member variables in OO PHP5 (which first may
+ *   mean we need to sort them out for PHP4!)
+ *
+ * Medium term:
+ *
+ * Handle default parameters on overloaded methods in PHP where possible.
+ *   (Mostly done - just need to handle cases of overloaded methods with
+ *   default parameters...)
+ *   This is an optimisation - we could handle this case using a PHP
+ *   default value, but currently we treat it as we would for a default
+ *   value which is a compound C++ expression (i.e. as if we had a
+ *   method with two overloaded forms instead of a single method with
+ *   a default parameter value).
+ *
+ * Long term:
+ *
+ * Sort out locale-dependent behaviour of strtod() - it's harmless unless
+ *   SWIG ever sets the locale and DOH/base.c calls atof, so we're probably
+ *   OK currently at least.
+ */
+
+/*
+ * TODO: Replace remaining stderr messages with Swig_error or Swig_warning
+ * (may need to add more WARN_PHP4_xxx codes...)
+ */
+
+char cvsroot_php4_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#include <ctype.h>
+#include <errno.h>
+
+static const char *usage = (char *) "\
+PHP Options (available with -php4 or -php5)\n\
+     -cppext          - cpp file extension (default to .cpp)\n\
+     -noproxy         - Don't generate proxy classes.\n\
+     -prefix <prefix> - Prepend <prefix> to all class names in PHP5 wrappers\n\
+     -make            - Create simple makefile\n\
+     -phpfull         - Create full make files\n\
+     -withincs <incs> - With -phpfull writes needed incs in config.m4\n\
+     -withlibs <libs> - With -phpfull writes needed libs in config.m4\n\
+     -withc <files>   - With -phpfull makes extra C files in Makefile.in\n\
+     -withcxx <files> - With -phpfull makes extra C++ files in Makefile.in\n\
+\n";
+
+/* The original class wrappers for PHP4 store the pointer to the C++ class in
+ * the object property _cPtr.  If we use the same name for the member variable
+ * which we put the pointer to the C++ class in, then the flat function
+ * wrappers will automatically pull it out without any changes being required.
+ * FIXME: Isn't using a leading underscore a bit suspect here?
+ */
+#define SWIG_PTR "_cPtr"
+
+static int constructors = 0;
+static String *NOTCLASS = NewString("Not a class");
+static Node *classnode = 0;
+static String *module = 0;
+static String *cap_module = 0;
+static String *prefix = 0;
+static String *withlibs = 0;
+static String *withincs = 0;
+static String *withc = 0;
+static String *withcxx = 0;
+
+static String *shadow_classname = 0;
+
+static int gen_extra = 0;
+static int gen_make = 0;
+
+static File *f_runtime = 0;
+static File *f_h = 0;
+static File *f_phpcode = 0;
+static String *phpfilename = 0;
+
+static String *s_header;
+static String *s_wrappers;
+static String *s_init;
+static String *r_init;		// RINIT user code
+static String *s_shutdown;	// MSHUTDOWN user code
+static String *r_shutdown;	// RSHUTDOWN user code
+static String *s_vinit;		// varinit initialization code.
+static String *s_vdecl;
+static String *s_cinit;		// consttab initialization code.
+static String *s_oinit;
+static String *s_entry;
+static String *cs_entry;
+static String *all_cs_entry;
+static String *pragma_incl;
+static String *pragma_code;
+static String *pragma_phpinfo;
+static String *s_oowrappers;
+static String *s_fakeoowrappers;
+static String *s_phpclasses;
+
+/* Variables for using PHP classes */
+static Node *current_class = 0;
+
+static Hash *shadow_get_vars;
+static Hash *shadow_set_vars;
+#define NATIVE_CONSTRUCTOR 1
+#define ALTERNATIVE_CONSTRUCTOR 2
+static int native_constructor = 0;
+static Hash *zend_types = 0;
+
+static int shadow = 1;
+
+static bool class_has_ctor = false;
+static String *wrapping_member_constant = NULL;
+
+// These static variables are used to pass some state from Handlers into functionWrapper
+static enum {
+  standard = 0,
+  memberfn,
+  staticmemberfn,
+  membervar,
+  staticmembervar,
+  constructor,
+  destructor
+} wrapperType = standard;
+
+extern "C" {
+  static void (*r_prevtracefunc) (SwigType *t, String *mangled, String *clientdata) = 0;
+}
+
+void SwigPHP_emit_resource_registrations() {
+  Iterator ki;
+
+  if (!zend_types)
+    return;
+
+  ki = First(zend_types);
+  if (ki.key)
+    Printf(s_oinit, "\n/* Register resource destructors for pointer types */\n");
+  while (ki.key) {
+    DOH *key = ki.key;
+    Node *class_node = ki.item;
+    String *human_name = key;
+
+    // Write out destructor function header
+    Printf(s_wrappers, "/* NEW Destructor style */\nstatic ZEND_RSRC_DTOR_FUNC(_wrap_destroy%s) {\n", key);
+
+    // write out body
+    if ((class_node != NOTCLASS)) {
+      String *destructor = Getattr(class_node, "destructor");
+      human_name = Getattr(class_node, "sym:name");
+      if (!human_name)
+        human_name = Getattr(class_node, "name");
+      // Do we have a known destructor for this type?
+      if (destructor) {
+        Printf(s_wrappers, "  %s(rsrc, SWIGTYPE%s->name TSRMLS_CC);\n", destructor, key);
+      } else {
+        Printf(s_wrappers, "  /* No destructor for class %s */\n", human_name);
+      }
+    } else {
+      Printf(s_wrappers, "  /* No destructor for simple type %s */\n", key);
+    }
+
+    // close function
+    Printf(s_wrappers, "}\n");
+
+    // declare le_swig_<mangled> to store php registration
+    Printf(s_vdecl, "static int le_swig_%s=0; /* handle for %s */\n", key, human_name);
+
+    // register with php
+    Printf(s_oinit, "le_swig_%s=zend_register_list_destructors_ex" "(_wrap_destroy%s,NULL,(char *)(SWIGTYPE%s->name),module_number);\n", key, key, key);
+
+    // store php type in class struct
+    Printf(s_oinit, "SWIG_TypeClientData(SWIGTYPE%s,&le_swig_%s);\n", key, key);
+
+    ki = Next(ki);
+  }
+}
+
+class PHP:public Language {
+  int php_version;
+
+public:
+   PHP(int php_version_):php_version(php_version_) {
+  }
+
+  /* Test to see if a type corresponds to something wrapped with a shadow class. */
+  
+  String *is_shadow(SwigType *t) {
+    String *r = 0;
+    Node *n = classLookup(t);
+    if (n) {
+      r = Getattr(n, "php:proxy");	// Set by classDeclaration()
+      if (!r) {
+	r = Getattr(n, "sym:name");	// Not seen by classDeclaration yet, but this is the name
+      }
+    }
+    return r;
+  }
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+    int i;
+    SWIG_library_directory("php4");
+    SWIG_config_cppext("cpp");
+
+    for (i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-phpfull") == 0) {
+	  gen_extra = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-dlname") == 0) {
+	  Printf(stderr, "*** -dlname is no longer supported\n*** if you want to change the module name, use -module instead.\n");
+	  SWIG_exit(EXIT_FAILURE);
+	} else if (strcmp(argv[i], "-prefix") == 0) {
+	  if (argv[i + 1]) {
+	    prefix = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-withlibs") == 0) {
+	  if (argv[i + 1]) {
+	    withlibs = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-withincs") == 0) {
+	  if (argv[i + 1]) {
+	    withincs = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-withc") == 0) {
+	  if (argv[i + 1]) {
+	    withc = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-withcxx") == 0) {
+	  if (argv[i + 1]) {
+	    withcxx = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-cppext") == 0) {
+	  if (argv[i + 1]) {
+	    SWIG_config_cppext(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if ((strcmp(argv[i], "-noshadow") == 0) || (strcmp(argv[i], "-noproxy") == 0)) {
+	  shadow = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-make") == 0) {
+	  gen_make = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stdout);
+	}
+      }
+    }
+
+    Preprocessor_define((void *) "SWIGPHP 1", 0);
+    if (php_version == 4) {
+      Preprocessor_define((void *) "SWIGPHP4 1", 0);
+    } else if (php_version == 5) {
+      Preprocessor_define((void *) "SWIGPHP5 1", 0);
+    }
+    SWIG_typemap_lang("php4");
+    /* DB: Suggest using a language configuration file */
+    SWIG_config_file("php4.swg");
+    allow_overloading();
+  }
+
+  void create_simple_make(void) {
+    File *f_make;
+
+    f_make = NewFile((void *) "makefile", "w");
+    Printf(f_make, "CC=gcc\n");
+    Printf(f_make, "CXX=g++\n");
+    Printf(f_make, "CXX_SOURCES=%s\n", withcxx);
+    Printf(f_make, "C_SOURCES=%s\n", withc);
+    Printf(f_make, "OBJS=%s_wrap.o $(C_SOURCES:.c=.o) $(CXX_SOURCES:.cxx=.o)\n", module);
+    Printf(f_make, "MODULE=%s.so\n", module);
+    Printf(f_make, "CFLAGS=-fpic\n");
+    Printf(f_make, "LDFLAGS=-shared\n");
+    Printf(f_make, "PHP_INC=`php-config --includes`\n");
+    Printf(f_make, "EXTRA_INC=\n");
+    Printf(f_make, "EXTRA_LIB=\n\n");
+    Printf(f_make, "$(MODULE): $(OBJS)\n");
+    if (CPlusPlus || (withcxx != NULL)) {
+      Printf(f_make, "\t$(CXX) $(LDFLAGS) $(OBJS) -o $@ $(EXTRA_LIB)\n\n");
+    } else {
+      Printf(f_make, "\t$(CC) $(LDFLAGS) $(OBJS) -o $@ $(EXTRA_LIB)\n\n");
+    }
+    Printf(f_make, "%%.o: %%.cpp\n");
+    Printf(f_make, "\t$(CXX) $(EXTRA_INC) $(PHP_INC) $(CFLAGS) -c $<\n");
+    Printf(f_make, "%%.o: %%.cxx\n");
+    Printf(f_make, "\t$(CXX) $(EXTRA_INC) $(PHP_INC) $(CFLAGS) -c $<\n");
+    Printf(f_make, "%%.o: %%.c\n");
+    Printf(f_make, "\t$(CC) $(EXTRA_INC) $(PHP_INC) $(CFLAGS) -c $<\n");
+
+    Close(f_make);
+  }
+
+  void create_extra_files(String *outfile) {
+    File *f_extra;
+
+    static String *configm4 = 0;
+    static String *makefilein = 0;
+    static String *credits = 0;
+
+    configm4 = NewStringEmpty();
+    Printv(configm4, SWIG_output_directory(), "config.m4", NIL);
+
+    makefilein = NewStringEmpty();
+    Printv(makefilein, SWIG_output_directory(), "Makefile.in", NIL);
+
+    credits = NewStringEmpty();
+    Printv(credits, SWIG_output_directory(), "CREDITS", NIL);
+
+    // are we a --with- or --enable-
+    int with = (withincs || withlibs) ? 1 : 0;
+
+    // Note Makefile.in only copes with one source file
+    // also withincs and withlibs only take one name each now
+    // the code they generate should be adapted to take multiple lines
+
+    /* Write out Makefile.in */
+    f_extra = NewFile(makefilein, "w");
+    if (!f_extra) {
+      FileErrorDisplay(makefilein);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    Printf(f_extra, "# $Id$\n\n" "LTLIBRARY_NAME          = %s.la\n", module);
+
+    // C++ has more and different entries to C in Makefile.in
+    if (!CPlusPlus) {
+      Printf(f_extra, "LTLIBRARY_SOURCES       = %s %s\n", Swig_file_filename(outfile), withc);
+      Printf(f_extra, "LTLIBRARY_SOURCES_CPP   = %s\n", withcxx);
+    } else {
+      Printf(f_extra, "LTLIBRARY_SOURCES       = %s\n", withc);
+      Printf(f_extra, "LTLIBRARY_SOURCES_CPP   = %s %s\n", Swig_file_filename(outfile), withcxx);
+      Printf(f_extra, "LTLIBRARY_OBJECTS_X = $(LTLIBRARY_SOURCES_CPP:.cpp=.lo) $(LTLIBRARY_SOURCES_CPP:.cxx=.lo)\n");
+    }
+    Printf(f_extra, "LTLIBRARY_SHARED_NAME   = %s.la\n", module);
+    Printf(f_extra, "LTLIBRARY_SHARED_LIBADD = $(%s_SHARED_LIBADD)\n\n", cap_module);
+    Printf(f_extra, "include $(top_srcdir)/build/dynlib.mk\n");
+
+    Printf(f_extra, "\n# patch in .cxx support to php build system to work like .cpp\n");
+    Printf(f_extra, ".SUFFIXES: .cxx\n\n");
+
+    Printf(f_extra, ".cxx.o:\n");
+    Printf(f_extra, "\t$(CXX_COMPILE) -c $<\n\n");
+
+    Printf(f_extra, ".cxx.lo:\n");
+    Printf(f_extra, "\t$(CXX_PHP_COMPILE)\n\n");
+    Printf(f_extra, ".cxx.slo:\n");
+
+    Printf(f_extra, "\t$(CXX_SHARED_COMPILE)\n\n");
+
+    Printf(f_extra, "\n# make it easy to test module\n");
+    Printf(f_extra, "testmodule:\n");
+    Printf(f_extra, "\tphp -q -d extension_dir=modules %s\n\n", Swig_file_filename(phpfilename));
+
+    Close(f_extra);
+
+    /* Now config.m4 */
+    // Note: # comments are OK in config.m4 if you don't mind them
+    // appearing in the final ./configure file
+    // (which can help with ./configure debugging)
+
+    // NOTE2: phpize really ought to be able to write out a sample
+    // config.m4 based on some simple data, I'll take this up with
+    // the php folk!
+    f_extra = NewFile(configm4, "w");
+    if (!f_extra) {
+      FileErrorDisplay(configm4);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    Printf(f_extra, "dnl $Id$\n");
+    Printf(f_extra, "dnl ***********************************************************************\n");
+    Printf(f_extra, "dnl ** THIS config.m4 is provided for PHPIZE and PHP's consumption NOT\n");
+    Printf(f_extra, "dnl ** for any part of the rest of the %s build system\n", module);
+    Printf(f_extra, "dnl ***********************************************************************\n\n");
+
+
+    if (!with) {		// must be enable then
+      Printf(f_extra, "PHP_ARG_ENABLE(%s, whether to enable %s support,\n", module, module);
+      Printf(f_extra, "[  --enable-%s             Enable %s support])\n\n", module, module);
+    } else {
+      Printf(f_extra, "PHP_ARG_WITH(%s, for %s support,\n", module, module);
+      Printf(f_extra, "[  --with-%s[=DIR]             Include %s support.])\n\n", module, module);
+      // These tests try and file the library we need
+      Printf(f_extra, "dnl THESE TESTS try and find the library and header files\n");
+      Printf(f_extra, "dnl your new php module needs. YOU MAY NEED TO EDIT THEM\n");
+      Printf(f_extra, "dnl as written they assume your header files are all in the same place\n\n");
+
+      Printf(f_extra, "dnl ** are we looking for %s_lib.h or something else?\n", module);
+      if (withincs)
+	Printf(f_extra, "HNAMES=\"%s\"\n\n", withincs);
+      else
+	Printf(f_extra, "HNAMES=\"\"; # %s_lib.h ?\n\n", module);
+
+      Printf(f_extra, "dnl ** Are we looking for lib%s.a or lib%s.so or something else?\n", module, module);
+
+      if (withlibs)
+	Printf(f_extra, "LIBNAMES=\"%s\"\n\n", withlibs);
+      else
+	Printf(f_extra, "LIBNAMES=\"\"; # lib%s.so ?\n\n", module);
+
+      Printf(f_extra, "dnl IF YOU KNOW one of the symbols in the library and you\n");
+      Printf(f_extra, "dnl specify it below then we can have a link test to see if it works\n");
+      Printf(f_extra, "LIBSYMBOL=\"\"\n\n");
+    }
+
+    // Now write out tests to find thing.. they may need to extend tests
+    Printf(f_extra, "if test \"$PHP_%s\" != \"no\"; then\n\n", cap_module);
+
+    // Ready for when we add libraries as we find them
+    Printf(f_extra, "  PHP_SUBST(%s_SHARED_LIBADD)\n\n", cap_module);
+
+    if (withlibs) {		// find more than one library
+      Printf(f_extra, "  for LIBNAME in $LIBNAMES ; do\n");
+      Printf(f_extra, "    LIBDIR=\"\"\n");
+      // For each path element to try...
+      Printf(f_extra, "    for i in $PHP_%s $PHP_%s/lib /usr/lib /usr/local/lib ; do\n", cap_module, cap_module);
+      Printf(f_extra, "      if test -r $i/lib$LIBNAME.a -o -r $i/lib$LIBNAME.so ; then\n");
+      Printf(f_extra, "        LIBDIR=\"$i\"\n");
+      Printf(f_extra, "        break\n");
+      Printf(f_extra, "      fi\n");
+      Printf(f_extra, "    done\n\n");
+      Printf(f_extra, "    dnl ** and $LIBDIR should be the library path\n");
+      Printf(f_extra, "    if test \"$LIBNAME\" != \"\" -a -z \"$LIBDIR\" ; then\n");
+      Printf(f_extra, "      AC_MSG_RESULT(Library files $LIBNAME not found)\n");
+      Printf(f_extra, "      AC_MSG_ERROR(Is the %s distribution installed properly?)\n", module);
+      Printf(f_extra, "    else\n");
+      Printf(f_extra, "      AC_MSG_RESULT(Library files $LIBNAME found in $LIBDIR)\n");
+      Printf(f_extra, "      PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $LIBDIR, %s_SHARED_LIBADD)\n", cap_module);
+      Printf(f_extra, "    fi\n");
+      Printf(f_extra, "  done\n\n");
+    }
+
+    if (withincs) {		// Find more than once include
+      Printf(f_extra, "  for HNAME in $HNAMES ; do\n");
+      Printf(f_extra, "    INCDIR=\"\"\n");
+      // For each path element to try...
+      Printf(f_extra, "    for i in $PHP_%s $PHP_%s/include $PHP_%s/includes $PHP_%s/inc $PHP_%s/incs /usr/local/include /usr/include; do\n", cap_module,
+	     cap_module, cap_module, cap_module, cap_module);
+      // Try and find header files
+      Printf(f_extra, "      if test \"$HNAME\" != \"\" -a -r $i/$HNAME ; then\n");
+      Printf(f_extra, "        INCDIR=\"$i\"\n");
+      Printf(f_extra, "        break\n");
+      Printf(f_extra, "      fi\n");
+      Printf(f_extra, "    done\n\n");
+
+      Printf(f_extra, "    dnl ** Now $INCDIR should be the include file path\n");
+      Printf(f_extra, "    if test \"$HNAME\" != \"\" -a -z \"$INCDIR\" ; then\n");
+      Printf(f_extra, "      AC_MSG_RESULT(Include files $HNAME not found)\n");
+      Printf(f_extra, "      AC_MSG_ERROR(Is the %s distribution installed properly?)\n", module);
+      Printf(f_extra, "    else\n");
+      Printf(f_extra, "      AC_MSG_RESULT(Include files $HNAME found in $INCDIR)\n");
+      Printf(f_extra, "      PHP_ADD_INCLUDE($INCDIR)\n");
+      Printf(f_extra, "    fi\n\n");
+      Printf(f_extra, "  done\n\n");
+    }
+
+    if (CPlusPlus) {
+      Printf(f_extra, "  # As this is a C++ module..\n");
+    }
+
+    Printf(f_extra, "  PHP_REQUIRE_CXX\n");
+    Printf(f_extra, "  AC_CHECK_LIB(stdc++, cin)\n");
+
+    if (with) {
+      Printf(f_extra, "  if test \"$LIBSYMBOL\" != \"\" ; then\n");
+      Printf(f_extra, "    old_LIBS=\"$LIBS\"\n");
+      Printf(f_extra, "    LIBS=\"$LIBS -L$TEST_DIR/lib -lm -ldl\"\n");
+      Printf(f_extra, "    AC_CHECK_LIB($LIBNAME, $LIBSYMBOL, [AC_DEFINE(HAVE_TESTLIB,1,  [ ])],\n");
+      Printf(f_extra, "    [AC_MSG_ERROR(wrong test lib version or lib not found)])\n");
+      Printf(f_extra, "    LIBS=\"$old_LIBS\"\n");
+      Printf(f_extra, "  fi\n\n");
+    }
+
+    Printf(f_extra, "  AC_DEFINE(HAVE_%s, 1, [ ])\n", cap_module);
+    Printf(f_extra, "dnl  AC_DEFINE_UNQUOTED(PHP_%s_DIR, \"$%s_DIR\", [ ])\n", cap_module, cap_module);
+    Printf(f_extra, "  PHP_EXTENSION(%s, $ext_shared)\n", module);
+
+    // and thats all!
+    Printf(f_extra, "fi\n");
+
+    Close(f_extra);
+
+    /*  CREDITS */
+    f_extra = NewFile(credits, "w");
+    if (!f_extra) {
+      FileErrorDisplay(credits);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Printf(f_extra, "%s\n", module);
+    Close(f_extra);
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+
+    String *filen;
+    String *s_type;
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+
+    /* main output file */
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    Swig_banner(f_runtime);
+
+    /* sections of the output file */
+    s_init = NewString("/* init section */\n");
+    r_init = NewString("/* rinit section */\n");
+    s_shutdown = NewString("/* shutdown section */\n");
+    r_shutdown = NewString("/* rshutdown section */\n");
+    s_header = NewString("/* header section */\n");
+    s_wrappers = NewString("/* wrapper section */\n");
+    s_type = NewStringEmpty();
+    /* subsections of the init section */
+    s_vinit = NewString("/* vinit subsection */\n");
+    s_vdecl = NewString("/* vdecl subsection */\n");
+    s_cinit = NewString("/* cinit subsection */\n");
+    s_oinit = NewString("/* oinit subsection */\n");
+    pragma_phpinfo = NewStringEmpty();
+    s_phpclasses = NewString("/* PHP Proxy Classes */\n");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", s_init);
+    Swig_register_filebyname("rinit", r_init);
+    Swig_register_filebyname("shutdown", s_shutdown);
+    Swig_register_filebyname("rshutdown", r_shutdown);
+    Swig_register_filebyname("header", s_header);
+    Swig_register_filebyname("wrapper", s_wrappers);
+
+    /* Set the module name */
+    module = Copy(Getattr(n, "name"));
+    cap_module = NewStringf("%(upper)s", module);
+    if (!prefix)
+      prefix = NewStringEmpty();
+
+    /* PHP module file */
+    filen = NewStringEmpty();
+    Printv(filen, SWIG_output_directory(), module, ".php", NIL);
+    phpfilename = NewString(filen);
+
+    f_phpcode = NewFile(filen, "w");
+    if (!f_phpcode) {
+      FileErrorDisplay(filen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    Printf(f_phpcode, "<?php\n\n");
+
+    Swig_banner(f_phpcode);
+
+    Printf(f_phpcode, "// Try to load our extension if it's not already loaded.\n");
+    Printf(f_phpcode, "if (!extension_loaded(\"%s\")) {\n", module);
+    Printf(f_phpcode, "  if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {\n");
+    Printf(f_phpcode, "    if (!dl('php_%s.dll')) return;\n", module);
+    Printf(f_phpcode, "  } else {\n");
+    Printf(f_phpcode, "    // PHP_SHLIB_SUFFIX is available as of PHP 4.3.0, for older PHP assume 'so'.\n");
+    Printf(f_phpcode, "    // It gives 'dylib' on MacOS X which is for libraries, modules are 'so'.\n");
+    Printf(f_phpcode, "    if (PHP_SHLIB_SUFFIX === 'PHP_SHLIB_SUFFIX' || PHP_SHLIB_SUFFIX === 'dylib') {\n");
+    Printf(f_phpcode, "      if (!dl('%s.so')) return;\n", module);
+    Printf(f_phpcode, "    } else {\n");
+    Printf(f_phpcode, "      if (!dl('%s.'.PHP_SHLIB_SUFFIX)) return;\n", module);
+    Printf(f_phpcode, "    }\n");
+    Printf(f_phpcode, "  }\n");
+    Printf(f_phpcode, "}\n\n");
+
+    /* sub-sections of the php file */
+    pragma_code = NewStringEmpty();
+    pragma_incl = NewStringEmpty();
+
+    /* Initialize the rest of the module */
+
+    Printf(s_oinit, "ZEND_INIT_MODULE_GLOBALS(%s, %s_init_globals, %s_destroy_globals);\n", module, module, module);
+
+    /* start the header section */
+    Printf(s_header, "ZEND_BEGIN_MODULE_GLOBALS(%s)\n", module);
+    Printf(s_header, "const char *error_msg;\n");
+    Printf(s_header, "int error_code;\n");
+    Printf(s_header, "ZEND_END_MODULE_GLOBALS(%s)\n", module);
+    Printf(s_header, "ZEND_DECLARE_MODULE_GLOBALS(%s)\n", module);
+    Printf(s_header, "#ifdef ZTS\n");
+    Printf(s_header, "#define SWIG_ErrorMsg() TSRMG(%s_globals_id, zend_%s_globals *, error_msg )\n", module, module);
+    Printf(s_header, "#define SWIG_ErrorCode() TSRMG(%s_globals_id, zend_%s_globals *, error_code )\n", module, module);
+    Printf(s_header, "#else\n");
+    Printf(s_header, "#define SWIG_ErrorMsg() (%s_globals.error_msg)\n", module);
+    Printf(s_header, "#define SWIG_ErrorCode() (%s_globals.error_code)\n", module);
+    Printf(s_header, "#endif\n\n");
+
+    Printf(s_header, "static void %s_init_globals(zend_%s_globals *globals ) {\n", module, module);
+    Printf(s_header, "  globals->error_msg = default_error_msg;\n");
+    Printf(s_header, "  globals->error_code = default_error_code;\n");
+    Printf(s_header, "}\n");
+
+    Printf(s_header, "static void %s_destroy_globals(zend_%s_globals * globals) { (void)globals; }\n", module, module);
+
+    Printf(s_header, "\n");
+    Printf(s_header, "static void SWIG_ResetError() {\n");
+    Printf(s_header, "  TSRMLS_FETCH();\n");
+    Printf(s_header, "  SWIG_ErrorMsg() = default_error_msg;\n");
+    Printf(s_header, "  SWIG_ErrorCode() = default_error_code;\n");
+    Printf(s_header, "}\n");
+
+    Printf(s_header, "#define SWIG_name  \"%s\"\n", module);
+    /*     Printf(s_header,"#ifdef HAVE_CONFIG_H\n");
+       Printf(s_header,"#include \"config.h\"\n");
+       Printf(s_header,"#endif\n\n");
+     */
+    Printf(s_header, "#ifdef __cplusplus\n");
+    Printf(s_header, "extern \"C\" {\n");
+    Printf(s_header, "#endif\n");
+    Printf(s_header, "#include \"php.h\"\n");
+    Printf(s_header, "#include \"php_ini.h\"\n");
+    Printf(s_header, "#include \"ext/standard/info.h\"\n");
+    Printf(s_header, "#include \"php_%s.h\"\n", module);
+    Printf(s_header, "#ifdef __cplusplus\n");
+    Printf(s_header, "}\n");
+    Printf(s_header, "#endif\n\n");
+
+    /* Create the .h file too */
+    filen = NewStringEmpty();
+    Printv(filen, SWIG_output_directory(), "php_", module, ".h", NIL);
+    f_h = NewFile(filen, "w");
+    if (!f_h) {
+      FileErrorDisplay(filen);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    Swig_banner(f_h);
+
+    Printf(f_h, "\n\n");
+    Printf(f_h, "#ifndef PHP_%s_H\n", cap_module);
+    Printf(f_h, "#define PHP_%s_H\n\n", cap_module);
+    Printf(f_h, "extern zend_module_entry %s_module_entry;\n", module);
+    Printf(f_h, "#define phpext_%s_ptr &%s_module_entry\n\n", module, module);
+    Printf(f_h, "#ifdef PHP_WIN32\n");
+    Printf(f_h, "# define PHP_%s_API __declspec(dllexport)\n", cap_module);
+    Printf(f_h, "#else\n");
+    Printf(f_h, "# define PHP_%s_API\n", cap_module);
+    Printf(f_h, "#endif\n\n");
+    Printf(f_h, "#ifdef ZTS\n");
+    Printf(f_h, "#include \"TSRM.h\"\n");
+    Printf(f_h, "#endif\n\n");
+    Printf(f_h, "PHP_MINIT_FUNCTION(%s);\n", module);
+    Printf(f_h, "PHP_MSHUTDOWN_FUNCTION(%s);\n", module);
+    Printf(f_h, "PHP_RINIT_FUNCTION(%s);\n", module);
+    Printf(f_h, "PHP_RSHUTDOWN_FUNCTION(%s);\n", module);
+    Printf(f_h, "PHP_MINFO_FUNCTION(%s);\n\n", module);
+
+    /* start the function entry section */
+    s_entry = NewString("/* entry subsection */\n");
+
+    /* holds all the per-class function entry sections */
+    all_cs_entry = NewString("/* class entry subsection */\n");
+    cs_entry = NULL;
+
+    Printf(s_entry, "/* Every non-class user visible function must have an entry here */\n");
+    Printf(s_entry, "static zend_function_entry %s_functions[] = {\n", module);
+
+    /* start the init section */
+    Printv(s_init, "zend_module_entry ", module, "_module_entry = {\n" "#if ZEND_MODULE_API_NO > 20010900\n" "    STANDARD_MODULE_HEADER,\n" "#endif\n", NIL);
+    Printf(s_init, "    (char*)\"%s\",\n", module);
+    Printf(s_init, "    %s_functions,\n", module);
+    Printf(s_init, "    PHP_MINIT(%s),\n", module);
+    Printf(s_init, "    PHP_MSHUTDOWN(%s),\n", module);
+    Printf(s_init, "    PHP_RINIT(%s),\n", module);
+    Printf(s_init, "    PHP_RSHUTDOWN(%s),\n", module);
+    Printf(s_init, "    PHP_MINFO(%s),\n", module);
+    Printf(s_init, "#if ZEND_MODULE_API_NO > 20010900\n");
+    Printf(s_init, "    NO_VERSION_YET,\n");
+    Printf(s_init, "#endif\n");
+    Printf(s_init, "    STANDARD_MODULE_PROPERTIES\n");
+    Printf(s_init, "};\n");
+    Printf(s_init, "zend_module_entry* SWIG_module_entry = &%s_module_entry;\n\n", module);
+
+    if (gen_extra) {
+      Printf(s_init, "#ifdef COMPILE_DL_%s\n", cap_module);
+    }
+    Printf(s_init, "#ifdef __cplusplus\n");
+    Printf(s_init, "extern \"C\" {\n");
+    Printf(s_init, "#endif\n");
+    // We want to write "SWIGEXPORT ZEND_GET_MODULE(%s)" but ZEND_GET_MODULE
+    // in PHP5 has "extern "C" { ... }" around it so we can't do that.
+    Printf(s_init, "SWIGEXPORT zend_module_entry *get_module(void) { return &%s_module_entry; }\n", module);
+    Printf(s_init, "#ifdef __cplusplus\n");
+    Printf(s_init, "}\n");
+    Printf(s_init, "#endif\n\n");
+
+    if (gen_extra) {
+      Printf(s_init, "#endif\n\n");
+    }
+
+    /* We have to register the constants before they are (possibly) used
+     * by the pointer typemaps. This all needs re-arranging really as
+     * things are being called in the wrong order
+     */
+    Printf(s_init, "#define SWIG_php_minit PHP_MINIT_FUNCTION(%s)\n", module);
+
+    /* Emit all of the code */
+    Language::top(n);
+
+    SwigPHP_emit_resource_registrations();
+    //    Printv(s_init,s_resourcetypes,NIL);
+    /* We need this after all classes written out by ::top */
+    Printf(s_oinit, "CG(active_class_entry) = NULL;\n");
+    Printf(s_oinit, "/* end oinit subsection */\n");
+    Printf(s_init, "%s\n", s_oinit);
+
+    /* Constants generated during top call */
+    Printf(s_cinit, "/* end cinit subsection */\n");
+    Printf(s_init, "%s\n", s_cinit);
+    Clear(s_cinit);
+    Delete(s_cinit);
+
+    Printf(s_init, "    return SUCCESS;\n");
+    Printf(s_init, "}\n\n");
+
+    // Now do REQUEST init which holds any user specified %rinit, and also vinit
+    Printf(s_init, "PHP_RINIT_FUNCTION(%s)\n{\n", module);
+    Printf(s_init, "%s\n", r_init);
+
+    /* finish our init section which will have been used by class wrappers */
+    Printf(s_vinit, "/* end vinit subsection */\n");
+    Printf(s_init, "%s\n", s_vinit);
+    Clear(s_vinit);
+    Delete(s_vinit);
+
+    Printf(s_init, "    return SUCCESS;\n");
+    Printf(s_init, "}\n\n");
+
+    Printv(s_init, "PHP_MSHUTDOWN_FUNCTION(", module, ")\n"
+		   "{\n",
+		   s_shutdown,
+		   "#ifdef ZTS\n"
+		   "    ts_free_id(", module, "_globals_id);\n"
+		   "#endif\n"
+		   "    return SUCCESS;\n"
+		   "}\n\n", NIL);
+
+    Printf(s_init, "PHP_RSHUTDOWN_FUNCTION(%s)\n{\n", module);
+    Printf(s_init, "%s\n", r_shutdown);
+    Printf(s_init, "    return SUCCESS;\n");
+    Printf(s_init, "}\n\n");
+
+    Printf(s_init, "PHP_MINFO_FUNCTION(%s)\n{\n", module);
+    Printf(s_init, "%s", pragma_phpinfo);
+    Printf(s_init, "}\n");
+    Printf(s_init, "/* end init section */\n");
+
+    Printf(f_h, "#endif /* PHP_%s_H */\n", cap_module);
+
+    Close(f_h);
+
+    String *type_table = NewStringEmpty();
+    SwigType_emit_type_table(f_runtime, type_table);
+    Printf(s_header, "%s", type_table);
+    Delete(type_table);
+
+    /* Oh dear, more things being called in the wrong order. This whole
+     * function really needs totally redoing.
+     */
+
+    Printf(s_header, "/* end header section */\n");
+    Printf(s_wrappers, "/* end wrapper section */\n");
+    Printf(s_vdecl, "/* end vdecl subsection */\n");
+
+    Printv(f_runtime, s_header, s_vdecl, s_wrappers, NIL);
+    Printv(f_runtime, all_cs_entry, "\n\n", s_entry, "{NULL, NULL, NULL}\n};\n\n", NIL);
+    Printv(f_runtime, s_init, NIL);
+    Delete(s_header);
+    Delete(s_wrappers);
+    Delete(s_init);
+    Delete(s_vdecl);
+    Delete(all_cs_entry);
+    Delete(s_entry);
+    Close(f_runtime);
+
+    Printf(f_phpcode, "%s\n%s\n", pragma_incl, pragma_code);
+    if (s_fakeoowrappers) {
+      Printf(f_phpcode, "abstract class %s {", Len(prefix) ? prefix : module);
+      Printf(f_phpcode, "%s", s_fakeoowrappers);
+      Printf(f_phpcode, "}\n\n");
+      Delete(s_fakeoowrappers);
+      s_fakeoowrappers = NULL;
+    }
+    Printf(f_phpcode, "%s\n?>\n", s_phpclasses);
+    Close(f_phpcode);
+
+    if (gen_extra) {
+      create_extra_files(outfile);
+    } else if (gen_make) {
+      create_simple_make();
+    }
+
+    return SWIG_OK;
+  }
+
+  /* Just need to append function names to function table to register with PHP. */
+  void create_command(String *cname, String *iname) {
+    // This is for the single main zend_function_entry record
+    if (shadow && php_version == 4) {
+      if (wrapperType != standard)
+	return;
+    }
+    Printf(f_h, "ZEND_NAMED_FUNCTION(%s);\n", iname);
+    String * s = cs_entry;
+    if (!s) s = s_entry;
+    Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,NULL)\n", cname, iname);
+  }
+
+  /* ------------------------------------------------------------
+   * dispatchFunction()
+   * ------------------------------------------------------------ */
+  void dispatchFunction(Node *n) {
+    /* Last node in overloaded chain */
+
+    int maxargs;
+    String *tmp = NewStringEmpty();
+    String *dispatch = Swig_overload_dispatch(n, "return %s(INTERNAL_FUNCTION_PARAM_PASSTHRU);", &maxargs);
+
+    int has_this_ptr = (wrapperType == memberfn && shadow && php_version == 4);
+
+    /* Generate a dispatch wrapper for all overloaded functions */
+
+    Wrapper *f = NewWrapper();
+    String *symname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(symname);
+
+    create_command(symname, wname);
+    Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL);
+
+    Wrapper_add_local(f, "argc", "int argc");
+
+    Printf(tmp, "zval **argv[%d]", maxargs);
+    Wrapper_add_local(f, "argv", tmp);
+
+    Printf(f->code, "argc = ZEND_NUM_ARGS();\n");
+
+    if (has_this_ptr) {
+      Printf(f->code, "argv[0] = &this_ptr;\n");
+      Printf(f->code, "zend_get_parameters_array_ex(argc,argv+1);\n");
+      Printf(f->code, "argc++;\n");
+    } else {
+      Printf(f->code, "zend_get_parameters_array_ex(argc,argv);\n");
+    }
+
+    Replaceall(dispatch, "$args", "self,args");
+
+    Printv(f->code, dispatch, "\n", NIL);
+
+    Printf(f->code, "SWIG_ErrorCode() = E_ERROR;\n");
+    Printf(f->code, "SWIG_ErrorMsg() = \"No matching function for overloaded '%s'\";\n", symname);
+    Printv(f->code, "zend_error(SWIG_ErrorCode(),SWIG_ErrorMsg());\n", NIL);
+
+    Printv(f->code, "}\n", NIL);
+    Wrapper_print(f, s_wrappers);
+
+    DelWrapper(f);
+    Delete(dispatch);
+    Delete(tmp);
+    Delete(wname);
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * ------------------------------------------------------------ */
+
+  /* Helper method for PHP::functionWrapper */
+  bool is_class(SwigType *t) {
+    Node *n = classLookup(t);
+    if (n) {
+      String *r = Getattr(n, "php:proxy");	// Set by classDeclaration()
+      if (!r)
+	r = Getattr(n, "sym:name");	// Not seen by classDeclaration yet, but this is the name
+      if (r)
+	return true;
+    }
+    return false;
+  }
+
+  virtual int functionWrapper(Node *n) {
+    String *name = GetChar(n, "name");
+    String *iname = GetChar(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    String *nodeType = Getattr(n, "nodeType");
+    int newobject = GetFlag(n, "feature:new");
+
+    Parm *p;
+    int i;
+    int numopt;
+    String *tm;
+    Wrapper *f;
+    bool mvr = (shadow && php_version == 4 && wrapperType == membervar);
+    bool mvrset = (mvr && (Strcmp(iname, Swig_name_set(Swig_name_member(shadow_classname, name))) == 0));
+
+    String *wname;
+    int overloaded = 0;
+    String *overname = 0;
+
+    if (Cmp(nodeType, "destructor") == 0) {
+      // We just generate the Zend List Destructor and let Zend manage the
+      // reference counting.  There's no explicit destructor, but the user can
+      // just do `$obj = null;' to remove a reference to an object.
+      return CreateZendListDestructor(n);
+    }
+    // Test for overloading;
+    if (Getattr(n, "sym:overloaded")) {
+      overloaded = 1;
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n))
+	return SWIG_ERROR;
+    }
+
+    wname = Swig_name_wrapper(iname);
+    if (overname) {
+      Printf(wname, "%s", overname);
+    }
+    // if PHP4, shadow and variable wrapper we want to snag the main contents
+    // of this function to stick in to the property handler...
+    if (mvr) {
+      String *php_function_name = NewString(iname);
+      if (Strcmp(iname, Swig_name_set(Swig_name_member(shadow_classname, name))) == 0) {
+	Setattr(shadow_set_vars, php_function_name, name);
+      }
+      if (Strcmp(iname, Swig_name_get(Swig_name_member(shadow_classname, name))) == 0) {
+	Setattr(shadow_get_vars, php_function_name, name);
+      }
+
+      Delete(php_function_name);
+    }
+
+    f = NewWrapper();
+    numopt = 0;
+
+    String *outarg = NewStringEmpty();
+    String *cleanup = NewStringEmpty();
+
+    if (mvr) {			// do prop[gs]et header
+      if (mvrset) {
+	Printf(f->def, "static int _wrap_%s(zend_property_reference *property_reference, pval *value) {\n", iname);
+      } else {
+	Printf(f->def, "static pval _wrap_%s(zend_property_reference *property_reference) {\n", iname);
+      }
+    } else {
+      // regular header
+      // Not issued for overloaded functions or static member variables.
+      if (!overloaded && wrapperType != staticmembervar) {
+	create_command(iname, wname);
+      }
+      Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL);
+    }
+
+    emit_parameter_variables(l, f);
+    /* Attach standard typemaps */
+
+    emit_attach_parmmaps(l, f);
+
+    // wrap:parms is used by overload resolution.
+    Setattr(n, "wrap:parms", l);
+
+    int num_arguments = emit_num_arguments(l);
+    int num_required = emit_num_required(l);
+    numopt = num_arguments - num_required;
+
+    int has_this_ptr = (wrapperType == memberfn && shadow && php_version == 4);
+
+    if (num_arguments - has_this_ptr > 0) {
+      String *args = NewStringf("zval **args[%d]", num_arguments - has_this_ptr);
+      Wrapper_add_local(f, "args", args);
+      Delete(args);
+      args = NULL;
+    }
+    // This generated code may be called:
+    // 1) as an object method, or
+    // 2) as a class-method/function (without a "this_ptr")
+    // Option (1) has "this_ptr" for "this", option (2) needs it as
+    // first parameter
+
+    // NOTE: possible we ignore this_ptr as a param for native constructor
+
+    Printf(f->code, "SWIG_ResetError();\n");
+
+    if (has_this_ptr)
+      Printf(f->code, "/* This function uses a this_ptr*/\n");
+
+    if (native_constructor) {
+      if (native_constructor == NATIVE_CONSTRUCTOR) {
+	Printf(f->code, "/* NATIVE Constructor */\n");
+      } else {
+	Printf(f->code, "/* ALTERNATIVE Constructor */\n");
+      }
+    }
+
+    if (mvr && !mvrset) {
+      Wrapper_add_local(f, "_return_value", "zval _return_value");
+      Wrapper_add_local(f, "return_value", "zval *return_value=&_return_value");
+    }
+
+    if (numopt > 0) {		// membervariable wrappers do not have optional args
+      Wrapper_add_local(f, "arg_count", "int arg_count");
+      Printf(f->code, "arg_count = ZEND_NUM_ARGS();\n");
+      Printf(f->code, "if(arg_count<%d || arg_count>%d ||\n", num_required, num_arguments);
+      Printf(f->code, "   zend_get_parameters_array_ex(arg_count,args)!=SUCCESS)\n");
+      Printf(f->code, "\tWRONG_PARAM_COUNT;\n\n");
+    } else if (!mvr) {
+      int num = num_arguments - has_this_ptr;
+      if (num == 0) {
+	Printf(f->code, "if(ZEND_NUM_ARGS() != 0) {\n");
+      } else {
+	Printf(f->code, "if(ZEND_NUM_ARGS() != %d || zend_get_parameters_array_ex(%d, args) != SUCCESS) {\n", num, num);
+      }
+      Printf(f->code, "WRONG_PARAM_COUNT;\n}\n\n");
+    }
+
+    /* Now convert from php to C variables */
+    // At this point, argcount if used is the number of deliberately passed args
+    // not including this_ptr even if it is used.
+    // It means error messages may be out by argbase with error
+    // reports.  We can either take argbase into account when raising
+    // errors, or find a better way of dealing with _thisptr.
+    // I would like, if objects are wrapped, to assume _thisptr is always
+    // _this and not the first argument.
+    // This may mean looking at Language::memberfunctionHandler
+
+    for (i = 0, p = l; i < num_arguments; i++) {
+      String *source;
+
+      /* Skip ignored arguments */
+      //while (Getattr(p,"tmap:ignore")) { p = Getattr(p,"tmap:ignore:next");}
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+
+      if (mvr) {		// do we assert that numargs=2, that i<2
+	if (i == 0) {
+	  source = NewString("&(property_reference->object)");
+	} else {
+	  source = NewString("&value");
+	}
+      } else {
+	if (i == 0 && has_this_ptr) {
+	  source = NewString("&this_ptr");
+	} else {
+	  source = NewStringf("args[%d]", i - has_this_ptr);
+	}
+      }
+
+      String *ln = Getattr(p, "lname");
+
+      /* Check if optional */
+      if (i >= num_required) {
+	Printf(f->code, "\tif(arg_count > %d) {\n", i);
+      }
+
+      if ((tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$source", source);
+	Replaceall(tm, "$target", ln);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", source);
+	Printf(f->code, "%s\n", tm);
+	if (i == 0 && Getattr(p, "self")) {
+	  Printf(f->code, "\tif(!arg1) SWIG_PHP_Error(E_ERROR, \"this pointer is NULL\");\n");
+	}
+	p = Getattr(p, "tmap:in:next");
+	if (i >= num_required) {
+	  Printf(f->code, "}\n");
+	}
+	continue;
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+      }
+      if (i >= num_required) {
+	Printf(f->code, "\t}\n");
+      }
+      Delete(source);
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (i = 0, p = l; p; i++) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    for (i = 0, p = l; p; i++) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	//      Replaceall(tm,"$input",Getattr(p,"lname"));
+	Replaceall(tm, "$target", "return_value");
+	Replaceall(tm, "$result", "return_value");
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    Setattr(n, "wrap:name", wname);
+
+    /* emit function call */
+    String *actioncode = emit_action(n);
+
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      Replaceall(tm, "$input", "result");
+      Replaceall(tm, "$source", "result");
+      Replaceall(tm, "$target", "return_value");
+      Replaceall(tm, "$result", "return_value");
+      Replaceall(tm, "$owner", newobject ? "1" : "0");
+      Printf(f->code, "%s\n", tm);
+      // Are we returning a wrapable object?
+      if (shadow && php_version == 4 && is_shadow(d) && (SwigType_type(d) != T_ARRAY)) {
+	// Make object.
+	Printf(f->code, "{\n/* Wrap this return value */\n");
+	Printf(f->code, "zval *_cPtr;\n");
+	Printf(f->code, "ALLOC_ZVAL(_cPtr);\n");
+	Printf(f->code, "*_cPtr = *return_value;\n");
+	Printf(f->code, "INIT_ZVAL(*return_value);\n");
+	if (native_constructor == NATIVE_CONSTRUCTOR) {
+	  Printf(f->code, "add_property_zval(this_ptr,\"" SWIG_PTR "\",_cPtr);\n");
+	} else {
+	  String *shadowrettype = GetShadowReturnType(n);
+	  Printf(f->code, "object_init_ex(return_value,ptr_ce_swig_%s);\n", shadowrettype);
+	  Delete(shadowrettype);
+	  Printf(f->code, "add_property_zval(return_value,\"" SWIG_PTR "\",_cPtr);\n");
+	}
+	Printf(f->code, "}\n");
+      }
+    } else {
+      Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
+    }
+    emit_return_variable(n, d, f);
+
+    if (outarg) {
+      Printv(f->code, outarg, NIL);
+    }
+
+    if (cleanup) {
+      Printv(f->code, cleanup, NIL);
+    }
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Printf(f->code, "%s\n", tm);
+	Delete(tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Printf(f->code, "%s\n", tm);
+      Delete(tm);
+    }
+
+
+    if (mvr) {
+      if (!mvrset) {
+	Printf(f->code, "return _return_value;\n");
+      } else {
+	Printf(f->code, "return SUCCESS;\n");
+      }
+    } else {
+      Printf(f->code, "return;\n");
+    }
+
+    /* Error handling code */
+    Printf(f->code, "fail:\n");
+    Printv(f->code, cleanup, NIL);
+    Printv(f->code, "zend_error(SWIG_ErrorCode(),SWIG_ErrorMsg());", NIL);
+
+    Printf(f->code, "}\n");
+
+    Replaceall(f->code, "$cleanup", cleanup);
+    Replaceall(f->code, "$symname", iname);
+
+    Wrapper_print(f, s_wrappers);
+
+    if (overloaded && !Getattr(n, "sym:nextSibling")) {
+      dispatchFunction(n);
+    }
+
+    Delete(wname);
+    wname = NULL;
+
+    if (!(shadow && php_version == 5)) {
+      DelWrapper(f);
+      return SWIG_OK;
+    }
+
+    // Handle getters and setters.
+    if (wrapperType == membervar) {
+      const char *p = Char(iname);
+      if (strlen(p) > 4) {
+	p += strlen(p) - 4;
+	String *varname = Getattr(n, "membervariableHandler:sym:name");
+	if (strcmp(p, "_get") == 0) {
+	  Setattr(shadow_get_vars, varname, iname);
+	} else if (strcmp(p, "_set") == 0) {
+	  Setattr(shadow_set_vars, varname, iname);
+	}
+      }
+    }
+    // Only look at non-overloaded methods and the last entry in each overload
+    // chain (we check the last so that wrap:parms and wrap:name have been set
+    // for them all).
+    if (overloaded && Getattr(n, "sym:nextSibling") != 0)
+      return SWIG_OK;
+
+    if (!s_oowrappers)
+      s_oowrappers = NewStringEmpty();
+    if (newobject || wrapperType == memberfn || wrapperType == staticmemberfn || wrapperType == standard) {
+      bool handle_as_overload = false;
+      String **arg_names;
+      String **arg_values;
+      // Method or static method or plain function.
+      const char *methodname = 0;
+      String *output = s_oowrappers;
+      if (newobject) {
+	class_has_ctor = true;
+	methodname = "__construct";
+      } else if (wrapperType == memberfn) {
+	methodname = Char(Getattr(n, "memberfunctionHandler:sym:name"));
+      } else if (wrapperType == staticmemberfn) {
+	methodname = Char(Getattr(n, "staticmemberfunctionHandler:sym:name"));
+      } else {			// wrapperType == standard
+	methodname = Char(iname);
+	if (!s_fakeoowrappers)
+	  s_fakeoowrappers = NewStringEmpty();
+	output = s_fakeoowrappers;
+      }
+
+      bool really_overloaded = overloaded ? true : false;
+      int min_num_of_arguments = emit_num_required(l);
+      int max_num_of_arguments = emit_num_arguments(l);
+      // For a function with default arguments, we end up with the fullest
+      // parmlist in full_parmlist.
+      ParmList *full_parmlist = l;
+      Hash *ret_types = NewHash();
+      Setattr(ret_types, d, d);
+
+      if (overloaded) {
+	// Look at all the overloaded versions of this method in turn to
+	// decide if it's really an overloaded method, or just one where some
+	// parameters have default values.
+	Node *o = Getattr(n, "sym:overloaded");
+	while (o) {
+	  if (o == n) {
+	    o = Getattr(o, "sym:nextSibling");
+	    continue;
+	  }
+
+	  SwigType *d2 = Getattr(o, "type");
+	  if (!d2) {
+	    assert(constructor);
+	  } else if (!Getattr(ret_types, d2)) {
+	    Setattr(ret_types, d2, d2);
+	  }
+
+	  ParmList *l2 = Getattr(o, "wrap:parms");
+	  int num_arguments = emit_num_arguments(l2);
+	  int num_required = emit_num_required(l2);
+	  if (num_required < min_num_of_arguments)
+	    min_num_of_arguments = num_required;
+
+	  if (num_arguments > max_num_of_arguments) {
+	    max_num_of_arguments = num_arguments;
+	    full_parmlist = l2;
+	  }
+	  o = Getattr(o, "sym:nextSibling");
+	}
+
+	o = Getattr(n, "sym:overloaded");
+	while (o) {
+	  if (o == n) {
+	    o = Getattr(o, "sym:nextSibling");
+	    continue;
+	  }
+
+	  ParmList *l2 = Getattr(o, "wrap:parms");
+	  Parm *p = l, *p2 = l2;
+	  if (wrapperType == memberfn) {
+	    p = nextSibling(p);
+	    p2 = nextSibling(p2);
+	  }
+	  while (p && p2) {
+	    if (Cmp(Getattr(p, "type"), Getattr(p2, "type")) != 0)
+	      break;
+	    if (Cmp(Getattr(p, "name"), Getattr(p2, "name")) != 0)
+	      break;
+	    String *value = Getattr(p, "value");
+	    String *value2 = Getattr(p2, "value");
+	    if (value && !value2)
+	      break;
+	    if (!value && value2)
+	      break;
+	    if (value) {
+	      if (Cmp(value, value2) != 0)
+		break;
+	    }
+	    p = nextSibling(p);
+	    p2 = nextSibling(p2);
+	  }
+	  if (p && p2)
+	    break;
+	  // One parameter list is a prefix of the other, so check that all
+	  // remaining parameters of the longer list are optional.
+	  if (p2)
+	    p = p2;
+	  while (p && Getattr(p, "value"))
+	    p = nextSibling(p);
+	  if (p)
+	    break;
+	  o = Getattr(o, "sym:nextSibling");
+	}
+	if (!o) {
+	  // This "overloaded method" is really just one with default args.
+	  really_overloaded = false;
+	  if (l != full_parmlist) {
+	    l = full_parmlist;
+	    if (wrapperType == memberfn)
+	      l = nextSibling(l);
+	  }
+	}
+      }
+
+      if (wrapperType == memberfn) {
+	// Allow for the "this" pointer.
+	--min_num_of_arguments;
+	--max_num_of_arguments;
+      }
+
+      arg_names = (String **) malloc(max_num_of_arguments * sizeof(String *));
+      if (!arg_names) {
+	/* FIXME: How should this be handled?  The rest of SWIG just seems
+	 * to not bother checking for malloc failing! */
+	fprintf(stderr, "Malloc failed!\n");
+	exit(1);
+      }
+      for (i = 0; i < max_num_of_arguments; ++i) {
+	arg_names[i] = NULL;
+      }
+
+      arg_values = (String **) malloc(max_num_of_arguments * sizeof(String *));
+      if (!arg_values) {
+	/* FIXME: How should this be handled?  The rest of SWIG just seems
+	 * to not bother checking for malloc failing! */
+	fprintf(stderr, "Malloc failed!\n");
+	exit(1);
+      }
+      for (i = 0; i < max_num_of_arguments; ++i) {
+	arg_values[i] = NULL;
+      }
+
+      Node *o;
+      if (overloaded) {
+	o = Getattr(n, "sym:overloaded");
+      } else {
+	o = n;
+      }
+      while (o) {
+	int argno = 0;
+	Parm *p = Getattr(o, "wrap:parms");
+	if (wrapperType == memberfn)
+	  p = nextSibling(p);
+	while (p) {
+	  if (GetInt(p, "tmap:in:numinputs") == 0) {
+	    p = nextSibling(p);
+	    continue;
+	  }
+	  assert(0 <= argno && argno < max_num_of_arguments);
+	  String *&pname = arg_names[argno];
+	  const char *pname_cstr = GetChar(p, "name");
+	  if (!pname_cstr) {
+	    // Unnamed parameter, e.g. int foo(int);
+	  } else if (pname == NULL) {
+	    pname = NewString(pname_cstr);
+	  } else {
+	    size_t len = strlen(pname_cstr);
+	    size_t spc = 0;
+	    size_t len_pname = strlen(Char(pname));
+	    while (spc + len <= len_pname) {
+	      if (strncmp(pname_cstr, Char(pname) + spc, len) == 0) {
+		char ch = ((char *) Char(pname))[spc + len];
+		if (ch == '\0' || ch == ' ') {
+		  // Already have this pname_cstr.
+		  pname_cstr = NULL;
+		  break;
+		}
+	      }
+	      char *p = strchr(Char(pname) + spc, ' ');
+	      if (!p)
+		break;
+	      spc = (p + 4) - Char(pname);
+	    }
+	    if (pname_cstr) {
+	      Printf(pname, " or_%s", pname_cstr);
+	    }
+	  }
+	  String *value = NewString(Getattr(p, "value"));
+	  if (Len(value)) {
+	    /* Check that value is a valid constant in PHP (and adjust it if
+	     * necessary, or replace it with "?" if it's just not valid). */
+	    SwigType *type = Getattr(p, "type");
+	    switch (SwigType_type(type)) {
+	      case T_BOOL: {
+		if (Strcmp(value, "true") == 0 || Strcmp(value, "false") == 0)
+		  break;
+		char *p;
+		errno = 0;
+		int n = strtol(Char(value), &p, 0);
+	        Clear(value);
+		if (errno || *p) {
+		  Append(value, "?");
+		} else if (n) {
+		  Append(value, "true");
+		} else {
+		  Append(value, "false");
+		}
+		break;
+	      }
+	      case T_CHAR:
+	      case T_SCHAR:
+	      case T_SHORT:
+	      case T_INT:
+	      case T_LONG: {
+		char *p;
+		errno = 0;
+		(void) strtol(Char(value), &p, 0);
+		if (errno || *p) {
+		  Clear(value);
+		  Append(value, "?");
+		}
+		break;
+	      }
+	      case T_UCHAR:
+	      case T_USHORT:
+	      case T_UINT:
+	      case T_ULONG: {
+		char *p;
+		errno = 0;
+		(void) strtoul(Char(value), &p, 0);
+		if (errno || *p) {
+		  Clear(value);
+		  Append(value, "?");
+		}
+		break;
+	      }
+	      case T_FLOAT:
+	      case T_DOUBLE:{
+		char *p;
+		errno = 0;
+		/* FIXME: strtod is locale dependent... */
+		double val = strtod(Char(value), &p);
+		if (errno || *p) {
+		  Clear(value);
+		  Append(value, "?");
+		} else if (strchr(Char(value), '.') == NULL) {
+		  // Ensure value is a double constant, not an integer one.
+		  Append(value, ".0");
+		  double val2 = strtod(Char(value), &p);
+		  if (errno || *p || val != val2) {
+		    Clear(value);
+		    Append(value, "?");
+		  }
+		}
+		break;
+	      }
+	      case T_REFERENCE:
+	      case T_USER:
+	      case T_ARRAY:
+		Clear(value);
+		Append(value, "?");
+		break;
+	      case T_STRING:
+		if (Len(value) < 2) {
+		  // How can a string (including "" be less than 2 characters?)
+		  Clear(value);
+		  Append(value, "?");
+		} else {
+		  const char *v = Char(value);
+		  if (v[0] != '"' || v[Len(value) - 1] != '"') {
+		    Clear(value);
+		    Append(value, "?");
+		  }
+		  // Strings containing "$" require special handling, but we do
+		  // that later.
+		}
+		break;
+	      case T_VOID:
+		assert(false);
+		break;
+	      case T_POINTER: {
+		const char *v = Char(value);
+		if (v[0] == '(') {
+		  // Handle "(void*)0", "(TYPE*)0", "(char*)NULL", etc.
+		  v += strcspn(v + 1, "*()") + 1;
+		  if (*v == '*') {
+		    do {
+		      v++;
+		      v += strspn(v, " \t");
+		    } while (*v == '*');
+		    if (*v++ == ')') {
+		      v += strspn(v, " \t");
+		      String * old = value;
+		      value = NewString(v);
+		      Delete(old);
+		    }
+		  }
+		}
+		if (Strcmp(value, "NULL") == 0 ||
+		    Strcmp(value, "0") == 0 ||
+		    Strcmp(value, "0L") == 0) {
+		  Clear(value);
+		  Append(value, "null");
+		} else {
+		  Clear(value);
+		  Append(value, "?");
+		}
+		break;
+	      }
+	    }
+
+	    if (!arg_values[argno]) {
+	      arg_values[argno] = value;
+	      value = NULL;
+	    } else if (Cmp(arg_values[argno], value) != 0) {
+	      // If a parameter has two different default values in
+	      // different overloaded forms of the function, we can't
+	      // set its default in PHP.  Flag this by setting its
+	      // default to `?'.
+	      Delete(arg_values[argno]);
+	      arg_values[argno] = NewString("?");
+	    }
+	  } else if (arg_values[argno]) {
+	    // This argument already has a default value in another overloaded
+	    // form, but doesn't in this form.  So don't try to do anything
+	    // clever, just let the C wrappers resolve the overload and set the
+	    // default values.
+	    //
+	    // This handling is safe, but I'm wondering if it may be overly
+	    // conservative (FIXME) in some cases.  It seems it's only bad when
+	    // there's an overloaded form with the appropriate number of
+	    // parameters which doesn't want the default value, but I need to
+	    // think about this more.
+	    Delete(arg_values[argno]);
+	    arg_values[argno] = NewString("?");
+	  }
+	  Delete(value);
+	  p = nextSibling(p);
+	  ++argno;
+	}
+	if (!really_overloaded)
+	  break;
+	o = Getattr(o, "sym:nextSibling");
+      }
+
+      /* Clean up any parameters which haven't yet got names, or whose
+       * names clash. */
+      Hash *seen = NewHash();
+      /* We need $this to refer to the current class, so can't allow it
+       * to be used as a parameter. */
+      Setattr(seen, "this", seen);
+      /* We use $r to store the return value, so disallow that as a parameter
+       * name in case the user uses the "call-time pass-by-reference" feature
+       * (it's deprecated and off by default in PHP5 and even later PHP4
+       * versions apparently, but we want to be maximally portable).
+       */
+      Setattr(seen, "r", seen);
+
+      for (int argno = 0; argno < max_num_of_arguments; ++argno) {
+	String *&pname = arg_names[argno];
+	if (pname) {
+	  Replaceall(pname, " ", "_");
+	} else {
+	  /* We get here if the SWIG .i file has "int foo(int);" */
+	  pname = NewStringEmpty();
+	  Printf(pname, "arg%d", argno + 1);
+	}
+	// Check if we've already used this parameter name.
+	while (Getattr(seen, pname)) {
+	  // Append "_" to clashing names until they stop clashing...
+	  Printf(pname, "_");
+	}
+	Setattr(seen, Char(pname), seen);
+
+	if (arg_values[argno] && Cmp(arg_values[argno], "?") == 0) {
+	  handle_as_overload = true;
+	}
+      }
+      Delete(seen);
+      seen = NULL;
+
+      String *invoke = NewStringEmpty();
+      String *prepare = NewStringEmpty();
+      String *args = NewStringEmpty();
+
+      if (!handle_as_overload && !(really_overloaded && max_num_of_arguments > min_num_of_arguments)) {
+	Printf(invoke, "%s(", iname);
+	if (wrapperType == memberfn) {
+	  Printf(invoke, "$this->%s", SWIG_PTR);
+	}
+	for (int i = 0; i < max_num_of_arguments; ++i) {
+	  if (i)
+	    Printf(args, ",");
+	  if (i || wrapperType == memberfn)
+	    Printf(invoke, ",");
+	  String *value = arg_values[i];
+	  if (value) {
+	    const char *v = Char(value);
+	    if (v[0] == '"') {
+	      /* In a PHP double quoted string, $ needs to be escaped as \$. */
+	      Replaceall(value, "$", "\\$");
+	    }
+	    Printf(args, "$%s=%s", arg_names[i], value);
+	  } else {
+	    Printf(args, "$%s", arg_names[i]);
+	  }
+	  Printf(invoke, "$%s", arg_names[i]);
+	}
+	Printf(invoke, ")");
+      } else {
+	int i;
+	for (i = 0; i < min_num_of_arguments; ++i) {
+	  if (i)
+	    Printf(args, ",");
+	  Printf(args, "$%s", arg_names[i]);
+	}
+	String *invoke_args = NewStringEmpty();
+	if (wrapperType == memberfn) {
+	  Printf(invoke_args, "$this->%s", SWIG_PTR);
+	  if (min_num_of_arguments > 0)
+	    Printf(invoke_args, ",");
+	}
+	Printf(invoke_args, "%s", args);
+	bool had_a_case = false;
+	int last_handled_i = i - 1;
+	for (; i < max_num_of_arguments; ++i) {
+	  if (i)
+	    Printf(args, ",");
+	  const char *value = Char(arg_values[i]);
+	  // FIXME: (really_overloaded && handle_as_overload) is perhaps a
+	  // little conservative, but it doesn't hit any cases that it
+	  // shouldn't for Xapian at least (and we need it to handle
+	  // "Enquire::get_mset()" correctly).
+	  bool non_php_default = ((really_overloaded && handle_as_overload) ||
+				  !value || strcmp(value, "?") == 0);
+	  if (non_php_default)
+	    value = "null";
+	  Printf(args, "$%s=%s", arg_names[i], value);
+	  if (non_php_default) {
+	    if (!had_a_case) {
+	      Printf(prepare, "\t\tswitch (func_num_args()) {\n");
+	      had_a_case = true;
+	    }
+	    Printf(prepare, "\t\t");
+	    while (last_handled_i < i) {
+	      Printf(prepare, "case %d: ", ++last_handled_i);
+	    }
+	    if (Cmp(d, "void") != 0)
+	      Printf(prepare, "$r=");
+	    Printf(prepare, "%s(%s); break;\n", iname, invoke_args);
+	  }
+	  if (i || wrapperType == memberfn)
+	    Printf(invoke_args, ",");
+	  Printf(invoke_args, "$%s", arg_names[i]);
+	}
+	Printf(prepare, "\t\t");
+	if (had_a_case)
+	  Printf(prepare, "default: ");
+	if (Cmp(d, "void") != 0)
+	  Printf(prepare, "$r=");
+	Printf(prepare, "%s(%s);\n", iname, invoke_args);
+	if (had_a_case)
+	  Printf(prepare, "\t\t}\n");
+	Delete(invoke_args);
+	Printf(invoke, "$r");
+      }
+
+      Printf(output, "\n");
+      // If it's a member function or a class constructor...
+      if (wrapperType == memberfn || (newobject && current_class)) {
+	Printf(output, "\tfunction %s(%s) {\n", methodname, args);
+	// We don't need this code if the wrapped class has a copy ctor
+	// since the flat function new_CLASSNAME will handle it for us.
+	if (newobject && !Getattr(current_class, "allocate:copy_constructor")) {
+	  SwigType *t = Getattr(current_class, "classtype");
+	  String *mangled_type = SwigType_manglestr(SwigType_ltype(t));
+	  Printf(s_oowrappers, "\t\tif (is_resource($%s) && get_resource_type($%s) == \"_p%s\") {\n", arg_names[0], arg_names[0], mangled_type);
+	  Printf(s_oowrappers, "\t\t\t$this->%s=$%s;\n", SWIG_PTR, arg_names[0]);
+	  Printf(s_oowrappers, "\t\t\treturn;\n");
+	  Printf(s_oowrappers, "\t\t}\n");
+	}
+      } else {
+	Printf(output, "\tstatic function %s(%s) {\n", methodname, args);
+      }
+      Delete(args);
+      args = NULL;
+
+      for (int i = 0; i < max_num_of_arguments; ++i) {
+	Delete(arg_names[i]);
+      }
+      free(arg_names);
+      arg_names = NULL;
+
+      Printf(output, "%s", prepare);
+      if (newobject) {
+	Printf(output, "\t\t$this->%s=%s;\n", SWIG_PTR, invoke);
+      } else if (Cmp(d, "void") == 0) {
+	if (Cmp(invoke, "$r") != 0)
+	  Printf(output, "\t\t%s;\n", invoke);
+      } else if (is_class(d)) {
+	if (Cmp(invoke, "$r") != 0)
+	  Printf(output, "\t\t$r=%s;\n", invoke);
+	if (Len(ret_types) == 1) {
+	  Printf(output, "\t\treturn is_resource($r) ? new %s%s($r) : $r;\n", prefix, Getattr(classLookup(d), "sym:name"));
+	} else {
+	  Printf(output, "\t\tif (!is_resource($r)) return $r;\n");
+	  Printf(output, "\t\tswitch (get_resource_type($r)) {\n");
+	  Iterator i = First(ret_types);
+	  while (i.item) {
+	    SwigType *ret_type = i.item;
+	    i = Next(i);
+	    Printf(output, "\t\t");
+	    String *mangled = NewString("_p");
+	    Printf(mangled, "%s", SwigType_manglestr(ret_type));
+	    Node *class_node = Getattr(zend_types, mangled);
+	    if (!class_node) {
+	      /* This is needed when we're returning a pointer to a type
+	       * rather than returning the type by value or reference. */
+	      class_node = current_class;
+	      Delete(mangled);
+	      mangled = NewString(SwigType_manglestr(ret_type));
+	      class_node = Getattr(zend_types, mangled);
+	    }
+	    if (i.item) {
+	      Printf(output, "case \"%s\": ", mangled);
+	    } else {
+	      Printf(output, "default: ");
+	    }
+	    const char *classname = GetChar(class_node, "sym:name");
+	    if (!classname)
+	      classname = GetChar(class_node, "name");
+	    if (classname)
+	      Printf(output, "return new %s%s($r);\n", prefix, classname);
+            else
+	      Printf(output, "return $r;\n");
+	    Delete(mangled);
+	  }
+	  Printf(output, "\t\t}\n");
+	}
+      } else {
+	Printf(output, "\t\treturn %s;\n", invoke);
+      }
+      Printf(output, "\t}\n");
+      Delete(prepare);
+      Delete(invoke);
+      free(arg_values);
+    }
+
+    DelWrapper(f);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * globalvariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int globalvariableHandler(Node *n) {
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    String *tm;
+
+    /* First do the wrappers such as name_set(), name_get()
+     * as provided by the baseclass's implementation of variableWrapper
+     */
+    if (Language::globalvariableHandler(n) == SWIG_NOWRAP) {
+      return SWIG_NOWRAP;
+    }
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    SwigType_remember(t);
+
+    /* First link C variables to PHP */
+
+    tm = Swig_typemap_lookup("varinit", n, name, 0);
+    if (tm) {
+      Replaceall(tm, "$target", name);
+      Printf(s_vinit, "%s\n", tm);
+    } else {
+      Printf(stderr, "%s: Line %d, Unable to link with type %s\n", input_file, line_number, SwigType_str(t, 0));
+    }
+
+    /* Now generate PHP -> C sync blocks */
+    /*
+       tm = Swig_typemap_lookup("varin", n, name, 0);
+       if(tm) {
+       Replaceall(tm, "$symname", iname);
+       Printf(f_c->code, "%s\n", tm);
+       } else {
+       Printf(stderr,"%s: Line %d, Unable to link with type %s\n",
+       input_file, line_number, SwigType_str(t, 0));
+       }
+     */
+    /* Now generate C -> PHP sync blocks */
+    /*
+       if(!GetFlag(n,"feature:immutable")) {
+
+       tm = Swig_typemap_lookup("varout", n, name, 0);
+       if(tm) {
+       Replaceall(tm, "$symname", iname);
+       Printf(f_php->code, "%s\n", tm);
+       } else {
+       Printf(stderr,"%s: Line %d, Unable to link with type %s\n",
+       input_file, line_number, SwigType_str(t, 0));
+       }
+       }
+     */
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *name = GetChar(n, "name");
+    String *iname = GetChar(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    SwigType_remember(type);
+
+    if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Printf(s_cinit, "%s\n", tm);
+    }
+
+    if (shadow && php_version == 5) {
+      String *enumvalue = GetChar(n, "enumvalue");
+      String *set_to = iname;
+
+      if (!enumvalue) {
+	enumvalue = GetChar(n, "enumvalueex");
+      }
+
+      if (enumvalue) {
+	// Check for a simple constant expression which is valid in PHP.
+	// If we find one, initialise the const member with it; otherwise
+	// we initialise it using the C/C++ wrapped constant.
+	const char *p;
+	for (p = Char(enumvalue); *p; ++p) {
+	  if (!isdigit((unsigned char)*p) && !strchr(" +-", *p)) {
+	    // FIXME: enhance to handle `<previous_enum> + 1' which is what
+	    // we get for enums that don't have an explicit value set.
+	    break;
+	  }
+	}
+	if (!*p) set_to = enumvalue;
+      }
+
+      if (wrapping_member_constant) {
+	if (!s_oowrappers)
+	  s_oowrappers = NewStringEmpty();
+	Printf(s_oowrappers, "\n\tconst %s = %s;\n", wrapping_member_constant, set_to);
+      } else {
+	if (!s_fakeoowrappers)
+	  s_fakeoowrappers = NewStringEmpty();
+	Printf(s_fakeoowrappers, "\n\tconst %s = %s;\n", iname, set_to);
+      }
+    }
+
+    return SWIG_OK;
+  }
+
+  /*
+   * PHP::pragma()
+   *
+   * Pragma directive.
+   *
+   * %pragma(php4) code="String"         # Includes a string in the .php file
+   * %pragma(php4) include="file.pl"     # Includes a file in the .php file
+   */
+
+  virtual int pragmaDirective(Node *n) {
+    if (!ImportMode) {
+      String *lang = Getattr(n, "lang");
+      String *type = Getattr(n, "name");
+      String *value = Getattr(n, "value");
+
+      if (Strcmp(lang, "php4") == 0) {
+	if (Strcmp(type, "code") == 0) {
+	  if (value) {
+	    Printf(pragma_code, "%s\n", value);
+	  }
+	} else if (Strcmp(type, "include") == 0) {
+	  if (value) {
+	    Printf(pragma_incl, "include \"%s\";\n", value);
+	  }
+	} else if (Strcmp(type, "phpinfo") == 0) {
+	  if (value) {
+	    Printf(pragma_phpinfo, "%s\n", value);
+	  }
+	} else {
+	  Swig_warning(WARN_PHP4_UNKNOWN_PRAGMA, input_file, line_number, "Unrecognized pragma <%s>.\n", type);
+	}
+      }
+    }
+    return Language::pragmaDirective(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int classDeclaration(Node *n) {
+    if (!Getattr(n, "feature:onlychildren")) {
+      String *symname = Getattr(n, "sym:name");
+      Setattr(n, "php:proxy", symname);
+    }
+
+    return Language::classDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int classHandler(Node *n) {
+    constructors = 0;
+    //SwigType *t = Getattr(n, "classtype");
+    current_class = n;
+    // String *use_class_name=SwigType_manglestr(SwigType_ltype(t));
+
+    if (shadow && php_version == 4) {
+      char *rename = GetChar(n, "sym:name");
+
+      if (!addSymbol(rename, n))
+	return SWIG_ERROR;
+      shadow_classname = NewString(rename);
+      cs_entry = NewStringEmpty();
+      Printf(cs_entry, "/* Function entries for %s */\n", shadow_classname);
+      Printf(cs_entry, "static zend_function_entry %s_functions[] = {\n", shadow_classname);
+
+      if (Strcmp(shadow_classname, module) == 0) {
+	Printf(stderr, "class name cannot be equal to module name: %s\n", module);
+	SWIG_exit(1);
+      }
+
+      shadow_get_vars = NewHash();
+      shadow_set_vars = NewHash();
+
+      /* Deal with inheritance */
+      List *baselist = Getattr(n, "bases");
+      if (baselist) {
+	Iterator base = First(baselist);
+	while (base.item && GetFlag(base.item, "feature:ignore")) {
+	  base = Next(base);
+	}
+	base = Next(base);
+	if (base.item) {
+	  /* Warn about multiple inheritance for additional base class(es) */
+	  while (base.item) {
+	    if (GetFlag(base.item, "feature:ignore")) {
+	      base = Next(base);
+	      continue;
+	    }
+	    String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0);
+	    String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0);
+	    Swig_warning(WARN_PHP4_MULTIPLE_INHERITANCE, input_file, line_number,
+			 "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Php4.\n", proxyclassname, baseclassname);
+	    base = Next(base);
+	  }
+	}
+      }
+
+      /* Write out class init code */
+      Printf(s_vdecl, "static zend_class_entry ce_swig_%s;\n", shadow_classname);
+      Printf(s_vdecl, "static zend_class_entry* ptr_ce_swig_%s=NULL;\n", shadow_classname);
+    } else if (shadow && php_version == 5) {
+      char *rename = GetChar(n, "sym:name");
+
+      if (!addSymbol(rename, n))
+	return SWIG_ERROR;
+      shadow_classname = NewString(rename);
+
+      shadow_get_vars = NewHash();
+      shadow_set_vars = NewHash();
+
+      /* Deal with inheritance */
+      List *baselist = Getattr(n, "bases");
+      if (baselist) {
+	Iterator base = First(baselist);
+	while (base.item && GetFlag(base.item, "feature:ignore")) {
+	  base = Next(base);
+	}
+	base = Next(base);
+	if (base.item) {
+	  /* Warn about multiple inheritance for additional base class(es) */
+	  while (base.item) {
+	    if (GetFlag(base.item, "feature:ignore")) {
+	      base = Next(base);
+	      continue;
+	    }
+	    String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0);
+	    String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0);
+	    Swig_warning(WARN_PHP4_MULTIPLE_INHERITANCE, input_file, line_number,
+			 "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in PHP.\n", proxyclassname, baseclassname);
+	    base = Next(base);
+	  }
+	}
+      }
+    }
+
+    classnode = n;
+    Language::classHandler(n);
+    classnode = 0;
+
+    if (shadow && php_version == 4) {
+      DOH *key;
+      String *s_propget = NewStringEmpty();
+      String *s_propset = NewStringEmpty();
+      List *baselist = Getattr(n, "bases");
+      Iterator ki, base;
+
+      // If no constructor was generated (abstract class) we had better
+      // generate a constructor that raises an error about instantiating
+      // abstract classes
+      if (Getattr(n, "abstract") && constructors == 0) {
+	// have to write out fake constructor which raises an error when called
+	abstractConstructorHandler(n);
+      }
+
+      Printf(s_oinit, "/* Define class %s */\n", shadow_classname);
+      Printf(s_oinit, "INIT_OVERLOADED_CLASS_ENTRY(ce_swig_%s,\"%(lower)s\",%s_functions,", shadow_classname, shadow_classname, shadow_classname);
+      Printf(s_oinit, "NULL,_wrap_propget_%s,_wrap_propset_%s);\n", shadow_classname, shadow_classname);
+
+      // ******** Write property SET handlers
+      Printf(s_header, "static int _wrap_propset_%s(zend_property_reference *property_reference, pval *value);\n", shadow_classname);
+      Printf(s_header, "static int _propset_%s(zend_property_reference *property_reference, pval *value);\n", shadow_classname);
+
+      Printf(s_propset, "static int _wrap_propset_%s(zend_property_reference *property_reference, pval *value) { \n", shadow_classname);
+      Printf(s_propset, "  zval * _value;\n");
+      Printf(s_propset, "  zend_llist_element *element = property_reference->elements_list->head;\n");
+      Printf(s_propset, "  zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n");
+      Printf(s_propset, "  if (_propset_%s(property_reference, value)==SUCCESS) return SUCCESS;\n", shadow_classname);
+      Printf(s_propset, "  /* set it ourselves as it is %s */\n", shadow_classname);
+      Printf(s_propset, "  MAKE_STD_ZVAL(_value);\n");
+      Printf(s_propset, "  *_value=*value;\n");
+      Printf(s_propset, "  INIT_PZVAL(_value);\n");
+      Printf(s_propset, "  zval_copy_ctor(_value);\n");
+      Printf(s_propset,
+	     "  return add_property_zval_ex(property_reference->object,Z_STRVAL_P(&(property->element)),1+Z_STRLEN_P(&(property->element)),_value);\n");
+      Printf(s_propset, "}\n");
+      Printf(s_propset, "static int _propset_%s(zend_property_reference *property_reference, pval *value) {\n", shadow_classname);
+
+
+      if (baselist) {
+	base = First(baselist);
+      } else {
+	base.item = NULL;
+      }
+
+      while (base.item && GetFlag(base.item, "feature:ignore")) {
+	base = Next(base);
+      }
+
+      ki = First(shadow_set_vars);
+      key = ki.key;
+
+      // Print function header; we only need to find property name if there
+      // are properties for this class to look up...
+      if (key || !base.item) {	// or if we are base class and set it ourselves
+	Printf(s_propset, "  /* get the property name */\n");
+	Printf(s_propset, "  zend_llist_element *element = property_reference->elements_list->head;\n");
+	Printf(s_propset, "  zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n");
+	Printf(s_propset, "  char *propname=Z_STRVAL_P(&(property->element));\n");
+      } else {
+	if (base.item) {
+	  Printf(s_propset, "  /* No extra properties for subclass %s */\n", shadow_classname);
+	} else {
+	  Printf(s_propset, "  /* No properties for base class %s */\n", shadow_classname);
+	}
+      }
+
+      while (ki.key) {
+	key = ki.key;
+	Printf(s_propset, "  if (strcmp(propname,\"%s\")==0) return _wrap_%s(property_reference, value);\n", ki.item, key);
+
+	ki = Next(ki);
+      }
+
+      // If the property wasn't in this class, try the handlers of each base
+      // class (if any) in turn until we succeed in setting the property or
+      // have tried all base classes.
+      if (base.item) {
+	Printf(s_propset, "  /* Try base class(es) */\n");
+	while (base.item) {
+	  Printf(s_propset, "  if (_propset_%s(property_reference, value)==SUCCESS) return SUCCESS;\n", GetChar(base.item, "sym:name"));
+
+	  base = Next(base);
+	  while (base.item && GetFlag(base.item, "feature:ignore")) {
+	    base = Next(base);
+	  }
+	}
+      }
+      Printf(s_propset, "  return FAILURE;\n}\n\n");
+
+      // ******** Write property GET handlers
+      Printf(s_header, "static pval _wrap_propget_%s(zend_property_reference *property_reference);\n", shadow_classname);
+      Printf(s_header, "static int _propget_%s(zend_property_reference *property_reference, pval *value);\n", shadow_classname);
+
+      Printf(s_propget, "static pval _wrap_propget_%s(zend_property_reference *property_reference) {\n", shadow_classname);
+      Printf(s_propget, "  pval result;\n");
+      Printf(s_propget, "  pval **_result;\n");
+      Printf(s_propget, "  zend_llist_element *element = property_reference->elements_list->head;\n");
+      Printf(s_propget, "  zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n");
+      Printf(s_propget, "  result.type = IS_NULL;\n");
+      Printf(s_propget, "  if (_propget_%s(property_reference, &result)==SUCCESS) return result;\n", shadow_classname);
+      Printf(s_propget, "  /* return it ourselves */\n");
+      Printf(s_propget,
+	     "  if (zend_hash_find(Z_OBJPROP_P(property_reference->object),Z_STRVAL_P(&(property->element)),1+Z_STRLEN_P(&(property->element)),(void**)&_result)==SUCCESS) {\n");
+      Printf(s_propget, "  zval *_value;\n");
+      Printf(s_propget, "  MAKE_STD_ZVAL(_value);");
+      Printf(s_propget, "  *_value=**_result;\n");
+      Printf(s_propget, "  INIT_PZVAL(_value);\n");
+      Printf(s_propget, "  zval_copy_ctor(_value);\n");
+      Printf(s_propget, "  return *_value;\n");
+      Printf(s_propget, "  }\n");
+      Printf(s_propget, "  result.type = IS_NULL;\n");
+      Printf(s_propget, "  return result;\n");
+      Printf(s_propget, "}\n");
+      Printf(s_propget, "static int _propget_%s(zend_property_reference *property_reference, pval *value) {\n", shadow_classname);
+
+      if (baselist) {
+	base = First(baselist);
+      } else {
+	base.item = NULL;
+      }
+      while (base.item && GetFlag(base.item, "feature:ignore")) {
+	base = Next(base);
+      }
+      ki = First(shadow_get_vars);
+
+      key = ki.key;
+
+      // Print function header; we only need to find property name if there
+      // are properties for this class to look up...
+      if (key || !base.item) {	// or if we are base class...
+	Printf(s_propget, "  /* get the property name */\n");
+	Printf(s_propget, "  zend_llist_element *element = property_reference->elements_list->head;\n");
+	Printf(s_propget, "  zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n");
+	Printf(s_propget, "  char *propname=Z_STRVAL_P(&(property->element));\n");
+      } else {
+	if (base.item) {
+	  Printf(s_propget, "  /* No extra properties for subclass %s */\n", shadow_classname);
+	} else {
+	  Printf(s_propget, "  /* No properties for base class %s */\n", shadow_classname);
+	}
+      }
+
+      while (ki.key) {
+	key = ki.key;
+	Printf(s_propget, "  if (strcmp(propname,\"%s\")==0) {\n", ki.item);
+	Printf(s_propget, "    *value=_wrap_%s(property_reference);\n", key);
+	Printf(s_propget, "    return SUCCESS;\n");
+	Printf(s_propget, "  }\n");
+
+	ki = Next(ki);
+      }
+
+      // If the property wasn't in this class, try the handlers of each base
+      // class (if any) in turn until we succeed in setting the property or
+      // have tried all base classes.
+      if (base.item) {
+	Printf(s_propget, "  /* Try base class(es). */\n");
+	while (base.item) {
+	  Printf(s_propget, "  if (_propget_%s(property_reference, value)==SUCCESS) return SUCCESS;\n", GetChar(base.item, "sym:name"));
+
+	  base = Next(base);
+	  while (base.item && GetFlag(base.item, "feature:ignore")) {
+	    base = Next(base);
+	  }
+	}
+      }
+      Printf(s_propget, "  return FAILURE;\n}\n\n");
+
+      // wrappers generated now...
+
+      // add wrappers to output code
+      Printf(s_wrappers, "/* property handler for class %s */\n", shadow_classname);
+      Printv(s_wrappers, s_propget, s_propset, NIL);
+
+      // Save class in class table
+      if (baselist) {
+	base = First(baselist);
+      } else {
+	base.item = NULL;
+      }
+      while (base.item && GetFlag(base.item, "feature:ignore")) {
+	base = Next(base);
+      }
+
+      if (base.item) {
+	Printf(s_oinit,
+	       "if (! (ptr_ce_swig_%s=zend_register_internal_class_ex(&ce_swig_%s,&ce_swig_%s,NULL TSRMLS_CC))) zend_error(E_ERROR,\"Error registering wrapper for class %s\");\n",
+	       shadow_classname, shadow_classname, GetChar(base.item, "sym:name"), shadow_classname);
+      } else {
+	Printf(s_oinit,
+	       "if (! (ptr_ce_swig_%s=zend_register_internal_class_ex(&ce_swig_%s,NULL,NULL TSRMLS_CC))) zend_error(E_ERROR,\"Error registering wrapper for class %s\");\n",
+	       shadow_classname, shadow_classname, shadow_classname);
+      }
+      Printf(s_oinit, "\n");
+
+      // Write the enum initialisation code in a static block
+      // These are all the enums defined within the C++ class.
+
+      Delete(shadow_classname);
+      shadow_classname = NULL;
+
+      Delete(shadow_set_vars);
+      shadow_set_vars = NULL;
+      Delete(shadow_get_vars);
+      shadow_get_vars = NULL;
+
+      Printv(all_cs_entry, cs_entry, " { NULL, NULL, NULL}\n};\n", NIL);
+      Delete(cs_entry);
+      cs_entry = NULL;
+    } else if (shadow && php_version == 5) {
+      DOH *key;
+      List *baselist = Getattr(n, "bases");
+      Iterator ki, base;
+
+      if (baselist) {
+	base = First(baselist);
+	while (base.item && GetFlag(base.item, "feature:ignore")) {
+	  base = Next(base);
+	}
+      } else {
+	base.item = NULL;
+      }
+
+      if (Getattr(n, "abstract") && !GetFlag(n, "feature:notabstract")) {
+	Printf(s_phpclasses, "abstract ");
+      }
+
+      Printf(s_phpclasses, "class %s%s ", prefix, shadow_classname);
+      if (base.item) {
+	String *baseclass = Getattr(base.item, "sym:name");
+	if (!baseclass)
+	  baseclass = Getattr(base.item, "name");
+	Printf(s_phpclasses, "extends %s%s ", prefix, baseclass);
+      }
+      Printf(s_phpclasses, "{\n\tpublic $%s=null;\n", SWIG_PTR);
+
+      // Write property SET handlers
+      ki = First(shadow_set_vars);
+
+      if (ki.key) {
+	// This class has setters.
+	// FIXME: just ignore setting an unknown property name for now.
+	Printf(s_phpclasses, "\n\tfunction __set($var,$value) {\n");
+	// FIXME: tune this threshold...
+	if (Len(shadow_set_vars) <= 2) {
+	  // Not many setters, so avoid call_user_func.
+	  while (ki.key) {
+	    key = ki.key;
+	    Printf(s_phpclasses, "\t\tif ($var == '%s') return %s($this->%s,$value);\n", key, ki.item, SWIG_PTR);
+	    ki = Next(ki);
+	  }
+	} else {
+	  Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_set';\n", shadow_classname);
+	  Printf(s_phpclasses, "\t\tif (function_exists($func)) call_user_func($func,$this->%s,$value);\n", SWIG_PTR);
+	}
+	Printf(s_phpclasses, "\t}\n");
+
+	/* Create __isset for PHP 5.1 and later; PHP 5.0 will just ignore it. */
+	Printf(s_phpclasses, "\n\tfunction __isset($var) {\n");
+	// FIXME: tune this threshold, but it should probably be different to
+	// that for __set() and __get() as we don't need to call_user_func()
+	// here...
+	if (Len(shadow_set_vars) == 1) {
+	  // Only one setter, so just check the name.
+	  Printf(s_phpclasses, "\t\treturn ");
+	  while (ki.key) {
+	      key = ki.key;
+	      Printf(s_phpclasses, "$var == '%s'", ki.key);
+	      ki = Next(ki);
+	      if (ki.key) Printf(s_phpclasses, " || ");
+	  }
+	  Printf(s_phpclasses, ";\n");
+	} else {
+	  Printf(s_phpclasses, "\t\treturn function_exists('%s_'.$var.'_set');\n", shadow_classname);
+	}
+	Printf(s_phpclasses, "\t}\n");
+      }
+      // Write property GET handlers
+      ki = First(shadow_get_vars);
+
+      if (ki.key) {
+	// This class has getters.
+	Printf(s_phpclasses, "\n\tfunction __get($var) {\n");
+	// FIXME: tune this threshold...
+	if (Len(shadow_get_vars) <= 2) {
+	  // Not many getters, so avoid call_user_func.
+	  while (ki.key) {
+	    key = ki.key;
+	    Printf(s_phpclasses, "\t\tif ($var == '%s') return %s($this->%s);\n", key, ki.item, SWIG_PTR);
+	    ki = Next(ki);
+	  }
+	} else {
+	  Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_get';\n", shadow_classname);
+	  Printf(s_phpclasses, "\t\tif (function_exists($func)) return call_user_func($func,$this->%s);\n", SWIG_PTR);
+	}
+	// Reading an unknown property name gives null in PHP.
+	Printf(s_phpclasses, "\t\treturn null;\n");
+	Printf(s_phpclasses, "\t}\n");
+      }
+
+      if (!class_has_ctor) {
+	Printf(s_phpclasses, "\tfunction __construct($h) {\n");
+	Printf(s_phpclasses, "\t\t$this->%s=$h;\n", SWIG_PTR);
+	Printf(s_phpclasses, "\t}\n");
+      }
+
+      if (s_oowrappers) {
+	Printf(s_phpclasses, "%s", s_oowrappers);
+	Delete(s_oowrappers);
+	s_oowrappers = NULL;
+      }
+      class_has_ctor = false;
+
+      Printf(s_phpclasses, "}\n\n");
+
+      Delete(shadow_classname);
+      shadow_classname = NULL;
+
+      Delete(shadow_set_vars);
+      shadow_set_vars = NULL;
+      Delete(shadow_get_vars);
+      shadow_get_vars = NULL;
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberfunctionHandler(Node *n) {
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+
+    wrapperType = memberfn;
+    this->Language::memberfunctionHandler(n);
+    wrapperType = standard;
+
+    // Only declare the member function if
+    // we are doing shadow classes, and the function
+    // is not overloaded, or if it is overloaded, it is the dispatch function.
+    if (shadow && php_version == 4 && (!Getattr(n, "sym:overloaded") || !Getattr(n, "sym:nextSibling"))) {
+      char *realname = iname ? iname : name;
+      String *php_function_name = Swig_name_member(shadow_classname, realname);
+      create_command(realname, Swig_name_wrapper(php_function_name));
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int membervariableHandler(Node *n) {
+
+    wrapperType = membervar;
+    Language::membervariableHandler(n);
+    wrapperType = standard;
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmembervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int staticmembervariableHandler(Node *n) {
+
+    wrapperType = staticmembervar;
+    Language::staticmembervariableHandler(n);
+    wrapperType = standard;
+
+    SwigType *type = Getattr(n, "type");
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+
+    /* A temporary(!) hack for static member variables.
+     * Php currently supports class functions, but not class variables.
+     * Until it does, we convert a class variable to a class function
+     * that returns the current value of the variable. E.g.
+     *
+     * class Example {
+     *  public:
+     *          static int ncount;
+     * };
+     *
+     * would be available in php as Example::ncount() 
+     */
+
+    // If the variable is const, then it's wrapped as a constant with set/get functions.
+    if (SwigType_isconst(type))
+      return SWIG_OK;
+
+    // This duplicates the logic from Language::variableWrapper() to test if the set wrapper
+    // is made.
+    int assignable = is_assignable(n);
+    if (assignable) {
+      String *tm = Swig_typemap_lookup("globalin", n, name, 0);
+      if (!tm && SwigType_isarray(type)) {
+	assignable = 0;
+      }
+    }
+
+    String *class_iname = Swig_name_member(Getattr(current_class, "sym:name"), iname);
+    create_command(iname, Swig_name_wrapper(class_iname));
+
+    Wrapper *f = NewWrapper();
+
+    Printv(f->def, "ZEND_NAMED_FUNCTION(", Swig_name_wrapper(class_iname), ") {\n", NIL);
+    String *mget = Swig_name_wrapper(Swig_name_get(class_iname));
+    String *mset = Swig_name_wrapper(Swig_name_set(class_iname));
+
+    if (assignable) {
+      Printf(f->code, "if (ZEND_NUM_ARGS() > 0 ) {\n");
+      Printf(f->code, "  %s( INTERNAL_FUNCTION_PARAM_PASSTHRU );\n", mset);
+      Printf(f->code, "  // need some error checking here?\n");
+      Printf(f->code, "  // Set the argument count to 0 for the get call\n");
+      Printf(f->code, "  ht = 0;\n");
+      Printf(f->code, "}\n");
+    }
+
+    Printf(f->code, "%s( INTERNAL_FUNCTION_PARAM_PASSTHRU );\n", mget);
+    Printf(f->code, "}\n");
+
+    Wrapper_print(f, s_wrappers);
+
+    Delete(class_iname);
+    Delete(mget);
+    Delete(mset);
+    DelWrapper(f);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+
+    wrapperType = staticmemberfn;
+    Language::staticmemberfunctionHandler(n);
+    wrapperType = standard;
+
+    if (shadow && php_version == 4) {
+      String *symname = Getattr(n, "sym:name");
+      char *realname = iname ? iname : name;
+      String *php_function_name = Swig_name_member(shadow_classname, realname);
+      create_command(symname, Swig_name_wrapper(php_function_name));
+    }
+
+    return SWIG_OK;
+  }
+
+  String * GetShadowReturnType(Node *n) {
+    SwigType *t = Getattr(n, "type");
+
+    /* Map type here */
+    switch (SwigType_type(t)) {
+      case T_CHAR:
+      case T_SCHAR:
+      case T_UCHAR:
+      case T_SHORT:
+      case T_USHORT:
+      case T_INT:
+      case T_UINT:
+      case T_LONG:
+      case T_ULONG:
+      case T_FLOAT:
+      case T_DOUBLE:
+      case T_BOOL:
+      case T_STRING:
+      case T_VOID:
+	break;
+      case T_POINTER:
+      case T_REFERENCE:
+      case T_USER:
+	if (is_shadow(t)) {
+	  return NewString(Char(is_shadow(t)));
+	}
+	break;
+      case T_ARRAY:
+	/* TODO */
+	break;
+      default:
+	Printf(stderr, "GetShadowReturnType: unhandled data type: %s\n", SwigType_str(t, 0));
+	break;
+    }
+
+    return NewStringEmpty();
+  }
+
+  String *PhpTypeFromTypemap(char *op, Node *n, String_or_char *lname) {
+    String *tms = Swig_typemap_lookup(op, n, lname, 0);
+    if (!tms)
+      return 0;
+    else
+      return NewStringf("%s", tms);
+  }
+
+  int abstractConstructorHandler(Node *n) {
+    String *iname = GetChar(n, "sym:name");
+    if (shadow && php_version == 4) {
+      Wrapper *f = NewWrapper();
+
+      String *wname = NewStringf("_wrap_new_%s", iname);
+      create_command(iname, wname);
+
+      Printf(f->def, "ZEND_NAMED_FUNCTION(_wrap_new_%s) {\n", iname);
+      Printf(f->def, "  zend_error(E_ERROR,\"Cannot create swig object type: %s as the underlying class is abstract\");\n", iname);
+      Printf(f->def, "}\n\n");
+      Wrapper_print(f, s_wrappers);
+      DelWrapper(f);
+      Delete(wname);
+    }
+    return SWIG_OK;
+  }
+  /* ------------------------------------------------------------
+   * constructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int constructorHandler(Node *n) {
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+
+    if (shadow && php_version == 4) {
+      if (iname && strcmp(iname, Char(shadow_classname)) == 0) {
+	native_constructor = NATIVE_CONSTRUCTOR;
+      } else {
+	native_constructor = ALTERNATIVE_CONSTRUCTOR;
+      }
+    } else {
+      native_constructor = 0;
+    }
+    constructors++;
+    wrapperType = constructor;
+    Language::constructorHandler(n);
+    wrapperType = standard;
+
+    if (shadow && php_version == 4) {
+      if (!Getattr(n, "sym:overloaded") || !Getattr(n, "sym:nextSibling")) {
+	char *realname = iname ? iname : name;
+	String *php_function_name = Swig_name_construct(realname);
+	create_command(realname, Swig_name_wrapper(php_function_name));
+      }
+    }
+
+    native_constructor = 0;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * CreateZendListDestructor()
+   * ------------------------------------------------------------ */
+  //virtual int destructorHandler(Node *n) {
+  //}
+  int CreateZendListDestructor(Node *n) {
+    String *name = GetChar(Swig_methodclass(n), "name");
+    String *iname = GetChar(n, "sym:name");
+    ParmList *l = Getattr(n, "parms");
+
+    String *destructorname = NewStringEmpty();
+    Printf(destructorname, "_%s", Swig_name_wrapper(iname));
+    Setattr(classnode, "destructor", destructorname);
+
+    Wrapper *f = NewWrapper();
+    Printf(f->def, "/* This function is designed to be called by the zend list destructors */\n");
+    Printf(f->def, "/* to typecast and do the actual destruction */\n");
+    Printf(f->def, "static void %s(zend_rsrc_list_entry *rsrc, const char *type_name TSRMLS_DC) {\n", destructorname);
+
+    Wrapper_add_localv(f, "value", "swig_object_wrapper *value=(swig_object_wrapper *) rsrc->ptr", NIL);
+    Wrapper_add_localv(f, "ptr", "void *ptr=value->ptr", NIL);
+    Wrapper_add_localv(f, "newobject", "int newobject=value->newobject", NIL);
+
+    emit_parameter_variables(l, f);
+    emit_attach_parmmaps(l, f);
+
+    // Get type of first arg, thing to be destructed
+    // Skip ignored arguments
+    Parm *p = l;
+    //while (Getattr(p,"tmap:ignore")) {p = Getattr(p,"tmap:ignore:next");}
+    while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    }
+    SwigType *pt = Getattr(p, "type");
+
+    Printf(f->code, "  efree(value);\n");
+    Printf(f->code, "  if (! newobject) return; /* can't delete it! */\n");
+    Printf(f->code, "  arg1 = (%s)SWIG_ZTS_ConvertResourceData(ptr,type_name,SWIGTYPE%s TSRMLS_CC);\n", SwigType_lstr(pt, 0), SwigType_manglestr(pt));
+    Printf(f->code, "  if (! arg1) zend_error(E_ERROR, \"%s resource already free'd\");\n", Char(name));
+
+    Setattr(n, "wrap:name", destructorname);
+
+    String *actioncode = emit_action(n);
+    Append(f->code, actioncode);
+    Delete(actioncode);
+
+    Printf(f->code, "}\n");
+
+    Wrapper_print(f, s_wrappers);
+
+    return SWIG_OK;
+
+  }
+
+  /* ------------------------------------------------------------
+   * memberconstantHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberconstantHandler(Node *n) {
+    wrapping_member_constant = Getattr(n, "name");
+    Language::memberconstantHandler(n);
+    wrapping_member_constant = NULL;
+    return SWIG_OK;
+  }
+
+};				/* class PHP */
+
+/* -----------------------------------------------------------------------------
+ * swig_php()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static PHP *maininstance = 0;
+
+// We use this function to be able to write out zend_register_list_destructor_ex
+// lines for most things in the type table
+// NOTE: it's a function NOT A PHP::METHOD
+extern "C" void typetrace(SwigType *ty, String *mangled, String *clientdata) {
+  Node *class_node;
+  if (!zend_types) {
+    zend_types = NewHash();
+  }
+  // we want to know if the type which reduced to this has a constructor
+  if ((class_node = maininstance->classLookup(ty))) {
+    if (!Getattr(zend_types, mangled)) {
+      // OK it may have been set before by a different SwigType but it would
+      // have had the same underlying class node I think
+      // - it is certainly required not to have different originating class
+      // nodes for the same SwigType
+      Setattr(zend_types, mangled, class_node);
+    }
+  } else {			// a non-class pointer
+    Setattr(zend_types, mangled, NOTCLASS);
+  }
+  if (r_prevtracefunc)
+    (*r_prevtracefunc) (ty, mangled, (String *) clientdata);
+}
+
+static Language *new_swig_php(int php_version) {
+  maininstance = new PHP(php_version);
+  if (!r_prevtracefunc) {
+    r_prevtracefunc = SwigType_remember_trace(typetrace);
+  } else {
+    Printf(stderr, "php Typetrace vector already saved!\n");
+    assert(0);
+  }
+  return maininstance;
+}
+extern "C" Language *swig_php4(void) {
+  return new_swig_php(4);
+}
+extern "C" Language *swig_php5(void) {
+  return new_swig_php(5);
+}
diff --git a/trunk/Source/Modules/pike.cxx b/trunk/Source/Modules/pike.cxx
new file mode 100644
index 0000000..30f9b3d
--- /dev/null
+++ b/trunk/Source/Modules/pike.cxx
@@ -0,0 +1,893 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pike.cxx
+ *
+ * Pike language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+/*
+ * Notes:
+ *
+ * - The current approach used for "out" typemaps is inconsistent with
+ *   how "out" typemaps are handled by other language modules. Instead
+ *   of converting the C/C++ type ($1) to a Pike object type (e.g. a
+ *   struct svalue), we're just calling the appropriate push_XXX
+ *   (e.g. push_int) to push the return value onto the stack.
+ *
+ * - Pike classes can't have static member functions or data, so we need
+ *   to find some other appropriate mapping for C++ static member functions
+ *   and data.
+ *
+ * - Pike doesn't seem to provide any default way to print the memory
+ *   address, etc. for extension objects. Should we do something here?
+ *
+ */
+
+char cvsroot_pike_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#include <ctype.h>		// for isalnum()
+
+static const char *usage = (char *) "\
+Pike Options (available with -pike)\n\
+     [None]\n\
+\n";
+
+class PIKE:public Language {
+private:
+
+  File *f_runtime;
+  File *f_header;
+  File *f_wrappers;
+  File *f_init;
+  File *f_classInit;
+
+  String *PrefixPlusUnderscore;
+  int current;
+
+  // Wrap modes
+  enum {
+    NO_CPP,
+    MEMBER_FUNC,
+    CONSTRUCTOR,
+    DESTRUCTOR,
+    MEMBER_VAR,
+    CLASS_CONST,
+    STATIC_FUNC,
+    STATIC_VAR
+  };
+
+public:
+
+  /* ---------------------------------------------------------------------
+   * PIKE()
+   *
+   * Initialize member data
+   * --------------------------------------------------------------------- */
+
+   PIKE() {
+    f_runtime = 0;
+    f_header = 0;
+    f_wrappers = 0;
+    f_init = 0;
+    f_classInit = 0;
+    PrefixPlusUnderscore = 0;
+    current = NO_CPP;
+  }
+
+  /* ---------------------------------------------------------------------
+   * main()
+   *
+   * Parse command line options and initializes variables.
+   * --------------------------------------------------------------------- */
+  
+   virtual void main(int argc, char *argv[]) {
+
+    /* Set location of SWIG library */
+    SWIG_library_directory("pike");
+
+    /* Look for certain command line options */
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stdout);
+	}
+      }
+    }
+
+    /* Add a symbol to the parser for conditional compilation */
+    Preprocessor_define("SWIGPIKE 1", 0);
+
+    /* Set language-specific configuration file */
+    SWIG_config_file("pike.swg");
+
+    /* Set typemap language */
+    SWIG_typemap_lang("pike");
+
+    /* Enable overloaded methods support */
+    allow_overloading();
+  }
+
+  /* ---------------------------------------------------------------------
+   * top()
+   * --------------------------------------------------------------------- */
+
+  virtual int top(Node *n) {
+    /* Get the module name */
+    String *module = Getattr(n, "name");
+
+    /* Get the output file name */
+    String *outfile = Getattr(n, "outfile");
+
+    /* Open the output file */
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_classInit = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("classInit", f_classInit);
+
+    /* Standard stuff for the SWIG runtime section */
+    Swig_banner(f_runtime);
+
+    Printf(f_header, "#define SWIG_init    pike_module_init\n");
+    Printf(f_header, "#define SWIG_name    \"%s\"\n\n", module);
+
+    /* Change naming scheme for constructors and destructors */
+    Swig_name_register("construct", "%c_create");
+    Swig_name_register("destroy", "%c_destroy");
+
+    /* Current wrap type */
+    current = NO_CPP;
+
+    /* Emit code for children */
+    Language::top(n);
+
+    /* Close the initialization function */
+    Printf(f_init, "}\n");
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Delete(f_classInit);
+
+    Close(f_runtime);
+    Delete(f_runtime);
+
+    /* Done */
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * validIdentifier()
+   * ------------------------------------------------------------ */
+
+  virtual int validIdentifier(String *s) {
+    char *c = Char(s);
+    const char *c0 = c;
+    const char *c1 = c0 + 1;
+    while (*c) {
+      if (*c == '`' && c == c0) {
+	c++;
+	continue;
+      }
+      if ((*c == '+' || *c == '-' || *c == '*' || *c == '/') && c == c1) {
+	c++;
+	continue;
+      }
+      if (!(isalnum(*c) || (*c == '_')))
+	return 0;
+      c++;
+    }
+    return 1;
+  }
+
+  /* ------------------------------------------------------------
+   * importDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int importDirective(Node *n) {
+    String *modname = Getattr(n, "module");
+    if (modname) {
+      Printf(f_init, "pike_require(\"%s\");\n", modname);
+    }
+    return Language::importDirective(n);
+  }
+
+  /* ------------------------------------------------------------
+   * strip()
+   *
+   * For names that begin with the current class prefix plus an
+   * underscore (e.g. "Foo_enum_test"), return the base function
+   * name (i.e. "enum_test").
+   * ------------------------------------------------------------ */
+
+  String *strip(const DOHString_or_char *name) {
+    String *s = Copy(name);
+    if (Strncmp(name, PrefixPlusUnderscore, Len(PrefixPlusUnderscore)) != 0) {
+      return s;
+    }
+    Replaceall(s, PrefixPlusUnderscore, "");
+    return s;
+  }
+
+  /* ------------------------------------------------------------
+   * add_method()
+   * ------------------------------------------------------------ */
+
+  void add_method(const DOHString_or_char *name, const DOHString_or_char *function, const DOHString_or_char *description) {
+    String *rename = NULL;
+    switch (current) {
+    case NO_CPP:
+      rename = NewString(name);
+      Printf(f_init, "ADD_FUNCTION(\"%s\", %s, tFunc(%s), 0);\n", rename, function, description);
+      break;
+    case STATIC_FUNC:
+    case STATIC_VAR:
+      rename = NewString(name);
+      Printf(f_init, "ADD_FUNCTION(\"%s\", %s, tFunc(%s), 0);\n", rename, function, description);
+      break;
+    case CONSTRUCTOR:
+    case DESTRUCTOR:
+    case MEMBER_FUNC:
+    case MEMBER_VAR:
+      rename = strip(name);
+      Printf(f_classInit, "ADD_FUNCTION(\"%s\", %s, tFunc(%s), 0);\n", rename, function, description);
+      break;
+    case CLASS_CONST:
+      assert(false);		// shouldn't have gotten here for CLASS_CONST nodes
+    default:
+      assert(false);		// what is this?
+    }
+    Delete(rename);
+  }
+
+  /* ---------------------------------------------------------------------
+   * functionWrapper()
+   *
+   * Create a function declaration and register it with the interpreter.
+   * --------------------------------------------------------------------- */
+
+  virtual int functionWrapper(Node *n) {
+
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+
+    Parm *p;
+    String *tm;
+    int i;
+
+    String *overname = 0;
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n))
+	return SWIG_ERROR;
+    }
+
+    Wrapper *f = NewWrapper();
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+
+    /* Get number of required and total arguments */
+    int num_arguments = emit_num_arguments(l);
+    int varargs = emit_isvarargs(l);
+
+    /* Which input argument to start with? */
+    int start = (current == MEMBER_FUNC || current == MEMBER_VAR || current == DESTRUCTOR) ? 1 : 0;
+
+    /* Offset to skip over the attribute name */
+    // int offset = (current == MEMBER_VAR) ? 1 : 0;
+    int offset = 0;
+
+    String *wname = Swig_name_wrapper(iname);
+    if (overname) {
+      Append(wname, overname);
+    }
+    Setattr(n, "wrap:name", wname);
+
+    Printv(f->def, "static void ", wname, "(INT32 args) {", NIL);
+
+    /* Generate code for argument marshalling */
+    String *description = NewString("");
+    char source[64];
+    for (i = 0, p = l; i < num_arguments; i++) {
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+
+      if (i < start) {
+	String *lstr = SwigType_lstr(pt, 0);
+	Printf(f->code, "%s = (%s) THIS;\n", ln, lstr);
+	Delete(lstr);
+      } else {
+	/* Look for an input typemap */
+	sprintf(source, "Pike_sp[%d-args]", i - start + offset);
+	if ((tm = Getattr(p, "tmap:in"))) {
+	  Replaceall(tm, "$source", source);
+	  Replaceall(tm, "$target", ln);
+	  Replaceall(tm, "$input", source);
+	  Setattr(p, "emit:input", source);
+	  Printf(f->code, "%s\n", tm);
+	  String *pikedesc = Getattr(p, "tmap:in:pikedesc");
+	  if (pikedesc) {
+	    Printv(description, pikedesc, " ", NIL);
+	  }
+	  p = Getattr(p, "tmap:in:next");
+	  continue;
+	} else {
+	  Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+	  break;
+	}
+      }
+      p = nextSibling(p);
+    }
+
+    /* Check for trailing varargs */
+    if (varargs) {
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$input", "varargs");
+	Printv(f->code, tm, "\n", NIL);
+      }
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    String *cleanup = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Printv(cleanup, tm, "\n", NIL);
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    String *outarg = NewString("");
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$target", "resultobj");
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Emit the function call */
+    String *actioncode = emit_action(n);
+
+    /* Clear the return stack */
+    Printf(actioncode, "pop_n_elems(args);\n");
+
+    /* Return the function value */
+    if (current == CONSTRUCTOR) {
+      Printv(actioncode, "THIS = (void *) result;\n", NIL);
+      Printv(description, ", tVoid", NIL);
+    } else if (current == DESTRUCTOR) {
+      Printv(description, ", tVoid", NIL);
+    } else {
+      Printv(description, ", ", NIL);
+      if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+        actioncode = 0;
+	Replaceall(tm, "$source", "result");
+	Replaceall(tm, "$target", "resultobj");
+	Replaceall(tm, "$result", "resultobj");
+	if (GetFlag(n, "feature:new")) {
+	  Replaceall(tm, "$owner", "1");
+	} else {
+	  Replaceall(tm, "$owner", "0");
+	}
+	String *pikedesc = Getattr(n, "tmap:out:pikedesc");
+	if (pikedesc) {
+	  Printv(description, pikedesc, NIL);
+	}
+	Printf(f->code, "%s\n", tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
+      }
+    }
+    if (actioncode) {
+      Append(f->code, actioncode);
+      Delete(actioncode);
+    }
+    emit_return_variable(n, d, f);
+
+    /* Output argument output code */
+    Printv(f->code, outarg, NIL);
+
+    /* Output cleanup code */
+    Printv(f->code, cleanup, NIL);
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printf(f->code, "%s\n", tm);
+    }
+
+    /* Close the function */
+    Printf(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", iname);
+    Replaceall(f->code, "$result", "resultobj");
+
+    /* Dump the function out */
+    Wrapper_print(f, f_wrappers);
+
+    /* Now register the function with the interpreter. */
+    if (!Getattr(n, "sym:overloaded")) {
+      add_method(iname, wname, description);
+    } else {
+      if (!Getattr(n, "sym:nextSibling")) {
+	dispatchFunction(n);
+      }
+    }
+
+    Delete(cleanup);
+    Delete(outarg);
+    Delete(description);
+    Delete(wname);
+    DelWrapper(f);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * dispatchFunction()
+   *
+   * Emit overloading dispatch function
+   * ------------------------------------------------------------ */
+
+  void dispatchFunction(Node *n) {
+    /* Last node in overloaded chain */
+
+    int maxargs;
+    String *tmp = NewString("");
+    String *dispatch = Swig_overload_dispatch(n, "%s(args); return;", &maxargs);
+
+    /* Generate a dispatch wrapper for all overloaded functions */
+
+    Wrapper *f = NewWrapper();
+    String *symname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(symname);
+
+    Printf(f->def, "static void %s(INT32 args) {", wname);
+
+    Wrapper_add_local(f, "argc", "INT32 argc");
+    Printf(tmp, "struct svalue argv[%d]", maxargs);
+    Wrapper_add_local(f, "argv", tmp);
+    Wrapper_add_local(f, "ii", "INT32 ii");
+
+    Printf(f->code, "argc = args;\n");
+    Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++) {\n", maxargs);
+    Printf(f->code, "argv[ii] = Pike_sp[ii-args];\n");
+    Printf(f->code, "}\n");
+
+    Replaceall(dispatch, "$args", "self, args");
+    Printv(f->code, dispatch, "\n", NIL);
+    Printf(f->code, "Pike_error(\"No matching function for overloaded '%s'.\");\n", symname);
+    Printv(f->code, "}\n", NIL);
+
+    Wrapper_print(f, f_wrappers);
+
+    String *description = NewString("");
+    Printf(description, "tAny,");
+    if (current == CONSTRUCTOR || current == DESTRUCTOR) {
+      Printf(description, " tVoid");
+    } else {
+      String *pd = Getattr(n, "tmap:out:pikedesc");
+      if (pd)
+	Printf(description, " %s", pd);
+    }
+    add_method(symname, wname, description);
+    Delete(description);
+
+    DelWrapper(f);
+    Delete(dispatch);
+    Delete(tmp);
+    Delete(wname);
+  }
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+    return Language::variableWrapper(n);
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+
+    Swig_require("constantWrapper", n, "*sym:name", "type", "value", NIL);
+
+    String *symname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *value = Getattr(n, "value");
+
+    /* Special hook for member pointer */
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(symname);
+      Printf(f_header, "static %s = %s;\n", SwigType_str(type, wname), value);
+      value = wname;
+    }
+
+    /* Perform constant typemap substitution */
+    String *tm = Swig_typemap_lookup("constant", n, value, 0);
+    if (tm) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", symname);
+      Replaceall(tm, "$symname", symname);
+      Replaceall(tm, "$value", value);
+      Printf(f_init, "%s\n", tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value %s = %s\n", SwigType_str(type, 0), value);
+    }
+
+    Swig_restore(n);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------ 
+   * nativeWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int nativeWrapper(Node *n) {
+    //   return Language::nativeWrapper(n);
+    String *name = Getattr(n, "sym:name");
+    String *wrapname = Getattr(n, "wrap:name");
+
+    if (!addSymbol(wrapname, n))
+      return SWIG_ERROR;
+
+    add_method(name, wrapname, 0);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * enumDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumDeclaration(Node *n) {
+    return Language::enumDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * enumvalueDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumvalueDeclaration(Node *n) {
+    return Language::enumvalueDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int classDeclaration(Node *n) {
+    return Language::classDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int classHandler(Node *n) {
+
+    String *symname = Getattr(n, "sym:name");
+    if (!addSymbol(symname, n))
+      return SWIG_ERROR;
+
+    PrefixPlusUnderscore = NewStringf("%s_", getClassPrefix());
+
+    Printf(f_classInit, "start_new_program();\n");
+
+    /* Handle inheritance */
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist) > 0) {
+      Iterator base = First(baselist);
+      while (base.item) {
+	String *basename = Getattr(base.item, "name");
+	SwigType *basetype = NewString(basename);
+	SwigType_add_pointer(basetype);
+	SwigType_remember(basetype);
+	String *basemangle = SwigType_manglestr(basetype);
+	Printf(f_classInit, "low_inherit((struct program *) SWIGTYPE%s->clientdata, 0, 0, 0, 0, 0);\n", basemangle);
+	Delete(basemangle);
+	Delete(basetype);
+	base = Next(base);
+      }
+    } else {
+      Printf(f_classInit, "ADD_STORAGE(swig_object_wrapper);\n");
+    }
+
+    Language::classHandler(n);
+
+    /* Accessors for member variables */
+    /*
+       List *membervariables = Getattr(n,"membervariables");
+       if (membervariables && Len(membervariables) > 0) {
+       membervariableAccessors(membervariables);
+       }
+     */
+
+    /* Done, close the class and dump its definition to the init function */
+    Printf(f_classInit, "add_program_constant(\"%s\", pr = end_program(), 0);\n", symname);
+    Dump(f_classInit, f_init);
+    Clear(f_classInit);
+
+    SwigType *tt = NewString(symname);
+    SwigType_add_pointer(tt);
+    SwigType_remember(tt);
+    String *tm = SwigType_manglestr(tt);
+    Printf(f_init, "SWIG_TypeClientData(SWIGTYPE%s, (void *) pr);\n", tm);
+    Delete(tm);
+    Delete(tt);
+
+    Delete(PrefixPlusUnderscore);
+    PrefixPlusUnderscore = 0;
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   *
+   * Method for adding C++ member function
+   * ------------------------------------------------------------ */
+
+  virtual int memberfunctionHandler(Node *n) {
+    current = MEMBER_FUNC;
+    Language::memberfunctionHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constructorHandler()
+   *
+   * Method for adding C++ member constructor
+   * ------------------------------------------------------------ */
+
+  virtual int constructorHandler(Node *n) {
+    current = CONSTRUCTOR;
+    Language::constructorHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * destructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int destructorHandler(Node *n) {
+    current = DESTRUCTOR;
+    Language::destructorHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableAccessors()
+   * ------------------------------------------------------------ */
+
+  void membervariableAccessors(List *membervariables) {
+    String *name;
+    Iterator i;
+    bool need_setter;
+    String *funcname;
+
+    /* If at least one of them is mutable, we need a setter */
+    need_setter = false;
+    i = First(membervariables);
+    while (i.item) {
+      if (!GetFlag(i.item, "feature:immutable")) {
+	need_setter = true;
+	break;
+      }
+      i = Next(i);
+    }
+
+    /* Create a function to set the values of the (mutable) variables */
+    if (need_setter) {
+      Wrapper *wrapper = NewWrapper();
+      String *setter = Swig_name_member(getClassPrefix(), (char *) "`->=");
+      String *wname = Swig_name_wrapper(setter);
+      Printv(wrapper->def, "static void ", wname, "(INT32 args) {", NIL);
+      Printf(wrapper->locals, "char *name = (char *) STR0(Pike_sp[0-args].u.string);\n");
+
+      i = First(membervariables);
+      while (i.item) {
+	if (!GetFlag(i.item, "feature:immutable")) {
+	  name = Getattr(i.item, "name");
+	  funcname = Swig_name_wrapper(Swig_name_set(Swig_name_member(getClassPrefix(), name)));
+	  Printf(wrapper->code, "if (!strcmp(name, \"%s\")) {\n", name);
+	  Printf(wrapper->code, "%s(args);\n", funcname);
+	  Printf(wrapper->code, "return;\n");
+	  Printf(wrapper->code, "}\n");
+	  Delete(funcname);
+	}
+	i = Next(i);
+      }
+
+      /* Close the function */
+      Printf(wrapper->code, "pop_n_elems(args);\n");
+      Printf(wrapper->code, "}\n");
+
+      /* Dump wrapper code to the output file */
+      Wrapper_print(wrapper, f_wrappers);
+
+      /* Register it with Pike */
+      String *description = NewString("tStr tFloat, tVoid");
+      add_method("`->=", wname, description);
+      Delete(description);
+
+      /* Clean up */
+      Delete(wname);
+      Delete(setter);
+      DelWrapper(wrapper);
+    }
+
+    /* Create a function to get the values of the (mutable) variables */
+    Wrapper *wrapper = NewWrapper();
+    String *getter = Swig_name_member(getClassPrefix(), (char *) "`->");
+    String *wname = Swig_name_wrapper(getter);
+    Printv(wrapper->def, "static void ", wname, "(INT32 args) {", NIL);
+    Printf(wrapper->locals, "char *name = (char *) STR0(Pike_sp[0-args].u.string);\n");
+
+    i = First(membervariables);
+    while (i.item) {
+      name = Getattr(i.item, "name");
+      funcname = Swig_name_wrapper(Swig_name_get(Swig_name_member(getClassPrefix(), name)));
+      Printf(wrapper->code, "if (!strcmp(name, \"%s\")) {\n", name);
+      Printf(wrapper->code, "%s(args);\n", funcname);
+      Printf(wrapper->code, "return;\n");
+      Printf(wrapper->code, "}\n");
+      Delete(funcname);
+      i = Next(i);
+    }
+
+    /* Close the function */
+    Printf(wrapper->code, "pop_n_elems(args);\n");
+    Printf(wrapper->code, "}\n");
+
+    /* Dump wrapper code to the output file */
+    Wrapper_print(wrapper, f_wrappers);
+
+    /* Register it with Pike */
+    String *description = NewString("tStr, tMix");
+    add_method("`->", wname, description);
+    Delete(description);
+
+    /* Clean up */
+    Delete(wname);
+    Delete(getter);
+    DelWrapper(wrapper);
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int membervariableHandler(Node *n) {
+    List *membervariables = Getattr(getCurrentClass(), "membervariables");
+    if (!membervariables) {
+      membervariables = NewList();
+      Setattr(getCurrentClass(), "membervariables", membervariables);
+    }
+    Append(membervariables, n);
+    current = MEMBER_VAR;
+    Language::membervariableHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   *
+   * Wrap a static C++ function
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    current = STATIC_FUNC;
+    Language::staticmemberfunctionHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberconstantHandler()
+   *
+   * Create a C++ constant
+   * ------------------------------------------------------------ */
+
+  virtual int memberconstantHandler(Node *n) {
+    current = CLASS_CONST;
+    constantWrapper(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ---------------------------------------------------------------------
+   * staticmembervariableHandler()
+   * --------------------------------------------------------------------- */
+
+  virtual int staticmembervariableHandler(Node *n) {
+    current = STATIC_VAR;
+    Language::staticmembervariableHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+};
+
+/* -----------------------------------------------------------------------------
+ * swig_pike()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_pike() {
+  return new PIKE();
+}
+extern "C" Language *swig_pike(void) {
+  return new_swig_pike();
+}
diff --git a/trunk/Source/Modules/python.cxx b/trunk/Source/Modules/python.cxx
new file mode 100644
index 0000000..f0e335c
--- /dev/null
+++ b/trunk/Source/Modules/python.cxx
@@ -0,0 +1,3770 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * python.cxx
+ *
+ * Python language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_python_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#define ctab2  " "
+#define ctab4  "  "
+#define ctab8  "    "
+
+#include "cparse.h"
+static int treduce = SWIG_cparse_template_reduce(0);
+
+#include <ctype.h>
+
+#define PYSHADOW_MEMBER  0x2
+
+static String *const_code = 0;
+static String *module = 0;
+static String *package = 0;
+static String *mainmodule = 0;
+static String *interface = 0;
+static String *global_name = 0;
+static int shadow = 1;
+static int use_kw = 0;
+static int director_method_index = 0;
+
+static File *f_runtime = 0;
+static File *f_runtime_h = 0;
+static File *f_header = 0;
+static File *f_wrappers = 0;
+static File *f_directors = 0;
+static File *f_directors_h = 0;
+static File *f_init = 0;
+static File *f_shadow_py = 0;
+static String *f_shadow = 0;
+static String *f_shadow_imports = 0;
+static String *f_shadow_stubs = 0;
+
+static String *methods;
+static String *class_name;
+static String *shadow_indent = 0;
+static int in_class = 0;
+static int classic = 0;
+static int modern = 0;
+static int apply = 0;
+static int new_repr = 1;
+static int no_header_file = 0;
+
+/* C++ Support + Shadow Classes */
+
+static int have_constructor;
+static int have_repr;
+static String *real_classname;
+
+/* Thread Support */
+static int threads = 0;
+static int nothreads = 0;
+static int classptr = 0;
+/* Other options */
+static int shadowimport = 1;
+static int buildnone = 0;
+static int nobuildnone = 0;
+static int safecstrings = 0;
+static int dirvtable = 0;
+static int proxydel = 1;
+static int fastunpack = 0;
+static int fastproxy = 0;
+static int fastquery = 0;
+static int fastinit = 0;
+static int olddefs = 0;
+static int modernargs = 0;
+static int aliasobj0 = 0;
+static int castmode = 0;
+static int extranative = 0;
+static int outputtuple = 0;
+static int nortti = 0;
+
+/* flags for the make_autodoc function */
+enum autodoc_t {
+  AUTODOC_CLASS,
+  AUTODOC_CTOR,
+  AUTODOC_DTOR,
+  AUTODOC_STATICFUNC,
+  AUTODOC_FUNC,
+  AUTODOC_METHOD
+};
+
+
+static const char *usage1 = (char *) "\
+Python Options (available with -python)\n\
+     -aliasobj0      - Alias obj0 when using fastunpack, needed for some old typemaps \n\
+     -apply          - Use apply() in proxy classes\n\
+     -buildnone      - Use Py_BuildValue(" ") to obtain Py_None (default in Windows)\n\
+     -castmode       - Enable the casting mode, which allows implicit cast between types in python\n\
+     -classic        - Use classic classes only\n\
+     -classptr       - Generate shadow 'ClassPtr' as in older swig versions\n\
+     -cppcast        - Enable C++ casting operators (default) \n\
+     -dirvtable      - Generate a pseudo virtual table for directors for faster dispatch \n\
+     -extranative    - Return extra native C++ wraps for std containers when possible \n\
+     -fastinit       - Use fast init mechanism for classes (default)\n\
+     -fastunpack     - Use fast unpack mechanism to parse the argument functions \n\
+     -fastproxy      - Use fast proxy mechanism for member methods \n\
+     -fastquery      - Use fast query mechanism for types \n\
+     -globals <name> - Set <name> used to access C global variable [default: 'cvar']\n\
+     -interface <lib>- Set the lib name to <lib>\n\
+     -keyword        - Use keyword arguments\n\
+     -modern         - Use modern python features only, without compatibility code\n\
+     -modernargs     - Use \"modern\" args mechanism to pack/unpack the function arguments\n";
+static const char *usage2 = (char *) "\
+     -newrepr        - Use more informative version of __repr__ in proxy classes (default) \n\
+     -newvwm         - New value wrapper mode, use only when everything else fails \n\
+     -noaliasobj0    - Don't generate an obj0 alias when using fastunpack (default) \n\
+     -nobuildnone    - Access Py_None directly (default in non-Windows systems)\n\
+     -nocastmode     - Disable the casting mode (default)\n\
+     -nocppcast      - Disable C++ casting operators, useful for generating bugs\n\
+     -nodirvtable    - Don't use the virtual table feature, resolve the python method each time (default)\n\
+     -noexcept       - No automatic exception handling\n\
+     -noextranative  - Don't use extra native C++ wraps for std containers when possible (default) \n\
+     -nofastinit     - Use traditional init mechanism for classes \n\
+     -nofastunpack   - Use traditional UnpackTuple method to parse the argument functions (default) \n\
+     -nofastproxy    - Use traditional proxy mechanism for member methods (default) \n\
+     -nofastquery    - Use traditional query mechanism for types (default) \n\
+     -noh            - Don't generate the output header file\n\
+     -nomodern       - Don't use modern python features which are not back compatible \n\
+     -nomodernargs   - Use classic ParseTuple/CallFunction methods to pack/unpack the function arguments (default) \n";
+static const char *usage3 = (char *) "\
+     -noolddefs      - Don't emit the old method definitions even when using fastproxy (default) \n\
+     -nooutputtuple  - Use a PyList for appending output values (default) \n\
+     -noproxy        - Don't generate proxy classes \n\
+     -noproxydel     - Don't generate the redundant __del__ method \n\
+     -noproxyimport  - Don't insert proxy import statements derived from the %import directive \n\
+     -nortti         - Disable the use of the native C++ RTTI with directors\n\
+     -nosafecstrings - Avoid extra strings copies when possible (default)\n\
+     -nothreads      - Disable thread support for the entire interface\n\
+     -olddefs        - Keep the old method definitions even when using fastproxy\n\
+     -oldrepr        - Use shorter and old version of __repr__ in proxy classes\n\
+     -outputtuple    - Use a PyTuple for outputs instead of a PyList (use carefully with legacy interfaces) \n\
+     -proxydel       - Generate a __del__ method even though it is now redundant (default) \n\
+     -safecstrings   - Use safer (but slower) C string mapping, generating copies from Python -> C/C++\n\
+     -threads        - Add thread support for all the interface\n\
+     -O              - Enable all the optimization options: \n\
+                         -modern -fastdispatch -dirvtable -nosafecstrings -fvirtual -noproxydel \n\
+                         -fastproxy -fastinit -fastunpack -fastquery -modernargs -nobuildnone \n\
+\n";
+
+class PYTHON:public Language {
+public:
+  PYTHON() {
+    /* Add code to manage protected constructors and directors */
+    director_prot_ctor_code = NewString("");
+    Printv(director_prot_ctor_code,
+	   "if ( $comparison ) { /* subclassed */\n",
+	   "  $director_new \n",
+	   "} else {\n", "  SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing abstract class or protected constructor\"); \n", "  SWIG_fail;\n", "}\n", NIL);
+    director_multiple_inheritance = 1;
+    director_language = 1;
+  }
+
+  /* ------------------------------------------------------------
+   * Thread Implementation
+   * ------------------------------------------------------------ */
+ 
+  int threads_enable(Node *n) const {
+    return threads && !GetFlagAttr(n, "feature:nothread");
+  }
+ 
+  int initialize_threads(String *f_init) {
+    if (!threads) {
+      return SWIG_OK;
+    }
+    Printf(f_init, "\n");
+    Printf(f_init, "/* Initialize threading */\n");
+    Printf(f_init, "SWIG_PYTHON_INITIALIZE_THREADS;\n");
+
+    return SWIG_OK;
+  }
+
+  virtual void thread_begin_block(Node *n, String *f) {
+    if (!GetFlag(n, "feature:nothreadblock")) {
+      String *bb = Getattr(n, "feature:threadbeginblock");
+      if (bb) {
+	Append(f, bb);
+      } else {
+	Append(f, "SWIG_PYTHON_THREAD_BEGIN_BLOCK;\n");
+      }
+    }
+  }
+
+  virtual void thread_end_block(Node *n, String *f) {
+    if (!GetFlag(n, "feature:nothreadblock")) {
+      String *eb = Getattr(n, "feature:threadendblock");
+      if (eb) {
+	Append(f, eb);
+      } else {
+	Append(f, "SWIG_PYTHON_THREAD_END_BLOCK;\n");
+      }
+    }
+  }
+
+  virtual void thread_begin_allow(Node *n, String *f) {
+    if (!GetFlag(n, "feature:nothreadallow")) {
+      String *bb = Getattr(n, "feature:threadbeginallow");
+      if (bb) {
+	Append(f, bb);
+      } else {
+	Append(f, "SWIG_PYTHON_THREAD_BEGIN_ALLOW;\n");
+      }
+    }
+  }
+
+  virtual void thread_end_allow(Node *n, String *f) {
+    if (!GetFlag(n, "feature:nothreadallow")) {
+      String *eb = Getattr(n, "feature:threadendallow");
+      if (eb) {
+	Append(f, eb);
+      } else {
+	Append(f, "SWIG_PYTHON_THREAD_END_ALLOW;\n");
+      }
+    }
+  }
+
+  /* ------------------------------------------------------------
+   * main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+    int cppcast = 1;
+
+    SWIG_library_directory("python");
+
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-interface") == 0) {
+	  if (argv[i + 1]) {
+	    interface = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	  /* end added */
+	} else if (strcmp(argv[i], "-globals") == 0) {
+	  if (argv[i + 1]) {
+	    global_name = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) {
+	  shadow = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-apply") == 0) {
+	  apply = 1;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-new_repr") == 0) || (strcmp(argv[i], "-newrepr") == 0)) {
+	  new_repr = 1;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-old_repr") == 0) || (strcmp(argv[i], "-oldrepr") == 0)) {
+	  new_repr = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-classptr") == 0) {
+	  classptr = 1;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-noproxy") == 0)) {
+	  shadow = 0;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-noproxyimport") == 0)) {
+	  shadowimport = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-keyword") == 0) {
+	  use_kw = 1;
+	  SWIG_cparse_set_compact_default_args(1);
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-classic") == 0) {
+	  classic = 1;
+	  modernargs = 0;
+	  apply = 1;
+	  modern = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-cppcast") == 0) {
+	  cppcast = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nocppcast") == 0) {
+	  cppcast = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-outputtuple") == 0) {
+	  outputtuple = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nooutputtuple") == 0) {
+	  outputtuple = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nortti") == 0) {
+	  nortti = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-threads") == 0) {
+	  threads = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nothreads") == 0) {
+	  /* Turn off thread suppor mode */
+	  nothreads = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-safecstrings") == 0) {
+	  safecstrings = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nosafecstrings") == 0) {
+	  safecstrings = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-buildnone") == 0) {
+	  buildnone = 1;
+	  nobuildnone = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nobuildnone") == 0) {
+	  buildnone = 0;
+	  nobuildnone = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-dirvtable") == 0) {
+	  dirvtable = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nodirvtable") == 0) {
+	  dirvtable = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-fastunpack") == 0) {
+	  fastunpack = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nofastunpack") == 0) {
+	  fastunpack = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-fastproxy") == 0) {
+	  fastproxy = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nofastproxy") == 0) {
+	  fastproxy = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-fastquery") == 0) {
+	  fastquery = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nofastquery") == 0) {
+	  fastquery = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-fastinit") == 0) {
+	  fastinit = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nofastinit") == 0) {
+	  fastinit = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-olddefs") == 0) {
+	  olddefs = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noolddefs") == 0) {
+	  olddefs = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-castmode") == 0) {
+	  castmode = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nocastmode") == 0) {
+	  castmode = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-extranative") == 0) {
+	  extranative = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noextranative") == 0) {
+	  extranative = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-modernargs") == 0) {
+	  modernargs = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nomodernargs") == 0) {
+	  modernargs = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-aliasobj0") == 0) {
+	  aliasobj0 = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noaliasobj0") == 0) {
+	  aliasobj0 = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-proxydel") == 0) {
+	  proxydel = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noproxydel") == 0) {
+	  proxydel = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-modern") == 0) {
+	  apply = 0;
+	  classic = 0;
+	  modern = 1;
+	  modernargs = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nomodern") == 0) {
+	  modern = 0;
+	  modernargs = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noh") == 0) {
+	  no_header_file = 1;
+	  Swig_mark_arg(i);
+	} else if ((strcmp(argv[i], "-new_vwm") == 0) || (strcmp(argv[i], "-newvwm") == 0)) {
+	  /* Turn on new value wrapper mpde */
+	  Swig_value_wrapper_mode(1);
+	  no_header_file = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-O") == 0) {
+	  apply = 0;
+	  classic = 0;
+	  modern = 1;
+	  dirvtable = 1;
+	  safecstrings = 0;
+	  buildnone = 0;
+	  nobuildnone = 1;
+	  classptr = 0;
+	  proxydel = 0;
+	  fastunpack = 1;
+	  fastproxy = 1;
+	  fastinit = 1;
+	  fastquery = 1;
+	  modernargs = 1;
+	  Wrapper_fast_dispatch_mode_set(1);
+	  Wrapper_virtual_elimination_mode_set(1);
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage1, stdout);
+	  fputs(usage2, stdout);
+	  fputs(usage3, stdout);
+	}
+      }
+    }
+
+    if (cppcast) {
+      Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
+    }
+
+    if (!global_name)
+      global_name = NewString("cvar");
+    Preprocessor_define("SWIGPYTHON 1", 0);
+    SWIG_typemap_lang("python");
+    SWIG_config_file("python.swg");
+    allow_overloading();
+  }
+
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+    /* check if directors are enabled for this module.  note: this 
+     * is a "master" switch, without which no director code will be
+     * emitted.  %feature("director") statements are also required
+     * to enable directors for individual classes or methods.
+     *
+     * use %module(directors="1") modulename at the start of the 
+     * interface file to enable director generation.
+     */
+    String *mod_docstring = NULL;
+    {
+      Node *mod = Getattr(n, "module");
+      if (mod) {
+	Node *options = Getattr(mod, "options");
+	if (options) {
+	  int dirprot = 0;
+	  if (Getattr(options, "dirprot")) {
+	    dirprot = 1;
+	  }
+	  if (Getattr(options, "nodirprot")) {
+	    dirprot = 0;
+	  }
+	  if (Getattr(options, "directors")) {
+	    allow_directors();
+	    if (dirprot)
+	      allow_dirprot();
+	  }
+	  if (Getattr(options, "threads")) {
+	    threads = 1;
+	  }
+	  if (Getattr(options, "castmode")) {
+	    castmode = 1;
+	  }
+	  if (Getattr(options, "nocastmode")) {
+	    castmode = 0;
+	  }
+	  if (Getattr(options, "extranative")) {
+	    extranative = 1;
+	  }
+	  if (Getattr(options, "noextranative")) {
+	    extranative = 0;
+	  }
+	  if (Getattr(options, "outputtuple")) {
+	    outputtuple = 1;
+	  }
+	  if (Getattr(options, "nooutputtuple")) {
+	    outputtuple = 0;
+	  }
+	  mod_docstring = Getattr(options, "docstring");
+	  package = Getattr(options, "package");
+	}
+      }
+    }
+
+    /* Set comparison with none for ConstructorToFunction */
+    setSubclassInstanceCheck(NewString("$arg != Py_None"));
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+    String *outfile_h = !no_header_file ? Getattr(n, "outfile_h") : 0;
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    if (directorsEnabled()) {
+      if (!no_header_file) {
+	f_runtime_h = NewFile(outfile_h, "w");
+	if (!f_runtime_h) {
+	  FileErrorDisplay(outfile_h);
+	  SWIG_exit(EXIT_FAILURE);
+	}
+      } else {
+	f_runtime_h = f_runtime;
+      }
+    }
+
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+    f_directors_h = NewString("");
+    f_directors = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("director", f_directors);
+    Swig_register_filebyname("director_h", f_directors_h);
+
+    const_code = NewString("");
+    methods = NewString("");
+
+    Swig_banner(f_runtime);
+
+    Printf(f_runtime, "#define SWIGPYTHON\n");
+
+    if (directorsEnabled()) {
+      Printf(f_runtime, "#define SWIG_DIRECTORS\n");
+    }
+
+    if (nothreads) {
+      Printf(f_runtime, "#define SWIG_PYTHON_NO_THREADS\n");
+    } else if (threads) {
+      Printf(f_runtime, "#define SWIG_PYTHON_THREADS\n");
+    }
+
+    if (safecstrings) {
+      Printf(f_runtime, "#define SWIG_PYTHON_SAFE_CSTRINGS\n");
+    }
+
+    if (buildnone) {
+      Printf(f_runtime, "#define SWIG_PYTHON_BUILD_NONE\n");
+    }
+
+    if (nobuildnone) {
+      Printf(f_runtime, "#define SWIG_PYTHON_NO_BUILD_NONE\n");
+    }
+
+    if (!dirvtable) {
+      Printf(f_runtime, "#define SWIG_PYTHON_DIRECTOR_NO_VTABLE\n");
+    }
+
+    if (outputtuple) {
+      Printf(f_runtime, "#define SWIG_PYTHON_OUTPUT_TUPLE\n");
+    }
+
+    if (nortti) {
+      Printf(f_runtime, "#ifndef SWIG_DIRECTOR_NORTTI\n");
+      Printf(f_runtime, "#define SWIG_DIRECTOR_NORTTI\n");
+      Printf(f_runtime, "#endif\n");
+    }
+
+    if (castmode) {
+      Printf(f_runtime, "#define SWIG_CASTRANK_MODE\n");
+      Printf(f_runtime, "#define SWIG_PYTHON_CAST_MODE\n");
+    }
+
+    if (extranative) {
+      Printf(f_runtime, "#define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS\n");
+    }
+
+    if (classic) {
+      Printf(f_runtime, "#define SWIG_PYTHON_CLASSIC\n");
+    }
+
+    Printf(f_header, "#if (PY_VERSION_HEX <= 0x02000000)\n");
+    Printf(f_header, "# if !defined(SWIG_PYTHON_CLASSIC)\n");
+    Printf(f_header, "#  error \"This python version requires swig to be run with the '-classic' option\"\n");
+    Printf(f_header, "# endif\n");
+    Printf(f_header, "#endif\n");
+
+    if (modern) {
+      Printf(f_header, "#if (PY_VERSION_HEX <= 0x02020000)\n");
+      Printf(f_header, "# error \"This python version requires swig to be run with the '-nomodern' option\"\n");
+      Printf(f_header, "#endif\n");
+    }
+
+    if (modernargs) {
+      Printf(f_header, "#if (PY_VERSION_HEX <= 0x02020000)\n");
+      Printf(f_header, "# error \"This python version requires swig to be run with the '-nomodernargs' option\"\n");
+      Printf(f_header, "#endif\n");
+    }
+
+    if (fastunpack) {
+      Printf(f_header, "#ifndef METH_O\n");
+      Printf(f_header, "# error \"This python version requires swig to be run with the '-nofastunpack' option\"\n");
+      Printf(f_header, "#endif\n");
+    }
+
+    if (fastquery) {
+      Printf(f_header, "#ifdef SWIG_TypeQuery\n");
+      Printf(f_header, "# undef SWIG_TypeQuery\n");
+      Printf(f_header, "#endif\n");
+      Printf(f_header, "#define SWIG_TypeQuery SWIG_Python_TypeQuery\n");
+    }
+
+
+    /* Set module name */
+    module = Copy(Getattr(n, "name"));
+    mainmodule = Getattr(n, "name");
+
+    if (directorsEnabled()) {
+      Swig_banner(f_directors_h);
+      Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module);
+      Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module);
+      if (dirprot_mode()) {
+	Printf(f_directors_h, "#include <map>\n");
+	Printf(f_directors_h, "#include <string>\n\n");
+      }
+
+      Printf(f_directors, "\n\n");
+      Printf(f_directors, "/* ---------------------------------------------------\n");
+      Printf(f_directors, " * C++ director class methods\n");
+      Printf(f_directors, " * --------------------------------------------------- */\n\n");
+      if (outfile_h)
+	Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h));
+    }
+
+    /* If shadow classing is enabled, we're going to change the module name to "_module" */
+    if (shadow) {
+      String *filen = NewStringf("%s%s.py", SWIG_output_directory(), Char(module));
+      // If we don't have an interface then change the module name X to _X
+      if (interface)
+	module = interface;
+      else
+	Insert(module, 0, "_");
+      if ((f_shadow_py = NewFile(filen, "w")) == 0) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      Delete(filen);
+      filen = NULL;
+
+      f_shadow = NewString("");
+      f_shadow_imports = NewString("");
+      f_shadow_stubs = NewString("");
+
+      Swig_register_filebyname("shadow", f_shadow);
+      Swig_register_filebyname("python", f_shadow);
+
+      Printf(f_shadow, "# This file was automatically generated by SWIG (http://www.swig.org).\n");
+      Printf(f_shadow, "# Version %s\n", Swig_package_version());
+      Printf(f_shadow, "#\n");
+      Printf(f_shadow, "# Don't modify this file, modify the SWIG interface instead.\n");
+
+      if (!modern) {
+	Printv(f_shadow, "# This file is compatible with both classic and new-style classes.\n", NIL);
+      }
+
+      if (mod_docstring && Len(mod_docstring)) {
+	Printv(f_shadow, "\n\"\"\"\n", mod_docstring, "\n\"\"\"\n", NIL);
+	Delete(mod_docstring);
+	mod_docstring = NULL;
+      }
+
+      Printf(f_shadow, "\nimport %s\n", module);
+
+      Printv(f_shadow, "import new\n", NULL);
+      Printv(f_shadow, "new_instancemethod = new.instancemethod\n", NULL);
+      if (modern || !classic) {
+	Printv(f_shadow, "try:\n", tab4, "_swig_property = property\n", "except NameError:\n", tab4, "pass # Python < 2.2 doesn't have 'property'.\n", NULL);
+      }
+      /* if (!modern) */
+      /* always needed, a class can be forced to be no-modern, such as an exception */
+      {
+	// Python-2.2 object hack
+	Printv(f_shadow,
+	       "def _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n",
+	       tab4, "if (name == \"thisown\"): return self.this.own(value)\n",
+	       tab4, "if (name == \"this\"):\n", tab4, tab4, "if type(value).__name__ == 'PySwigObject':\n", tab4, tab8, "self.__dict__[name] = value\n",
+#ifdef USE_THISOWN
+	       tab4, tab8, "if hasattr(value,\"thisown\"): self.__dict__[\"thisown\"] = value.thisown\n", tab4, tab8, "del value.thisown\n",
+#endif
+	       tab4, tab8, "return\n", tab4, "method = class_type.__swig_setmethods__.get(name,None)\n", tab4, "if method: return method(self,value)\n",
+#ifdef USE_THISOWN
+	       tab4, "if (not static) or hasattr(self,name) or (name == \"thisown\"):\n",
+#else
+	       tab4, "if (not static) or hasattr(self,name):\n",
+#endif
+	       tab4, tab4, "self.__dict__[name] = value\n",
+	       tab4, "else:\n",
+	       tab4, tab4, "raise AttributeError(\"You cannot add attributes to %s\" % self)\n\n",
+	       "def _swig_setattr(self,class_type,name,value):\n", tab4, "return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\n", NIL);
+
+	Printv(f_shadow,
+	       "def _swig_getattr(self,class_type,name):\n",
+	       tab4, "if (name == \"thisown\"): return self.this.own()\n",
+	       tab4, "method = class_type.__swig_getmethods__.get(name,None)\n",
+	       tab4, "if method: return method(self)\n", tab4, "raise AttributeError,name\n\n", NIL);
+
+	Printv(f_shadow,
+	       "def _swig_repr(self):\n",
+	       tab4, "try: strthis = \"proxy of \" + self.this.__repr__()\n",
+	       tab4, "except: strthis = \"\"\n", tab4, "return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n", NIL);
+
+	if (!classic) {
+	  Printv(f_shadow,
+		 "import types\n",
+		 "try:\n",
+		 "    _object = types.ObjectType\n",
+		 "    _newclass = 1\n", "except AttributeError:\n", "    class _object : pass\n", "    _newclass = 0\n", "del types\n", "\n\n", NIL);
+	}
+      }
+      if (modern) {
+	Printv(f_shadow, "def _swig_setattr_nondynamic_method(set):\n", tab4, "def set_attr(self,name,value):\n",
+#ifdef USE_THISOWN
+	       tab4, tab4, "if hasattr(self,name) or (name in (\"this\", \"thisown\")):\n",
+#else
+	       tab4, tab4, "if (name == \"thisown\"): return self.this.own(value)\n", tab4, tab4, "if hasattr(self,name) or (name == \"this\"):\n",
+#endif
+	       tab4, tab4, tab4, "set(self,name,value)\n",
+	       tab4, tab4, "else:\n",
+	       tab4, tab4, tab4, "raise AttributeError(\"You cannot add attributes to %s\" % self)\n", tab4, "return set_attr\n\n\n", NIL);
+      }
+
+      if (directorsEnabled()) {
+	// Try loading weakref.proxy, which is only available in Python 2.1 and higher
+	Printv(f_shadow,
+	       "try:\n", tab4, "import weakref\n", tab4, "weakref_proxy = weakref.proxy\n", "except:\n", tab4, "weakref_proxy = lambda x: x\n", "\n\n", NIL);
+      }
+      // Include some information in the code
+      Printf(f_header, "\n/*-----------------------------------------------\n              @(target):= %s.so\n\
+  ------------------------------------------------*/\n", module);
+
+    }
+
+    Printf(f_header, "#define SWIG_init    init%s\n\n", module);
+    Printf(f_header, "#define SWIG_name    \"%s\"\n", module);
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n");
+    Printf(f_wrappers, "extern \"C\" {\n");
+    Printf(f_wrappers, "#endif\n");
+    Append(const_code, "static swig_const_info swig_const_table[] = {\n");
+    Append(methods, "static PyMethodDef SwigMethods[] = {\n");
+
+    /* emit code */
+    Language::top(n);
+
+    if (directorsEnabled()) {
+      // Insert director runtime into the f_runtime file (make it occur before %header section)
+      Swig_insert_file("director.swg", f_runtime);
+    }
+
+    /* Close language module */
+    Append(methods, "\t { NULL, NULL, 0, NULL }\n");
+    Append(methods, "};\n");
+    Printf(f_wrappers, "%s\n", methods);
+
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+
+    Append(const_code, "{0, 0, 0, 0.0, 0, 0}};\n");
+    Printf(f_wrappers, "%s\n", const_code);
+    initialize_threads(f_init);
+    Printf(f_init, "}\n");
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n");
+    Printf(f_wrappers, "}\n");
+    Printf(f_wrappers, "#endif\n");
+
+    if (shadow) {
+      /*
+         Printf(f_shadow_imports,"\nimport %s\n", module);
+         Printv(f_shadow_py, f_shadow_imports, "\n",NIL);
+       */
+      Printv(f_shadow_py, f_shadow, "\n", NIL);
+      Printv(f_shadow_py, f_shadow_stubs, "\n", NIL);
+
+      Close(f_shadow_py);
+      Delete(f_shadow_py);
+    }
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+
+    if (directorsEnabled()) {
+      Dump(f_directors_h, f_runtime_h);
+      Printf(f_runtime_h, "\n");
+      Printf(f_runtime_h, "#endif\n");
+      if (f_runtime_h != f_runtime)
+	Close(f_runtime_h);
+      Dump(f_directors, f_runtime);
+    }
+
+    Dump(f_wrappers, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Delete(f_directors);
+    Delete(f_directors_h);
+
+    Close(f_runtime);
+    Delete(f_runtime);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * importDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int importDirective(Node *n) {
+    if (shadow) {
+      String *modname = Getattr(n, "module");
+
+      if (modname) {
+	String *import = NewString("import ");
+
+	// Find the module node for this imported module.  It should be the
+	// first child but search just in case.
+	Node *mod = firstChild(n);
+	while (mod && Strcmp(nodeType(mod), "module") != 0)
+	  mod = nextSibling(mod);
+
+	// Is the imported module in another package?  (IOW, does it use the
+	// %module(package="name") option and it's different than the package
+	// of this module.)
+	Node *options = Getattr(mod, "options");
+	String *pkg = options ? Getattr(options, "package") : 0;
+	if (pkg && (!package || Strcmp(pkg, package) != 0)) {
+	  Printf(import, "%s.", pkg);
+	}
+	// finally, output the name of the imported module
+	if (shadowimport) {
+	  if (!options || (!Getattr(options, "noshadow") && !Getattr(options, "noproxy"))) {
+	    Printf(import, "_%s\n", modname);
+	    if (!Strstr(f_shadow_imports, import)) {
+	      Printf(f_shadow, "import %s\n", modname);
+	      Printv(f_shadow_imports, import, NULL);
+	    }
+	  }
+	}
+
+	Delete(import);
+      }
+    }
+    return Language::importDirective(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * emitFuncCallHelper()
+   *    Write the shadow code to call a function in the extension
+   *    module.  Takes into account the -apply flag and whether
+   *    to use keyword args or not.
+   * ------------------------------------------------------------ */
+
+  String *funcCallHelper(String *name, int kw) {
+    String *str;
+
+    str = NewString("");
+    if (apply) {
+      Printv(str, "apply(", module, ".", name, ", args", (kw ? ", kwargs" : ""), ")", NIL);
+    } else {
+      Printv(str, module, ".", name, "(*args", (kw ? ", **kwargs" : ""), ")", NIL);
+    }
+    return str;
+  }
+
+  /* ------------------------------------------------------------
+   * pythoncode()     - Output python code into the shadow file
+   * ------------------------------------------------------------ */
+
+  String *pythoncode(String *code, const String *indent) {
+    String *out = NewString("");
+    String *temp;
+    char *t;
+    if (!indent)
+      indent = "";
+
+    temp = NewString(code);
+
+    t = Char(temp);
+    if (*t == '{') {
+      Delitem(temp, 0);
+      Delitem(temp, DOH_END);
+    }
+
+    /* Split the input text into lines */
+    List *clist = DohSplitLines(temp);
+    Delete(temp);
+    int initial = 0;
+    String *s = 0;
+    Iterator si;
+    /* Get the initial indentation */
+
+    for (si = First(clist); si.item; si = Next(si)) {
+      s = si.item;
+      if (Len(s)) {
+	char *c = Char(s);
+	while (*c) {
+	  if (!isspace(*c))
+	    break;
+	  initial++;
+	  c++;
+	}
+	if (*c && !isspace(*c))
+	  break;
+	else {
+	  initial = 0;
+	}
+      }
+    }
+    while (si.item) {
+      s = si.item;
+      if (Len(s) > initial) {
+	char *c = Char(s);
+	c += initial;
+	Printv(out, indent, c, "\n", NIL);
+      } else {
+	Printv(out, "\n", NIL);
+      }
+      si = Next(si);
+    }
+    Delete(clist);
+    return out;
+  }
+
+
+  /* ------------------------------------------------------------
+   * autodoc level declarations
+   * ------------------------------------------------------------ */
+
+  enum autodoc_l {
+    NO_AUTODOC = -2,		// no autodoc
+    STRING_AUTODOC = -1,	// use provided string
+    NAMES_AUTODOC = 0,		// only parameter names
+    TYPES_AUTODOC = 1,		// parameter names and types
+    EXTEND_AUTODOC = 2,		// extended documentation and parameter names
+    EXTEND_TYPES_AUTODOC = 3	// extended documentation and parameter types + names
+  };
+
+
+  autodoc_l autodoc_level(String *autodoc) {
+    autodoc_l dlevel = NO_AUTODOC;
+    if (autodoc) {
+      char *c = Char(autodoc);
+      if (c && isdigit(c[0])) {
+	dlevel = (autodoc_l) atoi(c);
+      } else {
+	if (strcmp(c, "extended") == 0) {
+	  dlevel = EXTEND_AUTODOC;
+	} else {
+	  dlevel = STRING_AUTODOC;
+	}
+      }
+    }
+    return dlevel;
+  }
+
+
+  /* ------------------------------------------------------------
+   * have_docstring()
+   *    Check if there is a docstring directive and it has text,
+   *    or there is an autodoc flag set
+   * ------------------------------------------------------------ */
+
+  bool have_docstring(Node *n) {
+    String *str = Getattr(n, "feature:docstring");
+    return (str != NULL && Len(str) > 0) || (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
+  }
+
+  /* ------------------------------------------------------------
+   * docstring()
+   *    Get the docstring text, stripping off {} if neccessary,
+   *    and enclose in triple double quotes.  If autodoc is also
+   *    set then it will build a combined docstring.
+   * ------------------------------------------------------------ */
+
+  String *docstring(Node *n, autodoc_t ad_type, const String *indent, bool use_triple = true) {
+    String *str = Getattr(n, "feature:docstring");
+    bool have_ds = (str != NULL && Len(str) > 0);
+    bool have_auto = (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
+    const char *triple_double = use_triple ? "\"\"\"" : "";
+    String *autodoc = NULL;
+    String *doc = NULL;
+
+    if (have_ds) {
+      char *t = Char(str);
+      if (*t == '{') {
+	Delitem(str, 0);
+	Delitem(str, DOH_END);
+      }
+    }
+
+    if (have_auto) {
+      autodoc = make_autodoc(n, ad_type);
+      have_auto = (autodoc != NULL && Len(autodoc) > 0);
+    }
+    // If there is more than one line then make docstrings like this:
+    //
+    //      """
+    //      This is line1
+    //      And here is line2 followed by the rest of them
+    //      """
+    //
+    // otherwise, put it all on a single line
+    //
+    if (have_auto && have_ds) {	// Both autodoc and docstring are present
+      doc = NewString("");
+      Printv(doc, triple_double, "\n", pythoncode(autodoc, indent), "\n", pythoncode(str, indent), indent, triple_double, NIL);
+    } else if (!have_auto && have_ds) {	// only docstring
+      if (Strchr(str, '\n') == NULL) {
+	doc = NewStringf("%s%s%s", triple_double, str, triple_double);
+      } else {
+	doc = NewString("");
+	Printv(doc, triple_double, "\n", pythoncode(str, indent), indent, triple_double, NIL);
+      }
+    } else if (have_auto && !have_ds) {	// only autodoc
+      if (Strchr(autodoc, '\n') == NULL) {
+	doc = NewStringf("%s%s%s", triple_double, autodoc, triple_double);
+      } else {
+	doc = NewString("");
+	Printv(doc, triple_double, "\n", pythoncode(autodoc, indent), indent, triple_double, NIL);
+      }
+    } else
+      doc = NewString("");
+
+    // Save the generated strings in the parse tree in case they are used later
+    // by post processing tools
+    Setattr(n, "python:docstring", doc);
+    Setattr(n, "python:autodoc", autodoc);
+    return doc;
+  }
+
+  /* ------------------------------------------------------------
+   * make_autodocParmList()
+   *   Generate the documentation for the function parameters
+   * ------------------------------------------------------------ */
+
+  String *make_autodocParmList(Node *n, bool showTypes) {
+    String *doc = NewString("");
+    String *pdocs = Copy(Getattr(n, "feature:pdocs"));
+    ParmList *plist = CopyParmList(Getattr(n, "parms"));
+    Parm *p;
+    Parm *pnext;
+    Node *lookup;
+    int lines = 0;
+    const int maxwidth = 50;
+
+    if (pdocs)
+      Append(pdocs, "\n");
+
+
+    Swig_typemap_attach_parms("in", plist, 0);
+    Swig_typemap_attach_parms("doc", plist, 0);
+
+    for (p = plist; p; p = pnext) {
+      String *name = 0;
+      String *type = 0;
+      String *value = 0;
+      String *ptype = 0;
+      String *pdoc = Getattr(p, "tmap:doc");
+      if (pdoc) {
+	name = Getattr(p, "tmap:doc:name");
+	type = Getattr(p, "tmap:doc:type");
+	value = Getattr(p, "tmap:doc:value");
+	ptype = Getattr(p, "tmap:doc:pytype");
+      }
+
+      name = name ? name : Getattr(p, "name");
+      type = type ? type : Getattr(p, "type");
+      value = value ? value : Getattr(p, "value");
+
+      String *tm = Getattr(p, "tmap:in");
+      if (tm) {
+	pnext = Getattr(p, "tmap:in:next");
+      } else {
+	pnext = nextSibling(p);
+      }
+
+      if (Len(doc)) {
+	// add a comma to the previous one if any
+	Append(doc, ", ");
+
+	// Do we need to wrap a long line?
+	if ((Len(doc) - lines * maxwidth) > maxwidth) {
+	  Printf(doc, "\n%s", tab4);
+	  lines += 1;
+	}
+      }
+      // Do the param type too?
+      if (showTypes) {
+	type = SwigType_base(type);
+	lookup = Swig_symbol_clookup(type, 0);
+	if (lookup)
+	  type = Getattr(lookup, "sym:name");
+	Printf(doc, "%s ", type);
+      }
+
+      if (name) {
+	Append(doc, name);
+	if (pdoc) {
+	  if (!pdocs)
+	    pdocs = NewString("Parameters:\n");
+	  Printf(pdocs, "   %s\n", pdoc);
+	}
+      } else {
+	Append(doc, "?");
+      }
+
+      if (value) {
+	if (Strcmp(value, "NULL") == 0)
+	  value = NewString("None");
+	else if (Strcmp(value, "true") == 0 || Strcmp(value, "TRUE") == 0)
+	  value = NewString("True");
+	else if (Strcmp(value, "false") == 0 || Strcmp(value, "FALSE") == 0)
+	  value = NewString("False");
+	else {
+	  lookup = Swig_symbol_clookup(value, 0);
+	  if (lookup)
+	    value = Getattr(lookup, "sym:name");
+	}
+	Printf(doc, "=%s", value);
+      }
+    }
+    if (pdocs)
+      Setattr(n, "feature:pdocs", pdocs);
+    Delete(plist);
+    return doc;
+  }
+
+  /* ------------------------------------------------------------
+   * make_autodoc()
+   *    Build a docstring for the node, using parameter and other
+   *    info in the parse tree.  If the value of the autodoc
+   *    attribute is "0" then do not include parameter types, if
+   *    it is "1" (the default) then do.  If it has some other
+   *    value then assume it is supplied by the extension writer
+   *    and use it directly.
+   * ------------------------------------------------------------ */
+
+  String *make_autodoc(Node *n, autodoc_t ad_type) {
+    int extended = 0;
+    // If the function is overloaded then this funciton is called
+    // for the last one.  Rewind to the first so the docstrings are
+    // in order.
+    while (Getattr(n, "sym:previousSibling"))
+      n = Getattr(n, "sym:previousSibling");
+
+    String *doc = NewString("");
+    while (n) {
+      bool showTypes = false;
+      bool skipAuto = false;
+      String *autodoc = Getattr(n, "feature:autodoc");
+      autodoc_l dlevel = autodoc_level(autodoc);
+      switch (dlevel) {
+      case NO_AUTODOC:
+	break;
+      case NAMES_AUTODOC:
+	showTypes = false;
+	break;
+      case TYPES_AUTODOC:
+	showTypes = true;
+	break;
+      case EXTEND_AUTODOC:
+	extended = 1;
+	showTypes = false;
+	break;
+      case EXTEND_TYPES_AUTODOC:
+	extended = 1;
+	showTypes = true;
+	break;
+      case STRING_AUTODOC:
+	Append(doc, autodoc);
+	skipAuto = true;
+	break;
+      }
+
+      if (!skipAuto) {
+	String *symname = Getattr(n, "sym:name");
+	SwigType *type = Getattr(n, "type");
+
+	if (type) {
+	  if (Strcmp(type, "void") == 0)
+	    type = NULL;
+	  else {
+	    type = SwigType_base(type);
+	    Node *lookup = Swig_symbol_clookup(type, 0);
+	    if (lookup)
+	      type = Getattr(lookup, "sym:name");
+	  }
+	}
+
+	switch (ad_type) {
+	case AUTODOC_CLASS:
+	  {
+	    // Only do the autodoc if there isn't a docstring for the class
+	    String *str = Getattr(n, "feature:docstring");
+	    if (str == NULL || Len(str) == 0) {
+	      if (CPlusPlus) {
+		Printf(doc, "Proxy of C++ %s class", class_name);
+	      } else {
+		Printf(doc, "Proxy of C %s struct", class_name);
+	      }
+	    }
+	  }
+	  break;
+	case AUTODOC_CTOR:
+	  if (Strcmp(class_name, symname) == 0) {
+	    String *paramList = make_autodocParmList(n, showTypes);
+	    if (Len(paramList))
+	      Printf(doc, "__init__(self, %s) -> %s", paramList, class_name);
+	    else
+	      Printf(doc, "__init__(self) -> %s", class_name);
+	  } else
+	    Printf(doc, "%s(%s) -> %s", symname, make_autodocParmList(n, showTypes), class_name);
+	  break;
+
+	case AUTODOC_DTOR:
+	  Append(doc, "__del__(self)");
+	  break;
+
+	case AUTODOC_STATICFUNC:
+	  Printf(doc, "%s(%s)", symname, make_autodocParmList(n, showTypes));
+	  if (type)
+	    Printf(doc, " -> %s", type);
+	  break;
+
+	case AUTODOC_FUNC:
+	  Printf(doc, "%s(%s)", symname, make_autodocParmList(n, showTypes));
+	  if (type)
+	    Printf(doc, " -> %s", type);
+	  break;
+
+	case AUTODOC_METHOD:
+	  String *paramList = make_autodocParmList(n, showTypes);
+	  if (Len(paramList))
+	    Printf(doc, "%s(self, %s)", symname, paramList);
+	  else
+	    Printf(doc, "%s(self)", symname);
+	  if (type)
+	    Printf(doc, " -> %s", type);
+	  break;
+	}
+      }
+      if (extended) {
+	String *pdocs = Getattr(n, "feature:pdocs");
+	if (pdocs) {
+	  Printv(doc, "\n", pdocs, NULL);
+	}
+      }
+
+      // if it's overloaded then get the next decl and loop around again
+      n = Getattr(n, "sym:nextSibling");
+      if (n)
+	Append(doc, "\n");
+    }
+
+    return doc;
+  }
+
+  /* ------------------------------------------------------------
+   * have_pythonprepend()
+   *    Check if there is a %pythonprepend directive and it has text
+   * ------------------------------------------------------------ */
+
+  bool have_pythonprepend(Node *n) {
+    String *str = Getattr(n, "feature:pythonprepend");
+    return (str != NULL && Len(str) > 0);
+  }
+
+  /* ------------------------------------------------------------
+   * pythonprepend()
+   *    Get the %pythonprepend code, stripping off {} if neccessary
+   * ------------------------------------------------------------ */
+
+  String *pythonprepend(Node *n) {
+    String *str = Getattr(n, "feature:pythonprepend");
+    char *t = Char(str);
+    if (*t == '{') {
+      Delitem(str, 0);
+      Delitem(str, DOH_END);
+    }
+    return str;
+  }
+
+  /* ------------------------------------------------------------
+   * have_pythonappend()
+   *    Check if there is a %pythonappend directive and it has text
+   * ------------------------------------------------------------ */
+
+  bool have_pythonappend(Node *n) {
+    String *str = Getattr(n, "feature:pythonappend");
+    if (!str)
+      str = Getattr(n, "feature:addtofunc");
+    return (str != NULL && Len(str) > 0);
+  }
+
+  /* ------------------------------------------------------------
+   * pythonappend()
+   *    Get the %pythonappend code, stripping off {} if neccessary
+   * ------------------------------------------------------------ */
+
+  String *pythonappend(Node *n) {
+    String *str = Getattr(n, "feature:pythonappend");
+    if (!str)
+      str = Getattr(n, "feature:addtofunc");
+
+    char *t = Char(str);
+    if (*t == '{') {
+      Delitem(str, 0);
+      Delitem(str, DOH_END);
+    }
+    return str;
+  }
+
+  /* ------------------------------------------------------------
+   * have_addtofunc()
+   *    Check if there is a %addtofunc directive and it has text
+   * ------------------------------------------------------------ */
+
+  bool have_addtofunc(Node *n) {
+    return have_pythonappend(n) || have_pythonprepend(n) || have_docstring(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * emitFunctionShadowHelper()
+   *    Refactoring some common code out of functionWrapper and
+   *    dispatchFunction that writes the proxy code for non-member
+   *    functions.
+   * ------------------------------------------------------------ */
+
+  void emitFunctionShadowHelper(Node *n, File *f_dest, String *name, int kw) {
+    if (Getattr(n, "feature:python:callback") || !have_addtofunc(n)) {
+      /* If there is no addtofunc directive then just assign from the extension module */
+      Printv(f_dest, name, " = ", module, ".", name, "\n", NIL);
+    } else {
+      /* Otherwise make a wrapper function to insert the code into */
+      Printv(f_dest, "\ndef ", name, "(*args", (kw ? ", **kwargs" : ""), "):\n", NIL);
+      if (have_docstring(n))
+	Printv(f_dest, ctab4, docstring(n, AUTODOC_FUNC, tab4), "\n", NIL);
+      if (have_pythonprepend(n))
+	Printv(f_dest, ctab4, pythonprepend(n), "\n", NIL);
+      if (have_pythonappend(n)) {
+	Printv(f_dest, ctab4, "val = ", funcCallHelper(name, kw), "\n", NIL);
+	Printv(f_dest, ctab4, pythonappend(n), "\n", NIL);
+	Printv(f_dest, ctab4, "return val\n", NIL);
+      } else {
+	Printv(f_dest, ctab4, "return ", funcCallHelper(name, kw), "\n", NIL);
+      }
+    }
+  }
+
+
+  /* ------------------------------------------------------------
+   * check_kwargs()
+   *    check if using kwargs is allowed for this Node
+   * ------------------------------------------------------------ */
+
+  int check_kwargs(Node *n) {
+    return (use_kw || GetFlag(n, "feature:kwargs"))
+	&& !GetFlag(n, "memberset") && !GetFlag(n, "memberget");
+  }
+
+
+
+  /* ------------------------------------------------------------
+   * add_method()
+   * ------------------------------------------------------------ */
+
+  void add_method(String *name, String *function, int kw, Node *n = 0, int funpack = 0, int num_required = -1, int num_arguments = -1) {
+    if (!kw) {
+      if (n && funpack) {
+	if (num_required == 0 && num_arguments == 0) {
+	  Printf(methods, "\t { (char *)\"%s\", (PyCFunction)%s, METH_NOARGS, ", name, function);
+	} else if (num_required == 1 && num_arguments == 1) {
+	  Printf(methods, "\t { (char *)\"%s\", (PyCFunction)%s, METH_O, ", name, function);
+	} else {
+	  Printf(methods, "\t { (char *)\"%s\", %s, METH_VARARGS, ", name, function);
+	}
+      } else {
+	Printf(methods, "\t { (char *)\"%s\", %s, METH_VARARGS, ", name, function);
+      }
+    } else {
+      Printf(methods, "\t { (char *)\"%s\", (PyCFunction) %s, METH_VARARGS | METH_KEYWORDS, ", name, function);
+    }
+
+    if (!n) {
+      Append(methods, "NULL");
+    } else if (Getattr(n, "feature:callback")) {
+      if (have_docstring(n)) {
+	String *ds = docstring(n, AUTODOC_FUNC, "", false);
+	Replaceall(ds, "\\", "\\\\");
+	Replaceall(ds, "\"", "\\\"");
+	Replaceall(ds, "\n", "\\n\"\n\t\t\"");
+	Printf(methods, "(char *)\"%s\\nswig_ptr: %s\"", ds, Getattr(n, "feature:callback:name"));
+      } else {
+	Printf(methods, "(char *)\"swig_ptr: %s\"", Getattr(n, "feature:callback:name"));
+      }
+    } else if (have_docstring(n)) {
+      String *ds = docstring(n, AUTODOC_FUNC, "", false);
+      Replaceall(ds, "\\", "\\\\");
+      Replaceall(ds, "\"", "\\\"");
+      Replaceall(ds, "\n", "\\n\"\n\t\t\"");
+      Printf(methods, "(char *)\"%s\"", ds);
+    } else {
+      Append(methods, "NULL");
+    }
+
+    Append(methods, "},\n");
+  }
+
+  /* ------------------------------------------------------------
+   * dispatchFunction()
+   * ------------------------------------------------------------ */
+  void dispatchFunction(Node *n, int funpack = 0) {
+    /* Last node in overloaded chain */
+
+    int maxargs;
+    int allow_thread = threads_enable(n);
+
+    String *tmp = NewString("");
+    String *dispatch;
+    const char *dispatch_code = funpack ? "return %s(self, argc, argv);" : "return %s(self, args);";
+
+    if (castmode) {
+      dispatch = Swig_overload_dispatch_cast(n, dispatch_code, &maxargs);
+    } else {
+      dispatch = Swig_overload_dispatch(n, dispatch_code, &maxargs);
+    }
+
+    /* Generate a dispatch wrapper for all overloaded functions */
+
+    Wrapper *f = NewWrapper();
+    String *symname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(symname);
+
+    Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *self, PyObject *args) {", NIL);
+
+    Wrapper_add_local(f, "argc", "int argc");
+    Printf(tmp, "PyObject *argv[%d]", maxargs + 1);
+    Wrapper_add_local(f, "argv", tmp);
+    if (allow_thread)
+      thread_begin_block(n, f->code);
+
+    if (!fastunpack) {
+      Wrapper_add_local(f, "ii", "int ii");
+      Append(f->code, "if (!PyTuple_Check(args)) SWIG_fail;\n");
+      Append(f->code, "argc = (int)PyObject_Length(args);\n");
+      Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++) {\n", maxargs);
+      Append(f->code, "argv[ii] = PyTuple_GET_ITEM(args,ii);\n");
+      Append(f->code, "}\n");
+    } else {
+      String *iname = Getattr(n, "sym:name");
+      Printf(f->code, "if (!(argc = SWIG_Python_UnpackTuple(args,\"%s\",0,%d,argv))) SWIG_fail;\n", iname, maxargs);
+      Append(f->code, "--argc;\n");
+    }
+
+    Replaceall(dispatch, "$args", "self,args");
+
+    if (allow_thread) {
+      String *ret = NewStringEmpty();
+      thread_end_block(n, ret);
+      Append(ret, "return ");
+      Replaceall(dispatch, "return ", ret);
+      Delete(ret);
+    }
+
+    Printv(f->code, dispatch, "\n", NIL);
+
+    if (allow_thread)
+      thread_end_block(n, f->code);
+
+    if (GetFlag(n, "feature:python:maybecall")) {
+      Append(f->code, "fail:\n");
+      Append(f->code, "Py_INCREF(Py_NotImplemented);\n");
+      Append(f->code, "return Py_NotImplemented;\n");
+    } else {
+      Node *sibl = n;
+      while (Getattr(sibl, "sym:previousSibling"))
+	sibl = Getattr(sibl, "sym:previousSibling");	// go all the way up
+      String *protoTypes = NewString("");
+      do {
+	Printf(protoTypes, "\n\"    %s(%s)\\n\"", SwigType_str(Getattr(sibl, "name"), 0), ParmList_protostr(Getattr(sibl, "wrap:parms")));
+      } while ((sibl = Getattr(sibl, "sym:nextSibling")));
+      Append(f->code, "fail:\n");
+      Printf(f->code, "SWIG_SetErrorMsg(PyExc_NotImplementedError,"
+	     "\"Wrong number of arguments for overloaded function '%s'.\\n\"" "\n\"  Possible C/C++ prototypes are:\\n\"%s);\n", symname, protoTypes);
+      Append(f->code, "return NULL;\n");
+      Delete(protoTypes);
+    }
+    Printv(f->code, "}\n", NIL);
+    Wrapper_print(f, f_wrappers);
+    Node *p = Getattr(n, "sym:previousSibling");
+    add_method(symname, wname, 0, p);
+
+    /* Create a shadow for this function (if enabled and not in a member function) */
+    if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) {
+      emitFunctionShadowHelper(n, f_shadow_stubs, symname, 0);
+    }
+    DelWrapper(f);
+    Delete(dispatch);
+    Delete(tmp);
+    Delete(wname);
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * ------------------------------------------------------------ */
+
+
+  const char *get_implicitconv_flag(Node *klass) {
+    int conv = 0;
+    if (klass && GetFlag(klass, "feature:implicitconv")) {
+      conv = 1;
+    }
+    return conv ? "SWIG_POINTER_IMPLICIT_CONV" : "0";
+  }
+
+
+  virtual int functionWrapper(Node *n) {
+
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *d = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    int director_method = 0;
+
+    Parm *p;
+    int i;
+    char source[64];
+    Wrapper *f;
+    String *parse_args;
+    String *arglist;
+    String *get_pointers;
+    String *cleanup;
+    String *outarg;
+    String *kwargs;
+    String *tm;
+    String *overname = 0;
+
+    int num_required;
+    int num_arguments;
+    int varargs = 0;
+    int allow_kwargs = check_kwargs(n);
+
+    String *nodeType = Getattr(n, "nodeType");
+    int constructor = (!Cmp(nodeType, "constructor"));
+    int destructor = (!Cmp(nodeType, "destructor"));
+    String *storage = Getattr(n, "storage");
+    /* Only the first constructor is handled as init method. Others
+       constructor can be emitted via %rename */
+    int handled_as_init = 0;
+    if (!have_constructor && (constructor || Getattr(n, "handled_as_constructor"))
+	&& ((shadow & PYSHADOW_MEMBER))) {
+      String *nname = Getattr(n, "sym:name");
+      String *sname = Getattr(getCurrentClass(), "sym:name");
+      String *cname = Swig_name_construct(sname);
+      handled_as_init = (Strcmp(nname, sname) == 0) || (Strcmp(nname, cname) == 0);
+      Delete(cname);
+    }
+
+
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n))
+	return SWIG_ERROR;
+    }
+
+    f = NewWrapper();
+    parse_args = NewString("");
+    arglist = NewString("");
+    get_pointers = NewString("");
+    cleanup = NewString("");
+    outarg = NewString("");
+    kwargs = NewString("");
+
+    int allow_thread = threads_enable(n);
+    if (allow_thread)
+      thread_begin_block(n, f->code);
+
+    Wrapper_add_local(f, "resultobj", "PyObject *resultobj = 0");
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(l, f);
+
+    /* Attach the standard typemaps */
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+    /* Get number of required and total arguments */
+    num_arguments = emit_num_arguments(l);
+    num_required = emit_num_required(l);
+    if (((num_arguments == 0) && (num_required == 0)) || ((num_arguments == 1) && (num_required == 1) && Getattr(l, "self")))
+      allow_kwargs = 0;
+    varargs = emit_isvarargs(l);
+
+    String *wname = Swig_name_wrapper(iname);
+    if (overname) {
+      Append(wname, overname);
+    }
+
+    if (!allow_kwargs || Getattr(n, "sym:overloaded")) {
+      if (!varargs) {
+	Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL);
+      } else {
+	Printv(f->def, "SWIGINTERN PyObject *", wname, "__varargs__", "(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *varargs) {", NIL);
+      }
+      if (allow_kwargs) {
+	Swig_warning(WARN_LANG_OVERLOAD_KEYWORD, input_file, line_number, "Can't use keyword arguments with overloaded functions.\n");
+	allow_kwargs = 0;
+      }
+    } else {
+      if (varargs) {
+	Swig_warning(WARN_LANG_VARARGS_KEYWORD, input_file, line_number, "Can't wrap varargs with keyword arguments enabled\n");
+	varargs = 0;
+      }
+      Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {", NIL);
+    }
+    if (!allow_kwargs) {
+      Append(parse_args, "    if (!PyArg_ParseTuple(args,(char *)\"");
+    } else {
+      Append(parse_args, "    if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"");
+      Append(arglist, ",kwnames");
+    }
+
+    int funpack = modernargs && fastunpack && !varargs && !allow_kwargs;
+    int noargs = funpack && (num_required == 0 && num_arguments == 0);
+    int onearg = funpack && (num_required == 1 && num_arguments == 1);
+
+    /* Generate code for argument marshalling */
+    if (funpack) {
+      if (overname) {
+	if (aliasobj0) {
+	  Append(f->code, "#define obj0 (swig_obj[0])\n");
+	}
+      } else if (num_arguments) {
+	sprintf(source, "PyObject *swig_obj[%d]", num_arguments);
+	Wrapper_add_localv(f, "swig_obj", source, NIL);
+	if (aliasobj0) {
+	  Append(f->code, "#define obj0 (swig_obj[0])\n");
+	}
+      }
+    }
+
+
+    if (constructor && num_arguments == 1 && num_required == 1) {
+      if (Cmp(storage, "explicit") == 0) {
+	Node *parent = Swig_methodclass(n);
+	if (GetFlag(parent, "feature:implicitconv")) {
+	  String *desc = NewStringf("SWIGTYPE%s", SwigType_manglestr(Getattr(n, "type")));
+	  Printf(f->code, "if (SWIG_CheckImplicit(%s)) SWIG_fail;\n", desc);
+	  Delete(desc);
+	}
+      }
+    }
+
+    int use_parse = 0;
+    Append(kwargs, "{");
+    for (i = 0, p = l; i < num_arguments; i++) {
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *pn = Getattr(p, "name");
+      String *ln = Getattr(p, "lname");
+      if (funpack) {
+	sprintf(source, "swig_obj[%d]", i);
+      } else {
+	sprintf(source, "obj%d", i);
+      }
+
+
+      Putc(',', arglist);
+      if (i == num_required)
+	Putc('|', parse_args);	/* Optional argument separator */
+
+      /* Keyword argument handling */
+      if (allow_kwargs) {
+	if (Len(pn)) {
+	  String *tmp = 0;
+	  String *name = pn;
+	  if (!Getattr(p,"hidden")) {
+	    name = tmp = Swig_name_make(p, 0, pn, 0, 0);
+	  }
+	  Printf(kwargs, "(char *) \"%s\",", name);
+	  if (tmp)
+	    Delete(tmp);
+	} else {
+	  Printf(kwargs, "(char *)\"arg%d\",", i + 1);
+	}
+      }
+
+      /* Look for an input typemap */
+      if ((tm = Getattr(p, "tmap:in"))) {
+	String *parse = Getattr(p, "tmap:in:parse");
+	if (!parse) {
+	  if (funpack) {
+	    Replaceall(tm, "$self", "swig_obj[0]");
+	  } else {
+	    Replaceall(tm, "$self", "obj0");
+	  }
+	  Replaceall(tm, "$source", source);
+	  Replaceall(tm, "$target", ln);
+	  Replaceall(tm, "$input", source);
+	  Setattr(p, "emit:input", source);	/* Save the location of the object */
+
+	  if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+	    Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	  } else {
+	    Replaceall(tm, "$disown", "0");
+	  }
+
+	  if (Getattr(p, "tmap:in:implicitconv")) {
+	    const char *convflag = "0";
+	    if (!Getattr(p,"hidden")) {
+	      SwigType *ptype = Getattr(p, "type");
+	      convflag = get_implicitconv_flag(classLookup(ptype));
+	    }
+	    Replaceall(tm, "$implicitconv", convflag);
+	    Setattr(p, "implicitconv", convflag);
+	  }
+
+	  Putc('O', parse_args);
+	  if (!funpack) {
+	    Wrapper_add_localv(f, source, "PyObject *", source, "= 0", NIL);
+	    Printf(arglist, "&%s", source);
+	  }
+	  if (i >= num_required)
+	    Printv(get_pointers, "if (", source, ") {\n", NIL);
+	  Printv(get_pointers, tm, "\n", NIL);
+	  if (i >= num_required)
+	    Printv(get_pointers, "}\n", NIL);
+
+	} else {
+	  use_parse = 1;
+	  Append(parse_args, parse);
+	  Printf(arglist, "&%s", ln);
+	}
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+	break;
+      }
+    }
+
+    /* finish argument marshalling */
+    Append(kwargs, " NULL }");
+    if (allow_kwargs) {
+      Printv(f->locals, ctab4, "char *  kwnames[] = ", kwargs, ";\n", NIL);
+    }
+
+    if (use_parse || allow_kwargs || !modernargs) {
+      Printf(parse_args, ":%s\"", iname);
+      Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL);
+      funpack = 0;
+    } else {
+      Clear(parse_args);
+      if (funpack) {
+	Clear(f->def);
+	if (overname) {
+	  if (noargs) {
+	    Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) {", NIL);
+	  } else {
+	    Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) {", NIL);
+	  }
+	  Printf(parse_args, "if ((nobjs < %d) || (nobjs > %d)) SWIG_fail;\n", num_required, num_arguments);
+	} else {
+	  if (noargs) {
+	    Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL);
+	  } else {
+	    Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL);
+	  }
+	  if (onearg) {
+	    Printf(parse_args, "if (!args) SWIG_fail;\n");
+	    Printf(parse_args, "swig_obj[0] = args;\n");
+	  } else if (!noargs) {
+	    Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args,\"%s\",%d,%d,swig_obj)) SWIG_fail;\n", iname, num_required, num_arguments);
+	  } else if (noargs) {
+	    Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args,\"%s\",%d,%d,0)) SWIG_fail;\n", iname, num_required, num_arguments);
+	  }
+	}
+      } else {
+	Printf(parse_args, "if(!PyArg_UnpackTuple(args,(char *)\"%s\",%d,%d", iname, num_required, num_arguments);
+	Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL);
+      }
+    }
+
+    /* Now piece together the first part of the wrapper function */
+    Printv(f->code, parse_args, get_pointers, NIL);
+
+    /* Check for trailing varargs */
+    if (varargs) {
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+	Replaceall(tm, "$input", "varargs");
+	Printv(f->code, tm, "\n", NIL);
+      }
+    }
+
+    /* Insert constraint checking code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (p = l; p;) {
+      //      if (!checkAttribute(p,"tmap:in:numinputs","0") && !Getattr(p,"tmap:in:parse")) {
+      if (!Getattr(p, "tmap:in:parse") && (tm = Getattr(p, "tmap:freearg"))) {
+	if (Getattr(p, "tmap:freearg:implicitconv")) {
+	  const char *convflag = "0";
+	  if (!Getattr(p,"hidden")) {
+	    SwigType *ptype = Getattr(p, "type");
+	    convflag = get_implicitconv_flag(classLookup(ptype));
+	  }
+	  if (strcmp(convflag, "0") == 0) {
+	    tm = 0;
+	  }
+	}
+	if (tm && (Len(tm) != 0)) {
+	  Replaceall(tm, "$source", Getattr(p, "lname"));
+	  Printv(cleanup, tm, "\n", NIL);
+	}
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$target", "resultobj");
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* if the object is a director, and the method call originated from its
+     * underlying python object, resolve the call by going up the c++ 
+     * inheritance chain.  otherwise try to resolve the method in python.  
+     * without this check an infinite loop is set up between the director and 
+     * shadow class method calls.
+     */
+
+    // NOTE: this code should only be inserted if this class is the
+    // base class of a director class.  however, in general we haven't
+    // yet analyzed all classes derived from this one to see if they are
+    // directors.  furthermore, this class may be used as the base of
+    // a director class defined in a completely different module at a
+    // later time, so this test must be included whether or not directorbase
+    // is true.  we do skip this code if directors have not been enabled
+    // at the command line to preserve source-level compatibility with
+    // non-polymorphic swig.  also, if this wrapper is for a smart-pointer
+    // method, there is no need to perform the test since the calling object
+    // (the smart-pointer) and the director object (the "pointee") are
+    // distinct.
+
+    director_method = is_member_director(n) && !is_smart_pointer() && !destructor;
+    if (director_method) {
+      Wrapper_add_local(f, "director", "Swig::Director *director = 0");
+      Append(f->code, "director = SWIG_DIRECTOR_CAST(arg1);\n");
+      if (dirprot_mode() && !is_public(n)) {
+	Printf(f->code, "if (!director || !(director->swig_get_inner(\"%s\"))) {\n", name);
+	Printf(f->code, "SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing protected member %s\");\n", name);
+	Append(f->code, "SWIG_fail;\n");
+	Append(f->code, "}\n");
+      }
+      Wrapper_add_local(f, "upcall", "bool upcall = false");
+      if (funpack) {
+	Append(f->code, "upcall = (director && (director->swig_get_self()==swig_obj[0]));\n");
+      } else {
+	Append(f->code, "upcall = (director && (director->swig_get_self()==obj0));\n");
+      }
+    }
+
+    /* Emit the function call */
+    if (director_method) {
+      Append(f->code, "try {\n");
+    } else {
+      if (allow_thread) {
+	Append(f->code, "{\n");
+	thread_begin_allow(n, f->code);
+      }
+    }
+
+    Setattr(n, "wrap:name", wname);
+
+    Swig_director_emit_dynamic_cast(n, f);
+    String *actioncode = emit_action(n);
+
+    if (director_method) {
+      Append(actioncode, "} catch (Swig::DirectorException&) {\n");
+      Append(actioncode, "  SWIG_fail;\n");
+      Append(actioncode, "}\n");
+    } else {
+      if (allow_thread) {
+	thread_end_allow(n, actioncode);
+	Append(actioncode, "}\n");
+      }
+    }
+
+    /* This part below still needs cleanup */
+
+    /* Return the function value */
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      if (funpack) {
+	Replaceall(tm, "$self", "swig_obj[0]");
+      } else {
+	Replaceall(tm, "$self", "obj0");
+      }
+      Replaceall(tm, "$source", "result");
+      Replaceall(tm, "$target", "resultobj");
+      Replaceall(tm, "$result", "resultobj");
+      if (handled_as_init) {
+	Replaceall(tm, "$owner", "SWIG_POINTER_NEW");
+      } else {
+	if (GetFlag(n, "feature:new")) {
+	  Replaceall(tm, "$owner", "SWIG_POINTER_OWN");
+	} else {
+	  Replaceall(tm, "$owner", "0");
+	}
+      }
+      // FIXME: this will not try to unwrap directors returned as non-director
+      //        base class pointers!
+
+      /* New addition to unwrap director return values so that the original
+       * python object is returned instead. 
+       */
+#if 1
+      int unwrap = 0;
+      String *decl = Getattr(n, "decl");
+      int is_pointer = SwigType_ispointer_return(decl);
+      int is_reference = SwigType_isreference_return(decl);
+      if (is_pointer || is_reference) {
+	String *type = Getattr(n, "type");
+	//Node *classNode = Swig_methodclass(n);
+	//Node *module = Getattr(classNode, "module");
+	Node *parent = Swig_methodclass(n);
+	Node *module = Getattr(parent, "module");
+	Node *target = Swig_directormap(module, type);
+	if (target)
+	  unwrap = 1;
+      }
+      if (unwrap) {
+	Wrapper_add_local(f, "director", "Swig::Director *director = 0");
+	Append(f->code, "director = SWIG_DIRECTOR_CAST(result);\n");
+	Append(f->code, "if (director) {\n");
+	Append(f->code, "  resultobj = director->swig_get_self();\n");
+	Append(f->code, "  Py_INCREF(resultobj);\n");
+	Append(f->code, "} else {\n");
+	Printf(f->code, "%s\n", tm);
+	Append(f->code, "}\n");
+      } else {
+	Printf(f->code, "%s\n", tm);
+      }
+#else
+      Printf(f->code, "%s\n", tm);
+#endif
+      Delete(tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
+    }
+    emit_return_variable(n, d, f);
+
+    /* Output argument output code */
+    Printv(f->code, outarg, NIL);
+
+    /* Output cleanup code */
+    int need_cleanup = Len(cleanup) != 0;
+    if (need_cleanup) {
+      Printv(f->code, cleanup, NIL);
+    }
+
+    /* Look to see if there is any newfree cleanup code */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printf(f->code, "%s\n", tm);
+	Delete(tm);
+      }
+    }
+
+    /* See if there is any return cleanup code */
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printf(f->code, "%s\n", tm);
+      Delete(tm);
+    }
+
+    if (director_method) {
+      if ((tm = Swig_typemap_lookup("directorfree", n, "result", 0))) {
+	Replaceall(tm, "$input", "result");
+	Replaceall(tm, "$result", "resultobj");
+	Printf(f->code, "%s\n", tm);
+	Delete(tm);
+      }
+    }
+
+    if (allow_thread)
+      thread_end_block(n, f->code);
+    Append(f->code, "    return resultobj;\n");
+
+    /* Error handling code */
+
+    Append(f->code, "fail:\n");
+    if (need_cleanup) {
+      Printv(f->code, cleanup, NIL);
+    }
+    if (allow_thread)
+      thread_end_block(n, f->code);
+    Printv(f->code, ctab4, "return NULL;\n", NIL);
+
+
+    if (funpack) {
+      if (aliasobj0) {
+	Append(f->code, "#if defined(obj0)\n");
+	Append(f->code, "#undef obj0\n");
+	Append(f->code, "#endif\n");
+      }
+    }
+
+
+    Append(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", iname);
+    Replaceall(f->code, "$result", "resultobj");
+
+    if (funpack) {
+      Replaceall(f->code, "$self", "swig_obj[0]");
+    } else {
+      Replaceall(f->code, "$self", "obj0");
+    }
+
+    /* Dump the function out */
+    Wrapper_print(f, f_wrappers);
+
+    /* If varargs.  Need to emit a varargs stub */
+    if (varargs) {
+      DelWrapper(f);
+      f = NewWrapper();
+      Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *self, PyObject *args) {", NIL);
+      Wrapper_add_local(f, "resultobj", "PyObject *resultobj");
+      Wrapper_add_local(f, "varargs", "PyObject *varargs");
+      Wrapper_add_local(f, "newargs", "PyObject *newargs");
+      Printf(f->code, "newargs = PyTuple_GetSlice(args,0,%d);\n", num_arguments);
+      Printf(f->code, "varargs = PyTuple_GetSlice(args,%d,PyTuple_Size(args)+1);\n", num_arguments);
+      Printf(f->code, "resultobj = %s__varargs__(self,newargs,varargs);\n", wname);
+      Append(f->code, "Py_XDECREF(newargs);\n");
+      Append(f->code, "Py_XDECREF(varargs);\n");
+      Append(f->code, "return resultobj;\n");
+      Append(f->code, "}\n");
+      Wrapper_print(f, f_wrappers);
+    }
+
+    /* Now register the function with the interpreter.   */
+    if (!Getattr(n, "sym:overloaded")) {
+      add_method(iname, wname, allow_kwargs, n, funpack, num_required, num_arguments);
+
+      /* Create a shadow for this function (if enabled and not in a member function) */
+      if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) {
+	emitFunctionShadowHelper(n, in_class ? f_shadow_stubs : f_shadow, iname, allow_kwargs);
+      }
+    } else {
+      if (!Getattr(n, "sym:nextSibling")) {
+	dispatchFunction(n, funpack);
+      }
+    }
+    Delete(parse_args);
+    Delete(arglist);
+    Delete(get_pointers);
+    Delete(cleanup);
+    Delete(outarg);
+    Delete(kwargs);
+    Delete(wname);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+
+    static int have_globals = 0;
+    String *tm;
+    Wrapper *getf, *setf;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    getf = NewWrapper();
+    setf = NewWrapper();
+
+    /* If this is our first call, add the globals variable to the
+       Python dictionary. */
+
+    if (!have_globals) {
+      Printf(f_init, "\t PyDict_SetItemString(d,(char*)\"%s\", SWIG_globals());\n", global_name);
+      have_globals = 1;
+      if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) {
+	Printf(f_shadow_stubs, "%s = %s.%s\n", global_name, module, global_name);
+      }
+    }
+    int assignable = is_assignable(n);
+
+    if ((shadow) && !assignable) {
+      if (!in_class) {
+	Printf(f_shadow_stubs, "%s = %s.%s\n", iname, global_name, iname);
+      }
+    }
+
+    String *getname = Swig_name_get(iname);
+    String *setname = Swig_name_set(iname);
+    String *vargetname = NewStringf("Swig_var_%s", getname);
+    String *varsetname = NewStringf("Swig_var_%s", setname);
+
+    /* Create a function for setting the value of the variable */
+    if (assignable) {
+      Setattr(n, "wrap:name", varsetname);
+      Printf(setf->def, "SWIGINTERN int %s(PyObject *_val) {", varsetname);
+      if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	Replaceall(tm, "$source", "_val");
+	Replaceall(tm, "$target", name);
+	Replaceall(tm, "$input", "_val");
+	if (Getattr(n, "tmap:varin:implicitconv")) {
+	  Replaceall(tm, "$implicitconv", get_implicitconv_flag(n));
+	}
+	emit_action_code(n, setf->code, tm);
+	Delete(tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
+      }
+      Printv(setf->code, ctab4, "return 0;\n", NULL);
+      Append(setf->code, "fail:\n");
+      Printv(setf->code, ctab4, "return 1;\n", NULL);
+    } else {
+      /* Is a readonly variable.  Issue an error */
+      if (CPlusPlus) {
+	Printf(setf->def, "SWIGINTERN int %s(PyObject *) {", varsetname);
+      } else {
+	Printf(setf->def, "SWIGINTERN int %s(PyObject *_val SWIGUNUSED) {", varsetname);
+      }
+      Printv(setf->code, ctab4, "SWIG_Error(SWIG_AttributeError,\"Variable ", iname, " is read-only.\");\n", ctab4, "return 1;\n", NIL);
+    }
+
+    Append(setf->code, "}\n");
+    Wrapper_print(setf, f_wrappers);
+
+    /* Create a function for getting the value of a variable */
+    Setattr(n, "wrap:name", vargetname);
+    int addfail = 0;
+    Printf(getf->def, "SWIGINTERN PyObject *%s(void) {", vargetname);
+    Wrapper_add_local(getf, "pyobj", "PyObject *pyobj = 0");
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+      Replaceall(tm, "$source", name);
+      Replaceall(tm, "$target", "pyobj");
+      Replaceall(tm, "$result", "pyobj");
+      addfail = emit_action_code(n, getf->code, tm);
+      Delete(tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+    }
+    Append(getf->code, "  return pyobj;\n");
+    if (addfail) {
+      Append(getf->code, "fail:\n");
+      Append(getf->code, "  return NULL;\n");
+    }
+    Append(getf->code, "}\n");
+
+    Wrapper_print(getf, f_wrappers);
+
+    /* Now add this to the variable linking mechanism */
+    Printf(f_init, "\t SWIG_addvarlink(SWIG_globals(),(char*)\"%s\",%s, %s);\n", iname, vargetname, varsetname);
+
+    Delete(vargetname);
+    Delete(varsetname);
+    Delete(getname);
+    Delete(setname);
+    DelWrapper(setf);
+    DelWrapper(getf);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+    String *tm;
+    int have_tm = 0;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    /* Special hook for member pointer */
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(iname);
+      String *str = SwigType_str(type, wname);
+      Printf(f_header, "static %s = %s;\n", str, value);
+      Delete(str);
+      value = wname;
+    }
+    if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Printf(const_code, "%s,\n", tm);
+      Delete(tm);
+      have_tm = 1;
+    }
+    if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Printf(f_init, "%s\n", tm);
+      Delete(tm);
+      have_tm = 1;
+    }
+    if (!have_tm) {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+    if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) {
+      if (!in_class) {
+	Printv(f_shadow, iname, " = ", module, ".", iname, "\n", NIL);
+      } else {
+	if (!(Getattr(n, "feature:python:callback"))) {
+	  Printv(f_shadow_stubs, iname, " = ", module, ".", iname, "\n", NIL);
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------ 
+   * nativeWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int nativeWrapper(Node *n) {
+    String *name = Getattr(n, "sym:name");
+    String *wrapname = Getattr(n, "wrap:name");
+
+    if (!addSymbol(wrapname, n))
+      return SWIG_ERROR;
+
+    add_method(name, wrapname, 0);
+    if (shadow) {
+      Printv(f_shadow_stubs, name, " = ", module, ".", name, "\n", NIL);
+    }
+    return SWIG_OK;
+  }
+
+
+
+/* ----------------------------------------------------------------------------
+ * BEGIN C++ Director Class modifications
+ * ------------------------------------------------------------------------- */
+
+/* C++/Python polymorphism demo code, copyright (C) 2002 Mark Rose <mrose@stm.lbl.gov>
+ *
+ * TODO
+ *
+ * Move some boilerplate code generation to Swig_...() functions.
+ *
+ */
+
+  /* ---------------------------------------------------------------
+   * classDirectorMethod()
+   *
+   * Emit a virtual director method to pass a method call on to the 
+   * underlying Python object.
+   * ** Moved down due to gcc-2.96 internal error **
+   * --------------------------------------------------------------- */
+
+  int classDirectorMethods(Node *n);
+
+  int classDirectorMethod(Node *n, Node *parent, String *super);
+
+  /* ------------------------------------------------------------
+   * classDirectorConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorConstructor(Node *n) {
+    Node *parent = Getattr(n, "parentNode");
+    String *sub = NewString("");
+    String *decl = Getattr(n, "decl");
+    String *supername = Swig_class_name(parent);
+    String *classname = NewString("");
+    Printf(classname, "SwigDirector_%s", supername);
+
+    /* insert self parameter */
+    Parm *p;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms = CopyParmList(superparms);
+    String *type = NewString("PyObject");
+    SwigType_add_pointer(type);
+    p = NewParm(type, NewString("self"));
+    set_nextSibling(p, parms);
+    parms = p;
+
+    if (!Getattr(n, "defaultargs")) {
+      /* constructor */
+      {
+	Wrapper *w = NewWrapper();
+	String *call;
+	String *basetype = Getattr(parent, "classtype");
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 0);
+	call = Swig_csuperclass_call(0, basetype, superparms);
+	Printf(w->def, "%s::%s: %s, Swig::Director(self) { \n", classname, target, call);
+	Printf(w->def, "   SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype);
+	Append(w->def, "}\n");
+	Delete(target);
+	Wrapper_print(w, f_directors);
+	Delete(call);
+	DelWrapper(w);
+      }
+
+      /* constructor header */
+      {
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 1);
+	Printf(f_directors_h, "    %s;\n", target);
+	Delete(target);
+      }
+    }
+
+    Delete(sub);
+    Delete(classname);
+    Delete(supername);
+    Delete(parms);
+    return Language::classDirectorConstructor(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorDefaultConstructor()
+   * ------------------------------------------------------------ */
+
+  int classDirectorDefaultConstructor(Node *n) {
+    String *classname = Swig_class_name(n);
+    {
+      Node *parent = Swig_methodclass(n);
+      String *basetype = Getattr(parent, "classtype");
+      Wrapper *w = NewWrapper();
+      Printf(w->def, "SwigDirector_%s::SwigDirector_%s(PyObject* self) : Swig::Director(self) { \n", classname, classname);
+      Printf(w->def, "   SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype);
+      Append(w->def, "}\n");
+      Wrapper_print(w, f_directors);
+      DelWrapper(w);
+    }
+    Printf(f_directors_h, "    SwigDirector_%s(PyObject* self);\n", classname);
+    Delete(classname);
+    return Language::classDirectorDefaultConstructor(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * classDirectorInit()
+   * ------------------------------------------------------------ */
+
+  int classDirectorInit(Node *n) {
+    String *declaration = Swig_director_declaration(n);
+    Printf(f_directors_h, "\n");
+    Printf(f_directors_h, "%s\n", declaration);
+    Printf(f_directors_h, "public:\n");
+    Delete(declaration);
+    return Language::classDirectorInit(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorEnd()
+   * ------------------------------------------------------------ */
+
+  int classDirectorEnd(Node *n) {
+    String *classname = Swig_class_name(n);
+
+    if (dirprot_mode()) {
+      /*
+         This implementation uses a std::map<std::string,int>.
+
+         It should be possible to rewrite it using a more elegant way,
+         like copying the Java approach for the 'override' array.
+
+         But for now, this seems to be the least intrusive way.
+       */
+      Printf(f_directors_h, "\n\n");
+      Printf(f_directors_h, "/* Internal Director utilities */\n");
+      Printf(f_directors_h, "public:\n");
+      Printf(f_directors_h, "    bool swig_get_inner(const char* name) const {\n");
+      Printf(f_directors_h, "      std::map<std::string, bool>::const_iterator iv = inner.find(name);\n");
+      Printf(f_directors_h, "      return (iv != inner.end() ? iv->second : false);\n");
+      Printf(f_directors_h, "    }\n\n");
+
+      Printf(f_directors_h, "    void swig_set_inner(const char* name, bool val) const\n");
+      Printf(f_directors_h, "    { inner[name] = val;}\n\n");
+      Printf(f_directors_h, "private:\n");
+      Printf(f_directors_h, "    mutable std::map<std::string, bool> inner;\n");
+
+    }
+    if (director_method_index) {
+      Printf(f_directors_h, "\n\n");
+      Printf(f_directors_h, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n");
+      Printf(f_directors_h, "/* VTable implementation */\n");
+      Printf(f_directors_h, "    PyObject *swig_get_method(size_t method_index, const char *method_name) const {\n");
+      Printf(f_directors_h, "      PyObject *method = vtable[method_index];\n");
+      Printf(f_directors_h, "      if (!method) {\n");
+      Printf(f_directors_h, "        swig::PyObject_var name = PyString_FromString(method_name);\n");
+      Printf(f_directors_h, "        method = PyObject_GetAttr(swig_get_self(), name);\n");
+      Printf(f_directors_h, "        if (method == NULL) {\n");
+      Printf(f_directors_h, "          std::string msg = \"Method in class %s doesn't exist, undefined \";\n", classname);
+      Printf(f_directors_h, "          msg += method_name;\n");
+      Printf(f_directors_h, "          Swig::DirectorMethodException::raise(msg.c_str());\n");
+      Printf(f_directors_h, "        }\n");
+      Printf(f_directors_h, "        vtable[method_index] = method;\n");
+      Printf(f_directors_h, "      };\n");
+      Printf(f_directors_h, "      return method;\n");
+      Printf(f_directors_h, "    }\n");
+      Printf(f_directors_h, "private:\n");
+      Printf(f_directors_h, "    mutable swig::PyObject_var vtable[%d];\n", director_method_index);
+      Printf(f_directors_h, "#endif\n\n");
+    }
+
+    Printf(f_directors_h, "};\n\n");
+    return Language::classDirectorEnd(n);
+  }
+
+
+  /* ------------------------------------------------------------
+   * classDirectorDisown()
+   * ------------------------------------------------------------ */
+
+  int classDirectorDisown(Node *n) {
+    int result;
+    int oldshadow = shadow;
+    /* disable shadowing */
+    if (shadow)
+      shadow = shadow | PYSHADOW_MEMBER;
+    result = Language::classDirectorDisown(n);
+    shadow = oldshadow;
+    if (shadow) {
+      String *symname = Getattr(n, "sym:name");
+      String *mrename = Swig_name_disown(symname);	//Getattr(n, "name"));
+      Printv(f_shadow, tab4, "def __disown__(self):\n", NIL);
+#ifdef USE_THISOWN
+      Printv(f_shadow, tab8, "self.thisown = 0\n", NIL);
+#else
+      Printv(f_shadow, tab8, "self.this.disown()\n", NIL);
+#endif
+      Printv(f_shadow, tab8, module, ".", mrename, "(self)\n", NIL);
+      Printv(f_shadow, tab8, "return weakref_proxy(self)\n", NIL);
+      Delete(mrename);
+    }
+    return result;
+  }
+
+/* ----------------------------------------------------------------------------
+ * END of C++ Director Class modifications
+ * ------------------------------------------------------------------------- */
+
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int classDeclaration(Node *n) {
+    if (shadow && !Getattr(n, "feature:onlychildren")) {
+      Node *mod = Getattr(n, "module");
+      if (mod) {
+	String *importname = NewString("");
+	String *modname = Getattr(mod, "name");
+	if (Strcmp(modname, mainmodule) != 0) {
+	  // check if the module has a package option
+	  Node *options = Getattr(mod, "options");
+	  String *pkg = options ? Getattr(options, "package") : 0;
+	  if (pkg && (!package || Strcmp(pkg, package) != 0)) {
+	    Printf(importname, "%s.", pkg);
+	  }
+	  Printf(importname, "%s.", modname);
+	}
+	Append(importname, Getattr(n, "sym:name"));
+	Setattr(n, "python:proxy", importname);
+      }
+    }
+    return Language::classDeclaration(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int classHandler(Node *n) {
+    int oldclassic = classic;
+    int oldmodern = modern;
+    File *f_shadow_file = f_shadow;
+
+    if (shadow) {
+
+      /* Create new strings for building up a wrapper function */
+      have_constructor = 0;
+      have_repr = 0;
+
+      if (GetFlag(n, "feature:classic")) {
+	classic = 1;
+	modern = 0;
+      }
+      if (GetFlag(n, "feature:modern")) {
+	classic = 0;
+	modern = 1;
+      }
+      if (GetFlag(n, "feature:exceptionclass")) {
+	classic = 1;
+	modern = 0;
+      }
+
+      shadow_indent = (String *) tab4;
+
+      class_name = Getattr(n, "sym:name");
+      real_classname = Getattr(n, "name");
+
+      if (!addSymbol(class_name, n))
+	return SWIG_ERROR;
+
+      /* Handle inheritance */
+      String *base_class = NewString("");
+      List *baselist = Getattr(n, "bases");
+      if (baselist && Len(baselist)) {
+	Iterator b;
+	b = First(baselist);
+	while (b.item) {
+	  String *bname = Getattr(b.item, "python:proxy");
+	  if (!bname || GetFlag(b.item, "feature:ignore")) {
+	    b = Next(b);
+	    continue;
+	  }
+	  Printv(base_class, bname, NIL);
+	  b = Next(b);
+	  if (b.item) {
+	    Putc(',', base_class);
+	  }
+	}
+      }
+      Printv(f_shadow, "class ", class_name, NIL);
+
+      if (Len(base_class)) {
+	Printf(f_shadow, "(%s)", base_class);
+      } else {
+	if (!classic) {
+	  Printf(f_shadow, modern ? "(object)" : "(_object)");
+	}
+      }
+      Printf(f_shadow, ":\n");
+      if (have_docstring(n)) {
+	String *str = docstring(n, AUTODOC_CLASS, tab4);
+	if (str != NULL && Len(str))
+	  Printv(f_shadow, tab4, str, "\n", NIL);
+      }
+      if (!modern) {
+	Printv(f_shadow, tab4, "__swig_setmethods__ = {}\n", NIL);
+	if (Len(base_class)) {
+	  Printf(f_shadow, "%sfor _s in [%s]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))\n", tab4, base_class);
+	}
+
+	if (!GetFlag(n, "feature:python:nondynamic")) {
+	  Printv(f_shadow, tab4, "__setattr__ = lambda self, name, value: _swig_setattr(self, ", class_name, ", name, value)\n", NIL);
+	} else {
+	  Printv(f_shadow, tab4, "__setattr__ = lambda self, name, value: _swig_setattr_nondynamic(self, ", class_name, ", name, value)\n", NIL);
+	}
+
+	Printv(f_shadow, tab4, "__swig_getmethods__ = {}\n", NIL);
+	if (Len(base_class)) {
+	  Printf(f_shadow, "%sfor _s in [%s]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))\n", tab4, base_class);
+	}
+
+	Printv(f_shadow, tab4, "__getattr__ = lambda self, name: _swig_getattr(self, ", class_name, ", name)\n", NIL);
+      } else {
+	Printv(f_shadow, tab4, "thisown = _swig_property(lambda x: x.this.own(), ", "lambda x, v: x.this.own(v), doc='The membership flag')\n", NIL);
+	/* Add static attribute */
+	if (GetFlag(n, "feature:python:nondynamic")) {
+	  Printv(f_shadow_file,
+		 tab4, "__setattr__ = _swig_setattr_nondynamic_method(object.__setattr__)\n",
+		 tab4, "class __metaclass__(type):\n", tab4, tab4, "__setattr__ = _swig_setattr_nondynamic_method(type.__setattr__)\n", NIL);
+	}
+      }
+    }
+
+    /* Emit all of the members */
+
+    in_class = 1;
+
+    /* Overide the shadow file so we can capture its methods */
+    f_shadow = NewString("");
+
+    Language::classHandler(n);
+    in_class = 0;
+
+    /* Complete the class */
+    if (shadow) {
+      /* Generate a class registration function */
+      {
+        String *smartptr = Getattr(n, "feature:smartptr"); // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers)
+        SwigType *smart = 0;
+        if (smartptr) {
+          SwigType *cpt = Swig_cparse_type(smartptr);
+          if (cpt) {
+            smart = SwigType_typedef_resolve_all(cpt);
+            Delete(cpt);
+          } else {
+            // TODO: report line number of where the feature comes from
+            Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, real_classname);
+          }
+        }
+	SwigType *ct = Copy(smart ? smart : real_classname);
+        SwigType_add_pointer(ct);
+	SwigType *realct = Copy(real_classname);
+        SwigType_add_pointer(realct);
+	SwigType_remember(realct);
+	Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL);
+	Printv(f_wrappers, ctab4, "PyObject *obj;\n", NIL);
+	if (modernargs) {
+	  if (fastunpack) {
+	    Printv(f_wrappers, ctab4, "if (!SWIG_Python_UnpackTuple(args,(char*)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL);
+	  } else {
+	    Printv(f_wrappers, ctab4, "if (!PyArg_UnpackTuple(args,(char*)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL);
+	  }
+	} else {
+	  Printv(f_wrappers, ctab4, "if (!PyArg_ParseTuple(args,(char*)\"O:swigregister\", &obj)) return NULL;\n", NIL);
+	}
+
+	Printv(f_wrappers,
+	       ctab4, "SWIG_TypeNewClientData(SWIGTYPE", SwigType_manglestr(ct), ", SWIG_NewClientData(obj));\n",
+	       ctab4, "return SWIG_Py_Void();\n", "}\n\n", NIL);
+	String *cname = NewStringf("%s_swigregister", class_name);
+	add_method(cname, cname, 0);
+	Delete(smart);
+	Delete(cname);
+	Delete(ct);
+	Delete(realct);
+      }
+      if (!have_constructor) {
+	Printv(f_shadow_file, tab4, "def __init__(self, *args, **kwargs): raise AttributeError, \"No constructor defined\"\n", NIL);
+      } else if (fastinit) {
+
+	Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL);
+	Printv(f_wrappers, ctab4, "return SWIG_Python_InitShadowInstance(args);\n", "}\n\n", NIL);
+	String *cname = NewStringf("%s_swiginit", class_name);
+	add_method(cname, cname, 0);
+	Delete(cname);
+      }
+      if (!have_repr) {
+	/* Supply a repr method for this class  */
+	String *rname = SwigType_namestr(real_classname);
+	if (new_repr) {
+	  Printv(f_shadow_file, tab4, "__repr__ = _swig_repr\n", NIL);
+	} else {
+	  Printv(f_shadow_file, tab4, "def __repr__(self):\n", tab8, "return \"<C ", rname, " instance at 0x%x>\" % (self.this,)\n", NIL);
+	}
+	Delete(rname);
+      }
+
+
+      /* Now emit methods */
+      Printv(f_shadow_file, f_shadow, NIL);
+
+      /* Now the Ptr class */
+      if (classptr) {
+	Printv(f_shadow_file, "\nclass ", class_name, "Ptr(", class_name, "):\n", tab4, "def __init__(self, this):\n", NIL);
+	if (!modern) {
+	  Printv(f_shadow_file,
+		 tab8, "try: self.this.append(this)\n",
+		 tab8, "except: self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL);
+	} else {
+	  Printv(f_shadow_file,
+		 tab8, "try: self.this.append(this)\n",
+		 tab8, "except: self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL);
+	}
+      }
+
+      if (fastproxy) {
+	List *shadow_list = Getattr(n, "shadow_methods");
+	for (int i = 0; i < Len(shadow_list); ++i) {
+	  String *symname = Getitem(shadow_list, i);
+	  Printf(f_shadow_file, "%s.%s = new_instancemethod(%s.%s,None,%s)\n", class_name, symname, module, Swig_name_member(class_name, symname), class_name);
+	}
+      }
+      Printf(f_shadow_file, "%s_swigregister = %s.%s_swigregister\n", class_name, module, class_name);
+      Printf(f_shadow_file, "%s_swigregister(%s)\n", class_name, class_name);
+
+      shadow_indent = 0;
+      Printf(f_shadow_file, "%s\n", f_shadow_stubs);
+      Clear(f_shadow_stubs);
+    }
+    classic = oldclassic;
+    modern = oldmodern;
+
+    /* Restore shadow file back to original version */
+    Delete(f_shadow);
+    f_shadow = f_shadow_file;
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * functionHandler()  -  Mainly overloaded for callback handling
+   * ------------------------------------------------------------ */
+
+  virtual int functionHandler(Node *n) {
+    String *pcb = GetFlagAttr(n, "feature:python:callback");
+    if (pcb) {
+      if (Strcmp(pcb, "1") == 0) {
+	SetFlagAttr(n, "feature:callback", "%s_cb_ptr");
+      } else {
+	SetFlagAttr(n, "feature:callback", pcb);
+      }
+      autodoc_l dlevel = autodoc_level(Getattr(n, "feature:autodoc"));
+      if (dlevel != NO_AUTODOC && dlevel > TYPES_AUTODOC) {
+	Setattr(n, "feature:autodoc", "1");
+      }
+    }
+    return Language::functionHandler(n);
+  }
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberfunctionHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    int oldshadow;
+
+    /* Create the default member function */
+    oldshadow = shadow;		/* Disable shadowing when wrapping member functions */
+    if (shadow)
+      shadow = shadow | PYSHADOW_MEMBER;
+    Language::memberfunctionHandler(n);
+    shadow = oldshadow;
+
+    if (!Getattr(n, "sym:nextSibling")) {
+      if (shadow) {
+	int allow_kwargs = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0;
+	int fproxy = fastproxy;
+	if (Strcmp(symname, "__repr__") == 0) {
+	  have_repr = 1;
+	}
+	if (Getattr(n, "feature:shadow")) {
+	  String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4);
+	  String *pyaction = NewStringf("%s.%s", module, Swig_name_member(class_name, symname));
+	  Replaceall(pycode, "$action", pyaction);
+	  Delete(pyaction);
+	  Printv(f_shadow, pycode, "\n", NIL);
+	  Delete(pycode);
+	  fproxy = 0;
+	} else {
+	  if (!have_addtofunc(n)) {
+	    if (!fastproxy || olddefs) {
+	      Printv(f_shadow, tab4, "def ", symname, "(*args", (allow_kwargs ? ", **kwargs" : ""), "):", NIL);
+	      Printv(f_shadow, " return ", funcCallHelper(Swig_name_member(class_name, symname), allow_kwargs), "\n", NIL);
+	    }
+	  } else {
+	    Printv(f_shadow, tab4, "def ", symname, "(*args", (allow_kwargs ? ", **kwargs" : ""), "):", NIL);
+	    Printv(f_shadow, "\n", NIL);
+	    if (have_docstring(n))
+	      Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD, tab8), "\n", NIL);
+	    if (have_pythonprepend(n)) {
+	      fproxy = 0;
+	      Printv(f_shadow, tab8, pythonprepend(n), "\n", NIL);
+	    }
+	    if (have_pythonappend(n)) {
+	      fproxy = 0;
+	      Printv(f_shadow, tab8, "val = ", funcCallHelper(Swig_name_member(class_name, symname), allow_kwargs), "\n", NIL);
+	      Printv(f_shadow, tab8, pythonappend(n), "\n", NIL);
+	      Printv(f_shadow, tab8, "return val\n\n", NIL);
+	    } else {
+	      Printv(f_shadow, tab8, "return ", funcCallHelper(Swig_name_member(class_name, symname), allow_kwargs), "\n\n", NIL);
+	    }
+	  }
+	}
+	if (fproxy) {
+	  List *shadow_list = Getattr(getCurrentClass(), "shadow_methods");
+	  if (!shadow_list) {
+	    shadow_list = NewList();
+	    Setattr(getCurrentClass(), "shadow_methods", shadow_list);
+	    Delete(shadow_list);
+	  }
+	  Append(shadow_list, symname);
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    Language::staticmemberfunctionHandler(n);
+
+    if (Getattr(n, "sym:nextSibling")) {
+      return SWIG_OK;
+    }
+
+    if (shadow) {
+      if (!classic && !Getattr(n, "feature:python:callback") && have_addtofunc(n)) {
+	int kw = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0;
+	Printv(f_shadow, tab4, "def ", symname, "(*args", (kw ? ", **kwargs" : ""), "):\n", NIL);
+	if (have_docstring(n))
+	  Printv(f_shadow, tab8, docstring(n, AUTODOC_STATICFUNC, tab8), "\n", NIL);
+	if (have_pythonprepend(n))
+	  Printv(f_shadow, tab8, pythonprepend(n), "\n", NIL);
+	if (have_pythonappend(n)) {
+	  Printv(f_shadow, tab8, "val = ", funcCallHelper(Swig_name_member(class_name, symname), kw), "\n", NIL);
+	  Printv(f_shadow, tab8, pythonappend(n), "\n", NIL);
+	  Printv(f_shadow, tab8, "return val\n\n", NIL);
+	} else {
+	  Printv(f_shadow, tab8, "return ", funcCallHelper(Swig_name_member(class_name, symname), kw), "\n\n", NIL);
+	}
+	Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = staticmethod(", symname, ")\n", NIL);
+
+	if (!modern) {
+	  Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = lambda x: ", symname, "\n", NIL);
+	}
+
+      } else {
+	if (!modern) {
+	  Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = lambda x: ", module, ".", Swig_name_member(class_name, symname), "\n", NIL);
+	}
+	if (!classic) {
+	  Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = staticmethod(", module, ".", Swig_name_member(class_name, symname), ")\n", NIL);
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constructorDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int constructorHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    int oldshadow = shadow;
+    int use_director = Swig_directorclass(n);
+
+    /* 
+     * If we're wrapping the constructor of a C++ director class, prepend a new parameter
+     * to receive the scripting language object (e.g. 'self')
+     *
+     */
+    Swig_save("python:constructorHandler", n, "parms", NIL);
+    if (use_director) {
+      Parm *parms = Getattr(n, "parms");
+      Parm *self;
+      String *name = NewString("self");
+      String *type = NewString("PyObject");
+      SwigType_add_pointer(type);
+      self = NewParm(type, name);
+      Delete(type);
+      Delete(name);
+      Setattr(self, "lname", "O");
+      if (parms)
+	set_nextSibling(self, parms);
+      Setattr(n, "parms", self);
+      Setattr(n, "wrap:self", "1");
+      Setattr(n, "hidden", "1");
+      Delete(self);
+    }
+
+    if (shadow)
+      shadow = shadow | PYSHADOW_MEMBER;
+    Language::constructorHandler(n);
+    shadow = oldshadow;
+
+    Delattr(n, "wrap:self");
+    Swig_restore(n);
+
+    if (!Getattr(n, "sym:nextSibling")) {
+      if (shadow) {
+	int allow_kwargs = (check_kwargs(n) && (!Getattr(n, "sym:overloaded"))) ? 1 : 0;
+	int handled_as_init = 0;
+	if (!have_constructor) {
+	  String *nname = Getattr(n, "sym:name");
+	  String *sname = Getattr(getCurrentClass(), "sym:name");
+	  String *cname = Swig_name_construct(sname);
+	  handled_as_init = (Strcmp(nname, sname) == 0) || (Strcmp(nname, cname) == 0);
+	  Delete(cname);
+	}
+
+	if (!have_constructor && handled_as_init) {
+	  if (Getattr(n, "feature:shadow")) {
+	    String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4);
+	    String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(symname));
+	    Replaceall(pycode, "$action", pyaction);
+	    Delete(pyaction);
+	    Printv(f_shadow, pycode, "\n", NIL);
+	    Delete(pycode);
+	  } else {
+	    String *pass_self = NewString("");
+	    Node *parent = Swig_methodclass(n);
+	    String *classname = Swig_class_name(parent);
+	    String *rclassname = Swig_class_name(getCurrentClass());
+	    assert(rclassname);
+	    if (use_director) {
+	      Printv(pass_self, tab8, NIL);
+	      Printf(pass_self, "if self.__class__ == %s:\n", classname);
+	      Printv(pass_self, tab8, tab4, "args = (None,) + args\n", tab8, "else:\n", tab8, tab4, "args = (self,) + args\n", NIL);
+	    }
+
+	    Printv(f_shadow, tab4, "def __init__(self, *args", (allow_kwargs ? ", **kwargs" : ""), "): \n", NIL);
+	    if (have_docstring(n))
+	      Printv(f_shadow, tab8, docstring(n, AUTODOC_CTOR, tab8), "\n", NIL);
+	    if (have_pythonprepend(n))
+	      Printv(f_shadow, tab8, pythonprepend(n), "\n", NIL);
+	    Printv(f_shadow, pass_self, NIL);
+	    if (fastinit) {
+	      Printv(f_shadow, tab8, module, ".", class_name, "_swiginit(self,", funcCallHelper(Swig_name_construct(symname), allow_kwargs), ")\n", NIL);
+	    } else {
+	      Printv(f_shadow,
+		     tab8, "this = ", funcCallHelper(Swig_name_construct(symname), allow_kwargs), "\n",
+		     tab8, "try: self.this.append(this)\n", tab8, "except: self.this = this\n", NIL);
+	    }
+	    if (have_pythonappend(n))
+	      Printv(f_shadow, tab8, pythonappend(n), "\n\n", NIL);
+	    Delete(pass_self);
+	  }
+	  have_constructor = 1;
+	} else {
+	  /* Hmmm. We seem to be creating a different constructor.  We're just going to create a
+	     function for it. */
+
+	  if (Getattr(n, "feature:shadow")) {
+	    String *pycode = pythoncode(Getattr(n, "feature:shadow"), "");
+	    String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(symname));
+	    Replaceall(pycode, "$action", pyaction);
+	    Delete(pyaction);
+	    Printv(f_shadow_stubs, pycode, "\n", NIL);
+	    Delete(pycode);
+	  } else {
+
+	    Printv(f_shadow_stubs, "\ndef ", symname, "(*args", (allow_kwargs ? ", **kwargs" : ""), "):\n", NIL);
+	    if (have_docstring(n))
+	      Printv(f_shadow_stubs, tab4, docstring(n, AUTODOC_CTOR, tab4), "\n", NIL);
+	    if (have_pythonprepend(n))
+	      Printv(f_shadow_stubs, tab4, pythonprepend(n), "\n", NIL);
+	    Printv(f_shadow_stubs, tab4, "val = ", funcCallHelper(Swig_name_construct(symname), allow_kwargs), "\n", NIL);
+#ifdef USE_THISOWN
+	    Printv(f_shadow_stubs, tab4, "val.thisown = 1\n", NIL);
+#endif
+	    if (have_pythonappend(n))
+	      Printv(f_shadow_stubs, tab4, pythonappend(n), "\n", NIL);
+	    Printv(f_shadow_stubs, tab4, "return val\n", NIL);
+	  }
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * destructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int destructorHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    int oldshadow = shadow;
+
+    if (shadow)
+      shadow = shadow | PYSHADOW_MEMBER;
+    //Setattr(n,"emit:dealloc","1");
+    Language::destructorHandler(n);
+    shadow = oldshadow;
+    if (shadow) {
+      if (Getattr(n, "feature:shadow")) {
+	String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4);
+	String *pyaction = NewStringf("%s.%s", module, Swig_name_destroy(symname));
+	Replaceall(pycode, "$action", pyaction);
+	Delete(pyaction);
+	Printv(f_shadow, pycode, "\n", NIL);
+	Delete(pycode);
+      } else {
+	Printv(f_shadow, tab4, "__swig_destroy__ = ", module, ".", Swig_name_destroy(symname), "\n", NIL);
+	if (!have_pythonprepend(n) && !have_pythonappend(n)) {
+	  if (proxydel) {
+	    Printv(f_shadow, tab4, "__del__ = lambda self : None;\n", NIL);
+	  }
+	  return SWIG_OK;
+	}
+	Printv(f_shadow, tab4, "def __del__(self):\n", NIL);
+	if (have_docstring(n))
+	  Printv(f_shadow, tab8, docstring(n, AUTODOC_DTOR, tab8), "\n", NIL);
+	if (have_pythonprepend(n))
+	  Printv(f_shadow, tab8, pythonprepend(n), "\n", NIL);
+#ifdef USE_THISOWN
+	Printv(f_shadow, tab8, "try:\n", NIL);
+	Printv(f_shadow, tab8, tab4, "if self.thisown: ", module, ".", Swig_name_destroy(symname), "(self)\n", NIL);
+	Printv(f_shadow, tab8, "except: pass\n", NIL);
+#else
+#endif
+	if (have_pythonappend(n))
+	  Printv(f_shadow, tab8, pythonappend(n), "\n", NIL);
+	Printv(f_shadow, tab8, "pass\n", NIL);
+	Printv(f_shadow, "\n", NIL);
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int membervariableHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+
+    int oldshadow = shadow;
+    if (shadow)
+      shadow = shadow | PYSHADOW_MEMBER;
+    Language::membervariableHandler(n);
+    shadow = oldshadow;
+
+    if (shadow) {
+      String *mname = Swig_name_member(class_name, symname);
+      String *setname = Swig_name_set(mname);
+      String *getname = Swig_name_get(mname);
+      if (shadow) {
+	int assignable = is_assignable(n);
+	if (!modern) {
+	  if (assignable) {
+	    Printv(f_shadow, tab4, "__swig_setmethods__[\"", symname, "\"] = ", module, ".", setname, "\n", NIL);
+	  }
+	  Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = ", module, ".", getname, "\n", NIL);
+	}
+	if (!classic) {
+	  if (!assignable) {
+	    Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ")\n", NIL);
+	  } else {
+	    Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ", ", module, ".", setname, ")\n", NIL);
+	  }
+	}
+      }
+      Delete(mname);
+      Delete(setname);
+      Delete(getname);
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * staticmembervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int staticmembervariableHandler(Node *n) {
+    Language::staticmembervariableHandler(n);
+
+    if (shadow && !GetFlag(n, "wrappedasconstant")) {
+      String *symname = Getattr(n, "sym:name");
+      if (GetFlag(n, "hasconsttype")) {
+	String *mname = Swig_name_member(class_name, symname);
+	Printf(f_shadow_stubs, "%s.%s = %s.%s.%s\n", class_name, symname, module, global_name, mname);
+	Delete(mname);
+      } else {
+	String *mname = Swig_name_member(class_name, symname);
+	String *getname = Swig_name_get(mname);
+	String *wrapgetname = Swig_name_wrapper(getname);
+        String *vargetname = NewStringf("Swig_var_%s", getname);
+	String *setname = Swig_name_set(mname);
+	String *wrapsetname = Swig_name_wrapper(setname);
+        String *varsetname = NewStringf("Swig_var_%s", setname);
+
+	Wrapper *f = NewWrapper();
+	Printv(f->def, "SWIGINTERN PyObject *", wrapgetname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(args)) {", NIL);
+	Printv(f->code, "  return ", vargetname, "();\n", NIL);
+	Append(f->code, "}\n");
+	add_method(getname, wrapgetname, 0);
+	Wrapper_print(f, f_wrappers);
+	DelWrapper(f);
+	int assignable = is_assignable(n);
+	if (assignable) {
+	  Wrapper *f = NewWrapper();
+	  Printv(f->def, "SWIGINTERN PyObject *", wrapsetname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL);
+	  Wrapper_add_local(f, "value", "PyObject *value");
+	  Wrapper_add_local(f, "res", "int res");
+	  Append(f->code, "if (!PyArg_ParseTuple(args,(char *)\"O:set\",&value)) return NULL;\n");
+	  Printv(f->code, "res = ", varsetname, "(value);\n", NIL);
+	  Append(f->code, "return !res ? SWIG_Py_Void() : NULL;\n");
+	  Append(f->code, "}\n");
+	  Wrapper_print(f, f_wrappers);
+	  add_method(setname, wrapsetname, 0);
+	  DelWrapper(f);
+	}
+	if (!modern) {
+	  if (assignable) {
+	    Printv(f_shadow, tab4, "__swig_setmethods__[\"", symname, "\"] = ", module, ".", setname, "\n", NIL);
+	  }
+	  Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = ", module, ".", getname, "\n", NIL);
+	}
+	if (!classic) {
+	  if (!assignable) {
+	    Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ")\n", NIL);
+	  } else {
+	    Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ", ", module, ".", setname, ")\n", NIL);
+	  }
+	}
+	Delete(mname);
+	Delete(getname);
+	Delete(wrapgetname);
+	Delete(vargetname);
+	Delete(setname);
+	Delete(wrapsetname);
+	Delete(varsetname);
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * memberconstantHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberconstantHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    int oldshadow = shadow;
+    if (shadow)
+      shadow = shadow | PYSHADOW_MEMBER;
+    Language::memberconstantHandler(n);
+    shadow = oldshadow;
+
+    if (shadow) {
+      Printv(f_shadow, tab4, symname, " = ", module, ".", Swig_name_member(class_name, symname), "\n", NIL);
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * insertDirective()
+   * 
+   * Hook for %insert directive.   We're going to look for special %shadow inserts
+   * as a special case so we can do indenting correctly
+   * ------------------------------------------------------------ */
+
+  virtual int insertDirective(Node *n) {
+    String *code = Getattr(n, "code");
+    String *section = Getattr(n, "section");
+
+    if ((!ImportMode) && ((Cmp(section, "python") == 0) || (Cmp(section, "shadow") == 0))) {
+      if (shadow) {
+	String *pycode = pythoncode(code, shadow_indent);
+	Printv(f_shadow, pycode, NIL);
+	Delete(pycode);
+      }
+    } else {
+      Language::insertDirective(n);
+    }
+    return SWIG_OK;
+  }
+
+  virtual String *runtimeCode() {
+    String *s = NewString("");
+    String *shead = Swig_include_sys("pyhead.swg");
+    if (!shead) {
+      Printf(stderr, "*** Unable to open 'pyhead.swg'\n");
+    } else {
+      Append(s, shead);
+      Delete(shead);
+    }
+    String *serrors = Swig_include_sys("pyerrors.swg");
+    if (!serrors) {
+      Printf(stderr, "*** Unable to open 'pyerrors.swg'\n");
+    } else {
+      Append(s, serrors);
+      Delete(serrors);
+    }
+    String *sthread = Swig_include_sys("pythreads.swg");
+    if (!sthread) {
+      Printf(stderr, "*** Unable to open 'pythreads.swg'\n");
+    } else {
+      Append(s, sthread);
+      Delete(sthread);
+    }
+    String *sapi = Swig_include_sys("pyapi.swg");
+    if (!sapi) {
+      Printf(stderr, "*** Unable to open 'pyapi.swg'\n");
+    } else {
+      Append(s, sapi);
+      Delete(sapi);
+    }
+    String *srun = Swig_include_sys("pyrun.swg");
+    if (!srun) {
+      Printf(stderr, "*** Unable to open 'pyrun.swg'\n");
+    } else {
+      Append(s, srun);
+      Delete(srun);
+    }
+    return s;
+  }
+
+  virtual String *defaultExternalRuntimeFilename() {
+    return NewString("swigpyrun.h");
+  }
+
+};
+
+/* ---------------------------------------------------------------
+ * classDirectorMethod()
+ *
+ * Emit a virtual director method to pass a method call on to the 
+ * underlying Python object.
+ *
+ * ** Moved it here due to internal error on gcc-2.96 **
+ * --------------------------------------------------------------- */
+int PYTHON::classDirectorMethods(Node *n) {
+  director_method_index = 0;
+  return Language::classDirectorMethods(n);
+}
+
+
+int PYTHON::classDirectorMethod(Node *n, Node *parent, String *super) {
+  int is_void = 0;
+  int is_pointer = 0;
+  String *decl;
+  String *type;
+  String *name;
+  String *classname;
+  String *c_classname = Getattr(parent, "name");
+  String *declaration;
+  ParmList *l;
+  Wrapper *w;
+  String *tm;
+  String *wrap_args = NewString("");
+  String *return_type;
+  String *value = Getattr(n, "value");
+  String *storage = Getattr(n, "storage");
+  bool pure_virtual = false;
+  int status = SWIG_OK;
+  int idx;
+  bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
+
+  if (Cmp(storage, "virtual") == 0) {
+    if (Cmp(value, "0") == 0) {
+      pure_virtual = true;
+    }
+  }
+
+  classname = Getattr(parent, "sym:name");
+  type = Getattr(n, "type");
+  name = Getattr(n, "name");
+
+  w = NewWrapper();
+  declaration = NewString("");
+
+  /* determine if the method returns a pointer */
+  decl = Getattr(n, "decl");
+  is_pointer = SwigType_ispointer_return(decl);
+  is_void = (!Cmp(type, "void") && !is_pointer);
+
+  /* form complete return type */
+  return_type = Copy(type);
+  {
+    SwigType *t = Copy(decl);
+    SwigType *f = 0;
+    f = SwigType_pop_function(t);
+    SwigType_push(return_type, t);
+    Delete(f);
+    Delete(t);
+  }
+
+  /* virtual method definition */
+  l = Getattr(n, "parms");
+  String *target;
+  String *pclassname = NewStringf("SwigDirector_%s", classname);
+  String *qualified_name = NewStringf("%s::%s", pclassname, name);
+  SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type;
+  target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0);
+  Printf(w->def, "%s", target);
+  Delete(qualified_name);
+  Delete(target);
+  /* header declaration */
+  target = Swig_method_decl(rtype, decl, name, l, 0, 1);
+  Printf(declaration, "    virtual %s", target);
+  Delete(target);
+
+  // Get any exception classes in the throws typemap
+  ParmList *throw_parm_list = 0;
+
+  if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) {
+    Parm *p;
+    int gencomma = 0;
+
+    Append(w->def, " throw(");
+    Append(declaration, " throw(");
+
+    if (throw_parm_list)
+      Swig_typemap_attach_parms("throws", throw_parm_list, 0);
+    for (p = throw_parm_list; p; p = nextSibling(p)) {
+      if ((tm = Getattr(p, "tmap:throws"))) {
+	if (gencomma++) {
+	  Append(w->def, ", ");
+	  Append(declaration, ", ");
+	}
+	String *str = SwigType_str(Getattr(p, "type"), 0);
+	Append(w->def, str);
+	Append(declaration, str);
+	Delete(str);
+      }
+    }
+
+    Append(w->def, ")");
+    Append(declaration, ")");
+  }
+
+  Append(w->def, " {");
+  Append(declaration, ";\n");
+
+  /* declare method return value 
+   * if the return value is a reference or const reference, a specialized typemap must
+   * handle it, including declaration of c_result ($result).
+   */
+  if (!is_void) {
+    if (!(ignored_method && !pure_virtual)) {
+      String *cres = SwigType_lstr(return_type, "c_result");
+      Printf(w->code, "%s;\n", cres);
+      Delete(cres);
+    }
+  }
+
+  if (ignored_method) {
+    if (!pure_virtual) {
+      if (!is_void)
+	Printf(w->code, "return ");
+      String *super_call = Swig_method_call(super, l);
+      Printf(w->code, "%s;\n", super_call);
+      Delete(super_call);
+    } else {
+      Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname),
+	     SwigType_namestr(name));
+    }
+  } else {
+    /* attach typemaps to arguments (C/C++ -> Python) */
+    String *arglist = NewString("");
+    String *parse_args = NewString("");
+
+    /* remove the wrapper 'w' since it was producing spurious temps */
+    Swig_typemap_attach_parms("in", l, 0);
+    Swig_typemap_attach_parms("directorin", l, 0);
+    Swig_typemap_attach_parms("directorargout", l, w);
+
+    Parm *p;
+    char source[256];
+
+    int outputs = 0;
+    if (!is_void)
+      outputs++;
+
+    /* build argument list and type conversion string */
+    idx = 0;
+    p = l;
+    int use_parse = 0;
+    while (p != NULL) {
+      if (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      }
+
+      /* old style?  caused segfaults without the p!=0 check
+         in the for() condition, and seems dangerous in the
+         while loop as well.
+         while (Getattr(p, "tmap:ignore")) {
+         p = Getattr(p, "tmap:ignore:next");
+         }
+       */
+
+      if (Getattr(p, "tmap:directorargout") != 0)
+	outputs++;
+
+      String *pname = Getattr(p, "name");
+      String *ptype = Getattr(p, "type");
+
+      Putc(',', arglist);
+      if ((tm = Getattr(p, "tmap:directorin")) != 0) {
+	String *parse = Getattr(p, "tmap:directorin:parse");
+	if (!parse) {
+	  sprintf(source, "obj%d", idx++);
+	  String *input = NewString(source);
+	  Replaceall(tm, "$input", input);
+	  Delete(input);
+	  Replaceall(tm, "$owner", "0");
+	  /* Wrapper_add_localv(w, source, "swig::PyObject_var", source, "= 0", NIL); */
+	  Printv(wrap_args, "swig::PyObject_var ", source, ";\n", NIL);
+
+	  Printv(wrap_args, tm, "\n", NIL);
+	  Printv(arglist, "(PyObject *)", source, NIL);
+	  Putc('O', parse_args);
+	} else {
+	  use_parse = 1;
+	  Append(parse_args, parse);
+	  Replaceall(tm, "$input", pname);
+	  Replaceall(tm, "$owner", "0");
+	  if (Len(tm) == 0)
+	    Append(tm, pname);
+	  Append(arglist, tm);
+	}
+	p = Getattr(p, "tmap:directorin:next");
+	continue;
+      } else if (Cmp(ptype, "void")) {
+	/* special handling for pointers to other C++ director classes.
+	 * ideally this would be left to a typemap, but there is currently no
+	 * way to selectively apply the dynamic_cast<> to classes that have
+	 * directors.  in other words, the type "SwigDirector_$1_lname" only exists
+	 * for classes with directors.  we avoid the problem here by checking
+	 * module.wrap::directormap, but it's not clear how to get a typemap to
+	 * do something similar.  perhaps a new default typemap (in addition
+	 * to SWIGTYPE) called DIRECTORTYPE?
+	 */
+	if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) {
+	  Node *module = Getattr(parent, "module");
+	  Node *target = Swig_directormap(module, ptype);
+	  sprintf(source, "obj%d", idx++);
+	  String *nonconst = 0;
+	  /* strip pointer/reference --- should move to Swig/stype.c */
+	  String *nptype = NewString(Char(ptype) + 2);
+	  /* name as pointer */
+	  String *ppname = Copy(pname);
+	  if (SwigType_isreference(ptype)) {
+	    Insert(ppname, 0, "&");
+	  }
+	  /* if necessary, cast away const since Python doesn't support it! */
+	  if (SwigType_isconst(nptype)) {
+	    nonconst = NewStringf("nc_tmp_%s", pname);
+	    String *nonconst_i = NewStringf("= const_cast<%s>(%s)", SwigType_lstr(ptype, 0), ppname);
+	    Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL);
+	    Delete(nonconst_i);
+	    Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number,
+			 "Target language argument '%s' discards const in director method %s::%s.\n",
+			 SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name));
+	  } else {
+	    nonconst = Copy(ppname);
+	  }
+	  Delete(nptype);
+	  Delete(ppname);
+	  String *mangle = SwigType_manglestr(ptype);
+	  if (target) {
+	    String *director = NewStringf("director_%s", mangle);
+	    Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL);
+	    Wrapper_add_localv(w, source, "swig::PyObject_var", source, "= 0", NIL);
+	    Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst);
+	    Printf(wrap_args, "if (!%s) {\n", director);
+	    Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
+	    Append(wrap_args, "} else {\n");
+	    Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director);
+	    Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source);
+	    Append(wrap_args, "}\n");
+	    Delete(director);
+	    Printv(arglist, source, NIL);
+	  } else {
+	    Wrapper_add_localv(w, source, "swig::PyObject_var", source, "= 0", NIL);
+	    Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
+	    //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", 
+	    //       source, nonconst, base);
+	    Printv(arglist, source, NIL);
+	  }
+	  Putc('O', parse_args);
+	  Delete(mangle);
+	  Delete(nonconst);
+	} else {
+	  Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
+		       "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0),
+		       SwigType_namestr(c_classname), SwigType_namestr(name));
+	  status = SWIG_NOWRAP;
+	  break;
+	}
+      }
+      p = nextSibling(p);
+    }
+
+    /* add the method name as a PyString */
+    String *pyname = Getattr(n, "sym:name");
+
+    int allow_thread = threads_enable(n);
+
+    if (allow_thread)
+      thread_begin_block(n, w->code);
+
+    if (allow_thread) {
+      Append(w->code, "{\n");
+    }
+
+    /* wrap complex arguments to PyObjects */
+    Printv(w->code, wrap_args, NIL);
+
+    /* pass the method call on to the Python object */
+    if (dirprot_mode() && !is_public(n)) {
+      Printf(w->code, "swig_set_inner(\"%s\", true);\n", name);
+    }
+
+
+    Append(w->code, "if (!swig_get_self()) {\n");
+    Printf(w->code, "  Swig::DirectorException::raise(\"'self' uninitialized, maybe you forgot to call %s.__init__.\");\n", classname);
+    Append(w->code, "}\n");
+    Append(w->code, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n");
+    Printf(w->code, "const size_t swig_method_index = %d;\n", director_method_index++);
+    Printf(w->code, "const char * const swig_method_name = \"%s\";\n", pyname);
+
+    Append(w->code, "PyObject* method = swig_get_method(swig_method_index, swig_method_name);\n");
+    if (Len(parse_args) > 0) {
+      if (use_parse || !modernargs) {
+	Printf(w->code, "swig::PyObject_var result = PyObject_CallFunction(method, (char *)\"(%s)\" %s);\n", parse_args, arglist);
+      } else {
+	Printf(w->code, "swig::PyObject_var result = PyObject_CallFunctionObjArgs(method %s, NULL);\n", arglist);
+      }
+    } else {
+      if (modernargs) {
+	Append(w->code, "swig::PyObject_var args = PyTuple_New(0);\n");
+	Append(w->code, "swig::PyObject_var result = PyObject_Call(method, (PyObject*) args, NULL);\n");
+      } else {
+	Printf(w->code, "swig::PyObject_var result = PyObject_CallFunction(method, NULL, NULL);\n");
+      }
+    }
+    Append(w->code, "#else\n");
+    if (Len(parse_args) > 0) {
+      if (use_parse || !modernargs) {
+	Printf(w->code, "swig::PyObject_var result = PyObject_CallMethod(swig_get_self(), (char *)\"%s\", (char *)\"(%s)\" %s);\n",
+	       pyname, parse_args, arglist);
+      } else {
+	Printf(w->code, "swig::PyObject_var swig_method_name = PyString_FromString((char *)\"%s\");\n", pyname);
+	Printf(w->code, "swig::PyObject_var result = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name %s, NULL);\n", arglist);
+      }
+    } else {
+      if (!modernargs) {
+	Printf(w->code, "swig::PyObject_var result = PyObject_CallMethod(swig_get_self(), (char *) \"%s\", NULL);\n", pyname);
+      } else {
+	Printf(w->code, "swig::PyObject_var swig_method_name = PyString_FromString((char *)\"%s\");\n", pyname);
+	Append(w->code, "swig::PyObject_var result = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name, NULL);\n");
+      }
+    }
+    Append(w->code, "#endif\n");
+
+    if (dirprot_mode() && !is_public(n))
+      Printf(w->code, "swig_set_inner(\"%s\", false);\n", name);
+
+    /* exception handling */
+    tm = Swig_typemap_lookup("director:except", n, "result", 0);
+    if (!tm) {
+      tm = Getattr(n, "feature:director:except");
+      if (tm)
+	tm = Copy(tm);
+    }
+    Append(w->code, "if (result == NULL) {\n");
+    Append(w->code, "  PyObject *error = PyErr_Occurred();\n");
+    if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) {
+      Replaceall(tm, "$error", "error");
+      Printv(w->code, Str(tm), "\n", NIL);
+    } else {
+      Append(w->code, "  if (error != NULL) {\n");
+      Printf(w->code, "    Swig::DirectorMethodException::raise(\"Error detected when calling '%s.%s'\");\n", classname, pyname);
+      Append(w->code, "  }\n");
+    }
+    Append(w->code, "}\n");
+    Delete(tm);
+
+    /*
+     * Python method may return a simple object, or a tuple.
+     * for in/out aruments, we have to extract the appropriate PyObjects from the tuple,
+     * then marshal everything back to C/C++ (return value and output arguments).
+     *
+     */
+
+    /* marshal return value and other outputs (if any) from PyObject to C/C++ type */
+
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+
+    if (outputs > 1) {
+      Wrapper_add_local(w, "output", "PyObject *output");
+      Append(w->code, "if (!PyTuple_Check(result)) {\n");
+      Printf(w->code, "  Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname);
+      Append(w->code, "}\n");
+    }
+
+    idx = 0;
+
+    /* marshal return value */
+    if (!is_void) {
+      /* this seems really silly.  the node's type excludes
+       * qualifier/pointer/reference markers, which have to be retrieved
+       * from the decl field to construct return_type.  but the typemap
+       * lookup routine uses the node's type, so we have to swap in and
+       * out the correct type.  it's not just me, similar silliness also
+       * occurs in Language::cDeclaration().
+       */
+      Setattr(n, "type", return_type);
+      tm = Swig_typemap_lookup("directorout", n, "result", w);
+      Setattr(n, "type", type);
+      if (tm == 0) {
+	String *name = NewString("result");
+	tm = Swig_typemap_search("directorout", return_type, name, NULL);
+	Delete(name);
+      }
+      if (tm != 0) {
+	if (outputs > 1) {
+	  Printf(w->code, "output = PyTuple_GetItem(result, %d);\n", idx++);
+	  Replaceall(tm, "$input", "output");
+	} else {
+	  Replaceall(tm, "$input", "result");
+	}
+	char temp[24];
+	sprintf(temp, "%d", idx);
+	Replaceall(tm, "$argnum", temp);
+
+	/* TODO check this */
+	if (Getattr(n, "wrap:disown")) {
+	  Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	} else {
+	  Replaceall(tm, "$disown", "0");
+	}
+	if (Getattr(n, "tmap:directorout:implicitconv")) {
+	  Replaceall(tm, "$implicitconv", get_implicitconv_flag(n));
+	}
+	Replaceall(tm, "$result", "c_result");
+	Printv(w->code, tm, "\n", NIL);
+	Delete(tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number,
+		     "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(return_type, 0), SwigType_namestr(c_classname),
+		     SwigType_namestr(name));
+	status = SWIG_ERROR;
+      }
+    }
+
+    /* marshal outputs */
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:directorargout")) != 0) {
+	if (outputs > 1) {
+	  Printf(w->code, "output = PyTuple_GetItem(result, %d);\n", idx++);
+	  Replaceall(tm, "$input", "output");
+	} else {
+	  Replaceall(tm, "$input", "result");
+	}
+	Replaceall(tm, "$result", Getattr(p, "name"));
+	Printv(w->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:directorargout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* any existing helper functions to handle this? */
+    if (allow_thread) {
+      Append(w->code, "}\n");
+      thread_end_block(n, w->code);
+    }
+
+    Delete(parse_args);
+    Delete(arglist);
+    Delete(cleanup);
+    Delete(outarg);
+  }
+
+  if (!is_void) {
+    if (!(ignored_method && !pure_virtual)) {
+      String *rettype = SwigType_str(return_type, 0);
+      if (!SwigType_isreference(return_type)) {
+	Printf(w->code, "return (%s) c_result;\n", rettype);
+      } else {
+	Printf(w->code, "return (%s) *c_result;\n", rettype);
+      }
+      Delete(rettype);
+    }
+  }
+
+  Append(w->code, "}\n");
+
+  // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method
+  String *inline_extra_method = NewString("");
+  if (dirprot_mode() && !is_public(n) && !pure_virtual) {
+    Printv(inline_extra_method, declaration, NIL);
+    String *extra_method_name = NewStringf("%sSwigPublic", name);
+    Replaceall(inline_extra_method, name, extra_method_name);
+    Replaceall(inline_extra_method, ";\n", " {\n      ");
+    if (!is_void)
+      Printf(inline_extra_method, "return ");
+    String *methodcall = Swig_method_call(super, l);
+    Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
+    Delete(methodcall);
+    Delete(extra_method_name);
+  }
+
+  /* emit the director method */
+  if (status == SWIG_OK) {
+    if (!Getattr(n, "defaultargs")) {
+      Wrapper_print(w, f_directors);
+      Printv(f_directors_h, declaration, NIL);
+      Printv(f_directors_h, inline_extra_method, NIL);
+    }
+  }
+
+  /* clean up */
+  Delete(wrap_args);
+  Delete(return_type);
+  Delete(pclassname);
+  DelWrapper(w);
+  return status;
+}
+
+/* -----------------------------------------------------------------------------
+ * swig_python()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_python() {
+  return new PYTHON();
+}
+extern "C" Language *swig_python(void) {
+  return new_swig_python();
+}
diff --git a/trunk/Source/Modules/r.cxx b/trunk/Source/Modules/r.cxx
new file mode 100644
index 0000000..49d3ecc
--- /dev/null
+++ b/trunk/Source/Modules/r.cxx
@@ -0,0 +1,2751 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * r.cxx
+ *
+ * R language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_r_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+#define UNUSED(a)  (void)a
+
+static const double DEFAULT_NUMBER = .0000123456712312312323;
+static const int MAX_OVERLOAD_ARGS = 5;
+
+static String* replaceInitialDash(const String *name)
+{
+  String *retval;
+  if (!Strncmp(name, "_", 1)) {
+    retval = Copy(name);
+    Insert(retval, 0, "s");
+  } else {
+    retval = Copy(name);
+  }
+  return retval;
+}
+
+static String * getRTypeName(SwigType *t, int *outCount = NULL) {
+  String *b = SwigType_base(t);
+  List *els = SwigType_split(t);
+  int count = 0;
+  int i;
+  
+  if(Strncmp(b, "struct ", 7) == 0) 
+    Replace(b, "struct ", "", DOH_REPLACE_FIRST);
+  
+  /* Printf(stderr, "<getRTypeName> %s,base = %s\n", t, b);
+     for(i = 0; i < Len(els); i++) 
+     Printf(stderr, "%d) %s, ", i, Getitem(els,i));
+     Printf(stderr, "\n"); */
+  
+  for(i = 0; i < Len(els); i++) {
+    String *el = Getitem(els, i);
+    if(Strcmp(el, "p.") == 0 || Strncmp(el, "a(", 2) == 0) {
+      count++;
+      Append(b, "Ref");
+    }
+  }
+  if(outCount)
+    *outCount = count;
+  
+  String *tmp = NewString("");
+  char *retName = Char(SwigType_manglestr(t));
+  Insert(tmp, 0, retName);
+  return tmp;
+  
+  /*
+  if(count)
+    return(b);
+  
+  Delete(b);
+  return(NewString(""));
+  */
+}
+
+#if 0
+static String * getRType(Node *n) {
+  SwigType *elType = Getattr(n, "type");
+  SwigType *elDecl = Getattr(n, "decl");
+  //XXX How can we tell if this is already done.
+  SwigType_push(elType, elDecl);
+  String *ans;
+
+  String *rtype = Swig_typemap_lookup("rtype", n, "", 0);
+  String *i = getRTypeName(elType);
+
+  if(Len(i) == 0) {
+    SwigType *td = SwigType_typedef_resolve(elType);
+    if(td) {
+      //     Printf(stderr, "Resolving typedef %s -> %s\n", elType, td);
+      i = getRTypeName(td);
+    }
+  }
+  //  Printf(stderr, "<getRType> i = %s,  rtype = %s  (for %s)\n", 
+  //	 i, rtype, elType);
+  if(rtype) {
+    ans = NewString("");
+    Printf(ans, "%s", rtype);
+    Replaceall(ans, "$R_class", Char(i));
+    //	Printf(stderr, "Found r type in typemap for %s (for %s) => %s (%s) => %s\n", 
+    //         SwigType_str(elType, 0), Getattr(n, "name"), rtype, i, ans);
+  } else {
+    ans = i;
+  }
+  
+  return(ans);
+}
+#endif
+
+/*********************
+ Tries to get the name of the R class corresponding  to the given type
+  e.g. struct A * is ARef,  struct A**  is  ARefRef.
+  Now handles arrays, i.e. struct A[2]
+****************/
+
+static String *getRClassName(String *retType, int /*addRef*/ = 1, int upRef=0) {
+  String *tmp = NewString("");
+  SwigType *resolved = SwigType_typedef_resolve_all(retType);
+  char *retName = Char(SwigType_manglestr(resolved));
+  if (upRef) {
+    Printf(tmp, "_p%s", retName);
+  } else{
+    Insert(tmp, 0, retName);
+  }
+  
+  return tmp;
+/*
+#if 1
+  List *l = SwigType_split(retType);
+  int n = Len(l);
+  if(!l || n == 0) {
+#ifdef R_SWIG_VERBOSE
+    if (debugMode)
+      Printf(stderr, "SwigType_split return an empty list for %s\n", 
+	     retType);
+#endif
+    return(tmp);
+  }
+  
+  
+  String *el = Getitem(l, n-1);
+  char *ptr = Char(el);
+  if(strncmp(ptr, "struct ", 7) == 0)
+    ptr += 7;
+  
+  Printf(tmp, "%s", ptr);
+  
+  if(addRef) {
+    for(int i = 0; i < n; i++) {
+      if(Strcmp(Getitem(l, i), "p.") == 0 || 
+	 Strncmp(Getitem(l, i), "a(", 2) == 0)
+	Printf(tmp, "Ref");
+    }
+  }
+  
+#else
+  char *retName = Char(SwigType_manglestr(retType));
+  if(!retName)
+    return(tmp);
+  
+  if(addRef) {
+    while(retName && strlen(retName) > 1 && strncmp(retName, "_p", 2) == 0)  {
+      retName += 2;
+      Printf(tmp, "Ref");
+    }
+  }
+  if(retName[0] == '_')
+    retName ++;
+  Insert(tmp, 0, retName);
+#endif
+  
+  return tmp;
+*/
+}
+
+/*********************
+ Tries to get the name of the R class corresponding  to the given type
+  e.g. struct A * is ARef,  struct A**  is  ARefRef.
+  Now handles arrays, i.e. struct A[2]
+****************/
+
+static String * getRClassNameCopyStruct(String *retType, int addRef) {
+  String *tmp = NewString("");
+  
+#if 1
+  List *l = SwigType_split(retType);
+  int n = Len(l);
+  if(!l || n == 0) {
+#ifdef R_SWIG_VERBOSE
+    Printf(stderr, "SwigType_split return an empty list for %s\n", retType);
+#endif
+    return(tmp);
+  }
+  
+  
+  String *el = Getitem(l, n-1);
+  char *ptr = Char(el);
+  if(strncmp(ptr, "struct ", 7) == 0)
+    ptr += 7;
+  
+  Printf(tmp, "%s", ptr);
+  
+  if(addRef) {
+    for(int i = 0; i < n; i++) {
+      if(Strcmp(Getitem(l, i), "p.") == 0 || 
+	 Strncmp(Getitem(l, i), "a(", 2) == 0)
+	Printf(tmp, "Ref");
+    }
+  }
+  
+#else
+  char *retName = Char(SwigType_manglestr(retType));
+  if(!retName)
+    return(tmp);
+  
+  if(addRef) {
+    while(retName && strlen(retName) > 1 && 
+	  strncmp(retName, "_p", 2) == 0)  {
+      retName += 2;
+      Printf(tmp, "Ref");
+    }
+  }
+  
+  if(retName[0] == '_')
+    retName ++;
+  Insert(tmp, 0, retName);
+#endif
+
+  return tmp;
+}
+
+
+/*********************************
+  Write the elements of a list to the File*, one element per line.
+  If quote  is true, surround the element with "element".
+  This takes care of inserting a tab in front of each line and also
+  a comma after each element, except the last one.
+**********************************/
+
+static void writeListByLine(List *l, File *out, bool quote = 0) {
+  int i, n = Len(l);
+  for(i = 0; i < n; i++) 
+    Printf(out, "%s%s%s%s%s\n", tab8, 
+	   quote ? "\"" :"",  
+	   Getitem(l, i), 
+	   quote ? "\"" :"", i < n-1 ? "," : "");
+}
+
+
+static const char *usage = (char *)"\
+R Options (available with -r)\n\
+     -copystruct      - Emit R code to copy C structs (on by default)\n\
+     -cppcast         - Enable C++ casting operators (default) \n\
+     -debug           - Output debug\n\
+     -dll <name>      - Name of the DLL (without the .dll or .so suffix). Default is the module name.\n\
+     -gc              - Aggressive garbage collection\n\
+     -memoryprof      - Add memory profile\n\
+     -namespace       - Output NAMESPACE file\n\
+     -no-init-code    - Turn off the generation of the R_init_<pkgname> code (registration information still generated)\n\
+     -package <name>  - Package name for the PACKAGE argument of the R .Call() invocations. Default is the module name.\n\
+";
+
+
+
+/************
+ Display the help for this module on the screen/console.
+*************/
+static void showUsage() {
+  fputs(usage, stdout);
+}
+
+static bool expandTypedef(SwigType *t) {
+  if (SwigType_isenum(t)) return false;
+  String *prefix = SwigType_prefix(t);
+  if (Strncmp(prefix, "f", 1)) return false;
+  if (Strncmp(prefix, "p.f", 3)) return false;
+  return true;
+}
+
+
+/*****
+      Determine whether  we should add a .copy argument to the S function
+      that wraps/interfaces to the routine that returns the given type.
+*****/
+static int addCopyParameter(SwigType *type) {
+  int ok = 0;
+  ok = Strncmp(type, "struct ", 7) == 0 || Strncmp(type, "p.struct ", 9) == 0;
+  if(!ok) {
+    ok = Strncmp(type, "p.", 2);
+  }
+
+  return(ok);
+}
+
+static void replaceRClass(String *tm, SwigType *type) {
+  String *tmp = getRClassName(type);
+  String *tmp_base = getRClassName(type, 0);
+  String *tmp_ref = getRClassName(type, 1, 1);
+  Replaceall(tm, "$R_class", tmp);
+  Replaceall(tm, "$*R_class", tmp_base);
+  Replaceall(tm, "$&R_class", tmp_ref);
+  Delete(tmp); Delete(tmp_base); Delete(tmp_ref);
+}
+
+static double getNumber(String *value, String *type) {
+  UNUSED(type);
+
+  double d = DEFAULT_NUMBER;
+  if(Char(value)) {
+    //        Printf(stderr, "getNumber %s %s\n", Char(value), type);
+    if(sscanf(Char(value), "%lf", &d) != 1)
+      return(DEFAULT_NUMBER);
+  }
+  return(d);
+}
+
+class R : public Language {
+public:
+  R();
+  void registerClass(Node *n);
+  void main(int argc, char *argv[]);
+  int top(Node *n);
+  
+  void dispatchFunction(Node *n);
+  int functionWrapper(Node *n);
+  int variableWrapper(Node *n);
+
+  int classDeclaration(Node *n);
+  int enumDeclaration(Node *n);
+
+  int membervariableHandler(Node *n);
+
+  int typedefHandler(Node *n);
+
+  int memberfunctionHandler(Node *n) {
+    if (debugMode)
+      Printf(stderr, "<memberfunctionHandler> %s %s\n", 
+	     Getattr(n, "name"),
+	     Getattr(n, "type"));
+    member_name = Getattr(n, "name");
+    processing_class_member_function = 1;
+    int status = Language::memberfunctionHandler(n);    
+    processing_class_member_function = 0;
+    return status;
+  }
+
+  /* Grab the name of the current class being processed so that we can 
+     deal with members of that class. */
+  int classHandler(Node *n){
+    if(!ClassMemberTable) 
+      ClassMemberTable = NewHash();
+    
+    class_name = Getattr(n, "name");
+    int status = Language::classHandler(n);
+    
+    class_name = NULL;
+    return status;
+  }
+
+  // Not used:
+  String *runtimeCode();
+  
+protected:
+  int addRegistrationRoutine(String *rname, int nargs);
+  int outputRegistrationRoutines(File *out);
+  
+  int outputCommandLineArguments(File *out);
+  int generateCopyRoutines(Node *n); 
+  int DumpCode(Node *n);
+  
+  int OutputMemberReferenceMethod(String *className, int isSet, List *el, File *out);
+  int OutputArrayMethod(String *className, List *el, File *out);
+  int OutputClassMemberTable(Hash *tb, File *out);
+  int OutputClassMethodsTable(File *out);
+  int OutputClassAccessInfo(Hash *tb, File *out);
+  
+  int defineArrayAccessors(SwigType *type);
+  
+  void addNamespaceFunction(String *name) {
+    if(!namespaceFunctions)
+      namespaceFunctions = NewList();
+    Append(namespaceFunctions, name);
+  }
+
+  void addNamespaceMethod(String *name) {
+    if(!namespaceMethods)
+      namespaceMethods = NewList();
+    Append(namespaceMethods, name);
+  }
+  
+  String* processType(SwigType *t, Node *n, int *nargs = NULL);
+  String *createFunctionPointerHandler(SwigType *t, Node *n, int *nargs);
+  int addFunctionPointerProxy(String *name, Node *n, SwigType *t, String *s_paramTypes) {
+    /*XXX Do we need to put the t in there to get the return type later. */
+    if(!functionPointerProxyTable) 
+      functionPointerProxyTable = NewHash();
+    
+    Setattr(functionPointerProxyTable, name, n);
+    
+    Setattr(SClassDefs, name, name);
+    Printv(s_classes, "setClass('", 
+	   name,
+	   "',\n", tab8, 
+	   "prototype = list(parameterTypes = c(", s_paramTypes, "),\n",
+	   tab8, tab8, tab8,
+	   "returnType = '", SwigType_manglestr(t), "'),\n", tab8, 
+	   "contains = 'CRoutinePointer')\n\n##\n", NIL);
+    
+    return SWIG_OK;
+  }
+  
+
+  void addSMethodInfo(String *name, 
+		      String *argType, int nargs);
+  // Simple initialization such as constant strings that can be reused. 
+  void init(); 
+  
+  
+  void addAccessor(String *memberName, Wrapper *f, 
+		   String *name, int isSet = -1);
+  
+  static int getFunctionPointerNumArgs(Node *n, SwigType *tt);
+
+protected: 
+  bool copyStruct;
+  bool memoryProfile;
+  bool aggressiveGc;
+
+  // Strings into which we cumulate the generated code that is to be written
+  //vto the files.
+  String *sfile;
+  String *f_init;
+  String *s_classes;
+  String *f_runtime;
+  String *f_wrapper;
+  String *s_header;
+  String *f_wrappers;
+  String *s_init;
+  String *s_init_routine;
+  String *s_namespace;
+  
+  // State variables that carry information across calls to functionWrapper() 
+  // from  member accessors and class declarations. 
+  String *opaqueClassDeclaration;
+  int processing_variable;
+  int processing_member_access_function;
+  String *member_name;
+  String *class_name;
+  
+  
+  int processing_class_member_function;
+  List *class_member_functions;
+  List *class_member_set_functions;
+  
+  /* */
+  Hash *ClassMemberTable;
+  Hash *ClassMethodsTable;
+  Hash *SClassDefs;
+  Hash *SMethodInfo;
+  
+  // Information about routines that are generated and to be registered with 
+  // R for dynamic lookup. 
+  Hash *registrationTable;
+  Hash *functionPointerProxyTable;
+  
+  List *namespaceFunctions;
+  List *namespaceMethods;
+  List *namespaceClasses; // Probably can do this from ClassMemberTable.
+  
+  
+  // Store a copy of the command line. 
+  // Need only keep a string that has it formatted. 
+  char **Argv;
+  int    Argc;
+  bool inCPlusMode;
+  
+  // State variables that we remember from the command line settings
+  // potentially that govern the code we generate.
+  String *DllName;
+  String *Rpackage;
+  bool    noInitializationCode;
+  bool    outputNamespaceInfo;
+  
+  String *UnProtectWrapupCode;
+
+  // Static members
+  static bool debugMode;
+};
+
+R::R() :
+  copyStruct(false),
+  memoryProfile(false),
+  aggressiveGc(false),
+  sfile(0),
+  f_init(0),
+  s_classes(0),
+  f_runtime(0),
+  f_wrapper(0),
+  s_header(0),
+  f_wrappers(0),
+  s_init(0),
+  s_init_routine(0),
+  s_namespace(0),
+  opaqueClassDeclaration(0),
+  processing_variable(0),
+  processing_member_access_function(0),
+  member_name(0),
+  class_name(0),
+  processing_class_member_function(0),
+  class_member_functions(0),
+  class_member_set_functions(0),
+  ClassMemberTable(0),
+  ClassMethodsTable(0),
+  SClassDefs(0),
+  SMethodInfo(0),
+  registrationTable(0),
+  functionPointerProxyTable(0),
+  namespaceFunctions(0),
+  namespaceMethods(0),
+  namespaceClasses(0),
+  Argv(0),
+  Argc(0),
+  inCPlusMode(false),
+  DllName(0),
+  Rpackage(0),
+  noInitializationCode(false),
+  outputNamespaceInfo(false),
+  UnProtectWrapupCode(0) {
+}
+
+bool R::debugMode = false;
+
+int R::getFunctionPointerNumArgs(Node *n, SwigType *tt) {
+  (void) tt;
+  n = Getattr(n, "type");
+  if (debugMode)
+    Printf(stderr, "type: %s\n", n);
+#if 0
+  SwigType *tmp = SwigType_typedef_resolve(tt);
+  
+  n = SwigType_typedef_resolve(tt);
+#endif
+  
+  ParmList *parms = Getattr(n, "parms");
+  if (debugMode)
+    Printf(stderr, "parms = %p\n", parms);
+  return ParmList_len(parms);
+}
+
+
+void R::addSMethodInfo(String *name, String *argType, int nargs) {
+  (void) argType;
+  
+  if(!SMethodInfo)
+    SMethodInfo = NewHash();
+  if (debugMode)
+    Printf(stderr, "[addMethodInfo] %s\n", name);
+
+  Hash *tb = Getattr(SMethodInfo, name);
+
+  if(!tb) {
+    tb = NewHash();
+    Setattr(SMethodInfo, name, tb);
+  }
+
+  String *str = Getattr(tb, "max");
+  int max = -1;
+  if(str)
+    max = atoi(Char(str));
+  if(max < nargs) {
+    if(str)  Delete(str);
+    str = NewStringf("%d", max);
+    Setattr(tb, "max", str);
+  }
+}
+ 
+/*
+Returns the name of the new routine.
+*/
+String * R::createFunctionPointerHandler(SwigType *t, Node *n, int *numArgs) {
+  String *funName = SwigType_manglestr(t);
+  
+  /* See if we have already processed this one. */
+  if(functionPointerProxyTable && Getattr(functionPointerProxyTable, funName))
+    return funName;
+  
+  if (debugMode)
+    Printf(stderr, "<createFunctionPointerHandler> Defining %s\n",  t);
+  
+  SwigType *rettype = Copy(Getattr(n, "type"));
+  SwigType *funcparams = SwigType_functionpointer_decompose(rettype);
+  String *rtype = SwigType_str(rettype, 0);
+
+  //   ParmList *parms = Getattr(n, "parms");
+  // memory leak
+  ParmList *parms = SwigType_function_parms(SwigType_del_pointer(Copy(t)));
+
+
+  //  if (debugMode) {
+    Printf(stderr, "Type: %s\n", t);
+    Printf(stderr, "Return type: %s\n", SwigType_base(t));
+    //}
+  
+  bool isVoidType = Strcmp(rettype, "void") == 0;
+  if (debugMode)
+    Printf(stderr, "%s is void ? %s  (%s)\n", funName, isVoidType ? "yes" : "no", rettype);
+  
+  Wrapper *f = NewWrapper();
+  
+  /* Go through argument list, attach lnames for arguments */
+  int i = 0;
+  Parm *p = parms;
+  for (i = 0; p; p = nextSibling(p), ++i) {
+    String *arg = Getattr(p, "name");
+    String *lname = NewString("");
+
+    if (!arg && Cmp(Getattr(p, "type"), "void")) {
+      lname = NewStringf("s_arg%d", i+1);
+      Setattr(p, "name", lname);
+    } else
+      lname = arg;
+
+    Setattr(p, "lname", lname);
+  }
+  
+  Swig_typemap_attach_parms("out", parms, f);
+  Swig_typemap_attach_parms("scoerceout", parms, f);
+  Swig_typemap_attach_parms("scheck", parms, f);
+
+  Printf(f->def, "%s %s(", rtype, funName);
+
+  emit_parameter_variables(parms, f);
+  emit_return_variable(n, rettype, f);
+//  emit_attach_parmmaps(parms,f);
+
+  /*  Using weird name and struct to avoid potential conflicts. */
+  Wrapper_add_local(f, "r_swig_cb_data", "RCallbackFunctionData *r_swig_cb_data = R_SWIG_getCallbackFunctionData()");
+  String *lvar = NewString("r_swig_cb_data");
+
+  Wrapper_add_local(f, "r_tmp", "SEXP r_tmp"); // for use in converting arguments to R objects for call.
+  Wrapper_add_local(f, "r_nprotect", "int r_nprotect = 0"); // for use in converting arguments to R objects for call.
+  Wrapper_add_local(f, "r_vmax", "char * r_vmax= 0"); // for use in converting arguments to R objects for call.
+
+  // Add local for error code in return value.  This is not in emit_return_variable because that assumes an out typemap
+  // whereas the type makes are reverse
+  Wrapper_add_local(f, "ecode", "int ecode = 0");
+
+  p = parms;
+  int nargs = ParmList_len(parms);
+  if(numArgs) {
+    *numArgs = nargs;
+    if (debugMode)
+      Printf(stderr, "Setting number of parameters to %d\n", *numArgs);
+  } 
+  String *setExprElements = NewString("");
+  
+  String *s_paramTypes = NewString("");
+  for(i = 0; p; i++) {
+    SwigType *tt = Getattr(p, "type");
+    SwigType *name = Getattr(p, "name");
+    //       String   *lname  = Getattr(p,"lname");
+    Printf(f->def,  "%s %s", SwigType_str(tt, 0), name);
+    String *tm = Getattr(p, "tmap:out");
+    if(tm) {
+      Replaceall(tm, "$1", name);
+      Replaceall(tm, "$result", "r_tmp");
+      replaceRClass(tm, Getattr(p,"type"));
+      Replaceall(tm,"$owner", "R_SWIG_EXTERNAL");
+    } 
+    
+    Printf(setExprElements, "%s\n", tm);
+    Printf(setExprElements, "SETCAR(r_swig_cb_data->el, %s);\n", "r_tmp");
+    Printf(setExprElements, "r_swig_cb_data->el = CDR(r_swig_cb_data->el);\n\n");
+    
+    Printf(s_paramTypes, "'%s'", SwigType_manglestr(tt));
+    
+    
+    p = nextSibling(p);
+    if(p) {
+      Printf(f->def, ", ");
+      Printf(s_paramTypes, ", ");
+    }
+  }
+  
+  Printf(f->def,  ") {\n");
+  
+  Printf(f->code, "Rf_protect(%s->expr = Rf_allocVector(LANGSXP, %d));\n", lvar, nargs + 1);
+  Printf(f->code, "r_nprotect++;\n");
+  Printf(f->code, "r_swig_cb_data->el = r_swig_cb_data->expr;\n\n");
+  
+  Printf(f->code, "SETCAR(r_swig_cb_data->el, r_swig_cb_data->fun);\n");
+  Printf(f->code, "r_swig_cb_data->el = CDR(r_swig_cb_data->el);\n\n");
+  
+  Printf(f->code, "%s\n\n", setExprElements);
+  
+  Printv(f->code, "r_swig_cb_data->retValue = R_tryEval(", 
+	 "r_swig_cb_data->expr,",
+	 " R_GlobalEnv,",
+	 " &r_swig_cb_data->errorOccurred",
+	 ");\n", 
+	 NIL);
+  
+  Printv(f->code, "\n",
+	 "if(r_swig_cb_data->errorOccurred) {\n",
+	 "R_SWIG_popCallbackFunctionData(1);\n",
+	 "Rf_error(\"error in calling R function as a function pointer (",
+	 funName,
+	 ")\");\n",
+	 "}\n",
+	 NIL);
+   
+   
+   
+  if(!isVoidType) {
+    /* Need to deal with the return type of the function pointer, not the function pointer itself. 
+       So build a new node that has the relevant pieces.
+       XXX  Have to be a little more clever so that we can deal with struct A * - the * is getting lost.
+       Is this still true? If so, will a SwigType_push() solve things?
+    */
+    Node *bbase = NewHash();
+    
+    Setattr(bbase, "type", rettype);
+    Setattr(bbase, "name", NewString("result"));
+    String *returnTM = Swig_typemap_lookup("in", bbase, "result", f);
+    if(returnTM) {
+      String *tm = returnTM;
+      Replaceall(tm,"$input", "r_swig_cb_data->retValue");
+      Replaceall(tm,"$target", "result");
+      replaceRClass(tm, rettype);
+      Replaceall(tm,"$owner", "R_SWIG_EXTERNAL");
+      Replaceall(tm,"$disown","0");
+      Printf(f->code, "%s\n", tm);
+    }
+    Delete(bbase);
+  }
+  
+  Printv(f->code, "R_SWIG_popCallbackFunctionData(1);\n", NIL);
+  Printv(f->code, "\n", UnProtectWrapupCode, NIL);
+  
+  if(!isVoidType)
+    Printv(f->code,  "return result;\n", NIL);
+  
+  Printv(f->code, "\n}\n", NIL);
+  
+  /* To coerce correctly in S, we really want to have an extra/intermediate
+     function that handles the scoerceout. 
+     We need to check if any of the argument types have an entry in
+     that map. If none do, the ignore and call the function straight.
+     Otherwise, generate the a marshalling function.
+     Need to be able to find it in S. Or use an entirely generic one
+     that evaluates the expressions.
+     Handle errors in the evaluation of the function by restoring
+     the stack, if there is one in use for this function (i.e. no 
+     userData).
+  */
+  
+  Wrapper_print(f, f_wrapper);
+  
+  addFunctionPointerProxy(funName, n, t, s_paramTypes);
+  Delete(s_paramTypes);
+  Delete(rtype);
+  Delete(rettype);
+  Delete(funcparams);
+  
+  return funName;
+}
+
+void R::init() {
+  UnProtectWrapupCode =  
+    NewStringf("%s", "vmaxset(r_vmax);\nif(r_nprotect)  Rf_unprotect(r_nprotect);\n\n");
+  
+  SClassDefs = NewHash();
+  
+  sfile = NewString("");
+  f_init = NewString("");
+  s_header = NewString("");
+  f_runtime = NewString("");
+  f_wrapper = NewString("");
+  s_classes = NewString("");
+  s_init = NewString("");
+  s_init_routine = NewString("");
+}
+
+
+
+#if 0
+int R::cDeclaration(Node *n) {
+  SwigType *t = Getattr(n, "type");
+  SwigType *name = Getattr(n, "name");
+  if (debugMode)
+    Printf(stderr, "cDeclaration (%s): %s\n", name, SwigType_lstr(t, 0));
+  return Language::cDeclaration(n);
+}
+#endif
+
+
+/**
+   Method from Language that is called to start the entire
+   processing off, i.e. the generation of the code. 
+   It is called after the input has been read and parsed.
+   Here we open the output streams and generate the code.
+***/
+int R::top(Node *n) {
+  String *module = Getattr(n, "name");
+  if(!Rpackage) 
+    Rpackage = Copy(module);
+  if(!DllName)
+    DllName = Copy(module);
+
+  if(outputNamespaceInfo) {
+    s_namespace = NewString("");
+    Swig_register_filebyname("snamespace", s_namespace);
+    Printf(s_namespace, "useDynLib(%s)\n", DllName);
+  }
+
+  /* Associate the different streams with names so that they can be used in %insert directives by the
+     typemap code. */
+  Swig_register_filebyname("sinit", s_init);
+  Swig_register_filebyname("sinitroutine", s_init_routine);
+
+  Swig_register_filebyname("runtime", f_runtime);
+  Swig_register_filebyname("init", f_init);
+  Swig_register_filebyname("header", s_header);
+  Swig_register_filebyname("wrapper", f_wrapper);
+  Swig_register_filebyname("s", sfile);
+
+  Swig_register_filebyname("sclasses", s_classes);
+
+
+  Printf(s_init, "# This is an automatically generated file by the R module for SWIG.\n\n");
+  outputCommandLineArguments(s_init);
+
+  Printf(f_wrapper, "#ifdef __cplusplus\n");
+  Printf(f_wrapper, "extern \"C\" {\n");
+  Printf(f_wrapper, "#endif\n\n");
+
+  Language::top(n);
+
+  Printf(f_wrapper, "#ifdef __cplusplus\n");
+  Printf(f_wrapper, "}\n");
+  Printf(f_wrapper, "#endif\n");
+
+  String *type_table = NewString("");
+  SwigType_emit_type_table(f_runtime,f_wrapper);
+  Delete(type_table);
+
+  if(ClassMemberTable) {
+    //XXX OutputClassAccessInfo(ClassMemberTable, sfile);
+    Delete(ClassMemberTable);
+    ClassMemberTable = NULL;
+  }
+
+  Printf(f_init,"}\n");
+  if(registrationTable)
+    outputRegistrationRoutines(f_init);
+
+  /* Now arrange to write the 2 files - .S and .c. */
+
+  DumpCode(n);
+
+  Delete(sfile);
+  Delete(s_classes);
+  Delete(s_init);
+  Delete(f_wrapper);
+  Delete(f_init);
+
+  Delete(s_header);
+  Delete(f_runtime);
+
+  return SWIG_OK;
+}
+
+
+/*****************************************************
+  Write the generated code  to the .S and the .c files.
+****************************************************/
+int R::DumpCode(Node *n) {
+  String *output_filename = NewString("");
+  
+  
+  /* The name of the file in which we will generate the S code. */
+  Printf(output_filename, "%s%s.R", SWIG_output_directory(), Rpackage);
+  
+#ifdef R_SWIG_VERBOSE
+  Printf(stderr, "Writing S code to %s\n", output_filename);
+#endif
+  
+  File *scode = NewFile(output_filename, "w");
+  if (!scode) {
+    FileErrorDisplay(output_filename);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Delete(output_filename);
+  
+  
+  Printf(scode, "%s\n\n", s_init);
+  Printf(scode, "%s\n\n", s_classes);
+  Printf(scode, "%s\n", sfile);
+  
+  Close(scode);
+  //  Delete(scode);
+  String *outfile = Getattr(n,"outfile");
+  File *runtime = NewFile(outfile,"w");
+  if (!runtime) {
+    FileErrorDisplay(outfile);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  
+  Swig_banner(runtime);
+  
+  
+  Printf(runtime, "/* Runtime */\n");
+  Printf(runtime, "%s\n", f_runtime);
+  
+  Printf(runtime, "/* Header */\n");
+  Printf(runtime, "%s\n", s_header);
+
+  Printf(runtime, "/* Wrapper */\n");
+  Printf(runtime, "%s\n", f_wrapper);
+
+  Printf(runtime, "/* Init code */\n");
+  Printf(runtime, "%s\n", f_init);
+
+  Close(runtime);
+  Delete(runtime);
+
+  if(outputNamespaceInfo) {
+    output_filename = NewString("");
+    Printf(output_filename, "%sNAMESPACE", SWIG_output_directory());
+    File *ns = NewFile(output_filename, "w");
+    if (!ns) {
+      FileErrorDisplay(output_filename);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Delete(output_filename);
+   
+    Printf(ns, "%s\n", s_namespace);
+
+    Printf(ns, "\nexport(\n");
+    writeListByLine(namespaceFunctions, ns);
+    Printf(ns, ")\n");
+    Printf(ns, "\nexportMethods(\n");
+    writeListByLine(namespaceFunctions, ns, 1);
+    Printf(ns, ")\n");
+    Close(ns);
+    Delete(ns);
+    Delete(s_namespace);
+  }
+
+  return SWIG_OK;
+}
+
+
+
+/*
+  We may need to do more.... so this is left as a 
+  stub for the moment.
+*/
+int R::OutputClassAccessInfo(Hash *tb, File *out) {
+  int n = OutputClassMemberTable(tb, out);
+  OutputClassMethodsTable(out);
+  return n;
+}
+
+/************************************************************************
+  Currently this just writes the information collected about the
+  different methods of the C++ classes that have been processed
+  to the console. 
+  This will be used later to define S4 generics and methods.
+**************************************************************************/
+int R::OutputClassMethodsTable(File *) {
+  Hash *tb = ClassMethodsTable;
+  
+  if(!tb)
+    return SWIG_OK;
+  
+  List *keys = Keys(tb);
+  String *key;
+  int i, n = Len(keys);
+  if (debugMode) {
+    for(i = 0; i < n ; i++ ) {
+      key = Getitem(keys, i);
+      Printf(stderr, "%d) %s\n", i, key);
+      List *els = Getattr(tb, key);
+      int nels = Len(els);
+      Printf(stderr, "\t");
+      for(int j = 0; j < nels; j+=2) {
+	Printf(stderr, "%s%s", Getitem(els, j), j < nels - 1 ? ", " : "");
+	Printf(stderr, "%s\n", Getitem(els, j+1));
+      }
+      Printf(stderr, "\n");
+    }
+  }
+
+  return SWIG_OK;
+}
+
+
+/*
+  Iterate over the <class name>_set and <>_get 
+  elements and generate the $ and $<- functions
+  that provide constrained access to the member
+  fields in these elements.
+
+  tb - a hash table that is built up in functionWrapper
+  as we process each membervalueHandler.
+  The entries are indexed by <class name>_set and 
+  <class_name>_get. Each entry is a List *.
+   
+  out - the stram where the code is to be written. This is the S
+  code stream as we generate only S code here..
+*/
+int R::OutputClassMemberTable(Hash *tb, File *out) {
+  List *keys = Keys(tb), *el;
+  
+  String *key;
+  int i, n = Len(keys);
+  /* Loop over all the  <Class>_set and <Class>_get entries in the table. */
+  
+  if(n && outputNamespaceInfo) {
+    Printf(s_namespace, "exportClasses(");
+  }
+  for(i = 0; i < n; i++) {
+    key = Getitem(keys, i);
+    el = Getattr(tb, key);
+    
+    String *className = Getitem(el, 0);
+    char *ptr = Char(key);
+    ptr = &ptr[Len(key) - 3];
+    int isSet = strcmp(ptr, "set") == 0;
+    
+    //        OutputArrayMethod(className, el, out);        
+    OutputMemberReferenceMethod(className, isSet, el, out);
+    
+    if(outputNamespaceInfo) 
+      Printf(s_namespace, "\"%s\"%s", className, i < n-1 ? "," : "");
+  }
+  if(n && outputNamespaceInfo) { 
+    Printf(s_namespace, ")\n");
+  }
+  
+  return n;
+}
+
+/*******************************************************************
+ Write the methods for $ or $<- for accessing a member field in an 
+ struct or union (or class).
+ className - the name of the struct or union (e.g. Bar for struct Bar)
+ isSet - a logical value indicating whether the method is for 
+           modifying ($<-) or accessing ($) the member field.
+ el - a list of length  2 * # accessible member elements  + 1.
+      The first element is the name of the class. 
+      The other pairs are  member name and the name of the R function to access it.
+ out - the stream where we write the code.
+********************************************************************/
+int R::OutputMemberReferenceMethod(String *className, int isSet, 
+				   List *el, File *out) {
+  int numMems = Len(el), j;
+  int has_getitem = 0, has_setitem = 0, has_str = 0;
+  int varaccessor = 0;
+  if (numMems == 0) 
+    return SWIG_OK;
+  
+  Wrapper *f = NewWrapper(), *attr = NewWrapper();
+  
+  Printf(f->def, "function(x, name%s)", isSet ? ", value" : "");
+  Printf(attr->def, "function(x, i, j, ...%s)", isSet ? ", value" : "");
+  
+  Printf(f->code, "{\n");
+  Printf(f->code, "%saccessorFuns = list(", tab8);
+
+  Node *itemList = NewHash();
+  bool has_prev = false;
+  for(j = 0; j < numMems; j+=3) {
+    String *item = Getitem(el, j);
+    if (Getattr(itemList, item)) 
+      continue;
+    Setattr(itemList, item, "1");
+    if (!Strcmp(item, "__getitem__")) has_getitem = 1;
+    if (!Strcmp(item, "__setitem__")) has_setitem = 1;
+    if (!Strcmp(item, "__str__")) has_str = 1;
+    
+    String *dup = Getitem(el, j + 1);
+    char *ptr = Char(dup);
+    ptr = &ptr[Len(dup) - 3];
+    
+    if (!strcmp(ptr, "get"))
+      varaccessor++;
+
+    String *pitem;
+    if (!Strcmp(item, "operator ()")) {
+      pitem = NewString("call");
+    } else if (!Strcmp(item, "operator ->")) {
+      pitem = NewString("deref");
+    } else if (!Strcmp(item, "operator +")) {
+      pitem = NewString("add");
+    } else if (!Strcmp(item, "operator -")) {
+      pitem = NewString("sub");
+    } else {
+      pitem = Copy(item);
+    }
+    if (has_prev) 
+      Printf(f->code, ", ");
+    Printf(f->code, "'%s' = %s", pitem, dup);
+    has_prev = true;
+    Delete(pitem);
+  }
+  Delete(itemList);
+  Printf(f->code, ")\n");
+  
+  if (!isSet && varaccessor > 0) {
+    Printf(f->code, "%svaccessors = c(", tab8);
+    int vcount = 0;
+    for(j = 0; j < numMems; j+=3) {
+      String *item = Getitem(el, j);
+      String *dup = Getitem(el, j + 1);
+      char *ptr = Char(dup);
+      ptr = &ptr[Len(dup) - 3];
+      
+      if (!strcmp(ptr, "get")) {
+	vcount++;
+	Printf(f->code, "'%s'%s", item, vcount < varaccessor ? ", " : "");
+      }
+    }
+    Printf(f->code, ")\n");
+  }
+  
+  
+  /*    Printv(f->code, tab8,
+	"idx = pmatch(name, names(accessorFuns))\n",
+	tab8,
+	"if(is.na(idx)) {\n",
+	tab8, tab4, 
+	"stop(\"No ", (isSet ? "modifiable" : "accessible"), " field named \", name, \" in ", className,
+	": fields are \", paste(names(accessorFuns), sep = \", \")", 
+	")", "\n}\n", NIL); */
+  Printv(f->code, tab8,
+	 "idx = pmatch(name, names(accessorFuns))\n",
+	 tab8,
+	 "if(is.na(idx)) \n",
+	 tab8, tab4, NIL);
+  Printf(f->code, "return(callNextMethod(x, name%s))\n",
+	 isSet ? ", value" : "");
+  Printv(f->code, tab8, "f = accessorFuns[[idx]]\n", NIL);
+  if(isSet) {
+    Printv(f->code, tab8, "f(x, value)\n", NIL);
+    Printv(f->code, tab8, "x\n", NIL); // make certain to return the S value.
+  } else {
+    Printv(f->code, tab8, "formals(f)[[1]] = x\n", NIL);
+    if (varaccessor) {
+      Printv(f->code, tab8,
+	     "if (is.na(match(name, vaccessors))) f else f(x)\n", NIL);
+    } else {
+      Printv(f->code, tab8, "f\n", NIL);
+    }
+  }
+  Printf(f->code, "}\n");
+  
+  
+  Printf(out, "# Start of accessor method for %s\n", className);
+  Printf(out, "setMethod('$%s', '_p%s', ",
+	 isSet ? "<-" : "", 
+	 getRClassName(className)); 
+  Wrapper_print(f, out);
+  Printf(out, ")\n");
+  
+  if(isSet) {
+    Printf(out, "setMethod('[[<-', c('_p%s', 'character'),", 
+	   getRClassName(className)); 
+    Insert(f->code, 2, "name = i\n");
+    Printf(attr->code, "%s", f->code);
+    Wrapper_print(attr, out);
+    Printf(out, ")\n");
+  }
+  
+  DelWrapper(attr);
+  DelWrapper(f);
+  
+  Printf(out, "# end of accessor method for %s\n", className);
+  
+  return SWIG_OK;
+}
+
+/*******************************************************************
+ Write the methods for [ or [<- for accessing a member field in an 
+ struct or union (or class).
+ className - the name of the struct or union (e.g. Bar for struct Bar)
+ el - a list of length  2 * # accessible member elements  + 1.
+      The first element is the name of the class. 
+      The other pairs are  member name and the name of the R function to access it.
+ out - the stream where we write the code.
+********************************************************************/
+int R::OutputArrayMethod(String *className, List *el, File *out) {
+  int numMems = Len(el), j;
+  
+  if(!el || numMems == 0)
+    return(0);
+  
+  Printf(out, "# start of array methods for %s\n", className);
+  for(j = 0; j < numMems; j+=3) {
+    String *item = Getitem(el, j);
+    String *dup = Getitem(el, j + 1);
+    if (!Strcmp(item, "__getitem__")) {
+      Printf(out, 
+	     "setMethod('[', '_p%s', function(x, i, j, ..., drop =TRUE) ", 
+	     getRClassName(className));
+      Printf(out, "  sapply(i, function (n)  %s(x, as.integer(n-1))))\n\n", dup);
+    }
+    if (!Strcmp(item, "__setitem__")) {
+      Printf(out, "setMethod('[<-', '_p%s', function(x, i, j, ..., value)", 
+	     getRClassName(className));
+      Printf(out, "  sapply(1:length(i), function(n) %s(x, as.integer(i[n]-1), value[n])))\n\n", dup);
+    }
+    
+  }
+  
+  Printf(out, "# end of array methods for %s\n", className);
+  
+  return SWIG_OK;
+}
+
+
+/************************************************************
+ Called when a enumeration is to be processed.
+ We want to call the R function defineEnumeration().
+ tdname is the typedef of the enumeration, i.e. giving its name.
+*************************************************************/
+int R::enumDeclaration(Node *n) {
+  String *name = Getattr(n, "name");
+  String *tdname = Getattr(n, "tdname");
+  
+  /* Using name if tdname is empty. */
+  
+  if(Len(tdname) == 0)
+    tdname = name;
+
+
+  if(!tdname || Strcmp(tdname, "") == 0) {
+    Language::enumDeclaration(n);
+    return SWIG_OK;
+  }
+  
+  String *mangled_tdname = SwigType_manglestr(tdname);
+  String *scode = NewString("");
+  
+  Printv(scode, "defineEnumeration('", mangled_tdname, "'", 
+	 ",\n",  tab8, tab8, tab4, ".values = c(\n", NIL);
+  
+  Node *c;
+  int value = -1; // First number is zero
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    //      const char *tag = Char(nodeType(c));
+    //      if (Strcmp(tag,"cdecl") == 0) {        
+    name = Getattr(c, "name");
+    String *type = Getattr(c, "type");
+    String *val = Getattr(c, "enumvalue");
+    if(val && Char(val)) {
+      int inval = (int) getNumber(val, type);
+      if(inval == DEFAULT_NUMBER) 
+	value++;
+      else 
+	value = inval;
+    } else
+      value++;
+    
+    Printf(scode, "%s%s%s'%s' = %d%s\n", tab8, tab8, tab8, name, value,
+	   nextSibling(c) ? ", " : "");
+    //      }
+  }
+  
+  Printv(scode, "))", NIL);
+  Printf(sfile, "%s\n", scode);
+  
+  Delete(scode);
+  Delete(mangled_tdname);
+  
+  return SWIG_OK;
+}
+
+
+/*************************************************************
+**************************************************************/
+int R::variableWrapper(Node *n) {
+  String *name = Getattr(n, "sym:name");
+  
+  processing_variable = 1;
+  Language::variableWrapper(n); // Force the emission of the _set and _get function wrappers.
+  processing_variable = 0;
+  
+  
+  SwigType *ty = Getattr(n, "type");
+  int addCopyParam = addCopyParameter(ty);
+  
+  //XXX
+  processType(ty, n);
+  
+  if(!SwigType_isconst(ty)) {
+    Wrapper *f = NewWrapper();
+    Printf(f->def, "%s = \nfunction(value%s)\n{\n", 
+	   name, addCopyParam ? ", .copy = FALSE" : "");
+    Printv(f->code, "if(missing(value)) {\n", 
+	   name, "_get(", addCopyParam ? ".copy" : "", ")\n}", NIL);
+    Printv(f->code, " else {\n", 
+	   name, "_set(value)\n}\n}", NIL);
+    
+    Wrapper_print(f, sfile);
+    DelWrapper(f);
+  } else {
+    Printf(sfile, "%s = %s_get\n", name, name);
+  }
+
+  return SWIG_OK;
+}
+
+
+void R::addAccessor(String *memberName, Wrapper *wrapper, String *name, 
+		    int isSet) {
+  if(isSet < 0) {
+    int n = Len(name);
+    char *ptr = Char(name);
+    isSet = Strcmp(NewString(&ptr[n-3]), "set") == 0;
+  }
+  
+  List *l = isSet ? class_member_set_functions : class_member_functions;
+  
+  if(!l) {
+    l = NewList();
+    if(isSet)
+      class_member_set_functions = l;
+    else
+      class_member_functions = l;
+  }
+  
+  Append(l, memberName);
+  Append(l, name);
+  
+  String *tmp = NewString("");
+  Wrapper_print(wrapper, tmp);
+  Append(l, tmp);
+  // if we could put the wrapper in directly:       Append(l, Copy(sfun));
+  if (debugMode)
+    Printf(stderr, "Adding accessor: %s (%s) => %s\n", memberName, name, tmp);
+}
+
+#define MAX_OVERLOAD 256
+
+struct Overloaded {
+  Node      *n;          /* Node                               */
+  int        argc;       /* Argument count                     */
+  ParmList  *parms;      /* Parameters used for overload check */
+  int        error;      /* Ambiguity error                    */
+};
+
+
+static List * Swig_overload_rank(Node *n, 
+				 bool script_lang_wrapping) {
+  Overloaded  nodes[MAX_OVERLOAD];
+  int         nnodes = 0;
+  Node *o = Getattr(n,"sym:overloaded");
+
+
+  if (!o) return 0;
+
+  Node *c = o;
+  while (c) {
+    if (Getattr(c,"error")) {
+      c = Getattr(c,"sym:nextSibling");
+      continue;
+    }
+    /*    if (SmartPointer && Getattr(c,"cplus:staticbase")) {
+	  c = Getattr(c,"sym:nextSibling");
+	  continue;
+	  } */
+
+    /* Make a list of all the declarations (methods) that are overloaded with
+     * this one particular method name */
+
+    if (Getattr(c,"wrap:name")) {
+      nodes[nnodes].n = c;
+      nodes[nnodes].parms = Getattr(c,"wrap:parms");
+      nodes[nnodes].argc = emit_num_required(nodes[nnodes].parms);
+      nodes[nnodes].error = 0;
+      nnodes++;
+    }
+    c = Getattr(c,"sym:nextSibling");
+  }
+  
+  /* Sort the declarations by required argument count */
+  {
+    int i,j;
+    for (i = 0; i < nnodes; i++) {
+      for (j = i+1; j < nnodes; j++) {
+	if (nodes[i].argc > nodes[j].argc) {
+	  Overloaded t = nodes[i];
+	  nodes[i] = nodes[j];
+	  nodes[j] = t;
+	}
+      }
+    }
+  }
+
+  /* Sort the declarations by argument types */
+  {
+    int i,j;
+    for (i = 0; i < nnodes-1; i++) {
+      if (nodes[i].argc == nodes[i+1].argc) {
+	for (j = i+1; (j < nnodes) && (nodes[j].argc == nodes[i].argc); j++) {
+	  Parm *p1 = nodes[i].parms;
+	  Parm *p2 = nodes[j].parms;
+	  int   differ = 0;
+	  int   num_checked = 0;
+	  while (p1 && p2 && (num_checked < nodes[i].argc)) {
+	    //	  Printf(stdout,"p1 = '%s', p2 = '%s'\n", Getattr(p1,"type"), Getattr(p2,"type"));
+	    if (checkAttribute(p1,"tmap:in:numinputs","0")) {
+	      p1 = Getattr(p1,"tmap:in:next");
+	      continue;
+	    }
+	    if (checkAttribute(p2,"tmap:in:numinputs","0")) {
+	      p2 = Getattr(p2,"tmap:in:next");
+	      continue;
+	    }
+	    String *t1 = Getattr(p1,"tmap:typecheck:precedence");
+	    String *t2 = Getattr(p2,"tmap:typecheck:precedence");
+	    if ((!t1) && (!nodes[i].error)) {
+	      Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[i].n), Getline(nodes[i].n),
+			   "Overloaded %s(%s) not supported (no type checking rule for '%s').\n", 
+			   Getattr(nodes[i].n,"name"),ParmList_str_defaultargs(Getattr(nodes[i].n,"parms")),
+			   SwigType_str(Getattr(p1,"type"),0));
+	      nodes[i].error = 1;
+	    } else if ((!t2) && (!nodes[j].error)) {
+	      Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[j].n), Getline(nodes[j].n),
+			   "Overloaded %s(%s) not supported (no type checking rule for '%s').\n", 
+			   Getattr(nodes[j].n,"name"),ParmList_str_defaultargs(Getattr(nodes[j].n,"parms")),
+			   SwigType_str(Getattr(p2,"type"),0));
+	      nodes[j].error = 1;
+	    }
+	    if (t1 && t2) {
+	      int t1v, t2v;
+	      t1v = atoi(Char(t1));
+	      t2v = atoi(Char(t2));
+	      differ = t1v-t2v;
+	    }
+	    else if (!t1 && t2) differ = 1;
+	    else if (t1 && !t2) differ = -1;
+	    else if (!t1 && !t2) differ = -1;
+	    num_checked++;
+	    if (differ > 0) {
+	      Overloaded t = nodes[i];
+	      nodes[i] = nodes[j];
+	      nodes[j] = t;
+	      break;
+	    } else if ((differ == 0) && (Strcmp(t1,"0") == 0)) {
+	      t1 = Getattr(p1,"ltype");
+	      if (!t1) {
+		t1 = SwigType_ltype(Getattr(p1,"type"));
+		if (Getattr(p1,"tmap:typecheck:SWIGTYPE")) {
+		  SwigType_add_pointer(t1);
+		}
+		Setattr(p1,"ltype",t1);
+	      }
+	      t2 = Getattr(p2,"ltype");
+	      if (!t2) {
+		t2 = SwigType_ltype(Getattr(p2,"type"));
+		if (Getattr(p2,"tmap:typecheck:SWIGTYPE")) {
+		  SwigType_add_pointer(t2);
+		}
+		Setattr(p2,"ltype",t2);
+	      }
+
+	      /* Need subtype check here.  If t2 is a subtype of t1, then we need to change the
+                 order */
+
+	      if (SwigType_issubtype(t2,t1)) {
+		Overloaded t = nodes[i];
+		nodes[i] = nodes[j];
+		nodes[j] = t;
+	      }
+
+	      if (Strcmp(t1,t2) != 0) {
+		differ = 1;
+		break;
+	      }
+	    } else if (differ) {
+	      break;
+	    }
+	    if (Getattr(p1,"tmap:in:next")) {
+	      p1 = Getattr(p1,"tmap:in:next");
+	    } else {
+	      p1 = nextSibling(p1);
+	    }
+	    if (Getattr(p2,"tmap:in:next")) {
+	      p2 = Getattr(p2,"tmap:in:next");
+	    } else {
+	      p2 = nextSibling(p2);
+	    }
+	  }
+	  if (!differ) {
+	    /* See if declarations differ by const only */
+	    String *d1 = Getattr(nodes[i].n,"decl");
+	    String *d2 = Getattr(nodes[j].n,"decl");
+	    if (d1 && d2) {
+	      String *dq1 = Copy(d1);
+	      String *dq2 = Copy(d2);
+	      if (SwigType_isconst(d1)) {
+		Delete(SwigType_pop(dq1));
+	      }
+	      if (SwigType_isconst(d2)) {
+		Delete(SwigType_pop(dq2));
+	      }
+	      if (Strcmp(dq1,dq2) == 0) {
+		
+		if (SwigType_isconst(d1) && !SwigType_isconst(d2)) {
+                  if (script_lang_wrapping) {
+                    // Swap nodes so that the const method gets ignored (shadowed by the non-const method)
+                    Overloaded t = nodes[i];
+                    nodes[i] = nodes[j];
+                    nodes[j] = t;
+                  }
+		  differ = 1;
+		  if (!nodes[j].error) {
+                    if (script_lang_wrapping) {
+		      Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[j].n), Getline(nodes[j].n),
+				   "Overloaded %s(%s) const ignored. Non-const method at %s:%d used.\n",
+				   Getattr(nodes[j].n,"name"), ParmList_errorstr(nodes[j].parms),
+				   Getfile(nodes[i].n), Getline(nodes[i].n));
+                    } else {
+                      if (!Getattr(nodes[j].n, "overload:ignore"))
+		        Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+				     "Overloaded method %s(%s) ignored. Method %s(%s) const at %s:%d used.\n",
+				     Getattr(nodes[j].n,"name"), ParmList_errorstr(nodes[j].parms),
+			             Getattr(nodes[i].n,"name"), ParmList_errorstr(nodes[i].parms),
+				     Getfile(nodes[i].n), Getline(nodes[i].n));
+                    }
+		  }
+		  nodes[j].error = 1;
+		} else if (!SwigType_isconst(d1) && SwigType_isconst(d2)) {
+		  differ = 1;
+		  if (!nodes[j].error) {
+                    if (script_lang_wrapping) {
+		      Swig_warning(WARN_LANG_OVERLOAD_CONST, Getfile(nodes[j].n), Getline(nodes[j].n),
+				   "Overloaded %s(%s) const ignored. Non-const method at %s:%d used.\n",
+				   Getattr(nodes[j].n,"name"), ParmList_errorstr(nodes[j].parms),
+				   Getfile(nodes[i].n), Getline(nodes[i].n));
+                    } else {
+                      if (!Getattr(nodes[j].n, "overload:ignore"))
+		        Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+				     "Overloaded method %s(%s) const ignored. Method %s(%s) at %s:%d used.\n",
+				     Getattr(nodes[j].n,"name"), ParmList_errorstr(nodes[j].parms),
+			             Getattr(nodes[i].n,"name"), ParmList_errorstr(nodes[i].parms),
+				     Getfile(nodes[i].n), Getline(nodes[i].n));
+                    }
+                  }
+		  nodes[j].error = 1;
+		}
+	      }
+	      Delete(dq1);
+	      Delete(dq2);
+	    }
+	  }
+	  if (!differ) {
+	    if (!nodes[j].error) {
+              if (script_lang_wrapping) {
+	        Swig_warning(WARN_LANG_OVERLOAD_SHADOW, Getfile(nodes[j].n), Getline(nodes[j].n),
+			     "Overloaded %s(%s)%s is shadowed by %s(%s)%s at %s:%d.\n",
+			     Getattr(nodes[j].n,"name"), ParmList_errorstr(nodes[j].parms),
+			     SwigType_isconst(Getattr(nodes[j].n,"decl")) ? " const" : "", 
+			     Getattr(nodes[i].n,"name"), ParmList_errorstr(nodes[i].parms),
+			     SwigType_isconst(Getattr(nodes[i].n,"decl")) ? " const" : "", 
+			     Getfile(nodes[i].n),Getline(nodes[i].n));
+              } else {
+                if (!Getattr(nodes[j].n, "overload:ignore"))
+	          Swig_warning(WARN_LANG_OVERLOAD_IGNORED, Getfile(nodes[j].n), Getline(nodes[j].n),
+			       "Overloaded method %s(%s)%s ignored. Method %s(%s)%s at %s:%d used.\n",
+			       Getattr(nodes[j].n,"name"), ParmList_errorstr(nodes[j].parms),
+			       SwigType_isconst(Getattr(nodes[j].n,"decl")) ? " const" : "", 
+                               Getattr(nodes[i].n,"name"), ParmList_errorstr(nodes[i].parms),
+			       SwigType_isconst(Getattr(nodes[i].n,"decl")) ? " const" : "", 
+			       Getfile(nodes[i].n),Getline(nodes[i].n));
+              }
+	      nodes[j].error = 1;
+	    }
+	  }
+	}
+      }
+    }
+  }
+  List *result = NewList();
+  {
+    int i;
+    for (i = 0; i < nnodes; i++) {
+      if (nodes[i].error)
+        Setattr(nodes[i].n, "overload:ignore", "1");
+      Append(result,nodes[i].n);
+      //      Printf(stdout,"[ %d ] %s\n", i, ParmList_errorstr(nodes[i].parms));
+      //      Swig_print_node(nodes[i].n);
+    }
+  }
+  return result;
+}
+
+void R::dispatchFunction(Node *n) {
+  Wrapper *f = NewWrapper();
+  String *symname = Getattr(n, "sym:name");
+  String *nodeType = Getattr(n, "nodeType");
+  bool constructor = (!Cmp(nodeType, "constructor")); 
+
+  String *sfname = NewString(symname);
+
+  if (constructor)
+    Replace(sfname, "new_", "", DOH_REPLACE_FIRST);
+
+  Printf(f->def,
+	 "`%s` <- function(...) {", sfname);
+  List *dispatch = Swig_overload_rank(n, true);
+  int   nfunc = Len(dispatch);
+  Printv(f->code, 
+	 "argtypes <- mapply(class, list(...))\n",
+	 "argv <- list(...)\n",
+	 "argc <- length(argtypes)\n", NIL );
+
+  Printf(f->code, "# dispatch functions %d\n", nfunc);
+  int cur_args = -1;
+  bool first_compare = true;
+  for (int i=0; i < nfunc; i++) {
+    Node *ni = Getitem(dispatch,i);
+    Parm *pi = Getattr(ni,"wrap:parms");
+    int num_arguments = emit_num_arguments(pi);
+
+    String *overname = Getattr(ni,"sym:overname");      
+    if (cur_args != num_arguments) {
+      if (cur_args != -1) {
+	Printv(f->code, "} else ", NIL);
+      }
+      Printf(f->code, "if (argc == %d) {", num_arguments);
+      cur_args = num_arguments;
+      first_compare = true;
+    }
+    Parm *p;
+    int j;
+    if (num_arguments > 0) {
+      if (!first_compare) {
+	Printv(f->code, " else ", NIL);
+      } else {
+	first_compare = false;
+      }
+      Printv(f->code, "if (", NIL);
+      for (p =pi, j = 0 ; j < num_arguments ; j++) {
+	String *tm = Swig_typemap_lookup("rtype", p, "", 0);
+	if(tm) {
+	  replaceRClass(tm, Getattr(p, "type"));
+	}
+	if (DohStrcmp(tm,"numeric")==0) {
+	Printf(f->code, "%sis.numeric(argv[[%d]])",
+	       j == 0 ? "" : " && ",
+	       j+1);
+	}
+	else {
+	Printf(f->code, "%sextends(argtypes[%d], '%s')",
+	       j == 0 ? "" : " && ",
+	       j+1,
+	       tm);
+	}
+	p = Getattr(p, "tmap:in:next");
+      }
+      Printf(f->code, ") { f <- %s%s }\n", sfname, overname);
+    } else {
+      Printf(f->code, "f <- %s%s", sfname, overname);
+    }
+  }
+  if (cur_args != -1) {
+    Printv(f->code, "}", NIL);
+  }
+  Printv(f->code, "\nf(...)", NIL);
+  Printv(f->code, "\n}", NIL);
+  Wrapper_print(f, sfile);
+  Printv(sfile, "# Dispatch function\n", NIL);
+  DelWrapper(f);
+}
+
+/******************************************************************
+
+*******************************************************************/
+int R::functionWrapper(Node *n) {
+  String *fname = Getattr(n, "name");
+  String *iname = Getattr(n, "sym:name");
+  String *type = Getattr(n, "type"); 
+  
+  if (debugMode) {
+    Printf(stderr, 
+	   "<functionWrapper> %s %s %s\n", fname, iname, type);
+  }
+  String *overname = 0;
+  String *nodeType = Getattr(n, "nodeType");
+  bool constructor = (!Cmp(nodeType, "constructor")); 
+  bool destructor = (!Cmp(nodeType, "destructor")); 
+  
+  String *sfname = NewString(iname);
+  
+  if (constructor)
+    Replace(sfname, "new_", "", DOH_REPLACE_FIRST);
+  
+  if (Getattr(n,"sym:overloaded")) {
+    overname = Getattr(n,"sym:overname");      
+    Append(sfname, overname);
+  }
+  
+  if (debugMode) 
+    Printf(stderr, 
+	   "<functionWrapper> processing parameters\n");
+  
+  
+  ParmList *l = Getattr(n, "parms");
+  Parm *p;
+  String *tm;
+  
+  p = l;
+  while(p) {
+    SwigType *resultType = Getattr(p, "type");
+    if (expandTypedef(resultType) && 
+	SwigType_istypedef(resultType)) {
+      SwigType *resolved =
+	SwigType_typedef_resolve_all(resultType);
+      if (expandTypedef(resolved)) {
+	Setattr(p, "type", Copy(resolved));
+      }
+    }
+    p = nextSibling(p);
+  } 
+  
+  String *unresolved_return_type = 
+    Copy(type);
+  if (expandTypedef(type) &&
+      SwigType_istypedef(type)) {
+    SwigType *resolved = 
+      SwigType_typedef_resolve_all(type);
+    if (expandTypedef(resolved)) {
+      type = Copy(resolved);
+      Setattr(n, "type", type);
+    }
+  }
+  if (debugMode) 
+    Printf(stderr, "<functionWrapper> unresolved_return_type %s\n",
+	   unresolved_return_type);
+  if(processing_member_access_function) {
+    if (debugMode)
+      Printf(stderr, "<functionWrapper memberAccess> '%s' '%s' '%s' '%s'\n", 
+	     fname, iname, member_name, class_name);
+    
+    if(opaqueClassDeclaration)
+      return SWIG_OK;
+      
+      
+    /* Add the name of this member to a list for this class_name. 
+       We will dump all these at the end. */
+    
+    int n = Len(iname);
+    char *ptr = Char(iname);
+    bool isSet(Strcmp(NewString(&ptr[n-3]), "set") == 0);
+    
+    
+    String *tmp = NewString("");
+    Printf(tmp, "%s_%s", class_name, isSet ? "set" : "get");
+    
+    List *memList = Getattr(ClassMemberTable, tmp);
+    if(!memList) {
+      memList = NewList();
+      Append(memList, class_name);
+      Setattr(ClassMemberTable, tmp, memList);
+    }
+    Delete(tmp);
+    Append(memList, member_name);
+    Append(memList, iname);
+  }
+  
+  int i;
+  int nargs, num_required, varargs;
+  UNUSED(varargs);
+  
+  String *wname = Swig_name_wrapper(iname);
+  Replace(wname, "_wrap", "R_swig", DOH_REPLACE_FIRST);
+  if(overname) 
+    Append(wname, overname);
+  Setattr(n,"wrap:name", wname);
+
+  Wrapper *f = NewWrapper();
+  Wrapper *sfun = NewWrapper();
+    
+  int isVoidReturnType = (Strcmp(type, "void") == 0);
+  // Need to use the unresolved return type since 
+  // typedef resolution removes the const which causes a 
+  // mismatch with the function action
+  emit_return_variable(n, unresolved_return_type, f);
+
+  SwigType *rtype = Getattr(n, "type");
+  int addCopyParam = 0;
+
+  if(!isVoidReturnType) 
+    addCopyParam = addCopyParameter(rtype);
+
+
+  // Can we get the nodeType() of the type node! and see if it is a struct.
+  //    int addCopyParam = SwigType_isclass(rtype);
+
+  //    if(addCopyParam)
+  if (debugMode)
+    Printf(stderr, "Adding a .copy argument to %s for %s = %s\n", 
+	   iname, type, addCopyParam ? "yes" : "no");
+
+  Printv(f->def, "SWIGEXPORT SEXP\n", wname, " ( ", NIL);
+
+  Printf(sfun->def, "# Start of %s\n", iname);         
+  Printv(sfun->def, "\n`", sfname, "` = function(", NIL);
+
+  if(outputNamespaceInfo) //XXX Need to be a little more discriminating
+    addNamespaceFunction(iname);
+
+  Swig_typemap_attach_parms("scoercein", l, f);
+  Swig_typemap_attach_parms("scoerceout", l, f);
+  Swig_typemap_attach_parms("scheck", l, f);
+
+  emit_parameter_variables(l, f);
+  emit_attach_parmmaps(l,f);
+  Setattr(n,"wrap:parms",l);
+
+  nargs = emit_num_arguments(l);
+  num_required = emit_num_required(l);
+  varargs = emit_isvarargs(l);
+
+  Wrapper_add_local(f, "r_nprotect", "unsigned int r_nprotect = 0");
+  Wrapper_add_localv(f, "r_ans", "SEXP", "r_ans = R_NilValue", NIL);
+  Wrapper_add_localv(f, "r_vmax", "VMAXTYPE", "r_vmax = vmaxget()", NIL);
+
+  String *sargs = NewString("");
+
+
+  String *s_inputTypes = NewString("");
+  String *s_inputMap = NewString("");
+  bool inFirstArg = true;
+  bool inFirstType = true;
+  Parm *curP;
+  for (p =l, i = 0 ; i < nargs ; i++) {
+
+    while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    }
+
+    SwigType *tt = Getattr(p, "type");
+    int nargs = -1;
+    String *funcptr_name = processType(tt, p, &nargs);
+
+    //      SwigType *tp = Getattr(p, "type");
+    String   *name  = Getattr(p,"name");
+    String   *lname  = Getattr(p,"lname");
+
+    // R keyword renaming
+    if (name && Swig_name_warning(p, 0, name, 0))
+      name = 0;
+
+    /* If we have a :: in the parameter name because we are accessing a static member of a class, say, then
+       we need to remove that prefix. */
+    while (Strstr(name, "::")) {
+      //XXX need to free.
+      name = NewStringf("%s", Strchr(name, ':') + 2);
+      if (debugMode)
+	Printf(stderr, "+++  parameter name with :: in it %s\n", name);
+    }
+    if (Len(name) == 0)
+      name = NewStringf("s_arg%d", i+1);
+
+    name = replaceInitialDash(name);
+
+    if (!Strncmp(name, "arg", 3)) {
+      name = Copy(name);
+      Insert(name, 0, "s_");
+    }
+      
+    if(processing_variable) {
+      name = Copy(name);
+      Insert(name, 0, "s_");
+    }
+
+    if(!Strcmp(name, fname)) {
+      name = Copy(name);
+      Insert(name, 0, "s_");
+    }
+
+    Printf(sargs, "%s, ", name);
+
+    String *tm;
+    if((tm = Getattr(p, "tmap:scoercein"))) {
+      Replaceall(tm, "$input", name);
+      replaceRClass(tm, Getattr(p, "type"));
+
+      if(funcptr_name) {
+	//XXX need to get this to return non-zero
+	if(nargs == -1)
+	  nargs = getFunctionPointerNumArgs(p, tt);
+
+	String *snargs = NewStringf("%d", nargs);
+	Printv(sfun->code, "if(is.function(", name, ")) {", "\n",
+	       "assert('...' %in% names(formals(", name, 
+	       ")) || length(formals(", name, ")) >= ", snargs, ")\n} ", NIL);
+	Delete(snargs);
+
+	Printv(sfun->code, "else {\n",
+	       "if(is.character(", name, ")) {\n",
+	       name, " = getNativeSymbolInfo(", name, ")",
+	       "\n}\n",
+	       "if(is(", name, ", \"NativeSymbolInfo\")) {\n",
+	       name, " = ", name, "$address", "\n}\n",
+	       "}\n",
+	       NIL);
+      } else {
+	Printf(sfun->code, "%s\n", tm);
+      }
+    }
+
+    Printv(sfun->def, inFirstArg ? "" : ", ", name, NIL);
+
+    if ((tm = Getattr(p,"tmap:scheck"))) {
+
+      Replaceall(tm,"$target", lname);
+      Replaceall(tm,"$source", name);
+      Replaceall(tm,"$input", name);
+      replaceRClass(tm, Getattr(p, "type"));
+      Printf(sfun->code,"%s\n",tm);
+    }
+
+
+
+    curP = p;
+    if ((tm = Getattr(p,"tmap:in"))) {
+
+      Replaceall(tm,"$target", lname);
+      Replaceall(tm,"$source", name);
+      Replaceall(tm,"$input", name);
+
+      if (Getattr(p,"wrap:disown") || (Getattr(p,"tmap:in:disown"))) {
+	Replaceall(tm,"$disown","SWIG_POINTER_DISOWN");
+      } else {
+	Replaceall(tm,"$disown","0");
+      }
+
+      if(funcptr_name) {
+	/* have us a function pointer */
+	Printf(f->code, "if(TYPEOF(%s) != CLOSXP) {\n", name);
+	Replaceall(tm,"$R_class", "");
+      } else {
+	replaceRClass(tm, Getattr(p, "type"));
+      }
+
+
+      Printf(f->code,"%s\n",tm);
+      if(funcptr_name) 
+	Printf(f->code, "} else {\n%s = %s;\nR_SWIG_pushCallbackFunctionData(%s, NULL);\n}\n", 
+	       lname, funcptr_name, name);
+      Printv(f->def, inFirstArg ? "" : ", ", "SEXP ", name, NIL);
+      if (Len(name) != 0) 
+	inFirstArg = false;
+      p = Getattr(p,"tmap:in:next");
+
+    } else {
+      p = nextSibling(p);
+    }
+
+
+    tm = Swig_typemap_lookup("rtype", curP, "", 0);
+    if(tm) {
+      replaceRClass(tm, Getattr(curP, "type"));
+    }
+    Printf(s_inputTypes, "%s'%s'", inFirstType ? "" : ", ", tm);
+    Printf(s_inputMap, "%s%s='%s'", inFirstType ? "" : ", ", name, tm);
+    inFirstType = false;
+
+    if(funcptr_name) 
+      Delete(funcptr_name);
+  } /* end of looping over parameters. */
+
+  if(addCopyParam) {
+    Printf(sfun->def, "%s.copy = FALSE", nargs > 0 ? ", " : "");
+    Printf(f->def, "%sSEXP s_swig_copy", nargs > 0 ? ", " : "");
+
+    Printf(sargs, "as.logical(.copy), ");
+  }
+
+  Printv(f->def, ")\n{\n", NIL);
+  Printv(sfun->def, ")\n{\n", NIL);
+
+
+  /* Insert cleanup code */
+  String *cleanup = NewString("");
+  for (p = l; p;) {
+    if ((tm = Getattr(p, "tmap:freearg"))) {
+      Replaceall(tm, "$source", Getattr(p, "lname"));
+      Printv(cleanup, tm, "\n", NIL);
+      p = Getattr(p, "tmap:freearg:next");
+    } else {
+      p = nextSibling(p);
+    }
+  }
+
+  String *outargs = NewString("");
+  int numOutArgs = isVoidReturnType ? -1 : 0;
+  for(p = l, i = 0; p; i++) {
+    if((tm = Getattr(p, "tmap:argout"))) {
+      //       String *lname =  Getattr(p, "lname");
+      numOutArgs++;
+      String *pos = NewStringf("%d", numOutArgs);
+      Replaceall(tm,"$source", Getattr(p, "lname"));
+      Replaceall(tm,"$result", "r_ans");
+      Replaceall(tm,"$n", pos); // The position into which to store the answer.
+      Replaceall(tm,"$arg", Getattr(p, "emit:input"));
+      Replaceall(tm,"$input", Getattr(p, "emit:input"));
+      Replaceall(tm,"$owner", "R_SWIG_EXTERNAL");
+
+
+      Printf(outargs, "%s\n", tm);
+      p = Getattr(p,"tmap:argout:next");
+    } else
+      p = nextSibling(p);
+  }
+
+  String *actioncode = emit_action(n);
+
+  /* Deal with the explicit return value. */
+  if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) { 
+    SwigType *retType = Getattr(n, "type");
+    //Printf(stderr, "Return Value for %s, array? %s\n", retType, SwigType_isarray(retType) ? "yes" : "no");     
+    /*      if(SwigType_isarray(retType)) {
+	    defineArrayAccessors(retType);
+	    } */
+
+
+    Replaceall(tm,"$1", "result");
+    Replaceall(tm,"$result", "r_ans");
+    replaceRClass(tm, retType);
+
+    if (GetFlag(n,"feature:new")) {
+      Replaceall(tm, "$owner", "R_SWIG_OWNER");
+    } else {
+      Replaceall(tm,"$owner", "R_SWIG_EXTERNAL");
+    }
+
+#if 0
+    if(addCopyParam) {
+      Printf(f->code, "if(LOGICAL(s_swig_copy)[0]) {\n");
+      Printf(f->code, "/* Deal with returning a reference. */\nr_ans = R_NilValue;\n");
+      Printf(f->code, "}\n else {\n");
+    } 
+#endif
+    Printf(f->code, "%s\n", tm);
+#if 0
+    if(addCopyParam) 
+      Printf(f->code, "}\n"); /* end of if(s_swig_copy) ... else { ... } */
+#endif
+
+  } else {
+    Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number,
+		 "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), fname);
+  }
+
+
+  if(Len(outargs)) {
+    Wrapper_add_local(f, "R_OutputValues", "SEXP R_OutputValues");
+
+    String *tmp = NewString("");
+    if(!isVoidReturnType)
+      Printf(tmp, "Rf_protect(r_ans);\n");
+
+    Printf(tmp, "Rf_protect(R_OutputValues = Rf_allocVector(VECSXP,%d));\nr_nprotect += %d;\n", 
+	   numOutArgs + !isVoidReturnType, 
+	   isVoidReturnType ? 1 : 2);
+
+    if(!isVoidReturnType)
+      Printf(tmp, "SET_VECTOR_ELT(R_OutputValues, 0, r_ans);\n");
+    Printf(tmp, "r_ans = R_OutputValues;\n");
+
+    Insert(outargs, 0, tmp);
+    Delete(tmp); 
+
+
+
+    Printv(f->code, outargs, NIL);
+    Delete(outargs);
+
+  }
+
+  /* Output cleanup code */
+  Printv(f->code, cleanup, NIL);
+  Delete(cleanup);
+
+
+
+  Printv(f->code, UnProtectWrapupCode, NIL);
+
+  /*If the user gave us something to convert the result in  */
+  if ((tm = Swig_typemap_lookup("scoerceout", n, 
+				    "result", sfun))) {
+    Replaceall(tm,"$source","ans");
+    Replaceall(tm,"$result","ans");
+    replaceRClass(tm, Getattr(n, "type"));
+    Chop(tm);
+  }
+
+
+  Printv(sfun->code, (Len(tm) ? "ans = " : ""), ".Call('", wname, 
+	 "', ", sargs, "PACKAGE='", Rpackage, "')\n", NIL);
+  if(Len(tm))
+    Printf(sfun->code, "%s\n\nans\n", tm);
+  if (destructor)
+    Printv(f->code, "R_ClearExternalPtr(self);\n", NIL);
+
+  Printv(f->code, "return r_ans;\n}\n", NIL);
+  Printv(sfun->code, "\n}", NIL);
+
+  /* Substitute the function name */
+  Replaceall(f->code,"$symname",iname);
+
+  Wrapper_print(f, f_wrapper);
+  Wrapper_print(sfun, sfile);
+
+  Printf(sfun->code, "\n# End of %s\n", iname);
+  tm = Swig_typemap_lookup("rtype", n, "", 0);
+  if(tm) {
+    SwigType *retType = Getattr(n, "type");
+    replaceRClass(tm, retType);
+  }  
+    
+  Printv(sfile, "attr(`", sfname, "`, 'returnType') = '", 
+	 isVoidReturnType ? "void" : (tm ? tm : ""), 
+	 "'\n", NIL); 
+    
+  if(nargs > 0)
+    Printv(sfile, "attr(`", sfname, "`, \"inputTypes\") = c(",
+	   s_inputTypes, ")\n", NIL);
+  Printv(sfile, "class(`", sfname, "`) = c(\"SWIGFunction\", class('", 
+	 sfname, "'))\n\n", NIL); 
+
+  if (memoryProfile) {
+    Printv(sfile, "memory.profile()\n", NIL);
+  }
+  if (aggressiveGc) {
+    Printv(sfile, "gc()\n", NIL);
+  }
+
+  // Printv(sfile, "setMethod('", name, "', '", name, "', ", iname, ")\n\n\n");
+
+
+
+  /* If we are dealing with a method in an C++ class, then 
+     add the name of the R function and its definition. 
+     XXX need to figure out how to store the Wrapper if possible in the hash/list.
+     Would like to be able to do this so that we can potentialy insert
+  */
+  if(processing_member_access_function || processing_class_member_function) {
+    String *tmp;
+    if(member_name)
+      tmp = member_name;
+    else
+      tmp = Getattr(n, "memberfunctionHandler:name");
+    addAccessor(member_name, sfun, iname);
+  }
+
+  if (Getattr(n, "sym:overloaded") &&
+      !Getattr(n, "sym:nextSibling")) {
+    dispatchFunction(n);
+  }
+
+  addRegistrationRoutine(wname, addCopyParam ? nargs +1 : nargs);
+
+  DelWrapper(f);
+  DelWrapper(sfun);
+
+  Delete(sargs);
+  Delete(sfname);
+  return SWIG_OK;
+}
+
+/*****************************************************
+ Add the specified routine name to the collection of 
+ generated routines that are called from R functions.
+ This is used to register the routines with R for 
+ resolving symbols.
+
+ rname - the name of the routine
+ nargs - the number of arguments it expects. 
+******************************************************/
+int R::addRegistrationRoutine(String *rname, int nargs) {
+  if(!registrationTable) 
+    registrationTable = NewHash();
+
+  String *el = 
+    NewStringf("{\"%s\", (DL_FUNC) &%s, %d}", rname, rname, nargs);
+  
+  Setattr(registrationTable, rname, el);
+
+  return SWIG_OK;
+}
+
+/*****************************************************
+ Write the registration information to an array and
+ create the initialization routine for registering
+ these.
+******************************************************/
+int R::outputRegistrationRoutines(File *out) {
+  int i, n;
+  if(!registrationTable) 
+    return(0);
+  if(inCPlusMode) 
+    Printf(out, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n");
+
+  Printf(out, "#include <R_ext/Rdynload.h>\n\n");
+  if(inCPlusMode) 
+    Printf(out, "#ifdef __cplusplus\n}\n#endif\n\n");
+
+  Printf(out, "SWIGINTERN R_CallMethodDef CallEntries[] = {\n");
+    
+  List *keys = Keys(registrationTable);
+  n = Len(keys);
+  for(i = 0; i < n; i++)
+    Printf(out, "   %s,\n", Getattr(registrationTable, Getitem(keys, i)));
+
+  Printf(out, "   {NULL, NULL, 0}\n};\n\n");
+
+  if(!noInitializationCode) {
+    if (inCPlusMode)
+      Printv(out, "extern \"C\" ", NIL);
+    Printf(out, "SWIGEXPORT void R_init_%s(DllInfo *dll) {\n", Rpackage);
+    Printf(out, "%sR_registerRoutines(dll, NULL, CallEntries, NULL, NULL);\n", tab4);
+    if(Len(s_init_routine)) {
+      Printf(out, "\n%s\n", s_init_routine);
+    }
+    Printf(out, "}\n");
+  }
+
+  return n;
+}
+
+
+
+/****************************************************************************
+  Process a struct, union or class declaration in the source code,
+  or an anonymous typedef struct
+ 
+*****************************************************************************/
+//XXX What do we need to do here - 
+// Define an S4 class to refer to this.
+
+void R::registerClass(Node *n) {
+  String *name = Getattr(n, "name");    
+  String *kind = Getattr(n, "kind");    
+
+  if (debugMode)
+    Swig_print_node(n);
+  String *sname = NewStringf("_p%s", SwigType_manglestr(name));
+  if(!Getattr(SClassDefs, sname)) {
+    Setattr(SClassDefs, sname, sname);
+    String *base;
+
+    if(Strcmp(kind, "class") == 0) {
+      base = NewString("");
+      List *l = Getattr(n, "bases");
+      if(Len(l)) {
+	Printf(base, "c(");
+	for(int i = 0; i < Len(l); i++) {
+	  registerClass(Getitem(l, i));
+	  Printf(base, "'_p%s'%s", 
+		 SwigType_manglestr(Getattr(Getitem(l, i), "name")), 
+		 i < Len(l)-1 ? ", " : "");                
+	}
+	Printf(base, ")");
+      } else {
+	base = NewString("'C++Reference'");
+      }
+    } else 
+      base = NewString("'ExternalReference'");
+
+    Printf(s_classes, "setClass('%s', contains = %s)\n", sname, base);
+    Delete(base);
+  }
+  
+}
+
+int R::classDeclaration(Node *n) {
+
+  String *name = Getattr(n, "name");    
+  String *kind = Getattr(n, "kind");    
+
+  if (debugMode)
+    Swig_print_node(n);
+  registerClass(n);
+
+    
+  /* If we have a typedef union { ... } U, then we never get to see the typedef
+     via a regular call to typedefHandler. Instead, */
+  if(Getattr(n, "unnamed") && Strcmp(Getattr(n, "storage"), "typedef") == 0 
+     && Getattr(n, "tdname") && Strcmp(Getattr(n, "tdname"), name) == 0) {
+    if (debugMode)
+      Printf(stderr, "Typedef in the class declaration for %s\n", name);
+    //        typedefHandler(n);
+  }
+
+  bool opaque = GetFlag(n, "feature:opaque") ? true : false;
+
+  if(opaque)
+    opaqueClassDeclaration = name;
+
+  int status = Language::classDeclaration(n);
+
+  opaqueClassDeclaration = NULL;
+
+
+  // OutputArrayMethod(name, class_member_functions, sfile);        
+  if (class_member_functions)
+    OutputMemberReferenceMethod(name, 0, class_member_functions, sfile);
+  if (class_member_set_functions)
+    OutputMemberReferenceMethod(name, 1, class_member_set_functions, sfile);
+
+  if(class_member_functions) {
+    Delete(class_member_functions);
+    class_member_functions = NULL;
+  }
+  if(class_member_set_functions) {
+    Delete(class_member_set_functions);
+    class_member_set_functions = NULL;
+  }
+  if (Getattr(n, "has_destructor")) {
+    Printf(sfile, "setMethod('delete', '_p%s', function(obj) {delete%s(obj)})\n",
+	   getRClassName(Getattr(n, "name")),
+	   getRClassName(Getattr(n, "name")));
+
+  }
+  if(!opaque && !Strcmp(kind, "struct") && copyStruct) {
+
+    String *def = 
+      NewStringf("setClass(\"%s\",\n%srepresentation(\n", name, tab4);
+    bool firstItem = true;
+
+    for(Node *c = firstChild(n); c; ) {
+      String *elName;
+      String *tp;
+
+      elName = Getattr(c, "name");
+ 
+      String *elKind = Getattr(c, "kind");
+      if (Strcmp(elKind, "variable") != 0) {
+	c = nextSibling(c);
+	continue;
+      }
+      if (!Len(elName)) {
+	c = nextSibling(c);
+	continue;
+      }
+#if 0
+      tp = getRType(c);
+#else
+      tp = Swig_typemap_lookup("rtype", c, "", 0);
+      if(!tp) {
+	c = nextSibling(c);
+	continue;
+      }
+      if (Strstr(tp, "R_class")) {
+	c = nextSibling(c);
+	continue;
+      }
+      if (Strcmp(tp, "character") &&
+	  Strstr(Getattr(c, "decl"), "p.")) {
+	c = nextSibling(c);
+	continue;
+      }
+
+      if (!firstItem) {
+	Printf(def, ",\n");
+      } 
+      //	    else 
+      //XXX How can we tell if this is already done.
+      //	      SwigType_push(elType, elDecl);
+	    
+	    
+      // returns ""  tp = processType(elType, c, NULL);
+      //	    Printf(stderr, "<classDeclaration> elType %p\n", elType);
+      //	    tp = getRClassNameCopyStruct(Getattr(c, "type"), 1);
+#endif
+      String *elNameT = replaceInitialDash(elName);
+      Printf(def, "%s%s = \"%s\"", tab8, elNameT, tp);
+      firstItem = false;
+      Delete(tp);
+      Delete(elNameT);
+      c = nextSibling(c);
+    }
+    Printf(def, "),\n%scontains = \"RSWIGStruct\")\n", tab8);
+    Printf(s_classes, "%s\n\n# End class %s\n\n", def, name);
+
+    generateCopyRoutines(n);
+
+    Delete(def);
+  }
+
+  return status;
+}
+
+
+
+/***************************************************************
+ Create the C routines that copy an S object of the class given
+ by the given struct definition in Node *n to the C value
+ and also the routine that goes from the C routine to an object
+ of this S class.
+****************************************************************/
+/*XXX
+  Clean up the toCRef - make certain the names are correct for the types, etc.
+  in all cases.
+*/
+
+int R::generateCopyRoutines(Node *n) {
+  Wrapper *copyToR = NewWrapper();
+  Wrapper *copyToC = NewWrapper();
+  
+  String *name = Getattr(n, "name");
+  String *tdname = Getattr(n, "tdname");
+  String *kind = Getattr(n, "kind");
+  String *type;
+
+  if(Len(tdname)) {
+    type = Copy(tdname);
+  } else {
+    type = NewStringf("%s %s", kind, name);
+  }
+
+  String *mangledName = SwigType_manglestr(name);
+
+  if (debugMode)
+    Printf(stderr, "generateCopyRoutines:  name = %s, %s\n", name, type);
+
+  Printf(copyToR->def, "CopyToR%s = function(value, obj = new(\"%s\"))\n{\n", 
+	 mangledName, name);
+  Printf(copyToC->def, "CopyToC%s = function(value, obj)\n{\n", 
+	 mangledName);
+
+  Node *c = firstChild(n);
+
+  for(; c; c = nextSibling(c)) {
+    String *elName = Getattr(c, "name");
+    if (!Len(elName)) {
+      continue;
+    }
+    String *elKind = Getattr(c, "kind");
+    if (Strcmp(elKind, "variable") != 0) {
+      Delete(elKind);
+      continue;
+    }
+
+    String *tp = Swig_typemap_lookup("rtype", c, "", 0);
+    if(!tp) {
+      continue;
+    }
+    if (Strstr(tp, "R_class")) {
+      continue;
+    }
+    if (Strcmp(tp, "character") &&
+	Strstr(Getattr(c, "decl"), "p.")) {
+      continue;
+    }
+
+
+    /* The S functions to get and set the member value. */
+    String *elNameT = replaceInitialDash(elName);
+    Printf(copyToR->code, "obj@%s = value$%s\n", elNameT, elNameT);
+    Printf(copyToC->code, "obj$%s = value@%s\n", elNameT, elNameT);
+    Delete(elNameT);
+  }
+  Printf(copyToR->code, "obj\n}\n\n");
+  String *rclassName = getRClassNameCopyStruct(type, 0); // without the Ref.
+  Printf(sfile, "# Start definition of copy functions & methods for %s\n", rclassName);  
+  
+  Wrapper_print(copyToR, sfile);
+  Printf(copyToC->code, "obj\n}\n\n");
+  Wrapper_print(copyToC, sfile);
+  
+  
+  Printf(sfile, "# Start definition of copy methods for %s\n", rclassName);  
+  Printf(sfile, "setMethod('copyToR', '_p_%s', CopyToR%s)\n", rclassName, 
+	 mangledName);
+  Printf(sfile, "setMethod('copyToC', '%s', CopyToC%s)\n\n", rclassName, 
+	 mangledName);
+  
+  Printf(sfile, "# End definition of copy methods for %s\n", rclassName);  
+  Printf(sfile, "# End definition of copy functions & methods for %s\n", rclassName);  
+      
+  String *m = NewStringf("%sCopyToR", name);
+  addNamespaceMethod(m);
+  char *tt = Char(m);  tt[Len(m)-1] = 'C';
+  addNamespaceMethod(m);
+  Delete(m);
+  Delete(rclassName);
+  Delete(mangledName);
+  DelWrapper(copyToR);
+  DelWrapper(copyToC);
+
+  return SWIG_OK;
+}
+
+
+
+/*****
+      Called when there is a typedef to be invoked. 
+
+      XXX Needs to be enhanced or split to handle the case where we have a 
+      typedef within a classDeclaration emission because the struct/union/etc.
+      is anonymous.
+******/
+int R::typedefHandler(Node *n) {
+  SwigType *tp = Getattr(n, "type");
+  String *type = Getattr(n, "type");
+  if (debugMode)
+    Printf(stderr, "<typedefHandler> %s\n", Getattr(n, "name"));
+
+  processType(tp, n);
+
+  if(Strncmp(type, "struct ", 7) == 0) {
+    String *name = Getattr(n, "name");
+    char *trueName = Char(type);
+    trueName += 7;
+    if (debugMode)
+      Printf(stderr, "<typedefHandler> Defining S class %s\n", trueName);
+    Printf(s_classes, "setClass('_p%s', contains = 'ExternalReference')\n", 
+	   SwigType_manglestr(name));
+  }
+
+  return Language::typedefHandler(n);
+}
+
+
+
+/*********************
+  Called when processing a field in a "class", i.e. struct, union or
+  actual class.  We set a state variable so that we can correctly
+  interpret the resulting functionWrapper() call and understand that 
+  it is for a field element.
+**********************/
+int R::membervariableHandler(Node *n) {
+  SwigType *t = Getattr(n, "type");
+  processType(t, n, NULL);
+  processing_member_access_function = 1;
+  member_name = Getattr(n,"sym:name");
+  if (debugMode)
+    Printf(stderr, "<membervariableHandler> name = %s, sym:name = %s\n", 
+	   Getattr(n, "name"), member_name);
+
+  int status(Language::membervariableHandler(n));
+
+  if(opaqueClassDeclaration == NULL && debugMode)
+    Printf(stderr, "<membervariableHandler> %s %s\n", Getattr(n, "name"), Getattr(n, "type"));
+
+  processing_member_access_function = 0;
+  member_name = NULL;
+
+  return status;
+}
+
+
+/*
+  This doesn't seem to get used so leave it out for the moment.
+*/
+String * R::runtimeCode() {
+  String *s = Swig_include_sys("rrun.swg");
+  if (!s) {
+    Printf(stderr, "*** Unable to open 'rrun.swg'\n");
+    s = NewString("");
+  }
+  return s;
+}
+
+
+/**
+   Called when SWIG wants to initialize this 
+   We initialize anythin we want here.
+   Most importantly, tell SWIG where to find the files (e.g. r.swg) for this module.
+   Use Swig_mark_arg() to tell SWIG that it is understood and not to throw an error.
+**/
+void R::main(int argc, char *argv[]) {
+  bool cppcast = true;
+  init();
+  SWIG_library_directory("r");
+  SWIG_config_file("r.swg");
+  Preprocessor_define("SWIGR 1", 0);
+  debugMode = false;
+  copyStruct = true;
+  memoryProfile = false;
+  aggressiveGc = false;
+  inCPlusMode = false;
+  outputNamespaceInfo = false;
+  noInitializationCode = false;
+
+  this->Argc = argc;
+  this->Argv = argv;
+
+  allow_overloading();// can we support this?    
+
+  for(int i = 0; i < argc; i++) {
+    if(strcmp(argv[i], "-package") == 0) {
+      Swig_mark_arg(i);
+      i++;
+      Swig_mark_arg(i);
+      Rpackage = argv[i];
+    } else if(strcmp(argv[i], "-dll") == 0) {
+      Swig_mark_arg(i);
+      i++;
+      Swig_mark_arg(i);
+      DllName = argv[i];
+    } else if(strcmp(argv[i], "-help") == 0) {
+      showUsage();
+    } else if(strcmp(argv[i], "-namespace") == 0) {
+      outputNamespaceInfo = true;
+      Swig_mark_arg(i);
+    } else if(!strcmp(argv[i], "-no-init-code")) {
+      noInitializationCode = true;
+      Swig_mark_arg(i);
+    } else if(!strcmp(argv[i], "-c++")) {
+      inCPlusMode = true;
+      Swig_mark_arg(i);
+      Printf(s_classes, "setClass('C++Reference', contains = 'ExternalReference')\n");
+    } else if(!strcmp(argv[i], "-debug")) {
+      debugMode = true;
+      Swig_mark_arg(i);
+    }  else if (!strcmp(argv[i],"-cppcast")) {
+      cppcast = true;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i],"-nocppcast")) {
+      cppcast = false;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i],"-copystruct")) {
+      copyStruct = true;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-nocopystruct")) {
+      copyStruct = false;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-memoryprof")) {
+      memoryProfile = true;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-nomemoryprof")) {
+      memoryProfile = false;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-aggressivegc")) {
+      aggressiveGc = true;
+      Swig_mark_arg(i);
+    } else if (!strcmp(argv[i], "-noaggressivegc")) {
+      aggressiveGc = false;
+      Swig_mark_arg(i);
+    }
+
+    if (cppcast) {
+      Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
+    }
+    /// copyToR copyToC functions.
+
+  }
+}
+
+/*
+  Could make this work for String or File and then just store the resulting string
+  rather than the collection of arguments and argc.
+*/
+int R::outputCommandLineArguments(File *out)
+{
+  if(Argc < 1 || !Argv || !Argv[0])
+    return(-1);
+
+  Printf(out, "##   Generated via the command line invocation:\n##\t");
+  for(int i = 0; i < Argc ; i++) {
+    Printf(out, " %s", Argv[i]);
+  }
+  Printf(out, "\n\n\n");
+
+  return Argc;
+}
+
+
+
+/* How SWIG instantiates an object from this module. 
+   See swigmain.cxx */
+extern "C" 
+Language *swig_r(void) {
+  return new R();
+}
+
+
+
+/*************************************************************************************/
+
+/*
+  Needs to be reworked.
+*/
+String * R::processType(SwigType *t, Node *n, int *nargs) {
+  //XXX Need to handle typedefs, e.g.
+  //  a type which is a typedef  to a function pointer.
+
+  SwigType *tmp = Getattr(n, "tdname");
+  if (debugMode)
+    Printf(stderr, "processType %s (tdname = %s)\n", Getattr(n, "name"), tmp);
+  
+  SwigType *td = t;
+  if (expandTypedef(t) &&
+      SwigType_istypedef(t)) {
+    SwigType *resolved = 
+      SwigType_typedef_resolve_all(t);
+    if (expandTypedef(resolved)) {
+      td = Copy(resolved);
+    }
+  }
+
+  if(!td) {
+    int count = 0;
+    String *b = getRTypeName(t, &count);
+    if(count && b && !Getattr(SClassDefs, b)) {
+      if (debugMode)
+	Printf(stderr, "<processType> Defining class %s\n",  b);
+
+      Printf(s_classes, "setClass('%s', contains = 'ExternalReference')\n", b);       
+      Setattr(SClassDefs, b, b);
+    }
+     
+  }
+
+
+  if(td)
+    t = td;
+
+  if(SwigType_isfunctionpointer(t)) {
+    if (debugMode)
+      Printf(stderr, 
+	     "<processType> Defining pointer handler %s\n",  t);
+       
+    String *tmp = createFunctionPointerHandler(t, n, nargs);
+    return tmp;
+  }
+
+#if 0
+  SwigType_isfunction(t) && SwigType_ispointer(t)
+#endif
+
+    return NULL;
+}
+
+
+
+
+
+
+
+
+
+/*************************************************************************************/
+
+
+
+
+
diff --git a/trunk/Source/Modules/ruby.cxx b/trunk/Source/Modules/ruby.cxx
new file mode 100644
index 0000000..ad448d3
--- /dev/null
+++ b/trunk/Source/Modules/ruby.cxx
@@ -0,0 +1,3422 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * ruby.cxx
+ *
+ * Ruby language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_ruby_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+static int treduce = SWIG_cparse_template_reduce(0);
+
+#define SWIG_PROTECTED_TARGET_METHODS 1
+
+#include <ctype.h>
+#include <string.h>
+#include <limits.h>		/* for INT_MAX */
+
+class RClass {
+private:
+  String *temp;
+
+public:
+  String *name;			/* class name (renamed) */
+  String *cname;		/* original C class/struct name */
+  String *mname;		/* Mangled name */
+
+  /**
+   * The C variable name used in the SWIG-generated wrapper code to refer to
+   * this class; usually it is of the form "cClassName.klass", where cClassName
+   * is a swig_class struct instance and klass is a member of that struct.
+   */
+  String *vname;
+
+  /**
+   * The C variable name used in the SWIG-generated wrapper code to refer to
+   * the module that implements this class's methods (when we're trying to
+   * support C++ multiple inheritance). Usually it is of the form
+   * "cClassName.mImpl", where cClassName is a swig_class struct instance
+   * and mImpl is a member of that struct.
+   */
+  String *mImpl;
+
+  String *type;
+  String *prefix;
+  String *init;
+
+
+  int constructor_defined;
+  int destructor_defined;
+
+   RClass() {
+    temp = NewString("");
+    name = NewString("");
+    cname = NewString("");
+    mname = NewString("");
+    vname = NewString("");
+    mImpl = NewString("");
+    type = NewString("");
+    prefix = NewString("");
+    init = NewString("");
+    constructor_defined = 0;
+    destructor_defined = 0;
+  }
+  
+  ~RClass() {
+    Delete(name);
+    Delete(cname);
+    Delete(vname);
+    Delete(mImpl);
+    Delete(mname);
+    Delete(type);
+    Delete(prefix);
+    Delete(init);
+    Delete(temp);
+  }
+
+  void set_name(const String_or_char *cn, const String_or_char *rn, const String_or_char *valn) {
+    /* Original C/C++ class (or struct) name */
+    Clear(cname);
+    Append(cname, cn);
+
+    /* Mangled name */
+    Delete(mname);
+    mname = Swig_name_mangle(cname);
+
+    /* Renamed class name */
+    Clear(name);
+    Append(name, valn);
+
+    /* Variable name for the VALUE that refers to the Ruby Class object */
+    Clear(vname);
+    Printf(vname, "c%s.klass", name);
+
+    /* Variable name for the VALUE that refers to the Ruby Class object */
+    Clear(mImpl);
+    Printf(mImpl, "c%s.mImpl", name);
+
+    /* Prefix */
+    Clear(prefix);
+    Printv(prefix, (rn ? rn : cn), "_", NIL);
+  }
+
+  char *strip(const String_or_char *s) {
+    Clear(temp);
+    Append(temp, s);
+    if (Strncmp(s, prefix, Len(prefix)) == 0) {
+      Replaceall(temp, prefix, "");
+    }
+    return Char(temp);
+  }
+};
+
+
+/* flags for the make_autodoc function */
+enum autodoc_t {
+  AUTODOC_CLASS,
+  AUTODOC_CTOR,
+  AUTODOC_DTOR,
+  AUTODOC_STATICFUNC,
+  AUTODOC_FUNC,
+  AUTODOC_METHOD,
+  AUTODOC_GETTER,
+  AUTODOC_SETTER
+};
+
+static const char *usage = "\
+Ruby Options (available with -ruby)\n\
+     -globalmodule   - Wrap everything into the global module\n\
+     -minherit       - Attempt to support multiple inheritance\n\
+     -nocppcast      - Disable C++ casting operators, useful for generating bugs\n\
+     -cppcast        - Enable C++ casting operators (default)\n\
+     -autorename     - Enable renaming of classes and methods to follow Ruby coding standards\n\
+     -noautorename   - Disable renaming of classes and methods (default)\n\
+     -prefix <name>  - Set a prefix <name> to be prepended to all names\n\
+     -initname <name> - Set entry function to Init_<name> (used by `require')\n";
+
+
+#define RCLASS(hash, name) (RClass*)(Getattr(hash, name) ? Data(Getattr(hash, name)) : 0)
+#define SET_RCLASS(hash, name, klass) Setattr(hash, name, NewVoid(klass, 0))
+
+
+class RUBY:public Language {
+private:
+
+  String *module;
+  String *modvar;
+  String *feature;
+  String *prefix;
+  int current;
+  Hash *classes;		/* key=cname val=RClass */
+  RClass *klass;		/* Currently processing class */
+  Hash *special_methods;	/* Python style special method name table */
+
+  File *f_directors;
+  File *f_directors_h;
+  File *f_directors_helpers;
+  File *f_runtime;
+  File *f_runtime_h;
+  File *f_header;
+  File *f_wrappers;
+  File *f_init;
+  File *f_initbeforefunc;
+
+  bool useGlobalModule;
+  bool multipleInheritance;
+
+  // Wrap modes
+  enum WrapperMode {
+    NO_CPP,
+    MEMBER_FUNC,
+    CONSTRUCTOR_ALLOCATE,
+    CONSTRUCTOR_INITIALIZE,
+    DESTRUCTOR,
+    MEMBER_VAR,
+    CLASS_CONST,
+    STATIC_FUNC,
+    STATIC_VAR
+  };
+
+  /* ------------------------------------------------------------
+   * autodoc level declarations
+   * ------------------------------------------------------------ */
+
+  enum autodoc_l {
+    NO_AUTODOC = -2,		// no autodoc
+    STRING_AUTODOC = -1,	// use provided string
+    NAMES_AUTODOC = 0,		// only parameter names
+    TYPES_AUTODOC = 1,		// parameter names and types
+    EXTEND_AUTODOC = 2,		// extended documentation and parameter names
+    EXTEND_TYPES_AUTODOC = 3	// extended documentation and parameter types + names
+  };
+
+  autodoc_t last_mode;
+  String*   last_autodoc;
+
+
+
+  autodoc_l autodoc_level(String *autodoc) {
+    autodoc_l dlevel = NO_AUTODOC;
+    if (autodoc) {
+      char *c = Char(autodoc);
+      if (c && isdigit(c[0])) {
+	dlevel = (autodoc_l) atoi(c);
+      } else {
+	if (strcmp(c, "extended") == 0) {
+	  dlevel = EXTEND_AUTODOC;
+	} else {
+	  dlevel = STRING_AUTODOC;
+	}
+      }
+    }
+    return dlevel;
+  }
+
+
+
+  /* ------------------------------------------------------------
+   * have_docstring()
+   *    Check if there is a docstring directive and it has text,
+   *    or there is an autodoc flag set
+   * ------------------------------------------------------------ */
+
+  bool have_docstring(Node *n) {
+    String *str = Getattr(n, "feature:docstring");
+    return (str != NULL && Len(str) > 0) || (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
+  }
+
+  /* ------------------------------------------------------------
+   * docstring()
+   *    Get the docstring text, stripping off {} if neccessary,
+   *    and enclose in triple double quotes.  If autodoc is also
+   *    set then it will build a combined docstring.
+   * ------------------------------------------------------------ */
+
+  String *docstring(Node *n, autodoc_t ad_type) {
+
+    String *str = Getattr(n, "feature:docstring");
+    bool have_ds = (str != NULL && Len(str) > 0);
+    bool have_auto = (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
+    String *autodoc = NULL;
+    String *doc = NULL;
+
+    if (have_ds) {
+      char *t = Char(str);
+      if (*t == '{') {
+	Delitem(str, 0);
+	Delitem(str, DOH_END);
+      }
+    }
+
+    if (have_auto) {
+      autodoc = make_autodoc(n, ad_type);
+      have_auto = (autodoc != NULL && Len(autodoc) > 0);
+    }
+    // If there is more than one line then make docstrings like this:
+    //
+    //      This is line1
+    //      And here is line2 followed by the rest of them
+    //
+    // otherwise, put it all on a single line
+    //
+    if (have_auto && have_ds) {	// Both autodoc and docstring are present
+      doc = NewString("");
+      Printv(doc, "\n", autodoc, "\n", str, NIL);
+    } else if (!have_auto && have_ds) {	// only docstring
+      if (Strchr(str, '\n') == NULL) {
+	doc = NewString(str);
+      } else {
+	doc = NewString("");
+	Printv(doc, str, NIL);
+      }
+    } else if (have_auto && !have_ds) {	// only autodoc
+      if (Strchr(autodoc, '\n') == NULL) {
+	doc = NewStringf("%s", autodoc);
+      } else {
+	doc = NewString("");
+	Printv(doc, "\n", autodoc, NIL);
+      }
+    } else
+      doc = NewString("");
+
+    // Save the generated strings in the parse tree in case they are used later
+    // by post processing tools
+    Setattr(n, "ruby:docstring", doc);
+    Setattr(n, "ruby:autodoc", autodoc);
+    return doc;
+  }
+
+  /* ------------------------------------------------------------
+   * make_autodocParmList()
+   *   Generate the documentation for the function parameters
+   * ------------------------------------------------------------ */
+
+  String *make_autodocParmList(Node *n, bool showTypes) {
+    String *doc = NewString("");
+    String *pdocs = Copy(Getattr(n, "feature:pdocs"));
+    ParmList *plist = CopyParmList(Getattr(n, "parms"));
+    Parm *p;
+    Parm *pnext;
+    Node *lookup;
+    int lines = 0;
+    const int maxwidth = 50;
+
+    if (pdocs)
+      Append(pdocs, ".\n");
+
+
+    Swig_typemap_attach_parms("in", plist, 0);
+    Swig_typemap_attach_parms("doc", plist, 0);
+
+    for (p = plist; p; p = pnext) {
+      String *name = 0;
+      String *type = 0;
+      String *value = 0;
+      String *ptype = 0;
+      String *pdoc = Getattr(p, "tmap:doc");
+      if (pdoc) {
+	name = Getattr(p, "tmap:doc:name");
+	type = Getattr(p, "tmap:doc:type");
+	value = Getattr(p, "tmap:doc:value");
+	ptype = Getattr(p, "tmap:doc:pytype");
+      }
+
+      name = name ? name : Getattr(p, "name");
+      type = type ? type : Getattr(p, "type");
+      value = value ? value : Getattr(p, "value");
+
+
+      String *tm = Getattr(p, "tmap:in");
+      if (tm) {
+	pnext = Getattr(p, "tmap:in:next");
+      } else {
+	pnext = nextSibling(p);
+      }
+
+      // Skip ignored input attributes
+      if (checkAttribute(p, "tmap:in:numinputs", "0"))
+	continue;
+
+      // Skip the 'self' parameter which in ruby is implicit
+      if ( Cmp(name, "self") == 0 )
+	continue;
+
+      // Make __p parameters just p (as used in STL)
+      Replace( name, "__", "", DOH_REPLACE_FIRST );
+
+      if (Len(doc)) {
+	// add a comma to the previous one if any
+	Append(doc, ", ");
+
+	// Do we need to wrap a long line?
+	if ((Len(doc) - lines * maxwidth) > maxwidth) {
+	  Printf(doc, "\n%s", tab4);
+	  lines += 1;
+	}
+      }
+      // Do the param type too?
+      if (showTypes) {
+	type = SwigType_base(type);
+	lookup = Swig_symbol_clookup(type, 0);
+	if (lookup)
+	  type = Getattr(lookup, "sym:name");
+	Printf(doc, "%s ", type);
+      }
+
+      if (name) {
+	Append(doc, name);
+	if (pdoc) {
+	  if (!pdocs)
+	    pdocs = NewString("Parameters:\n");
+	  Printf(pdocs, "   %s.\n", pdoc);
+	}
+      } else {
+	Append(doc, "?");
+      }
+
+      if (value) {
+	if (Strcmp(value, "NULL") == 0)
+	  value = NewString("nil");
+	else if (Strcmp(value, "true") == 0 || Strcmp(value, "TRUE") == 0)
+	  value = NewString("true");
+	else if (Strcmp(value, "false") == 0 || Strcmp(value, "FALSE") == 0)
+	  value = NewString("false");
+	else {
+	  lookup = Swig_symbol_clookup(value, 0);
+	  if (lookup)
+	    value = Getattr(lookup, "sym:name");
+	}
+	Printf(doc, "=%s", value);
+      }
+    }
+    if (pdocs)
+      Setattr(n, "feature:pdocs", pdocs);
+    Delete(plist);
+    return doc;
+  }
+
+  /* ------------------------------------------------------------
+   * make_autodoc()
+   *    Build a docstring for the node, using parameter and other
+   *    info in the parse tree.  If the value of the autodoc
+   *    attribute is "0" then do not include parameter types, if
+   *    it is "1" (the default) then do.  If it has some other
+   *    value then assume it is supplied by the extension writer
+   *    and use it directly.
+   * ------------------------------------------------------------ */
+
+  String *make_autodoc(Node *n, autodoc_t ad_type) {
+    int extended = 0;
+    // If the function is overloaded then this funciton is called
+    // for the last one.  Rewind to the first so the docstrings are
+    // in order.
+    while (Getattr(n, "sym:previousSibling"))
+      n = Getattr(n, "sym:previousSibling");
+
+    Node *pn = Swig_methodclass(n);
+    String* super_names = NewString(""); 
+    String* class_name = Getattr(pn, "sym:name") ; 
+
+    if ( !class_name ) class_name = NewString("");
+    else
+      {
+	class_name = Copy(class_name);
+	List *baselist = Getattr(pn, "bases");
+	if (baselist && Len(baselist)) {
+	  Iterator base = First(baselist);
+	  while (base.item && GetFlag(base.item, "feature:ignore")) {
+	    base = Next(base);
+	  }
+	  
+	  int count = 0;
+	  for ( ;base.item; ++count) {
+	    if ( count ) Append(super_names, ", ");
+	    String *basename = Getattr(base.item, "sym:name");
+
+	    String* basenamestr = NewString(basename);
+	    Node* parent = parentNode(base.item);
+	    while (parent)
+	      {
+		String *parent_name = Copy( Getattr(parent, "sym:name") );
+		if ( !parent_name ) {
+		  Node* mod = Getattr(parent, "module");
+		  if ( mod )
+		    parent_name = Copy( Getattr(mod, "name") );
+		  if ( parent_name )
+		    {
+		      (Char(parent_name))[0] = (char)toupper((Char(parent_name))[0]);
+		    }
+		}
+		if ( parent_name )
+		  {
+		    Insert(basenamestr, 0, "::");
+		    Insert(basenamestr, 0, parent_name);
+		    Delete(parent_name);
+		  }
+		parent = parentNode(parent);
+	      }
+
+	    Append(super_names, basenamestr );
+	    Delete(basenamestr);
+	    base = Next(base);
+	  }
+	}
+      }
+    String* full_name;
+    if ( module ) {
+      full_name = NewString(module);
+      if (class_name && Len(class_name) > 0) Append(full_name, "::");
+    }
+    else
+      full_name = NewString("");
+    Append(full_name, class_name);
+
+    String* symname = Getattr(n, "sym:name");
+    if ( Getattr( special_methods, symname ) )
+      symname = Getattr( special_methods, symname );
+
+    String* methodName = NewString(full_name);
+    Append(methodName, symname);
+
+
+    // Each overloaded function will try to get documented,
+    // so we keep the name of the last overloaded function and its type.
+    // Documenting just from functionWrapper() is not possible as
+    // sym:name has already been changed to include the class name
+    if ( last_mode == ad_type && Cmp(methodName, last_autodoc) == 0 ) {
+      Delete(full_name);
+      Delete(class_name);
+      Delete(super_names);
+      Delete(methodName);
+      return NewString("");
+    }
+
+
+    last_mode    = ad_type;
+    last_autodoc = Copy(methodName);
+
+    String *doc = NewString("/*\n");
+    int counter = 0;
+    bool skipAuto = false;
+    Node* on = n;
+    for ( ; n; ++counter ) {
+      skipAuto = false;
+      bool showTypes = false;
+      String *autodoc = Getattr(n, "feature:autodoc");
+      autodoc_l dlevel = autodoc_level(autodoc);
+      switch (dlevel) {
+      case NO_AUTODOC:
+	break;
+      case NAMES_AUTODOC:
+	showTypes = false;
+	break;
+      case TYPES_AUTODOC:
+	showTypes = true;
+	break;
+      case EXTEND_AUTODOC:
+	extended = 1;
+	showTypes = false;
+	break;
+      case EXTEND_TYPES_AUTODOC:
+	extended = 1;
+	showTypes = true;
+	break;
+      case STRING_AUTODOC:
+	skipAuto = true;
+	break;
+      }
+
+      SwigType *type = Getattr(n, "type");
+
+      if (type) {
+	if (Strcmp(type, "void") == 0)
+	  type = NULL;
+	else {
+	  SwigType *qt = SwigType_typedef_resolve_all(type);
+	  if (SwigType_isenum(qt))
+	      type = NewString("int");
+	  else {
+	    type = SwigType_base(type);
+	    Node *lookup = Swig_symbol_clookup(type, 0);
+	      if (lookup)
+		type = Getattr(lookup, "sym:name");
+	  }
+	}
+      }
+
+      if (counter == 0) {
+	switch (ad_type) {
+	case AUTODOC_CLASS:
+	  Printf(doc, "  Document-class: %s", full_name);
+	  if ( Len(super_names) > 0 )
+	    Printf( doc, " < %s", super_names);
+	  Append(doc, "\n\n");
+	  break;
+	case AUTODOC_CTOR:
+ 	  Printf(doc, "  Document-method: %s.new\n\n", full_name);
+	  break;
+
+	case AUTODOC_DTOR:
+	  break;
+
+	case AUTODOC_STATICFUNC:
+ 	  Printf(doc, "  Document-method: %s.%s\n\n", full_name, symname);
+	  break;
+
+	case AUTODOC_FUNC:
+	case AUTODOC_METHOD:
+	case AUTODOC_GETTER:
+ 	  Printf(doc, "  Document-method: %s.%s\n\n", full_name, symname);
+	  break;
+	case AUTODOC_SETTER:
+ 	  Printf(doc, "  Document-method: %s.%s=\n\n", full_name, symname);
+	  break;
+	}
+      }
+
+
+      if (skipAuto) {
+	if ( counter == 0 ) Printf(doc, "  call-seq:\n");
+	switch( ad_type )
+	  {
+	  case AUTODOC_STATICFUNC:
+	  case AUTODOC_FUNC:
+	  case AUTODOC_METHOD:
+	  case AUTODOC_GETTER:
+	    {
+	      String *paramList = make_autodocParmList(n, showTypes);
+	      if (Len(paramList))
+		Printf(doc, "    %s(%s)", symname, paramList);
+	      else
+		Printf(doc, "    %s", symname);
+	      if (type)
+		Printf(doc, " -> %s", type);
+	      break;
+	    }
+	  case AUTODOC_SETTER:
+	    {
+	      Printf(doc, "    %s=(x)", symname);
+	      if (type) Printf(doc, " -> %s", type);
+	      break;
+	    }
+	  default:
+	    break;
+	  }
+      }
+      else {
+	switch (ad_type) {
+	case AUTODOC_CLASS:
+	  {
+	    // Only do the autodoc if there isn't a docstring for the class
+	    String *str = Getattr(n, "feature:docstring");
+	    if (counter == 0 && (str == NULL || Len(str) == 0)) {
+	      if (CPlusPlus) {
+		Printf(doc, "  Proxy of C++ %s class", full_name);
+	      } else {
+		Printf(doc, "  Proxy of C %s struct", full_name);
+	      }
+	    }
+	  }
+	  break;
+	case AUTODOC_CTOR:
+	  if (counter == 0) Printf(doc, "  call-seq:\n");
+	  if (Strcmp(class_name, symname) == 0) {
+	    String *paramList = make_autodocParmList(n, showTypes);
+	    if (Len(paramList))
+	      Printf(doc, "    %s.new(%s)", class_name, paramList);
+	    else
+	      Printf(doc, "    %s.new", class_name);
+	  } else
+	    Printf(doc, "    %s.new(%s)", class_name, 
+		   make_autodocParmList(n, showTypes));
+	  break;
+
+	case AUTODOC_DTOR:
+	  break;
+
+	case AUTODOC_STATICFUNC:
+	case AUTODOC_FUNC:
+	case AUTODOC_METHOD:
+	case AUTODOC_GETTER:
+	  {
+	    if (counter == 0) Printf(doc, "  call-seq:\n");
+	    String *paramList = make_autodocParmList(n, showTypes);
+	    if (Len(paramList))
+	      Printf(doc, "    %s(%s)", symname, paramList);
+	    else
+	      Printf(doc, "    %s", symname);
+	    if (type)
+	      Printf(doc, " -> %s", type);
+	    break;
+	  }
+	case AUTODOC_SETTER:
+	  {
+	    Printf(doc, "  call-seq:\n");
+	    Printf(doc, "    %s=(x)", symname);
+	    if (type) Printf(doc, " -> %s", type);
+	    break;
+	  }
+	}
+      }
+
+      // if it's overloaded then get the next decl and loop around again
+      n = Getattr(n, "sym:nextSibling");
+      if (n)
+	Append(doc, "\n");
+    }
+
+    Printf(doc, "\n\n");
+    if (!skipAuto) {
+      switch (ad_type) {
+      case AUTODOC_CLASS:
+      case AUTODOC_DTOR:
+	break;
+      case AUTODOC_CTOR:
+	Printf(doc, "Class constructor.\n");
+	break;
+      case AUTODOC_STATICFUNC:
+	Printf(doc, "A class method.\n");
+	break;
+      case AUTODOC_FUNC:
+	Printf(doc, "A module function.\n");
+	break;
+      case AUTODOC_METHOD:
+	Printf(doc, "An instance method.\n");
+	break;
+      case AUTODOC_GETTER:
+	Printf(doc, "Get value of attribute.\n");
+	break;
+      case AUTODOC_SETTER:
+	Printf(doc, "Set new value for attribute.\n");
+	break;
+      }
+    }
+
+
+    n = on;
+    while ( n ) {
+      String *autodoc = Getattr(n, "feature:autodoc");
+      autodoc_l dlevel = autodoc_level(autodoc);
+
+      symname = Getattr(n, "sym:name");
+      if ( Getattr( special_methods, symname ) )
+	symname = Getattr( special_methods, symname );
+
+      switch (dlevel) {
+      case NO_AUTODOC:
+      case NAMES_AUTODOC:
+      case TYPES_AUTODOC:
+	extended = 0;
+	break;
+      case STRING_AUTODOC:
+	extended = 2;
+	Replaceall( autodoc, "$class", class_name );
+	Printv(doc, autodoc, ".", NIL);
+	break;
+      case EXTEND_AUTODOC:
+      case EXTEND_TYPES_AUTODOC:
+	extended = 1;
+	break;
+      }
+
+
+      if (extended) {
+	String *pdocs = Getattr(n, "feature:pdocs");
+	if (pdocs) {
+	  Printv(doc, "\n\n", pdocs, NULL);
+	  break;
+	}
+	if ( extended == 2 ) break;
+      }
+      n = Getattr(n, "sym:nextSibling");
+    }
+
+    Append(doc, "\n*/\n");
+    Delete(full_name);
+    Delete(class_name);
+    Delete(super_names);
+    Delete(methodName);
+
+    return doc;
+  }
+
+public:
+
+  /* ---------------------------------------------------------------------
+   * RUBY()
+   *
+   * Initialize member data
+   * --------------------------------------------------------------------- */
+
+   RUBY() {
+    module = 0;
+    modvar = 0;
+    feature = 0;
+    prefix = 0;
+    last_autodoc = NewString("");
+    current = NO_CPP;
+    classes = 0;
+    klass = 0;
+    special_methods = 0;
+    f_runtime = 0;
+    f_header = 0;
+    f_wrappers = 0;
+    f_init = 0;
+    f_initbeforefunc = 0;
+    useGlobalModule = false;
+    multipleInheritance = false;
+    director_prot_ctor_code = NewString("");
+    Printv(director_prot_ctor_code,
+	   "if ( $comparison ) { /* subclassed */\n",
+	   "  $director_new \n",
+	   "} else {\n", "  rb_raise(rb_eRuntimeError,\"accessing abstract class or protected constructor\"); \n", "  return Qnil;\n", "}\n", NIL);
+    director_multiple_inheritance = 0;
+    director_language = 1;
+  }
+
+  /* ---------------------------------------------------------------------
+   * main()
+   *
+   * Parse command line options and initializes variables.
+   * --------------------------------------------------------------------- */
+  
+  virtual void main(int argc, char *argv[]) {
+
+    int cppcast = 1;
+    int autorename = 0;
+
+    /* Set location of SWIG library */
+    SWIG_library_directory("ruby");
+
+    /* Look for certain command line options */
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-initname") == 0) {
+	  if (argv[i + 1]) {
+	    char *name = argv[i + 1];
+	    feature = NewString(name);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	}
+	else if (strcmp(argv[i], "-feature") == 0) {
+	  fprintf( stderr, "Warning: Ruby -feature option is deprecated, "
+		   "please use -initname instead.\n");
+	  if (argv[i + 1]) {
+	    char *name = argv[i + 1];
+	    feature = NewString(name);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-globalmodule") == 0) {
+	  useGlobalModule = true;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-minherit") == 0) {
+	  multipleInheritance = true;
+	  director_multiple_inheritance = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-cppcast") == 0) {
+	  cppcast = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nocppcast") == 0) {
+	  cppcast = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-autorename") == 0) {
+	  autorename = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-noautorename") == 0) {
+	  autorename = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-prefix") == 0) {
+	  if (argv[i + 1]) {
+	    char *name = argv[i + 1];
+	    prefix = NewString(name);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else {
+	    Swig_arg_error();
+	  }
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  Printf(stdout, "%s\n", usage);
+	}
+      }
+    }
+
+    if (cppcast) {
+      /* Turn on cppcast mode */
+      Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
+    }
+
+    if (autorename) {
+      /* Turn on the autorename mode */
+      Preprocessor_define((DOH *) "SWIG_RUBY_AUTORENAME", 0);
+    }
+
+    /* Add a symbol to the parser for conditional compilation */
+    Preprocessor_define("SWIGRUBY 1", 0);
+
+    /* Add typemap definitions */
+    SWIG_typemap_lang("ruby");
+    SWIG_config_file("ruby.swg");
+    allow_overloading();
+  }
+
+  /**
+   * Generate initialization code to define the Ruby module(s),
+   * accounting for nested modules as necessary.
+   */
+  void defineRubyModule() {
+    List *modules = Split(module, ':', INT_MAX);
+    if (modules != 0 && Len(modules) > 0) {
+      String *mv = 0;
+      Iterator m;
+      m = First(modules);
+      while (m.item) {
+	if (Len(m.item) > 0) {
+	  if (mv != 0) {
+	    Printv(f_init, tab4, modvar, " = rb_define_module_under(", modvar, ", \"", m.item, "\");\n", NIL);
+	  } else {
+	    Printv(f_init, tab4, modvar, " = rb_define_module(\"", m.item, "\");\n", NIL);
+	    mv = NewString(modvar);
+	  }
+	}
+	m = Next(m);
+      }
+      Delete(mv);
+      Delete(modules);
+    }
+  }
+
+  void registerMagicMethods() {
+
+    special_methods = NewHash();
+
+    /* Python->Ruby style special method name. */
+    /* Basic */
+    Setattr(special_methods, "__repr__", "inspect");
+    Setattr(special_methods, "__str__", "to_s");
+    Setattr(special_methods, "__cmp__", "<=>");
+    Setattr(special_methods, "__hash__", "hash");
+    Setattr(special_methods, "__nonzero__", "nonzero?");
+
+    /* Callable */
+    Setattr(special_methods, "__call__", "call");
+
+    /* Collection */
+    Setattr(special_methods, "__len__", "length");
+    Setattr(special_methods, "__getitem__", "[]");
+    Setattr(special_methods, "__setitem__", "[]=");
+
+    /* Operators */
+    Setattr(special_methods, "__add__", "+");
+    Setattr(special_methods, "__pos__", "+@");
+    Setattr(special_methods, "__sub__", "-");
+    Setattr(special_methods, "__neg__", "-@");
+    Setattr(special_methods, "__mul__", "*");
+    Setattr(special_methods, "__div__", "/");
+    Setattr(special_methods, "__mod__", "%");
+    Setattr(special_methods, "__lshift__", "<<");
+    Setattr(special_methods, "__rshift__", ">>");
+    Setattr(special_methods, "__and__", "&");
+    Setattr(special_methods, "__or__", "|");
+    Setattr(special_methods, "__xor__", "^");
+    Setattr(special_methods, "__invert__", "~");
+    Setattr(special_methods, "__lt__", "<");
+    Setattr(special_methods, "__le__", "<=");
+    Setattr(special_methods, "__gt__", ">");
+    Setattr(special_methods, "__ge__", ">=");
+    Setattr(special_methods, "__eq__", "==");
+
+    /* Other numeric */
+    Setattr(special_methods, "__divmod__", "divmod");
+    Setattr(special_methods, "__pow__", "**");
+    Setattr(special_methods, "__abs__", "abs");
+    Setattr(special_methods, "__int__", "to_i");
+    Setattr(special_methods, "__float__", "to_f");
+    Setattr(special_methods, "__coerce__", "coerce");
+  }
+
+  /* ---------------------------------------------------------------------
+   * top()
+   * --------------------------------------------------------------------- */
+
+  virtual int top(Node *n) {
+
+    /**
+     * See if any Ruby module options have been specified as options
+     * to the %module directive.
+     */
+    Node *swigModule = Getattr(n, "module");
+    if (swigModule) {
+      Node *options = Getattr(swigModule, "options");
+      if (options) {
+	if (Getattr(options, "directors")) {
+	  allow_directors();
+	}
+	if (Getattr(options, "dirprot")) {
+	  allow_dirprot();
+	}
+	if (Getattr(options, "ruby_globalmodule")) {
+	  useGlobalModule = true;
+	}
+	if (Getattr(options, "ruby_minherit")) {
+	  multipleInheritance = true;
+	  director_multiple_inheritance = 1;
+	}
+      }
+    }
+
+    /* Set comparison with none for ConstructorToFunction */
+
+
+    setSubclassInstanceCheck(NewStringf("strcmp(rb_obj_classname(self), classname) != 0"));
+    // setSubclassInstanceCheck(NewString("CLASS_OF(self) != cFoo.klass"));
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+    String *outfile_h = Getattr(n, "outfile_h");
+
+    if (!outfile) {
+      Printf(stderr, "Unable to determine outfile\n");
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+    if (directorsEnabled()) {
+      if (!outfile_h) {
+        Printf(stderr, "Unable to determine outfile_h\n");
+        SWIG_exit(EXIT_FAILURE);
+      }
+      f_runtime_h = NewFile(outfile_h, "w");
+      if (!f_runtime_h) {
+	FileErrorDisplay(outfile_h);
+	SWIG_exit(EXIT_FAILURE);
+      }
+    }
+
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+    f_directors_h = NewString("");
+    f_directors = NewString("");
+    f_directors_helpers = NewString("");
+    f_initbeforefunc = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+    Swig_register_filebyname("director", f_directors);
+    Swig_register_filebyname("director_h", f_directors_h);
+    Swig_register_filebyname("director_helpers", f_directors_helpers);
+    Swig_register_filebyname("initbeforefunc", f_initbeforefunc);
+
+    modvar = 0;
+    current = NO_CPP;
+    klass = 0;
+    classes = NewHash();
+
+    registerMagicMethods();
+
+    Swig_banner(f_runtime);
+
+    Printf(f_runtime, "#define SWIGRUBY\n");
+
+    if (directorsEnabled()) {
+      Printf(f_runtime, "#define SWIG_DIRECTORS\n");
+    }
+
+    /* typedef void *VALUE */
+    SwigType *value = NewSwigType(T_VOID);
+    SwigType_add_pointer(value);
+    SwigType_typedef(value, (char *) "VALUE");
+    Delete(value);
+
+    /* Set module name */
+    set_module(Char(Getattr(n, "name")));
+
+    if (directorsEnabled()) {
+      /* Build a version of the module name for use in a C macro name. */
+      String *module_macro = Copy(module);
+      Replaceall(module_macro, "::", "__");
+
+      Swig_banner(f_directors_h);
+      Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module_macro);
+      Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module_macro);
+      Printf(f_directors_h, "namespace Swig {\n");
+      Printf(f_directors_h, "  class Director;\n");
+      Printf(f_directors_h, "}\n\n");
+
+      Printf(f_directors_helpers, "/* ---------------------------------------------------\n");
+      Printf(f_directors_helpers, " * C++ director class helpers\n");
+      Printf(f_directors_helpers, " * --------------------------------------------------- */\n\n");
+
+      Printf(f_directors, "\n\n");
+      Printf(f_directors, "/* ---------------------------------------------------\n");
+      Printf(f_directors, " * C++ director class methods\n");
+      Printf(f_directors, " * --------------------------------------------------- */\n\n");
+      if (outfile_h)
+	Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h));
+
+      Delete(module_macro);
+    }
+
+    Printf(f_header, "#define SWIG_init    Init_%s\n", feature);
+    Printf(f_header, "#define SWIG_name    \"%s\"\n\n", module);
+    Printf(f_header, "static VALUE %s;\n", modvar);
+
+    /* Start generating the initialization function */
+    String* docs = docstring(n, AUTODOC_CLASS);
+    Printf(f_init, "/*\n%s\n*/", docs );
+    Printv(f_init, "\n", "#ifdef __cplusplus\n", "extern \"C\"\n", "#endif\n", "SWIGEXPORT void Init_", feature, "(void) {\n", "size_t i;\n", "\n", NIL);
+
+    Printv(f_init, tab4, "SWIG_InitRuntime();\n", NIL);
+
+    if (!useGlobalModule)
+      defineRubyModule();
+
+    Printv(f_init, "\n", "SWIG_InitializeModule(0);\n", "for (i = 0; i < swig_module.size; i++) {\n", "SWIG_define_class(swig_module.types[i]);\n", "}\n", NIL);
+    Printf(f_init, "\n");
+
+    /* Initialize code to keep track of objects */
+    Printf(f_init, "SWIG_RubyInitializeTrackings();\n");
+
+    Language::top(n);
+
+    if (directorsEnabled()) {
+      // Insert director runtime into the f_runtime file (make it occur before %header section)
+      Swig_insert_file("director.swg", f_runtime);
+    }
+
+    /* Finish off our init function */
+    Printf(f_init, "}\n");
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+
+    /* Close all of the files */
+    Dump(f_header, f_runtime);
+
+    if (directorsEnabled()) {
+      Dump(f_directors_helpers, f_runtime);
+      Dump(f_directors, f_runtime);
+      Dump(f_directors_h, f_runtime_h);
+      Printf(f_runtime_h, "\n");
+      Printf(f_runtime_h, "#endif\n");
+      Close(f_runtime_h);
+    }
+
+    Dump(f_wrappers, f_runtime);
+    Dump(f_initbeforefunc, f_runtime);
+    Wrapper_pretty_print(f_init, f_runtime);
+
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Delete(f_initbeforefunc);
+    Close(f_runtime);
+    Delete(f_runtime);
+
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * importDirective()
+   * ----------------------------------------------------------------------------- */
+
+  virtual int importDirective(Node *n) {
+    String *modname = Getattr(n, "module");
+    if (modname) {
+      if (prefix) {
+	Insert(modname, 0, prefix);
+      }
+
+      List *modules = Split(modname, ':', INT_MAX);
+      if (modules && Len(modules) > 0) {
+	modname = NewString("");
+	String *last = NULL;
+	Iterator m = First(modules);
+	while (m.item) {
+	  if (Len(m.item) > 0) {
+	    if (last) {
+	      Append(modname, "/");
+	    }
+	    Append(modname, m.item);
+	    last = m.item;
+	  }
+	  m = Next(m);
+	}
+	Printf(f_init, "rb_require(\"%s\");\n", modname);
+	Delete(modname);
+      }
+      Delete(modules);
+    }
+    return Language::importDirective(n);
+  }
+
+  /* ---------------------------------------------------------------------
+   * set_module(const char *mod_name)
+   *
+   * Sets the module name.  Does nothing if it's already set (so it can
+   * be overridden as a command line option).
+   *---------------------------------------------------------------------- */
+
+  void set_module(const char *s) {
+    String *mod_name = NewString(s);
+    if (module == 0) {
+      /* Start with the empty string */
+      module = NewString("");
+
+      if (prefix) {
+	Insert(mod_name, 0, prefix);
+      }
+
+      /* Account for nested modules */
+      List *modules = Split(mod_name, ':', INT_MAX);
+      if (modules != 0 && Len(modules) > 0) {
+	String *last = 0;
+	Iterator m = First(modules);
+	while (m.item) {
+	  if (Len(m.item) > 0) {
+	    String *cap = NewString(m.item);
+	    (Char(cap))[0] = (char)toupper((Char(cap))[0]);
+	    if (last != 0) {
+	      Append(module, "::");
+	    }
+	    Append(module, cap);
+	    last = m.item;
+	  }
+	  m = Next(m);
+	}
+	if (feature == 0) {
+	  feature = Copy(last);
+	}
+	(Char(last))[0] = (char)toupper((Char(last))[0]);
+	modvar = NewStringf("m%s", last);
+	Delete(modules);
+      }
+    }
+    Delete(mod_name);
+  }
+
+  /* --------------------------------------------------------------------------
+   * nativeWrapper()
+   * -------------------------------------------------------------------------- */
+  virtual int nativeWrapper(Node *n) {
+    String *funcname = Getattr(n, "wrap:name");
+    Swig_warning(WARN_LANG_NATIVE_UNIMPL, input_file, line_number, "Adding native function %s not supported (ignored).\n", funcname);
+    return SWIG_NOWRAP;
+  }
+
+  /**
+   * Process the comma-separated list of aliases (if any).
+   */
+  void defineAliases(Node *n, const String_or_char *iname) {
+    String *aliasv = Getattr(n, "feature:alias");
+    if (aliasv) {
+      List *aliases = Split(aliasv, ',', INT_MAX);
+      if (aliases && Len(aliases) > 0) {
+	Iterator alias = First(aliases);
+	while (alias.item) {
+	  if (Len(alias.item) > 0) {
+	    Printv(klass->init, tab4, "rb_define_alias(", klass->vname, ", \"", alias.item, "\", \"", iname, "\");\n", NIL);
+	  }
+	  alias = Next(alias);
+	}
+      }
+      Delete(aliases);
+    }
+  }
+
+  /* ---------------------------------------------------------------------
+   * create_command(Node *n, char *iname)
+   *
+   * Creates a new command from a C function.
+   *              iname = Name of function in scripting language
+   *
+   * A note about what "protected" and "private" mean in Ruby:
+   *
+   * A private method is accessible only within the class or its subclasses,
+   * and it is callable only in "function form", with 'self' (implicit or
+   * explicit) as a receiver.
+   *
+   * A protected method is callable only from within its class, but unlike
+   * a private method, it can be called with a receiver other than self, such
+   * as another instance of the same class.
+   * --------------------------------------------------------------------- */
+
+  void create_command(Node *n, const String_or_char *iname) {
+
+    String *alloc_func = Swig_name_wrapper(iname);
+    String *wname = Swig_name_wrapper(iname);
+    if (CPlusPlus) {
+      Insert(wname, 0, "VALUEFUNC(");
+      Append(wname, ")");
+    }
+    if (current != NO_CPP)
+      iname = klass->strip(iname);
+    if (Getattr(special_methods, iname)) {
+      iname = GetChar(special_methods, iname);
+    }
+
+    String *s = NewString("");
+    String *temp = NewString("");
+
+#ifdef SWIG_PROTECTED_TARGET_METHODS
+    const char *rb_define_method = is_public(n) ? "rb_define_method" : "rb_define_protected_method";
+#else
+    const char *rb_define_method = "rb_define_method";
+#endif
+    switch (current) {
+    case MEMBER_FUNC:
+      {
+	if (multipleInheritance) {
+	  Printv(klass->init, tab4, rb_define_method, "(", klass->mImpl, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
+	} else {
+	  Printv(klass->init, tab4, rb_define_method, "(", klass->vname, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
+	}
+      }
+      break;
+    case CONSTRUCTOR_ALLOCATE:
+      Printv(s, tab4, "rb_define_alloc_func(", klass->vname, ", ", alloc_func, ");\n", NIL);
+      Replaceall(klass->init, "$allocator", s);
+      break;
+    case CONSTRUCTOR_INITIALIZE:
+      Printv(s, tab4, rb_define_method, "(", klass->vname, ", \"initialize\", ", wname, ", -1);\n", NIL);
+      Replaceall(klass->init, "$initializer", s);
+      break;
+    case MEMBER_VAR:
+      Append(temp, iname);
+      /* Check for _set or _get at the end of the name. */
+      if (Len(temp) > 4) {
+	const char *p = Char(temp) + (Len(temp) - 4);
+	if (strcmp(p, "_set") == 0) {
+	  Delslice(temp, Len(temp) - 4, DOH_END);
+	  Append(temp, "=");
+	} else if (strcmp(p, "_get") == 0) {
+	  Delslice(temp, Len(temp) - 4, DOH_END);
+	}
+      }
+      if (multipleInheritance) {
+	Printv(klass->init, tab4, "rb_define_method(", klass->mImpl, ", \"", temp, "\", ", wname, ", -1);\n", NIL);
+      } else {
+	Printv(klass->init, tab4, "rb_define_method(", klass->vname, ", \"", temp, "\", ", wname, ", -1);\n", NIL);
+      }
+      break;
+    case STATIC_FUNC:
+      Printv(klass->init, tab4, "rb_define_singleton_method(", klass->vname, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
+      break;
+    case NO_CPP:
+      if (!useGlobalModule) {
+	Printv(s, tab4, "rb_define_module_function(", modvar, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
+	Printv(f_init, s, NIL);
+      } else {
+	Printv(s, tab4, "rb_define_global_function(\"", iname, "\", ", wname, ", -1);\n", NIL);
+	Printv(f_init, s, NIL);
+      }
+      break;
+    case DESTRUCTOR:
+    case CLASS_CONST:
+    case STATIC_VAR:
+      assert(false);		// Should not have gotten here for these types
+    default:
+      assert(false);
+    }
+
+    defineAliases(n, iname);
+
+    Delete(temp);
+    Delete(s);
+    Delete(wname);
+    Delete(alloc_func);
+  }
+
+  /* ---------------------------------------------------------------------
+   * applyInputTypemap()
+   *
+   * Look up the appropriate "in" typemap for this parameter (p),
+   * substitute the correct strings for the $target and $input typemap
+   * parameters, and dump the resulting code to the wrapper file.
+   * --------------------------------------------------------------------- */
+
+  Parm *applyInputTypemap(Parm *p, String *ln, String *source, Wrapper *f, String *symname) {
+    String *tm;
+    SwigType *pt = Getattr(p, "type");
+    if ((tm = Getattr(p, "tmap:in"))) {
+      Replaceall(tm, "$target", ln);
+      Replaceall(tm, "$source", source);
+      Replaceall(tm, "$input", source);
+      Replaceall(tm, "$symname", symname);
+
+      if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+	Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+      } else {
+	Replaceall(tm, "$disown", "0");
+      }
+
+      Setattr(p, "emit:input", Copy(source));
+      Printf(f->code, "%s\n", tm);
+      p = Getattr(p, "tmap:in:next");
+    } else {
+      Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+      p = nextSibling(p);
+    }
+    return p;
+  }
+
+  Parm *skipIgnoredArgs(Parm *p) {
+    while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+      p = Getattr(p, "tmap:in:next");
+    }
+    return p;
+  }
+
+  /* ---------------------------------------------------------------------
+   * marshalInputArgs()
+   *
+   * Process all of the arguments passed into the scripting language
+   * method and convert them into C/C++ function arguments using the
+   * supplied typemaps.
+   * --------------------------------------------------------------------- */
+
+  void marshalInputArgs(Node *n, ParmList *l, int numarg, int numreq, String *kwargs, bool allow_kwargs, Wrapper *f) {
+    int i;
+    Parm *p;
+    String *tm;
+    String *source;
+    String *target;
+
+    source = NewString("");
+    target = NewString("");
+
+    bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n));
+
+    /**
+     * The 'start' value indicates which of the C/C++ function arguments
+     * produced here corresponds to the first value in Ruby's argv[] array.
+     * The value of start is either zero or one. If start is zero, then
+     * the first argument (with name arg1) is based on the value of argv[0].
+     * If start is one, then arg1 is based on the value of argv[1].
+     */
+    int start = (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) ? 1 : 0;
+
+    int varargs = emit_isvarargs(l);
+
+    Printf(kwargs, "{ ");
+    for (i = 0, p = l; i < numarg; i++) {
+
+      p = skipIgnoredArgs(p);
+
+      String *pn = Getattr(p, "name");
+      String *ln = Getattr(p, "lname");
+
+      /* Produce string representation of source argument */
+      Clear(source);
+
+      /* First argument is a special case */
+      if (i == 0) {
+	Printv(source, (start == 0) ? "argv[0]" : "self", NIL);
+      } else {
+	Printf(source, "argv[%d]", i - start);
+      }
+
+      /* Produce string representation of target argument */
+      Clear(target);
+      Printf(target, "%s", Char(ln));
+
+      if (i >= (numreq)) {	/* Check if parsing an optional argument */
+	Printf(f->code, "    if (argc > %d) {\n", i - start);
+      }
+
+      /* Record argument name for keyword argument handling */
+      if (Len(pn)) {
+	Printf(kwargs, "\"%s\",", pn);
+      } else {
+	Printf(kwargs, "\"arg%d\",", i + 1);
+      }
+
+      /* Look for an input typemap */
+      p = applyInputTypemap(p, ln, source, f, Getattr(n, "name"));
+      if (i >= numreq) {
+	Printf(f->code, "}\n");
+      }
+    }
+
+    /* Finish argument marshalling */
+    Printf(kwargs, " NULL }");
+    if (allow_kwargs) {
+      Printv(f->locals, tab4, "char *kwnames[] = ", kwargs, ";\n", NIL);
+    }
+
+    /* Trailing varargs */
+    if (varargs) {
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+	Clear(source);
+	Printf(source, "argv[%d]", i - start);
+	Replaceall(tm, "$input", source);
+	Setattr(p, "emit:input", Copy(source));
+	Printf(f->code, "if (argc > %d) {\n", i - start);
+	Printv(f->code, tm, "\n", NIL);
+	Printf(f->code, "}\n");
+      }
+    }
+
+    Delete(source);
+    Delete(target);
+  }
+
+  /* ---------------------------------------------------------------------
+   * insertConstraintCheckingCode(ParmList *l, Wrapper *f)
+   *
+   * Checks each of the parameters in the parameter list for a "check"
+   * typemap and (if it finds one) inserts the typemapping code into
+   * the function wrapper.
+   * --------------------------------------------------------------------- */
+
+  void insertConstraintCheckingCode(ParmList *l, Wrapper *f) {
+    Parm *p;
+    String *tm;
+    for (p = l; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+  }
+
+  /* ---------------------------------------------------------------------
+   * insertCleanupCode(ParmList *l, String *cleanup)
+   *
+   * Checks each of the parameters in the parameter list for a "freearg"
+   * typemap and (if it finds one) inserts the typemapping code into
+   * the function wrapper.
+   * --------------------------------------------------------------------- */
+
+  void insertCleanupCode(ParmList *l, String *cleanup) {
+    String *tm;
+    for (Parm *p = l; p;) {
+      if ((tm = Getattr(p, "tmap:freearg"))) {
+	if (Len(tm) != 0) {
+	  Replaceall(tm, "$source", Getattr(p, "lname"));
+	  Printv(cleanup, tm, "\n", NIL);
+	}
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+  }
+
+  /* ---------------------------------------------------------------------
+   * insertArgOutputCode(ParmList *l, String *outarg, int& need_result)
+   *
+   * Checks each of the parameters in the parameter list for a "argout"
+   * typemap and (if it finds one) inserts the typemapping code into
+   * the function wrapper.
+   * --------------------------------------------------------------------- */
+
+  void insertArgOutputCode(ParmList *l, String *outarg, int &need_result) {
+    String *tm;
+    for (Parm *p = l; p;) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+	Replaceall(tm, "$target", "vresult");
+	Replaceall(tm, "$result", "vresult");
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+
+	Printv(outarg, tm, "\n", NIL);
+	need_result += 1;
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+  }
+
+  /* ---------------------------------------------------------------------
+   * validIdentifier()
+   *
+   * Is this a valid identifier in the scripting language?
+   * Ruby method names can include any combination of letters, numbers
+   * and underscores. A Ruby method name may optionally end with
+   * a question mark ("?"), exclamation point ("!") or equals sign ("=").
+   *
+   * Methods whose names end with question marks are, by convention,
+   * predicate methods that return true or false (e.g. Array#empty?).
+   *
+   * Methods whose names end with exclamation points are, by convention,
+   * called bang methods that modify the instance in place (e.g. Array#sort!).
+   *
+   * Methods whose names end with an equals sign are attribute setters
+   * (e.g. Thread#critical=).
+   * --------------------------------------------------------------------- */
+
+  virtual int validIdentifier(String *s) {
+    char *c = Char(s);
+    while (*c) {
+      if (!(isalnum(*c) || (*c == '_') || (*c == '?') || (*c == '!') || (*c == '=')))
+	return 0;
+      c++;
+    }
+    return 1;
+  }
+
+  /* ---------------------------------------------------------------------
+   * functionWrapper()
+   *
+   * Create a function declaration and register it with the interpreter.
+   * --------------------------------------------------------------------- */
+
+  virtual int functionWrapper(Node *n) {
+
+    String *nodeType;
+    bool constructor;
+    bool destructor;
+    String *storage;
+
+    String *symname = Copy(Getattr(n, "sym:name"));
+    SwigType *t = Getattr(n, "type");
+    ParmList *l = Getattr(n, "parms");
+    int director_method = 0;
+    String *tm;
+
+    int need_result = 0;
+
+    /* Ruby needs no destructor wrapper */
+    if (current == DESTRUCTOR)
+      return SWIG_NOWRAP;
+
+    nodeType = Getattr(n, "nodeType");
+    constructor = (!Cmp(nodeType, "constructor"));
+    destructor = (!Cmp(nodeType, "destructor"));
+    storage = Getattr(n, "storage");
+
+    /* If the C++ class constructor is overloaded, we only want to
+     * write out the "new" singleton method once since it is always
+     * the same. (It's the "initialize" method that will handle the
+     * overloading). */
+
+    if (current == CONSTRUCTOR_ALLOCATE && Swig_symbol_isoverloaded(n) && Getattr(n, "sym:nextSibling") != 0)
+      return SWIG_OK;
+
+    String *overname = 0;
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(symname, n))
+	return SWIG_ERROR;
+    }
+
+    String *cleanup = NewString("");
+    String *outarg = NewString("");
+    String *kwargs = NewString("");
+    Wrapper *f = NewWrapper();
+
+    /* Rename predicate methods */
+    if (GetFlag(n, "feature:predicate")) {
+      Append(symname, "?");
+    }
+
+    /* Rename bang methods */
+    if (GetFlag(n, "feature:bang")) {
+      Append(symname, "!");
+    }
+
+    /* Determine the name of the SWIG wrapper function */
+    String *wname = Swig_name_wrapper(symname);
+    if (overname && current != CONSTRUCTOR_ALLOCATE) {
+      Append(wname, overname);
+    }
+
+    /* Emit arguments */
+    if (current != CONSTRUCTOR_ALLOCATE) {
+      emit_parameter_variables(l, f);
+    }
+
+    /* Attach standard typemaps */
+    if (current != CONSTRUCTOR_ALLOCATE) {
+      emit_attach_parmmaps(l, f);
+    }
+    Setattr(n, "wrap:parms", l);
+
+    /* Get number of arguments */
+    int numarg = emit_num_arguments(l);
+    int numreq = emit_num_required(l);
+    int varargs = emit_isvarargs(l);
+    bool allow_kwargs = GetFlag(n, "feature:kwargs") ? true : false;
+
+    bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n));
+    int start = (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) ? 1 : 0;
+
+    /* Now write the wrapper function itself */
+    if (current == CONSTRUCTOR_ALLOCATE) {
+      Printf(f->def, "#ifdef HAVE_RB_DEFINE_ALLOC_FUNC\n");
+      Printv(f->def, "SWIGINTERN VALUE\n", wname, "(VALUE self) {", NIL);
+      Printf(f->def, "#else\n");
+      Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL);
+      Printf(f->def, "#endif\n");
+    } else if (current == CONSTRUCTOR_INITIALIZE) {
+      Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL);
+      if (!varargs) {
+	Printf(f->code, "if ((argc < %d) || (argc > %d)) ", numreq - start, numarg - start);
+      } else {
+	Printf(f->code, "if (argc < %d) ", numreq - start);
+      }
+      Printf(f->code, "{rb_raise(rb_eArgError, \"wrong # of arguments(%%d for %d)\",argc); SWIG_fail;}\n", numreq - start);
+    } else {
+
+      if ( current == NO_CPP )
+	{
+	  String* docs = docstring(n, AUTODOC_FUNC);
+	  Printf(f_wrappers, "%s", docs);
+	  Delete(docs);
+	}
+
+      Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL);
+      if (!varargs) {
+	Printf(f->code, "if ((argc < %d) || (argc > %d)) ", numreq - start, numarg - start);
+      } else {
+	Printf(f->code, "if (argc < %d) ", numreq - start);
+      }
+      Printf(f->code, "{rb_raise(rb_eArgError, \"wrong # of arguments(%%d for %d)\",argc); SWIG_fail;}\n", numreq - start);
+    }
+
+    /* Now walk the function parameter list and generate code */
+    /* to get arguments */
+    if (current != CONSTRUCTOR_ALLOCATE) {
+      marshalInputArgs(n, l, numarg, numreq, kwargs, allow_kwargs, f);
+    }
+    // FIXME?
+    if (ctor_director) {
+      numarg--;
+      numreq--;
+    }
+
+    /* Insert constraint checking code */
+    insertConstraintCheckingCode(l, f);
+
+    /* Insert cleanup code */
+    insertCleanupCode(l, cleanup);
+
+    /* Insert argument output code */
+    insertArgOutputCode(l, outarg, need_result);
+
+    /* if the object is a director, and the method call originated from its
+     * underlying Ruby object, resolve the call by going up the c++ 
+     * inheritance chain.  otherwise try to resolve the method in python.  
+     * without this check an infinite loop is set up between the director and 
+     * shadow class method calls.
+     */
+
+    // NOTE: this code should only be inserted if this class is the
+    // base class of a director class.  however, in general we haven't
+    // yet analyzed all classes derived from this one to see if they are
+    // directors.  furthermore, this class may be used as the base of
+    // a director class defined in a completely different module at a
+    // later time, so this test must be included whether or not directorbase
+    // is true.  we do skip this code if directors have not been enabled
+    // at the command line to preserve source-level compatibility with
+    // non-polymorphic swig.  also, if this wrapper is for a smart-pointer
+    // method, there is no need to perform the test since the calling object
+    // (the smart-pointer) and the director object (the "pointee") are
+    // distinct.
+
+    director_method = is_member_director(n) && !is_smart_pointer() && !destructor;
+    if (director_method) {
+      Wrapper_add_local(f, "director", "Swig::Director *director = 0");
+      Printf(f->code, "director = dynamic_cast<Swig::Director *>(arg1);\n");
+      Wrapper_add_local(f, "upcall", "bool upcall = false");
+      Append(f->code, "upcall = (director && (director->swig_get_self() == self));\n");
+    }
+
+    /* Now write code to make the function call */
+    if (current != CONSTRUCTOR_ALLOCATE) {
+      if (current == CONSTRUCTOR_INITIALIZE) {
+	Node *pn = Swig_methodclass(n);
+	String *symname = Getattr(pn, "sym:name");
+	String *action = Getattr(n, "wrap:action");
+	if (directorsEnabled()) {
+	  String *classname = NewStringf("const char *classname SWIGUNUSED = \"%s::%s\"", module, symname);
+	  Wrapper_add_local(f, "classname", classname);
+	}
+	if (action) {
+	  Append(action, "\nDATA_PTR(self) = result;");
+	  if (GetFlag(pn, "feature:trackobjects")) {
+	    Append(action, "\nSWIG_RubyAddTracking(result, self);");
+	  }
+	}
+      }
+
+      /* Emit the function call */
+      if (director_method) {
+	Printf(f->code, "try {\n");
+      }
+
+      Setattr(n, "wrap:name", wname);
+
+      Swig_director_emit_dynamic_cast(n, f);
+      String *actioncode = emit_action(n);
+
+      if (director_method) {
+	Printf(actioncode, "} catch (Swig::DirectorException& e) {\n");
+	Printf(actioncode, "  rb_exc_raise(e.getError());\n");
+	Printf(actioncode, "  SWIG_fail;\n");
+	Printf(actioncode, "}\n");
+      }
+
+      /* Return value if necessary */
+      if (SwigType_type(t) != T_VOID && current != CONSTRUCTOR_INITIALIZE) {
+        need_result = 1;
+        if (GetFlag(n, "feature:predicate")) {
+          Printv(actioncode, tab4, "vresult = (result ? Qtrue : Qfalse);\n", NIL);
+        } else {
+          tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode);
+          actioncode = 0;
+          if (tm) {
+            Replaceall(tm, "$result", "vresult");
+            Replaceall(tm, "$source", "result");
+            Replaceall(tm, "$target", "vresult");
+
+            if (GetFlag(n, "feature:new"))
+              Replaceall(tm, "$owner", "SWIG_POINTER_OWN");
+            else
+              Replaceall(tm, "$owner", "0");
+
+#if 1
+            // FIXME: this will not try to unwrap directors returned as non-director
+            //        base class pointers!
+
+            /* New addition to unwrap director return values so that the original
+             * Ruby object is returned instead. 
+             */
+            bool unwrap = false;
+            String *decl = Getattr(n, "decl");
+            int is_pointer = SwigType_ispointer_return(decl);
+            int is_reference = SwigType_isreference_return(decl);
+            if (is_pointer || is_reference) {
+              String *type = Getattr(n, "type");
+              Node *parent = Swig_methodclass(n);
+              Node *modname = Getattr(parent, "module");
+              Node *target = Swig_directormap(modname, type);
+              if (target)
+                unwrap = true;
+            }
+            if (unwrap) {
+              Wrapper_add_local(f, "director", "Swig::Director *director = 0");
+              Printf(f->code, "director = dynamic_cast<Swig::Director *>(result);\n");
+              Printf(f->code, "if (director) {\n");
+              Printf(f->code, "  vresult = director->swig_get_self();\n");
+              Printf(f->code, "} else {\n");
+              Printf(f->code, "%s\n", tm);
+              Printf(f->code, "}\n");
+              director_method = 0;
+            } else {
+              Printf(f->code, "%s\n", tm);
+            }
+#else
+            Printf(f->code, "%s\n", tm);
+#endif
+            Delete(tm);
+          } else {
+            Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s.\n", SwigType_str(t, 0));
+          }
+        }
+      }
+      if (actioncode) {
+        Append(f->code, actioncode);
+        Delete(actioncode);
+      }
+      emit_return_variable(n, t, f);
+    }
+
+    /* Extra code needed for new and initialize methods */
+    if (current == CONSTRUCTOR_ALLOCATE) {
+      need_result = 1;
+      Printf(f->code, "VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE%s);\n", Char(SwigType_manglestr(t)));
+      Printf(f->code, "#ifndef HAVE_RB_DEFINE_ALLOC_FUNC\n");
+      Printf(f->code, "rb_obj_call_init(vresult, argc, argv);\n");
+      Printf(f->code, "#endif\n");
+    } else if (current == CONSTRUCTOR_INITIALIZE) {
+      need_result = 1;
+      // Printf(f->code, "DATA_PTR(self) = result;\n");
+    }
+    else
+      {
+	if ( need_result > 1 ) {
+	  if ( SwigType_type(t) == T_VOID )
+	    Printf(f->code, "vresult = rb_ary_new();\n");
+	  else
+	    {
+	      Printf(f->code, "if (vresult == Qnil) vresult = rb_ary_new();\n");
+	      Printf(f->code, "else vresult = SWIG_Ruby_AppendOutput( "
+		     "rb_ary_new(), vresult);\n");
+	    }
+	}
+      }
+
+    /* Dump argument output code; */
+    Printv(f->code, outarg, NIL);
+
+    /* Dump the argument cleanup code */
+    int need_cleanup = (current != CONSTRUCTOR_ALLOCATE) && (Len(cleanup) != 0);
+    if (need_cleanup) {
+      Printv(f->code, cleanup, NIL);
+    }
+
+
+    /* Look for any remaining cleanup.  This processes the %new directive */
+    if (current != CONSTRUCTOR_ALLOCATE && GetFlag(n, "feature:new")) {
+      tm = Swig_typemap_lookup("newfree", n, "result", 0);
+      if (tm) {
+	Replaceall(tm, "$source", "result");
+	Printv(f->code, tm, "\n", NIL);
+	Delete(tm);
+      }
+    }
+
+    /* Special processing on return value. */
+    tm = Swig_typemap_lookup("ret", n, "result", 0);
+    if (tm) {
+      Replaceall(tm, "$source", "result");
+      Printv(f->code, tm, NIL);
+      Delete(tm);
+    }
+
+    if (director_method) {
+      if ((tm = Swig_typemap_lookup("directorfree", n, "result", 0))) {
+	Replaceall(tm, "$input", "result");
+	Replaceall(tm, "$result", "vresult");
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+
+    /* Wrap things up (in a manner of speaking) */
+    if (need_result) {
+      if (current == CONSTRUCTOR_ALLOCATE) {
+	Printv(f->code, tab4, "return vresult;\n", NIL);
+      } else if (current == CONSTRUCTOR_INITIALIZE) {
+	Printv(f->code, tab4, "return self;\n", NIL);
+	Printv(f->code, "fail:\n", NIL);
+	if (need_cleanup) {
+	  Printv(f->code, cleanup, NIL);
+	}
+	Printv(f->code, tab4, "return Qnil;\n", NIL);
+      } else {
+	Wrapper_add_local(f, "vresult", "VALUE vresult = Qnil");
+	Printv(f->code, tab4, "return vresult;\n", NIL);
+	Printv(f->code, "fail:\n", NIL);
+	if (need_cleanup) {
+	  Printv(f->code, cleanup, NIL);
+	}
+	Printv(f->code, tab4, "return Qnil;\n", NIL);
+      }
+    } else {
+      Printv(f->code, tab4, "return Qnil;\n", NIL);
+      Printv(f->code, "fail:\n", NIL);
+      if (need_cleanup) {
+	Printv(f->code, cleanup, NIL);
+      }
+      Printv(f->code, tab4, "return Qnil;\n", NIL);
+    }
+
+    Printf(f->code, "}\n");
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+
+    /* Substitute the function name */
+    Replaceall(f->code, "$symname", symname);
+
+    /* Emit the function */
+    Wrapper_print(f, f_wrappers);
+
+    /* Now register the function with the interpreter */
+    if (!Swig_symbol_isoverloaded(n)) {
+      create_command(n, symname);
+    } else {
+      if (current == CONSTRUCTOR_ALLOCATE) {
+	create_command(n, symname);
+      } else {
+	if (!Getattr(n, "sym:nextSibling"))
+	  dispatchFunction(n);
+      }
+    }
+
+    Delete(kwargs);
+    Delete(cleanup);
+    Delete(outarg);
+    DelWrapper(f);
+    Delete(symname);
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * dispatchFunction()
+   * ------------------------------------------------------------ */
+
+  void dispatchFunction(Node *n) {
+    /* Last node in overloaded chain */
+
+    int maxargs;
+    String *tmp = NewString("");
+    String *dispatch = Swig_overload_dispatch(n, "return %s(nargs, args, self);", &maxargs);
+
+    /* Generate a dispatch wrapper for all overloaded functions */
+
+    Wrapper *f = NewWrapper();
+    String *symname = Getattr(n, "sym:name");
+    String *wname = Swig_name_wrapper(symname);
+
+    Printv(f->def, "SWIGINTERN VALUE ", wname, "(int nargs, VALUE *args, VALUE self) {", NIL);
+
+    Wrapper_add_local(f, "argc", "int argc");
+    bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n));
+    if (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) {
+      Printf(tmp, "VALUE argv[%d]", maxargs + 1);
+    } else {
+      Printf(tmp, "VALUE argv[%d]", maxargs);
+    }
+    Wrapper_add_local(f, "argv", tmp);
+    Wrapper_add_local(f, "ii", "int ii");
+
+    if (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) {
+      maxargs += 1;
+      Printf(f->code, "argc = nargs + 1;\n");
+      Printf(f->code, "argv[0] = self;\n");
+      Printf(f->code, "if (argc > %d) SWIG_fail;\n", maxargs);
+      Printf(f->code, "for (ii = 1; (ii < argc); ++ii) {\n");
+      Printf(f->code, "argv[ii] = args[ii-1];\n");
+      Printf(f->code, "}\n");
+    } else {
+      Printf(f->code, "argc = nargs;\n");
+      Printf(f->code, "if (argc > %d) SWIG_fail;\n", maxargs);
+      Printf(f->code, "for (ii = 0; (ii < argc); ++ii) {\n");
+      Printf(f->code, "argv[ii] = args[ii];\n");
+      Printf(f->code, "}\n");
+    }
+
+    Replaceall(dispatch, "$args", "nargs, args, self");
+    Printv(f->code, dispatch, "\n", NIL);
+
+
+    
+    // Generate prototype list, go to first node
+    Node *sibl = n;
+
+    String* type = SwigType_str(Getattr(sibl,"type"),NULL);
+
+    while (Getattr(sibl, "sym:previousSibling"))
+      sibl = Getattr(sibl, "sym:previousSibling");	// go all the way up
+
+    // Constructors will be treated specially
+    const bool isCtor = Cmp(Getattr(sibl,"feature:new"), "1") == 0;
+    const bool isMethod = ( Cmp(Getattr(sibl, "ismember"), "1") == 0 &&
+			    (!isCtor) );
+
+    // Construct real method name
+    String* methodName = NewString("");
+    if ( isMethod ) 
+      Printv( methodName, Getattr(parentNode(sibl),"sym:name"), ".", NIL );
+    Append( methodName, Getattr(sibl,"sym:name" ) );
+    if ( isCtor ) Append( methodName, ".new" ); 
+
+    // Generate prototype list
+    String *protoTypes = NewString("");
+    do {
+      Append( protoTypes, "\n\"    ");
+      if ( !isCtor )  Printv( protoTypes, type, " ", NIL );
+      Printv(protoTypes, methodName, NIL );
+      Parm* p = Getattr(sibl, "wrap:parms");
+      if (p && (current == MEMBER_FUNC || current == MEMBER_VAR || 
+		ctor_director) )
+	p = nextSibling(p); // skip self
+      Append( protoTypes, "(" );
+      while(p)
+	{
+ 	  Append( protoTypes, SwigType_str(Getattr(p,"type"), Getattr(p,"name")) );
+	  if ( ( p = nextSibling(p)) ) Append(protoTypes, ", ");
+	}
+      Append( protoTypes, ")\\n\"" );
+    } while ((sibl = Getattr(sibl, "sym:nextSibling")));
+
+    Append(f->code, "fail:\n");
+    Printf(f->code, "Ruby_Format_OverloadedError( argc, %d, \"%s\", %s);\n", 
+	   maxargs, methodName, protoTypes);
+    Append(f->code, "\nreturn Qnil;\n");
+
+    Delete(methodName);
+    Delete(type);
+    Delete(protoTypes);
+
+    Printv(f->code, "}\n", NIL);
+    Wrapper_print(f, f_wrappers);
+    create_command(n, Char(symname));
+
+    DelWrapper(f);
+    Delete(dispatch);
+    Delete(tmp);
+    Delete(wname);
+  }
+
+  /* ---------------------------------------------------------------------
+   * variableWrapper()
+   * --------------------------------------------------------------------- */
+
+  virtual int variableWrapper(Node *n) {
+    String* docs = docstring(n, AUTODOC_GETTER);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+
+    char *name = GetChar(n, "name");
+    char *iname = GetChar(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+    String *tm;
+    String *getfname, *setfname;
+    Wrapper *getf, *setf;
+
+    getf = NewWrapper();
+    setf = NewWrapper();
+
+    /* create getter */
+    int addfail = 0;
+    String *getname = Swig_name_get(iname);
+    getfname = Swig_name_wrapper(getname);
+    Setattr(n, "wrap:name", getfname);
+    Printv(getf->def, "SWIGINTERN VALUE\n", getfname, "(", NIL);
+    Printf(getf->def, "VALUE self");
+    Printf(getf->def, ") {");
+    Wrapper_add_local(getf, "_val", "VALUE _val");
+
+    tm = Swig_typemap_lookup("varout", n, name, 0);
+    if (tm) {
+      Replaceall(tm, "$result", "_val");
+      Replaceall(tm, "$target", "_val");
+      Replaceall(tm, "$source", name);
+      /* Printv(getf->code,tm, NIL); */
+      addfail = emit_action_code(n, getf->code, tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+    }
+    Printv(getf->code, tab4, "return _val;\n", NIL);
+    if (addfail) {
+      Append(getf->code, "fail:\n");
+      Append(getf->code, "  return Qnil;\n");
+    }
+    Append(getf->code, "}\n");
+
+    Wrapper_print(getf, f_wrappers);
+
+    if (!is_assignable(n)) {
+      setfname = NewString("NULL");
+    } else {
+      /* create setter */
+      String* docs = docstring(n, AUTODOC_SETTER);
+      Printf(f_wrappers, "%s", docs);
+      Delete(docs);
+
+      String *setname = Swig_name_set(iname);
+      setfname = Swig_name_wrapper(setname);
+      Setattr(n, "wrap:name", setfname);
+      Printv(setf->def, "SWIGINTERN VALUE\n", setfname, "(VALUE self, ", NIL);
+      Printf(setf->def, "VALUE _val) {");
+      tm = Swig_typemap_lookup("varin", n, name, 0);
+      if (tm) {
+	Replaceall(tm, "$input", "_val");
+	Replaceall(tm, "$source", "_val");
+	Replaceall(tm, "$target", name);
+	/* Printv(setf->code,tm,"\n",NIL); */
+	emit_action_code(n, setf->code, tm);
+      } else {
+	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s\n", SwigType_str(t, 0));
+      }
+      Printv(setf->code, tab4, "return _val;\n", NIL);
+      Printf(setf->code, "fail:\n");
+      Printv(setf->code, tab4, "return Qnil;\n", NIL);
+      Printf(setf->code, "}\n");
+      Wrapper_print(setf, f_wrappers);
+      Delete(setname);
+    }
+
+    /* define accessor method */
+    if (CPlusPlus) {
+      Insert(getfname, 0, "VALUEFUNC(");
+      Append(getfname, ")");
+      Insert(setfname, 0, "VALUEFUNC(");
+      Append(setfname, ")");
+    }
+
+    String *s = NewString("");
+    switch (current) {
+    case STATIC_VAR:
+      /* C++ class variable */
+      Printv(s, tab4, "rb_define_singleton_method(", klass->vname, ", \"", klass->strip(iname), "\", ", getfname, ", 0);\n", NIL);
+      if (!GetFlag(n, "feature:immutable")) {
+	Printv(s, tab4, "rb_define_singleton_method(", klass->vname, ", \"", klass->strip(iname), "=\", ", setfname, ", 1);\n", NIL);
+      }
+      Printv(klass->init, s, NIL);
+      break;
+    default:
+      /* C global variable */
+      /* wrapped in Ruby module attribute */
+      assert(current == NO_CPP);
+      if (!useGlobalModule) {
+	Printv(s, tab4, "rb_define_singleton_method(", modvar, ", \"", iname, "\", ", getfname, ", 0);\n", NIL);
+	if (!GetFlag(n, "feature:immutable")) {
+	  Printv(s, tab4, "rb_define_singleton_method(", modvar, ", \"", iname, "=\", ", setfname, ", 1);\n", NIL);
+	}
+      } else {
+	Printv(s, tab4, "rb_define_global_method(\"", iname, "\", ", getfname, ", 0);\n", NIL);
+	if (!GetFlag(n, "feature:immutable")) {
+	  Printv(s, tab4, "rb_define_global_method(\"", iname, "=\", ", setfname, ", 1);\n", NIL);
+	}
+      }
+      Printv(f_init, s, NIL);
+      Delete(s);
+      break;
+    }
+    Delete(getname);
+    Delete(getfname);
+    Delete(setfname);
+    DelWrapper(setf);
+    DelWrapper(getf);
+    return SWIG_OK;
+  }
+
+
+  /* ---------------------------------------------------------------------
+   * validate_const_name(char *name)
+   *
+   * Validate constant name.
+   * --------------------------------------------------------------------- */
+
+  char *validate_const_name(char *name, const char *reason) {
+    if (!name || name[0] == '\0')
+      return name;
+
+    if (isupper(name[0]))
+      return name;
+
+    if (islower(name[0])) {
+      name[0] = (char)toupper(name[0]);
+      Swig_warning(WARN_RUBY_WRONG_NAME, input_file, line_number, "Wrong %s name (corrected to `%s')\n", reason, name);
+      return name;
+    }
+
+    Swig_warning(WARN_RUBY_WRONG_NAME, input_file, line_number, "Wrong %s name %s\n", reason, name);
+
+    return name;
+  }
+
+  /* ---------------------------------------------------------------------
+   * constantWrapper()
+   * --------------------------------------------------------------------- */
+
+  virtual int constantWrapper(Node *n) {
+    Swig_require("constantWrapper", n, "*sym:name", "type", "value", NIL);
+
+    char *iname = GetChar(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+
+    if (current == CLASS_CONST) {
+      iname = klass->strip(iname);
+    }
+    validate_const_name(iname, "constant");
+    SetChar(n, "sym:name", iname);
+
+    /* Special hook for member pointer */
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(iname);
+      Printf(f_header, "static %s = %s;\n", SwigType_str(type, wname), value);
+      value = Char(wname);
+    }
+    String *tm = Swig_typemap_lookup("constant", n, value, 0);
+    if (!tm)
+      tm = Swig_typemap_lookup("constcode", n, value, 0);
+    if (tm) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", iname);
+      Replaceall(tm, "$symname", iname);
+      Replaceall(tm, "$value", value);
+      if (current == CLASS_CONST) {
+	if (multipleInheritance) {
+	  Replaceall(tm, "$module", klass->mImpl);
+	  Printv(klass->init, tm, "\n", NIL);
+	} else {
+	  Replaceall(tm, "$module", klass->vname);
+	  Printv(klass->init, tm, "\n", NIL);
+	}
+      } else {
+	if (!useGlobalModule) {
+	  Replaceall(tm, "$module", modvar);
+	} else {
+	  Replaceall(tm, "$module", "rb_cObject");
+	}
+	Printf(f_init, "%s\n", tm);
+      }
+    } else {
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value %s = %s\n", SwigType_str(type, 0), value);
+    }
+    Swig_restore(n);
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------------
+   * classDeclaration() 
+   *
+   * Records information about classes---even classes that might be defined in
+   * other modules referenced by %import.
+   * ----------------------------------------------------------------------------- */
+
+  virtual int classDeclaration(Node *n) {
+    if (!Getattr(n, "feature:onlychildren")) {
+      String *name = Getattr(n, "name");
+      String *symname = Getattr(n, "sym:name");
+      String *tdname = Getattr(n, "tdname");
+
+      name = tdname ? tdname : name;
+      String *namestr = SwigType_namestr(name);
+      klass = RCLASS(classes, Char(namestr));
+      if (!klass) {
+	klass = new RClass();
+	String *valid_name = NewString(symname ? symname : namestr);
+	validate_const_name(Char(valid_name), "class");
+	klass->set_name(namestr, symname, valid_name);
+	SET_RCLASS(classes, Char(namestr), klass);
+	Delete(valid_name);
+      }
+      Delete(namestr);
+    }
+    return Language::classDeclaration(n);
+  }
+
+  /**
+   * Process the comma-separated list of mixed-in module names (if any).
+   */
+  void includeRubyModules(Node *n) {
+    String *mixin = Getattr(n, "feature:mixin");
+    if (mixin) {
+      List *modules = Split(mixin, ',', INT_MAX);
+      if (modules && Len(modules) > 0) {
+	Iterator mod = First(modules);
+	while (mod.item) {
+	  if (Len(mod.item) > 0) {
+	    Printf(klass->init, "rb_include_module(%s, rb_eval_string(\"%s\"));\n", klass->vname, mod.item);
+	  }
+	  mod = Next(mod);
+	}
+      }
+      Delete(modules);
+    }
+  }
+
+  void handleBaseClasses(Node *n) {
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist)) {
+      Iterator base = First(baselist);
+      while (base.item && GetFlag(base.item, "feature:ignore")) {
+	base = Next(base);
+      }
+      while (base.item) {
+	String *basename = Getattr(base.item, "name");
+	String *basenamestr = SwigType_namestr(basename);
+	RClass *super = RCLASS(classes, Char(basenamestr));
+	Delete(basenamestr);
+	if (super) {
+	  SwigType *btype = NewString(basename);
+	  SwigType_add_pointer(btype);
+	  SwigType_remember(btype);
+	  if (multipleInheritance) {
+	    String *bmangle = SwigType_manglestr(btype);
+	    Insert(bmangle, 0, "((swig_class *) SWIGTYPE");
+	    Append(bmangle, "->clientdata)->mImpl");
+	    Printv(klass->init, "rb_include_module(", klass->mImpl, ", ", bmangle, ");\n", NIL);
+	    Delete(bmangle);
+	  } else {
+	    String *bmangle = SwigType_manglestr(btype);
+	    Insert(bmangle, 0, "((swig_class *) SWIGTYPE");
+	    Append(bmangle, "->clientdata)->klass");
+	    Replaceall(klass->init, "$super", bmangle);
+	    Delete(bmangle);
+	  }
+	  Delete(btype);
+	}
+	base = Next(base);
+	while (base.item && GetFlag(base.item, "feature:ignore")) {
+	  base = Next(base);
+	}
+	if (!multipleInheritance) {
+	  /* Warn about multiple inheritance for additional base class(es) */
+	  while (base.item) {
+	    if (GetFlag(base.item, "feature:ignore")) {
+	      base = Next(base);
+	      continue;
+	    }
+	    String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0);
+	    String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0);
+	    Swig_warning(WARN_RUBY_MULTIPLE_INHERITANCE, input_file, line_number,
+			 "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Ruby.\n", proxyclassname, baseclassname);
+	    base = Next(base);
+	  }
+	}
+      }
+    }
+  }
+
+  /**
+   * Check to see if a %markfunc was specified.
+   */
+  void handleMarkFuncDirective(Node *n) {
+    String *markfunc = Getattr(n, "feature:markfunc");
+    if (markfunc) {
+      Printf(klass->init, "c%s.mark = (void (*)(void *)) %s;\n", klass->name, markfunc);
+    } else {
+      Printf(klass->init, "c%s.mark = 0;\n", klass->name);
+    }
+  }
+
+  /**
+   * Check to see if a %freefunc was specified.
+   */
+  void handleFreeFuncDirective(Node *n) {
+    String *freefunc = Getattr(n, "feature:freefunc");
+    if (freefunc) {
+      Printf(klass->init, "c%s.destroy = (void (*)(void *)) %s;\n", klass->name, freefunc);
+    } else {
+      if (klass->destructor_defined) {
+	Printf(klass->init, "c%s.destroy = (void (*)(void *)) free_%s;\n", klass->name, klass->mname);
+      }
+    }
+  }
+
+  /**
+   * Check to see if tracking is enabled for this class.
+   */
+  void handleTrackDirective(Node *n) {
+    int trackObjects = GetFlag(n, "feature:trackobjects");
+    if (trackObjects) {
+      Printf(klass->init, "c%s.trackObjects = 1;\n", klass->name);
+    } else {
+      Printf(klass->init, "c%s.trackObjects = 0;\n", klass->name);
+    }
+  }
+
+  /* ----------------------------------------------------------------------
+   * classHandler()
+   * ---------------------------------------------------------------------- */
+
+  virtual int classHandler(Node *n) {
+    String* docs = docstring(n, AUTODOC_CLASS);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    String *name = Getattr(n, "name");
+    String *symname = Getattr(n, "sym:name");
+    String *namestr = SwigType_namestr(name);	// does template expansion
+
+    klass = RCLASS(classes, Char(namestr));
+    assert(klass != 0);
+    Delete(namestr);
+    String *valid_name = NewString(symname);
+    validate_const_name(Char(valid_name), "class");
+
+    Clear(klass->type);
+    Printv(klass->type, Getattr(n, "classtype"), NIL);
+    Printv(f_wrappers, "swig_class c", valid_name, ";\n\n", NIL);
+    Printv(klass->init, "\n", tab4, NIL);
+
+    if (!useGlobalModule) {
+      Printv(klass->init, klass->vname, " = rb_define_class_under(", modvar, ", \"", klass->name, "\", $super);\n", NIL);
+    } else {
+      Printv(klass->init, klass->vname, " = rb_define_class(\"", klass->name, 
+	     "\", $super);\n", NIL);
+    }
+
+    if (multipleInheritance) {
+      Printv(klass->init, klass->mImpl, " = rb_define_module_under(", klass->vname, ", \"Impl\");\n", NIL);
+    }
+
+    SwigType *tt = NewString(name);
+    SwigType_add_pointer(tt);
+    SwigType_remember(tt);
+    String *tm = SwigType_manglestr(tt);
+    Printf(klass->init, "SWIG_TypeClientData(SWIGTYPE%s, (void *) &c%s);\n", tm, valid_name);
+    Delete(tm);
+    Delete(tt);
+    Delete(valid_name);
+
+    includeRubyModules(n);
+
+    Printv(klass->init, "$allocator", NIL);
+    Printv(klass->init, "$initializer", NIL);
+
+    Language::classHandler(n);
+
+    handleBaseClasses(n);
+    handleMarkFuncDirective(n);
+    handleFreeFuncDirective(n);
+    handleTrackDirective(n);
+
+    if (multipleInheritance) {
+      Printv(klass->init, "rb_include_module(", klass->vname, ", ", klass->mImpl, ");\n", NIL);
+    }
+
+    String *s = NewString("");
+    Printv(s, tab4, "rb_undef_alloc_func(", klass->vname, ");\n", NIL);
+    Replaceall(klass->init, "$allocator", s);
+    Replaceall(klass->init, "$initializer", "");
+
+    if (GetFlag(n, "feature:exceptionclass")) {
+      Replaceall(klass->init, "$super", "rb_eRuntimeError");
+    } else {
+      Replaceall(klass->init, "$super", "rb_cObject");
+    }
+    Delete(s);
+
+    Printv(f_init, klass->init, NIL);
+    klass = 0;
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberfunctionHandler()
+   *
+   * Method for adding C++ member function
+   *
+   * By default, we're going to create a function of the form :
+   *
+   *         Foo_bar(this,args)
+   *
+   * Where Foo is the classname, bar is the member name and the this pointer
+   * is explicitly attached to the beginning.
+   *
+   * The renaming only applies to the member function part, not the full
+   * classname.
+   *
+   * --------------------------------------------------------------------- */
+
+  virtual int memberfunctionHandler(Node *n) {
+    current = MEMBER_FUNC;
+
+    String* docs = docstring(n, AUTODOC_METHOD);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    Language::memberfunctionHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ---------------------------------------------------------------------
+   * constructorHandler()
+   *
+   * Method for adding C++ member constructor
+   * -------------------------------------------------------------------- */
+
+  void set_director_ctor_code(Node *n) {
+    /* director ctor code is specific for each class */
+    Delete(director_prot_ctor_code);
+    director_prot_ctor_code = NewString("");
+    Node *pn = Swig_methodclass(n);
+    String *symname = Getattr(pn, "sym:name");
+    String *name = Copy(symname);
+    char *cname = Char(name);
+    if (cname)
+      cname[0] = (char)toupper(cname[0]);
+    Printv(director_prot_ctor_code,
+	   "if ( $comparison ) { /* subclassed */\n",
+	   "  $director_new \n",
+	   "} else {\n", "  rb_raise(rb_eNameError,\"accessing abstract class or protected constructor\"); \n", "  return Qnil;\n", "}\n", NIL);
+    Delete(director_ctor_code);
+    director_ctor_code = NewString("");
+    Printv(director_ctor_code, "if ( $comparison ) { /* subclassed */\n", "  $director_new \n", "} else {\n", "  $nondirector_new \n", "}\n", NIL);
+    Delete(name);
+  }
+
+  virtual int constructorHandler(Node *n) {
+    int use_director = Swig_directorclass(n);
+    if (use_director) {
+      set_director_ctor_code(n);
+    }
+
+    /* First wrap the allocate method */
+    current = CONSTRUCTOR_ALLOCATE;
+    Swig_name_register((String_or_char *) "construct", (String_or_char *) "%c_allocate");
+
+
+    Language::constructorHandler(n);
+
+    /* 
+     * If we're wrapping the constructor of a C++ director class, prepend a new parameter
+     * to receive the scripting language object (e.g. 'self')
+     *
+     */
+    Swig_save("ruby:constructorHandler", n, "parms", NIL);
+    if (use_director) {
+      Parm *parms = Getattr(n, "parms");
+      Parm *self;
+      String *name = NewString("self");
+      String *type = NewString("VALUE");
+      self = NewParm(type, name);
+      Delete(type);
+      Delete(name);
+      Setattr(self, "lname", "Qnil");
+      if (parms)
+	set_nextSibling(self, parms);
+      Setattr(n, "parms", self);
+      Setattr(n, "wrap:self", "1");
+      Delete(self);
+    }
+
+
+
+    /* Now do the instance initialize method */
+    String* docs = docstring(n, AUTODOC_CTOR);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    current = CONSTRUCTOR_INITIALIZE;
+    Swig_name_register((String_or_char *) "construct", (String_or_char *) "new_%c");
+    Language::constructorHandler(n);
+
+    /* Restore original parameter list */
+    Delattr(n, "wrap:self");
+    Swig_restore(n);
+
+    /* Done */
+    Swig_name_unregister((String_or_char *) "construct");
+    current = NO_CPP;
+    klass->constructor_defined = 1;
+    return SWIG_OK;
+  }
+
+  virtual int copyconstructorHandler(Node *n) {
+    int use_director = Swig_directorclass(n);
+    if (use_director) {
+      set_director_ctor_code(n);
+    }
+
+    /* First wrap the allocate method */
+    current = CONSTRUCTOR_ALLOCATE;
+    Swig_name_register((String_or_char *) "construct", (String_or_char *) "%c_allocate");
+
+    return Language::copyconstructorHandler(n);
+  }
+
+
+  /* ---------------------------------------------------------------------
+   * destructorHandler()
+   * -------------------------------------------------------------------- */
+
+  virtual int destructorHandler(Node *n) {
+
+    /* Do no spit free function if user defined his own for this class */
+    Node *pn = Swig_methodclass(n);
+    String *freefunc = Getattr(pn, "feature:freefunc");
+    if (freefunc) return SWIG_OK;
+
+    current = DESTRUCTOR;
+    Language::destructorHandler(n);
+
+    freefunc = NewString("");
+    String *freebody = NewString("");
+    String *pname0 = Swig_cparm_name(0, 0);
+
+    Printv(freefunc, "free_", klass->mname, NIL);
+    Printv(freebody, "SWIGINTERN void\n", freefunc, "(", klass->type, " *", pname0, ") {\n", tab4, NIL);
+
+    /* Check to see if object tracking is activated for the class
+       that owns this destructor. */
+    if (GetFlag(pn, "feature:trackobjects")) {
+      Printf(freebody, "SWIG_RubyRemoveTracking(%s);\n", pname0);
+      Printv(freebody, tab4, NIL);
+    }
+
+    if (Extend) {
+      String *wrap = Getattr(n, "wrap:code");
+      if (wrap) {
+	Printv(f_wrappers, wrap, NIL);
+      }
+      /*    Printv(freebody, Swig_name_destroy(name), "(", pname0, ")", NIL); */
+      Printv(freebody, Getattr(n, "wrap:action"), "\n", NIL);
+    } else {
+      String *action = Getattr(n, "wrap:action");
+      if (action) {
+	Printv(freebody, action, "\n", NIL);
+      } else {
+	/* In the case swig emits no destroy function. */
+	if (CPlusPlus)
+	  Printf(freebody, "delete %s;\n", pname0);
+	else
+	  Printf(freebody, "free((char*) %s);\n", pname0);
+      }
+    }
+
+    Printv(freebody, "}\n\n", NIL);
+
+    Printv(f_wrappers, freebody, NIL);
+
+    klass->destructor_defined = 1;
+    current = NO_CPP;
+    Delete(freefunc);
+    Delete(freebody);
+    Delete(pname0);
+    return SWIG_OK;
+  }
+
+  /* ---------------------------------------------------------------------
+   * membervariableHandler()
+   *
+   * This creates a pair of functions to set/get the variable of a member.
+   * -------------------------------------------------------------------- */
+
+  virtual int membervariableHandler(Node *n) {
+    String* docs = docstring(n, AUTODOC_GETTER);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    if (is_assignable(n)) {
+      String* docs = docstring(n, AUTODOC_SETTER);
+      Printf(f_wrappers, "%s", docs);
+      Delete(docs);
+    }
+
+    current = MEMBER_VAR;
+    Language::membervariableHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* -----------------------------------------------------------------------
+   * staticmemberfunctionHandler()
+   *
+   * Wrap a static C++ function
+   * ---------------------------------------------------------------------- */
+
+  virtual int staticmemberfunctionHandler(Node *n) {
+    String* docs = docstring(n, AUTODOC_STATICFUNC);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    current = STATIC_FUNC;
+    Language::staticmemberfunctionHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ----------------------------------------------------------------------
+   * memberconstantHandler()
+   *
+   * Create a C++ constant
+   * --------------------------------------------------------------------- */
+
+  virtual int memberconstantHandler(Node *n) {
+    String* docs = docstring(n, AUTODOC_STATICFUNC);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    current = CLASS_CONST;
+    Language::memberconstantHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* ---------------------------------------------------------------------
+   * staticmembervariableHandler()
+   * --------------------------------------------------------------------- */
+
+  virtual int staticmembervariableHandler(Node *n) {
+    String* docs = docstring(n, AUTODOC_GETTER);
+    Printf(f_wrappers, "%s", docs);
+    Delete(docs);
+
+    if (is_assignable(n)) {
+      String* docs = docstring(n, AUTODOC_SETTER);
+      Printf(f_wrappers, "%s", docs);
+      Delete(docs);
+    }
+
+    current = STATIC_VAR;
+    Language::staticmembervariableHandler(n);
+    current = NO_CPP;
+    return SWIG_OK;
+  }
+
+  /* C++ director class generation */
+  virtual int classDirector(Node *n) {
+    return Language::classDirector(n);
+  }
+
+  virtual int classDirectorInit(Node *n) {
+    String *declaration;
+    declaration = Swig_director_declaration(n);
+    Printf(f_directors_h, "\n");
+    Printf(f_directors_h, "%s\n", declaration);
+    Printf(f_directors_h, "public:\n");
+    Delete(declaration);
+    return Language::classDirectorInit(n);
+  }
+
+  virtual int classDirectorEnd(Node *n) {
+    Printf(f_directors_h, "};\n\n");
+    return Language::classDirectorEnd(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorConstructor()
+   * ------------------------------------------------------------ */
+
+  virtual int classDirectorConstructor(Node *n) {
+    Node *parent = Getattr(n, "parentNode");
+    String *sub = NewString("");
+    String *decl = Getattr(n, "decl");
+    String *supername = Swig_class_name(parent);
+    String *classname = NewString("");
+    Printf(classname, "SwigDirector_%s", supername);
+
+    /* insert self parameter */
+    Parm *p;
+    ParmList *superparms = Getattr(n, "parms");
+    ParmList *parms = CopyParmList(superparms);
+    String *type = NewString("VALUE");
+    p = NewParm(type, NewString("self"));
+    set_nextSibling(p, parms);
+    parms = p;
+
+    if (!Getattr(n, "defaultargs")) {
+      /* constructor */
+      {
+	Wrapper *w = NewWrapper();
+	String *call;
+	String *basetype = Getattr(parent, "classtype");
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 0);
+	call = Swig_csuperclass_call(0, basetype, superparms);
+	Printf(w->def, "%s::%s: %s, Swig::Director(self) { }", classname, target, call);
+	Delete(target);
+	Wrapper_print(w, f_directors);
+	Delete(call);
+	DelWrapper(w);
+      }
+
+      /* constructor header */
+      {
+	String *target = Swig_method_decl(0, decl, classname, parms, 0, 1);
+	Printf(f_directors_h, "    %s;\n", target);
+	Delete(target);
+      }
+    }
+
+    Delete(sub);
+    Delete(classname);
+    Delete(supername);
+    Delete(parms);
+    return Language::classDirectorConstructor(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDirectorDefaultConstructor()
+   * ------------------------------------------------------------ */
+
+  virtual int classDirectorDefaultConstructor(Node *n) {
+    String *classname;
+    Wrapper *w;
+    classname = Swig_class_name(n);
+    w = NewWrapper();
+    Printf(w->def, "SwigDirector_%s::SwigDirector_%s(VALUE self) : Swig::Director(self) { }", classname, classname);
+    Wrapper_print(w, f_directors);
+    DelWrapper(w);
+    Printf(f_directors_h, "    SwigDirector_%s(VALUE self);\n", classname);
+    Delete(classname);
+    return Language::classDirectorDefaultConstructor(n);
+  }
+
+  /* ---------------------------------------------------------------
+   * exceptionSafeMethodCall()
+   *
+   * Emit a virtual director method to pass a method call on to the 
+   * underlying Ruby instance.
+   *
+   * --------------------------------------------------------------- */
+
+  void exceptionSafeMethodCall(String *className, Node *n, Wrapper *w, int argc, String *args, bool initstack) {
+    Wrapper *body = NewWrapper();
+    Wrapper *rescue = NewWrapper();
+
+    String *methodName = Getattr(n, "sym:name");
+
+    String *bodyName = NewStringf("%s_%s_body", className, methodName);
+    String *rescueName = NewStringf("%s_%s_rescue", className, methodName);
+    String *depthCountName = NewStringf("%s_%s_call_depth", className, methodName);
+
+    // Check for an exception typemap of some kind
+    String *tm = Swig_typemap_lookup("director:except", n, "result", 0);
+    if (!tm) {
+      tm = Getattr(n, "feature:director:except");
+    }
+
+    if ((tm != 0) && (Len(tm) > 0) && (Strcmp(tm, "1") != 0)) {
+      // Declare a global to hold the depth count
+      if (!Getattr(n, "sym:nextSibling")) {
+	Printf(body->def, "static int %s = 0;\n", depthCountName);
+
+	// Function body
+	Printf(body->def, "VALUE %s(VALUE data) {\n", bodyName);
+	Wrapper_add_localv(body, "args", "Swig::body_args *", "args", "= reinterpret_cast<Swig::body_args *>(data)", NIL);
+	Wrapper_add_localv(body, "result", "VALUE", "result", "= Qnil", NIL);
+	Printf(body->code, "%s++;\n", depthCountName);
+	Printv(body->code, "result = rb_funcall2(args->recv, args->id, args->argc, args->argv);\n", NIL);
+	Printf(body->code, "%s--;\n", depthCountName);
+	Printv(body->code, "return result;\n", NIL);
+	Printv(body->code, "}", NIL);
+
+	// Exception handler
+	Printf(rescue->def, "VALUE %s(VALUE args, VALUE error) {\n", rescueName);
+	Replaceall(tm, "$error", "error");
+	Printf(rescue->code, "%s--;\n", depthCountName);
+	Printf(rescue->code, "if (%s == 0) ", depthCountName);
+	Printv(rescue->code, Str(tm), "\n", NIL);
+	Printv(rescue->code, "rb_exc_raise(error);\n", NIL);
+	Printv(rescue->code, "}", NIL);
+      }
+
+      // Main code
+      Wrapper_add_localv(w, "args", "Swig::body_args", "args", NIL);
+      Wrapper_add_localv(w, "status", "int", "status", NIL);
+      Printv(w->code, "args.recv = swig_get_self();\n", NIL);
+      Printf(w->code, "args.id = rb_intern(\"%s\");\n", methodName);
+      Printf(w->code, "args.argc = %d;\n", argc);
+      if (argc > 0) {
+	Printf(w->code, "args.argv = new VALUE[%d];\n", argc);
+	for (int i = 0; i < argc; i++) {
+	  Printf(w->code, "args.argv[%d] = obj%d;\n", i, i);
+	}
+      } else {
+	Printv(w->code, "args.argv = 0;\n", NIL);
+      }
+      Printf(w->code, "result = rb_protect(PROTECTFUNC(%s), reinterpret_cast<VALUE>(&args), &status);\n", bodyName);
+      if ( initstack ) Printf(w->code, "SWIG_RELEASE_STACK;\n");
+      Printf(w->code, "if (status) {\n");
+      Printf(w->code, "VALUE lastErr = rb_gv_get(\"$!\");\n");
+      Printf(w->code, "%s(reinterpret_cast<VALUE>(&args), lastErr);\n", rescueName);
+      Printf(w->code, "}\n");
+      if (argc > 0) {
+	Printv(w->code, "delete [] args.argv;\n", NIL);
+      }
+      // Dump wrapper code
+      Wrapper_print(body, f_directors_helpers);
+      Wrapper_print(rescue, f_directors_helpers);
+    } else {
+      if (argc > 0) {
+	Printf(w->code, "result = rb_funcall(swig_get_self(), rb_intern(\"%s\"), %d%s);\n", methodName, argc, args);
+      } else {
+	Printf(w->code, "result = rb_funcall(swig_get_self(), rb_intern(\"%s\"), 0, NULL);\n", methodName);
+      }
+      if ( initstack ) Printf(w->code, "SWIG_RELEASE_STACK;\n");
+    }
+
+    // Clean up
+    Delete(bodyName);
+    Delete(rescueName);
+    Delete(depthCountName);
+    DelWrapper(body);
+    DelWrapper(rescue);
+  }
+
+  virtual int classDirectorMethod(Node *n, Node *parent, String *super) {
+    int is_void = 0;
+    int is_pointer = 0;
+    String *decl;
+    String *type;
+    String *name;
+    String *classname;
+    String *c_classname = Getattr(parent, "name");
+    String *declaration;
+    ParmList *l;
+    Wrapper *w;
+    String *tm;
+    String *wrap_args = NewString("");
+    String *return_type;
+    Parm *p;
+    String *value = Getattr(n, "value");
+    String *storage = Getattr(n, "storage");
+    bool pure_virtual = false;
+    int status = SWIG_OK;
+    int idx;
+    bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
+    bool asvoid = checkAttribute( n, "feature:numoutputs", "0") ? true : false;
+    bool initstack = checkAttribute( n, "feature:initstack", "1") ? true : false;
+
+    if (Cmp(storage, "virtual") == 0) {
+      if (Cmp(value, "0") == 0) {
+	pure_virtual = true;
+      }
+    }
+    String *overnametmp = NewString(Getattr(n, "sym:name"));
+    if (Getattr(n, "sym:overloaded")) {
+      Printf(overnametmp, "::%s", Getattr(n, "sym:overname"));
+    }
+
+    classname = Getattr(parent, "sym:name");
+    type = Getattr(n, "type");
+    name = Getattr(n, "name");
+
+    w = NewWrapper();
+    declaration = NewString("");
+
+    /* determine if the method returns a pointer */
+    decl = Getattr(n, "decl");
+    is_pointer = SwigType_ispointer_return(decl);
+    is_void = (!Cmp(type, "void") && !is_pointer);
+
+    /* form complete return type */
+    return_type = Copy(type);
+    {
+      SwigType *t = Copy(decl);
+      SwigType *f = 0;
+      f = SwigType_pop_function(t);
+      SwigType_push(return_type, t);
+      Delete(f);
+      Delete(t);
+    }
+
+    /* virtual method definition */
+    l = Getattr(n, "parms");
+    String *target;
+    String *pclassname = NewStringf("SwigDirector_%s", classname);
+    String *qualified_name = NewStringf("%s::%s", pclassname, name);
+    SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type;
+    target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0);
+    Printf(w->def, "%s", target);
+    Delete(qualified_name);
+    Delete(target);
+    /* header declaration */
+    target = Swig_method_decl(rtype, decl, name, l, 0, 1);
+    Printf(declaration, "    virtual %s", target);
+    Delete(target);
+
+    // Get any exception classes in the throws typemap
+    ParmList *throw_parm_list = 0;
+
+    if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) {
+      Parm *p;
+      int gencomma = 0;
+
+      Append(w->def, " throw(");
+      Append(declaration, " throw(");
+
+      if (throw_parm_list)
+	Swig_typemap_attach_parms("throws", throw_parm_list, 0);
+      for (p = throw_parm_list; p; p = nextSibling(p)) {
+	if ((tm = Getattr(p, "tmap:throws"))) {
+	  if (gencomma++) {
+	    Append(w->def, ", ");
+	    Append(declaration, ", ");
+	  }
+
+	  Printf(w->def, "%s", SwigType_str(Getattr(p, "type"), 0));
+	  Printf(declaration, "%s", SwigType_str(Getattr(p, "type"), 0));
+	}
+      }
+
+      Append(w->def, ")");
+      Append(declaration, ")");
+    }
+
+    Append(w->def, " {");
+    Append(declaration, ";\n");
+
+    if (initstack && !(ignored_method && !pure_virtual)) {
+      Append(w->def, "\nSWIG_INIT_STACK;\n");
+    }
+
+    /* declare method return value 
+     * if the return value is a reference or const reference, a specialized typemap must
+     * handle it, including declaration of c_result ($result).
+     */
+    if (!is_void) {
+      if (!(ignored_method && !pure_virtual)) {
+	Wrapper_add_localv(w, "c_result", SwigType_lstr(return_type, "c_result"), NIL);
+      }
+    }
+
+    if (ignored_method) {
+      if (!pure_virtual) {
+	if (!is_void)
+	  Printf(w->code, "return ");
+	String *super_call = Swig_method_call(super, l);
+	Printf(w->code, "%s;\n", super_call);
+	Delete(super_call);
+      } else {
+	Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname),
+	       SwigType_namestr(name));
+      }
+    } else {
+      /* attach typemaps to arguments (C/C++ -> Ruby) */
+      String *arglist = NewString("");
+
+      /**
+       * For each parameter to the C++ member function, copy the parameter name
+       * to its "lname"; this ensures that Swig_typemap_attach_parms() will do
+       * the right thing when it sees strings like "$1" in your "directorin" typemaps.
+       * Not sure if it's OK to leave it like this, but seems OK so far.
+       */
+      typemap_copy_pname_to_lname(l);
+
+      Swig_typemap_attach_parms("in", l, 0);
+      Swig_typemap_attach_parms("directorin", l, 0);
+      Swig_typemap_attach_parms("directorargout", l, w);
+
+      char source[256];
+
+      int outputs = 0;
+      if (!is_void && !asvoid)
+	outputs++;
+
+      /* build argument list and type conversion string */
+      idx = 0; p = l;
+      while ( p ) {
+
+	if (Getattr(p, "tmap:ignore")) {
+	  p = Getattr(p, "tmap:ignore:next");
+	  continue;
+	}
+
+	if (Getattr(p, "tmap:directorargout") != 0)
+	  outputs++;
+
+	if ( checkAttribute( p, "tmap:in:numinputs", "0") )
+	  {
+	    p = Getattr(p, "tmap:in:next");
+	    continue;
+	  }
+
+	String *parameterName = Getattr(p, "name");
+	String *parameterType = Getattr(p, "type");
+
+	Putc(',', arglist);
+	if ((tm = Getattr(p, "tmap:directorin")) != 0) {
+	  sprintf(source, "obj%d", idx++);
+	  Replaceall(tm, "$input", source);
+	  Replaceall(tm, "$owner", "0");
+	  Printv(wrap_args, tm, "\n", NIL);
+	  Wrapper_add_localv(w, source, "VALUE", source, "= Qnil", NIL);
+	  Printv(arglist, source, NIL);
+	  p = Getattr(p, "tmap:directorin:next");
+	  continue;
+	} else if (Cmp(parameterType, "void")) {
+	  /**
+	   * Special handling for pointers to other C++ director classes.
+	   * Ideally this would be left to a typemap, but there is currently no
+	   * way to selectively apply the dynamic_cast<> to classes that have
+	   * directors.  In other words, the type "SwigDirector_$1_lname" only exists
+	   * for classes with directors.  We avoid the problem here by checking
+	   * module.wrap::directormap, but it's not clear how to get a typemap to
+	   * do something similar.  Perhaps a new default typemap (in addition
+	   * to SWIGTYPE) called DIRECTORTYPE?
+	   */
+	  if (SwigType_ispointer(parameterType) || SwigType_isreference(parameterType)) {
+	    Node *modname = Getattr(parent, "module");
+	    Node *target = Swig_directormap(modname, parameterType);
+	    sprintf(source, "obj%d", idx++);
+	    String *nonconst = 0;
+	    /* strip pointer/reference --- should move to Swig/stype.c */
+	    String *nptype = NewString(Char(parameterType) + 2);
+	    /* name as pointer */
+	    String *ppname = Copy(parameterName);
+	    if (SwigType_isreference(parameterType)) {
+	      Insert(ppname, 0, "&");
+	    }
+	    /* if necessary, cast away const since Ruby doesn't support it! */
+	    if (SwigType_isconst(nptype)) {
+	      nonconst = NewStringf("nc_tmp_%s", parameterName);
+	      String *nonconst_i = NewStringf("= const_cast<%s>(%s)", SwigType_lstr(parameterType, 0), ppname);
+	      Wrapper_add_localv(w, nonconst, SwigType_lstr(parameterType, 0), nonconst, nonconst_i, NIL);
+	      Delete(nonconst_i);
+	      Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number,
+			   "Target language argument '%s' discards const in director method %s::%s.\n", SwigType_str(parameterType, parameterName),
+			   SwigType_namestr(c_classname), SwigType_namestr(name));
+	    } else {
+	      nonconst = Copy(ppname);
+	    }
+	    Delete(nptype);
+	    Delete(ppname);
+	    String *mangle = SwigType_manglestr(parameterType);
+	    if (target) {
+	      String *director = NewStringf("director_%s", mangle);
+	      Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL);
+	      Wrapper_add_localv(w, source, "VALUE", source, "= Qnil", NIL);
+	      Printf(wrap_args, "%s = dynamic_cast<Swig::Director *>(%s);\n", director, nonconst);
+	      Printf(wrap_args, "if (!%s) {\n", director);
+	      Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
+	      Printf(wrap_args, "} else {\n");
+	      Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director);
+	      Printf(wrap_args, "}\n");
+	      Delete(director);
+	      Printv(arglist, source, NIL);
+	    } else {
+	      Wrapper_add_localv(w, source, "VALUE", source, "= Qnil", NIL);
+	      Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
+	      //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", 
+	      //       source, nonconst, base);
+	      Printv(arglist, source, NIL);
+	    }
+	    Delete(mangle);
+	    Delete(nonconst);
+	  } else {
+	    Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
+			 "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(parameterType, 0),
+			 SwigType_namestr(c_classname), SwigType_namestr(name));
+	    status = SWIG_NOWRAP;
+	    break;
+	  }
+	}
+	p = nextSibling(p);
+      }
+
+      /* declare Ruby return value */
+      Wrapper_add_local(w, "result", "VALUE result");
+
+      /* wrap complex arguments to VALUEs */
+      Printv(w->code, wrap_args, NIL);
+
+      /* pass the method call on to the Ruby object */
+      exceptionSafeMethodCall(classname, n, w, idx, arglist, initstack);
+
+      /*
+       * Ruby method may return a simple object, or an Array of objects.
+       * For in/out arguments, we have to extract the appropriate VALUEs from the Array,
+       * then marshal everything back to C/C++ (return value and output arguments).
+       */
+
+      /* Marshal return value and other outputs (if any) from VALUE to C/C++ type */
+
+      String *cleanup = NewString("");
+      String *outarg = NewString("");
+
+      if (outputs > 1) {
+	Wrapper_add_local(w, "output", "VALUE output");
+	Printf(w->code, "if (TYPE(result) != T_ARRAY) {\n");
+	Printf(w->code, "Ruby_DirectorTypeMismatchException(\"Ruby method failed to return an array.\");\n");
+	Printf(w->code, "}\n");
+      }
+
+      idx = 0;
+
+      /* Marshal return value */
+      if (!is_void) {
+	/* This seems really silly.  The node's type excludes qualifier/pointer/reference markers,
+	 * which have to be retrieved from the decl field to construct return_type.  But the typemap
+	 * lookup routine uses the node's type, so we have to swap in and out the correct type.
+	 * It's not just me, similar silliness also occurs in Language::cDeclaration().
+	 */
+	Setattr(n, "type", return_type);
+	tm = Swig_typemap_lookup("directorout", n, "result", w);
+	Setattr(n, "type", type);
+	if (tm == 0) {
+	  String *name = NewString("result");
+	  tm = Swig_typemap_search("directorout", return_type, name, NULL);
+	  Delete(name);
+	}
+	if (tm != 0) {
+	  if (outputs > 1 && !asvoid ) {
+	    Printf(w->code, "output = rb_ary_entry(result, %d);\n", idx++);
+	    Replaceall(tm, "$input", "output");
+	  } else {
+	    Replaceall(tm, "$input", "result");
+	  }
+	  /* TODO check this */
+	  if (Getattr(n, "wrap:disown")) {
+	    Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	  } else {
+	    Replaceall(tm, "$disown", "0");
+	  }
+	  Replaceall(tm, "$result", "c_result");
+	  Printv(w->code, tm, "\n", NIL);
+	} else {
+	  Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number,
+		       "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(return_type, 0),
+		       SwigType_namestr(c_classname), SwigType_namestr(name));
+	  status = SWIG_ERROR;
+	}
+      }
+
+      /* Marshal outputs */
+      for (p = l; p;) {
+	if ((tm = Getattr(p, "tmap:directorargout")) != 0) {
+	  if (outputs > 1) {
+	    Printf(w->code, "output = rb_ary_entry(result, %d);\n", idx++);
+	    Replaceall(tm, "$input", "output");
+	  } else {
+	    Replaceall(tm, "$input", "result");
+	  }
+	  Replaceall(tm, "$result", Getattr(p, "name"));
+	  Printv(w->code, tm, "\n", NIL);
+	  p = Getattr(p, "tmap:directorargout:next");
+	} else {
+	  p = nextSibling(p);
+	}
+      }
+
+      Delete(arglist);
+      Delete(cleanup);
+      Delete(outarg);
+    }
+
+    /* any existing helper functions to handle this? */
+    if (!is_void) {
+      if (!(ignored_method && !pure_virtual)) {
+	String *rettype = SwigType_str(return_type, 0);
+	if (!SwigType_isreference(return_type)) {
+	  Printf(w->code, "return (%s) c_result;\n", rettype);
+	} else {
+	  Printf(w->code, "return (%s) *c_result;\n", rettype);
+	}
+	Delete(rettype);
+      }
+    }
+
+    Printf(w->code, "}\n");
+
+    // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method
+    String *inline_extra_method = NewString("");
+    if (dirprot_mode() && !is_public(n) && !pure_virtual) {
+      Printv(inline_extra_method, declaration, NIL);
+      String *extra_method_name = NewStringf("%sSwigPublic", name);
+      Replaceall(inline_extra_method, name, extra_method_name);
+      Replaceall(inline_extra_method, ";\n", " {\n      ");
+      if (!is_void)
+	Printf(inline_extra_method, "return ");
+      String *methodcall = Swig_method_call(super, l);
+      Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
+      Delete(methodcall);
+      Delete(extra_method_name);
+    }
+
+    /* emit the director method */
+    if (status == SWIG_OK) {
+      if (!Getattr(n, "defaultargs")) {
+	Wrapper_print(w, f_directors);
+	Printv(f_directors_h, declaration, NIL);
+	Printv(f_directors_h, inline_extra_method, NIL);
+      }
+    }
+
+    /* clean up */
+    Delete(wrap_args);
+    Delete(return_type);
+    Delete(pclassname);
+    DelWrapper(w);
+    return status;
+  }
+
+  virtual int classDirectorConstructors(Node *n) {
+    return Language::classDirectorConstructors(n);
+  }
+
+  virtual int classDirectorMethods(Node *n) {
+    return Language::classDirectorMethods(n);
+  }
+
+  virtual int classDirectorDisown(Node *n) {
+    return Language::classDirectorDisown(n);
+  }
+
+  void typemap_copy_pname_to_lname(ParmList *parms) {
+    Parm *p;
+    String *pname;
+    String *lname;
+
+    p = parms;
+    while (p) {
+      pname = Getattr(p, "name");
+      lname = Copy(pname);
+      Setattr(p, "lname", lname);
+      p = nextSibling(p);
+    }
+  }
+
+  String *runtimeCode() {
+    String *s = NewString("");
+    String *shead = Swig_include_sys("rubyhead.swg");
+    if (!shead) {
+      Printf(stderr, "*** Unable to open 'rubyhead.swg'\n");
+    } else {
+      Append(s, shead);
+      Delete(shead);
+    }
+    String *serrors = Swig_include_sys("rubyerrors.swg");
+    if (!serrors) {
+      Printf(stderr, "*** Unable to open 'rubyerrors.swg'\n");
+    } else {
+      Append(s, serrors);
+      Delete(serrors);
+    }
+    String *strack = Swig_include_sys("rubytracking.swg");
+    if (!strack) {
+      Printf(stderr, "*** Unable to open 'rubytracking.swg'\n");
+    } else {
+      Append(s, strack);
+      Delete(strack);
+    }
+    String *sapi = Swig_include_sys("rubyapi.swg");
+    if (!sapi) {
+      Printf(stderr, "*** Unable to open 'rubyapi.swg'\n");
+    } else {
+      Append(s, sapi);
+      Delete(sapi);
+    }
+    String *srun = Swig_include_sys("rubyrun.swg");
+    if (!srun) {
+      Printf(stderr, "*** Unable to open 'rubyrun.swg'\n");
+    } else {
+      Append(s, srun);
+      Delete(srun);
+    }
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigrubyrun.h");
+  }
+};				/* class RUBY */
+
+/* -----------------------------------------------------------------------------
+ * swig_ruby()    - Instantiate module
+ * ----------------------------------------------------------------------------- */
+
+static Language *new_swig_ruby() {
+  return new RUBY();
+}
+extern "C" Language *swig_ruby(void) {
+  return new_swig_ruby();
+}
+
+
+/*
+ * Local Variables:
+ * c-basic-offset: 2
+ * End:
+ */
diff --git a/trunk/Source/Modules/s-exp.cxx b/trunk/Source/Modules/s-exp.cxx
new file mode 100644
index 0000000..b89b309
--- /dev/null
+++ b/trunk/Source/Modules/s-exp.cxx
@@ -0,0 +1,390 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * s-exp.cxx
+ *
+ * A parse tree represented as Lisp s-expressions.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_s_exp_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "dohint.h"
+
+static const char *usage = "\
+S-Exp Options (available with -sexp)\n\
+     -typemaplang <lang> - Typemap language\n\n";
+
+//static Node *view_top = 0;
+static File *out = 0;
+
+class Sexp:public Language {
+public:
+  int indent_level;
+   Sexp():indent_level(0) {
+  }
+  
+  virtual ~ Sexp() {
+  }
+
+  virtual void main(int argc, char *argv[]) {
+    SWIG_typemap_lang("sexp");
+    for (int iX = 0; iX < argc; iX++) {
+      if (strcmp(argv[iX], "-typemaplang") == 0) {
+	Swig_mark_arg(iX);
+	iX++;
+	SWIG_typemap_lang(argv[iX]);
+	Swig_mark_arg(iX);
+	continue;
+      }
+      if (strcmp(argv[iX], "-help") == 0) {
+	fputs(usage, stdout);
+      }
+    }
+
+    // Add a symbol to the parser for conditional compilation
+    Preprocessor_define("SWIGSEXP 1", 0);
+  }
+
+  DOHHash *print_circle_hash;
+  int print_circle_count;
+  int hanging_parens;
+  bool need_whitespace;
+  bool need_newline;
+
+  /* Top of the parse tree */
+  virtual int top(Node *n) {
+    if (out == 0) {
+      String *outfile = Getattr(n, "outfile");
+      Replaceall(outfile, "_wrap.cxx", ".lisp");
+      Replaceall(outfile, "_wrap.c", ".lisp");
+      out = NewFile(outfile, "w");
+      if (!out) {
+	FileErrorDisplay(outfile);
+	SWIG_exit(EXIT_FAILURE);
+      }
+    }
+    String *f_sink = NewString("");
+    Swig_register_filebyname("header", f_sink);
+    Swig_register_filebyname("wrapper", f_sink);
+    Swig_register_filebyname("runtime", f_sink);
+    Swig_register_filebyname("init", f_sink);
+
+    Language::top(n);
+    Printf(out, ";;; Lisp parse tree produced by SWIG\n");
+    print_circle_hash = DohNewHash();
+    print_circle_count = 0;
+    hanging_parens = 0;
+    need_whitespace = 0;
+    need_newline = 0;
+    Sexp_print_node(n);
+    flush_parens();
+    return SWIG_OK;
+  }
+
+  void print_indent() {
+    int i;
+    for (i = 0; i < indent_level; i++) {
+      Printf(out, " ");
+    }
+  }
+
+  void open_paren(const String *oper) {
+    flush_parens();
+    Printf(out, "(");
+    if (oper)
+      Printf(out, "%s ", oper);
+    indent_level += 2;
+  }
+
+  void close_paren(bool neednewline = false) {
+    hanging_parens++;
+    if (neednewline)
+      print_lazy_whitespace();
+    indent_level -= 2;
+  }
+
+  void flush_parens() {
+    int i;
+    if (hanging_parens) {
+      for (i = 0; i < hanging_parens; i++)
+	Printf(out, ")");
+      hanging_parens = 0;
+      need_newline = true;
+      need_whitespace = true;
+    }
+    if (need_newline) {
+      Printf(out, "\n");
+      print_indent();
+      need_newline = false;
+      need_whitespace = false;
+    } else if (need_whitespace) {
+      Printf(out, " ");
+      need_whitespace = false;
+    }
+  }
+
+  void print_lazy_whitespace() {
+    need_whitespace = 1;
+  }
+
+  void print_lazy_newline() {
+    need_newline = 1;
+  }
+
+  bool internal_key_p(DOH *key) {
+    return ((Cmp(key, "nodeType") == 0)
+	    || (Cmp(key, "firstChild") == 0)
+	    || (Cmp(key, "lastChild") == 0)
+	    || (Cmp(key, "parentNode") == 0)
+	    || (Cmp(key, "nextSibling") == 0)
+	    || (Cmp(key, "previousSibling") == 0)
+	    || (Cmp(key, "csym:nextSibling") == 0)
+	    || (Cmp(key, "csym:previousSibling") == 0)
+	    || (Cmp(key, "typepass:visit") == 0)
+	    || (Cmp(key, "allocate:visit") == 0)
+	    || (*(Char(key)) == '$'));
+  }
+
+  bool boolean_key_p(DOH *key) {
+    return ((Cmp(key, "allocate:default_constructor") == 0)
+	    || (Cmp(key, "allocate:default_destructor") == 0)
+	    || (Cmp(key, "allows_typedef") == 0)
+	    || (Cmp(key, "feature:immutable") == 0));
+  }
+
+  bool list_key_p(DOH *key) {
+    return ((Cmp(key, "parms") == 0)
+	    || (Cmp(key, "baselist") == 0));
+  }
+
+  bool plist_key_p(DOH *key)
+      // true if KEY is the name of data that is a mapping from keys to
+      // values, which should be printed as a plist.
+  {
+    return ((Cmp(key, "typescope") == 0));
+  }
+
+  bool maybe_plist_key_p(DOH *key) {
+    return (Strncmp(key, "tmap:", 5) == 0);
+  }
+
+  bool print_circle(DOH *obj, bool list_p)
+      // We have a complex object, which might be referenced several
+      // times, or even recursively.  Use Lisp's reader notation for
+      // circular structures (#n#, #n=).
+      //
+      // An object can be printed in list-mode or object-mode; LIST_P toggles.
+      // return TRUE if OBJ still needs to be printed
+  {
+    flush_parens();
+    // Following is a silly hack.  It works around the limitation of
+    // DOH's hash tables that only work with string keys!
+    char address[32];
+    sprintf(address, "%p%c", obj, list_p ? 'L' : 'O');
+    DOH *placeholder = Getattr(print_circle_hash, address);
+    if (placeholder) {
+      Printv(out, placeholder, NIL);
+      return false;
+    } else {
+      String *placeholder = NewStringf("#%d#", ++print_circle_count);
+      Setattr(print_circle_hash, address, placeholder);
+      Printf(out, "#%d=", print_circle_count);
+      return true;
+    }
+  }
+
+  void Sexp_print_value_of_key(DOH *value, DOH *key) {
+    if ((Cmp(key, "parms") == 0) || (Cmp(key, "wrap:parms") == 0)
+	|| (Cmp(key, "kwargs") == 0) || (Cmp(key, "pattern") == 0))
+      Sexp_print_parms(value);
+    else if (plist_key_p(key))
+      Sexp_print_plist(value);
+    else if (maybe_plist_key_p(key)) {
+      if (DohIsMapping(value))
+	Sexp_print_plist(value);
+      else
+	Sexp_print_doh(value);
+    } else if (list_key_p(key))
+      Sexp_print_list(value);
+    else if (boolean_key_p(key))
+      Sexp_print_boolean(value);
+    else
+      Sexp_print_doh(value);
+  }
+
+  void Sexp_print_boolean(DOH *obj) {
+    flush_parens();
+    /* See DOH/Doh/base.c, DohGetInt() */
+    if (DohIsString(obj)) {
+      if (atoi(Char(obj)) != 0)
+	Printf(out, "t");
+      else
+	Printf(out, "nil");
+    } else
+      Printf(out, "nil");
+  }
+
+  void Sexp_print_list(DOH *obj) {
+    if (print_circle(obj, true)) {
+      open_paren(NIL);
+      for (; obj; obj = nextSibling(obj)) {
+	Sexp_print_doh(obj);
+	print_lazy_whitespace();
+      }
+      close_paren(true);
+    }
+  }
+
+  void Sexp_print_parms(DOH *obj) {
+    // print it as a list of plists
+    if (print_circle(obj, true)) {
+      open_paren(NIL);
+      for (; obj; obj = nextSibling(obj)) {
+	if (DohIsMapping(obj)) {
+	  Iterator k;
+	  open_paren(NIL);
+	  for (k = First(obj); k.key; k = Next(k)) {
+	    if (!internal_key_p(k.key)) {
+	      DOH *value = Getattr(obj, k.key);
+	      Sexp_print_as_keyword(k.key);
+	      Sexp_print_value_of_key(value, k.key);
+	      print_lazy_whitespace();
+	    }
+	  }
+	  close_paren(true);
+	} else
+	  Sexp_print_doh(obj);
+	print_lazy_whitespace();
+      }
+      close_paren(true);
+    }
+  }
+
+  void Sexp_print_doh(DOH *obj) {
+    flush_parens();
+    if (DohIsString(obj)) {
+      String *o = Str(obj);
+      Replaceall(o, "\\", "\\\\");
+      Replaceall(o, "\"", "\\\"");
+      Printf(out, "\"%s\"", o);
+      Delete(o);
+    } else {
+      if (print_circle(obj, false)) {
+	// Dispatch type
+	if (nodeType(obj)) {
+	  Sexp_print_node(obj);
+	}
+
+	else if (DohIsMapping(obj)) {
+	  Iterator k;
+	  open_paren(NIL);
+	  for (k = First(obj); k.key; k = Next(k)) {
+	    if (!internal_key_p(k.key)) {
+	      DOH *value = Getattr(obj, k.key);
+	      flush_parens();
+	      open_paren(NIL);
+	      Sexp_print_doh(k.key);
+	      Printf(out, " . ");
+	      Sexp_print_value_of_key(value, k.key);
+	      close_paren();
+	    }
+	  }
+	  close_paren();
+	} else if (strcmp(ObjType(obj)->objname, "List") == 0) {
+	  int i;
+	  open_paren(NIL);
+	  for (i = 0; i < Len(obj); i++) {
+	    DOH *item = Getitem(obj, i);
+	    Sexp_print_doh(item);
+	  }
+	  close_paren();
+	} else {
+	  // What is it?
+	  Printf(out, "#<DOH %s %x>", ObjType(obj)->objname, obj);
+	}
+      }
+    }
+  }
+
+  void Sexp_print_as_keyword(const DOH *k) {
+    /* Print key, replacing ":" with "-" because : is CL's package prefix */
+    flush_parens();
+    String *key = NewString(k);
+    Replaceall(key, ":", "-");
+    Replaceall(key, "_", "-");
+    Printf(out, ":%s ", key);
+    Delete(key);
+  }
+
+  void Sexp_print_plist_noparens(DOH *obj) {
+    /* attributes map names to objects */
+    Iterator k;
+    bool first;
+    for (k = First(obj), first = true; k.key; k = Next(k), first = false) {
+      if (!internal_key_p(k.key)) {
+	DOH *value = Getattr(obj, k.key);
+	flush_parens();
+	if (!first) {
+	  Printf(out, " ");
+	}
+	Sexp_print_as_keyword(k.key);
+	/* Print value */
+	Sexp_print_value_of_key(value, k.key);
+      }
+    }
+  }
+
+  void Sexp_print_plist(DOH *obj) {
+    flush_parens();
+    if (print_circle(obj, true)) {
+      open_paren(NIL);
+      Sexp_print_plist_noparens(obj);
+      close_paren();
+    }
+  }
+
+  void Sexp_print_attributes(Node *obj) {
+    Sexp_print_plist_noparens(obj);
+  }
+
+  void Sexp_print_node(Node *obj) {
+    Node *cobj;
+    open_paren(nodeType(obj));
+    /* A node has an attribute list... */
+    Sexp_print_attributes(obj);
+    /* ... and child nodes. */
+    cobj = firstChild(obj);
+    if (cobj) {
+      print_lazy_newline();
+      flush_parens();
+      Sexp_print_as_keyword("children");
+      open_paren(NIL);
+      for (; cobj; cobj = nextSibling(cobj)) {
+	Sexp_print_node(cobj);
+      }
+      close_paren();
+    }
+    close_paren();
+  }
+
+
+  virtual int functionWrapper(Node *n) {
+    ParmList *l = Getattr(n, "parms");
+    Wrapper *f = NewWrapper();
+    emit_attach_parmmaps(l, f);
+    Setattr(n, "wrap:parms", l);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+};
+
+
+static Language *new_swig_sexp() {
+  return new Sexp();
+}
+extern "C" Language *swig_sexp(void) {
+  return new_swig_sexp();
+}
diff --git a/trunk/Source/Modules/swigmain.cxx b/trunk/Source/Modules/swigmain.cxx
new file mode 100644
index 0000000..3b60f22
--- /dev/null
+++ b/trunk/Source/Modules/swigmain.cxx
@@ -0,0 +1,202 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * Simplified Wrapper and Interface Generator  (SWIG)
+ *
+ * swigmain.cxx
+ *
+ * This file is the main entry point to SWIG.  It collects the command
+ * line options, registers built-in language modules, and instantiates
+ * a module for code generation.   If adding new language modules
+ * to SWIG, you would modify this file.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_swigmain_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include <ctype.h>
+
+/* Module factories.  These functions are used to instantiate
+   the built-in language modules.    If adding a new language
+   module to SWIG, place a similar function here. Make sure
+   the function has "C" linkage.  This is required so that modules
+   can be dynamically loaded in future versions. */
+
+extern "C" {
+  Language *swig_tcl(void);
+  Language *swig_python(void);
+  Language *swig_perl5(void);
+  Language *swig_ruby(void);
+  Language *swig_guile(void);
+  Language *swig_modula3(void);
+  Language *swig_mzscheme(void);
+  Language *swig_java(void);
+  Language *swig_php4(void);
+  Language *swig_php5(void);
+  Language *swig_ocaml(void);
+  Language *swig_octave(void);
+  Language *swig_pike(void);
+  Language *swig_sexp(void);
+  Language *swig_xml(void);
+  Language *swig_chicken(void);
+  Language *swig_csharp(void);
+  Language *swig_allegrocl(void);
+  Language *swig_lua(void);
+  Language *swig_clisp(void);
+  Language *swig_cffi(void);
+  Language *swig_uffi(void);
+  Language *swig_r(void);
+}
+
+struct swig_module {
+  const char *name;
+  ModuleFactory fac;
+  const char *help;
+};
+
+/* Association of command line options to language modules.
+   Place an entry for new language modules here, keeping the
+   list sorted alphabetically. */
+
+static swig_module modules[] = {
+  {"-allegrocl", swig_allegrocl, "ALLEGROCL"},
+  {"-chicken", swig_chicken, "CHICKEN"},
+  {"-clisp", swig_clisp, "CLISP"},
+  {"-cffi", swig_cffi, "CFFI"},
+  {"-csharp", swig_csharp, "C#"},
+  {"-guile", swig_guile, "Guile"},
+  {"-java", swig_java, "Java"},
+  {"-lua", swig_lua, "Lua"},
+  {"-modula3", swig_modula3, "Modula 3"},
+  {"-mzscheme", swig_mzscheme, "Mzscheme"},
+  {"-ocaml", swig_ocaml, "Ocaml"},
+  {"-octave", swig_octave, "Octave"},
+  {"-perl", swig_perl5, "Perl"},
+  {"-perl5", swig_perl5, 0},
+  {"-php", swig_php4, 0},
+  {"-php4", swig_php4, "PHP4"},
+  {"-php5", swig_php5, "PHP5"},
+  {"-pike", swig_pike, "Pike"},
+  {"-python", swig_python, "Python"},
+  {"-r", swig_r, "R (aka GNU S)"},
+  {"-ruby", swig_ruby, "Ruby"},
+  {"-sexp", swig_sexp, "Lisp S-Expressions"},
+  {"-tcl", swig_tcl, "Tcl"},
+  {"-tcl8", swig_tcl, 0},
+  {"-uffi", swig_uffi, "Common Lisp / UFFI"},
+  {"-xml", swig_xml, "XML"},
+  {NULL, NULL, NULL}
+};
+
+#ifdef MACSWIG
+#include <console.h>
+#include <SIOUX.h>
+#endif
+
+#ifndef SWIG_LANG
+#define SWIG_LANG "-python"
+#endif
+
+//-----------------------------------------------------------------
+// main()
+//
+// Main program.    Initializes the files and starts the parser.
+//-----------------------------------------------------------------
+
+void SWIG_merge_envopt(const char *env, int oargc, char *oargv[], int *nargc, char ***nargv) {
+  if (!env) {
+    *nargc = oargc;
+    *nargv = oargv;
+    return;
+  }
+
+  int argc = 1;
+  int arge = oargc + 1024;
+  char **argv = (char **) malloc(sizeof(char *) * (arge));
+  char *buffer = (char *) malloc(2048);
+  char *b = buffer;
+  char *be = b + 1023;
+  const char *c = env;
+  while ((b != be) && *c && (argc < arge)) {
+    while (isspace(*c) && *c)
+      ++c;
+    if (*c) {
+      argv[argc] = b;
+      ++argc;
+    }
+    while ((b != be) && *c && !isspace(*c)) {
+      *(b++) = *(c++);
+    }
+    *b++ = 0;
+  }
+
+  argv[0] = oargv[0];
+  for (int i = 1; (i < oargc) && (argc < arge); ++i, ++argc) {
+    argv[argc] = oargv[i];
+  }
+
+  *nargc = argc;
+  *nargv = argv;
+}
+
+int main(int margc, char **margv) {
+  int i;
+  Language *dl = 0;
+  ModuleFactory fac = 0;
+
+  int argc;
+  char **argv;
+
+  SWIG_merge_envopt(getenv("SWIG_FEATURES"), margc, margv, &argc, &argv);
+
+#ifdef MACSWIG
+  SIOUXSettings.asktosaveonclose = false;
+  argc = ccommand(&argv);
+#endif
+
+  /* Register built-in modules */
+  for (i = 0; modules[i].name; i++) {
+    Swig_register_module(modules[i].name, modules[i].fac);
+  }
+
+  Swig_init_args(argc, argv);
+
+  /* Get options */
+  for (i = 1; i < argc; i++) {
+    if (argv[i]) {
+      fac = Swig_find_module(argv[i]);
+      if (fac) {
+	dl = (fac) ();
+	Swig_mark_arg(i);
+      } else if (strcmp(argv[i], "-nolang") == 0) {
+	dl = new Language;
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-dnone") == 0) ||
+		 (strcmp(argv[i], "-dhtml") == 0) ||
+		 (strcmp(argv[i], "-dlatex") == 0) || (strcmp(argv[i], "-dascii") == 0) || (strcmp(argv[i], "-stat") == 0)) {
+	Printf(stderr, "swig: Warning. %s option deprecated.\n", argv[i]);
+	Swig_mark_arg(i);
+      } else if ((strcmp(argv[i], "-help") == 0) || (strcmp(argv[i], "--help") == 0)) {
+	if (strcmp(argv[i], "--help") == 0)
+	  strcpy(argv[i], "-help");
+	Printf(stdout, "Target Language Options\n");
+	for (int j = 0; modules[j].name; j++) {
+	  if (modules[j].help) {
+	    Printf(stdout, "     %-15s - Generate %s wrappers\n", modules[j].name, modules[j].help);
+	  }
+	}
+	// Swig_mark_arg not called as the general -help options also need to be displayed later on
+      }
+    }
+  }
+  if (!dl) {
+    fac = Swig_find_module(SWIG_LANG);
+    if (fac) {
+      dl = (fac) ();
+    }
+  }
+  int res = SWIG_main(argc, argv, dl);
+  delete dl;
+  return res;
+}
diff --git a/trunk/Source/Modules/swigmod.h b/trunk/Source/Modules/swigmod.h
new file mode 100644
index 0000000..5835c63
--- /dev/null
+++ b/trunk/Source/Modules/swigmod.h
@@ -0,0 +1,381 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigmod.h
+ *
+ * Main header file for SWIG modules.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id$ */
+
+#ifndef SWIG_SWIGMOD_H_
+#define SWIG_SWIGMOD_H_
+
+#include "swig.h"
+#include "preprocessor.h"
+#include "swigwarn.h"
+
+#if !defined(HAVE_BOOL)
+typedef int bool;
+#define true ((bool)1)
+#define false ((bool)0)
+#endif
+
+#define NOT_VIRTUAL     0
+#define PLAIN_VIRTUAL   1
+#define PURE_VIRTUAL    2
+
+extern char *input_file;
+extern int line_number;
+extern int start_line;
+extern int CPlusPlus;		// C++ mode
+extern int Extend;		// Extend mode
+extern int Verbose;
+extern int IsVirtual;
+extern int ImportMode;
+extern int NoExcept;		// -no_except option
+extern int Abstract;		// abstract base class
+extern int SmartPointer;	// smart pointer methods being emitted
+extern int SwigRuntime;
+
+/* Overload "argc" and "argv" */
+extern String *argv_template_string;
+extern String *argc_template_string;
+
+/* Miscellaneous stuff */
+
+#define  tab2   "  "
+#define  tab4   "    "
+#define  tab8   "        "
+
+class Dispatcher {
+public:
+
+  Dispatcher ():cplus_mode(PUBLIC) {
+  }
+  virtual ~ Dispatcher () {
+  }
+
+  virtual int emit_one(Node *n);
+  virtual int emit_children(Node *n);
+  virtual int defaultHandler(Node *n);
+
+  /* Top of the parse tree */
+  virtual int top(Node *n) = 0;
+
+  /* SWIG directives */
+
+  virtual int applyDirective(Node *n);
+  virtual int clearDirective(Node *n);
+  virtual int constantDirective(Node *n);
+  virtual int extendDirective(Node *n);
+  virtual int fragmentDirective(Node *n);
+  virtual int importDirective(Node *n);
+  virtual int includeDirective(Node *n);
+  virtual int insertDirective(Node *n);
+  virtual int moduleDirective(Node *n);
+  virtual int nativeDirective(Node *n);
+  virtual int pragmaDirective(Node *n);
+  virtual int typemapDirective(Node *n);
+  virtual int typemapitemDirective(Node *n);
+  virtual int typemapcopyDirective(Node *n);
+  virtual int typesDirective(Node *n);
+
+  /* C/C++ parsing */
+
+  virtual int cDeclaration(Node *n);
+  virtual int externDeclaration(Node *n);
+  virtual int enumDeclaration(Node *n);
+  virtual int enumvalueDeclaration(Node *n);
+  virtual int enumforwardDeclaration(Node *n);
+  virtual int classDeclaration(Node *n);
+  virtual int classforwardDeclaration(Node *n);
+  virtual int constructorDeclaration(Node *n);
+  virtual int destructorDeclaration(Node *n);
+  virtual int accessDeclaration(Node *n);
+  virtual int usingDeclaration(Node *n);
+  virtual int namespaceDeclaration(Node *n);
+  virtual int templateDeclaration(Node *n);
+
+  enum AccessMode { PUBLIC, PRIVATE, PROTECTED };
+
+protected:
+  AccessMode cplus_mode;
+};
+
+/* ----------------------------------------------------------------------------
+ * class language:
+ *
+ * This class defines the functions that need to be supported by the
+ * scripting language being used.    The translator calls these virtual
+ * functions to output different types of code for different languages.
+ * ------------------------------------------------------------------------- */
+
+class Language:public Dispatcher {
+public:
+  Language ();
+   virtual ~ Language ();
+  virtual int emit_one(Node *n);
+
+  /* Parse command line options */
+
+  virtual void main(int argc, char *argv[]);
+
+  /* Top of the parse tree */
+
+  virtual int top(Node *n);
+
+  /* SWIG directives */
+
+
+  virtual int applyDirective(Node *n);
+  virtual int clearDirective(Node *n);
+  virtual int constantDirective(Node *n);
+  virtual int extendDirective(Node *n);
+  virtual int fragmentDirective(Node *n);
+  virtual int importDirective(Node *n);
+  virtual int includeDirective(Node *n);
+  virtual int insertDirective(Node *n);
+  virtual int moduleDirective(Node *n);
+  virtual int nativeDirective(Node *n);
+  virtual int pragmaDirective(Node *n);
+  virtual int typemapDirective(Node *n);
+  virtual int typemapcopyDirective(Node *n);
+  virtual int typesDirective(Node *n);
+
+  /* C/C++ parsing */
+
+  virtual int cDeclaration(Node *n);
+  virtual int externDeclaration(Node *n);
+  virtual int enumDeclaration(Node *n);
+  virtual int enumvalueDeclaration(Node *n);
+  virtual int enumforwardDeclaration(Node *n);
+  virtual int classDeclaration(Node *n);
+  virtual int classforwardDeclaration(Node *n);
+  virtual int constructorDeclaration(Node *n);
+  virtual int destructorDeclaration(Node *n);
+  virtual int accessDeclaration(Node *n);
+  virtual int namespaceDeclaration(Node *n);
+  virtual int usingDeclaration(Node *n);
+
+  /* Function handlers */
+
+  virtual int functionHandler(Node *n);
+  virtual int globalfunctionHandler(Node *n);
+  virtual int memberfunctionHandler(Node *n);
+  virtual int staticmemberfunctionHandler(Node *n);
+  virtual int callbackfunctionHandler(Node *n);
+
+  /* Variable handlers */
+
+  virtual int variableHandler(Node *n);
+  virtual int globalvariableHandler(Node *n);
+  virtual int membervariableHandler(Node *n);
+  virtual int staticmembervariableHandler(Node *n);
+
+  /* C++ handlers */
+
+  virtual int memberconstantHandler(Node *n);
+  virtual int constructorHandler(Node *n);
+  virtual int copyconstructorHandler(Node *n);
+  virtual int destructorHandler(Node *n);
+  virtual int classHandler(Node *n);
+
+  /* Miscellaneous */
+
+  virtual int typedefHandler(Node *n);
+
+  /* Low-level code generation */
+
+  virtual int constantWrapper(Node *n);
+  virtual int variableWrapper(Node *n);
+  virtual int functionWrapper(Node *n);
+  virtual int nativeWrapper(Node *n);
+
+  /* C++ director class generation */
+  virtual int classDirector(Node *n);
+  virtual int classDirectorInit(Node *n);
+  virtual int classDirectorEnd(Node *n);
+  virtual int unrollVirtualMethods(Node *n, Node *parent, List *vm, int default_director, int &virtual_destructor, int protectedbase = 0);
+  virtual int classDirectorConstructor(Node *n);
+  virtual int classDirectorDefaultConstructor(Node *n);
+  virtual int classDirectorMethod(Node *n, Node *parent, String *super);
+  virtual int classDirectorConstructors(Node *n);
+  virtual int classDirectorDestructor(Node *n);
+  virtual int classDirectorMethods(Node *n);
+  virtual int classDirectorDisown(Node *n);
+
+  /* Miscellaneous */
+  virtual int validIdentifier(String *s);	/* valid identifier? */
+  virtual int addSymbol(const String *s, const Node *n);	/* Add symbol        */
+  virtual Node *symbolLookup(String *s);	/* Symbol lookup     */
+  virtual Node *classLookup(SwigType *s);	/* Class lookup      */
+  virtual Node *enumLookup(SwigType *s);	/* Enum lookup       */
+  virtual int abstractClassTest(Node *n);	/* Is class really abstract? */
+  virtual int is_assignable(Node *n);	/* Is variable assignable? */
+  virtual String *runtimeCode();	/* returns the language specific runtime code */
+  virtual String *defaultExternalRuntimeFilename();	/* the default filename for the external runtime */
+
+  /* Runtime is C++ based, so extern "C" header section */
+  void enable_cplus_runtime_mode();
+
+  /* Returns the cplus_runtime mode */
+  int cplus_runtime_mode();
+
+  /* Allow director related code generation */
+  void allow_directors(int val = 1);
+
+  /* Return true if directors are enabled */
+  int directorsEnabled() const;
+
+  /* Allow director protected members related code generation */
+  void allow_dirprot(int val = 1);
+
+  /* Allow all protected members code generation (for directors) */
+  void allow_allprotected(int val = 0);
+
+  /* Returns the dirprot mode */
+  int dirprot_mode() const;
+
+  /* Check if the non public constructor is  needed (for directors) */
+  int need_nonpublic_ctor(Node *n);
+
+  /* Check if the non public member is  needed (for directors) */
+  int need_nonpublic_member(Node *n);
+
+  /* Set none comparison string */
+  void setSubclassInstanceCheck(String *s);
+
+  /* Set overload variable templates argc and argv */
+  void setOverloadResolutionTemplates(String *argc, String *argv);
+
+protected:
+  /* Allow multiple-input typemaps */
+  void allow_multiple_input(int val = 1);
+
+  /* Allow overloaded functions */
+  void allow_overloading(int val = 1);
+
+  /* Wrapping class query */
+  int is_wrapping_class();
+
+  /* Return the node for the current class */
+  Node *getCurrentClass() const;
+
+  /* Return C++ mode */
+  int getCPlusMode() const;
+
+  /* Return the real name of the current class */
+  String *getClassName() const;
+
+  /* Return the classes hash */
+  Hash *getClassHash() const;
+
+  /* Return the current class prefix */
+  String *getClassPrefix() const;
+
+  /* Fully qualified type name to use */
+  String *getClassType() const;
+
+  /* Return true if the current method is part of a smart-pointer */
+  int is_smart_pointer() const;
+
+  /* Some language modules require additional wrappers for virtual methods not declared in sub-classes */
+  virtual bool extraDirectorProtectedCPPMethodsRequired() const;
+
+  /* Director subclass comparison test */
+  String *none_comparison;
+
+  /* Director constructor "template" code */
+  String *director_ctor_code;
+
+  /* Director 'protected' constructor "template" code */
+  String *director_prot_ctor_code;
+
+  /* Director allows multiple inheritance */
+  int director_multiple_inheritance;
+
+  /* Director language module */
+  int director_language;
+
+private:
+  Hash *symbols;
+  Hash *classtypes;
+  Hash *enumtypes;
+  int overloading;
+  int multiinput;
+  int cplus_runtime;
+  int directors;
+};
+
+int SWIG_main(int, char **, Language *);
+void emit_parameter_variables(ParmList *l, Wrapper *f);
+void emit_return_variable(Node *n, SwigType *rt, Wrapper *f);
+void SWIG_exit(int);		/* use EXIT_{SUCCESS,FAILURE} */
+void SWIG_config_file(const String_or_char *);
+const String *SWIG_output_directory();
+void SWIG_config_cppext(const char *ext);
+
+void SWIG_library_directory(const char *);
+int emit_num_arguments(ParmList *);
+int emit_num_required(ParmList *);
+int emit_isvarargs(ParmList *);
+void emit_attach_parmmaps(ParmList *, Wrapper *f);
+void emit_mark_varargs(ParmList *l);
+String *emit_action(Node *n);
+int emit_action_code(Node *n, String *wrappercode, String *action);
+void Swig_overload_check(Node *n);
+String *Swig_overload_dispatch(Node *n, const String_or_char *fmt, int *);
+String *Swig_overload_dispatch_cast(Node *n, const String_or_char *fmt, int *);
+String *Swig_overload_dispatch_fast(Node *n, const String_or_char *fmt, int *);
+SwigType *cplus_value_type(SwigType *t);
+
+/* directors.cxx start */
+String *Swig_csuperclass_call(String *base, String *method, ParmList *l);
+String *Swig_class_declaration(Node *n, String *name);
+String *Swig_class_name(Node *n);
+String *Swig_method_call(String_or_char *name, ParmList *parms);
+String *Swig_method_decl(SwigType *rtype, SwigType *decl, const String_or_char *id, List *args, int strip, int values);
+String *Swig_director_declaration(Node *n);
+void Swig_director_emit_dynamic_cast(Node *n, Wrapper *f);
+/* directors.cxx end */
+
+extern "C" {
+  void SWIG_typemap_lang(const char *);
+  typedef Language *(*ModuleFactory) (void);
+} void Swig_register_module(const char *name, ModuleFactory fac);
+ModuleFactory Swig_find_module(const char *name);
+
+/* Utilities */
+
+int is_public(Node *n);
+int is_private(Node *n);
+int is_protected(Node *n);
+int is_member_director(Node *parentnode, Node *member);
+int is_member_director(Node *member);
+int is_non_virtual_protected_access(Node *n); /* Check if the non-virtual protected members are required (for directors) */
+int use_naturalvar_mode(Node *n);
+
+void Wrapper_virtual_elimination_mode_set(int);
+void Wrapper_fast_dispatch_mode_set(int);
+void Wrapper_cast_dispatch_mode_set(int);
+void Wrapper_naturalvar_mode_set(int);
+
+
+void clean_overloaded(Node *n);
+
+/* Contracts */
+
+void Swig_contracts(Node *n);
+void Swig_contract_mode_set(int flag);
+int Swig_contract_mode_get();
+
+/* Browser */
+
+void Swig_browser(Node *n, int);
+void Swig_default_allocators(Node *n);
+void Swig_process_types(Node *n);
+
+
+#endif
diff --git a/trunk/Source/Modules/tcl8.cxx b/trunk/Source/Modules/tcl8.cxx
new file mode 100644
index 0000000..09bd266
--- /dev/null
+++ b/trunk/Source/Modules/tcl8.cxx
@@ -0,0 +1,1298 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tcl8.cxx
+ *
+ * Tcl8 language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_tcl8_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+static int treduce = SWIG_cparse_template_reduce(0);
+
+static const char *usage = (char *) "\
+Tcl 8 Options (available with -tcl)\n\
+     -itcl           - Enable ITcl support\n\
+     -nosafe         - Leave out SafeInit module function.\n\
+     -prefix <name>  - Set a prefix <name> to be prepended to all names\n\
+     -namespace      - Build module into a Tcl 8 namespace\n\
+     -pkgversion     - Set package version\n\n";
+
+static String *cmd_tab = 0;	/* Table of command names    */
+static String *var_tab = 0;	/* Table of global variables */
+static String *const_tab = 0;	/* Constant table            */
+static String *methods_tab = 0;	/* Methods table             */
+static String *attr_tab = 0;	/* Attribute table           */
+static String *prefix = 0;
+static String *module = 0;
+static int nspace = 0;
+static String *init_name = 0;
+static String *ns_name = 0;
+static int have_constructor;
+static String *constructor_name;
+static int have_destructor;
+static int have_base_classes;
+static String *destructor_action = 0;
+static String *version = (String *) "0.0";
+static String *class_name = 0;
+
+static int have_attributes;
+static int have_methods;
+static int nosafe = 0;
+
+static File *f_header = 0;
+static File *f_wrappers = 0;
+static File *f_init = 0;
+static File *f_runtime = 0;
+
+
+//  Itcl support
+static int itcl = 0;
+static File *f_shadow = 0;
+static File *f_shadow_stubs = 0;
+
+static String *constructor = 0;
+static String *destructor = 0;
+static String *base_classes = 0;
+static String *base_class_init = 0;
+static String *methods = 0;
+static String *imethods = 0;
+static String *attributes = 0;
+static String *attribute_traces = 0;
+static String *iattribute_traces = 0;
+
+
+
+class TCL8:public Language {
+public:
+
+  /* ------------------------------------------------------------
+   * TCL8::main()
+   * ------------------------------------------------------------ */
+
+  virtual void main(int argc, char *argv[]) {
+    int cppcast = 1;
+
+     SWIG_library_directory("tcl");
+
+    for (int i = 1; i < argc; i++) {
+      if (argv[i]) {
+	if (strcmp(argv[i], "-prefix") == 0) {
+	  if (argv[i + 1]) {
+	    prefix = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  } else
+	     Swig_arg_error();
+	} else if (strcmp(argv[i], "-pkgversion") == 0) {
+	  if (argv[i + 1]) {
+	    version = NewString(argv[i + 1]);
+	    Swig_mark_arg(i);
+	    Swig_mark_arg(i + 1);
+	    i++;
+	  }
+	} else if (strcmp(argv[i], "-namespace") == 0) {
+	  nspace = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-itcl") == 0) {
+	  itcl = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nosafe") == 0) {
+	  nosafe = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-cppcast") == 0) {
+	  cppcast = 1;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-nocppcast") == 0) {
+	  cppcast = 0;
+	  Swig_mark_arg(i);
+	} else if (strcmp(argv[i], "-help") == 0) {
+	  fputs(usage, stdout);
+	}
+      }
+    }
+
+    if (cppcast) {
+      Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
+    }
+
+    Preprocessor_define("SWIGTCL 1", 0);
+    Preprocessor_define("SWIGTCL8 1", 0);
+    SWIG_typemap_lang("tcl8");
+    SWIG_config_file("tcl8.swg");
+    allow_overloading();
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+
+    /* Initialize all of the output files */
+    String *outfile = Getattr(n, "outfile");
+
+    f_runtime = NewFile(outfile, "w");
+    if (!f_runtime) {
+      FileErrorDisplay(outfile);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    f_init = NewString("");
+    f_header = NewString("");
+    f_wrappers = NewString("");
+
+    /* Register file targets with the SWIG file handler */
+    Swig_register_filebyname("header", f_header);
+    Swig_register_filebyname("wrapper", f_wrappers);
+    Swig_register_filebyname("runtime", f_runtime);
+    Swig_register_filebyname("init", f_init);
+
+    /* Initialize some variables for the object interface */
+
+    cmd_tab = NewString("");
+    var_tab = NewString("");
+    methods_tab = NewString("");
+    const_tab = NewString("");
+
+    Swig_banner(f_runtime);
+
+    /* Set the module name, namespace, and prefix */
+
+    module = NewStringf("%(lower)s", Getattr(n, "name"));
+    init_name = NewStringf("%(title)s_Init", module);
+
+    ns_name = prefix ? Copy(prefix) : Copy(module);
+    if (prefix)
+      Append(prefix, "_");
+
+
+    /* If shadow classing is enabled, we're going to change the module name to "_module" */
+    if (itcl) {
+      String *filen;
+      filen = NewStringf("%s%s.itcl", Swig_file_dirname(outfile), module);
+
+      Insert(module, 0, "_");
+
+      if ((f_shadow = NewFile(filen, "w")) == 0) {
+	FileErrorDisplay(filen);
+	SWIG_exit(EXIT_FAILURE);
+      }
+      f_shadow_stubs = NewString("");
+
+      Swig_register_filebyname("shadow", f_shadow);
+      Swig_register_filebyname("itcl", f_shadow);
+
+      Printf(f_shadow, "# This file was automatically generated by SWIG (http://www.swig.org).\n");
+      Printf(f_shadow, "# Version %s\n", Swig_package_version());
+      Printf(f_shadow, "#\n");
+      Printf(f_shadow, "# Don't modify this file, modify the SWIG interface instead.\n");
+
+      Printv(f_shadow, "\npackage require Itcl\n\n", NIL);
+      Delete(filen);
+    }
+
+    /* Generate some macros used throughout code generation */
+
+    Printf(f_header, "#define SWIG_init    %s\n", init_name);
+    Printf(f_header, "#define SWIG_name    \"%s\"\n", module);
+    if (nspace) {
+      Printf(f_header, "#define SWIG_prefix  \"%s::\"\n", ns_name);
+      Printf(f_header, "#define SWIG_namespace \"%s\"\n\n", ns_name);
+    } else {
+      Printf(f_header, "#define SWIG_prefix  \"%s\"\n", prefix);
+    }
+    Printf(f_header, "#define SWIG_version \"%s\"\n", version);
+
+    Printf(cmd_tab, "\nstatic swig_command_info swig_commands[] = {\n");
+    Printf(var_tab, "\nstatic swig_var_info swig_variables[] = {\n");
+    Printf(const_tab, "\nstatic swig_const_info swig_constants[] = {\n");
+
+    Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
+
+    /* Start emitting code */
+    Language::top(n);
+
+    /* Done.  Close up the module */
+    Printv(cmd_tab, tab4, "{0, 0, 0}\n", "};\n", NIL);
+    Printv(var_tab, tab4, "{0,0,0,0}\n", "};\n", NIL);
+    Printv(const_tab, tab4, "{0,0,0,0,0,0}\n", "};\n", NIL);
+
+    Printv(f_wrappers, cmd_tab, var_tab, const_tab, NIL);
+
+    /* Dump the pointer equivalency table */
+    SwigType_emit_type_table(f_runtime, f_wrappers);
+
+    Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n");
+
+    /* Close the init function and quit */
+    Printf(f_init, "return TCL_OK;\n}\n");
+
+    if (!nosafe) {
+      Printf(f_init, "SWIGEXPORT int %(title)s_SafeInit(Tcl_Interp *interp) {\n", module);
+      Printf(f_init, "    return SWIG_init(interp);\n");
+      Printf(f_init, "}\n");
+    }
+
+    if (itcl) {
+      Printv(f_shadow, f_shadow_stubs, "\n", NIL);
+      Close(f_shadow);
+      Delete(f_shadow);
+    }
+
+    /* Close all of the files */
+    Printv(f_runtime, f_header, f_wrappers, NIL);
+    Wrapper_pretty_print(f_init, f_runtime);
+    Delete(f_header);
+    Delete(f_wrappers);
+    Delete(f_init);
+    Close(f_runtime);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * functionWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int functionWrapper(Node *n) {
+    String *name = Getattr(n, "name");	/* Like to get rid of this */
+    String *iname = Getattr(n, "sym:name");
+    SwigType *type = Getattr(n, "type");
+    ParmList *parms = Getattr(n, "parms");
+    String *overname = 0;
+
+    Parm *p;
+    int i;
+    String *tm;
+    Wrapper *f;
+    String *incode, *cleanup, *outarg, *argstr, *args;
+    int num_arguments = 0;
+    int num_required = 0;
+    int varargs = 0;
+
+    char source[64];
+
+    if (Getattr(n, "sym:overloaded")) {
+      overname = Getattr(n, "sym:overname");
+    } else {
+      if (!addSymbol(iname, n))
+	return SWIG_ERROR;
+    }
+
+    incode = NewString("");
+    cleanup = NewString("");
+    outarg = NewString("");
+    argstr = NewString("\"");
+    args = NewString("");
+
+    f = NewWrapper();
+
+#ifdef SWIG_USE_RESULTOBJ
+    Wrapper_add_local(f, "resultobj", "Tcl_Obj *resultobj = NULL");
+#endif
+
+
+    String *wname = Swig_name_wrapper(iname);
+    if (overname) {
+      Append(wname, overname);
+    }
+    Setattr(n, "wrap:name", wname);
+
+    Printv(f->def, "SWIGINTERN int\n ", wname, "(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {", NIL);
+
+    // Emit all of the local variables for holding arguments.
+    emit_parameter_variables(parms, f);
+
+    /* Attach standard typemaps */
+    emit_attach_parmmaps(parms, f);
+    Setattr(n, "wrap:parms", parms);
+
+    /* Get number of require and total arguments */
+    num_arguments = emit_num_arguments(parms);
+    num_required = emit_num_required(parms);
+    varargs = emit_isvarargs(parms);
+
+    /* Unmarshal parameters */
+
+    for (i = 0, p = parms; i < num_arguments; i++) {
+      /* Skip ignored arguments */
+
+      while (checkAttribute(p, "tmap:in:numinputs", "0")) {
+	p = Getattr(p, "tmap:in:next");
+      }
+
+      SwigType *pt = Getattr(p, "type");
+      String *ln = Getattr(p, "lname");
+
+      /* Produce string representations of the source and target arguments */
+      sprintf(source, "objv[%d]", i + 1);
+
+      if (i == num_required)
+	Putc('|', argstr);
+      if ((tm = Getattr(p, "tmap:in"))) {
+	String *parse = Getattr(p, "tmap:in:parse");
+	if (!parse) {
+	  Replaceall(tm, "$target", ln);
+	  Replaceall(tm, "$source", source);
+	  Replaceall(tm, "$input", source);
+	  Setattr(p, "emit:input", source);
+
+	  if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
+	    Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
+	  } else {
+	    Replaceall(tm, "$disown", "0");
+	  }
+
+	  Putc('o', argstr);
+	  Printf(args, ",(void *)0");
+	  if (i >= num_required) {
+	    Printf(incode, "if (objc > %d) {\n", i + 1);
+	  }
+	  Printf(incode, "%s\n", tm);
+	  if (i >= num_required) {
+	    Printf(incode, "}\n");
+	  }
+	} else {
+	  Printf(argstr, "%s", parse);
+	  Printf(args, ",&%s", ln);
+	  if (Strcmp(parse, "p") == 0) {
+	    SwigType *lt = SwigType_ltype(pt);
+	    SwigType_remember(pt);
+	    if (Cmp(lt, "p.void") == 0) {
+	      Printf(args, ",(void *)0");
+	    } else {
+	      Printf(args, ",SWIGTYPE%s", SwigType_manglestr(pt));
+	    }
+	    Delete(lt);
+	  }
+	}
+	p = Getattr(p, "tmap:in:next");
+	continue;
+      } else {
+	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
+      }
+      p = nextSibling(p);
+    }
+
+    if (!varargs) {
+      Putc(':', argstr);
+    } else {
+      Putc(';', argstr);
+      /* If variable length arguments we need to emit the in typemap here */
+      if (p && (tm = Getattr(p, "tmap:in"))) {
+	sprintf(source, "objv[%d]", i + 1);
+	Printf(incode, "if (objc > %d) {\n", i);
+	Replaceall(tm, "$input", source);
+	Printv(incode, tm, "\n", NIL);
+	Printf(incode, "}\n");
+      }
+    }
+
+    Printf(argstr, "%s\"", usage_string(Char(iname), type, parms));
+
+    Printv(f->code, "if (SWIG_GetArgs(interp, objc, objv,", argstr, args, ") == TCL_ERROR) SWIG_fail;\n", NIL);
+
+    Printv(f->code, incode, NIL);
+
+    /* Insert constraint checking code */
+    for (p = parms; p;) {
+      if ((tm = Getattr(p, "tmap:check"))) {
+	Replaceall(tm, "$target", Getattr(p, "lname"));
+	Printv(f->code, tm, "\n", NIL);
+	p = Getattr(p, "tmap:check:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert cleanup code */
+    for (i = 0, p = parms; p; i++) {
+      if (!checkAttribute(p, "tmap:in:numinputs", "0")
+	  && !Getattr(p, "tmap:in:parse") && (tm = Getattr(p, "tmap:freearg"))) {
+	if (Len(tm) != 0) {
+	  Replaceall(tm, "$source", Getattr(p, "lname"));
+	  Printv(cleanup, tm, "\n", NIL);
+	}
+	p = Getattr(p, "tmap:freearg:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Insert argument output code */
+    for (i = 0, p = parms; p; i++) {
+      if ((tm = Getattr(p, "tmap:argout"))) {
+	Replaceall(tm, "$source", Getattr(p, "lname"));
+#ifdef SWIG_USE_RESULTOBJ
+	Replaceall(tm, "$target", "resultobj");
+	Replaceall(tm, "$result", "resultobj");
+#else
+	Replaceall(tm, "$target", "(Tcl_GetObjResult(interp))");
+	Replaceall(tm, "$result", "(Tcl_GetObjResult(interp))");
+#endif
+	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
+	Replaceall(tm, "$input", Getattr(p, "emit:input"));
+	Printv(outarg, tm, "\n", NIL);
+	p = Getattr(p, "tmap:argout:next");
+      } else {
+	p = nextSibling(p);
+      }
+    }
+
+    /* Now write code to make the function call */
+    String *actioncode = emit_action(n);
+
+    /* Need to redo all of this code (eventually) */
+
+    /* Return value if necessary  */
+    if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
+      Replaceall(tm, "$source", "result");
+#ifdef SWIG_USE_RESULTOBJ
+      Replaceall(tm, "$target", "resultobj");
+      Replaceall(tm, "$result", "resultobj");
+#else
+      Replaceall(tm, "$target", "(Tcl_GetObjResult(interp))");
+      Replaceall(tm, "$result", "(Tcl_GetObjResult(interp))");
+#endif
+      if (GetFlag(n, "feature:new")) {
+	Replaceall(tm, "$owner", "SWIG_POINTER_OWN");
+      } else {
+	Replaceall(tm, "$owner", "0");
+      }
+      Printf(f->code, "%s\n", tm);
+    } else {
+      Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), name);
+    }
+    emit_return_variable(n, type, f);
+
+    /* Dump output argument code */
+    Printv(f->code, outarg, NIL);
+
+    /* Dump the argument cleanup code */
+    Printv(f->code, cleanup, NIL);
+
+    /* Look for any remaining cleanup */
+    if (GetFlag(n, "feature:new")) {
+      if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
+	Replaceall(tm, "$source", "result");
+	Printf(f->code, "%s\n", tm);
+      }
+    }
+
+    if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
+      Replaceall(tm, "$source", "result");
+      Printf(f->code, "%s\n", tm);
+    }
+#ifdef SWIG_USE_RESULTOBJ
+    Printv(f->code, "if (resultobj) Tcl_SetObjResult(interp, resultobj);\n", NIL);
+#endif
+    Printv(f->code, "return TCL_OK;\n", NIL);
+    Printv(f->code, "fail:\n", cleanup, "return TCL_ERROR;\n", NIL);
+    Printv(f->code, "}\n", NIL);
+
+    /* Substitute the cleanup code */
+    Replaceall(f->code, "$cleanup", cleanup);
+    Replaceall(f->code, "$symname", iname);
+
+    /* Dump out the function */
+    Wrapper_print(f, f_wrappers);
+
+    if (!Getattr(n, "sym:overloaded")) {
+      /* Register the function with Tcl */
+      Printv(cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", Swig_name_wrapper(iname), ", NULL},\n", NIL);
+    } else {
+      if (!Getattr(n, "sym:nextSibling")) {
+	/* Emit overloading dispatch function */
+
+	int maxargs;
+	String *dispatch = Swig_overload_dispatch(n, "return %s(clientData, interp, objc, argv - 1);", &maxargs);
+
+	/* Generate a dispatch wrapper for all overloaded functions */
+
+	Wrapper *df = NewWrapper();
+	String *dname = Swig_name_wrapper(iname);
+
+	Printv(df->def, "SWIGINTERN int\n", dname, "(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {", NIL);
+	Printf(df->code, "Tcl_Obj *CONST *argv = objv+1;\n");
+	Printf(df->code, "int argc = objc-1;\n");
+	Printv(df->code, dispatch, "\n", NIL);
+	Printf(df->code, "Tcl_SetResult(interp,(char *) \"No matching function for overloaded '%s'\", TCL_STATIC);\n", iname);
+	Printf(df->code, "return TCL_ERROR;\n");
+	Printv(df->code, "}\n", NIL);
+	Wrapper_print(df, f_wrappers);
+	Printv(cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", dname, ", NULL},\n", NIL);
+	DelWrapper(df);
+	Delete(dispatch);
+	Delete(dname);
+      }
+    }
+
+    Delete(incode);
+    Delete(cleanup);
+    Delete(outarg);
+    Delete(argstr);
+    Delete(args);
+    DelWrapper(f);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * variableWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int variableWrapper(Node *n) {
+
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    SwigType *t = Getattr(n, "type");
+
+    String *setname = 0;
+    String *setfname = 0;
+    Wrapper *setf = 0, *getf = 0;
+    int readonly = 0;
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+
+    /* Create a function for getting a variable */
+    int addfail = 0;
+    getf = NewWrapper();
+    String *getname = Swig_name_get(iname);
+    String *getfname = Swig_name_wrapper(getname);
+    Setattr(n, "wrap:name", getfname);
+    Printv(getf->def, "SWIGINTERN const char *", getfname, "(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, char *name1, char *name2, int flags) {", NIL);
+    Wrapper_add_local(getf, "value", "Tcl_Obj *value = 0");
+    if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
+      Replaceall(tm, "$source", name);
+      Replaceall(tm, "$target", "value");
+      Replaceall(tm, "$result", "value");
+      /* Printf(getf->code, "%s\n",tm); */
+      addfail = emit_action_code(n, getf->code, tm);
+      Printf(getf->code, "if (value) {\n");
+      Printf(getf->code, "Tcl_SetVar2(interp,name1,name2,Tcl_GetStringFromObj(value,NULL), flags);\n");
+      Printf(getf->code, "Tcl_DecrRefCount(value);\n");
+      Printf(getf->code, "}\n");
+      Printf(getf->code, "return NULL;\n");
+      if (addfail) {
+	Append(getf->code, "fail:\n");
+	Printf(getf->code, "return \"%s\";\n", iname);
+      }
+      Printf(getf->code, "}\n");
+      Wrapper_print(getf, f_wrappers);
+    } else {
+      Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
+      DelWrapper(getf);
+      return SWIG_NOWRAP;
+    }
+    DelWrapper(getf);
+
+    /* Try to create a function setting a variable */
+    if (is_assignable(n)) {
+      setf = NewWrapper();
+      setname = Swig_name_set(iname);
+      setfname = Swig_name_wrapper(setname);
+      Setattr(n, "wrap:name", setfname);
+      if (setf) {
+        Printv(setf->def, "SWIGINTERN const char *", setfname,
+	     "(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, char *name1, char *name2 SWIGUNUSED, int flags) {", NIL);
+        Wrapper_add_local(setf, "value", "Tcl_Obj *value = 0");
+        Wrapper_add_local(setf, "name1o", "Tcl_Obj *name1o = 0");
+
+        if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
+	  Replaceall(tm, "$source", "value");
+	  Replaceall(tm, "$target", name);
+	  Replaceall(tm, "$input", "value");
+	  Printf(setf->code, "name1o = Tcl_NewStringObj(name1,-1);\n");
+	  Printf(setf->code, "value = Tcl_ObjGetVar2(interp, name1o, 0, flags);\n");
+	  Printf(setf->code, "Tcl_DecrRefCount(name1o);\n");
+	  Printf(setf->code, "if (!value) SWIG_fail;\n");
+	  /* Printf(setf->code,"%s\n", tm); */
+	  emit_action_code(n, setf->code, tm);
+	  Printf(setf->code, "return NULL;\n");
+	  Printf(setf->code, "fail:\n");
+	  Printf(setf->code, "return \"%s\";\n", iname);
+	  Printf(setf->code, "}\n");
+	  Wrapper_print(setf, f_wrappers);
+        } else {
+	  Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
+	  readonly = 1;
+        }
+      }
+      DelWrapper(setf);
+    } else {
+      readonly = 1;
+    }
+
+
+    Printv(var_tab, tab4, "{ SWIG_prefix \"", iname, "\", 0, (swig_variable_func) ", getfname, ",", NIL);
+    if (readonly) {
+      static int readonlywrap = 0;
+      if (!readonlywrap) {
+	Wrapper *ro = NewWrapper();
+	Printf(ro->def,
+	       "SWIGINTERN const char *swig_readonly(ClientData clientData SWIGUNUSED, Tcl_Interp *interp SWIGUNUSED, char *name1 SWIGUNUSED, char *name2 SWIGUNUSED, int flags SWIGUNUSED) {");
+	Printv(ro->code, "return \"Variable is read-only\";\n", "}\n", NIL);
+	Wrapper_print(ro, f_wrappers);
+	readonlywrap = 1;
+	DelWrapper(ro);
+      }
+      Printf(var_tab, "(swig_variable_func) swig_readonly},\n");
+    } else {
+      Printv(var_tab, "(swig_variable_func) ", setfname, "},\n", NIL);
+    }
+    Delete(getfname);
+    Delete(setfname);
+    Delete(setname);
+    Delete(getname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int constantWrapper(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = Getattr(n, "sym:name");
+    String *nsname = !nspace ? Copy(iname) : NewStringf("%s::%s", ns_name, iname);
+    SwigType *type = Getattr(n, "type");
+    String *rawval = Getattr(n, "rawval");
+    String *value = rawval ? rawval : Getattr(n, "value");
+    String *tm;
+
+    if (!addSymbol(iname, n))
+      return SWIG_ERROR;
+    if (nspace)
+      Setattr(n, "sym:name", nsname);
+
+    /* Special hook for member pointer */
+    if (SwigType_type(type) == T_MPOINTER) {
+      String *wname = Swig_name_wrapper(iname);
+      Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value);
+      value = Char(wname);
+    }
+
+    if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Replaceall(tm, "$nsname", nsname);
+      Printf(const_tab, "%s,\n", tm);
+    } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
+      Replaceall(tm, "$source", value);
+      Replaceall(tm, "$target", name);
+      Replaceall(tm, "$value", value);
+      Replaceall(tm, "$nsname", nsname);
+      Printf(f_init, "%s\n", tm);
+    } else {
+      Delete(nsname);
+      Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
+      return SWIG_NOWRAP;
+    }
+    Delete(nsname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * nativeWrapper()
+   * ------------------------------------------------------------ */
+
+  virtual int nativeWrapper(Node *n) {
+    String *name = Getattr(n, "sym:name");
+    String *funcname = Getattr(n, "wrap:name");
+    if (!addSymbol(funcname, n))
+      return SWIG_ERROR;
+
+    Printf(f_init, "\t Tcl_CreateObjCommand(interp, SWIG_prefix \"%s\", (swig_wrapper_func) %s, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);\n", name,
+	   funcname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int classHandler(Node *n) {
+    static Hash *emitted = NewHash();
+    String *mangled_classname = 0;
+    String *real_classname = 0;
+
+    have_constructor = 0;
+    have_destructor = 0;
+    destructor_action = 0;
+
+    if (itcl) {
+      constructor = NewString("");
+      destructor = NewString("");
+      base_classes = NewString("");
+      base_class_init = NewString("");
+      methods = NewString("");
+      imethods = NewString("");
+      attributes = NewString("");
+      attribute_traces = NewString("");
+      iattribute_traces = NewString("");
+
+      have_base_classes = 0;
+      have_methods = 0;
+      have_attributes = 0;
+    }
+
+    class_name = Getattr(n, "sym:name");
+    if (!addSymbol(class_name, n))
+      return SWIG_ERROR;
+
+    real_classname = Getattr(n, "name");
+    mangled_classname = Swig_name_mangle(real_classname);
+
+    if (Getattr(emitted, mangled_classname))
+      return SWIG_NOWRAP;
+    Setattr(emitted, mangled_classname, "1");
+
+    attr_tab = NewString("");
+    Printf(attr_tab, "static swig_attribute swig_");
+    Printv(attr_tab, mangled_classname, "_attributes[] = {\n", NIL);
+
+    methods_tab = NewStringf("");
+    Printf(methods_tab, "static swig_method swig_");
+    Printv(methods_tab, mangled_classname, "_methods[] = {\n", NIL);
+
+    /* Generate normal wrappers */
+    Language::classHandler(n);
+
+    SwigType *t = Copy(Getattr(n, "name"));
+    SwigType_add_pointer(t);
+
+    // Catch all: eg. a class with only static functions and/or variables will not have 'remembered'
+    // SwigType_remember(t);
+    String *wrap_class = NewStringf("&_wrap_class_%s", mangled_classname);
+    SwigType_remember_clientdata(t, wrap_class);
+
+    //    t = Copy(Getattr(n,"classtype"));
+    //    SwigType_add_pointer(t);
+
+    String *rt = Copy(Getattr(n, "classtype"));
+    SwigType_add_pointer(rt);
+
+    // Register the class structure with the type checker
+    /*    Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_classname); */
+    if (have_destructor) {
+      Printv(f_wrappers, "SWIGINTERN void swig_delete_", class_name, "(void *obj) {\n", NIL);
+      if (destructor_action) {
+	Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL);
+	Printv(f_wrappers, destructor_action, "\n", NIL);
+      } else {
+	if (CPlusPlus) {
+	  Printv(f_wrappers, "    delete (", SwigType_str(rt, 0), ") obj;\n", NIL);
+	} else {
+	  Printv(f_wrappers, "    free((char *) obj);\n", NIL);
+	}
+      }
+      Printf(f_wrappers, "}\n");
+    }
+
+    Printf(methods_tab, "    {0,0}\n};\n");
+    Printv(f_wrappers, methods_tab, NIL);
+
+    Printf(attr_tab, "    {0,0,0}\n};\n");
+    Printv(f_wrappers, attr_tab, NIL);
+
+    /* Handle inheritance */
+
+    String *base_class = NewString("");
+    String *base_class_names = NewString("");
+
+    if (itcl) {
+      base_classes = NewString("");
+    }
+
+    List *baselist = Getattr(n, "bases");
+    if (baselist && Len(baselist)) {
+      Iterator b;
+      int index = 0;
+      b = First(baselist);
+      while (b.item) {
+	String *bname = Getattr(b.item, "name");
+	if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) {
+	  b = Next(b);
+	  continue;
+	}
+	if (itcl) {
+	  have_base_classes = 1;
+	  Printv(base_classes, bname, " ", NIL);
+	  Printv(base_class_init, "    ", bname, "Ptr::constructor $ptr\n", NIL);
+	}
+	String *bmangle = Swig_name_mangle(bname);
+	//      Printv(f_wrappers,"extern swig_class _wrap_class_", bmangle, ";\n", NIL);
+	//      Printf(base_class,"&_wrap_class_%s",bmangle);
+	Printf(base_class, "0");
+	Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname));
+	/* Put code to register base classes in init function */
+
+	//Printf(f_init,"/* Register base : %s */\n", bmangle);
+	//Printf(f_init,"swig_%s_bases[%d] = (swig_class *) SWIG_TypeQuery(\"%s *\")->clientdata;\n",  mangled_classname, index, SwigType_namestr(bname));
+	b = Next(b);
+	index++;
+	Putc(',', base_class);
+	Delete(bmangle);
+      }
+    }
+
+    if (itcl) {
+      String *ptrclass = NewString("");
+
+      // First, build the pointer base class
+      Printv(ptrclass, "itcl::class ", class_name, "Ptr {\n", NIL);
+      if (have_base_classes)
+	Printv(ptrclass, "  inherit ", base_classes, "\n", NIL);
+
+      //  Define protected variables for SWIG object pointer
+      Printv(ptrclass, "  protected variable swigobj\n", "  protected variable thisown\n", NIL);
+
+      //  Define public variables
+      if (have_attributes) {
+	Printv(ptrclass, attributes, NIL);
+
+	// base class swig_getset was being called for complex inheritance trees
+	if (nspace) {
+
+	  Printv(ptrclass, "  protected method ", class_name, "_swig_getset {var name1 name2 op} {\n", NIL);
+
+	  Printv(ptrclass,
+		 "    switch -exact -- $op {\n",
+		 "      r {set $var [", ns_name, "::", class_name, "_[set var]_get $swigobj]}\n",
+		 "      w {", ns_name, "::", class_name, "_${var}_set $swigobj [set $var]}\n", "    }\n", "  }\n", NIL);
+	} else {
+	  Printv(ptrclass,
+		 "  protected method ", class_name, "_swig_getset {var name1 name2 op} {\n",
+		 "    switch -exact -- $op {\n",
+		 "      r {set $var [", class_name, "_[set var]_get $swigobj]}\n",
+		 "      w {", class_name, "_${var}_set $swigobj [set $var]}\n", "    }\n", "  }\n", NIL);
+	}
+      }
+      //  Add the constructor, which may include
+      //  calls to base class class constructors
+
+      Printv(ptrclass, "  constructor { ptr } {\n", NIL);
+      if (have_base_classes) {
+	Printv(ptrclass, base_class_init, NIL);
+	Printv(ptrclass, "  } {\n", NIL);
+      }
+
+      Printv(ptrclass, "    set swigobj $ptr\n", "    set thisown 0\n", NIL);
+
+      if (have_attributes) {
+	Printv(ptrclass, attribute_traces, NIL);
+      }
+      Printv(ptrclass, "  }\n", NIL);
+
+
+      //  Add destructor
+      Printv(ptrclass, "  destructor {\n",
+	     "    set d_func delete_", class_name, "\n",
+	     "    if { $thisown && ([info command $d_func] != \"\") } {\n" "      $d_func $swigobj\n", "    }\n", "  }\n", NIL);
+
+      //  Add methods
+      if (have_methods) {
+	Printv(ptrclass, imethods, NIL);
+      };
+
+      //  Close out the pointer class
+      Printv(ptrclass, "}\n\n", NIL);
+      Printv(f_shadow, ptrclass, NIL);
+      // pointer class end
+
+
+      //  Create the "real" class.
+      Printv(f_shadow, "itcl::class ", class_name, " {\n", NIL);
+      Printv(f_shadow, "  inherit ", class_name, "Ptr\n", NIL);
+
+      //  If we have a constructor, then use it.
+      //  If not, then we must have an abstract class without
+      //  any constructor.  So we create a class constructor
+      //  which will fail for this class (but not for inherited
+      //  classes).  Note that the constructor must fail before
+      //  calling the ptrclass constructor.
+
+      if (have_constructor) {
+	Printv(f_shadow, constructor, NIL);
+      } else {
+	Printv(f_shadow, "  constructor { } {\n", NIL);
+	Printv(f_shadow, "    # This constructor will fail if called directly\n", NIL);
+	Printv(f_shadow, "    if { [info class] == \"::", class_name, "\" } {\n", NIL);
+	Printv(f_shadow, "      error \"No constructor for class ", class_name, "\"\n", NIL);
+	Printv(f_shadow, "    }\n", NIL);
+	Printv(f_shadow, "  }\n", NIL);
+      }
+
+      Printv(f_shadow, "}\n\n", NIL);
+    };
+
+    Printv(f_wrappers, "static swig_class *swig_", mangled_classname, "_bases[] = {", base_class, "0};\n", NIL);
+    Printv(f_wrappers, "static const char * swig_", mangled_classname, "_base_names[] = {", base_class_names, "0};\n", NIL);
+    Delete(base_class);
+    Delete(base_class_names);
+
+    Printv(f_wrappers, "static swig_class _wrap_class_", mangled_classname, " = { \"", class_name, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL);
+
+    if (have_constructor) {
+      Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(constructor_name)));
+      Delete(constructor_name);
+      constructor_name = 0;
+    } else {
+      Printf(f_wrappers, "0");
+    }
+    if (have_destructor) {
+      Printv(f_wrappers, ", swig_delete_", class_name, NIL);
+    } else {
+      Printf(f_wrappers, ",0");
+    }
+    Printv(f_wrappers, ", swig_", mangled_classname, "_methods, swig_", mangled_classname, "_attributes, swig_", mangled_classname, "_bases,",
+	   "swig_", mangled_classname, "_base_names, &swig_module };\n", NIL);
+
+    if (!itcl) {
+      Printv(cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_", mangled_classname,
+	     "},\n", NIL);
+    };
+
+    Delete(t);
+    Delete(mangled_classname);
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------
+   * memberfunctionHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int memberfunctionHandler(Node *n) {
+    String *name = Getattr(n, "name");
+    String *iname = GetChar(n, "sym:name");
+
+    String *realname, *rname;
+
+    Language::memberfunctionHandler(n);
+
+    realname = iname ? iname : name;
+    rname = Swig_name_wrapper(Swig_name_member(class_name, realname));
+    if (!Getattr(n, "sym:nextSibling")) {
+      Printv(methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL);
+    }
+
+    if (itcl) {
+      ParmList *l = Getattr(n, "parms");
+      Parm *p = 0;
+      String *pname = NewString("");
+
+      // Add this member to our class handler function
+      Printv(imethods, tab2, "method ", realname, " [list ", NIL);
+
+      int pnum = 0;
+      for (p = l; p; p = nextSibling(p)) {
+
+	String *pn = Getattr(p, "name");
+	String *dv = Getattr(p, "value");
+	SwigType *pt = Getattr(p, "type");
+
+	Printv(pname, ",(", pt, ")", NIL);
+	Clear(pname);
+
+	/* Only print an argument if not void */
+	if (Cmp(pt, "void") != 0) {
+	  if (Len(pn) > 0) {
+	    Printv(pname, pn, NIL);
+	  } else {
+	    Printf(pname, "p%d", pnum);
+	  }
+
+	  if (Len(dv) > 0) {
+	    String *defval = NewString(dv);
+	    if (nspace) {
+	      Insert(defval, 0, "::");
+	      Insert(defval, 0, ns_name);
+	    }
+	    if (Strncmp(dv, "(", 1) == 0) {
+	      Insert(defval, 0, "$");
+	      Replaceall(defval, "(", "");
+	      Replaceall(defval, ")", "");
+	    }
+	    Printv(imethods, "[list ", pname, " ", defval, "] ", NIL);
+	  } else {
+	    Printv(imethods, pname, " ", NIL);
+	  }
+	}
+	++pnum;
+      }
+      Printv(imethods, "] ", NIL);
+
+      if (nspace) {
+	Printv(imethods, "{ ", ns_name, "::", class_name, "_", realname, " $swigobj", NIL);
+      } else {
+	Printv(imethods, "{ ", class_name, "_", realname, " $swigobj", NIL);
+      };
+
+      pnum = 0;
+      for (p = l; p; p = nextSibling(p)) {
+
+	String *pn = Getattr(p, "name");
+	SwigType *pt = Getattr(p, "type");
+	Clear(pname);
+
+	/* Only print an argument if not void */
+	if (Cmp(pt, "void") != 0) {
+	  if (Len(pn) > 0) {
+	    Printv(pname, pn, NIL);
+	  } else {
+	    Printf(pname, "p%d", pnum);
+	  }
+	  Printv(imethods, " $", pname, NIL);
+	}
+	++pnum;
+      }
+      Printv(imethods, " }\n", NIL);
+      have_methods = 1;
+    }
+
+    Delete(rname);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * membervariableHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int membervariableHandler(Node *n) {
+    String *symname = Getattr(n, "sym:name");
+    String *rname;
+
+    Language::membervariableHandler(n);
+    Printv(attr_tab, tab4, "{ \"-", symname, "\",", NIL);
+    rname = Swig_name_wrapper(Swig_name_get(Swig_name_member(class_name, symname)));
+    Printv(attr_tab, rname, ", ", NIL);
+    Delete(rname);
+    if (!GetFlag(n, "feature:immutable")) {
+      rname = Swig_name_wrapper(Swig_name_set(Swig_name_member(class_name, symname)));
+      Printv(attr_tab, rname, "},\n", NIL);
+      Delete(rname);
+    } else {
+      Printf(attr_tab, "0 },\n");
+    }
+
+    if (itcl) {
+      Printv(attributes, "  public variable ", symname, "\n", NIL);
+
+      Printv(attribute_traces, "    trace variable ", symname, " rw [list ", class_name, "_swig_getset ", symname, "]\n", NIL);
+      Printv(attribute_traces, "    set ", symname, "\n", NIL);
+
+      have_attributes = 1;
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int constructorHandler(Node *n) {
+    Language::constructorHandler(n);
+
+    if (itcl) {
+      String *name = Getattr(n, "name");
+      String *iname = GetChar(n, "sym:name");
+
+      String *realname;
+
+      ParmList *l = Getattr(n, "parms");
+      Parm *p = 0;
+
+      String *pname = NewString("");
+
+      realname = iname ? iname : name;
+
+      if (!have_constructor) {
+	// Add this member to our class handler function
+	Printf(constructor, "  constructor { ");
+
+	//  Add parameter list
+	int pnum = 0;
+	for (p = l; p; p = nextSibling(p)) {
+
+	  SwigType *pt = Getattr(p, "type");
+	  String *pn = Getattr(p, "name");
+	  String *dv = Getattr(p, "value");
+	  Clear(pname);
+
+	  /* Only print an argument if not void */
+	  if (Cmp(pt, "void") != 0) {
+	    if (Len(pn) > 0) {
+	      Printv(pname, pn, NIL);
+	    } else {
+	      Printf(pname, "p%d", pnum);
+	    }
+
+	    if (Len(dv) > 0) {
+	      Printv(constructor, "{", pname, " {", dv, "} } ", NIL);
+	    } else {
+	      Printv(constructor, pname, " ", NIL);
+	    }
+	  }
+	  ++pnum;
+	}
+	Printf(constructor, "} { \n");
+
+	// [BRE] 08/17/00 Added test to see if we are instantiating this object
+	// type, or, if this constructor is being called as part of the itcl
+	// inheritance hierarchy.
+	// In the former case, we need to call the C++ constructor, in the
+	// latter we don't, or we end up with two C++ objects.
+	// Check to see if we are instantiating a 'realname' or something 
+	// derived from it.
+	//
+	Printv(constructor, "    if { [string equal -nocase \"", realname, "\" \"[namespace tail [info class]]\" ] } {\n", NIL);
+
+	// Call to constructor wrapper and parent Ptr class
+	// [BRE] add -namespace/-prefix support
+
+	if (nspace) {
+	  Printv(constructor, "      ", realname, "Ptr::constructor [", ns_name, "::new_", realname, NIL);
+	} else {
+	  Printv(constructor, "      ", realname, "Ptr::constructor [new_", realname, NIL);
+	}
+
+	pnum = 0;
+	for (p = l; p; p = nextSibling(p)) {
+
+	  SwigType *pt = Getattr(p, "type");
+	  String *pn = Getattr(p, "name");
+	  Clear(pname);
+
+	  /* Only print an argument if not void */
+	  if (Cmp(pt, "void") != 0) {
+	    if (Len(pn) > 0) {
+	      Printv(pname, pn, NIL);
+	    } else {
+	      Printf(pname, "p%d", pnum);
+	    }
+	    Printv(constructor, " $", pname, NIL);
+	  }
+	  ++pnum;
+	}
+
+	Printv(constructor, "]\n", "    }\n", "  } {\n", "    set thisown 1\n", "  }\n", NIL);
+      }
+    }
+
+    constructor_name = NewString(Getattr(n, "sym:name"));
+    have_constructor = 1;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * destructorHandler()
+   * ------------------------------------------------------------ */
+
+  virtual int destructorHandler(Node *n) {
+    Language::destructorHandler(n);
+    have_destructor = 1;
+    destructor_action = Getattr(n, "wrap:action");
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * validIdentifier()
+   * ------------------------------------------------------------ */
+
+  virtual int validIdentifier(String *s) {
+    if (Strchr(s, ' '))
+      return 0;
+    return 1;
+  }
+
+  /* ------------------------------------------------------------
+   * usage_string()
+   * ------------------------------------------------------------ */
+
+  char *usage_string(char *iname, SwigType *, ParmList *l) {
+    static String *temp = 0;
+    Parm *p;
+    int i, numopt, pcount;
+
+    if (!temp)
+      temp = NewString("");
+    Clear(temp);
+    if (nspace) {
+      Printf(temp, "%s::%s ", ns_name, iname);
+    } else {
+      Printf(temp, "%s ", iname);
+    }
+    /* Now go through and print parameters */
+    i = 0;
+    pcount = emit_num_arguments(l);
+    numopt = pcount - emit_num_required(l);
+    for (p = l; p; p = nextSibling(p)) {
+
+      SwigType *pt = Getattr(p, "type");
+      String *pn = Getattr(p, "name");
+      /* Only print an argument if not ignored */
+      if (!checkAttribute(p, "tmap:in:numinputs", "0")) {
+	if (i >= (pcount - numopt))
+	  Putc('?', temp);
+	if (Len(pn) > 0) {
+	  Printf(temp, "%s", pn);
+	} else {
+	  Printf(temp, "%s", SwigType_str(pt, 0));
+	}
+	if (i >= (pcount - numopt))
+	  Putc('?', temp);
+	Putc(' ', temp);
+	i++;
+      }
+    }
+    return Char(temp);
+  }
+
+  String *runtimeCode() {
+    String *s = NewString("");
+    String *serrors = Swig_include_sys("tclerrors.swg");
+    if (!serrors) {
+      Printf(stderr, "*** Unable to open 'tclerrors.swg'\n");
+    } else {
+      Append(s, serrors);
+      Delete(serrors);
+    }
+    String *sapi = Swig_include_sys("tclapi.swg");
+    if (!sapi) {
+      Printf(stderr, "*** Unable to open 'tclapi.swg'\n");
+    } else {
+      Append(s, sapi);
+      Delete(sapi);
+    }
+    String *srun = Swig_include_sys("tclrun.swg");
+    if (!srun) {
+      Printf(stderr, "*** Unable to open 'tclrun.swg'\n");
+    } else {
+      Append(s, srun);
+      Delete(srun);
+    }
+
+    return s;
+  }
+
+  String *defaultExternalRuntimeFilename() {
+    return NewString("swigtclrun.h");
+  }
+};
+
+/* ----------------------------------------------------------------------
+ * swig_tcl()    - Instantiate module
+ * ---------------------------------------------------------------------- */
+
+static Language *new_swig_tcl() {
+  return new TCL8();
+}
+extern "C" Language *swig_tcl(void) {
+  return new_swig_tcl();
+}
diff --git a/trunk/Source/Modules/typepass.cxx b/trunk/Source/Modules/typepass.cxx
new file mode 100644
index 0000000..d663aed
--- /dev/null
+++ b/trunk/Source/Modules/typepass.cxx
@@ -0,0 +1,1118 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typepass.cxx
+ *
+ * This module builds all of the internal type information by collecting
+ * typedef declarations as well as registering classes, structures, and unions.
+ * This information is needed to correctly handle shadow classes and other
+ * advanced features.   This phase of compilation is also used to perform
+ * type-expansion.  All types are fully qualified with namespace prefixes
+ * and other information needed for compilation.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_typepass_cxx[] = "$Id$";
+
+#include "swigmod.h"
+#include "cparse.h"
+
+struct normal_node {
+  Symtab *symtab;
+  Hash *typescope;
+  List *normallist;
+  normal_node *next;
+};
+
+static normal_node *patch_list = 0;
+
+/* Singleton class - all non-static methods in this class are private */
+class TypePass:private Dispatcher {
+  Node *inclass;
+  Node *module;
+  int importmode;
+  String *nsname;
+  Hash *classhash;
+  List *normalize;
+
+  TypePass() {
+  }
+
+  /* Normalize a type. Replaces type with fully qualified version */
+  void normalize_type(SwigType *ty) {
+    SwigType *qty;
+    if (CPlusPlus) {
+      Replaceall(ty, "struct ", "");
+      Replaceall(ty, "union ", "");
+      Replaceall(ty, "class ", "");
+    }
+
+    qty = SwigType_typedef_qualified(ty);
+    /*    Printf(stdout,"%s --> %s\n", ty, qty); */
+    Clear(ty);
+    Append(ty, qty);
+    Delete(qty);
+  }
+
+  /* Normalize a parameter list */
+
+  void normalize_parms(ParmList *p) {
+    while (p) {
+      SwigType *ty = Getattr(p, "type");
+      normalize_type(ty);
+      /* This is a check for a function type */
+      {
+	SwigType *qty = SwigType_typedef_resolve_all(ty);
+	if (SwigType_isfunction(qty)) {
+	  SwigType_add_pointer(ty);
+	}
+	Delete(qty);
+      }
+
+      String *value = Getattr(p, "value");
+      if (value) {
+	Node *n = Swig_symbol_clookup(value, 0);
+	if (n) {
+	  String *q = Swig_symbol_qualified(n);
+	  if (q && Len(q)) {
+	    String *vb = Swig_scopename_last(value);
+	    Clear(value);
+	    Printf(value, "%s::%s", SwigType_namestr(q), vb);
+	    Delete(q);
+	  }
+	}
+      }
+      if (value && SwigType_istemplate(value)) {
+	String *nv = SwigType_namestr(value);
+	Setattr(p, "value", nv);
+      }
+      p = nextSibling(p);
+    }
+  }
+
+  void normalize_later(ParmList *p) {
+    while (p) {
+      SwigType *ty = Getattr(p, "type");
+      Append(normalize, ty);
+      p = nextSibling(p);
+    }
+  }
+
+  /* Walk through entries in normalize list and patch them up */
+  void normalize_list() {
+    Hash *currentsym = Swig_symbol_current();
+
+    normal_node *nn = patch_list;
+    normal_node *np;
+    while (nn) {
+      Swig_symbol_setscope(nn->symtab);
+      SwigType_set_scope(nn->typescope);
+      Iterator t;
+      for (t = First(nn->normallist); t.item; t = Next(t)) {
+	normalize_type(t.item);
+      }
+      Delete(nn->normallist);
+      np = nn->next;
+      delete(nn);
+      nn = np;
+    }
+    Swig_symbol_setscope(currentsym);
+  }
+
+  /* generate C++ inheritance type-relationships */
+  void cplus_inherit_types_impl(Node *first, Node *cls, String *clsname, const char *bases, const char *baselist, int ispublic, String *cast = 0) {
+
+    if (first == cls)
+      return;			/* The Marcelo check */
+    if (!cls)
+      cls = first;
+    List *alist = 0;
+    List *ilist = Getattr(cls, bases);
+    if (!ilist) {
+      List *nlist = Getattr(cls, baselist);
+      if (nlist) {
+	int len = Len(nlist);
+	int i;
+	for (i = 0; i < len; i++) {
+	  Node *bcls = 0;
+	  int clsforward = 0;
+	  String *bname = Getitem(nlist, i);
+	  String *sname = bname;
+	  String *tname = 0;
+
+	  /* Try to locate the base class.   We look in the symbol table and we chase 
+	     typedef declarations to get to the base class if necessary */
+	  Symtab *st = Getattr(cls, "sym:symtab");
+
+	  if (SwigType_istemplate(bname)) {
+	    tname = SwigType_typedef_resolve_all(bname);
+	    sname = tname;
+	  }
+	  while (1) {
+	    String *qsname = SwigType_typedef_qualified(sname);
+	    bcls = Swig_symbol_clookup(qsname, st);
+	    Delete(qsname);
+	    if (bcls) {
+	      if (Strcmp(nodeType(bcls), "class") != 0) {
+		/* Not a class.   The symbol could be a typedef. */
+		if (checkAttribute(bcls, "storage", "typedef")) {
+		  SwigType *decl = Getattr(bcls, "decl");
+		  if (!decl || !(Len(decl))) {
+		    sname = Getattr(bcls, "type");
+		    st = Getattr(bcls, "sym:symtab");
+		    if (SwigType_istemplate(sname)) {
+		      if (tname)
+			Delete(tname);
+		      tname = SwigType_typedef_resolve_all(sname);
+		      sname = tname;
+		    }
+		    continue;
+		  }
+		}
+		if (Strcmp(nodeType(bcls), "classforward") != 0) {
+		  Swig_error(Getfile(cls), Getline(cls), "'%s' does not have a valid base class.\n", Getattr(cls, "name"));
+		  Swig_error(Getfile(bcls), Getline(bcls), "'%s' is not a valid base class.\n", SwigType_namestr(bname));
+		} else {
+		  Swig_warning(WARN_TYPE_INCOMPLETE, Getfile(cls), Getline(cls), "Base class '%s' is incomplete.\n", SwigType_namestr(bname));
+		  Swig_warning(WARN_TYPE_INCOMPLETE, Getfile(bcls), Getline(bcls), "Only forward declaration '%s' was found.\n", SwigType_namestr(bname));
+		  clsforward = 1;
+		}
+		bcls = 0;
+	      } else {
+		if (Getattr(bcls, "typepass:visit")) {
+		  if (!ilist)
+		    ilist = alist = NewList();
+		  Append(ilist, bcls);
+		} else {
+		  Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(cls), Getline(cls), "Base class '%s' undefined.\n", SwigType_namestr(bname));
+		  Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(bcls), Getline(bcls), "'%s' must be defined before it is used as a base class.\n", SwigType_namestr(bname));
+		}
+	      }
+	    }
+	    break;
+	  }
+
+	  if (tname)
+	    Delete(tname);
+	  if (!bcls) {
+	    if (!clsforward) {
+	      if (ispublic && !Getmeta(bname, "already_warned")) {
+		Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(cls), Getline(cls), "Nothing known about base class '%s'. Ignored.\n", SwigType_namestr(bname));
+		if (Strchr(bname, '<')) {
+		  Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(cls), Getline(cls), "Maybe you forgot to instantiate '%s' using %%template.\n",
+			       SwigType_namestr(bname));
+		}
+		Setmeta(bname, "already_warned", "1");
+	      }
+	    }
+	    SwigType_inherit(clsname, bname, cast, 0);
+	  }
+	}
+      }
+      if (ilist) {
+	Setattr(cls, bases, ilist);
+      }
+    }
+    if (alist)
+      Delete(alist);
+
+    if (!ilist)
+      return;
+    int len = Len(ilist);
+    int i;
+    for (i = 0; i < len; i++) {
+      Node *n = Getitem(ilist, i);
+      String *bname = Getattr(n, "name");
+      Node *bclass = n;		/* Getattr(n,"class"); */
+      Hash *scopes = Getattr(bclass, "typescope");
+      SwigType_inherit(clsname, bname, cast, 0);
+      if (!importmode) {
+	String *btype = Copy(bname);
+	SwigType_add_pointer(btype);
+	SwigType_remember(btype);
+	Delete(btype);
+      }
+      if (scopes) {
+	SwigType_inherit_scope(scopes);
+      }
+      /* Set up inheritance in the symbol table */
+      Symtab *st = Getattr(cls, "symtab");
+      Symtab *bst = Getattr(bclass, "symtab");
+      if (st == bst) {
+	Swig_warning(WARN_PARSE_REC_INHERITANCE, Getfile(cls), Getline(cls), "Recursive scope inheritance of '%s'.\n", Getattr(cls, "name"));
+	continue;
+      }
+      Symtab *s = Swig_symbol_current();
+      Swig_symbol_setscope(st);
+      Swig_symbol_inherit(bst);
+      Swig_symbol_setscope(s);
+
+      /* Recursively hit base classes */
+      String *namestr = SwigType_namestr(Getattr(bclass, "name"));
+      String *newcast = NewStringf("(%s *)%s", namestr, cast);
+      Delete(namestr);
+      cplus_inherit_types_impl(first, bclass, clsname, bases, baselist, ispublic, newcast);
+      Delete(newcast);
+    }
+  }
+
+  void append_list(List *lb, List *la) {
+    if (la && lb) {
+      for (Iterator bi = First(la); bi.item; bi = Next(bi)) {
+	Append(lb, bi.item);
+      }
+    }
+  }
+
+  void cplus_inherit_types(Node *first, Node *cls, String *clsname, String *cast = 0) {
+    cplus_inherit_types_impl(first, cls, clsname, "bases", "baselist", 1, cast);
+    cplus_inherit_types_impl(first, cls, clsname, "protectedbases", "protectedbaselist", 0, cast);
+    cplus_inherit_types_impl(first, cls, clsname, "privatebases", "privatebaselist", 0, cast);
+
+    if (!cls)
+      cls = first;
+
+    List *allbases = NewList();
+    append_list(allbases, Getattr(cls, "bases"));
+    append_list(allbases, Getattr(cls, "protectedbases"));
+    append_list(allbases, Getattr(cls, "privatebases"));
+    if (Len(allbases)) {
+      Setattr(cls, "allbases", allbases);
+    }
+    Delete(allbases);
+  }
+
+  /* ------------------------------------------------------------
+   * top()
+   * ------------------------------------------------------------ */
+
+  virtual int top(Node *n) {
+    importmode = 0;
+    module = Getattr(n, "module");
+    inclass = 0;
+    normalize = 0;
+    nsname = 0;
+    classhash = Getattr(n, "classes");
+    emit_children(n);
+    normalize_list();
+    SwigType_set_scope(0);
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------
+   * moduleDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int moduleDirective(Node *n) {
+    if (!module) {
+      module = n;
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * importDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int importDirective(Node *n) {
+    String *oldmodule = module;
+    int oldimport = importmode;
+    importmode = 1;
+    module = 0;
+    emit_children(n);
+    importmode = oldimport;
+    module = oldmodule;
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * includeDirective()
+   * externDirective()
+   * extendDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int includeDirective(Node *n) {
+    return emit_children(n);
+  }
+  virtual int externDeclaration(Node *n) {
+    return emit_children(n);
+  }
+  virtual int extendDirective(Node *n) {
+    return emit_children(n);
+  }
+
+  /* ------------------------------------------------------------
+   * classDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int classDeclaration(Node *n) {
+    String *name = Getattr(n, "name");
+    String *tdname = Getattr(n, "tdname");
+    String *unnamed = Getattr(n, "unnamed");
+    String *storage = Getattr(n, "storage");
+    String *kind = Getattr(n, "kind");
+    Node *oldinclass = inclass;
+    List *olist = normalize;
+    Symtab *symtab;
+    String *nname = 0;
+    String *fname = 0;
+    String *scopename = 0;
+
+    normalize = NewList();
+
+    if (name) {
+      if (SwigType_istemplate(name)) {
+	// We need to fully resolve the name to make templates work correctly */
+	Node *cn;
+	fname = SwigType_typedef_resolve_all(name);
+	if (Strcmp(fname, name) != 0 && (cn = Swig_symbol_clookup_local(fname, 0))) {
+	  if ((n == cn)
+	      || (Strcmp(nodeType(cn), "template") == 0)
+	      || (Getattr(cn, "feature:onlychildren") != 0)
+	      || (Getattr(n, "feature:onlychildren") != 0)) {
+	    Swig_symbol_cadd(fname, n);
+	    SwigType_typedef_class(fname);
+	    scopename = Copy(fname);
+	  } else {
+	    Swig_warning(WARN_TYPE_REDEFINED, Getfile(n), Getline(n), "Template '%s' was already wrapped,\n", SwigType_namestr(name));
+	    Swig_warning(WARN_TYPE_REDEFINED, Getfile(cn), Getline(cn), "previous wrap of '%s'.\n", SwigType_namestr(Getattr(cn, "name")));
+	    scopename = 0;
+	  }
+	} else {
+	  Swig_symbol_cadd(fname, n);
+	  SwigType_typedef_class(fname);
+	  scopename = Copy(fname);
+	}
+      } else {
+	if ((CPlusPlus) || (unnamed)) {
+	  SwigType_typedef_class(name);
+	} else {
+	  SwigType_typedef_class(NewStringf("%s %s", kind, name));
+	}
+	scopename = Copy(name);
+      }
+    } else {
+      scopename = 0;
+    }
+
+    Setattr(n, "typepass:visit", "1");
+
+    /* Need to set up a typedef if unnamed */
+    if (unnamed && tdname && (Cmp(storage, "typedef") == 0)) {
+      SwigType_typedef(unnamed, tdname);
+    }
+
+    if (nsname) {
+      nname = NewStringf("%s::%s", nsname, name);
+      String *tdname = Getattr(n, "tdname");
+      if (tdname) {
+	tdname = NewStringf("%s::%s", nsname, tdname);
+	Setattr(n, "tdname", tdname);
+      }
+    }
+    SwigType_new_scope(scopename);
+    SwigType_attach_symtab(Getattr(n, "symtab"));
+
+    /* Inherit type definitions into the class */
+    if (name) {
+      cplus_inherit_types(n, 0, nname ? nname : (fname ? fname : name));
+    }
+
+    inclass = n;
+    symtab = Swig_symbol_setscope(Getattr(n, "symtab"));
+    emit_children(n);
+    Swig_symbol_setscope(symtab);
+
+    Hash *ts = SwigType_pop_scope();
+    Setattr(n, "typescope", ts);
+    Delete(ts);
+    Setattr(n, "module", module);
+
+    /* Normalize deferred types */
+    {
+      normal_node *nn = new normal_node();
+      nn->normallist = normalize;
+      nn->symtab = Getattr(n, "symtab");
+      nn->next = patch_list;
+      nn->typescope = Getattr(n, "typescope");
+      patch_list = nn;
+    }
+
+    normalize = olist;
+
+    inclass = oldinclass;
+
+    /* If in a namespace, patch the class name */
+    if (nname) {
+      Setattr(n, "name", nname);
+      Delete(nname);
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * namespaceDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int templateDeclaration(Node *n) {
+    String *name = Getattr(n, "name");
+    String *ttype = Getattr(n, "templatetype");
+    if (Strcmp(ttype, "class") == 0) {
+      String *rname = SwigType_typedef_resolve_all(name);
+      SwigType_typedef_class(rname);
+      Delete(rname);
+    } else if (Strcmp(ttype, "classforward") == 0) {
+      String *rname = SwigType_typedef_resolve_all(name);
+      SwigType_typedef_class(rname);
+      Delete(rname);
+      /*      SwigType_typedef_class(name); */
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * classforwardDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int classforwardDeclaration(Node *n) {
+
+    /* Temporary hack. Can't do inside a class because it breaks
+       C nested structure wrapping */
+
+    if ((!inclass) || (CPlusPlus)) {
+      String *name = Getattr(n, "name");
+      String *nname;
+      SwigType_typedef_class(name);
+      if (nsname) {
+	nname = NewStringf("%s::%s", nsname, name);
+	Setattr(n, "name", nname);
+      }
+
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * namespaceDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int namespaceDeclaration(Node *n) {
+    Symtab *symtab;
+    String *name = Getattr(n, "name");
+    String *alias = Getattr(n, "alias");
+    List *olist = normalize;
+    normalize = NewList();
+    if (alias) {
+      Typetab *ts = Getattr(n, "typescope");
+      if (!ts) {
+	Node *ns;
+	/* Create a empty scope for the alias */
+	ns = Getattr(n, "namespace");
+	if (ns) {
+	  SwigType_scope_alias(name, Getattr(ns, "typescope"));
+	}
+	ts = Getattr(ns, "typescope");
+	Setattr(n, "typescope", ts);
+      }
+      /* Namespace alias */
+      return SWIG_OK;
+    } else {
+      if (name) {
+	Node *nn = Swig_symbol_clookup(name, n);
+	Hash *ts = 0;
+	if (nn)
+	  ts = Getattr(nn, "typescope");
+	if (!ts) {
+	  SwigType_new_scope(name);
+	  SwigType_attach_symtab(Getattr(n, "symtab"));
+	} else {
+	  SwigType_set_scope(ts);
+	}
+      }
+      String *oldnsname = nsname;
+      nsname = Swig_symbol_qualified(Getattr(n, "symtab"));
+      symtab = Swig_symbol_setscope(Getattr(n, "symtab"));
+      emit_children(n);
+      Swig_symbol_setscope(symtab);
+
+      if (name) {
+	Hash *ts = SwigType_pop_scope();
+	Setattr(n, "typescope", ts);
+	Delete(ts);
+      }
+
+      /* Normalize deferred types */
+      {
+	normal_node *nn = new normal_node();
+	nn->normallist = normalize;
+	nn->symtab = Getattr(n, "symtab");
+	nn->next = patch_list;
+	nn->typescope = Getattr(n, "typescope");
+	patch_list = nn;
+      }
+      normalize = olist;
+
+      Delete(nsname);
+      nsname = oldnsname;
+      return SWIG_OK;
+    }
+  }
+
+  /* ------------------------------------------------------------
+   * cDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int cDeclaration(Node *n) {
+    if (NoExcept) {
+      Delattr(n, "throws");
+    }
+
+    /* Normalize types. */
+    SwigType *ty = Getattr(n, "type");
+    normalize_type(ty);
+    SwigType *decl = Getattr(n, "decl");
+    if (decl) {
+      normalize_type(decl);
+    }
+    normalize_parms(Getattr(n, "parms"));
+    normalize_parms(Getattr(n, "throws"));
+    if (GetFlag(n, "conversion_operator")) {
+      /* The call to the operator in the generated wrapper must be fully qualified in order to compile */
+      SwigType *name = Getattr(n, "name");
+      SwigType *qualifiedname = Swig_symbol_string_qualify(name,0);
+      Clear(name);
+      Append(name, qualifiedname);
+      Delete(qualifiedname);
+    }
+
+    if (checkAttribute(n, "storage", "typedef")) {
+      String *name = Getattr(n, "name");
+      ty = Getattr(n, "type");
+      decl = Getattr(n, "decl");
+      SwigType *t = Copy(ty);
+      {
+	/* If the typename is qualified, make sure the scopename is fully qualified when making a typedef */
+	if (Swig_scopename_check(t) && strncmp(Char(t), "::", 2)) {
+	  String *base, *prefix, *qprefix;
+	  base = Swig_scopename_last(t);
+	  prefix = Swig_scopename_prefix(t);
+	  qprefix = SwigType_typedef_qualified(prefix);
+	  Delete(t);
+	  t = NewStringf("%s::%s", qprefix, base);
+	  Delete(base);
+	  Delete(prefix);
+	  Delete(qprefix);
+	}
+      }
+      SwigType_push(t, decl);
+      if (CPlusPlus) {
+	Replaceall(t, "struct ", "");
+	Replaceall(t, "union ", "");
+	Replaceall(t, "class ", "");
+      }
+      SwigType_typedef(t, name);
+    }
+    /* If namespaces are active.  We need to patch the name with a namespace prefix */
+    if (nsname && !inclass) {
+      String *name = Getattr(n, "name");
+      if (name) {
+	String *nname = NewStringf("%s::%s", nsname, name);
+	Setattr(n, "name", nname);
+	Delete(nname);
+      }
+    }
+    clean_overloaded(n);
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------
+   * constructorDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int constructorDeclaration(Node *n) {
+    if (NoExcept) {
+      Delattr(n, "throws");
+    }
+
+    normalize_parms(Getattr(n, "parms"));
+    normalize_parms(Getattr(n, "throws"));
+
+    /* If in a namespace, patch the class name */
+    if (nsname) {
+      String *nname = NewStringf("%s::%s", nsname, Getattr(n, "name"));
+      Setattr(n, "name", nname);
+    }
+    clean_overloaded(n);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * destructorDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int destructorDeclaration(Node *n) {
+    /* If in a namespace, patch the class name */
+    if (nsname) {
+      String *nname = NewStringf("%s::%s", nsname, Getattr(n, "name"));
+      Setattr(n, "name", nname);
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * constantDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int constantDirective(Node *n) {
+    SwigType *ty = Getattr(n, "type");
+    if (ty) {
+      Setattr(n, "type", SwigType_typedef_qualified(ty));
+    }
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------
+   * enumDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumDeclaration(Node *n) {
+    String *name = Getattr(n, "name");
+
+    if (name) {
+      String *scope = 0;
+
+      // Add a typedef to the type table so that we can use 'enum Name' as well as just 'Name'
+      if (nsname || inclass) {
+
+	// But first correct the name and tdname to contain the fully qualified scopename
+	if (nsname && inclass) {
+	  scope = NewStringf("%s::%s", nsname, Getattr(inclass, "name"));
+	} else if (nsname) {
+	  scope = NewStringf("%s", nsname);
+	} else if (inclass) {
+	  scope = NewStringf("%s", Getattr(inclass, "name"));
+	}
+
+	String *nname = NewStringf("%s::%s", scope, name);
+	Setattr(n, "name", nname);
+
+	String *tdname = Getattr(n, "tdname");
+	if (tdname) {
+	  tdname = NewStringf("%s::%s", scope, tdname);
+	  Setattr(n, "tdname", tdname);
+	}
+
+	SwigType *t = NewStringf("enum %s", nname);
+	SwigType_typedef(t, name);
+      } else {
+	SwigType *t = NewStringf("enum %s", name);
+	SwigType_typedef(t, name);
+      }
+      Delete(scope);
+    }
+
+    String *tdname = Getattr(n, "tdname");
+    String *unnamed = Getattr(n, "unnamed");
+    String *storage = Getattr(n, "storage");
+
+    // Construct enumtype - for declaring an enum of this type with SwigType_ltype() etc
+    String *enumtype = 0;
+    if (unnamed && tdname && (Cmp(storage, "typedef") == 0)) {
+      enumtype = Copy(Getattr(n, "tdname"));
+    } else if (name) {
+      enumtype = NewStringf("%s%s", CPlusPlus ? "" : "enum ", Getattr(n, "name"));
+    } else {
+      // anonymous enums
+      enumtype = Copy(Getattr(n, "type"));
+    }
+    Setattr(n, "enumtype", enumtype);
+
+    emit_children(n);
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * enumvalueDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumvalueDeclaration(Node *n) {
+    String *name = Getattr(n, "name");
+    String *value = Getattr(n, "value");
+    if (!value)
+      value = name;
+    if (Strcmp(value, name) == 0) {
+      String *new_value;
+      if (((nsname) || (inclass)) && cparse_cplusplus) {
+	new_value = NewStringf("%s::%s", SwigType_namestr(Swig_symbol_qualified(n)), value);
+      } else {
+	new_value = NewString(value);
+      }
+      Setattr(n, "value", new_value);
+      Delete(new_value);
+    }
+    // Make up an enumvalue if one was not specified in the parsed code
+    if (Getattr(n, "_last") && !Getattr(n, "enumvalue")) {	// Only the first enum item has _last set
+      Setattr(n, "enumvalueex", "0");
+    }
+    Node *next = nextSibling(n);
+    if (next && !Getattr(next, "enumvalue")) {
+      Setattr(next, "enumvalueex", NewStringf("%s + 1", Getattr(n, "sym:name")));
+    }
+
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * enumforwardDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int enumforwardDeclaration(Node *n) {
+
+    // Use enumDeclaration() to do all the hard work.
+    // Note that no children can be emitted in a forward declaration as there aren't any.
+    return enumDeclaration(n);
+  }
+
+#ifdef DEBUG_OVERLOADED
+  static void show_overloaded(Node *n) {
+    Node *c = Getattr(n, "sym:overloaded");
+    Node *checkoverloaded = c;
+    Printf(stdout, "-------------------- overloaded start %s sym:overloaded():%p -------------------------------\n", Getattr(n, "name"), c);
+    while (c) {
+      if (Getattr(c, "error")) {
+        c = Getattr(c, "sym:nextSibling");
+        continue;
+      }
+      if (Getattr(c, "sym:overloaded") != checkoverloaded) {
+        Printf(stdout, "sym:overloaded error c:%p checkoverloaded:%p\n", c, checkoverloaded);
+        Swig_print_node(c);
+        exit (1);
+      }
+
+      String *decl = Strcmp(nodeType(c), "using") == 0 ? NewString("------") : Getattr(c, "decl");
+      Printf(stdout, "  show_overloaded %s::%s(%s)          [%s] nodeType:%s\n", parentNode(c) ? Getattr(parentNode(c), "name") : "NOPARENT", Getattr(c, "name"), decl, Getattr(c, "sym:overname"), nodeType(c));
+      if (!Getattr(c, "sym:overloaded")) {
+        Printf(stdout, "sym:overloaded error.....%p\n", c);
+        Swig_print_node(c);
+        exit (1);
+      }
+      c = Getattr(c, "sym:nextSibling");
+    }
+    Printf(stdout, "-------------------- overloaded end   %s -------------------------------\n", Getattr(n, "name"));
+  }
+#endif
+
+  /* ------------------------------------------------------------
+   * usingDeclaration()
+   * ------------------------------------------------------------ */
+
+  virtual int usingDeclaration(Node *n) {
+    if (Getattr(n, "namespace")) {
+      /* using namespace id */
+
+      /* For a namespace import.   We set up inheritance in the type system */
+      Node *ns = Getattr(n, "node");
+      if (ns) {
+	Typetab *ts = Getattr(ns, "typescope");
+	if (ts) {
+	  SwigType_using_scope(ts);
+	}
+      }
+      return SWIG_OK;
+    } else {
+      Node *ns;
+      /* using id */
+      Symtab *stab = Getattr(n, "sym:symtab");
+      if (stab) {
+	String *uname = Getattr(n, "uname");
+	ns = Swig_symbol_clookup(uname, stab);
+	if (!ns && SwigType_istemplate(uname)) {
+	  String *tmp = Swig_symbol_template_deftype(uname, 0);
+	  if (!Equal(tmp, uname)) {
+	    ns = Swig_symbol_clookup(tmp, stab);
+	  }
+	  Delete(tmp);
+	}
+      } else {
+	ns = 0;
+      }
+      if (!ns) {
+	if (is_public(n)) {
+	  Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(n), Getline(n), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(n, "uname")));
+	}
+      } else {
+	/* Only a single symbol is being used.  There are only a few symbols that
+	   we actually care about.  These are typedef, class declarations, and enum */
+	String *ntype = nodeType(ns);
+	if (Strcmp(ntype, "cdecl") == 0) {
+	  if (checkAttribute(ns, "storage", "typedef")) {
+	    /* A typedef declaration */
+	    String *uname = Getattr(n, "uname");
+	    SwigType_typedef_using(uname);
+	  } else {
+	    /* A normal C declaration. */
+	    if ((inclass) && (!GetFlag(n, "feature:ignore")) && (Getattr(n, "sym:name"))) {
+	      Node *c = ns;
+	      Node *unodes = 0, *last_unodes = 0;
+	      int ccount = 0;
+	      String *symname = Getattr(n, "sym:name");
+	      while (c) {
+		if (Strcmp(nodeType(c), "cdecl") == 0) {
+		  if (!(checkAttribute(c, "storage", "static")
+			|| checkAttribute(c, "storage", "typedef")
+			|| checkAttribute(c, "storage", "friend")
+			|| (Getattr(c, "feature:extend") && !Getattr(c, "code"))
+			|| GetFlag(c, "feature:ignore"))) {
+
+		    /* Don't generate a method if the method is overridden in this class, 
+		     * for example don't generate another m(bool) should there be a Base::m(bool) :
+		     * struct Derived : Base { 
+		     *   void m(bool);
+		     *   using Base::m;
+		     * };
+		     */
+		    String *csymname = Getattr(c, "sym:name");
+		    if (!csymname || (Strcmp(csymname, symname) == 0)) {
+		      {
+			String *decl = Getattr(c, "decl");
+			Node *over = Getattr(n, "sym:overloaded");
+			int match = 0;
+			while (over) {
+			  String *odecl = Getattr(over, "decl");
+			  if (Cmp(decl, odecl) == 0) {
+			    match = 1;
+			    break;
+			  }
+			  over = Getattr(over, "sym:nextSibling");
+			}
+			if (match) {
+			  c = Getattr(c, "csym:nextSibling");
+			  continue;
+			}
+		      }
+		      Node *nn = copyNode(c);
+		      Delattr(nn, "access");	// access might be different from the method in the base class
+		      if (!Getattr(nn, "sym:name"))
+			Setattr(nn, "sym:name", symname);
+
+		      if (!GetFlag(nn, "feature:ignore")) {
+			ParmList *parms = CopyParmList(Getattr(c, "parms"));
+			int is_pointer = SwigType_ispointer_return(Getattr(nn, "decl"));
+			int is_void = checkAttribute(nn, "type", "void") && !is_pointer;
+			Setattr(nn, "parms", parms);
+			Delete(parms);
+			if (Getattr(n, "feature:extend")) {
+			  String *ucode = is_void ? NewStringf("{ self->%s(", Getattr(n, "uname")) : NewStringf("{ return self->%s(", Getattr(n, "uname"));
+
+			  for (ParmList *p = parms; p;) {
+			    Append(ucode, Getattr(p, "name"));
+			    p = nextSibling(p);
+			    if (p)
+			      Append(ucode, ",");
+			  }
+			  Append(ucode, "); }");
+			  Setattr(nn, "code", ucode);
+			  Delete(ucode);
+			}
+			ParmList *throw_parm_list = Getattr(c, "throws");
+			if (throw_parm_list)
+			  Setattr(nn, "throws", CopyParmList(throw_parm_list));
+			ccount++;
+			if (!last_unodes) {
+			  last_unodes = nn;
+			  unodes = nn;
+			} else {
+			  Setattr(nn, "previousSibling", last_unodes);
+			  Setattr(last_unodes, "nextSibling", nn);
+			  Setattr(nn, "sym:previousSibling", last_unodes);
+			  Setattr(last_unodes, "sym:nextSibling", nn);
+			  Setattr(nn, "sym:overloaded", unodes);
+			  Setattr(unodes, "sym:overloaded", unodes);
+			  last_unodes = nn;
+			}
+		      } else {
+			Delete(nn);
+		      }
+		    }
+		  }
+		}
+		c = Getattr(c, "csym:nextSibling");
+	      }
+	      if (unodes) {
+		set_firstChild(n, unodes);
+		if (ccount > 1) {
+		  if (!Getattr(n, "sym:overloaded")) {
+		    Setattr(n, "sym:overloaded", n);
+		    Setattr(n, "sym:overname", "_SWIG_0");
+		  }
+		}
+	      }
+
+	      /* Hack the parse tree symbol table for overloaded methods. Replace the "using" node with the
+	       * list of overloaded methods we have just added in as child nodes to the "using" node.
+	       * The node will still exist, it is just the symbol table linked list of overloaded methods
+	       * which is hacked. */
+	      if (Getattr(n, "sym:overloaded"))
+	      {
+#ifdef DEBUG_OVERLOADED
+show_overloaded(n);
+#endif
+		int cnt = 0;
+		Node *debugnode = n;
+		if (!firstChild(n)) {
+		  // Remove from overloaded list ('using' node does not actually end up adding in any methods)
+		  Node *ps = Getattr(n, "sym:previousSibling");
+		  Node *ns = Getattr(n, "sym:nextSibling");
+		  if (ps) {
+		    Setattr(ps, "sym:nextSibling", ns);
+		  }
+		  if (ns) {
+		    Setattr(ns, "sym:previousSibling", ps);
+		  }
+		} else {
+		  // The 'using' node results in methods being added in - slot in the these methods here 
+		  Node *ps = Getattr(n, "sym:previousSibling");
+		  Node *ns = Getattr(n, "sym:nextSibling");
+		  Node *fc = firstChild(n);
+		  Node *pp = fc;
+
+		  Node *firstoverloaded = Getattr(n, "sym:overloaded");
+		  if (firstoverloaded == n) {
+		    // This 'using' node we are cutting out was the first node in the overloaded list. 
+		    // Change the first node in the list to its first sibling
+		    Delattr(firstoverloaded, "sym:overloaded");
+		    Node *nnn = Getattr(firstoverloaded, "sym:nextSibling");
+		    firstoverloaded = fc;
+		    while (nnn) {
+		      Setattr(nnn, "sym:overloaded", firstoverloaded);
+		      nnn = Getattr(nnn, "sym:nextSibling");
+		    }
+		  }
+		  while (pp) {
+		    Node *ppn = Getattr(pp, "sym:nextSibling");
+		    Setattr(pp, "sym:overloaded", firstoverloaded);
+		    Setattr(pp, "sym:overname", NewStringf("%s_%d", Getattr(n, "sym:overname"), cnt++));
+		    if (ppn)
+		      pp = ppn;
+		    else
+		      break;
+		  }
+		  if (ps) {
+		    Setattr(ps, "sym:nextSibling", fc);
+		    Setattr(fc, "sym:previousSibling", ps);
+		  }
+		  if (ns) {
+		    Setattr(ns, "sym:previousSibling", pp);
+		    Setattr(pp, "sym:nextSibling", ns);
+		  }
+		  debugnode = firstoverloaded;
+		}
+		Delattr(n, "sym:previousSibling");
+		Delattr(n, "sym:nextSibling");
+		Delattr(n, "sym:overloaded");
+		Delattr(n, "sym:overname");
+#ifdef DEBUG_OVERLOADED
+show_overloaded(debugnode);
+#endif
+		clean_overloaded(n); // Needed?
+	      }
+	    }
+	  }
+	} else if ((Strcmp(ntype, "class") == 0) || ((Strcmp(ntype, "classforward") == 0))) {
+	  /* We install the using class name as kind of a typedef back to the original class */
+	  String *uname = Getattr(n, "uname");
+	  /* Import into current type scope */
+	  SwigType_typedef_using(uname);
+	} else if (Strcmp(ntype, "enum") == 0) {
+	  SwigType_typedef_using(Getattr(n, "uname"));
+	}
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * typemapDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int typemapDirective(Node *n) {
+    if (inclass || nsname) {
+      Node *items = firstChild(n);
+      while (items) {
+	Parm *pattern = Getattr(items, "pattern");
+	Parm *parms = Getattr(items, "parms");
+	normalize_later(pattern);
+	normalize_later(parms);
+	items = nextSibling(items);
+      }
+    }
+    return SWIG_OK;
+  }
+
+
+  /* ------------------------------------------------------------
+   * typemapcopyDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int typemapcopyDirective(Node *n) {
+    if (inclass || nsname) {
+      Node *items = firstChild(n);
+      ParmList *pattern = Getattr(n, "pattern");
+      normalize_later(pattern);
+      while (items) {
+	ParmList *npattern = Getattr(items, "pattern");
+	normalize_later(npattern);
+	items = nextSibling(items);
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * applyDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int applyDirective(Node *n) {
+    if (inclass || nsname) {
+      ParmList *pattern = Getattr(n, "pattern");
+      normalize_later(pattern);
+      Node *items = firstChild(n);
+      while (items) {
+	Parm *apattern = Getattr(items, "pattern");
+	normalize_later(apattern);
+	items = nextSibling(items);
+      }
+    }
+    return SWIG_OK;
+  }
+
+  /* ------------------------------------------------------------
+   * clearDirective()
+   * ------------------------------------------------------------ */
+
+  virtual int clearDirective(Node *n) {
+    if (inclass || nsname) {
+      Node *p;
+      for (p = firstChild(n); p; p = nextSibling(p)) {
+	ParmList *pattern = Getattr(p, "pattern");
+	normalize_later(pattern);
+      }
+    }
+    return SWIG_OK;
+  }
+
+public:
+  static void pass(Node *n) {
+    TypePass t;
+    t.top(n);
+  }
+};
+
+void Swig_process_types(Node *n) {
+  if (!n)
+    return;
+  TypePass::pass(n);
+}
diff --git a/trunk/Source/Modules/uffi.cxx b/trunk/Source/Modules/uffi.cxx
new file mode 100644
index 0000000..7a94b77
--- /dev/null
+++ b/trunk/Source/Modules/uffi.cxx
@@ -0,0 +1,395 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * uffi.cxx
+ *
+ * Uffi language module for SWIG.
+ * ----------------------------------------------------------------------------- */
+
+// TODO: remove remnants of lisptype
+
+char cvsroot_uffi_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+class UFFI:public Language {
+public:
+
+  virtual void main(int argc, char *argv[]);
+  virtual int top(Node *n);
+  virtual int functionWrapper(Node *n);
+  virtual int constantWrapper(Node *n);
+  virtual int classHandler(Node *n);
+  virtual int membervariableHandler(Node *n);
+
+};
+
+static File *f_cl = 0;
+static File *f_null = 0;
+
+static struct {
+  int count;
+  String **entries;
+} defined_foreign_types;
+
+static const char *identifier_converter = "identifier-convert-null";
+
+static int any_varargs(ParmList *pl) {
+  Parm *p;
+
+  for (p = pl; p; p = nextSibling(p)) {
+    if (SwigType_isvarargs(Getattr(p, "type")))
+      return 1;
+  }
+
+  return 0;
+}
+
+
+/* utilities */
+/* returns new string w/ parens stripped */
+static String *strip_parens(String *string) {
+  char *s = Char(string), *p;
+  int len = Len(string);
+  String *res;
+
+  if (len == 0 || s[0] != '(' || s[len - 1] != ')') {
+    return NewString(string);
+  }
+
+  p = (char *) malloc(len - 2 + 1);
+  if (!p) {
+    Printf(stderr, "Malloc failed\n");
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  strncpy(p, s + 1, len - 1);
+  p[len - 2] = 0;		/* null terminate */
+
+  res = NewString(p);
+  free(p);
+
+  return res;
+}
+
+
+static String *convert_literal(String *num_param, String *type) {
+  String *num = strip_parens(num_param), *res;
+  char *s = Char(num);
+
+  /* Make sure doubles use 'd' instead of 'e' */
+  if (!Strcmp(type, "double")) {
+    String *updated = Copy(num);
+    if (Replace(updated, "e", "d", DOH_REPLACE_ANY) > 1) {
+      Printf(stderr, "Weird!! number %s looks invalid.\n", num);
+      SWIG_exit(EXIT_FAILURE);
+    }
+    Delete(num);
+    return updated;
+  }
+
+  if (SwigType_type(type) == T_CHAR) {
+    /* Use CL syntax for character literals */
+    return NewStringf("#\\%s", num_param);
+  } else if (SwigType_type(type) == T_STRING) {
+    /* Use CL syntax for string literals */
+    return NewStringf("\"%s\"", num_param);
+  }
+
+  if (Len(num) < 2 || s[0] != '0') {
+    return num;
+  }
+
+  /* octal or hex */
+
+  res = NewStringf("#%c%s", s[1] == 'x' ? 'x' : 'o', s + 2);
+  Delete(num);
+
+  return res;
+}
+
+static void add_defined_foreign_type(String *type) {
+  if (!defined_foreign_types.count) {
+    /* Make fresh */
+    defined_foreign_types.count = 1;
+    defined_foreign_types.entries = (String **) malloc(sizeof(String *));
+  } else {
+    /* make room */
+    defined_foreign_types.count++;
+    defined_foreign_types.entries = (String **)
+	realloc(defined_foreign_types.entries, defined_foreign_types.count * sizeof(String *));
+  }
+
+  if (!defined_foreign_types.entries) {
+    Printf(stderr, "Out of memory\n");
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  /* Fill in the new data */
+  defined_foreign_types.entries[defined_foreign_types.count - 1] = Copy(type);
+
+}
+
+
+static String *get_ffi_type(SwigType *ty, const String_or_char *name) {
+  Hash *typemap = Swig_typemap_search("ffitype", ty, name, 0);
+  if (typemap) {
+    String *typespec = Getattr(typemap, "code");
+    return NewString(typespec);
+  } else {
+    SwigType *tr = SwigType_typedef_resolve_all(ty);
+    char *type_reduced = Char(tr);
+    int i;
+
+    //Printf(stdout,"convert_type %s\n", ty);
+    if (SwigType_isconst(tr)) {
+      SwigType_pop(tr);
+      type_reduced = Char(tr);
+    }
+
+    if (SwigType_ispointer(type_reduced) || SwigType_isarray(ty) || !strncmp(type_reduced, "p.f", 3)) {
+      return NewString(":pointer-void");
+    }
+
+    for (i = 0; i < defined_foreign_types.count; i++) {
+      if (!Strcmp(ty, defined_foreign_types.entries[i])) {
+	return NewStringf("#.(%s \"%s\" :type :type)", identifier_converter, ty);
+      }
+    }
+
+    if (!Strncmp(type_reduced, "enum ", 5)) {
+      return NewString(":int");
+    }
+
+    Printf(stderr, "Unsupported data type: %s (was: %s)\n", type_reduced, ty);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  return 0;
+}
+
+static String *get_lisp_type(SwigType *ty, const String_or_char *name) {
+  Hash *typemap = Swig_typemap_search("lisptype", ty, name, 0);
+  if (typemap) {
+    String *typespec = Getattr(typemap, "code");
+    return NewString(typespec);
+  } else {
+    return NewString("");
+  }
+}
+
+void UFFI::main(int argc, char *argv[]) {
+  int i;
+
+  SWIG_library_directory("uffi");
+  SWIG_config_file("uffi.swg");
+
+
+  for (i = 1; i < argc; i++) {
+    if (!strcmp(argv[i], "-identifier-converter")) {
+      char *conv = argv[i + 1];
+
+      if (!conv)
+	Swig_arg_error();
+
+      Swig_mark_arg(i);
+      Swig_mark_arg(i + 1);
+      i++;
+
+      /* check for built-ins */
+      if (!strcmp(conv, "lispify")) {
+	identifier_converter = "identifier-convert-lispify";
+      } else if (!strcmp(conv, "null")) {
+	identifier_converter = "identifier-convert-null";
+      } else {
+	/* Must be user defined */
+	char *idconv = new char[strlen(conv) + 1];
+	strcpy(idconv, conv);
+	identifier_converter = idconv;
+      }
+    }
+
+    if (!strcmp(argv[i], "-help")) {
+      fprintf(stdout, "UFFI Options (available with -uffi)\n");
+      fprintf(stdout,
+	      "    -identifier-converter <type or funcname>\n"
+	      "\tSpecifies the type of conversion to do on C identifiers to convert\n"
+	      "\tthem to symbols.  There are two built-in converters:  'null' and\n"
+	      "\t 'lispify'.  The default is 'null'.  If you supply a name other\n"
+	      "\tthan one of the built-ins, then a function by that name will be\n"
+	      "\tcalled to convert identifiers to symbols.\n");
+    }
+  }
+}
+
+int UFFI::top(Node *n) {
+  String *module = Getattr(n, "name");
+  String *output_filename = NewString("");
+  String *devnull = NewString("/dev/null");
+
+  f_null = NewFile(devnull, "w+");
+  if (!f_null) {
+    FileErrorDisplay(devnull);
+    SWIG_exit(EXIT_FAILURE);
+  }
+  Delete(devnull);
+
+
+  Printf(output_filename, "%s%s.cl", SWIG_output_directory(), module);
+
+
+  f_cl = NewFile(output_filename, "w");
+  if (!f_cl) {
+    FileErrorDisplay(output_filename);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  Swig_register_filebyname("header", f_null);
+  Swig_register_filebyname("runtime", f_null);
+  Swig_register_filebyname("wrapper", f_cl);
+
+  Printf(f_cl,
+	 ";; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; package: %s -*-\n;; This is an automatically generated file.  Make changes in\n;; the definition file, not here.\n\n(defpackage :%s\n  (:use :common-lisp :uffi))\n\n(in-package :%s)\n",
+	 module, module, module);
+  Printf(f_cl, "(eval-when (compile load eval)\n  (defparameter *swig-identifier-converter* '%s))\n", identifier_converter);
+
+  Language::top(n);
+
+  Close(f_cl);
+  Delete(f_cl);			// Delete the handle, not the file
+  Close(f_null);
+  Delete(f_null);
+
+  return SWIG_OK;
+}
+
+int UFFI::functionWrapper(Node *n) {
+  String *funcname = Getattr(n, "sym:name");
+  ParmList *pl = Getattr(n, "parms");
+  Parm *p;
+  int argnum = 0, first = 1, varargs = 0;
+
+  //Language::functionWrapper(n);
+
+  Printf(f_cl, "(swig-defun \"%s\"\n", funcname);
+  Printf(f_cl, "  (");
+
+  /* Special cases */
+
+  if (ParmList_len(pl) == 0) {
+    Printf(f_cl, ":void");
+  } else if (any_varargs(pl)) {
+    Printf(f_cl, "#| varargs |#");
+    varargs = 1;
+  } else {
+    for (p = pl; p; p = nextSibling(p), argnum++) {
+      String *argname = Getattr(p, "name");
+      SwigType *argtype = Getattr(p, "type");
+      String *ffitype = get_ffi_type(argtype, argname);
+      String *lisptype = get_lisp_type(argtype, argname);
+      int tempargname = 0;
+
+      if (!argname) {
+	argname = NewStringf("arg%d", argnum);
+	tempargname = 1;
+      }
+
+      if (!first) {
+	Printf(f_cl, "\n   ");
+      }
+      Printf(f_cl, "(%s %s %s)", argname, ffitype, lisptype);
+      first = 0;
+
+      Delete(ffitype);
+      Delete(lisptype);
+      if (tempargname)
+	Delete(argname);
+
+    }
+  }
+  Printf(f_cl, ")\n");		/* finish arg list */
+  Printf(f_cl, "  :returning %s\n"
+	 //"  :strings-convert t\n"
+	 //"  :call-direct %s\n"
+	 //"  :optimize-for-space t"
+	 ")\n", get_ffi_type(Getattr(n, "type"), "result")
+	 //,varargs ? "nil"  : "t"
+      );
+
+
+  return SWIG_OK;
+}
+
+int UFFI::constantWrapper(Node *n) {
+  String *type = Getattr(n, "type");
+  String *converted_value = convert_literal(Getattr(n, "value"), type);
+  String *name = Getattr(n, "sym:name");
+
+#if 0
+  Printf(stdout, "constant %s is of type %s. value: %s\n", name, type, converted_value);
+#endif
+
+  Printf(f_cl, "(swig-defconstant \"%s\" %s)\n", name, converted_value);
+
+  Delete(converted_value);
+
+  return SWIG_OK;
+}
+
+// Includes structs
+int UFFI::classHandler(Node *n) {
+
+  String *name = Getattr(n, "sym:name");
+  String *kind = Getattr(n, "kind");
+  Node *c;
+
+  if (Strcmp(kind, "struct")) {
+    Printf(stderr, "Don't know how to deal with %s kind of class yet.\n", kind);
+    Printf(stderr, " (name: %s)\n", name);
+    SWIG_exit(EXIT_FAILURE);
+  }
+
+  Printf(f_cl, "(swig-def-struct \"%s\"\n \n", name);
+
+  for (c = firstChild(n); c; c = nextSibling(c)) {
+    SwigType *type = Getattr(c, "type");
+    SwigType *decl = Getattr(c, "decl");
+    type = Copy(type);
+    SwigType_push(type, decl);
+    String *lisp_type;
+
+    if (Strcmp(nodeType(c), "cdecl")) {
+      Printf(stderr, "Structure %s has a slot that we can't deal with.\n", name);
+      Printf(stderr, "nodeType: %s, name: %s, type: %s\n", nodeType(c), Getattr(c, "name"), Getattr(c, "type"));
+      SWIG_exit(EXIT_FAILURE);
+    }
+
+
+    /* Printf(stdout, "Converting %s in %s\n", type, name); */
+    lisp_type = get_ffi_type(type, Getattr(c, "sym:name"));
+
+    Printf(f_cl, "  (#.(%s \"%s\" :type :slot) %s)\n", identifier_converter, Getattr(c, "sym:name"), lisp_type);
+
+    Delete(lisp_type);
+  }
+
+  // Language::classHandler(n);
+
+  Printf(f_cl, " )\n");
+
+  /* Add this structure to the known lisp types */
+  //Printf(stdout, "Adding %s foreign type\n", name);
+  add_defined_foreign_type(name);
+
+  return SWIG_OK;
+}
+
+int UFFI::membervariableHandler(Node *n) {
+  Language::membervariableHandler(n);
+  return SWIG_OK;
+}
+
+
+extern "C" Language *swig_uffi(void) {
+  return new UFFI();
+}
diff --git a/trunk/Source/Modules/utils.cxx b/trunk/Source/Modules/utils.cxx
new file mode 100644
index 0000000..bf82119
--- /dev/null
+++ b/trunk/Source/Modules/utils.cxx
@@ -0,0 +1,98 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * utils.cxx
+ *
+ * Various utility functions.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_utils_cxx[] = "$Id$";
+
+#include <swigmod.h>
+
+int is_public(Node *n) {
+  String *access = Getattr(n, "access");
+  return !access || !Cmp(access, "public");
+}
+
+int is_private(Node *n) {
+  String *access = Getattr(n, "access");
+  return access && !Cmp(access, "private");
+}
+
+int is_protected(Node *n) {
+  String *access = Getattr(n, "access");
+  return access && !Cmp(access, "protected");
+}
+
+static int is_member_director_helper(Node *parentnode, Node *member) {
+  int parent_nodirector = GetFlag(parentnode, "feature:nodirector");
+  if (parent_nodirector)
+    return 0;
+  int parent_director = Swig_director_mode() && GetFlag(parentnode, "feature:director");
+  int cdecl_director = parent_director || GetFlag(member, "feature:director");
+  int cdecl_nodirector = GetFlag(member, "feature:nodirector");
+  return cdecl_director && !cdecl_nodirector && !GetFlag(member, "feature:extend");
+}
+
+int is_member_director(Node *parentnode, Node *member) {
+  if (parentnode && checkAttribute(member, "storage", "virtual")) {
+    return is_member_director_helper(parentnode, member);
+  } else {
+    return 0;
+  }
+}
+
+int is_member_director(Node *member) {
+  return is_member_director(Getattr(member, "parentNode"), member);
+}
+
+// Identifies the additional protected members that are generated when the allprotected option is used.
+// This does not include protected virtual methods as they are turned on with the dirprot option.
+int is_non_virtual_protected_access(Node *n) {
+  int result = 0;
+  if (Swig_director_mode() && Swig_director_protected_mode() && Swig_all_protected_mode() && is_protected(n) && !checkAttribute(n, "storage", "virtual")) {
+    if (is_member_director_helper(Getattr(n, "parentNode"), n))
+      result = 1;
+  }
+  return result;
+}
+
+/* Clean overloaded list.  Removes templates, ignored, and errors */
+
+void clean_overloaded(Node *n) {
+  Node *nn = Getattr(n, "sym:overloaded");
+  Node *first = 0;
+  while (nn) {
+    String *ntype = nodeType(nn);
+    if ((GetFlag(nn, "feature:ignore")) ||
+	(Getattr(nn, "error")) ||
+	(Strcmp(ntype, "template") == 0) ||
+	((Strcmp(ntype, "cdecl") == 0) && is_protected(nn) && !is_member_director(nn) && !is_non_virtual_protected_access(n))) {
+      /* Remove from overloaded list */
+      Node *ps = Getattr(nn, "sym:previousSibling");
+      Node *ns = Getattr(nn, "sym:nextSibling");
+      if (ps) {
+	Setattr(ps, "sym:nextSibling", ns);
+      }
+      if (ns) {
+	Setattr(ns, "sym:previousSibling", ps);
+      }
+      Delattr(nn, "sym:previousSibling");
+      Delattr(nn, "sym:nextSibling");
+      Delattr(nn, "sym:overloaded");
+      nn = ns;
+      continue;
+    } else {
+      if (!first)
+	first = nn;
+      Setattr(nn, "sym:overloaded", first);
+    }
+    nn = Getattr(nn, "sym:nextSibling");
+  }
+  if (!first || (first && !Getattr(first, "sym:nextSibling"))) {
+    if (Getattr(n, "sym:overloaded"))
+      Delattr(n, "sym:overloaded");
+  }
+}
diff --git a/trunk/Source/Modules/xml.cxx b/trunk/Source/Modules/xml.cxx
new file mode 100644
index 0000000..c74b48d
--- /dev/null
+++ b/trunk/Source/Modules/xml.cxx
@@ -0,0 +1,320 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * xml.cxx
+ *
+ * An Xml parse tree generator.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_xml_cxx[] = "$Id$";
+
+#include "swigmod.h"
+
+static const char *usage = "\
+XML Options (available with -xml)\n\
+     -xmllang <lang> - Typedef language\n\
+     -xmllite        - More lightweight version of XML\n\
+     ------\n\
+     deprecated (use -o): -xml <output.xml> - Use <output.xml> as output file (extension .xml mandatory)\n";
+
+static File *out = 0;
+static int xmllite = 0;
+
+
+class XML:public Language {
+public:
+
+  int indent_level;
+  long id;
+
+  XML() :indent_level(0) , id(0) {
+  }
+  
+  virtual ~ XML() {
+  }
+
+  virtual void main(int argc, char *argv[]) {
+    SWIG_typemap_lang("xml");
+    for (int iX = 0; iX < argc; iX++) {
+      if (strcmp(argv[iX], "-xml") == 0) {
+	char *extension = 0;
+	if (iX + 1 >= argc)
+	  continue;
+	extension = argv[iX + 1] + strlen(argv[iX + 1]) - 4;
+	if (strcmp(extension, ".xml"))
+	  continue;
+	iX++;
+	Swig_mark_arg(iX);
+	String *outfile = NewString(argv[iX]);
+	out = NewFile(outfile, "w");
+	if (!out) {
+	  FileErrorDisplay(outfile);
+	  SWIG_exit(EXIT_FAILURE);
+	}
+	continue;
+      }
+      if (strcmp(argv[iX], "-xmllang") == 0) {
+	Swig_mark_arg(iX);
+	iX++;
+	SWIG_typemap_lang(argv[iX]);
+	Swig_mark_arg(iX);
+	continue;
+      }
+      if (strcmp(argv[iX], "-help") == 0) {
+	fputs(usage, stdout);
+      }
+      if (strcmp(argv[iX], "-xmllite") == 0) {
+	Swig_mark_arg(iX);
+	xmllite = 1;
+      }
+    }
+
+    // Add a symbol to the parser for conditional compilation
+    Preprocessor_define("SWIGXML 1", 0);
+  }
+
+  /* Top of the parse tree */
+
+  virtual int top(Node *n) {
+    if (out == 0) {
+      String *outfile = Getattr(n, "outfile");
+      Replaceall(outfile, ".cxx", ".xml");
+      Replaceall(outfile, ".cpp", ".xml");
+      Replaceall(outfile, ".c", ".xml");
+      out = NewFile(outfile, "w");
+      if (!out) {
+	FileErrorDisplay(outfile);
+	SWIG_exit(EXIT_FAILURE);
+      }
+    }
+    Printf(out, "<?xml version=\"1.0\" ?> \n");
+    Xml_print_tree(n);
+    return SWIG_OK;
+  }
+
+  void print_indent(int l) {
+    int i;
+    for (i = 0; i < indent_level; i++) {
+      Printf(out, " ");
+    }
+    if (l) {
+      Printf(out, " ");
+    }
+  }
+
+  void Xml_print_tree(DOH *obj) {
+    while (obj) {
+      Xml_print_node(obj);
+      obj = nextSibling(obj);
+    }
+  }
+
+  void Xml_print_attributes(Node *obj) {
+    String *k;
+    indent_level += 4;
+    print_indent(0);
+    Printf(out, "<attributelist id=\"%ld\" addr=\"%x\" >\n", ++id, obj);
+    indent_level += 4;
+    Iterator ki;
+    ki = First(obj);
+    while (ki.key) {
+      k = ki.key;
+      if ((Cmp(k, "nodeType") == 0)
+	  || (Cmp(k, "firstChild") == 0)
+	  || (Cmp(k, "lastChild") == 0)
+	  || (Cmp(k, "parentNode") == 0)
+	  || (Cmp(k, "nextSibling") == 0)
+	  || (Cmp(k, "previousSibling") == 0)
+	  || (*(Char(k)) == '$')) {
+	/* Do nothing */
+      } else if (Cmp(k, "module") == 0) {
+	Xml_print_module(Getattr(obj, k));
+      } else if (Cmp(k, "baselist") == 0) {
+	Xml_print_baselist(Getattr(obj, k));
+      } else if (!xmllite && Cmp(k, "typescope") == 0) {
+	Xml_print_typescope(Getattr(obj, k));
+      } else if (!xmllite && Cmp(k, "typetab") == 0) {
+	Xml_print_typetab(Getattr(obj, k));
+      } else if (Cmp(k, "kwargs") == 0) {
+	Xml_print_kwargs(Getattr(obj, k));
+      } else if (Cmp(k, "parms") == 0 || Cmp(k, "pattern") == 0) {
+	Xml_print_parmlist(Getattr(obj, k));
+      } else {
+	DOH *o;
+	print_indent(0);
+	if (DohIsString(Getattr(obj, k))) {
+	  String *ck = NewString(k);
+	  o = Str(Getattr(obj, k));
+	  Replaceall(ck, ":", "_");
+	  Replaceall(ck, "<", "&lt;");
+	  /* Do first to avoid aliasing errors. */
+	  Replaceall(o, "&", "&amp;");
+	  Replaceall(o, "<", "&lt;");
+	  Replaceall(o, "\"", "&quot;");
+	  Replaceall(o, "\\", "\\\\");
+	  Replaceall(o, "\n", "&#10;");
+	  Printf(out, "<attribute name=\"%s\" value=\"%s\" id=\"%ld\" addr=\"%x\" />\n", ck, o, ++id, o);
+	  Delete(o);
+	  Delete(ck);
+	} else {
+	  o = Getattr(obj, k);
+	  String *ck = NewString(k);
+	  Replaceall(ck, ":", "_");
+	  Printf(out, "<attribute name=\"%s\" value=\"%x\" id=\"%ld\" addr=\"%x\" />\n", ck, o, ++id, o);
+	  Delete(ck);
+	}
+      }
+      ki = Next(ki);
+    }
+    indent_level -= 4;
+    print_indent(0);
+    Printf(out, "</attributelist >\n");
+    indent_level -= 4;
+  }
+
+  void Xml_print_node(Node *obj) {
+    Node *cobj;
+
+    print_indent(0);
+    Printf(out, "<%s id=\"%ld\" addr=\"%x\" >\n", nodeType(obj), ++id, obj);
+    Xml_print_attributes(obj);
+    cobj = firstChild(obj);
+    if (cobj) {
+      indent_level += 4;
+      Printf(out, "\n");
+      Xml_print_tree(cobj);
+      indent_level -= 4;
+    } else {
+      print_indent(1);
+      Printf(out, "\n");
+    }
+    print_indent(0);
+    Printf(out, "</%s >\n", nodeType(obj));
+  }
+
+
+  void Xml_print_parmlist(ParmList *p) {
+
+    print_indent(0);
+    Printf(out, "<parmlist id=\"%ld\" addr=\"%x\" >\n", ++id, p);
+    indent_level += 4;
+    while (p) {
+      print_indent(0);
+      Printf(out, "<parm id=\"%ld\">\n", ++id);
+      Xml_print_attributes(p);
+      print_indent(0);
+      Printf(out, "</parm >\n");
+      p = nextSibling(p);
+    }
+    indent_level -= 4;
+    print_indent(0);
+    Printf(out, "</parmlist >\n");
+  }
+
+  void Xml_print_baselist(List *p) {
+
+    print_indent(0);
+    Printf(out, "<baselist id=\"%ld\" addr=\"%x\" >\n", ++id, p);
+    indent_level += 4;
+    Iterator s;
+    for (s = First(p); s.item; s = Next(s)) {
+      print_indent(0);
+      String *item_name = Xml_escape_string(s.item);
+      Printf(out, "<base name=\"%s\" id=\"%ld\" addr=\"%x\" />\n", item_name, ++id, s.item);
+      Delete(item_name);
+    }
+    indent_level -= 4;
+    print_indent(0);
+    Printf(out, "</baselist >\n");
+  }
+
+  String *Xml_escape_string(String *str) {
+    String *escaped_str = 0;
+    if (str) {
+      escaped_str = NewString(str);
+      Replaceall(escaped_str, "&", "&amp;");
+      Replaceall(escaped_str, "<", "&lt;");
+      Replaceall(escaped_str, "\"", "&quot;");
+      Replaceall(escaped_str, "\\", "\\\\");
+      Replaceall(escaped_str, "\n", "&#10;");
+    }
+    return escaped_str;
+  }
+
+  void Xml_print_module(Node *p) {
+
+    print_indent(0);
+    Printf(out, "<attribute name=\"module\" value=\"%s\" id=\"%ld\" addr=\"%x\" />\n", Getattr(p, "name"), ++id, p);
+  }
+
+  void Xml_print_kwargs(Hash *p) {
+    Xml_print_hash(p, "kwargs");
+  }
+
+  void Xml_print_typescope(Hash *p) {
+
+    Xml_print_hash(p, "typescope");
+  }
+
+  void Xml_print_typetab(Hash *p) {
+
+    Xml_print_hash(p, "typetab");
+  }
+
+
+  void Xml_print_hash(Hash *p, const char *markup) {
+
+    print_indent(0);
+    Printf(out, "<%s id=\"%ld\" addr=\"%x\" >\n", markup, ++id, p);
+    Xml_print_attributes(p);
+    indent_level += 4;
+    Iterator n = First(p);
+    while (n.key) {
+      print_indent(0);
+      Printf(out, "<%ssitem id=\"%ld\" addr=\"%x\" >\n", markup, ++id, n.item);
+      Xml_print_attributes(n.item);
+      print_indent(0);
+      Printf(out, "</%ssitem >\n", markup);
+      n = Next(n);
+    }
+    indent_level -= 4;
+    print_indent(0);
+    Printf(out, "</%s >\n", markup);
+  }
+
+};
+
+/* -----------------------------------------------------------------------------
+ * Swig_print_xml
+ *
+ * Dump an XML version of the parse tree.  This is different from using the -xml
+ * language module normally as it allows the real language module to process the
+ * tree first, possibly stuffing in new attributes, so the XML that is output ends
+ * up being a post-processing version of the tree.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_print_xml(DOH *obj, String *filename) {
+  XML xml;
+  xmllite = 1;
+
+  if (!filename) {
+    out = stdout;
+  } else {
+    out = NewFile(filename, "w");
+    if (!out) {
+      FileErrorDisplay(filename);
+      SWIG_exit(EXIT_FAILURE);
+    }
+  }
+
+  Printf(out, "<?xml version=\"1.0\" ?> \n");
+  xml.Xml_print_tree(obj);
+}
+
+static Language *new_swig_xml() {
+  return new XML();
+}
+extern "C" Language *swig_xml(void) {
+  return new_swig_xml();
+}
diff --git a/trunk/Source/Preprocessor/cpp.c b/trunk/Source/Preprocessor/cpp.c
new file mode 100644
index 0000000..c04f95f
--- /dev/null
+++ b/trunk/Source/Preprocessor/cpp.c
@@ -0,0 +1,1859 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cpp.c
+ *
+ * An implementation of a C preprocessor plus some support for additional
+ * SWIG directives.
+ *
+ * - SWIG directives such as %include, %extern, and %import are handled
+ * - A new macro %define ... %enddef can be used for multiline macros
+ * - No preprocessing is performed in %{ ... %} blocks
+ * - Lines beginning with %# are stripped down to #... and passed through.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_cpp_c[] = "$Id$";
+
+#include "swig.h"
+#include "preprocessor.h"
+#include <ctype.h>
+
+static Hash *cpp = 0;		/* C preprocessor data */
+static int include_all = 0;	/* Follow all includes */
+static int ignore_missing = 0;
+static int import_all = 0;	/* Follow all includes, but as %import statements */
+static int imported_depth = 0;	/* Depth of %imported files */
+static int single_include = 1;	/* Only include each file once */
+static Hash *included_files = 0;
+static List *dependencies = 0;
+static Scanner *id_scan = 0;
+static int error_as_warning = 0;	/* Understand the cpp #error directive as a special #warning */
+
+/* Test a character to see if it starts an identifier */
+#define isidentifier(c) ((isalpha(c)) || (c == '_') || (c == '$'))
+
+/* Test a character to see if it valid in an identifier (after the first letter) */
+#define isidchar(c) ((isalnum(c)) || (c == '_') || (c == '$'))
+
+DOH *Preprocessor_replace(DOH *);
+
+/* Skip whitespace */
+static void skip_whitespace(String *s, String *out) {
+  int c;
+  while ((c = Getc(s)) != EOF) {
+    if (!isspace(c)) {
+      Ungetc(c, s);
+      break;
+    } else if (out)
+      Putc(c, out);
+  }
+}
+
+/* Skip to a specified character taking line breaks into account */
+static int skip_tochar(String *s, int ch, String *out) {
+  int c;
+  while ((c = Getc(s)) != EOF) {
+    if (out)
+      Putc(c, out);
+    if (c == ch)
+      break;
+    if (c == '\\') {
+      c = Getc(s);
+      if ((c != EOF) && (out))
+	Putc(c, out);
+    }
+  }
+  if (c == EOF)
+    return -1;
+  return 0;
+}
+
+static void copy_location(const DOH *s1, DOH *s2) {
+  Setfile(s2, Getfile((DOH *) s1));
+  Setline(s2, Getline((DOH *) s1));
+}
+
+static String *cpp_include(String_or_char *fn, int sysfile) {
+  String *s = sysfile ? Swig_include_sys(fn) : Swig_include(fn);
+  if (s && single_include) {
+    String *file = Getfile(s);
+    if (Getattr(included_files, file)) {
+      Delete(s);
+      return 0;
+    }
+    Setattr(included_files, file, file);
+  }
+  if (!s) {
+    Seek(fn, 0, SEEK_SET);
+    if (ignore_missing) {
+      Swig_warning(WARN_PP_MISSING_FILE, Getfile(fn), Getline(fn), "Unable to find '%s'\n", fn);
+    } else {
+      Swig_error(Getfile(fn), Getline(fn), "Unable to find '%s'\n", fn);
+    }
+  } else {
+    String *lf;
+    Seek(s, 0, SEEK_SET);
+    if (!dependencies) {
+      dependencies = NewList();
+    }
+    lf = Copy(Swig_last_file());
+    Append(dependencies, lf);
+    Delete(lf);
+  }
+  return s;
+}
+
+List *Preprocessor_depend(void) {
+  return dependencies;
+}
+
+/* -----------------------------------------------------------------------------
+ * void Preprocessor_cpp_init() - Initialize the preprocessor
+ * ----------------------------------------------------------------------------- */
+static String *kpp_args = 0;
+static String *kpp_define = 0;
+static String *kpp_defined = 0;
+static String *kpp_elif = 0;
+static String *kpp_else = 0;
+static String *kpp_endif = 0;
+static String *kpp_expanded = 0;
+static String *kpp_if = 0;
+static String *kpp_ifdef = 0;
+static String *kpp_ifndef = 0;
+static String *kpp_name = 0;
+static String *kpp_swigmacro = 0;
+static String *kpp_symbols = 0;
+static String *kpp_undef = 0;
+static String *kpp_value = 0;
+static String *kpp_varargs = 0;
+static String *kpp_error = 0;
+static String *kpp_warning = 0;
+static String *kpp_line = 0;
+static String *kpp_include = 0;
+static String *kpp_pragma = 0;
+static String *kpp_level = 0;
+
+static String *kpp_dline = 0;
+static String *kpp_ddefine = 0;
+static String *kpp_dinclude = 0;
+static String *kpp_dimport = 0;
+static String *kpp_dextern = 0;
+
+static String *kpp_LINE = 0;
+static String *kpp_FILE = 0;
+
+void Preprocessor_init(void) {
+  Hash *s;
+
+  kpp_args = NewString("args");
+  kpp_define = NewString("define");
+  kpp_defined = NewString("defined");
+  kpp_else = NewString("else");
+  kpp_elif = NewString("elif");
+  kpp_endif = NewString("endif");
+  kpp_expanded = NewString("*expanded*");
+  kpp_if = NewString("if");
+  kpp_ifdef = NewString("ifdef");
+  kpp_ifndef = NewString("ifndef");
+  kpp_name = NewString("name");
+  kpp_swigmacro = NewString("swigmacro");
+  kpp_symbols = NewString("symbols");
+  kpp_undef = NewString("undef");
+  kpp_value = NewString("value");
+  kpp_error = NewString("error");
+  kpp_warning = NewString("warning");
+  kpp_pragma = NewString("pragma");
+  kpp_level = NewString("level");
+  kpp_line = NewString("line");
+  kpp_include = NewString("include");
+  kpp_varargs = NewString("varargs");
+
+  kpp_dinclude = NewString("%include");
+  kpp_dimport = NewString("%import");
+  kpp_dextern = NewString("%extern");
+  kpp_ddefine = NewString("%define");
+  kpp_dline = NewString("%line");
+
+
+  kpp_LINE = NewString("__LINE__");
+  kpp_FILE = NewString("__FILE__");
+
+  cpp = NewHash();
+  s = NewHash();
+  Setattr(cpp, kpp_symbols, s);
+  Delete(s);
+  Preprocessor_expr_init();	/* Initialize the expression evaluator */
+  included_files = NewHash();
+
+  id_scan = NewScanner();;
+
+}
+
+void Preprocessor_delete(void) {
+  Delete(kpp_args);
+  Delete(kpp_define);
+  Delete(kpp_defined);
+  Delete(kpp_else);
+  Delete(kpp_elif);
+  Delete(kpp_endif);
+  Delete(kpp_expanded);
+  Delete(kpp_if);
+  Delete(kpp_ifdef);
+  Delete(kpp_ifndef);
+  Delete(kpp_name);
+  Delete(kpp_swigmacro);
+  Delete(kpp_symbols);
+  Delete(kpp_undef);
+  Delete(kpp_value);
+  Delete(kpp_error);
+  Delete(kpp_warning);
+  Delete(kpp_pragma);
+  Delete(kpp_level);
+  Delete(kpp_line);
+  Delete(kpp_include);
+  Delete(kpp_varargs);
+
+  Delete(kpp_dinclude);
+  Delete(kpp_dimport);
+  Delete(kpp_dextern);
+  Delete(kpp_ddefine);
+  Delete(kpp_dline);
+
+
+  Delete(kpp_LINE);
+  Delete(kpp_FILE);
+  Delete(cpp);
+  Delete(included_files);
+  Preprocessor_expr_delete();
+  DelScanner(id_scan);
+
+  Delete(dependencies);
+
+  Delete(Swig_add_directory(0));
+}
+
+/* -----------------------------------------------------------------------------
+ * void Preprocessor_include_all() - Instruct preprocessor to include all files
+ * ----------------------------------------------------------------------------- */
+void Preprocessor_include_all(int a) {
+  include_all = a;
+}
+
+void Preprocessor_import_all(int a) {
+  import_all = a;
+}
+
+void Preprocessor_ignore_missing(int a) {
+  ignore_missing = a;
+}
+
+void Preprocessor_error_as_warning(int a) {
+  error_as_warning = a;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Preprocessor_define()
+ *
+ * Defines a new C preprocessor symbol.   swigmacro specifies whether or not the macro has
+ * SWIG macro semantics.
+ * ----------------------------------------------------------------------------- */
+
+
+String_or_char *Macro_vararg_name(String_or_char *str, String_or_char *line) {
+  String_or_char *argname, *varargname;
+  char *s, *dots;
+
+  argname = Copy(str);
+  s = Char(argname);
+  dots = strchr(s, '.');
+  if (!dots) {
+    Delete(argname);
+    return NULL;
+  }
+
+  if (strcmp(dots, "...") != 0) {
+    Swig_error(Getfile(line), Getline(line), "Illegal macro argument name '%s'\n", str);
+    Delete(argname);
+    return NULL;
+  }
+  if (dots == s) {
+    varargname = NewString("__VA_ARGS__");
+  } else {
+    *dots = '\0';
+    varargname = NewString(s);
+  }
+  Delete(argname);
+  return varargname;
+}
+
+Hash *Preprocessor_define(const String_or_char *_str, int swigmacro) {
+  String *macroname = 0, *argstr = 0, *macrovalue = 0, *file = 0, *s = 0;
+  Hash *macro = 0, *symbols = 0, *m1;
+  List *arglist = 0;
+  int c, line;
+  int varargs = 0;
+  String_or_char *str = (String_or_char *) _str;
+
+  assert(cpp);
+  assert(str);
+
+  /* First make sure that string is actually a string */
+  if (DohCheck(str)) {
+    s = Copy(str);
+    copy_location(str, s);
+    str = s;
+  } else {
+    str = NewString((char *) str);
+  }
+  Seek(str, 0, SEEK_SET);
+  line = Getline(str);
+  file = Getfile(str);
+
+  /* Skip over any leading whitespace */
+  skip_whitespace(str, 0);
+
+  /* Now look for a macro name */
+  macroname = NewStringEmpty();
+  while ((c = Getc(str)) != EOF) {
+    if (c == '(') {
+      argstr = NewStringEmpty();
+      copy_location(str, argstr);
+      /* It is a macro.  Go extract its argument string */
+      while ((c = Getc(str)) != EOF) {
+	if (c == ')')
+	  break;
+	else
+	  Putc(c, argstr);
+      }
+      if (c != ')') {
+	Swig_error(Getfile(str), Getline(str), "Missing \')\' in macro parameters\n");
+	goto macro_error;
+      }
+      break;
+    } else if (isidchar(c) || (c == '%')) {
+      Putc(c, macroname);
+    } else if (isspace(c)) {
+      break;
+    } else if (c == '\\') {
+      c = Getc(str);
+      if (c != '\n') {
+	Ungetc(c, str);
+	Ungetc('\\', str);
+	break;
+      }
+    } else {
+      /*Swig_error(Getfile(str),Getline(str),"Illegal character in macro name\n");
+         goto macro_error; */
+      Ungetc(c, str);
+      break;
+    }
+  }
+  if (!swigmacro)
+    skip_whitespace(str, 0);
+  macrovalue = NewStringEmpty();
+  while ((c = Getc(str)) != EOF) {
+    Putc(c, macrovalue);
+  }
+
+  /* If there are any macro arguments, convert into a list */
+  if (argstr) {
+    String *argname, *varargname;
+    arglist = NewList();
+    Seek(argstr, 0, SEEK_SET);
+    argname = NewStringEmpty();
+    while ((c = Getc(argstr)) != EOF) {
+      if (c == ',') {
+	varargname = Macro_vararg_name(argname, str);
+	if (varargname) {
+	  Delete(varargname);
+	  Swig_error(Getfile(str), Getline(str), "Variable-length macro argument must be last parameter\n");
+	} else {
+	  Append(arglist, argname);
+	}
+	Delete(argname);
+	argname = NewStringEmpty();
+      } else if (isidchar(c) || (c == '.')) {
+	Putc(c, argname);
+      } else if (!(isspace(c) || (c == '\\'))) {
+	Delete(argname);
+	Swig_error(Getfile(str), Getline(str), "Illegal character in macro argument name\n");
+	goto macro_error;
+      }
+    }
+    if (Len(argname)) {
+      /* Check for varargs */
+      varargname = Macro_vararg_name(argname, str);
+      if (varargname) {
+	Append(arglist, varargname);
+	Delete(varargname);
+	varargs = 1;
+      } else {
+	Append(arglist, argname);
+      }
+    }
+    Delete(argname);
+  }
+
+  if (!swigmacro) {
+    Replace(macrovalue, "\\\n", " ", DOH_REPLACE_NOQUOTE);
+  }
+
+  /* Look for special # substitutions.   We only consider # that appears
+     outside of quotes and comments */
+
+  {
+    int state = 0;
+    char *cc = Char(macrovalue);
+    while (*cc) {
+      switch (state) {
+      case 0:
+	if (*cc == '#')
+	  *cc = '\001';
+	else if (*cc == '/')
+	  state = 10;
+	else if (*cc == '\'')
+	  state = 20;
+	else if (*cc == '\"')
+	  state = 30;
+	break;
+      case 10:
+	if (*cc == '*')
+	  state = 11;
+	else if (*cc == '/')
+	  state = 15;
+	else {
+	  state = 0;
+	  cc--;
+	}
+	break;
+      case 11:
+	if (*cc == '*')
+	  state = 12;
+	break;
+      case 12:
+	if (*cc == '/')
+	  state = 0;
+	else if (*cc != '*')
+	  state = 11;
+	break;
+      case 15:
+	if (*cc == '\n')
+	  state = 0;
+	break;
+      case 20:
+	if (*cc == '\'')
+	  state = 0;
+	if (*cc == '\\')
+	  state = 21;
+	break;
+      case 21:
+	state = 20;
+	break;
+      case 30:
+	if (*cc == '\"')
+	  state = 0;
+	if (*cc == '\\')
+	  state = 31;
+	break;
+      case 31:
+	state = 30;
+	break;
+      default:
+	break;
+      }
+      cc++;
+    }
+  }
+
+  /* Get rid of whitespace surrounding # */
+  /*  Replace(macrovalue,"#","\001",DOH_REPLACE_NOQUOTE); */
+  while (strstr(Char(macrovalue), "\001 ")) {
+    Replace(macrovalue, "\001 ", "\001", DOH_REPLACE_ANY);
+  }
+  while (strstr(Char(macrovalue), " \001")) {
+    Replace(macrovalue, " \001", "\001", DOH_REPLACE_ANY);
+  }
+  /* Replace '##' with a special token */
+  Replace(macrovalue, "\001\001", "\002", DOH_REPLACE_ANY);
+  /* Replace '#@' with a special token */
+  Replace(macrovalue, "\001@", "\004", DOH_REPLACE_ANY);
+  /* Replace '##@' with a special token */
+  Replace(macrovalue, "\002@", "\005", DOH_REPLACE_ANY);
+
+  /* Go create the macro */
+  macro = NewHash();
+  Setattr(macro, kpp_name, macroname);
+
+  if (arglist) {
+    Setattr(macro, kpp_args, arglist);
+    Delete(arglist);
+    if (varargs) {
+      Setattr(macro, kpp_varargs, "1");
+    }
+  }
+  Setattr(macro, kpp_value, macrovalue);
+  Setline(macro, line);
+  Setfile(macro, file);
+  if (swigmacro) {
+    Setattr(macro, kpp_swigmacro, "1");
+  }
+  symbols = Getattr(cpp, kpp_symbols);
+  if ((m1 = Getattr(symbols, macroname))) {
+    if (!Checkattr(m1, kpp_value, macrovalue)) {
+      Swig_error(Getfile(str), Getline(str), "Macro '%s' redefined,\n", macroname);
+      Swig_error(Getfile(m1), Getline(m1), "previous definition of '%s'.\n", macroname);
+      goto macro_error;
+    }
+  } else {
+    Setattr(symbols, macroname, macro);
+    Delete(macro);
+  }
+
+  Delete(macroname);
+  Delete(macrovalue);
+
+  Delete(str);
+  Delete(argstr);
+  return macro;
+
+macro_error:
+  Delete(str);
+  Delete(argstr);
+  Delete(arglist);
+  Delete(macroname);
+  Delete(macrovalue);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Preprocessor_undef()
+ *
+ * Undefines a macro.
+ * ----------------------------------------------------------------------------- */
+void Preprocessor_undef(const String_or_char *str) {
+  Hash *symbols;
+  assert(cpp);
+  symbols = Getattr(cpp, kpp_symbols);
+  Delattr(symbols, str);
+}
+
+/* -----------------------------------------------------------------------------
+ * find_args()
+ *
+ * Isolates macro arguments and returns them in a list.   For each argument,
+ * leading and trailing whitespace is stripped (ala K&R, pg. 230).
+ * ----------------------------------------------------------------------------- */
+static List *find_args(String *s) {
+  List *args;
+  String *str;
+  int c, level;
+  long pos;
+
+  /* Create a new list */
+  args = NewList();
+  copy_location(s, args);
+
+  /* First look for a '(' */
+  pos = Tell(s);
+  skip_whitespace(s, 0);
+
+  /* Now see if the next character is a '(' */
+  c = Getc(s);
+  if (c != '(') {
+    /* Not a macro, bail out now! */
+    Seek(s, pos, SEEK_SET);
+    Delete(args);
+    return 0;
+  }
+  c = Getc(s);
+  /* Okay.  This appears to be a macro so we will start isolating arguments */
+  while (c != EOF) {
+    if (isspace(c)) {
+      skip_whitespace(s, 0);	/* Skip leading whitespace */
+      c = Getc(s);
+    }
+    str = NewStringEmpty();
+    copy_location(s, str);
+    level = 0;
+    while (c != EOF) {
+      if (c == '\"') {
+	Putc(c, str);
+	skip_tochar(s, '\"', str);
+	c = Getc(s);
+	continue;
+      } else if (c == '\'') {
+	Putc(c, str);
+	skip_tochar(s, '\'', str);
+	c = Getc(s);
+	continue;
+      }
+      if ((c == ',') && (level == 0))
+	break;
+      if ((c == ')') && (level == 0))
+	break;
+      Putc(c, str);
+      if (c == '(')
+	level++;
+      if (c == ')')
+	level--;
+      c = Getc(s);
+    }
+    if (level > 0) {
+      goto unterm;
+    }
+    Chop(str);
+    if (Len(args) || Len(str))
+      Append(args, str);
+    Delete(str);
+
+    /*    if (Len(str) && (c != ')'))
+       Append(args,str); */
+
+    if (c == ')')
+      return args;
+    c = Getc(s);
+  }
+unterm:
+  Swig_error(Getfile(args), Getline(args), "Unterminated macro call.\n");
+  return args;
+}
+
+/* -----------------------------------------------------------------------------
+ * DOH *get_filename(DOH *str)
+ *
+ * Read a filename from str.   A filename can be enclose in quotes, angle brackets,
+ * or bare.
+ * ----------------------------------------------------------------------------- */
+
+static String *get_filename(String *str, int *sysfile) {
+  String *fn;
+  int c;
+
+  skip_whitespace(str, 0);
+  fn = NewStringEmpty();
+  copy_location(str, fn);
+  c = Getc(str);
+  *sysfile = 0;
+  if (c == '\"') {
+    while (((c = Getc(str)) != EOF) && (c != '\"'))
+      Putc(c, fn);
+  } else if (c == '<') {
+    *sysfile = 1;
+    while (((c = Getc(str)) != EOF) && (c != '>'))
+      Putc(c, fn);
+  } else {
+    Putc(c, fn);
+    while (((c = Getc(str)) != EOF) && (!isspace(c)))
+      Putc(c, fn);
+    if (isspace(c))
+      Ungetc(c, str);
+  }
+#if defined(_WIN32) || defined(MACSWIG)
+  /* accept Unix path separator on non-Unix systems */
+  Replaceall(fn, "/", SWIG_FILE_DELIMITER);
+#endif
+#if defined(__CYGWIN__)
+  /* accept Windows path separator in addition to Unix path separator */
+  Replaceall(fn, "\\", SWIG_FILE_DELIMITER);
+#endif
+  Seek(fn, 0, SEEK_SET);
+  return fn;
+}
+
+static String *get_options(String *str) {
+
+  int c;
+  skip_whitespace(str, 0);
+  c = Getc(str);
+  if (c == '(') {
+    String *opt;
+    int level = 1;
+    opt = NewString("(");
+    while (((c = Getc(str)) != EOF)) {
+      Putc(c, opt);
+      if (c == ')') {
+	level--;
+	if (!level)
+	  return opt;
+      }
+      if (c == '(')
+	level++;
+    }
+    Delete(opt);
+    return 0;
+  } else {
+    Ungetc(c, str);
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * expand_macro()
+ *
+ * Perform macro expansion and return a new string.  Returns NULL if some sort
+ * of error occurred.
+ * ----------------------------------------------------------------------------- */
+
+static String *expand_macro(String *name, List *args) {
+  String *ns;
+  DOH *symbols, *macro, *margs, *mvalue, *temp, *tempa, *e;
+  int i, l;
+  int isvarargs = 0;
+
+  symbols = Getattr(cpp, kpp_symbols);
+  if (!symbols)
+    return 0;
+
+  /* See if the name is actually defined */
+  macro = Getattr(symbols, name);
+  if (!macro)
+    return 0;
+  if (Getattr(macro, kpp_expanded)) {
+    ns = NewStringEmpty();
+    Append(ns, name);
+    if (args) {
+      int lenargs = Len(args);
+      if (lenargs)
+	Putc('(', ns);
+      for (i = 0; i < lenargs; i++) {
+	Append(ns, Getitem(args, i));
+	if (i < (lenargs - 1))
+	  Putc(',', ns);
+      }
+      if (i)
+	Putc(')', ns);
+    }
+    return ns;
+  }
+
+  /* Get macro arguments and value */
+  mvalue = Getattr(macro, kpp_value);
+  assert(mvalue);
+  margs = Getattr(macro, kpp_args);
+
+  if (args && Getattr(macro, kpp_varargs)) {
+    isvarargs = 1;
+    /* Variable length argument macro.  We need to collect all of the extra arguments into a single argument */
+    if (Len(args) >= (Len(margs) - 1)) {
+      int i;
+      int vi, na;
+      String *vararg = NewStringEmpty();
+      vi = Len(margs) - 1;
+      na = Len(args);
+      for (i = vi; i < na; i++) {
+	Append(vararg, Getitem(args, i));
+	if ((i + 1) < na) {
+	  Append(vararg, ",");
+	}
+      }
+      /* Remove arguments */
+      for (i = vi; i < na; i++) {
+	Delitem(args, vi);
+      }
+      Append(args, vararg);
+      Delete(vararg);
+    }
+  }
+  /* If there are arguments, see if they match what we were given */
+  if (args && (margs) && (Len(margs) != Len(args))) {
+    if (Len(margs) > (1 + isvarargs))
+      Swig_error(Getfile(args), Getline(args), "Macro '%s' expects %d arguments\n", name, Len(margs) - isvarargs);
+    else if (Len(margs) == (1 + isvarargs))
+      Swig_error(Getfile(args), Getline(args), "Macro '%s' expects 1 argument\n", name);
+    else
+      Swig_error(Getfile(args), Getline(args), "Macro '%s' expects no arguments\n", name);
+    return 0;
+  }
+
+  /* If the macro expects arguments, but none were supplied, we leave it in place */
+  if (!args && (margs) && Len(margs) > 0) {
+    return NewString(name);
+  }
+
+  /* Copy the macro value */
+  ns = Copy(mvalue);
+  copy_location(mvalue, ns);
+
+  /* Tag the macro as being expanded.   This is to avoid recursion in
+     macro expansion */
+
+  temp = NewStringEmpty();
+  tempa = NewStringEmpty();
+  if (args && margs) {
+    l = Len(margs);
+    for (i = 0; i < l; i++) {
+      DOH *arg, *aname;
+      String *reparg;
+      arg = Getitem(args, i);	/* Get an argument value */
+      reparg = Preprocessor_replace(arg);
+      aname = Getitem(margs, i);	/* Get macro argument name */
+      if (strstr(Char(ns), "\001")) {
+	/* Try to replace a quoted version of the argument */
+	Clear(temp);
+	Clear(tempa);
+	Printf(temp, "\001%s", aname);
+	Printf(tempa, "\"%s\"", arg);
+	Replace(ns, temp, tempa, DOH_REPLACE_ID_END);
+      }
+      if (strstr(Char(ns), "\002")) {
+	/* Look for concatenation tokens */
+	Clear(temp);
+	Clear(tempa);
+	Printf(temp, "\002%s", aname);
+	Append(tempa, "\002\003");
+	Replace(ns, temp, tempa, DOH_REPLACE_ID_END);
+	Clear(temp);
+	Clear(tempa);
+	Printf(temp, "%s\002", aname);
+	Append(tempa, "\003\002");
+	Replace(ns, temp, tempa, DOH_REPLACE_ID_BEGIN);
+      }
+
+      /* Non-standard macro expansion.   The value `x` is replaced by a quoted
+         version of the argument except that if the argument is already quoted
+         nothing happens */
+
+      if (strchr(Char(ns), '`')) {
+	String *rep;
+	char *c;
+	Clear(temp);
+	Printf(temp, "`%s`", aname);
+	c = Char(arg);
+	if (*c == '\"') {
+	  rep = arg;
+	} else {
+	  Clear(tempa);
+	  Printf(tempa, "\"%s\"", arg);
+	  rep = tempa;
+	}
+	Replace(ns, temp, rep, DOH_REPLACE_ANY);
+      }
+
+      /* Non-standard mangle expansions.  
+         The #@Name is replaced by mangle_arg(Name). */
+      if (strstr(Char(ns), "\004")) {
+	String *marg = Swig_string_mangle(arg);
+	Clear(temp);
+	Printf(temp, "\004%s", aname);
+	Replace(ns, temp, marg, DOH_REPLACE_ID_END);
+	Delete(marg);
+      }
+      if (strstr(Char(ns), "\005")) {
+	String *marg = Swig_string_mangle(arg);
+	Clear(temp);
+	Clear(tempa);
+	Printf(temp, "\005%s", aname);
+	Printf(tempa, "\"%s\"", marg);
+	Replace(ns, temp, tempa, DOH_REPLACE_ID_END);
+	Delete(marg);
+      }
+
+      if (isvarargs && i == l - 1 && Len(arg) == 0) {
+	/* Zero length varargs macro argument.   We search for commas that might appear before and nuke them */
+	char *a, *s, *t, *name;
+	int namelen;
+	s = Char(ns);
+	name = Char(aname);
+	namelen = Len(aname);
+	a = strstr(s, name);
+	while (a) {
+	  char ca = a[namelen + 1];
+	  if (!isidchar((int) ca)) {
+	    /* Matched the entire vararg name, not just a prefix */
+	    t = a - 1;
+	    if (*t == '\002') {
+	      t--;
+	      while (t >= s) {
+		if (isspace((int) *t))
+		  t--;
+		else if (*t == ',') {
+		  *t = ' ';
+		} else
+		  break;
+	      }
+	    }
+	  }
+	  a = strstr(a + namelen, name);
+	}
+      }
+      /*      Replace(ns, aname, arg, DOH_REPLACE_ID); */
+      Replace(ns, aname, reparg, DOH_REPLACE_ID);	/* Replace expanded args */
+      Replace(ns, "\003", arg, DOH_REPLACE_ANY);	/* Replace unexpanded arg */
+      Delete(reparg);
+    }
+  }
+  Replace(ns, "\002", "", DOH_REPLACE_ANY);	/* Get rid of concatenation tokens */
+  Replace(ns, "\001", "#", DOH_REPLACE_ANY);	/* Put # back (non-standard C) */
+  Replace(ns, "\004", "#@", DOH_REPLACE_ANY);	/* Put # back (non-standard C) */
+
+  /* Expand this macro even further */
+  Setattr(macro, kpp_expanded, "1");
+
+  e = Preprocessor_replace(ns);
+
+  Delattr(macro, kpp_expanded);
+  Delete(ns);
+
+  if (Getattr(macro, kpp_swigmacro)) {
+    String *g;
+    String *f = NewStringEmpty();
+    Seek(e, 0, SEEK_SET);
+    copy_location(macro, e);
+    g = Preprocessor_parse(e);
+
+#if 0
+    /* Drop the macro in place, but with a marker around it */
+    Printf(f, "/*@%s,%d,%s@*/%s/*@@*/", Getfile(macro), Getline(macro), name, g);
+#else
+    /* Use simplified around markers to properly count lines in cscanner.c */
+    if (strchr(Char(g), '\n')) {
+      Printf(f, "/*@SWIG:%s,%d,%s@*/%s/*@SWIG@*/", Getfile(macro), Getline(macro), name, g);
+#if 0
+      Printf(f, "/*@SWIG:%s@*/%s/*@SWIG@*/", name, g);
+#endif
+    } else {
+      Append(f, g);
+    }
+#endif
+
+    Delete(g);
+    Delete(e);
+    e = f;
+  }
+  Delete(temp);
+  Delete(tempa);
+  return e;
+}
+
+/* -----------------------------------------------------------------------------
+ * evaluate_args()
+ *
+ * Evaluate the arguments of a macro 
+ * ----------------------------------------------------------------------------- */
+
+List *evaluate_args(List *x) {
+  Iterator i;
+  List *nl = NewList();
+
+  for (i = First(x); i.item; i = Next(i)) {
+    Append(nl, Preprocessor_replace(i.item));
+  }
+  return nl;
+}
+
+/* -----------------------------------------------------------------------------
+ * DOH *Preprocessor_replace(DOH *s)
+ *
+ * Performs a macro substitution on a string s.  Returns a new string with
+ * substitutions applied.   This function works by walking down s and looking
+ * for identifiers.   When found, a check is made to see if they are macros
+ * which are then expanded.
+ * ----------------------------------------------------------------------------- */
+
+/* #define SWIG_PUT_BUFF  */
+
+DOH *Preprocessor_replace(DOH *s) {
+  DOH *ns, *symbols, *m;
+  int c, i, state = 0;
+
+  String *id = NewStringEmpty();
+
+  assert(cpp);
+  symbols = Getattr(cpp, kpp_symbols);
+
+  ns = NewStringEmpty();
+  copy_location(s, ns);
+  Seek(s, 0, SEEK_SET);
+
+  /* Try to locate identifiers in s and replace them with macro replacements */
+  while ((c = Getc(s)) != EOF) {
+    switch (state) {
+    case 0:
+      if (isidentifier(c) || (c == '%')) {
+	Clear(id);
+	Putc(c, id);
+	state = 1;
+      } else if (c == '\"') {
+	Putc(c, ns);
+	skip_tochar(s, '\"', ns);
+      } else if (c == '\'') {
+	Putc(c, ns);
+	skip_tochar(s, '\'', ns);
+      } else if (c == '/') {
+	Putc(c, ns);
+	state = 10;
+      } else {
+	Putc(c, ns);
+      }
+      break;
+    case 1:			/* An identifier */
+      if (isidchar(c)) {
+	Putc(c, id);
+	state = 1;
+      } else {
+	/* We found the end of a valid identifier */
+	Ungetc(c, s);
+	/* See if this is the special "defined" macro */
+	if (Equal(kpp_defined, id)) {
+	  int lenargs = 0;
+	  DOH *args = 0;
+	  /* See whether or not a paranthesis has been used */
+	  skip_whitespace(s, 0);
+	  c = Getc(s);
+	  if (c == '(') {
+	    Ungetc(c, s);
+	    args = find_args(s);
+	  } else if (isidchar(c)) {
+	    DOH *arg = NewStringEmpty();
+	    args = NewList();
+	    Putc(c, arg);
+	    while (((c = Getc(s)) != EOF)) {
+	      if (!isidchar(c)) {
+		Ungetc(c, s);
+		break;
+	      }
+	      Putc(c, arg);
+	    }
+	    if (Len(arg))
+	      Append(args, arg);
+	    Delete(arg);
+	  } else {
+	    Seek(s, -1, SEEK_CUR);
+	  }
+	  lenargs = Len(args);
+	  if ((!args) || (!lenargs)) {
+	    /* This is not a defined() macro. */
+	    Append(ns, id);
+	    state = 0;
+	    break;
+	  }
+	  for (i = 0; i < lenargs; i++) {
+	    DOH *o = Getitem(args, i);
+	    if (!Getattr(symbols, o)) {
+	      break;
+	    }
+	  }
+	  if (i < lenargs)
+	    Putc('0', ns);
+	  else
+	    Putc('1', ns);
+	  Delete(args);
+	  state = 0;
+	  break;
+	}
+	if (Equal(kpp_LINE, id)) {
+	  Printf(ns, "%d", Getline(s));
+	  state = 0;
+	  break;
+	}
+	if (Equal(kpp_FILE, id)) {
+	  String *fn = Copy(Getfile(s));
+	  Replaceall(fn, "\\", "\\\\");
+	  Printf(ns, "\"%s\"", fn);
+	  Delete(fn);
+	  state = 0;
+	  break;
+	}
+	/* See if the macro is defined in the preprocessor symbol table */
+	if ((m = Getattr(symbols, id))) {
+	  DOH *args = 0;
+	  DOH *e;
+	  /* See if the macro expects arguments */
+	  if (Getattr(m, kpp_args)) {
+	    /* Yep.  We need to go find the arguments and do a substitution */
+	    args = find_args(s);
+	    if (!Len(args)) {
+	      Delete(args);
+	      args = 0;
+	    }
+	  } else {
+	    args = 0;
+	  }
+	  e = expand_macro(id, args);
+	  if (e) {
+	    Append(ns, e);
+	  }
+	  Delete(e);
+	  Delete(args);
+	} else {
+	  Append(ns, id);
+	}
+	state = 0;
+      }
+      break;
+    case 10:
+      if (c == '/')
+	state = 11;
+      else if (c == '*')
+	state = 12;
+      else {
+	Ungetc(c, s);
+	state = 0;
+	break;
+      }
+      Putc(c, ns);
+      break;
+    case 11:
+      Putc(c, ns);
+      if (c == '\n')
+	state = 0;
+      break;
+    case 12:
+      Putc(c, ns);
+      if (c == '*')
+	state = 13;
+      break;
+    case 13:
+      Putc(c, ns);
+      if (c == '/')
+	state = 0;
+      else if (c != '*')
+	state = 12;
+      break;
+    default:
+      state = 0;
+      break;
+    }
+  }
+
+  /* Identifier at the end */
+  if (state == 1) {
+    /* See if this is the special "defined" macro */
+    if (Equal(kpp_defined, id)) {
+      Swig_error(Getfile(s), Getline(s), "No arguments given to defined()\n");
+    } else if ((m = Getattr(symbols, id))) {
+      DOH *e;
+      /* Yes.  There is a macro here */
+      /* See if the macro expects arguments */
+      /*      if (Getattr(m,"args")) {
+         Swig_error(Getfile(id),Getline(id),"Macro arguments expected.\n");
+         } */
+      e = expand_macro(id, 0);
+      Append(ns, e);
+      Delete(e);
+    } else {
+      Append(ns, id);
+    }
+  }
+  Delete(id);
+  return ns;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * int checkpp_id(DOH *s)
+ *
+ * Checks the string s to see if it contains any unresolved identifiers.  This
+ * function contains the heuristic that determines whether or not a macro
+ * definition passes through the preprocessor as a constant declaration.
+ * ----------------------------------------------------------------------------- */
+static int checkpp_id(DOH *s) {
+  int c;
+  int hastok = 0;
+  Scanner *scan = id_scan;
+
+  Seek(s, 0, SEEK_SET);
+
+  Scanner_clear(scan);
+  s = Copy(s);
+  Seek(s, SEEK_SET, 0);
+  Scanner_push(scan, s);
+  while ((c = Scanner_token(scan))) {
+    hastok = 1;
+    if ((c == SWIG_TOKEN_ID) || (c == SWIG_TOKEN_LBRACE) || (c == SWIG_TOKEN_RBRACE))
+      return 1;
+  }
+  if (!hastok)
+    return 1;
+  return 0;
+}
+
+/* addline().  Utility function for adding lines to a chunk */
+static void addline(DOH *s1, DOH *s2, int allow) {
+  if (allow) {
+    Append(s1, s2);
+  } else {
+    char *c = Char(s2);
+    while (*c) {
+      if (*c == '\n')
+	Putc('\n', s1);
+      c++;
+    }
+  }
+}
+
+static void add_chunk(DOH *ns, DOH *chunk, int allow) {
+  DOH *echunk;
+  Seek(chunk, 0, SEEK_SET);
+  if (allow) {
+    echunk = Preprocessor_replace(chunk);
+    addline(ns, echunk, allow);
+    Delete(echunk);
+  } else {
+    addline(ns, chunk, 0);
+  }
+  Clear(chunk);
+}
+
+/*
+  push/pop_imported(): helper functions for defining and undefining
+  SWIGIMPORTED (when %importing a file).
+ */
+static void push_imported() {
+  if (imported_depth == 0) {
+    Preprocessor_define("SWIGIMPORTED 1", 0);
+  }
+  ++imported_depth;
+}
+
+static void pop_imported() {
+  --imported_depth;
+  if (imported_depth == 0) {
+    Preprocessor_undef("SWIGIMPORTED");
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Preprocessor_parse()
+ *
+ * Parses the string s.  Returns a new string containing the preprocessed version.
+ *
+ * Parsing rules :
+ *       1.  Lines starting with # are C preprocessor directives
+ *       2.  Macro expansion inside strings is not allowed
+ *       3.  All code inside false conditionals is changed to blank lines
+ *       4.  Code in %{, %} is not parsed because it may need to be
+ *           included inline (with all preprocessor directives included).
+ * ----------------------------------------------------------------------------- */
+
+String *Preprocessor_parse(String *s) {
+  String *ns;			/* New string containing the preprocessed text */
+  String *chunk, *decl;
+  Hash *symbols;
+  String *id = 0, *value = 0, *comment = 0;
+  int i, state, e, c;
+  int start_line = 0;
+  int allow = 1;
+  int level = 0;
+  int dlevel = 0;
+  int mask = 0;
+  int start_level = 0;
+  int cpp_lines = 0;
+  int cond_lines[256];
+
+  /* Blow away all carriage returns */
+  Replace(s, "\015", "", DOH_REPLACE_ANY);
+
+  ns = NewStringEmpty();	/* Return result */
+
+  decl = NewStringEmpty();
+  id = NewStringEmpty();
+  value = NewStringEmpty();
+  comment = NewStringEmpty();
+  chunk = NewStringEmpty();
+  copy_location(s, chunk);
+  copy_location(s, ns);
+  symbols = Getattr(cpp, kpp_symbols);
+
+  state = 0;
+  while ((c = Getc(s)) != EOF) {
+    switch (state) {
+    case 0:			/* Initial state - in first column */
+      /* Look for C preprocessor directives.   Otherwise, go directly to state 1 */
+      if (c == '#') {
+	add_chunk(ns, chunk, allow);
+	copy_location(s, chunk);
+	cpp_lines = 1;
+	state = 40;
+      } else if (isspace(c)) {
+	Putc(c, chunk);
+	skip_whitespace(s, chunk);
+      } else {
+	state = 1;
+	Ungetc(c, s);
+      }
+      break;
+    case 1:			/* Non-preprocessor directive */
+      /* Look for SWIG directives */
+      if (c == '%') {
+	state = 100;
+	break;
+      }
+      Putc(c, chunk);
+      if (c == '\n')
+	state = 0;
+      else if (c == '\"') {
+	start_line = Getline(s);
+	if (skip_tochar(s, '\"', chunk) < 0) {
+	  Swig_error(Getfile(s), -1, "Unterminated string constant starting at line %d\n", start_line);
+	}
+      } else if (c == '\'') {
+	start_line = Getline(s);
+	if (skip_tochar(s, '\'', chunk) < 0) {
+	  Swig_error(Getfile(s), -1, "Unterminated character constant starting at line %d\n", start_line);
+	}
+      } else if (c == '/')
+	state = 30;		/* Comment */
+      break;
+
+    case 30:			/* Possibly a comment string of some sort */
+      start_line = Getline(s);
+      Putc(c, chunk);
+      if (c == '/')
+	state = 31;
+      else if (c == '*')
+	state = 32;
+      else
+	state = 1;
+      break;
+    case 31:
+      Putc(c, chunk);
+      if (c == '\n')
+	state = 0;
+      break;
+    case 32:
+      Putc(c, chunk);
+      if (c == '*')
+	state = 33;
+      break;
+    case 33:
+      Putc(c, chunk);
+      if (c == '/')
+	state = 1;
+      else if (c != '*')
+	state = 32;
+      break;
+
+    case 40:			/* Start of a C preprocessor directive */
+      if (c == '\n') {
+	Putc('\n', chunk);
+	state = 0;
+      } else if (isspace(c)) {
+	state = 40;
+      } else {
+	/* Got the start of a preprocessor directive */
+	Ungetc(c, s);
+	Clear(id);
+	copy_location(s, id);
+	state = 41;
+      }
+      break;
+
+    case 41:			/* Build up the name of the preprocessor directive */
+      if ((isspace(c) || (!isalpha(c)))) {
+	Clear(value);
+	Clear(comment);
+	if (c == '\n') {
+	  Ungetc(c, s);
+	  state = 50;
+	} else {
+	  state = 42;
+	  if (!isspace(c)) {
+	    Ungetc(c, s);
+	  }
+	}
+
+	copy_location(s, value);
+	break;
+      }
+      Putc(c, id);
+      break;
+
+    case 42:			/* Strip any leading space before preprocessor value */
+      if (isspace(c)) {
+	if (c == '\n') {
+	  Ungetc(c, s);
+	  state = 50;
+	}
+	break;
+      }
+      state = 43;
+      /* no break intended here */
+
+    case 43:
+      /* Get preprocessor value */
+      if (c == '\n') {
+	Ungetc(c, s);
+	state = 50;
+      } else if (c == '/') {
+	state = 45;
+      } else if (c == '\"') {
+	Putc(c, value);
+	skip_tochar(s, '\"', value);
+      } else if (c == '\'') {
+	Putc(c, value);
+	skip_tochar(s, '\'', value);
+      } else {
+	Putc(c, value);
+	if (c == '\\')
+	  state = 44;
+      }
+      break;
+
+    case 44:
+      if (c == '\n') {
+	Putc(c, value);
+	cpp_lines++;
+      } else {
+	Ungetc(c, s);
+      }
+      state = 43;
+      break;
+
+      /* States 45-48 are used to remove, but retain comments from macro values.  The comments
+         will be placed in the output in an alternative form */
+
+    case 45:
+      if (c == '/')
+	state = 46;
+      else if (c == '*')
+	state = 47;
+      else if (c == '\n') {
+	Putc('/', value);
+	Ungetc(c, s);
+	cpp_lines++;
+	state = 50;
+      } else {
+	Putc('/', value);
+	Putc(c, value);
+	state = 43;
+      }
+      break;
+    case 46:
+      if (c == '\n') {
+	Ungetc(c, s);
+	cpp_lines++;
+	state = 50;
+      } else
+	Putc(c, comment);
+      break;
+    case 47:
+      if (c == '*')
+	state = 48;
+      else
+	Putc(c, comment);
+      break;
+    case 48:
+      if (c == '/')
+	state = 43;
+      else if (c == '*')
+	Putc(c, comment);
+      else {
+	Putc('*', comment);
+	Putc(c, comment);
+	state = 47;
+      }
+      break;
+    case 50:
+      /* Check for various preprocessor directives */
+      Chop(value);
+      if (Equal(id, kpp_define)) {
+	if (allow) {
+	  DOH *m, *v, *v1;
+	  Seek(value, 0, SEEK_SET);
+	  m = Preprocessor_define(value, 0);
+	  if ((m) && !(Getattr(m, kpp_args))) {
+	    v = Copy(Getattr(m, kpp_value));
+	    if (Len(v)) {
+	      Swig_error_silent(1);
+	      v1 = Preprocessor_replace(v);
+	      Swig_error_silent(0);
+	      /*              Printf(stdout,"checking '%s'\n", v1); */
+	      if (!checkpp_id(v1)) {
+		if (Len(comment) == 0)
+		  Printf(ns, "%%constant %s = %s;\n", Getattr(m, kpp_name), v1);
+		else
+		  Printf(ns, "%%constant %s = %s; /*%s*/\n", Getattr(m, kpp_name), v1, comment);
+		cpp_lines--;
+	      }
+	      Delete(v1);
+	    }
+	    Delete(v);
+	  }
+	}
+      } else if (Equal(id, kpp_undef)) {
+	if (allow)
+	  Preprocessor_undef(value);
+      } else if (Equal(id, kpp_ifdef)) {
+	cond_lines[level] = Getline(id);
+	level++;
+	if (allow) {
+	  start_level = level;
+	  /* See if the identifier is in the hash table */
+	  if (!Getattr(symbols, value))
+	    allow = 0;
+	  mask = 1;
+	}
+      } else if (Equal(id, kpp_ifndef)) {
+	cond_lines[level] = Getline(id);
+	level++;
+	if (allow) {
+	  start_level = level;
+	  /* See if the identifier is in the hash table */
+	  if (Getattr(symbols, value))
+	    allow = 0;
+	  mask = 1;
+	}
+      } else if (Equal(id, kpp_else)) {
+	if (level <= 0) {
+	  Swig_error(Getfile(s), Getline(id), "Misplaced #else.\n");
+	} else {
+	  cond_lines[level - 1] = Getline(id);
+	  if (allow) {
+	    allow = 0;
+	    mask = 0;
+	  } else if (level == start_level) {
+	    allow = 1 * mask;
+	  }
+	}
+      } else if (Equal(id, kpp_endif)) {
+	level--;
+	if (level < 0) {
+	  Swig_error(Getfile(id), Getline(id), "Extraneous #endif.\n");
+	  level = 0;
+	} else {
+	  if (level < start_level) {
+	    allow = 1;
+	    start_level--;
+	  }
+	}
+      } else if (Equal(id, kpp_if)) {
+	cond_lines[level] = Getline(id);
+	level++;
+	if (allow) {
+	  int val;
+	  String *sval = Preprocessor_replace(value);
+	  start_level = level;
+	  Seek(sval, 0, SEEK_SET);
+	  /*      Printf(stdout,"Evaluating '%s'\n", sval); */
+	  val = Preprocessor_expr(sval, &e);
+	  if (e) {
+	    char *msg = Preprocessor_expr_error();
+	    Seek(value, 0, SEEK_SET);
+	    Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Could not evaluate '%s'\n", value);
+	    if (msg)
+	      Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Error: '%s'\n", msg);
+	    allow = 0;
+	  } else {
+	    if (val == 0)
+	      allow = 0;
+	  }
+	  mask = 1;
+	}
+      } else if (Equal(id, kpp_elif)) {
+	if (level == 0) {
+	  Swig_error(Getfile(s), Getline(id), "Misplaced #elif.\n");
+	} else {
+	  cond_lines[level - 1] = Getline(id);
+	  if (allow) {
+	    allow = 0;
+	    mask = 0;
+	  } else if (level == start_level) {
+	    int val;
+	    String *sval = Preprocessor_replace(value);
+	    Seek(sval, 0, SEEK_SET);
+	    val = Preprocessor_expr(sval, &e);
+	    if (e) {
+	      char *msg = Preprocessor_expr_error();
+	      Seek(value, 0, SEEK_SET);
+	      Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Could not evaluate '%s'\n", value);
+	      if (msg)
+		Swig_warning(WARN_PP_EVALUATION, Getfile(value), Getline(value), "Error: '%s'\n", msg);
+	      allow = 0;
+	    } else {
+	      if (val)
+		allow = 1 * mask;
+	      else
+		allow = 0;
+	    }
+	  }
+	}
+      } else if (Equal(id, kpp_warning)) {
+	if (allow) {
+	  Swig_warning(WARN_PP_CPP_WARNING, Getfile(s), Getline(id), "CPP #warning, %s\n", value);
+	}
+      } else if (Equal(id, kpp_error)) {
+	if (allow) {
+	  if (error_as_warning) {
+	    Swig_warning(WARN_PP_CPP_ERROR, Getfile(s), Getline(id), "CPP #error \"%s\".\n", value);
+	  } else {
+	    Swig_error(Getfile(s), Getline(id), "CPP #error \"%s\". Use the -cpperraswarn option to continue swig processing.\n", value);
+	  }
+	}
+      } else if (Equal(id, kpp_line)) {
+      } else if (Equal(id, kpp_include)) {
+	if (((include_all) || (import_all)) && (allow)) {
+	  String *s1, *s2, *fn;
+	  char *dirname;
+	  int sysfile = 0;
+	  if (include_all && import_all) {
+	    Swig_warning(WARN_PP_INCLUDEALL_IMPORTALL, Getfile(s), Getline(id), "Both includeall and importall are defined: using includeall\n");
+	    import_all = 0;
+	  }
+	  Seek(value, 0, SEEK_SET);
+	  fn = get_filename(value, &sysfile);
+	  s1 = cpp_include(fn, sysfile);
+	  if (s1) {
+	    if (include_all)
+	      Printf(ns, "%%includefile \"%s\" [\n", Swig_last_file());
+	    else if (import_all) {
+	      Printf(ns, "%%importfile \"%s\" [\n", Swig_last_file());
+	      push_imported();
+	    }
+
+	    /* See if the filename has a directory component */
+	    dirname = Swig_file_dirname(Swig_last_file());
+	    if (sysfile || !strlen(dirname))
+	      dirname = 0;
+	    if (dirname) {
+	      dirname[strlen(dirname) - 1] = 0;	/* Kill trailing directory delimiter */
+	      Swig_push_directory(dirname);
+	    }
+	    s2 = Preprocessor_parse(s1);
+	    addline(ns, s2, allow);
+	    Append(ns, "\n]");
+	    if (dirname) {
+	      Swig_pop_directory();
+	    }
+	    if (import_all) {
+	      pop_imported();
+	    }
+	    Delete(s2);
+	  }
+	  Delete(s1);
+	  Delete(fn);
+	}
+      } else if (Equal(id, kpp_pragma)) {
+	if (Strncmp(value, "SWIG ", 5) == 0) {
+	  char *c = Char(value) + 5;
+	  while (*c && (isspace((int) *c)))
+	    c++;
+	  if (*c) {
+	    if (strncmp(c, "nowarn=", 7) == 0) {
+	      String *val = NewString(c + 7);
+	      String *nowarn = Preprocessor_replace(val);
+	      Swig_warnfilter(nowarn, 1);
+	      Delete(nowarn);
+	      Delete(val);
+	    } else if (strncmp(c, "cpperraswarn=", 13) == 0) {
+	      error_as_warning = atoi(c + 13);
+	    } else {
+              Swig_error(Getfile(s), Getline(id), "Unknown SWIG pragma: %s\n", c);
+            }
+	  }
+	}
+      } else if (Equal(id, kpp_level)) {
+	Swig_error(Getfile(s), Getline(id), "cpp debug: level = %d, startlevel = %d\n", level, start_level);
+      }
+      for (i = 0; i < cpp_lines; i++)
+	Putc('\n', ns);
+      state = 0;
+      break;
+
+      /* Swig directives  */
+    case 100:
+      /* %{,%} block  */
+      if (c == '{') {
+	start_line = Getline(s);
+	add_chunk(ns, chunk, allow);
+	copy_location(s, chunk);
+	Putc('%', chunk);
+	Putc(c, chunk);
+	state = 105;
+      }
+      /* %#cpp -  an embedded C preprocessor directive (we strip off the %)  */
+      else if (c == '#') {
+	add_chunk(ns, chunk, allow);
+	Putc(c, chunk);
+	state = 107;
+      } else if (isidentifier(c)) {
+	Clear(decl);
+	Putc('%', decl);
+	Putc(c, decl);
+	state = 110;
+      } else {
+	Putc('%', chunk);
+	Putc(c, chunk);
+	state = 1;
+      }
+      break;
+
+    case 105:
+      Putc(c, chunk);
+      if (c == '%')
+	state = 106;
+      break;
+
+    case 106:
+      Putc(c, chunk);
+      if (c == '}') {
+	state = 1;
+	addline(ns, chunk, allow);
+	Clear(chunk);
+	copy_location(s, chunk);
+      } else {
+	state = 105;
+      }
+      break;
+
+    case 107:
+      Putc(c, chunk);
+      if (c == '\n') {
+	addline(ns, chunk, allow);
+	Clear(chunk);
+	state = 0;
+      } else if (c == '\\') {
+	state = 108;
+      }
+      break;
+
+    case 108:
+      Putc(c, chunk);
+      state = 107;
+      break;
+
+    case 110:
+      if (!isidchar(c)) {
+	Ungetc(c, s);
+	/* Look for common Swig directives  */
+	if (Equal(decl, kpp_dinclude) || Equal(decl, kpp_dimport) || Equal(decl, kpp_dextern)) {
+	  /* Got some kind of file inclusion directive  */
+	  if (allow) {
+	    DOH *s1, *s2, *fn, *opt;
+	    int sysfile = 0;
+
+	    if (Equal(decl, kpp_dextern)) {
+	      Swig_warning(WARN_DEPRECATED_EXTERN, Getfile(s), Getline(s), "%%extern is deprecated. Use %%import instead.\n");
+	      Clear(decl);
+	      Append(decl, "%%import");
+	    }
+	    opt = get_options(s);
+	    fn = get_filename(s, &sysfile);
+	    s1 = cpp_include(fn, sysfile);
+	    if (s1) {
+	      char *dirname;
+	      add_chunk(ns, chunk, allow);
+	      copy_location(s, chunk);
+	      Printf(ns, "%sfile%s \"%s\" [\n", decl, opt, Swig_last_file());
+	      if (Equal(decl, kpp_dimport)) {
+		push_imported();
+	      }
+	      dirname = Swig_file_dirname(Swig_last_file());
+	      if (sysfile || !strlen(dirname))
+		dirname = 0;
+	      if (dirname) {
+		dirname[strlen(dirname) - 1] = 0;	/* Kill trailing directory delimiter */
+		Swig_push_directory(dirname);
+	      }
+	      s2 = Preprocessor_parse(s1);
+	      if (dirname) {
+		Swig_pop_directory();
+	      }
+	      if (Equal(decl, kpp_dimport)) {
+		pop_imported();
+	      }
+	      addline(ns, s2, allow);
+	      Append(ns, "\n]");
+	      Delete(s2);
+	      Delete(s1);
+	    }
+	    Delete(fn);
+	  }
+	  state = 1;
+	} else if (Equal(decl, kpp_dline)) {
+	  /* Got a line directive  */
+	  state = 1;
+	} else if (Equal(decl, kpp_ddefine)) {
+	  /* Got a define directive  */
+	  dlevel++;
+	  add_chunk(ns, chunk, allow);
+	  copy_location(s, chunk);
+	  Clear(value);
+	  copy_location(s, value);
+	  state = 150;
+	} else {
+	  Append(chunk, decl);
+	  state = 1;
+	}
+      } else {
+	Putc(c, decl);
+      }
+      break;
+
+      /* Searching for the end of a %define statement  */
+    case 150:
+      Putc(c, value);
+      if (c == '%') {
+	const char *ed = "enddef";
+	const char *df = "define";
+	char statement[7];
+	int i = 0;
+	for (i = 0; i < 6;) {
+	  c = Getc(s);
+	  Putc(c, value);
+	  statement[i++] = (char)c;
+	  if (strncmp(statement, ed, i) && strncmp(statement, df, i))
+	    break;
+	}
+	c = Getc(s);
+	Ungetc(c, s);
+	if ((i == 6) && (isspace(c))) {
+	  if (strncmp(statement, df, i) == 0) {
+	    ++dlevel;
+	  } else {
+	    if (strncmp(statement, ed, i) == 0) {
+	      --dlevel;
+	      if (!dlevel) {
+		/* Got the macro  */
+		for (i = 0; i < 7; i++) {
+		  Delitem(value, DOH_END);
+		}
+		if (allow) {
+		  Seek(value, 0, SEEK_SET);
+		  Preprocessor_define(value, 1);
+		}
+		/* Putc('\n',ns); */
+		addline(ns, value, 0);
+		state = 0;
+	      }
+	    }
+	  }
+	}
+      }
+      break;
+    default:
+      Printf(stderr, "cpp: Invalid parser state %d\n", state);
+      abort();
+      break;
+    }
+  }
+  while (level > 0) {
+    Swig_error(Getfile(s), -1, "Missing #endif for conditional starting on line %d\n", cond_lines[level - 1]);
+    level--;
+  }
+  if (state == 150) {
+    Seek(value, 0, SEEK_SET);
+    Swig_error(Getfile(s), -1, "Missing %%enddef for macro starting on line %d\n", Getline(value));
+  }
+  if ((state >= 105) && (state < 107)) {
+    Swig_error(Getfile(s), -1, "Unterminated %%{ ... %%} block starting on line %d\n", start_line);
+  }
+  if ((state >= 30) && (state < 40)) {
+    Swig_error(Getfile(s), -1, "Unterminated comment starting on line %d\n", start_line);
+  }
+  add_chunk(ns, chunk, allow);
+  copy_location(s, chunk);
+
+  /*  DelScope(scp); */
+  Delete(decl);
+  Delete(id);
+  Delete(value);
+  Delete(comment);
+  Delete(chunk);
+
+  /*  fprintf(stderr,"cpp: %d\n", Len(Getattr(cpp,"symbols"))); */
+  return ns;
+}
diff --git a/trunk/Source/Preprocessor/expr.c b/trunk/Source/Preprocessor/expr.c
new file mode 100644
index 0000000..4da24a7
--- /dev/null
+++ b/trunk/Source/Preprocessor/expr.c
@@ -0,0 +1,436 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * expr.c
+ *
+ * Integer arithmetic expression evaluator used to handle expressions
+ * encountered during preprocessing.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_expr_c[] = "$Id$";
+
+#include "swig.h"
+#include "preprocessor.h"
+
+static Scanner *scan = 0;
+
+typedef struct {
+  int op;
+  long value;
+  String *svalue;
+} exprval;
+
+#define  EXPR_TOP      1
+#define  EXPR_VALUE    2
+#define  EXPR_OP       3
+#define  EXPR_GROUP    4
+#define  EXPR_UMINUS   100
+
+static exprval stack[256];	/* Parsing stack       */
+static int sp = 0;		/* Stack pointer       */
+static int prec[256];		/* Precedence rules    */
+static int expr_init = 0;	/* Initialization flag */
+static char *errmsg = 0;	/* Parsing error       */
+
+/* Initialize the precedence table for various operators.  Low values have higher precedence */
+static void init_precedence() {
+  prec[SWIG_TOKEN_NOT] = 10;
+  prec[EXPR_UMINUS] = 10;
+  prec[SWIG_TOKEN_STAR] = 20;
+  prec[SWIG_TOKEN_SLASH] = 20;
+  prec[SWIG_TOKEN_PERCENT] = 20;
+  prec[SWIG_TOKEN_PLUS] = 30;
+  prec[SWIG_TOKEN_MINUS] = 30;
+  prec[SWIG_TOKEN_LSHIFT] = 40;
+  prec[SWIG_TOKEN_RSHIFT] = 40;
+  prec[SWIG_TOKEN_AND] = 50;
+  prec[SWIG_TOKEN_XOR] = 60;
+  prec[SWIG_TOKEN_OR] = 70;
+  prec[SWIG_TOKEN_EQUALTO] = 80;
+  prec[SWIG_TOKEN_NOTEQUAL] = 80;
+  prec[SWIG_TOKEN_LESSTHAN] = 80;
+  prec[SWIG_TOKEN_GREATERTHAN] = 80;
+  prec[SWIG_TOKEN_LTEQUAL] = 80;
+  prec[SWIG_TOKEN_GTEQUAL] = 80;
+  prec[SWIG_TOKEN_LNOT] = 90;
+  prec[SWIG_TOKEN_LAND] = 100;
+  prec[SWIG_TOKEN_LOR] = 110;
+  expr_init = 1;
+}
+
+#define UNARY_OP(token) (((token) == SWIG_TOKEN_NOT) || \
+			 ((token) == SWIG_TOKEN_LNOT) || \
+			 ((token) == EXPR_UMINUS))
+
+/* Reduce a single operator on the stack */
+/* return 0 on failure, 1 on success */
+static int reduce_op() {
+  long op_token = stack[sp - 1].value;
+  assert(sp > 0);
+  assert(stack[sp - 1].op == EXPR_OP);
+  /* do some basic checking first: */
+  if (stack[sp].op != EXPR_VALUE) {
+    errmsg = "Right-hand side is not value";
+    return 0;
+  }
+  if (UNARY_OP(op_token)) {
+    if (stack[sp].svalue) {
+      errmsg = "Syntax error: attempt to apply unary operator to string";
+      return 0;
+    }
+  } else {
+    /* binary operator: */
+    if (sp == 1) {
+      /* top of stack: don't attempt to use sp-2! */
+      errmsg = "Missing left-hand side for binary operator";
+      return 0;
+    }
+    if (stack[sp].op != EXPR_VALUE) {
+      errmsg = "Left-hand side of binary operator is not a value";
+      return 0;
+    }
+    if ((!stack[sp - 2].svalue) != (!stack[sp].svalue)) {
+      errmsg = "Can't mix strings and integers in expression";
+      return 0;
+    }
+  }
+  if (stack[sp].svalue) {
+    /* A binary string expression */
+    switch (stack[sp - 1].value) {
+    case SWIG_TOKEN_EQUALTO:
+      stack[sp - 2].value = (Strcmp(stack[sp - 2].svalue, stack[sp].svalue) == 0);
+      Delete(stack[sp - 2].svalue);
+      Delete(stack[sp].svalue);
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_NOTEQUAL:
+      stack[sp - 2].value = (Strcmp(stack[sp - 2].svalue, stack[sp].svalue) != 0);
+      Delete(stack[sp - 2].svalue);
+      Delete(stack[sp].svalue);
+      sp -= 2;
+      break;
+    default:
+      errmsg = "Syntax error: bad binary operator for strings";
+      return 0;
+      break;
+    }
+  } else {
+    switch (op_token) {
+    case SWIG_TOKEN_STAR:
+      stack[sp - 2].value = stack[sp - 2].value * stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_EQUALTO:
+      stack[sp - 2].value = stack[sp - 2].value == stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_NOTEQUAL:
+      stack[sp - 2].value = stack[sp - 2].value != stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_PLUS:
+      stack[sp - 2].value = stack[sp - 2].value + stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_MINUS:
+      stack[sp - 2].value = stack[sp - 2].value - stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_AND:
+      stack[sp - 2].value = stack[sp - 2].value & stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_LAND:
+      stack[sp - 2].value = stack[sp - 2].value && stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_OR:
+      stack[sp - 2].value = stack[sp - 2].value | stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_LOR:
+      stack[sp - 2].value = stack[sp - 2].value || stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_XOR:
+      stack[sp - 2].value = stack[sp - 2].value ^ stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_LESSTHAN:
+      stack[sp - 2].value = stack[sp - 2].value < stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_GREATERTHAN:
+      stack[sp - 2].value = stack[sp - 2].value > stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_LTEQUAL:
+      stack[sp - 2].value = stack[sp - 2].value <= stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_GTEQUAL:
+      stack[sp - 2].value = stack[sp - 2].value >= stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_NOT:
+      stack[sp - 1].value = ~stack[sp].value;
+      sp--;
+      break;
+    case SWIG_TOKEN_LNOT:
+      stack[sp - 1].value = !stack[sp].value;
+      sp--;
+      break;
+    case EXPR_UMINUS:
+      stack[sp - 1].value = -stack[sp].value;
+      sp--;
+      break;
+    case SWIG_TOKEN_SLASH:
+      stack[sp - 2].value = stack[sp - 2].value / stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_PERCENT:
+      stack[sp - 2].value = stack[sp - 2].value % stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_LSHIFT:
+      stack[sp - 2].value = stack[sp - 2].value << stack[sp].value;
+      sp -= 2;
+      break;
+    case SWIG_TOKEN_RSHIFT:
+      stack[sp - 2].value = stack[sp - 2].value >> stack[sp].value;
+      sp -= 2;
+      break;
+    default:
+      errmsg = "Syntax error: bad operator";
+      return 0;
+      break;
+    }
+  }
+  stack[sp].op = EXPR_VALUE;
+  stack[sp].svalue = 0;		/* ensure it's not a string! */
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * Preprocessor_expr_init()
+ *
+ * Initialize the expression evaluator
+ * ----------------------------------------------------------------------------- */
+
+void Preprocessor_expr_init(void) {
+  if (!expr_init)
+    init_precedence();
+  if (!scan)
+    scan = NewScanner();
+}
+
+void Preprocessor_expr_delete(void) {
+  DelScanner(scan);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Tokenizer 
+ * ----------------------------------------------------------------------------- */
+
+static int expr_token(Scanner * s) {
+  int t;
+  while (1) {
+    t = Scanner_token(s);
+    if (!((t == SWIG_TOKEN_BACKSLASH) || (t == SWIG_TOKEN_ENDLINE) || (t == SWIG_TOKEN_COMMENT)))
+      break;
+  }
+  return t;
+}
+
+/* -----------------------------------------------------------------------------
+ * Preprocessor_expr()
+ *
+ * Evaluates an arithmetic expression.  Returns the result and sets an error code.
+ * ----------------------------------------------------------------------------- */
+
+int Preprocessor_expr(DOH *s, int *error) {
+  int token = 0;
+  int op = 0;
+
+  sp = 0;
+  assert(s);
+  assert(scan);
+
+  Seek(s, 0, SEEK_SET);
+  /* Printf(stdout,"evaluating : '%s'\n", s); */
+  *error = 0;
+  Scanner_clear(scan);
+  Scanner_push(scan, s);
+
+  /* Put initial state onto the stack */
+  stack[sp].op = EXPR_TOP;
+  stack[sp].value = 0;
+
+  while (1) {
+    /* Look at the top of the stack */
+    switch (stack[sp].op) {
+    case EXPR_TOP:
+      /* An expression.   Can be a number or another expression enclosed in parens */
+      token = expr_token(scan);
+      if (!token) {
+	errmsg = "Expected an expression";
+	*error = 1;
+	return 0;
+      }
+      if ((token == SWIG_TOKEN_INT) || (token == SWIG_TOKEN_UINT) || (token == SWIG_TOKEN_LONG) || (token == SWIG_TOKEN_ULONG)) {
+	/* A number.  Reduce EXPR_TOP to an EXPR_VALUE */
+	char *c = Char(Scanner_text(scan));
+	stack[sp].value = (long) strtol(c, 0, 0);
+	stack[sp].svalue = 0;
+	/*        stack[sp].value = (long) atol(Char(Scanner_text(scan))); */
+	stack[sp].op = EXPR_VALUE;
+      } else if (token == SWIG_TOKEN_PLUS) {
+      } else if ((token == SWIG_TOKEN_MINUS) || (token == SWIG_TOKEN_LNOT) || (token == SWIG_TOKEN_NOT)) {
+	if (token == SWIG_TOKEN_MINUS)
+	  token = EXPR_UMINUS;
+	stack[sp].value = token;
+	stack[sp++].op = EXPR_OP;
+	stack[sp].op = EXPR_TOP;
+	stack[sp].svalue = 0;
+      } else if ((token == SWIG_TOKEN_LPAREN)) {
+	stack[sp++].op = EXPR_GROUP;
+	stack[sp].op = EXPR_TOP;
+	stack[sp].value = 0;
+	stack[sp].svalue = 0;
+      } else if (token == SWIG_TOKEN_ENDLINE) {
+      } else if ((token == SWIG_TOKEN_STRING)) {
+	stack[sp].svalue = NewString(Scanner_text(scan));
+	stack[sp].op = EXPR_VALUE;
+      } else if ((token == SWIG_TOKEN_ID)) {
+	stack[sp].value = 0;
+	stack[sp].svalue = 0;
+	stack[sp].op = EXPR_VALUE;
+      } else
+	goto syntax_error;
+      break;
+    case EXPR_VALUE:
+      /* A value is on the stack.   We may reduce or evaluate depending on what the next token is */
+      token = expr_token(scan);
+      if (!token) {
+	/* End of input. Might have to reduce if an operator is on stack */
+	while (sp > 0) {
+	  if (stack[sp - 1].op == EXPR_OP) {
+	    if (!reduce_op())
+	      goto reduce_error;
+	  } else if (stack[sp - 1].op == EXPR_GROUP) {
+	    errmsg = "Missing \')\'";
+	    *error = 1;
+	    return 0;
+	  } else
+	    goto syntax_error;
+	}
+	return stack[sp].value;
+      }
+      /* Token must be an operator */
+      switch (token) {
+      case SWIG_TOKEN_STAR:
+      case SWIG_TOKEN_EQUALTO:
+      case SWIG_TOKEN_NOTEQUAL:
+      case SWIG_TOKEN_PLUS:
+      case SWIG_TOKEN_MINUS:
+      case SWIG_TOKEN_AND:
+      case SWIG_TOKEN_LAND:
+      case SWIG_TOKEN_OR:
+      case SWIG_TOKEN_LOR:
+      case SWIG_TOKEN_XOR:
+      case SWIG_TOKEN_LESSTHAN:
+      case SWIG_TOKEN_GREATERTHAN:
+      case SWIG_TOKEN_LTEQUAL:
+      case SWIG_TOKEN_GTEQUAL:
+      case SWIG_TOKEN_SLASH:
+      case SWIG_TOKEN_PERCENT:
+      case SWIG_TOKEN_LSHIFT:
+      case SWIG_TOKEN_RSHIFT:
+	if ((sp == 0) || (stack[sp - 1].op == EXPR_GROUP)) {
+	  /* No possibility of reduce. Push operator and expression */
+	  sp++;
+	  stack[sp].op = EXPR_OP;
+	  stack[sp].value = token;
+	  sp++;
+	  stack[sp].op = EXPR_TOP;
+	  stack[sp].value = 0;
+	} else {
+	  if (stack[sp - 1].op != EXPR_OP)
+	    goto syntax_error_expected_operator;
+	  op = stack[sp - 1].value;	/* Previous operator */
+
+	  /* Now, depending on the precedence relationship between the last operator and the current
+	     we will reduce or push */
+
+	  if (prec[op] <= prec[token]) {
+	    /* Reduce the previous operator */
+	    if (!reduce_op())
+	      goto reduce_error;
+	  }
+	  sp++;
+	  stack[sp].op = EXPR_OP;
+	  stack[sp].value = token;
+	  sp++;
+	  stack[sp].op = EXPR_TOP;
+	  stack[sp].value = 0;
+	}
+	break;
+      case SWIG_TOKEN_RPAREN:
+	if (sp == 0)
+	  goto extra_rparen;
+
+	/* Might have to reduce operators first */
+	while ((sp > 0) && (stack[sp - 1].op == EXPR_OP)) {
+	  if (!reduce_op())
+	    goto reduce_error;
+	}
+	if ((sp == 0) || (stack[sp - 1].op != EXPR_GROUP))
+	  goto extra_rparen;
+	stack[sp - 1].op = EXPR_VALUE;
+	stack[sp - 1].value = stack[sp].value;
+	sp--;
+	break;
+      default:
+	goto syntax_error_expected_operator;
+	break;
+      }
+      break;
+
+    default:
+      fprintf(stderr, "Internal error in expression evaluator.\n");
+      abort();
+    }
+  }
+
+syntax_error:
+  errmsg = "Syntax error";
+  *error = 1;
+  return 0;
+
+syntax_error_expected_operator:
+  errmsg = "Syntax error: expected operator";
+  *error = 1;
+  return 0;
+
+reduce_error:
+  /*  errmsg has been set by reduce_op */
+  *error = 1;
+  return 0;
+
+extra_rparen:
+  errmsg = "Extra \')\'";
+  *error = 1;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Preprocessor_expr_error()
+ *
+ * Return error message set by the evaluator (if any)
+ * ----------------------------------------------------------------------------- */
+
+char *Preprocessor_expr_error() {
+  return errmsg;
+}
diff --git a/trunk/Source/Preprocessor/preprocessor.h b/trunk/Source/Preprocessor/preprocessor.h
new file mode 100644
index 0000000..4f7ff88
--- /dev/null
+++ b/trunk/Source/Preprocessor/preprocessor.h
@@ -0,0 +1,38 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * preprocessor.h
+ *
+ * SWIG preprocessor module.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id$ */
+
+#ifndef SWIG_PREPROCESSOR_H_
+#define SWIG_PREPROCESSOR_H_
+
+#include "swigwarn.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+  extern int Preprocessor_expr(String *s, int *error);
+  extern char *Preprocessor_expr_error(void);
+  extern Hash *Preprocessor_define(const String_or_char *str, int swigmacro);
+  extern void Preprocessor_undef(const String_or_char *name);
+  extern void Preprocessor_init(void);
+  extern void Preprocessor_delete(void);
+  extern String *Preprocessor_parse(String *s);
+  extern void Preprocessor_include_all(int);
+  extern void Preprocessor_import_all(int);
+  extern void Preprocessor_ignore_missing(int);
+  extern void Preprocessor_error_as_warning(int);
+  extern List *Preprocessor_depend(void);
+  extern void Preprocessor_expr_init(void);
+  extern void Preprocessor_expr_delete(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/trunk/Source/README b/trunk/Source/README
new file mode 100644
index 0000000..8d910e4
--- /dev/null
+++ b/trunk/Source/README
@@ -0,0 +1,30 @@
+SWIG Source directory
+
+This directory currently contains a mix of legacy SWIG1.1 code and
+recent development work.  As a result, it's still a little messy.
+Here is a rough breakdown of the directories:
+
+ Source/DOH          -  A core set of basic datatypes including
+                        strings, lists, hashes, and files.  Used
+                        extensively by the rest of SWIG.
+
+ Source/Swig         -  Swig core. Type-system, utility functions.
+
+ Source/Preprocessor -  SWIG C Preprocessor
+
+ Source/CParse       -  SWIG C Parser (still messy)
+
+ Source/Modules      -  Language modules.
+
+
+The following directories may be in CVS, but are largely deprecated:
+
+ Source/Modules1.1   -  Old SWIG-1.1 modules. Empty.
+
+ Source/LParse       -  Experimental parser.  Officially dead
+                        as CParse is more capable.
+
+ Source/SWIG1.1      -  Old SWIG1.1 core. Completely empty now.
+
+
+
diff --git a/trunk/Source/Swig/cwrap.c b/trunk/Source/Swig/cwrap.c
new file mode 100644
index 0000000..18920ec
--- /dev/null
+++ b/trunk/Source/Swig/cwrap.c
@@ -0,0 +1,1467 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * cwrap.c
+ *
+ * This file defines a variety of wrapping rules for C/C++ handling including
+ * the naming of local variables, calling conventions, and so forth.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_cwrap_c[] = "$Id$";
+
+#include "swig.h"
+
+extern int cparse_cplusplus;
+
+static Parm *nonvoid_parms(Parm *p) {
+  if (p) {
+    SwigType *t = Getattr(p, "type");
+    if (SwigType_type(t) == T_VOID)
+      return 0;
+  }
+  return p;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_parm_name()
+ *
+ * Generates a name for the ith argument in an argument list
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cparm_name(Parm *p, int i) {
+  String *name = NewStringf("arg%d", i + 1);
+  if (p) {
+    Setattr(p, "lname", name);
+  }
+
+  return name;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_clocal()
+ *
+ * Creates a string that declares a C local variable type.  Converts references
+ * and user defined types to pointers.
+ * ----------------------------------------------------------------------------- */
+
+static String *Swig_clocal(SwigType *t, const String_or_char *name, const String_or_char *value) {
+  String *decl;
+
+  decl = NewStringEmpty();
+
+  switch (SwigType_type(t)) {
+  case T_REFERENCE:
+    if (value) {
+      String *lstrname = SwigType_lstr(t, name);
+      String *lstr = SwigType_lstr(t, 0);
+      Printf(decl, "%s = (%s) &%s_defvalue", lstrname, lstr, name);
+      Delete(lstrname);
+      Delete(lstr);
+    } else {
+      String *lstrname = SwigType_lstr(t, name);
+      Printf(decl, "%s = 0", lstrname);
+      Delete(lstrname);
+    }
+    break;
+  case T_VOID:
+    break;
+  case T_VARARGS:
+    Printf(decl, "void *%s = 0", name);
+    break;
+
+  default:
+    if (value) {
+      String *lcaststr = SwigType_lcaststr(t, value);
+      String *lstr = SwigType_lstr(t, 0);
+      String *lstrn = SwigType_lstr(t, name);
+      Printf(decl, "%s = (%s) %s", lstrn, lstr, lcaststr);
+      Delete(lcaststr);
+      Delete(lstr);
+      Delete(lstrn);
+    } else {
+      String *lstrname = SwigType_lstr(t, name);
+      Append(decl, lstrname);
+      Delete(lstrname);
+    }
+  }
+  return decl;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_wrapped_var_convert()
+ *
+ * Converts a member variable for use in the get and set wrapper methods.
+ * This function only converts user defined types to pointers.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_wrapped_var_type(SwigType *t, int varcref) {
+  SwigType *ty;
+
+  if (!Strstr(t, "enum $unnamed")) {
+    ty = Copy(t);
+  } else {
+    /* Change the type for unnamed enum instance variables */
+    ty = NewString("int");
+  }
+
+  if (SwigType_isclass(t)) {
+    if (varcref) {
+      if (cparse_cplusplus) {
+	if (!SwigType_isconst(ty))
+	  SwigType_add_qualifier(ty, "const");
+	SwigType_add_reference(ty);
+      } else {
+	return Copy(ty);
+      }
+    } else {
+      SwigType_add_pointer(ty);
+    }
+  }
+  return ty;
+}
+
+String *Swig_wrapped_member_var_type(SwigType *t, int varcref) {
+  SwigType *ty;
+
+  if (!Strstr(t, "enum $unnamed")) {
+    ty = Copy(t);
+  } else {
+    /* Change the type for unnamed enum instance variables */
+    ty = NewString("int");
+  }
+  if (SwigType_isclass(t)) {
+    if (varcref) {
+      if (cparse_cplusplus) {
+	if (!SwigType_isconst(ty))
+	  SwigType_add_qualifier(ty, "const");
+	SwigType_add_reference(ty);
+      } else {
+	return Copy(ty);
+      }
+    } else {
+      SwigType_add_pointer(ty);
+    }
+  }
+  return ty;
+}
+
+
+static String *Swig_wrapped_var_deref(SwigType *t, String_or_char *name, int varcref) {
+  if (SwigType_isclass(t)) {
+    if (varcref) {
+      if (cparse_cplusplus) {
+	return NewStringf("*%s", name);
+      } else {
+	return NewStringf("%s", name);
+      }
+    } else {
+      return NewStringf("*%s", name);
+    }
+  } else {
+    return SwigType_rcaststr(t, name);
+  }
+}
+
+static String *Swig_wrapped_var_assign(SwigType *t, const String_or_char *name, int varcref) {
+  if (SwigType_isclass(t)) {
+    if (varcref) {
+      return NewStringf("%s", name);
+    } else {
+      return NewStringf("&%s", name);
+    }
+  } else {
+    return SwigType_lcaststr(t, name);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cargs()
+ *
+ * Emit all of the local variables for a list of parameters.  Returns the
+ * number of parameters.
+ * Default values for the local variables are only emitted if the compact default
+ * argument behaviour is required.
+ * ----------------------------------------------------------------------------- */
+int Swig_cargs(Wrapper *w, ParmList *p) {
+  int i = 0;
+  int compactdefargs = ParmList_is_compactdefargs(p);
+
+  while (p != 0) {
+    String *lname = Swig_cparm_name(p, i);
+    SwigType *pt = Getattr(p, "type");
+    if ((SwigType_type(pt) != T_VOID)) {
+      String *local = 0;
+      String *type = Getattr(p, "type");
+      /* default values only emitted if in compact default args mode */
+      String *pvalue = (compactdefargs) ? Getattr(p, "value") : 0;
+      SwigType *altty = SwigType_alttype(type, 0);
+      int tycode = SwigType_type(type);
+      if (tycode == T_REFERENCE) {
+	if (pvalue) {
+	  SwigType *tvalue;
+	  String *defname, *defvalue, *rvalue, *qvalue;
+	  rvalue = SwigType_typedef_resolve_all(pvalue);
+	  qvalue = SwigType_typedef_qualified(rvalue);
+	  defname = NewStringf("%s_defvalue", lname);
+	  tvalue = Copy(type);
+	  SwigType_del_reference(tvalue);
+	  tycode = SwigType_type(tvalue);
+	  if (tycode != T_USER) {
+	    /* plain primitive type, we copy the the def value */
+	    String *lstr = SwigType_lstr(tvalue, defname);
+	    defvalue = NewStringf("%s = %s", lstr, qvalue);
+	    Delete(lstr);
+	  } else {
+	    /* user type, we copy the reference value */
+	    String *str = SwigType_str(type, defname);
+	    defvalue = NewStringf("%s = %s", str, qvalue);
+	    Delete(str);
+	  }
+	  Wrapper_add_localv(w, defname, defvalue, NIL);
+	  Delete(tvalue);
+	  Delete(rvalue);
+	  Delete(qvalue);
+	  Delete(defname);
+	  Delete(defvalue);
+	}
+      } else if (!pvalue && ((tycode == T_POINTER) || (tycode == T_STRING))) {
+	pvalue = (String *) "0";
+      }
+      if (!altty) {
+	local = Swig_clocal(pt, lname, pvalue);
+      } else {
+	local = Swig_clocal(altty, lname, pvalue);
+	Delete(altty);
+      }
+      Wrapper_add_localv(w, lname, local, NIL);
+      Delete(local);
+      i++;
+    }
+    Delete(lname);
+    p = nextSibling(p);
+  }
+  return (i);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cresult()
+ *
+ * This function generates the C code needed to set the result of a C
+ * function call.  
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cresult(SwigType *t, const String_or_char *name, const String_or_char *decl) {
+  String *fcall;
+
+  fcall = NewStringEmpty();
+  switch (SwigType_type(t)) {
+  case T_VOID:
+    break;
+  case T_REFERENCE:
+    {
+      String *str = SwigType_str(t, "_result_ref");
+      Printf(fcall, "{\n");
+      Printf(fcall, "%s = ", str);
+      Delete(str);
+    }
+    break;
+  case T_USER:
+    Printf(fcall, "%s = ", name);
+    break;
+
+  default:
+    /* Normal return value */
+    {
+      String *lstr = SwigType_lstr(t, 0);
+      Printf(fcall, "%s = (%s)", name, lstr);
+      Delete(lstr);
+    }
+    break;
+  }
+
+  /* Now print out function call */
+  Append(fcall, decl);
+
+  /* A sick hack */
+  {
+    char *c = Char(decl) + Len(decl) - 1;
+    if (!((*c == ';') || (*c == '}')))
+      Append(fcall, ";");
+  }
+
+  if (SwigType_type(t) == T_REFERENCE) {
+    String *lstr = SwigType_lstr(t, 0);
+    Printf(fcall, "\n%s = (%s) &_result_ref;\n", name, lstr);
+    Append(fcall, "}");
+    Delete(lstr);
+  }
+  return fcall;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cfunction_call()
+ *
+ * Creates a string that calls a C function using the local variable rules
+ * defined above.
+ *
+ *    name(arg0, arg1, arg2, ... argn)
+ *
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cfunction_call(String_or_char *name, ParmList *parms) {
+  String *func;
+  int i = 0;
+  int comma = 0;
+  Parm *p = parms;
+  String *nname;
+
+  func = NewStringEmpty();
+  nname = SwigType_namestr(name);
+
+  /*
+     SWIGTEMPLATEDISAMBIGUATOR is compiler dependent (swiglabels.swg),
+     - SUN Studio 9 requires 'template', 
+     - gcc-3.4 forbids the use of 'template'.
+     the rest seems not caring very much,
+   */
+  if (SwigType_istemplate(name)) {
+    String *prefix = Swig_scopename_prefix(nname);
+    if (!prefix || Len(prefix) == 0) {
+      Printf(func, "%s(", nname);
+    } else {
+      String *last = Swig_scopename_last(nname);
+      Printf(func, "%s::SWIGTEMPLATEDISAMBIGUATOR %s(", prefix, last);
+      Delete(last);
+    }
+    Delete(prefix);
+  } else {
+    Printf(func, "%s(", nname);
+  }
+  Delete(nname);
+
+  while (p) {
+    SwigType *pt = Getattr(p, "type");
+    if ((SwigType_type(pt) != T_VOID)) {
+      SwigType *rpt = SwigType_typedef_resolve_all(pt);
+      String *pname = Swig_cparm_name(p, i);
+      String *rcaststr = SwigType_rcaststr(rpt, pname);
+
+      if (comma) {
+	Printv(func, ",", rcaststr, NIL);
+      } else {
+	Append(func, rcaststr);
+      }
+      Delete(rpt);
+      Delete(pname);
+      Delete(rcaststr);
+      comma = 1;
+      i++;
+    }
+    p = nextSibling(p);
+  }
+  Append(func, ")");
+  return func;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cmethod_call()
+ *
+ * Generates a string that calls a C++ method from a list of parameters.
+ * 
+ *    arg0->name(arg1, arg2, arg3, ..., argn)
+ *
+ * self is an argument that defines how to handle the first argument. Normally,
+ * it should be set to "this->".  With C++ proxy classes enabled, it could be
+ * set to "(*this)->" or some similar sequence.
+ * ----------------------------------------------------------------------------- */
+
+static String *Swig_cmethod_call(String_or_char *name, ParmList *parms, String_or_char *self, String *explicit_qualifier, SwigType *director_type) {
+  String *func, *nname;
+  int i = 0;
+  Parm *p = parms;
+  SwigType *pt;
+  int comma = 0;
+
+  func = NewStringEmpty();
+  if (!p)
+    return func;
+
+  if (!self)
+    self = (char *) "(this)->";
+  Append(func, self);
+
+  if (SwigType_istemplate(name) && (strncmp(Char(name), "operator ", 9) == 0)) {
+    /* fix for template + operators and compilers like gcc 3.3.5 */
+    String *tprefix = SwigType_templateprefix(name);
+    nname = tprefix;
+  } else {
+    nname = SwigType_namestr(name);
+  }
+
+  if (director_type) {
+    const char *pname = "darg";
+    String *rcaststr = SwigType_rcaststr(director_type, pname);
+    Replaceall(func, "this", rcaststr);
+    Delete(rcaststr);
+  } else {
+    pt = Getattr(p, "type");
+
+    /* If the method is invoked through a dereferenced pointer, we don't add any casts
+       (needed for smart pointers).  Otherwise, we cast to the appropriate type */
+
+    if (Strstr(func, "*this")) {
+      String *pname = Swig_cparm_name(p, 0);
+      Replaceall(func, "this", pname);
+      Delete(pname);
+    } else {
+      String *pname = Swig_cparm_name(p, 0);
+      String *rcaststr = SwigType_rcaststr(pt, pname);
+      Replaceall(func, "this", rcaststr);
+      Delete(rcaststr);
+      Delete(pname);
+    }
+
+    /*
+       SWIGTEMPLATEDESIMBUAGATOR is compiler dependent (swiglabels.swg),
+       - SUN Studio 9 requires 'template', 
+       - gcc-3.4 forbids the use of 'template' (correctly implementing the ISO C++ standard)
+       the others don't seem to care,
+     */
+    if (SwigType_istemplate(name))
+      Printf(func, "SWIGTEMPLATEDISAMBIGUATOR ");
+
+    if (explicit_qualifier) {
+      Printv(func, explicit_qualifier, "::", NIL);
+    }
+  }
+
+  Printf(func, "%s(", nname);
+
+  i++;
+  p = nextSibling(p);
+  while (p) {
+    pt = Getattr(p, "type");
+    if ((SwigType_type(pt) != T_VOID)) {
+      String *pname = Swig_cparm_name(p, i);
+      String *rcaststr = SwigType_rcaststr(pt, pname);
+      if (comma)
+	Append(func, ",");
+      Append(func, rcaststr);
+      Delete(rcaststr);
+      Delete(pname);
+      comma = 1;
+      i++;
+    }
+    p = nextSibling(p);
+  }
+  Append(func, ")");
+  Delete(nname);
+  return func;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cconstructor_call()
+ *
+ * Creates a string that calls a C constructor function.
+ *
+ *      calloc(1,sizeof(name));
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cconstructor_call(String_or_char *name) {
+  DOH *func;
+
+  func = NewStringEmpty();
+  Printf(func, "calloc(1, sizeof(%s))", name);
+  return func;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_cppconstructor_call()
+ *
+ * Creates a string that calls a C function using the local variable rules
+ * defined above.
+ *
+ *    name(arg0, arg1, arg2, ... argn)
+ *
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cppconstructor_base_call(String_or_char *name, ParmList *parms, int skip_self) {
+  String *func;
+  String *nname;
+  int i = 0;
+  int comma = 0;
+  Parm *p = parms;
+  SwigType *pt;
+  if (skip_self) {
+    if (p)
+      p = nextSibling(p);
+    i++;
+  }
+  nname = SwigType_namestr(name);
+  func = NewStringEmpty();
+  Printf(func, "new %s(", nname);
+  while (p) {
+    pt = Getattr(p, "type");
+    if ((SwigType_type(pt) != T_VOID)) {
+      String *rcaststr = 0;
+      String *pname = 0;
+      if (comma)
+	Append(func, ",");
+      if (!Getattr(p, "arg:byname")) {
+	pname = Swig_cparm_name(p, i);
+	i++;
+      } else {
+        pname = Getattr(p, "value");
+	if (pname)
+	  pname = Copy(pname);
+	else
+	  pname = Copy(Getattr(p, "name"));
+      }
+      rcaststr = SwigType_rcaststr(pt, pname);
+      Append(func, rcaststr);
+      Delete(rcaststr);
+      comma = 1;
+      Delete(pname);
+    }
+    p = nextSibling(p);
+  }
+  Append(func, ")");
+  Delete(nname);
+  return func;
+}
+
+String *Swig_cppconstructor_call(String_or_char *name, ParmList *parms) {
+  return Swig_cppconstructor_base_call(name, parms, 0);
+}
+
+String *Swig_cppconstructor_nodirector_call(String_or_char *name, ParmList *parms) {
+  return Swig_cppconstructor_base_call(name, parms, 1);
+}
+
+String *Swig_cppconstructor_director_call(String_or_char *name, ParmList *parms) {
+  return Swig_cppconstructor_base_call(name, parms, 0);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_rflag_search()
+ *
+ * This function searches for the class attribute 'attr' in the class
+ * 'n' or recursively in its bases.
+ *
+ * If you define SWIG_FAST_REC_SEARCH, the method will set the found
+ * 'attr' in the target class 'n'. If not, the method will set the
+ * 'noattr' one. This prevents of having to navigate the entire
+ * hierarchy tree everytime, so, it is an O(1) method...  or something
+ * like that. However, it populates all the parsed classes with the
+ * 'attr' and/or 'noattr' attributes.
+ *
+ * If you undefine the SWIG_FAST_REC_SEARCH no attribute will be set
+ * while searching. This could be slower for large projects with very
+ * large hierarchy trees... or maybe not. But it will be cleaner. 
+ *
+ * Maybe later a swig option can be added to switch at runtime.
+ *
+ * ----------------------------------------------------------------------------- */
+
+/* #define SWIG_FAST_REC_SEARCH 1 */
+String *Swig_rflag_search(Node *n, const String *attr, const String *noattr) {
+  String *f = 0;
+  n = Swig_methodclass(n);
+  if (GetFlag(n, noattr)) {
+    return 0;
+  }
+  f = GetFlagAttr(n, attr);
+  if (f) {
+    return f;
+  } else {
+    List *bl = Getattr(n, "bases");
+    if (bl) {
+      Iterator bi;
+      for (bi = First(bl); bi.item; bi = Next(bi)) {
+	f = Swig_rflag_search(bi.item, attr, noattr);
+	if (f) {
+#ifdef SWIG_FAST_REC_SEARCH
+	  SetFlagAttr(n, attr, f);
+#endif
+	  return f;
+	}
+      }
+    }
+  }
+#ifdef SWIG_FAST_REC_SEARCH
+  SetFlag(n, noattr);
+#endif
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_unref_call()
+ *
+ * find the unref call, if any.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_unref_call(Node *n) {
+  Node *cn = Swig_methodclass(n);
+  String *unref = Swig_rflag_search(cn, "feature:unref", "feature:nounref");
+  if (unref) {
+    String *pname = Swig_cparm_name(0, 0);
+    unref = NewString(unref);
+    Replaceall(unref, "$this", pname);
+    Replaceall(unref, "$self", pname);
+    Delete(pname);
+  }
+  return unref;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_ref_call()
+ *
+ * find the ref call, if any.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_ref_call(Node *n, const String *lname) {
+  Node *cn = Swig_methodclass(n);
+  String *ref = Swig_rflag_search(cn, "feature:ref", "feature:noref");
+  if (ref) {
+    ref = NewString(ref);
+    Replaceall(ref, "$this", lname);
+    Replaceall(ref, "$self", lname);
+  }
+  return ref;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cdestructor_call()
+ *
+ * Creates a string that calls a C destructor function.
+ *
+ *      free((char *) arg0);
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cdestructor_call(Node *n) {
+  String *unref = Swig_unref_call(n);
+
+  if (unref) {
+    return unref;
+  } else {
+    String *pname = Swig_cparm_name(0, 0);
+    String *call = NewStringf("free((char *) %s);", pname);
+    Delete(pname);
+    return call;
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_cppdestructor_call()
+ *
+ * Creates a string that calls a C destructor function.
+ *
+ *      delete arg1;
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cppdestructor_call(Node *n) {
+  String *unref = Swig_unref_call(n);
+  if (unref) {
+    return unref;
+  } else {
+    String *pname = Swig_cparm_name(0, 0);
+    String *call = NewStringf("delete %s;", pname);
+    Delete(pname);
+    return call;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_cmemberset_call()
+ *
+ * Generates a string that sets the name of a member in a C++ class or C struct.
+ *
+ *        arg0->name = arg1
+ *
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cmemberset_call(String_or_char *name, SwigType *type, String_or_char *self, int varcref) {
+  String *func;
+  String *pname0 = Swig_cparm_name(0, 0);
+  String *pname1 = Swig_cparm_name(0, 1);
+  func = NewStringEmpty();
+  if (!self)
+    self = NewString("(this)->");
+  else
+    self = NewString(self);
+  Replaceall(self, "this", pname0);
+  if (SwigType_type(type) != T_ARRAY) {
+    if (!Strstr(type, "enum $unnamed")) {
+      String *dref = Swig_wrapped_var_deref(type, pname1, varcref);
+      Printf(func, "if (%s) %s%s = %s", pname0, self, name, dref);
+      Delete(dref);
+    } else {
+      Printf(func, "if (%s && sizeof(int) == sizeof(%s%s)) *(int*)(void*)&(%s%s) = %s", pname0, self, name, self, name, pname1);
+    }
+  }
+  Delete(self);
+  Delete(pname0);
+  Delete(pname1);
+  return (func);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_cmemberget_call()
+ *
+ * Generates a string that sets the name of a member in a C++ class or C struct.
+ *
+ *        arg0->name
+ *
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_cmemberget_call(const String_or_char *name, SwigType *t, String_or_char *self, int varcref) {
+  String *func;
+  String *call;
+  String *pname0 = Swig_cparm_name(0, 0);
+  if (!self)
+    self = NewString("(this)->");
+  else
+    self = NewString(self);
+  Replaceall(self, "this", pname0);
+  func = NewStringEmpty();
+  call = Swig_wrapped_var_assign(t, "", varcref);
+  Printf(func, "%s (%s%s)", call, self, name);
+  Delete(self);
+  Delete(call);
+  Delete(pname0);
+  return func;
+}
+
+/* -----------------------------------------------------------------------------
+ * extension_code()
+ *
+ * Generates an extension function (a function defined in %extend)
+ *
+ *        return_type function_name(parms) code
+ *
+ * ----------------------------------------------------------------------------- */
+static String *extension_code(const String *function_name, ParmList *parms, SwigType *return_type, const String *code, int cplusplus, const String *self) {
+  String *parms_str = cplusplus ? ParmList_str_defaultargs(parms) : ParmList_str(parms);
+  String *sig = NewStringf("%s(%s)", function_name, parms_str);
+  String *rt_sig = SwigType_str(return_type, sig);
+  String *body = NewStringf("SWIGINTERN %s", rt_sig);
+  Printv(body, code, "\n", NIL);
+  if (self)
+    Replaceall(body, "$self", self);
+  Delete(parms_str);
+  Delete(sig);
+  Delete(rt_sig);
+  return body;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_add_extension_code()
+ *
+ * Generates an extension function (a function defined in %extend) and
+ * adds it to the "wrap:code" attribute of a node
+ *
+ * See also extension_code()
+ *
+ * ----------------------------------------------------------------------------- */
+int Swig_add_extension_code(Node *n, const String *function_name, ParmList *parms, SwigType *return_type, const String *code, int cplusplus, const String *self) {
+  String *body = extension_code(function_name, parms, return_type, code, cplusplus, self);
+  Setattr(n, "wrap:code", body);
+  Delete(body);
+  return SWIG_OK;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_MethodToFunction(Node *n)
+ *
+ * Converts a C++ method node to a function accessor function.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_MethodToFunction(Node *n, String *classname, int flags, SwigType *director_type, int is_director) {
+  String *name, *qualifier;
+  ParmList *parms;
+  SwigType *type;
+  Parm *p;
+  String *self = 0;
+
+  /* If smart pointer, change self dereferencing */
+  if (flags & CWRAP_SMART_POINTER) {
+    self = NewString("(*this)->");
+  }
+
+  /* If node is a member template expansion, we don't allow added code */
+  if (Getattr(n, "templatetype"))
+    flags &= ~(CWRAP_EXTEND);
+
+  name = Getattr(n, "name");
+  qualifier = Getattr(n, "qualifier");
+  parms = CopyParmList(nonvoid_parms(Getattr(n, "parms")));
+
+  type = NewString(classname);
+  if (qualifier) {
+    SwigType_push(type, qualifier);
+  }
+  SwigType_add_pointer(type);
+  p = NewParm(type, "self");
+  Setattr(p, "self", "1");
+  Setattr(p, "hidden","1");
+  /*
+     Disable the 'this' ownership in 'self' to manage inplace
+     operations like:
+
+     A& A::operator+=(int i) { ...; return *this;}
+
+     Here the 'self' parameter ownership needs to be disabled since
+     there could be two objects sharing the same 'this' pointer: the
+     input and the result one. And worse, the pointer could be deleted
+     in one of the objects (input), leaving the other (output) with
+     just a seg. fault to happen.
+
+     To avoid the previous problem, use
+
+     %feature("self:disown") *::operator+=;
+     %feature("new") *::operator+=;
+
+     These two lines just transfer the ownership of the 'this' pointer
+     from the input to the output wrapping object.
+
+     This happens in python, but may also happens in other target
+     languages.
+   */
+  if (GetFlag(n, "feature:self:disown")) {
+    Setattr(p, "wrap:disown", "1");
+  }
+  set_nextSibling(p, parms);
+  Delete(type);
+
+  /* Generate action code for the access */
+  if (!(flags & CWRAP_EXTEND)) {
+    String *explicit_qualifier = 0;
+    String *call = 0;
+    String *cres = 0;
+    String *explicitcall_name = 0;
+    int pure_virtual = !(Cmp(Getattr(n, "storage"), "virtual")) && !(Cmp(Getattr(n, "value"), "0"));
+
+    /* Call the explicit method rather than allow for a polymorphic call */
+    if ((flags & CWRAP_DIRECTOR_TWO_CALLS) || (flags & CWRAP_DIRECTOR_ONE_CALL)) {
+      String *access = Getattr(n, "access");
+      if (access && (Cmp(access, "protected") == 0)) {
+	/* If protected access (can only be if a director method) then call the extra public accessor method (language module must provide this) */
+	String *explicit_qualifier_tmp = SwigType_namestr(Getattr(Getattr(parentNode(n), "typescope"), "qname"));
+	explicitcall_name = NewStringf("%sSwigPublic", name);
+	explicit_qualifier = NewStringf("SwigDirector_%s", explicit_qualifier_tmp);
+	Delete(explicit_qualifier_tmp);
+      } else {
+	explicit_qualifier = SwigType_namestr(Getattr(Getattr(parentNode(n), "typescope"), "qname"));
+      }
+    }
+
+    call = Swig_cmethod_call(explicitcall_name ? explicitcall_name : name, p, self, explicit_qualifier, director_type);
+    cres = Swig_cresult(Getattr(n, "type"), "result", call);
+
+    if (pure_virtual && is_director && (flags & CWRAP_DIRECTOR_TWO_CALLS)) {
+      String *qualifier = SwigType_namestr(Getattr(Getattr(parentNode(n), "typescope"), "qname"));
+      Delete(cres);
+      cres = NewStringf("Swig::DirectorPureVirtualException::raise(\"%s::%s\");", qualifier, name);
+      Delete(qualifier);
+    }
+
+    if (flags & CWRAP_DIRECTOR_TWO_CALLS) {
+      /* Create two method calls, one to call the explicit method, the other a normal polymorphic function call */
+      String *cres_both_calls = NewStringf("");
+      String *call_extra = Swig_cmethod_call(name, p, self, 0, director_type);
+      String *cres_extra = Swig_cresult(Getattr(n, "type"), "result", call_extra);
+      Printv(cres_both_calls, "if (upcall) {\n", cres, "\n", "} else {", cres_extra, "\n}", NIL);
+      Setattr(n, "wrap:action", cres_both_calls);
+      Delete(cres_extra);
+      Delete(call_extra);
+      Delete(cres_both_calls);
+    } else {
+      Setattr(n, "wrap:action", cres);
+    }
+
+    Delete(explicitcall_name);
+    Delete(call);
+    Delete(cres);
+    Delete(explicit_qualifier);
+  } else {
+    /* Methods with default arguments are wrapped with additional methods for each default argument,
+     * however, only one extra %extend method is generated. */
+
+    String *defaultargs = Getattr(n, "defaultargs");
+    String *code = Getattr(n, "code");
+    String *cname = Getattr(n, "classname") ? Getattr(n, "classname") : classname;
+    String *membername = Swig_name_member(cname, name);
+    String *mangled = Swig_name_mangle(membername);
+    int is_smart_pointer = flags & CWRAP_SMART_POINTER;
+
+    type = Getattr(n, "type");
+
+    /* Check if the method is overloaded.   If so, and it has code attached, we append an extra suffix
+       to avoid a name-clash in the generated wrappers.  This allows overloaded methods to be defined
+       in C. */
+    if (Getattr(n, "sym:overloaded") && code) {
+      Append(mangled, Getattr(defaultargs ? defaultargs : n, "sym:overname"));
+    }
+
+    /* See if there is any code that we need to emit */
+    if (!defaultargs && code && !is_smart_pointer) {
+      Swig_add_extension_code(n, mangled, p, type, code, cparse_cplusplus, "self");
+    }
+    if (is_smart_pointer) {
+      int i = 0;
+      Parm *pp = p;
+      String *func = NewStringf("%s(", mangled);
+      String *cres;
+
+      if (Cmp(Getattr(n, "storage"), "static") != 0) {
+	String *pname = Swig_cparm_name(pp, i);
+        String *ctname = SwigType_namestr(cname);
+	String *fadd = NewStringf("(%s*)(%s)->operator ->()", ctname, pname);
+	Append(func, fadd);
+        Delete(ctname);
+	Delete(fadd);
+	Delete(pname);
+	pp = nextSibling(pp);
+	if (pp)
+	  Append(func, ",");
+      } else {
+	pp = nextSibling(pp);
+      }
+      ++i;
+      while (pp) {
+	SwigType *pt = Getattr(pp, "type");
+	if ((SwigType_type(pt) != T_VOID)) {
+	  String *pname = Swig_cparm_name(pp, i++);
+	  String *rcaststr = SwigType_rcaststr(pt, pname);
+	  Append(func, rcaststr);
+	  Delete(rcaststr);
+	  Delete(pname);
+	  pp = nextSibling(pp);
+	  if (pp)
+	    Append(func, ",");
+	}
+      }
+      Append(func, ")");
+      cres = Swig_cresult(Getattr(n, "type"), "result", func);
+      Setattr(n, "wrap:action", cres);
+      Delete(cres);
+    } else {
+      String *call = Swig_cfunction_call(mangled, p);
+      String *cres = Swig_cresult(Getattr(n, "type"), "result", call);
+      Setattr(n, "wrap:action", cres);
+      Delete(call);
+      Delete(cres);
+    }
+
+    Delete(membername);
+    Delete(mangled);
+  }
+  Setattr(n, "parms", p);
+  Delete(p);
+  Delete(self);
+  Delete(parms);
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_methodclass()
+ *
+ * This function returns the class node for a given method or class.
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_methodclass(Node *n) {
+  Node *nodetype = nodeType(n);
+  if (Cmp(nodetype, "class") == 0)
+    return n;
+  return GetFlag(n, "feature:extend") ? parentNode(parentNode(n)) : parentNode(n);
+}
+
+int Swig_directorclass(Node *n) {
+  Node *classNode = Swig_methodclass(n);
+  assert(classNode != 0);
+  return (Getattr(classNode, "vtable") != 0);
+}
+
+Node *Swig_directormap(Node *module, String *type) {
+  int is_void = !Cmp(type, "void");
+  if (!is_void && module) {
+    /* ?? follow the inheritance hierarchy? */
+
+    String *base = SwigType_base(type);
+
+    Node *directormap = Getattr(module, "wrap:directormap");
+    if (directormap)
+      return Getattr(directormap, base);
+  }
+  return 0;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_ConstructorToFunction()
+ *
+ * This function creates a C wrapper for a C constructor function. 
+ * ----------------------------------------------------------------------------- */
+
+int Swig_ConstructorToFunction(Node *n, String *classname, String *none_comparison, String *director_ctor, int cplus, int flags) {
+  ParmList *parms;
+  Parm *prefix_args;
+  Parm *p;
+  ParmList *directorparms;
+  SwigType *type;
+  Node *classNode;
+  int use_director;
+
+  classNode = Swig_methodclass(n);
+  use_director = Swig_directorclass(n);
+
+  parms = CopyParmList(nonvoid_parms(Getattr(n, "parms")));
+
+  /* Prepend the list of prefix_args (if any) */
+  prefix_args = Getattr(n, "director:prefix_args");
+  if (prefix_args != NIL) {
+    Parm *p2, *p3;
+
+    directorparms = CopyParmList(prefix_args);
+    for (p = directorparms; nextSibling(p); p = nextSibling(p));
+    for (p2 = parms; p2; p2 = nextSibling(p2)) {
+      p3 = CopyParm(p2);
+      set_nextSibling(p, p3);
+      Delete(p3);
+      p = p3;
+    }
+  } else
+    directorparms = parms;
+
+  type = NewString(classname);
+  SwigType_add_pointer(type);
+
+  if (flags & CWRAP_EXTEND) {
+    /* Constructors with default arguments are wrapped with additional constructor methods for each default argument,
+     * however, only one extra %extend method is generated. */
+    String *call;
+    String *cres;
+    String *defaultargs = Getattr(n, "defaultargs");
+    String *code = Getattr(n, "code");
+    String *membername = Swig_name_construct(classname);
+    String *mangled = Swig_name_mangle(membername);
+
+    /* Check if the constructor is overloaded.   If so, and it has code attached, we append an extra suffix
+       to avoid a name-clash in the generated wrappers.  This allows overloaded constructors to be defined
+       in C. */
+    if (Getattr(n, "sym:overloaded") && code) {
+      Append(mangled, Getattr(defaultargs ? defaultargs : n, "sym:overname"));
+    }
+
+    /* See if there is any code that we need to emit */
+    if (!defaultargs && code) {
+      Swig_add_extension_code(n, mangled, parms, type, code, cparse_cplusplus, "self");
+    }
+
+    call = Swig_cfunction_call(mangled, parms);
+    cres = Swig_cresult(type, "result", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(cres);
+    Delete(call);
+    Delete(membername);
+    Delete(mangled);
+  } else {
+    if (cplus) {
+      /* if a C++ director class exists, create it rather than the original class */
+      if (use_director) {
+	Node *parent = Swig_methodclass(n);
+	int abstract = Getattr(parent, "abstract") != 0;
+	String *name = Getattr(parent, "sym:name");
+	String *directorname = NewStringf("SwigDirector_%s", name);
+	String *action = NewStringEmpty();
+	String *tmp_none_comparison = Copy(none_comparison);
+	String *director_call;
+	String *nodirector_call;
+
+	Replaceall(tmp_none_comparison, "$arg", "arg1");
+
+	director_call = Swig_cppconstructor_director_call(directorname, directorparms);
+	nodirector_call = Swig_cppconstructor_nodirector_call(classname, parms);
+
+	if (abstract) {
+	  /* whether or not the abstract class has been subclassed in python,
+	   * create a director instance (there's no way to create a normal
+	   * instance).  if any of the pure virtual methods haven't been
+	   * implemented in the target language, calls to those methods will
+	   * generate Swig::DirectorPureVirtualException exceptions.
+	   */
+	  String *cres = Swig_cresult(type, "result", director_call);
+	  Append(action, cres);
+	  Delete(cres);
+	} else {
+	  /* (scottm): The code for creating a new director is now a string
+	     template that gets passed in via the director_ctor argument.
+
+	     $comparison : an 'if' comparison from none_comparison
+	     $director_new: Call new for director class
+	     $nondirector_new: Call new for non-director class
+	   */
+	  String *cres;
+	  Append(action, director_ctor);
+	  Replaceall(action, "$comparison", tmp_none_comparison);
+
+	  cres = Swig_cresult(type, "result", director_call);
+	  Replaceall(action, "$director_new", cres);
+	  Delete(cres);
+
+	  cres = Swig_cresult(type, "result", nodirector_call);
+	  Replaceall(action, "$nondirector_new", cres);
+	  Delete(cres);
+	}
+	Setattr(n, "wrap:action", action);
+	Delete(tmp_none_comparison);
+	Delete(action);
+	Delete(directorname);
+      } else {
+	String *call = Swig_cppconstructor_call(classname, parms);
+	String *cres = Swig_cresult(type, "result", call);
+	Setattr(n, "wrap:action", cres);
+	Delete(cres);
+	Delete(call);
+      }
+    } else {
+      String *call = Swig_cconstructor_call(classname);
+      String *cres = Swig_cresult(type, "result", call);
+      Setattr(n, "wrap:action", cres);
+      Delete(cres);
+      Delete(call);
+    }
+  }
+  Setattr(n, "type", type);
+  Setattr(n, "parms", parms);
+  Delete(type);
+  if (directorparms != parms)
+    Delete(directorparms);
+  Delete(parms);
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_DestructorToFunction()
+ *
+ * This function creates a C wrapper for a destructor function.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_DestructorToFunction(Node *n, String *classname, int cplus, int flags) {
+  SwigType *type;
+  Parm *p;
+
+  type = NewString(classname);
+  SwigType_add_pointer(type);
+  p = NewParm(type, "self");
+  Setattr(p, "self", "1");
+  Setattr(p, "hidden", "1");
+  Setattr(p, "wrap:disown", "1");
+  Delete(type);
+  type = NewString("void");
+
+  if (flags & CWRAP_EXTEND) {
+    String *cres;
+    String *call;
+    String *membername, *mangled, *code;
+    membername = Swig_name_destroy(classname);
+    mangled = Swig_name_mangle(membername);
+    code = Getattr(n, "code");
+    if (code) {
+      Swig_add_extension_code(n, mangled, p, type, code, cparse_cplusplus, "self");
+    }
+    call = Swig_cfunction_call(mangled, p);
+    cres = NewStringf("%s;", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(membername);
+    Delete(mangled);
+    Delete(call);
+    Delete(cres);
+  } else {
+    if (cplus) {
+      String *call = Swig_cppdestructor_call(n);
+      String *cres = NewStringf("%s", call);
+      Setattr(n, "wrap:action", cres);
+      Delete(call);
+      Delete(cres);
+    } else {
+      String *call = Swig_cdestructor_call(n);
+      String *cres = NewStringf("%s", call);
+      Setattr(n, "wrap:action", cres);
+      Delete(call);
+      Delete(cres);
+    }
+  }
+  Setattr(n, "type", type);
+  Setattr(n, "parms", p);
+  Delete(type);
+  Delete(p);
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_MembersetToFunction()
+ *
+ * This function creates a C wrapper for setting a structure member.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_MembersetToFunction(Node *n, String *classname, int flags) {
+  String *name;
+  ParmList *parms;
+  Parm *p;
+  SwigType *t;
+  SwigType *ty;
+  SwigType *type;
+  SwigType *void_type = NewString("void");
+  String *membername;
+  String *mangled;
+  String *self = 0;
+  String *sname;
+
+  int varcref = flags & CWRAP_NATURAL_VAR;
+
+  if (flags & CWRAP_SMART_POINTER) {
+    self = NewString("(*this)->");
+  }
+  if (flags & CWRAP_ALL_PROTECTED_ACCESS) {
+    self = NewStringf("darg->");
+  }
+
+  name = Getattr(n, "name");
+  type = Getattr(n, "type");
+
+  sname = Swig_name_set(name);
+  membername = Swig_name_member(classname, sname);
+  mangled = Swig_name_mangle(membername);
+
+  t = NewString(classname);
+  SwigType_add_pointer(t);
+  parms = NewParm(t, "self");
+  Setattr(parms, "self", "1");
+  Setattr(parms, "hidden","1");
+  Delete(t);
+
+  ty = Swig_wrapped_member_var_type(type, varcref);
+  p = NewParm(ty, name);
+  Setattr(parms, "hidden", "1");
+  set_nextSibling(parms, p);
+
+  /* If the type is a pointer or reference.  We mark it with a special wrap:disown attribute */
+  if (SwigType_check_decl(type, "p.")) {
+    Setattr(p, "wrap:disown", "1");
+  }
+  Delete(p);
+
+  if (flags & CWRAP_EXTEND) {
+    String *call;
+    String *cres;
+    String *code = Getattr(n, "code");
+    if (code) {
+      /* I don't think this ever gets run - WSF */
+      Swig_add_extension_code(n, mangled, parms, void_type, code, cparse_cplusplus, "self");
+    }
+    call = Swig_cfunction_call(mangled, parms);
+    cres = NewStringf("%s;", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(call);
+    Delete(cres);
+  } else {
+    String *call = Swig_cmemberset_call(name, type, self, varcref);
+    String *cres = NewStringf("%s;", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(call);
+    Delete(cres);
+  }
+  Setattr(n, "type", void_type);
+  Setattr(n, "parms", parms);
+  Delete(parms);
+  Delete(ty);
+  Delete(void_type);
+  Delete(membername);
+  Delete(sname);
+  Delete(mangled);
+  Delete(self);
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_MembergetToFunction()
+ *
+ * This function creates a C wrapper for getting a structure member.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_MembergetToFunction(Node *n, String *classname, int flags) {
+  String *name;
+  ParmList *parms;
+  SwigType *t;
+  SwigType *ty;
+  SwigType *type;
+  String *membername;
+  String *mangled;
+  String *self = 0;
+  String *gname;
+
+  int varcref = flags & CWRAP_NATURAL_VAR;
+
+  if (flags & CWRAP_SMART_POINTER) {
+    if (checkAttribute(n, "storage", "static")) {
+      Node *sn = Getattr(n, "cplus:staticbase");
+      String *base = Getattr(sn, "name");
+      self = NewStringf("%s::", base);
+    } else {
+      self = NewString("(*this)->");
+    }
+  }
+  if (flags & CWRAP_ALL_PROTECTED_ACCESS) {
+    self = NewStringf("darg->");
+  }
+
+  name = Getattr(n, "name");
+  type = Getattr(n, "type");
+
+  gname = Swig_name_get(name);
+  membername = Swig_name_member(classname, gname);
+  mangled = Swig_name_mangle(membername);
+
+  t = NewString(classname);
+  SwigType_add_pointer(t);
+  parms = NewParm(t, "self");
+  Setattr(parms, "self", "1");
+  Setattr(parms, "hidden","1");
+  Delete(t);
+
+  ty = Swig_wrapped_member_var_type(type, varcref);
+  if (flags & CWRAP_EXTEND) {
+    String *call;
+    String *cres;
+
+    String *code = Getattr(n, "code");
+    if (code) {
+      /* I don't think this ever gets run - WSF */
+      Swig_add_extension_code(n, mangled, parms, ty, code, cparse_cplusplus, "self");
+    }
+    call = Swig_cfunction_call(mangled, parms);
+    cres = Swig_cresult(ty, "result", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(cres);
+    Delete(call);
+  } else {
+    String *call = Swig_cmemberget_call(name, type, self, varcref);
+    String *cres = Swig_cresult(ty, "result", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(call);
+    Delete(cres);
+  }
+  Setattr(n, "type", ty);
+  Setattr(n, "parms", parms);
+  Delete(parms);
+  Delete(ty);
+  Delete(membername);
+  Delete(gname);
+  Delete(mangled);
+
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_VarsetToFunction()
+ *
+ * This function creates a C wrapper for setting a global variable or static member
+ * variable.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_VarsetToFunction(Node *n, int flags) {
+  String *name, *nname;
+  ParmList *parms;
+  SwigType *type, *ty;
+
+  int varcref = flags & CWRAP_NATURAL_VAR;
+
+  name = Getattr(n, "name");
+  type = Getattr(n, "type");
+  nname = SwigType_namestr(name);
+  ty = Swig_wrapped_var_type(type, varcref);
+  parms = NewParm(ty, name);
+
+  if (flags & CWRAP_EXTEND) {
+    String *sname = Swig_name_set(name);
+    String *mangled = Swig_name_mangle(sname);
+    String *call = Swig_cfunction_call(mangled, parms);
+    String *cres = NewStringf("%s;", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(cres);
+    Delete(call);
+    Delete(mangled);
+    Delete(sname);
+  } else {
+    if (!Strstr(type, "enum $unnamed")) {
+      String *pname = Swig_cparm_name(0, 0);
+      String *dref = Swig_wrapped_var_deref(type, pname, varcref);
+      String *call = NewStringf("%s = %s;", nname, dref);
+      Setattr(n, "wrap:action", call);
+      Delete(call);
+      Delete(dref);
+      Delete(pname);
+    } else {
+      String *pname = Swig_cparm_name(0, 0);
+      String *call = NewStringf("if (sizeof(int) == sizeof(%s)) *(int*)(void*)&(%s) = %s;", nname, nname, pname);
+      Setattr(n, "wrap:action", call);
+      Delete(pname);
+      Delete(call);
+    }
+  }
+  Setattr(n, "type", "void");
+  Setattr(n, "parms", parms);
+  Delete(parms);
+  Delete(ty);
+  Delete(nname);
+  return SWIG_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_VargetToFunction()
+ *
+ * This function creates a C wrapper for getting a global variable or static member
+ * variable.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_VargetToFunction(Node *n, int flags) {
+  String *cres, *call;
+  String *name;
+  SwigType *type;
+  SwigType *ty = 0;
+
+  int varcref = flags & CWRAP_NATURAL_VAR;
+
+  name = Getattr(n, "name");
+  type = Getattr(n, "type");
+  ty = Swig_wrapped_var_type(type, varcref);
+
+  if (flags & CWRAP_EXTEND) {
+    String *sname = Swig_name_get(name);
+    String *mangled = Swig_name_mangle(sname);
+    call = Swig_cfunction_call(mangled, 0);
+    cres = Swig_cresult(ty, "result", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(mangled);
+    Delete(sname);
+  } else {
+    String *nname = SwigType_namestr(name);
+    call = Swig_wrapped_var_assign(type, nname, varcref);
+    cres = Swig_cresult(ty, "result", call);
+    Setattr(n, "wrap:action", cres);
+    Delete(nname);
+  }
+
+  Setattr(n, "type", ty);
+  Delattr(n, "parms");
+  Delete(cres);
+  Delete(call);
+  Delete(ty);
+  return SWIG_OK;
+}
diff --git a/trunk/Source/Swig/deprecate.c b/trunk/Source/Swig/deprecate.c
new file mode 100644
index 0000000..475d2c6
--- /dev/null
+++ b/trunk/Source/Swig/deprecate.c
@@ -0,0 +1,105 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * deprecate.c
+ *
+ * The functions in this file are SWIG core functions that are deprecated 
+ * or which do not fit in nicely with everything else.  Generally this means
+ * that the function and/or API needs to be changed in some future release.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_deprecate_c[] = "$Id: parms.c 9630 2007-01-02 21:17:19Z beazley $";
+
+#include "swig.h"
+
+/* ---------------------------------------------------------------------
+ * ParmList_is_compactdefargs()
+ *
+ * Returns 1 if the parameter list passed in is marked for compact argument
+ * handling (by the "compactdefargs" attribute). Otherwise returns 0.
+ * ---------------------------------------------------------------------- */
+
+/* Discussion:
+
+  "compactdefargs" is a property set by the Parser to indicate special
+  handling of default arguments.   This property seems to be something that
+  is associated with functions and methods rather than low-level ParmList
+  objects.   Therefore, I don't like the fact that this special purpose
+  feature is bolted onto the side of ParmList objects.
+
+  Proposed solution:
+
+     1. "compactdefargs" should be a feature set on function/method nodes
+        instead of ParmList objects.  For example, if you have a function,
+        you would check the function node to see if the parameters are
+        to be handled in this way.
+
+
+  Difficulties:
+
+     1. This is used by functions in cwrap.c and emit.cxx, none of which
+        are passed information about the function/method node.   We might
+        have to change the API of those functions to make this work correctly.
+        For example:
+
+           int emit_num_required(ParmList *parms)
+
+        might become
+
+           int emit_num_required(ParmList *parms, int compactargs)
+
+*/
+
+int ParmList_is_compactdefargs(ParmList *p) {
+  int compactdefargs = 0;
+
+  if (p) {
+    compactdefargs = Getattr(p, "compactdefargs") ? 1 : 0;
+
+    /* The "compactdefargs" attribute should only be set on the first parameter in the list.
+     * However, sometimes an extra parameter is inserted at the beginning of the parameter list,
+     * so we check the 2nd parameter too. */
+    if (!compactdefargs) {
+      Parm *nextparm = nextSibling(p);
+      compactdefargs = (nextparm && Getattr(nextparm, "compactdefargs")) ? 1 : 0;
+    }
+  }
+
+  return compactdefargs;
+}
+
+/* ---------------------------------------------------------------------
+ * ParmList_errorstr()
+ *
+ * Generate a prototype string suitable for use in error/warning messages.
+ * This function is aware of hidden parameters.
+ * ---------------------------------------------------------------------- */
+
+/* Discussion.  This function is used to generate error messages, but take 
+   into account that there might be a hidden parameter.  Although this involves
+   parameter lists, it really isn't a core feature of swigparm.h or parms.c.
+   This is because the "hidden" attribute of parameters is added elsewhere (cwrap.c).
+
+   For now, this function is placed here because it doesn't really seem to fit in
+   with the parms.c interface.
+ 
+*/
+
+String *ParmList_errorstr(ParmList *p) {
+  String *out = NewStringEmpty();
+  while (p) {
+    if (Getattr(p,"hidden")) {
+      p = nextSibling(p);
+    } else {
+      String *pstr = SwigType_str(Getattr(p, "type"), 0);
+      Append(out, pstr);
+      p = nextSibling(p);
+      if (p) {
+	Append(out, ",");
+      }
+      Delete(pstr);
+    }
+  }
+  return out;
+}
diff --git a/trunk/Source/Swig/error.c b/trunk/Source/Swig/error.c
new file mode 100644
index 0000000..1eaba1f
--- /dev/null
+++ b/trunk/Source/Swig/error.c
@@ -0,0 +1,277 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * error.c
+ *
+ * Error handling functions.   These are used to issue warnings and
+ * error messages.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_error_c[] = "$Id$";
+
+#include "swig.h"
+#include <stdarg.h>
+#include <ctype.h>
+
+/* -----------------------------------------------------------------------------
+ * Commentary on the warning filter.
+ *
+ * The warning filter is a string of numbers prefaced by (-) or (+) to
+ * indicate whether or not a warning message is displayed.  For example:
+ *
+ *      "-304-201-140+210+201"
+ *
+ * The filter string is scanned left to right and the first occurrence
+ * of a warning number is used to determine printing behavior.
+ *
+ * The same number may appear more than once in the string.  For example, in the 
+ * above string, "201" appears twice.  This simply means that warning 201
+ * was disabled after it was previously enabled.  This may only be temporary
+ * setting--the first number may be removed later in which case the warning
+ * is reenabled.
+ * ----------------------------------------------------------------------------- */
+
+#if defined(_WIN32)
+#  define  DEFAULT_ERROR_MSG_FORMAT EMF_MICROSOFT
+#else
+#  define  DEFAULT_ERROR_MSG_FORMAT EMF_STANDARD
+#endif
+static ErrorMessageFormat msg_format = DEFAULT_ERROR_MSG_FORMAT;
+static int silence = 0;		/* Silent operation */
+static String *filter = 0;	/* Warning filter */
+static int warnall = 0;
+static int nwarning = 0;
+static int nerrors = 0;
+
+static int init_fmt = 0;
+static char wrn_wnum_fmt[64];
+static char wrn_nnum_fmt[64];
+static char err_line_fmt[64];
+static char err_eof_fmt[64];
+
+static String *format_filename(const String_or_char *filename);
+
+/* -----------------------------------------------------------------------------
+ * Swig_warning()
+ *
+ * Issue a warning message
+ * ----------------------------------------------------------------------------- */
+
+void Swig_warning(int wnum, const String_or_char *filename, int line, const char *fmt, ...) {
+  String *out;
+  char *msg;
+  int wrn = 1;
+  va_list ap;
+  if (silence)
+    return;
+  if (!init_fmt)
+    Swig_error_msg_format(DEFAULT_ERROR_MSG_FORMAT);
+
+  va_start(ap, fmt);
+
+  out = NewStringEmpty();
+  vPrintf(out, fmt, ap);
+
+  msg = Char(out);
+  if (isdigit((unsigned char) *msg)) {
+    unsigned long result = strtoul(msg, &msg, 10);
+    if (msg != Char(out)) {
+      msg++;
+      wnum = result;
+    }
+  }
+
+  /* Check in the warning filter */
+  if (filter) {
+    char temp[32];
+    char *c;
+    char *f = Char(filter);
+    sprintf(temp, "%d", wnum);
+    while (*f != '\0' && (c = strstr(f, temp))) {
+      if (*(c - 1) == '-') {
+	wrn = 0;		/* Warning disabled */
+        break;
+      }
+      if (*(c - 1) == '+') {
+	wrn = 1;		/* Warning enabled */
+        break;
+      }
+      f += strlen(temp);
+    }
+  }
+  if (warnall || wrn) {
+    String *formatted_filename = format_filename(filename);
+    if (wnum) {
+      Printf(stderr, wrn_wnum_fmt, formatted_filename, line, wnum);
+    } else {
+      Printf(stderr, wrn_nnum_fmt, formatted_filename, line);
+    }
+    Printf(stderr, "%s", msg);
+    nwarning++;
+    Delete(formatted_filename);
+  }
+  Delete(out);
+  va_end(ap);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_error()
+ *
+ * Issue an error message
+ * ----------------------------------------------------------------------------- */
+
+void Swig_error(const String_or_char *filename, int line, const char *fmt, ...) {
+  va_list ap;
+  String *formatted_filename = NULL;
+
+  if (silence)
+    return;
+  if (!init_fmt)
+    Swig_error_msg_format(DEFAULT_ERROR_MSG_FORMAT);
+
+  va_start(ap, fmt);
+  formatted_filename = format_filename(filename);
+  if (line > 0) {
+    Printf(stderr, err_line_fmt, formatted_filename, line);
+  } else {
+    Printf(stderr, err_eof_fmt, formatted_filename);
+  }
+  vPrintf(stderr, fmt, ap);
+  va_end(ap);
+  nerrors++;
+  Delete(formatted_filename);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_error_count()
+ *
+ * Returns number of errors received.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_error_count(void) {
+  return nerrors;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_error_silent()
+ *
+ * Set silent flag
+ * ----------------------------------------------------------------------------- */
+
+void Swig_error_silent(int s) {
+  silence = s;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_warnfilter()
+ *
+ * Takes a comma separate list of warning numbers and puts in the filter.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_warnfilter(const String_or_char *wlist, int add) {
+  char *c;
+  char *cw;
+  String *s;
+  if (!filter)
+    filter = NewStringEmpty();
+
+  s = NewString("");
+  Clear(s);
+  cw = Char(wlist);
+  while (*cw != '\0') {
+    if (*cw != ' ') {
+      Putc(*cw, s);
+    }
+    ++cw;
+  }
+  c = Char(s);
+  c = strtok(c, ", ");
+  while (c) {
+    if (isdigit((int) *c) || (*c == '+') || (*c == '-')) {
+      /* Even if c is a digit, the rest of the string might not be, eg in the case of typemap 
+       * warnings (a bit odd really), eg: %warnfilter(SWIGWARN_TYPEMAP_CHARLEAK_MSG) */
+      if (add) {
+	Insert(filter, 0, c);
+	if (isdigit((int) *c)) {
+	  Insert(filter, 0, "-");
+	}
+      } else {
+	char *temp = (char *)malloc(sizeof(char)*strlen(c) + 2);
+	if (isdigit((int) *c)) {
+	  sprintf(temp, "-%s", c);
+	} else {
+	  strcpy(temp, c);
+	}
+	Replace(filter, temp, "", DOH_REPLACE_FIRST);
+        free(temp);
+      }
+    }
+    c = strtok(NULL, ", ");
+  }
+  Delete(s);
+}
+
+void Swig_warnall(void) {
+  warnall = 1;
+}
+
+
+/* ----------------------------------------------------------------------------- 
+ * Swig_warn_count()
+ *
+ * Return the number of warnings
+ * ----------------------------------------------------------------------------- */
+
+int Swig_warn_count(void) {
+  return nwarning;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_error_msg_format()
+ *
+ * Set the type of error/warning message display
+ * ----------------------------------------------------------------------------- */
+
+void Swig_error_msg_format(ErrorMessageFormat format) {
+  const char *error = "Error";
+  const char *warning = "Warning";
+
+  const char *fmt_eof = 0;
+  const char *fmt_line = 0;
+
+  /* here 'format' could be directly a string instead of an enum, but
+     by now a switch is used to translated into one. */
+  switch (format) {
+  case EMF_MICROSOFT:
+    fmt_line = "%s(%d)";
+    fmt_eof = "%s(999999)";	/* Is there a special character for EOF? Just use a large number. */
+    break;
+  case EMF_STANDARD:
+  default:
+    fmt_line = "%s:%d";
+    fmt_eof = "%s:EOF";
+  }
+
+  sprintf(wrn_wnum_fmt, "%s: %s(%%d): ", fmt_line, warning);
+  sprintf(wrn_nnum_fmt, "%s: %s: ", fmt_line, warning);
+  sprintf(err_line_fmt, "%s: %s: ", fmt_line, error);
+  sprintf(err_eof_fmt, "%s: %s: ", fmt_eof, error);
+
+  msg_format = format;
+  init_fmt = 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * format_filename()
+ *
+ * Remove double backslashes in Windows filename paths for display
+ * ----------------------------------------------------------------------------- */
+static String *format_filename(const String_or_char *filename) {
+  String *formatted_filename = NewString(filename);
+#if defined(_WIN32)
+  Replaceall(formatted_filename, "\\\\", "\\");
+#endif
+  return formatted_filename;
+}
diff --git a/trunk/Source/Swig/fragment.c b/trunk/Source/Swig/fragment.c
new file mode 100644
index 0000000..510a018
--- /dev/null
+++ b/trunk/Source/Swig/fragment.c
@@ -0,0 +1,181 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * fragment.c
+ *
+ * This file manages named code fragments.  Code fragments are typically
+ * used to hold helper-code that may or may not be included in the wrapper
+ * file (depending on what features are actually used in the interface).
+ *
+ * By using fragments, it's possible to greatly reduce the amount of
+ * wrapper code and to generate cleaner wrapper files. 
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_fragment_c[] = "$Id$";
+
+#include "swig.h"
+#include "swigwarn.h"
+
+static Hash *fragments = 0;
+static Hash *looking_fragments = 0;
+static int debug = 0;
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_fragment_register()
+ *
+ * Add a fragment. Use the original Node*, so, if something needs to be
+ * changed, lang.cxx doesn't nedd to be touched again.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_fragment_register(Node *fragment) {
+  if (Getattr(fragment, "emitonly")) {
+    Swig_fragment_emit(fragment);
+    return;
+  } else {
+    String *name = Copy(Getattr(fragment, "value"));
+    String *type = Getattr(fragment, "type");
+    if (type) {
+      SwigType *rtype = SwigType_typedef_resolve_all(type);
+      String *mangle = Swig_string_mangle(type);
+      Append(name, mangle);
+      Delete(mangle);
+      Delete(rtype);
+      if (debug)
+	Printf(stdout, "register fragment %s %s\n", name, type);
+    }
+    if (!fragments) {
+      fragments = NewHash();
+    }
+    if (!Getattr(fragments, name)) {
+      String *section = Copy(Getattr(fragment, "section"));
+      String *ccode = Copy(Getattr(fragment, "code"));
+      Hash *kwargs = Getattr(fragment, "kwargs");
+      Setmeta(ccode, "section", section);
+      if (kwargs) {
+	Setmeta(ccode, "kwargs", kwargs);
+      }
+      Setattr(fragments, name, ccode);
+      if (debug)
+	Printf(stdout, "registering fragment %s %s\n", name, section);
+      Delete(section);
+      Delete(ccode);
+    }
+    Delete(name);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_fragment_emit()
+ *
+ * Emit a fragment
+ * ----------------------------------------------------------------------------- */
+
+static
+char *char_index(char *str, char c) {
+  while (*str && (c != *str))
+    ++str;
+  return (c == *str) ? str : 0;
+}
+
+void Swig_fragment_emit(Node *n) {
+  String *code;
+  char *pc, *tok;
+  String *t;
+  String *mangle = 0;
+  String *name = 0;
+  String *type = 0;
+
+  if (!fragments) {
+    Swig_warning(WARN_FRAGMENT_NOT_FOUND, Getfile(n), Getline(n), "Fragment '%s' not found.\n", name);
+    return;
+  }
+
+
+  name = Getattr(n, "value");
+  if (!name) {
+    name = n;
+  }
+  type = Getattr(n, "type");
+  if (type) {
+    mangle = Swig_string_mangle(type);
+  }
+
+  if (debug)
+    Printf(stdout, "looking fragment %s %s\n", name, type);
+  t = Copy(name);
+  tok = Char(t);
+  pc = char_index(tok, ',');
+  if (pc)
+    *pc = 0;
+  while (tok) {
+    String *name = NewString(tok);
+    if (mangle)
+      Append(name, mangle);
+    if (looking_fragments && Getattr(looking_fragments, name)) {
+      return;
+    }
+    code = Getattr(fragments, name);
+    if (debug)
+      Printf(stdout, "looking subfragment %s\n", name);
+    if (code && (Strcmp(code, "ignore") != 0)) {
+      String *section = Getmeta(code, "section");
+      Hash *nn = Getmeta(code, "kwargs");
+      if (!looking_fragments)
+	looking_fragments = NewHash();
+      Setattr(looking_fragments, name, "1");
+      while (nn) {
+	if (Equal(Getattr(nn, "name"), "fragment")) {
+	  if (debug)
+	    Printf(stdout, "emitting fragment %s %s\n", nn, type);
+	  Setfile(nn, Getfile(n));
+	  Setline(nn, Getline(n));
+	  Swig_fragment_emit(nn);
+	}
+	nn = nextSibling(nn);
+      }
+      if (section) {
+	File *f = Swig_filebyname(section);
+	if (!f) {
+	  Swig_error(Getfile(code), Getline(code), "Bad section '%s' for code fragment '%s'\n", section, name);
+	} else {
+	  if (debug)
+	    Printf(stdout, "emitting subfragment %s %s\n", name, section);
+	  if (debug)
+	    Printf(f, "/* begin fragment %s */\n", name);
+	  Printf(f, "%s\n", code);
+	  if (debug)
+	    Printf(f, "/* end fragment %s */\n\n", name);
+	  Setattr(fragments, name, "ignore");
+	  Delattr(looking_fragments, name);
+	}
+      }
+    } else if (!code && type) {
+      SwigType *rtype = SwigType_typedef_resolve_all(type);
+      if (!Equal(type, rtype)) {
+	String *name = Copy(Getattr(n, "value"));
+	String *mangle = Swig_string_mangle(type);
+	Append(name, mangle);
+	Setfile(name, Getfile(n));
+	Setline(name, Getline(n));
+	Swig_fragment_emit(name);
+	Delete(mangle);
+	Delete(name);
+      }
+      Delete(rtype);
+    }
+
+    if (!code) {
+      Swig_warning(WARN_FRAGMENT_NOT_FOUND, Getfile(n), Getline(n), "Fragment '%s' not found.\n", name);
+    }
+    tok = pc ? pc + 1 : 0;
+    if (tok) {
+      pc = char_index(tok, ',');
+      if (pc)
+	*pc = 0;
+    }
+    Delete(name);
+  }
+  Delete(t);
+}
diff --git a/trunk/Source/Swig/getopt.c b/trunk/Source/Swig/getopt.c
new file mode 100644
index 0000000..87b0f7c
--- /dev/null
+++ b/trunk/Source/Swig/getopt.c
@@ -0,0 +1,107 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * getopt.c
+ *
+ * Handles the parsing of command line options.  This is particularly nasty
+ * compared to other utilities given that command line options can potentially
+ * be read by many different modules within SWIG.  Thus, in order to make sure
+ * there are no unrecognized options, each module is required to "mark"
+ * the options that it uses.  Afterwards, we can make a quick scan to make
+ * sure there are no unmarked options.
+ * 
+ * TODO: 
+ *     - This module needs to be modified so that it doesn't call exit().
+ *       Should have cleaner error handling in general.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_getopt_c[] = "$Id$";
+
+#include "swig.h"
+
+static char **args;
+static int numargs;
+static int *marked;
+
+/* -----------------------------------------------------------------------------
+ * Swig_init_args()
+ * 
+ * Initialize the argument list handler.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_init_args(int argc, char **argv) {
+  int i;
+  assert(argc > 0);
+  assert(argv);
+
+  numargs = argc;
+  args = argv;
+  marked = (int *) malloc(numargs * sizeof(int));
+  for (i = 0; i < argc; i++) {
+    marked[i] = 0;
+  }
+  marked[0] = 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_mark_arg()
+ * 
+ * Marks an argument as being parsed.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_mark_arg(int n) {
+  assert(marked);
+  assert((n >= 0) && (n < numargs));
+  marked[n] = 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_check_marked()
+ *
+ * Checks to see if argument has been picked up.
+ * ----------------------------------------------------------------------------- */
+
+int Swig_check_marked(int n) {
+  assert((n >= 0) && (n < numargs));
+  return marked[n];
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_check_options()
+ * 
+ * Checkers for unprocessed command line options and errors.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_check_options(int check_input) {
+  int error = 0;
+  int i;
+  int max = check_input ? numargs - 1 : numargs;
+  assert(marked);
+  for (i = 1; i < max; i++) {
+    if (!marked[i]) {
+      Printf(stderr, "swig error : Unrecognized option %s\n", args[i]);
+      error = 1;
+    }
+  }
+  if (error) {
+    Printf(stderr, "Use 'swig -help' for available options.\n");
+    exit(1);
+  }
+  if (check_input && marked[numargs - 1]) {
+    Printf(stderr, "Must specify an input file. Use -help for available options.\n");
+    exit(1);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_arg_error()
+ * 
+ * Generates a generic error message and exits.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_arg_error() {
+  Printf(stderr, "SWIG : Unable to parse command line options.\n");
+  Printf(stderr, "Use 'swig -help' for available options.\n");
+  exit(1);
+}
diff --git a/trunk/Source/Swig/include.c b/trunk/Source/Swig/include.c
new file mode 100644
index 0000000..3f47be1
--- /dev/null
+++ b/trunk/Source/Swig/include.c
@@ -0,0 +1,380 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * include.c
+ *
+ * The functions in this file are used to manage files in the SWIG library.
+ * General purpose functions for opening, including, and retrieving pathnames
+ * are provided.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_include_c[] = "$Id$";
+
+#include "swig.h"
+
+static List   *directories = 0;	        /* List of include directories */
+static String *lastpath = 0;	        /* Last file that was included */
+static List   *pdirectories = 0;        /* List of pushed directories  */
+static int     dopush = 1;		/* Whether to push directories */
+
+/* This functions determine whether to push/pop dirs in the preprocessor */
+void Swig_set_push_dir(int push) {
+  dopush = push;
+}
+
+int Swig_get_push_dir(void) {
+  return dopush;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_add_directory()
+ *
+ * Adds a directory to the SWIG search path.
+ * ----------------------------------------------------------------------------- */
+
+List *Swig_add_directory(const String_or_char *dirname) {
+  String *adirname;
+  if (!directories)
+    directories = NewList();
+  assert(directories);
+  if (dirname) {
+    adirname = NewString(dirname);
+    Append(directories,adirname);
+    Delete(adirname);
+  }
+  return directories;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_push_directory()
+ *
+ * Inserts a directory at the front of the SWIG search path.  This is used by
+ * the preprocessor to grab files in the same directory as other included files.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_push_directory(const String_or_char *dirname) {
+  String *pdirname;
+  if (!Swig_get_push_dir())
+    return;
+  if (!pdirectories)
+    pdirectories = NewList();
+  assert(pdirectories);
+  pdirname = NewString(dirname);
+  assert(pdirname);
+  Insert(pdirectories,0,pdirname);
+  Delete(pdirname);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_pop_directory()
+ *
+ * Pops a directory off the front of the SWIG search path.  This is used by
+ * the preprocessor.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_pop_directory() {
+  if (!Swig_get_push_dir())
+    return;
+  if (!pdirectories)
+    return;
+  Delitem(pdirectories, 0);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_last_file()
+ * 
+ * Returns the full pathname of the last file opened. 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_last_file() {
+  assert(lastpath);
+  return lastpath;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_search_path() 
+ * 
+ * Returns a list of the current search paths.
+ * ----------------------------------------------------------------------------- */
+
+static List *Swig_search_path_any(int syspath) {
+  String *filename;
+  List   *slist;
+  int     i, ilen;
+
+  slist = NewList();
+  assert(slist);
+  filename = NewStringEmpty();
+  assert(filename);
+#ifdef MACSWIG
+  Printf(filename, "%s", SWIG_FILE_DELIMITER);
+#else
+  Printf(filename, ".%s", SWIG_FILE_DELIMITER);
+#endif
+  Append(slist, filename);
+  Delete(filename);
+  
+  /* If there are any pushed directories.  Add them first */
+  if (pdirectories) {
+    ilen = Len(pdirectories);
+    for (i = 0; i < ilen; i++) {
+      filename = NewString(Getitem(pdirectories,i));
+      Append(filename,SWIG_FILE_DELIMITER);
+      Append(slist,filename);
+      Delete(filename);
+    }
+  }
+  /* Add system directories next */
+  ilen = Len(directories);
+  for (i = 0; i < ilen; i++) {
+    filename = NewString(Getitem(directories,i));
+    Append(filename,SWIG_FILE_DELIMITER);
+    if (syspath) {
+      /* If doing a system include, put the system directories first */
+      Insert(slist,i,filename);
+    } else {
+      /* Otherwise, just put the system directories after the pushed directories (if any) */
+      Append(slist,filename);
+    }
+    Delete(filename);
+  }
+  return slist;
+}
+
+List *Swig_search_path() {
+  return Swig_search_path_any(0);
+}
+
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_open()
+ *
+ * Looks for a file and open it.  Returns an open  FILE * on success.
+ * ----------------------------------------------------------------------------- */
+
+static FILE *Swig_open_any(const String_or_char *name, int sysfile) {
+  FILE *f;
+  String *filename;
+  List *spath = 0;
+  char *cname;
+  int i, ilen;
+
+  if (!directories)
+    directories = NewList();
+  assert(directories);
+
+  cname = Char(name);
+  filename = NewString(cname);
+  assert(filename);
+  f = fopen(Char(filename), "r");
+  if (!f) {
+    spath = Swig_search_path_any(sysfile);
+    ilen = Len(spath);
+    for (i = 0; i < ilen; i++) {
+      Clear(filename);
+      Printf(filename, "%s%s", Getitem(spath, i), cname);
+      f = fopen(Char(filename), "r");
+      if (f)
+	break;
+    }
+    Delete(spath);
+  }
+  if (f) {
+#if defined(_WIN32)		/* Note not on Cygwin else filename is displayed with double '/' */
+    Replaceall(filename, "\\\\", "\\");	/* remove double '\' in case any already present */
+    Replaceall(filename, "\\", "\\\\");
+#endif
+    Delete(lastpath);
+    lastpath = Copy(filename);
+  }
+  Delete(filename);
+  return f;
+}
+
+FILE *Swig_open(const String_or_char *name) {
+  return Swig_open_any(name, 0);
+}
+
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_read_file()
+ * 
+ * Reads data from an open FILE * and returns it as a string.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_read_file(FILE *f) {
+  int len;
+  char buffer[4096];
+  String *str = NewStringEmpty();
+
+  assert(str);
+  while (fgets(buffer, 4095, f)) {
+    Append(str, buffer);
+  }
+  len = Len(str);
+  if (len) {
+    char *cstr = Char(str);
+    if (cstr[len - 1] != '\n') {
+      Append(str, "\n");
+    }
+  }
+  return str;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_include()
+ *
+ * Opens a file and returns it as a string.
+ * ----------------------------------------------------------------------------- */
+
+static String *Swig_include_any(const String_or_char *name, int sysfile) {
+  FILE *f;
+  String *str;
+  String *file;
+
+  f = Swig_open_any(name, sysfile);
+  if (!f)
+    return 0;
+  str = Swig_read_file(f);
+  fclose(f);
+  Seek(str, 0, SEEK_SET);
+  file = Copy(lastpath);
+  Setfile(str, file);
+  Delete(file);
+  Setline(str, 1);
+  return str;
+}
+
+String *Swig_include(const String_or_char *name) {
+  return Swig_include_any(name, 0);
+}
+
+String *Swig_include_sys(const String_or_char *name) {
+  return Swig_include_any(name, 1);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_insert_file()
+ *
+ * Copies the contents of a file into another file
+ * ----------------------------------------------------------------------------- */
+
+int Swig_insert_file(const String_or_char *filename, File *outfile) {
+  char buffer[4096];
+  int nbytes;
+  FILE *f = Swig_open(filename);
+
+  if (!f)
+    return -1;
+  while ((nbytes = Read(f, buffer, 4096)) > 0) {
+    Write(outfile, buffer, nbytes);
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_register_filebyname()
+ *
+ * Register a "named" file with the core.  Named files can become targets
+ * for %insert directives and other SWIG operations.  This function takes
+ * the place of the f_header, f_wrapper, f_init, and other global variables
+ * in SWIG1.1
+ * ----------------------------------------------------------------------------- */
+
+static Hash *named_files = 0;
+
+void Swig_register_filebyname(const String_or_char *filename, File *outfile) {
+  if (!named_files)
+    named_files = NewHash();
+  Setattr(named_files, filename, outfile);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_filebyname()
+ *
+ * Get a named file
+ * ----------------------------------------------------------------------------- */
+
+File *Swig_filebyname(const String_or_char *filename) {
+  if (!named_files)
+    return 0;
+  return Getattr(named_files, filename);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_file_suffix()
+ *
+ * Returns the suffix of a file
+ * ----------------------------------------------------------------------------- */
+
+char *Swig_file_suffix(const String_or_char *filename) {
+  char *d;
+  char *c = Char(filename);
+  int len = Len(filename);
+  if (strlen(c)) {
+    d = c + len - 1;
+    while (d != c) {
+      if (*d == '.')
+	return d;
+      d--;
+    }
+    return c + len;
+  }
+  return c;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_file_basename()
+ *
+ * Returns the filename with no suffix attached.
+ * ----------------------------------------------------------------------------- */
+
+char *Swig_file_basename(const String_or_char *filename) {
+  static char tmp[1024];
+  char *c;
+  strcpy(tmp, Char(filename));
+  c = Swig_file_suffix(tmp);
+  *c = 0;
+  return tmp;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_file_filename()
+ *
+ * Return the file with any leading path stripped off
+ * ----------------------------------------------------------------------------- */
+char *Swig_file_filename(const String_or_char *filename) {
+  static char tmp[1024];
+  const char *delim = SWIG_FILE_DELIMITER;
+  char *c;
+
+  strcpy(tmp, Char(filename));
+  c = strrchr(tmp, *delim);
+  if (c)
+    return c + 1;
+  else
+    return tmp;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_file_dirname()
+ *
+ * Return the name of the directory associated with a file
+ * ----------------------------------------------------------------------------- */
+char *Swig_file_dirname(const String_or_char *filename) {
+  static char tmp[1024];
+  const char *delim = SWIG_FILE_DELIMITER;
+  char *c;
+  strcpy(tmp, Char(filename));
+  if (!strstr(tmp, delim)) {
+    return "";
+  }
+  c = tmp + strlen(tmp) - 1;
+  while (*c != *delim)
+    c--;
+  *(++c) = 0;
+  return tmp;
+}
diff --git a/trunk/Source/Swig/misc.c b/trunk/Source/Swig/misc.c
new file mode 100644
index 0000000..d292505
--- /dev/null
+++ b/trunk/Source/Swig/misc.c
@@ -0,0 +1,1077 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * misc.c
+ *
+ * Miscellaneous functions that don't really fit anywhere else.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_misc_c[] = "$Id$";
+
+#include "swig.h"
+#include <errno.h>
+#include <ctype.h>
+#include <limits.h>
+
+static char *fake_version = 0;
+
+/* -----------------------------------------------------------------------------
+ * Swig_copy_string()
+ *
+ * Duplicate a NULL-terminate string given as a char *.
+ * ----------------------------------------------------------------------------- */
+
+char *Swig_copy_string(const char *s) {
+  char *c = 0;
+  if (s) {
+    c = (char *) malloc(strlen(s) + 1);
+    strcpy(c, s);
+  }
+  return c;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_set_fakeversion()
+ *
+ * Version string override
+ * ----------------------------------------------------------------------------- */
+
+void Swig_set_fakeversion(const char *version) {
+  fake_version = Swig_copy_string(version);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_package_version()
+ *
+ * Return the package string containing the version number
+ * ----------------------------------------------------------------------------- */
+
+const char *Swig_package_version(void) {
+  return fake_version ? fake_version : PACKAGE_VERSION;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_banner()
+ *
+ * Emits the SWIG identifying banner.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_banner(File *f) {
+  Printf(f, "/* ----------------------------------------------------------------------------\n\
+ * This file was automatically generated by SWIG (http://www.swig.org).\n\
+ * Version %s\n\
+ * \n\
+ * This file is not intended to be easily readable and contains a number of \n\
+ * coding conventions designed to improve portability and efficiency. Do not make\n\
+ * changes to this file unless you know what you are doing--modify the SWIG \n\
+ * interface file instead. \n", Swig_package_version());
+  /* String too long for ISO compliance */
+  Printf(f, " * ----------------------------------------------------------------------------- */\n\n");
+
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_strip_c_comments()
+ *
+ * Return a new string with C comments stripped from the input string. Null is
+ * returned if there aren't any.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_strip_c_comments(const String *s) {
+  const char *c = Char(s);
+  const char *comment_begin = 0;
+  const char *comment_end = 0;
+  String *stripped = 0;
+
+  while (*c) {
+    if (!comment_begin && *c == '/') {
+      ++c;
+      if (!*c)
+        break;
+      if (*c == '*')
+        comment_begin = c-1;
+    } else if (comment_begin && !comment_end && *c == '*') {
+      ++c;
+      if (*c == '/')
+        comment_end = c;
+      break;
+    }
+    ++c;
+  }
+
+  if (comment_begin && comment_end) {
+    int size = comment_begin - Char(s);
+    String *stripmore = 0;
+    stripped = NewStringWithSize(s, size);
+    Printv(stripped, comment_end + 1, NIL);
+    do {
+      stripmore = Swig_strip_c_comments(stripped);
+      if (stripmore) {
+        Delete(stripped);
+        stripped = stripmore;
+      }
+    } while (stripmore);
+  }
+  return stripped;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_escape()
+ *
+ * Takes a string object and produces a string with escape codes added to it.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_escape(String *s) {
+  String *ns;
+  int c;
+  ns = NewStringEmpty();
+
+  while ((c = Getc(s)) != EOF) {
+    if (c == '\n') {
+      Printf(ns, "\\n");
+    } else if (c == '\r') {
+      Printf(ns, "\\r");
+    } else if (c == '\t') {
+      Printf(ns, "\\t");
+    } else if (c == '\\') {
+      Printf(ns, "\\\\");
+    } else if (c == '\'') {
+      Printf(ns, "\\'");
+    } else if (c == '\"') {
+      Printf(ns, "\\\"");
+    } else if (c == ' ') {
+      Putc(c, ns);
+    } else if (!isgraph(c)) {
+      if (c < 0)
+	c += UCHAR_MAX + 1;
+      Printf(ns, "\\%o", c);
+    } else {
+      Putc(c, ns);
+    }
+  }
+  return ns;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_upper()
+ *
+ * Takes a string object and returns a copy that is uppercase
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_upper(String *s) {
+  String *ns;
+  int c;
+  ns = NewStringEmpty();
+
+  Seek(s, 0, SEEK_SET);
+  while ((c = Getc(s)) != EOF) {
+    Putc(toupper(c), ns);
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_lower()
+ *
+ * Takes a string object and returns a copy that is lowercase
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_lower(String *s) {
+  String *ns;
+  int c;
+  ns = NewStringEmpty();
+
+  Seek(s, 0, SEEK_SET);
+  while ((c = Getc(s)) != EOF) {
+    Putc(tolower(c), ns);
+  }
+  return ns;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_title()
+ *
+ * Takes a string object and returns a copy that is lowercase with first letter
+ * capitalized
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_title(String *s) {
+  String *ns;
+  int first = 1;
+  int c;
+  ns = NewStringEmpty();
+
+  Seek(s, 0, SEEK_SET);
+  while ((c = Getc(s)) != EOF) {
+    Putc(first ? toupper(c) : tolower(c), ns);
+    first = 0;
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_ccase()
+ *
+ * Takes a string object and returns a copy that is lowercase with the first
+ * letter capitalized and the one following '_', which are removed.
+ *
+ *      camel_case -> CamelCase
+ *      camelCase  -> CamelCase
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_ccase(String *s) {
+  String *ns;
+  int first = 1;
+  int c;
+  ns = NewStringEmpty();
+
+  Seek(s, 0, SEEK_SET);
+  while ((c = Getc(s)) != EOF) {
+    if (c == '_') {
+      first = 1;
+      continue;
+    }
+    Putc(first ? toupper(c) : c, ns);
+    first = 0;
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_lccase()
+ *
+ * Takes a string object and returns a copy with the character after
+ * each '_' capitalised, and the '_' removed.  The first character is
+ * also forced to lowercase.
+ *
+ *      camel_case -> camelCase
+ *      CamelCase  -> camelCase
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_lccase(String *s) {
+  String *ns;
+  int first = 1;
+  int after_underscore = 0;
+  int c;
+  ns = NewStringEmpty();
+
+  Seek(s, 0, SEEK_SET);
+  while ((c = Getc(s)) != EOF) {
+    if (c == '_') {
+      after_underscore = 1;
+      continue;
+    }
+    if (first) {
+      Putc(tolower(c), ns);
+      first = 0;
+    } else {
+      Putc(after_underscore ? toupper(c) : c, ns);
+    }
+    after_underscore = 0;
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_ucase()
+ *
+ * This is the reverse case of ccase, ie
+ *
+ *      CamelCase -> camel_case
+ *      get2D     -> get_2d
+ *      asFloat2  -> as_float2
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_ucase(String *s) {
+  String *ns;
+  int c;
+  int lastC = 0;
+  int nextC = 0;
+  int underscore = 0;
+  ns = NewStringEmpty();
+
+  /* We insert a underscore when:
+     1. Lower case char followed by upper case char
+     getFoo > get_foo; getFOo > get_foo; GETFOO > getfoo
+     2. Number proceded by char and not end of string
+     get2D > get_2d; get22D > get_22d; GET2D > get_2d
+     but:
+     asFloat2 > as_float2
+  */
+
+  Seek(s, 0, SEEK_SET);
+
+  while ((c = Getc(s)) != EOF) {
+    nextC = Getc(s); Ungetc(nextC, s);
+    if (isdigit(c) && isalpha(lastC) && nextC != EOF)
+      underscore = 1;
+    else if (isupper(c) && isalpha(lastC) && !isupper(lastC))
+      underscore = 1;
+
+    lastC = c;
+
+    if (underscore) {
+      Putc('_', ns);
+      underscore = 0;
+    }
+
+    Putc(tolower(c), ns);
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_first_upper()
+ *
+ * Make the first character in the string uppercase, leave all the 
+ * rest the same.  This is used by the Ruby module to provide backwards
+ * compatibility with the old way of naming classes and constants.  For
+ * more info see the Ruby documentation.
+ *
+ *      firstUpper -> FirstUpper 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_first_upper(String *s) {
+  String *ns = NewStringEmpty();
+  char *cs = Char(s);
+  if (cs && cs[0] != 0) {
+    Putc(toupper((int)cs[0]), ns);
+    Append(ns, cs + 1);
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_first_lower()
+ *
+ * Make the first character in the string lowercase, leave all the 
+ * rest the same.  This is used by the Ruby module to provide backwards
+ * compatibility with the old way of naming classes and constants.  For
+ * more info see the Ruby documentation.
+ *
+ *      firstLower -> FirstLower 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_first_lower(String *s) {
+  String *ns = NewStringEmpty();
+  char *cs = Char(s);
+  if (cs && cs[0] != 0) {
+    Putc(tolower((int)cs[0]), ns);
+    Append(ns, cs + 1);
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_schemify()
+ *
+ * Replace underscores with dashes, to make identifiers look nice to Schemers.
+ *
+ *      under_scores -> under-scores
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_schemify(String *s) {
+  String *ns = NewString(s);
+  Replaceall(ns, "_", "-");
+  return ns;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_typecode()
+ *
+ * Takes a string with possible type-escapes in it and replaces them with
+ * real C datatypes.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_typecode(String *s) {
+  String *ns;
+  int c;
+  String *tc;
+  ns = NewStringEmpty();
+  while ((c = Getc(s)) != EOF) {
+    if (c == '`') {
+      String *str = 0;
+      tc = NewStringEmpty();
+      while ((c = Getc(s)) != EOF) {
+	if (c == '`')
+	  break;
+	Putc(c, tc);
+      }
+      str = SwigType_str(tc, 0);
+      Append(ns, str);
+      Delete(str);
+    } else {
+      Putc(c, ns);
+      if (c == '\'') {
+	while ((c = Getc(s)) != EOF) {
+	  Putc(c, ns);
+	  if (c == '\'')
+	    break;
+	  if (c == '\\') {
+	    c = Getc(s);
+	    Putc(c, ns);
+	  }
+	}
+      } else if (c == '\"') {
+	while ((c = Getc(s)) != EOF) {
+	  Putc(c, ns);
+	  if (c == '\"')
+	    break;
+	  if (c == '\\') {
+	    c = Getc(s);
+	    Putc(c, ns);
+	  }
+	}
+      }
+    }
+  }
+  return ns;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_mangle()
+ * 
+ * Take a string and mangle it by stripping all non-valid C identifier
+ * characters.
+ *
+ * This routine skips unnecessary blank spaces, therefore mangling
+ * 'char *' and 'char*', 'std::pair<int, int >' and
+ * 'std::pair<int,int>', produce the same result.
+ *
+ * However, note that 'long long' and 'long_long' produce different
+ * mangled strings.
+ *
+ * The mangling method still is not 'perfect', for example std::pair and
+ * std_pair return the same mangling. This is just a little better
+ * than before, but it seems to be enough for most of the purposes.
+ *
+ * Having a perfect mangling will break some examples and code which
+ * assume, for example, that A::get_value will be mangled as
+ * A_get_value. 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_string_mangle(const String *s) {
+#if 0
+  /* old mangling, not suitable for using in macros */
+  String *t = Copy(s);
+  char *c = Char(t);
+  while (*c) {
+    if (!isalnum(*c))
+      *c = '_';
+    c++;
+  }
+  return t;
+#else
+  String *result = NewStringEmpty();
+  int space = 0;
+  int state = 0;
+  char *pc, *cb;
+  String *b = Copy(s);
+  if (SwigType_istemplate(b)) {
+    String *st = Swig_symbol_template_deftype(b, 0);
+    String *sq = Swig_symbol_type_qualify(st, 0);
+    String *t = SwigType_namestr(sq);
+    Delete(st);
+    Delete(sq);
+    Delete(b);
+    b = t;
+  }
+  pc = cb = Char(b);
+  while (*pc) {
+    char c = *pc;
+    if (isalnum((int) c) || (c == '_')) {
+      state = 1;
+      if (space && (space == state)) {
+	Append(result, "_SS_");
+      }
+      space = 0;
+      Printf(result, "%c", (int) c);
+
+    } else {
+      if (isspace((int) c)) {
+	space = state;
+	++pc;
+	continue;
+      } else {
+	state = 3;
+	space = 0;
+      }
+      switch (c) {
+      case '.':
+	if ((cb != pc) && (*(pc - 1) == 'p')) {
+	  Append(result, "_");
+	  ++pc;
+	  continue;
+	} else {
+	  c = 'f';
+	}
+	break;
+      case ':':
+	if (*(pc + 1) == ':') {
+	  Append(result, "_");
+	  ++pc;
+	  ++pc;
+	  continue;
+	}
+	break;
+      case '*':
+	c = 'm';
+	break;
+      case '&':
+	c = 'A';
+	break;
+      case '<':
+	c = 'l';
+	break;
+      case '>':
+	c = 'g';
+	break;
+      case '=':
+	c = 'e';
+	break;
+      case ',':
+	c = 'c';
+	break;
+      case '(':
+	c = 'p';
+	break;
+      case ')':
+	c = 'P';
+	break;
+      case '[':
+	c = 'b';
+	break;
+      case ']':
+	c = 'B';
+	break;
+      case '^':
+	c = 'x';
+	break;
+      case '|':
+	c = 'o';
+	break;
+      case '~':
+	c = 'n';
+	break;
+      case '!':
+	c = 'N';
+	break;
+      case '%':
+	c = 'M';
+	break;
+      case '?':
+	c = 'q';
+	break;
+      case '+':
+	c = 'a';
+	break;
+      case '-':
+	c = 's';
+	break;
+      case '/':
+	c = 'd';
+	break;
+      default:
+	break;
+      }
+      if (isalpha((int) c)) {
+	Printf(result, "_S%c_", (int) c);
+      } else {
+	Printf(result, "_S%02X_", (int) c);
+      }
+    }
+    ++pc;
+  }
+  Delete(b);
+  return result;
+#endif
+}
+
+String *Swig_string_emangle(String *s) {
+  return Swig_string_mangle(s);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_scopename_prefix()
+ *
+ * Take a qualified name like "A::B::C" and return the scope name.
+ * In this case, "A::B".   Returns NULL if there is no base.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_scopename_split(String *s, String **rprefix, String **rlast) {
+  char *tmp = Char(s);
+  char *c = tmp;
+  char *cc = c;
+  char *co = 0;
+  if (!strstr(c, "::")) {
+    *rprefix = 0;
+    *rlast = Copy(s);
+  }
+
+  co = strstr(cc, "operator ");
+  if (co) {
+    if (co == cc) {
+      *rprefix = 0;
+      *rlast = Copy(s);
+      return;
+    } else {
+      *rprefix = NewStringWithSize(cc, co - cc - 2);
+      *rlast = NewString(co);
+      return;
+    }
+  }
+  while (*c) {
+    if ((*c == ':') && (*(c + 1) == ':')) {
+      cc = c;
+      c += 2;
+    } else {
+      if (*c == '<') {
+	int level = 1;
+	c++;
+	while (*c && level) {
+	  if (*c == '<')
+	    level++;
+	  if (*c == '>')
+	    level--;
+	  c++;
+	}
+      } else {
+	c++;
+      }
+    }
+  }
+
+  if (cc != tmp) {
+    *rprefix = NewStringWithSize(tmp, cc - tmp);
+    *rlast = NewString(cc + 2);
+    return;
+  } else {
+    *rprefix = 0;
+    *rlast = Copy(s);
+  }
+}
+
+
+String *Swig_scopename_prefix(String *s) {
+  char *tmp = Char(s);
+  char *c = tmp;
+  char *cc = c;
+  char *co = 0;
+  if (!strstr(c, "::"))
+    return 0;
+  co = strstr(cc, "operator ");
+
+  if (co) {
+    if (co == cc) {
+      return 0;
+    } else {
+      String *prefix = NewStringWithSize(cc, co - cc - 2);
+      return prefix;
+    }
+  }
+  while (*c) {
+    if ((*c == ':') && (*(c + 1) == ':')) {
+      cc = c;
+      c += 2;
+    } else {
+      if (*c == '<') {
+	int level = 1;
+	c++;
+	while (*c && level) {
+	  if (*c == '<')
+	    level++;
+	  if (*c == '>')
+	    level--;
+	  c++;
+	}
+      } else {
+	c++;
+      }
+    }
+  }
+
+  if (cc != tmp) {
+    return NewStringWithSize(tmp, cc - tmp);
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_scopename_last()
+ *
+ * Take a qualified name like "A::B::C" and returns the last.  In this
+ * case, "C". 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_scopename_last(String *s) {
+  char *tmp = Char(s);
+  char *c = tmp;
+  char *cc = c;
+  char *co = 0;
+  if (!strstr(c, "::"))
+    return NewString(s);
+
+  co = strstr(cc, "operator ");
+  if (co) {
+    return NewString(co);
+  }
+
+
+  while (*c) {
+    if ((*c == ':') && (*(c + 1) == ':')) {
+      cc = c;
+      c += 2;
+    } else {
+      if (*c == '<') {
+	int level = 1;
+	c++;
+	while (*c && level) {
+	  if (*c == '<')
+	    level++;
+	  if (*c == '>')
+	    level--;
+	  c++;
+	}
+      } else {
+	c++;
+      }
+    }
+  }
+  return NewString(cc + 2);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_scopename_first()
+ *
+ * Take a qualified name like "A::B::C" and returns the first scope name.
+ * In this case, "A".   Returns NULL if there is no base.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_scopename_first(String *s) {
+  char *tmp = Char(s);
+  char *c = tmp;
+  char *co = 0;
+  if (!strstr(c, "::"))
+    return 0;
+
+  co = strstr(c, "operator ");
+  if (co) {
+    if (co == c) {
+      return 0;
+    }
+  } else {
+    co = c + Len(s);
+  }
+
+  while (*c && (c != co)) {
+    if ((*c == ':') && (*(c + 1) == ':')) {
+      break;
+    } else {
+      if (*c == '<') {
+	int level = 1;
+	c++;
+	while (*c && level) {
+	  if (*c == '<')
+	    level++;
+	  if (*c == '>')
+	    level--;
+	  c++;
+	}
+      } else {
+	c++;
+      }
+    }
+  }
+  if (*c && (c != tmp)) {
+    return NewStringWithSize(tmp, c - tmp);
+  } else {
+    return 0;
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_scopename_suffix()
+ *
+ * Take a qualified name like "A::B::C" and returns the suffix.
+ * In this case, "B::C".   Returns NULL if there is no suffix.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_scopename_suffix(String *s) {
+  char *tmp = Char(s);
+  char *c = tmp;
+  char *co = 0;
+  if (!strstr(c, "::"))
+    return 0;
+
+  co = strstr(c, "operator ");
+  if (co) {
+    if (co == c)
+      return 0;
+  }
+  while (*c) {
+    if ((*c == ':') && (*(c + 1) == ':')) {
+      break;
+    } else {
+      if (*c == '<') {
+	int level = 1;
+	c++;
+	while (*c && level) {
+	  if (*c == '<')
+	    level++;
+	  if (*c == '>')
+	    level--;
+	  c++;
+	}
+      } else {
+	c++;
+      }
+    }
+  }
+  if (*c && (c != tmp)) {
+    return NewString(c + 2);
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_scopename_check()
+ *
+ * Checks to see if a name is qualified with a scope name
+ * ----------------------------------------------------------------------------- */
+
+int Swig_scopename_check(String *s) {
+  char *c = Char(s);
+  char *co = strstr(c, "operator ");
+
+  if (co) {
+    if (co == c)
+      return 0;
+  }
+  if (!strstr(c, "::"))
+    return 0;
+  while (*c) {
+    if ((*c == ':') && (*(c + 1) == ':')) {
+      return 1;
+    } else {
+      if (*c == '<') {
+	int level = 1;
+	c++;
+	while (*c && level) {
+	  if (*c == '<')
+	    level++;
+	  if (*c == '>')
+	    level--;
+	  c++;
+	}
+      } else {
+	c++;
+      }
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_command()
+ *
+ * Executes a external command via popen with the string as a command
+ * line parameter. For example:
+ *
+ *  Printf(stderr,"%(command:sed 's/[a-z]/\U\\1/' <<<)s","hello") -> Hello
+ * ----------------------------------------------------------------------------- */
+#if defined(HAVE_POPEN)
+#  if defined(_MSC_VER)
+#    define popen _popen
+#    define pclose _pclose
+#  else
+extern FILE *popen(const char *command, const char *type);
+extern int pclose(FILE *stream);
+#  endif
+#else
+#  if defined(_MSC_VER)
+#    define HAVE_POPEN 1
+#    define popen _popen
+#    define pclose _pclose
+#  endif
+#endif
+
+String *Swig_string_command(String *s) {
+  String *res = NewStringEmpty();
+#if defined(HAVE_POPEN)
+  if (Len(s)) {
+    char *command = Char(s);
+    FILE *fp = popen(command, "r");
+    if (fp) {
+      char buffer[1025];
+      while (fscanf(fp, "%1024s", buffer) != EOF) {
+	Append(res, buffer);
+      }
+      pclose(fp);
+    } else {
+      Swig_error("SWIG", Getline(s), "Command encoder fails attempting '%s'.\n", s);
+      exit(1);
+    }
+  }
+#endif
+  return res;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_string_rxspencer()
+ *
+ * Executes a regexp substitution via the RxSpencer library. For example:
+ *
+ *   Printf(stderr,"gsl%(rxspencer:[GSL_.*_][@1])s","GSL_Hello_") -> gslHello
+ * ----------------------------------------------------------------------------- */
+#if defined(HAVE_RXSPENCER)
+#include <sys/types.h>
+#include <rxspencer/regex.h>
+#define USE_RXSPENCER
+#endif
+
+const char *skip_delim(char pb, char pe, const char *ce) {
+  int end = 0;
+  int lb = 0;
+  while (!end && *ce != '\0') {
+    if (*ce == pb) {
+      ++lb;
+    }
+    if (*ce == pe) {
+      if (!lb) {
+	end = 1;
+	--ce;
+      } else {
+	--lb;
+      }
+    }
+    ++ce;
+  }
+  return end ? ce : 0;
+}
+
+
+#if defined(USE_RXSPENCER)
+String *Swig_string_rxspencer(String *s) {
+  String *res = 0;
+  if (Len(s)) {
+    const char *cs = Char(s);
+    const char *cb;
+    const char *ce;
+    if (*cs == '[') {
+      int retval;
+      regex_t compiled;
+      cb = ++cs;
+      ce = skip_delim('[', ']', cb);
+      if (ce) {
+	char bregexp[512];
+	strncpy(bregexp, cb, ce - cb);
+	bregexp[ce - cb] = '\0';
+	++ce;
+	retval = regcomp(&compiled, bregexp, REG_EXTENDED);
+	if (retval == 0) {
+	  cs = ce;
+	  if (*cs == '[') {
+	    cb = ++cs;
+	    ce = skip_delim('[', ']', cb);
+	    if (ce) {
+	      const char *cvalue = ce + 1;
+	      int nsub = (int) compiled.re_nsub + 1;
+	      regmatch_t *pmatch = (regmatch_t *) malloc(sizeof(regmatch_t) * (nsub));
+	      retval = regexec(&compiled, cvalue, nsub, pmatch, 0);
+	      if (retval != REG_NOMATCH) {
+		char *spos = 0;
+		res = NewStringWithSize(cb, ce - cb);
+		spos = Strchr(res, '@');
+		while (spos) {
+		  char cd = *(++spos);
+		  if (isdigit(cd)) {
+		    char arg[8];
+		    size_t len;
+		    int i = cd - '0';
+		    sprintf(arg, "@%d", i);
+		    if (i < nsub && (len = pmatch[i].rm_eo - pmatch[i].rm_so)) {
+		      char value[256];
+		      strncpy(value, cvalue + pmatch[i].rm_so, len);
+		      value[len] = 0;
+		      Replaceall(res, arg, value);
+		    } else {
+		      Replaceall(res, arg, "");
+		    }
+		    spos = Strchr(res, '@');
+		  } else if (cd == '@') {
+		    spos = strchr(spos + 1, '@');
+		  }
+		}
+	      }
+	      free(pmatch);
+	    }
+	  }
+	}
+	regfree(&compiled);
+      }
+    }
+  }
+  if (!res)
+    res = NewStringEmpty();
+  return res;
+}
+#else
+String *Swig_string_rxspencer(String *s) {
+  (void) s;
+  return NewStringEmpty();
+}
+#endif
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_init()
+ *
+ * Initialize the SWIG core
+ * ----------------------------------------------------------------------------- */
+
+void Swig_init() {
+  /* Set some useful string encoding methods */
+  DohEncoding("escape", Swig_string_escape);
+  DohEncoding("upper", Swig_string_upper);
+  DohEncoding("lower", Swig_string_lower);
+  DohEncoding("title", Swig_string_title);
+  DohEncoding("ctitle", Swig_string_ccase);
+  DohEncoding("lctitle", Swig_string_lccase);
+  DohEncoding("utitle", Swig_string_ucase);
+  DohEncoding("typecode", Swig_string_typecode);
+  DohEncoding("mangle", Swig_string_emangle);
+  DohEncoding("command", Swig_string_command);
+  DohEncoding("rxspencer", Swig_string_rxspencer);
+  DohEncoding("schemify", Swig_string_schemify);
+
+  /* aliases for the case encoders */
+  DohEncoding("uppercase", Swig_string_upper);
+  DohEncoding("lowercase", Swig_string_lower);
+  DohEncoding("camelcase", Swig_string_ccase);
+  DohEncoding("lowercamelcase", Swig_string_lccase);
+  DohEncoding("undercase", Swig_string_ucase);
+  DohEncoding("firstuppercase", Swig_string_first_upper);
+  DohEncoding("firstlowercase", Swig_string_first_lower);
+
+  /* Initialize typemaps */
+  Swig_typemap_init();
+
+  /* Initialize symbol table */
+  Swig_symbol_init();
+
+  /* Initialize type system */
+  SwigType_typesystem_init();
+
+  /* Initialize template system */
+  SwigType_template_init();
+}
diff --git a/trunk/Source/Swig/naming.c b/trunk/Source/Swig/naming.c
new file mode 100644
index 0000000..f34a246
--- /dev/null
+++ b/trunk/Source/Swig/naming.c
@@ -0,0 +1,1652 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * naming.c
+ *
+ * Functions for generating various kinds of names during code generation.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_naming_c[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+#include <ctype.h>
+
+/* Hash table containing naming data */
+
+static Hash *naming_hash = 0;
+
+#if 0
+#define SWIG_DEBUG
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_register()
+ *
+ * Register a new naming format.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_name_register(const String_or_char *method, const String_or_char *format) {
+  if (!naming_hash)
+    naming_hash = NewHash();
+  Setattr(naming_hash, method, format);
+}
+
+void Swig_name_unregister(const String_or_char *method) {
+  if (naming_hash) {
+    Delattr(naming_hash, method);
+  }
+}
+
+static int name_mangle(String *r) {
+  char *c;
+  int special;
+  special = 0;
+  Replaceall(r, "::", "_");
+  c = Char(r);
+  while (*c) {
+    if (!isalnum((int) *c) && (*c != '_')) {
+      special = 1;
+      switch (*c) {
+      case '+':
+	*c = 'a';
+	break;
+      case '-':
+	*c = 's';
+	break;
+      case '*':
+	*c = 'm';
+	break;
+      case '/':
+	*c = 'd';
+	break;
+      case '<':
+	*c = 'l';
+	break;
+      case '>':
+	*c = 'g';
+	break;
+      case '=':
+	*c = 'e';
+	break;
+      case ',':
+	*c = 'c';
+	break;
+      case '(':
+	*c = 'p';
+	break;
+      case ')':
+	*c = 'P';
+	break;
+      case '[':
+	*c = 'b';
+	break;
+      case ']':
+	*c = 'B';
+	break;
+      case '^':
+	*c = 'x';
+	break;
+      case '&':
+	*c = 'A';
+	break;
+      case '|':
+	*c = 'o';
+	break;
+      case '~':
+	*c = 'n';
+	break;
+      case '!':
+	*c = 'N';
+	break;
+      case '%':
+	*c = 'M';
+	break;
+      case '.':
+	*c = 'f';
+	break;
+      case '?':
+	*c = 'q';
+	break;
+      default:
+	*c = '_';
+	break;
+      }
+    }
+    c++;
+  }
+  if (special)
+    Append(r, "___");
+  return special;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_mangle()
+ *
+ * Converts all of the non-identifier characters of a string to underscores.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_mangle(const String_or_char *s) {
+#if 0
+  String *r = NewString(s);
+  name_mangle(r);
+  return r;
+#else
+  return Swig_string_mangle(s);
+#endif
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_wrapper()
+ *
+ * Returns the name of a wrapper function.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_wrapper(const String_or_char *fname) {
+  String *r;
+  String *f;
+
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "wrapper");
+  if (!f) {
+    Append(r, "_wrap_%f");
+  } else {
+    Append(r, f);
+  }
+  Replace(r, "%f", fname, DOH_REPLACE_ANY);
+  name_mangle(r);
+  return r;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_member()
+ *
+ * Returns the name of a class method.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_member(const String_or_char *classname, const String_or_char *mname) {
+  String *r;
+  String *f;
+  String *rclassname;
+  char *cname;
+
+  rclassname = SwigType_namestr(classname);
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "member");
+  if (!f) {
+    Append(r, "%c_%m");
+  } else {
+    Append(r, f);
+  }
+  cname = Char(rclassname);
+  if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) {
+    cname = strchr(cname, ' ') + 1;
+  }
+  Replace(r, "%c", cname, DOH_REPLACE_ANY);
+  Replace(r, "%m", mname, DOH_REPLACE_ANY);
+  /*  name_mangle(r); */
+  Delete(rclassname);
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_get()
+ *
+ * Returns the name of the accessor function used to get a variable.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_get(const String_or_char *vname) {
+  String *r;
+  String *f;
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_get:  '%s'\n", vname);
+#endif
+
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "get");
+  if (!f) {
+    Append(r, "%v_get");
+  } else {
+    Append(r, f);
+  }
+  Replace(r, "%v", vname, DOH_REPLACE_ANY);
+  /* name_mangle(r); */
+  return r;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * Swig_name_set()
+ *
+ * Returns the name of the accessor function used to set a variable.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_set(const String_or_char *vname) {
+  String *r;
+  String *f;
+
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "set");
+  if (!f) {
+    Append(r, "%v_set");
+  } else {
+    Append(r, f);
+  }
+  Replace(r, "%v", vname, DOH_REPLACE_ANY);
+  /* name_mangle(r); */
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_construct()
+ *
+ * Returns the name of the accessor function used to create an object.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_construct(const String_or_char *classname) {
+  String *r;
+  String *f;
+  String *rclassname;
+  char *cname;
+
+  rclassname = SwigType_namestr(classname);
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "construct");
+  if (!f) {
+    Append(r, "new_%c");
+  } else {
+    Append(r, f);
+  }
+
+  cname = Char(rclassname);
+  if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) {
+    cname = strchr(cname, ' ') + 1;
+  }
+  Replace(r, "%c", cname, DOH_REPLACE_ANY);
+  Delete(rclassname);
+  return r;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_copyconstructor()
+ *
+ * Returns the name of the accessor function used to copy an object.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_copyconstructor(const String_or_char *classname) {
+  String *r;
+  String *f;
+  String *rclassname;
+  char *cname;
+
+  rclassname = SwigType_namestr(classname);
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "copy");
+  if (!f) {
+    Append(r, "copy_%c");
+  } else {
+    Append(r, f);
+  }
+
+  cname = Char(rclassname);
+  if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) {
+    cname = strchr(cname, ' ') + 1;
+  }
+
+  Replace(r, "%c", cname, DOH_REPLACE_ANY);
+  Delete(rclassname);
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_destroy()
+ *
+ * Returns the name of the accessor function used to destroy an object.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_destroy(const String_or_char *classname) {
+  String *r;
+  String *f;
+  String *rclassname;
+  char *cname;
+  rclassname = SwigType_namestr(classname);
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "destroy");
+  if (!f) {
+    Append(r, "delete_%c");
+  } else {
+    Append(r, f);
+  }
+
+  cname = Char(rclassname);
+  if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) {
+    cname = strchr(cname, ' ') + 1;
+  }
+  Replace(r, "%c", cname, DOH_REPLACE_ANY);
+  Delete(rclassname);
+  return r;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_disown()
+ *
+ * Returns the name of the accessor function used to disown an object.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_disown(const String_or_char *classname) {
+  String *r;
+  String *f;
+  String *rclassname;
+  char *cname;
+  rclassname = SwigType_namestr(classname);
+  r = NewStringEmpty();
+  if (!naming_hash)
+    naming_hash = NewHash();
+  f = Getattr(naming_hash, "disown");
+  if (!f) {
+    Append(r, "disown_%c");
+  } else {
+    Append(r, f);
+  }
+
+  cname = Char(rclassname);
+  if ((strncmp(cname, "struct ", 7) == 0) || ((strncmp(cname, "class ", 6) == 0)) || ((strncmp(cname, "union ", 6) == 0))) {
+    cname = strchr(cname, ' ') + 1;
+  }
+  Replace(r, "%c", cname, DOH_REPLACE_ANY);
+  Delete(rclassname);
+  return r;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_object_set()
+ *
+ * Sets an object associated with a name and optional declarators. 
+ * ----------------------------------------------------------------------------- */
+
+void Swig_name_object_set(Hash *namehash, String *name, SwigType *decl, DOH *object) {
+  DOH *n;
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_object_set:  '%s', '%s'\n", name, decl);
+#endif
+  n = Getattr(namehash, name);
+  if (!n) {
+    n = NewHash();
+    Setattr(namehash, name, n);
+    Delete(n);
+  }
+  /* Add an object based on the declarator value */
+  if (!decl) {
+    Setattr(n, "start", object);
+  } else {
+    SwigType *cd = Copy(decl);
+    Setattr(n, cd, object);
+    Delete(cd);
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_object_get()
+ *
+ * Return an object associated with an optional class prefix, name, and 
+ * declarator.   This function operates according to name matching rules
+ * described for the %rename directive in the SWIG manual.
+ * ----------------------------------------------------------------------------- */
+
+static DOH *get_object(Hash *n, String *decl) {
+  DOH *rn = 0;
+  if (!n)
+    return 0;
+  if (decl) {
+    rn = Getattr(n, decl);
+  } else {
+    rn = Getattr(n, "start");
+  }
+  return rn;
+}
+
+static
+DOH *name_object_get(Hash *namehash, String *tname, SwigType *decl, SwigType *ncdecl) {
+  DOH *rn = 0;
+  Hash *n = Getattr(namehash, tname);
+  if (n) {
+    rn = get_object(n, decl);
+    if ((!rn) && ncdecl)
+      rn = get_object(n, ncdecl);
+    if (!rn)
+      rn = get_object(n, 0);
+  }
+  return rn;
+}
+
+DOH *Swig_name_object_get(Hash *namehash, String *prefix, String *name, SwigType *decl) {
+  String *tname = NewStringEmpty();
+  DOH *rn = 0;
+  char *ncdecl = 0;
+
+  if (!namehash)
+    return 0;
+
+  /* DB: This removed to more tightly control feature/name matching */
+  /*  if ((decl) && (SwigType_isqualifier(decl))) {
+     ncdecl = strchr(Char(decl),'.');
+     ncdecl++;
+     }
+   */
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_object_get:  '%s' '%s', '%s'\n", prefix, name, decl);
+#endif
+
+
+  /* Perform a class-based lookup (if class prefix supplied) */
+  if (prefix) {
+    if (Len(prefix)) {
+      Printf(tname, "%s::%s", prefix, name);
+      rn = name_object_get(namehash, tname, decl, ncdecl);
+      if (!rn) {
+	String *cls = Swig_scopename_last(prefix);
+	if (!Equal(cls, prefix)) {
+	  Clear(tname);
+	  Printf(tname, "*::%s::%s", cls, name);
+	  rn = name_object_get(namehash, tname, decl, ncdecl);
+	}
+	Delete(cls);
+      }
+      /* A template-based class lookup, check name first */
+      if (!rn && SwigType_istemplate(name)) {
+	String *t_name = SwigType_templateprefix(name);
+	if (!Equal(t_name, name)) {
+	  rn = Swig_name_object_get(namehash, prefix, t_name, decl);
+	}
+	Delete(t_name);
+      }
+      /* A template-based class lookup */
+      /*
+      if (!rn && SwigType_istemplate(prefix)) {
+	String *t_prefix = SwigType_templateprefix(prefix);
+	if (Strcmp(t_prefix, prefix) != 0) {
+	  String *t_name = SwigType_templateprefix(name);
+	  rn = Swig_name_object_get(namehash, t_prefix, t_name, decl);
+	  Delete(t_name);
+	}
+	Delete(t_prefix);
+      }
+      */
+    }
+    /* A wildcard-based class lookup */
+    if (!rn) {
+      Clear(tname);
+      Printf(tname, "*::%s", name);
+      rn = name_object_get(namehash, tname, decl, ncdecl);
+    }
+  } else {
+    /* Lookup in the global namespace only */
+    Clear(tname);
+    Printf(tname, "::%s", name);
+    rn = name_object_get(namehash, tname, decl, ncdecl);
+  }
+  /* Catch-all */
+  if (!rn) {
+    rn = name_object_get(namehash, name, decl, ncdecl);
+  }
+  if (!rn && Swig_scopename_check(name)) {
+    String *nprefix = NewStringEmpty();
+    String *nlast = NewStringEmpty();
+    Swig_scopename_split(name, &nprefix, &nlast);
+    rn = name_object_get(namehash, nlast, decl, ncdecl);
+    Delete(nlast);
+    Delete(nprefix);
+  }
+
+  Delete(tname);
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_object_get:  found %d\n", rn ? 1 : 0);
+#endif
+
+  return rn;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_object_inherit()
+ *
+ * Implements name-based inheritance scheme. 
+ * ----------------------------------------------------------------------------- */
+
+void Swig_name_object_inherit(Hash *namehash, String *base, String *derived) {
+  Iterator ki;
+  String *bprefix;
+  String *dprefix;
+  char *cbprefix;
+  int plen;
+
+  if (!namehash)
+    return;
+
+  bprefix = NewStringf("%s::", base);
+  dprefix = NewStringf("%s::", derived);
+  cbprefix = Char(bprefix);
+  plen = strlen(cbprefix);
+  for (ki = First(namehash); ki.key; ki = Next(ki)) {
+    char *k = Char(ki.key);
+    if (strncmp(k, cbprefix, plen) == 0) {
+      Iterator oi;
+      String *nkey = NewStringf("%s%s", dprefix, k + plen);
+      Hash *n = ki.item;
+      Hash *newh = Getattr(namehash, nkey);
+      if (!newh) {
+	newh = NewHash();
+	Setattr(namehash, nkey, newh);
+	Delete(newh);
+      }
+      for (oi = First(n); oi.key; oi = Next(oi)) {
+	if (!Getattr(newh, oi.key)) {
+	  String *ci = Copy(oi.item);
+	  Setattr(newh, oi.key, ci);
+	  Delete(ci);
+	}
+      }
+      Delete(nkey);
+    }
+  }
+  Delete(bprefix);
+  Delete(dprefix);
+}
+
+/* -----------------------------------------------------------------------------
+ * merge_features()
+ *
+ * Given a hash, this function merges the features in the hash into the node.
+ * ----------------------------------------------------------------------------- */
+
+static void merge_features(Hash *features, Node *n) {
+  Iterator ki;
+
+  if (!features)
+    return;
+  for (ki = First(features); ki.key; ki = Next(ki)) {
+    String *ci = Copy(ki.item);
+    Setattr(n, ki.key, ci);
+    Delete(ci);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_features_get()
+ *
+ * Attaches any features in the features hash to the node that matches
+ * the declaration, decl.
+ * ----------------------------------------------------------------------------- */
+
+static
+void features_get(Hash *features, String *tname, SwigType *decl, SwigType *ncdecl, Node *node) {
+  Node *n = Getattr(features, tname);
+#ifdef SWIG_DEBUG
+  Printf(stdout, "  features_get: %s\n", tname);
+#endif
+  if (n) {
+    merge_features(get_object(n, 0), node);
+    if (ncdecl)
+      merge_features(get_object(n, ncdecl), node);
+    merge_features(get_object(n, decl), node);
+  }
+}
+
+void Swig_features_get(Hash *features, String *prefix, String *name, SwigType *decl, Node *node) {
+  char *ncdecl = 0;
+  String *rdecl = 0;
+  String *rname = 0;
+  if (!features)
+    return;
+
+  /* MM: This removed to more tightly control feature/name matching */
+  /*
+     if ((decl) && (SwigType_isqualifier(decl))) {
+     ncdecl = strchr(Char(decl),'.');
+     ncdecl++;
+     }
+   */
+
+  /* very specific hack for template constructors/destructors */
+  if (name && SwigType_istemplate(name)) {
+    String *nodetype = nodeType(node);
+    if (nodetype && (Equal(nodetype, "constructor") || Equal(nodetype, "destructor"))) {
+      String *nprefix = NewStringEmpty();
+      String *nlast = NewStringEmpty();
+      String *tprefix;
+      Swig_scopename_split(name, &nprefix, &nlast);
+      tprefix = SwigType_templateprefix(nlast);
+      Delete(nlast);
+      if (Len(nprefix)) {
+	Append(nprefix, "::");
+	Append(nprefix, tprefix);
+	Delete(tprefix);
+	rname = nprefix;
+      } else {
+	rname = tprefix;
+	Delete(nprefix);
+      }
+      rdecl = Copy(decl);
+      Replaceall(rdecl, name, rname);
+      decl = rdecl;
+      name = rname;
+    }
+  }
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_features_get: %s %s %s\n", prefix, name, decl);
+#endif
+
+  /* Global features */
+  features_get(features, "", 0, 0, node);
+  if (name) {
+    String *tname = NewStringEmpty();
+    /* add features for 'root' template */
+    if (SwigType_istemplate(name)) {
+      String *dname = SwigType_templateprefix(name);
+      features_get(features, dname, decl, ncdecl, node);
+      Delete(dname);
+    }
+    /* Catch-all */
+    features_get(features, name, decl, ncdecl, node);
+    /* Perform a class-based lookup (if class prefix supplied) */
+    if (prefix) {
+      /* A class-generic feature */
+      if (Len(prefix)) {
+	Printf(tname, "%s::", prefix);
+	features_get(features, tname, decl, ncdecl, node);
+      }
+      /* A wildcard-based class lookup */
+      Clear(tname);
+      Printf(tname, "*::%s", name);
+      features_get(features, tname, decl, ncdecl, node);
+      /* A specific class lookup */
+      if (Len(prefix)) {
+	/* A template-based class lookup */
+	if (SwigType_istemplate(prefix)) {
+	  String *tprefix = SwigType_templateprefix(prefix);
+	  Clear(tname);
+	  Printf(tname, "%s::%s", tprefix, name);
+	  features_get(features, tname, decl, ncdecl, node);
+	  Delete(tprefix);
+	}
+	Clear(tname);
+	Printf(tname, "%s::%s", prefix, name);
+	features_get(features, tname, decl, ncdecl, node);
+      }
+    } else {
+      /* Lookup in the global namespace only */
+      Clear(tname);
+      Printf(tname, "::%s", name);
+      features_get(features, tname, decl, ncdecl, node);
+    }
+    Delete(tname);
+  }
+  if (name && SwigType_istemplate(name)) {
+    /* add features for complete template type */
+    String *dname = Swig_symbol_template_deftype(name, 0);
+    if (!Equal(dname, name)) {
+      Swig_features_get(features, prefix, dname, decl, node);
+    }
+    Delete(dname);
+  }
+
+  if (rname)
+    Delete(rname);
+  if (rdecl)
+    Delete(rdecl);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_feature_set()
+ *
+ * Sets a feature name and value. Also sets optional feature attributes as
+ * passed in by featureattribs. Optional feature attributes are given a full name
+ * concatenating the feature name plus ':' plus the attribute name.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_feature_set(Hash *features, const String_or_char *name, SwigType *decl, const String_or_char *featurename, String *value, Hash *featureattribs) {
+  Hash *n;
+  Hash *fhash;
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_feature_set: %s %s %s %s\n", name, decl, featurename, value);
+#endif
+
+  n = Getattr(features, name);
+  if (!n) {
+    n = NewHash();
+    Setattr(features, name, n);
+    Delete(n);
+  }
+  if (!decl) {
+    fhash = Getattr(n, "start");
+    if (!fhash) {
+      fhash = NewHash();
+      Setattr(n, "start", fhash);
+      Delete(fhash);
+    }
+  } else {
+    fhash = Getattr(n, decl);
+    if (!fhash) {
+      String *cdecl_ = Copy(decl);
+      fhash = NewHash();
+      Setattr(n, cdecl_, fhash);
+      Delete(cdecl_);
+      Delete(fhash);
+    }
+  }
+  if (value) {
+    Setattr(fhash, featurename, value);
+  } else {
+    Delattr(fhash, featurename);
+  }
+
+  {
+    /* Add in the optional feature attributes */
+    Hash *attribs = featureattribs;
+    while (attribs) {
+      String *attribname = Getattr(attribs, "name");
+      String *featureattribname = NewStringf("%s:%s", featurename, attribname);
+      if (value) {
+	String *attribvalue = Getattr(attribs, "value");
+	Setattr(fhash, featureattribname, attribvalue);
+      } else {
+	Delattr(fhash, featureattribname);
+      }
+      attribs = nextSibling(attribs);
+      Delete(featureattribname);
+    }
+  }
+
+  if (name && SwigType_istemplate(name)) {
+    String *dname = Swig_symbol_template_deftype(name, 0);
+    if (Strcmp(dname, name)) {
+      Swig_feature_set(features, dname, decl, featurename, value, featureattribs);
+    }
+    Delete(dname);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * The rename/namewarn engine
+ *
+ * Code below was in parser.y for a while
+ * ----------------------------------------------------------------------------- */
+
+static Hash *namewarn_hash = 0;
+Hash *Swig_name_namewarn_hash() {
+  if (!namewarn_hash)
+    namewarn_hash = NewHash();
+  return namewarn_hash;
+}
+
+static Hash *rename_hash = 0;
+Hash *Swig_name_rename_hash() {
+  if (!rename_hash)
+    rename_hash = NewHash();
+  return rename_hash;
+}
+
+static List *namewarn_list = 0;
+List *Swig_name_namewarn_list() {
+  if (!namewarn_list)
+    namewarn_list = NewList();
+  return namewarn_list;
+}
+
+static List *rename_list = 0;
+List *Swig_name_rename_list() {
+  if (!rename_list)
+    rename_list = NewList();
+  return rename_list;
+}
+
+/* -----------------------------------------------------------------------------
+ * int Swig_need_name_warning(Node *n)
+ *
+ * Detects if a node needs name warnings 
+ *
+ * ----------------------------------------------------------------------------- */
+
+int Swig_need_name_warning(Node *n) {
+  int need = 1;
+  /* 
+     we don't use name warnings for:
+     - class forwards, no symbol is generated at the target language.
+     - template declarations, only for real instances using %template(name).
+     - typedefs, they have no effect at the target language.
+   */
+  if (checkAttribute(n, "nodeType", "classforward")) {
+    need = 0;
+  } else if (checkAttribute(n, "storage", "typedef")) {
+    need = 0;
+  } else if (Getattr(n, "hidden")) {
+    need = 0;
+  } else if (Getattr(n, "ignore")) {
+    need = 0;
+  } else if (Getattr(n, "templatetype")) {
+    need = 0;
+  }
+  return need;
+}
+
+/* -----------------------------------------------------------------------------
+ * int Swig_need_redefined_warn()
+ *
+ * Detects when a redefined object needs a warning
+ * 
+ * ----------------------------------------------------------------------------- */
+
+static int nodes_are_equivalent(Node *a, Node *b, int a_inclass) {
+  /* they must have the same type */
+  String *ta = nodeType(a);
+  String *tb = nodeType(b);
+  if (Cmp(ta, tb) != 0)
+    return 0;
+
+  /* cdecl case */
+  if (Cmp(ta, "cdecl") == 0) {
+    /* typedef */
+    String *a_storage = Getattr(a, "storage");
+    String *b_storage = Getattr(b, "storage");
+
+    if ((Cmp(a_storage, "typedef") == 0)
+	|| (Cmp(b_storage, "typedef") == 0)) {
+      if (Cmp(a_storage, b_storage) == 0) {
+	String *a_type = (Getattr(a, "type"));
+	String *b_type = (Getattr(b, "type"));
+	if (Cmp(a_type, b_type) == 0)
+	  return 1;
+      }
+      return 0;
+    }
+
+    /* static functions */
+    if ((Cmp(a_storage, "static") == 0)
+	|| (Cmp(b_storage, "static") == 0)) {
+      if (Cmp(a_storage, b_storage) != 0)
+	return 0;
+    }
+
+    /* friend methods */
+
+    if (!a_inclass || (Cmp(a_storage, "friend") == 0)) {
+      /* check declaration */
+
+      String *a_decl = (Getattr(a, "decl"));
+      String *b_decl = (Getattr(b, "decl"));
+      if (Cmp(a_decl, b_decl) == 0) {
+	/* check return type */
+	String *a_type = (Getattr(a, "type"));
+	String *b_type = (Getattr(b, "type"));
+	if (Cmp(a_type, b_type) == 0) {
+	  /* check parameters */
+	  Parm *ap = (Getattr(a, "parms"));
+	  Parm *bp = (Getattr(b, "parms"));
+	  while (ap && bp) {
+	    SwigType *at = Getattr(ap, "type");
+	    SwigType *bt = Getattr(bp, "type");
+	    if (Cmp(at, bt) != 0)
+	      return 0;
+	    ap = nextSibling(ap);
+	    bp = nextSibling(bp);
+	  }
+	  if (ap || bp) {
+	    return 0;
+	  } else {
+	    Node *a_template = Getattr(a, "template");
+	    Node *b_template = Getattr(b, "template");
+	    /* Not equivalent if one is a template instantiation (via %template) and the other is a non-templated function */
+	    if ((a_template && !b_template) || (!a_template && b_template))
+	      return 0;
+	  }
+	  return 1;
+	}
+      }
+    }
+  } else {
+    /* %constant case */
+    String *a_storage = Getattr(a, "storage");
+    String *b_storage = Getattr(b, "storage");
+    if ((Cmp(a_storage, "%constant") == 0)
+	|| (Cmp(b_storage, "%constant") == 0)) {
+      if (Cmp(a_storage, b_storage) == 0) {
+	String *a_type = (Getattr(a, "type"));
+	String *b_type = (Getattr(b, "type"));
+	if ((Cmp(a_type, b_type) == 0)
+	    && (Cmp(Getattr(a, "value"), Getattr(b, "value")) == 0))
+	  return 1;
+      }
+      return 0;
+    }
+  }
+  return 0;
+}
+
+int Swig_need_redefined_warn(Node *a, Node *b, int InClass) {
+  String *a_name = Getattr(a, "name");
+  String *b_name = Getattr(b, "name");
+  String *a_symname = Getattr(a, "sym:name");
+  String *b_symname = Getattr(b, "sym:name");
+  /* always send a warning if a 'rename' is involved */
+  if ((a_symname && !Equal(a_symname, a_name))
+      || (b_symname && !Equal(b_symname, b_name))) {
+    if (!Equal(a_name, b_name)) {
+      return 1;
+    }
+  }
+
+
+  return !nodes_are_equivalent(a, b, InClass);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * int Swig_need_protected(Node* n)
+ *
+ * Detects when we need to fully register the protected member.
+ * This is basically any protected members when the allprotected mode is set.
+ * Otherwise we take just the protected virtual methods and non-static methods 
+ * (potentially virtual methods) as well as constructors/destructors.
+ * 
+ * ----------------------------------------------------------------------------- */
+
+int Swig_need_protected(Node *n) {
+  String *nodetype = nodeType(n);
+  if (checkAttribute(n, "access", "protected")) {
+    if ((Equal(nodetype, "cdecl"))) {
+      if (Swig_director_mode() && Swig_director_protected_mode() && Swig_all_protected_mode()) {
+        return 1;
+      }
+      if (SwigType_isfunction(Getattr(n, "decl"))) {
+        String *storage = Getattr(n, "storage");
+        /* The function is declared virtual, or it has no storage. This eliminates typedef, static etc. */
+        return !storage || Equal(storage, "virtual");
+      }
+    } else if (Equal(nodetype, "constructor") || Equal(nodetype, "destructor")) {
+      return 1;
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * void Swig_name_nameobj_add()
+ *
+ * Add nameobj (rename/namewarn)
+ * 
+ * ----------------------------------------------------------------------------- */
+
+static List *Swig_make_attrlist(const char *ckey) {
+  List *list = NewList();
+  const char *cattr = strchr(ckey, '$');
+  if (cattr) {
+    String *nattr;
+    const char *rattr = strchr(++cattr, '$');
+    while (rattr) {
+      nattr = NewStringWithSize(cattr, rattr - cattr);
+      Append(list, nattr);
+      Delete(nattr);
+      cattr = rattr + 1;
+      rattr = strchr(cattr, '$');
+    }
+    nattr = NewString(cattr);
+    Append(list, nattr);
+    Delete(nattr);
+  } else {
+    Append(list, "nodeType");
+  }
+  return list;
+}
+
+static void Swig_name_object_attach_keys(const char *keys[], Hash *nameobj) {
+  Node *kw = nextSibling(nameobj);
+  List *matchlist = 0;
+  while (kw) {
+    Node *next = nextSibling(kw);
+    String *kname = Getattr(kw, "name");
+    char *ckey = kname ? Char(kname) : 0;
+    if (ckey) {
+      const char **rkey;
+      int isnotmatch = 0;
+      int isrxsmatch = 0;
+      if ((strncmp(ckey, "match", 5) == 0)
+	  || (isnotmatch = (strncmp(ckey, "notmatch", 8) == 0))
+	  || (isrxsmatch = (strncmp(ckey, "rxsmatch", 8) == 0))
+	  || (isnotmatch = isrxsmatch = (strncmp(ckey, "notrxsmatch", 11) == 0))) {
+	Hash *mi = NewHash();
+	List *attrlist = Swig_make_attrlist(ckey);
+	if (!matchlist)
+	  matchlist = NewList();
+	Setattr(mi, "value", Getattr(kw, "value"));
+	Setattr(mi, "attrlist", attrlist);
+#ifdef SWIG_DEBUG
+	if (isrxsmatch)
+	  Printf(stdout, "rxsmatch to use: %s %s %s\n", ckey, Getattr(kw, "value"), attrlist);
+#endif
+	if (isnotmatch)
+	  SetFlag(mi, "notmatch");
+	if (isrxsmatch)
+	  SetFlag(mi, "rxsmatch");
+	Delete(attrlist);
+	Append(matchlist, mi);
+	Delete(mi);
+	removeNode(kw);
+      } else {
+	for (rkey = keys; *rkey != 0; ++rkey) {
+	  if (strcmp(ckey, *rkey) == 0) {
+	    Setattr(nameobj, *rkey, Getattr(kw, "value"));
+	    removeNode(kw);
+	  }
+	}
+      }
+    }
+    kw = next;
+  }
+  if (matchlist) {
+    Setattr(nameobj, "matchlist", matchlist);
+    Delete(matchlist);
+  }
+}
+
+void Swig_name_nameobj_add(Hash *name_hash, List *name_list, String *prefix, String *name, SwigType *decl, Hash *nameobj) {
+  String *nname = 0;
+  if (name && Len(name)) {
+    String *target_fmt = Getattr(nameobj, "targetfmt");
+    nname = prefix ? NewStringf("%s::%s", prefix, name) : NewString(name);
+    if (target_fmt) {
+      String *tmp = NewStringf(target_fmt, nname);
+      Delete(nname);
+      nname = tmp;
+    }
+  }
+
+  if (!nname || !Len(nname) || Getattr(nameobj, "fullname") ||	/* any of these options trigger a 'list' nameobj */
+      Getattr(nameobj, "sourcefmt") || Getattr(nameobj, "matchlist")) {
+    if (decl)
+      Setattr(nameobj, "decl", decl);
+    if (nname && Len(nname))
+      Setattr(nameobj, "targetname", nname);
+    /* put the new nameobj at the beginnig of the list, such that the
+       last inserted rule take precedence */
+    Insert(name_list, 0, nameobj);
+  } else {
+    /* here we add an old 'hash' nameobj, simple and fast */
+    Swig_name_object_set(name_hash, nname, decl, nameobj);
+  }
+  Delete(nname);
+}
+
+/* -----------------------------------------------------------------------------
+ * int Swig_name_match_nameobj()
+ *
+ * Apply and check the nameobj's math list to the node
+ * 
+ * ----------------------------------------------------------------------------- */
+
+static DOH *Swig_get_lattr(Node *n, List *lattr) {
+  DOH *res = 0;
+  int ilen = Len(lattr);
+  int i;
+  for (i = 0; n && (i < ilen); ++i) {
+    String *nattr = Getitem(lattr, i);
+    res = Getattr(n, nattr);
+#ifdef SWIG_DEBUG
+    if (!res) {
+      Printf(stdout, "missing %s %s %s\n", nattr, Getattr(n, "name"), Getattr(n, "member"));
+    } else {
+      Printf(stdout, "lattr %d %s %s\n", i, nattr, DohIsString(res) ? res : Getattr(res, "name"));
+    }
+#endif
+    n = res;
+  }
+  return res;
+}
+
+#if defined(HAVE_RXSPENCER)
+#include <sys/types.h>
+#include <rxspencer/regex.h>
+#define USE_RXSPENCER
+#endif
+
+#if defined(USE_RXSPENCER)
+int Swig_name_rxsmatch_value(String *mvalue, String *value) {
+  int match = 0;
+  char *cvalue = Char(value);
+  char *cmvalue = Char(mvalue);
+  regex_t compiled;
+  int retval = regcomp(&compiled, cmvalue, REG_EXTENDED | REG_NOSUB);
+  if (retval != 0)
+    return 0;
+  retval = regexec(&compiled, cvalue, 0, 0, 0);
+  match = (retval == REG_NOMATCH) ? 0 : 1;
+#ifdef SWIG_DEBUG
+  Printf(stdout, "rxsmatch_value: %s %s %d\n", cvalue, cmvalue, match);
+#endif
+  regfree(&compiled);
+  return match;
+}
+#else
+int Swig_name_rxsmatch_value(String *mvalue, String *value) {
+  (void) mvalue;
+  (void) value;
+  return 0;
+}
+#endif
+
+int Swig_name_match_value(String *mvalue, String *value) {
+#if defined(SWIG_USE_SIMPLE_MATCHOR)
+  int match = 0;
+  char *cvalue = Char(value);
+  char *cmvalue = Char(mvalue);
+  char *sep = strchr(cmvalue, '|');
+  while (sep && !match) {
+    match = strncmp(cvalue, cmvalue, sep - cmvalue) == 0;
+#ifdef SWIG_DEBUG
+    Printf(stdout, "match_value: %s %s %d\n", cvalue, cmvalue, match);
+#endif
+    cmvalue = sep + 1;
+    sep = strchr(cmvalue, '|');
+  }
+  if (!match) {
+    match = strcmp(cvalue, cmvalue) == 0;
+#ifdef SWIG_DEBUG
+    Printf(stdout, "match_value: %s %s %d\n", cvalue, cmvalue, match);
+#endif
+  }
+  return match;
+#else
+  return Equal(mvalue, value);
+#endif
+}
+
+
+int Swig_name_match_nameobj(Hash *rn, Node *n) {
+  int match = 1;
+  List *matchlist = Getattr(rn, "matchlist");
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_match_nameobj: %s\n", Getattr(n, "name"));
+#endif
+  if (matchlist) {
+    int ilen = Len(matchlist);
+    int i;
+    for (i = 0; match && (i < ilen); ++i) {
+      Node *mi = Getitem(matchlist, i);
+      List *lattr = Getattr(mi, "attrlist");
+      String *nval = Swig_get_lattr(n, lattr);
+      int notmatch = GetFlag(mi, "notmatch");
+      int rxsmatch = GetFlag(mi, "rxsmatch");
+#ifdef SWIG_DEBUG
+      Printf(stdout, "mi %d %s re %d not %d \n", i, nval, notmatch, rxsmatch);
+      if (rxsmatch) {
+	Printf(stdout, "rxsmatch %s\n", lattr);
+      }
+#endif
+      match = 0;
+      if (nval) {
+	String *kwval = Getattr(mi, "value");
+	match = rxsmatch ? Swig_name_rxsmatch_value(kwval, nval)
+	    : Swig_name_match_value(kwval, nval);
+#ifdef SWIG_DEBUG
+	Printf(stdout, "val %s %s %d %d \n", nval, kwval, match, ilen);
+#endif
+      }
+      if (notmatch)
+	match = !match;
+    }
+  }
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_match_nameobj: %d\n", match);
+#endif
+  return match;
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash *Swig_name_nameobj_lget()
+ *
+ * Get a nameobj (rename/namewarn) from the list of filters
+ * 
+ * ----------------------------------------------------------------------------- */
+
+Hash *Swig_name_nameobj_lget(List *namelist, Node *n, String *prefix, String *name, String *decl) {
+  Hash *res = 0;
+  if (namelist) {
+    int len = Len(namelist);
+    int i;
+    int match = 0;
+    for (i = 0; !match && (i < len); i++) {
+      Hash *rn = Getitem(namelist, i);
+      String *rdecl = Getattr(rn, "decl");
+      if (rdecl && (!decl || !Equal(rdecl, decl))) {
+	continue;
+      } else if (Swig_name_match_nameobj(rn, n)) {
+	String *tname = Getattr(rn, "targetname");
+	if (tname) {
+	  String *sfmt = Getattr(rn, "sourcefmt");
+	  String *sname = 0;
+	  int fullname = GetFlag(rn, "fullname");
+	  int rxstarget = GetFlag(rn, "rxstarget");
+	  if (sfmt) {
+	    if (fullname && prefix) {
+	      String *pname = NewStringf("%s::%s", prefix, name);
+	      sname = NewStringf(sfmt, pname);
+	      Delete(pname);
+	    } else {
+	      sname = NewStringf(sfmt, name);
+	    }
+	  } else {
+	    if (fullname && prefix) {
+	      sname = NewStringf("%s::%s", prefix, name);
+	    } else {
+	      sname = name;
+	      DohIncref(name);
+	    }
+	  }
+	  match = rxstarget ? Swig_name_rxsmatch_value(tname, sname) : Swig_name_match_value(tname, sname);
+	  Delete(sname);
+	} else {
+	  match = 1;
+	}
+      }
+      if (match) {
+	res = rn;
+	break;
+      }
+    }
+  }
+  return res;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_namewarn_add
+ *
+ * Add a namewarn objects
+ * 
+ * ----------------------------------------------------------------------------- */
+
+void Swig_name_namewarn_add(String *prefix, String *name, SwigType *decl, Hash *namewrn) {
+  const char *namewrn_keys[] = { "rename", "error", "fullname", "sourcefmt", "targetfmt", 0 };
+  Swig_name_object_attach_keys(namewrn_keys, namewrn);
+  Swig_name_nameobj_add(Swig_name_namewarn_hash(), Swig_name_namewarn_list(), prefix, name, decl, namewrn);
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash *Swig_name_namewarn_get()
+ *
+ * Return the namewarn object, if there is one.
+ * 
+ * ----------------------------------------------------------------------------- */
+
+Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl) {
+  if (!namewarn_hash && !namewarn_list)
+    return 0;
+  if (n) {
+    /* Return in the obvious cases */
+    if (!name || !Swig_need_name_warning(n)) {
+      return 0;
+    } else {
+      String *access = Getattr(n, "access");
+      int is_public = !access || Equal(access, "public");
+      if (!is_public && !Swig_need_protected(n)) {
+	return 0;
+      }
+    }
+  }
+  if (name) {
+    /* Check to see if the name is in the hash */
+    Hash *wrn = Swig_name_object_get(Swig_name_namewarn_hash(), prefix, name, decl);
+    if (wrn && !Swig_name_match_nameobj(wrn, n))
+      wrn = 0;
+    if (!wrn) {
+      wrn = Swig_name_nameobj_lget(Swig_name_namewarn_list(), n, prefix, name, decl);
+    }
+    if (wrn && Getattr(wrn, "error")) {
+      if (n) {
+	Swig_error(Getfile(n), Getline(n), "%s\n", Getattr(wrn, "name"));
+      } else {
+	Swig_error(cparse_file, cparse_line, "%s\n", Getattr(wrn, "name"));
+      }
+    }
+    return wrn;
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * String *Swig_name_warning()
+ *
+ * Return the name warning, if there is one.
+ * 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_warning(Node *n, String *prefix, String *name, SwigType *decl) {
+  Hash *wrn = Swig_name_namewarn_get(n, prefix, name, decl);
+  return (name && wrn) ? Getattr(wrn, "name") : 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_name_rename_add()
+ *
+ * Manage the rename objects
+ * 
+ * ----------------------------------------------------------------------------- */
+
+static void single_rename_add(String *prefix, String *name, SwigType *decl, Hash *newname) {
+  Swig_name_nameobj_add(Swig_name_rename_hash(), Swig_name_rename_list(), prefix, name, decl, newname);
+}
+
+/* Add a new rename. Works much like new_feature including default argument handling. */
+void Swig_name_rename_add(String *prefix, String *name, SwigType *decl, Hash *newname, ParmList *declaratorparms) {
+
+  ParmList *declparms = declaratorparms;
+
+  const char *rename_keys[] = { "fullname", "sourcefmt", "targetfmt", "continue", "rxstarget", 0 };
+  Swig_name_object_attach_keys(rename_keys, newname);
+
+  /* Add the name */
+  single_rename_add(prefix, name, decl, newname);
+
+  /* Add extra names if there are default parameters in the parameter list */
+  if (decl) {
+    int constqualifier = SwigType_isconst(decl);
+    while (declparms) {
+      if (ParmList_has_defaultargs(declparms)) {
+
+	/* Create a parameter list for the new rename by copying all
+	   but the last (defaulted) parameter */
+	ParmList *newparms = CopyParmListMax(declparms,ParmList_len(declparms)-1);
+
+	/* Create new declaration - with the last parameter removed */
+	SwigType *newdecl = Copy(decl);
+	Delete(SwigType_pop_function(newdecl));	/* remove the old parameter list from newdecl */
+	SwigType_add_function(newdecl, newparms);
+	if (constqualifier)
+	  SwigType_add_qualifier(newdecl, "const");
+
+	single_rename_add(prefix, name, newdecl, newname);
+	declparms = newparms;
+	Delete(newdecl);
+      } else {
+	declparms = 0;
+      }
+    }
+  }
+}
+
+
+/* Create a name applying rename/namewarn if needed */
+static String *apply_rename(String *newname, int fullname, String *prefix, String *name) {
+  String *result = 0;
+  if (newname && Len(newname)) {
+    if (Strcmp(newname, "$ignore") == 0) {
+      result = Copy(newname);
+    } else {
+      char *cnewname = Char(newname);
+      if (cnewname) {
+	int destructor = name && (*(Char(name)) == '~');
+	String *fmt = newname;
+	/* use name as a fmt, but avoid C++ "%" and "%=" operators */
+	if (Len(newname) > 1 && strchr(cnewname, '%') && !(strcmp(cnewname, "%=") == 0)) {
+	  if (fullname && prefix) {
+	    result = NewStringf(fmt, prefix, name);
+	  } else {
+	    result = NewStringf(fmt, name);
+	  }
+	} else {
+	  result = Copy(newname);
+	}
+	if (destructor && result && (*(Char(result)) != '~')) {
+	  Insert(result, 0, "~");
+	}
+      }
+    }
+  }
+
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * String *Swig_name_make()
+ *
+ * Make a name after applying all the rename/namewarn objects
+ * 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_make(Node *n, String *prefix, String_or_char *cname, SwigType *decl, String *oldname) {
+  String *nname = 0;
+  String *result = 0;
+  String *name = NewString(cname);
+  Hash *wrn = 0;
+  String *rdecl = 0;
+  String *rname = 0;
+
+  /* very specific hack for template constructors/destructors */
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_make: looking for %s %s %s %s\n", prefix, name, decl, oldname);
+#endif
+
+  if (name && n && SwigType_istemplate(name)) {
+    String *nodetype = nodeType(n);
+    if (nodetype && (Equal(nodetype, "constructor") || Equal(nodetype, "destructor"))) {
+      String *nprefix = NewStringEmpty();
+      String *nlast = NewStringEmpty();
+      String *tprefix;
+      Swig_scopename_split(name, &nprefix, &nlast);
+      tprefix = SwigType_templateprefix(nlast);
+      Delete(nlast);
+      if (Len(nprefix)) {
+	Append(nprefix, "::");
+	Append(nprefix, tprefix);
+	Delete(tprefix);
+	rname = nprefix;
+      } else {
+	rname = tprefix;
+	Delete(nprefix);
+      }
+      rdecl = Copy(decl);
+      Replaceall(rdecl, name, rname);
+#ifdef SWIG_DEBUG
+      Printf(stdout, "SWIG_name_make: use new name %s %s : %s %s\n", name, decl, rname, rdecl);
+#endif
+      decl = rdecl;
+      Delete(name);
+      name = rname;
+    }
+  }
+
+
+  if (rename_hash || rename_list || namewarn_hash || namewarn_list) {
+    Hash *rn = Swig_name_object_get(Swig_name_rename_hash(), prefix, name, decl);
+    if (!rn || !Swig_name_match_nameobj(rn, n)) {
+      rn = Swig_name_nameobj_lget(Swig_name_rename_list(), n, prefix, name, decl);
+      if (rn) {
+	String *sfmt = Getattr(rn, "sourcefmt");
+	int fullname = GetFlag(rn, "fullname");
+	if (fullname && prefix) {
+	  String *sname = NewStringf("%s::%s", prefix, name);
+	  Delete(name);
+	  name = sname;
+	  prefix = 0;
+	}
+	if (sfmt) {
+	  String *sname = NewStringf(sfmt, name);
+	  Delete(name);
+	  name = sname;
+	}
+      }
+    }
+    if (rn) {
+      String *newname = Getattr(rn, "name");
+      int fullname = GetFlag(rn, "fullname");
+      result = apply_rename(newname, fullname, prefix, name);
+    }
+    if (result && !Equal(result, name)) {
+      /* operators in C++ allow aliases, we look for them */
+      char *cresult = Char(result);
+      if (cresult && (strncmp(cresult, "operator ", 9) == 0)) {
+	String *nresult = Swig_name_make(n, prefix, result, decl, oldname);
+	if (!Equal(nresult, result)) {
+	  Delete(result);
+	  result = nresult;
+	} else {
+	  Delete(nresult);
+	}
+      }
+    }
+    nname = result ? result : name;
+    wrn = Swig_name_namewarn_get(n, prefix, nname, decl);
+    if (wrn) {
+      String *rename = Getattr(wrn, "rename");
+      if (rename) {
+	String *msg = Getattr(wrn, "name");
+	int fullname = GetFlag(wrn, "fullname");
+	if (result)
+	  Delete(result);
+	result = apply_rename(rename, fullname, prefix, name);
+	if ((msg) && (Len(msg))) {
+	  if (!Getmeta(nname, "already_warned")) {
+	    if (n) {
+	      SWIG_WARN_NODE_BEGIN(n);
+	      Swig_warning(0, Getfile(n), Getline(n), "%s\n", msg);
+	      SWIG_WARN_NODE_END(n);
+	    } else {
+	      Swig_warning(0, Getfile(name), Getline(name), "%s\n", msg);
+	    }
+	    Setmeta(nname, "already_warned", "1");
+	  }
+	}
+      }
+    }
+  }
+  if (!result || !Len(result)) {
+    if (result)
+      Delete(result);
+    if (oldname) {
+      result = NewString(oldname);
+    } else {
+      result = NewString(cname);
+    }
+  }
+  Delete(name);
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_name_make: result  '%s' '%s'\n", cname, result);
+#endif
+
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * void Swig_name_inherit()
+ *
+ * Inherit namewarn,rename, and feature objects
+ * 
+ * ----------------------------------------------------------------------------- */
+
+void Swig_name_inherit(String *base, String *derived) {
+  /*  Printf(stdout,"base = '%s', derived = '%s'\n", base, derived); */
+  Swig_name_object_inherit(Swig_name_rename_hash(), base, derived);
+  Swig_name_object_inherit(Swig_name_namewarn_hash(), base, derived);
+  Swig_name_object_inherit(Swig_cparse_features(), base, derived);
+}
+
+/* -----------------------------------------------------------------------------
+ * void Swig_name_decl()
+ *
+ * Return a stringified version of a C/C++ declaration without the return type.
+ * The node passed in is expected to be a function. Some example return values:
+ *   "MyNameSpace::MyTemplate<MyNameSpace::ABC >::~MyTemplate()"
+ *   "MyNameSpace::ABC::ABC(int,double)"
+ *   "MyNameSpace::ABC::constmethod(int) const"
+ * 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_decl(Node *n) {
+  String *qname;
+  String *decl;
+  String *qualifier = Swig_symbol_qualified(n);
+  String *name = Swig_scopename_last(Getattr(n, "name"));
+  if (qualifier)
+    qualifier = SwigType_namestr(qualifier);
+
+  /* Very specific hack for template constructors/destructors */
+  if (SwigType_istemplate(name)) {
+    String *nodetype = nodeType(n);
+    if (nodetype && (Equal(nodetype, "constructor") || Equal(nodetype, "destructor"))) {
+      String *nprefix = NewStringEmpty();
+      String *nlast = NewStringEmpty();
+      String *tprefix;
+      Swig_scopename_split(name, &nprefix, &nlast);
+      tprefix = SwigType_templateprefix(nlast);
+      Delete(nlast);
+      Delete(name);
+      name = tprefix;
+    }
+  }
+
+  qname = NewString("");
+  if (qualifier && Len(qualifier) > 0)
+    Printf(qname, "%s::", qualifier);
+  Printf(qname, "%s", name);
+
+  decl = NewStringf("%s(%s)%s", qname, ParmList_errorstr(Getattr(n, "parms")), SwigType_isconst(Getattr(n, "decl")) ? " const" : "");
+
+  Delete(name);
+  Delete(qualifier);
+  Delete(qname);
+
+  return decl;
+}
+
+/* -----------------------------------------------------------------------------
+ * void Swig_name_fulldecl()
+ *
+ * Return a stringified version of a C/C++ declaration including the return type.
+ * The node passed in is expected to be a function. Some example return values:
+ *   "MyNameSpace::MyTemplate<MyNameSpace::ABC >::~MyTemplate()"
+ *   "MyNameSpace::ABC::ABC(int,double)"
+ *   "int * MyNameSpace::ABC::constmethod(int) const"
+ * 
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_name_fulldecl(Node *n) {
+  String *decl = Swig_name_decl(n);
+  String *type = Getattr(n, "type");
+  String *nodetype = nodeType(n);
+  String *fulldecl;
+  /* add on the return type */
+  if (nodetype && (Equal(nodetype, "constructor") || Equal(nodetype, "destructor"))) {
+    fulldecl = decl;
+  } else {
+    String *t = SwigType_str(type, 0);
+    fulldecl = NewStringf("%s %s", t, decl);
+    Delete(decl);
+    Delete(t);
+  }
+  return fulldecl;
+}
+
diff --git a/trunk/Source/Swig/parms.c b/trunk/Source/Swig/parms.c
new file mode 100644
index 0000000..baa1dfb
--- /dev/null
+++ b/trunk/Source/Swig/parms.c
@@ -0,0 +1,196 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * parms.c
+ *
+ * Parameter list class.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_parms_c[] = "$Id$";
+
+#include "swig.h"
+
+/* ------------------------------------------------------------------------
+ * NewParm()
+ *
+ * Create a new parameter from datatype 'type' and name 'name'.
+ * ------------------------------------------------------------------------ */
+
+Parm *NewParm(SwigType *type, const String_or_char *name) {
+  Parm *p = NewHash();
+  set_nodeType(p, "parm");
+  if (type) {
+    SwigType *ntype = Copy(type);
+    Setattr(p, "type", ntype);
+    Delete(ntype);
+  }
+  Setattr(p, "name", name);
+  return p;
+}
+
+/* ------------------------------------------------------------------------
+ * CopyParm()
+ * ------------------------------------------------------------------------ */
+
+Parm *CopyParm(Parm *p) {
+  Parm *np = NewHash();
+  Iterator ki;
+  for (ki = First(p); ki.key; ki = Next(ki)) {
+    if (DohIsString(ki.item)) {
+      DOH *c = Copy(ki.item);
+      Setattr(np,ki.key,c);
+      Delete(c);
+    }
+  }
+  Setfile(np, Getfile(p));
+  Setline(np, Getline(p));
+  return np;
+}
+
+/* ------------------------------------------------------------------
+ * CopyParmListMax()
+ * CopyParmList()
+ * ------------------------------------------------------------------ */
+
+ParmList *CopyParmListMax(ParmList *p, int count) {
+  Parm *np;
+  Parm *pp = 0;
+  Parm *fp = 0;
+
+  if (!p)
+    return 0;
+
+  while (p) {
+    if (count == 0) break;
+    np = CopyParm(p);
+    if (pp) {
+      set_nextSibling(pp, np);
+      Delete(np);
+    } else {
+      fp = np;
+    }
+    pp = np;
+    p = nextSibling(p);
+    count--;
+  }
+  return fp;
+}
+
+ParmList *CopyParmList(ParmList *p) {
+  return CopyParmListMax(p,-1);
+}
+
+/* -----------------------------------------------------------------------------
+ * int ParmList_numrequired().  Return number of required arguments
+ * ----------------------------------------------------------------------------- */
+
+int ParmList_numrequired(ParmList *p) {
+  int i = 0;
+  while (p) {
+    SwigType *t = Getattr(p, "type");
+    String *value = Getattr(p, "value");
+    if (value)
+      return i;
+    if (!(SwigType_type(t) == T_VOID))
+      i++;
+    else
+      break;
+    p = nextSibling(p);
+  }
+  return i;
+}
+
+/* -----------------------------------------------------------------------------
+ * int ParmList_len()
+ * ----------------------------------------------------------------------------- */
+
+int ParmList_len(ParmList *p) {
+  int i = 0;
+  while (p) {
+    i++;
+    p = nextSibling(p);
+  }
+  return i;
+}
+
+/* ---------------------------------------------------------------------
+ * ParmList_str()
+ *
+ * Generates a string of parameters
+ * ---------------------------------------------------------------------- */
+
+String *ParmList_str(ParmList *p) {
+  String *out = NewStringEmpty();
+  while (p) {
+    String *pstr = SwigType_str(Getattr(p, "type"), Getattr(p, "name"));
+    Append(out, pstr);
+    p = nextSibling(p);
+    if (p) {
+      Append(out, ",");
+    }
+    Delete(pstr);
+  }
+  return out;
+}
+
+/* ---------------------------------------------------------------------
+ * ParmList_str_defaultargs()
+ *
+ * Generates a string of parameters including default arguments
+ * ---------------------------------------------------------------------- */
+
+String *ParmList_str_defaultargs(ParmList *p) {
+  String *out = NewStringEmpty();
+  while (p) {
+    String *value = Getattr(p, "value");
+    String *pstr = SwigType_str(Getattr(p, "type"), Getattr(p, "name"));
+    Append(out, pstr);
+    if (value) {
+      Printf(out, "=%s", value);
+    }
+    p = nextSibling(p);
+    if (p) {
+      Append(out, ",");
+    }
+    Delete(pstr);
+  }
+  return out;
+}
+
+/* ---------------------------------------------------------------------
+ * ParmList_protostr()
+ *
+ * Generate a prototype string.
+ * ---------------------------------------------------------------------- */
+
+String *ParmList_protostr(ParmList *p) {
+  String *out = NewStringEmpty();
+  while (p) {
+    String *pstr = SwigType_str(Getattr(p, "type"), 0);
+    Append(out, pstr);
+    p = nextSibling(p);
+    if (p) {
+      Append(out, ",");
+    }
+    Delete(pstr);
+  }
+  return out;
+}
+
+/* ---------------------------------------------------------------------
+ * ParmList_has_defaultargs()
+ *
+ * Returns 1 if the parameter list passed in is has one or more default
+ * arguments. Otherwise returns 0.
+ * ---------------------------------------------------------------------- */
+
+int ParmList_has_defaultargs(ParmList *p) {
+  while (p) {
+    if (Getattr(p, "value")) {
+      return 1;
+    }
+    p = nextSibling(p);
+  }
+  return 0;
+}
diff --git a/trunk/Source/Swig/scanner.c b/trunk/Source/Swig/scanner.c
new file mode 100644
index 0000000..06e78db
--- /dev/null
+++ b/trunk/Source/Swig/scanner.c
@@ -0,0 +1,1223 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * scanner.c
+ *
+ * This file implements a general purpose C/C++ compatible lexical scanner.
+ * This scanner isn't intended to be plugged directly into a parser built
+ * with yacc. Rather, it contains a lot of generic code that could be used
+ * to easily construct yacc-compatible scanners.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_scanner_c[] = "$Id$";
+
+#include "swig.h"
+#include <ctype.h>
+
+struct Scanner {
+  String *text;			/* Current token value */
+  List   *scanobjs;		/* Objects being scanned */
+  String *str;			/* Current object being scanned */
+  char   *idstart;		/* Optional identifier start characters */
+  int     nexttoken;		/* Next token to be returned */
+  int     start_line;		/* Starting line of certain declarations */
+  int     line;
+  int     yylen;	        /* Length of text pushed into text */
+  String *file;
+  String *error;                /* Last error message (if any) */
+  int     error_line;           /* Error line number */
+  int     freeze_line;          /* Suspend line number updates */
+};
+
+/* -----------------------------------------------------------------------------
+ * NewScanner()
+ *
+ * Create a new scanner object
+ * ----------------------------------------------------------------------------- */
+
+Scanner *NewScanner() {
+  Scanner *s;
+  s = (Scanner *) malloc(sizeof(Scanner));
+  s->line = 1;
+  s->file = 0;
+  s->nexttoken = -1;
+  s->start_line = 1;
+  s->yylen = 0;
+  s->idstart = NULL;
+  s->scanobjs = NewList();
+  s->text = NewStringEmpty();
+  s->str = 0;
+  s->error = 0;
+  s->freeze_line = 0;
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * DelScanner()
+ *
+ * Delete a scanner object.
+ * ----------------------------------------------------------------------------- */
+
+void DelScanner(Scanner * s) {
+  assert(s);
+  Delete(s->scanobjs);
+  Delete(s->text);
+  Delete(s->file);
+  Delete(s->error);
+  Delete(s->str);
+  free(s->idstart);
+  free(s);
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_clear()
+ *
+ * Clear the contents of a scanner object.
+ * ----------------------------------------------------------------------------- */
+
+void Scanner_clear(Scanner * s) {
+  assert(s);
+  Delete(s->str);
+  Clear(s->text);
+  Clear(s->scanobjs);
+  Delete(s->error);
+  s->error = 0;
+  s->line = 1;
+  s->nexttoken = -1;
+  s->start_line = 0;
+  s->yylen = 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_push()
+ *
+ * Push some new text into the scanner.  The scanner will start parsing this text
+ * immediately before returning to the old text.
+ * ----------------------------------------------------------------------------- */
+
+void Scanner_push(Scanner * s, String *txt) {
+  assert(s && txt);
+  Push(s->scanobjs, txt);
+  if (s->str) {
+    Setline(s->str,s->line);
+    Delete(s->str);
+  }
+  s->str = txt;
+  DohIncref(s->str);
+  s->line = Getline(txt);
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_pushtoken()
+ *
+ * Push a token into the scanner.  This token will be returned on the next
+ * call to Scanner_token().
+ * ----------------------------------------------------------------------------- */
+
+void Scanner_pushtoken(Scanner * s, int nt, const String_or_char *val) {
+  assert(s);
+  assert((nt >= 0) && (nt < SWIG_MAXTOKENS));
+  s->nexttoken = nt;
+  if (val != s->text) {
+    Clear(s->text);
+    Append(s->text,val);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_set_location()
+ *
+ * Set the file and line number location of the scanner.
+ * ----------------------------------------------------------------------------- */
+
+void Scanner_set_location(Scanner * s, String *file, int line) {
+  Setline(s->str, line);
+  Setfile(s->str, file);
+  s->line = line;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_file()
+ *
+ * Get the current file.
+ * ----------------------------------------------------------------------------- */
+
+String *Scanner_file(Scanner * s) {
+  return Getfile(s->str);
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_line()
+ *
+ * Get the current line number
+ * ----------------------------------------------------------------------------- */
+int Scanner_line(Scanner * s) {
+  return s->line;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_start_line()
+ *
+ * Get the line number on which the current token starts
+ * ----------------------------------------------------------------------------- */
+int Scanner_start_line(Scanner * s) {
+  return s->start_line;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_idstart()
+ *
+ * Change the set of additional characters that can be used to start an identifier.
+ * ----------------------------------------------------------------------------- */
+
+void Scanner_idstart(Scanner * s, const char *id) {
+  free(s->idstart);
+  s->idstart = Swig_copy_string(id);
+}
+
+/* -----------------------------------------------------------------------------
+ * nextchar()
+ * 
+ * Returns the next character from the scanner or 0 if end of the string.
+ * ----------------------------------------------------------------------------- */
+static char nextchar(Scanner * s) {
+  int nc;
+  if (!s->str)
+    return 0;
+  while ((nc = Getc(s->str)) == EOF) {
+    Delete(s->str);
+    s->str = 0;
+    Delitem(s->scanobjs, 0);
+    if (Len(s->scanobjs) == 0)
+      return 0;
+    s->str = Getitem(s->scanobjs, 0);
+    if (s->str) {
+      s->line = Getline(s->str);
+      DohIncref(s->str);
+    }
+  }
+  if ((nc == '\n') && (!s->freeze_line)) 
+    s->line++;
+  Putc(nc,s->text);
+  return (char)nc;
+}
+
+/* -----------------------------------------------------------------------------
+ * set_error() 
+ *
+ * Sets error information on the scanner.
+ * ----------------------------------------------------------------------------- */
+
+static void set_error(Scanner *s, int line, String_or_char *msg) {
+  s->error_line = line;
+  s->error = NewString(msg);
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_errmsg()
+ * Scanner_errline()
+ *
+ * Returns error information (if any)
+ * ----------------------------------------------------------------------------- */
+
+String *
+Scanner_errmsg(Scanner *s) {
+  return s->error;
+}
+
+int
+Scanner_errline(Scanner *s) {
+  return s->error_line;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_freeze_line()
+ *
+ * Freezes the current line number.
+ * ----------------------------------------------------------------------------- */
+
+void
+Scanner_freeze_line(Scanner *s, int val) {
+  s->freeze_line = val;
+}
+
+/* -----------------------------------------------------------------------------
+ * retract()
+ *
+ * Retract n characters
+ * ----------------------------------------------------------------------------- */
+static void retract(Scanner * s, int n) {
+  int i, l;
+  char *str;
+
+  str = Char(s->text);
+  l = Len(s->text);
+  assert(n <= l);
+  for (i = 0; i < n; i++) {
+    if (str[l - 1] == '\n') {
+      if (!s->freeze_line) s->line--;
+    }
+    Seek(s->str, -1, SEEK_CUR);
+    Delitem(s->text, DOH_END);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * get_escape()
+ * 
+ * Get escape sequence.  Called when a backslash is found in a string
+ * ----------------------------------------------------------------------------- */
+
+static void get_escape(Scanner *s) {
+  int result = 0;
+  int state = 0;
+  int c;
+
+  while (1) {
+    c = nextchar(s);
+    if (c == 0)
+      break;
+    switch (state) {
+    case 0:
+      if (c == 'n') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\n");
+	return;
+      }
+      if (c == 'r') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\r");
+	return;
+      }
+      if (c == 't') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\t");
+	return;
+      }
+      if (c == 'a') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\a");
+	return;
+      }
+      if (c == 'b') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\b");
+	return;
+      }
+      if (c == 'f') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\f");
+	return;
+      }
+      if (c == '\\') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\\");
+	return;
+      }
+      if (c == 'v') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\v");
+	return;
+      }
+      if (c == 'e') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\033");
+	return;
+      }
+      if (c == '\'') {
+	Delitem(s->text, DOH_END);
+	Append(s->text,"\'");
+	return;
+      }
+      if (c == '\"') {
+	Delitem(s->text, DOH_END);	
+	Append(s->text,"\"");
+	return;
+      }
+      if (c == '\n') {
+	Delitem(s->text, DOH_END);
+	return;
+      }
+      if (isdigit(c)) {
+	state = 10;
+	result = (c - '0');
+	Delitem(s->text, DOH_END);
+      } else if (c == 'x') {
+	state = 20;
+	Delitem(s->text, DOH_END);
+      } else {
+	char tmp[3];
+	tmp[0] = '\\';
+	tmp[1] = (char)c;
+	tmp[2] = 0;
+	Delitem(s->text, DOH_END);
+	Append(s->text, tmp);
+	return;
+      }
+      break;
+    case 10:
+      if (!isdigit(c)) {
+	retract(s,1);
+	Putc((char)result,s->text);
+	return;
+      }
+      result = (result << 3) + (c - '0');
+      Delitem(s->text, DOH_END);
+      break;
+    case 20:
+      if (!isxdigit(c)) {
+	retract(s,1);
+	Putc((char)result, s->text);
+	return;
+      }
+      if (isdigit(c))
+	result = (result << 4) + (c - '0');
+      else
+	result = (result << 4) + (10 + tolower(c) - 'a');
+      Delitem(s->text, DOH_END);
+      break;
+    }
+  }
+  return;
+}
+
+/* -----------------------------------------------------------------------------
+ * look()
+ *
+ * Return the raw value of the next token.
+ * ----------------------------------------------------------------------------- */
+
+static int look(Scanner * s) {
+  int state;
+  int c = 0;
+
+  state = 0;
+  Clear(s->text);
+  s->start_line = s->line;
+  Setfile(s->text, Getfile(s->str));
+  while (1) {
+    switch (state) {
+    case 0:
+      if ((c = nextchar(s)) == 0)
+	return (0);
+
+      /* Process delimiters */
+
+      if (c == '\n') {
+	return SWIG_TOKEN_ENDLINE;
+      } else if (!isspace(c)) {
+	retract(s, 1);
+	state = 1000;
+	Clear(s->text);
+	Setline(s->text, s->line);
+	Setfile(s->text, Getfile(s->str));
+      }
+      break;
+
+    case 1000:
+      if ((c = nextchar(s)) == 0)
+	return (0);
+      if (c == '%')
+	state = 4;		/* Possibly a SWIG directive */
+
+      /* Look for possible identifiers */
+
+      else if ((isalpha(c)) || (c == '_') ||
+	       (s->idstart && strchr(s->idstart, c)))
+	state = 7;
+
+      /* Look for single character symbols */
+
+      else if (c == '(')
+	return SWIG_TOKEN_LPAREN;
+      else if (c == ')')
+	return SWIG_TOKEN_RPAREN;
+      else if (c == ';')
+	return SWIG_TOKEN_SEMI;
+      else if (c == ',')
+	return SWIG_TOKEN_COMMA;
+      else if (c == '*')
+	state = 220;
+      else if (c == '}')
+	return SWIG_TOKEN_RBRACE;
+      else if (c == '{')
+	return SWIG_TOKEN_LBRACE;
+      else if (c == '=')
+	state = 33;
+      else if (c == '+')
+	state = 200;
+      else if (c == '-')
+	state = 210;
+      else if (c == '&')
+	state = 31;
+      else if (c == '|')
+	state = 32;
+      else if (c == '^')
+	state = 230;
+      else if (c == '<')
+	state = 60;
+      else if (c == '>')
+	state = 61;
+      else if (c == '~')
+	return SWIG_TOKEN_NOT;
+      else if (c == '!')
+	state = 3;
+      else if (c == '\\')
+	return SWIG_TOKEN_BACKSLASH;
+      else if (c == '[')
+	return SWIG_TOKEN_LBRACKET;
+      else if (c == ']')
+	return SWIG_TOKEN_RBRACKET;
+      else if (c == '@')
+	return SWIG_TOKEN_AT;
+      else if (c == '$')
+	state = 75;
+      else if (c == '#')
+	return SWIG_TOKEN_POUND;
+      else if (c == '?')
+	return SWIG_TOKEN_QUESTION;
+
+      /* Look for multi-character sequences */
+
+      else if (c == '/') {
+	state = 1;		/* Comment (maybe)  */
+	s->start_line = s->line;
+      }
+      else if (c == '\"') {
+	state = 2;		/* Possibly a string */
+	s->start_line = s->line;
+	Clear(s->text);
+      }
+
+      else if (c == ':')
+	state = 5;		/* maybe double colon */
+      else if (c == '0')
+	state = 83;		/* An octal or hex value */
+      else if (c == '\'') {
+	s->start_line = s->line;
+	Clear(s->text);
+	state = 9;		/* A character constant */
+      } else if (c == '`') {
+	s->start_line = s->line;
+	Clear(s->text);
+	state = 900;
+      }
+
+      else if (c == '.')
+	state = 100;		/* Maybe a number, maybe just a period */
+      else if (isdigit(c))
+	state = 8;		/* A numerical value */
+      else
+	state = 99;		/* An error */
+      break;
+
+    case 1:			/*  Comment block */
+      if ((c = nextchar(s)) == 0)
+	return (0);
+      if (c == '/') {
+	state = 10;		/* C++ style comment */
+	Clear(s->text);
+	Setline(s->text, Getline(s->str));
+	Setfile(s->text, Getfile(s->str));
+	Append(s->text, "//");
+      } else if (c == '*') {
+	state = 11;		/* C style comment */
+	Clear(s->text);
+	Setline(s->text, Getline(s->str));
+	Setfile(s->text, Getfile(s->str));
+	Append(s->text, "/*");
+      } else if (c == '=') {
+	return SWIG_TOKEN_DIVEQUAL;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_SLASH;
+      }
+      break;
+    case 10:			/* C++ style comment */
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated comment");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '\n') {
+	retract(s,1);
+	return SWIG_TOKEN_COMMENT;
+      } else {
+	state = 10;
+      }
+      break;
+    case 11:			/* C style comment block */
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated comment");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '*') {
+	state = 12;
+      } else {
+	state = 11;
+      }
+      break;
+    case 12:			/* Still in C style comment */
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated comment");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '*') {
+	state = 12;
+      } else if (c == '/') {
+	return SWIG_TOKEN_COMMENT;
+      } else {
+	state = 11;
+      }
+      break;
+
+    case 2:			/* Processing a string */
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line, "Unterminated string");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '\"') {
+	Delitem(s->text, DOH_END);
+	return SWIG_TOKEN_STRING;
+      } else if (c == '\\') {
+	Delitem(s->text, DOH_END);
+	get_escape(s);
+      } else
+	state = 2;
+      break;
+
+    case 3:			/* Maybe a not equals */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_LNOT;
+      else if (c == '=')
+	return SWIG_TOKEN_NOTEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_LNOT;
+      }
+      break;
+
+    case 31:			/* AND or Logical AND or ANDEQUAL */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_AND;
+      else if (c == '&')
+	return SWIG_TOKEN_LAND;
+      else if (c == '=')
+	return SWIG_TOKEN_ANDEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_AND;
+      }
+      break;
+
+    case 32:			/* OR or Logical OR */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_OR;
+      else if (c == '|')
+	return SWIG_TOKEN_LOR;
+      else if (c == '=')
+	return SWIG_TOKEN_OREQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_OR;
+      }
+      break;
+
+    case 33:			/* EQUAL or EQUALTO */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_EQUAL;
+      else if (c == '=')
+	return SWIG_TOKEN_EQUALTO;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_EQUAL;
+      }
+      break;
+
+    case 4:			/* A wrapper generator directive (maybe) */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_PERCENT;
+      if (c == '{') {
+	state = 40;		/* Include block */
+	Clear(s->text);
+	Setline(s->text, Getline(s->str));
+	Setfile(s->text, Getfile(s->str));
+	s->start_line = s->line;
+      } else if (s->idstart && strchr(s->idstart, '%') &&
+	         ((isalpha(c)) || (c == '_'))) {
+	state = 7;
+      } else if (c == '=') {
+	return SWIG_TOKEN_MODEQUAL;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_PERCENT;
+      }
+      break;
+
+    case 40:			/* Process an include block */
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated code block");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '%')
+	state = 41;
+      break;
+    case 41:			/* Still processing include block */
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated code block");
+	return 0;
+      }
+      if (c == '}') {
+	Delitem(s->text, DOH_END);
+	Delitem(s->text, DOH_END);
+	Seek(s->text,0,SEEK_SET);
+	return SWIG_TOKEN_CODEBLOCK;
+      } else {
+	state = 40;
+      }
+      break;
+
+    case 5:			/* Maybe a double colon */
+
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_COLON;
+      if (c == ':')
+	state = 50;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_COLON;
+      }
+      break;
+
+    case 50:			/* DCOLON, DCOLONSTAR */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_DCOLON;
+      else if (c == '*')
+	return SWIG_TOKEN_DCOLONSTAR;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_DCOLON;
+      }
+      break;
+
+    case 60:			/* shift operators */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_LESSTHAN;
+      if (c == '<')
+	state = 240;
+      else if (c == '=')
+	return SWIG_TOKEN_LTEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_LESSTHAN;
+      }
+      break;
+    case 61:
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_GREATERTHAN;
+      if (c == '>')
+	state = 250;
+      else if (c == '=')
+	return SWIG_TOKEN_GTEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_GREATERTHAN;
+      }
+      break;
+    case 7:			/* Identifier */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_ID;
+      if (isalnum(c) || (c == '_') || (c == '$')) {
+	state = 7;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_ID;
+      }
+      break;
+
+    case 75:			/* Special identifier $ */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_DOLLAR;
+      if (isalnum(c) || (c == '_') || (c == '*') || (c == '&')) {
+	state = 7;
+      } else {
+	retract(s,1);
+	if (Len(s->text) == 1) return SWIG_TOKEN_DOLLAR;
+	return SWIG_TOKEN_ID;
+      }
+      break;
+
+    case 8:			/* A numerical digit */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_INT;
+      if (c == '.') {
+	state = 81;
+      } else if ((c == 'e') || (c == 'E')) {
+	state = 82;
+      } else if ((c == 'f') || (c == 'F')) {
+	Delitem(s->text, DOH_END);
+	return SWIG_TOKEN_FLOAT;
+      } else if (isdigit(c)) {
+	state = 8;
+      } else if ((c == 'l') || (c == 'L')) {
+	state = 87;
+      } else if ((c == 'u') || (c == 'U')) {
+	state = 88;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_INT;
+      }
+      break;
+    case 81:			/* A floating pointer number of some sort */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_DOUBLE;
+      if (isdigit(c))
+	state = 81;
+      else if ((c == 'e') || (c == 'E'))
+	state = 820;
+      else if ((c == 'f') || (c == 'F')) {
+	Delitem(s->text, DOH_END);
+	return SWIG_TOKEN_FLOAT;
+      } else if ((c == 'l') || (c == 'L')) {
+	Delitem(s->text, DOH_END);
+	return SWIG_TOKEN_DOUBLE;
+      } else {
+	retract(s, 1);
+	return (SWIG_TOKEN_DOUBLE);
+      }
+      break;
+    case 82:
+      if ((c = nextchar(s)) == 0) {
+	retract(s, 1);
+	return SWIG_TOKEN_INT;
+      }
+      if ((isdigit(c)) || (c == '-') || (c == '+'))
+	state = 86;
+      else {
+	retract(s, 2);
+	return (SWIG_TOKEN_INT);
+      }
+      break;
+    case 820:
+      /* Like case 82, but we've seen a decimal point. */
+      if ((c = nextchar(s)) == 0) {
+	retract(s, 1);
+	return SWIG_TOKEN_DOUBLE;
+      }
+      if ((isdigit(c)) || (c == '-') || (c == '+'))
+	state = 86;
+      else {
+	retract(s, 2);
+	return (SWIG_TOKEN_DOUBLE);
+      }
+      break;
+    case 83:
+      /* Might be a hexadecimal or octal number */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_INT;
+      if (isdigit(c))
+	state = 84;
+      else if ((c == 'x') || (c == 'X'))
+	state = 85;
+      else if (c == '.')
+	state = 81;
+      else if ((c == 'l') || (c == 'L')) {
+	state = 87;
+      } else if ((c == 'u') || (c == 'U')) {
+	state = 88;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_INT;
+      }
+      break;
+    case 84:
+      /* This is an octal number */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_INT;
+      if (isdigit(c))
+	state = 84;
+      else if ((c == 'l') || (c == 'L')) {
+	state = 87;
+      } else if ((c == 'u') || (c == 'U')) {
+	state = 88;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_INT;
+      }
+      break;
+    case 85:
+      /* This is an hex number */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_INT;
+      if (isxdigit(c))
+	state = 85;
+      else if ((c == 'l') || (c == 'L')) {
+	state = 87;
+      } else if ((c == 'u') || (c == 'U')) {
+	state = 88;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_INT;
+      }
+      break;
+
+    case 86:
+      /* Rest of floating point number */
+
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_DOUBLE;
+      if (isdigit(c))
+	state = 86;
+      else if ((c == 'f') || (c == 'F')) {
+	Delitem(s->text, DOH_END);
+	return SWIG_TOKEN_FLOAT;
+      } else if ((c == 'l') || (c == 'L')) {
+	Delitem(s->text, DOH_END);
+	return SWIG_TOKEN_DOUBLE;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_DOUBLE;
+      }
+      break;
+
+    case 87:
+      /* A long integer of some sort */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_LONG;
+      if ((c == 'u') || (c == 'U')) {
+	return SWIG_TOKEN_ULONG;
+      } else if ((c == 'l') || (c == 'L')) {
+	state = 870;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_LONG;
+      }
+      break;
+
+      /* A long long integer */
+
+    case 870:
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_LONGLONG;
+      if ((c == 'u') || (c == 'U')) {
+	return SWIG_TOKEN_ULONGLONG;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_LONGLONG;
+      }
+
+      /* An unsigned number */
+    case 88:
+
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_UINT;
+      if ((c == 'l') || (c == 'L')) {
+	state = 880;
+      } else {
+	retract(s, 1);
+	return SWIG_TOKEN_UINT;
+      }
+      break;
+
+      /* Possibly an unsigned long long or unsigned long */
+    case 880:
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_ULONG;
+      if ((c == 'l') || (c == 'L'))
+	return SWIG_TOKEN_ULONGLONG;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_ULONG;
+      }
+
+      /* A character constant */
+    case 9:
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated character constant");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '\'') {
+	Delitem(s->text, DOH_END);
+	return (SWIG_TOKEN_CHAR);
+      } else if (c == '\\') {
+	Delitem(s->text, DOH_END);
+	get_escape(s);
+      }
+      break;
+
+      /* A period or maybe a floating point number */
+
+    case 100:
+      if ((c = nextchar(s)) == 0)
+	return (0);
+      if (isdigit(c))
+	state = 81;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_PERIOD;
+      }
+      break;
+
+    case 200:			/* PLUS, PLUSPLUS, PLUSEQUAL */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_PLUS;
+      else if (c == '+')
+	return SWIG_TOKEN_PLUSPLUS;
+      else if (c == '=')
+	return SWIG_TOKEN_PLUSEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_PLUS;
+      }
+      break;
+
+    case 210:			/* MINUS, MINUSMINUS, MINUSEQUAL, ARROW */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_MINUS;
+      else if (c == '-')
+	return SWIG_TOKEN_MINUSMINUS;
+      else if (c == '=')
+	return SWIG_TOKEN_MINUSEQUAL;
+      else if (c == '>')
+	state = 211;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_MINUS;
+      }
+      break;
+
+    case 211:			/* ARROW, ARROWSTAR */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_ARROW;
+      else if (c == '*')
+	return SWIG_TOKEN_ARROWSTAR;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_ARROW;
+      }
+      break;
+
+
+    case 220:			/* STAR, TIMESEQUAL */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_STAR;
+      else if (c == '=')
+	return SWIG_TOKEN_TIMESEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_STAR;
+      }
+      break;
+
+    case 230:			/* XOR, XOREQUAL */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_XOR;
+      else if (c == '=')
+	return SWIG_TOKEN_XOREQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_XOR;
+      }
+      break;
+
+    case 240:			/* LSHIFT, LSEQUAL */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_LSHIFT;
+      else if (c == '=')
+	return SWIG_TOKEN_LSEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_LSHIFT;
+      }
+      break;
+
+    case 250:			/* RSHIFT, RSEQUAL */
+      if ((c = nextchar(s)) == 0)
+	return SWIG_TOKEN_RSHIFT;
+      else if (c == '=')
+	return SWIG_TOKEN_RSEQUAL;
+      else {
+	retract(s, 1);
+	return SWIG_TOKEN_RSHIFT;
+      }
+      break;
+
+
+      /* An illegal character */
+
+      /* Reverse string */
+    case 900:
+      if ((c = nextchar(s)) == 0) {
+	set_error(s,s->start_line,"Unterminated character constant");
+	return SWIG_TOKEN_ERROR;
+      }
+      if (c == '`') {
+	Delitem(s->text, DOH_END);
+	return (SWIG_TOKEN_RSTRING);
+      }
+      break;
+
+    default:
+      return SWIG_TOKEN_ILLEGAL;
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_token()
+ *
+ * Real entry point to return the next token. Returns 0 if at end of input.
+ * ----------------------------------------------------------------------------- */
+
+int Scanner_token(Scanner * s) {
+  int t;
+  Delete(s->error);
+  if (s->nexttoken >= 0) {
+    t = s->nexttoken;
+    s->nexttoken = -1;
+    return t;
+  }
+  s->start_line = 0;
+  t = look(s);
+  if (!s->start_line) {
+    Setline(s->text,s->line);
+  } else {
+    Setline(s->text,s->start_line);
+  }
+  return t;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_text()
+ *
+ * Return the lexene associated with the last returned token.
+ * ----------------------------------------------------------------------------- */
+
+String *Scanner_text(Scanner * s) {
+  return s->text;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_skip_line()
+ *
+ * Skips to the end of a line
+ * ----------------------------------------------------------------------------- */
+
+void Scanner_skip_line(Scanner * s) {
+  char c;
+  int done = 0;
+  Clear(s->text);
+  Setfile(s->text, Getfile(s->str));
+  Setline(s->text, s->line);
+  while (!done) {
+    if ((c = nextchar(s)) == 0)
+      return;
+    if (c == '\\') {
+      c = nextchar(s);
+    } else if (c == '\n') {
+      done = 1;
+    }
+  }
+  return;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_skip_balanced()
+ *
+ * Skips a piece of code enclosed in begin/end symbols such as '{...}' or
+ * (...).  Ignores symbols inside comments or strings.
+ * ----------------------------------------------------------------------------- */
+
+int Scanner_skip_balanced(Scanner * s, int startchar, int endchar) {
+  char c;
+  int num_levels = 1;
+  int l;
+  int state = 0;
+  char temp[2] = { 0, 0 };
+  l = s->line;
+  temp[0] = (char) startchar;
+  Clear(s->text);
+  Setfile(s->text, Getfile(s->str));
+  Setline(s->text, s->line);
+
+  Append(s->text, temp);
+  while (num_levels > 0) {
+    if ((c = nextchar(s)) == 0) {
+      return -1;
+    }
+    switch (state) {
+    case 0:
+      if (c == startchar)
+	num_levels++;
+      else if (c == endchar)
+	num_levels--;
+      else if (c == '/')
+	state = 10;
+      else if (c == '\"')
+	state = 20;
+      else if (c == '\'')
+	state = 30;
+      break;
+    case 10:
+      if (c == '/')
+	state = 11;
+      else if (c == '*')
+	state = 12;
+      else
+	state = 0;
+      break;
+    case 11:
+      if (c == '\n')
+	state = 0;
+      else
+	state = 11;
+      break;
+    case 12:
+      if (c == '*')
+	state = 13;
+      break;
+    case 13:
+      if (c == '*')
+	state = 13;
+      else if (c == '/')
+	state = 0;
+      else
+	state = 12;
+      break;
+    case 20:
+      if (c == '\"')
+	state = 0;
+      else if (c == '\\')
+	state = 21;
+      break;
+    case 21:
+      state = 20;
+      break;
+    case 30:
+      if (c == '\'')
+	state = 0;
+      else if (c == '\\')
+	state = 31;
+      break;
+    case 31:
+      state = 30;
+      break;
+    default:
+      break;
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Scanner_isoperator()
+ *
+ * Returns 0 or 1 depending on whether or not a token corresponds to a C/C++
+ * operator.
+ * ----------------------------------------------------------------------------- */
+
+int
+Scanner_isoperator(int tokval) {
+  if (tokval >= 100) return 1;
+  return 0;
+}
diff --git a/trunk/Source/Swig/stype.c b/trunk/Source/Swig/stype.c
new file mode 100644
index 0000000..5ffd28e
--- /dev/null
+++ b/trunk/Source/Swig/stype.c
@@ -0,0 +1,1105 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * stype.c
+ *
+ * This file provides general support for datatypes that are encoded in
+ * the form of simple strings.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_stype_c[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+#include <ctype.h>
+
+/* -----------------------------------------------------------------------------
+ * Synopsis
+ *
+ * The purpose of this module is to provide a general purpose type representation
+ * based on simple text strings. 
+ *
+ * General idea:
+ *
+ * Types are represented by a base type (e.g., "int") and a collection of
+ * type operators applied to the base (e.g., pointers, arrays, etc...).
+ *
+ * Encoding:
+ *
+ * Types are encoded as strings of type constructors such as follows:
+ *
+ *        String Encoding                 C Example
+ *        ---------------                 ---------
+ *        p.p.int                         int **
+ *        a(300).a(400).int               int [300][400]
+ *        p.q(const).char                 char const *
+ *
+ * All type constructors are denoted by a trailing '.':
+ * 
+ *  'p.'                = Pointer (*)
+ *  'r.'                = Reference (&)
+ *  'a(n).'             = Array of size n  [n]
+ *  'f(..,..).'         = Function with arguments  (args)
+ *  'q(str).'           = Qualifier (such as const or volatile) (const, volatile)
+ *  'm(qual).'          = Pointer to member (qual::*)
+ *
+ * The encoding follows the order that you might describe a type in words.
+ * For example "p.a(200).int" is "A pointer to array of int's" and
+ * "p.q(const).char" is "a pointer to a const char".
+ *
+ * This representation of types is fairly convenient because ordinary string
+ * operations can be used for type manipulation. For example, a type could be
+ * formed by combining two strings such as the following:
+ *
+ *        "p.p." + "a(400).int" = "p.p.a(400).int"
+ *
+ * Similarly, one could strip a 'const' declaration from a type doing something
+ * like this:
+ *
+ *        Replace(t,"q(const).","",DOH_REPLACE_ANY)
+ *
+ * For the most part, this module tries to minimize the use of special
+ * characters (*, [, <, etc...) in its type encoding.  One reason for this
+ * is that SWIG might be extended to encode data in formats such as XML
+ * where you might want to do this:
+ * 
+ *      <function>
+ *         <type>p.p.int</type>
+ *         ...
+ *      </function>
+ *
+ * Or alternatively,
+ *
+ *      <function type="p.p.int" ...>blah</function>
+ *
+ * In either case, it's probably best to avoid characters such as '&', '*', or '<'.
+ *
+ * Why not use C syntax?  Well, C syntax is fairly complicated to parse
+ * and not particularly easy to manipulate---especially for adding, deleting and
+ * composing type constructors.  The string representation presented here makes
+ * this pretty easy.
+ *
+ * Why not use a bunch of nested data structures?  Are you kidding? How
+ * would that be easier to use than a few simple string operations? 
+ * ----------------------------------------------------------------------------- */
+
+
+SwigType *NewSwigType(int t) {
+  switch (t) {
+  case T_BOOL:
+    return NewString("bool");
+    break;
+  case T_INT:
+    return NewString("int");
+    break;
+  case T_UINT:
+    return NewString("unsigned int");
+    break;
+  case T_SHORT:
+    return NewString("short");
+    break;
+  case T_USHORT:
+    return NewString("unsigned short");
+    break;
+  case T_LONG:
+    return NewString("long");
+    break;
+  case T_ULONG:
+    return NewString("unsigned long");
+    break;
+  case T_FLOAT:
+    return NewString("float");
+    break;
+  case T_DOUBLE:
+    return NewString("double");
+    break;
+  case T_COMPLEX:
+    return NewString("complex");
+    break;
+  case T_CHAR:
+    return NewString("char");
+    break;
+  case T_SCHAR:
+    return NewString("signed char");
+    break;
+  case T_UCHAR:
+    return NewString("unsigned char");
+    break;
+  case T_STRING:{
+      SwigType *t = NewString("char");
+      SwigType_add_pointer(t);
+      return t;
+      break;
+    }
+  case T_LONGLONG:
+    return NewString("long long");
+    break;
+  case T_ULONGLONG:
+    return NewString("unsigned long long");
+    break;
+  case T_VOID:
+    return NewString("void");
+    break;
+  default:
+    break;
+  }
+  return NewStringEmpty();
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_push()
+ *
+ * Push a type constructor onto the type
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_push(SwigType *t, String *cons) {
+  if (!cons)
+    return;
+  if (!Len(cons))
+    return;
+
+  if (Len(t)) {
+    char *c = Char(cons);
+    if (c[strlen(c) - 1] != '.')
+      Insert(t, 0, ".");
+  }
+  Insert(t, 0, cons);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_ispointer_return()
+ *
+ * Testing functions for querying a raw datatype
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_ispointer_return(SwigType *t) {
+  char *c;
+  int idx;
+  if (!t)
+    return 0;
+  c = Char(t);
+  idx = strlen(c) - 4;
+  if (idx >= 0) {
+    return (strcmp(c + idx, ").p.") == 0);
+  }
+  return 0;
+}
+
+int SwigType_isreference_return(SwigType *t) {
+  char *c;
+  int idx;
+  if (!t)
+    return 0;
+  c = Char(t);
+  idx = strlen(c) - 4;
+  if (idx >= 0) {
+    return (strcmp(c + idx, ").r.") == 0);
+  }
+  return 0;
+}
+
+int SwigType_isconst(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  if (strncmp(c, "q(", 2) == 0) {
+    String *q = SwigType_parm(t);
+    if (strstr(Char(q), "const")) {
+      Delete(q);
+      return 1;
+    }
+    Delete(q);
+  }
+  /* Hmmm. Might be const through a typedef */
+  if (SwigType_issimple(t)) {
+    int ret;
+    SwigType *td = SwigType_typedef_resolve(t);
+    if (td) {
+      ret = SwigType_isconst(td);
+      Delete(td);
+      return ret;
+    }
+  }
+  return 0;
+}
+
+int SwigType_ismutable(SwigType *t) {
+  int r;
+  SwigType *qt = SwigType_typedef_resolve_all(t);
+  if (SwigType_isreference(qt) || SwigType_isarray(qt)) {
+    Delete(SwigType_pop(qt));
+  }
+  r = SwigType_isconst(qt);
+  Delete(qt);
+  return r ? 0 : 1;
+}
+
+int SwigType_isenum(SwigType *t) {
+  char *c = Char(t);
+  if (!t)
+    return 0;
+  if (strncmp(c, "enum ", 5) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+int SwigType_issimple(SwigType *t) {
+  char *c = Char(t);
+  if (!t)
+    return 0;
+  while (*c) {
+    if (*c == '<') {
+      int nest = 1;
+      c++;
+      while (*c && nest) {
+	if (*c == '<')
+	  nest++;
+	if (*c == '>')
+	  nest--;
+	c++;
+      }
+      c--;
+    }
+    if (*c == '.')
+      return 0;
+    c++;
+  }
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_default()
+ *
+ * Create the default string for this datatype.   This takes a type and strips it
+ * down to its most primitive form--resolving all typedefs and removing operators.
+ *
+ * Rules:
+ *     Pointers:      p.SWIGTYPE
+ *     References:    r.SWIGTYPE
+ *     Arrays:        a().SWIGTYPE
+ *     Types:         SWIGTYPE
+ *     MemberPointer: m(CLASS).SWIGTYPE
+ *     Enums:         enum SWIGTYPE
+ *
+ * Note: if this function is applied to a primitive type, it returns NULL.  This
+ * allows recursive application for special types like arrays.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef SWIG_DEFAULT_CACHE
+static Hash *default_cache = 0;
+#endif
+
+#define SWIG_NEW_TYPE_DEFAULT
+/* The new default type resolution method:
+
+1.- It preserves the original mixed types, then it goes 'backward'
+    first deleting the qualifier, then the inner types
+    
+    typedef A *Aptr;
+    const Aptr&;
+    r.q(const).Aptr       -> r.q(const).p.SWIGTYPE
+    r.q(const).p.SWIGTYPE -> r.p.SWIGTYPE
+    r.p.SWIGTYPE          -> r.SWIGTYPE
+    r.SWIGTYPE            -> SWIGTYPE
+
+
+    enum Hello {};
+    const Hello& hi;
+    r.q(const).Hello          -> r.q(const).enum SWIGTYPE
+    r.q(const).enum SWIGTYPE  -> r.enum SWIGTYPE
+    r.enum SWIGTYPE           -> r.SWIGTYPE
+    r.SWIGTYPE                -> SWIGTYPE
+
+    int a[2][4];
+    a(2).a(4).int           -> a(ANY).a(ANY).SWIGTYPE
+    a(ANY).a(ANY).SWIGTYPE  -> a(ANY).a().SWIGTYPE
+    a(ANY).a().SWIGTYPE     -> a(ANY).p.SWIGTYPE
+    a(ANY).p.SWIGTYPE       -> a(ANY).SWIGTYPE
+    a(ANY).SWIGTYPE         -> a().SWIGTYPE
+    a().SWIGTYPE            -> p.SWIGTYPE
+    p.SWIGTYPE              -> SWIGTYPE
+*/
+
+static
+void SwigType_add_default(String *def, SwigType *nr) {
+  if (Strcmp(nr, "SWIGTYPE") == 0) {
+    Append(def, "SWIGTYPE");
+  } else {
+    String *q = SwigType_isqualifier(nr) ? SwigType_pop(nr) : 0;
+    if (q && strstr(Char(nr), "SWIGTYPE")) {
+      Append(def, nr);
+    } else {
+      String *nd = SwigType_default(nr);
+      if (nd) {
+	String *bdef = nd;
+	if (q) {
+	  bdef = NewStringf("%s%s", q, nd);
+	  if ((Strcmp(nr, bdef) == 0)) {
+	    Delete(bdef);
+	    bdef = nd;
+	  } else {
+	    Delete(nd);
+	  }
+	}
+	Append(def, bdef);
+	Delete(bdef);
+      } else {
+	Append(def, nr);
+      }
+    }
+    Delete(q);
+  }
+}
+
+
+SwigType *SwigType_default(SwigType *t) {
+  String *r1, *def;
+  String *r = 0;
+  char *cr;
+
+#ifdef SWIG_DEFAULT_CACHE
+  if (!default_cache)
+    default_cache = NewHash();
+
+  r = Getattr(default_cache, t);
+  if (r) {
+    return Copy(r);
+  }
+#endif
+
+  if (SwigType_isvarargs(t)) {
+    return 0;
+  }
+
+  r = t;
+  while ((r1 = SwigType_typedef_resolve(r))) {
+    if (r != t)
+      Delete(r);
+    r = r1;
+  }
+  if (SwigType_isqualifier(r)) {
+    String *q;
+    if (r == t)
+      r = Copy(t);
+    q = SwigType_pop(r);
+    if (strstr(Char(r), "SWIGTYPE")) {
+      Delete(q);
+      def = r;
+      return def;
+    }
+    Delete(q);
+  }
+  cr = Char(r);
+  if (strcmp(cr, "p.SWIGTYPE") == 0) {
+    def = NewString("SWIGTYPE");
+  } else if (SwigType_ispointer(r)) {
+#ifdef SWIG_NEW_TYPE_DEFAULT
+    SwigType *nr = Copy(r);
+    SwigType_del_pointer(nr);
+    def = SwigType_isfunction(nr) ? NewStringEmpty() : NewString("p.");
+    SwigType_add_default(def, nr);
+    Delete(nr);
+#else
+    def = NewString("p.SWIGTYPE");
+#endif
+  } else if (strcmp(cr, "r.SWIGTYPE") == 0) {
+    def = NewString("SWIGTYPE");
+  } else if (SwigType_isreference(r)) {
+#ifdef SWIG_NEW_TYPE_DEFAULT
+    SwigType *nr = Copy(r);
+    SwigType_del_reference(nr);
+    def = NewString("r.");
+    SwigType_add_default(def, nr);
+    Delete(nr);
+#else
+    def = NewString("r.SWIGTYPE");
+#endif
+  } else if (SwigType_isarray(r)) {
+    if (strcmp(cr, "a().SWIGTYPE") == 0) {
+      def = NewString("p.SWIGTYPE");
+    } else if (strcmp(cr, "a(ANY).SWIGTYPE") == 0) {
+      def = NewString("a().SWIGTYPE");
+    } else {
+      int i, empty = 0;
+      int ndim = SwigType_array_ndim(r);
+      SwigType *nr = Copy(r);
+      for (i = 0; i < ndim; i++) {
+	String *dim = SwigType_array_getdim(r, i);
+	if (!Len(dim)) {
+	  char *c = Char(nr);
+	  empty = strstr(c, "a(ANY).") != c;
+	}
+	Delete(dim);
+      }
+      if (empty) {
+	def = NewString("a().");
+      } else {
+	def = NewString("a(ANY).");
+      }
+#ifdef SWIG_NEW_TYPE_DEFAULT
+      SwigType_del_array(nr);
+      SwigType_add_default(def, nr);
+#else
+      Append(def, "SWIGTYPE");
+#endif
+      Delete(nr);
+    }
+  } else if (SwigType_ismemberpointer(r)) {
+    if (strcmp(cr, "m(CLASS).SWIGTYPE") == 0) {
+      def = NewString("p.SWIGTYPE");
+    } else {
+      def = NewString("m(CLASS).SWIGTYPE");
+    }
+  } else if (SwigType_isenum(r)) {
+    if (strcmp(cr, "enum SWIGTYPE") == 0) {
+      def = NewString("SWIGTYPE");
+    } else {
+      def = NewString("enum SWIGTYPE");
+    }
+  } else if (SwigType_isfunction(r)) {
+    if (strcmp(cr, "f(ANY).SWIGTYPE") == 0) {
+      def = NewString("p.SWIGTYPE");
+    } else {
+      def = NewString("p.f(ANY).SWIGTYPE");
+    }
+  } else {
+    def = NewString("SWIGTYPE");
+  }
+  if (r != t)
+    Delete(r);
+  if (Equal(def, t)) {
+    Delete(def);
+    def = 0;
+  }
+#ifdef SWIG_DEFAULT_CACHE
+  /* The cache produces strange results, see enum_template.i case */
+  if (def) {
+    String *cdef = Copy(def);
+    Setattr(default_cache, t, cdef);
+    Delete(cdef);
+  }
+#endif
+
+  /* Printf(stderr,"type : def %s : %s\n", t, def);  */
+
+  return def;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_namestr()
+ *
+ * Returns a string of the base type.  Takes care of template expansions
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_namestr(const SwigType *t) {
+  String *r;
+  String *suffix;
+  List *p;
+  int i, sz;
+  char *d = Char(t);
+  char *c = strstr(d, "<(");
+
+  if (!c || !strstr(c + 2, ")>"))
+    return NewString(t);
+
+  r = NewStringWithSize(d, c - d);
+  if (*(c - 1) == '<')
+    Putc(' ', r);
+  Putc('<', r);
+
+  p = SwigType_parmlist(c + 1);
+  sz = Len(p);
+  for (i = 0; i < sz; i++) {
+    String *str = SwigType_str(Getitem(p, i), 0);
+    /* Avoid creating a <: token, which is the same as [ in C++ - put a space after '<'. */
+    if (i == 0 && Len(str))
+      Putc(' ', r);
+    Append(r, str);
+    if ((i + 1) < sz)
+      Putc(',', r);
+    Delete(str);
+  }
+  Putc(' ', r);
+  Putc('>', r);
+  suffix = SwigType_templatesuffix(t);
+  Append(r, suffix);
+  Delete(suffix);
+  Delete(p);
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_str()
+ *
+ * Create a C string representation of a datatype.
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_str(SwigType *s, const String_or_char *id) {
+  String *result;
+  String *element = 0, *nextelement;
+  List *elements;
+  int nelements, i;
+
+  if (id) {
+    result = NewString(id);
+  } else {
+    result = NewStringEmpty();
+  }
+
+  elements = SwigType_split(s);
+  nelements = Len(elements);
+
+  if (nelements > 0) {
+    element = Getitem(elements, 0);
+  }
+  /* Now, walk the type list and start emitting */
+  for (i = 0; i < nelements; i++) {
+    if (i < (nelements - 1)) {
+      nextelement = Getitem(elements, i + 1);
+    } else {
+      nextelement = 0;
+    }
+    if (SwigType_isqualifier(element)) {
+      DOH *q = 0;
+      q = SwigType_parm(element);
+      Insert(result, 0, " ");
+      Insert(result, 0, q);
+      Delete(q);
+    } else if (SwigType_ispointer(element)) {
+      Insert(result, 0, "*");
+      if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	Insert(result, 0, "(");
+	Append(result, ")");
+      }
+    } else if (SwigType_ismemberpointer(element)) {
+      String *q;
+      q = SwigType_parm(element);
+      Insert(result, 0, "::*");
+      Insert(result, 0, q);
+      if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	Insert(result, 0, "(");
+	Append(result, ")");
+      }
+      Delete(q);
+    } else if (SwigType_isreference(element)) {
+      Insert(result, 0, "&");
+      if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	Insert(result, 0, "(");
+	Append(result, ")");
+      }
+    } else if (SwigType_isarray(element)) {
+      DOH *size;
+      Append(result, "[");
+      size = SwigType_parm(element);
+      Append(result, size);
+      Append(result, "]");
+      Delete(size);
+    } else if (SwigType_isfunction(element)) {
+      DOH *parms, *p;
+      int j, plen;
+      Append(result, "(");
+      parms = SwigType_parmlist(element);
+      plen = Len(parms);
+      for (j = 0; j < plen; j++) {
+	p = SwigType_str(Getitem(parms, j), 0);
+	Append(result, p);
+	if (j < (plen - 1))
+	  Append(result, ",");
+      }
+      Append(result, ")");
+      Delete(parms);
+    } else {
+      if (strcmp(Char(element), "v(...)") == 0) {
+	Insert(result, 0, "...");
+      } else {
+	String *bs = SwigType_namestr(element);
+	Insert(result, 0, " ");
+	Insert(result, 0, bs);
+	Delete(bs);
+      }
+    }
+    element = nextelement;
+  }
+  Delete(elements);
+  Chop(result);
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_ltype(SwigType *ty)
+ *
+ * Create a locally assignable type
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_ltype(SwigType *s) {
+  String *result;
+  String *element;
+  SwigType *td, *tc = 0;
+  List *elements;
+  int nelements, i;
+  int firstarray = 1;
+  int notypeconv = 0;
+
+  result = NewStringEmpty();
+  tc = Copy(s);
+  /* Nuke all leading qualifiers */
+  while (SwigType_isqualifier(tc)) {
+    Delete(SwigType_pop(tc));
+  }
+  if (SwigType_issimple(tc)) {
+    /* Resolve any typedef definitions */
+    SwigType *tt = Copy(tc);
+    td = 0;
+    while ((td = SwigType_typedef_resolve(tt))) {
+      if (td && (SwigType_isconst(td) || SwigType_isarray(td) || SwigType_isreference(td))) {
+	/* We need to use the typedef type */
+	Delete(tt);
+	tt = td;
+	break;
+      } else if (td) {
+	Delete(tt);
+	tt = td;
+      }
+    }
+    if (td) {
+      Delete(tc);
+      tc = td;
+    }
+  }
+  elements = SwigType_split(tc);
+  nelements = Len(elements);
+
+  /* Now, walk the type list and start emitting */
+  for (i = 0; i < nelements; i++) {
+    element = Getitem(elements, i);
+    /* when we see a function, we need to preserve the following types */
+    if (SwigType_isfunction(element)) {
+      notypeconv = 1;
+    }
+    if (SwigType_isqualifier(element)) {
+      /* Do nothing. Ignore */
+    } else if (SwigType_ispointer(element)) {
+      Append(result, element);
+      firstarray = 0;
+    } else if (SwigType_ismemberpointer(element)) {
+      Append(result, element);
+      firstarray = 0;
+    } else if (SwigType_isreference(element)) {
+      if (notypeconv) {
+	Append(result, element);
+      } else {
+	Append(result, "p.");
+      }
+      firstarray = 0;
+    } else if (SwigType_isarray(element) && firstarray) {
+      if (notypeconv) {
+	Append(result, element);
+      } else {
+	Append(result, "p.");
+      }
+      firstarray = 0;
+    } else if (SwigType_isenum(element)) {
+      int anonymous_enum = (Cmp(element, "enum ") == 0);
+      if (notypeconv || !anonymous_enum) {
+	Append(result, element);
+      } else {
+	Append(result, "int");
+      }
+    } else {
+      Append(result, element);
+    }
+  }
+  Delete(elements);
+  Delete(tc);
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_lstr(DOH *s, DOH *id)
+ *
+ * Produces a type-string that is suitable as a lvalue in an expression.
+ * That is, a type that can be freely assigned a value without violating
+ * any C assignment rules.
+ *
+ *      -   Qualifiers such as 'const' and 'volatile' are stripped.
+ *      -   Arrays are converted into a *single* pointer (i.e.,
+ *          double [][] becomes double *).
+ *      -   References are converted into a pointer.
+ *      -   Typedef names that refer to read-only types will be replaced
+ *          with an equivalent assignable version.
+ * -------------------------------------------------------------------- */
+
+String *SwigType_lstr(SwigType *s, const String_or_char *id) {
+  String *result;
+  SwigType *tc;
+
+  tc = SwigType_ltype(s);
+  result = SwigType_str(tc, id);
+  Delete(tc);
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_rcaststr()
+ *
+ * Produces a casting string that maps the type returned by lstr() to the real 
+ * datatype printed by str().
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_rcaststr(SwigType *s, const String_or_char *name) {
+  String *result, *cast;
+  String *element = 0, *nextelement;
+  SwigType *td, *rs, *tc = 0;
+  List *elements;
+  int nelements, i;
+  int clear = 1;
+  int firstarray = 1;
+  int isreference = 0;
+  int isarray = 0;
+
+  result = NewStringEmpty();
+
+  if (SwigType_isconst(s)) {
+    tc = Copy(s);
+    Delete(SwigType_pop(tc));
+    rs = tc;
+  } else {
+    rs = s;
+  }
+
+  if ((SwigType_isconst(rs) || SwigType_isarray(rs) || SwigType_isreference(rs))) {
+    td = 0;
+  } else {
+    td = SwigType_typedef_resolve(rs);
+  }
+
+  if (td) {
+    if ((SwigType_isconst(td) || SwigType_isarray(td) || SwigType_isreference(td))) {
+      elements = SwigType_split(td);
+    } else {
+      elements = SwigType_split(rs);
+    }
+    Delete(td);
+  } else {
+    elements = SwigType_split(rs);
+  }
+  nelements = Len(elements);
+  if (nelements > 0) {
+    element = Getitem(elements, 0);
+  }
+  /* Now, walk the type list and start emitting */
+  for (i = 0; i < nelements; i++) {
+    if (i < (nelements - 1)) {
+      nextelement = Getitem(elements, i + 1);
+    } else {
+      nextelement = 0;
+    }
+    if (SwigType_isqualifier(element)) {
+      DOH *q = 0;
+      q = SwigType_parm(element);
+      Insert(result, 0, " ");
+      Insert(result, 0, q);
+      Delete(q);
+      clear = 0;
+    } else if (SwigType_ispointer(element)) {
+      Insert(result, 0, "*");
+      if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	Insert(result, 0, "(");
+	Append(result, ")");
+      }
+      firstarray = 0;
+    } else if (SwigType_ismemberpointer(element)) {
+      String *q;
+      Insert(result, 0, "::*");
+      q = SwigType_parm(element);
+      Insert(result, 0, q);
+      Delete(q);
+      if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	Insert(result, 0, "(");
+	Append(result, ")");
+      }
+      firstarray = 0;
+    } else if (SwigType_isreference(element)) {
+      Insert(result, 0, "&");
+      if ((nextelement) && ((SwigType_isfunction(nextelement) || (SwigType_isarray(nextelement))))) {
+	Insert(result, 0, "(");
+	Append(result, ")");
+      }
+      isreference = 1;
+    } else if (SwigType_isarray(element)) {
+      DOH *size;
+      if (firstarray && !isreference) {
+	Append(result, "(*)");
+	firstarray = 0;
+      } else {
+	Append(result, "[");
+	size = SwigType_parm(element);
+	Append(result, size);
+	Append(result, "]");
+	Delete(size);
+	clear = 0;
+      }
+      isarray = 1;
+    } else if (SwigType_isfunction(element)) {
+      DOH *parms, *p;
+      int j, plen;
+      Append(result, "(");
+      parms = SwigType_parmlist(element);
+      plen = Len(parms);
+      for (j = 0; j < plen; j++) {
+	p = SwigType_str(Getitem(parms, j), 0);
+	Append(result, p);
+	Delete(p);
+	if (j < (plen - 1))
+	  Append(result, ",");
+      }
+      Append(result, ")");
+      Delete(parms);
+    } else {
+      String *bs = SwigType_namestr(element);
+      Insert(result, 0, " ");
+      Insert(result, 0, bs);
+      Delete(bs);
+    }
+    element = nextelement;
+  }
+  Delete(elements);
+  if (clear) {
+    cast = NewStringEmpty();
+  } else {
+    cast = NewStringf("(%s)", result);
+  }
+  if (name) {
+    if (isreference) {
+      if (isarray)
+	Clear(cast);
+      Append(cast, "*");
+    }
+    Append(cast, name);
+  }
+  Delete(result);
+  Delete(tc);
+  return cast;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_lcaststr()
+ *
+ * Casts a variable from the real type to the local datatype.
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_lcaststr(SwigType *s, const String_or_char *name) {
+  String *result;
+
+  result = NewStringEmpty();
+
+  if (SwigType_isarray(s)) {
+    String *lstr = SwigType_lstr(s, 0);
+    Printf(result, "(%s)%s", lstr, name);
+    Delete(lstr);
+  } else if (SwigType_isreference(s)) {
+    String *str = SwigType_str(s, 0);
+    Printf(result, "(%s)", str);
+    Delete(str);
+    if (name)
+      Append(result, name);
+  } else if (SwigType_isqualifier(s)) {
+    String *lstr = SwigType_lstr(s, 0);
+    Printf(result, "(%s)%s", lstr, name);
+    Delete(lstr);
+  } else {
+    if (name)
+      Append(result, name);
+  }
+  return result;
+}
+
+
+/* keep old mangling since Java codes need it */
+String *SwigType_manglestr_default(SwigType *s) {
+  char *c;
+  String *result = 0;
+  String *base = 0;
+  SwigType *lt;
+  SwigType *sr = SwigType_typedef_qualified(s);
+  SwigType *ss = SwigType_typedef_resolve_all(sr);
+
+  s = ss;
+
+  if (SwigType_istemplate(ss)) {
+    SwigType *ty = Swig_symbol_template_deftype(ss, 0);
+    Delete(ss);
+    ss = ty;
+    s = ss;
+  }
+  Delete(sr);
+
+  lt = SwigType_ltype(s);
+  result = SwigType_prefix(lt);
+  base = SwigType_base(lt);
+
+  c = Char(result);
+  while (*c) {
+    if (!isalnum((int) *c))
+      *c = '_';
+    c++;
+  }
+  if (SwigType_istemplate(base)) {
+    String *b = SwigType_namestr(base);
+    Delete(base);
+    base = b;
+  }
+
+  Replace(base, "struct ", "", DOH_REPLACE_ANY);	/* This might be problematic */
+  Replace(base, "class ", "", DOH_REPLACE_ANY);
+  Replace(base, "union ", "", DOH_REPLACE_ANY);
+  Replace(base, "enum ", "", DOH_REPLACE_ANY);
+
+  c = Char(base);
+  while (*c) {
+    if (*c == '<')
+      *c = 'T';
+    else if (*c == '>')
+      *c = 't';
+    else if (*c == '*')
+      *c = 'p';
+    else if (*c == '[')
+      *c = 'a';
+    else if (*c == ']')
+      *c = 'A';
+    else if (*c == '&')
+      *c = 'R';
+    else if (*c == '(')
+      *c = 'f';
+    else if (*c == ')')
+      *c = 'F';
+    else if (!isalnum((int) *c))
+      *c = '_';
+    c++;
+  }
+  Append(result, base);
+  Insert(result, 0, "_");
+  Delete(lt);
+  Delete(base);
+  if (ss)
+    Delete(ss);
+  return result;
+}
+
+String *SwigType_manglestr(SwigType *s) {
+  return SwigType_manglestr_default(s);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_typename_replace()
+ *
+ * Replaces a typename in a type with something else.  Needed for templates.
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_typename_replace(SwigType *t, String *pat, String *rep) {
+  String *nt;
+  int i, ilen;
+  List *elem;
+
+  if (!Strstr(t, pat))
+    return;
+
+  if (Equal(t, pat)) {
+    Replace(t, pat, rep, DOH_REPLACE_ANY);
+    return;
+  }
+  nt = NewStringEmpty();
+  elem = SwigType_split(t);
+  ilen = Len(elem);
+  for (i = 0; i < ilen; i++) {
+    String *e = Getitem(elem, i);
+    if (SwigType_issimple(e)) {
+      if (Equal(e, pat)) {
+	/* Replaces a type of the form 'pat' with 'rep<args>' */
+	Replace(e, pat, rep, DOH_REPLACE_ANY);
+      } else if (SwigType_istemplate(e)) {
+	/* Replaces a type of the form 'pat<args>' with 'rep' */
+	if (Equal(e, pat)) {
+	  String *repbase = SwigType_templateprefix(rep);
+	  Replace(e, pat, repbase, DOH_REPLACE_ID | DOH_REPLACE_FIRST);
+	  Delete(repbase);
+	}
+	{
+	  String *tsuffix;
+	  List *tparms = SwigType_parmlist(e);
+	  int j, jlen;
+	  String *nt = SwigType_templateprefix(e);
+	  Append(nt, "<(");
+	  jlen = Len(tparms);
+	  for (j = 0; j < jlen; j++) {
+	    SwigType_typename_replace(Getitem(tparms, j), pat, rep);
+	    Append(nt, Getitem(tparms, j));
+	    if (j < (jlen - 1))
+	      Putc(',', nt);
+	  }
+	  tsuffix = SwigType_templatesuffix(e);
+	  Printf(nt, ")>%s", tsuffix);
+	  Delete(tsuffix);
+	  Clear(e);
+	  Append(e, nt);
+	  Delete(nt);
+	  Delete(tparms);
+	}
+      } else if (Swig_scopename_check(e)) {
+	String *first, *rest;
+	first = Swig_scopename_first(e);
+	rest = Swig_scopename_suffix(e);
+	SwigType_typename_replace(rest, pat, rep);
+	SwigType_typename_replace(first, pat, rep);
+	Clear(e);
+	Printv(e, first, "::", rest, NIL);
+	Delete(first);
+	Delete(rest);
+      }
+    } else if (SwigType_isfunction(e)) {
+      int j, jlen;
+      List *fparms = SwigType_parmlist(e);
+      Clear(e);
+      Append(e, "f(");
+      jlen = Len(fparms);
+      for (j = 0; j < jlen; j++) {
+	SwigType_typename_replace(Getitem(fparms, j), pat, rep);
+	Append(e, Getitem(fparms, j));
+	if (j < (jlen - 1))
+	  Putc(',', e);
+      }
+      Append(e, ").");
+      Delete(fparms);
+    } else if (SwigType_isarray(e)) {
+      Replace(e, pat, rep, DOH_REPLACE_ID);
+    }
+    Append(nt, e);
+  }
+  Clear(t);
+  Append(t, nt);
+  Delete(nt);
+  Delete(elem);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_check_decl()
+ *
+ * Checks type declarators for a match
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_check_decl(SwigType *ty, const SwigType *decl) {
+  SwigType *t, *t1, *t2;
+  int r;
+  t = SwigType_typedef_resolve_all(ty);
+  t1 = SwigType_strip_qualifiers(t);
+  t2 = SwigType_prefix(t1);
+  r = Equal(t2, decl);
+  Delete(t);
+  Delete(t1);
+  Delete(t2);
+  return r == 1;
+}
diff --git a/trunk/Source/Swig/swig.h b/trunk/Source/Swig/swig.h
new file mode 100644
index 0000000..451de86
--- /dev/null
+++ b/trunk/Source/Swig/swig.h
@@ -0,0 +1,402 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swig.h
+ *
+ * Header file for the SWIG core.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id$ */
+
+#ifndef SWIGCORE_H_
+#define SWIGCORE_H_
+
+#ifndef MACSWIG
+#include "swigconfig.h"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "doh.h"
+
+/* Status codes */
+
+#define SWIG_OK         1
+#define SWIG_ERROR      0
+#define SWIG_NOWRAP     0
+
+/* Short names for common data types */
+
+  typedef DOH String;
+  typedef DOH Hash;
+  typedef DOH List;
+  typedef DOH String_or_char;
+  typedef DOH File;
+  typedef DOH Parm;
+  typedef DOH ParmList;
+  typedef DOH Node;
+  typedef DOH Symtab;
+  typedef DOH Typetab;
+  typedef DOH SwigType;
+
+/* --- Legacy DataType interface.  These type codes are provided solely 
+       for backwards compatibility with older modules --- */
+
+/* --- The ordering of type values is used to determine type-promotion 
+       in the parser.  Do not change */
+
+/* Numeric types */
+
+#define   T_BOOL       1
+#define   T_SCHAR      2
+#define   T_UCHAR      3
+#define   T_SHORT      4
+#define   T_USHORT     5
+#define   T_ENUM       6
+#define   T_INT        7
+#define   T_UINT       8
+#define   T_LONG       9
+#define   T_ULONG      10
+#define   T_LONGLONG   11
+#define   T_ULONGLONG  12
+#define   T_FLOAT      20
+#define   T_DOUBLE     21
+#define   T_LONGDOUBLE 22
+#define   T_FLTCPLX    23
+#define   T_DBLCPLX    24
+#define   T_NUMERIC    25
+
+#define   T_COMPLEX    T_DBLCPLX
+
+/* non-numeric */
+
+#define   T_CHAR       29
+#define   T_WCHAR      30
+#define   T_USER       31
+#define   T_VOID       32
+#define   T_STRING     33
+#define   T_POINTER    34
+#define   T_REFERENCE  35
+#define   T_ARRAY      36
+#define   T_FUNCTION   37
+#define   T_MPOINTER   38
+#define   T_VARARGS    39
+#define   T_SYMBOL     98
+#define   T_ERROR      99
+
+
+/* --- File interface --- */
+
+#include "swigfile.h"
+
+/* --- Command line parsing --- */
+
+#include "swigopt.h"
+
+/* --- Scanner Interface --- */
+
+#include "swigscan.h"
+
+/* --- Functions for manipulating the string-based type encoding --- */
+
+  extern SwigType *NewSwigType(int typecode);
+  extern SwigType *SwigType_del_element(SwigType *t);
+  extern SwigType *SwigType_add_pointer(SwigType *t);
+  extern SwigType *SwigType_add_memberpointer(SwigType *t, const String_or_char *qual);
+  extern SwigType *SwigType_del_memberpointer(SwigType *t);
+  extern SwigType *SwigType_del_pointer(SwigType *t);
+  extern SwigType *SwigType_add_array(SwigType *t, const String_or_char *size);
+  extern SwigType *SwigType_del_array(SwigType *t);
+  extern SwigType *SwigType_pop_arrays(SwigType *t);
+  extern SwigType *SwigType_add_reference(SwigType *t);
+  extern SwigType *SwigType_del_reference(SwigType *t);
+  extern SwigType *SwigType_add_qualifier(SwigType *t, const String_or_char *qual);
+  extern SwigType *SwigType_del_qualifier(SwigType *t);
+  extern SwigType *SwigType_add_function(SwigType *t, ParmList *parms);
+  extern SwigType *SwigType_add_template(SwigType *t, ParmList *parms);
+  extern SwigType *SwigType_pop_function(SwigType *t);
+  extern ParmList *SwigType_function_parms(SwigType *t);
+  extern List *SwigType_split(const SwigType *t);
+  extern String *SwigType_pop(SwigType *t);
+  extern void SwigType_push(SwigType *t, SwigType *s);
+  extern List *SwigType_parmlist(const SwigType *p);
+  extern String *SwigType_parm(String *p);
+  extern String *SwigType_str(SwigType *s, const String_or_char *id);
+  extern String *SwigType_lstr(SwigType *s, const String_or_char *id);
+  extern String *SwigType_rcaststr(SwigType *s, const String_or_char *id);
+  extern String *SwigType_lcaststr(SwigType *s, const String_or_char *id);
+  extern String *SwigType_manglestr(SwigType *t);
+  extern SwigType *SwigType_ltype(SwigType *t);
+  extern int SwigType_ispointer(SwigType *t);
+  extern int SwigType_ispointer_return(SwigType *t);
+  extern int SwigType_isfunctionpointer(SwigType *t);
+  extern int SwigType_ismemberpointer(SwigType *t);
+  extern int SwigType_isreference(SwigType *t);
+  extern int SwigType_isreference_return(SwigType *t);
+  extern int SwigType_isarray(SwigType *t);
+  extern int SwigType_prefix_is_simple_1D_array(SwigType *t);
+  extern int SwigType_isfunction(SwigType *t);
+  extern int SwigType_isqualifier(SwigType *t);
+  extern int SwigType_isconst(SwigType *t);
+  extern int SwigType_issimple(SwigType *t);
+  extern int SwigType_ismutable(SwigType *t);
+  extern int SwigType_isvarargs(const SwigType *t);
+  extern int SwigType_istemplate(const SwigType *t);
+  extern int SwigType_isenum(SwigType *t);
+  extern int SwigType_check_decl(SwigType *t, const String_or_char *decl);
+  extern SwigType *SwigType_strip_qualifiers(SwigType *t);
+  extern SwigType *SwigType_functionpointer_decompose(SwigType *t);
+  extern String *SwigType_base(const SwigType *t);
+  extern String *SwigType_namestr(const SwigType *t);
+  extern String *SwigType_templateprefix(const SwigType *t);
+  extern String *SwigType_templatesuffix(const SwigType *t);
+  extern String *SwigType_templateargs(const SwigType *t);
+  extern String *SwigType_prefix(const SwigType *t);
+  extern int SwigType_array_ndim(SwigType *t);
+  extern String *SwigType_array_getdim(SwigType *t, int n);
+  extern void SwigType_array_setdim(SwigType *t, int n, const String_or_char *rep);
+  extern SwigType *SwigType_array_type(SwigType *t);
+  extern String *SwigType_default(SwigType *t);
+  extern void SwigType_typename_replace(SwigType *t, String *pat, String *rep);
+  extern SwigType *SwigType_alttype(SwigType *t, int ltmap);
+
+  extern void SwigType_template_defargs(Parm *parms, Parm *targs, Symtab *tscope, Symtab *tsdecl);
+  extern SwigType *SwigType_template_deftype(const SwigType *type, Symtab *tscope);
+
+/* --- Type-system managment --- */
+  extern void SwigType_typesystem_init(void);
+  extern int SwigType_typedef(SwigType *type, String_or_char *name);
+  extern int SwigType_typedef_class(String_or_char *name);
+  extern int SwigType_typedef_using(String_or_char *qname);
+  extern void SwigType_inherit(String *subclass, String *baseclass, String *cast, String *conversioncode);
+  extern int SwigType_issubtype(SwigType *subtype, SwigType *basetype);
+  extern void SwigType_scope_alias(String *aliasname, Typetab *t);
+  extern void SwigType_using_scope(Typetab *t);
+  extern void SwigType_new_scope(const String_or_char *name);
+  extern void SwigType_inherit_scope(Typetab *scope);
+  extern Typetab *SwigType_pop_scope(void);
+  extern Typetab *SwigType_set_scope(Typetab *h);
+  extern void SwigType_print_scope(Typetab *t);
+  extern SwigType *SwigType_typedef_resolve(SwigType *t);
+  extern SwigType *SwigType_typedef_resolve_all(SwigType *t);
+  extern SwigType *SwigType_typedef_qualified(SwigType *t);
+  extern int SwigType_istypedef(SwigType *t);
+  extern int SwigType_isclass(SwigType *t);
+  extern void SwigType_attach_symtab(Symtab *syms);
+  extern void SwigType_remember(SwigType *t);
+  extern void SwigType_remember_clientdata(SwigType *t, const String_or_char *clientdata);
+  extern void SwigType_remember_mangleddata(String *mangled, const String_or_char *clientdata);
+  extern void (*SwigType_remember_trace(void (*tf) (SwigType *, String *, String *))) (SwigType *, String *, String *);
+  extern void SwigType_emit_type_table(File *f_headers, File *f_table);
+  extern int SwigType_type(SwigType *t);
+
+/* --- Symbol table module --- */
+
+  extern void Swig_symbol_init(void);
+  extern void Swig_symbol_setscopename(const String_or_char *name);
+  extern String *Swig_symbol_getscopename(void);
+  extern String *Swig_symbol_qualifiedscopename(Symtab *symtab);
+  extern Symtab *Swig_symbol_newscope(void);
+  extern Symtab *Swig_symbol_setscope(Symtab *);
+  extern Symtab *Swig_symbol_getscope(const String_or_char *symname);
+  extern Symtab *Swig_symbol_current(void);
+  extern Symtab *Swig_symbol_popscope(void);
+  extern Node *Swig_symbol_add(String_or_char *symname, Node *node);
+  extern void Swig_symbol_cadd(String_or_char *symname, Node *node);
+  extern Node *Swig_symbol_clookup(String_or_char *symname, Symtab *tab);
+  extern Node *Swig_symbol_clookup_check(String_or_char *symname, Symtab *tab, int (*check) (Node *));
+  extern Symtab *Swig_symbol_cscope(String_or_char *symname, Symtab *tab);
+  extern Node *Swig_symbol_clookup_local(String_or_char *symname, Symtab *tab);
+  extern Node *Swig_symbol_clookup_local_check(String_or_char *symname, Symtab *tab, int (*check) (Node *));
+  extern String *Swig_symbol_qualified(Node *node);
+  extern Node *Swig_symbol_isoverloaded(Node *node);
+  extern void Swig_symbol_remove(Node *node);
+  extern void Swig_symbol_alias(String_or_char *aliasname, Symtab *tab);
+  extern void Swig_symbol_inherit(Symtab *tab);
+  extern SwigType *Swig_symbol_type_qualify(const SwigType *ty, Symtab *tab);
+  extern String *Swig_symbol_string_qualify(String *s, Symtab *tab);
+  extern SwigType *Swig_symbol_typedef_reduce(SwigType *ty, Symtab *tab);
+
+  extern ParmList *Swig_symbol_template_defargs(Parm *parms, Parm *targs, Symtab *tscope, Symtab *tsdecl);
+  extern SwigType *Swig_symbol_template_deftype(const SwigType *type, Symtab *tscope);
+  extern SwigType *Swig_symbol_template_param_eval(const SwigType *p, Symtab *symtab);
+
+/* --- Parameters and Parameter Lists --- */
+
+#include "swigparm.h"
+
+extern String    *ParmList_errorstr(ParmList *);
+extern int        ParmList_is_compactdefargs(ParmList *p);
+
+/* --- Parse tree support --- */
+
+#include "swigtree.h"
+
+/* -- Wrapper function Object */
+
+#include "swigwrap.h"
+
+/* --- Naming functions --- */
+
+  extern void Swig_name_register(const String_or_char *method, const String_or_char *format);
+  extern void Swig_name_unregister(const String_or_char *method);
+  extern String *Swig_name_mangle(const String_or_char *s);
+  extern String *Swig_name_wrapper(const String_or_char *fname);
+  extern String *Swig_name_member(const String_or_char *classname, const String_or_char *mname);
+  extern String *Swig_name_get(const String_or_char *vname);
+  extern String *Swig_name_set(const String_or_char *vname);
+  extern String *Swig_name_construct(const String_or_char *classname);
+  extern String *Swig_name_copyconstructor(const String_or_char *classname);
+  extern String *Swig_name_destroy(const String_or_char *classname);
+  extern String *Swig_name_disown(const String_or_char *classname);
+
+  extern void Swig_naming_init(void);
+  extern void Swig_name_namewarn_add(String *prefix, String *name, SwigType *decl, Hash *namewrn);
+  extern Hash *Swig_name_namewarn_get(Node *n, String *prefix, String *name, SwigType *decl);
+  extern void Swig_name_rename_add(String *prefix, String *name, SwigType *decl, Hash *namewrn, ParmList *declaratorparms);
+  extern void Swig_name_inherit(String *base, String *derived);
+  extern int Swig_need_protected(Node *n);
+  extern int Swig_need_name_warning(Node *n);
+  extern int Swig_need_redefined_warn(Node *a, Node *b, int InClass);
+
+  extern String *Swig_name_make(Node *n, String *prefix, String_or_char *cname, SwigType *decl, String *oldname);
+  extern String *Swig_name_warning(Node *n, String *prefix, String *name, SwigType *decl);
+  extern String *Swig_name_decl(Node *n);
+  extern String *Swig_name_fulldecl(Node *n);
+
+/* --- parameterized rename functions --- */
+
+  extern void Swig_name_object_set(Hash *namehash, String_or_char *name, SwigType *decl, DOH *object);
+  extern DOH *Swig_name_object_get(Hash *namehash, String_or_char *prefix, String_or_char *name, SwigType *decl);
+  extern void Swig_name_object_inherit(Hash *namehash, String *base, String *derived);
+  extern void Swig_features_get(Hash *features, String_or_char *prefix, String_or_char *name, SwigType *decl, Node *n);
+  extern void Swig_feature_set(Hash *features, const String_or_char *name, SwigType *decl, const String_or_char *featurename, String *value, Hash *featureattribs);
+
+/* --- Misc --- */
+  extern char *Swig_copy_string(const char *c);
+  extern void Swig_set_fakeversion(const char *version);
+  extern const char *Swig_package_version(void);
+  extern void Swig_banner(File *f);
+  extern String *Swig_strip_c_comments(const String *s);
+  extern String *Swig_string_escape(String *s);
+  extern String *Swig_string_mangle(const String *s);
+  extern void Swig_scopename_split(String *s, String **prefix, String **last);
+  extern String *Swig_scopename_prefix(String *s);
+  extern String *Swig_scopename_last(String *s);
+  extern String *Swig_scopename_first(String *s);
+  extern String *Swig_scopename_suffix(String *s);
+  extern int Swig_scopename_check(String *s);
+  extern String *Swig_string_lower(String *s);
+  extern String *Swig_string_upper(String *s);
+  extern String *Swig_string_title(String *s);
+
+  extern void Swig_init(void);
+  extern void Swig_warn(const char *filename, int line, const char *msg);
+
+  extern int Swig_value_wrapper_mode(int mode);
+
+
+#define WARNING(msg) Swig_warn(__FILE__,__LINE__,msg)
+
+  typedef enum { EMF_STANDARD, EMF_MICROSOFT } ErrorMessageFormat;
+
+  extern void Swig_warning(int num, const String_or_char *filename, int line, const char *fmt, ...);
+  extern void Swig_error(const String_or_char *filename, int line, const char *fmt, ...);
+  extern int Swig_error_count(void);
+  extern void Swig_error_silent(int s);
+  extern void Swig_warnfilter(const String_or_char *wlist, int val);
+  extern void Swig_warnall(void);
+  extern int Swig_warn_count(void);
+  extern void Swig_error_msg_format(ErrorMessageFormat format);
+
+/* --- C Wrappers --- */
+  extern String *Swig_cparm_name(Parm *p, int i);
+  extern String *Swig_wrapped_var_type(SwigType *t, int varcref);
+  extern int Swig_cargs(Wrapper *w, ParmList *l);
+  extern String *Swig_cresult(SwigType *t, const String_or_char *name, const String_or_char *decl);
+
+  extern String *Swig_cfunction_call(String_or_char *name, ParmList *parms);
+  extern String *Swig_cconstructor_call(String_or_char *name);
+  extern String *Swig_cppconstructor_call(String_or_char *name, ParmList *parms);
+  extern String *Swig_unref_call(Node *n);
+  extern String *Swig_ref_call(Node *n, const String *lname);
+  extern String *Swig_cdestructor_call(Node *n);
+  extern String *Swig_cppdestructor_call(Node *n);
+  extern String *Swig_cmemberset_call(String_or_char *name, SwigType *type, String_or_char *self, int varcref);
+  extern String *Swig_cmemberget_call(const String_or_char *name, SwigType *t, String_or_char *self, int varcref);
+
+  extern int Swig_add_extension_code(Node *n, const String *function_name, ParmList *parms, SwigType *return_type, const String *code, int cplusplus, const String *self);
+
+/* --- Transformations --- */
+
+  extern int Swig_MethodToFunction(Node *n, String *classname, int flags, SwigType *director_type, int is_director);
+  extern int Swig_ConstructorToFunction(Node *n, String *classname, String *none_comparison, String *director_ctor, int cplus, int flags);
+  extern int Swig_DestructorToFunction(Node *n, String *classname, int cplus, int flags);
+  extern int Swig_MembersetToFunction(Node *n, String *classname, int flags);
+  extern int Swig_MembergetToFunction(Node *n, String *classname, int flags);
+  extern int Swig_VargetToFunction(Node *n, int flags);
+  extern int Swig_VarsetToFunction(Node *n, int flags);
+
+#define  CWRAP_EXTEND                 0x01
+#define  CWRAP_SMART_POINTER          0x02
+#define  CWRAP_NATURAL_VAR            0x04
+#define  CWRAP_DIRECTOR_ONE_CALL      0x08
+#define  CWRAP_DIRECTOR_TWO_CALLS     0x10
+#define  CWRAP_ALL_PROTECTED_ACCESS   0x20
+
+/* --- Director Helpers --- */
+  extern Node *Swig_methodclass(Node *n);
+  extern int Swig_directorclass(Node *n);
+  extern Node *Swig_directormap(Node *n, String *type);
+
+/* --- Legacy Typemap API (somewhat simplified, ha!) --- */
+
+  extern void Swig_typemap_init(void);
+  extern void Swig_typemap_register(const String_or_char *op, ParmList *pattern, String_or_char *code, ParmList *locals, ParmList *kwargs);
+  extern int Swig_typemap_copy(const String_or_char *op, ParmList *srcpattern, ParmList *pattern);
+  extern void Swig_typemap_clear(const String_or_char *op, ParmList *pattern);
+  extern int Swig_typemap_apply(ParmList *srcpat, ParmList *destpat);
+  extern void Swig_typemap_clear_apply(ParmList *pattern);
+  extern void Swig_typemap_debug(void);
+
+  extern Hash *Swig_typemap_search(const String_or_char *op, SwigType *type, const String_or_char *pname, SwigType **matchtype);
+  extern Hash *Swig_typemap_search_multi(const String_or_char *op, ParmList *parms, int *nmatch);
+  extern String *Swig_typemap_lookup(const String_or_char *op, Node *n, const String_or_char *lname, Wrapper *f);
+  extern String *Swig_typemap_lookup_out(const String_or_char *op, Node *n, const String_or_char *lname, Wrapper *f, String *actioncode);
+  extern void Swig_typemap_attach_kwargs(Hash *tm, const String_or_char *op, Parm *p);
+  extern void Swig_typemap_new_scope(void);
+  extern Hash *Swig_typemap_pop_scope(void);
+
+  extern void Swig_typemap_attach_parms(const String_or_char *op, ParmList *parms, Wrapper *f);
+
+/* --- Code fragment support --- */
+
+  extern void Swig_fragment_register(Node *fragment);
+  extern void Swig_fragment_emit(String *name);
+  extern void Swig_fragment_clear(String *section);
+
+/* hacks defined in C++ ! */
+  extern int Swig_director_mode(void);
+  extern int Swig_director_protected_mode(void);
+  extern int Swig_all_protected_mode(void);
+  extern void Wrapper_director_mode_set(int);
+  extern void Wrapper_director_protected_mode_set(int);
+  extern void Wrapper_all_protected_mode_set(int);
+
+
+/* -- template init -- */
+  extern void SwigType_template_init(void);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/trunk/Source/Swig/swigfile.h b/trunk/Source/Swig/swigfile.h
new file mode 100644
index 0000000..c945fb1
--- /dev/null
+++ b/trunk/Source/Swig/swigfile.h
@@ -0,0 +1,39 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigfile.h
+ *
+ * File handling functions in the SWIG core
+ * ----------------------------------------------------------------------------- */
+
+/* $Id: swig.h 9603 2006-12-05 21:47:01Z beazley $ */
+
+extern List   *Swig_add_directory(const String_or_char *dirname);
+extern void    Swig_push_directory(const String_or_char *dirname);
+extern void    Swig_pop_directory();
+extern String *Swig_last_file();
+extern List   *Swig_search_path();
+extern FILE   *Swig_open(const String_or_char *name);
+extern String *Swig_read_file(FILE *f); 
+extern String *Swig_include(const String_or_char *name);
+extern String *Swig_include_sys(const String_or_char *name);
+extern int     Swig_insert_file(const String_or_char *name, File *outfile);
+extern void    Swig_set_push_dir(int dopush);
+extern int     Swig_get_push_dir(void);
+extern void    Swig_register_filebyname(const String_or_char *filename, File *outfile);
+extern File   *Swig_filebyname(const String_or_char *filename);
+extern char   *Swig_file_suffix(const String_or_char *filename);
+extern char   *Swig_file_basename(const String_or_char *filename);
+extern char   *Swig_file_filename(const String_or_char *filename);
+extern char   *Swig_file_dirname(const String_or_char *filename);
+
+/* Delimiter used in accessing files and directories */
+
+#if defined(MACSWIG)
+#  define SWIG_FILE_DELIMITER ":"
+#elif defined(_WIN32)
+#  define SWIG_FILE_DELIMITER "\\"
+#else
+#  define SWIG_FILE_DELIMITER "/"
+#endif
diff --git a/trunk/Source/Swig/swigopt.h b/trunk/Source/Swig/swigopt.h
new file mode 100644
index 0000000..428d90d
--- /dev/null
+++ b/trunk/Source/Swig/swigopt.h
@@ -0,0 +1,16 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigopt.h
+ *
+ * Header file for the SWIG command line processing functions
+ * ----------------------------------------------------------------------------- */
+
+/* $Id: swig.h 9622 2006-12-19 03:49:17Z beazley $ */
+
+ extern void  Swig_init_args(int argc, char **argv);
+ extern void  Swig_mark_arg(int n);
+ extern int   Swig_check_marked(int n);
+ extern void  Swig_check_options(int check_input);
+ extern void  Swig_arg_error();
diff --git a/trunk/Source/Swig/swigparm.h b/trunk/Source/Swig/swigparm.h
new file mode 100644
index 0000000..529438b
--- /dev/null
+++ b/trunk/Source/Swig/swigparm.h
@@ -0,0 +1,29 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigparm.h
+ *
+ * Functions related to the handling of function/method parameters and
+ * parameter lists.  
+ * ----------------------------------------------------------------------------- */
+
+/* $Id: swig.h 9629 2006-12-30 18:27:47Z beazley $ */
+
+/* Individual parameters */
+extern Parm      *NewParm(SwigType *type, const String_or_char *name);
+extern Parm      *CopyParm(Parm *p);
+
+/* Parameter lists */
+extern ParmList  *CopyParmList(ParmList *);
+extern ParmList  *CopyParmListMax(ParmList *, int count);
+extern int        ParmList_len(ParmList *);
+extern int        ParmList_numrequired(ParmList *);
+extern int        ParmList_has_defaultargs(ParmList *p);
+
+/* Output functions */
+extern String    *ParmList_str(ParmList *);
+extern String    *ParmList_str_defaultargs(ParmList *);
+extern String    *ParmList_protostr(ParmList *);
+
+
diff --git a/trunk/Source/Swig/swigscan.h b/trunk/Source/Swig/swigscan.h
new file mode 100644
index 0000000..2486286
--- /dev/null
+++ b/trunk/Source/Swig/swigscan.h
@@ -0,0 +1,108 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigscan.h
+ *
+ * C/C++ scanner. 
+ * ----------------------------------------------------------------------------- */
+
+/* $Id: swig.h 9633 2007-01-10 23:43:07Z beazley $ */
+
+typedef struct Scanner Scanner;
+
+extern Scanner     *NewScanner();
+extern void         DelScanner(Scanner *);
+extern void         Scanner_clear(Scanner *);
+extern void         Scanner_push(Scanner *, String *);
+extern void         Scanner_pushtoken(Scanner *, int, const String_or_char *value);
+extern int          Scanner_token(Scanner *);
+extern String      *Scanner_text(Scanner *);
+extern void         Scanner_skip_line(Scanner *);
+extern int          Scanner_skip_balanced(Scanner *, int startchar, int endchar);
+extern void         Scanner_set_location(Scanner *, String *file, int line);
+extern String      *Scanner_file(Scanner *);
+extern int          Scanner_line(Scanner *);
+extern int          Scanner_start_line(Scanner *);
+extern void         Scanner_idstart(Scanner *, const char *idchar);
+extern String      *Scanner_errmsg(Scanner *);
+extern int          Scanner_errline(Scanner *);
+extern int          Scanner_isoperator(int tokval);
+extern void         Scanner_freeze_line(Scanner *s, int val);
+
+/* Note: Tokens in range 100+ are for C/C++ operators */
+
+#define   SWIG_MAXTOKENS          200
+#define   SWIG_TOKEN_LPAREN       1        /* ( */
+#define   SWIG_TOKEN_RPAREN       2        /* ) */
+#define   SWIG_TOKEN_SEMI         3        /* ; */
+#define   SWIG_TOKEN_LBRACE       4        /* { */
+#define   SWIG_TOKEN_RBRACE       5        /* } */
+#define   SWIG_TOKEN_LBRACKET     6        /* [ */
+#define   SWIG_TOKEN_RBRACKET     7        /* ] */
+#define   SWIG_TOKEN_BACKSLASH    8        /* \ */
+#define   SWIG_TOKEN_ENDLINE      9        /* \n */
+#define   SWIG_TOKEN_STRING       10       /* "str" */
+#define   SWIG_TOKEN_POUND        11       /* # */
+#define   SWIG_TOKEN_COLON        12       /* : */
+#define   SWIG_TOKEN_DCOLON       13       /* :: */
+#define   SWIG_TOKEN_DCOLONSTAR   14       /* ::* */
+#define   SWIG_TOKEN_ID           15       /* identifer */
+#define   SWIG_TOKEN_FLOAT        16       /* 3.1415F */
+#define   SWIG_TOKEN_DOUBLE       17       /* 3.1415 */
+#define   SWIG_TOKEN_INT          18       /* 314 */
+#define   SWIG_TOKEN_UINT         19       /* 314U */
+#define   SWIG_TOKEN_LONG         20       /* 314L */
+#define   SWIG_TOKEN_ULONG        21       /* 314UL */
+#define   SWIG_TOKEN_CHAR         22       /* 'charconst' */
+#define   SWIG_TOKEN_PERIOD       23       /* . */
+#define   SWIG_TOKEN_AT           24       /* @ */
+#define   SWIG_TOKEN_DOLLAR       25       /* $ */
+#define   SWIG_TOKEN_CODEBLOCK    26       /* %{ ... %} ... */
+#define   SWIG_TOKEN_RSTRING      27       /* `charconst` */
+#define   SWIG_TOKEN_LONGLONG     28       /* 314LL */
+#define   SWIG_TOKEN_ULONGLONG    29       /* 314ULL */
+#define   SWIG_TOKEN_QUESTION     30       /* ? */
+#define   SWIG_TOKEN_COMMENT      31       /* C or C++ comment */
+#define   SWIG_TOKEN_ILLEGAL      99
+#define   SWIG_TOKEN_ERROR        -1
+
+#define   SWIG_TOKEN_COMMA        101      /* , */
+#define   SWIG_TOKEN_STAR         102      /* * */
+#define   SWIG_TOKEN_TIMES        102      /* * */
+#define   SWIG_TOKEN_EQUAL        103      /* = */
+#define   SWIG_TOKEN_EQUALTO      104      /* == */
+#define   SWIG_TOKEN_NOTEQUAL     105      /* != */
+#define   SWIG_TOKEN_PLUS         106      /* + */
+#define   SWIG_TOKEN_MINUS        107      /* - */
+#define   SWIG_TOKEN_AND          108      /* & */
+#define   SWIG_TOKEN_LAND         109      /* && */
+#define   SWIG_TOKEN_OR           110      /* | */
+#define   SWIG_TOKEN_LOR          111      /* || */
+#define   SWIG_TOKEN_XOR          112      /* ^ */
+#define   SWIG_TOKEN_LESSTHAN     113      /* < */
+#define   SWIG_TOKEN_GREATERTHAN  114      /* > */
+#define   SWIG_TOKEN_LTEQUAL      115      /* <= */
+#define   SWIG_TOKEN_GTEQUAL      116      /* >= */
+#define   SWIG_TOKEN_NOT          117      /* ~ */
+#define   SWIG_TOKEN_LNOT         118      /* ! */
+#define   SWIG_TOKEN_SLASH        119      /* / */
+#define   SWIG_TOKEN_DIVIDE       119      /* / */
+#define   SWIG_TOKEN_PERCENT      120      /* % */
+#define   SWIG_TOKEN_MODULO       120      /* % */
+#define   SWIG_TOKEN_LSHIFT       121      /* << */
+#define   SWIG_TOKEN_RSHIFT       122      /* >> */
+#define   SWIG_TOKEN_PLUSPLUS     123      /* ++ */
+#define   SWIG_TOKEN_MINUSMINUS   124      /* -- */
+#define   SWIG_TOKEN_PLUSEQUAL    125      /* += */
+#define   SWIG_TOKEN_MINUSEQUAL   126      /* -= */
+#define   SWIG_TOKEN_TIMESEQUAL   127      /* *= */
+#define   SWIG_TOKEN_DIVEQUAL     128      /* /= */
+#define   SWIG_TOKEN_ANDEQUAL     129      /* &= */
+#define   SWIG_TOKEN_OREQUAL      130      /* |= */
+#define   SWIG_TOKEN_XOREQUAL     131      /* ^= */
+#define   SWIG_TOKEN_LSEQUAL      132      /* <<= */
+#define   SWIG_TOKEN_RSEQUAL      133      /* >>= */
+#define   SWIG_TOKEN_MODEQUAL     134      /* %= */
+#define   SWIG_TOKEN_ARROW        135      /* -> */
+#define   SWIG_TOKEN_ARROWSTAR    136      /* ->* */
diff --git a/trunk/Source/Swig/swigtree.h b/trunk/Source/Swig/swigtree.h
new file mode 100644
index 0000000..2e5c4da
--- /dev/null
+++ b/trunk/Source/Swig/swigtree.h
@@ -0,0 +1,50 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigtree.h
+ *
+ * These functions are used to access and manipulate the SWIG parse tree.
+ * The structure of this tree is modeled directly after XML-DOM.  The attribute 
+ * and function names are meant to be similar.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id: swig.h 9622 2006-12-19 03:49:17Z beazley $ */
+
+/* Macros to traverse the DOM tree */
+
+#define  nodeType(x)               Getattr(x,"nodeType")
+#define  parentNode(x)             Getattr(x,"parentNode")
+#define  previousSibling(x)        Getattr(x,"previousSibling")
+#define  nextSibling(x)            Getattr(x,"nextSibling")
+#define  firstChild(x)             Getattr(x,"firstChild")
+#define  lastChild(x)              Getattr(x,"lastChild")
+
+/* Macros to set up the DOM tree (mostly used by the parser) */
+
+#define  set_nodeType(x,v)         Setattr(x,"nodeType",v)
+#define  set_parentNode(x,v)       Setattr(x,"parentNode",v)
+#define  set_previousSibling(x,v)  Setattr(x,"previousSibling",v)
+#define  set_nextSibling(x,v)      Setattr(x,"nextSibling",v)
+#define  set_firstChild(x,v)       Setattr(x,"firstChild",v)
+#define  set_lastChild(x,v)        Setattr(x,"lastChild",v)
+
+/* Utility functions */
+
+extern int    checkAttribute(Node *obj, const String_or_char *name, const String_or_char *value);
+extern void   appendChild(Node *node, Node *child);
+extern void   prependChild(Node *node, Node *child);
+extern void   removeNode(Node *node);
+extern Node  *copyNode(Node *node);
+
+/* Node restoration/restore functions */
+
+extern void  Swig_require(const char *ns, Node *node, ...);
+extern void  Swig_save(const char *ns, Node *node, ...);
+extern void  Swig_restore(Node *node);
+
+/* Debugging of parse trees */
+
+extern void Swig_print_tags(File *obj, Node *root);
+extern void Swig_print_tree(Node *obj);
+extern void Swig_print_node(Node *obj);
diff --git a/trunk/Source/Swig/swigwrap.h b/trunk/Source/Swig/swigwrap.h
new file mode 100644
index 0000000..25eeb6f
--- /dev/null
+++ b/trunk/Source/Swig/swigwrap.h
@@ -0,0 +1,29 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * swigwrap.h
+ *
+ * Functions related to wrapper objects.
+ * ----------------------------------------------------------------------------- */
+
+/* $Id: swig.h 9635 2007-01-12 01:44:16Z beazley $ */
+
+typedef struct Wrapper {
+    Hash *localh;
+    String *def;
+    String *locals;
+    String *code;
+} Wrapper;
+
+extern Wrapper *NewWrapper();
+extern void     DelWrapper(Wrapper *w);
+extern void     Wrapper_compact_print_mode_set(int flag);
+extern void     Wrapper_pretty_print(String *str, File *f);
+extern void     Wrapper_compact_print(String *str, File *f);
+extern void     Wrapper_print(Wrapper *w, File *f);
+extern int      Wrapper_add_local(Wrapper *w, const String_or_char *name, const String_or_char *decl);
+extern int      Wrapper_add_localv(Wrapper *w, const String_or_char *name, ...);
+extern int      Wrapper_check_local(Wrapper *w, const String_or_char *name);
+extern char    *Wrapper_new_local(Wrapper *w, const String_or_char *name, const String_or_char *decl);
+extern char    *Wrapper_new_localv(Wrapper *w, const String_or_char *name, ...);
diff --git a/trunk/Source/Swig/symbol.c b/trunk/Source/Swig/symbol.c
new file mode 100644
index 0000000..c9691fa
--- /dev/null
+++ b/trunk/Source/Swig/symbol.c
@@ -0,0 +1,1914 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * symbol.c
+ *
+ * This file implements the SWIG symbol table.  See details below.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_symbol_c[] = "$Id$";
+
+#include "swig.h"
+#include "swigwarn.h"
+#include <ctype.h>
+
+/* #define SWIG_DEBUG*/
+/* -----------------------------------------------------------------------------
+ * Synopsis
+ *
+ * This module provides symbol table management for all of SWIG.  In previous
+ * releases, the management of symbols was rather haphazard.  This module tries
+ * to correct that.
+ *
+ * All symbols are associated with simple identifiers.  For example, here are some
+ * declarations that generate symbol table entries:
+ *
+ *  decl                                    symbol
+ *  --------------                          ------------
+ *  void foo(int);                          foo
+ *  int  x;                                 x
+ *  typedef int *blah;                      blah
+ *
+ * Associated with each symbol is a Hash table that can contain any set of
+ * attributes that make sense for that object.  For example:
+ *
+ *  typedef int *blah;             ---->    "name" : 'blah'
+ *                                          "type" : 'int'
+ *                                          "decl" : 'p.'
+ *                                       "storage" : 'typedef'          
+ * 
+ * In some cases, the symbol table needs to manage overloaded entries.  For instance,
+ * overloaded functions.  In this case, a linked list is built.  The "sym:nextSibling"
+ * attribute is reserved to hold a link to the next entry.  For example:
+ *
+ * int foo(int);            --> "name" : "foo"         "name" : "foo"
+ * int foo(int,double);         "type" : "int"         "type" : "int" 
+ *                              "decl" : "f(int)."     "decl" : "f(int,double)."
+ *                               ...                    ...
+ *                   "sym:nextSibling" :  --------> "sym:nextSibling": --------> ...
+ *
+ * When more than one symbol has the same name, the symbol declarator is 
+ * used to detect duplicates.  For example, in the above case, foo(int) and
+ * foo(int,double) are different because their "decl" attribute is different.
+ * However, if a third declaration "foo(int)" was made, it would generate a 
+ * conflict (due to having a declarator that matches a previous entry).
+ *
+ * Structures and classes:
+ *
+ * C/C++ symbol tables are normally managed in a few different spaces.  The
+ * most visible namespace is reserved for functions, variables, typedef, enum values
+ * and such.  In C, a separate tag-space is reserved for 'struct name', 'class name',
+ * and 'union name' declarations.   In SWIG, a single namespace is used for everything
+ * this means that certain incompatibilities will arise with some C programs. For instance:
+ *
+ *        struct Foo {
+ *             ...
+ *        }
+ *
+ *        int Foo();       // Error. Name clash.  Works in C though 
+ * 
+ * Due to the unified namespace for structures, special handling is performed for
+ * the following:
+ *
+ *        typedef struct Foo {
+ *
+ *        } Foo;
+ * 
+ * In this case, the symbol table contains an entry for the structure itself.  The
+ * typedef is left out of the symbol table.
+ *
+ * Target language vs C:
+ *
+ * The symbol tables are normally managed *in the namespace of the target language*.
+ * This means that name-collisions can be resolved using %rename and related 
+ * directives.   A quirk of this is that sometimes the symbol tables need to
+ * be used for C type resolution as well.  To handle this, each symbol table
+ * also has a C-symbol table lurking behind the scenes.  This is used to locate 
+ * symbols in the C namespace.  However, this symbol table is not used for error 
+ * reporting nor is it used for anything else during code generation.
+ *
+ * Symbol table structure:
+ *
+ * Symbol tables themselves are a special kind of node that is organized just like
+ * a normal parse tree node.  Symbol tables are organized in a tree that can be
+ * traversed using the SWIG-DOM API. The following attributes names are reserved.
+ *
+ *     name           -- Name of the scope defined by the symbol table (if any)
+ *                       This name is the C-scope name and is not affected by
+ *                       %renaming operations
+ *     symtab         -- Hash table mapping identifiers to nodes.
+ *     csymtab        -- Hash table mapping C identifiers to nodes.
+ *
+ * Reserved attributes on symbol objects:
+ *
+ * When a symbol is placed in the symbol table, the following attributes
+ * are set:
+ *       
+ *     sym:name             -- Symbol name
+ *     sym:nextSibling      -- Next symbol (if overloaded)
+ *     sym:previousSibling  -- Previous symbol (if overloaded)
+ *     sym:symtab           -- Symbol table object holding the symbol
+ *     sym:overloaded       -- Set to the first symbol if overloaded
+ *
+ * These names are modeled after XML namespaces.  In particular, every attribute 
+ * pertaining to symbol table management is prefaced by the "sym:" prefix.   
+ *
+ * An example dump of the parse tree showing symbol table entries for the 
+ * following code should clarify this:
+ *
+ *   namespace OuterNamespace {
+ *       namespace InnerNamespace {
+ *           class Class {
+ *           };
+ *           struct Struct {
+ *               int Var;
+ *           };
+ *       }
+ *    }
+ *
+ *   +++ namespace ----------------------------------------
+ *   | sym:name     - "OuterNamespace"
+ *   | symtab       - 0xa064bf0
+ *   | sym:symtab   - 0xa041690
+ *   | sym:overname - "__SWIG_0"
+ *  
+ *         +++ namespace ----------------------------------------
+ *         | sym:name     - "InnerNamespace"
+ *         | symtab       - 0xa064cc0
+ *         | sym:symtab   - 0xa064bf0
+ *         | sym:overname - "__SWIG_0"
+ *  
+ *               +++ class ----------------------------------------
+ *               | sym:name     - "Class"
+ *               | symtab       - 0xa064d80
+ *               | sym:symtab   - 0xa064cc0
+ *               | sym:overname - "__SWIG_0"
+ *               | 
+ *               +++ class ----------------------------------------
+ *               | sym:name     - "Struct"
+ *               | symtab       - 0xa064f00
+ *               | sym:symtab   - 0xa064cc0
+ *               | sym:overname - "__SWIG_0"
+ *  
+ *                     +++ cdecl ----------------------------------------
+ *                     | sym:name     - "Var"
+ *                     | sym:symtab   - 0xa064f00
+ *                     | sym:overname - "__SWIG_0"
+ *                     | 
+ *  
+ *
+ * Each class and namespace has its own scope and thus a new symbol table (sym)
+ * is created. The sym attribute is only set for the first entry in the symbol
+ * table. The sym:symtab entry points to the symbol table in which the symbol
+ * exists, so for example, Struct is in the scope OuterNamespace::InnerNamespace
+ * so sym:symtab points to this symbol table (0xa064cc0).
+ *
+ * ----------------------------------------------------------------------------- */
+
+static Hash *current = 0;	/* The current symbol table hash */
+static Hash *ccurrent = 0;	/* The current c symbol table hash */
+static Hash *current_symtab = 0;	/* Current symbol table node */
+static Hash *symtabs = 0;	/* Hash of all symbol tables by fully-qualified name */
+static Hash *global_scope = 0;	/* Global scope */
+
+/* common attribute keys, to avoid calling find_key all the times */
+
+
+
+#if 0
+void Swig_symbol_dump_symtable() {
+  Printf(stdout, "DUMPING SYMTABLE start =======================================\n");
+  {
+    Hash *cst = Getattr(current_symtab, "csymtab");
+    Swig_print_tree(cst);
+    /*
+       Swig_print_tree(Getattr(cst, "NumSpace"));
+     */
+  }
+  Printf(stdout, "DUMPING SYMTABLE end   =======================================\n");
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_init()
+ *
+ * Create a new symbol table object
+ * ----------------------------------------------------------------------------- */
+
+void Swig_symbol_init() {
+
+  current = NewHash();
+  current_symtab = NewHash();
+  ccurrent = NewHash();
+  set_nodeType(current_symtab, "symboltable");
+  Setattr(current_symtab, "symtab", current);
+  Delete(current);
+  Setattr(current_symtab, "csymtab", ccurrent);
+  Delete(ccurrent);
+
+  /* Set the global scope */
+  symtabs = NewHash();
+  Setattr(symtabs, "", current_symtab);
+  Delete(current_symtab);
+  global_scope = current_symtab;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_setscopename()
+ *
+ * Set the C scopename of the current symbol table.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_symbol_setscopename(const String_or_char *name) {
+  String *qname;
+  /* assert(!Getattr(current_symtab,"name")); */
+  Setattr(current_symtab, "name", name);
+
+  /* Set nested scope in parent */
+
+  qname = Swig_symbol_qualifiedscopename(current_symtab);
+
+  /* Save a reference to this scope */
+  Setattr(symtabs, qname, current_symtab);
+  Delete(qname);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_getscopename()
+ *
+ * Get the C scopename of the current symbol table
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_symbol_getscopename() {
+  return Getattr(current_symtab, "name");
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_getscope()
+ *
+ * Given a fully qualified C scopename, this function returns a symbol table
+ * ----------------------------------------------------------------------------- */
+
+Symtab *Swig_symbol_getscope(const String_or_char *name) {
+  if (!symtabs)
+    return 0;
+  if (Equal("::", (String_or_char *) name))
+    name = "";
+  return Getattr(symtabs, name);
+}
+
+/* ----------------------------------------------------------------------------- 
+ * Swig_symbol_qualifiedscopename()
+ *
+ * Get the fully qualified C scopename of a symbol table.  Note, this only pertains
+ * to the C/C++ scope name.  It is not affected by renaming.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_symbol_qualifiedscopename(Symtab *symtab) {
+  String *result = 0;
+  Hash *parent;
+  String *name;
+  if (!symtab)
+    symtab = current_symtab;
+  parent = Getattr(symtab, "parentNode");
+  if (parent) {
+    result = Swig_symbol_qualifiedscopename(parent);
+  }
+  name = Getattr(symtab, "name");
+  if (name) {
+    if (!result) {
+      result = NewStringEmpty();
+    }
+    if (Len(result)) {
+      Printv(result, "::", name, NIL);
+    } else {
+      Append(result, name);
+    }
+  }
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_newscope()
+ *
+ * Create a new scope.  Returns the newly created scope.
+ * ----------------------------------------------------------------------------- */
+
+Symtab *Swig_symbol_newscope() {
+  Hash *n;
+  Hash *hsyms, *h;
+
+  hsyms = NewHash();
+  h = NewHash();
+
+  set_nodeType(h, "symboltable");
+  Setattr(h, "symtab", hsyms);
+  Delete(hsyms);
+  set_parentNode(h, current_symtab);
+
+  n = lastChild(current_symtab);
+  if (!n) {
+    set_firstChild(current_symtab, h);
+  } else {
+    set_nextSibling(n, h);
+    Delete(h);
+  }
+  set_lastChild(current_symtab, h);
+  current = hsyms;
+  ccurrent = NewHash();
+  Setattr(h, "csymtab", ccurrent);
+  Delete(ccurrent);
+  current_symtab = h;
+  return h;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_setscope()
+ *
+ * Set the current scope.  Returns the previous current scope.
+ * ----------------------------------------------------------------------------- */
+
+Symtab *Swig_symbol_setscope(Symtab *sym) {
+  Symtab *ret = current_symtab;
+  current_symtab = sym;
+  current = Getattr(sym, "symtab");
+  assert(current);
+  ccurrent = Getattr(sym, "csymtab");
+  assert(ccurrent);
+  return ret;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_popscope()
+ *
+ * Pop out of the current scope.  Returns the popped scope and sets the
+ * scope to the parent scope.
+ * ----------------------------------------------------------------------------- */
+
+Symtab *Swig_symbol_popscope() {
+  Hash *h = current_symtab;
+  current_symtab = Getattr(current_symtab, "parentNode");
+  assert(current_symtab);
+  current = Getattr(current_symtab, "symtab");
+  assert(current);
+  ccurrent = Getattr(current_symtab, "csymtab");
+  assert(ccurrent);
+  return h;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_current()
+ *
+ * Return the current symbol table.
+ * ----------------------------------------------------------------------------- */
+
+Symtab *Swig_symbol_current() {
+  return current_symtab;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_alias()
+ *
+ * Makes an alias for a symbol in the global symbol table.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_symbol_alias(String_or_char *aliasname, Symtab *s) {
+  String *qname = Swig_symbol_qualifiedscopename(current_symtab);
+  if (qname) {
+    Printf(qname, "::%s", aliasname);
+  } else {
+    qname = NewString(aliasname);
+  }
+  if (!Getattr(symtabs, qname)) {
+    Setattr(symtabs, qname, s);
+  }
+  Delete(qname);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_inherit()
+ *
+ * Inherit symbols from another scope.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_symbol_inherit(Symtab *s) {
+  int i, ilen;
+  List *inherit = Getattr(current_symtab, "inherit");
+  if (!inherit) {
+    inherit = NewList();
+    Setattr(current_symtab, "inherit", inherit);
+    Delete(inherit);
+  }
+
+  if (s == current_symtab) {
+    Swig_warning(WARN_PARSE_REC_INHERITANCE, Getfile(s), Getline(s), "Recursive scope inheritance of '%s'.\n", Getattr(s, "name"));
+    return;
+  }
+  assert(s != current_symtab);
+  ilen = Len(inherit);
+  for (i = 0; i < ilen; i++) {
+    Node *n = Getitem(inherit, i);
+    if (n == s)
+      return;			/* Already inherited */
+  }
+  Append(inherit, s);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_cadd()
+ *
+ * Adds a node to the C symbol table only.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_symbol_cadd(String_or_char *name, Node *n) {
+  Node *append = 0;
+
+  Node *cn;
+  /* There are a few options for weak symbols.  A "weak" symbol 
+     is any symbol that can be replaced by another symbol in the C symbol
+     table.  An example would be a forward class declaration.  A forward
+     class sits in the symbol table until a real class declaration comes along.
+
+     Certain symbols are marked as "sym:typename".  These are important 
+     symbols related to the C++ type-system and take precedence in the C
+     symbol table.  An example might be code like this:
+
+     template<class T> T foo(T x);
+     int foo(int);
+
+     In this case, the template is marked with "sym:typename" so that it
+     stays in the C symbol table (so that it can be expanded using %template).
+   */
+
+  if (!name)
+    return;
+  if (SwigType_istemplate(name)) {
+    String *cname = NewString(name);
+    String *dname = Swig_symbol_template_deftype(cname, 0);
+    if (!Equal(dname, name)) {
+      Swig_symbol_cadd(dname, n);
+    }
+    Delete(dname);
+    Delete(cname);
+  }
+#ifdef SWIG_DEBUG
+  Printf(stderr, "symbol_cadd %s %x\n", name, n);
+#endif
+  cn = Getattr(ccurrent, name);
+
+  if (cn && (Getattr(cn, "sym:typename"))) {
+    /* The node in the C symbol table is a typename.  Do nothing */
+    /* We might append the symbol at the end */
+    append = n;
+  } else if (cn && (Getattr(cn, "sym:weak"))) {
+    /* The node in the symbol table is weak. Replace it */
+    if (checkAttribute(cn, "nodeType", "template")
+	&& checkAttribute(cn, "templatetype", "classforward")) {
+      /* The node is a template classforward declaration, and the
+         default template parameters here take precedence. */
+      ParmList *pc = Getattr(cn, "templateparms");
+      ParmList *pn = Getattr(n, "templateparms");
+#ifdef SWIG_DEBUG
+      Printf(stderr, "found template classforward %s\n", Getattr(cn, "name"));
+#endif
+      while (pc && pn) {
+	String *value = Getattr(pc, "value");
+	if (value) {
+#ifdef SWIG_DEBUG
+	  Printf(stderr, "add default template value %s %s\n", Getattr(pc, "name"), value);
+#endif
+	  Setattr(pn, "value", value);
+	}
+	pc = nextSibling(pc);
+	pn = nextSibling(pn);
+      }
+      Setattr(n, "templateparms", Getattr(cn, "templateparms"));
+    }
+    Setattr(ccurrent, name, n);
+
+  } else if (cn && (Getattr(n, "sym:weak"))) {
+    /* The node being added is weak.  Don't worry about it */
+  } else if (cn && (Getattr(n, "sym:typename"))) {
+    /* The node being added is a typename.  We definitely add it */
+    Setattr(ccurrent, name, n);
+    append = cn;
+  } else if (cn && (Checkattr(cn, "nodeType", "templateparm"))) {
+    Swig_error(Getfile(n), Getline(n), "Declaration of '%s' shadows template parameter,\n", name);
+    Swig_error(Getfile(cn), Getline(cn), "previous template parameter declaration '%s'.\n", name);
+    return;
+  } else if (cn) {
+    append = n;
+  } else if (!cn) {
+    /* No conflict. Add the symbol */
+    Setattr(ccurrent, name, n);
+  }
+
+  /* Multiple entries in the C symbol table.   We append to to the symbol table */
+  if (append) {
+    Node *fn, *pn = 0;
+    cn = Getattr(ccurrent, name);
+    fn = cn;
+    while (fn) {
+      pn = fn;
+      if (fn == append) {
+	/* already added. Bail */
+	return;
+      }
+      fn = Getattr(fn, "csym:nextSibling");
+    }
+    if (pn) {
+      Setattr(pn, "csym:nextSibling", append);
+    }
+  }
+
+  /* Special typedef handling.  When a typedef node is added to the symbol table, we
+     might have to add a type alias.   This would occur if the typedef mapped to another
+     scope in the system.  For example:
+
+     class Foo {
+     };
+
+     typedef Foo OtherFoo;
+
+     In this case, OtherFoo becomes an alias for Foo. */
+
+  {
+    Node *td = n;
+    while (td && Checkattr(td, "nodeType", "cdecl") && Checkattr(td, "storage", "typedef")) {
+      SwigType *type;
+      Node *td1;
+      type = Copy(Getattr(td, "type"));
+      SwigType_push(type, Getattr(td, "decl"));
+      td1 = Swig_symbol_clookup(type, 0);
+
+      /* Fix pathetic case #1214313:
+
+         class Foo
+         {
+         };
+
+         typedef Foo FooBar;
+
+         class CBaz
+         {
+         public:
+         typedef FooBar Foo;
+         };
+
+         ie, when Foo -> FooBar -> Foo, jump one scope up when possible.
+
+       */
+      if (td1 && Checkattr(td1, "storage", "typedef")) {
+	String *st = Getattr(td1, "type");
+	String *sn = Getattr(td, "name");
+	if (st && sn && Equal(st, sn)) {
+	  Symtab *sc = Getattr(current_symtab, "parentNode");
+	  if (sc)
+	    td1 = Swig_symbol_clookup(type, sc);
+	}
+      }
+
+      Delete(type);
+      if (td1 == td)
+	break;
+      td = td1;
+      if (td) {
+	Symtab *st = Getattr(td, "symtab");
+	if (st) {
+	  Swig_symbol_alias(Getattr(n, "name"), st);
+	  break;
+	}
+      }
+    }
+  }
+}
+
+/* ----------------------------------------------------------------------------- 
+ * Swig_symbol_add()
+ *
+ * Adds a node to the symbol table.  Returns the node itself if successfully
+ * added.  Otherwise, it returns the symbol table entry of the conflicting node.
+ *
+ * Also places the symbol in a behind-the-scenes C symbol table.  This is needed
+ * for namespace support, type resolution, and other issues.
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_symbol_add(String_or_char *symname, Node *n) {
+  Hash *c, *cn, *cl = 0;
+  SwigType *decl, *ndecl;
+  String *cstorage, *nstorage;
+  int nt = 0, ct = 0;
+  int pn = 0;
+  int u1 = 0, u2 = 0;
+  String *name, *overname;
+
+  /* See if the node has a name.  If so, we place in the C symbol table for this
+     scope. We don't worry about overloading here---the primary purpose of this
+     is to record information for type/name resolution for later. Conflicts
+     in C namespaces are errors, but these will be caught by the C++ compiler
+     when compiling the wrapper code */
+
+
+  /* There are a few options for weak symbols.  A "weak" symbol 
+     is any symbol that can be replaced by another symbol in the C symbol
+     table.  An example would be a forward class declaration.  A forward
+     class sits in the symbol table until a real class declaration comes along.
+
+     Certain symbols are marked as "sym:typename".  These are important 
+     symbols related to the C++ type-system and take precedence in the C
+     symbol table.  An example might be code like this:
+
+     template<class T> T foo(T x);
+     int foo(int);
+
+     In this case, the template is marked with "sym:typename" so that it
+     stays in the C symbol table (so that it can be expanded using %template).
+   */
+
+  name = Getattr(n, "name");
+  if (name && Len(name)) {
+    Swig_symbol_cadd(name, n);
+  }
+
+  /* No symbol name defined.  We return. */
+  if (!symname) {
+    Setattr(n, "sym:symtab", current_symtab);
+    return n;
+  }
+
+  /* If node is ignored. We don't proceed any further */
+  if (GetFlag(n, "feature:ignore"))
+    return n;
+
+  /* See if the symbol already exists in the table */
+  c = Getattr(current, symname);
+
+  /* Check for a weak symbol.  A weak symbol is allowed to be in the
+     symbol table, but is silently overwritten by other symbols.  An example
+     would be a forward class declaration.  For instance:
+
+     class Foo;
+
+     In this case, "Foo" sits in the symbol table.  However, the
+     definition of Foo would replace the entry if it appeared later. */
+
+  if (c && Getattr(c, "sym:weak")) {
+    c = 0;
+  }
+  if (c) {
+    /* There is a symbol table conflict.  There are a few cases to consider here:
+       (1) A conflict between a class/enum and a typedef declaration is okay.
+       In this case, the symbol table entry is set to the class/enum declaration
+       itself, not the typedef.   
+
+       (2) A conflict between namespaces is okay--namespaces are open
+
+       (3) Otherwise, overloading is only allowed for functions
+     */
+
+    /* Check for namespaces */
+    String *ntype = Getattr(n, "nodeType");
+    if ((Equal(ntype, Getattr(c, "nodeType"))) && ((Equal(ntype, "namespace")))) {
+      Node *cl, *pcl = 0;
+      cl = c;
+      while (cl) {
+	pcl = cl;
+	cl = Getattr(cl, "sym:nextSibling");
+      }
+      Setattr(pcl, "sym:nextSibling", n);
+      Setattr(n, "sym:symtab", current_symtab);
+      Setattr(n, "sym:name", symname);
+      Setattr(n, "sym:previousSibling", pcl);
+      return n;
+    }
+    if (Getattr(n, "allows_typedef"))
+      nt = 1;
+    if (Getattr(c, "allows_typedef"))
+      ct = 1;
+    if (nt || ct) {
+      Node *td, *other;
+      String *s;
+      /* At least one of the nodes allows typedef overloading.  Make sure that
+         both don't--this would be a conflict */
+
+      if (nt && ct)
+	return c;
+
+      /* Figure out which node allows the typedef */
+      if (nt) {
+	td = n;
+	other = c;
+      } else {
+	td = c;
+	other = n;
+      }
+      /* Make sure the other node is a typedef */
+      s = Getattr(other, "storage");
+      if (!s || (!Equal(s, "typedef")))
+	return c;		/* No.  This is a conflict */
+
+      /* Hmmm.  This appears to be okay.  Make sure the symbol table refers to the allow_type node */
+
+      if (td != c) {
+	Setattr(current, symname, td);
+	Setattr(td, "sym:symtab", current_symtab);
+	Setattr(td, "sym:name", symname);
+      }
+      return n;
+    }
+
+    decl = Getattr(c, "decl");
+    ndecl = Getattr(n, "decl");
+
+    {
+      String *nt1, *nt2;
+      nt1 = Getattr(n, "nodeType");
+      if (Equal(nt1, "template"))
+	nt1 = Getattr(n, "templatetype");
+      nt2 = Getattr(c, "nodeType");
+      if (Equal(nt2, "template"))
+	nt2 = Getattr(c, "templatetype");
+      if (Equal(nt1, "using"))
+	u1 = 1;
+      if (Equal(nt2, "using"))
+	u2 = 1;
+
+      if ((!Equal(nt1, nt2)) && !(u1 || u2))
+	return c;
+    }
+    if (!(u1 || u2)) {
+      if ((!SwigType_isfunction(decl)) || (!SwigType_isfunction(ndecl))) {
+	/* Symbol table conflict */
+	return c;
+      }
+    }
+
+    /* Hmmm. Declarator seems to indicate that this is a function */
+    /* Look at storage class to see if compatible */
+    cstorage = Getattr(c, "storage");
+    nstorage = Getattr(n, "storage");
+
+    /* If either one is declared as typedef, forget it. We're hosed */
+    if (Cmp(cstorage, "typedef") == 0) {
+      return c;
+    }
+    if (Cmp(nstorage, "typedef") == 0) {
+      return c;
+    }
+
+    /* Okay. Walk down the list of symbols and see if we get a declarator match */
+    {
+      String *nt = Getattr(n, "nodeType");
+      int n_template = Equal(nt, "template") && Checkattr(n, "templatetype", "cdecl");
+      int n_plain_cdecl = Equal(nt, "cdecl");
+      cn = c;
+      pn = 0;
+      while (cn) {
+	decl = Getattr(cn, "decl");
+	if (!(u1 || u2)) {
+	  if (Cmp(ndecl, decl) == 0) {
+	    /* Declarator conflict */
+	    /* Now check we don't have a non-templated function overloaded by a templated function with same params,
+	     * eg void foo(); template<typename> void foo(); */
+	    String *cnt = Getattr(cn, "nodeType");
+	    int cn_template = Equal(cnt, "template") && Checkattr(cn, "templatetype", "cdecl");
+	    int cn_plain_cdecl = Equal(cnt, "cdecl");
+	    if (!((n_template && cn_plain_cdecl) || (cn_template && n_plain_cdecl))) {
+	      /* found a conflict */
+	      return cn;
+	    }
+	  }
+	}
+	cl = cn;
+	cn = Getattr(cn, "sym:nextSibling");
+	pn++;
+      }
+    }
+    /* Well, we made it this far.  Guess we can drop the symbol in place */
+    Setattr(n, "sym:symtab", current_symtab);
+    Setattr(n, "sym:name", symname);
+    /* Printf(stdout,"%s %x\n", Getattr(n,"sym:overname"), current_symtab); */
+    assert(!Getattr(n, "sym:overname"));
+    overname = NewStringf("__SWIG_%d", pn);
+    Setattr(n, "sym:overname", overname);
+    /*Printf(stdout,"%s %s %s\n", symname, Getattr(n,"decl"), Getattr(n,"sym:overname")); */
+    Setattr(cl, "sym:nextSibling", n);
+    Setattr(n, "sym:previousSibling", cl);
+    Setattr(cl, "sym:overloaded", c);
+    Setattr(n, "sym:overloaded", c);
+    Delete(overname);
+    return n;
+  }
+
+  /* No conflict.  Just add it */
+  Setattr(n, "sym:symtab", current_symtab);
+  Setattr(n, "sym:name", symname);
+  /* Printf(stdout,"%s\n", Getattr(n,"sym:overname")); */
+  overname = NewStringf("__SWIG_%d", pn);
+  Setattr(n, "sym:overname", overname);
+  Delete(overname);
+  /* Printf(stdout,"%s %s %s\n", symname, Getattr(n,"decl"), Getattr(n,"sym:overname")); */
+  Setattr(current, symname, n);
+  return n;
+}
+
+/* -----------------------------------------------------------------------------
+ * symbol_lookup()
+ *
+ * Internal function to handle fully qualified symbol table lookups.  This
+ * works from the symbol table supplied in symtab and unwinds its way out
+ * towards the global scope. 
+ *
+ * This function operates in the C namespace, not the target namespace.
+ *
+ * The check function is an optional callback that can be used to verify a particular
+ * symbol match.   This is only used in some of the more exotic parts of SWIG. For instance,
+ * verifying that a class hierarchy implements all pure virtual methods.
+ * ----------------------------------------------------------------------------- */
+
+static Node *_symbol_lookup(String *name, Symtab *symtab, int (*check) (Node *n)) {
+  Node *n;
+  List *inherit;
+  Hash *sym = Getattr(symtab, "csymtab");
+  if (Getmark(symtab))
+    return 0;
+  Setmark(symtab, 1);
+
+
+  n = Getattr(sym, name);
+
+#ifdef SWIG_DEBUG
+  Printf(stderr, "symbol_look %s %x %x %s\n", name, n, symtab, Getattr(symtab, "name"));
+#endif
+
+  if (n) {
+    /* if a check-function is defined.  Call it to determine a match */
+    if (check) {
+      int c = check(n);
+      if (c == 1) {
+	Setmark(symtab, 0);
+	return n;
+      }
+      if (c < 0) {
+	/* Terminate the search right away */
+	Setmark(symtab, 0);
+	return 0;
+      }
+    } else {
+      Setmark(symtab, 0);
+      return n;
+    }
+  }
+
+  if (!n && SwigType_istemplate(name)) {
+    String *dname = 0;
+    Setmark(symtab, 0);
+    dname = Swig_symbol_template_deftype(name, symtab);
+    if (!Equal(dname, name)) {
+      n = _symbol_lookup(dname, symtab, check);
+    }
+    Delete(dname);
+    if (n)
+      return n;
+  }
+
+  inherit = Getattr(symtab, "inherit");
+  if (inherit) {
+    int i, len;
+    len = Len(inherit);
+    for (i = 0; i < len; i++) {
+      n = _symbol_lookup(name, Getitem(inherit, i), check);
+      if (n) {
+	Setmark(symtab, 0);
+	return n;
+      }
+    }
+  }
+
+  Setmark(symtab, 0);
+  return 0;
+}
+
+static Node *symbol_lookup(String_or_char *name, Symtab *symtab, int (*check) (Node *n)) {
+  Node *n = 0;
+  if (DohCheck(name)) {
+    n = _symbol_lookup(name, symtab, check);
+  } else {
+    String *sname = NewString(name);
+    n = _symbol_lookup(sname, symtab, check);
+    Delete(sname);
+  }
+  return n;
+}
+
+
+
+/* -----------------------------------------------------------------------------
+ * symbol_lookup_qualified()
+ * ----------------------------------------------------------------------------- */
+
+static Node *symbol_lookup_qualified(String_or_char *name, Symtab *symtab, String *prefix, int local, int (*checkfunc) (Node *n)) {
+  /* This is a little funky, we search by fully qualified names */
+
+  if (!symtab)
+    return 0;
+  if (!prefix) {
+    Node *n;
+    String *bname;
+    String *prefix;
+    Swig_scopename_split(name, &prefix, &bname);
+    n = symbol_lookup_qualified(bname, symtab, prefix, local, checkfunc);
+    Delete(bname);
+    Delete(prefix);
+    return n;
+  } else {
+    Symtab *st;
+    Node *n = 0;
+    /* Make qualified name of current scope */
+    String *qalloc = 0;
+    String *qname = Swig_symbol_qualifiedscopename(symtab);
+    if (qname) {
+      if (Len(qname)) {
+	if (prefix && Len(prefix)) {
+	  Printv(qname, "::", prefix, NIL);
+	}
+      } else {
+	Append(qname, prefix);
+      }
+      qalloc = qname;
+    } else {
+      qname = prefix;
+    }
+    st = Getattr(symtabs, qname);
+    /* Found a scope match */
+    if (st) {
+      if (!name) {
+	if (qalloc)
+	  Delete(qalloc);
+	return st;
+      }
+      n = symbol_lookup(name, st, checkfunc);
+    }
+    if (qalloc)
+      Delete(qalloc);
+
+    if (!n) {
+      if (!local) {
+	Node *pn = Getattr(symtab, "parentNode");
+	if (pn)
+	  n = symbol_lookup_qualified(name, pn, prefix, local, checkfunc);
+      } else {
+	n = 0;
+      }
+    }
+    return n;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_clookup()
+ *
+ * Look up a symbol in the symbol table.   This uses the C name, not scripting
+ * names.   Note: If we come across a using a directive, we follow it to
+ * to get the real node.
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_symbol_clookup(String_or_char *name, Symtab *n) {
+  Hash *hsym = 0;
+  Node *s = 0;
+
+  if (!n) {
+    hsym = current_symtab;
+  } else {
+    if (!Checkattr(n, "nodeType", "symboltable")) {
+      n = Getattr(n, "sym:symtab");
+    }
+    assert(n);
+    if (n) {
+      hsym = n;
+    }
+  }
+
+  if (Swig_scopename_check(name)) {
+    char *cname = Char(name);
+    if (strncmp(cname, "::", 2) == 0) {
+      String *nname = NewString(cname + 2);
+      if (Swig_scopename_check(nname)) {
+	s = symbol_lookup_qualified(nname, global_scope, 0, 0, 0);
+      }
+      Delete(nname);
+    } else {
+      String *prefix = Swig_scopename_prefix(name);
+      if (prefix) {
+	s = symbol_lookup_qualified(name, hsym, 0, 0, 0);
+	Delete(prefix);
+	if (!s) {
+	  return 0;
+	}
+      }
+    }
+  }
+  if (!s) {
+    while (hsym) {
+      s = symbol_lookup(name, hsym, 0);
+      if (s)
+	break;
+      hsym = Getattr(hsym, "parentNode");
+      if (!hsym)
+	break;
+    }
+  }
+
+  if (!s) {
+    return 0;
+  }
+  /* Check if s is a 'using' node */
+  while (s && Checkattr(s, "nodeType", "using")) {
+    String *uname = Getattr(s, "uname");
+    Symtab *un = Getattr(s, "sym:symtab");
+    Node *ss = (!Equal(name, uname) || (un != n)) ? Swig_symbol_clookup(uname, un) : 0;	/* avoid infinity loop */
+    if (!ss) {
+      Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname"));
+    }
+    s = ss;
+  }
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_clookup_check()
+ *
+ * This function is identical to Swig_symbol_clookup() except that it
+ * accepts a callback function that is invoked to determine a symbol match.
+ * The purpose of this function is to support complicated algorithms that need
+ * to examine multiple definitions of the same symbol that might appear in an
+ * inheritance hierarchy. 
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_symbol_clookup_check(String_or_char *name, Symtab *n, int (*checkfunc) (Node *n)) {
+  Hash *hsym = 0;
+  Node *s = 0;
+
+  if (!n) {
+    hsym = current_symtab;
+  } else {
+    if (!Checkattr(n, "nodeType", "symboltable")) {
+      n = Getattr(n, "sym:symtab");
+    }
+    assert(n);
+    if (n) {
+      hsym = n;
+    }
+  }
+
+  if (Swig_scopename_check(name)) {
+    char *cname = Char(name);
+    if (strncmp(cname, "::", 2) == 0) {
+      String *nname = NewString(cname + 2);
+      if (Swig_scopename_check(nname)) {
+	s = symbol_lookup_qualified(nname, global_scope, 0, 0, checkfunc);
+      }
+      Delete(nname);
+    } else {
+      String *prefix = Swig_scopename_prefix(name);
+      if (prefix) {
+	s = symbol_lookup_qualified(name, hsym, 0, 0, checkfunc);
+	Delete(prefix);
+	if (!s) {
+	  return 0;
+	}
+      }
+    }
+  }
+  if (!s) {
+    while (hsym) {
+      s = symbol_lookup(name, hsym, checkfunc);
+      if (s)
+	break;
+      hsym = Getattr(hsym, "parentNode");
+      if (!hsym)
+	break;
+    }
+  }
+  if (!s) {
+    return 0;
+  }
+  /* Check if s is a 'using' node */
+  while (s && Checkattr(s, "nodeType", "using")) {
+    Node *ss;
+    ss = Swig_symbol_clookup(Getattr(s, "uname"), Getattr(s, "sym:symtab"));
+    if (!ss && !checkfunc) {
+      Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname"));
+    }
+    s = ss;
+  }
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_clookup_local()
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_symbol_clookup_local(String_or_char *name, Symtab *n) {
+  Hash *h, *hsym;
+  Node *s = 0;
+
+  if (!n) {
+    hsym = current_symtab;
+    h = ccurrent;
+  } else {
+    if (!Checkattr(n, "nodeType", "symboltable")) {
+      n = Getattr(n, "sym:symtab");
+    }
+    assert(n);
+    hsym = n;
+    h = Getattr(n, "csymtab");
+  }
+
+  if (Swig_scopename_check(name)) {
+    char *cname = Char(name);
+    if (strncmp(cname, "::", 2) == 0) {
+      String *nname = NewString(cname + 2);
+      if (Swig_scopename_check(nname)) {
+	s = symbol_lookup_qualified(nname, global_scope, 0, 0, 0);
+      }
+      Delete(nname);
+    } else {
+      s = symbol_lookup_qualified(name, hsym, 0, 0, 0);
+    }
+  }
+  if (!s) {
+    s = symbol_lookup(name, hsym, 0);
+  }
+  if (!s)
+    return 0;
+  /* Check if s is a 'using' node */
+  while (s && Checkattr(s, "nodeType", "using")) {
+    Node *ss = Swig_symbol_clookup_local(Getattr(s, "uname"), Getattr(s, "sym:symtab"));
+    if (!ss) {
+      Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname"));
+    }
+    s = ss;
+  }
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_clookup_local_check()
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_symbol_clookup_local_check(String_or_char *name, Symtab *n, int (*checkfunc) (Node *)) {
+  Hash *h, *hsym;
+  Node *s = 0;
+
+  if (!n) {
+    hsym = current_symtab;
+    h = ccurrent;
+  } else {
+    if (!Checkattr(n, "nodeType", "symboltable")) {
+      n = Getattr(n, "sym:symtab");
+    }
+    assert(n);
+    hsym = n;
+    h = Getattr(n, "csymtab");
+  }
+
+  if (Swig_scopename_check(name)) {
+    char *cname = Char(name);
+    if (strncmp(cname, "::", 2) == 0) {
+      String *nname = NewString(cname + 2);
+      if (Swig_scopename_check(nname)) {
+	s = symbol_lookup_qualified(nname, global_scope, 0, 0, checkfunc);
+      }
+      Delete(nname);
+    } else {
+      s = symbol_lookup_qualified(name, hsym, 0, 0, checkfunc);
+    }
+  }
+  if (!s) {
+    s = symbol_lookup(name, hsym, checkfunc);
+  }
+  if (!s)
+    return 0;
+  /* Check if s is a 'using' node */
+  while (s && Checkattr(s, "nodeType", "using")) {
+    Node *ss = Swig_symbol_clookup_local_check(Getattr(s, "uname"), Getattr(s, "sym:symtab"), checkfunc);
+    if (!ss && !checkfunc) {
+      Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname"));
+    }
+    s = ss;
+  }
+  return s;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_cscope()
+ *
+ * Look up a scope name.
+ * ----------------------------------------------------------------------------- */
+
+Symtab *Swig_symbol_cscope(String_or_char *name, Symtab *symtab) {
+  char *cname = Char(name);
+  if (strncmp(cname, "::", 2) == 0)
+    return symbol_lookup_qualified(0, global_scope, name, 0, 0);
+  return symbol_lookup_qualified(0, symtab, name, 0, 0);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_remove()
+ *
+ * Remove a symbol. If the symbol is an overloaded function and the symbol removed
+ * is not the last in the list of overloaded functions, then the overloaded
+ * names (sym:overname attribute) are changed to start from zero, eg __SWIG_0.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_symbol_remove(Node *n) {
+  Symtab *symtab;
+  String *symname;
+  String *overname;
+  Node *symprev;
+  Node *symnext;
+  Node *fixovername = 0;
+  symtab = Getattr(n, "sym:symtab");	/* Get symbol table object */
+  symtab = Getattr(symtab, "symtab");	/* Get actual hash table of symbols */
+  symname = Getattr(n, "sym:name");
+  symprev = Getattr(n, "sym:previousSibling");
+  symnext = Getattr(n, "sym:nextSibling");
+
+  /* If previous symbol, just fix the links */
+  if (symprev) {
+    if (symnext) {
+      Setattr(symprev, "sym:nextSibling", symnext);
+      fixovername = symprev;	/* fix as symbol to remove is somewhere in the middle of the linked list */
+    } else {
+      Delattr(symprev, "sym:nextSibling");
+    }
+  } else {
+    /* If no previous symbol, see if there is a next symbol */
+    if (symnext) {
+      Setattr(symtab, symname, symnext);
+      fixovername = symnext;	/* fix as symbol to remove is at head of linked list */
+    } else {
+      Delattr(symtab, symname);
+    }
+  }
+  if (symnext) {
+    if (symprev) {
+      Setattr(symnext, "sym:previousSibling", symprev);
+    } else {
+      Delattr(symnext, "sym:previousSibling");
+    }
+  }
+  Delattr(n, "sym:symtab");
+  Delattr(n, "sym:previousSibling");
+  Delattr(n, "sym:nextSibling");
+  Delattr(n, "csym:nextSibling");
+  Delattr(n, "sym:overname");
+  Delattr(n, "csym:previousSibling");
+  Delattr(n, "sym:overloaded");
+  n = 0;
+
+  if (fixovername) {
+    Node *nn = fixovername;
+    Node *head = fixovername;
+    int pn = 0;
+
+    /* find head of linked list */
+    while (nn) {
+      head = nn;
+      nn = Getattr(nn, "sym:previousSibling");
+    }
+
+    /* adjust all the sym:overname strings to start from 0 and increment by one */
+    nn = head;
+    while (nn) {
+      assert(Getattr(nn, "sym:overname"));
+      Delattr(nn, "sym:overname");
+      overname = NewStringf("__SWIG_%d", pn);
+      Setattr(nn, "sym:overname", overname);
+      Delete(overname);
+      pn++;
+      nn = Getattr(nn, "sym:nextSibling");
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_qualified()
+ *
+ * Return the qualified name of a symbol
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_symbol_qualified(Node *n) {
+  Hash *symtab;
+  if (Checkattr(n, "nodeType", "symboltable")) {
+    symtab = n;
+  } else {
+    symtab = Getattr(n, "sym:symtab");
+  }
+  if (!symtab)
+    return NewStringEmpty();
+#ifdef SWIG_DEBUG
+  Printf(stderr, "symbol_qscope %s %x %s\n", Getattr(n, "name"), symtab, Getattr(symtab, "name"));
+#endif
+  return Swig_symbol_qualifiedscopename(symtab);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_isoverloaded()
+ * 
+ * Check if a symbol is overloaded.  Returns the first symbol if so.
+ * ----------------------------------------------------------------------------- */
+
+Node *Swig_symbol_isoverloaded(Node *n) {
+  return Getattr(n, "sym:overloaded");
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_type_qualify()
+ *
+ * Create a fully qualified type name
+ * ----------------------------------------------------------------------------- */
+
+/* This cache produces problems with OSS, don't active it */
+/* #define SWIG_TEMPLATE_QUALIFY_CACHE */
+static SwigType *Swig_symbol_template_qualify(const SwigType *e, Symtab *st) {
+  String *tprefix, *tsuffix;
+  SwigType *qprefix;
+  List *targs;
+  Node *tempn;
+  Symtab *tscope;
+  Iterator ti;
+#ifdef SWIG_TEMPLATE_QUALIFY_CACHE
+  static Hash *qualify_cache = 0;
+  String *scopetype = st ? NewStringf("%s::%s", Getattr(st, "name"), e)
+      : NewStringf("%s::%s", Swig_symbol_getscopename(), e);
+  if (!qualify_cache) {
+    qualify_cache = NewHash();
+  }
+  if (scopetype) {
+    String *cres = Getattr(qualify_cache, scopetype);
+    if (cres) {
+      Delete(scopetype);
+      return Copy(cres);
+    }
+  }
+#endif
+
+  tprefix = SwigType_templateprefix(e);
+  tsuffix = SwigType_templatesuffix(e);
+  qprefix = Swig_symbol_type_qualify(tprefix, st);
+  targs = SwigType_parmlist(e);
+  tempn = Swig_symbol_clookup_local(tprefix, st);
+  tscope = tempn ? Getattr(tempn, "sym:symtab") : 0;
+  Append(qprefix, "<(");
+  for (ti = First(targs); ti.item;) {
+    String *vparm;
+    String *qparm = Swig_symbol_type_qualify(ti.item, st);
+    if (tscope && (tscope != st)) {
+      String *ty = Swig_symbol_type_qualify(qparm, tscope);
+      Delete(qparm);
+      qparm = ty;
+    }
+
+    vparm = Swig_symbol_template_param_eval(qparm, st);
+    Append(qprefix, vparm);
+    ti = Next(ti);
+    if (ti.item) {
+      Putc(',', qprefix);
+    }
+    Delete(qparm);
+    Delete(vparm);
+  }
+  Append(qprefix, ")>");
+  Append(qprefix, tsuffix);
+  Delete(tprefix);
+  Delete(tsuffix);
+  Delete(targs);
+#ifdef SWIG_DEBUG
+  Printf(stderr, "symbol_temp_qual %s %s\n", e, qprefix);
+#endif
+#ifdef SWIG_TEMPLATE_QUALIFY_CACHE
+  Setattr(qualify_cache, scopetype, qprefix);
+  Delete(scopetype);
+#endif
+
+  return qprefix;
+}
+
+
+static int no_constructor(Node *n) {
+  return !Checkattr(n, "nodeType", "constructor");
+}
+
+SwigType *Swig_symbol_type_qualify(const SwigType *t, Symtab *st) {
+  List *elements;
+  String *result = NewStringEmpty();
+  int i, len;
+  char *c = Char(t);
+  if (strncmp(c, "::", 2) == 0) {
+    Append(result, t);
+    return result;
+  }
+
+  elements = SwigType_split(t);
+
+  len = Len(elements);
+  for (i = 0; i < len; i++) {
+    String *e = Getitem(elements, i);
+    if (SwigType_issimple(e)) {
+      Node *n = Swig_symbol_clookup_check(e, st, no_constructor);
+      if (n) {
+	String *name = Getattr(n, "name");
+	Clear(e);
+	Append(e, name);
+#ifdef SWIG_DEBUG
+	Printf(stderr, "symbol_qual_ei %d %s %s %x\n", i, name, e, st);
+#endif
+	if (!Swig_scopename_check(name)) {
+	  String *qname = Swig_symbol_qualified(n);
+	  if (qname && Len(qname)) {
+	    Insert(e, 0, "::");
+	    Insert(e, 0, qname);
+	  }
+#ifdef SWIG_DEBUG
+	  Printf(stderr, "symbol_qual_sc %d %s %s %x\n", i, qname, e, st);
+#endif
+	  Delete(qname);
+	}
+      } else if (SwigType_istemplate(e)) {
+	SwigType *ty = Swig_symbol_template_qualify(e, st);
+	Clear(e);
+	Append(e, ty);
+	Delete(ty);
+      }
+      if (strncmp(Char(e), "::", 2) == 0) {
+	Delitem(e, 0);
+	Delitem(e, 0);
+      }
+      Append(result, e);
+    } else if (SwigType_isfunction(e)) {
+      List *parms = SwigType_parmlist(e);
+      String *s = NewString("f(");
+      Iterator pi = First(parms);
+      while (pi.item) {
+	String *pf = Swig_symbol_type_qualify(pi.item, st);
+	Append(s, pf);
+	pi = Next(pi);
+	if (pi.item) {
+	  Append(s, ",");
+	}
+	Delete(pf);
+      }
+      Append(s, ").");
+      Append(result, s);
+      Delete(parms);
+      Delete(s);
+    } else {
+      Append(result, e);
+    }
+  }
+  Delete(elements);
+#ifdef SWIG_DEBUG
+  Printf(stderr, "symbol_qualify %s %s %x %s\n", t, result, st, st ? Getattr(st, "name") : 0);
+#endif
+
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_template_reduce()
+ * Resolves template parameter types
+ * For example:
+ *   typedef int Int;
+ *   typedef Int Integer;
+ * with input:
+ *   Foo<(Int,Integer)> 
+ * returns:
+ *   Foo<(int,int)>
+ * ----------------------------------------------------------------------------- */
+
+static
+SwigType *Swig_symbol_template_reduce(SwigType *qt, Symtab *ntab) {
+  Parm *p;
+  String *templateargs = SwigType_templateargs(qt);
+  List *parms = SwigType_parmlist(templateargs);
+  Iterator pi = First(parms);
+  String *tprefix = SwigType_templateprefix(qt);
+  String *tsuffix = SwigType_templatesuffix(qt);
+  String *qprefix = SwigType_typedef_qualified(tprefix);
+  Append(qprefix, "<(");
+  while ((p = pi.item)) {
+    String *np;
+    String *tp = Swig_symbol_typedef_reduce(p, ntab);
+    String *qp = Swig_symbol_type_qualify(tp, ntab);
+    Node *n = Swig_symbol_clookup(qp, ntab);
+    if (n) {
+      String *qual = Swig_symbol_qualified(n);
+      np = Copy(Getattr(n, "name"));
+      Delete(tp);
+      tp = np;
+      if (qual && Len(qual)) {
+	Insert(np, 0, "::");
+	Insert(np, 0, qual);
+      }
+      Delete(qual);
+    } else {
+      np = qp;
+    }
+    Append(qprefix, np);
+    pi = Next(pi);
+    if (pi.item) {
+      Append(qprefix, ",");
+    }
+    Delete(qp);
+    Delete(tp);
+  }
+  Append(qprefix, ")>");
+  Append(qprefix, tsuffix);
+  Delete(parms);
+  Delete(tprefix);
+  Delete(tsuffix);
+  Delete(templateargs);
+  return qprefix;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_typedef_reduce()
+ *
+ * Chase a typedef through symbol tables looking for a match.
+ * ----------------------------------------------------------------------------- */
+
+SwigType *Swig_symbol_typedef_reduce(SwigType *ty, Symtab *tab) {
+  SwigType *prefix, *base;
+  Node *n;
+  String *nt;
+
+  base = SwigType_base(ty);
+  prefix = SwigType_prefix(ty);
+
+  n = Swig_symbol_clookup(base, tab);
+  if (!n) {
+    if (SwigType_istemplate(ty)) {
+      SwigType *qt = Swig_symbol_template_reduce(base, tab);
+      Append(prefix, qt);
+      Delete(qt);
+#ifdef SWIG_DEBUG
+      Printf(stderr, "symbol_reduce (a) %s %s\n", ty, prefix);
+#endif
+      Delete(base);
+      return prefix;
+    } else {
+      Delete(prefix);
+#ifdef SWIG_DEBUG
+      Printf(stderr, "symbol_reduce (b) %s %s\n", ty, ty);
+#endif
+      return Copy(ty);
+    }
+  }
+  nt = Getattr(n, "nodeType");
+  if (Equal(nt, "using")) {
+    String *uname = Getattr(n, "uname");
+    if (uname) {
+      n = Swig_symbol_clookup(base, Getattr(n, "sym:symtab"));
+      if (!n) {
+	Delete(base);
+	Delete(prefix);
+#ifdef SWIG_DEBUG
+	Printf(stderr, "symbol_reduce (c) %s %s\n", ty, ty);
+#endif
+	return Copy(ty);
+      }
+    }
+  }
+  if (Equal(nt, "cdecl")) {
+    String *storage = Getattr(n, "storage");
+    if (storage && (Equal(storage, "typedef"))) {
+      SwigType *decl;
+      SwigType *rt;
+      SwigType *qt;
+      Symtab *ntab;
+      SwigType *nt = Copy(Getattr(n, "type"));
+
+      /* Fix for case 'typedef struct Hello hello;' */
+      {
+	const char *dclass[3] = { "struct ", "union ", "class " };
+	int i;
+	char *c = Char(nt);
+	for (i = 0; i < 3; i++) {
+	  if (strstr(c, dclass[i]) == c) {
+	    Replace(nt, dclass[i], "", DOH_REPLACE_FIRST);
+	  }
+	}
+      }
+      decl = Getattr(n, "decl");
+      if (decl) {
+	SwigType_push(nt, decl);
+      }
+      SwigType_push(nt, prefix);
+      Delete(base);
+      Delete(prefix);
+      ntab = Getattr(n, "sym:symtab");
+      rt = Swig_symbol_typedef_reduce(nt, ntab);
+      qt = Swig_symbol_type_qualify(rt, ntab);
+      if (SwigType_istemplate(qt)) {
+	SwigType *qtr = Swig_symbol_template_reduce(qt, ntab);
+	Delete(qt);
+	qt = qtr;
+      }
+      Delete(nt);
+      Delete(rt);
+#ifdef SWIG_DEBUG
+      Printf(stderr, "symbol_reduce (d) %s %s\n", qt, ty);
+#endif
+      return qt;
+    }
+  }
+  Delete(base);
+  Delete(prefix);
+#ifdef SWIG_DEBUG
+  Printf(stderr, "symbol_reduce (e) %s %s\n", ty, ty);
+#endif
+  return Copy(ty);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_string_qualify()
+ *
+ * This function takes a string and looks for identifiers.  Identifiers are
+ * then qualified according to scope rules.  This function is used in a number
+ * of settings including expression evaluation, scoping of conversion operators,
+ * and so forth.
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_symbol_string_qualify(String *s, Symtab *st) {
+  int have_id = 0;
+  String *id = NewStringEmpty();
+  String *r = NewStringEmpty();
+  char *c = Char(s);
+  while (*c) {
+    if (isalpha((int) *c) || (*c == '_') || (*c == ':')) {
+      Putc(*c, id);
+      have_id = 1;
+    } else {
+      if (have_id) {
+	String *qid = Swig_symbol_type_qualify(id, st);
+	Append(r, qid);
+	Clear(id);
+	Delete(qid);
+	have_id = 0;
+      }
+      Putc(*c, r);
+    }
+    c++;
+  }
+  if (have_id) {
+    String *qid = Swig_symbol_type_qualify(id, st);
+    Append(r, qid);
+    Delete(qid);
+  }
+  Delete(id);
+  return r;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_template_defargs()
+ *
+ * Apply default arg from generic template default args 
+ * Returns a parameter list which contains missing default arguments (if any)
+ * Note side effects: parms will also contain the extra parameters in its list
+ * (but only if non-zero).
+ * ----------------------------------------------------------------------------- */
+
+
+ParmList *Swig_symbol_template_defargs(Parm *parms, Parm *targs, Symtab *tscope, Symtab *tsdecl) {
+  ParmList *expandedparms = parms;
+  if (Len(parms) < Len(targs)) {
+    Parm *lp = parms;
+    Parm *p = lp;
+    Parm *tp = targs;
+    while (p && tp) {
+      p = nextSibling(p);
+      tp = nextSibling(tp);
+      if (p)
+	lp = p;
+    }
+    while (tp) {
+      String *value = Getattr(tp, "value");
+      if (value) {
+	Parm *cp;
+	Parm *ta = targs;
+	Parm *p = parms;
+	SwigType *nt = Swig_symbol_string_qualify(value, tsdecl);
+	SwigType *ntq = 0;
+#ifdef SWIG_DEBUG
+	Printf(stderr, "value %s %s %s\n", value, nt, tsdecl ? Getattr(tsdecl, "name") : tsdecl);
+#endif
+	while (p && ta) {
+	  String *name = Getattr(ta, "name");
+	  String *pvalue = Getattr(p, "value");
+	  String *value = pvalue ? pvalue : Getattr(p, "type");
+	  String *ttq = Swig_symbol_type_qualify(value, tscope);
+	  /* value = SwigType_typedef_resolve_all(value); */
+	  Replaceid(nt, name, ttq);
+	  p = nextSibling(p);
+	  ta = nextSibling(ta);
+	  Delete(ttq);
+	}
+	ntq = Swig_symbol_type_qualify(nt, tsdecl);
+	if (SwigType_istemplate(ntq)) {
+	  String *ty = Swig_symbol_template_deftype(ntq, tscope);
+	  Delete(ntq);
+	  ntq = ty;
+	}
+	/* Printf(stderr,"value %s %s %s\n",value,ntr,ntq); */
+	cp = NewParm(ntq, 0);
+        if (lp)
+          set_nextSibling(lp, cp);
+        else
+          expandedparms = CopyParm(cp);
+	lp = cp;
+	tp = nextSibling(tp);
+	Delete(cp);
+	Delete(nt);
+	Delete(ntq);
+      } else {
+	tp = 0;
+      }
+    }
+  }
+  return expandedparms;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_symbol_template_deftype()
+ *
+ * Apply default args to generic template type
+ * ----------------------------------------------------------------------------- */
+
+#define SWIG_TEMPLATE_DEFTYPE_CACHE
+SwigType *Swig_symbol_template_deftype(const SwigType *type, Symtab *tscope) {
+  String *result = NewStringEmpty();
+  List *elements = SwigType_split(type);
+  int len = Len(elements);
+  int i;
+#ifdef SWIG_TEMPLATE_DEFTYPE_CACHE
+  static Hash *deftype_cache = 0;
+  String *scopetype = tscope ? NewStringf("%s::%s", Getattr(tscope, "name"), type)
+      : NewStringf("%s::%s", Swig_symbol_getscopename(), type);
+  if (!deftype_cache) {
+    deftype_cache = NewHash();
+  }
+  if (scopetype) {
+    String *cres = Getattr(deftype_cache, scopetype);
+    if (cres) {
+      Append(result, cres);
+      Delete(scopetype);
+      return result;
+    }
+  }
+#endif
+
+#ifdef SWIG_DEBUG
+  Printf(stderr, "finding deftype %s\n", type);
+#endif
+
+  for (i = 0; i < len; i++) {
+    String *e = Getitem(elements, i);
+    if (SwigType_isfunction(e)) {
+      String *s = NewString("f(");
+      List *parms = SwigType_parmlist(e);
+      Iterator pi = First(parms);
+      while (pi.item) {
+	String *pf = SwigType_istemplate(e) ? Swig_symbol_template_deftype(pi.item, tscope)
+	    : Swig_symbol_type_qualify(pi.item, tscope);
+	Append(s, pf);
+	pi = Next(pi);
+	if (pi.item) {
+	  Append(s, ",");
+	}
+	Delete(pf);
+      }
+      Append(s, ").");
+      Append(result, s);
+      Delete(s);
+      Delete(parms);
+    } else if (SwigType_istemplate(e)) {
+      String *prefix = SwigType_prefix(e);
+      String *base = SwigType_base(e);
+      String *tprefix = SwigType_templateprefix(base);
+      String *targs = SwigType_templateargs(base);
+      String *tsuffix = SwigType_templatesuffix(base);
+      ParmList *tparms = SwigType_function_parms(targs);
+      Node *tempn = Swig_symbol_clookup_local(tprefix, tscope);
+      if (!tempn && tsuffix && Len(tsuffix)) {
+	tempn = Swig_symbol_clookup(tprefix, 0);
+      }
+#ifdef SWIG_DEBUG
+      Printf(stderr, "deftype type %s %s %d\n", e, tprefix, (long) tempn);
+#endif
+      if (tempn) {
+	ParmList *tnargs = Getattr(tempn, "templateparms");
+        ParmList *expandedparms;
+	Parm *p;
+	Symtab *tsdecl = Getattr(tempn, "sym:symtab");
+
+#ifdef SWIG_DEBUG
+	Printf(stderr, "deftype type %s %s %s\n", tprefix, targs, tsuffix);
+#endif
+	Append(tprefix, "<(");
+	expandedparms = Swig_symbol_template_defargs(tparms, tnargs, tscope, tsdecl);
+	p = expandedparms;
+	tscope = tsdecl;
+	while (p) {
+	  SwigType *ptype = Getattr(p, "type");
+	  SwigType *ttr = ptype ? ptype : Getattr(p, "value");
+	  SwigType *ttf = Swig_symbol_type_qualify(ttr, tscope);
+	  SwigType *ttq = Swig_symbol_template_param_eval(ttf, tscope);
+#ifdef SWIG_DEBUG
+	  Printf(stderr, "arg type %s\n", ttq);
+#endif
+	  if (SwigType_istemplate(ttq)) {
+	    SwigType *ttd = Swig_symbol_template_deftype(ttq, tscope);
+	    Delete(ttq);
+	    ttq = ttd;
+#ifdef SWIG_DEBUG
+	    Printf(stderr, "arg deftype %s\n", ttq);
+#endif
+	  }
+	  Append(tprefix, ttq);
+	  p = nextSibling(p);
+	  if (p)
+	    Putc(',', tprefix);
+	  Delete(ttf);
+	  Delete(ttq);
+	}
+	Append(tprefix, ")>");
+	Append(tprefix, tsuffix);
+	Append(prefix, tprefix);
+#ifdef SWIG_DEBUG
+	Printf(stderr, "deftype %s %s \n", type, tprefix);
+#endif
+	Append(result, prefix);
+      } else {
+	Append(result, e);
+      }
+      Delete(prefix);
+      Delete(base);
+      Delete(tprefix);
+      Delete(tsuffix);
+      Delete(targs);
+      Delete(tparms);
+    } else {
+      Append(result, e);
+    }
+  }
+  Delete(elements);
+#ifdef SWIG_TEMPLATE_DEFTYPE_CACHE
+  Setattr(deftype_cache, scopetype, result);
+  Delete(scopetype);
+#endif
+
+  return result;
+}
+
+SwigType *Swig_symbol_template_param_eval(const SwigType *p, Symtab *symtab) {
+  String *value = Copy(p);
+  Node *lastnode = 0;
+  while (1) {
+    Node *n = Swig_symbol_clookup(value, symtab);
+    if (n == lastnode)
+      break;
+    lastnode = n;
+    if (n) {
+      String *nt = Getattr(n, "nodeType");
+      if (Equal(nt, "enumitem")) {
+	/* An enum item.   Generate a fully qualified name */
+	String *qn = Swig_symbol_qualified(n);
+	if (qn && Len(qn)) {
+	  Append(qn, "::");
+	  Append(qn, Getattr(n, "name"));
+	  Delete(value);
+	  value = qn;
+	  continue;
+	} else {
+	  Delete(qn);
+	  break;
+	}
+      } else if ((Equal(nt, "cdecl"))) {
+	String *nv = Getattr(n, "value");
+	if (nv) {
+	  Delete(value);
+	  value = Copy(nv);
+	  continue;
+	}
+      }
+    }
+    break;
+  }
+  return value;
+}
diff --git a/trunk/Source/Swig/tree.c b/trunk/Source/Swig/tree.c
new file mode 100644
index 0000000..61dca83
--- /dev/null
+++ b/trunk/Source/Swig/tree.c
@@ -0,0 +1,376 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * tree.c
+ *
+ * This file provides some general purpose functions for manipulating
+ * parse trees.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_tree_c[] = "$Id$";
+
+#include "swig.h"
+#include <stdarg.h>
+#include <assert.h>
+
+/* -----------------------------------------------------------------------------
+ * Swig_print_tags()
+ *
+ * Dump the tag structure of a parse tree to standard output
+ * ----------------------------------------------------------------------------- */
+
+void Swig_print_tags(DOH *obj, DOH *root) {
+  DOH *croot, *newroot;
+  DOH *cobj;
+
+  if (!root)
+    croot = NewStringEmpty();
+  else
+    croot = root;
+
+  while (obj) {
+    Printf(stdout, "%s . %s (%s:%d)\n", croot, nodeType(obj), Getfile(obj), Getline(obj));
+    cobj = firstChild(obj);
+    if (cobj) {
+      newroot = NewStringf("%s . %s", croot, nodeType(obj));
+      Swig_print_tags(cobj, newroot);
+      Delete(newroot);
+    }
+    obj = nextSibling(obj);
+  }
+  if (!root)
+    Delete(croot);
+}
+
+static int indent_level = 0;
+
+static void print_indent(int l) {
+  int i;
+  for (i = 0; i < indent_level; i++) {
+    fputc(' ', stdout);
+  }
+  if (l) {
+    fputc('|', stdout);
+    fputc(' ', stdout);
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_print_node(Node *n)
+ * ----------------------------------------------------------------------------- */
+
+void Swig_print_node(Node *obj) {
+  Iterator ki;
+  Node *cobj;
+
+  print_indent(0);
+  Printf(stdout, "+++ %s ----------------------------------------\n", nodeType(obj));
+  ki = First(obj);
+  while (ki.key) {
+    String *k = ki.key;
+    if ((Cmp(k, "nodeType") == 0) || (Cmp(k, "firstChild") == 0) || (Cmp(k, "lastChild") == 0) ||
+	(Cmp(k, "parentNode") == 0) || (Cmp(k, "nextSibling") == 0) || (Cmp(k, "previousSibling") == 0) || (*(Char(k)) == '$')) {
+      /* Do nothing */
+    } else if (Cmp(k, "parms") == 0) {
+      print_indent(2);
+      Printf(stdout, "%-12s - %s\n", k, ParmList_protostr(Getattr(obj, k)));
+    } else {
+      DOH *o;
+      char *trunc = "";
+      print_indent(2);
+      if (DohIsString(Getattr(obj, k))) {
+	o = Str(Getattr(obj, k));
+	if (Len(o) > 80) {
+	  trunc = "...";
+	}
+	Printf(stdout, "%-12s - \"%(escape)-0.80s%s\"\n", k, o, trunc);
+	Delete(o);
+      } else {
+	Printf(stdout, "%-12s - 0x%x\n", k, Getattr(obj, k));
+      }
+    }
+    ki = Next(ki);
+  }
+  cobj = firstChild(obj);
+  if (cobj) {
+    indent_level += 6;
+    Printf(stdout, "\n");
+    Swig_print_tree(cobj);
+    indent_level -= 6;
+  } else {
+    print_indent(1);
+    Printf(stdout, "\n");
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_print_tree()
+ *
+ * Dump the tree structure of a parse tree to standard output
+ * ----------------------------------------------------------------------------- */
+
+void Swig_print_tree(DOH *obj) {
+  while (obj) {
+    Swig_print_node(obj);
+    obj = nextSibling(obj);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * appendChild()
+ *
+ * Appends a new child to a node
+ * ----------------------------------------------------------------------------- */
+
+void appendChild(Node *node, Node *chd) {
+  Node *lc;
+
+  if (!chd)
+    return;
+
+  lc = lastChild(node);
+  if (!lc) {
+    set_firstChild(node, chd);
+  } else {
+    set_nextSibling(lc, chd);
+    set_previousSibling(chd, lc);
+  }
+  while (chd) {
+    lc = chd;
+    set_parentNode(chd, node);
+    chd = nextSibling(chd);
+  }
+  set_lastChild(node, lc);
+}
+
+/* -----------------------------------------------------------------------------
+ * prependChild()
+ *
+ * Prepends a new child to a node
+ * ----------------------------------------------------------------------------- */
+
+void prependChild(Node *node, Node *chd) {
+  Node *fc;
+
+  if (!chd)
+    return;
+
+  fc = firstChild(node);
+  if (fc) {
+    set_nextSibling(chd, fc);
+    set_previousSibling(fc, chd);
+  }
+  set_firstChild(node, chd);
+  while (chd) {
+    set_parentNode(chd, node);
+    chd = nextSibling(chd);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * removeNode()
+ *
+ * Removes a node from the parse tree.  Detaches it from its parent's child list.
+ * ----------------------------------------------------------------------------- */
+
+void removeNode(Node *n) {
+  Node *parent;
+  Node *prev;
+  Node *next;
+
+  parent = parentNode(n);
+  if (!parent) return;
+
+  prev = previousSibling(n);
+  next = nextSibling(n);
+  if (prev) {
+    set_nextSibling(prev, next);
+  } else {
+    if (parent) {
+      set_firstChild(parent, next);
+    }
+  }
+  if (next) {
+    set_previousSibling(next, prev);
+  } else {
+    if (parent) {
+      set_lastChild(parent, prev);
+    }
+  }
+
+  /* Delete attributes */
+  Delattr(n,"parentNode");
+  Delattr(n,"nextSibling");
+  Delattr(n,"prevSibling");
+}
+
+/* -----------------------------------------------------------------------------
+ * copyNode()
+ *
+ * Copies a node, but only copies simple attributes (no lists, hashes).
+ * ----------------------------------------------------------------------------- */
+
+Node *copyNode(Node *n) {
+  Iterator ki;
+  Node *c = NewHash();
+  for (ki = First(n); ki.key; ki = Next(ki)) {
+    if (DohIsString(ki.item)) {
+      Setattr(c, ki.key, Copy(ki.item));
+    }
+  }
+  Setfile(c, Getfile(n));
+  Setline(c, Getline(n));
+  return c;
+}
+
+/* -----------------------------------------------------------------------------
+ * checkAttribute()
+ * ----------------------------------------------------------------------------- */
+
+int checkAttribute(Node *n, const String_or_char *name, const String_or_char *value) {
+  String *v = Getattr(n, name);
+  return v ? Equal(v, value) : 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_require()
+ * ns   - namespace for the view name for saving any attributes under
+ * n    - node
+ * ...  - list of attribute names of type char*
+ * This method checks that the attribute names exist in the node n and asserts if
+ * not. Assert will only occur unless the attribute is optional. An attribute is
+ * optional if it is prefixed by ?, eg "?value". If the attribute name is prefixed
+ * by * or ?, eg "*value" then a copy of the attribute is saved. The saved
+ * attributes will be restored on a subsequent call to Swig_restore(). All the
+ * saved attributes are saved in the view namespace (prefixed by ns).
+ * This function can be called more than once with different namespaces.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_require(const char *ns, Node *n, ...) {
+  va_list ap;
+  char *name;
+  DOH *obj;
+
+  va_start(ap, n);
+  name = va_arg(ap, char *);
+  while (name) {
+    int newref = 0;
+    int opt = 0;
+    if (*name == '*') {
+      newref = 1;
+      name++;
+    } else if (*name == '?') {
+      newref = 1;
+      opt = 1;
+      name++;
+    }
+    obj = Getattr(n, name);
+    if (!opt && !obj) {
+      Printf(stderr, "%s:%d. Fatal error (Swig_require).  Missing attribute '%s' in node '%s'.\n", Getfile(n), Getline(n), name, nodeType(n));
+      assert(obj);
+    }
+    if (!obj)
+      obj = DohNone;
+    if (newref) {
+      /* Save a copy of the attribute */
+      Setattr(n, NewStringf("%s:%s", ns, name), obj);
+    }
+    name = va_arg(ap, char *);
+  }
+  va_end(ap);
+
+  /* Save the view */
+  {
+    String *view = Getattr(n, "view");
+    if (view) {
+      if (Strcmp(view, ns) != 0) {
+	Setattr(n, NewStringf("%s:view", ns), view);
+	Setattr(n, "view", ns);
+      }
+    } else {
+      Setattr(n, "view", ns);
+    }
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_save()
+ * Same as Swig_require(), but all attribute names are optional and all attributes
+ * are saved, ie behaves as if all the attribute names were prefixed by ?.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_save(const char *ns, Node *n, ...) {
+  va_list ap;
+  char *name;
+  DOH *obj;
+
+  va_start(ap, n);
+  name = va_arg(ap, char *);
+  while (name) {
+    if (*name == '*') {
+      name++;
+    } else if (*name == '?') {
+      name++;
+    }
+    obj = Getattr(n, name);
+    if (!obj)
+      obj = DohNone;
+
+    /* Save a copy of the attribute */
+    if (Setattr(n, NewStringf("%s:%s", ns, name), obj)) {
+      Printf(stderr, "Swig_save('%s','%s'): Warning, attribute '%s' was already saved.\n", ns, nodeType(n), name);
+    }
+    name = va_arg(ap, char *);
+  }
+  va_end(ap);
+
+  /* Save the view */
+  {
+    String *view = Getattr(n, "view");
+    if (view) {
+      if (Strcmp(view, ns) != 0) {
+	Setattr(n, NewStringf("%s:view", ns), view);
+	Setattr(n, "view", ns);
+      }
+    } else {
+      Setattr(n, "view", ns);
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_restore()
+ * Restores attributes saved by a previous call to Swig_require() or Swig_save().
+ * ----------------------------------------------------------------------------- */
+
+void Swig_restore(Node *n) {
+  String *temp;
+  int len;
+  List *l;
+  String *ns;
+  Iterator ki;
+
+  ns = Getattr(n, "view");
+  assert(ns);
+
+  l = NewList();
+
+  temp = NewStringf("%s:", ns);
+  len = Len(temp);
+
+  for (ki = First(n); ki.key; ki = Next(ki)) {
+    if (Strncmp(temp, ki.key, len) == 0) {
+      Append(l, ki.key);
+    }
+  }
+  for (ki = First(l); ki.item; ki = Next(ki)) {
+    DOH *obj = Getattr(n, ki.item);
+    Setattr(n, Char(ki.item) + len, obj);
+    Delattr(n, ki.item);
+  }
+  Delete(l);
+  Delete(temp);
+}
diff --git a/trunk/Source/Swig/typemap.c b/trunk/Source/Swig/typemap.c
new file mode 100644
index 0000000..6cbeb67
--- /dev/null
+++ b/trunk/Source/Swig/typemap.c
@@ -0,0 +1,1893 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typemap.c
+ *
+ * A somewhat generalized implementation of SWIG1.1 typemaps.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_typemap_c[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+#include <ctype.h>
+
+#if 0
+#define SWIG_DEBUG
+#endif
+
+static void replace_embedded_typemap(String *s);
+
+/* -----------------------------------------------------------------------------
+ * Typemaps are stored in a collection of nested hash tables.  Something like
+ * this:
+ *
+ * [ type ]
+ *    +-------- [ name ]
+ *    +-------- [ name ]
+ *    
+ * Each hash table [ type ] or [ name ] then contains references to the
+ * different typemap methods.    These are referenced by names such as
+ * "tmap:in", "tmap:out", "tmap:argout", and so forth.
+ *
+ * The object corresponding to a specific method has the following
+ * attributes:
+ *
+ *    "type"    -  Typemap type
+ *    "pname"   -  Parameter name
+ *    "code"    -  Typemap code
+ *    "typemap" -  Descriptive text describing the actual map
+ *    "locals"  -  Local variables (if any)
+ * 
+ * ----------------------------------------------------------------------------- */
+
+#define MAX_SCOPE  32
+
+
+static Hash *typemaps[MAX_SCOPE];
+static int tm_scope = 0;
+
+static Hash *get_typemap(int tm_scope, SwigType *type) {
+  Hash *tm = 0;
+  SwigType *dtype = 0;
+  if (SwigType_istemplate(type)) {
+    String *ty = Swig_symbol_template_deftype(type, 0);
+    dtype = Swig_symbol_type_qualify(ty, 0);
+    /* Printf(stderr,"gettm %s %s\n", type, dtype); */
+    type = dtype;
+    Delete(ty);
+  }
+  tm = Getattr(typemaps[tm_scope], type);
+
+
+  if (dtype) {
+    if (!tm) {
+      String *t_name = SwigType_templateprefix(type);
+      if (!Equal(t_name, type)) {
+	tm = Getattr(typemaps[tm_scope], t_name);
+      }
+      Delete(t_name);
+    }
+    Delete(dtype);
+  }
+
+  return tm;
+}
+
+static void set_typemap(int tm_scope, SwigType *type, Hash *tm) {
+  SwigType *dtype = 0;
+  if (SwigType_istemplate(type)) {
+    String *ty = Swig_symbol_template_deftype(type, 0);
+    dtype = Swig_symbol_type_qualify(ty, 0);
+    /* Printf(stderr,"settm %s %s\n", type, dtype); */
+    type = dtype;
+    Delete(ty);
+  } else {
+    dtype = Copy(type);
+    type = dtype;
+  }
+  Setattr(typemaps[tm_scope], type, tm);
+  Delete(dtype);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_init()
+ *
+ * Initialize the typemap system
+ * ----------------------------------------------------------------------------- */
+
+void Swig_typemap_init() {
+  int i;
+  for (i = 0; i < MAX_SCOPE; i++) {
+    typemaps[i] = 0;
+  }
+  typemaps[0] = NewHash();
+  tm_scope = 0;
+}
+
+static String *tmop_name(const String_or_char *op) {
+  static Hash *names = 0;
+  String *s;
+  /* Due to "interesting" object-identity semantics of DOH,
+     we have to make sure that we only intern strings without object
+     identity into the hash table.
+
+     (Swig_typemap_attach_kwargs calls tmop_name several times with
+     the "same" String *op (i.e., same object identity) but differing
+     string values.)
+
+     Most other callers work around this by using char* rather than
+     String *.
+     -- mkoeppe, Jun 17, 2003
+   */
+  const char *op_without_object_identity = Char(op);
+  if (!names)
+    names = NewHash();
+  s = Getattr(names, op_without_object_identity);
+  if (s)
+    return s;
+  s = NewStringf("tmap:%s", op);
+  Setattr(names, op_without_object_identity, s);
+  Delete(s);
+  return s;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_new_scope()
+ * 
+ * Create a new typemap scope
+ * ----------------------------------------------------------------------------- */
+
+void Swig_typemap_new_scope() {
+  tm_scope++;
+  typemaps[tm_scope] = NewHash();
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_pop_scope()
+ *
+ * Pop the last typemap scope off
+ * ----------------------------------------------------------------------------- */
+
+Hash *Swig_typemap_pop_scope() {
+  if (tm_scope > 0) {
+    return typemaps[tm_scope--];
+  }
+  return 0;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * Swig_typemap_register()
+ *
+ * Add a new multi-valued typemap
+ * ----------------------------------------------------------------------------- */
+
+void Swig_typemap_register(const String_or_char *op, ParmList *parms, String_or_char *code, ParmList *locals, ParmList *kwargs) {
+  Hash *tm;
+  Hash *tm1;
+  Hash *tm2;
+  Parm *np;
+  String *tmop;
+  SwigType *type;
+  String *pname;
+
+  if (!parms)
+    return;
+  tmop = tmop_name(op);
+
+  /* Register the first type in the parameter list */
+
+  type = Getattr(parms, "type");
+  pname = Getattr(parms, "name");
+
+  /* See if this type has been seen before */
+  tm = get_typemap(tm_scope, type);
+  if (!tm) {
+    tm = NewHash();
+    set_typemap(tm_scope, type, tm);
+    Delete(tm);
+  }
+  if (pname) {
+    /* See if parameter has been seen before */
+    tm1 = Getattr(tm, pname);
+    if (!tm1) {
+      tm1 = NewHash();
+      Setattr(tm, pname, tm1);
+      Delete(tm1);
+    }
+    tm = tm1;
+  }
+
+  /* Now see if this typemap op has been seen before */
+  tm2 = Getattr(tm, tmop);
+  if (!tm2) {
+    tm2 = NewHash();
+    Setattr(tm, tmop, tm2);
+    Delete(tm2);
+  }
+
+  /* For a multi-valued typemap, the typemap code and information
+     is really only stored in the last argument.  However, to
+     make this work, we perform a really neat trick using
+     the typemap operator name.
+
+     For example, consider this typemap
+
+     %typemap(in) (int foo, int *bar, char *blah[]) {
+     ...
+     }
+
+     To store it, we look at typemaps for the following:
+
+     operator                  type-name
+     ----------------------------------------------
+     "in"                      int foo
+     "in-int+foo:"             int *bar
+     "in-int+foo:-p.int+bar:   char *blah[]
+
+     Notice how the operator expands to encode information about
+     previous arguments.        
+
+   */
+
+  np = nextSibling(parms);
+  if (np) {
+    /* Make an entirely new operator key */
+    String *newop = NewStringf("%s-%s+%s:", op, type, pname);
+    /* Now reregister on the remaining arguments */
+    Swig_typemap_register(newop, np, code, locals, kwargs);
+
+    /*    Setattr(tm2,newop,newop); */
+    Delete(newop);
+  } else {
+    String *str = SwigType_str(type, pname);
+    String *typemap = NewStringf("typemap(%s) %s", op, str);
+    ParmList *clocals = CopyParmList(locals);
+    ParmList *ckwargs = CopyParmList(kwargs);
+
+    Setattr(tm2, "code", code);
+    Setattr(tm2, "type", type);
+    Setattr(tm2, "typemap", typemap);
+    if (pname) {
+      Setattr(tm2, "pname", pname);
+    }
+    Setattr(tm2, "locals", clocals);
+    Setattr(tm2, "kwargs", ckwargs);
+
+    Delete(clocals);
+    Delete(ckwargs);
+
+    Delete(str);
+    Delete(typemap);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_get()
+ *
+ * Retrieve typemap information from current scope.
+ * ----------------------------------------------------------------------------- */
+
+static Hash *Swig_typemap_get(SwigType *type, String_or_char *name, int scope) {
+  Hash *tm, *tm1;
+  /* See if this type has been seen before */
+  if ((scope < 0) || (scope > tm_scope))
+    return 0;
+  tm = get_typemap(scope, type);
+  if (!tm) {
+    return 0;
+  }
+  if ((name) && Len(name)) {
+    tm1 = Getattr(tm, name);
+    return tm1;
+  }
+  return tm;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_copy()
+ *
+ * Copy a typemap
+ * ----------------------------------------------------------------------------- */
+
+int Swig_typemap_copy(const String_or_char *op, ParmList *srcparms, ParmList *parms) {
+  Hash *tm = 0;
+  String *tmop;
+  Parm *p;
+  String *pname;
+  SwigType *ptype;
+  int ts = tm_scope;
+  String *tmops, *newop;
+  if (ParmList_len(parms) != ParmList_len(srcparms))
+    return -1;
+
+  tmop = tmop_name(op);
+  while (ts >= 0) {
+    p = srcparms;
+    tmops = NewString(tmop);
+    while (p) {
+      ptype = Getattr(p, "type");
+      pname = Getattr(p, "name");
+
+      /* Lookup the type */
+      tm = Swig_typemap_get(ptype, pname, ts);
+      if (!tm)
+	break;
+
+      tm = Getattr(tm, tmops);
+      if (!tm)
+	break;
+
+      /* Got a match.  Look for next typemap */
+      newop = NewStringf("%s-%s+%s:", tmops, ptype, pname);
+      Delete(tmops);
+      tmops = newop;
+      p = nextSibling(p);
+    }
+    Delete(tmops);
+
+    if (!p && tm) {
+
+      /* Got some kind of match */
+      Swig_typemap_register(op, parms, Getattr(tm, "code"), Getattr(tm, "locals"), Getattr(tm, "kwargs"));
+      return 0;
+    }
+    ts--;
+  }
+  /* Not found */
+  return -1;
+
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_clear()
+ *
+ * Delete a multi-valued typemap
+ * ----------------------------------------------------------------------------- */
+
+void Swig_typemap_clear(const String_or_char *op, ParmList *parms) {
+  SwigType *type;
+  String *name;
+  Parm *p;
+  String *newop;
+  Hash *tm = 0;
+
+  /* This might not work */
+  newop = NewString(op);
+  p = parms;
+  while (p) {
+    type = Getattr(p, "type");
+    name = Getattr(p, "name");
+    tm = Swig_typemap_get(type, name, tm_scope);
+    if (!tm)
+      return;
+    p = nextSibling(p);
+    if (p)
+      Printf(newop, "-%s+%s:", type, name);
+  }
+  if (tm) {
+    tm = Getattr(tm, tmop_name(newop));
+    if (tm) {
+      Delattr(tm, "code");
+      Delattr(tm, "locals");
+      Delattr(tm, "kwargs");
+    }
+  }
+  Delete(newop);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_apply()
+ *
+ * Multi-argument %apply directive.  This is pretty horrible so I sure hope
+ * it works.
+ * ----------------------------------------------------------------------------- */
+
+static
+int count_args(String *s) {
+  /* Count up number of arguments */
+  int na = 0;
+  char *c = Char(s);
+  while (*c) {
+    if (*c == '+')
+      na++;
+    c++;
+  }
+  return na;
+}
+
+int Swig_typemap_apply(ParmList *src, ParmList *dest) {
+  String *ssig, *dsig;
+  Parm *p, *np, *lastp, *dp, *lastdp = 0;
+  int narg = 0;
+  int ts = tm_scope;
+  SwigType *type = 0, *name;
+  Hash *tm, *sm;
+  int match = 0;
+
+  /*  Printf(stdout,"apply : %s --> %s\n", ParmList_str(src), ParmList_str(dest)); */
+
+  /* Create type signature of source */
+  ssig = NewStringEmpty();
+  dsig = NewStringEmpty();
+  p = src;
+  dp = dest;
+  lastp = 0;
+  while (p) {
+    lastp = p;
+    lastdp = dp;
+    np = nextSibling(p);
+    if (np) {
+      Printf(ssig, "-%s+%s:", Getattr(p, "type"), Getattr(p, "name"));
+      Printf(dsig, "-%s+%s:", Getattr(dp, "type"), Getattr(dp, "name"));
+      narg++;
+    }
+    p = np;
+    dp = nextSibling(dp);
+  }
+
+  /* make sure a typemap node exists for the last destination node */
+  type = Getattr(lastdp, "type");
+  tm = get_typemap(tm_scope, type);
+  if (!tm) {
+    tm = NewHash();
+    set_typemap(tm_scope, type, tm);
+    Delete(tm);
+  }
+  name = Getattr(lastdp, "name");
+  if (name) {
+    Hash *tm1 = Getattr(tm, name);
+    if (!tm1) {
+      tm1 = NewHash();
+      Setattr(tm, NewString(name), tm1);
+      Delete(tm1);
+    }
+    tm = tm1;
+  }
+
+  /* This is a little nasty.  We need to go searching for all possible typemaps in the
+     source and apply them to the target */
+
+  type = Getattr(lastp, "type");
+  name = Getattr(lastp, "name");
+
+  while (ts >= 0) {
+
+    /* See if there is a matching typemap in this scope */
+    sm = Swig_typemap_get(type, name, ts);
+
+    /* if there is not matching, look for a typemap in the
+       original typedef, if any, like in:
+
+       typedef unsigned long size_t;
+       ...
+       %apply(size_t) {my_size};  ==>  %apply(unsigned long) {my_size};
+     */
+    if (!sm) {
+      SwigType *ntype = SwigType_typedef_resolve(type);
+      if (ntype && (Cmp(ntype, type) != 0)) {
+	sm = Swig_typemap_get(ntype, name, ts);
+      }
+      Delete(ntype);
+    }
+
+    if (sm) {
+      /* Got a typemap.  Need to only merge attributes for methods that match our signature */
+      Iterator ki;
+      match = 1;
+      for (ki = First(sm); ki.key; ki = Next(ki)) {
+	/* Check for a signature match with the source signature */
+	if ((count_args(ki.key) == narg) && (Strstr(ki.key, ssig))) {
+	  String *oldm;
+	  /* A typemap we have to copy */
+	  String *nkey = Copy(ki.key);
+	  Replace(nkey, ssig, dsig, DOH_REPLACE_ANY);
+
+	  /* Make sure the typemap doesn't already exist in the target map */
+
+	  oldm = Getattr(tm, nkey);
+	  if (!oldm || (!Getattr(tm, "code"))) {
+	    String *code;
+	    ParmList *locals;
+	    ParmList *kwargs;
+	    Hash *sm1 = ki.item;
+
+	    code = Getattr(sm1, "code");
+	    locals = Getattr(sm1, "locals");
+	    kwargs = Getattr(sm1, "kwargs");
+	    if (code) {
+	      Replace(nkey, dsig, "", DOH_REPLACE_ANY);
+	      Replace(nkey, "tmap:", "", DOH_REPLACE_ANY);
+	      Swig_typemap_register(nkey, dest, code, locals, kwargs);
+	    }
+	  }
+	  Delete(nkey);
+	}
+      }
+    }
+    ts--;
+  }
+  Delete(ssig);
+  Delete(dsig);
+  return match;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_clear_apply()
+ *
+ * %clear directive.   Clears all typemaps for a type (in the current scope only).    
+ * ----------------------------------------------------------------------------- */
+
+/* Multi-argument %clear directive */
+void Swig_typemap_clear_apply(Parm *parms) {
+  String *tsig;
+  Parm *p, *np, *lastp;
+  int narg = 0;
+  Hash *tm;
+  String *name;
+
+  /* Create a type signature of the parameters */
+  tsig = NewStringEmpty();
+  p = parms;
+  lastp = 0;
+  while (p) {
+    lastp = p;
+    np = nextSibling(p);
+    if (np) {
+      Printf(tsig, "-%s+%s:", Getattr(p, "type"), Getattr(p, "name"));
+      narg++;
+    }
+    p = np;
+  }
+  tm = get_typemap(tm_scope, Getattr(lastp, "type"));
+  if (!tm) {
+    Delete(tsig);
+    return;
+  }
+  name = Getattr(lastp, "name");
+  if (name) {
+    tm = Getattr(tm, name);
+  }
+  if (tm) {
+    /* Clear typemaps that match our signature */
+    Iterator ki, ki2;
+    char *ctsig = Char(tsig);
+    for (ki = First(tm); ki.key; ki = Next(ki)) {
+      char *ckey = Char(ki.key);
+      if (strncmp(ckey, "tmap:", 5) == 0) {
+	int na = count_args(ki.key);
+	if ((na == narg) && strstr(ckey, ctsig)) {
+	  Hash *h = ki.item;
+	  for (ki2 = First(h); ki2.key; ki2 = Next(ki2)) {
+	    Delattr(h, ki2.key);
+	  }
+	}
+      }
+    }
+  }
+  Delete(tsig);
+}
+
+/* Internal function to strip array dimensions. */
+static SwigType *strip_arrays(SwigType *type) {
+  SwigType *t;
+  int ndim;
+  int i;
+  t = Copy(type);
+  ndim = SwigType_array_ndim(t);
+  for (i = 0; i < ndim; i++) {
+    SwigType_array_setdim(t, i, "ANY");
+  }
+  return t;
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_search()
+ *
+ * Search for a typemap match.    Tries to find the most specific typemap
+ * that includes a 'code' attribute.
+ * ----------------------------------------------------------------------------- */
+
+Hash *Swig_typemap_search(const String_or_char *op, SwigType *type, const String_or_char *name, SwigType **matchtype) {
+  Hash *result = 0, *tm, *tm1, *tma;
+  Hash *backup = 0;
+  SwigType *noarrays = 0;
+  SwigType *primitive = 0;
+  SwigType *ctype = 0;
+  int ts;
+  int isarray;
+  const String *cname = 0;
+  SwigType *unstripped = 0;
+  String *tmop = tmop_name(op);
+
+  if ((name) && Len(name))
+    cname = name;
+  ts = tm_scope;
+
+  while (ts >= 0) {
+    ctype = type;
+    while (ctype) {
+      /* Try to get an exact type-match */
+      tm = get_typemap(ts, ctype);
+      if (tm && cname) {
+	tm1 = Getattr(tm, cname);
+	if (tm1) {
+	  result = Getattr(tm1, tmop);	/* See if there is a type-name match */
+	  if (result && Getattr(result, "code"))
+	    goto ret_result;
+	  if (result)
+	    backup = result;
+	}
+      }
+      if (tm) {
+	result = Getattr(tm, tmop);	/* See if there is simply a type match */
+	if (result && Getattr(result, "code"))
+	  goto ret_result;
+	if (result)
+	  backup = result;
+      }
+      isarray = SwigType_isarray(ctype);
+      if (isarray) {
+	/* If working with arrays, strip away all of the dimensions and replace with "ANY".
+	   See if that generates a match */
+	if (!noarrays) {
+	  noarrays = strip_arrays(ctype);
+	}
+	tma = get_typemap(ts, noarrays);
+	if (tma && cname) {
+	  tm1 = Getattr(tma, cname);
+	  if (tm1) {
+	    result = Getattr(tm1, tmop);	/* type-name match */
+	    if (result && Getattr(result, "code"))
+	      goto ret_result;
+	    if (result)
+	      backup = result;
+	  }
+	}
+	if (tma) {
+	  result = Getattr(tma, tmop);	/* type match */
+	  if (result && Getattr(result, "code"))
+	    goto ret_result;
+	  if (result)
+	    backup = result;
+	}
+	Delete(noarrays);
+	noarrays = 0;
+      }
+
+      /* No match so far.   If the type is unstripped, we'll strip its
+         qualifiers and check.   Otherwise, we'll try to resolve a typedef */
+
+      if (!unstripped) {
+	unstripped = ctype;
+	ctype = SwigType_strip_qualifiers(ctype);
+	if (!Equal(ctype, unstripped))
+	  continue;		/* Types are different */
+	Delete(ctype);
+	ctype = unstripped;
+	unstripped = 0;
+      }
+      {
+	String *octype;
+	if (unstripped) {
+	  Delete(ctype);
+	  ctype = unstripped;
+	  unstripped = 0;
+	}
+	octype = ctype;
+	ctype = SwigType_typedef_resolve(ctype);
+	if (octype != type)
+	  Delete(octype);
+      }
+    }
+
+    /* Hmmm. Well, no match seems to be found at all. See if there is some kind of default mapping */
+
+    primitive = SwigType_default(type);
+    while (primitive) {
+      tm = get_typemap(ts, primitive);
+      if (tm && cname) {
+	tm1 = Getattr(tm, cname);
+	if (tm1) {
+	  result = Getattr(tm1, tmop);	/* See if there is a type-name match */
+	  if (result)
+	    goto ret_result;
+	}
+      }
+      if (tm) {			/* See if there is simply a type match */
+	result = Getattr(tm, tmop);
+	if (result)
+	  goto ret_result;
+      }
+      {
+	SwigType *nprim = SwigType_default(primitive);
+	Delete(primitive);
+	primitive = nprim;
+      }
+    }
+    if (ctype != type) {
+      Delete(ctype);
+      ctype = 0;
+    }
+    ts--;			/* Hmmm. Nothing found in this scope.  Guess we'll go try another scope */
+  }
+  result = backup;
+
+ret_result:
+  if (noarrays)
+    Delete(noarrays);
+  if (primitive)
+    Delete(primitive);
+  if ((unstripped) && (unstripped != type))
+    Delete(unstripped);
+  if (matchtype) {
+    *matchtype = Copy(ctype);
+  }
+  if (type != ctype)
+    Delete(ctype);
+  return result;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_search_multi()
+ *
+ * Search for a multi-valued typemap.
+ * ----------------------------------------------------------------------------- */
+
+Hash *Swig_typemap_search_multi(const String_or_char *op, ParmList *parms, int *nmatch) {
+  SwigType *type;
+  SwigType *mtype = 0;
+  String *name;
+  String *newop;
+  Hash *tm, *tm1;
+
+  if (!parms) {
+    *nmatch = 0;
+    return 0;
+  }
+  type = Getattr(parms, "type");
+  name = Getattr(parms, "name");
+
+  /* Try to find a match on the first type */
+  tm = Swig_typemap_search(op, type, name, &mtype);
+  if (tm) {
+    if (mtype && SwigType_isarray(mtype)) {
+      Setattr(parms, "tmap:match", mtype);
+    }
+    Delete(mtype);
+    newop = NewStringf("%s-%s+%s:", op, type, name);
+    tm1 = Swig_typemap_search_multi(newop, nextSibling(parms), nmatch);
+    if (tm1)
+      tm = tm1;
+    if (Getattr(tm, "code")) {
+      *(nmatch) = *nmatch + 1;
+    } else {
+      tm = 0;
+    }
+    Delete(newop);
+  }
+  return tm;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * typemap_replace_vars()
+ *
+ * Replaces typemap variables on a string.  index is the $n variable.
+ * type and pname are the type and parameter name.
+ * ----------------------------------------------------------------------------- */
+
+static
+void replace_local_types(ParmList *p, const String *name, const String *rep) {
+  SwigType *t;
+  while (p) {
+    t = Getattr(p, "type");
+    Replace(t, name, rep, DOH_REPLACE_ANY);
+    p = nextSibling(p);
+  }
+}
+
+static
+int check_locals(ParmList *p, const char *s) {
+  while (p) {
+    char *c = GetChar(p, "type");
+    if (strstr(c, s))
+      return 1;
+    p = nextSibling(p);
+  }
+  return 0;
+}
+
+static
+int typemap_replace_vars(String *s, ParmList *locals, SwigType *type, SwigType *rtype, String *pname, String *lname, int index) {
+  char var[512];
+  char *varname;
+  SwigType *ftype;
+  int bare_substitution_count = 0;
+
+  Replaceall(s, "$typemap", "$TYPEMAP");
+
+  ftype = SwigType_typedef_resolve_all(type);
+
+  if (!pname)
+    pname = lname;
+  {
+    Parm *p;
+    int rep = 0;
+    p = locals;
+    while (p) {
+      if (Strchr(Getattr(p, "type"), '$'))
+	rep = 1;
+      p = nextSibling(p);
+    }
+    if (!rep)
+      locals = 0;
+  }
+
+  sprintf(var, "$%d_", index);
+  varname = &var[strlen(var)];
+
+  /* If the original datatype was an array. We're going to go through and substitute
+     its array dimensions */
+
+  if (SwigType_isarray(type) || SwigType_isarray(ftype)) {
+    String *size;
+    int ndim;
+    int i;
+    if (SwigType_array_ndim(type) != SwigType_array_ndim(ftype))
+      type = ftype;
+    ndim = SwigType_array_ndim(type);
+    size = NewStringEmpty();
+    for (i = 0; i < ndim; i++) {
+      String *dim = SwigType_array_getdim(type, i);
+      if (index == 1) {
+	char t[32];
+	sprintf(t, "$dim%d", i);
+	Replace(s, t, dim, DOH_REPLACE_ANY);
+	replace_local_types(locals, t, dim);
+      }
+      sprintf(varname, "dim%d", i);
+      Replace(s, var, dim, DOH_REPLACE_ANY);
+      replace_local_types(locals, var, dim);
+      if (Len(size))
+	Putc('*', size);
+      Append(size, dim);
+      Delete(dim);
+    }
+    sprintf(varname, "size");
+    Replace(s, var, size, DOH_REPLACE_ANY);
+    replace_local_types(locals, var, size);
+    Delete(size);
+  }
+
+  /* Parameter name substitution */
+  if (index == 1) {
+    Replace(s, "$parmname", pname, DOH_REPLACE_ANY);
+  }
+  strcpy(varname, "name");
+  Replace(s, var, pname, DOH_REPLACE_ANY);
+
+  /* Type-related stuff */
+  {
+    SwigType *star_type, *amp_type, *base_type, *lex_type;
+    SwigType *ltype, *star_ltype, *amp_ltype;
+    String *mangle, *star_mangle, *amp_mangle, *base_mangle, *base_name;
+    String *descriptor, *star_descriptor, *amp_descriptor;
+    String *ts;
+    char *sc;
+
+    sc = Char(s);
+
+    if (strstr(sc, "type") || check_locals(locals, "type")) {
+      /* Given type : $type */
+      ts = SwigType_str(type, 0);
+      if (index == 1) {
+	Replace(s, "$type", ts, DOH_REPLACE_ANY);
+	replace_local_types(locals, "$type", type);
+      }
+      strcpy(varname, "type");
+      Replace(s, var, ts, DOH_REPLACE_ANY);
+      replace_local_types(locals, var, type);
+      Delete(ts);
+      sc = Char(s);
+    }
+    if (strstr(sc, "ltype") || check_locals(locals, "ltype")) {
+      /* Local type:  $ltype */
+      ltype = SwigType_ltype(type);
+      ts = SwigType_str(ltype, 0);
+      if (index == 1) {
+	Replace(s, "$ltype", ts, DOH_REPLACE_ANY);
+	replace_local_types(locals, "$ltype", ltype);
+      }
+      strcpy(varname, "ltype");
+      Replace(s, var, ts, DOH_REPLACE_ANY);
+      replace_local_types(locals, var, ltype);
+      Delete(ts);
+      Delete(ltype);
+      sc = Char(s);
+    }
+    if (strstr(sc, "mangle") || strstr(sc, "descriptor")) {
+      /* Mangled type */
+
+      mangle = SwigType_manglestr(type);
+      if (index == 1)
+	Replace(s, "$mangle", mangle, DOH_REPLACE_ANY);
+      strcpy(varname, "mangle");
+      Replace(s, var, mangle, DOH_REPLACE_ANY);
+
+      descriptor = NewStringf("SWIGTYPE%s", mangle);
+
+      if (index == 1)
+	if (Replace(s, "$descriptor", descriptor, DOH_REPLACE_ANY))
+	  SwigType_remember(type);
+
+      strcpy(varname, "descriptor");
+      if (Replace(s, var, descriptor, DOH_REPLACE_ANY))
+	SwigType_remember(type);
+
+      Delete(descriptor);
+      Delete(mangle);
+    }
+
+    /* One pointer level removed */
+    /* This creates variables of the form
+       $*n_type
+       $*n_ltype
+     */
+
+    if (SwigType_ispointer(ftype) || (SwigType_isarray(ftype)) || (SwigType_isreference(ftype))) {
+      if (!(SwigType_isarray(type) || SwigType_ispointer(type) || SwigType_isreference(type))) {
+	star_type = Copy(ftype);
+      } else {
+	star_type = Copy(type);
+      }
+      if (!SwigType_isreference(star_type)) {
+	if (SwigType_isarray(star_type)) {
+	  SwigType_del_element(star_type);
+	} else {
+	  SwigType_del_pointer(star_type);
+	}
+	ts = SwigType_str(star_type, 0);
+	if (index == 1) {
+	  Replace(s, "$*type", ts, DOH_REPLACE_ANY);
+	  replace_local_types(locals, "$*type", star_type);
+	}
+	sprintf(varname, "$*%d_type", index);
+	Replace(s, varname, ts, DOH_REPLACE_ANY);
+	replace_local_types(locals, varname, star_type);
+	Delete(ts);
+      } else {
+	SwigType_del_element(star_type);
+      }
+      star_ltype = SwigType_ltype(star_type);
+      ts = SwigType_str(star_ltype, 0);
+      if (index == 1) {
+	Replace(s, "$*ltype", ts, DOH_REPLACE_ANY);
+	replace_local_types(locals, "$*ltype", star_ltype);
+      }
+      sprintf(varname, "$*%d_ltype", index);
+      Replace(s, varname, ts, DOH_REPLACE_ANY);
+      replace_local_types(locals, varname, star_ltype);
+      Delete(ts);
+      Delete(star_ltype);
+
+      star_mangle = SwigType_manglestr(star_type);
+      if (index == 1)
+	Replace(s, "$*mangle", star_mangle, DOH_REPLACE_ANY);
+
+      sprintf(varname, "$*%d_mangle", index);
+      Replace(s, varname, star_mangle, DOH_REPLACE_ANY);
+
+      star_descriptor = NewStringf("SWIGTYPE%s", star_mangle);
+      if (index == 1)
+	if (Replace(s, "$*descriptor", star_descriptor, DOH_REPLACE_ANY))
+	  SwigType_remember(star_type);
+      sprintf(varname, "$*%d_descriptor", index);
+      if (Replace(s, varname, star_descriptor, DOH_REPLACE_ANY))
+	SwigType_remember(star_type);
+
+      Delete(star_descriptor);
+      Delete(star_mangle);
+      Delete(star_type);
+    } else {
+      /* TODO: Signal error if one of the $* substitutions is
+         requested */
+    }
+    /* One pointer level added */
+    amp_type = Copy(type);
+    SwigType_add_pointer(amp_type);
+    ts = SwigType_str(amp_type, 0);
+    if (index == 1) {
+      Replace(s, "$&type", ts, DOH_REPLACE_ANY);
+      replace_local_types(locals, "$&type", amp_type);
+    }
+    sprintf(varname, "$&%d_type", index);
+    Replace(s, varname, ts, DOH_REPLACE_ANY);
+    replace_local_types(locals, varname, amp_type);
+    Delete(ts);
+
+    amp_ltype = SwigType_ltype(type);
+    SwigType_add_pointer(amp_ltype);
+    ts = SwigType_str(amp_ltype, 0);
+
+    if (index == 1) {
+      Replace(s, "$&ltype", ts, DOH_REPLACE_ANY);
+      replace_local_types(locals, "$&ltype", amp_ltype);
+    }
+    sprintf(varname, "$&%d_ltype", index);
+    Replace(s, varname, ts, DOH_REPLACE_ANY);
+    replace_local_types(locals, varname, amp_ltype);
+    Delete(ts);
+    Delete(amp_ltype);
+
+    amp_mangle = SwigType_manglestr(amp_type);
+    if (index == 1)
+      Replace(s, "$&mangle", amp_mangle, DOH_REPLACE_ANY);
+    sprintf(varname, "$&%d_mangle", index);
+    Replace(s, varname, amp_mangle, DOH_REPLACE_ANY);
+
+    amp_descriptor = NewStringf("SWIGTYPE%s", amp_mangle);
+    if (index == 1)
+      if (Replace(s, "$&descriptor", amp_descriptor, DOH_REPLACE_ANY))
+	SwigType_remember(amp_type);
+    sprintf(varname, "$&%d_descriptor", index);
+    if (Replace(s, varname, amp_descriptor, DOH_REPLACE_ANY))
+      SwigType_remember(amp_type);
+
+    Delete(amp_descriptor);
+    Delete(amp_mangle);
+    Delete(amp_type);
+
+    /* Base type */
+    if (SwigType_isarray(type)) {
+      SwigType *bt = Copy(type);
+      Delete(SwigType_pop_arrays(bt));
+      base_type = SwigType_str(bt, 0);
+      Delete(bt);
+    } else {
+      base_type = SwigType_base(type);
+    }
+
+    base_name = SwigType_namestr(base_type);
+    if (index == 1) {
+      Replace(s, "$basetype", base_name, DOH_REPLACE_ANY);
+      replace_local_types(locals, "$basetype", base_name);
+    }
+    strcpy(varname, "basetype");
+    Replace(s, var, base_type, DOH_REPLACE_ANY);
+    replace_local_types(locals, var, base_name);
+
+    base_mangle = SwigType_manglestr(base_type);
+    if (index == 1)
+      Replace(s, "$basemangle", base_mangle, DOH_REPLACE_ANY);
+    strcpy(varname, "basemangle");
+    Replace(s, var, base_mangle, DOH_REPLACE_ANY);
+    Delete(base_mangle);
+    Delete(base_type);
+    Delete(base_name);
+
+    lex_type = SwigType_base(rtype);
+    if (index == 1)
+      Replace(s, "$lextype", lex_type, DOH_REPLACE_ANY);
+    strcpy(varname, "lextype");
+    Replace(s, var, lex_type, DOH_REPLACE_ANY);
+    Delete(lex_type);
+  }
+
+  /* Replace any $n. with (&n)-> */
+  {
+    char temp[64];
+    sprintf(var, "$%d.", index);
+    sprintf(temp, "(&$%d)->", index);
+    Replace(s, var, temp, DOH_REPLACE_ANY);
+  }
+
+  /* Replace the bare $n variable */
+  sprintf(var, "$%d", index);
+  bare_substitution_count = Replace(s, var, lname, DOH_REPLACE_ANY);
+  Delete(ftype);
+  return bare_substitution_count;
+}
+
+/* ------------------------------------------------------------------------
+ * static typemap_locals()
+ *
+ * Takes a string, a parameter list and a wrapper function argument and
+ * creates the local variables.
+ * ------------------------------------------------------------------------ */
+
+static void typemap_locals(DOHString * s, ParmList *l, Wrapper *f, int argnum) {
+  Parm *p;
+  char *new_name;
+
+  p = l;
+  while (p) {
+    SwigType *pt = Getattr(p, "type");
+    SwigType *at = SwigType_alttype(pt, 1);
+    String *pn = Getattr(p, "name");
+    String *value = Getattr(p, "value");
+    if (at)
+      pt = at;
+    if (pn) {
+      if (Len(pn) > 0) {
+	String *str;
+	int isglobal = 0;
+
+	str = NewStringEmpty();
+
+	if (strncmp(Char(pn), "_global_", 8) == 0) {
+	  isglobal = 1;
+	}
+
+	/* If the user gave us $type as the name of the local variable, we'll use
+	   the passed datatype instead */
+
+	if ((argnum >= 0) && (!isglobal)) {
+	  Printf(str, "%s%d", pn, argnum);
+	} else {
+	  Append(str, pn);
+	}
+	if (isglobal && Wrapper_check_local(f, str)) {
+	  p = nextSibling(p);
+	  Delete(str);
+	  if (at)
+	    Delete(at);
+	  continue;
+	}
+	if (value) {
+	  String *pstr = SwigType_str(pt, str);
+	  new_name = Wrapper_new_localv(f, str, pstr, "=", value, NIL);
+	  Delete(pstr);
+	} else {
+	  String *pstr = SwigType_str(pt, str);
+	  new_name = Wrapper_new_localv(f, str, pstr, NIL);
+	  Delete(pstr);
+	}
+	if (!isglobal) {
+	  /* Substitute  */
+	  Replace(s, pn, new_name, DOH_REPLACE_ID | DOH_REPLACE_NOQUOTE);
+	}
+	Delete(str);
+      }
+    }
+    p = nextSibling(p);
+    if (at)
+      Delete(at);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_lookup()
+ *
+ * Attach one or more typemaps to a node and optionally generate the typemap contents
+ * into the wrapper.
+ * op         - typemap name, eg "out", "newfree"
+ * node       - the node to attach the typemaps to
+ * lname      - name of variable to substitute $1, $2 etc for
+ * f          - wrapper code to generate into if non null
+ * actioncode - code to generate into f before the out typemap code, unless
+ *              the optimal attribute is set in the out typemap in which case
+ *              $1 in the out typemap will be replaced  by the code in actioncode.
+ * ----------------------------------------------------------------------------- */
+
+static String *Swig_typemap_lookup_impl(const String_or_char *op, Node *node, const String_or_char *lname, Wrapper *f, String *actioncode) {
+  SwigType *type;
+  SwigType *mtype = 0;
+  String *pname;
+  Hash *tm = 0;
+  String *s = 0;
+  String *sdef = 0;
+  ParmList *locals;
+  ParmList *kw;
+  char temp[256];
+  String *symname;
+  String *cname = 0;
+  String *clname = 0;
+  char *cop = Char(op);
+  int optimal_attribute = 0;
+  int optimal_substitution = 0;
+  int num_substitutions = 0;
+
+  /* special case, we need to check for 'ref' call 
+     and set the default code 'sdef' */
+  if (node && Cmp(op, "newfree") == 0) {
+    sdef = Swig_ref_call(node, lname);
+  }
+
+  type = Getattr(node, "type");
+  if (!type)
+    return sdef;
+
+  pname = Getattr(node, "name");
+
+#if 1
+  if (pname && node && checkAttribute(node, "kind", "function")) {
+    /* 
+       For functions, look qualified names first, such as
+
+       struct Foo {
+       int *foo(int bar)   ->  Foo::foo
+       };
+     */
+    Symtab *st = Getattr(node, "sym:symtab");
+    String *qsn = st ? Swig_symbol_string_qualify(pname, st) : 0;
+    if (qsn) {
+      if (Len(qsn) && !Equal(qsn, pname)) {
+	tm = Swig_typemap_search(op, type, qsn, &mtype);
+	if (tm && (!Getattr(tm, "pname") || strstr(Char(Getattr(tm, "type")), "SWIGTYPE"))) {
+	  tm = 0;
+	}
+      }
+      Delete(qsn);
+    }
+  }
+  if (!tm)
+#endif
+    tm = Swig_typemap_search(op, type, pname, &mtype);
+  if (!tm)
+    return sdef;
+
+  s = Getattr(tm, "code");
+  if (!s)
+    return sdef;
+
+  /* Empty typemap. No match */
+  if (Cmp(s, "pass") == 0)
+    return sdef;
+
+  s = Copy(s);			/* Make a local copy of the typemap code */
+
+  /* Attach kwargs - ie the typemap attributes */
+  kw = Getattr(tm, "kwargs");
+  while (kw) {
+    String *value = Copy(Getattr(kw, "value"));
+    String *type = Getattr(kw, "type");
+    char *ckwname = Char(Getattr(kw, "name"));
+    if (type) {
+      String *mangle = Swig_string_mangle(type);
+      Append(value, mangle);
+      Delete(mangle);
+    }
+    sprintf(temp, "%s:%s", cop, ckwname);
+    Setattr(node, tmop_name(temp), value);
+    if (Cmp(temp, "out:optimal") == 0)
+      optimal_attribute = (Cmp(value, "0") != 0) ? 1 : 0;
+    Delete(value);
+    kw = nextSibling(kw);
+  }
+  
+  if (optimal_attribute) {
+    /* Note: "out" typemap is the only typemap that will have the "optimal" attribute set.
+     * If f and actioncode are NULL, then the caller is just looking to attach the "out" attributes
+     * ie, not use the typemap code, otherwise both f and actioncode must be non null. */
+    if (actioncode) {
+      clname = Copy(actioncode);
+      /* check that the code in the typemap can be used in this optimal way.
+       * The code should be in the form "result = ...;\n". We need to extract
+       * the "..." part. This may not be possible for various reasons, eg
+       * code added by %exception. This optimal code generation is bit of a
+       * hack and circumvents the normal requirement for a temporary variable 
+       * to hold the result returned from a wrapped function call.
+       */
+      if (Strncmp(clname, "result = ", 9) == 0) {
+        int numreplacements = Replace(clname, "result = ", "", DOH_REPLACE_ID_BEGIN);
+        if (numreplacements == 1) {
+          numreplacements = Replace(clname, ";\n", "", DOH_REPLACE_ID_END);
+          if (numreplacements == 1) {
+            if (Strchr(clname, ';') == 0) {
+              lname = clname;
+              actioncode = 0;
+              optimal_substitution = 1;
+            }
+          }
+        }
+      }
+      if (!optimal_substitution) {
+        Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(node), Getline(node), "Method %s usage of the optimal attribute in the out typemap at %s:%d ignored as the following cannot be used to generate optimal code: %s\n", Swig_name_decl(node), Getfile(s), Getline(s), clname);
+        Delattr(node, "tmap:out:optimal");
+      }
+    } else {
+      assert(!f);
+    }
+  }
+  if (actioncode) {
+    assert(f);
+    Append(f->code, actioncode);
+  }
+
+  /* emit local variables declared in typemap, eg emit declarations for aa and bb in:
+   * %typemap(in) foo (int aa, int bb) "..." */
+  locals = Getattr(tm, "locals");
+  if (locals)
+    locals = CopyParmList(locals);
+
+  if (pname) {
+    if (SwigType_istemplate(pname)) {
+      cname = SwigType_namestr(pname);
+      pname = cname;
+    }
+  }
+  if (SwigType_istemplate((char *) lname)) {
+    clname = SwigType_namestr((char *) lname);
+    lname = clname;
+  }
+
+  if (mtype && SwigType_isarray(mtype)) {
+    num_substitutions = typemap_replace_vars(s, locals, mtype, type, pname, (char *) lname, 1);
+  } else {
+    num_substitutions = typemap_replace_vars(s, locals, type, type, pname, (char *) lname, 1);
+  }
+  if (optimal_substitution && num_substitutions > 1)
+    Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_MULTIPLE, Getfile(node), Getline(node), "Multiple calls to %s might be generated due to optimal attribute usage in the out typemap at %s:%d.\n", Swig_name_decl(node), Getfile(s), Getline(s));
+
+  if (locals && f) {
+    typemap_locals(s, locals, f, -1);
+  }
+  replace_embedded_typemap(s);
+
+  Replace(s, "$name", pname, DOH_REPLACE_ANY);
+
+  symname = Getattr(node, "sym:name");
+  if (symname) {
+    Replace(s, "$symname", symname, DOH_REPLACE_ANY);
+  }
+
+  Setattr(node, tmop_name(op), s);
+  if (locals) {
+    sprintf(temp, "%s:locals", cop);
+    Setattr(node, tmop_name(temp), locals);
+    Delete(locals);
+  }
+
+  if (Checkattr(tm, "type", "SWIGTYPE")) {
+    sprintf(temp, "%s:SWIGTYPE", cop);
+    Setattr(node, tmop_name(temp), "1");
+  }
+
+  /* Look for warnings */
+  {
+    String *w;
+    sprintf(temp, "%s:warning", cop);
+    w = Getattr(node, tmop_name(temp));
+    if (w) {
+      Swig_warning(0, Getfile(node), Getline(node), "%s\n", w);
+    }
+  }
+
+  /* Look for code fragments */
+  {
+    String *f;
+    sprintf(temp, "%s:fragment", cop);
+    f = Getattr(node, tmop_name(temp));
+    if (f) {
+      String *fname = Copy(f);
+      Setfile(fname, Getfile(node));
+      Setline(fname, Getline(node));
+      Swig_fragment_emit(fname);
+      Delete(fname);
+    }
+  }
+
+  Delete(cname);
+  Delete(clname);
+  Delete(mtype);
+  if (sdef) {			/* put 'ref' and 'newfree' codes together */
+    String *p = NewStringf("%s\n%s", sdef, s);
+    Delete(s);
+    Delete(sdef);
+    s = p;
+  }
+  Delete(actioncode);
+  return s;
+}
+
+String *Swig_typemap_lookup_out(const String_or_char *op, Node *node, const String_or_char *lname, Wrapper *f, String *actioncode) {
+  assert(actioncode);
+  assert(Cmp(op, "out") == 0);
+  return Swig_typemap_lookup_impl(op, node, lname, f, actioncode);
+}
+
+String *Swig_typemap_lookup(const String_or_char *op, Node *node, const String_or_char *lname, Wrapper *f) {
+  return Swig_typemap_lookup_impl(op, node, lname, f, 0);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_attach_kwargs()
+ *
+ * If this hash (tm) contains a linked list of parameters under its "kwargs"
+ * attribute, add keys for each of those named keyword arguments to this
+ * parameter for later use.
+ * For example, attach the typemap attributes to p:
+ * %typemap(in, foo="xyz") ...
+ * A new attribute called "tmap:in:foo" with value "xyz" is attached to p.
+ * ----------------------------------------------------------------------------- */
+
+void Swig_typemap_attach_kwargs(Hash *tm, const String_or_char *op, Parm *p) {
+  String *temp = NewStringEmpty();
+  Parm *kw = Getattr(tm, "kwargs");
+  while (kw) {
+    String *value = Copy(Getattr(kw, "value"));
+    String *type = Getattr(kw, "type");
+    if (type) {
+      Hash *v = NewHash();
+      Setattr(v, "type", type);
+      Setattr(v, "value", value);
+      Delete(value);
+      value = v;
+    }
+    Clear(temp);
+    Printf(temp, "%s:%s", op, Getattr(kw, "name"));
+    Setattr(p, tmop_name(temp), value);
+    Delete(value);
+    kw = nextSibling(kw);
+  }
+  Clear(temp);
+  Printf(temp, "%s:match_type", op);
+  Setattr(p, tmop_name(temp), Getattr(tm, "type"));
+  Delete(temp);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_warn()
+ *
+ * If any warning message is attached to this parameter's "tmap:op:warning"
+ * attribute, print that warning message.
+ * ----------------------------------------------------------------------------- */
+
+static void Swig_typemap_warn(const String_or_char *op, Parm *p) {
+  String *temp = NewStringf("%s:warning", op);
+  String *w = Getattr(p, tmop_name(temp));
+  Delete(temp);
+  if (w) {
+    Swig_warning(0, Getfile(p), Getline(p), "%s\n", w);
+  }
+}
+
+static void Swig_typemap_emit_code_fragments(const String_or_char *op, Parm *p) {
+  String *temp = NewStringf("%s:fragment", op);
+  String *f = Getattr(p, tmop_name(temp));
+  if (f) {
+    String *fname = Copy(f);
+    Setfile(fname, Getfile(p));
+    Setline(fname, Getline(p));
+    Swig_fragment_emit(fname);
+    Delete(fname);
+  }
+  Delete(temp);
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_attach_parms()
+ *
+ * Given a parameter list, this function attaches all of the typemaps for a
+ * given typemap type
+ * ----------------------------------------------------------------------------- */
+
+String *Swig_typemap_get_option(Hash *tm, String *name) {
+  Parm *kw = Getattr(tm, "kwargs");
+  while (kw) {
+    String *kname = Getattr(kw, "name");
+    if (Equal(kname, name)) {
+      return Getattr(kw, "value");
+    }
+    kw = nextSibling(kw);
+  }
+  return 0;
+}
+
+void Swig_typemap_attach_parms(const String_or_char *op, ParmList *parms, Wrapper *f) {
+  Parm *p, *firstp;
+  Hash *tm;
+  int nmatch = 0;
+  int i;
+  String *s;
+  ParmList *locals;
+  int argnum = 0;
+  char temp[256];
+  char *cop = Char(op);
+  String *kwmatch = 0;
+  p = parms;
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_typemap_attach_parms:  %s\n", op);
+#endif
+
+  while (p) {
+    argnum++;
+    nmatch = 0;
+#ifdef SWIG_DEBUG
+    Printf(stdout, "parms:  %s %s %s\n", op, Getattr(p, "name"), Getattr(p, "type"));
+#endif
+    tm = Swig_typemap_search_multi(op, p, &nmatch);
+#ifdef SWIG_DEBUG
+    if (tm)
+      Printf(stdout, "found:  %s\n", tm);
+#endif
+    if (!tm) {
+      p = nextSibling(p);
+      continue;
+    }
+    /*
+       Check if the typemap requires to match the type of another
+       typemap, for example:
+
+       %typemap(in) SWIGTYPE * (int var) {...}
+       %typemap(freearg,match="in") SWIGTYPE * {if (var$argnum) ...}
+
+       here, the freearg typemap requires the "in" typemap to match,
+       or the 'var$argnum' variable will not exist.
+     */
+    kwmatch = Swig_typemap_get_option(tm, "match");
+    if (kwmatch) {
+      String *tmname = NewStringf("tmap:%s", kwmatch);
+      String *tmin = Getattr(p, tmname);
+      Delete(tmname);
+#ifdef SWIG_DEBUG
+      if (tm)
+	Printf(stdout, "matching:  %s\n", kwmatch);
+#endif
+      if (tmin) {
+	String *tmninp = NewStringf("tmap:%s:numinputs", kwmatch);
+	String *ninp = Getattr(p, tmninp);
+	Delete(tmninp);
+	if (ninp && Equal(ninp, "0")) {
+	  p = nextSibling(p);
+	  continue;
+	} else {
+	  SwigType *typetm = Getattr(tm, "type");
+	  String *temp = NewStringf("tmap:%s:match_type", kwmatch);
+	  SwigType *typein = Getattr(p, temp);
+	  Delete(temp);
+	  if (!Equal(typein, typetm)) {
+	    p = nextSibling(p);
+	    continue;
+	  } else {
+	    int nnmatch;
+	    Hash *tmapin = Swig_typemap_search_multi(kwmatch, p, &nnmatch);
+	    String *tmname = Getattr(tm, "pname");
+	    String *tnname = Getattr(tmapin, "pname");
+	    if (!(tmname && tnname && Equal(tmname, tnname)) && !(!tmname && !tnname)) {
+	      p = nextSibling(p);
+	      continue;
+	    }
+	  }
+
+	}
+      } else {
+	p = nextSibling(p);
+	continue;
+      }
+    }
+
+    s = Getattr(tm, "code");
+    if (!s) {
+      p = nextSibling(p);
+      continue;
+    }
+#ifdef SWIG_DEBUG
+    if (s)
+      Printf(stdout, "code:  %s\n", s);
+#endif
+
+    /* Empty typemap. No match */
+    if (Cmp(s, "pass") == 0) {
+      p = nextSibling(p);
+      continue;
+    }
+
+    s = Copy(s);
+    locals = Getattr(tm, "locals");
+    if (locals)
+      locals = CopyParmList(locals);
+    firstp = p;
+#ifdef SWIG_DEBUG
+    Printf(stdout, "nmatch:  %d\n", nmatch);
+#endif
+    for (i = 0; i < nmatch; i++) {
+      SwigType *type;
+      String *pname;
+      String *lname;
+      SwigType *mtype;
+
+
+      type = Getattr(p, "type");
+      pname = Getattr(p, "name");
+      lname = Getattr(p, "lname");
+      mtype = Getattr(p, "tmap:match");
+
+      if (mtype) {
+	typemap_replace_vars(s, locals, mtype, type, pname, lname, i + 1);
+	Delattr(p, "tmap:match");
+      } else {
+	typemap_replace_vars(s, locals, type, type, pname, lname, i + 1);
+      }
+
+      if (Checkattr(tm, "type", "SWIGTYPE")) {
+	sprintf(temp, "%s:SWIGTYPE", cop);
+	Setattr(p, tmop_name(temp), "1");
+      }
+      p = nextSibling(p);
+    }
+
+    if (locals && f) {
+      typemap_locals(s, locals, f, argnum);
+    }
+
+    replace_embedded_typemap(s);
+
+    /* Replace the argument number */
+    sprintf(temp, "%d", argnum);
+    Replace(s, "$argnum", temp, DOH_REPLACE_ANY);
+
+    /* Attach attributes to object */
+#ifdef SWIG_DEBUG
+    Printf(stdout, "attach: %s %s %s\n", Getattr(firstp, "name"), tmop_name(op), s);
+#endif
+    Setattr(firstp, tmop_name(op), s);	/* Code object */
+
+    if (locals) {
+      sprintf(temp, "%s:locals", cop);
+      Setattr(firstp, tmop_name(temp), locals);
+      Delete(locals);
+    }
+
+    /* Attach a link to the next parameter.  Needed for multimaps */
+    sprintf(temp, "%s:next", cop);
+    Setattr(firstp, tmop_name(temp), p);
+
+    /* Attach kwargs */
+    Swig_typemap_attach_kwargs(tm, op, firstp);
+
+    /* Print warnings, if any */
+    Swig_typemap_warn(op, firstp);
+
+    /* Look for code fragments */
+    Swig_typemap_emit_code_fragments(op, firstp);
+
+    /* increase argnum to consider numinputs */
+    argnum += nmatch - 1;
+    Delete(s);
+#ifdef SWIG_DEBUG
+    Printf(stdout, "res: %s %s %s\n", Getattr(firstp, "name"), tmop_name(op), Getattr(firstp, tmop_name(op)));
+#endif
+
+  }
+#ifdef SWIG_DEBUG
+  Printf(stdout, "Swig_typemap_attach_parms: end\n");
+#endif
+
+}
+
+/* -----------------------------------------------------------------------------
+ * split_embedded()
+ *
+ * This function replaces the special variable $typemap(....) with typemap
+ * code.  The general form of $typemap is as follows:
+ *
+ *   $TYPEMAP(method, $var1=value, $var2=value, $var3=value,...)
+ *
+ * For example:
+ *
+ *   $TYPEMAP(in, $1=int x, $input=y, ...)
+ *
+ * Note: this was added as an experiment and could be removed
+ * ----------------------------------------------------------------------------- */
+
+/* Splits the arguments of an embedded typemap */
+static List *split_embedded(String *s) {
+  List *args = 0;
+  char *c, *start;
+  int level = 0;
+  int leading = 1;
+  args = NewList();
+
+  c = strchr(Char(s), '(');
+  c++;
+
+  start = c;
+  while (*c) {
+    if (*c == '\"') {
+      c++;
+      while (*c) {
+	if (*c == '\\') {
+	  c++;
+	} else {
+	  if (*c == '\"')
+	    break;
+	}
+	c++;
+      }
+    }
+    if ((level == 0) && ((*c == ',') || (*c == ')'))) {
+      String *tmp = NewStringWithSize(start, c - start);
+      Append(args, tmp);
+      Delete(tmp);
+      start = c + 1;
+      leading = 1;
+      if (*c == ')')
+	break;
+      c++;
+      continue;
+    }
+    if (*c == '(')
+      level++;
+    if (*c == ')')
+      level--;
+    if (isspace((int) *c) && leading)
+      start++;
+    if (!isspace((int) *c))
+      leading = 0;
+    c++;
+  }
+  return args;
+}
+
+static void split_var(String *s, String **name, String **value) {
+  char *eq;
+  char *c;
+
+  eq = strchr(Char(s), '=');
+  if (!eq) {
+    *name = 0;
+    *value = 0;
+    return;
+  }
+  c = Char(s);
+  *name = NewStringWithSize(c, eq - c);
+
+  /* Look for $n variables */
+  if (isdigit((int) *(c))) {
+    /* Parse the value as a type */
+    String *v;
+    Parm *p;
+    v = NewString(eq + 1);
+    p = Swig_cparse_parm(v);
+    Delete(v);
+    *value = p;
+  } else {
+    *value = NewString(eq + 1);
+  }
+}
+
+static void replace_embedded_typemap(String *s) {
+  char *start = 0;
+  while ((start = strstr(Char(s), "$TYPEMAP("))) {
+
+    /* Gather the argument */
+    char *end = 0, *c;
+    int level = 0;
+    String *tmp;
+    c = start;
+    while (*c) {
+      if (*c == '(')
+	level++;
+      if (*c == ')') {
+	level--;
+	if (level == 0) {
+	  end = c + 1;
+	  break;
+	}
+      }
+      c++;
+    }
+    if (end) {
+      tmp = NewStringWithSize(start, (end - start));
+    } else {
+      tmp = 0;
+    }
+
+    /* Got a substitution. Split it apart into pieces */
+    if (tmp) {
+      List *l;
+      Hash *vars;
+      String *method;
+      int i, ilen;
+
+      l = split_embedded(tmp);
+      vars = NewHash();
+      ilen = Len(l);
+      for (i = 1; i < ilen; i++) {
+	String *n, *v;
+	split_var(Getitem(l, i), &n, &v);
+	if (n && v) {
+	  Insert(n, 0, "$");
+	  Setattr(vars, n, v);
+	}
+	Delete(n);
+	Delete(v);
+      }
+
+      method = Getitem(l, 0);
+      /* Generate the parameter list for matching typemaps */
+
+      {
+	Parm *p = 0;
+	Parm *first = 0;
+	char temp[32];
+	int n = 1;
+	while (1) {
+	  Hash *v;
+	  sprintf(temp, "$%d", n);
+	  v = Getattr(vars, temp);
+	  if (v) {
+	    if (p) {
+	      set_nextSibling(p, v);
+	      set_previousSibling(v, p);
+	    }
+	    p = v;
+	    Setattr(p, "lname", Getattr(p, "name"));
+	    if (Getattr(p, "value")) {
+	      Setattr(p, "name", Getattr(p, "value"));
+	    }
+	    if (!first)
+	      first = p;
+	    DohIncref(p);
+	    Delattr(vars, temp);
+	  } else {
+	    break;
+	  }
+	  n++;
+	}
+	/* Perform a typemap search */
+	if (first) {
+#ifdef SWIG_DEBUG
+	  Printf(stdout, "Swig_typemap_attach_parms:  embedded\n");
+#endif
+	  Swig_typemap_attach_parms(method, first, 0);
+	  {
+	    String *tm;
+	    int match = 0;
+	    char attr[64];
+	    sprintf(attr, "tmap:%s", Char(method));
+
+	    /* Look for the typemap code */
+	    tm = Getattr(first, attr);
+	    if (tm) {
+	      sprintf(attr, "tmap:%s:next", Char(method));
+	      if (!Getattr(first, attr)) {
+		/* Should be no more matches.  Hack??? */
+		/* Replace all of the remaining variables */
+		Iterator ki;
+		for (ki = First(vars); ki.key; ki = Next(ki)) {
+		  Replace(tm, ki.key, ki.item, DOH_REPLACE_ANY);
+		}
+		/* Do the replacement */
+		Replace(s, tmp, tm, DOH_REPLACE_ANY);
+		Delete(tm);
+		match = 1;
+	      }
+	    }
+	    if (!match) {
+	      Swig_error(Getfile(s), Getline(s), "No typemap found for %s\n", tmp);
+	    }
+	  }
+	}
+      }
+      Replace(s, tmp, "<embedded typemap>", DOH_REPLACE_ANY);
+      Delete(vars);
+      Delete(tmp);
+      Delete(l);
+    }
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Swig_typemap_debug()
+ * ----------------------------------------------------------------------------- */
+
+void Swig_typemap_debug() {
+  int ts;
+  Printf(stdout, "---[ typemaps ]--------------------------------------------------------------\n");
+
+  ts = tm_scope;
+  while (ts >= 0) {
+    Printf(stdout, "::: scope %d\n\n", ts);
+    Printf(stdout, "%s\n", typemaps[ts]);
+    ts--;
+  }
+  Printf(stdout, "-----------------------------------------------------------------------------\n");
+}
diff --git a/trunk/Source/Swig/typeobj.c b/trunk/Source/Swig/typeobj.c
new file mode 100644
index 0000000..18d1b23
--- /dev/null
+++ b/trunk/Source/Swig/typeobj.c
@@ -0,0 +1,1095 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typeobj.c
+ *
+ * This file provides functions for constructing, manipulating, and testing
+ * type objects.   Type objects are merely the raw low-level representation
+ * of C++ types.   They do not incorporate high-level type system features
+ * like typedef, namespaces, etc.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_typeobj_c[] = "$Id$";
+
+#include "swig.h"
+#include <ctype.h>
+
+/* -----------------------------------------------------------------------------
+ * Synopsis
+ *
+ * This file provides a collection of low-level functions for constructing and
+ * manipulating C++ data types.   In SWIG, C++ datatypes are encoded as simple
+ * text strings.  This representation is compact, easy to debug, and easy to read.
+ *
+ * General idea:
+ *
+ * Types are represented by a base type (e.g., "int") and a collection of
+ * type operators applied to the base (e.g., pointers, arrays, etc...).
+ *
+ * Encoding:
+ *
+ * Types are encoded as strings of type constructors such as follows:
+ *
+ *        String Encoding                 C Example
+ *        ---------------                 ---------
+ *        p.p.int                         int **
+ *        a(300).a(400).int               int [300][400]
+ *        p.q(const).char                 char const *
+ *
+ * All type constructors are denoted by a trailing '.':
+ * 
+ *  'p.'                = Pointer (*)
+ *  'r.'                = Reference (&)
+ *  'a(n).'             = Array of size n  [n]
+ *  'f(..,..).'         = Function with arguments  (args)
+ *  'q(str).'           = Qualifier (such as const or volatile) (const, volatile)
+ *  'm(qual).'          = Pointer to member (qual::*)
+ *
+ * The encoding follows the order that you might describe a type in words.
+ * For example "p.a(200).int" is "A pointer to array of int's" and
+ * "p.q(const).char" is "a pointer to a const char".
+ *
+ * This representation of types is fairly convenient because ordinary string
+ * operations can be used for type manipulation. For example, a type could be
+ * formed by combining two strings such as the following:
+ *
+ *        "p.p." + "a(400).int" = "p.p.a(400).int"
+ *
+ * For C++, typenames may be parameterized using <(...)>.  Here are some
+ * examples:
+ *
+ *       String Encoding                  C++ Example
+ *       ---------------                  ------------
+ *       p.vector<(int)>                  vector<int> *
+ *       r.foo<(int,p.double)>            foo<int,double *> &
+ *
+ * Contents of this file:
+ *
+ * Most of this functions in this file pertain to the low-level manipulation
+ * of type objects.   There are constructor functions like this:
+ *
+ *       SwigType_add_pointer()
+ *       SwigType_add_reference()
+ *       SwigType_add_array()
+ *
+ * These are used to build new types.  There are also functions to undo these
+ * operations.  For example:
+ *
+ *       SwigType_del_pointer()
+ *       SwigType_del_reference()
+ *       SwigType_del_array()
+ *
+ * In addition, there are query functions
+ *
+ *       SwigType_ispointer()
+ *       SwigType_isreference()
+ *       SwigType_isarray()
+ *
+ * Finally, there are some data extraction functions that can be used to
+ * extract array dimensions, template arguments, and so forth.
+ * 
+ * It is very important for developers to realize that the functions in this
+ * module do *NOT* incorporate higher-level type system features like typedef.
+ * For example, you could have C code like this:
+ *
+ *        typedef  int  *intptr;
+ *       
+ * In this case, a SwigType of type 'intptr' will be treated as a simple type and
+ * functions like SwigType_ispointer() will evaluate as false.  It is strongly
+ * advised that developers use the TypeSys_* interface to check types in a more
+ * reliable manner.
+ * ----------------------------------------------------------------------------- */
+
+
+/* -----------------------------------------------------------------------------
+ * NewSwigType()
+ *
+ * Constructs a new type object.   Eventually, it would be nice for this function
+ * to accept an initial value in the form a C/C++ abstract type (currently unimplemented).
+ * ----------------------------------------------------------------------------- */
+
+#ifdef NEW
+SwigType *NewSwigType(const String_or_char *initial) {
+  return NewString(initial);
+}
+
+#endif
+
+/* The next few functions are utility functions used in the construction and 
+   management of types */
+
+/* -----------------------------------------------------------------------------
+ * static element_size()
+ *
+ * This utility function finds the size of a single type element in a type string.
+ * Type elements are always delimited by periods, but may be nested with
+ * parentheses.  A nested element is always handled as a single item.
+ *
+ * Returns the integer size of the element (which can be used to extract a 
+ * substring, to chop the element off, or for other purposes).
+ * ----------------------------------------------------------------------------- */
+
+static int element_size(char *c) {
+  int nparen;
+  char *s = c;
+  while (*c) {
+    if (*c == '.') {
+      c++;
+      return (int) (c - s);
+    } else if (*c == '(') {
+      nparen = 1;
+      c++;
+      while (*c) {
+	if (*c == '(')
+	  nparen++;
+	if (*c == ')') {
+	  nparen--;
+	  if (nparen == 0)
+	    break;
+	}
+	c++;
+      }
+    }
+    if (*c)
+      c++;
+  }
+  return (int) (c - s);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_del_element()
+ *
+ * Deletes one type element from the type.  
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_del_element(SwigType *t) {
+  int sz = element_size(Char(t));
+  Delslice(t, 0, sz);
+  return t;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_pop()
+ * 
+ * Pop one type element off the type.
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_pop(SwigType *t) {
+  SwigType *result;
+  char *c;
+  int sz;
+
+  c = Char(t);
+  if (!*c)
+    return 0;
+
+  sz = element_size(c);
+  result = NewStringWithSize(c, sz);
+  Delslice(t, 0, sz);
+  c = Char(t);
+  if (*c == '.') {
+    Delitem(t, 0);
+  }
+  return result;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_parm()
+ *
+ * Returns the parameter of an operator as a string
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_parm(SwigType *t) {
+  char *start, *c;
+  int nparens = 0;
+
+  c = Char(t);
+  while (*c && (*c != '(') && (*c != '.'))
+    c++;
+  if (!*c || (*c == '.'))
+    return 0;
+  c++;
+  start = c;
+  while (*c) {
+    if (*c == ')') {
+      if (nparens == 0)
+	break;
+      nparens--;
+    } else if (*c == '(') {
+      nparens++;
+    }
+    c++;
+  }
+  return NewStringWithSize(start, (int) (c - start));
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_split()
+ *
+ * Splits a type into it's component parts and returns a list of string.
+ * ----------------------------------------------------------------------------- */
+
+List *SwigType_split(const SwigType *t) {
+  String *item;
+  List *list;
+  char *c;
+  int len;
+
+  c = Char(t);
+  list = NewList();
+  while (*c) {
+    len = element_size(c);
+    item = NewStringWithSize(c, len);
+    Append(list, item);
+    Delete(item);
+    c = c + len;
+    if (*c == '.')
+      c++;
+  }
+  return list;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_parmlist()
+ *
+ * Splits a comma separated list of parameters into its component parts
+ * The input is expected to contain the parameter list within () brackets
+ * Returns 0 if no argument list in the input, ie there are no round brackets ()
+ * Returns an empty List if there are no parameters in the () brackets
+ * For example:
+ *
+ *     Foo(std::string,p.f().Bar<(int,double)>)
+ *
+ * returns 2 elements in the list:
+ *    std::string
+ *    p.f().Bar<(int,double)>
+ * ----------------------------------------------------------------------------- */
+ 
+List *SwigType_parmlist(const String *p) {
+  String *item = 0;
+  List *list;
+  char *c;
+  char *itemstart;
+  int size;
+
+  assert(p);
+  c = Char(p);
+  while (*c && (*c != '(') && (*c != '.'))
+    c++;
+  if (!*c)
+    return 0;
+  assert(*c != '.'); /* p is expected to contain sub elements of a type */
+  c++;
+  list = NewList();
+  itemstart = c;
+  while (*c) {
+    if (*c == ',') {
+      size = (int) (c - itemstart);
+      item = NewStringWithSize(itemstart, size);
+      Append(list, item);
+      Delete(item);
+      itemstart = c + 1;
+    } else if (*c == '(') {
+      int nparens = 1;
+      c++;
+      while (*c) {
+	if (*c == '(')
+	  nparens++;
+	if (*c == ')') {
+	  nparens--;
+	  if (nparens == 0)
+	    break;
+	}
+	c++;
+      }
+    } else if (*c == ')') {
+      break;
+    }
+    if (*c)
+      c++;
+  }
+  size = (int) (c - itemstart);
+  if (size > 0) {
+    item = NewStringWithSize(itemstart, size);
+    Append(list, item);
+  }
+  Delete(item);
+  return list;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                 Pointers
+ *
+ * SwigType_add_pointer()
+ * SwigType_del_pointer()
+ * SwigType_ispointer()
+ *
+ * Add, remove, and test if a type is a pointer.  The deletion and query
+ * functions take into account qualifiers (if any).
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_add_pointer(SwigType *t) {
+  Insert(t, 0, "p.");
+  return t;
+}
+
+SwigType *SwigType_del_pointer(SwigType *t) {
+  char *c, *s;
+  c = Char(t);
+  s = c;
+  /* Skip qualifiers, if any */
+  if (strncmp(c, "q(", 2) == 0) {
+    c = strchr(c, '.');
+    assert(c);
+    c++;
+  }
+  if (strncmp(c, "p.", 2)) {
+    printf("Fatal error. SwigType_del_pointer applied to non-pointer.\n");
+    abort();
+  }
+  Delslice(t, 0, (c - s) + 2);
+  return t;
+}
+
+int SwigType_ispointer(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  /* Skip qualifiers, if any */
+  if (strncmp(c, "q(", 2) == 0) {
+    c = strchr(c, '.');
+    if (!c)
+      return 0;
+    c++;
+  }
+  if (strncmp(c, "p.", 2) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                 References
+ *
+ * SwigType_add_reference()
+ * SwigType_del_reference()
+ * SwigType_isreference()
+ *
+ * Add, remove, and test if a type is a reference.  The deletion and query
+ * functions take into account qualifiers (if any).
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_add_reference(SwigType *t) {
+  Insert(t, 0, "r.");
+  return t;
+}
+
+SwigType *SwigType_del_reference(SwigType *t) {
+  char *c = Char(t);
+  int check = strncmp(c, "r.", 2);
+  assert(check == 0);
+  Delslice(t, 0, 2);
+  return t;
+}
+
+int SwigType_isreference(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  if (strncmp(c, "r.", 2) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                  Qualifiers
+ *
+ * SwigType_add_qualifier()
+ * SwigType_del_qualifier()
+ * SwigType_is_qualifier()
+ *
+ * Adds type qualifiers like "const" and "volatile".   When multiple qualifiers
+ * are added to a type, they are combined together into a single qualifier.
+ * Repeated qualifications have no effect.  Moreover, the order of qualifications
+ * is alphabetical---meaning that "const volatile" and "volatile const" are
+ * stored in exactly the same way as "q(const volatile)".
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_add_qualifier(SwigType *t, const String_or_char *qual) {
+  char temp[256], newq[256];
+  int sz, added = 0;
+  char *q, *cqual;
+
+  char *c = Char(t);
+  cqual = Char(qual);
+
+  if (!(strncmp(c, "q(", 2) == 0)) {
+    sprintf(temp, "q(%s).", cqual);
+    Insert(t, 0, temp);
+    return t;
+  }
+
+  /* The type already has a qualifier on it.  In this case, we first check to
+     see if the qualifier is already specified.  In that case do nothing.
+     If it is a new qualifier, we add it to the qualifier list in alphabetical
+     order */
+
+  sz = element_size(c);
+  strncpy(temp, c, (sz < 256) ? sz : 256);
+
+  if (strstr(temp, cqual)) {
+    /* Qualifier already added */
+    return t;
+  }
+
+  /* Add the qualifier to the existing list. */
+
+  strcpy(newq, "q(");
+  q = temp + 2;
+  q = strtok(q, " ).");
+  while (q) {
+    if (strcmp(cqual, q) < 0) {
+      /* New qualifier is less that current qualifier.  We need to insert it */
+      strcat(newq, cqual);
+      strcat(newq, " ");
+      strcat(newq, q);
+      added = 1;
+    } else {
+      strcat(newq, q);
+    }
+    q = strtok(NULL, " ).");
+    if (q) {
+      strcat(newq, " ");
+    }
+  }
+  if (!added) {
+    strcat(newq, " ");
+    strcat(newq, cqual);
+  }
+  strcat(newq, ").");
+  Delslice(t, 0, sz);
+  Insert(t, 0, newq);
+  return t;
+}
+
+SwigType *SwigType_del_qualifier(SwigType *t) {
+  char *c = Char(t);
+  int check = strncmp(c, "q(", 2);
+  assert(check == 0);
+  Delslice(t, 0, element_size(c));
+  return t;
+}
+
+int SwigType_isqualifier(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  if (strncmp(c, "q(", 2) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                Function Pointers
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_isfunctionpointer(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  if (strncmp(c, "p.f(", 4) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_functionpointer_decompose
+ *
+ * Decompose the function pointer into the parameter list and the return type
+ * t - input and on completion contains the return type
+ * returns the function's parameters
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_functionpointer_decompose(SwigType *t) {
+  String *p;
+  assert(SwigType_isfunctionpointer(t));
+  p = SwigType_pop(t);
+  Delete(p);
+  p = SwigType_pop(t);
+  return p;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                Member Pointers
+ *
+ * SwigType_add_memberpointer()
+ * SwigType_del_memberpointer()
+ * SwigType_ismemberpointer()
+ *
+ * Add, remove, and test for C++ pointer to members.
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_add_memberpointer(SwigType *t, const String_or_char *name) {
+  String *temp = NewStringf("m(%s).", name);
+  Insert(t, 0, temp);
+  Delete(temp);
+  return t;
+}
+
+SwigType *SwigType_del_memberpointer(SwigType *t) {
+  char *c = Char(t);
+  int check = strncmp(c, "m(", 2);
+  assert(check == 0);
+  Delslice(t, 0, element_size(c));
+  return t;
+}
+
+int SwigType_ismemberpointer(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  if (strncmp(c, "m(", 2) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                    Arrays
+ *
+ * SwigType_add_array()
+ * SwigType_del_array()
+ * SwigType_isarray()
+ *
+ * Utility functions:
+ *
+ * SwigType_array_ndim()        - Calculate number of array dimensions.
+ * SwigType_array_getdim()      - Get array dimension
+ * SwigType_array_setdim()      - Set array dimension
+ * SwigType_array_type()        - Return array type
+ * SwigType_pop_arrays()        - Remove all arrays
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_add_array(SwigType *t, const String_or_char *size) {
+  char temp[512];
+  strcpy(temp, "a(");
+  strcat(temp, Char(size));
+  strcat(temp, ").");
+  Insert(t, 0, temp);
+  return t;
+}
+
+SwigType *SwigType_del_array(SwigType *t) {
+  char *c = Char(t);
+  int check = strncmp(c, "a(", 2);
+  assert(check == 0);
+  Delslice(t, 0, element_size(c));
+  return t;
+}
+
+int SwigType_isarray(SwigType *t) {
+  char *c;
+  if (!t)
+    return 0;
+  c = Char(t);
+  if (strncmp(c, "a(", 2) == 0) {
+    return 1;
+  }
+  return 0;
+}
+/*
+ * SwigType_prefix_is_simple_1D_array
+ *
+ * Determine if the type is a 1D array type that is treated as a pointer within SWIG
+ * eg Foo[], Foo[3] return true, but Foo[3][3], Foo*[], Foo*[3], Foo**[] return false
+ */
+int SwigType_prefix_is_simple_1D_array(SwigType *t) {
+  char *c = Char(t);
+
+  if (c && (strncmp(c, "a(", 2) == 0)) {
+    c = strchr(c, '.');
+    c++;
+    return (*c == 0);
+  }
+  return 0;
+}
+
+
+/* Remove all arrays */
+SwigType *SwigType_pop_arrays(SwigType *t) {
+  String *ta;
+  assert(SwigType_isarray(t));
+  ta = NewStringEmpty();
+  while (SwigType_isarray(t)) {
+    SwigType *td = SwigType_pop(t);
+    Append(ta, td);
+    Delete(td);
+  }
+  return ta;
+}
+
+/* Return number of array dimensions */
+int SwigType_array_ndim(SwigType *t) {
+  int ndim = 0;
+  char *c = Char(t);
+
+  while (c && (strncmp(c, "a(", 2) == 0)) {
+    c = strchr(c, '.');
+    c++;
+    ndim++;
+  }
+  return ndim;
+}
+
+/* Get nth array dimension */
+String *SwigType_array_getdim(SwigType *t, int n) {
+  char *c = Char(t);
+  while (c && (strncmp(c, "a(", 2) == 0) && (n > 0)) {
+    c = strchr(c, '.');
+    c++;
+    n--;
+  }
+  if (n == 0) {
+    String *dim = SwigType_parm(c);
+    if (SwigType_istemplate(dim)) {
+      String *ndim = SwigType_namestr(dim);
+      Delete(dim);
+      dim = ndim;
+    }
+
+    return dim;
+  }
+
+  return 0;
+}
+
+/* Replace nth array dimension */
+void SwigType_array_setdim(SwigType *t, int n, const String_or_char *rep) {
+  String *result = 0;
+  char temp;
+  char *start;
+  char *c = Char(t);
+
+  start = c;
+  if (strncmp(c, "a(", 2))
+    abort();
+
+  while (c && (strncmp(c, "a(", 2) == 0) && (n > 0)) {
+    c = strchr(c, '.');
+    c++;
+    n--;
+  }
+  if (n == 0) {
+    temp = *c;
+    *c = 0;
+    result = NewString(start);
+    Printf(result, "a(%s)", rep);
+    *c = temp;
+    c = strchr(c, '.');
+    Append(result, c);
+  }
+  Clear(t);
+  Append(t, result);
+  Delete(result);
+}
+
+/* Return base type of an array */
+SwigType *SwigType_array_type(SwigType *ty) {
+  SwigType *t;
+  t = Copy(ty);
+  while (SwigType_isarray(t)) {
+    Delete(SwigType_pop(t));
+  }
+  return t;
+}
+
+
+/* -----------------------------------------------------------------------------
+ *                                    Functions
+ *
+ * SwigType_add_function()
+ * SwigType_del_function()
+ * SwigType_isfunction()
+ * SwigType_pop_function()
+ *
+ * Add, remove, and test for function types.
+ * ----------------------------------------------------------------------------- */
+
+/* Returns the function type, t, constructed from the parameters, parms */
+SwigType *SwigType_add_function(SwigType *t, ParmList *parms) {
+  String *pstr;
+  Parm *p;
+
+  Insert(t, 0, ").");
+  pstr = NewString("f(");
+  p = parms;
+  for (p = parms; p; p = nextSibling(p)) {
+    if (p != parms)
+      Putc(',', pstr);
+    Append(pstr, Getattr(p, "type"));
+  }
+  Insert(t, 0, pstr);
+  Delete(pstr);
+  return t;
+}
+
+SwigType *SwigType_pop_function(SwigType *t) {
+  SwigType *f = 0;
+  SwigType *g = 0;
+  char *c = Char(t);
+  if (strncmp(c, "q(", 2) == 0) {
+    f = SwigType_pop(t);
+    c = Char(t);
+  }
+  if (strncmp(c, "f(", 2)) {
+    printf("Fatal error. SwigType_pop_function applied to non-function.\n");
+    abort();
+  }
+  g = SwigType_pop(t);
+  if (f)
+    SwigType_push(g, f);
+  Delete(f);
+  return g;
+}
+
+int SwigType_isfunction(SwigType *t) {
+  char *c;
+  if (!t) {
+    return 0;
+  }
+  c = Char(t);
+  if (strncmp(c, "q(", 2) == 0) {
+    /* Might be a 'const' function.  Try to skip over the 'const' */
+    c = strchr(c, '.');
+    if (c)
+      c++;
+    else
+      return 0;
+  }
+  if (strncmp(c, "f(", 2) == 0) {
+    return 1;
+  }
+  return 0;
+}
+
+ParmList *SwigType_function_parms(SwigType *t) {
+  List *l = SwigType_parmlist(t);
+  Hash *p, *pp = 0, *firstp = 0;
+  Iterator o;
+
+  for (o = First(l); o.item; o = Next(o)) {
+    p = NewParm(o.item, 0);
+    if (!firstp)
+      firstp = p;
+    if (pp) {
+      set_nextSibling(pp, p);
+      Delete(p);
+    }
+    pp = p;
+  }
+  Delete(l);
+  return firstp;
+}
+
+int SwigType_isvarargs(const SwigType *t) {
+  if (Strcmp(t, "v(...)") == 0)
+    return 1;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ *                                    Templates
+ *
+ * SwigType_add_template()
+ *
+ * Template handling.
+ * ----------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * SwigType_add_template()
+ *
+ * Adds a template to a type.   This template is encoded in the SWIG type
+ * mechanism and produces a string like this:
+ *
+ *  vector<int *> ----> "vector<(p.int)>"
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_add_template(SwigType *t, ParmList *parms) {
+  Parm *p;
+
+  Append(t, "<(");
+  p = parms;
+  for (p = parms; p; p = nextSibling(p)) {
+    String *v;
+    if (Getattr(p, "default"))
+      continue;
+    if (p != parms)
+      Append(t, ",");
+    v = Getattr(p, "value");
+    if (v) {
+      Append(t, v);
+    } else {
+      Append(t, Getattr(p, "type"));
+    }
+  }
+  Append(t, ")>");
+  return t;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_templateprefix()
+ *
+ * Returns the prefix before the first template definition.
+ * For example:
+ *
+ *     Foo<(p.int)>::bar
+ *
+ * returns "Foo"
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_templateprefix(const SwigType *t) {
+  const char *s = Char(t);
+  const char *c = strstr(s, "<(");
+  return c ? NewStringWithSize(s, c - s) : NewString(s);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_templatesuffix()
+ *
+ * Returns text after a template substitution.  Used to handle scope names
+ * for example:
+ *
+ *        Foo<(p.int)>::bar
+ *
+ * returns "::bar"
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_templatesuffix(const SwigType *t) {
+  const char *c;
+  c = Char(t);
+  while (*c) {
+    if ((*c == '<') && (*(c + 1) == '(')) {
+      int nest = 1;
+      c++;
+      while (*c && nest) {
+	if (*c == '<')
+	  nest++;
+	if (*c == '>')
+	  nest--;
+	c++;
+      }
+      return NewString(c);
+    }
+    c++;
+  }
+  return NewStringEmpty();
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_templateargs()
+ *
+ * Returns the template arguments
+ * For example:
+ *
+ *     Foo<(p.int)>::bar
+ *
+ * returns "<(p.int)>"
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_templateargs(const SwigType *t) {
+  const char *c;
+  const char *start;
+  c = Char(t);
+  while (*c) {
+    if ((*c == '<') && (*(c + 1) == '(')) {
+      int nest = 1;
+      start = c;
+      c++;
+      while (*c && nest) {
+	if (*c == '<')
+	  nest++;
+	if (*c == '>')
+	  nest--;
+	c++;
+      }
+      return NewStringWithSize(start, c - start);
+    }
+    c++;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_istemplate()
+ *
+ * Tests a type to see if it includes template parameters
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_istemplate(const SwigType *t) {
+  char *ct = Char(t);
+  ct = strstr(ct, "<(");
+  if (ct && (strstr(ct + 2, ")>")))
+    return 1;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_base()
+ *
+ * This function returns the base of a type.  For example, if you have a
+ * type "p.p.int", the function would return "int".
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_base(const SwigType *t) {
+  char *c;
+  char *lastop = 0;
+  c = Char(t);
+
+  lastop = c;
+
+  /* Search for the last type constructor separator '.' */
+  while (*c) {
+    if (*c == '.') {
+      if (*(c + 1)) {
+	lastop = c + 1;
+      }
+      c++;
+      continue;
+    }
+    if (*c == '<') {
+      /* Skip over template---it's part of the base name */
+      int ntemp = 1;
+      c++;
+      while ((*c) && (ntemp > 0)) {
+	if (*c == '>')
+	  ntemp--;
+	else if (*c == '<')
+	  ntemp++;
+	c++;
+      }
+      if (ntemp)
+	break;
+      continue;
+    }
+    if (*c == '(') {
+      /* Skip over params */
+      int nparen = 1;
+      c++;
+      while ((*c) && (nparen > 0)) {
+	if (*c == '(')
+	  nparen++;
+	else if (*c == ')')
+	  nparen--;
+	c++;
+      }
+      if (nparen)
+	break;
+      continue;
+    }
+    c++;
+  }
+  return NewString(lastop);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_prefix()
+ *
+ * Returns the prefix of a datatype.  For example, the prefix of the
+ * type "p.p.int" is "p.p.".
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_prefix(const SwigType *t) {
+  char *c, *d;
+  String *r = 0;
+
+  c = Char(t);
+  d = c + strlen(c);
+
+  /* Check for a type constructor */
+  if ((d > c) && (*(d - 1) == '.'))
+    d--;
+
+  while (d > c) {
+    d--;
+    if (*d == '>') {
+      int nest = 1;
+      d--;
+      while ((d > c) && (nest)) {
+	if (*d == '>')
+	  nest++;
+	if (*d == '<')
+	  nest--;
+	d--;
+      }
+    }
+    if (*d == ')') {
+      /* Skip over params */
+      int nparen = 1;
+      d--;
+      while ((d > c) && (nparen)) {
+	if (*d == ')')
+	  nparen++;
+	if (*d == '(')
+	  nparen--;
+	d--;
+      }
+    }
+
+    if (*d == '.') {
+      char t = *(d + 1);
+      *(d + 1) = 0;
+      r = NewString(c);
+      *(d + 1) = t;
+      return r;
+    }
+  }
+  return NewStringEmpty();
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_strip_qualifiers()
+ * 
+ * Strip all qualifiers from a type and return a new type
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_strip_qualifiers(SwigType *t) {
+  static Hash *memoize_stripped = 0;
+  SwigType *r;
+  List *l;
+  Iterator ei;
+
+  if (!memoize_stripped)
+    memoize_stripped = NewHash();
+  r = Getattr(memoize_stripped, t);
+  if (r)
+    return Copy(r);
+
+  l = SwigType_split(t);
+  r = NewStringEmpty();
+
+  for (ei = First(l); ei.item; ei = Next(ei)) {
+    if (SwigType_isqualifier(ei.item))
+      continue;
+    Append(r, ei.item);
+  }
+  Delete(l);
+  {
+    String *key, *value;
+    key = Copy(t);
+    value = Copy(r);
+    Setattr(memoize_stripped, key, value);
+    Delete(key);
+    Delete(value);
+  }
+  return r;
+}
diff --git a/trunk/Source/Swig/typesys.c b/trunk/Source/Swig/typesys.c
new file mode 100644
index 0000000..ae6ab3d
--- /dev/null
+++ b/trunk/Source/Swig/typesys.c
@@ -0,0 +1,2073 @@
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * typesys.c
+ *
+ * SWIG type system management.   These functions are used to manage
+ * the C++ type system including typenames, typedef, type scopes, 
+ * inheritance, and namespaces.   Generation of support code for the
+ * run-time type checker is also handled here.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_typesys_c[] = "$Id$";
+
+#include "swig.h"
+#include "cparse.h"
+
+/* -----------------------------------------------------------------------------
+ * Synopsis
+ *
+ * The purpose of this module is to manage type names and scoping issues related
+ * to the C++ type system.   The primary use is tracking typenames through typedef
+ * and inheritance. 
+ *
+ * New typenames are introduced by typedef, class, and enum declarations.
+ * Each type is declared in a scope.  This is either the global scope, a
+ * class, or a namespace.  For example:
+ *
+ *  typedef int A;         // Typename A, in global scope
+ *  namespace Foo {
+ *    typedef int A;       // Typename A, in scope Foo::
+ *  }
+ *  class Bar {            // Typename Bar, in global scope
+ *    typedef int A;       // Typename A, in scope Bar::
+ *  }
+ *
+ * To manage scopes, the type system is constructed as a tree of hash tables.  Each 
+ * hash table contains the following attributes:
+ *
+ *    "name"            -  Scope name
+ *    "qname"           -  Fully qualified typename
+ *    "typetab"         -  Type table containing typenames and typedef information
+ *    "symtab"          -  Hash table of symbols defined in a scope
+ *    "inherit"         -  List of inherited scopes       
+ *    "parent"          -  Parent scope
+ * 
+ * Typedef information is stored in the "typetab" hash table.  For example,
+ * if you have these declarations:
+ *
+ *      typedef int A;
+ *      typedef A B;
+ *      typedef B *C;
+ *
+ * typetab is built as follows:
+ *
+ *      "A"     : "int"
+ *      "B"     : "A"
+ *      "C"     : "p.B"
+ *
+ * To resolve a type back to its root type, one repeatedly expands on the type base.
+ * For example:
+ *
+ *     C *[40]   ---> a(40).p.C       (string type representation, see stype.c)
+ *               ---> a(40).p.p.B     (C --> p.B)
+ *               ---> a(40).p.p.A     (B --> A)
+ *               ---> a(40).p.p.int   (A --> int)
+ *
+ * For inheritance, SWIG tries to resolve types back to the base class. For instance, if
+ * you have this:
+ *
+ *     class Foo {
+ *     public:
+ *        typedef int Integer;
+ *     };
+ *
+ *     class Bar : public Foo {
+ *           void blah(Integer x);
+ *     }
+ *
+ * The argument type of Bar::blah will be set to Foo::Integer.   
+ *
+ * The scope-inheritance mechanism is used to manage C++ namespace aliases.
+ * For example, if you have this:
+ *
+ *    namespace Foo {
+ *         typedef int Integer;
+ *    }
+ *
+ *   namespace F = Foo;
+ *
+ * In this case, "F::" is defined as a scope that "inherits" from Foo.  Internally,
+ * "F::" will merely be an empty scope that refers to Foo.  SWIG will never 
+ * place new type information into a namespace alias---attempts to do so
+ * will generate a warning message (in the parser) and will place information into 
+ * Foo instead.
+ *
+ *----------------------------------------------------------------------------- */
+
+static Typetab *current_scope = 0;	/* Current type scope                           */
+static Hash *current_typetab = 0;	/* Current type table                           */
+static Hash *current_symtab = 0;	/* Current symbol table                         */
+static Typetab *global_scope = 0;	/* The global scope                             */
+static Hash *scopes = 0;	/* Hash table containing fully qualified scopes */
+
+/* Performance optimization */
+#define SWIG_TYPEDEF_RESOLVE_CACHE
+static Hash *typedef_resolve_cache = 0;
+static Hash *typedef_all_cache = 0;
+static Hash *typedef_qualified_cache = 0;
+
+static Typetab *SwigType_find_scope(Typetab *s, String *nameprefix);
+
+/* common attribute keys, to avoid calling find_key all the times */
+
+/* 
+   Enable this one if your language fully support SwigValueWrapper<T>.
+   
+   Leaving at '0' keeps the old swig behavior, which is not
+   always safe, but is well known.
+
+   Setting at '1' activates the new scheme, which is always safe but
+   it requires all the typemaps to be ready for that.
+  
+*/
+static int value_wrapper_mode = 0;
+int Swig_value_wrapper_mode(int mode) {
+  value_wrapper_mode = mode;
+  return mode;
+}
+
+
+static void flush_cache() {
+  typedef_resolve_cache = 0;
+  typedef_all_cache = 0;
+  typedef_qualified_cache = 0;
+}
+
+/* Initialize the scoping system */
+
+void SwigType_typesystem_init() {
+  if (global_scope)
+    Delete(global_scope);
+  if (scopes)
+    Delete(scopes);
+
+  current_scope = NewHash();
+  global_scope = current_scope;
+
+  Setattr(current_scope, "name", "");	/* No name for global scope */
+  current_typetab = NewHash();
+  Setattr(current_scope, "typetab", current_typetab);
+
+  current_symtab = 0;
+  scopes = NewHash();
+  Setattr(scopes, "", current_scope);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_typedef()
+ *
+ * Defines a new typedef in the current scope. Returns -1 if the type name is 
+ * already defined.  
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_typedef(SwigType *type, String_or_char *name) {
+  if (Getattr(current_typetab, name))
+    return -1;			/* Already defined */
+  if (Strcmp(type, name) == 0) {	/* Can't typedef a name to itself */
+    return 0;
+  }
+
+  /* Check if 'type' is already a scope.  If so, we create an alias in the type
+     system for it.  This is needed to make strange nested scoping problems work
+     correctly.  */
+  {
+    Typetab *t = SwigType_find_scope(current_scope, type);
+    if (t) {
+      SwigType_new_scope(name);
+      SwigType_inherit_scope(t);
+      SwigType_pop_scope();
+    }
+  }
+  Setattr(current_typetab, name, type);
+  flush_cache();
+  return 0;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_typedef_class()
+ *
+ * Defines a class in the current scope. 
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_typedef_class(String_or_char *name) {
+  String *cname;
+  /*  Printf(stdout,"class : '%s'\n", name); */
+  if (Getattr(current_typetab, name))
+    return -1;			/* Already defined */
+  cname = NewString(name);
+  Setmeta(cname, "class", "1");
+  Setattr(current_typetab, cname, cname);
+  Delete(cname);
+  flush_cache();
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_scope_name()
+ *
+ * Returns the qualified scope name of a type table
+ * ----------------------------------------------------------------------------- */
+
+String *SwigType_scope_name(Typetab *ttab) {
+  String *qname = NewString(Getattr(ttab, "name"));
+  ttab = Getattr(ttab, "parent");
+  while (ttab) {
+    String *pname = Getattr(ttab, "name");
+    if (Len(pname)) {
+      Insert(qname, 0, "::");
+      Insert(qname, 0, pname);
+    }
+    ttab = Getattr(ttab, "parent");
+  }
+  return qname;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_new_scope()
+ *
+ * Creates a new scope
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_new_scope(const String_or_char *name) {
+  Typetab *s;
+  Hash *ttab;
+  String *qname;
+
+  if (!name) {
+    name = "<unnamed>";
+  }
+  s = NewHash();
+  Setattr(s, "name", name);
+  Setattr(s, "parent", current_scope);
+  ttab = NewHash();
+  Setattr(s, "typetab", ttab);
+
+  /* Build fully qualified name and */
+  qname = SwigType_scope_name(s);
+  Setattr(scopes, qname, s);
+  Setattr(s, "qname", qname);
+  Delete(qname);
+
+  current_scope = s;
+  current_typetab = ttab;
+  current_symtab = 0;
+  flush_cache();
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_inherit_scope()
+ *
+ * Makes the current scope inherit from another scope.  This is used for both
+ * C++ class inheritance, namespaces, and namespace aliases.
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_inherit_scope(Typetab *scope) {
+  List *inherits;
+  int i, len;
+  inherits = Getattr(current_scope, "inherit");
+  if (!inherits) {
+    inherits = NewList();
+    Setattr(current_scope, "inherit", inherits);
+    Delete(inherits);
+  }
+  assert(scope != current_scope);
+
+  len = Len(inherits);
+  for (i = 0; i < len; i++) {
+    Node *n = Getitem(inherits, i);
+    if (n == scope)
+      return;
+  }
+  Append(inherits, scope);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_scope_alias()
+ *
+ * Creates a scope-alias.
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_scope_alias(String *aliasname, Typetab *ttab) {
+  String *q;
+  /*  Printf(stdout,"alias: '%s' '%x'\n", aliasname, ttab); */
+  q = SwigType_scope_name(current_scope);
+  if (Len(q)) {
+    Append(q, "::");
+  }
+  Append(q, aliasname);
+  Setattr(scopes, q, ttab);
+  flush_cache();
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_using_scope()
+ *
+ * Import another scope into this scope.
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_using_scope(Typetab *scope) {
+  SwigType_inherit_scope(scope);
+  {
+    List *ulist;
+    int i, len;
+    ulist = Getattr(current_scope, "using");
+    if (!ulist) {
+      ulist = NewList();
+      Setattr(current_scope, "using", ulist);
+      Delete(ulist);
+    }
+    assert(scope != current_scope);
+    len = Len(ulist);
+    for (i = 0; i < len; i++) {
+      Typetab *n = Getitem(ulist, i);
+      if (n == scope)
+	return;
+    }
+    Append(ulist, scope);
+  }
+  flush_cache();
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_pop_scope()
+ *
+ * Pop off the last scope and perform a merge operation.  Returns the hash
+ * table for the scope that was popped off.
+ * ----------------------------------------------------------------------------- */
+
+Typetab *SwigType_pop_scope() {
+  Typetab *t, *old = current_scope;
+  t = Getattr(current_scope, "parent");
+  if (!t)
+    t = global_scope;
+  current_scope = t;
+  current_typetab = Getattr(t, "typetab");
+  current_symtab = Getattr(t, "symtab");
+  flush_cache();
+  return old;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_set_scope()
+ *
+ * Set the scope.  Returns the old scope.
+ * ----------------------------------------------------------------------------- */
+
+Typetab *SwigType_set_scope(Typetab *t) {
+  Typetab *old = current_scope;
+  if (!t)
+    t = global_scope;
+  current_scope = t;
+  current_typetab = Getattr(t, "typetab");
+  current_symtab = Getattr(t, "symtab");
+  flush_cache();
+  return old;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_attach_symtab()
+ *
+ * Attaches a symbol table to a type scope
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_attach_symtab(Symtab *sym) {
+  Setattr(current_scope, "symtab", sym);
+  current_symtab = sym;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_print_scope()
+ *
+ * Debugging function for printing out current scope
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_print_scope(Typetab *t) {
+  Hash *ttab;
+  Iterator i, j;
+
+  for (i = First(scopes); i.key; i = Next(i)) {
+    t = i.item;
+    ttab = Getattr(i.item, "typetab");
+
+    Printf(stdout, "Type scope '%s' (%x)\n", i.key, i.item);
+    {
+      List *inherit = Getattr(i.item, "inherit");
+      if (inherit) {
+	Iterator j;
+	for (j = First(inherit); j.item; j = Next(j)) {
+	  Printf(stdout, "    Inherits from '%s' (%x)\n", Getattr(j.item, "qname"), j.item);
+	}
+      }
+    }
+    Printf(stdout, "-------------------------------------------------------------\n");
+    for (j = First(ttab); j.key; j = Next(j)) {
+      Printf(stdout, "%40s -> %s\n", j.key, j.item);
+    }
+  }
+}
+
+static Typetab *SwigType_find_scope(Typetab *s, String *nameprefix) {
+  Typetab *ss;
+  String *nnameprefix = 0;
+  static int check_parent = 1;
+
+  /*  Printf(stdout,"find_scope: %x(%s) '%s'\n", s, Getattr(s,"name"), nameprefix); */
+
+  if (SwigType_istemplate(nameprefix)) {
+    nnameprefix = SwigType_typedef_resolve_all(nameprefix);
+    nameprefix = nnameprefix;
+  }
+
+  ss = s;
+  while (ss) {
+    String *full;
+    String *qname = Getattr(ss, "qname");
+    if (qname) {
+      full = NewStringf("%s::%s", qname, nameprefix);
+    } else {
+      full = NewString(nameprefix);
+    }
+    if (Getattr(scopes, full)) {
+      s = Getattr(scopes, full);
+    } else {
+      s = 0;
+    }
+    Delete(full);
+    if (s) {
+      if (nnameprefix)
+	Delete(nnameprefix);
+      return s;
+    }
+    if (!s) {
+      /* Check inheritance */
+      List *inherit;
+      inherit = Getattr(ss, "using");
+      if (inherit) {
+	Typetab *ttab;
+	int i, len;
+	len = Len(inherit);
+	for (i = 0; i < len; i++) {
+	  int oldcp = check_parent;
+	  ttab = Getitem(inherit, i);
+	  check_parent = 0;
+	  s = SwigType_find_scope(ttab, nameprefix);
+	  check_parent = oldcp;
+	  if (s) {
+	    if (nnameprefix)
+	      Delete(nnameprefix);
+	    return s;
+	  }
+	}
+      }
+    }
+    if (!check_parent)
+      break;
+    ss = Getattr(ss, "parent");
+  }
+  if (nnameprefix)
+    Delete(nnameprefix);
+  return 0;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * typedef_resolve()
+ *
+ * Resolves a typedef and returns a new type string.  Returns 0 if there is no
+ * typedef mapping.  base is a name without qualification.
+ * Internal function.
+ * ----------------------------------------------------------------------------- */
+
+static Typetab *resolved_scope = 0;
+
+/* Internal function */
+
+static SwigType *_typedef_resolve(Typetab *s, String *base, int look_parent) {
+  Hash *ttab;
+  SwigType *type = 0;
+  List *inherit;
+  Typetab *parent;
+
+  /* if (!s) return 0; *//* now is checked bellow */
+  /* Printf(stdout,"Typetab %s : %s\n", Getattr(s,"name"), base);  */
+
+  if (!Getmark(s)) {
+    Setmark(s, 1);
+
+    ttab = Getattr(s, "typetab");
+    type = Getattr(ttab, base);
+    if (type) {
+      resolved_scope = s;
+      Setmark(s, 0);
+    } else {
+      /* Hmmm. Not found in my scope.  It could be in an inherited scope */
+      inherit = Getattr(s, "inherit");
+      if (inherit) {
+	int i, len;
+	len = Len(inherit);
+	for (i = 0; i < len; i++) {
+	  type = _typedef_resolve(Getitem(inherit, i), base, 0);
+	  if (type) {
+	    Setmark(s, 0);
+	    break;
+	  }
+	}
+      }
+      if (!type) {
+	/* Hmmm. Not found in my scope.  check parent */
+	if (look_parent) {
+	  parent = Getattr(s, "parent");
+	  type = parent ? _typedef_resolve(parent, base, 1) : 0;
+	}
+      }
+      Setmark(s, 0);
+    }
+  }
+  return type;
+}
+
+static SwigType *typedef_resolve(Typetab *s, String *base) {
+  return _typedef_resolve(s, base, 1);
+}
+
+
+/* ----------------------------------------------------------------------------- 
+ * SwigType_typedef_resolve()
+ * ----------------------------------------------------------------------------- */
+
+/* #define SWIG_DEBUG */
+SwigType *SwigType_typedef_resolve(SwigType *t) {
+  String *base;
+  String *type = 0;
+  String *r = 0;
+  Typetab *s;
+  Hash *ttab;
+  String *namebase = 0;
+  String *nameprefix = 0;
+  int newtype = 0;
+
+  /*
+     if (!noscope) {
+     noscope = NewStringEmpty();
+     }
+   */
+
+  resolved_scope = 0;
+
+#ifdef SWIG_TYPEDEF_RESOLVE_CACHE
+  if (!typedef_resolve_cache) {
+    typedef_resolve_cache = NewHash();
+  }
+  r = Getattr(typedef_resolve_cache, t);
+  if (r) {
+    resolved_scope = Getmeta(r, "scope");
+    return Copy(r);
+  }
+#endif
+
+  base = SwigType_base(t);
+
+#ifdef SWIG_DEBUG
+  Printf(stdout, "base = '%s' t='%s'\n", base, t);
+#endif
+
+  if (SwigType_issimple(base)) {
+    s = current_scope;
+    ttab = current_typetab;
+    if (strncmp(Char(base), "::", 2) == 0) {
+      s = global_scope;
+      ttab = Getattr(s, "typetab");
+      Delitem(base, 0);
+      Delitem(base, 0);
+    }
+    /* Do a quick check in the local scope */
+    type = Getattr(ttab, base);
+    if (type) {
+      resolved_scope = s;
+    }
+    if (!type) {
+      /* Didn't find in this scope.   We need to do a little more searching */
+      if (Swig_scopename_check(base)) {
+	/* A qualified name. */
+	Swig_scopename_split(base, &nameprefix, &namebase);
+#ifdef SWIG_DEBUG
+	Printf(stdout, "nameprefix = '%s'\n", nameprefix);
+#endif
+	if (nameprefix) {
+	  /* Name had a prefix on it.   See if we can locate the proper scope for it */
+	  s = SwigType_find_scope(s, nameprefix);
+
+	  /* Couldn't locate a scope for the type.  */
+	  if (!s) {
+	    Delete(base);
+	    Delete(namebase);
+	    Delete(nameprefix);
+	    r = 0;
+	    goto return_result;
+	  }
+	  /* Try to locate the name starting in the scope */
+#ifdef SWIG_DEBUG
+	  Printf(stdout, "namebase = '%s'\n", namebase);
+#endif
+	  type = typedef_resolve(s, namebase);
+	  if (type) {
+	    /* we need to look for the resolved type, this will also
+	       fix the resolved_scope if 'type' and 'namebase' are
+	       declared in different scopes */
+	    String *rtype = 0;
+	    rtype = typedef_resolve(resolved_scope, type);
+	    if (rtype)
+	      type = rtype;
+	  }
+#ifdef SWIG_DEBUG
+	  Printf(stdout, "%s type = '%s'\n", Getattr(s, "name"), type);
+#endif
+	  if ((type) && (!Swig_scopename_check(type)) && resolved_scope) {
+	    Typetab *rtab = resolved_scope;
+	    String *qname = Getattr(resolved_scope, "qname");
+	    /* If qualified *and* the typename is defined from the resolved scope, we qualify */
+	    if ((qname) && typedef_resolve(resolved_scope, type)) {
+	      type = Copy(type);
+	      Insert(type, 0, "::");
+	      Insert(type, 0, qname);
+#ifdef SWIG_DEBUG
+	      Printf(stdout, "qual %s \n", type);
+#endif
+	      newtype = 1;
+	    }
+	    resolved_scope = rtab;
+	  }
+	} else {
+	  /* Name is unqualified. */
+	  type = typedef_resolve(s, base);
+	}
+      } else {
+	/* Name is unqualified. */
+	type = typedef_resolve(s, base);
+      }
+    }
+
+    if (type && (Equal(base, type))) {
+      if (newtype)
+	Delete(type);
+      Delete(base);
+      Delete(namebase);
+      Delete(nameprefix);
+      r = 0;
+      goto return_result;
+    }
+
+    /* If the type is a template, and no typedef was found, we need to check the
+       template arguments one by one to see if they can be resolved. */
+
+    if (!type && SwigType_istemplate(base)) {
+      List *tparms;
+      String *suffix;
+      int i, sz;
+      int rep = 0;
+      type = SwigType_templateprefix(base);
+      newtype = 1;
+      suffix = SwigType_templatesuffix(base);
+      Append(type, "<(");
+      tparms = SwigType_parmlist(base);
+      sz = Len(tparms);
+      for (i = 0; i < sz; i++) {
+	SwigType *tpr;
+	SwigType *tp = Getitem(tparms, i);
+	if (!rep) {
+	  tpr = SwigType_typedef_resolve(tp);
+	} else {
+	  tpr = 0;
+	}
+	if (tpr) {
+	  Append(type, tpr);
+	  Delete(tpr);
+	  rep = 1;
+	} else {
+	  Append(type, tp);
+	}
+	if ((i + 1) < sz)
+	  Append(type, ",");
+      }
+      Append(type, ")>");
+      Append(type, suffix);
+      Delete(suffix);
+      Delete(tparms);
+      if (!rep) {
+	Delete(type);
+	type = 0;
+      }
+    }
+    if (namebase)
+      Delete(namebase);
+    if (nameprefix)
+      Delete(nameprefix);
+  } else {
+    if (SwigType_isfunction(base)) {
+      List *parms;
+      int i, sz;
+      int rep = 0;
+      type = NewString("f(");
+      newtype = 1;
+      parms = SwigType_parmlist(base);
+      sz = Len(parms);
+      for (i = 0; i < sz; i++) {
+	SwigType *tpr;
+	SwigType *tp = Getitem(parms, i);
+	if (!rep) {
+	  tpr = SwigType_typedef_resolve(tp);
+	} else {
+	  tpr = 0;
+	}
+	if (tpr) {
+	  Append(type, tpr);
+	  Delete(tpr);
+	  rep = 1;
+	} else {
+	  Append(type, tp);
+	}
+	if ((i + 1) < sz)
+	  Append(type, ",");
+      }
+      Append(type, ").");
+      Delete(parms);
+      if (!rep) {
+	Delete(type);
+	type = 0;
+      }
+    } else if (SwigType_ismemberpointer(base)) {
+      String *rt;
+      String *mtype = SwigType_parm(base);
+      rt = SwigType_typedef_resolve(mtype);
+      if (rt) {
+	type = NewStringf("m(%s).", rt);
+	newtype = 1;
+	Delete(rt);
+      }
+      Delete(mtype);
+    } else {
+      type = 0;
+    }
+  }
+  r = SwigType_prefix(t);
+  if (!type) {
+    if (r && Len(r)) {
+      char *cr = Char(r);
+      if ((strstr(cr, "f(") || (strstr(cr, "m(")))) {
+	SwigType *rt = SwigType_typedef_resolve(r);
+	if (rt) {
+	  Delete(r);
+	  Append(rt, base);
+	  Delete(base);
+	  r = rt;
+	  goto return_result;
+	}
+      }
+    }
+    Delete(r);
+    Delete(base);
+    r = 0;
+    goto return_result;
+  }
+  Delete(base);
+  Append(r, type);
+  if (newtype) {
+    Delete(type);
+  }
+
+return_result:
+#ifdef SWIG_TYPEDEF_RESOLVE_CACHE
+  {
+    String *key = NewString(t);
+    if (r) {
+      SwigType *r1;
+      Setattr(typedef_resolve_cache, key, r);
+      Setmeta(r, "scope", resolved_scope);
+      r1 = Copy(r);
+      Delete(r);
+      r = r1;
+    }
+    Delete(key);
+  }
+#endif
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_typedef_resolve_all()
+ *
+ * Fully resolve a type down to its most basic datatype
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_typedef_resolve_all(SwigType *t) {
+  SwigType *n;
+  SwigType *r;
+
+  /* Check to see if the typedef resolve has been done before by checking the cache */
+  if (!typedef_all_cache) {
+    typedef_all_cache = NewHash();
+  }
+  r = Getattr(typedef_all_cache, t);
+  if (r) {
+    return Copy(r);
+  }
+
+  /* Recursively resolve the typedef */
+  r = NewString(t);
+  while ((n = SwigType_typedef_resolve(r))) {
+    Delete(r);
+    r = n;
+  }
+
+  /* Add the typedef to the cache for next time it is looked up */
+  {
+    String *key;
+    SwigType *rr = Copy(r);
+    key = NewString(t);
+    Setattr(typedef_all_cache, key, rr);
+    Delete(key);
+    Delete(rr);
+  }
+  return r;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_typedef_qualified()
+ *
+ * Given a type declaration, this function tries to fully qualify it according to
+ * typedef scope rules.
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_typedef_qualified(SwigType *t) {
+  List *elements;
+  String *result;
+  int i, len;
+
+  if (t && strncmp(Char(t), "::", 2) == 0) {
+    return Copy(t);
+  }
+
+  if (!typedef_qualified_cache)
+    typedef_qualified_cache = NewHash();
+  result = Getattr(typedef_qualified_cache, t);
+  if (result) {
+    String *rc = Copy(result);
+    return rc;
+  }
+
+  result = NewStringEmpty();
+  elements = SwigType_split(t);
+  len = Len(elements);
+  for (i = 0; i < len; i++) {
+    String *ty = 0;
+    String *e = Getitem(elements, i);
+    if (SwigType_issimple(e)) {
+      if (!SwigType_istemplate(e)) {
+	String *isenum = 0;
+	if (SwigType_isenum(e)) {
+	  isenum = NewString("enum ");
+	  ty = NewString(Char(e) + 5);
+	  e = ty;
+	}
+	resolved_scope = 0;
+	if (typedef_resolve(current_scope, e)) {
+	  /* resolved_scope contains the scope that actually resolved the symbol */
+	  String *qname = Getattr(resolved_scope, "qname");
+	  if (qname) {
+	    Insert(e, 0, "::");
+	    Insert(e, 0, qname);
+	  }
+	} else {
+	  if (Swig_scopename_check(e)) {
+	    String *qlast;
+	    String *qname;
+	    Swig_scopename_split(e, &qname, &qlast);
+	    if (qname) {
+	      String *tqname = SwigType_typedef_qualified(qname);
+	      Clear(e);
+	      Printf(e, "%s::%s", tqname, qlast);
+	      Delete(qname);
+	      Delete(tqname);
+	    }
+	    Delete(qlast);
+
+	    /* Automatic template instantiation might go here??? */
+	  } else {
+	    /* It's a bare name.  It's entirely possible, that the
+	       name is part of a namespace. We'll check this by unrolling
+	       out of the current scope */
+
+	    Typetab *cs = current_scope;
+	    while (cs) {
+	      String *qs = SwigType_scope_name(cs);
+	      if (Len(qs)) {
+		Append(qs, "::");
+	      }
+	      Append(qs, e);
+	      if (Getattr(scopes, qs)) {
+		Clear(e);
+		Append(e, qs);
+		Delete(qs);
+		break;
+	      }
+	      Delete(qs);
+	      cs = Getattr(cs, "parent");
+	    }
+	  }
+	}
+	if (isenum) {
+	  Insert(e, 0, isenum);
+	  Delete(isenum);
+	}
+      } else {
+	/* Template.  We need to qualify template parameters as well as the template itself */
+	String *tprefix, *qprefix;
+	String *tsuffix;
+	Iterator pi;
+	Parm *p;
+	List *parms;
+	ty = Swig_symbol_template_deftype(e, current_symtab);
+	e = ty;
+	parms = SwigType_parmlist(e);
+	tprefix = SwigType_templateprefix(e);
+	tsuffix = SwigType_templatesuffix(e);
+	qprefix = SwigType_typedef_qualified(tprefix);
+	Append(qprefix, "<(");
+	pi = First(parms);
+	while ((p = pi.item)) {
+	  String *qt = SwigType_typedef_qualified(p);
+	  if (Equal(qt, p)) {	/*  && (!Swig_scopename_check(qt))) */
+	    /* No change in value.  It is entirely possible that the parameter is an integer value.
+	       If there is a symbol table associated with this scope, we're going to check for this */
+
+	    if (current_symtab) {
+	      Node *lastnode = 0;
+	      String *value = Copy(p);
+	      while (1) {
+		Node *n = Swig_symbol_clookup(value, current_symtab);
+		if (n == lastnode)
+		  break;
+		lastnode = n;
+		if (n) {
+		  char *ntype = Char(nodeType(n));
+		  if (strcmp(ntype, "enumitem") == 0) {
+		    /* An enum item.   Generate a fully qualified name */
+		    String *qn = Swig_symbol_qualified(n);
+		    if (Len(qn)) {
+		      Append(qn, "::");
+		      Append(qn, Getattr(n, "name"));
+		      Delete(value);
+		      value = qn;
+		      continue;
+		    } else {
+		      Delete(qn);
+		      break;
+		    }
+		  } else if ((strcmp(ntype, "cdecl") == 0) && (Getattr(n, "value"))) {
+		    Delete(value);
+		    value = Copy(Getattr(n, "value"));
+		    continue;
+		  }
+		}
+		break;
+	      }
+	      Append(qprefix, value);
+	      Delete(value);
+	    } else {
+	      Append(qprefix, p);
+	    }
+	  } else {
+	    Append(qprefix, qt);
+	  }
+	  Delete(qt);
+	  pi = Next(pi);
+	  if (pi.item) {
+	    Append(qprefix, ",");
+	  }
+	}
+	Append(qprefix, ")>");
+	Append(qprefix, tsuffix);
+	Delete(tsuffix);
+	Clear(e);
+	Append(e, qprefix);
+	Delete(tprefix);
+	Delete(qprefix);
+	Delete(parms);
+      }
+      if (strncmp(Char(e), "::", 2) == 0) {
+	Delitem(e, 0);
+	Delitem(e, 0);
+      }
+      Append(result, e);
+      Delete(ty);
+    } else if (SwigType_isfunction(e)) {
+      List *parms = SwigType_parmlist(e);
+      String *s = NewString("f(");
+      Iterator pi;
+      pi = First(parms);
+      while (pi.item) {
+	String *pq = SwigType_typedef_qualified(pi.item);
+	Append(s, pq);
+	Delete(pq);
+	pi = Next(pi);
+	if (pi.item) {
+	  Append(s, ",");
+	}
+      }
+      Append(s, ").");
+      Append(result, s);
+      Delete(s);
+      Delete(parms);
+    } else if (SwigType_isarray(e)) {
+      String *ndim;
+      String *dim = SwigType_parm(e);
+      ndim = Swig_symbol_string_qualify(dim, 0);
+      Printf(result, "a(%s).", ndim);
+      Delete(dim);
+      Delete(ndim);
+    } else {
+      Append(result, e);
+    }
+  }
+  Delete(elements);
+  {
+    String *key, *cresult;
+    key = NewString(t);
+    cresult = NewString(result);
+    Setattr(typedef_qualified_cache, key, cresult);
+    Delete(key);
+    Delete(cresult);
+  }
+  return result;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * SwigType_istypedef()
+ *
+ * Checks a typename to see if it is a typedef.
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_istypedef(SwigType *t) {
+  String *type;
+
+  type = SwigType_typedef_resolve(t);
+  if (type) {
+    Delete(type);
+    return 1;
+  } else {
+    return 0;
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_typedef_using()
+ *
+ * Processes a 'using' declaration to import types from one scope into another.
+ * Name is a qualified name like A::B.
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_typedef_using(String_or_char *name) {
+  String *base;
+  String *td;
+  String *prefix;
+  Typetab *s;
+  Typetab *tt = 0;
+
+  String *defined_name = 0;
+
+  /*  Printf(stdout,"using %s\n", name); */
+
+  if (!Swig_scopename_check(name))
+    return -1;			/* Not properly qualified */
+  base = Swig_scopename_last(name);
+
+  /* See if the base is already defined in this scope */
+  if (Getattr(current_typetab, base)) {
+    Delete(base);
+    return -1;
+  }
+
+  /* See if the using name is a scope */
+  /*  tt = SwigType_find_scope(current_scope,name);
+     Printf(stdout,"tt = %x, name = '%s'\n", tt, name); */
+
+  /* We set up a typedef  B --> A::B */
+  Setattr(current_typetab, base, name);
+
+  /* Find the scope name where the symbol is defined */
+  td = SwigType_typedef_resolve(name);
+  /*  Printf(stdout,"td = '%s' %x\n", td, resolved_scope); */
+  if (resolved_scope) {
+    defined_name = Getattr(resolved_scope, "qname");
+    if (defined_name) {
+      defined_name = Copy(defined_name);
+      Append(defined_name, "::");
+      Append(defined_name, base);
+      /*  Printf(stdout,"defined_name = '%s'\n", defined_name); */
+      tt = SwigType_find_scope(current_scope, defined_name);
+    }
+  }
+  if (td)
+    Delete(td);
+
+
+  /* Figure out the scope the using directive refers to */
+  {
+    prefix = Swig_scopename_prefix(name);
+    s = SwigType_find_scope(current_scope, prefix);
+    if (s) {
+      Hash *ttab = Getattr(s, "typetab");
+      if (!Getattr(ttab, base) && defined_name) {
+	Setattr(ttab, base, defined_name);
+      }
+    }
+  }
+
+  if (tt) {
+    /* Using directive had its own scope.  We need to create a new scope for it */
+    SwigType_new_scope(base);
+    SwigType_inherit_scope(tt);
+    SwigType_pop_scope();
+  }
+
+  if (defined_name)
+    Delete(defined_name);
+  Delete(prefix);
+  Delete(base);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_isclass()
+ *
+ * Determines if a type defines a class or not.   A class is defined by
+ * its type-table entry maps to itself.  Note: a pointer to a class is not
+ * a class.
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_isclass(SwigType *t) {
+  SwigType *qty, *qtys;
+  int isclass = 0;
+
+  qty = SwigType_typedef_resolve_all(t);
+  qtys = SwigType_strip_qualifiers(qty);
+  if (SwigType_issimple(qtys)) {
+    String *td = SwigType_typedef_resolve(qtys);
+    if (td) {
+      Delete(td);
+    }
+    if (resolved_scope) {
+      isclass = 1;
+    }
+    /* Hmmm. Not a class.  If a template, it might be uninstantiated */
+    if (!isclass && SwigType_istemplate(qtys)) {
+      String *tp = SwigType_templateprefix(qtys);
+      if (Strcmp(tp, t) != 0) {
+	isclass = SwigType_isclass(tp);
+      }
+      Delete(tp);
+    }
+  }
+  Delete(qty);
+  Delete(qtys);
+  return isclass;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_type()
+ *
+ * Returns an integer code describing the datatype.  This is only used for
+ * compatibility with SWIG1.1 language modules and is likely to go away once
+ * everything is based on typemaps.
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_type(SwigType *t) {
+  char *c;
+  /* Check for the obvious stuff */
+  c = Char(t);
+
+  if (strncmp(c, "p.", 2) == 0) {
+    if (SwigType_type(c + 2) == T_CHAR)
+      return T_STRING;
+    else
+      return T_POINTER;
+  }
+  if (strncmp(c, "a(", 2) == 0)
+    return T_ARRAY;
+  if (strncmp(c, "r.", 2) == 0)
+    return T_REFERENCE;
+  if (strncmp(c, "m(", 2) == 0)
+    return T_MPOINTER;
+  if (strncmp(c, "q(", 2) == 0) {
+    while (*c && (*c != '.'))
+      c++;
+    if (*c)
+      return SwigType_type(c + 1);
+    return T_ERROR;
+  }
+  if (strncmp(c, "f(", 2) == 0)
+    return T_FUNCTION;
+
+  /* Look for basic types */
+  if (strcmp(c, "int") == 0)
+    return T_INT;
+  if (strcmp(c, "long") == 0)
+    return T_LONG;
+  if (strcmp(c, "short") == 0)
+    return T_SHORT;
+  if (strcmp(c, "unsigned") == 0)
+    return T_UINT;
+  if (strcmp(c, "unsigned short") == 0)
+    return T_USHORT;
+  if (strcmp(c, "unsigned long") == 0)
+    return T_ULONG;
+  if (strcmp(c, "unsigned int") == 0)
+    return T_UINT;
+  if (strcmp(c, "char") == 0)
+    return T_CHAR;
+  if (strcmp(c, "signed char") == 0)
+    return T_SCHAR;
+  if (strcmp(c, "unsigned char") == 0)
+    return T_UCHAR;
+  if (strcmp(c, "float") == 0)
+    return T_FLOAT;
+  if (strcmp(c, "double") == 0)
+    return T_DOUBLE;
+  if (strcmp(c, "long double") == 0)
+    return T_LONGDOUBLE;
+  if (!cparse_cplusplus && (strcmp(c, "float complex") == 0))
+    return T_FLTCPLX;
+  if (!cparse_cplusplus && (strcmp(c, "double complex") == 0))
+    return T_DBLCPLX;
+  if (!cparse_cplusplus && (strcmp(c, "complex") == 0))
+    return T_COMPLEX;
+  if (strcmp(c, "void") == 0)
+    return T_VOID;
+  if (strcmp(c, "bool") == 0)
+    return T_BOOL;
+  if (strcmp(c, "long long") == 0)
+    return T_LONGLONG;
+  if (strcmp(c, "unsigned long long") == 0)
+    return T_ULONGLONG;
+  if (strncmp(c, "enum ", 5) == 0)
+    return T_INT;
+
+  if (strcmp(c, "v(...)") == 0)
+    return T_VARARGS;
+  /* Hmmm. Unknown type */
+  if (SwigType_istypedef(t)) {
+    int r;
+    SwigType *nt = SwigType_typedef_resolve(t);
+    r = SwigType_type(nt);
+    Delete(nt);
+    return r;
+  }
+  return T_USER;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_alttype()
+ *
+ * Returns the alternative value type needed in C++ for class value
+ * types. When swig is not sure about using a plain $ltype value,
+ * since the class doesn't have a default constructor, or it can't be
+ * assigned, you will get back 'SwigValueWrapper<type >'.
+ *
+ * This is the default behavior unless:
+ *
+ *  1.- swig detects a default_constructor and 'setallocate:default_constructor'
+ *      attribute.
+ *
+ *  2.- swig doesn't mark 'type' as non-assignable.
+ *
+ *  3.- the user specify that the value wrapper is not needed by using
+ *      the %feature("novaluewrapper"), in that case the user need to type
+ *
+ *        %feature("novaluewrapper") MyOpaqueClass;
+ *        class MyOpaqueClass;
+ *
+ * Users can also force the use of the value wrapper by using the
+ * %feature("valuewrapper").
+ * ----------------------------------------------------------------------------- */
+
+SwigType *SwigType_alttype(SwigType *t, int local_tmap) {
+  Node *n;
+  SwigType *w = 0;
+  int use_wrapper = 0;
+  SwigType *td = 0;
+
+  if (!cparse_cplusplus)
+    return 0;
+
+  if (value_wrapper_mode == 0) {
+    /* old partial use of SwigValueTypes, it can fail for opaque types */
+    if (local_tmap)
+      return 0;
+    if (SwigType_isclass(t)) {
+      SwigType *ftd = SwigType_typedef_resolve_all(t);
+      td = SwigType_strip_qualifiers(ftd);
+      Delete(ftd);
+      n = Swig_symbol_clookup(td, 0);
+      if (n) {
+	if (GetFlag(n, "feature:valuewrapper")) {
+	  use_wrapper = 1;
+	} else {
+	  if (Checkattr(n, "nodeType", "class")
+	      && (!Getattr(n, "allocate:default_constructor")
+		  || (Getattr(n, "allocate:noassign")))) {
+	    use_wrapper = !GetFlag(n, "feature:novaluewrapper") || GetFlag(n, "feature:nodefault");
+	  }
+	}
+      } else {
+	if (SwigType_issimple(td) && SwigType_istemplate(td)) {
+	  use_wrapper = !n || !GetFlag(n, "feature:novaluewrapper");
+	}
+      }
+    }
+  } else {
+    /* safe use of SwigValueTypes, it can fail with some typemaps */
+    SwigType *ftd = SwigType_typedef_resolve_all(t);
+    td = SwigType_strip_qualifiers(ftd);
+    Delete(ftd);
+    if (SwigType_type(td) == T_USER) {
+      use_wrapper = 1;
+      n = Swig_symbol_clookup(td, 0);
+      if (n) {
+	if ((Checkattr(n, "nodeType", "class")
+	     && !Getattr(n, "allocate:noassign")
+	     && (Getattr(n, "allocate:default_constructor")))
+	    || (GetFlag(n, "feature:novaluewrapper"))) {
+	  use_wrapper = GetFlag(n, "feature:valuewrapper");
+	}
+      }
+    }
+  }
+
+  if (use_wrapper) {
+    /* Need a space before the type in case it starts "::" (since the <:
+     * token is a digraph for [ in C++.  Also need a space after the
+     * type in case it ends with ">" since then we form the token ">>".
+     */
+    w = NewStringf("SwigValueWrapper< %s >", td);
+  }
+  Delete(td);
+  return w;
+}
+
+/* ----------------------------------------------------------------------------
+ *                         * * * WARNING * * *                            ***
+ *                                                                        ***
+ * Don't even think about modifying anything below this line unless you   ***
+ * are completely on top of *EVERY* subtle aspect of the C++ type system  ***
+ * and you are prepared to suffer endless hours of agony trying to        ***
+ * debug the SWIG run-time type checker after you break it.               ***
+ * ------------------------------------------------------------------------- */
+
+/* -----------------------------------------------------------------------------
+ * SwigType_remember()
+ *
+ * This function "remembers" a datatype that was used during wrapper code generation
+ * so that a type-checking table can be generated later on. It is up to the language
+ * modules to actually call this function--it is not done automatically.
+ *
+ * Type tracking is managed through two separate hash tables.  The hash 'r_mangled'
+ * is mapping between mangled type names (used in the target language) and 
+ * fully-resolved C datatypes used in the source input.   The second hash 'r_resolved'
+ * is the inverse mapping that maps fully-resolved C datatypes to all of the mangled
+ * names in the scripting languages.  For example, consider the following set of
+ * typedef declarations:
+ *
+ *      typedef double Real;
+ *      typedef double Float;
+ *      typedef double Point[3];
+ *
+ * Now, suppose that the types 'double *', 'Real *', 'Float *', 'double[3]', and
+ * 'Point' were used in an interface file and "remembered" using this function.
+ * The hash tables would look like this:
+ *
+ * r_mangled {
+ *   _p_double : [ p.double, a(3).double ]
+ *   _p_Real   : [ p.double ]
+ *   _p_Float  : [ p.double ]
+ *   _Point    : [ a(3).double ]
+ *
+ * r_resolved {
+ *   p.double     : [ _p_double, _p_Real, _p_Float ]
+ *   a(3).double  : [ _p_double, _Point ]
+ * }
+ *
+ * Together these two hash tables can be used to determine type-equivalency between
+ * mangled typenames.  To do this, we view the two hash tables as a large graph and
+ * compute the transitive closure.
+ * ----------------------------------------------------------------------------- */
+
+static Hash *r_mangled = 0;	/* Hash mapping mangled types to fully resolved types */
+static Hash *r_resolved = 0;	/* Hash mapping resolved types to mangled types       */
+static Hash *r_ltype = 0;	/* Hash mapping mangled names to their local c type   */
+static Hash *r_clientdata = 0;	/* Hash mapping resolved types to client data         */
+static Hash *r_mangleddata = 0;	/* Hash mapping mangled types to client data         */
+static Hash *r_remembered = 0;	/* Hash of types we remembered already */
+
+static void (*r_tracefunc) (SwigType *t, String *mangled, String *clientdata) = 0;
+
+void SwigType_remember_mangleddata(String *mangled, const String_or_char *clientdata) {
+  if (!r_mangleddata) {
+    r_mangleddata = NewHash();
+  }
+  Setattr(r_mangleddata, mangled, clientdata);
+}
+
+
+void SwigType_remember_clientdata(SwigType *t, const String_or_char *clientdata) {
+  String *mt;
+  SwigType *lt;
+  Hash *h;
+  SwigType *fr;
+  SwigType *qr;
+  String *tkey;
+  String *cd;
+  Hash *lthash;
+
+  if (!r_mangled) {
+    r_mangled = NewHash();
+    r_resolved = NewHash();
+    r_ltype = NewHash();
+    r_clientdata = NewHash();
+    r_remembered = NewHash();
+  }
+
+  {
+    String *last;
+    last = Getattr(r_remembered, t);
+    if (last && (Cmp(last, clientdata) == 0))
+      return;
+  }
+
+  tkey = Copy(t);
+  cd = clientdata ? NewString(clientdata) : NewStringEmpty();
+  Setattr(r_remembered, tkey, cd);
+  Delete(tkey);
+  Delete(cd);
+
+  mt = SwigType_manglestr(t);	/* Create mangled string */
+
+  if (r_tracefunc) {
+    (*r_tracefunc) (t, mt, (String *) clientdata);
+  }
+
+  if (SwigType_istypedef(t)) {
+    lt = Copy(t);
+  } else {
+    lt = SwigType_ltype(t);
+  }
+
+  lthash = Getattr(r_ltype, mt);
+  if (!lthash) {
+    lthash = NewHash();
+    Setattr(r_ltype, mt, lthash);
+  }
+  Setattr(lthash, lt, "1");
+  Delete(lt);
+
+  fr = SwigType_typedef_resolve_all(t);	/* Create fully resolved type */
+  qr = SwigType_typedef_qualified(fr);
+  Delete(fr);
+
+  /* Added to deal with possible table bug */
+  fr = SwigType_strip_qualifiers(qr);
+  Delete(qr);
+
+  /*Printf(stdout,"t = '%s'\n", t);
+     Printf(stdout,"fr= '%s'\n\n", fr); */
+
+  if (t) {
+    char *ct = Char(t);
+    if (strchr(ct, '<') && !(strstr(ct, "<("))) {
+      Printf(stdout, "Bad template type passed to SwigType_remember: %s\n", t);
+      assert(0);
+    }
+  }
+
+  h = Getattr(r_mangled, mt);
+  if (!h) {
+    h = NewHash();
+    Setattr(r_mangled, mt, h);
+    Delete(h);
+  }
+  Setattr(h, fr, mt);
+
+  h = Getattr(r_resolved, fr);
+  if (!h) {
+    h = NewHash();
+    Setattr(r_resolved, fr, h);
+    Delete(h);
+  }
+  Setattr(h, mt, fr);
+
+  if (clientdata) {
+    String *cd = Getattr(r_clientdata, fr);
+    if (cd) {
+      if (Strcmp(clientdata, cd) != 0) {
+	Printf(stderr, "*** Internal error. Inconsistent clientdata for type '%s'\n", SwigType_str(fr, 0));
+	Printf(stderr, "*** '%s' != '%s'\n", clientdata, cd);
+	assert(0);
+      }
+    } else {
+      String *cstr = NewString(clientdata);
+      Setattr(r_clientdata, fr, cstr);
+      Delete(cstr);
+    }
+  }
+
+  /* If the remembered type is a reference, we also remember the pointer version.
+     This is to prevent odd problems with mixing pointers and references--especially
+     when different functions are using different typenames (via typedef). */
+
+  if (SwigType_isreference(t)) {
+    SwigType *tt = Copy(t);
+    SwigType_del_reference(tt);
+    SwigType_add_pointer(tt);
+    SwigType_remember_clientdata(tt, clientdata);
+  }
+}
+
+void SwigType_remember(SwigType *ty) {
+  SwigType_remember_clientdata(ty, 0);
+}
+
+void (*SwigType_remember_trace(void (*tf) (SwigType *, String *, String *))) (SwigType *, String *, String *) {
+  void (*o) (SwigType *, String *, String *) = r_tracefunc;
+  r_tracefunc = tf;
+  return o;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_equivalent_mangle()
+ *
+ * Return a list of all of the mangled typenames that are equivalent to another
+ * mangled name.   This works as follows: For each fully qualified C datatype
+ * in the r_mangled hash entry, we collect all of the mangled names from the
+ * r_resolved hash and combine them together in a list (removing duplicate entries).
+ * ----------------------------------------------------------------------------- */
+
+List *SwigType_equivalent_mangle(String *ms, Hash *checked, Hash *found) {
+  List *l;
+  Hash *h;
+  Hash *ch;
+  Hash *mh;
+
+  if (found) {
+    h = found;
+  } else {
+    h = NewHash();
+  }
+  if (checked) {
+    ch = checked;
+  } else {
+    ch = NewHash();
+  }
+  if (Getattr(ch, ms))
+    goto check_exit;		/* Already checked this type */
+  Setattr(h, ms, "1");
+  Setattr(ch, ms, "1");
+  mh = Getattr(r_mangled, ms);
+  if (mh) {
+    Iterator ki;
+    ki = First(mh);
+    while (ki.key) {
+      Hash *rh;
+      if (Getattr(ch, ki.key)) {
+	ki = Next(ki);
+	continue;
+      }
+      Setattr(ch, ki.key, "1");
+      rh = Getattr(r_resolved, ki.key);
+      if (rh) {
+	Iterator rk;
+	rk = First(rh);
+	while (rk.key) {
+	  Setattr(h, rk.key, "1");
+	  SwigType_equivalent_mangle(rk.key, ch, h);
+	  rk = Next(rk);
+	}
+      }
+      ki = Next(ki);
+    }
+  }
+check_exit:
+  if (!found) {
+    l = Keys(h);
+    Delete(h);
+    Delete(ch);
+    return l;
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_clientdata_collect()
+ *
+ * Returns the clientdata field for a mangled type-string.
+ * ----------------------------------------------------------------------------- */
+
+static
+String *SwigType_clientdata_collect(String *ms) {
+  Hash *mh;
+  String *clientdata = 0;
+
+  if (r_mangleddata) {
+    clientdata = Getattr(r_mangleddata, ms);
+    if (clientdata)
+      return clientdata;
+  }
+
+  mh = Getattr(r_mangled, ms);
+  if (mh) {
+    Iterator ki;
+    ki = First(mh);
+    while (ki.key) {
+      clientdata = Getattr(r_clientdata, ki.key);
+      if (clientdata)
+	break;
+      ki = Next(ki);
+    }
+  }
+  return clientdata;
+}
+
+
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_inherit()
+ *
+ * Record information about inheritance.  We keep a hash table that keeps
+ * a mapping between base classes and all of the classes that are derived
+ * from them.
+ *
+ * subclass is a hash that maps base-classes to all of the classes derived from them.
+ *
+ * derived - name of derived class
+ * base - name of base class
+ * cast - additional casting code when casting from derived to base
+ * conversioncode - if set, overrides the default code in the function when casting
+ *                from derived to base
+ * ----------------------------------------------------------------------------- */
+
+static Hash *subclass = 0;
+static Hash *conversions = 0;
+
+void SwigType_inherit(String *derived, String *base, String *cast, String *conversioncode) {
+  Hash *h;
+  String *dd = 0;
+  String *bb = 0;
+  if (!subclass)
+    subclass = NewHash();
+
+  /* Printf(stdout,"'%s' --> '%s'  '%s'\n", derived, base, cast); */
+
+  if (SwigType_istemplate(derived)) {
+    String *ty = SwigType_typedef_resolve_all(derived);
+    dd = SwigType_typedef_qualified(ty);
+    derived = dd;
+    Delete(ty);
+  }
+  if (SwigType_istemplate(base)) {
+    String *ty = SwigType_typedef_resolve_all(base);
+    bb = SwigType_typedef_qualified(ty);
+    base = bb;
+    Delete(ty);
+  }
+
+  /* Printf(stdout,"'%s' --> '%s'  '%s'\n", derived, base, cast); */
+
+  h = Getattr(subclass, base);
+  if (!h) {
+    h = NewHash();
+    Setattr(subclass, base, h);
+    Delete(h);
+  }
+  if (!Getattr(h, derived)) {
+    Hash *c = NewHash();
+    if (cast)
+      Setattr(c, "cast", cast);
+    if (conversioncode)
+      Setattr(c, "convcode", conversioncode);
+    Setattr(h, derived, c);
+    Delete(c);
+  }
+
+  Delete(dd);
+  Delete(bb);
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_issubtype()
+ *
+ * Determines if a t1 is a subtype of t2, ie, is t1 derived from t2
+ * ----------------------------------------------------------------------------- */
+
+int SwigType_issubtype(SwigType *t1, SwigType *t2) {
+  SwigType *ft1, *ft2;
+  String *b1, *b2;
+  Hash *h;
+  int r = 0;
+
+  if (!subclass)
+    return 0;
+
+  ft1 = SwigType_typedef_resolve_all(t1);
+  ft2 = SwigType_typedef_resolve_all(t2);
+  b1 = SwigType_base(ft1);
+  b2 = SwigType_base(ft2);
+
+  h = Getattr(subclass, b2);
+  if (h) {
+    if (Getattr(h, b1)) {
+      r = 1;
+    }
+  }
+  Delete(ft1);
+  Delete(ft2);
+  Delete(b1);
+  Delete(b2);
+  /* Printf(stdout, "issubtype(%s,%s) --> %d\n", t1, t2, r); */
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_inherit_equiv()
+ *
+ * Modify the type table to handle C++ inheritance
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_inherit_equiv(File *out) {
+  String *ckey;
+  String *prefix, *base;
+  String *mprefix, *mkey;
+  Hash *sub;
+  Hash *rh;
+  List *rlist;
+  Iterator rk, bk, ck;
+
+  if (!conversions)
+    conversions = NewHash();
+  if (!subclass)
+    subclass = NewHash();
+
+  rk = First(r_resolved);
+  while (rk.key) {
+    /* rkey is a fully qualified type.  We strip all of the type constructors off of it just to get the base */
+    base = SwigType_base(rk.key);
+    /* Check to see whether the base is recorded in the subclass table */
+    sub = Getattr(subclass, base);
+    Delete(base);
+    if (!sub) {
+      rk = Next(rk);
+      continue;
+    }
+
+    /* This type has subclasses.  We now need to walk through these subtypes and generate pointer converion functions */
+
+    rh = Getattr(r_resolved, rk.key);
+    rlist = NewList();
+    for (ck = First(rh); ck.key; ck = Next(ck)) {
+      Append(rlist, ck.key);
+    }
+    /*    Printf(stdout,"rk.key = '%s'\n", rk.key);
+       Printf(stdout,"rh = %x '%s'\n", rh,rh); */
+
+    bk = First(sub);
+    while (bk.key) {
+      prefix = SwigType_prefix(rk.key);
+      Append(prefix, bk.key);
+      /*      Printf(stdout,"set %x = '%s' : '%s'\n", rh, SwigType_manglestr(prefix),prefix); */
+      mprefix = SwigType_manglestr(prefix);
+      Setattr(rh, mprefix, prefix);
+      mkey = SwigType_manglestr(rk.key);
+      ckey = NewStringf("%s+%s", mprefix, mkey);
+      if (!Getattr(conversions, ckey)) {
+	String *convname = NewStringf("%sTo%s", mprefix, mkey);
+	String *lkey = SwigType_lstr(rk.key, 0);
+	String *lprefix = SwigType_lstr(prefix, 0);
+        Hash *subhash = Getattr(sub, bk.key);
+        String *convcode = Getattr(subhash, "convcode");
+        if (convcode) {
+          char *newmemoryused = Strstr(convcode, "newmemory"); /* see if newmemory parameter is used in order to avoid unused parameter warnings */
+          String *fn = Copy(convcode);
+          Replaceall(fn, "$from", "x");
+          Printf(out, "static void *%s(void *x, int *%s) {", convname, newmemoryused ? "newmemory" : "SWIGUNUSEDPARM(newmemory)");
+          Printf(out, "%s", fn);
+        } else {
+          String *cast = Getattr(subhash, "cast");
+          Printf(out, "static void *%s(void *x, int *SWIGUNUSEDPARM(newmemory)) {", convname);
+          Printf(out, "\n    return (void *)((%s) ", lkey);
+          if (cast)
+            Printf(out, "%s", cast);
+          Printf(out, " ((%s) x));\n", lprefix);
+        }
+	Printf(out, "}\n");
+	Setattr(conversions, ckey, convname);
+	Delete(ckey);
+	Delete(lkey);
+	Delete(lprefix);
+
+	/* This inserts conversions for typedefs */
+	{
+	  Hash *r = Getattr(r_resolved, prefix);
+	  if (r) {
+	    Iterator rrk;
+	    rrk = First(r);
+	    while (rrk.key) {
+	      Iterator rlk;
+	      String *rkeymangle;
+
+	      /* Make sure this name equivalence is not due to inheritance */
+	      if (Cmp(prefix, Getattr(r, rrk.key)) == 0) {
+		rkeymangle = Copy(mkey);
+		ckey = NewStringf("%s+%s", rrk.key, rkeymangle);
+		if (!Getattr(conversions, ckey)) {
+		  Setattr(conversions, ckey, convname);
+		}
+		Delete(ckey);
+		for (rlk = First(rlist); rlk.item; rlk = Next(rlk)) {
+		  ckey = NewStringf("%s+%s", rrk.key, rlk.item);
+		  Setattr(conversions, ckey, convname);
+		  Delete(ckey);
+		}
+		Delete(rkeymangle);
+		/* This is needed to pick up other alternative names for the same type.
+		   Needed to make templates work */
+		Setattr(rh, rrk.key, rrk.item);
+	      }
+	      rrk = Next(rrk);
+	    }
+	  }
+	}
+	Delete(convname);
+      }
+      Delete(prefix);
+      Delete(mprefix);
+      Delete(mkey);
+      bk = Next(bk);
+    }
+    rk = Next(rk);
+    Delete(rlist);
+  }
+}
+
+/* Helper function to sort the mangled list */
+static int SwigType_compare_mangled(const DOH *a, const DOH *b) {
+  return strcmp((char *) Data(a), (char *) Data(b));
+}
+
+/* -----------------------------------------------------------------------------
+ * SwigType_get_sorted_mangled_list()
+ *
+ * Returns the sorted list of mangled type names that should be exported into the
+ * wrapper file.
+ * ----------------------------------------------------------------------------- */
+List *SwigType_get_sorted_mangled_list() {
+  List *l = Keys(r_mangled);
+  SortList(l, SwigType_compare_mangled);
+  return l;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * SwigType_type_table()
+ *
+ * Generate the type-table for the type-checker.
+ * ----------------------------------------------------------------------------- */
+
+void SwigType_emit_type_table(File *f_forward, File *f_table) {
+  Iterator ki;
+  String *types, *table, *cast, *cast_init, *cast_temp;
+  Hash *imported_types;
+  List *mangled_list;
+  List *table_list = NewList();
+  int i = 0;
+
+  if (!r_mangled) {
+    r_mangled = NewHash();
+    r_resolved = NewHash();
+  }
+
+  Printf(f_table, "\n/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */\n\n");
+
+  SwigType_inherit_equiv(f_table);
+
+   /*#define DEBUG 1*/
+#ifdef DEBUG
+  Printf(stdout, "---r_mangled---\n");
+  Printf(stdout, "%s\n", r_mangled);
+
+  Printf(stdout, "---r_resolved---\n");
+  Printf(stdout, "%s\n", r_resolved);
+
+  Printf(stdout, "---r_ltype---\n");
+  Printf(stdout, "%s\n", r_ltype);
+
+  Printf(stdout, "---subclass---\n");
+  Printf(stdout, "%s\n", subclass);
+
+  Printf(stdout, "---conversions---\n");
+  Printf(stdout, "%s\n", conversions);
+
+  Printf(stdout, "---r_clientdata---\n");
+  Printf(stdout, "%s\n", r_clientdata);
+
+#endif
+  table = NewStringEmpty();
+  types = NewStringEmpty();
+  cast = NewStringEmpty();
+  cast_init = NewStringEmpty();
+  imported_types = NewHash();
+
+  Printf(table, "static swig_type_info *swig_type_initial[] = {\n");
+  Printf(cast_init, "static swig_cast_info *swig_cast_initial[] = {\n");
+
+  Printf(f_forward, "\n/* -------- TYPES TABLE (BEGIN) -------- */\n\n");
+
+  mangled_list = SwigType_get_sorted_mangled_list();
+  for (ki = First(mangled_list); ki.item; ki = Next(ki)) {
+    List *el;
+    Iterator ei;
+    SwigType *lt;
+    SwigType *rt = 0;
+    String *nt;
+    String *ln;
+    String *rn;
+    const String *cd;
+    Hash *lthash;
+    Iterator ltiter;
+    Hash *nthash;
+
+    cast_temp = NewStringEmpty();
+
+    Printv(types, "static swig_type_info _swigt_", ki.item, " = {", NIL);
+    Append(table_list, ki.item);
+    Printf(cast_temp, "static swig_cast_info _swigc_%s[] = {", ki.item);
+    i++;
+
+    cd = SwigType_clientdata_collect(ki.item);
+    if (!cd)
+      cd = "0";
+
+    lthash = Getattr(r_ltype, ki.item);
+    nt = 0;
+    nthash = NewHash();
+    ltiter = First(lthash);
+    while (ltiter.key) {
+      lt = ltiter.key;
+      rt = SwigType_typedef_resolve_all(lt);
+      /* we save the original type and the fully resolved version */
+      ln = SwigType_lstr(lt, 0);
+      rn = SwigType_lstr(rt, 0);
+      if (Equal(ln, rn)) {
+        Setattr(nthash, ln, "1");
+      } else {
+	Setattr(nthash, rn, "1");
+	Setattr(nthash, ln, "1");
+      }
+      if (SwigType_istemplate(rt)) {
+        String *dt = Swig_symbol_template_deftype(rt, 0);
+        String *dn = SwigType_lstr(dt, 0);
+        if (!Equal(dn, rn) && !Equal(dn, ln)) {
+          Setattr(nthash, dn, "1");
+        }
+        Delete(dt);
+        Delete(dn);
+      }
+
+      ltiter = Next(ltiter);
+    }
+
+    /* now build nt */
+    ltiter = First(nthash);
+    nt = 0;
+    while (ltiter.key) {
+      if (nt) {
+	 Printf(nt, "|%s", ltiter.key);
+      } else {
+	 nt = NewString(ltiter.key);
+      }
+      ltiter = Next(ltiter);
+    }
+    Delete(nthash);
+
+    Printf(types, "\"%s\", \"%s\", 0, 0, (void*)%s, 0};\n", ki.item, nt, cd);
+
+    el = SwigType_equivalent_mangle(ki.item, 0, 0);
+    for (ei = First(el); ei.item; ei = Next(ei)) {
+      String *ckey;
+      String *conv;
+      ckey = NewStringf("%s+%s", ei.item, ki.item);
+      conv = Getattr(conversions, ckey);
+      if (conv) {
+	Printf(cast_temp, "  {&_swigt_%s, %s, 0, 0},", ei.item, conv);
+      } else {
+	Printf(cast_temp, "  {&_swigt_%s, 0, 0, 0},", ei.item);
+      }
+      Delete(ckey);
+
+      if (!Getattr(r_mangled, ei.item) && !Getattr(imported_types, ei.item)) {
+	Printf(types, "static swig_type_info _swigt_%s = {\"%s\", 0, 0, 0, 0, 0};\n", ei.item, ei.item);
+	Append(table_list, ei.item);
+
+	Printf(cast, "static swig_cast_info _swigc_%s[] = {{&_swigt_%s, 0, 0, 0},{0, 0, 0, 0}};\n", ei.item, ei.item);
+	i++;
+
+	Setattr(imported_types, ei.item, "1");
+      }
+    }
+    Delete(el);
+    Printf(cast, "%s{0, 0, 0, 0}};\n", cast_temp);
+    Delete(cast_temp);
+    Delete(nt);
+    Delete(rt);
+  }
+  /* print the tables in the proper order */
+  SortList(table_list, SwigType_compare_mangled);
+  i = 0;
+  for (ki = First(table_list); ki.item; ki = Next(ki)) {
+    Printf(f_forward, "#define SWIGTYPE%s swig_types[%d]\n", ki.item, i++);
+    Printf(table, "  &_swigt_%s,\n", ki.item);
+    Printf(cast_init, "  _swigc_%s,\n", ki.item);
+  }
+  if (i == 0) {
+    /* empty arrays are not allowed by ISO C */
+    Printf(table, "  NULL\n");
+    Printf(cast_init, "  NULL\n");
+  }
+
+  Delete(table_list);
+
+  Delete(mangled_list);
+
+  Printf(table, "};\n");
+  Printf(cast_init, "};\n");
+  Printf(f_table, "%s\n", types);
+  Printf(f_table, "%s\n", table);
+  Printf(f_table, "%s\n", cast);
+  Printf(f_table, "%s\n", cast_init);
+  Printf(f_table, "\n/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */\n\n");
+
+  Printf(f_forward, "static swig_type_info *swig_types[%d];\n", i + 1);
+  Printf(f_forward, "static swig_module_info swig_module = {swig_types, %d, 0, 0, 0, 0};\n", i);
+  Printf(f_forward, "#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)\n");
+  Printf(f_forward, "#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)\n");
+  Printf(f_forward, "\n/* -------- TYPES TABLE (END) -------- */\n\n");
+
+  Delete(types);
+  Delete(table);
+  Delete(cast);
+  Delete(cast_init);
+  Delete(imported_types);
+}
diff --git a/trunk/Source/Swig/warn.c b/trunk/Source/Swig/warn.c
new file mode 100644
index 0000000..a8dadc7
--- /dev/null
+++ b/trunk/Source/Swig/warn.c
@@ -0,0 +1,34 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * warn.c
+ *
+ * SWIG warning framework.  This was added to warn developers about 
+ * deprecated APIs and other features.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_warn_c[] = "$Id$";
+
+#include "swig.h"
+
+static Hash *warnings = 0;
+
+/* -----------------------------------------------------------------------------
+ * Swig_warn()
+ * 
+ * Issue a warning
+ * ----------------------------------------------------------------------------- */
+
+void Swig_warn(const char *filename, int line, const char *msg) {
+  String *key;
+  if (!warnings) {
+    warnings = NewHash();
+  }
+  key = NewStringf("%s:%d", filename, line);
+  if (!Getattr(warnings, key)) {
+    Printf(stderr, "swig-dev warning:%s:%d:%s\n", filename, line, msg);
+    Setattr(warnings, key, key);
+  }
+  Delete(key);
+}
diff --git a/trunk/Source/Swig/wrapfunc.c b/trunk/Source/Swig/wrapfunc.c
new file mode 100644
index 0000000..3778066
--- /dev/null
+++ b/trunk/Source/Swig/wrapfunc.c
@@ -0,0 +1,518 @@
+/* ----------------------------------------------------------------------------- 
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * wrapfunc.c
+ *
+ * This file defines a object for creating wrapper functions.  Primarily
+ * this is used for convenience since it allows pieces of a wrapper function
+ * to be created in a piecemeal manner.
+ * ----------------------------------------------------------------------------- */
+
+char cvsroot_wrapfunc_c[] = "$Id$";
+
+#include "swig.h"
+#include <ctype.h>
+
+static int Compact_mode = 0;	/* set to 0 on default */
+static int Max_line_size = 128;
+
+/* -----------------------------------------------------------------------------
+ * NewWrapper()
+ *
+ * Create a new wrapper function object.
+ * ----------------------------------------------------------------------------- */
+
+Wrapper *NewWrapper() {
+  Wrapper *w;
+  w = (Wrapper *) malloc(sizeof(Wrapper));
+  w->localh = NewHash();
+  w->locals = NewStringEmpty();
+  w->code = NewStringEmpty();
+  w->def = NewStringEmpty();
+  return w;
+}
+
+/* -----------------------------------------------------------------------------
+ * DelWrapper()
+ *
+ * Delete a wrapper function object.
+ * ----------------------------------------------------------------------------- */
+
+void DelWrapper(Wrapper *w) {
+  Delete(w->localh);
+  Delete(w->locals);
+  Delete(w->code);
+  Delete(w->def);
+  free(w);
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_compact_print_mode_set()
+ *
+ * Set compact_mode.
+ * ----------------------------------------------------------------------------- */
+
+void Wrapper_compact_print_mode_set(int flag) {
+  Compact_mode = flag;
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_pretty_print()
+ *
+ * Formats a wrapper function and fixes up the indentation.
+ * ----------------------------------------------------------------------------- */
+
+void Wrapper_pretty_print(String *str, File *f) {
+  String *ts;
+  int level = 0;
+  int c, i;
+  int empty = 1;
+  int indent = 2;
+  int plevel = 0;
+  int label = 0;
+
+  ts = NewStringEmpty();
+  Seek(str, 0, SEEK_SET);
+  while ((c = Getc(str)) != EOF) {
+    if (c == '\"') {
+      Putc(c, ts);
+      while ((c = Getc(str)) != EOF) {
+	if (c == '\\') {
+	  Putc(c, ts);
+	  c = Getc(str);
+	}
+	Putc(c, ts);
+	if (c == '\"')
+	  break;
+      }
+      empty = 0;
+    } else if (c == '\'') {
+      Putc(c, ts);
+      while ((c = Getc(str)) != EOF) {
+	if (c == '\\') {
+	  Putc(c, ts);
+	  c = Getc(str);
+	}
+	Putc(c, ts);
+	if (c == '\'')
+	  break;
+      }
+      empty = 0;
+    } else if (c == ':') {
+      Putc(c, ts);
+      if ((c = Getc(str)) == '\n') {
+	if (!empty && !strchr(Char(ts), '?'))
+	  label = 1;
+      }
+      Ungetc(c, str);
+    } else if (c == '(') {
+      Putc(c, ts);
+      plevel += indent;
+      empty = 0;
+    } else if (c == ')') {
+      Putc(c, ts);
+      plevel -= indent;
+      empty = 0;
+    } else if (c == '{') {
+      Putc(c, ts);
+      Putc('\n', ts);
+      for (i = 0; i < level; i++)
+	Putc(' ', f);
+      Printf(f, "%s", ts);
+      Clear(ts);
+      level += indent;
+      while ((c = Getc(str)) != EOF) {
+	if (!isspace(c)) {
+	  Ungetc(c, str);
+	  break;
+	}
+      }
+      empty = 0;
+    } else if (c == '}') {
+      if (!empty) {
+	Putc('\n', ts);
+	for (i = 0; i < level; i++)
+	  Putc(' ', f);
+	Printf(f, "%s", ts);
+	Clear(ts);
+      }
+      level -= indent;
+      Putc(c, ts);
+      empty = 0;
+    } else if (c == '\n') {
+      Putc(c, ts);
+      empty = 0;
+      if (!empty) {
+	int slevel = level;
+	if (label && (slevel >= indent))
+	  slevel -= indent;
+	if ((Char(ts))[0] != '#') {
+	  for (i = 0; i < slevel; i++)
+	    Putc(' ', f);
+	}
+	Printf(f, "%s", ts);
+	for (i = 0; i < plevel; i++)
+	  Putc(' ', f);
+      }
+      Clear(ts);
+      label = 0;
+      empty = 1;
+    } else if (c == '/') {
+      empty = 0;
+      Putc(c, ts);
+      c = Getc(str);
+      if (c != EOF) {
+	Putc(c, ts);
+	if (c == '/') {		/* C++ comment */
+	  while ((c = Getc(str)) != EOF) {
+	    if (c == '\n') {
+	      Ungetc(c, str);
+	      break;
+	    }
+	    Putc(c, ts);
+	  }
+	} else if (c == '*') {	/* C comment */
+	  int endstar = 0;
+	  while ((c = Getc(str)) != EOF) {
+	    if (endstar && c == '/') {	/* end of C comment */
+	      Putc(c, ts);
+	      break;
+	    }
+	    endstar = (c == '*');
+	    Putc(c, ts);
+	    if (c == '\n') {	/* multi-line C comment. Could be improved slightly. */
+	      for (i = 0; i < level; i++)
+		Putc(' ', ts);
+	    }
+	  }
+	}
+      }
+    } else {
+      if (!empty || !isspace(c)) {
+	Putc(c, ts);
+	empty = 0;
+      }
+    }
+  }
+  if (!empty)
+    Printf(f, "%s", ts);
+  Delete(ts);
+  Printf(f, "\n");
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_compact_print()
+ *
+ * Formats a wrapper function and fixes up the indentation.
+ * Print out in compact format, with Compact enabled.
+ * ----------------------------------------------------------------------------- */
+
+void Wrapper_compact_print(String *str, File *f) {
+  String *ts, *tf;		/*temp string & temp file */
+  int level = 0;
+  int c, i;
+  int empty = 1;
+  int indent = 2;
+
+  ts = NewStringEmpty();
+  tf = NewStringEmpty();
+  Seek(str, 0, SEEK_SET);
+
+  while ((c = Getc(str)) != EOF) {
+    if (c == '\"') {		/* string 1 */
+      empty = 0;
+      Putc(c, ts);
+      while ((c = Getc(str)) != EOF) {
+	if (c == '\\') {
+	  Putc(c, ts);
+	  c = Getc(str);
+	}
+	Putc(c, ts);
+	if (c == '\"')
+	  break;
+      }
+    } else if (c == '\'') {	/* string 2 */
+      empty = 0;
+      Putc(c, ts);
+      while ((c = Getc(str)) != EOF) {
+	if (c == '\\') {
+	  Putc(c, ts);
+	  c = Getc(str);
+	}
+	Putc(c, ts);
+	if (c == '\'')
+	  break;
+      }
+    } else if (c == '{') {	/* start of {...} */
+      empty = 0;
+      Putc(c, ts);
+      if (Len(tf) == 0) {
+	for (i = 0; i < level; i++)
+	  Putc(' ', tf);
+      } else if ((Len(tf) + Len(ts)) < Max_line_size) {
+	Putc(' ', tf);
+      } else {
+	Putc('\n', tf);
+	Printf(f, "%s", tf);
+	Clear(tf);
+	for (i = 0; i < level; i++)
+	  Putc(' ', tf);
+      }
+      Append(tf, ts);
+      Clear(ts);
+      level += indent;
+      while ((c = Getc(str)) != EOF) {
+	if (!isspace(c)) {
+	  Ungetc(c, str);
+	  break;
+	}
+      }
+    } else if (c == '}') {	/* end of {...} */
+      empty = 0;
+      if (Len(tf) == 0) {
+	for (i = 0; i < level; i++)
+	  Putc(' ', tf);
+      } else if ((Len(tf) + Len(ts)) < Max_line_size) {
+	Putc(' ', tf);
+      } else {
+	Putc('\n', tf);
+	Printf(f, "%s", tf);
+	Clear(tf);
+	for (i = 0; i < level; i++)
+	  Putc(' ', tf);
+      }
+      Append(tf, ts);
+      Putc(c, tf);
+      Clear(ts);
+      level -= indent;
+    } else if (c == '\n') {	/* line end */
+      while ((c = Getc(str)) != EOF) {
+	if (!isspace(c))
+	  break;
+      }
+      if (c == '#') {
+	Putc('\n', ts);
+      } else if (c == '}') {
+	Putc(' ', ts);
+      } else if ((c != EOF) || (Len(ts) != 0)) {
+	if (Len(tf) == 0) {
+	  for (i = 0; i < level; i++)
+	    Putc(' ', tf);
+	} else if ((Len(tf) + Len(ts)) < Max_line_size) {
+	  Putc(' ', tf);
+	} else {
+	  Putc('\n', tf);
+	  Printf(f, "%s", tf);
+	  Clear(tf);
+	  for (i = 0; i < level; i++)
+	    Putc(' ', tf);
+	}
+	Append(tf, ts);
+	Clear(ts);
+      }
+      Ungetc(c, str);
+
+      empty = 1;
+    } else if (c == '/') {	/* comment */
+      empty = 0;
+      c = Getc(str);
+      if (c != EOF) {
+	if (c == '/') {		/* C++ comment */
+	  while ((c = Getc(str)) != EOF) {
+	    if (c == '\n') {
+	      Ungetc(c, str);
+	      break;
+	    }
+	  }
+	} else if (c == '*') {	/* C comment */
+	  int endstar = 0;
+	  while ((c = Getc(str)) != EOF) {
+	    if (endstar && c == '/') {	/* end of C comment */
+	      break;
+	    }
+	    endstar = (c == '*');
+	  }
+	} else {
+	  Putc('/', ts);
+	  Putc(c, ts);
+	}
+      }
+    } else if (c == '#') {	/* Preprocessor line */
+      Putc('#', ts);
+      while ((c = Getc(str)) != EOF) {
+	Putc(c, ts);
+	if (c == '\\') {	/* Continued line of the same PP */
+	  c = Getc(str);
+	  if (c == '\n')
+	    Putc(c, ts);
+	  else
+	    Ungetc(c, str);
+	} else if (c == '\n')
+	  break;
+      }
+      if (!empty) {
+	Append(tf, "\n");
+      }
+      Append(tf, ts);
+      Printf(f, "%s", tf);
+      Clear(tf);
+      Clear(ts);
+      for (i = 0; i < level; i++)
+	Putc(' ', tf);
+      empty = 1;
+    } else {
+      if (!empty || !isspace(c)) {
+	Putc(c, ts);
+	empty = 0;
+      }
+    }
+  }
+  if (!empty) {
+    Append(tf, ts);
+  }
+  if (Len(tf) != 0)
+    Printf(f, "%s", tf);
+  Delete(ts);
+  Delete(tf);
+  Printf(f, "\n");
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_print()
+ *
+ * Print out a wrapper function.  Does pretty or compact printing as well.
+ * ----------------------------------------------------------------------------- */
+
+void Wrapper_print(Wrapper *w, File *f) {
+  String *str;
+
+  str = NewStringEmpty();
+  Printf(str, "%s\n", w->def);
+  Printf(str, "%s\n", w->locals);
+  Printf(str, "%s\n", w->code);
+  if (Compact_mode == 1)
+    Wrapper_compact_print(str, f);
+  else
+    Wrapper_pretty_print(str, f);
+
+  Delete(str);
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_add_local()
+ *
+ * Adds a new local variable declaration to a function. Returns -1 if already
+ * present (which may or may not be okay to the caller).
+ * ----------------------------------------------------------------------------- */
+
+int Wrapper_add_local(Wrapper *w, const String_or_char *name, const String_or_char *decl) {
+  /* See if the local has already been declared */
+  if (Getattr(w->localh, name)) {
+    return -1;
+  }
+  Setattr(w->localh, name, decl);
+  Printf(w->locals, "%s;\n", decl);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_add_localv()
+ *
+ * Same as add_local(), but allows a NULL terminated list of strings to be
+ * used as a replacement for decl.   This saves the caller the trouble of having
+ * to manually construct the 'decl' string before calling.
+ * ----------------------------------------------------------------------------- */
+
+int Wrapper_add_localv(Wrapper *w, const String_or_char *name, ...) {
+  va_list ap;
+  int ret;
+  String *decl;
+  DOH *obj;
+  decl = NewStringEmpty();
+  va_start(ap, name);
+
+  obj = va_arg(ap, void *);
+  while (obj) {
+    Append(decl, obj);
+    Putc(' ', decl);
+    obj = va_arg(ap, void *);
+  }
+  va_end(ap);
+
+  ret = Wrapper_add_local(w, name, decl);
+  Delete(decl);
+  return ret;
+}
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_check_local()
+ *
+ * Check to see if a local name has already been declared
+ * ----------------------------------------------------------------------------- */
+
+int Wrapper_check_local(Wrapper *w, const String_or_char *name) {
+  if (Getattr(w->localh, name)) {
+    return 1;
+  }
+  return 0;
+}
+
+/* ----------------------------------------------------------------------------- 
+ * Wrapper_new_local()
+ *
+ * Adds a new local variable with a guarantee that a unique local name will be
+ * used.  Returns the name that was actually selected.
+ * ----------------------------------------------------------------------------- */
+
+char *Wrapper_new_local(Wrapper *w, const String_or_char *name, const String_or_char *decl) {
+  int i;
+  String *nname = NewString(name);
+  String *ndecl = NewString(decl);
+  char *ret;
+
+  i = 0;
+
+  while (Wrapper_check_local(w, nname)) {
+    Clear(nname);
+    Printf(nname, "%s%d", name, i);
+    i++;
+  }
+  Replace(ndecl, name, nname, DOH_REPLACE_ID);
+  Setattr(w->localh, nname, ndecl);
+  Printf(w->locals, "%s;\n", ndecl);
+  ret = Char(nname);
+  Delete(nname);
+  Delete(ndecl);
+  return ret;			/* Note: nname should still exists in the w->localh hash */
+}
+
+
+/* -----------------------------------------------------------------------------
+ * Wrapper_new_localv()
+ *
+ * Same as add_local(), but allows a NULL terminated list of strings to be
+ * used as a replacement for decl.   This saves the caller the trouble of having
+ * to manually construct the 'decl' string before calling.
+ * ----------------------------------------------------------------------------- */
+
+char *Wrapper_new_localv(Wrapper *w, const String_or_char *name, ...) {
+  va_list ap;
+  char *ret;
+  String *decl;
+  DOH *obj;
+  decl = NewStringEmpty();
+  va_start(ap, name);
+
+  obj = va_arg(ap, void *);
+  while (obj) {
+    Append(decl, obj);
+    Putc(' ', decl);
+    obj = va_arg(ap, void *);
+  }
+  va_end(ap);
+
+  ret = Wrapper_new_local(w, name, decl);
+  Delete(decl);
+  return ret;
+}
diff --git a/trunk/TODO b/trunk/TODO
new file mode 100644
index 0000000..103185d
--- /dev/null
+++ b/trunk/TODO
@@ -0,0 +1,372 @@
+SWIG TO-DO
+
+Release: SWIG-1.3.36
+
+-----------------------------------------------------------------------------
+
+****    = High Priority
+***     = Implement if possible.
+**      = Will implement if time.
+*       = Implement if bored (or deemed necessary).
+
+defer   = Implement in next version
+
+CORE:
+
+****   Add support for nested classes.   The type system should be
+defer  ready to go.  The primary obstacle lies in the target language
+       modules (which were never programmed with nested classes in
+       mind).  There are also issues with nested C structures.  For
+       example:
+
+             struct Foo {
+                 struct {
+                     int x,y;
+                 } z;
+             };
+
+       This is one of the last remaining "hard" problems in the SWIG
+       core, but it is important that we solve it.
+
+***    "Nested" typemaps. The basic idea is similar to allowing one to 
+       use $descriptor(T) for any T, rather than just $descriptor
+       for the type currently being typemapped.
+
+       In short (ha!), given a previously defined typemap:
+
+       %typemap(in) Foo {
+           // whatever it takes to initialize $1 from $input
+       }
+
+       it would be possible to inline its code inside another typemap. 
+       While the syntax is still to be defined, the use would be
+       along the lines of:
+
+       template <class T> class vector {
+           %typemap(in) vector<T> {
+               ...
+               for (int i=0; i<N; i++) {
+                   PyObject* x = ... // i-th element
+                   $typemap(in, T, x, $1[i]);
+               }
+               ...
+           }
+           ...
+       }
+
+       i.e., when $typemap(in,Foo,x,y) is encountered, it will
+       be replaced by the code for %typemap(in) Foo; in the latter,
+       x will be replaced for $input and y will be replaced for $1. 
+       As in the case above, x and y themselves might need to be 
+       expanded before or after being substituted in the typemap code.
+       Also, $typemap(what,Foo,x,y,z,...) will be used in case of 
+       multi-arguments typemaps. The same will hold for "out" typemaps
+       and all the others.
+
+       Comment by mkoeppe:  
+
+	  I think we need to be careful to keep the syntax readable.
+	  I would like to get a syntax that is close to that of
+	  typemap definitions.  So consider this typemap:
+
+		 %typemap(in) int { ... }
+
+	  I would like to refer to this typemap like this:
+
+		 $typemap(in, input=x) int = foo;
+
+	  Here $input would be replaced by the given keyword argument
+	  x, and $1 would be replaced by foo.
+
+	  This syntax would extend easily to multi-typemaps:
+
+		 %typemap(in) ( int FIRST, double SECOND ) { ... }
+
+	      -> $typemap(in, input=x) 
+	      	    ( int FIRST = foo, double SECOND = bar );
+
+	  The advantage of this syntax would be that the formal
+	  arguments (int FIRST, double SECOND) are close to the
+	  actual arguments (foo, bar).
+
+	Comment by beazley
+
+               $typemap(in, input=x) int = foo;
+
+        is a little bit hard to parse in terms of variable substitution.
+        I'm considering something like this:
+
+               $typemap(in,1=int foo, input=x)
+
+       Note: This is partially implemented in the new Unified Typemap
+       Library(python,tcl,ruby and perl) via %fragments and the
+       SWIG_From/SWIG_AsVal methdos.
+
+***    Implement $fail special variable substitution in wrappers. Used
+       to properly transfer control out of a wrapper function while
+       reclaiming resources.
+
+       Note: Implemented in languages that uses the UTL via the
+       'SWIG_fail' macro.
+
+***    Rewrite declaration annotation to better unify %rename and related
+       directives.  Add a selector mechanism that allows specific parse tree
+       nodes to be identified.  For example:
+
+             %feature("foo", nodetype="class") Foo { ... some code ... };
+
+       Consider use of wildcards.   Namespace/nested scope support in
+       %feature is currently weak.  It works, but is fragile.  Consider
+       an implementation that is better integrated with symbol table
+       management.  Continue to consolidate SWIG directives to %feature.
+
+       Note: Initial implementation in the %rename directive.
+
+***    Add more intelligent information related to object ownership.
+       SWIG should be able to automatically strip ownership from
+       objects when they are assigned to pointer variables and structure
+       members as well as stored in a container (i.e., an array of pointers).
+
+       [ Partially finished for Ruby/Perl/Tcl/Python. ]
+
+**     Restoration of the documentation system.
+       [ Partially done for Python. ]
+              
+
+**     Restoration of Objective-C support.
+
+**     Unification of symbol tables and type system scopes.  In a sense
+       they capture the same information so it is not necessary to have
+       both.  The existence of two symbol management systems is mostly
+       historical.
+
+Build
+-----
+
+Library
+-------
+
+****   Add more support for the C++ standard library.  std::complex and other
+       core datatypes.   Refine support for STL vector.   Add more STL objects.
+
+       [ Partially finished for Python. ]
+
+****   Continue to expand the set of recognized typemaps.
+
+Windows
+-------
+
+All language modules
+--------------------
+
+Python
+------
+
+***    Ability to wrap certain classes as Python built-in types.
+
+Perl
+----
+
+****   Rewrite runtime pointer type checking to better integrate
+       shadow classes.   Creation of shadow classes should be done
+       in C instead of Perl.   This will fix a number of problems
+       related to typemaps and reduce the amount of Perl wrapper code.
+
+****   Create tests for existing support for operator overloading
+
+Tcl
+---
+
+Ruby
+----
+
+****   The "Resource Management in Proxies" section of the "SWIG and C++"
+       chapter discusses how proxies' ownership of their associated C++
+       object can change, and the use of the special disown() and
+       acquire() methods to change this ownership status. Need to
+       address this for Ruby as well.
+
+***    Add support for keyword arguments (by collecting them in a hash?).
+
+Java
+----
+
+
+C#
+--
+
+PHP
+---
+
+****   Look at moving to using the UTL.
+
+***    Director support.
+
+**     When returning wrapped objects via alternate constructors if that
+       pointer value already exists "out there" as a resource we should
+       use the same resource, we can't have multiple ref-counted resources
+       mapping to the same object in case it gets twice destroyed.  And check
+       if ref count destroying is even working, see smart_pointer_rename
+
+*      Work out how classes without even inherited constructors should
+       interact with the php "new <class>" notation.
+       See: abstract_inherit_wrap.cpptest
+
+**     Look at pass by point and passby ref,
+       Make sometype** to be auto allocated
+       Make sometype& and sometype* to be autoallocated IF THEY ARE NOT
+       ALREADY swigtype wrapped.
+
+*      Review to see what else is missing!
+
+Guile
+-----
+
+**     Maybe rename slot setters from CLASS-SLOT-set to CLASS-SLOT-set!
+       to match Scheme convention for naming of mutators.
+
+**     Support keyword args.
+
+**     Director Support!
+
+**     Cleaner handling of multiple values.
+       Use a typemap keyword argument "numoutputs" of "out" and
+       "argout" to indicate how many values are returned.
+
+**     Make SWIG's types first-class by using a separate smob type for
+       SWIG type descriptors; enable reflection on types.  (Maybe
+       GOOPS metaclasses?)
+
+**     Provide a clean way to construct type predicates.
+
+**     In GOOPS mode, maybe make overloaded functions methods. 
+
+**     Increase the safety of destructor functions.  John Lenz suggests:
+
+	  I think the best way of doing this would be to use %feature to mark  
+	  which classes allow for "normal" <swig> smobs to be deleted explicitly.
+
+	  We separate pointers into two classes, those that can be deleted from  
+	  scheme and those that can't.  The pointers that can be deleted use the
+	  <collectable-swig> smob and those that can not be deleted use the  
+	  <swig> smob.  A user can specify which type of each object they want  
+	  with %newobject and the CONSUMED typemap.
+
+	  By default, the exported destructor will only accept <collectable-swig>  
+	  smobs, because by definition, collectable-swig smobs are those that can  
+	  be deleted from scheme.  This allows for the user to implement  
+	  protection.  In the interface file, the user has complete control over  
+	  which objects can and can not be deleted, and can guarantee that  
+	  objects that should not be deleted can not be deleted, and that objects  
+	  that should eventually be deleted will be garbage collected.
+
+	  This protection can then be overridden with a %feature directive,  
+	  something like
+
+	  %feature("guile_allow_destroy_all","1") Foo::~Foo;
+
+	  I don't know what word we want to use, guile_allow_destroy_all is kinda  
+	  bad.  This feature would then allow for a <swig Foo *> smob to be  
+	  deleted by passing it to the destructor.  This would allow users to  
+	  maintain the protection on other classes, only manually overriding the  
+	  protection on the classes that need it.
+
+
+Mzscheme
+--------
+
+**     Port list-vector.i and pointer-in-out.i from Guile.
+
+**     Add shadow class support for the Swindle system. 
+
+Pike
+----
+
+*      Decide how to handle global variables (probably using something
+       like the Python module's cvar). Affects Examples/pike/simple.
+
+*      Decide how to handle static class member functions and member
+       variables.
+
+*      Should investigate the possibility of generating .cmod files
+       in addition to straight C/C++ code for extensions.
+
+Common Lisp
+-----------
+
+*      Random thoughts by mkoeppe on supporting Common Lisp implementations:
+
+       There are many different Foreign Function Interfaces (FFI) for
+       the various CL implementations.  Probably SWIG should interface
+       to UFFI, a least-common-denominator FFI that supports many
+       implementations.
+
+       Via the s-expression SWIG module we can export SWIG's parse
+       tree and import it into CL.  It remains to check if all
+       relevant information is dumped (for instance, the type
+       information).  Experimental code is available to generate
+       low-level UFFI declarations from this parse tree.
+
+       However, for wrapping C++, we also need to create C wrappers
+       because most FFIs cannot directly import C++.  A CL SWIG module
+       could be exporting both these wrappers and UFFI declarations.
+       I have experimental code (not checked in yet) that does this.
+
+       This is fine for generating low-level wrappers. But how do we
+       support user typemaps (like converting lists and vectors to C
+       arrays on input)?  We have to generate Lisp code that does the
+       conversion and then calls the low-level wrapper.  If we
+       generate Lisp code, it should be beautiful and readable.
+       Therefore, we need at least a Lisp pretty printer.  A Lisp
+       pretty printer works best when the Lisp program is represented
+       not as text but as Lisp data.  Moreover, typemap writers will
+       feel very much constrained by SWIG's capabilities for
+       generating wrapper code, when compared to writing Lisp macros.
+       Thus we would need half a re-implementation of Lisp in SWIG to
+       make users happy.
+
+       The solution could be the following:
+
+**     Build a SWIG library (again) and load it into a Common Lisp
+       implementation.
+
+       The FFI declarations could be written manually, or this could
+       be bootstrapped via the s-expression module or the primitive
+       UFFI wrappers.  This should be easy because SWIG's API is quite
+       simple. 
+
+       The embedded SWIG would be driven by a CL program.  High-level
+       typemaps would be written as Lisp programs that generate Lisp
+       code.
+
+Ocaml
+-----
+**     I've been working with my camlp4 module and type information
+       from the compiler.  When I'm done, the user will have access
+       to type inference when writing code, when the inference is
+       unambiguous.  This allows the user to write x = _foo 1.0
+       instead of x = get_float (_foo (C_float 1.0)).  It's not as
+       easy as it sounds, because O'caml doesn't keep type information
+       at run time, and doesn't really have a mechanism for doing what
+       I need.  However, it's possible to write a preprocessor that
+       inserts correct type info at compile time.
+
+       That having been said, the program must compile for type info
+       to be available, so I need to attend to a lot of details;  The
+       program must compile both with and without type augmentation.
+       
+Xml
+---
+
+
+Documentation
+-------------
+
+****   Extending SWIG (and internals).
+
+***    Perl, Python, Tcl modules.
+
+***    add section for Perl module support for operator overloading
+
+**     Add section on WAD.
+
diff --git a/trunk/Tools/WAD/CHANGES b/trunk/Tools/WAD/CHANGES
new file mode 100644
index 0000000..186d15e
--- /dev/null
+++ b/trunk/Tools/WAD/CHANGES
@@ -0,0 +1,25 @@
+WAD 0.3  - June 2, 2002
+
+   -   Added to the SWIG distribution.
+
+WAD 0.2  - June 24, 2001
+   
+   -   Minor changes.  Added the wadtrace file
+
+   -   Put everything under the LGPL.
+
+WAD 0.1  - March 23, 2001
+
+   -   Extensive changes to WAD core.  WAD now builds an exception
+       object that can be queried and manipulated after a fault
+       occurs.
+
+   -   Better collection of debugging information.  WAD is now
+       able to determine basic datatypes and other information
+       from stabs data.
+
+   -   Better reliability overall.
+
+WAD 0.0 - January, 2001
+
+beazley  - Initial "release".  Not much of a release really.
diff --git a/trunk/Tools/WAD/COPYING b/trunk/Tools/WAD/COPYING
new file mode 100644
index 0000000..b1e3f5a
--- /dev/null
+++ b/trunk/Tools/WAD/COPYING
@@ -0,0 +1,504 @@
+		  GNU LESSER GENERAL PUBLIC LICENSE
+		       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+		  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+			    NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/trunk/Tools/WAD/HACK b/trunk/Tools/WAD/HACK
new file mode 100644
index 0000000..dfece60
--- /dev/null
+++ b/trunk/Tools/WAD/HACK
@@ -0,0 +1,78 @@
+The WAD Developers Guide
+
+David Beazley (beazley@cs.uchicago.edu)
+
+$Id$
+
+1.  Introduction
+
+This short document is intended for anyone who feels inclined to work
+on WAD and make improvements.   It is by no means complete.  However,
+it contains random commentary on the current implementation.
+
+2.  A brief word on the execution environment
+
+Because WAD is embedded in the same application it is intended to
+debug, it must take an extremely conservative approach to its own
+execution environment.  Specifically, it can not rely upon the correct
+operation of C library--especially with respect to memory management
+and other basic operations.  Because of this, the implementation of
+WAD makes every effort to be as self-contained as possible--thus
+minimizing its exposure to corrupted libraries in the faulting
+application.  Closely related to this, WAD does not rely on any
+third-party libraries (e.g., libbfd) since it is almost impossible to
+fully verify the way in which such libraries might use other programming
+libraries.  
+
+With that said, you might keep the following rules in mind:
+
+     rule 1:   Trust nothing--it might be broken.
+     rule 2:   When in doubt, see rule 1.
+
+(Of course, we can probably get away with assuming that the OS isn't
+hosed).
+
+3.  Memory management
+
+There are two problems here: first, the dynamic memory
+allocator may be corrupted or broken (e.g., as might occur when
+you double-free memory or free memory not allocated by malloc). 
+Second, the WAD signal handler prefers to execute own on its own
+signal handling stack.  This stack is of limited size so it is not
+a reliable place to put large amounts of data.
+
+Small buffers and scratch areas are managed through the use of static
+variables allocated in the WAD data-segment.  
+
+For dynamic memory management, WAD provides its own memory allocator
+in the function wad_malloc().  This function allocates memory by using
+mmap() to grab anonymous memory regions (mapped to /dev/zero).  This
+memory is currently allocated in chunks of 64Kbytes as needed.
+
+To simplify the implementation and prevent potential memory problems
+in WAD itself, WAD never releases the memory that it allocates.  There
+is no wad_free() operation nor is there any way to release all of the
+memory previously allocated.
+
+Although memory is never released, WAD tries to intern commonly used
+strings. An internal string hash is built as WAD runs and in most
+cases, each string is mapped to a single instance of the string in
+this hash table.  The function wad_string_lookup(char *s) is used to
+return a pointer to the string s in the hash table.  If no entry
+exists, it is created and a pointer is returned.
+
+4. I/O
+
+It is probably a bad idea to use buffered I/O with WAD.   This may
+result in implicit calls to malloc() and related functions.
+
+
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Tools/WAD/Include/wad.h b/trunk/Tools/WAD/Include/wad.h
new file mode 100644
index 0000000..9a50073
--- /dev/null
+++ b/trunk/Tools/WAD/Include/wad.h
@@ -0,0 +1,269 @@
+/* ----------------------------------------------------------------------------- 
+ * wad.h
+ *
+ *     WAD header file (obviously)
+ *    
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2001. University of Chicago. All rights reserved.
+ *
+ * $Id$
+ * ----------------------------------------------------------------------------- */
+
+#include <stdio.h>
+#include <unistd.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/mman.h>
+#include <ctype.h>
+#include <sys/ucontext.h>
+
+#ifdef WAD_SOLARIS
+#include <procfs.h>
+
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+  /* Core datatypes */
+
+  typedef int             int32;
+  typedef unsigned        uint32;
+  typedef short           int16;
+  typedef unsigned short  uint16;
+  typedef signed char     int8;
+  typedef unsigned char   uint8;
+
+
+#ifndef MAX_PATH
+#define MAX_PATH 1024
+#endif
+
+#define WAD_SRC_WINDOW 2
+
+/* --- Low level memory management functions --- */
+
+extern int   wad_memory_init();
+extern void *wad_malloc(int nbytes);
+extern char *wad_strdup(const char *c);
+extern void  wad_memory_debug();
+extern void  wad_memcpy(void *t, const void *s, unsigned len);
+
+  /* --- Low level string handling --- */
+
+extern char *wad_string_lookup(char *s);
+extern void  wad_string_debug();
+extern char *wad_strcpy(char *t, const char *s);
+extern char *wad_strcat(char *t, const char *s);
+extern int   wad_strlen(const char *s);
+
+/* --- I/O, Debugging --- */
+
+extern void wad_printf(const char *fmt, ...);
+extern char *wad_format_hex(unsigned long u, int leading);
+extern char *wad_format_unsigned(unsigned long u, int width);
+extern char *wad_format_signed(long s, int width);
+
+/* --- Memory segments --- */
+typedef struct WadSegment {
+  char              *base;                  /* Base address for symbol lookup */
+  char              *vaddr;                 /* Virtual address start          */
+  unsigned long      size;                  /* Size of the segment (bytes)    */
+  unsigned long      offset;                /* Offset into mapped object      */
+  char              *mapname;               /* Filename mapped to this region */
+  char              *mappath;               /* Full path to mapname           */
+  struct WadSegment *next;                  /* Next segment                   */
+} WadSegment;
+
+extern int         wad_segment_read();
+extern WadSegment *wad_segment_find(void *vaddr);
+extern int         wad_segment_valid(void *vaddr);
+
+/* --- Object files --- */
+typedef struct WadObjectFile {
+  void             *ptr;            /* Pointer to data           */
+  int               len;            /* Length of data            */
+  int               type;           /* Type of the object file   */
+  char             *path;           /* Path name of this object  */
+  struct WadObjectFile *next;
+} WadObjectFile;
+
+extern void            wad_object_reset();
+extern WadObjectFile  *wad_object_load(const char *path);
+extern int             wad_file_check(void *);
+
+#define SYM_LOCAL     1
+#define SYM_GLOBAL    2
+
+/* Signal handling */
+extern void wad_init();
+extern void wad_signalhandler(int, siginfo_t *, void *);
+extern void wad_signal_init();
+extern void wad_signal_clear();
+extern void wad_set_return(const char *name, long value);
+extern void wad_set_return_value(long value);
+extern void wad_set_return_func(void (*f)(void));
+
+typedef struct WadLocal {
+  char              *name;       /* Name of the local */
+  void              *ptr;        /* Pointer to the actual data (if known)  */
+  int                size;       /* Size of the data (if known)  */
+  int                type;       /* Data type         */
+
+  /* Debugging information */
+
+  int                loc;        /* Location: register or stack */
+  int                stack;      /* location on the stack       */
+  int                reg;        /* Register number             */
+  int                line;       /* Line number where defined   */
+  struct WadLocal   *next;
+} WadLocal;
+
+#define PARM_REGISTER 1
+#define PARM_STACK    2
+
+/* Type codes for local variables */
+
+#define WAD_TYPE_UNKNOWN      0
+#define WAD_TYPE_INT32        1
+#define WAD_TYPE_INT16        2
+#define WAD_TYPE_INT8         3
+#define WAD_TYPE_INT64        4
+#define WAD_TYPE_UINT32       5
+#define WAD_TYPE_UINT16       6
+#define WAD_TYPE_UINT8        7
+#define WAD_TYPE_UINT64       8
+#define WAD_TYPE_FLOAT        9
+#define WAD_TYPE_DOUBLE      10
+#define WAD_TYPE_POINTER     11
+#define WAD_TYPE_CHAR        12
+
+extern long   wad_local_as_long(WadLocal *loc);
+extern double wad_local_as_double(WadLocal *loc);
+
+/* Data structure containing information about each stack frame */
+
+typedef struct WadFrame {
+  long               frameno;       /* Frame number */
+  struct WadFrame   *next;          /* Next frame up the stack */
+  struct WadFrame   *prev;          /* Previous frame down the stack */
+
+  /* Stack context information */
+  long               pc;            /* Real PC */
+  long               sp;            /* Real SP */
+  long               fp;            /* Real FP */
+  char              *stack;         /* Pointer to where a copy of the stack frame is stored */
+  int                stack_size;    /* Stack frame size (fp-sp) */
+
+  /* Loading information.  Contains information from /proc as well as a pointer to
+     the executable or shared library in which the PC is located */
+
+  WadSegment        *segment;       /* Memory segment corresponding to PC */
+  WadObjectFile     *object;        /* Object file corresponding to PC */
+
+  /* Symbol table information for PC */
+
+  char              *sym_name;        /* Symbol name          */
+  int                sym_nlen;        /* Symbol name length   */
+  char              *sym_file;        /* Source file (if any) */
+  unsigned long      sym_base;        /* Symbol base address  */
+  unsigned long      sym_size;        /* Symbol size          */
+  int                sym_type;        /* Symbol type          */
+  int                sym_bind;        /* Symbol binding       */
+
+  /* Location information */
+  char              *loc_objfile;     /* Object filename */
+  char              *loc_srcfile;     /* Source filename */
+  int                loc_line;        /* Source line */
+
+  /* Debugging information */
+  int                debug_check;     /* Checked debugging information */
+  int                debug_nargs;     /* Number of arguments */
+  WadLocal          *debug_args;      /* Arguments           */
+  WadLocal          *debug_lastarg;   /* Last argument       */
+  int                debug_nlocals;   /* Number of locals    */
+  WadLocal          *debug_locals;    /* Local variables     */
+  WadLocal          *debug_lastlocal; /* Last local          */
+
+  /* Output strings */
+  char              *debug_str;       /* Debugging string */
+  char              *debug_srcstr;    /* Source string    */
+
+  int                last;            /* Last frame flag */
+} WadFrame;
+
+extern WadFrame *wad_stack_trace(unsigned long, unsigned long, unsigned long);
+extern void      wad_stack_debug(WadFrame *f);
+
+extern char   *wad_strip_dir(char *);
+extern void    wad_default_callback(int signo, WadFrame *frame, char *ret);
+extern void    wad_dump_trace(int fd, int signo, WadFrame *frame, char *ret);
+
+extern void    wad_set_callback(void (*h)(int, WadFrame *, char *));
+extern char   *wad_load_source(char *, int line);
+extern void    wad_release_source();
+extern void    wad_release_trace();
+extern long    wad_steal_arg(WadFrame *f, char *symbol, int argno, int *error);
+extern long    wad_steal_outarg(WadFrame *f, char *symbol, int argno, int *error);
+
+extern char *wad_arg_string(WadFrame *f);
+
+typedef struct {
+  char        name[128];
+  long        value;
+} WadReturnFunc;
+
+extern void wad_set_returns(WadReturnFunc *rf);
+extern WadReturnFunc *wad_check_return(const char *name);
+
+extern int wad_search_stab(void *stab, int size, char *stabstr, WadFrame *f);
+
+extern void wad_find_object(WadFrame *f);
+extern void wad_find_symbol(WadFrame *f);
+extern void wad_find_debug(WadFrame *f);
+extern void wad_build_vars(WadFrame *f);
+extern char *wad_format_var(WadLocal *l);
+
+extern void  wad_debug_make_strings(WadFrame *f);
+
+/* --- Debugging Interface --- */
+
+#define DEBUG_SEGMENT        0x1
+#define DEBUG_SYMBOL         0x2
+#define DEBUG_STABS          0x4
+#define DEBUG_OBJECT         0x8
+#define DEBUG_FILE           0x10
+#define DEBUG_HOLD           0x20
+#define DEBUG_RETURN         0x40
+#define DEBUG_SYMBOL_SEARCH  0x80
+#define DEBUG_INIT           0x100
+#define DEBUG_NOSTACK        0x200
+#define DEBUG_ONESHOT        0x400
+#define DEBUG_STACK          0x800
+#define DEBUG_UNWIND         0x1000
+#define DEBUG_SIGNAL         0x2000
+#define DEBUG_STRING         0x4000
+#define DEBUG_MEMORY         0x8000
+
+extern int wad_debug_mode;
+extern int wad_heap_overflow;
+
+#ifdef WAD_LINUX
+#define   WAD_LITTLE_ENDIAN
+#endif
+#ifdef WAD_SOLARIS
+#define   WAD_BIG_ENDIAN
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
diff --git a/trunk/Tools/WAD/Makefile.in b/trunk/Tools/WAD/Makefile.in
new file mode 100644
index 0000000..d76f117
--- /dev/null
+++ b/trunk/Tools/WAD/Makefile.in
@@ -0,0 +1,46 @@
+# Generated automatically from Makefile.in by configure.
+
+SHELL     = /bin/sh
+prefix    = @prefix@
+execprefix= @exec_prefix@
+LIB        = $(execprefix)/lib
+
+# Location of your Python installation
+PYINCLUDE = @PYINCLUDE@
+
+# Location of your Tcl installation
+TCLINCLUDE = @TCLINCLUDE@
+
+# Location of your Perl installation
+PERLINCLUDE = @PERL5EXT@
+
+all: wad @MAKEPYTHON@ @MAKETCL@ #@MAKEPERL@
+
+wad:
+	@cd Wad; $(MAKE) wad
+
+python:
+	@cd Python; $(MAKE) SINCLUDE='$(PYINCLUDE)' python
+
+tcl:
+	@cd Tcl; $(MAKE) SINCLUDE='$(TCLINCLUDE)' tcl
+
+perl:
+	@cd Wad; $(MAKE) SINCLUDE='$(PERLINCLUDE)' perl
+
+install:
+	cp libwad*.so $(LIB)
+	chmod a+rx $(LIB)/libwad*.so
+
+semi:
+	@cd Wad; $(MAKE) semi
+	@cd Python; $(MAKE) semi
+	@cd Tcl; $(MAKE) semi
+
+clean:
+	@cd Wad; $(MAKE) clean
+	@cd Python; $(MAKE) clean
+	@cd Tcl; $(MAKE) clean
+	@cd Test; $(MAKE) clean
+	rm *.so
+
diff --git a/trunk/Tools/WAD/Misc/fileheader b/trunk/Tools/WAD/Misc/fileheader
new file mode 100644
index 0000000..7b82e9e
--- /dev/null
+++ b/trunk/Tools/WAD/Misc/fileheader
@@ -0,0 +1,28 @@
+/* ----------------------------------------------------------------------------- 
+ * segment.c
+ *
+ *     This file provides access to the virtual memory map of a process
+ *     including the location of the executable, data segments, shared
+ *     libraries, and memory mapped regions.  This information is 
+ *     obtained through /proc.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
diff --git a/trunk/Tools/WAD/Papers/README b/trunk/Tools/WAD/Papers/README
new file mode 100644
index 0000000..8eb7b81
--- /dev/null
+++ b/trunk/Tools/WAD/Papers/README
@@ -0,0 +1,5 @@
+Papers about WAD can be obtained at:
+
+   http://systems.cs.uchicago.edu/wad
+
+
diff --git a/trunk/Tools/WAD/Prebuilt/linux/Makefile.in b/trunk/Tools/WAD/Prebuilt/linux/Makefile.in
new file mode 100644
index 0000000..074e654
--- /dev/null
+++ b/trunk/Tools/WAD/Prebuilt/linux/Makefile.in
@@ -0,0 +1,11 @@
+# Generated automatically from Makefile.in by configure.
+
+SHELL     = /bin/sh
+prefix    = @prefix@
+execprefix= @exec_prefix@
+LIB        = $(execprefix)/lib
+
+install:
+	cp libwad*.so $(LIB)
+	chmod a+rx $(LIB)/libwad*.so
+
diff --git a/trunk/Tools/WAD/Prebuilt/solaris/Makefile.in b/trunk/Tools/WAD/Prebuilt/solaris/Makefile.in
new file mode 100644
index 0000000..074e654
--- /dev/null
+++ b/trunk/Tools/WAD/Prebuilt/solaris/Makefile.in
@@ -0,0 +1,11 @@
+# Generated automatically from Makefile.in by configure.
+
+SHELL     = /bin/sh
+prefix    = @prefix@
+execprefix= @exec_prefix@
+LIB        = $(execprefix)/lib
+
+install:
+	cp libwad*.so $(LIB)
+	chmod a+rx $(LIB)/libwad*.so
+
diff --git a/trunk/Tools/WAD/Python/Makefile.in b/trunk/Tools/WAD/Python/Makefile.in
new file mode 100644
index 0000000..2859039
--- /dev/null
+++ b/trunk/Tools/WAD/Python/Makefile.in
@@ -0,0 +1,54 @@
+#######################################################################
+# WAD Makefile
+#
+# David Beazley
+# January 1, 2001
+#######################################################################
+
+# These are the files that make up the WAD core
+SRCS = type.c python.c
+OBJS = type.o python.o
+INCLUDE = -I../Include -I.  $(SINCLUDE)
+WADOPT     = @WADOPT@
+
+# Location of your Python installation
+PYINCLUDE = @PYINCLUDE@
+PYSRCS    = wadpyinit.cxx
+PYOBJS    = wadpyinit.o
+
+# C Compiler
+CC = @CC@
+CFLAGS = #@CCSHARED@
+
+# C++ Compiler
+CXX = @CXX@
+CXXFLAGS = #@CXXSHARED@
+
+# Linking options
+CLINK = 
+CXXLINK = @CXXLINK@
+
+# Rules for creation of a .o file from .cxx
+.SUFFIXES: .cxx
+.cxx.o:
+	$(CXX) $(CXXFLAGS) $(WADOPT) $(INCLUDE) -c -o $*.o $<
+
+.c.o:
+	$(CC) $(CFLAGS) $(PYINCLUDE) $(WADOPT) $(INCLUDE) -c -o $*.o $<
+
+python: $(OBJS) $(PYOBJS)
+	$(CXXLINK) $(OBJS) $(PYOBJS) -o libwadpy.so -L.. -lwadcore
+	cp libwadpy.so ..
+
+wc::
+	wc $(SRCS)
+
+semi::
+	@egrep ";" $(SRCS) $(PYSRCS) | wc
+
+clean::
+	rm -f *.o *.so *~ 
+
+
+
+
diff --git a/trunk/Tools/WAD/Python/python.c b/trunk/Tools/WAD/Python/python.c
new file mode 100644
index 0000000..9f46865
--- /dev/null
+++ b/trunk/Tools/WAD/Python/python.c
@@ -0,0 +1,221 @@
+/* ----------------------------------------------------------------------------- 
+ * python.c
+ *
+ *     Dynamically loadable python module for wad.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "Python.h"
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* These are the python exception objects we will add
+   SegFault, BusError, AbortError */
+
+static PyObject *segfault_exc = 0;
+static PyObject *buserror_exc = 0;
+static PyObject *abort_exc = 0;
+static PyObject *illegal_exc = 0;
+
+extern PyObject *new_wadobject(WadFrame *f,int);
+
+/* Function return points and values */
+
+static WadReturnFunc retpts[] = {
+  {"call_builtin", 0},
+  {"_PyImport_LoadDynamicModule", 0},
+  {"PyEval_EvalCode", 0},
+  {"PyObject_GetAttrString", 0},
+  {"PyObject_SetAttrString", -1},
+  {"PyObject_Repr", 0},
+  {"PyObject_Print", -1},
+  {"PyObject_CallFunction", 0},
+  {"PyObject_CallMethod", 0},
+  {"PyObject_CallObject", 0},
+  {"PyObject_Cmp", -1},
+  {"PyObject_Compare", -1},
+  {"PyObject_DelAttrString",-1},
+  {"PyObject_DelItem",-1},
+  {"PyObject_GetItem",0},
+  {"PyObject_SetItem",-1},
+  {"PyObject_HasAttrString",-1},
+  {"PyObject_Hash",-1},
+  {"PyObject_Length",-1},
+  {"PyObject_Str",0},
+  {"PyObject_Type", 0},
+
+  {"PyNumber_Absolute", 0},
+  {"PyNumber_Add",0},
+  {"PyNumber_And",0},
+  {"PyNumber_Coerce",0},
+  {"PyNumber_Divide",0},
+  {"PyNumber_Divmod",0},
+  {"PyNumber_Float",0},
+  {"PyNumber_Int",0},
+  {"PyNumber_Invert",0},
+  {"PyNumber_Long",0},
+  {"PyNumber_Lshift",0},
+  {"PyNumber_Multiply", 0},
+  {"PyNumber_Negative", 0},
+  {"PyNumber_Or",0},
+  {"PyNumber_Positive", 0},
+  {"PyNumber_Power",0},
+  {"PyNumber_Remainder",0},
+  {"PyNumber_Rshift",0},
+  {"PyNumber_Subtract",0},
+  {"PyNumber_Xor",0},
+
+  {"PySequence_Concat",0},
+  {"PySequence_Count",-1},
+  {"PySequence_Delitem",-1},
+  {"PySequence_DelSlice",-1},
+  {"PySequence_Getitem",0},
+  {"PySequence_GetSlice",0},
+  {"PySequence_In",-1},
+  {"PySequence_Index",-1},
+  {"PySequence_Repeat",0},
+  {"PySequence_SetItem",-1},
+  {"PySequence_SetSlice",-1},
+  {"PySequence_Tuple",0},
+
+  {"PyMapping_Clear",-1},
+  {"PyMapping_DelItem",-1},
+  {"PyMapping_DelItemString",-1},
+  {"PyMapping_GetItemString",0},
+  {"PyMapping_HasKey",-1},
+  {"PyMapping_HasKeyString",-1},
+  {"PyMapping_Items",0},
+  {"PyMapping_Keys",0},
+  {"PyMapping_Length", -1},
+  {"PyMapping_SetItemString", -1},
+  {"PyMapping_Values", 0},
+  {"",0}};
+
+/* Handler function */	
+static void handler(int signo, WadFrame *frame, char *ret) {
+  static char message[65536];
+  static char temp[1024];
+  int  len = 0;
+  PyObject *type;
+  char *name;
+  WadFrame *f;
+  WadFrame *fline = 0;
+  char     *srcstr = 0;
+
+  /*  printf("python handler.\n"); */
+  if (!ret) {
+    wad_default_callback(signo, frame, ret);
+    return;
+  }
+
+  strcpy(message,"[ C stack trace ]\n\n");
+  switch(signo) {
+  case SIGSEGV:
+    type = segfault_exc;
+    break;
+  case SIGBUS:
+    type = buserror_exc;
+    break;
+  case SIGABRT:
+    type = abort_exc;
+    break;
+  case SIGFPE:
+    type = PyExc_FloatingPointError;
+    break;
+  case SIGILL:
+    type = illegal_exc;
+    break;
+  default:
+    type = PyExc_RuntimeError;
+    break;
+  }
+
+#ifdef OLD
+  f = frame;
+  /* Find the last exception frame */
+  while (!f->last) {
+    f= f->next;
+  }
+  /* Now work backwards */
+  f = f->prev;
+  while (f) {
+    strcat(message, f->debug_str);
+    if (f->debug_srcstr) srcstr = f->debug_srcstr;
+    f = f->prev;
+  }
+  if (srcstr) {
+    strcat(message,"\n");
+    strcat(message, srcstr);
+    strcat(message,"\n");
+  }
+#endif
+
+  if (wad_heap_overflow) {
+    write(2, "WAD: Heap overflow detected.\n", 30);
+    wad_default_callback(signo, frame, ret);
+  }
+
+  /* Note: if the heap is blown, there is a very good chance that this
+  function will not succeed and we'll dump core.  However, the check
+  above should dump a stack trace to stderr just in case we don't make it
+  back. */
+
+#ifdef OLD
+  PyErr_SetString(type, message);
+#endif
+  PyErr_SetObject(type, new_wadobject(frame,0));
+
+}
+
+void pywadinit() {
+  PyObject *d, *m;
+  m = PyImport_ImportModule((char *)"__builtin__");
+  d = PyModule_GetDict(m);
+  printf("WAD Enabled\n");
+
+  segfault_exc = PyErr_NewException((char *)"exceptions.SegFault", NULL, NULL);
+  PyDict_SetItemString(d,(char *)"SegFault",segfault_exc);
+
+  buserror_exc = PyErr_NewException((char *)"exceptions.BusError", NULL, NULL);
+  PyDict_SetItemString(d,(char *)"BusError",buserror_exc);
+
+  abort_exc = PyErr_NewException((char*)"exceptions.AbortError", NULL, NULL);
+  PyDict_SetItemString(d,(char *)"AbortError",abort_exc);
+
+  illegal_exc = PyErr_NewException((char *)"exceptions.IllegalInstruction", NULL, NULL);
+  PyDict_SetItemString(d,(char *)"IllegalInstruction",illegal_exc);  
+
+  wad_init();
+  wad_set_callback(handler);
+  wad_set_returns(retpts);
+}
+
+static PyMethodDef wadmethods[] = {
+  {0,0},
+};
+
+void initlibwadpy() {
+  Py_InitModule((char *)"libwadpy",wadmethods);
+}
+
+
diff --git a/trunk/Tools/WAD/Python/type.c b/trunk/Tools/WAD/Python/type.c
new file mode 100644
index 0000000..7d8248e
--- /dev/null
+++ b/trunk/Tools/WAD/Python/type.c
@@ -0,0 +1,277 @@
+/* ----------------------------------------------------------------------------- 
+ * type.c
+ *
+ *     This file defines a new python type that contains information from
+ *     the WAD stack trace.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+
+#include "wad.h"
+#include "Python.h"
+
+static char cvs[] = "$Id$";
+
+typedef struct {
+  PyObject_HEAD
+  WadFrame   *frame;       /* Wad Stack frame object   */
+  int         count;       /* Number of frames         */
+} wadobject;
+
+staticforward PyTypeObject WadObjectType;
+
+
+PyObject *
+new_wadobject(WadFrame *f, int count) {
+  wadobject   *self;
+  self = PyObject_NEW(wadobject, &WadObjectType);
+  if (self == NULL) return NULL;
+  
+  self->frame = f;
+  if (count > 0) {
+    self->count = count;
+  } else {
+    self->count = 0;
+    while (f) {
+      self->count++;
+      f = f->next;
+    }
+  }
+  return (PyObject *) self;
+}
+
+/* release a wad object */
+static void
+wadobject_dealloc(wadobject *self) {
+  PyObject_Del(self);
+}
+
+static char message[65536];
+static PyObject *
+wadobject_repr(wadobject *self) {
+  char *srcstr = 0;
+  WadFrame *fp = 0;
+  int    n;
+  WadFrame *f = self->frame;
+
+  message[0] = 0;
+  /* Find the last exception frame */
+  n = self->count;
+  while (f && n) {
+    fp = f;
+    f= f->next;
+    n--;
+  }
+
+  if (fp) {
+  /* Now work backwards */
+    f = fp;
+    while (f) {
+      strcat(message, f->debug_str);
+      if (f->debug_srcstr) srcstr = f->debug_srcstr;
+      if (f == self->frame) break;
+      f = f->prev;
+    }
+    if (srcstr) {
+      strcat(message,"\n");
+      strcat(message, srcstr);
+      strcat(message,"\n");
+    }
+  }
+  return PyString_FromString(message);
+}
+
+static PyObject *
+wadobject_str(wadobject *self) {
+  char *srcstr = 0;
+  int   n;
+
+  WadFrame *f = self->frame;
+  n = self->count;
+  strcpy(message,"[ C stack trace ]\n\n");
+  /* Find the last exception frame */
+  while (!f->last && n) {
+    f= f->next;
+    n--;
+  }
+  /* Now work backwards */
+  if (n <= 0) {
+    f = f->prev;
+  }
+  while (f) {
+    strcat(message, f->debug_str);
+    if (f->debug_srcstr) srcstr = f->debug_srcstr;
+    if (self->frame == f) break;
+    f = f->prev;
+  }
+  if (srcstr) {
+    strcat(message,"\n");
+    strcat(message, srcstr);
+    strcat(message,"\n");
+  }
+  return PyString_FromString(message);
+}
+
+static int
+wadobject_len(wadobject *self) {
+  int n = 0;
+  WadFrame *f = self->frame;
+  while (f) {
+    n++;
+    f = f->next;
+  }
+  return n;
+}
+
+static PyObject *
+wadobject_getitem(wadobject *self, int n) {
+  int i;
+  WadFrame *f;
+  if (n < 0) {
+    n = self->count + n;
+  }
+  if ((n < 0) || (n >= self->count)) {
+    PyErr_SetString(PyExc_IndexError,"Stack frame out of range");
+    return NULL;
+  }
+  f = self->frame;
+  for (i = 0; i <n; i++) {
+    f = f->next;
+  }
+  return new_wadobject(f,1);
+}
+
+static PyObject *
+wadobject_getslice(wadobject *self, int start, int end) {
+  int i;
+  WadFrame *f;
+
+  f = self->frame;
+  for (i = 0; i < start; i++) {
+    f = f->next;
+  }
+  return new_wadobject(f,(end-start));
+}
+
+static PyObject *
+wadobject_getattr(wadobject *self, char *name) {
+  if (strcmp(name,"__NAME__") == 0) {
+    return Py_BuildValue("z", self->frame->sym_name);
+  } else if (strcmp(name,"__EXE__") == 0) {
+    return Py_BuildValue("z", self->frame->object->path);
+  } else if (strcmp(name,"__FILE__") == 0) {
+    return Py_BuildValue("z", self->frame->loc_srcfile);
+  } else if (strcmp(name,"__OBJECT__") == 0) {
+    return Py_BuildValue("z", self->frame->loc_objfile);
+  } else if (strcmp(name,"__LINE__") == 0) {
+    return Py_BuildValue("i", self->frame->loc_line);
+  } else if (strcmp(name,"__SOURCE__") == 0) {
+    return Py_BuildValue("z",self->frame->debug_srcstr);
+  } else if (strcmp(name,"__PC__") == 0) {
+    return PyLong_FromUnsignedLong(self->frame->pc);
+  } else if (strcmp(name,"__SP__") == 0) {
+    return PyLong_FromUnsignedLong(self->frame->sp);
+  } else if (strcmp(name,"__FP__") == 0) {
+    return PyLong_FromUnsignedLong(self->frame->fp);
+  } else if (strcmp(name,"__STACK__") == 0) {
+    return PyString_FromStringAndSize(self->frame->stack, self->frame->stack_size);
+  } else if (strcmp(name,"__NARGS__") == 0) {
+    return PyInt_FromLong(self->frame->debug_nargs);
+  } else if (strcmp(name,"__LAST__") == 0) {
+    return PyInt_FromLong(self->frame->last);
+  } else if (strcmp(name,"__WHERE__") == 0) {
+    return Py_BuildValue("z",self->frame->debug_str);
+  } else if (strcmp(name,"__WAD__") == 0) {
+    return PyInt_FromLong(1);
+  }
+
+  
+  /* Put a check for local variables */
+  {
+    int i;
+    for (i = 0; i < 2; i++) {
+      WadLocal *loc;
+      if (i == 0) loc = self->frame->debug_locals;
+      else loc = self->frame->debug_args;
+      while (loc) {
+	if (strcmp(name,loc->name) == 0) {
+	  switch(loc->type) {
+	  case WAD_TYPE_INT32:
+	  case WAD_TYPE_INT16:
+	  case WAD_TYPE_INT8:
+	    return PyLong_FromLong(wad_local_as_long(loc));
+	    break;
+	  case WAD_TYPE_UINT8:
+	  case WAD_TYPE_UINT16:
+	  case WAD_TYPE_UINT32:
+	    return PyLong_FromUnsignedLong((unsigned long) wad_local_as_long(loc));
+	    break;
+	  case WAD_TYPE_CHAR:
+	    return Py_BuildValue("c", (char) (PyLong_FromLong(wad_local_as_long(loc))));
+	    break;
+	  case WAD_TYPE_FLOAT:
+	  case WAD_TYPE_DOUBLE:
+	    return PyFloat_FromDouble(wad_local_as_double(loc));
+	    break;
+	  default:
+	    return PyLong_FromUnsignedLong((unsigned long) wad_local_as_long(loc));
+	  }
+	}
+	loc = loc->next;
+      }
+    }
+  }
+  
+  PyErr_SetString(PyExc_NameError,"Unknown attribute.");
+  return NULL;
+}
+static PySequenceMethods wadobject_as_sequence = {
+  (inquiry)   wadobject_len,
+  0,
+  0,
+  (intargfunc)  wadobject_getitem,  /* get item */
+  (intintargfunc)  wadobject_getslice,  /* get slice */
+  0,
+  0
+};
+
+static PyTypeObject WadObjectType = {
+  PyObject_HEAD_INIT(&PyType_Type)
+  0,
+  "WadObject",
+  sizeof(wadobject),
+  0,
+  (destructor) wadobject_dealloc,
+  0,             /* printfunc */
+  (getattrfunc) wadobject_getattr,
+  (setattrfunc) 0,
+  (cmpfunc) 0,
+  (reprfunc) wadobject_repr,
+  
+  0,     /* number */
+  &wadobject_as_sequence,     /* sequence */
+  0,     /* mapping */
+  0,     /* hash */
+  0,     /* call */
+  (reprfunc) wadobject_str,   /* str */
+};
+
diff --git a/trunk/Tools/WAD/Python/wadpyinit.cxx b/trunk/Tools/WAD/Python/wadpyinit.cxx
new file mode 100644
index 0000000..b970094
--- /dev/null
+++ b/trunk/Tools/WAD/Python/wadpyinit.cxx
@@ -0,0 +1,45 @@
+/* ----------------------------------------------------------------------------- 
+ * wadpyinit.cxx
+ *
+ *     C++ automatic initializer for Python module.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+extern "C" void pywadinit();
+
+/* This hack is used to auto-initialize wad regardless of whether we are
+   used as an imported module or as a link-library for another module */
+   
+class wadinitializer {
+public:
+  wadinitializer() {
+    pywadinit();
+  }
+};
+
+static wadinitializer wi;
+
+
diff --git a/trunk/Tools/WAD/README b/trunk/Tools/WAD/README
new file mode 100644
index 0000000..c777c4e
--- /dev/null
+++ b/trunk/Tools/WAD/README
@@ -0,0 +1,376 @@
+WAD (Wrapped Application Debugger)
+
+Author(s):
+    David M. Beazley (beazley@cs.uchicago.edu)
+
+Copyright (C) 2001
+University of Chicago
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+See the file COPYING for a complete copy of the LGPL.
+
+$Id$
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!                     DISCLAIMER                         !!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+THIS IS EXPERIMENTAL UNMAINTAINED RESEARCH SOFTWARE THAT REPRESENTS
+WORK IN PROGRESS.  IT IS NOT PORTABLE, IT HAS NOT BEEN EXHAUSTIVELY
+TESTED, AND IT MIGHT NOT WORK AT ALL.  PLEASE KEEP AWAY FROM SMALL
+CHILDREN, PETS, NUCLEAR REACTORS, AIR-TRAFFIC CONTROL, AND VOTING
+MACHINES.
+
+0. Supported Platforms 
+
+This software is currently only known to work with 32-bit applications
+on Sun Sparc Solaris 2.8 and recent i386-Linux systems. In addition,
+there are numerous issues concerning the interaction of this software
+with signal handling, thread libraries, and compilers.  Please read
+this entire document before proceeding.
+
+1. Introduction
+
+WAD is an embedded error-recovery mechanism that attempts to convert
+fatal errors such as SIGSEGV, SIGBUS, and SIGFPE into sensible error
+messages and exceptions.  It is primarily designed to support
+scripting language extension programming although it can also be used
+with stand-alone C programs.
+
+The primary goal of this system is to explore an alternative approach
+to mixed scripting-compiled debugging.  It requires no modifications
+or recompilation of existing software. Therefore, it should be
+relatively easy to try out.  Feedback is welcome. Contributions and
+modifications are even more welcome.
+
+2. Compilation and Installation
+
+WAD is not particularly portable and at this time, only two platforms
+are supported: Sun Sparc Solaris and i386-Linux.
+
+Installation is as follows:
+
+      ./configure
+      make
+      make install
+
+The build process creates the following shared libraries:
+
+    libwad.so        -  Standalone WAD.  Can be linked with C/C++
+                        programs.
+
+    libwadpy.so      -  Python WAD.  Can be linked to Python extension
+                        modules or imported on its own as 'import libwadpy'
+
+    libwadtcl.so     -  Tcl WAD.  Can be linked to Tcl extension
+                        modules or loaded as 'load libwadtcl.so'.
+
+    libwadpl.so      -  Perl WAD.  Can be linked to Perl extension
+                        modules or loaded as 'libwadpl'.
+
+To install the libraries, simply type 'make install'.  This copies the libraries
+to /usr/local/lib (unless you modify the makefile).
+
+Notes:
+
+   -  The Sun version of WAD has only been tested when compiled with the
+      Sun Workshop C/C++ compilers.   However WAD works with other programs
+      that have been compiled with gcc.  If gcc is installed on your
+      machine, you may want to set the following environment variables
+      before running configure:
+
+           setenv CC cc
+           setenv CXX CC
+           ./configure
+ 
+   -  You may need to modify the Makefile to point to the installed locations
+      of various scripting language libraries if you have installed
+      them in non-traditional locations. 
+
+   -  The Linux version has only been tested with 2.2-12 and 2.2-14 kernels
+      and the RedHat 6.x distribution.  Your mileage may vary.   There
+      may be some compatibility issues related to glibc and other parts
+      of the system as well.
+     
+3. Using WAD
+
+WAD has no functional API nor does it have any command line options so
+it's pretty easy to describe---simply link the appropriate WAD library with
+your C code.  For example:
+
+   % cc blah.c -lwad
+
+Once linked, fatal errors will now produce stack traces. For example:
+
+% ./a.out seg
+starting.
+Segmentation fault.
+#2   0x400571eb in __libc_start_main() in 'libc-start.c', line 90
+#1   0x08048b39 in main(argc=0x2,argv=0xbffffce4) in 'debug.c', line 62
+#0   0x080489b3 in seg_crash(n=0x0) in 'debug.c', line 9
+
+/r0/beazley/Projects/WAD/Wad/debug.c, line 9
+
+      int *a = 0;
+      if (n > 0) seg_crash(n-1);
+ =>   *a = 3;
+      return 1;
+    }
+
+For scripting languages, WAD works in a similar manner--simply link
+your scripting language extension module with the appropriate WAD library
+(wadpy, wadtcl, wadpl).  For example:
+
+   % ld -G $(OBJS) -lwadpy -o pymodule.so
+
+When the scripting module is loaded into the interpreter, WAD should
+automatically initialize.
+
+4. Debugging Modes
+
+Due to WAD's experimental nature, a number of debugging modes can be set
+through the use of environment variables.   These variables control WAD's
+runtime behavior and cause the system to dump debugging information for
+various stages of error recovery.   A lot of this data is pretty ugly and 
+probably only of interest to you if you are trying to debug WAD itself.
+
+WAD_DEBUG_SEGMENT       -  Displays information about the virtual memory
+                           map and mapping of addresses to segments.
+
+WAD_DEBUG_SYMBOL        -  Symbol table mapping.
+
+WAD_DEBUG_OBJECT        -  Loading/Unloading of object files.
+
+WAD_DEBUG_FILE          -  Loading/Unloading of raw files.
+
+WAD_DEBUG_HOLD          -  Freezes WAD before it returns from the signal handler.
+                           Useful if you need to attach a debugger to WAD itself.
+
+WAD_DEBUG_STABS         -  Display stabs data.
+
+WAD_DEBUG_RETURN        -  Display information about WAD return points.
+
+WAD_DEBUG_SYMBOL_SEARCH -  Display all symbols in the symbol table that are
+                           searched.
+
+WAD_DEBUG_UNWIND        -  Display information about stack unwinding.
+
+WAD_DEBUG_SIGNAL        -  Display information about signal handling.
+
+WAD_DEBUG_INIT          -  Print initialization information.
+
+WAD_NOSTACK             -  Do NOT use an alternative signal handling stack.
+                           This may be necessary on certain Linux systems when
+                           threads are being used.
+
+WAD_ONESHOT             -  Disable WAD signal handler after first signal has
+                           been received.
+
+WAD_DEBUG_MEMORY        -  Print information about WAD memory use.
+
+WAD_DEBUG_STRINGS       -  Print information about WAD string manager.
+
+5.  Platform Specific Issues
+
+General:
+
+  -  WAD does not gracefully recover from errors that corrupt the call
+     stack (i.e., buffer overlow).
+
+  -  Errors that destroy the process heap may or may not be recoverable
+     depending on what has been destroyed.
+
+  -  WAD does not currently support 64 bit applications on any platform.
+
+  -  If executables have been stripped, their symbol tables might not
+     have enough information to recover from errors.  Therefore, if you
+     are using Python, Tcl, or Perl from a binary distribution, you
+     may want to rebuild non-stripped versions of these packages yourself.
+
+  -  WAD only works with programs that utilize the ELF32 linking format
+     and stabs debugging data.  Newer formats such as DWARF2 are not
+     supported at this time.
+
+  -  WAD does not correctly report argument values for structures or
+     floating point numbers yet.
+
+  -  Overly aggressive compiler optimization may lead to very strange
+     WAD output.
+
+Solaris:
+
+  -  WAD is extremely slow at collecting debugging information
+     from large applications. 
+
+Linux:
+
+  -  The interaction of threads and signals are particularly problematic
+     on this platform and may cause WAD not to work at all.   Here are
+     some specific thread-based issues that may arise:
+
+     1.  WAD causes the program to crash immediately upon startup. 
+         This appears to be caused by a bug in in the implementation
+         of sigaction() and the initialization of signals.  This 
+         only occurs if WAD is directly linked to an executable
+         using threads.  It does not occur when WAD is dynamically
+         loaded into a threaded application.
+
+     2.  Programs may lock up when an error occurs.  This is sometimes
+         caused by an apparently broken implementation of sigaltstack().
+         One solution to this is to set the following environment
+         variable:
+
+             setenv WAD_NOSTACK
+
+         in which case the WAD signal handler will use the same
+         stack as the thread/process that generates the error.
+
+     3.  WAD just crashes altogether and doesn't seem to do anything.
+         It appears that some versions of Linux threads do *not*
+         pass CPU context information correctly to signal handlers
+         defined in threaded programs.   There is no known fix to
+         this at this time.  Upgrade your system.
+
+  -  WAD does not work if it is compiled as PIC code.  The WAD libraries
+     should be compiled *without* the -fpic option.
+
+  -  WAD has to rely upon a heuristic register recovery scheme when it
+     returns to scripting language interpreters.  It seems to
+     work, but it relies upon a very specific compiler code generation
+     convention for saving registers in function prologues.  It also
+     relies upon the register save conventions described in the Linux
+     Assembly HOWTO.
+
+  -  If you are using WAD with pre-installed binaries for Python, Tcl,
+     and other scripting languages, it may not work correctly due to
+     stripped symbol tables.  Most Linux installs such as Redhat strip
+     symbol tables from executables.  This makes it difficult for WAD
+     to determine context correctly (although it may still work since
+     the dynamic loading symbol table is still available in most cases).
+
+6.  Language specific issues
+
+If WAD is linked with a normal C/C++ program, errors simply produce a stack trace
+that is printed on standard error.
+
+Python:
+
+WAD tries to raise a Python exception and return.  At this time, the exception
+merely contains a traceback string.  However, in future versions, it may be
+possible to access a complete exception object. 
+
+Tcl:
+
+WAD returns a Tcl and places the stack trace into the Tcl variable $errorInfo.
+The wish shell uses this to dump error information.  
+
+Perl:
+
+Perl doesn't seem to have a very well-defined exception handling
+mechanism.  Standard functions tend to just exit.  The WAD handler
+produces a C stack trace and produces a Perl stack trace using some
+code derived from the sigtrap module.
+
+Note: 3/23/01 - Perl support is currently broken.
+
+7. Testing and Examples
+
+The Test directory contains some very simple code for testing WAD.  In the
+most simple form, compile the stand-along test program 'debug' as follows:
+
+% cd Test
+% make
+
+Now, running it:
+
+% debug
+WAD debug program.
+
+Usage: debug type
+   seg        - Fail with an uninitialized pointer.
+   bus        - Fail with a bus error.
+   abort      - Fail with an assertion error.
+   math       - Fail with a math error.
+   heap       - Blow the process heap.
+   overflow   - Buffer overflow on the stack.
+
+% debug seg
+WAD debug program.
+Segmentation fault.
+#2   0x400581eb in __libc_start_main() in 'libc-start.c', line 90
+#1   0x08048b61 in main(argc=0x2,argv=0xbffffc54) in 'debug.c', line 85
+#0   0x080489d0 in seg_crash() in 'debug.c', line 15
+
+/r0/beazley/Projects/WAD/Test/debug.c, line 15
+
+    int seg_crash() {
+      int *a = 0;
+ =>   *a = 3;
+      return 1;
+    }
+
+Additional targets 'make python', 'make tcl', and 'make perl' are also available. 
+The scripts debug.py, debug.tcl, debug.pl can be used to test these extensions.
+
+8.  Documentation
+
+No official documentation exists at this time.  However, details
+of WAD's design and implementation can be found in papers presented
+at the Ninth International Python Conference and the 2000 USENIX
+Technical Conference.  Both papers can be obtained at:
+
+   http://systems.cs.uchicago.edu/wad
+
+
+9. To-Do
+
+If you find WAD to be interesting or useful, there are a variety of
+ways to contribute.  Here is the short to-do list:
+
+    -  Better register management.  Try to implement in a more portable
+       way.   Add some support code for recovering local variables
+       that happen to be stored in registers.
+
+    -  Add heuristic for recovering functions called through an
+       -fomit-frame-pointer compiler optimization scheme.   This
+       can probably be determined by looking at the function preamble
+       machine code.   Then one can back-trace to the calling function
+       and look at it's preamble. 
+
+    -  Continued clean up and modularization of the core.  Many of the
+       internal APIs could be greatly improved.
+
+    -  Support for ELF64 linking format.
+
+    -  Support for DWARF2 debugging data.
+
+    -  Improved support for stack-overflow and heap-corruption.  Although WAD
+       probably won't be able to recover, it still might be able to produce some 
+       informative diagnostics.
+
+    -  Removal of printf() and other high-level library calls which may not
+       operate with a corrupted heap.
+
+    -  Better integration with scripting languages.
+
+    -  Support for new platforms.
+
+    -  Support for new scripting languages.
+
+Please contact me if you are interested in working on any of these projects.
+
+Dave Beazley (beazley@cs.uchicago.edu)
+June 24, 2001
diff --git a/trunk/Tools/WAD/Tcl/Makefile.in b/trunk/Tools/WAD/Tcl/Makefile.in
new file mode 100644
index 0000000..b734a8c
--- /dev/null
+++ b/trunk/Tools/WAD/Tcl/Makefile.in
@@ -0,0 +1,54 @@
+#######################################################################
+# WAD Makefile
+#
+# David Beazley
+# January 1, 2001
+#######################################################################
+
+# These are the files that make up the WAD core
+SRCS = wadtcl.c
+OBJS = wadtcl.o
+INCLUDE = -I../Include -I.  $(SINCLUDE)
+WADOPT     = @WADOPT@
+
+# Location of your Tcl installation
+TCLINCLUDE = @TCLINCLUDE@
+TCLSRCS    = wadtclinit.cxx
+TCLOBJS    = wadtclinit.o
+
+# C Compiler
+CC = @CC@
+CFLAGS = #@CCSHARED@
+
+# C++ Compiler
+CXX = @CXX@
+CXXFLAGS = #@CXXSHARED@
+
+# Linking options
+CLINK = 
+CXXLINK = @CXXLINK@
+
+# Rules for creation of a .o file from .cxx
+.SUFFIXES: .cxx
+.cxx.o:
+	$(CXX) $(CXXFLAGS) $(WADOPT) $(INCLUDE) -c -o $*.o $<
+
+.c.o:
+	$(CC) $(CFLAGS) $(TCLINCLUDE) $(WADOPT) $(INCLUDE) -c -o $*.o $<
+
+tcl: $(OBJS) $(TCLOBJS)
+	$(CXXLINK) $(OBJS) $(TCLOBJS) -o libwadtcl.so -L.. -lwadcore
+	cp libwadtcl.so ..
+
+wc::
+	wc $(SRCS)
+
+semi::
+	@egrep ";" $(SRCS) $(TCLSRCS) | wc
+
+clean::
+	rm -f *.o *.so *~ 
+
+
+
+
diff --git a/trunk/Tools/WAD/Tcl/wadtcl.c b/trunk/Tools/WAD/Tcl/wadtcl.c
new file mode 100644
index 0000000..df68f74
--- /dev/null
+++ b/trunk/Tools/WAD/Tcl/wadtcl.c
@@ -0,0 +1,122 @@
+/* ----------------------------------------------------------------------------- 
+ * wadtcl.c
+ *
+ *     Dynamically loadable Tcl module for wad.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include <tcl.h>
+#include "wad.h"
+#include <signal.h>
+
+static char cvs[] = "$Id$";
+
+/* Handler function */	
+static void handler(int signo, WadFrame *frame, char *ret) {
+  static char message[65536];
+  static char temp[1024];
+  int  len = 0;
+  char *name;
+  WadFrame *f;
+  WadFrame *fline = 0;
+  char *srcstr= 0;
+  Tcl_Interp *interp;
+  int err;
+  char  *type;
+
+  if (!ret) {
+    wad_default_callback(signo, frame, ret);
+    return;
+  }
+
+  strcpy(message,"[ C stack trace ]\n\n");
+  switch(signo) {
+  case SIGSEGV:
+    type = (char*)"Segmentation fault.";
+    break;
+  case SIGBUS:
+    type = (char*)"Bus error.";
+    break;
+  case SIGABRT:
+    type = (char*)"Abort.";
+    break;
+  case SIGFPE:
+    type = (char*)"Floating point exception.";
+    break;
+  default:
+    type = (char*)"Unknown.";
+    break;
+  }
+
+  f = frame;
+  /* Find the last exception frame */
+  while (!f->last) {
+    f= f->next;
+  }
+  /* Now work backwards */
+  f = f->prev;
+  while (f) {
+    strcat(message, f->debug_str);
+    if (f->debug_srcstr) srcstr = f->debug_srcstr;
+    f = f->prev;
+  }
+  if (srcstr) {
+    strcat(message,"\n");
+    strcat(message, srcstr);
+    strcat(message,"\n");
+  }
+
+  if (wad_heap_overflow) {
+    write(2, "WAD: Heap overflow detected.\n", 30);
+    wad_default_callback(signo, frame, ret);
+  }
+
+  /* Note: if the heap is blown, there is a very good chance that this
+  function will not succeed and we'll dump core.  However, the check
+  above should dump a stack trace to stderr just in case we don't make it
+  back. */
+
+  /* Try to get the Tcl interpreter through magic */
+  if (ret) {
+    interp = (Tcl_Interp *) wad_steal_outarg(frame,ret,1,&err);
+    if (err == 0) {
+      Tcl_SetResult(interp,type,TCL_STATIC);
+      Tcl_AddErrorInfo(interp,message);
+    }
+  }
+}
+
+void tclwadinit() {
+  printf("WAD Enabled\n");
+  wad_init();
+  wad_set_callback(handler);
+  wad_set_return("TclExecuteByteCode", TCL_ERROR);
+  wad_set_return("EvalObjv", TCL_ERROR);
+}
+
+int Wad_Init(Tcl_Interp *interp) {
+  return TCL_OK;
+}
+
+int Wadtcl_Init(Tcl_Interp *interp) {
+  return TCL_OK;
+}
diff --git a/trunk/Tools/WAD/Tcl/wadtclinit.cxx b/trunk/Tools/WAD/Tcl/wadtclinit.cxx
new file mode 100644
index 0000000..30c288c
--- /dev/null
+++ b/trunk/Tools/WAD/Tcl/wadtclinit.cxx
@@ -0,0 +1,38 @@
+/* -----------------------------------------------------------------------------
+ * wadtclinit.cxx
+ *
+ *     C++ initializer for Tcl wad.
+ * 
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+static char cvs[] = "$Id$";
+
+extern "C" void tclwadinit();
+
+/* This hack is used to auto-initialize wad regardless of whether we are
+   used as an imported module or as a link-library for another module */
+   
+class wadinitializer {
+public:
+  wadinitializer() {
+    tclwadinit();
+  }
+};
+
+static wadinitializer wi;
diff --git a/trunk/Tools/WAD/Test/Makefile.in b/trunk/Tools/WAD/Test/Makefile.in
new file mode 100644
index 0000000..c6e8082
--- /dev/null
+++ b/trunk/Tools/WAD/Test/Makefile.in
@@ -0,0 +1,44 @@
+#######################################################################
+# WAD Test makefile
+#
+# Build some WAD test programs.
+#######################################################################
+
+CC= @CC@
+CCSHARED = @CCSHARED@
+LDSHARED = @LDSHARED@
+RPATH    = @RPATH@
+
+PYINCLUDE = @PYINCLUDE@
+TCLINCLUDE = @TCLINCLUDE@
+PERLINCLUDE = @PERL5EXT@
+INCLUDE = -I../Include 
+WADLIB = ..
+WADLINK = -L$(WADLIB) $(RPATH)$(WADLIB)
+
+test:
+	$(CC) -g -DNEED_MAIN debug.c $(INCLUDE) $(WADLINK) -lwad -o debug
+
+python: pydebug.c
+	$(CC) $(CCSHARED) -c -g debug.c pydebug.c $(PYINCLUDE)
+	$(LDSHARED) debug.o pydebug.o $(WADLINK) -lwadpy -o debugmodule.so
+
+tcl: tcldebug.c
+	$(CC) $(CCSHARED) -c -g debug.c tcldebug.c $(TCLINCLUDE)
+	$(LDSHARED) debug.o tcldebug.o $(WADLINK) -lwadtcl -o debug.so
+
+perl: pldebug.c
+	$(CC) $(CCSHARED) -c -Dbool=char -g debug.c pldebug.c $(PERLINCLUDE)
+	$(LDSHARED) debug.o pldebug.o $(WADLINK) -lwadpl -o debug.so
+
+pydebug.c:
+	swig -python -o pydebug.c debug.i
+
+tcldebug.c:
+	swig -tcl -o tcldebug.c debug.i
+
+pldebug.c:
+	swig -perl5 -o pldebug.c debug.i
+
+clean:
+	rm -f *.so *.o debug *_wrap*
diff --git a/trunk/Tools/WAD/Test/README b/trunk/Tools/WAD/Test/README
new file mode 100644
index 0000000..6a04a7e
--- /dev/null
+++ b/trunk/Tools/WAD/Test/README
@@ -0,0 +1,5 @@
+Simple test programs for WAD.  This is currently incomplete.
+
+Note: To completely rebuild the Python, Perl, and Tcl tests,
+you need to have SWIG installed (www.swig.org).
+
diff --git a/trunk/Tools/WAD/Test/death.py b/trunk/Tools/WAD/Test/death.py
new file mode 100644
index 0000000..ba1de20
--- /dev/null
+++ b/trunk/Tools/WAD/Test/death.py
@@ -0,0 +1,65 @@
+import debug
+from Tkinter import *
+
+def death_by_segmentation():
+    debug.seg_crash()
+
+def death_by_bus():
+    debug.bus_crash()
+
+def death_by_abort():
+    debug.abort_crash(-1)
+
+def death_by_math():
+    debug.math_crash(37,0)
+
+def death_by_buffer():
+    debug.overflow_crash()
+
+def death(f):
+    ty = f.tvar.get()
+    if ty == 1:
+        death_by_segmentation()
+    elif ty == 2:
+        death_by_abort()  
+    elif ty == 3:
+        death_by_math()
+    elif ty == 4:
+        death_by_bus()
+    elif ty == 5:
+        death_by_buffer()
+
+class death_options(Frame):
+   def __init__(self):
+        Frame.__init__(self)
+        tvar = IntVar()
+        Radiobutton(self,text="Segmentation fault", variable=tvar, value=1).pack(anchor=W)
+        Radiobutton(self,text="Failed assertion", variable=tvar, value=2).pack(anchor=W)
+        Radiobutton(self,text="Math error", variable=tvar, value=3).pack(anchor=W)
+        Radiobutton(self,text="Bus error", variable=tvar, value=4).pack(anchor=W)
+        Radiobutton(self,text="Stack overflow", variable=tvar, value=5).pack(anchor=W)
+        Button(self,text="Die", command=lambda x=self: death(x)).pack(expand=1, fill=BOTH)
+        self.tvar = tvar
+        tvar.set(1)
+
+def death_wizard():
+    root = Tk()
+    l = Label(text="How would you like to die today?")
+    l.pack()
+    death_options().pack()
+    root.title("Death Wizard")
+death_wizard()
+
+#root.mainloop()
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Tools/WAD/Test/death.tcl b/trunk/Tools/WAD/Test/death.tcl
new file mode 100644
index 0000000..e52fa9e
--- /dev/null
+++ b/trunk/Tools/WAD/Test/death.tcl
@@ -0,0 +1,65 @@
+load ./debug[info sharedlibextension]
+
+proc death_by_segmentation { } {
+    seg_crash
+}
+
+proc death_by_bus { } {
+    bus_crash
+}
+
+proc death_by_abort { } {
+    abort_crash -1
+}
+
+proc death_by_math { } {
+    math_crash 37 0
+}
+
+proc death_by_buffer { } {
+    overflow_crash
+}
+
+set method 1
+proc death {} {
+    global method
+    if { $method == 1 } {
+        death_by_segmentation
+    }
+    if { $method == 2 } {
+        death_by_abort
+    }
+    if { $method == 3 } {
+        death_by_math
+    }
+    if { $method == 4 } {
+        death_by_bus
+    }
+    if { $method == 5 } {
+        death_by_buffer
+    }
+}
+
+label .l -text "How would you like to die today?"
+pack .l
+
+radiobutton .r1 -text "Segmentation fault" -variable method -value 1
+pack .r1 -anchor w
+
+radiobutton .r2 -text "Failed assertion" -variable method -value 2
+pack .r2 -anchor w
+
+radiobutton .r3 -text "Math error" -variable method -value 3
+pack .r3 -anchor w
+
+radiobutton .r4 -text "Bus error" -variable method -value 4
+pack .r4 -anchor w
+
+radiobutton .r5 -text "Stack overflow" -variable method -value 5
+pack .r5 -anchor w 
+
+button .b -text "Die" -command death 
+pack .b -fill both -expand 1
+
+wm title . "Death Wizard"
+
diff --git a/trunk/Tools/WAD/Test/debug.c b/trunk/Tools/WAD/Test/debug.c
new file mode 100644
index 0000000..b95b539
--- /dev/null
+++ b/trunk/Tools/WAD/Test/debug.c
@@ -0,0 +1,119 @@
+/* -----------------------------------------------------------------------------
+ * debug.c
+ * 
+ * This file contains a variety of different programming errors to test with
+ * WAD.
+ * ----------------------------------------------------------------------------- */
+
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+typedef double Real;
+typedef Real Float;
+
+char buffer[256];
+
+/* A simple segmentation fault on an uninitialized pointer */
+int seg_crash() {
+  int *a = 0;
+  *a = 3;
+  return 1;
+}
+
+/* Blow the process heap */
+
+int blowheap_crash() {
+  int i;
+  int *a = (int *) malloc(sizeof(int));
+
+  for (i = 0;; i++) {
+    a[i] = i;
+  }
+}
+
+/* Buffer overflow crash on the stack */
+int overflow_crash() {
+  int a[512];
+  int i;
+
+  for (i = 0; i < 1024; i++) {
+    a[i] = i;
+  }
+}
+
+/* A simple bus error.  */
+int bus_crash() {
+  double *a = (double *) (buffer+1);
+  *a = 3.4;
+  return 1;
+}
+
+/* An assertion */
+int abort_crash(int n) {
+  assert(n > 0);
+  return 1;
+}
+
+/* A math error (maybe) */
+int math_crash(int x, int y) {
+  return x/y;
+}
+
+void type_crash(int a, short b, char c, unsigned long d, float f, double g) {
+  int la;
+  short lb;
+  char  lc;
+  long  ld;
+  float lf;
+  double lg;
+  long   ll;
+
+  la = a;
+  lb = b;
+  lc = c;
+  ld = ld;
+  lf = lf;
+  lg = lg;
+  assert(0);
+}
+
+#ifdef NEED_MAIN
+
+static const char *usage="\n\
+Usage: debug type\n\
+   seg        - Fail with an uninitialized pointer.\n\
+   bus        - Fail with a bus error.\n\
+   abort      - Fail with an assertion error.\n\
+   math       - Fail with a math error.\n\
+   heap       - Blow the process heap.\n\
+   overflow   - Buffer overflow on the stack.\n\
+";
+
+int main(int argc, char **argv) {
+  int n;
+
+  printf("WAD debug program.\n");
+
+  if (argc < 2) {
+    printf("%s\n", usage);
+    exit(0);
+  }
+  if (strcmp(argv[1],"abort") == 0) {
+    abort_crash(-4);
+  } else if (strcmp(argv[1],"seg") ==0) {
+    seg_crash();
+  } else if (strcmp(argv[1],"bus") == 0) {
+    bus_crash();
+  } else if (strcmp(argv[1],"math") == 0) {
+    math_crash(3,0);
+  } else if (strcmp(argv[1],"heap") == 0) {
+    blowheap_crash();
+  } else if (strcmp(argv[1],"overflow") == 0) {
+    overflow_crash();
+  } else if (strcmp(argv[1],"type") == 0) {
+    type_crash(0,2,'x',420000,3.14159,2.1828);
+  }
+}
+
+#endif
diff --git a/trunk/Tools/WAD/Test/debug.i b/trunk/Tools/WAD/Test/debug.i
new file mode 100644
index 0000000..1823161
--- /dev/null
+++ b/trunk/Tools/WAD/Test/debug.i
@@ -0,0 +1,9 @@
+%module debug
+
+extern int seg_crash();
+extern int bus_crash();
+extern int blowheap_crash();
+extern int overflow_crash();
+extern int abort_crash(int);
+extern int math_crash(int x, int y);
+extern void type_crash(int, short, char, unsigned long, float, double);
diff --git a/trunk/Tools/WAD/Test/debug.py b/trunk/Tools/WAD/Test/debug.py
new file mode 100644
index 0000000..07d9453
--- /dev/null
+++ b/trunk/Tools/WAD/Test/debug.py
@@ -0,0 +1,35 @@
+# WAD debugging module for python
+
+import debug
+import sys
+
+try:
+   name = sys.argv[1]
+except:
+   print """
+usage: debug.py test
+
+     seg        - Segmentation fault due to uninitialized pointer.
+     bus        - Bus error.
+     abort      - Failed assertion.
+     math       - Math error.
+     heap       - Blown heap.
+     overflow   - Buffer overflow.
+"""
+   sys.exit(1)
+
+if name == "seg":
+    debug.seg_crash()
+elif name == "bus":
+    debug.bus_crash()
+elif name == "abort":
+    debug.abort_crash(-2)
+elif name == "math":
+    debug.math_crash(3,0)
+elif name == "heap":
+    debug.blowheap_crash()
+elif name == "overflow":
+    debug.overflow_crash()
+elif name == "type":
+    debug.type_crash(37,42, 'x', 420000, 3.14159, 2.1828)
+
diff --git a/trunk/Tools/WAD/Test/debug.tcl b/trunk/Tools/WAD/Test/debug.tcl
new file mode 100644
index 0000000..ab5cd16
--- /dev/null
+++ b/trunk/Tools/WAD/Test/debug.tcl
@@ -0,0 +1,25 @@
+# WAD debugging module for Tcl.  This should be executed with wish
+
+load ./debug[info sharedlibextension]
+
+message .t -text "This program tests various program faults. Note: Not all of these errors can be gracefully handled."
+
+button .b1 -text "Segmentation fault" -command "seg_crash" 
+button .b2 -text "Bus error (not on Linux)" -command "bus_crash"
+button .b3 -text "Abort" -command "abort_crash -1"
+button .b4 -text "Math" -command "math_crash 3 0"
+button .b5 -text "Blow Heap" -command "blowheap_crash"
+button .b6 -text "Buffer overflow" -command "overflow_crash"
+button .q -text "Quit" -command "exit"
+
+pack .t -fill x
+
+pack .b1 -fill x
+pack .b2 -fill x
+pack .b3 -fill x
+pack .b4 -fill x
+pack .b5 -fill x
+pack .b6 -fill x
+pack .q -fill x
+
+
diff --git a/trunk/Tools/WAD/Test/foo.py b/trunk/Tools/WAD/Test/foo.py
new file mode 100644
index 0000000..dee2e7d
--- /dev/null
+++ b/trunk/Tools/WAD/Test/foo.py
@@ -0,0 +1,31 @@
+import debug
+
+def foo():
+    debug.abort_crash(-1)
+
+def bar():
+    foo()
+
+def spam():
+    bar()
+
+from Tkinter import *
+
+root = Tk()
+
+button = Button(text="Press me", command=spam)
+button.pack()
+
+#root.mainloop()
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/trunk/Tools/WAD/Test/wadpm.py b/trunk/Tools/WAD/Test/wadpm.py
new file mode 100644
index 0000000..8a63312
--- /dev/null
+++ b/trunk/Tools/WAD/Test/wadpm.py
@@ -0,0 +1,49 @@
+# -----------------------------------------------------------------------------
+# Wad port-mortem debugger
+#
+# David Beazley
+# -----------------------------------------------------------------------------
+
+import sys
+
+_last_exc = None
+_last_level = 0
+
+print "WAD port-mortem"
+
+class where_impl:
+    def __repr__(self):
+        global _last_exc, _last_level
+	if sys.last_value:
+	     if sys.last_value[0] != _last_exc:
+		_last_exc = sys.last_value[0]
+                _last_level = 0
+        else:
+             raise RuntimeError,"No pending error."
+        print repr(_last_exc)
+        return ""
+
+where = where_impl()
+
+class up_impl:
+    def __repr__(self):
+        global _last_exc, _last_level
+	if not _last_exc:
+	     return ""
+	_last_level += 1
+	print repr(_last_exc[_last_level])
+        return ""
+
+up = up_impl()
+
+class down_impl:
+    def __repr__(self):
+        global _last_exc, _last_level
+	if not _last_exc:
+	     return ""
+	_last_level -= 1
+	print repr(_last_exc[_last_level])
+        return ""
+
+down = down_impl()
+
diff --git a/trunk/Tools/WAD/Test/wpm.py b/trunk/Tools/WAD/Test/wpm.py
new file mode 100644
index 0000000..f849e31
--- /dev/null
+++ b/trunk/Tools/WAD/Test/wpm.py
@@ -0,0 +1,280 @@
+# -----------------------------------------------------------------------------
+# WAD Post-mortem debugger
+#
+# This program can be used to walk up and down the call stack of a mixed
+# Python-C program.   The following commands are supported:
+# 
+#     w          -  A stack traceback 
+#     u          -  Go up the call stack
+#     d          -  Go down the call stack
+#     e          -  Edit a file
+#     c          -  Clear the debugger.
+#
+# David Beazley
+# Copyright (C) 2001
+# University of Chicago
+# All Rights Reserved
+# -----------------------------------------------------------------------------
+
+import sys
+import os
+import traceback
+import types
+import linecache
+
+
+print "**************************************************"
+print "*                WAD Debugger                    *"
+print "**************************************************"
+
+# Save a local copy of the last exception and value objects from sys
+
+_last_type = sys.last_type
+_last_value = sys.last_value
+_last_traceback = sys.last_traceback
+_last_level = 0
+
+_cstack = None                   # Stack of C-only code
+_pystack = None                  # Stack of Python only code
+_combined_stack = None           # Combined C-python stack
+
+_allmode = 0                     # Show entire C stack
+
+# Generalized object for holding stack frames
+
+class wad_frame:
+    def __init__(self,frame, n = 0):
+	if isinstance(frame,types.TupleType):
+               # A Python traceback object
+               self.__FILE__ = frame[0]
+               self.__LINE__ = frame[1]
+               self.__NAME__ = frame[2]
+               self.__ARGSTR__ = frame[3]
+               self.__FRAMENO__ = n
+               # Make the debugging string
+               self.__DEBUGSTR__ = "#%-3d [ Python ] in %s in %s, line %d" % (self.__FRAMENO__, self.__ARGSTR__, self.__FILE__, self.__LINE__)
+               
+               # Try to get source data
+               self.__SOURCE__ = "%s, Line %d\n\n" % (self.__FILE__, self.__LINE__)
+               for i in range(self.__LINE__-2,self.__LINE__+3):
+                     l = linecache.getline(self.__FILE__,i)
+                     if not l: l = '\n'
+                     if (i == self.__LINE__):
+                        self.__SOURCE__ += " => "
+                     else:
+                        self.__SOURCE__ += "    "
+                     self.__SOURCE__ += l
+               self.__frame__ = None
+                
+        elif hasattr(frame,"__WAD__"):
+               # A WAD traceback object
+               self.__FILE__ = frame.__FILE__
+               self.__LINE__ = frame.__LINE__
+               self.__NAME__ = frame.__NAME__
+               self.__DEBUGSTR__ = frame.__WHERE__
+               self.__SOURCE__ = frame.__SOURCE__
+               self.__frame__ = frame
+
+    def __str__(self):
+               return self.__DEBUGSTR__.strip()
+
+    def __getattr__(self,name):
+        if self.__frame__:
+              return getattr(self.__frame__,name)
+        raise AttributeError
+
+    def output(self):
+        print self
+        if self.__SOURCE__:
+               print "\n%s" % (self.__SOURCE__)
+
+
+def wad_build_info():
+    global _last_type,_last_value, _last_traceback, _cstack, _combined_stack,_pystack
+
+    _last_type = None
+    _last_value = None
+    _last_traceback = None
+    _cstack = None
+    _combined_stack = []
+
+    # Check to see if any exception is defined
+    if not sys.last_type:
+           print "No exception has occurred."
+           return
+     
+    # Save a copy of previous exception
+    _last_type = sys.last_type
+    _last_value = sys.last_value
+    _last_traceback = sys.last_traceback
+    _last_level = 0
+
+    start_frame = 0
+    # Test to see what kind of object it is
+    if issubclass(_last_type,StandardError):
+          # Python exception
+          print "Python exception"
+    elif hasattr(_last_value[0],"__WAD__"):
+          # A wad exception frame object
+          w = sys.last_value[0]
+          i = 0
+          _cstack = []
+          while not w[i].__LAST__:
+                start_frame += 1
+                wf = wad_frame(w[i])
+                _cstack.append(wf)
+                i = i + 1
+
+#          wf = wad_frame(w[i])
+#          _cstack.append(wf)
+#          start_frame += 1
+
+          # Build the rest of the c stack
+          _combined_stack = _cstack[:]
+          while i < len(w):
+               wf = wad_frame(w[i])
+               _cstack.append(wf)
+               i = i + 1
+
+    else:
+          print "Unknown error"
+
+    # Build the Python call stack
+    _pystack = []
+    t = sys.last_traceback
+    tp = None
+    while hasattr(t,"tb_frame"):
+          tp = t
+          t = t.tb_next
+
+    fr = traceback.extract_stack(tp.tb_frame)	
+    for i in range(len(fr),0,-1):
+          f = wad_frame(fr[i-1], start_frame)
+          start_frame += 1
+          _pystack.append(f)
+    _combined_stack.extend(_pystack)
+
+
+wad_build_info()
+
+class where_impl:
+    def __init__(self):
+	self.all = 0;
+        self.cstack = 0
+
+    def __repr__(self):
+        global _combined_stack, _cstack, _last_level
+        if (self.cstack):
+             stack = _cstack
+        else:
+             stack = _combined_stack
+
+	if not stack:
+             print "No current exception."
+             return ""
+
+        last_source = None
+        for i in range(len(stack),0,-1):
+             f = stack[i-1]
+             print f
+             if (f.__SOURCE__):
+                 last_source = f.__SOURCE__
+                 _last_level = i-1
+        if last_source: print "\n%s" % last_source
+        return ""
+
+    def __getitem__(self,n):
+        global _last_level, _cstack, _combined_stack
+        if (self.cstack):
+              stack = _cstack
+        else:
+              stack = _combined_stack
+        _last_level = n
+        stack[_last_level].output()
+	return None
+
+    def __len__(self):
+        return len(frame)
+
+
+where = where_impl()
+w = where
+
+class up_impl:
+    def __repr__(self):
+        global _last_level, _combined_stack, _cstack
+        if where.cstack:
+             stack = _cstack
+        else:
+             stack = _combined_stack
+
+	if not stack:
+	     return ""
+	_last_level += 1
+        stack[_last_level].output()
+        return ""
+
+up = up_impl()
+u = up
+
+class down_impl:
+    def __repr__(self):
+        global _last_level, _combined_stack, _cstack
+        if where.cstack:
+             stack = _cstack
+        else:
+             stack = _combined_stack
+
+	if not stack:
+	     return ""
+	_last_level -= 1
+        stack[_last_level].output()
+        return ""
+
+down = down_impl()
+d = down
+
+class clear_impl:
+    def __repr__(self):
+	global _last_exc, _last_level, frame
+        _last_exc = None
+        frame = None
+
+clear = clear_impl()
+c = clear
+
+class edit_impl:
+    def __repr__(self):
+        global _last_level, _combined_stack, _cstack
+        if where.cstack:
+             stack = _cstack
+        else:
+             stack = _combined_stack
+
+	if not stack:
+	     return ""
+	f = stack[_last_level]
+        e = os.getenv("EDITOR","vi")
+	if f.__FILE__:
+	     os.system("%s +%d %s" % (e,f.__LINE__,f.__FILE__))
+        return ""
+
+edit = edit_impl()
+e = edit
+
+class var_impl:
+    def __getattr__(self,name):
+        if (w.cstack):
+             stack = _cstack
+        else:
+             stack = _combined_stack
+	
+        return getattr(stack[_last_level],name)
+
+
+v = var_impl()
+
+
+repr(w)
+
+
diff --git a/trunk/Tools/WAD/Wad/Makefile.in b/trunk/Tools/WAD/Wad/Makefile.in
new file mode 100644
index 0000000..b933dfa
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/Makefile.in
@@ -0,0 +1,73 @@
+#######################################################################
+# WAD Makefile
+#
+# David Beazley
+# January 1, 2001
+#######################################################################
+
+# These are the files that make up the WAD core
+WADSRCS = string.c vars.c io.c memory.c return.c default.c stack.c stab.c elf.c object.c init.c segment.c signal.c
+WADOBJS = string.o vars.o io.o memory.o return.o default.o stack.o stab.o elf.o object.o signal.o segment.o init.o
+INCLUDE = -I../Include -I.  $(SINCLUDE)
+WADOPT     = @WADOPT@
+
+
+# Location of your Perl installation
+PERLINCLUDE = @PERL5EXT@
+PERLSRCS   = wadpl.cxx
+PERLOBJS   = wadpl.o
+
+# C Compiler
+CC = @CC@
+CFLAGS = #@CCSHARED@
+
+# C++ Compiler
+CXX = @CXX@
+CXXFLAGS = #@CXXSHARED@
+
+# Linking options
+CLINK = 
+CXXLINK = @CXXLINK@
+
+# AR
+AR = @AR@
+
+# Rules for creation of a .o file from .cxx
+.SUFFIXES: .cxx
+.cxx.o:
+	$(CXX) $(CXXFLAGS) $(WADOPT) $(INCLUDE) -c -o $*.o $<
+
+.c.o:
+	$(CC) $(CFLAGS) $(WADOPT) $(INCLUDE) -c -o $*.o $<
+
+wad:    $(WADOBJS) main.o
+	$(CXXLINK) $(WADOBJS) main.o -o libwad.so 
+	$(AR) cr libwadcore.a $(WADOBJS)
+	cp libwad.so ..
+	cp libwadcore.a ..
+
+perl: wad_perl_handler.c $(WADOBJS) $(PERLOBJS)
+	$(CXXLINK) $(WADOBJS) $(PERLOBJS) -o libwadpl.so
+	cp libwadpl.so ..
+
+wad_perl_handler.c:
+	python makehandler.py
+
+debug::
+	cc -g debug.c $(INCLUDE) -L. -R. -lwad
+
+plus::
+	CC -g debug.cxx $(INCLUDE) -L. -R. -lwad
+
+wc::
+	wc $(SRCS)
+
+semi::
+	@egrep ";" $(WADSRCS) plat/*.c | wc
+
+clean::
+	rm -f *.o *.so *~ 
+
+
+
+
diff --git a/trunk/Tools/WAD/Wad/debug.c b/trunk/Tools/WAD/Wad/debug.c
new file mode 100644
index 0000000..fcdb87a
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/debug.c
@@ -0,0 +1,98 @@
+#include <stdio.h>
+#include <string.h>
+#include "wad.h"
+#include <assert.h>
+
+typedef struct Foo {
+  double a;
+  double b;
+  float c;
+} Foo;
+
+static int type_crash(int n, short m, char c, double x, float y, Foo f, void *ptr) {
+  int *a = 0;
+  *a = 3;
+  return 1;
+}
+static int seg_crash(int n, double x,
+		     float y) {
+  int *a = 0;
+  if (n > 0) seg_crash(n-1,x,y);
+  *a = 3;
+  return 1;
+}
+
+int bus_crash(int n) {
+  int b;
+  int *a = &b;
+  a = (int *) ((int) a | 0x1);
+  if (n > 0) bus_crash(n-1);
+  *a = 3;
+  printf("well, well, well.\n");
+  return 1;
+}
+
+int abort_crash(int n) {
+  assert(n > 0);
+  abort_crash(n-1);
+  return 1;
+}
+
+double double_crash(double a, double b) {
+  double *c;
+  *c = a+b;
+  return *c;
+}
+
+int math_crash(int x, int y) {
+  return x/y;
+}
+
+int call_func(int n, int (*f)(int)) {
+
+  int ret;
+  ret = (*f)(n);
+  if (ret <= 0) {
+    printf("An error occurred!\n");
+  }
+  return 0;
+}
+
+static int multi(char a, short b, int c, double d) {
+  a = 'x';
+  b = 15236;
+  c = 12345678;
+  d = 3.14159;
+  return c;
+}
+
+static int test(int x, int (*f)(int)) {
+  return (*f)(-x);
+}
+
+int main(int argc, char **argv) {
+  int n;
+  int (*f)(int);
+  Foo foo = { 3.14, 28.18, 1.0 };
+
+  printf("starting.\n");
+  
+  if (strcmp(argv[1],"abort") == 0) {
+    abort_crash(0);
+  } else if (strcmp(argv[1],"seg") ==0) {
+    seg_crash(0,1,2);
+  } else if (strcmp(argv[1],"bus") == 0) {
+    bus_crash(0);
+  } else if (strcmp(argv[1],"ret") == 0) {
+    call_func(4,abort_crash);
+  } else if (strcmp(argv[1],"test") == 0) {
+    test(-1000,abort_crash);
+  } else if (strcmp(argv[1],"double") == 0) {
+    double_crash(3.14159,2.1828);
+  } else if (strcmp(argv[1],"math") == 0) {
+    math_crash(3,0);
+  } else if (strcmp(argv[1],"type") == 0) {
+    type_crash(34,42,17, 3.14159, 2.1828, foo, &foo);
+  }
+  multi(3,5,10,3.14);
+}
diff --git a/trunk/Tools/WAD/Wad/default.c b/trunk/Tools/WAD/Wad/default.c
new file mode 100644
index 0000000..fc72a9e
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/default.c
@@ -0,0 +1,311 @@
+/* ----------------------------------------------------------------------------- 
+ * default.c
+ *
+ *     Default signal handler.  Just prints a stack trace and returns.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+#include <sys/mman.h>
+
+
+/* This function tries to produce some kind of sensible argument 
+   string for a stack frame.  If no debugging information is available,
+   we'll just dump the %i0-%i5 registers in hex.  If debugging information
+   is available, we'll try to do something a little more sensible */
+ 
+char *wad_arg_string(WadFrame *frame) {
+  static char str[1024];
+  WadLocal *wp;
+  long    *stack;
+  long    *nextstack;
+  long    *prevstack;
+  int     i;
+  WadFrame *nf;
+  WadFrame *pf;
+
+  nf = frame->next;
+  if (nf) 
+    nextstack = (long *) nf->stack;
+  else
+    nextstack = 0;
+
+  pf = frame->prev;
+  if (pf)
+    prevstack = (long *) pf->stack;
+  else
+    prevstack = 0;
+
+  str[0] = 0;
+  stack = (long *) frame->stack;
+
+
+#ifdef WAD_LINUX
+  if (!nf) {
+    return "";
+  }
+#endif
+
+  if ((frame->debug_nargs < 0) || (0)){
+    /* No argument information is available. If we are on SPARC, we'll dump
+       the %in registers since these usually hold input parameters.  On
+       Linux, we do nothing */
+    
+#ifdef WAD_SOLARIS
+    for (i = 0; i < 6; i++) {
+      wad_strcat(str,"0x");
+      wad_strcat(str,wad_format_hex((unsigned long) stack[8+i],0));
+      if (i < 5)
+	wad_strcat(str,",");
+    }
+#endif
+  } else {
+    /* We were able to get some argument information out the debugging table */
+    wp = frame->debug_args;
+    for (i = 0; i < frame->debug_nargs; i++, wp = wp->next) {
+      wad_strcat(str,wp->name);
+      wad_strcat(str,"=");
+      wad_strcat(str,wad_format_var(wp));
+      if (i < (frame->debug_nargs-1)) wad_strcat(str,",");
+    }
+  }
+  return str;
+
+}
+
+char *wad_strip_dir(char *name) {
+  char *c;
+  /*  printf("strip: '%s'\n", name); */
+  c = name + strlen(name);
+  while (c != name) {
+    if (*c == '/') {
+      c++;
+      return c;
+    }
+    c--;
+  }
+  return name;
+}
+
+
+
+static char *src_file = 0;
+static int   src_len = 0;
+static char  src_path[1024] = "";
+
+/* Opens up a source file and tries to locate a specific line number */
+
+char *wad_load_source(char *path, int line) {
+  int fd;
+  char *c;
+  char *start;
+  int   n;
+
+  if (strcmp(src_path,path)) {
+    if (src_file) {
+      munmap(src_file, src_len);
+      src_file = 0;
+      src_len = 0;
+    }
+    fd = open(path, O_RDONLY);
+    if (fd < 0) return 0;
+    src_len = lseek(fd, 0, SEEK_END);
+    lseek(fd,0,SEEK_SET);
+    src_file = (char *)mmap(NULL,src_len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
+    if (src_file == MAP_FAILED) {
+      close(fd);
+      return 0;
+    }
+    close(fd);
+    wad_strcpy(src_path,path);
+  } 
+  n = 0;
+  start = src_file;
+  c = src_file;
+  while (n < src_len) {
+    if (*c == '\n') {
+      line--;
+      if (line == 0) {
+	return start;
+      }
+      start = c+1;
+    }
+    c++;
+    n++;
+  }
+  return 0;
+}
+
+void wad_release_source() {
+  if (src_file) {
+    munmap(src_file,src_len);
+    src_file = 0;
+    src_len = 0;
+    src_path[0] = 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_debug_src_code(WadFrame *f)
+ *
+ * Get source code for a frame 
+ * ----------------------------------------------------------------------------- */
+
+char *wad_debug_src_string(WadFrame *f, int window) {
+  static char temp[16384];
+
+  if (f->loc_srcfile && strlen(f->loc_srcfile) && (f->loc_line > 0)) {
+    char *line, *c;
+    int   i;
+    int   first, last;
+    first = f->loc_line - window;
+    last  = f->loc_line + window;
+    if (first < 1) first = 1;
+    line = wad_load_source(f->loc_srcfile,first);
+    if (line) {
+      wad_strcpy(temp,f->loc_srcfile);
+      wad_strcat(temp,", line ");
+      wad_strcat(temp,wad_format_signed(f->loc_line,-1));
+      wad_strcat(temp,"\n\n");
+      for (i = first; i <= last; i++) {
+	if (i == f->loc_line) wad_strcat(temp," => ");
+	else                  wad_strcat(temp,"    ");
+	c = strchr(line,'\n');
+	if (c) {
+	  *c = 0;
+	  wad_strcat(temp,line);
+	  wad_strcat(temp,"\n");
+	  *c = '\n';
+	} else {
+	  wad_strcat(temp,line);
+	  wad_strcat(temp,"\n");
+	  break;
+	}
+	line = c+1;
+      }
+      f->debug_srcstr = wad_strdup(temp);
+      return f->debug_srcstr;
+    }
+  }
+  f->debug_srcstr = 0;
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_debug_make_strings(WadFrame *f)
+ *
+ * This function walks the stack trace and tries to generate a debugging string
+ * ----------------------------------------------------------------------------- */
+
+void 
+wad_debug_make_strings(WadFrame *f) {
+  static char msg[16384];
+  while (f) {
+    wad_strcpy(msg,"#");
+    wad_strcat(msg,wad_format_signed(f->frameno,3));
+    wad_strcat(msg," 0x");
+    wad_strcat(msg,wad_format_hex(f->pc,1));
+    wad_strcat(msg," in ");
+    wad_strcat(msg, f->sym_name ? f->sym_name : "?");
+    wad_strcat(msg,"(");
+    wad_strcat(msg,wad_arg_string(f));
+    wad_strcat(msg,")");
+    if (f->loc_srcfile && strlen(f->loc_srcfile)) {
+      wad_strcat(msg," in '");
+      wad_strcat(msg, wad_strip_dir(f->loc_srcfile));
+      wad_strcat(msg,"'");
+      if (f->loc_line > 0) {
+	wad_strcat(msg,", line ");
+	wad_strcat(msg,wad_format_signed(f->loc_line,-1));
+	/* Try to locate the source file */
+	wad_debug_src_string(f, WAD_SRC_WINDOW);
+      }
+    } else {
+      if (f->loc_objfile && strlen(f->loc_objfile)) {
+	wad_strcat(msg," from '");
+	wad_strcat(msg, wad_strip_dir(f->loc_objfile));
+	wad_strcat(msg,"'");
+      }
+    }
+    wad_strcat(msg,"\n");
+    f->debug_str = wad_strdup(msg);
+    f = f->next;
+  }
+}
+
+/* Dump trace to a file */
+void wad_dump_trace(int fd, int signo, WadFrame *f, char *ret) {
+  static char buffer[128];
+  char  *srcstr = 0;
+
+  switch(signo) {
+  case SIGSEGV:
+    write(fd,"WAD: Segmentation fault.\n", 25);
+    break;
+  case SIGBUS:
+    write(fd,"WAD: Bus error.\n",17);
+    break;
+  case SIGABRT:
+    write(fd,"WAD: Abort.\n",12);
+    break;
+  case SIGFPE:
+    write(fd,"WAD: Floating point exception.\n", 31);
+    break;
+  case SIGILL:
+    write(fd,"WAD: Illegal instruction.\n", 26);
+    break;
+  default:
+    sprintf(buffer,"WAD: Signal %d\n", signo);
+    write(fd,buffer,strlen(buffer));
+    break;
+  }
+  /* Find the last exception frame */
+
+  while (f && !(f->last)) {
+    f = f->next;
+  }
+
+  while (f) {
+    write(fd,f->debug_str,strlen(f->debug_str));
+    if (f->debug_srcstr) {
+      srcstr = f->debug_srcstr;
+    }
+    f = f->prev;
+  }
+  if (srcstr) {
+    write(fd,"\n",1);
+    write(fd,srcstr,strlen(srcstr));
+    write(fd,"\n",1);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * Default callback
+ * ----------------------------------------------------------------------------- */
+
+void wad_default_callback(int signo, WadFrame *f, char *ret) {
+  wad_dump_trace(2,signo,f,ret);
+}
+
diff --git a/trunk/Tools/WAD/Wad/demangle.c b/trunk/Tools/WAD/Wad/demangle.c
new file mode 100644
index 0000000..6b8b541
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/demangle.c
@@ -0,0 +1,36 @@
+/* ----------------------------------------------------------------------------- 
+ * demangle.c
+ *
+ *     This file performs C++ partial name demangling to the extent that it 
+ *     seems reasonable.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+char *wad_cplus_demangle(WadSymbol *ws) {
+  static char buffer[4096];
+  strcpy(buffer,ws->name);
+  return buffer;
+}
diff --git a/trunk/Tools/WAD/Wad/elf.c b/trunk/Tools/WAD/Wad/elf.c
new file mode 100644
index 0000000..5a2947b
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/elf.c
@@ -0,0 +1,428 @@
+/* ----------------------------------------------------------------------------- 
+ * elf.c
+ *
+ *     ELF file management. This file contains functions for accessing ELF
+ *     file data from a raw memory mapped ELF file (as performed by the
+ *     functions in object.c).
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+#ifdef WAD_SOLARIS
+#include <sys/elf.h>
+#endif
+#ifdef WAD_LINUX
+#include <elf.h>
+#endif
+
+/* --- What's needed here (high level interface) :
+     - Mapping of addresses to symbols
+     - Mapping of symbols to file+line
+*/
+
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_check()
+ *
+ * Checks to see if an object file is an ELF file. Returns 1 on success and 
+ * changes the type flag of wo to indicate the type of ELF file.
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_elf_check(WadObjectFile *wo) {
+  if (strncmp((char *)wo->ptr,ELFMAG, SELFMAG) != 0)
+    return 0;
+  
+  /* Probably need to put some kind of 32/64 bit check here */
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_phdrcnt()
+ * 
+ * Return number of entries in the ELF program header section
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_elf_phdrcnt(WadObjectFile *wo) {
+  Elf32_Ehdr *eh;
+  
+  eh = (Elf32_Ehdr *) wo->ptr;
+  return eh->e_phnum;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_phdrpos()
+ *
+ * Return the location of the ELF program header.
+ * ----------------------------------------------------------------------------- */
+
+void *
+wad_elf_phdrpos(WadObjectFile *wo) {
+  Elf32_Ehdr *eh;
+  char *c;
+  eh = (Elf32_Ehdr *) wo->ptr;
+  c = (char *) wo->ptr;
+  return (void *) (c+eh->e_phoff);
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_shdrcnt()
+ * 
+ * Return number of entries in the ELF section header
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_elf_shdrcnt(WadObjectFile *wo) {
+  Elf32_Ehdr *eh;
+  
+  eh = (Elf32_Ehdr *) wo->ptr;
+  return eh->e_shnum;
+}
+
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_shdrpos()
+ *
+ * Return the location of the section headers
+ * ----------------------------------------------------------------------------- */
+
+void *
+wad_elf_shdrpos(WadObjectFile *wo) {
+  Elf32_Ehdr *eh;
+  char *c;
+  eh = (Elf32_Ehdr *) wo->ptr;
+  c = (char *) wo->ptr;
+  return (void *) (c+eh->e_shoff);
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_section_header()
+ *
+ * Get a specific section number
+ * ----------------------------------------------------------------------------- */
+
+void *wad_elf_section_header(WadObjectFile *wo, int sn) {
+  Elf32_Ehdr *eh;
+  char  *r;
+
+  eh = (Elf32_Ehdr *) wo->ptr;
+  if ((sn < 0) || (sn >= eh->e_shnum)) return 0;
+  
+  r = (char *) wad_elf_shdrpos(wo) + (sn*eh->e_shentsize);
+  return (void *) r;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_section_data()
+ *
+ * Get section data
+ * ----------------------------------------------------------------------------- */
+
+void *wad_elf_section_data(WadObjectFile *wo, int sn) {
+  Elf32_Shdr *sh;
+  char *r;
+
+  sh = (Elf32_Shdr *) wad_elf_section_header(wo,sn);
+  if (!sh) return 0;
+  
+  r = ((char *) wo->ptr) + sh->sh_offset;
+  return r;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_section_size()
+ * Return section size
+ * ----------------------------------------------------------------------------- */
+
+int wad_elf_section_size(WadObjectFile *wo, int sn) {
+  Elf32_Shdr *sh;
+
+  sh = (Elf32_Shdr *) wad_elf_section_header(wo,sn);
+  if (!sh) return -1;
+  return sh->sh_size;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_section_name()
+ *
+ * Returns the name of an ELF section 
+ * ----------------------------------------------------------------------------- */
+
+char *wad_elf_section_name(WadObjectFile *wo, int sn) {
+  Elf32_Ehdr *eh;
+  Elf32_Shdr *sh;
+  char    *sectionstr;
+
+  eh = (Elf32_Ehdr *) wo->ptr;
+
+  /* Get the string table */
+  sectionstr = (char *) wad_elf_section_data(wo,eh->e_shstrndx);
+  if (!sectionstr) {
+    return 0;
+  }
+
+  /* Get the section header for the section */
+  sh = (Elf32_Shdr *) wad_elf_section_header(wo,sn);
+  if (!sh) return 0;
+  return sectionstr + sh->sh_name;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_section_byname()
+ *
+ * Get section data given a section name
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_elf_section_byname(WadObjectFile *wo, char *name) {
+  int i;
+  char *sn;
+  int n;
+
+  n = wad_elf_shdrcnt(wo);
+  for (i = 0; i <n; i++) {
+    sn = wad_elf_section_name(wo,i);
+    if (strcmp(sn,name) == 0) {
+      return i;
+    }
+  }
+  return -1;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_find_symbol()
+ *
+ * Tries to find the symbol associated with a given address. base is the
+ * base address of the object file.
+ * ----------------------------------------------------------------------------- */
+
+static
+int elf_search_section_sym(WadFrame *f, char *secname, char *strname) {
+  int         nsymtab;
+  int         nstrtab;
+  int         symtab_size;
+  Elf32_Sym  *sym;
+  int         nsym;
+  char       *str;
+  int         i;
+  unsigned long vaddr, base;
+  char        *name;
+  char        *localfile = 0;
+
+  vaddr = (unsigned long) f->pc;
+  base  = (unsigned long) f->segment->base;
+
+  nsymtab = wad_elf_section_byname(f->object,secname);
+  if (nsymtab < 0) return 0;
+  nstrtab = wad_elf_section_byname(f->object,strname);
+  if (nstrtab < 0) return 0;
+  
+  symtab_size = wad_elf_section_size(f->object,nsymtab);
+  sym = (Elf32_Sym *) wad_elf_section_data(f->object,nsymtab);
+  str = (char *) wad_elf_section_data(f->object,nstrtab);
+
+  nsym = (symtab_size/sizeof(Elf32_Sym));
+  for (i = 0; i < nsym; i++) {
+    name = str + sym[i].st_name;
+    /* Look for filename in case the symbol maps to a local symbol */
+    if (ELF32_ST_TYPE(sym[i].st_info) == STT_FILE) {
+      localfile = name;
+    }
+    if (wad_debug_mode & DEBUG_SYMBOL_SEARCH) {
+      wad_printf("%x(%x): %s   %x + %x, %x, %x\n", base, vaddr, name, sym[i].st_value, sym[i].st_size, sym[i].st_info, sym[i].st_shndx);
+    }
+    if (((base + sym[i].st_value) <= vaddr) && (vaddr <= (base+sym[i].st_value + sym[i].st_size))) {
+#ifdef WAD_LINUX
+      /* If the section index is 0, the symbol is undefined */
+      if (sym[i].st_shndx == 0) continue;
+#endif
+      f->sym_name = name;
+      f->sym_nlen = strlen(name);
+      f->sym_base = base + sym[i].st_value;
+      f->sym_size = sym[i].st_size;
+      if (ELF32_ST_BIND(sym[i].st_info) == STB_LOCAL) {
+	f->sym_file = localfile;
+	f->sym_bind = SYM_LOCAL;
+      } else {
+	f->sym_bind = SYM_GLOBAL;
+      }
+      return 1;
+    }
+  }
+  return 0;
+}
+
+void
+wad_elf_find_symbol(WadFrame *f) {
+  /* We simply try a few possible sections */
+  if (elf_search_section_sym(f,".symtab",".strtab")) return;
+  if (elf_search_section_sym(f,".dynsym",".dynstr")) return;
+
+  /* Hmmm. No match found. Oh well */
+  return;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_debug_info()
+ *
+ * Gather debugging information about a function (if possible)
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_elf_debug_info(WadFrame *f) {
+  int nstab, nstabstr, nstabindex, nstabindexstr, nstabexcl, nstabexclstr;
+  int ret;
+  void *stab;
+  char *stabstr;
+  int   stabsize;
+
+  nstab = wad_elf_section_byname(f->object,".stab");
+  nstabstr = wad_elf_section_byname(f->object,".stabstr");
+  nstabindex = wad_elf_section_byname(f->object,".stab.index");
+  nstabindexstr = wad_elf_section_byname(f->object,".stab.indexstr");
+  nstabexcl = wad_elf_section_byname(f->object,".stab.excl");
+  nstabexclstr = wad_elf_section_byname(f->object,".stab.exclstr");
+
+#ifdef DEBUG_DEBUG
+  wad_printf("nstab         = %d\n", nstab);
+  wad_printf("nstabstr      = %d\n", nstabstr);
+  wad_printf("nstabindex    = %d\n", nstabindex);
+  wad_printf("nstabindexstr = %d\n", nstabindexstr);
+  wad_printf("nstabexcl     = %d\n", nstabexcl);
+  wad_printf("nstabexclstr  = %d\n", nstabexclstr);
+#endif 
+
+  /* Now start searching stabs */
+
+  /* Look in the .stab section */
+  if (nstab > 0) {
+    stab = wad_elf_section_data(f->object,nstab);
+    stabsize = wad_elf_section_size(f->object,nstab);
+    stabstr = (char *) wad_elf_section_data(f->object,nstabstr);
+
+    
+    if (wad_search_stab(stab,stabsize,stabstr, f)) return 1;
+  }
+
+  /* Look in the .stab.excl section. A solaris oddity? */
+  
+  if (nstabexcl > 0) {
+    stab = wad_elf_section_data(f->object,nstabexcl);
+    stabsize = wad_elf_section_size(f->object, nstabexcl);
+    stabstr = (char *) wad_elf_section_data(f->object, nstabexclstr);
+
+    if (wad_search_stab(stab,stabsize,stabstr, f)) return 1;
+  }
+
+  /* Look in the .stab.index section. A Solaris oddity? */
+  if (nstabindex > 0) {
+
+    stab = wad_elf_section_data(f->object,nstabindex);
+    stabsize = wad_elf_section_size(f->object, nstabindex);
+    stabstr = (char *) wad_elf_section_data(f->object, nstabindexstr);
+
+    if (wad_search_stab(stab,stabsize,stabstr, f)) {
+      /* Hmmm. Might be in a different file */
+      WadObjectFile *wo1, *wold;
+      char objfile[MAX_PATH];
+      /*      printf("DEBUG %s\n", f->sym_name); */
+      wad_strcpy(objfile, f->loc_objfile);
+      wo1 = wad_object_load(objfile);
+      if (wo1) {
+	wold = f->object;
+	f->object = wo1;
+	wad_find_debug(f);
+	f->object = wold;
+	return ret;
+      } else {
+	/*	wad_printf("couldn't load %s\n", objfile); */
+      }
+      /*      if (!ret) return wad_search_stab(stab,stabsize,stabstr,f);*/
+      return ret;
+    }
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_elf_debug()
+ *
+ * Print some debugging information about an object
+ * ----------------------------------------------------------------------------- */
+
+void
+wad_elf_debug(WadObjectFile *wo) {
+  int i;
+  wad_printf("ELF Debug : obj = %x (%s)\n", wo, wo->path);
+  wad_printf("   phdrcnt      = %d\n", wad_elf_phdrcnt(wo));
+  wad_printf("   phdrpos      = %x\n", wad_elf_phdrpos(wo));
+  wad_printf("   shdrcnt      = %d\n", wad_elf_shdrcnt(wo));
+  wad_printf("   shdrpos      = %x\n", wad_elf_shdrpos(wo));
+  for (i = 0; i < wad_elf_shdrcnt(wo); i++) {
+    wad_printf("      section '%s': data = 0x%x, size = %d\n", 
+	   wad_elf_section_name(wo,i),
+	   wad_elf_section_data(wo,i),
+	   wad_elf_section_size(wo,i));
+  }
+}
+
+/* general purpose functions exposed to the outside world */
+
+/* -----------------------------------------------------------------------------
+ * wad_find_symbol()
+ * ----------------------------------------------------------------------------- */
+
+void
+wad_find_symbol(WadFrame *f) {
+  if (wad_debug_mode & DEBUG_SYMBOL) {
+    wad_printf("wad: Searching for 0x%08x --> ", f->pc);
+  }
+  if (f->object)
+    wad_elf_find_symbol(f);
+  if (wad_debug_mode & DEBUG_SYMBOL) {
+    if (f->sym_name) {
+      wad_printf("%s", f->sym_name);
+      if (f->sym_file)
+	wad_printf(" in '%s'\n", f->sym_file);
+      else
+	wad_printf("\n");
+    } else {
+      wad_printf("?\n");
+    }
+  }
+}
+
+void
+wad_find_debug(WadFrame *f) {
+  /*  if (f->debug_check) return; */
+  if (f->object) {
+    wad_elf_debug_info(f);
+  }
+  /*  f->debug_check = 1; */
+}
+
+
+
diff --git a/trunk/Tools/WAD/Wad/init.c b/trunk/Tools/WAD/Wad/init.c
new file mode 100644
index 0000000..fb44b8d
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/init.c
@@ -0,0 +1,113 @@
+/* ----------------------------------------------------------------------------- 
+ * init.c
+ *
+ *     Initialize the wad system.  This sets up a signal handler for catching
+ *     SIGSEGV, SIGBUS, and SIGABRT.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* Debugging flag */
+int    wad_debug_mode = 0;
+
+/* Initialize wad */
+void wad_init() {
+  static int init = 0;
+
+  wad_memory_init();
+  if (getenv("WAD_DEBUG_SEGMENT")) {
+    wad_debug_mode |= DEBUG_SEGMENT;
+  }
+  if (getenv("WAD_DEBUG_SYMBOL")) {
+    wad_debug_mode |= DEBUG_SYMBOL;
+  }
+
+  if (getenv("WAD_DEBUG_OBJECT")) {
+    wad_debug_mode |= DEBUG_OBJECT;
+  }
+
+  if (getenv("WAD_DEBUG_FILE")) {
+    wad_debug_mode |= DEBUG_FILE;
+  }
+
+  if (getenv("WAD_DEBUG_HOLD")) {
+    wad_debug_mode |= DEBUG_HOLD;
+  }
+
+  if (getenv("WAD_DEBUG_STABS")) {
+    wad_debug_mode |= DEBUG_STABS;
+  }
+
+  if (getenv("WAD_DEBUG_RETURN")) {
+    wad_debug_mode |= DEBUG_RETURN;
+  }
+
+  if (getenv("WAD_DEBUG_SYMBOL_SEARCH")) {
+    wad_debug_mode |= DEBUG_SYMBOL_SEARCH;
+  }
+
+  if (getenv("WAD_DEBUG_INIT")) {
+    wad_debug_mode |= DEBUG_INIT;
+  }
+
+  if (getenv("WAD_DEBUG_STACK")) {
+    wad_debug_mode |= DEBUG_STACK;
+  }
+
+  if (getenv("WAD_DEBUG_UNWIND")) {
+    wad_debug_mode |= DEBUG_UNWIND;
+  }
+
+  if (getenv("WAD_DEBUG_SIGNAL")) {
+    wad_debug_mode |= DEBUG_SIGNAL;
+  }
+
+  if (getenv("WAD_NOSTACK")) {
+    wad_debug_mode |= DEBUG_NOSTACK;
+  }
+
+  if (getenv("WAD_ONESHOT")) {
+    wad_debug_mode |= DEBUG_ONESHOT;
+  }
+
+  if (getenv("WAD_DEBUG_STRING")) {
+    wad_debug_mode |= DEBUG_STRING;
+  }
+
+  if (getenv("WAD_DEBUG_MEMORY")) {
+    wad_debug_mode |= DEBUG_MEMORY;
+  }
+
+  if (wad_debug_mode & DEBUG_INIT) {
+    wad_printf("WAD: initializing\n");
+  }
+
+
+  if (!init) {
+    wad_signal_init();
+    wad_object_reset();
+  }
+  init = 1;
+}
diff --git a/trunk/Tools/WAD/Wad/io.c b/trunk/Tools/WAD/Wad/io.c
new file mode 100644
index 0000000..afbb309
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/io.c
@@ -0,0 +1,107 @@
+/* ----------------------------------------------------------------------------- 
+ * io.c
+ *
+ *     This file provides some I/O routines so that WAD can produce 
+ *     debugging output without using buffered I/O.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+#include <stdarg.h>
+
+static char cvs[] = "$Id$";
+
+/* Utility functions used to generate strings that are guaranteed not to 
+   rely upon malloc() and related functions */
+
+char *wad_format_hex(unsigned long u, int leading) {
+  static char result[64];
+  int i;
+  char *c;
+  c = &result[63];
+  *c = 0;
+  for (i = 0; i < (sizeof(unsigned long)*2); i++) {
+    int d;
+    d = (int) (u & 0xf);
+    c--;
+    if (d < 10) {
+      *c = '0' + d;
+    } else {
+      *c = 'a' + (d-10);
+    }
+    if (!u && !leading) break;
+    u = u >> 4;
+  }
+  return c;
+}
+
+char *wad_format_unsigned(unsigned long u, int width) {
+  static char result[128];
+  static char digits[] = "0123456789";
+  char *c, *w;
+  int count = 0;
+  int i;
+  c = &result[64];
+  while (u) {
+    int digit = u % 10;
+    *(--c) = digits[digit];
+    count++;
+    u = u / 10;
+  }
+  if (!count) {
+    *(--c) = '0';
+    count++;
+  }
+  w = &result[64];
+  for (i = count; i < width; i++) {
+    *(w++) = ' ';
+  }
+  *w = 0;
+  return c;
+}
+
+char *wad_format_signed(signed long s, int width) {
+  static char result[128];
+  unsigned long u;
+  char *c = result;
+  if (s < 0) {
+    *(c++) = '-';
+    width--;
+    u = (unsigned long) (-s);
+    if (u == 0) {
+      u = (unsigned long) s;
+    }
+  } else {
+    u = (unsigned long) s;
+  }
+  *c = 0;
+  wad_strcat(result, wad_format_unsigned(u,width));
+  return result;
+}
+
+
+void wad_printf(const char *fmt, ...) {
+  va_list ap;
+  va_start(ap, fmt);
+  vfprintf(stderr,fmt,ap);
+  va_end(ap);
+}
diff --git a/trunk/Tools/WAD/Wad/libwadpl.pm b/trunk/Tools/WAD/Wad/libwadpl.pm
new file mode 100644
index 0000000..21a01db
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/libwadpl.pm
@@ -0,0 +1,8 @@
+package libwadpl;
+require Exporter;
+require DynaLoader;
+@ISA = qw(Exporter DynaLoader);
+package libwadpl;
+bootstrap libwadpl;
+@EXPORT = qw( );
+1;
diff --git a/trunk/Tools/WAD/Wad/main.cxx b/trunk/Tools/WAD/Wad/main.cxx
new file mode 100644
index 0000000..1cf5ce9
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/main.cxx
@@ -0,0 +1,14 @@
+extern "C" {
+#include "wad.h"
+}
+
+/* This is a sick hack to force initialization upon loading */
+
+class StartDebug {
+public:
+  StartDebug() {
+    wad_init();
+  }
+};
+
+static StartDebug s;
diff --git a/trunk/Tools/WAD/Wad/makehandler.py b/trunk/Tools/WAD/Wad/makehandler.py
new file mode 100755
index 0000000..c4e23a6
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/makehandler.py
@@ -0,0 +1,20 @@
+#!/usr/local/bin/python
+import string
+f = open("wadhandler.pl")
+data = f.read()
+f.close()
+
+data = string.replace(data,"\\", "\\\\")
+data = string.replace(data,"\"", "\\\"")
+data = string.replace(data,"\n", "\\n\\\n")
+
+f = open("wad_perl_handler.c","w")
+
+f.write("static char wad_perl_handler[] = \"")
+f.write(data)
+f.write("\";\n");
+f.close()
+
+
+
+
diff --git a/trunk/Tools/WAD/Wad/memory.c b/trunk/Tools/WAD/Wad/memory.c
new file mode 100644
index 0000000..0260cb8
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/memory.c
@@ -0,0 +1,174 @@
+/* ----------------------------------------------------------------------------- 
+ * memory.c
+ *
+ *     This file provides simple mmap() based memory management for WAD.  Since
+ *     the process heap-allocator might be corrupted when WAD is invoked, we
+ *     have to do all of our own memory management.  However, since WAD mostly
+ *     just collects data, we only provide the function wad_malloc().  To
+ *     release all allocated memory, the wad_release_memory() function should
+ *     be used.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+typedef struct _WadMemory {
+  int                npages;          /* Number of pages            */
+  int                last;            /* Last offset in page        */ 
+  struct _WadMemory *next;            /* Pointer to next allocation */
+} WadMemory;
+
+static WadMemory *current = 0;                /* Current memory block        */
+static int        pagesize = 0;               /* System page size            */
+static int        devzero = 0;
+static int        npalloc = 8;                 /* Number of pages per alloc   */
+
+/* -----------------------------------------------------------------------------
+ * wad_memory_init()
+ *
+ * Initialize the WAD allocator.
+ * ----------------------------------------------------------------------------- */
+
+int wad_memory_init() {
+  pagesize = getpagesize();
+  devzero = open("/dev/zero", O_RDWR);
+  if (devzero < 0) {
+    wad_printf("WAD: couldn't open /dev/zero.\n");
+    return -1;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_page_alloc()
+ *
+ * Allocate pages using mmap
+ * ----------------------------------------------------------------------------- */
+
+void *wad_page_alloc(int npages) {
+  void *m;
+  m = mmap(NULL, npages*pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE, devzero, 0);
+  if (((long) m) == -1) return 0;
+  /*  printf("page_alloc: %x - %x\n", m, ((char *) m) + npages*pagesize); */
+  return m;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_malloc()
+ *
+ * Allocate memory using mmap().   If the allocation is smaller than half a page,
+ * We'll look at current to see if there is enough space.  If so, we'll just
+ * use that memory.  Otherwise, we'll allocate a new page.  If the allocation
+ * request is larger than a page, we'll round up to the nearest page size and
+ * do a special allocation.
+ * ----------------------------------------------------------------------------- */
+
+void *wad_malloc(int nbytes) {
+  void *ptr;
+  WadMemory *wm;
+  char      *c;
+  int npages;
+  /*  wad_printf("wad_malloc: %d\n", nbytes); */
+  if (nbytes >= ((npalloc*pagesize) >> 2)) {
+    /* Large allocation. */
+    npages = ((nbytes + sizeof(WadMemory))/pagesize) + 1;
+    ptr = wad_page_alloc(npages);
+    if (!ptr) return 0;
+    wm = (WadMemory *)ptr;
+    wm->npages = npages;
+    wm->last = sizeof(WadMemory) + 8;
+    wm->next = current;
+    current = wm;
+    c = (char *) current + (current->last);
+    current->last += ((nbytes & ~0x7) + 8);
+    return c;
+  }
+  /* Small allocation.  See if there are any regions big enough */
+  wm = current;
+  while (wm) {
+    if (((wm->npages*pagesize) - wm->last) > nbytes) {
+      /* Yep. Found a region */
+      break;
+    }
+    wm = wm->next;
+  }
+  if (!wm) {
+    /*    wad_printf("wad_malloc: new page\n", nbytes);*/
+    wm = (WadMemory *) wad_page_alloc(npalloc);
+    if (!wm) return 0;
+    wm->npages = npalloc;
+    wm->last = sizeof(WadMemory) + 8;
+    wm->next = current;
+    current = wm;
+  }
+  c = ((char *) wm) + (wm->last);
+  wm->last += ((nbytes & ~0x7) + 8);
+  return c;
+}  
+
+/* -----------------------------------------------------------------------------
+ * wad_strdup()
+ *
+ * Duplicate a string 
+ * ----------------------------------------------------------------------------- */
+
+char *wad_strdup(const char *c) {
+  char *t;
+  if (!c) c = "";
+  t = (char *) wad_malloc(strlen(c)+1);
+  wad_strcpy(t,c);
+  return t;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_memcpy()
+ * ----------------------------------------------------------------------------- */
+
+void wad_memcpy(void *t, const void *s, unsigned len) {
+  char *tc, *sc;
+  int i;
+  tc = (char *) t;
+  sc = (char *) s;
+  for (i = 0; i < len; i++, tc++, sc++)
+    *tc = *sc;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_memory_debug()
+ * ----------------------------------------------------------------------------- */
+
+void wad_memory_debug() {
+  int   total_alloc = 0;
+  int   inuse = 0;
+  WadMemory *m;
+  if (wad_debug_mode & DEBUG_MEMORY) {
+    m = current;
+    while (m) {
+      total_alloc += (m->npages)*pagesize;
+      inuse += m->last;
+      m = m->next;
+    }
+    wad_printf("WAD: memory allocated %d bytes (%d bytes used).\n", total_alloc, inuse);
+  }
+}
diff --git a/trunk/Tools/WAD/Wad/object.c b/trunk/Tools/WAD/Wad/object.c
new file mode 100644
index 0000000..f13d6b3
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/object.c
@@ -0,0 +1,303 @@
+/* ----------------------------------------------------------------------------- 
+ * object.c
+ *
+ *     This file provides access to raw object files, executables, and
+ *     library files.  Memory management is handled through mmap() to
+ *     avoid the use of heap/stack space.
+ *
+ *     All of the files and objects created by this module persist
+ *     until the process exits.  Since WAD may be invoked multiple times
+ *     over the course of program execution, it makes little sense to keep
+ *     loading and unloading files---subsequent invocations of the handler
+ *     can simply used previously loaded copies.  Caveat: things probably
+ *     won't work right if a program is doing lots of low-level manipulation
+ *     of the dynamic loader.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+#include <ar.h>
+
+typedef struct WadFile {
+  void   *addr;                /* Base address of the file */
+  int     size;                /* Size in bytes            */
+  char   *path;                /* Path name                */
+  struct  WadFile *next;       /* Next file                */
+} WadFile;
+
+static WadFile     *wad_files = 0;              /* Linked list of loaded files */
+
+/* private function to manage the loading of raw files into memory */
+static WadFile *
+load_file(const char *path) {
+  int fd;
+  WadFile *wf = wad_files;
+
+  if (wad_debug_mode & DEBUG_FILE) {
+    wad_printf("wad: Loading file     '%s' ... ", path);
+  }
+  while (wf) {
+    if (strcmp(wf->path,path) == 0) {
+      if (wad_debug_mode & DEBUG_FILE) wad_printf("cached.\n");
+      return wf;
+    }
+    wf = wf->next;
+  }
+  fd = open(path, O_RDONLY);
+  if (fd < 0) {
+    if (wad_debug_mode & DEBUG_FILE) wad_printf("not found!\n");
+    return 0;       /* Doesn't exist. Oh well */
+  }
+  if (wad_debug_mode & DEBUG_FILE) wad_printf("loaded.\n");
+  wf = (WadFile *) wad_malloc(sizeof(WadFile));
+  wf->path = wad_strdup(path);
+
+  /* Get file length */
+  wf->size = lseek(fd,0,SEEK_END);
+  lseek(fd,0,SEEK_SET);
+  
+  /* Try to mmap the file */
+  wf->addr = mmap(NULL,wf->size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE, fd, 0);
+  close(fd);
+  if (wf->addr == MAP_FAILED) {
+    if (wad_debug_mode & DEBUG_FILE) wad_printf("wad: Couldn't mmap '%s'\n", path);
+    return 0;
+  }
+  wf->next = wad_files;
+  wad_files = wf;
+  return wf;
+}
+
+static WadObjectFile *wad_objects = 0;              /* Linked list of object files */
+
+/* -----------------------------------------------------------------------------
+ * wad_object_cleanup()
+ *
+ * Reset the object file loader.  This unmaps the files themselves, but
+ * memory will leak for object files pointers themselves. 
+ * ----------------------------------------------------------------------------- */
+
+void
+wad_object_reset() {
+  WadFile *f = wad_files;
+  if (wad_debug_mode & DEBUG_OBJECT) {
+    wad_printf("wad: Releasing all files.\n");
+  }
+  /* Unmap all of the loaded files */
+  while (f) {
+    if (f->addr) {
+      munmap(f->addr, f->size);
+    }
+    f = f->next;
+  }
+  /* Reset the linked lists */
+  wad_files = 0;
+  wad_objects = 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_object_load()
+ * 
+ * Load an object file into memory using mmap.   Returns 0 if the object does
+ * not exist or if we're out of memory.
+ * ----------------------------------------------------------------------------- */
+
+WadObjectFile *
+wad_object_load(const char *path) {
+  WadObjectFile *wo;
+  WadFile *wf;
+  WadObjectFile  *wad_arobject_load(const char *path, const char *name);
+
+  if (wad_debug_mode & DEBUG_OBJECT) {
+    wad_printf("wad: Loading object   '%s'", path);
+  }
+  for (wo = wad_objects; wo; wo=wo->next) {
+    if (strcmp(wo->path,path) == 0) {
+      if (wad_debug_mode & DEBUG_OBJECT) {
+	wad_printf(" (cached)\n");
+      }
+      return wo;
+    }
+  }
+  if (wad_debug_mode & DEBUG_OBJECT) {
+    wad_printf("\n");
+  }
+  /* Didn't find it.  Now we need to go load some files */
+
+  /* If this is an archive reference like /path/libfoo.a(blah.o), we need to
+     split up the name a little bit */
+  {
+    char realfile[MAX_PATH];
+    char *objfile;
+    char *c;
+    c = strchr(path,'(');
+    if (c) {
+      wad_strcpy(realfile,path);
+      c = strchr(realfile,'(');
+      *c = 0;
+      objfile = c+1;
+      c = strchr(objfile,')');
+      *c = 0;
+      
+      /* Okay, I'm going to attempt to map this as a library file */
+      wo = wad_arobject_load(realfile,objfile);
+      if (wo) {
+	/* Reset the path */
+	wo->path = wad_strdup(path);
+	wo->next = wad_objects;
+	wad_objects = wo;
+	return wo;
+      }
+    }
+  }
+  wf = load_file(path);
+  if (!wf) return 0;
+
+  wo = (WadObjectFile *) wad_malloc(sizeof(WadObjectFile));
+  wo->path = wad_strdup(path);
+  wo->ptr = wf->addr;
+  wo->len = wf->size;
+  wo->next = wad_objects;
+  wad_objects = wo;
+  return wo;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_arobject_load()
+ * 
+ * Load an object file stored in an archive file created with an archive.  The
+ * pathname should be the path of the .a file and robjname should be the name
+ * of the object file stored in the object file.
+ * ----------------------------------------------------------------------------- */
+
+WadObjectFile *
+wad_arobject_load(const char *arpath, const char *robjname) {
+  WadObjectFile *wo;
+  WadFile       *wf;
+  int arlen;
+  char *arptr;
+  struct ar_hdr  *ah;
+  int offset;
+  int msize;
+  char *strtab = 0;
+  int   sobjname;
+  char  objname[MAX_PATH];
+
+  wad_strcpy(objname,robjname);
+  wad_strcat(objname,"/");
+  sobjname = strlen(objname);
+
+  wf = load_file(arpath);
+  if (!wf) return 0;          /* Doesn't exit */
+
+  arptr = (char *) wf->addr;
+  arlen = wf->size;
+
+  /* Now take a look at the archive */
+  if (strncmp(arptr,ARMAG,SARMAG) == 0) {
+    /* printf("Got an archive\n"); */
+  } else {
+    return 0;
+  }
+
+  /* Search the archive for the request member */
+  strtab = 0;
+  offset = SARMAG;
+  while (offset < arlen) {
+    char mname[MAX_PATH];
+    ah = (struct ar_hdr *) (arptr + offset);
+    if (strncmp(ah->ar_name,"// ", 3) == 0) {
+      strtab = arptr + offset + sizeof(struct ar_hdr);
+    }
+    msize = atoi(ah->ar_size);    
+
+    offset += sizeof(struct ar_hdr);
+    /* Try to figure out the filename */
+    if ((ah->ar_name[0] == '/') && (isdigit(ah->ar_name[1]))) {
+      int soff;
+      char *e;
+      /* Must be in the string offset table */
+      soff = atoi(ah->ar_name+1);
+      if (!strtab) {
+	/* No offset table */
+	return 0;
+      }
+      e = strchr(strtab+soff,'\n');
+      if (e) {
+	strncpy(mname, strtab+soff, (e - (strtab+soff)));
+	mname[e-(strtab+soff)] = 0;
+      } else {
+	mname[0] = 0;
+      }
+    } else {
+      /* Name must be in the name field */
+      strncpy(mname,ah->ar_name,16);
+      mname[16] = 0;
+    }
+    /* Compare the names */
+    if (strncmp(mname,objname,sobjname) == 0) {
+      /* Found the archive */
+      wo = (WadObjectFile *) wad_malloc(sizeof(WadObjectFile));
+      wo->ptr = (void *) (arptr + offset);
+      wo->len = msize;
+      wo->path = 0;
+      return wo;
+    }
+    offset += msize;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_find_object(WadFrame *f)
+ *
+ * Given a stack frame.  Try to locate the object file
+ * ----------------------------------------------------------------------------- */
+
+void wad_find_object(WadFrame *f) {
+  if (f->segment) {
+    f->object = wad_object_load(f->segment->mappath);
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_file_check(void *addr)
+ *
+ * Given an address, this function checks to see if it corresponds to a file
+ * we already mapped.
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_file_check(void *addr) {
+  WadFile *f = wad_files;
+  while (f) {
+    if ((((char *) f->addr) <= ((char *) addr)) && 
+	(((char *) addr) < (((char *) f->addr) + f->size))) {
+      return 1;
+    }
+    f = f->next;
+  }
+  return 0;
+}
diff --git a/trunk/Tools/WAD/Wad/return.c b/trunk/Tools/WAD/Wad/return.c
new file mode 100644
index 0000000..909cba3
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/return.c
@@ -0,0 +1,69 @@
+/* ----------------------------------------------------------------------------- 
+ * return.c
+ *
+ *     This file manages the set of return-points for the WAD signal handler.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* Maximum number of return points */
+#define WAD_NUMBER_RETURN  128
+
+static WadReturnFunc return_points[WAD_NUMBER_RETURN];
+static int           num_return = 0;
+
+void wad_set_return(const char *name, long value) {
+  WadReturnFunc *rp;
+  rp = &return_points[num_return];
+  wad_strcpy(rp->name,name);
+  rp->value = value;
+  num_return++;
+  if (wad_debug_mode & DEBUG_RETURN) {
+    printf("wad: Setting return ('%s', %d)\n", name,value);
+  }
+}
+
+void wad_set_returns(WadReturnFunc *rf) {
+  int i = 0;
+  while (strlen(rf[i].name)) {
+    wad_set_return(rf[i].name, rf[i].value);
+    i++;
+  }
+}
+
+WadReturnFunc *wad_check_return(const char *name) {
+  int i;
+  if (!name) return 0;
+  for (i = 0; i < num_return; i++) {
+    if (strcmp(name,return_points[i].name) == 0) {
+      if (wad_debug_mode & DEBUG_RETURN) {
+	printf("wad: Found return ('%s', %d)\n", return_points[i].name, return_points[i].value);
+      }
+      return &return_points[i];
+    }
+  }
+  return 0;
+}
+
diff --git a/trunk/Tools/WAD/Wad/segment.c b/trunk/Tools/WAD/Wad/segment.c
new file mode 100644
index 0000000..ec4cf13
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/segment.c
@@ -0,0 +1,227 @@
+/* ----------------------------------------------------------------------------- 
+ * segment.c
+ *
+ *     This file provides access to the virtual memory map of a process
+ *     including the location of the executable, data segments, shared
+ *     libraries, and memory mapped regions. 
+ *
+ *     The primary purpose of this module is to collect this information
+ *     and store it in a form that hides platform specific details (the
+ *     WadSegment structure).
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* Include the proper code for reading the segment map */
+
+#ifdef WAD_SOLARIS
+
+/* This code is used to read the process virtual memory map on Solaris machines */
+
+static int
+segment_open() {
+  int f;
+  f = open("/proc/self/map", O_RDONLY);
+  return f;
+}
+
+static int
+segment_read(int fs, WadSegment *s) {
+  int     dz;
+  int     n;
+  prmap_t pmap;
+
+  n = read(fs, &pmap, sizeof(prmap_t));
+  if (n <= 0) return 0;
+  s->mapname = wad_strdup(pmap.pr_mapname);
+  s->mappath = (char *) wad_malloc(20+strlen(pmap.pr_mapname));
+  wad_strcpy(s->mappath,"/proc/self/object/");
+  strcat(s->mappath,pmap.pr_mapname);
+  s->vaddr = (char *) pmap.pr_vaddr;
+
+  /* This is a solaris oddity.  a.out section starts 1 page up, but
+     symbols are relative to a base of 0 */
+
+  if (strcmp(s->mapname,"a.out") == 0) s->base = 0;
+  else s->base = s->vaddr;
+
+  s->size  = pmap.pr_size;
+  s->offset = pmap.pr_offset;
+  return 1;
+}
+
+#endif           /* WAD_SOLARIS */
+
+#ifdef WAD_LINUX
+static char linux_firstsegment[1024];
+static int linux_first = 1;
+
+static int
+segment_open() {
+  FILE *f;
+  f = fopen("/proc/self/maps", "r");
+  linux_first =1;
+  return (int) f;
+}
+
+static int 
+segment_read(int fd, WadSegment *s)
+{
+  char pbuffer[1024];
+  char *c;
+  int  len;
+  FILE *fs = (FILE *) fd;
+  c = fgets(pbuffer,1024,fs);
+  if (!c) return 0;
+
+  pbuffer[strlen(pbuffer)-1] = 0;   /* Chop off endline */
+
+  /* Break up the field into records */
+  /*    0-8       : Starting address
+	9-17      : Ending Address
+	18        : r
+	19        : w
+	20        : x
+	21        : p
+	23-31     : Offset 
+	49-       : Filename */
+
+  len = strlen(pbuffer);
+  pbuffer[8] = 0;
+  pbuffer[17] = 0;
+  pbuffer[31] = 0;
+  if (len >= 49) {
+    s->mapname = wad_strdup(pbuffer+49);
+    s->mappath = s->mapname;
+  }  else {
+    s->mapname = "";
+    s->mappath = s->mapname;
+  }
+  if (linux_first) {
+    wad_strcpy(linux_firstsegment, s->mappath);
+    linux_first = 0;
+  }
+  s->vaddr = (char *) strtoul(pbuffer,NULL,16);
+  s->size = strtoul(pbuffer+9,NULL,16) - (long) (s->vaddr);
+  s->offset = strtoul(pbuffer+23,NULL,16);
+  if (strcmp(linux_firstsegment, s->mappath) == 0) {
+    s->base = 0;
+  } else {
+    s->base = s->vaddr;
+  }
+  s++;
+  return 1;
+}
+
+#endif   /* WAD_LINUX */
+
+static WadSegment    *segments = 0;   /* Linked list of segments */
+
+/* ----------------------------------------------------------------------------- 
+ * wad_segment_read()
+ *
+ * Read all of the memory segments into a linked list.  Any previous segment
+ * map is simply lost.  The only way to reclaim this memory is to call
+ * wad_release_memory().
+ * ----------------------------------------------------------------------------- */
+
+int
+wad_segment_read() {
+  int         fs;
+  int         n;
+  WadSegment *s, *lasts;
+
+  segments = 0;
+  lasts = 0;
+  fs = segment_open();
+
+  while (1) {
+    s = (WadSegment *) wad_malloc(sizeof(WadSegment));    
+  skip:
+    n = segment_read(fs,s);
+    if (n <= 0) break;
+    if (wad_file_check(s->vaddr)) goto skip;  /* Skip files we already loaded */
+    s->next = 0;
+    if (!lasts) {
+      segments = s;
+      lasts = s;
+    } else {
+      lasts->next = s;
+      lasts = s;
+    }
+    if (wad_debug_mode & DEBUG_SEGMENT) {
+      wad_printf("wad_segment: read : %08x-%08x, base=%x in %s\n", s->vaddr, ((char *) s->vaddr) + s->size, s->base, s->mappath);
+    }
+  }
+  close(fs);
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_segment_find()
+ *
+ * Try to find the virtual memory segment corresponding to a virtual address.
+ * If a segment is mapped to a file, this function actually returns the *first*
+ * segment that is mapped.   This is because symbol relocations are always
+ * performed relative to the beginning of the file (so we need the base address)
+ * ----------------------------------------------------------------------------- */
+
+WadSegment *
+wad_segment_find(void *vaddr) {
+  WadSegment *ls;
+  WadSegment *s;
+  char *addr = (char *)vaddr;
+
+  s = segments;
+  ls = segments;
+  while (s) {
+    if (strcmp(s->mapname,ls->mapname) || (!strlen(ls->mapname))) {
+      ls = s;    /* First segment for a given name */
+    }
+    if ((addr >= s->vaddr) && (addr < (s->vaddr + s->size))) {
+      if (wad_debug_mode & DEBUG_SEGMENT) {
+	wad_printf("wad_segment: %08x --> %08x-%08x in %s\n", vaddr, s->vaddr, ((char *) s->vaddr) + s->size, s->mappath);
+      }
+      return ls;
+    }
+    s = s->next;
+  }
+  return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_segment_valid()
+ *
+ * Checks to see if a memory address is valid or not based on data in the
+ * segment map 
+ * ----------------------------------------------------------------------------- */
+
+int wad_segment_valid(void *vaddr) {
+  return wad_segment_find(vaddr) ? 1 : 0;
+}
+
+
+
+
diff --git a/trunk/Tools/WAD/Wad/signal.c b/trunk/Tools/WAD/Wad/signal.c
new file mode 100644
index 0000000..36f89c3
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/signal.c
@@ -0,0 +1,520 @@
+/* ----------------------------------------------------------------------------- 
+ * signal.c
+ *
+ *     WAD signal handler. 
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+extern void wad_stab_debug();
+
+/* For some odd reason, certain linux distributions do not seem to define the
+   register constants in a way that is easily accessible to us.  This is a hack */
+
+#ifdef WAD_LINUX
+#ifndef ESP
+#define ESP      7
+#endif
+#ifndef EBP
+#define EBP      6
+#endif
+#ifndef EIP
+#define EIP      14
+#endif
+#ifndef ESI
+#define ESI      5
+#endif
+#ifndef EDI
+#define EDI      4
+#endif
+#ifndef EBX
+#define EBX      8
+#endif
+
+#endif
+
+/* Signal handling stack */
+#define STACK_SIZE 4*SIGSTKSZ
+char wad_sig_stack[STACK_SIZE];
+
+/* This variable is set if the signal handler thinks that the
+   heap has overflowed */
+
+int wad_heap_overflow = 0;
+
+static void (*sig_callback)(int signo, WadFrame *data, char *ret) = 0;
+
+void wad_set_callback(void (*s)(int,WadFrame *,char *ret)) {
+  sig_callback = s;
+}
+
+/* This bit of nastiness is used to make a non-local return from the
+   signal handler to a configurable location on the call stack. In a nutshell,
+   this works by repeatedly calling "restore" to roll back the 
+   register windows and stack pointer.  Then we fake a return value and
+   return to the caller as if the function had actually completed
+   normally. */
+
+int            wad_nlr_levels = 0;
+static volatile int  *volatile nlr_p = &wad_nlr_levels;
+long           wad_nlr_value = 0;
+void          (*wad_nlr_func)(void) = 0;
+
+/* Set the return value from another module */
+void wad_set_return_value(long value) {
+  wad_nlr_value = value;
+}
+
+/* Set the return function */
+void wad_set_return_func(void(*f)(void)) {
+  wad_nlr_func = f;
+}
+
+#ifdef WAD_SOLARIS
+static void nonlocalret() {
+  long a;
+  
+  a = wad_nlr_value;
+  /* We never call this procedure as a function.  This code
+     causes an immediate return if someone does this */
+
+  asm("jmp %i7 + 8");
+  asm("restore");
+
+  /* This is the real entry point */
+  /*  asm(".globl _returnsignal");*/
+  asm(".type   _returnsignal,2");
+  asm("_returnsignal:");
+
+  while (*nlr_p > 0) {
+    (*nlr_p)--;
+    asm("restore");
+  }
+
+  asm("sethi %hi(wad_nlr_value), %o0");
+  asm("or %o0, %lo(wad_nlr_value), %o0");
+  asm("ld [%o0], %i0");
+
+  /* If there is a non-local return function.  We're going to go ahead
+     and transfer control to it */
+  
+  if (wad_nlr_func) 
+    (*wad_nlr_func)();
+
+  asm("jmp %i7 + 8");
+  asm("restore");
+  asm(".size	_returnsignal,(.-_returnsignal)");
+}
+#endif
+
+#ifdef WAD_LINUX
+
+/* Saved values of the machine registers */
+
+long   wad_saved_esi = 0;
+long   wad_saved_edi = 0;
+long   wad_saved_ebx = 0;
+
+static void nonlocalret() {
+  asm("_returnsignal:");
+  while (*nlr_p > 0) {
+    (*nlr_p)--;
+    asm("leave");
+  }
+
+  if (wad_nlr_func) 
+    (*wad_nlr_func)();
+
+  /* Restore the registers */
+  asm("movl wad_saved_esi, %esi");
+  asm("movl wad_saved_edi, %edi");
+  asm("movl wad_saved_ebx, %ebx");
+  asm("movl wad_nlr_value, %eax");
+  asm("leave");
+  asm("ret");
+}
+
+/* This function uses a heuristic to restore the callee-save registers on i386.
+   According to the Linux Assembly HOWTO, the %esi, %edi, %ebx, and %ebp registers
+   are callee-saved.  All others are caller saved.    To restore the callee-save
+   registers, we use the fact that the C compiler saves the callee-save registers
+   (if any) at the beginning of function execution.   Therefore, we can scan the
+   instructions at the start of each function in the stack trace to try and find
+   where they are. 
+
+   The following heuristic is used:
+
+   1. Each function starts with a preamble like this which saves the %ebp 
+      register:
+
+          55 89 e5       --->   push %ebp
+                                mov  %esp, %ebp
+
+   2. Next, space is allocated for local variables, using one of two schemes:
+ 
+          83 ec xx       --->  Less than 256 bytes of local storage
+                ^^^
+                length
+
+          81 ec xx xx xx xx  --> More than 256 bytes of local storage
+                ^^^^^^^^^^^
+                   length
+
+   3. After this, a collection of 1-byte stack push op codes might appear
+          
+          56      = pushl %esi
+          57      = pushl %edi
+          53      = pushl %ebx
+
+
+   Based on the size of local variable storage and the order in which 
+   the %esi, %edi, and %ebx registers are pushed on the stack, we can
+   determine where in memory the registers are saved and restore them to
+   their proper values.
+*/
+
+void wad_restore_i386_registers(WadFrame *f, int nlevels) {
+  WadFrame *lastf = f;
+  int       localsize = 0;
+  unsigned char     *pc;
+  unsigned long     *saved;
+  int i, j;
+  int pci;
+  for (i = 0; i <= nlevels; i++, f=f->next) {
+
+    /* This gets the starting instruction for the stack frame */
+    pc = (unsigned char *) f->sym_base;
+    /*    printf("pc = %x, base = %x, %s\n", f->pc, f->sym_base, SYMBOL(f)); */
+    if (!pc) continue;
+
+    /* Look for the standard prologue 0x55 0x89 0xe5 */
+    if ((pc[0] == 0x55) && (pc[1] == 0x89) && (pc[2] == 0xe5)) {
+      /* Determine the size */
+      pci = 3;
+      if ((pc[3] == 0x83) && (pc[4] == 0xec)) {
+	/*	printf("8-bit size\n");*/
+	localsize = (int) pc[5];
+	pci = 6;
+      } 
+      if ((pc[3] == 0x81) && (pc[4] == 0xec)) {
+	/*	printf("32-bit size\n"); */
+	localsize = (int) *((long *) (pc+5));
+	pci = 10;
+      }
+      saved = (long *) (f->fp - localsize - sizeof(long));
+      /*      printf("saved = %x, fp = %x\n", saved, f->fp);
+      printf("localsize = %d\n", localsize);
+      */
+      for (j = 0; j < 3; j++, saved--, pci++) {
+	if (pc[pci] == 0x57) {
+	  wad_saved_edi = *saved;
+	  /*	  printf("restored edi = %x\n", wad_saved_edi); */
+	}
+	else if (pc[pci] == 0x56) {
+	  wad_saved_esi = *saved;
+	  /*	  printf("restored esi = %x\n", wad_saved_esi); */
+	}
+	else if (pc[pci] == 0x53) {
+	  wad_saved_ebx = *saved;
+	  /*	  printf("restored ebx = %x\n", wad_saved_ebx); */
+	}
+	else break;
+      }
+    }
+  }
+}
+
+#endif
+
+void wad_signalhandler(int sig, siginfo_t *si, void *vcontext) {
+  greg_t  *pc;
+  greg_t  *npc;
+  greg_t  *sp;
+  greg_t  *fp;
+#ifdef WAD_LINUX
+  greg_t  *esi;
+  greg_t  *edi;
+  greg_t  *ebx;
+#endif
+
+  unsigned long   addr;
+  ucontext_t      *context;
+  unsigned long   p_sp;        /* process stack pointer   */
+  unsigned long   p_pc;        /* Process program counter */
+  unsigned long   p_fp;        /* Process frame pointer   */
+  int      nlevels = 0;
+  int      found = 0;
+  void     _returnsignal();
+  WadFrame  *frame, *origframe;
+  char      *framedata;
+  char      *retname = 0;
+  unsigned long current_brk;
+
+  /* Reset all of the signals while running WAD */
+  wad_signal_clear();
+
+  wad_nlr_func = 0;
+
+  context = (ucontext_t *) vcontext;
+
+  wad_printf("WAD: Collecting debugging information...\n");
+
+  /* Read the segments */
+  if (wad_segment_read() < 0) {
+    wad_printf("WAD: Unable to read segment map\n");
+    return;
+  }
+ 
+  if (wad_debug_mode & DEBUG_SIGNAL) {
+    wad_printf("WAD: siginfo = %x, context = %x\n", si, vcontext);
+  }
+  
+  current_brk = (long) sbrk(0);
+
+  /* Get some information about the current context */
+
+#ifdef WAD_SOLARIS
+  pc = &((context->uc_mcontext).gregs[REG_PC]);
+  npc = &((context->uc_mcontext).gregs[REG_nPC]);
+  sp = &((context->uc_mcontext).gregs[REG_SP]);
+#endif
+
+#ifdef WAD_LINUX
+  sp = &((context->uc_mcontext).gregs[ESP]);        /* Top of stack */
+  fp = &((context->uc_mcontext).gregs[EBP]);        /* Stack base - frame pointer */
+  pc = &((context->uc_mcontext).gregs[EIP]);        /* Current instruction */
+  esi = &((context->uc_mcontext).gregs[ESI]);       
+  edi = &((context->uc_mcontext).gregs[EDI]);       
+  ebx = &((context->uc_mcontext).gregs[EBX]);       
+  
+  wad_saved_esi = (unsigned long) (*esi);
+  wad_saved_edi = (unsigned long) (*edi);
+  wad_saved_ebx = (unsigned long) (*ebx);
+
+  /*  printf("esi = %x, edi = %x, ebx = %x\n", wad_saved_esi, wad_saved_edi, wad_saved_ebx); */
+
+  /*   printf("&sp = %x, &pc = %x\n", sp, pc); */
+#endif
+  
+  /* Get some information out of the signal handler stack */
+  addr = (unsigned long) si->si_addr;
+
+  /* See if this might be a stack overflow */
+
+  p_pc = (unsigned long) (*pc);
+  p_sp = (unsigned long) (*sp);
+#ifdef WAD_LINUX
+  p_fp = (unsigned long) (*fp);
+#endif
+#ifdef WAD_SOLARIS
+  p_fp = (unsigned long) *(((long *) p_sp) + 14);
+#endif
+  
+  if (wad_debug_mode & DEBUG_SIGNAL) {
+    wad_printf("fault at address %x, pc = %x, sp = %x, fp = %x\n", addr, p_pc, p_sp, p_fp);
+  }
+  frame = wad_stack_trace(p_pc, p_sp, p_fp);
+
+  if (!frame) {
+    /* We're really hosed.  Not possible to generate a stack trace */
+    wad_printf("WAD: Unable to generate stack trace.\n");
+    wad_printf("WAD: Maybe the call stack has been corrupted by buffer overflow.\n");
+    wad_signal_clear();
+    return;
+  }
+
+  {
+    WadFrame *f = frame;
+    while (f) {
+      wad_find_object(f);
+      wad_find_symbol(f);
+      f = f->next;
+    }
+    f = frame;
+    while (f) {
+      wad_find_debug(f);
+      wad_build_vars(f);
+      f = f->next;
+    }
+  }
+  wad_heap_overflow = 0;
+  if (sig == SIGSEGV) {
+    if (addr >= current_brk) wad_heap_overflow = 1;
+  }
+
+  wad_stack_debug(frame);
+
+  /* Generate debugging strings */
+  wad_debug_make_strings(frame);
+  
+  wad_stab_debug();
+
+  /* Walk the exception frames and try to find a return point */
+  origframe = frame;
+  while (frame) {
+    WadReturnFunc *wr = wad_check_return(frame->sym_name);
+    if (wr) {
+      found = 1;
+      wad_nlr_value = wr->value;
+      retname = wr->name;
+    }
+    if (found) {
+      frame->last = 1;   /* Cut off top of the stack trace */
+      break;
+    }
+    frame = frame->next;
+    nlevels++;
+  }
+  
+
+  if (found) {
+    wad_nlr_levels = nlevels - 1;
+#ifdef WAD_LINUX
+    wad_restore_i386_registers(origframe, wad_nlr_levels);
+#endif
+  } else {
+    wad_nlr_levels = -1;
+  }
+
+  wad_string_debug();
+  wad_memory_debug();
+
+  /* Before we do anything with callbacks, we are going
+     to attempt to dump a wad-core */
+  
+  {
+    int fd;
+    static int already = 0;
+    fd = open("wadtrace",O_WRONLY | O_CREAT | (already*O_APPEND) | ((already==0)*O_TRUNC),0666);
+    if (fd > 0) {
+      wad_dump_trace(fd,sig,origframe,retname);
+      close(fd);
+      already=1;
+    }
+  }
+
+  if (sig_callback) {
+    (*sig_callback)(sig,origframe,retname);
+  } else {
+    /* No signal handler defined.  Go invoke the default */
+
+    wad_default_callback(sig, origframe,retname);
+  }
+
+  if (wad_debug_mode & DEBUG_HOLD) while(1);
+
+  /* If we found a function to which we should return, we jump to
+     an alternative piece of code that unwinds the stack and 
+     initiates a non-local return. */
+
+  if (wad_nlr_levels >= 0) {
+    *(pc) = (greg_t) _returnsignal;
+#ifdef WAD_SOLARIS
+    *(npc) = *(pc) + 4;
+#endif
+    if (!(wad_debug_mode & DEBUG_ONESHOT)) {
+      wad_signal_init();
+    }
+    return;
+  }
+  exit(1);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * wad_signal_init()
+ *
+ * Resets the signal handler.
+ * ----------------------------------------------------------------------------- */
+
+void wad_signal_init() {
+  struct sigaction newvec;
+  static stack_t  sigstk;
+  static int      initstack = 0;
+
+  if (wad_debug_mode & DEBUG_INIT) {
+    wad_printf("WAD: Initializing signal handler.\n");
+  }
+  /* This is buggy in Linux and threads.  disabled by default */
+
+#ifndef WAD_LINUX
+
+  if (!initstack) {
+    /* Set up an alternative stack */
+    
+    sigstk.ss_sp = (char *) wad_sig_stack;
+    sigstk.ss_size = STACK_SIZE;
+    sigstk.ss_flags = 0;
+    if (!(wad_debug_mode & DEBUG_NOSTACK)) {
+      if (sigaltstack(&sigstk, (stack_t*)0) < 0) {
+	perror("sigaltstack");
+      }
+    }
+    initstack=1;
+  }
+#endif
+
+  sigemptyset(&newvec.sa_mask);
+  sigaddset(&newvec.sa_mask, SIGSEGV);
+  sigaddset(&newvec.sa_mask, SIGBUS);
+  sigaddset(&newvec.sa_mask, SIGABRT);
+  sigaddset(&newvec.sa_mask, SIGILL);
+  sigaddset(&newvec.sa_mask, SIGFPE);
+  newvec.sa_flags = SA_SIGINFO;
+
+  if (wad_debug_mode & DEBUG_ONESHOT) {
+    newvec.sa_flags |= SA_RESETHAND;
+  }
+#ifndef WAD_LINUX
+  if (!(wad_debug_mode & DEBUG_NOSTACK)) {
+    newvec.sa_flags |= SA_ONSTACK;
+  } 
+#endif
+  newvec.sa_sigaction = ((void (*)(int,siginfo_t *, void *)) wad_signalhandler);
+  if (sigaction(SIGSEGV, &newvec, NULL) < 0) goto werror;
+  if (sigaction(SIGBUS, &newvec, NULL) < 0) goto werror;
+  if (sigaction(SIGABRT, &newvec, NULL) < 0) goto werror;
+  if (sigaction(SIGFPE, &newvec, NULL) < 0) goto werror;
+  if (sigaction(SIGILL, &newvec, NULL) < 0) goto werror;
+  
+  return;
+ werror:
+  wad_printf("WAD: Couldn't install signal handler!\n");
+}
+
+/* -----------------------------------------------------------------------------
+ * clear signals 
+ * ----------------------------------------------------------------------------- */
+
+void wad_signal_clear() {
+  signal(SIGSEGV, SIG_DFL);
+  signal(SIGBUS, SIG_DFL);
+  signal(SIGILL, SIG_DFL);
+  signal(SIGFPE, SIG_DFL);
+  signal(SIGABRT, SIG_DFL);  
+}
+
+
+
diff --git a/trunk/Tools/WAD/Wad/stab.c b/trunk/Tools/WAD/Wad/stab.c
new file mode 100644
index 0000000..29626ae
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/stab.c
@@ -0,0 +1,682 @@
+/* ----------------------------------------------------------------------------- 
+ * stab.c
+ *
+ *     This file reads stabs data and looks for various properties of a 
+ *     given symbol.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* stabs data structure.   This appears to be somewhat universal. */
+typedef struct Stab {
+  unsigned        n_strx;         /* index into file string table */
+  unsigned char   n_type;         /* type flag (N_TEXT,..)  */
+  char            n_other;        /* used by N_SLINE stab */
+  unsigned short  n_desc;         /* see stabs documentation */
+  unsigned        n_value;        /* value of symbol (or sdb offset) */ 
+} Stab;
+
+/* stabs data types used by this module */
+
+#define N_UNDF      0x0           /* undefined         */
+#define N_FUN       0x24          /* function          */
+#define N_OBJ       0x38          /* object file path  */
+#define N_RSYM      0x40          /* Register symbol   */
+#define N_SLINE     0x44          /* Source line       */
+#define N_SO        0x64          /* Source file name  */
+#define N_LSYM      0x80          /* Local symbol      */
+#define N_PSYM      0xa0          /* Parameter         */
+#define N_LBRAC     0xc0          /* Left brace        */
+#define N_RBRAC     0xe0          /* Right brace       */
+
+/* -----------------------------------------------------------------------------
+ * stabs type handler
+ *
+ * Type names are defined as N_LSYM types.   We need to keep a hash table of
+ * logical type names and stabs type names.
+ *
+ * We also need to keep a hash table of stabs types.
+ * ----------------------------------------------------------------------------- */
+
+typedef struct stabtype {
+  char             *name;
+  char             *value;
+  struct stabtype  *next;
+  int               visit;
+} stabtype;
+
+#define HASH_SIZE    113
+
+static int       stab_type_init = 0;
+static stabtype *lnames[HASH_SIZE];      /* Hash of local names */
+static stabtype  *deadnames[HASH_SIZE];  /* Hash of dead names */
+
+/* Initialize the hash table */
+
+static void init_hash() {
+  int i;
+  stabtype *s, *sp = 0;
+
+  for (i = 0; i < HASH_SIZE; i++) {
+    if (stab_type_init) {
+      /* Add stabs to dead list */
+      s = lnames[i];
+      sp = 0;
+      while (s) {
+	sp = s;
+	s = s->next;
+      }
+      if (sp) {
+	sp->next = deadnames[i];
+	deadnames[i] = lnames[i];
+      }
+    }
+    lnames[i] = 0;
+  }
+  stab_type_init = 1;
+}
+
+static int thash(char *name) {
+  unsigned int h = 0;
+  int i;
+  for (i = 0; i < 8 && (*name); i++, name++) {
+    h = ((h << 7) + *name);
+  }
+  return (h % HASH_SIZE);
+}
+
+/* Add a symbol to the hash */
+
+static void type_add(char *name, char *value) {
+  int h;
+  stabtype *s;
+  char      sc =0;
+  char     *v;
+  char     *vr;
+  char     *split;
+
+  if (!stab_type_init) {
+    init_hash();
+    stab_type_init = 1;
+  }
+
+  /* Split the "value" up into a type name and a value */
+  
+  split = strchr(value,'=');
+  if (value[0] != '(') split = 0;
+  if (split) {
+    sc = *split;
+    v = value;
+    *split = 0;
+    vr = split+1;
+  } else {
+    v = value;
+    sc = 0;
+    vr = 0;
+  }
+
+  h = thash(name);
+  s = lnames[h];
+  while (s) {
+    if (strcmp(s->name,name) == 0) {
+      if (strcmp(s->value,v)) {
+	s->value = wad_string_lookup(v);
+      }
+      goto add_more;
+    }
+    s = s->next;
+  }
+  s = deadnames[h];
+  if (!s) {
+    s = (stabtype *) wad_malloc(sizeof(stabtype));
+  } else {
+    deadnames[h] = s->next; 
+  }
+  s->name = wad_string_lookup(name);
+  s->value = wad_string_lookup(v);
+  s->next = lnames[h];
+  s->visit = 0;
+  lnames[h] = s;
+
+  /* Now take a look at the value.   If it is contains other types, we might be able to define more stuff */
+ add_more:
+  if (vr) {
+    /* There is a mapping to another type */
+    type_add(v,vr);
+  }
+}
+
+static
+char *type_resolve(char *name) {
+  int h;
+  stabtype *s;
+  h = thash(name);
+  s = lnames[h];
+  while(s) {
+    if (strcmp(s->name,name) == 0) {
+      if (!s->visit) {
+	char *c;
+	/* The visit flag is set so that we don't get in infinite loops */
+	s->visit = 1;
+	c = type_resolve(s->value);
+	s->visit = 0;
+	return c;
+      } else {
+	return name;
+      }
+    }
+    s = s->next;
+  }
+  return name;
+}  
+
+/* This function tries to resolve base stabs types into a machine equivalent */
+static
+int type_typecode(char *name) {
+  char *range;
+
+  if (name[0] == '*') {
+    return WAD_TYPE_POINTER;
+  }
+
+  range = strchr(name,';');
+  if (!range) return WAD_TYPE_UNKNOWN;
+  range++;
+
+  if (name[0] == 'r') {
+    /* GNU-style range specifiers */
+    if (
+	(strcmp(range,"0000000000000;0037777777777;") == 0)
+	) {
+      return WAD_TYPE_UINT32;
+    }
+    if (
+	(strcmp(range,"0020000000000;0017777777777;") == 0)
+	) {
+      return WAD_TYPE_INT32;
+    }
+    if (
+	(strcmp(range,"-32768;32767;") == 0)
+	) {
+      return WAD_TYPE_INT16;
+    }
+    if (
+	(strcmp(range,"0;65535;") == 0) 
+	) {
+      return WAD_TYPE_UINT16;
+    }
+    if (
+	(strcmp(range,"0;127;") == 0)
+	) {
+      return WAD_TYPE_CHAR;
+    }
+    if (
+	(strcmp(range,"-128;127;") == 0)
+	) {
+      return WAD_TYPE_INT8;
+    }
+    if (
+	(strcmp(range,"0;255;") == 0) 
+	) {
+      return WAD_TYPE_UINT8;
+    }
+    if (
+	(strcmp(range,"4;0;") == 0)
+	) {
+      return WAD_TYPE_FLOAT;
+    }
+    if (
+	(strcmp(range,"8;0;") == 0)
+	) {
+      return WAD_TYPE_DOUBLE;
+    }
+  }
+  /* Traditional built-in types */
+  if (strcmp(name,"bs4;0;32;") == 0) {
+    return WAD_TYPE_INT32;
+  } 
+  if (strcmp(name,"bs2;0;16;") == 0) {
+    return WAD_TYPE_INT16;
+  }
+  if (strcmp(name,"bs1;0;8;") == 0) {
+    return WAD_TYPE_INT8;
+  }
+  if (strcmp(name,"bsc1;0;8;") == 0) {
+    return WAD_TYPE_CHAR;
+  }
+  if (strcmp(name,"bu4;0;32;") == 0) {
+    return WAD_TYPE_UINT32;
+  }
+  if (strcmp(name,"bu2;0;16;") == 0) {
+    return WAD_TYPE_UINT16;
+  }
+  if (strcmp(name,"bu1;0;8;") == 0) {
+    return WAD_TYPE_UINT8;
+  }
+  if (strcmp(name,"R1;4;") == 0) {
+    return WAD_TYPE_FLOAT;
+  }
+  if (strcmp(name,"R2;8;") == 0) {
+    return WAD_TYPE_DOUBLE;
+  }
+  return WAD_TYPE_UNKNOWN;
+}
+
+static void types_print() {
+  stabtype *s;
+  int i;
+  for (i = 0; i < HASH_SIZE; i++) {
+    s = lnames[i];
+    while (s) {
+      wad_printf("%20s  %s\n", s->name, s->value);
+      s = s->next;
+    }
+  }
+}
+
+void wad_stab_debug() {
+  /*  types_print();*/
+}
+
+/* -----------------------------------------------------------------------------
+ * match_stab_symbol()
+ *
+ * Match a stabs symbol name against a stab string.  The stab string may contain
+ * extra information delimited by a colon which is not used in the comparsion.
+ * Returns 1 on match, 0 on mismatch.
+ * ----------------------------------------------------------------------------- */
+
+static int
+match_stab_symbol(char *symbol, char *stabtext, int slen) {
+  if (strcmp(symbol,stabtext) == 0) {
+    return 1;
+  }
+  if ((strncmp(symbol, stabtext, slen) == 0) && (*(stabtext+slen) == ':')) return 1;
+  return 0;
+}
+
+static char *
+stab_string_parm(char *str) {
+  return strchr(str,':');
+}
+
+/* -----------------------------------------------------------------------------
+ * stab_symbol(Stab *s, char *stabstr)
+ *
+ * Process stab symbol specifier N_LSYM
+ * ----------------------------------------------------------------------------- */
+
+static void
+stab_symbol(Stab *s, char *stabstr) {
+  char *str;
+  char *pstr;
+  char name[1024]; 
+  char value[65536];
+
+  str = stabstr+s->n_strx;
+  pstr = stab_string_parm(str);
+  if (!pstr) return;
+  
+  strncpy(name,str, pstr-str);
+  name[(int)(pstr-str)] = 0;
+  if ((pstr[1] == 't') || (pstr[1] == 'p') || (pstr[1] == 'r')) {
+    /* A stabs type definition */
+    /*    printf("stab lsym:  other=%d, desc=%d, value=%d, str='%s'\n", s->n_other,s->n_desc,s->n_value,
+	  stabstr+s->n_strx); */
+    /*    wad_printf("name = '%s', pstr='%s'\n", name, pstr+2); */
+    wad_strcpy(value,pstr+2);
+    type_add(name,value);
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * scan_function()
+ *
+ * Collect stabs data for a function definition.
+ * ----------------------------------------------------------------------------- */
+
+static int
+scan_function(Stab *s, char *stabstr, int ns, WadFrame *f) {
+  int i;
+  unsigned long offset;
+  int      get_parms = 1;
+  int      nbrace = 0;
+
+  offset = f->pc - f->sym_base;
+  if (wad_debug_mode & DEBUG_STABS) {
+    wad_printf("---[ %s ] --------------\n", f->sym_name);
+  }
+  
+  for (i = 0; i < ns; i++,s++) {
+    if (wad_debug_mode & DEBUG_STABS) {
+      wad_printf("   %10d %10x %10d %10d %10d: '%s'\n", s->n_strx, s->n_type, s->n_other, s->n_desc, s->n_value, 
+	     stabstr+s->n_strx);
+      
+    }
+    
+    if ((s->n_type == N_UNDF) || (s->n_type == N_SO) || /* (s->n_type == N_FUN) || */
+	(s->n_type == N_OBJ)) return i;
+
+    if ((s->n_type == N_FUN) && !(strlen(stabstr+s->n_strx))) return 1;
+
+    if (s->n_type == N_LBRAC) {
+      nbrace++;
+      get_parms = 0;
+    }
+    if (s->n_type == N_RBRAC) {
+      nbrace--;
+      if (nbrace <= 0) return i;
+    }
+    /* Local variable declaration */
+
+    if (s->n_type == N_LSYM) {
+      /* This might be a local variable definition */
+      /*      wad_printf("local: n_value = %d, offset = %d\n", s->n_value, offset);*/
+      if (s->n_desc <= f->loc_line)
+      {
+	/* Okay. We can pay attention to it */
+	char *pname;
+	char *c;
+	int   len;
+	WadLocal *arg, *a;
+	pname = stabstr+s->n_strx;
+	c = strchr(pname,':');
+	if (*(c+1) != '(') continue;
+	if (c) {
+	  len = (c-pname);
+	} else {
+	  len = strlen(pname);
+	}
+	/*	printf("local\n"); */
+	stab_symbol(s,stabstr);
+	a = f->debug_locals;
+	while (a) {
+	  if ((strncmp(a->name,pname,len) == 0) && (strlen(a->name) == len)) {
+	    /* We already saw this argument.  Given a choice between a register and a stack
+	       argument.  We will choose the stack version */
+	    a->loc = PARM_STACK;
+	    a->stack = s->n_value;
+	    break;
+	  }
+	  a = a->next;
+	}
+	if (a) continue; /* We got an argument match.  Just skip to the next stab */
+	arg = (WadLocal *) wad_malloc(sizeof(WadLocal));
+	{
+	  char t = pname[len];
+	  pname[len] = 0;
+	  arg->name = wad_string_lookup(pname);
+	  pname[len] = t;
+	}
+	arg->loc = PARM_STACK;
+	arg->line = s->n_desc;
+	arg->stack = s->n_value;
+	arg->type = 0;
+	arg->next = 0;
+	{
+	  char tname[128];
+	  char *t = tname;
+	  
+	  c+=1;
+	  while ((*c) && (*c != '=')) {
+	    *t++ = *c++;
+	  }
+	  *t = 0;
+	  t = type_resolve(tname);
+	  arg->type = type_typecode(t);
+	  if (wad_debug_mode & DEBUG_STABS) {
+	    wad_printf("type_resolve '%s' -> '%s' (%d)\n", tname, t, arg->type);
+	  }
+	}
+	if (f->debug_locals) {
+	  f->debug_lastlocal->next = arg;
+	  f->debug_lastlocal = arg;
+	} else {
+	  f->debug_locals = arg;
+	  f->debug_lastlocal = arg;
+	  f->debug_nlocals= 0;
+	}
+	f->debug_nlocals++;
+      }
+    }
+
+    if (s->n_type == N_SLINE) {
+      get_parms = 0;
+      if (s->n_value <= offset) {
+	f->loc_line = s->n_desc;
+      }
+    } else if (((s->n_type == N_PSYM) || (s->n_type == N_RSYM)) && get_parms) {
+      /* Parameter counting */
+      char *pname;
+      char *c;
+      int   len;
+      WadLocal *arg;
+      pname = stabstr+s->n_strx;
+      c = strchr(pname,':');
+      if (c) {
+	len = (c-pname);
+      } else {
+	len = strlen(pname);
+      }
+      /* Get type information */
+      
+      stab_symbol(s,stabstr);
+      
+      /* Check if the argument was already used */
+      /* In this case, the first stab simply identifies an argument.  The second
+	 one identifies its location for the debugger */
+      
+      {
+	/* Need to do some fix up for linux here */
+	WadLocal *a = f->debug_args;
+	while (a) {
+	  if ((strncmp(a->name,pname,len) == 0) && (strlen(a->name) == len)) {
+	    /* We already saw this argument.  Given a choice between a register and a stack
+	       argument.  We will choose the stack version */
+	    
+	    if (a->loc == PARM_STACK) {
+	      break;
+	    }
+	    /* Go ahead and use the new argument */
+	    if (s->n_type == N_RSYM) {
+	      a->loc = PARM_REGISTER;
+	      a->reg = s->n_value;
+	    } else {
+	      a->loc = PARM_STACK;
+	      a->stack = s->n_value;
+	    }
+	    break;
+	  }
+	  a = a->next;
+	}
+	if (a) continue; /* We got an argument match.  Just skip to the next stab */
+      }
+	
+      arg = (WadLocal *) wad_malloc(sizeof(WadLocal));
+      {
+	char t = pname[len];
+	pname[len] = 0;
+	arg->name = wad_string_lookup(pname);
+	pname[len] = t;
+      }
+      if (s->n_type == N_RSYM) {
+	arg->loc = PARM_REGISTER;
+	arg->reg = s->n_value;
+	arg->stack = 0;
+      } else {
+	arg->loc = PARM_STACK;
+	arg->line = s->n_desc;
+	arg->stack = s->n_value;
+      }
+      arg->type = 0;
+      arg->next = 0;
+      {
+	char tname[128];
+	char *t = tname;
+	
+	c+=2;
+	while ((*c) && (*c != '=')) {
+	  *t++ = *c++;
+	}
+	*t = 0;
+	t = type_resolve(tname);
+	arg->type = type_typecode(t);
+	if (wad_debug_mode & DEBUG_STABS) {
+	  wad_printf("type_resolve '%s' -> '%s' (%d)\n", tname, t, arg->type);
+	}
+      }
+      if (f->debug_args) {
+	f->debug_lastarg->next = arg;
+	f->debug_lastarg = arg;
+      } else {
+	f->debug_args = arg;
+	f->debug_lastarg = arg;
+	f->debug_nargs= 0;
+      }
+      f->debug_nargs++;
+    }
+  }
+  return i;
+}
+
+/* Given a stabs data segment (obtained somehow), this function tries to
+   collect as much information as it can about a given symbol. 
+
+   s points to the stab data.  stabstr points to the stab string section,
+   ns is the size of the stab section, symbol is the item of interest,
+   and offset is the offset in the object file of the symbol
+
+   Note: this function may recurse upon itself if there are multiple
+   stabs sections.
+
+   Note: If a symbol corresponds to a local symbol, it's entirely possible
+   that the only stabs data we will find is a file specifier. In this case,
+ */
+
+int
+wad_search_stab(void *sp, int size, char *stabstr, WadFrame *f) {
+  Stab *s;
+  int   ns;
+  int   i;
+  int   found = 0;
+
+  char  *file, *lastfile = 0;
+
+  char   srcfile[MAX_PATH];
+  char   objfile[MAX_PATH];
+
+  /* It appears to be necessary to clear the types table on each new stabs section */
+
+  init_hash();
+
+  if (!f->sym_name) return 0;
+
+  s = (Stab *) sp;            /* Stabs data      */
+  ns = size/sizeof(Stab);     /* number of stabs */
+
+  srcfile[0] = 0;
+  objfile[0] = 0;
+
+  for (i = 0; i < ns; i++, s++) {
+    if (wad_debug_mode & DEBUG_STABS) {
+      /*      wad_printf("   %10d %10x %10d %10d %10d: '%s'\n", s->n_strx, s->n_type, s->n_other, s->n_desc, s->n_value, 
+	      stabstr+s->n_strx); */
+      
+	     }
+    if (s->n_type == N_LSYM) {
+      stab_symbol(s,stabstr);
+      continue;
+    }
+    if ((s->n_type == N_UNDF)) { /* && (s->n_desc >= 0)) { */
+      /* New stabs section.  We need to be a little careful here. Do a recursive 
+	 search of the subsection. */
+
+      if (wad_search_stab(s+1,s->n_desc*sizeof(Stab), stabstr, f)) {
+	return 1;
+      }
+
+      /* On solaris, each stabs section seems to increment the stab string pointer.  On Linux,
+         the linker seems to do a certain amount of optimization that results in a single
+         string table. */
+
+#ifdef WAD_SOLARIS
+      stabstr += s->n_value;     /* Update the string table location*/
+#endif
+      i += s->n_desc;
+      s += s->n_desc;
+      objfile[0] = 0;
+      srcfile[0] = 0;
+      continue;
+    } else if (s->n_type == N_SO) {
+      /* Source file specification */
+      /* Look for directory */
+      file = stabstr+s->n_strx;
+      if (strlen(file) && (file[strlen(file)-1] == '/')) {
+	wad_strcpy(srcfile,file);
+      } else {
+	wad_strcat(srcfile,file);
+      }
+      objfile[0] = 0;
+      /* If we have a file match, we might be looking for a local symbol.   If so,
+         we'll go ahead and set the srcfile field of the frame */
+
+      /* We're going to check for a file match. Maybe we're looking for a local symbol */
+      if (f->sym_file && strcmp(f->sym_file,file) == 0) {
+	found = 1;
+      }
+      lastfile = file;
+    } else if (s->n_type == N_OBJ) {
+      /* Object file specifier */
+      if (objfile[0]) {
+	wad_strcat(objfile,"/");
+      }
+      wad_strcat(objfile,stabstr+s->n_strx);
+    } else if (s->n_type == N_FUN) {
+      if (match_stab_symbol(f->sym_name, stabstr+s->n_strx, f->sym_nlen)) {
+	  if (!f->sym_file || (strcmp(f->sym_file,lastfile) == 0)) {
+	    int n;
+	    /* Go find debugging information for the function */
+	    n = scan_function(s+1, stabstr, ns -i - 1, f);
+	    f->loc_srcfile = wad_string_lookup(srcfile);
+	    f->loc_objfile = wad_string_lookup(objfile);
+	    return 1;
+	  }
+      }
+    }
+  }
+  /* If found, but no other debugging information was filled in, go ahead and copy the
+     source and objfile information */
+  
+  if ((found) && (!f->debug_check)) {
+    f->loc_srcfile = wad_string_lookup(srcfile);
+    f->loc_objfile = wad_string_lookup(objfile);
+  }
+  return found;
+}
+
+
+
+
diff --git a/trunk/Tools/WAD/Wad/stack.c b/trunk/Tools/WAD/Wad/stack.c
new file mode 100644
index 0000000..68a55a7
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/stack.c
@@ -0,0 +1,309 @@
+/* ----------------------------------------------------------------------------- 
+ * stack.c
+ *
+ *     This file unwinds the C call stack and creates a list of stack frames.
+ *
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* -----------------------------------------------------------------------------
+ * new_frame()
+ *
+ * Create a new stack frame object and initialize all of the fields.
+ * ----------------------------------------------------------------------------- */
+
+static WadFrame *
+new_frame() {
+  WadFrame *f;
+  f = (WadFrame *) wad_malloc(sizeof(WadFrame));
+  f->frameno = 0;
+  f->segment = 0;
+  f->object = 0;
+  f->pc = 0;
+  f->sp = 0;
+  f->sp = 0;
+  f->stack = 0;
+  f->stack_size = 0;
+
+  f->sym_name = 0;
+  f->sym_nlen = 0;
+  f->sym_file = 0;
+  f->sym_base = 0;
+  f->sym_size = 0;
+  f->sym_type = 0;
+  f->sym_bind = 0;
+
+  f->loc_objfile = 0;
+  f->loc_srcfile = 0;
+  f->loc_line = 0;
+
+  f->debug_check = 0;
+  f->debug_nargs = -1;
+  f->debug_args = 0;
+  f->debug_lastarg = 0;
+  f->debug_nlocals = 0;
+  f->debug_locals = 0;
+  f->debug_lastlocal = 0;
+  f->debug_str = 0;
+  f->debug_srcstr = 0;
+
+  f->last = 0;
+  f->next = 0;
+  f->prev = 0;
+  return f;
+}
+
+/* -----------------------------------------------------------------------------
+ * stack_unwind()
+ *
+ * This function performs a single level of stack unwinding given the stack pointer
+ * frame pointer and program counter.   Validations are made to make sure the stack
+ * and frame pointers are in valid memory.  Updates the values of the sp, pc, and fp
+ * in-place.  Returns a stack frame object on success, 0 if memory is invalid
+ * or the end of the stack has been reached.
+ * ----------------------------------------------------------------------------- */
+
+static WadFrame *
+stack_unwind(unsigned long *pc, unsigned long *sp, unsigned long *fp) {
+  WadSegment *sp_seg, *fp_seg;
+  WadFrame   *f;
+  unsigned   long fake_fp;
+
+  if (wad_debug_mode & DEBUG_UNWIND) {
+    wad_printf("::: stack unwind :  pc = %x, sp = %x, fp = %x\n", *pc, *sp, *fp);
+  }
+
+  /* Verify that the sp and fp are in mapped memory */
+  sp_seg = wad_segment_find((void *) *sp);
+  fp_seg = wad_segment_find((void *) *fp);
+
+  /* Make sure the stack pointer is in memory */
+  if (!sp_seg) {
+    return 0;
+  }
+
+  if (!fp_seg) {
+    /* Hmmm. If no frame pointer, we must be off the top of the call stack */
+    fake_fp = (unsigned long) (sp_seg->vaddr + sp_seg->size);
+    fp_seg = sp_seg;
+  } else {
+    fake_fp = *fp;
+  }
+  if (sp_seg != fp_seg) {
+    /* Whoa. Stack pointer and frame pointer are in different memory segments. */
+    wad_printf("WAD: Warning. Stack pointer and frame pointer are in different regions.\n");
+    return 0;
+  }
+
+  /* Check to see if the PC is valid */
+  if (!wad_segment_valid((void *) *pc)) {
+    return 0;
+  }
+
+  f = new_frame();
+  f->pc = *pc;
+  f->sp = *sp;
+  f->fp = fake_fp;
+  f->segment = wad_segment_find((void *) *pc);
+  f->stack_size = fake_fp - *sp;
+  /* Make a copy of the call stack */
+  f->stack = (char *) wad_malloc(f->stack_size);
+  wad_memcpy(f->stack,(void *) *sp, f->stack_size);
+
+  /* Update the sp, fp, and pc */
+
+#ifdef WAD_SOLARIS
+  *pc = *((unsigned long *) *sp+15);         /* %i7 - Return address  */
+  *sp = *((unsigned long *) *sp+14);         /* %i6 - frame pointer   */
+  if (wad_segment_valid((void *) *sp)) {
+    *fp = *((unsigned long *) *sp+14);
+  } else {
+    *fp = 0;
+  }
+#endif
+
+#ifdef WAD_LINUX
+  if (wad_segment_valid((void *) ((unsigned long *) *fp+1))) {
+    *pc = *((unsigned long *) *fp+1); 
+    *sp = *fp;
+  } else {
+    *sp = 0;
+  }
+  if (wad_segment_valid((void *) ((unsigned long *) *fp))) {
+    *fp = *((unsigned long *) *fp);
+  } else {
+    *fp = 0;
+  }
+#endif
+  return f;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_stack_trace()
+ *
+ * Create a stack trace of the process. Returns a linked list of stack frames
+ * with a limited about debugging information and other details.
+ * ----------------------------------------------------------------------------- */
+
+WadFrame *
+wad_stack_trace(unsigned long pc, unsigned long sp, unsigned long fp) {
+  WadFrame        *firstframe=0, *lastframe=0, *frame=0;
+  unsigned long   p_pc;
+  unsigned long   p_sp;
+  unsigned long   p_fp;
+  int             n = 0;
+
+  /* Try to do a stack traceback */
+
+  p_pc = pc;
+  p_sp = sp;
+  p_fp = fp;
+
+  while ((frame = stack_unwind(&p_pc, &p_sp, &p_fp))) {
+    /* Got a frame successfully */
+    frame->frameno = n;
+    if (lastframe) {
+      lastframe->next = frame;
+      frame->prev = lastframe;
+      lastframe = frame;
+    } else {
+      firstframe = frame;
+      lastframe = frame;
+    }
+    n++;
+  }
+  if (lastframe)
+    lastframe->last = 1;
+  return firstframe;
+}
+
+/* -----------------------------------------------------------------------------
+ * wad_stack_debug() 
+ *
+ * Make a dump of a stack trace
+ * ----------------------------------------------------------------------------- */
+
+void wad_stack_debug(WadFrame *frame) {
+  if (wad_debug_mode & DEBUG_STACK) {
+    /* Walk the exception frames and try to find a return point */
+    while (frame) {
+      /* Print out detailed stack trace information */
+      wad_printf("::: Stack frame - 0x%08x :::\n", frame);
+      wad_printf("    pc           = %x\n", frame->pc);
+      wad_printf("    sp           = %x\n", frame->sp);
+      wad_printf("    fp           = %x\n", frame->fp);
+      wad_printf("    stack        = %x\n", frame->stack);
+      wad_printf("    size         = %x\n", frame->stack_size);
+      wad_printf("    segment      = %x (%s)\n", frame->segment, frame->segment ? frame->segment->mappath : "?");
+      wad_printf("    object       = %x (%s)\n", frame->object, frame->object ? frame->object->path : "?");
+
+      if (frame->sym_name) {
+	wad_printf("    sym_name     = %s\n", frame->sym_name);
+	wad_printf("    sym_base     = %x\n", frame->sym_base);
+	wad_printf("    sym_size     = %x\n", frame->sym_size);
+	wad_printf("    sym_bind     = %x\n", frame->sym_bind);
+	wad_printf("    sym_file     = %s\n", frame->sym_file ? frame->sym_file : "");
+      }
+
+      if (frame->loc_srcfile) {
+	wad_printf("    loc_srcfile  = %s\n", frame->loc_srcfile);
+      }
+
+      if (frame->loc_objfile) {
+	wad_printf("    loc_objfile  = %s\n", frame->loc_objfile);
+      }
+      wad_printf("    loc_line     = %d\n", frame->loc_line);
+
+
+      wad_printf("    debug_nargs  = %d\n", frame->debug_nargs);
+      if (frame->debug_args) {
+	int i = 0;
+	WadLocal *p = frame->debug_args;
+	wad_printf("    debug_args = [ \n");
+	while (p) {
+	  wad_printf("        arg[%d] : name = '%s', loc = %d, type = %d, stack = %d, reg = %d, line=%d, ptr=%x(%d)\n", i, p->name, p->loc, p->type, p->stack,p->reg,p->line,p->ptr,p->size);
+	  p = p->next;
+	}
+      }
+      wad_printf("    ]\n");
+
+      wad_printf("    debug_nlocal  = %d\n", frame->debug_nlocals);
+      if (frame->debug_locals) {
+	int i = 0;
+	WadLocal *p = frame->debug_locals;
+	wad_printf("    debug_locals = [ \n");
+	while (p) {
+	  wad_printf("        loc[%d] : name = '%s', loc = %d, type = %d, stack = %d, reg = %d, line=%d, ptr=%x(%d)\n", i, p->name, p->loc, p->type, p->stack,p->reg,p->line,p->ptr,p->size);
+	  p = p->next;
+	}
+      }
+      wad_printf("    ]\n");
+
+      frame = frame->next;
+    }
+  }
+}
+
+
+/* -----------------------------------------------------------------------------
+ * wad_steal_outarg()
+ *
+ * Steal an output argument
+ * ----------------------------------------------------------------------------- */
+
+long 
+wad_steal_outarg(WadFrame *f, char *symbol, int argno, int *error) {
+  long *regs;
+  WadFrame *lastf = 0;
+
+  *error = 0;
+  /* Start searching */
+  while (f) {
+    if (f->sym_name && (strcmp(f->sym_name,symbol) == 0)) {
+      /* Got a match */
+      if (lastf) {
+#ifdef WAD_SOLARIS
+	regs = (long *) lastf->stack;
+	return regs[8+argno];
+#endif
+#ifdef WAD_LINUX
+	regs = (long *) f->stack;
+	return regs[argno+2];
+#endif
+      }
+    }
+    lastf = f;
+    f = f->next;
+  }
+  *error = -1;
+  return 0;
+}
+
+
+
+
+
+
+
diff --git a/trunk/Tools/WAD/Wad/string.c b/trunk/Tools/WAD/Wad/string.c
new file mode 100644
index 0000000..1a15878
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/string.c
@@ -0,0 +1,131 @@
+/* ----------------------------------------------------------------------------- 
+ * string.c
+ *
+ *    This file provides support for string storage in WAD.  Since strings are
+ *    used frequently in WAD, this file implements string interning and
+ *    some lookup functions that can be used to return a previously stored
+ *    string rather than making a new copy.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* Hash table containing stab strings and such */
+typedef struct stringtype {
+  char             *str;
+  struct stringtype *next;
+} stringtype;
+
+#define STRING_HASH_SIZE  1013
+
+static stringtype *strings[STRING_HASH_SIZE];
+static int         strings_init = 0;
+
+static int shash(char *name) {
+  unsigned int h = 0;
+  char *c;
+  int i;
+  c = name;
+  for (i = 0; (i < 16) && (*c); i++, c++) {
+    h = ((h^~i) << 6) + *c;
+  }
+  return h % STRING_HASH_SIZE;
+}
+
+char *
+wad_string_lookup(char *s) {
+  int h;
+  int i;
+  stringtype *st;
+
+  if (!strings_init) {
+    for (i = 0; i < STRING_HASH_SIZE; i++) {
+      strings[i] = 0;
+    }
+    strings_init = 1;
+  }
+  
+  h = shash(s);
+  st = strings[h];
+  while (st) {
+    if (strcmp(st->str,s) == 0) return st->str;
+    st = st->next;
+  }
+  
+  /* Not found. Add the string to the hash table */
+  st = (stringtype *) wad_malloc(sizeof(stringtype));
+  st->str = wad_strdup(s);
+  st->next = strings[h];
+  strings[h] = st;
+  return st->str;
+}
+
+void wad_string_debug() {
+  if (wad_debug_mode & DEBUG_STRING) {
+    int maxdepth = 0;
+    int total = 0;
+    int stringlen = 0;
+    int i;
+
+    for (i = 0; i < STRING_HASH_SIZE; i++) {
+      stringtype *s;
+      int c = 0;
+      s = strings[i];
+      while (s) {
+	c++;
+	stringlen += strlen(s->str);
+	s = s->next;
+      }
+      /*      wad_printf("WAD: stringhash[%d] = %d\n", i, c);*/
+      if (c > maxdepth) maxdepth = c;
+      total += c;
+    }
+    wad_printf("WAD: nstrings = %d (%d bytes)\n", total, stringlen + total*sizeof(stringtype));
+    wad_printf("WAD: maxdepth = %d\n", maxdepth);
+    }
+}
+
+/* Our own string copy */
+char *wad_strcpy(char *t, const char *s) {
+  if (s)
+    for (; *s; s++, t++) *t = *s;
+  *t = 0;
+  return t;
+}
+
+char *
+wad_strcat(char *t, const char *s) {
+  while (*t) t++;
+  return wad_strcpy(t,s);
+}
+
+int
+wad_strlen(const char *s) {
+  int count = 0;
+  while (*(s++)) count++;
+  return count;
+}
+
+
+
diff --git a/trunk/Tools/WAD/Wad/vars.c b/trunk/Tools/WAD/Wad/vars.c
new file mode 100644
index 0000000..b22f717
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/vars.c
@@ -0,0 +1,271 @@
+/* ----------------------------------------------------------------------------- 
+ * vars.c
+ *
+ *     This file examines the stack trace and tries to make some sense out of
+ *     collected debugging information.  This includes locating the data on
+ *     the stack and/or registers. 
+ *
+ *     This feature is detached from the debugging info collector to make
+ *     it independent of debugging formats.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago. 
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * 
+ * See the file COPYING for a complete copy of the LGPL.
+ * ----------------------------------------------------------------------------- */
+
+#include "wad.h"
+
+static char cvs[] = "$Id$";
+
+/* -----------------------------------------------------------------------------
+ * wad_build_vars()
+ *
+ * Build variable information for a single stack frame
+ * ----------------------------------------------------------------------------- */
+ 
+void wad_build_vars(WadFrame *f) {
+  char *stack = 0;
+  char *nstack = 0;
+  char *pstack = 0;
+  WadLocal  *loc;
+  int   n;
+
+  stack = (char *) f->stack;
+  if (f->next) {
+    nstack = (char *) f->next->stack;
+  }
+  if (f->prev) {
+    pstack = (char *) f->prev->stack;
+  }
+
+  for (n = 0; n < 2; n++) {
+    if (n == 0) loc = f->debug_args;
+    else loc = f->debug_locals;
+
+    while (loc) {
+      loc->ptr = 0;
+      if (loc->loc == PARM_STACK) {
+	if ((loc->stack >= 0) && (nstack)) {
+	  loc->ptr = (void *) (nstack + loc->stack);
+	} else if (loc->stack < 0) {
+	  loc->ptr = (void *) (stack + f->stack_size + loc->stack);
+	}
+	loc->size = sizeof(long);
+      }
+      if (loc->loc == PARM_REGISTER) {
+	/* Parameter is located in a register */
+#ifdef WAD_SOLARIS
+	if ((loc->reg >= 24) && (loc->reg < 32)) {
+	  /* Value is located in the %in registers.  */
+	  loc->ptr = (void *) (stack + (loc->reg - 16)*sizeof(int));
+	  loc->size = sizeof(int);
+	} else if ((loc->reg >= 8) && (loc->reg < 16)) {
+	  
+          /* Value is located in the %on registers */
+	  if (nstack) {
+	    loc->ptr = (void *) (stack + (loc->reg)*sizeof(int));
+	    loc->size = sizeof(int);
+	  }
+	} else if ((loc->reg >= 16) && (loc->reg < 24)) {
+	  /* Value has been placed in the %ln registers */
+	  loc->ptr = (void *) (stack + (loc->reg - 16)*sizeof(int));
+	  loc->size = sizeof(int);
+	}
+#endif
+      }
+      loc = loc->next;
+    }
+  }
+}
+
+/* This function creates a formatted integer given a pointer, size, and sign flag */
+static
+char *wad_format_int(char *ptr, int nbytes, int sgn) {
+  static char fmt[128];
+  unsigned char   *s;
+  int     incr;
+  unsigned long value = 0;
+  int     i;
+
+#ifdef WAD_LITTLE_ENDIAN
+  s = (unsigned char *) (ptr + nbytes - 1);
+  incr = -1;
+#else
+  s = (unsigned char *) (ptr);
+  incr = +1;
+#endif
+  for (i = 0; i < nbytes; i++, s += incr) {
+    value = (value << 8) + *s;
+  }
+  if (sgn) {
+    return wad_format_signed((long) value,-1);
+  } else {
+    return wad_format_unsigned((unsigned long) value, -1);
+  }
+  return fmt;
+}
+
+/* Try to make a formatted version of a local */
+char *wad_format_var(WadLocal *l) {
+  static char hexdigits[] = "0123456789abcdef";
+  static char buffer[1024];
+  double dval;
+  float  fval;
+
+  buffer[0] = 0;
+
+  switch(l->type) {
+  case WAD_TYPE_INT32:
+    wad_strcpy(buffer,wad_format_int(l->ptr,4,1));
+    break;
+  case WAD_TYPE_UINT32:
+    wad_strcpy(buffer,wad_format_int(l->ptr,4,0));
+    break;
+  case WAD_TYPE_INT16:
+    wad_strcpy(buffer,wad_format_int(l->ptr,2,1));
+    break;
+  case WAD_TYPE_UINT16:
+    wad_strcpy(buffer,wad_format_int(l->ptr,2,0));
+    break;
+  case WAD_TYPE_INT8:
+    wad_strcpy(buffer,wad_format_int(l->ptr,1,1));
+    break;
+  case WAD_TYPE_UINT8:
+    wad_strcpy(buffer,wad_format_int(l->ptr,1,0));
+    break;
+  case WAD_TYPE_CHAR:
+    buffer[0] = '\'';
+    buffer[1] = *((char *) l->ptr);
+    buffer[2] = '\'';
+    buffer[3] = 0;
+    break;
+  case WAD_TYPE_FLOAT:
+    wad_memcpy(&fval,l->ptr,sizeof(float));
+    sprintf(buffer,"%g",fval);
+    break;
+  case WAD_TYPE_DOUBLE:
+    wad_memcpy(&dval,l->ptr,sizeof(double));
+    sprintf(buffer,"%g",dval);
+    break;
+  case WAD_TYPE_UNKNOWN:
+  case WAD_TYPE_POINTER:
+  default:
+    /* Hmmm. Unknown data type.   We'll just treat it as a word */
+    if (l->ptr) {
+      int   incr,i;
+      int    b;
+      int    leading = 1;
+      char  *c;
+      char  *ptr;
+
+#ifdef WAD_LITTLE_ENDIAN
+      ptr = ((char *) l->ptr) + 3;
+      incr = -1;
+#else
+      ptr = (char *) l->ptr;
+      incr =1 ;
+#endif
+      wad_strcat(buffer,"0x");
+      c = buffer+2;
+      for (i = 0; i < sizeof(void *); i++) {
+	b = (int) *ptr;
+	if (!leading || (b)) {
+	  if (!leading || (b & 0xf0))
+	    *(c++) = hexdigits[(b & 0xf0) >> 4];
+	  *(c++) = hexdigits[(b & 0xf)];
+	  leading = 0;
+	}
+	ptr += incr;
+      }
+      if (leading)
+	*(c++) = '0';
+      
+      *c = 0;
+    }
+  }
+  return buffer;
+}
+
+/* Convert a wad local variable to a long */
+long wad_local_as_long(WadLocal *loc) {
+  long           value = 0;
+  int32          i32;
+  int16          i16;
+  int8           i8;
+  uint32         u32;
+  uint16         u16;
+  uint8          u8;
+
+  switch(loc->type) {
+  case WAD_TYPE_INT32:
+    wad_memcpy(&i32,loc->ptr,4);
+    value = (long) i32;
+    break;
+  case WAD_TYPE_UINT32:
+    wad_memcpy(&u32,loc->ptr,4);
+    value = (long) u32;
+    break;
+  case WAD_TYPE_INT16:
+    wad_memcpy(&i16,loc->ptr,2);
+    value = (long) i16;
+    break;
+  case WAD_TYPE_UINT16:
+    wad_memcpy(&u16,loc->ptr,2);
+    value = (long) u16;
+    break;
+  case WAD_TYPE_INT8:
+  case WAD_TYPE_CHAR:
+    wad_memcpy(&i8, loc->ptr,1);
+    value = (long) i8;
+    break;
+  case WAD_TYPE_UINT8:
+    wad_memcpy(&u8, loc->ptr,1);
+    value = (long) u8;
+    break;
+  default:
+    wad_memcpy(&u32,loc->ptr,4);
+    value = (long) u32;
+  }
+  return value;
+}
+
+/* Convert a wad local variable to a long */
+double wad_local_as_double(WadLocal *loc) {
+  double         value = 0;
+  float          fval;
+
+  switch(loc->type) {
+  case WAD_TYPE_DOUBLE:
+    wad_memcpy(&value,loc->ptr,8);
+    break;
+  case WAD_TYPE_FLOAT:
+    wad_memcpy(&fval,loc->ptr,4);
+    value = (double) fval;
+    break;
+  default:
+    value = 0;
+  }
+  return value;
+}
+
+
+
+
+
+
diff --git a/trunk/Tools/WAD/Wad/wadhandler.pl b/trunk/Tools/WAD/Wad/wadhandler.pl
new file mode 100644
index 0000000..e29240b
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/wadhandler.pl
@@ -0,0 +1,36 @@
+package libwadpl;
+sub wad_handler_traceback {
+    package DB;
+    my $es = "";
+    ($pack,$file,$line) = caller(1);
+
+    for ($i = 2; ($p,$f,$l,$s,$h,$w,$e,$r) = caller($i); $i++) {
+        @a = ();
+        for $arg (@args) {
+            $_ = "$arg";
+            s/([\'\\])/\\$1/g;
+            s/([^\0]*)/'$1'/
+              unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
+            s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
+            s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
+            push(@a, $_);
+        }
+        $w = $w ? '@ = ' : '$ = ';
+        $a = $h ? '(' . join(', ', @a) . ')' : '';
+        $e =~ s/\n\s*\;\s*\Z// if $e;
+        $e =~ s/[\\\']/\\$1/g if $e;
+        if ($r) {
+            $s = "require '$e'";
+        } elsif (defined $r) {
+            $s = "eval '$e'";
+        } elsif ($s eq '(eval)') {
+            $s = "eval {...}";
+        }
+        $f = "file `$f'" unless $f eq '-e';
+        $mess = "$w$s$a called from $f line $l\n";
+	$es = $mess . $es;
+
+    }
+    $es = "Signal at $file line $line\n" . $es;
+    return $es;
+}
diff --git a/trunk/Tools/WAD/Wad/wadpl.cxx b/trunk/Tools/WAD/Wad/wadpl.cxx
new file mode 100644
index 0000000..25ca5bb
--- /dev/null
+++ b/trunk/Tools/WAD/Wad/wadpl.cxx
@@ -0,0 +1,176 @@
+/* ----------------------------------------------------------------------------- 
+ * wadpl.cxx
+ *
+ *     Dynamically loadable module for Perl.
+ * 
+ * Author(s) : David Beazley (beazley@cs.uchicago.edu)
+ *
+ * Copyright (C) 2000.  The University of Chicago
+ * See the file LICENSE for information on usage and redistribution.	
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include "EXTERN.h"
+#include "perl.h"
+#include "XSUB.h"
+
+#include "wad.h"
+#ifdef __cplusplus
+}
+#endif
+
+#include <signal.h>
+
+#include "wad_perl_handler.c"
+
+/* Error message returned to perl */
+
+static char message[65536];
+static int  global_signo = 0;
+
+static void returnfunc(void) {
+  SV     *s;
+  s = perl_eval_pv((char*)"libwadpl::wad_handler_traceback(0)", 0);
+  croak("%s\n%s",SvPV(s,PL_na),message);
+  return;
+}
+
+/* Handler function */	
+static void handler(int signo, WadFrame *frame, char *ret) {
+
+  static char temp[1024];
+  int  len = 0;
+  char *name;
+  char *fd;
+  WadFrame *f;
+  WadFrame *fline = 0;
+  int err;
+  char  *type;
+
+  if (!ret) {
+    wad_default_callback(signo, frame, ret);
+    return;
+  }
+
+
+  switch(signo) {
+  case SIGSEGV:
+    type = (char*)"Segmentation fault.";
+    break;
+  case SIGBUS:
+    type = (char*)"Bus error.";
+    break;
+  case SIGABRT:
+    type = (char*)"Abort.";
+    break;
+  case SIGFPE:
+    type = (char*)"Math.";
+  default:
+    break;
+  }
+  strcpy(message,type);
+  strcat(message,"\n[ C stack trace ]\n\n");
+  fd = (char *) frame;
+  f = (WadFrame *) fd;
+
+  /* Find the last exception frame */
+  while (!f->last) {
+    fd = fd + f->size;
+    f = (WadFrame *) fd;
+  }
+  /* Now work backwards */
+  fd = fd - f->lastsize;
+  f = (WadFrame *) fd;
+  while (1) {
+    sprintf(temp,"#%-3d 0x%08x in ", f->frameno, f->pc);
+    strcat(message,temp);
+    strcat(message,*(fd + f->sym_off) ? fd+f->sym_off : "?");
+    strcat(message,"()");
+    if (strlen(SRCFILE(f))) {
+      strcat(message," in '");
+      strcat(message, wad_strip_dir(SRCFILE(f)));
+      strcat(message,"'");
+      if (f->line_number > 0) {
+	sprintf(temp,", line %d", f->line_number);
+	strcat(message,temp);
+	fline = f;
+      }
+    } else {
+      if (strlen(fd+f->obj_off)) {
+	strcat(message," from '");
+	strcat(message, wad_strip_dir(OBJFILE(f)));
+	strcat(message,"'");
+      }
+    }
+    strcat(message,"\n");
+    if (!f->lastsize) break;
+    fd = fd - f->lastsize;
+    f = (WadFrame *) fd;
+  }
+  if (fline) {
+    int first;
+    int last;
+    char *line, *c;
+    int i;
+    first = fline->line_number - 2;
+    last  = fline->line_number + 2;
+    if (first < 1) first = 1;
+    
+    line = wad_load_source(SRCFILE(fline),first);
+    if (line) {
+      strcat(message,"\n");
+      strcat(message, SRCFILE(fline));
+      sprintf(temp,", line %d\n\n", fline->line_number);
+      strcat(message, temp);
+      for (i = first; i <= last; i++) {
+	if (i == fline->line_number) strcat(message," => ");
+	else                         strcat(message,"    ");
+	c = strchr(line,'\n');
+	if (c) {
+	  *c = 0;
+	  strcat(message,line);
+	  strcat(message,"\n");
+	  *c = '\n';
+	} else {
+	  strcat(message,line);
+	  strcat(message,"\n");
+	  break;
+	}
+	line = c+1;
+      }
+      wad_release_source();
+      strcat(message,"\n");
+    }
+  }
+  wad_set_return_func(returnfunc);
+  wad_release_trace();
+}
+
+static void perlwadinit() {
+  printf("WAD Enabled\n");
+  wad_init();
+  wad_set_callback(handler);
+  wad_set_return("Perl_pp_entersub", 0);
+  perl_eval_pv(wad_perl_handler, 0);
+}
+
+/* This hack is used to auto-initialize wad regardless of whether we are
+   used as an imported module or as a link-library for another module */
+   
+class wadinitializer {
+public:
+  wadinitializer() {
+    perlwadinit();
+  }
+};
+
+static wadinitializer wi;
+
+extern "C"
+XS(boot_libwadpl) {
+  dXSARGS;
+  ST(0) = &PL_sv_yes;
+  XSRETURN(1);
+}
diff --git a/trunk/Tools/WAD/configure.in b/trunk/Tools/WAD/configure.in
new file mode 100644
index 0000000..1a8dcdb
--- /dev/null
+++ b/trunk/Tools/WAD/configure.in
@@ -0,0 +1,365 @@
+dnl Process this file with autoconf to produce a configure script.
+
+dnl NOTES:
+dnl * As of 1.34, we no longer use and test for "nope" to indicate
+dnl   an empty variable.  Instead, we use `VAR=' (set the variable
+dnl   to nothing) and `test -z "$VAR"' or `test -n "$VAR"' as the
+dnl   case may be.  --ttn, 2000/08/04 12:11:26
+
+AC_INIT
+AC_CONFIG_SRCDIR([Include/wad.h])
+AC_PREREQ(2.53)
+
+# Set name for machine-dependent library files
+AC_SUBST(MACHDEP)
+AC_MSG_CHECKING(MACHDEP)
+if test -z "$MACHDEP"
+then
+	if test -f /usr/lib/NextStep/software_version; then
+		set X `hostinfo | grep 'NeXT Mach.*:' | \
+			sed -e 's/://' -e 's/\./_/'` && \
+		ac_sys_system=next && ac_sys_release=$4
+		MACHDEP="$ac_sys_system$ac_sys_release$ac_sys_cpu"
+	else
+		ac_sys_system=`uname -s`
+		if test "$ac_sys_system" = "AIX" ; then
+			ac_sys_release=`uname -v`
+		else
+			ac_sys_release=`uname -r`
+		fi
+		ac_md_system=`echo $ac_sys_system |
+				   tr -d '[/ ]' | tr '[[A-Z]]' '[[a-z]]'`
+		ac_md_release=`echo $ac_sys_release |
+				   tr -d '[/ ]' | sed 's/\..*//'`
+		MACHDEP="$ac_md_system$ac_md_release"
+	fi
+	case MACHDEP in
+	'')	MACHDEP=unknown;;
+	esac
+fi
+AC_MSG_RESULT($MACHDEP)
+
+AC_PROG_CC
+AC_PROG_CXX
+AC_PROG_RANLIB
+
+dnl Checks for programs.
+
+AC_SUBST(AR)
+AC_CHECK_PROGS(AR, ar aal, ar)
+
+dnl Checks for header files.
+AC_HEADER_STDC
+dnl Checks for library functions.
+
+# Set info about shared libraries.
+AC_SUBST(SO)
+AC_SUBST(LDSHARED)
+AC_SUBST(CCSHARED)
+
+# SO is the extension of shared libraries `(including the dot!)
+# -- usually .so, .sl on HP-UX
+AC_MSG_CHECKING(SO)
+if test -z "$SO"
+then
+	case $ac_sys_system in
+	hp*|HP*)   SO=.sl;;
+	*)	   SO=.so;;
+	esac
+fi
+AC_MSG_RESULT($SO)
+
+# WAD Options
+AC_SUBST(WADOPT)
+AC_MSG_CHECKING(WADOPT)
+if test -z "$WADOPT"
+then
+	case $ac_sys_system/$ac_sys_release in
+	SunOS/5*) WADOPT="-DWAD_SOLARIS";;
+	Linux*) WADOPT="-DWAD_LINUX";;
+	*)	WADOPT="-DWAD_UNKWOWN";;
+	esac
+fi
+AC_MSG_RESULT($WADOPT)
+
+
+# LDSHARED is the ld *command* used to create shared library
+# -- "ld" on SunOS 4.x.x, "ld -G" on SunOS 5.x, "ld -shared" on IRIX 5
+# (Shared libraries in this instance are shared modules to be loaded into
+# Python, as opposed to building Python itself as a shared library.)
+AC_MSG_CHECKING(LDSHARED)
+if test -z "$LDSHARED"
+then
+	case $ac_sys_system/$ac_sys_release in
+	AIX*) LDSHARED="\$(srcdir)/ld_so_aix \$(CC)";;
+	IRIX/5*) LDSHARED="ld -shared";;
+	IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";;
+	SunOS/4*) LDSHARED="ld";;
+	SunOS/5*) LDSHARED="ld -G";;
+	hp*|HP*) LDSHARED="ld -b";;
+	OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";;
+	DYNIX/ptx*) LDSHARED="ld -G";;
+	next/*)
+		if test "$ns_dyld"
+		then LDSHARED='$(CC) $(LDFLAGS) -bundle -prebind'
+		else LDSHARED='$(CC) $(CFLAGS) -nostdlib -r';
+		fi
+                if test "$with_next_framework" ; then
+		    LDSHARED="$LDSHARED \$(LDLIBRARY)"
+		fi ;;
+	Linux*) LDSHARED="gcc -shared";;
+	dgux*) LDSHARED="ld -G";;
+	FreeBSD*/3*) LDSHARED="gcc -shared";;
+	FreeBSD*|OpenBSD*) LDSHARED="ld -Bshareable";;
+	NetBSD*)
+		if [[ "`$CC -dM -E - </dev/null | grep __ELF__`" != "" ]]
+		then
+			LDSHARED="cc -shared"
+		else
+			LDSHARED="ld -Bshareable"
+		fi;;
+	SCO_SV*) LDSHARED="cc -G -KPIC -Ki486 -belf -Wl,-Bexport";;
+	*)	LDSHARED="ld";;
+	esac
+fi
+AC_MSG_RESULT($LDSHARED)
+
+
+# CXXSHARED is the C++ *command* used to create shared library
+AC_SUBST(CXXLINK)
+
+AC_MSG_CHECKING(CXXLINK)
+if test -z "$CXXLINK"
+then
+	case $ac_sys_system/$ac_sys_release in
+	SunOS/5*) if test "$GCC" = yes;
+             then CXXLINK="g++ -shared";
+             else CXXLINK="CC -G";
+             fi;;
+	Linux*) CXXLINK="g++ -shared";;
+	*)	CXXLINK="g++";;
+	esac
+fi
+AC_MSG_RESULT($CXXLINK)
+
+# CCSHARED are the C *flags* used to create objects to go into a shared
+# library (module) -- this is only needed for a few systems
+AC_MSG_CHECKING(CCSHARED)
+if test -z "$CCSHARED"
+then
+	case $ac_sys_system/$ac_sys_release in
+	hp*|HP*) if test "$GCC" = yes;
+		 then CCSHARED="-fpic";
+		 else CCSHARED="+z";
+		 fi;;
+	Linux*) CCSHARED="-fpic";;
+	FreeBSD*|OpenBSD*) CCSHARED="-fpic";;
+	NetBSD*) CCSHARED="-fPIC";;
+	SCO_SV*) CCSHARED="-KPIC -dy -Bdynamic";;
+	IRIX*/6*)  case $CC in
+		   *gcc*) CCSHARED="-shared";;
+		   *) CCSHARED="";;
+		   esac;;
+	esac
+fi
+AC_MSG_RESULT($CCSHARED)
+
+AC_SUBST(CXXSHARED)
+# CCSHARED are the C *flags* used to create objects to go into a shared
+# library (module) -- this is only needed for a few systems
+AC_MSG_CHECKING(CXXSHARED)
+if test -z "$CXXSHARED"
+then
+	case $ac_sys_system/$ac_sys_release in
+	Linux*) CXXSHARED="-fpic";;
+	SunOS/5*) if test "$GCC" = yes;
+             then CXXSHARED="-fpic";
+             else CXXSHARED="-Kpic";
+             fi;;
+	esac
+fi
+AC_MSG_RESULT($CXXSHARED)
+
+# RPATH is the path used to look for shared library files.
+AC_MSG_CHECKING(RPATH)
+if test -z "$RPATH"
+then
+	case $ac_sys_system/$ac_sys_release in
+	SunOS/5*) RPATH="\"-R\"";;
+	Linux*) RPATH="-Xlinker -rpath ";;
+	*)	RPATH="";;
+	esac
+fi
+AC_MSG_RESULT($RPATH)
+AC_SUBST(RPATH)
+
+#--------------------------------------------------------------------
+#	Try to locate the Tcl package
+#--------------------------------------------------------------------
+
+TCLINCLUDE=
+TCLLIB=
+TCLPACKAGE=
+MAKETCL=
+
+AC_ARG_WITH(tcl,[  --with-tcl=path         Set location of Tcl package],[
+	TCLPACKAGE="$withval"], [TCLPACKAGE=])
+AC_ARG_WITH(tclincl,[  --with-tclincl=path     Set location of Tcl include directory],[
+	TCLINCLUDE="-I$withval"], [TCLINCLUDE=])
+AC_ARG_WITH(tcllib,[  --with-tcllib=path      Set location of Tcl library directory],[
+	TCLLIB="-L$withval"], [TCLLIB=])
+
+if test -z "$TCLINCLUDE"; then
+   if test -n "$TCLPACKAGE"; then
+	TCLINCLUDE="-I$TCLPACKAGE/include"
+   fi
+fi
+
+if test -z "$TCLLIB"; then
+   if test -n "$TCLPACKAGE"; then
+	TCLLIB="-L$TCLPACKAGE/lib"
+   fi
+fi
+
+AC_MSG_CHECKING(for Tcl header files)
+if test -z "$TCLINCLUDE"; then
+AC_TRY_CPP([#include <tcl.h>], , TCLINCLUDE="")
+if test -z "$TCLINCLUDE"; then
+	dirs="$prefix/include /usr/local/include /usr/include /opt/local/include /home/sci/local/include"
+	for i in $dirs ; do
+		if test -r $i/tcl.h; then
+			AC_MSG_RESULT($i)
+			TCLINCLUDE="-I$i"
+			MAKETCL="tcl"
+			break
+		fi
+	done
+fi
+if test -z "$TCLINCLUDE"; then
+	TCLINCLUDE=""
+	MAKETCL=""
+    	AC_MSG_RESULT(not found)
+fi
+else
+        AC_MSG_RESULT($TCLINCLUDE)
+fi
+
+AC_SUBST(TCLINCLUDE)
+AC_SUBST(MAKETCL)
+
+#----------------------------------------------------------------
+# Look for Python
+#----------------------------------------------------------------
+
+PYINCLUDE=
+MAKEPYTHON=
+PYLIB=
+PYPACKAGE=
+
+AC_ARG_WITH(py,[  --with-py=path          Set location of Python],[
+	PYPACKAGE="$withval"], [PYPACKAGE=])
+AC_ARG_WITH(pyincl,[  --with-pyincl=path      Set location of Python include directory],[
+	PYINCLUDE="$withval"], [PYINCLUDE=])
+AC_ARG_WITH(pylib,[  --with-pylib=path       Set location of Python library directory],[
+	PYLIB="$withval"], [PYLIB=])
+
+if test -z "$PYINCLUDE"; then
+   if test -n "$PYPACKAGE"; then
+	PYINCLUDE="$PYPACKAGE/include"
+   fi
+fi
+
+if test -z "$PYLIB"; then
+   if test -n "$PYPACKAGE"; then
+	PYLIB="$PYPACKAGE/lib"
+   fi
+fi
+
+
+AC_MSG_CHECKING(for Python header files)
+
+dirs="$PYINCLUDE $PYINCLUDE/python2.0 $PYINCLUDE/python1.6 $PYINCLUDE/python1.5 $prefix/include/python2.0 $prefix/include/python1.6 $prefix/include/python1.5 /usr/local/include/python2.0 /usr/local/include/python1.6 /usr/local/include/python1.5 /usr/include/python1.5" 
+for i in $dirs ; do
+	if test -r $i/Python.h; then
+		AC_MSG_RESULT($i)
+		PYINCLUDE="-I$i"
+		MAKEPYTHON="python"
+		break
+	fi
+done
+if test -z "$PYINCLUDE"; then
+	PYINCLUDE=""
+	MAKEPYTHON=""
+    	AC_MSG_RESULT(not found)
+fi
+
+AC_SUBST(PYINCLUDE)
+AC_SUBST(PYLINK)
+AC_SUBST(MAKEPYTHON)
+
+#----------------------------------------------------------------
+# Look for Perl5
+#----------------------------------------------------------------
+
+PERLBIN=
+MAKEPERL=
+
+AC_ARG_WITH(perl5,[  --with-perl5=path       Set location of Perl5 executable],[ PERLBIN="$withval"], [PERLBIN=])
+
+# First figure out what the name of Perl5 is
+
+if test -z "$PERLBIN"; then
+AC_CHECK_PROGS(PERL, perl5.004 perl5.003 perl5.002 perl5.001 perl5 perl)
+else
+PERL="$PERLBIN"
+fi
+AC_MSG_CHECKING(for Perl5 header files)
+if test -n "$PERL"; then
+	PERL5DIR=`($PERL -e 'use Config; print $Config{archlib};') 2>/dev/null`
+	if test "$PERL5DIR" != ""; then
+		dirs="$PERL5DIR $PERL5DIR/CORE"
+		PERL5EXT=none
+		for i in $dirs; do
+			if test -r $i/perl.h; then
+				AC_MSG_RESULT($i)
+				PERL5EXT="-I$i"
+				MAKEPERL="perl"
+				break;
+			fi
+		done
+		if test "$PERL5EXT" = none; then
+			PERL5EXT=""
+			MAKEPERL=""
+			AC_MSG_RESULT(could not locate perl.h...using $PERL5EXT)
+		fi
+	else
+		AC_MSG_RESULT(unable to determine perl5 configuration)
+		PERL5EXT=""
+		MAKEPERL=""
+	fi
+    else
+       	AC_MSG_RESULT(could not figure out how to run perl5)
+	PERL5EXT=""
+	MAKEPERL=""
+    fi
+
+AC_SUBST(PERL5EXT)
+AC_SUBST(MAKEPERL)
+
+dnl We use the following in `AC_CONFIG_FILES' and "make distclean".
+configure_substituted_files=`echo	\
+    Wad/Makefile			\
+    Python/Makefile    \
+    Tcl/Makefile \
+    Test/Makefile  \
+    Prebuilt/linux/Makefile \
+    Prebuilt/solaris/Makefile \
+    Makefile				\
+`
+AC_SUBST(configure_substituted_files)
+
+AC_CONFIG_FILES([$configure_substituted_files])
+AC_OUTPUT
+
+dnl configure.in ends here
+
diff --git a/trunk/Tools/capitalize b/trunk/Tools/capitalize
new file mode 100755
index 0000000..a8330d1
--- /dev/null
+++ b/trunk/Tools/capitalize
@@ -0,0 +1,5 @@
+#!/bin/sh
+# usage: capitalize word
+# write word to stdout w/ first character upcased
+first_char=`echo $1 | sed 's/^\(.\).*/\1/' | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`
+echo ${first_char}`echo $1 | sed 's/^.//'`
diff --git a/trunk/Tools/check-include-path.pike b/trunk/Tools/check-include-path.pike
new file mode 100644
index 0000000..2bfb2b9
--- /dev/null
+++ b/trunk/Tools/check-include-path.pike
@@ -0,0 +1,20 @@
+/**
+ * This is a helper script to identify the proper include path
+ * for Pike header files. It should be run with the full path
+ * to the Pike executable as its single argument, e.g.
+ *
+ *     pike check-include-path.pike /usr/local/bin/pike
+ *
+ * and its output should be the correct path to the header
+ * files, e.g.
+ *
+ *     /usr/local/pike/7.2.239/include/pike
+ *
+ */
+
+int main(int argc, array(string) argv)
+{
+    string prefix = replace(argv[1], "/bin/pike", "");
+    write(prefix + "/pike/" + __MAJOR__ + "." + __MINOR__ + "." + __BUILD__ + "/include/pike");
+    return 0;
+}
diff --git a/trunk/Tools/config/ac_compare_version.m4 b/trunk/Tools/config/ac_compare_version.m4
new file mode 100644
index 0000000..79e94cc
--- /dev/null
+++ b/trunk/Tools/config/ac_compare_version.m4
@@ -0,0 +1,40 @@
+dnl @synopsis AC_COMPARE_VERSION\
+dnl  (version-a, version-b, action-if-greater, action-if-equal, action-if-less)
+dnl 
+dnl This macro compares two version numbers and executes the indicated action
+dnl based on whether they're equal or one is greater than the other.
+dnl It's needed to determine whether ocaml is new enough that the incompatible
+dnl change 'loc' -> '_loc' is present in this version of camlp4.
+dnl 
+dnl It's implemented from scratch just for SWIG by arty.
+dnl
+dnl @category Misc
+dnl @author arty
+dnl @version 2006-11-02
+dnl @license GPLWithACException
+
+AC_DEFUN([AC_COMPARE_VERSION], [
+	# Split the version into units.
+	ver_a="[$1]"
+	ver_b="[$2]"
+	nodots_a=`echo $ver_a | sed -e 's/\./ /g'`
+	condition="equal"
+	isolate_b_regex='\([[0-9]]\+\).*'
+	for ver_part in $nodots_a ; do
+		b_ver_part=`echo "$ver_b" | sed -e 's/'"$isolate_b_regex"'/\1/'`
+		if test \( "$ver_part" -lt "$b_ver_part" \) -a \( "x$condition" == "xequal" \) ; then
+			condition=less
+		elif test \( "$ver_part" -gt "$b_ver_part" \) -a \( "x$condition" == "xequal" \) ; then
+			condition=greater
+		fi
+		isolate_b_regex='[[0-9]]\+\.'"$isolate_b_regex"
+	done
+
+	if test "x$condition" == "xequal" ; then
+		[$4]
+	elif test "x$condition" == "xless" ; then
+		[$3]
+	elif test "x$condition" == "xgreater" ; then
+		[$5]
+	fi
+])
\ No newline at end of file
diff --git a/trunk/Tools/config/ac_compile_warnings.m4 b/trunk/Tools/config/ac_compile_warnings.m4
new file mode 100644
index 0000000..4c030ea
--- /dev/null
+++ b/trunk/Tools/config/ac_compile_warnings.m4
@@ -0,0 +1,56 @@
+dnl @synopsis AC_COMPILE_WARNINGS
+dnl
+dnl Set the maximum warning verbosity according to C and C++ compiler used.
+dnl Currently supports g++ and gcc.
+dnl
+dnl The compiler options are always added CFLAGS and CXXFLAGS even if
+dnl these are overidden at configure time. Removing the maximum warning
+dnl flags can be removed with --without-maximum-compile-warnings. For example:
+dnl
+dnl   ./configure --without-maximum-compile-warnings CFLAGS= CXXFLAGS=
+dnl
+dnl @category Misc
+dnl @author Loic Dachary <loic@senga.org>
+dnl @author William Fulton <wsf@fultondesigns.co.uk>
+dnl @version 2005-04-29
+dnl @license GPLWithACException
+
+AC_DEFUN([AC_COMPILE_WARNINGS], [
+AC_MSG_CHECKING([maximum warning verbosity option])
+  AC_REQUIRE([AC_PROG_CC])
+  AC_REQUIRE([AC_PROG_CXX])
+
+  AC_ARG_WITH([maximum-compile-warnings], 
+              AS_HELP_STRING([--without-maximum-compile-warnings],
+                             [Disable maximum warning verbosity]),
+              [ac_compile_warnings_on="$withval"],
+              [ac_compile_warnings_on=""])
+
+  if test x"$ac_compile_warnings_on" = xno
+  then
+    ac_compile_warnings_msg=no
+  else
+    if test -n "$CXX"
+    then
+      if test "$GXX" = "yes"
+      then
+        ac_compile_warnings_opt='-Wall -W -ansi -pedantic'
+      fi
+      CXXFLAGS="$CXXFLAGS $ac_compile_warnings_opt"
+      ac_compile_warnings_msg="$ac_compile_warnings_opt for C++"
+    fi
+
+  if test -n "$CC"
+  then
+    if test "$GCC" = "yes"
+    then
+      ac_compile_warnings_opt='-Wall -W -ansi -pedantic'
+    fi
+    CFLAGS="$CFLAGS $ac_compile_warnings_opt"
+    ac_compile_warnings_msg="$ac_compile_warnings_msg $ac_compile_warnings_opt for C"
+  fi
+  fi
+  AC_MSG_RESULT([$ac_compile_warnings_msg])
+  unset ac_compile_warnings_msg
+  unset ac_compile_warnings_opt
+])
diff --git a/trunk/Tools/config/ac_define_dir.m4 b/trunk/Tools/config/ac_define_dir.m4
new file mode 100644
index 0000000..fc81b09
--- /dev/null
+++ b/trunk/Tools/config/ac_define_dir.m4
@@ -0,0 +1,35 @@
+dnl @synopsis AC_DEFINE_DIR(VARNAME, DIR [, DESCRIPTION])
+dnl
+dnl This macro sets VARNAME to the expansion of the DIR variable,
+dnl taking care of fixing up ${prefix} and such.
+dnl
+dnl VARNAME is then offered as both an output variable and a C
+dnl preprocessor symbol.
+dnl
+dnl Example:
+dnl
+dnl    AC_DEFINE_DIR([DATADIR], [datadir], [Where data are placed to.])
+dnl
+dnl @category Misc
+dnl @author Stepan Kasal <kasal@ucw.cz>
+dnl @author Andreas Schwab <schwab@suse.de>
+dnl @author Guido Draheim <guidod@gmx.de>
+dnl @author Alexandre Oliva
+dnl @version 2005-07-29
+dnl @license AllPermissive
+
+AC_DEFUN([AC_DEFINE_DIR], [
+  prefix_NONE=
+  exec_prefix_NONE=
+  test "x$prefix" = xNONE && prefix_NONE=yes && prefix=$ac_default_prefix
+  test "x$exec_prefix" = xNONE && exec_prefix_NONE=yes && exec_prefix=$prefix
+dnl In Autoconf 2.60, ${datadir} refers to ${datarootdir}, which in turn
+dnl refers to ${prefix}.  Thus we have to use `eval' twice.
+  eval ac_define_dir="\"[$]$2\""
+  eval ac_define_dir="\"$ac_define_dir\""
+  AC_SUBST($1, "$ac_define_dir")
+  AC_DEFINE_UNQUOTED($1, "$ac_define_dir", [$3])
+  test "$prefix_NONE" && prefix=NONE
+  test "$exec_prefix_NONE" && exec_prefix=NONE
+])
+
diff --git a/trunk/Tools/config/config.guess b/trunk/Tools/config/config.guess
new file mode 100755
index 0000000..396482d
--- /dev/null
+++ b/trunk/Tools/config/config.guess
@@ -0,0 +1,1500 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
+#   Inc.
+
+timestamp='2006-07-02'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Originally written by Per Bothner <per@bothner.com>.
+# Please send patches to <config-patches@gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub.  If it succeeds, it prints the system name on stdout, and
+# exits with 0.  Otherwise, it exits with 1.
+#
+# The plan is that this can be called by configure scripts if you
+# don't specify an explicit build system type.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help" >&2
+       exit 1 ;;
+    * )
+       break ;;
+  esac
+done
+
+if test $# != 0; then
+  echo "$me: too many arguments$help" >&2
+  exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,)    echo "int x;" > $dummy.c ;
+	for c in cc gcc c89 c99 ; do
+	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+	     CC_FOR_BUILD="$c"; break ;
+	  fi ;
+	done ;
+	if test x"$CC_FOR_BUILD" = x ; then
+	  CC_FOR_BUILD=no_compiler_found ;
+	fi
+	;;
+ ,,*)   CC_FOR_BUILD=$CC ;;
+ ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi@noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+	PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+    *:NetBSD:*:*)
+	# NetBSD (nbsd) targets should (where applicable) match one or
+	# more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
+	# switched to ELF, *-*-netbsd* would select the old
+	# object file format.  This provides both forward
+	# compatibility and a consistent mechanism for selecting the
+	# object file format.
+	#
+	# Note: NetBSD doesn't particularly care about the vendor
+	# portion of the name.  We always set it to "unknown".
+	sysctl="sysctl -n hw.machine_arch"
+	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+	case "${UNAME_MACHINE_ARCH}" in
+	    armeb) machine=armeb-unknown ;;
+	    arm*) machine=arm-unknown ;;
+	    sh3el) machine=shl-unknown ;;
+	    sh3eb) machine=sh-unknown ;;
+	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+	esac
+	# The Operating System including object format, if it has switched
+	# to ELF recently, or will in the future.
+	case "${UNAME_MACHINE_ARCH}" in
+	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+		eval $set_cc_for_build
+		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+			| grep __ELF__ >/dev/null
+		then
+		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+		    # Return netbsd for either.  FIX?
+		    os=netbsd
+		else
+		    os=netbsdelf
+		fi
+		;;
+	    *)
+	        os=netbsd
+		;;
+	esac
+	# The OS release
+	# Debian GNU/NetBSD machines have a different userland, and
+	# thus, need a distinct triplet. However, they do not need
+	# kernel version information, so it can be replaced with a
+	# suitable tag, in the style of linux-gnu.
+	case "${UNAME_VERSION}" in
+	    Debian*)
+		release='-gnu'
+		;;
+	    *)
+		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+		;;
+	esac
+	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+	# contains redundant information, the shorter form:
+	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+	echo "${machine}-${os}${release}"
+	exit ;;
+    *:OpenBSD:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+	exit ;;
+    *:ekkoBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+	exit ;;
+    *:SolidBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:MirBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    alpha:OSF1:*:*)
+	case $UNAME_RELEASE in
+	*4.0)
+		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+		;;
+	*5.*)
+	        UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+		;;
+	esac
+	# According to Compaq, /usr/sbin/psrinfo has been available on
+	# OSF/1 and Tru64 systems produced since 1995.  I hope that
+	# covers most systems running today.  This code pipes the CPU
+	# types through head -n 1, so we only detect the type of CPU 0.
+	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+	case "$ALPHA_CPU_TYPE" in
+	    "EV4 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV4.5 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "LCA4 (21066/21068)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV5 (21164)")
+		UNAME_MACHINE="alphaev5" ;;
+	    "EV5.6 (21164A)")
+		UNAME_MACHINE="alphaev56" ;;
+	    "EV5.6 (21164PC)")
+		UNAME_MACHINE="alphapca56" ;;
+	    "EV5.7 (21164PC)")
+		UNAME_MACHINE="alphapca57" ;;
+	    "EV6 (21264)")
+		UNAME_MACHINE="alphaev6" ;;
+	    "EV6.7 (21264A)")
+		UNAME_MACHINE="alphaev67" ;;
+	    "EV6.8CB (21264C)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8AL (21264B)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8CX (21264D)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.9A (21264/EV69A)")
+		UNAME_MACHINE="alphaev69" ;;
+	    "EV7 (21364)")
+		UNAME_MACHINE="alphaev7" ;;
+	    "EV7.9 (21364A)")
+		UNAME_MACHINE="alphaev79" ;;
+	esac
+	# A Pn.n version is a patched version.
+	# A Vn.n version is a released version.
+	# A Tn.n version is a released field test version.
+	# A Xn.n version is an unreleased experimental baselevel.
+	# 1.2 uses "1.2" for uname -r.
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	exit ;;
+    Alpha\ *:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# Should we change UNAME_MACHINE based on the output of uname instead
+	# of the specific Alpha model?
+	echo alpha-pc-interix
+	exit ;;
+    21064:Windows_NT:50:3)
+	echo alpha-dec-winnt3.5
+	exit ;;
+    Amiga*:UNIX_System_V:4.0:*)
+	echo m68k-unknown-sysv4
+	exit ;;
+    *:[Aa]miga[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-amigaos
+	exit ;;
+    *:[Mm]orph[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-morphos
+	exit ;;
+    *:OS/390:*:*)
+	echo i370-ibm-openedition
+	exit ;;
+    *:z/VM:*:*)
+	echo s390-ibm-zvmoe
+	exit ;;
+    *:OS400:*:*)
+        echo powerpc-ibm-os400
+	exit ;;
+    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+	echo arm-acorn-riscix${UNAME_RELEASE}
+	exit ;;
+    arm:riscos:*:*|arm:RISCOS:*:*)
+	echo arm-unknown-riscos
+	exit ;;
+    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+	echo hppa1.1-hitachi-hiuxmpp
+	exit ;;
+    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+	if test "`(/bin/universe) 2>/dev/null`" = att ; then
+		echo pyramid-pyramid-sysv3
+	else
+		echo pyramid-pyramid-bsd
+	fi
+	exit ;;
+    NILE*:*:*:dcosx)
+	echo pyramid-pyramid-svr4
+	exit ;;
+    DRS?6000:unix:4.0:6*)
+	echo sparc-icl-nx6
+	exit ;;
+    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+	case `/usr/bin/uname -p` in
+	    sparc) echo sparc-icl-nx7; exit ;;
+	esac ;;
+    sun4H:SunOS:5.*:*)
+	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    i86pc:SunOS:5.*:*)
+	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:6*:*)
+	# According to config.sub, this is the proper way to canonicalize
+	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
+	# it's likely to be more like Solaris than SunOS4.
+	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:*:*)
+	case "`/usr/bin/arch -k`" in
+	    Series*|S4*)
+		UNAME_RELEASE=`uname -v`
+		;;
+	esac
+	# Japanese Language versions have a version number like `4.1.3-JL'.
+	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+	exit ;;
+    sun3*:SunOS:*:*)
+	echo m68k-sun-sunos${UNAME_RELEASE}
+	exit ;;
+    sun*:*:4.2BSD:*)
+	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+	case "`/bin/arch`" in
+	    sun3)
+		echo m68k-sun-sunos${UNAME_RELEASE}
+		;;
+	    sun4)
+		echo sparc-sun-sunos${UNAME_RELEASE}
+		;;
+	esac
+	exit ;;
+    aushp:SunOS:*:*)
+	echo sparc-auspex-sunos${UNAME_RELEASE}
+	exit ;;
+    # The situation for MiNT is a little confusing.  The machine name
+    # can be virtually everything (everything which is not
+    # "atarist" or "atariste" at least should have a processor
+    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
+    # to the lowercase version "mint" (or "freemint").  Finally
+    # the system name "TOS" denotes a system which is actually not
+    # MiNT.  But MiNT is downward compatible to TOS, so this should
+    # be no problem.
+    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+        echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+        exit ;;
+    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+        echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+        echo m68k-milan-mint${UNAME_RELEASE}
+        exit ;;
+    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+        echo m68k-hades-mint${UNAME_RELEASE}
+        exit ;;
+    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+        echo m68k-unknown-mint${UNAME_RELEASE}
+        exit ;;
+    m68k:machten:*:*)
+	echo m68k-apple-machten${UNAME_RELEASE}
+	exit ;;
+    powerpc:machten:*:*)
+	echo powerpc-apple-machten${UNAME_RELEASE}
+	exit ;;
+    RISC*:Mach:*:*)
+	echo mips-dec-mach_bsd4.3
+	exit ;;
+    RISC*:ULTRIX:*:*)
+	echo mips-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    VAX*:ULTRIX*:*:*)
+	echo vax-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    2020:CLIX:*:* | 2430:CLIX:*:*)
+	echo clipper-intergraph-clix${UNAME_RELEASE}
+	exit ;;
+    mips:*:*:UMIPS | mips:*:*:RISCos)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h>  /* for printf() prototype */
+	int main (int argc, char *argv[]) {
+#else
+	int main (argc, argv) int argc; char *argv[]; {
+#endif
+	#if defined (host_mips) && defined (MIPSEB)
+	#if defined (SYSTYPE_SYSV)
+	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_SVR4)
+	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+	#endif
+	#endif
+	  exit (-1);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c &&
+	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+	  SYSTEM_NAME=`$dummy $dummyarg` &&
+	    { echo "$SYSTEM_NAME"; exit; }
+	echo mips-mips-riscos${UNAME_RELEASE}
+	exit ;;
+    Motorola:PowerMAX_OS:*:*)
+	echo powerpc-motorola-powermax
+	exit ;;
+    Motorola:*:4.3:PL8-*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:Power_UNIX:*:*)
+	echo powerpc-harris-powerunix
+	exit ;;
+    m88k:CX/UX:7*:*)
+	echo m88k-harris-cxux7
+	exit ;;
+    m88k:*:4*:R4*)
+	echo m88k-motorola-sysv4
+	exit ;;
+    m88k:*:3*:R3*)
+	echo m88k-motorola-sysv3
+	exit ;;
+    AViiON:dgux:*:*)
+        # DG/UX returns AViiON for all architectures
+        UNAME_PROCESSOR=`/usr/bin/uname -p`
+	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+	then
+	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+	       [ ${TARGET_BINARY_INTERFACE}x = x ]
+	    then
+		echo m88k-dg-dgux${UNAME_RELEASE}
+	    else
+		echo m88k-dg-dguxbcs${UNAME_RELEASE}
+	    fi
+	else
+	    echo i586-dg-dgux${UNAME_RELEASE}
+	fi
+ 	exit ;;
+    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
+	echo m88k-dolphin-sysv3
+	exit ;;
+    M88*:*:R3*:*)
+	# Delta 88k system running SVR3
+	echo m88k-motorola-sysv3
+	exit ;;
+    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+	echo m88k-tektronix-sysv3
+	exit ;;
+    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+	echo m68k-tektronix-bsd
+	exit ;;
+    *:IRIX*:*:*)
+	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+	exit ;;
+    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
+    i*86:AIX:*:*)
+	echo i386-ibm-aix
+	exit ;;
+    ia64:AIX:*:*)
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:2:3)
+	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+		eval $set_cc_for_build
+		sed 's/^		//' << EOF >$dummy.c
+		#include <sys/systemcfg.h>
+
+		main()
+			{
+			if (!__power_pc())
+				exit(1);
+			puts("powerpc-ibm-aix3.2.5");
+			exit(0);
+			}
+EOF
+		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+		then
+			echo "$SYSTEM_NAME"
+		else
+			echo rs6000-ibm-aix3.2.5
+		fi
+	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+		echo rs6000-ibm-aix3.2.4
+	else
+		echo rs6000-ibm-aix3.2
+	fi
+	exit ;;
+    *:AIX:*:[45])
+	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+		IBM_ARCH=rs6000
+	else
+		IBM_ARCH=powerpc
+	fi
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:*:*)
+	echo rs6000-ibm-aix
+	exit ;;
+    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+	echo romp-ibm-bsd4.4
+	exit ;;
+    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
+	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
+	exit ;;                             # report: romp-ibm BSD 4.3
+    *:BOSX:*:*)
+	echo rs6000-bull-bosx
+	exit ;;
+    DPX/2?00:B.O.S.:*:*)
+	echo m68k-bull-sysv3
+	exit ;;
+    9000/[34]??:4.3bsd:1.*:*)
+	echo m68k-hp-bsd
+	exit ;;
+    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+	echo m68k-hp-bsd4.4
+	exit ;;
+    9000/[34678]??:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	case "${UNAME_MACHINE}" in
+	    9000/31? )            HP_ARCH=m68000 ;;
+	    9000/[34]?? )         HP_ARCH=m68k ;;
+	    9000/[678][0-9][0-9])
+		if [ -x /usr/bin/getconf ]; then
+		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+                    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+                    case "${sc_cpu_version}" in
+                      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+                      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+                      532)                      # CPU_PA_RISC2_0
+                        case "${sc_kernel_bits}" in
+                          32) HP_ARCH="hppa2.0n" ;;
+                          64) HP_ARCH="hppa2.0w" ;;
+			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+                        esac ;;
+                    esac
+		fi
+		if [ "${HP_ARCH}" = "" ]; then
+		    eval $set_cc_for_build
+		    sed 's/^              //' << EOF >$dummy.c
+
+              #define _HPUX_SOURCE
+              #include <stdlib.h>
+              #include <unistd.h>
+
+              int main ()
+              {
+              #if defined(_SC_KERNEL_BITS)
+                  long bits = sysconf(_SC_KERNEL_BITS);
+              #endif
+                  long cpu  = sysconf (_SC_CPU_VERSION);
+
+                  switch (cpu)
+              	{
+              	case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+              	case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+              	case CPU_PA_RISC2_0:
+              #if defined(_SC_KERNEL_BITS)
+              	    switch (bits)
+              		{
+              		case 64: puts ("hppa2.0w"); break;
+              		case 32: puts ("hppa2.0n"); break;
+              		default: puts ("hppa2.0"); break;
+              		} break;
+              #else  /* !defined(_SC_KERNEL_BITS) */
+              	    puts ("hppa2.0"); break;
+              #endif
+              	default: puts ("hppa1.0"); break;
+              	}
+                  exit (0);
+              }
+EOF
+		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    test -z "$HP_ARCH" && HP_ARCH=hppa
+		fi ;;
+	esac
+	if [ ${HP_ARCH} = "hppa2.0w" ]
+	then
+	    eval $set_cc_for_build
+
+	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+	    # generating 64-bit code.  GNU and HP use different nomenclature:
+	    #
+	    # $ CC_FOR_BUILD=cc ./config.guess
+	    # => hppa2.0w-hp-hpux11.23
+	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+	    # => hppa64-hp-hpux11.23
+
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+		grep __LP64__ >/dev/null
+	    then
+		HP_ARCH="hppa2.0w"
+	    else
+		HP_ARCH="hppa64"
+	    fi
+	fi
+	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+	exit ;;
+    ia64:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	echo ia64-hp-hpux${HPUX_REV}
+	exit ;;
+    3050*:HI-UX:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <unistd.h>
+	int
+	main ()
+	{
+	  long cpu = sysconf (_SC_CPU_VERSION);
+	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
+	     results, however.  */
+	  if (CPU_IS_PA_RISC (cpu))
+	    {
+	      switch (cpu)
+		{
+		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+		  default: puts ("hppa-hitachi-hiuxwe2"); break;
+		}
+	    }
+	  else if (CPU_IS_HP_MC68K (cpu))
+	    puts ("m68k-hitachi-hiuxwe2");
+	  else puts ("unknown-hitachi-hiuxwe2");
+	  exit (0);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+		{ echo "$SYSTEM_NAME"; exit; }
+	echo unknown-hitachi-hiuxwe2
+	exit ;;
+    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+	echo hppa1.1-hp-bsd
+	exit ;;
+    9000/8??:4.3bsd:*:*)
+	echo hppa1.0-hp-bsd
+	exit ;;
+    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+	echo hppa1.0-hp-mpeix
+	exit ;;
+    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+	echo hppa1.1-hp-osf
+	exit ;;
+    hp8??:OSF1:*:*)
+	echo hppa1.0-hp-osf
+	exit ;;
+    i*86:OSF1:*:*)
+	if [ -x /usr/sbin/sysversion ] ; then
+	    echo ${UNAME_MACHINE}-unknown-osf1mk
+	else
+	    echo ${UNAME_MACHINE}-unknown-osf1
+	fi
+	exit ;;
+    parisc*:Lites*:*:*)
+	echo hppa1.1-hp-lites
+	exit ;;
+    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+	echo c1-convex-bsd
+        exit ;;
+    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+        exit ;;
+    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+	echo c34-convex-bsd
+        exit ;;
+    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+	echo c38-convex-bsd
+        exit ;;
+    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+	echo c4-convex-bsd
+        exit ;;
+    CRAY*Y-MP:*:*:*)
+	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*[A-Z]90:*:*:*)
+	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+	      -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*TS:*:*:*)
+	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*T3E:*:*:*)
+	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*SV1:*:*:*)
+	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    *:UNICOS/mp:*:*)
+	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+        echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+        exit ;;
+    5000:UNIX_System_V:4.*:*)
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+	exit ;;
+    sparc*:BSD/OS:*:*)
+	echo sparc-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:BSD/OS:*:*)
+	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:FreeBSD:*:*)
+	case ${UNAME_MACHINE} in
+	    pc98)
+		echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
+    i*:CYGWIN*:*)
+	echo ${UNAME_MACHINE}-pc-cygwin
+	exit ;;
+    i*:MINGW*:*)
+	echo ${UNAME_MACHINE}-pc-mingw32
+	exit ;;
+    i*:windows32*:*)
+    	# uname -m includes "-pc" on this system.
+    	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
+    i*:PW*:*)
+	echo ${UNAME_MACHINE}-pc-pw32
+	exit ;;
+    x86:Interix*:[3456]*)
+	echo i586-pc-interix${UNAME_RELEASE}
+	exit ;;
+    EM64T:Interix*:[3456]*)
+	echo x86_64-unknown-interix${UNAME_RELEASE}
+	exit ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
+    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+	# UNAME_MACHINE based on the output of uname instead of i386?
+	echo i586-pc-interix
+	exit ;;
+    i*:UWIN*:*)
+	echo ${UNAME_MACHINE}-pc-uwin
+	exit ;;
+    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+	echo x86_64-unknown-cygwin
+	exit ;;
+    p*:CYGWIN*:*)
+	echo powerpcle-unknown-cygwin
+	exit ;;
+    prep*:SunOS:5.*:*)
+	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    *:GNU:*:*)
+	# the GNU system
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	exit ;;
+    *:GNU/*:*:*)
+	# other systems with GNU libc and userland
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	exit ;;
+    i*86:Minix:*:*)
+	echo ${UNAME_MACHINE}-pc-minix
+	exit ;;
+    arm*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    cris:Linux:*:*)
+	echo cris-axis-linux-gnu
+	exit ;;
+    crisv32:Linux:*:*)
+	echo crisv32-axis-linux-gnu
+	exit ;;
+    frv:Linux:*:*)
+    	echo frv-unknown-linux-gnu
+	exit ;;
+    ia64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m68*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    mips:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef mips
+	#undef mipsel
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=mipsel
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=mips
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^CPU/{
+		s: ::g
+		p
+	    }'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef mips64
+	#undef mips64el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=mips64el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=mips64
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^CPU/{
+		s: ::g
+		p
+	    }'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    or32:Linux:*:*)
+	echo or32-unknown-linux-gnu
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-gnu
+	exit ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-gnu
+	exit ;;
+    alpha:Linux:*:*)
+	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+	  EV5)   UNAME_MACHINE=alphaev5 ;;
+	  EV56)  UNAME_MACHINE=alphaev56 ;;
+	  PCA56) UNAME_MACHINE=alphapca56 ;;
+	  PCA57) UNAME_MACHINE=alphapca56 ;;
+	  EV6)   UNAME_MACHINE=alphaev6 ;;
+	  EV67)  UNAME_MACHINE=alphaev67 ;;
+	  EV68*) UNAME_MACHINE=alphaev68 ;;
+        esac
+	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	exit ;;
+    parisc:Linux:*:* | hppa:Linux:*:*)
+	# Look for CPU level
+	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+	  PA7*) echo hppa1.1-unknown-linux-gnu ;;
+	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
+	  *)    echo hppa-unknown-linux-gnu ;;
+	esac
+	exit ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-gnu
+	exit ;;
+    s390:Linux:*:* | s390x:Linux:*:*)
+	echo ${UNAME_MACHINE}-ibm-linux
+	exit ;;
+    sh64*:Linux:*:*)
+    	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    sh*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    sparc:Linux:*:* | sparc64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-gnu
+	exit ;;
+    x86_64:Linux:*:*)
+	echo x86_64-unknown-linux-gnu
+	exit ;;
+    i*86:Linux:*:*)
+	# The BFD linker knows what the default object file format is, so
+	# first see if it will tell us. cd to the root directory to prevent
+	# problems with other programs or directories called `ld' in the path.
+	# Set LC_ALL=C to ensure ld outputs messages in English.
+	ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
+			 | sed -ne '/supported targets:/!d
+				    s/[ 	][ 	]*/ /g
+				    s/.*supported targets: *//
+				    s/ .*//
+				    p'`
+        case "$ld_supported_targets" in
+	  elf32-i386)
+		TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
+		;;
+	  a.out-i386-linux)
+		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
+		exit ;;
+	  coff-i386)
+		echo "${UNAME_MACHINE}-pc-linux-gnucoff"
+		exit ;;
+	  "")
+		# Either a pre-BFD a.out linker (linux-gnuoldld) or
+		# one that does not give us useful --help.
+		echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
+		exit ;;
+	esac
+	# Determine whether the default compiler is a.out or elf
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <features.h>
+	#ifdef __ELF__
+	# ifdef __GLIBC__
+	#  if __GLIBC__ >= 2
+	LIBC=gnu
+	#  else
+	LIBC=gnulibc1
+	#  endif
+	# else
+	LIBC=gnulibc1
+	# endif
+	#else
+	#if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC)
+	LIBC=gnu
+	#else
+	LIBC=gnuaout
+	#endif
+	#endif
+	#ifdef __dietlibc__
+	LIBC=dietlibc
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^LIBC/{
+		s: ::g
+		p
+	    }'`"
+	test x"${LIBC}" != x && {
+		echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+		exit
+	}
+	test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; }
+	;;
+    i*86:DYNIX/ptx:4*:*)
+	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+	# earlier versions are messed up and put the nodename in both
+	# sysname and nodename.
+	echo i386-sequent-sysv4
+	exit ;;
+    i*86:UNIX_SV:4.2MP:2.*)
+        # Unixware is an offshoot of SVR4, but it has its own version
+        # number series starting with 2...
+        # I am not positive that other SVR4 systems won't match this,
+	# I just have to hope.  -- rms.
+        # Use sysv4.2uw... so that sysv4* matches it.
+	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+	exit ;;
+    i*86:OS/2:*:*)
+	# If we were able to find `uname', then EMX Unix compatibility
+	# is probably installed.
+	echo ${UNAME_MACHINE}-pc-os2-emx
+	exit ;;
+    i*86:XTS-300:*:STOP)
+	echo ${UNAME_MACHINE}-unknown-stop
+	exit ;;
+    i*86:atheos:*:*)
+	echo ${UNAME_MACHINE}-unknown-atheos
+	exit ;;
+    i*86:syllable:*:*)
+	echo ${UNAME_MACHINE}-pc-syllable
+	exit ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+	echo i386-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    i*86:*DOS:*:*)
+	echo ${UNAME_MACHINE}-pc-msdosdjgpp
+	exit ;;
+    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+	else
+		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+	fi
+	exit ;;
+    i*86:*:5:[678]*)
+    	# UnixWare 7.x, OpenUNIX and OpenServer 6.
+	case `/bin/uname -X | grep "^Machine"` in
+	    *486*)	     UNAME_MACHINE=i486 ;;
+	    *Pentium)	     UNAME_MACHINE=i586 ;;
+	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+	esac
+	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+	exit ;;
+    i*86:*:3.2:*)
+	if test -f /usr/options/cb.name; then
+		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+	elif /bin/uname -X 2>/dev/null >/dev/null ; then
+		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+			&& UNAME_MACHINE=i586
+		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+	else
+		echo ${UNAME_MACHINE}-pc-sysv32
+	fi
+	exit ;;
+    pc:*:*:*)
+	# Left here for compatibility:
+        # uname -m prints for DJGPP always 'pc', but it prints nothing about
+        # the processor, so we play safe by assuming i386.
+	echo i386-pc-msdosdjgpp
+        exit ;;
+    Intel:Mach:3*:*)
+	echo i386-pc-mach3
+	exit ;;
+    paragon:*:*:*)
+	echo i860-intel-osf1
+	exit ;;
+    i860:*:4.*:*) # i860-SVR4
+	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+	else # Add other i860-SVR4 vendors below as they are discovered.
+	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
+	fi
+	exit ;;
+    mini*:CTIX:SYS*5:*)
+	# "miniframe"
+	echo m68010-convergent-sysv
+	exit ;;
+    mc68k:UNIX:SYSTEM5:3.51m)
+	echo m68k-convergent-sysv
+	exit ;;
+    M680?0:D-NIX:5.3:*)
+	echo m68k-diab-dnix
+	exit ;;
+    M68*:*:R3V[5678]*:*)
+	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+	OS_REL=''
+	test -r /etc/.relid \
+	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+        /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+          && { echo i486-ncr-sysv4; exit; } ;;
+    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+	echo m68k-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    mc68030:UNIX_System_V:4.*:*)
+	echo m68k-atari-sysv4
+	exit ;;
+    TSUNAMI:LynxOS:2.*:*)
+	echo sparc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    rs6000:LynxOS:2.*:*)
+	echo rs6000-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
+	echo powerpc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    SM[BE]S:UNIX_SV:*:*)
+	echo mips-dde-sysv${UNAME_RELEASE}
+	exit ;;
+    RM*:ReliantUNIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    RM*:SINIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    *:SINIX-*:*:*)
+	if uname -p 2>/dev/null >/dev/null ; then
+		UNAME_MACHINE=`(uname -p) 2>/dev/null`
+		echo ${UNAME_MACHINE}-sni-sysv4
+	else
+		echo ns32k-sni-sysv
+	fi
+	exit ;;
+    PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+                      # says <Richard.M.Bartel@ccMail.Census.GOV>
+        echo i586-unisys-sysv4
+        exit ;;
+    *:UNIX_System_V:4*:FTX*)
+	# From Gerald Hewes <hewes@openmarket.com>.
+	# How about differentiating between stratus architectures? -djm
+	echo hppa1.1-stratus-sysv4
+	exit ;;
+    *:*:*:FTX*)
+	# From seanf@swdc.stratus.com.
+	echo i860-stratus-sysv4
+	exit ;;
+    i*86:VOS:*:*)
+	# From Paul.Green@stratus.com.
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
+    *:VOS:*:*)
+	# From Paul.Green@stratus.com.
+	echo hppa1.1-stratus-vos
+	exit ;;
+    mc68*:A/UX:*:*)
+	echo m68k-apple-aux${UNAME_RELEASE}
+	exit ;;
+    news*:NEWS-OS:6*:*)
+	echo mips-sony-newsos6
+	exit ;;
+    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+	if [ -d /usr/nec ]; then
+	        echo mips-nec-sysv${UNAME_RELEASE}
+	else
+	        echo mips-unknown-sysv${UNAME_RELEASE}
+	fi
+        exit ;;
+    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
+	echo powerpc-be-beos
+	exit ;;
+    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
+	echo powerpc-apple-beos
+	exit ;;
+    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
+	echo i586-pc-beos
+	exit ;;
+    SX-4:SUPER-UX:*:*)
+	echo sx4-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-5:SUPER-UX:*:*)
+	echo sx5-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-6:SUPER-UX:*:*)
+	echo sx6-nec-superux${UNAME_RELEASE}
+	exit ;;
+    Power*:Rhapsody:*:*)
+	echo powerpc-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Rhapsody:*:*)
+	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Darwin:*:*)
+	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+	case $UNAME_PROCESSOR in
+	    unknown) UNAME_PROCESSOR=powerpc ;;
+	esac
+	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+	exit ;;
+    *:procnto*:*:* | *:QNX:[0123456789]*:*)
+	UNAME_PROCESSOR=`uname -p`
+	if test "$UNAME_PROCESSOR" = "x86"; then
+		UNAME_PROCESSOR=i386
+		UNAME_MACHINE=pc
+	fi
+	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+	exit ;;
+    *:QNX:*:4*)
+	echo i386-pc-qnx
+	exit ;;
+    NSE-?:NONSTOP_KERNEL:*:*)
+	echo nse-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSR-?:NONSTOP_KERNEL:*:*)
+	echo nsr-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    *:NonStop-UX:*:*)
+	echo mips-compaq-nonstopux
+	exit ;;
+    BS2000:POSIX*:*:*)
+	echo bs2000-siemens-sysv
+	exit ;;
+    DS/*:UNIX_System_V:*:*)
+	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+	exit ;;
+    *:Plan9:*:*)
+	# "uname -m" is not consistent, so use $cputype instead. 386
+	# is converted to i386 for consistency with other x86
+	# operating systems.
+	if test "$cputype" = "386"; then
+	    UNAME_MACHINE=i386
+	else
+	    UNAME_MACHINE="$cputype"
+	fi
+	echo ${UNAME_MACHINE}-unknown-plan9
+	exit ;;
+    *:TOPS-10:*:*)
+	echo pdp10-unknown-tops10
+	exit ;;
+    *:TENEX:*:*)
+	echo pdp10-unknown-tenex
+	exit ;;
+    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+	echo pdp10-dec-tops20
+	exit ;;
+    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+	echo pdp10-xkl-tops20
+	exit ;;
+    *:TOPS-20:*:*)
+	echo pdp10-unknown-tops20
+	exit ;;
+    *:ITS:*:*)
+	echo pdp10-unknown-its
+	exit ;;
+    SEI:*:*:SEIUX)
+        echo mips-sei-seiux${UNAME_RELEASE}
+	exit ;;
+    *:DragonFly:*:*)
+	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+	exit ;;
+    *:*VMS:*:*)
+    	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+	case "${UNAME_MACHINE}" in
+	    A*) echo alpha-dec-vms ; exit ;;
+	    I*) echo ia64-dec-vms ; exit ;;
+	    V*) echo vax-dec-vms ; exit ;;
+	esac ;;
+    *:XENIX:*:SysV)
+	echo i386-pc-xenix
+	exit ;;
+    i*86:skyos:*:*)
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	exit ;;
+    i*86:rdos:*:*)
+	echo ${UNAME_MACHINE}-pc-rdos
+	exit ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
+     I don't know....  */
+  printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+  printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+          "4"
+#else
+	  ""
+#endif
+         ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+  printf ("arm-acorn-riscix\n"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+  printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+  int version;
+  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+  if (version < 4)
+    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+  else
+    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+  exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+  printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+  printf ("ns32k-encore-mach\n"); exit (0);
+#else
+  printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+  printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+  printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+  printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+    struct utsname un;
+
+    uname(&un);
+
+    if (strncmp(un.version, "V2", 2) == 0) {
+	printf ("i386-sequent-ptx2\n"); exit (0);
+    }
+    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+	printf ("i386-sequent-ptx1\n"); exit (0);
+    }
+    printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+#  include <sys/param.h>
+#  if defined (BSD)
+#   if BSD == 43
+      printf ("vax-dec-bsd4.3\n"); exit (0);
+#   else
+#    if BSD == 199006
+      printf ("vax-dec-bsd4.3reno\n"); exit (0);
+#    else
+      printf ("vax-dec-bsd\n"); exit (0);
+#    endif
+#   endif
+#  else
+    printf ("vax-dec-bsd\n"); exit (0);
+#  endif
+# else
+    printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+  printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+  exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+	{ echo "$SYSTEM_NAME"; exit; }
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+    case `getsysinfo -f cpu_type` in
+    c1*)
+	echo c1-convex-bsd
+	exit ;;
+    c2*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+	exit ;;
+    c34*)
+	echo c34-convex-bsd
+	exit ;;
+    c38*)
+	echo c38-convex-bsd
+	exit ;;
+    c4*)
+	echo c4-convex-bsd
+	exit ;;
+    esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess
+and
+  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches@gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo               = `(hostinfo) 2>/dev/null`
+/bin/universe          = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch              = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM  = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/trunk/Tools/config/config.sub b/trunk/Tools/config/config.sub
new file mode 100755
index 0000000..fab0aa3
--- /dev/null
+++ b/trunk/Tools/config/config.sub
@@ -0,0 +1,1616 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
+#   Inc.
+
+timestamp='2006-09-20'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine.  It does not imply ALL GNU software can.
+#
+# This file is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Please send patches to <config-patches@gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support.  The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+       $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help"
+       exit 1 ;;
+
+    *local*)
+       # First pass through any local machine types.
+       echo $1
+       exit ;;
+
+    * )
+       break ;;
+  esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+    exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+    exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+  nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
+  uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
+    os=-$maybe_os
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+    ;;
+  *)
+    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+    if [ $basic_machine != $1 ]
+    then os=`echo $1 | sed 's/.*-/-/'`
+    else os=; fi
+    ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work.  We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+	-sun*os*)
+		# Prevent following clause from handling this invalid input.
+		;;
+	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+	-apple | -axis | -knuth | -cray)
+		os=
+		basic_machine=$1
+		;;
+	-sim | -cisco | -oki | -wec | -winbond)
+		os=
+		basic_machine=$1
+		;;
+	-scout)
+		;;
+	-wrs)
+		os=-vxworks
+		basic_machine=$1
+		;;
+	-chorusos*)
+		os=-chorusos
+		basic_machine=$1
+		;;
+ 	-chorusrdb)
+ 		os=-chorusrdb
+		basic_machine=$1
+ 		;;
+	-hiux*)
+		os=-hiuxwe2
+		;;
+	-sco6)
+		os=-sco5v6
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5)
+		os=-sco3.2v5
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco4)
+		os=-sco3.2v4
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2.[4-9]*)
+		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2v[4-9]*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5v6*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco*)
+		os=-sco3.2v2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-udk*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-isc)
+		os=-isc2.2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-clix*)
+		basic_machine=clipper-intergraph
+		;;
+	-isc*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-lynx*)
+		os=-lynxos
+		;;
+	-ptx*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+		;;
+	-windowsnt*)
+		os=`echo $os | sed -e 's/windowsnt/winnt/'`
+		;;
+	-psos*)
+		os=-psos
+		;;
+	-mint | -mint[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+	# Recognize the basic CPU types without company name.
+	# Some are omitted here because they have special meanings below.
+	1750a | 580 \
+	| a29k \
+	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+	| am33_2.0 \
+	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
+	| bfin \
+	| c4x | clipper \
+	| d10v | d30v | dlx | dsp16xx \
+	| fr30 | frv \
+	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+	| i370 | i860 | i960 | ia64 \
+	| ip2k | iq2000 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | mcore \
+	| mips | mipsbe | mipseb | mipsel | mipsle \
+	| mips16 \
+	| mips64 | mips64el \
+	| mips64vr | mips64vrel \
+	| mips64orion | mips64orionel \
+	| mips64vr4100 | mips64vr4100el \
+	| mips64vr4300 | mips64vr4300el \
+	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
+	| mipsisa32 | mipsisa32el \
+	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64sb1 | mipsisa64sb1el \
+	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipstx39 | mipstx39el \
+	| mn10200 | mn10300 \
+	| mt \
+	| msp430 \
+	| nios | nios2 \
+	| ns16k | ns32k \
+	| or32 \
+	| pdp10 | pdp11 | pj | pjl \
+	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
+	| pyramid \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh64 | sh64le \
+	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+	| spu | strongarm \
+	| tahoe | thumb | tic4x | tic80 | tron \
+	| v850 | v850e \
+	| we32k \
+	| x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \
+	| z8k)
+		basic_machine=$basic_machine-unknown
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12)
+		# Motorola 68HC11/12.
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
+
+	# We use `pc' rather than `unknown'
+	# because (1) that's what they normally are, and
+	# (2) the word "unknown" tends to confuse beginning users.
+	i*86 | x86_64)
+	  basic_machine=$basic_machine-pc
+	  ;;
+	# Object if more than one company name word.
+	*-*-*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+	# Recognize the basic CPU types with company name.
+	580-* \
+	| a29k-* \
+	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
+	| avr-* | avr32-* \
+	| bfin-* | bs2000-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
+	| clipper-* | craynv-* | cydra-* \
+	| d10v-* | d30v-* | dlx-* \
+	| elxsi-* \
+	| f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
+	| h8300-* | h8500-* \
+	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+	| i*86-* | i860-* | i960-* | ia64-* \
+	| ip2k-* | iq2000-* \
+	| m32c-* | m32r-* | m32rle-* \
+	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* \
+	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+	| mips16-* \
+	| mips64-* | mips64el-* \
+	| mips64vr-* | mips64vrel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64vr4100-* | mips64vr4100el-* \
+	| mips64vr4300-* | mips64vr4300el-* \
+	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
+	| mipsisa32-* | mipsisa32el-* \
+	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64sb1-* | mipsisa64sb1el-* \
+	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
+	| msp430-* \
+	| nios-* | nios2-* \
+	| none-* | np1-* | ns16k-* | ns32k-* \
+	| orion-* \
+	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
+	| pyramid-* \
+	| romp-* | rs6000-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+	| sparclite-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \
+	| tahoe-* | thumb-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tron-* \
+	| v850-* | v850e-* | vax-* \
+	| we32k-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \
+	| xstormy16-* | xtensa-* \
+	| ymp-* \
+	| z8k-*)
+		;;
+	# Recognize the various machine names and aliases which stand
+	# for a CPU type and a company and sometimes even an OS.
+	386bsd)
+		basic_machine=i386-unknown
+		os=-bsd
+		;;
+	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+		basic_machine=m68000-att
+		;;
+	3b*)
+		basic_machine=we32k-att
+		;;
+	a29khif)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+    	abacus)
+		basic_machine=abacus-unknown
+		;;
+	adobe68k)
+		basic_machine=m68010-adobe
+		os=-scout
+		;;
+	alliant | fx80)
+		basic_machine=fx80-alliant
+		;;
+	altos | altos3068)
+		basic_machine=m68k-altos
+		;;
+	am29k)
+		basic_machine=a29k-none
+		os=-bsd
+		;;
+	amd64)
+		basic_machine=x86_64-pc
+		;;
+	amd64-*)
+		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	amdahl)
+		basic_machine=580-amdahl
+		os=-sysv
+		;;
+	amiga | amiga-*)
+		basic_machine=m68k-unknown
+		;;
+	amigaos | amigados)
+		basic_machine=m68k-unknown
+		os=-amigaos
+		;;
+	amigaunix | amix)
+		basic_machine=m68k-unknown
+		os=-sysv4
+		;;
+	apollo68)
+		basic_machine=m68k-apollo
+		os=-sysv
+		;;
+	apollo68bsd)
+		basic_machine=m68k-apollo
+		os=-bsd
+		;;
+	aux)
+		basic_machine=m68k-apple
+		os=-aux
+		;;
+	balance)
+		basic_machine=ns32k-sequent
+		os=-dynix
+		;;
+	c90)
+		basic_machine=c90-cray
+		os=-unicos
+		;;
+	convex-c1)
+		basic_machine=c1-convex
+		os=-bsd
+		;;
+	convex-c2)
+		basic_machine=c2-convex
+		os=-bsd
+		;;
+	convex-c32)
+		basic_machine=c32-convex
+		os=-bsd
+		;;
+	convex-c34)
+		basic_machine=c34-convex
+		os=-bsd
+		;;
+	convex-c38)
+		basic_machine=c38-convex
+		os=-bsd
+		;;
+	cray | j90)
+		basic_machine=j90-cray
+		os=-unicos
+		;;
+	craynv)
+		basic_machine=craynv-cray
+		os=-unicosmp
+		;;
+	cr16c)
+		basic_machine=cr16c-unknown
+		os=-elf
+		;;
+	crds | unos)
+		basic_machine=m68k-crds
+		;;
+	crisv32 | crisv32-* | etraxfs*)
+		basic_machine=crisv32-axis
+		;;
+	cris | cris-* | etrax*)
+		basic_machine=cris-axis
+		;;
+	crx)
+		basic_machine=crx-unknown
+		os=-elf
+		;;
+	da30 | da30-*)
+		basic_machine=m68k-da30
+		;;
+	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+		basic_machine=mips-dec
+		;;
+	decsystem10* | dec10*)
+		basic_machine=pdp10-dec
+		os=-tops10
+		;;
+	decsystem20* | dec20*)
+		basic_machine=pdp10-dec
+		os=-tops20
+		;;
+	delta | 3300 | motorola-3300 | motorola-delta \
+	      | 3300-motorola | delta-motorola)
+		basic_machine=m68k-motorola
+		;;
+	delta88)
+		basic_machine=m88k-motorola
+		os=-sysv3
+		;;
+	djgpp)
+		basic_machine=i586-pc
+		os=-msdosdjgpp
+		;;
+	dpx20 | dpx20-*)
+		basic_machine=rs6000-bull
+		os=-bosx
+		;;
+	dpx2* | dpx2*-bull)
+		basic_machine=m68k-bull
+		os=-sysv3
+		;;
+	ebmon29k)
+		basic_machine=a29k-amd
+		os=-ebmon
+		;;
+	elxsi)
+		basic_machine=elxsi-elxsi
+		os=-bsd
+		;;
+	encore | umax | mmax)
+		basic_machine=ns32k-encore
+		;;
+	es1800 | OSE68k | ose68k | ose | OSE)
+		basic_machine=m68k-ericsson
+		os=-ose
+		;;
+	fx2800)
+		basic_machine=i860-alliant
+		;;
+	genix)
+		basic_machine=ns32k-ns
+		;;
+	gmicro)
+		basic_machine=tron-gmicro
+		os=-sysv
+		;;
+	go32)
+		basic_machine=i386-pc
+		os=-go32
+		;;
+	h3050r* | hiux*)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	h8300hms)
+		basic_machine=h8300-hitachi
+		os=-hms
+		;;
+	h8300xray)
+		basic_machine=h8300-hitachi
+		os=-xray
+		;;
+	h8500hms)
+		basic_machine=h8500-hitachi
+		os=-hms
+		;;
+	harris)
+		basic_machine=m88k-harris
+		os=-sysv3
+		;;
+	hp300-*)
+		basic_machine=m68k-hp
+		;;
+	hp300bsd)
+		basic_machine=m68k-hp
+		os=-bsd
+		;;
+	hp300hpux)
+		basic_machine=m68k-hp
+		os=-hpux
+		;;
+	hp3k9[0-9][0-9] | hp9[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k2[0-9][0-9] | hp9k31[0-9])
+		basic_machine=m68000-hp
+		;;
+	hp9k3[2-9][0-9])
+		basic_machine=m68k-hp
+		;;
+	hp9k6[0-9][0-9] | hp6[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k7[0-79][0-9] | hp7[0-79][0-9])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k78[0-9] | hp78[0-9])
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][13679] | hp8[0-9][13679])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][0-9] | hp8[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hppa-next)
+		os=-nextstep3
+		;;
+	hppaosf)
+		basic_machine=hppa1.1-hp
+		os=-osf
+		;;
+	hppro)
+		basic_machine=hppa1.1-hp
+		os=-proelf
+		;;
+	i370-ibm* | ibm*)
+		basic_machine=i370-ibm
+		;;
+# I'm not sure what "Sysv32" means.  Should this be sysv3.2?
+	i*86v32)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv32
+		;;
+	i*86v4*)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv4
+		;;
+	i*86v)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv
+		;;
+	i*86sol2)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-solaris2
+		;;
+	i386mach)
+		basic_machine=i386-mach
+		os=-mach
+		;;
+	i386-vsta | vsta)
+		basic_machine=i386-unknown
+		os=-vsta
+		;;
+	iris | iris4d)
+		basic_machine=mips-sgi
+		case $os in
+		    -irix*)
+			;;
+		    *)
+			os=-irix4
+			;;
+		esac
+		;;
+	isi68 | isi)
+		basic_machine=m68k-isi
+		os=-sysv
+		;;
+	m88k-omron*)
+		basic_machine=m88k-omron
+		;;
+	magnum | m3230)
+		basic_machine=mips-mips
+		os=-sysv
+		;;
+	merlin)
+		basic_machine=ns32k-utek
+		os=-sysv
+		;;
+	mingw32)
+		basic_machine=i386-pc
+		os=-mingw32
+		;;
+	miniframe)
+		basic_machine=m68000-convergent
+		;;
+	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+	mips3*-*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+		;;
+	mips3*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+		;;
+	monitor)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	morphos)
+		basic_machine=powerpc-unknown
+		os=-morphos
+		;;
+	msdos)
+		basic_machine=i386-pc
+		os=-msdos
+		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
+	mvs)
+		basic_machine=i370-ibm
+		os=-mvs
+		;;
+	ncr3000)
+		basic_machine=i486-ncr
+		os=-sysv4
+		;;
+	netbsd386)
+		basic_machine=i386-unknown
+		os=-netbsd
+		;;
+	netwinder)
+		basic_machine=armv4l-rebel
+		os=-linux
+		;;
+	news | news700 | news800 | news900)
+		basic_machine=m68k-sony
+		os=-newsos
+		;;
+	news1000)
+		basic_machine=m68030-sony
+		os=-newsos
+		;;
+	news-3600 | risc-news)
+		basic_machine=mips-sony
+		os=-newsos
+		;;
+	necv70)
+		basic_machine=v70-nec
+		os=-sysv
+		;;
+	next | m*-next )
+		basic_machine=m68k-next
+		case $os in
+		    -nextstep* )
+			;;
+		    -ns2*)
+		      os=-nextstep2
+			;;
+		    *)
+		      os=-nextstep3
+			;;
+		esac
+		;;
+	nh3000)
+		basic_machine=m68k-harris
+		os=-cxux
+		;;
+	nh[45]000)
+		basic_machine=m88k-harris
+		os=-cxux
+		;;
+	nindy960)
+		basic_machine=i960-intel
+		os=-nindy
+		;;
+	mon960)
+		basic_machine=i960-intel
+		os=-mon960
+		;;
+	nonstopux)
+		basic_machine=mips-compaq
+		os=-nonstopux
+		;;
+	np1)
+		basic_machine=np1-gould
+		;;
+	nsr-tandem)
+		basic_machine=nsr-tandem
+		;;
+	op50n-* | op60c-*)
+		basic_machine=hppa1.1-oki
+		os=-proelf
+		;;
+	openrisc | openrisc-*)
+		basic_machine=or32-unknown
+		;;
+	os400)
+		basic_machine=powerpc-ibm
+		os=-os400
+		;;
+	OSE68000 | ose68000)
+		basic_machine=m68000-ericsson
+		os=-ose
+		;;
+	os68k)
+		basic_machine=m68k-none
+		os=-os68k
+		;;
+	pa-hitachi)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	paragon)
+		basic_machine=i860-intel
+		os=-osf
+		;;
+	pbd)
+		basic_machine=sparc-tti
+		;;
+	pbb)
+		basic_machine=m68k-tti
+		;;
+	pc532 | pc532-*)
+		basic_machine=ns32k-pc532
+		;;
+	pc98)
+		basic_machine=i386-pc
+		;;
+	pc98-*)
+		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium | p5 | k5 | k6 | nexgen | viac3)
+		basic_machine=i586-pc
+		;;
+	pentiumpro | p6 | 6x86 | athlon | athlon_*)
+		basic_machine=i686-pc
+		;;
+	pentiumii | pentium2 | pentiumiii | pentium3)
+		basic_machine=i686-pc
+		;;
+	pentium4)
+		basic_machine=i786-pc
+		;;
+	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumpro-* | p6-* | 6x86-* | athlon-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium4-*)
+		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pn)
+		basic_machine=pn-gould
+		;;
+	power)	basic_machine=power-ibm
+		;;
+	ppc)	basic_machine=powerpc-unknown
+		;;
+	ppc-*)	basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppcle | powerpclittle | ppc-le | powerpc-little)
+		basic_machine=powerpcle-unknown
+		;;
+	ppcle-* | powerpclittle-*)
+		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64)	basic_machine=powerpc64-unknown
+		;;
+	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+		basic_machine=powerpc64le-unknown
+		;;
+	ppc64le-* | powerpc64little-*)
+		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ps2)
+		basic_machine=i386-ibm
+		;;
+	pw32)
+		basic_machine=i586-unknown
+		os=-pw32
+		;;
+	rdos)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
+	rom68k)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	rm[46]00)
+		basic_machine=mips-siemens
+		;;
+	rtpc | rtpc-*)
+		basic_machine=romp-ibm
+		;;
+	s390 | s390-*)
+		basic_machine=s390-ibm
+		;;
+	s390x | s390x-*)
+		basic_machine=s390x-ibm
+		;;
+	sa29200)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	sb1)
+		basic_machine=mipsisa64sb1-unknown
+		;;
+	sb1el)
+		basic_machine=mipsisa64sb1el-unknown
+		;;
+	sde)
+		basic_machine=mipsisa32-sde
+		os=-elf
+		;;
+	sei)
+		basic_machine=mips-sei
+		os=-seiux
+		;;
+	sequent)
+		basic_machine=i386-sequent
+		;;
+	sh)
+		basic_machine=sh-hitachi
+		os=-hms
+		;;
+	sh64)
+		basic_machine=sh64-unknown
+		;;
+	sparclite-wrs | simso-wrs)
+		basic_machine=sparclite-wrs
+		os=-vxworks
+		;;
+	sps7)
+		basic_machine=m68k-bull
+		os=-sysv2
+		;;
+	spur)
+		basic_machine=spur-unknown
+		;;
+	st2000)
+		basic_machine=m68k-tandem
+		;;
+	stratus)
+		basic_machine=i860-stratus
+		os=-sysv4
+		;;
+	sun2)
+		basic_machine=m68000-sun
+		;;
+	sun2os3)
+		basic_machine=m68000-sun
+		os=-sunos3
+		;;
+	sun2os4)
+		basic_machine=m68000-sun
+		os=-sunos4
+		;;
+	sun3os3)
+		basic_machine=m68k-sun
+		os=-sunos3
+		;;
+	sun3os4)
+		basic_machine=m68k-sun
+		os=-sunos4
+		;;
+	sun4os3)
+		basic_machine=sparc-sun
+		os=-sunos3
+		;;
+	sun4os4)
+		basic_machine=sparc-sun
+		os=-sunos4
+		;;
+	sun4sol2)
+		basic_machine=sparc-sun
+		os=-solaris2
+		;;
+	sun3 | sun3-*)
+		basic_machine=m68k-sun
+		;;
+	sun4)
+		basic_machine=sparc-sun
+		;;
+	sun386 | sun386i | roadrunner)
+		basic_machine=i386-sun
+		;;
+	sv1)
+		basic_machine=sv1-cray
+		os=-unicos
+		;;
+	symmetry)
+		basic_machine=i386-sequent
+		os=-dynix
+		;;
+	t3e)
+		basic_machine=alphaev5-cray
+		os=-unicos
+		;;
+	t90)
+		basic_machine=t90-cray
+		os=-unicos
+		;;
+	tic54x | c54x*)
+		basic_machine=tic54x-unknown
+		os=-coff
+		;;
+	tic55x | c55x*)
+		basic_machine=tic55x-unknown
+		os=-coff
+		;;
+	tic6x | c6x*)
+		basic_machine=tic6x-unknown
+		os=-coff
+		;;
+	tx39)
+		basic_machine=mipstx39-unknown
+		;;
+	tx39el)
+		basic_machine=mipstx39el-unknown
+		;;
+	toad1)
+		basic_machine=pdp10-xkl
+		os=-tops20
+		;;
+	tower | tower-32)
+		basic_machine=m68k-ncr
+		;;
+	tpf)
+		basic_machine=s390x-ibm
+		os=-tpf
+		;;
+	udi29k)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	ultra3)
+		basic_machine=a29k-nyu
+		os=-sym1
+		;;
+	v810 | necv810)
+		basic_machine=v810-nec
+		os=-none
+		;;
+	vaxv)
+		basic_machine=vax-dec
+		os=-sysv
+		;;
+	vms)
+		basic_machine=vax-dec
+		os=-vms
+		;;
+	vpp*|vx|vx-*)
+		basic_machine=f301-fujitsu
+		;;
+	vxworks960)
+		basic_machine=i960-wrs
+		os=-vxworks
+		;;
+	vxworks68)
+		basic_machine=m68k-wrs
+		os=-vxworks
+		;;
+	vxworks29k)
+		basic_machine=a29k-wrs
+		os=-vxworks
+		;;
+	w65*)
+		basic_machine=w65-wdc
+		os=-none
+		;;
+	w89k-*)
+		basic_machine=hppa1.1-winbond
+		os=-proelf
+		;;
+	xbox)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
+	xps | xps100)
+		basic_machine=xps100-honeywell
+		;;
+	ymp)
+		basic_machine=ymp-cray
+		os=-unicos
+		;;
+	z8k-*-coff)
+		basic_machine=z8k-unknown
+		os=-sim
+		;;
+	none)
+		basic_machine=none-none
+		os=-none
+		;;
+
+# Here we handle the default manufacturer of certain CPU types.  It is in
+# some cases the only manufacturer, in others, it is the most popular.
+	w89k)
+		basic_machine=hppa1.1-winbond
+		;;
+	op50n)
+		basic_machine=hppa1.1-oki
+		;;
+	op60c)
+		basic_machine=hppa1.1-oki
+		;;
+	romp)
+		basic_machine=romp-ibm
+		;;
+	mmix)
+		basic_machine=mmix-knuth
+		;;
+	rs6000)
+		basic_machine=rs6000-ibm
+		;;
+	vax)
+		basic_machine=vax-dec
+		;;
+	pdp10)
+		# there are many clones, so DEC is not a safe bet
+		basic_machine=pdp10-unknown
+		;;
+	pdp11)
+		basic_machine=pdp11-dec
+		;;
+	we32k)
+		basic_machine=we32k-att
+		;;
+	sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
+		basic_machine=sh-unknown
+		;;
+	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+		basic_machine=sparc-sun
+		;;
+	cydra)
+		basic_machine=cydra-cydrome
+		;;
+	orion)
+		basic_machine=orion-highlevel
+		;;
+	orion105)
+		basic_machine=clipper-highlevel
+		;;
+	mac | mpw | mac-mpw)
+		basic_machine=m68k-apple
+		;;
+	pmac | pmac-mpw)
+		basic_machine=powerpc-apple
+		;;
+	*-unknown)
+		# Make sure to match an already-canonicalized machine name.
+		;;
+	*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+	*-digital*)
+		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+		;;
+	*-commodore*)
+		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+		;;
+	*)
+		;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+        # First match some system type aliases
+        # that might get confused with valid system types.
+	# -solaris* is a basic system type, with this one exception.
+	-solaris1 | -solaris1.*)
+		os=`echo $os | sed -e 's|solaris1|sunos4|'`
+		;;
+	-solaris)
+		os=-solaris2
+		;;
+	-svr4*)
+		os=-sysv4
+		;;
+	-unixware*)
+		os=-sysv4.2uw
+		;;
+	-gnu/linux*)
+		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+		;;
+	# First accept the basic system types.
+	# The portable systems comes first.
+	# Each alternative MUST END IN A *, to match a version number.
+	# -sysv* is not here because it comes later, after sysvr4.
+	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+	      | -aos* \
+	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -openbsd* | -solidbsd* \
+	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+	      | -chorusos* | -chorusrdb* \
+	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos* | -toppers*)
+	# Remember, each alternative MUST END IN *, to match a version number.
+		;;
+	-qnx*)
+		case $basic_machine in
+		    x86-* | i*86-*)
+			;;
+		    *)
+			os=-nto$os
+			;;
+		esac
+		;;
+	-nto-qnx*)
+		;;
+	-nto*)
+		os=`echo $os | sed -e 's|nto|nto-qnx|'`
+		;;
+	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+		;;
+	-mac*)
+		os=`echo $os | sed -e 's|mac|macos|'`
+		;;
+	-linux-dietlibc)
+		os=-linux-dietlibc
+		;;
+	-linux*)
+		os=`echo $os | sed -e 's|linux|linux-gnu|'`
+		;;
+	-sunos5*)
+		os=`echo $os | sed -e 's|sunos5|solaris2|'`
+		;;
+	-sunos6*)
+		os=`echo $os | sed -e 's|sunos6|solaris3|'`
+		;;
+	-opened*)
+		os=-openedition
+		;;
+        -os400*)
+		os=-os400
+		;;
+	-wince*)
+		os=-wince
+		;;
+	-osfrose*)
+		os=-osfrose
+		;;
+	-osf*)
+		os=-osf
+		;;
+	-utek*)
+		os=-bsd
+		;;
+	-dynix*)
+		os=-bsd
+		;;
+	-acis*)
+		os=-aos
+		;;
+	-atheos*)
+		os=-atheos
+		;;
+	-syllable*)
+		os=-syllable
+		;;
+	-386bsd)
+		os=-bsd
+		;;
+	-ctix* | -uts*)
+		os=-sysv
+		;;
+	-nova*)
+		os=-rtmk-nova
+		;;
+	-ns2 )
+		os=-nextstep2
+		;;
+	-nsk*)
+		os=-nsk
+		;;
+	# Preserve the version number of sinix5.
+	-sinix5.*)
+		os=`echo $os | sed -e 's|sinix|sysv|'`
+		;;
+	-sinix*)
+		os=-sysv4
+		;;
+        -tpf*)
+		os=-tpf
+		;;
+	-triton*)
+		os=-sysv3
+		;;
+	-oss*)
+		os=-sysv3
+		;;
+	-svr4)
+		os=-sysv4
+		;;
+	-svr3)
+		os=-sysv3
+		;;
+	-sysvr4)
+		os=-sysv4
+		;;
+	# This must come after -sysvr4.
+	-sysv*)
+		;;
+	-ose*)
+		os=-ose
+		;;
+	-es1800*)
+		os=-ose
+		;;
+	-xenix)
+		os=-xenix
+		;;
+	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+		os=-mint
+		;;
+	-aros*)
+		os=-aros
+		;;
+	-kaos*)
+		os=-kaos
+		;;
+	-zvmoe)
+		os=-zvmoe
+		;;
+	-none)
+		;;
+	*)
+		# Get rid of the `-' at the beginning of $os.
+		os=`echo $os | sed 's/[^-]*-//'`
+		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+		exit 1
+		;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system.  Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+        score-*)
+		os=-elf
+		;;
+        spu-*)
+		os=-elf
+		;;
+	*-acorn)
+		os=-riscix1.2
+		;;
+	arm*-rebel)
+		os=-linux
+		;;
+	arm*-semi)
+		os=-aout
+		;;
+        c4x-* | tic4x-*)
+        	os=-coff
+		;;
+	# This must come before the *-dec entry.
+	pdp10-*)
+		os=-tops20
+		;;
+	pdp11-*)
+		os=-none
+		;;
+	*-dec | vax-*)
+		os=-ultrix4.2
+		;;
+	m68*-apollo)
+		os=-domain
+		;;
+	i386-sun)
+		os=-sunos4.0.2
+		;;
+	m68000-sun)
+		os=-sunos3
+		# This also exists in the configure program, but was not the
+		# default.
+		# os=-sunos4
+		;;
+	m68*-cisco)
+		os=-aout
+		;;
+	mips*-cisco)
+		os=-elf
+		;;
+	mips*-*)
+		os=-elf
+		;;
+	or32-*)
+		os=-coff
+		;;
+	*-tti)	# must be before sparc entry or we get the wrong os.
+		os=-sysv3
+		;;
+	sparc-* | *-sun)
+		os=-sunos4.1.1
+		;;
+	*-be)
+		os=-beos
+		;;
+	*-haiku)
+		os=-haiku
+		;;
+	*-ibm)
+		os=-aix
+		;;
+    	*-knuth)
+		os=-mmixware
+		;;
+	*-wec)
+		os=-proelf
+		;;
+	*-winbond)
+		os=-proelf
+		;;
+	*-oki)
+		os=-proelf
+		;;
+	*-hp)
+		os=-hpux
+		;;
+	*-hitachi)
+		os=-hiux
+		;;
+	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+		os=-sysv
+		;;
+	*-cbm)
+		os=-amigaos
+		;;
+	*-dg)
+		os=-dgux
+		;;
+	*-dolphin)
+		os=-sysv3
+		;;
+	m68k-ccur)
+		os=-rtu
+		;;
+	m88k-omron*)
+		os=-luna
+		;;
+	*-next )
+		os=-nextstep
+		;;
+	*-sequent)
+		os=-ptx
+		;;
+	*-crds)
+		os=-unos
+		;;
+	*-ns)
+		os=-genix
+		;;
+	i370-*)
+		os=-mvs
+		;;
+	*-next)
+		os=-nextstep3
+		;;
+	*-gould)
+		os=-sysv
+		;;
+	*-highlevel)
+		os=-bsd
+		;;
+	*-encore)
+		os=-bsd
+		;;
+	*-sgi)
+		os=-irix
+		;;
+	*-siemens)
+		os=-sysv4
+		;;
+	*-masscomp)
+		os=-rtu
+		;;
+	f30[01]-fujitsu | f700-fujitsu)
+		os=-uxpv
+		;;
+	*-rom68k)
+		os=-coff
+		;;
+	*-*bug)
+		os=-coff
+		;;
+	*-apple)
+		os=-macos
+		;;
+	*-atari*)
+		os=-mint
+		;;
+	*)
+		os=-none
+		;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer.  We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+	*-unknown)
+		case $os in
+			-riscix*)
+				vendor=acorn
+				;;
+			-sunos*)
+				vendor=sun
+				;;
+			-aix*)
+				vendor=ibm
+				;;
+			-beos*)
+				vendor=be
+				;;
+			-hpux*)
+				vendor=hp
+				;;
+			-mpeix*)
+				vendor=hp
+				;;
+			-hiux*)
+				vendor=hitachi
+				;;
+			-unos*)
+				vendor=crds
+				;;
+			-dgux*)
+				vendor=dg
+				;;
+			-luna*)
+				vendor=omron
+				;;
+			-genix*)
+				vendor=ns
+				;;
+			-mvs* | -opened*)
+				vendor=ibm
+				;;
+			-os400*)
+				vendor=ibm
+				;;
+			-ptx*)
+				vendor=sequent
+				;;
+			-tpf*)
+				vendor=ibm
+				;;
+			-vxsim* | -vxworks* | -windiss*)
+				vendor=wrs
+				;;
+			-aux*)
+				vendor=apple
+				;;
+			-hms*)
+				vendor=hitachi
+				;;
+			-mpw* | -macos*)
+				vendor=apple
+				;;
+			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+				vendor=atari
+				;;
+			-vos*)
+				vendor=stratus
+				;;
+		esac
+		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+		;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/trunk/Tools/mkdist.py b/trunk/Tools/mkdist.py
new file mode 100755
index 0000000..f5bdd01
--- /dev/null
+++ b/trunk/Tools/mkdist.py
@@ -0,0 +1,69 @@
+#!/usr/local/bin/python
+
+# This script builds a swig-1.3 distribution.
+# Usage : mkdist.py version, where version should be 1.3.x
+
+import sys
+import string
+import os
+
+def failed():
+  print "mkdist.py failed to complete"
+  sys.exit(2)
+
+
+try:
+   version = sys.argv[1]
+   dirname = "swig-" + version
+except:
+   print "Usage: mkdist.py version, where version should be 1.3.x"
+   sys.exit(1)
+
+# Check name matches normal unix conventions
+if string.lower(dirname) != dirname:
+  print "directory name ("+dirname+") should be in lowercase"
+  sys.exit(3)
+
+# If directory and tarball exist, remove it
+print "Removing ", dirname
+os.system("rm -rf "+dirname)
+
+print "Removing "+dirname+".tar if exists"
+os.system("rm -f "+dirname+".tar.gz")
+
+print "Removing "+dirname+".tar.gz if exists"
+os.system("rm -f "+dirname+".tar")
+
+# Do a SVN export into the directory name
+
+print "Grabbing latest SWIG from svn"
+os.system("svn export -r HEAD https://swig.svn.sourceforge.net/svnroot/swig/trunk "+dirname) == 0 or failed()
+
+# Remove the debian directory -- it's not official
+
+os.system("rm -Rf "+dirname+"/debian") == 0 or failed()
+
+# Blow away all .cvsignore files
+
+print "Blowing away .cvsignore files"
+os.system("find "+dirname+" -name .cvsignore -exec rm {} \\;") == 0 or failed()
+
+# Go build the system
+
+print "Building system"
+os.system("cd "+dirname+"; ./autogen.sh") == 0 or failed()
+os.system("cd "+dirname+"/Tools/WAD; autoconf") == 0 or failed()
+os.system("cd "+dirname+"/Source/CParse; bison -y -d parser.y; mv y.tab.c parser.c; mv y.tab.h parser.h") == 0 or failed()
+os.system("cd "+dirname+"; make -f Makefile.in libfiles srcdir=./") == 0 or failed()
+
+# Remove autoconf files
+os.system("find "+dirname+" -name autom4te.cache -exec rm -rf {} \\;")
+
+# Build documentation
+print "Building documentation"
+os.system("cd "+dirname+"/Doc/Manual && make && rm *.bak") == 0 or failed()
+
+# Build the tar-ball
+os.system("tar -cf "+dirname+".tar "+dirname) == 0 or failed()
+os.system("gzip "+dirname+".tar") == 0 or failed()
+
diff --git a/trunk/Tools/mkrelease.py b/trunk/Tools/mkrelease.py
new file mode 100755
index 0000000..d7927f8
--- /dev/null
+++ b/trunk/Tools/mkrelease.py
@@ -0,0 +1,39 @@
+#!/usr/bin/python
+
+# This script builds the SWIG source tarball, creates the Windows executable and the Windows zip package
+# and uploads them both to SF ready for release
+import sys
+import string
+import os
+
+def failed(message):
+  if message == "":
+    print "mkrelease.py failed to complete"
+  else:
+    print message
+  sys.exit(2)
+
+try:
+   version = sys.argv[1]
+   username = sys.argv[2]
+except:
+   print "Usage: python mkrelease.py version username"
+   print "where version should be 1.3.x and username is your SF username"
+   sys.exit(1)
+
+print "Looking for rsync"
+os.system("which rsync") and failed("rsync not installed/found. Please install.")
+
+print "Making source tarball"
+os.system("python ./mkdist.py " + version) and failed("")
+
+print "Build Windows package"
+os.system("./mkwindows.sh " + version) and failed("")
+
+print "Uploading to Sourceforge"
+os.system("rsync --archive --verbose -P --times -e ssh swig-" + version + ".tar.gz " + username + "@frs.sourceforge.net:uploads/") and failed("")
+os.system("rsync --archive --verbose -P --times -e ssh swigwin-" + version + ".zip " + username + "@frs.sourceforge.net:uploads/") and failed("")
+
+os.system("svn copy -m \"rel-" + version + "\" https://swig.svn.sourceforge.net/svnroot/swig/trunk https://swig.svn.sourceforge.net/svnroot/swig/tags/rel-" + version + "/")
+
+print "Finished"
diff --git a/trunk/Tools/mkwindows.sh b/trunk/Tools/mkwindows.sh
new file mode 100755
index 0000000..116e32d
--- /dev/null
+++ b/trunk/Tools/mkwindows.sh
@@ -0,0 +1,108 @@
+#!/bin/sh
+
+# Build Windows distribution (swigwin-1.3.x.zip) -- requires running in either:
+# - MinGW environment
+# - Linux using MinGW cross compiler
+# - Cygwin using MinGW compiler
+
+# path to zip program
+zip=
+
+# options for configure
+extraconfigureoptions=
+compileflags="-O2"
+extracompileflags=
+
+if test x$1 != x; then
+    version=$1
+    if test x$2 != x; then
+        zip=$2;
+        echo zip: $zip;
+    fi
+else
+    echo "Usage: mkwindows.sh version [zip]"
+    echo "       Build Windows distribution. Works on Cygwin, MinGW or Linux"
+    echo "       version should be 1.3.x"
+    echo "       zip is full path to zip program - default is /c/cygwin/bin/zip on MinGW, zip on Linux and Cygwin"
+    exit 1
+fi
+
+uname=`uname -a`
+mingw=`echo "$uname" | grep -i mingw`
+linux=`echo "$uname" | grep -i linux`
+cygwin=`echo "$uname" | grep -i cygwin`
+if test "$mingw"; then
+  echo "Building native Windows executable on MinGW";
+  if test x$zip = x; then
+    zip=/c/cygwin/bin/zip
+  fi
+else 
+  if test "$linux"; then
+    echo "Building native Windows executable on Linux"
+    if test x$zip = x; then
+      zip=zip
+    fi
+    extraconfigureoptions="--host=i586-mingw32msvc --build=i686-linux CXXFLAGS=-O2 CFLAGS=-O2"
+  else 
+    if test "$cygwin"; then
+      echo "Building native Windows executable on Cygwin"
+      if test x$zip = x; then
+        zip=zip
+      fi
+      compileflags="-O2 -mno-cygwin"
+    else
+      echo "Unknown platform. Requires either Linux or MinGW."
+      exit 1;
+    fi
+  fi
+fi
+
+swigbasename=swig-$version
+swigwinbasename=swigwin-$version
+tarball=$swigbasename.tar.gz
+
+if test -f "$tarball"; then
+    builddir=build-$version
+    if test -e $builddir; then
+      echo "Deleting directory $builddir..."
+      rm -rf $builddir
+    fi
+    echo "Creating directory $builddir..."
+    mkdir $builddir
+    cd $builddir
+    echo "Unzipping tarball..."
+    tar -zxf ../$tarball
+    sleep 2 # fix strange not finding newly created directory
+    if test -d $swigbasename; then
+      mv $swigbasename $swigwinbasename
+      tar -zxf ../$tarball
+      cd $swigbasename
+      echo Running: ./configure $extraconfigureoptions CFLAGS="$compileflags" CXXFLAGS="$compileflags"
+      ./configure $extraconfigureoptions CFLAGS="$compileflags" CXXFLAGS="$compileflags"
+      echo "Compiling (quietly)..."
+      make > build.log
+      echo "Simple check to see if swig.exe runs..."
+      env LD_LIBRARY_PATH= PATH= ./swig.exe -version
+      echo "Creating $swigwinbasename.zip..."
+      cd ..
+      cp $swigbasename/swig.exe $swigwinbasename
+      cp $swigbasename/Lib/swigwarn.swg $swigwinbasename/Lib
+      sleep 2 # fix strange not finding swig.exe
+      echo "Unzip into a directory of your choice. Please read the README file as well as Doc\Manual\Windows.html for installation instructions." > swig_windows_zip_comments.txt
+      rm -f ../$swigwinbasename.zip
+      $zip -q -r -9 -z < swig_windows_zip_comments.txt ../$swigwinbasename.zip $swigwinbasename
+      rm -f swig_windows_zip_comments.txt
+      echo "Cleaning up..."
+      cd ..
+      rm -rf $builddir
+      echo "Finished building $swigwinbasename.zip"
+    else
+      echo "Expecting tarball to create directory: $swigbasename but it does not exist"
+      exit 1
+    fi
+else
+    echo tarball missing: $tarball 
+    exit 1
+fi
+
+exit 0
diff --git a/trunk/Tools/setup.py.tmpl b/trunk/Tools/setup.py.tmpl
new file mode 100644
index 0000000..0bfcde2
--- /dev/null
+++ b/trunk/Tools/setup.py.tmpl
@@ -0,0 +1,139 @@
+#!@PYTHON@
+'''A setup.py script with better SWIG support.  To use it, either
+rename it to setup.py.in and have it pe processed by your configure
+script (you will need to define @PYTHON@), or replace the @*@ strings
+by hand.
+
+Copyright 2001,  Anthony Joseph Seward'''
+
+
+from distutils.core import setup, Extension
+
+###############################################################################
+##      Start of better Swig support
+###############################################################################
+from distutils.command.build_ext import build_ext
+import os
+import string
+class build_swig_ext(build_ext):
+    '''Better swig support for Distutils'''
+
+    ## __ Tell Distutils about the options
+    user_options = build_ext.user_options
+    boolean_options = build_ext.boolean_options
+
+    user_options.append(
+        ('swig-doc=', None,
+         'what type of documentation should SWIG produce (default: none)')
+        )
+    user_options.append(
+        ('swig-inc=', None,
+         'a list of directories to add to the SWIG include path'
+         +  "(separated by ':')(default: SWIG)")
+        )
+    user_options.append(
+        ('swig-shadow', None,
+         'have SWIG create shadow classes'
+         + ' (also adds docstrings to the shadow classes')
+        )
+
+    boolean_options.append('swig-shadow')
+
+    def initialize_options(self):
+        '''Initialize the new options after the inherited ones'''
+        build_ext.initialize_options(self)
+        self.swig_doc = 'none'
+        self.swig_inc = 'SWIG'
+        self.swig_shadow = None        
+    
+    def swig_sources(self, sources):
+        """Override the definition of 'swig_sources' in build_ext.  This
+        is essentially the same function but with better swig support.
+        I will now quote the original docstring:
+
+          Walk the list of source files in 'sources', looking for SWIG
+          interface (.i) files.  Run SWIG on all that are found, and
+          return a modified 'sources' list with SWIG source files replaced
+          by the generated C (or C++) files.
+        """
+
+        new_sources = []
+        swig_sources = []
+        swig_targets = {}
+
+        # XXX this drops generated C/C++ files into the source tree, which
+        # is fine for developers who want to distribute the generated
+        # source -- but there should be an option to put SWIG output in
+        # the temp dir.
+
+        if self.swig_cpp:
+            target_ext = '.cpp'
+        else:
+            target_ext = '.c'
+
+        for source in sources:
+            (base, ext) = os.path.splitext(source)
+            if ext == ".i":             # SWIG interface file
+                new_sources.append(base + target_ext)
+                swig_sources.append(source)
+                swig_targets[source] = new_sources[-1]
+            else:
+                new_sources.append(source)
+
+        if not swig_sources:
+            return new_sources
+
+        includes = self.swig_inc
+        if type(includes) is type(''):
+            includes = string.split(includes, ':')
+            includes = map(lambda x: '-I'+x, includes)
+            includes = string.join(includes)
+        
+        swig = self.find_swig()
+##        swig_cmd = [swig, "-python", "-d%s" % self.swig_doc,  includes]
+        swig_cmd = [swig, '-v', '-python', '-d%s' % self.swig_doc,  includes]
+        if self.swig_cpp:
+            swig_cmd.append('-c++')
+
+        if self.swig_shadow:
+            swig_cmd.append('-shadow')
+## swig1.1            swig_cmd.append('-docstring')
+
+        for source in swig_sources:
+            target = swig_targets[source]
+            self.announce('swigging %s to %s' % (source, target))
+            self.spawn(swig_cmd + ['-o', target, source])
+
+        return new_sources
+
+    # swig_sources ()
+###############################################################################
+##      End of improved swig support
+###############################################################################
+
+package = '@PACKAGE@'
+version = '@VERSION@'
+include_dirs = ['@top_srcdir@']
+lib_dirs = ['@top_srcdir@/@PACKAGE@']
+libraries = ['@PACKAGE@', 'stdc++']
+
+setup(name = package,
+      version = version,
+      description = '',
+      author = '',
+      author_email = '',
+      url = 'http://',
+
+      cmdclass = {'build_ext': build_swig_ext},
+      ext_modules = [Extension(package+'cmodule',
+                               [package+'.i'],
+                               include_dirs=include_dirs,
+                               library_dirs=lib_dirs,
+                               libraries=libraries,
+                               )],
+      options = {'build_ext':
+                 {'swig_doc': 'html',
+                  'swig_cpp': not None,
+                  'swig_shadow': not None}
+                 }
+      )
diff --git a/trunk/Tools/swig.spec.1 b/trunk/Tools/swig.spec.1
new file mode 100644
index 0000000..7af0440
--- /dev/null
+++ b/trunk/Tools/swig.spec.1
@@ -0,0 +1,42 @@
+%define version 1.3.7
+%define release	1
+
+# Preamble
+Summary: Simplified Wrapper and Interface Generator
+Name: swig
+Version: %{version}
+Release: %{release}
+Copyright: BSD
+URL: http://www.swig.org
+Group: System Environment/Daemons
+Source0: http://download.sourceforge.net/swig/swig-%{version}.tar.gz
+Packager: Dustin Mitchell <dustin@cs.uchicago.edu>
+BuildRoot: /var/tmp/rpm/swig-root
+Prefix: /usr
+
+%description
+SWIG is an interface compiler that connects programs written in C,
+C++, and Objective-C with scripting languages including Perl, Python,
+and Tcl/Tk. It works by taking the declarations commonly found in
+C/C++ header files and using them to generate the glue code (wrappers)
+that scripting languages need to access the underlying C/C++ code
+
+# PREP
+%prep
+%setup -n SWIG-%{version}
+
+# BUILD
+%build
+./configure --prefix=%prefix
+make
+
+# INSTALL
+%install
+rm -rf ${RPM_BUILD_ROOT}
+install -d -m 755 ${RPM_BUILD_ROOT}
+make prefix=${RPM_BUILD_ROOT}%prefix install
+
+# FILES
+%files
+%prefix/lib/*
+%prefix/bin/swig
diff --git a/trunk/Tools/vcfilter b/trunk/Tools/vcfilter
new file mode 100755
index 0000000..2683fc2
--- /dev/null
+++ b/trunk/Tools/vcfilter
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+# This is a simple utility for Cygwin/Mingw which is useful when running the SWIG
+# test-suite through Visual Studio. If the output from the test-suite is piped
+# through this utility, it will filter the junk that the compiler generates.
+# Typical usage: make check | vcfilter
+
+# dos2unix needed for ^ and $ to work.
+2>&1 dos2unix | grep -v "\.cxx$" | grep -v "\.c$" | grep -v "^   Creating library" | grep -v "^Generating Code"
+
diff --git a/trunk/Win/README.txt b/trunk/Win/README.txt
new file mode 100644
index 0000000..4bdb9e1
--- /dev/null
+++ b/trunk/Win/README.txt
@@ -0,0 +1 @@
+Please see the Doc/Manual/Windows.html file in the main manual for instructions for using and installing SWIG on Windows including running the examples.
diff --git a/trunk/autogen.sh b/trunk/autogen.sh
new file mode 100755
index 0000000..33f54aa
--- /dev/null
+++ b/trunk/autogen.sh
@@ -0,0 +1,15 @@
+#! /bin/sh
+
+# Bootstrap the development environment - add extra files needed to run configure. 
+# Note autoreconf should do what this file achieves, but it has a bug when working with automake!
+# The latest config.guess and config.sub should be copied into Tools/config and checked into SVN
+# when upgrading the autotools. Otherwise this script will ensure the latest is copied from 
+# your autotool installation.
+
+set -e
+set -x
+test -d Tools/config || mkdir Tools/config
+${ACLOCAL-aclocal} -I Tools/config
+${AUTOHEADER-autoheader}
+${AUTOMAKE-automake} --add-missing --copy --force-missing
+${AUTOCONF-autoconf}
diff --git a/trunk/configure.in b/trunk/configure.in
new file mode 100644
index 0000000..a6aa775
--- /dev/null
+++ b/trunk/configure.in
@@ -0,0 +1,2048 @@
+dnl Process this file with autoconf to produce a configure script.
+dnl The macros which aren't shipped with the autotools are stored in the
+dnl Tools/config directory in .m4 files.
+
+AC_INIT([swig],[1.3.36],[http://www.swig.org])
+AC_PREREQ(2.58)
+AC_CONFIG_SRCDIR([Source/Swig/swig.h])
+AC_CONFIG_AUX_DIR([Tools/config])
+AC_CONFIG_HEADERS([Source/Include/swigconfig.h])
+AC_CANONICAL_HOST
+AM_INIT_AUTOMAKE
+
+dnl Some extra defines for the config file
+AH_BOTTOM([
+/* Default language */
+#define SWIG_LANG               "-tcl"
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if defined(_MSC_VER)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+])
+
+dnl Checks for programs.
+AC_PROG_CC
+AC_PROG_CXX
+AC_PROG_YACC
+AC_EXEEXT
+AC_OBJEXT
+AC_PROG_RANLIB
+AM_PROG_CC_C_O  # Needed for subdir-objects in AUTOMAKE_OPTIONS
+AC_CHECK_PROGS(AR, ar aal, ar)
+AC_SUBST(AR)
+
+AC_COMPILE_WARNINGS # Increase warning levels
+
+AC_DEFINE_UNQUOTED(SWIG_CXX, ["$CXX"], [Compiler that built SWIG])
+AC_DEFINE_UNQUOTED(SWIG_PLATFORM, ["$build"], [Platform that SWIG is built for])
+
+
+dnl Checks for header files.
+AC_HEADER_STDC
+
+dnl How to specify include directories that may be system directories.
+# -I should not be used on system directories (GCC)
+if test "$GCC" = yes; then
+    ISYSTEM="-isystem "
+else
+    ISYSTEM="-I"
+fi
+
+
+dnl Checks for types.
+AC_LANG_PUSH([C++])
+AC_CHECK_TYPES([bool])
+AC_LANG_POP([C++])
+
+
+# Set info about shared libraries.
+AC_SUBST(SO)
+AC_SUBST(LDSHARED)
+AC_SUBST(CCSHARED)
+AC_SUBST(CXXSHARED)
+AC_SUBST(TRYLINKINGWITHCXX)
+AC_SUBST(LINKFORSHARED)
+
+# SO is the extension of shared libraries `(including the dot!)
+AC_MSG_CHECKING(SO)
+if test -z "$SO"
+then
+	case $host in
+	*-*-hp*) SO=.sl;;
+	*-*-darwin*) SO=.bundle;;
+	*-*-cygwin* | *-*-mingw*) SO=.dll;;
+	*) SO=.so;;
+	esac
+fi
+AC_MSG_RESULT($SO)
+
+# LDSHARED is the ld *command* used to create shared library
+# -- "ld" on SunOS 4.x.x, "ld -G" on SunOS 5.x, "ld -shared" on IRIX 5
+# (Shared libraries in this instance are shared modules to be loaded into
+# Python, as opposed to building Python itself as a shared library.)
+AC_MSG_CHECKING(LDSHARED)
+if test -z "$LDSHARED"
+then
+	case $host in
+	*-*-aix*) LDSHARED="\$(srcdir)/ld_so_aix \$(CC)";;
+	*-*-cygwin* | *-*-mingw*)
+            if test "$GCC" = yes; then
+                LDSHARED="$CC -shared"
+            else
+                if test "cl" = $CC ;  then
+                    # Microsoft Visual C++ (MSVC)
+                    LDSHARED="$CC -nologo -LD"
+                else
+                    # Unknown compiler try gcc approach
+                    LDSHARED="$CC -shared"
+                fi
+            fi ;;
+	*-*-irix5*) LDSHARED="ld -shared";;
+	*-*-irix6*) LDSHARED="ld ${SGI_ABI} -shared -all";;
+	*-*-sunos4*) LDSHARED="ld";;
+	*-*-solaris*) LDSHARED="ld -G";;
+	*-*-hp*) LDSHARED="ld -b";;
+	*-*-osf*) LDSHARED="ld -shared -expect_unresolved \"*\"";;
+	*-sequent-sysv4) LDSHARED="ld -G";;
+	*-*-next*)
+		if test "$ns_dyld"
+		then LDSHARED='$(CC) $(LDFLAGS) -bundle -prebind'
+		else LDSHARED='$(CC) $(CFLAGS) -nostdlib -r';
+		fi
+                if test "$with_next_framework" ; then
+		    LDSHARED="$LDSHARED \$(LDLIBRARY)"
+		fi ;;
+	*-*-linux*) LDSHARED="gcc -shared";;
+	*-*-dgux*) LDSHARED="ld -G";;
+	*-*-freebsd3*) LDSHARED="gcc -shared";;
+	*-*-freebsd* | *-*-openbsd*) LDSHARED="ld -Bshareable";;
+	*-*-netbsd*)
+		if [[ "`$CC -dM -E - </dev/null | grep __ELF__`" != "" ]]
+		then
+			LDSHARED="cc -shared"
+		else
+			LDSHARED="ld -Bshareable"
+		fi;;
+	*-sco-sysv*) LDSHARED="cc -G -KPIC -Ki486 -belf -Wl,-Bexport";;
+	*-*-darwin*) LDSHARED="cc -bundle -undefined suppress -flat_namespace";;
+	*)	LDSHARED="ld";;
+	esac
+fi
+AC_MSG_RESULT($LDSHARED)
+# CXXSHARED is the ld *command* used to create C++ shared library
+# -- "ld" on SunOS 4.x.x, "ld -G" on SunOS 5.x, "ld -shared" on IRIX 5
+# (Shared libraries in this instance are shared modules to be loaded into
+# Python, as opposed to building Python itself as a shared library.)
+AC_MSG_CHECKING(CXXSHARED)
+if test -z "$CXXSHARED"
+then
+	CXXSHARED="$LDSHARED"
+fi
+AC_MSG_RESULT($CXXSHARED)
+
+#
+AC_MSG_CHECKING(TRYLINKINGWITHCXX)
+if test -z "$TRYLINKINGWITHCXX"
+then
+	case $host in
+	*-*-solaris*) if test "$GCC" = yes;
+             then TRYLINKINGWITHCXX="CXXSHARED= $CXX -Wl,-G";
+             else TRYLINKINGWITHCXX="CXXSHARED= $CXX -G -L/opt/SUNWspro/lib -lCrun -lCstd";
+             fi;;
+        *-*-hp*) TRYLINKINGWITHCXX="CXXSHARED= $CXX +z ";;
+        *-*-darwin*) TRYLINKINGWITHCXX="CXXSHARED= $CXX -bundle -undefined suppress -flat_namespace";;
+        *-*-cygwin* | *-*-mingw*)
+            if test "$GCC" = yes; then
+                TRYLINKINGWITHCXX="CXXSHARED= $CXX -shared "
+            else
+                if test "cl" = $CXX ;  then
+                    # Microsoft Visual C++ (MSVC)
+                    TRYLINKINGWITHCXX="CXXSHARED= $CXX -nologo -LD"
+                else
+                    TRYLINKINGWITHCXX="#unknown Windows compiler"
+                fi
+            fi ;;
+        *)       TRYLINKINGWITHCXX="CXXSHARED= $CXX -shared ";;
+        esac
+fi
+AC_MSG_RESULT($TRYLINKINGWITHCXX)
+# CCSHARED are the C *flags* used to create objects to go into a shared
+# library (module) -- this is only needed for a few systems
+AC_MSG_CHECKING(CCSHARED)
+if test -z "$CCSHARED"
+then
+	case $host in
+	*-*-hp*) if test "$GCC" = yes;
+		 then CCSHARED="-fpic";
+		 else CCSHARED="+z";
+		 fi;;
+	*-*-linux*) CCSHARED="-fpic";;
+	*-*-freebsd* | *-*-openbsd*) CCSHARED="-fpic";;
+	*-*-netbsd*) CCSHARED="-fPIC";;
+	*-sco-sysv*) CCSHARED="-KPIC -dy -Bdynamic";;
+	*-*-irix6*)  case $CC in
+		   *gcc*) CCSHARED="-shared";;
+		   *) CCSHARED="";;
+		   esac;;
+	esac
+fi
+AC_MSG_RESULT($CCSHARED)
+
+# RPATH is the path used to look for shared library files.
+AC_MSG_CHECKING(RPATH)
+if test -z "$RPATH"
+then
+	case $host in
+	*-*-solaris*) RPATH='-R. -R$(exec_prefix)/lib';;
+        *-*-irix*) RPATH='-rpath .:$(exec_prefix)/lib';;
+	*-*-linux*) RPATH='-Xlinker -rpath $(exec_prefix)/lib -Xlinker -rpath .';;
+	*)	RPATH='';;
+	esac
+fi
+AC_MSG_RESULT($RPATH)
+AC_SUBST(RPATH)
+
+# LINKFORSHARED are the flags passed to the $(CC) command that links
+# the a few executables -- this is only needed for a few systems
+
+AC_MSG_CHECKING(LINKFORSHARED)
+if test -z "$LINKFORSHARED"
+then
+	case $host in
+	*-*-aix*)	LINKFORSHARED='-Wl,-bE:$(srcdir)/python.exp -lld';;
+	*-*-hp*)
+	    LINKFORSHARED="-Wl,-E -Wl,+s -Wl,+b\$(BINLIBDEST)/lib-dynload";;
+	*-*-linux*) LINKFORSHARED="-Xlinker -export-dynamic";;
+	*-*-next*) LINKFORSHARED="-u libsys_s";;
+	*-sco-sysv*) LINKFORSHARED="-Bdynamic -dy -Wl,-Bexport";;
+	*-*-irix6*) LINKFORSHARED="-all";;
+	esac
+fi
+AC_MSG_RESULT($LINKFORSHARED)
+
+# This variation is needed on OS-X because there is no (apparent) consistency in shared library naming.
+# Sometimes .bundle works, but sometimes .so is needed.  It depends on the target language
+
+AC_SUBST(PYTHON_SO)
+case $host in
+   *-*-mingw*) PYTHON_SO=.pyd;;
+   *-*-darwin*) PYTHON_SO=.so;;
+   *) PYTHON_SO=$SO;;
+esac
+
+AC_SUBST(TCL_SO)
+case $host in
+   *-*-darwin*) TCL_SO=.dylib;;
+   *) TCL_SO=$SO;;
+esac
+
+AC_SUBST(GUILE_SO)
+case $host in
+   *-*-darwin*) GUILE_SO=.so;;
+   *) GUILE_SO=$SO;;
+esac
+
+AC_SUBST(PHP4_SO)
+case $host in
+   *-*-darwin*) PHP4_SO=.so;;
+   *) PHP4_SO=$SO;;
+esac
+
+AC_SUBST(MZSCHEME_SO)
+case $host in
+   *) MZSCHEME_SO=.so;;
+esac
+
+AC_SUBST(LUA_SO)
+case $host in
+   *-*-darwin*) LUA_SO=.so;;
+   *) LUA_SO=$SO;;
+esac
+
+# Optional CFLAGS used to silence compiler warnings on some platforms.
+
+AC_SUBST(PLATFLAGS)
+case $host in
+   *-*-darwin*) PLATFLAGS="-Wno-long-double";;
+   *) PLATFLAGS="";;
+esac
+
+
+
+echo ""
+echo "Checking for installed packages."
+echo "Note : None of the following packages are required to compile SWIG"
+echo ""
+
+#----------------------------------------------------------------
+# Look for popen
+#----------------------------------------------------------------
+
+AC_ARG_WITH(popen, AS_HELP_STRING([--without-popen], [Disable popen]), with_popen="$withval")
+if test x"${with_popen}" = xno ; then 
+AC_MSG_NOTICE([Disabling popen])
+else
+AC_CHECK_FUNC(popen, AC_DEFINE(HAVE_POPEN, 1, [Define if popen is available]), AC_MSG_NOTICE([Disabling popen]))
+fi
+
+#----------------------------------------------------------------
+# Look for RxSpencer 
+#----------------------------------------------------------------
+
+AC_ARG_WITH(rxspencer, AS_HELP_STRING([--with-rxspencer], [Enable RxSpencer]), with_rxspencer="yes")
+if test x"${with_rxspencer}" = xyes ; then 
+#check first for the header
+ AC_CHECK_HEADER(rxspencer/regex.h,with_rxspencer="yes",with_rxspencer="no")
+ if test x"${with_rxspencer}" = xyes ; then 
+# now check for the library
+  AC_CHECK_LIB(rxspencer, regcomp,with_rxspencer="yes",with_rxspencer="no")
+ fi
+ if test x"${with_rxspencer}" = xyes ; then 
+# library and header are available
+  AC_DEFINE(HAVE_RXSPENCER, 1,[Define if rxspencer is available])
+  LIBS="$LIBS -lrxspencer"
+ else
+  AC_MSG_NOTICE([RxSpencer not found. Obtain it at http://arglist.com/regex or http://gnuwin32.sourceforge.net/packages.html])
+ fi
+fi
+
+#----------------------------------------------------------------
+
+# Check for specific libraries.   Used for SWIG examples
+AC_CHECK_LIB(dl, dlopen)	# Dynamic linking for SunOS/Solaris and SYSV
+AC_CHECK_LIB(dld, shl_load)	# Dynamic linking for HP-UX
+
+dnl The following three libraries (nsl,inet,socket) are needed on Sequent,
+dnl and must be checked for in this order since each library depends on the
+dnl preceding one.
+dnl
+dnl Most SVR4 platforms will need -lsocket and -lnsl.  However on SGI IRIX 5,
+dnl these exist but are broken, so we use AC_SEARCH_LIBS which will only try
+dnl the library if the function isn't already available without it.
+AC_SEARCH_LIBS(t_open, nsl) # SVR4
+AC_SEARCH_LIBS(gethostbyname, inet) # Sequent
+AC_SEARCH_LIBS(socket, socket) # SVR4 sockets
+
+AC_CHECK_LIB(swill, swill_init, [SWIGLIBS="-lswill $LIBS" SWILL="-DSWIG_SWILL"])
+AC_SUBST(SWIGLIBS)
+AC_SUBST(SWILL)
+
+# check for --with-libm=...
+AC_SUBST(LIBM)
+LIBM=-lm
+AC_ARG_WITH(libm, [  --with-libm=STRING      math library], [
+if test "$withval" != yes
+then LIBM=$withval
+else AC_MSG_ERROR([proper usage is --with-libm=STRING])
+fi])
+AC_CHECK_LIB(ieee, main, [LIBM="-lieee $LIBM"])
+AC_CHECK_LIB(crypt,crypt, [LIBCRYPT="-lcrypt"])
+AC_SUBST(LIBCRYPT)
+
+# check for --with-libc=...
+AC_SUBST(LIBC)
+AC_ARG_WITH(libc, [  --with-libc=STRING      C library], [
+if test "$withval" != yes
+then LIBC=$withval
+else AC_MSG_ERROR([proper usage is --with-libc=STRING])
+fi])
+
+#--------------------------------------------------------------------
+#	Locate the X11 header files and the X11 library archive.  Try
+#	the ac_path_x macro first, but if it doesn't find the X stuff
+#	(e.g. because there's no xmkmf program) then check through
+#	a list of possible directories.  Under some conditions the
+#	autoconf macro will return an include directory that contains
+#	no include files, so double-check its result just to be safe.
+#--------------------------------------------------------------------
+
+AC_PATH_X
+not_really_there=""
+if test "$no_x" = ""; then
+    if test "$x_includes" = ""; then
+	AC_TRY_CPP([#include <X11/XIntrinsic.h>], , not_really_there="yes")
+    else
+	if test ! -r $x_includes/X11/Intrinsic.h; then
+	    not_really_there="yes"
+	fi
+    fi
+fi
+if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
+    AC_MSG_CHECKING(for X11 header files)
+    XINCLUDES="# no special path needed"
+    AC_TRY_CPP([#include <X11/Intrinsic.h>], , XINCLUDES="")
+    if test -z "$XINCLUDES"; then
+        dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/include/X11R4 /usr/X11R5/include /usr/include/X11R5 /usr/openwin/include /usr/X11/include /usr/sww/include /usr/X11R6/include /usr/include/X11R6"
+        for i in $dirs ; do
+	    if test -r $i/X11/Intrinsic.h; then
+		AC_MSG_RESULT($i)
+	        XINCLUDES=" -I$i"
+		break
+	    fi
+        done
+    fi
+else
+    if test "$x_includes" != ""; then
+	XINCLUDES=-I$x_includes
+    else
+	XINCLUDES="# no special path needed"
+    fi
+fi
+if test -z "$XINCLUDES"; then
+    AC_MSG_RESULT(couldn't find any!)
+    XINCLUDES="# no include files found"
+fi
+
+if test "$no_x" = yes; then
+    AC_MSG_CHECKING(for X11 libraries)
+    XLIBSW=
+    dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/lib/X11R4 /usr/X11R5/lib /usr/lib/X11R5 /usr/X11R6/lib /usr/lib/X11R6 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
+    for i in $dirs ; do
+	if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl; then
+	    AC_MSG_RESULT($i)
+	    XLIBSW="-L$i -lX11"
+	    break
+	fi
+    done
+else
+    if test "$x_libraries" = ""; then
+	XLIBSW=-lX11
+    else
+	XLIBSW="-L$x_libraries -lX11"
+    fi
+fi
+if test -z "$XLIBSW" ; then
+    AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
+fi
+if test -z "$XLIBSW" ; then
+    AC_MSG_RESULT(couldn't find any!  Using -lX11.)
+    XLIBSW=-lX11
+fi
+
+AC_SUBST(XINCLUDES)
+AC_SUBST(XLIBSW)
+
+AC_ARG_WITH(alllang, AS_HELP_STRING([--without-alllang], [Disable all languages]), with_alllang="$withval")
+
+#--------------------------------------------------------------------
+# Look for Tcl
+#--------------------------------------------------------------------
+
+TCLINCLUDE=
+TCLLIB=
+TCLPACKAGE=
+
+AC_ARG_WITH(tclconfig, AS_HELP_STRING([--without-tcl], [Disable Tcl])
+AS_HELP_STRING([--with-tclconfig=path], [Set location of tclConfig.sh]), [with_tclconfig="$withval"], [with_tclconfig=])
+AC_ARG_WITH(tcl,
+ [  --with-tcl=path         Set location of Tcl package],[
+	TCLPACKAGE="$withval"], [TCLPACKAGE=yes])
+AC_ARG_WITH(tclincl,[  --with-tclincl=path     Set location of Tcl include directory],[
+	TCLINCLUDE="$ISYSTEM$withval"], [TCLINCLUDE=])
+AC_ARG_WITH(tcllib,[  --with-tcllib=path      Set location of Tcl library directory],[
+	TCLLIB="-L$withval"], [TCLLIB=])
+
+# First, check for "--without-tcl" or "--with-tcl=no".
+if test x"${TCLPACKAGE}" = xno -o x"${with_alllang}" = xno; then 
+AC_MSG_NOTICE([Disabling Tcl])
+else
+AC_MSG_CHECKING([for Tcl configuration])
+# First check to see if --with-tclconfig was specified.
+if test x"${with_tclconfig}" != x ; then
+   if test -f "${with_tclconfig}/tclConfig.sh" ; then
+      TCLCONFIG=`(cd ${with_tclconfig}; pwd)`
+   else
+      AC_MSG_ERROR([${with_tcl} directory doesn't contain tclConfig.sh])
+   fi
+fi
+# check in a few common install locations
+if test x"${TCLCONFIG}" = x ; then
+    for i in `ls -d /usr/lib/ 2>/dev/null` \
+	     `ls -d -r /usr/lib/tcl*/ 2>/dev/null` \
+	     `ls -d /usr/local/lib/ 2>/dev/null` \
+	     `ls -d -r /usr/local/lib/tcl*/ 2>/dev/null` ; do
+	if test -f $i"tclConfig.sh" ; then
+	    TCLCONFIG=`(cd $i; pwd)`
+	    break
+	fi
+    done
+fi
+if test x"${TCLCONFIG}" = x ; then
+    AC_MSG_RESULT(no)
+else
+    AC_MSG_RESULT(found $TCLCONFIG/tclConfig.sh)
+    . $TCLCONFIG/tclConfig.sh
+    if test -z "$TCLINCLUDE"; then
+        TCLINCLUDE=`echo $TCL_INCLUDE_SPEC | sed "s/-I/$ISYSTEM/"`
+    fi
+    if test -z "$TCLLIB"; then
+        TCLLIB=$TCL_LIB_SPEC
+    fi
+fi
+
+if test -z "$TCLINCLUDE"; then
+   if test "x$TCLPACKAGE" != xyes; then
+	TCLINCLUDE="$ISYSTEM$TCLPACKAGE/include"
+   fi
+fi
+
+if test -z "$TCLLIB"; then
+   if test "x$TCLPACKAGE" != xyes; then
+	TCLLIB="-L$TCLPACKAGE/lib -ltcl"
+   fi
+fi
+
+AC_MSG_CHECKING(for Tcl header files)
+if test -z "$TCLINCLUDE"; then
+AC_TRY_CPP([#include <tcl.h>], , TCLINCLUDE="")
+if test -z "$TCLINCLUDE"; then
+	dirs="/usr/local/include /usr/include /opt/local/include"
+	for i in $dirs ; do
+		if test -r $i/tcl.h; then
+			AC_MSG_RESULT($i)
+			TCLINCLUDE="$ISYSTEM$i"
+			break
+		fi
+	done
+fi
+if test -z "$TCLINCLUDE"; then
+    	AC_MSG_RESULT(not found)
+fi
+else
+        AC_MSG_RESULT($TCLINCLUDE)
+fi
+
+AC_MSG_CHECKING(for Tcl library)
+if test -z "$TCLLIB"; then
+dirs="/usr/local/lib /usr/lib /opt/local/lib"
+for i in $dirs ; do
+	if test -r $i/libtcl.a; then
+	    AC_MSG_RESULT($i)
+	    TCLLIB="-L$i -ltcl"
+	    break
+	fi
+done
+if test -z "$TCLLIB"; then
+	AC_MSG_RESULT(not found)
+fi
+else
+AC_MSG_RESULT($TCLLIB)
+fi
+
+# Cygwin (Windows) needs the library for dynamic linking
+case $host in
+*-*-cygwin* | *-*-mingw*) TCLDYNAMICLINKING="$TCLLIB";;
+*-*-darwin*) TCLDYNAMICLINKING="-dynamiclib -flat_namespace -undefined suppress";;
+*)TCLDYNAMICLINKING="";;
+esac
+fi
+
+AC_SUBST(TCLINCLUDE)
+AC_SUBST(TCLLIB)
+AC_SUBST(TCLDYNAMICLINKING)
+
+#----------------------------------------------------------------
+# Look for Python
+#----------------------------------------------------------------
+
+PYINCLUDE=
+PYLIB=
+PYPACKAGE=
+
+AC_ARG_WITH(python, AS_HELP_STRING([--without-python], [Disable Python])
+AS_HELP_STRING([--with-python=path], [Set location of Python executable]),[ PYBIN="$withval"], [PYBIN=yes])
+
+# First, check for "--without-python" or "--with-python=no".
+if test x"${PYBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Python])
+else
+# First figure out the name of the Python executable
+
+if test "x$PYBIN" = xyes; then
+AC_CHECK_PROGS(PYTHON, python python2.8 python2.7 python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0 python1.6 python1.5 python1.4 python)
+else
+PYTHON="$PYBIN"
+fi
+
+if test -n "$PYTHON"; then
+    AC_MSG_CHECKING(for Python prefix)
+    PYPREFIX=`($PYTHON -c "import sys; print sys.prefix") 2>/dev/null`
+    AC_MSG_RESULT($PYPREFIX)
+    AC_MSG_CHECKING(for Python exec-prefix)
+    PYEPREFIX=`($PYTHON -c "import sys; print sys.exec_prefix") 2>/dev/null`
+    AC_MSG_RESULT($PYEPREFIX)
+
+
+    # Note: I could not think of a standard way to get the version string from different versions.
+    # This trick pulls it out of the file location for a standard library file.
+
+    AC_MSG_CHECKING(for Python version)
+
+    # Need to do this hack since autoconf replaces __file__ with the name of the configure file
+    filehack="file__"
+    PYVERSION=`($PYTHON -c "import string,operator,os.path; print operator.getitem(os.path.split(operator.getitem(os.path.split(string.__$filehack),0)),1)")`
+    AC_MSG_RESULT($PYVERSION)
+
+    # Find the directory for libraries this is necessary to deal with
+    # platforms that can have apps built for multiple archs: e.g. x86_64
+    AC_MSG_CHECKING(for Python lib dir)
+    PYLIBDIR=`($PYTHON -c "import sys; print sys.lib") 2>/dev/null`
+    if test -z "$PYLIBDIR"; then
+      # older versions don't have sys.lib  so the best we can do is assume lib
+      PYLIBDIR="lib" 
+    fi
+    AC_MSG_RESULT($PYLIBDIR)
+    
+    # Set the include directory
+
+    AC_MSG_CHECKING(for Python header files)
+    if test -r $PYPREFIX/include/$PYVERSION/Python.h; then
+        PYINCLUDE="-I$PYPREFIX/include/$PYVERSION -I$PYEPREFIX/$PYLIBDIR/$PYVERSION/config"
+    fi
+    if test -z "$PYINCLUDE"; then
+        if test -r $PYPREFIX/include/Py/Python.h; then
+            PYINCLUDE="-I$PYPREFIX/include/Py -I$PYEPREFIX/$PYLIBDIR/python/lib"
+        fi
+    fi
+    AC_MSG_RESULT($PYINCLUDE)
+
+    # Set the library directory blindly.   This probably won't work with older versions
+    AC_MSG_CHECKING(for Python library)
+    dirs="$PYVERSION/config $PYVERSION/$PYLIBDIR python/$PYLIBDIR"
+    for i in $dirs; do
+        if test -d $PYEPREFIX/$PYLIBDIR/$i; then
+           PYLIB="$PYEPREFIX/$PYLIBDIR/$i"
+           break
+        fi
+    done
+    if test -z "$PYLIB"; then
+        AC_MSG_RESULT(Not found)
+    else
+        AC_MSG_RESULT($PYLIB)
+    fi
+
+    # Check for really old versions
+    if test -r $PYLIB/libPython.a; then
+         PYLINK="-lModules -lPython -lObjects -lParser"
+    else
+         PYLINK="-l$PYVERSION"
+    fi
+fi
+
+# Cygwin (Windows) needs the library for dynamic linking
+case $host in
+*-*-cygwin* | *-*-mingw*) PYTHONDYNAMICLINKING="-L$PYLIB $PYLINK"
+         DEFS="-DUSE_DL_IMPORT $DEFS" PYINCLUDE="$PYINCLUDE"
+         ;;
+*)PYTHONDYNAMICLINKING="";;
+esac
+fi
+
+AC_SUBST(PYINCLUDE)
+AC_SUBST(PYLIB)
+AC_SUBST(PYLINK)
+AC_SUBST(PYTHONDYNAMICLINKING)
+
+#----------------------------------------------------------------
+# Look for Perl5
+#----------------------------------------------------------------
+
+PERLBIN=
+
+AC_ARG_WITH(perl5, AS_HELP_STRING([--without-perl5], [Disable Perl5])
+AS_HELP_STRING([--with-perl5=path], [Set location of Perl5 executable]),[ PERLBIN="$withval"], [PERLBIN=yes])
+
+# First, check for "--without-perl5" or "--with-perl5=no".
+if test x"${PERLBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Perl5])
+PERL=
+else
+
+# First figure out what the name of Perl5 is
+
+if test "x$PERLBIN" = xyes; then
+AC_CHECK_PROGS(PERL, perl perl5.6.1 perl5.6.0 perl5.004 perl5.003 perl5.002 perl5.001 perl5 perl)
+else
+PERL="$PERLBIN"
+fi
+
+
+# This could probably be simplified as for all platforms and all versions of Perl the following apparently should be run to get the compilation options:
+# perl -MExtUtils::Embed -e ccopts
+AC_MSG_CHECKING(for Perl5 header files)
+if test -n "$PERL"; then
+	PERL5DIR=`($PERL -e 'use Config; print $Config{archlib}, "\n";') 2>/dev/null`
+	if test "$PERL5DIR" != ""; then
+		dirs="$PERL5DIR $PERL5DIR/CORE"
+		PERL5EXT=none
+		for i in $dirs; do
+			if test -r $i/perl.h; then
+				AC_MSG_RESULT($i)
+				PERL5EXT="$i"
+				break;
+			fi
+		done
+		if test "$PERL5EXT" = none; then
+			PERL5EXT="$PERL5DIR/CORE"
+			AC_MSG_RESULT(could not locate perl.h...using $PERL5EXT)
+		fi
+
+		AC_MSG_CHECKING(for Perl5 library)
+		PERL5LIB=`($PERL -e 'use Config; $_=$Config{libperl}; s/^lib//; s/$Config{_a}$//; print $_, "\n"') 2>/dev/null`
+		if test "$PERL5LIB" = "" ; then
+			AC_MSG_RESULT(not found)
+		else
+			AC_MSG_RESULT($PERL5LIB)
+		fi
+    AC_MSG_CHECKING(for Perl5 compiler options)
+ 		PERL5CCFLAGS=`($PERL -e 'use Config; print $Config{ccflags}, "\n"' | sed "s/-Wdeclaration-after-statement//" | sed "s/-I/$ISYSTEM/") 2>/dev/null`
+ 		if test "$PERL5CCFLAGS" = "" ; then
+ 			AC_MSG_RESULT(not found)
+ 		else
+ 			AC_MSG_RESULT($PERL5CCFLAGS)
+ 		fi
+	else
+		AC_MSG_RESULT(unable to determine perl5 configuration)
+		PERL5EXT=$PERL5DIR
+	fi
+else
+       	AC_MSG_RESULT(could not figure out how to run perl5)
+fi
+
+# Cygwin (Windows) needs the library for dynamic linking
+case $host in
+*-*-cygwin* | *-*-mingw*) PERL5DYNAMICLINKING="-L$PERL5EXT -l$PERL5LIB";;
+*)PERL5DYNAMICLINKING="";;
+esac
+fi
+
+AC_SUBST(PERL)
+AC_SUBST(PERL5EXT)
+AC_SUBST(PERL5DYNAMICLINKING)
+AC_SUBST(PERL5LIB)
+AC_SUBST(PERL5CCFLAGS)
+
+#----------------------------------------------------------------
+# Look for Octave
+#----------------------------------------------------------------
+
+OCTAVEBIN=
+OCTAVEDYNAMICLINKING=
+OCTAVE_SO=.oct
+
+AC_ARG_WITH(octave, AS_HELP_STRING([--without-octave], [Disable Octave])
+AS_HELP_STRING([--with-octave=path], [Set location of Octave executable]),[ OCTAVEBIN="$withval"], [OCTAVEBIN=yes])
+
+# First, check for "--without-octave" or "--with-octave=no".
+if test x"${OCTAVEBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Octave])
+OCTAVE=
+fi
+
+# First figure out what the name of Octave is
+
+if test "x$OCTAVEBIN" = xyes; then
+AC_CHECK_PROGS(OCTAVE, octave)
+else
+OCTAVE="$OCTAVEBIN"
+fi
+
+
+AC_MSG_CHECKING(for Octave header files)
+if test -n "$OCTAVE"; then
+	OCTAVEDIR="/usr/include"
+	if test "$OCTAVEDIR" != ""; then
+		dirs="$OCTAVEDIR"
+		OCTAVEEXT=""
+		for i in $dirs; do
+			if test -r $i/octave/oct.h; then
+				OCTAVEEXT="$i"
+				break;
+			fi
+			if test -r $i/octave/octave/oct.h; then
+				OCTAVEEXT="$i/octave"
+				break;
+			fi
+		done
+		if test "$OCTAVEEXT" = "" ; then
+			AC_MSG_RESULT(not found)
+		else
+			AC_MSG_RESULT($OCTAVEEXT)
+		fi
+
+		AC_MSG_CHECKING(for Octave compiler options)
+ 		OCTAVECCFLAGS=""
+		AC_MSG_RESULT($OCTAVECCFLAGS)
+	fi
+else
+       	AC_MSG_RESULT(could not figure out how to run octave)
+fi
+
+AC_SUBST(OCTAVE)
+AC_SUBST(OCTAVEEXT)
+AC_SUBST(OCTAVE_SO)
+AC_SUBST(OCTAVEDYNAMICLINKING)
+AC_SUBST(OCTAVELIB)
+AC_SUBST(OCTAVECCFLAGS)
+
+#----------------------------------------------------------------
+# Look for java
+#----------------------------------------------------------------
+
+AC_ARG_WITH(java, AS_HELP_STRING([--without-java], [Disable Java])
+AS_HELP_STRING([--with-java=path], [Set location of java executable]),[JAVABIN="$withval"], [JAVABIN=yes])
+AC_ARG_WITH(javac, [  --with-javac=path       Set location of javac executable],[JAVACBIN="$withval"], [JAVACBIN=])
+
+# First, check for "--without-java" or "--with-java=no".
+if test x"${JAVABIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Java])
+JAVA=
+else
+
+if test "x$JAVABIN" = xyes; then
+  AC_CHECK_PROGS(JAVA, java kaffe guavac)
+else
+  JAVA="$JAVABIN"
+fi
+
+if test -z "$JAVACBIN"; then
+  AC_CHECK_PROGS(JAVAC, javac)
+else
+  JAVAC="$JAVACBIN"
+fi
+
+AC_MSG_CHECKING(for java include file jni.h)
+AC_ARG_WITH(javaincl, [  --with-javaincl=path    Set location of Java include directory], [JAVAINCDIR="$withval"], [JAVAINCDIR=])
+
+if test -z "$JAVAINCDIR" ; then
+  JAVAINCDIR="/usr/j2sdk*/include /usr/local/j2sdk*/include /usr/jdk*/include /usr/local/jdk*/include /opt/j2sdk*/include /opt/jdk*/include /usr/java/include /usr/java/j2sdk*/include /usr/java/jdk*/include /usr/local/java/include /opt/java/include /usr/include/java /usr/local/include/java /usr/lib/java/include /usr/lib/jvm/java*/include /usr/include/kaffe /usr/local/include/kaffe /usr/include"
+
+  # Add in default installation directory on Windows for Cygwin
+  case $host in
+  *-*-cygwin* | *-*-mingw*) JAVAINCDIR="c:/Program*Files/Java/jdk*/include d:/Program*Files/Java/jdk*/include c:/j2sdk*/include d:/j2sdk*/include c:/jdk*/include d:/jdk*/include $JAVAINCDIR";;
+  *-*-darwin*) JAVAINCDIR="/System/Library/Frameworks/JavaVM.framework/Headers $JAVAINCDIR";;
+  *);;
+  esac
+fi
+
+JAVAINC=""
+for d in $JAVAINCDIR ; do
+  if test -r "$d/jni.h" ; then
+    AC_MSG_RESULT($d)
+    JAVAINCDIR=$d
+    JAVAINC=-I\"$d\"
+    break
+  fi
+done
+
+if test "$JAVAINC" = "" ; then
+  AC_MSG_RESULT(not found)
+else
+  # now look for <arch>/jni_md.h
+  AC_MSG_CHECKING(for java include file jni_md.h)
+  JAVAMDDIR=`find "$JAVAINCDIR" -follow -name jni_md.h -print`
+  if test "$JAVAMDDIR" = "" ; then
+    AC_MSG_RESULT(not found)
+  else
+    JAVAMDDIR=`dirname "$JAVAMDDIR" | tail -1`
+    JAVAINC="${JAVAINC} -I\"$JAVAMDDIR\""
+    AC_MSG_RESULT($JAVAMDDIR)
+  fi
+fi
+
+# java.exe on Cygwin requires the Windows standard (Pascal) calling convention as it is a normal Windows executable and not a Cygwin built executable
+case $host in
+*-*-cygwin* | *-*-mingw*)
+    if test "$GCC" = yes; then
+        JAVADYNAMICLINKING=" -mno-cygwin -mthreads -Wl,--add-stdcall-alias"
+        JAVACFLAGS="-mno-cygwin -mthreads"
+    else
+        JAVADYNAMICLINKING=""
+        JAVACFLAGS=""
+    fi ;;
+*-*-darwin*) 
+        JAVADYNAMICLINKING="-dynamiclib -framework JavaVM"
+        JAVACFLAGS=""
+        ;;
+*)
+        JAVADYNAMICLINKING=""
+        JAVACFLAGS=""
+        ;;
+esac
+
+# Java on Windows platforms including Cygwin doesn't use libname.dll, rather name.dll when loading dlls
+case $host in
+*-*-cygwin* | *-*-mingw*) JAVALIBRARYPREFIX="";;
+*)JAVALIBRARYPREFIX="lib";;
+esac
+
+# Java on Mac OS X tweaks
+case $host in
+*-*-darwin*) 
+    JAVASO=".jnilib"
+    JAVALDSHARED='$(CC)'
+    JAVACXXSHARED='$(CXX)'
+    ;;
+*)
+    JAVASO=$SO
+    JAVALDSHARED='$(LDSHARED)'
+    JAVACXXSHARED='$(CXXSHARED)'
+    ;;
+esac
+fi
+
+AC_SUBST(JAVA)
+AC_SUBST(JAVAC)
+AC_SUBST(JAVAINC)
+AC_SUBST(JAVADYNAMICLINKING)
+AC_SUBST(JAVALIBRARYPREFIX)
+AC_SUBST(JAVASO)
+AC_SUBST(JAVALDSHARED)
+AC_SUBST(JAVACXXSHARED)
+AC_SUBST(JAVACFLAGS)
+
+#----------------------------------------------------------------
+# Look for gcj
+#----------------------------------------------------------------
+
+AC_ARG_WITH(gcj, AS_HELP_STRING([--without-gcj], [Disable GCJ])
+AS_HELP_STRING([--with-gcj=path], [Set location of gcj executable]),[GCJBIN="$withval"], [GCJBIN=yes])
+AC_ARG_WITH(gcjh, [  --with-gcjh=path        Set location of gcjh executable],[GCJHBIN="$withval"], [GCJHBIN=])
+
+# First, check for "--without-gcj" or "--with-gcj=no".
+if test x"${GCJBIN}" = xno -o x"${with_alllang}" = xno ; then 
+  AC_MSG_NOTICE([Disabling GCJ])
+else
+  if test "x$GCJBIN" = xyes; then
+    AC_CHECK_PROGS(GCJ, gcj)
+  else
+    GCJ="$GCJBIN"
+  fi
+
+  if test -z "$GCJCBIN"; then
+    AC_CHECK_PROGS(GCJH, gcjh)
+  else
+    GCJH="$GCJHBIN"
+  fi
+fi
+
+AC_SUBST(GCJ)
+AC_SUBST(GCJH)
+
+#----------------------------------------------------------------
+# Look for Guile
+#----------------------------------------------------------------
+
+GUILEPACKAGE=
+GUILEINCLUDE=
+GUILE=
+GUILELIB=
+GUILELINK=
+GUILEPKGDATADIR=
+
+AC_ARG_WITH(guile-config,AS_HELP_STRING([--without-guile], [Disable Guile])
+AS_HELP_STRING([--with-guile-config=path], [Set location of guile-config]),[ GUILE_CONFIG="$withval"], [GUILE_CONFIG=])
+AC_ARG_WITH(guilepackage, AS_HELP_STRING([--with-guile-prefix=path], [Set location of Guile tree]),[
+	GUILEPACKAGE="$withval"])
+AC_ARG_WITH(guile,[  --with-guile=path       Set location of Guile executable],[
+	GUILE="$withval"], [GUILE=yes])
+AC_ARG_WITH(guileincl,[  --with-guileincl=path   Set location of Guile include directory],[
+	GUILEINCLUDE="$withval"])
+AC_ARG_WITH(guilelib,[  --with-guilelib=path    Set location of Guile library directory],[
+	GUILELIB="$withval"])
+
+# First, check for "--without-guile" or "--with-guile=no".
+if test x"${GUILE}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Guile])
+else
+
+if test -z "$GUILE_CONFIG" ; then
+  AC_PATH_PROG(GUILE_CONFIG, guile-config)
+fi
+
+if test -n "$GUILE_CONFIG" ; then
+  GUILEPACKAGE="`$GUILE_CONFIG info prefix`"
+  GUILEINCLUDE="`$GUILE_CONFIG info includedir`"
+  GUILELIB="`$GUILE_CONFIG info libdir`"
+  GUILE="`$GUILE_CONFIG info bindir`/guile"
+  GUILELINK="`$GUILE_CONFIG link`"
+  GUILEPKGDATADIR="`$GUILE_CONFIG info pkgdatadir`"
+fi
+
+  if test -z "$GUILE" -o "x$GUILE" = xyes; then
+     if test -n "$GUILEPACKAGE"; then
+  	GUILE="$GUILEPACKAGE/bin/guile"
+     else
+  	GUILE=
+     fi
+  fi
+
+  if test -z "$GUILEINCLUDE"; then
+     if test -n "$GUILEPACKAGE"; then
+  	GUILEINCLUDE="$GUILEPACKAGE/include"
+     fi
+  fi
+
+  if test -z "$GUILELIB"; then
+     if test -n "$GUILEPACKAGE"; then
+  	GUILELIB="$GUILEPACKAGE/lib"
+     fi
+  fi
+
+
+AC_MSG_CHECKING(for Guile header files)
+
+  dirs="$GUILEINCLUDE"
+  for i in $dirs ; do
+  	if test -r $i/guile/gh.h; then
+  		AC_MSG_RESULT($i)
+  		GUILEINCLUDE="$ISYSTEM$i"
+  		break
+  	fi
+  done
+  if test -z "$GUILEINCLUDE"; then
+      	AC_MSG_RESULT(not found)
+  fi
+
+  AC_MSG_CHECKING(for Guile library)
+  dirs="$GUILELIB"
+  for i in $dirs ; do
+  	if test -r $i/libguile.so; then
+  	    AC_MSG_RESULT($i)
+  	    GUILELIB="$i"
+  	    break
+  	fi
+  done
+  if test -z "$GUILELIB"; then
+  	AC_MSG_RESULT(not found)
+  fi
+
+if test -z "$GUILELINK"; then
+  GUILELINK="-L$GUILELIB -lguile"
+fi
+
+guilesafe_CFLAGS=$CFLAGS
+guilesafe_LIBS=$LIBS
+# Filter out "-ansi -pedantic" because Guile header files will not compile with these flags.
+# (The flags -ansi -pedantic are automatically added by ac_compile_warnings.m4)
+CFLAGS="`echo $CFLAGS | sed 's/-ansi//g;s/-pedantic//g;'` $GUILEINCLUDE"
+LIBS="$LIBS $GUILELINK"
+
+AC_MSG_CHECKING(whether Guile's gh_ API works)
+AC_LINK_IFELSE([#include <guile/gh.h>
+  int main() { SCM s; return gh_scm2int(s); }], GUILE_GH_INTERFACE=1, )
+if test -n "$GUILE_GH_INTERFACE" ; then
+        AC_MSG_RESULT(yes)
+else
+	AC_MSG_RESULT(no)
+fi
+AC_MSG_CHECKING(whether Guile's SCM_ API works)
+AC_LINK_IFELSE([#include <libguile.h>
+  int main() { SCM s; scm_slot_exists_p(SCM_BOOL_F, SCM_BOOL_F); return SCM_STRING_LENGTH(s); }], GUILE_SCM_INTERFACE=1, )
+if test -n "$GUILE_SCM_INTERFACE" ; then
+        AC_MSG_RESULT(yes)
+else
+	AC_MSG_RESULT(no)
+fi
+CFLAGS=$guilesafe_CFLAGS
+LIBS=$guilesafe_LIBS
+fi
+
+AC_SUBST(GUILE)
+AC_SUBST(GUILEINCLUDE)
+AC_SUBST(GUILELIB)
+AC_SUBST(GUILELINK)
+AC_SUBST(GUILE_GH_INTERFACE)
+AC_SUBST(GUILE_SCM_INTERFACE)
+
+#----------------------------------------------------------------
+# Look for MzScheme
+#----------------------------------------------------------------
+
+AC_ARG_WITH(mzscheme, AS_HELP_STRING([--without-mzscheme], [Disable MzScheme])
+AS_HELP_STRING([--with-mzscheme=path], [Set location of MzScheme executable]),[ MZSCHEMEBIN="$withval"], [MZSCHEMEBIN=yes])
+AC_ARG_WITH(mzc, AS_HELP_STRING([--with-mzc=path], [Set location of MzScheme's mzc]), [ MZCBIN="$withval"], [MZCBIN=])
+
+# First, check for "--without-mzscheme" or "--with-mzscheme=no".
+if test x"${MZSCHEMEBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling MzScheme])
+MZC=
+else
+
+if test "x$MZSCHEMEBIN" = xyes; then
+   AC_PATH_PROG(MZSCHEME, mzscheme)
+else
+   MZSCHEME="$MZSCHEMEBIN"
+fi
+
+if test -z "$MZCBIN"; then
+   AC_PATH_PROG(MZC, mzc)
+fi
+
+if test -n "$MZSCHEME"; then
+AC_MSG_CHECKING(for MzScheme dynext object) 
+MZDYNOBJ=`$MZSCHEME --mute-banner --version --eval '(begin (require (lib "link.ss" "dynext")) (with-handlers (((lambda args #t) (lambda args #f))) (for-each (lambda (x) (display x) (display " ")) ((current-make-standard-link-libraries)))) (with-handlers (((lambda args #t) (lambda args #f))) (for-each (lambda (x) (display x) (display " ")) (expand-for-link-variant (current-standard-link-libraries)))))'`
+AC_MSG_RESULT($MZDYNOBJ)
+fi
+fi
+AC_SUBST(MZDYNOBJ)
+
+#----------------------------------------------------------------
+# Look for Ruby
+#----------------------------------------------------------------
+
+RUBYBIN=
+
+AC_ARG_WITH(ruby, AS_HELP_STRING([--without-ruby], [Disable Ruby])
+AS_HELP_STRING([--with-ruby=path], [Set location of Ruby executable]),[ RUBYBIN="$withval"], [RUBYBIN=yes])
+
+# First, check for "--without-ruby" or "--with-ruby=no".
+if test x"${RUBYBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Ruby])
+RUBY=
+else
+
+# First figure out what the name of Ruby is
+
+if test "x$RUBYBIN" = xyes; then
+	AC_CHECK_PROGS(RUBY, ruby)
+else
+	RUBY="$RUBYBIN"
+fi
+
+AC_MSG_CHECKING(for Ruby header files)
+if test -n "$RUBY"; then
+	RUBYDIR=`($RUBY -rmkmf -e 'print Config::CONFIG[["archdir"]] || $archdir') 2>/dev/null`
+	if test "$RUBYDIR" != ""; then
+		dirs="$RUBYDIR"
+		RUBYINCLUDE=none
+		for i in $dirs; do
+			if test -r $i/ruby.h; then
+				AC_MSG_RESULT($i)
+				RUBYINCLUDE="-I$i"
+				break;
+			fi
+		done
+		if test "$RUBYINCLUDE" = none; then
+			RUBYINCLUDE="-I$RUBYDIR"
+			AC_MSG_RESULT(could not locate ruby.h...using $RUBYINCLUDE)
+		fi
+
+		# Find library and path for linking.
+		AC_MSG_CHECKING(for Ruby library)
+		RUBYLIB=""
+		rb_libdir=`($RUBY -rrbconfig -e 'print Config::CONFIG[["libdir"]]') 2>/dev/null`
+		rb_bindir=`($RUBY -rrbconfig -e 'print Config::CONFIG[["bindir"]]') 2>/dev/null`
+		dirs="$dirs $rb_libdir $rb_bindir"
+
+        rb_libruby=`($RUBY -rrbconfig -e 'print Config::CONFIG[["LIBRUBY_A"]]') 2>/dev/null`
+        RUBYLINK=`($RUBY -rrbconfig -e '
+            c = Config::CONFIG
+            if c.has_key? "LIBRUBYARG_STATIC" # 1.8.x
+                if c[["LIBRUBY"]] == c[["LIBRUBY_A"]]
+                    link = c[["LIBRUBYARG_STATIC"]]
+                else
+                    link = c[["LIBRUBYARG_SHARED"]]
+                end
+            else # 1.6.x
+                link = "-l" + c[["RUBY_INSTALL_NAME"]]
+            end
+            
+            # Get the target Ruby was built for
+            target = c[["target"]]
+           
+            if target == "i386-pc-mswin32"
+              # Need to change msvcrt-ruby*.lib to -lmsvcrt-ruby*
+              ext = File.extname(link)
+              # Get index that counts backwards from end of string
+              index = -1 - ext.size
+              # Strip off the extension
+              link = link.slice(0..index)
+              puts "-l#{link}"
+            else
+              puts link
+            end') 2>/dev/null`
+
+		if test "$rb_libruby" != ""; then
+			for i in $dirs; do
+				if (test -r $i/$rb_libruby;) then
+					RUBYLIB="$i"
+					break;
+				fi
+			done
+		fi
+		if test "$RUBYLIB" = ""; then
+			RUBYLIB="$RUBYDIR"
+			AC_MSG_RESULT(not found... using $RUBYDIR)
+		else
+			AC_MSG_RESULT($RUBYLINK in $RUBYLIB)
+		fi
+	else
+		AC_MSG_RESULT(unable to determine ruby configuration)
+		RUBYINCLUDE="-I$RUBYDIR"
+		RUBYLIB="$RUBYDIR"
+	fi
+
+	case $host in
+		*-*-mingw*) ;; # do nothing, the default windows libraries are already included
+		*) RUBYLINK="$RUBYLINK `($RUBY -rrbconfig -e 'print Config::CONFIG[["LIBS"]]') 2>/dev/null`";;
+	esac
+
+	RUBYCCDLFLAGS=`($RUBY -rrbconfig -e 'print Config::CONFIG[["CCDLFLAGS"]]') 2>/dev/null`
+else
+	AC_MSG_RESULT(could not figure out how to run ruby)
+	RUBYINCLUDE="-I/usr/local/lib/ruby/1.4/arch"
+	RUBYLIB="/usr/local/lib/ruby/1.4/arch"
+	RUBYLINK="-lruby -lm"
+fi
+
+case $host in
+*-*-cygwin* | *-*-mingw*)	RUBYDYNAMICLINKING="-L$RUBYLIB $RUBYLINK";;
+*)		RUBYDYNAMICLINKING="";;
+esac
+fi
+
+AC_SUBST(RUBYINCLUDE)
+AC_SUBST(RUBYLIB)
+AC_SUBST(RUBYLINK)
+AC_SUBST(RUBYCCDLFLAGS)
+AC_SUBST(RUBYDYNAMICLINKING)
+
+#-------------------------------------------------------------------------
+# Look for PHP
+#-------------------------------------------------------------------------
+
+PHP4BIN=
+
+AC_ARG_WITH(php4, AS_HELP_STRING([--without-php4], [Disable PHP])
+AS_HELP_STRING([--with-php4=path], [Set location of PHP executable]),[ PHP4BIN="$withval"], [PHP4BIN=yes])
+
+# First, check for "--without-php4" or "--with-php4=no".
+if test x"${PHP4BIN}" = xno -o x"${with_alllang}" = xno ; then 
+    AC_MSG_NOTICE([Disabling PHP])
+    PHP4=
+else
+
+    if test "x$PHP4BIN" = xyes; then
+      AC_CHECK_PROGS(PHP4, [php5 php])
+    else
+      PHP4=$PHP4BIN
+    fi
+
+    AC_MSG_CHECKING(for PHP header files)
+    dnl /usr/bin/php5 -> /usr/bin/php-config5
+    case $PHP4 in
+      *5)
+	PHP4CONFIG=`echo "$PHP4"|sed 's/5$/-config5/'` ;;
+      *)
+	PHP4CONFIG=$PHP4-config ;;
+    esac
+    php_version=`$PHP4CONFIG --version 2>/dev/null`
+    case $php_version in
+    5*) 
+	PHP4INC=`$PHP4CONFIG --includes 2>/dev/null`
+	if test -n "$PHP4INC"; then
+	  AC_MSG_RESULT($PHP4INC)
+	else
+	  AC_MSG_RESULT(not found)
+	fi
+	;;
+    *)
+	AC_MSG_RESULT([found PHP $version, but only PHP 5 is supported]) ;;
+    esac
+fi
+AC_SUBST(PHP4)
+AC_SUBST(PHP4INC)
+
+#----------------------------------------------------------------
+# Look for ocaml
+#----------------------------------------------------------------
+
+AC_ARG_WITH(ocaml, AS_HELP_STRING([--without-ocaml], [Disable OCaml])
+AS_HELP_STRING([--with-ocaml=path], [Set location of ocaml executable]),[ OCAMLBIN="$withval"], [OCAMLBIN=yes])
+AC_ARG_WITH(ocamlc,[  --with-ocamlc=path      Set location of ocamlc executable],[ OCAMLC="$withval"], [OCAMLC=])
+AC_ARG_WITH(ocamldlgen,[  --with-ocamldlgen=path  Set location of ocamldlgen],[ OCAMLDLGEN="$withval" ], [OCAMLDLGEN=])
+AC_ARG_WITH(ocamlfind,[  --with-ocamlfind=path   Set location of ocamlfind],[OCAMLFIND="$withval"],[OCAMLFIND=])
+AC_ARG_WITH(ocamlmktop,[  --with-ocamlmktop=path  Set location of ocamlmktop executable],[ OCAMLMKTOP="$withval"], [OCAMLMKTOP=])
+
+# First, check for "--without-ocaml" or "--with-ocaml=no".
+if test x"${OCAMLBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling OCaml])
+OCAMLBIN=
+else
+
+AC_MSG_CHECKING(for Ocaml DL load generator)
+if test -z "$OCAMLDLGEN"; then
+AC_CHECK_PROGS(OCAMLDLGEN, ocamldlgen, :)
+else
+OCAMLDLGEN="$OCAMLDLGEN"
+fi
+
+AC_MSG_CHECKING(for Ocaml package tool)
+if test -z "$OCAMLFIND"; then
+AC_CHECK_PROGS(OCAMLFIND, ocamlfind, :)
+else
+OCAMLFIND="$OCAMLFIND"
+fi
+
+AC_MSG_CHECKING(for Ocaml compiler)
+if test -z "$OCAMLC"; then
+AC_CHECK_PROGS(OCAMLC, ocamlc, :)
+else
+OCAMLC="$OCAMLC"
+fi
+
+AC_MSG_CHECKING(for Ocaml interpreter)
+if test "x$OCAMLBIN" = xyes; then
+AC_CHECK_PROGS(OCAMLBIN, ocaml, :)
+else
+OCAMLBIN="$OCAMLBIN"
+fi
+
+AC_MSG_CHECKING(for Ocaml toplevel creator)
+if test -z "$OCAMLMKTOP"; then
+AC_CHECK_PROGS(OCAMLMKTOP, ocamlmktop, :)
+else
+OCAMLMKTOP="$OCAMLMKTOP"
+fi
+
+OCAMLLOC=loc
+if test "$OCAMLC" != ":" ; then
+	AC_MSG_CHECKING(for Ocaml header files)
+	dirs="/usr/lib/ocaml/caml /usr/local/lib/ocaml/caml"
+	dir="`$OCAMLC -where 2>/dev/null`"
+	if test "$dir"; then
+		dirs="$dir/caml $dirs"
+	fi
+	for i in $dirs; do
+		if test -r $i/mlvalues.h; then
+			AC_MSG_RESULT($i)
+			OCAMLEXT="$i"
+			OCAMLINC="-I$OCAMLEXT"
+			break;
+		fi
+	done
+	if test -z "$OCAMLINC"; then
+		AC_MSG_RESULT(not found)
+	fi
+
+	AC_MSG_CHECKING(for Ocaml version 3.08.2 or higher)
+	OCAMLVER=`$OCAMLC -version | sed -e 's/.*version //g'`
+	AC_COMPARE_VERSION([$OCAMLVER],[3.08.2],[:],[:],[OCAMLLOC=_loc])
+	AC_MSG_RESULT($OCAMLVER)
+fi
+fi # Disabling ocaml
+
+export OCAMLLOC
+export OCAMLVER
+export OCAMLINC
+export OCAMLBIN
+export OCAMLC
+export OCAMLDLGEN
+export OCAMLFIND
+export OCAMLMKTOP
+
+AC_SUBST(OCAMLLOC)
+AC_SUBST(OCAMLVER)
+AC_SUBST(OCAMLINC)
+AC_SUBST(OCAMLBIN)
+AC_SUBST(OCAMLC)
+AC_SUBST(OCAMLDLGEN)
+AC_SUBST(OCAMLFIND)
+AC_SUBST(OCAMLMKTOP)
+
+#----------------------------------------------------------------
+# Look for Pike
+#----------------------------------------------------------------
+
+# Identify the name of the Pike executable
+# Priority: configure option, automatic search
+PIKEBIN=
+AC_ARG_WITH(pike, AS_HELP_STRING([--without-pike], [Disable Pike])
+AS_HELP_STRING([--with-pike=path], [Set location of Pike executable]),[PIKEBIN="$withval"], [PIKEBIN=yes])
+
+# First, check for "--without-pike" or "--with-pike=no".
+if test x"${PIKEBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Pike])
+PIKEBIN=
+else
+
+if test "x$PIKEBIN" = xyes; then
+	AC_CHECK_PROGS(PIKE, pike pike7.6 pike7.4 pike7.2)
+else
+	PIKE="$PIKEBIN"
+fi
+
+
+# Check for pike-config
+# Priority: configure option, guessed from $PIKE, search from list
+AC_ARG_WITH(pike-config, AS_HELP_STRING([--with-pike-config=path], 
+  	[Set location of pike-config script]),
+  [PIKECONFIG="$withval"], [PIKECONFIG=""])
+
+if test -z "$PIKECONFIG" -a -n "$PIKE"; then
+	AC_CHECK_PROGS(PIKECONFIG, $PIKE-config pike-config \
+		pike7.6-config pike7.4-config pike7.2-config)
+fi
+
+# Check for a --with-pikeincl option to configure
+# Priority: configure option, info from $PIKECONFIG, guessed by pike script
+AC_ARG_WITH(pikeincl, AS_HELP_STRING([--with-pikeincl=path], 
+	[Set location of Pike include directory]),
+  [PIKEINCLUDE="-I$withval"], [PIKEINCLUDE=])
+
+if test -n "$PIKE"; then
+      AC_MSG_CHECKING([for Pike header files])
+      if test -z "$PIKEINCLUDE" -a -n "$PIKECONFIG"; then
+              PIKEINCLUDE=`$PIKECONFIG --cflags`
+      fi
+      if test -z "$PIKEINCLUDE" -a -n "$PIKE"; then
+              PIKEPATH=`which $PIKE`
+              PIKEINCLUDE=`$PIKE Tools/check-include-path.pike $PIKEPATH`
+              PIKEINCLUDE="-I$PIKEINCLUDE"
+      fi
+
+      if test -z "$PIKEINCLUDE"; then
+              AC_MSG_RESULT(not found)
+      else
+              AC_MSG_RESULT($PIKEINCLUDE)
+      fi
+fi
+fi
+
+AC_SUBST(PIKEINCLUDE)
+AC_SUBST(PIKECCDLFLAGS)		dnl XXX: where is this used/defined?
+AC_SUBST(PIKEDYNAMICLINKING)	dnl XXX: where is this used/defined?
+
+#----------------------------------------------------------------
+# Look for CHICKEN
+#----------------------------------------------------------------
+
+CHICKEN=
+CHICKEN_CONFIG=
+CHICKENHOME=
+CHICKENOPTS=
+CHICKENLIB=
+
+
+AC_ARG_WITH(chicken, AS_HELP_STRING([--without-chicken], [Disable CHICKEN])
+AS_HELP_STRING([--with-chicken=path], [Set location of CHICKEN executable]),[ CHICKENBIN="$withval"], [CHICKENBIN=yes])
+
+# First, check for "--without-chicken" or "--with-chicken=no".
+if test x"${CHICKENBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling CHICKEN])
+else
+
+if test "x$CHICKENBIN" = xyes; then
+AC_CHECK_PROGS(CHICKEN, chicken)
+else
+CHICKEN="$CHICKENBIN"
+fi
+
+AC_ARG_WITH(chickencsc,[  --with-chickencsc=path  Set location of csc executable],[ CHICKEN_CSC="$withval"], [CHICKEN_CSC=])
+
+if test -z "$CHICKEN_CSC"; then
+  AC_CHECK_PROGS(CHICKEN_CSC, csc)
+  # Both the Microsoft C# compiler and chicken have an executable called csc, so check that this csc is really the chicken one
+  if test -n "$CHICKEN_CSC" ; then
+    AC_MSG_CHECKING(whether csc is the chicken compiler)
+    $CHICKEN_CSC -version 2>/dev/null | grep "chicken" > /dev/null || CHICKEN_CSC=""
+    if test -z "$CHICKEN_CSC"; then
+      AC_MSG_RESULT(no)
+    else
+      AC_MSG_RESULT(yes)
+    fi
+  fi
+fi
+
+AC_ARG_WITH(chickencsi,[  --with-chickencsi=path  Set location of csi executable],[ CHICKEN_CSI="$withval"], [CHICKEN_CSI=])
+
+if test -z "$CHICKEN_CSI"; then
+AC_CHECK_PROGS(CHICKEN_CSI, csi)
+fi
+
+if test -n "$CHICKEN_CSC" ; then
+
+  AC_ARG_WITH(chickenopts,[  --with-chickenopts=args Set compiler options for static CHICKEN generated code],[
+	CHICKENOPTS="$withval"], [CHICKENOPTS=])
+  AC_ARG_WITH(chickensharedlib,[  --with-chickensharedlib=args    Set linker options for shared CHICKEN generated code],[
+	CHICKENSHAREDLIB="$withval"], [CHICKENSHAREDLIB=])
+  AC_ARG_WITH(chickenlib,[  --with-chickenlib=args  Set linker options for static CHICKEN generated code],[
+	CHICKENLIB="$withval"], [CHICKENLIB=])
+
+  AC_MSG_CHECKING(for compiler options for static CHICKEN generated code)
+  if test -z "$CHICKENOPTS"; then
+        CHICKENOPTS="`$CHICKEN_CSC -cflags`"
+  else
+        CHICKENOPTS="`$CHICKEN_CSC -cflags` $CHICKENOPTS"
+  fi
+  if test -z "$CHICKENOPTS"; then
+        AC_MSG_RESULT(not found)
+  else
+        AC_MSG_RESULT($CHICKENOPTS)
+  fi
+
+  AC_MSG_CHECKING(for linker options for shared CHICKEN generated code)
+  if test -z "$CHICKENSHAREDLIB"; then
+        CHICKENSHAREDLIB="`$CHICKEN_CSC -shared -libs`"
+  else
+        CHICKENSHAREDLIB="`$CHICKEN_CSC -shared -libs` $CHICKENSHAREDLIB"
+  fi
+  if test -z "$CHICKENSHAREDLIB"; then
+  	AC_MSG_RESULT(not found)
+  else
+        AC_MSG_RESULT($CHICKENSHAREDLIB)
+  fi
+
+  AC_MSG_CHECKING(for linker options for static CHICKEN generated code)
+  if test -z "$CHICKENLIB"; then
+        CHICKENLIB="`$CHICKEN_CSC -libs`"
+  else
+        CHICKENLIB="`$CHICKEN_CSC -libs` $CHICKENLIB"
+  fi
+  if test -z "$CHICKENLIB"; then
+  	AC_MSG_RESULT(not found)
+  else
+        AC_MSG_RESULT($CHICKENLIB)
+  fi
+
+fi # have CHICKEN_CONFIG
+fi # Check for --without-chicken
+
+AC_SUBST(CHICKEN)
+AC_SUBST(CHICKEN_CSC)
+AC_SUBST(CHICKEN_CSI)
+AC_SUBST(CHICKENOPTS)
+AC_SUBST(CHICKENLIB)
+AC_SUBST(CHICKENSHAREDLIB)
+
+#----------------------------------------------------------------
+# Look for C#
+#----------------------------------------------------------------
+
+AC_ARG_WITH(csharp, AS_HELP_STRING([--without-csharp], [Disable CSharp]), [with_csharp="$withval"], [with_csharp=yes])
+AC_ARG_WITH(cil-interpreter, [  --with-cil-interpreter=path     Set location of CIL interpreter for CSharp],[CSHARPBIN="$withval"], [CSHARPBIN=])
+AC_ARG_WITH(csharp-compiler, [  --with-csharp-compiler=path     Set location of CSharp compiler],[CSHARPCOMPILERBIN="$withval"], [CSHARPCOMPILERBIN=])
+
+# First, check for "--without-csharp" or "--with-csharp=no".
+if test x"${with_csharp}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling CSharp])
+CSHARPCOMPILER=
+else
+
+if test -z "$CSHARPCOMPILERBIN" ; then
+  case $host in
+  *-*-cygwin* | *-*-mingw*)
+    # prefer Mono gmcs (.NET 2.0) over mcs (.NET 1.1) - note mcs-1.2.3 has major pinvoke bug
+    AC_CHECK_PROGS(CSHARPCOMPILER, csc gmcs mcs cscc)
+    if test -n "$CSHARPCOMPILER" && test "$CSHARPCOMPILER" = "csc" ; then
+      AC_MSG_CHECKING(whether csc is the Microsoft CSharp compiler)
+      csc 2>/dev/null | grep "C#" > /dev/null || CSHARPCOMPILER=""
+      if test -z "$CSHARPCOMPILER" ; then
+        AC_MSG_RESULT(no)
+        AC_CHECK_PROGS(CSHARPCOMPILER, gmcs mcs cscc)
+      else
+        AC_MSG_RESULT(yes)
+      fi
+    fi
+    ;;
+  *)AC_CHECK_PROGS(CSHARPCOMPILER, gmcs mcs cscc);;
+  esac
+else
+  CSHARPCOMPILER="$CSHARPCOMPILERBIN"
+fi
+
+CSHARPPATHSEPARATOR="/"
+CSHARPCYGPATH_W=echo
+if test -z "$CSHARPBIN" ; then
+  CSHARPCILINTERPRETER=""
+  if test "cscc" = "$CSHARPCOMPILER" ; then
+    AC_CHECK_PROGS(CSHARPCILINTERPRETER, ilrun)
+  else
+    if test "mcs" = "$CSHARPCOMPILER"; then
+      # Check that mcs is the C# compiler and not the Unix mcs utility by examining the output of 'mcs --version'
+      # The Mono compiler should emit: Mono C# compiler version a.b.c.d
+      csharp_version_raw=`(mcs --version) 2>/dev/null`
+      csharp_version_searched=`(mcs --version | sed -e "/C#/b" -e "/Mono/b" -e d) 2>/dev/null` # return string if contains 'Mono' or 'C#'
+      CSHARPCOMPILER="";
+      if test -n "$csharp_version_raw" ; then
+        if test "$csharp_version_raw" = "$csharp_version_searched" ; then
+          CSHARPCOMPILER="mcs"
+        fi
+      fi
+      if test "mcs" != "$CSHARPCOMPILER" ; then
+        echo "mcs is not a working Mono C# compiler"
+      fi
+    fi
+    if test "mcs" = "$CSHARPCOMPILER" || test "gmcs" = "$CSHARPCOMPILER"; then
+        AC_CHECK_PROGS(CSHARPCILINTERPRETER, mono) # Mono JIT
+    else 
+      if test "csc" = "$CSHARPCOMPILER"; then
+          CSHARPPATHSEPARATOR="\\\\"
+          CSHARPCYGPATH_W='cygpath -w'
+      fi
+    fi
+  fi
+else
+  CSHARPCILINTERPRETER="$CSHARPBIN"
+fi
+
+# Cygwin requires the Windows standard (Pascal) calling convention as it is a Windows executable and not a Cygwin built executable
+case $host in
+*-*-cygwin* | *-*-mingw*)
+    if test "$GCC" = yes; then
+        CSHARPDYNAMICLINKING=" -mno-cygwin -mthreads -Wl,--add-stdcall-alias"
+        CSHARPCFLAGS="-mno-cygwin -mthreads"
+    else
+        CSHARPDYNAMICLINKING=""
+        CSHARPCFLAGS=""
+    fi ;;
+*)
+        CSHARPDYNAMICLINKING=""
+        CSHARPCFLAGS=""
+        ;;
+esac
+
+# CSharp on Windows platforms including Cygwin doesn't use libname.dll, rather name.dll when loading dlls
+case $host in
+*-*-cygwin* | *-*-mingw*) CSHARPLIBRARYPREFIX="";;
+*)CSHARPLIBRARYPREFIX="lib";;
+esac
+
+# C#/Mono on Mac OS X tweaks
+case $host in
+*-*-darwin*)
+    CSHARPSO=".so"
+    ;;
+*)
+    CSHARPSO=$SO
+    ;;
+esac
+fi
+
+AC_SUBST(CSHARPCILINTERPRETER)
+AC_SUBST(CSHARPPATHSEPARATOR)
+AC_SUBST(CSHARPCYGPATH_W)
+AC_SUBST(CSHARPCOMPILER)
+AC_SUBST(CSHARPDYNAMICLINKING)
+AC_SUBST(CSHARPLIBRARYPREFIX) # Is this going to be used?
+AC_SUBST(CSHARPCFLAGS)
+AC_SUBST(CSHARPSO)
+
+#----------------------------------------------------------------
+# Look for Lua
+#----------------------------------------------------------------
+
+LUABIN=
+LUAINCLUDE=
+LUALIB=
+LUADYNAMICLOADLIB=
+LUAFLAGS=
+LUALINK=
+# note: if LUABIN is empty then lua tests will not be done
+# LUABIN will be cleared if certain dependencies cannot be found
+
+AC_ARG_WITH(lua, AS_HELP_STRING([--without-lua], [Disable Lua])
+AS_HELP_STRING([--with-lua=path], [Set location of Lua executable]),[ LUABIN="$withval"], [LUABIN=yes])
+AC_ARG_WITH(luaincl,[  --with-luaincl=path     Set location of Lua include directory],[
+	LUAINCLUDE="$withval"], [LUAINCLUDE=])
+AC_ARG_WITH(lualib,[  --with-lualib=path      Set location of Lua library directory],[
+	LUALIB="$withval"], [LUALIB=])
+
+# First, check for "--without-lua" or "--with-lua=no".
+if test x"${LUABIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Lua])
+else
+
+# can we find lua?
+if test "x$LUABIN" = xyes; then
+   AC_PATH_PROG(LUABIN, lua)
+fi
+
+# check version: we need Lua 5.x
+if test "$LUABIN"; then
+   AC_MSG_CHECKING(Lua version)
+   # if version 5.x
+   LUAV5=`$LUABIN -e 'if string.sub(_VERSION,5,5)=="5" then print "1" end'`
+   # if not version 5.0
+   LUAV51=`$LUABIN -e 'if string.sub(_VERSION,5,7)~="5.0" then print "1" end'`
+
+   if test -z "$LUAV5"; then
+     AC_MSG_WARN(Not Lua 5.x, SWIG does not support this version of Lua)
+     LUABIN=""
+   elif test -z "$LUAV51"; then
+     AC_MSG_RESULT(Lua 5.0.x)
+   else
+     AC_MSG_RESULT(Lua 5.1 or later)
+   fi
+fi
+
+if test "$LUABIN"; then
+   AC_MSG_CHECKING(whether Lua dynamic loading is enabled)
+   # using Lua to check Lua
+   # lua 5.0 & 5.1 have different fn names
+   if test -z "$LUAV51"; then
+     LUADYNAMICLOADLIB=`$LUABIN -e '_,_,c=loadlib("no_such_lib","") if c~="absent" then print "1" end'`
+   else
+     LUADYNAMICLOADLIB=`$LUABIN -e '_,_,c=package.loadlib("no_such_lib","") if c~="absent" then print "1" end'`
+   fi
+   
+   if test -z "$LUADYNAMICLOADLIB"; then 
+     AC_MSG_RESULT(no)
+   else
+     AC_MSG_RESULT(yes)
+   fi
+fi
+
+# look for the header files & set LUAFLAGS accordingly
+# will clear LUABIN if not present
+if test -n "$LUAINCLUDE"; then
+  AC_CHECK_FILE($LUAINCLUDE/lua.h,[LUAFLAGS="$ISYSTEM$LUAINCLUDE"],[LUABIN=])
+else
+  LUA_OK="1"
+  AC_CHECK_HEADER(lua.h,[LUAFLAGS=""],[LUA_OK=""])
+  # if we didn't get it, going to have to look elsewhere (the hard way)
+  if test -z "$LUA_OK"; then
+    AC_MSG_CHECKING(for lua.h in other locations)
+    # note: ubuntu seems to like /usr/include/lua5.1/lua.h
+    dirs="/usr/include/lua* /usr/local/include"
+    for i in $dirs; do
+      #echo "$i"
+      if test -r $i/lua.h; then
+        AC_MSG_RESULT($i/lua.h)
+	LUAFLAGS="$ISYSTEM$i"
+	break;
+      fi
+    done
+    if test -z "$LUAFLAGS"; then
+      AC_MSG_RESULT(not found)
+      LUABIN="" # clear the bin
+    fi
+  fi
+fi
+
+# look for the library files & set LUALINK accordingly
+# will clear LUABIN if not present
+lua_save_LIBS=$LIBS # the code seems to disrupt LIBS, so saving
+	
+if test -n "$LUALIB"; then
+  AC_CHECK_FILE($LUALIB/liblua.a,[LUALINK="-L$LUALIB -llua"],[LUABIN=])
+else
+  AC_SEARCH_LIBS(lua_close, [lua lua51 lua5.1 lua50 lua5.0], [LUALINK="-l$ac_lib"],[LUABIN=])
+fi
+
+# adding lualib for lua 5.0
+if test -z "$LUAV51"; then # extra for lua 5.0
+  LUALINK="$LUALINK -llualib"
+fi
+
+LIBS=$lua_save_LIBS	# restore LIBS
+
+fi # if not disabled
+
+AC_SUBST(LUADYNAMICLINKING)
+AC_SUBST(LUAFLAGS)
+AC_SUBST(LUALINK)
+AC_SUBST(LUABIN)
+
+#----------------------------------------------------------------
+# Look for Allegro Common Lisp
+#----------------------------------------------------------------
+
+ALLEGROCLBIN=
+
+AC_ARG_WITH(allegrocl, AS_HELP_STRING([--without-allegrocl], [Disable Allegro CL])
+AS_HELP_STRING([--with-allegrocl=path], [Set location of Allegro CL executable (alisp)]),[ ALLEGROCLBIN="$withval"], [ALLEGROCLBIN=yes])
+
+# First, check for "--without-allegrocl" or "--with-allegrocl=no".
+if test x"${ALLEGROCLBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling Allegro CL])
+ALLEGROCLBIN=
+else
+
+# can we find allegrocl?
+if test "x$ALLEGROCLBIN" = xyes; then
+   AC_PATH_PROG(ALLEGROCLBIN, alisp)
+fi
+fi
+
+AC_SUBST(ALLEGROCLBIN)
+
+#----------------------------------------------------------------
+# Look for GNU CLISP
+#----------------------------------------------------------------
+
+CLISPBIN=
+
+AC_ARG_WITH(clisp, AS_HELP_STRING([--without-clisp], [Disable CLISP])
+AS_HELP_STRING([--with-clisp=path], [Set location of CLISP executable (clisp)]),[ CLISPBIN="$withval"], [CLISPBIN=yes])
+
+# First, check for "--without-clisp" or "--with-clisp=no".
+if test x"${CLISPBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling CLISP])
+CLISPBIN=
+else
+
+# can we find clisp?
+if test "x$CLISPBIN" = xyes; then
+   AC_PATH_PROG(CLISPBIN, clisp)
+fi
+fi
+
+AC_SUBST(CLISPBIN)
+
+#----------------------------------------------------------------
+# Look for GNU R
+#----------------------------------------------------------------
+
+RBIN=
+
+AC_ARG_WITH(r, AS_HELP_STRING([--without-r], [Disable R])
+AS_HELP_STRING([--with-r=path], [Set location of R executable (r)]),[ RBIN="$withval"], [RBIN=yes])
+
+# First, check for "--without-r" or "--with-r=no".
+if test x"${RBIN}" = xno -o x"${with_alllang}" = xno ; then 
+AC_MSG_NOTICE([Disabling R])
+RBIN=
+else
+
+# can we find R?
+if test "x$RBIN" = xyes; then
+   AC_PATH_PROG(RBIN, R)
+fi
+fi
+
+AC_SUBST(RBIN)
+
+#----------------------------------------------------------------
+# Determine which languages to use for examples/test-suite
+#----------------------------------------------------------------
+
+SKIP_TCL=
+if test -z "$TCLINCLUDE" || test -z "$TCLLIB" ; then
+    SKIP_TCL="1"
+fi
+AC_SUBST(SKIP_TCL)
+
+
+SKIP_PERL5=
+if test -z "$PERL" || test -z "$PERL5EXT" ; then
+    SKIP_PERL5="1"
+fi
+AC_SUBST(SKIP_PERL5)
+
+
+SKIP_OCTAVE=
+if test -z "$OCTAVE" || test -z "$OCTAVEEXT" ; then
+    SKIP_OCTAVE="1"
+fi
+AC_SUBST(SKIP_OCTAVE)
+
+
+SKIP_PYTHON=
+if test -z "$PYINCLUDE" || test -z "$PYLIB" ; then
+    SKIP_PYTHON="1"
+fi
+AC_SUBST(SKIP_PYTHON)
+
+
+SKIP_JAVA=
+if test -z "$JAVA" || test -z "$JAVAC" || test -z "$JAVAINC" ; then
+    SKIP_JAVA="1"
+fi
+AC_SUBST(SKIP_JAVA)
+
+
+SKIP_GUILE=
+if test -z "$GUILEINCLUDE" || test -z "$GUILELIB" || test -z "$GUILE_GH_INTERFACE"; then
+    SKIP_GUILE="1"
+fi
+AC_SUBST(SKIP_GUILE)
+
+SKIP_GUILESCM=
+if test -z "$GUILEINCLUDE" || test -z "$GUILELIB" || test -z "$GUILE_SCM_INTERFACE"; then
+    SKIP_GUILESCM="1"
+fi
+AC_SUBST(SKIP_GUILESCM)
+
+
+SKIP_MZSCHEME=
+if test -z "$MZC" ; then
+    SKIP_MZSCHEME="1"
+fi
+AC_SUBST(SKIP_MZSCHEME)
+
+
+SKIP_RUBY=
+if test -z "$RUBY" || test -z "$RUBYINCLUDE" || test -z "$RUBYLIB" ; then
+    SKIP_RUBY="1"
+fi
+AC_SUBST(SKIP_RUBY)
+
+
+SKIP_PHP4=
+if test -z "$PHP4" || test -z "$PHP4INC" ; then
+    SKIP_PHP4="1"
+fi
+AC_SUBST(SKIP_PHP4)
+
+
+SKIP_OCAML=
+if test -z "$OCAMLBIN" || test -z "$OCAMLINC" ; then
+    SKIP_OCAML="1"
+fi
+AC_SUBST(SKIP_OCAML)
+
+
+SKIP_PIKE="1" # Always skipped!
+if test -z "$PIKE" || test -z "$PIKEINCLUDE" ; then
+    SKIP_PIKE="1"
+fi
+AC_SUBST(SKIP_PIKE)
+
+
+SKIP_CHICKEN=
+if test -z "$CHICKEN_CSC" || test -z "$CHICKEN"; then
+    SKIP_CHICKEN="1"
+fi
+AC_SUBST(SKIP_CHICKEN)
+
+
+SKIP_CSHARP=
+if test -z "$CSHARPCOMPILER" ; then
+    SKIP_CSHARP="1"
+else
+    if test "cscc" = "$CSHARPCOMPILER" && test -z "$CSHARPCILINTERPRETER" ; then
+      SKIP_CSHARP="1"
+    fi
+fi
+AC_SUBST(SKIP_CSHARP)
+
+SKIP_MODULA3="1" # Always skipped!
+AC_SUBST(SKIP_MODULA3)
+
+SKIP_LUA=
+# we need LUABIN & dynamic loading
+if test -z "$LUABIN" || test -z "$LUADYNAMICLOADLIB"; then
+    SKIP_LUA="1"
+fi
+AC_SUBST(SKIP_LUA)
+
+SKIP_ALLEGROCL=
+if test -z "$ALLEGROCLBIN" ; then
+    SKIP_ALLEGROCL="1"
+fi
+AC_SUBST(SKIP_ALLEGROCL)
+
+SKIP_CLISP=
+if test -z "$CLISPBIN" ; then
+    SKIP_CLISP="1"
+fi
+AC_SUBST(SKIP_CLISP)
+
+SKIP_R=
+if test -z "$RBIN" ; then
+    SKIP_R="1"
+fi
+AC_SUBST(SKIP_R)
+
+SKIP_CFFI=
+#if test -z "$CFFIBIN" ; then
+    SKIP_CFFI="1"
+#fi
+AC_SUBST(SKIP_CFFI)
+
+SKIP_UFFI=
+#if test -z "$UFFIBIN" ; then
+    SKIP_UFFI="1"
+#fi
+AC_SUBST(SKIP_UFFI)
+
+#----------------------------------------------------------------
+# Additional language dependencies
+#----------------------------------------------------------------
+SKIP_GCJ=
+if test -z "$GCJ" || test -z "$GCJH" ; then
+  SKIP_GCJ="1"
+else
+  if test "$GCC" != yes; then
+    SKIP_GCJ="1"
+  fi
+fi
+AC_SUBST(SKIP_GCJ)
+
+
+#----------------------------------------------------------------
+# Miscellaneous
+#----------------------------------------------------------------
+
+# Root directory
+# Translate path for native Windows compilers for use with 'make check'
+ROOT_DIR=`pwd`
+case $host in
+*-*-cygwin* | *-*-mingw*)
+  if (cygpath --mixed $ROOT_DIR) >/dev/null 2>/dev/null; then
+    ROOT_DIR=`cygpath --mixed $ROOT_DIR`
+  fi
+  # Extra files generated by some Windows compilers
+  EXTRA_CLEAN="*.stackdump *.exp *.lib *.pdb *.ilk"
+  ;;
+esac
+
+AC_SUBST(ROOT_DIR)
+AC_SUBST(EXTRA_CLEAN)
+AC_SUBST(ac_aux_dir)
+
+# Configure SWIG_LIB path
+
+AC_ARG_WITH(swiglibdir,[  --with-swiglibdir=DIR   Put SWIG system-independent libraries into DIR.],
+  [swig_lib="$withval"], [swig_lib="${datadir}/swig/${PACKAGE_VERSION}"])
+AC_SUBST(swig_lib)
+AC_DEFINE_DIR(SWIG_LIB, swig_lib, [Directory for SWIG system-independent libraries])
+
+case $host in
+        # Windows does not understand unix directories. Convert into a windows directory with drive letter.
+        *-*-mingw*) SWIG_LIB_WIN_UNIX=`cmd //c echo $SWIG_LIB | sed -e "s/[ ]*$//"`;; # This echo converts unix to mixed paths. Then zap unexpected trailing space.
+        *-*-cygwin*) SWIG_LIB_WIN_UNIX=`cygpath --mixed "$SWIG_LIB"`;;
+        *) SWIG_LIB_WIN_UNIX="";;
+esac
+AC_DEFINE_UNQUOTED(SWIG_LIB_WIN_UNIX, ["$SWIG_LIB_WIN_UNIX"], [Directory for SWIG system-independent libraries (Unix install on native Windows)])
+
+
+AC_CONFIG_FILES([			        \
+    Makefile				        \
+    swig.spec				        \
+    Source/Makefile			        \
+    Examples/Makefile			        \
+    Examples/guile/Makefile		        \
+    Examples/xml/Makefile		        \
+    Examples/GIFPlot/Makefile		        \
+    Examples/GIFPlot/Lib/Makefile	        \
+    Examples/test-suite/chicken/Makefile	\
+    Examples/test-suite/csharp/Makefile	        \
+    Examples/test-suite/guile/Makefile	        \
+    Examples/test-suite/guilescm/Makefile	\
+    Examples/test-suite/java/Makefile	        \
+    Examples/test-suite/mzscheme/Makefile	\
+    Examples/test-suite/ocaml/Makefile	        \
+    Examples/test-suite/octave/Makefile	        \
+    Examples/test-suite/perl5/Makefile	        \
+    Examples/test-suite/php4/Makefile	        \
+    Examples/test-suite/pike/Makefile	        \
+    Examples/test-suite/python/Makefile	        \
+    Examples/test-suite/ruby/Makefile	        \
+    Examples/test-suite/tcl/Makefile	        \
+    Examples/test-suite/lua/Makefile	        \
+    Examples/test-suite/allegrocl/Makefile	\
+    Examples/test-suite/clisp/Makefile		\
+    Examples/test-suite/cffi/Makefile		\
+    Examples/test-suite/uffi/Makefile		\
+    Examples/test-suite/r/Makefile		\
+    Lib/ocaml/swigp4.ml
+])
+AC_CONFIG_FILES([preinst-swig], [chmod +x preinst-swig])
+AC_OUTPUT
+
+
+dnl configure.in ends here
diff --git a/trunk/debian/README b/trunk/debian/README
new file mode 100644
index 0000000..9cbe96a
--- /dev/null
+++ b/trunk/debian/README
@@ -0,0 +1,20 @@
+The Debian Package swig1.3
+--------------------------
+
+This is SWIG 1.3 (Simplified Wrapper and Interface Generator)
+packaged for Debian GNU/Linux.
+
+SWIG 1.3 is not fully compatible with SWIG 1.1. It is a re-development
+effort of SWIG 1.1 (which was written in C++) in ANSI C.  The 1.3
+series is in "alpha" state.  Release 1.3a5 was rather stable, and it
+should be used for new projects rather than the ancient release
+1.1p5.  See the file `NEW' for information on the new features of the
+1.3 series.
+
+This Debian package derives from the release 1.3a5 and corresponds to
+the "mkoeppe-1-3-a5-patches" branch of the SWIG CVS repository.  It
+fixes several bugs and enhances several language backends.  See the
+top of the file `CHANGES' for details.
+
+
+Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>, Mon, 28 May 2001 15:08:55 +0200
diff --git a/trunk/debian/changelog b/trunk/debian/changelog
new file mode 100644
index 0000000..da43b40
--- /dev/null
+++ b/trunk/debian/changelog
@@ -0,0 +1,66 @@
+swig1.3 (1.3.pnet) unstable; urgency=low
+
+  * Support for dotgnu pnet under debian
+  
+ -- James Michael DuPont <mdupont777@yahoo.com>  Wed,  12 Mar 2003 20:55:53 +0200
+  
+swig1.3 (1.3.a5+patches-9) unstable; urgency=low
+
+  * New upstream version
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Wed,  6 Jun 2001 16:11:41 +0200
+
+swig1.3 (1.3.a5+patches-8) unstable; urgency=low
+
+  * New upstream version
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Wed,  6 Jun 2001 14:06:51 +0200
+
+swig1.3 (1.3.a5+patches-7) unstable; urgency=low
+
+  * New upstream version
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Wed,  6 Jun 2001 13:34:44 +0200
+
+swig1.3 (1.3.a5+patches-6) unstable; urgency=low
+
+  * New upstream version
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Tue,  5 Jun 2001 14:11:52 +0200
+
+swig1.3 (1.3.a5+patches-5) unstable; urgency=low
+
+  * New upstream version.
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Fri,  1 Jun 2001 18:48:59 +0200
+
+swig1.3 (1.3.a5+patches-4) unstable; urgency=low
+
+  * Fix hard-coded location of swig library.  Added build-dependency on
+    tcl-dev. 
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Fri,  1 Jun 2001 13:32:34 +0200
+
+swig1.3 (1.3.a5+patches-3) unstable; urgency=low
+
+  * New upstream version
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Thu, 31 May 2001 13:15:20 +0200
+
+swig1.3 (1.3.a5+patches-2) unstable; urgency=low
+
+  * Binary and manpage now include version number, to improve
+    cooperation with the "swig" package.
+
+ -- Matthias Koeppe <mkoeppe@rotehorn.math.uni-magdeburg.de>  Tue, 29 May 2001 15:15:07 +0200
+
+swig1.3 (1.3.a5+patches-1) unstable; urgency=low
+
+  * First release.
+
+ -- Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>  Sat, 20 Nov 1999 01:09:11 +0100
+
+Local variables:
+mode: debian-changelog
+add-log-mailing-address: "mkoeppe@mail.math.uni-magdeburg.de"
+End:
\ No newline at end of file
diff --git a/trunk/debian/control b/trunk/debian/control
new file mode 100644
index 0000000..80e0a70
--- /dev/null
+++ b/trunk/debian/control
@@ -0,0 +1,18 @@
+Source: swig1.3
+Section: interpreters
+Priority: optional
+Maintainer: Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>
+Build-Depends: debhelper (>> 3.0.0), libguile-dev, python-dev, perl,
+ ruby-dev, ruby, tcl8.0-dev
+Standards-Version: 3.5.2
+
+Package: swig1.3
+Architecture: any
+Depends: ${shlibs:Depends}
+Description: Generate scripting interfaces to C/C++ code
+ SWIG (Simplified Wrapper and Interface Generator) is a system for
+ automatically generating wrapper/glue code for several languages
+ (Tcl, Python, Perl, Ruby, MzScheme, Guile, Java) from annotated C or
+ C++ header files.
+ This package represents some point in the SWIG 1.3 development
+ series. It is not fully compatible with the SWIG 1.1 release.
diff --git a/trunk/debian/copyright b/trunk/debian/copyright
new file mode 100644
index 0000000..8cb8692
--- /dev/null
+++ b/trunk/debian/copyright
@@ -0,0 +1,83 @@
+This is SWIG, written and maintained by:
+
+ Dave Beazley (beazley@cs.uchicago.edu)                 (SWIG core)
+ Loic Dachary (loic@ceic.com)                           (Perl5)
+ Harco de Hilster (Harco.de.Hilster@ATComputing.nl)     (Java)
+ Thien-Thi Nguyen (ttn@glug.org)                        (Testing/Misc)
+ Masaki Fukushima (fukusima@goto.info.waseda.ac.jp)     (Ruby)
+ Matthias Koeppe (mkoeppe@mail.math.uni-magdeburg.de)   (Guile/MzScheme)
+
+Past contributors:
+
+ Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran Kovuk, Gary Holt,
+ David Fletcher, Oleg Tolmatcev.
+
+SWIG can be obtained by anonymous CVS:
+
+     cvs -d :pserver:cvs@swig.cs.uchicago.edu:/cvsroot co SWIG
+
+SWIG is distributed under the following terms:
+
+I.
+
+Copyright (C) 1998-2000
+The University of Chicago
+
+Permission is hereby granted, without written agreement and without
+license or royalty fees, to use, copy, modify, and distribute this
+software and its documentation for any purpose, provided that 
+(1) The above copyright notice and the following two paragraphs
+appear in all copies of the source code and (2) redistributions
+including binaries reproduces these notices in the supporting
+documentation.   Substantial modifications to this software may be
+copyrighted by their authors and need not follow the licensing terms
+described here, provided that the new terms are clearly indicated in
+all files where they apply.
+
+IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CHICAGO, OR
+DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT,
+INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF
+THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE AUTHORS OR
+ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+THE AUTHOR AND THE UNIVERSITY OF CHICAGO SPECIFICALLY DISCLAIM ANY
+WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
+PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE AUTHORS AND
+DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
+UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+
+II.
+
+Copyright (c) 1995-1998
+The University of Utah and the Regents of the University of California
+All Rights Reserved
+
+Permission is hereby granted, without written agreement and without
+license or royalty fees, to use, copy, modify, and distribute this
+software and its documentation for any purpose, provided that 
+(1) The above copyright notice and the following two paragraphs
+appear in all copies of the source code and (2) redistributions
+including binaries reproduces these notices in the supporting
+documentation.   Substantial modifications to this software may be
+copyrighted by their authors and need not follow the licensing terms
+described here, provided that the new terms are clearly indicated in
+all files where they apply.
+
+IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE 
+UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
+PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
+EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGE.
+
+THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH
+SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO, 
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND 
+THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE,
+SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+
diff --git a/trunk/debian/dirs b/trunk/debian/dirs
new file mode 100644
index 0000000..587d584
--- /dev/null
+++ b/trunk/debian/dirs
@@ -0,0 +1,4 @@
+usr/bin
+usr/lib
+#usr/share/swig1.3-pnet
+#usr/share/doc/swig1.3-pnet
diff --git a/trunk/debian/docs b/trunk/debian/docs
new file mode 100644
index 0000000..9e310ea
--- /dev/null
+++ b/trunk/debian/docs
@@ -0,0 +1,47 @@
+README
+TODO
+ANNOUNCE
+CHANGES
+NEW
+Doc/Devel/engineering.html
+Doc/Devel/index.html
+Doc/Devel/internals.html
+Doc/Devel/migrate.txt
+Doc/README
+Doc/Manual/About.html
+Doc/Manual/Advanced.html
+Doc/Manual/Arguments.html
+Doc/Manual/Chicken.html
+Doc/Manual/Contents.html
+Doc/Manual/Copyright.html
+Doc/Manual/Customization.html
+Doc/Manual/Documentation.html
+Doc/Manual/Extending.html
+Doc/Manual/Guile.html
+Doc/Manual/Introduction.html
+Doc/Manual/Java.html
+Doc/Manual/Library.html
+Doc/Manual/Ocaml.html
+Doc/Manual/Perl5.html
+Doc/Manual/Php.html
+Doc/Manual/Preface.html
+Doc/Manual/Preprocessor.html
+Doc/Manual/Python.html
+Doc/Manual/README
+Doc/Manual/Ruby.html
+Doc/Manual/SWIG.html
+Doc/Manual/SWIGPlus.html
+Doc/Manual/Scripting.html
+Doc/Manual/Tcl.html
+Doc/Manual/Typemaps.html
+Doc/Manual/Varargs.html
+Doc/Manual/Warnings.html
+Doc/Manual/Windows.html
+Doc/Manual/ch11.1.png
+Doc/Manual/ch11.2.png
+Doc/Manual/ch11.3.png
+Doc/Manual/ch12.1.png
+Doc/Manual/ch2.1.png
+Doc/Manual/ch9.table.2.png
+Doc/Manual/chapters
+Doc/Manual/index.html
diff --git a/trunk/debian/postinst b/trunk/debian/postinst
new file mode 100644
index 0000000..164b5ff
--- /dev/null
+++ b/trunk/debian/postinst
@@ -0,0 +1,45 @@
+#! /bin/sh
+# postinst script for swig1.3
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <postinst> `configure' <most-recently-configured-version>
+#        * <old-postinst> `abort-upgrade' <new version>
+#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
+#          <new-version>
+#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
+#          <failed-install-package> <version> `removing'
+#          <conflicting-package> <version>
+# for details, see /usr/share/doc/packaging-manual/
+#
+# quoting from the policy:
+#     Any necessary prompting should almost always be confined to the
+#     post-installation script, and should be protected with a conditional
+#     so that unnecessary prompting doesn't happen if a package's
+#     installation fails and the `postinst' is called with `abort-upgrade',
+#     `abort-remove' or `abort-deconfigure'.
+
+case "$1" in
+    configure)
+
+    ;;
+
+    abort-upgrade|abort-remove|abort-deconfigure)
+
+    ;;
+
+    *)
+        echo "postinst called with unknown argument \`$1'" >&2
+        exit 0
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
diff --git a/trunk/debian/rules b/trunk/debian/rules
new file mode 100755
index 0000000..1fafed9
--- /dev/null
+++ b/trunk/debian/rules
@@ -0,0 +1,76 @@
+#!/usr/bin/make -f
+# Sample debian/rules that uses debhelper.
+# GNU copyright 1997 to 1999 by Joey Hess.
+
+# Uncomment this to turn on verbose mode.
+export DH_VERBOSE=1
+
+# This is the debhelper compatability version to use.
+export DH_COMPAT=3
+
+configure: configure-stamp
+configure-stamp:
+	dh_testdir
+	./autogen-debian.sh
+	./configure --prefix=/usr --mandir=/usr/share/man --with-swiglibdir=/usr/share/swig1.3 --program-suffix=-1.3
+	touch configure-stamp
+
+build: configure-stamp build-stamp
+build-stamp:
+	dh_testdir
+	$(MAKE) 
+	$(MAKE) runtime
+	touch build-stamp
+
+clean:
+	dh_testdir
+	dh_testroot
+	rm -f build-stamp configure-stamp
+
+	-$(MAKE) clean
+
+	dh_clean
+
+install: build
+	dh_testdir
+	dh_testroot
+	dh_clean -k
+	dh_installdirs
+	$(MAKE) install DESTDIR=$(CURDIR)/debian/swig1.3
+
+# Build architecture-independent files here.
+binary-indep: build install
+# We have nothing to do by default.
+
+# Build architecture-dependent files here.
+binary-arch: build install
+	dh_testdir
+	dh_testroot
+#	dh_installdebconf	
+	dh_installdocs
+	dh_installexamples
+	dh_installmenu
+#	dh_installlogrotate
+#	dh_installemacsen
+#	dh_installpam
+#	dh_installmime
+#	dh_installinit
+#	dh_installcron
+	dh_installman
+	dh_installinfo
+	dh_undocumented swig-1.3.1
+#	dh_installchangelogs CHANGES
+	dh_link
+	dh_strip
+	dh_compress
+	dh_fixperms
+	dh_makeshlibs
+	dh_installdeb
+#	dh_perl
+	dh_shlibdeps
+	dh_gencontrol
+	dh_md5sums
+	dh_builddeb
+
+binary: binary-indep binary-arch
+.PHONY: build clean binary-indep binary-arch binary install configure
diff --git a/trunk/debian/substvars b/trunk/debian/substvars
new file mode 100644
index 0000000..c9df68b
--- /dev/null
+++ b/trunk/debian/substvars
@@ -0,0 +1 @@
+shlibs:Depends=libc6 (>= 2.2.3-1), libstdc++2.10-glibc2.2
diff --git a/trunk/preinst-swig.in b/trunk/preinst-swig.in
new file mode 100755
index 0000000..0f49e2e
--- /dev/null
+++ b/trunk/preinst-swig.in
@@ -0,0 +1,7 @@
+#!/bin/sh
+builddir=`dirname $0`
+srcdir=`cd "$builddir" && cd '@srcdir@' && pwd`
+SWIG_LIB=$srcdir/Lib
+#SWIG_LIB=`cygpath -w $srcdir/Lib` # For native Windows version of SWIG
+export SWIG_LIB
+exec "$builddir/swig" $*
diff --git a/trunk/swig.spec.in b/trunk/swig.spec.in
new file mode 100644
index 0000000..14d95d2
--- /dev/null
+++ b/trunk/swig.spec.in
@@ -0,0 +1,70 @@
+# You can build the package from SVN using something like:
+# tar -czf swig-@PACKAGE_VERSION@.tar.gz swig-@PACKAGE_VERSION@ && rpmbuild -tb swig-@PACKAGE_VERSION@.tar.gz
+# @configure_input@
+
+%define ver          @PACKAGE_VERSION@
+%define rel          1
+%define prefix       /usr
+%define home_page    http://www.swig.org
+%define docprefix    %{prefix}/share
+
+######################################################################
+# Usually, nothing needs to be changed below here between releases
+######################################################################
+Summary: Simplified Wrapper and Interface Generator
+Name: swig
+Version: %{ver}
+Release: %{rel}
+URL: %{home_page}
+Source0: %{name}-%{version}.tar.gz
+License: BSD
+Group: Development/Tools
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+SWIG is a software development tool that connects programs written in C and C++
+with a variety of high-level programming languages. SWIG is primarily used with
+common scripting languages such as Perl, Python, Tcl/Tk, and Ruby, however the
+list of supported languages also includes non-scripting languages such as Java,
+OCAML and C#. Also several interpreted and compiled Scheme implementations
+(Guile, MzScheme, Chicken) are supported. SWIG is most commonly used to create
+high-level interpreted or compiled programming environments, user interfaces,
+and as a tool for testing and prototyping C/C++ software. SWIG can also export
+its parse tree in the form of XML and Lisp s-expressions. 
+
+%prep
+%setup -q -n %{name}-%{version}
+
+%build
+# so we can build package from SVN source too
+[ ! -r configure ] && ./autogen.sh
+%configure
+make
+
+%install
+rm -rf ${RPM_BUILD_ROOT}
+make DESTDIR=$RPM_BUILD_ROOT install
+
+%clean
+rm -rf ${RPM_BUILD_ROOT}
+
+%files
+%defattr(-,root,root)
+%doc ANNOUNCE CHANGES FUTURE INSTALL LICENSE NEW README TODO
+%doc Doc/*
+%{_bindir}/*
+%{prefix}/share/*
+
+%changelog
+* Thu Sep 16 2004 Marcelo Matus <mmatus@acms.arizona.edu>
+- Small fixes needed after removing the runtime package
+* Tue Jul 20 2004 William Fulton <wsf@fultondesigns.co.uk>
+- Update for SWIG-1.3.22 - Removed runtime package
+* Wed Mar 03 2004 Robert H De Vries
+- Update to work with Fedora Core 1 rpm 4.2.1
+* Wed Jul 24 2002 Sam Liddicott <sam@liddicott.com>
+- Added runtime package of runtime libs
+* Mon Sep 10 2001 Tony Seward <anthony.seward@ieee.org>
+- Merge Red Hat's and Dustin Mitchell's .spec files.
+- Install all of the examples in the documentation directory.
+- Auto create the list of installed files.
diff --git a/trunk/vms/aaareadme.txt b/trunk/vms/aaareadme.txt
new file mode 100644
index 0000000..52746a7
--- /dev/null
+++ b/trunk/vms/aaareadme.txt
@@ -0,0 +1,18 @@
+Port on OpenVMS 7.3 using CC 6.5 and CXX 6.5
+
+
+Building procedure:
+$ @logicals
+$ @build_all
+
+the logicals swig_root is defined by the procedure logicals.com.
+The logicals.com procedure can be invoke with an optional argument
+for the define command, for example:
+$ @logicals "/system/exec"
+
+
+genbuild.py is the python program use to generate all the procedures in the
+[vms.scripts] directory.
+
+
+jf.pieronne@laposte.net
diff --git a/trunk/vms/build_end.com b/trunk/vms/build_end.com
new file mode 100644
index 0000000..1033022
--- /dev/null
+++ b/trunk/vms/build_end.com
@@ -0,0 +1,21 @@
+$ set def swig_root:[vms]
+$
+$ file = f$search("swig_root:[vms.o_alpha]*.obj")
+$ newobj = 0 
+$ if file .nes. ""
+$ then
+$    v = f$verify(1)
+$    library/replace swig_root:[vms.o_alpha]swig.olb swig_root:[vms.o_alpha]*.obj
+$    delete swig_root:[vms.o_alpha]*.obj;*
+$    v = f$verify(v)
+$    newobj = 1
+$ endif
+$ file = f$search("swig_root:[vms]swig.exe")
+$ if file .eqs. "" .or. newobj
+$ then
+$    v = f$verify(1)
+$    cxxlink/exe=swig_root:[vms]swig.exe -
+	/repo=swig_root:[source.modules1_1.cxx_repository] -
+        swig_root:[vms.o_alpha]swig.olb/include=swigmain
+$    v = f$verify(v)
+$ endif
diff --git a/trunk/vms/build_init.com b/trunk/vms/build_init.com
new file mode 100644
index 0000000..9a1992d
--- /dev/null
+++ b/trunk/vms/build_init.com
@@ -0,0 +1,13 @@
+$ set def swig_root:[vms]
+$
+$ swiglib = "swig_root:[vms.o_alpha]swig.olb
+$
+$ if (f$search("swig_root:[vms]o_alpha.dir") .eqs. "") then $ -
+	create/dir swig_root:[vms.o_alpha]
+$
+$ copy swigconfig.h [-.source.include]
+$ copy swigver.h [-.source.include]
+$
+$ if (f$search("''swiglib'") .eqs. "") then $ -
+          library/create/object 'swiglib'
+$
diff --git a/trunk/vms/build_swig.com b/trunk/vms/build_swig.com
new file mode 100644
index 0000000..5570db0
--- /dev/null
+++ b/trunk/vms/build_swig.com
@@ -0,0 +1 @@
+$ @swig_root:[vms.scripts]build_all
diff --git a/trunk/vms/genbuild.py b/trunk/vms/genbuild.py
new file mode 100644
index 0000000..df18ce3
--- /dev/null
+++ b/trunk/vms/genbuild.py
@@ -0,0 +1,155 @@
+import os.path, string, posix, pyvms
+#
+#
+
+IDIR = ['swig_root:[source.swig]', 'swig_root:[source.doh.include]',
+        'swig_root:[source.include]', 'swig_root:[source.preprocessor]'] 
+
+def new_file(fg, dirname):
+    global IDIR
+    fn = 'swig_root:[vms.scripts]compil_' + os.path.basename(dirname) + '.com'
+    print >> fg, '$ @' + fn
+    f = open(fn, 'w')
+    print >> f, '$!'
+    print >> f, '$! Generated by genbuild.py'
+    print >> f, '$!'
+    print >> f, '$ libname = "swig_root:[vms.o_alpha]swig.olb"'
+    print >> f, '$'
+    print >> f, '$ set default', pyvms.crtl_to_vms(dirname)[0][0]
+    print >> f, '$'
+    print >> f, "$ idir := ", IDIR[0]
+    for i in range(1, len(IDIR)):
+        print >> f, '$ idir = idir + ",' + IDIR[i] + '"'
+    print >> f, '$'
+    print >> f, "$ iflags = \"/include=(''idir', sys$disk:[])\""
+    print >> f, '$ oflags = \"/object=swig_root:[vms.o_alpha]'
+    print >> f, "$ cflags = \"''oflags'''iflags'''dflags'\""
+    print >> f, "$ cxxflags = \"''oflags'''iflags'''dflags'\""
+    print >> f, '$'
+    return f
+
+
+def end_file(f):
+    print >>f,"""$ exit
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 = Source file
+$! P4 - P8  What it depends on
+$
+$ modname = f$parse(p3,,,"name")
+$ set noon
+$ set message/nofacility/noident/noseverity/notext
+$ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname'
+$ set message/facility/ident/severity/text
+$ on error then exit
+$ open/read swigtmp swig_root:[vms]swiglib.tmp
+$! skip header
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$!
+$
+$ read/end=module_not_found swigtmp r
+$ modfound = 1
+$ Time = f$cvtime(f$extract(49, 20, r))
+$ goto end_search_module
+$ module_not_found:
+$ modfound = 0
+$
+$ end_search_module:
+$ close swigtmp
+$ delete swig_root:[vms]swiglib.tmp;*
+$
+$ if modfound .eq. 0 then $ goto Makeit
+$
+$! Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(1)
+$ 'P2' 'P3'
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE"""
+
+
+def listRep(args, dirname, filenames):
+    fg = args[0]
+    first = 1
+    for fn in filenames:
+        if fn[-2:] == '.c':
+            if first:
+                first = 0
+                fc = new_file(fg, dirname)
+
+            cstr = "\"cc ''cflags'\" "
+            line = "$ call make swig_root:[vms.o_alpha]"
+            line += fn[:-1] + 'obj -'
+            print >> fc, line
+            line = "\t" + cstr + fn
+            print >> fc, line
+        elif fn[-4:] == '.cxx':
+            if first:
+                first = 0
+                fc = new_file(fg, dirname)
+
+            cstr = "\"cxx ''cxxflags'\" "
+            line = "$ call make swig_root:[vms.o_alpha]"
+            line += fn[:-3] + 'obj -'
+            print >> fc, line
+            line = "\t" + cstr + fn
+            print >> fc, line
+    if first == 0:
+        end_file(fc)
+        fc.close()
+#
+def genbuild(f, dir):
+    os.path.walk(dir, listRep, (f,))
+    cmd = 'set default swig_root:[vms]'
+#
+f = open('swig_root:[vms.scripts]build_all.com','w')
+print >> f, '$!'
+print >> f, '$! Generated by genbuild.py'
+print >> f, '$!'
+print >> f, '$ set default swig_root:[vms]'
+print >> f, '$'
+print >> f, '$ @swig_root:[vms]build_init'
+#
+genbuild(f, '/swig_root/source')
+print >> f, '$'
+print >> f, '$ set default swig_root:[vms]'
+print >> f, '$'
+print >> f, '$ @swig_root:[vms]build_end'
+f.close
diff --git a/trunk/vms/logicals.com b/trunk/vms/logicals.com
new file mode 100644
index 0000000..20da9d4
--- /dev/null
+++ b/trunk/vms/logicals.com
@@ -0,0 +1,18 @@
+$!
+$!
+$!
+$ proc = f$environment("PROCEDURE")
+$ proc = f$parse(proc,"sys$disk:[]",,,"NO_CONCEAL")
+$ cur_dev = f$parse(proc,,,"DEVICE","SYNTAX_ONLY")
+$ cur_dir = f$parse(proc,,,"DIRECTORY","SYNTAX_ONLY")
+$ cur_dir = f$extract(1,f$length(cur_dir)-2,cur_dir)
+$ cur_dir = cur_dir - "["
+$ cur_dir = cur_dir - "]"
+$ cur_dir = cur_dir - "<"
+$ cur_dir = cur_dir - ">"
+$
+$! remove trealing .VMS
+$ root_dir = f$extract(0,f$length(cur_dir)-4,cur_dir)
+$
+$ define 'p1' /trans=concealed swig_root 'cur_dev'['root_dir'.]
+
diff --git a/trunk/vms/scripts/build_all.com b/trunk/vms/scripts/build_all.com
new file mode 100644
index 0000000..d411983
--- /dev/null
+++ b/trunk/vms/scripts/build_all.com
@@ -0,0 +1,15 @@
+$!
+$! Generated by genbuild.py
+$!
+$ set default swig_root:[vms]
+$
+$ @swig_root:[vms]build_init
+$ @swig_root:[vms.scripts]compil_cparse.com
+$ @swig_root:[vms.scripts]compil_doh.com
+$ @swig_root:[vms.scripts]compil_modules1_1.com
+$ @swig_root:[vms.scripts]compil_preprocessor.com
+$ @swig_root:[vms.scripts]compil_swig.com
+$
+$ set default swig_root:[vms]
+$
+$ @swig_root:[vms]build_end
diff --git a/trunk/vms/scripts/compil_cparse.com b/trunk/vms/scripts/compil_cparse.com
new file mode 100644
index 0000000..4f78f41
--- /dev/null
+++ b/trunk/vms/scripts/compil_cparse.com
@@ -0,0 +1,98 @@
+$!
+$! Generated by genbuild.py
+$!
+$ libname = "swig_root:[vms.o_alpha]swig.olb"
+$
+$ set default SWIG_ROOT:[SOURCE.CPARSE]
+$
+$ idir :=  swig_root:[source.swig]
+$ idir = idir + ",swig_root:[source.doh.include]"
+$ idir = idir + ",swig_root:[source.include]"
+$ idir = idir + ",swig_root:[source.preprocessor]"
+$
+$ iflags = "/include=(''idir', sys$disk:[])"
+$ oflags = "/object=swig_root:[vms.o_alpha]
+$ cflags = "''oflags'''iflags'''dflags'"
+$ cxxflags = "''oflags'''iflags'''dflags'"
+$
+$ call make swig_root:[vms.o_alpha]cscanner.obj -
+	"cc ''cflags'" cscanner.c
+$ call make swig_root:[vms.o_alpha]parser.obj -
+	"cc ''cflags'" parser.c
+$ call make swig_root:[vms.o_alpha]templ.obj -
+	"cc ''cflags'" templ.c
+$ call make swig_root:[vms.o_alpha]util.obj -
+	"cc ''cflags'" util.c
+$ exit
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 = Source file
+$! P4 - P8  What it depends on
+$
+$ modname = f$parse(p3,,,"name")
+$ set noon
+$ set message/nofacility/noident/noseverity/notext
+$ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname'
+$ set message/facility/ident/severity/text
+$ on error then exit
+$ open/read swigtmp swig_root:[vms]swiglib.tmp
+$! skip header
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$!
+$
+$ read/end=module_not_found swigtmp r
+$ modfound = 1
+$ Time = f$cvtime(f$extract(49, 20, r))
+$ goto end_search_module
+$ module_not_found:
+$ modfound = 0
+$
+$ end_search_module:
+$ close swigtmp
+$ delete swig_root:[vms]swiglib.tmp;*
+$
+$ if modfound .eq. 0 then $ goto Makeit
+$
+$! Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(1)
+$ 'P2' 'P3'
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE
diff --git a/trunk/vms/scripts/compil_doh.com b/trunk/vms/scripts/compil_doh.com
new file mode 100644
index 0000000..6d4ae89
--- /dev/null
+++ b/trunk/vms/scripts/compil_doh.com
@@ -0,0 +1,106 @@
+$!
+$! Generated by genbuild.py
+$!
+$ libname = "swig_root:[vms.o_alpha]swig.olb"
+$
+$ set default SWIG_ROOT:[SOURCE.DOH.DOH]
+$
+$ idir :=  swig_root:[source.swig]
+$ idir = idir + ",swig_root:[source.doh.include]"
+$ idir = idir + ",swig_root:[source.include]"
+$ idir = idir + ",swig_root:[source.preprocessor]"
+$
+$ iflags = "/include=(''idir', sys$disk:[])"
+$ oflags = "/object=swig_root:[vms.o_alpha]
+$ cflags = "''oflags'''iflags'''dflags'"
+$ cxxflags = "''oflags'''iflags'''dflags'"
+$
+$ call make swig_root:[vms.o_alpha]base.obj -
+	"cc ''cflags'" base.c
+$ call make swig_root:[vms.o_alpha]file.obj -
+	"cc ''cflags'" file.c
+$ call make swig_root:[vms.o_alpha]fio.obj -
+	"cc ''cflags'" fio.c
+$ call make swig_root:[vms.o_alpha]hash.obj -
+	"cc ''cflags'" hash.c
+$ call make swig_root:[vms.o_alpha]list.obj -
+	"cc ''cflags'" list.c
+$ call make swig_root:[vms.o_alpha]memory.obj -
+	"cc ''cflags'" memory.c
+$ call make swig_root:[vms.o_alpha]string.obj -
+	"cc ''cflags'" string.c
+$ call make swig_root:[vms.o_alpha]void.obj -
+	"cc ''cflags'" void.c
+$ exit
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 = Source file
+$! P4 - P8  What it depends on
+$
+$ modname = f$parse(p3,,,"name")
+$ set noon
+$ set message/nofacility/noident/noseverity/notext
+$ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname'
+$ set message/facility/ident/severity/text
+$ on error then exit
+$ open/read swigtmp swig_root:[vms]swiglib.tmp
+$! skip header
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$!
+$
+$ read/end=module_not_found swigtmp r
+$ modfound = 1
+$ Time = f$cvtime(f$extract(49, 20, r))
+$ goto end_search_module
+$ module_not_found:
+$ modfound = 0
+$
+$ end_search_module:
+$ close swigtmp
+$ delete swig_root:[vms]swiglib.tmp;*
+$
+$ if modfound .eq. 0 then $ goto Makeit
+$
+$! Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(1)
+$ 'P2' 'P3'
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE
diff --git a/trunk/vms/scripts/compil_modules1_1.com b/trunk/vms/scripts/compil_modules1_1.com
new file mode 100644
index 0000000..c570dfe
--- /dev/null
+++ b/trunk/vms/scripts/compil_modules1_1.com
@@ -0,0 +1,132 @@
+$!
+$! Generated by genbuild.py
+$!
+$ libname = "swig_root:[vms.o_alpha]swig.olb"
+$
+$ set default SWIG_ROOT:[SOURCE.MODULES1_1]
+$
+$ idir :=  swig_root:[source.swig]
+$ idir = idir + ",swig_root:[source.doh.include]"
+$ idir = idir + ",swig_root:[source.include]"
+$ idir = idir + ",swig_root:[source.preprocessor]"
+$
+$ iflags = "/include=(''idir', sys$disk:[])"
+$ oflags = "/object=swig_root:[vms.o_alpha]
+$ cflags = "''oflags'''iflags'''dflags'"
+$ cxxflags = "''oflags'''iflags'''dflags'"
+$
+$ call make swig_root:[vms.o_alpha]allocate.obj -
+	"cxx ''cxxflags'" allocate.cxx
+$ call make swig_root:[vms.o_alpha]browser.obj -
+	"cxx ''cxxflags'" browser.cxx
+$ call make swig_root:[vms.o_alpha]contract.obj -
+	"cxx ''cxxflags'" contract.cxx
+$ call make swig_root:[vms.o_alpha]emit.obj -
+	"cxx ''cxxflags'" emit.cxx
+$ call make swig_root:[vms.o_alpha]guile.obj -
+	"cxx ''cxxflags'" guile.cxx
+$ call make swig_root:[vms.o_alpha]java.obj -
+	"cxx ''cxxflags'" java.cxx
+$ call make swig_root:[vms.o_alpha]lang.obj -
+	"cxx ''cxxflags'" lang.cxx
+$ call make swig_root:[vms.o_alpha]main.obj -
+	"cxx ''cxxflags'" main.cxx
+$ call make swig_root:[vms.o_alpha]module.obj -
+	"cxx ''cxxflags'" module.cxx
+$ call make swig_root:[vms.o_alpha]mzscheme.obj -
+	"cxx ''cxxflags'" mzscheme.cxx
+$ call make swig_root:[vms.o_alpha]ocaml.obj -
+	"cxx ''cxxflags'" ocaml.cxx
+$ call make swig_root:[vms.o_alpha]overload.obj -
+	"cxx ''cxxflags'" overload.cxx
+$ call make swig_root:[vms.o_alpha]perl5.obj -
+	"cxx ''cxxflags'" perl5.cxx
+$ call make swig_root:[vms.o_alpha]php4.obj -
+	"cxx ''cxxflags'" php4.cxx
+$ call make swig_root:[vms.o_alpha]pike.obj -
+	"cxx ''cxxflags'" pike.cxx
+$ call make swig_root:[vms.o_alpha]python.obj -
+	"cxx ''cxxflags'" python.cxx
+$ call make swig_root:[vms.o_alpha]ruby.obj -
+	"cxx ''cxxflags'" ruby.cxx
+$ call make swig_root:[vms.o_alpha]swigmain.obj -
+	"cxx ''cxxflags'" swigmain.cxx
+$ call make swig_root:[vms.o_alpha]tcl8.obj -
+	"cxx ''cxxflags'" tcl8.cxx
+$ call make swig_root:[vms.o_alpha]typepass.obj -
+	"cxx ''cxxflags'" typepass.cxx
+$ call make swig_root:[vms.o_alpha]xml.obj -
+	"cxx ''cxxflags'" xml.cxx
+$ exit
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 = Source file
+$! P4 - P8  What it depends on
+$
+$ modname = f$parse(p3,,,"name")
+$ set noon
+$ set message/nofacility/noident/noseverity/notext
+$ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname'
+$ set message/facility/ident/severity/text
+$ on error then exit
+$ open/read swigtmp swig_root:[vms]swiglib.tmp
+$! skip header
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$!
+$
+$ read/end=module_not_found swigtmp r
+$ modfound = 1
+$ Time = f$cvtime(f$extract(49, 20, r))
+$ goto end_search_module
+$ module_not_found:
+$ modfound = 0
+$
+$ end_search_module:
+$ close swigtmp
+$ delete swig_root:[vms]swiglib.tmp;*
+$
+$ if modfound .eq. 0 then $ goto Makeit
+$
+$! Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(1)
+$ 'P2' 'P3'
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE
diff --git a/trunk/vms/scripts/compil_preprocessor.com b/trunk/vms/scripts/compil_preprocessor.com
new file mode 100644
index 0000000..f95961e
--- /dev/null
+++ b/trunk/vms/scripts/compil_preprocessor.com
@@ -0,0 +1,94 @@
+$!
+$! Generated by genbuild.py
+$!
+$ libname = "swig_root:[vms.o_alpha]swig.olb"
+$
+$ set default SWIG_ROOT:[SOURCE.PREPROCESSOR]
+$
+$ idir :=  swig_root:[source.swig]
+$ idir = idir + ",swig_root:[source.doh.include]"
+$ idir = idir + ",swig_root:[source.include]"
+$ idir = idir + ",swig_root:[source.preprocessor]"
+$
+$ iflags = "/include=(''idir', sys$disk:[])"
+$ oflags = "/object=swig_root:[vms.o_alpha]
+$ cflags = "''oflags'''iflags'''dflags'"
+$ cxxflags = "''oflags'''iflags'''dflags'"
+$
+$ call make swig_root:[vms.o_alpha]cpp.obj -
+	"cc ''cflags'" cpp.c
+$ call make swig_root:[vms.o_alpha]expr.obj -
+	"cc ''cflags'" expr.c
+$ exit
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 = Source file
+$! P4 - P8  What it depends on
+$
+$ modname = f$parse(p3,,,"name")
+$ set noon
+$ set message/nofacility/noident/noseverity/notext
+$ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname'
+$ set message/facility/ident/severity/text
+$ on error then exit
+$ open/read swigtmp swig_root:[vms]swiglib.tmp
+$! skip header
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$!
+$
+$ read/end=module_not_found swigtmp r
+$ modfound = 1
+$ Time = f$cvtime(f$extract(49, 20, r))
+$ goto end_search_module
+$ module_not_found:
+$ modfound = 0
+$
+$ end_search_module:
+$ close swigtmp
+$ delete swig_root:[vms]swiglib.tmp;*
+$
+$ if modfound .eq. 0 then $ goto Makeit
+$
+$! Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(1)
+$ 'P2' 'P3'
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE
diff --git a/trunk/vms/scripts/compil_swig.com b/trunk/vms/scripts/compil_swig.com
new file mode 100644
index 0000000..103e275
--- /dev/null
+++ b/trunk/vms/scripts/compil_swig.com
@@ -0,0 +1,122 @@
+$!
+$! Generated by genbuild.py
+$!
+$ libname = "swig_root:[vms.o_alpha]swig.olb"
+$
+$ set default SWIG_ROOT:[SOURCE.SWIG]
+$
+$ idir :=  swig_root:[source.swig]
+$ idir = idir + ",swig_root:[source.doh.include]"
+$ idir = idir + ",swig_root:[source.include]"
+$ idir = idir + ",swig_root:[source.preprocessor]"
+$
+$ iflags = "/include=(''idir', sys$disk:[])"
+$ oflags = "/object=swig_root:[vms.o_alpha]
+$ cflags = "''oflags'''iflags'''dflags'"
+$ cxxflags = "''oflags'''iflags'''dflags'"
+$
+$ call make swig_root:[vms.o_alpha]cwrap.obj -
+	"cc ''cflags'" cwrap.c
+$ call make swig_root:[vms.o_alpha]error.obj -
+	"cc ''cflags'" error.c
+$ call make swig_root:[vms.o_alpha]fragment.obj -
+	"cc ''cflags'" fragment.c
+$ call make swig_root:[vms.o_alpha]getopt.obj -
+	"cc ''cflags'" getopt.c
+$ call make swig_root:[vms.o_alpha]include.obj -
+	"cc ''cflags'" include.c
+$ call make swig_root:[vms.o_alpha]misc.obj -
+	"cc ''cflags'" misc.c
+$ call make swig_root:[vms.o_alpha]naming.obj -
+	"cc ''cflags'" naming.c
+$ call make swig_root:[vms.o_alpha]parms.obj -
+	"cc ''cflags'" parms.c
+$ call make swig_root:[vms.o_alpha]scanner.obj -
+	"cc ''cflags'" scanner.c
+$ call make swig_root:[vms.o_alpha]stype.obj -
+	"cc ''cflags'" stype.c
+$ call make swig_root:[vms.o_alpha]symbol.obj -
+	"cc ''cflags'" symbol.c
+$ call make swig_root:[vms.o_alpha]tree.obj -
+	"cc ''cflags'" tree.c
+$ call make swig_root:[vms.o_alpha]typemap.obj -
+	"cc ''cflags'" typemap.c
+$ call make swig_root:[vms.o_alpha]typesys.obj -
+	"cc ''cflags'" typesys.c
+$ call make swig_root:[vms.o_alpha]warn.obj -
+	"cc ''cflags'" warn.c
+$ call make swig_root:[vms.o_alpha]wrapfunc.obj -
+	"cc ''cflags'" wrapfunc.c
+$ exit
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 = Source file
+$! P4 - P8  What it depends on
+$
+$ modname = f$parse(p3,,,"name")
+$ set noon
+$ set message/nofacility/noident/noseverity/notext
+$ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname'
+$ set message/facility/ident/severity/text
+$ on error then exit
+$ open/read swigtmp swig_root:[vms]swiglib.tmp
+$! skip header
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$ read swigtmp r
+$!
+$
+$ read/end=module_not_found swigtmp r
+$ modfound = 1
+$ Time = f$cvtime(f$extract(49, 20, r))
+$ goto end_search_module
+$ module_not_found:
+$ modfound = 0
+$
+$ end_search_module:
+$ close swigtmp
+$ delete swig_root:[vms]swiglib.tmp;*
+$
+$ if modfound .eq. 0 then $ goto Makeit
+$
+$! Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(1)
+$ 'P2' 'P3'
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE
diff --git a/trunk/vms/swigconfig.h b/trunk/vms/swigconfig.h
new file mode 100644
index 0000000..3ee0864
--- /dev/null
+++ b/trunk/vms/swigconfig.h
@@ -0,0 +1,2 @@
+
+/* Note that this file has changed. TODO Get the latest from the original version. */